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.
package/README.md CHANGED
@@ -71,7 +71,7 @@ Interact in the terminal and follow task progress in the live browser view.
71
71
  On first use, enter `/connect` and follow the setup prompts to connect your model service. Then describe what you want: “Read the materials in this folder, summarize the key points, and write a report.”
72
72
 
73
73
  Use your model service account and API key, or select **OpenAI Codex (ChatGPT)**
74
- to sign in with a ChatGPT account using OAuth. Usage and model access depend on
74
+ to sign in with a ChatGPT account using OAuth. Codex connections also support image generation: ask Zap to create an image and save it to a new `.png` file. [Image generation](docs/usage.md#image-generation-with-codex). Usage and model access depend on
75
75
  your provider/account. [Connection guide](docs/usage.md#getting-started).
76
76
 
77
77
  Update from your terminal with `zap update` (or `zap update --yes` for unattended installation).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zapagent",
3
- "version": "1.14.22",
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} />}
package/src/acp/events.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { SessionUpdate, StopReason, ToolKind } from "@agentclientprotocol/sdk"
1
+ import type { SessionUpdate, StopReason, ToolKind, ToolCallContent } from "@agentclientprotocol/sdk"
2
2
  import type { AgentEvent } from "../../zapsdk/agent/events.js"
3
3
 
4
4
  export function acpStopReason(reason: string): StopReason {
@@ -46,9 +46,11 @@ export class AcpEventMapper {
46
46
  }
47
47
  if (event.type === "content_final" && event.kind === "tool_result") {
48
48
  const text = typeof event.result.output === "string" ? event.result.output : JSON.stringify(event.result.output ?? "")
49
+ const images: ToolCallContent[] = event.toolName === "generate_image" ? (event.result.contentBlocks ?? []).flatMap(block =>
50
+ block.type === "image" && block.base64 ? [{ type: "content" as const, content: { type: "image" as const, data: block.base64, mimeType: block.mediaType } }] : []) : []
49
51
  return [{ sessionUpdate: "tool_call_update", toolCallId: id(event.id),
50
52
  status: event.result.success === false ? "failed" : "completed", rawOutput: event.result,
51
- content: [{ type: "content", content: { type: "text", text: event.result.error ?? text } }] }]
53
+ content: [{ type: "content", content: { type: "text", text: event.result.error ?? text } }, ...images] }]
52
54
  }
53
55
  return []
54
56
  }
@@ -1,3 +1,5 @@
1
+ import { getAppDataDir } from "../zapsdk/utils/platform.js"
2
+ import { generateCodexImage } from "../zapsdk/core/providers/codex-image-generation.js"
1
3
  import { modelCanonicalIds } from "./provider-metadata.js"
2
4
  import { getCodexCredentials } from "./codex-auth.js"
3
5
  import { serviceTools } from "../zapsdk/services/tools.js"
