zapagent 1.14.25 → 1.14.27

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.
Files changed (56) hide show
  1. package/LICENSE +2 -3
  2. package/README.md +3 -3
  3. package/README.zh-CN.md +3 -3
  4. package/SECURITY.md +3 -2
  5. package/THIRD_PARTY_NOTICES.md +4 -8
  6. package/bundled-dependencies.json +204 -204
  7. package/package.json +1 -1
  8. package/src/App.tsx +19 -6
  9. package/src/agent/contextAttachments.ts +4 -2
  10. package/src/agent/remote-agent.ts +150 -0
  11. package/src/agent/remote-turn.ts +72 -0
  12. package/src/agent/wireRunHandlers.ts +5 -2
  13. package/src/agent-factory.ts +20 -11
  14. package/src/approval-facts.ts +20 -3
  15. package/src/commands/dispatcher.ts +47 -3
  16. package/src/commands.ts +4 -0
  17. package/src/config.ts +13 -2
  18. package/src/execution-environment.ts +20 -2
  19. package/src/goal-command.ts +6 -3
  20. package/src/goal-session.ts +1 -1
  21. package/src/goal-turn.ts +1 -1
  22. package/src/headless/goalPhase.ts +3 -3
  23. package/src/headless/runHeadless.ts +6 -6
  24. package/src/hooks/useAgentObjects.ts +8 -0
  25. package/src/hooks/useAgentRunner.ts +50 -1
  26. package/src/permission-policy.ts +5 -2
  27. package/src/permissions.ts +19 -12
  28. package/src/singletons.ts +25 -17
  29. package/src/tool-grants.ts +2 -2
  30. package/src/ui/Transcript.tsx +2 -1
  31. package/src/ui/dialog-approval.tsx +1 -1
  32. package/src/ui/dialog-rewind.tsx +1 -1
  33. package/src/ui/dialog-tool-grant.tsx +2 -2
  34. package/src/ui/footer.tsx +4 -1
  35. package/src/ui/group-logs.ts +1 -1
  36. package/src/ui/live-activity.tsx +1 -1
  37. package/src/ui/slash-palette.tsx +1 -0
  38. package/src/ui/transcript-format.ts +5 -1
  39. package/zapsdk/acp-client/connection.ts +228 -0
  40. package/zapsdk/acp-client/detect.ts +28 -0
  41. package/zapsdk/acp-client/event-mapper.ts +231 -0
  42. package/zapsdk/acp-client/host-handlers.ts +225 -0
  43. package/zapsdk/acp-client/index.ts +6 -0
  44. package/zapsdk/acp-client/run.ts +169 -0
  45. package/zapsdk/acp-client/types.ts +52 -0
  46. package/zapsdk/agent/loop.ts +51 -4
  47. package/zapsdk/agent/tool-execution-guards.ts +23 -37
  48. package/zapsdk/builtin-tools/acp-agent.ts +188 -0
  49. package/zapsdk/builtin-tools/delegate-detect.ts +1 -1
  50. package/zapsdk/builtin-tools/index.ts +20 -16
  51. package/zapsdk/builtin-tools/plan-mode.ts +1 -1
  52. package/zapsdk/builtin-tools/subagent.ts +2 -2
  53. package/zapsdk/execution/process.ts +1 -1
  54. package/zapsdk/execution/sandbox.ts +6 -4
  55. package/zapsdk/execution/types.ts +3 -0
  56. package/zapsdk/goal/git-history-snapshot.ts +3 -1
