zapagent 1.14.6 → 1.14.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,134 +1,178 @@
1
1
  <p align="center">
2
- <img src="docs/images/readme/hero.png" alt="zapAgent — Code flows. Your terminal. A team of agents." width="100%" />
2
+ <img src="docs/images/readme/logo.png" alt="zapAgent logo" width="360" />
3
3
  </p>
4
4
 
5
- <h1 align="center">One task. A coordinated team of agents.</h1>
5
+ <h1 align="center">One task. A team of agents.</h1>
6
6
 
7
7
  <p align="center">
8
- Delegate work. Keep edits isolated. Watch every step.<br />
9
- A terminal coding agent with a reusable TypeScript runtime.
8
+ Delegate independent work. Review isolated edits. Watch the run unfold.<br />
9
+ An open-source, general-purpose agent and TypeScript SDK.
10
10
  </p>
11
11
 
12
12
  <p align="center">
13
+ <a href="https://www.npmjs.com/package/zapagent"><img src="https://img.shields.io/npm/v/zapagent?style=flat-square&color=b4e66e" alt="npm version" /></a>
14
+ <a href="https://github.com/JackCaow/zapagent/releases"><img src="https://img.shields.io/github/v/release/JackCaow/zapagent?style=flat-square" alt="Latest release" /></a>
15
+ <a href="https://github.com/JackCaow/zapagent/actions/workflows/ci.yml"><img src="https://github.com/JackCaow/zapagent/actions/workflows/ci.yml/badge.svg?branch=main" alt="CI" /></a>
16
+ <a href="LICENSE"><img src="https://img.shields.io/badge/CLI_%26_SDK-MIT-blue?style=flat-square" alt="CLI and SDK: MIT" /></a>
17
+ </p>
18
+
19
+ <p align="center">
20
+ <a href="#what-can-you-do-with-it">Use cases</a> ·
13
21
  <a href="#quick-start">Quick start</a> ·
14
- <a href="#see-the-work-as-it-happens">Live visualization</a> ·
15
- <a href="#how-the-agents-work-together">Architecture</a> ·
16
- <a href="docs/usage.md">CLI reference</a> ·
22
+ <a href="#give-your-agents-a-task">Try it</a> ·
23
+ <a href="#watch-the-work-happen">Live view</a> ·
24
+ <a href="#how-it-works">Architecture</a> ·
25
+ <a href="docs/usage.md">Docs</a> ·
17
26
  <a href="README.zh-CN.md">简体中文</a>
18
27
  </p>
19
28
 
20
- zapAgent brings **multi-agent collaboration, isolated workspaces, and live runtime visualization** into your terminal. Ask it to investigate a codebase, split an implementation into independent pieces, or review a change. Writing agents work in private snapshots; you can inspect their progress and approve artifact merges back into your project.
29
+ zapAgent works from your terminal to understand tasks, call tools, and deliver results. Use it to research a topic, organize documents, analyze data, develop software, or automate a workflow. For complex tasks, a coordinator can delegate work to child agents and bring their findings and artifacts together.
21
30
 
22
- Use Anthropic Messages, OpenAI Chat Completions, or **OpenAI Responses API**, including compatible endpoints. Keep your editor, terminal, and existing toolchain.
31
+ - **Work in parallel.** Split research, analysis, execution, and review into independent tasks, with dependencies and messages connecting the agents.
32
+ - **Keep edits isolated.** Agents produce files and edits in separate workspaces. Collect and review their artifacts before merging, with a clear delivery boundary for each change.
33
+ - **See the whole run.** `zap --watch` opens a local view of agents, tool calls, approvals, and completion states alongside your terminal.
23
34
 
24
- ## Built for work that needs more than one agent
35
+ Bring your own model connection: **Anthropic Messages, OpenAI Chat Completions, and OpenAI Responses API**, including compatible services. Connect your existing files, tools, and workflows.
25
36
 
26
- | Collaborate | Isolate | Observe |
27
- | :--- | :--- | :--- |
28
- | Delegate exploration, planning, and implementation to child agents. The coordinator manages dependencies, concurrency, messages, and run state. | Writing agents get private workspaces, including in non-Git projects. Their edits return as artifacts for an explicit merge. | `--watch` opens a live graph of model requests, tools, approvals, and child agents alongside the terminal. |
29
- | **Independent work can happen together.** | **Child edits reach your project through a merge gate.** | **See what is running, waiting, or finished.** |
37
+ ## What can you do with it?
30
38
 
31
- Try a prompt like this:
32
-
33
- ```text
34
- Investigate how authentication works in this repository.
35
- Delegate independent parts to agents: map the request flow, review session
36
- handling, and inspect the tests. Summarize their findings, then propose a fix.
37
- Ask before merging implementation artifacts into my workspace.
38
- ```
39
+ | Task | Try asking |
40
+ | :--- | :--- |
41
+ | Research | “Read these materials, compare the viewpoints, and summarize the findings with sources.” |
42
+ | Organize documents | “Turn the notes in this folder into a structured report.” |
43
+ | Analyze data | “Find trends and anomalies in this dataset and explain the evidence.” |
44
+ | Automate a workflow | “Organize these files by the given rules and produce an inventory and summary.” |
45
+ | Develop software | “Understand this project, implement the change, add tests, and review the result.” |
39
46
 
40
- Delegation follows the task and model decisions; independent steps can run concurrently, while dependent steps wait for their prerequisites.
47
+ Start with a task in plain language. When it benefits from delegation, agents can explore, analyze, and execute separate parts, then combine their results. Available capabilities depend on your model connection, configured tools, and permissions.
41
48
 
42
49
  ## Quick start
43
50
 
