zapagent 1.14.11 → 1.14.13

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 (51) hide show
  1. package/bundled-dependencies.json +201 -201
  2. package/package.json +1 -1
  3. package/src/agent-factory.ts +6 -3
  4. package/src/commands/dispatcher.ts +10 -0
  5. package/src/commands.ts +4 -0
  6. package/src/execution-environment.ts +1 -1
  7. package/src/goal-command.ts +173 -0
  8. package/src/goal-host.ts +408 -0
  9. package/src/goal-runner.ts +31 -0
  10. package/src/headless/goal-npm-install.ts +96 -0
  11. package/src/headless/goalPhase.ts +380 -0
  12. package/src/headless/runHeadless.ts +56 -4
  13. package/src/hooks/useTurnDispatcher.ts +3 -0
  14. package/src/index.tsx +17 -0
  15. package/src/ui/slash-palette.tsx +1 -0
  16. package/zapsdk/agent/loop.ts +13 -2
  17. package/zapsdk/agent/subagent-assembly.ts +5 -0
  18. package/zapsdk/agent/tool-execution-guards.ts +30 -17
  19. package/zapsdk/builtin-tools/command.ts +11 -0
  20. package/zapsdk/builtin-tools/subagent.ts +10 -3
  21. package/zapsdk/core/llm.ts +2 -0
  22. package/zapsdk/core/retry.ts +3 -0
  23. package/zapsdk/execution/broker.ts +18 -1
  24. package/zapsdk/execution/goal-workspace-gate.ts +95 -0
  25. package/zapsdk/execution/required-process-seal.ts +35 -0
  26. package/zapsdk/execution/types.ts +8 -0
  27. package/zapsdk/execution/workspace-runtime.ts +6 -0
  28. package/zapsdk/execution/zapvm.ts +117 -15
  29. package/zapsdk/goal/acceptance.ts +139 -0
  30. package/zapsdk/goal/budget.ts +406 -0
  31. package/zapsdk/goal/contracts.ts +93 -0
  32. package/zapsdk/goal/controller.ts +234 -0
  33. package/zapsdk/goal/errors.ts +17 -0
  34. package/zapsdk/goal/git-history-snapshot.ts +210 -0
  35. package/zapsdk/goal/git-operation-owner.ts +64 -0
  36. package/zapsdk/goal/metered-provider.ts +80 -0
  37. package/zapsdk/goal/npm-installer.ts +362 -0
  38. package/zapsdk/goal/scheduler.ts +34 -0
  39. package/zapsdk/goal/store.ts +173 -0
  40. package/zapsdk/goal/structured-output.ts +84 -0
  41. package/zapsdk/goal/workspace-broker.ts +11 -0
  42. package/zapsdk/goal/workspace.ts +425 -0
  43. package/zapsdk/policy/types.ts +4 -0
  44. package/zapsdk/runtime/factory.ts +7 -0
  45. package/zapsdk/scheduler/batch-scheduler.ts +2 -2
  46. package/zapsdk/tools/executor.ts +79 -6
  47. package/zapsdk/tools/types.ts +2 -0
  48. package/zapsdk/workspace/context.ts +8 -4
  49. package/zapsdk/workspace/copy.ts +14 -1
  50. package/zapsdk/workspace/manager.ts +67 -3
  51. package/zapsdk/workspace/types.ts +11 -0
@@ -2,10 +2,26 @@ import type { ToolResult } from "../tools/types.js";
2
2
  import type { ToolExecutor } from "../tools/executor.js";
3
3
  import type { ToolExecutionHooks } from "./streaming-tool-executor.js";
4
4
  import { operationFailure } from "../execution/failure.js";
5
+ import { isEffectivelyReadOnly } from "../tools/effects.js";
5
6
  import { canonicalizeJsonSchema } from "../tools/schema.js";
6
7
  import { sliceHeadCodePoints } from "../utils/logical-lines.js";
7
8
  import { createHash } from "node:crypto";
8
9
 
10
+ // Only results created before executor dispatch carry this in-process proof.
11
+ // Serialized metadata (including runtime.suppression) cannot establish that no
12
+ // process ran, and copied/replayed results deliberately lose this authority.
13
+ const hostDuplicateSuppressions = new WeakSet<ToolResult>();
14
+
15
+ export function isHostDuplicateSuppression(result: ToolResult): boolean {
16
+ return hostDuplicateSuppressions.has(result);
17
+ }
18
+
19
+ function duplicateSuppression(output: string): ToolResult {
20
+ const result: ToolResult = { success: true, runtime: { suppression: "duplicate" }, output };
21
+ hostDuplicateSuppressions.add(result);
22
+ return result;
23
+ }
24
+
9
25
  /** Short target label for observations and duplicate-query explanations.
10
26
  * This lossy display value must not be used as an execution identity. */
11
27
  export function primaryArgSig(name: string, args: Record<string, unknown> | undefined): string {
@@ -231,7 +247,7 @@ export function createRunToolExecutionHooks(
231
247
  failure: operationFailure("TASK_PLAN_REQUIRED", "harness") };
232
248
  }
233
249
  } else if (!planState.ready) {
234
- const readOnly = executor.isReadOnly(name, args);
250
+ const readOnly = executor.workspaceGate ? executor.isStaticallyReadOnly(name) : executor.isReadOnly(name, args);
235
251
  const allowUnplanned = readOnly && planState.baselineReads++ < 1;
236
252
  if (!allowUnplanned) return taskPlanRequiredResult(taskDecomposition);
237
253
  }
