zapagent 1.14.22 → 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.
@@ -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 && <>
@@ -0,0 +1,31 @@
1
+ /** @jsxImportSource react */
2
+ import { Box, Text } from "ink"
3
+ import { generatedImageArtifact } from "../../zapsdk/utils/generated-image.js"
4
+ import { c } from "./theme.js"
5
+
6
+ /** Stored pixels are small, validated RGB data; no file reads or provider ANSI. */
7
+ export function GeneratedImageResult({ meta }: { meta: unknown }) {
8
+ const image = generatedImageArtifact(meta)
9
+ if (!image) return null
10
+ const thumbnail = image.thumbnail
11
+ const rows: string[] = []
12
+ if (thumbnail && Number.isInteger(thumbnail.width) && Number.isInteger(thumbnail.height)
13
+ && thumbnail.width > 0 && thumbnail.width <= 32 && thumbnail.height > 0 && thumbnail.height <= 32
14
+ && typeof thumbnail.rgb === "string" && thumbnail.rgb.length === thumbnail.width * thumbnail.height * 6
15
+ && /^[a-f0-9]+$/.test(thumbnail.rgb)) {
16
+ const rgb = Buffer.from(thumbnail.rgb, "hex")
17
+ const color = (x: number, y: number) => {
18
+ const offset = (Math.min(y, thumbnail.height - 1) * thumbnail.width + x) * 3
19
+ return `${rgb[offset]};${rgb[offset + 1]};${rgb[offset + 2]}`
20
+ }
21
+ for (let y = 0; y < thumbnail.height; y += 2) {
22
+ let line = ""
23
+ for (let x = 0; x < thumbnail.width; x++) line += `\x1b[38;2;${color(x, y)}m\x1b[48;2;${color(x, y + 1)}m▀`
24
+ rows.push(line + "\x1b[0m")
25
+ }
26
+ }
27
+ return <Box flexDirection="column">
28
+ {rows.map((row, index) => <Text key={index}>{row}</Text>)}
29
+ <Text color={c.text.faint}>{`PNG · ${image.width}×${image.height} · ${(image.bytes / 1024).toFixed(0)} KB`}</Text>
30
+ </Box>
31
+ }
@@ -69,6 +69,7 @@ function formatArgs(name: string, args: Record<string, unknown> | undefined): st
69
69
  if (args.source) return oneLine(`${normalizePath(String(args.source))} -> ${normalizePath(String(args.destination ?? ""))}`)
70
70
  if (args.command ?? args.cmd) return oneLine(String(args.command ?? args.cmd).replace(/\s*\n\s*/g, " "))
71
71
  if (name === "bash" && args.check_steps) return oneLine(shellCommandDisplay(args))
72
+ if (name === "generate_image" && args.output_path) return oneLine(normalizePath(String(args.output_path)))
72
73
  if (args.pattern) return oneLine(args.pattern)
73
74
  if (args.query) return oneLine(args.query)
74
75
  if (args.url) return oneLine(args.url)
@@ -89,7 +90,7 @@ const TOOL_ALIASES: Record<string, string> = {
89
90
  read_document: "ReadDocument", read_pdf: "ReadPdf", read_docx: "ReadDocx",
90
91
  current_time: "Time", memory_save: "Memory", memory_review: "MemoryReview", memory_merge: "MemoryMerge",
91
92
  cron_create: "CronCreate", cron_delete: "CronDelete", cron_list: "CronList",
92
- monitor: "Monitor",
93
+ monitor: "Monitor", generate_image: "GenerateImage",
93
94
  }
94
95
 
