co-maintainer 0.6.1 → 0.6.3

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.
@@ -0,0 +1,552 @@
1
+ /** Sign in with ChatGPT (experimental).
2
+ *
3
+ * Runs the Responses API on a user's ChatGPT plan through OpenAI's
4
+ * open-source Sign in with ChatGPT flow, instead of an API key. The OAuth
5
+ * dance registers a client on first use, keeps the tokens in
6
+ * `~/.config/co-maintainer/oauth/sign-in-with-chatgpt.json` (0600), and
7
+ * refreshes them. The Responses translation itself lives in `openai.ts` and
8
+ * is shared; this file only adds the auth and the plan-usage request shape.
9
+ *
10
+ * Route quirks this file exists to respect (confirmed against the live
11
+ * route): `store:false` and `stream:true` are required, `max_output_tokens`
12
+ * is rejected, system messages are rejected in favor of `instructions`, and
13
+ * there is no `previous_response_id`, so the full history is sent each time.
14
+ */
15
+ import { createHash, createPublicKey, randomBytes, randomUUID, verify, } from "node:crypto";
16
+ import { spawn } from "node:child_process";
17
+ import { createServer } from "node:http";
18
+ import { CliError, EXIT_RUNTIME, EXIT_USAGE, networkFailure, } from "../../cli/error.js";
19
+ import { getConfigDir } from "../../config.js";
20
+ import { chmod, getEnv, isNotFound, mkdir, readTextFileSync, remove, writeTextFile, } from "../../util/runtime.js";
21
+ import { parseResponsesBody, readResponsesStream, responsesBody, } from "../openai.js";
22
+ import { SIWC_ALIAS, SIWC_LABEL, SIWC_PROVIDER } from "./ids.js";
23
+ export { SIWC_ALIAS, SIWC_LABEL, SIWC_PROVIDER };
24
+ const CALLBACK_PATH = "/auth/callback";
25
+ const APP_NAME = "co-maintainer";
26
+ const DEFAULT_CLIENT_ID = "dynamic_agent_client";
27
+ const SCOPE = "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct";
28
+ const HELP_URL = "https://developers.openai.com/siwc/token-sharing-open-source";
29
+ /** How long the browser sign-in waits for the callback. `CM_SIWC_LOGIN_TIMEOUT_MS`
30
+ * overrides it so a test can prove the loopback server closes on a timeout
31
+ * without waiting five minutes. */
32
+ function loginTimeoutMs() {
33
+ const raw = Number(getEnv("CM_SIWC_LOGIN_TIMEOUT_MS"));
34
+ return Number.isFinite(raw) && raw > 0 ? raw : 5 * 60 * 1000;
35
+ }
36
+ /** `CM_SIWC_AUTH_URL` and `CM_SIWC_API_URL` point the flow at local fakes in
37
+ * tests; unset means the real endpoints. `CM_SIWC_DIR` moves the credentials
38
+ * file so tests never touch the real one. */
39
+ function authOrigin() {
40
+ return (getEnv("CM_SIWC_AUTH_URL") ?? "https://auth.openai.com").replace(/\/$/, "");
41
+ }
42
+ function accountBase() {
43
+ return `${authOrigin()}/api/accounts`;
44
+ }
45
+ function apiBase() {
46
+ return (getEnv("CM_SIWC_API_URL") ?? "https://api.openai.com/v1").replace(/\/$/, "");
47
+ }
48
+ export function credentialsDir() {
49
+ return getEnv("CM_SIWC_DIR") ?? `${getConfigDir()}/co-maintainer/oauth`;
50
+ }
51
+ export function credentialsPath() {
52
+ return `${credentialsDir()}/${SIWC_PROVIDER}.json`;
53
+ }
54
+ /** OpenRouter-style ids carry a provider prefix (`openai/gpt-6-luna`) the
55
+ * plan route does not know. Stripping it lets the same value work on both. */
56
+ export function normalizeModel(model) {
57
+ return model.replace(/^openai\//, "");
58
+ }
59
+ function b64url(input) {
60
+ return Buffer.from(input).toString("base64url");
61
+ }
62
+ function query(params) {
63
+ return Object.entries(params)
64
+ .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
65
+ .join("&");
66
+ }
67
+ function decodeJwt(token) {
68
+ const parts = token.split(".");
69
+ if (parts.length !== 3)
70
+ throw new Error("id_token is not a JWT");
71
+ const [header, payload, signature] = parts;
72
+ return {
73
+ header: JSON.parse(Buffer.from(header, "base64url").toString("utf8")),
74
+ payload: JSON.parse(Buffer.from(payload, "base64url").toString("utf8")),
75
+ signingInput: `${header}.${payload}`,
76
+ signature: Buffer.from(signature, "base64url"),
77
+ };
78
+ }
79
+ async function fetchJson(url) {
80
+ const response = await fetch(url);
81
+ if (!response.ok)
82
+ throw new Error(`${url} returned ${response.status}`);
83
+ return (await response.json());
84
+ }
85
+ async function verifySignature(header, signingInput, signature) {
86
+ if (header.alg !== "RS256") {
87
+ throw new Error(`unsupported id_token algorithm ${header.alg}`);
88
+ }
89
+ const discovery = await fetchJson(`${authOrigin()}/.well-known/openid-configuration`);
90
+ const jwksUri = discovery.jwks_uri;
91
+ if (typeof jwksUri !== "string")
92
+ throw new Error("no jwks_uri in discovery");
93
+ const jwks = await fetchJson(jwksUri);
94
+ const keys = Array.isArray(jwks.keys) ? jwks.keys : [];
95
+ const jwk = keys.find((key) => key.kid === header.kid) ?? keys[0];
96
+ if (!jwk)
97
+ throw new Error("no JWKS key for the id_token");
98
+ const publicKey = createPublicKey({ key: jwk, format: "jwk" });
99
+ const ok = verify("RSA-SHA256", Buffer.from(signingInput), publicKey, signature);
100
+ if (!ok)
101
+ throw new Error("id_token signature did not verify");
102
+ }
103
+ function audiences(payload) {
104
+ const aud = payload.aud;
105
+ if (typeof aud === "string")
106
+ return [aud];
107
+ if (Array.isArray(aud))
108
+ return aud.map(String);
109
+ return [];
110
+ }
111
+ async function validateIdToken(idToken, clientId, nonce) {
112
+ const { header, payload, signingInput, signature } = decodeJwt(idToken);
113
+ if (String(payload.iss ?? "") !== authOrigin()) {
114
+ throw new Error(`id_token issuer ${payload.iss} is not ${authOrigin()}`);
115
+ }
116
+ if (!audiences(payload).includes(clientId)) {
117
+ throw new Error("id_token audience does not match the client id");
118
+ }
119
+ const exp = Number(payload.exp ?? 0);
120
+ if (!exp || exp * 1000 < Date.now())
121
+ throw new Error("id_token expired");
122
+ if (nonce && payload.nonce !== nonce)
123
+ throw new Error("id_token nonce mismatch");
124
+ await verifySignature(header, signingInput, signature);
125
+ return {
126
+ subject: String(payload.sub ?? ""),
127
+ email: typeof payload.email === "string" ? payload.email : undefined,
128
+ };
129
+ }
130
+ export function loadCredentials() {
131
+ try {
132
+ return JSON.parse(readTextFileSync(credentialsPath()));
133
+ }
134
+ catch (error) {
135
+ if (isNotFound(error))
136
+ return undefined;
137
+ return undefined;
138
+ }
139
+ }
140
+ async function saveCredentials(creds) {
141
+ const path = credentialsPath();
142
+ await mkdir(path.replace(/\/[^/]+$/, ""), { recursive: true });
143
+ await writeTextFile(path, `${JSON.stringify(creds, null, 2)}\n`);
144
+ try {
145
+ await chmod(path, 0o600);
146
+ }
147
+ catch {
148
+ // Windows has no POSIX chmod; NotSupported there is expected.
149
+ }
150
+ }
151
+ /** Keeps the issued client id even when the code exchange fails, so a later
152
+ * run reauthorizes with it instead of registering again. */
153
+ async function rememberClientId(clientId, hostId) {
154
+ const current = loadCredentials();
155
+ await saveCredentials({
156
+ ...(current ?? {}),
157
+ issuer: authOrigin(),
158
+ client_id: clientId,
159
+ ext_agent_host_id: hostId,
160
+ saved_at: new Date().toISOString(),
161
+ });
162
+ }
163
+ export async function logout() {
164
+ const path = credentialsPath();
165
+ try {
166
+ await remove(path);
167
+ return true;
168
+ }
169
+ catch (error) {
170
+ if (isNotFound(error))
171
+ return false;
172
+ throw error;
173
+ }
174
+ }
175
+ let browserOpener;
176
+ /** Tests replace the browser with a helper that completes the callback; the
177
+ * real opener shells out to the platform's open command. */
178
+ export function setBrowserOpener(opener) {
179
+ browserOpener = opener;
180
+ }
181
+ function openBrowser(url) {
182
+ if (browserOpener) {
183
+ browserOpener(url);
184
+ return;
185
+ }
186
+ const { command, args } = process.platform === "darwin"
187
+ ? { command: "open", args: [url] }
188
+ : process.platform === "win32"
189
+ ? // `start` is a cmd.exe builtin, not an executable, so it needs cmd.
190
+ { command: "cmd", args: ["/c", "start", "", url] }
191
+ : { command: "xdg-open", args: [url] };
192
+ try {
193
+ const child = spawn(command, args, { detached: true, stdio: "ignore" });
194
+ // A missing launcher (no xdg-open, no cmd) reports through this event, not
195
+ // a throw. Swallow it: the printed URL is the manual fallback.
196
+ child.on("error", () => { });
197
+ child.unref();
198
+ }
199
+ catch {
200
+ // Synchronous spawn failures are the same: the printed URL is the fallback.
201
+ }
202
+ }
203
+ async function tokenRequest(body) {
204
+ let response;
205
+ try {
206
+ response = await fetch(`${accountBase()}/oauth/token`, {
207
+ method: "POST",
208
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
209
+ body: query(body),
210
+ });
211
+ }
212
+ catch (error) {
213
+ throw networkFailure(`${accountBase()}/oauth/token`, error);
214
+ }
215
+ const text = await response.text();
216
+ if (!response.ok) {
217
+ throw new Error(`token endpoint ${response.status}: ${text.slice(0, 300)}`);
218
+ }
219
+ return JSON.parse(text);
220
+ }
221
+ function invalidGrant(error) {
222
+ return error instanceof Error && error.message.includes("invalid_grant");
223
+ }
224
+ async function authorize(opts) {
225
+ let resolveCallback;
226
+ const pending = new Promise((resolve) => {
227
+ resolveCallback = resolve;
228
+ });
229
+ const server = createServer((req, res) => {
230
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
231
+ if (url.pathname !== CALLBACK_PATH) {
232
+ res.writeHead(404).end();
233
+ return;
234
+ }
235
+ res.writeHead(200, { "content-type": "text/html" });
236
+ res.end("<h2>Signed in. You can close this tab.</h2>");
237
+ resolveCallback({
238
+ code: url.searchParams.get("code") ?? undefined,
239
+ state: url.searchParams.get("state") ?? undefined,
240
+ client_id: url.searchParams.get("client_id") ?? undefined,
241
+ error: url.searchParams.get("error") ?? undefined,
242
+ error_description: url.searchParams.get("error_description") ?? undefined,
243
+ });
244
+ });
245
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
246
+ const address = server.address();
247
+ const port = typeof address === "object" && address ? address.port : 0;
248
+ const redirectUri = `http://127.0.0.1:${port}${CALLBACK_PATH}`;
249
+ const verifier = b64url(randomBytes(32));
250
+ const challenge = b64url(createHash("sha256").update(verifier).digest());
251
+ const state = b64url(randomBytes(16));
252
+ const nonce = b64url(randomBytes(16));
253
+ const params = {
254
+ client_id: opts.clientId,
255
+ ext_agent_host_id: opts.hostId,
256
+ response_type: "code",
257
+ redirect_uri: redirectUri,
258
+ scope: SCOPE,
259
+ resource: `${apiBase()}`,
260
+ state,
261
+ nonce,
262
+ code_challenge_method: "S256",
263
+ code_challenge: challenge,
264
+ };
265
+ if (opts.agentNameHint)
266
+ params.agent_name_hint = opts.agentNameHint;
267
+ if (opts.idTokenHint)
268
+ params.id_token_hint = opts.idTokenHint;
269
+ if (opts.loginHint)
270
+ params.login_hint = opts.loginHint;
271
+ const url = `${accountBase()}/authorize?${query(params)}`;
272
+ console.log("Open this URL to sign in with ChatGPT:");
273
+ console.log(url);
274
+ openBrowser(url);
275
+ let timer;
276
+ const timeout = new Promise((_, reject) => {
277
+ timer = setTimeout(() => reject(new Error("timed out waiting for the browser sign-in")), loginTimeoutMs());
278
+ timer.unref?.();
279
+ });
280
+ let result;
281
+ try {
282
+ result = await Promise.race([pending, timeout]);
283
+ }
284
+ finally {
285
+ // The timeout path must not leave the loopback server listening, or it
286
+ // keeps the CLI process alive after the sign-in failed.
287
+ if (timer)
288
+ clearTimeout(timer);
289
+ server.close();
290
+ }
291
+ if (!result)
292
+ throw new Error("sign-in ended without a result");
293
+ if (result.error) {
294
+ throw new CliError("siwc_denied", `ChatGPT denied access (${result.error}).`, `This may be because the account has no paid ChatGPT subscription (Go, Plus or Pro is required). See ${HELP_URL}`, EXIT_USAGE);
295
+ }
296
+ if (result.state !== state)
297
+ throw new Error("state mismatch on callback");
298
+ if (!result.code)
299
+ throw new Error("no code on callback");
300
+ return {
301
+ code: result.code,
302
+ issuedClientId: result.client_id,
303
+ redirectUri,
304
+ verifier,
305
+ nonce,
306
+ };
307
+ }
308
+ async function exchange(clientId, result) {
309
+ return tokenRequest({
310
+ grant_type: "authorization_code",
311
+ client_id: clientId,
312
+ code: result.code,
313
+ code_verifier: result.verifier,
314
+ redirect_uri: result.redirectUri,
315
+ resource: apiBase(),
316
+ });
317
+ }
318
+ function toCredentials(token, clientId, hostId, identity) {
319
+ const expiresIn = Number(token.expires_in ?? 3600);
320
+ return {
321
+ subject: identity.subject,
322
+ ...(identity.email ? { email: identity.email } : {}),
323
+ issuer: authOrigin(),
324
+ client_id: clientId,
325
+ ext_agent_host_id: hostId,
326
+ id_token: String(token.id_token ?? ""),
327
+ access_token: String(token.access_token ?? ""),
328
+ refresh_token: String(token.refresh_token ?? ""),
329
+ token_type: String(token.token_type ?? "Bearer"),
330
+ expires_in: expiresIn,
331
+ expires_at: Date.now() + expiresIn * 1000,
332
+ scopes: typeof token.scope === "string" && token.scope
333
+ ? token.scope.split(" ")
334
+ : [],
335
+ saved_at: new Date().toISOString(),
336
+ };
337
+ }
338
+ let cached;
339
+ /** The freshest credentials this process has seen. `complete()` refreshes on a
340
+ * 401, and this is what makes the new token visible to the next caller instead
341
+ * of the stale record `ensureCredentials` resolved earlier. */
342
+ function remember(creds) {
343
+ cached = creds;
344
+ return creds;
345
+ }
346
+ /** The browser flow. Always runs, so a user can switch accounts; `logout`
347
+ * first if the old one should not be reused. */
348
+ export async function login() {
349
+ const existing = loadCredentials();
350
+ const hostId = existing?.ext_agent_host_id ?? `urn:uuid:${randomUUID()}`;
351
+ let attempt = await authorize({
352
+ clientId: existing?.client_id ?? DEFAULT_CLIENT_ID,
353
+ hostId,
354
+ agentNameHint: existing ? undefined : APP_NAME,
355
+ idTokenHint: existing?.id_token,
356
+ loginHint: existing?.email,
357
+ });
358
+ let clientId = attempt.issuedClientId ?? existing?.client_id;
359
+ if (!clientId)
360
+ throw new Error("registration did not return a client id");
361
+ await rememberClientId(clientId, hostId);
362
+ let token;
363
+ try {
364
+ token = await exchange(clientId, attempt);
365
+ }
366
+ catch (error) {
367
+ if (!invalidGrant(error) || !attempt.issuedClientId)
368
+ throw error;
369
+ console.log("Retrying the sign-in with the issued client id.");
370
+ clientId = attempt.issuedClientId;
371
+ attempt = await authorize({ clientId, hostId });
372
+ token = await exchange(clientId, attempt);
373
+ }
374
+ const identity = await validateIdToken(String(token.id_token ?? ""), clientId, attempt.nonce);
375
+ const creds = toCredentials(token, clientId, hostId, identity);
376
+ await saveCredentials(creds);
377
+ return remember(creds);
378
+ }
379
+ export async function refresh(creds) {
380
+ const token = await tokenRequest({
381
+ grant_type: "refresh_token",
382
+ client_id: creds.client_id,
383
+ refresh_token: creds.refresh_token,
384
+ resource: apiBase(),
385
+ });
386
+ const identity = await validateIdToken(String(token.id_token ?? creds.id_token), creds.client_id);
387
+ const next = toCredentials({
388
+ ...token,
389
+ // A refresh response may omit the id_token. Keep the one that was
390
+ // already validated, or a later refresh has nothing to decode.
391
+ id_token: token.id_token ?? creds.id_token,
392
+ refresh_token: token.refresh_token ?? creds.refresh_token,
393
+ }, creds.client_id, creds.ext_agent_host_id, identity);
394
+ await saveCredentials(next);
395
+ return remember(next);
396
+ }
397
+ function requireInteractive() {
398
+ if (process.stdin.isTTY !== true) {
399
+ throw new CliError("siwc_no_browser", "Sign in with ChatGPT needs a browser, which is not available here.", `Run co-maintainer oauth login --provider=${SIWC_PROVIDER} on a machine with a browser.`, EXIT_USAGE);
400
+ }
401
+ }
402
+ let inflight;
403
+ /** Credentials for a run: reuse the freshest token this process has seen,
404
+ * refresh an expired one, or start the browser flow. `inflight` dedups so
405
+ * `init`'s low and high providers never open two browsers; `cached` keeps a
406
+ * 401 refresh done inside `complete()` visible to later callers. */
407
+ export function ensureCredentials() {
408
+ if (cached && cached.expires_at - 60_000 > Date.now()) {
409
+ return Promise.resolve(cached);
410
+ }
411
+ if (inflight)
412
+ return inflight;
413
+ inflight = (async () => {
414
+ const existing = cached ?? loadCredentials();
415
+ if (existing?.refresh_token) {
416
+ if (existing.expires_at - 60_000 > Date.now())
417
+ return existing;
418
+ return refresh(existing);
419
+ }
420
+ requireInteractive();
421
+ return login();
422
+ })();
423
+ // Clear on settle, not only on rejection: a resolved `inflight` that stayed
424
+ // set would be handed out again after `cached` expires, serving a stale
425
+ // token. Concurrent callers still share this one promise.
426
+ inflight.then(() => {
427
+ inflight = undefined;
428
+ }, () => {
429
+ inflight = undefined;
430
+ });
431
+ return inflight;
432
+ }
433
+ /** For `oauth refresh|ping|list-models`, which operate on an existing login
434
+ * and must not start a browser flow. A live token is reused, an expired one
435
+ * refreshed; no login at all is a clear error. */
436
+ export async function requireCredentials() {
437
+ const existing = loadCredentials();
438
+ if (!existing?.refresh_token && !existing?.access_token) {
439
+ throw new CliError("siwc_not_signed_in", "Not signed in to ChatGPT.", `Run co-maintainer oauth login --provider=${SIWC_PROVIDER} first.`, EXIT_USAGE);
440
+ }
441
+ if (existing.expires_at - 60_000 > Date.now())
442
+ return existing;
443
+ if (!existing.refresh_token)
444
+ return existing;
445
+ return refresh(existing);
446
+ }
447
+ export async function listModels(creds) {
448
+ const url = `${apiBase()}/models`;
449
+ let response;
450
+ try {
451
+ response = await fetch(url, {
452
+ headers: { Authorization: `Bearer ${creds.access_token}` },
453
+ });
454
+ }
455
+ catch (error) {
456
+ throw networkFailure(url, error);
457
+ }
458
+ if (!response.ok) {
459
+ throw new CliError("siwc_models_failed", `ChatGPT returned ${response.status} while listing models.`, `If the token expired, run co-maintainer oauth login --provider=${SIWC_PROVIDER}.`, EXIT_RUNTIME);
460
+ }
461
+ const json = (await response.json());
462
+ const listed = Array.isArray(json.models) ? json.models : [];
463
+ if (listed.length > 0) {
464
+ return listed
465
+ .filter((model) => model.visibility === "list" && model.slug)
466
+ .map((model) => ({
467
+ slug: String(model.slug),
468
+ displayName: String(model.display_name ?? model.slug),
469
+ }));
470
+ }
471
+ const data = Array.isArray(json.data) ? json.data : [];
472
+ return data
473
+ .filter((model) => model.id)
474
+ .map((model) => ({
475
+ slug: String(model.id),
476
+ displayName: String(model.id),
477
+ }));
478
+ }
479
+ /** The model slugs a user can pick, for prompts and error messages. */
480
+ export async function availableModelSlugs() {
481
+ const creds = await ensureCredentials();
482
+ return (await listModels(creds)).map((model) => model.slug);
483
+ }
484
+ function eligibilityHelp() {
485
+ return new CliError("siwc_ineligible", "ChatGPT denied access. This may be because the account has no paid ChatGPT subscription (Go, Plus or Pro is required).", `For details see ${HELP_URL}`);
486
+ }
487
+ async function planError(creds, model, status, body) {
488
+ let code = "";
489
+ let message = "";
490
+ try {
491
+ const parsed = JSON.parse(body);
492
+ code = String(parsed.error?.code ?? "");
493
+ message = String(parsed.error?.message ?? "");
494
+ }
495
+ catch {
496
+ message = body.trim().slice(0, 200);
497
+ }
498
+ if (status === 401) {
499
+ return new CliError("siwc_unauthorized", "Sign in with ChatGPT rejected the token.", `Run co-maintainer oauth login --provider=${SIWC_PROVIDER} to sign in again.`, EXIT_USAGE);
500
+ }
501
+ if (status === 403 && code.startsWith("subscription_sharing")) {
502
+ return eligibilityHelp();
503
+ }
504
+ if ((status === 400 || status === 404) && code === "model_not_found") {
505
+ const slugs = await listModels(creds).then((models) => models.map((info) => info.slug), () => []);
506
+ return new CliError("siwc_unknown_model", `This ChatGPT plan does not serve the model ${normalizeModel(model)}${message ? `: ${message}` : "."}`, slugs.length
507
+ ? `Available models: ${slugs.join(", ")}. Set one with --low-model=... or --high-model=...`
508
+ : undefined, EXIT_USAGE);
509
+ }
510
+ return new CliError("siwc_failed", `ChatGPT failed with ${status}${message ? `: ${message}` : "."}`, undefined, EXIT_RUNTIME);
511
+ }
512
+ export class SignInWithChatGptProvider {
513
+ supportsTools = true;
514
+ model;
515
+ constructor(model) {
516
+ this.model = normalizeModel(model);
517
+ }
518
+ async post(accessToken, request) {
519
+ const endpoint = `${apiBase()}/responses`;
520
+ try {
521
+ return await fetch(endpoint, {
522
+ method: "POST",
523
+ headers: {
524
+ Authorization: `Bearer ${accessToken}`,
525
+ "Content-Type": "application/json",
526
+ },
527
+ body: JSON.stringify(responsesBody(this.model, request, { planUsage: true })),
528
+ });
529
+ }
530
+ catch (error) {
531
+ throw networkFailure(endpoint, error);
532
+ }
533
+ }
534
+ async complete(request) {
535
+ let creds = await ensureCredentials();
536
+ let response = await this.post(creds.access_token, request);
537
+ if (response.status === 401) {
538
+ creds = await refresh(creds);
539
+ response = await this.post(creds.access_token, request);
540
+ }
541
+ if (!response.ok) {
542
+ const detail = await response.text();
543
+ throw await planError(creds, this.model, response.status, detail);
544
+ }
545
+ const json = await readResponsesStream(response);
546
+ if (json.status === "failed") {
547
+ const error = (json.error ?? {});
548
+ throw await planError(creds, this.model, Number(error.status ?? 400), JSON.stringify({ error }));
549
+ }
550
+ return parseResponsesBody(json, this.model, SIWC_PROVIDER);
551
+ }
552
+ }
@@ -26,7 +26,7 @@
26
26
  * turns out to matter in practice; codegraph's own tool loop caps rounds low
27
27
  * (mermaid_loop.ts's `maxToolRounds`), which limits how much is at stake.
28
28
  */
29
- import type { AiProvider, AiRequest, AiResponse } from "../types.ts";
29
+ import type { AiProvider, AiRequest, AiResponse, Json } from "../types.ts";
30
30
  import { CliError } from "../cli/error.ts";
31
31
  /** `CM_OPENAI_URL` points at a local fake in tests. Unset means the real
32
32
  * endpoint, so production behavior is unchanged. */
@@ -34,6 +34,23 @@ export declare function openAiBase(): string;
34
34
  /** A failed response as actionable text. Only `error.message` is
35
35
  * shown: the raw body can carry request ids that mean nothing in a terminal. */
36
36
  export declare function openAiError(model: string, status: number, body: string): CliError;
37
+ export type ResponsesBodyOptions = {
38
+ /** The ChatGPT plan usage route. It rejects `max_output_tokens` and
39
+ * requires `store: false` with `stream: true`, unlike the API-key route
40
+ * this file otherwise targets. */
41
+ planUsage?: boolean;
42
+ };
43
+ export declare function responsesBody(model: string, request: AiRequest, options?: ResponsesBodyOptions): Json;
44
+ export declare function parseResponsesBody(json: Json, model: string, provider?: AiResponse["provider"]): AiResponse;
45
+ /** The SSE body the plan usage route always returns (`stream: true`). The
46
+ * text deltas are ignored; the output items arrive as their own
47
+ * `response.output_item.done` events, because this route's terminal
48
+ * `response.completed` carries an empty `output` array (the standard API
49
+ * fills it). The terminal response supplies `usage` and `status`; the
50
+ * collected items supply `output`, so the shared {@link parseResponsesBody}
51
+ * sees the same shape on both routes. A stream with no terminal response
52
+ * throws. */
53
+ export declare function readResponsesStream(response: Response): Promise<Json>;
37
54
  export declare class OpenAiProvider implements AiProvider {
38
55
  readonly supportsTools = true;
39
56
  private readonly endpoint;
@@ -89,14 +89,16 @@ function toResponsesInput(messages) {
89
89
  }
90
90
  return { instructions, input };
91
91
  }
92
- function responsesBody(model, request) {
92
+ export function responsesBody(model, request, options = {}) {
93
93
  const { instructions, input } = toResponsesInput(effectiveMessages(request));
94
94
  const schema = request.responseFormat?.json_schema;
95
95
  return {
96
96
  model,
97
97
  ...(instructions ? { instructions } : {}),
98
98
  input,
99
- max_output_tokens: request.maxTokens,
99
+ ...(options.planUsage
100
+ ? { store: false, stream: true }
101
+ : { max_output_tokens: request.maxTokens }),
100
102
  ...(request.reasoningEffort
101
103
  ? { reasoning: { effort: request.reasoningEffort } }
102
104
  : {}),
@@ -120,7 +122,7 @@ function responsesBody(model, request) {
120
122
  : {}),
121
123
  };
122
124
  }
123
- function parseResponsesBody(json, model) {
125
+ export function parseResponsesBody(json, model, provider = "openai") {
124
126
  const output = Array.isArray(json.output)
125
127
  ? json.output
126
128
  : [];
@@ -148,7 +150,7 @@ function parseResponsesBody(json, model) {
148
150
  const usage = json.usage;
149
151
  const text = texts.join("");
150
152
  if (json.status === "incomplete" && !text.trim() && !toolCalls.length) {
151
- throw outputLimitError("openai", model);
153
+ throw outputLimitError(provider, model);
152
154
  }
153
155
  return {
154
156
  text,
@@ -159,9 +161,70 @@ function parseResponsesBody(json, model) {
159
161
  // unknown (`costReasonText`'s "provider_did_not_report").
160
162
  cost: undefined,
161
163
  model,
162
- provider: "openai",
164
+ provider,
163
165
  };
164
166
  }
167
+ /** The SSE body the plan usage route always returns (`stream: true`). The
168
+ * text deltas are ignored; the output items arrive as their own
169
+ * `response.output_item.done` events, because this route's terminal
170
+ * `response.completed` carries an empty `output` array (the standard API
171
+ * fills it). The terminal response supplies `usage` and `status`; the
172
+ * collected items supply `output`, so the shared {@link parseResponsesBody}
173
+ * sees the same shape on both routes. A stream with no terminal response
174
+ * throws. */
175
+ export async function readResponsesStream(response) {
176
+ if (!response.body) {
177
+ throw new Error("OpenAI returned no response body to stream");
178
+ }
179
+ const reader = response.body.getReader();
180
+ const decoder = new TextDecoder();
181
+ let buffer = "";
182
+ let terminal;
183
+ const items = [];
184
+ for (;;) {
185
+ const { done, value } = await reader.read();
186
+ if (done)
187
+ break;
188
+ buffer += decoder.decode(value, { stream: true });
189
+ // SSE events are separated by a blank line; tolerate CRLF.
190
+ buffer = buffer.replace(/\r/g, "");
191
+ let index = buffer.indexOf("\n\n");
192
+ while (index >= 0) {
193
+ const block = buffer.slice(0, index);
194
+ buffer = buffer.slice(index + 2);
195
+ for (const line of block.split("\n")) {
196
+ if (!line.startsWith("data:"))
197
+ continue;
198
+ const data = line.slice(5).trim();
199
+ if (!data || data === "[DONE]")
200
+ continue;
201
+ let event;
202
+ try {
203
+ event = JSON.parse(data);
204
+ }
205
+ catch {
206
+ continue;
207
+ }
208
+ const type = String(event.type ?? "");
209
+ if (type === "response.output_item.done" && event.item) {
210
+ items.push(event.item);
211
+ }
212
+ else if (type === "response.completed" ||
213
+ type === "response.incomplete" ||
214
+ type === "response.failed") {
215
+ terminal = event.response;
216
+ }
217
+ }
218
+ index = buffer.indexOf("\n\n");
219
+ }
220
+ }
221
+ if (!terminal)
222
+ throw new Error("OpenAI stream ended without a response");
223
+ const output = terminal.output;
224
+ if (Array.isArray(output) && output.length > 0)
225
+ return terminal;
226
+ return { ...terminal, output: items };
227
+ }
165
228
  export class OpenAiProvider {
166
229
  supportsTools = true;
167
230
  endpoint = `${openAiBase()}/responses`;