@koreanhole/opencodex 3.2.21 → 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
|
@@ -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
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
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
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
3
|
-
import {
|
|
2
|
+
import { accessSync, constants, existsSync, readFileSync, statSync } from "node:fs";
|
|
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,154 @@ 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
|
+
|
|
327
|
+
function hasPlaintextGeminiOAuthStore(sourceEnv: NodeJS.ProcessEnv): boolean {
|
|
328
|
+
const path = join(geminiVendorHome(sourceEnv), ".gemini", "oauth_creds.json");
|
|
329
|
+
try {
|
|
330
|
+
const info = statSync(path);
|
|
331
|
+
accessSync(path, constants.R_OK);
|
|
332
|
+
return info.isFile() && info.size > 0;
|
|
333
|
+
} catch {
|
|
334
|
+
return false;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
176
338
|
function safeMessage(value: unknown, fallback: string): string {
|
|
177
339
|
const raw = typeof value === "string"
|
|
178
340
|
? value
|
|
@@ -213,7 +375,10 @@ export function buildGeminiHeadlessEnv(
|
|
|
213
375
|
}
|
|
214
376
|
if (geminiHeadlessAuth(sourceEnv) === "oauth") {
|
|
215
377
|
env.GOOGLE_GENAI_USE_GCA = "true";
|
|
216
|
-
if (
|
|
378
|
+
if (
|
|
379
|
+
env.GEMINI_FORCE_ENCRYPTED_FILE_STORAGE === undefined
|
|
380
|
+
&& !hasPlaintextGeminiOAuthStore(sourceEnv)
|
|
381
|
+
) {
|
|
217
382
|
env.GEMINI_FORCE_ENCRYPTED_FILE_STORAGE = "true";
|
|
218
383
|
}
|
|
219
384
|
}
|
|
@@ -306,6 +471,7 @@ export interface GeminiHeadlessWorkspace {
|
|
|
306
471
|
root: string;
|
|
307
472
|
geminiHome: string;
|
|
308
473
|
settingsPath: string;
|
|
474
|
+
diagnostics?: string[];
|
|
309
475
|
catalogPath?: string;
|
|
310
476
|
capturePath?: string;
|
|
311
477
|
cleanup: () => Promise<void>;
|
|
@@ -383,6 +549,11 @@ export async function stageGeminiHeadlessWorkspace(
|
|
|
383
549
|
mcp?: GeminiHeadlessMcpLaunch;
|
|
384
550
|
} = {},
|
|
385
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)];
|
|
386
557
|
const root = options.root ?? await mkdtemp(join(tmpdir(), "ocx-gemini-headless-"));
|
|
387
558
|
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
388
559
|
const geminiHome = join(root, "gemini-home");
|
|
@@ -392,8 +563,6 @@ export async function stageGeminiHeadlessWorkspace(
|
|
|
392
563
|
const catalog = options.catalog ?? [];
|
|
393
564
|
const capturePath = catalog.length > 0 ? join(root, "tool-intents.ndjson") : undefined;
|
|
394
565
|
const mcpServers = geminiMcpSettings(catalog, options.mcp, catalogPath, capturePath);
|
|
395
|
-
const sourceEnv = options.sourceEnv ?? process.env;
|
|
396
|
-
const auth = geminiHeadlessAuth(sourceEnv);
|
|
397
566
|
const exclusive = options.root === undefined;
|
|
398
567
|
const writeOptions = { encoding: "utf8" as const, mode: 0o600, ...(exclusive ? { flag: "wx" as const } : {}) };
|
|
399
568
|
await mkdir(geminiConfigDir, { recursive: true, mode: 0o700 });
|
|
@@ -402,11 +571,12 @@ export async function stageGeminiHeadlessWorkspace(
|
|
|
402
571
|
writeFile(catalogPath, JSON.stringify(catalog), writeOptions),
|
|
403
572
|
...(capturePath ? [writeFile(capturePath, "", writeOptions)] : []),
|
|
404
573
|
]);
|
|
405
|
-
await linkGeminiAuth(geminiConfigDir,
|
|
574
|
+
await linkGeminiAuth(geminiConfigDir, credentialSource, diagnostics);
|
|
406
575
|
return {
|
|
407
576
|
root,
|
|
408
577
|
geminiHome,
|
|
409
578
|
settingsPath,
|
|
579
|
+
diagnostics,
|
|
410
580
|
catalogPath,
|
|
411
581
|
...(capturePath ? { capturePath } : {}),
|
|
412
582
|
cleanup: async () => { await rm(root, { recursive: true, force: true }).catch(() => undefined); },
|
|
@@ -415,29 +585,82 @@ export async function stageGeminiHeadlessWorkspace(
|
|
|
415
585
|
|
|
416
586
|
async function linkGeminiAuth(
|
|
417
587
|
targetDir: string,
|
|
418
|
-
|
|
419
|
-
|
|
588
|
+
source: GeminiCredentialSource,
|
|
589
|
+
diagnostics: string[],
|
|
420
590
|
): Promise<void> {
|
|
421
|
-
const
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
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)`);
|
|
428
633
|
return;
|
|
429
634
|
}
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
}
|
|
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;
|
|
439
645
|
}
|
|
440
|
-
|
|
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`);
|
|
441
664
|
}
|
|
442
665
|
|
|
443
666
|
export interface GeminiHeadlessArgsInput {
|
|
@@ -476,6 +699,7 @@ export interface GeminiHeadlessTurnInput {
|
|
|
476
699
|
toolNames?: ReadonlyMap<string, string>;
|
|
477
700
|
maxToolCalls?: number;
|
|
478
701
|
requireToolCall?: boolean;
|
|
702
|
+
diagnostics?: readonly string[];
|
|
479
703
|
deps?: CliAgentTurnDeps;
|
|
480
704
|
}
|
|
481
705
|
|
|
@@ -553,6 +777,27 @@ function classifyFailure(exitCode: number, stderr: string): Extract<AdapterEvent
|
|
|
553
777
|
return { type: "error", message, ...classifyError(message) };
|
|
554
778
|
}
|
|
555
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
|
+
|
|
556
801
|
function killWindowsProcessTree(pid: number): void {
|
|
557
802
|
const taskkill = (process.env.SystemRoot ?? "C:\\Windows") + "\\System32\\taskkill.exe";
|
|
558
803
|
nodeSpawn(taskkill, ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
@@ -570,8 +815,7 @@ async function runAttempt(
|
|
|
570
815
|
const killGraceMs = deps.killGraceMs ?? DEFAULT_KILL_GRACE_MS;
|
|
571
816
|
const reapTimeoutMs = deps.reapTimeoutMs ?? killGraceMs * 2 + 250;
|
|
572
817
|
const promptText = resumeSessionId && input.deltaPrompt ? input.deltaPrompt : input.prompt;
|
|
573
|
-
|
|
574
|
-
let stderrBytes = 0;
|
|
818
|
+
let stderr = "";
|
|
575
819
|
let child: ChildProcess | undefined;
|
|
576
820
|
let terminal: AttemptResult["terminal"] | undefined;
|
|
577
821
|
let sawText = false;
|
|
@@ -750,11 +994,9 @@ async function runAttempt(
|
|
|
750
994
|
|
|
751
995
|
child.stderr?.setEncoding("utf8");
|
|
752
996
|
child.stderr?.on("data", (chunk: string) => {
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
stderr.push(admitted);
|
|
757
|
-
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;
|
|
758
1000
|
});
|
|
759
1001
|
|
|
760
1002
|
if (!child.stdin) throw new Error("Gemini headless process produced no stdin stream.");
|
|
@@ -851,7 +1093,7 @@ async function runAttempt(
|
|
|
851
1093
|
retryable: false,
|
|
852
1094
|
});
|
|
853
1095
|
} else if (exitCode !== null && exitCode !== 0) {
|
|
854
|
-
finish(classifyFailure(exitCode, stderr
|
|
1096
|
+
finish(classifyFailure(exitCode, stderr));
|
|
855
1097
|
} else if (state.toolCalls > 0) {
|
|
856
1098
|
finish({ type: "done", stopReason: "tool_use", ...(usage ? { usage } : {}) });
|
|
857
1099
|
} else if (input.requireToolCall) {
|
|
@@ -894,7 +1136,7 @@ async function runAttempt(
|
|
|
894
1136
|
if (killTimer) clearTimeout(killTimer);
|
|
895
1137
|
}
|
|
896
1138
|
|
|
897
|
-
const
|
|
1139
|
+
const rawResult = terminal ?? {
|
|
898
1140
|
type: "error" as const,
|
|
899
1141
|
message: "Gemini headless ended without a terminal result.",
|
|
900
1142
|
status: 502,
|
|
@@ -902,6 +1144,9 @@ async function runAttempt(
|
|
|
902
1144
|
code: "cli_protocol_error",
|
|
903
1145
|
retryable: false,
|
|
904
1146
|
};
|
|
1147
|
+
const result = rawResult.type === "error"
|
|
1148
|
+
? withFailureDiagnostics(rawResult, stderr, input.diagnostics)
|
|
1149
|
+
: rawResult;
|
|
905
1150
|
return {
|
|
906
1151
|
terminal: result,
|
|
907
1152
|
...(sessionId ? { sessionId } : {}),
|