@ai-agent-forge/plugin-image-generation 0.88.28 → 0.88.29
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/PLUGIN.md +20 -0
- package/README.md +29 -23
- package/agent-forge.json +1 -1
- package/dist/capability.d.ts +4 -4
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +127 -180
- package/dist/capability.js.map +1 -1
- package/dist/images-client.d.ts.map +1 -1
- package/dist/images-client.js +3 -1
- package/dist/images-client.js.map +1 -1
- package/dist/types.d.ts +14 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +4 -4
- package/plugin.json +2 -3
- package/MANUAL.md +0 -15
package/PLUGIN.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: "Image generation: generate an image from a prompt or edit an existing image with the session-selected image model. Use when an image must be generated or modified and a target is selected; do not use when the main model can already view images. Fails when no target is selected."
|
|
3
|
+
title: "agent-forge.plugin.image-generation"
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# image-generation capability manual
|
|
7
|
+
|
|
8
|
+
`image_generate` generates an image from a prompt; `image_edit` edits an input image using instructions.
|
|
9
|
+
|
|
10
|
+
## Model selection
|
|
11
|
+
|
|
12
|
+
The session's `generate_image` selection (`/model` → image generation) is the only target source: tool parameters, settings slots, and environment variables cannot specify its provider or model. When no target is selected the tools fail with `config_missing` and the message asks the user to choose one in `/model`. Credentials come from the host's auth.json; the provider must have apiKey/baseUrl configured. A structured credentials error means the user should run `/login` or complete configuration; do not retry blindly.
|
|
13
|
+
|
|
14
|
+
## Usage
|
|
15
|
+
|
|
16
|
+
1. Describe subject, style, and composition in the prompt. For editing, provide an explicit input image path and editing instructions.
|
|
17
|
+
2. Results are files; tell the user the output path from the tool result instead of pasting base64 into the conversation.
|
|
18
|
+
3. If no image target is selected, ask the user to choose one in `/model` and relay the actual error.
|
|
19
|
+
4. Image downloads use standard proxy environment variables (`HTTPS_PROXY`/`HTTP_PROXY`), as curl does. If a provider's image URL cannot be reached directly, start agent-forge with proxy environment variables or image_generate will fail during download. As a workaround bash with a proxy may retrieve `b64_json`; report that the tool itself failed.
|
|
20
|
+
5. `image_edit` selects protocol by model ID: `grok-imagine-image` and `grok-imagine-image-*` use JSON data URLs; other models use multipart. Endpoint and credentials still come from the host provider configuration.
|
package/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# @agent-forge/plugin-image-generation
|
|
2
2
|
|
|
3
3
|
First-party image generation capability plugin for Agent Forge. Registers the
|
|
4
|
-
`image_generate` and `image_edit` tools
|
|
4
|
+
`image_generate` and `image_edit` tools against the
|
|
5
5
|
host-configured provider's image endpoint (OpenAI-compatible request shapes
|
|
6
6
|
by default, with a Grok Imagine edit adapter):
|
|
7
7
|
|
|
@@ -12,14 +12,28 @@ by default, with a Grok Imagine edit adapter):
|
|
|
12
12
|
target (`/model` capability menu); the call cannot override them. The first
|
|
13
13
|
adapter is `openai-images`.
|
|
14
14
|
- `capabilityConfig.generate_image.options` may provide default `size`, `quality` and `n`; explicit tool parameters win.
|
|
15
|
-
- Hosts without a capability-selection service
|
|
16
|
-
|
|
17
|
-
the session selection exclusively.
|
|
15
|
+
- Hosts without a capability-selection service do not register the tools: there
|
|
16
|
+
is no fallback target source.
|
|
18
17
|
- Generated and edited image files are written under the workspace
|
|
19
18
|
`generated-images/` directory, named and typed by their actual format
|
|
20
19
|
(magic-byte sniff: png/jpg/webp/gif; unknown falls back to png); the tool
|
|
21
20
|
result returns their workspace-relative paths only (see "Images never ride
|
|
22
21
|
the conversation" below) — the model reads a returned file to view it.
|
|
22
|
+
- A provider response without image entries produces a failed result with
|
|
23
|
+
`image_response_empty`; neither generation nor editing reports success or
|
|
24
|
+
creates a new image file for that response.
|
|
25
|
+
- If a response mixes recognized images and unrecognized entries, the tool
|
|
26
|
+
saves the recognized images and returns `status: "partial"` with the count
|
|
27
|
+
and reason for the unrecognized entries. If all returned entries are
|
|
28
|
+
unrecognized, the result fails and reports their count. A response with fewer entries than the
|
|
29
|
+
requested `n` alone is not treated as an unrecognized entry.
|
|
30
|
+
- If writing an image fails, the error result identifies every image whose
|
|
31
|
+
write completed and includes the original write error. The failed attempt's
|
|
32
|
+
path is reported as unknown: it may not exist, may be incomplete, or may have
|
|
33
|
+
changed concurrently; the tool does not delete it. If a cancellation signal
|
|
34
|
+
and a write error coincide, both facts remain visible in the error result.
|
|
35
|
+
When the original error exceeds the error-message budget, the shortened
|
|
36
|
+
message is accompanied by `messageTruncated: true`.
|
|
23
37
|
- Cancellation cascades through `api.sessionAbortSignal()` and the invocation
|
|
24
38
|
signal; requests time out after 180s and error messages never echo the API
|
|
25
39
|
key or request headers.
|
|
@@ -36,17 +50,11 @@ by default, with a Grok Imagine edit adapter):
|
|
|
36
50
|
|
|
37
51
|
## Configuring an image provider
|
|
38
52
|
|
|
39
|
-
Register the model in `models.json`, then select it in `/model` →
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
{
|
|
45
|
-
"capabilities": {
|
|
46
|
-
"imageGeneration": { "provider": "myimg", "model": "gpt-image-1" }
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
```
|
|
53
|
+
Register the model in `models.json`, then select it in `/model` → 生图. The
|
|
54
|
+
session selection is the only target source; there is no settings slot, no
|
|
55
|
+
environment variable, and no tool-parameter override. For a cross-session
|
|
56
|
+
default, set `settings.defaultCapabilities.generate_image` (or press Ctrl+S on
|
|
57
|
+
the model in `/model`).
|
|
50
58
|
|
|
51
59
|
`models.json` registers the provider and its image model (`capabilities`
|
|
52
60
|
marks image-capable models; the adapter selects the image protocol):
|
|
@@ -80,14 +88,12 @@ through the host's credential API: the stored key lives in `auth.json`, and
|
|
|
80
88
|
`models.json` is not a key source — `--api-key`/runtime-injected and
|
|
81
89
|
provider-registered keys are resolved too.
|
|
82
90
|
|
|
83
|
-
With only the `models.json` registration
|
|
84
|
-
|
|
85
|
-
Registering an image model in `models.json` implies
|
|
86
|
-
an `/images/generations` endpoint; chat models never
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
`api.config.imageModelCatalog` snapshot) — the plugin never reads host
|
|
90
|
-
settings files itself.
|
|
91
|
+
With only the `models.json` registration, nothing happens until a target is
|
|
92
|
+
selected — image generation never guesses a provider from the main model or
|
|
93
|
+
from the model catalog. Registering an image model in `models.json` implies
|
|
94
|
+
that provider really has an `/images/generations` endpoint; chat models never
|
|
95
|
+
take part. The plugin reads the selected target through the public
|
|
96
|
+
`api.selection` host service and never reads host settings files itself.
|
|
91
97
|
|
|
92
98
|
## Proxy support
|
|
93
99
|
|
package/agent-forge.json
CHANGED
package/dist/capability.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import type { CapabilityPluginSyncFactory } from "@agent-forge/plugin-sdk";
|
|
2
2
|
/**
|
|
3
|
-
* Registers the
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
3
|
+
* Registers the `image_generate` and `image_edit` tools. The factory takes no
|
|
4
|
+
* credentials: provider auth (`apiKey` + `baseUrl`) is resolved at call time
|
|
5
|
+
* through the host's public `CredentialAPI`. The optional `fetchImpl` is a
|
|
6
|
+
* test seam only; production hosts use global fetch.
|
|
7
7
|
*/
|
|
8
8
|
export declare function createImageGenerationCapabilityFactoryV1(options?: {
|
|
9
9
|
readonly fetchImpl?: typeof fetch;
|
package/dist/capability.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"capability.d.ts","sourceRoot":"","sources":["../src/capability.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAiB,2BAA2B,EAAgB,MAAM,yBAAyB,CAAC;AA+dxG;;;;;GAKG;AACH,wBAAgB,wCAAwC,CAAC,OAAO,CAAC,EAAE;IAClE,QAAQ,CAAC,SAAS,CAAC,EAAE,OAAO,KAAK,CAAC;CAClC,GAAG,2BAA2B,CA2M9B","sourcesContent":["import { mkdir, readFile, realpath, stat, writeFile } from \"node:fs/promises\";\nimport { join, sep } from \"node:path\";\nimport type { CapabilityAPI, CapabilityPluginSyncFactory, PluginConfig } from \"@agent-forge/plugin-sdk\";\nimport { Type } from \"typebox\";\nimport { wrapFetchWithEnvProxyV1 } from \"./env-proxy-fetch.ts\";\nimport { createImagesClientV1 } from \"./images-client.ts\";\nimport {\n\tboundedImageMessageV1,\n\tdetectImageFormatV1,\n\tIMAGE_GENERATION_DOWNLOAD_TIMEOUT_MS_V1,\n\tIMAGE_GENERATION_MAX_DOWNLOAD_BYTES_V1,\n\ttype ImageFormatV1,\n\ttype ImageGenResultV1,\n\ttype ImagesClientResponseV1,\n} from \"./types.ts\";\n\nconst IMAGE_GENERATE_PARAMETERS = Type.Object(\n\t{\n\t\tprompt: Type.String({ minLength: 1, maxLength: 4000 }),\n\t\tsize: Type.Optional(Type.String({ minLength: 1, maxLength: 32 })),\n\t\tquality: Type.Optional(Type.String({ minLength: 1, maxLength: 32 })),\n\t\tn: Type.Optional(Type.Integer({ minimum: 1, maximum: 4 })),\n\t},\n\t{ additionalProperties: false },\n);\n\nconst IMAGE_EDIT_PARAMETERS = Type.Object(\n\t{\n\t\timagePath: Type.String({ minLength: 1, maxLength: 512, pattern: \"^[A-Za-z0-9_][A-Za-z0-9._/-]*$\" }),\n\t\tprompt: Type.String({ minLength: 1, maxLength: 4000 }),\n\t},\n\t{ additionalProperties: false },\n);\n\nconst IMAGE_PATH_PATTERN_V1 = /^[A-Za-z0-9_][A-Za-z0-9._/-]*$/u;\n\nconst GENERATED_IMAGES_DIRECTORY = \"generated-images\";\n\ninterface ImageFailureV1 {\n\treadonly code: string;\n\treadonly message: string;\n}\n\nfunction objectInput(first: unknown, second: unknown): Record<string, unknown> {\n\t// Shape-based dual-convention read (aligned with subagent-delegate): the\n\t// runtime invoke face passes the input object first and the host\n\t// CapabilityToolContext second; the agent tool face passes the tool call\n\t// id (a string) first and the params object second.\n\tconst value = first !== null && typeof first === \"object\" && !Array.isArray(first) ? first : second;\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value))\n\t\tthrow new Error(\"Image generation input must be an object\");\n\treturn value as Record<string, unknown>;\n}\n\nfunction signalFrom(value: unknown): AbortSignal | undefined {\n\treturn value instanceof AbortSignal ? value : undefined;\n}\n\nfunction combineSignals(signals: readonly (AbortSignal | undefined)[]): AbortSignal | undefined {\n\tconst present = signals.filter((signal): signal is AbortSignal => signal !== undefined);\n\tif (present.length === 0) return undefined;\n\tif (present.length === 1) return present[0];\n\treturn AbortSignal.any(present);\n}\n\nfunction failed(model: string, code: string, message: string): ImageGenResultV1 {\n\treturn {\n\t\tversion: 1,\n\t\tstatus: \"failed\",\n\t\tfiles: [],\n\t\tmodel,\n\t\terror: { code, message: boundedImageMessageV1(message) },\n\t};\n}\n\nfunction cancelled(model: string): ImageGenResultV1 {\n\treturn {\n\t\tversion: 1,\n\t\tstatus: \"cancelled\",\n\t\tfiles: [],\n\t\tmodel,\n\t\terror: { code: \"cancelled\", message: \"Image generation was cancelled\" },\n\t};\n}\n\n/** `param` (non-empty string), a non-empty env value, or undefined. */\nfunction nonEmptyEnvValue(name: string): string | undefined {\n\tconst value = process.env[name];\n\treturn typeof value === \"string\" && value.trim() !== \"\" ? value : undefined;\n}\n\nfunction boundedString(value: unknown, maxLength: number): string | undefined {\n\treturn typeof value === \"string\" && value !== \"\" && value.length <= maxLength ? value : undefined;\n}\n\n/** settings 槽位形状(宿主经 configOverride 注入,设计 §3.1/§3.3)。 */\ninterface ImageGenerationSlotV1 {\n\treadonly provider: string;\n\treadonly model?: string;\n}\n\n/** 目录快照条目:宿主装配期从 models.json 登记项投影(设计 §3.2 推断供料)。 */\ninterface CatalogModelV1 {\n\treadonly id: string;\n\treadonly name?: string;\n}\n\ntype ImageModelCatalogV1 = Readonly<Record<string, ReadonlyArray<CatalogModelV1>>>;\n\nfunction readInjectedSlot(config: PluginConfig): { readonly slot?: ImageGenerationSlotV1; readonly error?: string } {\n\tconst raw = config.imageGeneration;\n\tif (raw === undefined) return {};\n\tif (typeof raw !== \"object\" || raw === null || Array.isArray(raw))\n\t\treturn { error: \"injected config imageGeneration must be an object\" };\n\tconst record = raw as Record<string, unknown>;\n\tif (typeof record.provider !== \"string\" || record.provider.trim() === \"\")\n\t\treturn {\n\t\t\terror: `injected config imageGeneration.provider must be a non-empty string (got ${typeof record.provider})`,\n\t\t};\n\tif (record.model !== undefined && (typeof record.model !== \"string\" || record.model.trim() === \"\"))\n\t\treturn { error: \"injected config imageGeneration.model must be a non-empty string when present\" };\n\treturn { slot: { provider: record.provider, ...(record.model === undefined ? {} : { model: record.model }) } };\n}\n\nfunction readInjectedCatalog(config: PluginConfig): { readonly catalog: ImageModelCatalogV1; readonly error?: string } {\n\tconst raw = config.imageModelCatalog;\n\tif (raw === undefined) return { catalog: {} };\n\tif (typeof raw !== \"object\" || raw === null || Array.isArray(raw))\n\t\treturn {\n\t\t\tcatalog: {},\n\t\t\terror: \"injected config imageModelCatalog must be an object mapping providers to image models\",\n\t\t};\n\tconst catalog: Record<string, Array<{ id: string; name?: string }>> = {};\n\tfor (const [providerId, entries] of Object.entries(raw as Record<string, unknown>)) {\n\t\tif (!Array.isArray(entries))\n\t\t\treturn { catalog: {}, error: `injected config imageModelCatalog[\"${providerId}\"] must be an array` };\n\t\tconst models: Array<{ id: string; name?: string }> = [];\n\t\tfor (const entry of entries) {\n\t\t\tif (typeof entry !== \"object\" || entry === null)\n\t\t\t\treturn { catalog: {}, error: `injected config imageModelCatalog[\"${providerId}\"] entries must be objects` };\n\t\t\tconst record = entry as Record<string, unknown>;\n\t\t\tif (typeof record.id !== \"string\" || record.id === \"\")\n\t\t\t\treturn {\n\t\t\t\t\tcatalog: {},\n\t\t\t\t\terror: `injected config imageModelCatalog[\"${providerId}\"] entries need a non-empty string id`,\n\t\t\t\t};\n\t\t\tmodels.push({ id: record.id, ...(typeof record.name === \"string\" ? { name: record.name } : {}) });\n\t\t}\n\t\tif (models.length > 0) catalog[providerId] = models;\n\t}\n\treturn { catalog };\n}\n\n/** 确定性排序键:name 优先(缺省回退 id),同键按 id;码点序,与宿主快照顺序无关。 */\nfunction compareCatalogModels(left: CatalogModelV1, right: CatalogModelV1): number {\n\tconst leftKey = left.name ?? left.id;\n\tconst rightKey = right.name ?? right.id;\n\tif (leftKey !== rightKey) return leftKey < rightKey ? -1 : 1;\n\treturn left.id < right.id ? -1 : left.id > right.id ? 1 : 0;\n}\n\ntype ImageTargetResolution =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\treadonly provider: string;\n\t\t\treadonly model: string;\n\t\t\treadonly baseUrl?: string;\n\t\t\treadonly options?: Readonly<Record<string, unknown>>;\n\t\t\treadonly modelSourceNote?: string;\n\t }\n\t| { readonly ok: false; readonly message: string };\n\nconst IMAGE_GENERATION_CONFIG_EXAMPLE =\n\t'Example settings.json: { \"capabilities\": { \"imageGeneration\": { \"provider\": \"myimg\", \"model\": \"gpt-image-1\" } } }';\n\n/**\n * 六层取值链(供应商能力槽位设计 §3.2):\n * 1. 工具参数 provider/model;\n * 2. settings 槽位(宿主注入的 config.imageGeneration,model 可省);\n * 3. env AGENT_FORGE_IMAGEGEN_PROVIDER/MODEL(存量兼容);\n * 4. 主供应商推断——会话当前 provider 在目录快照中登记过生图模型时取用;\n * 5. 唯一候选推断——全配置域恰好一个 provider 登记过生图模型(且非当前主)时取用;\n * 6. fail-closed——config_missing,多候选时列出候选清单。\n * model 在 1-3 层均未命中时按已解析 provider 的登记生图模型推断(唯一命中直接\n * 用;多命中确定性排序取第一个并注明来源)。\n */\nfunction resolveImageTarget(\n\tinput: Record<string, unknown>,\n\tslot: ImageGenerationSlotV1 | undefined,\n\tcatalog: ImageModelCatalogV1,\n\tsessionProvider: string | undefined,\n): ImageTargetResolution {\n\tconst paramProvider = boundedString(input.provider, 64);\n\tconst paramModel = boundedString(input.model, 128);\n\tconst envProvider = nonEmptyEnvValue(\"AGENT_FORGE_IMAGEGEN_PROVIDER\");\n\tconst envModel = nonEmptyEnvValue(\"AGENT_FORGE_IMAGEGEN_MODEL\");\n\n\tlet provider = paramProvider ?? slot?.provider ?? envProvider;\n\tif (provider === undefined) {\n\t\tif (sessionProvider !== undefined && (catalog[sessionProvider]?.length ?? 0) > 0) provider = sessionProvider;\n\t\telse {\n\t\t\tconst candidates = Object.keys(catalog)\n\t\t\t\t.filter((providerId) => catalog[providerId].length > 0)\n\t\t\t\t.sort();\n\t\t\tif (candidates.length === 1) provider = candidates[0];\n\t\t\telse if (candidates.length > 1)\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t`Multiple image-generation providers are registered in models.json (${candidates.join(\", \")}); image generation fails closed instead of guessing. ` +\n\t\t\t\t\t\t`Configure capabilities.imageGeneration in settings.json or pass the provider parameter. ${IMAGE_GENERATION_CONFIG_EXAMPLE}`,\n\t\t\t\t};\n\t\t\telse\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t\"Image generation is not configured: pass provider and model via the tool parameters, set capabilities.imageGeneration in settings.json, \" +\n\t\t\t\t\t\t'set AGENT_FORGE_IMAGEGEN_PROVIDER and AGENT_FORGE_IMAGEGEN_MODEL, or register a model with \"capabilities\": [\"generate_image\"] for a provider in models.json. ' +\n\t\t\t\t\t\tIMAGE_GENERATION_CONFIG_EXAMPLE,\n\t\t\t\t};\n\t\t}\n\t}\n\n\tlet model = paramModel ?? slot?.model ?? envModel;\n\tlet modelSourceNote: string | undefined;\n\tif (model === undefined) {\n\t\tconst registered = catalog[provider] ?? [];\n\t\tif (registered.length === 1) model = registered[0].id;\n\t\telse if (registered.length > 1) {\n\t\t\tconst first = [...registered].sort(compareCatalogModels)[0];\n\t\t\tmodel = first.id;\n\t\t\tmodelSourceNote =\n\t\t\t\t`model ${first.id} was picked deterministically (first by name) from ${registered.length} image models registered for provider ${provider} in models.json; ` +\n\t\t\t\t\"pass an explicit model to choose another\";\n\t\t} else\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tmessage:\n\t\t\t\t\t`No image model is configured for provider ${provider}: no model came from the tool parameters, settings, or env, ` +\n\t\t\t\t\t`and provider ${provider} has no models.json model with \"capabilities\": [\"generate_image\"]. Register one or pass an explicit model. ${IMAGE_GENERATION_CONFIG_EXAMPLE}`,\n\t\t\t};\n\t}\n\treturn { ok: true, provider, model, ...(modelSourceNote === undefined ? {} : { modelSourceNote }) };\n}\n\nfunction promptFrom(value: unknown): string | undefined {\n\treturn boundedString(value, 4000);\n}\n\nfunction countFrom(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isSafeInteger(value) && value >= 1 && value <= 4 ? value : undefined;\n}\n\n/** Workspace-relative identifier confined to the generated-images directory. */\nfunction validImagePath(imagePath: string): boolean {\n\tif (!IMAGE_PATH_PATTERN_V1.test(imagePath)) return false;\n\tif (!imagePath.startsWith(`${GENERATED_IMAGES_DIRECTORY}/`)) return false;\n\treturn !imagePath.split(\"/\").includes(\"..\");\n}\n\n/**\n * image_edit ships workspace bytes to an external image provider, so the\n * lexical validImagePath gate is not enough: a symlink inside\n * generated-images/ can point anywhere on disk. Same sandbox model as the\n * workspace-files-write host: resolve the workspace root and the candidate to\n * their real paths and require the candidate to stay inside the real root.\n * A missing file (or dangling link) fails realpath and maps to the regular\n * not-found outcome; a link resolving outside the workspace is a boundary\n * escape and is refused. Links that stay inside the workspace keep working —\n * their bytes never leave the sandbox boundary.\n */\nasync function sandboxedImagePath(workspace: string, imagePath: string): Promise<\"missing\" | \"escape\" | \"ok\"> {\n\tconst root = await realpath(workspace).catch(() => undefined);\n\tif (root === undefined) return \"missing\";\n\tconst real = await realpath(join(workspace, imagePath)).catch(() => undefined);\n\tif (real === undefined) return \"missing\";\n\tif (real !== root && !real.startsWith(root + sep)) return \"escape\";\n\treturn \"ok\";\n}\n\n/**\n * Local-time `yyyymmdd-HHmmss` stamp shared by every file of one invocation.\n * Local (not UTC): users find today's images by the date in the filename, and\n * on UTC+8 machines a UTC stamp labels evening images as \"tomorrow\". Sorting\n * stays monotonic wherever local time has no DST jumps (e.g. China).\n */\nfunction localStampV1(date: Date): string {\n\tconst pad = (value: number): string => String(value).padStart(2, \"0\");\n\treturn `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(\n\t\tdate.getHours(),\n\t)}${pad(date.getMinutes())}${pad(date.getSeconds())}`;\n}\n\ninterface ImageToolSuccessV1 {\n\treadonly content: readonly { readonly type: \"text\"; readonly text: string }[];\n\treadonly details: Record<string, never>;\n}\n\ninterface ProducedImageV1 {\n\treadonly bytes: Uint8Array;\n\treadonly format: ImageFormatV1;\n}\n\nfunction successResult(\n\tresult: ImageGenResultV1,\n\timages: readonly ProducedImageV1[],\n\tmodelSourceNote?: string,\n): ImageToolSuccessV1 | ImageGenResultV1 {\n\tif (result.status !== \"succeeded\") return result;\n\t// Zero inlining (user decision, 2026-09-30): image payloads never ride\n\t// the conversation — they would cost context on every later turn. The\n\t// tool result carries conclusions only (paths/model/usage); the model\n\t// reads a file on demand when it actually needs to look, which the host\n\t// read tool serves as an auto-resized image attachment.\n\tvoid images;\n\treturn {\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t{\n\t\t\t\t\t\tfiles: result.files,\n\t\t\t\t\t\tmodel: result.model,\n\t\t\t\t\t\t...(modelSourceNote === undefined ? {} : { modelSource: modelSourceNote }),\n\t\t\t\t\t\t...(result.usage === undefined ? {} : { usage: result.usage }),\n\t\t\t\t\t\tnote: \"images are saved to disk only; read a file to view it\",\n\t\t\t\t\t},\n\t\t\t\t\tnull,\n\t\t\t\t\t1,\n\t\t\t\t),\n\t\t\t},\n\t\t],\n\t\tdetails: {},\n\t};\n}\n\n/** Write one image; the exclusive-create retry makes concurrent invocations (parallel tool groups) safe. */\nasync function writeImage(\n\tworkspace: string,\n\tstamp: string,\n\tstartSequence: number,\n\tproduced: ProducedImageV1,\n): Promise<{ readonly relativePath: string; readonly sequence: number }> {\n\tconst directory = join(workspace, GENERATED_IMAGES_DIRECTORY);\n\tawait mkdir(directory, { recursive: true });\n\t// flag \"wx\" fails atomically when the name is taken (same-second stamp or\n\t// a concurrent tool group) instead of racing existsSync-then-write, which\n\t// silently overwrote one image with another under parallel execution.\n\tlet sequence = startSequence;\n\tfor (;;) {\n\t\tconst name = `img-${stamp}-${sequence}.${produced.format.extension}`;\n\t\ttry {\n\t\t\tawait writeFile(join(directory, name), produced.bytes, { flag: \"wx\" });\n\t\t\treturn { relativePath: `${GENERATED_IMAGES_DIRECTORY}/${name}`, sequence };\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code === \"EEXIST\") {\n\t\t\t\tsequence += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n\n/** Persist every produced image file for a settled response. */\nasync function persistImages(\n\tworkspace: string,\n\tproduced: readonly ProducedImageV1[],\n): Promise<{ readonly files: string[]; readonly images: ProducedImageV1[] }> {\n\tconst stamp = localStampV1(new Date());\n\tconst files: string[] = [];\n\tconst images: ProducedImageV1[] = [];\n\tlet sequence = 1;\n\tfor (const image of produced) {\n\t\tconst written = await writeImage(workspace, stamp, sequence, image);\n\t\tfiles.push(written.relativePath);\n\t\timages.push(image);\n\t\tsequence = written.sequence + 1;\n\t}\n\treturn { files, images };\n}\n\n/** Inline b64 items pass through; url items are downloaded with the same fetch injection. */\nasync function collectImages(\n\tresponse: ImagesClientResponseV1,\n\tfetchImpl: typeof fetch,\n\tsignal: AbortSignal | undefined,\n): Promise<ProducedImageV1[] | ImageFailureV1> {\n\tconst images: ProducedImageV1[] = [];\n\tfor (const item of response.data) {\n\t\tif (item.b64 !== undefined) {\n\t\t\tconst bytes = Buffer.from(item.b64, \"base64\");\n\t\t\timages.push({ bytes, format: detectImageFormatV1(bytes) });\n\t\t\tcontinue;\n\t\t}\n\t\tif (item.url === undefined) continue;\n\t\t// The download carries its own 120s budget: a slow proxy route must\n\t\t// not hang the tool on undici's default 300s body timeout.\n\t\tconst downloadSignal =\n\t\t\tsignal === undefined\n\t\t\t\t? AbortSignal.timeout(IMAGE_GENERATION_DOWNLOAD_TIMEOUT_MS_V1)\n\t\t\t\t: AbortSignal.any([signal, AbortSignal.timeout(IMAGE_GENERATION_DOWNLOAD_TIMEOUT_MS_V1)]);\n\t\tlet download: Response;\n\t\ttry {\n\t\t\tdownload = await fetchImpl(item.url, { signal: downloadSignal });\n\t\t} catch (error) {\n\t\t\tif (signal?.aborted) throw error;\n\t\t\t// Network-level download failures must name the host and the proxy\n\t\t\t// fix: a bare \"fetch failed\" filed under the *request* code sent the\n\t\t\t// seat diagnosis down the wrong path for an hour (the generation\n\t\t\t// itself was succeeding; the CDN was unreachable without a proxy).\n\t\t\tlet host = \"the provider cdn\";\n\t\t\ttry {\n\t\t\t\thost = new URL(item.url).host;\n\t\t\t} catch {}\n\t\t\treturn {\n\t\t\t\tcode: \"download_failed\",\n\t\t\t\tmessage: `image download from ${host} failed (${error instanceof Error ? error.message : \"network error\"}); if that host is only reachable through a proxy, set HTTPS_PROXY/HTTP_PROXY — see the image-generation plugin README`,\n\t\t\t};\n\t\t}\n\t\tif (!download.ok)\n\t\t\treturn {\n\t\t\t\tcode: \"download_failed\",\n\t\t\t\tmessage: `image download from the provider url failed with status ${download.status} (if this machine reaches the internet through a proxy, set HTTPS_PROXY/HTTP_PROXY — see the image-generation plugin README)`,\n\t\t\t};\n\t\tconst bytes = Buffer.from(await download.arrayBuffer());\n\t\tif (bytes.byteLength > IMAGE_GENERATION_MAX_DOWNLOAD_BYTES_V1)\n\t\t\treturn { code: \"response_too_large\", message: \"downloaded image exceeds the 20 MiB response limit\" };\n\t\timages.push({ bytes, format: detectImageFormatV1(bytes) });\n\t}\n\treturn images;\n}\n\nfunction usageOf(response: ImagesClientResponseV1): { readonly usage?: Record<string, unknown> } {\n\treturn response.usage === undefined ? {} : { usage: response.usage };\n}\n\n/** Resolve provider config/credentials/workspace; a miss returns the failed result directly. */\nasync function resolveInvocation(\n\tapi: CapabilityAPI,\n\tproviderId: string,\n\tfetchImpl: typeof fetch,\n\tmodel: string,\n\tbaseUrlOverride?: string,\n): Promise<\n\t| { readonly status: \"ok\"; readonly client: ReturnType<typeof createImagesClientV1>; readonly workspace: string }\n\t| { readonly status: \"failed\"; readonly result: ImageGenResultV1 }\n> {\n\tconst workspace = api.host.workspaceDirectory;\n\tif (typeof workspace !== \"string\" || workspace === \"\")\n\t\treturn {\n\t\t\tstatus: \"failed\",\n\t\t\tresult: failed(\n\t\t\t\tmodel,\n\t\t\t\t\"workspace_unavailable\",\n\t\t\t\t\"Image generation requires the host workspaceDirectory service to write generated-images/\",\n\t\t\t),\n\t\t};\n\tconst resolution = api.credentials === undefined ? undefined : await api.credentials.resolve({ providerId });\n\tif (resolution === undefined) {\n\t\treturn { status: \"failed\", result: credentialsFailure(model, providerId) };\n\t}\n\tconst baseUrl = baseUrlOverride ?? resolution.baseUrl;\n\tif (typeof resolution.apiKey !== \"string\" || resolution.apiKey === \"\" || baseUrl === undefined || baseUrl === \"\") {\n\t\treturn { status: \"failed\", result: credentialsFailure(model, providerId) };\n\t}\n\treturn {\n\t\tstatus: \"ok\",\n\t\tworkspace,\n\t\tclient: createImagesClientV1({ baseUrl, apiKey: resolution.apiKey, fetchImpl }),\n\t};\n}\n\nfunction credentialsFailure(model: string, providerId: string): ImageGenResultV1 {\n\treturn failed(\n\t\tmodel,\n\t\t\"credentials_unavailable\",\n\t\t`Image generation credentials are unavailable for provider ${providerId}: the host must resolve apiKey and baseUrl for this provider (auth.json; store the key via /login)`,\n\t);\n}\n\n/**\n * Registers the full-control `image_generate` and `image_edit` tools. The\n * factory takes no credentials: provider auth (`apiKey` + `baseUrl`) is\n * resolved at call time through the host's public `CredentialAPI`. The\n * optional `fetchImpl` is a test seam only; production hosts use global fetch.\n */\nexport function createImageGenerationCapabilityFactoryV1(options?: {\n\treadonly fetchImpl?: typeof fetch;\n}): CapabilityPluginSyncFactory {\n\t// Every outbound request (generation and url download alike) rides the\n\t// same proxy-aware fetch: HTTPS_PROXY/HTTP_PROXY/NO_PROXY are honored\n\t// per request without touching the host's global dispatcher. The default\n\t// base is the undici package's fetch — the global fetch bundles another\n\t// undici version and rejects this package's dispatchers.\n\tconst fetchImpl: typeof fetch = wrapFetchWithEnvProxyV1(options?.fetchImpl);\n\treturn (api) => {\n\t\tif (api.host.mode === \"readonly\") return;\n\t\t// 宿主装配期注入(设计 §3.3):settings 槽位 + 生图模型目录快照经\n\t\t// configOverride 合并进 api.config。Hosts that expose capability\n\t\t// selection use the session-selected target; the injected slot/catalog\n\t\t// remain only as the fallback for hosts without that service.\n\t\tconst slotInjection = readInjectedSlot(api.config);\n\t\tconst catalogInjection = readInjectedCatalog(api.config);\n\t\tconst sessionProvider = (): string | undefined => api.session?.getModel?.()?.provider;\n\t\tconst resolveTarget = (input: Record<string, unknown>): ImageTargetResolution => {\n\t\t\tif (api.selection !== undefined) {\n\t\t\t\tconst selected = api.selection.get(\"generate_image\");\n\t\t\t\tif (selected === undefined) {\n\t\t\t\t\treturn { ok: false, message: \"No image-generation target is selected; use /model to choose one\" };\n\t\t\t\t}\n\t\t\t\tif (!selected.available) {\n\t\t\t\t\treturn { ok: false, message: selected.error ?? \"The selected image-generation target is unavailable\" };\n\t\t\t\t}\n\t\t\t\tif (selected.adapter !== \"openai-images\") {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\tmessage: `Image-generation adapter \"${selected.adapter ?? \"none\"}\" is not supported`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tok: true,\n\t\t\t\t\tprovider: selected.provider,\n\t\t\t\t\tmodel: selected.id,\n\t\t\t\t\t...(selected.baseUrl === undefined ? {} : { baseUrl: selected.baseUrl }),\n\t\t\t\t\t...(selected.options === undefined ? {} : { options: selected.options }),\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (slotInjection.error !== undefined)\n\t\t\t\treturn { ok: false, message: `Invalid injected image-generation config: ${slotInjection.error}` };\n\t\t\tif (catalogInjection.error !== undefined)\n\t\t\t\treturn { ok: false, message: `Invalid injected image-generation config: ${catalogInjection.error}` };\n\t\t\treturn resolveImageTarget(input, slotInjection.slot, catalogInjection.catalog, sessionProvider());\n\t\t};\n\t\tapi.registerTool({\n\t\t\tname: \"image_generate\",\n\t\t\tlabel: \"Image generate\",\n\t\t\t...(api.selection === undefined ? {} : { capability: { key: \"generate_image\", requiresSelection: true } }),\n\t\t\tdescription:\n\t\t\t\t\"Generate images from a prompt via the host-configured provider's OpenAI-compatible images API; saves image files (png/jpg/webp/gif as produced) under generated-images/ and returns their workspace-relative paths — images are never inlined into the conversation, read a returned file to view it\",\n\t\t\tparameters: IMAGE_GENERATE_PARAMETERS,\n\t\t\texecute: async (first: unknown, second?: unknown, third?: unknown) => {\n\t\t\t\tlet input: Record<string, unknown>;\n\t\t\t\ttry {\n\t\t\t\t\tinput = objectInput(first, second);\n\t\t\t\t} catch {\n\t\t\t\t\treturn failed(\"\", \"invalid_input\", \"Image generation input must be an object\");\n\t\t\t\t}\n\t\t\t\tconst prompt = promptFrom(input.prompt);\n\t\t\t\tif (prompt === undefined)\n\t\t\t\t\treturn failed(\"\", \"invalid_input\", \"prompt must be a non-empty string of at most 4000 characters\");\n\t\t\t\tconst size = boundedString(input.size, 32);\n\t\t\t\tconst quality = boundedString(input.quality, 32);\n\t\t\t\tif (input.n !== undefined && countFrom(input.n) === undefined)\n\t\t\t\t\treturn failed(\"\", \"invalid_input\", \"n must be an integer between 1 and 4\");\n\t\t\t\tconst n = countFrom(input.n) ?? 1;\n\t\t\t\tconst sessionSignal = api.sessionAbortSignal?.();\n\t\t\t\tconst invocationSignal = signalFrom(third);\n\t\t\t\tconst clientSignal = combineSignals([invocationSignal, sessionSignal]);\n\t\t\t\tif (clientSignal?.aborted) return cancelled(\"\");\n\t\t\t\tconst target = resolveTarget(input);\n\t\t\t\tif (!target.ok) return failed(\"\", \"config_missing\", boundedImageMessageV1(target.message));\n\t\t\t\tconst { provider, model, modelSourceNote, baseUrl, options } = target;\n\t\t\t\tconst resolvedSize = size ?? boundedString(options?.size, 32);\n\t\t\t\tconst resolvedQuality = quality ?? boundedString(options?.quality, 32);\n\t\t\t\tconst resolvedCount = countFrom(options?.n) ?? n;\n\t\t\t\ttry {\n\t\t\t\t\tconst resolved = await resolveInvocation(api, provider, fetchImpl, model, baseUrl);\n\t\t\t\t\tif (resolved.status === \"failed\") return resolved.result;\n\t\t\t\t\tconst response = await resolved.client.generateImages(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tprompt,\n\t\t\t\t\t\t\tn: resolvedCount,\n\t\t\t\t\t\t\t...(resolvedSize === undefined ? {} : { size: resolvedSize }),\n\t\t\t\t\t\t\t...(resolvedQuality === undefined ? {} : { quality: resolvedQuality }),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tclientSignal,\n\t\t\t\t\t);\n\t\t\t\t\tconst collected = await collectImages(response, fetchImpl, clientSignal);\n\t\t\t\t\tif (!Array.isArray(collected)) return failed(model, collected.code, collected.message);\n\t\t\t\t\tconst persisted = await persistImages(resolved.workspace, collected);\n\t\t\t\t\treturn successResult(\n\t\t\t\t\t\t{ version: 1, status: \"succeeded\", files: persisted.files, model, ...usageOf(response) },\n\t\t\t\t\t\tpersisted.images,\n\t\t\t\t\t\tmodelSourceNote,\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn failureFrom(error, clientSignal, model, \"Image generation request failed\");\n\t\t\t\t}\n\t\t\t},\n\t\t});\n\t\tapi.registerTool({\n\t\t\tname: \"image_edit\",\n\t\t\tlabel: \"Image edit\",\n\t\t\t...(api.selection === undefined ? {} : { capability: { key: \"generate_image\", requiresSelection: true } }),\n\t\t\tdescription:\n\t\t\t\t\"Edit a previously generated image (workspace-relative path under generated-images/) with a revision prompt; returns the new file path\",\n\t\t\tparameters: IMAGE_EDIT_PARAMETERS,\n\t\t\texecute: async (first: unknown, second?: unknown, third?: unknown) => {\n\t\t\t\tlet input: Record<string, unknown>;\n\t\t\t\ttry {\n\t\t\t\t\tinput = objectInput(first, second);\n\t\t\t\t} catch {\n\t\t\t\t\treturn failed(\"\", \"invalid_input\", \"Image generation input must be an object\");\n\t\t\t\t}\n\t\t\t\tconst prompt = promptFrom(input.prompt);\n\t\t\t\tif (prompt === undefined)\n\t\t\t\t\treturn failed(\"\", \"invalid_input\", \"prompt must be a non-empty string of at most 4000 characters\");\n\t\t\t\tconst imagePath = typeof input.imagePath === \"string\" ? input.imagePath : undefined;\n\t\t\t\tif (imagePath === undefined || !validImagePath(imagePath))\n\t\t\t\t\treturn failed(\n\t\t\t\t\t\t\"\",\n\t\t\t\t\t\t\"invalid_path\",\n\t\t\t\t\t\t\"imagePath must be a workspace-relative identifier inside the generated-images/ directory (no .. segments)\",\n\t\t\t\t\t);\n\t\t\t\tconst sessionSignal = api.sessionAbortSignal?.();\n\t\t\t\tconst invocationSignal = signalFrom(third);\n\t\t\t\tconst clientSignal = combineSignals([invocationSignal, sessionSignal]);\n\t\t\t\tif (clientSignal?.aborted) return cancelled(\"\");\n\t\t\t\tconst target = resolveTarget(input);\n\t\t\t\tif (!target.ok) return failed(\"\", \"config_missing\", boundedImageMessageV1(target.message));\n\t\t\t\tconst { provider, model, modelSourceNote, baseUrl } = target;\n\t\t\t\ttry {\n\t\t\t\t\tconst resolved = await resolveInvocation(api, provider, fetchImpl, model, baseUrl);\n\t\t\t\t\tif (resolved.status === \"failed\") return resolved.result;\n\t\t\t\t\t// Defense in depth (readonly never registers these tools): the\n\t\t\t\t\t// lexical validImagePath gate cannot see symlinks, so refuse any\n\t\t\t\t\t// candidate whose real path escapes the workspace before a byte\n\t\t\t\t\t// is read and shipped to the provider.\n\t\t\t\t\tconst sandbox = await sandboxedImagePath(resolved.workspace, imagePath);\n\t\t\t\t\tif (sandbox === \"missing\")\n\t\t\t\t\t\treturn failed(\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\"image_not_found\",\n\t\t\t\t\t\t\t`image ${imagePath} was not found under the workspace generated-images/ directory`,\n\t\t\t\t\t\t);\n\t\t\t\t\tif (sandbox === \"escape\")\n\t\t\t\t\t\treturn failed(\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\"invalid_path\",\n\t\t\t\t\t\t\t`imagePath ${imagePath} resolves outside the workspace; only files under the workspace generated-images/ directory can be read`,\n\t\t\t\t\t\t);\n\t\t\t\t\t// Size-check before reading: users can drop their own files\n\t\t\t\t\t// into generated-images/, and the 20 MiB download cap must\n\t\t\t\t\t// not be bypassed by a renamed local file.\n\t\t\t\t\tconst sourceStats = await stat(join(resolved.workspace, imagePath)).catch(() => undefined);\n\t\t\t\t\tif (sourceStats === undefined || !sourceStats.isFile())\n\t\t\t\t\t\treturn failed(\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\"image_not_found\",\n\t\t\t\t\t\t\t`image ${imagePath} was not found under the workspace generated-images/ directory`,\n\t\t\t\t\t\t);\n\t\t\t\t\tif (sourceStats.size > IMAGE_GENERATION_MAX_DOWNLOAD_BYTES_V1)\n\t\t\t\t\t\treturn failed(\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\"response_too_large\",\n\t\t\t\t\t\t\t`image ${imagePath} is ${sourceStats.size} bytes, above the 20 MiB limit`,\n\t\t\t\t\t\t);\n\t\t\t\t\tconst source = await readFile(join(resolved.workspace, imagePath)).catch(() => undefined);\n\t\t\t\t\tif (source === undefined)\n\t\t\t\t\t\treturn failed(\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\"image_not_found\",\n\t\t\t\t\t\t\t`image ${imagePath} was not found under the workspace generated-images/ directory`,\n\t\t\t\t\t\t);\n\t\t\t\t\tconst response = await resolved.client.editImage(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\timage: source,\n\t\t\t\t\t\t\t// The edits endpoint accepts png/jpeg/webp inputs; the\n\t\t\t\t\t\t\t// multipart blob must carry the source's real format\n\t\t\t\t\t\t\t// (a prior url-form download may be JPEG).\n\t\t\t\t\t\t\tmimeType: detectImageFormatV1(source).mimeType,\n\t\t\t\t\t\t\tprompt,\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tclientSignal,\n\t\t\t\t\t);\n\t\t\t\t\tconst collected = await collectImages(response, fetchImpl, clientSignal);\n\t\t\t\t\tif (!Array.isArray(collected)) return failed(model, collected.code, collected.message);\n\t\t\t\t\tconst persisted = await persistImages(resolved.workspace, collected);\n\t\t\t\t\treturn successResult(\n\t\t\t\t\t\t{ version: 1, status: \"succeeded\", files: persisted.files, model, ...usageOf(response) },\n\t\t\t\t\t\tpersisted.images,\n\t\t\t\t\t\tmodelSourceNote,\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn failureFrom(error, clientSignal, model, \"Image edit request failed\");\n\t\t\t\t}\n\t\t\t},\n\t\t});\n\t};\n}\n\n/** HTTP status embedded in the images client's error text (`... failed with status 403: ...`). */\nfunction imageErrorStatus(message: string): number | undefined {\n\tconst match = /failed with status (\\d{3})(?::|$)/u.exec(message);\n\treturn match === null ? undefined : Number(match[1]);\n}\n\nfunction failureFrom(\n\terror: unknown,\n\tsignal: AbortSignal | undefined,\n\tmodel: string,\n\tfallbackMessage: string,\n): ImageGenResultV1 {\n\tif (signal?.aborted) return cancelled(model);\n\tlet message = error instanceof Error ? error.message : fallbackMessage;\n\t// A rejected credential is not a request failure the caller can retry with\n\t// the same key: name it and point at the provider-specific auth entry\n\t// (2026-10-29 round-4 tick 7: the shared gateway key lacks image capability,\n\t// while the dedicated image key succeeds).\n\tconst status = imageErrorStatus(message);\n\tif (status === 401 || status === 403) {\n\t\treturn failed(\n\t\t\tmodel,\n\t\t\t\"credentials_insufficient\",\n\t\t\tboundedImageMessageV1(\n\t\t\t\t`${message} (the configured image-generation credential was rejected${status === 403 ? \" with 403, which usually means this API key has no image capability\" : \"\"}; configure a dedicated image-generation key for the selected provider — auth.json entry for that provider — instead of reusing the main text key)`,\n\t\t\t),\n\t\t);\n\t}\n\t// Append (never replace) a proxy hint for opaque network failures: the\n\t// single most common cause on machines that route out through a VPN.\n\tif (/fetch failed|terminated|ENOTFOUND|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|UND_ERR/u.test(message))\n\t\tmessage = `${message} (if this machine reaches the internet through a proxy, set HTTPS_PROXY/HTTP_PROXY — see the image-generation plugin README)`;\n\treturn failed(model, \"image_request_failed\", boundedImageMessageV1(message));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"capability.d.ts","sourceRoot":"","sources":["../src/capability.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAiB,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AA+Z1F;;;;;GAKG;AACH,wBAAgB,wCAAwC,CAAC,OAAO,CAAC,EAAE;IAClE,QAAQ,CAAC,SAAS,CAAC,EAAE,OAAO,KAAK,CAAC;CAClC,GAAG,2BAA2B,CAwM9B","sourcesContent":["import { mkdir, readFile, realpath, stat, writeFile } from \"node:fs/promises\";\nimport { join, sep } from \"node:path\";\nimport type { CapabilityAPI, CapabilityPluginSyncFactory } from \"@agent-forge/plugin-sdk\";\nimport { Type } from \"typebox\";\nimport { wrapFetchWithEnvProxyV1 } from \"./env-proxy-fetch.ts\";\nimport { createImagesClientV1 } from \"./images-client.ts\";\nimport {\n\tboundedImageMessageV1,\n\tdetectImageFormatV1,\n\tIMAGE_GENERATION_DOWNLOAD_TIMEOUT_MS_V1,\n\tIMAGE_GENERATION_MAX_DOWNLOAD_BYTES_V1,\n\tIMAGE_GENERATION_MAX_MESSAGE_CHARS_V1,\n\ttype ImageFormatV1,\n\ttype ImageGenResultV1,\n\ttype ImagesClientResponseV1,\n} from \"./types.ts\";\n\nconst IMAGE_GENERATE_PARAMETERS = Type.Object(\n\t{\n\t\tprompt: Type.String({ minLength: 1, maxLength: 4000 }),\n\t\tsize: Type.Optional(Type.String({ minLength: 1, maxLength: 32 })),\n\t\tquality: Type.Optional(Type.String({ minLength: 1, maxLength: 32 })),\n\t\tn: Type.Optional(Type.Integer({ minimum: 1, maximum: 4 })),\n\t},\n\t{ additionalProperties: false },\n);\n\nconst IMAGE_EDIT_PARAMETERS = Type.Object(\n\t{\n\t\timagePath: Type.String({ minLength: 1, maxLength: 512, pattern: \"^[A-Za-z0-9_][A-Za-z0-9._/-]*$\" }),\n\t\tprompt: Type.String({ minLength: 1, maxLength: 4000 }),\n\t},\n\t{ additionalProperties: false },\n);\n\nconst IMAGE_PATH_PATTERN_V1 = /^[A-Za-z0-9_][A-Za-z0-9._/-]*$/u;\n\nconst GENERATED_IMAGES_DIRECTORY = \"generated-images\";\nconst UNRECOGNIZED_IMAGE_REASON = \"Provider response entries did not contain a recognized image payload or URL.\";\n\ninterface ImageFailureV1 {\n\treadonly code: string;\n\treadonly message: string;\n}\n\nfunction objectInput(first: unknown, second: unknown): Record<string, unknown> {\n\t// Shape-based dual-convention read (aligned with subagent-delegate): the\n\t// runtime invoke face passes the input object first and the host\n\t// CapabilityToolContext second; the agent tool face passes the tool call\n\t// id (a string) first and the params object second.\n\tconst value = first !== null && typeof first === \"object\" && !Array.isArray(first) ? first : second;\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value))\n\t\tthrow new Error(\"Image generation input must be an object\");\n\treturn value as Record<string, unknown>;\n}\n\nfunction signalFrom(value: unknown): AbortSignal | undefined {\n\treturn value instanceof AbortSignal ? value : undefined;\n}\n\nfunction combineSignals(signals: readonly (AbortSignal | undefined)[]): AbortSignal | undefined {\n\tconst present = signals.filter((signal): signal is AbortSignal => signal !== undefined);\n\tif (present.length === 0) return undefined;\n\tif (present.length === 1) return present[0];\n\treturn AbortSignal.any(present);\n}\n\nfunction failed(model: string, code: string, message: string): ImageGenResultV1 {\n\treturn {\n\t\tversion: 1,\n\t\tstatus: \"failed\",\n\t\tfiles: [],\n\t\tmodel,\n\t\terror: { code, message: boundedImageMessageV1(message) },\n\t};\n}\n\nfunction emptyImageResponse(\n\tmodel: string,\n\tmessage = \"Image provider returned no usable images\",\n\tunrecognizedItems = 0,\n) {\n\tconst reason =\n\t\tunrecognizedItems > 0\n\t\t\t? `${message}; ${unrecognizedItems} unrecognized response item(s). ${UNRECOGNIZED_IMAGE_REASON}`\n\t\t\t: message;\n\tconst result = failed(model, \"image_response_empty\", reason);\n\treturn {\n\t\tcontent: [{ type: \"text\" as const, text: JSON.stringify(result, null, 2) }],\n\t\tdetails: result,\n\t\tisError: true,\n\t};\n}\n\nfunction cancelled(model: string): ImageGenResultV1 {\n\treturn {\n\t\tversion: 1,\n\t\tstatus: \"cancelled\",\n\t\tfiles: [],\n\t\tmodel,\n\t\terror: { code: \"cancelled\", message: \"Image generation was cancelled\" },\n\t};\n}\n\nfunction boundedString(value: unknown, maxLength: number): string | undefined {\n\treturn typeof value === \"string\" && value !== \"\" && value.length <= maxLength ? value : undefined;\n}\n\ntype ImageTargetResolution =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\treadonly provider: string;\n\t\t\treadonly model: string;\n\t\t\treadonly baseUrl?: string;\n\t\t\treadonly options?: Readonly<Record<string, unknown>>;\n\t }\n\t| { readonly ok: false; readonly message: string };\n\nfunction promptFrom(value: unknown): string | undefined {\n\treturn boundedString(value, 4000);\n}\n\nfunction countFrom(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isSafeInteger(value) && value >= 1 && value <= 4 ? value : undefined;\n}\n\n/** Workspace-relative identifier confined to the generated-images directory. */\nfunction validImagePath(imagePath: string): boolean {\n\tif (!IMAGE_PATH_PATTERN_V1.test(imagePath)) return false;\n\tif (!imagePath.startsWith(`${GENERATED_IMAGES_DIRECTORY}/`)) return false;\n\treturn !imagePath.split(\"/\").includes(\"..\");\n}\n\n/**\n * image_edit ships workspace bytes to an external image provider, so the\n * lexical validImagePath gate is not enough: a symlink inside\n * generated-images/ can point anywhere on disk. Same sandbox model as the\n * workspace-files-write host: resolve the workspace root and the candidate to\n * their real paths and require the candidate to stay inside the real root.\n * A missing file (or dangling link) fails realpath and maps to the regular\n * not-found outcome; a link resolving outside the workspace is a boundary\n * escape and is refused. Links that stay inside the workspace keep working —\n * their bytes never leave the sandbox boundary.\n */\nasync function sandboxedImagePath(workspace: string, imagePath: string): Promise<\"missing\" | \"escape\" | \"ok\"> {\n\tconst root = await realpath(workspace).catch(() => undefined);\n\tif (root === undefined) return \"missing\";\n\tconst real = await realpath(join(workspace, imagePath)).catch(() => undefined);\n\tif (real === undefined) return \"missing\";\n\tif (real !== root && !real.startsWith(root + sep)) return \"escape\";\n\treturn \"ok\";\n}\n\n/**\n * Local-time `yyyymmdd-HHmmss` stamp shared by every file of one invocation.\n * Local (not UTC): users find today's images by the date in the filename, and\n * on UTC+8 machines a UTC stamp labels evening images as \"tomorrow\". Sorting\n * stays monotonic wherever local time has no DST jumps (e.g. China).\n */\nfunction localStampV1(date: Date): string {\n\tconst pad = (value: number): string => String(value).padStart(2, \"0\");\n\treturn `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(\n\t\tdate.getHours(),\n\t)}${pad(date.getMinutes())}${pad(date.getSeconds())}`;\n}\n\ninterface ImageToolSuccessV1 {\n\treadonly content: readonly { readonly type: \"text\"; readonly text: string }[];\n\treadonly details: Record<string, never>;\n}\n\ninterface ProducedImageV1 {\n\treadonly bytes: Uint8Array;\n\treadonly format: ImageFormatV1;\n}\n\nfunction successResult(\n\tresult: ImageGenResultV1,\n\timages: readonly ProducedImageV1[],\n): ImageToolSuccessV1 | ImageGenResultV1 {\n\tif (result.status !== \"succeeded\" && result.status !== \"partial\") return result;\n\t// Zero inlining (user decision, 2026-09-30): image payloads never ride\n\t// the conversation — they would cost context on every later turn. The\n\t// tool result carries conclusions only (paths/model/usage); the model\n\t// reads a file on demand when it actually needs to look, which the host\n\t// read tool serves as an auto-resized image attachment.\n\tvoid images;\n\treturn {\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t{\n\t\t\t\t\t\t...(result.status === \"partial\" ? { status: result.status, omitted: result.omitted } : {}),\n\t\t\t\t\t\tfiles: result.files,\n\t\t\t\t\t\tmodel: result.model,\n\t\t\t\t\t\t...(result.usage === undefined ? {} : { usage: result.usage }),\n\t\t\t\t\t\tnote: \"images are saved to disk only; read a file to view it\",\n\t\t\t\t\t},\n\t\t\t\t\tnull,\n\t\t\t\t\t1,\n\t\t\t\t),\n\t\t\t},\n\t\t],\n\t\tdetails: {},\n\t};\n}\n\n/** Write one image; the exclusive-create retry makes concurrent invocations (parallel tool groups) safe. */\nasync function writeImage(\n\tworkspace: string,\n\tstamp: string,\n\tstartSequence: number,\n\tproduced: ProducedImageV1,\n): Promise<\n\t| { readonly ok: true; readonly relativePath: string; readonly sequence: number }\n\t| { readonly ok: false; readonly error: unknown; readonly attemptedPath?: string }\n> {\n\tconst directory = join(workspace, GENERATED_IMAGES_DIRECTORY);\n\ttry {\n\t\tawait mkdir(directory, { recursive: true });\n\t} catch (error) {\n\t\treturn { ok: false, error };\n\t}\n\t// flag \"wx\" fails atomically when the name is taken (same-second stamp or\n\t// a concurrent tool group) instead of racing existsSync-then-write, which\n\t// silently overwrote one image with another under parallel execution.\n\tlet sequence = startSequence;\n\tfor (;;) {\n\t\tconst name = `img-${stamp}-${sequence}.${produced.format.extension}`;\n\t\ttry {\n\t\t\tawait writeFile(join(directory, name), produced.bytes, { flag: \"wx\" });\n\t\t\treturn { ok: true, relativePath: `${GENERATED_IMAGES_DIRECTORY}/${name}`, sequence };\n\t\t} catch (error) {\n\t\t\tif (typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"EEXIST\") {\n\t\t\t\tsequence += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn { ok: false, error, attemptedPath: `${GENERATED_IMAGES_DIRECTORY}/${name}` };\n\t\t}\n\t}\n}\n\n/** Persist every produced image file for a settled response. */\nasync function persistImages(\n\tworkspace: string,\n\tproduced: readonly ProducedImageV1[],\n): Promise<\n\t| { readonly ok: true; readonly files: string[]; readonly images: ProducedImageV1[] }\n\t| { readonly ok: false; readonly files: string[]; readonly error: unknown; readonly attemptedPath?: string }\n> {\n\tconst stamp = localStampV1(new Date());\n\tconst files: string[] = [];\n\tconst images: ProducedImageV1[] = [];\n\tlet sequence = 1;\n\tfor (const image of produced) {\n\t\tconst written = await writeImage(workspace, stamp, sequence, image);\n\t\tif (!written.ok) return { ...written, files };\n\t\tfiles.push(written.relativePath);\n\t\timages.push(image);\n\t\tsequence = written.sequence + 1;\n\t}\n\treturn { ok: true, files, images };\n}\n\n/** Inline b64 items pass through; url items are downloaded with the same fetch injection. */\nasync function collectImages(\n\tresponse: ImagesClientResponseV1,\n\tfetchImpl: typeof fetch,\n\tsignal: AbortSignal | undefined,\n): Promise<ProducedImageV1[] | ImageFailureV1> {\n\tconst images: ProducedImageV1[] = [];\n\tfor (const item of response.data) {\n\t\tif (item.b64 !== undefined) {\n\t\t\tconst bytes = Buffer.from(item.b64, \"base64\");\n\t\t\tif (bytes.length === 0)\n\t\t\t\treturn { code: \"image_response_empty\", message: \"Image provider returned an empty image\" };\n\t\t\timages.push({ bytes, format: detectImageFormatV1(bytes) });\n\t\t\tcontinue;\n\t\t}\n\t\tif (item.url === undefined) continue;\n\t\t// The download carries its own 120s budget: a slow proxy route must\n\t\t// not hang the tool on undici's default 300s body timeout.\n\t\tconst downloadSignal =\n\t\t\tsignal === undefined\n\t\t\t\t? AbortSignal.timeout(IMAGE_GENERATION_DOWNLOAD_TIMEOUT_MS_V1)\n\t\t\t\t: AbortSignal.any([signal, AbortSignal.timeout(IMAGE_GENERATION_DOWNLOAD_TIMEOUT_MS_V1)]);\n\t\tlet download: Response;\n\t\ttry {\n\t\t\tdownload = await fetchImpl(item.url, { signal: downloadSignal });\n\t\t} catch (error) {\n\t\t\tif (signal?.aborted) throw error;\n\t\t\t// Network-level download failures must name the host and the proxy\n\t\t\t// fix: a bare \"fetch failed\" filed under the *request* code sent the\n\t\t\t// seat diagnosis down the wrong path for an hour (the generation\n\t\t\t// itself was succeeding; the CDN was unreachable without a proxy).\n\t\t\tlet host = \"the provider cdn\";\n\t\t\ttry {\n\t\t\t\thost = new URL(item.url).host;\n\t\t\t} catch {}\n\t\t\treturn {\n\t\t\t\tcode: \"download_failed\",\n\t\t\t\tmessage: `image download from ${host} failed (${error instanceof Error ? error.message : \"network error\"}); if that host is only reachable through a proxy, set HTTPS_PROXY/HTTP_PROXY — see the image-generation plugin README`,\n\t\t\t};\n\t\t}\n\t\tif (!download.ok)\n\t\t\treturn {\n\t\t\t\tcode: \"download_failed\",\n\t\t\t\tmessage: `image download from the provider url failed with status ${download.status} (if this machine reaches the internet through a proxy, set HTTPS_PROXY/HTTP_PROXY — see the image-generation plugin README)`,\n\t\t\t};\n\t\tconst bytes = Buffer.from(await download.arrayBuffer());\n\t\tif (bytes.length === 0)\n\t\t\treturn { code: \"image_response_empty\", message: \"Image provider returned an empty image\" };\n\t\tif (bytes.byteLength > IMAGE_GENERATION_MAX_DOWNLOAD_BYTES_V1)\n\t\t\treturn { code: \"response_too_large\", message: \"downloaded image exceeds the 20 MiB response limit\" };\n\t\timages.push({ bytes, format: detectImageFormatV1(bytes) });\n\t}\n\treturn images;\n}\n\nfunction usageOf(response: ImagesClientResponseV1): { readonly usage?: Record<string, unknown> } {\n\treturn response.usage === undefined ? {} : { usage: response.usage };\n}\n\nfunction producedImageResult(files: string[], model: string, response: ImagesClientResponseV1): ImageGenResultV1 {\n\tconst count = response.unrecognizedItems ?? 0;\n\treturn {\n\t\tversion: 1,\n\t\tstatus: count > 0 ? \"partial\" : \"succeeded\",\n\t\tfiles,\n\t\tmodel,\n\t\t...usageOf(response),\n\t\t...(count > 0 ? { omitted: { count, reason: UNRECOGNIZED_IMAGE_REASON } } : {}),\n\t};\n}\n\nfunction imageWriteFailure(\n\tmodel: string,\n\tresponse: ImagesClientResponseV1,\n\tresult: { readonly files: string[]; readonly error: unknown; readonly attemptedPath?: string },\n\tsignal: AbortSignal | undefined,\n) {\n\tconst message = result.error instanceof Error ? result.error.message : String(result.error);\n\tconst causeCode =\n\t\ttypeof result.error === \"object\" &&\n\t\tresult.error !== null &&\n\t\t\"code\" in result.error &&\n\t\ttypeof result.error.code === \"string\"\n\t\t\t? result.error.code\n\t\t\t: undefined;\n\tconst details: ImageGenResultV1 = {\n\t\t...producedImageResult(result.files, model, response),\n\t\tstatus: signal?.aborted ? \"cancelled\" : result.files.length > 0 ? \"partial\" : \"failed\",\n\t\terror: {\n\t\t\tcode: \"image_write_failed\",\n\t\t\tmessage: boundedImageMessageV1(message),\n\t\t\t...(causeCode === undefined ? {} : { causeCode }),\n\t\t\t...(message.length > IMAGE_GENERATION_MAX_MESSAGE_CHARS_V1 ? { messageTruncated: true } : {}),\n\t\t},\n\t\t...(result.attemptedPath === undefined\n\t\t\t? {}\n\t\t\t: { attemptedFile: { path: result.attemptedPath, status: \"unknown\" } }),\n\t};\n\tconst output =\n\t\tresult.attemptedPath === undefined\n\t\t\t? details\n\t\t\t: {\n\t\t\t\t\t...details,\n\t\t\t\t\tnote: \"The attempted file may not exist, may be incomplete, or may have changed concurrently.\",\n\t\t\t\t};\n\treturn { content: [{ type: \"text\" as const, text: JSON.stringify(output, null, 2) }], details, isError: true };\n}\n\n/** Resolve provider config/credentials/workspace; a miss returns the failed result directly. */\nasync function resolveInvocation(\n\tapi: CapabilityAPI,\n\tproviderId: string,\n\tfetchImpl: typeof fetch,\n\tmodel: string,\n\tbaseUrlOverride?: string,\n): Promise<\n\t| { readonly status: \"ok\"; readonly client: ReturnType<typeof createImagesClientV1>; readonly workspace: string }\n\t| { readonly status: \"failed\"; readonly result: ImageGenResultV1 }\n> {\n\tconst workspace = api.host.workspaceDirectory;\n\tif (typeof workspace !== \"string\" || workspace === \"\")\n\t\treturn {\n\t\t\tstatus: \"failed\",\n\t\t\tresult: failed(\n\t\t\t\tmodel,\n\t\t\t\t\"workspace_unavailable\",\n\t\t\t\t\"Image generation requires the host workspaceDirectory service to write generated-images/\",\n\t\t\t),\n\t\t};\n\tconst resolution = api.credentials === undefined ? undefined : await api.credentials.resolve({ providerId });\n\tif (resolution === undefined) {\n\t\treturn { status: \"failed\", result: credentialsFailure(model, providerId) };\n\t}\n\tconst baseUrl = baseUrlOverride ?? resolution.baseUrl;\n\tif (typeof resolution.apiKey !== \"string\" || resolution.apiKey === \"\" || baseUrl === undefined || baseUrl === \"\") {\n\t\treturn { status: \"failed\", result: credentialsFailure(model, providerId) };\n\t}\n\treturn {\n\t\tstatus: \"ok\",\n\t\tworkspace,\n\t\tclient: createImagesClientV1({ baseUrl, apiKey: resolution.apiKey, fetchImpl }),\n\t};\n}\n\nfunction credentialsFailure(model: string, providerId: string): ImageGenResultV1 {\n\treturn failed(\n\t\tmodel,\n\t\t\"credentials_unavailable\",\n\t\t`Image generation credentials are unavailable for provider ${providerId}: the host must resolve apiKey and baseUrl for this provider (auth.json; store the key via /login)`,\n\t);\n}\n\n/**\n * Registers the `image_generate` and `image_edit` tools. The factory takes no\n * credentials: provider auth (`apiKey` + `baseUrl`) is resolved at call time\n * through the host's public `CredentialAPI`. The optional `fetchImpl` is a\n * test seam only; production hosts use global fetch.\n */\nexport function createImageGenerationCapabilityFactoryV1(options?: {\n\treadonly fetchImpl?: typeof fetch;\n}): CapabilityPluginSyncFactory {\n\t// Every outbound request (generation and url download alike) rides the\n\t// same proxy-aware fetch: HTTPS_PROXY/HTTP_PROXY/NO_PROXY are honored\n\t// per request without touching the host's global dispatcher. The default\n\t// base is the undici package's fetch — the global fetch bundles another\n\t// undici version and rejects this package's dispatchers.\n\tconst fetchImpl: typeof fetch = wrapFetchWithEnvProxyV1(options?.fetchImpl);\n\treturn (api) => {\n\t\t// The session selection is the only target source (D-134). Hosts without\n\t\t// the capability-selection service cannot run image generation; keep the\n\t\t// tools unregistered instead of shipping an unreachable fallback.\n\t\tif (api.selection === undefined) {\n\t\t\tapi.logger?.debug(\"image-generation: host provides no capability-selection service; tools stay unregistered\");\n\t\t\treturn;\n\t\t}\n\t\tconst selection = api.selection;\n\t\tconst resolveTarget = (): ImageTargetResolution => {\n\t\t\tconst selected = selection.get(\"generate_image\");\n\t\t\tif (selected === undefined) {\n\t\t\t\treturn { ok: false, message: \"No image-generation target is selected; use /model to choose one\" };\n\t\t\t}\n\t\t\tif (!selected.available) {\n\t\t\t\treturn { ok: false, message: selected.error ?? \"The selected image-generation target is unavailable\" };\n\t\t\t}\n\t\t\tif (selected.adapter !== \"openai-images\") {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tmessage: `Image-generation adapter \"${selected.adapter ?? \"none\"}\" is not supported`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tprovider: selected.provider,\n\t\t\t\tmodel: selected.id,\n\t\t\t\t...(selected.baseUrl === undefined ? {} : { baseUrl: selected.baseUrl }),\n\t\t\t\t...(selected.options === undefined ? {} : { options: selected.options }),\n\t\t\t};\n\t\t};\n\t\tapi.registerTool({\n\t\t\tname: \"image_generate\",\n\t\t\tlabel: \"Image generate\",\n\t\t\tcapability: { key: \"generate_image\", requiresSelection: true },\n\t\t\tdescription:\n\t\t\t\t\"Generate images from a prompt via the host-configured provider's OpenAI-compatible images API; saves image files (png/jpg/webp/gif as produced) under generated-images/ and returns their workspace-relative paths — images are never inlined into the conversation, read a returned file to view it\",\n\t\t\tparameters: IMAGE_GENERATE_PARAMETERS,\n\t\t\texecute: async (first: unknown, second?: unknown, third?: unknown) => {\n\t\t\t\tlet input: Record<string, unknown>;\n\t\t\t\ttry {\n\t\t\t\t\tinput = objectInput(first, second);\n\t\t\t\t} catch {\n\t\t\t\t\treturn failed(\"\", \"invalid_input\", \"Image generation input must be an object\");\n\t\t\t\t}\n\t\t\t\tconst prompt = promptFrom(input.prompt);\n\t\t\t\tif (prompt === undefined)\n\t\t\t\t\treturn failed(\"\", \"invalid_input\", \"prompt must be a non-empty string of at most 4000 characters\");\n\t\t\t\tconst size = boundedString(input.size, 32);\n\t\t\t\tconst quality = boundedString(input.quality, 32);\n\t\t\t\tif (input.n !== undefined && countFrom(input.n) === undefined)\n\t\t\t\t\treturn failed(\"\", \"invalid_input\", \"n must be an integer between 1 and 4\");\n\t\t\t\tconst n = countFrom(input.n);\n\t\t\t\tconst sessionSignal = api.sessionAbortSignal?.();\n\t\t\t\tconst invocationSignal = signalFrom(third);\n\t\t\t\tconst clientSignal = combineSignals([invocationSignal, sessionSignal]);\n\t\t\t\tif (clientSignal?.aborted) return cancelled(\"\");\n\t\t\t\tconst target = resolveTarget();\n\t\t\t\tif (!target.ok) return failed(\"\", \"config_missing\", boundedImageMessageV1(target.message));\n\t\t\t\tconst { provider, model, baseUrl, options } = target;\n\t\t\t\tconst resolvedSize = size ?? boundedString(options?.size, 32);\n\t\t\t\tconst resolvedQuality = quality ?? boundedString(options?.quality, 32);\n\t\t\t\tconst resolvedCount = n ?? countFrom(options?.n) ?? 1;\n\t\t\t\ttry {\n\t\t\t\t\tconst resolved = await resolveInvocation(api, provider, fetchImpl, model, baseUrl);\n\t\t\t\t\tif (resolved.status === \"failed\") return resolved.result;\n\t\t\t\t\tconst response = await resolved.client.generateImages(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tprompt,\n\t\t\t\t\t\t\tn: resolvedCount,\n\t\t\t\t\t\t\t...(resolvedSize === undefined ? {} : { size: resolvedSize }),\n\t\t\t\t\t\t\t...(resolvedQuality === undefined ? {} : { quality: resolvedQuality }),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tclientSignal,\n\t\t\t\t\t);\n\t\t\t\t\tconst collected = await collectImages(response, fetchImpl, clientSignal);\n\t\t\t\t\tif (!Array.isArray(collected)) {\n\t\t\t\t\t\tif (collected.code === \"image_response_empty\")\n\t\t\t\t\t\t\treturn emptyImageResponse(model, collected.message, response.unrecognizedItems);\n\t\t\t\t\t\treturn failed(model, collected.code, collected.message);\n\t\t\t\t\t}\n\t\t\t\t\tif (collected.length === 0) return emptyImageResponse(model, undefined, response.unrecognizedItems);\n\t\t\t\t\tconst persisted = await persistImages(resolved.workspace, collected);\n\t\t\t\t\tif (!persisted.ok) return imageWriteFailure(model, response, persisted, clientSignal);\n\t\t\t\t\treturn successResult(producedImageResult(persisted.files, model, response), persisted.images);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn failureFrom(error, clientSignal, model, \"Image generation request failed\");\n\t\t\t\t}\n\t\t\t},\n\t\t});\n\t\tapi.registerTool({\n\t\t\tname: \"image_edit\",\n\t\t\tlabel: \"Image edit\",\n\t\t\tcapability: { key: \"generate_image\", requiresSelection: true },\n\t\t\tdescription:\n\t\t\t\t\"Edit a previously generated image (workspace-relative path under generated-images/) with a revision prompt; returns the new file path\",\n\t\t\tparameters: IMAGE_EDIT_PARAMETERS,\n\t\t\texecute: async (first: unknown, second?: unknown, third?: unknown) => {\n\t\t\t\tlet input: Record<string, unknown>;\n\t\t\t\ttry {\n\t\t\t\t\tinput = objectInput(first, second);\n\t\t\t\t} catch {\n\t\t\t\t\treturn failed(\"\", \"invalid_input\", \"Image generation input must be an object\");\n\t\t\t\t}\n\t\t\t\tconst prompt = promptFrom(input.prompt);\n\t\t\t\tif (prompt === undefined)\n\t\t\t\t\treturn failed(\"\", \"invalid_input\", \"prompt must be a non-empty string of at most 4000 characters\");\n\t\t\t\tconst imagePath = typeof input.imagePath === \"string\" ? input.imagePath : undefined;\n\t\t\t\tif (imagePath === undefined || !validImagePath(imagePath))\n\t\t\t\t\treturn failed(\n\t\t\t\t\t\t\"\",\n\t\t\t\t\t\t\"invalid_path\",\n\t\t\t\t\t\t\"imagePath must be a workspace-relative identifier inside the generated-images/ directory (no .. segments)\",\n\t\t\t\t\t);\n\t\t\t\tconst sessionSignal = api.sessionAbortSignal?.();\n\t\t\t\tconst invocationSignal = signalFrom(third);\n\t\t\t\tconst clientSignal = combineSignals([invocationSignal, sessionSignal]);\n\t\t\t\tif (clientSignal?.aborted) return cancelled(\"\");\n\t\t\t\tconst target = resolveTarget();\n\t\t\t\tif (!target.ok) return failed(\"\", \"config_missing\", boundedImageMessageV1(target.message));\n\t\t\t\tconst { provider, model, baseUrl } = target;\n\t\t\t\ttry {\n\t\t\t\t\tconst resolved = await resolveInvocation(api, provider, fetchImpl, model, baseUrl);\n\t\t\t\t\tif (resolved.status === \"failed\") return resolved.result;\n\t\t\t\t\t// Defense in depth (readonly never registers these tools): the\n\t\t\t\t\t// lexical validImagePath gate cannot see symlinks, so refuse any\n\t\t\t\t\t// candidate whose real path escapes the workspace before a byte\n\t\t\t\t\t// is read and shipped to the provider.\n\t\t\t\t\tconst sandbox = await sandboxedImagePath(resolved.workspace, imagePath);\n\t\t\t\t\tif (sandbox === \"missing\")\n\t\t\t\t\t\treturn failed(\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\"image_not_found\",\n\t\t\t\t\t\t\t`image ${imagePath} was not found under the workspace generated-images/ directory`,\n\t\t\t\t\t\t);\n\t\t\t\t\tif (sandbox === \"escape\")\n\t\t\t\t\t\treturn failed(\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\"invalid_path\",\n\t\t\t\t\t\t\t`imagePath ${imagePath} resolves outside the workspace; only files under the workspace generated-images/ directory can be read`,\n\t\t\t\t\t\t);\n\t\t\t\t\t// Size-check before reading: users can drop their own files\n\t\t\t\t\t// into generated-images/, and the 20 MiB download cap must\n\t\t\t\t\t// not be bypassed by a renamed local file.\n\t\t\t\t\tconst sourceStats = await stat(join(resolved.workspace, imagePath)).catch(() => undefined);\n\t\t\t\t\tif (sourceStats === undefined || !sourceStats.isFile())\n\t\t\t\t\t\treturn failed(\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\"image_not_found\",\n\t\t\t\t\t\t\t`image ${imagePath} was not found under the workspace generated-images/ directory`,\n\t\t\t\t\t\t);\n\t\t\t\t\tif (sourceStats.size > IMAGE_GENERATION_MAX_DOWNLOAD_BYTES_V1)\n\t\t\t\t\t\treturn failed(\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\"response_too_large\",\n\t\t\t\t\t\t\t`image ${imagePath} is ${sourceStats.size} bytes, above the 20 MiB limit`,\n\t\t\t\t\t\t);\n\t\t\t\t\tconst source = await readFile(join(resolved.workspace, imagePath)).catch(() => undefined);\n\t\t\t\t\tif (source === undefined)\n\t\t\t\t\t\treturn failed(\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\"image_not_found\",\n\t\t\t\t\t\t\t`image ${imagePath} was not found under the workspace generated-images/ directory`,\n\t\t\t\t\t\t);\n\t\t\t\t\tconst response = await resolved.client.editImage(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\timage: source,\n\t\t\t\t\t\t\t// The edits endpoint accepts png/jpeg/webp inputs; the\n\t\t\t\t\t\t\t// multipart blob must carry the source's real format\n\t\t\t\t\t\t\t// (a prior url-form download may be JPEG).\n\t\t\t\t\t\t\tmimeType: detectImageFormatV1(source).mimeType,\n\t\t\t\t\t\t\tprompt,\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tclientSignal,\n\t\t\t\t\t);\n\t\t\t\t\tconst collected = await collectImages(response, fetchImpl, clientSignal);\n\t\t\t\t\tif (!Array.isArray(collected)) {\n\t\t\t\t\t\tif (collected.code === \"image_response_empty\")\n\t\t\t\t\t\t\treturn emptyImageResponse(model, collected.message, response.unrecognizedItems);\n\t\t\t\t\t\treturn failed(model, collected.code, collected.message);\n\t\t\t\t\t}\n\t\t\t\t\tif (collected.length === 0) return emptyImageResponse(model, undefined, response.unrecognizedItems);\n\t\t\t\t\tconst persisted = await persistImages(resolved.workspace, collected);\n\t\t\t\t\tif (!persisted.ok) return imageWriteFailure(model, response, persisted, clientSignal);\n\t\t\t\t\treturn successResult(producedImageResult(persisted.files, model, response), persisted.images);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn failureFrom(error, clientSignal, model, \"Image edit request failed\");\n\t\t\t\t}\n\t\t\t},\n\t\t});\n\t};\n}\n\n/** HTTP status embedded in the images client's error text (`... failed with status 403: ...`). */\nfunction imageErrorStatus(message: string): number | undefined {\n\tconst match = /failed with status (\\d{3})(?::|$)/u.exec(message);\n\treturn match === null ? undefined : Number(match[1]);\n}\n\nfunction failureFrom(\n\terror: unknown,\n\tsignal: AbortSignal | undefined,\n\tmodel: string,\n\tfallbackMessage: string,\n): ImageGenResultV1 {\n\tif (signal?.aborted) return cancelled(model);\n\tlet message = error instanceof Error ? error.message : fallbackMessage;\n\t// A rejected credential is not a request failure the caller can retry with\n\t// the same key: name it and point at the provider-specific auth entry\n\t// (2026-10-29 round-4 tick 7: the shared gateway key lacks image capability,\n\t// while the dedicated image key succeeds).\n\tconst status = imageErrorStatus(message);\n\tif (status === 401 || status === 403) {\n\t\treturn failed(\n\t\t\tmodel,\n\t\t\t\"credentials_insufficient\",\n\t\t\tboundedImageMessageV1(\n\t\t\t\t`${message} (the configured image-generation credential was rejected${status === 403 ? \" with 403, which usually means this API key has no image capability\" : \"\"}; configure a dedicated image-generation key for the selected provider — auth.json entry for that provider — instead of reusing the main text key)`,\n\t\t\t),\n\t\t);\n\t}\n\t// Append (never replace) a proxy hint for opaque network failures: the\n\t// single most common cause on machines that route out through a VPN.\n\tif (/fetch failed|terminated|ENOTFOUND|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|UND_ERR/u.test(message))\n\t\tmessage = `${message} (if this machine reaches the internet through a proxy, set HTTPS_PROXY/HTTP_PROXY — see the image-generation plugin README)`;\n\treturn failed(model, \"image_request_failed\", boundedImageMessageV1(message));\n}\n"]}
|