dsh-agy-link 0.6.56 → 0.6.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -457,7 +457,7 @@ function extractAuthUrl(text) {
457
457
  */
458
458
  function looksLikeHardRateLimit(text) {
459
459
  if (!text) return false;
460
- return /RESOURCE_EXHAUSTED|code[ :]?429\b|status[ :]?429\b|HTTP[ :]?429\b|too many requests|individual quota reached|quota (?:exceeded|reached|exhausted|limit)|rate[ -]?limit(?:ed)? (?:exceeded|reached|hit)?|exceeded (?:your |the )?quota|has been exhausted|exhausted your (?:quota|capacity)|out of quota|check quota|insufficient quota|usage limit reached/i.test(text);
460
+ return /RESOURCE_EXHAUSTED|\bQUOTA_EXHAUSTED\b|"?code"?\s*[:=]\s*429\b|"?status"?\s*[:=]\s*429\b|HTTP(?:\/[\d.]+)?[ :]?429\b|too many requests|individual quota reached|quota (?:exceeded|reached|exhausted|limit)|rate[ -]?limit(?:ed)? (?:exceeded|reached|hit)?|exceeded (?:your |the )?quota|has been exhausted|exhausted your (?:quota|capacity)|out of quota|check quota|insufficient quota|usage limit reached/i.test(text);
461
461
  }
462
462
  /**
463
463
  * Failures that belong to the ACCOUNT (spent quota, refused region, broken
@@ -491,18 +491,19 @@ function looksLikeRateLimit(text) {
491
491
  }
492
492
  /**
493
493
  * Parse reset duration in milliseconds from rate-limit / quota-exhausted error strings.
494
- * Supports compact formats ("Resets in 21m25s", "Resets in 2h26m6s", "Resets in 45s"),
495
- * verbose formats ("Resets in 15 minutes", "retry after 30 seconds"), and ISO timestamps.
494
+ * Supports compact formats ("Resets in 21m25s", "reset after 4h58m46s",
495
+ * `"quotaResetDelay": "4h58m46.438s"`), verbose formats ("Resets in 15 minutes",
496
+ * "retry after 30 seconds"), and ISO timestamps.
496
497
  */
497
498
  function parseResetDurationMs(text) {
498
499
  if (!text) return void 0;
499
- const compactMatch = text.match(/resets?\s+in\s+((?:(\d+)\s*h)?\s*(?:(\d+)\s*m)?\s*(?:(\d+)\s*s)?)/i);
500
- if (compactMatch && compactMatch[1]?.trim()) {
500
+ const compactMatch = text.match(/(?:resets?\s+(?:in|after)|"(?:quotaResetDelay|retryDelay)"\s*:\s*")\s*((?:(\d+)\s*h)?\s*(?:(\d+)\s*m)?\s*(?:(\d+(?:\.\d+)?)\s*s)?)/i);
501
+ if (compactMatch && (compactMatch[2] || compactMatch[3] || compactMatch[4])) {
501
502
  const hours = parseInt(compactMatch[2] || "0", 10);
502
503
  const minutes = parseInt(compactMatch[3] || "0", 10);
503
- const seconds = parseInt(compactMatch[4] || "0", 10);
504
- const totalMs = (hours * 3600 + minutes * 60 + seconds) * 1e3;
505
- if (totalMs > 0) return totalMs;
504
+ const seconds = parseFloat(compactMatch[4] || "0");
505
+ const totalMs = Math.round((hours * 3600 + minutes * 60 + seconds) * 1e3);
506
+ if (Number.isFinite(totalMs) && totalMs > 0) return totalMs;
506
507
  }
507
508
  const wordMatch = text.match(/(?:resets?|retry)\s+(?:in|after)\s+(\d+)\s*(hour|hr|minute|min|second|sec)s?/i);
508
509
  if (wordMatch) {
@@ -518,6 +519,45 @@ function parseResetDurationMs(text) {
518
519
  if (!Number.isNaN(parsed) && parsed > Date.now()) return parsed - Date.now();
519
520
  }
520
521
  }
522
+ const TRANSIENT_BURST_CAP_MS = 3e4;
523
+ /**
524
+ * True when a 429 error represents a short transient per-minute/per-second QPS burst
525
+ * (`reason: RATE_LIMIT_EXCEEDED` with reset <= 30s) rather than window quota exhaustion.
526
+ * Must NOT trigger long account cooldown or kill a running parent conversation.
527
+ */
528
+ function isTransientBurstRateLimit(text) {
529
+ if (!text) return false;
530
+ if (!/\bRATE_LIMIT_EXCEEDED\b/i.test(text)) return false;
531
+ if (/\bQUOTA_EXHAUSTED\b|individual quota reached/i.test(text)) return false;
532
+ const resetMs = parseResetDurationMs(text);
533
+ return resetMs !== void 0 && resetMs > 0 && resetMs <= TRANSIENT_BURST_CAP_MS;
534
+ }
535
+ /** Extract Google RPC error metadata model slug (e.g. "gemini-3.1-flash-image"), if present. */
536
+ function extractQuotaErrorModel(text) {
537
+ if (!text) return void 0;
538
+ return text.match(/"model"\s*:\s*"([A-Za-z0-9._:/-]+)"/i)?.[1];
539
+ }
540
+ /**
541
+ * True when a failed result envelope carries a hard quota refusal (meaning the
542
+ * attempt must rotate accounts rather than soft-finish on any partial text).
543
+ */
544
+ function isHardQuotaResultError(ok, error, response) {
545
+ if (ok) return false;
546
+ if (error && error.trim() !== "") return looksLikeHardRateLimit(error) && !isTransientBurstRateLimit(error);
547
+ return Boolean(response && looksLikeHardRateLimit(response) && !isTransientBurstRateLimit(response));
548
+ }
549
+ /**
550
+ * True when a failed result envelope represents a non-consumable account/policy
551
+ * failure even when partial response text was already buffered before the error.
552
+ */
553
+ function isNonConsumableResultError(ok, error, response) {
554
+ if (ok) return false;
555
+ if (isHardQuotaResultError(ok, error, response)) return true;
556
+ if (looksLikeTosViolation(error) || looksLikeTosViolation(response)) return true;
557
+ if (looksLikeValidationRequired(error) || looksLikeValidationRequired(response)) return true;
558
+ if (error && (looksLikeEligibilityFailure(error) || looksLikeAuthFailure(error))) return true;
559
+ return false;
560
+ }
521
561
  //#endregion
522
562
  //#region src/common/atomic-write.ts
523
563
  let seq = 0;
@@ -1476,11 +1516,16 @@ function isWeeklyQuotaBenched(quota, clearedAt, now) {
1476
1516
  * `updatedAt` of the snapshot it overrode; the gate stays off only while the
1477
1517
  * cached row is no newer than that stamp, so a fresh poll always re-arms it.
1478
1518
  */
1479
- function isQuotaBenched(acc, family, now) {
1519
+ function isQuotaBenched(acc, family, now, model) {
1480
1520
  const quota = acc.quotas?.[family] ?? (family === "argon" ? acc.quotas?.google : void 0);
1481
1521
  if (!quota) return false;
1482
1522
  const clearedAt = acc.quotaGateClearedAt?.[family];
1483
- return is5hQuotaBenched(quota, clearedAt, now) || isWeeklyQuotaBenched(quota, clearedAt, now);
1523
+ if (is5hQuotaBenched(quota, clearedAt, now) || isWeeklyQuotaBenched(quota, clearedAt, now)) return true;
1524
+ if (!model || model.trim() === "" || !Array.isArray(quota.models)) return false;
1525
+ if (clearedAt !== void 0 && (quota.updatedAt ?? 0) <= clearedAt) return false;
1526
+ const matched = quota.models.filter((m) => modelMatches(model, m.modelId));
1527
+ if (matched.length === 0) return false;
1528
+ return matched.every((m) => isWindowBenched(m.remainingFraction, m.resetTime ?? quota.resetTime, LOW_QUOTA_WEEKLY, now));
1484
1529
  }
1485
1530
  /** True when a family has an active local 429 cooldown timer on this account. */
1486
1531
  function isFamilyInCooldown(acc, family, now) {
@@ -1591,7 +1636,7 @@ function explainIneligibility(acc, family, now, pool, model) {
1591
1636
  if (model && pool?.isModelSupported && !pool.isModelSupported(acc, model)) return "model-unsupported";
1592
1637
  const cd = acc.cooldowns?.[family];
1593
1638
  if (cd && cd.cooldownUntil > now) return "cooldown";
1594
- if (isQuotaBenched(acc, family, now)) return "quota";
1639
+ if (isQuotaBenched(acc, family, now, model)) return "quota";
1595
1640
  return null;
1596
1641
  }
1597
1642
  /**
@@ -2021,7 +2066,7 @@ var PoolAdmin = class {
2021
2066
  consecutiveFailures: failures
2022
2067
  };
2023
2068
  const famPinned = data.activeAccountIds?.[family];
2024
- if (famPinned === id || famPinned === void 0 && data.lastActiveAccountId === id) this.advanceAccount(id, family);
2069
+ if (famPinned === id || famPinned === void 0 && (data.lastActiveAccountId === id || data.lastActiveAccountId === void 0)) this.advanceAccount(id, family);
2025
2070
  this.deps.persist();
2026
2071
  }
2027
2072
  /**
@@ -4198,7 +4243,7 @@ function startAgyProcess(opts) {
4198
4243
  },
4199
4244
  kill: (reason) => {
4200
4245
  if (reason === "timeout") state.timedOut = true;
4201
- else state.aborted = true;
4246
+ else if (reason === "abort") state.aborted = true;
4202
4247
  if (state.watchdog) clearTimeout(state.watchdog);
4203
4248
  if (state.turnCap) clearTimeout(state.turnCap);
4204
4249
  if (state.idleGraceTimer) clearTimeout(state.idleGraceTimer);
@@ -30119,62 +30164,26 @@ async function schemaArgs(schema) {
30119
30164
  })
30120
30165
  };
30121
30166
  }
30122
- async function runAgyOnce(deps, req) {
30123
- const cfg = deps.cfg();
30124
- const bin = deps.bin();
30125
- if (!bin) return {
30126
- ok: false,
30127
- text: "",
30128
- conversationId: null,
30129
- error: "agy binary not found",
30130
- durationMs: 0
30131
- };
30132
- const timeoutMs = req.timeoutMs ?? cfg.timeoutMs;
30133
- const args = [
30134
- "--output-format",
30135
- "stream-json",
30136
- "--print-timeout",
30137
- Math.max(1, Math.ceil(timeoutMs / 6e4)) + "m"
30138
- ];
30139
- const mode = req.mode ?? cfg.permissionMode;
30140
- if (mode === "skip") args.push("--dangerously-skip-permissions");
30141
- else args.push("--mode", mode);
30142
- if (req.sandbox ?? cfg.sandbox) args.push("--sandbox");
30143
- const agent = (req.agent ?? cfg.agent).trim();
30144
- if (agent !== "") args.push("--agent", agent);
30145
- const agySettings = (req.agySettings ?? cfg.agySettings).trim();
30146
- if (agySettings !== "") args.push("--settings", agySettings);
30147
- if (req.conversationId && req.conversationId.trim() !== "") args.push("--conversation", req.conversationId.trim());
30148
- if (req.model) args.push("--model", req.model);
30149
- if (req.effort) args.push("--effort", req.effort);
30150
- let prompt = req.prompt;
30151
- if (req.readPaths && req.readPaths.length > 0) prompt = await inlineFiles(prompt, req.readPaths, cfg.workspaceRoot !== "" ? cfg.workspaceRoot : process.cwd());
30152
- prompt = stripNulBytes(prompt);
30153
- const pool = deps.pool?.();
30154
- const family = modelFamilyOf(req.model || cfg.defaultModel || "gemini");
30155
- const account = pool?.selectAccount(family, req.model) ?? void 0;
30156
- let cleanup = null;
30167
+ async function runSingleOneShotAttempt(opts) {
30168
+ const { deps, cfg, bin, baseArgs, prompt, conversationId: reqCid, timeoutMs, signal, pool, account, family, model, canRetry } = opts;
30169
+ const args = [...baseArgs];
30170
+ if (reqCid && reqCid.trim() !== "") args.push("--conversation", reqCid.trim());
30171
+ args.push("-p", prompt);
30172
+ let stdinPayload;
30173
+ if (shouldUsePromptStdin(args)) {
30174
+ args.splice(args.length - 2, 2);
30175
+ args.push("--input-format", "stream-json");
30176
+ stdinPayload = buildStreamInputLine(prompt);
30177
+ }
30157
30178
  let releaseSem;
30158
30179
  let slotLease;
30159
30180
  try {
30160
- if (req.schema !== void 0 && req.schema !== null) {
30161
- const sa = await schemaArgs(req.schema);
30162
- args.push(...sa.args);
30163
- cleanup = sa.cleanup;
30164
- }
30165
- args.push("-p", prompt);
30166
- let stdinPayload;
30167
- if (shouldUsePromptStdin(args)) {
30168
- args.splice(args.length - 2, 2);
30169
- args.push("--input-format", "stream-json");
30170
- stdinPayload = buildStreamInputLine(prompt);
30171
- }
30172
- if (deps.acquire) releaseSem = await deps.acquire(req.signal);
30181
+ if (deps.acquire) releaseSem = await deps.acquire(signal);
30173
30182
  if (process.platform === "win32" && process.env.NODE_TEST_CONTEXT === void 0 && pool && account) slotLease = await acquireCredentialSlot(account, pool, {
30174
30183
  baseDir: pool.dir,
30175
30184
  proxyUrl: account.proxyUrl || cfg.proxyUrl || detectSystemProxy() || void 0,
30176
30185
  log: deps.log,
30177
- signal: req.signal,
30186
+ signal,
30178
30187
  dispatchTimeoutMs: cfg.dispatchTimeoutMinutes > 0 ? cfg.dispatchTimeoutMinutes * 6e4 : 6e4,
30179
30188
  parallel: cfg.parallelSameAccount
30180
30189
  });
@@ -30182,6 +30191,8 @@ async function runAgyOnce(deps, req) {
30182
30191
  let streamedText = "";
30183
30192
  let prevWasStepText = false;
30184
30193
  let resultText = "";
30194
+ let resultOk = null;
30195
+ let resultError;
30185
30196
  let conversationId = null;
30186
30197
  const appendTextEv = (text, fragment) => {
30187
30198
  if (text === "") return;
@@ -30194,12 +30205,22 @@ async function runAgyOnce(deps, req) {
30194
30205
  prevWasStepText = true;
30195
30206
  }
30196
30207
  };
30208
+ const handleEv = (ev) => {
30209
+ if (ev.kind === "init" && ev.conversationId) conversationId = ev.conversationId;
30210
+ if (ev.kind === "step" && ev.stepKind === "text") appendTextEv(ev.text, ev.fragment);
30211
+ if (ev.kind === "result") {
30212
+ if (ev.conversationId !== "") conversationId = ev.conversationId;
30213
+ resultOk = ev.ok;
30214
+ resultText = ev.response;
30215
+ resultError = ev.error;
30216
+ }
30217
+ };
30197
30218
  const outcome = await startAgyProcess({
30198
30219
  bin,
30199
30220
  args,
30200
30221
  cwd: cfg.workspaceRoot !== "" ? cfg.workspaceRoot : void 0,
30201
30222
  timeoutMs,
30202
- signal: req.signal,
30223
+ signal,
30203
30224
  env: buildAgyEnv({
30204
30225
  ...account ? { account } : {},
30205
30226
  cfg
@@ -30207,66 +30228,268 @@ async function runAgyOnce(deps, req) {
30207
30228
  stdinPayload,
30208
30229
  preemptAutoUpdate: cfg.suppressAgyAutoUpdate,
30209
30230
  onLine: (line) => {
30210
- for (const ev of parser.feed(line + "\n")) {
30211
- if (ev.kind === "init" && ev.conversationId) conversationId = ev.conversationId;
30212
- if (ev.kind === "step" && ev.stepKind === "text") appendTextEv(ev.text, ev.fragment);
30213
- if (ev.kind === "result") {
30214
- if (ev.conversationId !== "") conversationId = ev.conversationId;
30215
- resultText = ev.response;
30216
- }
30217
- }
30231
+ for (const ev of parser.feed(line + "\n")) handleEv(ev);
30218
30232
  }
30219
30233
  }).outcome;
30220
- for (const ev of parser.flush()) {
30221
- if (ev.kind === "step" && ev.stepKind === "text") appendTextEv(ev.text, ev.fragment);
30222
- if (ev.kind === "result") {
30223
- if (ev.conversationId !== "") conversationId = ev.conversationId;
30224
- resultText = ev.response;
30225
- }
30226
- }
30234
+ for (const ev of parser.flush()) handleEv(ev);
30227
30235
  if (outcome.aborted) return {
30228
- ok: false,
30229
- text: "",
30230
- conversationId,
30231
- error: "aborted",
30232
- durationMs: outcome.durationMs
30236
+ kind: "done",
30237
+ result: {
30238
+ ok: false,
30239
+ text: "",
30240
+ conversationId,
30241
+ error: "aborted",
30242
+ durationMs: outcome.durationMs
30243
+ }
30233
30244
  };
30234
30245
  if (outcome.timedOut) return {
30235
- ok: false,
30236
- text: "",
30237
- conversationId,
30238
- error: "timed out after " + timeoutMs + "ms",
30239
- durationMs: outcome.durationMs
30246
+ kind: "done",
30247
+ result: {
30248
+ ok: false,
30249
+ text: "",
30250
+ conversationId,
30251
+ error: "timed out after " + timeoutMs + "ms",
30252
+ durationMs: outcome.durationMs
30253
+ }
30240
30254
  };
30241
30255
  const joined = streamedText.trim();
30242
30256
  const text = joined !== "" ? joined : resultText;
30243
- if (text === "" && (looksLikeAuthFailure(outcome.stderrTail) || parser.stats.sawAuthFailure)) return {
30244
- ok: false,
30245
- text: "",
30246
- conversationId,
30247
- error: "agy is not signed in — run /agy auth",
30248
- durationMs: outcome.durationMs
30249
- };
30257
+ const rawErr = [
30258
+ resultError,
30259
+ parser.stats.lastResultError,
30260
+ outcome.stderrTail,
30261
+ resultOk === false ? resultText : ""
30262
+ ].filter((s) => typeof s === "string" && s.trim() !== "").join(" ").trim();
30263
+ if (looksLikeTosViolation(rawErr) || looksLikeTosViolation(resultText)) {
30264
+ if (pool && account) pool.markAuthRequired(account.id, rawErr || resultText);
30265
+ return {
30266
+ kind: "done",
30267
+ result: {
30268
+ ok: false,
30269
+ text: "",
30270
+ conversationId,
30271
+ error: rawErr || resultText || "TOS_VIOLATION",
30272
+ durationMs: outcome.durationMs
30273
+ }
30274
+ };
30275
+ }
30276
+ if (isHardQuotaResultError(resultOk !== false, resultError, resultText) || looksLikeHardRateLimit(rawErr) && !isTransientBurstRateLimit(rawErr)) {
30277
+ const errModel = extractQuotaErrorModel(rawErr);
30278
+ const modelFam = errModel ? modelFamilyOf(errModel) : void 0;
30279
+ const targetFam = modelFam && modelFam !== "unknown" ? modelFam : family;
30280
+ const resetMs = parseResetDurationMs(rawErr);
30281
+ const resetIso = resetMs && resetMs > 0 ? new Date(Date.now() + resetMs).toISOString() : void 0;
30282
+ if (pool && account) {
30283
+ pool.recordFailure(account.id, targetFam, rawErr || "quota exhausted", resetIso);
30284
+ if (targetFam !== family) pool.advanceAccount(account.id, family, model);
30285
+ }
30286
+ const errMsg = rawErr || "Antigravity quota / rate limit reached";
30287
+ if (canRetry && pool && pool.selectAccount(family, model) !== null) return {
30288
+ kind: "retry",
30289
+ error: errMsg,
30290
+ durationMs: outcome.durationMs
30291
+ };
30292
+ return {
30293
+ kind: "done",
30294
+ result: {
30295
+ ok: false,
30296
+ text: "",
30297
+ conversationId,
30298
+ error: errMsg,
30299
+ durationMs: outcome.durationMs
30300
+ }
30301
+ };
30302
+ }
30303
+ const nonConsumable = resultOk === false && isNonConsumableResultError(false, resultError, resultText);
30304
+ if (nonConsumable || text === "") {
30305
+ if (looksLikeEligibilityFailure(rawErr)) {
30306
+ if (pool && account) pool.advanceAccount(account.id, family, model);
30307
+ if (canRetry && pool && pool.selectAccount(family, model) !== null) return {
30308
+ kind: "retry",
30309
+ error: rawErr,
30310
+ durationMs: outcome.durationMs
30311
+ };
30312
+ return {
30313
+ kind: "done",
30314
+ result: {
30315
+ ok: false,
30316
+ text: "",
30317
+ conversationId,
30318
+ error: rawErr,
30319
+ durationMs: outcome.durationMs
30320
+ }
30321
+ };
30322
+ }
30323
+ if (looksLikeAuthFailure(rawErr) || parser.stats.sawAuthFailure) {
30324
+ if (pool && account && shouldMarkAuthRequired("AUTH", rawErr)) {
30325
+ pool.noteAuthFailure(account.id, rawErr);
30326
+ pool.advanceAccount(account.id, family, model);
30327
+ }
30328
+ if (canRetry && pool && pool.selectAccount(family, model) !== null) return {
30329
+ kind: "retry",
30330
+ error: "agy is not signed in — run /agy auth",
30331
+ durationMs: outcome.durationMs
30332
+ };
30333
+ return {
30334
+ kind: "done",
30335
+ result: {
30336
+ ok: false,
30337
+ text: "",
30338
+ conversationId,
30339
+ error: "agy is not signed in — run /agy auth",
30340
+ durationMs: outcome.durationMs
30341
+ }
30342
+ };
30343
+ }
30344
+ if (nonConsumable) return {
30345
+ kind: "done",
30346
+ result: {
30347
+ ok: false,
30348
+ text: "",
30349
+ conversationId,
30350
+ error: rawErr || resultText,
30351
+ durationMs: outcome.durationMs
30352
+ }
30353
+ };
30354
+ }
30250
30355
  if (outcome.code !== 0 && text === "") {
30251
30356
  const envelopeError = parser.stats.lastResultError ?? "";
30252
30357
  const detail = envelopeError !== "" ? envelopeError : outcome.stderrTail.slice(-300);
30253
30358
  return {
30359
+ kind: "done",
30360
+ result: {
30361
+ ok: false,
30362
+ text: "",
30363
+ conversationId,
30364
+ error: "agy exited with code " + outcome.code + ": " + detail,
30365
+ durationMs: outcome.durationMs
30366
+ }
30367
+ };
30368
+ }
30369
+ if (text !== "") {
30370
+ if (pool && account) pool.recordSuccess(account.id, family);
30371
+ return {
30372
+ kind: "done",
30373
+ result: {
30374
+ ok: true,
30375
+ text,
30376
+ conversationId,
30377
+ durationMs: outcome.durationMs
30378
+ }
30379
+ };
30380
+ }
30381
+ return {
30382
+ kind: "done",
30383
+ result: {
30254
30384
  ok: false,
30255
- text: "",
30385
+ text: "(no output)",
30256
30386
  conversationId,
30257
- error: "agy exited with code " + outcome.code + ": " + detail,
30258
30387
  durationMs: outcome.durationMs
30388
+ }
30389
+ };
30390
+ } finally {
30391
+ slotLease?.release();
30392
+ releaseSem?.();
30393
+ }
30394
+ }
30395
+ async function runAgyOnce(deps, req) {
30396
+ const cfg = deps.cfg();
30397
+ const bin = deps.bin();
30398
+ if (!bin) return {
30399
+ ok: false,
30400
+ text: "",
30401
+ conversationId: null,
30402
+ error: "agy binary not found",
30403
+ durationMs: 0
30404
+ };
30405
+ const timeoutMs = req.timeoutMs ?? cfg.timeoutMs;
30406
+ const baseArgs = [
30407
+ "--output-format",
30408
+ "stream-json",
30409
+ "--print-timeout",
30410
+ Math.max(1, Math.ceil(timeoutMs / 6e4)) + "m"
30411
+ ];
30412
+ const mode = req.mode ?? cfg.permissionMode;
30413
+ if (mode === "skip") baseArgs.push("--dangerously-skip-permissions");
30414
+ else baseArgs.push("--mode", mode);
30415
+ if (req.sandbox ?? cfg.sandbox) baseArgs.push("--sandbox");
30416
+ const agent = (req.agent ?? cfg.agent).trim();
30417
+ if (agent !== "") baseArgs.push("--agent", agent);
30418
+ const agySettings = (req.agySettings ?? cfg.agySettings).trim();
30419
+ if (agySettings !== "") baseArgs.push("--settings", agySettings);
30420
+ if (req.model) baseArgs.push("--model", req.model);
30421
+ if (req.effort) baseArgs.push("--effort", req.effort);
30422
+ let prompt = req.prompt;
30423
+ if (req.readPaths && req.readPaths.length > 0) prompt = await inlineFiles(prompt, req.readPaths, cfg.workspaceRoot !== "" ? cfg.workspaceRoot : process.cwd());
30424
+ prompt = stripNulBytes(prompt);
30425
+ const pool = deps.pool?.();
30426
+ const family = modelFamilyOf(req.model || cfg.defaultModel || "gemini");
30427
+ const enabledCount = pool ? pool.getAccounts().filter((a) => a.enabled).length : 0;
30428
+ const maxAttempts = pool ? Math.min(Math.max(1, enabledCount), 17) : 1;
30429
+ const triedAccounts = /* @__PURE__ */ new Set();
30430
+ let totalDurationMs = 0;
30431
+ let lastError = "";
30432
+ let cleanup = null;
30433
+ try {
30434
+ if (req.schema !== void 0 && req.schema !== null) {
30435
+ const sa = await schemaArgs(req.schema);
30436
+ baseArgs.push(...sa.args);
30437
+ cleanup = sa.cleanup;
30438
+ }
30439
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
30440
+ if (req.signal?.aborted) return {
30441
+ ok: false,
30442
+ text: "",
30443
+ conversationId: null,
30444
+ error: "aborted",
30445
+ durationMs: totalDurationMs
30446
+ };
30447
+ let account;
30448
+ if (pool && pool.getAccounts().length > 0) {
30449
+ const selected = pool.selectAccount(family, req.model);
30450
+ if (!selected || triedAccounts.has(selected.id)) return {
30451
+ ok: false,
30452
+ text: "",
30453
+ conversationId: null,
30454
+ error: lastError || "All Antigravity accounts are currently unavailable (cooling down, quota exhausted, or disabled)",
30455
+ durationMs: totalDurationMs
30456
+ };
30457
+ account = selected;
30458
+ triedAccounts.add(selected.id);
30459
+ }
30460
+ const out = await runSingleOneShotAttempt({
30461
+ deps,
30462
+ cfg,
30463
+ bin,
30464
+ baseArgs,
30465
+ prompt,
30466
+ ...attempt === 0 && req.conversationId !== void 0 ? { conversationId: req.conversationId } : {},
30467
+ timeoutMs,
30468
+ ...req.signal !== void 0 ? { signal: req.signal } : {},
30469
+ ...pool !== void 0 ? { pool } : {},
30470
+ ...account !== void 0 ? { account } : {},
30471
+ family,
30472
+ ...req.model !== void 0 ? { model: req.model } : {},
30473
+ canRetry: attempt + 1 < maxAttempts
30474
+ });
30475
+ if (out.kind === "retry") {
30476
+ totalDurationMs += out.durationMs;
30477
+ lastError = out.error;
30478
+ continue;
30479
+ }
30480
+ return {
30481
+ ...out.result,
30482
+ durationMs: totalDurationMs + out.result.durationMs
30259
30483
  };
30260
30484
  }
30261
30485
  return {
30262
- ok: text !== "",
30263
- text: text === "" ? "(no output)" : text,
30264
- conversationId,
30265
- durationMs: outcome.durationMs
30486
+ ok: false,
30487
+ text: "",
30488
+ conversationId: null,
30489
+ error: lastError || "All Antigravity accounts are currently unavailable",
30490
+ durationMs: totalDurationMs
30266
30491
  };
30267
30492
  } finally {
30268
- slotLease?.release();
30269
- releaseSem?.();
30270
30493
  if (cleanup) cleanup().catch(() => {});
30271
30494
  }
30272
30495
  }
@@ -30432,6 +30655,9 @@ function classifyToolError(error) {
30432
30655
  return "tool_error";
30433
30656
  }
30434
30657
  const waiters = Symbol("waiters");
30658
+ function isConsumableResult(ev) {
30659
+ return (ev.ok || ev.response !== "") && !isNonConsumableResultError(ev.ok, ev.error, ev.response);
30660
+ }
30435
30661
  /** One agy run's append-only event log plus its settlement state. */
30436
30662
  var RunRecording = class {
30437
30663
  now;
@@ -30587,10 +30813,10 @@ var RunRecording = class {
30587
30813
  get hasResult() {
30588
30814
  return this.events.some((e) => e.kind === "result");
30589
30815
  }
30590
- /** Whether a result event that EventMapper will finish on (ok, or non-empty error response) was recorded. */
30816
+ /** Whether a result event that EventMapper will finish on (ok, or non-empty consumable error response) was recorded. */
30591
30817
  get hasConsumableResult() {
30592
30818
  const r = this.getResultEvent();
30593
- return r !== null && (r.ok || r.response !== "");
30819
+ return r !== null && isConsumableResult(r);
30594
30820
  }
30595
30821
  /**
30596
30822
  * Whether any recorded event at or after `from` can finish a span cleanly
@@ -30603,7 +30829,7 @@ var RunRecording = class {
30603
30829
  for (let i = Math.max(0, from); i < this.events.length; i++) {
30604
30830
  const ev = this.events[i];
30605
30831
  if (ev === void 0) continue;
30606
- if (ev.kind === "result" && (ev.ok || ev.response !== "")) return true;
30832
+ if (ev.kind === "result" && isConsumableResult(ev)) return true;
30607
30833
  if (cutOnTool && ev.kind === "step" && ev.stepKind === "tool" && ev.tool !== void 0 && (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))) return true;
30608
30834
  }
30609
30835
  return false;
@@ -30614,22 +30840,21 @@ var RunRecording = class {
30614
30840
  const ev = this.events[i];
30615
30841
  if (ev !== void 0 && ev.kind === "result") return {
30616
30842
  ok: ev.ok,
30617
- response: ev.response
30843
+ response: ev.response,
30844
+ ...ev.error === void 0 ? {} : { error: ev.error }
30618
30845
  };
30619
30846
  }
30620
30847
  return null;
30621
30848
  }
30622
30849
  /**
30623
30850
  * True when at least one consumable `result` event (`ok` or non-empty
30624
- * `response`) exists at index >= `from`. A settled recording with
30625
- * `failureInfo === null` and no consumable result at `>= from` would always
30626
- * fail with `agy stream ended without a result event` if re-driven.
30851
+ * `response`, excluding hard quota / policy errors) exists at index >= `from`.
30627
30852
  */
30628
30853
  hasConsumableResultFrom(from) {
30629
30854
  const start = Math.max(0, from);
30630
30855
  for (let i = start; i < this.events.length; i++) {
30631
30856
  const ev = this.events[i];
30632
- if (ev !== void 0 && ev.kind === "result" && (ev.ok || ev.response !== "")) return true;
30857
+ if (ev !== void 0 && ev.kind === "result" && isConsumableResult(ev)) return true;
30633
30858
  }
30634
30859
  return false;
30635
30860
  }
@@ -32851,7 +33076,7 @@ var EventMapper = class {
32851
33076
  return;
32852
33077
  }
32853
33078
  if (!ev.ok) {
32854
- if (ev.response === "") return;
33079
+ if (ev.response === "" || isNonConsumableResultError(ev.ok, ev.error, ev.response)) return;
32855
33080
  const respText = this.formatAssistantText(ev.response);
32856
33081
  if (!this.sawTextStep) {
32857
33082
  yield* this.ensureBlock("text");
@@ -34324,15 +34549,32 @@ function providerRetryPolicyFor(pool) {
34324
34549
  Err.OVERLOADED
34325
34550
  ];
34326
34551
  if (enabledAccounts >= 2) retryableCodes.push(Err.AUTH);
34552
+ const poolHops = Math.min(Math.max(1, enabledAccounts - 1), 16);
34327
34553
  return {
34328
34554
  mode: "normal",
34329
- maxRetries: Math.max(enabledAccounts >= 3 ? 2 : 1, NETWORK_RETRY_DELAYS_MS.length),
34555
+ maxRetries: Math.max(poolHops, NETWORK_RETRY_DELAYS_MS.length),
34330
34556
  retryableCodes,
34331
34557
  initialDelayMs: 2e3,
34332
34558
  maxDelayMs: 45e3,
34333
34559
  jitterRatio: .1
34334
34560
  };
34335
34561
  }
34562
+ function isAuxCall(options) {
34563
+ return (options.purpose ?? "chat") !== "chat" || typeof options.system === "string" && options.system.includes("REVIEW_POLICY");
34564
+ }
34565
+ function canRetryAuxQuota(deps, options, emitted, finish, quotaHops, rawMsg) {
34566
+ if (!isAuxCall(options) || emitted || options.signal?.aborted) return false;
34567
+ if (finish.reason.kind !== "error" || looksLikeTosViolation(rawMsg)) return false;
34568
+ const code = finish.reason.failure?.code;
34569
+ if (code !== Err.RATE_LIMIT && code !== Err.ELIGIBILITY && code !== Err.AUTH) return false;
34570
+ const pool = deps.pool;
34571
+ if (!pool) return false;
34572
+ const enabledCount = pool.getAccounts().filter((a) => a.enabled).length;
34573
+ if (quotaHops >= Math.min(Math.max(0, enabledCount - 1), 16)) return false;
34574
+ const model = options.model || deps.defaultModel?.() || "gemini";
34575
+ const fam = modelFamilyOf(model);
34576
+ return pool.selectAccount(fam, model) !== null;
34577
+ }
34336
34578
  /**
34337
34579
  * Effort self-healing wrapper around streamAttempt (issue #67).
34338
34580
  *
@@ -34344,13 +34586,25 @@ function providerRetryPolicyFor(pool) {
34344
34586
  * becomes one extra spawn. The refusal text itself is the evidence that WE
34345
34587
  * passed the flag, so the replay does not depend on who requested the effort
34346
34588
  * (an explicit request, `defaultEffort`, or the aux channel's pinning).
34589
+ *
34590
+ * Also rotates across spare pool accounts for auxiliary routes (`isAux`) that
34591
+ * bypass `dsh-llm-retry`, and switches accounts when a model is unrecognized.
34347
34592
  */
34348
34593
  async function* streamWithEffortRetry(deps, options) {
34349
- for (let attempt = 0;; attempt++) {
34594
+ let suppressEffort = false;
34595
+ let effortSelfHealed = false;
34596
+ let modelSelfHealed = false;
34597
+ let quotaHops = 0;
34598
+ const isAux = isAuxCall(options);
34599
+ const poolEnabled = deps.pool ? deps.pool.getAccounts().filter((a) => a.enabled).length : 0;
34600
+ const maxAuxHops = Math.min(Math.max(0, poolEnabled - 1), 16);
34601
+ for (;;) {
34350
34602
  let emitted = false;
34603
+ const bufferAux = isAux && quotaHops < maxAuxHops;
34604
+ const buffered = [];
34351
34605
  const telemetry = [];
34352
34606
  let finish = null;
34353
- for await (const chunk of deps.streamAttempt(options, attempt > 0)) {
34607
+ for await (const chunk of deps.streamAttempt(options, suppressEffort)) {
34354
34608
  if (chunk.type === "finish") {
34355
34609
  finish = chunk;
34356
34610
  continue;
@@ -34359,27 +34613,51 @@ async function* streamWithEffortRetry(deps, options) {
34359
34613
  telemetry.push(chunk);
34360
34614
  continue;
34361
34615
  }
34616
+ if (bufferAux) {
34617
+ buffered.push(chunk);
34618
+ continue;
34619
+ }
34362
34620
  emitted = true;
34363
34621
  yield chunk;
34364
34622
  }
34365
34623
  if (finish === null) {
34624
+ for (const chunk of buffered) yield chunk;
34366
34625
  for (const chunk of telemetry) yield chunk;
34367
34626
  return;
34368
34627
  }
34369
- if (attempt === 0 && !emitted && finish.reason.kind === "error") {
34628
+ if (!emitted && finish.reason.kind === "error") {
34370
34629
  const failure = finish.reason.failure;
34371
34630
  const rawMsg = String(failure?.message ?? "");
34372
- const refused = parseEffortUnsupported(rawMsg);
34373
- if (refused !== null) {
34374
- if (deps.catalogAdvertisesEffort?.(refused) !== true) deps.learnEffortUnsupported(refused);
34375
- continue;
34631
+ if (buffered.length === 0) {
34632
+ const refused = parseEffortUnsupported(rawMsg);
34633
+ if (!effortSelfHealed && refused !== null) {
34634
+ effortSelfHealed = true;
34635
+ suppressEffort = true;
34636
+ if (deps.catalogAdvertisesEffort?.(refused) !== true) deps.learnEffortUnsupported(refused);
34637
+ continue;
34638
+ }
34639
+ const unrecog = parseModelNotRecognized(rawMsg);
34640
+ if (!modelSelfHealed && unrecog !== null) {
34641
+ modelSelfHealed = true;
34642
+ if (deps.onModelUnsupported) {
34643
+ deps.onModelUnsupported(unrecog);
34644
+ continue;
34645
+ }
34646
+ if (deps.pool) {
34647
+ const fam = modelFamilyOf(unrecog);
34648
+ const currentId = deps.pool.getActiveAccountId(fam);
34649
+ if (currentId) deps.pool.markModelUnsupported(currentId, unrecog);
34650
+ deps.pool.selectAccount(fam, unrecog);
34651
+ continue;
34652
+ }
34653
+ }
34376
34654
  }
34377
- const unrecog = parseModelNotRecognized(rawMsg);
34378
- if (unrecog !== null && deps.onModelUnsupported) {
34379
- deps.onModelUnsupported(unrecog);
34655
+ if (canRetryAuxQuota(deps, options, emitted, finish, quotaHops, rawMsg)) {
34656
+ quotaHops++;
34380
34657
  continue;
34381
34658
  }
34382
34659
  }
34660
+ for (const chunk of buffered) yield chunk;
34383
34661
  for (const chunk of telemetry) yield chunk;
34384
34662
  yield finish;
34385
34663
  return;
@@ -34582,7 +34860,7 @@ async function finalizeAttempt(input) {
34582
34860
  emitRunTelemetry(input);
34583
34861
  }
34584
34862
  function applySuccess(input) {
34585
- if (input.account) input.pool?.recordSuccess(input.account.id, input.family);
34863
+ if (input.account && !input.cooledInLiveFamilies?.has(input.family)) input.pool?.recordSuccess(input.account.id, input.family);
34586
34864
  input.dropFailoverBudget(input.sessionKey);
34587
34865
  input.clearRateLimitFailover(input.sessionKey);
34588
34866
  input.clearNetworkStreak(input.sessionKey);
@@ -34611,7 +34889,14 @@ function applyFailure(input, failure) {
34611
34889
  */
34612
34890
  function rotateOnFailure(input, failure) {
34613
34891
  const { account, pool, family, outcome } = input;
34614
- if (account && !outcome.aborted && looksLikeHardRateLimit(input.rawErrText)) pool?.recordFailure(account.id, family, failure.message);
34892
+ const qf = input.quotaFailover;
34893
+ const targetFamily = qf?.family ?? family;
34894
+ const resetMs = parseResetDurationMs(input.rawErrText) ?? parseResetDurationMs(failure.message);
34895
+ const serverResetTime = qf?.resetTime ?? (resetMs && resetMs > 0 ? new Date(Date.now() + resetMs).toISOString() : void 0);
34896
+ if (account && !outcome.aborted && (looksLikeHardRateLimit(input.rawErrText) || Boolean(qf))) {
34897
+ if (!qf?.cooledInLive) pool?.recordFailure(account.id, targetFamily, failure.message, serverResetTime);
34898
+ if (qf?.crossFamily) pool?.advanceAccount(account.id, family, input.activeModel);
34899
+ }
34615
34900
  if (account && input.silentTimeout) pool?.advanceAccount(account.id, family);
34616
34901
  if (account && failure.code === Err.ELIGIBILITY) {
34617
34902
  const unrecog = parseModelNotRecognized(failure.message ?? "");
@@ -34631,7 +34916,7 @@ function rotateOnFailure(input, failure) {
34631
34916
  * persisted as resumable-interrupted, then write it.
34632
34917
  */
34633
34918
  function persistFailureBinding(input, failure) {
34634
- const staleConversation = failure.code === Err.AUTH || failure.message !== "" && /conversation.*(not found|invalid|not recognized|expired|does not exist)|session.*(expired|invalid)/i.test(failure.message);
34919
+ const staleConversation = failure.code === Err.AUTH || input.quotaFailover?.crossFamily === true || failure.message !== "" && /conversation.*(not found|invalid|not recognized|expired|does not exist)|session.*(expired|invalid)/i.test(failure.message);
34635
34920
  const interruptedTurn = failure.kind === "aborted" || input.outcome.timedOut === true;
34636
34921
  if (input.persistBinding && input.sessionAccountKey !== "" && staleConversation) input.store.delete(input.sessionAccountKey);
34637
34922
  else if (input.persistBinding && input.sessionAccountKey !== "" && !input.superseded) {
@@ -35705,6 +35990,62 @@ function noteFailure(log, what, err) {
35705
35990
  if (code === "ENOENT" || code === "EACCES" || code === "EPERM" || code === "EBUSY") return;
35706
35991
  log?.(`subagent tracker: ${what} — ${String(err)}`);
35707
35992
  }
35993
+ function createTranscriptCursor(offset = 0) {
35994
+ return {
35995
+ offset,
35996
+ decoder: new StringDecoder("utf8"),
35997
+ rest: ""
35998
+ };
35999
+ }
36000
+ function fileSizeOrZero(logPath) {
36001
+ try {
36002
+ const st = statSync(logPath);
36003
+ return st.isFile() ? st.size : 0;
36004
+ } catch {
36005
+ return 0;
36006
+ }
36007
+ }
36008
+ function readTranscriptDelta(logPath, cursor) {
36009
+ let size;
36010
+ try {
36011
+ const st = statSync(logPath);
36012
+ if (!st.isFile()) return [];
36013
+ size = st.size;
36014
+ } catch {
36015
+ return [];
36016
+ }
36017
+ if (size < cursor.offset) {
36018
+ cursor.offset = 0;
36019
+ cursor.decoder = new StringDecoder("utf8");
36020
+ cursor.rest = "";
36021
+ }
36022
+ if (size === cursor.offset) return [];
36023
+ const length = size - cursor.offset;
36024
+ const buffer = Buffer.allocUnsafe(length);
36025
+ let bytesRead = 0;
36026
+ try {
36027
+ const fd = openSync(logPath, "r");
36028
+ try {
36029
+ bytesRead = readSync(fd, buffer, 0, length, cursor.offset);
36030
+ } finally {
36031
+ closeSync(fd);
36032
+ }
36033
+ } catch {
36034
+ return [];
36035
+ }
36036
+ if (bytesRead <= 0) return [];
36037
+ cursor.offset += bytesRead;
36038
+ const parts = (cursor.rest + cursor.decoder.write(buffer.subarray(0, bytesRead))).split("\n");
36039
+ cursor.rest = parts.pop() ?? "";
36040
+ return parts.filter((line) => line.trim() !== "");
36041
+ }
36042
+ function extractAuthoritativeSubagentQuotaError(text, fromParentSystemMessage) {
36043
+ if (!text) return false;
36044
+ if (!looksLikeHardRateLimit(text) || isTransientBurstRateLimit(text) || looksLikeTosViolation(text)) return false;
36045
+ if (fromParentSystemMessage) return /The subagent\b[\s\S]*?\bencountered an error/i.test(text);
36046
+ if (/Command exited with code\b/i.test(text)) return false;
36047
+ return /image failed to generate|failed to generate content|cloudcode-pa\.googleapis\.com|RESOURCE_EXHAUSTED|QUOTA_EXHAUSTED|Individual quota reached|agent executor error/i.test(text);
36048
+ }
35708
36049
  function isActiveSubagentState(state) {
35709
36050
  return state === void 0 || state === "" || state === "SUBAGENT_STATE_ALIVE";
35710
36051
  }
@@ -35780,6 +36121,8 @@ var SubagentTracker = class {
35780
36121
  active = false;
35781
36122
  polling = false;
35782
36123
  pollIntervalMs;
36124
+ parentCursor = createTranscriptCursor();
36125
+ parentLines = 0;
35783
36126
  constructor(opts) {
35784
36127
  this.opts = opts;
35785
36128
  this.conversationId = opts.conversationId ?? "";
@@ -35793,6 +36136,8 @@ var SubagentTracker = class {
35793
36136
  this.conversationId = cid;
35794
36137
  this.brainDir = null;
35795
36138
  this.baselined = false;
36139
+ this.parentCursor = createTranscriptCursor();
36140
+ this.parentLines = 0;
35796
36141
  this.taskActivity.reset();
35797
36142
  if (this.active) {
35798
36143
  if (this.opts.resumed === true) {
@@ -35818,6 +36163,8 @@ var SubagentTracker = class {
35818
36163
  try {
35819
36164
  if (!this.brainDir) this.brainDir = findBrainDir(this.conversationId, this.accountHome);
35820
36165
  if (!this.brainDir) return;
36166
+ const parentLog = join(this.brainDir, ".system_generated", "logs", "transcript.jsonl");
36167
+ this.parentCursor = createTranscriptCursor(fileSizeOrZero(parentLog));
35821
36168
  this.taskActivity.baseline(this.brainDir);
35822
36169
  this.scanSubagentsForConv(this.conversationId, true);
35823
36170
  for (const cid of Array.from(this.trackedSubagents.keys())) this.scanSubagentsForConv(cid, true);
@@ -35836,14 +36183,19 @@ var SubagentTracker = class {
35836
36183
  }
35837
36184
  }
35838
36185
  }
35839
- /** Run one scan across known conversations and subagents. */
35840
- poll() {
35841
- if (this.polling || !this.active) return;
36186
+ /** Perform one final synchronous scan even after `stop()` halted the interval. */
36187
+ flush() {
36188
+ this.poll(true);
36189
+ }
36190
+ /** Run one scan across parent transcript, known conversations, and subagents. */
36191
+ poll(force = false) {
36192
+ if (this.polling || !this.active && !force) return;
35842
36193
  if (!this.conversationId) return;
35843
36194
  this.polling = true;
35844
36195
  try {
35845
36196
  if (!this.brainDir) this.brainDir = findBrainDir(this.conversationId, this.accountHome);
35846
36197
  if (!this.brainDir) return;
36198
+ this.pollParentTranscript();
35847
36199
  this.taskActivity.poll(this.brainDir, (ev) => {
35848
36200
  this.emitSubagentEvent(ev.stepKey, ev.text, ev.raw);
35849
36201
  });
@@ -35856,6 +36208,30 @@ var SubagentTracker = class {
35856
36208
  this.polling = false;
35857
36209
  }
35858
36210
  }
36211
+ pollParentTranscript() {
36212
+ if (!this.brainDir) return;
36213
+ const logPath = join(this.brainDir, ".system_generated", "logs", "transcript.jsonl");
36214
+ for (const line of readTranscriptDelta(logPath, this.parentCursor)) try {
36215
+ const o = JSON.parse(line);
36216
+ this.parentLines += 1;
36217
+ if (o.source !== "SYSTEM" || o.type !== "SYSTEM_MESSAGE" || typeof o.content !== "string") continue;
36218
+ if (!extractAuthoritativeSubagentQuotaError(o.content, true)) continue;
36219
+ const qKey = `parent-quota-${typeof o.step_index === "number" ? o.step_index : this.parentLines}`;
36220
+ if (this.seenStepKeys.has(qKey)) continue;
36221
+ const role = o.content.match(/The subagent\s+(.+?)\s+(?:\([^)]+\)\s+)?(?:with id|encountered an error)/i)?.[1]?.trim();
36222
+ const model = extractQuotaErrorModel(o.content);
36223
+ const resetMs = parseResetDurationMs(o.content);
36224
+ const prefix = role ? `[子代理 · ${role}]` : "[子代理]";
36225
+ this.emitSubagentEvent(qKey, `${prefix} 额度已用尽,正在准备切换账号...\n`, o);
36226
+ this.opts.onQuotaExhausted?.({
36227
+ source: "parent-system-message",
36228
+ errorText: o.content,
36229
+ ...role ? { role } : {},
36230
+ ...model ? { model } : {},
36231
+ ...resetMs !== void 0 ? { resetMs } : {}
36232
+ });
36233
+ } catch {}
36234
+ }
35859
36235
  emitSubagentEvent(stepKey, text, raw) {
35860
36236
  if (this.seenStepKeys.has(stepKey)) return;
35861
36237
  this.seenStepKeys.add(stepKey);
@@ -35905,14 +36281,8 @@ var SubagentTracker = class {
35905
36281
  const typeName = typeof desc?.typeName === "string" && desc.typeName !== "" ? desc.typeName : "Subagent";
35906
36282
  const subBrainDir = findBrainDir(subId, this.accountHome) ?? join(bDir, "..", subId);
35907
36283
  const active = isActiveSubagentState(rawState);
35908
- let initialOffset = 0;
35909
- if (baselineOnly || !active) try {
35910
- const logPath = join(subBrainDir, ".system_generated", "logs", "transcript.jsonl");
35911
- const st = statSync(logPath);
35912
- if (st.isFile()) initialOffset = st.size;
35913
- } catch {
35914
- initialOffset = 0;
35915
- }
36284
+ const logPath = join(subBrainDir, ".system_generated", "logs", "transcript.jsonl");
36285
+ const initialOffset = baselineOnly ? fileSizeOrZero(logPath) : 0;
35916
36286
  const tracked = {
35917
36287
  conversationId: subId,
35918
36288
  role,
@@ -35920,9 +36290,7 @@ var SubagentTracker = class {
35920
36290
  brainDir: subBrainDir,
35921
36291
  state: rawState,
35922
36292
  terminal: !active,
35923
- offset: initialOffset,
35924
- decoder: new StringDecoder("utf8"),
35925
- rest: "",
36293
+ cursor: createTranscriptCursor(initialOffset),
35926
36294
  lines: 0
35927
36295
  };
35928
36296
  this.trackedSubagents.set(subId, tracked);
@@ -35931,6 +36299,7 @@ var SubagentTracker = class {
35931
36299
  else if (active) this.emitSubagentEvent(spawnKey, `[子代理 · ${role}] 已启动协同专员 (${typeName})\n`, obj);
35932
36300
  else {
35933
36301
  this.seenStepKeys.add(spawnKey);
36302
+ this.pollSubagentTranscript(tracked, true);
35934
36303
  if (rawState !== void 0) this.emitSubagentEvent(`subagent-state-${subId}-${rawState}`, `[子代理 · ${role}] 协同专员未保持运行 (${rawState})\n`, obj);
35935
36304
  }
35936
36305
  } catch (err) {
@@ -35938,70 +36307,161 @@ var SubagentTracker = class {
35938
36307
  }
35939
36308
  }
35940
36309
  }
35941
- /**
35942
- * Read the transcript lines appended since the last poll.
35943
- *
35944
- * agy rewrites nothing and only appends, so the tracker keeps a byte offset
35945
- * instead of re-reading (and re-splitting) a transcript that grows to hundreds
35946
- * of kilobytes: each poll costs one bounded read of the new bytes.
35947
- */
35948
- readNewLines(sub) {
36310
+ pollSubagentTranscript(sub, quotaOnly = false) {
35949
36311
  const logPath = join(sub.brainDir, ".system_generated", "logs", "transcript.jsonl");
35950
- let size;
35951
- try {
35952
- const st = statSync(logPath);
35953
- if (!st.isFile()) return [];
35954
- size = st.size;
35955
- } catch {
35956
- return [];
35957
- }
35958
- if (size < sub.offset) {
35959
- sub.offset = 0;
35960
- sub.decoder = new StringDecoder("utf8");
35961
- sub.rest = "";
35962
- }
35963
- if (size === sub.offset) return [];
35964
- const length = size - sub.offset;
35965
- const buffer = Buffer.allocUnsafe(length);
35966
- let bytesRead = 0;
35967
- try {
35968
- const fd = openSync(logPath, "r");
35969
- try {
35970
- bytesRead = readSync(fd, buffer, 0, length, sub.offset);
35971
- } finally {
35972
- closeSync(fd);
35973
- }
35974
- } catch {
35975
- return [];
35976
- }
35977
- if (bytesRead <= 0) return [];
35978
- sub.offset += bytesRead;
35979
- const parts = (sub.rest + sub.decoder.write(buffer.subarray(0, bytesRead))).split("\n");
35980
- sub.rest = parts.pop() ?? "";
35981
- return parts.filter((line) => line.trim() !== "");
35982
- }
35983
- pollSubagentTranscript(sub) {
35984
- for (const line of this.readNewLines(sub)) try {
36312
+ for (const line of readTranscriptDelta(logPath, sub.cursor)) try {
35985
36313
  const o = JSON.parse(line);
35986
36314
  sub.lines += 1;
35987
36315
  const stepIdx = typeof o.step_index === "number" ? o.step_index : sub.lines;
35988
36316
  const baseKey = `subagent-${sub.conversationId}-${stepIdx}`;
35989
- if (Array.isArray(o.tool_calls) && o.tool_calls.length > 0) for (let tcIdx = 0; tcIdx < o.tool_calls.length; tcIdx++) {
35990
- const tc = o.tool_calls[tcIdx];
35991
- const toolName = typeof tc?.name === "string" ? tc.name : "";
35992
- if (toolName === "") continue;
35993
- const msg = formatSubagentAction(sub.role, toolName, tc.args);
35994
- this.emitSubagentEvent(`${baseKey}-tc-${tcIdx}`, `${msg}\n`, o);
35995
- }
35996
- else if (o.type === "PLANNER_RESPONSE" && typeof o.content === "string" && o.content.trim() !== "") {
35997
- const firstLine = o.content.trim().split("\n")[0].replace(/^#+\s*/, "").slice(0, 100);
35998
- if (firstLine !== "") this.emitSubagentEvent(`${baseKey}-content`, `[子代理 · ${sub.role}] 阶段进展: ${firstLine}\n`, o);
35999
- }
36000
- if (isTerminalTranscriptStatus(o.status)) this.emitSubagentEvent(`${baseKey}-status`, `[子代理 · ${sub.role}] 执行异常/中止 (${o.status})\n`, o);
36317
+ if (!quotaOnly) {
36318
+ if (Array.isArray(o.tool_calls) && o.tool_calls.length > 0) for (let tcIdx = 0; tcIdx < o.tool_calls.length; tcIdx++) {
36319
+ const tc = o.tool_calls[tcIdx];
36320
+ const toolName = typeof tc?.name === "string" ? tc.name : "";
36321
+ if (toolName === "") continue;
36322
+ const msg = formatSubagentAction(sub.role, toolName, tc.args);
36323
+ this.emitSubagentEvent(`${baseKey}-tc-${tcIdx}`, `${msg}\n`, o);
36324
+ }
36325
+ else if (o.type === "PLANNER_RESPONSE" && typeof o.content === "string" && o.content.trim() !== "") {
36326
+ const firstLine = o.content.trim().split("\n")[0].replace(/^#+\s*/, "").slice(0, 100);
36327
+ if (firstLine !== "") this.emitSubagentEvent(`${baseKey}-content`, `[子代理 · ${sub.role}] 阶段进展: ${firstLine}\n`, o);
36328
+ }
36329
+ }
36330
+ if (isTerminalTranscriptStatus(o.status)) {
36331
+ if (!quotaOnly) this.emitSubagentEvent(`${baseKey}-status`, `[子代理 · ${sub.role}] 执行异常/中止 (${o.status})\n`, o);
36332
+ if (/^(ERROR|FAILED)$/i.test(o.status.trim()) && typeof o.content === "string" && extractAuthoritativeSubagentQuotaError(o.content, false)) {
36333
+ const qKey = `subagent-quota-${sub.conversationId}-${stepIdx}`;
36334
+ if (!this.seenStepKeys.has(qKey)) {
36335
+ const model = extractQuotaErrorModel(o.content);
36336
+ const resetMs = parseResetDurationMs(o.content);
36337
+ this.emitSubagentEvent(qKey, `[子代理 · ${sub.role}] 额度已用尽,正在准备切换账号...\n`, o);
36338
+ this.opts.onQuotaExhausted?.({
36339
+ source: "subagent-transcript",
36340
+ errorText: o.content,
36341
+ role: sub.role,
36342
+ conversationId: sub.conversationId,
36343
+ ...model ? { model } : {},
36344
+ ...resetMs !== void 0 ? { resetMs } : {}
36345
+ });
36346
+ }
36347
+ }
36348
+ }
36001
36349
  } catch {}
36002
36350
  }
36003
36351
  };
36004
36352
  //#endregion
36353
+ //#region src/provider/quota-failover.ts
36354
+ const DIRECT_QUOTA_TOOLS = /* @__PURE__ */ new Set([
36355
+ "generate_image",
36356
+ "invoke_subagent",
36357
+ "swarm",
36358
+ "run_workflow"
36359
+ ]);
36360
+ /**
36361
+ * Inspect one completed/failed tool step for an authoritative hard quota error
36362
+ * emitted directly by agy's image-generation or subagent delegation tool.
36363
+ */
36364
+ function isDirectToolQuotaExhausted(ev) {
36365
+ if (ev.kind !== "step" || ev.stepKind !== "tool" || !ev.tool) return null;
36366
+ if (ev.state !== "ERROR" && !ev.tool.error) return null;
36367
+ const unwrapped = unwrapMcpTool(ev.tool.name, ev.tool.args);
36368
+ if (!DIRECT_QUOTA_TOOLS.has(unwrapped.tool)) return null;
36369
+ const err = [ev.tool.error, typeof ev.tool.output === "string" ? ev.tool.output : ""].filter(Boolean).join(" ").trim();
36370
+ if (err === "") return null;
36371
+ if (!looksLikeHardRateLimit(err) || isTransientBurstRateLimit(err) || looksLikeTosViolation(err)) return null;
36372
+ return {
36373
+ toolName: unwrapped.tool,
36374
+ errorText: err
36375
+ };
36376
+ }
36377
+ /**
36378
+ * Find an alternative healthy account that can serve BOTH the current turn's
36379
+ * `(inputFamily, activeModel)` and (if different) the exhausted `exhaustedFamily`.
36380
+ */
36381
+ function findAlternativeAccount(pool, currentAccountId, inputFamily, activeModel, exhaustedFamily) {
36382
+ const now = Date.now();
36383
+ return pool.getAccounts().find((alt) => {
36384
+ if (alt.id === currentAccountId) return false;
36385
+ if (!(typeof pool.isAccountEligibleForModel === "function" ? pool.isAccountEligibleForModel(alt, inputFamily, activeModel, now) : pool.isAccountEligible(alt, inputFamily, now))) return false;
36386
+ if (exhaustedFamily !== inputFamily && !pool.isAccountEligible(alt, exhaustedFamily, now)) return false;
36387
+ return true;
36388
+ });
36389
+ }
36390
+ function createLiveQuotaController(ctx) {
36391
+ const cooled = /* @__PURE__ */ new Set();
36392
+ let state = null;
36393
+ let triggeredKill = false;
36394
+ const handleQuotaExhausted = (info) => {
36395
+ const raw = info.errorText.trim();
36396
+ if (raw === "" || isTransientBurstRateLimit(raw) || looksLikeTosViolation(raw)) return;
36397
+ const detectedModel = info.model ?? extractQuotaErrorModel(raw);
36398
+ const modelFam = detectedModel ? modelFamilyOf(detectedModel) : void 0;
36399
+ const targetFamily = modelFam && modelFam !== "unknown" ? modelFam : ctx.inputFamily;
36400
+ const resetMs = info.resetMs ?? parseResetDurationMs(raw);
36401
+ const resetTime = resetMs && resetMs > 0 ? new Date(Date.now() + resetMs).toISOString() : void 0;
36402
+ let cooledNow = false;
36403
+ if (ctx.account && ctx.pool && !cooled.has(targetFamily)) {
36404
+ cooled.add(targetFamily);
36405
+ ctx.pool.recordFailure(ctx.account.id, targetFamily, raw, resetTime);
36406
+ cooledNow = true;
36407
+ }
36408
+ const alt = ctx.account && ctx.pool ? findAlternativeAccount(ctx.pool, ctx.account.id, ctx.inputFamily, ctx.activeModel, targetFamily) : void 0;
36409
+ const subject = info.role ? `子代理 (${info.role})` : "子代理/工具";
36410
+ if (alt && !triggeredKill) {
36411
+ triggeredKill = true;
36412
+ state = {
36413
+ family: targetFamily,
36414
+ crossFamily: targetFamily !== ctx.inputFamily,
36415
+ errorText: raw.slice(0, 300),
36416
+ rawErrorText: raw,
36417
+ ...resetTime === void 0 ? {} : { resetTime },
36418
+ cooledInLive: cooledNow || cooled.has(targetFamily)
36419
+ };
36420
+ ctx.emitNotice(`live-quota-switch-${ctx.account?.id ?? "none"}-${targetFamily}`, `[agy] ${subject}额度耗尽,已自动切换至可用账号 ${alt.alias || alt.id}...\n`);
36421
+ ctx.onTriggerKill();
36422
+ } else if (!alt) ctx.emitNotice(`live-quota-none-${ctx.account?.id ?? "none"}-${targetFamily}`, `[agy] ${subject}额度耗尽,当前无其他可用账号可切换\n`);
36423
+ };
36424
+ return {
36425
+ handleQuotaExhausted,
36426
+ failoverState: () => state,
36427
+ cooledFamilies: () => cooled
36428
+ };
36429
+ }
36430
+ function reportDirectToolQuota(quotaCtrl, ev) {
36431
+ if (!quotaCtrl) return;
36432
+ const direct = isDirectToolQuotaExhausted(ev);
36433
+ if (!direct) return;
36434
+ const m = extractQuotaErrorModel(direct.errorText);
36435
+ const r = parseResetDurationMs(direct.errorText);
36436
+ quotaCtrl.handleQuotaExhausted({
36437
+ source: "tool-step",
36438
+ errorText: direct.errorText,
36439
+ ...m ? { model: m } : {},
36440
+ ...r !== void 0 ? { resetMs: r } : {}
36441
+ });
36442
+ }
36443
+ function poolQuotaHopsFor(pool) {
36444
+ if (!pool) return 0;
36445
+ return Math.min(Math.max(0, pool.getAccounts().filter((a) => a.enabled).length - 1), 16);
36446
+ }
36447
+ function createPoolQuotaHooks(pool) {
36448
+ return {
36449
+ poolQuotaHops: () => poolQuotaHopsFor(pool),
36450
+ onQuotaExhausted: (accountId, model, errorText) => {
36451
+ const errFam = modelFamilyOf(extractQuotaErrorModel(errorText) || model);
36452
+ const mainFam = modelFamilyOf(model);
36453
+ const targetFam = errFam !== "unknown" ? errFam : mainFam;
36454
+ const resetMs = parseResetDurationMs(errorText);
36455
+ const resetTime = resetMs && resetMs > 0 ? new Date(Date.now() + resetMs).toISOString() : void 0;
36456
+ if (accountId) {
36457
+ pool.recordFailure(accountId, targetFam, errorText, resetTime);
36458
+ if (targetFam !== mainFam) pool.advanceAccount(accountId, mainFam, model);
36459
+ }
36460
+ return pool.selectAccount(mainFam, model) !== null;
36461
+ }
36462
+ };
36463
+ }
36464
+ //#endregion
36005
36465
  //#region src/provider/attempt.ts
36006
36466
  function brief$1(s) {
36007
36467
  const flat = s.trim().replace(/\s+/g, " ");
@@ -36092,7 +36552,7 @@ function buildSpawnArgs(input, printTimeoutMinutes, log) {
36092
36552
  };
36093
36553
  }
36094
36554
  /** Create the recording, parser, HOME snapshot and tool watchdog for one run. */
36095
- function createAttemptRecorder(deps, cfg, account, initialConversationId, trackSubagents = true) {
36555
+ function createAttemptRecorder(deps, cfg, account, initialConversationId, trackSubagents = true, quotaCtx) {
36096
36556
  const rec = deps.runs.create();
36097
36557
  rec.accountHome = account && account.dir ? account.dir : void 0;
36098
36558
  const conversationsDir = conversationsDirFor(rec.accountHome);
@@ -36100,17 +36560,33 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId, trackS
36100
36560
  const parser = new StreamJsonParser();
36101
36561
  deps.onParser?.(parser);
36102
36562
  const watchdog = createToolWatchdog(deps.log, cfg);
36563
+ let attachedProc = null;
36564
+ let pendingQuotaKill = false;
36565
+ const quotaCtrl = quotaCtx ? createLiveQuotaController({
36566
+ pool: deps.pool,
36567
+ account,
36568
+ inputFamily: quotaCtx.family,
36569
+ activeModel: quotaCtx.activeModel,
36570
+ emitNotice: (stepKey, text) => rec.append({
36571
+ kind: "step",
36572
+ stepKey,
36573
+ stepKind: "subagent",
36574
+ text,
36575
+ raw: {}
36576
+ }),
36577
+ onTriggerKill: () => {
36578
+ if (attachedProc) attachedProc.kill("quota");
36579
+ else pendingQuotaKill = true;
36580
+ }
36581
+ }) : null;
36103
36582
  const tracker = trackSubagents ? new SubagentTracker({
36104
36583
  conversationId: initialConversationId,
36105
36584
  resumed: Boolean(initialConversationId),
36106
36585
  accountHome: rec.accountHome,
36107
36586
  log: deps.log,
36108
- onEvent: (ev) => {
36109
- rec.append(ev);
36110
- },
36111
- noteActivity: () => {
36112
- watchdog.markEvent();
36113
- }
36587
+ onEvent: (ev) => rec.append(ev),
36588
+ ...quotaCtrl ? { onQuotaExhausted: (info) => quotaCtrl.handleQuotaExhausted(info) } : {},
36589
+ noteActivity: () => watchdog.markEvent()
36114
36590
  }) : void 0;
36115
36591
  const state = {
36116
36592
  rec,
@@ -36120,8 +36596,10 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId, trackS
36120
36596
  streamCid: initialConversationId ?? null,
36121
36597
  printTimeoutMinutes: watchdog.printTimeoutMinutes,
36122
36598
  attachProcess: (proc) => {
36599
+ attachedProc = proc;
36123
36600
  watchdog.attach(proc);
36124
36601
  tracker?.start();
36602
+ if (pendingQuotaKill) proc.kill("quota");
36125
36603
  proc.outcome.finally(() => tracker?.stop());
36126
36604
  },
36127
36605
  startTracker: () => {
@@ -36141,6 +36619,7 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId, trackS
36141
36619
  }
36142
36620
  watchdog.trackStep(ev);
36143
36621
  rec.append(ev);
36622
+ reportDirectToolQuota(quotaCtrl, ev);
36144
36623
  if (typeof onEvent === "function") try {
36145
36624
  onEvent(ev);
36146
36625
  } catch {}
@@ -36158,10 +36637,15 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId, trackS
36158
36637
  } catch {}
36159
36638
  }
36160
36639
  },
36640
+ flushTracker: () => {
36641
+ tracker?.flush();
36642
+ },
36161
36643
  stop: () => {
36162
36644
  watchdog.stop();
36163
36645
  tracker?.stop();
36164
36646
  },
36647
+ quotaFailover: () => quotaCtrl?.failoverState() ?? null,
36648
+ cooledInLiveFamilies: () => quotaCtrl?.cooledFamilies() ?? /* @__PURE__ */ new Set(),
36165
36649
  conversationId: () => state.streamCid ?? diffConversations(before, conversationsDir).conversationId
36166
36650
  };
36167
36651
  return state;
@@ -36731,19 +37215,24 @@ async function* dispatchCredentialSlot(deps, input) {
36731
37215
  }
36732
37216
  /** Evidence + failure for one settled run (pure classification inputs). */
36733
37217
  function classifyRun(input) {
36734
- const { cfg, outcome, parser, rec, runLogHome, runLogsBefore } = input;
37218
+ const { cfg, outcome, parser, rec, runLogHome, runLogsBefore, quotaFailover } = input;
36735
37219
  const r = rec.getResultEvent();
36736
37220
  const u = rec.lastUsage ?? rec.finalUsage({});
36737
37221
  const zeroUsageTos = r !== null && (u?.input_tokens ?? 0) === 0 && (u?.output_tokens ?? 0) === 0 && looksLikeTosViolation(r.response);
36738
37222
  const errorResponseTos = r !== null && !r.ok && looksLikeTosViolation(r.response);
36739
- const consumable = r !== null && (r.ok || r.response !== "") && !zeroUsageTos && !errorResponseTos;
37223
+ const errorResponseHardQuota = r !== null && isHardQuotaResultError(r.ok, r.error, r.response);
37224
+ const liveQuota = quotaFailover !== null;
37225
+ const consumable = !liveQuota && r !== null && (r.ok || r.response !== "") && !zeroUsageTos && !errorResponseTos && !errorResponseHardQuota;
37226
+ const runLogText = readAgyRunLogText(runLogHome, runLogsBefore);
37227
+ const logQuotaHint = !consumable && !liveQuota ? runLogText.split(/\r?\n/).filter((l) => /(?:errorreport\.go|session\.go).*?(?:RESOURCE_EXHAUSTED|Individual quota reached|QUOTA_EXHAUSTED)/i.test(l)).slice(-2).join(" ") : "";
36740
37228
  const rawErrText = [
36741
37229
  outcome.stderrTail,
36742
37230
  parser.stats.lastResultError,
36743
- !consumable && r && (!r.ok || zeroUsageTos) ? r.response : ""
37231
+ !consumable && r && (!r.ok || zeroUsageTos) ? r.error ?? r.response : "",
37232
+ liveQuota ? quotaFailover.rawErrorText : "",
37233
+ logQuotaHint
36744
37234
  ].filter(Boolean).join(" ");
36745
- const isRateLimit = looksLikeRateLimit(rawErrText);
36746
- const runLogText = readAgyRunLogText(runLogHome, runLogsBefore);
37235
+ const isRateLimit = liveQuota || looksLikeRateLimit(rawErrText);
36747
37236
  const keyringJitter = looksLikeAuthVerificationJitter(runLogText);
36748
37237
  const transportFailure = isTransportFailure({
36749
37238
  rawErrText,
@@ -36752,20 +37241,27 @@ function classifyRun(input) {
36752
37241
  stdoutHead: outcome.stdout,
36753
37242
  runLogText
36754
37243
  });
36755
- const silentTimeout = outcome.timedOut === true && outcome.stdout.trim() === "";
37244
+ const silentTimeout = !liveQuota && outcome.timedOut === true && outcome.stdout.trim() === "";
37245
+ const failure = classifyFailure({
37246
+ cfg,
37247
+ outcome: liveQuota ? {
37248
+ ...outcome,
37249
+ capped: false,
37250
+ timedOut: false,
37251
+ idleGraceTerminated: false
37252
+ } : outcome,
37253
+ parser,
37254
+ sawAuthFailure: liveQuota ? false : sawAuthFailure(parser, outcome),
37255
+ consumable,
37256
+ transportFailure: liveQuota ? false : transportFailure,
37257
+ keyringJitter: liveQuota ? false : keyringJitter,
37258
+ rawErrText,
37259
+ isRateLimit,
37260
+ silentTimeout
37261
+ });
37262
+ if (failure && liveQuota && failure.code === Err.RATE_LIMIT && parser.stats.lastResultError === void 0 && outcome.stderrTail === "") failure.message = "Google Antigravity quota / rate limit reached (subagent/tool): " + quotaFailover.errorText;
36756
37263
  return {
36757
- failure: classifyFailure({
36758
- cfg,
36759
- outcome,
36760
- parser,
36761
- sawAuthFailure: sawAuthFailure(parser, outcome),
36762
- consumable,
36763
- transportFailure,
36764
- keyringJitter,
36765
- rawErrText,
36766
- isRateLimit,
36767
- silentTimeout
36768
- }),
37264
+ failure,
36769
37265
  rawErrText,
36770
37266
  runLogText,
36771
37267
  silentTimeout
@@ -36788,12 +37284,15 @@ async function handleAttemptOutcome(deps, input, ctx) {
36788
37284
  const { cfg, sessionKey } = input;
36789
37285
  const outcome = await ctx.proc.outcome;
36790
37286
  slot.releaseOnce();
37287
+ recorder.flushTracker();
36791
37288
  recorder.stop();
36792
37289
  deps.unregisterActiveRun(sessionKey, rec);
36793
37290
  deps.clearInFlightPrompt(sessionKey, spawn.prompt);
36794
37291
  recorder.drain(input.agyOnEvent);
37292
+ const quotaFailover = recorder.quotaFailover();
37293
+ const cooledInLiveFamilies = recorder.cooledInLiveFamilies();
36795
37294
  const conversationId = recorder.conversationId();
36796
- if (!rec.hasConsumableResult && outcome.idleGraceTerminated) {
37295
+ if (!rec.hasConsumableResult && outcome.idleGraceTerminated && quotaFailover === null) {
36797
37296
  const recovered = conversationId === null ? "" : recoverFinalReply(conversationId, rec.accountHome);
36798
37297
  const synthResult = {
36799
37298
  kind: "result",
@@ -36812,41 +37311,47 @@ async function handleAttemptOutcome(deps, input, ctx) {
36812
37311
  parser,
36813
37312
  rec,
36814
37313
  runLogHome,
36815
- runLogsBefore
37314
+ runLogsBefore,
37315
+ quotaFailover
36816
37316
  });
36817
37317
  if (failure !== null) {
36818
37318
  if (failure.code === Err.NETWORK) failure.retryAfterMs = networkRetryDelayMs(deps.noteNetworkFailure(sessionKey));
36819
37319
  else deps.clearNetworkStreak(sessionKey);
36820
37320
  }
36821
- rec.settle(failure);
36822
37321
  const superseded = deps.isSuperseded(sessionKey, rec);
36823
- await finalizeAttempt({
36824
- rec,
36825
- outcome,
36826
- failure,
36827
- store: deps.store,
36828
- ...deps.pool === void 0 ? {} : { pool: deps.pool },
36829
- ...input.account === void 0 ? {} : { account: input.account },
36830
- family: input.family,
36831
- persistBinding: input.persistBinding,
36832
- sessionAccountKey: input.sessionAccountKey,
36833
- ...input.binding === void 0 ? {} : { binding: input.binding },
36834
- conversationId,
36835
- messages: input.messages,
36836
- model: input.model,
36837
- activeModel: input.activeModel,
36838
- superseded,
36839
- newlySentImageIds: input.newlySentImageIds,
36840
- rawErrText,
36841
- runLogText,
36842
- silentTimeout,
36843
- sessionKey,
36844
- clearNetworkStreak: (key) => deps.clearNetworkStreak(key),
36845
- dropFailoverBudget: (key) => deps.dropFailoverBudget(key),
36846
- clearRateLimitFailover: (key) => deps.clearRateLimitFailover(key),
36847
- sharesSingleEgress: () => deps.sharesSingleEgress(),
36848
- ...deps.onRun === void 0 ? {} : { onRun: deps.onRun }
36849
- });
37322
+ try {
37323
+ await finalizeAttempt({
37324
+ rec,
37325
+ outcome,
37326
+ failure,
37327
+ store: deps.store,
37328
+ ...deps.pool === void 0 ? {} : { pool: deps.pool },
37329
+ ...input.account === void 0 ? {} : { account: input.account },
37330
+ family: input.family,
37331
+ persistBinding: input.persistBinding,
37332
+ sessionAccountKey: input.sessionAccountKey,
37333
+ ...input.binding === void 0 ? {} : { binding: input.binding },
37334
+ conversationId,
37335
+ messages: input.messages,
37336
+ model: input.model,
37337
+ activeModel: input.activeModel,
37338
+ superseded,
37339
+ newlySentImageIds: input.newlySentImageIds,
37340
+ rawErrText,
37341
+ runLogText,
37342
+ silentTimeout,
37343
+ sessionKey,
37344
+ quotaFailover,
37345
+ cooledInLiveFamilies,
37346
+ clearNetworkStreak: (key) => deps.clearNetworkStreak(key),
37347
+ dropFailoverBudget: (key) => deps.dropFailoverBudget(key),
37348
+ clearRateLimitFailover: (key) => deps.clearRateLimitFailover(key),
37349
+ sharesSingleEgress: () => deps.sharesSingleEgress(),
37350
+ ...deps.onRun === void 0 ? {} : { onRun: deps.onRun }
37351
+ });
37352
+ } finally {
37353
+ rec.settle(failure);
37354
+ }
36850
37355
  }
36851
37356
  /**
36852
37357
  * Run one attempt: recorder → slot dispatch → spawn → concurrent outcome.
@@ -36854,7 +37359,10 @@ async function handleAttemptOutcome(deps, input, ctx) {
36854
37359
  * queue notices; the outcome closure runs detached exactly as before.
36855
37360
  */
36856
37361
  async function* runAgyAttempt(deps, input) {
36857
- const recorder = createAttemptRecorder(deps, input.cfg, input.account, input.binding?.conversationId);
37362
+ const recorder = createAttemptRecorder(deps, input.cfg, input.account, input.binding?.conversationId, true, {
37363
+ family: input.family,
37364
+ activeModel: input.activeModel
37365
+ });
36858
37366
  const spawn = buildSpawnArgs(input, recorder.printTimeoutMinutes, deps.log);
36859
37367
  const slot = yield* dispatchCredentialSlot(deps, {
36860
37368
  ...input,
@@ -37021,21 +37529,14 @@ var AgyAdapter = class extends LlmAdapter {
37021
37529
  buildArgs(opts) {
37022
37530
  return buildAgyArgs(opts);
37023
37531
  }
37024
- /** Effort and model self-healing wrapper around streamAttempt (issue #67, PR #100). */
37532
+ /** Effort, model, and aux-quota self-healing wrapper around streamAttempt (issue #67, PR #100). */
37025
37533
  async *stream(options) {
37026
37534
  yield* streamWithEffortRetry({
37027
37535
  streamAttempt: (opts, suppressEffort) => this.streamAttempt(opts, suppressEffort),
37028
37536
  learnEffortUnsupported: (model) => this.learnEffortUnsupported(model),
37029
37537
  catalogAdvertisesEffort: (model) => this.deps.catalog.advertisedEfforts(model).length > 0,
37030
- onModelUnsupported: (unrecog) => {
37031
- const fam = modelFamilyOf(unrecog);
37032
- const pool = this.deps.pool;
37033
- if (pool) {
37034
- const currentId = pool.getActiveAccountId(fam);
37035
- if (currentId) pool.markModelUnsupported(currentId, unrecog);
37036
- pool.selectAccount(fam, unrecog);
37037
- }
37038
- }
37538
+ pool: this.deps.pool,
37539
+ defaultModel: () => this.deps.getConfig().defaultModel
37039
37540
  }, options);
37040
37541
  }
37041
37542
  async *streamAttempt(options, suppressEffort = false) {
@@ -37774,6 +38275,21 @@ function simplifyRatio(width, height) {
37774
38275
  }
37775
38276
  //#endregion
37776
38277
  //#region src/features/image/service.ts
38278
+ function isHardQuotaErrorText(text) {
38279
+ return Boolean(text && text.trim() !== "" && looksLikeHardRateLimit(text) && !isTransientBurstRateLimit(text) && !looksLikeTosViolation(text));
38280
+ }
38281
+ function detectHardQuotaError(res, replyError) {
38282
+ if (!res.ok) {
38283
+ const err = res.error ?? "";
38284
+ if (looksLikeTosViolation(err)) return null;
38285
+ if (res.code === Err.RATE_LIMIT || res.code === Err.QUOTA || isHardQuotaErrorText(err)) return isTransientBurstRateLimit(err) ? null : err || "Antigravity quota exhausted";
38286
+ return null;
38287
+ }
38288
+ const toolHit = res.toolCalls.find((t) => (t.name === "generate_image" || t.name === "invoke_subagent") && isHardQuotaErrorText(t.error));
38289
+ if (toolHit?.error) return toolHit.error;
38290
+ if (isHardQuotaErrorText(replyError)) return replyError;
38291
+ return null;
38292
+ }
37777
38293
  function emptyImageResult(req, model, effort) {
37778
38294
  return {
37779
38295
  ok: false,
@@ -37931,6 +38447,8 @@ var ImageService = class {
37931
38447
  let last = ctx.last;
37932
38448
  let effort = target.effort;
37933
38449
  let effortFallbackUsed = false;
38450
+ let quotaHopsUsed = 0;
38451
+ const maxQuotaHops = Math.min(Math.max(0, Math.round(this.deps.poolQuotaHops?.() ?? 0)), 16);
37934
38452
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
37935
38453
  const startedAt = this.now();
37936
38454
  last.effort = effort;
@@ -37943,9 +38461,34 @@ var ImageService = class {
37943
38461
  imagePaths: refs,
37944
38462
  ...signal === void 0 ? {} : { signal }
37945
38463
  });
37946
- last.attempts = attempt;
38464
+ last.attempts = attempt + quotaHopsUsed;
37947
38465
  last.durationMs = this.now() - startedAt;
37948
38466
  if (res.conversationId !== void 0) last.conversationId = res.conversationId;
38467
+ if (!res.ok && looksLikeTosViolation(res.error)) return {
38468
+ ...last,
38469
+ ok: false,
38470
+ code: "AGY_ERROR",
38471
+ error: res.error ?? "account suspended (TOS_VIOLATION)"
38472
+ };
38473
+ const reply = res.ok ? parseImageReply(res.text) : { error: void 0 };
38474
+ const quotaErr = detectHardQuotaError(res, reply.error);
38475
+ if (quotaErr !== null) {
38476
+ last = {
38477
+ ...last,
38478
+ ok: false,
38479
+ code: "NO_ACCOUNT",
38480
+ error: quotaErr
38481
+ };
38482
+ const errModel = extractQuotaErrorModel(quotaErr) ?? target.model;
38483
+ const canSwitch = this.deps.onQuotaExhausted ? this.deps.onQuotaExhausted(res.accountId, errModel, quotaErr) : true;
38484
+ if (canSwitch && quotaHopsUsed < maxQuotaHops) {
38485
+ quotaHopsUsed++;
38486
+ attempt--;
38487
+ continue;
38488
+ }
38489
+ if (canSwitch && attempt < maxAttempts) continue;
38490
+ return last;
38491
+ }
37949
38492
  if (!res.ok) {
37950
38493
  const failure = res.error ?? "";
37951
38494
  if (!effortFallbackUsed && effort !== "" && /--effort/i.test(failure) && /not supported/i.test(failure)) {
@@ -37975,7 +38518,6 @@ var ImageService = class {
37975
38518
  if (attempt < maxAttempts) continue;
37976
38519
  return last;
37977
38520
  }
37978
- const reply = parseImageReply(res.text);
37979
38521
  if (reply.error !== void 0) {
37980
38522
  last = {
37981
38523
  ...last,
@@ -38164,6 +38706,14 @@ async function runViaAdapter(adapter, call) {
38164
38706
  agyImagePrompt: call.prompt,
38165
38707
  agyPermissionMode: call.permissionMode,
38166
38708
  agyOnAccount: (info) => {
38709
+ if (accountId !== void 0 && typeof info.id === "string" && info.id !== accountId) {
38710
+ toolCalls.length = 0;
38711
+ subagents.length = 0;
38712
+ textParts.length = 0;
38713
+ responseText = "";
38714
+ conversationId = void 0;
38715
+ failure = null;
38716
+ }
38167
38717
  if (typeof info.id === "string") accountId = info.id;
38168
38718
  if (typeof info.home === "string" && info.home !== "") home = info.home;
38169
38719
  },
@@ -41490,14 +42040,18 @@ var TranslationService = class {
41490
42040
  }
41491
42041
  }
41492
42042
  async withRetry(req, retries, signal) {
41493
- const max = Math.max(0, Math.round(retries));
42043
+ const maxNonQuota = Math.max(0, Math.round(retries));
42044
+ const maxQuota = Math.max(maxNonQuota, Math.min(Math.max(0, Math.round(this.deps.poolQuotaHops?.() ?? 0)), 16));
42045
+ let nonQuotaErrors = 0;
42046
+ let quotaErrors = 0;
42047
+ let attempt = 0;
41494
42048
  let last = {
41495
42049
  ok: false,
41496
42050
  text: "",
41497
42051
  error: "translation was never attempted",
41498
42052
  code: Err.AGY_ERROR
41499
42053
  };
41500
- for (let attempt = 0; attempt <= max; attempt++) {
42054
+ for (;;) {
41501
42055
  if (signal?.aborted === true) {
41502
42056
  last = {
41503
42057
  ok: false,
@@ -41518,9 +42072,17 @@ var TranslationService = class {
41518
42072
  };
41519
42073
  }
41520
42074
  if (last.ok) return last;
41521
- if (last.code === "ABORTED" || last.code !== void 0 && !RETRYABLE_CODES.has(last.code)) break;
42075
+ if (last.code === "ABORTED" || looksLikeTosViolation(last.error) || last.code !== void 0 && !RETRYABLE_CODES.has(last.code)) break;
42076
+ if (last.code === Err.RATE_LIMIT || last.code === Err.QUOTA) {
42077
+ quotaErrors++;
42078
+ if (quotaErrors > maxQuota) break;
42079
+ } else {
42080
+ nonQuotaErrors++;
42081
+ if (nonQuotaErrors > maxNonQuota) break;
42082
+ }
41522
42083
  const pause = last.code === Err.EMPTY_RESPONSE ? 900 * (attempt + 1) : 150 * (attempt + 1);
41523
- if (attempt < max) await delay(pause, signal);
42084
+ attempt++;
42085
+ await delay(pause, signal);
41524
42086
  }
41525
42087
  return last;
41526
42088
  }
@@ -42154,7 +42716,7 @@ var TranslationWorkerPool = class {
42154
42716
  ...accountPatch,
42155
42717
  durationMs
42156
42718
  };
42157
- if (looksLikeHardRateLimit(errText)) {
42719
+ if (looksLikeHardRateLimit(errText) && !isTransientBurstRateLimit(errText)) {
42158
42720
  if (account && pool) {
42159
42721
  const resetMs = parseResetDurationMs(errText);
42160
42722
  const resetIso = resetMs ? new Date(this.now() + resetMs).toISOString() : void 0;
@@ -45485,15 +46047,17 @@ function acpUsageToRawUsage(u) {
45485
46047
  }
45486
46048
  function acpPromptResultToAgyEvent(sessionId, result, accumulatedText) {
45487
46049
  const stopReason = typeof result.stopReason === "string" ? result.stopReason : "end_turn";
45488
- const ok = stopReason !== "error" && stopReason !== "refusal";
46050
+ const rawErr = result.error;
46051
+ const errObj = asObj(rawErr);
46052
+ const extractedErr = typeof rawErr === "string" && rawErr !== "" ? rawErr : typeof errObj?.message === "string" && errObj.message !== "" ? errObj.message : void 0;
46053
+ const ok = stopReason !== "error" && stopReason !== "refusal" && extractedErr === void 0;
45489
46054
  const usage = acpUsageToRawUsage(result.usage);
45490
- const errMsg = !ok && typeof result.error === "string" ? result.error : void 0;
45491
46055
  return {
45492
46056
  kind: "result",
45493
46057
  conversationId: sessionId,
45494
46058
  ok,
45495
46059
  response: accumulatedText,
45496
- ...errMsg ? { error: errMsg } : {},
46060
+ ...!ok && extractedErr ? { error: extractedErr } : {},
45497
46061
  usage,
45498
46062
  raw: result
45499
46063
  };
@@ -46025,7 +46589,7 @@ var AcpSessionPool = class {
46025
46589
  //#endregion
46026
46590
  //#region src/features/acp/run-attempt.ts
46027
46591
  async function settleAcpOutcome(opts) {
46028
- const { deps, input, rec, account, sid, failure, durationMs, stderr, rawErrText, runLogText, silentTimeout, outcomeOverride } = opts;
46592
+ const { deps, input, rec, account, sid, failure, durationMs, stderr, rawErrText, runLogText, silentTimeout, quotaFailover, cooledInLiveFamilies, outcomeOverride } = opts;
46029
46593
  await finalizeAttempt({
46030
46594
  rec,
46031
46595
  outcome: outcomeOverride ?? {
@@ -46056,6 +46620,8 @@ async function settleAcpOutcome(opts) {
46056
46620
  runLogText,
46057
46621
  silentTimeout,
46058
46622
  sessionKey: input.sessionKey,
46623
+ ...quotaFailover === void 0 ? {} : { quotaFailover },
46624
+ ...cooledInLiveFamilies === void 0 ? {} : { cooledInLiveFamilies },
46059
46625
  clearNetworkStreak: (k) => deps.clearNetworkStreak(k),
46060
46626
  dropFailoverBudget: (k) => deps.dropFailoverBudget(k),
46061
46627
  clearRateLimitFailover: (k) => deps.clearRateLimitFailover(k),
@@ -46070,11 +46636,38 @@ async function driveAcpPrompt(opts) {
46070
46636
  const streamState = createAcpStreamState();
46071
46637
  let emittedAny = false;
46072
46638
  let terminalFailure = null;
46639
+ let quotaCancelled = false;
46640
+ const quotaCtrl = createLiveQuotaController({
46641
+ pool: deps.pool,
46642
+ account,
46643
+ inputFamily: input.family,
46644
+ activeModel: input.activeModel,
46645
+ emitNotice: (stepKey, text) => recorder.rec.append({
46646
+ kind: "step",
46647
+ stepKey,
46648
+ stepKind: "subagent",
46649
+ text,
46650
+ raw: {}
46651
+ }),
46652
+ onTriggerKill: () => {
46653
+ quotaCancelled = true;
46654
+ proc.cancelSession(sid);
46655
+ }
46656
+ });
46657
+ const subTracker = !input.isAux && sid !== "" ? new SubagentTracker({
46658
+ conversationId: sid,
46659
+ resumed: Boolean(input.binding?.conversationId),
46660
+ accountHome: recorder.rec.accountHome,
46661
+ log: deps.log,
46662
+ onEvent: (ev) => recorder.rec.append(ev),
46663
+ onQuotaExhausted: (info) => quotaCtrl.handleQuotaExhausted(info)
46664
+ }) : null;
46073
46665
  try {
46666
+ subTracker?.start();
46074
46667
  const idleMs = cfg.timeoutMs;
46075
46668
  const longToolIdleMs = cfg.longToolIdleMinutes > 0 ? cfg.longToolIdleMinutes * 6e4 : 0;
46076
46669
  const maxTurnMs = cfg.maxTurnMinutes > 0 ? cfg.maxTurnMinutes * 6e4 : 0;
46077
- const resEv = acpPromptResultToAgyEvent(sid, await proc.prompt({
46670
+ const result = await proc.prompt({
46078
46671
  sessionId: sid,
46079
46672
  text: input.prompt,
46080
46673
  timeoutMs: idleMs,
@@ -46087,12 +46680,17 @@ async function driveAcpPrompt(opts) {
46087
46680
  emittedAny = true;
46088
46681
  recorder.rec.append(ev);
46089
46682
  input.agyOnEvent?.(ev);
46683
+ reportDirectToolQuota(quotaCtrl, ev);
46090
46684
  }
46091
46685
  }
46092
- }), streamState.accumulatedText);
46686
+ });
46687
+ subTracker?.flush();
46688
+ const liveQf = quotaCtrl.failoverState();
46689
+ if (liveQf !== null) throw new Error(liveQf.rawErrorText);
46690
+ const resEv = acpPromptResultToAgyEvent(sid, result, streamState.accumulatedText);
46093
46691
  recorder.rec.append(resEv);
46094
46692
  input.agyOnEvent?.(resEv);
46095
- if (resEv.kind === "result" && !resEv.ok && resEv.response === "") throw new Error(resEv.error ?? "ACP prompt returned error without response");
46693
+ if (resEv.kind === "result" && !resEv.ok && (resEv.response === "" || isNonConsumableResultError(resEv.ok, resEv.error, resEv.response))) throw new Error(resEv.error ?? "ACP prompt returned error without response");
46096
46694
  await settleAcpOutcome({
46097
46695
  deps,
46098
46696
  input,
@@ -46104,14 +46702,21 @@ async function driveAcpPrompt(opts) {
46104
46702
  stderr: proc.stderr,
46105
46703
  rawErrText: "",
46106
46704
  runLogText: "",
46107
- silentTimeout: false
46705
+ silentTimeout: false,
46706
+ cooledInLiveFamilies: quotaCtrl.cooledFamilies()
46108
46707
  });
46109
46708
  } catch (err) {
46709
+ subTracker?.flush();
46710
+ const liveQf = quotaCtrl.failoverState();
46110
46711
  const msg = err instanceof Error ? err.message : String(err);
46111
- const rawErrText = `${msg} ${proc.stderr}`.trim();
46712
+ const rawErrText = [
46713
+ msg,
46714
+ proc.stderr,
46715
+ liveQf?.rawErrorText
46716
+ ].filter(Boolean).join(" ").trim();
46112
46717
  const runLogText = readAgyRunLogText(runLogHome, runLogsBefore);
46113
- const timedOut = /timed out/i.test(msg);
46114
- const aborted = Boolean(input.signal?.aborted) || /aborted/i.test(msg);
46718
+ const timedOut = liveQf === null && /timed out/i.test(msg);
46719
+ const aborted = !quotaCancelled && liveQf === null && (Boolean(input.signal?.aborted) || /aborted/i.test(msg));
46115
46720
  const outcome = {
46116
46721
  code: 1,
46117
46722
  signal: null,
@@ -46126,9 +46731,9 @@ async function driveAcpPrompt(opts) {
46126
46731
  cfg,
46127
46732
  outcome,
46128
46733
  parser: new StreamJsonParser(),
46129
- sawAuthFailure: looksLikeAuthFailure(rawErrText),
46734
+ sawAuthFailure: liveQf === null && looksLikeAuthFailure(rawErrText),
46130
46735
  consumable: false,
46131
- transportFailure: isTransportFailure({
46736
+ transportFailure: liveQf === null && isTransportFailure({
46132
46737
  rawErrText,
46133
46738
  authFailureText: "",
46134
46739
  stderrTail: proc.stderr,
@@ -46137,7 +46742,7 @@ async function driveAcpPrompt(opts) {
46137
46742
  }),
46138
46743
  keyringJitter: false,
46139
46744
  rawErrText,
46140
- isRateLimit: looksLikeRateLimit(rawErrText),
46745
+ isRateLimit: liveQf !== null || looksLikeRateLimit(rawErrText),
46141
46746
  silentTimeout: timedOut && !emittedAny
46142
46747
  }) ?? {
46143
46748
  kind: aborted ? "aborted" : "error",
@@ -46156,9 +46761,12 @@ async function driveAcpPrompt(opts) {
46156
46761
  rawErrText,
46157
46762
  runLogText,
46158
46763
  silentTimeout: timedOut && !emittedAny,
46764
+ quotaFailover: liveQf,
46765
+ cooledInLiveFamilies: quotaCtrl.cooledFamilies(),
46159
46766
  outcomeOverride: outcome
46160
46767
  });
46161
46768
  } finally {
46769
+ subTracker?.stop();
46162
46770
  recorder.stop();
46163
46771
  deps.unregisterActiveRun(sessionKey, recorder.rec);
46164
46772
  slot.releaseOnce();
@@ -46244,9 +46852,8 @@ async function runAcpAttempt(pool, deps, input, slot) {
46244
46852
  proc.cancelSession(sid);
46245
46853
  return settleEarlyAbort(deps, input, slot, sid, "request aborted after ACP session opened");
46246
46854
  }
46247
- const recorder = createAttemptRecorder(deps, cfg, account, sid, !input.isAux);
46855
+ const recorder = createAttemptRecorder(deps, cfg, account, sid, false);
46248
46856
  recorder.streamCid = sid;
46249
- recorder.startTracker?.();
46250
46857
  recorder.rec.requestAbort = () => proc.cancelSession(sid);
46251
46858
  if (!input.isAux && sessionKey !== "") deps.registerActiveRun(sessionKey, recorder.rec);
46252
46859
  slot.armHandoff()?.onFirstEvent();
@@ -46731,6 +47338,7 @@ function createHostServices(ctx, entryConfig = {}) {
46731
47338
  }
46732
47339
  }
46733
47340
  });
47341
+ const quotaHooks = createPoolQuotaHooks(pool);
46734
47342
  const translation = new TranslationService({
46735
47343
  cfg: getConfig,
46736
47344
  catalog: () => catalog.get(),
@@ -46738,6 +47346,7 @@ function createHostServices(ctx, entryConfig = {}) {
46738
47346
  autoEnabled: (id) => sessionAuto.get(id) ?? getConfig().autoTranslate,
46739
47347
  sessionCwd: (id) => sessionWorkspace(id),
46740
47348
  sessionLogPath: (id) => findSessionLogFile(dshHome(), id),
47349
+ poolQuotaHops: quotaHooks.poolQuotaHops,
46741
47350
  log,
46742
47351
  run: (req) => runTranslationStream(ctx, getConfig, log, req, translationWorkers),
46743
47352
  appendRecord: async (sessionId, record) => {
@@ -46815,6 +47424,7 @@ function createHostServices(ctx, entryConfig = {}) {
46815
47424
  bin,
46816
47425
  run: (call) => runViaAdapter(adapter, call),
46817
47426
  catalog: () => catalog.get(),
47427
+ ...quotaHooks,
46818
47428
  log
46819
47429
  }),
46820
47430
  translation,