zapagent 1.14.23 → 1.14.24

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zapagent",
3
- "version": "1.14.23",
3
+ "version": "1.14.24",
4
4
  "packageManager": "bun@1.3.14",
5
5
  "author": "",
6
6
  "main": "src/index.tsx",
package/src/App.tsx CHANGED
@@ -1134,6 +1134,8 @@ export function App() {
1134
1134
  availableTools={agentRef.current.registry.definitions().filter(tool => tool.permission === "confirm").map(tool => tool.name)}
1135
1135
  unsandboxed={approvalFacts(pendingApproval.name, pendingApproval.args, pendingApproval.context).sandboxEscape}
1136
1136
  rulePreview={inferInvocationRules(pendingApproval.name, pendingApproval.args, process.cwd(), pendingApproval.context).map(rule => rule.pattern).join(", ") || null}
1137
+ cwd={pendingApproval.context?.cwd}
1138
+ workspaceRoot={pendingApproval.context?.workspaceRoot}
1137
1139
  />
1138
1140
  )}
1139
1141
  {!inModal && pendingPlan && <PlanApprovalBar plan={pendingPlan.plan} onChoose={pendingPlan.resolve} />}
@@ -8,6 +8,7 @@ import { getCurrentSessionId } from "../session.js"
8
8
  import { approvalFacts } from "../approval-facts.js"
9
9
  import { evaluateApprovalPolicy } from "../permission-policy.js"
10
10
  import { buildToolGrantRules, type ToolGrantRequest } from "../tool-grants.js"
11
+ import type { PermissionRule } from "../permissions.js"
11
12
  import { buildEditPreview, isEditTool } from "../ui/edit-preview.js"
12
13
  import { getToolAlias } from "../ui/transcript-format.js"
13
14
  import type { ApprovalCallback, ApprovalContext, ApprovalResponse } from "../../zapsdk/tools/executor.js"
@@ -28,7 +29,7 @@ interface PendingApproval {
28
29
  args: Record<string, unknown>
29
30
  allowScope: boolean
30
31
  resolve: (choice: ApprovalChoice) => void
31
- grant: (request: ToolGrantRequest, availableTools: string[]) => string | void
32
+ grant: (request: ToolGrantRequest, availableTools: string[], reviewedRules?: readonly PermissionRule[]) => string | void
32
33
  }
33
34
 
