pi-codex-image-gen 0.1.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/LICENSE +201 -0
- package/README.md +111 -0
- package/extensions/codex-image-gen.ts +468 -0
- package/package.json +22 -0
- package/skills/imagegen/LICENSE.txt +201 -0
- package/skills/imagegen/SKILL.md +359 -0
- package/skills/imagegen/assets/imagegen-small.svg +5 -0
- package/skills/imagegen/assets/imagegen.png +0 -0
- package/skills/imagegen/references/cli.md +241 -0
- package/skills/imagegen/references/codex-network.md +33 -0
- package/skills/imagegen/references/image-api.md +90 -0
- package/skills/imagegen/references/prompting.md +118 -0
- package/skills/imagegen/references/sample-prompts.md +433 -0
- package/skills/imagegen/scripts/image_gen.py +995 -0
- package/skills/imagegen/scripts/remove_chroma_key.py +440 -0
|
@@ -0,0 +1,468 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Project-local Codex image generation extension.
|
|
3
|
+
*
|
|
4
|
+
* Registers `codex_generate_image`, a tool that uses Pi's existing
|
|
5
|
+
* openai-codex ChatGPT/Codex auth to call the Codex Responses backend with the
|
|
6
|
+
* native `image_generation` tool. The backend maps that tool to gpt-image-2.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { readFileSync } from "node:fs";
|
|
10
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
11
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
12
|
+
import { StringEnum } from "@mariozechner/pi-ai";
|
|
13
|
+
import { type ExtensionAPI, getAgentDir, withFileMutationQueue } from "@mariozechner/pi-coding-agent";
|
|
14
|
+
import { type Static, Type } from "typebox";
|
|
15
|
+
|
|
16
|
+
const PROVIDER = "openai-codex";
|
|
17
|
+
const DEFAULT_MODEL = "gpt-5.5";
|
|
18
|
+
const CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
|
|
19
|
+
const JWT_CLAIM_PATH = "https://api.openai.com/auth";
|
|
20
|
+
const DEFAULT_SAVE_MODE = "global";
|
|
21
|
+
const OPENAI_BETA_HEADER = "responses=experimental";
|
|
22
|
+
const MAX_RETRIES = 3;
|
|
23
|
+
const BASE_DELAY_MS = 1000;
|
|
24
|
+
|
|
25
|
+
const SAVE_MODES = ["none", "project", "global", "custom"] as const;
|
|
26
|
+
type SaveMode = (typeof SAVE_MODES)[number];
|
|
27
|
+
|
|
28
|
+
const OUTPUT_FORMATS = ["png", "jpeg", "webp"] as const;
|
|
29
|
+
type OutputFormat = (typeof OUTPUT_FORMATS)[number];
|
|
30
|
+
|
|
31
|
+
// --- #1: Retry helpers with exponential backoff + jitter ---
|
|
32
|
+
|
|
33
|
+
function isRetryableStatus(status: number, errorText: string): boolean {
|
|
34
|
+
if ([429, 500, 502, 503, 504].includes(status)) return true;
|
|
35
|
+
return /rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(errorText);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function backoffMs(attempt: number): number {
|
|
39
|
+
const jitter = 0.9 + Math.random() * 0.2; // matches codex-rs jitter range
|
|
40
|
+
return BASE_DELAY_MS * 2 ** (attempt - 1) * jitter;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// --- Tool parameter schema ---
|
|
44
|
+
|
|
45
|
+
const TOOL_PARAMS = Type.Object({
|
|
46
|
+
prompt: Type.String({ description: "The image prompt. Be specific about subject, composition, style, text, and constraints." }),
|
|
47
|
+
model: Type.Optional(
|
|
48
|
+
Type.String({ description: `Codex model that should invoke image generation. Defaults to ${DEFAULT_MODEL}.` }),
|
|
49
|
+
),
|
|
50
|
+
outputFormat: Type.Optional(StringEnum(OUTPUT_FORMATS)),
|
|
51
|
+
save: Type.Optional(StringEnum(SAVE_MODES)),
|
|
52
|
+
saveDir: Type.Optional(
|
|
53
|
+
Type.String({
|
|
54
|
+
description: "Directory to save the image when save=custom. Relative paths resolve under the current workspace.",
|
|
55
|
+
}),
|
|
56
|
+
),
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
type ToolParams = Static<typeof TOOL_PARAMS>;
|
|
60
|
+
|
|
61
|
+
// --- Config types ---
|
|
62
|
+
|
|
63
|
+
interface ExtensionConfig {
|
|
64
|
+
save?: SaveMode;
|
|
65
|
+
saveDir?: string;
|
|
66
|
+
model?: string;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
interface SaveConfig {
|
|
70
|
+
mode: SaveMode;
|
|
71
|
+
outputDir?: string;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
interface GeneratedImage {
|
|
75
|
+
id: string;
|
|
76
|
+
status: string;
|
|
77
|
+
result: string;
|
|
78
|
+
revisedPrompt?: string;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
interface ParsedCodexResponse {
|
|
82
|
+
image?: GeneratedImage;
|
|
83
|
+
text: string[];
|
|
84
|
+
responseId?: string;
|
|
85
|
+
usage?: unknown;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// --- #11: Typed SSE event discriminated union ---
|
|
89
|
+
|
|
90
|
+
type CodexSseEvent =
|
|
91
|
+
| { type: "error"; message?: string; code?: string }
|
|
92
|
+
| { type: "response.failed"; response?: { error?: { message?: string } } }
|
|
93
|
+
| { type: "response.created"; response?: { id?: string } }
|
|
94
|
+
| { type: "response.output_text.delta"; delta?: string }
|
|
95
|
+
| {
|
|
96
|
+
type: "response.output_item.done";
|
|
97
|
+
item?: {
|
|
98
|
+
type?: string;
|
|
99
|
+
id?: string | number;
|
|
100
|
+
status?: string;
|
|
101
|
+
result?: string;
|
|
102
|
+
revised_prompt?: string;
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
| { type: "response.completed"; response?: { id?: string; usage?: unknown } };
|
|
106
|
+
|
|
107
|
+
// --- JWT helpers ---
|
|
108
|
+
|
|
109
|
+
function decodeJwtPayload(token: string): Record<string, unknown> {
|
|
110
|
+
const parts = token.split(".");
|
|
111
|
+
if (parts.length !== 3 || !parts[1]) {
|
|
112
|
+
throw new Error("OpenAI Codex auth token is not a JWT. Run /login for openai-codex again.");
|
|
113
|
+
}
|
|
114
|
+
try {
|
|
115
|
+
return JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8")) as Record<string, unknown>;
|
|
116
|
+
} catch (error) {
|
|
117
|
+
throw new Error(`Failed to decode OpenAI Codex auth token: ${error instanceof Error ? error.message : String(error)}`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function extractChatGptAccountId(token: string): string {
|
|
122
|
+
const payload = decodeJwtPayload(token);
|
|
123
|
+
const authClaims = payload[JWT_CLAIM_PATH];
|
|
124
|
+
if (!authClaims || typeof authClaims !== "object") {
|
|
125
|
+
throw new Error("OpenAI Codex auth token does not contain ChatGPT auth claims. Run /login for openai-codex again.");
|
|
126
|
+
}
|
|
127
|
+
const accountId = (authClaims as Record<string, unknown>).chatgpt_account_id;
|
|
128
|
+
if (typeof accountId !== "string" || accountId.length === 0) {
|
|
129
|
+
throw new Error("OpenAI Codex auth token does not contain chatgpt_account_id. Run /login for openai-codex again.");
|
|
130
|
+
}
|
|
131
|
+
return accountId;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// --- #10: try/catch readConfigFile replaces racy existsSync + readFileSync ---
|
|
135
|
+
|
|
136
|
+
function readConfigFile(path: string): ExtensionConfig {
|
|
137
|
+
try {
|
|
138
|
+
return JSON.parse(readFileSync(path, "utf8")) ?? {};
|
|
139
|
+
} catch {
|
|
140
|
+
return {};
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function loadConfig(cwd: string): ExtensionConfig {
|
|
145
|
+
const globalConfig = readConfigFile(join(getAgentDir(), "extensions", "codex-image-gen.json"));
|
|
146
|
+
const projectConfig = readConfigFile(join(cwd, ".pi", "extensions", "codex-image-gen.json"));
|
|
147
|
+
return { ...globalConfig, ...projectConfig };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// --- Path helpers ---
|
|
151
|
+
|
|
152
|
+
function resolveUnderCwd(cwd: string, path: string): string {
|
|
153
|
+
return isAbsolute(path) ? path : resolve(cwd, path);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function sanitizePathPart(value: string, fallback: string): string {
|
|
157
|
+
const sanitized = value
|
|
158
|
+
.split("")
|
|
159
|
+
.map((ch) => (/[a-zA-Z0-9_-]/.test(ch) ? ch : "_"))
|
|
160
|
+
.join("")
|
|
161
|
+
.replace(/_+$/g, "");
|
|
162
|
+
return sanitized || fallback;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// --- #5: resolveSaveConfig accepts pre-loaded config (no double loadConfig) ---
|
|
166
|
+
|
|
167
|
+
function resolveSaveConfig(params: ToolParams, cwd: string, sessionId: string, config: ExtensionConfig): SaveConfig {
|
|
168
|
+
const envMode = process.env.PI_CODEX_IMAGE_SAVE_MODE?.toLowerCase();
|
|
169
|
+
const mode = (params.save || envMode || config.save || DEFAULT_SAVE_MODE) as SaveMode;
|
|
170
|
+
const safeSessionId = sanitizePathPart(sessionId, "session");
|
|
171
|
+
if (!SAVE_MODES.includes(mode)) {
|
|
172
|
+
throw new Error(`Invalid save mode: ${mode}. Expected one of ${SAVE_MODES.join(", ")}.`);
|
|
173
|
+
}
|
|
174
|
+
if (mode === "project") {
|
|
175
|
+
return { mode, outputDir: join(cwd, ".pi", "generated-images", safeSessionId) };
|
|
176
|
+
}
|
|
177
|
+
if (mode === "global") {
|
|
178
|
+
return { mode, outputDir: join(getAgentDir(), "generated-images", safeSessionId) };
|
|
179
|
+
}
|
|
180
|
+
if (mode === "custom") {
|
|
181
|
+
const configuredDir = params.saveDir || process.env.PI_CODEX_IMAGE_SAVE_DIR || config.saveDir;
|
|
182
|
+
if (!configuredDir || !configuredDir.trim()) {
|
|
183
|
+
throw new Error("save=custom requires saveDir or PI_CODEX_IMAGE_SAVE_DIR.");
|
|
184
|
+
}
|
|
185
|
+
return { mode, outputDir: join(resolveUnderCwd(cwd, configuredDir), safeSessionId) };
|
|
186
|
+
}
|
|
187
|
+
return { mode };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// --- Image save helpers ---
|
|
191
|
+
|
|
192
|
+
function extensionForFormat(outputFormat: OutputFormat): string {
|
|
193
|
+
return outputFormat === "jpeg" ? "jpg" : outputFormat;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function mimeForFormat(outputFormat: OutputFormat): string {
|
|
197
|
+
return outputFormat === "jpeg" ? "image/jpeg" : `image/${outputFormat}`;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async function saveImage(base64Data: string, outputFormat: OutputFormat, outputDir: string, imageCallId: string): Promise<string> {
|
|
201
|
+
const filename = `${sanitizePathPart(imageCallId, "image_generation")}.${extensionForFormat(outputFormat)}`;
|
|
202
|
+
const filePath = join(outputDir, filename);
|
|
203
|
+
await withFileMutationQueue(filePath, async () => {
|
|
204
|
+
await mkdir(outputDir, { recursive: true });
|
|
205
|
+
await writeFile(filePath, Buffer.from(base64Data, "base64"));
|
|
206
|
+
});
|
|
207
|
+
return filePath;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// --- Request building ---
|
|
211
|
+
// #2: prompt_cache_key set to sessionId
|
|
212
|
+
// #7: parallel_tool_calls: false
|
|
213
|
+
// #14: include removed (not needed without reasoning)
|
|
214
|
+
|
|
215
|
+
function buildRequestBody(params: ToolParams, model: string, outputFormat: OutputFormat, sessionId: string) {
|
|
216
|
+
return {
|
|
217
|
+
model,
|
|
218
|
+
store: false,
|
|
219
|
+
stream: true,
|
|
220
|
+
prompt_cache_key: sessionId,
|
|
221
|
+
instructions:
|
|
222
|
+
"You are generating bitmap image assets. For this request, call the image_generation tool exactly once. Do not answer with only text unless image generation is unavailable.",
|
|
223
|
+
input: [
|
|
224
|
+
{
|
|
225
|
+
role: "user",
|
|
226
|
+
content: [{ type: "input_text", text: params.prompt }],
|
|
227
|
+
},
|
|
228
|
+
],
|
|
229
|
+
tools: [{ type: "image_generation", output_format: outputFormat }],
|
|
230
|
+
tool_choice: "auto",
|
|
231
|
+
parallel_tool_calls: false,
|
|
232
|
+
text: { verbosity: "low" },
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// --- SSE parsing ---
|
|
237
|
+
|
|
238
|
+
function parseSseDataLines(chunk: string): string | undefined {
|
|
239
|
+
const data = chunk
|
|
240
|
+
.split("\n")
|
|
241
|
+
.filter((line) => line.startsWith("data:"))
|
|
242
|
+
.map((line) => line.slice(5).trim())
|
|
243
|
+
.join("\n")
|
|
244
|
+
.trim();
|
|
245
|
+
return data && data !== "[DONE]" ? data : undefined;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async function parseCodexSse(response: Response, signal?: AbortSignal): Promise<ParsedCodexResponse> {
|
|
249
|
+
if (!response.body) throw new Error("Codex response did not include a stream body.");
|
|
250
|
+
const reader = response.body.getReader();
|
|
251
|
+
const decoder = new TextDecoder();
|
|
252
|
+
let buffer = "";
|
|
253
|
+
const parsed: ParsedCodexResponse = { text: [] };
|
|
254
|
+
|
|
255
|
+
try {
|
|
256
|
+
while (true) {
|
|
257
|
+
if (signal?.aborted) throw new Error("Image generation was aborted.");
|
|
258
|
+
const { done, value } = await reader.read();
|
|
259
|
+
if (done) break;
|
|
260
|
+
buffer += decoder.decode(value, { stream: true });
|
|
261
|
+
|
|
262
|
+
let separator = buffer.indexOf("\n\n");
|
|
263
|
+
while (separator !== -1) {
|
|
264
|
+
const chunk = buffer.slice(0, separator);
|
|
265
|
+
buffer = buffer.slice(separator + 2);
|
|
266
|
+
const data = parseSseDataLines(chunk);
|
|
267
|
+
if (data) handleCodexEvent(JSON.parse(data) as CodexSseEvent, parsed);
|
|
268
|
+
separator = buffer.indexOf("\n\n");
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
const remaining = parseSseDataLines(buffer);
|
|
272
|
+
if (remaining) handleCodexEvent(JSON.parse(remaining) as CodexSseEvent, parsed);
|
|
273
|
+
} finally {
|
|
274
|
+
try {
|
|
275
|
+
await reader.cancel();
|
|
276
|
+
} catch {
|
|
277
|
+
// ignored: stream may already be closed
|
|
278
|
+
}
|
|
279
|
+
reader.releaseLock();
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
return parsed;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// --- #11: Typed event handler via discriminated union ---
|
|
286
|
+
|
|
287
|
+
function handleCodexEvent(event: CodexSseEvent, parsed: ParsedCodexResponse): void {
|
|
288
|
+
if (!event || typeof event !== "object") return;
|
|
289
|
+
|
|
290
|
+
switch (event.type) {
|
|
291
|
+
case "error": {
|
|
292
|
+
const e = event as Extract<CodexSseEvent, { type: "error" }>;
|
|
293
|
+
throw new Error(`Codex error: ${e.message || e.code || JSON.stringify(event)}`);
|
|
294
|
+
}
|
|
295
|
+
case "response.failed": {
|
|
296
|
+
const e = event as Extract<CodexSseEvent, { type: "response.failed" }>;
|
|
297
|
+
throw new Error(e.response?.error?.message || "Codex response failed.");
|
|
298
|
+
}
|
|
299
|
+
case "response.created": {
|
|
300
|
+
const e = event as Extract<CodexSseEvent, { type: "response.created" }>;
|
|
301
|
+
if (typeof e.response?.id === "string") {
|
|
302
|
+
parsed.responseId = e.response.id;
|
|
303
|
+
}
|
|
304
|
+
break;
|
|
305
|
+
}
|
|
306
|
+
case "response.output_text.delta": {
|
|
307
|
+
const e = event as Extract<CodexSseEvent, { type: "response.output_text.delta" }>;
|
|
308
|
+
if (typeof e.delta === "string") {
|
|
309
|
+
parsed.text.push(e.delta);
|
|
310
|
+
}
|
|
311
|
+
break;
|
|
312
|
+
}
|
|
313
|
+
case "response.output_item.done": {
|
|
314
|
+
const e = event as Extract<CodexSseEvent, { type: "response.output_item.done" }>;
|
|
315
|
+
const item = e.item;
|
|
316
|
+
if (item?.type === "image_generation_call") {
|
|
317
|
+
if (typeof item.result !== "string" || item.result.length === 0) {
|
|
318
|
+
throw new Error("Codex image_generation_call did not contain image data.");
|
|
319
|
+
}
|
|
320
|
+
parsed.image = {
|
|
321
|
+
id: String(item.id || "image_generation"),
|
|
322
|
+
status: String(item.status || "completed"),
|
|
323
|
+
result: item.result,
|
|
324
|
+
revisedPrompt: typeof item.revised_prompt === "string" ? item.revised_prompt : undefined,
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
break;
|
|
328
|
+
}
|
|
329
|
+
case "response.completed": {
|
|
330
|
+
const e = event as Extract<CodexSseEvent, { type: "response.completed" }>;
|
|
331
|
+
if (typeof e.response?.id === "string") parsed.responseId = e.response.id;
|
|
332
|
+
if (e.response?.usage) parsed.usage = e.response.usage;
|
|
333
|
+
break;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// --- #1: requestImage with retry + backoff + jitter ---
|
|
339
|
+
|
|
340
|
+
async function requestImage(
|
|
341
|
+
params: ToolParams,
|
|
342
|
+
token: string,
|
|
343
|
+
accountId: string,
|
|
344
|
+
model: string,
|
|
345
|
+
outputFormat: OutputFormat,
|
|
346
|
+
sessionId: string,
|
|
347
|
+
signal?: AbortSignal,
|
|
348
|
+
): Promise<ParsedCodexResponse> {
|
|
349
|
+
const body = JSON.stringify(buildRequestBody(params, model, outputFormat, sessionId));
|
|
350
|
+
const headers: Record<string, string> = {
|
|
351
|
+
Authorization: `Bearer ${token}`,
|
|
352
|
+
"chatgpt-account-id": accountId,
|
|
353
|
+
originator: "pi",
|
|
354
|
+
"OpenAI-Beta": OPENAI_BETA_HEADER,
|
|
355
|
+
accept: "text/event-stream",
|
|
356
|
+
"content-type": "application/json",
|
|
357
|
+
};
|
|
358
|
+
|
|
359
|
+
for (let attempt = 1; attempt <= MAX_RETRIES + 1; attempt++) {
|
|
360
|
+
if (signal?.aborted) throw new Error("Image generation was aborted.");
|
|
361
|
+
|
|
362
|
+
const response = await fetch(CODEX_RESPONSES_URL, {
|
|
363
|
+
method: "POST",
|
|
364
|
+
headers,
|
|
365
|
+
body,
|
|
366
|
+
signal,
|
|
367
|
+
});
|
|
368
|
+
|
|
369
|
+
if (!response.ok) {
|
|
370
|
+
const errorText = await response.text();
|
|
371
|
+
if (attempt <= MAX_RETRIES && isRetryableStatus(response.status, errorText)) {
|
|
372
|
+
const delay = backoffMs(attempt);
|
|
373
|
+
await new Promise<void>((resolve) => setTimeout(resolve, delay));
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
throw new Error(`Codex image generation request failed (${response.status}): ${errorText}`);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
return parseCodexSse(response, signal);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
throw new Error("Codex image generation request failed after all retries.");
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// --- Extension entry point ---
|
|
386
|
+
|
|
387
|
+
export default function codexImageGen(pi: ExtensionAPI) {
|
|
388
|
+
pi.registerTool({
|
|
389
|
+
name: "codex_generate_image",
|
|
390
|
+
label: "Codex Image",
|
|
391
|
+
description:
|
|
392
|
+
"Generate an image with the OpenAI Codex ChatGPT backend built-in image_generation tool (gpt-image-2). Uses the existing openai-codex login; does not require OPENAI_API_KEY.",
|
|
393
|
+
promptSnippet: "Generate bitmap images via the OpenAI Codex ChatGPT backend gpt-image-2 image_generation tool.",
|
|
394
|
+
promptGuidelines: [
|
|
395
|
+
"Use codex_generate_image when the user asks to generate a raster image, illustration, photo, sprite, icon draft, banner, or other bitmap asset with OpenAI/Codex image generation.",
|
|
396
|
+
"Do not use codex_generate_image without a clear image-generation request, because it consumes the user's Codex image quota.",
|
|
397
|
+
],
|
|
398
|
+
parameters: TOOL_PARAMS,
|
|
399
|
+
executionMode: "parallel", // #4: safe to run concurrently — no shared state, saves serialized per-path
|
|
400
|
+
async execute(toolCallId, params: ToolParams, signal, onUpdate, ctx) {
|
|
401
|
+
const outputFormat = params.outputFormat || "png";
|
|
402
|
+
const config = loadConfig(ctx.cwd); // #5: load once, pass to resolveSaveConfig
|
|
403
|
+
const requestedModel = params.model || config.model || DEFAULT_MODEL;
|
|
404
|
+
const model = ctx.modelRegistry.find(PROVIDER, requestedModel)?.id || requestedModel; // #6: removed dead FALLBACK_MODEL
|
|
405
|
+
const token = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER);
|
|
406
|
+
if (!token) {
|
|
407
|
+
throw new Error(`Missing ${PROVIDER} credentials. Run /login and select ChatGPT Plus/Pro (Codex).`);
|
|
408
|
+
}
|
|
409
|
+
const accountId = extractChatGptAccountId(token);
|
|
410
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
411
|
+
|
|
412
|
+
onUpdate?.({
|
|
413
|
+
content: [{ type: "text", text: `Requesting gpt-image-2 generation through ${PROVIDER}/${model}...` }],
|
|
414
|
+
details: { provider: PROVIDER, model, outputFormat },
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
const parsed = await requestImage(params, token, accountId, model, outputFormat, sessionId, signal);
|
|
418
|
+
if (!parsed.image) {
|
|
419
|
+
const text = parsed.text.join("").trim();
|
|
420
|
+
throw new Error(text ? `Codex did not return an image. Response text: ${text}` : "Codex did not return an image.");
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
const saveConfig = resolveSaveConfig(params, ctx.cwd, sessionId, config);
|
|
424
|
+
let savedPath: string | undefined;
|
|
425
|
+
if (saveConfig.mode !== "none" && saveConfig.outputDir) {
|
|
426
|
+
savedPath = await saveImage(parsed.image.result, outputFormat, saveConfig.outputDir, parsed.image.id || toolCallId);
|
|
427
|
+
// #12: second onUpdate after save with path + byte count
|
|
428
|
+
onUpdate?.({
|
|
429
|
+
content: [{ type: "text", text: `Image saved to ${savedPath}.` }],
|
|
430
|
+
details: {
|
|
431
|
+
provider: PROVIDER,
|
|
432
|
+
model,
|
|
433
|
+
savedPath,
|
|
434
|
+
byteCount: Buffer.byteLength(parsed.image.result, "base64"),
|
|
435
|
+
},
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
const summary = [
|
|
440
|
+
`Generated image via ${PROVIDER}/${model} using backend gpt-image-2.`,
|
|
441
|
+
`Status: ${parsed.image.status}.`,
|
|
442
|
+
parsed.image.revisedPrompt ? `Revised prompt: ${parsed.image.revisedPrompt}` : undefined,
|
|
443
|
+
savedPath ? `Saved image to: ${savedPath}` : "Image was not saved to disk.",
|
|
444
|
+
]
|
|
445
|
+
.filter(Boolean)
|
|
446
|
+
.join(" ");
|
|
447
|
+
|
|
448
|
+
return {
|
|
449
|
+
content: [
|
|
450
|
+
{ type: "text", text: summary },
|
|
451
|
+
{ type: "image", data: parsed.image.result, mimeType: mimeForFormat(outputFormat) },
|
|
452
|
+
],
|
|
453
|
+
details: {
|
|
454
|
+
provider: PROVIDER,
|
|
455
|
+
model,
|
|
456
|
+
backendImageModel: "gpt-image-2",
|
|
457
|
+
outputFormat,
|
|
458
|
+
saveMode: saveConfig.mode,
|
|
459
|
+
savedPath,
|
|
460
|
+
responseId: parsed.responseId,
|
|
461
|
+
imageGenerationId: parsed.image.id,
|
|
462
|
+
revisedPrompt: parsed.image.revisedPrompt,
|
|
463
|
+
usage: parsed.usage,
|
|
464
|
+
},
|
|
465
|
+
};
|
|
466
|
+
},
|
|
467
|
+
});
|
|
468
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "pi-codex-image-gen",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Image generation for Pi using the ChatGPT Images 2.0 model.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"files": ["extensions", "skills", "README.md", "LICENSE"],
|
|
7
|
+
"keywords": ["pi-package", "pi", "codex", "image-generation", "gpt-image-2"],
|
|
8
|
+
"type": "module",
|
|
9
|
+
"peerDependencies": {
|
|
10
|
+
"@mariozechner/pi-ai": "^0.70.2",
|
|
11
|
+
"@mariozechner/pi-coding-agent": "^0.70.2",
|
|
12
|
+
"typebox": "^1.1.33"
|
|
13
|
+
},
|
|
14
|
+
"pi": {
|
|
15
|
+
"extensions": ["./extensions"],
|
|
16
|
+
"skills": ["./skills"]
|
|
17
|
+
},
|
|
18
|
+
"devDependencies": {
|
|
19
|
+
"@types/node": "^25.6.0",
|
|
20
|
+
"typescript": "^6.0.3"
|
|
21
|
+
}
|
|
22
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf of
|
|
171
|
+
any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don\'t include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|