zapagent 1.14.23 → 1.14.25

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.
@@ -6,6 +6,7 @@ import { relative, resolve, sep } from "node:path";
6
6
  import { DEFAULT_TOOL_RESOURCE_LIMITS, type ToolResourceLimits } from "../tools/effects.js";
7
7
  import type { ToolResult } from "../tools/types.js";
8
8
  import { createPlatformSandbox } from "./sandbox.js";
9
+ import { destinationHostPattern } from "./network-proxy.js";
9
10
  import { DefaultExecutionProcessBroker } from "./process.js";
10
11
  import { earliestDeadlineAt, hasDeadlineExpired } from "./deadline.js";
11
12
  import { ExecutionBoundaryError, executionFailureResult, normalizeToolFailure, operationFailure } from "./failure.js";
@@ -124,12 +125,13 @@ export class DefaultExecutionBroker implements ExecutionBroker {
124
125
  const denials = processBroker?.networkDenials?.slice(0, 16) ?? [];
125
126
  if (denials.length) {
126
127
  result = { ...result,
127
- output: `${result.output}\n[Sandbox network refusals] ${JSON.stringify(denials)}\nThe proxy refused these destinations. Resolve the network policy or request authorization before retrying; a zero shell exit does not prove all requests succeeded.`,
128
+ output: `${result.output}\n[Sandbox network refusals] ${JSON.stringify(denials)}\nThe proxy refused these destinations. To retry, declare the refused hosts in network_destinations (the user approves each host once); a zero shell exit does not prove all requests succeeded.`,
128
129
  ...(!result.success && !result.runtime?.command?.timedOut && !result.runtime?.command?.aborted
129
130
  && (!result.failure || result.failure.source === "unknown") ? { failure: {
130
131
  ...operationFailure("SANDBOX_DENIED", "backend", request.executionId),
131
132
  missingCapabilities: denials.map(item => `network:${item.host}`),
132
- safeAlternatives: ["Ask the user to authorize the required destination in sandboxNetwork.allowedDomains, or an approved unsandboxed command."],
133
+ safeAlternatives: ["Retry inside the sandbox with network_destinations listing the refused hosts; each host needs approval once.",
134
+ "Ask the user to add the destination to sandboxNetwork.allowedDomains."],
133
135
  } } : {}),
134
136
  };
135
137
  }
@@ -215,7 +217,12 @@ export class DefaultExecutionBroker implements ExecutionBroker {
215
217
  && request.tool.definition.executionLocation === "host"
216
218
  && request.workspace.mode !== "shared-readonly"
217
219
  && request.effects.workspace.mode === "root-integration"
218
- && request.effects.process.some(effect => effect.commandClass === "external-cli") })
220
+ && request.effects.process.some(effect => effect.commandClass === "external-cli"),
221
+ // Only a shell declares extra hosts; the approved grant carries them.
222
+ declaredNetworkDomains: request.effects.process.some(effect => effect.commandClass === "shell")
223
+ ? [...new Set((request.grant.network?.destinations ?? []).filter(value => value !== "*")
224
+ .map(destinationHostPattern).filter((host): host is string => !!host))]
225
+ : undefined })
219
226
  : undefined;
220
227
  processBroker = needsProcessSandbox
221
228
  ? this.processBrokerFactory?.({ request, sandbox, signal: executionAbort.signal, limits })
@@ -23,6 +23,18 @@ export const DEFAULT_ALLOWED_DOMAINS: readonly string[] = [
23
23
  "fonts.googleapis.com", "fonts.gstatic.com",
24
24
  ];
25
25
 
