zapagent 1.14.21 → 1.14.23
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 +2 -2
- package/package.json +1 -1
- package/src/acp/events.ts +4 -2
- package/src/agent-factory.ts +11 -2
- package/src/codex-provider.ts +3 -2
- package/src/config.ts +25 -3
- package/src/headless/formatter.ts +5 -0
- package/src/provider-catalog.ts +7 -2
- package/src/provider-metadata.ts +10 -1
- package/src/session.ts +26 -1
- package/src/ui/Transcript.tsx +2 -0
- package/src/ui/dialog-config.tsx +53 -32
- package/src/ui/generated-image.tsx +31 -0
- package/src/ui/transcript-format.ts +3 -2
- package/zapsdk/builtin-tools/filesystem.ts +14 -4
- package/zapsdk/builtin-tools/generate-image.ts +96 -0
- package/zapsdk/builtin-tools/index.ts +5 -0
- package/zapsdk/core/providers/codex-image-generation.ts +186 -0
- package/zapsdk/core/providers/openai-responses.ts +12 -0
- package/zapsdk/core/reasoning-effort.ts +48 -0
- package/zapsdk/index.ts +3 -0
- package/zapsdk/utils/generated-image.ts +84 -0
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).
|
|
@@ -97,7 +97,7 @@ Git workspaces also require [Git](https://git-scm.com).
|
|
|
97
97
|
| Linux | [ARM64](https://github.com/JackCaow/zapagent/releases/latest/download/zap-linux-arm64) · [x64](https://github.com/JackCaow/zapagent/releases/latest/download/zap-linux-x64) |
|
|
98
98
|
| Windows | [x64](https://github.com/JackCaow/zapagent/releases/latest/download/zap-windows-x64.exe) |
|
|
99
99
|
|
|
100
|
-
**Model configuration** — use `/model` to choose a model and `/effort` to adjust supported reasoning settings. For custom services, enter the Base URL and API key in `/connect` and select the service's API protocol; choose **OpenAI Responses** for a Responses endpoint. [Responses configuration](docs/usage.md#openai-responses-api).
|
|
100
|
+
**Model configuration** — use `/model` to choose a model and `/effort` to adjust supported reasoning settings. For custom services, enter the Base URL and API key in `/connect` and select the service's API protocol; choose **OpenAI Responses** for a Responses endpoint. [Responses configuration](docs/usage.md#openai-responses-api). Codex OAuth reads reasoning levels, descriptions and the default from the current model’s authenticated catalog. Choices are saved per model; **default** (or `/effort off`) lets the server choose. Saved capabilities remain available offline. [Terminal recording](docs/recordings/model-effort.cast).
|
|
101
101
|
|
|
102
102
|
**From source** — the repository pins Bun 1.3.14:
|
|
103
103
|
|
package/package.json
CHANGED
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
|
}
|
package/src/agent-factory.ts
CHANGED
|
@@ -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
|
|
@@ -120,7 +127,7 @@ export function buildAgentObjects(
|
|
|
120
127
|
} as unknown as Record<string, string>
|
|
121
128
|
: undefined
|
|
122
129
|
const rawProvider = active?.authMode === "codex-oauth"
|
|
123
|
-
? new OpenAIResponsesProvider({ model, codex: { getCredentials: getCodexCredentials },
|
|
130
|
+
? new OpenAIResponsesProvider({ model, codex: { getCredentials: getCodexCredentials, reasoningByModel: active.reasoningByModel, effortByModel: active.effortByModel },
|
|
124
131
|
canonicalModelIds: modelCanonicalIds(active), supportsVision: resolveVisionSupport(active, model),
|
|
125
132
|
extraRequestParams: active.extraRequestParams, maxRequestBytes: active.maxRequestBytes })
|
|
126
133
|
: isAnthropic
|
|
@@ -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,
|
package/src/codex-provider.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { CODEX_BASE_URL, getCodexCredentials } from "./codex-auth.js"
|
|
2
|
+
import { normalizeModelReasoning, type ModelReasoning } from "../zapsdk/core/reasoning-effort.js"
|
|
2
3
|
import { VERSION } from "./version.js"
|
|
3
4
|
import { setActive, upsertProvider, type AppConfig, type Provider, type ProviderModelMetadata } from "./config.js"
|
|
4
5
|
|
|
@@ -14,7 +15,7 @@ export function connectCodexProvider(config: AppConfig): { config: AppConfig; pr
|
|
|
14
15
|
return { config: next, provider }
|
|
15
16
|
}
|
|
16
17
|
|
|
17
|
-
export async function discoverCodexModels(signal: AbortSignal): Promise<Array<{ id: string; metadata: ProviderModelMetadata }>> {
|
|
18
|
+
export async function discoverCodexModels(signal: AbortSignal): Promise<Array<{ id: string; metadata: ProviderModelMetadata; reasoning?: ModelReasoning }>> {
|
|
18
19
|
const credentials = await getCodexCredentials(signal)
|
|
19
20
|
const response = await fetch(`${CODEX_BASE_URL}/models?client_version=${encodeURIComponent(VERSION)}`, {
|
|
20
21
|
headers: { Authorization: `Bearer ${credentials.accessToken}`, originator: "zap",
|
|
@@ -27,7 +28,7 @@ export async function discoverCodexModels(signal: AbortSignal): Promise<Array<{
|
|
|
27
28
|
return data.models.flatMap(model => {
|
|
28
29
|
// supported_in_api only gates API-key accounts; Codex OAuth can use backend-only models.
|
|
29
30
|
if (typeof model.slug !== "string" || !model.slug || model.visibility === "hide" || model.visibility === "hidden") return []
|
|
30
|
-
return [{ id: model.slug, metadata: {
|
|
31
|
+
return [{ id: model.slug, reasoning: normalizeModelReasoning(model.supported_reasoning_levels, model.default_reasoning_level), metadata: {
|
|
31
32
|
name: typeof model.display_name === "string" ? model.display_name : undefined,
|
|
32
33
|
contextWindow: typeof model.context_window === "number" && model.context_window > 0 ? model.context_window : undefined,
|
|
33
34
|
supportsVision: Array.isArray(model.input_modalities) ? model.input_modalities.includes("image") : undefined,
|
package/src/config.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { modelReasoningFor, normalizeReasoningMap, resolveModelEffort, effortName, type ModelReasoning } from "../zapsdk/core/reasoning-effort.js"
|
|
1
2
|
import { deriveCompactionThresholds } from "../zapsdk/context/compact-budget.js"
|
|
2
3
|
import { canonicalModelId } from "../zapsdk/core/model-identity.js"
|
|
3
4
|
import { existsSync, readFileSync } from "node:fs"
|
|
@@ -117,6 +118,10 @@ export interface Provider {
|
|
|
117
118
|
* hints apply; unknown capability preserves images. The host can persist
|
|
118
119
|
* LoopAgent's bounded image-rejection fallback here for subsequent runs. */
|
|
119
120
|
visionByModel?: Record<string, boolean>
|
|
121
|
+
/** Authenticated capabilities, independent of public catalog alias metadata. */
|
|
122
|
+
reasoningByModel?: Record<string, ModelReasoning>
|
|
123
|
+
/** Codex model preferences; null explicitly uses the server default. */
|
|
124
|
+
effortByModel?: Record<string, string | null>
|
|
120
125
|
}
|
|
121
126
|
|
|
122
127
|
export interface CompactionConfig {
|
|
@@ -461,6 +466,9 @@ function normalizeProvider(value: unknown, index: number): Provider | null {
|
|
|
461
466
|
: [],
|
|
462
467
|
protocol: value.protocol === "anthropic" || value.protocol === "openai" || value.protocol === "openai-responses" ? value.protocol : undefined,
|
|
463
468
|
modelMetadata,
|
|
469
|
+
reasoningByModel: normalizeReasoningMap(value.reasoningByModel),
|
|
470
|
+
effortByModel: isRecord(value.effortByModel) ? Object.fromEntries(Object.entries(value.effortByModel)
|
|
471
|
+
.filter(([model, effort]) => !!model && model.length <= 256 && !/[\x00-\x1f\x7f]/.test(model) && (effort === null || effortName(effort)))) : undefined,
|
|
464
472
|
} as Provider
|
|
465
473
|
provider.contextWindowMode = value.contextWindowMode === "auto" || value.contextWindowMode === "manual"
|
|
466
474
|
? value.contextWindowMode
|
|
@@ -813,11 +821,16 @@ export function removeModelFromProvider(config: AppConfig, providerId: string, m
|
|
|
813
821
|
// reasoning_effort`; "unset" = key absent, server uses its own default.
|
|
814
822
|
// The Responses adapter maps this setting to `reasoning.effort`.
|
|
815
823
|
|
|
816
|
-
/**
|
|
817
|
-
|
|
818
|
-
|
|
824
|
+
/** The request-body model override also controls the effort capability lookup. */
|
|
825
|
+
export function effortModel(config: AppConfig, provider: Provider): string {
|
|
826
|
+
return typeof provider.extraRequestParams?.model === "string" ? provider.extraRequestParams.model
|
|
827
|
+
: config.active.providerId === provider.id ? config.active.model : provider.models[0] ?? ""
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/** OAuth uses exact model capabilities; other providers keep preset/passthrough behavior. */
|
|
819
831
|
export function getEffortValuesForProvider(config: AppConfig, providerId: string): readonly string[] {
|
|
820
832
|
const p = config.providers.find(x => x.id === providerId)
|
|
833
|
+
if (p?.authMode === "codex-oauth") return modelReasoningFor(p.reasoningByModel, effortModel(config, p))?.levels.map(level => level.effort) ?? []
|
|
821
834
|
const preset = p?.sourcePresetId ? presetMap.get(p.sourcePresetId) : undefined
|
|
822
835
|
return preset?.effortValues ?? DEFAULT_EFFORT_VALUES
|
|
823
836
|
}
|
|
@@ -830,6 +843,7 @@ export function getEffortValuesForProvider(config: AppConfig, providerId: string
|
|
|
830
843
|
* upstream server enforce its own rules. */
|
|
831
844
|
export function hasDeclaredEffortValues(config: AppConfig, providerId: string): boolean {
|
|
832
845
|
const p = config.providers.find(x => x.id === providerId)
|
|
846
|
+
if (p?.authMode === "codex-oauth") return !!modelReasoningFor(p.reasoningByModel, effortModel(config, p))
|
|
833
847
|
const preset = p?.sourcePresetId ? presetMap.get(p.sourcePresetId) : undefined
|
|
834
848
|
return preset?.effortValues !== undefined
|
|
835
849
|
}
|
|
@@ -861,6 +875,13 @@ export function resolveEffortInput(
|
|
|
861
875
|
/** Current effort, or undefined if unset (= use server default). */
|
|
862
876
|
export function getEffort(config: AppConfig, providerId: string): string | undefined {
|
|
863
877
|
const p = config.providers.find(x => x.id === providerId)
|
|
878
|
+
if (p?.authMode === "codex-oauth") {
|
|
879
|
+
const model = effortModel(config, p)
|
|
880
|
+
const nested = p.extraRequestParams?.reasoning as { effort?: unknown } | undefined
|
|
881
|
+
const value = Object.hasOwn(p.effortByModel ?? {}, model) ? p.effortByModel![model]
|
|
882
|
+
: typeof p.extraRequestParams?.reasoning_effort === "string" ? p.extraRequestParams.reasoning_effort : nested?.effort
|
|
883
|
+
return resolveModelEffort(modelReasoningFor(p.reasoningByModel, model), value)
|
|
884
|
+
}
|
|
864
885
|
const v = p?.extraRequestParams?.reasoning_effort
|
|
865
886
|
return typeof v === "string" ? v : undefined
|
|
866
887
|
}
|
|
@@ -872,6 +893,7 @@ export function setEffort(config: AppConfig, providerId: string, value: string |
|
|
|
872
893
|
const providers = config.providers.map(p => {
|
|
873
894
|
if (p.id !== providerId) return p
|
|
874
895
|
const extra = { ...(p.extraRequestParams ?? {}) }
|
|
896
|
+
if (p.authMode === "codex-oauth") return { ...p, effortByModel: { ...p.effortByModel, [effortModel(config, p)]: value } }
|
|
875
897
|
if (value === null) delete extra.reasoning_effort
|
|
876
898
|
else extra.reasoning_effort = value
|
|
877
899
|
return { ...p, extraRequestParams: extra }
|
|
@@ -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 } : {}),
|
package/src/provider-catalog.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { ModelReasoning } from "../zapsdk/core/reasoning-effort.js"
|
|
1
2
|
import { listModels } from "../zapsdk/core/list-models.js"
|
|
2
3
|
import { getModelsDevProvider, suggestedModelsDevIds, type ModelsDevProvider } from "../zapsdk/core/models-dev.js"
|
|
3
4
|
import { resolveCatalogProviderId, upsertProvider, setActive, type AppConfig, type Provider, type ProviderModelMetadata } from "./config.js"
|
|
@@ -5,7 +6,7 @@ import { enrichProviderMetadata, mergeModelMetadata, modelsDevMetadata, pickMode
|
|
|
5
6
|
import { discoverCodexModels } from "./codex-provider.js"
|
|
6
7
|
|
|
7
8
|
export type ModelSource = "saved" | "provider" | "models.dev" | "manual"
|
|
8
|
-
export interface CatalogRow { id: string; source: ModelSource; metadata?: ProviderModelMetadata }
|
|
9
|
+
export interface CatalogRow { id: string; source: ModelSource; metadata?: ProviderModelMetadata; reasoning?: ModelReasoning }
|
|
9
10
|
export interface DiscoveredCatalog { rows: CatalogRow[]; error?: string }
|
|
10
11
|
|
|
11
12
|
/** User-selected metadata for a gateway alias, independent of transport identity. */
|
|
@@ -73,7 +74,11 @@ export function selectCatalogModel(config: AppConfig, providerId: string, row: C
|
|
|
73
74
|
const models = [...new Set([...provider.models, row.id])]
|
|
74
75
|
const modelMetadata = pickModelMetadata(mergeModelMetadata(provider.modelMetadata ?? {},
|
|
75
76
|
row.metadata ? { [row.id]: row.metadata } : {}), models)
|
|
76
|
-
|
|
77
|
+
const liveReasoning = provider.authMode === "codex-oauth" && row.source === "provider"
|
|
78
|
+
const reasoningByModel = { ...provider.reasoningByModel,
|
|
79
|
+
...(liveReasoning && row.reasoning ? { [row.id]: row.reasoning } : {}) }
|
|
80
|
+
if (liveReasoning && !row.reasoning) delete reasoningByModel[row.id]
|
|
81
|
+
return setActive(upsertProvider(config, { ...provider, models, modelMetadata, reasoningByModel }), providerId, row.id)
|
|
77
82
|
}
|
|
78
83
|
|
|
79
84
|
export function describeCatalogRow(row: CatalogRow): string {
|
package/src/provider-metadata.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { discoverCodexModels } from "./codex-provider.js"
|
|
1
2
|
import type { ImageTokenContext } from "../zapsdk/context/image-tokens.js"
|
|
2
3
|
import { canonicalModelId } from "../zapsdk/core/model-identity.js"
|
|
3
4
|
import {
|
|
@@ -83,6 +84,14 @@ export function enrichProviderMetadata(provider: Provider, catalog: ModelsDevPro
|
|
|
83
84
|
export async function refreshModelsDevMetadata(config: AppConfig): Promise<AppConfig> {
|
|
84
85
|
const providers = await Promise.all(config.providers.map(async provider => {
|
|
85
86
|
if (provider.models.length === 0) return provider
|
|
87
|
+
if (provider.authMode === "codex-oauth") {
|
|
88
|
+
try {
|
|
89
|
+
const rows = await discoverCodexModels(AbortSignal.timeout(6500))
|
|
90
|
+
const reasoningByModel = Object.fromEntries(rows.flatMap(row => row.reasoning ? [[row.id, row.reasoning]] : []))
|
|
91
|
+
return JSON.stringify(reasoningByModel) === JSON.stringify(provider.reasoningByModel ?? {})
|
|
92
|
+
? provider : { ...provider, reasoningByModel }
|
|
93
|
+
} catch { return provider }
|
|
94
|
+
}
|
|
86
95
|
const ids = new Set([resolveCatalogProviderId(provider), ...provider.models.map(id =>
|
|
87
96
|
provider.modelMetadata?.[id]?.catalogRef?.providerId)].filter((id): id is string => !!id))
|
|
88
97
|
const catalogs = await Promise.all([...ids].map(id => getModelsDevProvider(id).catch(() => null)))
|
|
@@ -124,7 +133,7 @@ export function applyMetadataRefresh(current: AppConfig, initial: AppConfig, ref
|
|
|
124
133
|
const after = refreshed.providers.find(item => item.id === provider.id)
|
|
125
134
|
if (!before || !after || before === after || provider !== before) return provider
|
|
126
135
|
return { ...provider, contextWindow: after.contextWindow,
|
|
127
|
-
contextWindowMode: after.contextWindowMode, modelMetadata: after.modelMetadata }
|
|
136
|
+
contextWindowMode: after.contextWindowMode, modelMetadata: after.modelMetadata, reasoningByModel: after.reasoningByModel }
|
|
128
137
|
})
|
|
129
138
|
return providers.every((provider, index) => provider === current.providers[index])
|
|
130
139
|
? current : { ...current, providers }
|
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
|
}
|
package/src/ui/Transcript.tsx
CHANGED
|
@@ -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>
|
package/src/ui/dialog-config.tsx
CHANGED
|
@@ -3,7 +3,12 @@
|
|
|
3
3
|
// dialogs: Model, Mode, Effort. Kept in one file because they share the
|
|
4
4
|
// same 30-line shape — caller hands in `{config, onCommit, onCancel}`,
|
|
5
5
|
// the dialog wires options + commit semantics around PickerDialog.
|
|
6
|
+
import { modelReasoningFor } from "../../zapsdk/core/reasoning-effort.js"
|
|
7
|
+
import { useEffect, useState } from "react"
|
|
8
|
+
import { discoverCodexModels } from "../codex-provider.js"
|
|
6
9
|
import {
|
|
10
|
+
effortModel,
|
|
11
|
+
upsertProvider,
|
|
7
12
|
getActiveProvider,
|
|
8
13
|
getEffort,
|
|
9
14
|
setEffort,
|
|
@@ -48,37 +53,53 @@ export function ModeDialog({ config, onCommit, onCancel }: DialogProps) {
|
|
|
48
53
|
// ── Effort picker ────────────────────────────────────────────────────────
|
|
49
54
|
export function EffortDialog({ config, onCommit, onCancel }: DialogProps) {
|
|
50
55
|
const provider = getActiveProvider(config)
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
56
|
+
// A changed connection remounts the fetch and picker, including its cursor.
|
|
57
|
+
return <ModelEffortDialog key={provider ? `${provider.id}:${effortModel(config, provider)}` : "none"}
|
|
58
|
+
config={config} onCommit={onCommit} onCancel={onCancel} />
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function ModelEffortDialog({ config, onCommit, onCancel }: DialogProps) {
|
|
62
|
+
const provider = getActiveProvider(config)
|
|
63
|
+
const [snapshot, setSnapshot] = useState<{ provider: typeof provider; rows: Awaited<ReturnType<typeof discoverCodexModels>> }>()
|
|
64
|
+
const [status, setStatus] = useState("Loading model capabilities…")
|
|
65
|
+
useEffect(() => {
|
|
66
|
+
if (provider?.authMode !== "codex-oauth") return
|
|
67
|
+
const controller = new AbortController()
|
|
68
|
+
setStatus("Loading model capabilities…")
|
|
69
|
+
discoverCodexModels(controller.signal).then(rows => {
|
|
70
|
+
if (controller.signal.aborted) return
|
|
71
|
+
setSnapshot({ provider, rows })
|
|
72
|
+
setStatus("Model has not advertised reasoning levels")
|
|
73
|
+
}, () => {
|
|
74
|
+
if (!controller.signal.aborted) setStatus("Discovery unavailable; using saved model capabilities")
|
|
75
|
+
})
|
|
76
|
+
return () => controller.abort()
|
|
77
|
+
}, [provider])
|
|
78
|
+
let latest = config
|
|
79
|
+
if (provider && snapshot?.provider === provider) {
|
|
80
|
+
const reasoningByModel = Object.fromEntries(snapshot.rows.flatMap(row => row.reasoning ? [[row.id, row.reasoning]] : []))
|
|
81
|
+
latest = upsertProvider(config, { ...provider, reasoningByModel })
|
|
61
82
|
}
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
const
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
83
|
+
const active = getActiveProvider(latest)
|
|
84
|
+
const codex = active?.authMode === "codex-oauth"
|
|
85
|
+
const values = active ? getEffortValuesForProvider(latest, active.id) : []
|
|
86
|
+
const model = active ? effortModel(latest, active) : ""
|
|
87
|
+
const profile = modelReasoningFor(active?.reasoningByModel, model)
|
|
88
|
+
if (!active || (!codex && values.length === 0)) {
|
|
89
|
+
return <PickerDialog title="Reasoning effort"
|
|
90
|
+
options={[{ id: "__none", label: "Active provider does not expose reasoning_effort", disabled: true }]}
|
|
91
|
+
onCancel={onCancel} onSelect={onCancel} />
|
|
92
|
+
}
|
|
93
|
+
const current = getEffort(latest, active.id)
|
|
94
|
+
const options: PickerOption[] = [{ id: "__default", label: codex ? "default" : "off",
|
|
95
|
+
meta: `${codex ? `server default${profile?.defaultEffort ? ` (${profile.defaultEffort})` : ""}` : "server default"}${!current ? " (current)" : ""}` },
|
|
96
|
+
...values.map(value => ({ id: `level:${value}`, label: value,
|
|
97
|
+
meta: [profile?.levels.find(level => level.effort === value)?.description,
|
|
98
|
+
current === value ? "(current)" : undefined].filter(Boolean).join(" · ") }))]
|
|
99
|
+
if (codex && !profile) options.push({ id: "__status", label: status, disabled: true })
|
|
100
|
+
if (codex && profile?.levels.length === 0) options.push({ id: "__none", label: "No adjustable reasoning levels", disabled: true })
|
|
101
|
+
return <PickerDialog key={`${model}:${values.join(",")}:${current ?? "default"}`}
|
|
102
|
+
title={`Reasoning effort — ${codex ? model : active.name}`}
|
|
103
|
+
options={options} initialIndex={current ? Math.max(0, values.indexOf(current) + 1) : 0}
|
|
104
|
+
onCancel={onCancel} onSelect={id => onCommit(setEffort(latest, active.id, id === "__default" ? null : id.slice(6)))} />
|
|
84
105
|
}
|
|
@@ -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 {
|
|
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
|
|
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));
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { inflateSync } from "node:zlib";
|
|
2
|
+
import { CODEX_RESPONSES_BASE_URL } from "./openai-responses.js";
|
|
3
|
+
import { parseImageDimensions } from "../../utils/image-dimensions.js";
|
|
4
|
+
|
|
5
|
+
export const IMAGE_MAX_BYTES = 8 * 1024 * 1024;
|
|
6
|
+
export const IMAGE_RESPONSE_MAX_BYTES = 32 * 1024 * 1024;
|
|
7
|
+
export const IMAGE_TIMEOUT_MS = 300_000;
|
|
8
|
+
export interface ImageGenerationRequest {
|
|
9
|
+
prompt: string;
|
|
10
|
+
quality?: "auto" | "low" | "medium" | "high";
|
|
11
|
+
size?: "auto" | "1024x1024" | "1536x1024" | "1024x1536";
|
|
12
|
+
background?: "auto" | "opaque" | "transparent";
|
|
13
|
+
}
|
|
14
|
+
export interface GeneratedImage {
|
|
15
|
+
bytes: Buffer;
|
|
16
|
+
width: number;
|
|
17
|
+
height: number;
|
|
18
|
+
requestBytes: number;
|
|
19
|
+
responseBytes: number;
|
|
20
|
+
}
|
|
21
|
+
export interface CodexImageOptions {
|
|
22
|
+
model: string;
|
|
23
|
+
getCredentials: (signal?: AbortSignal) => Promise<{ accessToken: string; accountId?: string }>;
|
|
24
|
+
fetch?: typeof globalThis.fetch;
|
|
25
|
+
timeoutMs?: number;
|
|
26
|
+
idleMs?: number;
|
|
27
|
+
maxResponseBytes?: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
const crcTable = Uint32Array.from({ length: 256 }, (_, index) => {
|
|
32
|
+
let crc = index;
|
|
33
|
+
for (let bit = 0; bit < 8; bit++) crc = crc & 1 ? 0xedb88320 ^ (crc >>> 1) : crc >>> 1;
|
|
34
|
+
return crc >>> 0;
|
|
35
|
+
});
|
|
36
|
+
function validPngPixels(bytes: Buffer, width: number, height: number): boolean {
|
|
37
|
+
const compressed: Buffer[] = [];
|
|
38
|
+
let offset = 8, header = false, ended = false, palette = false, depth = 0, color = 0, interlace = 0;
|
|
39
|
+
while (offset + 12 <= bytes.length) {
|
|
40
|
+
const length = bytes.readUInt32BE(offset), end = offset + 8 + length;
|
|
41
|
+
if (end + 4 > bytes.length) return false;
|
|
42
|
+
const kind = bytes.toString("latin1", offset + 4, offset + 8);
|
|
43
|
+
if (!/^[A-Za-z]{4}$/.test(kind)) return false;
|
|
44
|
+
let crc = 0xffffffff;
|
|
45
|
+
for (let i = offset + 4; i < end; i++) crc = crcTable[(crc ^ bytes[i]!) & 255]! ^ (crc >>> 8);
|
|
46
|
+
if (((crc ^ 0xffffffff) >>> 0) !== bytes.readUInt32BE(end)) return false;
|
|
47
|
+
if (!header && kind !== "IHDR") return false;
|
|
48
|
+
if (kind === "IHDR") {
|
|
49
|
+
if (header || length !== 13) return false;
|
|
50
|
+
header = true; depth = bytes[offset + 16]!; color = bytes[offset + 17]!; interlace = bytes[offset + 20]!;
|
|
51
|
+
const depths: Record<number, number[]> = { 0: [1, 2, 4, 8, 16], 2: [8, 16], 3: [1, 2, 4, 8], 4: [8, 16], 6: [8, 16] };
|
|
52
|
+
if (!depths[color]?.includes(depth) || bytes[offset + 18] !== 0 || bytes[offset + 19] !== 0 || interlace > 1) return false;
|
|
53
|
+
} else if (kind === "IDAT") compressed.push(bytes.subarray(offset + 8, end));
|
|
54
|
+
else if (kind === "PLTE") { if (!length || length > 768 || length % 3) return false; palette = true; }
|
|
55
|
+
else if (kind === "IEND") { ended = length === 0 && end + 4 === bytes.length; break; }
|
|
56
|
+
else if (kind === "acTL" || !/^[a-z]/.test(kind)) return false;
|
|
57
|
+
offset = end + 4;
|
|
58
|
+
}
|
|
59
|
+
if (!ended || !compressed.length || (color === 3 && !palette)) return false;
|
|
60
|
+
const channels: Record<number, number> = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 };
|
|
61
|
+
const passes = interlace ? [[0, 0, 8, 8], [4, 0, 8, 8], [0, 4, 4, 8], [2, 0, 4, 4], [0, 2, 2, 4], [1, 0, 2, 2], [0, 1, 1, 2]] : [[0, 0, 1, 1]];
|
|
62
|
+
try {
|
|
63
|
+
const raw = inflateSync(Buffer.concat(compressed), { maxOutputLength: 68 * 1024 * 1024 });
|
|
64
|
+
let cursor = 0;
|
|
65
|
+
for (const [x, y, dx, dy] of passes) {
|
|
66
|
+
const w = Math.max(0, Math.ceil((width - x!) / dx!)), h = Math.max(0, Math.ceil((height - y!) / dy!));
|
|
67
|
+
if (!w || !h) continue;
|
|
68
|
+
const row = Math.ceil(w * depth * channels[color]! / 8) + 1;
|
|
69
|
+
for (let line = 0; line < h; line++) { if (cursor + row > raw.length || raw[cursor]! > 4) return false; cursor += row; }
|
|
70
|
+
}
|
|
71
|
+
return cursor === raw.length;
|
|
72
|
+
} catch { return false; }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function validateGeneratedPng(bytes: Buffer): { width: number; height: number } {
|
|
76
|
+
const dimensions = parseImageDimensions(bytes);
|
|
77
|
+
if (bytes.length > IMAGE_MAX_BYTES || bytes.length < 32 || bytes.subarray(0, 8).toString("hex") !== "89504e470d0a1a0a"
|
|
78
|
+
|| !dimensions || dimensions.width > 4096 || dimensions.height > 4096 || dimensions.width * dimensions.height > 16_777_216 || !validPngPixels(bytes, dimensions.width, dimensions.height)) {
|
|
79
|
+
throw new Error("Generated image is not a supported PNG or exceeds the image size limit.");
|
|
80
|
+
}
|
|
81
|
+
return dimensions;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function abortable<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {
|
|
85
|
+
signal.throwIfAborted();
|
|
86
|
+
let abort: (() => void) | undefined;
|
|
87
|
+
try {
|
|
88
|
+
return await Promise.race([work, new Promise<never>((_, reject) => {
|
|
89
|
+
abort = () => reject(signal.reason ?? new Error("Image generation cancelled."));
|
|
90
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
91
|
+
if (signal.aborted) abort();
|
|
92
|
+
})]);
|
|
93
|
+
} finally { if (abort) signal.removeEventListener("abort", abort); }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Host-owned model request, like the conversation provider. It has its own
|
|
97
|
+
* bounded HTTP budget, not the ordinary tool HTTP-fetch budget. No retries:
|
|
98
|
+
* retrying an interrupted generation can charge for another image. */
|
|
99
|
+
export async function generateCodexImage(options: CodexImageOptions, args: ImageGenerationRequest, signal?: AbortSignal): Promise<GeneratedImage> {
|
|
100
|
+
if (!options.model || options.model.length > 256 || /[\x00-\x1f\x7f]/.test(options.model)) throw new Error("Select a valid Codex model before generating images.");
|
|
101
|
+
if (!args.prompt.trim() || Buffer.byteLength(args.prompt) > 16_000) throw new Error("Image prompt must be 1–16000 UTF-8 bytes.");
|
|
102
|
+
const requestSignal = AbortSignal.any([AbortSignal.timeout(options.timeoutMs ?? IMAGE_TIMEOUT_MS), ...(signal ? [signal] : [])]);
|
|
103
|
+
requestSignal.throwIfAborted();
|
|
104
|
+
const credentials = await abortable(options.getCredentials(requestSignal), requestSignal);
|
|
105
|
+
requestSignal.throwIfAborted();
|
|
106
|
+
const body = JSON.stringify({ model: options.model, instructions: "Generate exactly one image with the image generation tool, following the user's prompt.",
|
|
107
|
+
input: [{ role: "user", content: args.prompt }], store: false, stream: true,
|
|
108
|
+
tools: [{ type: "image_generation", model: "gpt-image-2", output_format: "png", quality: args.quality ?? "auto",
|
|
109
|
+
size: args.size ?? "auto", background: args.background ?? "auto" }], tool_choice: { type: "image_generation" } });
|
|
110
|
+
const requestBytes = Buffer.byteLength(body);
|
|
111
|
+
const response = await abortable((options.fetch ?? fetch)(`${CODEX_RESPONSES_BASE_URL}/responses`, {
|
|
112
|
+
method: "POST", headers: { Authorization: `Bearer ${credentials.accessToken}`, "Content-Type": "application/json", originator: "zap",
|
|
113
|
+
...(credentials.accountId ? { "ChatGPT-Account-ID": credentials.accountId } : {}) },
|
|
114
|
+
body, signal: requestSignal, redirect: "error",
|
|
115
|
+
}), requestSignal);
|
|
116
|
+
if (!response.ok || !response.body) {
|
|
117
|
+
void response.body?.cancel().catch(() => {});
|
|
118
|
+
throw new Error(`Codex image generation failed (HTTP ${response.status}). Check Codex sign-in, model access and usage limits.`);
|
|
119
|
+
}
|
|
120
|
+
const reader = response.body.getReader();
|
|
121
|
+
const decoder = new TextDecoder();
|
|
122
|
+
const images = new Map<string, { bytes: Buffer; width: number; height: number }>();
|
|
123
|
+
let responseBytes = 0, buffer = "", data: string[] = [], completed = false;
|
|
124
|
+
const capture = (item: any) => {
|
|
125
|
+
if (item?.type !== "image_generation_call") return;
|
|
126
|
+
if (item.status !== "completed" || typeof item.id !== "string" || typeof item.result !== "string") {
|
|
127
|
+
throw new Error("Codex returned an incomplete image generation result.");
|
|
128
|
+
}
|
|
129
|
+
if (item.result.length > Math.ceil(IMAGE_MAX_BYTES / 3) * 4 || !/^[A-Za-z0-9+/]+={0,2}$/.test(item.result)) {
|
|
130
|
+
throw new Error("Codex returned an invalid or oversized image payload.");
|
|
131
|
+
}
|
|
132
|
+
if (images.has(item.id)) {
|
|
133
|
+
if (images.get(item.id)!.bytes.toString("base64") !== item.result) throw new Error("Codex returned conflicting image results.");
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
if (images.size) throw new Error("Codex returned more than one image for a single-image request.");
|
|
137
|
+
const bytes = Buffer.from(item.result, "base64");
|
|
138
|
+
if (bytes.toString("base64") !== item.result) throw new Error("Codex returned an invalid image encoding.");
|
|
139
|
+
images.set(item.id, { bytes, ...validateGeneratedPng(bytes) });
|
|
140
|
+
};
|
|
141
|
+
const dispatch = () => {
|
|
142
|
+
if (!data.length) return;
|
|
143
|
+
const payload = data.join("\n"); data = [];
|
|
144
|
+
if (payload === "[DONE]") return;
|
|
145
|
+
let event: any;
|
|
146
|
+
try { event = JSON.parse(payload); } catch { throw new Error("Invalid Codex image generation stream."); }
|
|
147
|
+
if (event.type === "response.output_item.done") capture(event.item);
|
|
148
|
+
if (event.type === "response.completed") {
|
|
149
|
+
if (event.response?.status !== "completed") throw new Error("Codex image generation did not complete.");
|
|
150
|
+
for (const item of event.response.output ?? []) capture(item);
|
|
151
|
+
completed = true;
|
|
152
|
+
} else if (["response.failed", "response.incomplete", "error"].includes(event.type)) {
|
|
153
|
+
throw new Error("Codex image generation failed or was incomplete. It was not automatically retried.");
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
const consume = (text: string) => {
|
|
157
|
+
buffer += text;
|
|
158
|
+
let newline: number;
|
|
159
|
+
while ((newline = buffer.indexOf("\n")) !== -1) {
|
|
160
|
+
const line = buffer.slice(0, newline).replace(/\r$/, ""); buffer = buffer.slice(newline + 1);
|
|
161
|
+
if (!line) dispatch();
|
|
162
|
+
else if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, ""));
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
try {
|
|
166
|
+
while (!completed) {
|
|
167
|
+
requestSignal.throwIfAborted();
|
|
168
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
169
|
+
const onAbort = () => { void reader.cancel().catch(() => {}); };
|
|
170
|
+
requestSignal.addEventListener("abort", onAbort, { once: true });
|
|
171
|
+
try {
|
|
172
|
+
const part = await Promise.race([reader.read(), new Promise<never>((_, reject) => {
|
|
173
|
+
timer = setTimeout(() => { reject(new Error("Codex image generation stream timed out.")); void reader.cancel().catch(() => {}); }, options.idleMs ?? 90_000);
|
|
174
|
+
})]);
|
|
175
|
+
requestSignal.throwIfAborted();
|
|
176
|
+
if (part.done) { consume(decoder.decode() + "\n\n"); break; }
|
|
177
|
+
responseBytes += part.value.byteLength;
|
|
178
|
+
if (responseBytes > Math.min(options.maxResponseBytes ?? IMAGE_RESPONSE_MAX_BYTES, IMAGE_RESPONSE_MAX_BYTES)) throw new Error("Codex image generation response exceeds its byte limit.");
|
|
179
|
+
consume(decoder.decode(part.value, { stream: true }));
|
|
180
|
+
} finally { if (timer) clearTimeout(timer); requestSignal.removeEventListener("abort", onAbort); }
|
|
181
|
+
}
|
|
182
|
+
requestSignal.throwIfAborted();
|
|
183
|
+
if (!completed || images.size !== 1) throw new Error("Codex stream ended without a completed image. It was not automatically retried.");
|
|
184
|
+
return { ...images.values().next().value!, requestBytes, responseBytes };
|
|
185
|
+
} finally { void reader.cancel().catch(() => {}); try { reader.releaseLock(); } catch {} }
|
|
186
|
+
}
|
|
@@ -7,6 +7,7 @@ import { canonicalizeJsonSchema, zodToJsonSchema } from "../../tools/schema.js";
|
|
|
7
7
|
import { ProviderRequest } from "../provider-request.js";
|
|
8
8
|
import { getStreamIdleMs, withStreamIdleTimeout } from "../stream-idle.js";
|
|
9
9
|
import { OpenAICompatibleProvider, type OpenAICompatibleProviderOptions } from "./openai-compatible.js";
|
|
10
|
+
import { modelReasoningFor, resolveModelEffort, type ModelReasoning } from "../reasoning-effort.js";
|
|
10
11
|
import { stripBoundary } from "../prompt-boundary.js";
|
|
11
12
|
|
|
12
13
|
export const CODEX_RESPONSES_BASE_URL = "https://chatgpt.com/backend-api/codex";
|
|
@@ -15,6 +16,8 @@ export interface OpenAIResponsesProviderOptions extends OpenAICompatibleProvider
|
|
|
15
16
|
codex?: {
|
|
16
17
|
getCredentials: (signal?: AbortSignal) => Promise<{ accessToken: string; accountId?: string }>;
|
|
17
18
|
fetch?: typeof globalThis.fetch;
|
|
19
|
+
reasoningByModel?: Record<string, ModelReasoning>;
|
|
20
|
+
effortByModel?: Record<string, string | null>;
|
|
18
21
|
};
|
|
19
22
|
}
|
|
20
23
|
type LayoutItem =
|
|
@@ -128,6 +131,15 @@ export class OpenAIResponsesProvider implements LLMProvider {
|
|
|
128
131
|
stream,
|
|
129
132
|
} as ResponseCreateParams;
|
|
130
133
|
if (this.options.codex) {
|
|
134
|
+
const { reasoningByModel, effortByModel } = this.options.codex;
|
|
135
|
+
const model = body.model ?? "";
|
|
136
|
+
const reasoning = { ...body.reasoning };
|
|
137
|
+
const value = Object.hasOwn(effortByModel ?? {}, model) ? effortByModel![model] : reasoning.effort;
|
|
138
|
+
const effort = resolveModelEffort(modelReasoningFor(reasoningByModel, model), value);
|
|
139
|
+
if (effort === undefined) delete reasoning.effort;
|
|
140
|
+
else reasoning.effort = effort as typeof reasoning.effort;
|
|
141
|
+
if (Object.keys(reasoning).length) body.reasoning = reasoning;
|
|
142
|
+
else delete body.reasoning;
|
|
131
143
|
let leadingSystemEnd = 0;
|
|
132
144
|
while (messages[leadingSystemEnd]?.role === "system") leadingSystemEnd++;
|
|
133
145
|
body.instructions = messages.slice(0, leadingSystemEnd).map(message => stripBoundary(message.content)).join("\n\n");
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/** Account-advertised capabilities for an exact request model ID. */
|
|
2
|
+
export interface ModelReasoning {
|
|
3
|
+
levels: Array<{ effort: string; description?: string }>;
|
|
4
|
+
defaultEffort?: string;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function effortName(value: unknown): value is string {
|
|
8
|
+
return typeof value === "string" && /^[a-zA-Z0-9_-]{1,64}$/.test(value);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Missing/malformed is unknown; an explicit empty array means no override. */
|
|
12
|
+
export function normalizeModelReasoning(levels: unknown, defaultEffort?: unknown): ModelReasoning | undefined {
|
|
13
|
+
if (!Array.isArray(levels)) return undefined;
|
|
14
|
+
const result: ModelReasoning = { levels: [] };
|
|
15
|
+
const seen = new Set<string>();
|
|
16
|
+
for (const level of levels) {
|
|
17
|
+
if (!level || typeof level !== "object" || !effortName(level.effort)) return undefined;
|
|
18
|
+
const key = level.effort.toLowerCase();
|
|
19
|
+
if (seen.has(key)) continue;
|
|
20
|
+
seen.add(key);
|
|
21
|
+
const description = typeof level.description === "string"
|
|
22
|
+
? level.description.replace(/[\x00-\x1f\x7f-\x9f]/g, " ").slice(0, 256) : undefined;
|
|
23
|
+
result.levels.push({ effort: level.effort, ...(description ? { description } : {}) });
|
|
24
|
+
}
|
|
25
|
+
const canonical = typeof defaultEffort === "string"
|
|
26
|
+
? result.levels.find(level => level.effort.toLowerCase() === defaultEffort.toLowerCase())?.effort : undefined;
|
|
27
|
+
if (canonical) result.defaultEffort = canonical;
|
|
28
|
+
return result;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function resolveModelEffort(profile: ModelReasoning | undefined, value: unknown): string | undefined {
|
|
32
|
+
if (typeof value !== "string") return undefined;
|
|
33
|
+
return profile ? profile.levels.find(level => level.effort.toLowerCase() === value.toLowerCase())?.effort : value;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function normalizeReasoningMap(value: unknown): Record<string, ModelReasoning> | undefined {
|
|
37
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
38
|
+
const entries = Object.entries(value).flatMap(([model, raw]) => {
|
|
39
|
+
if (!model || model.length > 256 || /[\x00-\x1f\x7f]/.test(model) || !raw || typeof raw !== "object") return [];
|
|
40
|
+
const profile = normalizeModelReasoning(raw.levels, raw.defaultEffort);
|
|
41
|
+
return profile ? [[model, profile]] : [];
|
|
42
|
+
});
|
|
43
|
+
return entries.length ? Object.fromEntries(entries) : undefined;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function modelReasoningFor(profiles: Record<string, ModelReasoning> | undefined, model: string): ModelReasoning | undefined {
|
|
47
|
+
return profiles && Object.hasOwn(profiles, model) ? profiles[model] : undefined;
|
|
48
|
+
}
|
package/zapsdk/index.ts
CHANGED
|
@@ -12,6 +12,9 @@ export { type LLMProvider, type LLMCallOptions, type ProviderRequestEvent } from
|
|
|
12
12
|
export { ProviderRequestTimeoutError } from "./core/provider-request.js";
|
|
13
13
|
export { AnthropicProvider, type AnthropicProviderOptions } from "./core/providers/anthropic.js";
|
|
14
14
|
export { ContextOverflowError } from "./core/errors.js";
|
|
15
|
+
export { generateCodexImage, type CodexImageOptions, type GeneratedImage, type ImageGenerationRequest } from "./core/providers/codex-image-generation.js";
|
|
16
|
+
export { generateImageTool, type GenerateImageOptions } from "./builtin-tools/generate-image.js";
|
|
17
|
+
export { type GeneratedImageArtifact, type GeneratedImageMeta } from "./utils/generated-image.js";
|
|
15
18
|
export { OpenAIResponsesProvider, type OpenAIResponsesProviderOptions } from "./core/providers/openai-responses.js";
|
|
16
19
|
export { OpenAICompatibleProvider, type OpenAICompatibleProviderOptions } from "./core/providers/openai-compatible.js";
|
|
17
20
|
export { RetryProvider, type RetryOptions, type CallOptions } from "./core/retry.js";
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from "node:fs";
|
|
3
|
+
import { mkdir } from "node:fs/promises";
|
|
4
|
+
import { atomicWrite } from "../builtin-tools/filesystem.js";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { Resvg } from "@resvg/resvg-js";
|
|
7
|
+
import { IMAGE_MAX_BYTES, validateGeneratedPng, type GeneratedImage } from "../core/providers/codex-image-generation.js";
|
|
8
|
+
|
|
9
|
+
export interface GeneratedImageArtifact {
|
|
10
|
+
id: string;
|
|
11
|
+
filePath?: string;
|
|
12
|
+
cachePath?: string;
|
|
13
|
+
mediaType: "image/png";
|
|
14
|
+
width: number;
|
|
15
|
+
height: number;
|
|
16
|
+
bytes: number;
|
|
17
|
+
/** Small RGB thumbnail, never provider-controlled terminal escape sequences. */
|
|
18
|
+
thumbnail?: { width: number; height: number; rgb: string };
|
|
19
|
+
}
|
|
20
|
+
export interface GeneratedImageMeta {
|
|
21
|
+
generatedImage: GeneratedImageArtifact;
|
|
22
|
+
providerRequest: { requestBytes: number; responseBytes: number };
|
|
23
|
+
}
|
|
24
|
+
const hash = (bytes: Buffer) => createHash("sha256").update(bytes).digest("hex");
|
|
25
|
+
|
|
26
|
+
export function generatedImageArtifact(meta: unknown): GeneratedImageArtifact | undefined {
|
|
27
|
+
const image = (meta as GeneratedImageMeta | undefined)?.generatedImage;
|
|
28
|
+
if (!image || typeof image.id !== "string" || !/^[a-f0-9]{64}$/.test(image.id) || image.mediaType !== "image/png" || !Number.isSafeInteger(image.bytes)
|
|
29
|
+
|| image.bytes < 32 || image.bytes > IMAGE_MAX_BYTES || !Number.isSafeInteger(image.width) || !Number.isSafeInteger(image.height)
|
|
30
|
+
|| image.width < 1 || image.height < 1 || image.width > 4096 || image.height > 4096) return;
|
|
31
|
+
return { id: image.id, mediaType: "image/png", width: image.width, height: image.height, bytes: image.bytes,
|
|
32
|
+
...(typeof image.filePath === "string" && image.filePath.length <= 4096 && !/[\x00-\x1f\x7f]/.test(image.filePath) ? { filePath: image.filePath } : {}),
|
|
33
|
+
...(typeof image.cachePath === "string" && image.cachePath.length <= 4096 && !/[\x00-\x1f\x7f]/.test(image.cachePath) ? { cachePath: image.cachePath } : {}),
|
|
34
|
+
...(image.thumbnail ? { thumbnail: image.thumbnail } : {}) };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function generatedImageThumbnail(bytes: Buffer): GeneratedImageArtifact["thumbnail"] {
|
|
38
|
+
const { width, height } = validateGeneratedPng(bytes);
|
|
39
|
+
const w = 32, h = Math.max(2, Math.min(32, Math.round(w * height / width)));
|
|
40
|
+
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}"><rect width="100%" height="100%" fill="white"/><image href="data:image/png;base64,${bytes.toString("base64")}" width="${w}" height="${h}"/></svg>`;
|
|
41
|
+
const rendered = new Resvg(svg, { font: { loadSystemFonts: false } }).render();
|
|
42
|
+
const rgba = rendered.pixels, rgb = Buffer.alloc(w * h * 3);
|
|
43
|
+
for (let i = 0; i < w * h; i++) rgba.copy(rgb, i * 3, i * 4, i * 4 + 3);
|
|
44
|
+
return { width: w, height: h, rgb: rgb.toString("hex") };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Runtime-owned artifact storage is separate from model-chosen workspace writes.
|
|
48
|
+
* A cache key is always a digest; restore never reads an arbitrary metadata path. */
|
|
49
|
+
export async function cacheGeneratedImage(directory: string, image: GeneratedImage): Promise<GeneratedImageArtifact> {
|
|
50
|
+
const dimensions = validateGeneratedPng(image.bytes);
|
|
51
|
+
const thumbnail = generatedImageThumbnail(image.bytes); // Decode/validate before publishing.
|
|
52
|
+
const id = hash(image.bytes), path = join(directory, `${id}.png`);
|
|
53
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
54
|
+
try { await atomicWrite(path, image.bytes, { replaceExisting: false, mode: 0o600 }); }
|
|
55
|
+
catch (error) {
|
|
56
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
57
|
+
const existing = restoreGeneratedImage(directory, { generatedImage: { id, mediaType: "image/png", ...dimensions, bytes: image.bytes.length } });
|
|
58
|
+
if (!existing?.equals(image.bytes)) throw new Error("Generated image artifact cache collision.");
|
|
59
|
+
}
|
|
60
|
+
return { id, cachePath: path, mediaType: "image/png", ...dimensions, bytes: image.bytes.length, thumbnail };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function restoreGeneratedImage(directory: string, meta: unknown): Buffer | undefined {
|
|
64
|
+
const image = generatedImageArtifact(meta);
|
|
65
|
+
if (!image) return;
|
|
66
|
+
let fd: number | undefined;
|
|
67
|
+
try {
|
|
68
|
+
if (lstatSync(join(directory, `${image.id}.png`)).isSymbolicLink()) return;
|
|
69
|
+
fd = openSync(join(directory, `${image.id}.png`), constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
70
|
+
const stat = fstatSync(fd);
|
|
71
|
+
if (!stat.isFile() || stat.size !== image.bytes || stat.size > IMAGE_MAX_BYTES) return;
|
|
72
|
+
const bytes = Buffer.alloc(image.bytes);
|
|
73
|
+
let offset = 0;
|
|
74
|
+
while (offset < bytes.length) {
|
|
75
|
+
const count = readSync(fd, bytes, offset, bytes.length - offset, offset);
|
|
76
|
+
if (!count) return;
|
|
77
|
+
offset += count;
|
|
78
|
+
}
|
|
79
|
+
if (fstatSync(fd).size !== image.bytes) return;
|
|
80
|
+
const size = validateGeneratedPng(bytes);
|
|
81
|
+
if (hash(bytes) !== image.id || size.width !== image.width || size.height !== image.height) return;
|
|
82
|
+
return bytes;
|
|
83
|
+
} catch { return; } finally { if (fd !== undefined) closeSync(fd); }
|
|
84
|
+
}
|