zapagent 1.14.26 → 1.14.28

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 (53) 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 +187 -187
  7. package/package.json +1 -1
  8. package/src/App.tsx +19 -6
  9. package/src/agent/remote-agent.ts +150 -0
  10. package/src/agent/remote-turn.ts +72 -0
  11. package/src/agent/wireRunHandlers.ts +5 -2
  12. package/src/agent-factory.ts +19 -2
  13. package/src/approval-facts.ts +20 -3
  14. package/src/commands/dispatcher.ts +47 -3
  15. package/src/commands.ts +4 -0
  16. package/src/config.ts +13 -2
  17. package/src/execution-environment.ts +20 -2
  18. package/src/goal-command.ts +6 -3
  19. package/src/goal-session.ts +1 -1
  20. package/src/goal-turn.ts +1 -1
  21. package/src/headless/runHeadless.ts +2 -1
  22. package/src/hooks/useAgentObjects.ts +8 -0
  23. package/src/hooks/useAgentRunner.ts +50 -1
  24. package/src/permission-policy.ts +5 -2
  25. package/src/permissions.ts +19 -12
  26. package/src/singletons.ts +21 -3
  27. package/src/tool-grants.ts +2 -2
  28. package/src/ui/Transcript.tsx +2 -1
  29. package/src/ui/dialog-approval.tsx +1 -1
  30. package/src/ui/dialog-tool-grant.tsx +2 -2
  31. package/src/ui/footer.tsx +4 -1
  32. package/src/ui/group-logs.ts +1 -1
  33. package/src/ui/live-activity.tsx +1 -1
  34. package/src/ui/slash-palette.tsx +1 -0
  35. package/src/ui/transcript-format.ts +5 -1
  36. package/zapsdk/acp-client/connection.ts +228 -0
  37. package/zapsdk/acp-client/detect.ts +28 -0
  38. package/zapsdk/acp-client/event-mapper.ts +231 -0
  39. package/zapsdk/acp-client/host-handlers.ts +225 -0
  40. package/zapsdk/acp-client/index.ts +6 -0
  41. package/zapsdk/acp-client/run.ts +169 -0
  42. package/zapsdk/acp-client/types.ts +52 -0
  43. package/zapsdk/agent/loop.ts +3 -1
  44. package/zapsdk/agent/single-call.ts +4 -2
  45. package/zapsdk/builtin-tools/acp-agent.ts +188 -0
  46. package/zapsdk/builtin-tools/delegate-detect.ts +1 -1
  47. package/zapsdk/builtin-tools/index.ts +9 -0
  48. package/zapsdk/core/llm.ts +2 -0
  49. package/zapsdk/core/providers/openai-responses.ts +25 -7
  50. package/zapsdk/execution/process.ts +1 -1
  51. package/zapsdk/execution/sandbox.ts +6 -4
  52. package/zapsdk/execution/types.ts +3 -0
  53. 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
  }
@@ -26,6 +26,7 @@ import type { CronToolsHandle } from "./cron.js";
26
26
  import type { MonitorToolHandle } from "./monitor.js";
27
27
  import { taskStatusTool, taskStopTool, type TaskToolsOptions } from "./task.js";
28
28
  import { delegateAgentTool } from "./delegate.js";
29
+ import { acpAgentTool, type AcpAgentToolOptions } from "./acp-agent.js";
29
30
  import type { DetectedProvider } from "./delegate-detect.js";
30
31
  import type { AgentEventHandler } from "../agent/events.js";
31
32
 
@@ -78,6 +79,7 @@ export { taskStatusTool, taskStopTool, type TaskToolsOptions } from "./task.js";
78
79
  export { subagentTool, type SubagentToolOptions } from "./subagent.js";
79
80
 
80
81
  export { delegateAgentTool, type DelegateAgentOptions } from "./delegate.js";
82
+ export { acpAgentTool, ACP_AGENT_TOOL, type AcpAgentToolOptions } from "./acp-agent.js";
81
83
  export { detectProviders, type DetectedProvider } from "./delegate-detect.js";