26
+ /** Host pattern for a declared destination (URL, host or `*.host`), or null. */
27
+ export function destinationHostPattern(value: string): string | null {
28
+ const trimmed = value.trim().toLowerCase();
29
+ let host = trimmed;
30
+ if (/^[a-z][a-z0-9+.-]*:\/\//.test(trimmed)) {
31
+ try { host = new URL(trimmed).hostname; } catch { return null; }
32
+ }
33
+ host = host.replace(/\.$/, "");
34
+ if (host.length > 253) return null;
35
+ return /^(?:\*\.)?[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/.test(host) ? host : null;
36
+ }
37
+
26
38
  const LOOPBACK_NAMES = new Set(["localhost", "localhost.localdomain", "ip6-localhost"]);
27
39
 
28
40
  function normalizeHost(host: string): string {
@@ -30,7 +42,8 @@ function normalizeHost(host: string): string {
30
42
  }
31
43
 
32
44
  function isLoopbackAddress(host: string): boolean {
33
- return LOOPBACK_NAMES.has(host) || /^127\./.test(host) || host === "::1" || host === "::ffff:127.0.0.1";
45
+ // Only a literal address: a name like 127.evil.com resolves wherever its owner wants.
46
+ return LOOPBACK_NAMES.has(host) || (isIP(host) === 4 && /^127\./.test(host)) || host === "::1" || host === "::ffff:127.0.0.1";
34
47
  }
35
48
 
36
49
  /** Link-local space holds cloud metadata services (169.254.169.254) and is never
@@ -161,7 +174,7 @@ export class NetworkProxy {
161
174
  if (!this.blocked.has(key)) this.blocked.set(key, decision.reason);
162
175
  return this.reject(client, 403,
163
176
  `zap sandbox: network access to ${key} is blocked (${decision.reason}). `
164
- + "Add it to sandboxNetwork.allowedDomains in the config, or retry the command outside the sandbox with approval.");
177
+ + "Declare it in the command's network_destinations to request approval, or add it to sandboxNetwork.allowedDomains in the config.");
165
178
  }
166
179
  let address = normalizeHost(host);
167
180
  if (isIP(address) === 0) {
@@ -145,6 +145,7 @@ abstract class CommandWrappingSandbox implements OsSandbox {
145
145
  }
146
146
  }
147
147
  if (input.externalCliIntegration) proxy?.allowDomains(options.networkDomains ?? []);
148
+ proxy?.allowDomains(input.declaredNetworkDomains ?? []);
148
149
  wrapped = this.wrap(executable, args, {
149
150
  cwd: canonicalPath(resolve(options.cwd)),
150
151
  readablePaths: [...new Set([
@@ -97,6 +97,8 @@ export interface OsSandbox {
97
97
  executionId: string;
98
98
  /** Broker-authorized external CLI integration, never derived from shell arguments. */
99
99
  externalCliIntegration?: boolean;
100
+ /** Hosts a shell declared and the host approved; the proxy admits them for this command only. */
101
+ declaredNetworkDomains?: string[];
100
102
  workspace: WorkspaceIdentity;
101
103
  effects: ToolEffects;
102
104
  grant: CapabilityGrant;
package/zapsdk/index.ts CHANGED
@@ -28,7 +28,7 @@ export { emptyToolEffects, unknownToolEffects, inferredReadOnlyEffects, isEffect
28
28
  export { resolveDefinitionEffects, isDefinitionCallReadOnly } from "./tools/compatibility.js";
29
29
  export { adaptLegacyTool, inferToolSource, type ToolId, type ToolManifest, type ToolNamespace, type ToolSource } from "./tools/manifest.js";
30
30
  export { ToolRegistry } from "./tools/registry.js";
31
- export { type ToolApprovalFacts } from "./tools/approval.js";
31
+ export { resolveToolCapabilities, type CapabilityKind, type ToolApprovalFacts, type ToolCapability } from "./tools/approval.js";
32
32
  export { ToolExecutor, isToolAuthorization, type ToolAuthorization, type ToolExecutorOptions, type ApprovalCallback, type ApprovalContext, type ApprovalResponse, type ApprovalDenial, type ApprovalCoordinator, type ApprovalLifecycleEvent, type ApprovalLifecycleHandler, type ApprovalLifecycleStatus, type ToolExecutionLifecycleEvent, type ToolExecutionLifecycleHandler, type ToolExecutionLifecycleStatus, type PostProcessCallback } from "./tools/executor.js";
33
33
  export { DefaultToolPolicyEngine, createCapabilityGrant, type DefaultToolPolicyOptions, type AgentIdentity, type ApprovalRequest, type CapabilityGrant, type PolicyDecision, type PolicyRequest, type ResolvedToolCall, type ToolPolicyEngine, type WorkspaceIdentity } from "./policy/index.js";
34
34
  export { DefaultExecutionBroker, TransparentExecutionBroker, ZapVmRuntime, HttpsZapVmCloudControlClient, buildZapVmExecArgs, createPlatformSandbox, hostPackageWriteRoots, NetworkProxy, DEFAULT_ALLOWED_DOMAINS, decideHost, type NetworkPolicy, createZapVmCloudExecutionBroker, deriveZapVmCloudComputerId, discoverZapVmCloudConfig, discoverZapVmInstallation, normalizeZapVmShellCommand, parseZapVmCloudConfig, readZapVmCapabilities, resolveZapVmGuestCwd, resolveZapVmNetworkPolicy, selectZapVmCloudConfigForWorkspace, type DefaultExecutionBrokerOptions, type PlatformSandboxOptions, type ExecutionBroker, type ExecutionBrokerRequest, type OsSandbox, type SandboxedCommand, type SandboxExecutionContext, type SandboxMode, type SandboxProviderKind, type SandboxStatus, type TransparentExecutionBrokerOptions, type ZapVmCloudConfig, type ZapVmCloudControlClient, type ZapVmCloudExecutionBrokerOptions, type ZapVmCloudFixedConfig, type ZapVmCloudLocalAutoConfig, type ZapVmCloudSubmit, type ZapVmCloudTask, type ZapVmCloudTaskEvent, type ZapVmInstallation, type ZapVmNetworkPolicy, type ZapVmRuntimeController, type ZapVmRuntimeOptions } from "./execution/index.js";
@@ -1,5 +1,15 @@
1
1
  import type { ToolDefinition } from "./types.js";
2
2
  import { isEffectivelyReadOnly, type ToolEffects } from "./effects.js";
3
+ import { destinationHostPattern } from "../execution/network-proxy.js";
4
+
5
+ /** A reusable unit of consent. File scopes are paths, network scopes are
6
+ * hosts, external scopes are the adapter's system name. */
7
+ export type CapabilityKind = "fs.write" | "fs.delete" | "net.read" | "net.write" | "external.read" | "external.write";
8
+
9
+ export interface ToolCapability {
10
+ readonly kind: CapabilityKind;
11
+ readonly scope: string;
12
+ }
3
13
 
4
14
  /** Host facts from the registered adapter, never model-supplied authority. */
5
15
  export interface ToolApprovalFacts {
@@ -11,6 +21,39 @@ export interface ToolApprovalFacts {
11
21
  readonly workspaceShell: boolean;
12
22
  /** undefined = not a shell tool; null = shell payload unavailable. */
13
23
  readonly shellCommands?: readonly string[] | null;
24
+ /** Every effect as a capability, or undefined when some effect has no
25
+ * reusable form (processes, wildcard destinations, destructive external
26
+ * operations, unknown effects). Such calls keep tool-level consent. */
27
+ readonly capabilities?: readonly ToolCapability[];
28
+ }
29
+
30
+ /** Same host grammar as shell declarations, so one grant covers both. */
31
+ function networkHost(destination: string): string | null {
32
+ return !destination || destination.includes("*") ? null : destinationHostPattern(destination);
33
+ }
34
+
35
+ /** Capabilities exactly covering the declared effects, or undefined. */
36
+ export function resolveToolCapabilities(effects: ToolEffects): readonly ToolCapability[] | undefined {
37
+ if (effects.confidence === "unknown" || effects.process.length > 0) return undefined;
38
+ const out: ToolCapability[] = [];
39
+ for (const effect of effects.filesystem) {
40
+ if (effect.operation === "read") continue;
41
+ const kind = effect.operation === "delete" ? "fs.delete" : "fs.write";
42
+ for (const path of effect.paths) out.push({ kind, scope: path });
43
+ }
44
+ for (const effect of effects.network) {
45
+ for (const destination of effect.destinations) {
46
+ const host = networkHost(destination);
47
+ if (!host) return undefined;
48
+ out.push({ kind: effect.operation === "mutate" ? "net.write" : "net.read", scope: host });
49
+ }
50
+ }
51
+ for (const effect of effects.external) {
52
+ if (effect.operation === "destructive" || !effect.system) return undefined;
53
+ out.push({ kind: effect.operation === "read" ? "external.read" : "external.write", scope: effect.system });
54
+ }
55
+ const seen = new Set<string>();
56
+ return Object.freeze(out.filter(cap => !seen.has(`${cap.kind}\0${cap.scope}`) && !!seen.add(`${cap.kind}\0${cap.scope}`)).map(cap => Object.freeze(cap)));
14
57
  }
15
58
 
16
59
  export function resolveToolApprovalFacts(definition: ToolDefinition, args: Record<string, unknown>, effects: ToolEffects): Readonly<ToolApprovalFacts> {
@@ -33,5 +76,6 @@ export function resolveToolApprovalFacts(definition: ToolDefinition, args: Recor
33
76
  // External effects are not contained by the workspace process sandbox.
34
77
  workspaceShell: shell && definition.executionLocation === "workspace" && effects.external.length === 0,
35
78
  ...(shell ? { shellCommands: commands } : {}),
79
+ ...(!shell ? { capabilities: resolveToolCapabilities(effects) } : {}),
36
80
  });
37
81
  }
@@ -49,12 +49,18 @@ export interface ApprovalContext {
49
49
  readonly shell: Readonly<ShellExecutionEnvironment>;
50
50
  readonly authorization?: Readonly<ToolApprovalFacts>;
51
51
  }
52
- export type ApprovalCallback = (
52
+ export type ApprovalCallback = ((
53
53
  toolName: string,
54
54
  args: Record<string, unknown>,
55
55
  signal?: AbortSignal,
56
56
  context?: Readonly<ApprovalContext>,
57
- ) => Promise<ApprovalResponse>;
57
+ ) => Promise<ApprovalResponse>) & {
58
+ /** Optional synchronous decision that needs no human. A settled answer skips
59
+ * the shared approval queue, so allowed calls never wait behind a prompt;
60
+ * undefined queues the call for `onApproval` as usual. Wrappers that do not
61
+ * forward it simply keep the queued path. */
62
+ precheck?: (toolName: string, args: Record<string, unknown>, context?: Readonly<ApprovalContext>) => ApprovalResponse | undefined;
63
+ };
58
64
 
59
65
  export type ApprovalLifecycleStatus =
60
66
  | "requested"
@@ -937,6 +943,18 @@ export class ToolExecutor {
937
943
  // the shared approval queue while awaiting them: other Agents need to
938
944
  // reach approval to release their own capacity.
939
945
  await notify("requested");
946
+ // Prechecks may log or notify, so a cancelled call never reaches one.
947
+ const settled = signal?.aborted ? undefined : onApproval.precheck?.(name, parsedArgs, approvalContext);
948
+ if (settled !== undefined) {
949
+ const approved = settled === true;
950
+ const denial = settled && typeof settled === "object" && settled.approved === false
951
+ && (settled.source === "policy" || settled.source === "approval")
952
+ && typeof settled.reason === "string" ? settled : undefined;
953
+ const reason = denial?.reason ?? "approval not granted";
954
+ await notify(approved ? "approved" : "denied", approved ? undefined : reason);
955
+ return approved ? true : { success: false, output: "", error: `Tool "${name}" denied: ${reason}`,
956
+ failure: operationFailure("POLICY_DENIED", denial?.source ?? "approval", approvalId) };
957
+ }
940
958
  const previousApproval = this.approvalQueue.current.catch(() => undefined);
941
959
  const approval = previousApproval.then(() => {
942
960
  if (signal?.aborted) throw new ExecutionBoundaryError("aborted", operationFailure("CANCELLED", "approval"));
@@ -1,4 +1,5 @@
1
1
  import { realpathSync } from "node:fs";
2
+ import { homedir, tmpdir } from "node:os";
2
3
  import { isAbsolute, relative, resolve, sep, dirname, basename, posix } from "node:path";
3
4
 
4
5
  export interface ShellSafetyContext {
@@ -183,6 +184,19 @@ function canonical(path: string): string | null {
183
184
  }
184
185
  }
185
186
 
187
+ /** Scratch roots whose strict descendants are not system paths. A root that is
188
+ * the home directory or one of its ancestors (an unusual TMPDIR) is ignored,
189
+ * and so is one holding the workspace, whose siblings may be other projects. */
190
+ function temporaryRoots(lexical: boolean): string[] {
191
+ if (lexical) return ["/tmp"];
192
+ const home = canonical(homedir());
193
+ return [...new Set([tmpdir(), "/tmp"].map(canonical))].filter((root): root is string => {
194
+ if (!root || root === resolve(root, "..")) return false;
195
+ const rel = home ? relative(root, home) : "..";
196
+ return rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel);
197
+ });
198
+ }
199
+
186
200
  function worldWritable(mode: string): boolean {
187
201
  if (/^[0-7]{3,4}$/.test(mode)) return (parseInt(mode, 8) & 2) !== 0;
188
202
  return mode.split(",").some(clause => /^(?:[ugoa]*[oa][ugoa]*|)[+=][rwxXst]*w/.test(clause));
@@ -245,6 +259,8 @@ function scopedRisk(
245
259
  const rel = paths.relative(root, path);
246
260
  return rel !== "" && rel !== ".." && !rel.startsWith(`..${paths.sep}`) && !paths.isAbsolute(rel);
247
261
  };
262
+ const scratch = temporaryRoots(context.pathResolution === "lexical")
263
+ .filter(tmp => !root || !(root === tmp || strictChild(root, tmp)));
248
264
  const stack: Array<Array<string | null>> = [];
249
265
  let words: Word[] = [];
250
266
  let documents: HereDocument[] = [];
@@ -360,7 +376,10 @@ function scopedRisk(
360
376
  const path = pathFrom(base, target);
361
377
  // A filesystem-root workspace cannot turn system-wide operations into
362
378
  // narrow project operations. The workspace itself is broad too.
363
- if (!root || root === paths.resolve(root, "..") || !path || !strictChild(path, root)) return id;
379
+ const inWorkspace = !!root && root !== paths.resolve(root, "..") && !!path && strictChild(path, root);
380
+ // Recursive removal under a scratch root is routine cleanup; chmod is not.
381
+ const inScratch = name === "rm" && !!path && scratch.some(tmp => strictChild(path, tmp));
382
+ if (!inWorkspace && !inScratch) return id;
364
383
  }
365
384
  }
366
385
  return null;