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.
@@ -26,7 +26,9 @@ 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 { inferPattern, type PermissionRule } from "../permissions.js"
31
+ import { REQUEST_CAPABILITIES_TOOL, describeCapabilityPatterns } from "../capabilities.js"
30
32
  import { formatToolCall, getToolAlias } from "./transcript-format.js"
31
33
 
32
34
  export type ApprovalChoice = "once" | "always" | "forever" | "deny"
@@ -46,8 +48,12 @@ interface Props {
46
48
  rulePreview?: string | null
47
49
  unsandboxed?: boolean
48
50
  allowScope?: boolean
51
+ /** One-time approvals of the same consent earlier this session. */
52
+ repeats?: number
49
53
  availableTools?: string[]
50
- onGrant?: (request: ToolGrantRequest, availableTools: string[]) => string | void
54
+ cwd?: string
55
+ workspaceRoot?: string
56
+ onGrant?: (request: ToolGrantRequest, availableTools: string[], reviewedRules?: readonly PermissionRule[]) => string | void
51
57
  }
52
58
 
53
59
  interface Option {
@@ -55,7 +61,7 @@ interface Option {
55
61
  label: string
56
62
  }
57
63
 
58
- export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed: escape, allowScope = true, availableTools = [], onGrant }: Props) {
64
+ export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed: escape, allowScope = true, repeats = 0, availableTools = [], cwd, workspaceRoot, onGrant }: Props) {
59
65
  useHideNativeCursor()
60
66
  // Three accept tiers ("once" / session-scoped "always" / persistent
61
67
  // "forever") + deny. Both persistent consent and ordinary tool grants
@@ -63,12 +69,21 @@ export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed
63
69
  // When rulePreview is provided, surface the actual saved pattern in
64
70
  // both "always" and "forever" labels so the user sees the literal
65
71
  // glob/prefix rather than a vague "in this session/project".
66
- const scopeText = rulePreview
72
+ const capabilityText = rulePreview ? describeCapabilityPatterns(rulePreview.split(", ")) : null
73
+ const scopeText = capabilityText ?? (rulePreview
67
74
  ? rulePreview === toolName ? `${getToolAlias(toolName)} (entire tool)` : `${rulePreview}`
68
- : `${getToolAlias(toolName)} commands`
75
+ : `${getToolAlias(toolName)} commands`)
69
76
  const unsandboxed = escape ?? isUnsandboxedBash(toolName, args)
70
- const canCustomize = allowScope && !unsandboxed && toolName !== "delegate_agent" && availableTools.includes(toolName) && !!onGrant
71
- const options: Option[] = !allowScope
77
+ const request = toolName === REQUEST_CAPABILITIES_TOOL
78
+ const canCustomize = allowScope && !unsandboxed && !request && toolName !== "delegate_agent" && availableTools.includes(toolName) && !!onGrant
79
+ const directory = canCustomize ? suggestToolGrantDirectory(toolName, args, cwd) : undefined
80
+ // A capability request is only worth something when it is remembered.
81
+ const options: Option[] = request && allowScope ? [
82
+ { value: "always", label: `Yes, allow ${scopeText} for this session` },
83
+ { value: "forever", label: `Yes, allow ${scopeText} for this project` },
84
+ { value: "deny", label: "No" },
85
+ ]
86
+ : !allowScope
72
87
  ? [
73
88
  { value: "once", label: unsandboxed ? "Yes, run outside the sandbox this once" : "Yes, this once" },
74
89
  { value: "deny", label: "No" },
@@ -86,18 +101,21 @@ export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed
86
101
  ]
87
102
  const [idx, setIdx] = useState(0)
88
103
  const [customizing, setCustomizing] = useState(false)
104
+ const [directoryShortcut, setDirectoryShortcut] = useState(false)
89
105
 
90
106
  useInput((input, key) => {
91
- if (input === "g" && canCustomize) { setCustomizing(true); return }
92
- const directChoice = approvalChoiceForInput(input, key, idx, allowScope)
107
+ if (input === "g" && canCustomize) { setDirectoryShortcut(false); setCustomizing(true); return }
108
+ if (input === "d" && directory) { setDirectoryShortcut(true); setCustomizing(true); return }
109
+ const directChoice = approvalChoiceForInput(input, key, idx, allowScope, options.map(option => option.value))
93
110
  if (directChoice) { onChoose(directChoice); return }
94
111
  if (key.upArrow) { setIdx(i => (i - 1 + options.length) % options.length); return }
95
112
  if (key.downArrow) { setIdx(i => (i + 1) % options.length); return }
96
113
  }, { isActive: !(customizing && canCustomize) })
97
114
 
98
115
  if (customizing && canCustomize && onGrant) return <ToolGrantDialog availableTools={availableTools} initialTools={[toolName]}
99
- initialPattern={rulePreview?.match(/^[^(]+\(([^()]*)\)$/)?.[1] ?? ""}
100
- onSave={request => onGrant(request, availableTools)} onCancel={() => setCustomizing(false)} />
116
+ initialPattern={(capabilityText ? inferPattern(toolName, args, workspaceRoot ?? cwd ?? process.cwd()) : rulePreview)?.match(/^[^(]+\(([^()]*)\)$/)?.[1] ?? ""}
117
+ initialDirectory={directory} directoryShortcut={directoryShortcut} cwd={workspaceRoot}
118
+ onSave={(request, reviewedRules) => onGrant(request, availableTools, reviewedRules)} onCancel={() => setCustomizing(false)} />
101
119
 
102
120
  // Height is load-bearing: a tall dynamic frame above a long transcript
103
121
  // gets partially scrolled into scrollback by every re-render that
@@ -114,6 +132,7 @@ export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed
114
132
  {toolName === "bash" && ([ ["read_paths", "Additional read access"], ["write_paths", "Additional write access"] ] as const).map(([field, label]) =>
115
133
  Array.isArray(args[field]) && args[field].length > 0
116
134
  ? <Text key={field} color={c.warning}>{label}: {JSON.stringify(args[field])}</Text> : null)}
135
+ {request && typeof args.reason === "string" && <Text color={c.text.secondary} wrap="truncate-end">{`Reason: ${args.reason.replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ")}`}</Text>}
117
136
  {unsandboxed && <Text color={c.error}>Runs outside the OS sandbox: full access to your files and network.</Text>}
118
137
  <Text color={c.warning} bold>Approve?</Text>
119
138
  <Box flexDirection="column">
@@ -129,7 +148,9 @@ export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed
129
148
  )
130
149
  })}
