zapagent 1.14.7 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zapagent",
3
- "version": "1.14.7",
3
+ "version": "1.14.8",
4
4
  "packageManager": "bun@1.3.14",
5
5
  "author": "",
6
6
  "main": "src/index.tsx",
@@ -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
+ }