dsh-agy-link 0.6.55 → 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
  }
@@ -32200,10 +32425,26 @@ function presentMirrorCall(args) {
32200
32425
  default: return presentDefaultCall(input, name, server);
32201
32426
  }
32202
32427
  }
32428
+ function formatBackgroundTerminalOutput(text) {
32429
+ const taskMatch = /\b(task-\d+)\b/i.exec(text);
32430
+ if (!(/^Tool is running as a background task(?:\s*\([^)]+\))?(?::\s*.*)?$/i.test(text) || /^Running in background\b/i.test(text)) || /tasks[\\/]+task-\d+\.log/i.test(text)) return text;
32431
+ const hint = taskMatch ? `[background] ${taskMatch[1]} running — live lines stream from .system_generated/tasks/${taskMatch[1]}.log; completion arrives via background message.` : "[background] running in background — awaiting completion notice.";
32432
+ return text === "" ? hint : `${text}\n${hint}`;
32433
+ }
32434
+ function formatScheduleResultOutput(input, text) {
32435
+ const cron = pick(input, "CronExpression", "cron_expression");
32436
+ const duration = pick(input, "DurationSeconds", "duration_seconds");
32437
+ const prompt = pick(input, "Prompt", "prompt");
32438
+ const timing = cron ? `cron ${cron}` : duration ? `${duration}s timer` : "schedule";
32439
+ const header = prompt ? `[scheduled] ${timing} — ${prompt}` : `[scheduled] ${timing}`;
32440
+ if (text === "" || /^Tool is running as a background task/i.test(text)) return header;
32441
+ return `${header}\n${text}`;
32442
+ }
32203
32443
  /** Native completed-card projection for one mirrored agy tool call. */
