dsh-agy-link 0.6.33 → 0.6.35

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.
@@ -8,10 +8,11 @@ import { copyFile, mkdir, open, readdir, stat, unlink, writeFile } from "node:fs
8
8
  import * as dshLlm from "@deepseek-ai/dsh-llm";
9
9
  import { LlmAdapter, LlmError } from "@deepseek-ai/dsh-llm";
10
10
  import { execFile, execFileSync, spawn } from "node:child_process";
11
+ import { promisify } from "node:util";
11
12
  import "@deepseek-ai/dsh-tools";
12
13
  import { randomUUID } from "node:crypto";
13
- import { promisify } from "node:util";
14
14
  import { EventEmitter } from "node:events";
15
+ import { StringDecoder } from "node:string_decoder";
15
16
  //#region \0rolldown/runtime.js
16
17
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
17
18
  var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
@@ -190,7 +191,7 @@ function defaultConfig() {
190
191
  * disproved.
191
192
  */
192
193
  function isAuthoritativeAuthError(message) {
193
- return /invalid_grant|invalid_client|revoked|disabled|unauthorized_client/i.test(message);
194
+ return /\b(?:invalid_grant|invalid_client|unauthorized_client|token_revoked|account_disabled|user_disabled|TOS_VIOLATION|revoked)\b|token has been expired or revoked|violation of Terms of Service/i.test(message);
194
195
  }
195
196
  /**
196
197
  * Transient transport failures — never proof that a login is dead.
@@ -204,7 +205,7 @@ function isAuthoritativeAuthError(message) {
204
205
  * (observed live: 2026-10-10 14:17, session-c65a826e turn 22).
205
206
  */
206
207
  function looksLikeNetworkError(message) {
207
- return /dial tcp|fetch failed|econn(?:refused|reset|aborted)|enotfound|ehostunreach|enetunreach|socket hang up|getaddrinfo|bad gateway|service unavailable|unexpected eof|\beof\b|tls handshake timeout|i\/o timeout|network (?:error|is unreachable)|no route to host|connection reset|context deadline exceeded|temporary failure in name resolution|proxyconnect|token validation failed|validate (?:the )?token|silent auth failed/i.test(message);
208
+ return /dial tcp|fetch failed|econn(?:refused|reset|aborted)|enotfound|ehostunreach|enetunreach|socket hang up|getaddrinfo|bad gateway|gateway time-?out|\b50[24]\b|\b52[0-4]\b|service unavailable|unexpected eof|\beof\b|tls handshake timeout|tls:\s*(?:handshake failure|bad record mac|alert)|http2:\s*client connection lost|\b(?:GOAWAY|REFUSED_STREAM)\b|broken pipe|\bepipe\b|connection timed out|socks connect|i\/o timeout|network (?:error|is unreachable)|no route to host|connection reset|context deadline exceeded|temporary failure in name resolution|proxyconnect|token validation failed|validate (?:the )?token|silent auth failed/i.test(message);
208
209
  }
209
210
  /**
210
211
  * Decide AUTH vs NETWORK for one failed agy run.
@@ -397,9 +398,30 @@ const Err = {
397
398
  //#endregion
398
399
  //#region src/common/types/diagnostics.ts
399
400
  function looksLikeAuthFailure(text) {
400
- return /authentication required|authentication failed|please sign in|not signed in|timed out waiting for authentication/i.test(text);
401
+ if (!text) return false;
402
+ const nonMcpLines = text.split(/\r?\n/).filter((line) => !/\bmcp\b.*(?:authentication (?:required|failed)|not signed in|please sign in)/i.test(line)).join("\n");
403
+ return /authentication required|authentication failed|please sign in|not signed in|timed out waiting for authentication/i.test(nonMcpLines);
404
+ }
405
+ /** Terminal Google account suspension (TOS_VIOLATION). Must NEVER auto-rotate across sibling accounts. */
406
+ function looksLikeTosViolation(text) {
407
+ if (!text) return false;
408
+ return /\bTOS_VIOLATION\b|violation of Terms of Service|This service has been disabled in this account/i.test(text);
409
+ }
410
+ /** Temporary Google account challenge (VALIDATION_REQUIRED) — recoverable via verification URL. */
411
+ function looksLikeValidationRequired(text) {
412
+ if (!text) return false;
413
+ return /\bVALIDATION_REQUIRED\b|Verify your account to continue/i.test(text);
401
414
  }
402
415
  /**
416
+ * Headless print-mode permission refusal (issue #121): agy refuses interactive
417
+ * tool approval prompts when running under `-p` without `--dangerously-skip-permissions`.
418
+ */
419
+ function looksLikeHeadlessPermissionDenial(text) {
420
+ if (!text) return false;
421
+ return /(?:approval|confirmation|review)\s+required\s+in\s+(?:non-interactive|print|headless)|cannot\s+(?:prompt|request)\s+(?:for\s+)?(?:permission|approval|review)\s+in\s+(?:print|non-interactive)|tool\s+execution\s+denied:\s*approval\s+required/i.test(text);
422
+ }
423
+ const HEADLESS_PERMISSION_ERROR_HINT = "Antigravity refused an interactive permission prompt in headless print mode. Set permissionMode to \"skip\" (or run `/agy mode skip`) so unattended tool runs can proceed.";
424
+ /**
403
425
  * Google-side account/region eligibility refusals (issue #32). agy exits 1
404
426
  * with "Eligibility check failed: … not currently available in your
405
427
  * location" — not an auth bug and not something the bridge can retry past.
@@ -1205,11 +1227,14 @@ var ImageService = class {
1205
1227
  if (!prepared.ok) return prepared.result;
1206
1228
  const input = prepared.value;
1207
1229
  const cached = this.cache.get(input.cacheKey);
1208
- if (req.force !== true && cached !== void 0 && cached.ok) return {
1209
- ...cached,
1210
- durationMs: 0,
1211
- attempts: 0
1212
- };
1230
+ if (req.force !== true && cached !== void 0 && cached.ok) {
1231
+ if (cached.path !== "" && existsSync(cached.path)) return {
1232
+ ...cached,
1233
+ durationMs: 0,
1234
+ attempts: 0
1235
+ };
1236
+ this.cache.delete(input.cacheKey);
1237
+ }
1213
1238
  const last = { ...emptyImageResult({
1214
1239
  ...req,
1215
1240
  name: input.name,
@@ -1504,7 +1529,7 @@ function accountSupportsModel(acc, model, pool, catalog) {
1504
1529
  */
1505
1530
  /** A terminal account ban (Google TOS_VIOLATION) is not a transient auth error. */
1506
1531
  function isTerminalAuthError(message) {
1507
- return typeof message === "string" && /TOS_VIOLATION/i.test(message);
1532
+ return typeof message === "string" && /\bTOS_VIOLATION\b|violation of Terms of Service/i.test(message);
1508
1533
  }
1509
1534
  function defaultPoolData() {
1510
1535
  return {
@@ -1912,42 +1937,60 @@ const MIRROR_TOOL_NAME = "agy_tool";
1912
1937
  const WRAPPER_TOOL_NAME = "run_code";
1913
1938
  //#endregion
1914
1939
  //#region src/provider/mirror/git-head.ts
1940
+ const execFileAsync$1 = promisify(execFile);
1941
+ const MAX_ROOT_CACHE = 128;
1942
+ const gitRootCache = /* @__PURE__ */ new Map();
1943
+ const ROOT_CACHE_TTL_MS = 6e4;
1944
+ function getCachedRoot(dir) {
1945
+ const hit = gitRootCache.get(dir);
1946
+ if (!hit) return void 0;
1947
+ if (Date.now() - hit.at > ROOT_CACHE_TTL_MS) {
1948
+ gitRootCache.delete(dir);
1949
+ return;
1950
+ }
1951
+ return hit.root;
1952
+ }
1953
+ function setCachedRoot(dir, root) {
1954
+ if (gitRootCache.size >= MAX_ROOT_CACHE) {
1955
+ const oldest = gitRootCache.keys().next();
1956
+ if (!oldest.done) gitRootCache.delete(oldest.value);
1957
+ }
1958
+ gitRootCache.set(dir, {
1959
+ root,
1960
+ at: Date.now()
1961
+ });
1962
+ }
1915
1963
  /**
1916
- * Retrieve the committed HEAD content of a file via git, for computing
1917
- * line diffs on full-file writes. Pure & safe: catches all failures (not in git,
1918
- * untracked, git missing, binary) and returns null in <=500ms.
1964
+ * Non-blocking version of {@link getGitHeadContent} for async span processing.
1965
+ * Caches git toplevel resolution per parent directory so repeated writes do
1966
+ * not spawn redundant `git rev-parse` calls or block the Node event loop.
1919
1967
  */
1920
- function getGitHeadContent(filePath, execFn = execFileSync) {
1968
+ async function getGitHeadContentAsync(filePath, execFn = execFileAsync$1) {
1921
1969
  if (!filePath || typeof filePath !== "string" || filePath === "file") return null;
1922
1970
  try {
1923
1971
  const resolved = path.resolve(filePath);
1924
- const toplevel = execFn("git", ["rev-parse", "--show-toplevel"], {
1925
- cwd: path.dirname(resolved),
1926
- encoding: "utf-8",
1927
- stdio: [
1928
- "ignore",
1929
- "pipe",
1930
- "ignore"
1931
- ],
1932
- timeout: 500,
1933
- windowsHide: true
1934
- });
1935
- const root = typeof toplevel === "string" ? toplevel.trim() : "";
1972
+ const dir = path.dirname(resolved);
1973
+ let root = execFn === execFileAsync$1 ? getCachedRoot(dir) : void 0;
1974
+ if (root === void 0) {
1975
+ const res = await execFn("git", ["rev-parse", "--show-toplevel"], {
1976
+ cwd: dir,
1977
+ encoding: "utf-8",
1978
+ timeout: 500,
1979
+ windowsHide: true
1980
+ });
1981
+ root = typeof res.stdout === "string" && res.stdout.trim() !== "" ? res.stdout.trim() : null;
1982
+ if (execFn === execFileAsync$1) setCachedRoot(dir, root);
1983
+ }
1936
1984
  if (!root) return null;
1937
1985
  const relPath = path.relative(root, resolved).replace(/\\/g, "/");
1938
1986
  if (relPath.startsWith("..")) return null;
1939
- const content = execFn("git", ["show", `HEAD:${relPath}`], {
1987
+ const contentRes = await execFn("git", ["show", `HEAD:${relPath}`], {
1940
1988
  cwd: root,
1941
1989
  encoding: "utf-8",
1942
- stdio: [
1943
- "ignore",
1944
- "pipe",
1945
- "ignore"
1946
- ],
1947
1990
  timeout: 500,
1948
1991
  windowsHide: true
1949
1992
  });
1950
- const str = typeof content === "string" ? content : "";
1993
+ const str = typeof contentRes.stdout === "string" ? contentRes.stdout : "";
1951
1994
  if (str.includes("\0")) return null;
1952
1995
  return str;
1953
1996
  } catch {
@@ -2320,7 +2363,7 @@ var RunRecording = class {
2320
2363
  }
2321
2364
  /** Whether a result event (ok or error-with-response) was recorded. */
2322
2365
  get hasResult() {
2323
- return this.resultConversationId !== null || this.events.some((e) => e.kind === "result");
2366
+ return this.events.some((e) => e.kind === "result");
2324
2367
  }
2325
2368
  /** The last result envelope's finish-relevant projection, when one arrived. */
2326
2369
  getResultEvent() {
@@ -2823,7 +2866,7 @@ var EventMapper = class {
2823
2866
  return;
2824
2867
  }
2825
2868
  if (ev.stepKind === "tool" && ev.tool) {
2826
- if (!(ev.state === "DONE" || ev.state === "ERROR" || ev.state === "RUNNING" || ev.state === void 0 && (ev.tool.output !== void 0 || ev.tool.error !== void 0))) {
2869
+ if (!(ev.state === "DONE" || ev.state === "ERROR" || ev.state === "CANCELED" || ev.state === "CANCELLED" || ev.state === "RUNNING" || ev.state === void 0 && (ev.tool.output !== void 0 || ev.tool.error !== void 0))) {
2827
2870
  if (this.opts.cutOnTool && !this.finished && ev.state === "ACTIVE" && !this.pendingAnnounced.has(ev.stepKey)) {
2828
2871
  this.pendingAnnounced.add(ev.stepKey);
2829
2872
  yield* this.ensureBlock("reasoning");
@@ -3069,12 +3112,14 @@ function extractStepThoughts(payload) {
3069
3112
  const res = thoughts.join("\n").trim();
3070
3113
  if (res !== "") return res;
3071
3114
  }
3072
- const full = payload.toString("utf8");
3073
- const act = /"toolAction"\s*:\s*"([^"]{3,200})"/.exec(full);
3074
- const sum = /"toolSummary"\s*:\s*"([^"]{3,200})"/.exec(full);
3075
- if (act || sum) {
3076
- const line = [act?.[1] ?? "", sum?.[1] ?? ""].filter((s) => s !== "").join(" — ");
3077
- if (line !== "") actionCandidates.push(line);
3115
+ if (payload.includes("toolAction") || payload.includes("toolSummary")) {
3116
+ const full = payload.toString("utf8");
3117
+ const act = /"toolAction"\s*:\s*"([^"]{3,200})"/.exec(full);
3118
+ const sum = /"toolSummary"\s*:\s*"([^"]{3,200})"/.exec(full);
3119
+ if (act || sum) {
3120
+ const line = [act?.[1] ?? "", sum?.[1] ?? ""].filter((s) => s !== "").join(" — ");
3121
+ if (line !== "") actionCandidates.push(line);
3122
+ }
3078
3123
  }
3079
3124
  if (actionCandidates.length > 0) return actionCandidates[0];
3080
3125
  return null;
@@ -3159,18 +3204,9 @@ function extractToolInfo(payload) {
3159
3204
  if (payload[i + 2 + nameLen] === 26) {
3160
3205
  const nameStr = payload.subarray(i + 2, i + 2 + nameLen).toString("utf-8");
3161
3206
  if (/^[a-zA-Z0-9_]+$/.test(nameStr)) {
3162
- let pos = i + 3 + nameLen;
3163
- let jsonLen = 0;
3164
- let shift = 0;
3165
- while (pos < payload.length) {
3166
- const b = payload[pos];
3167
- pos++;
3168
- jsonLen |= (b & 127) << shift;
3169
- shift += 7;
3170
- if ((b & 128) === 0) break;
3171
- }
3172
- if (jsonLen > 1 && pos + jsonLen <= payload.length) {
3173
- const jsonSlice = payload.subarray(pos, pos + jsonLen);
3207
+ const lenRes = readVarint(payload, i + 3 + nameLen);
3208
+ if (lenRes !== null && lenRes.val > 1 && lenRes.next + lenRes.val <= payload.length) {
3209
+ const jsonSlice = payload.subarray(lenRes.next, lenRes.next + lenRes.val);
3174
3210
  if (jsonSlice[0] === 123) try {
3175
3211
  const obj = JSON.parse(jsonSlice.toString("utf-8"));
3176
3212
  if (typeof obj === "object" && obj !== null && !Array.isArray(obj)) return {
@@ -3273,29 +3309,23 @@ const TOOL_STEP_TYPES$1 = /* @__PURE__ */ new Set([
3273
3309
  139
3274
3310
  ]);
3275
3311
  const MAX_CACHE_AGE_MS = 3e5;
3312
+ const STEP_FILTER_SQL = `(step_type IN (5,7,8,9,14,15,17,21,33,101,132,138,139)) AND length(step_payload) > 20`;
3276
3313
  /**
3277
3314
  * Query tool-type steps AND text/thinking steps with payload > 20 bytes.
3278
3315
  * step_type 14/15 are agent_response prose; the rest are tool steps.
3279
3316
  */
3280
- const STEP_QUERY_SQL = `SELECT idx, step_type, hex(step_payload) AS payload_hex FROM steps WHERE (step_type IN (5,7,8,9,14,15,17,21,33,101,132,138,139)) AND length(step_payload) > 20`;
3317
+ const STEP_QUERY_SQL = `SELECT idx, step_type, hex(step_payload) AS payload_hex FROM steps WHERE ${STEP_FILTER_SQL}`;
3318
+ const STEP_QUERY_RAW_SQL = `SELECT idx, step_type, step_payload FROM steps WHERE ${STEP_FILTER_SQL} AND idx >= ?`;
3281
3319
  //#endregion
3282
3320
  //#region src/runtime/agy/db/reader.ts
3283
3321
  const execFileAsync = promisify(execFile);
3284
- /**
3285
- * node:sqlite reader (Node >= 22.5, REQUIRED node >= 24 for this plugin).
3286
- * Preferred over the sqlite3 CLI: GUI/desktop hosts often lack the CLI on
3287
- * PATH (macOS GUI apps do not inherit the shell PATH; Windows never ships
3288
- * one), which is exactly the "thinking/tool args invisible on desktop"
3289
- * report (issue #43). `undefined` = not probed yet, `null` = unavailable.
3290
- */
3291
- let nodeSqliteQuery;
3292
- async function queryViaNodeSqlite(dbPath, sql) {
3293
- if (nodeSqliteQuery === null) throw new Error("node:sqlite unavailable");
3294
- if (nodeSqliteQuery === void 0) try {
3322
+ let nodeSqliteRawQuery;
3323
+ async function queryRawViaNodeSqlite(dbPath, minIdx) {
3324
+ if (nodeSqliteRawQuery === void 0 && true) try {
3295
3325
  const mod = await import("node:sqlite");
3296
3326
  if (typeof mod.DatabaseSync !== "function") throw new Error("DatabaseSync missing");
3297
3327
  const Database = mod.DatabaseSync;
3298
- nodeSqliteQuery = async (p, q) => {
3328
+ nodeSqliteRawQuery = async (p, startIdx) => {
3299
3329
  let db;
3300
3330
  try {
3301
3331
  db = new Database(p, { readOnly: true });
@@ -3309,16 +3339,53 @@ async function queryViaNodeSqlite(dbPath, sql) {
3309
3339
  try {
3310
3340
  db.exec("PRAGMA query_only = ON;");
3311
3341
  } catch {}
3312
- return db.prepare(q).all().map((r) => `${String(r.idx)}|${String(r.step_type)}|${typeof r.payload_hex === "string" ? r.payload_hex : ""}`);
3342
+ const rows = db.prepare(STEP_QUERY_RAW_SQL).all(startIdx);
3343
+ const out = [];
3344
+ for (const r of rows) {
3345
+ const idx = typeof r.idx === "number" ? r.idx : Number(r.idx);
3346
+ const stepType = typeof r.step_type === "number" ? r.step_type : Number(r.step_type);
3347
+ if (!Number.isFinite(idx) || !Number.isFinite(stepType)) continue;
3348
+ let payload;
3349
+ if (r.step_payload instanceof Uint8Array) payload = Buffer.from(r.step_payload.buffer, r.step_payload.byteOffset, r.step_payload.byteLength);
3350
+ else if (typeof r.step_payload === "string" && r.step_payload !== "") payload = Buffer.from(r.step_payload, "utf8");
3351
+ else continue;
3352
+ out.push({
3353
+ idx,
3354
+ stepType,
3355
+ payload
3356
+ });
3357
+ }
3358
+ return out;
3313
3359
  } finally {
3314
3360
  db.close();
3315
3361
  }
3316
3362
  };
3317
3363
  } catch (err) {
3318
- nodeSqliteQuery = null;
3364
+ nodeSqliteRawQuery = null;
3319
3365
  throw err instanceof Error ? err : new Error(String(err));
3320
3366
  }
3321
- return nodeSqliteQuery(dbPath, sql);
3367
+ if (nodeSqliteRawQuery) return nodeSqliteRawQuery(dbPath, minIdx);
3368
+ throw new Error("node:sqlite unavailable");
3369
+ }
3370
+ function parseHexLines(lines) {
3371
+ const out = [];
3372
+ for (const line of lines) {
3373
+ const firstPipe = line.indexOf("|");
3374
+ if (firstPipe < 0) continue;
3375
+ const secondPipe = line.indexOf("|", firstPipe + 1);
3376
+ if (secondPipe < 0) continue;
3377
+ const idx = parseInt(line.slice(0, firstPipe), 10);
3378
+ const stepType = parseInt(line.slice(firstPipe + 1, secondPipe), 10);
3379
+ if (!Number.isFinite(idx) || !Number.isFinite(stepType)) continue;
3380
+ const hexPayload = line.slice(secondPipe + 1).trim();
3381
+ if (hexPayload === "" || hexPayload === "NULL") continue;
3382
+ out.push({
3383
+ idx,
3384
+ stepType,
3385
+ payload: Buffer.from(hexPayload, "hex")
3386
+ });
3387
+ }
3388
+ return out;
3322
3389
  }
3323
3390
  /**
3324
3391
  * Failure backoff state. Without it, a missing `sqlite3` binary (or an
@@ -3345,70 +3412,69 @@ function isBackingOff(now) {
3345
3412
  * during copy. SQLite WAL mode provides concurrent read MVCC snapshots
3346
3413
  * natively without copying to temp.
3347
3414
  */
3348
- async function loadAgyDbData(conversationId, accountHome) {
3415
+ async function loadAgyDbData(conversationId, accountHome, sinceIdx = 0) {
3349
3416
  const steps = /* @__PURE__ */ new Map();
3350
3417
  const thoughts = /* @__PURE__ */ new Map();
3351
3418
  const seenSteps = /* @__PURE__ */ new Set();
3419
+ let maxSeenIdx = sinceIdx > 0 ? Math.floor(sinceIdx) - 1 : -1;
3352
3420
  if (!isSafeConversationId(conversationId)) return {
3353
3421
  steps,
3354
3422
  thoughts,
3355
- seenSteps
3423
+ seenSteps,
3424
+ maxSeenIdx
3356
3425
  };
3357
3426
  const dbPath = findConversationDb(conversationId, accountHome);
3358
3427
  if (dbPath === null) return {
3359
3428
  steps,
3360
3429
  thoughts,
3361
- seenSteps
3430
+ seenSteps,
3431
+ maxSeenIdx
3362
3432
  };
3363
3433
  try {
3364
3434
  if ((await stat(dbPath)).size === 0) return {
3365
3435
  steps,
3366
3436
  thoughts,
3367
- seenSteps
3437
+ seenSteps,
3438
+ maxSeenIdx
3368
3439
  };
3369
3440
  } catch {
3370
3441
  return {
3371
3442
  steps,
3372
3443
  thoughts,
3373
- seenSteps
3444
+ seenSteps,
3445
+ maxSeenIdx
3374
3446
  };
3375
3447
  }
3376
3448
  try {
3377
- let lines = null;
3449
+ const minIdx = Number.isFinite(sinceIdx) && sinceIdx > 0 ? Math.floor(sinceIdx) : 0;
3450
+ let rows = null;
3378
3451
  try {
3379
- lines = await queryViaNodeSqlite(dbPath, STEP_QUERY_SQL);
3452
+ rows = await queryRawViaNodeSqlite(dbPath, minIdx);
3380
3453
  } catch {
3381
3454
  try {
3455
+ const sql = minIdx > 0 ? `${STEP_QUERY_SQL} AND idx >= ${minIdx}` : STEP_QUERY_SQL;
3382
3456
  const { stdout } = await execFileAsync("sqlite3", [
3383
3457
  "-cmd",
3384
3458
  ".timeout 2000",
3385
3459
  "-cmd",
3386
3460
  "PRAGMA query_only = ON;",
3387
3461
  dbPath,
3388
- STEP_QUERY_SQL
3462
+ sql
3389
3463
  ], {
3390
3464
  timeout: 5e3,
3391
3465
  encoding: "utf-8",
3392
3466
  maxBuffer: 26214400
3393
3467
  });
3394
- lines = stdout.split("\n");
3468
+ rows = parseHexLines(stdout.split("\n"));
3395
3469
  } catch {
3396
- lines = null;
3397
- }
3398
- }
3399
- if (lines === null) throw new Error("no sqlite reader available (node:sqlite and sqlite3 CLI both failed)");
3400
- for (const line of lines) {
3401
- const firstPipe = line.indexOf("|");
3402
- if (firstPipe < 0) continue;
3403
- const secondPipe = line.indexOf("|", firstPipe + 1);
3404
- if (secondPipe < 0) continue;
3405
- const idx = parseInt(line.slice(0, firstPipe), 10);
3406
- const stepType = parseInt(line.slice(firstPipe + 1, secondPipe), 10);
3407
- if (!Number.isFinite(idx)) continue;
3470
+ rows = null;
3471
+ }
3472
+ }
3473
+ if (rows === null) throw new Error("no sqlite reader available (node:sqlite and sqlite3 CLI both failed)");
3474
+ for (const row of rows) {
3475
+ const { idx, stepType, payload } = row;
3408
3476
  seenSteps.add(idx);
3409
- const hexPayload = line.slice(secondPipe + 1).trim();
3410
- if (hexPayload === "" || hexPayload === "NULL") continue;
3411
- const payload = Buffer.from(hexPayload, "hex");
3477
+ if (idx > maxSeenIdx) maxSeenIdx = idx;
3412
3478
  if (TOOL_STEP_TYPES$1.has(stepType)) {
3413
3479
  const info = extractToolInfo(payload);
3414
3480
  if (info !== null) steps.set(idx, info);
@@ -3435,65 +3501,97 @@ async function loadAgyDbData(conversationId, accountHome) {
3435
3501
  return {
3436
3502
  steps,
3437
3503
  thoughts,
3438
- seenSteps
3504
+ seenSteps,
3505
+ maxSeenIdx
3439
3506
  };
3440
3507
  }
3441
3508
  //#endregion
3442
3509
  //#region src/runtime/agy/db/cache.ts
3443
- let cache = null;
3444
- let cacheTime = 0;
3445
- /** In-flight loader: parallel readFullToolArgs/readStepThoughts share one spawn. */
3446
- let loadInFlight = null;
3510
+ const MAX_CACHE_CONVS = 8;
3511
+ const caches = /* @__PURE__ */ new Map();
3512
+ /** In-flight loader: parallel readFullToolArgs/readStepThoughts share one query per conv+cursor. */
3513
+ const inFlightLoads = /* @__PURE__ */ new Map();
3514
+ function cacheKeyFor(conversationId, accountHome) {
3515
+ return conversationId + "|" + (accountHome ?? "");
3516
+ }
3517
+ function getFreshCache(key, now) {
3518
+ const entry = caches.get(key);
3519
+ if (!entry || !entry.loaded) return void 0;
3520
+ if (now - entry.cacheTime >= 3e5) {
3521
+ caches.delete(key);
3522
+ return;
3523
+ }
3524
+ caches.delete(key);
3525
+ caches.set(key, entry);
3526
+ return entry;
3527
+ }
3447
3528
  /**
3448
3529
  * Shared loader behind readFullToolArgs/readStepThoughts: deduplicates
3449
- * concurrent callers into ONE spawn, and honors the failure backoff so a
3450
- * missing/failing sqlite3 cannot turn every step event into a re-spawn.
3530
+ * concurrent callers into ONE query, performs O(1) incremental tail reads
3531
+ * using `maxSeenIdx`, and honors the failure backoff so a missing/failing
3532
+ * sqlite3 cannot turn every step event into a re-spawn.
3451
3533
  */
3452
- async function loadCached(conversationId, accountHome) {
3534
+ async function loadCached(conversationId, stepIndex, accountHome) {
3453
3535
  const now = Date.now();
3454
- if (isBackingOff(now)) return;
3455
- const key = conversationId + "|" + (accountHome ?? "");
3456
- if (loadInFlight !== null && loadInFlight.key === key) {
3457
- await loadInFlight.promise;
3458
- return;
3459
- }
3460
- const promise = loadAgyDbData(conversationId, accountHome);
3461
- loadInFlight = {
3462
- key,
3463
- promise
3464
- };
3465
- try {
3466
- const data = await promise;
3467
- cache = {
3536
+ const key = cacheKeyFor(conversationId, accountHome);
3537
+ if (isBackingOff(now)) return caches.get(key);
3538
+ const existing = getFreshCache(key, now);
3539
+ const sinceIdx = existing !== void 0 && existing.maxSeenIdx >= 0 ? stepIndex <= existing.maxSeenIdx ? Math.max(0, stepIndex) : existing.maxSeenIdx + 1 : 0;
3540
+ const flightKey = `${key}|${sinceIdx}`;
3541
+ const running = inFlightLoads.get(flightKey);
3542
+ if (running !== void 0) {
3543
+ await running;
3544
+ return caches.get(key);
3545
+ }
3546
+ const job = (async () => {
3547
+ const data = await loadAgyDbData(conversationId, accountHome, sinceIdx);
3548
+ const target = existing && sinceIdx > 0 ? existing : {
3468
3549
  conversationId,
3469
- steps: data.steps,
3470
- thoughts: data.thoughts,
3471
- checkedSteps: data.seenSteps,
3550
+ steps: /* @__PURE__ */ new Map(),
3551
+ thoughts: /* @__PURE__ */ new Map(),
3552
+ checkedSteps: /* @__PURE__ */ new Set(),
3553
+ maxSeenIdx: -1,
3554
+ cacheTime: now,
3472
3555
  loaded: true
3473
3556
  };
3474
- cacheTime = now;
3475
- } finally {
3476
- if (loadInFlight !== null && loadInFlight.promise === promise) loadInFlight = null;
3477
- }
3557
+ for (const [k, v] of data.steps) target.steps.set(k, v);
3558
+ for (const [k, v] of data.thoughts) target.thoughts.set(k, v);
3559
+ for (const k of data.seenSteps) target.checkedSteps.add(k);
3560
+ if (data.maxSeenIdx > target.maxSeenIdx) target.maxSeenIdx = data.maxSeenIdx;
3561
+ target.cacheTime = Date.now();
3562
+ target.loaded = true;
3563
+ caches.delete(key);
3564
+ caches.set(key, target);
3565
+ while (caches.size > MAX_CACHE_CONVS) {
3566
+ const oldest = caches.keys().next();
3567
+ if (oldest.done) break;
3568
+ caches.delete(oldest.value);
3569
+ }
3570
+ })().finally(() => {
3571
+ if (inFlightLoads.get(flightKey) === job) inFlightLoads.delete(flightKey);
3572
+ });
3573
+ inFlightLoads.set(flightKey, job);
3574
+ await job;
3575
+ return caches.get(key);
3478
3576
  }
3479
3577
  /**
3480
3578
  * Read the full tool parameter object for a given step index from the agy
3481
3579
  * conversation database. Returns null when the DB is unavailable or does
3482
3580
  * not contain the requested step.
3483
3581
  *
3484
- * Results are cached per conversationId for up to 5 minutes to avoid
3485
- * repeated DB reads within the same session.
3582
+ * Results are cached in an 8-conversation LRU for up to 5 minutes with O(1)
3583
+ * incremental tail queries.
3486
3584
  */
3487
3585
  async function readFullToolArgs(conversationId, stepIndex, accountHome) {
3488
3586
  if (!isSafeConversationId(conversationId)) return null;
3489
3587
  const now = Date.now();
3490
- if (cache?.conversationId === conversationId && cache.loaded && now - cacheTime < 3e5) {
3491
- const cached = cache.steps.get(stepIndex);
3588
+ const entry = getFreshCache(cacheKeyFor(conversationId, accountHome), now);
3589
+ if (entry) {
3590
+ const cached = entry.steps.get(stepIndex);
3492
3591
  if (cached !== void 0) return cached;
3493
- if (cache.checkedSteps.has(stepIndex) && now - cacheTime < 500) return null;
3592
+ if (entry.checkedSteps.has(stepIndex) && now - entry.cacheTime < 500) return null;
3494
3593
  }
3495
- await loadCached(conversationId, accountHome);
3496
- return cache?.steps.get(stepIndex) ?? null;
3594
+ return (await loadCached(conversationId, stepIndex, accountHome))?.steps.get(stepIndex) ?? null;
3497
3595
  }
3498
3596
  /**
3499
3597
  * Read the full thought/reasoning text for a given step index from the agy
@@ -3503,13 +3601,13 @@ async function readFullToolArgs(conversationId, stepIndex, accountHome) {
3503
3601
  async function readStepThoughts(conversationId, stepIndex, accountHome) {
3504
3602
  if (!isSafeConversationId(conversationId)) return null;
3505
3603
  const now = Date.now();
3506
- if (cache?.conversationId === conversationId && cache.loaded && now - cacheTime < 3e5) {
3507
- const cached = cache.thoughts.get(stepIndex);
3604
+ const entry = getFreshCache(cacheKeyFor(conversationId, accountHome), now);
3605
+ if (entry) {
3606
+ const cached = entry.thoughts.get(stepIndex);
3508
3607
  if (cached !== void 0) return cached;
3509
- if (cache.checkedSteps.has(stepIndex) && now - cacheTime < 500) return null;
3608
+ if (entry.checkedSteps.has(stepIndex) && now - entry.cacheTime < 500) return null;
3510
3609
  }
3511
- await loadCached(conversationId, accountHome);
3512
- return cache?.thoughts.get(stepIndex) ?? null;
3610
+ return (await loadCached(conversationId, stepIndex, accountHome))?.thoughts.get(stepIndex) ?? null;
3513
3611
  }
3514
3612
  //#endregion
3515
3613
  //#region src/provider/span.ts
@@ -3550,6 +3648,7 @@ function brief$2(s) {
3550
3648
  * `step_update`). Used to look the step's full args/thoughts up in agy's DB.
3551
3649
  */
3552
3650
  function activeConversationId(rec, ev) {
3651
+ if ("conversationId" in ev && typeof ev.conversationId === "string" && ev.conversationId !== "") return rec.conversationId ?? ev.conversationId;
3553
3652
  const rawObj = "raw" in ev && ev.raw && typeof ev.raw === "object" ? ev.raw : null;
3554
3653
  const stepUpdate = rawObj?.step_update && typeof rawObj.step_update === "object" ? rawObj.step_update : null;
3555
3654
  return rec.conversationId ?? (typeof rawObj?.conversation_id === "string" ? rawObj.conversation_id : null) ?? (typeof stepUpdate?.conversation_id === "string" ? stepUpdate.conversation_id : null);
@@ -3628,7 +3727,7 @@ async function resolveEventToolArgs(rec, ev, i, resolved) {
3628
3727
  const currentArgs = unwrapped.input;
3629
3728
  const targetFile = currentArgs.TargetFile ?? currentArgs.target_file ?? currentArgs.path ?? currentArgs.AbsolutePath;
3630
3729
  if (targetFile && typeof targetFile === "string" && !currentArgs.oldText && !currentArgs.old_string && !currentArgs.TargetContent) {
3631
- const head = getGitHeadContent(targetFile);
3730
+ const head = await getGitHeadContentAsync(targetFile);
3632
3731
  if (head !== null) {
3633
3732
  const updated = {
3634
3733
  ...currentArgs,
@@ -3863,11 +3962,23 @@ var FailoverBudget = class FailoverBudget {
3863
3962
  * the failure is not account-scoped or the budget is spent — the caller then
3864
3963
  * replays the recorded failure so the turn ends with the real error.
3865
3964
  */
3965
+ sweepIfLarge(now) {
3966
+ if (this.failover.size > 256) {
3967
+ for (const [k, v] of this.failover) if (now - v.firstAt > FailoverBudget.FAILOVER_WINDOW_MS) this.failover.delete(k);
3968
+ }
3969
+ if (this.rateLimit.size > 256) {
3970
+ for (const [k, v] of this.rateLimit) if (now - v.firstAt > FailoverBudget.RATE_LIMIT_FAILOVER_WINDOW_MS) this.rateLimit.delete(k);
3971
+ }
3972
+ if (this.network.size > 256) {
3973
+ for (const [k, v] of this.network) if (now - v.at > FailoverBudget.NETWORK_STREAK_WINDOW_MS) this.network.delete(k);
3974
+ }
3975
+ }
3866
3976
  claim(sessionKey, code, ctx) {
3867
3977
  if (!isAccountScopedFailure(code)) return false;
3868
3978
  if (code === Err.NETWORK && ctx.sharesSingleEgress()) return true;
3869
3979
  const max = Math.max(1, ctx.enabledAccounts() - 1);
3870
3980
  const now = Date.now();
3981
+ this.sweepIfLarge(now);
3871
3982
  if (code === Err.RATE_LIMIT) {
3872
3983
  const prevRl = this.rateLimit.get(sessionKey);
3873
3984
  const freshRl = prevRl === void 0 || now - prevRl.firstAt > FailoverBudget.RATE_LIMIT_FAILOVER_WINDOW_MS;
@@ -3917,6 +4028,127 @@ var FailoverBudget = class FailoverBudget {
3917
4028
  }
3918
4029
  };
3919
4030
  //#endregion
4031
+ //#region src/provider/spawn-limiter.ts
4032
+ const MAX_TRACKED_KEYS = 256;
4033
+ var SpawnLimiter = class {
4034
+ rateSlots = [];
4035
+ nextAccountAt = /* @__PURE__ */ new Map();
4036
+ nextEgressAt = /* @__PURE__ */ new Map();
4037
+ /**
4038
+ * Reserve a slot in the global per-minute sliding window.
4039
+ * Returns `{ delayMs, slotAt }`; call `cancelRateSlot(slotAt)` on abort.
4040
+ */
4041
+ reserveRateLimitSlot(limitPerMinute, now = Date.now()) {
4042
+ if (limitPerMinute <= 0) return {
4043
+ delayMs: 0,
4044
+ slotAt: now
4045
+ };
4046
+ const cutoff = now - 6e4;
4047
+ while (this.rateSlots.length > 0 && this.rateSlots[0] <= cutoff) this.rateSlots.shift();
4048
+ const slotAt = this.rateSlots.length >= limitPerMinute ? Math.max(now, this.rateSlots[this.rateSlots.length - limitPerMinute] + 6e4) : now;
4049
+ this.rateSlots.push(slotAt);
4050
+ return {
4051
+ delayMs: Math.max(0, slotAt - now),
4052
+ slotAt
4053
+ };
4054
+ }
4055
+ cancelRateLimitSlot(slotAt) {
4056
+ const idx = this.rateSlots.indexOf(slotAt);
4057
+ if (idx !== -1) this.rateSlots.splice(idx, 1);
4058
+ }
4059
+ /**
4060
+ * Reserve a spawn timestamp honoring BOTH per-account burst spacing and
4061
+ * shared-proxy cross-account spacing. Returns milliseconds to wait (`>= 0`).
4062
+ */
4063
+ reserveSpawnDelay(accountId, egressKey, minAccountIntervalMs = 500, jitterMs = Math.floor(Math.random() * 300), now = Date.now()) {
4064
+ if (!accountId && !egressKey) return 0;
4065
+ if (minAccountIntervalMs <= 0 && jitterMs <= 0) return 0;
4066
+ const accReadyAt = accountId ? this.nextAccountAt.get(accountId) ?? 0 : 0;
4067
+ const egressReadyAt = egressKey ? this.nextEgressAt.get(egressKey) ?? 0 : 0;
4068
+ const slotAt = Math.max(now, accReadyAt, egressReadyAt);
4069
+ const accountStep = Math.max(0, minAccountIntervalMs + jitterMs);
4070
+ const egressStep = Math.max(350, Math.floor(minAccountIntervalMs * .75)) + Math.floor(jitterMs * .5);
4071
+ if (accountId) {
4072
+ if (this.nextAccountAt.size >= MAX_TRACKED_KEYS && !this.nextAccountAt.has(accountId)) {
4073
+ const oldest = this.nextAccountAt.keys().next().value;
4074
+ if (oldest !== void 0) this.nextAccountAt.delete(oldest);
4075
+ }
4076
+ this.nextAccountAt.set(accountId, slotAt + accountStep);
4077
+ }
4078
+ if (egressKey) {
4079
+ if (this.nextEgressAt.size >= MAX_TRACKED_KEYS && !this.nextEgressAt.has(egressKey)) {
4080
+ const oldest = this.nextEgressAt.keys().next().value;
4081
+ if (oldest !== void 0) this.nextEgressAt.delete(oldest);
4082
+ }
4083
+ this.nextEgressAt.set(egressKey, slotAt + egressStep);
4084
+ }
4085
+ return Math.max(0, slotAt - now);
4086
+ }
4087
+ };
4088
+ //#endregion
4089
+ //#region src/common/atomic-write.ts
4090
+ let seq = 0;
4091
+ /** Unique temp path beside `file` (same directory, so rename stays atomic). */
4092
+ function atomicTmpPath(file) {
4093
+ const rand = Math.random().toString(36).slice(2, 8);
4094
+ return file + "." + process.pid + "." + (seq++).toString(36) + "." + rand + ".tmp";
4095
+ }
4096
+ /** Write `data` to `file` atomically; on any failure remove the temp file. */
4097
+ function writeFileAtomicSync(file, data, mode = 384) {
4098
+ const tmp = atomicTmpPath(file);
4099
+ try {
4100
+ mkdirSync(dirname(file), { recursive: true });
4101
+ writeFileSync(tmp, data, {
4102
+ encoding: "utf8",
4103
+ mode
4104
+ });
4105
+ renameSync(tmp, file);
4106
+ } catch (err) {
4107
+ try {
4108
+ if (existsSync(tmp)) unlinkSync(tmp);
4109
+ } catch {}
4110
+ throw err;
4111
+ }
4112
+ }
4113
+ /** Best-effort boolean wrapper around `writeFileAtomicSync` (never throws). */
4114
+ function tryWriteFileAtomic(file, data, mode = 384) {
4115
+ try {
4116
+ writeFileAtomicSync(file, data, mode);
4117
+ return true;
4118
+ } catch {
4119
+ return false;
4120
+ }
4121
+ }
4122
+ //#endregion
4123
+ //#region src/domain/quota/identity.ts
4124
+ /**
4125
+ * Organic stagger delay with randomized jitter for multi-account sequential polling.
4126
+ * Prevents rigid periodic cadence against Google Cloud Code endpoints (default: 2000~3500ms).
4127
+ */
4128
+ function staggerJitterMs(baseMs = 2e3, maxJitterMs = 1500) {
4129
+ return baseMs + Math.floor(Math.random() * maxJitterMs);
4130
+ }
4131
+ /** Used when the installed agy version is unknown or older than AGY_UA_MIN_VERSION. */
4132
+ const AGY_UA_FALLBACK_VERSION = "1.5.10";
4133
+ function semverAtLeast(candidate, floor) {
4134
+ if (!candidate) return false;
4135
+ const a = candidate.match(/^(\d+)\.(\d+)\.(\d+)$/);
4136
+ const b = floor.match(/^(\d+)\.(\d+)\.(\d+)$/);
4137
+ if (!a || !b) return false;
4138
+ for (let i = 1; i <= 3; i += 1) {
4139
+ const x = Number(a[i]);
4140
+ const y = Number(b[i]);
4141
+ if (x !== y) return x > y;
4142
+ }
4143
+ return true;
4144
+ }
4145
+ /** Platform-faithful agy User-Agent (hardcoding darwin/arm64 on Windows is a bad fingerprint). */
4146
+ function agyUserAgent(version) {
4147
+ const os = process.platform === "win32" ? "windows" : process.platform;
4148
+ const arch = process.arch === "x64" ? "amd64" : process.arch;
4149
+ return `antigravity/cli/${semverAtLeast(version, "1.3.0") ? version : AGY_UA_FALLBACK_VERSION} (aidev_client; os_type=${os}; arch=${arch}; auth_method=consumer)`;
4150
+ }
4151
+ //#endregion
3920
4152
  //#region src/common/reasoning.ts
3921
4153
  /** Every effort id agy accepts, in ascending intensity order. */
3922
4154
  const REASONING_EFFORTS = [
@@ -3991,11 +4223,21 @@ function normalizeEfforts(list) {
3991
4223
  return [...known, ...unknown];
3992
4224
  }
3993
4225
  //#endregion
3994
- //#region src/host/models.ts
3995
- /** Check whether any enabled account in the pool has confirmed access to Argon. */
3996
- function poolHasArgon(pool, catalog) {
3997
- if (!pool) return false;
3998
- return pool.getAccounts().filter((a) => a.enabled).some((acc) => accountHasArgon(acc, pool, catalog?.get(acc.id)));
4226
+ //#region src/domain/models/parse.ts
4227
+ /**
4228
+ * True when `agy models` exited 0 only because it printed an unauthenticated
4229
+ * static fallback list while warning on stderr/stdout (#122).
4230
+ */
4231
+ function isUnauthenticatedModelsFallback(stdout, stderr) {
4232
+ return /please sign in|not signed in|not logged in|authentication required|silent auth failed|auth mode is unspecified/i.test(stderr + "\n" + stdout);
4233
+ }
4234
+ function sameCatalogEntry(a, b) {
4235
+ if (!b || a.id !== b.id || a.name !== b.name) return false;
4236
+ const ea = a.efforts ?? null;
4237
+ const eb = b.efforts ?? null;
4238
+ if (ea === eb) return true;
4239
+ if (!ea || !eb || ea.length !== eb.length) return false;
4240
+ return ea.every((v, idx) => v === eb[idx]);
3999
4241
  }
4000
4242
  /** Parse `agy models` stdout: JSON shapes first, then two-column text. */
4001
4243
  function parseModelsOutput(stdout) {
@@ -4021,7 +4263,6 @@ function parseModelsOutput(stdout) {
4021
4263
  }
4022
4264
  return dedupeBySlug(out);
4023
4265
  }
4024
- /** First occurrence wins: duplicate raw slugs would become duplicate catalog ids. */
4025
4266
  function dedupeBySlug(raw) {
4026
4267
  const seen = /* @__PURE__ */ new Set();
4027
4268
  const out = [];
@@ -4073,16 +4314,7 @@ function extractModelList(parsed) {
4073
4314
  }
4074
4315
  return out;
4075
4316
  }
4076
- /** Fold Gemini/Argon/Claude effort variants into base + effort set (spec ADR-10).
4077
- * Claude 5.5 is listed only as tiered slugs by agy 1.5.3; the base slug is the
4078
- * one that accepts `--effort`, and passing a tiered slug together with the flag
4079
- * is rejected ("--model … conflicts with --effort=…").
4080
- *
4081
- * The effort vocabulary itself (including agy 1.5.7's `xhigh`, which its picker
4082
- * labels "Extra") comes from `common/reasoning.ts` — folding must never carry
4083
- * its own copy of the list, or a new level silently becomes a bogus MODEL:
4084
- * a missed `xhigh` used to surface `gemini-4-hydrogen-xhigh` next to
4085
- * `gemini-4-hydrogen` in DSH's picker. */
4317
+ /** Fold Gemini/Argon/Claude effort variants into base + effort set (spec ADR-10). */
4086
4318
  function foldEfforts(raw) {
4087
4319
  const bases = /* @__PURE__ */ new Map();
4088
4320
  const verbatim = [];
@@ -4146,12 +4378,6 @@ function buildFallbackCatalog(defs) {
4146
4378
  efforts: Array.isArray(d.efforts) && d.efforts.length > 0 ? d.efforts.filter((e) => typeof e === "string" && e.trim() !== "") : null
4147
4379
  }));
4148
4380
  }
4149
- /**
4150
- * Sanitized (id, name) projection of a catalog: trimmed non-empty ids with
4151
- * first occurrence winning — exactly what listModels serves to DSH. Shared
4152
- * with the settings UI's model-visibility list so the picker and the UI can
4153
- * never disagree about which models exist.
4154
- */
4155
4381
  function sanitizeCatalogEntries(models) {
4156
4382
  const seen = /* @__PURE__ */ new Set();
4157
4383
  const entries = [];
@@ -4177,44 +4403,133 @@ function sanitizeCatalogEntries(models) {
4177
4403
  dropped
4178
4404
  };
4179
4405
  }
4406
+ function resolveModelSlug(id) {
4407
+ const s = id.trim().toLowerCase();
4408
+ if (s === "claude-opus") return PREFERRED_CLAUDE_OPUS;
4409
+ if (s === "claude-sonnet") return PREFERRED_CLAUDE;
4410
+ if (s === "claude-opus-4-6" || s === "claude-opus-4-8" || s === "claude-opus-4.6" || s === "claude-opus-4-5") return "claude-opus-4-6-thinking";
4411
+ if (s === "claude-sonnet-4.6" || s === "claude-sonnet-4-5") return "claude-sonnet-4-6";
4412
+ if (s === "gpt-oss-120b" || s === "gpt-oss-20b" || s === "gpt-oss") return PREFERRED_OPENAI;
4413
+ const claude55 = s.match(/^(claude-(?:sonnet|opus)-5-5)-(?:low|medium|high)$/);
4414
+ if (claude55 !== null && claude55[1] !== void 0) return claude55[1];
4415
+ return id.trim();
4416
+ }
4417
+ function findEntry(catalog, id) {
4418
+ const direct = catalog.models.find((m) => m.id === id);
4419
+ if (direct) return direct;
4420
+ const resolved = resolveModelSlug(id);
4421
+ if (resolved !== id) return catalog.models.find((m) => m.id === resolved);
4422
+ }
4423
+ function defaultEffortFor(entry, cfg) {
4424
+ if (!entry.efforts || entry.efforts.length === 0) return void 0;
4425
+ if (cfg.defaultEffort !== "" && entry.efforts.includes(cfg.defaultEffort)) return cfg.defaultEffort;
4426
+ for (const pref of [
4427
+ "high",
4428
+ "medium",
4429
+ "low"
4430
+ ]) if (entry.efforts.includes(pref)) return pref;
4431
+ return entry.efforts[entry.efforts.length - 1];
4432
+ }
4433
+ //#endregion
4434
+ //#region src/host/models.ts
4435
+ /** Check whether any enabled account in the pool has confirmed access to Argon. */
4436
+ function poolHasArgon(pool, catalog) {
4437
+ if (!pool) return false;
4438
+ return pool.getAccounts().filter((a) => a.enabled).some((acc) => accountHasArgon(acc, pool, catalog?.getAccountCatalog(acc.id)));
4439
+ }
4180
4440
  var ModelCatalog = class ModelCatalog {
4181
4441
  discover;
4182
4442
  fallbackDefs;
4183
4443
  ttlMs;
4184
4444
  onUpdate;
4445
+ options;
4185
4446
  current;
4186
4447
  accountCatalogs = /* @__PURE__ */ new Map();
4187
- refreshing = null;
4188
- /**
4189
- * While the catalog is still on the fallback source, re-probe at most once
4190
- * per this interval: `agy models` costs a 30s-capped spawn, and with the
4191
- * user signed out EVERY listModels call (picker open, resolveModel, stream)
4192
- * used to trigger one — a spawn storm that never converged.
4193
- */
4448
+ refreshingByKey = /* @__PURE__ */ new Map();
4194
4449
  static FALLBACK_RETRY_MS = 6e4;
4195
4450
  lastAttemptAt = 0;
4196
- /**
4197
- * Per-account probe timestamps. `refreshIfNeeded(accountId)` used to skip
4198
- * the throttle whenever the account had no catalog yet, so a signed-out /
4199
- * expired account could be probed on EVERY listModels() read (issue #106).
4200
- */
4201
4451
  accountAttemptAt = /* @__PURE__ */ new Map();
4202
- constructor(discover, fallbackDefs, ttlMs, onUpdate) {
4452
+ persistedAgyVersion = null;
4453
+ constructor(discover, fallbackDefs, ttlMs, onUpdate, options = {}) {
4203
4454
  this.discover = discover;
4204
4455
  this.fallbackDefs = fallbackDefs;
4205
4456
  this.ttlMs = ttlMs;
4206
4457
  this.onUpdate = onUpdate;
4458
+ this.options = options;
4207
4459
  this.current = {
4208
4460
  source: "fallback",
4209
4461
  models: buildFallbackCatalog(fallbackDefs),
4210
4462
  discoveredAt: 0
4211
4463
  };
4464
+ this.hydrateFromDisk();
4465
+ }
4466
+ sanitizePersisted(cat) {
4467
+ if (!cat || cat.source !== "discovered" || !Array.isArray(cat.models)) return null;
4468
+ const rawEntries = sanitizeCatalogEntries(cat.models).entries;
4469
+ if (rawEntries.length === 0) return null;
4470
+ return {
4471
+ source: "discovered",
4472
+ models: rawEntries.map((e) => ({
4473
+ id: e.id,
4474
+ name: e.name,
4475
+ efforts: e.efforts.length === 0 ? null : e.efforts
4476
+ })),
4477
+ discoveredAt: typeof cat.discoveredAt === "number" && Number.isFinite(cat.discoveredAt) ? cat.discoveredAt : 0
4478
+ };
4479
+ }
4480
+ hydrateFromDisk() {
4481
+ const file = this.options.cacheFile;
4482
+ if (!file || !existsSync(file)) return;
4483
+ try {
4484
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
4485
+ if (!parsed || parsed.version !== 1) return;
4486
+ const liveVer = this.options.agyVersion?.() ?? null;
4487
+ if (liveVer && parsed.agyVersion && parsed.agyVersion !== liveVer) return;
4488
+ this.persistedAgyVersion = parsed.agyVersion ?? null;
4489
+ const cur = this.sanitizePersisted(parsed.current);
4490
+ if (cur) this.current = cur;
4491
+ if (parsed.accounts && typeof parsed.accounts === "object") for (const [accId, rawCat] of Object.entries(parsed.accounts)) {
4492
+ const valid = this.sanitizePersisted(rawCat);
4493
+ if (valid) this.accountCatalogs.set(accId, valid);
4494
+ }
4495
+ } catch {}
4496
+ }
4497
+ persistToDisk() {
4498
+ const file = this.options.cacheFile;
4499
+ if (!file) return;
4500
+ try {
4501
+ const accounts = {};
4502
+ for (const [accId, cat] of this.accountCatalogs.entries()) if (cat.source === "discovered" && cat.models.length > 0) accounts[accId] = cat;
4503
+ const liveVer = this.options.agyVersion?.() ?? this.persistedAgyVersion;
4504
+ this.persistedAgyVersion = liveVer;
4505
+ const doc = {
4506
+ version: 1,
4507
+ agyVersion: liveVer,
4508
+ ...this.current.source === "discovered" ? { current: this.current } : {},
4509
+ accounts
4510
+ };
4511
+ writeFileAtomicSync(file, JSON.stringify(doc, null, 2), 384);
4512
+ } catch {}
4513
+ }
4514
+ /** Invalidate cached entries if `agy --version` reveals a binary upgrade after boot. */
4515
+ syncAgyVersion(liveVersion) {
4516
+ if (!liveVersion) return;
4517
+ if (this.persistedAgyVersion && this.persistedAgyVersion !== liveVersion) {
4518
+ this.accountCatalogs.clear();
4519
+ this.current = {
4520
+ source: "fallback",
4521
+ models: buildFallbackCatalog(this.fallbackDefs),
4522
+ discoveredAt: 0
4523
+ };
4524
+ this.persistedAgyVersion = liveVersion;
4525
+ this.persistToDisk();
4526
+ return;
4527
+ }
4528
+ if (this.persistedAgyVersion !== liveVersion) {
4529
+ this.persistedAgyVersion = liveVersion;
4530
+ if (this.current.source === "discovered" || this.accountCatalogs.size > 0) this.persistToDisk();
4531
+ }
4212
4532
  }
4213
- /**
4214
- * Return the deduplicated set of all real models discovered from `agy models`
4215
- * across base and per-account catalogs. Quotas are never treated as models,
4216
- * and fallback definitions are only used when discovery failed everywhere.
4217
- */
4218
4533
  getAllKnownModels(accounts = []) {
4219
4534
  const list = [];
4220
4535
  const seen = /* @__PURE__ */ new Set();
@@ -4234,53 +4549,43 @@ var ModelCatalog = class ModelCatalog {
4234
4549
  if (list.length === 0) addEntries(buildFallbackCatalog(this.fallbackDefs));
4235
4550
  return list;
4236
4551
  }
4237
- /**
4238
- * Return the union of all models available across all pool accounts,
4239
- * without Argon if no enabled account in the pool has Argon access.
4240
- */
4241
4552
  getUnion(accounts = [], pool) {
4242
4553
  if (accounts.length === 0 && !pool) return this.current.models;
4243
4554
  const all = this.getAllKnownModels(accounts);
4244
- const hasAnyArgon = pool ? poolHasArgon(pool, this) : accounts.some((a) => accountHasArgon(a, pool, this.get(a.id)));
4245
- return all.filter((entry) => {
4246
- if (isArgonModel(entry.id) && !hasAnyArgon) return false;
4247
- return true;
4248
- });
4555
+ const hasAnyArgon = pool ? poolHasArgon(pool, this) : accounts.some((a) => accountHasArgon(a, pool, this.getAccountCatalog(a.id)));
4556
+ return all.filter((entry) => !(isArgonModel(entry.id) && !hasAnyArgon));
4249
4557
  }
4250
- /**
4251
- * Return the authoritative real models for a specific managed account.
4252
- * If the account's catalog was discovered from `agy models`, returns its models directly.
4253
- * If not yet discovered, uses current discovered models filtered by account capabilities.
4254
- */
4255
4558
  getModelsForAccount(acc, pool) {
4256
4559
  const accountCat = this.accountCatalogs.get(acc.id);
4257
4560
  if (accountCat && accountCat.source === "discovered" && accountCat.models.length > 0) return accountCat.models;
4258
4561
  const hasArgon = accountHasArgon(acc, pool, this.current);
4259
- if (this.current.source === "discovered" && this.current.models.length > 0) return this.current.models.filter((m) => {
4260
- if (isArgonModel(m.id) && !hasArgon) return false;
4261
- return true;
4262
- });
4263
- return buildFallbackCatalog(this.fallbackDefs).filter((m) => {
4264
- if (isArgonModel(m.id) && !hasArgon) return false;
4265
- return true;
4266
- });
4562
+ if (this.current.source === "discovered" && this.current.models.length > 0) {
4563
+ const filtered = this.current.models.filter((m) => !(isArgonModel(m.id) && !hasArgon));
4564
+ if (hasArgon && !filtered.some((m) => isArgonModel(m.id))) {
4565
+ const argonCandidates = [...[...this.accountCatalogs.values()].filter((c) => c.source === "discovered").flatMap((c) => c.models), ...buildFallbackCatalog(this.fallbackDefs)].filter((m) => isArgonModel(m.id));
4566
+ const seen = new Set(filtered.map((m) => m.id));
4567
+ const extra = [];
4568
+ for (const m of argonCandidates) if (!seen.has(m.id)) {
4569
+ seen.add(m.id);
4570
+ extra.push(m);
4571
+ }
4572
+ if (extra.length > 0) return [...extra, ...filtered];
4573
+ }
4574
+ return filtered;
4575
+ }
4576
+ return buildFallbackCatalog(this.fallbackDefs).filter((m) => !(isArgonModel(m.id) && !hasArgon));
4267
4577
  }
4268
4578
  get(accountId) {
4269
4579
  if (accountId && this.accountCatalogs.has(accountId)) return this.accountCatalogs.get(accountId);
4270
4580
  return this.current;
4271
4581
  }
4582
+ /** Return ONLY this account's own discovered catalog (never `this.current`). */
4583
+ getAccountCatalog(accountId) {
4584
+ return accountId ? this.accountCatalogs.get(accountId) : void 0;
4585
+ }
4272
4586
  hasAccountCatalog(accountId) {
4273
4587
  return this.accountCatalogs.has(accountId);
4274
4588
  }
4275
- /**
4276
- * Effort ids the LIVE DISCOVERED catalog advertises for one model (across the
4277
- * base catalog and every per-account catalog). Fallback entries are excluded:
4278
- * they are a static mirror, not proof about the installed agy build.
4279
- *
4280
- * Used to reject false "--effort is not supported" refusals: agy's print-mode
4281
- * validation emits that text when its model-config fetch fails, even though
4282
- * `agy models` lists the level (issue #115).
4283
- */
4284
4589
  advertisedEfforts(modelId) {
4285
4590
  const out = /* @__PURE__ */ new Set();
4286
4591
  for (const cat of [this.current, ...this.accountCatalogs.values()]) {
@@ -4292,35 +4597,31 @@ var ModelCatalog = class ModelCatalog {
4292
4597
  }
4293
4598
  return [...out];
4294
4599
  }
4295
- /** Refresh if stale; never throws — failures keep the previous catalog. */
4296
4600
  async refreshIfNeeded(accountId) {
4297
- if (this.refreshing) return this.refreshing;
4601
+ const key = accountId ?? "__default__";
4602
+ const inFlight = this.refreshingByKey.get(key);
4603
+ if (inFlight) return inFlight;
4298
4604
  const now = Date.now();
4299
4605
  const accountCat = accountId ? this.accountCatalogs.get(accountId) : void 0;
4300
4606
  if (!accountId || accountCat) {
4301
4607
  const targetCat = accountCat ?? this.current;
4302
4608
  const age = now - targetCat.discoveredAt;
4303
4609
  if (targetCat.source === "discovered" && age < this.ttlMs) return;
4304
- if (targetCat.source === "fallback" && now - this.lastAttemptAt < ModelCatalog.FALLBACK_RETRY_MS) return;
4610
+ const last = accountId ? this.accountAttemptAt.get(accountId) ?? 0 : this.lastAttemptAt;
4611
+ if (targetCat.source === "fallback" && now - last < ModelCatalog.FALLBACK_RETRY_MS) return;
4612
+ if (accountId) this.accountAttemptAt.set(accountId, now);
4613
+ else this.lastAttemptAt = now;
4305
4614
  } else {
4306
4615
  if (now - (this.accountAttemptAt.get(accountId) ?? 0) < ModelCatalog.FALLBACK_RETRY_MS) return;
4307
4616
  this.accountAttemptAt.set(accountId, now);
4308
4617
  }
4309
- this.lastAttemptAt = now;
4310
- this.refreshing = this.refresh(accountId).finally(() => {
4311
- this.refreshing = null;
4618
+ if (!accountId) this.lastAttemptAt = now;
4619
+ const job = this.refresh(accountId).finally(() => {
4620
+ if (this.refreshingByKey.get(key) === job) this.refreshingByKey.delete(key);
4312
4621
  });
4313
- return this.refreshing;
4622
+ this.refreshingByKey.set(key, job);
4623
+ return job;
4314
4624
  }
4315
- /**
4316
- * Read-path discovery for one account (listModels). Unlike
4317
- * `forceRefreshAndNotify()` this is throttled and NEVER broadcasts on a
4318
- * failed probe: an unconditional `adapters-updated` made DSH's browser
4319
- * re-read the catalog, which called listModels() again — a self-exciting
4320
- * 1:1 read/probe/announce loop while signed out (issue #106). `refresh()`
4321
- * itself announces only when the catalog contents actually changed, so a
4322
- * successful first build still updates the picker exactly once.
4323
- */
4324
4625
  async ensureAccountCatalog(accountId) {
4325
4626
  if (!accountId || this.accountCatalogs.has(accountId)) return this.get(accountId);
4326
4627
  await this.refreshIfNeeded(accountId);
@@ -4330,19 +4631,6 @@ var ModelCatalog = class ModelCatalog {
4330
4631
  await this.refresh(accountId);
4331
4632
  return this.get(accountId);
4332
4633
  }
4333
- /**
4334
- * Refresh one account's catalog, then ALWAYS announce a picker update.
4335
- *
4336
- * `refresh()` only fires onUpdate when the catalog *contents* changed. But
4337
- * switching the active account changes the picker's visible set even when
4338
- * the catalog itself is identical — `listModels()` filters the Argon family
4339
- * by the active account's plan, and it resolves `catalog.get(accountId)`,
4340
- * which must be populated for the newly active account before the picker
4341
- * re-reads. So an account switch must (a) discover that account's catalog and
4342
- * (b) emit the update unconditionally, or the composer's cached model
4343
- * snapshot keeps showing the previous account's models (e.g. no Argon after
4344
- * switching to a Pro/Ultra account).
4345
- */
4346
4634
  async forceRefreshAndNotify(accountId) {
4347
4635
  const hadCatalog = accountId ? this.hasAccountCatalog(accountId) : true;
4348
4636
  await this.refresh(accountId, false);
@@ -4350,13 +4638,19 @@ var ModelCatalog = class ModelCatalog {
4350
4638
  if (hadCatalog || hasCatalog) this.onUpdate?.();
4351
4639
  return this.get(accountId);
4352
4640
  }
4353
- /**
4354
- * Warm account catalogs in the background so switching between accounts is instant.
4355
- */
4356
4641
  async warmAccounts(accounts) {
4357
- for (const acc of accounts) {
4358
- if (!acc.enabled || acc.authRequired) continue;
4359
- if (!this.accountCatalogs.has(acc.id)) await this.refresh(acc.id, false).catch(() => void 0);
4642
+ const now = Date.now();
4643
+ const due = accounts.filter((acc) => {
4644
+ if (!acc.enabled || acc.authRequired) return false;
4645
+ const cached = this.accountCatalogs.get(acc.id);
4646
+ return !(cached && cached.source === "discovered" && now - cached.discoveredAt < this.ttlMs);
4647
+ });
4648
+ for (let i = 0; i < due.length; i++) {
4649
+ await this.refresh(due[i].id, false).catch(() => void 0);
4650
+ if (i < due.length - 1) {
4651
+ const delay = this.options.staggerMs?.() ?? (process.env.NODE_TEST_CONTEXT !== void 0 ? 0 : staggerJitterMs());
4652
+ if (delay > 0) await new Promise((r) => setTimeout(r, delay));
4653
+ }
4360
4654
  }
4361
4655
  }
4362
4656
  async refresh(accountId, announce = true) {
@@ -4364,7 +4658,18 @@ var ModelCatalog = class ModelCatalog {
4364
4658
  const ac = new AbortController();
4365
4659
  const timer = setTimeout(() => ac.abort(), 3e4);
4366
4660
  try {
4367
- const { stdout } = await this.discover(ac.signal, accountId);
4661
+ const { stdout, stderr } = await this.discover(ac.signal, accountId);
4662
+ if (isUnauthenticatedModelsFallback(stdout, stderr)) {
4663
+ const msg = "agy models returned unauthenticated fallback output";
4664
+ if (accountId) {
4665
+ const cat = this.accountCatalogs.get(accountId);
4666
+ if (cat) cat.lastError = msg;
4667
+ } else this.current = {
4668
+ ...this.current,
4669
+ lastError: msg
4670
+ };
4671
+ return;
4672
+ }
4368
4673
  const raw = parseModelsOutput(stdout);
4369
4674
  if (raw.length > 0) {
4370
4675
  const newModels = foldEfforts(raw);
@@ -4373,12 +4678,17 @@ var ModelCatalog = class ModelCatalog {
4373
4678
  models: newModels,
4374
4679
  discoveredAt: Date.now()
4375
4680
  };
4376
- const prev = this.get(accountId);
4377
- const changed = prev.source !== "discovered" || prev.models.length !== newModels.length || prev.models.some((m, i) => m.id !== newModels[i]?.id);
4681
+ const prev = accountId ? this.accountCatalogs.get(accountId) ?? {
4682
+ source: "fallback",
4683
+ models: [],
4684
+ discoveredAt: 0
4685
+ } : this.current;
4686
+ const changed = prev.source !== "discovered" || prev.models.length !== newModels.length || prev.models.some((m, i) => !sameCatalogEntry(m, newModels[i]));
4378
4687
  if (accountId) {
4379
4688
  this.accountCatalogs.set(accountId, newCatalog);
4380
4689
  if (this.current.source !== "discovered") this.current = newCatalog;
4381
4690
  } else this.current = newCatalog;
4691
+ this.persistToDisk();
4382
4692
  if (changed && announce) this.onUpdate?.();
4383
4693
  return;
4384
4694
  }
@@ -4404,33 +4714,6 @@ var ModelCatalog = class ModelCatalog {
4404
4714
  }
4405
4715
  }
4406
4716
  };
4407
- function resolveModelSlug(id) {
4408
- const s = id.trim().toLowerCase();
4409
- if (s === "claude-opus") return PREFERRED_CLAUDE_OPUS;
4410
- if (s === "claude-sonnet") return PREFERRED_CLAUDE;
4411
- if (s === "claude-opus-4-6" || s === "claude-opus-4-8" || s === "claude-opus-4.6" || s === "claude-opus-4-5") return "claude-opus-4-6-thinking";
4412
- if (s === "claude-sonnet-4.6" || s === "claude-sonnet-4-5") return "claude-sonnet-4-6";
4413
- if (s === "gpt-oss-120b" || s === "gpt-oss-20b" || s === "gpt-oss") return PREFERRED_OPENAI;
4414
- const claude55 = s.match(/^(claude-(?:sonnet|opus)-5-5)-(?:low|medium|high)$/);
4415
- if (claude55 !== null && claude55[1] !== void 0) return claude55[1];
4416
- return id.trim();
4417
- }
4418
- function findEntry(catalog, id) {
4419
- const direct = catalog.models.find((m) => m.id === id);
4420
- if (direct) return direct;
4421
- const resolved = resolveModelSlug(id);
4422
- if (resolved !== id) return catalog.models.find((m) => m.id === resolved);
4423
- }
4424
- function defaultEffortFor(entry, cfg) {
4425
- if (!entry.efforts || entry.efforts.length === 0) return void 0;
4426
- if (cfg.defaultEffort !== "" && entry.efforts.includes(cfg.defaultEffort)) return cfg.defaultEffort;
4427
- for (const pref of [
4428
- "high",
4429
- "medium",
4430
- "low"
4431
- ]) if (entry.efforts.includes(pref)) return pref;
4432
- return entry.efforts[entry.efforts.length - 1];
4433
- }
4434
4717
  //#endregion
4435
4718
  //#region src/provider/model-resolution.ts
4436
4719
  function activeAccount(deps) {
@@ -4904,13 +5187,6 @@ function nodeScriptEnv(env) {
4904
5187
  * own idle budget so short-budget tests and genuine idle kills stay prompt.
4905
5188
  */
4906
5189
  const WATCHDOG_GRACE_MS = 5e3;
4907
- /**
4908
- * Grace after agy reports `root agent idle; waiting ... for background task(s)`.
4909
- * The prompt turn's answer is already streamed; a stuck GUI dialog / background
4910
- * child would otherwise keep print mode alive for hours (issue #119). Short and
4911
- * fixed so the turn settles promptly instead of hanging DSH's event stream.
4912
- */
4913
- const IDLE_BACKGROUND_GRACE_MS = 5e3;
4914
5190
  //#endregion
4915
5191
  //#region src/host/auto-updater.ts
4916
5192
  function nonBlank(v) {
@@ -5074,7 +5350,9 @@ function createRunState(opts) {
5074
5350
  watchdogGraceUsed: false,
5075
5351
  turnCap: null,
5076
5352
  idleGraceTimer: null,
5077
- idleGraceTerminated: false
5353
+ idleGraceTerminated: false,
5354
+ idleGraceExempt: false,
5355
+ idleObserved: false
5078
5356
  };
5079
5357
  }
5080
5358
  function spawnAgyChild(opts, env, viaCmd, isNode) {
@@ -5161,11 +5439,44 @@ function armTurnCap(child, opts, state) {
5161
5439
  function isBackgroundStderrNoise(line) {
5162
5440
  return line.includes("fetchAvailableModels") || line.includes("loadCodeAssist") || line.includes("token refreshed") || line.includes("FetchConfig") || line.includes("ListExperiments") || line.includes("daily-cloudcode-pa.googleapis.com") || line.includes("http_helpers.go");
5163
5441
  }
5442
+ function clearIdleGrace(state) {
5443
+ if (state.idleGraceTimer !== null) {
5444
+ clearTimeout(state.idleGraceTimer);
5445
+ state.idleGraceTimer = null;
5446
+ }
5447
+ }
5448
+ /**
5449
+ * Arm the idle-grace reaper for a `root agent idle; waiting …` line.
5450
+ *
5451
+ * The reaper exists for genuinely orphaned background work (a dev server, a
5452
+ * blocked GUI dialog) that would otherwise keep print mode alive for hours
5453
+ * (#119). It must NOT fire while agy is legitimately waiting for a subagent to
5454
+ * wake the root agent — `exemptIdleGrace(true)` is how the attempt layer marks
5455
+ * that state (#124). When exempt, the check re-arms instead of killing, and the
5456
+ * normal activity watchdog / maxTurnMinutes still bound the wait.
5457
+ */
5458
+ function armIdleGrace(child, opts, state) {
5459
+ if (state.idleGraceTimer !== null || state.settled) return;
5460
+ const graceMs = opts.idleGraceMs ?? 5e3;
5461
+ state.idleGraceTimer = setTimeout(() => {
5462
+ state.idleGraceTimer = null;
5463
+ if (state.settled) return;
5464
+ if (state.idleGraceExempt) {
5465
+ armIdleGrace(child, opts, state);
5466
+ return;
5467
+ }
5468
+ state.idleGraceTerminated = true;
5469
+ killTree(child);
5470
+ }, graceMs);
5471
+ state.idleGraceTimer.unref?.();
5472
+ }
5164
5473
  function attachOutputStreams(child, opts, state, refreshWatchdog) {
5165
5474
  const stdoutDecoder = makeLineDecoder(consoleOutputEncoding());
5166
5475
  const stderrDecoder = makeLineDecoder(consoleOutputEncoding());
5167
5476
  child.stdout?.on("data", (chunk) => {
5168
5477
  refreshWatchdog();
5478
+ clearIdleGrace(state);
5479
+ state.idleObserved = false;
5169
5480
  const text = stdoutDecoder.push(chunk);
5170
5481
  if (text === "") return;
5171
5482
  state.stdout += text;
@@ -5183,15 +5494,8 @@ function attachOutputStreams(child, opts, state, refreshWatchdog) {
5183
5494
  if (text !== "") {
5184
5495
  state.stderr = (state.stderr + text).slice(-4096);
5185
5496
  if (/root agent idle;\s*waiting/i.test(text)) {
5186
- if (!state.idleGraceTimer) {
5187
- state.idleGraceTimer = setTimeout(() => {
5188
- if (!state.settled) {
5189
- state.idleGraceTerminated = true;
5190
- killTree(child);
5191
- }
5192
- }, IDLE_BACKGROUND_GRACE_MS);
5193
- state.idleGraceTimer.unref?.();
5194
- }
5497
+ state.idleObserved = true;
5498
+ armIdleGrace(child, opts, state);
5195
5499
  } else if (opts.stderrKeepalive && !isBackgroundStderrNoise(text)) refreshWatchdog();
5196
5500
  }
5197
5501
  });
@@ -5264,6 +5568,11 @@ function startAgyProcess(opts) {
5264
5568
  if (budgetMs !== void 0) state.idleBudgetMs = budgetMs;
5265
5569
  refreshWatchdog();
5266
5570
  },
5571
+ exemptIdleGrace: (exempt) => {
5572
+ state.idleGraceExempt = exempt;
5573
+ if (exempt) clearIdleGrace(state);
5574
+ else if (state.idleObserved) armIdleGrace(child, opts, state);
5575
+ },
5267
5576
  kill: (reason) => {
5268
5577
  if (reason === "timeout") state.timedOut = true;
5269
5578
  else state.aborted = true;
@@ -5707,27 +6016,6 @@ async function deliverContext(digest, sessionKey, extraAddDirs, cfg) {
5707
6016
  return digest;
5708
6017
  }
5709
6018
  //#endregion
5710
- //#region src/common/atomic-write.ts
5711
- let seq = 0;
5712
- /** Unique temp path beside `file` (same directory, so rename stays atomic). */
5713
- function atomicTmpPath(file) {
5714
- const rand = Math.random().toString(36).slice(2, 8);
5715
- return file + "." + process.pid + "." + (seq++).toString(36) + "." + rand + ".tmp";
5716
- }
5717
- /** Write `data` to `file` atomically; on any failure remove the temp file. */
5718
- function writeFileAtomicSync(file, data) {
5719
- const tmp = atomicTmpPath(file);
5720
- try {
5721
- writeFileSync(tmp, data, "utf8");
5722
- renameSync(tmp, file);
5723
- } catch (err) {
5724
- try {
5725
- if (existsSync(tmp)) unlinkSync(tmp);
5726
- } catch {}
5727
- throw err;
5728
- }
5729
- }
5730
- //#endregion
5731
6019
  //#region src/host/sessions.ts
5732
6020
  var SessionStore = class {
5733
6021
  file;
@@ -5736,18 +6024,55 @@ var SessionStore = class {
5736
6024
  dirty = /* @__PURE__ */ new Set();
5737
6025
  /** Keys deleted by THIS process since the last persist. */
5738
6026
  removed = /* @__PURE__ */ new Set();
6027
+ lastMtimeMs = 0;
5739
6028
  constructor(file) {
5740
6029
  this.file = file;
5741
6030
  this.load();
5742
6031
  }
6032
+ readParsed(target) {
6033
+ try {
6034
+ if (!existsSync(target)) return null;
6035
+ const v = JSON.parse(readFileSync(target, "utf8"));
6036
+ if (v && typeof v === "object" && !Array.isArray(v)) return v;
6037
+ } catch {}
6038
+ return null;
6039
+ }
6040
+ updateStatMtime() {
6041
+ try {
6042
+ this.lastMtimeMs = existsSync(this.file) ? statSync(this.file).mtimeMs : 0;
6043
+ } catch {
6044
+ this.lastMtimeMs = 0;
6045
+ }
6046
+ }
5743
6047
  load() {
6048
+ const primary = this.readParsed(this.file);
6049
+ if (primary !== null) {
6050
+ this.data = primary;
6051
+ this.updateStatMtime();
6052
+ return;
6053
+ }
6054
+ const backup = this.readParsed(this.file + ".last-good");
6055
+ if (backup !== null) this.data = backup;
6056
+ this.updateStatMtime();
6057
+ }
6058
+ /** Lazily merge bindings written by another host process when mtime advances. */
6059
+ reloadIfChanged() {
5744
6060
  try {
5745
6061
  if (!existsSync(this.file)) return;
5746
- const v = JSON.parse(readFileSync(this.file, "utf8"));
5747
- if (v && typeof v === "object") this.data = v;
6062
+ const mtime = statSync(this.file).mtimeMs;
6063
+ if (mtime === this.lastMtimeMs) return;
6064
+ const onDisk = this.readParsed(this.file);
6065
+ this.lastMtimeMs = mtime;
6066
+ if (!onDisk) return;
6067
+ for (const [k, diskVal] of Object.entries(onDisk)) {
6068
+ if (this.removed.has(k) || this.dirty.has(k)) continue;
6069
+ const cur = this.data[k];
6070
+ if (!cur || (diskVal?.updatedAt ?? 0) >= (cur.updatedAt ?? 0)) this.data[k] = diskVal;
6071
+ }
5748
6072
  } catch {}
5749
6073
  }
5750
6074
  get(key) {
6075
+ this.reloadIfChanged();
5751
6076
  return this.data[key];
5752
6077
  }
5753
6078
  set(key, b) {
@@ -5763,15 +6088,44 @@ var SessionStore = class {
5763
6088
  this.persist();
5764
6089
  }
5765
6090
  clear() {
6091
+ this.reloadIfChanged();
5766
6092
  for (const key of Object.keys(this.data)) this.removed.add(key);
5767
6093
  this.data = {};
5768
6094
  this.dirty.clear();
5769
6095
  this.persist();
5770
6096
  }
5771
6097
  all() {
6098
+ this.reloadIfChanged();
5772
6099
  return this.data;
5773
6100
  }
5774
6101
  /**
6102
+ * Prune bindings older than `cutoffMs` and cap total entries at `maxEntries`
6103
+ * (keeping newest `updatedAt` first) so `sessions.json` never grows unboundedly.
6104
+ */
6105
+ pruneStaleBindings(cutoffMs = Date.now() - 2592e6, maxEntries = 2e3) {
6106
+ this.reloadIfChanged();
6107
+ let pruned = 0;
6108
+ for (const [key, b] of Object.entries(this.data)) if ((b?.updatedAt ?? 0) < cutoffMs) {
6109
+ delete this.data[key];
6110
+ this.dirty.delete(key);
6111
+ this.removed.add(key);
6112
+ pruned++;
6113
+ }
6114
+ const entries = Object.entries(this.data);
6115
+ if (entries.length > maxEntries) {
6116
+ entries.sort((a, b) => (b[1]?.updatedAt ?? 0) - (a[1]?.updatedAt ?? 0));
6117
+ for (let i = maxEntries; i < entries.length; i++) {
6118
+ const key = entries[i][0];
6119
+ delete this.data[key];
6120
+ this.dirty.delete(key);
6121
+ this.removed.add(key);
6122
+ pruned++;
6123
+ }
6124
+ }
6125
+ if (pruned > 0) this.persist();
6126
+ return pruned;
6127
+ }
6128
+ /**
5775
6129
  * Purge bindings associated with accounts that no longer exist in the pool.
5776
6130
  * Prevents deleted account ids from lingering in sessions.json.
5777
6131
  */
@@ -5812,9 +6166,17 @@ var SessionStore = class {
5812
6166
  for (const key of this.removed) delete merged[key];
5813
6167
  for (const key of this.dirty) {
5814
6168
  const b = this.data[key];
5815
- if (b !== void 0) merged[key] = b;
6169
+ if (b !== void 0) {
6170
+ const existing = merged[key];
6171
+ if (!existing || (b.updatedAt ?? 0) >= (existing.updatedAt ?? 0)) merged[key] = b;
6172
+ }
5816
6173
  }
5817
- writeFileAtomicSync(this.file, JSON.stringify(merged, null, 2));
6174
+ const body = JSON.stringify(merged, null, 2);
6175
+ writeFileAtomicSync(this.file, body);
6176
+ try {
6177
+ writeFileAtomicSync(this.file + ".last-good", body);
6178
+ } catch {}
6179
+ this.updateStatMtime();
5818
6180
  this.data = merged;
5819
6181
  this.dirty.clear();
5820
6182
  this.removed.clear();
@@ -5938,15 +6300,19 @@ function mergeSentImageIds(existing, added, max = 64) {
5938
6300
  }
5939
6301
  //#endregion
5940
6302
  //#region src/provider/account-selection.ts
5941
- /** Session affinity: reuse the account this session last ran on, if eligible. */
6303
+ /** Upper bound on the self-heal refresh so a slow network cannot stall a turn. */
6304
+ const MODEL_HEAL_TIMEOUT_MS = 2e4;
6305
+ /** Session affinity: reuse the account this session last ran on, if eligible and not superseded by a manual switch. */
5942
6306
  function stickyAccount(deps, family, sessionKey, model) {
5943
6307
  const pool = deps.pool;
5944
6308
  if (pool === void 0 || sessionKey === "") return void 0;
6309
+ const manualPinAt = pool.getPoolData().manualPinAt ?? 0;
5945
6310
  const prefix = `${sessionKey}:`;
5946
6311
  let mostRecent;
5947
6312
  let latestUpdated = -1;
5948
6313
  for (const [k, b] of Object.entries(deps.store.all())) {
5949
6314
  if (!k.startsWith(prefix) || b.updatedAt <= latestUpdated) continue;
6315
+ if (manualPinAt > 0 && b.updatedAt < manualPinAt) continue;
5950
6316
  const boundAcc = pool.getAccount(k.slice(prefix.length));
5951
6317
  if (boundAcc !== void 0) {
5952
6318
  mostRecent = boundAcc;
@@ -5986,6 +6352,28 @@ async function waitForShortReset(pool, family, model) {
5986
6352
  await new Promise((r) => setTimeout(r, countdown + 250));
5987
6353
  return pool.selectAccount(family, model) ?? void 0;
5988
6354
  }
6355
+ /**
6356
+ * One self-heal attempt for issue #125: if EVERY enabled account was denied
6357
+ * solely because the requested model is absent from its per-model snapshot,
6358
+ * refresh quotas and retry selection once. A truncated snapshot is the common
6359
+ * cause (the pool demonstrably served the model minutes earlier); a genuinely
6360
+ * unsupported model simply fails the retry and reports as before.
6361
+ */
6362
+ async function healStaleModelSnapshot(deps, pool, family, model) {
6363
+ const refresh = deps.refreshQuota;
6364
+ if (refresh === void 0 || model === "") return void 0;
6365
+ const enabled = pool.getAccounts().filter((a) => a.enabled);
6366
+ if (enabled.length === 0) return void 0;
6367
+ if (!enabled.map((a) => pool.explainIneligibility?.(a, family, Date.now(), model) ?? null).every((r) => r === "model-unsupported")) return void 0;
6368
+ try {
6369
+ await Promise.race([refresh(), new Promise((resolve) => {
6370
+ setTimeout(resolve, MODEL_HEAL_TIMEOUT_MS).unref?.();
6371
+ })]);
6372
+ } catch {
6373
+ return;
6374
+ }
6375
+ return pool.selectAccount(family, model) ?? void 0;
6376
+ }
5989
6377
  /** Build the "all accounts unavailable" error with the real reasons. */
5990
6378
  function unavailableError(pool, family, model) {
5991
6379
  const allAccounts = pool.getAccounts();
@@ -6025,7 +6413,10 @@ async function selectSessionAccount(input) {
6025
6413
  if (pool !== void 0 && !isAux && sessionKey !== "" && process.platform === "win32" && cfg.parallelSameAccount) account = pool.selectAccount(family, activeModel) ?? void 0;
6026
6414
  if (account === void 0 && pool !== void 0 && !isAux && sessionKey !== "") account = stickyAccount(deps, family, sessionKey, activeModel);
6027
6415
  if (account === void 0 && pool !== void 0) account = pool.selectAccount(family, activeModel) ?? void 0;
6028
- if (account !== void 0 && pool !== void 0 && pool.getPoolData().lastActiveAccountId !== account.id) pool.setActiveAccount(account.id, family);
6416
+ if (account !== void 0 && pool !== void 0 && pool.getPoolData().lastActiveAccountId !== account.id) {
6417
+ if (typeof pool.markAccountActive === "function") pool.markAccountActive(account.id);
6418
+ else pool.setActiveAccount(account.id, family);
6419
+ }
6029
6420
  if (account === void 0 && pool !== void 0 && pool.getAccounts().length > 0) {
6030
6421
  if (cfg.autoFallbackModel) {
6031
6422
  const fb = crossFamilyFallback(deps, family);
@@ -6037,6 +6428,7 @@ async function selectSessionAccount(input) {
6037
6428
  }
6038
6429
  }
6039
6430
  if (account === void 0) account = await waitForShortReset(pool, family, activeModel);
6431
+ if (account === void 0) account = await healStaleModelSnapshot(deps, pool, family, activeModel);
6040
6432
  if (account === void 0) throw unavailableError(pool, family, activeModel);
6041
6433
  }
6042
6434
  return {
@@ -6367,6 +6759,130 @@ async function stagePromptImages(input) {
6367
6759
  };
6368
6760
  }
6369
6761
  //#endregion
6762
+ //#region src/provider/tool-watchdog.ts
6763
+ /**
6764
+ * agy tools that hand work to a subagent and leave the ROOT agent idle until the
6765
+ * subagent reports back. While one of these is outstanding, the
6766
+ * `root agent idle; waiting …` line is normal cooperation, not an orphaned
6767
+ * background command (issue #124).
6768
+ */
6769
+ const SUBAGENT_COLLAB_TOOLS = /* @__PURE__ */ new Set([
6770
+ "invoke_subagent",
6771
+ "send_message",
6772
+ "run_workflow",
6773
+ "swarm"
6774
+ ]);
6775
+ function resolveWatchdogBudgets(cfg) {
6776
+ const longToolIdleMinutes = cfg.longToolIdleMinutes > 0 ? cfg.longToolIdleMinutes : 0;
6777
+ let printTimeoutMinutes = Math.max(longToolIdleMinutes > 0 ? longToolIdleMinutes : Math.ceil(cfg.timeoutMs / 6e4), Math.ceil(cfg.timeoutMs / 6e4));
6778
+ if (cfg.maxTurnMinutes > 0 && printTimeoutMinutes > cfg.maxTurnMinutes) printTimeoutMinutes = cfg.maxTurnMinutes;
6779
+ const longToolIdleMs = longToolIdleMinutes > 0 ? longToolIdleMinutes * 6e4 : cfg.timeoutMs;
6780
+ const generationIdleMs = Math.max(cfg.timeoutMs, 9e5);
6781
+ return {
6782
+ printTimeoutMinutes,
6783
+ longToolIdleMs,
6784
+ generationIdleMs
6785
+ };
6786
+ }
6787
+ function isStepFailedOrCanceled(ev) {
6788
+ return ev.state === "ERROR" || ev.state === "CANCELED" || ev.state === "CANCELLED" || ev.tool?.error !== void 0;
6789
+ }
6790
+ function isToolStepCompleted(ev) {
6791
+ return ev.state === "DONE" || ev.state === "ERROR" || ev.state === "CANCELED" || ev.state === "CANCELLED" || ev.state === "RUNNING" || ev.state === void 0 && (ev.tool?.output !== void 0 || ev.tool?.error !== void 0);
6792
+ }
6793
+ /**
6794
+ * Idle-budget + long-tool heartbeat state. While an agy tool step is ACTIVE the
6795
+ * child is legitimately silent on stdout (maven compile, language-server
6796
+ * build, …) — issue #33 — so the watchdog raises the idle budget; bare
6797
+ * generation gets a bounded floor so a hung SSE stream can fail and rotate.
6798
+ */
6799
+ function createToolWatchdog(log, cfg) {
6800
+ const openToolKeys = /* @__PURE__ */ new Set();
6801
+ const openToolSince = /* @__PURE__ */ new Map();
6802
+ const { printTimeoutMinutes, longToolIdleMs, generationIdleMs } = resolveWatchdogBudgets(cfg);
6803
+ let runningProc = null;
6804
+ let awaitingSubagent = false;
6805
+ let sawAnyEvent = false;
6806
+ let lastOutputAt = 0;
6807
+ const TOOL_HEARTBEAT_MS = 3e5;
6808
+ let toolHeartbeat = null;
6809
+ const apply = () => {
6810
+ runningProc?.noteActivity(openToolKeys.size > 0 ? longToolIdleMs : generationIdleMs);
6811
+ };
6812
+ const setAwaitingSubagent = (next) => {
6813
+ if (awaitingSubagent === next) return;
6814
+ awaitingSubagent = next;
6815
+ runningProc?.exemptIdleGrace(next);
6816
+ };
6817
+ const stop = () => {
6818
+ if (toolHeartbeat !== null) {
6819
+ clearInterval(toolHeartbeat);
6820
+ toolHeartbeat = null;
6821
+ }
6822
+ };
6823
+ const start = () => {
6824
+ if (toolHeartbeat !== null) return;
6825
+ toolHeartbeat = setInterval(() => {
6826
+ if (openToolKeys.size === 0 && !sawAnyEvent) {
6827
+ stop();
6828
+ return;
6829
+ }
6830
+ let oldest = Date.now();
6831
+ for (const startedAt of openToolSince.values()) if (startedAt < oldest) oldest = startedAt;
6832
+ if (openToolKeys.size === 0 && lastOutputAt > 0) oldest = lastOutputAt;
6833
+ const mins = Math.max(1, Math.round((Date.now() - oldest) / 6e4));
6834
+ log?.(openToolKeys.size > 0 ? "agy tool step still running: " + openToolKeys.size + " open, oldest " + mins + "m (idle budget " + Math.round(longToolIdleMs / 6e4) + "m) — the turn is waiting on agy" : "agy run still working: no new output for " + mins + "m (idle budget " + Math.round(longToolIdleMs / 6e4) + "m) — the turn is waiting on agy; press Stop to cancel");
6835
+ }, TOOL_HEARTBEAT_MS);
6836
+ toolHeartbeat.unref?.();
6837
+ };
6838
+ return {
6839
+ printTimeoutMinutes,
6840
+ attach: (proc) => {
6841
+ runningProc = proc;
6842
+ proc?.exemptIdleGrace(awaitingSubagent);
6843
+ apply();
6844
+ },
6845
+ markEvent: () => {
6846
+ sawAnyEvent = true;
6847
+ lastOutputAt = Date.now();
6848
+ start();
6849
+ apply();
6850
+ },
6851
+ trackStep: (ev) => {
6852
+ if (ev.kind !== "step") return;
6853
+ if (ev.stepKind === "tool" && ev.tool !== void 0) {
6854
+ if (SUBAGENT_COLLAB_TOOLS.has(ev.tool.name)) setAwaitingSubagent(!isStepFailedOrCanceled(ev));
6855
+ if (!isToolStepCompleted(ev)) {
6856
+ if (!openToolKeys.has(ev.stepKey)) {
6857
+ openToolKeys.add(ev.stepKey);
6858
+ openToolSince.set(ev.stepKey, Date.now());
6859
+ apply();
6860
+ start();
6861
+ }
6862
+ } else if (openToolKeys.delete(ev.stepKey)) {
6863
+ openToolSince.delete(ev.stepKey);
6864
+ apply();
6865
+ if (openToolKeys.size === 0) stop();
6866
+ }
6867
+ } else if (ev.stepKind === "text" || ev.stepKind === "thinking") {
6868
+ setAwaitingSubagent(false);
6869
+ if (openToolKeys.size > 0) {
6870
+ openToolKeys.clear();
6871
+ openToolSince.clear();
6872
+ apply();
6873
+ stop();
6874
+ }
6875
+ }
6876
+ },
6877
+ stop: () => {
6878
+ stop();
6879
+ setAwaitingSubagent(false);
6880
+ openToolKeys.clear();
6881
+ openToolSince.clear();
6882
+ }
6883
+ };
6884
+ }
6885
+ //#endregion
6370
6886
  //#region src/host/discovery.ts
6371
6887
  function defaultConversationsDir() {
6372
6888
  return process.env.DSH_AGY_CONVERSATIONS_DIR ?? join(homedir(), ".gemini", "antigravity-cli", "conversations");
@@ -6639,8 +7155,11 @@ function classifyEvent(obj, seq) {
6639
7155
  const text = delta !== void 0 ? delta : extractText(src);
6640
7156
  const stateV = pick(src, ["state"]);
6641
7157
  if (stateV === "ERROR" && toolInfo && !toolInfo.error) toolInfo.error = "tool execution failed";
7158
+ else if ((stateV === "CANCELED" || stateV === "CANCELLED") && toolInfo && !toolInfo.error) toolInfo.error = "tool execution canceled";
6642
7159
  if (stateV === "RUNNING" && toolInfo && toolInfo.output === void 0 && text !== "") toolInfo.output = text;
6643
7160
  const usageRaw = pick(src, ["usage"]);
7161
+ const convIdRaw = pick(o, ["conversation_id", "conversationId"]) ?? pick(src, ["conversation_id", "conversationId"]);
7162
+ const isTextFragment = stepKind === "text" && delta !== void 0;
6644
7163
  return {
6645
7164
  kind: "step",
6646
7165
  stepKey,
@@ -6650,7 +7169,8 @@ function classifyEvent(obj, seq) {
6650
7169
  ...toolInfo !== void 0 ? { tool: toolInfo } : {},
6651
7170
  ...typeof stateV === "string" ? { state: stateV } : {},
6652
7171
  ...usageRaw && typeof usageRaw === "object" ? { usage: parseUsage(usageRaw) } : {},
6653
- raw: o
7172
+ ...typeof convIdRaw === "string" && convIdRaw !== "" ? { conversationId: convIdRaw } : {},
7173
+ ...isTextFragment ? {} : { raw: o }
6654
7174
  };
6655
7175
  }
6656
7176
  if (evt === "result" || evt === "done" || evt === "final") {
@@ -6791,50 +7311,115 @@ function agyHomeDirFor(account) {
6791
7311
  function agyLogDir(homeDir) {
6792
7312
  return join(homeDir, ".gemini", "antigravity-cli", "log");
6793
7313
  }
6794
- /** Names of the cli-*.log files present right now (cheap readdir). */
7314
+ /**
7315
+ * Byte-size snapshot of `cli-*.log` files present right now.
7316
+ * Recording byte offsets (instead of filenames alone) ensures two `agy` spawns
7317
+ * within the same wall-clock second (`cli-YYYYMMDD_HHMMSS.log`) still capture
7318
+ * the second invocation's appended log lines.
7319
+ */
6795
7320
  function snapshotAgyLogs(homeDir) {
6796
7321
  const dir = agyLogDir(homeDir);
7322
+ const out = /* @__PURE__ */ new Map();
6797
7323
  try {
6798
- return new Set(readdirSync(dir).filter((f) => f.startsWith("cli-") && f.endsWith(".log")));
6799
- } catch {
6800
- return /* @__PURE__ */ new Set();
6801
- }
7324
+ for (const f of readdirSync(dir)) {
7325
+ if (!f.startsWith("cli-") || !f.endsWith(".log")) continue;
7326
+ try {
7327
+ out.set(f, statSync(join(dir, f)).size);
7328
+ } catch {
7329
+ out.set(f, 0);
7330
+ }
7331
+ }
7332
+ } catch {}
7333
+ return out;
6802
7334
  }
6803
7335
  /** Upper bound so one pathological log cannot balloon the failure path. */
6804
7336
  const MAX_LOG_BYTES = 262144;
6805
7337
  const MAX_LOG_FILES = 3;
7338
+ function readFileTailFromOffset(filePath, offset, maxBytes) {
7339
+ const size = statSync(filePath).size;
7340
+ if (size <= offset || maxBytes <= 0) return "";
7341
+ if (offset === 0 && size <= maxBytes) return readFileSync(filePath, "utf8");
7342
+ const available = size - offset;
7343
+ const length = Math.min(available, maxBytes);
7344
+ const start = size - length;
7345
+ const fd = openSync(filePath, "r");
7346
+ try {
7347
+ const buf = Buffer.allocUnsafe(length);
7348
+ const read = readSync(fd, buf, 0, length, start);
7349
+ return buf.subarray(0, read).toString("utf8");
7350
+ } finally {
7351
+ closeSync(fd);
7352
+ }
7353
+ }
6806
7354
  /**
6807
- * Concatenated text of the log files THIS run created (present now, absent
6808
- * from the pre-spawn snapshot), newest first. Returns '' when the run wrote no
7355
+ * Concatenated text of the log bytes THIS run created (new files or bytes
7356
+ * appended past `before`), newest first. Returns '' when the run wrote no
6809
7357
  * readable log — callers must treat that as "no evidence", never as proof
6810
7358
  * either way.
6811
7359
  */
6812
7360
  function readAgyRunLogText(homeDir, before) {
6813
7361
  const dir = agyLogDir(homeDir);
6814
- let names;
7362
+ let entries;
6815
7363
  try {
6816
7364
  if (!existsSync(dir)) return "";
6817
- names = readdirSync(dir).filter((f) => f.startsWith("cli-") && f.endsWith(".log") && !before.has(f)).map((f) => ({
6818
- f,
6819
- m: statSync(join(dir, f)).mtimeMs
6820
- })).sort((a, b) => b.m - a.m).slice(0, MAX_LOG_FILES).map((e) => e.f);
7365
+ entries = readdirSync(dir).filter((f) => f.startsWith("cli-") && f.endsWith(".log")).flatMap((f) => {
7366
+ try {
7367
+ const st = statSync(join(dir, f));
7368
+ if (before instanceof Set) return before.has(f) ? [] : [{
7369
+ f,
7370
+ m: st.mtimeMs,
7371
+ offset: 0
7372
+ }];
7373
+ const prevSize = before.get(f);
7374
+ if (prevSize === void 0) return [{
7375
+ f,
7376
+ m: st.mtimeMs,
7377
+ offset: 0
7378
+ }];
7379
+ if (st.size > prevSize) return [{
7380
+ f,
7381
+ m: st.mtimeMs,
7382
+ offset: prevSize
7383
+ }];
7384
+ return [];
7385
+ } catch {
7386
+ return [];
7387
+ }
7388
+ }).sort((a, b) => b.m - a.m).slice(0, MAX_LOG_FILES);
6821
7389
  } catch {
6822
7390
  return "";
6823
7391
  }
6824
7392
  const parts = [];
6825
7393
  let budget = MAX_LOG_BYTES;
6826
- for (const name of names) {
7394
+ for (const entry of entries) {
6827
7395
  if (budget <= 0) break;
6828
7396
  try {
6829
- const text = readFileSync(join(dir, name), "utf8");
6830
- const slice = text.length > budget ? text.slice(-budget) : text;
6831
- parts.push(slice);
6832
- budget -= slice.length;
7397
+ const slice = readFileTailFromOffset(join(dir, entry.f), entry.offset, budget);
7398
+ if (slice !== "") {
7399
+ parts.push(slice);
7400
+ budget -= Buffer.byteLength(slice, "utf8");
7401
+ }
6833
7402
  } catch {}
6834
7403
  }
6835
7404
  return parts.join("\n");
6836
7405
  }
6837
7406
  //#endregion
7407
+ //#region src/host/model-support.ts
7408
+ /**
7409
+ * Whether `acc` can serve `model`.
7410
+ *
7411
+ * A learned refusal is final for that account. Otherwise the per-model quota
7412
+ * snapshot and the discovered catalog decide. Deliberately ACCOUNT-scoped: this
7413
+ * is what `selectAccount` routes on, so a sibling account must never make an
7414
+ * account look capable of a model its own evidence denies (that would route an
7415
+ * unsupported model to the wrong account). Pool-wide "nobody serves this" is
7416
+ * handled by the self-heal refresh in account-selection instead (issue #125).
7417
+ */
7418
+ function accountCanServeModel(acc, model, ctx) {
7419
+ if (ctx.unsupportedModels.get(acc.id)?.has(baseModelSlug(model))) return false;
7420
+ return accountSupportsModel(acc, model, ctx.pool, ctx.catalogFor(acc.id));
7421
+ }
7422
+ //#endregion
6838
7423
  //#region src/domain/accounts/paths.ts
6839
7424
  /**
6840
7425
  * Write `body` to `file` without ever publishing a torn snapshot: a tmp name
@@ -6869,6 +7454,66 @@ function defaultPoolDir(home) {
6869
7454
  }
6870
7455
  return join(effectiveHome, ".dsh", "agy-accounts");
6871
7456
  }
7457
+ //#endregion
7458
+ //#region src/common/quota-pacing.ts
7459
+ const FIVE_HOUR_WINDOW_MS = 18e6;
7460
+ const WEEKLY_WINDOW_MS = 6048e5;
7461
+ /**
7462
+ * Compare remaining quota fraction against remaining reset window fraction.
7463
+ *
7464
+ * For example, 80% remaining with 1h left in a 5h window (20% time left) has
7465
+ * `surplus = +0.60` ('surplus' — use freely before rollover), whereas 25%
7466
+ * remaining with 6d left in a 7d window (85.7% time left) has `surplus = -0.61`
7467
+ * ('burning_fast' — will exhaust early at current pace).
7468
+ */
7469
+ function computeQuotaPacing(remainingFraction, resetTimeIso, windowMs, now = Date.now()) {
7470
+ if (typeof remainingFraction !== "number" || !Number.isFinite(remainingFraction) || windowMs <= 0) return {
7471
+ status: "unknown",
7472
+ timeRemainingFraction: 1,
7473
+ elapsedFraction: 0,
7474
+ surplus: 0,
7475
+ burnMultiplier: 1
7476
+ };
7477
+ const clampedQuota = Math.max(0, Math.min(1, remainingFraction));
7478
+ if (!resetTimeIso) return {
7479
+ status: clampedQuota >= .999 ? "unactivated" : "unknown",
7480
+ timeRemainingFraction: 1,
7481
+ elapsedFraction: 0,
7482
+ surplus: 0,
7483
+ burnMultiplier: 1
7484
+ };
7485
+ const resetMs = Date.parse(resetTimeIso);
7486
+ if (Number.isNaN(resetMs)) return {
7487
+ status: "unknown",
7488
+ timeRemainingFraction: 1,
7489
+ elapsedFraction: 0,
7490
+ surplus: 0,
7491
+ burnMultiplier: 1
7492
+ };
7493
+ const diffMs = resetMs - now;
7494
+ if (diffMs <= 0) return {
7495
+ status: "reset",
7496
+ timeRemainingFraction: 0,
7497
+ elapsedFraction: 1,
7498
+ surplus: clampedQuota,
7499
+ burnMultiplier: 0
7500
+ };
7501
+ const timeRemainingFraction = Math.max(0, Math.min(1, diffMs / windowMs));
7502
+ const elapsedFraction = 1 - timeRemainingFraction;
7503
+ const surplus = clampedQuota - timeRemainingFraction;
7504
+ const usedFraction = Math.max(0, 1 - clampedQuota);
7505
+ const burnMultiplier = elapsedFraction >= .02 ? usedFraction / elapsedFraction : 1;
7506
+ let status = "on_track";
7507
+ if (elapsedFraction >= .04 && surplus <= -.15) status = "burning_fast";
7508
+ else if (surplus >= .15) status = "surplus";
7509
+ return {
7510
+ status,
7511
+ timeRemainingFraction,
7512
+ elapsedFraction,
7513
+ surplus,
7514
+ burnMultiplier
7515
+ };
7516
+ }
6872
7517
  /**
6873
7518
  * True when a family's cached quota snapshot benches the account.
6874
7519
  *
@@ -6906,7 +7551,7 @@ function explainIneligibility(acc, family, now, pool, model) {
6906
7551
  if (!acc.enabled) return "disabled";
6907
7552
  if (acc.authRequired) return "auth";
6908
7553
  if (family === "argon" && !accountHasArgon(acc, pool)) return "unsupported";
6909
- if (model && pool && typeof pool.isModelSupported === "function" && !pool.isModelSupported(acc, model)) return "model-unsupported";
7554
+ if (model && pool?.isModelSupported && !pool.isModelSupported(acc, model)) return "model-unsupported";
6910
7555
  const cd = acc.cooldowns?.[family];
6911
7556
  if (cd && cd.cooldownUntil > now) return "cooldown";
6912
7557
  if (isQuotaBenched(acc, family, now)) return "quota";
@@ -6918,12 +7563,17 @@ function explainIneligibility(acc, family, now, pool, model) {
6918
7563
  function isAccountEligible(acc, family, now, pool, model) {
6919
7564
  return explainIneligibility(acc, family, now, pool, model) === null;
6920
7565
  }
7566
+ function effectiveFamilyQuota(acc, family) {
7567
+ return acc.quotas?.[family] ?? (family === "argon" ? acc.quotas?.google : void 0);
7568
+ }
7569
+ /** Reset timestamps within 5m belong to the same reset cohort (avoids 1-60s clock jitter). */
7570
+ const RESET_COHORT_TOLERANCE_MS = 3e5;
6921
7571
  /**
6922
7572
  * Next moment this account's quota state refreshes for one family: the
6923
7573
  * sooner of the 5h window reset and the weekly cap reset. NaN when unknown.
6924
7574
  */
6925
7575
  function nextQuotaResetAt(acc, family) {
6926
- const q = acc.quotas?.[family];
7576
+ const q = effectiveFamilyQuota(acc, family);
6927
7577
  const stamps = [q?.resetTime, q?.weeklyResetTime].filter((v) => typeof v === "string" && v !== "").map((v) => Date.parse(v)).filter((t) => !Number.isNaN(t));
6928
7578
  return stamps.length === 0 ? NaN : Math.min(...stamps);
6929
7579
  }
@@ -6937,18 +7587,24 @@ function cyclicDistance(accounts, fromId, id) {
6937
7587
  if (start === -1) return idx;
6938
7588
  return (idx - start + total) % total;
6939
7589
  }
7590
+ function candidateSurplusScore(q, now) {
7591
+ if (!q) return null;
7592
+ const scores = [];
7593
+ if (typeof q.weeklyFraction === "number") scores.push(computeQuotaPacing(q.weeklyFraction, q.weeklyResetTime, WEEKLY_WINDOW_MS, now).surplus);
7594
+ if (typeof q.remainingFraction === "number") scores.push(computeQuotaPacing(q.remainingFraction, q.resetTime, FIVE_HOUR_WINDOW_MS, now).surplus);
7595
+ return scores.length > 0 ? Math.min(...scores) : null;
7596
+ }
6940
7597
  /**
6941
- * "Use it or lose it" rotation order.
6942
- * Priority 1: Weekly quota expiring soonest (least remaining time until weeklyResetTime).
6943
- * Priority 2: 5-hour quota expiring soonest (least remaining time until resetTime).
6944
- * Priority 3: Cyclic distance from `fromId` (or pool order).
6945
- *
6946
- * `accounts` is the pool order used for cycle distance; `now` is threaded in so
6947
- * callers keep the exact clock snapshot they passed to the eligibility check.
7598
+ * "Use it or lose it" rotation order with cohort burn-rate surplus tie-breaking.
7599
+ * Priority 1: Weekly quota expiring soonest (>5m difference).
7600
+ * Priority 2: 5-hour quota expiring soonest (>5m difference).
7601
+ * Priority 3: Within the same reset cohort, fewest consecutive failures, then
7602
+ * highest quota pacing surplus (>5% difference).
7603
+ * Priority 4: Cyclic distance from `fromId` (or pool order).
6948
7604
  */
6949
7605
  function orderByExpiry(accounts, candidates, family, fromId, now) {
6950
7606
  return candidates.map((acc, index) => {
6951
- const q = acc.quotas?.[family];
7607
+ const q = effectiveFamilyQuota(acc, family);
6952
7608
  const weeklyMs = q?.weeklyResetTime ? Date.parse(q.weeklyResetTime) : NaN;
6953
7609
  const fiveHourMs = q?.resetTime ? Date.parse(q.resetTime) : NaN;
6954
7610
  const weeklyRemaining = !Number.isNaN(weeklyMs) ? Math.max(0, weeklyMs - now) : Number.POSITIVE_INFINITY;
@@ -6959,15 +7615,19 @@ function orderByExpiry(accounts, candidates, family, fromId, now) {
6959
7615
  weeklyRemaining,
6960
7616
  fiveHourRemaining,
6961
7617
  weeklyKnown: Number.isFinite(weeklyRemaining),
6962
- fiveHourKnown: Number.isFinite(fiveHourRemaining)
7618
+ fiveHourKnown: Number.isFinite(fiveHourRemaining),
7619
+ failures: acc.cooldowns?.[family]?.consecutiveFailures ?? 0,
7620
+ surplus: candidateSurplusScore(q, now)
6963
7621
  };
6964
7622
  }).sort((a, b) => {
6965
7623
  if (a.weeklyKnown && b.weeklyKnown) {
6966
- if (a.weeklyRemaining !== b.weeklyRemaining) return a.weeklyRemaining - b.weeklyRemaining;
7624
+ if (Math.abs(a.weeklyRemaining - b.weeklyRemaining) > RESET_COHORT_TOLERANCE_MS) return a.weeklyRemaining - b.weeklyRemaining;
6967
7625
  } else if (a.weeklyKnown !== b.weeklyKnown) return a.weeklyKnown ? -1 : 1;
6968
7626
  if (a.fiveHourKnown && b.fiveHourKnown) {
6969
- if (a.fiveHourRemaining !== b.fiveHourRemaining) return a.fiveHourRemaining - b.fiveHourRemaining;
7627
+ if (Math.abs(a.fiveHourRemaining - b.fiveHourRemaining) > RESET_COHORT_TOLERANCE_MS) return a.fiveHourRemaining - b.fiveHourRemaining;
6970
7628
  } else if (a.fiveHourKnown !== b.fiveHourKnown) return a.fiveHourKnown ? -1 : 1;
7629
+ if (a.failures !== b.failures) return a.failures - b.failures;
7630
+ if (a.surplus !== null && b.surplus !== null && Math.abs(b.surplus - a.surplus) > .05) return b.surplus - a.surplus;
6971
7631
  const da = cyclicDistance(accounts, fromId, a.acc.id);
6972
7632
  const db = cyclicDistance(accounts, fromId, b.acc.id);
6973
7633
  return da !== db ? da - db : a.index - b.index;
@@ -7150,6 +7810,7 @@ var PoolAdmin = class {
7150
7810
  if (!data.activeAccountIds) data.activeAccountIds = {};
7151
7811
  data.activeAccountIds[family] = id;
7152
7812
  data.lastActiveAccountId = id;
7813
+ data.manualPinAt = Date.now();
7153
7814
  if (!accountHasArgon(acc, this.deps.pool)) delete data.activeAccountIds.argon;
7154
7815
  else data.activeAccountIds.argon = id;
7155
7816
  this.deps.persist();
@@ -7249,12 +7910,16 @@ var PoolAdmin = class {
7249
7910
  acc.enabled = true;
7250
7911
  data.primaryAccountId = id;
7251
7912
  data.accounts.unshift(acc);
7252
- data.activeAccountIds = {
7253
- google: id,
7254
- anthropic: id,
7255
- openai: id
7256
- };
7257
- data.lastActiveAccountId = id;
7913
+ if (!acc.authRequired) {
7914
+ data.activeAccountIds = {
7915
+ google: id,
7916
+ anthropic: id,
7917
+ openai: id,
7918
+ ...accountHasArgon(acc, this.deps.pool) ? { argon: id } : {}
7919
+ };
7920
+ data.lastActiveAccountId = id;
7921
+ }
7922
+ data.manualPinAt = Date.now();
7258
7923
  this.deps.persist();
7259
7924
  return true;
7260
7925
  }
@@ -7273,6 +7938,7 @@ var PoolAdmin = class {
7273
7938
  data.accounts = reordered;
7274
7939
  data.activeAccountIds = {};
7275
7940
  data.lastActiveAccountId = void 0;
7941
+ data.manualPinAt = Date.now();
7276
7942
  this.deps.persist();
7277
7943
  return true;
7278
7944
  }
@@ -7312,7 +7978,7 @@ var PoolAdmin = class {
7312
7978
  const acc = this.account(id);
7313
7979
  if (!acc) return;
7314
7980
  acc.lastUsedAt = Date.now();
7315
- if (acc.authRequired) {
7981
+ if (acc.authRequired && !isTerminalAuthError(acc.authError)) {
7316
7982
  delete acc.authRequired;
7317
7983
  delete acc.authError;
7318
7984
  delete acc.authMarkedAt;
@@ -7365,6 +8031,68 @@ var PoolAdmin = class {
7365
8031
  }
7366
8032
  };
7367
8033
  //#endregion
8034
+ //#region src/domain/accounts/countdown.ts
8035
+ /** Get countdown in milliseconds until the earliest account in cooldown resets. */
8036
+ function earliestResetCountdown(accounts, family, now = Date.now()) {
8037
+ let earliest = null;
8038
+ for (const acc of accounts) {
8039
+ if (!acc.enabled) continue;
8040
+ const cd = acc.cooldowns?.[family];
8041
+ if (cd && cd.cooldownUntil > now && (earliest === null || cd.cooldownUntil < earliest)) earliest = cd.cooldownUntil;
8042
+ }
8043
+ return earliest !== null ? Math.max(0, earliest - now) : null;
8044
+ }
8045
+ /**
8046
+ * Earliest moment ANY enabled account could serve `family` again: the sooner
8047
+ * of a cooldown expiry and a quota-window reset.
8048
+ */
8049
+ function earliestAvailableCountdown(accounts, family, now = Date.now()) {
8050
+ let earliest = null;
8051
+ const bump = (at) => {
8052
+ if (at === null || Number.isNaN(at) || at <= now) return;
8053
+ if (earliest === null || at < earliest) earliest = at;
8054
+ };
8055
+ for (const acc of accounts) {
8056
+ if (!acc.enabled || acc.authRequired) continue;
8057
+ const cd = acc.cooldowns?.[family];
8058
+ if (cd && cd.cooldownUntil > now) bump(cd.cooldownUntil);
8059
+ const quota = acc.quotas?.[family];
8060
+ if (quota === void 0) continue;
8061
+ const clearedAt = acc.quotaGateClearedAt?.[family];
8062
+ if (clearedAt !== void 0 && (quota.updatedAt ?? 0) <= clearedAt) continue;
8063
+ const drained5h = typeof quota.remainingFraction === "number" && quota.remainingFraction <= .1 && typeof quota.resetTime === "string" && Date.parse(quota.resetTime) > now;
8064
+ const drainedWeekly = typeof quota.weeklyFraction === "number" && quota.weeklyFraction <= .05 && typeof quota.weeklyResetTime === "string" && Date.parse(quota.weeklyResetTime) > now;
8065
+ if (drained5h || drainedWeekly) bump(nextQuotaResetAt(acc, family));
8066
+ }
8067
+ return earliest !== null ? Math.max(0, earliest - now) : null;
8068
+ }
8069
+ /**
8070
+ * Sweep `cli-*.log` files older than `maxDays` across managed account homes
8071
+ * plus the system `~/.gemini/antigravity-cli/log` directory.
8072
+ */
8073
+ function sweepOldAgyLogs(accounts, systemHome, maxDays = 7, now = Date.now()) {
8074
+ const maxAgeMs = Math.max(1, maxDays) * 864e5;
8075
+ let removed = 0;
8076
+ const targetLogDirs = [join(systemHome, ".gemini", "antigravity-cli", "log")];
8077
+ for (const acc of accounts) if (acc.dir) targetLogDirs.push(join(acc.dir, ".gemini", "antigravity-cli", "log"));
8078
+ for (const logDir of targetLogDirs) {
8079
+ if (!existsSync(logDir)) continue;
8080
+ try {
8081
+ for (const f of readdirSync(logDir)) {
8082
+ if (!f.startsWith("cli-") || !f.endsWith(".log")) continue;
8083
+ const fp = join(logDir, f);
8084
+ try {
8085
+ if (now - statSync(fp).mtimeMs > maxAgeMs) {
8086
+ rmSync(fp, { force: true });
8087
+ removed++;
8088
+ }
8089
+ } catch {}
8090
+ }
8091
+ } catch {}
8092
+ }
8093
+ return removed;
8094
+ }
8095
+ //#endregion
7368
8096
  //#region src/domain/accounts/store.ts
7369
8097
  var PoolStore = class {
7370
8098
  baseDir;
@@ -7454,13 +8182,62 @@ var PoolStore = class {
7454
8182
  try {
7455
8183
  if (existsSync(this.file)) {
7456
8184
  const onDisk = JSON.parse(readFileSync(this.file, "utf8"));
8185
+ const base = this.persistedJson ? JSON.parse(this.persistedJson) : null;
8186
+ const baseMap = new Map((base?.accounts ?? []).map((a) => [a.id, a]));
7457
8187
  if (onDisk && Array.isArray(onDisk.accounts)) {
8188
+ const onDiskMap = new Map(onDisk.accounts.filter((a) => Boolean(a && typeof a === "object" && a.id !== void 0)).map((a) => [a.id, a]));
8189
+ let accountMerged = false;
8190
+ const now = Date.now();
8191
+ const nextAccounts = data.accounts.map((ourAcc) => {
8192
+ const diskAcc = onDiskMap.get(ourAcc.id);
8193
+ if (!diskAcc || !this.knownIds.has(ourAcc.id)) return ourAcc;
8194
+ const baseAcc = baseMap.get(ourAcc.id);
8195
+ let nextQuot = ourAcc.quotas;
8196
+ for (const [fam, dq] of Object.entries(diskAcc.quotas ?? {})) {
8197
+ if (!dq) continue;
8198
+ const oq = ourAcc.quotas?.[fam];
8199
+ const bq = baseAcc?.quotas?.[fam];
8200
+ if ((dq.updatedAt ?? 0) > (oq?.updatedAt ?? 0) && (dq.updatedAt ?? 0) > (bq?.updatedAt ?? 0)) {
8201
+ nextQuot = {
8202
+ ...nextQuot,
8203
+ [fam]: dq
8204
+ };
8205
+ accountMerged = true;
8206
+ }
8207
+ }
8208
+ let nextCd = ourAcc.cooldowns;
8209
+ for (const [fam, dcd] of Object.entries(diskAcc.cooldowns ?? {})) {
8210
+ if (!dcd || dcd.cooldownUntil <= now) continue;
8211
+ const ocd = ourAcc.cooldowns?.[fam];
8212
+ const bcd = baseAcc?.cooldowns?.[fam];
8213
+ if (dcd.cooldownUntil > (ocd?.cooldownUntil ?? 0) && dcd.cooldownUntil !== (bcd?.cooldownUntil ?? 0)) {
8214
+ nextCd = {
8215
+ ...nextCd,
8216
+ [fam]: dcd
8217
+ };
8218
+ accountMerged = true;
8219
+ }
8220
+ }
8221
+ const diskTos = Boolean(diskAcc.authRequired && isTerminalAuthError(diskAcc.authError));
8222
+ const baseTos = Boolean(baseAcc?.authRequired && isTerminalAuthError(baseAcc.authError));
8223
+ const adoptTos = diskTos && !baseTos && !ourAcc.authRequired;
8224
+ if (nextQuot === ourAcc.quotas && nextCd === ourAcc.cooldowns && !adoptTos) return ourAcc;
8225
+ accountMerged = true;
8226
+ ourAcc.quotas = nextQuot;
8227
+ ourAcc.cooldowns = nextCd;
8228
+ if (adoptTos) {
8229
+ ourAcc.authRequired = true;
8230
+ ourAcc.authError = diskAcc.authError;
8231
+ ourAcc.authMarkedAt = diskAcc.authMarkedAt;
8232
+ }
8233
+ return ourAcc;
8234
+ });
7458
8235
  const ours = new Set(data.accounts.map((a) => a.id));
7459
8236
  const foreign = onDisk.accounts.filter((a) => a && typeof a === "object" && a.id !== void 0 && !ours.has(a.id) && !this.knownIds.has(a.id));
7460
- if (foreign.length > 0) {
8237
+ if (foreign.length > 0 || accountMerged) {
7461
8238
  merged = {
7462
8239
  ...data,
7463
- accounts: [...data.accounts, ...foreign]
8240
+ accounts: [...nextAccounts, ...foreign]
7464
8241
  };
7465
8242
  for (const acc of foreign) this.knownIds.add(acc.id);
7466
8243
  }
@@ -7907,11 +8684,18 @@ var AccountPoolManager = class {
7907
8684
  selectAccount: (family, model) => this.selectAccount(family, model)
7908
8685
  });
7909
8686
  }
8687
+ catalogForAccount(accountId) {
8688
+ if (!this.catalog) return void 0;
8689
+ if (typeof this.catalog.getAccountCatalog === "function") return this.catalog.getAccountCatalog(accountId);
8690
+ return this.catalog.get(accountId);
8691
+ }
7910
8692
  /** Determine whether a managed account supports a specific model. */
7911
8693
  isModelSupported(acc, model) {
7912
- if (this.unsupportedModels.get(acc.id)?.has(baseModelSlug(model))) return false;
7913
- const cat = this.catalog?.get(acc.id);
7914
- return accountSupportsModel(acc, model, this, cat);
8694
+ return accountCanServeModel(acc, model, {
8695
+ unsupportedModels: this.unsupportedModels,
8696
+ catalogFor: (id) => this.catalogForAccount(id),
8697
+ pool: this
8698
+ });
7915
8699
  }
7916
8700
  markModelUnsupported(accountId, model) {
7917
8701
  const set = this.unsupportedModels.get(accountId) ?? /* @__PURE__ */ new Set();
@@ -7963,35 +8747,20 @@ var AccountPoolManager = class {
7963
8747
  * as well as the primary system ~/.gemini/antigravity-cli/log directory.
7964
8748
  */
7965
8749
  sweepOldLogs(maxDays = 7) {
7966
- const maxAgeMs = Math.max(1, maxDays) * 864e5;
7967
- const now = Date.now();
7968
- let removed = 0;
7969
- const targetLogDirs = [join(homedir(), ".gemini", "antigravity-cli", "log")];
7970
- for (const acc of this.data.accounts) if (acc.dir) targetLogDirs.push(join(acc.dir, ".gemini", "antigravity-cli", "log"));
7971
- for (const logDir of targetLogDirs) {
7972
- if (!existsSync(logDir)) continue;
7973
- try {
7974
- const files = readdirSync(logDir);
7975
- for (const f of files) {
7976
- if (!f.startsWith("cli-") || !f.endsWith(".log")) continue;
7977
- const fp = join(logDir, f);
7978
- try {
7979
- if (now - statSync(fp).mtimeMs > maxAgeMs) {
7980
- rmSync(fp, { force: true });
7981
- removed++;
7982
- }
7983
- } catch {}
7984
- }
7985
- } catch {}
7986
- }
7987
- return removed;
8750
+ return sweepOldAgyLogs(this.data.accounts, homedir(), maxDays);
7988
8751
  }
7989
8752
  /** Create a new isolated account slot and prepare its filesystem home. */
7990
8753
  createAccountSlot(alias) {
7991
8754
  return this.admin.createAccountSlot(alias);
7992
8755
  }
7993
8756
  deleteAccount(id) {
7994
- return this.admin.deleteAccount(id);
8757
+ const wasActive = this.data.activeAccountIds?.google === id || this.data.lastActiveAccountId === id;
8758
+ const ok = this.admin.deleteAccount(id);
8759
+ if (ok && wasActive) {
8760
+ const next = this.data.accounts.find((a) => a.enabled && !a.authRequired)?.id;
8761
+ if (next) this.onAccountSwitch?.(next);
8762
+ }
8763
+ return ok;
7995
8764
  }
7996
8765
  setAccountProxy(id, proxyUrl) {
7997
8766
  return this.admin.setAccountProxy(id, proxyUrl);
@@ -8000,7 +8769,13 @@ var AccountPoolManager = class {
8000
8769
  return this.admin.setAccountAlias(id, alias);
8001
8770
  }
8002
8771
  setAccountEnabled(id, enabled) {
8003
- return this.admin.setAccountEnabled(id, enabled);
8772
+ const wasActive = this.data.activeAccountIds?.google === id || this.data.lastActiveAccountId === id;
8773
+ const ok = this.admin.setAccountEnabled(id, enabled);
8774
+ if (ok && (!enabled ? wasActive : !this.data.lastActiveAccountId)) {
8775
+ const next = this.data.accounts.find((a) => a.enabled && !a.authRequired)?.id;
8776
+ if (next) this.onAccountSwitch?.(next);
8777
+ }
8778
+ return ok;
8004
8779
  }
8005
8780
  /**
8006
8781
  * Record the account a run actually spawned with. The console derives its
@@ -8064,26 +8839,12 @@ var AccountPoolManager = class {
8064
8839
  setMode(mode) {
8065
8840
  this.admin.setMode(mode);
8066
8841
  }
8067
- /**
8068
- * True when a family's cached quota snapshot benches the account.
8069
- *
8070
- * A user-visible `clearCooldown(..., includeQuotaBench = true)` records the
8071
- * `updatedAt` of the snapshot it overrode; the gate stays off only while the
8072
- * cached row is no newer than that stamp, so a fresh poll always re-arms it.
8073
- */
8074
- isQuotaBenched(acc, family, now) {
8075
- return isQuotaBenched(acc, family, now);
8076
- }
8077
8842
  /** Determine whether a managed account has confirmed access to Gemini 4 Argon. */
8078
8843
  accountHasArgon(acc) {
8079
- return accountHasArgon(acc, this);
8844
+ return accountHasArgon(acc, this, this.catalogForAccount(acc.id));
8080
8845
  }
8081
8846
  /**
8082
8847
  * Why this account cannot serve `family` right now, or null when it can.
8083
- *
8084
- * Exists so callers can report the ACTUAL blocker: quota rotation used to be
8085
- * folded into "in cooldown", which pointed users at `/agy clear-cooldown` for
8086
- * a state that command did not touch.
8087
8848
  */
8088
8849
  explainIneligibility(acc, family, now = Date.now(), model) {
8089
8850
  return explainIneligibility(acc, family, now, this, model);
@@ -8100,23 +8861,6 @@ var AccountPoolManager = class {
8100
8861
  getActiveAccountId(family = "google", model) {
8101
8862
  return this.admin.getActiveAccountId(family, model);
8102
8863
  }
8103
- /**
8104
- * Next moment this account's quota state refreshes for one family: the
8105
- * sooner of the 5h window reset and the weekly cap reset. NaN when unknown.
8106
- */
8107
- nextQuotaResetAt(acc, family) {
8108
- return nextQuotaResetAt(acc, family);
8109
- }
8110
- /** Cyclic distance from `fromId` (0 = itself), so ties keep pool order. */
8111
- cyclicDistance(fromId, id) {
8112
- return cyclicDistance(this.data.accounts, fromId, id);
8113
- }
8114
- /**
8115
- * "Use it or lose it" rotation order.
8116
- * Priority 1: Weekly quota expiring soonest (least remaining time until weeklyResetTime).
8117
- * Priority 2: 5-hour quota expiring soonest (least remaining time until resetTime).
8118
- * Priority 3: Cyclic distance from `fromId` (or pool order).
8119
- */
8120
8864
  orderByExpiry(candidates, family, fromId) {
8121
8865
  return orderByExpiry(this.data.accounts, candidates, family, fromId, Date.now());
8122
8866
  }
@@ -8144,7 +8888,9 @@ var AccountPoolManager = class {
8144
8888
  const isExhaustedWeekly = typeof info.weeklyFraction === "number" && info.weeklyFraction <= .05 && (!info.weeklyResetTime || Number.isNaN(Date.parse(info.weeklyResetTime)) || Date.parse(info.weeklyResetTime) > now);
8145
8889
  if (isExhausted5h || isExhaustedWeekly) {
8146
8890
  const clearedAt = acc.quotaGateClearedAt?.[famKey];
8147
- if (!(clearedAt !== void 0 && (info.updatedAt ?? 0) <= clearedAt) && (this.data.activeAccountIds?.[famKey] === id || this.data.lastActiveAccountId === id)) this.advanceAccount(id, famKey);
8891
+ const gateCleared = clearedAt !== void 0 && (info.updatedAt ?? 0) <= clearedAt;
8892
+ if (!gateCleared && (this.data.activeAccountIds?.[famKey] === id || this.data.lastActiveAccountId === id)) this.advanceAccount(id, famKey);
8893
+ if (!gateCleared && famKey === "google" && !acc.quotas?.argon && this.data.activeAccountIds?.argon === id) this.advanceAccount(id, "argon");
8148
8894
  }
8149
8895
  }
8150
8896
  this.persist();
@@ -8164,7 +8910,10 @@ var AccountPoolManager = class {
8164
8910
  }
8165
8911
  /** Records a rate-limit / 429 error and sets cooldown for the requested model family. */
8166
8912
  recordFailure(id, family, reason, serverResetTime) {
8913
+ const prev = this.data.activeAccountIds?.[family] ?? this.data.lastActiveAccountId;
8167
8914
  this.admin.recordFailure(id, family, reason, serverResetTime);
8915
+ const next = this.data.activeAccountIds?.[family] ?? this.data.lastActiveAccountId;
8916
+ if (next && next !== prev) this.onAccountSwitch?.(next, family);
8168
8917
  }
8169
8918
  /** Records a successful run, clearing failure counter and authRequired flag for the family. */
8170
8919
  recordSuccess(id, family) {
@@ -8266,39 +9015,14 @@ var AccountPoolManager = class {
8266
9015
  }
8267
9016
  /** Get countdown in milliseconds until the earliest account in cooldown resets. */
8268
9017
  getEarliestResetCountdown(family) {
8269
- const now = Date.now();
8270
- let earliest = null;
8271
- for (const acc of this.data.accounts) {
8272
- if (!acc.enabled) continue;
8273
- const cd = acc.cooldowns?.[family];
8274
- if (cd && cd.cooldownUntil > now && (earliest === null || cd.cooldownUntil < earliest)) earliest = cd.cooldownUntil;
8275
- }
8276
- return earliest !== null ? Math.max(0, earliest - now) : null;
9018
+ return earliestResetCountdown(this.data.accounts, family);
8277
9019
  }
8278
9020
  /**
8279
9021
  * Earliest moment ANY enabled account could serve `family` again: the sooner
8280
9022
  * of a cooldown expiry and a quota-window reset.
8281
9023
  */
8282
9024
  getEarliestAvailableCountdown(family) {
8283
- const now = Date.now();
8284
- let earliest = null;
8285
- const bump = (at) => {
8286
- if (at === null || Number.isNaN(at) || at <= now) return;
8287
- if (earliest === null || at < earliest) earliest = at;
8288
- };
8289
- for (const acc of this.data.accounts) {
8290
- if (!acc.enabled || acc.authRequired) continue;
8291
- const cd = acc.cooldowns?.[family];
8292
- if (cd && cd.cooldownUntil > now) bump(cd.cooldownUntil);
8293
- const quota = acc.quotas?.[family];
8294
- if (quota === void 0) continue;
8295
- const clearedAt = acc.quotaGateClearedAt?.[family];
8296
- if (clearedAt !== void 0 && (quota.updatedAt ?? 0) <= clearedAt) continue;
8297
- const drained5h = typeof quota.remainingFraction === "number" && quota.remainingFraction <= .1 && typeof quota.resetTime === "string" && Date.parse(quota.resetTime) > now;
8298
- const drainedWeekly = typeof quota.weeklyFraction === "number" && quota.weeklyFraction <= .05 && typeof quota.weeklyResetTime === "string" && Date.parse(quota.weeklyResetTime) > now;
8299
- if (drained5h || drainedWeekly) bump(this.nextQuotaResetAt(acc, family));
8300
- }
8301
- return earliest !== null ? Math.max(0, earliest - now) : null;
9025
+ return earliestAvailableCountdown(this.data.accounts, family);
8302
9026
  }
8303
9027
  };
8304
9028
  //#endregion
@@ -31736,36 +32460,60 @@ var import_undici = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
31736
32460
  }
31737
32461
  module.exports.install = install;
31738
32462
  })))();
31739
- const envAgent = new import_undici.EnvHttpProxyAgent();
32463
+ const defaultEnvAgent = new import_undici.EnvHttpProxyAgent();
31740
32464
  const perProxyAgents = /* @__PURE__ */ new Map();
31741
- function agentFor(proxyUrl) {
31742
- const effective = proxyUrl || detectSystemProxy();
32465
+ const perScopeEnvAgents = /* @__PURE__ */ new Map();
32466
+ const MAX_CACHED_AGENTS = 32;
32467
+ function dispatcherKeyFor(proxyUrl, accountScope) {
32468
+ return `${accountScope && accountScope.trim() !== "" ? accountScope.trim() : "global"}@@${(proxyUrl ?? "").trim() || (detectSystemProxy() ?? "").trim() || "env"}`;
32469
+ }
32470
+ function agentForScope(proxyUrl, accountScope) {
32471
+ const effective = (proxyUrl ?? "").trim() || (detectSystemProxy() ?? "").trim();
31743
32472
  if (effective) {
31744
- let agent = perProxyAgents.get(effective);
32473
+ const key = dispatcherKeyFor(effective, accountScope);
32474
+ let agent = perProxyAgents.get(key);
31745
32475
  if (!agent) {
32476
+ if (perProxyAgents.size >= MAX_CACHED_AGENTS) {
32477
+ const oldestKey = perProxyAgents.keys().next().value;
32478
+ if (oldestKey !== void 0) {
32479
+ const old = perProxyAgents.get(oldestKey);
32480
+ perProxyAgents.delete(oldestKey);
32481
+ old?.close().catch(() => void 0);
32482
+ }
32483
+ }
31746
32484
  agent = new import_undici.ProxyAgent(effective);
31747
- perProxyAgents.set(effective, agent);
32485
+ perProxyAgents.set(key, agent);
31748
32486
  }
31749
32487
  return agent;
31750
32488
  }
31751
- return envAgent;
32489
+ if (accountScope && accountScope.trim() !== "") {
32490
+ const scopeKey = accountScope.trim();
32491
+ let envScoped = perScopeEnvAgents.get(scopeKey);
32492
+ if (!envScoped) {
32493
+ if (perScopeEnvAgents.size >= MAX_CACHED_AGENTS) {
32494
+ const oldestKey = perScopeEnvAgents.keys().next().value;
32495
+ if (oldestKey !== void 0) {
32496
+ const old = perScopeEnvAgents.get(oldestKey);
32497
+ perScopeEnvAgents.delete(oldestKey);
32498
+ old?.close().catch(() => void 0);
32499
+ }
32500
+ }
32501
+ envScoped = new import_undici.EnvHttpProxyAgent();
32502
+ perScopeEnvAgents.set(scopeKey, envScoped);
32503
+ }
32504
+ return envScoped;
32505
+ }
32506
+ return defaultEnvAgent;
31752
32507
  }
31753
- /**
31754
- * Default timeout for one Google endpoint call. undici's own default
31755
- * headers timeout is 300s, so a hung refresh-token / quota endpoint used to
31756
- * park the whole chain (token refresh → two endpoints → userinfo) for many
31757
- * minutes — enough for `/agy refresh-quota` to look dead. Callers may pass
31758
- * their own `signal`; it is combined with the timeout.
31759
- */
31760
32508
  const AGY_FETCH_TIMEOUT_MS = 1e4;
31761
- /** fetch() honoring env proxies, or an explicit per-account proxy URL. */
31762
- function agyFetch(url, init = {}, proxyUrl) {
32509
+ /** fetch() honoring env/per-account proxies and per-account connection-pool isolation. */
32510
+ function agyFetch(url, init = {}, proxyUrl, accountScope) {
31763
32511
  const callerSignal = init.signal ?? void 0;
31764
32512
  const signal = callerSignal !== void 0 ? AbortSignal.any([AbortSignal.timeout(AGY_FETCH_TIMEOUT_MS), callerSignal]) : AbortSignal.timeout(AGY_FETCH_TIMEOUT_MS);
31765
32513
  return (0, import_undici.fetch)(url, {
31766
32514
  ...init,
31767
32515
  signal,
31768
- dispatcher: agentFor(proxyUrl)
32516
+ dispatcher: agentForScope(proxyUrl, accountScope)
31769
32517
  });
31770
32518
  }
31771
32519
  function resolveClientCredentials() {
@@ -31775,7 +32523,9 @@ function resolveClientCredentials() {
31775
32523
  };
31776
32524
  }
31777
32525
  const OAUTH_TOKEN_URL = "https://oauth2.googleapis.com/token";
31778
- async function postTokenForm(fields, proxyUrl) {
32526
+ const OAUTH_USERINFO_URL = "https://www.googleapis.com/oauth2/v1/userinfo";
32527
+ let runtimeAgyVersion = null;
32528
+ async function postTokenForm(fields, proxyUrl, accountScope) {
31779
32529
  const { clientId, clientSecret } = resolveClientCredentials();
31780
32530
  const body = new URLSearchParams({
31781
32531
  client_id: clientId,
@@ -31784,9 +32534,12 @@ async function postTokenForm(fields, proxyUrl) {
31784
32534
  });
31785
32535
  const res = await agyFetch(OAUTH_TOKEN_URL, {
31786
32536
  method: "POST",
31787
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
32537
+ headers: {
32538
+ "Content-Type": "application/x-www-form-urlencoded",
32539
+ "User-Agent": agyUserAgent(runtimeAgyVersion)
32540
+ },
31788
32541
  body: body.toString()
31789
- }, proxyUrl);
32542
+ }, proxyUrl, accountScope);
31790
32543
  const payload = await res.json().catch(() => ({}));
31791
32544
  if (!res.ok) {
31792
32545
  const code = typeof payload.error === "string" ? payload.error : payload.error?.status;
@@ -31804,12 +32557,41 @@ function toTokenSet(payload, refreshTokenFallback) {
31804
32557
  expiryMs: typeof payload.expires_in === "number" ? Date.now() + payload.expires_in * 1e3 : void 0
31805
32558
  };
31806
32559
  }
31807
- /** Refresh an access token; throws on invalid_grant (credential revoked). */
31808
- async function refreshTokens(refreshToken, proxyUrl) {
31809
- return toTokenSet(await postTokenForm({
31810
- grant_type: "refresh_token",
31811
- refresh_token: refreshToken
31812
- }, proxyUrl), refreshToken);
32560
+ /** Refresh an access token (with one 500ms confirmation retry on transient invalid_grant). */
32561
+ async function refreshTokens(refreshToken, proxyUrl, accountScope) {
32562
+ try {
32563
+ return toTokenSet(await postTokenForm({
32564
+ grant_type: "refresh_token",
32565
+ refresh_token: refreshToken
32566
+ }, proxyUrl, accountScope), refreshToken);
32567
+ } catch (err) {
32568
+ if (/invalid_grant/i.test(String(err))) {
32569
+ await new Promise((r) => setTimeout(r, 500));
32570
+ return toTokenSet(await postTokenForm({
32571
+ grant_type: "refresh_token",
32572
+ refresh_token: refreshToken
32573
+ }, proxyUrl, accountScope), refreshToken);
32574
+ }
32575
+ throw err;
32576
+ }
32577
+ }
32578
+ /** Canonical Google OAuth userinfo reader shared across auth, quota and slot identity checks. */
32579
+ async function fetchUserInfo(accessToken, proxyUrl, accountScope) {
32580
+ try {
32581
+ const res = await agyFetch(OAUTH_USERINFO_URL, { headers: {
32582
+ Authorization: `Bearer ${accessToken}`,
32583
+ "User-Agent": agyUserAgent(runtimeAgyVersion)
32584
+ } }, proxyUrl, accountScope);
32585
+ if (!res.ok) return null;
32586
+ return await res.json();
32587
+ } catch {
32588
+ return null;
32589
+ }
32590
+ }
32591
+ /** Fetch the account email for a valid access token (best effort). */
32592
+ async function fetchUserEmail(accessToken, proxyUrl, accountScope) {
32593
+ const info = await fetchUserInfo(accessToken, proxyUrl, accountScope);
32594
+ return typeof info?.email === "string" && info.email ? info.email : void 0;
31813
32595
  }
31814
32596
  //#endregion
31815
32597
  //#region src/domain/credentials/backup.ts
@@ -31834,12 +32616,12 @@ function sleepMs(ms) {
31834
32616
  }
31835
32617
  /** Read a file with retry backoff for transient Windows sharing violations. */
31836
32618
  function readWithRetry(file) {
31837
- for (let attempt = 0; attempt < 3; attempt++) try {
32619
+ for (let attempt = 0; attempt < 5; attempt++) try {
31838
32620
  return readFileSync(file, "utf8");
31839
32621
  } catch (err) {
31840
32622
  const code = err.code;
31841
32623
  if (code === "ENOENT") return null;
31842
- if (attempt < 2 && (code === "EBUSY" || code === "EPERM" || code === "EACCES")) {
32624
+ if (attempt < 4 && (code === "EBUSY" || code === "EPERM" || code === "EACCES")) {
31843
32625
  sleepMs(50);
31844
32626
  continue;
31845
32627
  }
@@ -31960,20 +32742,9 @@ function readTokenFileRaw(file) {
31960
32742
  const raw = readAccountCredential(file);
31961
32743
  return raw && raw.trim() ? raw : null;
31962
32744
  }
31963
- /** Atomic-ish replace: write a sibling temp file then rename over the target. */
32745
+ /** Atomic replace: write a sibling temp file then rename over the target. */
31964
32746
  function writeFileAtomic(file, data) {
31965
- const tmp = file + ".tmp-" + process.pid + "-" + Date.now();
31966
- try {
31967
- mkdirSync(dirname(file), { recursive: true });
31968
- writeFileSync(tmp, data, { encoding: "utf8" });
31969
- renameSync(tmp, file);
31970
- return true;
31971
- } catch {
31972
- try {
31973
- unlinkSync(tmp);
31974
- } catch {}
31975
- return false;
31976
- }
32747
+ return tryWriteFileAtomic(file, data);
31977
32748
  }
31978
32749
  function accountTokenFilePath(account, homeDir) {
31979
32750
  const home = account.dir ? account.dir : homeDir;
@@ -32077,9 +32848,11 @@ var WaitTimeoutError = class extends Error {
32077
32848
  };
32078
32849
  /** The slot cannot be handed over safely; the caller must abort the run. */
32079
32850
  var SlotUnavailableError = class extends Error {
32080
- constructor(message) {
32851
+ target;
32852
+ constructor(message, target = "account") {
32081
32853
  super(message);
32082
32854
  this.name = "SlotUnavailableError";
32855
+ this.target = target;
32083
32856
  }
32084
32857
  };
32085
32858
  //#endregion
@@ -32602,7 +33375,7 @@ var SlotAcquire = class {
32602
33375
  const accountRaw = readTokenFileRaw(accountFile);
32603
33376
  if (!primary) {
32604
33377
  this.done();
32605
- throw new SlotUnavailableError("Cannot verify the primary Antigravity credential, so the Windows credential slot cannot be handed over safely. Sign the primary account in again, then retry.");
33378
+ throw new SlotUnavailableError("Cannot verify the primary Antigravity credential, so the Windows credential slot cannot be handed over safely. Sign the primary account in again, then retry.", "primary");
32606
33379
  }
32607
33380
  if (this.isPrimarySlot) return this.primaryLease(primary);
32608
33381
  await this.drainPrimaryFastRuns();
@@ -32774,22 +33547,13 @@ function defaultSlotIo() {
32774
33547
  async function identifyCredential(raw, proxyUrl) {
32775
33548
  const doc = parseCredentialDoc(raw);
32776
33549
  if (!doc) return void 0;
32777
- const probe = async (accessToken) => {
32778
- try {
32779
- const res = await agyFetch("https://www.googleapis.com/oauth2/v1/userinfo", { headers: { Authorization: "Bearer " + accessToken } }, proxyUrl);
32780
- if (!res.ok) return void 0;
32781
- return (await res.json()).email;
32782
- } catch {
32783
- return;
32784
- }
32785
- };
32786
33550
  if (doc.accessToken && (!doc.expiryMs || doc.expiryMs > Date.now() + 6e4)) {
32787
- const email = await probe(doc.accessToken);
33551
+ const email = await fetchUserEmail(doc.accessToken, proxyUrl);
32788
33552
  if (email) return email;
32789
33553
  }
32790
33554
  if (doc.refreshToken) try {
32791
33555
  const refreshed = await refreshTokens(doc.refreshToken, proxyUrl);
32792
- if (refreshed?.access_token) return await probe(refreshed.access_token);
33556
+ if (refreshed?.access_token) return await fetchUserEmail(refreshed.access_token, proxyUrl);
32793
33557
  } catch {
32794
33558
  return;
32795
33559
  }
@@ -32890,6 +33654,12 @@ function noteFailure(log, what, err) {
32890
33654
  if (code === "ENOENT" || code === "EACCES" || code === "EPERM" || code === "EBUSY") return;
32891
33655
  log?.(`subagent tracker: ${what} — ${String(err)}`);
32892
33656
  }
33657
+ function isActiveSubagentState(state) {
33658
+ return state === void 0 || state === "" || state === "SUBAGENT_STATE_ALIVE";
33659
+ }
33660
+ function isTerminalTranscriptStatus(status) {
33661
+ return typeof status === "string" && /^(ERROR|FAILED|CANCELED|CANCELLED)$/i.test(status.trim());
33662
+ }
32893
33663
  function stripQuotes(s) {
32894
33664
  if (s.startsWith("\"") && s.endsWith("\"") || s.startsWith("'") && s.endsWith("'")) return s.slice(1, -1);
32895
33665
  return s;
@@ -32969,15 +33739,37 @@ var SubagentTracker = class {
32969
33739
  if (cid === "" || cid === this.conversationId) return;
32970
33740
  this.conversationId = cid;
32971
33741
  this.brainDir = null;
32972
- if (this.active) this.poll();
33742
+ this.baselined = false;
33743
+ if (this.active) {
33744
+ if (this.opts.resumed === true) {
33745
+ this.baselined = true;
33746
+ this.baselineExisting();
33747
+ }
33748
+ this.poll();
33749
+ }
32973
33750
  }
33751
+ baselined = false;
32974
33752
  start() {
32975
33753
  if (this.active) return;
32976
33754
  this.active = true;
33755
+ if (this.opts.resumed === true && !this.baselined && this.conversationId !== "") {
33756
+ this.baselined = true;
33757
+ this.baselineExisting();
33758
+ }
32977
33759
  this.poll();
32978
33760
  this.timer = setInterval(() => this.poll(), this.pollIntervalMs);
32979
33761
  this.timer.unref?.();
32980
33762
  }
33763
+ baselineExisting() {
33764
+ try {
33765
+ if (!this.brainDir) this.brainDir = findBrainDir(this.conversationId, this.accountHome);
33766
+ if (!this.brainDir) return;
33767
+ this.scanSubagentsForConv(this.conversationId, true);
33768
+ for (const cid of Array.from(this.trackedSubagents.keys())) this.scanSubagentsForConv(cid, true);
33769
+ } catch (err) {
33770
+ noteFailure(this.opts.log, "baseline", err);
33771
+ }
33772
+ }
32981
33773
  stop() {
32982
33774
  this.active = false;
32983
33775
  if (this.timer) {
@@ -32995,14 +33787,26 @@ var SubagentTracker = class {
32995
33787
  if (!this.brainDir) return;
32996
33788
  const convsToScan = [this.conversationId, ...Array.from(this.trackedSubagents.keys())];
32997
33789
  for (const cid of convsToScan) this.scanSubagentsForConv(cid);
32998
- for (const sub of this.trackedSubagents.values()) this.pollSubagentTranscript(sub);
33790
+ for (const sub of this.trackedSubagents.values()) if (!sub.terminal) this.pollSubagentTranscript(sub);
32999
33791
  } catch (err) {
33000
33792
  noteFailure(this.opts.log, "poll", err);
33001
33793
  } finally {
33002
33794
  this.polling = false;
33003
33795
  }
33004
33796
  }
33005
- scanSubagentsForConv(cid) {
33797
+ emitSubagentEvent(stepKey, text, raw) {
33798
+ if (this.seenStepKeys.has(stepKey)) return;
33799
+ this.seenStepKeys.add(stepKey);
33800
+ this.opts.onEvent({
33801
+ kind: "step",
33802
+ stepKey,
33803
+ stepKind: "subagent",
33804
+ text,
33805
+ raw
33806
+ });
33807
+ this.opts.noteActivity?.();
33808
+ }
33809
+ scanSubagentsForConv(cid, baselineOnly = false) {
33006
33810
  const bDir = cid === this.conversationId ? this.brainDir : findBrainDir(cid, this.accountHome);
33007
33811
  if (!bDir) return;
33008
33812
  const subagentsDir = join(bDir, ".system_generated", "subagents");
@@ -33020,32 +33824,52 @@ var SubagentTracker = class {
33020
33824
  const raw = readFileSync(fullPath, "utf8");
33021
33825
  const obj = JSON.parse(raw);
33022
33826
  const subId = typeof obj?.conversationId === "string" ? obj.conversationId : f.replace(/\.json$/, "");
33023
- if (!subId || this.trackedSubagents.has(subId)) continue;
33827
+ if (!subId) continue;
33828
+ const rawState = typeof obj?.state === "string" && obj.state.trim() !== "" ? obj.state.trim() : void 0;
33829
+ const existing = this.trackedSubagents.get(subId);
33830
+ if (existing) {
33831
+ if (!existing.terminal && rawState !== void 0 && rawState !== existing.state && !isActiveSubagentState(rawState)) {
33832
+ this.pollSubagentTranscript(existing);
33833
+ existing.state = rawState;
33834
+ existing.terminal = true;
33835
+ const stateKey = `subagent-state-${subId}-${rawState}`;
33836
+ if (baselineOnly) this.seenStepKeys.add(stateKey);
33837
+ else this.emitSubagentEvent(stateKey, `[子代理 · ${existing.role}] 协同专员已停止 (${rawState})\n`, obj);
33838
+ }
33839
+ continue;
33840
+ }
33024
33841
  const desc = obj?.subagentDescriptor;
33025
33842
  const role = typeof desc?.role === "string" && desc.role !== "" ? desc.role : "专员";
33026
33843
  const typeName = typeof desc?.typeName === "string" && desc.typeName !== "" ? desc.typeName : "Subagent";
33844
+ const subBrainDir = findBrainDir(subId, this.accountHome) ?? join(bDir, "..", subId);
33845
+ const active = isActiveSubagentState(rawState);
33846
+ let initialOffset = 0;
33847
+ if (baselineOnly || !active) try {
33848
+ const logPath = join(subBrainDir, ".system_generated", "logs", "transcript.jsonl");
33849
+ const st = statSync(logPath);
33850
+ if (st.isFile()) initialOffset = st.size;
33851
+ } catch {
33852
+ initialOffset = 0;
33853
+ }
33027
33854
  const tracked = {
33028
33855
  conversationId: subId,
33029
33856
  role,
33030
33857
  typeName,
33031
- brainDir: findBrainDir(subId, this.accountHome) ?? join(bDir, "..", subId),
33032
- offset: 0,
33858
+ brainDir: subBrainDir,
33859
+ state: rawState,
33860
+ terminal: !active,
33861
+ offset: initialOffset,
33862
+ decoder: new StringDecoder("utf8"),
33033
33863
  rest: "",
33034
33864
  lines: 0
33035
33865
  };
33036
33866
  this.trackedSubagents.set(subId, tracked);
33037
33867
  const spawnKey = `subagent-spawn-${subId}`;
33038
- if (!this.seenStepKeys.has(spawnKey)) {
33868
+ if (baselineOnly) this.seenStepKeys.add(spawnKey);
33869
+ else if (active) this.emitSubagentEvent(spawnKey, `[子代理 · ${role}] 已启动协同专员 (${typeName})\n`, obj);
33870
+ else {
33039
33871
  this.seenStepKeys.add(spawnKey);
33040
- const ev = {
33041
- kind: "step",
33042
- stepKey: spawnKey,
33043
- stepKind: "subagent",
33044
- text: `[子代理 · ${role}] 已启动协同专员 (${typeName})\n`,
33045
- raw: obj
33046
- };
33047
- this.opts.onEvent(ev);
33048
- this.opts.noteActivity?.();
33872
+ if (rawState !== void 0) this.emitSubagentEvent(`subagent-state-${subId}-${rawState}`, `[子代理 · ${role}] 协同专员未保持运行 (${rawState})\n`, obj);
33049
33873
  }
33050
33874
  } catch (err) {
33051
33875
  noteFailure(this.opts.log, `descriptor ${f}`, err);
@@ -33071,23 +33895,26 @@ var SubagentTracker = class {
33071
33895
  }
33072
33896
  if (size < sub.offset) {
33073
33897
  sub.offset = 0;
33898
+ sub.decoder = new StringDecoder("utf8");
33074
33899
  sub.rest = "";
33075
33900
  }
33076
33901
  if (size === sub.offset) return [];
33077
33902
  const length = size - sub.offset;
33078
33903
  const buffer = Buffer.allocUnsafe(length);
33904
+ let bytesRead = 0;
33079
33905
  try {
33080
33906
  const fd = openSync(logPath, "r");
33081
33907
  try {
33082
- readSync(fd, buffer, 0, length, sub.offset);
33908
+ bytesRead = readSync(fd, buffer, 0, length, sub.offset);
33083
33909
  } finally {
33084
33910
  closeSync(fd);
33085
33911
  }
33086
33912
  } catch {
33087
33913
  return [];
33088
33914
  }
33089
- sub.offset = size;
33090
- const parts = (sub.rest + buffer.toString("utf8")).split("\n");
33915
+ if (bytesRead <= 0) return [];
33916
+ sub.offset += bytesRead;
33917
+ const parts = (sub.rest + sub.decoder.write(buffer.subarray(0, bytesRead))).split("\n");
33091
33918
  sub.rest = parts.pop() ?? "";
33092
33919
  return parts.filter((line) => line.trim() !== "");
33093
33920
  }
@@ -33101,36 +33928,14 @@ var SubagentTracker = class {
33101
33928
  const tc = o.tool_calls[tcIdx];
33102
33929
  const toolName = typeof tc?.name === "string" ? tc.name : "";
33103
33930
  if (toolName === "") continue;
33104
- const k = `${baseKey}-tc-${tcIdx}`;
33105
- if (this.seenStepKeys.has(k)) continue;
33106
- this.seenStepKeys.add(k);
33107
- const ev = {
33108
- kind: "step",
33109
- stepKey: k,
33110
- stepKind: "subagent",
33111
- text: `${formatSubagentAction(sub.role, toolName, tc.args)}\n`,
33112
- raw: o
33113
- };
33114
- this.opts.onEvent(ev);
33115
- this.opts.noteActivity?.();
33931
+ const msg = formatSubagentAction(sub.role, toolName, tc.args);
33932
+ this.emitSubagentEvent(`${baseKey}-tc-${tcIdx}`, `${msg}\n`, o);
33116
33933
  }
33117
33934
  else if (o.type === "PLANNER_RESPONSE" && typeof o.content === "string" && o.content.trim() !== "") {
33118
- const k = `${baseKey}-content`;
33119
- if (this.seenStepKeys.has(k)) continue;
33120
- this.seenStepKeys.add(k);
33121
33935
  const firstLine = o.content.trim().split("\n")[0].replace(/^#+\s*/, "").slice(0, 100);
33122
- if (firstLine !== "") {
33123
- const ev = {
33124
- kind: "step",
33125
- stepKey: k,
33126
- stepKind: "subagent",
33127
- text: `[子代理 · ${sub.role}] 阶段进展: ${firstLine}\n`,
33128
- raw: o
33129
- };
33130
- this.opts.onEvent(ev);
33131
- this.opts.noteActivity?.();
33132
- }
33936
+ if (firstLine !== "") this.emitSubagentEvent(`${baseKey}-content`, `[子代理 · ${sub.role}] 阶段进展: ${firstLine}\n`, o);
33133
33937
  }
33938
+ if (isTerminalTranscriptStatus(o.status)) this.emitSubagentEvent(`${baseKey}-status`, `[子代理 · ${sub.role}] 执行异常/中止 (${o.status})\n`, o);
33134
33939
  } catch {}
33135
33940
  }
33136
33941
  };
@@ -33198,92 +34003,6 @@ function buildSpawnArgs(input, printTimeoutMinutes, log) {
33198
34003
  stdinPayload
33199
34004
  };
33200
34005
  }
33201
- /**
33202
- * Idle-budget + long-tool heartbeat state. While an agy tool step is ACTIVE the
33203
- * child is legitimately silent on stdout (maven compile, language-server
33204
- * build, …) — issue #33 — so the watchdog raises the idle budget; bare
33205
- * generation gets a bounded floor so a hung SSE stream can fail and rotate.
33206
- */
33207
- function createToolWatchdog(log, cfg) {
33208
- const openToolKeys = /* @__PURE__ */ new Set();
33209
- const openToolSince = /* @__PURE__ */ new Map();
33210
- const longToolIdleMinutes = cfg.longToolIdleMinutes > 0 ? cfg.longToolIdleMinutes : 0;
33211
- let printTimeoutMinutes = Math.max(longToolIdleMinutes > 0 ? longToolIdleMinutes : Math.ceil(cfg.timeoutMs / 6e4), Math.ceil(cfg.timeoutMs / 6e4));
33212
- if (cfg.maxTurnMinutes > 0 && printTimeoutMinutes > cfg.maxTurnMinutes) printTimeoutMinutes = cfg.maxTurnMinutes;
33213
- const longToolIdleMs = longToolIdleMinutes > 0 ? longToolIdleMinutes * 6e4 : cfg.timeoutMs;
33214
- const generationIdleMs = Math.max(cfg.timeoutMs, 9e5);
33215
- let runningProc = null;
33216
- let sawAnyEvent = false;
33217
- let lastOutputAt = 0;
33218
- const TOOL_HEARTBEAT_MS = 3e5;
33219
- let toolHeartbeat = null;
33220
- const apply = () => {
33221
- runningProc?.noteActivity(openToolKeys.size > 0 ? longToolIdleMs : generationIdleMs);
33222
- };
33223
- const stop = () => {
33224
- if (toolHeartbeat !== null) {
33225
- clearInterval(toolHeartbeat);
33226
- toolHeartbeat = null;
33227
- }
33228
- };
33229
- const start = () => {
33230
- if (toolHeartbeat !== null) return;
33231
- toolHeartbeat = setInterval(() => {
33232
- if (openToolKeys.size === 0 && !sawAnyEvent) {
33233
- stop();
33234
- return;
33235
- }
33236
- let oldest = Date.now();
33237
- for (const startedAt of openToolSince.values()) if (startedAt < oldest) oldest = startedAt;
33238
- if (openToolKeys.size === 0 && lastOutputAt > 0) oldest = lastOutputAt;
33239
- const mins = Math.max(1, Math.round((Date.now() - oldest) / 6e4));
33240
- log?.(openToolKeys.size > 0 ? "agy tool step still running: " + openToolKeys.size + " open, oldest " + mins + "m (idle budget " + Math.round(longToolIdleMs / 6e4) + "m) — the turn is waiting on agy" : "agy run still working: no new output for " + mins + "m (idle budget " + Math.round(longToolIdleMs / 6e4) + "m) — the turn is waiting on agy; press Stop to cancel");
33241
- }, TOOL_HEARTBEAT_MS);
33242
- toolHeartbeat.unref?.();
33243
- };
33244
- return {
33245
- printTimeoutMinutes,
33246
- attach: (proc) => {
33247
- runningProc = proc;
33248
- apply();
33249
- },
33250
- markEvent: () => {
33251
- sawAnyEvent = true;
33252
- lastOutputAt = Date.now();
33253
- start();
33254
- apply();
33255
- },
33256
- trackStep: (ev) => {
33257
- if (ev.kind !== "step") return;
33258
- if (ev.stepKind === "tool" && ev.tool !== void 0) {
33259
- if (!(ev.state === "DONE" || ev.state === "ERROR" || ev.state === "RUNNING" || ev.state === void 0 && (ev.tool.output !== void 0 || ev.tool.error !== void 0))) {
33260
- if (!openToolKeys.has(ev.stepKey)) {
33261
- openToolKeys.add(ev.stepKey);
33262
- openToolSince.set(ev.stepKey, Date.now());
33263
- apply();
33264
- start();
33265
- }
33266
- } else if (openToolKeys.delete(ev.stepKey)) {
33267
- openToolSince.delete(ev.stepKey);
33268
- apply();
33269
- if (openToolKeys.size === 0) stop();
33270
- }
33271
- } else if (ev.stepKind === "text" || ev.stepKind === "thinking") {
33272
- if (openToolKeys.size > 0) {
33273
- openToolKeys.clear();
33274
- openToolSince.clear();
33275
- apply();
33276
- stop();
33277
- }
33278
- }
33279
- },
33280
- stop: () => {
33281
- stop();
33282
- openToolKeys.clear();
33283
- openToolSince.clear();
33284
- }
33285
- };
33286
- }
33287
34006
  /** Create the recording, parser, HOME snapshot and tool watchdog for one run. */
33288
34007
  function createAttemptRecorder(deps, cfg, account, initialConversationId) {
33289
34008
  const rec = deps.runs.create();
@@ -33295,6 +34014,7 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId) {
33295
34014
  const watchdog = createToolWatchdog(deps.log, cfg);
33296
34015
  const tracker = new SubagentTracker({
33297
34016
  conversationId: initialConversationId,
34017
+ resumed: Boolean(initialConversationId),
33298
34018
  accountHome: rec.accountHome,
33299
34019
  log: deps.log,
33300
34020
  onEvent: (ev) => {
@@ -33438,11 +34158,9 @@ async function startAttemptProcess(deps, input, spawn, recorder, slot) {
33438
34158
  let spawned = false;
33439
34159
  try {
33440
34160
  if (account) {
33441
- const lastSpawn = deps.lastAccountSpawnTime.get(account.id) ?? 0;
33442
- const elapsed = Date.now() - lastSpawn;
33443
- const jitter = Math.floor(Math.random() * 300);
33444
- const targetInterval = deps.minSpawnIntervalMs + jitter;
33445
- if (elapsed < targetInterval) await abortableDelay(targetInterval - elapsed, signal, "request aborted before the agy process was spawned");
34161
+ const egressKey = pickProxy(account.proxyUrl, cfg.proxyUrl) || "__direct__";
34162
+ const delayMs = deps.spawnLimiter ? deps.spawnLimiter.reserveSpawnDelay(account.id, egressKey, deps.minSpawnIntervalMs) : Math.max(0, deps.minSpawnIntervalMs + Math.floor(Math.random() * 300) - (Date.now() - (deps.lastAccountSpawnTime.get(account.id) ?? 0)));
34163
+ if (delayMs > 0) await abortableDelay(delayMs, signal, "request aborted before the agy process was spawned");
33446
34164
  deps.lastAccountSpawnTime.set(account.id, Date.now());
33447
34165
  }
33448
34166
  const slotHandoff = slot.armHandoff();
@@ -33490,83 +34208,109 @@ function brief(s) {
33490
34208
  const flat = s.trim().replace(/\s+/g, " ");
33491
34209
  return flat.length > 300 ? flat.slice(0, 300) + "..." : flat;
33492
34210
  }
34211
+ function detailText(c, fallback = "") {
34212
+ return c.parser.stats.lastResultError ?? (c.outcome.stderrTail !== "" ? brief(c.outcome.stderrTail) : fallback);
34213
+ }
34214
+ function classifyPolicyOrQuota(c) {
34215
+ if (c.sawAuthFailure) return c.transportFailure ? {
34216
+ kind: "error",
34217
+ code: Err.NETWORK,
34218
+ message: "agy could not validate its Google login over the network (transport failure" + (c.keyringJitter ? "; its own log shows keyring auth timing out on the network, not a sign-out" : "") + ", not a sign-out) — retrying on another account. " + (c.rawErrText !== "" ? brief(c.rawErrText) : "")
34219
+ } : {
34220
+ kind: "error",
34221
+ code: Err.AUTH,
34222
+ message: "agy is not signed in — run /agy auth (or run agy once in a terminal) to login"
34223
+ };
34224
+ if (c.isRateLimit) {
34225
+ const bestMsg = detailText(c, "Rate limit or quota reached");
34226
+ const hard = looksLikeHardRateLimit(c.rawErrText);
34227
+ return {
34228
+ kind: "error",
34229
+ code: hard ? Err.RATE_LIMIT : Err.OVERLOADED,
34230
+ message: hard ? "Google Antigravity quota / rate limit reached: " + bestMsg : "Google Antigravity quota / rate limit reached (server capacity overloaded): " + bestMsg
34231
+ };
34232
+ }
34233
+ const resultErr = c.parser.stats.lastResultError ?? "";
34234
+ if (looksLikeContextWindowExceeded(c.rawErrText) || looksLikeContextWindowExceeded(resultErr)) return {
34235
+ kind: "error",
34236
+ code: Err.CONTEXT_WINDOW_EXCEEDED,
34237
+ message: "Google Antigravity context window exceeded: " + detailText(c, "Prompt exceeds context window limit")
34238
+ };
34239
+ if (!c.transportFailure && (looksLikeEligibilityFailure(c.rawErrText) || looksLikeEligibilityFailure(resultErr))) {
34240
+ const detail = detailText(c);
34241
+ return {
34242
+ kind: "error",
34243
+ code: Err.ELIGIBILITY,
34244
+ message: ELIGIBILITY_ERROR_HINT + (detail !== "" ? " (" + detail + ")" : "")
34245
+ };
34246
+ }
34247
+ if (!c.transportFailure && (looksLikeTosViolation(c.rawErrText) || looksLikeTosViolation(resultErr))) return {
34248
+ kind: "error",
34249
+ code: Err.AGY_ERROR,
34250
+ message: "Google Antigravity account suspended (TOS_VIOLATION): " + detailText(c, brief(c.rawErrText))
34251
+ };
34252
+ if (!c.transportFailure && (looksLikeValidationRequired(c.rawErrText) || looksLikeValidationRequired(resultErr))) return {
34253
+ kind: "error",
34254
+ code: Err.AGY_ERROR,
34255
+ message: "Google Antigravity account requires verification (VALIDATION_REQUIRED): " + detailText(c, brief(c.rawErrText))
34256
+ };
34257
+ if (looksLikeHeadlessPermissionDenial(c.rawErrText) || looksLikeHeadlessPermissionDenial(resultErr)) {
34258
+ const detail = detailText(c);
34259
+ return {
34260
+ kind: "error",
34261
+ code: Err.AGY_ERROR,
34262
+ message: HEADLESS_PERMISSION_ERROR_HINT + (detail !== "" ? " (" + detail + ")" : "")
34263
+ };
34264
+ }
34265
+ return null;
34266
+ }
34267
+ function classifyExitOrFallback(c) {
34268
+ if (c.outcome.code !== 0) {
34269
+ const detail = detailText(c);
34270
+ return c.transportFailure ? {
34271
+ kind: "error",
34272
+ code: Err.NETWORK,
34273
+ message: "agy hit a network error while talking to Google — the automatic retry usually succeeds. " + (detail !== "" ? detail : brief(c.rawErrText))
34274
+ } : {
34275
+ kind: "error",
34276
+ code: Err.PROCESS_EXIT,
34277
+ message: "agy exited with code " + c.outcome.code + (detail !== "" ? ": " + detail : "")
34278
+ };
34279
+ }
34280
+ if (c.transportFailure) return {
34281
+ kind: "error",
34282
+ code: Err.NETWORK,
34283
+ message: "agy hit a network error while talking to Google — the automatic retry usually succeeds. " + brief(c.rawErrText)
34284
+ };
34285
+ if (c.parser.stats.lastResultError) return {
34286
+ kind: "error",
34287
+ code: Err.AGY_ERROR,
34288
+ message: "agy reported an error: " + c.parser.stats.lastResultError
34289
+ };
34290
+ return {
34291
+ kind: "error",
34292
+ code: Err.INVALID_OUTPUT,
34293
+ message: "agy produced no result event (" + c.parser.stats.garbage + " unparseable lines)"
34294
+ };
34295
+ }
33493
34296
  function classifyFailure(c) {
33494
34297
  if (c.outcome.aborted) return {
33495
34298
  kind: "aborted",
33496
34299
  code: "ABORTED",
33497
34300
  message: "agy run aborted by caller"
33498
34301
  };
33499
- else if (c.outcome.capped) return {
34302
+ if (c.outcome.capped) return {
33500
34303
  kind: "error",
33501
34304
  code: Err.TIMEOUT,
33502
34305
  message: "agy turn exceeded maxTurnMinutes (" + c.cfg.maxTurnMinutes + " min) — the agy process tree was terminated. Re-send to continue. 本轮超过 maxTurnMinutes 上限,已终止 agy 进程树"
33503
34306
  };
33504
- else if (c.outcome.timedOut) return {
34307
+ if (c.outcome.timedOut) return {
33505
34308
  kind: "error",
33506
34309
  code: Err.TIMEOUT,
33507
34310
  message: "agy run was idle for " + c.cfg.timeoutMs + "ms without output" + (c.silentTimeout ? " — agy never emitted a single event; it is likely unable to reach Google (check proxy/network). 无法连接 Google,请检查代理或网络配置" : "")
33508
34311
  };
33509
- else if (c.outcome.idleGraceTerminated) return null;
33510
- else if (!c.consumable) {
33511
- if (c.sawAuthFailure) return c.transportFailure ? {
33512
- kind: "error",
33513
- code: Err.NETWORK,
33514
- message: "agy could not validate its Google login over the network (transport failure" + (c.keyringJitter ? "; its own log shows keyring auth timing out on the network, not a sign-out" : "") + ", not a sign-out) — retrying on another account. " + (c.rawErrText !== "" ? brief(c.rawErrText) : "")
33515
- } : {
33516
- kind: "error",
33517
- code: Err.AUTH,
33518
- message: "agy is not signed in — run /agy auth (or run agy once in a terminal) to login"
33519
- };
33520
- else if (c.isRateLimit) {
33521
- const bestMsg = c.parser.stats.lastResultError || (c.outcome.stderrTail ? brief(c.outcome.stderrTail) : "Rate limit or quota reached");
33522
- const hard = looksLikeHardRateLimit(c.rawErrText);
33523
- return {
33524
- kind: "error",
33525
- code: hard ? Err.RATE_LIMIT : Err.OVERLOADED,
33526
- message: hard ? "Google Antigravity quota / rate limit reached: " + bestMsg : "Google Antigravity quota / rate limit reached (server capacity overloaded): " + bestMsg
33527
- };
33528
- } else if (looksLikeContextWindowExceeded(c.rawErrText) || looksLikeContextWindowExceeded(c.parser.stats.lastResultError ?? "")) {
33529
- const detail = c.parser.stats.lastResultError || (c.outcome.stderrTail !== "" ? brief(c.outcome.stderrTail) : "Prompt exceeds context window limit");
33530
- return {
33531
- kind: "error",
33532
- code: Err.CONTEXT_WINDOW_EXCEEDED,
33533
- message: "Google Antigravity context window exceeded: " + detail
33534
- };
33535
- } else if (!c.transportFailure && (looksLikeEligibilityFailure(c.rawErrText) || looksLikeEligibilityFailure(c.parser.stats.lastResultError ?? ""))) {
33536
- const detail = c.parser.stats.lastResultError ?? (c.outcome.stderrTail !== "" ? brief(c.outcome.stderrTail) : "");
33537
- return {
33538
- kind: "error",
33539
- code: Err.ELIGIBILITY,
33540
- message: ELIGIBILITY_ERROR_HINT + (detail !== "" ? " (" + detail + ")" : "")
33541
- };
33542
- } else if (c.outcome.code !== 0) {
33543
- const detail = c.parser.stats.lastResultError ?? (c.outcome.stderrTail !== "" ? brief(c.outcome.stderrTail) : "");
33544
- return c.transportFailure ? {
33545
- kind: "error",
33546
- code: Err.NETWORK,
33547
- message: "agy hit a network error while talking to Google — the automatic retry usually succeeds. " + (detail !== "" ? detail : brief(c.rawErrText))
33548
- } : {
33549
- kind: "error",
33550
- code: Err.PROCESS_EXIT,
33551
- message: "agy exited with code " + c.outcome.code + (detail !== "" ? ": " + detail : "")
33552
- };
33553
- } else if (c.transportFailure) return {
33554
- kind: "error",
33555
- code: Err.NETWORK,
33556
- message: "agy hit a network error while talking to Google — the automatic retry usually succeeds. " + brief(c.rawErrText)
33557
- };
33558
- else if (c.parser.stats.lastResultError) return {
33559
- kind: "error",
33560
- code: Err.AGY_ERROR,
33561
- message: "agy reported an error: " + c.parser.stats.lastResultError
33562
- };
33563
- else return {
33564
- kind: "error",
33565
- code: Err.INVALID_OUTPUT,
33566
- message: "agy produced no result event (" + c.parser.stats.garbage + " unparseable lines)"
33567
- };
33568
- }
33569
- return null;
34312
+ if (c.outcome.idleGraceTerminated || c.consumable) return null;
34313
+ return classifyPolicyOrQuota(c) ?? classifyExitOrFallback(c);
33570
34314
  }
33571
34315
  /**
33572
34316
  * Await `work` while periodically yielding a SESSION-VISIBLE notice.
@@ -33753,7 +34497,8 @@ async function* dispatchCredentialSlot(deps, input) {
33753
34497
  release?.();
33754
34498
  release = null;
33755
34499
  if (e instanceof SlotUnavailableError && currentAccount && deps.pool) {
33756
- deps.pool.markAuthRequired(currentAccount.id, e.message);
34500
+ const isPrimaryAccount = Boolean(currentAccount.systemHome) || !currentAccount.dir;
34501
+ if (e.target !== "primary" || isPrimaryAccount) deps.pool.markAuthRequired(currentAccount.id, e.message);
33757
34502
  const next = attempt < maxDispatchAttempts ? deps.pool.selectAccount(input.family, input.activeModel) : void 0;
33758
34503
  if (next && next.id !== currentAccount.id) {
33759
34504
  deps.log?.(`slot unavailable on ${currentAccount.id}: ${e.message} — failed over to ${next.id}`);
@@ -33803,8 +34548,15 @@ async function* dispatchCredentialSlot(deps, input) {
33803
34548
  function classifyRun(input) {
33804
34549
  const { cfg, outcome, parser, rec, runLogHome, runLogsBefore } = input;
33805
34550
  const r = rec.getResultEvent();
33806
- const consumable = r !== null && (r.ok || r.response !== "");
33807
- const rawErrText = [outcome.stderrTail, parser.stats.lastResultError].filter(Boolean).join(" ");
34551
+ const u = rec.lastUsage ?? rec.finalUsage({});
34552
+ const zeroUsageTos = r !== null && (u?.input_tokens ?? 0) === 0 && (u?.output_tokens ?? 0) === 0 && looksLikeTosViolation(r.response);
34553
+ const errorResponseTos = r !== null && !r.ok && looksLikeTosViolation(r.response);
34554
+ const consumable = r !== null && (r.ok || r.response !== "") && !zeroUsageTos && !errorResponseTos;
34555
+ const rawErrText = [
34556
+ outcome.stderrTail,
34557
+ parser.stats.lastResultError,
34558
+ !consumable && r && (!r.ok || zeroUsageTos) ? r.response : ""
34559
+ ].filter(Boolean).join(" ");
33808
34560
  const isRateLimit = looksLikeRateLimit(rawErrText);
33809
34561
  const runLogText = readAgyRunLogText(runLogHome, runLogsBefore);
33810
34562
  const keyringJitter = looksLikeAuthVerificationJitter(runLogText);
@@ -34001,12 +34753,11 @@ var AgyAdapter = class extends LlmAdapter {
34001
34753
  /** accountId -> timestamp of last spawn for spacing throttling */
34002
34754
  lastAccountSpawnTime = /* @__PURE__ */ new Map();
34003
34755
  minSpawnIntervalMs = 500;
34004
- /** Global sliding window timestamps for batch rate-limiting protection */
34005
- requestTimestamps = [];
34756
+ spawnLimiter = new SpawnLimiter();
34006
34757
  constructor(deps) {
34007
34758
  super();
34008
34759
  this.deps = deps;
34009
- if (deps.pool && deps.catalog && typeof deps.pool.setCatalog === "function") deps.pool.setCatalog(deps.catalog);
34760
+ deps.pool?.setCatalog?.(deps.catalog);
34010
34761
  this.effortPolicy = new EffortPolicy(() => this.deps.effortUnsupported?.(), this.deps.log, this.deps.onEffortUnsupported);
34011
34762
  }
34012
34763
  /** Models currently known to reject `--effort` (persisted seed + learned). */
@@ -34023,6 +34774,10 @@ var AgyAdapter = class extends LlmAdapter {
34023
34774
  }
34024
34775
  warnOnce(key, msg) {
34025
34776
  if (this.warnedKeys.has(key)) return;
34777
+ if (this.warnedKeys.size >= 512) {
34778
+ const oldest = this.warnedKeys.values().next().value;
34779
+ if (oldest !== void 0) this.warnedKeys.delete(oldest);
34780
+ }
34026
34781
  this.warnedKeys.add(key);
34027
34782
  this.deps.log?.("WARNING: " + msg);
34028
34783
  }
@@ -34185,30 +34940,26 @@ var AgyAdapter = class extends LlmAdapter {
34185
34940
  }
34186
34941
  const messages = options.messages;
34187
34942
  if (!isAux && cfg.rateLimitPerMinute > 0) {
34188
- const now = Date.now();
34189
- const windowStart = now - 6e4;
34190
- while (this.requestTimestamps.length > 0 && this.requestTimestamps[0] < windowStart) this.requestTimestamps.shift();
34191
- if (this.requestTimestamps.length >= cfg.rateLimitPerMinute) {
34192
- const delayMs = this.requestTimestamps[0] + 6e4 - now;
34193
- if (delayMs > 0) await new Promise((resolve, reject) => {
34194
- const timer = setTimeout(() => {
34195
- options.signal?.removeEventListener("abort", onAbort);
34196
- resolve();
34197
- }, delayMs);
34198
- const onAbort = () => {
34199
- clearTimeout(timer);
34200
- reject(new LlmError("aborted during rate-limit spacing", Err.AGY_ERROR));
34201
- };
34202
- options.signal?.addEventListener("abort", onAbort, { once: true });
34203
- });
34204
- }
34205
- this.requestTimestamps.push(Date.now());
34943
+ const { delayMs, slotAt } = this.spawnLimiter.reserveRateLimitSlot(cfg.rateLimitPerMinute);
34944
+ if (delayMs > 0) await new Promise((resolve, reject) => {
34945
+ const timer = setTimeout(() => {
34946
+ options.signal?.removeEventListener("abort", onAbort);
34947
+ resolve();
34948
+ }, delayMs);
34949
+ const onAbort = () => {
34950
+ clearTimeout(timer);
34951
+ this.spawnLimiter.cancelRateLimitSlot(slotAt);
34952
+ reject(new LlmError("aborted during rate-limit spacing", Err.AGY_ERROR));
34953
+ };
34954
+ options.signal?.addEventListener("abort", onAbort, { once: true });
34955
+ });
34206
34956
  }
34207
34957
  const selection = await selectSessionAccount({
34208
34958
  deps: {
34209
34959
  ...this.deps.pool === void 0 ? {} : { pool: this.deps.pool },
34210
34960
  store: this.deps.store,
34211
- ...this.deps.syncSessionModel === void 0 ? {} : { syncSessionModel: (id, m, effort) => this.deps.syncSessionModel?.(id, m, effort) }
34961
+ ...this.deps.syncSessionModel === void 0 ? {} : { syncSessionModel: (id, m, effort) => this.deps.syncSessionModel?.(id, m, effort) },
34962
+ ...this.deps.refreshQuota === void 0 ? {} : { refreshQuota: this.deps.refreshQuota }
34212
34963
  },
34213
34964
  cfg,
34214
34965
  model,
@@ -34329,7 +35080,8 @@ var AgyAdapter = class extends LlmAdapter {
34329
35080
  clearRateLimitFailover: (key) => this.failover.clearRateLimit(key),
34330
35081
  sharesSingleEgress: () => this.sharesSingleEgress(),
34331
35082
  lastAccountSpawnTime: this.lastAccountSpawnTime,
34332
- minSpawnIntervalMs: this.minSpawnIntervalMs
35083
+ minSpawnIntervalMs: this.minSpawnIntervalMs,
35084
+ spawnLimiter: this.spawnLimiter
34333
35085
  }, {
34334
35086
  cfg,
34335
35087
  bin,