131
150
  </Box>
151
+ {allowScope && !unsandboxed && !request && repeats >= 2 && <Text color={c.text.muted}>{`Approved ${repeats} times this session; 2 stops asking for the rest of it`}</Text>}
132
152
  {canCustomize && <Text color={c.text.muted}>g customize scope / select tools</Text>}
153
+ {directory && <Text color={c.text.muted}>d authorize folder / select tools: {directory}</Text>}
133
154
  </Box>
134
155
  )
135
156
  }
@@ -143,9 +164,9 @@ export function approvalChoiceForInput(
143
164
  key: { escape?: boolean; return?: boolean },
144
165
  selectedIndex: number,
145
166
  allowScope = true,
167
+ choices: readonly ApprovalChoice[] = allowScope ? APPROVAL_CHOICES : ["once", "deny"],
146
168
  ): ApprovalChoice | null {
147
169
  if (key.escape) return "deny"
148
- const choices: ApprovalChoice[] = allowScope ? APPROVAL_CHOICES : ["once", "deny"]
149
170
  const prefix = commandInput(input, key)
150
171
  if (prefix !== null && /^[1-9]$/.test(prefix)) return choices[Number(prefix) - 1] ?? null
151
172
  if (isReturnInput(input, key)) return choices[selectedIndex] ?? null
@@ -26,10 +26,10 @@ interface DialogProps {
26
26
 
27
27
  // ── Mode picker ──────────────────────────────────────────────────────────
28
28
  const MODES: { id: PermissionMode; label: string; meta: string }[] = [
29
- { id: "default", label: "default", meta: "ask before write/edit/exec" },
30
- { id: "acceptEdits", label: "acceptEdits", meta: "auto-approve file edits" },
29
+ { id: "default", label: "default", meta: "strict: ask before write/edit/exec" },
30
+ { id: "acceptEdits", label: "acceptEdits", meta: "balanced: auto-approve file edits" },
31
31
  { id: "plan", label: "plan", meta: "research only — no edits or commands" },
32
- { id: "bypassPermissions", label: "bypassPermissions", meta: "auto-approve everything (use with care)" },
32
+ { id: "bypassPermissions", label: "bypassPermissions", meta: "autonomous: auto-approve everything (use with care)" },
33
33
  ]
34
34
 
35
35
  export function ModeDialog({ config, onCommit, onCancel }: DialogProps) {
@@ -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>}
@@ -24,6 +24,7 @@ import { truncateToWidth } from "./truncate.js"
24
24
  import { ToolGrantDialog } from "./dialog-tool-grant.js"
25
25
  import { buildToolGrantRules } from "../tool-grants.js"
26
26
  import { commandInput } from "./controlled-input.js"
27
+ import { describeCapabilityPatterns } from "../capabilities.js"
27
28
 
28
29
  interface Props { onCancel: () => void; availableTools: string[] }
29
30
 
@@ -97,7 +98,7 @@ export function PermissionsDialog({ onCancel, availableTools }: Props) {
97
98
  const rule = flat.group.rules[flat.ruleIdx]
98
99
  if (rule) {
99
100
  try {
100
- permissionManager.removeRule(rule.rule.pattern, rule.rule.type, scopeOf(flat.group))
101
+ permissionManager.removeRule(rule.rule.pattern, rule.rule.type, scopeOf(flat.group), rule.rule.canonicalPath === true)
101
102
  try { appLogger.info(`permission_remove pattern=${rule.rule.pattern} type=${rule.rule.type}`) } catch {}
102
103
  } catch (failure) { setError(String(failure)) }
103
104
  }
@@ -119,7 +120,7 @@ export function PermissionsDialog({ onCancel, availableTools }: Props) {
119
120
  for (const g of groups) {
120
121
  if (g.label === "session") continue
121
122
  for (const r of g.rules) {
122
- try { permissionManager.removeRule(r.rule.pattern, r.rule.type, scopeOf(g)) } catch (failure) { setError(String(failure)) }
123
+ try { permissionManager.removeRule(r.rule.pattern, r.rule.type, scopeOf(g), r.rule.canonicalPath === true) } catch (failure) { setError(String(failure)) }
123
124
  }
124
125
  }
125
126
  try { appLogger.info("permission_clear_all") } catch {}
@@ -134,9 +135,9 @@ export function PermissionsDialog({ onCancel, availableTools }: Props) {
134
135
  }
135
136
  }, { isActive: !grantOpen })
136
137
 
137
- if (grantOpen) return <ToolGrantDialog availableTools={availableTools} onCancel={() => setGrantOpen(false)} onSave={request => {
138
+ if (grantOpen) return <ToolGrantDialog availableTools={availableTools} onCancel={() => setGrantOpen(false)} onSave={(request, reviewedRules) => {
138
139
  try {
139
- permissionManager.addToolRules(buildToolGrantRules(request, availableTools), request.lifetime)
140
+ permissionManager.addToolRules(buildToolGrantRules(request, availableTools, process.cwd(), reviewedRules), request.lifetime)
140
141
  setGrantOpen(false); setTick(value => value + 1)
141
142
  } catch (failure) { return String(failure) }
142
143
  }} />
@@ -169,7 +170,7 @@ export function PermissionsDialog({ onCancel, availableTools }: Props) {
169
170
  const { rule, shadowedBy } = annotated
170
171
  return (
171
172
  <Box
172
- key={`${group.label}::${rule.type}::${rule.pattern}`}
173
+ key={`${group.label}::${rule.type}::${rule.pattern}::${rule.canonicalPath ? "canonical" : "legacy"}`}
173
174
  flexDirection="column"
174
175
  >
175
176
  <Box flexDirection="row">
@@ -181,6 +182,8 @@ export function PermissionsDialog({ onCancel, availableTools }: Props) {
181
182
  <Text color={isSelected ? c.text.primary : c.text.muted} wrap="truncate-end">
182
183
  {truncateToWidth(rule.pattern, 60)}
183
184
  </Text>
185
+ {rule.canonicalPath && <Text color={c.text.ghost}> (fixed folder target)</Text>}
186
+ {describeCapabilityPatterns([rule.pattern]) && <Text color={c.text.ghost} wrap="truncate-end"> — {describeCapabilityPatterns([rule.pattern])}</Text>}
184
187
  {shadowedBy && (
185
188
  <Text color={c.text.ghost} wrap="truncate-end">
186
189
  {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 && <>
@@ -43,6 +43,9 @@ export interface ExecuteCommandOptions {
43
43
  workspaceOnly?: boolean;
44
44
  /** Expose destination declarations for a restricted execution backend. */
45
45
  restrictedNetwork?: boolean;
46
+ /** The host sandbox filters egress through an allowlist: offer
47
+ * network_destinations for other hosts, which the host approves. */
48
+ declaredNetwork?: boolean;
46
49
  /** Offer the per-call `dangerouslyDisableSandbox` retry. Defaults to true;
47
50
  * hosts set false when a backend (VM) or policy has no sandbox escape. */
48
51
  allowUnsandboxed?: boolean;
@@ -196,6 +199,12 @@ export function executeCommandTool(options: ExecuteCommandOptions = {}): Tool {
196
199
  .max(128)
197
200
  .optional()
198
201
  .describe("Exact HTTP(S) URLs, domains, or wildcard subdomains requested by this command; subject to the execution backend's network policy"),
202
+ } : options.declaredNetwork ? {
203
+ network_destinations: z
204
+ .array(z.string().min(1).max(253))
205
+ .max(16)
206
+ .optional()
207
+ .describe("Hosts outside the sandbox network allowlist this command must reach (api.example.com or *.example.com); each needs approval once"),
199
208
  } : {}),
200
209
  });
201
210
 
@@ -245,6 +254,12 @@ export function executeCommandTool(options: ExecuteCommandOptions = {}): Tool {
245
254
  "No sleep/ps polling. Exit sends a <task-notification>. For logs, use task_status: task_id with include_output=true (tail) or output_offset=0 (pages). outputFile grants no read_file access. Wait only for dependencies.",
246
255
  ]
247
256
  : [];
257
+ if (options.declaredNetwork) {
258
+ promptLines.push(
259
+ "",
260
+ "Sandboxed network reaches an allowlist (package registries, git hosts, common CDNs). For another host, declare it in network_destinations; the user approves each host once and the command stays sandboxed. Do not use dangerouslyDisableSandbox for network access.",
261
+ );
262
+ }
248
263
  if (options.restrictedNetwork) {
249
264
  promptLines.push(
250
265
  "",
@@ -294,7 +309,7 @@ export function executeCommandTool(options: ExecuteCommandOptions = {}): Tool {
294
309
  (args.cwd as string | undefined) ?? options.defaultCwd ?? context.cwd,
295
310
  options.defaultCwd ?? context.cwd,
296
311
  );
297
- const declaredDestinations = options.restrictedNetwork
312
+ const declaredDestinations = (options.restrictedNetwork || options.declaredNetwork)
298
313
  && Array.isArray((args as { network_destinations?: unknown }).network_destinations)
299
314
  ? ((args as { network_destinations: string[] }).network_destinations)
300
315
  : [];
@@ -305,10 +320,11 @@ export function executeCommandTool(options: ExecuteCommandOptions = {}): Tool {
305
320
  { kind: "filesystem", operation: "read", paths: [accessRoot, ...((args.read_paths ?? []) as string[]).map(path => resolveToolPathCanonical(path, cwd))] },
306
321
  { kind: "filesystem", operation: "modify", paths: [accessRoot, ...((args.write_paths ?? []) as string[]).map(path => resolveToolPathCanonical(path, cwd))] },
307
322
  ],
308
- network: declaredDestinations.length > 0
323
+ network: options.restrictedNetwork && declaredDestinations.length > 0
309
324
  ? [{ kind: "network", operation: "connect", destinations: declaredDestinations, methods: [] }]
310
325
  : options.sandboxNetwork === true
311
- ? [{ kind: "network", operation: "connect", destinations: ["*"], methods: [] }]
326
+ // The proxy still filters "*" through its allowlist; declared hosts extend it.
327
+ ? [{ kind: "network", operation: "connect", destinations: ["*", ...declaredDestinations], methods: [] }]
312
328
  : [],
313
329
  process: [{
314
330
  kind: "process",
@@ -185,6 +185,9 @@ async function fetchWithValidatedRedirects(
185
185
  request = { ...request, method: "GET", body: null, headers };
186
186
  }
187
187
  const next = await assertSafePublicHttpUrl(new URL(location, current).toString(), options.resolveHostname);
188
+ // Consent is per host: a body approved for one host is never replayed to
189
+ // another. Return the redirect itself instead of following it.
190
+ if (next.host !== current.host && request.body != null) return { response, finalUrl: current };
188
191
  if (next.origin !== current.origin) {
189
192
  // Fetch drops Authorization on cross-origin redirects; never hand caller
190
193
  // credentials to a host the caller did not name. Not restored on return.
@@ -61,8 +61,8 @@ const MEMORY_TIMESTAMP_SCHEMA = z.string().min(1).max(80).refine(
61
61
  * - project — facts about the current project not derivable from code/git
62
62
  * - reference — pointers to external systems (Linear, Slack, dashboards)
63
63
  *
64
- * Permission default is `confirm` so the user sees what's being saved on first
65
- * write. Allow via `/permissions allow memory_save` to skip prompts after vetting.
64
+ * Permission is `confirm`; the zapcode host allows project/reference writes
65
+ * and asks for global user/feedback writes. Other hosts decide for themselves.
66
66
  */
67
67
  export function memorySaveTool(options: MemorySaveToolOptions): Tool {
68
68
  const { store, globalStore } = options;