82
84
  export { memoryMergeTool, memoryReviewTool, memorySaveTool, type MemoryMergeToolOptions, type MemoryReviewToolOptions, type MemorySaveToolOptions } from "./memory.js";
83
85
 
@@ -134,6 +136,8 @@ export interface BuiltinToolsOptions {
134
136
  timeoutMs?: number;
135
137
  stateDir?: string;
136
138
  };
139
+ /** External ACP agents. Absent or empty → `acp_agent` is not registered. */
140
+ acpAgent?: Omit<AcpAgentToolOptions, "defaultCwd">;
137
141
  exclude?: string[];
138
142
  }
139
143
 
@@ -195,5 +199,10 @@ export function createBuiltinRegistry(options: BuiltinToolsOptions = {}): ToolRe
195
199
  if (tool) registry.register(tool);
196
200
  }
197
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
+
198
207
  return registry;
199
208
  }
@@ -68,6 +68,8 @@ export interface LLMCallOptions {
68
68
  onRequestEvent?: (event: ProviderRequestEvent) => void;
69
69
  /** RetryProvider supplies this metadata to each adapter attempt. */
70
70
  requestAttempt?: { attempt: number; maxAttempts: number };
71
+ /** Conversation identity for providers with session-scoped prompt cache routing. */
72
+ sessionId?: string;
71
73
  /** Host-local logical request identity, shared by retry attempts. */
72
74
  requestId?: string;
73
75
  }
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  import OpenAI from "openai";
2
3
  import type { Response as APIResponse, ResponseInputItem, ResponseCreateParams } from "openai/resources/responses/responses";
3
4
  import type { LLMProvider, LLMCallOptions } from "../llm.js";
