@koreanhole/opencodex 3.2.22 → 3.2.24

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.24",
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";
@@ -65,8 +67,30 @@ const FORWARDED_ENV_KEYS = [
65
67
  "no_proxy",
66
68
  ] as const;
67
69
 
70
+ const CA_FILE_ENV_KEYS = ["NODE_EXTRA_CA_CERTS", "SSL_CERT_FILE"] as const;
71
+ const CA_DIRECTORY_ENV_KEYS = ["SSL_CERT_DIR"] as const;
72
+
73
+ type GeminiCaTrustKind = "file" | "directory";
74
+
75
+ interface GeminiCaTrust {
76
+ env: Record<string, string>;
77
+ diagnostics: string[];
78
+ }
79
+
68
80
  const AUTH_FILE_NAMES = ["oauth_creds.json", "google_accounts.json", ".env"] as const;
69
81
  const OAUTH_AUTH_FILE_NAMES = ["oauth_creds.json", "google_accounts.json", "gemini-credentials.json"] as const;
82
+ const GEMINI_AUTH_CONSULTED_KEYS = [
83
+ "GEMINI_CLI_HOME",
84
+ "HOME",
85
+ "USERPROFILE",
86
+ "APPDATA",
87
+ "GOOGLE_GENAI_USE_GCA",
88
+ "GEMINI_API_KEY",
89
+ "GOOGLE_API_KEY",
90
+ "GOOGLE_GEMINI_BASE_URL",
91
+ "GOOGLE_APPLICATION_CREDENTIALS",
92
+ "GEMINI_FORCE_ENCRYPTED_FILE_STORAGE",
93
+ ] as const;
70
94
  type GeminiHeadlessAuth = "oauth" | "environment" | "vertex";
71
95
 
