# Node.js

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

Die volle Oberfläche: eine Sitzung, die auf der Festplatte gecachet wird, ein echter Workspace, Shells, die eine Antwort überstehen, und ein Agent, der auf der Maschine arbeitet, auf der es läuft.

Status: node ≥ 18 · Dateisystem · Shell

## Wo die Sitzung wohnt {#session}

In `~/.iagenify/session`, innerhalb eines Verzeichnisses, das mit dem Modus `0700` erstellt wurde. Es überlebt Neustarts, so dass ein langlebiger Prozess den Schlüssel immer wieder austauscht.

```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",
});
```

> **Eine Datei, ein Konto**
>
> Zwei Clients mit verschiedenen Schlüsseln, die eine Session teilenPath überschreiben sich gegenseitig. Geben Sie jedem seinen eigenen Pfad.

## Der Arbeitsbereich {#workspace}

Ein Node-Rechner registriert sich als Speicher auf dem ersten Schlüsselaustausch. Seine Dateien leben in `~/.iagenify/files` und bleiben dort: ein Computerspeicher hält keine Bytes auf dem Server, und ein Upload auf einen gerichtet wird mit `storage_is_local` abgelehnt.

```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");
```

### Nichts ist standardmäßig verloren

| Aktion | Was bleibt |
| --- | --- |
| Überschreiben einer Datei | die vorherige Version, unter .versions |
| Entfernen einer Datei oder eines Ordners | die Position unter .trash |
| Auf einen vorhandenen Pfad gehen | nichts wird überschrieben — der Umzug wird abgelehnt |

Diese beiden Ordner sind das Sicherheitsnetz des Agenten, und es sind gewöhnliche Ordner: Sie können sie lesen, von ihnen wiederherstellen oder sie selbst leeren.

## Terminals {#terminals}

Nur hier. Ein Terminal ist eine echte Shell, die die Antwort, die sie gestartet hat, überdauert – ein dev-Server, ein Watcher, ein Build. Es lebt im Node-Prozess, der den SDK ausführt, also startet dieser Prozess neu.

```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);
```

### Lesen der Ausgabe

`output()` ist ein Cursor, kein Stream. Fragen Sie von einer Position und Sie erhalten, was danach kam, plus die nächste Position.

```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));
}
```

| Feld | Bedeutung |
| --- | --- |
| Text | was seither gedruckt wurde |
| Cursor | eine absolute Position — nächstes Mal wieder übergeben |
| Status | Laufen oder Fertigstellen |
| ExitCode | eingestellt, sobald es fertig ist |
| gekürzt | dein da war älter als das, was noch gehalten wird |

### Aufhören

```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() und kill() sind nicht die gleichen**
>
> interrupt() stoppt das, was läuft und lässt eine Shell zu verwenden. kill() nimmt den gesamten Prozessbaum mit, was Sie für einen Dev-Server wünschen, mit dem Sie fertig sind.

## Ein Agent auf dieser Maschine {#agent}

Nichts zu liefern: die Festplatte und die Shell sind bereits vorhanden, so dass das komplette Tool-Set verfügbar ist.

```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 ?? ""),
});
```

## Auf einem Server, mit niemand zu fragen {#headless}

`onPermission` Sie wird ohne Menschen genannt, und sie wird nicht als Politik, sondern als Politik, sondern als unruhiges Verhalten bezeichnet.

```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",
)
```
