dsh-agy-link 0.6.34 → 0.6.36

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 {
@@ -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) {
@@ -5733,27 +6016,6 @@ async function deliverContext(digest, sessionKey, extraAddDirs, cfg) {
5733
6016
  return digest;
5734
6017
  }
5735
6018
  //#endregion
5736
- //#region src/common/atomic-write.ts
5737
- let seq = 0;
5738
- /** Unique temp path beside `file` (same directory, so rename stays atomic). */
5739
- function atomicTmpPath(file) {
5740
- const rand = Math.random().toString(36).slice(2, 8);
5741
- return file + "." + process.pid + "." + (seq++).toString(36) + "." + rand + ".tmp";
5742
- }
5743
- /** Write `data` to `file` atomically; on any failure remove the temp file. */
5744
- function writeFileAtomicSync(file, data) {
5745
- const tmp = atomicTmpPath(file);
5746
- try {
5747
- writeFileSync(tmp, data, "utf8");
5748
- renameSync(tmp, file);
5749
- } catch (err) {
5750
- try {
5751
- if (existsSync(tmp)) unlinkSync(tmp);
5752
- } catch {}
5753
- throw err;
5754
- }
5755
- }
5756
- //#endregion
5757
6019
  //#region src/host/sessions.ts
5758
6020
  var SessionStore = class {
5759
6021
  file;
@@ -5762,18 +6024,55 @@ var SessionStore = class {
5762
6024
  dirty = /* @__PURE__ */ new Set();
5763
6025
  /** Keys deleted by THIS process since the last persist. */
5764
6026
  removed = /* @__PURE__ */ new Set();
6027
+ lastMtimeMs = 0;
5765
6028
  constructor(file) {
5766
6029
  this.file = file;
5767
6030
  this.load();
5768
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
+ }
5769
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() {
5770
6060
  try {
5771
6061
  if (!existsSync(this.file)) return;
5772
- const v = JSON.parse(readFileSync(this.file, "utf8"));
5773
- 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
+ }
5774
6072
  } catch {}
5775
6073
  }
5776
6074
  get(key) {
6075
+ this.reloadIfChanged();
5777
6076
  return this.data[key];
5778
6077
  }
5779
6078
  set(key, b) {
@@ -5789,15 +6088,44 @@ var SessionStore = class {
5789
6088
  this.persist();
5790
6089
  }
5791
6090
  clear() {
6091
+ this.reloadIfChanged();
5792
6092
  for (const key of Object.keys(this.data)) this.removed.add(key);
5793
6093
  this.data = {};
5794
6094
  this.dirty.clear();
5795
6095
  this.persist();
5796
6096
  }
5797
6097
  all() {
6098
+ this.reloadIfChanged();
5798
6099
  return this.data;
5799
6100
  }
5800
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
+ /**
5801
6129
  * Purge bindings associated with accounts that no longer exist in the pool.
5802
6130
  * Prevents deleted account ids from lingering in sessions.json.
5803
6131
  */
@@ -5838,9 +6166,17 @@ var SessionStore = class {
5838
6166
  for (const key of this.removed) delete merged[key];
5839
6167
  for (const key of this.dirty) {
5840
6168
  const b = this.data[key];
5841
- 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
+ }
5842
6173
  }
5843
- 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();
5844
6180
  this.data = merged;
5845
6181
  this.dirty.clear();
5846
6182
  this.removed.clear();
@@ -5966,15 +6302,17 @@ function mergeSentImageIds(existing, added, max = 64) {
5966
6302
  //#region src/provider/account-selection.ts
5967
6303
  /** Upper bound on the self-heal refresh so a slow network cannot stall a turn. */
5968
6304
  const MODEL_HEAL_TIMEOUT_MS = 2e4;
5969
- /** Session affinity: reuse the account this session last ran on, if eligible. */
6305
+ /** Session affinity: reuse the account this session last ran on, if eligible and not superseded by a manual switch. */
5970
6306
  function stickyAccount(deps, family, sessionKey, model) {
5971
6307
  const pool = deps.pool;
5972
6308
  if (pool === void 0 || sessionKey === "") return void 0;
6309
+ const manualPinAt = pool.getPoolData().manualPinAt ?? 0;
5973
6310
  const prefix = `${sessionKey}:`;
5974
6311
  let mostRecent;
5975
6312
  let latestUpdated = -1;
5976
6313
  for (const [k, b] of Object.entries(deps.store.all())) {
5977
6314
  if (!k.startsWith(prefix) || b.updatedAt <= latestUpdated) continue;
6315
+ if (manualPinAt > 0 && b.updatedAt < manualPinAt) continue;
5978
6316
  const boundAcc = pool.getAccount(k.slice(prefix.length));
5979
6317
  if (boundAcc !== void 0) {
5980
6318
  mostRecent = boundAcc;
@@ -6075,7 +6413,10 @@ async function selectSessionAccount(input) {
6075
6413
  if (pool !== void 0 && !isAux && sessionKey !== "" && process.platform === "win32" && cfg.parallelSameAccount) account = pool.selectAccount(family, activeModel) ?? void 0;
6076
6414
  if (account === void 0 && pool !== void 0 && !isAux && sessionKey !== "") account = stickyAccount(deps, family, sessionKey, activeModel);
6077
6415
  if (account === void 0 && pool !== void 0) account = pool.selectAccount(family, activeModel) ?? void 0;
6078
- 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
+ }
6079
6420
  if (account === void 0 && pool !== void 0 && pool.getAccounts().length > 0) {
6080
6421
  if (cfg.autoFallbackModel) {
6081
6422
  const fb = crossFamilyFallback(deps, family);
@@ -6431,6 +6772,24 @@ const SUBAGENT_COLLAB_TOOLS = /* @__PURE__ */ new Set([
6431
6772
  "run_workflow",
6432
6773
  "swarm"
6433
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
+ }
6434
6793
  /**
6435
6794
  * Idle-budget + long-tool heartbeat state. While an agy tool step is ACTIVE the
6436
6795
  * child is legitimately silent on stdout (maven compile, language-server
@@ -6440,11 +6799,7 @@ const SUBAGENT_COLLAB_TOOLS = /* @__PURE__ */ new Set([
6440
6799
  function createToolWatchdog(log, cfg) {
6441
6800
  const openToolKeys = /* @__PURE__ */ new Set();
6442
6801
  const openToolSince = /* @__PURE__ */ new Map();
6443
- const longToolIdleMinutes = cfg.longToolIdleMinutes > 0 ? cfg.longToolIdleMinutes : 0;
6444
- let printTimeoutMinutes = Math.max(longToolIdleMinutes > 0 ? longToolIdleMinutes : Math.ceil(cfg.timeoutMs / 6e4), Math.ceil(cfg.timeoutMs / 6e4));
6445
- if (cfg.maxTurnMinutes > 0 && printTimeoutMinutes > cfg.maxTurnMinutes) printTimeoutMinutes = cfg.maxTurnMinutes;
6446
- const longToolIdleMs = longToolIdleMinutes > 0 ? longToolIdleMinutes * 6e4 : cfg.timeoutMs;
6447
- const generationIdleMs = Math.max(cfg.timeoutMs, 9e5);
6802
+ const { printTimeoutMinutes, longToolIdleMs, generationIdleMs } = resolveWatchdogBudgets(cfg);
6448
6803
  let runningProc = null;
6449
6804
  let awaitingSubagent = false;
6450
6805
  let sawAnyEvent = false;
@@ -6496,8 +6851,8 @@ function createToolWatchdog(log, cfg) {
6496
6851
  trackStep: (ev) => {
6497
6852
  if (ev.kind !== "step") return;
6498
6853
  if (ev.stepKind === "tool" && ev.tool !== void 0) {
6499
- if (SUBAGENT_COLLAB_TOOLS.has(ev.tool.name)) setAwaitingSubagent(true);
6500
- if (!(ev.state === "DONE" || ev.state === "ERROR" || ev.state === "RUNNING" || ev.state === void 0 && (ev.tool.output !== void 0 || ev.tool.error !== void 0))) {
6854
+ if (SUBAGENT_COLLAB_TOOLS.has(ev.tool.name)) setAwaitingSubagent(!isStepFailedOrCanceled(ev));
6855
+ if (!isToolStepCompleted(ev)) {
6501
6856
  if (!openToolKeys.has(ev.stepKey)) {
6502
6857
  openToolKeys.add(ev.stepKey);
6503
6858
  openToolSince.set(ev.stepKey, Date.now());
@@ -6800,8 +7155,11 @@ function classifyEvent(obj, seq) {
6800
7155
  const text = delta !== void 0 ? delta : extractText(src);
6801
7156
  const stateV = pick(src, ["state"]);
6802
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";
6803
7159
  if (stateV === "RUNNING" && toolInfo && toolInfo.output === void 0 && text !== "") toolInfo.output = text;
6804
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;
6805
7163
  return {
6806
7164
  kind: "step",
6807
7165
  stepKey,
@@ -6811,7 +7169,8 @@ function classifyEvent(obj, seq) {
6811
7169
  ...toolInfo !== void 0 ? { tool: toolInfo } : {},
6812
7170
  ...typeof stateV === "string" ? { state: stateV } : {},
6813
7171
  ...usageRaw && typeof usageRaw === "object" ? { usage: parseUsage(usageRaw) } : {},
6814
- raw: o
7172
+ ...typeof convIdRaw === "string" && convIdRaw !== "" ? { conversationId: convIdRaw } : {},
7173
+ ...isTextFragment ? {} : { raw: o }
6815
7174
  };
6816
7175
  }
6817
7176
  if (evt === "result" || evt === "done" || evt === "final") {
@@ -6952,45 +7311,94 @@ function agyHomeDirFor(account) {
6952
7311
  function agyLogDir(homeDir) {
6953
7312
  return join(homeDir, ".gemini", "antigravity-cli", "log");
6954
7313
  }
6955
- /** 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
+ */
6956
7320
  function snapshotAgyLogs(homeDir) {
6957
7321
  const dir = agyLogDir(homeDir);
7322
+ const out = /* @__PURE__ */ new Map();
6958
7323
  try {
6959
- return new Set(readdirSync(dir).filter((f) => f.startsWith("cli-") && f.endsWith(".log")));
6960
- } catch {
6961
- return /* @__PURE__ */ new Set();
6962
- }
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;
6963
7334
  }
6964
7335
  /** Upper bound so one pathological log cannot balloon the failure path. */
6965
7336
  const MAX_LOG_BYTES = 262144;
6966
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
+ }
6967
7354
  /**
6968
- * Concatenated text of the log files THIS run created (present now, absent
6969
- * 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
6970
7357
  * readable log — callers must treat that as "no evidence", never as proof
6971
7358
  * either way.
6972
7359
  */
6973
7360
  function readAgyRunLogText(homeDir, before) {
6974
7361
  const dir = agyLogDir(homeDir);
6975
- let names;
7362
+ let entries;
6976
7363
  try {
6977
7364
  if (!existsSync(dir)) return "";
6978
- names = readdirSync(dir).filter((f) => f.startsWith("cli-") && f.endsWith(".log") && !before.has(f)).map((f) => ({
6979
- f,
6980
- m: statSync(join(dir, f)).mtimeMs
6981
- })).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);
6982
7389
  } catch {
6983
7390
  return "";
6984
7391
  }
6985
7392
  const parts = [];
6986
7393
  let budget = MAX_LOG_BYTES;
6987
- for (const name of names) {
7394
+ for (const entry of entries) {
6988
7395
  if (budget <= 0) break;
6989
7396
  try {
6990
- const text = readFileSync(join(dir, name), "utf8");
6991
- const slice = text.length > budget ? text.slice(-budget) : text;
6992
- parts.push(slice);
6993
- 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
+ }
6994
7402
  } catch {}
6995
7403
  }
6996
7404
  return parts.join("\n");
@@ -7046,6 +7454,66 @@ function defaultPoolDir(home) {
7046
7454
  }
7047
7455
  return join(effectiveHome, ".dsh", "agy-accounts");
7048
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
+ }
7049
7517
  /**
7050
7518
  * True when a family's cached quota snapshot benches the account.
7051
7519
  *
@@ -7083,7 +7551,7 @@ function explainIneligibility(acc, family, now, pool, model) {
7083
7551
  if (!acc.enabled) return "disabled";
7084
7552
  if (acc.authRequired) return "auth";
7085
7553
  if (family === "argon" && !accountHasArgon(acc, pool)) return "unsupported";
7086
- 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";
7087
7555
  const cd = acc.cooldowns?.[family];
7088
7556
  if (cd && cd.cooldownUntil > now) return "cooldown";
7089
7557
  if (isQuotaBenched(acc, family, now)) return "quota";
@@ -7095,12 +7563,17 @@ function explainIneligibility(acc, family, now, pool, model) {
7095
7563
  function isAccountEligible(acc, family, now, pool, model) {
7096
7564
  return explainIneligibility(acc, family, now, pool, model) === null;
7097
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;
7098
7571
  /**
7099
7572
  * Next moment this account's quota state refreshes for one family: the
7100
7573
  * sooner of the 5h window reset and the weekly cap reset. NaN when unknown.
7101
7574
  */
7102
7575
  function nextQuotaResetAt(acc, family) {
7103
- const q = acc.quotas?.[family];
7576
+ const q = effectiveFamilyQuota(acc, family);
7104
7577
  const stamps = [q?.resetTime, q?.weeklyResetTime].filter((v) => typeof v === "string" && v !== "").map((v) => Date.parse(v)).filter((t) => !Number.isNaN(t));
7105
7578
  return stamps.length === 0 ? NaN : Math.min(...stamps);
7106
7579
  }
@@ -7114,18 +7587,24 @@ function cyclicDistance(accounts, fromId, id) {
7114
7587
  if (start === -1) return idx;
7115
7588
  return (idx - start + total) % total;
7116
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
+ }
7117
7597
  /**
7118
- * "Use it or lose it" rotation order.
7119
- * Priority 1: Weekly quota expiring soonest (least remaining time until weeklyResetTime).
7120
- * Priority 2: 5-hour quota expiring soonest (least remaining time until resetTime).
7121
- * Priority 3: Cyclic distance from `fromId` (or pool order).
7122
- *
7123
- * `accounts` is the pool order used for cycle distance; `now` is threaded in so
7124
- * 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).
7125
7604
  */
7126
7605
  function orderByExpiry(accounts, candidates, family, fromId, now) {
7127
7606
  return candidates.map((acc, index) => {
7128
- const q = acc.quotas?.[family];
7607
+ const q = effectiveFamilyQuota(acc, family);
7129
7608
  const weeklyMs = q?.weeklyResetTime ? Date.parse(q.weeklyResetTime) : NaN;
7130
7609
  const fiveHourMs = q?.resetTime ? Date.parse(q.resetTime) : NaN;
7131
7610
  const weeklyRemaining = !Number.isNaN(weeklyMs) ? Math.max(0, weeklyMs - now) : Number.POSITIVE_INFINITY;
@@ -7136,15 +7615,19 @@ function orderByExpiry(accounts, candidates, family, fromId, now) {
7136
7615
  weeklyRemaining,
7137
7616
  fiveHourRemaining,
7138
7617
  weeklyKnown: Number.isFinite(weeklyRemaining),
7139
- fiveHourKnown: Number.isFinite(fiveHourRemaining)
7618
+ fiveHourKnown: Number.isFinite(fiveHourRemaining),
7619
+ failures: acc.cooldowns?.[family]?.consecutiveFailures ?? 0,
7620
+ surplus: candidateSurplusScore(q, now)
7140
7621
  };
7141
7622
  }).sort((a, b) => {
7142
7623
  if (a.weeklyKnown && b.weeklyKnown) {
7143
- 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;
7144
7625
  } else if (a.weeklyKnown !== b.weeklyKnown) return a.weeklyKnown ? -1 : 1;
7145
7626
  if (a.fiveHourKnown && b.fiveHourKnown) {
7146
- 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;
7147
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;
7148
7631
  const da = cyclicDistance(accounts, fromId, a.acc.id);
7149
7632
  const db = cyclicDistance(accounts, fromId, b.acc.id);
7150
7633
  return da !== db ? da - db : a.index - b.index;
@@ -7327,6 +7810,7 @@ var PoolAdmin = class {
7327
7810
  if (!data.activeAccountIds) data.activeAccountIds = {};
7328
7811
  data.activeAccountIds[family] = id;
7329
7812
  data.lastActiveAccountId = id;
7813
+ data.manualPinAt = Date.now();
7330
7814
  if (!accountHasArgon(acc, this.deps.pool)) delete data.activeAccountIds.argon;
7331
7815
  else data.activeAccountIds.argon = id;
7332
7816
  this.deps.persist();
@@ -7426,12 +7910,16 @@ var PoolAdmin = class {
7426
7910
  acc.enabled = true;
7427
7911
  data.primaryAccountId = id;
7428
7912
  data.accounts.unshift(acc);
7429
- data.activeAccountIds = {
7430
- google: id,
7431
- anthropic: id,
7432
- openai: id
7433
- };
7434
- 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();
7435
7923
  this.deps.persist();
7436
7924
  return true;
7437
7925
  }
@@ -7450,6 +7938,7 @@ var PoolAdmin = class {
7450
7938
  data.accounts = reordered;
7451
7939
  data.activeAccountIds = {};
7452
7940
  data.lastActiveAccountId = void 0;
7941
+ data.manualPinAt = Date.now();
7453
7942
  this.deps.persist();
7454
7943
  return true;
7455
7944
  }
@@ -7489,7 +7978,7 @@ var PoolAdmin = class {
7489
7978
  const acc = this.account(id);
7490
7979
  if (!acc) return;
7491
7980
  acc.lastUsedAt = Date.now();
7492
- if (acc.authRequired) {
7981
+ if (acc.authRequired && !isTerminalAuthError(acc.authError)) {
7493
7982
  delete acc.authRequired;
7494
7983
  delete acc.authError;
7495
7984
  delete acc.authMarkedAt;
@@ -7542,6 +8031,68 @@ var PoolAdmin = class {
7542
8031
  }
7543
8032
  };
7544
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
7545
8096
  //#region src/domain/accounts/store.ts
7546
8097
  var PoolStore = class {
7547
8098
  baseDir;
@@ -7631,13 +8182,62 @@ var PoolStore = class {
7631
8182
  try {
7632
8183
  if (existsSync(this.file)) {
7633
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]));
7634
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
+ });
7635
8235
  const ours = new Set(data.accounts.map((a) => a.id));
7636
8236
  const foreign = onDisk.accounts.filter((a) => a && typeof a === "object" && a.id !== void 0 && !ours.has(a.id) && !this.knownIds.has(a.id));
7637
- if (foreign.length > 0) {
8237
+ if (foreign.length > 0 || accountMerged) {
7638
8238
  merged = {
7639
8239
  ...data,
7640
- accounts: [...data.accounts, ...foreign]
8240
+ accounts: [...nextAccounts, ...foreign]
7641
8241
  };
7642
8242
  for (const acc of foreign) this.knownIds.add(acc.id);
7643
8243
  }
@@ -8084,11 +8684,16 @@ var AccountPoolManager = class {
8084
8684
  selectAccount: (family, model) => this.selectAccount(family, model)
8085
8685
  });
8086
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
+ }
8087
8692
  /** Determine whether a managed account supports a specific model. */
8088
8693
  isModelSupported(acc, model) {
8089
8694
  return accountCanServeModel(acc, model, {
8090
8695
  unsupportedModels: this.unsupportedModels,
8091
- catalogFor: (id) => this.catalog?.get(id),
8696
+ catalogFor: (id) => this.catalogForAccount(id),
8092
8697
  pool: this
8093
8698
  });
8094
8699
  }
@@ -8142,35 +8747,20 @@ var AccountPoolManager = class {
8142
8747
  * as well as the primary system ~/.gemini/antigravity-cli/log directory.
8143
8748
  */
8144
8749
  sweepOldLogs(maxDays = 7) {
8145
- const maxAgeMs = Math.max(1, maxDays) * 864e5;
8146
- const now = Date.now();
8147
- let removed = 0;
8148
- const targetLogDirs = [join(homedir(), ".gemini", "antigravity-cli", "log")];
8149
- for (const acc of this.data.accounts) if (acc.dir) targetLogDirs.push(join(acc.dir, ".gemini", "antigravity-cli", "log"));
8150
- for (const logDir of targetLogDirs) {
8151
- if (!existsSync(logDir)) continue;
8152
- try {
8153
- const files = readdirSync(logDir);
8154
- for (const f of files) {
8155
- if (!f.startsWith("cli-") || !f.endsWith(".log")) continue;
8156
- const fp = join(logDir, f);
8157
- try {
8158
- if (now - statSync(fp).mtimeMs > maxAgeMs) {
8159
- rmSync(fp, { force: true });
8160
- removed++;
8161
- }
8162
- } catch {}
8163
- }
8164
- } catch {}
8165
- }
8166
- return removed;
8750
+ return sweepOldAgyLogs(this.data.accounts, homedir(), maxDays);
8167
8751
  }
8168
8752
  /** Create a new isolated account slot and prepare its filesystem home. */
8169
8753
  createAccountSlot(alias) {
8170
8754
  return this.admin.createAccountSlot(alias);
8171
8755
  }
8172
8756
  deleteAccount(id) {
8173
- 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;
8174
8764
  }
8175
8765
  setAccountProxy(id, proxyUrl) {
8176
8766
  return this.admin.setAccountProxy(id, proxyUrl);
@@ -8179,7 +8769,13 @@ var AccountPoolManager = class {
8179
8769
  return this.admin.setAccountAlias(id, alias);
8180
8770
  }
8181
8771
  setAccountEnabled(id, enabled) {
8182
- 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;
8183
8779
  }
8184
8780
  /**
8185
8781
  * Record the account a run actually spawned with. The console derives its
@@ -8243,26 +8839,12 @@ var AccountPoolManager = class {
8243
8839
  setMode(mode) {
8244
8840
  this.admin.setMode(mode);
8245
8841
  }
8246
- /**
8247
- * True when a family's cached quota snapshot benches the account.
8248
- *
8249
- * A user-visible `clearCooldown(..., includeQuotaBench = true)` records the
8250
- * `updatedAt` of the snapshot it overrode; the gate stays off only while the
8251
- * cached row is no newer than that stamp, so a fresh poll always re-arms it.
8252
- */
8253
- isQuotaBenched(acc, family, now) {
8254
- return isQuotaBenched(acc, family, now);
8255
- }
8256
8842
  /** Determine whether a managed account has confirmed access to Gemini 4 Argon. */
8257
8843
  accountHasArgon(acc) {
8258
- return accountHasArgon(acc, this);
8844
+ return accountHasArgon(acc, this, this.catalogForAccount(acc.id));
8259
8845
  }
8260
8846
  /**
8261
8847
  * Why this account cannot serve `family` right now, or null when it can.
8262
- *
8263
- * Exists so callers can report the ACTUAL blocker: quota rotation used to be
8264
- * folded into "in cooldown", which pointed users at `/agy clear-cooldown` for
8265
- * a state that command did not touch.
8266
8848
  */
8267
8849
  explainIneligibility(acc, family, now = Date.now(), model) {
8268
8850
  return explainIneligibility(acc, family, now, this, model);
@@ -8279,23 +8861,6 @@ var AccountPoolManager = class {
8279
8861
  getActiveAccountId(family = "google", model) {
8280
8862
  return this.admin.getActiveAccountId(family, model);
8281
8863
  }
8282
- /**
8283
- * Next moment this account's quota state refreshes for one family: the
8284
- * sooner of the 5h window reset and the weekly cap reset. NaN when unknown.
8285
- */
8286
- nextQuotaResetAt(acc, family) {
8287
- return nextQuotaResetAt(acc, family);
8288
- }
8289
- /** Cyclic distance from `fromId` (0 = itself), so ties keep pool order. */
8290
- cyclicDistance(fromId, id) {
8291
- return cyclicDistance(this.data.accounts, fromId, id);
8292
- }
8293
- /**
8294
- * "Use it or lose it" rotation order.
8295
- * Priority 1: Weekly quota expiring soonest (least remaining time until weeklyResetTime).
8296
- * Priority 2: 5-hour quota expiring soonest (least remaining time until resetTime).
8297
- * Priority 3: Cyclic distance from `fromId` (or pool order).
8298
- */
8299
8864
  orderByExpiry(candidates, family, fromId) {
8300
8865
  return orderByExpiry(this.data.accounts, candidates, family, fromId, Date.now());
8301
8866
  }
@@ -8323,7 +8888,9 @@ var AccountPoolManager = class {
8323
8888
  const isExhaustedWeekly = typeof info.weeklyFraction === "number" && info.weeklyFraction <= .05 && (!info.weeklyResetTime || Number.isNaN(Date.parse(info.weeklyResetTime)) || Date.parse(info.weeklyResetTime) > now);
8324
8889
  if (isExhausted5h || isExhaustedWeekly) {
8325
8890
  const clearedAt = acc.quotaGateClearedAt?.[famKey];
8326
- 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");
8327
8894
  }
8328
8895
  }
8329
8896
  this.persist();
@@ -8343,7 +8910,10 @@ var AccountPoolManager = class {
8343
8910
  }
8344
8911
  /** Records a rate-limit / 429 error and sets cooldown for the requested model family. */
8345
8912
  recordFailure(id, family, reason, serverResetTime) {
8913
+ const prev = this.data.activeAccountIds?.[family] ?? this.data.lastActiveAccountId;
8346
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);
8347
8917
  }
8348
8918
  /** Records a successful run, clearing failure counter and authRequired flag for the family. */
8349
8919
  recordSuccess(id, family) {
@@ -8445,39 +9015,14 @@ var AccountPoolManager = class {
8445
9015
  }
8446
9016
  /** Get countdown in milliseconds until the earliest account in cooldown resets. */
8447
9017
  getEarliestResetCountdown(family) {
8448
- const now = Date.now();
8449
- let earliest = null;
8450
- for (const acc of this.data.accounts) {
8451
- if (!acc.enabled) continue;
8452
- const cd = acc.cooldowns?.[family];
8453
- if (cd && cd.cooldownUntil > now && (earliest === null || cd.cooldownUntil < earliest)) earliest = cd.cooldownUntil;
8454
- }
8455
- return earliest !== null ? Math.max(0, earliest - now) : null;
9018
+ return earliestResetCountdown(this.data.accounts, family);
8456
9019
  }
8457
9020
  /**
8458
9021
  * Earliest moment ANY enabled account could serve `family` again: the sooner
8459
9022
  * of a cooldown expiry and a quota-window reset.
8460
9023
  */
8461
9024
  getEarliestAvailableCountdown(family) {
8462
- const now = Date.now();
8463
- let earliest = null;
8464
- const bump = (at) => {
8465
- if (at === null || Number.isNaN(at) || at <= now) return;
8466
- if (earliest === null || at < earliest) earliest = at;
8467
- };
8468
- for (const acc of this.data.accounts) {
8469
- if (!acc.enabled || acc.authRequired) continue;
8470
- const cd = acc.cooldowns?.[family];
8471
- if (cd && cd.cooldownUntil > now) bump(cd.cooldownUntil);
8472
- const quota = acc.quotas?.[family];
8473
- if (quota === void 0) continue;
8474
- const clearedAt = acc.quotaGateClearedAt?.[family];
8475
- if (clearedAt !== void 0 && (quota.updatedAt ?? 0) <= clearedAt) continue;
8476
- const drained5h = typeof quota.remainingFraction === "number" && quota.remainingFraction <= .1 && typeof quota.resetTime === "string" && Date.parse(quota.resetTime) > now;
8477
- const drainedWeekly = typeof quota.weeklyFraction === "number" && quota.weeklyFraction <= .05 && typeof quota.weeklyResetTime === "string" && Date.parse(quota.weeklyResetTime) > now;
8478
- if (drained5h || drainedWeekly) bump(this.nextQuotaResetAt(acc, family));
8479
- }
8480
- return earliest !== null ? Math.max(0, earliest - now) : null;
9025
+ return earliestAvailableCountdown(this.data.accounts, family);
8481
9026
  }
8482
9027
  };
8483
9028
  //#endregion
@@ -31915,36 +32460,60 @@ var import_undici = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
31915
32460
  }
31916
32461
  module.exports.install = install;
31917
32462
  })))();
31918
- const envAgent = new import_undici.EnvHttpProxyAgent();
32463
+ const defaultEnvAgent = new import_undici.EnvHttpProxyAgent();
31919
32464
  const perProxyAgents = /* @__PURE__ */ new Map();
31920
- function agentFor(proxyUrl) {
31921
- 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();
31922
32472
  if (effective) {
31923
- let agent = perProxyAgents.get(effective);
32473
+ const key = dispatcherKeyFor(effective, accountScope);
32474
+ let agent = perProxyAgents.get(key);
31924
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
+ }
31925
32484
  agent = new import_undici.ProxyAgent(effective);
31926
- perProxyAgents.set(effective, agent);
32485
+ perProxyAgents.set(key, agent);
31927
32486
  }
31928
32487
  return agent;
31929
32488
  }
31930
- 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;
31931
32507
  }
31932
- /**
31933
- * Default timeout for one Google endpoint call. undici's own default
31934
- * headers timeout is 300s, so a hung refresh-token / quota endpoint used to
31935
- * park the whole chain (token refresh → two endpoints → userinfo) for many
31936
- * minutes — enough for `/agy refresh-quota` to look dead. Callers may pass
31937
- * their own `signal`; it is combined with the timeout.
31938
- */
31939
32508
  const AGY_FETCH_TIMEOUT_MS = 1e4;
31940
- /** fetch() honoring env proxies, or an explicit per-account proxy URL. */
31941
- 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) {
31942
32511
  const callerSignal = init.signal ?? void 0;
31943
32512
  const signal = callerSignal !== void 0 ? AbortSignal.any([AbortSignal.timeout(AGY_FETCH_TIMEOUT_MS), callerSignal]) : AbortSignal.timeout(AGY_FETCH_TIMEOUT_MS);
31944
32513
  return (0, import_undici.fetch)(url, {
31945
32514
  ...init,
31946
32515
  signal,
31947
- dispatcher: agentFor(proxyUrl)
32516
+ dispatcher: agentForScope(proxyUrl, accountScope)
31948
32517
  });
31949
32518
  }
31950
32519
  function resolveClientCredentials() {
@@ -31954,7 +32523,9 @@ function resolveClientCredentials() {
31954
32523
  };
31955
32524
  }
31956
32525
  const OAUTH_TOKEN_URL = "https://oauth2.googleapis.com/token";
31957
- 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) {
31958
32529
  const { clientId, clientSecret } = resolveClientCredentials();
31959
32530
  const body = new URLSearchParams({
31960
32531
  client_id: clientId,
@@ -31963,9 +32534,12 @@ async function postTokenForm(fields, proxyUrl) {
31963
32534
  });
31964
32535
  const res = await agyFetch(OAUTH_TOKEN_URL, {
31965
32536
  method: "POST",
31966
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
32537
+ headers: {
32538
+ "Content-Type": "application/x-www-form-urlencoded",
32539
+ "User-Agent": agyUserAgent(runtimeAgyVersion)
32540
+ },
31967
32541
  body: body.toString()
31968
- }, proxyUrl);
32542
+ }, proxyUrl, accountScope);
31969
32543
  const payload = await res.json().catch(() => ({}));
31970
32544
  if (!res.ok) {
31971
32545
  const code = typeof payload.error === "string" ? payload.error : payload.error?.status;
@@ -31983,12 +32557,41 @@ function toTokenSet(payload, refreshTokenFallback) {
31983
32557
  expiryMs: typeof payload.expires_in === "number" ? Date.now() + payload.expires_in * 1e3 : void 0
31984
32558
  };
31985
32559
  }
31986
- /** Refresh an access token; throws on invalid_grant (credential revoked). */
31987
- async function refreshTokens(refreshToken, proxyUrl) {
31988
- return toTokenSet(await postTokenForm({
31989
- grant_type: "refresh_token",
31990
- refresh_token: refreshToken
31991
- }, 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;
31992
32595
  }
31993
32596
  //#endregion
31994
32597
  //#region src/domain/credentials/backup.ts
@@ -32013,12 +32616,12 @@ function sleepMs(ms) {
32013
32616
  }
32014
32617
  /** Read a file with retry backoff for transient Windows sharing violations. */
32015
32618
  function readWithRetry(file) {
32016
- for (let attempt = 0; attempt < 3; attempt++) try {
32619
+ for (let attempt = 0; attempt < 5; attempt++) try {
32017
32620
  return readFileSync(file, "utf8");
32018
32621
  } catch (err) {
32019
32622
  const code = err.code;
32020
32623
  if (code === "ENOENT") return null;
32021
- if (attempt < 2 && (code === "EBUSY" || code === "EPERM" || code === "EACCES")) {
32624
+ if (attempt < 4 && (code === "EBUSY" || code === "EPERM" || code === "EACCES")) {
32022
32625
  sleepMs(50);
32023
32626
  continue;
32024
32627
  }
@@ -32139,20 +32742,9 @@ function readTokenFileRaw(file) {
32139
32742
  const raw = readAccountCredential(file);
32140
32743
  return raw && raw.trim() ? raw : null;
32141
32744
  }
32142
- /** 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. */
32143
32746
  function writeFileAtomic(file, data) {
32144
- const tmp = file + ".tmp-" + process.pid + "-" + Date.now();
32145
- try {
32146
- mkdirSync(dirname(file), { recursive: true });
32147
- writeFileSync(tmp, data, { encoding: "utf8" });
32148
- renameSync(tmp, file);
32149
- return true;
32150
- } catch {
32151
- try {
32152
- unlinkSync(tmp);
32153
- } catch {}
32154
- return false;
32155
- }
32747
+ return tryWriteFileAtomic(file, data);
32156
32748
  }
32157
32749
  function accountTokenFilePath(account, homeDir) {
32158
32750
  const home = account.dir ? account.dir : homeDir;
@@ -32256,9 +32848,11 @@ var WaitTimeoutError = class extends Error {
32256
32848
  };
32257
32849
  /** The slot cannot be handed over safely; the caller must abort the run. */
32258
32850
  var SlotUnavailableError = class extends Error {
32259
- constructor(message) {
32851
+ target;
32852
+ constructor(message, target = "account") {
32260
32853
  super(message);
32261
32854
  this.name = "SlotUnavailableError";
32855
+ this.target = target;
32262
32856
  }
32263
32857
  };
32264
32858
  //#endregion
@@ -32781,7 +33375,7 @@ var SlotAcquire = class {
32781
33375
  const accountRaw = readTokenFileRaw(accountFile);
32782
33376
  if (!primary) {
32783
33377
  this.done();
32784
- 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");
32785
33379
  }
32786
33380
  if (this.isPrimarySlot) return this.primaryLease(primary);
32787
33381
  await this.drainPrimaryFastRuns();
@@ -32953,22 +33547,13 @@ function defaultSlotIo() {
32953
33547
  async function identifyCredential(raw, proxyUrl) {
32954
33548
  const doc = parseCredentialDoc(raw);
32955
33549
  if (!doc) return void 0;
32956
- const probe = async (accessToken) => {
32957
- try {
32958
- const res = await agyFetch("https://www.googleapis.com/oauth2/v1/userinfo", { headers: { Authorization: "Bearer " + accessToken } }, proxyUrl);
32959
- if (!res.ok) return void 0;
32960
- return (await res.json()).email;
32961
- } catch {
32962
- return;
32963
- }
32964
- };
32965
33550
  if (doc.accessToken && (!doc.expiryMs || doc.expiryMs > Date.now() + 6e4)) {
32966
- const email = await probe(doc.accessToken);
33551
+ const email = await fetchUserEmail(doc.accessToken, proxyUrl);
32967
33552
  if (email) return email;
32968
33553
  }
32969
33554
  if (doc.refreshToken) try {
32970
33555
  const refreshed = await refreshTokens(doc.refreshToken, proxyUrl);
32971
- if (refreshed?.access_token) return await probe(refreshed.access_token);
33556
+ if (refreshed?.access_token) return await fetchUserEmail(refreshed.access_token, proxyUrl);
32972
33557
  } catch {
32973
33558
  return;
32974
33559
  }
@@ -33069,6 +33654,12 @@ function noteFailure(log, what, err) {
33069
33654
  if (code === "ENOENT" || code === "EACCES" || code === "EPERM" || code === "EBUSY") return;
33070
33655
  log?.(`subagent tracker: ${what} — ${String(err)}`);
33071
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
+ }
33072
33663
  function stripQuotes(s) {
33073
33664
  if (s.startsWith("\"") && s.endsWith("\"") || s.startsWith("'") && s.endsWith("'")) return s.slice(1, -1);
33074
33665
  return s;
@@ -33148,15 +33739,37 @@ var SubagentTracker = class {
33148
33739
  if (cid === "" || cid === this.conversationId) return;
33149
33740
  this.conversationId = cid;
33150
33741
  this.brainDir = null;
33151
- 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
+ }
33152
33750
  }
33751
+ baselined = false;
33153
33752
  start() {
33154
33753
  if (this.active) return;
33155
33754
  this.active = true;
33755
+ if (this.opts.resumed === true && !this.baselined && this.conversationId !== "") {
33756
+ this.baselined = true;
33757
+ this.baselineExisting();
33758
+ }
33156
33759
  this.poll();
33157
33760
  this.timer = setInterval(() => this.poll(), this.pollIntervalMs);
33158
33761
  this.timer.unref?.();
33159
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
+ }
33160
33773
  stop() {
33161
33774
  this.active = false;
33162
33775
  if (this.timer) {
@@ -33174,14 +33787,26 @@ var SubagentTracker = class {
33174
33787
  if (!this.brainDir) return;
33175
33788
  const convsToScan = [this.conversationId, ...Array.from(this.trackedSubagents.keys())];
33176
33789
  for (const cid of convsToScan) this.scanSubagentsForConv(cid);
33177
- for (const sub of this.trackedSubagents.values()) this.pollSubagentTranscript(sub);
33790
+ for (const sub of this.trackedSubagents.values()) if (!sub.terminal) this.pollSubagentTranscript(sub);
33178
33791
  } catch (err) {
33179
33792
  noteFailure(this.opts.log, "poll", err);
33180
33793
  } finally {
33181
33794
  this.polling = false;
33182
33795
  }
33183
33796
  }
33184
- 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) {
33185
33810
  const bDir = cid === this.conversationId ? this.brainDir : findBrainDir(cid, this.accountHome);
33186
33811
  if (!bDir) return;
33187
33812
  const subagentsDir = join(bDir, ".system_generated", "subagents");
@@ -33199,32 +33824,52 @@ var SubagentTracker = class {
33199
33824
  const raw = readFileSync(fullPath, "utf8");
33200
33825
  const obj = JSON.parse(raw);
33201
33826
  const subId = typeof obj?.conversationId === "string" ? obj.conversationId : f.replace(/\.json$/, "");
33202
- 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
+ }
33203
33841
  const desc = obj?.subagentDescriptor;
33204
33842
  const role = typeof desc?.role === "string" && desc.role !== "" ? desc.role : "专员";
33205
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
+ }
33206
33854
  const tracked = {
33207
33855
  conversationId: subId,
33208
33856
  role,
33209
33857
  typeName,
33210
- brainDir: findBrainDir(subId, this.accountHome) ?? join(bDir, "..", subId),
33211
- offset: 0,
33858
+ brainDir: subBrainDir,
33859
+ state: rawState,
33860
+ terminal: !active,
33861
+ offset: initialOffset,
33862
+ decoder: new StringDecoder("utf8"),
33212
33863
  rest: "",
33213
33864
  lines: 0
33214
33865
  };
33215
33866
  this.trackedSubagents.set(subId, tracked);
33216
33867
  const spawnKey = `subagent-spawn-${subId}`;
33217
- 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 {
33218
33871
  this.seenStepKeys.add(spawnKey);
33219
- const ev = {
33220
- kind: "step",
33221
- stepKey: spawnKey,
33222
- stepKind: "subagent",
33223
- text: `[子代理 · ${role}] 已启动协同专员 (${typeName})\n`,
33224
- raw: obj
33225
- };
33226
- this.opts.onEvent(ev);
33227
- this.opts.noteActivity?.();
33872
+ if (rawState !== void 0) this.emitSubagentEvent(`subagent-state-${subId}-${rawState}`, `[子代理 · ${role}] 协同专员未保持运行 (${rawState})\n`, obj);
33228
33873
  }
33229
33874
  } catch (err) {
33230
33875
  noteFailure(this.opts.log, `descriptor ${f}`, err);
@@ -33250,23 +33895,26 @@ var SubagentTracker = class {
33250
33895
  }
33251
33896
  if (size < sub.offset) {
33252
33897
  sub.offset = 0;
33898
+ sub.decoder = new StringDecoder("utf8");
33253
33899
  sub.rest = "";
33254
33900
  }
33255
33901
  if (size === sub.offset) return [];
33256
33902
  const length = size - sub.offset;
33257
33903
  const buffer = Buffer.allocUnsafe(length);
33904
+ let bytesRead = 0;
33258
33905
  try {
33259
33906
  const fd = openSync(logPath, "r");
33260
33907
  try {
33261
- readSync(fd, buffer, 0, length, sub.offset);
33908
+ bytesRead = readSync(fd, buffer, 0, length, sub.offset);
33262
33909
  } finally {
33263
33910
  closeSync(fd);
33264
33911
  }
33265
33912
  } catch {
33266
33913
  return [];
33267
33914
  }
33268
- sub.offset = size;
33269
- 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");
33270
33918
  sub.rest = parts.pop() ?? "";
33271
33919
  return parts.filter((line) => line.trim() !== "");
33272
33920
  }
@@ -33280,36 +33928,14 @@ var SubagentTracker = class {
33280
33928
  const tc = o.tool_calls[tcIdx];
33281
33929
  const toolName = typeof tc?.name === "string" ? tc.name : "";
33282
33930
  if (toolName === "") continue;
33283
- const k = `${baseKey}-tc-${tcIdx}`;
33284
- if (this.seenStepKeys.has(k)) continue;
33285
- this.seenStepKeys.add(k);
33286
- const ev = {
33287
- kind: "step",
33288
- stepKey: k,
33289
- stepKind: "subagent",
33290
- text: `${formatSubagentAction(sub.role, toolName, tc.args)}\n`,
33291
- raw: o
33292
- };
33293
- this.opts.onEvent(ev);
33294
- this.opts.noteActivity?.();
33931
+ const msg = formatSubagentAction(sub.role, toolName, tc.args);
33932
+ this.emitSubagentEvent(`${baseKey}-tc-${tcIdx}`, `${msg}\n`, o);
33295
33933
  }
33296
33934
  else if (o.type === "PLANNER_RESPONSE" && typeof o.content === "string" && o.content.trim() !== "") {
33297
- const k = `${baseKey}-content`;
33298
- if (this.seenStepKeys.has(k)) continue;
33299
- this.seenStepKeys.add(k);
33300
33935
  const firstLine = o.content.trim().split("\n")[0].replace(/^#+\s*/, "").slice(0, 100);
33301
- if (firstLine !== "") {
33302
- const ev = {
33303
- kind: "step",
33304
- stepKey: k,
33305
- stepKind: "subagent",
33306
- text: `[子代理 · ${sub.role}] 阶段进展: ${firstLine}\n`,
33307
- raw: o
33308
- };
33309
- this.opts.onEvent(ev);
33310
- this.opts.noteActivity?.();
33311
- }
33936
+ if (firstLine !== "") this.emitSubagentEvent(`${baseKey}-content`, `[子代理 · ${sub.role}] 阶段进展: ${firstLine}\n`, o);
33312
33937
  }
33938
+ if (isTerminalTranscriptStatus(o.status)) this.emitSubagentEvent(`${baseKey}-status`, `[子代理 · ${sub.role}] 执行异常/中止 (${o.status})\n`, o);
33313
33939
  } catch {}
33314
33940
  }
33315
33941
  };
@@ -33388,6 +34014,7 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId) {
33388
34014
  const watchdog = createToolWatchdog(deps.log, cfg);
33389
34015
  const tracker = new SubagentTracker({
33390
34016
  conversationId: initialConversationId,
34017
+ resumed: Boolean(initialConversationId),
33391
34018
  accountHome: rec.accountHome,
33392
34019
  log: deps.log,
33393
34020
  onEvent: (ev) => {
@@ -33531,11 +34158,9 @@ async function startAttemptProcess(deps, input, spawn, recorder, slot) {
33531
34158
  let spawned = false;
33532
34159
  try {
33533
34160
  if (account) {
33534
- const lastSpawn = deps.lastAccountSpawnTime.get(account.id) ?? 0;
33535
- const elapsed = Date.now() - lastSpawn;
33536
- const jitter = Math.floor(Math.random() * 300);
33537
- const targetInterval = deps.minSpawnIntervalMs + jitter;
33538
- 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");
33539
34164
  deps.lastAccountSpawnTime.set(account.id, Date.now());
33540
34165
  }
33541
34166
  const slotHandoff = slot.armHandoff();
@@ -33578,88 +34203,193 @@ async function startAttemptProcess(deps, input, spawn, recorder, slot) {
33578
34203
  };
33579
34204
  }
33580
34205
  //#endregion
34206
+ //#region src/provider/idle-grace-reply.ts
34207
+ /**
34208
+ * How much of the transcript tail to inspect. The file grows for the lifetime
34209
+ * of a conversation, and only the newest turn matters, so a bounded tail read
34210
+ * keeps this O(1) regardless of history size.
34211
+ */
34212
+ const TAIL_BYTES = 262144;
34213
+ /**
34214
+ * Shown when the idle reaper ended the turn without a recoverable reply.
34215
+ *
34216
+ * Silently finishing with no text made DSH render "completed" while the user
34217
+ * saw no answer at all, which reads as success for work that was never
34218
+ * confirmed (issue #127). The turn is still a clean finish — this only explains
34219
+ * what happened instead of leaving a blank turn.
34220
+ */
34221
+ const IDLE_GRACE_NO_REPLY_NOTICE = "⚠️ 后台等待已结束,本轮没有收到最终答复;任务结果未确认,部分操作可能已经执行。\n⚠️ Background wait ended without a final reply — the task outcome is unconfirmed and some steps may have run.\n";
34222
+ /**
34223
+ * The final assistant reply written during the CURRENT turn, or '' when the
34224
+ * transcript does not prove one.
34225
+ *
34226
+ * "Current turn" = after the last `USER_INPUT` row. A `PLANNER_RESPONSE` still
34227
+ * carrying `tool_calls` is an in-flight step, not a final answer, and is
34228
+ * skipped. Anything unreadable degrades to '' so the caller keeps its previous
34229
+ * behaviour.
34230
+ */
34231
+ function recoverFinalReply(conversationId, accountHome) {
34232
+ const logPath = transcriptPath(conversationId, accountHome);
34233
+ if (logPath === null) return "";
34234
+ let text;
34235
+ try {
34236
+ text = readTail(logPath);
34237
+ } catch {
34238
+ return "";
34239
+ }
34240
+ const rows = text.split("\n").filter((line) => line.trim() !== "");
34241
+ let lastUserInput = -1;
34242
+ for (let i = 0; i < rows.length; i++) if (rowType(rows[i]) === "USER_INPUT") lastUserInput = i;
34243
+ for (let i = rows.length - 1; i > lastUserInput; i--) {
34244
+ const row = parseRow(rows[i]);
34245
+ if (row === null || row.type !== "PLANNER_RESPONSE") continue;
34246
+ if (Array.isArray(row.tool_calls) && row.tool_calls.length > 0) continue;
34247
+ if (typeof row.content !== "string") continue;
34248
+ if (row.content.trim() !== "") return row.content;
34249
+ }
34250
+ return "";
34251
+ }
34252
+ function transcriptPath(conversationId, accountHome) {
34253
+ const brainDir = findBrainDir(conversationId, accountHome);
34254
+ if (brainDir === null) return null;
34255
+ const logPath = join(brainDir, ".system_generated", "logs", "transcript.jsonl");
34256
+ return existsSync(logPath) ? logPath : null;
34257
+ }
34258
+ function readTail(logPath) {
34259
+ const size = statSync(logPath).size;
34260
+ const start = Math.max(0, size - TAIL_BYTES);
34261
+ const length = size - start;
34262
+ if (length <= 0) return "";
34263
+ const buf = Buffer.alloc(length);
34264
+ const fd = openSync(logPath, "r");
34265
+ try {
34266
+ readSync(fd, buf, 0, length, start);
34267
+ } finally {
34268
+ closeSync(fd);
34269
+ }
34270
+ return buf.toString("utf8");
34271
+ }
34272
+ function parseRow(line) {
34273
+ try {
34274
+ const parsed = JSON.parse(line);
34275
+ return parsed !== null && typeof parsed === "object" ? parsed : null;
34276
+ } catch {
34277
+ return null;
34278
+ }
34279
+ }
34280
+ function rowType(line) {
34281
+ const row = parseRow(line);
34282
+ return row !== null && typeof row.type === "string" ? row.type : "";
34283
+ }
34284
+ //#endregion
33581
34285
  //#region src/provider/failure.ts
33582
34286
  function brief(s) {
33583
34287
  const flat = s.trim().replace(/\s+/g, " ");
33584
34288
  return flat.length > 300 ? flat.slice(0, 300) + "..." : flat;
33585
34289
  }
34290
+ function detailText(c, fallback = "") {
34291
+ return c.parser.stats.lastResultError ?? (c.outcome.stderrTail !== "" ? brief(c.outcome.stderrTail) : fallback);
34292
+ }
34293
+ function classifyPolicyOrQuota(c) {
34294
+ if (c.sawAuthFailure) return c.transportFailure ? {
34295
+ kind: "error",
34296
+ code: Err.NETWORK,
34297
+ 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) : "")
34298
+ } : {
34299
+ kind: "error",
34300
+ code: Err.AUTH,
34301
+ message: "agy is not signed in — run /agy auth (or run agy once in a terminal) to login"
34302
+ };
34303
+ if (c.isRateLimit) {
34304
+ const bestMsg = detailText(c, "Rate limit or quota reached");
34305
+ const hard = looksLikeHardRateLimit(c.rawErrText);
34306
+ return {
34307
+ kind: "error",
34308
+ code: hard ? Err.RATE_LIMIT : Err.OVERLOADED,
34309
+ message: hard ? "Google Antigravity quota / rate limit reached: " + bestMsg : "Google Antigravity quota / rate limit reached (server capacity overloaded): " + bestMsg
34310
+ };
34311
+ }
34312
+ const resultErr = c.parser.stats.lastResultError ?? "";
34313
+ if (looksLikeContextWindowExceeded(c.rawErrText) || looksLikeContextWindowExceeded(resultErr)) return {
34314
+ kind: "error",
34315
+ code: Err.CONTEXT_WINDOW_EXCEEDED,
34316
+ message: "Google Antigravity context window exceeded: " + detailText(c, "Prompt exceeds context window limit")
34317
+ };
34318
+ if (!c.transportFailure && (looksLikeEligibilityFailure(c.rawErrText) || looksLikeEligibilityFailure(resultErr))) {
34319
+ const detail = detailText(c);
34320
+ return {
34321
+ kind: "error",
34322
+ code: Err.ELIGIBILITY,
34323
+ message: ELIGIBILITY_ERROR_HINT + (detail !== "" ? " (" + detail + ")" : "")
34324
+ };
34325
+ }
34326
+ if (!c.transportFailure && (looksLikeTosViolation(c.rawErrText) || looksLikeTosViolation(resultErr))) return {
34327
+ kind: "error",
34328
+ code: Err.AGY_ERROR,
34329
+ message: "Google Antigravity account suspended (TOS_VIOLATION): " + detailText(c, brief(c.rawErrText))
34330
+ };
34331
+ if (!c.transportFailure && (looksLikeValidationRequired(c.rawErrText) || looksLikeValidationRequired(resultErr))) return {
34332
+ kind: "error",
34333
+ code: Err.AGY_ERROR,
34334
+ message: "Google Antigravity account requires verification (VALIDATION_REQUIRED): " + detailText(c, brief(c.rawErrText))
34335
+ };
34336
+ if (looksLikeHeadlessPermissionDenial(c.rawErrText) || looksLikeHeadlessPermissionDenial(resultErr)) {
34337
+ const detail = detailText(c);
34338
+ return {
34339
+ kind: "error",
34340
+ code: Err.AGY_ERROR,
34341
+ message: HEADLESS_PERMISSION_ERROR_HINT + (detail !== "" ? " (" + detail + ")" : "")
34342
+ };
34343
+ }
34344
+ return null;
34345
+ }
34346
+ function classifyExitOrFallback(c) {
34347
+ if (c.outcome.code !== 0) {
34348
+ const detail = detailText(c);
34349
+ return c.transportFailure ? {
34350
+ kind: "error",
34351
+ code: Err.NETWORK,
34352
+ message: "agy hit a network error while talking to Google — the automatic retry usually succeeds. " + (detail !== "" ? detail : brief(c.rawErrText))
34353
+ } : {
34354
+ kind: "error",
34355
+ code: Err.PROCESS_EXIT,
34356
+ message: "agy exited with code " + c.outcome.code + (detail !== "" ? ": " + detail : "")
34357
+ };
34358
+ }
34359
+ if (c.transportFailure) return {
34360
+ kind: "error",
34361
+ code: Err.NETWORK,
34362
+ message: "agy hit a network error while talking to Google — the automatic retry usually succeeds. " + brief(c.rawErrText)
34363
+ };
34364
+ if (c.parser.stats.lastResultError) return {
34365
+ kind: "error",
34366
+ code: Err.AGY_ERROR,
34367
+ message: "agy reported an error: " + c.parser.stats.lastResultError
34368
+ };
34369
+ return {
34370
+ kind: "error",
34371
+ code: Err.INVALID_OUTPUT,
34372
+ message: "agy produced no result event (" + c.parser.stats.garbage + " unparseable lines)"
34373
+ };
34374
+ }
33586
34375
  function classifyFailure(c) {
33587
34376
  if (c.outcome.aborted) return {
33588
34377
  kind: "aborted",
33589
34378
  code: "ABORTED",
33590
34379
  message: "agy run aborted by caller"
33591
34380
  };
33592
- else if (c.outcome.capped) return {
34381
+ if (c.outcome.capped) return {
33593
34382
  kind: "error",
33594
34383
  code: Err.TIMEOUT,
33595
34384
  message: "agy turn exceeded maxTurnMinutes (" + c.cfg.maxTurnMinutes + " min) — the agy process tree was terminated. Re-send to continue. 本轮超过 maxTurnMinutes 上限,已终止 agy 进程树"
33596
34385
  };
33597
- else if (c.outcome.timedOut) return {
34386
+ if (c.outcome.timedOut) return {
33598
34387
  kind: "error",
33599
34388
  code: Err.TIMEOUT,
33600
34389
  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,请检查代理或网络配置" : "")
33601
34390
  };
33602
- else if (c.outcome.idleGraceTerminated) return null;
33603
- else if (!c.consumable) {
33604
- if (c.sawAuthFailure) return c.transportFailure ? {
33605
- kind: "error",
33606
- code: Err.NETWORK,
33607
- 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) : "")
33608
- } : {
33609
- kind: "error",
33610
- code: Err.AUTH,
33611
- message: "agy is not signed in — run /agy auth (or run agy once in a terminal) to login"
33612
- };
33613
- else if (c.isRateLimit) {
33614
- const bestMsg = c.parser.stats.lastResultError || (c.outcome.stderrTail ? brief(c.outcome.stderrTail) : "Rate limit or quota reached");
33615
- const hard = looksLikeHardRateLimit(c.rawErrText);
33616
- return {
33617
- kind: "error",
33618
- code: hard ? Err.RATE_LIMIT : Err.OVERLOADED,
33619
- message: hard ? "Google Antigravity quota / rate limit reached: " + bestMsg : "Google Antigravity quota / rate limit reached (server capacity overloaded): " + bestMsg
33620
- };
33621
- } else if (looksLikeContextWindowExceeded(c.rawErrText) || looksLikeContextWindowExceeded(c.parser.stats.lastResultError ?? "")) {
33622
- const detail = c.parser.stats.lastResultError || (c.outcome.stderrTail !== "" ? brief(c.outcome.stderrTail) : "Prompt exceeds context window limit");
33623
- return {
33624
- kind: "error",
33625
- code: Err.CONTEXT_WINDOW_EXCEEDED,
33626
- message: "Google Antigravity context window exceeded: " + detail
33627
- };
33628
- } else if (!c.transportFailure && (looksLikeEligibilityFailure(c.rawErrText) || looksLikeEligibilityFailure(c.parser.stats.lastResultError ?? ""))) {
33629
- const detail = c.parser.stats.lastResultError ?? (c.outcome.stderrTail !== "" ? brief(c.outcome.stderrTail) : "");
33630
- return {
33631
- kind: "error",
33632
- code: Err.ELIGIBILITY,
33633
- message: ELIGIBILITY_ERROR_HINT + (detail !== "" ? " (" + detail + ")" : "")
33634
- };
33635
- } else if (c.outcome.code !== 0) {
33636
- const detail = c.parser.stats.lastResultError ?? (c.outcome.stderrTail !== "" ? brief(c.outcome.stderrTail) : "");
33637
- return c.transportFailure ? {
33638
- kind: "error",
33639
- code: Err.NETWORK,
33640
- message: "agy hit a network error while talking to Google — the automatic retry usually succeeds. " + (detail !== "" ? detail : brief(c.rawErrText))
33641
- } : {
33642
- kind: "error",
33643
- code: Err.PROCESS_EXIT,
33644
- message: "agy exited with code " + c.outcome.code + (detail !== "" ? ": " + detail : "")
33645
- };
33646
- } else if (c.transportFailure) return {
33647
- kind: "error",
33648
- code: Err.NETWORK,
33649
- message: "agy hit a network error while talking to Google — the automatic retry usually succeeds. " + brief(c.rawErrText)
33650
- };
33651
- else if (c.parser.stats.lastResultError) return {
33652
- kind: "error",
33653
- code: Err.AGY_ERROR,
33654
- message: "agy reported an error: " + c.parser.stats.lastResultError
33655
- };
33656
- else return {
33657
- kind: "error",
33658
- code: Err.INVALID_OUTPUT,
33659
- message: "agy produced no result event (" + c.parser.stats.garbage + " unparseable lines)"
33660
- };
33661
- }
33662
- return null;
34391
+ if (c.outcome.idleGraceTerminated || c.consumable) return null;
34392
+ return classifyPolicyOrQuota(c) ?? classifyExitOrFallback(c);
33663
34393
  }
33664
34394
  /**
33665
34395
  * Await `work` while periodically yielding a SESSION-VISIBLE notice.
@@ -33846,7 +34576,8 @@ async function* dispatchCredentialSlot(deps, input) {
33846
34576
  release?.();
33847
34577
  release = null;
33848
34578
  if (e instanceof SlotUnavailableError && currentAccount && deps.pool) {
33849
- deps.pool.markAuthRequired(currentAccount.id, e.message);
34579
+ const isPrimaryAccount = Boolean(currentAccount.systemHome) || !currentAccount.dir;
34580
+ if (e.target !== "primary" || isPrimaryAccount) deps.pool.markAuthRequired(currentAccount.id, e.message);
33850
34581
  const next = attempt < maxDispatchAttempts ? deps.pool.selectAccount(input.family, input.activeModel) : void 0;
33851
34582
  if (next && next.id !== currentAccount.id) {
33852
34583
  deps.log?.(`slot unavailable on ${currentAccount.id}: ${e.message} — failed over to ${next.id}`);
@@ -33896,8 +34627,15 @@ async function* dispatchCredentialSlot(deps, input) {
33896
34627
  function classifyRun(input) {
33897
34628
  const { cfg, outcome, parser, rec, runLogHome, runLogsBefore } = input;
33898
34629
  const r = rec.getResultEvent();
33899
- const consumable = r !== null && (r.ok || r.response !== "");
33900
- const rawErrText = [outcome.stderrTail, parser.stats.lastResultError].filter(Boolean).join(" ");
34630
+ const u = rec.lastUsage ?? rec.finalUsage({});
34631
+ const zeroUsageTos = r !== null && (u?.input_tokens ?? 0) === 0 && (u?.output_tokens ?? 0) === 0 && looksLikeTosViolation(r.response);
34632
+ const errorResponseTos = r !== null && !r.ok && looksLikeTosViolation(r.response);
34633
+ const consumable = r !== null && (r.ok || r.response !== "") && !zeroUsageTos && !errorResponseTos;
34634
+ const rawErrText = [
34635
+ outcome.stderrTail,
34636
+ parser.stats.lastResultError,
34637
+ !consumable && r && (!r.ok || zeroUsageTos) ? r.response : ""
34638
+ ].filter(Boolean).join(" ");
33901
34639
  const isRateLimit = looksLikeRateLimit(rawErrText);
33902
34640
  const runLogText = readAgyRunLogText(runLogHome, runLogsBefore);
33903
34641
  const keyringJitter = looksLikeAuthVerificationJitter(runLogText);
@@ -33950,11 +34688,12 @@ async function handleAttemptOutcome(deps, input, ctx) {
33950
34688
  recorder.drain(input.agyOnEvent);
33951
34689
  const conversationId = recorder.conversationId();
33952
34690
  if (!rec.hasResult && outcome.idleGraceTerminated) {
34691
+ const recovered = conversationId === null ? "" : recoverFinalReply(conversationId, rec.accountHome);
33953
34692
  const synthResult = {
33954
34693
  kind: "result",
33955
34694
  conversationId: conversationId ?? "",
33956
34695
  ok: true,
33957
- response: "",
34696
+ response: recovered === "" ? IDLE_GRACE_NO_REPLY_NOTICE : recovered,
33958
34697
  usage: rec.finalUsage({}),
33959
34698
  raw: {}
33960
34699
  };
@@ -34094,12 +34833,11 @@ var AgyAdapter = class extends LlmAdapter {
34094
34833
  /** accountId -> timestamp of last spawn for spacing throttling */
34095
34834
  lastAccountSpawnTime = /* @__PURE__ */ new Map();
34096
34835
  minSpawnIntervalMs = 500;
34097
- /** Global sliding window timestamps for batch rate-limiting protection */
34098
- requestTimestamps = [];
34836
+ spawnLimiter = new SpawnLimiter();
34099
34837
  constructor(deps) {
34100
34838
  super();
34101
34839
  this.deps = deps;
34102
- if (deps.pool && deps.catalog && typeof deps.pool.setCatalog === "function") deps.pool.setCatalog(deps.catalog);
34840
+ deps.pool?.setCatalog?.(deps.catalog);
34103
34841
  this.effortPolicy = new EffortPolicy(() => this.deps.effortUnsupported?.(), this.deps.log, this.deps.onEffortUnsupported);
34104
34842
  }
34105
34843
  /** Models currently known to reject `--effort` (persisted seed + learned). */
@@ -34116,6 +34854,10 @@ var AgyAdapter = class extends LlmAdapter {
34116
34854
  }
34117
34855
  warnOnce(key, msg) {
34118
34856
  if (this.warnedKeys.has(key)) return;
34857
+ if (this.warnedKeys.size >= 512) {
34858
+ const oldest = this.warnedKeys.values().next().value;
34859
+ if (oldest !== void 0) this.warnedKeys.delete(oldest);
34860
+ }
34119
34861
  this.warnedKeys.add(key);
34120
34862
  this.deps.log?.("WARNING: " + msg);
34121
34863
  }
@@ -34278,24 +35020,19 @@ var AgyAdapter = class extends LlmAdapter {
34278
35020
  }
34279
35021
  const messages = options.messages;
34280
35022
  if (!isAux && cfg.rateLimitPerMinute > 0) {
34281
- const now = Date.now();
34282
- const windowStart = now - 6e4;
34283
- while (this.requestTimestamps.length > 0 && this.requestTimestamps[0] < windowStart) this.requestTimestamps.shift();
34284
- if (this.requestTimestamps.length >= cfg.rateLimitPerMinute) {
34285
- const delayMs = this.requestTimestamps[0] + 6e4 - now;
34286
- if (delayMs > 0) await new Promise((resolve, reject) => {
34287
- const timer = setTimeout(() => {
34288
- options.signal?.removeEventListener("abort", onAbort);
34289
- resolve();
34290
- }, delayMs);
34291
- const onAbort = () => {
34292
- clearTimeout(timer);
34293
- reject(new LlmError("aborted during rate-limit spacing", Err.AGY_ERROR));
34294
- };
34295
- options.signal?.addEventListener("abort", onAbort, { once: true });
34296
- });
34297
- }
34298
- this.requestTimestamps.push(Date.now());
35023
+ const { delayMs, slotAt } = this.spawnLimiter.reserveRateLimitSlot(cfg.rateLimitPerMinute);
35024
+ if (delayMs > 0) await new Promise((resolve, reject) => {
35025
+ const timer = setTimeout(() => {
35026
+ options.signal?.removeEventListener("abort", onAbort);
35027
+ resolve();
35028
+ }, delayMs);
35029
+ const onAbort = () => {
35030
+ clearTimeout(timer);
35031
+ this.spawnLimiter.cancelRateLimitSlot(slotAt);
35032
+ reject(new LlmError("aborted during rate-limit spacing", Err.AGY_ERROR));
35033
+ };
35034
+ options.signal?.addEventListener("abort", onAbort, { once: true });
35035
+ });
34299
35036
  }
34300
35037
  const selection = await selectSessionAccount({
34301
35038
  deps: {
@@ -34423,7 +35160,8 @@ var AgyAdapter = class extends LlmAdapter {
34423
35160
  clearRateLimitFailover: (key) => this.failover.clearRateLimit(key),
34424
35161
  sharesSingleEgress: () => this.sharesSingleEgress(),
34425
35162
  lastAccountSpawnTime: this.lastAccountSpawnTime,
34426
- minSpawnIntervalMs: this.minSpawnIntervalMs
35163
+ minSpawnIntervalMs: this.minSpawnIntervalMs,
35164
+ spawnLimiter: this.spawnLimiter
34427
35165
  }, {
34428
35166
  cfg,
34429
35167
  bin,