pi-codex-image-gen 0.1.8 → 0.1.10
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/CHANGELOG.md +14 -0
- package/CONTRIBUTING.md +2 -2
- package/NOTICE +20 -0
- package/README.md +16 -2
- package/extensions/index.ts +472 -0
- package/index.ts +1 -549
- package/package.json +22 -10
- package/src/index.ts +1 -0
- package/src/install-telemetry.ts +104 -0
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,20 @@ This project follows the spirit of [Keep a Changelog](https://keepachangelog.com
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [0.1.10] - 2026-06-06
|
|
10
|
+
|
|
11
|
+
### Changed
|
|
12
|
+
|
|
13
|
+
- Restructured package to follow monorepo guidelines (added root `index.ts` re-export, moved extension code to `extensions/index.ts`, extracted telemetry to `src/install-telemetry.ts`).
|
|
14
|
+
- Update `author` field to full name for monorepo consistency.
|
|
15
|
+
|
|
16
|
+
## [0.1.9] - 2026-05-20
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
|
|
20
|
+
- Moved package source to the `jvm/pi-mono` monorepo.
|
|
21
|
+
- Updated npm metadata to point at the monorepo package directory.
|
|
22
|
+
|
|
9
23
|
## [0.1.8] - 2026-05-10
|
|
10
24
|
|
|
11
25
|
### Fixed
|
package/CONTRIBUTING.md
CHANGED
|
@@ -18,7 +18,7 @@ Install this checkout into a temporary Pi project:
|
|
|
18
18
|
```bash
|
|
19
19
|
mkdir -p <test-project>
|
|
20
20
|
cd <test-project>
|
|
21
|
-
pi
|
|
21
|
+
pi install -l /path/to/pi-mono/packages/pi-codex-image-gen
|
|
22
22
|
pi
|
|
23
23
|
```
|
|
24
24
|
|
|
@@ -27,7 +27,7 @@ Then run `/login` for `openai-codex` and ask Pi to generate an image.
|
|
|
27
27
|
For a one-off run without changing settings:
|
|
28
28
|
|
|
29
29
|
```bash
|
|
30
|
-
pi -e /path/to/pi-codex-image-gen
|
|
30
|
+
pi -e /path/to/pi-mono/packages/pi-codex-image-gen
|
|
31
31
|
```
|
|
32
32
|
|
|
33
33
|
To validate the Python CLI fallback without an API key:
|
package/NOTICE
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
pi-codex-image-gen includes imagegen skill helper files derived from OpenAI Codex.
|
|
2
|
+
|
|
3
|
+
OpenAI Codex
|
|
4
|
+
Copyright 2025 OpenAI
|
|
5
|
+
Licensed under the Apache License, Version 2.0.
|
|
6
|
+
Source: https://github.com/openai/codex
|
|
7
|
+
|
|
8
|
+
The following files are vendored from the OpenAI Codex imagegen skill and remain under the Apache License, Version 2.0:
|
|
9
|
+
|
|
10
|
+
- skills/imagegen/scripts/image_gen.py
|
|
11
|
+
- skills/imagegen/scripts/remove_chroma_key.py
|
|
12
|
+
- skills/imagegen/references/cli.md
|
|
13
|
+
- skills/imagegen/references/codex-network.md
|
|
14
|
+
- skills/imagegen/references/image-api.md
|
|
15
|
+
- skills/imagegen/references/prompting.md
|
|
16
|
+
- skills/imagegen/references/sample-prompts.md
|
|
17
|
+
- skills/imagegen/SKILL.md
|
|
18
|
+
- skills/imagegen/LICENSE.txt
|
|
19
|
+
- skills/imagegen/assets/imagegen-small.svg
|
|
20
|
+
- skills/imagegen/assets/imagegen.png
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# pi-codex-image-gen
|
|
2
2
|
|
|
3
|
-
Image generation for [Pi](https://
|
|
3
|
+
Image generation for [Pi](https://pi.dev) using the ChatGPT Images 2.0 model via the OpenAI Codex Responses backend.
|
|
4
4
|
|
|
5
5
|
## Install
|
|
6
6
|
|
|
@@ -8,6 +8,18 @@ Image generation for [Pi](https://github.com/badlogic/pi-mono) using the ChatGPT
|
|
|
8
8
|
pi install npm:pi-codex-image-gen
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
+
During local development from this monorepo:
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
pi install /path/to/pi-mono/packages/pi-codex-image-gen
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
For a one-off test run without installing:
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
pi -e /path/to/pi-mono/packages/pi-codex-image-gen
|
|
21
|
+
```
|
|
22
|
+
|
|
11
23
|
To uninstall:
|
|
12
24
|
|
|
13
25
|
```sh
|
|
@@ -110,4 +122,6 @@ Project config overrides global config. Example:
|
|
|
110
122
|
|
|
111
123
|
## License
|
|
112
124
|
|
|
113
|
-
Apache-2.0
|
|
125
|
+
Apache-2.0. See [LICENSE](./LICENSE).
|
|
126
|
+
|
|
127
|
+
This package includes imagegen skill helper files derived from [OpenAI Codex](https://github.com/openai/codex), including `skills/imagegen/scripts/image_gen.py`. Those files remain under the Apache License, Version 2.0. See [NOTICE](./NOTICE) and `skills/imagegen/LICENSE.txt`.
|
|
@@ -0,0 +1,472 @@
|
|
|
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 "@earendil-works/pi-ai";
|
|
13
|
+
import { type ExtensionAPI, getAgentDir, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
|
|
14
|
+
import { type Static, Type } from "typebox";
|
|
15
|
+
import { reportInstallTelemetry } from "../src/install-telemetry.js";
|
|
16
|
+
|
|
17
|
+
const PACKAGE_NAME = "pi-codex-image-gen";
|
|
18
|
+
const PROVIDER = "openai-codex";
|
|
19
|
+
const DEFAULT_MODEL = "gpt-5.5";
|
|
20
|
+
const CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
|
|
21
|
+
const JWT_CLAIM_PATH = "https://api.openai.com/auth";
|
|
22
|
+
const DEFAULT_SAVE_MODE = "global";
|
|
23
|
+
const OPENAI_BETA_HEADER = "responses=experimental";
|
|
24
|
+
const MAX_RETRIES = 3;
|
|
25
|
+
const BASE_DELAY_MS = 1000;
|
|
26
|
+
|
|
27
|
+
const SAVE_MODES = ["none", "project", "global", "custom"] as const;
|
|
28
|
+
type SaveMode = (typeof SAVE_MODES)[number];
|
|
29
|
+
|
|
30
|
+
const OUTPUT_FORMATS = ["png", "jpeg", "webp"] as const;
|
|
31
|
+
type OutputFormat = (typeof OUTPUT_FORMATS)[number];
|
|
32
|
+
|
|
33
|
+
// --- #1: Retry helpers with exponential backoff + jitter ---
|
|
34
|
+
|
|
35
|
+
function isRetryableStatus(status: number, errorText: string): boolean {
|
|
36
|
+
if ([429, 500, 502, 503, 504].includes(status)) return true;
|
|
37
|
+
return /rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(errorText);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function backoffMs(attempt: number): number {
|
|
41
|
+
const jitter = 0.9 + Math.random() * 0.2; // matches codex-rs jitter range
|
|
42
|
+
return BASE_DELAY_MS * 2 ** (attempt - 1) * jitter;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// --- Tool parameter schema ---
|
|
46
|
+
|
|
47
|
+
const TOOL_PARAMS = Type.Object({
|
|
48
|
+
prompt: Type.String({ description: "The image prompt. Be specific about subject, composition, style, text, and constraints." }),
|
|
49
|
+
model: Type.Optional(
|
|
50
|
+
Type.String({ description: `Codex model that should invoke image generation. Defaults to ${DEFAULT_MODEL}.` }),
|
|
51
|
+
),
|
|
52
|
+
outputFormat: Type.Optional(StringEnum(OUTPUT_FORMATS)),
|
|
53
|
+
save: Type.Optional(StringEnum(SAVE_MODES)),
|
|
54
|
+
saveDir: Type.Optional(
|
|
55
|
+
Type.String({
|
|
56
|
+
description: "Directory to save the image when save=custom. Relative paths resolve under the current workspace.",
|
|
57
|
+
}),
|
|
58
|
+
),
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
type ToolParams = Static<typeof TOOL_PARAMS>;
|
|
62
|
+
|
|
63
|
+
// --- Config types ---
|
|
64
|
+
|
|
65
|
+
interface ExtensionConfig {
|
|
66
|
+
save?: SaveMode;
|
|
67
|
+
saveDir?: string;
|
|
68
|
+
model?: string;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
interface SaveConfig {
|
|
72
|
+
mode: SaveMode;
|
|
73
|
+
outputDir?: string;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
interface GeneratedImage {
|
|
77
|
+
id: string;
|
|
78
|
+
status: string;
|
|
79
|
+
result: string;
|
|
80
|
+
revisedPrompt?: string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
interface ParsedCodexResponse {
|
|
84
|
+
image?: GeneratedImage;
|
|
85
|
+
text: string[];
|
|
86
|
+
responseId?: string;
|
|
87
|
+
usage?: unknown;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// --- #11: Typed SSE event discriminated union ---
|
|
91
|
+
|
|
92
|
+
type CodexSseEvent =
|
|
93
|
+
| { type: "error"; message?: string; code?: string }
|
|
94
|
+
| { type: "response.failed"; response?: { error?: { message?: string } } }
|
|
95
|
+
| { type: "response.created"; response?: { id?: string } }
|
|
96
|
+
| { type: "response.output_text.delta"; delta?: string }
|
|
97
|
+
| {
|
|
98
|
+
type: "response.output_item.done";
|
|
99
|
+
item?: {
|
|
100
|
+
type?: string;
|
|
101
|
+
id?: string | number;
|
|
102
|
+
status?: string;
|
|
103
|
+
result?: string;
|
|
104
|
+
revised_prompt?: string;
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
| { type: "response.completed"; response?: { id?: string; usage?: unknown } };
|
|
108
|
+
|
|
109
|
+
// --- JWT helpers ---
|
|
110
|
+
|
|
111
|
+
function decodeJwtPayload(token: string): Record<string, unknown> {
|
|
112
|
+
const parts = token.split(".");
|
|
113
|
+
if (parts.length !== 3 || !parts[1]) {
|
|
114
|
+
throw new Error("OpenAI Codex auth token is not a JWT. Run /login for openai-codex again.");
|
|
115
|
+
}
|
|
116
|
+
try {
|
|
117
|
+
return JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8")) as Record<string, unknown>;
|
|
118
|
+
} catch (error) {
|
|
119
|
+
throw new Error(`Failed to decode OpenAI Codex auth token: ${error instanceof Error ? error.message : String(error)}`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function extractChatGptAccountId(token: string): string {
|
|
124
|
+
const payload = decodeJwtPayload(token);
|
|
125
|
+
const authClaims = payload[JWT_CLAIM_PATH];
|
|
126
|
+
if (!authClaims || typeof authClaims !== "object") {
|
|
127
|
+
throw new Error("OpenAI Codex auth token does not contain ChatGPT auth claims. Run /login for openai-codex again.");
|
|
128
|
+
}
|
|
129
|
+
const accountId = (authClaims as Record<string, unknown>).chatgpt_account_id;
|
|
130
|
+
if (typeof accountId !== "string" || accountId.length === 0) {
|
|
131
|
+
throw new Error("OpenAI Codex auth token does not contain chatgpt_account_id. Run /login for openai-codex again.");
|
|
132
|
+
}
|
|
133
|
+
return accountId;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// --- #10: try/catch readConfigFile replaces racy existsSync + readFileSync ---
|
|
137
|
+
|
|
138
|
+
function readConfigFile(path: string): ExtensionConfig {
|
|
139
|
+
try {
|
|
140
|
+
return JSON.parse(readFileSync(path, "utf8")) ?? {};
|
|
141
|
+
} catch {
|
|
142
|
+
return {};
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function loadConfig(cwd: string): ExtensionConfig {
|
|
147
|
+
const globalConfig = readConfigFile(join(getAgentDir(), "extensions", "codex-image-gen.json"));
|
|
148
|
+
const projectConfig = readConfigFile(join(cwd, ".pi", "extensions", "codex-image-gen.json"));
|
|
149
|
+
return { ...globalConfig, ...projectConfig };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// --- Path helpers ---
|
|
153
|
+
|
|
154
|
+
function resolveUnderCwd(cwd: string, path: string): string {
|
|
155
|
+
return isAbsolute(path) ? path : resolve(cwd, path);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function sanitizePathPart(value: string, fallback: string): string {
|
|
159
|
+
const sanitized = value
|
|
160
|
+
.split("")
|
|
161
|
+
.map((ch) => (/[a-zA-Z0-9_-]/.test(ch) ? ch : "_"))
|
|
162
|
+
.join("")
|
|
163
|
+
.replace(/_+$/g, "");
|
|
164
|
+
return sanitized || fallback;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// --- #5: resolveSaveConfig accepts pre-loaded config (no double loadConfig) ---
|
|
168
|
+
|
|
169
|
+
function resolveSaveConfig(params: ToolParams, cwd: string, sessionId: string, config: ExtensionConfig): SaveConfig {
|
|
170
|
+
const envMode = process.env.PI_CODEX_IMAGE_SAVE_MODE?.toLowerCase();
|
|
171
|
+
const mode = (params.save || envMode || config.save || DEFAULT_SAVE_MODE) as SaveMode;
|
|
172
|
+
const safeSessionId = sanitizePathPart(sessionId, "session");
|
|
173
|
+
if (!SAVE_MODES.includes(mode)) {
|
|
174
|
+
throw new Error(`Invalid save mode: ${mode}. Expected one of ${SAVE_MODES.join(", ")}.`);
|
|
175
|
+
}
|
|
176
|
+
if (mode === "project") {
|
|
177
|
+
return { mode, outputDir: join(cwd, ".pi", "generated-images", safeSessionId) };
|
|
178
|
+
}
|
|
179
|
+
if (mode === "global") {
|
|
180
|
+
return { mode, outputDir: join(getAgentDir(), "generated-images", safeSessionId) };
|
|
181
|
+
}
|
|
182
|
+
if (mode === "custom") {
|
|
183
|
+
const configuredDir = params.saveDir || process.env.PI_CODEX_IMAGE_SAVE_DIR || config.saveDir;
|
|
184
|
+
if (!configuredDir || !configuredDir.trim()) {
|
|
185
|
+
throw new Error("save=custom requires saveDir or PI_CODEX_IMAGE_SAVE_DIR.");
|
|
186
|
+
}
|
|
187
|
+
return { mode, outputDir: join(resolveUnderCwd(cwd, configuredDir), safeSessionId) };
|
|
188
|
+
}
|
|
189
|
+
return { mode };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// --- Image save helpers ---
|
|
193
|
+
|
|
194
|
+
function extensionForFormat(outputFormat: OutputFormat): string {
|
|
195
|
+
return outputFormat === "jpeg" ? "jpg" : outputFormat;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function mimeForFormat(outputFormat: OutputFormat): string {
|
|
199
|
+
return outputFormat === "jpeg" ? "image/jpeg" : `image/${outputFormat}`;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async function saveImage(base64Data: string, outputFormat: OutputFormat, outputDir: string, imageCallId: string): Promise<string> {
|
|
203
|
+
const filename = `${sanitizePathPart(imageCallId, "image_generation")}.${extensionForFormat(outputFormat)}`;
|
|
204
|
+
const filePath = join(outputDir, filename);
|
|
205
|
+
await withFileMutationQueue(filePath, async () => {
|
|
206
|
+
await mkdir(outputDir, { recursive: true });
|
|
207
|
+
await writeFile(filePath, Buffer.from(base64Data, "base64"));
|
|
208
|
+
});
|
|
209
|
+
return filePath;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// --- Request building ---
|
|
213
|
+
// #2: prompt_cache_key set to sessionId
|
|
214
|
+
// #7: parallel_tool_calls: false
|
|
215
|
+
// #14: include removed (not needed without reasoning)
|
|
216
|
+
|
|
217
|
+
function buildRequestBody(params: ToolParams, model: string, outputFormat: OutputFormat, sessionId: string) {
|
|
218
|
+
return {
|
|
219
|
+
model,
|
|
220
|
+
store: false,
|
|
221
|
+
stream: true,
|
|
222
|
+
prompt_cache_key: sessionId,
|
|
223
|
+
instructions:
|
|
224
|
+
"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.",
|
|
225
|
+
input: [
|
|
226
|
+
{
|
|
227
|
+
role: "user",
|
|
228
|
+
content: [{ type: "input_text", text: params.prompt }],
|
|
229
|
+
},
|
|
230
|
+
],
|
|
231
|
+
tools: [{ type: "image_generation", output_format: outputFormat }],
|
|
232
|
+
tool_choice: "auto",
|
|
233
|
+
parallel_tool_calls: false,
|
|
234
|
+
text: { verbosity: "low" },
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// --- SSE parsing ---
|
|
239
|
+
|
|
240
|
+
function parseSseDataLines(chunk: string): string | undefined {
|
|
241
|
+
const data = chunk
|
|
242
|
+
.split("\n")
|
|
243
|
+
.filter((line) => line.startsWith("data:"))
|
|
244
|
+
.map((line) => line.slice(5).trim())
|
|
245
|
+
.join("\n")
|
|
246
|
+
.trim();
|
|
247
|
+
return data && data !== "[DONE]" ? data : undefined;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async function parseCodexSse(response: Response, signal?: AbortSignal): Promise<ParsedCodexResponse> {
|
|
251
|
+
if (!response.body) throw new Error("Codex response did not include a stream body.");
|
|
252
|
+
const reader = response.body.getReader();
|
|
253
|
+
const decoder = new TextDecoder();
|
|
254
|
+
let buffer = "";
|
|
255
|
+
const parsed: ParsedCodexResponse = { text: [] };
|
|
256
|
+
|
|
257
|
+
try {
|
|
258
|
+
while (true) {
|
|
259
|
+
if (signal?.aborted) throw new Error("Image generation was aborted.");
|
|
260
|
+
const { done, value } = await reader.read();
|
|
261
|
+
if (done) break;
|
|
262
|
+
buffer += decoder.decode(value, { stream: true });
|
|
263
|
+
|
|
264
|
+
let separator = buffer.indexOf("\n\n");
|
|
265
|
+
while (separator !== -1) {
|
|
266
|
+
const chunk = buffer.slice(0, separator);
|
|
267
|
+
buffer = buffer.slice(separator + 2);
|
|
268
|
+
const data = parseSseDataLines(chunk);
|
|
269
|
+
if (data) handleCodexEvent(JSON.parse(data) as CodexSseEvent, parsed);
|
|
270
|
+
separator = buffer.indexOf("\n\n");
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
const remaining = parseSseDataLines(buffer);
|
|
274
|
+
if (remaining) handleCodexEvent(JSON.parse(remaining) as CodexSseEvent, parsed);
|
|
275
|
+
} finally {
|
|
276
|
+
try {
|
|
277
|
+
await reader.cancel();
|
|
278
|
+
} catch {
|
|
279
|
+
// ignored: stream may already be closed
|
|
280
|
+
}
|
|
281
|
+
reader.releaseLock();
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
return parsed;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// --- #11: Typed event handler via discriminated union ---
|
|
288
|
+
|
|
289
|
+
function handleCodexEvent(event: CodexSseEvent, parsed: ParsedCodexResponse): void {
|
|
290
|
+
if (!event || typeof event !== "object") return;
|
|
291
|
+
|
|
292
|
+
switch (event.type) {
|
|
293
|
+
case "error": {
|
|
294
|
+
const e = event as Extract<CodexSseEvent, { type: "error" }>;
|
|
295
|
+
throw new Error(`Codex error: ${e.message || e.code || JSON.stringify(event)}`);
|
|
296
|
+
}
|
|
297
|
+
case "response.failed": {
|
|
298
|
+
const e = event as Extract<CodexSseEvent, { type: "response.failed" }>;
|
|
299
|
+
throw new Error(e.response?.error?.message || "Codex response failed.");
|
|
300
|
+
}
|
|
301
|
+
case "response.created": {
|
|
302
|
+
const e = event as Extract<CodexSseEvent, { type: "response.created" }>;
|
|
303
|
+
if (typeof e.response?.id === "string") {
|
|
304
|
+
parsed.responseId = e.response.id;
|
|
305
|
+
}
|
|
306
|
+
break;
|
|
307
|
+
}
|
|
308
|
+
case "response.output_text.delta": {
|
|
309
|
+
const e = event as Extract<CodexSseEvent, { type: "response.output_text.delta" }>;
|
|
310
|
+
if (typeof e.delta === "string") {
|
|
311
|
+
parsed.text.push(e.delta);
|
|
312
|
+
}
|
|
313
|
+
break;
|
|
314
|
+
}
|
|
315
|
+
case "response.output_item.done": {
|
|
316
|
+
const e = event as Extract<CodexSseEvent, { type: "response.output_item.done" }>;
|
|
317
|
+
const item = e.item;
|
|
318
|
+
if (item?.type === "image_generation_call") {
|
|
319
|
+
if (typeof item.result !== "string" || item.result.length === 0) {
|
|
320
|
+
throw new Error("Codex image_generation_call did not contain image data.");
|
|
321
|
+
}
|
|
322
|
+
parsed.image = {
|
|
323
|
+
id: String(item.id || "image_generation"),
|
|
324
|
+
status: String(item.status || "completed"),
|
|
325
|
+
result: item.result,
|
|
326
|
+
revisedPrompt: typeof item.revised_prompt === "string" ? item.revised_prompt : undefined,
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
break;
|
|
330
|
+
}
|
|
331
|
+
case "response.completed": {
|
|
332
|
+
const e = event as Extract<CodexSseEvent, { type: "response.completed" }>;
|
|
333
|
+
if (typeof e.response?.id === "string") parsed.responseId = e.response.id;
|
|
334
|
+
if (e.response?.usage) parsed.usage = e.response.usage;
|
|
335
|
+
break;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// --- #1: requestImage with retry + backoff + jitter ---
|
|
341
|
+
|
|
342
|
+
async function requestImage(
|
|
343
|
+
params: ToolParams,
|
|
344
|
+
token: string,
|
|
345
|
+
accountId: string,
|
|
346
|
+
model: string,
|
|
347
|
+
outputFormat: OutputFormat,
|
|
348
|
+
sessionId: string,
|
|
349
|
+
signal?: AbortSignal,
|
|
350
|
+
): Promise<ParsedCodexResponse> {
|
|
351
|
+
const body = JSON.stringify(buildRequestBody(params, model, outputFormat, sessionId));
|
|
352
|
+
const headers: Record<string, string> = {
|
|
353
|
+
Authorization: `Bearer ${token}`,
|
|
354
|
+
"chatgpt-account-id": accountId,
|
|
355
|
+
originator: "pi",
|
|
356
|
+
"OpenAI-Beta": OPENAI_BETA_HEADER,
|
|
357
|
+
accept: "text/event-stream",
|
|
358
|
+
"content-type": "application/json",
|
|
359
|
+
};
|
|
360
|
+
|
|
361
|
+
for (let attempt = 1; attempt <= MAX_RETRIES + 1; attempt++) {
|
|
362
|
+
if (signal?.aborted) throw new Error("Image generation was aborted.");
|
|
363
|
+
|
|
364
|
+
const response = await fetch(CODEX_RESPONSES_URL, {
|
|
365
|
+
method: "POST",
|
|
366
|
+
headers,
|
|
367
|
+
body,
|
|
368
|
+
signal,
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
if (!response.ok) {
|
|
372
|
+
const errorText = await response.text();
|
|
373
|
+
if (attempt <= MAX_RETRIES && isRetryableStatus(response.status, errorText)) {
|
|
374
|
+
const delay = backoffMs(attempt);
|
|
375
|
+
await new Promise<void>((resolve) => setTimeout(resolve, delay));
|
|
376
|
+
continue;
|
|
377
|
+
}
|
|
378
|
+
throw new Error(`Codex image generation request failed (${response.status}): ${errorText}`);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
return parseCodexSse(response, signal);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
throw new Error("Codex image generation request failed after all retries.");
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// --- Extension entry point ---
|
|
388
|
+
|
|
389
|
+
export default function codexImageGen(pi: ExtensionAPI) {
|
|
390
|
+
reportInstallTelemetry();
|
|
391
|
+
|
|
392
|
+
pi.registerTool({
|
|
393
|
+
name: "codex_generate_image",
|
|
394
|
+
label: "Codex Image",
|
|
395
|
+
description:
|
|
396
|
+
"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.",
|
|
397
|
+
promptSnippet: "Generate bitmap images via the OpenAI Codex ChatGPT backend gpt-image-2 image_generation tool.",
|
|
398
|
+
promptGuidelines: [
|
|
399
|
+
"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.",
|
|
400
|
+
"Do not use codex_generate_image without a clear image-generation request, because it consumes the user's Codex image quota.",
|
|
401
|
+
],
|
|
402
|
+
parameters: TOOL_PARAMS,
|
|
403
|
+
executionMode: "parallel", // #4: safe to run concurrently — no shared state, saves serialized per-path
|
|
404
|
+
async execute(toolCallId, params: ToolParams, signal, onUpdate, ctx) {
|
|
405
|
+
const outputFormat = params.outputFormat || "png";
|
|
406
|
+
const config = loadConfig(ctx.cwd); // #5: load once, pass to resolveSaveConfig
|
|
407
|
+
const requestedModel = params.model || config.model || DEFAULT_MODEL;
|
|
408
|
+
const model = ctx.modelRegistry.find(PROVIDER, requestedModel)?.id || requestedModel; // #6: removed dead FALLBACK_MODEL
|
|
409
|
+
const token = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER);
|
|
410
|
+
if (!token) {
|
|
411
|
+
throw new Error(`Missing ${PROVIDER} credentials. Run /login and select ChatGPT Plus/Pro (Codex).`);
|
|
412
|
+
}
|
|
413
|
+
const accountId = extractChatGptAccountId(token);
|
|
414
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
415
|
+
|
|
416
|
+
onUpdate?.({
|
|
417
|
+
content: [{ type: "text", text: `Requesting gpt-image-2 generation through ${PROVIDER}/${model}...` }],
|
|
418
|
+
details: { provider: PROVIDER, model, outputFormat },
|
|
419
|
+
});
|
|
420
|
+
|
|
421
|
+
const parsed = await requestImage(params, token, accountId, model, outputFormat, sessionId, signal);
|
|
422
|
+
if (!parsed.image) {
|
|
423
|
+
const text = parsed.text.join("").trim();
|
|
424
|
+
throw new Error(text ? `Codex did not return an image. Response text: ${text}` : "Codex did not return an image.");
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
const saveConfig = resolveSaveConfig(params, ctx.cwd, sessionId, config);
|
|
428
|
+
let savedPath: string | undefined;
|
|
429
|
+
if (saveConfig.mode !== "none" && saveConfig.outputDir) {
|
|
430
|
+
savedPath = await saveImage(parsed.image.result, outputFormat, saveConfig.outputDir, parsed.image.id || toolCallId);
|
|
431
|
+
// #12: second onUpdate after save with path + byte count
|
|
432
|
+
onUpdate?.({
|
|
433
|
+
content: [{ type: "text", text: `Image saved to ${savedPath}.` }],
|
|
434
|
+
details: {
|
|
435
|
+
provider: PROVIDER,
|
|
436
|
+
model,
|
|
437
|
+
savedPath,
|
|
438
|
+
byteCount: Buffer.byteLength(parsed.image.result, "base64"),
|
|
439
|
+
},
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
const summary = [
|
|
444
|
+
`Generated image via ${PROVIDER}/${model} using backend gpt-image-2.`,
|
|
445
|
+
`Status: ${parsed.image.status}.`,
|
|
446
|
+
parsed.image.revisedPrompt ? `Revised prompt: ${parsed.image.revisedPrompt}` : undefined,
|
|
447
|
+
savedPath ? `Saved image to: ${savedPath}` : "Image was not saved to disk.",
|
|
448
|
+
]
|
|
449
|
+
.filter(Boolean)
|
|
450
|
+
.join(" ");
|
|
451
|
+
|
|
452
|
+
return {
|
|
453
|
+
content: [
|
|
454
|
+
{ type: "text", text: summary },
|
|
455
|
+
{ type: "image", data: parsed.image.result, mimeType: mimeForFormat(outputFormat) },
|
|
456
|
+
],
|
|
457
|
+
details: {
|
|
458
|
+
provider: PROVIDER,
|
|
459
|
+
model,
|
|
460
|
+
backendImageModel: "gpt-image-2",
|
|
461
|
+
outputFormat,
|
|
462
|
+
saveMode: saveConfig.mode,
|
|
463
|
+
savedPath,
|
|
464
|
+
responseId: parsed.responseId,
|
|
465
|
+
imageGenerationId: parsed.image.id,
|
|
466
|
+
revisedPrompt: parsed.image.revisedPrompt,
|
|
467
|
+
usage: parsed.usage,
|
|
468
|
+
},
|
|
469
|
+
};
|
|
470
|
+
},
|
|
471
|
+
});
|
|
472
|
+
}
|
package/index.ts
CHANGED
|
@@ -1,549 +1 @@
|
|
|
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 "@earendil-works/pi-ai";
|
|
13
|
-
import { type ExtensionAPI, getAgentDir, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
|
|
14
|
-
import { type Static, Type } from "typebox";
|
|
15
|
-
|
|
16
|
-
const PACKAGE_NAME = "pi-codex-image-gen";
|
|
17
|
-
const PROVIDER = "openai-codex";
|
|
18
|
-
const DEFAULT_MODEL = "gpt-5.5";
|
|
19
|
-
const CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
|
|
20
|
-
const JWT_CLAIM_PATH = "https://api.openai.com/auth";
|
|
21
|
-
const DEFAULT_SAVE_MODE = "global";
|
|
22
|
-
const OPENAI_BETA_HEADER = "responses=experimental";
|
|
23
|
-
const MAX_RETRIES = 3;
|
|
24
|
-
const BASE_DELAY_MS = 1000;
|
|
25
|
-
const INSTALL_TELEMETRY_URL = "https://mocito.dev/api/report-install";
|
|
26
|
-
const INSTALL_TELEMETRY_TIMEOUT_MS = 5000;
|
|
27
|
-
const CI_ENV_VARS = [
|
|
28
|
-
"CI",
|
|
29
|
-
"GITHUB_ACTIONS",
|
|
30
|
-
"GITLAB_CI",
|
|
31
|
-
"CIRCLECI",
|
|
32
|
-
"BUILDKITE",
|
|
33
|
-
"JENKINS_URL",
|
|
34
|
-
"TEAMCITY_VERSION",
|
|
35
|
-
"TF_BUILD",
|
|
36
|
-
"BITBUCKET_BUILD_NUMBER",
|
|
37
|
-
"APPVEYOR",
|
|
38
|
-
"TRAVIS",
|
|
39
|
-
"DRONE",
|
|
40
|
-
"CODEBUILD_BUILD_ID",
|
|
41
|
-
] as const;
|
|
42
|
-
|
|
43
|
-
const SAVE_MODES = ["none", "project", "global", "custom"] as const;
|
|
44
|
-
type SaveMode = (typeof SAVE_MODES)[number];
|
|
45
|
-
|
|
46
|
-
const OUTPUT_FORMATS = ["png", "jpeg", "webp"] as const;
|
|
47
|
-
type OutputFormat = (typeof OUTPUT_FORMATS)[number];
|
|
48
|
-
|
|
49
|
-
// --- #1: Retry helpers with exponential backoff + jitter ---
|
|
50
|
-
|
|
51
|
-
function isRetryableStatus(status: number, errorText: string): boolean {
|
|
52
|
-
if ([429, 500, 502, 503, 504].includes(status)) return true;
|
|
53
|
-
return /rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(errorText);
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
function backoffMs(attempt: number): number {
|
|
57
|
-
const jitter = 0.9 + Math.random() * 0.2; // matches codex-rs jitter range
|
|
58
|
-
return BASE_DELAY_MS * 2 ** (attempt - 1) * jitter;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
// --- Tool parameter schema ---
|
|
62
|
-
|
|
63
|
-
const TOOL_PARAMS = Type.Object({
|
|
64
|
-
prompt: Type.String({ description: "The image prompt. Be specific about subject, composition, style, text, and constraints." }),
|
|
65
|
-
model: Type.Optional(
|
|
66
|
-
Type.String({ description: `Codex model that should invoke image generation. Defaults to ${DEFAULT_MODEL}.` }),
|
|
67
|
-
),
|
|
68
|
-
outputFormat: Type.Optional(StringEnum(OUTPUT_FORMATS)),
|
|
69
|
-
save: Type.Optional(StringEnum(SAVE_MODES)),
|
|
70
|
-
saveDir: Type.Optional(
|
|
71
|
-
Type.String({
|
|
72
|
-
description: "Directory to save the image when save=custom. Relative paths resolve under the current workspace.",
|
|
73
|
-
}),
|
|
74
|
-
),
|
|
75
|
-
});
|
|
76
|
-
|
|
77
|
-
type ToolParams = Static<typeof TOOL_PARAMS>;
|
|
78
|
-
|
|
79
|
-
// --- Config types ---
|
|
80
|
-
|
|
81
|
-
interface ExtensionConfig {
|
|
82
|
-
save?: SaveMode;
|
|
83
|
-
saveDir?: string;
|
|
84
|
-
model?: string;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
interface SaveConfig {
|
|
88
|
-
mode: SaveMode;
|
|
89
|
-
outputDir?: string;
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
interface GeneratedImage {
|
|
93
|
-
id: string;
|
|
94
|
-
status: string;
|
|
95
|
-
result: string;
|
|
96
|
-
revisedPrompt?: string;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
interface ParsedCodexResponse {
|
|
100
|
-
image?: GeneratedImage;
|
|
101
|
-
text: string[];
|
|
102
|
-
responseId?: string;
|
|
103
|
-
usage?: unknown;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
interface InstallTelemetryState {
|
|
107
|
-
lastReportedVersion?: string;
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
// --- #11: Typed SSE event discriminated union ---
|
|
111
|
-
|
|
112
|
-
type CodexSseEvent =
|
|
113
|
-
| { type: "error"; message?: string; code?: string }
|
|
114
|
-
| { type: "response.failed"; response?: { error?: { message?: string } } }
|
|
115
|
-
| { type: "response.created"; response?: { id?: string } }
|
|
116
|
-
| { type: "response.output_text.delta"; delta?: string }
|
|
117
|
-
| {
|
|
118
|
-
type: "response.output_item.done";
|
|
119
|
-
item?: {
|
|
120
|
-
type?: string;
|
|
121
|
-
id?: string | number;
|
|
122
|
-
status?: string;
|
|
123
|
-
result?: string;
|
|
124
|
-
revised_prompt?: string;
|
|
125
|
-
};
|
|
126
|
-
}
|
|
127
|
-
| { type: "response.completed"; response?: { id?: string; usage?: unknown } };
|
|
128
|
-
|
|
129
|
-
// --- JWT helpers ---
|
|
130
|
-
|
|
131
|
-
function decodeJwtPayload(token: string): Record<string, unknown> {
|
|
132
|
-
const parts = token.split(".");
|
|
133
|
-
if (parts.length !== 3 || !parts[1]) {
|
|
134
|
-
throw new Error("OpenAI Codex auth token is not a JWT. Run /login for openai-codex again.");
|
|
135
|
-
}
|
|
136
|
-
try {
|
|
137
|
-
return JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8")) as Record<string, unknown>;
|
|
138
|
-
} catch (error) {
|
|
139
|
-
throw new Error(`Failed to decode OpenAI Codex auth token: ${error instanceof Error ? error.message : String(error)}`);
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
function extractChatGptAccountId(token: string): string {
|
|
144
|
-
const payload = decodeJwtPayload(token);
|
|
145
|
-
const authClaims = payload[JWT_CLAIM_PATH];
|
|
146
|
-
if (!authClaims || typeof authClaims !== "object") {
|
|
147
|
-
throw new Error("OpenAI Codex auth token does not contain ChatGPT auth claims. Run /login for openai-codex again.");
|
|
148
|
-
}
|
|
149
|
-
const accountId = (authClaims as Record<string, unknown>).chatgpt_account_id;
|
|
150
|
-
if (typeof accountId !== "string" || accountId.length === 0) {
|
|
151
|
-
throw new Error("OpenAI Codex auth token does not contain chatgpt_account_id. Run /login for openai-codex again.");
|
|
152
|
-
}
|
|
153
|
-
return accountId;
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
// --- #10: try/catch readConfigFile replaces racy existsSync + readFileSync ---
|
|
157
|
-
|
|
158
|
-
function readConfigFile(path: string): ExtensionConfig {
|
|
159
|
-
try {
|
|
160
|
-
return JSON.parse(readFileSync(path, "utf8")) ?? {};
|
|
161
|
-
} catch {
|
|
162
|
-
return {};
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
function loadConfig(cwd: string): ExtensionConfig {
|
|
167
|
-
const globalConfig = readConfigFile(join(getAgentDir(), "extensions", "codex-image-gen.json"));
|
|
168
|
-
const projectConfig = readConfigFile(join(cwd, ".pi", "extensions", "codex-image-gen.json"));
|
|
169
|
-
return { ...globalConfig, ...projectConfig };
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
function isTruthyEnvFlag(value: string | undefined): boolean {
|
|
173
|
-
if (!value) return false;
|
|
174
|
-
return value === "1" || value.toLowerCase() === "true" || value.toLowerCase() === "yes";
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
function isCiEnvironment(): boolean {
|
|
178
|
-
return CI_ENV_VARS.some((name) => {
|
|
179
|
-
const value = process.env[name];
|
|
180
|
-
return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
181
|
-
});
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
function isInstallTelemetryEnabled(): boolean {
|
|
185
|
-
if (isCiEnvironment()) return false;
|
|
186
|
-
if (isTruthyEnvFlag(process.env.PI_OFFLINE)) return false;
|
|
187
|
-
if (process.env.PI_TELEMETRY !== undefined) return isTruthyEnvFlag(process.env.PI_TELEMETRY);
|
|
188
|
-
const settings = readConfigFile(join(getAgentDir(), "settings.json")) as { enableInstallTelemetry?: unknown };
|
|
189
|
-
return settings.enableInstallTelemetry !== false;
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
function getPackageVersion(): string {
|
|
193
|
-
try {
|
|
194
|
-
const packageJson = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")) as { version?: unknown };
|
|
195
|
-
return typeof packageJson.version === "string" && packageJson.version.length > 0 ? packageJson.version : "0.0.0";
|
|
196
|
-
} catch {
|
|
197
|
-
return "0.0.0";
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
function getInstallTelemetryUserAgent(version: string): string {
|
|
202
|
-
const runtimeVersions = process.versions as NodeJS.ProcessVersions & { bun?: string };
|
|
203
|
-
const runtime = runtimeVersions.bun ? `bun/${runtimeVersions.bun}` : `node/${process.version}`;
|
|
204
|
-
return `${PACKAGE_NAME}/${version} (${process.platform}; ${runtime}; ${process.arch})`;
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
async function reportInstallTelemetry(): Promise<void> {
|
|
208
|
-
try {
|
|
209
|
-
if (!isInstallTelemetryEnabled()) return;
|
|
210
|
-
|
|
211
|
-
const version = getPackageVersion();
|
|
212
|
-
const statePath = join(getAgentDir(), "extensions", "codex-image-gen-install.json");
|
|
213
|
-
const state = readConfigFile(statePath) as InstallTelemetryState;
|
|
214
|
-
if (state.lastReportedVersion === version) return;
|
|
215
|
-
|
|
216
|
-
await mkdir(join(getAgentDir(), "extensions"), { recursive: true });
|
|
217
|
-
await writeFile(statePath, `${JSON.stringify({ lastReportedVersion: version }, null, 2)}\n`);
|
|
218
|
-
|
|
219
|
-
const params = new URLSearchParams({ tool: PACKAGE_NAME, version });
|
|
220
|
-
await fetch(`${INSTALL_TELEMETRY_URL}?${params.toString()}`, {
|
|
221
|
-
headers: { "User-Agent": getInstallTelemetryUserAgent(version) },
|
|
222
|
-
signal: AbortSignal.timeout(INSTALL_TELEMETRY_TIMEOUT_MS),
|
|
223
|
-
});
|
|
224
|
-
} catch {
|
|
225
|
-
// Best-effort telemetry: ignore settings, filesystem, and network failures.
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
// --- Path helpers ---
|
|
230
|
-
|
|
231
|
-
function resolveUnderCwd(cwd: string, path: string): string {
|
|
232
|
-
return isAbsolute(path) ? path : resolve(cwd, path);
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
function sanitizePathPart(value: string, fallback: string): string {
|
|
236
|
-
const sanitized = value
|
|
237
|
-
.split("")
|
|
238
|
-
.map((ch) => (/[a-zA-Z0-9_-]/.test(ch) ? ch : "_"))
|
|
239
|
-
.join("")
|
|
240
|
-
.replace(/_+$/g, "");
|
|
241
|
-
return sanitized || fallback;
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
// --- #5: resolveSaveConfig accepts pre-loaded config (no double loadConfig) ---
|
|
245
|
-
|
|
246
|
-
function resolveSaveConfig(params: ToolParams, cwd: string, sessionId: string, config: ExtensionConfig): SaveConfig {
|
|
247
|
-
const envMode = process.env.PI_CODEX_IMAGE_SAVE_MODE?.toLowerCase();
|
|
248
|
-
const mode = (params.save || envMode || config.save || DEFAULT_SAVE_MODE) as SaveMode;
|
|
249
|
-
const safeSessionId = sanitizePathPart(sessionId, "session");
|
|
250
|
-
if (!SAVE_MODES.includes(mode)) {
|
|
251
|
-
throw new Error(`Invalid save mode: ${mode}. Expected one of ${SAVE_MODES.join(", ")}.`);
|
|
252
|
-
}
|
|
253
|
-
if (mode === "project") {
|
|
254
|
-
return { mode, outputDir: join(cwd, ".pi", "generated-images", safeSessionId) };
|
|
255
|
-
}
|
|
256
|
-
if (mode === "global") {
|
|
257
|
-
return { mode, outputDir: join(getAgentDir(), "generated-images", safeSessionId) };
|
|
258
|
-
}
|
|
259
|
-
if (mode === "custom") {
|
|
260
|
-
const configuredDir = params.saveDir || process.env.PI_CODEX_IMAGE_SAVE_DIR || config.saveDir;
|
|
261
|
-
if (!configuredDir || !configuredDir.trim()) {
|
|
262
|
-
throw new Error("save=custom requires saveDir or PI_CODEX_IMAGE_SAVE_DIR.");
|
|
263
|
-
}
|
|
264
|
-
return { mode, outputDir: join(resolveUnderCwd(cwd, configuredDir), safeSessionId) };
|
|
265
|
-
}
|
|
266
|
-
return { mode };
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
// --- Image save helpers ---
|
|
270
|
-
|
|
271
|
-
function extensionForFormat(outputFormat: OutputFormat): string {
|
|
272
|
-
return outputFormat === "jpeg" ? "jpg" : outputFormat;
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
function mimeForFormat(outputFormat: OutputFormat): string {
|
|
276
|
-
return outputFormat === "jpeg" ? "image/jpeg" : `image/${outputFormat}`;
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
async function saveImage(base64Data: string, outputFormat: OutputFormat, outputDir: string, imageCallId: string): Promise<string> {
|
|
280
|
-
const filename = `${sanitizePathPart(imageCallId, "image_generation")}.${extensionForFormat(outputFormat)}`;
|
|
281
|
-
const filePath = join(outputDir, filename);
|
|
282
|
-
await withFileMutationQueue(filePath, async () => {
|
|
283
|
-
await mkdir(outputDir, { recursive: true });
|
|
284
|
-
await writeFile(filePath, Buffer.from(base64Data, "base64"));
|
|
285
|
-
});
|
|
286
|
-
return filePath;
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
// --- Request building ---
|
|
290
|
-
// #2: prompt_cache_key set to sessionId
|
|
291
|
-
// #7: parallel_tool_calls: false
|
|
292
|
-
// #14: include removed (not needed without reasoning)
|
|
293
|
-
|
|
294
|
-
function buildRequestBody(params: ToolParams, model: string, outputFormat: OutputFormat, sessionId: string) {
|
|
295
|
-
return {
|
|
296
|
-
model,
|
|
297
|
-
store: false,
|
|
298
|
-
stream: true,
|
|
299
|
-
prompt_cache_key: sessionId,
|
|
300
|
-
instructions:
|
|
301
|
-
"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.",
|
|
302
|
-
input: [
|
|
303
|
-
{
|
|
304
|
-
role: "user",
|
|
305
|
-
content: [{ type: "input_text", text: params.prompt }],
|
|
306
|
-
},
|
|
307
|
-
],
|
|
308
|
-
tools: [{ type: "image_generation", output_format: outputFormat }],
|
|
309
|
-
tool_choice: "auto",
|
|
310
|
-
parallel_tool_calls: false,
|
|
311
|
-
text: { verbosity: "low" },
|
|
312
|
-
};
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
// --- SSE parsing ---
|
|
316
|
-
|
|
317
|
-
function parseSseDataLines(chunk: string): string | undefined {
|
|
318
|
-
const data = chunk
|
|
319
|
-
.split("\n")
|
|
320
|
-
.filter((line) => line.startsWith("data:"))
|
|
321
|
-
.map((line) => line.slice(5).trim())
|
|
322
|
-
.join("\n")
|
|
323
|
-
.trim();
|
|
324
|
-
return data && data !== "[DONE]" ? data : undefined;
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
async function parseCodexSse(response: Response, signal?: AbortSignal): Promise<ParsedCodexResponse> {
|
|
328
|
-
if (!response.body) throw new Error("Codex response did not include a stream body.");
|
|
329
|
-
const reader = response.body.getReader();
|
|
330
|
-
const decoder = new TextDecoder();
|
|
331
|
-
let buffer = "";
|
|
332
|
-
const parsed: ParsedCodexResponse = { text: [] };
|
|
333
|
-
|
|
334
|
-
try {
|
|
335
|
-
while (true) {
|
|
336
|
-
if (signal?.aborted) throw new Error("Image generation was aborted.");
|
|
337
|
-
const { done, value } = await reader.read();
|
|
338
|
-
if (done) break;
|
|
339
|
-
buffer += decoder.decode(value, { stream: true });
|
|
340
|
-
|
|
341
|
-
let separator = buffer.indexOf("\n\n");
|
|
342
|
-
while (separator !== -1) {
|
|
343
|
-
const chunk = buffer.slice(0, separator);
|
|
344
|
-
buffer = buffer.slice(separator + 2);
|
|
345
|
-
const data = parseSseDataLines(chunk);
|
|
346
|
-
if (data) handleCodexEvent(JSON.parse(data) as CodexSseEvent, parsed);
|
|
347
|
-
separator = buffer.indexOf("\n\n");
|
|
348
|
-
}
|
|
349
|
-
}
|
|
350
|
-
const remaining = parseSseDataLines(buffer);
|
|
351
|
-
if (remaining) handleCodexEvent(JSON.parse(remaining) as CodexSseEvent, parsed);
|
|
352
|
-
} finally {
|
|
353
|
-
try {
|
|
354
|
-
await reader.cancel();
|
|
355
|
-
} catch {
|
|
356
|
-
// ignored: stream may already be closed
|
|
357
|
-
}
|
|
358
|
-
reader.releaseLock();
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
return parsed;
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
// --- #11: Typed event handler via discriminated union ---
|
|
365
|
-
|
|
366
|
-
function handleCodexEvent(event: CodexSseEvent, parsed: ParsedCodexResponse): void {
|
|
367
|
-
if (!event || typeof event !== "object") return;
|
|
368
|
-
|
|
369
|
-
switch (event.type) {
|
|
370
|
-
case "error": {
|
|
371
|
-
const e = event as Extract<CodexSseEvent, { type: "error" }>;
|
|
372
|
-
throw new Error(`Codex error: ${e.message || e.code || JSON.stringify(event)}`);
|
|
373
|
-
}
|
|
374
|
-
case "response.failed": {
|
|
375
|
-
const e = event as Extract<CodexSseEvent, { type: "response.failed" }>;
|
|
376
|
-
throw new Error(e.response?.error?.message || "Codex response failed.");
|
|
377
|
-
}
|
|
378
|
-
case "response.created": {
|
|
379
|
-
const e = event as Extract<CodexSseEvent, { type: "response.created" }>;
|
|
380
|
-
if (typeof e.response?.id === "string") {
|
|
381
|
-
parsed.responseId = e.response.id;
|
|
382
|
-
}
|
|
383
|
-
break;
|
|
384
|
-
}
|
|
385
|
-
case "response.output_text.delta": {
|
|
386
|
-
const e = event as Extract<CodexSseEvent, { type: "response.output_text.delta" }>;
|
|
387
|
-
if (typeof e.delta === "string") {
|
|
388
|
-
parsed.text.push(e.delta);
|
|
389
|
-
}
|
|
390
|
-
break;
|
|
391
|
-
}
|
|
392
|
-
case "response.output_item.done": {
|
|
393
|
-
const e = event as Extract<CodexSseEvent, { type: "response.output_item.done" }>;
|
|
394
|
-
const item = e.item;
|
|
395
|
-
if (item?.type === "image_generation_call") {
|
|
396
|
-
if (typeof item.result !== "string" || item.result.length === 0) {
|
|
397
|
-
throw new Error("Codex image_generation_call did not contain image data.");
|
|
398
|
-
}
|
|
399
|
-
parsed.image = {
|
|
400
|
-
id: String(item.id || "image_generation"),
|
|
401
|
-
status: String(item.status || "completed"),
|
|
402
|
-
result: item.result,
|
|
403
|
-
revisedPrompt: typeof item.revised_prompt === "string" ? item.revised_prompt : undefined,
|
|
404
|
-
};
|
|
405
|
-
}
|
|
406
|
-
break;
|
|
407
|
-
}
|
|
408
|
-
case "response.completed": {
|
|
409
|
-
const e = event as Extract<CodexSseEvent, { type: "response.completed" }>;
|
|
410
|
-
if (typeof e.response?.id === "string") parsed.responseId = e.response.id;
|
|
411
|
-
if (e.response?.usage) parsed.usage = e.response.usage;
|
|
412
|
-
break;
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
// --- #1: requestImage with retry + backoff + jitter ---
|
|
418
|
-
|
|
419
|
-
async function requestImage(
|
|
420
|
-
params: ToolParams,
|
|
421
|
-
token: string,
|
|
422
|
-
accountId: string,
|
|
423
|
-
model: string,
|
|
424
|
-
outputFormat: OutputFormat,
|
|
425
|
-
sessionId: string,
|
|
426
|
-
signal?: AbortSignal,
|
|
427
|
-
): Promise<ParsedCodexResponse> {
|
|
428
|
-
const body = JSON.stringify(buildRequestBody(params, model, outputFormat, sessionId));
|
|
429
|
-
const headers: Record<string, string> = {
|
|
430
|
-
Authorization: `Bearer ${token}`,
|
|
431
|
-
"chatgpt-account-id": accountId,
|
|
432
|
-
originator: "pi",
|
|
433
|
-
"OpenAI-Beta": OPENAI_BETA_HEADER,
|
|
434
|
-
accept: "text/event-stream",
|
|
435
|
-
"content-type": "application/json",
|
|
436
|
-
};
|
|
437
|
-
|
|
438
|
-
for (let attempt = 1; attempt <= MAX_RETRIES + 1; attempt++) {
|
|
439
|
-
if (signal?.aborted) throw new Error("Image generation was aborted.");
|
|
440
|
-
|
|
441
|
-
const response = await fetch(CODEX_RESPONSES_URL, {
|
|
442
|
-
method: "POST",
|
|
443
|
-
headers,
|
|
444
|
-
body,
|
|
445
|
-
signal,
|
|
446
|
-
});
|
|
447
|
-
|
|
448
|
-
if (!response.ok) {
|
|
449
|
-
const errorText = await response.text();
|
|
450
|
-
if (attempt <= MAX_RETRIES && isRetryableStatus(response.status, errorText)) {
|
|
451
|
-
const delay = backoffMs(attempt);
|
|
452
|
-
await new Promise<void>((resolve) => setTimeout(resolve, delay));
|
|
453
|
-
continue;
|
|
454
|
-
}
|
|
455
|
-
throw new Error(`Codex image generation request failed (${response.status}): ${errorText}`);
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
return parseCodexSse(response, signal);
|
|
459
|
-
}
|
|
460
|
-
|
|
461
|
-
throw new Error("Codex image generation request failed after all retries.");
|
|
462
|
-
}
|
|
463
|
-
|
|
464
|
-
// --- Extension entry point ---
|
|
465
|
-
|
|
466
|
-
export default function codexImageGen(pi: ExtensionAPI) {
|
|
467
|
-
void reportInstallTelemetry();
|
|
468
|
-
|
|
469
|
-
pi.registerTool({
|
|
470
|
-
name: "codex_generate_image",
|
|
471
|
-
label: "Codex Image",
|
|
472
|
-
description:
|
|
473
|
-
"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.",
|
|
474
|
-
promptSnippet: "Generate bitmap images via the OpenAI Codex ChatGPT backend gpt-image-2 image_generation tool.",
|
|
475
|
-
promptGuidelines: [
|
|
476
|
-
"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.",
|
|
477
|
-
"Do not use codex_generate_image without a clear image-generation request, because it consumes the user's Codex image quota.",
|
|
478
|
-
],
|
|
479
|
-
parameters: TOOL_PARAMS,
|
|
480
|
-
executionMode: "parallel", // #4: safe to run concurrently — no shared state, saves serialized per-path
|
|
481
|
-
async execute(toolCallId, params: ToolParams, signal, onUpdate, ctx) {
|
|
482
|
-
const outputFormat = params.outputFormat || "png";
|
|
483
|
-
const config = loadConfig(ctx.cwd); // #5: load once, pass to resolveSaveConfig
|
|
484
|
-
const requestedModel = params.model || config.model || DEFAULT_MODEL;
|
|
485
|
-
const model = ctx.modelRegistry.find(PROVIDER, requestedModel)?.id || requestedModel; // #6: removed dead FALLBACK_MODEL
|
|
486
|
-
const token = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER);
|
|
487
|
-
if (!token) {
|
|
488
|
-
throw new Error(`Missing ${PROVIDER} credentials. Run /login and select ChatGPT Plus/Pro (Codex).`);
|
|
489
|
-
}
|
|
490
|
-
const accountId = extractChatGptAccountId(token);
|
|
491
|
-
const sessionId = ctx.sessionManager.getSessionId();
|
|
492
|
-
|
|
493
|
-
onUpdate?.({
|
|
494
|
-
content: [{ type: "text", text: `Requesting gpt-image-2 generation through ${PROVIDER}/${model}...` }],
|
|
495
|
-
details: { provider: PROVIDER, model, outputFormat },
|
|
496
|
-
});
|
|
497
|
-
|
|
498
|
-
const parsed = await requestImage(params, token, accountId, model, outputFormat, sessionId, signal);
|
|
499
|
-
if (!parsed.image) {
|
|
500
|
-
const text = parsed.text.join("").trim();
|
|
501
|
-
throw new Error(text ? `Codex did not return an image. Response text: ${text}` : "Codex did not return an image.");
|
|
502
|
-
}
|
|
503
|
-
|
|
504
|
-
const saveConfig = resolveSaveConfig(params, ctx.cwd, sessionId, config);
|
|
505
|
-
let savedPath: string | undefined;
|
|
506
|
-
if (saveConfig.mode !== "none" && saveConfig.outputDir) {
|
|
507
|
-
savedPath = await saveImage(parsed.image.result, outputFormat, saveConfig.outputDir, parsed.image.id || toolCallId);
|
|
508
|
-
// #12: second onUpdate after save with path + byte count
|
|
509
|
-
onUpdate?.({
|
|
510
|
-
content: [{ type: "text", text: `Image saved to ${savedPath}.` }],
|
|
511
|
-
details: {
|
|
512
|
-
provider: PROVIDER,
|
|
513
|
-
model,
|
|
514
|
-
savedPath,
|
|
515
|
-
byteCount: Buffer.byteLength(parsed.image.result, "base64"),
|
|
516
|
-
},
|
|
517
|
-
});
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
const summary = [
|
|
521
|
-
`Generated image via ${PROVIDER}/${model} using backend gpt-image-2.`,
|
|
522
|
-
`Status: ${parsed.image.status}.`,
|
|
523
|
-
parsed.image.revisedPrompt ? `Revised prompt: ${parsed.image.revisedPrompt}` : undefined,
|
|
524
|
-
savedPath ? `Saved image to: ${savedPath}` : "Image was not saved to disk.",
|
|
525
|
-
]
|
|
526
|
-
.filter(Boolean)
|
|
527
|
-
.join(" ");
|
|
528
|
-
|
|
529
|
-
return {
|
|
530
|
-
content: [
|
|
531
|
-
{ type: "text", text: summary },
|
|
532
|
-
{ type: "image", data: parsed.image.result, mimeType: mimeForFormat(outputFormat) },
|
|
533
|
-
],
|
|
534
|
-
details: {
|
|
535
|
-
provider: PROVIDER,
|
|
536
|
-
model,
|
|
537
|
-
backendImageModel: "gpt-image-2",
|
|
538
|
-
outputFormat,
|
|
539
|
-
saveMode: saveConfig.mode,
|
|
540
|
-
savedPath,
|
|
541
|
-
responseId: parsed.responseId,
|
|
542
|
-
imageGenerationId: parsed.image.id,
|
|
543
|
-
revisedPrompt: parsed.image.revisedPrompt,
|
|
544
|
-
usage: parsed.usage,
|
|
545
|
-
},
|
|
546
|
-
};
|
|
547
|
-
},
|
|
548
|
-
});
|
|
549
|
-
}
|
|
1
|
+
export { default } from "./extensions/index.js";
|
package/package.json
CHANGED
|
@@ -1,18 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-codex-image-gen",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.10",
|
|
4
4
|
"description": "Image generation for Pi using the ChatGPT Images 2.0 model.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
7
|
-
"author": "
|
|
7
|
+
"author": "Jose Mocito",
|
|
8
8
|
"repository": {
|
|
9
9
|
"type": "git",
|
|
10
|
-
"url": "git+https://github.com/jvm/pi-
|
|
10
|
+
"url": "git+https://github.com/jvm/pi-mono.git",
|
|
11
|
+
"directory": "packages/pi-codex-image-gen"
|
|
11
12
|
},
|
|
12
13
|
"bugs": {
|
|
13
|
-
"url": "https://github.com/jvm/pi-
|
|
14
|
+
"url": "https://github.com/jvm/pi-mono/issues"
|
|
14
15
|
},
|
|
15
|
-
"homepage": "https://github.com/jvm/pi-codex-image-gen#readme",
|
|
16
|
+
"homepage": "https://github.com/jvm/pi-mono/tree/main/packages/pi-codex-image-gen#readme",
|
|
16
17
|
"keywords": [
|
|
17
18
|
"pi-package",
|
|
18
19
|
"pi-extension",
|
|
@@ -21,10 +22,16 @@
|
|
|
21
22
|
"image-generation",
|
|
22
23
|
"gpt-image-2"
|
|
23
24
|
],
|
|
25
|
+
"exports": {
|
|
26
|
+
".": "./src/index.ts"
|
|
27
|
+
},
|
|
24
28
|
"files": [
|
|
25
29
|
"index.ts",
|
|
30
|
+
"extensions",
|
|
31
|
+
"src",
|
|
26
32
|
"skills",
|
|
27
33
|
"README.md",
|
|
34
|
+
"NOTICE",
|
|
28
35
|
"LICENSE",
|
|
29
36
|
"CHANGELOG.md",
|
|
30
37
|
"SECURITY.md",
|
|
@@ -33,11 +40,16 @@
|
|
|
33
40
|
],
|
|
34
41
|
"scripts": {
|
|
35
42
|
"check": "tsc --noEmit",
|
|
43
|
+
"typecheck": "tsc --noEmit",
|
|
36
44
|
"pack:dry-run": "npm pack --dry-run"
|
|
37
45
|
},
|
|
38
46
|
"pi": {
|
|
39
|
-
"extensions": [
|
|
40
|
-
|
|
47
|
+
"extensions": [
|
|
48
|
+
"./index.ts"
|
|
49
|
+
],
|
|
50
|
+
"skills": [
|
|
51
|
+
"./skills"
|
|
52
|
+
]
|
|
41
53
|
},
|
|
42
54
|
"peerDependencies": {
|
|
43
55
|
"@earendil-works/pi-ai": "*",
|
|
@@ -45,10 +57,10 @@
|
|
|
45
57
|
"typebox": "*"
|
|
46
58
|
},
|
|
47
59
|
"devDependencies": {
|
|
48
|
-
"@earendil-works/pi-ai": "^0.
|
|
49
|
-
"@earendil-works/pi-coding-agent": "^0.
|
|
60
|
+
"@earendil-works/pi-ai": "^0.75.4",
|
|
61
|
+
"@earendil-works/pi-coding-agent": "^0.75.4",
|
|
50
62
|
"typebox": "^1.1.33",
|
|
51
|
-
"@types/node": "^25.6.
|
|
63
|
+
"@types/node": "^25.6.2",
|
|
52
64
|
"typescript": "^6.0.3"
|
|
53
65
|
},
|
|
54
66
|
"publishConfig": {
|
package/src/index.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { reportInstallTelemetry } from "./install-telemetry.js";
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
|
|
7
|
+
const PACKAGE_NAME = "pi-codex-image-gen";
|
|
8
|
+
const INSTALL_TELEMETRY_URL = "https://mocito.dev/api/report-install";
|
|
9
|
+
const INSTALL_TELEMETRY_TIMEOUT_MS = 5000;
|
|
10
|
+
const CI_ENVIRONMENT_VARIABLES = [
|
|
11
|
+
"APPVEYOR",
|
|
12
|
+
"BITBUCKET_BUILD_NUMBER",
|
|
13
|
+
"BUILDKITE",
|
|
14
|
+
"CIRCLECI",
|
|
15
|
+
"CODESPACES",
|
|
16
|
+
"DRONE",
|
|
17
|
+
"GITHUB_ACTIONS",
|
|
18
|
+
"GITLAB_CI",
|
|
19
|
+
"JENKINS_URL",
|
|
20
|
+
"NETLIFY",
|
|
21
|
+
"TEAMCITY_VERSION",
|
|
22
|
+
"TF_BUILD",
|
|
23
|
+
"TRAVIS",
|
|
24
|
+
"VERCEL",
|
|
25
|
+
];
|
|
26
|
+
|
|
27
|
+
interface InstallTelemetryState {
|
|
28
|
+
lastReportedVersion?: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
interface PiSettingsDocument {
|
|
32
|
+
enableInstallTelemetry?: unknown;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function readJsonFile(path: string): unknown {
|
|
36
|
+
try {
|
|
37
|
+
return JSON.parse(readFileSync(path, "utf8")) as unknown;
|
|
38
|
+
} catch {
|
|
39
|
+
return {};
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function isTruthyEnvFlag(value: string | undefined): boolean {
|
|
44
|
+
if (!value) return false;
|
|
45
|
+
return value === "1" || value.toLowerCase() === "true" || value.toLowerCase() === "yes";
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function isPresentEnvFlag(value: string | undefined): boolean {
|
|
49
|
+
if (!value) return false;
|
|
50
|
+
const normalized = value.toLowerCase();
|
|
51
|
+
return normalized !== "0" && normalized !== "false" && normalized !== "no";
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function isCiEnvironment(): boolean {
|
|
55
|
+
if (isTruthyEnvFlag(process.env.CI)) return true;
|
|
56
|
+
return CI_ENVIRONMENT_VARIABLES.some((name) => isPresentEnvFlag(process.env[name]));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function isInstallTelemetryEnabled(): boolean {
|
|
60
|
+
if (isCiEnvironment()) return false;
|
|
61
|
+
if (isTruthyEnvFlag(process.env.PI_OFFLINE)) return false;
|
|
62
|
+
if (process.env.PI_TELEMETRY !== undefined) return isTruthyEnvFlag(process.env.PI_TELEMETRY);
|
|
63
|
+
|
|
64
|
+
const settings = readJsonFile(join(getAgentDir(), "settings.json")) as PiSettingsDocument;
|
|
65
|
+
return settings.enableInstallTelemetry !== false;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function getPackageVersion(): string {
|
|
69
|
+
const packageJson = readJsonFile(fileURLToPath(new URL("../package.json", import.meta.url))) as { version?: unknown };
|
|
70
|
+
return typeof packageJson.version === "string" && packageJson.version.length > 0 ? packageJson.version : "0.0.0";
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function getInstallTelemetryUserAgent(version: string): string {
|
|
74
|
+
const runtimeVersions = process.versions as NodeJS.ProcessVersions & { bun?: string };
|
|
75
|
+
const runtime = runtimeVersions.bun ? `bun/${runtimeVersions.bun}` : `node/${process.version}`;
|
|
76
|
+
return `${PACKAGE_NAME}/${version} (${process.platform}; ${runtime}; ${process.arch})`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function reportInstallTelemetryAsync(): Promise<void> {
|
|
80
|
+
try {
|
|
81
|
+
if (!isInstallTelemetryEnabled()) return;
|
|
82
|
+
|
|
83
|
+
const version = getPackageVersion();
|
|
84
|
+
const extensionsDir = join(getAgentDir(), "extensions");
|
|
85
|
+
const statePath = join(extensionsDir, "pi-codex-image-gen-install.json");
|
|
86
|
+
const state = readJsonFile(statePath) as InstallTelemetryState;
|
|
87
|
+
if (state.lastReportedVersion === version) return;
|
|
88
|
+
|
|
89
|
+
await mkdir(extensionsDir, { recursive: true });
|
|
90
|
+
await writeFile(statePath, `${JSON.stringify({ lastReportedVersion: version }, null, 2)}\n`, "utf8");
|
|
91
|
+
|
|
92
|
+
const params = new URLSearchParams({ tool: PACKAGE_NAME, version });
|
|
93
|
+
await fetch(`${INSTALL_TELEMETRY_URL}?${params.toString()}`, {
|
|
94
|
+
headers: { "User-Agent": getInstallTelemetryUserAgent(version) },
|
|
95
|
+
signal: AbortSignal.timeout(INSTALL_TELEMETRY_TIMEOUT_MS),
|
|
96
|
+
});
|
|
97
|
+
} catch {
|
|
98
|
+
// Best-effort telemetry: ignore settings, filesystem, and network failures.
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function reportInstallTelemetry(): void {
|
|
103
|
+
void reportInstallTelemetryAsync();
|
|
104
|
+
}
|