@@ -0,0 +1,188 @@
1
+ import { z } from "zod";
2
+ import { relative } from "node:path";
3
+ import type { Tool, ToolResult } from "../tools/types.js";
4
+ import type { AgentEventHandler } from "../agent/events.js";
5
+ import type { ApprovalCallback } from "../tools/executor.js";
6
+ import { createLocalProcessBroker } from "../execution/process.js";
7
+ import { integrationGitWriteRoots } from "../execution/workspace-runtime.js";
8
+ import { currentRuntimeObservation, observeRuntime } from "../runtime/observation.js";
9
+ import { resolveToolPath, resolveToolPathCanonical } from "./filesystem.js";
10
+ import { diffSnapshots, formatChangeSummary, gitStatusSnapshot } from "./delegate-changes.js";
11
+ import { stdioTransport, type AcpTransport } from "../acp-client/connection.js";
12
+ import { createAcpHostHandlers } from "../acp-client/host-handlers.js";
13
+ import { runAcpTask, type AcpTaskResult } from "../acp-client/run.js";
14
+ import { AcpClientError, type AcpAgentSpec } from "../acp-client/types.js";
15
+
16
+ export interface AcpAgentToolOptions {
17
+ agents: AcpAgentSpec[];
18
+ onEvent?: AgentEventHandler;
19
+ defaultCwd?: string;
20
+ /** Zap's approval gate for the agent's permission and fs requests. */
21
+ approve?: ApprovalCallback;
22
+ /** Checkpoint hook for writes the agent makes through fs/write_text_file. */
23
+ trackEdit?: (paths: string[]) => Promise<unknown>;
24
+ /** Default 1_200_000 (20 min). */
25
+ timeoutMs?: number;
26
+ clientVersion?: string;
27
+ /** Tests inject an in-process agent instead of spawning. */
28
+ transportFactory?: (spec: AcpAgentSpec, cwd: string) => AcpTransport;
29
+ }
30
+
31
+ const TASK_MAX_CHARS = 100_000;
32
+
33
+ export const ACP_AGENT_TOOL = "acp_agent";
34
+
35
+ export function acpAgentTool(opts: AcpAgentToolOptions): Tool | null {
36
+ if (!opts.agents.length) return null;
37
+ const ids = opts.agents.map(agent => agent.id) as [string, ...string[]];
38
+ const byId = new Map(opts.agents.map(agent => [agent.id, agent]));
39
+ const defaultTimeout = opts.timeoutMs ?? 1_200_000;
40
+ const maxTimeout = Math.max(defaultTimeout, ...opts.agents.map(agent => agent.timeoutMs ?? 0));
41
+
42
+ return {
43
+ definition: {
44
+ name: ACP_AGENT_TOOL,
45
+ checkpointTracking: "unsupported",
46
+ description: [
47
+ "Hand a task to an external coding agent over the Agent Client Protocol and return its report.",
48
+ `Available: ${opts.agents.map(agent => `\`${agent.id}\`${agent.description ? ` (${agent.description})` : ""}`).join(", ")}.`,
49
+ "Use for self-contained work that benefits from a different agent; work directly for small edits.",
50
+ "The agent's file reads, writes and permission requests go through zap's approvals.",
51
+ "Returns the agent's final message, files changed, and a session id for follow-ups.",
52
+ ].join(" "),
53
+ parameters: z.object({
54
+ agent: z.enum(ids),
55
+ task: z.string().describe("Goal, relevant context, and expected deliverable. For a follow-up in an existing session, only the new instruction."),
56
+ cwd: z.string().optional().describe("Working directory. Defaults to zap's cwd."),
57
+ session_id: z.string().optional().describe("Session id from a prior acp_agent result with the same agent, to continue that conversation."),
58
+ mode: z.string().optional().describe("Agent session mode id, when the agent offers modes."),
59
+ }),
60
+ permission: "confirm",
61
+ timeoutMs: maxTimeout + 30_000,
62
+ sandboxAware: true,
63
+ executionLocation: "host",
64
+ resolveEffects: (args, context) => {
65
+ const base = opts.defaultCwd ?? context.cwd;
66
+ const cwd = resolveToolPathCanonical((args.cwd as string | undefined) ?? base, base);
67
+ return {
68
+ filesystem: [
69
+ { kind: "filesystem", operation: "read", paths: [cwd] },
70
+ { kind: "filesystem", operation: "modify", paths: [cwd] },
71
+ ...integrationGitWriteRoots(cwd).map(path => ({ kind: "filesystem" as const, operation: "modify" as const, paths: [path] })),
72
+ ],
73
+ network: [{ kind: "network", operation: "connect", destinations: ["*"], methods: [] }],
74
+ // External agents keep their own state, credentials and endpoints;
75
+ // they run on the host like an approved unsandboxed command. Their
76
+ // fs and permission requests still pass through zap.
77
+ process: [{ kind: "process", operation: "spawn", commandClass: "acp-agent", background: false, unsandboxed: true }],
78
+ external: [],
79
+ workspace: { mode: "root-integration" },
80
+ confidence: "declared",
81
+ };
82
+ },
83
+ },
84
+
85
+ handler: async (args, signal, context): Promise<ToolResult> => {
86
+ const spec = byId.get(String(args.agent));
87
+ if (!spec) return { success: false, output: "", error: `ACP agent ${String(args.agent)} is not configured.` };
88
+ const task = String(args.task ?? "");
89
+ if (!task.trim()) return { success: false, output: "", error: "task is empty" };
90
+ if (task.length > TASK_MAX_CHARS) {
91
+ return { success: false, output: "", error: `Task is too long (${task.length} chars > ${TASK_MAX_CHARS}). Put details in files under cwd and reference them.` };
92
+ }
93
+ const base = opts.defaultCwd ?? process.cwd();
94
+ const cwd = resolveToolPathCanonical(resolveToolPath((args.cwd as string | undefined) ?? base, base), base);
95
+ const timeoutMs = spec.timeoutMs ?? defaultTimeout;
96
+
97
+ const subagentId = `acp_${spec.id}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6).padEnd(4, "0")}`;
98
+ const observation = currentRuntimeObservation();
99
+ const observe = (phase: "starting" | "running" | "failed" | "cancelled" | "exited") => {
100
+ if (observation) observeRuntime({ kind: "external_run", scope: observation.scope, childRunId: subagentId,
101
+ toolCallId: context?.toolCallId, step: context?.step, phase, at: Date.now() }, observation);
102
+ };
103
+
104
+ const processBroker = context?.process ?? createLocalProcessBroker(signal);
105
+ const before = await gitStatusSnapshot(cwd, processBroker);
106
+ if (signal?.aborted) return { success: false, output: "", error: "aborted" };
107
+
108
+ const controller = new AbortController();
109
+ const onAbort = () => controller.abort(signal?.reason);
110
+ signal?.addEventListener("abort", onAbort, { once: true });
111
+ let timedOut = false;
112
+ const timer = setTimeout(() => { timedOut = true; controller.abort(new Error("timeout")); }, timeoutMs);
113
+ timer.unref?.();
114
+
115
+ const handlers = createAcpHostHandlers({ agentId: spec.id, cwd, approve: opts.approve,
116
+ trackEdit: opts.trackEdit, signal: controller.signal });
117
+ opts.onEvent?.({ type: "sub_agent_started", subagentId, agentType: spec.id, task, path: [] });
118
+ observe("starting");
119
+
120
+ let result: AcpTaskResult | undefined;
121
+ let failure: unknown;
122
+ const startedAt = Date.now();
123
+ try {
124
+ const transport = opts.transportFactory?.(spec, cwd) ?? stdioTransport(processBroker.spawnCommand(spec.command, spec.args ?? [], {
125
+ cwd, hostHome: true, environment: spec.env, stdin: "pipe",
126
+ }));
127
+ observe("running");
128
+ result = await runAcpTask({
129
+ spec, task, cwd, transport, handlers,
130
+ sessionId: (args.session_id as string | undefined)?.trim() || undefined,
131
+ mode: (args.mode as string | undefined)?.trim() || undefined,
132
+ path: [subagentId],
133
+ onEvent: opts.onEvent,
134
+ signal: controller.signal,
135
+ clientVersion: opts.clientVersion,
136
+ });
137
+ } catch (error) {
138
+ failure = error;
139
+ } finally {
140
+ clearTimeout(timer);
141
+ signal?.removeEventListener("abort", onAbort);
142
+ }
143
+
144
+ const aborted = !!signal?.aborted;
145
+ const after = await gitStatusSnapshot(cwd, processBroker);
146
+ const changes = diffSnapshots(before, after);
147
+ // A timeout or abort the agent honoured still returns a result with
148
+ // stopReason "cancelled"; that is not a completed task.
149
+ const success = !!result && !failure && !aborted && !timedOut
150
+ && result.stopReason !== "refusal" && result.stopReason !== "cancelled";
151
+ observe(aborted ? "cancelled" : success ? "exited" : "failed");
152
+ opts.onEvent?.({ type: "sub_agent_finished", subagentId, agentType: spec.id, success,
153
+ usage: result?.usage, steps: result?.toolCalls, path: [] });
154
+
155
+ const changeText = changes ? formatChangeSummary(spec.id, cwd, changes) : "";
156
+ // subagentId links this row to its nested agent rows in the transcript.
157
+ const meta = { subagentId, agent: spec.id, agentName: result?.agentName, durationMs: Date.now() - startedAt,
158
+ sessionId: result?.sessionId, resumed: result?.resumed, stopReason: result?.stopReason, usage: result?.usage,
159
+ changes, written: [...handlers.written], permissions: handlers.decisions, warnings: result?.warnings };
160
+
161
+ if (!result) {
162
+ const reason = aborted ? "aborted"
163
+ : timedOut ? `${spec.id} timed out after ${Math.round(timeoutMs / 1000)}s`
164
+ : `${spec.id} failed: ${failure instanceof Error ? failure.message : String(failure)}`
165
+ + (failure instanceof AcpClientError && failure.code === "auth_required"
166
+ ? `\nThe agent reported an authentication problem; sign in with its own CLI (\`${spec.command}\`) if needed.` : "");
167
+ return { success: false, output: changeText, error: reason, meta };
168
+ }
169
+
170
+ const sections: string[] = [result.report || "_(The agent ended its turn without a message.)_"];
171
+ if (result.stopReason !== "end_turn") sections.push(`_Stop reason: ${result.stopReason}_`);
172
+ const notes: string[] = [];
173
+ if (handlers.written.size) notes.push(`Written through zap: ${[...handlers.written].map(path => relative(cwd, path) || path).join(", ")}`);
174
+ const denied = handlers.decisions.filter(decision => !decision.allowed);
175
+ if (denied.length) notes.push(`Denied by zap: ${denied.map(decision => decision.title).join("; ")}`);
176
+ if (result.warnings.length) notes.push(`Setup warnings: ${result.warnings.join("; ")}`);
177
+ if (spec.selfGoverned && changeText) notes.push(`${spec.id} edits files directly; zap checkpoints do not cover those changes.`);
178
+ if (changeText) sections.push(`---\n${changeText}`);
179
+ if (notes.length) sections.push(notes.map(note => `_${note}_`).join("\n"));
180
+ if (result.resumable) sections.push(`_Session: pass \`session_id="${result.sessionId}"\` with agent="${spec.id}" to continue._`);
181
+ const error = success ? undefined
182
+ : timedOut ? `${spec.id} timed out after ${Math.round(timeoutMs / 1000)}s; partial report above.`
183
+ : aborted ? "aborted"
184
+ : `stop reason: ${result.stopReason}`;
185
+ return { success, output: sections.join("\n\n"), error, meta };
186
+ },
187
+ };
188
+ }
@@ -12,7 +12,7 @@ export interface DetectProvidersOptions {
12
12
  pathEnv?: string;
13
13
  }
