@howaboua/pi-durable-imagegen 0.11.0 → 0.13.0

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/NOTICE CHANGED
@@ -234,3 +234,7 @@ distributed under the License is distributed on an "AS IS" BASIS,
234
234
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
235
235
  See the License for the specific language governing permissions and
236
236
  limitations under the License.
237
+
238
+ Selected changes adapted from IgorWarzocha/howaboua-agent-stuff,
239
+ packages/pi-codex-imagegen at e1730759db35bf454d0c86c34a80e63129dd929f.
240
+ See docs/parity.md for the scope of this source sync.
package/README.md CHANGED
@@ -1,9 +1,9 @@
1
1
  # Durable Image Generation
2
2
 
3
- Generate images or edit local and recent conversation images with `imagegen`. Requires Node.js and Pi Durable, pi-ai and Chord 1.5.0, an authenticated Codex-compatible image backend and a conversation ExecutionEnv.
3
+ Generate images or edit local and recent conversation images with `imagegen`. Requires Node.js and Pi Durable, pi-ai and Chord 1.8.0, an authenticated Codex-compatible image backend or an OpenAI API key and a conversation ExecutionEnv.
4
4
 
5
5
  ```sh
6
- npm install https://github.com/IgorWarzocha/pi-durable-components/releases/download/v0.11.0/howaboua-pi-durable-imagegen-0.11.0.tgz
6
+ npm install @howaboua/pi-durable-imagegen@0.13.0
7
7
  ```
8
8
 
9
9
  Install the bundle with your authenticated pi-ai Models collection. Provide a conversation reader if recent-image edits should be available:
@@ -19,12 +19,14 @@ registry.install(createImageGenerationExtension({
19
19
 
20
20
  Configure `Harness.open({ models, registry, env })` with your conversation environment. `createImageGenerationTool` also registers in an ordinary custom extension. Code and Notebook discover the registration without adapters.
21
21
 
22
- Without selectors, the tool generates a new image. Local edits validate PNG, JPEG, GIF or WebP bytes. Recent edits select up to five images from the active model context after edits and compaction. Durable 1.5.0's tool handle does not expose a context reader, so the explicit `conversation` capability is required for that selector. Missing context access fails visibly.
22
+ Without selectors, the tool generates a new image. Local edits validate PNG, JPEG, GIF or WebP bytes. Recent edits select up to five images from the active model context after edits and compaction. Durable 1.8.0's tool handle does not expose a context reader, so the explicit `conversation` capability is required for that selector. Missing context access fails visibly.
23
23
 
24
- Generated images and `latest.png` are saved through ExecutionEnv under the nearest workspace `.git` root in `.pi/openai-codex-images`. Results include paths, image attachments, response metadata and reported usage when present. Billing costs are not invented. Text-only conversation models receive paths without image attachments.
24
+ Generated images and a per-format latest alias are saved through ExecutionEnv under the nearest workspace `.git` root in `.pi/openai-codex-images`. Results include paths, image attachments, response metadata and reported usage when present. Billing costs are not invented. Text-only conversation models receive paths without image attachments.
25
25
 
26
26
  Custom transports accept host-loaded `routes: normalizeCodexToolRouteConfig(config)`, `allowConfiguredProvider` or an explicit `resolveProvider`. The bundle allows Codex auth fallback by default. Requests use `gpt-image-2.5`, automatic size and quality, and an opaque background unless transparency is requested. Network responses are bounded to 64 MiB and proxy routing is checked at every redirect.
27
27
 
28
+ For the OpenAI Images API, set `access: "openai"` and configure the canonical `openai` provider in Models with an API key. This route never falls back to Codex. It adds `size`, `output_format` and GIF frame controls. `api` selects the model, quality and complexity (defaults: `gpt-image-2.6-flare`, `auto`, `high`). GIF and SVG support generation only. SVG stays on disk. For GIF still previews, supply the exported `nativeGifPreview` as `gifPreview`, or grant native execution in the conversation's namespace when using component activation. Without a codec the animation is saved and the result states that no still is available.
29
+
28
30
  Calls execute sequentially and are never replayed automatically after interruption. A lost response can leave the remote outcome unknown. Artifact failure after a successful response is reported separately. Do not automatically repeat either request.
29
31
 
30
32
  See [parity evidence](../../docs/parity/web-imagegen.md) for source revisions and integration boundaries.
@@ -3,7 +3,8 @@ import {
3
3
  defineCapability,
4
4
  isCapabilityObject,
5
5
  modelsCapability,
6
- networkCapability
6
+ networkCapability,
7
+ nodeExecutionCapability
7
8
  } from "@howaboua/pi-durable-components";
8
9
  import { Type as Type2 } from "typebox";
9
10
  import { Check } from "typebox/value";
@@ -248,6 +249,26 @@ var IMAGE_GENERATION_PARAMETERS = Type.Object({
248
249
  Type.Null()
249
250
  ]))
250
251
  }, { additionalProperties: false });
252
+ var openAIParameters = Type.Object({
253
+ ...IMAGE_GENERATION_PARAMETERS.properties,
254
+ output_format: Type.Optional(Type.Union([
255
+ Type.Literal("png"),
256
+ Type.Literal("jpeg"),
257
+ Type.Literal("webp"),
258
+ Type.Literal("gif"),
259
+ Type.Literal("svg")
260
+ ], { description: "GIF/SVG generation only" })),
261
+ size: Type.Optional(Type.String({ description: "auto or WIDTHxHEIGHT, multiples of 16" })),
262
+ gif: Type.Optional(Type.Object({
263
+ frame_count: Type.Optional(Type.Integer({ minimum: 2, maximum: 64 })),
264
+ frame_duration_ms: Type.Optional(Type.Integer({ minimum: 20, maximum: 2000, multipleOf: 10 }))
265
+ }, { additionalProperties: false }))
266
+ }, { additionalProperties: false });
267
+ var defaultApi = {
268
+ model: "gpt-image-2.6-flare",
269
+ quality: "auto",
270
+ complexity: "high"
271
+ };
251
272
 
252
273
  // internal/codex/config.ts
253
274
  function nonEmptyName(value, field) {
@@ -607,107 +628,8 @@ async function resolveCodexToolProvider(current, options, context) {
607
628
  };
608
629
  }
609
630
 
610
- // packages/imagegen/src/artifacts.ts
611
- import { randomUUID } from "node:crypto";
612
- import { getOrThrow } from "@earendil-works/pi-durable/env";
613
- async function workspaceRoot(env, context) {
614
- const cwd = getOrThrow(await env.absolutePath(env.cwd, context));
615
- let current = cwd;
616
- while (true) {
617
- const git = getOrThrow(await env.joinPath([current, ".git"], context));
618
- if (getOrThrow(await env.exists(git, context)))
619
- return current;
620
- const parent = getOrThrow(await env.absolutePath(getOrThrow(await env.joinPath([current, ".."], context)), context));
621
- if (parent === current)
622
- return cwd;
623
- current = parent;
624
- }
625
- }
626
- function decodeBase64Image(value) {
627
- const normalized = value.trim();
628
- if (normalized.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(normalized))
629
- throw new Error("image generation returned invalid base64 data");
630
- const bytes = Buffer.from(normalized, "base64");
631
- if (!bytes.length)
632
- throw new Error("image generation returned empty image data");
633
- return bytes;
634
- }
635
- async function saveGeneratedImages(env, context, response, requestId) {
636
- const root = await workspaceRoot(env, context);
637
- const directory = getOrThrow(await env.joinPath([root, ".pi", "openai-codex-images"], context));
638
- getOrThrow(await env.createDir(directory, { recursive: true }, context));
639
- const latest = getOrThrow(await env.joinPath([directory, "latest.png"], context));
640
- const images = [];
641
- const content = [];
642
- for (const [index, item] of response.data.entries()) {
643
- const bytes = decodeBase64Image(item.b64_json);
644
- const suffix = randomUUID().replaceAll("-", "");
645
- const name = "ig_" + suffix + (index ? "_" + (index + 1) : "") + ".png";
646
- const path = getOrThrow(await env.joinPath([directory, name], context));
647
- getOrThrow(await env.writeFile(path, bytes, context));
648
- if (!index)
649
- getOrThrow(await env.writeFile(latest, bytes, context));
650
- images.push({
651
- path: ".pi/openai-codex-images/" + name,
652
- absolute_path: path,
653
- latest_path: ".pi/openai-codex-images/latest.png",
654
- latest_absolute_path: latest
655
- });
656
- content.push({
657
- type: "image",
658
- mimeType: "image/png",
659
- data: Buffer.from(bytes).toString("base64")
660
- });
661
- }
662
- const first = images[0];
663
- if (!first)
664
- throw new Error("image generation returned no image data");
665
- const output = {
666
- path: first.path,
667
- latest_path: first.latest_path,
668
- images,
669
- ...response.background !== undefined ? { background: response.background } : {},
670
- ...response.background === "transparent" ? { transparent_background: true } : response.background === "opaque" ? { transparent_background: false } : {},
671
- ...response.quality !== undefined ? { quality: response.quality } : {},
672
- ...response.size !== undefined ? { size: response.size } : {},
673
- ...requestId ? { imagegen_request_id: requestId } : {},
674
- ...response.usage !== undefined ? { usage: response.usage } : {}
675
- };
676
- return { output, content };
677
- }
678
-
679
- // packages/imagegen/src/history.ts
680
- function recentConversationImageUrls(messages, count) {
681
- const images = [];
682
- for (let index = messages.length - 1;index >= 0; index--) {
683
- const message = messages[index];
684
- if (!message || !("content" in message))
685
- continue;
686
- const content = message.content;
687
- if (!Array.isArray(content))
688
- continue;
689
- for (let contentIndex = content.length - 1;contentIndex >= 0; contentIndex--) {
690
- const image = imageDataUrl(content[contentIndex]);
691
- if (!image)
692
- continue;
693
- images.push(image);
694
- if (images.length === count)
695
- return images.reverse();
696
- }
697
- }
698
- return images.reverse();
699
- }
700
- function imageDataUrl(value) {
701
- if (!value || typeof value !== "object")
702
- return;
703
- const image = value;
704
- if (image.type !== "image" || typeof image.data !== "string" || image.data.length === 0 || typeof image.mimeType !== "string" || !image.mimeType.startsWith("image/"))
705
- return;
706
- return `data:${image.mimeType};base64,${image.data}`;
707
- }
708
-
709
631
  // packages/imagegen/src/request.ts
