zapagent 1.14.24 → 1.14.26

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 (43) hide show
  1. package/package.json +1 -1
  2. package/src/App.tsx +4 -1
  3. package/src/agent/contextAttachments.ts +4 -2
  4. package/src/agent/types.ts +2 -0
  5. package/src/agent-factory.ts +3 -11
  6. package/src/capabilities.ts +121 -0
  7. package/src/commands/dispatcher.ts +6 -2
  8. package/src/commands.ts +1 -1
  9. package/src/config.ts +10 -0
  10. package/src/execution-environment.ts +17 -7
  11. package/src/headless/approval.ts +45 -27
  12. package/src/headless/args.ts +6 -8
  13. package/src/headless/goalPhase.ts +3 -3
  14. package/src/headless/runHeadless.ts +9 -7
  15. package/src/hooks/useAgentObjects.ts +6 -1
  16. package/src/hooks/useAgentRunner.ts +4 -2
  17. package/src/hooks/usePermissionApproval.ts +40 -22
  18. package/src/permission-policy.ts +44 -2
  19. package/src/permissions.ts +240 -11
  20. package/src/readonly-commands.ts +31 -0
  21. package/src/request-capabilities-tool.ts +37 -0
  22. package/src/singletons.ts +4 -14
  23. package/src/tool-grants.ts +2 -2
  24. package/src/ui/dialog-approval.tsx +22 -9
  25. package/src/ui/dialog-config.tsx +3 -3
  26. package/src/ui/dialog-permissions.tsx +2 -0
  27. package/src/ui/dialog-rewind.tsx +1 -1
  28. package/zapsdk/agent/loop.ts +51 -4
  29. package/zapsdk/agent/tool-execution-guards.ts +23 -37
  30. package/zapsdk/builtin-tools/command.ts +19 -3
  31. package/zapsdk/builtin-tools/http.ts +3 -0
  32. package/zapsdk/builtin-tools/index.ts +11 -16
  33. package/zapsdk/builtin-tools/memory.ts +2 -2
  34. package/zapsdk/builtin-tools/plan-mode.ts +1 -1
  35. package/zapsdk/builtin-tools/subagent.ts +2 -2
  36. package/zapsdk/execution/broker.ts +10 -3
  37. package/zapsdk/execution/network-proxy.ts +15 -2
  38. package/zapsdk/execution/sandbox.ts +1 -0
  39. package/zapsdk/execution/types.ts +2 -0
  40. package/zapsdk/index.ts +1 -1
  41. package/zapsdk/tools/approval.ts +44 -0
  42. package/zapsdk/tools/executor.ts +20 -2
  43. package/zapsdk/utils/destructive-shell.ts +20 -1
@@ -3,27 +3,24 @@ import {
3
3
  readFileTool,
4
4
  writeFileTool,
5
5
  deleteFileTool,
6
- moveFileTool,
7
6
  type ReadFileOptions,
8
7
  type WriteFileOptions,
9
8
  type DeleteFileOptions,
10
- type MoveFileOptions,
11
9
  } from "./filesystem.js";
12
10
  import { editFileTool, type EditFileOptions } from "./edit.js";
13
11
  import { multiEditTool, type MultiEditOptions } from "./multi-edit.js";
14
12
  import { listTreeTool, type ListTreeOptions } from "./list-tree.js";
15
13
  import { executeCommandTool, type ExecuteCommandOptions } from "./command.js";
16
- import { httpFetchTool, httpRequestTool, type HttpFetchOptions } from "./http.js";
14
+ import { httpFetchTool, type HttpFetchOptions } from "./http.js";
17
15
  import { searchFilesTool, type SearchFilesOptions } from "./search.js";
18
16
  import { globFilesTool, type GlobFilesOptions } from "./glob.js";
19
17
  import { webSearchTool, type WebSearchOptions } from "./web-search.js";
20
- import { currentTimeTool } from "./time.js";
21
18
  import { readDocumentTool, readPdfTool, readDocxTool, type DocumentReadOptions } from "./document.js";
