zapagent 1.14.9 → 1.14.10

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.9",
3
+ "version": "1.14.10",
4
4
  "packageManager": "bun@1.3.14",
5
5
  "author": "",
6
6
  "main": "src/index.tsx",
@@ -22,7 +22,7 @@ export interface ExecutionEnvironment {
22
22
  capacity?: ExecutionCapacityFacts
23
23
  // No prompt, model, retry, budget or completion policy is accepted here.
24
24
  commandOptions: Pick<ExecuteCommandOptions,
25
- "disableBackgroundTasks" | "restrictedNetwork" | "preserveEnvironment" | "allowUnsandboxed" | "sandboxNetwork" | "sandboxExcludedCommands">
25
+ "disableBackgroundTasks" | "restrictedNetwork" | "preserveEnvironment" | "allowUnsandboxed" | "sandboxNetwork" | "sandboxExcludedCommands" | "sandboxGitIntegration">
26
26
  }
27
27
 
28
28
  export type ExecutionBackend = "local" | "vm"
@@ -123,6 +123,7 @@ export function createExecutionEnvironment(
123
123
  const local = new DefaultExecutionBroker({
124
124
  services: serviceOwner,
125
125
  sandbox: createPlatformSandbox({
126
+ rootWorkspaceGitWrites: true,
126
127
  workspaceStateRoot: resident || installation || cloud ? undefined : join(getAppDataDir(), "sandbox", "workspaces"),
127
128
  // Trusted outer mounts/egress are enforcement details, not Agent policy.
128
129
  trustedWritablePaths: resident ? ["/nix"] : (installation || cloud ? [] : hostPackageWriteRoots()),
@@ -148,6 +149,7 @@ export function createExecutionEnvironment(
148
149
  vm: cloud ? createZapVmCloudExecutionBroker(cloud) : undefined,
149
150
  }),
150
151
  commandOptions: {
152
+ sandboxGitIntegration: hostSandboxed && sandboxMode !== "disabled" && local.sandboxStatus().available,
151
153
  // These transports cannot retain a detached child beyond its lease.
152
154
  // Other backends defer to the user's env setting instead of overriding it.
153
155
  disableBackgroundTasks: cloud !== undefined || resident ? true : undefined,
@@ -24,6 +24,8 @@ export interface ExecuteCommandOptions {
24
24
  * launch an interpreter; the execution broker owns that decision. */
25
25
  executionShell?: string;
26
26
  sandboxTemporaryDirectory?: ExecutionEnvironmentFacts["sandboxTemporaryDirectory"];
27
+ /** Host advertises its scoped, sandboxed root Git adapter. */
28
+ sandboxGitIntegration?: boolean;
27
29
  /** Inject a shared TaskStore to enable the `run_in_background:true`
28
30
  * flag. When omitted (or when `ZAPCODE_DISABLE_BACKGROUND_TASKS=1` is
29
31
  * set), background fields are stripped from the schema entirely — the
@@ -243,6 +245,9 @@ export function executeCommandTool(options: ExecuteCommandOptions = {}): Tool {
243
245
  "Exit 0 reports final shell status only. Inspect stderr for warnings or masked failures; do not auto-replay side effects. Chain dependencies with &&. Pipelines report the last stage: check stages or use supported pipefail. Use check_steps for independent checks; each uses a fresh shell and stops on nonzero.",
244
246
  "cwd selects the starting directory, not a narrower workspace. For external inputs/outputs declare read_paths/write_paths (relative to cwd); these need file authorization. A prior Read alone does not grant Bash access. Sandboxed .git/.zapcode remain read-only.",
245
247
  );
248
+ if (options.sandboxGitIntegration) {
249
+ promptLines.push("For root-repository Git writes, use standalone Bash calls: git add <paths>, git commit -m <message>, git stash push/pop, git rebase <ref>. The Host runs supported commands using trusted Git inside the OS sandbox. Do not combine them with &&, cd, redirects, -c/-C or interactive options. Arbitrary shell writes to .git remain blocked; unsupported or executable Git config retains the normal approval path.");
250
+ }
246
251
  if (options.sandboxTemporaryDirectory) {
247
252
  promptLines.push(
248
253
  `Local sandbox: expand ${options.sandboxTemporaryDirectory.environmentVariables.join(", ")} for a private writable scratch directory; avoid hard-coded /tmp or disposable project files.`,
@@ -0,0 +1,106 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, realpathSync, statSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { integrationGitWriteRoots } from "./workspace-runtime.js";
5
+
6
+ /** Deliberately smaller than shell syntax: never evaluate substitutions, chains,
7
+ * redirections or environment assignments with elevated Git metadata access. */
8
+ export function rootGitArguments(command: string): string[] | undefined {
9
+ if (/[\r\n$`\0]/.test(command)) return;
10
+ const words: string[] = [];
11
+ let word = "", quote = "", active = false;
12
+ for (let i = 0; i < command.length; i++) {
13
+ const ch = command[i]!;
14
+ if (quote) {
15
+ if (ch === quote) quote = "";
16
+ else if (ch === "\\" && quote === '"') {
17
+ const next = command[++i]; if (next === undefined || !['"', "\\"].includes(next)) return;
18
+ word += next;
19
+ } else word += ch;
20
+ } else if (ch === "'" || ch === '"') { quote = ch; active = true; }
21
+ else if (/\s/.test(ch)) { if (active) { words.push(word); word = ""; active = false; } }
22
+ else if (/[;&|<>()[\]{}*?!#\\]/.test(ch)) return;
23
+ else { word += ch; active = true; }
24
+ }
25
+ if (quote) return;
26
+ if (active) words.push(word);
27
+ if (words.shift() !== "git") return;
28
+ const op = words.shift();
29
+ if (!op || !["add", "commit", "stash", "rebase"].includes(op)) return;
30
+ const flags: Record<string, Set<string>> = {
31
+ add: new Set(["-A", "--all", "-u", "--update", "-f", "--force", "-v", "--verbose"]),
32
+ commit: new Set(["-a", "--all", "--amend", "--no-edit", "--allow-empty", "-q", "--quiet", "-v", "--verbose"]),
33
+ stash: new Set(["-u", "--include-untracked", "-a", "--all", "-k", "--keep-index", "-q", "--quiet", "--index"]),
34
+ rebase: new Set(["--onto", "--root", "--autostash", "--no-autostash", "-q", "--quiet", "-v", "--verbose"]),
35
+ };
36
+ let paths = false;
37
+ for (let i = 0; i < words.length; i++) {
38
+ const word = words[i]!;
39
+ if (word === "--" && op !== "rebase") { paths = true; continue; }
40
+ if (paths) continue;
41
+ if ((op === "commit" || op === "stash") && ["-m", "--message", ...(op === "commit" ? ["-am", "-ma", "-qm"] : [])].includes(word)) {
42
+ if (words[++i] === undefined) return;
43
+ continue;
44
+ }
45
+ if (word.startsWith("-")) { if (!flags[op]!.has(word)) return; }
46
+ else if (op === "rebase" && !/^[A-Za-z0-9_][A-Za-z0-9_./~^@{}-]*$/.test(word)) return;
47
+ }
48
+ if (op === "stash" && words[0] && !words[0].startsWith("-") && !["push", "pop", "apply", "drop", "list"].includes(words[0])) return;
49
+ // Never permit commit to enter an editor or rebase to consume an existing
50
+ // todo containing exec instructions. Fresh non-interactive rebase only.
51
+ if (op === "commit" && !words.some(word => ["-m", "--message", "-am", "-ma", "-qm", "--no-edit"].includes(word))) return;
52
+ if (op === "rebase" && !words.length) return;
53
+ return [op, ...words];
54
+ }
55
+
56
+ export function trustedGitExecutable(): string {
57
+ let path = process.platform === "win32" ? join(process.env.ProgramFiles ?? "C:\\Program Files", "Git", "cmd", "git.exe") : "/usr/bin/git";
58
+ if (process.platform === "darwin") path = execFileSync("/usr/bin/xcrun", ["--find", "git"], { encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] }).trim();
59
+ path = realpathSync(path);
60
+ const file = statSync(path);
61
+ if (!file.isFile() || (process.platform !== "win32" && (file.uid !== 0 || (file.mode & 0o022)))) throw new Error("Git integration requires a trusted system Git executable");
62
+ return path;
63
+ }
64
+
65
+ export function rootGitEnvironment(): NodeJS.ProcessEnv {
66
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^GIT_/i.test(key)));
67
+ const empty = process.platform === "win32" ? "NUL" : "/dev/null";
68
+ return { ...env, GIT_CONFIG_GLOBAL: empty, GIT_CONFIG_SYSTEM: empty, GIT_CONFIG_NOSYSTEM: "1", GIT_TERMINAL_PROMPT: "0" };
69
+ }
70
+
71
+ /** No Git helper may execute arbitrary code while Git metadata is writable.
72
+ * Fail back to the ordinary sandbox for unsupported/executable repository config. */
73
+ export function prepareRootGit(command: string, workspace: string, cwd: string): { executable: string; args: string[]; environment: NodeJS.ProcessEnv } | undefined {
74
+ const args = rootGitArguments(command);
75
+ if (!args) return;
76
+ const roots = integrationGitWriteRoots(workspace);
77
+ if (!roots.length) return;
78
+ const metadata = roots[0]!;
79
+ if (["rebase-merge", "rebase-apply", "sequencer"].some(name => existsSync(join(metadata, name)))) return;
80
+ // Nested repositories are not implicitly the authorized root repository.
81
+ const executable = trustedGitExecutable();
82
+ const environment = rootGitEnvironment();
83
+ const top = execFileSync(executable, ["rev-parse", "--show-toplevel"], { cwd, env: environment, encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] }).trim();
84
+ if (realpathSync(top) !== realpathSync(workspace)) return;
85
+ const keys = execFileSync(executable, ["config", "--local", "--no-includes", "--null", "--name-only", "--list"], { cwd, env: environment, encoding: "utf8", timeout: 3000, maxBuffer: 64 * 1024, stdio: ["ignore", "pipe", "ignore"] }).split("\0").filter(Boolean);
86
+ const safe = /^(?:core\.(?:repositoryformatversion|filemode|bare|logallrefupdates|ignorecase|precomposeunicode|quotepath|autocrlf|safecrlf|symlinks|abbrev|hookspath|fsmonitor|editor)|user\.(?:name|email)|remote\..+\.(?:url|fetch|pushurl|glab-resolved-head)|branch\..+\.(?:remote|merge|rebase|vscode-merge-base)|commit\.gpgsign|tag\.gpgsign|extensions\.objectformat)$/i;
87
+ if (keys.some(key => !safe.test(key))) return;
88
+ // Preserve identity without loading executable global config into the Git
89
+ // sandbox. Git config queries do not execute hooks, aliases or helpers.
90
+ for (const field of ["name", "email"] as const) {
91
+ let fallback: string | undefined;
92
+ if (!keys.some(key => key.toLowerCase() === `user.${field}`)) {
93
+ const host = { ...environment };
94
+ delete host.GIT_CONFIG_GLOBAL;
95
+ try { fallback = execFileSync(executable, ["config", "--global", "--null", "--get", `user.${field}`], { cwd, env: host, encoding: "utf8", timeout: 3000, maxBuffer: 8192, stdio: ["ignore", "pipe", "ignore"] }).replace(/\0$/, ""); }
96
+ catch { /* Git reports a missing identity normally if none is configured. */ }
97
+ }
98
+ for (const role of ["AUTHOR", "COMMITTER"]) {
99
+ const key = `GIT_${role}_${field.toUpperCase()}`;
100
+ const value = process.env[key] ?? fallback;
101
+ if (value !== undefined) environment[key] = value;
102
+ }
103
+ }
104
+ const empty = process.platform === "win32" ? "NUL" : "/dev/null";
105
+ return { executable, environment, args: ["--no-pager", "-c", `core.hooksPath=${empty}`, "-c", "core.fsmonitor=false", "-c", "commit.gpgsign=false", "-c", "tag.gpgsign=false", "-c", "core.editor=false", "-c", "sequence.editor=false", "-c", "submodule.recurse=false", "-c", "rebase.backend=apply", ...args] };
106
+ }
@@ -1,3 +1,4 @@
1
+ import { prepareRootGit } from "./root-git.js";
1
2
  import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, rmdirSync, writeFileSync } from "node:fs";
2
3
  import { homedir, tmpdir } from "node:os";
3
4
  import { delimiter, dirname, join, resolve } from "node:path";
@@ -10,7 +11,7 @@ import type {
10
11
  } from "./types.js";
11
12
  import { WINDOWS_APPCONTAINER_HELPER } from "./windows-appcontainer.js";
12
13
  import { localExecutionShell } from "./shell.js";
13
- import { linkedWorktreeReadRoots, privateGitWriteRoot, macToolShimPath, workspaceRuntimeDirectory, workspaceRuntimeEnvironment, workspaceRuntimeTemporaryDirectory } from "./workspace-runtime.js";
14
+ import { linkedWorktreeReadRoots, privateGitWriteRoot, integrationGitWriteRoots, macToolShimPath, workspaceRuntimeDirectory, workspaceRuntimeEnvironment, workspaceRuntimeTemporaryDirectory } from "./workspace-runtime.js";
14
15
  import { NODE_PROXY_PRELOAD } from "./node-proxy-preload.generated.js";
15
16
  import { ExecutionBoundaryError, operationFailure } from "./failure.js";
16
17
 
@@ -23,6 +24,9 @@ export interface PlatformSandboxOptions {
23
24
  /** Host-owned, workspace-scoped home/cache/scratch. Omitted for strict,
24
25
  * stateless SDK sandboxes and remote runtimes. */
25
26
  workspaceStateRoot?: string;
27
+ /** Trusted Host opt-in for strictly parsed single Git commands in an authorized root workspace.
28
+ * Never applies to readonly/shared or isolated child workspaces. */
29
+ rootWorkspaceGitWrites?: boolean;
26
30
  /** Embedder-owned paths that stay writable inside the process sandbox.
27
31
  * These are not derived from model/tool grants and must only be supplied by
28
32
  * a trusted runtime boundary such as a per-Computer persistent tool store. */
@@ -63,6 +67,7 @@ abstract class CommandWrappingSandbox implements OsSandbox {
63
67
  trustedEnvironmentNames: string[] = [],
64
68
  networkProxy?: NetworkProxy | (() => NetworkProxy | undefined),
65
69
  workspaceStateRoot?: string,
70
+ private readonly rootWorkspaceGitWrites = false,
66
71
  ) {
67
72
  this.networkProxy = networkProxy;
68
73
  this.workspaceStateRoot = workspaceStateRoot;
@@ -86,7 +91,7 @@ abstract class CommandWrappingSandbox implements OsSandbox {
86
91
  },
87
92
  ): { executable: string; args: string[]; release?: () => void };
88
93
 
89
- createContext(input: Parameters<OsSandbox["createContext"]>[0]): SandboxExecutionContext {
94
+ createContext(input: Parameters<OsSandbox["createContext"]>[0], gitOperation = false): SandboxExecutionContext {
90
95
  const status = this.status();
91
96
  if (!status.available || status.provider === "none") {
92
97
  throw new Error(status.reason ?? "OS sandbox is unavailable");
@@ -95,10 +100,14 @@ abstract class CommandWrappingSandbox implements OsSandbox {
95
100
  ? workspaceRuntimeDirectory(this.workspaceStateRoot, input.workspace.root) : undefined;
96
101
  const runtimeTemp = runtimeDirectory ? workspaceRuntimeTemporaryDirectory(runtimeDirectory) : undefined;
97
102
  const privateGit = privateGitWriteRoot(input.workspace);
103
+ const rootGit = gitOperation && this.rootWorkspaceGitWrites && input.workspace.mode === "root"
104
+ && input.grant.filesystem?.write.some(path => canonicalPath(resolve(input.workspace.root, path)) === canonicalPath(input.workspace.root))
105
+ ? integrationGitWriteRoots(input.workspace.root) : [];
98
106
  const writablePaths = [...new Set([
99
107
  ...(input.grant.filesystem?.write ?? []),
100
108
  ...this.trustedWritablePaths,
101
109
  ...(privateGit ? [privateGit] : []),
110
+ ...rootGit,
102
111
  ...(runtimeDirectory ? [runtimeDirectory] : []),
103
112
  ...(runtimeTemp ? [runtimeTemp] : []),
104
113
  ].map((path) => canonicalPath(resolve(input.workspace.root, path))))];
@@ -114,7 +123,7 @@ abstract class CommandWrappingSandbox implements OsSandbox {
114
123
  && input.grant.filesystem?.write.some(path => canonicalPath(path) === canonicalPath(join(input.workspace.root, ".git")));
115
124
  const protectedPaths = [".git", ".zapcode"]
116
125
  .map((name) => canonicalPath(resolve(input.workspace.root, name)))
117
- .filter((path) => path !== privateGit && !(integrationGit && path === canonicalPath(join(input.workspace.root, ".git"))));
126
+ .filter((path) => path !== privateGit && !rootGit.includes(path) && !(integrationGit && path === canonicalPath(join(input.workspace.root, ".git"))));
118
127
  const provider = status.provider;
119
128
  const prepare = (
120
129
  executable: string,
@@ -184,6 +193,20 @@ abstract class CommandWrappingSandbox implements OsSandbox {
184
193
  networkAllowed,
185
194
  prepareCommand: prepare,
186
195
  prepareShell: (command, options) => {
196
+ if (!gitOperation && this.rootWorkspaceGitWrites && input.workspace.mode === "root"
197
+ && input.grant.filesystem?.write.some(path => canonicalPath(resolve(input.workspace.root, path)) === canonicalPath(input.workspace.root))) {
198
+ let git: ReturnType<typeof prepareRootGit>;
199
+ try { git = prepareRootGit(command, input.workspace.root, options.cwd); } catch { /* Unsupported repository: retain normal sandbox protection. */ }
200
+ if (git) {
201
+ const prepared = this.createContext(input, true).prepareCommand(git.executable, git.args, { ...options, environment: {} });
202
+ // Remove inherited GIT_* overrides after normal sandbox environment
203
+ // construction; untrusted tool environment cannot redirect Git.
204
+ if (process.platform !== "win32") prepared.env.PATH = `${dirname(git.executable)}:/usr/bin:/bin:/usr/sbin:/sbin`;
205
+ for (const key of Object.keys(prepared.env)) if (/^GIT_/i.test(key)) delete prepared.env[key];
206
+ for (const [key, value] of Object.entries(git.environment)) if (/^GIT_/i.test(key)) prepared.env[key] = value;
207
+ return prepared;
208
+ }
209
+ }
187
210
  const { executable, argsPrefix } = localExecutionShell();
188
211
  return prepare(executable, [...argsPrefix, command], options);
189
212
  },
@@ -196,7 +219,7 @@ class MacOsSeatbeltSandbox extends CommandWrappingSandbox {
196
219
  protected override readonly enforcesNetworkProxy = true;
197
220
 
198
221
  constructor(options: PlatformSandboxOptions) {
199
- super(options.tempRoot, options.trustedWritablePaths, options.trustedEnvironmentNames, options.networkProxy, options.workspaceStateRoot);
222
+ super(options.tempRoot, options.trustedWritablePaths, options.trustedEnvironmentNames, options.networkProxy, options.workspaceStateRoot, options.rootWorkspaceGitWrites);
200
223
  this.executable = options.sandboxExecPath ?? "/usr/bin/sandbox-exec";
201
224
  }
202
225
 
@@ -264,7 +287,7 @@ class LinuxBubblewrapSandbox extends CommandWrappingSandbox {
264
287
  private readonly executable: string;
265
288
 
266
289
  constructor(options: PlatformSandboxOptions) {
267
- super(options.tempRoot, options.trustedWritablePaths, options.trustedEnvironmentNames, undefined, options.workspaceStateRoot);
290
+ super(options.tempRoot, options.trustedWritablePaths, options.trustedEnvironmentNames, undefined, options.workspaceStateRoot, options.rootWorkspaceGitWrites);
268
291
  this.executable = options.bwrapPath ?? findOnPath("bwrap") ?? "bwrap";
269
292
  }
270
293
 
@@ -366,7 +389,7 @@ class WindowsHelperSandbox extends CommandWrappingSandbox {
366
389
  private readonly trace: boolean;
367
390
 
368
391
  constructor(options: PlatformSandboxOptions) {
369
- super(options.tempRoot, options.trustedWritablePaths, options.trustedEnvironmentNames, undefined, options.workspaceStateRoot);
392
+ super(options.tempRoot, options.trustedWritablePaths, options.trustedEnvironmentNames, undefined, options.workspaceStateRoot, options.rootWorkspaceGitWrites);
370
393
  this.executable = options.windowsHelperPath
371
394
  ?? join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
372
395
  this.trace = options.trace === true;
@@ -97,14 +97,14 @@ export class DefaultToolPolicyEngine implements ToolPolicyEngine {
97
97
  if (permission === "confirm") {
98
98
  return {
99
99
  decision: "ask",
100
- request: { call: request.call, effects: request.effects, proposedGrant: grant },
100
+ request: { call: request.call, effects: request.effects, proposedGrant: grant, grantTtlMs: this.grantTtlMs },
101
101
  reason: "tool requires confirmation",
102
102
  };
103
103
  }
104
104
  if (request.effects.confidence === "unknown" && this.askOnUnknownEffects) {
105
105
  return {
106
106
  decision: "ask",
107
- request: { call: request.call, effects: request.effects, proposedGrant: grant },
107
+ request: { call: request.call, effects: request.effects, proposedGrant: grant, grantTtlMs: this.grantTtlMs },
108
108
  reason: "tool effects are unknown",
109
109
  };
110
110
  }
@@ -52,6 +52,9 @@ export interface ApprovalRequest {
52
52
  call: ResolvedToolCall;
53
53
  effects: ToolEffects;
54
54
  proposedGrant: CapabilityGrant;
55
+ /** Host policy opt-in: start this grant lifetime after approval completes.
56
+ * Omitted custom policies retain their absolute proposedGrant expiry. */
57
+ grantTtlMs?: number;
55
58
  }
56
59
 
57
60
  export interface PolicyRequest {
@@ -803,9 +803,18 @@ export class ToolExecutor {
803
803
  failure: operationFailure("APPROVAL_REQUIRED", "approval", context?.toolCallId),
804
804
  };
805
805
  }
806
- return this.requestApproval(tool, name, parsedArgs, effects, signal, context).then((result) => (
807
- result === true ? authorized() : result
808
- ));
806
+ return this.requestApproval(tool, name, parsedArgs, effects, signal, context).then((result) => {
807
+ if (result !== true) return result;
808
+ const authorization = authorized();
809
+ const ttl = policy.request.grantTtlMs;
810
+ // Human/approval-queue wait consumes no execution authority lifetime.
811
+ // Only a policy that explicitly supplies a duration may activate a fresh
812
+ // expiry. Absolute custom-policy expiries and task deadlines stay intact.
813
+ if (typeof ttl === "number" && Number.isFinite(ttl) && ttl > 0) {
814
+ authorization.grant = { ...grant, expiresAt: Date.now() + ttl };
815
+ }
816
+ return authorization;
817
+ });
809
818
  }
810
819
 
811
820
  private async requestApproval(