@@ -37,7 +39,7 @@ import { createExecutionEnvironment, resolveExecutionBackend, type ExecutionEnvi
37
39
  const CWD_SENSITIVE_TOOLS = new Set([
38
40
  "read_file", "write_file", "edit_file", "multi_edit",
39
41
  "delete_file", "move_file", "list_tree", "bash",
40
- "search_files", "glob_files", "read_document", "browser_screenshot", "delegate_agent",
42
+ "search_files", "glob_files", "read_document", "browser_screenshot", "delegate_agent", "generate_image",
41
43
  ])
42
44
 
43
45
  function safeHost(url: string): string {
@@ -84,6 +86,11 @@ export function buildAgentObjects(
84
86
  const apiKey = rawApiKey || "unconfigured"
85
87
  const model = config.active.model
86
88
  const maxOutputTokens = getActiveMaxOutputTokens(config)
89
+ const imageCapability = active?.authMode === "codex-oauth" ? {
90
+ generate: (request: import("../zapsdk/core/providers/codex-image-generation.js").ImageGenerationRequest, signal?: AbortSignal) =>
91
+ generateCodexImage({ model: typeof active.extraRequestParams?.model === "string" ? active.extraRequestParams.model : model, getCredentials: getCodexCredentials }, request, signal),
92
+ artifactDirectory: join(getAppDataDir(), "generated-images"),
93
+ } : undefined
87
94
  // Protocol selection: explicit `protocol` field on the provider wins;
88
95
  // fall back to host substring detection so legacy configs (saved before
89
96
  // the field existed) still route the official Anthropic endpoint to
@@ -163,6 +170,7 @@ export function buildAgentObjects(
163
170
  globFiles: { allowedPaths, useExecutionGrants: true },
164
171
  documentRead: { allowedPaths, useExecutionGrants: true },
165
172
  browserScreenshot: { allowedPaths },
173
+ generateImage: imageCapability ? { ...imageCapability, allowedPaths, protectedPaths, useExecutionGrants: true, defaultCwd: effectiveCwd } : undefined,
166
174
  executeCommand: {
167
175
  timeoutMs: 60000,
168
176
  defaultCwd: effectiveCwd,
@@ -241,6 +249,7 @@ export function buildAgentObjects(
241
249
  globFiles: { allowedPaths, useExecutionGrants: true },
242
250
  documentRead: { allowedPaths, useExecutionGrants: true },
243
251
  browserScreenshot: { allowedPaths },
252
+ generateImage: imageCapability ? { ...imageCapability, allowedPaths, protectedPaths, useExecutionGrants: true, defaultCwd: workspaceCwd } : undefined,
244
253
  executeCommand: {
245
254
  timeoutMs: 60000,
246
255
  defaultCwd: workspaceCwd,
@@ -1,3 +1,4 @@
1
+ import { generatedImageArtifact, type GeneratedImageArtifact } from "../../zapsdk/utils/generated-image.js"
1
2
  import type { AgentOutcomeV1 } from "../../zapsdk/runtime/outcome.js"
2
3
  import type { InlineAcceptanceRecord } from "../../zapsdk/runtime/inline-acceptance.js"
3
4
  // Output formatters for headless runs. Three modes, all sharing one observer
@@ -36,6 +37,7 @@ export type StopReason =
36
37
  | "capability_unavailable"
37
38
 
38
39
  export interface ToolCallRecord {
40
+ generatedImage?: Omit<GeneratedImageArtifact, "thumbnail">
39
41
  name: string
40
42
  args: Record<string, unknown>
41
43
  ok: boolean
@@ -156,7 +158,10 @@ export function createFormatter(format: OutputFormat, quiet: boolean, resultSche
156
158
  const errMsg = !ok
157
159
  ? (event.result.error ?? (typeof event.result.output === "string" ? event.result.output : ""))
158
160
  : undefined
161
+ const image = event.toolName === "generate_image" ? generatedImageArtifact(event.result.meta) : undefined
162
+ const artifact = image ? (({ thumbnail, ...metadata }) => metadata)(image) : undefined
159
163
  const audit = {
164
+ ...(artifact ? { generatedImage: artifact } : {}),
160
165
  ...(event.result.runtime?.service ? { service: event.result.runtime.service } : {}),
161
166
  ...(event.result.runtime?.serviceOperation ? { serviceOperation: event.result.runtime.serviceOperation } : {}),
162
167
  ...(event.result.runtime?.resultSourcePolicy ? { resultSourcePolicy: event.result.runtime.resultSourcePolicy } : {}),
@@ -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
package/src/session.ts CHANGED
@@ -12,6 +12,7 @@ import {
12
12
  stat as statAsync,
13
13
  } from "node:fs/promises"
14
14
  import { createHash, randomUUID } from "node:crypto"
15
+ import { generatedImageArtifact, restoreGeneratedImage } from "../zapsdk/utils/generated-image.js"
15
16
  import { getAppDataDir } from "../zapsdk/utils/platform.js"
16
17
  import { legacyProjectDataSegment, resolveProjectDataSegment } from "../zapsdk/utils/project-paths.js"
17
18
  import type { ImageContent, Message } from "../zapsdk/index.js"
@@ -1984,7 +1985,25 @@ export function sessionLogsToTurns(logs: SessionLog[]): Turn[] {
1984
1985
  // toolCalls keyed by id — duplicates from replaceLog chaining are
1985
1986
  // de-duped in place. Order is preserved by tracking insertion order.
1986
1987
  const pendingToolCalls: { id: string; name: string; arguments: Record<string, unknown> }[] = []
1987
- const pendingToolResults = new Map<string, { content: string; success?: boolean; suppression?: "duplicate" }>()
1988
+ const pendingToolResults = new Map<string, { content: string; success?: boolean; suppression?: "duplicate"; meta?: unknown; generatedBlock?: ImageContent }>()
1989
+ // Restore recent generated pixels from authenticated runtime artifacts only.
1990
+ // Older outputs retain their paths; avoid loading an unbounded image history.
1991
+ const generatedBlocks = new Map<SessionLog, ImageContent>()
1992
+ const seenGeneratedCalls = new Set<string>()
1993
+ let generatedBytes = 0
1994
+ for (const log of [...logs].reverse()) {
1995
+ if (log.restore === false || log.type !== "result" || log.tool?.name !== "generate_image") continue
1996
+ if (!log.tool.id || seenGeneratedCalls.has(log.tool.id)) continue
1997
+ seenGeneratedCalls.add(log.tool.id)
1998
+ const artifact = generatedImageArtifact(log.tool.meta)
1999
+ if (!artifact || generatedBlocks.size >= 4 || generatedBytes + artifact.bytes > 16 * 1024 * 1024) continue
2000
+ const bytes = restoreGeneratedImage(join(getAppDataDir(), "generated-images"), log.tool.meta)
2001
+ if (!bytes) continue
2002
+ generatedBytes += bytes.length
2003
+ generatedBlocks.set(log, { type: "image", filePath: join(getAppDataDir(), "generated-images", `${artifact.id}.png`),
2004
+ mediaType: "image/png", base64: bytes.toString("base64"), source: "generate_image" })
2005
+ }
2006
+
1988
2007
 
1989
2008
  const flushPending = () => {
1990
2009
  if (pendingToolCalls.length > 0) {
@@ -1993,6 +2012,8 @@ export function sessionLogsToTurns(logs: SessionLog[]): Turn[] {
1993
2012
  for (const tc of pendingToolCalls) {
1994
2013
  const got = pendingToolResults.get(tc.id)
1995
2014
  if (got) {
2015
+ const artifact = tc.name === "generate_image" ? generatedImageArtifact(got.meta) : undefined
2016
+ const generatedBlock = got.generatedBlock
1996
2017
  completed.push({
1997
2018
  id: tc.id,
1998
2019
  name: tc.name,
@@ -2000,6 +2021,8 @@ export function sessionLogsToTurns(logs: SessionLog[]): Turn[] {
2000
2021
  result: {
2001
2022
  success: got.success ?? true,
2002
2023
  output: got.content,
2024
+ ...(artifact ? { meta: { generatedImage: artifact } } : {}),
2025
+ ...(generatedBlock ? { contentBlocks: [generatedBlock] } : {}),
2003
2026
  ...(got.suppression ? { runtime: { suppression: got.suppression } } : {}),
2004
2027
  },
2005
2028
  // Legacy logs lack status evidence. Preserve their output without
@@ -2078,6 +2101,8 @@ export function sessionLogsToTurns(logs: SessionLog[]): Turn[] {
2078
2101
  content: log.tool.output ?? "",
2079
2102
  success: log.tool.success,
2080
2103
  suppression: log.tool.suppression,
2104
+ meta: log.tool.name === "generate_image" ? log.tool.meta : undefined,
2105
+ generatedBlock: generatedBlocks.get(log),
2081
2106
  })
2082
2107
  }
2083
2108
  }
@@ -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
+ }
@@ -9,6 +9,7 @@
9
9
  // continuation rows leak back to col 0. <IndentedRow> bakes the right
10
10
  // pattern in once and every renderer reuses it.
11
11
 
12
+ import { GeneratedImageResult } from "./generated-image.js"
12
13
  import { Fragment, memo, useMemo, useRef } from "react"
13
14
  import { Box, Static, Text } from "ink"
14
15
  import type { LogEntry } from "./types.js"
@@ -488,6 +489,7 @@ export const ToolResult = memo(function ToolResult({ log }: { log: LogEntry }) {
488
489
  <Text color={c.text.muted}>{lines.join("\n")}</Text>
489
490
  </IndentedRow>
490
491
  )}
492
+ {tool.name === "generate_image" && <IndentedRow width={NESTED_COLS}><GeneratedImageResult meta={tool.meta} /></IndentedRow>}
491
493
  {checkpointWarning && (
492
494
  <IndentedRow width={NESTED_COLS}>
493
495
  <Text color={c.warning}>{`⚠ ${checkpointWarning}`}</Text>
@@ -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
  }