22
19
  import { todoWriteTool, type TodoWriteToolOptions, type TodoStore, type Todo, type TodoStatus } from "./todo.js";
23
20
  import { askUserQuestionTool, type AskUserToolOptions } from "./ask-user.js";
24
21
  import { generateImageTool, type GenerateImageOptions } from "./generate-image.js";
25
22
  import { browserScreenshotTool, type BrowserScreenshotOptions } from "./browser.js";
26
- import { enterPlanModeTool, exitPlanModeTool, type PlanModeToolsOptions, type PlanModeCallbacks } from "./plan-mode.js";
23
+ import { exitPlanModeTool, type PlanModeToolsOptions } from "./plan-mode.js";
27
24
  import { skillTool, type SkillToolOptions } from "./skill.js";
28
25
  import type { CronToolsHandle } from "./cron.js";
29
26
  import type { MonitorToolHandle } from "./monitor.js";
@@ -90,10 +87,8 @@ export interface BuiltinToolsOptions {
90
87
  editFile?: EditFileOptions;
91
88
  multiEdit?: MultiEditOptions;
92
89
  deleteFile?: DeleteFileOptions;
93
- moveFile?: MoveFileOptions;
94
90
  executeCommand?: ExecuteCommandOptions;
95
91
  httpFetch?: HttpFetchOptions;
96
- httpRequest?: HttpFetchOptions;
97
92
  searchFiles?: SearchFilesOptions;
98
93
  globFiles?: GlobFilesOptions;
99
94
  listTree?: ListTreeOptions;
@@ -106,8 +101,10 @@ export interface BuiltinToolsOptions {
106
101
  * subagent registries), `todo_write` is not registered — mirrors CCB's
107
102
  * "todos are main-agent-only" choice. */
108
103
  todoWrite?: TodoWriteToolOptions;
109
- /** Required for the main agent to get `enter_plan_mode` / `exit_plan_mode`.
110
- * Omit to skip registration (subagent registries don't manage plan mode). */
104
+ /** Required for the main agent to get `exit_plan_mode`. Omit to skip
105
+ * registration (subagent registries don't manage plan mode). Entering plan
106
+ * mode is a user action; register `enterPlanModeTool` explicitly to let the
107
+ * model request it. */
111
108
  planMode?: PlanModeToolsOptions;
112
109
  /** Main agent in an interactive UI only. Omit (headless, subagents) to leave
113
110
  * `ask_user_question` unregistered: nobody is there to answer. */
@@ -140,6 +137,10 @@ export interface BuiltinToolsOptions {
140
137
  exclude?: string[];
141
138
  }
142
139
 
140
+ /** Registers the core tool set. Specialized tools (`move_file`, `http_request`,
141
+ * `current_time`, `enter_plan_mode`, cron, monitor) remain exported for hosts
142
+ * that register them explicitly; each one the model sees costs prompt tokens
143
+ * on every request and widens its choice of tools. */
143
144
  export function createBuiltinRegistry(options: BuiltinToolsOptions = {}): ToolRegistry {
144
145
  const registry = new ToolRegistry();
145
146
  const exclude = new Set(options.exclude ?? []);
@@ -150,25 +151,19 @@ export function createBuiltinRegistry(options: BuiltinToolsOptions = {}): ToolRe
150
151
  if (!exclude.has("edit_file")) registry.register(editFileTool({ defaultCwd, ...options.editFile }));
151
152
  if (!exclude.has("multi_edit")) registry.register(multiEditTool({ defaultCwd, ...options.multiEdit }));
152
153
  if (!exclude.has("delete_file")) registry.register(deleteFileTool({ defaultCwd, ...options.deleteFile }));
153
- if (!exclude.has("move_file")) registry.register(moveFileTool({ defaultCwd, ...options.moveFile }));
154
154
  if (!exclude.has("list_tree")) registry.register(listTreeTool({ defaultCwd, ...options.listTree }));
155
155
  if (options.generateImage && !exclude.has("generate_image")) registry.register(generateImageTool({ defaultCwd, ...options.generateImage }));
156
156
  if (!exclude.has("bash")) registry.register(executeCommandTool(options.executeCommand));
157
157
  if (!exclude.has("http_fetch")) registry.register(httpFetchTool(options.httpFetch));
158
- if (!exclude.has("http_request")) registry.register(httpRequestTool(options.httpRequest));
159
158
  if (!exclude.has("search_files")) registry.register(searchFilesTool({ defaultCwd, ...options.searchFiles }));
160
159
  if (!exclude.has("glob_files")) registry.register(globFilesTool({ defaultCwd, ...options.globFiles }));
161
160
  if (!exclude.has("web_search")) registry.register(webSearchTool(options.webSearch));
162
- if (!exclude.has("current_time")) registry.register(currentTimeTool());
163
161
  if (!exclude.has("browser_screenshot")) registry.register(browserScreenshotTool({ defaultCwd, ...options.browserScreenshot }));
164
162
  if (!exclude.has("read_document")) registry.register(readDocumentTool({ defaultCwd, ...options.documentRead }));
165
163
  if (options.todoWrite && !exclude.has("todo_write")) {
166
164
  registry.register(todoWriteTool(options.todoWrite));
167
165
  }
168
- if (options.planMode) {
169
- if (!exclude.has("enter_plan_mode")) registry.register(enterPlanModeTool(options.planMode));
170
- if (!exclude.has("exit_plan_mode")) registry.register(exitPlanModeTool(options.planMode));
171
- }
166
+ if (options.planMode && !exclude.has("exit_plan_mode")) registry.register(exitPlanModeTool(options.planMode));
172
167
  if (options.askUser && !exclude.has("ask_user_question")) registry.register(askUserQuestionTool(options.askUser));
173
168
  if (options.skill && !exclude.has("skill")) {
174
169
  registry.register(skillTool(options.skill));
@@ -61,8 +61,8 @@ const MEMORY_TIMESTAMP_SCHEMA = z.string().min(1).max(80).refine(
61
61
  * - project — facts about the current project not derivable from code/git
62
62
  * - reference — pointers to external systems (Linear, Slack, dashboards)
63
63
  *
64
- * Permission default is `confirm` so the user sees what's being saved on first
65
- * write. Allow via `/permissions allow memory_save` to skip prompts after vetting.
64
+ * Permission is `confirm`; the zapcode host allows project/reference writes
65
+ * and asks for global user/feedback writes. Other hosts decide for themselves.
66
66
  */
67
67
  export function memorySaveTool(options: MemorySaveToolOptions): Tool {
68
68
  const { store, globalStore } = options;
@@ -105,7 +105,7 @@ export function exitPlanModeTool(options: PlanModeToolsOptions): Tool {
105
105
  success: false,
106
106
  output: "",
107
107
  error:
108
- "Not in plan mode — nothing to exit. Call `enter_plan_mode` first if you want to design before implementing.",
108
+ "Not in plan mode — nothing to exit. Present the plan in your reply instead; the user enters plan mode with /mode plan.",
109
109
  };
110
110
  }
111
111
  const plan = args.plan as string;
@@ -282,12 +282,12 @@ export function readOnlyBashTool(defaultCwd?: string): Tool {
282
282
 
283
283
  const EXPLORE_TOOLS = new Set([
284
284
  "read_file", "glob_files", "search_files", "list_tree",
285
- "web_search", "http_fetch", "current_time", "bash",
285
+ "web_search", "http_fetch", "bash",
286
286
  ]);
287
287
 
288
288
  const PLAN_TOOLS = new Set([
289
289
  "read_file", "glob_files", "search_files", "list_tree",
290
- "web_search", "http_fetch", "current_time", "bash",
290
+ "web_search", "http_fetch", "bash",
291
291
  ]);
292
292
 
293
293
  type Thoroughness = "quick" | "medium" | "thorough";
@@ -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;