# Node.js

Canonical URL: https://developers.iagenify.com/ar/sdk/runtimes/node/
Language: ar

جميع الإمكانات متاحة: جلسة محفوظة مؤقتًا على القرص، ومساحة عمل فعلية، وصَدَفات أوامر تبقى بعد اكتمال الإجابة، ووكيل يعمل على الجهاز الذي يشغّله.

Status: node ≥ 18 · منظومة الملفات · صدفة الأوامر

## مكان حفظ الجلسة {#session}

تُحفظ في `~/.iagenify/session` داخل مجلد يُنشأ بالأذونات `0700`. وتبقى بعد إعادة التشغيل، لذا تستبدل العملية طويلة التشغيل المفتاح بجلسة مرة واحدة دون تكرار ذلك.

```javascript
// One account per machine: nothing to configure
const api = new IaGenify({ apiKey: process.env.IAGENIFY_API_KEY });

// Several accounts on one machine: give each its own file
const api = new IaGenify({
  apiKey: process.env.IAGENIFY_API_KEY,
  sessionPath: "/var/lib/myapp/sessions/tenant-a",
});
```

> **ملف مستقل لكل حساب**
>
> إذا استخدم عميلان بمفتاحين مختلفين قيمة sessionPath نفسها، فسيكتب كل منهما فوق بيانات الآخر. خصّص مسارًا مستقلًا لكل عميل.

## مساحة العمل {#workspace}

يسجّل جهاز Node نفسه كوحدة تخزين عند أول تبادل للمفتاح. تبقى ملفاته في `~/.iagenify/files`؛ فوحدة تخزين الحاسوب لا تحفظ أي محتوى على الخادم، ويُرفض أي رفع موجّه إليها بالخطأ `storage_is_local`.

```javascript
const pc = await api.storage.get();   // this computer

await pc.files.write("Launch plan/brief.md", "# Brief\n");
await pc.files.mkdir("Archive");

await pc.files.list();                // the root
await pc.files.list("Launch plan");
await pc.files.list("", { recursive: true });
// [{ name, path, type: "file" | "folder", size, mimeType, modifiedAt }]

const { content } = await pc.files.read("Launch plan/brief.md");

await pc.files.move("Launch plan/brief.md", "Archive/brief.md");
await pc.files.remove("Archive");
```

### الاحتفاظ بالبيانات افتراضيًا

| الإجراء | ما يُحتفظ به |
| --- | --- |
| استبدال محتوى ملف | النسخة السابقة داخل .versions |
| إزالة ملف أو مجلد | العنصر داخل .trash |
| النقل إلى مسار موجود | لا يُستبدل أي شيء؛ تُرفض عملية النقل |

يوفر هذان المجلدان حماية لعمل الوكيل، وهما مجلدان عاديان يمكنك قراءتهما أو استعادة الملفات منهما أو إفراغهما بنفسك.

## الطرفيات {#terminals}

تتوفر الطرفيات في هذه البيئة فقط. الطرفية صدفة أوامر فعلية تستمر بعد الإجابة التي أنشأتها، مثل خادم تطوير أو أداة مراقبة أو عملية بناء. وتعمل داخل عملية Node التي تشغّل حزمة SDK، لذا تنتهي عند إعادة تشغيل تلك العملية.

```javascript
// An open shell you send lines to
const shell = await pc.terminals.create({ name: "dev", cwd: "site" });
await shell.run("npm install");
await shell.run("npm run dev");

// Or a command that is the terminal, started immediately
const server = await pc.terminals.create({ name: "api", command: "node server.js" });

await pc.terminals.list();            // every open terminal
await pc.terminals.get(shell.id);
await pc.terminals.remove(shell.id);
```

### قراءة المخرجات

تعتمد `output()` على مؤشر موضع وليست تدفقًا. اطلب المخرجات بدءًا من موضع معين لتحصل على النص الذي جاء بعده، مع الموضع التالي.

```javascript
let cursor = 0;

for (;;) {
  const out = await shell.output({ since: cursor });
  if (out.text) process.stdout.write(out.text);
  cursor = out.cursor;
  if (out.truncated) console.warn("fell behind — older output was dropped");
  if (out.status !== "running") { console.log("exit", out.exitCode); break; }
  await new Promise((r) => setTimeout(r, 400));
}
```

| الحقل | المعنى |
| --- | --- |
| text | النص المطبوع بعد الموضع since |
| cursor | موضع مطلق؛ مرّره في الطلب التالي |
| status | running أو finished |
| exitCode | تُضبط قيمته بعد انتهاء العملية |
| truncated | الموضع since الذي أرسلته أقدم من المخرجات التي ما زالت محفوظة |