14
14
 
15
- async function which(name: string, pathEnv = process.env.PATH ?? ""): Promise<string | null> {
15
+ export async function which(name: string, pathEnv = process.env.PATH ?? ""): Promise<string | null> {
16
16
  if (isAbsolute(name)) {
17
17
  return await isExecutable(name) ? name : null;
18
18
  }
@@ -3,32 +3,30 @@ import {
3
3
  readFileTool,
4
4
  writeFileTool,
5
5
  deleteFileTool,
6
- moveFileTool,
7
6
  type ReadFileOptions,
8
7
  type WriteFileOptions,
9
8
  type DeleteFileOptions,
10
- type MoveFileOptions,
11
9
  } from "./filesystem.js";
12
10
  import { editFileTool, type EditFileOptions } from "./edit.js";
13
11
  import { multiEditTool, type MultiEditOptions } from "./multi-edit.js";
14
12
  import { listTreeTool, type ListTreeOptions } from "./list-tree.js";
15
13
  import { executeCommandTool, type ExecuteCommandOptions } from "./command.js";
16
- import { httpFetchTool, httpRequestTool, type HttpFetchOptions } from "./http.js";
14
+ import { httpFetchTool, type HttpFetchOptions } from "./http.js";
17
15
  import { searchFilesTool, type SearchFilesOptions } from "./search.js";
18
16
  import { globFilesTool, type GlobFilesOptions } from "./glob.js";
19
17
  import { webSearchTool, type WebSearchOptions } from "./web-search.js";
20
- import { currentTimeTool } from "./time.js";
21
18
  import { readDocumentTool, readPdfTool, readDocxTool, type DocumentReadOptions } from "./document.js";
22
19
  import { todoWriteTool, type TodoWriteToolOptions, type TodoStore, type Todo, type TodoStatus } from "./todo.js";
23
20
  import { askUserQuestionTool, type AskUserToolOptions } from "./ask-user.js";
24
21
  import { generateImageTool, type GenerateImageOptions } from "./generate-image.js";
25
22
  import { browserScreenshotTool, type BrowserScreenshotOptions } from "./browser.js";
26
- import { enterPlanModeTool, exitPlanModeTool, type PlanModeToolsOptions, type PlanModeCallbacks } from "./plan-mode.js";
23
+ import { exitPlanModeTool, type PlanModeToolsOptions } from "./plan-mode.js";
27
24
  import { skillTool, type SkillToolOptions } from "./skill.js";
28
25
  import type { CronToolsHandle } from "./cron.js";
29
26
  import type { MonitorToolHandle } from "./monitor.js";
30
27
  import { taskStatusTool, taskStopTool, type TaskToolsOptions } from "./task.js";
31
28
  import { delegateAgentTool } from "./delegate.js";
29
+ import { acpAgentTool, type AcpAgentToolOptions } from "./acp-agent.js";
32
30
  import type { DetectedProvider } from "./delegate-detect.js";
33
31
  import type { AgentEventHandler } from "../agent/events.js";
34
32
 
@@ -81,6 +79,7 @@ export { taskStatusTool, taskStopTool, type TaskToolsOptions } from "./task.js";
81
79
  export { subagentTool, type SubagentToolOptions } from "./subagent.js";
82
80
 
83
81
  export { delegateAgentTool, type DelegateAgentOptions } from "./delegate.js";
82
+ export { acpAgentTool, ACP_AGENT_TOOL, type AcpAgentToolOptions } from "./acp-agent.js";
84
83
  export { detectProviders, type DetectedProvider } from "./delegate-detect.js";
85
84
  export { memoryMergeTool, memoryReviewTool, memorySaveTool, type MemoryMergeToolOptions, type MemoryReviewToolOptions, type MemorySaveToolOptions } from "./memory.js";
86
85
 
@@ -90,10 +89,8 @@ export interface BuiltinToolsOptions {
90
89
  editFile?: EditFileOptions;
91
90
  multiEdit?: MultiEditOptions;
92
91
  deleteFile?: DeleteFileOptions;
93
- moveFile?: MoveFileOptions;
94
92
  executeCommand?: ExecuteCommandOptions;
95
93
  httpFetch?: HttpFetchOptions;
96
- httpRequest?: HttpFetchOptions;
97
94
  searchFiles?: SearchFilesOptions;
98
95
  globFiles?: GlobFilesOptions;
99
96
  listTree?: ListTreeOptions;
@@ -106,8 +103,10 @@ export interface BuiltinToolsOptions {
106
103
  * subagent registries), `todo_write` is not registered — mirrors CCB's
107
104
  * "todos are main-agent-only" choice. */
108
105
  todoWrite?: TodoWriteToolOptions;
109
- /** Required for the main agent to get `enter_plan_mode` / `exit_plan_mode`.
110
- * Omit to skip registration (subagent registries don't manage plan mode). */
106
+ /** Required for the main agent to get `exit_plan_mode`. Omit to skip
107
+ * registration (subagent registries don't manage plan mode). Entering plan
108
+ * mode is a user action; register `enterPlanModeTool` explicitly to let the
109
+ * model request it. */
111
110
  planMode?: PlanModeToolsOptions;
112
111
  /** Main agent in an interactive UI only. Omit (headless, subagents) to leave
113
112
  * `ask_user_question` unregistered: nobody is there to answer. */
@@ -137,9 +136,15 @@ export interface BuiltinToolsOptions {
137
136
  timeoutMs?: number;
138
137
  stateDir?: string;
139
138
  };
139
+ /** External ACP agents. Absent or empty → `acp_agent` is not registered. */
140
+ acpAgent?: Omit<AcpAgentToolOptions, "defaultCwd">;
140
141
  exclude?: string[];
141
142
  }
142
143
 
144
+ /** Registers the core tool set. Specialized tools (`move_file`, `http_request`,
145
+ * `current_time`, `enter_plan_mode`, cron, monitor) remain exported for hosts
146
+ * that register them explicitly; each one the model sees costs prompt tokens
147
+ * on every request and widens its choice of tools. */
143
148
  export function createBuiltinRegistry(options: BuiltinToolsOptions = {}): ToolRegistry {
144
149
  const registry = new ToolRegistry();
145
150
  const exclude = new Set(options.exclude ?? []);
@@ -150,25 +155,19 @@ export function createBuiltinRegistry(options: BuiltinToolsOptions = {}): ToolRe
150
155
  if (!exclude.has("edit_file")) registry.register(editFileTool({ defaultCwd, ...options.editFile }));
151
156
  if (!exclude.has("multi_edit")) registry.register(multiEditTool({ defaultCwd, ...options.multiEdit }));
152
157
  if (!exclude.has("delete_file")) registry.register(deleteFileTool({ defaultCwd, ...options.deleteFile }));
153
- if (!exclude.has("move_file")) registry.register(moveFileTool({ defaultCwd, ...options.moveFile }));
154
158
  if (!exclude.has("list_tree")) registry.register(listTreeTool({ defaultCwd, ...options.listTree }));
155
159
  if (options.generateImage && !exclude.has("generate_image")) registry.register(generateImageTool({ defaultCwd, ...options.generateImage }));
156
160
  if (!exclude.has("bash")) registry.register(executeCommandTool(options.executeCommand));
157
161
  if (!exclude.has("http_fetch")) registry.register(httpFetchTool(options.httpFetch));
158
- if (!exclude.has("http_request")) registry.register(httpRequestTool(options.httpRequest));
159
162
  if (!exclude.has("search_files")) registry.register(searchFilesTool({ defaultCwd, ...options.searchFiles }));
160
163
  if (!exclude.has("glob_files")) registry.register(globFilesTool({ defaultCwd, ...options.globFiles }));
161
164
  if (!exclude.has("web_search")) registry.register(webSearchTool(options.webSearch));
162
- if (!exclude.has("current_time")) registry.register(currentTimeTool());
163
165
  if (!exclude.has("browser_screenshot")) registry.register(browserScreenshotTool({ defaultCwd, ...options.browserScreenshot }));
164
166
  if (!exclude.has("read_document")) registry.register(readDocumentTool({ defaultCwd, ...options.documentRead }));
165
167
  if (options.todoWrite && !exclude.has("todo_write")) {
166
168
  registry.register(todoWriteTool(options.todoWrite));
167
169
  }
168
- if (options.planMode) {
169
- if (!exclude.has("enter_plan_mode")) registry.register(enterPlanModeTool(options.planMode));
170
- if (!exclude.has("exit_plan_mode")) registry.register(exitPlanModeTool(options.planMode));
171
- }
170
+ if (options.planMode && !exclude.has("exit_plan_mode")) registry.register(exitPlanModeTool(options.planMode));
172
171
  if (options.askUser && !exclude.has("ask_user_question")) registry.register(askUserQuestionTool(options.askUser));
173
172
  if (options.skill && !exclude.has("skill")) {
174
173
  registry.register(skillTool(options.skill));
@@ -200,5 +199,10 @@ export function createBuiltinRegistry(options: BuiltinToolsOptions = {}): ToolRe
200
199
  if (tool) registry.register(tool);
201
200
  }
202
201
 
202
+ if (options.acpAgent && !exclude.has("acp_agent")) {
203
+ const tool = acpAgentTool({ ...options.acpAgent, defaultCwd: options.executeCommand?.defaultCwd });
204
+ if (tool) registry.register(tool);
205
+ }
206
+
203
207
  return registry;
204
208
  }
@@ -105,7 +105,7 @@ export function exitPlanModeTool(options: PlanModeToolsOptions): Tool {
105
105
  success: false,
106
106
  output: "",
107
107
  error:
108
- "Not in plan mode — nothing to exit. Call `enter_plan_mode` first if you want to design before implementing.",
108
+ "Not in plan mode — nothing to exit. Present the plan in your reply instead; the user enters plan mode with /mode plan.",
109
109
  };
110
110
  }
111
111
  const plan = args.plan as string;
@@ -282,12 +282,12 @@ export function readOnlyBashTool(defaultCwd?: string): Tool {
282
282
 
283
283
  const EXPLORE_TOOLS = new Set([
284
284
  "read_file", "glob_files", "search_files", "list_tree",
285
- "web_search", "http_fetch", "current_time", "bash",
285
+ "web_search", "http_fetch", "bash",
286
286
  ]);
287
287
 
288
288
  const PLAN_TOOLS = new Set([
289
289
  "read_file", "glob_files", "search_files", "list_tree",
290
- "web_search", "http_fetch", "current_time", "bash",
290
+ "web_search", "http_fetch", "bash",
291
291
  ]);
292
292
 
293
293
  type Thoroughness = "quick" | "medium" | "thorough";
@@ -88,7 +88,7 @@ export class DefaultExecutionProcessBroker implements ExecutionProcessBroker {
88
88
  detached: process.platform !== "win32",
89
89
  shell: false,
90
90
  });
91
- child.stdin?.end();
91
+ if (options.stdin !== "pipe") child.stdin?.end();
92
92
  } catch (error) {
93
93
  release?.();
94
94
  throw error;
@@ -1,7 +1,7 @@
1
1
  import { prepareRootGit } from "./root-git.js";
2
2
  import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, rmdirSync, writeFileSync } from "node:fs";
