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.
- package/package.json +1 -1
- package/src/App.tsx +6 -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 +44 -25
- package/src/model-catalog.ts +54 -0
- package/src/permission-policy.ts +49 -7
- package/src/permissions.ts +254 -21
- package/src/readonly-commands.ts +31 -0
- package/src/request-capabilities-tool.ts +37 -0
- package/src/tool-grants.ts +45 -6
- package/src/ui/dialog-approval.tsx +33 -12
- package/src/ui/dialog-config.tsx +3 -3
- package/src/ui/dialog-model.tsx +88 -67
- package/src/ui/dialog-permissions.tsx +8 -5
- package/src/ui/dialog-tool-grant.tsx +25 -15
- 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
package/package.json
CHANGED
package/src/App.tsx
CHANGED
|
@@ -38,7 +38,7 @@ import { useAgentRunner } from "./hooks/useAgentRunner.js"
|
|
|
38
38
|
import { useToasts } from "./hooks/useToasts.js"
|
|
39
39
|
import { useUpdateCheck } from "./hooks/useUpdateCheck.js"
|
|
40
40
|
import { UpdateNotice } from "./ui/UpdateNotice.js"
|
|
41
|
-
import { autoMemory, appLogger, agentLogger, conversation, tokenAccounting } from "./singletons.js"
|
|
41
|
+
import { autoMemory, appLogger, agentLogger, conversation, permissionManager, tokenAccounting } from "./singletons.js"
|
|
42
42
|
import { CheckpointManager } from "../zapsdk/checkpoint/index.js"
|
|
43
43
|
import { type Todo, type TodoStore } from "../zapsdk/index.js"
|
|
44
44
|
import { loadAllSkills } from "../zapsdk/skills/loader.js"
|
|
@@ -714,6 +714,7 @@ export function App() {
|
|
|
714
714
|
try {
|
|
715
715
|
return await runAgent(text, systemPrompt, images, memoryQueryText ?? displayText ?? text, {
|
|
716
716
|
propagateErrors: true,
|
|
717
|
+
keepTurnDenials: silent,
|
|
717
718
|
onInputAccepted: () => {
|
|
718
719
|
onAccepted?.()
|
|
719
720
|
if (silent) addLog("task-notification", text)
|
|
@@ -730,6 +731,7 @@ export function App() {
|
|
|
730
731
|
onSteeringAccepted: input => {
|
|
731
732
|
const entry = steering.get(input.id)
|
|
732
733
|
if (!entry) return
|
|
734
|
+
permissionManager.startTurn()
|
|
733
735
|
const warning = queue.acknowledge(entry.id, entry.sessionId)
|
|
734
736
|
if (warning) addLog("error", warning)
|
|
735
737
|
logUser(entry.displayForm, entry.restoreText, entry.images?.map(image => image.content))
|
|
@@ -1130,10 +1132,13 @@ export function App() {
|
|
|
1130
1132
|
args={pendingApproval.args}
|
|
1131
1133
|
onChoose={pendingApproval.resolve}
|
|
1132
1134
|
allowScope={pendingApproval.allowScope}
|
|
1135
|
+
repeats={pendingApproval.repeats}
|
|
1133
1136
|
onGrant={pendingApproval.grant}
|
|
1134
1137
|
availableTools={agentRef.current.registry.definitions().filter(tool => tool.permission === "confirm").map(tool => tool.name)}
|
|
1135
1138
|
unsandboxed={approvalFacts(pendingApproval.name, pendingApproval.args, pendingApproval.context).sandboxEscape}
|
|
1136
1139
|
rulePreview={inferInvocationRules(pendingApproval.name, pendingApproval.args, process.cwd(), pendingApproval.context).map(rule => rule.pattern).join(", ") || null}
|
|
1140
|
+
cwd={pendingApproval.context?.cwd}
|
|
1141
|
+
workspaceRoot={pendingApproval.context?.workspaceRoot}
|
|
1137
1142
|
/>
|
|
1138
1143
|
)}
|
|
1139
1144
|
{!inModal && pendingPlan && <PlanApprovalBar plan={pendingPlan.plan} onChoose={pendingPlan.resolve} />}
|
package/src/agent/types.ts
CHANGED
|
@@ -11,6 +11,8 @@ export interface AgentObjects {
|
|
|
11
11
|
executionCapacity?: ExecutionCapacityFacts
|
|
12
12
|
/** Commands run inside the OS sandbox or the VM (see PermissionManager). */
|
|
13
13
|
sandboxConfined: boolean
|
|
14
|
+
/** The allowlist the sandbox proxy enforces, when it enforces one. */
|
|
15
|
+
sandboxNetworkPolicy?: import("../../zapsdk/execution/network-proxy.js").NetworkPolicy
|
|
14
16
|
/** Rebuilds cwd-sensitive builtin tools while preserving live MCP/plugin
|
|
15
17
|
* registrations. Used by isolated writing subagents. */
|
|
16
18
|
createRegistryForCwd?: (cwd: string) => ToolRegistry
|
package/src/agent-factory.ts
CHANGED
|
@@ -285,5 +285,5 @@ export function buildAgentObjects(
|
|
|
285
285
|
postProcess: createMemoryReadPostProcess({ autoMemory, globalMemoryDir }),
|
|
286
286
|
})
|
|
287
287
|
|
|
288
|
-
return { provider, registry, executor, modelId: model, cwd: effectiveCwd, createRegistryForCwd, executionFacts: environment.facts, executionCapacity: environment.capacity, sandboxConfined }
|
|
288
|
+
return { provider, registry, executor, modelId: model, cwd: effectiveCwd, createRegistryForCwd, executionFacts: environment.facts, executionCapacity: environment.capacity, sandboxConfined, sandboxNetworkPolicy: environment.sandboxNetworkPolicy }
|
|
289
289
|
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import type { CapabilityKind, ToolCapability } from "../zapsdk/tools/approval.js"
|
|
2
|
+
import { destinationHostPattern } from "../zapsdk/execution/network-proxy.js"
|
|
3
|
+
|
|
4
|
+
// Capability rules are stored as ordinary `{ pattern, type }` rules with the
|
|
5
|
+
// pattern `Capability(<kind>:<scope>)`. They never match a tool name, so older
|
|
6
|
+
// versions read them as inert rules.
|
|
7
|
+
|
|
8
|
+
export const CAPABILITY_KINDS: readonly CapabilityKind[] = ["fs.write", "fs.delete", "net.read", "net.write", "external.read", "external.write"]
|
|
9
|
+
const RULE = /^Capability\(([a-z.]+):(.+)\)$/
|
|
10
|
+
|
|
11
|
+
export function capabilityPattern(kind: CapabilityKind, scope: string): string {
|
|
12
|
+
return `Capability(${kind}:${scope})`
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function parseCapabilityPattern(pattern: string): ToolCapability | null {
|
|
16
|
+
const match = RULE.exec(pattern)
|
|
17
|
+
if (!match || !CAPABILITY_KINDS.includes(match[1] as CapabilityKind) || /[\r\n\0]/.test(match[2]!)) return null
|
|
18
|
+
return { kind: match[1] as CapabilityKind, scope: match[2]! }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function isFileCapability(kind: CapabilityKind): boolean {
|
|
22
|
+
return kind === "fs.write" || kind === "fs.delete"
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Host and system scopes: `*` matches any run of characters, nothing else is special. */
|
|
26
|
+
export function matchCapabilityScope(value: string, pattern: string): boolean {
|
|
27
|
+
// Greedy two-pointer glob: linear in practice, no regex backtracking.
|
|
28
|
+
const text = value.toLowerCase(), glob = pattern.toLowerCase()
|
|
29
|
+
let t = 0, g = 0, star = -1, mark = 0
|
|
30
|
+
while (t < text.length) {
|
|
31
|
+
if (g < glob.length && glob[g] !== "*" && glob[g] === text[t]) { t++; g++ }
|
|
32
|
+
else if (g < glob.length && glob[g] === "*") { star = g++; mark = t }
|
|
33
|
+
else if (star >= 0) { g = star + 1; t = ++mark }
|
|
34
|
+
else return false
|
|
35
|
+
}
|
|
36
|
+
while (glob[g] === "*") g++
|
|
37
|
+
return g === glob.length
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The content-editing tools; one `fs.write` consent covers all of them. */
|
|
41
|
+
export const WORKSPACE_EDIT_TOOLS: readonly string[] = ["write_file", "create_file", "edit_file", "multi_edit"]
|
|
42
|
+
const FILE_WRITE_TOOLS = new Set(WORKSPACE_EDIT_TOOLS)
|
|
43
|
+
|
|
44
|
+
/** File tools a capability can stand in for; their tool rules restrict it too. */
|
|
45
|
+
export function capabilityFileTools(kind: CapabilityKind): readonly string[] {
|
|
46
|
+
return kind === "fs.write" ? [...WORKSPACE_EDIT_TOOLS, "move_file"] : kind === "fs.delete" ? ["delete_file", "move_file"] : []
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Built-in file tools are judged from their arguments, like their tool rules,
|
|
50
|
+
* so a shell's write_paths check never borrows the shell's own facts. */
|
|
51
|
+
export function fileToolCapabilities(name: string, args: Record<string, unknown>): ToolCapability[] | undefined {
|
|
52
|
+
const path = (key: string) => typeof args[key] === "string" && args[key] ? args[key] as string : null
|
|
53
|
+
if (FILE_WRITE_TOOLS.has(name)) {
|
|
54
|
+
const target = path("path")
|
|
55
|
+
return target ? [{ kind: "fs.write", scope: target }] : undefined
|
|
56
|
+
}
|
|
57
|
+
if (name === "delete_file") {
|
|
58
|
+
const target = path("path")
|
|
59
|
+
return target ? [{ kind: "fs.delete", scope: target }] : undefined
|
|
60
|
+
}
|
|
61
|
+
if (name === "move_file") {
|
|
62
|
+
const source = path("source"), destination = path("destination")
|
|
63
|
+
return source && destination ? [{ kind: "fs.delete", scope: source }, { kind: "fs.write", scope: destination }] : undefined
|
|
64
|
+
}
|
|
65
|
+
return []
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function describeOne(capability: ToolCapability): string {
|
|
69
|
+
const { kind, scope } = capability
|
|
70
|
+
const where = scope === "**" ? "anywhere in this project" : `in ${scope.replace(/\/\*\*$/, "")}`
|
|
71
|
+
switch (kind) {
|
|
72
|
+
case "fs.write": return `file edits ${where}`
|
|
73
|
+
case "fs.delete": return `file deletes ${where}`
|
|
74
|
+
case "net.read": return `network reads from ${scope}`
|
|
75
|
+
case "net.write": return `network access to ${scope} (send and receive)`
|
|
76
|
+
case "external.read": return scope.startsWith("mcp:") ? `read-only tools of MCP server ${scope.slice(4)}` : `reads from ${scope}`
|
|
77
|
+
case "external.write": return scope.startsWith("mcp:") ? `changes through MCP server ${scope.slice(4)}` : `changes through ${scope}`
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Plain-language summary for an approval label; other rules stay as written.
|
|
82
|
+
* Null when no rule is a capability. */
|
|
83
|
+
export function describeCapabilityPatterns(patterns: readonly string[]): string | null {
|
|
84
|
+
const capabilities = patterns.map(parseCapabilityPattern)
|
|
85
|
+
if (!capabilities.some(Boolean)) return null
|
|
86
|
+
return capabilities.map((capability, index) => capability ? describeOne(capability) : patterns[index]).join(", ")
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export const REQUEST_CAPABILITIES_TOOL = "request_capabilities"
|
|
90
|
+
export const MAX_REQUESTED_CAPABILITIES = 8
|
|
91
|
+
|
|
92
|
+
/** Capabilities `request_capabilities` asks for, in rule form, or why they
|
|
93
|
+
* cannot be granted. Files stay project-relative; hosts and systems are
|
|
94
|
+
* named exactly or by `*.` subdomain, never by `*` alone. */
|
|
95
|
+
export function parseCapabilityRequest(args: Record<string, unknown>): ToolCapability[] | string {
|
|
96
|
+
const list = args.capabilities
|
|
97
|
+
if (!Array.isArray(list) || !list.length) return "request at least one capability"
|
|
98
|
+
if (list.length > MAX_REQUESTED_CAPABILITIES) return `request at most ${MAX_REQUESTED_CAPABILITIES} capabilities`
|
|
99
|
+
const parsed: ToolCapability[] = []
|
|
100
|
+
for (const item of list) {
|
|
101
|
+
const kind = (item as { kind?: unknown })?.kind, raw = (item as { scope?: unknown })?.scope
|
|
102
|
+
if (!CAPABILITY_KINDS.includes(kind as CapabilityKind) || typeof raw !== "string") return "each capability needs a kind and a scope"
|
|
103
|
+
const scope = raw.trim()
|
|
104
|
+
if (!scope || /[\r\n\0\\()]/.test(scope)) return `invalid scope: ${JSON.stringify(raw)}`
|
|
105
|
+
if (isFileCapability(kind as CapabilityKind)) {
|
|
106
|
+
if (/^[/~]|^[a-zA-Z]:/.test(scope) || scope.split("/").includes(".."))
|
|
107
|
+
return `${kind} scope must be a project-relative path or glob; paths outside the project are approved per call`
|
|
108
|
+
parsed.push({ kind: kind as CapabilityKind, scope: scope.replace(/^\.\//, "") })
|
|
109
|
+
} else if (kind === "net.read" || kind === "net.write") {
|
|
110
|
+
const host = destinationHostPattern(scope)
|
|
111
|
+
if (!host) return `${kind} scope must be a host such as api.github.com or *.github.com`
|
|
112
|
+
parsed.push({ kind, scope: host })
|
|
113
|
+
} else {
|
|
114
|
+
if (!/^[a-z][\w.-]*(?::[\w.-]+)?$/i.test(scope)) return `${kind} scope must name one system, such as mcp:<server> or http`
|
|
115
|
+
// MCP tools that change state have unknown effects and keep per-tool consent.
|
|
116
|
+
if (kind === "external.write" && scope.startsWith("mcp:")) return "MCP changes are approved per tool; request external.read for read-only MCP tools"
|
|
117
|
+
parsed.push({ kind: kind as CapabilityKind, scope })
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return parsed.filter((capability, index) => parsed.findIndex(other => other.kind === capability.kind && other.scope === capability.scope) === index)
|
|
121
|
+
}
|
|
@@ -3,7 +3,7 @@ import { RequestMeter } from "../../zapsdk/agent/request-meter.js"
|
|
|
3
3
|
import { recordMaintenanceUsage } from "../agent/maintenanceUsage.js"
|
|
4
4
|
import { existsSync, readFileSync } from "node:fs"
|
|
5
5
|
import { spawnSync } from "node:child_process"
|
|
6
|
-
import type
|
|
6
|
+
import { parsePermissionMode, type AppConfig, type PermissionMode } from "../config.js"
|
|
7
7
|
import {
|
|
8
8
|
cycleEffort,
|
|
9
9
|
getActiveProvider,
|
|
@@ -419,7 +419,11 @@ export function dispatchSlashCommand(
|
|
|
419
419
|
}
|
|
420
420
|
|
|
421
421
|
case "set_permission_mode": {
|
|
422
|
-
const v = (cmd.value ?? "default")
|
|
422
|
+
const v = parsePermissionMode(cmd.value ?? "default")
|
|
423
|
+
if (!v) {
|
|
424
|
+
deps.addLog("error", `Unknown permission mode: ${cmd.value}. Use default, acceptEdits, plan, bypass, or a preset: strict, balanced, autonomous`)
|
|
425
|
+
return true
|
|
426
|
+
}
|
|
423
427
|
deps.updateConfig({ ...deps.configRef.current, permissionMode: v })
|
|
424
428
|
deps.addToast(`mode → ${v}`)
|
|
425
429
|
return true
|
package/src/commands.ts
CHANGED
|
@@ -108,7 +108,7 @@ export function parseCommand(input: string): CommandResult | null {
|
|
|
108
108
|
"",
|
|
109
109
|
" Permissions:",
|
|
110
110
|
" /permissions — Manage active permission rules (interactive)",
|
|
111
|
-
" /mode [name] — Set permission mode (default | acceptEdits | plan | bypass)",
|
|
111
|
+
" /mode [name] — Set permission mode (default | acceptEdits | plan | bypass; presets strict | balanced | autonomous)",
|
|
112
112
|
"",
|
|
113
113
|
" Todos:",
|
|
114
114
|
" /todos [on|off] — Show or hide the todo panel",
|
package/src/config.ts
CHANGED
|
@@ -194,6 +194,16 @@ export type MCPServerConfig = SDKMCPServerConfig
|
|
|
194
194
|
|
|
195
195
|
export type PermissionMode = "default" | "acceptEdits" | "plan" | "bypassPermissions"
|
|
196
196
|
|
|
197
|
+
/** Presets name the trade-off; each is an existing mode. */
|
|
198
|
+
export const PERMISSION_PRESETS = { strict: "default", balanced: "acceptEdits", autonomous: "bypassPermissions" } as const satisfies Record<string, PermissionMode>
|
|
199
|
+
|
|
200
|
+
/** A mode, the `bypass` short form, or a preset name. */
|
|
201
|
+
export function parsePermissionMode(value: string): PermissionMode | null {
|
|
202
|
+
if (value === "default" || value === "acceptEdits" || value === "plan" || value === "bypassPermissions") return value
|
|
203
|
+
if (value === "bypass") return "bypassPermissions"
|
|
204
|
+
return Object.hasOwn(PERMISSION_PRESETS, value) ? PERMISSION_PRESETS[value as keyof typeof PERMISSION_PRESETS] : null
|
|
205
|
+
}
|
|
206
|
+
|
|
197
207
|
/** Pointer to the currently active (provider, model) pair. Both fields
|
|
198
208
|
* must reference something that exists in `providers[]` — loadAppConfig
|
|
199
209
|
* normalises this on startup. */
|
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
createZapVmCloudExecutionBroker, createPlatformSandbox, hostPackageWriteRoots, NetworkProxy, DEFAULT_ALLOWED_DOMAINS,
|
|
10
10
|
discoverZapVmCloudConfig, discoverZapVmInstallation, readZapVmCapabilities,
|
|
11
11
|
selectZapVmCloudConfigForWorkspace,
|
|
12
|
-
type ExecutionBroker, type SandboxMode, type ExecutionEnvironmentFacts, type AuthorizedServiceBackend,
|
|
12
|
+
type ExecutionBroker, type SandboxMode, type ExecutionEnvironmentFacts, type AuthorizedServiceBackend, type NetworkPolicy,
|
|
13
13
|
} from "../zapsdk/index.js"
|
|
14
14
|
import type { ExecuteCommandOptions } from "../zapsdk/builtin-tools/command.js"
|
|
15
15
|
import { observeLocalExecutionCapacity, type ExecutionCapacityFacts } from "../zapsdk/execution/capacity.js"
|
|
@@ -20,9 +20,12 @@ export interface ExecutionEnvironment {
|
|
|
20
20
|
workspaceId?: string
|
|
21
21
|
facts?: ExecutionEnvironmentFacts
|
|
22
22
|
capacity?: ExecutionCapacityFacts
|
|
23
|
+
/** The allowlist the host sandbox proxy enforces, when it enforces one.
|
|
24
|
+
* Hosts outside it need a declared, approved destination. */
|
|
25
|
+
sandboxNetworkPolicy?: NetworkPolicy
|
|
23
26
|
// No prompt, model, retry, budget or completion policy is accepted here.
|
|
24
27
|
commandOptions: Pick<ExecuteCommandOptions,
|
|
25
|
-
"disableBackgroundTasks" | "restrictedNetwork" | "preserveEnvironment" | "allowUnsandboxed" | "sandboxNetwork" | "sandboxExcludedCommands" | "sandboxGitIntegration" | "workspaceOnly">
|
|
28
|
+
"disableBackgroundTasks" | "restrictedNetwork" | "preserveEnvironment" | "allowUnsandboxed" | "sandboxNetwork" | "sandboxExcludedCommands" | "sandboxGitIntegration" | "workspaceOnly" | "declaredNetwork">
|
|
26
29
|
}
|
|
27
30
|
|
|
28
31
|
export type ExecutionBackend = "local" | "vm"
|
|
@@ -88,15 +91,19 @@ export interface SandboxNetworkConfig {
|
|
|
88
91
|
deniedDomains?: string[]
|
|
89
92
|
}
|
|
90
93
|
|
|
94
|
+
/** The proxy allowlist, or undefined where no proxy filters host egress. */
|
|
95
|
+
function sandboxNetworkPolicy(config: SandboxNetworkConfig | undefined): NetworkPolicy | undefined {
|
|
96
|
+
if (process.platform !== "darwin") return undefined
|
|
97
|
+
if (process.env.ZAPCODE_SANDBOX_NETWORK?.trim().toLowerCase() === "open" || config?.mode === "open") return undefined
|
|
98
|
+
return { allowedDomains: [...DEFAULT_ALLOWED_DOMAINS, ...(config?.allowedDomains ?? [])], deniedDomains: [...(config?.deniedDomains ?? [])] }
|
|
99
|
+
}
|
|
100
|
+
|
|
91
101
|
/** Each command owns a proxy with a policy snapshot, including subagents.
|
|
92
102
|
* Configuration changes cannot close a running background command's proxy. */
|
|
93
103
|
function networkProxyFor(config: SandboxNetworkConfig | undefined): NetworkProxy | undefined {
|
|
94
|
-
|
|
95
|
-
if (process.env.ZAPCODE_SANDBOX_NETWORK?.trim().toLowerCase() === "open" || config?.mode === "open") return undefined
|
|
96
|
-
const allowedDomains = [...DEFAULT_ALLOWED_DOMAINS, ...(config?.allowedDomains ?? [])]
|
|
97
|
-
const deniedDomains = [...(config?.deniedDomains ?? [])]
|
|
104
|
+
const policy = sandboxNetworkPolicy(config)
|
|
98
105
|
// Initialization failure must not silently turn an allowlist into open egress.
|
|
99
|
-
return new NetworkProxy(() =>
|
|
106
|
+
return policy ? new NetworkProxy(() => policy) : undefined
|
|
100
107
|
}
|
|
101
108
|
|
|
102
109
|
export function createExecutionEnvironment(
|
|
@@ -138,11 +145,13 @@ export function createExecutionEnvironment(
|
|
|
138
145
|
// A VM or resident boundary has no host sandbox to step out of, and a VM
|
|
139
146
|
// failure must never fall back to an arbitrary host shell.
|
|
140
147
|
const hostSandboxed = !installation && !cloud && !resident
|
|
148
|
+
const networkPolicy = hostSandboxed && sandboxMode !== "disabled" && local.sandboxStatus().available ? sandboxNetworkPolicy(sandboxNetwork) : undefined
|
|
141
149
|
return {
|
|
142
150
|
...(serviceOwner ? { workspaceId: serviceOwner.capabilities.workspaceId } : {}),
|
|
143
151
|
facts: describeExecutionEnvironment(runtime, sandboxMode !== "disabled" && local.sandboxStatus().available),
|
|
144
152
|
// A VM transport has its own execution resources. Never substitute Host observations.
|
|
145
153
|
capacity: !installation && !cloud ? observeLocalExecutionCapacity() : undefined,
|
|
154
|
+
...(networkPolicy ? { sandboxNetworkPolicy: networkPolicy } : {}),
|
|
146
155
|
broker: new TransparentExecutionBroker({
|
|
147
156
|
local,
|
|
148
157
|
runtime: installation ? new ZapVmRuntime({ installation }) : undefined,
|
|
@@ -160,6 +169,7 @@ export function createExecutionEnvironment(
|
|
|
160
169
|
// Host sandbox confines writes to the workspace; network stays open so
|
|
161
170
|
// installs and fetches work, like Claude Code's default sandbox.
|
|
162
171
|
sandboxNetwork: hostSandboxed ? true : undefined,
|
|
172
|
+
declaredNetwork: networkPolicy ? true : undefined,
|
|
163
173
|
},
|
|
164
174
|
}
|
|
165
175
|
}
|
package/src/headless/approval.ts
CHANGED
|
@@ -5,9 +5,10 @@
|
|
|
5
5
|
// asks are denied. Dangerous execution remains denied in headless hosts.
|
|
6
6
|
|
|
7
7
|
import type { PermissionMode } from "../config.js"
|
|
8
|
-
import { evaluateApprovalPolicy } from "../permission-policy.js"
|
|
8
|
+
import { evaluateApprovalPolicy, type ApprovalPolicyDecision } from "../permission-policy.js"
|
|
9
9
|
import { PermissionManager } from "../permissions.js"
|
|
10
|
-
import type { ApprovalCallback, ApprovalDenial } from "../../zapsdk/tools/executor.js"
|
|
10
|
+
import type { ApprovalCallback, ApprovalDenial, ApprovalResponse } from "../../zapsdk/tools/executor.js"
|
|
11
|
+
import type { NetworkPolicy } from "../../zapsdk/execution/network-proxy.js"
|
|
11
12
|
|
|
12
13
|
export interface HeadlessApprovalOptions {
|
|
13
14
|
cwd: string
|
|
@@ -18,7 +19,7 @@ export interface HeadlessApprovalOptions {
|
|
|
18
19
|
* stopReason to "permission_denied" and surface a stderr line). */
|
|
19
20
|
onDeny?: (toolName: string, reason: string) => void
|
|
20
21
|
/** Called on every decision (allow + deny) for stream-json telemetry. */
|
|
21
|
-
onDecision?: (toolName: string, decision: "allow" | "deny", reason: string) => void
|
|
22
|
+
onDecision?: (toolName: string, decision: "allow" | "deny", reason: string, evaluated?: Pick<ApprovalPolicyDecision, "category" | "tier">) => void
|
|
22
23
|
/** Interactive hosts may resolve an ask through their own transport.
|
|
23
24
|
* Explicit denies and safety gates above remain authoritative. */
|
|
24
25
|
onAsk?: ApprovalCallback
|
|
@@ -28,6 +29,8 @@ export interface HeadlessApprovalResult {
|
|
|
28
29
|
/** Tell the permission rules whether commands run inside the OS sandbox or VM. */
|
|
29
30
|
setSandboxConfined: (confined: boolean, autoAllowAll?: boolean) => void
|
|
30
31
|
setSandboxExcludedCommands: (patterns: string[] | undefined) => void
|
|
32
|
+
setSandboxNetworkPolicy: (policy: NetworkPolicy | undefined) => void
|
|
33
|
+
setProjectMemoryLookup: (exists: ((name: string) => boolean) | undefined) => void
|
|
31
34
|
onApproval: ApprovalCallback
|
|
32
35
|
/** True iff at least one tool was denied during the run. */
|
|
33
36
|
anyDenied: () => boolean
|
|
@@ -39,40 +42,55 @@ export function buildHeadlessApproval(opts: HeadlessApprovalOptions): HeadlessAp
|
|
|
39
42
|
const disallowed = new Set(opts.disallowedTools ?? [])
|
|
40
43
|
let denied = false
|
|
41
44
|
|
|
42
|
-
const deny = (tool: string, reason: string, source: ApprovalDenial["source"] = "policy"): ApprovalDenial => {
|
|
45
|
+
const deny = (tool: string, reason: string, source: ApprovalDenial["source"] = "policy", evaluated?: Pick<ApprovalPolicyDecision, "category" | "tier">): ApprovalDenial => {
|
|
43
46
|
denied = true
|
|
44
47
|
opts.onDeny?.(tool, reason)
|
|
45
|
-
opts.onDecision?.(tool, "deny", reason)
|
|
48
|
+
opts.onDecision?.(tool, "deny", reason, evaluated)
|
|
46
49
|
return { approved: false, source, reason }
|
|
47
50
|
}
|
|
48
|
-
const allow = (tool: string, reason: string): boolean => {
|
|
49
|
-
opts.onDecision?.(tool, "allow", reason)
|
|
51
|
+
const allow = (tool: string, reason: string, evaluated?: Pick<ApprovalPolicyDecision, "category" | "tier">): boolean => {
|
|
52
|
+
opts.onDecision?.(tool, "allow", reason, evaluated)
|
|
50
53
|
return true
|
|
51
54
|
}
|
|
52
55
|
|
|
56
|
+
const evaluate = (toolName: string, args: Record<string, unknown>, context?: Parameters<ApprovalCallback>[3]) => evaluateApprovalPolicy(mgr, toolName, args, {
|
|
57
|
+
mode: opts.permissionMode, cwd: opts.cwd, context,
|
|
58
|
+
allowedTools: [...allowed], disallowedTools: [...disallowed],
|
|
59
|
+
})
|
|
60
|
+
/** The answer when no host needs asking, else undefined. */
|
|
61
|
+
const settle = (toolName: string, decision: ApprovalPolicyDecision): ApprovalResponse | undefined => {
|
|
62
|
+
if (decision.decision === "deny" || decision.source === "dangerous") return deny(toolName, decision.reason, "policy", decision)
|
|
63
|
+
if (decision.decision === "allow") return allow(toolName, decision.reason, decision)
|
|
64
|
+
if (!opts.onAsk) return deny(toolName, `${decision.reason}; non-interactive approval required`, "policy", decision)
|
|
65
|
+
return undefined
|
|
66
|
+
}
|
|
67
|
+
// Settled decisions skip the executor's approval queue; only host asks wait in it.
|
|
68
|
+
const onApproval: ApprovalCallback = Object.assign(async (toolName: string, args: Record<string, unknown>, signal?: AbortSignal, context?: Parameters<ApprovalCallback>[3]) => {
|
|
69
|
+
if (signal?.aborted) return deny(toolName, "approval cancelled")
|
|
70
|
+
const decision = evaluate(toolName, args, context)
|
|
71
|
+
const settled = settle(toolName, decision)
|
|
72
|
+
if (settled !== undefined) return settled
|
|
73
|
+
const granted = await opts.onAsk!(toolName, args, signal, context)
|
|
74
|
+
if (signal?.aborted) return deny(toolName, "approval cancelled", "policy", decision)
|
|
75
|
+
const current = evaluate(toolName, args, context)
|
|
76
|
+
if (current.decision === "deny" || current.source === "dangerous") return deny(toolName, current.reason, "policy", current)
|
|
77
|
+
if (granted === true) return allow(toolName, "host approval", decision)
|
|
78
|
+
// The model must not loop back to the same request within this run.
|
|
79
|
+
mgr.recordDenial(toolName, args, context)
|
|
80
|
+
return granted && typeof granted === "object"
|
|
81
|
+
? deny(toolName, granted.reason, granted.source, decision)
|
|
82
|
+
: deny(toolName, "host declined approval", "approval", decision)
|
|
83
|
+
}, {
|
|
84
|
+
precheck: (toolName: string, args: Record<string, unknown>, context?: Parameters<ApprovalCallback>[3]) =>
|
|
85
|
+
settle(toolName, evaluate(toolName, args, context)),
|
|
86
|
+
})
|
|
87
|
+
|
|
53
88
|
return {
|
|
54
89
|
setSandboxConfined: (confined, autoAllowAll) => mgr.setSandboxConfined(confined, autoAllowAll),
|
|
55
90
|
setSandboxExcludedCommands: patterns => mgr.setSandboxExcludedCommands(patterns),
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
mode: opts.permissionMode, cwd: opts.cwd, context,
|
|
60
|
-
allowedTools: [...allowed], disallowedTools: [...disallowed],
|
|
61
|
-
})
|
|
62
|
-
const decision = evaluate()
|
|
63
|
-
if (decision.decision === "deny" || decision.source === "dangerous") return deny(toolName, decision.reason)
|
|
64
|
-
if (decision.decision === "allow") return allow(toolName, decision.reason)
|
|
65
|
-
if (!opts.onAsk) return deny(toolName, `${decision.reason}; non-interactive approval required`)
|
|
66
|
-
const granted = await opts.onAsk(toolName, args, signal, context)
|
|
67
|
-
if (signal?.aborted) return deny(toolName, "approval cancelled")
|
|
68
|
-
const current = evaluate()
|
|
69
|
-
if (current.decision === "deny" || current.source === "dangerous") return deny(toolName, current.reason)
|
|
70
|
-
if (granted === true) return allow(toolName, "host approval")
|
|
71
|
-
return granted && typeof granted === "object"
|
|
72
|
-
? deny(toolName, granted.reason, granted.source)
|
|
73
|
-
: deny(toolName, "host declined approval", "approval")
|
|
74
|
-
|
|
75
|
-
},
|
|
91
|
+
setSandboxNetworkPolicy: policy => mgr.setSandboxNetworkPolicy(policy),
|
|
92
|
+
setProjectMemoryLookup: exists => mgr.setProjectMemoryLookup(exists),
|
|
93
|
+
onApproval,
|
|
76
94
|
anyDenied: () => denied,
|
|
77
95
|
}
|
|
78
96
|
}
|
package/src/headless/args.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
//
|
|
4
4
|
// Accepts:
|
|
5
5
|
// -p, --print <text> prompt string
|
|
6
|
-
// --permission-mode <mode> default | acceptEdits | bypassPermissions | plan
|
|
6
|
+
// --permission-mode <mode> default | acceptEdits | bypassPermissions | plan, or strict | balanced | autonomous
|
|
7
7
|
// --result-schema <schema> outcome-v1 (default) | legacy
|
|
8
8
|
// --output-format <fmt> text | json | stream-json
|
|
9
9
|
// --max-turns <n> integer cap
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
// Any positional arg before flags is treated as the prompt (unless -p was
|
|
28
28
|
// given). Multiple positionals are joined with spaces.
|
|
29
29
|
|
|
30
|
-
import type
|
|
30
|
+
import { parsePermissionMode, type PermissionMode } from "../config.js"
|
|
31
31
|
import { isValidSessionId } from "../utils/session-id.js"
|
|
32
32
|
|
|
33
33
|
export type ResultSchema = "outcome-v1" | "legacy"
|
|
@@ -82,10 +82,6 @@ export interface ParseError {
|
|
|
82
82
|
message: string
|
|
83
83
|
}
|
|
84
84
|
|
|
85
|
-
function isPermissionMode(s: string): s is PermissionMode {
|
|
86
|
-
return s === "default" || s === "acceptEdits" || s === "bypassPermissions" || s === "plan"
|
|
87
|
-
}
|
|
88
|
-
|
|
89
85
|
function isOutputFormat(s: string): s is OutputFormat {
|
|
90
86
|
return s === "text" || s === "json" || s === "stream-json"
|
|
91
87
|
}
|
|
@@ -181,8 +177,9 @@ export function parseHeadlessArgs(argv: readonly string[]): ParseResult | ParseE
|
|
|
181
177
|
}
|
|
182
178
|
case "--permission-mode": {
|
|
183
179
|
const v = take(i, a); if (typeof v !== "string") return v
|
|
184
|
-
|
|
185
|
-
|
|
180
|
+
const mode = parsePermissionMode(v)
|
|
181
|
+
if (!mode) return { ok: false, message: `invalid --permission-mode: ${v}` }
|
|
182
|
+
permissionMode = mode; i++; break
|
|
186
183
|
}
|
|
187
184
|
case "--output-format": {
|
|
188
185
|
const v = take(i, a); if (typeof v !== "string") return v
|
|
@@ -398,6 +395,7 @@ Options:
|
|
|
398
395
|
--watch-linger <s> Retain the viewer after completion (0..300)
|
|
399
396
|
-p, --print <text> Prompt to send (alternative: positional / stdin pipe)
|
|
400
397
|
--permission-mode <mode> default | acceptEdits | bypassPermissions | plan
|
|
398
|
+
(presets: strict | balanced | autonomous)
|
|
401
399
|
(default: 'default' — any non-allowed tool is denied)
|
|
402
400
|
--result-schema <schema> outcome-v1 (default) | legacy
|
|
403
401
|
--output-format <fmt> text (default) | json | stream-json
|
|
@@ -435,7 +435,7 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
|
|
|
435
435
|
formatter.progress(`✗ denied ${getToolAlias(tool)}: ${reason}`)
|
|
436
436
|
host.onPermissionDenied?.(tool, reason)
|
|
437
437
|
},
|
|
438
|
-
onDecision: (tool, decision, reason) => {
|
|
438
|
+
onDecision: (tool, decision, reason, evaluated) => {
|
|
439
439
|
if (args.outputFormat === "stream-json" && !host.formatter) {
|
|
440
440
|
// Surface decisions as observations so downstream tooling can see
|
|
441
441
|
// the gate without parsing stderr.
|
|
@@ -445,6 +445,7 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
|
|
|
445
445
|
alias: getToolAlias(tool),
|
|
446
446
|
decision,
|
|
447
447
|
reason,
|
|
448
|
+
...(evaluated ? { category: evaluated.category, tier: evaluated.tier } : {}),
|
|
448
449
|
}) + "\n")
|
|
449
450
|
}
|
|
450
451
|
},
|
|
@@ -497,7 +498,7 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
|
|
|
497
498
|
executionEnvironment.commandOptions.disableBackgroundTasks = true
|
|
498
499
|
if (host.requireProcessSeal) executionEnvironment.broker = requireProcessSealing(executionEnvironment.broker, host.onProcessSealUnconfirmed)
|
|
499
500
|
}
|
|
500
|
-
const { provider: llmProvider, registry, executor: baseExecutor, createRegistryForCwd, executionFacts, executionCapacity, sandboxConfined } = buildAgentObjects(
|
|
501
|
+
const { provider: llmProvider, registry, executor: baseExecutor, createRegistryForCwd, executionFacts, executionCapacity, sandboxConfined, sandboxNetworkPolicy } = buildAgentObjects(
|
|
501
502
|
config,
|
|
502
503
|
approval.onApproval,
|
|
503
504
|
/* todoStore */ headlessTodoStore,
|
|
@@ -524,6 +525,8 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
|
|
|
524
525
|
const isolatedExecutor = host.readOnlyWorkspace ? guardedExecutor.withWorkspace({ root: realpathSync(cwd), mode: "shared-readonly", sandbox: sandboxConfined ? "enforced" : "none" }) : host.isolateWorkspace ? guardedExecutor.withWorkspace({ root: realpathSync(cwd), mode: "isolated-write", sandbox: sandboxConfined ? "enforced" : "none", ...(host.privateGit ? { privateGitDirectory: host.privateGit.directory, privateGitIdentity: { device: host.privateGit.device, inode: host.privateGit.inode } } : {}) }) : guardedExecutor
|
|
525
526
|
const executor = host.admitToolExecution ? isolatedExecutor.withExecutionAdmission(host.admitToolExecution) : isolatedExecutor
|
|
526
527
|
approval.setSandboxConfined(sandboxConfined, config.autoAllowSandboxedCommands !== false)
|
|
528
|
+
approval.setSandboxNetworkPolicy(sandboxNetworkPolicy)
|
|
529
|
+
approval.setProjectMemoryLookup(name => !!mdStore.get(`${name}.md`))
|
|
527
530
|
approval.setSandboxExcludedCommands(config.allowUnsandboxedCommands !== false ? config.sandboxExcludedCommands : undefined)
|
|
528
531
|
if (host.readOnlyWorkspace) {
|
|
529
532
|
// No network tools: read-only Goal roles take worker output and workspace
|
|
@@ -5,8 +5,10 @@ import type { AskUserCallbacks, PlanModeCallbacks, TodoStore, Tool } from "../..
|
|
|
5
5
|
import type { ApprovalCallback } from "../../zapsdk/tools/executor.js"
|
|
6
6
|
import type { SkillDefinition } from "../../zapsdk/skills/types.js"
|
|
7
7
|
import { buildAgentObjects } from "../agent-factory.js"
|
|
8
|
-
import { delegateProvidersReady, permissionManager } from "../singletons.js"
|
|
8
|
+
import { delegateProvidersReady, mdStore, permissionManager } from "../singletons.js"
|
|
9
9
|
import type { AgentObjects } from "../agent/types.js"
|
|
10
|
+
import { REQUEST_CAPABILITIES_TOOL } from "../capabilities.js"
|
|
11
|
+
import { requestCapabilitiesTool } from "../request-capabilities-tool.js"
|
|
10
12
|
|
|
11
13
|
export interface UseAgentObjectsOptions {
|
|
12
14
|
config: AppConfig
|
|
@@ -55,7 +57,10 @@ export function useAgentObjects(opts: UseAgentObjectsOptions & {
|
|
|
55
57
|
const build = () => {
|
|
56
58
|
const objs = buildAgentObjects(config, onApproval, todoStore, planCallbacks, checkpoint, skillsRef.current, undefined, undefined, undefined, undefined, askUserCallbacks)
|
|
57
59
|
permissionManager.setSandboxConfined(objs.sandboxConfined, config.autoAllowSandboxedCommands !== false)
|
|
60
|
+
permissionManager.setSandboxNetworkPolicy(objs.sandboxNetworkPolicy)
|
|
58
61
|
permissionManager.setSandboxExcludedCommands(config.allowUnsandboxedCommands !== false ? config.sandboxExcludedCommands : undefined)
|
|
62
|
+
permissionManager.setProjectMemoryLookup(name => !!mdStore.get(`${name}.md`))
|
|
63
|
+
objs.registry.register(requestCapabilitiesTool(args => permissionManager.checkPermission(REQUEST_CAPABILITIES_TOOL, args).decision === "allow"))
|
|
59
64
|
for (const tool of mcpTools) {
|
|
60
65
|
// Defensive: skip name clashes rather than throw — a misconfigured
|
|
61
66
|
// server shouldn't take down the whole agent registry. The MCP
|
|
@@ -23,7 +23,7 @@ import { buildCustomSystemPrompt, buildSystemPrompt, deriveCompaction, getActive
|
|
|
23
23
|
import { appendUsage, saveLastOutput, getCurrentSessionId } from "../session.js"
|
|
24
24
|
import type { AppConfig } from "../config.js"
|
|
25
25
|
import type { LogType, ToolCallInfo, UserImageRef } from "../ui/types.js"
|
|
26
|
-
import { appLogger, delegateEventBridge, mdStore, globalMdStore, globalMemoryDir, memorySemanticRetriever, tokenAccounting } from "../singletons.js"
|
|
26
|
+
import { appLogger, permissionManager, delegateEventBridge, mdStore, globalMdStore, globalMemoryDir, memorySemanticRetriever, tokenAccounting } from "../singletons.js"
|
|
27
27
|
import { createStreamingPreview } from "../agent/streamingPreview.js"
|
|
28
28
|
import {
|
|
29
29
|
buildMemoryQueryHistoryFromLogs,
|
|
@@ -546,10 +546,12 @@ export function useAgentRunner({
|
|
|
546
546
|
systemPrompt?: string,
|
|
547
547
|
images?: import("../../zapsdk/core/types.js").ImageContent[],
|
|
548
548
|
memoryQueryText?: string,
|
|
549
|
-
invocation?: { goalTurn?: GoalTurnInput; goalController?: AbortController; onOutcome?: (outcome: AgentOutcomeV1) => void; signal?: AbortSignal; propagateErrors?: boolean; resultSchema?: "outcome-v1" | "legacy" } & Pick<import("../../zapsdk/agent/loop.js").RunOptions,
|
|
549
|
+
invocation?: { keepTurnDenials?: boolean; goalTurn?: GoalTurnInput; goalController?: AbortController; onOutcome?: (outcome: AgentOutcomeV1) => void; signal?: AbortSignal; propagateErrors?: boolean; resultSchema?: "outcome-v1" | "legacy" } & Pick<import("../../zapsdk/agent/loop.js").RunOptions,
|
|
550
550
|
"onInputAccepted" | "hasSteering" | "takeSteering" | "onSteeringAccepted">,
|
|
551
551
|
): Promise<LoopAgentResult | undefined> => {
|
|
552
552
|
if (!invocation?.goalTurn) { resetGoalView(true); setGoalTodoId(undefined) }
|
|
553
|
+
// Background notifications are not the user answering; a decline stands.
|
|
554
|
+
if (!invocation?.keepTurnDenials) permissionManager.startTurn()
|
|
553
555
|
running.current = true
|
|
554
556
|
agentRunStore.clear()
|
|
555
557
|
const controller = new AbortController()
|