34
35
  export interface UsePermissionApprovalOptions {
@@ -150,12 +151,12 @@ export function usePermissionApproval(
150
151
  name,
151
152
  args: ar,
152
153
  allowScope,
153
- grant: (request, availableTools) => {
154
+ grant: (request, availableTools, reviewedRules) => {
154
155
  const expired = validate()
155
156
  if (expired) return expired
156
157
  if (!scopeAllowed || (approvalFacts(name, ar, context).sandboxEscape)) return "This approval only supports its displayed choices"
157
158
  try {
158
- const rules = buildToolGrantRules(request, availableTools)
159
+ const rules = buildToolGrantRules(request, availableTools, context?.workspaceRoot ?? process.cwd(), reviewedRules)
159
160
  if (!permissionManager.grantCoversCall(rules, name, ar, context)) return "The selected authorization must cover this waiting call"
160
161
  permissionManager.addToolRules(rules, request.lifetime)
161
162
  addLog("system", `Permission: ${request.lifetime} allow saved: ${rules.map(rule => rule.pattern).join(", ")}; manage in /permissions`)
@@ -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,5 +1,5 @@
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"
@@ -48,10 +48,10 @@ export function evaluateApprovalPolicy(manager: PermissionManager, name: string,
48
48
  if (rule.decision === "allow") return result("allow", rule.reason ?? `rule ${rule.rule?.pattern}`, "rule")
49
49
  if (options.allowedTools?.includes(name)) return result("allow", "allowed by --allowed-tools")
50
50
  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
- }
51
+ // Reading screenshots, skill resources and reference files must not require
52
+ // a new grant for every path. Explicit restrictions were checked above;
53
+ // filesystem confinement remains the executor/backend's responsibility.
54
+ if (isPathReadTool(name) && facts.readOnly) return result("allow", "read-only filesystem access")
55
55
  if (options.mode === "bypassPermissions") return result("allow", "bypassPermissions mode")
56
56
  if (options.mode === "acceptEdits" && facts.editOnly) return result("allow", "acceptEdits mode")
57
57
  return result("ask", "no rule, prompting user", "fallback", true)
@@ -23,6 +23,8 @@ export interface PermissionRule {
23
23
  * deny wins over ask, and ask wins over allow, including bypass mode. */
24
24
  pattern: string
25
25
  type: RuleType
26
+ /** Folder grants store a reviewed canonical target, never a live symlink alias. */
27
+ canonicalPath?: true
26
28
  }
27
29
 
28
30
  export interface PermissionSettings {
@@ -384,9 +386,9 @@ function extractArgString(toolName: string, args: Record<string, unknown>): stri
384
386
  return typeof first === "string" ? first : ""
385
387
  }
386
388
 
387
- function matchFilePattern(path: string, pattern: string): boolean {
389
+ function matchFilePattern(path: string, pattern: string, canonicalPath = false): boolean {
388
390
  if (!isAbsolute(pattern) && (isAbsolute(path) || path === ".." || path.startsWith("../") || path.startsWith("..\\"))) return false
389
- return matchGlob(path, pattern) || (isAbsolute(pattern) && matchGlob(path, canonicalizeWithNearestExistingAncestorSync(pattern)))
391
+ return matchGlob(path, pattern) || (!canonicalPath && isAbsolute(pattern) && matchGlob(path, canonicalizeWithNearestExistingAncestorSync(pattern)))
390
392
  }
391
393
 
392
394
  /** Directory readers may touch every descendant. When a restriction could
@@ -424,12 +426,12 @@ export function ruleMatchesTool(
424
426
  if (argPattern === null) return true
425
427
  if (toolName === "move_file") {
426
428
  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))
429
+ return rule.type === "allow" ? paths.length === 2 && paths.every(path => matchFilePattern(path, argPattern, rule.canonicalPath)) : paths.some(path => matchFilePattern(path, argPattern))
428
430
  }
429
431
  const subject = extractArgString(toolName, args)
430
432
  if (toolName === "bash") return matchCommandGlob(subject, argPattern)
431
433
  if (toolName === "delegate_agent") return subject === argPattern
432
- return FILE_TOOLS.has(toolName) ? matchFilePattern(subject, argPattern) : matchGlob(subject, argPattern)
434
+ return FILE_TOOLS.has(toolName) ? matchFilePattern(subject, argPattern, rule.type === "allow" && rule.canonicalPath) : matchGlob(subject, argPattern)
433
435
  }
434
436
 
435
437
  // ─── Shadow detection ─────────────────────────────────────────────────────────
@@ -695,8 +697,8 @@ export class PermissionManager {
695
697
  if (!rules.length || rules.some(rule => rule.type !== "allow" || rule.pattern === SANDBOX_ESCAPE_RULE)) throw new Error("Invalid tool grant")
696
698
  const path = getProjectAuthorizationSettingsPath(this.cwd)
697
699
  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)
700
+ const added = rules.filter((rule, index) => !existing.some(value => value.type === rule.type && value.pattern === rule.pattern && value.canonicalPath === rule.canonicalPath)
701
+ && rules.findIndex(value => value.type === rule.type && value.pattern === rule.pattern && value.canonicalPath === rule.canonicalPath) === index)
700
702
  const next = [...existing, ...added]
701
703
  if (lifetime === "session") this.sessionRules = next
702
704
  else savePermissionSettings(path, { rules: next })
@@ -965,7 +967,7 @@ export class PermissionManager {
965
967
  /** Attribute a rule object to the settings layer it lives in. */
966
968
  private locateRuleScope(rule: PermissionRule): RuleScope {
967
969
  const findsIt = (p: string) =>
968
- loadPermissionSettings(p).rules.some(r => r.pattern === rule.pattern && r.type === rule.type)
970
+ loadPermissionSettings(p).rules.some(r => r.pattern === rule.pattern && r.type === rule.type && r.canonicalPath === rule.canonicalPath)
969
971
  if (findsIt(getProjectAuthorizationSettingsPath(this.cwd))) return "project"
970
972
  if (findsIt(getProjectLocalSettingsPath(this.cwd))) return "local"
971
973
  if (findsIt(getProjectSettingsPath(this.cwd))) return "project"
@@ -1011,14 +1013,15 @@ export class PermissionManager {
1011
1013
  * scope it was removed from, or null if no rule matched. An explicit removal
1012
1014
  * scope targets the displayed group, separating host grants from repo rules.
1013
1015
  */
1014
- removeRule(pattern: string, type: RuleType, scope?: RuleRemovalScope): RuleScope | null {
1016
+ removeRule(pattern: string, type: RuleType, scope?: RuleRemovalScope, canonicalPath?: boolean): RuleScope | null {
1015
1017
  if ((!scope || scope === "session") && this.sessionSandboxEscape?.pattern === pattern && this.sessionSandboxEscape.type === type) {
1016
1018
  this.sessionSandboxEscape = undefined
1017
1019
  this.logger?.log("info", "permission_rule_removed", { pattern, type, scope: "session" })
1018
1020
  return "session"
1019
1021
  }
1020
1022
  // Session first (in-memory)
1021
- const sessionIdx = this.sessionRules.findIndex(r => r.pattern === pattern && r.type === type)
1023
+ const matches = (r: PermissionRule) => r.pattern === pattern && r.type === type && (canonicalPath === undefined || (r.canonicalPath === true) === canonicalPath)
1024
+ const sessionIdx = this.sessionRules.findIndex(matches)
1022
1025
  if (sessionIdx >= 0 && (!scope || scope === "session")) {
1023
1026
  this.sessionRules.splice(sessionIdx, 1)
1024
1027
  this.logger?.log("info", "permission_rule_removed", { pattern, type, scope: "session" })
@@ -1035,7 +1038,7 @@ export class PermissionManager {
1035
1038
  if (scope && layer.scope !== scope) continue
1036
1039
  const { scope: layerScope, path } = layer
1037
1040
  const settings = loadPermissionSettings(path)
1038
- const idx = settings.rules.findIndex(r => r.pattern === pattern && r.type === type)
1041
+ const idx = settings.rules.findIndex(matches)
1039
1042
  if (idx >= 0) {
1040
1043
  settings.rules.splice(idx, 1)
1041
1044
  savePermissionSettings(path, settings)
@@ -1095,6 +1098,7 @@ export class PermissionManager {
1095
1098
  const cur = checkOrder[i]
1096
1099
  for (let j = 0; j < i; j++) {
1097
1100
  const earlier = checkOrder[j]
1101
+ if (earlier.rule.canonicalPath && !cur.rule.canonicalPath) continue
1098
1102
  if (patternCovers(earlier.rule.pattern, cur.rule.pattern)) {
1099
1103
  shadowMap.set(cur.rule, earlier)
1100
1104
  break
@@ -1,9 +1,11 @@
1
- import { isAbsolute } from "node:path"
1
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path"
2
+ import { homedir } from "node:os"
2
3
  import { 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
 
@@ -11,8 +13,31 @@ export const FILE_GRANT_TOOLS = ["read_file", "list_tree", "read_document", "sea
11
13
  export const READ_GRANT_TOOLS = ["read_file", "list_tree", "read_document", "search_files", "glob_files"]
12
14
  export const EDIT_GRANT_TOOLS = ["write_file", "create_file", "edit_file", "multi_edit"]
13
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
+ }
38
+
14
39
  /** Expand a reviewed snapshot of exact registry names; never save a tool wildcard. */
15
- export function buildToolGrantRules(request: ToolGrantRequest, availableTools: readonly string[]): PermissionRule[] {
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
+ }
@@ -26,7 +26,8 @@ import { commandInput, isReturnInput } from "./controlled-input.js"
26
26
  import { useHideNativeCursor } from "./dialog-frame.js"
27
27
  import { c } from "./theme.js"
28
28
  import { ToolGrantDialog } from "./dialog-tool-grant.js"
29
- import type { ToolGrantRequest } from "../tool-grants.js"
29
+ import { suggestToolGrantDirectory, type ToolGrantRequest } from "../tool-grants.js"
30
+ import type { PermissionRule } from "../permissions.js"
30
31
  import { formatToolCall, getToolAlias } from "./transcript-format.js"
31
32
 
32
33
  export type ApprovalChoice = "once" | "always" | "forever" | "deny"
@@ -47,7 +48,9 @@ interface Props {
47
48
  unsandboxed?: boolean
48
49
  allowScope?: boolean
49
50
  availableTools?: string[]
50
- onGrant?: (request: ToolGrantRequest, availableTools: string[]) => string | void
51
+ cwd?: string
52
+ workspaceRoot?: string
53
+ onGrant?: (request: ToolGrantRequest, availableTools: string[], reviewedRules?: readonly PermissionRule[]) => string | void
51
54
  }
52
55
 
53
56
  interface Option {
@@ -55,7 +58,7 @@ interface Option {
55
58
  label: string
56
59
  }
57
60
 
58
- export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed: escape, allowScope = true, availableTools = [], onGrant }: Props) {
61
+ export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed: escape, allowScope = true, availableTools = [], cwd, workspaceRoot, onGrant }: Props) {
59
62
  useHideNativeCursor()
60
63
  // Three accept tiers ("once" / session-scoped "always" / persistent
61
64
  // "forever") + deny. Both persistent consent and ordinary tool grants
@@ -68,6 +71,7 @@ export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed
68
71
  : `${getToolAlias(toolName)} commands`
69
72
  const unsandboxed = escape ?? isUnsandboxedBash(toolName, args)
70
73
  const canCustomize = allowScope && !unsandboxed && toolName !== "delegate_agent" && availableTools.includes(toolName) && !!onGrant
74
+ const directory = canCustomize ? suggestToolGrantDirectory(toolName, args, cwd) : undefined
71
75
  const options: Option[] = !allowScope
72
76
  ? [
73
77
  { value: "once", label: unsandboxed ? "Yes, run outside the sandbox this once" : "Yes, this once" },
@@ -86,9 +90,11 @@ export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed
86
90
  ]
87
91
  const [idx, setIdx] = useState(0)
88
92
  const [customizing, setCustomizing] = useState(false)
93
+ const [directoryShortcut, setDirectoryShortcut] = useState(false)
89
94
 
90
95
  useInput((input, key) => {
91
- if (input === "g" && canCustomize) { setCustomizing(true); return }
96
+ if (input === "g" && canCustomize) { setDirectoryShortcut(false); setCustomizing(true); return }
97
+ if (input === "d" && directory) { setDirectoryShortcut(true); setCustomizing(true); return }
92
98
  const directChoice = approvalChoiceForInput(input, key, idx, allowScope)
93
99
  if (directChoice) { onChoose(directChoice); return }
94
100
  if (key.upArrow) { setIdx(i => (i - 1 + options.length) % options.length); return }
@@ -97,7 +103,8 @@ export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed
97
103
 
98
104
  if (customizing && canCustomize && onGrant) return <ToolGrantDialog availableTools={availableTools} initialTools={[toolName]}
99
105
  initialPattern={rulePreview?.match(/^[^(]+\(([^()]*)\)$/)?.[1] ?? ""}
100
- onSave={request => onGrant(request, availableTools)} onCancel={() => setCustomizing(false)} />
106
+ initialDirectory={directory} directoryShortcut={directoryShortcut} cwd={workspaceRoot}
107
+ onSave={(request, reviewedRules) => onGrant(request, availableTools, reviewedRules)} onCancel={() => setCustomizing(false)} />
101
108
 
102
109
  // Height is load-bearing: a tall dynamic frame above a long transcript
103
110
  // gets partially scrolled into scrollback by every re-render that
@@ -130,6 +137,7 @@ export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed
130
137
  })}
131
138
  </Box>
132
139
  {canCustomize && <Text color={c.text.muted}>g customize scope / select tools</Text>}
140
+ {directory && <Text color={c.text.muted}>d authorize folder / select tools: {directory}</Text>}
133
141
  </Box>
134
142
  )
135
143
  }
@@ -2,7 +2,8 @@
2
2
  import { useEffect, useRef, useState } from "react"
3
3
  import { Box, Text, useInput } from "ink"
4
4
  import { inferLegacyContextWindowMode, resolveProviderContextWindow, upsertProvider, type AppConfig } from "../config.js"
5
- import { associateModelMetadata, discoverProviderModels, describeCatalogRow, selectCatalogModel, type CatalogRow } from "../provider-catalog.js"
5
+ import { associateModelMetadata, describeCatalogRow, selectCatalogModel } from "../provider-catalog.js"
6
+ import { configuredModelRows, discoverConfiguredModels, modelCatalogKey, savedConnectionCatalogs, type ConnectionCatalog, type ConnectionModelRow } from "../model-catalog.js"
6
7
  import { DialogFrame } from "./dialog-frame.js"
7
8
  import { PickerDialog } from "./dialog-picker.js"
8
9
  import { TextField } from "./text-field.js"
@@ -23,114 +24,134 @@ export function ModelDialog({ config, initialProviderId, setup = false, onSave,
23
24
  process.stdout.on("resize", resize)
24
25
  return () => { process.stdout.off("resize", resize) }
25
26
  }, [])
26
- const [providerId, setProviderId] = useState(initialProviderId ?? (config.active.providerId || config.providers[0]?.id || ""))
27
- const provider = config.providers.find(item => item.id === providerId)
27
+ const [providerFilter, setProviderFilter] = useState<string | null>(initialProviderId ?? (setup ? config.active.providerId || config.providers[0]?.id || null : null))
28
28
  const [phase, setPhase] = useState<"models" | "providers" | "manual" | "search" | "metadata" | "context">("models")
29
- const [metadataTarget, setMetadataTarget] = useState<CatalogRow | null>(null)
30
- const [rows, setRows] = useState<CatalogRow[]>([])
31
- const [index, setIndex] = useState(0)
29
+ const [providerAction, setProviderAction] = useState<"filter" | "manual">("filter")
30
+ const [target, setTarget] = useState<ConnectionModelRow | null>(null)
31
+ const [manualProviderId, setManualProviderId] = useState("")
32
+ const [catalogState, setCatalogState] = useState(() => ({ providers: config.providers, catalogs: savedConnectionCatalogs(config.providers) }))
33
+ const [selectedKey, setSelectedKey] = useState<string | null>(() => modelCatalogKey(config.active.providerId, config.active.model))
32
34
  const [query, setQuery] = useState("")
33
35
  const [manual, setManual] = useState("")
34
- const [loading, setLoading] = useState(false)
35
- const [error, setError] = useState("")
36
36
  const [refresh, setRefresh] = useState(0)
37
- const shown = rows.filter(row => row.id.toLowerCase().includes(query.toLowerCase()))
38
- const selectedIndex = Math.min(index, Math.max(0, shown.length - 1))
39
- const live = useRef({ phase, selectedIndex, shown, config, providerId, onCommit, onCancel })
40
- live.current = { phase, selectedIndex, shown, config, providerId, onCommit, onCancel }
37
+ const setupProviderId = setup ? providerFilter : null
38
+ // Configuration changes cannot briefly expose a removed connection's rows.
39
+ const catalogs = catalogState.providers === config.providers ? catalogState.catalogs : savedConnectionCatalogs(config.providers)
40
+ const shown = configuredModelRows(config.providers, catalogs, providerFilter, query)
41
+ const selectedIndex = Math.max(0, shown.findIndex(row => modelCatalogKey(row.provider.id, row.id) === selectedKey))
42
+ const selected = shown[selectedIndex]
43
+ const displayedKey = selected ? modelCatalogKey(selected.provider.id, selected.id) : null
44
+ // Pin a fallback as soon as it is displayed. Later discovery may insert rows
45
+ // before it, including after a search/filter removed the previous selection.
46
+ useEffect(() => {
47
+ if (displayedKey !== null && displayedKey !== selectedKey) setSelectedKey(displayedKey)
48
+ }, [displayedKey, selectedKey])
49
+ const provider = selected?.provider ?? config.providers.find(item => item.id === providerFilter)
50
+ ?? config.providers.find(item => item.id === config.active.providerId) ?? config.providers[0]
51
+ const targetProvider = config.providers.find(item => item.id === target?.provider.id)
52
+ const manualProvider = config.providers.find(item => item.id === manualProviderId)
53
+ const orphanedPhase = (phase === "metadata" || phase === "context") && !targetProvider || phase === "manual" && !manualProvider
54
+ const currentPhase = !provider || orphanedPhase ? "models" : phase
55
+ const live = useRef({ phase: currentPhase, selectedIndex, shown, config, provider, providerFilter, onCommit, onCancel })
56
+ live.current = { phase: currentPhase, selectedIndex, shown, config, provider, providerFilter, onCommit, onCancel }
41
57
 
42
58
  useEffect(() => {
43
- if (!provider) { setRows([]); return }
44
- const controller = new AbortController()
45
- let finished = false
46
- setRows(provider.models.map(id => ({ id, source: "saved", metadata: provider.modelMetadata?.[id] })))
47
- setLoading(true); setError(""); setIndex(Math.max(0, provider.models.indexOf(config.active.model)))
48
- const timer = setTimeout(() => {
49
- if (finished) return
50
- finished = true; controller.abort(); setLoading(false)
51
- setError("Discovery timed out. Saved models remain available; press t to enter an ID.")
52
- }, 6500)
53
- void discoverProviderModels(provider, controller.signal).then(result => {
54
- if (finished) return
55
- finished = true; clearTimeout(timer)
56
- setRows(result.rows); setError(result.error ?? ""); setLoading(false)
57
- }).catch(() => {
58
- if (finished) return
59
- finished = true; clearTimeout(timer); setLoading(false)
60
- setError("Discovery unavailable. Press r to retry or t for a manual model ID.")
61
- })
62
- return () => { finished = true; controller.abort(); clearTimeout(timer) }
63
- }, [provider, refresh])
59
+ const providers = config.providers
60
+ const requested = setupProviderId === null ? providers : providers.filter(item => item.id === setupProviderId)
61
+ setCatalogState({ providers, catalogs: savedConnectionCatalogs(requested) })
62
+ const update = (catalog: ConnectionCatalog) => setCatalogState(current => current.providers !== providers ? current
63
+ : { providers, catalogs: current.catalogs.map(item => item.providerId === catalog.providerId ? catalog : item) })
64
+ return discoverConfiguredModels(requested, update)
65
+ }, [config.providers, refresh, setupProviderId])
64
66
 
65
67
  useInput((input, key) => {
66
68
  const state = live.current
67
69
  if (state.phase !== "models") return
68
70
  const cmd = commandInput(input, key)
69
71
  if (key.escape) { state.onCancel(); return }
70
- if (cmd === "p" && !setup) { setPhase("providers"); return }
71
- if (cmd === "t") { setManual(""); setPhase("manual"); return }
72
+ if (!state.provider) return
73
+ if (cmd === "p" && !setup) { setProviderAction("filter"); setPhase("providers"); return }
74
+ if (cmd === "t") {
75
+ setManual("")
76
+ if (state.providerFilter !== null && state.provider) { setManualProviderId(state.provider.id); setPhase("manual") }
77
+ else { setProviderAction("manual"); setPhase("providers") }
78
+ return
79
+ }
72
80
  if (cmd === "/") { setPhase("search"); return }
73
81
  if (cmd === "r") { setRefresh(value => value + 1); return }
74
- if (cmd === "c") { setPhase("context"); return }
75
- if (cmd === "m") {
82
+ if (cmd === "c" || cmd === "m") {
76
83
  const row = state.shown[state.selectedIndex]
77
- if (row) { setMetadataTarget(row); setPhase("metadata") }
84
+ if (row) { setTarget(row); setPhase(cmd === "c" ? "context" : "metadata") }
85
+ return
86
+ }
87
+ if (key.upArrow || key.downArrow) {
88
+ const next = Math.max(0, Math.min(state.shown.length - 1, state.selectedIndex + (key.upArrow ? -1 : 1)))
89
+ const row = state.shown[next]
90
+ if (row) setSelectedKey(modelCatalogKey(row.provider.id, row.id))
78
91
  return
79
92
  }
80
- if (key.upArrow) { setIndex(Math.max(0, state.selectedIndex - 1)); return }
81
- if (key.downArrow) { setIndex(Math.min(Math.max(0, state.shown.length - 1), state.selectedIndex + 1)); return }
82
93
  if (isReturnInput(input, key)) {
83
94
  const row = state.shown[state.selectedIndex]
84
- if (row) state.onCommit(selectCatalogModel(state.config, state.providerId, row))
95
+ if (row) state.onCommit(selectCatalogModel(state.config, row.provider.id, row))
85
96
  }
86
97
  })
87
98
 
88
99
  if (!provider) return <DialogFrame title="Models · /model" hint="esc close">
89
100
  <Text>No connection configured. Use /connect to create one first.</Text>
90
101
  </DialogFrame>
91
- if (phase === "metadata" && metadataTarget) return <ModelMetadataDialog modelId={metadataTarget.id}
102
+ if (phase === "metadata" && target && targetProvider) return <ModelMetadataDialog modelId={target.id}
92
103
  onCancel={() => setPhase("models")} onSelect={metadata => {
93
- onSave(associateModelMetadata(config, providerId, metadataTarget.id, metadata))
104
+ onSave(associateModelMetadata(config, targetProvider.id, target.id, metadata))
94
105
  setPhase("models")
95
106
  }} />
96
- if (phase === "context") return <ContextWindowDialog
97
- mode={provider.contextWindowMode ?? inferLegacyContextWindowMode(provider)}
98
- contextWindow={resolveProviderContextWindow(provider, config.active.model)}
107
+ if (phase === "context" && target && targetProvider) return <ContextWindowDialog
108
+ mode={targetProvider.contextWindowMode ?? inferLegacyContextWindowMode(targetProvider)}
109
+ contextWindow={resolveProviderContextWindow(targetProvider, target.id)}
99
110
  onCancel={() => setPhase("models")} onSave={(mode, tokens) => {
100
- onSave({ ...upsertProvider(config, { ...provider, contextWindowMode: mode, contextWindow: tokens }), active: config.active })
111
+ onSave({ ...upsertProvider(config, { ...targetProvider, contextWindowMode: mode, contextWindow: tokens }), active: config.active })
101
112
  setPhase("models")
102
113
  }} />
103
- if (phase === "providers") return <PickerDialog title="Models · choose connection"
104
- options={config.providers.map(item => ({ id: item.id, label: item.name || item.baseURL, meta: item.baseURL }))}
105
- initialIndex={Math.max(0, config.providers.findIndex(item => item.id === providerId))}
106
- onCancel={() => setPhase("models")} onSelect={id => { setProviderId(id); setQuery(""); setIndex(0); setPhase("models") }} />
107
- if (phase === "manual" || phase === "search") return <DialogFrame
108
- title={phase === "manual" ? `Manual model ID · ${provider.name}` : "Filter model directory"} hint="enter confirm · esc back">
109
- <Text color={c.text.faint}>{phase === "manual" ? "Manual IDs are unverified. The endpoint must support this exact ID." : "Filter by model ID. Discovery does not change your current selection."}</Text>
114
+ if (phase === "providers") return <PickerDialog key={providerAction} title={providerAction === "manual" ? "Manual model · choose connection" : "Models · filter connections"}
115
+ options={[...(providerAction === "filter" ? [{ id: "all", label: "All configured connections", meta: `${config.providers.length} connections` }] : []),
116
+ ...config.providers.map(item => ({ id: `provider:${item.id}`, label: item.name || item.baseURL, meta: item.baseURL }))]}
117
+ initialIndex={providerAction === "filter" ? providerFilter === null ? 0 : Math.max(0, config.providers.findIndex(item => item.id === providerFilter) + 1)
118
+ : Math.max(0, config.providers.findIndex(item => item.id === provider.id))}
119
+ onCancel={() => setPhase("models")} onSelect={id => {
120
+ if (providerAction === "manual") { setManualProviderId(id.slice("provider:".length)); setPhase("manual") }
121
+ else { setProviderFilter(id === "all" ? null : id.slice("provider:".length)); setQuery(""); setSelectedKey(null); setPhase("models") }
122
+ }} />
123
+ if (phase === "search" || phase === "manual" && manualProvider) return <DialogFrame
124
+ title={phase === "manual" ? `Manual model ID · ${manualProvider!.name}` : "Filter models and connections"} hint="enter confirm · esc back">
125
+ <Text color={c.text.faint}>{phase === "manual" ? "Manual IDs are unverified. The endpoint must support this exact ID." : "Search model IDs, connection names or endpoints. Selection changes only on Enter."}</Text>
110
126
  <TextField key={phase} isActive value={phase === "manual" ? manual : query}
111
127
  onChange={phase === "manual" ? setManual : setQuery} onCancel={() => setPhase("models")}
112
128
  onSubmit={value => {
113
129
  if (phase === "manual") {
114
- if (value.trim()) onCommit(selectCatalogModel(config, providerId, { id: value.trim(), source: "manual" }))
115
- } else { setQuery(value.trim()); setIndex(0); setPhase("models") }
130
+ if (value.trim() && manualProvider) onCommit(selectCatalogModel(config, manualProvider.id, { id: value.trim(), source: "manual" }))
131
+ } else { setQuery(value.trim()); setSelectedKey(null); setPhase("models") }
116
132
  }} />
117
133
  </DialogFrame>
134
+ const scopedCatalogs = catalogs.filter(item => providerFilter === null || item.providerId === providerFilter)
135
+ const loading = scopedCatalogs.filter(item => item.loading).length
136
+ const failed = scopedCatalogs.filter(item => item.error).length
137
+ const error = catalogs.find(item => item.providerId === provider.id)?.error
118
138
  const count = Math.max(1, Math.min(7, Math.floor((height - 14) / 3)))
119
139
  const start = Math.max(0, selectedIndex - Math.floor(count / 2))
120
- return <DialogFrame title={`${setup ? "Choose a model" : "Models"} · ${provider.name || provider.baseURL}`}
121
- hint={setup ? "↑↓ navigate · enter select and finish · m metadata · c context · / filter · t manual · esc choose later" : "↑↓ navigate · enter select · m metadata · c context · / filter · p connection · r refresh · t manual · esc close"}>
140
+ const activeProvider = config.providers.find(item => item.id === config.active.providerId)
141
+ return <DialogFrame title={`${setup ? "Choose a model" : "Models"} · ${providerFilter === null ? "All connections" : provider.name || provider.baseURL}`}
142
+ hint={setup ? "↑↓ navigate · enter select and finish · m metadata · c context · / filter · t manual · esc choose later" : "↑↓ navigate · enter select · / search · p filter connections · m metadata · c context · r refresh · t manual · esc close"}>
122
143
  {setup && <Text color={c.accent}>Connection saved. Choose a model to use it, or press esc to choose later with /model.</Text>}
123
- <Text color={c.text.faint}>{truncateToWidth(provider.baseURL, width)}</Text>
124
- <Text color={c.text.faint}>{truncateToWidth(`Current: ${config.active.providerId === providerId ? config.active.model || "none" : "none on this connection"} · ${shown.length} models${loading ? " · discovering…" : ""}${query ? ` · filter: ${query}` : ""}`, width)}</Text>
144
+ <Text color={c.text.faint}>{truncateToWidth(`Current: ${config.active.model || "none"} · ${activeProvider?.name || "none"}`, width)}</Text>
145
+ <Text color={c.text.faint}>{truncateToWidth(`${shown.length} models · ${scopedCatalogs.length} connections${loading ? ` · ${loading} discovering…` : ""}${failed ? ` · ${failed} discovery unavailable` : ""}${query ? ` · filter: ${query}` : ""}`, width)}</Text>
125
146
  <Text color={c.text.faint}>{truncateToWidth((provider.contextWindowMode ?? inferLegacyContextWindowMode(provider)) === "manual"
126
- ? `Manual context: ${provider.contextWindow.toLocaleString("en-US")} tokens · c to change`
127
- : `Automatic context · m to link metadata · unknown models use fallback ${provider.contextWindow.toLocaleString("en-US")} tokens (unverified)`, width)}</Text>
128
- {error && <Text color={c.warning}>{truncateToWidth(error, width)}</Text>}
147
+ ? `${provider.name}: manual context ${provider.contextWindow.toLocaleString("en-US")} tokens · c to change`
148
+ : `${provider.name}: automatic context · m to link metadata · fallback ${provider.contextWindow.toLocaleString("en-US")} tokens`, width)}</Text>
149
+ {error && <Text color={c.warning}>{truncateToWidth(`${provider.name}: ${error}`, width)}</Text>}
129
150
  <Box flexDirection="column" marginTop={1}>
130
- {shown.slice(start, start + count).map((row, i) => <Box key={row.id} flexDirection="column">
131
- <Text color={start + i === selectedIndex ? c.accent : c.text.primary} bold={start + i === selectedIndex}>{truncateToWidth(`${start + i === selectedIndex ? "›" : " "} ${row.id}`, width)}</Text>
132
- <Text color={c.text.faint}>{truncateToWidth(` ${describeCatalogRow(row).split(" · ").slice(0, 3).join(" · ")}`, width)}</Text>
133
- <Text color={c.text.faint}>{truncateToWidth(` ${describeCatalogRow(row).split(" · ").slice(3).join(" · ")}`, width)}</Text>
151
+ {shown.slice(start, start + count).map((row, i) => <Box key={modelCatalogKey(row.provider.id, row.id)} flexDirection="column">
152
+ <Text color={start + i === selectedIndex ? c.accent : c.text.primary} bold={start + i === selectedIndex}>{truncateToWidth(`${start + i === selectedIndex ? "›" : " "} ${row.id}${row.provider.id === config.active.providerId && row.id === config.active.model ? " (current)" : ""}`, width)}</Text>
153
+ <Text color={c.text.faint}>{truncateToWidth(` ${row.provider.name || row.provider.id} · ${row.provider.baseURL}`, width)}</Text>
154
+ <Text color={c.text.faint}>{truncateToWidth(` ${describeCatalogRow(row)}`, width)}</Text>
134
155
  </Box>)}
135
156
  {!shown.length && <Text color={c.text.faint}>{loading ? "Discovering models… You can enter an ID with t." : "No matching models. Press t to enter an ID or / to change the filter."}</Text>}
136
157
  {start + count < shown.length && <Text color={c.text.faint}>{`… ${shown.length - start - count} more`}</Text>}
@@ -97,7 +97,7 @@ export function PermissionsDialog({ onCancel, availableTools }: Props) {
97
97
  const rule = flat.group.rules[flat.ruleIdx]
98
98
  if (rule) {
99
99
  try {
100
- permissionManager.removeRule(rule.rule.pattern, rule.rule.type, scopeOf(flat.group))
100
+ permissionManager.removeRule(rule.rule.pattern, rule.rule.type, scopeOf(flat.group), rule.rule.canonicalPath === true)
101
101
  try { appLogger.info(`permission_remove pattern=${rule.rule.pattern} type=${rule.rule.type}`) } catch {}
102
102
  } catch (failure) { setError(String(failure)) }
103
103
  }
@@ -119,7 +119,7 @@ export function PermissionsDialog({ onCancel, availableTools }: Props) {
119
119
  for (const g of groups) {
120
120
  if (g.label === "session") continue
121
121
  for (const r of g.rules) {
122
- try { permissionManager.removeRule(r.rule.pattern, r.rule.type, scopeOf(g)) } catch (failure) { setError(String(failure)) }
122
+ try { permissionManager.removeRule(r.rule.pattern, r.rule.type, scopeOf(g), r.rule.canonicalPath === true) } catch (failure) { setError(String(failure)) }
123
123
  }
124
124
  }
125
125
  try { appLogger.info("permission_clear_all") } catch {}
@@ -134,9 +134,9 @@ export function PermissionsDialog({ onCancel, availableTools }: Props) {
134
134
  }
135
135
  }, { isActive: !grantOpen })
136
136
 
137
- if (grantOpen) return <ToolGrantDialog availableTools={availableTools} onCancel={() => setGrantOpen(false)} onSave={request => {
137
+ if (grantOpen) return <ToolGrantDialog availableTools={availableTools} onCancel={() => setGrantOpen(false)} onSave={(request, reviewedRules) => {
138
138
  try {
139
- permissionManager.addToolRules(buildToolGrantRules(request, availableTools), request.lifetime)
139
+ permissionManager.addToolRules(buildToolGrantRules(request, availableTools, process.cwd(), reviewedRules), request.lifetime)
140
140
  setGrantOpen(false); setTick(value => value + 1)
141
141
  } catch (failure) { return String(failure) }
142
142
  }} />
@@ -169,7 +169,7 @@ export function PermissionsDialog({ onCancel, availableTools }: Props) {
169
169
  const { rule, shadowedBy } = annotated
170
170
  return (
171
171
  <Box
172
- key={`${group.label}::${rule.type}::${rule.pattern}`}
172
+ key={`${group.label}::${rule.type}::${rule.pattern}::${rule.canonicalPath ? "canonical" : "legacy"}`}
173
173
  flexDirection="column"
174
174
  >
175
175
  <Box flexDirection="row">
@@ -181,6 +181,7 @@ export function PermissionsDialog({ onCancel, availableTools }: Props) {
181
181
  <Text color={isSelected ? c.text.primary : c.text.muted} wrap="truncate-end">
182
182
  {truncateToWidth(rule.pattern, 60)}
183
183
  </Text>
184
+ {rule.canonicalPath && <Text color={c.text.ghost}> (fixed folder target)</Text>}
184
185
  {shadowedBy && (
185
186
  <Text color={c.text.ghost} wrap="truncate-end">
186
187
  {truncateToWidth(` ⤴ shadowed by ${shadowedBy.rule.type} ${shadowedBy.rule.pattern} (${shadowedBy.scope})`, 70)}
@@ -2,6 +2,7 @@
2
2
  import { useRef, useState } from "react"
3
3
  import { Box, Text, useInput } from "ink"
4
4
  import { buildToolGrantRules, EDIT_GRANT_TOOLS, READ_GRANT_TOOLS, type ToolGrantRequest } from "../tool-grants.js"
5
+ import type { PermissionRule } from "../permissions.js"
5
6
  import { ControlledInput, commandInput, isReturnInput } from "./controlled-input.js"
6
7
  import { c } from "./theme.js"
7
8
  import { useHideNativeCursor } from "./dialog-frame.js"
@@ -10,30 +11,35 @@ interface Props {
10
11
  availableTools: string[]
11
12
  initialTools?: string[]
12
13
  initialPattern?: string
13
- onSave: (request: ToolGrantRequest) => string | void
14
+ initialDirectory?: string
15
+ directoryShortcut?: boolean
16
+ cwd?: string
17
+ onSave: (request: ToolGrantRequest, reviewedRules: readonly PermissionRule[]) => string | void
14
18
  onCancel: () => void
15
19
  }
16
20
 
17
- export function ToolGrantDialog({ availableTools, initialTools = [], initialPattern = "", onSave, onCancel }: Props) {
21
+ export function ToolGrantDialog({ availableTools, initialTools = [], initialPattern = "", initialDirectory = "", directoryShortcut = false, cwd = process.cwd(), onSave, onCancel }: Props) {
18
22
  useHideNativeCursor()
19
23
  // Freeze the reviewed registry snapshot: later MCP registrations cannot join it.
20
24
  const [tools] = useState(() => [...new Set(availableTools)].filter(name => name !== "delegate_agent").sort())
21
25
  const [selected, setSelected] = useState(() => initialTools.filter(name => tools.includes(name)))
22
26
  const [step, setStep] = useState(0)
23
27
  const [index, setIndex] = useState(0)
24
- const [pattern, setPattern] = useState(initialPattern)
25
- const [cursor, setCursor] = useState(initialPattern.length)
28
+ const [pattern, setPattern] = useState(directoryShortcut ? initialDirectory : initialPattern)
29
+ const [cursor, setCursor] = useState((directoryShortcut ? initialDirectory : initialPattern).length)
30
+ const [filterKind, setFilterKind] = useState<"pattern" | "directory">(directoryShortcut ? "directory" : "pattern")
26
31
  const [resource, setResource] = useState<ToolGrantRequest["resource"]>({ kind: "all" })
27
32
  const [lifetime, setLifetime] = useState<ToolGrantRequest["lifetime"]>("session")
28
33
  const [error, setError] = useState("")
34
+ const reviewedRules = useRef<PermissionRule[]>([])
29
35
  const request: ToolGrantRequest = { tools: selected, resource, lifetime }
30
36
  const live = useRef({ step, index, selected, pattern, request, onSave, onCancel })
31
37
  live.current = { step, index, selected, pattern, request, onSave, onCancel }
32
38
  const checkPattern = () => {
33
39
  const value = live.current.pattern
34
40
  try {
35
- buildToolGrantRules({ ...live.current.request, resource: { kind: "pattern", value } }, tools)
36
- setResource({ kind: "pattern", value }); setStep(3); setError("")
41
+ buildToolGrantRules({ ...live.current.request, resource: { kind: filterKind, value } }, tools, cwd)
42
+ setResource({ kind: filterKind, value }); setStep(3); setError("")
37
43
  } catch (failure) { setError(String(failure)) }
38
44
  }
39
45
  useInput((input, key) => {
@@ -61,27 +67,30 @@ export function ToolGrantDialog({ availableTools, initialTools = [], initialPatt
61
67
  if (cmd === "n") { setSelected([]); return }
62
68
  if (isReturnInput(input, key)) {
63
69
  if (!current.selected.length) { setError("Select at least one tool"); return }
64
- setStep(1); setIndex(0)
70
+ setStep(directoryShortcut ? 2 : 1); setIndex(0)
65
71
  }
66
72
  } else if (current.step === 1) {
67
73
  if (cmd === "1") { setResource({ kind: "all" }); setStep(3) }
68
- if (cmd === "2") setStep(2)
74
+ if (cmd === "2") { setFilterKind("pattern"); setPattern(initialPattern); setCursor(initialPattern.length); setStep(2) }
75
+ if (cmd === "3") { setFilterKind("directory"); setPattern(initialDirectory); setCursor(initialDirectory.length); setStep(2) }
69
76
  } else if (current.step === 3) {
70
- if (cmd === "1" || cmd === "2") { setLifetime(cmd === "1" ? "session" : "project"); setStep(4); setIndex(0) }
77
+ if (cmd === "1" || cmd === "2") {
78
+ try {
79
+ reviewedRules.current = buildToolGrantRules(current.request, tools, cwd)
80
+ setLifetime(cmd === "1" ? "session" : "project"); setStep(4); setIndex(0)
81
+ } catch (failure) { setError(String(failure)) }
82
+ }
71
83
  } else if (current.step === 4) {
72
84
  if (key.upArrow) { setIndex(value => Math.max(0, value - 1)); return }
73
85
  if (key.downArrow) { setIndex(value => Math.min(current.selected.length - 1, value + 1)); return }
74
86
  if (isReturnInput(input, key)) {
75
- const failure = current.onSave(current.request)
87
+ const failure = current.onSave(current.request, reviewedRules.current)
76
88
  if (failure) setError(failure)
77
89
  }
78
90
  }
79
91
  })
80
92
  const start = Math.max(0, Math.min(index - 4, tools.length - 8))
81
- let preview: string[] = []
82
- if (step === 4) {
83
- try { preview = buildToolGrantRules(request, tools).map(rule => rule.pattern) } catch (failure) { preview = [String(failure)] }
84
- }
93
+ const preview = step === 4 ? reviewedRules.current.map(rule => rule.pattern) : []
85
94
  return <Box flexDirection="column" paddingX={1} marginTop={1}>
86
95
  <Text bold color={c.text.primary}>Tool authorization — {["select tools", "resource scope", "resource filter", "lifetime", "review authorization"][step]}</Text>
87
96
  {step === 0 && <>
@@ -92,10 +101,11 @@ export function ToolGrantDialog({ availableTools, initialTools = [], initialPatt
92
101
  {step === 1 && <>
93
102
  <Text>1. Entire selected tools (all arguments)</Text>
94
103
  <Text>2. Project path glob or Bash command pattern</Text>
104
+ <Text>3. Folder and all descendants (relative, absolute or ~/ path)</Text>
95
105
  <Text color={c.text.muted}>Tool grants do not authorize sandbox escape. Esc back</Text>
96
106
  </>}
97
107
  {step === 2 && <>
98
- <Text color={c.text.muted}>Project-relative path glob, e.g. src/**; Bash alone, e.g. git log:* · Enter next · Esc back</Text>
108
+ <Text color={c.text.muted}>{filterKind === "directory" ? "Folder path, e.g. src or ~/.local/share/android-use/screenshots; includes future files" : "Project-relative path glob, e.g. src/**; Bash alone, e.g. git log:*"} · Enter next · Esc back</Text>
99
109
  <ControlledInput value={pattern} cursorOffset={cursor} onValueChange={value => { setPattern(value.value); setCursor(value.cursorOffset) }} onSubmit={checkPattern} />
100
110
  </>}
101
111
  {step === 3 && <>