@koreanhole/opencodex 3.2.22 → 3.2.23

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@koreanhole/opencodex",
3
- "version": "3.2.22",
3
+ "version": "3.2.23",
4
4
  "description": "Full opencodex runtime with Cline 2.2.0+ JSON and Gemini CLI headless provider adapters",
5
5
  "type": "module",
6
6
  "main": "./bin/package-main.mjs",
@@ -12,7 +12,9 @@ import {
12
12
  type GeminiMetadataResult,
13
13
  } from "./model-metadata";
14
14
  import {
15
+ assertGeminiExplicitOAuthCredentials,
15
16
  buildGeminiHeadlessEnv,
17
+ GeminiAuthPreflightError,
16
18
  geminiHeadlessArgs,
17
19
  probeGeminiHeadlessSupport,
18
20
  runGeminiHeadlessTurn,
@@ -156,6 +158,17 @@ function failure(error: unknown): Extract<AdapterEvent, { type: "error" }> {
156
158
  };
157
159
  }
158
160
 
161
+ function geminiConfigError(error: GeminiAuthPreflightError): Extract<AdapterEvent, { type: "error" }> {
162
+ return {
163
+ type: "error",
164
+ message: error.message,
165
+ status: 400,
166
+ errorType: "invalid_request_error",
167
+ code: error.code,
168
+ retryable: false,
169
+ };
170
+ }
171
+
159
172
  async function resolveSession(
160
173
  parsed: OcxParsedRequest,
161
174
  incoming: IncomingMeta,
@@ -195,6 +208,14 @@ export async function runGeminiTurn(
195
208
  return;
196
209
  }
197
210
 
211
+ const sourceEnv = deps.env ?? process.env;
212
+ try {
213
+ assertGeminiExplicitOAuthCredentials(sourceEnv);
214
+ } catch (error) {
215
+ emit(error instanceof GeminiAuthPreflightError ? geminiConfigError(error) : failure(error));
216
+ return;
217
+ }
218
+
198
219
  let catalog: ReturnType<typeof buildCodingAgentToolCatalog>;
199
220
  try {
200
221
  catalog = buildCodingAgentToolCatalog(parsed, GEMINI_MCP_SERVER_NAME);
@@ -208,7 +229,6 @@ export async function runGeminiTurn(
208
229
  return;
209
230
  }
210
231
 
211
- const sourceEnv = deps.env ?? process.env;
212
232
  await reclaimGeminiSessions(sourceEnv).catch(() => undefined);
213
233
  const binary = resolveGeminiBinary(deps.which ?? whichFromPath, sourceEnv);
214
234
  if (!binary) {
@@ -312,14 +332,20 @@ export async function runGeminiTurn(
312
332
  await deleteGeminiSession(prior.keyHash, sourceEnv).catch(() => undefined);
313
333
  prior = undefined;
314
334
  }
315
- const workspace = await (deps.stageHeadless ?? stageGeminiHeadlessWorkspace)(
316
- reasoning ? { modelId: requestedModel, thinkingConfig: reasoning.thinkingConfig } : undefined,
317
- {
318
- ...(reuse && prior ? { root: prior.workspace } : sessionKey ? { root: geminiSessionWorkspace(sessionKey, sourceEnv) } : {}),
319
- sourceEnv,
320
- ...(catalog.tools.length > 0 ? { catalog: catalog.tools, mcp: mcpLaunch() } : {}),
321
- },
322
- );
335
+ let workspace: Awaited<ReturnType<typeof stageGeminiHeadlessWorkspace>>;
336
+ try {
337
+ workspace = await (deps.stageHeadless ?? stageGeminiHeadlessWorkspace)(
338
+ reasoning ? { modelId: requestedModel, thinkingConfig: reasoning.thinkingConfig } : undefined,
339
+ {
340
+ ...(reuse && prior ? { root: prior.workspace } : sessionKey ? { root: geminiSessionWorkspace(sessionKey, sourceEnv) } : {}),
341
+ sourceEnv,
342
+ ...(catalog.tools.length > 0 ? { catalog: catalog.tools, mcp: mcpLaunch() } : {}),
343
+ },
344
+ );
345
+ } catch (error) {
346
+ emit(error instanceof GeminiAuthPreflightError ? geminiConfigError(error) : failure(error));
347
+ return;
348
+ }
323
349
  let vendorSessionId: string | undefined;
324
350
  let terminal: AdapterEvent | undefined;
325
351
  try {
@@ -337,6 +363,7 @@ export async function runGeminiTurn(
337
363
  args: geminiHeadlessArgs({ modelId: requestedModel }),
338
364
  modelId: requestedModel,
339
365
  prompt: fullPrompt,
366
+ ...(workspace.diagnostics?.length ? { diagnostics: workspace.diagnostics } : {}),
340
367
  ...(reuse && prior && deltaPrompt ? { deltaPrompt, resumeSessionId: prior.vendorSessionId } : {}),
341
368
  ...(resolved.source ? { sessionKeySource: resolved.source } : {}),
342
369
  hadPreviousResponseId: Boolean(parsed.previousResponseId),
@@ -1,6 +1,6 @@
1
1
  import { spawn as nodeSpawn, type ChildProcess } from "node:child_process";
2
2
  import { accessSync, constants, existsSync, readFileSync, statSync } from "node:fs";
3
- import { link, lstat, mkdir, mkdtemp, readFile, rm, stat, symlink, writeFile } from "node:fs/promises";
3
+ import { chmod, copyFile, link, mkdir, mkdtemp, readFile, rm, stat, symlink, writeFile } from "node:fs/promises";
4
4
  import { homedir, tmpdir } from "node:os";
5
5
  import { join, resolve } from "node:path";
6
6
  import type { AdapterEvent, IncomingMeta, OcxUsage } from "../../../types";
@@ -18,6 +18,8 @@ const HELP_TIMEOUT_MS = 15_000;
18
18
  const MAX_HELP_BYTES = 256 * 1024;
19
19
  const MAX_STDERR_BYTES = 8 * 1024;
20
20
  const MAX_ERROR_CHARS = 2_048;
21
+ const MAX_STDERR_SURFACED_CHARS = 1_024;
22
+ const MAX_DIAGNOSTIC_CHARS = 768;
21
23
  const MAX_CAPTURE_FILE_BYTES = 4 * 1024 * 1024;
22
24
  const CAPTURE_POLL_MS = 25;
23
25
  const GEMINI_MCP_SERVER_NAME = "opencodex";
@@ -67,6 +69,18 @@ const FORWARDED_ENV_KEYS = [
67
69
 
68
70
  const AUTH_FILE_NAMES = ["oauth_creds.json", "google_accounts.json", ".env"] as const;
69
71
  const OAUTH_AUTH_FILE_NAMES = ["oauth_creds.json", "google_accounts.json", "gemini-credentials.json"] as const;
72
+ const GEMINI_AUTH_CONSULTED_KEYS = [
73
+ "GEMINI_CLI_HOME",
74
+ "HOME",
75
+ "USERPROFILE",
76
+ "APPDATA",
77
+ "GOOGLE_GENAI_USE_GCA",
78
+ "GEMINI_API_KEY",
79
+ "GOOGLE_API_KEY",
80
+ "GOOGLE_GEMINI_BASE_URL",
81
+ "GOOGLE_APPLICATION_CREDENTIALS",
82
+ "GEMINI_FORCE_ENCRYPTED_FILE_STORAGE",
83
+ ] as const;
70
84
  type GeminiHeadlessAuth = "oauth" | "environment" | "vertex";
71
85
 
72
86
  export interface GeminiHeadlessDeps extends CliAgentTurnDeps {
@@ -173,6 +187,143 @@ function geminiVendorHome(sourceEnv: NodeJS.ProcessEnv): string {
173
187
  ?? homedir();
174
188
  }
175
189
 
190
+ interface GeminiCredentialCandidate {
191
+ geminiDir: string;
192
+ label: "vendor home" | "real user home";
193
+ key: string;
194
+ }
195
+
196
+ interface GeminiCredentialProbe extends GeminiCredentialCandidate {
197
+ usableFiles: string[];
198
+ }
199
+
200
+ interface GeminiCredentialSource {
201
+ candidate: GeminiCredentialCandidate;
202
+ names: readonly string[];
203
+ probes: GeminiCredentialProbe[];
204
+ usableFiles: string[];
205
+ }
206
+
207
+ export class GeminiAuthPreflightError extends Error {
208
+ readonly code = "gemini_oauth_credentials_missing";
209
+
210
+ constructor(message: string) {
211
+ super(message);
212
+ this.name = "GeminiAuthPreflightError";
213
+ }
214
+ }
215
+
216
+ function realUserHome(sourceEnv: NodeJS.ProcessEnv): string {
217
+ return nonEmpty(sourceEnv.HOME) ?? nonEmpty(sourceEnv.USERPROFILE) ?? homedir();
218
+ }
219
+
220
+ function geminiHomeKey(sourceEnv: NodeJS.ProcessEnv, allowVendorOverride: boolean): string {
221
+ if (allowVendorOverride && nonEmpty(sourceEnv.GEMINI_CLI_HOME)) return "GEMINI_CLI_HOME";
222
+ if (nonEmpty(sourceEnv.HOME)) return "HOME";
223
+ if (nonEmpty(sourceEnv.USERPROFILE)) return "USERPROFILE";
224
+ return "homedir()";
225
+ }
226
+
227
+ function geminiAuthFileNames(auth: GeminiHeadlessAuth): readonly string[] {
228
+ return auth === "oauth" ? OAUTH_AUTH_FILE_NAMES : AUTH_FILE_NAMES;
229
+ }
230
+
231
+ function usableCredentialFiles(geminiDir: string, names: readonly string[]): string[] {
232
+ return names.filter(name => {
233
+ const path = join(geminiDir, name);
234
+ try {
235
+ const info = statSync(path);
236
+ accessSync(path, constants.R_OK);
237
+ return info.isFile() && info.size > 0;
238
+ } catch {
239
+ return false;
240
+ }
241
+ });
242
+ }
243
+
244
+ function resolveGeminiCredentialSource(
245
+ sourceEnv: NodeJS.ProcessEnv,
246
+ auth: GeminiHeadlessAuth,
247
+ ): GeminiCredentialSource {
248
+ const names = geminiAuthFileNames(auth);
249
+ const vendorHome = geminiVendorHome(sourceEnv);
250
+ const userHome = realUserHome(sourceEnv);
251
+ const probeBases: GeminiCredentialCandidate[] = [
252
+ {
253
+ geminiDir: join(vendorHome, ".gemini"),
254
+ label: "vendor home",
255
+ key: geminiHomeKey(sourceEnv, true),
256
+ },
257
+ {
258
+ geminiDir: join(userHome, ".gemini"),
259
+ label: "real user home",
260
+ key: geminiHomeKey(sourceEnv, false),
261
+ },
262
+ ];
263
+ const probes: GeminiCredentialProbe[] = probeBases.map(probe => ({
264
+ ...probe,
265
+ usableFiles: usableCredentialFiles(probe.geminiDir, names),
266
+ }));
267
+ const unique = probes.filter((probe, index) =>
268
+ probes.findIndex(candidate => resolve(candidate.geminiDir) === resolve(probe.geminiDir)) === index);
269
+ const candidate = unique.find(probe => probe.usableFiles.length > 0)
270
+ ?? unique.find(probe => names.some(name => existsSync(join(probe.geminiDir, name))))
271
+ ?? unique[0]!;
272
+ return {
273
+ candidate,
274
+ names,
275
+ probes,
276
+ usableFiles: candidate.usableFiles,
277
+ };
278
+ }
279
+
280
+ function hasAlternateGeminiAuth(sourceEnv: NodeJS.ProcessEnv): boolean {
281
+ return Boolean(
282
+ nonEmpty(sourceEnv.GEMINI_API_KEY)
283
+ || nonEmpty(sourceEnv.GOOGLE_API_KEY)
284
+ || nonEmpty(sourceEnv.GOOGLE_GEMINI_BASE_URL)
285
+ || nonEmpty(sourceEnv.GOOGLE_APPLICATION_CREDENTIALS)
286
+ || hasVertexAdc(sourceEnv),
287
+ );
288
+ }
289
+
290
+ function assertResolvedGeminiCredentials(
291
+ sourceEnv: NodeJS.ProcessEnv,
292
+ source: GeminiCredentialSource,
293
+ ): void {
294
+ if (!enabled(sourceEnv.GOOGLE_GENAI_USE_GCA)) return;
295
+ if (source.usableFiles.length > 0 || hasAlternateGeminiAuth(sourceEnv)) return;
296
+ const vendor = source.probes.find(probe => probe.label === "vendor home")!;
297
+ const real = source.probes.find(probe => probe.label === "real user home")!;
298
+ const sameLocation = resolve(vendor.geminiDir) === resolve(real.geminiDir);
299
+ throw new GeminiAuthPreflightError([
300
+ "Gemini OAuth credentials are missing.",
301
+ `Probed vendor home: ${vendor.geminiDir} (selected by ${vendor.key}).`,
302
+ `Probed real user home: ${real.geminiDir} (selected by ${real.key})${sameLocation ? " (same location)" : ""}.`,
303
+ `Consulted environment keys: ${GEMINI_AUTH_CONSULTED_KEYS.join(", ")}.`,
304
+ "Run `gemini` in an interactive terminal to sign in, point GEMINI_CLI_HOME at an authenticated Gemini home, or configure GEMINI_API_KEY/GOOGLE_API_KEY or Application Default Credentials.",
305
+ "No credential contents were read.",
306
+ ].join("\n"));
307
+ }
308
+
309
+ export function assertGeminiExplicitOAuthCredentials(sourceEnv: NodeJS.ProcessEnv = process.env): void {
310
+ if (!enabled(sourceEnv.GOOGLE_GENAI_USE_GCA)) return;
311
+ assertResolvedGeminiCredentials(
312
+ sourceEnv,
313
+ resolveGeminiCredentialSource(sourceEnv, "oauth"),
314
+ );
315
+ }
316
+
317
+ function credentialSourceDiagnostic(source: GeminiCredentialSource): string {
318
+ const files = source.usableFiles.length > 0
319
+ ? `usable files: ${source.usableFiles.join(", ")}`
320
+ : "no usable credential file";
321
+ const probed = source.probes
322
+ .map(probe => `${probe.label} ${probe.geminiDir} (${probe.key}; ${probe.usableFiles.length > 0 ? "usable" : "no usable store"})`)
323
+ .join("; ");
324
+ return `Gemini credentials: using ${source.candidate.label} ${source.candidate.geminiDir} (${source.candidate.key}); ${files}; probed ${probed}`;
325
+ }
326
+
176
327
  function hasPlaintextGeminiOAuthStore(sourceEnv: NodeJS.ProcessEnv): boolean {
177
328
  const path = join(geminiVendorHome(sourceEnv), ".gemini", "oauth_creds.json");
178
329
  try {
@@ -320,6 +471,7 @@ export interface GeminiHeadlessWorkspace {
320
471
  root: string;
321
472
  geminiHome: string;
322
473
  settingsPath: string;
474
+ diagnostics?: string[];
323
475
  catalogPath?: string;
324
476
  capturePath?: string;
325
477
  cleanup: () => Promise<void>;
@@ -397,6 +549,11 @@ export async function stageGeminiHeadlessWorkspace(
397
549
  mcp?: GeminiHeadlessMcpLaunch;
398
550
  } = {},
399
551
  ): Promise<GeminiHeadlessWorkspace> {
552
+ const sourceEnv = options.sourceEnv ?? process.env;
553
+ const auth = geminiHeadlessAuth(sourceEnv);
554
+ const credentialSource = resolveGeminiCredentialSource(sourceEnv, auth);
555
+ assertResolvedGeminiCredentials(sourceEnv, credentialSource);
556
+ const diagnostics = [credentialSourceDiagnostic(credentialSource)];
400
557
  const root = options.root ?? await mkdtemp(join(tmpdir(), "ocx-gemini-headless-"));
401
558
  await mkdir(root, { recursive: true, mode: 0o700 });
402
559
  const geminiHome = join(root, "gemini-home");
@@ -406,8 +563,6 @@ export async function stageGeminiHeadlessWorkspace(
406
563
  const catalog = options.catalog ?? [];
407
564
  const capturePath = catalog.length > 0 ? join(root, "tool-intents.ndjson") : undefined;
408
565
  const mcpServers = geminiMcpSettings(catalog, options.mcp, catalogPath, capturePath);
409
- const sourceEnv = options.sourceEnv ?? process.env;
410
- const auth = geminiHeadlessAuth(sourceEnv);
411
566
  const exclusive = options.root === undefined;
412
567
  const writeOptions = { encoding: "utf8" as const, mode: 0o600, ...(exclusive ? { flag: "wx" as const } : {}) };
413
568
  await mkdir(geminiConfigDir, { recursive: true, mode: 0o700 });
@@ -416,11 +571,12 @@ export async function stageGeminiHeadlessWorkspace(
416
571
  writeFile(catalogPath, JSON.stringify(catalog), writeOptions),
417
572
  ...(capturePath ? [writeFile(capturePath, "", writeOptions)] : []),
418
573
  ]);
419
- await linkGeminiAuth(geminiConfigDir, sourceEnv, auth);
574
+ await linkGeminiAuth(geminiConfigDir, credentialSource, diagnostics);
420
575
  return {
421
576
  root,
422
577
  geminiHome,
423
578
  settingsPath,
579
+ diagnostics,
424
580
  catalogPath,
425
581
  ...(capturePath ? { capturePath } : {}),
426
582
  cleanup: async () => { await rm(root, { recursive: true, force: true }).catch(() => undefined); },
@@ -429,29 +585,82 @@ export async function stageGeminiHeadlessWorkspace(
429
585
 
430
586
  async function linkGeminiAuth(
431
587
  targetDir: string,
432
- sourceEnv: NodeJS.ProcessEnv,
433
- auth: GeminiHeadlessAuth,
588
+ source: GeminiCredentialSource,
589
+ diagnostics: string[],
434
590
  ): Promise<void> {
435
- const realGemini = join(geminiVendorHome(sourceEnv), ".gemini");
436
- const names = auth === "oauth" ? OAUTH_AUTH_FILE_NAMES : AUTH_FILE_NAMES;
437
- await Promise.all(names.map(async name => {
438
- const target = join(realGemini, name);
439
- try {
440
- await lstat(target);
441
- } catch {
591
+ for (const name of source.names) {
592
+ const sourcePath = join(source.candidate.geminiDir, name);
593
+ if (!existsSync(sourcePath)) continue;
594
+ await stageGeminiCredentialFile(sourcePath, join(targetDir, name), name, diagnostics);
595
+ }
596
+ }
597
+
598
+ async function isStagedFile(path: string): Promise<boolean> {
599
+ try {
600
+ return (await stat(path)).isFile();
601
+ } catch {
602
+ return false;
603
+ }
604
+ }
605
+
606
+ async function stageGeminiCredentialFile(
607
+ sourcePath: string,
608
+ targetPath: string,
609
+ name: string,
610
+ diagnostics: string[],
611
+ ): Promise<void> {
612
+ let sourceInfo;
613
+ try {
614
+ sourceInfo = await stat(sourcePath);
615
+ } catch (error) {
616
+ diagnostics.push(`Gemini credentials: could not inspect ${name} at ${sourcePath} (${safeMessage(error, "unknown error")}); not staged`);
617
+ return;
618
+ }
619
+ if (!sourceInfo.isFile()) {
620
+ diagnostics.push(`Gemini credentials: ${sourcePath} is not a regular file; ${name} not staged`);
621
+ return;
622
+ }
623
+ if (await isStagedFile(targetPath)) {
624
+ diagnostics.push(`Gemini credentials: ${name} already staged from ${sourcePath} (existing)`);
625
+ return;
626
+ }
627
+ await rm(targetPath, { recursive: true, force: true }).catch(() => undefined);
628
+ const failures: string[] = [];
629
+ try {
630
+ await symlink(resolve(sourcePath), targetPath);
631
+ if (await isStagedFile(targetPath)) {
632
+ diagnostics.push(`Gemini credentials: ${name} staged from ${sourcePath} (symlink)`);
442
633
  return;
443
634
  }
444
- const path = join(targetDir, name);
445
- try {
446
- await symlink(resolve(target), path);
447
- } catch {
448
- try {
449
- await link(resolve(target), path);
450
- } catch {
451
- // Best-effort; environment-provided auth remains the primary contract.
452
- }
635
+ throw new Error("target is not a regular file");
636
+ } catch (error) {
637
+ failures.push(`symlink: ${safeMessage(error, "failed")}`);
638
+ }
639
+ await rm(targetPath, { recursive: true, force: true }).catch(() => undefined);
640
+ try {
641
+ await link(resolve(sourcePath), targetPath);
642
+ if (await isStagedFile(targetPath)) {
643
+ diagnostics.push(`Gemini credentials: ${name} staged from ${sourcePath} (hardlink)`);
644
+ return;
453
645
  }
454
- }));
646
+ throw new Error("target is not a regular file");
647
+ } catch (error) {
648
+ failures.push(`hardlink: ${safeMessage(error, "failed")}`);
649
+ }
650
+ await rm(targetPath, { recursive: true, force: true }).catch(() => undefined);
651
+ try {
652
+ await copyFile(sourcePath, targetPath, constants.COPYFILE_EXCL);
653
+ await chmod(targetPath, 0o600);
654
+ if (await isStagedFile(targetPath)) {
655
+ diagnostics.push(`Gemini credentials: ${name} staged from ${sourcePath} (copy)`);
656
+ return;
657
+ }
658
+ throw new Error("target is not a regular file");
659
+ } catch (error) {
660
+ failures.push(`copy: ${safeMessage(error, "failed")}`);
661
+ }
662
+ await rm(targetPath, { recursive: true, force: true }).catch(() => undefined);
663
+ diagnostics.push(`Gemini credentials: could not stage ${name} from ${sourcePath}; ${failures.join("; ")}; not available`);
455
664
  }
456
665
 
457
666
  export interface GeminiHeadlessArgsInput {
@@ -490,6 +699,7 @@ export interface GeminiHeadlessTurnInput {
490
699
  toolNames?: ReadonlyMap<string, string>;
491
700
  maxToolCalls?: number;
492
701
  requireToolCall?: boolean;
702
+ diagnostics?: readonly string[];
493
703
  deps?: CliAgentTurnDeps;
494
704
  }
495
705
 
@@ -567,6 +777,27 @@ function classifyFailure(exitCode: number, stderr: string): Extract<AdapterEvent
567
777
  return { type: "error", message, ...classifyError(message) };
568
778
  }
569
779
 
780
+ function withFailureDiagnostics(
781
+ event: Extract<AdapterEvent, { type: "error" }>,
782
+ stderr: string,
783
+ diagnostics: readonly string[] | undefined,
784
+ ): Extract<AdapterEvent, { type: "error" }> {
785
+ const rawTail = stderr.trim();
786
+ const tail = rawTail
787
+ ? redactSecretString(rawTail.slice(-(MAX_STDERR_SURFACED_CHARS * 4))).trim().slice(-MAX_STDERR_SURFACED_CHARS)
788
+ : "";
789
+ const tailPart = tail && !event.message.includes(tail) ? `\nGemini stderr tail: ${tail}` : "";
790
+ const diagnosticText = (diagnostics ?? []).filter(Boolean).join("; ");
791
+ const diagnosticPart = diagnosticText
792
+ ? `\nGemini credential diagnostics: ${redactSecretString(diagnosticText).slice(0, MAX_DIAGNOSTIC_CHARS)}`
793
+ : "";
794
+ if (!tailPart && !diagnosticPart) return event;
795
+ const room = Math.max(0, MAX_ERROR_CHARS - tailPart.length - diagnosticPart.length);
796
+ const message = (redactSecretString(event.message.slice(0, room)) + tailPart + diagnosticPart)
797
+ .slice(0, MAX_ERROR_CHARS);
798
+ return { ...event, message };
799
+ }
800
+
570
801
  function killWindowsProcessTree(pid: number): void {
571
802
  const taskkill = (process.env.SystemRoot ?? "C:\\Windows") + "\\System32\\taskkill.exe";
572
803
  nodeSpawn(taskkill, ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
@@ -584,8 +815,7 @@ async function runAttempt(
584
815
  const killGraceMs = deps.killGraceMs ?? DEFAULT_KILL_GRACE_MS;
585
816
  const reapTimeoutMs = deps.reapTimeoutMs ?? killGraceMs * 2 + 250;
586
817
  const promptText = resumeSessionId && input.deltaPrompt ? input.deltaPrompt : input.prompt;
587
- const stderr: string[] = [];
588
- let stderrBytes = 0;
818
+ let stderr = "";
589
819
  let child: ChildProcess | undefined;
590
820
  let terminal: AttemptResult["terminal"] | undefined;
591
821
  let sawText = false;
@@ -764,11 +994,9 @@ async function runAttempt(
764
994
 
765
995
  child.stderr?.setEncoding("utf8");
766
996
  child.stderr?.on("data", (chunk: string) => {
767
- if (stderrBytes >= MAX_STDERR_BYTES) return;
768
- const remaining = MAX_STDERR_BYTES - stderrBytes;
769
- const admitted = chunk.slice(0, remaining);
770
- stderr.push(admitted);
771
- stderrBytes += Buffer.byteLength(admitted);
997
+ let tail = (stderr + chunk).slice(-MAX_STDERR_BYTES);
998
+ while (Buffer.byteLength(tail) > MAX_STDERR_BYTES) tail = tail.slice(1);
999
+ stderr = tail;
772
1000
  });
773
1001
 
774
1002
  if (!child.stdin) throw new Error("Gemini headless process produced no stdin stream.");
@@ -865,7 +1093,7 @@ async function runAttempt(
865
1093
  retryable: false,
866
1094
  });
867
1095
  } else if (exitCode !== null && exitCode !== 0) {
868
- finish(classifyFailure(exitCode, stderr.join("")));
1096
+ finish(classifyFailure(exitCode, stderr));
869
1097
  } else if (state.toolCalls > 0) {
870
1098
  finish({ type: "done", stopReason: "tool_use", ...(usage ? { usage } : {}) });
871
1099
  } else if (input.requireToolCall) {
@@ -908,7 +1136,7 @@ async function runAttempt(
908
1136
  if (killTimer) clearTimeout(killTimer);
909
1137
  }
910
1138
 
911
- const result = terminal ?? {
1139
+ const rawResult = terminal ?? {
912
1140
  type: "error" as const,
913
1141
  message: "Gemini headless ended without a terminal result.",
914
1142
  status: 502,
@@ -916,6 +1144,9 @@ async function runAttempt(
916
1144
  code: "cli_protocol_error",
917
1145
  retryable: false,
918
1146
  };
1147
+ const result = rawResult.type === "error"
1148
+ ? withFailureDiagnostics(rawResult, stderr, input.diagnostics)
1149
+ : rawResult;
919
1150
  return {
920
1151
  terminal: result,
921
1152
  ...(sessionId ? { sessionId } : {}),