72
96
  export interface GeminiHeadlessDeps extends CliAgentTurnDeps {
@@ -90,6 +114,42 @@ function nonEmpty(value: unknown): string | undefined {
90
114
  return typeof value === "string" && value.trim() ? value.trim() : undefined;
91
115
  }
92
116
 
117
+ function readablePathOfKind(path: string, kind: GeminiCaTrustKind): boolean {
118
+ try {
119
+ accessSync(path, constants.R_OK);
120
+ const info = statSync(path);
121
+ return kind === "file" ? info.isFile() : info.isDirectory();
122
+ } catch {
123
+ return false;
124
+ }
125
+ }
126
+
127
+ function geminiCaTrust(sourceEnv: NodeJS.ProcessEnv): GeminiCaTrust {
128
+ const env: Record<string, string> = {};
129
+ const forwarded: string[] = [];
130
+ const diagnostics: string[] = [];
131
+ const add = (key: string, value: string, kind: GeminiCaTrustKind): void => {
132
+ if (readablePathOfKind(value, kind)) {
133
+ env[key] = value;
134
+ forwarded.push(`${key}=${value}`);
135
+ } else {
136
+ diagnostics.push(`Gemini CA trust: ${key}=${value} is not an existing readable ${kind}; not forwarded`);
137
+ }
138
+ };
139
+ for (const key of CA_FILE_ENV_KEYS) {
140
+ const value = nonEmpty(sourceEnv[key]);
141
+ if (value) add(key, value, "file");
142
+ }
143
+ for (const key of CA_DIRECTORY_ENV_KEYS) {
144
+ const value = nonEmpty(sourceEnv[key]);
145
+ if (value) add(key, value, "directory");
146
+ }
147
+ if (forwarded.length > 0) {
148
+ diagnostics.unshift(`Gemini CA trust: forwarded ${forwarded.join("; ")}`);
149
+ }
150
+ return { env, diagnostics };
151
+ }
152
+
93
153
  function enabled(value: unknown): boolean {
94
154
  return nonEmpty(value)?.toLowerCase() === "true";
95
155
  }
@@ -173,6 +233,143 @@ function geminiVendorHome(sourceEnv: NodeJS.ProcessEnv): string {
173
233
  ?? homedir();
174
234
  }
175
235
 
236
+ interface GeminiCredentialCandidate {
237
+ geminiDir: string;
238
+ label: "vendor home" | "real user home";
239
+ key: string;
240
+ }
241
+
242
+ interface GeminiCredentialProbe extends GeminiCredentialCandidate {
243
+ usableFiles: string[];
244
+ }
245
+
246
+ interface GeminiCredentialSource {
247
+ candidate: GeminiCredentialCandidate;
248
+ names: readonly string[];
249
+ probes: GeminiCredentialProbe[];
250
+ usableFiles: string[];
251
+ }
252
+
253
+ export class GeminiAuthPreflightError extends Error {
254
+ readonly code = "gemini_oauth_credentials_missing";
255
+
256
+ constructor(message: string) {
257
+ super(message);
258
+ this.name = "GeminiAuthPreflightError";
259
+ }
260
+ }
261
+
262
+ function realUserHome(sourceEnv: NodeJS.ProcessEnv): string {
263
+ return nonEmpty(sourceEnv.HOME) ?? nonEmpty(sourceEnv.USERPROFILE) ?? homedir();
264
+ }
265
+
266
+ function geminiHomeKey(sourceEnv: NodeJS.ProcessEnv, allowVendorOverride: boolean): string {
267
+ if (allowVendorOverride && nonEmpty(sourceEnv.GEMINI_CLI_HOME)) return "GEMINI_CLI_HOME";
268
+ if (nonEmpty(sourceEnv.HOME)) return "HOME";
269
+ if (nonEmpty(sourceEnv.USERPROFILE)) return "USERPROFILE";
270
+ return "homedir()";
271
+ }
272
+
273
+ function geminiAuthFileNames(auth: GeminiHeadlessAuth): readonly string[] {
274
+ return auth === "oauth" ? OAUTH_AUTH_FILE_NAMES : AUTH_FILE_NAMES;
275
+ }
276
+
277
+ function usableCredentialFiles(geminiDir: string, names: readonly string[]): string[] {
278
+ return names.filter(name => {
279
+ const path = join(geminiDir, name);
280
+ try {
281
+ const info = statSync(path);
282
+ accessSync(path, constants.R_OK);
283
+ return info.isFile() && info.size > 0;
284
+ } catch {
285
+ return false;
286
+ }
287
+ });
288
+ }
289
+
290
+ function resolveGeminiCredentialSource(
291
+ sourceEnv: NodeJS.ProcessEnv,
292
+ auth: GeminiHeadlessAuth,
293
+ ): GeminiCredentialSource {
294
+ const names = geminiAuthFileNames(auth);
295
+ const vendorHome = geminiVendorHome(sourceEnv);
296
+ const userHome = realUserHome(sourceEnv);
297
+ const probeBases: GeminiCredentialCandidate[] = [
298
+ {
299
+ geminiDir: join(vendorHome, ".gemini"),
300
+ label: "vendor home",
301
+ key: geminiHomeKey(sourceEnv, true),
302
+ },
303
+ {
304
+ geminiDir: join(userHome, ".gemini"),
305
+ label: "real user home",
306
+ key: geminiHomeKey(sourceEnv, false),
307
+ },
308
+ ];
309
+ const probes: GeminiCredentialProbe[] = probeBases.map(probe => ({
310
+ ...probe,
311
+ usableFiles: usableCredentialFiles(probe.geminiDir, names),
312
+ }));
313
+ const unique = probes.filter((probe, index) =>
314
+ probes.findIndex(candidate => resolve(candidate.geminiDir) === resolve(probe.geminiDir)) === index);
315
+ const candidate = unique.find(probe => probe.usableFiles.length > 0)
316
+ ?? unique.find(probe => names.some(name => existsSync(join(probe.geminiDir, name))))
317
+ ?? unique[0]!;
318
+ return {
319
+ candidate,
320
+ names,
321
+ probes,
322
+ usableFiles: candidate.usableFiles,
323
+ };
324
+ }
325
+
326
+ function hasAlternateGeminiAuth(sourceEnv: NodeJS.ProcessEnv): boolean {
327
+ return Boolean(
328
+ nonEmpty(sourceEnv.GEMINI_API_KEY)
329
+ || nonEmpty(sourceEnv.GOOGLE_API_KEY)
330
+ || nonEmpty(sourceEnv.GOOGLE_GEMINI_BASE_URL)
331
+ || nonEmpty(sourceEnv.GOOGLE_APPLICATION_CREDENTIALS)
332
+ || hasVertexAdc(sourceEnv),
333
+ );
334
+ }
335
+
336
+ function assertResolvedGeminiCredentials(
337
+ sourceEnv: NodeJS.ProcessEnv,
338
+ source: GeminiCredentialSource,
339
+ ): void {
340
+ if (!enabled(sourceEnv.GOOGLE_GENAI_USE_GCA)) return;
341
+ if (source.usableFiles.length > 0 || hasAlternateGeminiAuth(sourceEnv)) return;
342
+ const vendor = source.probes.find(probe => probe.label === "vendor home")!;
343
+ const real = source.probes.find(probe => probe.label === "real user home")!;
344
+ const sameLocation = resolve(vendor.geminiDir) === resolve(real.geminiDir);
345
+ throw new GeminiAuthPreflightError([
346
+ "Gemini OAuth credentials are missing.",
347
+ `Probed vendor home: ${vendor.geminiDir} (selected by ${vendor.key}).`,
348
+ `Probed real user home: ${real.geminiDir} (selected by ${real.key})${sameLocation ? " (same location)" : ""}.`,
349
+ `Consulted environment keys: ${GEMINI_AUTH_CONSULTED_KEYS.join(", ")}.`,
350
+ "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.",
351
+ "No credential contents were read.",
352
+ ].join("\n"));
353
+ }
354
+
355
+ export function assertGeminiExplicitOAuthCredentials(sourceEnv: NodeJS.ProcessEnv = process.env): void {
356
+ if (!enabled(sourceEnv.GOOGLE_GENAI_USE_GCA)) return;
357
+ assertResolvedGeminiCredentials(
358
+ sourceEnv,
359
+ resolveGeminiCredentialSource(sourceEnv, "oauth"),
360
+ );
361
+ }
362
+
363
+ function credentialSourceDiagnostic(source: GeminiCredentialSource): string {
364
+ const files = source.usableFiles.length > 0
365
+ ? `usable files: ${source.usableFiles.join(", ")}`
366
+ : "no usable credential file";
367
+ const probed = source.probes
368
+ .map(probe => `${probe.label} ${probe.geminiDir} (${probe.key}; ${probe.usableFiles.length > 0 ? "usable" : "no usable store"})`)
369
+ .join("; ");
370
+ return `Gemini credentials: using ${source.candidate.label} ${source.candidate.geminiDir} (${source.candidate.key}); ${files}; probed ${probed}`;
371
+ }
372
+
176
373
  function hasPlaintextGeminiOAuthStore(sourceEnv: NodeJS.ProcessEnv): boolean {
177
374
  const path = join(geminiVendorHome(sourceEnv), ".gemini", "oauth_creds.json");
178
375
  try {
@@ -222,6 +419,7 @@ export function buildGeminiHeadlessEnv(
222
419
  if (key === "CODE_ASSIST_ENDPOINT" && !isHttpEndpoint(value)) continue;
223
420
  env[key] = value;
224
421
  }
422
+ Object.assign(env, geminiCaTrust(sourceEnv).env);
225
423
  if (geminiHeadlessAuth(sourceEnv) === "oauth") {
226
424
  env.GOOGLE_GENAI_USE_GCA = "true";
227
425
  if (
@@ -320,6 +518,7 @@ export interface GeminiHeadlessWorkspace {
320
518
  root: string;
321
519
  geminiHome: string;
322
520
  settingsPath: string;
521
+ diagnostics?: string[];
323
522
  catalogPath?: string;
324
523
  capturePath?: string;
325
524
  cleanup: () => Promise<void>;
@@ -397,6 +596,14 @@ export async function stageGeminiHeadlessWorkspace(
397
596
  mcp?: GeminiHeadlessMcpLaunch;
398
597
  } = {},
399
598
  ): Promise<GeminiHeadlessWorkspace> {
599
+ const sourceEnv = options.sourceEnv ?? process.env;
600
+ const auth = geminiHeadlessAuth(sourceEnv);
601
+ const credentialSource = resolveGeminiCredentialSource(sourceEnv, auth);
602
+ assertResolvedGeminiCredentials(sourceEnv, credentialSource);
603
+ const diagnostics = [
604
+ ...geminiCaTrust(sourceEnv).diagnostics,
605
+ credentialSourceDiagnostic(credentialSource),
606
+ ];
400
607
  const root = options.root ?? await mkdtemp(join(tmpdir(), "ocx-gemini-headless-"));
401
608
  await mkdir(root, { recursive: true, mode: 0o700 });
402
609
  const geminiHome = join(root, "gemini-home");
@@ -406,8 +613,6 @@ export async function stageGeminiHeadlessWorkspace(
406
613
  const catalog = options.catalog ?? [];
407
614
  const capturePath = catalog.length > 0 ? join(root, "tool-intents.ndjson") : undefined;
408
615
  const mcpServers = geminiMcpSettings(catalog, options.mcp, catalogPath, capturePath);
409
- const sourceEnv = options.sourceEnv ?? process.env;
410
- const auth = geminiHeadlessAuth(sourceEnv);
411
616
  const exclusive = options.root === undefined;
412
617
  const writeOptions = { encoding: "utf8" as const, mode: 0o600, ...(exclusive ? { flag: "wx" as const } : {}) };
413
618
  await mkdir(geminiConfigDir, { recursive: true, mode: 0o700 });
@@ -416,11 +621,12 @@ export async function stageGeminiHeadlessWorkspace(
416
621
  writeFile(catalogPath, JSON.stringify(catalog), writeOptions),
417
622
  ...(capturePath ? [writeFile(capturePath, "", writeOptions)] : []),
418
623
  ]);
419
- await linkGeminiAuth(geminiConfigDir, sourceEnv, auth);
624
+ await linkGeminiAuth(geminiConfigDir, credentialSource, diagnostics);
420
625
  return {
421
626
  root,
422
627
  geminiHome,
423
628
  settingsPath,
629
+ diagnostics,
424
630
  catalogPath,
425
631
  ...(capturePath ? { capturePath } : {}),
426
632
  cleanup: async () => { await rm(root, { recursive: true, force: true }).catch(() => undefined); },
@@ -429,29 +635,82 @@ export async function stageGeminiHeadlessWorkspace(
429
635
 
430
636
  async function linkGeminiAuth(
431
637
  targetDir: string,
432
- sourceEnv: NodeJS.ProcessEnv,
433
- auth: GeminiHeadlessAuth,
638
+ source: GeminiCredentialSource,
639
+ diagnostics: string[],
434
640
  ): 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 {
641
+ for (const name of source.names) {
642
+ const sourcePath = join(source.candidate.geminiDir, name);
643
+ if (!existsSync(sourcePath)) continue;
644
+ await stageGeminiCredentialFile(sourcePath, join(targetDir, name), name, diagnostics);
645
+ }
646
+ }
647
+
648
+ async function isStagedFile(path: string): Promise<boolean> {
649
+ try {
650
+ return (await stat(path)).isFile();
651
+ } catch {
652
+ return false;
653
+ }
654
+ }
655
+
656
+ async function stageGeminiCredentialFile(
657
+ sourcePath: string,
658
+ targetPath: string,
659
+ name: string,
660
+ diagnostics: string[],
661
+ ): Promise<void> {
662
+ let sourceInfo;
663
+ try {
664
+ sourceInfo = await stat(sourcePath);
665
+ } catch (error) {
666
+ diagnostics.push(`Gemini credentials: could not inspect ${name} at ${sourcePath} (${safeMessage(error, "unknown error")}); not staged`);
667
+ return;
668
+ }
669
+ if (!sourceInfo.isFile()) {
670
+ diagnostics.push(`Gemini credentials: ${sourcePath} is not a regular file; ${name} not staged`);
671
+ return;
672
+ }
673
+ if (await isStagedFile(targetPath)) {
674
+ diagnostics.push(`Gemini credentials: ${name} already staged from ${sourcePath} (existing)`);
675
+ return;
676
+ }
677
+ await rm(targetPath, { recursive: true, force: true }).catch(() => undefined);
678
+ const failures: string[] = [];
679
+ try {
680
+ await symlink(resolve(sourcePath), targetPath);
681
+ if (await isStagedFile(targetPath)) {
682
+ diagnostics.push(`Gemini credentials: ${name} staged from ${sourcePath} (symlink)`);
442
683
  return;
443
684
  }
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
- }
685
+ throw new Error("target is not a regular file");
686
+ } catch (error) {
687
+ failures.push(`symlink: ${safeMessage(error, "failed")}`);
688
+ }
689
+ await rm(targetPath, { recursive: true, force: true }).catch(() => undefined);
690
+ try {
691
+ await link(resolve(sourcePath), targetPath);
692
+ if (await isStagedFile(targetPath)) {
693
+ diagnostics.push(`Gemini credentials: ${name} staged from ${sourcePath} (hardlink)`);
694
+ return;
453
695
  }
454
- }));
696
+ throw new Error("target is not a regular file");
697
+ } catch (error) {
698
+ failures.push(`hardlink: ${safeMessage(error, "failed")}`);
699
+ }
700
+ await rm(targetPath, { recursive: true, force: true }).catch(() => undefined);
701
+ try {
702
+ await copyFile(sourcePath, targetPath, constants.COPYFILE_EXCL);
703
+ await chmod(targetPath, 0o600);
704
+ if (await isStagedFile(targetPath)) {
705
+ diagnostics.push(`Gemini credentials: ${name} staged from ${sourcePath} (copy)`);
706
+ return;
707
+ }
708
+ throw new Error("target is not a regular file");
709
+ } catch (error) {
710
+ failures.push(`copy: ${safeMessage(error, "failed")}`);
711
+ }
712
+ await rm(targetPath, { recursive: true, force: true }).catch(() => undefined);
713
+ diagnostics.push(`Gemini credentials: could not stage ${name} from ${sourcePath}; ${failures.join("; ")}; not available`);
455
714
  }
456
715
 
457
716
  export interface GeminiHeadlessArgsInput {
@@ -490,6 +749,7 @@ export interface GeminiHeadlessTurnInput {
490
749
  toolNames?: ReadonlyMap<string, string>;
491
750
  maxToolCalls?: number;
492
751
  requireToolCall?: boolean;
752
+ diagnostics?: readonly string[];
493
753
  deps?: CliAgentTurnDeps;
494
754
  }
495
755
 
@@ -567,6 +827,27 @@ function classifyFailure(exitCode: number, stderr: string): Extract<AdapterEvent
567
827
  return { type: "error", message, ...classifyError(message) };
568
828
  }
569
829
 
830
+ function withFailureDiagnostics(
831
+ event: Extract<AdapterEvent, { type: "error" }>,
832
+ stderr: string,
833
+ diagnostics: readonly string[] | undefined,
834
+ ): Extract<AdapterEvent, { type: "error" }> {
835
+ const rawTail = stderr.trim();
836
+ const tail = rawTail
837
+ ? redactSecretString(rawTail.slice(-(MAX_STDERR_SURFACED_CHARS * 4))).trim().slice(-MAX_STDERR_SURFACED_CHARS)
838
+ : "";
839
+ const tailPart = tail && !event.message.includes(tail) ? `\nGemini stderr tail: ${tail}` : "";
840
+ const diagnosticText = (diagnostics ?? []).filter(Boolean).join("; ");
841
+ const diagnosticPart = diagnosticText
842
+ ? `\nGemini credential diagnostics: ${redactSecretString(diagnosticText).slice(0, MAX_DIAGNOSTIC_CHARS)}`
843
+ : "";
844
+ if (!tailPart && !diagnosticPart) return event;
845
+ const room = Math.max(0, MAX_ERROR_CHARS - tailPart.length - diagnosticPart.length);
846
+ const message = (redactSecretString(event.message.slice(0, room)) + tailPart + diagnosticPart)
847
+ .slice(0, MAX_ERROR_CHARS);
848
+ return { ...event, message };
849
+ }
850
+
570
851
  function killWindowsProcessTree(pid: number): void {
571
852
  const taskkill = (process.env.SystemRoot ?? "C:\\Windows") + "\\System32\\taskkill.exe";
572
853
  nodeSpawn(taskkill, ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
@@ -584,8 +865,7 @@ async function runAttempt(
584
865
  const killGraceMs = deps.killGraceMs ?? DEFAULT_KILL_GRACE_MS;
585
866
  const reapTimeoutMs = deps.reapTimeoutMs ?? killGraceMs * 2 + 250;
586
867
  const promptText = resumeSessionId && input.deltaPrompt ? input.deltaPrompt : input.prompt;
587
- const stderr: string[] = [];
588
- let stderrBytes = 0;
868
+ let stderr = "";
589
869
  let child: ChildProcess | undefined;
590
870
  let terminal: AttemptResult["terminal"] | undefined;
591
871
  let sawText = false;
@@ -764,11 +1044,9 @@ async function runAttempt(
764
1044
 
765
1045
  child.stderr?.setEncoding("utf8");
766
1046
  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);
1047
+ let tail = (stderr + chunk).slice(-MAX_STDERR_BYTES);
1048
+ while (Buffer.byteLength(tail) > MAX_STDERR_BYTES) tail = tail.slice(1);
1049
+ stderr = tail;
772
1050
  });
773
1051
 
774
1052
  if (!child.stdin) throw new Error("Gemini headless process produced no stdin stream.");
@@ -865,7 +1143,7 @@ async function runAttempt(
865
1143
  retryable: false,
866
1144
  });
867
1145
  } else if (exitCode !== null && exitCode !== 0) {
868
- finish(classifyFailure(exitCode, stderr.join("")));
1146
+ finish(classifyFailure(exitCode, stderr));
869
1147
  } else if (state.toolCalls > 0) {
870
1148
  finish({ type: "done", stopReason: "tool_use", ...(usage ? { usage } : {}) });
871
1149
  } else if (input.requireToolCall) {
@@ -908,7 +1186,7 @@ async function runAttempt(
908
1186
  if (killTimer) clearTimeout(killTimer);
909
1187
  }
910
1188
 
911
- const result = terminal ?? {
1189
+ const rawResult = terminal ?? {
912
1190
  type: "error" as const,
913
1191
  message: "Gemini headless ended without a terminal result.",
914
1192
  status: 502,
@@ -916,6 +1194,9 @@ async function runAttempt(
916
1194
  code: "cli_protocol_error",
917
1195
  retryable: false,
918
1196
  };
1197
+ const result = rawResult.type === "error"
1198
+ ? withFailureDiagnostics(rawResult, stderr, input.diagnostics)
1199
+ : rawResult;
919
1200
  return {
920
1201
  terminal: result,
921
1202
  ...(sessionId ? { sessionId } : {}),