3
3
  import { homedir, tmpdir } from "node:os";
4
- import { delimiter, dirname, join, resolve } from "node:path";
4
+ import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
5
5
  import type {
6
6
  OsSandbox,
7
7
  SandboxCommandOptions,
@@ -132,7 +132,6 @@ abstract class CommandWrappingSandbox implements OsSandbox {
132
132
  ): SandboxedCommand => {
133
133
  mkdirSync(this.tempRoot, { recursive: true, mode: 0o700 });
134
134
  const tempDir = mkdtempSync(join(this.tempRoot, "run-"));
135
- const canonicalExecutable = canonicalPath(executable);
136
135
  let proxy: NetworkProxy | undefined;
137
136
  let wrapped: { executable: string; args: string[]; release?: () => void } | undefined;
138
137
  try {
@@ -150,7 +149,9 @@ abstract class CommandWrappingSandbox implements OsSandbox {
150
149
  cwd: canonicalPath(resolve(options.cwd)),
151
150
  readablePaths: [...new Set([
152
151
  ...readablePaths,
153
- dirname(canonicalExecutable),
152
+ // Bare commands resolve on the sandbox PATH. Only an explicit
153
+ // absolute executable needs an additional host directory mount.
154
+ ...(isAbsolute(executable) ? [dirname(canonicalPath(executable))] : []),
154
155
  canonicalPath(tempDir),
155
156
  ])],
156
157
  writablePaths,
@@ -376,9 +377,10 @@ function pathIsWithin(path: string, root: string): boolean {
376
377
  }
377
378
 
378
379
  function missingMountParents(path: string, systemRoots: string[]): string[] {
380
+ if (!isAbsolute(path)) throw new Error("Sandbox mount paths must be absolute");
379
381
  const parents: string[] = [];
380
382
  let current = dirname(path);
381
- while (current !== "/" && !systemRoots.some((root) => pathIsWithin(current, root))) {
383
+ while (dirname(current) !== current && !systemRoots.some((root) => pathIsWithin(current, root))) {
382
384
  parents.push(current);
383
385
  current = dirname(current);
384
386
  }
@@ -47,6 +47,9 @@ export interface SandboxCommandOptions {
47
47
  temporaryDirectoryEnvironment?: string[];
48
48
  /** Trusted adapter endpoints, scoped to this command; explicit host denials still win. */
49
49
  networkDomains?: string[];
50
+ /** "pipe" keeps the child's stdin writable for stdio protocols (ACP).
51
+ * Default closes it right after launch so commands observe EOF. */
52
+ stdin?: "close" | "pipe";
50
53
  }
51
54
 
52
55
  export interface SandboxExecutionContext {
@@ -199,7 +199,9 @@ export async function materializePrivateGitMetadata(repository: string, workspac
199
199
  await validate(repo);
200
200
  await mkdir(directory, { mode: 0o700 }); // exclusive: never replace a user's .git
201
201
  try {
202
- await cp(repo, directory, { recursive: true, force: false, errorOnExist: true, verbatimSymlinks: true });
202
+ for (const name of await readdir(repo)) {
203
+ await cp(join(repo, name), join(directory, name), { recursive: true, force: false, errorOnExist: true, verbatimSymlinks: true });
204
+ }
203
205
  await validate(directory);
204
206
  await writeFile(join(directory, "config"), "[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = false\n\tlogallrefupdates = true\n", { mode: 0o600 });
205
207
  await execute(git, directory, [`--git-dir=${directory}`, "read-tree", "HEAD"], deadline, undefined, undefined, undefined, directory);