zapagent 1.14.24 → 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.
- package/package.json +1 -1
- package/src/App.tsx +4 -1
- package/src/agent/types.ts +2 -0
- package/src/agent-factory.ts +1 -1
- package/src/capabilities.ts +121 -0
- package/src/commands/dispatcher.ts +6 -2
- package/src/commands.ts +1 -1
- package/src/config.ts +10 -0
- package/src/execution-environment.ts +17 -7
- package/src/headless/approval.ts +45 -27
- package/src/headless/args.ts +6 -8
- package/src/headless/runHeadless.ts +5 -2
- package/src/hooks/useAgentObjects.ts +6 -1
- package/src/hooks/useAgentRunner.ts +4 -2
- package/src/hooks/usePermissionApproval.ts +40 -22
- package/src/permission-policy.ts +44 -2
- package/src/permissions.ts +240 -11
- package/src/readonly-commands.ts +31 -0
- package/src/request-capabilities-tool.ts +37 -0
- package/src/tool-grants.ts +2 -2
- package/src/ui/dialog-approval.tsx +22 -9
- package/src/ui/dialog-config.tsx +3 -3
- package/src/ui/dialog-permissions.tsx +2 -0
- package/zapsdk/builtin-tools/command.ts +19 -3
- package/zapsdk/builtin-tools/http.ts +3 -0
- package/zapsdk/builtin-tools/memory.ts +2 -2
- package/zapsdk/execution/broker.ts +10 -3
- package/zapsdk/execution/network-proxy.ts +15 -2
- package/zapsdk/execution/sandbox.ts +1 -0
- package/zapsdk/execution/types.ts +2 -0
- package/zapsdk/index.ts +1 -1
- package/zapsdk/tools/approval.ts +44 -0
- package/zapsdk/tools/executor.ts +20 -2
- package/zapsdk/utils/destructive-shell.ts +20 -1
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { z } from "zod"
|
|
2
|
+
import type { Tool, ToolResult } from "../zapsdk/tools/types.js"
|
|
3
|
+
import { emptyToolEffects } from "../zapsdk/tools/effects.js"
|
|
4
|
+
import { CAPABILITY_KINDS, MAX_REQUESTED_CAPABILITIES, REQUEST_CAPABILITIES_TOOL, capabilityPattern, describeCapabilityPatterns, parseCapabilityRequest } from "./capabilities.js"
|
|
5
|
+
|
|
6
|
+
/** Asks the user up front for what a task will need. The Host decides: the
|
|
7
|
+
* approval prompt saves the requested capability rules for the session or
|
|
8
|
+
* project, and deny/ask rules keep precedence over them. */
|
|
9
|
+
export function requestCapabilitiesTool(granted: (args: Record<string, unknown>) => boolean): Tool {
|
|
10
|
+
return {
|
|
11
|
+
definition: {
|
|
12
|
+
name: REQUEST_CAPABILITIES_TOOL,
|
|
13
|
+
description: "Ask the user once, before multi-step work, for the file edits, network hosts or external systems it will need, so later calls run without interrupting them.",
|
|
14
|
+
prompt: "Use only when a task will clearly need several approvals of the same kind (for example edits under src/** plus requests to one API host). " +
|
|
15
|
+
"Request the narrowest scopes that cover the work. File scopes are project-relative globs; net scopes are hosts (shell network_destinations need net.write); external scopes are systems such as mcp:<server>. " +
|
|
16
|
+
"This cannot authorize shell commands or running outside the sandbox. If the user declines, continue with ordinary per-call approval or ask them.",
|
|
17
|
+
parameters: z.object({
|
|
18
|
+
capabilities: z.array(z.object({
|
|
19
|
+
kind: z.enum(CAPABILITY_KINDS as [string, ...string[]]),
|
|
20
|
+
scope: z.string().min(1).max(200),
|
|
21
|
+
})).min(1).max(MAX_REQUESTED_CAPABILITIES),
|
|
22
|
+
reason: z.string().min(1).max(300).describe("What the task is and why it needs these capabilities"),
|
|
23
|
+
}),
|
|
24
|
+
permission: "confirm",
|
|
25
|
+
// Changes Host authorization state, so it is never read-only.
|
|
26
|
+
resolveEffects: () => ({ ...emptyToolEffects(), external: [{ kind: "external", system: "zapcode:permissions", operation: "mutate" }] }),
|
|
27
|
+
},
|
|
28
|
+
handler: async (args): Promise<ToolResult> => {
|
|
29
|
+
const requested = parseCapabilityRequest(args)
|
|
30
|
+
if (typeof requested === "string") return { success: false, output: "", error: requested }
|
|
31
|
+
const described = describeCapabilityPatterns(requested.map(capability => capabilityPattern(capability.kind, capability.scope)))
|
|
32
|
+
return granted(args)
|
|
33
|
+
? { success: true, output: `Granted: ${described}. Calls within these capabilities run without asking; deny/ask rules still apply and anything else still asks.` }
|
|
34
|
+
: { success: true, output: `Approved without saving: ${described}. Matching calls may still ask.` }
|
|
35
|
+
},
|
|
36
|
+
}
|
|
37
|
+
}
|
package/src/tool-grants.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { dirname, isAbsolute, join, relative, resolve } from "node:path"
|
|
2
2
|
import { homedir } from "node:os"
|
|
3
|
-
import { type PermissionRule } from "./permissions.js"
|
|
3
|
+
import { WORKSPACE_EDIT_TOOLS, type PermissionRule } from "./permissions.js"
|
|
4
4
|
import { canonicalizeWithNearestExistingAncestorSync } from "../zapsdk/builtin-tools/filesystem.js"
|
|
5
5
|
|
|
6
6
|
export interface ToolGrantRequest {
|
|
@@ -11,7 +11,7 @@ export interface ToolGrantRequest {
|
|
|
11
11
|
|
|
12
12
|
export const FILE_GRANT_TOOLS = ["read_file", "list_tree", "read_document", "search_files", "glob_files", "write_file", "create_file", "edit_file", "multi_edit", "delete_file", "move_file"]
|
|
13
13
|
export const READ_GRANT_TOOLS = ["read_file", "list_tree", "read_document", "search_files", "glob_files"]
|
|
14
|
-
export const EDIT_GRANT_TOOLS = [
|
|
14
|
+
export const EDIT_GRANT_TOOLS = [...WORKSPACE_EDIT_TOOLS]
|
|
15
15
|
|
|
16
16
|
function expandDirectory(value: string): string {
|
|
17
17
|
return value === "~" ? homedir() : value.startsWith("~/") ? join(homedir(), value.slice(2)) : value
|
|
@@ -27,7 +27,8 @@ import { useHideNativeCursor } from "./dialog-frame.js"
|
|
|
27
27
|
import { c } from "./theme.js"
|
|
28
28
|
import { ToolGrantDialog } from "./dialog-tool-grant.js"
|
|
29
29
|
import { suggestToolGrantDirectory, type ToolGrantRequest } from "../tool-grants.js"
|
|
30
|
-
import type
|
|
30
|
+
import { inferPattern, type PermissionRule } from "../permissions.js"
|
|
31
|
+
import { REQUEST_CAPABILITIES_TOOL, describeCapabilityPatterns } from "../capabilities.js"
|
|
31
32
|
import { formatToolCall, getToolAlias } from "./transcript-format.js"
|
|
32
33
|
|
|
33
34
|
export type ApprovalChoice = "once" | "always" | "forever" | "deny"
|
|
@@ -47,6 +48,8 @@ interface Props {
|
|
|
47
48
|
rulePreview?: string | null
|
|
48
49
|
unsandboxed?: boolean
|
|
49
50
|
allowScope?: boolean
|
|
51
|
+
/** One-time approvals of the same consent earlier this session. */
|
|
52
|
+
repeats?: number
|
|
50
53
|
availableTools?: string[]
|
|
51
54
|
cwd?: string
|
|
52
55
|
workspaceRoot?: string
|
|
@@ -58,7 +61,7 @@ interface Option {
|
|
|
58
61
|
label: string
|
|
59
62
|
}
|
|
60
63
|
|
|
61
|
-
export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed: escape, allowScope = true, availableTools = [], cwd, workspaceRoot, onGrant }: Props) {
|
|
64
|
+
export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed: escape, allowScope = true, repeats = 0, availableTools = [], cwd, workspaceRoot, onGrant }: Props) {
|
|
62
65
|
useHideNativeCursor()
|
|
63
66
|
// Three accept tiers ("once" / session-scoped "always" / persistent
|
|
64
67
|
// "forever") + deny. Both persistent consent and ordinary tool grants
|
|
@@ -66,13 +69,21 @@ export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed
|
|
|
66
69
|
// When rulePreview is provided, surface the actual saved pattern in
|
|
67
70
|
// both "always" and "forever" labels so the user sees the literal
|
|
68
71
|
// glob/prefix rather than a vague "in this session/project".
|
|
69
|
-
const
|
|
72
|
+
const capabilityText = rulePreview ? describeCapabilityPatterns(rulePreview.split(", ")) : null
|
|
73
|
+
const scopeText = capabilityText ?? (rulePreview
|
|
70
74
|
? rulePreview === toolName ? `${getToolAlias(toolName)} (entire tool)` : `${rulePreview}`
|
|
71
|
-
: `${getToolAlias(toolName)} commands`
|
|
75
|
+
: `${getToolAlias(toolName)} commands`)
|
|
72
76
|
const unsandboxed = escape ?? isUnsandboxedBash(toolName, args)
|
|
73
|
-
const
|
|
77
|
+
const request = toolName === REQUEST_CAPABILITIES_TOOL
|
|
78
|
+
const canCustomize = allowScope && !unsandboxed && !request && toolName !== "delegate_agent" && availableTools.includes(toolName) && !!onGrant
|
|
74
79
|
const directory = canCustomize ? suggestToolGrantDirectory(toolName, args, cwd) : undefined
|
|
75
|
-
|
|
80
|
+
// A capability request is only worth something when it is remembered.
|
|
81
|
+
const options: Option[] = request && allowScope ? [
|
|
82
|
+
{ value: "always", label: `Yes, allow ${scopeText} for this session` },
|
|
83
|
+
{ value: "forever", label: `Yes, allow ${scopeText} for this project` },
|
|
84
|
+
{ value: "deny", label: "No" },
|
|
85
|
+
]
|
|
86
|
+
: !allowScope
|
|
76
87
|
? [
|
|
77
88
|
{ value: "once", label: unsandboxed ? "Yes, run outside the sandbox this once" : "Yes, this once" },
|
|
78
89
|
{ value: "deny", label: "No" },
|
|
@@ -95,14 +106,14 @@ export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed
|
|
|
95
106
|
useInput((input, key) => {
|
|
96
107
|
if (input === "g" && canCustomize) { setDirectoryShortcut(false); setCustomizing(true); return }
|
|
97
108
|
if (input === "d" && directory) { setDirectoryShortcut(true); setCustomizing(true); return }
|
|
98
|
-
const directChoice = approvalChoiceForInput(input, key, idx, allowScope)
|
|
109
|
+
const directChoice = approvalChoiceForInput(input, key, idx, allowScope, options.map(option => option.value))
|
|
99
110
|
if (directChoice) { onChoose(directChoice); return }
|
|
100
111
|
if (key.upArrow) { setIdx(i => (i - 1 + options.length) % options.length); return }
|
|
101
112
|
if (key.downArrow) { setIdx(i => (i + 1) % options.length); return }
|
|
102
113
|
}, { isActive: !(customizing && canCustomize) })
|
|
103
114
|
|
|
104
115
|
if (customizing && canCustomize && onGrant) return <ToolGrantDialog availableTools={availableTools} initialTools={[toolName]}
|
|
105
|
-
initialPattern={rulePreview?.match(/^[^(]+\(([^()]*)\)$/)?.[1] ?? ""}
|
|
116
|
+
initialPattern={(capabilityText ? inferPattern(toolName, args, workspaceRoot ?? cwd ?? process.cwd()) : rulePreview)?.match(/^[^(]+\(([^()]*)\)$/)?.[1] ?? ""}
|
|
106
117
|
initialDirectory={directory} directoryShortcut={directoryShortcut} cwd={workspaceRoot}
|
|
107
118
|
onSave={(request, reviewedRules) => onGrant(request, availableTools, reviewedRules)} onCancel={() => setCustomizing(false)} />
|
|
108
119
|
|
|
@@ -121,6 +132,7 @@ export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed
|
|
|
121
132
|
{toolName === "bash" && ([ ["read_paths", "Additional read access"], ["write_paths", "Additional write access"] ] as const).map(([field, label]) =>
|
|
122
133
|
Array.isArray(args[field]) && args[field].length > 0
|
|
123
134
|
? <Text key={field} color={c.warning}>{label}: {JSON.stringify(args[field])}</Text> : null)}
|
|
135
|
+
{request && typeof args.reason === "string" && <Text color={c.text.secondary} wrap="truncate-end">{`Reason: ${args.reason.replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ")}`}</Text>}
|
|
124
136
|
{unsandboxed && <Text color={c.error}>Runs outside the OS sandbox: full access to your files and network.</Text>}
|
|
125
137
|
<Text color={c.warning} bold>Approve?</Text>
|
|
126
138
|
<Box flexDirection="column">
|
|
@@ -136,6 +148,7 @@ export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed
|
|
|
136
148
|
)
|
|
137
149
|
})}
|
|
138
150
|
</Box>
|
|
151
|
+
{allowScope && !unsandboxed && !request && repeats >= 2 && <Text color={c.text.muted}>{`Approved ${repeats} times this session; 2 stops asking for the rest of it`}</Text>}
|
|
139
152
|
{canCustomize && <Text color={c.text.muted}>g customize scope / select tools</Text>}
|
|
140
153
|
{directory && <Text color={c.text.muted}>d authorize folder / select tools: {directory}</Text>}
|
|
141
154
|
</Box>
|
|
@@ -151,9 +164,9 @@ export function approvalChoiceForInput(
|
|
|
151
164
|
key: { escape?: boolean; return?: boolean },
|
|
152
165
|
selectedIndex: number,
|
|
153
166
|
allowScope = true,
|
|
167
|
+
choices: readonly ApprovalChoice[] = allowScope ? APPROVAL_CHOICES : ["once", "deny"],
|
|
154
168
|
): ApprovalChoice | null {
|
|
155
169
|
if (key.escape) return "deny"
|
|
156
|
-
const choices: ApprovalChoice[] = allowScope ? APPROVAL_CHOICES : ["once", "deny"]
|
|
157
170
|
const prefix = commandInput(input, key)
|
|
158
171
|
if (prefix !== null && /^[1-9]$/.test(prefix)) return choices[Number(prefix) - 1] ?? null
|
|
159
172
|
if (isReturnInput(input, key)) return choices[selectedIndex] ?? null
|
package/src/ui/dialog-config.tsx
CHANGED
|
@@ -26,10 +26,10 @@ interface DialogProps {
|
|
|
26
26
|
|
|
27
27
|
// ── Mode picker ──────────────────────────────────────────────────────────
|
|
28
28
|
const MODES: { id: PermissionMode; label: string; meta: string }[] = [
|
|
29
|
-
{ id: "default", label: "default", meta: "ask before write/edit/exec" },
|
|
30
|
-
{ id: "acceptEdits", label: "acceptEdits", meta: "auto-approve file edits" },
|
|
29
|
+
{ id: "default", label: "default", meta: "strict: ask before write/edit/exec" },
|
|
30
|
+
{ id: "acceptEdits", label: "acceptEdits", meta: "balanced: auto-approve file edits" },
|
|
31
31
|
{ id: "plan", label: "plan", meta: "research only — no edits or commands" },
|
|
32
|
-
{ id: "bypassPermissions", label: "bypassPermissions", meta: "auto-approve everything (use with care)" },
|
|
32
|
+
{ id: "bypassPermissions", label: "bypassPermissions", meta: "autonomous: auto-approve everything (use with care)" },
|
|
33
33
|
]
|
|
34
34
|
|
|
35
35
|
export function ModeDialog({ config, onCommit, onCancel }: DialogProps) {
|
|
@@ -24,6 +24,7 @@ import { truncateToWidth } from "./truncate.js"
|
|
|
24
24
|
import { ToolGrantDialog } from "./dialog-tool-grant.js"
|
|
25
25
|
import { buildToolGrantRules } from "../tool-grants.js"
|
|
26
26
|
import { commandInput } from "./controlled-input.js"
|
|
27
|
+
import { describeCapabilityPatterns } from "../capabilities.js"
|
|
27
28
|
|
|
28
29
|
interface Props { onCancel: () => void; availableTools: string[] }
|
|
29
30
|
|
|
@@ -182,6 +183,7 @@ export function PermissionsDialog({ onCancel, availableTools }: Props) {
|
|
|
182
183
|
{truncateToWidth(rule.pattern, 60)}
|
|
183
184
|
</Text>
|
|
184
185
|
{rule.canonicalPath && <Text color={c.text.ghost}> (fixed folder target)</Text>}
|
|
186
|
+
{describeCapabilityPatterns([rule.pattern]) && <Text color={c.text.ghost} wrap="truncate-end"> — {describeCapabilityPatterns([rule.pattern])}</Text>}
|
|
185
187
|
{shadowedBy && (
|
|
186
188
|
<Text color={c.text.ghost} wrap="truncate-end">
|
|
187
189
|
{truncateToWidth(` ⤴ shadowed by ${shadowedBy.rule.type} ${shadowedBy.rule.pattern} (${shadowedBy.scope})`, 70)}
|
|
@@ -43,6 +43,9 @@ export interface ExecuteCommandOptions {
|
|
|
43
43
|
workspaceOnly?: boolean;
|
|
44
44
|
/** Expose destination declarations for a restricted execution backend. */
|
|
45
45
|
restrictedNetwork?: boolean;
|
|
46
|
+
/** The host sandbox filters egress through an allowlist: offer
|
|
47
|
+
* network_destinations for other hosts, which the host approves. */
|
|
48
|
+
declaredNetwork?: boolean;
|
|
46
49
|
/** Offer the per-call `dangerouslyDisableSandbox` retry. Defaults to true;
|
|
47
50
|
* hosts set false when a backend (VM) or policy has no sandbox escape. */
|
|
48
51
|
allowUnsandboxed?: boolean;
|
|
@@ -196,6 +199,12 @@ export function executeCommandTool(options: ExecuteCommandOptions = {}): Tool {
|
|
|
196
199
|
.max(128)
|
|
197
200
|
.optional()
|
|
198
201
|
.describe("Exact HTTP(S) URLs, domains, or wildcard subdomains requested by this command; subject to the execution backend's network policy"),
|
|
202
|
+
} : options.declaredNetwork ? {
|
|
203
|
+
network_destinations: z
|
|
204
|
+
.array(z.string().min(1).max(253))
|
|
205
|
+
.max(16)
|
|
206
|
+
.optional()
|
|
207
|
+
.describe("Hosts outside the sandbox network allowlist this command must reach (api.example.com or *.example.com); each needs approval once"),
|
|
199
208
|
} : {}),
|
|
200
209
|
});
|
|
201
210
|
|
|
@@ -245,6 +254,12 @@ export function executeCommandTool(options: ExecuteCommandOptions = {}): Tool {
|
|
|
245
254
|
"No sleep/ps polling. Exit sends a <task-notification>. For logs, use task_status: task_id with include_output=true (tail) or output_offset=0 (pages). outputFile grants no read_file access. Wait only for dependencies.",
|
|
246
255
|
]
|
|
247
256
|
: [];
|
|
257
|
+
if (options.declaredNetwork) {
|
|
258
|
+
promptLines.push(
|
|
259
|
+
"",
|
|
260
|
+
"Sandboxed network reaches an allowlist (package registries, git hosts, common CDNs). For another host, declare it in network_destinations; the user approves each host once and the command stays sandboxed. Do not use dangerouslyDisableSandbox for network access.",
|
|
261
|
+
);
|
|
262
|
+
}
|
|
248
263
|
if (options.restrictedNetwork) {
|
|
249
264
|
promptLines.push(
|
|
250
265
|
"",
|
|
@@ -294,7 +309,7 @@ export function executeCommandTool(options: ExecuteCommandOptions = {}): Tool {
|
|
|
294
309
|
(args.cwd as string | undefined) ?? options.defaultCwd ?? context.cwd,
|
|
295
310
|
options.defaultCwd ?? context.cwd,
|
|
296
311
|
);
|
|
297
|
-
const declaredDestinations = options.restrictedNetwork
|
|
312
|
+
const declaredDestinations = (options.restrictedNetwork || options.declaredNetwork)
|
|
298
313
|
&& Array.isArray((args as { network_destinations?: unknown }).network_destinations)
|
|
299
314
|
? ((args as { network_destinations: string[] }).network_destinations)
|
|
300
315
|
: [];
|
|
@@ -305,10 +320,11 @@ export function executeCommandTool(options: ExecuteCommandOptions = {}): Tool {
|
|
|
305
320
|
{ kind: "filesystem", operation: "read", paths: [accessRoot, ...((args.read_paths ?? []) as string[]).map(path => resolveToolPathCanonical(path, cwd))] },
|
|
306
321
|
{ kind: "filesystem", operation: "modify", paths: [accessRoot, ...((args.write_paths ?? []) as string[]).map(path => resolveToolPathCanonical(path, cwd))] },
|
|
307
322
|
],
|
|
308
|
-
network: declaredDestinations.length > 0
|
|
323
|
+
network: options.restrictedNetwork && declaredDestinations.length > 0
|
|
309
324
|
? [{ kind: "network", operation: "connect", destinations: declaredDestinations, methods: [] }]
|
|
310
325
|
: options.sandboxNetwork === true
|
|
311
|
-
|
|
326
|
+
// The proxy still filters "*" through its allowlist; declared hosts extend it.
|
|
327
|
+
? [{ kind: "network", operation: "connect", destinations: ["*", ...declaredDestinations], methods: [] }]
|
|
312
328
|
: [],
|
|
313
329
|
process: [{
|
|
314
330
|
kind: "process",
|
|
@@ -185,6 +185,9 @@ async function fetchWithValidatedRedirects(
|
|
|
185
185
|
request = { ...request, method: "GET", body: null, headers };
|
|
186
186
|
}
|
|
187
187
|
const next = await assertSafePublicHttpUrl(new URL(location, current).toString(), options.resolveHostname);
|
|
188
|
+
// Consent is per host: a body approved for one host is never replayed to
|
|
189
|
+
// another. Return the redirect itself instead of following it.
|
|
190
|
+
if (next.host !== current.host && request.body != null) return { response, finalUrl: current };
|
|
188
191
|
if (next.origin !== current.origin) {
|
|
189
192
|
// Fetch drops Authorization on cross-origin redirects; never hand caller
|
|
190
193
|
// credentials to a host the caller did not name. Not restored on return.
|
|
@@ -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
|
|
65
|
-
*
|
|
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;
|
|
@@ -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.
|
|
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: ["
|
|
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
|
-
|
|
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
|
-
+ "
|
|
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";
|
package/zapsdk/tools/approval.ts
CHANGED
|
@@ -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
|
}
|
package/zapsdk/tools/executor.ts
CHANGED
|
@@ -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
|
-
|
|
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;
|