@@ -243,13 +259,10 @@ export function createRunToolExecutionHooks(
243
259
  const fetchedAt = fetchedUrls.get(fetchKey);
244
260
  if (fetchedAt !== undefined && Date.now() - fetchedAt < FETCH_REUSE_WINDOW_MS) {
245
261
  onSuppressed(name, args);
246
- return {
247
- success: true,
248
- runtime: { suppression: "duplicate" },
249
- output:
250
- `[Duplicate http_fetch suppressed for ${String(args.url)}. It was already fetched in the last few minutes; ` +
251
- "reuse that result instead of fetching it again, or fetch a different page.]",
252
- };
262
+ return duplicateSuppression(
263
+ `[Duplicate http_fetch suppressed for ${String(args.url)}. It was already fetched in the last few minutes; ` +
264
+ "reuse that result instead of fetching it again, or fetch a different page.]",
265
+ );
253
266
  }
254
267
  fetchedUrls.set(fetchKey, Date.now());
255
268
  return undefined;
@@ -259,14 +272,11 @@ export function createRunToolExecutionHooks(
259
272
  if (completedOrInFlight.has(key)) {
260
273
  onSuppressed(name, args);
261
274
  const target = primaryArgSig(name, args) || "the same arguments";
262
- return {
263
- success: true,
264
- runtime: { suppression: "duplicate" },
265
- output:
266
- `[Duplicate ${name} suppressed for ${target}. ` +
267
- "Reuse the previous result; the workspace has not changed since it was returned. " +
268
- "Choose the next concrete action instead of reading/searching it again.]",
269
- };
275
+ return duplicateSuppression(
276
+ `[Duplicate ${name} suppressed for ${target}. ` +
277
+ "Reuse the previous result; the workspace has not changed since it was returned. " +
278
+ "Choose the next concrete action instead of reading/searching it again.]",
279
+ );
270
280
  }
271
281
  completedOrInFlight.add(key);
272
282
  return undefined;
@@ -284,7 +294,10 @@ export function createRunToolExecutionHooks(
284
294
  if (name === "todo_write" && result.success) {
285
295
  planState.ready = true;
286
296
  }
287
- if (result.success && !executor.isReadOnly(name, args)) {
297
+ const readOnly = executor.workspaceGate
298
+ ? !!result.runtime?.effects && isEffectivelyReadOnly(result.runtime.effects)
299
+ : executor.isReadOnly(name, args);
300
+ if (result.success && !readOnly) {
288
301
  completedOrInFlight.clear();
289
302
  }
290
303
  },
@@ -39,6 +39,8 @@ export interface ExecuteCommandOptions {
39
39
  /** Whether sandboxed commands may open outbound network connections.
40
40
  * Defaults to false; network tools are the brokered egress path. */
41
41
  sandboxNetwork?: boolean;
42
+ /** Restrict shell cwd and declared paths to this tool's workspace root. */
43
+ workspaceOnly?: boolean;
42
44
  /** Expose destination declarations for a restricted execution backend. */
43
45
  restrictedNetwork?: boolean;
44
46
  /** Offer the per-call `dangerouslyDisableSandbox` retry. Defaults to true;
@@ -205,6 +207,15 @@ export function executeCommandTool(options: ExecuteCommandOptions = {}): Tool {
205
207
  || (args.command !== undefined && args.command !== shellCommandDisplay({ check_steps: args.check_steps })))) {
206
208
  ctx.addIssue({ code: "custom", message: "check_steps requires foreground execution and command matching the complete parenthesized step list when provided" });
207
209
  }
210
+ if (options.workspaceOnly) {
211
+ const workspace = resolveToolPathCanonical(options.defaultCwd ?? process.cwd(), options.defaultCwd ?? process.cwd());
212
+ const cwd = resolveToolPathCanonical(args.cwd ?? workspace, workspace);
213
+ const paths = [cwd, ...(args.read_paths ?? []).map(path => resolveToolPathCanonical(path, cwd)),
214
+ ...(args.write_paths ?? []).map(path => resolveToolPathCanonical(path, cwd))];
215
+ if (paths.some(path => !pathIsInsideRoot(path, workspace))) {
216
+ ctx.addIssue({ code: "custom", message: "Goal shell paths must remain inside its workspace" });
217
+ }
218
+ }
208
219
  }).overwrite(args => ({ ...args, command: args.command ?? shellCommandDisplay(args) }));
209
220
  // Keep an object schema for embedders. Parsing supplies the canonical command
210
221
  // before policy, approval, argument hashing and execution see the call.
@@ -81,6 +81,9 @@ export interface SubagentToolOptions {
81
81
  createRegistryForCwd?: (cwd: string) => ToolRegistry;
82
82
  /** When true, a general Agent is blocked instead of sharing the root cwd. */
83
83
  requireWriteIsolation?: boolean;
84
+ /** Trusted Host preparation of a freshly acquired child lease. */
85
+ prepareWorkspace?: (cwd: string, signal?: AbortSignal) => Promise<void>;
86
+ validateWorkspace?: (cwd: string, signal?: AbortSignal) => Promise<void>;
84
87
  /** Runtime-owned scheduler. When present this Tool is only a submission
85
88
  * adapter; it never constructs an independently owned Agent lifecycle. */
86
89
  coordinator?: AgentCoordinator;
@@ -647,6 +650,7 @@ function createDirectSubagentTool(options: SubagentToolOptions): Tool {
647
650
  if (options.workspaceManager && options.createRegistryForCwd) {
648
651
  try {
649
652
  workspaceLease = await options.workspaceManager.acquire(subagentId, true);
653
+ await options.prepareWorkspace?.(workspaceLease.path, signal);
650
654
  } catch (err) {
651
655
  const error = `Writing Agent workspace setup failed: ${err instanceof Error ? err.message : String(err)}`;
652
656
  emitRunState("blocked", {
@@ -786,9 +790,11 @@ function createDirectSubagentTool(options: SubagentToolOptions): Tool {
786
790
  cwd: workspaceLease?.path ?? options.storageProjectCwd,
787
791
  workspace: workspaceLease
788
792
  ? { id: workspaceLease.workspaceId, root: workspaceLease.path, mode: "isolated-write",
789
- ...(workspaceLease.mode === "isolated-git" && workspaceLease.repoPath
790
- ? { privateGitDirectory: join(workspaceLease.repoPath, ".git") } : {}) }
791
- : undefined,
793
+ ...(workspaceLease.privateGit ? { privateGitDirectory: workspaceLease.privateGit.directory,
794
+ privateGitIdentity: { device: workspaceLease.privateGit.device, inode: workspaceLease.privateGit.inode } }
795
+ : workspaceLease.mode === "isolated-git" && workspaceLease.repoPath
796
+ ? { privateGitDirectory: join(workspaceLease.repoPath, ".git") } : {}) }
797
+ : options.executorOptions?.workspace,
792
798
  // Child writes need their own coverage. Never reuse root-path
793
799
  // checkpoints or bypass the destructive-write gate in a worktree.
794
800
  onTrackEdit: isolatedCheckpoint
@@ -869,6 +875,7 @@ function createDirectSubagentTool(options: SubagentToolOptions): Tool {
869
875
  const hadOutput = options.getResultSchema?.() === "outcome-v1" || !!result.text || result.toolResults.some((r) => r.success);
870
876
  let artifact: import("../workspace/types.js").AgentArtifact | null = null;
871
877
  if (workspaceLease && hadOutput && !signal?.aborted && options.workspaceManager) {
878
+ await options.validateWorkspace?.(workspaceLease.path, signal);
872
879
  emitRunState("validating", {
873
880
  statusDetail: "freezing workspace artifact",
874
881
  workspaceId: workspaceLease.workspaceId,
@@ -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
+ /** Host-local logical request identity, shared by retry attempts. */
72
+ requestId?: string;
71
73
  }
72
74
 
73
75
  export interface LLMProvider {
@@ -1,4 +1,5 @@
1
1
  import type { LLMProvider, LLMCallOptions } from "./llm.js";
2
+ import { randomUUID } from "node:crypto";
2
3
  import type { LLMResponse, LLMChunk, Message } from "./types.js";
3
4
  import type { ToolDefinition } from "../tools/types.js";
4
5
  import { hasMeaningfulOutput, notifyProviderRequest, ProviderRequestTimeoutError } from "./provider-request.js";
@@ -48,6 +49,7 @@ export class RetryProvider implements LLMProvider {
48
49
  options?: CallOptions
49
50
  ): Promise<LLMResponse> {
50
51
  let lastError: Error | undefined;
52
+ options = { ...options, requestId: options?.requestId ?? randomUUID() };
51
53
 
52
54
  for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
53
55
  assertProviderRequestAllowed(options);
@@ -94,6 +96,7 @@ export class RetryProvider implements LLMProvider {
94
96
  // Partial reasoning can be abandoned only by an explicitly capable
95
97
  // consumer. Any text/tool/protocol output makes replay unsafe.
96
98
  let lastError: Error | undefined;
99
+ options = { ...options, requestId: options?.requestId ?? randomUUID() };
97
100
  for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
98
101
  assertProviderRequestAllowed(options);
99
102
  let producedOutput = false;
@@ -25,6 +25,8 @@ import type {
25
25
  } from "./types.js";
26
26
 
27
27
  export interface DefaultExecutionBrokerOptions {
28
+ /** The configured process factory implements the Host seal protocol. */
29
+ supportsProcessSeal?: boolean;
28
30
  /** Host-selected independent owner. No owner or process fallback is created. */
29
31
  services?: AuthorizedServiceBackend;
30
32
  /** Required to describe a custom process launcher; omission stays unknown. */
@@ -58,6 +60,7 @@ export class DefaultExecutionBroker implements ExecutionBroker {
58
60
  private readonly limits: ToolResourceLimits;
59
61
  private readonly hardTimeout: boolean;
60
62
  private readonly processBrokerFactory?: DefaultExecutionBrokerOptions["processBrokerFactory"];
63
+ private readonly sealSupported: boolean;
61
64
 
62
65
  constructor(options: DefaultExecutionBrokerOptions = {}) {
63
66
  if (options.services && options.processBrokerFactory) throw new Error("Service ownership must be implemented by the selected backend, not a local process fallback");
@@ -71,8 +74,11 @@ export class DefaultExecutionBroker implements ExecutionBroker {
71
74
  this.limits = configureLimits(DEFAULT_TOOL_RESOURCE_LIMITS, options.limits);
72
75
  this.hardTimeout = options.limits?.timeoutMs !== undefined;
73
76
  this.processBrokerFactory = options.processBrokerFactory;
77
+ this.sealSupported = options.supportsProcessSeal === true;
74
78
  }
75
79
 
80
+ supportsProcessSeal(): boolean { return this.sealSupported; }
81
+
76
82
  serviceCapabilities(workspace: ExecutionBrokerRequest["workspace"]) { return this.services?.capabilities(workspace); }
77
83
 
78
84
  shellEnvironment(): ShellExecutionEnvironment { return { ...this.shellFacts }; }
@@ -112,6 +118,7 @@ export class DefaultExecutionBroker implements ExecutionBroker {
112
118
  const observe = observeLegacyExecution(request, sandboxStatus, this.sandboxMode, limits);
113
119
  let sandbox: SandboxExecutionContext | undefined;
114
120
  let processBroker: ExecutionProcessBroker | undefined;
121
+ let processSealed = false;
115
122
  const budget = new DefaultExecutionResourceBudget(limits);
116
123
  const finish = (result: ToolResult, outcome: EnforcementReceipt["outcome"]): ToolResult => {
117
124
  const denials = processBroker?.networkDenials?.slice(0, 16) ?? [];
@@ -128,10 +135,11 @@ export class DefaultExecutionBroker implements ExecutionBroker {
128
135
  }
129
136
  const normalized = normalizeToolFailure(result, request.executionId);
130
137
  // Ordinary handlers cannot manufacture service-owner evidence.
131
- const { service: _service, serviceOperation: _operation, ...runtime } = normalized.runtime ?? {};
138
+ const { service: _service, serviceOperation: _operation, processSeal: _untrustedSeal, ...runtime } = normalized.runtime ?? {};
132
139
  const usage = budget.usage;
133
140
  return { ...normalized, runtime: {
134
141
  ...runtime, ...serviceEvidence,
142
+ ...(processSealed ? { processSeal: { state: "sealed" as const, executionId: request.executionId } } : {}),
135
143
  ...(denials.length ? { networkDenials: denials } : {}),
136
144
  ...(this.sandboxMode !== "disabled" ? { broker: {
137
145
  executionId: request.executionId,
@@ -213,6 +221,9 @@ export class DefaultExecutionBroker implements ExecutionBroker {
213
221
  ? this.processBrokerFactory?.({ request, sandbox, signal: executionAbort.signal, limits })
214
222
  ?? new DefaultExecutionProcessBroker(sandbox, executionAbort.signal)
215
223
  : undefined;
224
+ if (needsProcessSandbox && request.requireProcessSeal && !processBroker?.verifyProcessSeal) {
225
+ return reject("Selected backend cannot prove process-tree sealing", "CAPABILITY_UNSUPPORTED");
226
+ }
216
227
  if (signal?.aborted) {
217
228
  executionAbort.abort(signal.reason);
218
229
  return reject("aborted", "CANCELLED");
@@ -258,6 +269,12 @@ export class DefaultExecutionBroker implements ExecutionBroker {
258
269
  });
259
270
  };
260
271
  const result = await Promise.race([invoke(), timeoutPromise, abortPromise]);
272
+ if (needsProcessSandbox && request.requireProcessSeal) {
273
+ // The handler may return a failure after it launched a process. Its
274
+ // descendants still need confirmation before any outcome is trusted.
275
+ await Promise.race([processBroker!.verifyProcessSeal!(), timeoutPromise, abortPromise]);
276
+ processSealed = true;
277
+ }
261
278
  if (result.success && needsProcessSandbox && processBroker?.spawnCount === 0) {
262
279
  return finish({ ...brokerFailure(
263
280
  `process tool ${request.name} returned success without using the broker-owned process launcher`),
@@ -0,0 +1,95 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ import { realpathSync, statSync } from "node:fs";
4
+ import { isAbsolute, relative, sep } from "node:path";
5
+ import { ToolBatchScheduler } from "../scheduler/batch-scheduler.js";
6
+ import type { ToolResult } from "../tools/types.js";
7
+ import type { ToolAuthorization, WorkspaceExecutionGate } from "../tools/executor.js";
8
+
9
+ function canonicalDirectory(path: string): { root: string; device: bigint; inode: bigint } {
10
+ if (!isAbsolute(path)) throw new Error("Goal workspace must be absolute");
11
+ const root = realpathSync(path);
12
+ const stat = statSync(root, { bigint: true });
13
+ if (!stat.isDirectory()) throw new Error("Goal workspace must be a directory");
14
+ return { root, device: stat.dev, inode: stat.ino };
15
+ }
16
+ function overlaps(a: string, b: string): boolean {
17
+ const inside = (parent: string, child: string) => {
18
+ const rel = relative(parent, child);
19
+ return !rel || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
20
+ };
21
+ return inside(a, b) || inside(b, a);
22
+ }
23
+
24
+ /** In-process coordination only. One instance must be shared by the Host and
25
+ * every executor, including all child-agent executors. This does not fence
26
+ * independently spawned processes, external clients, or process crashes. */
27
+ export class GoalWorkspaceGate implements WorkspaceExecutionGate {
28
+ private readonly scheduler = new ToolBatchScheduler();
29
+ private readonly poisoned = new Set<string>();
30
+ private readonly ownership = new AsyncLocalStorage<{ active: boolean; root: string }>();
31
+
32
+ private poison(root: string): void { this.poisoned.add(root); }
33
+ private assertHealthy(root: string): void {
34
+ if ([...this.poisoned].some(other => overlaps(root, other))) throw new Error("GOAL_WORKSPACE_EXECUTION_UNCONFIRMED");
35
+ }
36
+
37
+ markUnconfirmed(): void {
38
+ const owner = this.ownership.getStore();
39
+ if (!owner?.active) throw new Error("Goal workspace uncertainty has no active owner");
40
+ this.poison(owner.root);
41
+ }
42
+
43
+ /** The caller must settle only when all effects and descendants have ceased.
44
+ * Exceptions or cancellation poison the workspace until the owning Goal is
45
+ * explicitly reconciled by its durable Host lifecycle. */
46
+ async withExclusiveWorkspace<T>(workspace: string, action: () => Promise<T>, signal?: AbortSignal): Promise<T> {
47
+ // A nested acquisition can deadlock even for different roots: two owners
48
+ // could each wait for the other's lock. Do not treat an async descendant
49
+ // as a fresh owner while its enclosing Host action still holds a lease.
50
+ if (this.ownership.getStore()?.active) throw new Error("GOAL_WORKSPACE_REENTRANT_LOCK");
51
+ const identity = canonicalDirectory(workspace);
52
+ const root = identity.root;
53
+ return this.scheduler.schedule(randomUUID(), [{ key: `fs:${root}`, mode: "exclusive" }], async () => {
54
+ this.assertHealthy(root);
55
+ if (signal?.aborted) throw new Error("aborted");
56
+ // The path may be a symlink or a directory replaced while waiting.
57
+ // Never execute under a lock for an identity other than the one queued.
58
+ const current = canonicalDirectory(workspace);
59
+ if (current.root !== root || current.device !== identity.device || current.inode !== identity.inode) {
60
+ throw new Error("GOAL_WORKSPACE_IDENTITY_CHANGED");
61
+ }
62
+ const owner = { active: true, root };
63
+ return this.ownership.run(owner, async () => {
64
+ try {
65
+ const value = await action();
66
+ if (signal?.aborted) { this.poison(root); throw new Error("GOAL_WORKSPACE_EXECUTION_UNCONFIRMED"); }
67
+ this.assertHealthy(root);
68
+ return value;
69
+ } catch (error) {
70
+ this.poison(root);
71
+ throw error;
72
+ } finally { owner.active = false; }
73
+ });
74
+ }, signal);
75
+ }
76
+
77
+ authorize<T>(workspace: string, action: () => T | Promise<T>, signal?: AbortSignal): Promise<T> {
78
+ return this.withExclusiveWorkspace(workspace, async () => action(), signal);
79
+ }
80
+
81
+ async execute(workspace: string, authorization: ToolAuthorization, action: () => Promise<ToolResult>, signal?: AbortSignal): Promise<ToolResult> {
82
+ if (["agent", "delegate_agent", "merge_agent_artifacts"].includes(authorization.name)) {
83
+ return { success: false, output: "", error: "Goal workspace gate does not yet support agent orchestration" };
84
+ }
85
+ return this.withExclusiveWorkspace(workspace, async () => {
86
+ const result = await action();
87
+ if (signal?.aborted || ["CANCELLED", "DEADLINE_EXCEEDED"].includes(result.failure?.code ?? "")
88
+ || (authorization.effects.process.length > 0 && result.runtime?.processSeal?.state !== "sealed")) {
89
+ throw new Error("GOAL_WORKSPACE_EXECUTION_UNCONFIRMED");
90
+ }
91
+ return result;
92
+ }, signal);
93
+ }
94
+
95
+ }
@@ -0,0 +1,35 @@
1
+ import { operationFailure } from "./failure.js";
2
+ import type { ExecutionBroker, ExecutionBrokerRequest } from "./types.js";
3
+ import type { ToolResult } from "../tools/types.js";
4
+
5
+ /** Host decorator: require the selected backend to verify every process
6
+ * before a tool result is accepted. Never changes the selected backend or a
7
+ * permission grant. The capability check concerns protocol support, not a
8
+ * claim that a specific command has already been sealed. */
9
+ export function requireProcessSealing(inner: ExecutionBroker, onUnconfirmed?: () => void): ExecutionBroker {
10
+ return {
11
+ sandboxStatus: () => inner.sandboxStatus(),
12
+ ...(inner.shellEnvironment ? { shellEnvironment: tool => inner.shellEnvironment!(tool) } : {}),
13
+ ...(inner.serviceCapabilities ? { serviceCapabilities: workspace => inner.serviceCapabilities!(workspace) } : {}),
14
+ supportsProcessSeal: tool => inner.supportsProcessSeal?.(tool) === true,
15
+ async execute(request: ExecutionBrokerRequest, signal?: AbortSignal): Promise<ToolResult> {
16
+ if (!request.effects.process.length) return inner.execute(request, signal);
17
+ const tool = { name: request.name, executionLocation: request.tool.definition.executionLocation };
18
+ if (inner.supportsProcessSeal?.(tool) !== true) {
19
+ onUnconfirmed?.();
20
+ return { success: false, output: "", error: "Selected backend cannot prove process-tree sealing",
21
+ failure: operationFailure("CAPABILITY_UNSUPPORTED", "broker", request.executionId) };
22
+ }
23
+ let result: ToolResult;
24
+ try { result = await inner.execute({ ...request, requireProcessSeal: true }, signal); }
25
+ catch (error) { onUnconfirmed?.(); throw error; }
26
+ if (result.runtime?.processSeal?.state !== "sealed" || result.runtime.processSeal.executionId !== request.executionId) {
27
+ onUnconfirmed?.();
28
+ return { success: false, output: "", error: "Process-tree sealing was not confirmed",
29
+ failure: operationFailure("BACKEND_UNAVAILABLE", "broker", request.executionId),
30
+ runtime: result.runtime };
31
+ }
32
+ return result;
33
+ },
34
+ };
35
+ }
@@ -74,6 +74,9 @@ export interface ExecutionProcessBroker {
74
74
  /** Adapter readiness is checked under the execution deadline, before the
75
75
  * handler may launch anything. Failure never selects a different backend. */
76
76
  ensureReady?(): Promise<void>;
77
+ /** Host-only, backend-authored check that every launched process is sealed.
78
+ * Absence means the backend cannot satisfy a required process seal. */
79
+ verifyProcessSeal?(): Promise<void>;
77
80
  spawnCommand(
78
81
  executable: string,
79
82
  args: string[],
@@ -101,6 +104,8 @@ export interface OsSandbox {
101
104
  }
102
105
 
103
106
  export interface ExecutionBrokerRequest {
107
+ /** Host requirement, never supplied by model tool arguments. */
108
+ requireProcessSeal?: boolean;
104
109
  /** Host-minted stable approval identity; never read from model arguments. */
105
110
  serviceOperationNonce?: string;
106
111
  /** Host-only progress facts, so outer cancellation retains unknown effects. */
@@ -136,6 +141,9 @@ export interface ExecutionResourceBudget {
136
141
  }
137
142
 
138
143
  export interface ExecutionBroker {
144
+ /** Host configuration supports requesting per-execution seal verification.
145
+ * This is not itself a seal receipt for a command. */
146
+ supportsProcessSeal?(tool: { name: string; executionLocation?: "workspace" | "host" }): boolean;
139
147
  /** Explicit selected-backend service capability; never inferred from shell support. */
140
148
  serviceCapabilities?(workspace: WorkspaceIdentity): ServiceCapabilities | undefined;
141
149
  sandboxStatus(): SandboxStatus;
@@ -19,6 +19,12 @@ export function privateGitWriteRoot(workspace: WorkspaceIdentity): string | unde
19
19
  || !isWithin(repo, root) || realpathSync(path) !== path) {
20
20
  throw new Error("Private Agent Git directory must belong to its standalone clone");
21
21
  }
22
+ if (workspace.privateGitIdentity) {
23
+ const identity = lstatSync(path, { bigint: true });
24
+ if (identity.dev.toString() !== workspace.privateGitIdentity.device || identity.ino.toString() !== workspace.privateGitIdentity.inode) {
25
+ throw new Error("Private Agent Git directory identity changed");
26
+ }
27
+ }
22
28
  return path;
23
29
  }
24
30
 
@@ -1,5 +1,7 @@
1
1
  import { spawn, spawnSync, type ChildProcess } from "node:child_process";
2
- import { closeSync, lstatSync, mkdirSync, openSync } from "node:fs";
2
+ import { closeSync, constants, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, rmSync, realpathSync } from "node:fs";
3
+ import { randomUUID } from "node:crypto";
4
+ import { tmpdir } from "node:os";
3
5
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
6
  import { resolveZapVmGuestCwd } from "./workspace-path.js";
5
7
  import { getAppDataDir } from "../utils/platform.js";
@@ -17,6 +19,8 @@ import { DefaultExecutionBroker } from "./broker.js";
17
19
  import { terminateProcessTreeWithGrace } from "./process.js";
18
20
  import { operationFailure } from "./failure.js";
19
21
  import { observeLegacyExecution } from "./observation.js";
22
+ import { privateGitWriteRoot } from "./workspace-runtime.js";
23
+ import type { WorkspaceIdentity } from "../policy/types.js";
20
24
 
21
25
  const DEFAULT_START_TIMEOUT_MS = 10_000;
22
26
 
@@ -311,6 +315,11 @@ export class TransparentExecutionBroker implements ExecutionBroker {
311
315
  return this.vm?.sandboxStatus() ?? this.local.sandboxStatus();
312
316
  }
313
317
 
318
+ supportsProcessSeal(tool: { name: string; executionLocation?: "workspace" | "host" }): boolean {
319
+ const backend = this.usesWorkspaceBackend(tool.name, tool.executionLocation) ? this.vm! : this.local;
320
+ return backend.supportsProcessSeal?.(tool) === true;
321
+ }
322
+
314
323
  serviceCapabilities(workspace: import("../policy/types.js").WorkspaceIdentity) {
315
324
  return (this.vm ?? this.local).serviceCapabilities?.(workspace);
316
325
  }
@@ -370,6 +379,8 @@ export function buildZapVmExecArgs(input: {
370
379
  workspaceReadOnly?: boolean;
371
380
  protectedWorkspacePaths?: string[];
372
381
  networkPolicy?: ZapVmNetworkPolicy;
382
+ /** Host-only strict process seal result, outside the guest workspace. */
383
+ processSeal?: { requestId: string; resultFile: string };
373
384
  }): string[] {
374
385
  if (input.argv.length === 0 || !input.argv[0]) throw new Error("Guest command requires an executable");
375
386
  const networkPolicy = input.networkPolicy;
@@ -383,6 +394,7 @@ export function buildZapVmExecArgs(input: {
383
394
  "--network", networkPolicy ? "restricted" : "off",
384
395
  ];
385
396
  if (input.workspaceReadOnly) args.push("--workspace-read-only");
397
+ if (input.processSeal) args.push("--request-id", input.processSeal.requestId, "--require-process-seal", "--result-file", input.processSeal.resultFile);
386
398
  for (const protectedPath of input.protectedWorkspacePaths ?? []) {
387
399
  args.push("--protect-workspace-path", protectedPath);
388
400
  }
@@ -438,6 +450,7 @@ export function resolveZapVmNetworkPolicy(
438
450
  class ZapVmExecutionProcessBroker implements ExecutionProcessBroker {
439
451
  private _spawnCount = 0;
440
452
  private _sandboxedSpawnCount = 0;
453
+ private readonly sealResults: Array<{ path: string; directory: string; requestId: string; sessionId: string; closed: Promise<number | null> }> = [];
441
454
 
442
455
  constructor(
443
456
  private readonly installation: ZapVmInstallation,
@@ -468,20 +481,42 @@ class ZapVmExecutionProcessBroker implements ExecutionProcessBroker {
468
481
 
469
482
  private launch(argv: string[], options: SandboxCommandOptions): ChildProcess {
470
483
  if (this.signal.aborted) throw new Error("aborted");
484
+ const workspaceReadOnly = this.request.effects.workspace.mode === "shared-readonly";
485
+ const protectedPaths = protectedPathsForVm(this.request.workspace, workspaceReadOnly);
486
+ // virtiofs presents Host-created private clones with the Host uid rather
487
+ // than the Guest workload uid. Trust only this one Guest mount, and only
488
+ // after the Host has bound its standalone private .git directory.
489
+ if (!workspaceReadOnly && this.request.workspace.privateGitDirectory && !protectedPaths.includes(".git")) {
490
+ argv = ["/usr/bin/env", "GIT_CONFIG_COUNT=1", "GIT_CONFIG_KEY_0=safe.directory", "GIT_CONFIG_VALUE_0=/workspace", ...argv];
491
+ }
492
+ const sessionId = boundedIdentifier(this.request.context?.agentRun?.runId ?? this.request.context?.sessionId ?? "zap-session", "zap-session");
493
+ let seal: { requestId: string; resultFile: string; directory: string } | undefined;
494
+ if (this.request.requireProcessSeal) {
495
+ // The guest must never see or modify the receipt path. Refuse to put
496
+ // private Host state beneath a workspace that is mapped into the guest.
497
+ const parent = realpathSync(tmpdir());
498
+ const workspace = realpathSync(this.request.workspace.root);
499
+ const rel = relative(workspace, parent);
500
+ if (!rel || (!rel.startsWith(`..${sep}`) && rel !== ".." && !isAbsolute(rel))) {
501
+ throw new Error("Process seal storage is within the guest workspace");
502
+ }
503
+ const directory = mkdtempSync(join(parent, "zap-seal-"));
504
+ seal = { directory, requestId: randomUUID(), resultFile: join(directory, "result.json") };
505
+ }
471
506
  this._spawnCount += 1;
472
507
  this._sandboxedSpawnCount += 1;
473
- const child = spawn(this.installation.binaryPath, buildZapVmExecArgs({
508
+ let child: ChildProcess;
509
+ try { child = spawn(this.installation.binaryPath, buildZapVmExecArgs({
474
510
  endpoint: this.endpoint,
475
511
  workspaceRoot: this.request.workspace.root,
476
512
  hostCwd: options.cwd,
477
- sessionId: this.request.context?.agentRun?.runId
478
- ?? this.request.context?.sessionId
479
- ?? "zap-session",
513
+ sessionId,
480
514
  timeoutMs: this.limits.timeoutMs,
481
515
  argv,
482
- workspaceReadOnly: this.request.effects.workspace.mode === "shared-readonly",
483
- protectedWorkspacePaths: ensureProtectedWorkspacePaths(this.request.workspace.root),
516
+ workspaceReadOnly,
517
+ protectedWorkspacePaths: protectedPaths,
484
518
  networkPolicy: resolveZapVmNetworkPolicy(this.request.grant.network),
519
+ ...(seal ? { processSeal: { requestId: seal.requestId, resultFile: seal.resultFile } } : {}),
485
520
  }), {
486
521
  cwd: this.request.workspace.root,
487
522
  detached: process.platform !== "win32",
@@ -489,7 +524,16 @@ class ZapVmExecutionProcessBroker implements ExecutionProcessBroker {
489
524
  shell: false,
490
525
  stdio: ["pipe", "pipe", "pipe"],
491
526
  windowsHide: true,
492
- });
527
+ }); } catch (error) { if (seal) rmSync(seal.directory, { recursive: true, force: true }); throw error; }
528
+ if (seal) {
529
+ const expected = seal;
530
+ const closed = new Promise<number | null>((resolveClose) => {
531
+ child.once("error", () => resolveClose(null));
532
+ child.once("close", resolveClose);
533
+ });
534
+ this.sealResults.push({ path: expected.resultFile, directory: expected.directory,
535
+ requestId: expected.requestId, sessionId, closed });
536
+ }
493
537
  child.stdin?.end();
494
538
  const onAbort = () => terminateProcessTreeWithGrace(child);
495
539
  this.signal.addEventListener("abort", onAbort, { once: true });
@@ -498,10 +542,40 @@ class ZapVmExecutionProcessBroker implements ExecutionProcessBroker {
498
542
  child.once("error", cleanup);
499
543
  return child;
500
544
  }
545
+
546
+ async verifyProcessSeal(): Promise<void> {
547
+ if (!this.request.requireProcessSeal || !this.sealResults.length || this.sealResults.length !== this._spawnCount) {
548
+ throw new Error("Process seal receipt missing");
549
+ }
550
+ try {
551
+ for (const expected of this.sealResults) {
552
+ const code = await expected.closed;
553
+ const fd = openSync(expected.path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
554
+ let receipt: unknown;
555
+ try {
556
+ const stat = fstatSync(fd);
557
+ if (!stat.isFile() || stat.size > 8192 || (process.getuid && stat.uid !== process.getuid())) {
558
+ throw new Error("Invalid process seal receipt file");
559
+ }
560
+ receipt = JSON.parse(readFileSync(fd, "utf8"));
561
+ } finally { closeSync(fd); }
562
+ if (!receipt || typeof receipt !== "object" || Array.isArray(receipt)) throw new Error("Invalid process seal receipt");
563
+ const data = receipt as { request_id?: unknown; session_id?: unknown; exit_code?: unknown; seal?: { mechanism?: unknown; state?: unknown } };
564
+ if (data.request_id !== expected.requestId || data.session_id !== expected.sessionId ||
565
+ !Number.isSafeInteger(data.exit_code) || (data.exit_code as number) < 0 || (data.exit_code as number) > 255 ||
566
+ code !== data.exit_code || data.seal?.mechanism !== "cgroup-v2" || data.seal.state !== "empty") {
567
+ throw new Error("Process seal receipt is missing, unbound, or incompatible");
568
+ }
569
+ }
570
+ } finally {
571
+ for (const item of this.sealResults) rmSync(item.directory, { recursive: true, force: true });
572
+ }
573
+ }
501
574
  }
502
575
 
503
576
  function createZapVmExecutionBroker(runtime: ZapVmRuntimeController, limits?: Partial<ToolResourceLimits>): ExecutionBroker {
504
577
  return new DefaultExecutionBroker({
578
+ supportsProcessSeal: true,
505
579
  shellEnvironment: { syntax: "posix", filesystem: "workspace-mapped", workspaceRoot: "/workspace" },
506
580
  sandbox: new ZapVmSandbox(),
507
581
  sandboxMode: "required",
@@ -526,7 +600,7 @@ class ZapVmSandbox implements OsSandbox {
526
600
  enforced: true,
527
601
  readablePaths: input.grant.filesystem?.read ?? [],
528
602
  writablePaths: input.grant.filesystem?.write ?? [],
529
- protectedPaths: ensureProtectedWorkspacePaths(input.workspace.root)
603
+ protectedPaths: protectedPathsForVm(input.workspace, input.effects.workspace.mode === "shared-readonly")
530
604
  .map((path) => join(input.workspace.root, path)),
531
605
  networkAllowed: (input.grant.network?.destinations.length ?? 0) > 0,
532
606
  prepareCommand: unsupported,
@@ -535,14 +609,42 @@ class ZapVmSandbox implements OsSandbox {
535
609
  }
536
610
  }
537
611
 
538
- export function ensureProtectedWorkspacePaths(workspaceRoot: string): string[] {
612
+ /** Only Host workspace identity can authorize a private clone's control
613
+ * directory. Read-only requests always retain the protection. */
614
+ export function protectedPathsForVm(workspace: WorkspaceIdentity, readOnly: boolean): string[] {
615
+ const paths = ensureProtectedWorkspacePaths(workspace.root, !readOnly);
616
+ if (!readOnly && workspace.privateGitDirectory) {
617
+ const git = privateGitWriteRoot(workspace);
618
+ // A nested Goal workspace does not expose the parent repo's .git through
619
+ // the single workspace mount, so only a clone at the mount root qualifies.
620
+ if (git && dirname(git) === realpathSync(workspace.root)) {
621
+ const index = paths.indexOf(".git");
622
+ if (index < 0) throw new Error("Private Agent Git directory is unavailable");
623
+ paths.splice(index, 1);
624
+ }
625
+ }
626
+ for (const path of workspace.protectedWorkspacePaths ?? []) {
627
+ if (typeof path !== "string" || !path || Buffer.byteLength(path) > 4096 || path.includes("\\") || path.includes("\0") || isAbsolute(path)
628
+ || path.split("/").some(part => !part || part === "." || part === "..")) throw new Error("Invalid Host protected workspace path");
629
+ if (!paths.includes(path)) paths.push(path);
630
+ }
631
+ if (paths.length > 16) throw new Error("Too many Host protected workspace paths");
632
+ return paths;
633
+ }
634
+
635
+ export function ensureProtectedWorkspacePaths(workspaceRoot: string, createControlDirectory = true): string[] {
539
636
  const zapcodePath = join(workspaceRoot, ".zapcode");
540
- mkdirSync(zapcodePath, { recursive: true, mode: 0o700 });
541
- const zapcodeInfo = lstatSync(zapcodePath);
542
- if (!zapcodeInfo.isDirectory() || zapcodeInfo.isSymbolicLink()) {
543
- throw new Error("Workspace .zapcode control path must be a real directory");
637
+ if (createControlDirectory) mkdirSync(zapcodePath, { recursive: true, mode: 0o700 });
638
+ const protectedPaths: string[] = [];
639
+ try {
640
+ const zapcodeInfo = lstatSync(zapcodePath);
641
+ if (!zapcodeInfo.isDirectory() || zapcodeInfo.isSymbolicLink()) {
642
+ throw new Error("Workspace .zapcode control path must be a real directory");
643
+ }
644
+ protectedPaths.push(".zapcode");
645
+ } catch (error) {
646
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT" || createControlDirectory) throw error;
544
647
  }
545
- const protectedPaths = [".zapcode"];
546
648
  const gitPath = join(workspaceRoot, ".git");
547
649
  try {
548
650
  const gitInfo = lstatSync(gitPath);