@@ -41,7 +42,7 @@ export class OpenAIResponsesProvider implements LLMProvider {
41
42
  setVisionSupported(supported: boolean): void { this.formatter.setVisionSupported(supported); }
42
43
  getImageTokenContext(options?: LLMCallOptions) { return this.formatter.getImageTokenContext(options); }
43
44
 
44
- private async requestClient(request: ProviderRequest): Promise<OpenAI> {
45
+ private async requestClient(request: ProviderRequest, sessionAffinity?: string): Promise<OpenAI> {
45
46
  const codex = this.options.codex;
46
47
  if (!codex) return this.client;
47
48
  const credentials = await request.wait(codex.getCredentials(request.signal));
@@ -49,6 +50,7 @@ export class OpenAIResponsesProvider implements LLMProvider {
49
50
  // OAuth tokens are never sent to a user-configurable endpoint/client.
50
51
  return new OpenAI({ baseURL: CODEX_RESPONSES_BASE_URL, apiKey: credentials.accessToken, maxRetries: 0,
51
52
  fetch: codex.fetch, defaultHeaders: { originator: "zap",
53
+ ...(sessionAffinity ? { "session-id": sessionAffinity } : {}),
52
54
  ...(credentials.accountId ? { "ChatGPT-Account-ID": credentials.accountId } : {}) } });
53
55
  }
54
56
 
@@ -121,7 +123,7 @@ export class OpenAIResponsesProvider implements LLMProvider {
121
123
  model: opts?.model ?? this.options.model,
122
124
  max_output_tokens: opts?.maxOutputTokens ?? this.options.maxTokens ?? 4096,
123
125
  ...extra,
124
- input: this.serializeMessages(messages),
126
+ input: [],
125
127
  tools: tools?.length ? [...tools].sort((a, b) => a.name.localeCompare(b.name)).map(tool => ({
126
128
  type: "function", name: tool.name, description: tool.description, strict: false,
127
129
  parameters: canonicalizeJsonSchema(tool.rawSchema ?? zodToJsonSchema(tool.parameters)),
@@ -142,13 +144,19 @@ export class OpenAIResponsesProvider implements LLMProvider {
142
144
  else delete body.reasoning;
143
145
  let leadingSystemEnd = 0;
144
146
  while (messages[leadingSystemEnd]?.role === "system") leadingSystemEnd++;
145
- body.instructions = messages.slice(0, leadingSystemEnd).map(message => stripBoundary(message.content)).join("\n\n");
146
- body.input = this.serializeMessages(messages.slice(leadingSystemEnd));
147
+ // GPT-6.2 renders top-level instructions after the cacheable input.
148
+ const instructions = messages.slice(0, leadingSystemEnd).map(message => stripBoundary(message.content)).join("\n\n");
149
+ const input = this.serializeMessages(messages.slice(leadingSystemEnd));
150
+ if (instructions) input.unshift({ role: "developer", content: instructions });
151
+ body.input = input;
152
+ body.instructions = "";
147
153
  // Codex requires SSE and rejects generation controls accepted by the API.
148
154
  delete body.max_output_tokens;
149
155
  delete body.temperature;
150
156
  delete body.top_p;
151
157
  body.stream = true;
158
+ } else {
159
+ body.input = this.serializeMessages(messages);
152
160
  }
153
161
  return body;
154
162
  }
@@ -183,12 +191,18 @@ export class OpenAIResponsesProvider implements LLMProvider {
183
191
  }
184
192
  const usage = response.usage;
185
193
  const cached = usage?.input_tokens_details?.cached_tokens;
194
+ const written = usage?.input_tokens_details?.cache_write_tokens;
186
195
  return {
187
196
  type: toolCalls.length ? "tool_call" : "text", text,
188
197
  toolCalls: toolCalls.length ? toolCalls : undefined,
189
198
  finishReason: truncated ? "length" : toolCalls.length ? "tool_calls" : "stop",
190
- usage: { inputTokens: Math.max(0, (usage?.input_tokens ?? 0) - (cached ?? 0)), outputTokens: usage?.output_tokens ?? 0,
191
- providerUsageReported: !!usage, ...(cached !== undefined ? { cacheReadInputTokens: cached } : {}) },
199
+ usage: {
200
+ inputTokens: Math.max(0, (usage?.input_tokens ?? 0) - (cached ?? 0) - (written ?? 0)),
201
+ outputTokens: usage?.output_tokens ?? 0,
202
+ providerUsageReported: !!usage,
203
+ ...(cached !== undefined ? { cacheReadInputTokens: cached } : {}),
204
+ ...(written !== undefined ? { cacheCreationInputTokens: written } : {}),
205
+ },
192
206
  raw: layout.length ? { openaiResponses: { items: layout } } : undefined,
193
207
  };
194
208
  }
@@ -237,8 +251,12 @@ export class OpenAIResponsesProvider implements LLMProvider {
237
251
 
238
252
  private async *streamResponse(messages: Message[], tools: ToolDefinition[] | undefined, opts: LLMCallOptions | undefined, request: ProviderRequest): AsyncIterable<LLMChunk> {
239
253
  const body = this.body(messages, tools, opts, true);
254
+ // Derive both routing fields from the same header-safe conversation identity.
255
+ const sessionAffinity = this.options.codex && opts?.sessionId
256
+ ? createHash("sha256").update(opts.sessionId).digest("hex") : undefined;
257
+ if (sessionAffinity && body.prompt_cache_key === undefined) body.prompt_cache_key = sessionAffinity;
240
258
  request.measureBody(body, this.options.maxRequestBytes, `responses:${this.options.codex ? CODEX_RESPONSES_BASE_URL : this.options.baseURL ?? this.options.client?.baseURL ?? "default"}`);
241
- const client = await this.requestClient(request);
259
+ const client = await this.requestClient(request, sessionAffinity);
242
260
  const stream = await request.wait(client.responses.create({ ...body, stream: true }, { signal: request.signal, maxRetries: 0 }));
243
261
  request.responseReceived();
244
262
  let emittedText = "";
@@ -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);