32204
32444
  function presentMirrorResult(args, result) {
32205
32445
  const a = args;
32206
- const name = unwrapMcpTool(typeof a?.tool === "string" ? a.tool : "", a?.input).tool;
32446
+ const unwrapped = unwrapMcpTool(typeof a?.tool === "string" ? a.tool : "", a?.input);
32447
+ const name = unwrapped.tool;
32207
32448
  const text = cleanResultText(resultText$1(result.content));
32208
32449
  switch (name) {
32209
32450
  case "run_command":
@@ -32218,10 +32459,17 @@ function presentMirrorResult(args, result) {
32218
32459
  else if (/\[command timed out/i.test(text) || result.isError) exitCode = 1;
32219
32460
  return {
32220
32461
  card: "terminal",
32221
- output: text,
32462
+ output: formatBackgroundTerminalOutput(text),
32222
32463
  ...exitCode !== void 0 ? { exitCode } : {}
32223
32464
  };
32224
32465
  }
32466
+ case "schedule": return {
32467
+ card: "generic",
32468
+ content: [{
32469
+ type: "text",
32470
+ text: clip$1(formatScheduleResultOutput(unwrapped.input, text), 4e3)
32471
+ }]
32472
+ };
32225
32473
  case "replace_file_content":
32226
32474
  case "write_to_file":
32227
32475
  case "write_file":
@@ -32536,6 +32784,29 @@ function buildToolCallBlock(input) {
32536
32784
  }
32537
32785
  //#endregion
32538
32786
  //#region src/provider/mapper/event-mapper.ts
32787
+ function formatRunningToolFallback(toolName, rawArgs) {
32788
+ const unwrapped = unwrapMcpTool(toolName, rawArgs);
32789
+ const a = unwrapped.input;
32790
+ const str = (...keys) => {
32791
+ for (const k of keys) {
32792
+ const v = a[k];
32793
+ if (typeof v === "string" && v.trim() !== "") return v.trim();
32794
+ if (typeof v === "number" && Number.isFinite(v)) return String(v);
32795
+ }
32796
+ return "";
32797
+ };
32798
+ if (unwrapped.tool === "schedule") {
32799
+ const cron = str("CronExpression", "cron_expression");
32800
+ const dur = str("DurationSeconds", "duration_seconds");
32801
+ const prompt = str("Prompt", "prompt");
32802
+ const timing = cron ? `cron ${cron}` : dur ? `${dur}s timer` : "schedule";
32803
+ return prompt ? `Schedule active (${timing}): ${prompt}` : `Schedule active (${timing})`;
32804
+ }
32805
+ const cmd = str("CommandLine", "command_line", "command", "cmd");
32806
+ const taskId = str("TaskId", "taskId", "task_id", "bgTaskId");
32807
+ if (cmd !== "") return `Tool is running as a background task${taskId ? ` (${taskId})` : ""}: ${cmd}`;
32808
+ return taskId ? `Tool is running as a background task (${taskId})` : "Tool is running as a background task";
32809
+ }
32539
32810
  var EventMapper = class {
32540
32811
  opts;
32541
32812
  blockIdx = 0;
@@ -32778,7 +33049,7 @@ var EventMapper = class {
32778
33049
  }
32779
33050
  return;
32780
33051
  }
32781
- if (ev.state === "RUNNING" && ev.tool.output === void 0) ev.tool.output = ev.text !== "" ? ev.text : "Tool is running as a background task";
33052
+ if (ev.state === "RUNNING" && (ev.tool.output === void 0 || ev.tool.output === "")) ev.tool.output = ev.text !== "" ? ev.text : formatRunningToolFallback(ev.tool.name, ev.tool.args);
32782
33053
  if (this.announcedTools.has(ev.stepKey)) return;
32783
33054
  this.announcedTools.add(ev.stepKey);
32784
33055
  if (!this.opts.cutOnTool) return;
@@ -32805,7 +33076,7 @@ var EventMapper = class {
32805
33076
  return;
32806
33077
  }
32807
33078
  if (!ev.ok) {
32808
- if (ev.response === "") return;
33079
+ if (ev.response === "" || isNonConsumableResultError(ev.ok, ev.error, ev.response)) return;
32809
33080
  const respText = this.formatAssistantText(ev.response);
32810
33081
  if (!this.sawTextStep) {
32811
33082
  yield* this.ensureBlock("text");
@@ -34278,15 +34549,32 @@ function providerRetryPolicyFor(pool) {
34278
34549
  Err.OVERLOADED
34279
34550
  ];
34280
34551
  if (enabledAccounts >= 2) retryableCodes.push(Err.AUTH);
34552
+ const poolHops = Math.min(Math.max(1, enabledAccounts - 1), 16);
34281
34553
  return {
34282
34554
  mode: "normal",
34283
- maxRetries: Math.max(enabledAccounts >= 3 ? 2 : 1, NETWORK_RETRY_DELAYS_MS.length),
34555
+ maxRetries: Math.max(poolHops, NETWORK_RETRY_DELAYS_MS.length),
34284
34556
  retryableCodes,
34285
34557
  initialDelayMs: 2e3,
34286
34558
  maxDelayMs: 45e3,
34287
34559
  jitterRatio: .1
34288
34560
  };
34289
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
+ }
34290
34578
  /**
34291
34579
  * Effort self-healing wrapper around streamAttempt (issue #67).
34292
34580
  *
@@ -34298,13 +34586,25 @@ function providerRetryPolicyFor(pool) {
34298
34586
  * becomes one extra spawn. The refusal text itself is the evidence that WE
34299
34587
  * passed the flag, so the replay does not depend on who requested the effort
34300
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.
34301
34592
  */
34302
34593
  async function* streamWithEffortRetry(deps, options) {
34303
- 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 (;;) {
34304
34602
  let emitted = false;
34603
+ const bufferAux = isAux && quotaHops < maxAuxHops;
34604
+ const buffered = [];
34305
34605
  const telemetry = [];
34306
34606
  let finish = null;
34307
- for await (const chunk of deps.streamAttempt(options, attempt > 0)) {
34607
+ for await (const chunk of deps.streamAttempt(options, suppressEffort)) {
34308
34608
  if (chunk.type === "finish") {
34309
34609
  finish = chunk;
34310
34610
  continue;
@@ -34313,27 +34613,51 @@ async function* streamWithEffortRetry(deps, options) {
34313
34613
  telemetry.push(chunk);
34314
34614
  continue;
34315
34615
  }
34616
+ if (bufferAux) {
34617
+ buffered.push(chunk);
34618
+ continue;
34619
+ }
34316
34620
  emitted = true;
34317
34621
  yield chunk;
34318
34622
  }
34319
34623
  if (finish === null) {
34624
+ for (const chunk of buffered) yield chunk;
34320
34625
  for (const chunk of telemetry) yield chunk;
34321
34626
  return;
34322
34627
  }
34323
- if (attempt === 0 && !emitted && finish.reason.kind === "error") {
34628
+ if (!emitted && finish.reason.kind === "error") {
34324
34629
  const failure = finish.reason.failure;
34325
34630
  const rawMsg = String(failure?.message ?? "");
34326
- const refused = parseEffortUnsupported(rawMsg);
34327
- if (refused !== null) {
34328
- if (deps.catalogAdvertisesEffort?.(refused) !== true) deps.learnEffortUnsupported(refused);
34329
- 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
+ }
34330
34654
  }
34331
- const unrecog = parseModelNotRecognized(rawMsg);
34332
- if (unrecog !== null && deps.onModelUnsupported) {
34333
- deps.onModelUnsupported(unrecog);
34655
+ if (canRetryAuxQuota(deps, options, emitted, finish, quotaHops, rawMsg)) {
34656
+ quotaHops++;
34334
34657
  continue;
34335
34658
  }
34336
34659
  }
34660
+ for (const chunk of buffered) yield chunk;
34337
34661
  for (const chunk of telemetry) yield chunk;
34338
34662
  yield finish;
34339
34663
  return;
@@ -34536,7 +34860,7 @@ async function finalizeAttempt(input) {
34536
34860
  emitRunTelemetry(input);
34537
34861
  }
34538
34862
  function applySuccess(input) {
34539
- 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);
34540
34864
  input.dropFailoverBudget(input.sessionKey);
34541
34865
  input.clearRateLimitFailover(input.sessionKey);
34542
34866
  input.clearNetworkStreak(input.sessionKey);
@@ -34565,7 +34889,14 @@ function applyFailure(input, failure) {
34565
34889
  */
34566
34890
  function rotateOnFailure(input, failure) {
34567
34891
  const { account, pool, family, outcome } = input;
34568
- 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
+ }
34569
34900
  if (account && input.silentTimeout) pool?.advanceAccount(account.id, family);
34570
34901
  if (account && failure.code === Err.ELIGIBILITY) {
34571
34902
  const unrecog = parseModelNotRecognized(failure.message ?? "");
@@ -34585,7 +34916,7 @@ function rotateOnFailure(input, failure) {
34585
34916
  * persisted as resumable-interrupted, then write it.
34586
34917
  */
34587
34918
  function persistFailureBinding(input, failure) {
34588
- 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);
34589
34920
  const interruptedTurn = failure.kind === "aborted" || input.outcome.timedOut === true;
34590
34921
  if (input.persistBinding && input.sessionAccountKey !== "" && staleConversation) input.store.delete(input.sessionAccountKey);
34591
34922
  else if (input.persistBinding && input.sessionAccountKey !== "" && !input.superseded) {
@@ -35448,6 +35779,205 @@ function readAgyRunLogText(homeDir, before) {
35448
35779
  return parts.join("\n");
35449
35780
  }
35450
35781
  //#endregion
35782
+ //#region src/features/subagent/task-activity.ts
35783
+ const MAX_READ_BYTES_PER_POLL = 131072;
35784
+ const MAX_LINES_PER_POLL = 20;
35785
+ const MAX_LINE_CHARS = 220;
35786
+ const MAX_MESSAGE_CHARS = 240;
35787
+ function noteWarn(log, context, err) {
35788
+ const detail = err instanceof Error ? err.message : String(err);
35789
+ log?.(`[task-activity] ${context}: ${detail}`);
35790
+ }
35791
+ function clipSingleLine(text, maxChars) {
35792
+ const single = text.replace(/\r/g, "").replace(/\s+/g, " ").trim();
35793
+ if (single.length <= maxChars) return single;
35794
+ return single.slice(0, Math.max(0, maxChars - 1)) + "…";
35795
+ }
35796
+ function formatTaskLogLine(taskId, line) {
35797
+ return `[后台任务 · ${taskId}] ${clipSingleLine(line, MAX_LINE_CHARS)}`;
35798
+ }
35799
+ function summarizeMessageJson(rawObj, fallbackName = "message") {
35800
+ if (!rawObj || typeof rawObj !== "object") return null;
35801
+ const obj = rawObj;
35802
+ const id = typeof obj.id === "string" && obj.id.trim() !== "" ? obj.id.trim() : "";
35803
+ const rawSender = typeof obj.sender === "string" ? obj.sender.trim() : "";
35804
+ const senderLabel = rawSender.includes("/") ? rawSender.slice(rawSender.lastIndexOf("/") + 1) : rawSender || "system";
35805
+ const details = obj.renderDetails && typeof obj.renderDetails === "object" ? obj.renderDetails : void 0;
35806
+ const title = typeof details?.messageTitle === "string" ? clipSingleLine(details.messageTitle, 120) : "";
35807
+ const content = typeof obj.content === "string" ? clipSingleLine(obj.content, MAX_MESSAGE_CHARS) : "";
35808
+ if (title === "" && content === "") return null;
35809
+ const body = title !== "" && content !== "" && !content.toLowerCase().includes(title.toLowerCase()) ? `${title} — ${content}` : content !== "" ? content : title;
35810
+ return {
35811
+ dedupKey: id !== "" ? id : fallbackName,
35812
+ text: `[后台通知 · ${senderLabel}] ${body}`
35813
+ };
35814
+ }
35815
+ function listFilesSafe(dir, suffix) {
35816
+ if (!existsSync(dir)) return [];
35817
+ try {
35818
+ return readdirSync(dir).filter((f) => f.endsWith(suffix)).sort();
35819
+ } catch {
35820
+ return [];
35821
+ }
35822
+ }
35823
+ var TaskActivityTracker = class {
35824
+ log;
35825
+ logs = /* @__PURE__ */ new Map();
35826
+ seenMessageFiles = /* @__PURE__ */ new Set();
35827
+ seenMessageIds = /* @__PURE__ */ new Set();
35828
+ baselined = false;
35829
+ constructor(log) {
35830
+ this.log = log;
35831
+ }
35832
+ reset() {
35833
+ this.logs.clear();
35834
+ this.seenMessageFiles.clear();
35835
+ this.seenMessageIds.clear();
35836
+ this.baselined = false;
35837
+ }
35838
+ /** Record pre-existing logs and messages at EOF so resumed runs only emit new activity. */
35839
+ baseline(brainDir) {
35840
+ this.baselined = true;
35841
+ this.scanTaskLogs(brainDir, true, () => {});
35842
+ this.scanMessages(brainDir, true, () => {});
35843
+ }
35844
+ poll(brainDir, emit) {
35845
+ try {
35846
+ this.scanTaskLogs(brainDir, false, emit);
35847
+ this.scanMessages(brainDir, false, emit);
35848
+ } catch (err) {
35849
+ noteWarn(this.log, "poll", err);
35850
+ }
35851
+ }
35852
+ scanTaskLogs(brainDir, baselineOnly, emit) {
35853
+ const tasksDir = join(brainDir, ".system_generated", "tasks");
35854
+ for (const file of listFilesSafe(tasksDir, ".log")) {
35855
+ const taskId = file.slice(0, -4);
35856
+ const fullPath = join(tasksDir, file);
35857
+ let tracked = this.logs.get(file);
35858
+ if (!tracked) {
35859
+ let initialOffset = 0;
35860
+ if (baselineOnly || this.baselined) {
35861
+ if (baselineOnly) try {
35862
+ const st = statSync(fullPath);
35863
+ if (st.isFile()) initialOffset = st.size;
35864
+ } catch {
35865
+ initialOffset = 0;
35866
+ }
35867
+ }
35868
+ tracked = {
35869
+ taskId,
35870
+ filePath: fullPath,
35871
+ offset: initialOffset,
35872
+ decoder: new StringDecoder("utf8"),
35873
+ rest: "",
35874
+ seq: 0
35875
+ };
35876
+ this.logs.set(file, tracked);
35877
+ }
35878
+ if (baselineOnly) continue;
35879
+ this.pollSingleTaskLog(tracked, emit);
35880
+ }
35881
+ }
35882
+ pollSingleTaskLog(tracked, emit) {
35883
+ let size;
35884
+ try {
35885
+ const st = statSync(tracked.filePath);
35886
+ if (!st.isFile()) return;
35887
+ size = st.size;
35888
+ } catch {
35889
+ return;
35890
+ }
35891
+ if (size < tracked.offset) {
35892
+ tracked.offset = 0;
35893
+ tracked.decoder = new StringDecoder("utf8");
35894
+ tracked.rest = "";
35895
+ }
35896
+ if (size === tracked.offset) return;
35897
+ const toRead = Math.min(size - tracked.offset, MAX_READ_BYTES_PER_POLL);
35898
+ const buffer = Buffer.allocUnsafe(toRead);
35899
+ let bytesRead = 0;
35900
+ try {
35901
+ const fd = openSync(tracked.filePath, "r");
35902
+ try {
35903
+ bytesRead = readSync(fd, buffer, 0, toRead, tracked.offset);
35904
+ } finally {
35905
+ closeSync(fd);
35906
+ }
35907
+ } catch {
35908
+ return;
35909
+ }
35910
+ if (bytesRead <= 0) return;
35911
+ tracked.offset += bytesRead;
35912
+ const parts = (tracked.rest + tracked.decoder.write(buffer.subarray(0, bytesRead))).split("\n");
35913
+ tracked.rest = size > tracked.offset ? "" : parts.pop() ?? "";
35914
+ if (size > tracked.offset) {
35915
+ tracked.offset = size;
35916
+ tracked.decoder = new StringDecoder("utf8");
35917
+ }
35918
+ const lines = parts.map((l) => l.trim()).filter((l) => l !== "");
35919
+ if (lines.length === 0) return;
35920
+ const skipped = Math.max(0, lines.length - MAX_LINES_PER_POLL);
35921
+ const visible = skipped > 0 ? lines.slice(-20) : lines;
35922
+ if (skipped > 0) {
35923
+ tracked.seq += 1;
35924
+ emit({
35925
+ stepKey: `task-log-${tracked.taskId}-${tracked.seq}`,
35926
+ text: `[后台任务 · ${tracked.taskId}] … 跳过 ${skipped} 行中间输出,最新日志如下\n`,
35927
+ raw: {
35928
+ kind: "task-log",
35929
+ taskId: tracked.taskId,
35930
+ skipped
35931
+ }
35932
+ });
35933
+ }
35934
+ for (const line of visible) {
35935
+ tracked.seq += 1;
35936
+ emit({
35937
+ stepKey: `task-log-${tracked.taskId}-${tracked.seq}`,
35938
+ text: `${formatTaskLogLine(tracked.taskId, line)}\n`,
35939
+ raw: {
35940
+ kind: "task-log",
35941
+ taskId: tracked.taskId,
35942
+ line
35943
+ }
35944
+ });
35945
+ }
35946
+ }
35947
+ scanMessages(brainDir, baselineOnly, emit) {
35948
+ const baseDir = join(brainDir, ".system_generated", "messages");
35949
+ const dirs = [{
35950
+ tag: "delivered",
35951
+ path: baseDir
35952
+ }, {
35953
+ tag: "undelivered",
35954
+ path: join(baseDir, "undelivered")
35955
+ }];
35956
+ for (const dir of dirs) for (const file of listFilesSafe(dir.path, ".json")) {
35957
+ const fileKey = `${dir.tag}:${file}`;
35958
+ if (this.seenMessageFiles.has(fileKey)) continue;
35959
+ this.seenMessageFiles.add(fileKey);
35960
+ const stem = file.slice(0, -5);
35961
+ let parsed;
35962
+ try {
35963
+ parsed = JSON.parse(readFileSync(join(dir.path, file), "utf8"));
35964
+ } catch {
35965
+ continue;
35966
+ }
35967
+ const summary = summarizeMessageJson(parsed, stem);
35968
+ if (!summary) continue;
35969
+ if (this.seenMessageIds.has(summary.dedupKey)) continue;
35970
+ this.seenMessageIds.add(summary.dedupKey);
35971
+ if (baselineOnly) continue;
35972
+ emit({
35973
+ stepKey: `task-msg-${summary.dedupKey}`,
35974
+ text: `${summary.text}\n`,
35975
+ raw: parsed
35976
+ });
35977
+ }
35978
+ }
35979
+ };
35980
+ //#endregion
35451
35981
  //#region src/features/subagent/tracker.ts
35452
35982
  /**
35453
35983
  * Swallow the failures a live transcript produces by design — a row still being
@@ -35460,6 +35990,62 @@ function noteFailure(log, what, err) {
35460
35990
  if (code === "ENOENT" || code === "EACCES" || code === "EPERM" || code === "EBUSY") return;
35461
35991
  log?.(`subagent tracker: ${what} — ${String(err)}`);
35462
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
+ }
35463
36049
  function isActiveSubagentState(state) {
35464
36050
  return state === void 0 || state === "" || state === "SUBAGENT_STATE_ALIVE";
35465
36051
  }
@@ -35530,15 +36116,19 @@ var SubagentTracker = class {
35530
36116
  brainDir = null;
35531
36117
  trackedSubagents = /* @__PURE__ */ new Map();
35532
36118
  seenStepKeys = /* @__PURE__ */ new Set();
36119
+ taskActivity;
35533
36120
  timer = null;
35534
36121
  active = false;
35535
36122
  polling = false;
35536
36123
  pollIntervalMs;
36124
+ parentCursor = createTranscriptCursor();
36125
+ parentLines = 0;
35537
36126
  constructor(opts) {
35538
36127
  this.opts = opts;
35539
36128
  this.conversationId = opts.conversationId ?? "";
35540
36129
  this.accountHome = opts.accountHome;
35541
36130
  this.pollIntervalMs = opts.pollIntervalMs ?? 500;
36131
+ this.taskActivity = new TaskActivityTracker(opts.log);
35542
36132
  }
35543
36133
  /** Follow the conversation agy reported in its stream-json init/result envelope. */
35544
36134
  setConversationId(cid) {
@@ -35546,6 +36136,9 @@ var SubagentTracker = class {
35546
36136
  this.conversationId = cid;
35547
36137
  this.brainDir = null;
35548
36138
  this.baselined = false;
36139
+ this.parentCursor = createTranscriptCursor();
36140
+ this.parentLines = 0;
36141
+ this.taskActivity.reset();
35549
36142
  if (this.active) {
35550
36143
  if (this.opts.resumed === true) {
35551
36144
  this.baselined = true;
@@ -35570,6 +36163,9 @@ var SubagentTracker = class {
35570
36163
  try {
35571
36164
  if (!this.brainDir) this.brainDir = findBrainDir(this.conversationId, this.accountHome);
35572
36165
  if (!this.brainDir) return;
36166
+ const parentLog = join(this.brainDir, ".system_generated", "logs", "transcript.jsonl");
36167
+ this.parentCursor = createTranscriptCursor(fileSizeOrZero(parentLog));
36168
+ this.taskActivity.baseline(this.brainDir);
35573
36169
  this.scanSubagentsForConv(this.conversationId, true);
35574
36170
  for (const cid of Array.from(this.trackedSubagents.keys())) this.scanSubagentsForConv(cid, true);
35575
36171
  } catch (err) {
@@ -35577,20 +36173,32 @@ var SubagentTracker = class {
35577
36173
  }
35578
36174
  }
35579
36175
  stop() {
35580
- this.active = false;
35581
- if (this.timer) {
35582
- clearInterval(this.timer);
35583
- this.timer = null;
36176
+ try {
36177
+ if (this.active && !this.polling && this.conversationId !== "") this.poll();
36178
+ } finally {
36179
+ this.active = false;
36180
+ if (this.timer) {
36181
+ clearInterval(this.timer);
36182
+ this.timer = null;
36183
+ }
35584
36184
  }
35585
36185
  }
35586
- /** Run one scan across known conversations and subagents. */
35587
- poll() {
35588
- 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;
35589
36193
  if (!this.conversationId) return;
35590
36194
  this.polling = true;
35591
36195
  try {
35592
36196
  if (!this.brainDir) this.brainDir = findBrainDir(this.conversationId, this.accountHome);
35593
36197
  if (!this.brainDir) return;
36198
+ this.pollParentTranscript();
36199
+ this.taskActivity.poll(this.brainDir, (ev) => {
36200
+ this.emitSubagentEvent(ev.stepKey, ev.text, ev.raw);
36201
+ });
35594
36202
  const convsToScan = [this.conversationId, ...Array.from(this.trackedSubagents.keys())];
35595
36203
  for (const cid of convsToScan) this.scanSubagentsForConv(cid);
35596
36204
  for (const sub of this.trackedSubagents.values()) if (!sub.terminal) this.pollSubagentTranscript(sub);
@@ -35600,6 +36208,30 @@ var SubagentTracker = class {
35600
36208
  this.polling = false;
35601
36209
  }
35602
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
+ }
35603
36235
  emitSubagentEvent(stepKey, text, raw) {
35604
36236
  if (this.seenStepKeys.has(stepKey)) return;
35605
36237
  this.seenStepKeys.add(stepKey);
@@ -35649,14 +36281,8 @@ var SubagentTracker = class {
35649
36281
  const typeName = typeof desc?.typeName === "string" && desc.typeName !== "" ? desc.typeName : "Subagent";
35650
36282
  const subBrainDir = findBrainDir(subId, this.accountHome) ?? join(bDir, "..", subId);
35651
36283
  const active = isActiveSubagentState(rawState);
35652
- let initialOffset = 0;
35653
- if (baselineOnly || !active) try {
35654
- const logPath = join(subBrainDir, ".system_generated", "logs", "transcript.jsonl");
35655
- const st = statSync(logPath);
35656
- if (st.isFile()) initialOffset = st.size;
35657
- } catch {
35658
- initialOffset = 0;
35659
- }
36284
+ const logPath = join(subBrainDir, ".system_generated", "logs", "transcript.jsonl");
36285
+ const initialOffset = baselineOnly ? fileSizeOrZero(logPath) : 0;
35660
36286
  const tracked = {
35661
36287
  conversationId: subId,
35662
36288
  role,
@@ -35664,9 +36290,7 @@ var SubagentTracker = class {
35664
36290
  brainDir: subBrainDir,
35665
36291
  state: rawState,
35666
36292
  terminal: !active,
35667
- offset: initialOffset,
35668
- decoder: new StringDecoder("utf8"),
35669
- rest: "",
36293
+ cursor: createTranscriptCursor(initialOffset),
35670
36294
  lines: 0
35671
36295
  };
35672
36296
  this.trackedSubagents.set(subId, tracked);
@@ -35675,6 +36299,7 @@ var SubagentTracker = class {
35675
36299
  else if (active) this.emitSubagentEvent(spawnKey, `[子代理 · ${role}] 已启动协同专员 (${typeName})\n`, obj);
35676
36300
  else {
35677
36301
  this.seenStepKeys.add(spawnKey);
36302
+ this.pollSubagentTranscript(tracked, true);
35678
36303
  if (rawState !== void 0) this.emitSubagentEvent(`subagent-state-${subId}-${rawState}`, `[子代理 · ${role}] 协同专员未保持运行 (${rawState})\n`, obj);
35679
36304
  }
35680
36305
  } catch (err) {
@@ -35682,70 +36307,161 @@ var SubagentTracker = class {
35682
36307
  }
35683
36308
  }
35684
36309
  }
35685
- /**
35686
- * Read the transcript lines appended since the last poll.
35687
- *
35688
- * agy rewrites nothing and only appends, so the tracker keeps a byte offset
35689
- * instead of re-reading (and re-splitting) a transcript that grows to hundreds
35690
- * of kilobytes: each poll costs one bounded read of the new bytes.
35691
- */
35692
- readNewLines(sub) {
36310
+ pollSubagentTranscript(sub, quotaOnly = false) {
35693
36311
  const logPath = join(sub.brainDir, ".system_generated", "logs", "transcript.jsonl");
35694
- let size;
35695
- try {
35696
- const st = statSync(logPath);
35697
- if (!st.isFile()) return [];
35698
- size = st.size;
35699
- } catch {
35700
- return [];
35701
- }
35702
- if (size < sub.offset) {
35703
- sub.offset = 0;
35704
- sub.decoder = new StringDecoder("utf8");
35705
- sub.rest = "";
35706
- }
35707
- if (size === sub.offset) return [];
35708
- const length = size - sub.offset;
35709
- const buffer = Buffer.allocUnsafe(length);
35710
- let bytesRead = 0;
35711
- try {
35712
- const fd = openSync(logPath, "r");
35713
- try {
35714
- bytesRead = readSync(fd, buffer, 0, length, sub.offset);
35715
- } finally {
35716
- closeSync(fd);
35717
- }
35718
- } catch {
35719
- return [];
35720
- }
35721
- if (bytesRead <= 0) return [];
35722
- sub.offset += bytesRead;
35723
- const parts = (sub.rest + sub.decoder.write(buffer.subarray(0, bytesRead))).split("\n");
35724
- sub.rest = parts.pop() ?? "";
35725
- return parts.filter((line) => line.trim() !== "");
35726
- }
35727
- pollSubagentTranscript(sub) {
35728
- for (const line of this.readNewLines(sub)) try {
36312
+ for (const line of readTranscriptDelta(logPath, sub.cursor)) try {
35729
36313
  const o = JSON.parse(line);
35730
36314
  sub.lines += 1;
35731
36315
  const stepIdx = typeof o.step_index === "number" ? o.step_index : sub.lines;
35732
36316
  const baseKey = `subagent-${sub.conversationId}-${stepIdx}`;
35733
- if (Array.isArray(o.tool_calls) && o.tool_calls.length > 0) for (let tcIdx = 0; tcIdx < o.tool_calls.length; tcIdx++) {
35734
- const tc = o.tool_calls[tcIdx];
35735
- const toolName = typeof tc?.name === "string" ? tc.name : "";
35736
- if (toolName === "") continue;
35737
- const msg = formatSubagentAction(sub.role, toolName, tc.args);
35738
- this.emitSubagentEvent(`${baseKey}-tc-${tcIdx}`, `${msg}\n`, o);
35739
- }
35740
- else if (o.type === "PLANNER_RESPONSE" && typeof o.content === "string" && o.content.trim() !== "") {
35741
- const firstLine = o.content.trim().split("\n")[0].replace(/^#+\s*/, "").slice(0, 100);
35742
- if (firstLine !== "") this.emitSubagentEvent(`${baseKey}-content`, `[子代理 · ${sub.role}] 阶段进展: ${firstLine}\n`, o);
35743
- }
35744
- 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
+ }
35745
36349
  } catch {}
35746
36350
  }
35747
36351
  };
35748
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
35749
36465
  //#region src/provider/attempt.ts
35750
36466
  function brief$1(s) {
35751
36467
  const flat = s.trim().replace(/\s+/g, " ");
@@ -35836,7 +36552,7 @@ function buildSpawnArgs(input, printTimeoutMinutes, log) {
35836
36552
  };
35837
36553
  }
35838
36554
  /** Create the recording, parser, HOME snapshot and tool watchdog for one run. */
35839
- function createAttemptRecorder(deps, cfg, account, initialConversationId, trackSubagents = true) {
36555
+ function createAttemptRecorder(deps, cfg, account, initialConversationId, trackSubagents = true, quotaCtx) {
35840
36556
  const rec = deps.runs.create();
35841
36557
  rec.accountHome = account && account.dir ? account.dir : void 0;
35842
36558
  const conversationsDir = conversationsDirFor(rec.accountHome);
@@ -35844,17 +36560,33 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId, trackS
35844
36560
  const parser = new StreamJsonParser();
35845
36561
  deps.onParser?.(parser);
35846
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;
35847
36582
  const tracker = trackSubagents ? new SubagentTracker({
35848
36583
  conversationId: initialConversationId,
35849
36584
  resumed: Boolean(initialConversationId),
35850
36585
  accountHome: rec.accountHome,
35851
36586
  log: deps.log,
35852
- onEvent: (ev) => {
35853
- rec.append(ev);
35854
- },
35855
- noteActivity: () => {
35856
- watchdog.markEvent();
35857
- }
36587
+ onEvent: (ev) => rec.append(ev),
36588
+ ...quotaCtrl ? { onQuotaExhausted: (info) => quotaCtrl.handleQuotaExhausted(info) } : {},
36589
+ noteActivity: () => watchdog.markEvent()
35858
36590
  }) : void 0;
35859
36591
  const state = {
35860
36592
  rec,
@@ -35864,10 +36596,15 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId, trackS
35864
36596
  streamCid: initialConversationId ?? null,
35865
36597
  printTimeoutMinutes: watchdog.printTimeoutMinutes,
35866
36598
  attachProcess: (proc) => {
36599
+ attachedProc = proc;
35867
36600
  watchdog.attach(proc);
35868
36601
  tracker?.start();
36602
+ if (pendingQuotaKill) proc.kill("quota");
35869
36603
  proc.outcome.finally(() => tracker?.stop());
35870
36604
  },
36605
+ startTracker: () => {
36606
+ tracker?.start();
36607
+ },
35871
36608
  feedLine: (line, onEvent, onFirstEvent) => {
35872
36609
  watchdog.markEvent();
35873
36610
  onFirstEvent?.();
@@ -35882,6 +36619,7 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId, trackS
35882
36619
  }
35883
36620
  watchdog.trackStep(ev);
35884
36621
  rec.append(ev);
36622
+ reportDirectToolQuota(quotaCtrl, ev);
35885
36623
  if (typeof onEvent === "function") try {
35886
36624
  onEvent(ev);
35887
36625
  } catch {}
@@ -35899,10 +36637,15 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId, trackS
35899
36637
  } catch {}
35900
36638
  }
35901
36639
  },
36640
+ flushTracker: () => {
36641
+ tracker?.flush();
36642
+ },
35902
36643
  stop: () => {
35903
36644
  watchdog.stop();
35904
36645
  tracker?.stop();
35905
36646
  },
36647
+ quotaFailover: () => quotaCtrl?.failoverState() ?? null,
36648
+ cooledInLiveFamilies: () => quotaCtrl?.cooledFamilies() ?? /* @__PURE__ */ new Set(),
35906
36649
  conversationId: () => state.streamCid ?? diffConversations(before, conversationsDir).conversationId
35907
36650
  };
35908
36651
  return state;
@@ -36472,19 +37215,24 @@ async function* dispatchCredentialSlot(deps, input) {
36472
37215
  }
36473
37216
  /** Evidence + failure for one settled run (pure classification inputs). */
36474
37217
  function classifyRun(input) {
36475
- const { cfg, outcome, parser, rec, runLogHome, runLogsBefore } = input;
37218
+ const { cfg, outcome, parser, rec, runLogHome, runLogsBefore, quotaFailover } = input;
36476
37219
  const r = rec.getResultEvent();
36477
37220
  const u = rec.lastUsage ?? rec.finalUsage({});
36478
37221
  const zeroUsageTos = r !== null && (u?.input_tokens ?? 0) === 0 && (u?.output_tokens ?? 0) === 0 && looksLikeTosViolation(r.response);
36479
37222
  const errorResponseTos = r !== null && !r.ok && looksLikeTosViolation(r.response);
36480
- 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(" ") : "";
36481
37228
  const rawErrText = [
36482
37229
  outcome.stderrTail,
36483
37230
  parser.stats.lastResultError,
36484
- !consumable && r && (!r.ok || zeroUsageTos) ? r.response : ""
37231
+ !consumable && r && (!r.ok || zeroUsageTos) ? r.error ?? r.response : "",
37232
+ liveQuota ? quotaFailover.rawErrorText : "",
37233
+ logQuotaHint
36485
37234
  ].filter(Boolean).join(" ");
36486
- const isRateLimit = looksLikeRateLimit(rawErrText);
36487
- const runLogText = readAgyRunLogText(runLogHome, runLogsBefore);
37235
+ const isRateLimit = liveQuota || looksLikeRateLimit(rawErrText);
36488
37236
  const keyringJitter = looksLikeAuthVerificationJitter(runLogText);
36489
37237
  const transportFailure = isTransportFailure({
36490
37238
  rawErrText,
@@ -36493,20 +37241,27 @@ function classifyRun(input) {
36493
37241
  stdoutHead: outcome.stdout,
36494
37242
  runLogText
36495
37243
  });
36496
- 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;
36497
37263
  return {
36498
- failure: classifyFailure({
36499
- cfg,
36500
- outcome,
36501
- parser,
36502
- sawAuthFailure: sawAuthFailure(parser, outcome),
36503
- consumable,
36504
- transportFailure,
36505
- keyringJitter,
36506
- rawErrText,
36507
- isRateLimit,
36508
- silentTimeout
36509
- }),
37264
+ failure,
36510
37265
  rawErrText,
36511
37266
  runLogText,
36512
37267
  silentTimeout
@@ -36529,12 +37284,15 @@ async function handleAttemptOutcome(deps, input, ctx) {
36529
37284
  const { cfg, sessionKey } = input;
36530
37285
  const outcome = await ctx.proc.outcome;
36531
37286
  slot.releaseOnce();
37287
+ recorder.flushTracker();
36532
37288
  recorder.stop();
36533
37289
  deps.unregisterActiveRun(sessionKey, rec);
36534
37290
  deps.clearInFlightPrompt(sessionKey, spawn.prompt);
36535
37291
  recorder.drain(input.agyOnEvent);
37292
+ const quotaFailover = recorder.quotaFailover();
37293
+ const cooledInLiveFamilies = recorder.cooledInLiveFamilies();
36536
37294
  const conversationId = recorder.conversationId();
36537
- if (!rec.hasConsumableResult && outcome.idleGraceTerminated) {
37295
+ if (!rec.hasConsumableResult && outcome.idleGraceTerminated && quotaFailover === null) {
36538
37296
  const recovered = conversationId === null ? "" : recoverFinalReply(conversationId, rec.accountHome);
36539
37297
  const synthResult = {
36540
37298
  kind: "result",
@@ -36553,41 +37311,47 @@ async function handleAttemptOutcome(deps, input, ctx) {
36553
37311
  parser,
36554
37312
  rec,
36555
37313
  runLogHome,
36556
- runLogsBefore
37314
+ runLogsBefore,
37315
+ quotaFailover
36557
37316
  });
36558
37317
  if (failure !== null) {
36559
37318
  if (failure.code === Err.NETWORK) failure.retryAfterMs = networkRetryDelayMs(deps.noteNetworkFailure(sessionKey));
36560
37319
  else deps.clearNetworkStreak(sessionKey);
36561
37320
  }
36562
- rec.settle(failure);
36563
37321
  const superseded = deps.isSuperseded(sessionKey, rec);
36564
- await finalizeAttempt({
36565
- rec,
36566
- outcome,
36567
- failure,
36568
- store: deps.store,
36569
- ...deps.pool === void 0 ? {} : { pool: deps.pool },
36570
- ...input.account === void 0 ? {} : { account: input.account },
36571
- family: input.family,
36572
- persistBinding: input.persistBinding,
36573
- sessionAccountKey: input.sessionAccountKey,
36574
- ...input.binding === void 0 ? {} : { binding: input.binding },
36575
- conversationId,
36576
- messages: input.messages,
36577
- model: input.model,
36578
- activeModel: input.activeModel,
36579
- superseded,
36580
- newlySentImageIds: input.newlySentImageIds,
36581
- rawErrText,
36582
- runLogText,
36583
- silentTimeout,
36584
- sessionKey,
36585
- clearNetworkStreak: (key) => deps.clearNetworkStreak(key),
36586
- dropFailoverBudget: (key) => deps.dropFailoverBudget(key),
36587
- clearRateLimitFailover: (key) => deps.clearRateLimitFailover(key),
36588
- sharesSingleEgress: () => deps.sharesSingleEgress(),
36589
- ...deps.onRun === void 0 ? {} : { onRun: deps.onRun }
36590
- });
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
+ }
36591
37355
  }
36592
37356
  /**
36593
37357
  * Run one attempt: recorder → slot dispatch → spawn → concurrent outcome.
@@ -36595,7 +37359,10 @@ async function handleAttemptOutcome(deps, input, ctx) {
36595
37359
  * queue notices; the outcome closure runs detached exactly as before.
36596
37360
  */
36597
37361
  async function* runAgyAttempt(deps, input) {
36598
- 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
+ });
36599
37366
  const spawn = buildSpawnArgs(input, recorder.printTimeoutMinutes, deps.log);
36600
37367
  const slot = yield* dispatchCredentialSlot(deps, {
36601
37368
  ...input,
@@ -36762,21 +37529,14 @@ var AgyAdapter = class extends LlmAdapter {
36762
37529
  buildArgs(opts) {
36763
37530
  return buildAgyArgs(opts);
36764
37531
  }
36765
- /** 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). */
36766
37533
  async *stream(options) {
36767
37534
  yield* streamWithEffortRetry({
36768
37535
  streamAttempt: (opts, suppressEffort) => this.streamAttempt(opts, suppressEffort),
36769
37536
  learnEffortUnsupported: (model) => this.learnEffortUnsupported(model),
36770
37537
  catalogAdvertisesEffort: (model) => this.deps.catalog.advertisedEfforts(model).length > 0,
36771
- onModelUnsupported: (unrecog) => {
36772
- const fam = modelFamilyOf(unrecog);
36773
- const pool = this.deps.pool;
36774
- if (pool) {
36775
- const currentId = pool.getActiveAccountId(fam);
36776
- if (currentId) pool.markModelUnsupported(currentId, unrecog);
36777
- pool.selectAccount(fam, unrecog);
36778
- }
36779
- }
37538
+ pool: this.deps.pool,
37539
+ defaultModel: () => this.deps.getConfig().defaultModel
36780
37540
  }, options);
36781
37541
  }
36782
37542
  async *streamAttempt(options, suppressEffort = false) {
@@ -36932,22 +37692,25 @@ var AgyAdapter = class extends LlmAdapter {
36932
37692
  }
36933
37693
  if (samePrompt && prevPrompt !== void 0 && prevPrompt.inFlight && liveRun === void 0 && now - prevPrompt.startedAt < 2e3) throw new LlmError("Duplicate request ignored: an identical request is already running for this session.", Err.BUSY);
36934
37694
  if (runLive && !samePrompt) {
36935
- const liveCid = (liveRun.accountHome ?? "") === (account?.dir ?? "") ? liveRun.conversationId : null;
36936
- if (liveCid !== null && binding === void 0 && !isAux && sessionAccountKey !== "") binding = {
36937
- conversationId: liveCid,
36938
- lastMessageCount: Math.max(0, lastAssistantIdx + 1),
36939
- updatedAt: Date.now(),
36940
- model: currentModel,
36941
- interrupted: true
36942
- };
36943
- else if (binding !== void 0) binding.interrupted = true;
36944
37695
  if (liveRun.hasResult) {
36945
37696
  if (!await waitForRunSettle(liveRun, 1500)) this.deps.log?.("previous agy run did not exit within 1.5s after producing its result — preempting it");
36946
37697
  }
37698
+ const wasConsumable = liveRun.hasConsumableResult;
36947
37699
  if (!liveRun.isSettled) {
37700
+ const liveCid = (liveRun.accountHome ?? "") === (account?.dir ?? "") ? liveRun.conversationId : null;
37701
+ if (!wasConsumable) {
37702
+ if (liveCid !== null && binding === void 0 && !isAux && sessionAccountKey !== "") binding = {
37703
+ conversationId: liveCid,
37704
+ lastMessageCount: Math.max(0, lastAssistantIdx + 1),
37705
+ updatedAt: Date.now(),
37706
+ model: currentModel,
37707
+ interrupted: true
37708
+ };
37709
+ else if (binding !== void 0) binding.interrupted = true;
37710
+ }
36948
37711
  liveRun.requestAbort?.();
36949
37712
  if (!await waitForRunSettle(liveRun, 3500)) this.warnOnce("settle-timeout:" + sessionKey, "the preempted agy run did not exit within 3.5s — starting the replacement anyway; its late write-back is ignored because the newer run owns the session");
36950
- if (!prompt.includes("the previous turn was interrupted")) prompt = "[the previous turn was interrupted before it finished — do not continue or answer that unfinished work; respond only to the newest request below]\n\n" + prompt;
37713
+ if (!wasConsumable && !prompt.includes("the previous turn was interrupted")) prompt = "[the previous turn was interrupted before it finished — do not continue or answer that unfinished work; respond only to the newest request below]\n\n" + prompt;
36951
37714
  }
36952
37715
  }
36953
37716
  this.activeSessionPrompts.set(sessionKey, {
@@ -37512,6 +38275,21 @@ function simplifyRatio(width, height) {
37512
38275
  }
37513
38276
  //#endregion
37514
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
+ }
37515
38293
  function emptyImageResult(req, model, effort) {
37516
38294
  return {
37517
38295
  ok: false,
@@ -37669,6 +38447,8 @@ var ImageService = class {
37669
38447
  let last = ctx.last;
37670
38448
  let effort = target.effort;
37671
38449
  let effortFallbackUsed = false;
38450
+ let quotaHopsUsed = 0;
38451
+ const maxQuotaHops = Math.min(Math.max(0, Math.round(this.deps.poolQuotaHops?.() ?? 0)), 16);
37672
38452
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
37673
38453
  const startedAt = this.now();
37674
38454
  last.effort = effort;
@@ -37681,9 +38461,34 @@ var ImageService = class {
37681
38461
  imagePaths: refs,
37682
38462
  ...signal === void 0 ? {} : { signal }
37683
38463
  });
37684
- last.attempts = attempt;
38464
+ last.attempts = attempt + quotaHopsUsed;
37685
38465
  last.durationMs = this.now() - startedAt;
37686
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
+ }
37687
38492
  if (!res.ok) {
37688
38493
  const failure = res.error ?? "";
37689
38494
  if (!effortFallbackUsed && effort !== "" && /--effort/i.test(failure) && /not supported/i.test(failure)) {
@@ -37713,7 +38518,6 @@ var ImageService = class {
37713
38518
  if (attempt < maxAttempts) continue;
37714
38519
  return last;
37715
38520
  }
37716
- const reply = parseImageReply(res.text);
37717
38521
  if (reply.error !== void 0) {
37718
38522
  last = {
37719
38523
  ...last,
@@ -37902,6 +38706,14 @@ async function runViaAdapter(adapter, call) {
37902
38706
  agyImagePrompt: call.prompt,
37903
38707
  agyPermissionMode: call.permissionMode,
37904
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
+ }
37905
38717
  if (typeof info.id === "string") accountId = info.id;
37906
38718
  if (typeof info.home === "string" && info.home !== "") home = info.home;
37907
38719
  },
@@ -41228,14 +42040,18 @@ var TranslationService = class {
41228
42040
  }
41229
42041
  }
41230
42042
  async withRetry(req, retries, signal) {
41231
- 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;
41232
42048
  let last = {
41233
42049
  ok: false,
41234
42050
  text: "",
41235
42051
  error: "translation was never attempted",
41236
42052
  code: Err.AGY_ERROR
41237
42053
  };
41238
- for (let attempt = 0; attempt <= max; attempt++) {
42054
+ for (;;) {
41239
42055
  if (signal?.aborted === true) {
41240
42056
  last = {
41241
42057
  ok: false,
@@ -41256,9 +42072,17 @@ var TranslationService = class {
41256
42072
  };
41257
42073
  }
41258
42074
  if (last.ok) return last;
41259
- 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
+ }
41260
42083
  const pause = last.code === Err.EMPTY_RESPONSE ? 900 * (attempt + 1) : 150 * (attempt + 1);
41261
- if (attempt < max) await delay(pause, signal);
42084
+ attempt++;
42085
+ await delay(pause, signal);
41262
42086
  }
41263
42087
  return last;
41264
42088
  }
@@ -41892,7 +42716,7 @@ var TranslationWorkerPool = class {
41892
42716
  ...accountPatch,
41893
42717
  durationMs
41894
42718
  };
41895
- if (looksLikeHardRateLimit(errText)) {
42719
+ if (looksLikeHardRateLimit(errText) && !isTransientBurstRateLimit(errText)) {
41896
42720
  if (account && pool) {
41897
42721
  const resetMs = parseResetDurationMs(errText);
41898
42722
  const resetIso = resetMs ? new Date(this.now() + resetMs).toISOString() : void 0;
@@ -45223,15 +46047,17 @@ function acpUsageToRawUsage(u) {
45223
46047
  }
45224
46048
  function acpPromptResultToAgyEvent(sessionId, result, accumulatedText) {
45225
46049
  const stopReason = typeof result.stopReason === "string" ? result.stopReason : "end_turn";
45226
- 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;
45227
46054
  const usage = acpUsageToRawUsage(result.usage);
45228
- const errMsg = !ok && typeof result.error === "string" ? result.error : void 0;
45229
46055
  return {
45230
46056
  kind: "result",
45231
46057
  conversationId: sessionId,
45232
46058
  ok,
45233
46059
  response: accumulatedText,
45234
- ...errMsg ? { error: errMsg } : {},
46060
+ ...!ok && extractedErr ? { error: extractedErr } : {},
45235
46061
  usage,
45236
46062
  raw: result
45237
46063
  };
@@ -45763,7 +46589,7 @@ var AcpSessionPool = class {
45763
46589
  //#endregion
45764
46590
  //#region src/features/acp/run-attempt.ts
45765
46591
  async function settleAcpOutcome(opts) {
45766
- 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;
45767
46593
  await finalizeAttempt({
45768
46594
  rec,
45769
46595
  outcome: outcomeOverride ?? {
@@ -45794,6 +46620,8 @@ async function settleAcpOutcome(opts) {
45794
46620
  runLogText,
45795
46621
  silentTimeout,
45796
46622
  sessionKey: input.sessionKey,
46623
+ ...quotaFailover === void 0 ? {} : { quotaFailover },
46624
+ ...cooledInLiveFamilies === void 0 ? {} : { cooledInLiveFamilies },
45797
46625
  clearNetworkStreak: (k) => deps.clearNetworkStreak(k),
45798
46626
  dropFailoverBudget: (k) => deps.dropFailoverBudget(k),
45799
46627
  clearRateLimitFailover: (k) => deps.clearRateLimitFailover(k),
@@ -45808,11 +46636,38 @@ async function driveAcpPrompt(opts) {
45808
46636
  const streamState = createAcpStreamState();
45809
46637
  let emittedAny = false;
45810
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;
45811
46665
  try {
46666
+ subTracker?.start();
45812
46667
  const idleMs = cfg.timeoutMs;
45813
46668
  const longToolIdleMs = cfg.longToolIdleMinutes > 0 ? cfg.longToolIdleMinutes * 6e4 : 0;
45814
46669
  const maxTurnMs = cfg.maxTurnMinutes > 0 ? cfg.maxTurnMinutes * 6e4 : 0;
45815
- const resEv = acpPromptResultToAgyEvent(sid, await proc.prompt({
46670
+ const result = await proc.prompt({
45816
46671
  sessionId: sid,
45817
46672
  text: input.prompt,
45818
46673
  timeoutMs: idleMs,
@@ -45825,12 +46680,17 @@ async function driveAcpPrompt(opts) {
45825
46680
  emittedAny = true;
45826
46681
  recorder.rec.append(ev);
45827
46682
  input.agyOnEvent?.(ev);
46683
+ reportDirectToolQuota(quotaCtrl, ev);
45828
46684
  }
45829
46685
  }
45830
- }), 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);
45831
46691
  recorder.rec.append(resEv);
45832
46692
  input.agyOnEvent?.(resEv);
45833
- 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");
45834
46694
  await settleAcpOutcome({
45835
46695
  deps,
45836
46696
  input,
@@ -45842,14 +46702,21 @@ async function driveAcpPrompt(opts) {
45842
46702
  stderr: proc.stderr,
45843
46703
  rawErrText: "",
45844
46704
  runLogText: "",
45845
- silentTimeout: false
46705
+ silentTimeout: false,
46706
+ cooledInLiveFamilies: quotaCtrl.cooledFamilies()
45846
46707
  });
45847
46708
  } catch (err) {
46709
+ subTracker?.flush();
46710
+ const liveQf = quotaCtrl.failoverState();
45848
46711
  const msg = err instanceof Error ? err.message : String(err);
45849
- const rawErrText = `${msg} ${proc.stderr}`.trim();
46712
+ const rawErrText = [
46713
+ msg,
46714
+ proc.stderr,
46715
+ liveQf?.rawErrorText
46716
+ ].filter(Boolean).join(" ").trim();
45850
46717
  const runLogText = readAgyRunLogText(runLogHome, runLogsBefore);
45851
- const timedOut = /timed out/i.test(msg);
45852
- 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));
45853
46720
  const outcome = {
45854
46721
  code: 1,
45855
46722
  signal: null,
@@ -45864,9 +46731,9 @@ async function driveAcpPrompt(opts) {
45864
46731
  cfg,
45865
46732
  outcome,
45866
46733
  parser: new StreamJsonParser(),
45867
- sawAuthFailure: looksLikeAuthFailure(rawErrText),
46734
+ sawAuthFailure: liveQf === null && looksLikeAuthFailure(rawErrText),
45868
46735
  consumable: false,
45869
- transportFailure: isTransportFailure({
46736
+ transportFailure: liveQf === null && isTransportFailure({
45870
46737
  rawErrText,
45871
46738
  authFailureText: "",
45872
46739
  stderrTail: proc.stderr,
@@ -45875,7 +46742,7 @@ async function driveAcpPrompt(opts) {
45875
46742
  }),
45876
46743
  keyringJitter: false,
45877
46744
  rawErrText,
45878
- isRateLimit: looksLikeRateLimit(rawErrText),
46745
+ isRateLimit: liveQf !== null || looksLikeRateLimit(rawErrText),
45879
46746
  silentTimeout: timedOut && !emittedAny
45880
46747
  }) ?? {
45881
46748
  kind: aborted ? "aborted" : "error",
@@ -45894,9 +46761,12 @@ async function driveAcpPrompt(opts) {
45894
46761
  rawErrText,
45895
46762
  runLogText,
45896
46763
  silentTimeout: timedOut && !emittedAny,
46764
+ quotaFailover: liveQf,
46765
+ cooledInLiveFamilies: quotaCtrl.cooledFamilies(),
45897
46766
  outcomeOverride: outcome
45898
46767
  });
45899
46768
  } finally {
46769
+ subTracker?.stop();
45900
46770
  recorder.stop();
45901
46771
  deps.unregisterActiveRun(sessionKey, recorder.rec);
45902
46772
  slot.releaseOnce();
@@ -46468,6 +47338,7 @@ function createHostServices(ctx, entryConfig = {}) {
46468
47338
  }
46469
47339
  }
46470
47340
  });
47341
+ const quotaHooks = createPoolQuotaHooks(pool);
46471
47342
  const translation = new TranslationService({
46472
47343
  cfg: getConfig,
46473
47344
  catalog: () => catalog.get(),
@@ -46475,6 +47346,7 @@ function createHostServices(ctx, entryConfig = {}) {
46475
47346
  autoEnabled: (id) => sessionAuto.get(id) ?? getConfig().autoTranslate,
46476
47347
  sessionCwd: (id) => sessionWorkspace(id),
46477
47348
  sessionLogPath: (id) => findSessionLogFile(dshHome(), id),
47349
+ poolQuotaHops: quotaHooks.poolQuotaHops,
46478
47350
  log,
46479
47351
  run: (req) => runTranslationStream(ctx, getConfig, log, req, translationWorkers),
46480
47352
  appendRecord: async (sessionId, record) => {
@@ -46552,6 +47424,7 @@ function createHostServices(ctx, entryConfig = {}) {
46552
47424
  bin,
46553
47425
  run: (call) => runViaAdapter(adapter, call),
46554
47426
  catalog: () => catalog.get(),
47427
+ ...quotaHooks,
46555
47428
  log
46556
47429
  }),
46557
47430
  translation,