### إيقاف العمليات

```javascript
shell.busy;              // true while a command is running
shell.cwd;               // follows every cd

await shell.interrupt(); // Ctrl+C: stops the command, keeps the shell
await shell.kill();      // ends the shell and every process it started
```

> **تختلف interrupt() عن kill()**
>
> توقف interrupt() الأمر الجاري وتُبقي صدفة الأوامر متاحة للاستخدام. أما kill() فتنهي شجرة العمليات كاملةً، وهو ما يناسب خادم تطوير انتهيت من استخدامه.

## وكيل يعمل على هذا الجهاز {#agent}

لا تحتاج إلى توفير شيء إضافي: القرص وصدفة الأوامر متاحان بالفعل، ولذلك تتوفر مجموعة الأدوات كاملةً.

```javascript
const agent = api.agents.create({
  runtime: "local",
  machine: pc,
  model: "gemini-3.5-flash",
  mode: "ask",
  budget: 200,
  onPermission: async ({ tool, args, category }) => {
    if (category === "exec") return "deny";     // no commands in this process
    return "once";
  },
});

await agent.run({
  message: "Read Launch plan/brief.md and list what is missing.",
  onEvent: (e) => console.log(e.type, e.tool ?? ""),
});
```

## التشغيل على خادم دون مستخدم للموافقة {#headless}

تُستدعى `onPermission` دون وجود مستخدم يجيب. نفّذ داخلها سياسة لاتخاذ القرار بدلًا من تركها دون إعداد.

```javascript
const ALLOWED = new Set(["read", "list", "glob", "grep", "write", "edit"]);

api.agents.create({
  runtime: "local",
  machine: pc,
  model: "gemini-3.5-flash",
  mode: "auto",
  budget: 500,
  onPermission: async ({ tool }) => (ALLOWED.has(tool) ? "always" : "deny"),
});
```

```python
import os

# One account per machine: nothing to configure
api = IaGenify(api_key=os.environ["IAGENIFY_API_KEY"])

# Several accounts on one machine: give each its own file
api = IaGenify(
    api_key=os.environ["IAGENIFY_API_KEY"],
    session_path="/var/lib/myapp/sessions/tenant-a",
)
```

```python
pc = api.storage.get()   # this computer

pc.files.write("Launch plan/brief.md", "# Brief\n")
pc.files.mkdir("Archive")

pc.files.list()                # the root
pc.files.list("Launch plan")
pc.files.list("", recursive=True)
# [{"name", "path", "type": "file" | "folder", "size"}]

content = pc.files.read("Launch plan/brief.md")["content"]

pc.files.move("Launch plan/brief.md", "Archive/brief.md")
pc.files.remove("Archive")
```

```python
# An open shell you send lines to
shell = pc.terminals.create(name="dev", cwd="site")
shell.run("npm install")
shell.run("npm run dev")

# Or a command that is the terminal, started immediately
server = pc.terminals.create(name="api", command="node server.js")

pc.terminals.list()            # every open terminal
pc.terminals.get(shell.id)
pc.terminals.remove(shell.id)
```

```python
import sys, time

cursor = 0

while True:
    out = shell.output(since=cursor)
    if out["text"]:
        sys.stdout.write(out["text"])
    cursor = out["cursor"]
    if out["status"] != "running":
        print("exit", out["exitCode"])
        break
    time.sleep(0.4)
```

```python
shell.busy     # True while the shell process is alive
shell.cwd      # the folder it was started in

shell.interrupt()  # Ctrl+C: stops the command, keeps the shell
shell.kill()       # ends the shell and every process it started
```

```python
def on_permission(request):
    if request["category"] == "exec":
        return "deny"     # no commands in this process
    return "once"

agent = api.agents.create(
    runtime="local",
    machine=pc,
    model="gemini-3.5-flash",
    mode="ask",
    budget=200,
    on_permission=on_permission,
)

agent.run(
    message="Read Launch plan/brief.md and list what is missing.",
    on_event=lambda e: print(e["type"], e.get("tool", "")),
)
```

```python
ALLOWED = {"read", "list", "glob", "grep", "write", "edit"}

api.agents.create(
    runtime="local",
    machine=pc,
    model="gemini-3.5-flash",
    mode="auto",
    budget=500,
    on_permission=lambda request: "always" if request["tool"] in ALLOWED else "deny",
)
```