95
96
  export function getToolAlias(name: string): string {
@@ -108,7 +109,7 @@ const TOOL_ICONS: Record<string, string> = {
108
109
  read_file: "→", write_file: "←", append_file: "+", edit_file: "←", multi_edit: "←",
109
110
  delete_file: "✕", move_file: "↔", execute_command: "$", bash: "$",
110
111
  glob_files: "✱", search_files: "✱", web_search: "◈", http_fetch: "%",
111
- agent: "◇", list_directory: "→",
112
+ agent: "◇", list_directory: "→", generate_image: "▧",
112
113
  }
113
114
 
114
115
  export function getToolIcon(toolName: string): string {
@@ -1,4 +1,4 @@
1
- import { readFile, writeFile, readdir, mkdir, unlink, rename, link, stat, lstat, realpath } from "node:fs/promises";
1
+ import { open, readFile, readdir, mkdir, unlink, rename, link, stat, lstat, realpath } from "node:fs/promises";
2
2
  import { lstatSync, realpathSync } from "node:fs";
3
3
  import { basename, dirname, resolve, join, relative, isAbsolute, sep } from "node:path";
4
4
  import { randomBytes } from "node:crypto";
@@ -155,19 +155,29 @@ export function canonicalizeWithNearestExistingAncestorSync(path: string): strin
155
155
  export interface AtomicWriteOptions {
156
156
  /** Fail atomically if the destination appeared after the caller observed it missing. */
157
157
  replaceExisting?: boolean;
158
+ signal?: AbortSignal;
159
+ beforeCommit?: () => void | Promise<void>;
160
+ mode?: number;
158
161
  }
159
162
 
160
163
  /** Write via a same-directory temporary file, then atomically publish it. */
161
164
  export async function atomicWrite(
162
165
  filePath: string,
163
- content: string,
166
+ content: string | Uint8Array,
164
167
  options: AtomicWriteOptions = {},
165
168
  ): Promise<void> {
166
169
  const abs = resolve(filePath);
170
+ options.signal?.throwIfAborted();
167
171
  await mkdir(dirname(abs), { recursive: true });
168
172
  const tmp = `${abs}.tmp.${randomBytes(4).toString("hex")}`;
173
+ let ownsTemporaryFile = false;
169
174
  try {
170
- await writeFile(tmp, content, "utf-8");
175
+ const handle = await open(tmp, "wx", options.mode);
176
+ ownsTemporaryFile = true;
177
+ try { await handle.writeFile(content, { encoding: "utf-8", signal: options.signal }); }
178
+ finally { await handle.close(); }
179
+ await options.beforeCommit?.();
180
+ options.signal?.throwIfAborted();
171
181
  if (options.replaceExisting === false) {
172
182
  // A same-filesystem hard link is an atomic create-if-absent operation.
173
183
  // Unlike rename(), it cannot overwrite a destination created after the
@@ -178,7 +188,7 @@ export async function atomicWrite(
178
188
  }
179
189
  await rename(tmp, abs);
180
190
  } catch (err) {
181
- try { await unlink(tmp); } catch {}
191
+ if (ownsTemporaryFile) try { await unlink(tmp); } catch {}
182
192
  throw err;
183
193
  }
184
194
  }
@@ -0,0 +1,96 @@
1
+ import { access, lstat, mkdir, realpath } from "node:fs/promises";
2
+ import { constants } from "node:fs";
3
+ import { dirname, extname, join } from "node:path";
4
+ import { z } from "zod";
5
+ import type { Tool, ToolResult } from "../tools/types.js";
6
+ import type { GeneratedImage, ImageGenerationRequest } from "../core/providers/codex-image-generation.js";
7
+ import { IMAGE_TIMEOUT_MS } from "../core/providers/codex-image-generation.js";
8
+ import { cacheGeneratedImage, type GeneratedImageMeta } from "../utils/generated-image.js";
9
+ import { atomicWrite, isToolPathWriteAllowed, resolveToolEffectPaths, resolveToolPath, resolveToolPathCanonical, type FileAccessOptions } from "./filesystem.js";
10
+
11
+ export interface GenerateImageOptions extends FileAccessOptions {
12
+ defaultCwd?: string;
13
+ protectedPaths?: string[];
14
+ /** Host-owned model capability: pinned authenticated provider, independently
15
+ * bounded request/response bytes and deadlines, and no automatic retries.
16
+ * Model HTTP uses the provider budget; workspace bytes use execution grants. */
17
+ generate: (request: ImageGenerationRequest, signal?: AbortSignal) => Promise<GeneratedImage>;
18
+ /** Trusted runtime storage, never chosen by model arguments. Retains completed
19
+ * results if a workspace write fails, until the user removes the artifacts. */
20
+ artifactDirectory: string;
21
+ }
22
+
23
+ export function generateImageTool(options: GenerateImageOptions): Tool {
24
+ const cwd = options.defaultCwd ?? process.cwd();
25
+ return {
26
+ definition: {
27
+ name: "generate_image",
28
+ description: "Generate a PNG image with your Codex/ChatGPT account and save it to output_path. Use for illustrations, UI assets, photos, backgrounds and transparent cutouts. Creates a new file; never overwrites an existing file. Generation uses account image limits.",
29
+ prompt: "Use generate_image when the user asks to create an image. Choose a descriptive .png output_path in the workspace, then report the saved image path. Describe the desired visual in prompt; background=transparent produces a cutout. The provider chooses the final pixel dimensions. If a completed image has a local save error, recover the cached artifact reported by the tool instead of generating again. Do not retry a failed or interrupted generation without an explicit user request.",
30
+ parameters: z.object({
31
+ prompt: z.string().min(1).max(16000).describe("Visual description: subject, composition, style and constraints"),
32
+ output_path: z.string().min(1).max(1024).regex(/^[^\x00-\x1f\x7f]+$/).describe("New .png path, relative to the workspace or absolute; an existing file is never replaced"),
33
+ quality: z.enum(["auto", "low", "medium", "high"]).optional(),
34
+ size: z.enum(["auto", "1024x1024", "1536x1024", "1024x1536"]).optional().describe("Requested shape/size; returned dimensions may differ"),
35
+ background: z.enum(["auto", "opaque", "transparent"]).optional(),
36
+ }),
37
+ permission: "confirm", executionLocation: "host", timeoutMs: IMAGE_TIMEOUT_MS + 10_000,
38
+ checkpointTracking: "files",
39
+ writesPath: args => [resolveToolPath(String(args.output_path), cwd)],
40
+ resolveEffects: args => ({
41
+ filesystem: [{ kind: "filesystem", operation: "create", paths: resolveToolEffectPaths(String(args.output_path), cwd) }],
42
+ network: [{ kind: "network", operation: "mutate", destinations: ["https://chatgpt.com/backend-api/codex/responses"], methods: ["POST"] }],
43
+ external: [{ kind: "external", system: "openai:codex:image-generation", operation: "mutate" }],
44
+ process: [], workspace: { mode: "root-integration" }, confidence: "declared",
45
+ }),
46
+ },
47
+ handler: async (args, signal, context) => {
48
+ const path = resolveToolPath(String(args.output_path), cwd);
49
+ let meta: GeneratedImageMeta | undefined;
50
+ let providerCompleted = false;
51
+ try {
52
+ signal?.throwIfAborted();
53
+ if (extname(path).toLowerCase() !== ".png") throw new Error("Image output_path must end in .png.");
54
+ const check = async (expected?: string) => {
55
+ signal?.throwIfAborted();
56
+ if (!(await isToolPathWriteAllowed(path, options, context))) throw new Error("Image output path is outside the granted writable paths or is protected.");
57
+ const canonical = resolveToolPathCanonical(path, cwd);
58
+ if (expected && canonical !== expected) throw new Error("Image output path changed during generation; recover the cached image.");
59
+ try { await lstat(path); throw new Error("Image output already exists. Choose a new .png path; no generation was retried."); }
60
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
61
+ return canonical;
62
+ };
63
+ const target = await check();
64
+ // Fail unwritable/missing parents before spending image usage.
65
+ await mkdir(dirname(path), { recursive: true });
66
+ const parent = await realpath(dirname(path));
67
+ await check(target);
68
+ await mkdir(options.artifactDirectory, { recursive: true, mode: 0o700 });
69
+ await access(options.artifactDirectory, constants.W_OK);
70
+ const image = await options.generate({ prompt: String(args.prompt), quality: args.quality as ImageGenerationRequest["quality"],
71
+ size: args.size as ImageGenerationRequest["size"], background: args.background as ImageGenerationRequest["background"] }, signal);
72
+ // Cache only a confirmed provider result. Runtime artifact storage uses
73
+ // the provider's image bound, separately from workspace execution bytes.
74
+ providerCompleted = true;
75
+ const artifact = await cacheGeneratedImage(options.artifactDirectory, image);
76
+ meta = { generatedImage: artifact, providerRequest: { requestBytes: image.requestBytes, responseBytes: image.responseBytes } };
77
+ signal?.throwIfAborted();
78
+ context?.resources?.consumeFiles();
79
+ context?.resources?.consumeFileBytes(image.bytes.length);
80
+ await check(target);
81
+ if (await realpath(dirname(path)) !== parent) throw new Error("Image output directory changed during generation.");
82
+ await atomicWrite(target, image.bytes, { replaceExisting: false, signal, mode: 0o600, beforeCommit: async () => {
83
+ await check(target);
84
+ if (await realpath(dirname(path)) !== parent) throw new Error("Image output directory changed during generation.");
85
+ } });
86
+ artifact.filePath = path;
87
+ return { success: true, output: `Generated image saved to ${path}\nPNG · ${artifact.width}×${artifact.height} · ${image.bytes.length} bytes`, meta,
88
+ contentBlocks: [{ type: "image", filePath: path, mediaType: "image/png", base64: image.bytes.toString("base64"), source: "generate_image" }] };
89
+ } catch (error) {
90
+ const failure = error instanceof Error ? error.message : "Image generation failed.";
91
+ const recovery = meta ? `\nGeneration completed; recover the existing PNG at ${join(options.artifactDirectory, `${meta.generatedImage.id}.png`)}. Do not generate it again.` : providerCompleted ? "\nImage generation completed but persistence failed. Do not generate it again automatically." : "";
92
+ return { success: false, output: recovery.trim(), error: failure + recovery, ...(meta ? { meta } : {}) } satisfies ToolResult;
93
+ }
94
+ },
95
+ };
96
+ }
@@ -21,6 +21,7 @@ import { currentTimeTool } from "./time.js";
21
21
  import { readDocumentTool, readPdfTool, readDocxTool, type DocumentReadOptions } from "./document.js";
22
22
  import { todoWriteTool, type TodoWriteToolOptions, type TodoStore, type Todo, type TodoStatus } from "./todo.js";
23
23
  import { askUserQuestionTool, type AskUserToolOptions } from "./ask-user.js";
24
+ import { generateImageTool, type GenerateImageOptions } from "./generate-image.js";
24
25
  import { browserScreenshotTool, type BrowserScreenshotOptions } from "./browser.js";
25
26
  import { enterPlanModeTool, exitPlanModeTool, type PlanModeToolsOptions, type PlanModeCallbacks } from "./plan-mode.js";
26
27
  import { skillTool, type SkillToolOptions } from "./skill.js";
@@ -59,6 +60,7 @@ export { readDocumentTool, readPdfTool, readDocxTool, type DocumentReadOptions }
59
60
  export { todoWriteTool, renderTodoList, type TodoWriteToolOptions, type TodoStore, type Todo, type TodoStatus } from "./todo.js";
60
61
  export { enterPlanModeTool, exitPlanModeTool, type PlanModeToolsOptions, type PlanModeCallbacks } from "./plan-mode.js";
61
62
  export { askUserQuestionTool, type AskUserToolOptions, type AskUserCallbacks, type AskUserQuestion, type AskUserAnswer } from "./ask-user.js";
63
+ export { generateImageTool, type GenerateImageOptions } from "./generate-image.js";
62
64
  export { browserScreenshotTool, findBrowser, type BrowserScreenshotOptions } from "./browser.js";
63
65
  export { skillTool, type SkillToolOptions } from "./skill.js";
64
66
  export {
@@ -97,6 +99,8 @@ export interface BuiltinToolsOptions {
97
99
  listTree?: ListTreeOptions;
98
100
  documentRead?: DocumentReadOptions;
99
101
  browserScreenshot?: BrowserScreenshotOptions;
102
+ /** Only registered when the host supplies an authenticated image capability. */
103
+ generateImage?: GenerateImageOptions;
100
104
  webSearch?: WebSearchOptions;
101
105
  /** Required for the main agent to get `todo_write`. When omitted (e.g.
102
106
  * subagent registries), `todo_write` is not registered — mirrors CCB's
@@ -148,6 +152,7 @@ export function createBuiltinRegistry(options: BuiltinToolsOptions = {}): ToolRe
148
152
  if (!exclude.has("delete_file")) registry.register(deleteFileTool({ defaultCwd, ...options.deleteFile }));
149
153
  if (!exclude.has("move_file")) registry.register(moveFileTool({ defaultCwd, ...options.moveFile }));
150
154
  if (!exclude.has("list_tree")) registry.register(listTreeTool({ defaultCwd, ...options.listTree }));
155
+ if (options.generateImage && !exclude.has("generate_image")) registry.register(generateImageTool({ defaultCwd, ...options.generateImage }));
151
156
  if (!exclude.has("bash")) registry.register(executeCommandTool(options.executeCommand));
152
157
  if (!exclude.has("http_fetch")) registry.register(httpFetchTool(options.httpFetch));
153
158
  if (!exclude.has("http_request")) registry.register(httpRequestTool(options.httpRequest));