# Node.js

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

La superficie completa: una sessione memorizzata sul disco, un vero spazio di lavoro, conchas che sopravviven a una risposta, e un agente che lavora sulla macchina su cui eserce.

Status: node ≥ 18 · sistema de arquivos · shell

## Onde vive la sessione {#session}

In `~/.iagenify/session`, dentro un directory creato con moda `0700`. Sopravvivivive reinizio, quindi un processo di lunga durata intercambia la chiave una e mai più.

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

> **Un file, un conto**
>
> Due clienti con chiavi diverse che condivide una sessionPath s'ecrascen reciprocamente. Dare a cada uno su propria via.

## L'espazion de lavoro {#workspace}

Una macchina Node registra se come un storage sul primo scambio di chiude. I suoi files vivon in `~/.iagenify/files` e stany là: un storage computer ningun byte not tiende sul servidor, e un upload mirat a un è rifiutat con `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");
```

### Nada è perdut per o predefinit

| Ação | Cenès che è conservat |
| --- | --- |
| Soprapponendo un dossier | la versione precedente, sotto .versions |
| Retira un file o un dossier | l'elemento, sotto .listra |
| Moviment su un sentiero existente | Nada è sovrascrit — la mossa è negata |

Those two folders are the agent's safety net, and they are ordinary folders: you can read them, restore from them, or empty them yourself.

## Terminals {#terminals}

Solo qui. Un terminal è un shell real che vive la risposta che lo ha inceput — un server dev, un watcher, un build. Vive nel processo Node che esegue il SDK, quindi reinizion che processo lo termina.

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

### Lectura del output

`output()` è un cursor, non un stream. Prego da una posizione e si ottiene quello che viene dopo, plus la posizione successiva.

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

| Campo | Significado |
| --- | --- |
| text | cosa fu imprimit dopo daque |
| Curtis | una posizione absoluta — ripassala la próxima volta |
| status | o terminato |
| Codigo di salida | set una volta che ha terminat |
| di troncatura | Tua dante era mais velho que lo que ancora se mantenne |

### Parando coses

```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() e kill() non sono imedes**
>
> interrupt() ferma ciò che sta correndo e te lascia un shell a usar. kill() prende l'arbore del processo completo con il, che è ciò che tu vuoi per un server dev con il quale tu hai finito.

## Un agent in questa macchina {#agent}

Nada da fornire: il disco e la shell sono ya là, quindi il set completo di utensili è disponibile.

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

## Su un server, con nessuno a chie {#headless}

`onPermission` è chiamato senza un humano dietro di esso. Risponde-lo come una politica, invece di lascia-lo desimpostato.

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