zapagent 1.14.23 → 1.14.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,8 +6,10 @@ 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"
12
+ import type { PermissionRule } from "../permissions.js"
11
13
  import { buildEditPreview, isEditTool } from "../ui/edit-preview.js"
12
14
  import { getToolAlias } from "../ui/transcript-format.js"
13
15
  import type { ApprovalCallback, ApprovalContext, ApprovalResponse } from "../../zapsdk/tools/executor.js"
@@ -27,8 +29,10 @@ interface PendingApproval {
27
29
  name: string
28
30
  args: Record<string, unknown>
29
31
  allowScope: boolean
32
+ /** One-time approvals of the same consent earlier this session. */
33
+ repeats: number
30
34
  resolve: (choice: ApprovalChoice) => void
31
- grant: (request: ToolGrantRequest, availableTools: string[]) => string | void
35
+ grant: (request: ToolGrantRequest, availableTools: string[], reviewedRules?: readonly PermissionRule[]) => string | void
32
36
  }
33
37
 
34
38
  export interface UsePermissionApprovalOptions {
@@ -66,8 +70,6 @@ export function usePermissionApproval(
66
70
  async (
67
71
  name: string,
68
72
  ar: Record<string, unknown>,
69
- mode: string,
70
- why: string,
71
73
  signal?: AbortSignal,
72
74
  allowScope = true,
73
75
  context?: Readonly<ApprovalContext>,
@@ -75,13 +77,6 @@ export function usePermissionApproval(
75
77
  ): Promise<ApprovalResponse> => {
76
78
  const sessionId = getCurrentSessionId()
77
79
  if (signal?.aborted) return false
78
- try {
79
- // Match the `permission_decision` log line emitted in onApproval's
80
- // synchronous decision tiers so log consumers see a uniform format.
81
- appLogger.info(
82
- `permission_decision tool=${name} mode=${mode} decision=ask (${why})`,
83
- )
84
- } catch {}
85
80
  // For edit/create tools, push a scrollback "approval" log carrying the
86
81
  // proposed diff *before* showing the live ApprovalBar. The entry is
87
82
  // finalized at addLog time (no replaceLog) so it commits to Static
@@ -150,12 +145,14 @@ export function usePermissionApproval(
150
145
  name,
151
146
  args: ar,
152
147
  allowScope,
153
- grant: (request, availableTools) => {
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),
150
+ grant: (request, availableTools, reviewedRules) => {
154
151
  const expired = validate()
155
152
  if (expired) return expired
156
153
  if (!scopeAllowed || (approvalFacts(name, ar, context).sandboxEscape)) return "This approval only supports its displayed choices"
157
154
  try {
158
- const rules = buildToolGrantRules(request, availableTools)
155
+ const rules = buildToolGrantRules(request, availableTools, context?.workspaceRoot ?? process.cwd(), reviewedRules)
159
156
  if (!permissionManager.grantCoversCall(rules, name, ar, context)) return "The selected authorization must cover this waiting call"
160
157
  permissionManager.addToolRules(rules, request.lifetime)
161
158
  addLog("system", `Permission: ${request.lifetime} allow saved: ${rules.map(rule => rule.pattern).join(", ")}; manage in /permissions`)
@@ -168,7 +165,7 @@ export function usePermissionApproval(
168
165
  clear()
169
166
  // A stale or synthetic scope choice cannot extend a one-time prompt.
170
167
  if (!scopeAllowed && choice !== "deny") choice = "once"
171
- try { appLogger.info(`permission_user tool=${name} choice=${choice}`) } catch {}
168
+ try { appLogger.info("permission_user", { tool: name, choice }) } catch {}
172
169
  const escape = approvalFacts(name, ar, context).sandboxEscape
173
170
  if (escape) {
174
171
  if (choice === "always" || choice === "forever") {
@@ -195,7 +192,9 @@ export function usePermissionApproval(
195
192
  } else if (choice === "deny") {
196
193
  addLog("system", `Permission: user denied ${getToolAlias(name)}`)
197
194
  }
198
- settle(choice !== "deny" ? true : { approved: false, source: "approval", reason: "user declined approval" })
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" })
199
198
  },
200
199
  })
201
200
  })
@@ -203,26 +202,46 @@ export function usePermissionApproval(
203
202
  [addLog, configRef],
204
203
  )
205
204
 
206
- const onApproval = useCallback(
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(
207
221
  (toolName: string, args: Record<string, unknown>, signal?: AbortSignal, context?: Readonly<ApprovalContext>): Promise<ApprovalResponse> => {
208
222
  queue.cancelStale()
209
223
  return queue.enqueue(async (signal, id) => {
210
224
  if (signal?.aborted) return Promise.resolve(false)
211
- permissionManager.setSessionId(getCurrentSessionId())
212
- const mode = configRef.current.permissionMode
213
- const decision = evaluateApprovalPolicy(permissionManager, toolName, args, { mode, cwd: process.cwd(), context })
214
- 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)
215
227
  if (decision.decision === "allow") return Promise.resolve(true)
216
- if (decision.decision === "deny") {
217
- addLog("system", `Permission: denied ${getToolAlias(toolName)} — ${decision.reason}`)
218
- return Promise.resolve({ approved: false, source: "policy", reason: decision.reason })
219
- }
228
+ if (decision.decision === "deny") return Promise.resolve({ approved: false, source: "policy", reason: decision.reason })
220
229
  if (decision.source === "dangerous") addLog("system", `Approval required for ${decision.reason}`)
221
- return promptApproval(toolName, args, mode, decision.reason, signal, decision.allowScope, context, id)
230
+ return promptApproval(toolName, args, signal, decision.allowScope, context, id)
222
231
  }, signal)
223
232
  },
224
- [addLog, configRef, promptApproval, queue],
233
+ [addLog, decide, promptApproval, queue],
225
234
  )
226
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
+
227
246
  return { onApproval, pendingApproval }
228
247
  }
@@ -0,0 +1,54 @@
1
+ import type { Provider } from "./config.js"
2
+ import { discoverProviderModels, type CatalogRow, type DiscoveredCatalog } from "./provider-catalog.js"
3
+
4
+ export interface ConnectionCatalog extends DiscoveredCatalog {
5
+ providerId: string
6
+ loading: boolean
7
+ }
8
+
9
+ export function savedConnectionCatalogs(providers: readonly Provider[]): ConnectionCatalog[] {
10
+ return providers.map(provider => ({ providerId: provider.id, loading: true,
11
+ rows: provider.models.map(id => ({ id, source: "saved", metadata: provider.modelMetadata?.[id] })),
12
+ }))
13
+ }
14
+
15
+ export function modelCatalogKey(providerId: string, modelId: string): string {
16
+ return JSON.stringify([providerId, modelId])
17
+ }
18
+
19
+ export interface ConnectionModelRow extends CatalogRow { provider: Provider }
20
+
21
+ export function configuredModelRows(providers: readonly Provider[], catalogs: readonly ConnectionCatalog[], providerId: string | null, query: string): ConnectionModelRow[] {
22
+ const search = query.trim().toLowerCase()
23
+ return providers.filter(provider => providerId === null || provider.id === providerId).flatMap(provider => {
24
+ const rows = catalogs.find(catalog => catalog.providerId === provider.id)?.rows ?? []
25
+ return rows.filter(row => !search || [row.id, provider.name, provider.baseURL].some(value => value.toLowerCase().includes(search)))
26
+ .map(row => ({ ...row, provider }))
27
+ })
28
+ }
29
+
30
+ /** Each connection settles independently. One hung endpoint cannot block the list. */
31
+ export function discoverConfiguredModels(providers: readonly Provider[], onUpdate: (catalog: ConnectionCatalog) => void,
32
+ discover: typeof discoverProviderModels = discoverProviderModels, timeoutMs = 6500): () => void {
33
+ const disposers = providers.map(provider => {
34
+ const controller = new AbortController()
35
+ let finished = false
36
+ const saved = savedConnectionCatalogs([provider])[0]
37
+ const timer = setTimeout(() => {
38
+ if (finished) return
39
+ finished = true; controller.abort()
40
+ onUpdate({ ...saved, loading: false, error: "Discovery timed out. Saved models remain available; press t to enter an ID." })
41
+ }, timeoutMs)
42
+ void Promise.resolve().then(() => { controller.signal.throwIfAborted(); return discover(provider, controller.signal) }).then(result => {
43
+ if (finished) return
44
+ finished = true; clearTimeout(timer)
45
+ onUpdate({ ...result, providerId: provider.id, loading: false })
46
+ }).catch(() => {
47
+ if (finished) return
48
+ finished = true; clearTimeout(timer)
49
+ onUpdate({ ...saved, loading: false, error: "Discovery unavailable. Saved models remain available; press r to retry." })
50
+ })
51
+ return () => { finished = true; controller.abort(); clearTimeout(timer) }
52
+ })
53
+ return () => { for (const dispose of disposers) dispose() }
54
+ }
@@ -1,8 +1,9 @@
1
1
  import type { PermissionMode } from "./config.js"
2
- import { PermissionManager, isPathReadTool, pathReadOutsideCwdReason } from "./permissions.js"
2
+ 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 result = (decision: ApprovalPolicyDecision["decision"], reason: string, source: ApprovalPolicyDecision["source"] = "policy", allowScope = false): ApprovalPolicyDecision => ({ decision, reason, source, allowScope })
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?.pattern}`, "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,14 +79,21 @@ 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")
51
- if (isPathReadTool(name)) {
52
- const outside = pathReadOutsideCwdReason(name, args, options.context?.workspaceRoot ?? options.cwd)
53
- return outside ? result("ask", outside, "fallback", true) : result("allow", "project path read")
54
- }
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")
93
+ // Reading screenshots, skill resources and reference files must not require
94
+ // a new grant for every path. Explicit restrictions were checked above;
95
+ // filesystem confinement remains the executor/backend's responsibility.
96
+ if (isPathReadTool(name) && facts.readOnly) return result("allow", "read-only filesystem access")
55
97
  if (options.mode === "bypassPermissions") return result("allow", "bypassPermissions mode")
56
98
  if (options.mode === "acceptEdits" && facts.editOnly) return result("allow", "acceptEdits mode")
57
99
  return result("ask", "no rule, prompting user", "fallback", true)