@howaboua/pi-durable-imagegen 0.9.1 → 0.11.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/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.
|
|
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.
|
|
4
4
|
|
|
5
5
|
```sh
|
|
6
|
-
npm install https://github.com/IgorWarzocha/pi-durable-components/releases/download/v0.
|
|
6
|
+
npm install https://github.com/IgorWarzocha/pi-durable-components/releases/download/v0.11.0/howaboua-pi-durable-imagegen-0.11.0.tgz
|
|
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,7 +19,7 @@ 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.
|
|
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.
|
|
23
23
|
|
|
24
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.
|
|
25
25
|
|
|
@@ -0,0 +1,1161 @@
|
|
|
1
|
+
// packages/imagegen/src/activation.ts
|
|
2
|
+
import {
|
|
3
|
+
defineCapability,
|
|
4
|
+
isCapabilityObject,
|
|
5
|
+
modelsCapability,
|
|
6
|
+
networkCapability
|
|
7
|
+
} from "@howaboua/pi-durable-components";
|
|
8
|
+
import { Type as Type2 } from "typebox";
|
|
9
|
+
import { Check } from "typebox/value";
|
|
10
|
+
|
|
11
|
+
// internal/codex/cloudflare-cookies.ts
|
|
12
|
+
var MAX_COOKIE_STATE_BYTES = 64 * 1024;
|
|
13
|
+
var MAX_COOKIES = 64;
|
|
14
|
+
var EXACT_HOSTS = new Set([
|
|
15
|
+
"chatgpt.com",
|
|
16
|
+
"chat.openai.com",
|
|
17
|
+
"chatgpt-staging.com"
|
|
18
|
+
]);
|
|
19
|
+
var EXACT_COOKIE_NAMES = new Set([
|
|
20
|
+
"__cf_bm",
|
|
21
|
+
"__cflb",
|
|
22
|
+
"__cfruid",
|
|
23
|
+
"__cfseq",
|
|
24
|
+
"__cfwaitingroom",
|
|
25
|
+
"_cfuvid",
|
|
26
|
+
"cf_clearance",
|
|
27
|
+
"cf_ob_info",
|
|
28
|
+
"cf_use_ob"
|
|
29
|
+
]);
|
|
30
|
+
function isChatGptCookieUrl(url) {
|
|
31
|
+
return url.protocol === "https:" && isChatGptHost(url.hostname);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
class ChatGptCloudflareCookieStore {
|
|
35
|
+
cookies = new Map;
|
|
36
|
+
constructor(snapshot = []) {
|
|
37
|
+
if (!Array.isArray(snapshot) || snapshot.length > MAX_COOKIES || new TextEncoder().encode(JSON.stringify(snapshot)).byteLength > MAX_COOKIE_STATE_BYTES)
|
|
38
|
+
throw new Error("Invalid stored ChatGPT cookie state");
|
|
39
|
+
for (const value of snapshot) {
|
|
40
|
+
if (!value || typeof value !== "object" || typeof value.name !== "string" || !isAllowedCookieName(value.name) || typeof value.value !== "string" || !validCookieValue(value.value) || typeof value.domain !== "string" || !isAllowedCookieDomain(value.domain) || typeof value.hostOnly !== "boolean" || typeof value.path !== "string" || !value.path.startsWith("/") || value.expiresAt !== undefined && (typeof value.expiresAt !== "number" || !Number.isFinite(value.expiresAt)))
|
|
41
|
+
throw new Error("Invalid stored ChatGPT cookie state");
|
|
42
|
+
const cookie = {
|
|
43
|
+
name: value.name,
|
|
44
|
+
value: value.value,
|
|
45
|
+
domain: value.domain,
|
|
46
|
+
hostOnly: value.hostOnly,
|
|
47
|
+
path: value.path,
|
|
48
|
+
...value.expiresAt === undefined ? {} : { expiresAt: value.expiresAt }
|
|
49
|
+
};
|
|
50
|
+
this.cookies.set(cookieKey(cookie), cookie);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
snapshot() {
|
|
54
|
+
this.removeExpired();
|
|
55
|
+
return [...this.cookies.values()].map((cookie) => ({ ...cookie }));
|
|
56
|
+
}
|
|
57
|
+
removeExpired() {
|
|
58
|
+
const now = Date.now();
|
|
59
|
+
for (const [key, cookie] of this.cookies)
|
|
60
|
+
if (cookie.expiresAt !== undefined && cookie.expiresAt <= now)
|
|
61
|
+
this.cookies.delete(key);
|
|
62
|
+
}
|
|
63
|
+
requestHeader(url) {
|
|
64
|
+
if (!isChatGptCookieUrl(url))
|
|
65
|
+
return;
|
|
66
|
+
this.removeExpired();
|
|
67
|
+
const matches = [];
|
|
68
|
+
for (const cookie of this.cookies.values()) {
|
|
69
|
+
if ((cookie.hostOnly ? url.hostname === cookie.domain : domainMatches(url.hostname, cookie.domain)) && pathMatches(url.pathname, cookie.path))
|
|
70
|
+
matches.push(cookie);
|
|
71
|
+
}
|
|
72
|
+
matches.sort((left, right) => right.path.length - left.path.length);
|
|
73
|
+
return matches.length ? matches.map((cookie) => cookie.name + "=" + cookie.value).join("; ") : undefined;
|
|
74
|
+
}
|
|
75
|
+
storeResponse(url, setCookieHeaders) {
|
|
76
|
+
if (!isChatGptCookieUrl(url))
|
|
77
|
+
return;
|
|
78
|
+
const candidate = new ChatGptCloudflareCookieStore(this.snapshot());
|
|
79
|
+
for (const header of setCookieHeaders)
|
|
80
|
+
candidate.storeCookie(url, header);
|
|
81
|
+
candidate.removeExpired();
|
|
82
|
+
if (candidate.cookies.size > MAX_COOKIES || new TextEncoder().encode(JSON.stringify([...candidate.cookies.values()])).byteLength > MAX_COOKIE_STATE_BYTES)
|
|
83
|
+
throw new Error("ChatGPT cookie state exceeded 65536 bytes");
|
|
84
|
+
this.cookies.clear();
|
|
85
|
+
for (const [key, cookie] of candidate.cookies)
|
|
86
|
+
this.cookies.set(key, cookie);
|
|
87
|
+
}
|
|
88
|
+
storeCookie(url, header) {
|
|
89
|
+
const parts = header.split(";");
|
|
90
|
+
const pair = parts.shift()?.trim();
|
|
91
|
+
const separator = pair?.indexOf("=") ?? -1;
|
|
92
|
+
if (!pair || separator <= 0)
|
|
93
|
+
return;
|
|
94
|
+
const name = pair.slice(0, separator).trim();
|
|
95
|
+
if (!isAllowedCookieName(name))
|
|
96
|
+
return;
|
|
97
|
+
const value = pair.slice(separator + 1).trim();
|
|
98
|
+
if (value && !validCookieValue(value))
|
|
99
|
+
throw new Error("Invalid ChatGPT response cookie");
|
|
100
|
+
let domain = url.hostname;
|
|
101
|
+
let hostOnly = true;
|
|
102
|
+
let path = "/";
|
|
103
|
+
let expiresAt;
|
|
104
|
+
let maxAge;
|
|
105
|
+
for (const part of parts) {
|
|
106
|
+
const [rawName, ...rawValue] = part.trim().split("=");
|
|
107
|
+
const attribute = rawName?.toLowerCase();
|
|
108
|
+
const attributeValue = rawValue.join("=").trim();
|
|
109
|
+
if (attribute === "domain" && attributeValue) {
|
|
110
|
+
const candidate = attributeValue.replace(/^\./, "").toLowerCase();
|
|
111
|
+
if (!isAllowedCookieDomain(candidate) || !domainMatches(url.hostname, candidate))
|
|
112
|
+
return;
|
|
113
|
+
domain = candidate;
|
|
114
|
+
hostOnly = false;
|
|
115
|
+
} else if (attribute === "path" && attributeValue.startsWith("/")) {
|
|
116
|
+
path = attributeValue;
|
|
117
|
+
} else if (attribute === "max-age" && /^-?\d+$/.test(attributeValue)) {
|
|
118
|
+
maxAge = Number(attributeValue);
|
|
119
|
+
if (!Number.isFinite(maxAge) || !Number.isFinite(Date.now() + maxAge * 1000))
|
|
120
|
+
throw new Error("Invalid ChatGPT response cookie expiry");
|
|
121
|
+
} else if (attribute === "expires" && attributeValue) {
|
|
122
|
+
const parsed = Date.parse(attributeValue);
|
|
123
|
+
if (Number.isFinite(parsed))
|
|
124
|
+
expiresAt = parsed;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (maxAge !== undefined)
|
|
128
|
+
expiresAt = Date.now() + maxAge * 1000;
|
|
129
|
+
const key = cookieKey({ domain, path, name, hostOnly });
|
|
130
|
+
if (!value || expiresAt !== undefined && expiresAt <= Date.now()) {
|
|
131
|
+
this.cookies.delete(key);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
this.cookies.set(key, { name, value, domain, hostOnly, path, expiresAt });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
function cookieKey(cookie) {
|
|
138
|
+
return [
|
|
139
|
+
cookie.domain,
|
|
140
|
+
cookie.path,
|
|
141
|
+
cookie.name,
|
|
142
|
+
cookie.hostOnly ? "host" : "domain"
|
|
143
|
+
].join(`
|
|
144
|
+
`);
|
|
145
|
+
}
|
|
146
|
+
function validCookieValue(value) {
|
|
147
|
+
if (!value.length)
|
|
148
|
+
return false;
|
|
149
|
+
const inner = value.startsWith('"') && value.endsWith('"') ? value.slice(1, -1) : value;
|
|
150
|
+
return /^[\x21-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/.test(inner);
|
|
151
|
+
}
|
|
152
|
+
function isChatGptHost(host) {
|
|
153
|
+
const normalized = host.toLowerCase();
|
|
154
|
+
return EXACT_HOSTS.has(normalized) || normalized.endsWith(".chatgpt.com") || normalized.endsWith(".chatgpt-staging.com");
|
|
155
|
+
}
|
|
156
|
+
function isAllowedCookieName(name) {
|
|
157
|
+
return /^[!#$%&'*+\-.^_`|~0-9a-zA-Z]+$/.test(name) && (EXACT_COOKIE_NAMES.has(name) || name.startsWith("cf_chl_"));
|
|
158
|
+
}
|
|
159
|
+
function isAllowedCookieDomain(domain) {
|
|
160
|
+
return domain === "openai.com" || isChatGptHost(domain);
|
|
161
|
+
}
|
|
162
|
+
function domainMatches(host, domain) {
|
|
163
|
+
return host === domain || host.endsWith("." + domain);
|
|
164
|
+
}
|
|
165
|
+
function pathMatches(requestPath, cookiePath) {
|
|
166
|
+
return requestPath === cookiePath || requestPath.startsWith(cookiePath.endsWith("/") ? cookiePath : cookiePath + "/");
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// internal/codex/component-cookies.ts
|
|
170
|
+
var MAX_SESSIONS = 64;
|
|
171
|
+
function createComponentCookieStores() {
|
|
172
|
+
const sessions = new Map;
|
|
173
|
+
let closed = false;
|
|
174
|
+
return {
|
|
175
|
+
forProvider(provider) {
|
|
176
|
+
if (closed)
|
|
177
|
+
throw new Error("Component cookie stores are closed");
|
|
178
|
+
const key = JSON.stringify([
|
|
179
|
+
provider.route,
|
|
180
|
+
provider.accountId,
|
|
181
|
+
provider.token,
|
|
182
|
+
...[provider.baseUrl, provider.responsesUrl, provider.searchUrl].map((url) => new URL(url).origin)
|
|
183
|
+
]);
|
|
184
|
+
const store = sessions.get(key) ?? new ChatGptCloudflareCookieStore;
|
|
185
|
+
sessions.delete(key);
|
|
186
|
+
sessions.set(key, store);
|
|
187
|
+
while (sessions.size > MAX_SESSIONS) {
|
|
188
|
+
const oldest = sessions.keys().next().value;
|
|
189
|
+
if (oldest !== undefined)
|
|
190
|
+
sessions.delete(oldest);
|
|
191
|
+
}
|
|
192
|
+
return store;
|
|
193
|
+
},
|
|
194
|
+
close() {
|
|
195
|
+
closed = true;
|
|
196
|
+
sessions.clear();
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// packages/imagegen/src/index.ts
|
|
202
|
+
import { defineExtension, defineTool } from "@earendil-works/pi-durable";
|
|
203
|
+
|
|
204
|
+
// internal/codex/json.ts
|
|
205
|
+
function jsonValue(value) {
|
|
206
|
+
if (value === null || typeof value === "string" || typeof value === "boolean")
|
|
207
|
+
return value;
|
|
208
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
209
|
+
return value;
|
|
210
|
+
if (Array.isArray(value))
|
|
211
|
+
return value.map(jsonValue);
|
|
212
|
+
if (value && typeof value === "object") {
|
|
213
|
+
const result = {};
|
|
214
|
+
for (const [key, item] of Object.entries(value))
|
|
215
|
+
if (item !== undefined)
|
|
216
|
+
result[key] = jsonValue(item);
|
|
217
|
+
return result;
|
|
218
|
+
}
|
|
219
|
+
throw new Error("Tool response contains non-JSON data");
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// packages/imagegen/src/contract.ts
|
|
223
|
+
import { Type } from "typebox";
|
|
224
|
+
var IMAGE_GENERATION_TOOL_NAME = "imagegen";
|
|
225
|
+
var IMAGE_GENERATION_UNSUPPORTED_MESSAGE = "imagegen requires an image-capable OpenAI Codex-compatible Responses provider";
|
|
226
|
+
var IMAGE_MODEL = "gpt-image-2.5";
|
|
227
|
+
var MAX_EDIT_IMAGES = 5;
|
|
228
|
+
var IMAGE_GENERATION_PARAMETERS = Type.Object({
|
|
229
|
+
prompt: Type.String({
|
|
230
|
+
description: "Include target aspect ratio and quality"
|
|
231
|
+
}),
|
|
232
|
+
transparent_background: Type.Optional(Type.Boolean({
|
|
233
|
+
description: "True for transparency or cutouts; for edits preserve existing transparency unless asked to change it"
|
|
234
|
+
})),
|
|
235
|
+
referenced_image_paths: Type.Optional(Type.Union([
|
|
236
|
+
Type.Array(Type.String(), {
|
|
237
|
+
description: "Local edit targets",
|
|
238
|
+
maxItems: MAX_EDIT_IMAGES
|
|
239
|
+
}),
|
|
240
|
+
Type.Null()
|
|
241
|
+
])),
|
|
242
|
+
num_last_images_to_include: Type.Optional(Type.Union([
|
|
243
|
+
Type.Integer({
|
|
244
|
+
description: "Smallest recent edit count",
|
|
245
|
+
minimum: 1,
|
|
246
|
+
maximum: MAX_EDIT_IMAGES
|
|
247
|
+
}),
|
|
248
|
+
Type.Null()
|
|
249
|
+
]))
|
|
250
|
+
}, { additionalProperties: false });
|
|
251
|
+
|
|
252
|
+
// internal/codex/config.ts
|
|
253
|
+
function nonEmptyName(value, field) {
|
|
254
|
+
if (typeof value !== "string" || !value.trim())
|
|
255
|
+
throw new Error(field + " must be a non-empty string");
|
|
256
|
+
return value.trim();
|
|
257
|
+
}
|
|
258
|
+
function normalizeCodexToolRouteConfig(value) {
|
|
259
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
260
|
+
throw new Error("pi-codex-tools config must be an object");
|
|
261
|
+
const rawProviders = "providers" in value ? value.providers ?? {} : {};
|
|
262
|
+
if (!rawProviders || typeof rawProviders !== "object" || Array.isArray(rawProviders))
|
|
263
|
+
throw new Error("pi-codex-tools providers must be an object");
|
|
264
|
+
const providers = Object.create(null);
|
|
265
|
+
for (const [provider, rawModels] of Object.entries(rawProviders)) {
|
|
266
|
+
const name = nonEmptyName(provider, "pi-codex-tools provider name").toLowerCase();
|
|
267
|
+
if (!rawModels || typeof rawModels !== "object" || Array.isArray(rawModels))
|
|
268
|
+
throw new Error("pi-codex-tools provider " + name + " must be an object");
|
|
269
|
+
const models = Object.create(null);
|
|
270
|
+
for (const [canonical, alias] of Object.entries(rawModels))
|
|
271
|
+
models[nonEmptyName(canonical, "pi-codex-tools model name").toLowerCase()] = nonEmptyName(alias, "pi-codex-tools model alias");
|
|
272
|
+
providers[name] = models;
|
|
273
|
+
}
|
|
274
|
+
return { providers };
|
|
275
|
+
}
|
|
276
|
+
function isCodexToolRoute(config, model) {
|
|
277
|
+
const provider = model?.provider.trim().toLowerCase();
|
|
278
|
+
return Boolean(provider && Object.hasOwn(config.providers, provider));
|
|
279
|
+
}
|
|
280
|
+
function resolveCodexToolModel(config, model, canonical) {
|
|
281
|
+
const provider = model?.provider.trim().toLowerCase();
|
|
282
|
+
const aliases = provider && Object.hasOwn(config.providers, provider) ? config.providers[provider] : undefined;
|
|
283
|
+
return aliases?.[canonical.trim().toLowerCase()] || canonical;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// internal/codex/durable.ts
|
|
287
|
+
import { ProviderDoc } from "@earendil-works/pi-durable";
|
|
288
|
+
async function callingModel(api, options, context) {
|
|
289
|
+
const reference = (await api.agent(context)).model;
|
|
290
|
+
return reference ? options.models.getModel(reference.provider, reference.modelId) : undefined;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// internal/codex/types.ts
|
|
294
|
+
var CODEX_TOOL_PROVIDER_UNSUPPORTED_MESSAGE = "Codex-backed tool requires an OpenAI Codex-compatible Responses provider";
|
|
295
|
+
var CODEX_TOOL_ORIGINATOR = "codex_cli_rs";
|
|
296
|
+
var OPENAI_CODEX_PROVIDER = "openai-codex";
|
|
297
|
+
var DEFAULT_CODEX_BASE_URL = "https://chatgpt.com/backend-api";
|
|
298
|
+
|
|
299
|
+
// internal/codex/headers.ts
|
|
300
|
+
function codexToolProviderHeaders(provider, runtime = "node") {
|
|
301
|
+
const headers = new Headers;
|
|
302
|
+
headers.set("originator", CODEX_TOOL_ORIGINATOR);
|
|
303
|
+
headers.set("User-Agent", runtime === "workerd" ? CODEX_TOOL_ORIGINATOR + "/0.0.0 (workerd unknown; unknown) unknown" : codexWebRunUserAgent(CODEX_TOOL_ORIGINATOR));
|
|
304
|
+
headers.set("version", "0.0.0");
|
|
305
|
+
headers.set("content-type", "application/json");
|
|
306
|
+
for (const [name, value] of Object.entries(provider.headers ?? {})) {
|
|
307
|
+
if (value === null)
|
|
308
|
+
headers.delete(name);
|
|
309
|
+
else if (typeof value === "string")
|
|
310
|
+
headers.set(name, value);
|
|
311
|
+
}
|
|
312
|
+
headers.set("Authorization", "Bearer " + provider.token);
|
|
313
|
+
headers.set("ChatGPT-Account-ID", provider.accountId);
|
|
314
|
+
return headers;
|
|
315
|
+
}
|
|
316
|
+
function codexWebRunUserAgent(originator = CODEX_TOOL_ORIGINATOR) {
|
|
317
|
+
const platform = process.platform === "darwin" ? "Mac OS" : process.platform === "win32" ? "Windows" : process.platform === "linux" ? "Linux" : process.platform;
|
|
318
|
+
const arch = process.arch === "arm64" ? "arm64" : process.arch;
|
|
319
|
+
const terminal = process.env["TERM_PROGRAM"]?.trim() || process.env["TERM"]?.trim() || "unknown";
|
|
320
|
+
return originator + "/0.0.0 (" + platform + " unknown; " + arch + ") " + terminal;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// internal/codex/http-node.ts
|
|
324
|
+
async function createNodeCodexTransport() {
|
|
325
|
+
const [{ fetch, ProxyAgent }, { getProxyForUrl }] = await Promise.all([
|
|
326
|
+
import("undici"),
|
|
327
|
+
import("proxy-from-env")
|
|
328
|
+
]);
|
|
329
|
+
const dispatchers = new Map;
|
|
330
|
+
return {
|
|
331
|
+
async fetch(url, init) {
|
|
332
|
+
const proxy = getProxyForUrl(url.href);
|
|
333
|
+
let dispatcher = proxy ? dispatchers.get(proxy) : undefined;
|
|
334
|
+
if (proxy && !dispatcher) {
|
|
335
|
+
dispatcher = new ProxyAgent(proxy);
|
|
336
|
+
dispatchers.set(proxy, dispatcher);
|
|
337
|
+
}
|
|
338
|
+
const response = await fetch(url, {
|
|
339
|
+
...init,
|
|
340
|
+
headers: Object.fromEntries(init.headers.entries()),
|
|
341
|
+
...dispatcher ? { dispatcher } : {}
|
|
342
|
+
});
|
|
343
|
+
return response;
|
|
344
|
+
},
|
|
345
|
+
async close() {
|
|
346
|
+
await Promise.all([...dispatchers.values()].map((agent) => agent.close()));
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// internal/codex/http.ts
|
|
352
|
+
var DEFAULT_MAX_RESPONSE_BYTES = 64 * 1024 * 1024;
|
|
353
|
+
var MAX_REDIRECTS = 10;
|
|
354
|
+
var defaultCookies = new ChatGptCloudflareCookieStore;
|
|
355
|
+
async function fetchCodexTool(url, options) {
|
|
356
|
+
const transport = options.runtime === "workerd" || options.fetch ? undefined : await createNodeCodexTransport();
|
|
357
|
+
let currentUrl = new URL(url);
|
|
358
|
+
let method = options.method;
|
|
359
|
+
let body = options.body;
|
|
360
|
+
const baseHeaders = new Headers(options.headers);
|
|
361
|
+
const cookies = options.cookieStore ?? defaultCookies;
|
|
362
|
+
const sensitiveCookies = new Map;
|
|
363
|
+
const rememberCookie = (pair) => {
|
|
364
|
+
const separator = pair.indexOf("=");
|
|
365
|
+
const value = pair.slice(separator + 1).trim();
|
|
366
|
+
const name = pair.slice(0, separator).trim();
|
|
367
|
+
if (separator > 0 && value)
|
|
368
|
+
sensitiveCookies.set(`${name}=${value}`, { name, value });
|
|
369
|
+
};
|
|
370
|
+
const redact = (text) => {
|
|
371
|
+
for (const { name, value } of sensitiveCookies.values()) {
|
|
372
|
+
text = text === value ? "[redacted]" : text.replaceAll(`${name}=${value}`, `${name}=[redacted]`);
|
|
373
|
+
if (value.length >= 8)
|
|
374
|
+
text = text.replaceAll(value, "[redacted]");
|
|
375
|
+
}
|
|
376
|
+
return text;
|
|
377
|
+
};
|
|
378
|
+
try {
|
|
379
|
+
for (let redirects = 0;; redirects += 1) {
|
|
380
|
+
const chatGptRequest = isChatGptCookieUrl(currentUrl);
|
|
381
|
+
const headers = new Headers(baseHeaders);
|
|
382
|
+
if (chatGptRequest) {
|
|
383
|
+
const cookie = await cookies.requestHeader(currentUrl);
|
|
384
|
+
if (cookie)
|
|
385
|
+
headers.set("cookie", cookie);
|
|
386
|
+
}
|
|
387
|
+
for (const pair of (headers.get("cookie") ?? "").split(";")) {
|
|
388
|
+
rememberCookie(pair);
|
|
389
|
+
}
|
|
390
|
+
const init = {
|
|
391
|
+
...method ? { method } : {},
|
|
392
|
+
headers,
|
|
393
|
+
...body === undefined ? {} : { body },
|
|
394
|
+
...options.signal ? { signal: options.signal } : {},
|
|
395
|
+
redirect: "manual"
|
|
396
|
+
};
|
|
397
|
+
const response = transport ? await transport.fetch(currentUrl, init) : await (options.fetch ?? globalThis.fetch)(currentUrl, init);
|
|
398
|
+
try {
|
|
399
|
+
if (chatGptRequest) {
|
|
400
|
+
const received = response.headers.getSetCookie();
|
|
401
|
+
await cookies.storeResponse(currentUrl, received);
|
|
402
|
+
for (const header of received) {
|
|
403
|
+
const pair = header.split(";", 1)[0] ?? "";
|
|
404
|
+
rememberCookie(pair);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
} catch (error) {
|
|
408
|
+
await response.body?.cancel();
|
|
409
|
+
throw error;
|
|
410
|
+
}
|
|
411
|
+
const location = redirectLocation(response.status, response.headers.get("location"));
|
|
412
|
+
if (!location) {
|
|
413
|
+
const text = await readBoundedText(response, options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES);
|
|
414
|
+
return {
|
|
415
|
+
status: response.status,
|
|
416
|
+
statusText: response.statusText,
|
|
417
|
+
headers: new Headers([...response.headers.entries()]),
|
|
418
|
+
text,
|
|
419
|
+
redact
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
if (redirects >= MAX_REDIRECTS) {
|
|
423
|
+
await response.body?.cancel();
|
|
424
|
+
throw new Error("Codex tool request exceeded " + MAX_REDIRECTS + " redirects");
|
|
425
|
+
}
|
|
426
|
+
let nextUrl;
|
|
427
|
+
try {
|
|
428
|
+
nextUrl = new URL(location, currentUrl);
|
|
429
|
+
} catch (error) {
|
|
430
|
+
await response.body?.cancel();
|
|
431
|
+
throw error;
|
|
432
|
+
}
|
|
433
|
+
if (options.runtime === "workerd" && currentUrl.protocol === "https:" && nextUrl.protocol !== "https:") {
|
|
434
|
+
await response.body?.cancel();
|
|
435
|
+
throw new Error("Codex tool request refused redirect outside HTTPS");
|
|
436
|
+
}
|
|
437
|
+
if (chatGptRequest && !isChatGptCookieUrl(nextUrl)) {
|
|
438
|
+
await response.body?.cancel();
|
|
439
|
+
throw new Error("Codex tool request refused redirect outside ChatGPT: " + nextUrl.origin);
|
|
440
|
+
}
|
|
441
|
+
if (nextUrl.origin !== currentUrl.origin) {
|
|
442
|
+
baseHeaders.delete("authorization");
|
|
443
|
+
baseHeaders.delete("chatgpt-account-id");
|
|
444
|
+
baseHeaders.delete("cookie");
|
|
445
|
+
baseHeaders.delete("proxy-authorization");
|
|
446
|
+
baseHeaders.delete("host");
|
|
447
|
+
}
|
|
448
|
+
if (response.status === 303 && method?.toUpperCase() !== "GET" && method?.toUpperCase() !== "HEAD" || (response.status === 301 || response.status === 302) && method?.toUpperCase() === "POST") {
|
|
449
|
+
method = "GET";
|
|
450
|
+
body = undefined;
|
|
451
|
+
baseHeaders.delete("content-encoding");
|
|
452
|
+
baseHeaders.delete("content-language");
|
|
453
|
+
baseHeaders.delete("content-location");
|
|
454
|
+
baseHeaders.delete("content-type");
|
|
455
|
+
baseHeaders.delete("content-length");
|
|
456
|
+
}
|
|
457
|
+
await response.body?.cancel();
|
|
458
|
+
currentUrl = nextUrl;
|
|
459
|
+
}
|
|
460
|
+
} finally {
|
|
461
|
+
await transport?.close();
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
function redirectLocation(status, location) {
|
|
465
|
+
return location && [301, 302, 303, 307, 308].includes(status) ? location : undefined;
|
|
466
|
+
}
|
|
467
|
+
async function readBoundedText(response, maxBytes) {
|
|
468
|
+
const contentLength = Number(response.headers.get("content-length"));
|
|
469
|
+
if (Number.isFinite(contentLength) && contentLength > maxBytes) {
|
|
470
|
+
await response.body?.cancel();
|
|
471
|
+
throw new Error("Codex tool response exceeded " + maxBytes + " bytes");
|
|
472
|
+
}
|
|
473
|
+
if (!response.body)
|
|
474
|
+
return "";
|
|
475
|
+
const reader = response.body.getReader();
|
|
476
|
+
const decoder = new TextDecoder;
|
|
477
|
+
let total = 0;
|
|
478
|
+
let text = "";
|
|
479
|
+
try {
|
|
480
|
+
while (true) {
|
|
481
|
+
const chunk = await reader.read();
|
|
482
|
+
if (chunk.done)
|
|
483
|
+
break;
|
|
484
|
+
total += chunk.value.byteLength;
|
|
485
|
+
if (total > maxBytes) {
|
|
486
|
+
await reader.cancel();
|
|
487
|
+
throw new Error("Codex tool response exceeded " + maxBytes + " bytes");
|
|
488
|
+
}
|
|
489
|
+
text += decoder.decode(chunk.value, { stream: true });
|
|
490
|
+
}
|
|
491
|
+
return text + decoder.decode();
|
|
492
|
+
} finally {
|
|
493
|
+
reader.releaseLock();
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
// internal/codex/urls.ts
|
|
498
|
+
function resolveCodexApiProviderBaseUrl(modelBaseUrl) {
|
|
499
|
+
const base = modelBaseUrl?.trim() || DEFAULT_CODEX_BASE_URL;
|
|
500
|
+
const normalized = base.replace(/\/+$/, "");
|
|
501
|
+
try {
|
|
502
|
+
const url = new URL(normalized);
|
|
503
|
+
if (url.pathname === "" || url.pathname === "/")
|
|
504
|
+
return normalized + "/api/codex";
|
|
505
|
+
} catch {}
|
|
506
|
+
if (normalized.endsWith("/codex/responses"))
|
|
507
|
+
return normalized.slice(0, -"/responses".length);
|
|
508
|
+
if (normalized.endsWith("/codex"))
|
|
509
|
+
return normalized;
|
|
510
|
+
if (normalized.endsWith("/backend-api") || normalized.endsWith("/api"))
|
|
511
|
+
return normalized + "/codex";
|
|
512
|
+
return normalized;
|
|
513
|
+
}
|
|
514
|
+
function resolveCodexResponsesUrl(providerBaseUrl) {
|
|
515
|
+
const base = providerBaseUrl.replace(/\/+$/, "");
|
|
516
|
+
if (base.endsWith("/codex/responses"))
|
|
517
|
+
return base;
|
|
518
|
+
return resolveCodexApiProviderBaseUrl(base) + "/responses";
|
|
519
|
+
}
|
|
520
|
+
function resolveCodexSearchUrl(providerBaseUrl) {
|
|
521
|
+
const normalized = providerBaseUrl.trim().replace(/\/+$/, "");
|
|
522
|
+
if (normalized.endsWith("/alpha/search"))
|
|
523
|
+
return normalized;
|
|
524
|
+
const base = normalized.endsWith("/responses") ? normalized.slice(0, -"/responses".length) : resolveCodexApiProviderBaseUrl(normalized);
|
|
525
|
+
return base + "/alpha/search";
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// internal/codex/resolve.ts
|
|
529
|
+
var PREFERRED_MODELS = [
|
|
530
|
+
"gpt-5.6-luna",
|
|
531
|
+
"gpt-5.6-terra",
|
|
532
|
+
"gpt-5.6-sol",
|
|
533
|
+
"gpt-5.5",
|
|
534
|
+
"gpt-5.4-mini"
|
|
535
|
+
];
|
|
536
|
+
function codexTransport(model, options) {
|
|
537
|
+
return Boolean(model && (model.provider.trim().toLowerCase() === OPENAI_CODEX_PROVIDER || model.api.trim().toLowerCase() === "openai-codex-responses" || options.routes && isCodexToolRoute(options.routes, model)));
|
|
538
|
+
}
|
|
539
|
+
function supportsExecutableCodexTool(model, options, images = false) {
|
|
540
|
+
return Boolean(model?.api.includes("responses") && codexTransport(model, options) && (!images || model.input.includes("image")) || options.allowConfiguredProvider?.(model) || options.allowCodexProviderFallback === true);
|
|
541
|
+
}
|
|
542
|
+
async function resolveAuthModel(current, options, context) {
|
|
543
|
+
if (current && (options.routes && isCodexToolRoute(options.routes, current) || current.api.includes("responses") && (codexTransport(current, options) || options.allowConfiguredProvider?.(current))))
|
|
544
|
+
return current;
|
|
545
|
+
const usable = (model) => Boolean(model && model.provider.trim().toLowerCase() === OPENAI_CODEX_PROVIDER && model.api.includes("responses"));
|
|
546
|
+
const direct = current ? options.models.getModel(OPENAI_CODEX_PROVIDER, current.id) : undefined;
|
|
547
|
+
if (usable(direct))
|
|
548
|
+
return direct;
|
|
549
|
+
const preferred = PREFERRED_MODELS.map((id) => options.models.getModel(OPENAI_CODEX_PROVIDER, id)).find(usable);
|
|
550
|
+
if (preferred)
|
|
551
|
+
return preferred;
|
|
552
|
+
const available = (await options.models.getAvailable(undefined, context.abortSignal ? { signal: context.abortSignal } : {})).find(usable);
|
|
553
|
+
const fallback = available ?? options.models.getModels().find(usable);
|
|
554
|
+
if (fallback)
|
|
555
|
+
return fallback;
|
|
556
|
+
throw new Error(CODEX_TOOL_PROVIDER_UNSUPPORTED_MESSAGE);
|
|
557
|
+
}
|
|
558
|
+
function headerValue(headers, name) {
|
|
559
|
+
const entry = Object.entries(headers ?? {}).find(([key]) => key.toLowerCase() === name.toLowerCase());
|
|
560
|
+
return typeof entry?.[1] === "string" ? entry[1] : undefined;
|
|
561
|
+
}
|
|
562
|
+
function extractAccountId(token) {
|
|
563
|
+
try {
|
|
564
|
+
const payload = token.split(".")[1];
|
|
565
|
+
if (!payload)
|
|
566
|
+
throw new Error("Invalid token");
|
|
567
|
+
const claims = JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(payload.replace(/-/g, "+").replace(/_/g, "/")), (character) => character.charCodeAt(0))));
|
|
568
|
+
const auth = claims && typeof claims === "object" && "https://api.openai.com/auth" in claims ? claims["https://api.openai.com/auth"] : undefined;
|
|
569
|
+
const id = auth && typeof auth === "object" && "chatgpt_account_id" in auth ? auth.chatgpt_account_id : undefined;
|
|
570
|
+
if (typeof id !== "string" || !id)
|
|
571
|
+
throw new Error("No account ID");
|
|
572
|
+
return id;
|
|
573
|
+
} catch {
|
|
574
|
+
throw new Error("Failed to extract accountId from token");
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
async function resolveCodexToolProvider(current, options, context) {
|
|
578
|
+
if (!(options.routes && isCodexToolRoute(options.routes, current))) {
|
|
579
|
+
const hosted = await options.resolveProvider?.(current, context);
|
|
580
|
+
if (hosted)
|
|
581
|
+
return hosted;
|
|
582
|
+
}
|
|
583
|
+
const model = await resolveAuthModel(current, options, context);
|
|
584
|
+
const resolution = await options.models.getAuth(model, context.abortSignal ? { signal: context.abortSignal } : {});
|
|
585
|
+
if (!resolution)
|
|
586
|
+
throw new Error(CODEX_TOOL_PROVIDER_UNSUPPORTED_MESSAGE);
|
|
587
|
+
const auth = resolution.auth;
|
|
588
|
+
const codex = codexTransport(model, options);
|
|
589
|
+
const authorization = headerValue(auth.headers, "authorization")?.match(/^Bearer\s+(.+)$/i)?.[1]?.trim();
|
|
590
|
+
const token = codex ? auth.apiKey ?? authorization : authorization ?? auth.apiKey;
|
|
591
|
+
if (!token)
|
|
592
|
+
throw new Error(CODEX_TOOL_PROVIDER_UNSUPPORTED_MESSAGE);
|
|
593
|
+
const resolvedBase = auth.baseUrl ?? model.baseUrl;
|
|
594
|
+
const baseUrl = codex ? resolveCodexApiProviderBaseUrl(resolvedBase) : resolvedBase?.trim().replace(/\/+$/, "");
|
|
595
|
+
if (!baseUrl)
|
|
596
|
+
throw new Error("Configured Responses provider is missing a base URL");
|
|
597
|
+
const responsesUrl = codex ? resolveCodexResponsesUrl(baseUrl) : baseUrl.endsWith("/responses") ? baseUrl : baseUrl + "/responses";
|
|
598
|
+
return {
|
|
599
|
+
route: codex ? "openai-codex" : "configured-responses",
|
|
600
|
+
baseUrl,
|
|
601
|
+
responsesUrl,
|
|
602
|
+
searchUrl: resolveCodexSearchUrl(responsesUrl),
|
|
603
|
+
model: model.id,
|
|
604
|
+
token,
|
|
605
|
+
accountId: headerValue(auth.headers, "chatgpt-account-id") ?? (codex ? extractAccountId(token) : ""),
|
|
606
|
+
...auth.headers ? { headers: auth.headers } : {}
|
|
607
|
+
};
|
|
608
|
+
}
|
|
609
|
+
|
|
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
|
+
// packages/imagegen/src/request.ts
|
|
710
|
+
import { getOrThrow as getOrThrow2 } from "@earendil-works/pi-durable/env";
|
|
711
|
+
|
|
712
|
+
// packages/imagegen/src/image-validation.ts
|
|
713
|
+
var PNG_SIGNATURE = Uint8Array.of(137, 80, 78, 71, 13, 10, 26, 10);
|
|
714
|
+
function startsWith(bytes, prefix) {
|
|
715
|
+
return prefix.every((byte, index) => bytes[index] === byte);
|
|
716
|
+
}
|
|
717
|
+
function ascii(bytes, start, end) {
|
|
718
|
+
return Buffer.from(bytes.subarray(start, end)).toString("ascii");
|
|
719
|
+
}
|
|
720
|
+
function u16be(bytes, offset) {
|
|
721
|
+
return bytes[offset] * 256 + bytes[offset + 1];
|
|
722
|
+
}
|
|
723
|
+
function u16le(bytes, offset) {
|
|
724
|
+
return bytes[offset] + bytes[offset + 1] * 256;
|
|
725
|
+
}
|
|
726
|
+
function u32be(bytes, offset) {
|
|
727
|
+
return bytes[offset] * 16777216 + bytes[offset + 1] * 65536 + bytes[offset + 2] * 256 + bytes[offset + 3] >>> 0;
|
|
728
|
+
}
|
|
729
|
+
function u32le(bytes, offset) {
|
|
730
|
+
return bytes[offset] + bytes[offset + 1] * 256 + bytes[offset + 2] * 65536 + bytes[offset + 3] * 16777216 >>> 0;
|
|
731
|
+
}
|
|
732
|
+
function crc32(bytes, start, end) {
|
|
733
|
+
let crc = 4294967295;
|
|
734
|
+
for (let index = start;index < end; index++) {
|
|
735
|
+
crc ^= bytes[index];
|
|
736
|
+
for (let bit = 0;bit < 8; bit++) {
|
|
737
|
+
crc = crc >>> 1 ^ (crc & 1 ? 3988292384 : 0);
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
return (crc ^ 4294967295) >>> 0;
|
|
741
|
+
}
|
|
742
|
+
function validPng(bytes) {
|
|
743
|
+
if (bytes.length < 45 || !startsWith(bytes, PNG_SIGNATURE))
|
|
744
|
+
return false;
|
|
745
|
+
let offset = PNG_SIGNATURE.length;
|
|
746
|
+
let first = true;
|
|
747
|
+
let sawHeader = false;
|
|
748
|
+
let sawImageData = false;
|
|
749
|
+
while (offset + 12 <= bytes.length) {
|
|
750
|
+
const length = u32be(bytes, offset);
|
|
751
|
+
const typeStart = offset + 4;
|
|
752
|
+
const dataStart = typeStart + 4;
|
|
753
|
+
const dataEnd = dataStart + length;
|
|
754
|
+
const chunkEnd = dataEnd + 4;
|
|
755
|
+
if (dataEnd < dataStart || chunkEnd > bytes.length)
|
|
756
|
+
return false;
|
|
757
|
+
if (crc32(bytes, typeStart, dataEnd) !== u32be(bytes, dataEnd))
|
|
758
|
+
return false;
|
|
759
|
+
const type = ascii(bytes, typeStart, dataStart);
|
|
760
|
+
if (first) {
|
|
761
|
+
if (type !== "IHDR" || length !== 13 || u32be(bytes, dataStart) === 0 || u32be(bytes, dataStart + 4) === 0)
|
|
762
|
+
return false;
|
|
763
|
+
sawHeader = true;
|
|
764
|
+
first = false;
|
|
765
|
+
} else if (type === "IHDR") {
|
|
766
|
+
return false;
|
|
767
|
+
}
|
|
768
|
+
if (type === "IDAT")
|
|
769
|
+
sawImageData = true;
|
|
770
|
+
if (type === "IEND") {
|
|
771
|
+
return length === 0 && sawHeader && sawImageData && chunkEnd === bytes.length;
|
|
772
|
+
}
|
|
773
|
+
offset = chunkEnd;
|
|
774
|
+
}
|
|
775
|
+
return false;
|
|
776
|
+
}
|
|
777
|
+
function jpegFrameMarker(marker) {
|
|
778
|
+
return marker >= 192 && marker <= 195 || marker >= 197 && marker <= 199 || marker >= 201 && marker <= 203 || marker >= 205 && marker <= 207;
|
|
779
|
+
}
|
|
780
|
+
function validJpeg(bytes) {
|
|
781
|
+
if (bytes.length < 12 || bytes[0] !== 255 || bytes[1] !== 216 || bytes.at(-2) !== 255 || bytes.at(-1) !== 217)
|
|
782
|
+
return false;
|
|
783
|
+
let offset = 2;
|
|
784
|
+
let sawFrame = false;
|
|
785
|
+
let sawScan = false;
|
|
786
|
+
while (offset < bytes.length) {
|
|
787
|
+
if (bytes[offset] !== 255)
|
|
788
|
+
return false;
|
|
789
|
+
while (bytes[offset] === 255)
|
|
790
|
+
offset++;
|
|
791
|
+
const marker = bytes[offset++];
|
|
792
|
+
if (marker === undefined || marker === 0)
|
|
793
|
+
return false;
|
|
794
|
+
if (marker === 217)
|
|
795
|
+
return sawFrame && sawScan && offset === bytes.length;
|
|
796
|
+
if (marker === 1 || marker >= 208 && marker <= 215)
|
|
797
|
+
continue;
|
|
798
|
+
if (offset + 2 > bytes.length)
|
|
799
|
+
return false;
|
|
800
|
+
const length = u16be(bytes, offset);
|
|
801
|
+
if (length < 2 || offset + length > bytes.length)
|
|
802
|
+
return false;
|
|
803
|
+
if (jpegFrameMarker(marker)) {
|
|
804
|
+
if (length < 7 || u16be(bytes, offset + 3) === 0 || u16be(bytes, offset + 5) === 0)
|
|
805
|
+
return false;
|
|
806
|
+
sawFrame = true;
|
|
807
|
+
}
|
|
808
|
+
offset += length;
|
|
809
|
+
if (marker !== 218)
|
|
810
|
+
continue;
|
|
811
|
+
sawScan = true;
|
|
812
|
+
while (offset < bytes.length) {
|
|
813
|
+
if (bytes[offset] !== 255) {
|
|
814
|
+
offset++;
|
|
815
|
+
continue;
|
|
816
|
+
}
|
|
817
|
+
const markerStart = offset;
|
|
818
|
+
while (bytes[offset] === 255)
|
|
819
|
+
offset++;
|
|
820
|
+
const entropyMarker = bytes[offset];
|
|
821
|
+
if (entropyMarker === 0 || entropyMarker >= 208 && entropyMarker <= 215) {
|
|
822
|
+
offset++;
|
|
823
|
+
continue;
|
|
824
|
+
}
|
|
825
|
+
offset = markerStart;
|
|
826
|
+
break;
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
return false;
|
|
830
|
+
}
|
|
831
|
+
function skipGifSubBlocks(bytes, start) {
|
|
832
|
+
let offset = start;
|
|
833
|
+
while (offset < bytes.length) {
|
|
834
|
+
const length = bytes[offset++];
|
|
835
|
+
if (length === 0)
|
|
836
|
+
return offset;
|
|
837
|
+
if (offset + length > bytes.length)
|
|
838
|
+
return;
|
|
839
|
+
offset += length;
|
|
840
|
+
}
|
|
841
|
+
return;
|
|
842
|
+
}
|
|
843
|
+
function validGif(bytes) {
|
|
844
|
+
if (bytes.length < 14 || !["GIF87a", "GIF89a"].includes(ascii(bytes, 0, 6)) || u16le(bytes, 6) === 0 || u16le(bytes, 8) === 0)
|
|
845
|
+
return false;
|
|
846
|
+
let offset = 13;
|
|
847
|
+
const globalTable = (bytes[10] & 128) !== 0;
|
|
848
|
+
if (globalTable)
|
|
849
|
+
offset += 3 * 2 ** ((bytes[10] & 7) + 1);
|
|
850
|
+
if (offset > bytes.length)
|
|
851
|
+
return false;
|
|
852
|
+
let sawImage = false;
|
|
853
|
+
while (offset < bytes.length) {
|
|
854
|
+
const introducer = bytes[offset++];
|
|
855
|
+
if (introducer === 59)
|
|
856
|
+
return sawImage && offset === bytes.length;
|
|
857
|
+
if (introducer === 33) {
|
|
858
|
+
if (offset >= bytes.length)
|
|
859
|
+
return false;
|
|
860
|
+
offset++;
|
|
861
|
+
const next = skipGifSubBlocks(bytes, offset);
|
|
862
|
+
if (next === undefined)
|
|
863
|
+
return false;
|
|
864
|
+
offset = next;
|
|
865
|
+
continue;
|
|
866
|
+
}
|
|
867
|
+
if (introducer !== 44 || offset + 9 > bytes.length)
|
|
868
|
+
return false;
|
|
869
|
+
const width = u16le(bytes, offset + 4);
|
|
870
|
+
const height = u16le(bytes, offset + 6);
|
|
871
|
+
if (width === 0 || height === 0)
|
|
872
|
+
return false;
|
|
873
|
+
const packed = bytes[offset + 8];
|
|
874
|
+
offset += 9;
|
|
875
|
+
if ((packed & 128) !== 0)
|
|
876
|
+
offset += 3 * 2 ** ((packed & 7) + 1);
|
|
877
|
+
if (offset >= bytes.length)
|
|
878
|
+
return false;
|
|
879
|
+
offset++;
|
|
880
|
+
const next = skipGifSubBlocks(bytes, offset);
|
|
881
|
+
if (next === undefined)
|
|
882
|
+
return false;
|
|
883
|
+
offset = next;
|
|
884
|
+
sawImage = true;
|
|
885
|
+
}
|
|
886
|
+
return false;
|
|
887
|
+
}
|
|
888
|
+
function validWebp(bytes) {
|
|
889
|
+
if (bytes.length < 20 || ascii(bytes, 0, 4) !== "RIFF" || ascii(bytes, 8, 12) !== "WEBP" || u32le(bytes, 4) + 8 !== bytes.length)
|
|
890
|
+
return false;
|
|
891
|
+
let offset = 12;
|
|
892
|
+
let sawImage = false;
|
|
893
|
+
while (offset + 8 <= bytes.length) {
|
|
894
|
+
const type = ascii(bytes, offset, offset + 4);
|
|
895
|
+
const length = u32le(bytes, offset + 4);
|
|
896
|
+
const data = offset + 8;
|
|
897
|
+
const end = data + length;
|
|
898
|
+
const paddedEnd = end + (length & 1);
|
|
899
|
+
if (end < data || paddedEnd > bytes.length)
|
|
900
|
+
return false;
|
|
901
|
+
if (type === "VP8 ") {
|
|
902
|
+
if (length < 10 || bytes[data + 3] !== 157 || bytes[data + 4] !== 1 || bytes[data + 5] !== 42 || (u16le(bytes, data + 6) & 16383) === 0 || (u16le(bytes, data + 8) & 16383) === 0)
|
|
903
|
+
return false;
|
|
904
|
+
sawImage = true;
|
|
905
|
+
} else if (type === "VP8L") {
|
|
906
|
+
if (length < 5 || bytes[data] !== 47)
|
|
907
|
+
return false;
|
|
908
|
+
sawImage = true;
|
|
909
|
+
} else if (type === "ANMF") {
|
|
910
|
+
if (length < 16)
|
|
911
|
+
return false;
|
|
912
|
+
sawImage = true;
|
|
913
|
+
}
|
|
914
|
+
offset = paddedEnd;
|
|
915
|
+
}
|
|
916
|
+
return sawImage && offset === bytes.length;
|
|
917
|
+
}
|
|
918
|
+
function validatedImageMime(bytes) {
|
|
919
|
+
if (validPng(bytes))
|
|
920
|
+
return "image/png";
|
|
921
|
+
if (validJpeg(bytes))
|
|
922
|
+
return "image/jpeg";
|
|
923
|
+
if (validGif(bytes))
|
|
924
|
+
return "image/gif";
|
|
925
|
+
if (validWebp(bytes))
|
|
926
|
+
return "image/webp";
|
|
927
|
+
return;
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
// packages/imagegen/src/request.ts
|
|
931
|
+
var MAX_IMAGE_BYTES = 1024 * 1024 * 1024;
|
|
932
|
+
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));
|
|
935
|
+
if (info.kind !== "file")
|
|
936
|
+
throw new Error("edit image is not a file: " + value);
|
|
937
|
+
if (info.size > MAX_IMAGE_BYTES)
|
|
938
|
+
throw new Error("edit image exceeds " + MAX_IMAGE_BYTES + " bytes: " + value);
|
|
939
|
+
const bytes = getOrThrow2(await env.readBinaryFile(path, context));
|
|
940
|
+
const mime = validatedImageMime(bytes);
|
|
941
|
+
if (!mime)
|
|
942
|
+
throw new Error("edit image must be PNG, JPEG, GIF, or WebP: " + value);
|
|
943
|
+
return "data:" + mime + ";base64," + Buffer.from(bytes).toString("base64");
|
|
944
|
+
}
|
|
945
|
+
function recentImageDataUrl(value) {
|
|
946
|
+
const separator = value.indexOf(",");
|
|
947
|
+
const metadata = separator >= 0 ? value.slice(0, separator) : "";
|
|
948
|
+
const data = separator >= 0 ? value.slice(separator + 1) : "";
|
|
949
|
+
if (!metadata.startsWith("data:image/") || !metadata.endsWith(";base64") || !data)
|
|
950
|
+
throw new Error("recent conversation image is not a base64 image data URL");
|
|
951
|
+
return value;
|
|
952
|
+
}
|
|
953
|
+
async function buildImageGenerationRequest(args, recentImages, env, context, model = IMAGE_MODEL) {
|
|
954
|
+
const paths = args.referenced_image_paths ?? [];
|
|
955
|
+
const background = args.transparent_background === true ? "transparent" : "opaque";
|
|
956
|
+
if (paths.length > MAX_EDIT_IMAGES)
|
|
957
|
+
throw new Error("referenced_image_paths must contain at most " + MAX_EDIT_IMAGES + " paths");
|
|
958
|
+
if (paths.length > 0 && args.num_last_images_to_include != null)
|
|
959
|
+
throw new Error("provide only one of referenced_image_paths or num_last_images_to_include");
|
|
960
|
+
if (paths.length === 0 && args.num_last_images_to_include == null) {
|
|
961
|
+
return {
|
|
962
|
+
operation: "generations",
|
|
963
|
+
body: {
|
|
964
|
+
prompt: args.prompt,
|
|
965
|
+
model,
|
|
966
|
+
background,
|
|
967
|
+
quality: "auto",
|
|
968
|
+
size: "auto"
|
|
969
|
+
}
|
|
970
|
+
};
|
|
971
|
+
}
|
|
972
|
+
const images = paths.length > 0 ? await Promise.all(paths.map(async (path) => ({
|
|
973
|
+
image_url: await localImageDataUrl(path, env, context)
|
|
974
|
+
}))) : (recentImages ?? []).map((image) => ({
|
|
975
|
+
image_url: recentImageDataUrl(image)
|
|
976
|
+
}));
|
|
977
|
+
return {
|
|
978
|
+
operation: "edits",
|
|
979
|
+
body: {
|
|
980
|
+
images,
|
|
981
|
+
prompt: args.prompt,
|
|
982
|
+
model,
|
|
983
|
+
background,
|
|
984
|
+
quality: "auto",
|
|
985
|
+
size: "auto"
|
|
986
|
+
}
|
|
987
|
+
};
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
// packages/imagegen/src/execute.ts
|
|
991
|
+
function parseImageResponse(text) {
|
|
992
|
+
let parsed;
|
|
993
|
+
try {
|
|
994
|
+
parsed = JSON.parse(text);
|
|
995
|
+
} catch {
|
|
996
|
+
throw new Error("failed to decode image generation response");
|
|
997
|
+
}
|
|
998
|
+
if (!parsed || typeof parsed !== "object" || !("data" in parsed) || !Array.isArray(parsed.data))
|
|
999
|
+
throw new Error("image generation returned no image data");
|
|
1000
|
+
const data = parsed.data.map((item) => {
|
|
1001
|
+
if (!item || typeof item !== "object" || !("b64_json" in item) || typeof item.b64_json !== "string" || !item.b64_json.length)
|
|
1002
|
+
throw new Error("image generation returned no image data");
|
|
1003
|
+
return { b64_json: item.b64_json };
|
|
1004
|
+
});
|
|
1005
|
+
const result = { data };
|
|
1006
|
+
const metadata = parsed;
|
|
1007
|
+
for (const key of ["background", "quality", "size"]) {
|
|
1008
|
+
if (key in metadata) {
|
|
1009
|
+
const value = metadata[key];
|
|
1010
|
+
if (typeof value !== "string" && value !== null)
|
|
1011
|
+
throw new Error("image generation returned invalid " + key);
|
|
1012
|
+
result[key] = value;
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
if ("usage" in parsed)
|
|
1016
|
+
result.usage = jsonValue(parsed.usage);
|
|
1017
|
+
return result;
|
|
1018
|
+
}
|
|
1019
|
+
async function executeCodexImageGeneration(args, api, context, options) {
|
|
1020
|
+
context.abortSignal?.throwIfAborted();
|
|
1021
|
+
const env = api.env;
|
|
1022
|
+
if (!env)
|
|
1023
|
+
throw new Error("imagegen requires a conversation execution environment");
|
|
1024
|
+
const current = await callingModel(api, options, context);
|
|
1025
|
+
if (!supportsExecutableCodexTool(current, options, true))
|
|
1026
|
+
throw new Error(IMAGE_GENERATION_UNSUPPORTED_MESSAGE);
|
|
1027
|
+
let recentImages;
|
|
1028
|
+
if (args.num_last_images_to_include != null) {
|
|
1029
|
+
const conversation = await options.conversation?.(api.conversationId, context);
|
|
1030
|
+
if (!conversation)
|
|
1031
|
+
throw new Error("Recent image selection requires an active conversation context reader");
|
|
1032
|
+
recentImages = recentConversationImageUrls((await conversation.context(context)).messages, args.num_last_images_to_include);
|
|
1033
|
+
if (recentImages.length !== args.num_last_images_to_include)
|
|
1034
|
+
throw new Error("requested the last " + args.num_last_images_to_include + " conversation images, but only " + recentImages.length + " were available");
|
|
1035
|
+
}
|
|
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);
|
|
1040
|
+
headers.set("accept", "application/json");
|
|
1041
|
+
headers.set("x-codex-image-turn-id", api.callId);
|
|
1042
|
+
let response;
|
|
1043
|
+
try {
|
|
1044
|
+
response = await fetchCodexTool(provider.baseUrl.replace(/\/+$/, "") + "/images/" + request.operation, {
|
|
1045
|
+
method: "POST",
|
|
1046
|
+
headers,
|
|
1047
|
+
body: JSON.stringify(request.body),
|
|
1048
|
+
...options.fetch ? { fetch: options.fetch } : {},
|
|
1049
|
+
...options.runtime ? { runtime: options.runtime } : {},
|
|
1050
|
+
...cookieStore ? { cookieStore } : {},
|
|
1051
|
+
...context.abortSignal ? { signal: context.abortSignal } : {}
|
|
1052
|
+
});
|
|
1053
|
+
} catch {
|
|
1054
|
+
throw new Error("Image request failed or was interrupted. Remote outcome is unknown; do not replay automatically.");
|
|
1055
|
+
}
|
|
1056
|
+
if (response.status < 200 || response.status >= 300) {
|
|
1057
|
+
const challenge = response.headers.get("cf-mitigated")?.toLowerCase() === "challenge" || response.headers.get("server")?.toLowerCase() === "cloudflare" && response.text.trimStart().startsWith("<html");
|
|
1058
|
+
if (response.status === 403 && (challenge || response.text.toLowerCase().includes("cloudflare")))
|
|
1059
|
+
throw new Error("Image generation failed: HTTP 403 Cloudflare challenge. Try again later.");
|
|
1060
|
+
if (response.status === 401 || response.status === 403 && /auth|token|credential|access_enforcement|oauth/i.test(response.text))
|
|
1061
|
+
throw new Error("Image generation access was rejected: HTTP " + response.status + ". Ask the user to check credentials and access for the configured provider.");
|
|
1062
|
+
throw new Error("Image generation failed: HTTP " + response.status);
|
|
1063
|
+
}
|
|
1064
|
+
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
|
+
};
|
|
1070
|
+
} catch (error) {
|
|
1071
|
+
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
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
// packages/imagegen/src/output.ts
|
|
1076
|
+
function formatImagegenOutput(output) {
|
|
1077
|
+
return `Generated image: ${output.path}
|
|
1078
|
+
Latest: ${output.latest_path}`;
|
|
1079
|
+
}
|
|
1080
|
+
// packages/imagegen/src/index.ts
|
|
1081
|
+
function createImageGenerationTool(options) {
|
|
1082
|
+
return defineTool({
|
|
1083
|
+
name: IMAGE_GENERATION_TOOL_NAME,
|
|
1084
|
+
description: "Generate/edit images; omit selectors to generate",
|
|
1085
|
+
parameters: IMAGE_GENERATION_PARAMETERS,
|
|
1086
|
+
replay: "unsafe",
|
|
1087
|
+
executionMode: "sequential",
|
|
1088
|
+
async execute(args, api, context) {
|
|
1089
|
+
const result = await executeCodexImageGeneration(args, api, context, options);
|
|
1090
|
+
return {
|
|
1091
|
+
output: [
|
|
1092
|
+
{ type: "text", text: formatImagegenOutput(result.output) },
|
|
1093
|
+
...result.content
|
|
1094
|
+
],
|
|
1095
|
+
details: jsonValue(result.output)
|
|
1096
|
+
};
|
|
1097
|
+
}
|
|
1098
|
+
});
|
|
1099
|
+
}
|
|
1100
|
+
function createImageGenerationExtension(options) {
|
|
1101
|
+
return defineExtension({
|
|
1102
|
+
name: "imagegen",
|
|
1103
|
+
tools: [
|
|
1104
|
+
createImageGenerationTool({
|
|
1105
|
+
allowCodexProviderFallback: true,
|
|
1106
|
+
...options
|
|
1107
|
+
})
|
|
1108
|
+
]
|
|
1109
|
+
});
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
// packages/imagegen/src/activation.ts
|
|
1113
|
+
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
|
+
var configuration = Type2.Object({
|
|
1115
|
+
runtime: Type2.Optional(Type2.Union([Type2.Literal("node"), Type2.Literal("workerd")])),
|
|
1116
|
+
allowCodexProviderFallback: Type2.Optional(Type2.Boolean()),
|
|
1117
|
+
routes: Type2.Optional(Type2.Unknown())
|
|
1118
|
+
}, { additionalProperties: false });
|
|
1119
|
+
function baseline(request, conversation) {
|
|
1120
|
+
if (!Check(configuration, request.configuration))
|
|
1121
|
+
throw new Error("Invalid imagegen configuration");
|
|
1122
|
+
const { routes, ...options } = request.configuration;
|
|
1123
|
+
return {
|
|
1124
|
+
...options,
|
|
1125
|
+
models: request.capabilities.get(modelsCapability),
|
|
1126
|
+
fetch: request.capabilities.get(networkCapability).fetch,
|
|
1127
|
+
conversation,
|
|
1128
|
+
...routes === undefined ? {} : { routes: normalizeCodexToolRouteConfig(routes) }
|
|
1129
|
+
};
|
|
1130
|
+
}
|
|
1131
|
+
function createComponent(request) {
|
|
1132
|
+
let harness;
|
|
1133
|
+
const advanced = request.capabilities.has(imagegenOptions.id);
|
|
1134
|
+
const options = advanced ? request.capabilities.get(imagegenOptions) : baseline(request, async (id, context) => {
|
|
1135
|
+
if (!harness)
|
|
1136
|
+
throw new Error("Imagegen component is not bound to a Harness");
|
|
1137
|
+
return harness.conversation(id, context);
|
|
1138
|
+
});
|
|
1139
|
+
const cookies = createComponentCookieStores();
|
|
1140
|
+
const api = createImageGenerationExtension({
|
|
1141
|
+
...options,
|
|
1142
|
+
cookieStore: options.cookieStore ?? ((provider) => cookies.forProvider(provider))
|
|
1143
|
+
});
|
|
1144
|
+
return {
|
|
1145
|
+
extensions: [api],
|
|
1146
|
+
api,
|
|
1147
|
+
retention: advanced ? "idle" : "harness",
|
|
1148
|
+
bind(binding) {
|
|
1149
|
+
if (!advanced)
|
|
1150
|
+
harness = binding.harness;
|
|
1151
|
+
},
|
|
1152
|
+
afterClose() {
|
|
1153
|
+
harness = undefined;
|
|
1154
|
+
cookies.close();
|
|
1155
|
+
}
|
|
1156
|
+
};
|
|
1157
|
+
}
|
|
1158
|
+
export {
|
|
1159
|
+
createComponent,
|
|
1160
|
+
imagegenOptions
|
|
1161
|
+
};
|
package/dist/index.js
CHANGED
|
@@ -994,6 +994,7 @@ async function executeCodexImageGeneration(args, api, context, options) {
|
|
|
994
994
|
const request = await buildImageGenerationRequest(args, recentImages, env, context, resolveCodexToolModel(options.routes ?? { providers: {} }, current, IMAGE_MODEL));
|
|
995
995
|
const provider = await resolveCodexToolProvider(current, options, context);
|
|
996
996
|
const headers = codexToolProviderHeaders(provider);
|
|
997
|
+
const cookieStore = await options.cookieStore?.(provider, context);
|
|
997
998
|
headers.set("accept", "application/json");
|
|
998
999
|
headers.set("x-codex-image-turn-id", api.callId);
|
|
999
1000
|
let response;
|
|
@@ -1002,6 +1003,9 @@ async function executeCodexImageGeneration(args, api, context, options) {
|
|
|
1002
1003
|
method: "POST",
|
|
1003
1004
|
headers,
|
|
1004
1005
|
body: JSON.stringify(request.body),
|
|
1006
|
+
...options.fetch ? { fetch: options.fetch } : {},
|
|
1007
|
+
...options.runtime ? { runtime: options.runtime } : {},
|
|
1008
|
+
...cookieStore ? { cookieStore } : {},
|
|
1005
1009
|
...context.abortSignal ? { signal: context.abortSignal } : {}
|
|
1006
1010
|
});
|
|
1007
1011
|
} catch {
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { ChatGptCloudflareCookieStore } from "./cloudflare-cookies.ts";
|
|
2
|
+
import type { CodexToolProvider } from "./types.ts";
|
|
3
|
+
/** Marketplace-owned ephemeral cookies. Legacy direct factories retain their existing policy. */
|
|
4
|
+
export declare function createComponentCookieStores(): {
|
|
5
|
+
forProvider(provider: CodexToolProvider): ChatGptCloudflareCookieStore;
|
|
6
|
+
close(): void;
|
|
7
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type ComponentInstance, type ComponentRequest } from "@howaboua/pi-durable-components";
|
|
2
|
+
import { createImageGenerationExtension, type ImageGenerationToolOptions } from "./index.ts";
|
|
3
|
+
/** All original route options, with explicit egress and conversation history access. */
|
|
4
|
+
export interface ImagegenComponentOptions extends ImageGenerationToolOptions {
|
|
5
|
+
fetch: typeof globalThis.fetch;
|
|
6
|
+
conversation: NonNullable<ImageGenerationToolOptions["conversation"]>;
|
|
7
|
+
}
|
|
8
|
+
export declare const imagegenOptions: import("@howaboua/pi-durable-components").ComponentCapability<ImagegenComponentOptions>;
|
|
9
|
+
export declare function createComponent(request: ComponentRequest): ComponentInstance<ReturnType<typeof createImageGenerationExtension>>;
|
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
import type { Context } from "@earendil-works/chord";
|
|
2
2
|
import type { Conversation, ConversationId, ToolExecutionApi } from "@earendil-works/pi-durable";
|
|
3
|
-
import type {
|
|
3
|
+
import type { CodexCookieStore } from "../../../internal/codex/cloudflare-cookies.ts";
|
|
4
|
+
import type { CodexRuntimeOptions, CodexToolProvider } from "../../../internal/codex/types.ts";
|
|
4
5
|
import { type ImagegenArgs } from "./contract.ts";
|
|
5
6
|
export interface ImageGenerationToolOptions extends CodexRuntimeOptions {
|
|
7
|
+
/** Explicit host-owned egress; omitted by existing native callers. */
|
|
8
|
+
fetch?: typeof globalThis.fetch;
|
|
9
|
+
runtime?: "node" | "workerd";
|
|
10
|
+
cookieStore?: (provider: CodexToolProvider, context: Context) => CodexCookieStore | Promise<CodexCookieStore>;
|
|
6
11
|
/** Durable 1.0.2's tool conversation handle has no context reader. */
|
|
7
12
|
conversation?: (id: ConversationId, context: Context) => Promise<Pick<Conversation, "context"> | undefined>;
|
|
8
13
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@howaboua/pi-durable-imagegen",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"description": "Codex image generation and editing for Pi Durable",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -23,6 +23,10 @@
|
|
|
23
23
|
".": {
|
|
24
24
|
"types": "./dist/packages/imagegen/src/index.d.ts",
|
|
25
25
|
"import": "./dist/index.js"
|
|
26
|
+
},
|
|
27
|
+
"./component": {
|
|
28
|
+
"types": "./dist/packages/imagegen/src/activation.d.ts",
|
|
29
|
+
"import": "./dist/activation.js"
|
|
26
30
|
}
|
|
27
31
|
},
|
|
28
32
|
"files": [
|
|
@@ -35,15 +39,33 @@
|
|
|
35
39
|
"dependencies": {
|
|
36
40
|
"proxy-from-env": "2.1.0",
|
|
37
41
|
"undici": "8.10.2",
|
|
38
|
-
"typebox": "1.3.27"
|
|
42
|
+
"typebox": "1.3.27",
|
|
43
|
+
"@howaboua/pi-durable-components": "0.11.0"
|
|
39
44
|
},
|
|
40
45
|
"peerDependencies": {
|
|
41
|
-
"@earendil-works/chord": "1.
|
|
42
|
-
"@earendil-works/pi-ai": "1.
|
|
43
|
-
"@earendil-works/pi-durable": "1.
|
|
44
|
-
"@modelcontextprotocol/sdk": "1.25.2"
|
|
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"
|
|
45
50
|
},
|
|
46
51
|
"publishConfig": {
|
|
47
52
|
"access": "public"
|
|
53
|
+
},
|
|
54
|
+
"durable": {
|
|
55
|
+
"schemaVersion": 1,
|
|
56
|
+
"kind": "extension",
|
|
57
|
+
"entry": "./component",
|
|
58
|
+
"runtimes": [
|
|
59
|
+
"node"
|
|
60
|
+
],
|
|
61
|
+
"requires": [
|
|
62
|
+
"durable.models.v1",
|
|
63
|
+
"durable.network.v1"
|
|
64
|
+
],
|
|
65
|
+
"permissions": [
|
|
66
|
+
"filesystem",
|
|
67
|
+
"network",
|
|
68
|
+
"models"
|
|
69
|
+
]
|
|
48
70
|
}
|
|
49
71
|
}
|