# Node.js

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

整个表面:一个会话在磁盘上缓存,一个真正的工作空间, 超过答案的弹壳, 和一个在机器上运行的代理。

Status: node ≥ 18 · 文件系统 · Shell

## 届会居住地点 {#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",
});
```

> **同一个文件,一个账户**
>
> 两个客户端, 不同的密钥共享会话Path 覆盖对方。 给每个客户端各自选择自己的路径 。

## 工作空间 {#workspace}

A A A 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 |
| 删除文件或文件夹 | 中的项目,在.倾弃 |
| 正在移动到现有路径 | 没有任何东西被覆盖 - 移动被拒绝 |

这两个文件夹是特工的安全网,它们是普通的文件夹: 你可以读读它们,从它们那里恢复,或者自己清空它们。

## 终端终端 {#terminals}

仅此。 终端是一个真正的外壳, 其寿命超过启动它时的答案—— 一台Dev服务器, 一台监视器, 一台建筑。 它生活在 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));
}
```

| 字段 | 含义 |
| --- | --- |
| 文字文字文字文字 | 之后的印刷品 |
| 光标光标 | 绝对位置——下次传回去 |
| 状态状态状态状态状态状态状态 | 运行中或完成 |
| 退出日出日出 | 设置完成后设置 |
| 短短 | 那时你已经比现在还老了 |

### 阻止事情

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

> **中断( & kill () 不一样**
>
> 中() 中 中 中 中 停止运行中的内容, 并留给您一个 shell 可用 。 kill () 将整个进程树随此而去, 这就是您想要的 dev 服务器要完成的 。

## 这机器上的特工 {#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",
)
```
