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.
- package/package.json +1 -1
- package/src/App.tsx +4 -1
- package/src/agent/contextAttachments.ts +4 -2
- package/src/agent/types.ts +2 -0
- package/src/agent-factory.ts +3 -11
- 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/goalPhase.ts +3 -3
- package/src/headless/runHeadless.ts +9 -7
- 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/singletons.ts +4 -14
- 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/src/ui/dialog-rewind.tsx +1 -1
- package/zapsdk/agent/loop.ts +51 -4
- package/zapsdk/agent/tool-execution-guards.ts +23 -37
- package/zapsdk/builtin-tools/command.ts +19 -3
- package/zapsdk/builtin-tools/http.ts +3 -0
- package/zapsdk/builtin-tools/index.ts +11 -16
- package/zapsdk/builtin-tools/memory.ts +2 -2
- package/zapsdk/builtin-tools/plan-mode.ts +1 -1
- package/zapsdk/builtin-tools/subagent.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
|
@@ -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()
|
|
@@ -6,6 +6,7 @@ import { appLogger, permissionManager } from "../singletons.js"
|
|
|
6
6
|
import { ApprovalQueue } from "../approval-queue.js"
|
|
7
7
|
import { getCurrentSessionId } from "../session.js"
|
|
8
8
|
import { approvalFacts } from "../approval-facts.js"
|
|
9
|
+
import { REQUEST_CAPABILITIES_TOOL } from "../capabilities.js"
|
|
9
10
|
import { evaluateApprovalPolicy } from "../permission-policy.js"
|
|
10
11
|
import { buildToolGrantRules, type ToolGrantRequest } from "../tool-grants.js"
|
|
11
12
|
import type { PermissionRule } from "../permissions.js"
|
|
@@ -28,6 +29,8 @@ interface PendingApproval {
|
|
|
28
29
|
name: string
|
|
29
30
|
args: Record<string, unknown>
|
|
30
31
|
allowScope: boolean
|
|
32
|
+
/** One-time approvals of the same consent earlier this session. */
|
|
33
|
+
repeats: number
|
|
31
34
|
resolve: (choice: ApprovalChoice) => void
|
|
32
35
|
grant: (request: ToolGrantRequest, availableTools: string[], reviewedRules?: readonly PermissionRule[]) => string | void
|
|
33
36
|
}
|
|
@@ -67,8 +70,6 @@ export function usePermissionApproval(
|
|
|
67
70
|
async (
|
|
68
71
|
name: string,
|
|
69
72
|
ar: Record<string, unknown>,
|
|
70
|
-
mode: string,
|
|
71
|
-
why: string,
|
|
72
73
|
signal?: AbortSignal,
|
|
73
74
|
allowScope = true,
|
|
74
75
|
context?: Readonly<ApprovalContext>,
|
|
@@ -76,13 +77,6 @@ export function usePermissionApproval(
|
|
|
76
77
|
): Promise<ApprovalResponse> => {
|
|
77
78
|
const sessionId = getCurrentSessionId()
|
|
78
79
|
if (signal?.aborted) return false
|
|
79
|
-
try {
|
|
80
|
-
// Match the `permission_decision` log line emitted in onApproval's
|
|
81
|
-
// synchronous decision tiers so log consumers see a uniform format.
|
|
82
|
-
appLogger.info(
|
|
83
|
-
`permission_decision tool=${name} mode=${mode} decision=ask (${why})`,
|
|
84
|
-
)
|
|
85
|
-
} catch {}
|
|
86
80
|
// For edit/create tools, push a scrollback "approval" log carrying the
|
|
87
81
|
// proposed diff *before* showing the live ApprovalBar. The entry is
|
|
88
82
|
// finalized at addLog time (no replaceLog) so it commits to Static
|
|
@@ -151,6 +145,8 @@ export function usePermissionApproval(
|
|
|
151
145
|
name,
|
|
152
146
|
args: ar,
|
|
153
147
|
allowScope,
|
|
148
|
+
// Outside-sandbox prompts never count: their option 2 is a far broader grant.
|
|
149
|
+
repeats: approvalFacts(name, ar, context).sandboxEscape || name === REQUEST_CAPABILITIES_TOOL ? 0 : permissionManager.priorOnceApprovals(name, ar, context),
|
|
154
150
|
grant: (request, availableTools, reviewedRules) => {
|
|
155
151
|
const expired = validate()
|
|
156
152
|
if (expired) return expired
|
|
@@ -169,7 +165,7 @@ export function usePermissionApproval(
|
|
|
169
165
|
clear()
|
|
170
166
|
// A stale or synthetic scope choice cannot extend a one-time prompt.
|
|
171
167
|
if (!scopeAllowed && choice !== "deny") choice = "once"
|
|
172
|
-
try { appLogger.info(
|
|
168
|
+
try { appLogger.info("permission_user", { tool: name, choice }) } catch {}
|
|
173
169
|
const escape = approvalFacts(name, ar, context).sandboxEscape
|
|
174
170
|
if (escape) {
|
|
175
171
|
if (choice === "always" || choice === "forever") {
|
|
@@ -196,7 +192,9 @@ export function usePermissionApproval(
|
|
|
196
192
|
} else if (choice === "deny") {
|
|
197
193
|
addLog("system", `Permission: user denied ${getToolAlias(name)}`)
|
|
198
194
|
}
|
|
199
|
-
|
|
195
|
+
if (choice === "deny") permissionManager.recordDenial(name, ar, context)
|
|
196
|
+
else if (choice === "once" && !escape) permissionManager.recordOnceApproval(name, ar, context)
|
|
197
|
+
settle(choice !== "deny" ? true : { approved: false, source: "approval", reason: "user declined approval; do not retry the same request this turn" })
|
|
200
198
|
},
|
|
201
199
|
})
|
|
202
200
|
})
|
|
@@ -204,26 +202,46 @@ export function usePermissionApproval(
|
|
|
204
202
|
[addLog, configRef],
|
|
205
203
|
)
|
|
206
204
|
|
|
207
|
-
|
|
205
|
+
/** Policy decision without a human. Unsettled ones are logged only when
|
|
206
|
+
* the queue reaches them, so a precheck never logs twice. */
|
|
207
|
+
const decide = useCallback(
|
|
208
|
+
(toolName: string, args: Record<string, unknown>, context?: Readonly<ApprovalContext>, logAsk = true) => {
|
|
209
|
+
permissionManager.setSessionId(getCurrentSessionId())
|
|
210
|
+
const mode = configRef.current.permissionMode
|
|
211
|
+
const decision = evaluateApprovalPolicy(permissionManager, toolName, args, { mode, cwd: process.cwd(), context })
|
|
212
|
+
if (decision.decision === "ask" && !logAsk) return decision
|
|
213
|
+
try { appLogger.info("permission_decision", { tool: toolName, mode, decision: decision.decision, category: decision.category, tier: decision.tier, source: decision.source, reason: decision.reason }) } catch {}
|
|
214
|
+
if (decision.decision === "deny") addLog("system", `Permission: denied ${getToolAlias(toolName)} — ${decision.reason}`)
|
|
215
|
+
return decision
|
|
216
|
+
},
|
|
217
|
+
[addLog, configRef],
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
const queued = useCallback(
|
|
208
221
|
(toolName: string, args: Record<string, unknown>, signal?: AbortSignal, context?: Readonly<ApprovalContext>): Promise<ApprovalResponse> => {
|
|
209
222
|
queue.cancelStale()
|
|
210
223
|
return queue.enqueue(async (signal, id) => {
|
|
211
224
|
if (signal?.aborted) return Promise.resolve(false)
|
|
212
|
-
|
|
213
|
-
const
|
|
214
|
-
const decision = evaluateApprovalPolicy(permissionManager, toolName, args, { mode, cwd: process.cwd(), context })
|
|
215
|
-
try { appLogger.info(`permission_decision tool=${toolName} mode=${mode} decision=${decision.decision} (${decision.reason})`) } catch {}
|
|
225
|
+
// Re-decided when the prompt's turn comes: an earlier answer may cover it.
|
|
226
|
+
const decision = decide(toolName, args, context)
|
|
216
227
|
if (decision.decision === "allow") return Promise.resolve(true)
|
|
217
|
-
if (decision.decision === "deny") {
|
|
218
|
-
addLog("system", `Permission: denied ${getToolAlias(toolName)} — ${decision.reason}`)
|
|
219
|
-
return Promise.resolve({ approved: false, source: "policy", reason: decision.reason })
|
|
220
|
-
}
|
|
228
|
+
if (decision.decision === "deny") return Promise.resolve({ approved: false, source: "policy", reason: decision.reason })
|
|
221
229
|
if (decision.source === "dangerous") addLog("system", `Approval required for ${decision.reason}`)
|
|
222
|
-
return promptApproval(toolName, args,
|
|
230
|
+
return promptApproval(toolName, args, signal, decision.allowScope, context, id)
|
|
223
231
|
}, signal)
|
|
224
232
|
},
|
|
225
|
-
[addLog,
|
|
233
|
+
[addLog, decide, promptApproval, queue],
|
|
226
234
|
)
|
|
227
235
|
|
|
236
|
+
// Calls the policy settles never wait behind an open prompt.
|
|
237
|
+
const onApproval: ApprovalCallback = useCallback(Object.assign(
|
|
238
|
+
(toolName: string, args: Record<string, unknown>, signal?: AbortSignal, context?: Readonly<ApprovalContext>) => queued(toolName, args, signal, context),
|
|
239
|
+
{ precheck: (toolName: string, args: Record<string, unknown>, context?: Readonly<ApprovalContext>): ApprovalResponse | undefined => {
|
|
240
|
+
const decision = decide(toolName, args, context, false)
|
|
241
|
+
return decision.decision === "allow" ? true
|
|
242
|
+
: decision.decision === "deny" ? { approved: false, source: "policy", reason: decision.reason } : undefined
|
|
243
|
+
} },
|
|
244
|
+
), [decide, queued])
|
|
245
|
+
|
|
228
246
|
return { onApproval, pendingApproval }
|
|
229
247
|
}
|
package/src/permission-policy.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { PermissionManager, isPathReadTool } from "./permissions.js"
|
|
|
3
3
|
import type { ApprovalContext } from "../zapsdk/tools/executor.js"
|
|
4
4
|
import { approvalFacts } from "./approval-facts.js"
|
|
5
5
|
import { matchDangerousToolCall } from "../zapsdk/utils/safety.js"
|
|
6
|
+
import { REQUEST_CAPABILITIES_TOOL, parseCapabilityRequest } from "./capabilities.js"
|
|
6
7
|
|
|
7
8
|
export interface ApprovalPolicyOptions {
|
|
8
9
|
mode: PermissionMode
|
|
@@ -16,19 +17,53 @@ export interface ApprovalPolicyDecision {
|
|
|
16
17
|
reason: string
|
|
17
18
|
source: "rule" | "dangerous" | "policy" | "sandbox" | "fallback"
|
|
18
19
|
allowScope: boolean
|
|
20
|
+
/** What kind of capability the call needs; used to measure interruptions. */
|
|
21
|
+
category: ApprovalCategory
|
|
22
|
+
/** R0 read-only, R1 workspace-contained, R2 beyond the workspace, R3 dangerous. */
|
|
23
|
+
tier: RiskTier
|
|
19
24
|
}
|
|
20
25
|
|
|
26
|
+
export type RiskTier = "R0" | "R1" | "R2" | "R3"
|
|
27
|
+
|
|
28
|
+
export type ApprovalCategory = "read" | "edit" | "shell" | "sandbox-escape" | "dangerous" | "mcp" | "tool"
|
|
29
|
+
|
|
21
30
|
/** One factual policy order shared by interactive and headless hosts. */
|
|
22
31
|
export function evaluateApprovalPolicy(manager: PermissionManager, name: string, args: Record<string, unknown>, options: ApprovalPolicyOptions): ApprovalPolicyDecision {
|
|
23
|
-
const
|
|
32
|
+
const decision = decide(manager, name, args, options)
|
|
33
|
+
// Only a prompt the user already answered this turn becomes a refusal; a
|
|
34
|
+
// mode change or new rule that allows the call still lets it run.
|
|
35
|
+
return decision.decision === "ask" && manager.declinedThisTurn(name, args, options.context)
|
|
36
|
+
? { ...decision, decision: "deny", source: "policy", allowScope: false,
|
|
37
|
+
reason: "the user declined this request earlier in this turn; ask the user before trying it again or choose another approach" }
|
|
38
|
+
: decision
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function decide(manager: PermissionManager, name: string, args: Record<string, unknown>, options: ApprovalPolicyOptions): ApprovalPolicyDecision {
|
|
24
42
|
const facts = approvalFacts(name, args, options.context)
|
|
43
|
+
const kind: ApprovalCategory = facts.sandboxEscape ? "sandbox-escape" : facts.shellCommands !== undefined ? "shell"
|
|
44
|
+
: name.startsWith("mcp__") ? "mcp" : facts.editOnly ? "edit" : facts.readOnly ? "read" : "tool"
|
|
45
|
+
// Only a new, unpinned note that replaces nothing: overwriting, pinning or
|
|
46
|
+
// superseding memory steers future sessions, so it still asks.
|
|
47
|
+
const projectMemory = name === "memory_save" && (args.type === "project" || args.type === "reference")
|
|
48
|
+
&& !(Array.isArray(args.tags) && args.tags.includes("pinned")) && !(Array.isArray(args.supersedes) && args.supersedes.length > 0)
|
|
49
|
+
&& typeof args.name === "string" && manager.isNewProjectMemory(args.name)
|
|
50
|
+
const tier = (): RiskTier => facts.readOnly ? "R0" : projectMemory ? "R1"
|
|
51
|
+
: facts.shellCommands !== undefined ? (!facts.sandboxEscape && manager.isSandboxConfined() && !manager.reachesBeyondAllowlist(args) ? "R1" : "R2")
|
|
52
|
+
: manager.changesOnlyWorkspaceFiles(name, args, options.context) ? "R1" : "R2"
|
|
53
|
+
const result = (decision: ApprovalPolicyDecision["decision"], reason: string, source: ApprovalPolicyDecision["source"] = "policy", allowScope = false): ApprovalPolicyDecision =>
|
|
54
|
+
({ decision, reason, source, allowScope, category: source === "dangerous" ? "dangerous" : kind, tier: source === "dangerous" ? "R3" : tier() })
|
|
25
55
|
if (options.mode === "plan" && !facts.readOnly) return result("deny", "plan-mode is read-only")
|
|
26
56
|
if (options.disallowedTools?.includes(name)) return result("deny", "disallowed by --disallowed-tools")
|
|
57
|
+
if (name === REQUEST_CAPABILITIES_TOOL) {
|
|
58
|
+
if (options.mode === "plan") return result("deny", "plan-mode is read-only")
|
|
59
|
+
const requested = parseCapabilityRequest(args)
|
|
60
|
+
if (typeof requested === "string") return result("deny", requested)
|
|
61
|
+
}
|
|
27
62
|
const rule = manager.checkPermission(name, args, options.context)
|
|
28
63
|
const escape = facts.sandboxEscape
|
|
29
64
|
const sandbox = escape ? manager.checkSandboxEscape() : undefined
|
|
30
65
|
const denial = rule.decision === "deny" ? rule : sandbox?.decision === "deny" ? sandbox : undefined
|
|
31
|
-
if (denial) return result("deny", `matched deny rule ${denial.rule
|
|
66
|
+
if (denial) return result("deny", denial.rule ? `matched deny rule ${denial.rule.pattern}` : denial.reason ?? "denied", "rule")
|
|
32
67
|
if (facts.shellCommands) {
|
|
33
68
|
const danger = facts.shellCommands.map(command => matchDangerousToolCall({ ...args, command, check_steps: undefined }, options.context?.workspaceRoot ?? options.cwd, options.context?.cwd ?? options.cwd, options.context?.shell)).find(Boolean)
|
|
34
69
|
if (danger) return result("ask", `dangerous bash (${danger.id})`, "dangerous")
|
|
@@ -44,10 +79,17 @@ export function evaluateApprovalPolicy(manager: PermissionManager, name: string,
|
|
|
44
79
|
if (name === "bash" && options.mode !== "bypassPermissions") {
|
|
45
80
|
const paths = manager.checkShellPaths(args, options.context)
|
|
46
81
|
if (paths.decision === "ask") return result("ask", paths.reason ?? "Shell filesystem paths require authorization", "fallback", true)
|
|
82
|
+
const network = manager.checkShellNetwork(args, options.context)
|
|
83
|
+
if (network.decision === "ask") return result("ask", network.reason ?? "Shell network destinations require authorization", "fallback", true)
|
|
47
84
|
}
|
|
48
85
|
if (rule.decision === "allow") return result("allow", rule.reason ?? `rule ${rule.rule?.pattern}`, "rule")
|
|
49
86
|
if (options.allowedTools?.includes(name)) return result("allow", "allowed by --allowed-tools")
|
|
50
87
|
if (name === "read_tool_output") return result("allow", "session-scoped runtime output read")
|
|
88
|
+
// The handler only stops tasks owned by the calling session.
|
|
89
|
+
if (name === "task_stop") return result("allow", "stops a task owned by this session")
|
|
90
|
+
// New project notes are agent-owned, reviewable in /mem and stay in this
|
|
91
|
+
// project. Global user/feedback memory reaches every project, so it asks.
|
|
92
|
+
if (projectMemory) return result("allow", "new project memory note")
|
|
51
93
|
// Reading screenshots, skill resources and reference files must not require
|
|
52
94
|
// a new grant for every path. Explicit restrictions were checked above;
|
|
53
95
|
// filesystem confinement remains the executor/backend's responsibility.
|
package/src/permissions.ts
CHANGED
|
@@ -9,6 +9,10 @@ import type { ApprovalContext } from "../zapsdk/tools/executor.js"
|
|
|
9
9
|
import type { Logger } from "../zapsdk/debug/logger.js"
|
|
10
10
|
import { writeFileAtomic } from "./utils/secure-write.js"
|
|
11
11
|
import { canonicalizeWithNearestExistingAncestorSync, resolveToolPathCanonical } from "../zapsdk/builtin-tools/filesystem.js"
|
|
12
|
+
import type { ToolCapability } from "../zapsdk/tools/approval.js"
|
|
13
|
+
import { decideHost, destinationHostPattern, type NetworkPolicy } from "../zapsdk/execution/network-proxy.js"
|
|
14
|
+
export { WORKSPACE_EDIT_TOOLS } from "./capabilities.js"
|
|
15
|
+
import { REQUEST_CAPABILITIES_TOOL, capabilityFileTools, capabilityPattern, fileToolCapabilities, isFileCapability, matchCapabilityScope, parseCapabilityPattern, parseCapabilityRequest } from "./capabilities.js"
|
|
12
16
|
|
|
13
17
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
|
14
18
|
|
|
@@ -175,9 +179,24 @@ function stripProcessWrappers(parts: string[]): string[] {
|
|
|
175
179
|
|
|
176
180
|
// Import and re-export from shared utility so callers only need one import
|
|
177
181
|
import { matchCommandGlob, matchesAnyCommandPattern, shellCommandDisplay, shellExecutionCommands, splitShellSubcommands } from "../zapsdk/utils/shell.js"
|
|
178
|
-
import { effectiveCommandCwd, isReadOnlyCommand } from "./readonly-commands.js"
|
|
182
|
+
import { effectiveCommandCwd, isNeutralShellSubcommand, isReadOnlyCommand } from "./readonly-commands.js"
|
|
179
183
|
export { splitShellSubcommands }
|
|
180
184
|
|
|
185
|
+
/** Subcommands that carry a shell call's decision. A neutral `cd` or stdin
|
|
186
|
+
* filter rides along with a sibling judged on its own; alone it is kept. */
|
|
187
|
+
function significantShellSubcommands(subs: string[], workspace: string, runDir: string | null): string[] {
|
|
188
|
+
if (runDir === null) return subs
|
|
189
|
+
// Only the first `cd` is judged from the directory it really runs in.
|
|
190
|
+
let moved = false
|
|
191
|
+
const kept = subs.filter(sub => {
|
|
192
|
+
const cd = /^\s*cd(?:\s|$)/.test(sub)
|
|
193
|
+
const neutral = !(cd && moved) && isNeutralShellSubcommand(sub, workspace, runDir)
|
|
194
|
+
moved ||= cd
|
|
195
|
+
return !neutral
|
|
196
|
+
})
|
|
197
|
+
return kept.length ? kept : subs
|
|
198
|
+
}
|
|
199
|
+
|
|
181
200
|
// ─── Pattern parsing ──────────────────────────────────────────────────────────
|
|
182
201
|
|
|
183
202
|
const TOOL_ALIASES: Record<string, string[]> = {
|
|
@@ -434,6 +453,65 @@ export function ruleMatchesTool(
|
|
|
434
453
|
return FILE_TOOLS.has(toolName) ? matchFilePattern(subject, argPattern, rule.type === "allow" && rule.canonicalPath) : matchGlob(subject, argPattern)
|
|
435
454
|
}
|
|
436
455
|
|
|
456
|
+
// ─── Capability rules ─────────────────────────────────────────────────────────
|
|
457
|
+
|
|
458
|
+
/** Capabilities a call needs: built-in file tools from their arguments, other
|
|
459
|
+
* tools from the adapter's effects. Shells and delegation keep their own rules. */
|
|
460
|
+
function callCapabilities(name: string, args: Record<string, unknown>, context?: Readonly<ApprovalContext>): readonly ToolCapability[] | undefined {
|
|
461
|
+
if (FILE_TOOLS.has(name)) return fileToolCapabilities(name, args)
|
|
462
|
+
if (name === "delegate_agent") return undefined
|
|
463
|
+
// A capability request needs exactly what it asks for.
|
|
464
|
+
if (name === REQUEST_CAPABILITIES_TOOL) {
|
|
465
|
+
const requested = parseCapabilityRequest(args)
|
|
466
|
+
return typeof requested === "string" ? undefined : requested
|
|
467
|
+
}
|
|
468
|
+
const facts = approvalFacts(name, args, context)
|
|
469
|
+
return facts.shellCommands !== undefined ? undefined : facts.capabilities
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/** Workspace coordinates of a file capability. An allow must cover the real
|
|
473
|
+
* target and the directory entry; a restriction applies to any spelling. */
|
|
474
|
+
function fileCapabilityViews(path: string, cwd: string, context?: Readonly<ApprovalContext>): { covered: string[]; touched: string[] } {
|
|
475
|
+
const view = (canonical: boolean | "entry") => String(normalizeFileArgs("write_file", { path }, cwd, context, canonical).path)
|
|
476
|
+
const covered = [...new Set([view(true), view("entry")])]
|
|
477
|
+
return { covered, touched: [...new Set([...covered, view(false)])] }
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/** Restrictions apply across a family (a write deny also stops deletes and a
|
|
481
|
+
* read deny stops writes); an allow covers only its own kind. */
|
|
482
|
+
function capabilityRuleMatches(rule: PermissionRule, capability: ToolCapability, cwd: string, context: Readonly<ApprovalContext> | undefined): boolean {
|
|
483
|
+
const parsed = parseCapabilityPattern(rule.pattern)
|
|
484
|
+
if (!parsed) return false
|
|
485
|
+
const family = (kind: string) => kind.slice(0, kind.indexOf("."))
|
|
486
|
+
if (rule.type === "allow" ? parsed.kind !== capability.kind : family(parsed.kind) !== family(capability.kind)) return false
|
|
487
|
+
if (!isFileCapability(capability.kind)) return matchCapabilityScope(capability.scope, parsed.scope)
|
|
488
|
+
// A wildcard request (`*.example.com`) meets any restriction inside it.
|
|
489
|
+
|| rule.type !== "allow" && matchCapabilityScope(parsed.scope, capability.scope)
|
|
490
|
+
const views = fileCapabilityViews(capability.scope, cwd, context)
|
|
491
|
+
return rule.type === "allow"
|
|
492
|
+
? views.covered.every(path => matchFilePattern(path, parsed.scope, rule.canonicalPath))
|
|
493
|
+
: views.touched.some(path => matchFilePattern(path, parsed.scope))
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/** One rule per capability. Workspace writes share one workspace-wide grant;
|
|
497
|
+
* deletes keep their directory; anything outside keeps its exact target. */
|
|
498
|
+
function inferCapabilityRules(name: string, args: Record<string, unknown>, cwd: string, context?: Readonly<ApprovalContext>): PermissionRule[] | null {
|
|
499
|
+
const capabilities = callCapabilities(name, args, context)
|
|
500
|
+
if (!capabilities?.length) return null
|
|
501
|
+
const patterns = capabilities.flatMap(capability => {
|
|
502
|
+
if (!isFileCapability(capability.kind)) return [capabilityPattern(capability.kind, capability.scope)]
|
|
503
|
+
const views = fileCapabilityViews(capability.scope, cwd, context).covered
|
|
504
|
+
if (capability.kind === "fs.write" && views.every(view => !isAbsolute(view))) return [capabilityPattern("fs.write", "**")]
|
|
505
|
+
return views.map(view => capabilityPattern(capability.kind,
|
|
506
|
+
!isAbsolute(view) && capability.kind === "fs.delete" ? fileRuleScope("delete_file", view) : view))
|
|
507
|
+
})
|
|
508
|
+
return [...new Set(patterns)].map(pattern => ({ pattern, type: "allow" }))
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
function strongestRestriction(...decisions: Array<PermissionDecision | null>): PermissionDecision | null {
|
|
512
|
+
return decisions.find(decision => decision?.decision === "deny") ?? decisions.find(decision => decision?.decision === "ask") ?? null
|
|
513
|
+
}
|
|
514
|
+
|
|
437
515
|
// ─── Shadow detection ─────────────────────────────────────────────────────────
|
|
438
516
|
|
|
439
517
|
/** Does `a`'s arg pattern match any possible arg for the tool?
|
|
@@ -597,19 +675,33 @@ export function inferPattern(toolName: string, args: Record<string, unknown>, cw
|
|
|
597
675
|
|
|
598
676
|
/** The same complete rule set powers previews and both persistence lifetimes. */
|
|
599
677
|
export function inferInvocationRules(name: string, args: Record<string, unknown>, cwd: string, context?: Readonly<ApprovalContext>): PermissionRule[] {
|
|
600
|
-
|
|
601
|
-
|
|
678
|
+
if (name === REQUEST_CAPABILITIES_TOOL) {
|
|
679
|
+
// Saved exactly as requested; file scopes are never widened to `**`.
|
|
680
|
+
const requested = parseCapabilityRequest(args)
|
|
681
|
+
return typeof requested === "string" ? [] : requested.map(capability => ({ pattern: capabilityPattern(capability.kind, capability.scope), type: "allow" }))
|
|
682
|
+
}
|
|
683
|
+
const pathPatterns = name === "bash" ? [...shellPathRequests(args, context?.cwd ?? cwd)
|
|
684
|
+
.map(request => inferPattern(request.tool, { path: request.path }, cwd)).filter((pattern): pattern is string => !!pattern),
|
|
685
|
+
...shellNetworkHosts(args).map(host => capabilityPattern("net.write", host))] : []
|
|
602
686
|
if (opaqueShell(approvalFacts(name, args, context), context)) return [name, ...pathPatterns].map(pattern => ({ pattern, type: "allow" }))
|
|
603
687
|
const views = [normalizeFileArgs(name, args, cwd, context)]
|
|
604
688
|
if (MUTATION_TOOLS.has(name)) views.push(normalizeFileArgs(name, args, cwd, context, "entry"))
|
|
689
|
+
const capabilityRules = name === "bash" ? null : inferCapabilityRules(name, args, cwd, context)
|
|
690
|
+
if (capabilityRules) return capabilityRules
|
|
605
691
|
const invocations = views.flatMap(normalized => name === "bash"
|
|
606
|
-
? shellExecutionCommands(normalized).flatMap(command => splitShellSubcommands(command, context?.shell?.syntax)).map(command => ({ ...normalized, command }))
|
|
692
|
+
? shellExecutionCommands(normalized).flatMap(command => significantShellSubcommands(splitShellSubcommands(command, context?.shell?.syntax), cwd, effectiveCommandCwd(cwd, args.cwd))).map(command => ({ ...normalized, command }))
|
|
607
693
|
: name === "move_file" ? [normalized.source, normalized.destination].map(path => ({ source: path, destination: path })) : [normalized])
|
|
608
694
|
const patterns = invocations.map(value => inferPattern(name, value, cwd)).filter((pattern): pattern is string => !!pattern)
|
|
609
695
|
patterns.push(...pathPatterns)
|
|
610
696
|
return [...new Set(patterns)].map(pattern => ({ pattern, type: "allow" }))
|
|
611
697
|
}
|
|
612
698
|
|
|
699
|
+
/** Hosts a shell declares beyond the sandbox allowlist. */
|
|
700
|
+
function shellNetworkHosts(args: Record<string, unknown>): string[] {
|
|
701
|
+
const declared = Array.isArray(args.network_destinations) ? args.network_destinations.filter((value): value is string => typeof value === "string") : []
|
|
702
|
+
return [...new Set(declared.map(destinationHostPattern).filter((host): host is string => !!host))]
|
|
703
|
+
}
|
|
704
|
+
|
|
613
705
|
function shellPathRequests(args: Record<string, unknown>, cwd: string): Array<{ tool: "read_file" | "write_file"; path: string }> {
|
|
614
706
|
const runCwd = resolveToolPathCanonical(typeof args.cwd === "string" ? args.cwd : cwd, cwd)
|
|
615
707
|
return ([ ["read_paths", "read_file"], ["write_paths", "write_file"] ] as const).flatMap(([field, tool]) =>
|
|
@@ -646,6 +738,19 @@ export class PermissionManager {
|
|
|
646
738
|
private sandboxExcluded: string[] = []
|
|
647
739
|
setSandboxExcludedCommands(patterns: string[] | undefined): void { this.sandboxExcluded = patterns ?? [] }
|
|
648
740
|
|
|
741
|
+
isSandboxConfined(): boolean { return this.sandboxConfined }
|
|
742
|
+
|
|
743
|
+
/** The allowlist the sandbox proxy enforces; undefined when egress is not filtered. */
|
|
744
|
+
private sandboxNetworkPolicy?: NetworkPolicy
|
|
745
|
+
setSandboxNetworkPolicy(policy: NetworkPolicy | undefined): void { this.sandboxNetworkPolicy = policy }
|
|
746
|
+
|
|
747
|
+
/** True when every capability is a file change inside the workspace (R1). */
|
|
748
|
+
changesOnlyWorkspaceFiles(name: string, args: Record<string, unknown>, context?: Readonly<ApprovalContext>): boolean {
|
|
749
|
+
const capabilities = callCapabilities(name, args, context)
|
|
750
|
+
return !!capabilities?.length && capabilities.every(capability => isFileCapability(capability.kind)
|
|
751
|
+
&& fileCapabilityViews(capability.scope, this.cwd, context).covered.every(view => !isAbsolute(view)))
|
|
752
|
+
}
|
|
753
|
+
|
|
649
754
|
setSandboxConfined(confined: boolean, autoAllowAll = true): void {
|
|
650
755
|
this.sandboxConfined = confined
|
|
651
756
|
this.sandboxAutoAllow = autoAllowAll
|
|
@@ -663,6 +768,56 @@ export class PermissionManager {
|
|
|
663
768
|
this.sandboxSessionId = sessionId
|
|
664
769
|
this.sessionSandboxEscape = undefined
|
|
665
770
|
this.sessionRules = []
|
|
771
|
+
this.turnDenials.clear()
|
|
772
|
+
this.onceApprovals.clear()
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/** Calls the user declined since their last message. Only the identical call
|
|
776
|
+
* is refused again: a declined edit says nothing about the next one. */
|
|
777
|
+
private turnDenials = new Set<string>()
|
|
778
|
+
|
|
779
|
+
private denialKey(name: string, args: Record<string, unknown>): string {
|
|
780
|
+
return `${name}#${argsFingerprint(args)}`
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
recordDenial(name: string, args: Record<string, unknown>, _context?: Readonly<ApprovalContext>): void {
|
|
784
|
+
this.turnDenials.add(this.denialKey(name, args))
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
/** The model is retrying a call the user already declined this turn. */
|
|
788
|
+
declinedThisTurn(name: string, args: Record<string, unknown>, _context?: Readonly<ApprovalContext>): boolean {
|
|
789
|
+
return this.turnDenials.size > 0 && this.turnDenials.has(this.denialKey(name, args))
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
private memoryRecordExists?: (name: string) => boolean
|
|
793
|
+
|
|
794
|
+
/** How the policy learns whether a project memory name is already taken. */
|
|
795
|
+
setProjectMemoryLookup(exists: ((name: string) => boolean) | undefined): void { this.memoryRecordExists = exists }
|
|
796
|
+
|
|
797
|
+
/** A project memory name that is not yet in use; unknown counts as taken. */
|
|
798
|
+
isNewProjectMemory(name: string): boolean {
|
|
799
|
+
try { return !!this.memoryRecordExists && !this.memoryRecordExists(name) } catch { return false }
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
/** A new user message may change their answer. */
|
|
803
|
+
startTurn(): void { this.turnDenials.clear() }
|
|
804
|
+
|
|
805
|
+
/** One-time approvals this session, by the consent a saved rule would hold. */
|
|
806
|
+
private onceApprovals = new Map<string, number>()
|
|
807
|
+
|
|
808
|
+
private approvalKey(name: string, args: Record<string, unknown>, context?: Readonly<ApprovalContext>): string {
|
|
809
|
+
return inferInvocationRules(name, args, this.cwd, context).map(rule => rule.pattern).sort().join("\n")
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
recordOnceApproval(name: string, args: Record<string, unknown>, context?: Readonly<ApprovalContext>): void {
|
|
813
|
+
const key = this.approvalKey(name, args, context)
|
|
814
|
+
if (key) this.onceApprovals.set(key, (this.onceApprovals.get(key) ?? 0) + 1)
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
/** How often the user already approved the same consent once this session. */
|
|
818
|
+
priorOnceApprovals(name: string, args: Record<string, unknown>, context?: Readonly<ApprovalContext>): number {
|
|
819
|
+
const key = this.approvalKey(name, args, context)
|
|
820
|
+
return key ? this.onceApprovals.get(key) ?? 0 : 0
|
|
666
821
|
}
|
|
667
822
|
|
|
668
823
|
/** Dedicated consent is separate from ordinary Bash command allow rules. */
|
|
@@ -715,12 +870,18 @@ export class PermissionManager {
|
|
|
715
870
|
const fileArgs = normalizeFileArgs(tool, { path }, this.cwd, context)
|
|
716
871
|
return rules.some(rule => rule.type === "allow" && ruleMatchesTool(rule, tool, fileArgs))
|
|
717
872
|
})) return false
|
|
873
|
+
if (name === "bash" && !shellNetworkHosts(args).every(host => this.checkShellNetwork({ ...args, network_destinations: [host] }, context).decision === "allow"
|
|
874
|
+
|| rules.some(rule => rule.type === "allow" && capabilityRuleMatches(rule, { kind: "net.write", scope: host }, this.cwd, context)))) return false
|
|
718
875
|
if (opaqueShell(facts, context)) return rules.some(rule => rule.type === "allow" && isWholeToolRule(rule, name))
|
|
719
876
|
if (name === "bash") {
|
|
720
|
-
const commands = shellExecutionCommands(normalized).flatMap(command =>
|
|
877
|
+
const commands = shellExecutionCommands(normalized).flatMap(command =>
|
|
878
|
+
significantShellSubcommands(splitShellSubcommands(command, context?.shell?.syntax), this.cwd, effectiveCommandCwd(this.cwd, args.cwd)))
|
|
721
879
|
return commands.length > 0 && commands.every(command => rules.some(rule =>
|
|
722
880
|
ruleMatchesTool(rule, name, { command }) || ruleMatchesTool(rule, name, { command: normalizeBashSubcommand(command) })))
|
|
723
881
|
}
|
|
882
|
+
const capabilities = callCapabilities(name, args, context)
|
|
883
|
+
if (capabilities?.length && capabilities.every(capability =>
|
|
884
|
+
rules.some(rule => rule.type === "allow" && capabilityRuleMatches(rule, capability, this.cwd, context)))) return true
|
|
724
885
|
const views = [normalized]
|
|
725
886
|
if (MUTATION_TOOLS.has(name)) views.push(normalizeFileArgs(name, args, this.cwd, context, "entry"))
|
|
726
887
|
return views.every(view => name === "move_file" ? [view.source, view.destination].every(path =>
|
|
@@ -743,7 +904,7 @@ export class PermissionManager {
|
|
|
743
904
|
checkPermission(toolName: string, args: Record<string, unknown>, context?: Readonly<ApprovalContext>): PermissionDecision {
|
|
744
905
|
const base = this.checkPermissionCore(toolName, args, context)
|
|
745
906
|
if (toolName !== "bash" || base.decision === "deny") return base
|
|
746
|
-
const decisions = [base, this.checkShellPaths(args, context)]
|
|
907
|
+
const decisions = [base, this.checkShellPaths(args, context), this.checkShellNetwork(args, context)]
|
|
747
908
|
return decisions.find(value => value.decision === "deny")
|
|
748
909
|
?? decisions.find(value => value.decision === "ask" && value.rule)
|
|
749
910
|
?? decisions.find(value => value.decision === "ask") ?? base
|
|
@@ -768,6 +929,43 @@ export class PermissionManager {
|
|
|
768
929
|
?? decisions.find(value => value.decision === "ask") ?? { decision: "allow" }
|
|
769
930
|
}
|
|
770
931
|
|
|
932
|
+
/** A shell declares a host the sandbox allowlist would refuse. */
|
|
933
|
+
reachesBeyondAllowlist(args: Record<string, unknown>): boolean {
|
|
934
|
+
const policy = this.sandboxNetworkPolicy
|
|
935
|
+
return !!policy && shellNetworkHosts(args).some(host => !decideHost(policy, host).allowed)
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
/** Declared hosts extend the sandbox proxy for one command. Allowlisted
|
|
939
|
+
* hosts need nothing, denied hosts are refused, others need `net.write`:
|
|
940
|
+
* the proxy filters by host only, so a shell can send as well as receive.
|
|
941
|
+
* Like `sandboxNetwork.allowedDomains`, only the user can widen egress:
|
|
942
|
+
* allows count from this session, host-owned project grants and user
|
|
943
|
+
* settings, never from repository `.zapcode/settings*.json` files. */
|
|
944
|
+
checkShellNetwork(args: Record<string, unknown>, context?: Readonly<ApprovalContext>): PermissionDecision {
|
|
945
|
+
const policy = this.sandboxNetworkPolicy
|
|
946
|
+
if (!policy) return { decision: "allow" }
|
|
947
|
+
const facts = approvalFacts("bash", args, context)
|
|
948
|
+
// Outside the sandbox no proxy applies; that path has its own consent.
|
|
949
|
+
if (facts.sandboxEscape || (facts.shellCommands ?? []).some(command => matchesAnyCommandPattern(command, this.sandboxExcluded))) return { decision: "allow" }
|
|
950
|
+
this.merged = loadMergedSettings(this.cwd)
|
|
951
|
+
const granted = [...this.sessionRules, ...loadPermissionSettings(getProjectAuthorizationSettingsPath(this.cwd)).rules,
|
|
952
|
+
...loadPermissionSettings(getGlobalSettingsPath()).rules].filter(rule => rule.type === "allow")
|
|
953
|
+
const decisions = shellNetworkHosts(args).map((host): PermissionDecision => {
|
|
954
|
+
const capability: ToolCapability = { kind: "net.write", scope: host }
|
|
955
|
+
const restriction = this.matchRules(rule => rule.type !== "allow" && capabilityRuleMatches(rule, capability, this.cwd, context))
|
|
956
|
+
if (restriction) return restriction
|
|
957
|
+
const refused = decideHost({ allowedDomains: ["*"], deniedDomains: policy.deniedDomains }, host)
|
|
958
|
+
if (!refused.allowed) return { decision: "deny", reason: refused.reason }
|
|
959
|
+
if (decideHost(policy, host).allowed) return { decision: "allow" }
|
|
960
|
+
const grant = granted.find(rule => capabilityRuleMatches(rule, capability, this.cwd, context))
|
|
961
|
+
return grant ? { decision: "allow", rule: grant, scope: this.sessionRules.includes(grant) ? "session" : this.locateRuleScope(grant) }
|
|
962
|
+
: { decision: "ask", reason: `Shell network access requires authorization: ${host}` }
|
|
963
|
+
})
|
|
964
|
+
return decisions.find(value => value.decision === "deny")
|
|
965
|
+
?? decisions.find(value => value.decision === "ask" && value.rule)
|
|
966
|
+
?? decisions.find(value => value.decision === "ask") ?? { decision: "allow" }
|
|
967
|
+
}
|
|
968
|
+
|
|
771
969
|
private checkPermissionCore(toolName: string, args: Record<string, unknown>, context?: Readonly<ApprovalContext>): PermissionDecision {
|
|
772
970
|
// Normalize once at the entry; rule evaluation and generation both
|
|
773
971
|
// operate in cwd-relative space afterwards. This is the fix for the
|
|
@@ -779,14 +977,16 @@ export class PermissionManager {
|
|
|
779
977
|
const lexical = normalizeFileArgs(toolName, args, this.cwd, context, false)
|
|
780
978
|
const views = [a]
|
|
781
979
|
if (MUTATION_TOOLS.has(toolName)) views.push(normalizeFileArgs(toolName, args, this.cwd, context, "entry"))
|
|
782
|
-
const
|
|
980
|
+
const capabilities = fileToolCapabilities(toolName, args)
|
|
981
|
+
const restriction = strongestRestriction(this.matchRules(rule => rule.type !== "allow" && (
|
|
783
982
|
[...views, lexical].some(view => ruleMatchesTool(rule, toolName, view))
|
|
784
|
-
|| isDirectoryReadTool(toolName) && directoryRuleIntersects(rule, toolName, args, this.cwd, context)))
|
|
983
|
+
|| isDirectoryReadTool(toolName) && directoryRuleIntersects(rule, toolName, args, this.cwd, context))),
|
|
984
|
+
this.capabilityRestriction(capabilities, context))
|
|
785
985
|
if (restriction) return restriction
|
|
786
986
|
const matches = views.flatMap(view => toolName === "move_file" ? [view.source, view.destination].map(path =>
|
|
787
987
|
typeof path === "string" && !!path ? this.matchRules(rule => rule.type === "allow" && ruleMatchesTool(rule, toolName, { source: path, destination: path })) : null)
|
|
788
988
|
: [this.matchRules(rule => rule.type === "allow" && ruleMatchesTool(rule, toolName, view))])
|
|
789
|
-
return matches.every(Boolean) ? matches[0]! : { decision: "ask" }
|
|
989
|
+
return matches.every(Boolean) ? matches[0]! : this.capabilityAllow(capabilities, context) ?? { decision: "ask" }
|
|
790
990
|
}
|
|
791
991
|
|
|
792
992
|
const facts = approvalFacts(toolName, args, context)
|
|
@@ -813,7 +1013,27 @@ export class PermissionManager {
|
|
|
813
1013
|
return decisions.find(decision => decision.decision === "ask") ?? decisions[0] ?? { decision: "ask" }
|
|
814
1014
|
}
|
|
815
1015
|
|
|
816
|
-
|
|
1016
|
+
const capabilities = callCapabilities(toolName, args, context)
|
|
1017
|
+
const tool = this.matchRules(rule => ruleMatchesTool(rule, toolName, a))
|
|
1018
|
+
const restriction = strongestRestriction(tool?.decision === "allow" ? null : tool, this.capabilityRestriction(capabilities, context))
|
|
1019
|
+
if (restriction) return restriction
|
|
1020
|
+
return tool ?? this.capabilityAllow(capabilities, context) ?? { decision: "ask" }
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
private capabilityRestriction(capabilities: readonly ToolCapability[] | undefined, context?: Readonly<ApprovalContext>): PermissionDecision | null {
|
|
1024
|
+
if (!capabilities?.length) return null
|
|
1025
|
+
return this.matchRules(rule => rule.type !== "allow" && capabilities.some(capability => capabilityRuleMatches(rule, capability, this.cwd, context)
|
|
1026
|
+
// A capability grant covers sibling tools, so their deny/ask rules apply too:
|
|
1027
|
+
// `Edit(.env)` must still stop write_file once fs.write is granted.
|
|
1028
|
+
|| isFileCapability(capability.kind) && fileCapabilityViews(capability.scope, this.cwd, context).touched.some(path =>
|
|
1029
|
+
capabilityFileTools(capability.kind).some(tool => ruleMatchesTool(rule, tool, tool === "move_file" ? { source: path, destination: path } : { path })))))
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
/** Every capability must be covered; the first match explains the decision. */
|
|
1033
|
+
private capabilityAllow(capabilities: readonly ToolCapability[] | undefined, context?: Readonly<ApprovalContext>): PermissionDecision | null {
|
|
1034
|
+
if (!capabilities?.length) return null
|
|
1035
|
+
const matches = capabilities.map(capability => this.matchRules(rule => rule.type === "allow" && capabilityRuleMatches(rule, capability, this.cwd, context)))
|
|
1036
|
+
return matches.every(Boolean) ? matches[0]! : null
|
|
817
1037
|
}
|
|
818
1038
|
|
|
819
1039
|
private matchRules(matches: (rule: PermissionRule) => boolean): PermissionDecision | null {
|
|
@@ -839,13 +1059,22 @@ export class PermissionManager {
|
|
|
839
1059
|
if (!command.trim()) return { decision: "ask" }
|
|
840
1060
|
const subs = splitShellSubcommands(command, syntax)
|
|
841
1061
|
if (subs.length === 0) return { decision: "ask" }
|
|
1062
|
+
const significant = significantShellSubcommands(subs, this.cwd, runDir)
|
|
842
1063
|
|
|
843
1064
|
let firstAllowRule: PermissionRule | undefined
|
|
844
1065
|
let firstAllowScope: RuleScope | undefined
|
|
845
1066
|
let ask: PermissionDecision | undefined
|
|
1067
|
+
let dir = runDir
|
|
846
1068
|
for (const sub of subs) {
|
|
847
|
-
const r = this.checkShellSubcommand(sub,
|
|
1069
|
+
const r = this.checkShellSubcommand(sub, dir, toolName)
|
|
848
1070
|
if (r === null) {
|
|
1071
|
+
// Rules still apply to neutral subcommands; only the missing rule is waived.
|
|
1072
|
+
if (!significant.includes(sub)) {
|
|
1073
|
+
// Later pieces run elsewhere than built-in allowances would judge
|
|
1074
|
+
// them (`cd sub; cat link`), so only user rules may allow them.
|
|
1075
|
+
if (/^cd\s/.test(sub.trim())) dir = null
|
|
1076
|
+
continue
|
|
1077
|
+
}
|
|
849
1078
|
ask ??= { decision: "ask" }
|
|
850
1079
|
continue
|
|
851
1080
|
}
|