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/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
|
|
|
@@ -23,6 +27,8 @@ export interface PermissionRule {
|
|
|
23
27
|
* deny wins over ask, and ask wins over allow, including bypass mode. */
|
|
24
28
|
pattern: string
|
|
25
29
|
type: RuleType
|
|
30
|
+
/** Folder grants store a reviewed canonical target, never a live symlink alias. */
|
|
31
|
+
canonicalPath?: true
|
|
26
32
|
}
|
|
27
33
|
|
|
28
34
|
export interface PermissionSettings {
|
|
@@ -173,9 +179,24 @@ function stripProcessWrappers(parts: string[]): string[] {
|
|
|
173
179
|
|
|
174
180
|
// Import and re-export from shared utility so callers only need one import
|
|
175
181
|
import { matchCommandGlob, matchesAnyCommandPattern, shellCommandDisplay, shellExecutionCommands, splitShellSubcommands } from "../zapsdk/utils/shell.js"
|
|
176
|
-
import { effectiveCommandCwd, isReadOnlyCommand } from "./readonly-commands.js"
|
|
182
|
+
import { effectiveCommandCwd, isNeutralShellSubcommand, isReadOnlyCommand } from "./readonly-commands.js"
|
|
177
183
|
export { splitShellSubcommands }
|
|
178
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
|
+
|
|
179
200
|
// ─── Pattern parsing ──────────────────────────────────────────────────────────
|
|
180
201
|
|
|
181
202
|
const TOOL_ALIASES: Record<string, string[]> = {
|
|
@@ -384,9 +405,9 @@ function extractArgString(toolName: string, args: Record<string, unknown>): stri
|
|
|
384
405
|
return typeof first === "string" ? first : ""
|
|
385
406
|
}
|
|
386
407
|
|
|
387
|
-
function matchFilePattern(path: string, pattern: string): boolean {
|
|
408
|
+
function matchFilePattern(path: string, pattern: string, canonicalPath = false): boolean {
|
|
388
409
|
if (!isAbsolute(pattern) && (isAbsolute(path) || path === ".." || path.startsWith("../") || path.startsWith("..\\"))) return false
|
|
389
|
-
return matchGlob(path, pattern) || (isAbsolute(pattern) && matchGlob(path, canonicalizeWithNearestExistingAncestorSync(pattern)))
|
|
410
|
+
return matchGlob(path, pattern) || (!canonicalPath && isAbsolute(pattern) && matchGlob(path, canonicalizeWithNearestExistingAncestorSync(pattern)))
|
|
390
411
|
}
|
|
391
412
|
|
|
392
413
|
/** Directory readers may touch every descendant. When a restriction could
|
|
@@ -424,12 +445,71 @@ export function ruleMatchesTool(
|
|
|
424
445
|
if (argPattern === null) return true
|
|
425
446
|
if (toolName === "move_file") {
|
|
426
447
|
const paths = [args.source, args.destination].filter((value): value is string => typeof value === "string" && !!value)
|
|
427
|
-
return rule.type === "allow" ? paths.length === 2 && paths.every(path => matchFilePattern(path, argPattern)) : paths.some(path => matchFilePattern(path, argPattern))
|
|
448
|
+
return rule.type === "allow" ? paths.length === 2 && paths.every(path => matchFilePattern(path, argPattern, rule.canonicalPath)) : paths.some(path => matchFilePattern(path, argPattern))
|
|
428
449
|
}
|
|
429
450
|
const subject = extractArgString(toolName, args)
|
|
430
451
|
if (toolName === "bash") return matchCommandGlob(subject, argPattern)
|
|
431
452
|
if (toolName === "delegate_agent") return subject === argPattern
|
|
432
|
-
return FILE_TOOLS.has(toolName) ? matchFilePattern(subject, argPattern) : matchGlob(subject, argPattern)
|
|
453
|
+
return FILE_TOOLS.has(toolName) ? matchFilePattern(subject, argPattern, rule.type === "allow" && rule.canonicalPath) : matchGlob(subject, argPattern)
|
|
454
|
+
}
|
|
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
|
|
433
513
|
}
|
|
434
514
|
|
|
435
515
|
// ─── Shadow detection ─────────────────────────────────────────────────────────
|
|
@@ -595,19 +675,33 @@ export function inferPattern(toolName: string, args: Record<string, unknown>, cw
|
|
|
595
675
|
|
|
596
676
|
/** The same complete rule set powers previews and both persistence lifetimes. */
|
|
597
677
|
export function inferInvocationRules(name: string, args: Record<string, unknown>, cwd: string, context?: Readonly<ApprovalContext>): PermissionRule[] {
|
|
598
|
-
|
|
599
|
-
|
|
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))] : []
|
|
600
686
|
if (opaqueShell(approvalFacts(name, args, context), context)) return [name, ...pathPatterns].map(pattern => ({ pattern, type: "allow" }))
|
|
601
687
|
const views = [normalizeFileArgs(name, args, cwd, context)]
|
|
602
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
|
|
603
691
|
const invocations = views.flatMap(normalized => name === "bash"
|
|
604
|
-
? 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 }))
|
|
605
693
|
: name === "move_file" ? [normalized.source, normalized.destination].map(path => ({ source: path, destination: path })) : [normalized])
|
|
606
694
|
const patterns = invocations.map(value => inferPattern(name, value, cwd)).filter((pattern): pattern is string => !!pattern)
|
|
607
695
|
patterns.push(...pathPatterns)
|
|
608
696
|
return [...new Set(patterns)].map(pattern => ({ pattern, type: "allow" }))
|
|
609
697
|
}
|
|
610
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
|
+
|
|
611
705
|
function shellPathRequests(args: Record<string, unknown>, cwd: string): Array<{ tool: "read_file" | "write_file"; path: string }> {
|
|
612
706
|
const runCwd = resolveToolPathCanonical(typeof args.cwd === "string" ? args.cwd : cwd, cwd)
|
|
613
707
|
return ([ ["read_paths", "read_file"], ["write_paths", "write_file"] ] as const).flatMap(([field, tool]) =>
|
|
@@ -644,6 +738,19 @@ export class PermissionManager {
|
|
|
644
738
|
private sandboxExcluded: string[] = []
|
|
645
739
|
setSandboxExcludedCommands(patterns: string[] | undefined): void { this.sandboxExcluded = patterns ?? [] }
|
|
646
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
|
+
|
|
647
754
|
setSandboxConfined(confined: boolean, autoAllowAll = true): void {
|
|
648
755
|
this.sandboxConfined = confined
|
|
649
756
|
this.sandboxAutoAllow = autoAllowAll
|
|
@@ -661,6 +768,56 @@ export class PermissionManager {
|
|
|
661
768
|
this.sandboxSessionId = sessionId
|
|
662
769
|
this.sessionSandboxEscape = undefined
|
|
663
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
|
|
664
821
|
}
|
|
665
822
|
|
|
666
823
|
/** Dedicated consent is separate from ordinary Bash command allow rules. */
|
|
@@ -695,8 +852,8 @@ export class PermissionManager {
|
|
|
695
852
|
if (!rules.length || rules.some(rule => rule.type !== "allow" || rule.pattern === SANDBOX_ESCAPE_RULE)) throw new Error("Invalid tool grant")
|
|
696
853
|
const path = getProjectAuthorizationSettingsPath(this.cwd)
|
|
697
854
|
const existing = lifetime === "session" ? [...this.sessionRules] : loadPermissionSettings(path).rules
|
|
698
|
-
const added = rules.filter((rule, index) => !existing.some(value => value.type === rule.type && value.pattern === rule.pattern)
|
|
699
|
-
&& rules.findIndex(value => value.type === rule.type && value.pattern === rule.pattern) === index)
|
|
855
|
+
const added = rules.filter((rule, index) => !existing.some(value => value.type === rule.type && value.pattern === rule.pattern && value.canonicalPath === rule.canonicalPath)
|
|
856
|
+
&& rules.findIndex(value => value.type === rule.type && value.pattern === rule.pattern && value.canonicalPath === rule.canonicalPath) === index)
|
|
700
857
|
const next = [...existing, ...added]
|
|
701
858
|
if (lifetime === "session") this.sessionRules = next
|
|
702
859
|
else savePermissionSettings(path, { rules: next })
|
|
@@ -713,12 +870,18 @@ export class PermissionManager {
|
|
|
713
870
|
const fileArgs = normalizeFileArgs(tool, { path }, this.cwd, context)
|
|
714
871
|
return rules.some(rule => rule.type === "allow" && ruleMatchesTool(rule, tool, fileArgs))
|
|
715
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
|
|
716
875
|
if (opaqueShell(facts, context)) return rules.some(rule => rule.type === "allow" && isWholeToolRule(rule, name))
|
|
717
876
|
if (name === "bash") {
|
|
718
|
-
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)))
|
|
719
879
|
return commands.length > 0 && commands.every(command => rules.some(rule =>
|
|
720
880
|
ruleMatchesTool(rule, name, { command }) || ruleMatchesTool(rule, name, { command: normalizeBashSubcommand(command) })))
|
|
721
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
|
|
722
885
|
const views = [normalized]
|
|
723
886
|
if (MUTATION_TOOLS.has(name)) views.push(normalizeFileArgs(name, args, this.cwd, context, "entry"))
|
|
724
887
|
return views.every(view => name === "move_file" ? [view.source, view.destination].every(path =>
|
|
@@ -741,7 +904,7 @@ export class PermissionManager {
|
|
|
741
904
|
checkPermission(toolName: string, args: Record<string, unknown>, context?: Readonly<ApprovalContext>): PermissionDecision {
|
|
742
905
|
const base = this.checkPermissionCore(toolName, args, context)
|
|
743
906
|
if (toolName !== "bash" || base.decision === "deny") return base
|
|
744
|
-
const decisions = [base, this.checkShellPaths(args, context)]
|
|
907
|
+
const decisions = [base, this.checkShellPaths(args, context), this.checkShellNetwork(args, context)]
|
|
745
908
|
return decisions.find(value => value.decision === "deny")
|
|
746
909
|
?? decisions.find(value => value.decision === "ask" && value.rule)
|
|
747
910
|
?? decisions.find(value => value.decision === "ask") ?? base
|
|
@@ -766,6 +929,43 @@ export class PermissionManager {
|
|
|
766
929
|
?? decisions.find(value => value.decision === "ask") ?? { decision: "allow" }
|
|
767
930
|
}
|
|
768
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
|
+
|
|
769
969
|
private checkPermissionCore(toolName: string, args: Record<string, unknown>, context?: Readonly<ApprovalContext>): PermissionDecision {
|
|
770
970
|
// Normalize once at the entry; rule evaluation and generation both
|
|
771
971
|
// operate in cwd-relative space afterwards. This is the fix for the
|
|
@@ -777,14 +977,16 @@ export class PermissionManager {
|
|
|
777
977
|
const lexical = normalizeFileArgs(toolName, args, this.cwd, context, false)
|
|
778
978
|
const views = [a]
|
|
779
979
|
if (MUTATION_TOOLS.has(toolName)) views.push(normalizeFileArgs(toolName, args, this.cwd, context, "entry"))
|
|
780
|
-
const
|
|
980
|
+
const capabilities = fileToolCapabilities(toolName, args)
|
|
981
|
+
const restriction = strongestRestriction(this.matchRules(rule => rule.type !== "allow" && (
|
|
781
982
|
[...views, lexical].some(view => ruleMatchesTool(rule, toolName, view))
|
|
782
|
-
|| isDirectoryReadTool(toolName) && directoryRuleIntersects(rule, toolName, args, this.cwd, context)))
|
|
983
|
+
|| isDirectoryReadTool(toolName) && directoryRuleIntersects(rule, toolName, args, this.cwd, context))),
|
|
984
|
+
this.capabilityRestriction(capabilities, context))
|
|
783
985
|
if (restriction) return restriction
|
|
784
986
|
const matches = views.flatMap(view => toolName === "move_file" ? [view.source, view.destination].map(path =>
|
|
785
987
|
typeof path === "string" && !!path ? this.matchRules(rule => rule.type === "allow" && ruleMatchesTool(rule, toolName, { source: path, destination: path })) : null)
|
|
786
988
|
: [this.matchRules(rule => rule.type === "allow" && ruleMatchesTool(rule, toolName, view))])
|
|
787
|
-
return matches.every(Boolean) ? matches[0]! : { decision: "ask" }
|
|
989
|
+
return matches.every(Boolean) ? matches[0]! : this.capabilityAllow(capabilities, context) ?? { decision: "ask" }
|
|
788
990
|
}
|
|
789
991
|
|
|
790
992
|
const facts = approvalFacts(toolName, args, context)
|
|
@@ -811,7 +1013,27 @@ export class PermissionManager {
|
|
|
811
1013
|
return decisions.find(decision => decision.decision === "ask") ?? decisions[0] ?? { decision: "ask" }
|
|
812
1014
|
}
|
|
813
1015
|
|
|
814
|
-
|
|
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
|
|
815
1037
|
}
|
|
816
1038
|
|
|
817
1039
|
private matchRules(matches: (rule: PermissionRule) => boolean): PermissionDecision | null {
|
|
@@ -837,13 +1059,22 @@ export class PermissionManager {
|
|
|
837
1059
|
if (!command.trim()) return { decision: "ask" }
|
|
838
1060
|
const subs = splitShellSubcommands(command, syntax)
|
|
839
1061
|
if (subs.length === 0) return { decision: "ask" }
|
|
1062
|
+
const significant = significantShellSubcommands(subs, this.cwd, runDir)
|
|
840
1063
|
|
|
841
1064
|
let firstAllowRule: PermissionRule | undefined
|
|
842
1065
|
let firstAllowScope: RuleScope | undefined
|
|
843
1066
|
let ask: PermissionDecision | undefined
|
|
1067
|
+
let dir = runDir
|
|
844
1068
|
for (const sub of subs) {
|
|
845
|
-
const r = this.checkShellSubcommand(sub,
|
|
1069
|
+
const r = this.checkShellSubcommand(sub, dir, toolName)
|
|
846
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
|
+
}
|
|
847
1078
|
ask ??= { decision: "ask" }
|
|
848
1079
|
continue
|
|
849
1080
|
}
|
|
@@ -965,7 +1196,7 @@ export class PermissionManager {
|
|
|
965
1196
|
/** Attribute a rule object to the settings layer it lives in. */
|
|
966
1197
|
private locateRuleScope(rule: PermissionRule): RuleScope {
|
|
967
1198
|
const findsIt = (p: string) =>
|
|
968
|
-
loadPermissionSettings(p).rules.some(r => r.pattern === rule.pattern && r.type === rule.type)
|
|
1199
|
+
loadPermissionSettings(p).rules.some(r => r.pattern === rule.pattern && r.type === rule.type && r.canonicalPath === rule.canonicalPath)
|
|
969
1200
|
if (findsIt(getProjectAuthorizationSettingsPath(this.cwd))) return "project"
|
|
970
1201
|
if (findsIt(getProjectLocalSettingsPath(this.cwd))) return "local"
|
|
971
1202
|
if (findsIt(getProjectSettingsPath(this.cwd))) return "project"
|
|
@@ -1011,14 +1242,15 @@ export class PermissionManager {
|
|
|
1011
1242
|
* scope it was removed from, or null if no rule matched. An explicit removal
|
|
1012
1243
|
* scope targets the displayed group, separating host grants from repo rules.
|
|
1013
1244
|
*/
|
|
1014
|
-
removeRule(pattern: string, type: RuleType, scope?: RuleRemovalScope): RuleScope | null {
|
|
1245
|
+
removeRule(pattern: string, type: RuleType, scope?: RuleRemovalScope, canonicalPath?: boolean): RuleScope | null {
|
|
1015
1246
|
if ((!scope || scope === "session") && this.sessionSandboxEscape?.pattern === pattern && this.sessionSandboxEscape.type === type) {
|
|
1016
1247
|
this.sessionSandboxEscape = undefined
|
|
1017
1248
|
this.logger?.log("info", "permission_rule_removed", { pattern, type, scope: "session" })
|
|
1018
1249
|
return "session"
|
|
1019
1250
|
}
|
|
1020
1251
|
// Session first (in-memory)
|
|
1021
|
-
const
|
|
1252
|
+
const matches = (r: PermissionRule) => r.pattern === pattern && r.type === type && (canonicalPath === undefined || (r.canonicalPath === true) === canonicalPath)
|
|
1253
|
+
const sessionIdx = this.sessionRules.findIndex(matches)
|
|
1022
1254
|
if (sessionIdx >= 0 && (!scope || scope === "session")) {
|
|
1023
1255
|
this.sessionRules.splice(sessionIdx, 1)
|
|
1024
1256
|
this.logger?.log("info", "permission_rule_removed", { pattern, type, scope: "session" })
|
|
@@ -1035,7 +1267,7 @@ export class PermissionManager {
|
|
|
1035
1267
|
if (scope && layer.scope !== scope) continue
|
|
1036
1268
|
const { scope: layerScope, path } = layer
|
|
1037
1269
|
const settings = loadPermissionSettings(path)
|
|
1038
|
-
const idx = settings.rules.findIndex(
|
|
1270
|
+
const idx = settings.rules.findIndex(matches)
|
|
1039
1271
|
if (idx >= 0) {
|
|
1040
1272
|
settings.rules.splice(idx, 1)
|
|
1041
1273
|
savePermissionSettings(path, settings)
|
|
@@ -1095,6 +1327,7 @@ export class PermissionManager {
|
|
|
1095
1327
|
const cur = checkOrder[i]
|
|
1096
1328
|
for (let j = 0; j < i; j++) {
|
|
1097
1329
|
const earlier = checkOrder[j]
|
|
1330
|
+
if (earlier.rule.canonicalPath && !cur.rule.canonicalPath) continue
|
|
1098
1331
|
if (patternCovers(earlier.rule.pattern, cur.rule.pattern)) {
|
|
1099
1332
|
shadowMap.set(cur.rule, earlier)
|
|
1100
1333
|
break
|
package/src/readonly-commands.ts
CHANGED
|
@@ -357,3 +357,34 @@ export function effectiveCommandCwd(workspace: string, cwdArg: unknown): string
|
|
|
357
357
|
if (dir === null || !insideWorkspace(dir, workspace)) return null
|
|
358
358
|
return dir
|
|
359
359
|
}
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* A subcommand that adds nothing to the command it accompanies: `cd` into a
|
|
363
|
+
* workspace directory, or a stdin filter (`head`/`tail` without operands, a
|
|
364
|
+
* non-recursive `grep` whose only operand is its pattern). Callers skip these
|
|
365
|
+
* only next to a sibling that is judged on its own, which already holds more
|
|
366
|
+
* capability than reading its own output.
|
|
367
|
+
*/
|
|
368
|
+
export function isNeutralShellSubcommand(command: string, workspace: string, runDir: string): boolean {
|
|
369
|
+
if (process.platform === "win32") return false
|
|
370
|
+
if (!command.trim() || SHELL_METACHARACTERS.test(command)) return false
|
|
371
|
+
const tokens = words(command.trim())
|
|
372
|
+
if (!tokens || tokens.length === 0 || tokens.some(token => token.unquotedExpansion)) return false
|
|
373
|
+
const name = tokens[0]!.text
|
|
374
|
+
const args = tokens.slice(1)
|
|
375
|
+
if (name === "cd") {
|
|
376
|
+
const target = args[0]?.text
|
|
377
|
+
if (args.length !== 1 || !target || target.startsWith("-") || target.startsWith("~") || target.includes("$")) return false
|
|
378
|
+
if (target.split(/[\\/]+/).includes("..")) return false
|
|
379
|
+
return effectiveCommandCwd(workspace, isAbsolute(target) ? target : join(runDir, target)) !== null
|
|
380
|
+
}
|
|
381
|
+
if (name !== "head" && name !== "tail" && name !== "grep") return false
|
|
382
|
+
if (!isReadOnlyCommand(command, runDir)) return false
|
|
383
|
+
const operands = parseArgs(args, SPECS[name]!)
|
|
384
|
+
if (operands === null) return false
|
|
385
|
+
if (name !== "grep") return operands.length === 0
|
|
386
|
+
// Conservative flag scan: any r/R or e letter in a short cluster counts.
|
|
387
|
+
const flags = args.filter(token => /^-[^-]/.test(token.text)).map(token => token.text)
|
|
388
|
+
if (flags.some(flag => /r/i.test(flag)) || args.some(token => token.text === "--recursive")) return false
|
|
389
|
+
return operands.length === (flags.some(flag => flag.includes("e")) ? 0 : 1)
|
|
390
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { z } from "zod"
|
|
2
|
+
import type { Tool, ToolResult } from "../zapsdk/tools/types.js"
|
|
3
|
+
import { emptyToolEffects } from "../zapsdk/tools/effects.js"
|
|
4
|
+
import { CAPABILITY_KINDS, MAX_REQUESTED_CAPABILITIES, REQUEST_CAPABILITIES_TOOL, capabilityPattern, describeCapabilityPatterns, parseCapabilityRequest } from "./capabilities.js"
|
|
5
|
+
|
|
6
|
+
/** Asks the user up front for what a task will need. The Host decides: the
|
|
7
|
+
* approval prompt saves the requested capability rules for the session or
|
|
8
|
+
* project, and deny/ask rules keep precedence over them. */
|
|
9
|
+
export function requestCapabilitiesTool(granted: (args: Record<string, unknown>) => boolean): Tool {
|
|
10
|
+
return {
|
|
11
|
+
definition: {
|
|
12
|
+
name: REQUEST_CAPABILITIES_TOOL,
|
|
13
|
+
description: "Ask the user once, before multi-step work, for the file edits, network hosts or external systems it will need, so later calls run without interrupting them.",
|
|
14
|
+
prompt: "Use only when a task will clearly need several approvals of the same kind (for example edits under src/** plus requests to one API host). " +
|
|
15
|
+
"Request the narrowest scopes that cover the work. File scopes are project-relative globs; net scopes are hosts (shell network_destinations need net.write); external scopes are systems such as mcp:<server>. " +
|
|
16
|
+
"This cannot authorize shell commands or running outside the sandbox. If the user declines, continue with ordinary per-call approval or ask them.",
|
|
17
|
+
parameters: z.object({
|
|
18
|
+
capabilities: z.array(z.object({
|
|
19
|
+
kind: z.enum(CAPABILITY_KINDS as [string, ...string[]]),
|
|
20
|
+
scope: z.string().min(1).max(200),
|
|
21
|
+
})).min(1).max(MAX_REQUESTED_CAPABILITIES),
|
|
22
|
+
reason: z.string().min(1).max(300).describe("What the task is and why it needs these capabilities"),
|
|
23
|
+
}),
|
|
24
|
+
permission: "confirm",
|
|
25
|
+
// Changes Host authorization state, so it is never read-only.
|
|
26
|
+
resolveEffects: () => ({ ...emptyToolEffects(), external: [{ kind: "external", system: "zapcode:permissions", operation: "mutate" }] }),
|
|
27
|
+
},
|
|
28
|
+
handler: async (args): Promise<ToolResult> => {
|
|
29
|
+
const requested = parseCapabilityRequest(args)
|
|
30
|
+
if (typeof requested === "string") return { success: false, output: "", error: requested }
|
|
31
|
+
const described = describeCapabilityPatterns(requested.map(capability => capabilityPattern(capability.kind, capability.scope)))
|
|
32
|
+
return granted(args)
|
|
33
|
+
? { success: true, output: `Granted: ${described}. Calls within these capabilities run without asking; deny/ask rules still apply and anything else still asks.` }
|
|
34
|
+
: { success: true, output: `Approved without saving: ${described}. Matching calls may still ask.` }
|
|
35
|
+
},
|
|
36
|
+
}
|
|
37
|
+
}
|
package/src/tool-grants.ts
CHANGED
|
@@ -1,18 +1,43 @@
|
|
|
1
|
-
import { isAbsolute } from "node:path"
|
|
2
|
-
import {
|
|
1
|
+
import { dirname, isAbsolute, join, relative, resolve } from "node:path"
|
|
2
|
+
import { homedir } from "node:os"
|
|
3
|
+
import { WORKSPACE_EDIT_TOOLS, type PermissionRule } from "./permissions.js"
|
|
4
|
+
import { canonicalizeWithNearestExistingAncestorSync } from "../zapsdk/builtin-tools/filesystem.js"
|
|
3
5
|
|
|
4
6
|
export interface ToolGrantRequest {
|
|
5
7
|
tools: string[]
|
|
6
|
-
resource: { kind: "all" } | { kind: "pattern"; value: string }
|
|
8
|
+
resource: { kind: "all" } | { kind: "pattern" | "directory"; value: string }
|
|
7
9
|
lifetime: "session" | "project"
|
|
8
10
|
}
|
|
9
11
|
|
|
10
12
|
export const FILE_GRANT_TOOLS = ["read_file", "list_tree", "read_document", "search_files", "glob_files", "write_file", "create_file", "edit_file", "multi_edit", "delete_file", "move_file"]
|
|
11
13
|
export const READ_GRANT_TOOLS = ["read_file", "list_tree", "read_document", "search_files", "glob_files"]
|
|
12
|
-
export const EDIT_GRANT_TOOLS = [
|
|
14
|
+
export const EDIT_GRANT_TOOLS = [...WORKSPACE_EDIT_TOOLS]
|
|
15
|
+
|
|
16
|
+
function expandDirectory(value: string): string {
|
|
17
|
+
return value === "~" ? homedir() : value.startsWith("~/") ? join(homedir(), value.slice(2)) : value
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Freeze the reviewed directory target; descendants outside it need another grant. */
|
|
21
|
+
function directoryGrantPattern(value: string, cwd: string): string {
|
|
22
|
+
const valid = (path: string) => !!path.trim() && !/[\r\n\0*?{}]/.test(path) && (process.platform === "win32" || !path.includes("\\"))
|
|
23
|
+
if (!valid(value)) throw new Error("Enter a literal folder path without glob characters")
|
|
24
|
+
const base = canonicalizeWithNearestExistingAncestorSync(resolve(cwd))
|
|
25
|
+
const target = canonicalizeWithNearestExistingAncestorSync(resolve(cwd, expandDirectory(value)))
|
|
26
|
+
if (!valid(target)) throw new Error("The folder target contains unsupported glob characters")
|
|
27
|
+
const rel = relative(base, target)
|
|
28
|
+
if (!rel) return "**"
|
|
29
|
+
const scope = (!isAbsolute(rel) && rel !== ".." && !rel.startsWith("../") && !rel.startsWith("..\\") ? rel : target).replaceAll("\\", "/")
|
|
30
|
+
return scope.endsWith("/") ? `${scope}{,**}` : `${scope}{,/**}`
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function suggestToolGrantDirectory(name: string, args: Record<string, unknown>, cwd = process.cwd()): string | undefined {
|
|
34
|
+
if (!FILE_GRANT_TOOLS.includes(name) || typeof args.path !== "string" || !args.path.trim()) return undefined
|
|
35
|
+
const path = resolve(cwd, expandDirectory(args.path))
|
|
36
|
+
return ["list_tree", "search_files", "glob_files"].includes(name) ? path : dirname(path)
|
|
37
|
+
}
|
|
13
38
|
|
|
14
39
|
/** Expand a reviewed snapshot of exact registry names; never save a tool wildcard. */
|
|
15
|
-
|
|
40
|
+
function expandToolGrantRules(request: ToolGrantRequest, availableTools: readonly string[], cwd: string): PermissionRule[] {
|
|
16
41
|
if (!["session", "project"].includes(request.lifetime)) throw new Error("Choose session or project lifetime")
|
|
17
42
|
const tools = [...new Set(request.tools)]
|
|
18
43
|
if (!tools.length) throw new Error("Select at least one tool")
|
|
@@ -21,12 +46,26 @@ export function buildToolGrantRules(request: ToolGrantRequest, availableTools: r
|
|
|
21
46
|
if (tool === "delegate_agent") throw new Error("delegate_agent requires a provider/cwd-scoped approval")
|
|
22
47
|
}
|
|
23
48
|
if (request.resource.kind === "all") return tools.map(tool => ({ pattern: tool, type: "allow" }))
|
|
49
|
+
const filesOnly = tools.every(tool => FILE_GRANT_TOOLS.includes(tool))
|
|
50
|
+
if (request.resource.kind === "directory") {
|
|
51
|
+
if (!filesOnly) throw new Error("Folder authorization requires file tools only")
|
|
52
|
+
const pattern = directoryGrantPattern(request.resource.value, cwd)
|
|
53
|
+
return tools.map(tool => ({ pattern: `${tool}(${pattern})`, type: "allow", canonicalPath: true }))
|
|
54
|
+
}
|
|
24
55
|
if (request.resource.kind !== "pattern") throw new Error("Choose a resource scope")
|
|
25
56
|
const value = request.resource.value.trim()
|
|
26
57
|
if (!value || /[\r\n\0()]/.test(value)) throw new Error("Enter a nonempty path glob or command pattern without parentheses")
|
|
27
|
-
const filesOnly = tools.every(tool => FILE_GRANT_TOOLS.includes(tool))
|
|
28
58
|
const bashOnly = tools.length === 1 && tools[0] === "bash"
|
|
29
59
|
if (!filesOnly && !bashOnly) throw new Error("A resource filter needs only file tools, or Bash alone; use entire tools for a mixed set")
|
|
30
60
|
if (filesOnly && (isAbsolute(value) || value.split(/[\\/]/).includes(".."))) throw new Error("Use a project-relative path glob without ..")
|
|
31
61
|
return tools.map(tool => ({ pattern: `${tool}(${value})`, type: "allow" }))
|
|
32
62
|
}
|
|
63
|
+
|
|
64
|
+
/** A save must still describe exactly the scope shown when review began. */
|
|
65
|
+
export function buildToolGrantRules(request: ToolGrantRequest, availableTools: readonly string[], cwd = process.cwd(), reviewedRules?: readonly PermissionRule[]): PermissionRule[] {
|
|
66
|
+
const rules = expandToolGrantRules(request, availableTools, cwd)
|
|
67
|
+
if (reviewedRules && JSON.stringify(rules) !== JSON.stringify(reviewedRules)) {
|
|
68
|
+
throw new Error("Authorization scope changed after review; go back and review it again")
|
|
69
|
+
}
|
|
70
|
+
return rules
|
|
71
|
+
}
|