710
- import { getOrThrow as getOrThrow2 } from "@earendil-works/pi-durable/env";
632
+ import { getOrThrow } from "@earendil-works/pi-durable/env";
711
633
 
712
634
  // packages/imagegen/src/image-validation.ts
713
635
  var PNG_SIGNATURE = Uint8Array.of(137, 80, 78, 71, 13, 10, 26, 10);
@@ -930,13 +852,13 @@ function validatedImageMime(bytes) {
930
852
  // packages/imagegen/src/request.ts
931
853
  var MAX_IMAGE_BYTES = 1024 * 1024 * 1024;
932
854
  async function localImageDataUrl(value, env, context) {
933
- const path = getOrThrow2(await env.canonicalPath(getOrThrow2(await env.absolutePath(value, context)), context));
934
- const info = getOrThrow2(await env.fileInfo(path, context));
855
+ const path = getOrThrow(await env.canonicalPath(getOrThrow(await env.absolutePath(value, context)), context));
856
+ const info = getOrThrow(await env.fileInfo(path, context));
935
857
  if (info.kind !== "file")
936
858
  throw new Error("edit image is not a file: " + value);
937
859
  if (info.size > MAX_IMAGE_BYTES)
938
860
  throw new Error("edit image exceeds " + MAX_IMAGE_BYTES + " bytes: " + value);
939
- const bytes = getOrThrow2(await env.readBinaryFile(path, context));
861
+ const bytes = getOrThrow(await env.readBinaryFile(path, context));
940
862
  const mime = validatedImageMime(bytes);
941
863
  if (!mime)
942
864
  throw new Error("edit image must be PNG, JPEG, GIF, or WebP: " + value);
@@ -987,6 +909,169 @@ async function buildImageGenerationRequest(args, recentImages, env, context, mod
987
909
  };
988
910
  }
989
911
 
912
+ // packages/imagegen/src/api-request.ts
913
+ function validateImageSize(size, format) {
914
+ if (size === "auto")
915
+ return;
916
+ if (!/^[1-9][0-9]*x[1-9][0-9]*$/.test(size))
917
+ throw new Error("Image size must be auto or WIDTHxHEIGHT.");
918
+ const [width, height] = size.split("x").map(Number);
919
+ if (!width || !height || width % 16 || height % 16 || Math.max(width, height) > 3840 || Math.max(width / height, height / width) > 3)
920
+ throw new Error("Image dimensions: multiples of 16, max 3840 per edge, aspect ratio 1:3 to 3:1.");
921
+ if (format !== "gif" && (width * height < 655360 || width * height > 8294400))
922
+ throw new Error("Still images require 655360 to 8294400 pixels. Use auto or resize within that range.");
923
+ }
924
+ async function buildOpenAIImageRequest(args, recentImages, env, context, settings) {
925
+ const format = args.output_format ?? (args.gif ? "gif" : "png");
926
+ if (args.gif && format !== "gif")
927
+ throw new Error("gif controls require GIF output_format.");
928
+ const background = args.transparent_background ? "transparent" : "opaque";
929
+ if (background === "transparent" && !["png", "webp"].includes(format))
930
+ throw new Error("Use PNG or WebP for transparency, or choose an opaque background.");
931
+ validateImageSize(args.size ?? "auto", format);
932
+ const editing = Boolean(args.referenced_image_paths?.length || args.num_last_images_to_include != null);
933
+ if (editing && ["gif", "svg"].includes(format))
934
+ throw new Error("OpenAI API " + format.toUpperCase() + " output supports generation only. Use PNG, JPEG or WebP for edits.");
935
+ const request = await buildImageGenerationRequest(args, recentImages, env, context, settings.model);
936
+ if (request.operation === "edits") {
937
+ for (const item of request.body.images) {
938
+ if (!/^data:image\/(png|jpeg|webp);base64,/.test(item.image_url))
939
+ throw new Error("OpenAI API edits require PNG, JPEG or WebP inputs. Convert GIFs first.");
940
+ if (item.image_url.length > 20 * 1024 * 1024)
941
+ throw new Error("OpenAI API edit image is too large. Resize or compress it and retry.");
942
+ }
943
+ }
944
+ Object.assign(request.body, {
945
+ background,
946
+ quality: settings.quality,
947
+ complexity: settings.complexity,
948
+ size: args.size ?? "auto",
949
+ n: 1,
950
+ output_format: format
951
+ });
952
+ if (format === "gif")
953
+ Object.assign(request.body, args.gif);
954
+ return request;
955
+ }
956
+
957
+ // packages/imagegen/src/artifacts.ts
958
+ import { randomUUID } from "node:crypto";
959
+ import { getOrThrow as getOrThrow2 } from "@earendil-works/pi-durable/env";
960
+ async function workspaceRoot(env, context) {
961
+ const cwd = getOrThrow2(await env.absolutePath(env.cwd, context));
962
+ let current = cwd;
963
+ while (true) {
964
+ const git = getOrThrow2(await env.joinPath([current, ".git"], context));
965
+ if (getOrThrow2(await env.exists(git, context)))
966
+ return current;
967
+ const parent = getOrThrow2(await env.absolutePath(getOrThrow2(await env.joinPath([current, ".."], context)), context));
968
+ if (parent === current)
969
+ return cwd;
970
+ current = parent;
971
+ }
972
+ }
973
+ function decodeBase64Image(value) {
974
+ const normalized = value.trim();
975
+ if (normalized.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(normalized))
976
+ throw new Error("image generation returned invalid base64 data");
977
+ const bytes = Buffer.from(normalized, "base64");
978
+ if (!bytes.length)
979
+ throw new Error("image generation returned empty image data");
980
+ return bytes;
981
+ }
982
+ async function saveGeneratedImages(env, context, response, requestId, format, preview, includeImages) {
983
+ const mime = format === "svg" ? "image/svg+xml" : "image/" + format;
984
+ const decoded = response.data.map((item) => {
985
+ const bytes = decodeBase64Image(item.b64_json);
986
+ const actual = validatedImageMime(bytes) ?? (/^\s*(?:<\?xml[^>]*>\s*)?(?:<!--[\s\S]*?-->\s*)*<svg(?:\s|>)/.test(Buffer.from(bytes).toString("utf8")) ? "image/svg+xml" : undefined);
987
+ if (actual !== mime)
988
+ throw new Error("Expected " + format.toUpperCase() + " output, got another format. Nothing saved.");
989
+ return bytes;
990
+ });
991
+ if (!decoded.length)
992
+ throw new Error("image generation returned no image data");
993
+ const root = await workspaceRoot(env, context);
994
+ const directory = getOrThrow2(await env.joinPath([root, ".pi", "openai-codex-images"], context));
995
+ getOrThrow2(await env.createDir(directory, { recursive: true }, context));
996
+ const latest = getOrThrow2(await env.joinPath([directory, "latest." + format], context));
997
+ const images = [];
998
+ const content = [];
999
+ for (const [index, bytes] of decoded.entries()) {
1000
+ const suffix = randomUUID().replaceAll("-", "");
1001
+ const name = "ig_" + suffix + (index ? "_" + (index + 1) : "") + "." + format;
1002
+ const path = getOrThrow2(await env.joinPath([directory, name], context));
1003
+ getOrThrow2(await env.writeFile(path, bytes, context));
1004
+ if (!index)
1005
+ getOrThrow2(await env.writeFile(latest, bytes, context));
1006
+ let previewPath;
1007
+ const display = format === "gif" ? await preview?.(bytes, context, env) : format === "svg" ? undefined : bytes;
1008
+ if (format === "gif" && display) {
1009
+ previewPath = getOrThrow2(await env.joinPath([directory, "ig_" + suffix + ".preview.png"], context));
1010
+ getOrThrow2(await env.writeFile(previewPath, display, context));
1011
+ }
1012
+ images.push({
1013
+ mime_type: mime,
1014
+ ...previewPath ? { preview_absolute_path: previewPath } : {},
1015
+ path: ".pi/openai-codex-images/" + name,
1016
+ absolute_path: path,
1017
+ latest_path: ".pi/openai-codex-images/latest." + format,
1018
+ latest_absolute_path: latest
1019
+ });
1020
+ if (display && includeImages)
1021
+ content.push({
1022
+ type: "image",
1023
+ mimeType: format === "gif" ? "image/png" : mime,
1024
+ data: Buffer.from(display).toString("base64")
1025
+ });
1026
+ }
1027
+ const first = images[0];
1028
+ if (!first)
1029
+ throw new Error("image generation returned no image data");
1030
+ const output = {
1031
+ output_format: format,
1032
+ path: first.path,
1033
+ latest_path: first.latest_path,
1034
+ images,
1035
+ ...response.background !== undefined ? { background: response.background } : {},
1036
+ ...response.background === "transparent" ? { transparent_background: true } : response.background === "opaque" ? { transparent_background: false } : {},
1037
+ ...response.quality !== undefined ? { quality: response.quality } : {},
1038
+ ...response.size !== undefined ? { size: response.size } : {},
1039
+ ...requestId ? { imagegen_request_id: requestId } : {},
1040
+ ...response.usage !== undefined ? { usage: response.usage } : {}
1041
+ };
1042
+ return { output, content };
1043
+ }
1044
+
1045
+ // packages/imagegen/src/history.ts
1046
+ function recentConversationImageUrls(messages, count) {
1047
+ const images = [];
1048
+ for (let index = messages.length - 1;index >= 0; index--) {
1049
+ const message = messages[index];
1050
+ if (!message || !("content" in message))
1051
+ continue;
1052
+ const content = message.content;
1053
+ if (!Array.isArray(content))
1054
+ continue;
1055
+ for (let contentIndex = content.length - 1;contentIndex >= 0; contentIndex--) {
1056
+ const image = imageDataUrl(content[contentIndex]);
1057
+ if (!image)
1058
+ continue;
1059
+ images.push(image);
1060
+ if (images.length === count)
1061
+ return images.reverse();
1062
+ }
1063
+ }
1064
+ return images.reverse();
1065
+ }
1066
+ function imageDataUrl(value) {
1067
+ if (!value || typeof value !== "object")
1068
+ return;
1069
+ const image = value;
1070
+ if (image.type !== "image" || typeof image.data !== "string" || image.data.length === 0 || typeof image.mimeType !== "string" || !image.mimeType.startsWith("image/"))
1071
+ return;
1072
+ return `data:${image.mimeType};base64,${image.data}`;
1073
+ }
1074
+
990
1075
  // packages/imagegen/src/execute.ts
991
1076
  function parseImageResponse(text) {
992
1077
  let parsed;
@@ -1022,7 +1107,10 @@ async function executeCodexImageGeneration(args, api, context, options) {
1022
1107
  if (!env)
1023
1108
  throw new Error("imagegen requires a conversation execution environment");
1024
1109
  const current = await callingModel(api, options, context);
1025
- if (!supportsExecutableCodexTool(current, options, true))
1110
+ const openai = options.access === "openai";
1111
+ if (!openai && (args.size || args.gif || args.output_format && args.output_format !== "png"))
1112
+ throw new Error("These output controls require OpenAI API access");
1113
+ if (!openai && !supportsExecutableCodexTool(current, options, true))
1026
1114
  throw new Error(IMAGE_GENERATION_UNSUPPORTED_MESSAGE);
1027
1115
  let recentImages;
1028
1116
  if (args.num_last_images_to_include != null) {
@@ -1033,15 +1121,16 @@ async function executeCodexImageGeneration(args, api, context, options) {
1033
1121
  if (recentImages.length !== args.num_last_images_to_include)
1034
1122
  throw new Error("requested the last " + args.num_last_images_to_include + " conversation images, but only " + recentImages.length + " were available");
1035
1123
  }
1036
- const request = await buildImageGenerationRequest(args, recentImages, env, context, resolveCodexToolModel(options.routes ?? { providers: {} }, current, IMAGE_MODEL));
1037
- const provider = await resolveCodexToolProvider(current, options, context);
1038
- const headers = codexToolProviderHeaders(provider);
1039
- const cookieStore = await options.cookieStore?.(provider, context);
1124
+ const request = openai ? await buildOpenAIImageRequest(args, recentImages, env, context, options.api ?? defaultApi) : await buildImageGenerationRequest(args, recentImages, env, context, resolveCodexToolModel(options.routes ?? { providers: {} }, current, IMAGE_MODEL));
1125
+ const provider = openai ? undefined : await resolveCodexToolProvider(current, options, context);
1126
+ const headers = provider ? codexToolProviderHeaders(provider, options.runtime) : await openAIHeaders(options, context);
1127
+ const cookieStore = provider ? await options.cookieStore?.(provider, context) : undefined;
1040
1128
  headers.set("accept", "application/json");
1041
- headers.set("x-codex-image-turn-id", api.callId);
1129
+ if (provider)
1130
+ headers.set("x-codex-image-turn-id", api.callId);
1042
1131
  let response;
1043
1132
  try {
1044
- response = await fetchCodexTool(provider.baseUrl.replace(/\/+$/, "") + "/images/" + request.operation, {
1133
+ response = await fetchCodexTool((provider?.baseUrl.replace(/\/+$/, "") ?? "https://api.openai.com/v1") + "/images/" + request.operation, {
1045
1134
  method: "POST",
1046
1135
  headers,
1047
1136
  body: JSON.stringify(request.body),
@@ -1062,27 +1151,64 @@ async function executeCodexImageGeneration(args, api, context, options) {
1062
1151
  throw new Error("Image generation failed: HTTP " + response.status);
1063
1152
  }
1064
1153
  try {
1065
- const saved = await saveGeneratedImages(env, context, parseImageResponse(response.text), response.headers.get("x-codex-imagegen-request-id") ?? undefined);
1066
- return {
1067
- ...saved,
1068
- content: current && !current.input.includes("image") ? [] : saved.content
1069
- };
1154
+ return await saveGeneratedImages(env, context, parseImageResponse(response.text), response.headers.get("x-codex-imagegen-request-id") ?? response.headers.get("x-request-id") ?? undefined, args.output_format ?? (args.gif ? "gif" : "png"), options.gifPreview, !current || current.input.includes("image"));
1070
1155
  } catch (error) {
1071
1156
  throw new Error("Image service returned success, but decoding or saving artifacts failed. Do not replay this request: " + (error instanceof Error ? error.message : String(error)), { cause: error });
1072
1157
  }
1073
1158
  }
1159
+ async function openAIHeaders(options, context) {
1160
+ const provider = options.models.getProvider("openai");
1161
+ const canonical = (url) => url?.replace(/\/+$/, "") === "https://api.openai.com/v1";
1162
+ if (!provider || !canonical(provider.baseUrl))
1163
+ throw new Error("OpenAI API access requires a canonical openai provider");
1164
+ const signal = context.abortSignal ? { signal: context.abortSignal } : {};
1165
+ if ((await options.models.checkAuth("openai", signal))?.type !== "api_key")
1166
+ throw new Error("OpenAI Images requires an API key, not a ChatGPT subscription. No Codex request sent");
1167
+ const auth = await options.models.getAuth("openai", context.abortSignal ? { signal: context.abortSignal } : {});
1168
+ if (!auth?.auth.apiKey || auth.auth.baseUrl !== undefined && !canonical(auth.auth.baseUrl))
1169
+ throw new Error("No OpenAI API key for the canonical Images endpoint. No Codex request sent");
1170
+ return new Headers({
1171
+ authorization: "Bearer " + auth.auth.apiKey,
1172
+ "content-type": "application/json"
1173
+ });
1174
+ }
1074
1175
 
1075
1176
  // packages/imagegen/src/output.ts
1076
1177
  function formatImagegenOutput(output) {
1077
- return `Generated image: ${output.path}
1078
- Latest: ${output.latest_path}`;
1178
+ return [
1179
+ `Generated image: ${output.path}`,
1180
+ ...output.latest_path ? [`Latest: ${output.latest_path}`] : [],
1181
+ ...output.output_format === "gif" ? ["Saved animation; image preview is a still frame."] : [],
1182
+ ...output.output_format === "gif" && output.images?.some((image) => !image.preview_absolute_path) ? ["Still preview unavailable; open the saved GIF to view it."] : [],
1183
+ ...output.output_format === "svg" ? ["Saved SVG; no inline preview."] : []
1184
+ ].join(`
1185
+ `);
1079
1186
  }
1187
+ // packages/imagegen/src/gif-preview.ts
1188
+ var nativeGifPreview = async (bytes, context) => {
1189
+ context.abortSignal?.throwIfAborted();
1190
+ const { default: sharp } = await import("sharp");
1191
+ const decoder = sharp(bytes, { animated: false, failOn: "error" });
1192
+ const abort = () => decoder.destroy();
1193
+ context.abortSignal?.addEventListener("abort", abort, { once: true });
1194
+ try {
1195
+ context.abortSignal?.throwIfAborted();
1196
+ return await decoder.png().toBuffer();
1197
+ } catch {
1198
+ context.abortSignal?.throwIfAborted();
1199
+ return;
1200
+ } finally {
1201
+ context.abortSignal?.removeEventListener("abort", abort);
1202
+ decoder.destroy();
1203
+ }
1204
+ };
1205
+
1080
1206
  // packages/imagegen/src/index.ts
1081
1207
  function createImageGenerationTool(options) {
1082
1208
  return defineTool({
1083
1209
  name: IMAGE_GENERATION_TOOL_NAME,
1084
1210
  description: "Generate/edit images; omit selectors to generate",
1085
- parameters: IMAGE_GENERATION_PARAMETERS,
1211
+ parameters: options.access === "openai" ? openAIParameters : IMAGE_GENERATION_PARAMETERS,
1086
1212
  replay: "unsafe",
1087
1213
  executionMode: "sequential",
1088
1214
  async execute(args, api, context) {
@@ -1112,6 +1238,26 @@ function createImageGenerationExtension(options) {
1112
1238
  // packages/imagegen/src/activation.ts
1113
1239
  var imagegenOptions = defineCapability("howaboua.imagegen.options.v1", (value) => isCapabilityObject(value) && isCapabilityObject(value["models"]) && typeof value["models"]["getModel"] === "function" && typeof value["fetch"] === "function" && typeof value["conversation"] === "function");
1114
1240
  var configuration = Type2.Object({
1241
+ access: Type2.Optional(Type2.Union([Type2.Literal("codex"), Type2.Literal("openai")])),
1242
+ api: Type2.Optional(Type2.Object({
1243
+ model: Type2.Union([
1244
+ Type2.Literal("gpt-image-2.6-flare"),
1245
+ Type2.Literal("gpt-image-2.6-sunburst")
1246
+ ]),
1247
+ quality: Type2.Union([
1248
+ Type2.Literal("auto"),
1249
+ Type2.Literal("low"),
1250
+ Type2.Literal("medium"),
1251
+ Type2.Literal("high"),
1252
+ Type2.Literal("xhigh"),
1253
+ Type2.Literal("max")
1254
+ ]),
1255
+ complexity: Type2.Union([
1256
+ Type2.Literal("low"),
1257
+ Type2.Literal("medium"),
1258
+ Type2.Literal("high")
1259
+ ])
1260
+ }, { additionalProperties: false })),
1115
1261
  runtime: Type2.Optional(Type2.Union([Type2.Literal("node"), Type2.Literal("workerd")])),
1116
1262
  allowCodexProviderFallback: Type2.Optional(Type2.Boolean()),
1117
1263
  routes: Type2.Optional(Type2.Unknown())
@@ -1120,8 +1266,14 @@ function baseline(request, conversation) {
1120
1266
  if (!Check(configuration, request.configuration))
1121
1267
  throw new Error("Invalid imagegen configuration");
1122
1268
  const { routes, ...options } = request.configuration;
1269
+ const grant = request.capabilities.has(nodeExecutionCapability.id) ? request.capabilities.get(nodeExecutionCapability) : undefined;
1123
1270
  return {
1124
1271
  ...options,
1272
+ ...grant ? {
1273
+ gifPreview(bytes, context, env) {
1274
+ return grant.environmentId === env.id ? nativeGifPreview(bytes, context, env) : Promise.resolve(undefined);
1275
+ }
1276
+ } : {},
1125
1277
  models: request.capabilities.get(modelsCapability),
1126
1278
  fetch: request.capabilities.get(networkCapability).fetch,
1127
1279
  conversation,
package/dist/index.js CHANGED
@@ -48,6 +48,26 @@ var IMAGE_GENERATION_PARAMETERS = Type.Object({
48
48
  Type.Null()
49
49
  ]))
50
50
  }, { additionalProperties: false });
51
+ var openAIParameters = Type.Object({
52
+ ...IMAGE_GENERATION_PARAMETERS.properties,
53
+ output_format: Type.Optional(Type.Union([
54
+ Type.Literal("png"),
55
+ Type.Literal("jpeg"),
56
+ Type.Literal("webp"),
57
+ Type.Literal("gif"),
58
+ Type.Literal("svg")
59
+ ], { description: "GIF/SVG generation only" })),
60
+ size: Type.Optional(Type.String({ description: "auto or WIDTHxHEIGHT, multiples of 16" })),
61
+ gif: Type.Optional(Type.Object({
62
+ frame_count: Type.Optional(Type.Integer({ minimum: 2, maximum: 64 })),
63
+ frame_duration_ms: Type.Optional(Type.Integer({ minimum: 20, maximum: 2000, multipleOf: 10 }))
64
+ }, { additionalProperties: false }))
65
+ }, { additionalProperties: false });
66
+ var defaultApi = {
67
+ model: "gpt-image-2.6-flare",
68
+ quality: "auto",
69
+ complexity: "high"
70
+ };
51
71
 
52
72
  // internal/codex/config.ts
53
73
  function nonEmptyName(value, field) {
@@ -565,107 +585,8 @@ async function resolveCodexToolProvider(current, options, context) {
565
585
  };
566
586
  }
567
587
 
568
- // packages/imagegen/src/artifacts.ts
569
- import { randomUUID } from "node:crypto";
570
- import { getOrThrow } from "@earendil-works/pi-durable/env";
571
- async function workspaceRoot(env, context) {
572
- const cwd = getOrThrow(await env.absolutePath(env.cwd, context));
573
- let current = cwd;
574
- while (true) {
575
- const git = getOrThrow(await env.joinPath([current, ".git"], context));
576
- if (getOrThrow(await env.exists(git, context)))
577
- return current;
578
- const parent = getOrThrow(await env.absolutePath(getOrThrow(await env.joinPath([current, ".."], context)), context));
579
- if (parent === current)
580
- return cwd;
581
- current = parent;
582
- }
583
- }
584
- function decodeBase64Image(value) {
585
- const normalized = value.trim();
586
- if (normalized.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(normalized))
587
- throw new Error("image generation returned invalid base64 data");
588
- const bytes = Buffer.from(normalized, "base64");
589
- if (!bytes.length)
590
- throw new Error("image generation returned empty image data");
591
- return bytes;
592
- }
593
- async function saveGeneratedImages(env, context, response, requestId) {
594
- const root = await workspaceRoot(env, context);
595
- const directory = getOrThrow(await env.joinPath([root, ".pi", "openai-codex-images"], context));
596
- getOrThrow(await env.createDir(directory, { recursive: true }, context));
597
- const latest = getOrThrow(await env.joinPath([directory, "latest.png"], context));
598
- const images = [];
599
- const content = [];
600
- for (const [index, item] of response.data.entries()) {
601
- const bytes = decodeBase64Image(item.b64_json);
602
- const suffix = randomUUID().replaceAll("-", "");
603
- const name = "ig_" + suffix + (index ? "_" + (index + 1) : "") + ".png";
604
- const path = getOrThrow(await env.joinPath([directory, name], context));
605
- getOrThrow(await env.writeFile(path, bytes, context));
606
- if (!index)
607
- getOrThrow(await env.writeFile(latest, bytes, context));
608
- images.push({
609
- path: ".pi/openai-codex-images/" + name,
610
- absolute_path: path,
611
- latest_path: ".pi/openai-codex-images/latest.png",
612
- latest_absolute_path: latest
613
- });
614
- content.push({
615
- type: "image",
616
- mimeType: "image/png",
617
- data: Buffer.from(bytes).toString("base64")
618
- });
619
- }
620
- const first = images[0];
621
- if (!first)
622
- throw new Error("image generation returned no image data");
623
- const output = {
624
- path: first.path,
625
- latest_path: first.latest_path,
626
- images,
627
- ...response.background !== undefined ? { background: response.background } : {},
628
- ...response.background === "transparent" ? { transparent_background: true } : response.background === "opaque" ? { transparent_background: false } : {},
629
- ...response.quality !== undefined ? { quality: response.quality } : {},
630
- ...response.size !== undefined ? { size: response.size } : {},
631
- ...requestId ? { imagegen_request_id: requestId } : {},
632
- ...response.usage !== undefined ? { usage: response.usage } : {}
633
- };
634
- return { output, content };
635
- }
636
-
637
- // packages/imagegen/src/history.ts
638
- function recentConversationImageUrls(messages, count) {
639
- const images = [];
640
- for (let index = messages.length - 1;index >= 0; index--) {
641
- const message = messages[index];
642
- if (!message || !("content" in message))
643
- continue;
644
- const content = message.content;
645
- if (!Array.isArray(content))
646
- continue;
647
- for (let contentIndex = content.length - 1;contentIndex >= 0; contentIndex--) {
648
- const image = imageDataUrl(content[contentIndex]);
649
- if (!image)
650
- continue;
651
- images.push(image);
652
- if (images.length === count)
653
- return images.reverse();
654
- }
655
- }
656
- return images.reverse();
657
- }
658
- function imageDataUrl(value) {
659
- if (!value || typeof value !== "object")
660
- return;
661
- const image = value;
662
- if (image.type !== "image" || typeof image.data !== "string" || image.data.length === 0 || typeof image.mimeType !== "string" || !image.mimeType.startsWith("image/"))
663
- return;
664
- return `data:${image.mimeType};base64,${image.data}`;
665
- }
666
-
667
588
  // packages/imagegen/src/request.ts
668
- import { getOrThrow as getOrThrow2 } from "@earendil-works/pi-durable/env";
589
+ import { getOrThrow } from "@earendil-works/pi-durable/env";
669
590
 
670
591
  // packages/imagegen/src/image-validation.ts
671
592
  var PNG_SIGNATURE = Uint8Array.of(137, 80, 78, 71, 13, 10, 26, 10);
@@ -888,13 +809,13 @@ function validatedImageMime(bytes) {
888
809
  // packages/imagegen/src/request.ts
889
810
  var MAX_IMAGE_BYTES = 1024 * 1024 * 1024;
890
811
  async function localImageDataUrl(value, env, context) {
891
- const path = getOrThrow2(await env.canonicalPath(getOrThrow2(await env.absolutePath(value, context)), context));
892
- const info = getOrThrow2(await env.fileInfo(path, context));
812
+ const path = getOrThrow(await env.canonicalPath(getOrThrow(await env.absolutePath(value, context)), context));
813
+ const info = getOrThrow(await env.fileInfo(path, context));
893
814
  if (info.kind !== "file")
894
815
  throw new Error("edit image is not a file: " + value);
895
816
  if (info.size > MAX_IMAGE_BYTES)
896
817
  throw new Error("edit image exceeds " + MAX_IMAGE_BYTES + " bytes: " + value);
897
- const bytes = getOrThrow2(await env.readBinaryFile(path, context));
818
+ const bytes = getOrThrow(await env.readBinaryFile(path, context));
898
819
  const mime = validatedImageMime(bytes);
899
820
  if (!mime)
900
821
  throw new Error("edit image must be PNG, JPEG, GIF, or WebP: " + value);
@@ -945,6 +866,169 @@ async function buildImageGenerationRequest(args, recentImages, env, context, mod
945
866
  };
946
867
  }
947
868
 
869
+ // packages/imagegen/src/api-request.ts
870
+ function validateImageSize(size, format) {
871
+ if (size === "auto")
872
+ return;
873
+ if (!/^[1-9][0-9]*x[1-9][0-9]*$/.test(size))
874
+ throw new Error("Image size must be auto or WIDTHxHEIGHT.");
875
+ const [width, height] = size.split("x").map(Number);
876
+ if (!width || !height || width % 16 || height % 16 || Math.max(width, height) > 3840 || Math.max(width / height, height / width) > 3)
877
+ throw new Error("Image dimensions: multiples of 16, max 3840 per edge, aspect ratio 1:3 to 3:1.");
878
+ if (format !== "gif" && (width * height < 655360 || width * height > 8294400))
879
+ throw new Error("Still images require 655360 to 8294400 pixels. Use auto or resize within that range.");
880
+ }
881
+ async function buildOpenAIImageRequest(args, recentImages, env, context, settings) {
882
+ const format = args.output_format ?? (args.gif ? "gif" : "png");
883
+ if (args.gif && format !== "gif")
884
+ throw new Error("gif controls require GIF output_format.");
885
+ const background = args.transparent_background ? "transparent" : "opaque";
886
+ if (background === "transparent" && !["png", "webp"].includes(format))
887
+ throw new Error("Use PNG or WebP for transparency, or choose an opaque background.");
888
+ validateImageSize(args.size ?? "auto", format);
889
+ const editing = Boolean(args.referenced_image_paths?.length || args.num_last_images_to_include != null);
890
+ if (editing && ["gif", "svg"].includes(format))
891
+ throw new Error("OpenAI API " + format.toUpperCase() + " output supports generation only. Use PNG, JPEG or WebP for edits.");
892
+ const request = await buildImageGenerationRequest(args, recentImages, env, context, settings.model);
893
+ if (request.operation === "edits") {
894
+ for (const item of request.body.images) {
895
+ if (!/^data:image\/(png|jpeg|webp);base64,/.test(item.image_url))
896
+ throw new Error("OpenAI API edits require PNG, JPEG or WebP inputs. Convert GIFs first.");
897
+ if (item.image_url.length > 20 * 1024 * 1024)
898
+ throw new Error("OpenAI API edit image is too large. Resize or compress it and retry.");
899
+ }
900
+ }
901
+ Object.assign(request.body, {
902
+ background,
903
+ quality: settings.quality,
904
+ complexity: settings.complexity,
905
+ size: args.size ?? "auto",
906
+ n: 1,
907
+ output_format: format
908
+ });
909
+ if (format === "gif")
910
+ Object.assign(request.body, args.gif);
911
+ return request;
912
+ }
913
+
914
+ // packages/imagegen/src/artifacts.ts
915
+ import { randomUUID } from "node:crypto";
916
+ import { getOrThrow as getOrThrow2 } from "@earendil-works/pi-durable/env";
917
+ async function workspaceRoot(env, context) {
918
+ const cwd = getOrThrow2(await env.absolutePath(env.cwd, context));
919
+ let current = cwd;
920
+ while (true) {
921
+ const git = getOrThrow2(await env.joinPath([current, ".git"], context));
922
+ if (getOrThrow2(await env.exists(git, context)))
923
+ return current;
924
+ const parent = getOrThrow2(await env.absolutePath(getOrThrow2(await env.joinPath([current, ".."], context)), context));
925
+ if (parent === current)
926
+ return cwd;
927
+ current = parent;
928
+ }
929
+ }
930
+ function decodeBase64Image(value) {
931
+ const normalized = value.trim();
932
+ if (normalized.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(normalized))
933
+ throw new Error("image generation returned invalid base64 data");
934
+ const bytes = Buffer.from(normalized, "base64");
935
+ if (!bytes.length)
936
+ throw new Error("image generation returned empty image data");
937
+ return bytes;
938
+ }
939
+ async function saveGeneratedImages(env, context, response, requestId, format, preview, includeImages) {
940
+ const mime = format === "svg" ? "image/svg+xml" : "image/" + format;
941
+ const decoded = response.data.map((item) => {
942
+ const bytes = decodeBase64Image(item.b64_json);
943
+ const actual = validatedImageMime(bytes) ?? (/^\s*(?:<\?xml[^>]*>\s*)?(?:<!--[\s\S]*?-->\s*)*<svg(?:\s|>)/.test(Buffer.from(bytes).toString("utf8")) ? "image/svg+xml" : undefined);
944
+ if (actual !== mime)
945
+ throw new Error("Expected " + format.toUpperCase() + " output, got another format. Nothing saved.");
946
+ return bytes;
947
+ });
948
+ if (!decoded.length)
949
+ throw new Error("image generation returned no image data");
950
+ const root = await workspaceRoot(env, context);
951
+ const directory = getOrThrow2(await env.joinPath([root, ".pi", "openai-codex-images"], context));
952
+ getOrThrow2(await env.createDir(directory, { recursive: true }, context));
953
+ const latest = getOrThrow2(await env.joinPath([directory, "latest." + format], context));
954
+ const images = [];
955
+ const content = [];
956
+ for (const [index, bytes] of decoded.entries()) {
957
+ const suffix = randomUUID().replaceAll("-", "");
958
+ const name = "ig_" + suffix + (index ? "_" + (index + 1) : "") + "." + format;
959
+ const path = getOrThrow2(await env.joinPath([directory, name], context));
960
+ getOrThrow2(await env.writeFile(path, bytes, context));
961
+ if (!index)
962
+ getOrThrow2(await env.writeFile(latest, bytes, context));
963
+ let previewPath;
964
+ const display = format === "gif" ? await preview?.(bytes, context, env) : format === "svg" ? undefined : bytes;
965
+ if (format === "gif" && display) {
966
+ previewPath = getOrThrow2(await env.joinPath([directory, "ig_" + suffix + ".preview.png"], context));
967
+ getOrThrow2(await env.writeFile(previewPath, display, context));
968
+ }
969
+ images.push({
970
+ mime_type: mime,
971
+ ...previewPath ? { preview_absolute_path: previewPath } : {},
972
+ path: ".pi/openai-codex-images/" + name,
973
+ absolute_path: path,
974
+ latest_path: ".pi/openai-codex-images/latest." + format,
975
+ latest_absolute_path: latest
976
+ });
977
+ if (display && includeImages)
978
+ content.push({
979
+ type: "image",
980
+ mimeType: format === "gif" ? "image/png" : mime,
981
+ data: Buffer.from(display).toString("base64")
982
+ });
983
+ }
984
+ const first = images[0];
985
+ if (!first)
986
+ throw new Error("image generation returned no image data");
987
+ const output = {
988
+ output_format: format,
989
+ path: first.path,
990
+ latest_path: first.latest_path,
991
+ images,
992
+ ...response.background !== undefined ? { background: response.background } : {},
993
+ ...response.background === "transparent" ? { transparent_background: true } : response.background === "opaque" ? { transparent_background: false } : {},
994
+ ...response.quality !== undefined ? { quality: response.quality } : {},
995
+ ...response.size !== undefined ? { size: response.size } : {},
996
+ ...requestId ? { imagegen_request_id: requestId } : {},
997
+ ...response.usage !== undefined ? { usage: response.usage } : {}
998
+ };
999
+ return { output, content };
1000
+ }
1001
+
1002
+ // packages/imagegen/src/history.ts
1003
+ function recentConversationImageUrls(messages, count) {
1004
+ const images = [];
1005
+ for (let index = messages.length - 1;index >= 0; index--) {
1006
+ const message = messages[index];
1007
+ if (!message || !("content" in message))
1008
+ continue;
1009
+ const content = message.content;
1010
+ if (!Array.isArray(content))
1011
+ continue;
1012
+ for (let contentIndex = content.length - 1;contentIndex >= 0; contentIndex--) {
1013
+ const image = imageDataUrl(content[contentIndex]);
1014
+ if (!image)
1015
+ continue;
1016
+ images.push(image);
1017
+ if (images.length === count)
1018
+ return images.reverse();
1019
+ }
1020
+ }
1021
+ return images.reverse();
1022
+ }
1023
+ function imageDataUrl(value) {
1024
+ if (!value || typeof value !== "object")
1025
+ return;
1026
+ const image = value;
1027
+ if (image.type !== "image" || typeof image.data !== "string" || image.data.length === 0 || typeof image.mimeType !== "string" || !image.mimeType.startsWith("image/"))
1028
+ return;
1029
+ return `data:${image.mimeType};base64,${image.data}`;
1030
+ }
1031
+
948
1032
  // packages/imagegen/src/execute.ts
949
1033
  function parseImageResponse(text) {
950
1034
  let parsed;
@@ -980,7 +1064,10 @@ async function executeCodexImageGeneration(args, api, context, options) {
980
1064
  if (!env)
981
1065
  throw new Error("imagegen requires a conversation execution environment");
982
1066
  const current = await callingModel(api, options, context);
983
- if (!supportsExecutableCodexTool(current, options, true))
1067
+ const openai = options.access === "openai";
1068
+ if (!openai && (args.size || args.gif || args.output_format && args.output_format !== "png"))
1069
+ throw new Error("These output controls require OpenAI API access");
1070
+ if (!openai && !supportsExecutableCodexTool(current, options, true))
984
1071
  throw new Error(IMAGE_GENERATION_UNSUPPORTED_MESSAGE);
985
1072
  let recentImages;
986
1073
  if (args.num_last_images_to_include != null) {
@@ -991,15 +1078,16 @@ async function executeCodexImageGeneration(args, api, context, options) {
991
1078
  if (recentImages.length !== args.num_last_images_to_include)
992
1079
  throw new Error("requested the last " + args.num_last_images_to_include + " conversation images, but only " + recentImages.length + " were available");
993
1080
  }
994
- const request = await buildImageGenerationRequest(args, recentImages, env, context, resolveCodexToolModel(options.routes ?? { providers: {} }, current, IMAGE_MODEL));
995
- const provider = await resolveCodexToolProvider(current, options, context);
996
- const headers = codexToolProviderHeaders(provider);
997
- const cookieStore = await options.cookieStore?.(provider, context);
1081
+ const request = openai ? await buildOpenAIImageRequest(args, recentImages, env, context, options.api ?? defaultApi) : await buildImageGenerationRequest(args, recentImages, env, context, resolveCodexToolModel(options.routes ?? { providers: {} }, current, IMAGE_MODEL));
1082
+ const provider = openai ? undefined : await resolveCodexToolProvider(current, options, context);
1083
+ const headers = provider ? codexToolProviderHeaders(provider, options.runtime) : await openAIHeaders(options, context);
1084
+ const cookieStore = provider ? await options.cookieStore?.(provider, context) : undefined;
998
1085
  headers.set("accept", "application/json");
999
- headers.set("x-codex-image-turn-id", api.callId);
1086
+ if (provider)
1087
+ headers.set("x-codex-image-turn-id", api.callId);
1000
1088
  let response;
1001
1089
  try {
1002
- response = await fetchCodexTool(provider.baseUrl.replace(/\/+$/, "") + "/images/" + request.operation, {
1090
+ response = await fetchCodexTool((provider?.baseUrl.replace(/\/+$/, "") ?? "https://api.openai.com/v1") + "/images/" + request.operation, {
1003
1091
  method: "POST",
1004
1092
  headers,
1005
1093
  body: JSON.stringify(request.body),
@@ -1020,28 +1108,64 @@ async function executeCodexImageGeneration(args, api, context, options) {
1020
1108
  throw new Error("Image generation failed: HTTP " + response.status);
1021
1109
  }
1022
1110
  try {
1023
- const saved = await saveGeneratedImages(env, context, parseImageResponse(response.text), response.headers.get("x-codex-imagegen-request-id") ?? undefined);
1024
- return {
1025
- ...saved,
1026
- content: current && !current.input.includes("image") ? [] : saved.content
1027
- };
1111
+ return await saveGeneratedImages(env, context, parseImageResponse(response.text), response.headers.get("x-codex-imagegen-request-id") ?? response.headers.get("x-request-id") ?? undefined, args.output_format ?? (args.gif ? "gif" : "png"), options.gifPreview, !current || current.input.includes("image"));
1028
1112
  } catch (error) {
1029
1113
  throw new Error("Image service returned success, but decoding or saving artifacts failed. Do not replay this request: " + (error instanceof Error ? error.message : String(error)), { cause: error });
1030
1114
  }
1031
1115
  }
1116
+ async function openAIHeaders(options, context) {
1117
+ const provider = options.models.getProvider("openai");
1118
+ const canonical = (url) => url?.replace(/\/+$/, "") === "https://api.openai.com/v1";
1119
+ if (!provider || !canonical(provider.baseUrl))
1120
+ throw new Error("OpenAI API access requires a canonical openai provider");
1121
+ const signal = context.abortSignal ? { signal: context.abortSignal } : {};
1122
+ if ((await options.models.checkAuth("openai", signal))?.type !== "api_key")
1123
+ throw new Error("OpenAI Images requires an API key, not a ChatGPT subscription. No Codex request sent");
1124
+ const auth = await options.models.getAuth("openai", context.abortSignal ? { signal: context.abortSignal } : {});
1125
+ if (!auth?.auth.apiKey || auth.auth.baseUrl !== undefined && !canonical(auth.auth.baseUrl))
1126
+ throw new Error("No OpenAI API key for the canonical Images endpoint. No Codex request sent");
1127
+ return new Headers({
1128
+ authorization: "Bearer " + auth.auth.apiKey,
1129
+ "content-type": "application/json"
1130
+ });
1131
+ }
1032
1132
 
1033
1133
  // packages/imagegen/src/output.ts
1034
1134
  function formatImagegenOutput(output) {
1035
- return `Generated image: ${output.path}
1036
- Latest: ${output.latest_path}`;
1135
+ return [
1136
+ `Generated image: ${output.path}`,
1137
+ ...output.latest_path ? [`Latest: ${output.latest_path}`] : [],
1138
+ ...output.output_format === "gif" ? ["Saved animation; image preview is a still frame."] : [],
1139
+ ...output.output_format === "gif" && output.images?.some((image) => !image.preview_absolute_path) ? ["Still preview unavailable; open the saved GIF to view it."] : [],
1140
+ ...output.output_format === "svg" ? ["Saved SVG; no inline preview."] : []
1141
+ ].join(`
1142
+ `);
1037
1143
  }
1144
+ // packages/imagegen/src/gif-preview.ts
1145
+ var nativeGifPreview = async (bytes, context) => {
1146
+ context.abortSignal?.throwIfAborted();
1147
+ const { default: sharp } = await import("sharp");
1148
+ const decoder = sharp(bytes, { animated: false, failOn: "error" });
1149
+ const abort = () => decoder.destroy();
1150
+ context.abortSignal?.addEventListener("abort", abort, { once: true });
1151
+ try {
1152
+ context.abortSignal?.throwIfAborted();
1153
+ return await decoder.png().toBuffer();
1154
+ } catch {
1155
+ context.abortSignal?.throwIfAborted();
1156
+ return;
1157
+ } finally {
1158
+ context.abortSignal?.removeEventListener("abort", abort);
1159
+ decoder.destroy();
1160
+ }
1161
+ };
1038
1162
 
1039
1163
  // packages/imagegen/src/index.ts
1040
1164
  function createImageGenerationTool(options) {
1041
1165
  return defineTool({
1042
1166
  name: IMAGE_GENERATION_TOOL_NAME,
1043
1167
  description: "Generate/edit images; omit selectors to generate",
1044
- parameters: IMAGE_GENERATION_PARAMETERS,
1168
+ parameters: options.access === "openai" ? openAIParameters : IMAGE_GENERATION_PARAMETERS,
1045
1169
  replay: "unsafe",
1046
1170
  executionMode: "sequential",
1047
1171
  async execute(args, api, context) {
@@ -1071,5 +1195,6 @@ export {
1071
1195
  IMAGE_GENERATION_PARAMETERS,
1072
1196
  createImageGenerationExtension,
1073
1197
  createImageGenerationTool,
1198
+ nativeGifPreview,
1074
1199
  normalizeCodexToolRouteConfig
1075
1200
  };
@@ -1,4 +1,4 @@
1
- import type { Context } from "@earendil-works/chord";
1
+ import type { Context } from "@earendil-works/chord/context";
2
2
  import { type ToolExecutionApi } from "@earendil-works/pi-durable";
3
3
  import type { CodexRuntimeOptions } from "./types.ts";
4
4
  export declare function callingModel(api: ToolExecutionApi, options: CodexRuntimeOptions, context: Context): Promise<import("@earendil-works/pi-ai").Model<import("@earendil-works/pi-ai").Api> | undefined>;
@@ -1,3 +1,3 @@
1
- import type { JsonValue } from "@earendil-works/chord";
1
+ import type { JsonValue } from "@earendil-works/chord/json";
2
2
  /** Keep tool details within Durable's persisted JSON contract. */
3
3
  export declare function jsonValue(value: unknown): JsonValue;
@@ -1,4 +1,4 @@
1
- import type { Context } from "@earendil-works/chord";
1
+ import type { Context } from "@earendil-works/chord/context";
2
2
  import { type CodexModel, type CodexRuntimeOptions, type CodexToolProvider } from "./types.ts";
3
3
  export declare function supportsExecutableCodexTool(model: CodexModel | undefined, options: CodexRuntimeOptions, images?: boolean): boolean;
4
4
  export declare function resolveCodexToolProvider(current: CodexModel | undefined, options: CodexRuntimeOptions, context: Context): Promise<CodexToolProvider>;
@@ -1,4 +1,4 @@
1
- import type { Context } from "@earendil-works/chord";
1
+ import type { Context } from "@earendil-works/chord/context";
2
2
  import type { Api, Model, Models, ProviderHeaders } from "@earendil-works/pi-ai";
3
3
  import type { CodexToolRouteConfig } from "./config.ts";
4
4
  export declare const CODEX_TOOL_PROVIDER_UNSUPPORTED_MESSAGE = "Codex-backed tool requires an OpenAI Codex-compatible Responses provider";
@@ -0,0 +1,5 @@
1
+ import type { Context } from "@earendil-works/chord/context";
2
+ import type { ExecutionEnv } from "@earendil-works/pi-durable/env";
3
+ import type { ImagegenApiSettings, ImagegenArgs } from "./contract.ts";
4
+ import { buildImageGenerationRequest } from "./request.ts";
5
+ export declare function buildOpenAIImageRequest(args: ImagegenArgs, recentImages: string[] | undefined, env: ExecutionEnv, context: Context, settings: ImagegenApiSettings): ReturnType<typeof buildImageGenerationRequest>;
@@ -1,8 +1,9 @@
1
- import type { Context } from "@earendil-works/chord";
1
+ import type { Context } from "@earendil-works/chord/context";
2
2
  import { type ExecutionEnv } from "@earendil-works/pi-durable/env";
3
- import type { ImageResponse } from "./contract.ts";
3
+ import type { ImageResponse, OutputFormat } from "./contract.ts";
4
4
  import type { ImagegenOutput } from "./output.ts";
5
- export declare function saveGeneratedImages(env: ExecutionEnv, context: Context, response: ImageResponse, requestId: string | undefined): Promise<{
5
+ export type GifPreview = (bytes: Uint8Array, context: Context, environment: ExecutionEnv) => Promise<Uint8Array | undefined>;
6
+ export declare function saveGeneratedImages(env: ExecutionEnv, context: Context, response: ImageResponse, requestId: string | undefined, format: OutputFormat, preview: GifPreview | undefined, includeImages: boolean): Promise<{
6
7
  output: ImagegenOutput;
7
8
  content: {
8
9
  type: "image";
@@ -1,4 +1,4 @@
1
- import type { JsonValue } from "@earendil-works/chord";
1
+ import type { JsonValue } from "@earendil-works/chord/json";
2
2
  import { Type } from "typebox";
3
3
  export declare const IMAGE_GENERATION_TOOL_NAME = "imagegen";
4
4
  export declare const IMAGE_GENERATION_UNSUPPORTED_MESSAGE = "imagegen requires an image-capable OpenAI Codex-compatible Responses provider";
@@ -10,7 +10,32 @@ export declare const IMAGE_GENERATION_PARAMETERS: Type.TObject<{
10
10
  referenced_image_paths: Type.TOptional<Type.TUnion<[Type.TArray<Type.TString>, Type.TNull]>>;
11
11
  num_last_images_to_include: Type.TOptional<Type.TUnion<[Type.TInteger, Type.TNull]>>;
12
12
  }>;
13
+ export declare const openAIParameters: Type.TObject<{
14
+ prompt: Type.TString;
15
+ transparent_background: Type.TOptional<Type.TBoolean>;
16
+ referenced_image_paths: Type.TOptional<Type.TUnion<[Type.TArray<Type.TString>, Type.TNull]>>;
17
+ num_last_images_to_include: Type.TOptional<Type.TUnion<[Type.TInteger, Type.TNull]>>;
18
+ output_format: Type.TOptional<Type.TUnion<[Type.TLiteral<"png">, Type.TLiteral<"jpeg">, Type.TLiteral<"webp">, Type.TLiteral<"gif">, Type.TLiteral<"svg">]>>;
19
+ size: Type.TOptional<Type.TString>;
20
+ gif: Type.TOptional<Type.TObject<{
21
+ frame_count: Type.TOptional<Type.TInteger>;
22
+ frame_duration_ms: Type.TOptional<Type.TInteger>;
23
+ }>>;
24
+ }>;
25
+ export type OutputFormat = "png" | "jpeg" | "webp" | "gif" | "svg";
26
+ export interface ImagegenApiSettings {
27
+ model: "gpt-image-2.6-flare" | "gpt-image-2.6-sunburst";
28
+ quality: "auto" | "low" | "medium" | "high" | "xhigh" | "max";
29
+ complexity: "low" | "medium" | "high";
30
+ }
31
+ export declare const defaultApi: ImagegenApiSettings;
13
32
  export interface ImagegenArgs {
33
+ output_format?: OutputFormat;
34
+ size?: string;
35
+ gif?: {
36
+ frame_count?: number;
37
+ frame_duration_ms?: number;
38
+ };
14
39
  prompt: string;
15
40
  transparent_background?: boolean;
16
41
  referenced_image_paths?: string[] | null;
@@ -1,9 +1,13 @@
1
- import type { Context } from "@earendil-works/chord";
1
+ import type { Context } from "@earendil-works/chord/context";
2
2
  import type { Conversation, ConversationId, ToolExecutionApi } from "@earendil-works/pi-durable";
3
3
  import type { CodexCookieStore } from "../../../internal/codex/cloudflare-cookies.ts";
4
4
  import type { CodexRuntimeOptions, CodexToolProvider } from "../../../internal/codex/types.ts";
5
- import { type ImagegenArgs } from "./contract.ts";
5
+ import { type GifPreview } from "./artifacts.ts";
6
+ import { type ImagegenApiSettings, type ImagegenArgs } from "./contract.ts";
6
7
  export interface ImageGenerationToolOptions extends CodexRuntimeOptions {
8
+ access?: "openai" | "codex";
9
+ api?: ImagegenApiSettings;
10
+ gifPreview?: GifPreview;
7
11
  /** Explicit host-owned egress; omitted by existing native callers. */
8
12
  fetch?: typeof globalThis.fetch;
9
13
  runtime?: "node" | "workerd";
@@ -0,0 +1,3 @@
1
+ import type { GifPreview } from "./artifacts.ts";
2
+ /** Explicit native codec. Decode the first frame only; never open an artifact path. */
3
+ export declare const nativeGifPreview: GifPreview;
@@ -3,16 +3,17 @@ export { normalizeCodexToolRouteConfig } from "../../../internal/codex/config.ts
3
3
  export type { CodexRuntimeOptions, CodexToolProvider, } from "../../../internal/codex/types.ts";
4
4
  export { IMAGE_GENERATION_PARAMETERS } from "./contract.ts";
5
5
  export type { ImageGenerationToolOptions } from "./execute.ts";
6
+ export { nativeGifPreview } from "./gif-preview.ts";
6
7
  export type { ImagegenOutput } from "./output.ts";
7
8
  export declare function createImageGenerationTool(options: ImageGenerationToolOptions): import("@earendil-works/pi-durable").ToolRegistration<import("typebox").TObject<{
8
9
  prompt: import("typebox").TString;
9
10
  transparent_background: import("typebox").TOptional<import("typebox").TBoolean>;
10
11
  referenced_image_paths: import("typebox").TOptional<import("typebox").TUnion<[import("typebox").TArray<import("typebox").TString>, import("typebox").TNull]>>;
11
12
  num_last_images_to_include: import("typebox").TOptional<import("typebox").TUnion<[import("typebox").TInteger, import("typebox").TNull]>>;
12
- }>, import("@earendil-works/chord").JsonValue>;
13
+ }>, import("@earendil-works/chord/json").JsonValue, import("@earendil-works/chord/json").JsonValue>;
13
14
  export declare function createImageGenerationExtension(options: ImageGenerationToolOptions): import("@earendil-works/pi-durable").Extension<import("@earendil-works/pi-durable").ToolRegistration<import("typebox").TObject<{
14
15
  prompt: import("typebox").TString;
15
16
  transparent_background: import("typebox").TOptional<import("typebox").TBoolean>;
16
17
  referenced_image_paths: import("typebox").TOptional<import("typebox").TUnion<[import("typebox").TArray<import("typebox").TString>, import("typebox").TNull]>>;
17
18
  num_last_images_to_include: import("typebox").TOptional<import("typebox").TUnion<[import("typebox").TInteger, import("typebox").TNull]>>;
18
- }>, import("@earendil-works/chord").JsonValue>>;
19
+ }>, import("@earendil-works/chord/json").JsonValue, import("@earendil-works/chord/json").JsonValue>>;
@@ -1,11 +1,14 @@
1
- import type { JsonValue } from "@earendil-works/chord";
1
+ import type { JsonValue } from "@earendil-works/chord/json";
2
2
  export interface SavedImage {
3
+ mime_type?: string;
4
+ preview_absolute_path?: string;
3
5
  path: string;
4
6
  absolute_path: string;
5
7
  latest_path: string;
6
8
  latest_absolute_path: string;
7
9
  }
8
10
  export type ImagegenOutput = {
11
+ output_format?: string;
9
12
  path: string;
10
13
  latest_path: string;
11
14
  images: SavedImage[];
@@ -1,7 +1,23 @@
1
- import type { Context } from "@earendil-works/chord";
1
+ import type { Context } from "@earendil-works/chord/context";
2
2
  import { type ExecutionEnv } from "@earendil-works/pi-durable/env";
3
3
  import { type ImagegenArgs } from "./contract.ts";
4
- export declare function buildImageGenerationRequest(args: ImagegenArgs, recentImages: string[] | undefined, env: ExecutionEnv, context: Context, model?: string): Promise<{
5
- operation: "generations" | "edits";
6
- body: Record<string, unknown>;
7
- }>;
4
+ interface ImageRequestBody extends Record<string, unknown> {
5
+ prompt: string;
6
+ model: string;
7
+ background: string;
8
+ quality: string;
9
+ size: string;
10
+ }
11
+ type ImageRequest = {
12
+ operation: "generations";
13
+ body: ImageRequestBody;
14
+ } | {
15
+ operation: "edits";
16
+ body: ImageRequestBody & {
17
+ images: Array<{
18
+ image_url: string;
19
+ }>;
20
+ };
21
+ };
22
+ export declare function buildImageGenerationRequest(args: ImagegenArgs, recentImages: string[] | undefined, env: ExecutionEnv, context: Context, model?: string): Promise<ImageRequest>;
23
+ export {};
@@ -7,6 +7,8 @@ function saved(value) {
7
7
  return {
8
8
  path: string(image["path"]),
9
9
  absolute_path: string(image["absolute_path"]),
10
+ ...image["mime_type"] === undefined ? {} : { mime_type: string(image["mime_type"]) },
11
+ ...image["preview_absolute_path"] === undefined ? {} : { preview_absolute_path: string(image["preview_absolute_path"]) },
10
12
  latest_path: string(image["latest_path"]),
11
13
  latest_absolute_path: string(image["latest_absolute_path"])
12
14
  };
@@ -36,6 +38,8 @@ function parseState(value) {
36
38
  throw new TypeError("Invalid transparency");
37
39
  detail.transparent_background = output["transparent_background"];
38
40
  }
41
+ if (output["output_format"] !== undefined)
42
+ detail.output_format = string(output["output_format"]);
39
43
  if (output["imagegen_request_id"] !== undefined)
40
44
  detail.imagegen_request_id = string(output["imagegen_request_id"]);
41
45
  if (output["usage"] !== undefined) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howaboua/pi-durable-imagegen",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "description": "Codex image generation and editing for Pi Durable",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -37,16 +37,17 @@
37
37
  ],
38
38
  "sideEffects": false,
39
39
  "dependencies": {
40
+ "sharp": "0.35.6",
40
41
  "proxy-from-env": "2.1.0",
41
- "undici": "8.10.2",
42
- "typebox": "1.3.27",
43
- "@howaboua/pi-durable-components": "0.11.0"
42
+ "undici": "8.14.0",
43
+ "typebox": "1.4.7",
44
+ "@howaboua/pi-durable-components": "0.13.0"
44
45
  },
45
46
  "peerDependencies": {
46
- "@earendil-works/chord": "1.5.0",
47
- "@earendil-works/pi-ai": "1.5.0",
48
- "@earendil-works/pi-durable": "1.5.0",
49
- "@modelcontextprotocol/sdk": ">=1.25.2 <2"
47
+ "@earendil-works/chord": "1.8.0",
48
+ "@earendil-works/pi-ai": "1.8.0",
49
+ "@earendil-works/pi-durable": "1.8.0",
50
+ "@modelcontextprotocol/sdk": ">=1.32.2 <2"
50
51
  },
51
52
  "publishConfig": {
52
53
  "access": "public"