44
- Requires **Git** and **[Bun](https://bun.sh) 1.3+**. Bun 1.3.14 is the version pinned by this repository.
51
+ **1. Install zapAgent**
52
+
53
+ Requires Node.js 22+ (includes npm). Installation fetches the native program for your platform; no separate Bun installation is needed:
45
54
 
46
55
  ```bash
47
- git clone https://github.com/JackCaow/zapagent.git
48
- cd zapagent
49
- bun install --frozen-lockfile
50
- bun start
56
+ npm install -g zapagent
51
57
  ```
52
58
 
53
- In the terminal UI, run `/connect` to configure a provider, then `/model` to choose a model.
59
+ **2. Start in your working folder**
54
60
 
55
- To use this checkout from your own project:
61
+ Open a terminal in the folder containing your materials or project and run:
56
62
 
57
63
  ```bash
58
- # Run once inside the zapagent checkout.
59
- bun link
64
+ zap --watch
65
+ ```
66
+
67
+ Interact in the terminal and follow task progress in the live browser view.
68
+
69
+ **3. Connect a model and describe your task**
70
+
71
+ On first use, enter `/connect` and follow the setup prompts to connect your model service. Then describe what you want: “Read the materials in this folder, summarize the key points, and write a report.”
72
+
73
+ You need your own model service account and API key; usage is billed by your provider. [Connection guide](docs/usage.md#getting-started).
60
74
 
61
- # Then run from the project you want to work on.
62
- cd /path/to/your-project
63
- zapdev --watch
75
+ <details>
76
+ <summary>Other installation options and advanced setup: Bun, binaries, source, API protocols</summary>
77
+
78
+ **Install with Bun**:
79
+
80
+ ```bash
81
+ bun add --global zapagent
64
82
  ```
65
83
 
66
- Prefer a compiled CLI? Run `bun run build`, then use `dist/zap` from your checkout. Examples below use `zap`; the development command `zapdev` accepts the same arguments.
84
+ Git workspaces also require [Git](https://git-scm.com).
85
+
86
+ **Native binaries** — download from the [latest release](https://github.com/JackCaow/zapagent/releases/latest) and follow the [launch instructions](docs/usage.md#native-binary-setup):
87
+
88
+ | Platform | Downloads |
89
+ | :--- | :--- |
90
+ | macOS | [Apple Silicon](https://github.com/JackCaow/zapagent/releases/latest/download/zap-macos-arm64) · [Intel](https://github.com/JackCaow/zapagent/releases/latest/download/zap-macos-x64) |
91
+ | Linux | [ARM64](https://github.com/JackCaow/zapagent/releases/latest/download/zap-linux-arm64) · [x64](https://github.com/JackCaow/zapagent/releases/latest/download/zap-linux-x64) |
92
+ | Windows | [x64](https://github.com/JackCaow/zapagent/releases/latest/download/zap-windows-x64.exe) |
67
93
 
68
- > Source installation is available now. Binary and npm releases are published through the [release workflows](docs/releasing.md); check [GitHub Releases](https://github.com/JackCaow/zapagent/releases) for available versions.
94
+ **Model configuration** — use `/model` to choose a model and `/effort` to adjust supported reasoning settings. For custom services, enter the Base URL and API key in `/connect` and select the service's API protocol; choose **OpenAI Responses** for a Responses endpoint. [Responses configuration](docs/usage.md#openai-responses-api).
69
95
 
70
- ## See the work as it happens
96
+ **From source** — the repository pins Bun 1.3.14:
71
97
 
72
98
  ```bash
73
- zap --watch
99
+ git clone https://github.com/JackCaow/zapagent.git
100
+ cd zapagent
101
+ bun install --frozen-lockfile
102
+ bun start
74
103
  ```
75
104
 
76
- Keep coding in the terminal while a local browser view shows the run unfolding: which agent is active, which tool is running, where approval is needed, and which steps have finished.
105
+ Run `bun link` in the checkout, then use `zapdev` from your working folder. Or run `bun run build` and use `dist/zap`.
77
106
 
78
- ![Watch UI showing a root agent, a child agent, tool activity, and an approval wait. Synthetic demo events.](docs/images/readme/watch-preview.png)
107
+ Binaries include SHA-256 checksums. macOS binaries are ad-hoc signed, not Developer ID signed or notarized. See the [release guide](docs/releasing.md).
79
108
 
80
- *The actual Watch interface, captured with the repository's synthetic preview events. This is a UI demonstration, not a benchmark or a recorded model run.*
109
+ </details>
81
110
 
82
- - **Follow the agent tree:** root and child runs stay connected to their tools and lifecycle states.
83
- - **Understand waits:** distinguish model activity, tool execution, approval, and completion.
84
- - **Keep the terminal in control:** Watch is read-only. Refreshing the page does not replay tools or change the run.
85
- - **Keep content out of the viewer:** Watch projects runtime metadata; prompts, tool arguments, and tool output are excluded. Its loopback URL contains a private access token.
111
+ ## Give your agents a task
86
112
 
87
- Use `--watch-no-open` to print the viewer URL without opening a browser. See [Watch architecture](docs/architecture/57-watch-runtime-observability.md) for the event flow and current limits.
113
+ Start with a task that benefits from several perspectives:
88
114
 
89
- ## How the agents work together
115
+ ```text
116
+ Read the materials in this directory and prepare a project assessment.
117
+ Delegate independent parts to child agents: map the project background,
118
+ analyze risks, and review the conclusions against the evidence.
119
+ Combine the results in report.md. Cite sources and flag missing information.
120
+ Ask before merging the report into my workspace.
121
+ ```
90
122
 
91
- ![Agent architecture: the host drives a root agent and coordinator; read-only agents share a view, writing agents use private snapshots, and artifacts pass conflict and drift checks before merging. Tools run through policy and execution layers; events feed the read-only Watch view.](docs/images/readme/architecture.svg)
123
+ The coordinator manages child-agent dependencies, concurrency, messages, and lifecycle states. Delegation follows the task and model decisions; independent work can run together, while dependent work waits for prerequisites.
92
124
 
93
- 1. **The host starts a run.** The terminal, headless CLI, or ACP adapter uses `AgentRuntime`. `LoopAgent` handles the model/tool loop with context management and execution budgets.
94
- 2. **The coordinator delegates.** Child runs have their own identities, lifecycle states, dependencies, and messaging. Independent work can run concurrently within configured limits.
95
- 3. **Writing agents work in isolation.** Git projects use private clones of a working-tree snapshot, including eligible uncommitted changes. Non-Git projects use controlled copy snapshots. Read-only agents can share the parent workspace view.
96
- 4. **Results come back through a merge gate.** Writing agents produce frozen artifacts. Merging checks conflicts and parent-workspace drift before applying changes. Child staging and commits stay private; merging delivers file changes, not child commit history.
97
- 5. **Runtime events make progress visible.** Watch observes the execution lifecycle without controlling it. The runtime distinguishes execution outcomes from acceptance; task acceptance requires an explicit evaluator or human review.
125
+ Writing agents can process files, write reports, and run scripts in their private workspaces. Development tasks can also install dependencies, run tests, and stage or commit changes, subject to tool permissions and the platform sandbox. Merging applies file changes to the parent workspace; it does not import the child's commit history. See [workspace isolation](docs/architecture/48-non-git-workspace-isolation.md).
98
126
 
99
- The three modules have separate responsibilities:
127
+ ## Watch the work happen
100
128
 
101
- | Module | Responsibility |
102
- | :--- | :--- |
103
- | [`src/`](src/) | Terminal UI, provider setup, sessions, headless/ACP hosts, and Watch. |
104
- | [`zapsdk/`](zapsdk/) | Reusable TypeScript agent runtime: model loop, orchestration, tools, policy, workspaces, merge, context, memory, and events. |
105
- | [`zapvm/`](zapvm/) | Independent Go execution runtime. Optional VM execution sits behind the SDK's execution protocol; the VM does not own agent prompts, permissions, or completion decisions. |
129
+ ![The actual Watch UI showing connected agents, tool activity, and an approval wait, using synthetic demo events.](docs/images/readme/watch-preview.png)
106
130
 
107
- Explore the [architecture guide](docs/architecture/README.md), [multi-agent design](docs/architecture/26-multi-agent-orchestration.md), and [non-Git workspace isolation](docs/architecture/48-non-git-workspace-isolation.md).
131
+ *Captured from the actual Watch UI using synthetic preview events. This illustrates the interface, not a benchmark or a recorded model run.*
108
132
 
109
- ## More of your workflow, in one place
133
+ Run `zap --watch` to follow the agent tree and tool lifecycle in a local browser. See which agents are active, which tools are executing, and where approval is needed.
110
134
 
111
- - **Choose your model.** Connect Anthropic or OpenAI-compatible providers and switch with `/model`; adjust supported reasoning settings with `/effort`.
112
- - **Keep long tasks moving.** Context compaction, project memory, saved sessions, and a follow-up queue help carry work across turns. Steer the active task or queue the next request with `/queue`.
113
- - **Control tool access.** Inspect permissions and scoped approvals with `/permissions`. Commands use the host OS sandbox by default; VM execution is opt-in. See the [execution boundary](docs/architecture/39-local-sandbox-default.md) for platform-specific restrictions.
114
- - **Return to earlier work.** `/rewind` can restore conversation, tracked code changes, or both. Checkpoints have coverage limits; external effects and every filesystem topology change are not fully reversible.
115
- - **Bring your tools.** Built-in file, search, shell, HTTP, and document tools sit alongside MCP integrations and skills.
116
- - **Build your own host.** Reuse the SDK, stream structured headless output, or connect an ACP-compatible client.
135
+ Watch is **read-only** and displays runtime metadata rather than prompts, tool arguments, or tool output. Refreshing the page does not replay tools. Its loopback URL contains a private access token; do not share it. Use `--watch-no-open` to print the URL without opening a browser. [Watch details →](docs/architecture/57-watch-runtime-observability.md)
117
136
 
118
- ### Script it
137
+ ## Fit it into your workflow
119
138
 
120
- After configuring a provider:
139
+ | What you need | What zapAgent provides |
140
+ | :--- | :--- |
141
+ | Use your model provider | `/connect`, `/model`, and `/effort`; Anthropic, Chat Completions, and Responses protocols. |
142
+ | Continue a long task | Context compaction, project memory, saved sessions, and `/queue` for follow-up requests. |
143
+ | Control tool access | `/permissions`, scoped approvals, and the host OS sandbox by default. [Platform boundaries](docs/architecture/39-local-sandbox-default.md). |
144
+ | Return to earlier work | `/rewind` for conversation, tracked code changes, or both. External effects and some filesystem changes are outside checkpoint coverage. |
145
+ | Bring existing tools | Built-in file, search, shell, HTTP, and document tools, plus MCP integrations and skills. |
146
+ | Automate or build a host | Structured headless output, an ACP adapter, and a reusable TypeScript SDK. |
147
+
148
+ After configuring a provider, use the CLI in scripts:
121
149
 
122
150
  ```bash
123
- zap -p "Explain this repository's architecture" --output-format json
124
- zap --watch -p "Review the latest changes" --output-format stream-json --watch-linger 30
151
+ zap -p "Organize the materials in this directory into themes, findings, and open questions" --output-format json
152
+ zap --watch -p "Analyze the data in this directory and write a report" --output-format stream-json --watch-linger 30
125
153
  ```
126
154
 
127
- Use `zap --help-headless` for automation options. See the [CLI reference](docs/usage.md) for all slash commands, keyboard shortcuts, environment variables, approval scopes, and optional VM setup.
155
+ See `zap --help-headless` and the [CLI reference](docs/usage.md) for commands, configuration, approvals, and automation.
156
+
157
+ ## How it works
158
+
159
+ ![Architecture: a host and coordinator delegate to read-only agents or isolated writing agents. Artifacts pass merge checks, tools run through policy and execution layers, and runtime events feed the read-only Watch view.](docs/images/readme/architecture.svg)
128
160
 
129
- ## Build with us
161
+ The host starts a run through `AgentRuntime`. `LoopAgent` manages the model/tool loop, context, and execution budgets. The coordinator manages child runs; writing agents return frozen artifacts that pass conflict and workspace-drift checks before merging. Runtime events feed Watch. Execution success and task acceptance are separate: acceptance requires an explicit evaluator or human review.
130
162
 
131
- Useful contributions include reproducible agent failures, clearer runtime visualization, provider compatibility fixes, and platform-specific sandbox tests. Include the expected behavior and a minimal reproduction; remove credentials and private code from reports.
163
+ | Module | Responsibility |
164
+ | :--- | :--- |
165
+ | [`src/`](src/) | Terminal UI, provider setup, sessions, headless/ACP hosts, and Watch. |
166
+ | [`zapsdk/`](zapsdk/) | TypeScript agent runtime: model loop, orchestration, tools, permissions, workspaces, merge, context, memory, and events. |
167
+ | [`zapvm/`](zapvm/) | Independent Go execution runtime. Optional VM execution connects through the SDK protocol; the VM does not own agent prompts, permissions, or completion decisions. |
168
+
169
+ Git workspaces use private clones of a working-tree snapshot, including eligible uncommitted changes. Non-Git projects use controlled copy snapshots. Read-only agents can share the parent workspace view.
170
+
171
+ Read the [architecture guide](docs/architecture/README.md) and [multi-agent design](docs/architecture/26-multi-agent-orchestration.md) for implementation details.
172
+
173
+ ## Contributing
174
+
175
+ Help improve provider compatibility, sandbox behavior, collaboration, or the live view. Bug reports are most useful with expected behavior and a minimal reproduction, with credentials and private code removed.
132
176
 
133
177
  ```bash
134
178
  bun run typecheck
@@ -136,9 +180,7 @@ bun test
136
180
  bun run build
137
181
  ```
138
182
 
139
- Working on the independent VM module? Use `bun run check:vm`; `bun run build:all` builds both host components. See [CONTRIBUTING.md](CONTRIBUTING.md) and report vulnerabilities via [SECURITY.md](SECURITY.md).
140
-
141
- If this is the workflow you want in your terminal, star the repository and help shape it.
183
+ For the independent VM module, use `bun run check:vm`; `bun run build:all` builds both host components. See [CONTRIBUTING.md](CONTRIBUTING.md), [open issues](https://github.com/JackCaow/zapagent/issues), and [SECURITY.md](SECURITY.md).
142
184
 
143
185
  ## License
144
186
 
package/README.zh-CN.md CHANGED
@@ -1,134 +1,177 @@
1
1
  <p align="center">
2
- <img src="docs/images/readme/hero.png" alt="zapAgent — Code flows. 在终端里,与一组 agent 协作。" width="100%" />
2
+ <img src="docs/images/readme/logo.png" alt="zapAgent 品牌标志" width="360" />
3
3
  </p>
4
4
 
5
5
  <h1 align="center">一个任务,一组协作的 agent。</h1>
6
6
 
7
7
  <p align="center">
8
- 分工协作 · 隔离修改 · 实时可见<br />
9
- 运行在终端中的编程 agent,以及可复用的 TypeScript 运行时。
8
+ 分工并行,隔离修改,实时看见进展。<br />
9
+ 开源通用 agent,以及可复用的 TypeScript SDK。
10
10
  </p>
11
11
 
12
12
  <p align="center">
13
+ <a href="https://www.npmjs.com/package/zapagent"><img src="https://img.shields.io/npm/v/zapagent?style=flat-square&color=b4e66e" alt="npm 版本" /></a>
14
+ <a href="https://github.com/JackCaow/zapagent/releases"><img src="https://img.shields.io/github/v/release/JackCaow/zapagent?style=flat-square" alt="最新版本" /></a>
15
+ <a href="https://github.com/JackCaow/zapagent/actions/workflows/ci.yml"><img src="https://github.com/JackCaow/zapagent/actions/workflows/ci.yml/badge.svg?branch=main" alt="CI" /></a>
16
+ <a href="LICENSE"><img src="https://img.shields.io/badge/CLI_%26_SDK-MIT-blue?style=flat-square" alt="CLI 与 SDK:MIT" /></a>
17
+ </p>
18
+
19
+ <p align="center">
20
+ <a href="#你可以让它做什么">能做什么</a> ·
13
21
  <a href="#快速开始">快速开始</a> ·
22
+ <a href="#交给-agent-一个任务">协作示例</a> ·
14
23
  <a href="#看见任务如何推进">实时可视化</a> ·
15
- <a href="#agent-如何协作">架构</a> ·
16
- <a href="docs/usage.md">CLI 手册</a> ·
24
+ <a href="#它如何工作">架构</a> ·
25
+ <a href="docs/usage.md">文档</a> ·
17
26
  <a href="README.md">English</a>
18
27
  </p>
19
28
 
20
- zapAgent 把 **多 agent 协作、隔离工作区和实时运行图**带进你的终端。让它梳理陌生仓库、拆分独立实现任务,或审查一组改动。写入型 agent 在私有快照里工作,你可以观察过程,再审批将产物合并回项目。
29
+ zapAgent 在终端中理解任务、调用工具并交付结果。用它调研信息、整理文档、分析数据、开发软件,或将多个步骤串成自动化流程。面对复杂任务,协调器可以分派多个子 agent,汇总它们的发现和产物。
21
30
 
22
- 支持 Anthropic Messages、OpenAI Chat Completions、**OpenAI Responses API** 及兼容服务,沿用你现有的编辑器、终端和工具链。
31
+ - **分工并行。** 将调研、分析、执行、审查拆成独立任务,通过依赖关系和消息组织协作。
32
+ - **隔离修改。** 让不同 agent 在独立工作区中产出文件和修改,收集产物后再检查、合并。每份改动都有清晰的交付边界。
33
+ - **实时可见。** `zap --watch` 在终端旁打开本地运行视图,展示 agent、工具调用、审批和完成状态。
23
34
 
24
- ## 让复杂任务有分工,让每份改动有边界
35
+ 支持自带模型连接:**Anthropic Messages、OpenAI Chat Completions、OpenAI Responses API** 及兼容服务,接入你现有的文件、工具和工作流。
25
36
 
26
- | 多 agent 协作 | 隔离工作区 | 实时可视化 |
27
- | :--- | :--- | :--- |
28
- | 把探索、规划、实现交给子 agent。协调器管理依赖、并发、消息和运行状态。 | 写入型 agent 使用独立工作区,非 Git 项目同样适用。修改收集为产物,经显式合并回到项目。 | `--watch` 打开实时运行图,在终端旁查看模型请求、工具执行、审批和子 agent 状态。 |
29
- | **独立的工作可以一起推进。** | **子 agent 的修改通过合并检查进入项目。** | **看清谁在运行、谁在等待、谁已完成。** |
37
+ ## 你可以让它做什么
30
38
 
31
- 可以从这样的任务开始:
32
-
33
- ```text
34
- 帮我梳理这个仓库的认证机制。
35
- 把独立部分交给子 agent:梳理请求链路、审查会话管理、检查测试覆盖。
36
- 汇总它们的发现,再提出修复方案。
37
- 将实现产物合并回我的工作区之前,先请求审批。
38
- ```
39
+ | 场景 | 试着这样说 |
40
+ | :--- | :--- |
41
+ | 资料调研 | “阅读这些材料,对比不同观点,整理结论并标明来源。” |
42
+ | 文档整理 | “把这个文件夹里的零散记录整理成一份结构清晰的报告。” |
43
+ | 数据分析 | “分析这份数据,找出变化趋势和异常,说明判断依据。” |
44
+ | 流程自动化 | “按规则整理这些文件,生成目录清单和处理结果。” |
45
+ | 软件开发 | “理解这个项目,完成改动、补充测试,再审查结果。” |
39
46
 
40
- 实际分工由任务和模型决策驱动;独立步骤可以并发执行,有依赖的步骤等待前置结果。
47
+ 任务可以从一句话开始。需要分工时,让多个 agent 分别探索、分析和执行,最后汇总成你需要的结果。可用范围取决于连接的模型、已配置的工具和授权。
41
48
 
42
49
  ## 快速开始
43
50
 
44
- 需要 **Git** 和 **[Bun](https://bun.sh) 1.3+**,仓库固定使用 Bun 1.3.14。
51
+ **1. 安装 zapAgent**
52
+
53
+ 需要 Node.js 22+(包含 npm)。安装时自动获取对应平台的独立程序,无需单独安装 Bun:
45
54
 
46
55
  ```bash
47
- git clone https://github.com/JackCaow/zapagent.git
48
- cd zapagent
49
- bun install --frozen-lockfile
50
- bun start
56
+ npm install -g zapagent
51
57
  ```
52
58
 
53
- 进入终端界面后,使用 `/connect` 配置模型服务,再用 `/model` 选择模型。
59
+ **2. 在你的工作文件夹中启动**
54
60
 
55
- 在你自己的项目中使用:
61
+ 在存放资料或项目的文件夹中打开终端,运行:
56
62
 
57
63
  ```bash
58
- # 在 zapagent 源码目录执行一次。
59
- bun link
64
+ zap --watch
65
+ ```
66
+
67
+ 终端用于交互,浏览器中的实时视图展示任务进展。
68
+
69
+ **3. 连接模型,描述任务**
70
+
71
+ 首次使用时,输入 `/connect`,按界面引导连接你的模型服务。然后直接告诉它你要完成什么,例如:“阅读这个文件夹里的资料,整理重点并生成一份报告。”
72
+
73
+ 需要你自己的模型服务账号和 API Key,调用费用由模型服务商收取。[连接指南](docs/usage.md#getting-started)。
60
74
 
61
- # 切换到需要处理的项目。
62
- cd /path/to/your-project
63
- zapdev --watch
75
+ <details>
76
+ <summary>其他安装方式与高级配置:Bun、二进制、源码、API 协议</summary>
77
+
78
+ **Bun 安装**:
79
+
80
+ ```bash
81
+ bun add --global zapagent
64
82
  ```
65
83
 
66
- 也可以运行 `bun run build`,使用源码目录下的 `dist/zap` 编译产物。下文以 `zap` 为例,开发命令 `zapdev` 接受相同参数。
84
+ Git 工作区还需要安装 [Git](https://git-scm.com)。
67
85
 
68
- > 目前可从源码安装。二进制和 npm 发布流程见[发布说明](docs/releasing.md),可用版本以 [GitHub Releases](https://github.com/JackCaow/zapagent/releases) 为准。
86
+ **独立二进制**——从 [最新版本](https://github.com/JackCaow/zapagent/releases/latest) 下载,并按[启动步骤](docs/usage.md#native-binary-setup)运行:
69
87
 
70
- ## 看见任务如何推进
88
+ | 平台 | 下载 |
89
+ | :--- | :--- |
90
+ | macOS | [Apple Silicon](https://github.com/JackCaow/zapagent/releases/latest/download/zap-macos-arm64) · [Intel](https://github.com/JackCaow/zapagent/releases/latest/download/zap-macos-x64) |
91
+ | Linux | [ARM64](https://github.com/JackCaow/zapagent/releases/latest/download/zap-linux-arm64) · [x64](https://github.com/JackCaow/zapagent/releases/latest/download/zap-linux-x64) |
92
+ | Windows | [x64](https://github.com/JackCaow/zapagent/releases/latest/download/zap-windows-x64.exe) |
93
+
94
+ **模型配置**——用 `/model` 选择模型,用 `/effort` 调整模型支持的推理档位。自定义服务时,在 `/connect` 填入 Base URL 和 API Key,并选择服务支持的协议;Responses 端点选择 **OpenAI Responses**。[Responses 配置](docs/usage.md#openai-responses-api)。
95
+
96
+ **从源码运行**——仓库固定使用 Bun 1.3.14:
71
97
 
72
98
  ```bash
73
- zap --watch
99
+ git clone https://github.com/JackCaow/zapagent.git
100
+ cd zapagent
101
+ bun install --frozen-lockfile
102
+ bun start
74
103
  ```
75
104
 
76
- 继续在终端里工作,同时在本地浏览器查看 agent、工具和审批如何推进。模型还在生成,工具正在执行,还是子 agent 在等待依赖,都有对应的运行状态。
105
+ 在源码目录执行 `bun link` 后,可在自己的工作目录中使用 `zapdev`;也可以执行 `bun run build`,使用 `dist/zap`。
77
106
 
78
- ![Watch 实际界面:主 agent、子 agent、工具活动与审批等待;使用模拟事件演示。](docs/images/readme/watch-preview.png)
107
+ 二进制附带 SHA-256 校验文件。macOS 二进制使用临时签名,尚未进行 Developer ID 签名或公证。详见[发布说明](docs/releasing.md)。
79
108
 
80
- *截图来自仓库的真实 Watch 界面,使用内置模拟事件进行展示,不代表基准测试或一次真实模型任务。*
109
+ </details>
81
110
 
82
- - **跟随协作关系:** 主 agent、子 agent 和工具调用保留各自的身份与关联。
83
- - **区分等待原因:** 查看模型活动、工具执行、审批和完成状态。
84
- - **在终端掌握控制权:** Watch 只读;刷新页面不会重放工具或改变任务。
85
- - **只展示运行元数据:** 页面排除提示词、工具参数和工具输出。本地回环地址包含访问令牌,请勿分享。
111
+ ## 交给 agent 一个任务
86
112
 
87
- 使用 `--watch-no-open` 可以只输出地址,不自动打开浏览器。事件流与当前边界见 [Watch 架构说明](docs/architecture/57-watch-runtime-observability.md)。
113
+ 从一个需要多方协作的任务开始:
88
114
 
89
- ## Agent 如何协作
115
+ ```text
116
+ 阅读当前目录的资料,整理一份项目评估报告。
117
+ 把独立部分交给子 agent:梳理项目背景、分析风险、审查结论与依据。
118
+ 汇总为 report.md,引用资料来源,标明信息缺口。
119
+ 将报告合并回我的工作区之前,先请求审批。
120
+ ```
90
121
 
91
- ![Agent 架构:宿主驱动主 agent 与协调器;只读 agent 共享视图,写入 agent 使用私有快照;产物经冲突和工作区漂移检查后合并。工具通过权限与执行层运行,事件流进入只读 Watch。](docs/images/readme/architecture.svg)
122
+ 协调器管理子 agent 的依赖、并发、消息和生命周期。实际分工由任务和模型决策驱动;独立步骤可以并行,有依赖的步骤等待前置结果。
92
123
 
93
- 1. **宿主发起任务。** 终端、Headless CLI 或 ACP 适配器接入 `AgentRuntime`。`LoopAgent` 负责模型与工具循环,同时管理上下文和执行预算。
94
- 2. **协调器组织分工。** 子 agent 拥有独立身份、生命周期、依赖和消息通道。独立任务可以在配置的并发额度内同时推进。
95
- 3. **写入任务进入隔离工作区。** Git 项目从工作树快照创建私有克隆,包含符合快照规则的未提交修改;非 Git 项目使用受控复制快照。只读 agent 可以共享父工作区视图。
96
- 4. **通过产物合并交付修改。** 写入型 agent 生成冻结产物;合并前检查冲突和父工作区是否发生变化。子 agent 的暂存和提交留在私有仓库,合并交付文件修改,不搬运子 agent 的提交历史。
97
- 5. **事件流让过程可见。** Watch 观察执行生命周期,不控制任务。运行时区分执行结果与任务验收;任务是否满足要求,需要显式评估器或人工审查。
124
+ 写入型 agent 在私有工作区中处理文件、编写报告、运行脚本;开发任务也可以安装依赖、运行测试,以及暂存或提交修改,具体受工具权限和平台沙箱约束。合并交付文件修改,不搬运子 agent 的提交历史。详见[工作区隔离](docs/architecture/48-non-git-workspace-isolation.md)。
98
125
 
99
- 三个模块各司其职:
126
+ ## 看见任务如何推进
100
127
 
101
- | 模块 | 职责 |
102
- | :--- | :--- |
103
- | [`src/`](src/) | 终端交互、模型配置、会话、Headless/ACP 宿主和 Watch。 |
104
- | [`zapsdk/`](zapsdk/) | 可复用的 TypeScript agent 运行时:模型循环、协作、工具、权限、工作区、合并、上下文、记忆与事件。 |
105
- | [`zapvm/`](zapvm/) | 独立 Go 执行运行时。可选 VM 通过 SDK 执行协议接入,不负责 agent 提示词、权限或完成判定。 |
128
+ ![真实 Watch 界面:主 agent、子 agent、工具活动与审批等待;使用模拟事件演示。](docs/images/readme/watch-preview.png)
106
129
 
107
- 深入阅读:[架构索引](docs/architecture/README.md)、[多 agent 设计](docs/architecture/26-multi-agent-orchestration.md)、[非 Git 工作区隔离](docs/architecture/48-non-git-workspace-isolation.md)。
130
+ *截图来自真实 Watch 界面,使用内置模拟事件展示,不代表基准测试或一次真实模型任务。*
108
131
 
109
- ## 把日常工作串起来
132
+ 运行 `zap --watch`,在本地浏览器中跟随 agent 协作关系和工具生命周期:谁在运行、哪个工具正在执行、哪里需要审批,都有对应状态。
110
133
 
111
- - **自由选择模型。** 连接 Anthropic 或 OpenAI 兼容服务,用 `/model` 切换模型,用 `/effort` 调整受支持的推理设置。
112
- - **持续推进长任务。** 上下文压缩、项目记忆、保存的会话和后续消息队列帮助跨轮次工作。用 `/queue` 追加下一步,或调整当前任务方向。
113
- - **掌握工具权限。** 通过 `/permissions` 查看权限和授权范围。命令默认使用宿主 OS 沙箱,VM 按需启用;平台差异见[执行边界说明](docs/architecture/39-local-sandbox-default.md)。
114
- - **回到之前的工作。** `/rewind` 支持恢复对话、已跟踪的代码修改或两者。恢复点有覆盖范围,外部副作用和所有文件目录结构变化并非都能完整撤销。
115
- - **接入已有工具。** 内置文件、搜索、Shell、HTTP 和文档工具,并支持 MCP 与 skills。
116
- - **构建自己的宿主。** 复用 SDK,通过 Headless 输出结构化事件,或接入兼容 ACP 的客户端。
134
+ Watch **只读**,展示运行元数据,不展示提示词、工具参数或工具输出。刷新页面不会重放工具。本地回环地址包含私有访问令牌,请勿分享。使用 `--watch-no-open` 可以只输出地址,不自动打开浏览器。[Watch 详细说明 →](docs/architecture/57-watch-runtime-observability.md)
117
135
 
118
- ### 接入脚本
136
+ ## 接入你的工作流
119
137
 
120
- 配置模型服务后:
138
+ | 你的需求 | zapAgent 提供的能力 |
139
+ | :--- | :--- |
140
+ | 使用自己的模型服务 | `/connect`、`/model`、`/effort`;支持 Anthropic、Chat Completions 和 Responses 协议。 |
141
+ | 持续推进长任务 | 上下文压缩、项目记忆、保存的会话,以及 `/queue` 后续请求队列。 |
142
+ | 掌握工具权限 | `/permissions`、限定范围的审批,默认使用宿主 OS 沙箱。[平台边界](docs/architecture/39-local-sandbox-default.md)。 |
143
+ | 回到之前的工作 | `/rewind` 恢复对话、已跟踪的代码修改或两者;外部副作用和部分文件系统变化不在恢复范围内。 |
144
+ | 接入现有工具 | 内置文件、搜索、Shell、HTTP 和文档工具,以及 MCP 集成和 skills。 |
145
+ | 自动化或构建自己的宿主 | 结构化 Headless 输出、ACP 适配器,以及可复用的 TypeScript SDK。 |
146
+
147
+ 配置模型服务后,可以接入脚本:
121
148
 
122
149
  ```bash
123
- zap -p "解释这个仓库的架构" --output-format json
124
- zap --watch -p "审查最近的改动" --output-format stream-json --watch-linger 30
150
+ zap -p "整理当前目录的资料,列出主题、结论与待确认的问题" --output-format json
151
+ zap --watch -p "分析当前目录的数据并生成报告" --output-format stream-json --watch-linger 30
125
152
  ```
126
153
 
127
- 运行 `zap --help-headless` 查看自动化选项。完整命令、快捷键、环境变量、审批范围和可选 VM 配置见 [CLI 手册](docs/usage.md)。
154
+ 完整命令、配置、审批和自动化选项见 `zap --help-headless` 与 [CLI 手册](docs/usage.md)。
155
+
156
+ ## 它如何工作
157
+
158
+ ![架构:宿主和协调器向只读 agent 或隔离写入 agent 分派任务;产物经过合并检查,工具经过权限与执行层,事件流进入只读 Watch。](docs/images/readme/architecture.svg)
159
+
160
+ 宿主通过 `AgentRuntime` 发起任务,`LoopAgent` 管理模型与工具循环、上下文和执行预算。协调器组织子任务;写入型 agent 返回冻结产物,经过冲突和工作区漂移检查后合并。运行事件驱动 Watch。执行成功与任务验收分别记录,验收需要显式评估器或人工审查。
161
+
162
+ | 模块 | 职责 |
163
+ | :--- | :--- |
164
+ | [`src/`](src/) | 终端交互、模型配置、会话、Headless/ACP 宿主和 Watch。 |
165
+ | [`zapsdk/`](zapsdk/) | TypeScript agent 运行时:模型循环、协作、工具、权限、工作区、合并、上下文、记忆与事件。 |
166
+ | [`zapvm/`](zapvm/) | 独立 Go 执行运行时;可选 VM 通过 SDK 协议接入,不负责 agent 提示词、权限或完成判定。 |
128
167
 
129
- ## 一起改进
168
+ Git 项目使用工作树快照的私有克隆,包含符合规则的未提交修改;非 Git 项目使用受控复制快照。只读 agent 可以共享父工作区视图。
130
169
 
131
- 欢迎提交可复现的 agent 问题、运行可视化改进、模型服务兼容性修复,以及各平台的沙箱测试。反馈时附上预期行为与最小复现,并移除凭据和私有代码。
170
+ 实现细节见[架构索引](docs/architecture/README.md)与[多 agent 设计](docs/architecture/26-multi-agent-orchestration.md)。
171
+
172
+ ## 参与贡献
173
+
174
+ 欢迎改进模型兼容性、沙箱行为、多 agent 协作和运行可视化。反馈问题时,请附上预期行为与最小复现,并移除凭据和私有代码。
132
175
 
133
176
  ```bash
134
177
  bun run typecheck
@@ -136,9 +179,7 @@ bun test
136
179
  bun run build
137
180
  ```
138
181
 
139
- 修改独立 VM 模块时使用 `bun run check:vm`;`bun run build:all` 构建两部分宿主组件。开发流程见 [CONTRIBUTING.md](CONTRIBUTING.md),漏洞报告方式见 [SECURITY.md](SECURITY.md)。
140
-
141
- 如果这也是你期待的终端工作方式,欢迎 Star 并参与完善。
182
+ 修改独立 VM 模块时使用 `bun run check:vm`;`bun run build:all` 构建两部分宿主组件。详见 [CONTRIBUTING.md](CONTRIBUTING.md)、[Issues](https://github.com/JackCaow/zapagent/issues) 和 [SECURITY.md](SECURITY.md)。
142
183
 
143
184
  ## 许可证
144
185
 
package/npm/cli.cjs ADDED
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env node
2
+ const { spawn } = require("node:child_process");
3
+ const { constants } = require("node:os");
4
+ const { ensureBinary } = require("./install.cjs");
5
+ (async () => {
6
+ const binary = await ensureBinary();
7
+ const child = spawn(binary, process.argv.slice(2), { stdio: "inherit", env: process.env });
8
+ const forward = signal => { if (!child.killed) child.kill(signal); };
9
+ const handlers = Object.fromEntries(["SIGINT", "SIGTERM", "SIGHUP"].map(signal => [signal, () => forward(signal)]));
10
+ for (const [signal, handler] of Object.entries(handlers)) process.on(signal, handler);
11
+ child.on("error", error => { console.error(`Could not start zapAgent: ${error.message}`); process.exitCode = 1; });
12
+ child.on("exit", (code, signal) => {
13
+ for (const [name, handler] of Object.entries(handlers)) process.removeListener(name, handler);
14
+ process.exitCode = code ?? (signal ? 128 + (constants.signals[signal] || 1) : 1);
15
+ });
16
+ })().catch(error => {
17
+ console.error(`zapAgent: ${error.message}\nCheck network access to GitHub Releases, then run zap again.`);
18
+ process.exitCode = 1;
19
+ });
@@ -0,0 +1,80 @@
1
+ // The CLI is a compiled executable; only SDK/source development needs Bun.
2
+ const { createHash, randomUUID } = require("node:crypto");
3
+ const { chmodSync, createReadStream, createWriteStream, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } = require("node:fs");
4
+ const { Readable, Transform } = require("node:stream");
5
+ const { pipeline } = require("node:stream/promises");
6
+ const { homedir } = require("node:os");
7
+ const { dirname, join } = require("node:path");
8
+
9
+ const assets = Object.freeze({
10
+ "darwin-arm64": "zap-macos-arm64", "darwin-x64": "zap-macos-x64",
11
+ "linux-arm64": "zap-linux-arm64", "linux-x64": "zap-linux-x64",
12
+ "win32-x64": "zap-windows-x64.exe",
13
+ });
14
+ function target(platform = process.platform, arch = process.arch) {
15
+ const asset = assets[`${platform}-${arch}`];
16
+ if (!asset) throw new Error(`zapAgent does not provide a binary for ${platform}/${arch}. Supported: ${Object.keys(assets).join(", ")}`);
17
+ return asset;
18
+ }
19
+ function digest(bytes) { return createHash("sha256").update(bytes).digest("hex"); }
20
+ async function validBinary(file, checksum) {
21
+ if (typeof checksum !== "string" || !/^[a-f0-9]{64}$/.test(checksum)) return false;
22
+ try {
23
+ const hash = createHash("sha256");
24
+ for await (const bytes of createReadStream(file)) hash.update(bytes);
25
+ return hash.digest("hex") === checksum;
26
+ } catch { return false; }
27
+ }
28
+ async function ensureBinary(options = {}) {
29
+ const platform = options.platform ?? process.platform, arch = options.arch ?? process.arch;
30
+ const asset = target(platform, arch);
31
+ const version = options.version ?? require("../package.json").version;
32
+ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) throw new Error("Invalid zapAgent package version");
33
+ const env = options.env ?? process.env;
34
+ const cache = env.ZAPAGENT_CACHE_DIR || (platform === "win32" ? env.LOCALAPPDATA : env.XDG_CACHE_HOME) || join(homedir(), ".cache");
35
+ const file = join(cache, "zapagent", version, `${platform}-${arch}`, platform === "win32" ? "zap.exe" : "zap");
36
+ const checksumFile = `${file}.sha256`;
37
+ let checksum;
38
+ try { checksum = readFileSync(checksumFile, "utf8").trim(); } catch {}
39
+ if (await validBinary(file, checksum)) return file;
40
+ const base = new URL(env.ZAPAGENT_DOWNLOAD_BASE_URL || "https://github.com/JackCaow/zapagent/releases/download/");
41
+ if (base.protocol !== "https:" && !(base.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(base.hostname))) {
42
+ throw new Error("Binary downloads require HTTPS (HTTP is allowed only for loopback tests)");
43
+ }
44
+ const url = `${base.href.replace(/\/$/, "")}/v${version}/${asset}`;
45
+ const fetcher = options.fetch ?? fetch;
46
+ async function download(address) {
47
+ const response = await fetcher(address, { signal: AbortSignal.timeout(180_000), redirect: "follow" });
48
+ if (!response.ok) throw new Error(`HTTP ${response.status} downloading ${address}`);
49
+ return response;
50
+ }
51
+ // Validate metadata before fetching executable bytes. Never run a partial download.
52
+ const metadata = await (await download(`${url}.sha256`)).text();
53
+ const match = metadata.trim().match(/^([a-fA-F0-9]{64})\s+\*?([^\r\n]+)$/);
54
+ if (!match || match[2] !== asset) throw new Error(`Invalid checksum metadata for ${asset}`);
55
+ checksum = match[1].toLowerCase();
56
+ const response = await download(url);
57
+ if (!response.body) throw new Error(`Empty binary response for ${asset}`);
58
+ mkdirSync(dirname(file), { recursive: true });
59
+ const pending = `${file}.${randomUUID()}.tmp`;
60
+ try {
61
+ const hash = createHash("sha256");
62
+ const meter = new Transform({ transform(bytes, _encoding, done) { hash.update(bytes); done(null, bytes); } });
63
+ await pipeline(Readable.fromWeb(response.body), meter, createWriteStream(pending, { flags: "wx", mode: 0o600 }));
64
+ if (hash.digest("hex") !== checksum) throw new Error(`Checksum verification failed for ${asset}`);
65
+ chmodSync(pending, 0o755);
66
+ try { renameSync(pending, file); } catch (error) {
67
+ // Concurrent installers may finish the same verified download on Windows.
68
+ if (!await validBinary(file, checksum)) throw error;
69
+ }
70
+ writeFileSync(checksumFile, `${checksum}\n`);
71
+ } finally { rmSync(pending, { force: true }); }
72
+ return file;
73
+ }
74
+ module.exports = { assets, target, digest, ensureBinary };
75
+ if (require.main === module) {
76
+ ensureBinary().catch(error => {
77
+ // npm/Bun --ignore-scripts and temporary network failures are recoverable at launch.
78
+ console.warn(`zapAgent binary setup deferred: ${error.message}\nRun zap to retry. No separate Bun installation is needed.`);
79
+ });
80
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zapagent",
3
- "version": "1.14.6",
3
+ "version": "1.14.8",
4
4
  "packageManager": "bun@1.3.14",
5
5
  "author": "",
6
6
  "main": "src/index.tsx",
@@ -67,7 +67,7 @@
67
67
  "zod": "4.6.7"
68
68
  },
69
69
  "bin": {
70
- "zap": "src/index.tsx"
70
+ "zap": "npm/cli.cjs"
71
71
  },
72
72
  "description": "Terminal-based AI coding agent for fast, agentic software development.",
73
73
  "repository": {
@@ -80,6 +80,7 @@
80
80
  },
81
81
  "files": [
82
82
  "src",
83
+ "npm",
83
84
  "zapsdk",
84
85
  "patches",
85
86
  "third_party/yoga-layout/LICENSE",
@@ -100,7 +101,7 @@
100
101
  ],
101
102
  "license": "MIT",
102
103
  "engines": {
103
- "bun": ">=1.3.0"
104
+ "node": ">=22"
104
105
  },
105
106
  "type": "module",
106
107
  "devDependencies": {
@@ -112,5 +113,8 @@
112
113
  "ink-spinner",
113
114
  "ink-text-input",
114
115
  "react"
115
- ]
116
+ ],
117
+ "scripts": {
118
+ "postinstall": "node npm/install.cjs"
119
+ }
116
120
  }
@@ -8,6 +8,7 @@ export interface ParserCtx {
8
8
  stepCounter: { value: number };
9
9
  textBlockId: string | null;
10
10
  finalText: string;
11
+ error?: string;
11
12
  startedEmitted: boolean;
12
13
  finishedEmitted: boolean;
13
14
  /** Captured from the first event that carries it:
@@ -326,6 +327,9 @@ export function parseCodexLine(line: string, ctx: ParserCtx): AgentEvent[] {
326
327
  case "turn.failed":
327
328
  case "thread.failed":
328
329
  case "error": {
330
+ const detail = o.error as { message?: unknown } | undefined;
331
+ const message = detail?.message ?? o.message;
332
+ if (typeof message === "string") ctx.error = message;
329
333
  const ev = emitFinished(ctx, "codex", false);
330
334
  if (ev) out.push(ev);
331
335
  return out;
@@ -1,10 +1,10 @@
1
1
  import { z } from "zod";
2
2
  import { currentRuntimeObservation, observeRuntime } from "../runtime/observation.js";
3
- import { existsSync, mkdirSync, lstatSync } from "node:fs";
3
+ import { existsSync, mkdirSync, lstatSync, symlinkSync, realpathSync } from "node:fs";
4
4
  import { createHash } from "node:crypto";
5
5
  import { execFileSync } from "node:child_process";
6
6
  import { homedir } from "node:os";
7
- import { join } from "node:path";
7
+ import { join, resolve } from "node:path";
8
8
  import type { Tool, ToolResult } from "../tools/types.js";
9
9
  import type { AgentEventHandler } from "../agent/events.js";
10
10
  import type { DetectedProvider } from "./delegate-detect.js";
@@ -19,6 +19,7 @@ import {
19
19
  diffSnapshots,
20
20
  formatChangeSummary,
21
21
  } from "./delegate-changes.js";
22
+ import { integrationGitWriteRoots } from "../execution/workspace-runtime.js";
22
23
  import { resolveToolPath, resolveToolPathCanonical } from "./filesystem.js";
23
24
  import { createLocalProcessBroker, terminateProcessTreeWithGrace } from "../execution/process.js";
24
25
 
@@ -52,11 +53,12 @@ export function buildCliArgs(
52
53
  args.push("-p", task);
53
54
  return args;
54
55
  }
55
- // codex
56
+ // Codex must preserve the broker environment: login profiles reset PATH and
57
+ // bypass the sandbox toolchain shims (notably Apple git/xcrun).
56
58
  if (resumeId) {
57
- return ["exec", "resume", "--dangerously-bypass-approvals-and-sandbox", "--json", resumeId, task];
59
+ return ["exec", "resume", "--dangerously-bypass-approvals-and-sandbox", "--config", "allow_login_shell=false", "--json", resumeId, task];
58
60
  }
59
- return ["exec", "--dangerously-bypass-approvals-and-sandbox", "--json", task];
61
+ return ["exec", "--dangerously-bypass-approvals-and-sandbox", "--config", "allow_login_shell=false", "--json", task];
60
62
  }
61
63
 
62
64
  function buildDescription(providers: DetectedProvider[]): string {
@@ -75,6 +77,7 @@ function buildDescription(providers: DetectedProvider[]): string {
75
77
  claudeBlurb,
76
78
  codexBlurb,
77
79
  "Returns a final report, git change summary, and resumable session id.",
80
+ "Sandbox temp is per-call; save reusable files in cwd.",
78
81
  ].filter(Boolean).join(" ");
79
82
  }
80
83
 
@@ -110,10 +113,11 @@ export function delegateAgentTool(opts: DelegateAgentOptions): Tool | null {
110
113
  opts.defaultCwd ?? context.cwd,
111
114
  );
112
115
  const provider = String(args.provider) as "claude" | "codex";
113
- const keychain = provider === "claude" ? macKeychainPaths() : undefined;
116
+ const keychain = macKeychainPaths();
114
117
  return {
115
118
  filesystem: [
116
119
  { kind: "filesystem", operation: "read", paths: [cwd] },
120
+ ...integrationGitWriteRoots(cwd).map(path => ({ kind: "filesystem" as const, operation: "modify" as const, paths: [path] })),
117
121
  ...delegateCredentialPaths(provider).map((path) => ({
118
122
  kind: "filesystem" as const,
119
123
  operation: "read" as const,
@@ -124,8 +128,8 @@ export function delegateAgentTool(opts: DelegateAgentOptions): Tool | null {
124
128
  { kind: "filesystem" as const, operation: "modify" as const, paths: [keychain.lock] },
125
129
  ] : []),
126
130
  { kind: "filesystem", operation: "modify", paths: [cwd] },
127
- ...(provider === "claude" ? [{ kind: "filesystem" as const, operation: "modify" as const,
128
- paths: [claudeStateDirectory(cwd, opts.stateDir)] }] : []),
131
+ { kind: "filesystem" as const, operation: "modify" as const,
132
+ paths: [delegateStateDirectory(provider, cwd, opts.stateDir)] },
129
133
  ],
130
134
  network: [{ kind: "network", operation: "connect", destinations: ["*"], methods: [] }],
131
135
  process: [{
@@ -181,22 +185,34 @@ export function delegateAgentTool(opts: DelegateAgentOptions): Tool | null {
181
185
  // Cancellation may arrive while the asynchronous workspace snapshot runs.
182
186
  if (signal?.aborted) return { success: false, output: "", error: "aborted" };
183
187
 
184
- let environment: Record<string, string> | undefined;
185
- if (provider === "claude") {
186
- const stateDir = claudeStateDirectory(resolveToolPathCanonical(cwd, cwd), opts.stateDir);
188
+ let environment: Record<string, string>;
189
+ {
190
+ const stateDir = delegateStateDirectory(provider, resolveToolPathCanonical(cwd, cwd), opts.stateDir);
187
191
  mkdirSync(stateDir, { recursive: true, mode: 0o700 });
188
192
  const state = lstatSync(stateDir);
189
- if (!state.isDirectory() || (state.mode & 0o077) !== 0) {
190
- return { success: false, output: "", error: "Claude delegate state must be a private directory (0700)." };
193
+ if (!state.isDirectory() || state.isSymbolicLink() || (state.mode & 0o077) !== 0) {
194
+ return { success: false, output: "", error: "Delegate state must be a private directory (0700)." };
191
195
  }
192
- environment = {
196
+ environment = provider === "claude" ? {
193
197
  CLAUDE_CONFIG_DIR: stateDir,
194
198
  // Keep the login/keychain namespace, but never make host settings or
195
199
  // credentials writable. Session/debug/cache writes use private state.
196
200
  // Empty selects Claude's default credential/keychain namespace;
197
201
  // a nonempty path hashes into a different, unauthenticated namespace.
198
202
  CLAUDE_SECURESTORAGE_CONFIG_DIR: "",
199
- };
203
+ } : { CODEX_HOME: stateDir };
204
+ if (provider === "codex") {
205
+ const host = codexHome();
206
+ for (const name of ["auth.json", "config.toml"]) {
207
+ const source = join(host, name), target = join(stateDir, name);
208
+ if (existsSync(source)) {
209
+ try { lstatSync(target); } catch (error) {
210
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
211
+ symlinkSync(realpathSync(source), target);
212
+ }
213
+ }
214
+ }
215
+ }
200
216
  }
201
217
 
202
218
  observeExternal("starting");
@@ -204,6 +220,9 @@ export function delegateAgentTool(opts: DelegateAgentOptions): Tool | null {
204
220
  try { child = processBroker.spawnCommand(detected.bin, cliArgs, {
205
221
  cwd,
206
222
  hostHome: true,
223
+ networkDomains: provider === "claude"
224
+ ? ["api.anthropic.com", "console.anthropic.com", "claude.ai", "*.claude.ai"]
225
+ : ["chatgpt.com", "*.chatgpt.com", "api.openai.com", "auth.openai.com", "*.oaiusercontent.com"],
207
226
  environment,
208
227
  temporaryDirectoryEnvironment: provider === "claude" ? ["CLAUDE_CODE_TMPDIR"] : undefined,
209
228
  preserveEnvironment: provider === "claude"
@@ -314,6 +333,7 @@ export function delegateAgentTool(opts: DelegateAgentOptions): Tool | null {
314
333
  // main agent has no way to learn what id to pass back next call.
315
334
  const sessionLine = ctx.sessionId
316
335
  ? `\n\n_Session resumable: pass \`resume_session_id="${ctx.sessionId}"\` (provider="${provider}") in your next delegate_agent call to continue this session._`
336
+ + (processBroker.sandboxedSpawnCount > 0 ? "\n_Sandbox temporary files were cleaned up at CLI exit; session resume does not restore TMPDIR files. Save reusable artifacts in cwd._" : "")
317
337
  : "";
318
338
 
319
339
  if (aborted) {
@@ -331,7 +351,7 @@ export function delegateAgentTool(opts: DelegateAgentOptions): Tool | null {
331
351
  return {
332
352
  success: false,
333
353
  output: "",
334
- error: `${provider} exited with code ${exitInfo.code}. stderr (last ${STDERR_TAIL_BYTES}B):\n${stderrTail}`,
354
+ error: `${provider} exited with code ${exitInfo.code}. ${ctx.error ? `${ctx.error}\n` : ""}stderr (last ${STDERR_TAIL_BYTES}B):\n${stderrTail}`,
335
355
  meta,
336
356
  };
337
357
  }
@@ -362,10 +382,23 @@ export function delegateAgentTool(opts: DelegateAgentOptions): Tool | null {
362
382
  };
363
383
  }
364
384
 
365
- function claudeStateDirectory(cwd: string, stateDir?: string): string {
385
+ function delegateStateDirectory(provider: "claude" | "codex", cwd: string, stateDir?: string): string {
366
386
  const root = stateDir ?? join(process.env.ZAPCODE_DATA_DIR || join(homedir(), ".zapcode"), "delegates");
367
- const workspaceId = createHash("sha256").update(cwd).digest("hex").slice(0, 24);
368
- return resolveToolPathCanonical(join(root, "claude", workspaceId), process.cwd());
387
+ const workspaceId = createHash("sha256").update(resolveToolPathCanonical(cwd, cwd)).digest("hex").slice(0, 24);
388
+ const target = resolve(root, provider, workspaceId);
389
+ // Do not canonicalize an existing state symlink into a new host write grant.
390
+ for (const path of [resolve(root), resolve(root, provider), target]) {
391
+ try {
392
+ const stat = lstatSync(path);
393
+ if (!stat.isDirectory() || stat.isSymbolicLink()
394
+ || (process.getuid && (stat.uid !== process.getuid() || (stat.mode & 0o077) !== 0))) {
395
+ throw new Error("Delegate state must be a private directory (0700).");
396
+ }
397
+ } catch (error) {
398
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
399
+ }
400
+ }
401
+ return resolveToolPathCanonical(target, process.cwd());
369
402
  }
370
403
 
371
404
  /** Security.framework reads its per-user MDS cache and locks mds.lock even
@@ -385,6 +418,8 @@ function delegateCredentialPaths(provider: "claude" | "codex"): string[] {
385
418
  const home = homedir();
386
419
  const candidates = provider === "claude"
387
420
  ? [join(home, ".claude"), join(home, ".claude.json"), join(home, ".config", "claude")]
388
- : [join(home, ".codex"), join(home, ".config", "codex")];
421
+ : [codexHome(), join(home, ".config", "codex")];
389
422
  return candidates.filter(existsSync);
390
423
  }
424
+
425
+ function codexHome(): string { return process.env.CODEX_HOME || join(homedir(), ".codex"); }
@@ -202,7 +202,12 @@ export class DefaultExecutionBroker implements ExecutionBroker {
202
202
  if (signal?.aborted) return reject("aborted", "CANCELLED");
203
203
  sandbox = needsProcessSandbox && !unsandboxed && sandboxStatus.available
204
204
  ? this.sandbox.createContext({ executionId: request.executionId,
205
- workspace: request.workspace, effects: request.effects, grant: request.grant })
205
+ workspace: request.workspace, effects: request.effects, grant: request.grant,
206
+ externalCliIntegration: request.tool.definition.name === "delegate_agent"
207
+ && request.tool.definition.executionLocation === "host"
208
+ && request.workspace.mode !== "shared-readonly"
209
+ && request.effects.workspace.mode === "root-integration"
210
+ && request.effects.process.some(effect => effect.commandClass === "external-cli") })
206
211
  : undefined;
207
212
  processBroker = needsProcessSandbox
208
213
  ? this.processBrokerFactory?.({ request, sandbox, signal: executionAbort.signal, limits })
@@ -92,6 +92,19 @@ export class NetworkProxy {
92
92
  * Concurrent commands must never inherit one another's denial evidence. */
93
93
  fork(): NetworkProxy { return new NetworkProxy(this.policy); }
94
94
 
95
+ /** Only trusted adapters may extend a command-owned listener. */
96
+ private readonly additionalDomains = new Set<string>();
97
+ allowDomains(domains: string[]): void {
98
+ for (const domain of domains) {
99
+ if (/^(?:\*\.)?[a-z0-9][a-z0-9.-]*$/i.test(domain)) this.additionalDomains.add(domain);
100
+ }
101
+ }
102
+
103
+ decideHost(host: string): ReturnType<typeof decideHost> {
104
+ const policy = this.policy();
105
+ return decideHost({ ...policy, allowedDomains: [...policy.allowedDomains, ...this.additionalDomains] }, host);
106
+ }
107
+
95
108
  close(): void {
96
109
  this.server.close();
97
110
  for (const socket of this.sockets) socket.destroy();
@@ -142,7 +155,7 @@ export class NetworkProxy {
142
155
  const headers = lines.slice(1).filter((line) => !/^(proxy-connection|connection|proxy-authorization):/i.test(line));
143
156
  forwardHead = [`${method} ${url.pathname}${url.search} HTTP/1.1`, ...headers, "Connection: close"].join("\r\n") + "\r\n\r\n";
144
157
  }
145
- const decision = decideHost(this.policy(), host);
158
+ const decision = this.decideHost(host);
146
159
  if (!decision.allowed) {
147
160
  const key = normalizeHost(host);
148
161
  if (!this.blocked.has(key)) this.blocked.set(key, decision.reason);
@@ -110,9 +110,11 @@ abstract class CommandWrappingSandbox implements OsSandbox {
110
110
  dirname(canonicalPath(process.execPath)),
111
111
  ].map((path) => canonicalPath(resolve(input.workspace.root, path))))];
112
112
  const networkAllowed = (input.grant.network?.destinations.length ?? 0) > 0;
113
+ const integrationGit = input.externalCliIntegration
114
+ && input.grant.filesystem?.write.some(path => canonicalPath(path) === canonicalPath(join(input.workspace.root, ".git")));
113
115
  const protectedPaths = [".git", ".zapcode"]
114
116
  .map((name) => canonicalPath(resolve(input.workspace.root, name)))
115
- .filter((path) => path !== privateGit);
117
+ .filter((path) => path !== privateGit && !(integrationGit && path === canonicalPath(join(input.workspace.root, ".git"))));
116
118
  const provider = status.provider;
117
119
  const prepare = (
118
120
  executable: string,
@@ -133,6 +135,7 @@ abstract class CommandWrappingSandbox implements OsSandbox {
133
135
  operationFailure("BACKEND_UNAVAILABLE", "backend", input.executionId));
134
136
  }
135
137
  }
138
+ if (input.externalCliIntegration) proxy?.allowDomains(options.networkDomains ?? []);
136
139
  wrapped = this.wrap(executable, args, {
137
140
  cwd: canonicalPath(resolve(options.cwd)),
138
141
  readablePaths: [...new Set([
@@ -523,6 +526,9 @@ function sandboxEnvironment(
523
526
  Object.assign(env, options.environment);
524
527
  for (const key of options.temporaryDirectoryEnvironment ?? []) env[key] = tempDir;
525
528
  env.HOME = options.hostHome ? homedir() : tempDir;
529
+ // Authenticated CLIs use explicit credential paths, not implicit host XDG
530
+ // settings (Git otherwise probes ~/.config/git/ignore outside its grant).
531
+ if (options.hostHome) env.XDG_CONFIG_HOME = join(tempDir, "config");
526
532
  env.TMPDIR = tempDir;
527
533
  env.TMP = tempDir;
528
534
  env.TEMP = tempDir;
@@ -534,6 +540,8 @@ function sandboxEnvironment(
534
540
  : [join(env.HOME!, ".local", "bin"), join(env.HOME!, ".cargo", "bin"), join(env.HOME!, ".bun", "bin")];
535
541
  env.PATH = [...bins, ...(env.PATH ? [env.PATH] : [])].join(delimiter);
536
542
  }
543
+ // zsh uses TMPPREFIX rather than TMPDIR for heredoc temporary files.
544
+ env.TMPPREFIX = join(env.TMPDIR!, "zsh");
537
545
  env.GIT_CONFIG_GLOBAL = "/dev/null";
538
546
  if (proxyUrl) {
539
547
  for (const name of ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"]) env[name] = proxyUrl;
@@ -45,6 +45,8 @@ export interface SandboxCommandOptions {
45
45
  environment?: Record<string, string>;
46
46
  /** Adapter-specific aliases for the broker's private per-command temp dir. */
47
47
  temporaryDirectoryEnvironment?: string[];
48
+ /** Trusted adapter endpoints, scoped to this command; explicit host denials still win. */
49
+ networkDomains?: string[];
48
50
  }
49
51
 
50
52
  export interface SandboxExecutionContext {
@@ -90,6 +92,8 @@ export interface OsSandbox {
90
92
  status(): SandboxStatus;
91
93
  createContext(input: {
92
94
  executionId: string;
95
+ /** Broker-authorized external CLI integration, never derived from shell arguments. */
96
+ externalCliIntegration?: boolean;
93
97
  workspace: WorkspaceIdentity;
94
98
  effects: ToolEffects;
95
99
  grant: CapabilityGrant;
@@ -146,3 +146,20 @@ export function workspaceRuntimeEnvironment(root: string, temp: string): Record<
146
146
  }
147
147
  return env;
148
148
  }
149
+
150
+ /** Explicit Git integration roots for an approved external CLI. Never follow
151
+ * arbitrary .git pointers; linked worktrees must pass the reciprocal checks. */
152
+ export function integrationGitWriteRoots(workspace: string): string[] {
153
+ const root = realpathSync(workspace);
154
+ const entry = join(root, ".git");
155
+ try {
156
+ const stat = lstatSync(entry);
157
+ if (stat.isDirectory() && !stat.isSymbolicLink()) return [entry];
158
+ const [gitDir, common] = linkedWorktreeReadRoots(root);
159
+ if (!gitDir || !common) return [];
160
+ return [gitDir, ...["objects", "refs", "logs"].map(name => join(common, name)).filter(path => {
161
+ try { const stat = lstatSync(path); return stat.isDirectory() && !stat.isSymbolicLink() && realpathSync(path) === path; }
162
+ catch { return false; }
163
+ })];
164
+ } catch { return []; }
165
+ }