dsh-agy-link 0.6.45 → 0.6.47

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
@@ -100,6 +100,7 @@ function defaultConfig() {
100
100
  timeoutMs: 6e5,
101
101
  longToolIdleMinutes: 240,
102
102
  maxTurnMinutes: 0,
103
+ idleGraceMinutes: 10,
103
104
  /**
104
105
  * Hard cap (minutes) on waiting for the Windows credential slot before the
105
106
  * dispatch releases, backs off and retries (dispatchRetries). Each attempt
@@ -161,7 +162,7 @@ function defaultConfig() {
161
162
  warmupModels: [PREFERRED_GEMINI_FLASH, PREFERRED_CLAUDE],
162
163
  autoTranslate: false,
163
164
  translateModel: PREFERRED_GEMINI_FLASH,
164
- translateEffort: "medium",
165
+ translateEffort: "low",
165
166
  translateTargetLanguage: "中文(简体)",
166
167
  translateMaxChars: 8e3,
167
168
  translateMaxTokens: 4096,
@@ -568,28 +569,27 @@ function modelFamilyOf(modelId) {
568
569
  /**
569
570
  * True when the unattended quota probe must skip this account's summary call.
570
571
  *
571
- * Only a licence refusal suppresses: it is the one verdict the network cannot
572
- * fix on its own, and re-probing it every hour is pure risk-control exposure.
573
- * `auth` stays on the existing authRequired lifecycle, and network faults must
574
- * be retried normally.
572
+ * Only terminal account-level refusals suppress: retrying them every hour is
573
+ * pure risk-control exposure. `auth` stays on the existing authRequired
574
+ * lifecycle, and network faults must be retried normally.
575
575
  */
576
576
  function quotaSummarySuppressed(account, now = Date.now()) {
577
577
  const state = account.quotaUnavailable;
578
578
  if (state === void 0) return false;
579
- if (state.reason !== "no_license" && state.reason !== "no_summary_access") return false;
579
+ if (state.reason !== "no_license" && state.reason !== "no_summary_access" && state.reason !== "validation_required" && state.reason !== "tos_violation") return false;
580
580
  return state.retryAfter > now;
581
581
  }
582
582
  /**
583
583
  * Whether the account should leave the background poll ENTIRELY.
584
584
  *
585
- * Only a licence-less account qualifies: it can produce no quota data at all.
586
- * A free-tier account whose SUMMARY is refused still refreshes its model list
587
- * and user quota, so skipping it would freeze the picker (issue #137).
585
+ * Unlicensed, verification-blocked, and suspended accounts cannot produce
586
+ * usable quota until the user intervenes. A free-tier account whose SUMMARY is
587
+ * refused still refreshes its model list and user quota (issue #137).
588
588
  */
589
589
  function accountPollSuppressed(account, now = Date.now()) {
590
590
  const state = account.quotaUnavailable;
591
591
  if (state === void 0) return false;
592
- if (state.reason !== "no_license") return false;
592
+ if (state.reason !== "no_license" && state.reason !== "validation_required" && state.reason !== "tos_violation") return false;
593
593
  return state.retryAfter > now;
594
594
  }
595
595
  /**
@@ -610,7 +610,7 @@ function accountHasArgon(acc, pool, catalog) {
610
610
  if (catalog && catalog.source === "discovered") return catalog.models?.some((m) => isArgonModel(m.id)) ?? false;
611
611
  return false;
612
612
  }
613
- const EFFORT_SUFFIX_RE = /-(?:low|medium|high|tiered|thinking)$/i;
613
+ const EFFORT_SUFFIX_RE = /-(?:tiered-)?(?:low|medium|high|xhigh|tiered|thinking)$/i;
614
614
  /**
615
615
  * Return the un-tiered base model slug (e.g. claude-opus-4-6-thinking -> claude-opus-4-6,
616
616
  * claude-opus-5-5-high -> claude-opus-5-5).
@@ -632,6 +632,14 @@ function modelMatches(requestedModel, candidateModelId) {
632
632
  if (r === c) return true;
633
633
  return baseModelSlug(r) === baseModelSlug(c);
634
634
  }
635
+ function quotaSupportsModel(acc, clean, pool, catalog) {
636
+ const familyQuotaModels = acc.quotas?.[modelFamilyOf(clean)]?.models;
637
+ if (Array.isArray(familyQuotaModels) && familyQuotaModels.some((m) => modelMatches(clean, m.modelId))) return true;
638
+ const lower = clean.toLowerCase();
639
+ if (lower === "gemini-pro-orchestrator-neon") return Array.isArray(familyQuotaModels) && familyQuotaModels.some((m) => modelMatches("gemini-4-neon", m.modelId));
640
+ if (lower === "gemini-pro-orchestrator-g1-pro") return accountHasArgon(acc, pool, catalog);
641
+ return false;
642
+ }
635
643
  /**
636
644
  * Determine whether a managed account supports a specific model.
637
645
  * If the account's quota or discovered catalog enumerates models for that family,
@@ -644,14 +652,13 @@ function accountSupportsModel(acc, model, pool, catalog) {
644
652
  if (isArgonModel(clean)) return accountHasArgon(acc, pool, catalog);
645
653
  if (catalog && catalog.source === "discovered" && Array.isArray(catalog.models) && catalog.models.length > 0) {
646
654
  if (catalog.models.some((m) => modelMatches(clean, m.id))) return true;
647
- const familyQuotaModels = acc.quotas?.[modelFamilyOf(clean)]?.models;
648
- if (Array.isArray(familyQuotaModels) && familyQuotaModels.some((m) => modelMatches(clean, m.modelId))) return true;
655
+ if (quotaSupportsModel(acc, clean, pool, catalog)) return true;
649
656
  return false;
650
657
  }
651
658
  const family = modelFamilyOf(clean);
652
659
  const familyQuota = acc.quotas?.[family];
653
660
  if (familyQuota) {
654
- if (Array.isArray(familyQuota.models) && familyQuota.models.length > 0) return familyQuota.models.some((m) => modelMatches(clean, m.modelId));
661
+ if (Array.isArray(familyQuota.models) && familyQuota.models.length > 0) return quotaSupportsModel(acc, clean, pool, catalog);
655
662
  return true;
656
663
  }
657
664
  if (acc.quotas && Object.keys(acc.quotas).length > 0 && acc.quotas.google !== void 0) return false;
@@ -1293,7 +1300,7 @@ var ModelCatalog = class ModelCatalog {
1293
1300
  const ac = new AbortController();
1294
1301
  const timer = setTimeout(() => ac.abort(), 3e4);
1295
1302
  try {
1296
- const { stdout, stderr } = await this.discover(ac.signal, accountId);
1303
+ const { stdout, stderr, accountId: probedAccountId } = await this.discover(ac.signal, accountId);
1297
1304
  if (isUnauthenticatedModelsFallback(stdout, stderr)) {
1298
1305
  const msg = "agy models returned unauthenticated fallback output";
1299
1306
  if (accountId) {
@@ -1322,7 +1329,10 @@ var ModelCatalog = class ModelCatalog {
1322
1329
  if (accountId) {
1323
1330
  this.accountCatalogs.set(accountId, newCatalog);
1324
1331
  if (this.current.source !== "discovered") this.current = newCatalog;
1325
- } else this.current = newCatalog;
1332
+ } else {
1333
+ this.current = newCatalog;
1334
+ if (probedAccountId) this.accountCatalogs.set(probedAccountId, newCatalog);
1335
+ }
1326
1336
  this.persistToDisk();
1327
1337
  if (changed && announce) this.onUpdate?.();
1328
1338
  return;
@@ -3218,6 +3228,27 @@ function describeAgyAutoUpdate(env = process.env, now = Date.now()) {
3218
3228
  return "stale — last check " + minutes + "m ago; the next spawn pre-empts it";
3219
3229
  }
3220
3230
  //#endregion
3231
+ //#region src/runtime/agy/idle-line.ts
3232
+ /**
3233
+ * Parse agy's background-wait line.
3234
+ *
3235
+ * While a turn is finishing, agy prints
3236
+ * `root agent idle; waiting for N background task(s)` — and N is its OWN count
3237
+ * of work it launched and is still waiting on (a build, an integration test, a
3238
+ * Docker job). That count is authoritative: as long as N > 0 the wait is
3239
+ * legitimate, so no grace period can make terminating the tree correct
3240
+ * (issue #144 — the reaper used a hard-coded 5 s and killed those turns).
3241
+ *
3242
+ * Returns `null` when the text carries no count (older agy builds, or a chunk
3243
+ * boundary cut the line), which keeps the conservative "arm the grace" path.
3244
+ */
3245
+ function backgroundTasksFrom(text) {
3246
+ const match = /root agent idle;\s*waiting\s+for\s+(\d+)\s+background/i.exec(text);
3247
+ if (match === null) return null;
3248
+ const count = Number(match[1]);
3249
+ return Number.isSafeInteger(count) && count >= 0 ? count : null;
3250
+ }
3251
+ //#endregion
3221
3252
  //#region src/runtime/agy/process.ts
3222
3253
  const IS_WIN$1 = process.platform === "win32";
3223
3254
  /**
@@ -3319,7 +3350,8 @@ function createRunState(opts) {
3319
3350
  idleGraceTimer: null,
3320
3351
  idleGraceTerminated: false,
3321
3352
  idleGraceExempt: false,
3322
- idleObserved: false
3353
+ idleObserved: false,
3354
+ idleBackgroundTasks: null
3323
3355
  };
3324
3356
  }
3325
3357
  function spawnAgyChild(opts, env, viaCmd, isNode) {
@@ -3424,7 +3456,9 @@ function clearIdleGrace(state) {
3424
3456
  */
3425
3457
  function armIdleGrace(child, opts, state) {
3426
3458
  if (state.idleGraceTimer !== null || state.settled) return;
3459
+ if ((state.idleBackgroundTasks ?? 0) > 0) return;
3427
3460
  const graceMs = opts.idleGraceMs ?? 5e3;
3461
+ if (graceMs <= 0) return;
3428
3462
  state.idleGraceTimer = setTimeout(() => {
3429
3463
  state.idleGraceTimer = null;
3430
3464
  if (state.settled) return;
@@ -3462,6 +3496,8 @@ function attachOutputStreams(child, opts, state, refreshWatchdog) {
3462
3496
  state.stderr = (state.stderr + text).slice(-4096);
3463
3497
  if (/root agent idle;\s*waiting/i.test(text)) {
3464
3498
  state.idleObserved = true;
3499
+ const waiting = backgroundTasksFrom(text);
3500
+ if (waiting !== null) state.idleBackgroundTasks = waiting;
3465
3501
  armIdleGrace(child, opts, state);
3466
3502
  } else if (opts.stderrKeepalive && !isBackgroundStderrNoise(text)) refreshWatchdog();
3467
3503
  }
@@ -30909,6 +30945,20 @@ var RunRecording = class {
30909
30945
  }
30910
30946
  return null;
30911
30947
  }
30948
+ /**
30949
+ * True when at least one consumable `result` event (`ok` or non-empty
30950
+ * `response`) exists at index >= `from`. A settled recording with
30951
+ * `failureInfo === null` and no consumable result at `>= from` would always
30952
+ * fail with `agy stream ended without a result event` if re-driven.
30953
+ */
30954
+ hasConsumableResultFrom(from) {
30955
+ const start = Math.max(0, from);
30956
+ for (let i = start; i < this.events.length; i++) {
30957
+ const ev = this.events[i];
30958
+ if (ev !== void 0 && ev.kind === "result" && (ev.ok || ev.response !== "")) return true;
30959
+ }
30960
+ return false;
30961
+ }
30912
30962
  /** Event at an absolute index (bounds-checked). */
30913
30963
  eventAt(index) {
30914
30964
  return this.events[index];
@@ -32272,7 +32322,7 @@ async function resolveEventToolArgs(rec, ev, i, resolved) {
32272
32322
  }
32273
32323
  }
32274
32324
  }
32275
- async function* driveSpan(deps, rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal, compactionNotice) {
32325
+ async function* driveSpan(deps, rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal, compactionNotice, skipDbEnrichment = false) {
32276
32326
  if (signal?.aborted) {
32277
32327
  rec.requestAbort?.();
32278
32328
  yield {
@@ -32290,14 +32340,14 @@ async function* driveSpan(deps, rec, from, cutOnTool, useCodeWrapper, goalContex
32290
32340
  deps.runs.remember(rec);
32291
32341
  deps.runs.pin(rec.runId);
32292
32342
  try {
32293
- yield* driveSpanBody(deps, rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal, compactionNotice);
32343
+ yield* driveSpanBody(deps, rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal, compactionNotice, skipDbEnrichment);
32294
32344
  } finally {
32295
32345
  deps.runs.unpin(rec.runId);
32296
32346
  deps.runs.remember(rec);
32297
32347
  }
32298
32348
  }
32299
32349
  /** Body of {@link driveSpan}: map recorded events until the span finishes. */
32300
- async function* driveSpanBody(deps, rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal, compactionNotice) {
32350
+ async function* driveSpanBody(deps, rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal, compactionNotice, skipDbEnrichment = false) {
32301
32351
  const queue = new ChunkQueue();
32302
32352
  let abortedLocally = false;
32303
32353
  const onAbort = () => {
@@ -32338,9 +32388,11 @@ async function* driveSpanBody(deps, rec, from, cutOnTool, useCodeWrapper, goalCo
32338
32388
  try {
32339
32389
  for await (const ev of rec.eventsFrom(from)) {
32340
32390
  if (abortedLocally || signal?.aborted) break;
32341
- await resolveEventThought(rec, ev, i, resolvedThoughts, pendingThoughtSteps);
32342
- if (pendingThoughtSteps.size > 0) await resolvePendingThoughts(rec, ev, resolvedThoughts, pendingThoughtSteps);
32343
- await resolveEventToolArgs(rec, ev, i, resolved);
32391
+ if (!skipDbEnrichment) {
32392
+ await resolveEventThought(rec, ev, i, resolvedThoughts, pendingThoughtSteps);
32393
+ if (pendingThoughtSteps.size > 0) await resolvePendingThoughts(rec, ev, resolvedThoughts, pendingThoughtSteps);
32394
+ await resolveEventToolArgs(rec, ev, i, resolved);
32395
+ }
32344
32396
  for (const ch of mapper.map(ev, i)) queue.push(ch);
32345
32397
  i++;
32346
32398
  if (mapper.isFinished) {
@@ -32859,6 +32911,7 @@ function resolveConfig(entry, env = process.env, overrides = readOverrides()) {
32859
32911
  timeoutMs: asNum(get("timeoutMs")) ?? base.timeoutMs,
32860
32912
  longToolIdleMinutes: asNum(get("longToolIdleMinutes")) ?? base.longToolIdleMinutes,
32861
32913
  maxTurnMinutes: asNum(get("maxTurnMinutes")) ?? base.maxTurnMinutes,
32914
+ idleGraceMinutes: asNum(get("idleGraceMinutes")) ?? base.idleGraceMinutes,
32862
32915
  dispatchTimeoutMinutes: asNum(get("dispatchTimeoutMinutes")) ?? base.dispatchTimeoutMinutes,
32863
32916
  dispatchRetries: asNum(get("dispatchRetries")) ?? base.dispatchRetries,
32864
32917
  parallelSameAccount: asBool(get("parallelSameAccount")) ?? base.parallelSameAccount,
@@ -32938,6 +32991,10 @@ function resolveConfig(entry, env = process.env, overrides = readOverrides()) {
32938
32991
  const mt = asNum(env.DSH_AGY_MAX_TURN_MINUTES);
32939
32992
  if (mt !== void 0 && mt >= 0) cfg.maxTurnMinutes = mt;
32940
32993
  }
32994
+ if (env.DSH_AGY_IDLE_GRACE_MINUTES) {
32995
+ const g = asNum(env.DSH_AGY_IDLE_GRACE_MINUTES);
32996
+ if (g !== void 0 && g >= 0) cfg.idleGraceMinutes = g;
32997
+ }
32941
32998
  if (env.DSH_AGY_CONTEXT_WINDOW) {
32942
32999
  const w = asNum(env.DSH_AGY_CONTEXT_WINDOW);
32943
33000
  if (w !== void 0 && w > 0) cfg.contextWindowDefault = Math.floor(w);
@@ -34264,13 +34321,21 @@ function createToolWatchdog(log, cfg) {
34264
34321
  let lastOutputAt = 0;
34265
34322
  const TOOL_HEARTBEAT_MS = 3e5;
34266
34323
  let toolHeartbeat = null;
34324
+ let idleGraceExempt = false;
34325
+ const syncIdleGraceExempt = () => {
34326
+ const next = awaitingSubagent || openToolKeys.size > 0;
34327
+ if (next === idleGraceExempt) return;
34328
+ idleGraceExempt = next;
34329
+ runningProc?.exemptIdleGrace(next);
34330
+ };
34267
34331
  const apply = () => {
34268
34332
  runningProc?.noteActivity(openToolKeys.size > 0 ? longToolIdleMs : generationIdleMs);
34333
+ syncIdleGraceExempt();
34269
34334
  };
34270
34335
  const setAwaitingSubagent = (next) => {
34271
34336
  if (awaitingSubagent === next) return;
34272
34337
  awaitingSubagent = next;
34273
- runningProc?.exemptIdleGrace(next);
34338
+ syncIdleGraceExempt();
34274
34339
  };
34275
34340
  const stop = () => {
34276
34341
  if (toolHeartbeat !== null) {
@@ -34297,7 +34362,7 @@ function createToolWatchdog(log, cfg) {
34297
34362
  printTimeoutMinutes,
34298
34363
  attach: (proc) => {
34299
34364
  runningProc = proc;
34300
- proc?.exemptIdleGrace(awaitingSubagent);
34365
+ proc?.exemptIdleGrace(idleGraceExempt);
34301
34366
  apply();
34302
34367
  },
34303
34368
  markEvent: () => {
@@ -34334,9 +34399,10 @@ function createToolWatchdog(log, cfg) {
34334
34399
  },
34335
34400
  stop: () => {
34336
34401
  stop();
34337
- setAwaitingSubagent(false);
34402
+ awaitingSubagent = false;
34338
34403
  openToolKeys.clear();
34339
34404
  openToolSince.clear();
34405
+ syncIdleGraceExempt();
34340
34406
  }
34341
34407
  };
34342
34408
  }
@@ -34853,7 +34919,7 @@ function buildSpawnArgs(input, printTimeoutMinutes, log) {
34853
34919
  };
34854
34920
  }
34855
34921
  /** Create the recording, parser, HOME snapshot and tool watchdog for one run. */
34856
- function createAttemptRecorder(deps, cfg, account, initialConversationId) {
34922
+ function createAttemptRecorder(deps, cfg, account, initialConversationId, trackSubagents = true) {
34857
34923
  const rec = deps.runs.create();
34858
34924
  rec.accountHome = account && account.dir ? account.dir : void 0;
34859
34925
  const conversationsDir = conversationsDirFor(rec.accountHome);
@@ -34861,7 +34927,7 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId) {
34861
34927
  const parser = new StreamJsonParser();
34862
34928
  deps.onParser?.(parser);
34863
34929
  const watchdog = createToolWatchdog(deps.log, cfg);
34864
- const tracker = new SubagentTracker({
34930
+ const tracker = trackSubagents ? new SubagentTracker({
34865
34931
  conversationId: initialConversationId,
34866
34932
  resumed: Boolean(initialConversationId),
34867
34933
  accountHome: rec.accountHome,
@@ -34872,7 +34938,7 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId) {
34872
34938
  noteActivity: () => {
34873
34939
  watchdog.markEvent();
34874
34940
  }
34875
- });
34941
+ }) : void 0;
34876
34942
  const state = {
34877
34943
  rec,
34878
34944
  parser,
@@ -34882,8 +34948,8 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId) {
34882
34948
  printTimeoutMinutes: watchdog.printTimeoutMinutes,
34883
34949
  attachProcess: (proc) => {
34884
34950
  watchdog.attach(proc);
34885
- tracker.start();
34886
- proc.outcome.finally(() => tracker.stop());
34951
+ tracker?.start();
34952
+ proc.outcome.finally(() => tracker?.stop());
34887
34953
  },
34888
34954
  feedLine: (line, onEvent, onFirstEvent) => {
34889
34955
  watchdog.markEvent();
@@ -34891,11 +34957,11 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId) {
34891
34957
  for (const ev of parser.feed(line + "\n")) {
34892
34958
  if (ev.kind === "init" && ev.conversationId) {
34893
34959
  state.streamCid = ev.conversationId;
34894
- tracker.setConversationId(ev.conversationId);
34960
+ tracker?.setConversationId(ev.conversationId);
34895
34961
  }
34896
34962
  if (ev.kind === "result" && ev.conversationId !== "") {
34897
34963
  state.streamCid = ev.conversationId;
34898
- tracker.setConversationId(ev.conversationId);
34964
+ tracker?.setConversationId(ev.conversationId);
34899
34965
  }
34900
34966
  watchdog.trackStep(ev);
34901
34967
  rec.append(ev);
@@ -34908,7 +34974,7 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId) {
34908
34974
  for (const ev of parser.flush()) {
34909
34975
  if (ev.kind === "result" && ev.conversationId !== "") {
34910
34976
  state.streamCid = ev.conversationId;
34911
- tracker.setConversationId(ev.conversationId);
34977
+ tracker?.setConversationId(ev.conversationId);
34912
34978
  }
34913
34979
  rec.append(ev);
34914
34980
  if (typeof onEvent === "function") try {
@@ -34918,7 +34984,7 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId) {
34918
34984
  },
34919
34985
  stop: () => {
34920
34986
  watchdog.stop();
34921
- tracker.stop();
34987
+ tracker?.stop();
34922
34988
  },
34923
34989
  conversationId: () => state.streamCid ?? diffConversations(before, conversationsDir).conversationId
34924
34990
  };
@@ -34982,6 +35048,19 @@ async function waitForRunSettle(run, timeoutMs) {
34982
35048
  }
34983
35049
  return run.isSettled;
34984
35050
  }
35051
+ function persistBindingOnResult(deps, input, recorder, ev) {
35052
+ if (ev.kind !== "result" || !ev.ok || looksLikeTosViolation(ev.response) || !input.persistBinding || input.sessionAccountKey === "" || deps.isSuperseded(input.sessionKey, recorder.rec)) return;
35053
+ const finalId = input.binding !== void 0 ? input.binding.conversationId : ev.conversationId || recorder.streamCid;
35054
+ if (!finalId) return;
35055
+ const mergedImages = input.binding?.sentImageIds || input.newlySentImageIds.length > 0 ? [.../* @__PURE__ */ new Set([...input.binding?.sentImageIds ?? [], ...input.newlySentImageIds])] : void 0;
35056
+ deps.store.set(input.sessionAccountKey, {
35057
+ conversationId: finalId,
35058
+ lastMessageCount: input.messages.length,
35059
+ updatedAt: Date.now(),
35060
+ model: input.activeModel,
35061
+ ...mergedImages && mergedImages.length > 0 ? { sentImageIds: mergedImages } : {}
35062
+ });
35063
+ }
34985
35064
  /**
34986
35065
  * Spawn the child under the held slot. Installs the line callback (parser feed
34987
35066
  * + tool watchdog + first-event hand-off), registers the run for steer
@@ -35019,14 +35098,16 @@ async function startAttemptProcess(deps, input, spawn, recorder, slot) {
35019
35098
  cwd: workspaceRoot,
35020
35099
  timeoutMs: cfg.timeoutMs,
35021
35100
  maxTurnMs: cfg.maxTurnMinutes > 0 ? cfg.maxTurnMinutes * 6e4 : void 0,
35101
+ idleGraceMs: cfg.idleGraceMinutes > 0 ? Math.round(cfg.idleGraceMinutes * 6e4) : 0,
35022
35102
  signal,
35023
35103
  env,
35024
35104
  stdinPayload: spawn.stdinPayload,
35025
35105
  preemptAutoUpdate: cfg.suppressAgyAutoUpdate,
35026
35106
  stderrKeepalive: true,
35027
- onLine: (line) => {
35028
- recorder.feedLine(line, input.agyOnEvent, () => slotHandoff?.onFirstEvent());
35029
- }
35107
+ onLine: (line) => recorder.feedLine(line, (ev) => {
35108
+ persistBindingOnResult(deps, input, recorder, ev);
35109
+ input.agyOnEvent?.(ev);
35110
+ }, () => slotHandoff?.onFirstEvent())
35030
35111
  });
35031
35112
  spawned = true;
35032
35113
  recorder.attachProcess(proc);
@@ -35536,7 +35617,8 @@ async function handleAttemptOutcome(deps, input, ctx) {
35536
35617
  deps.clearInFlightPrompt(sessionKey, spawn.prompt);
35537
35618
  recorder.drain(input.agyOnEvent);
35538
35619
  const conversationId = recorder.conversationId();
35539
- if (!rec.hasResult && outcome.idleGraceTerminated) {
35620
+ const existingRes = rec.getResultEvent();
35621
+ if (!(existingRes !== null && (existingRes.ok || existingRes.response !== "")) && outcome.idleGraceTerminated) {
35540
35622
  const recovered = conversationId === null ? "" : recoverFinalReply(conversationId, rec.accountHome);
35541
35623
  const synthResult = {
35542
35624
  kind: "result",
@@ -35597,7 +35679,7 @@ async function handleAttemptOutcome(deps, input, ctx) {
35597
35679
  * queue notices; the outcome closure runs detached exactly as before.
35598
35680
  */
35599
35681
  async function* runAgyAttempt(deps, input) {
35600
- const recorder = createAttemptRecorder(deps, input.cfg, input.account, input.binding?.conversationId);
35682
+ const recorder = createAttemptRecorder(deps, input.cfg, input.account, input.binding?.conversationId, !input.isAux);
35601
35683
  const spawn = buildSpawnArgs(input, recorder.printTimeoutMinutes, deps.log);
35602
35684
  const slot = yield* dispatchCredentialSlot(deps, {
35603
35685
  ...input,
@@ -35842,13 +35924,14 @@ var AgyAdapter = class extends LlmAdapter {
35842
35924
  if (continuation !== null) {
35843
35925
  const rec = this.deps.runs.get(continuation.runId);
35844
35926
  const deadFailure = rec !== void 0 && rec.isSettled ? rec.failureInfo : null;
35845
- if (rec !== void 0 && !(deadFailure !== null && this.claimFailover(sessionKey, deadFailure.code))) {
35927
+ const deadMissingResult = rec !== void 0 && rec.isSettled && deadFailure === null && !rec.hasConsumableResultFrom(continuation.eventIndex + 1);
35928
+ if (rec !== void 0 && !deadMissingResult && !(deadFailure !== null && this.claimFailover(sessionKey, deadFailure.code))) {
35846
35929
  yield* driveSpan(this.deps, rec, continuation.eventIndex + 1, hasToolSupport, isCodeMode, goalContext, supportsGoalUpdate, supportsPlanExit, options.signal);
35847
35930
  return;
35848
35931
  }
35849
35932
  if (rec !== void 0) {
35850
35933
  this.deps.runs.forget(continuation.runId);
35851
- this.warnOnce("dead-continuation:" + continuation.runId, "agy run " + continuation.runId + " settled in " + (deadFailure?.code ?? "") + " — retrying this step instead of replaying it" + (deadFailure?.code === Err.NETWORK && this.sharesSingleEgress() ? " on the same account (shared egress)" : " on another account"));
35934
+ this.warnOnce("dead-continuation:" + continuation.runId, deadMissingResult ? "agy run " + continuation.runId + " settled without a consumable result — retrying this step instead of replaying an empty stream" : "agy run " + continuation.runId + " settled in " + (deadFailure?.code ?? "") + " — retrying this step instead of replaying it" + (deadFailure?.code === Err.NETWORK && this.sharesSingleEgress() ? " on the same account (shared egress)" : " on another account"));
35852
35935
  } else this.warnOnce("stale-continuation:" + continuation.runId, "agy run " + continuation.runId + " is no longer available in memory (server restarted?) — falling back to fresh turn prompt assembly");
35853
35936
  }
35854
35937
  const catalog = this.deps.catalog.get();
@@ -36033,7 +36116,7 @@ var AgyAdapter = class extends LlmAdapter {
36033
36116
  signal: options.signal,
36034
36117
  agyOnEvent: options.agyOnEvent
36035
36118
  });
36036
- yield* driveSpan(this.deps, rec, 0, policy.mirrorTools && hasToolSupport, isCodeMode, goalContext, supportsGoalUpdate, supportsPlanExit, options.signal, compactionNotice);
36119
+ yield* driveSpan(this.deps, rec, 0, policy.mirrorTools && hasToolSupport, isCodeMode, goalContext, supportsGoalUpdate, supportsPlanExit, options.signal, compactionNotice, isAux && !isImage);
36037
36120
  }
36038
36121
  };
36039
36122
  //#endregion
@@ -38731,6 +38814,495 @@ var TranslationService = class {
38731
38814
  }
38732
38815
  }
38733
38816
  };
38817
+ const STDERR_TAIL_CAP = 2048;
38818
+ const PRINT_TIMEOUT_ARG = "30m";
38819
+ function appendTail(prev, chunk) {
38820
+ const next = prev + chunk;
38821
+ return next.length > STDERR_TAIL_CAP ? next.slice(-2048) : next;
38822
+ }
38823
+ function killWorkerProcess(worker, platform) {
38824
+ if (worker.idleTimer !== null) {
38825
+ clearTimeout(worker.idleTimer);
38826
+ worker.idleTimer = null;
38827
+ }
38828
+ worker.closed = true;
38829
+ const child = worker.child;
38830
+ try {
38831
+ child.stdin?.end();
38832
+ } catch {}
38833
+ if (platform !== "win32" && typeof child.pid === "number" && child.pid > 0) try {
38834
+ process.kill(-child.pid, "SIGKILL");
38835
+ return;
38836
+ } catch {}
38837
+ try {
38838
+ child.kill("SIGKILL");
38839
+ } catch {}
38840
+ }
38841
+ function resetParserTurnStats(worker) {
38842
+ worker.stderrTail = "";
38843
+ worker.parser.stats.lastResultError = void 0;
38844
+ worker.parser.stats.sawAuthFailure = false;
38845
+ worker.parser.stats.authFailureText = void 0;
38846
+ }
38847
+ function attachWorkerStreams(worker, onClose) {
38848
+ const dispatchEvents = (events) => {
38849
+ const waiter = worker.activeTurn;
38850
+ if (!waiter) return;
38851
+ for (const ev of events) if (ev.kind === "step" && ev.stepKind === "text") {
38852
+ if (ev.fragment) waiter.deltaText += ev.text;
38853
+ else if (ev.text !== "") waiter.fullStepText = ev.text;
38854
+ } else if (ev.kind === "result") {
38855
+ worker.activeTurn = null;
38856
+ const text = (ev.response || waiter.deltaText || waiter.fullStepText).trim();
38857
+ waiter.resolve({
38858
+ kind: "result",
38859
+ ok: ev.ok,
38860
+ response: text,
38861
+ ...ev.error === void 0 ? {} : { error: ev.error }
38862
+ });
38863
+ return;
38864
+ }
38865
+ };
38866
+ worker.child.stdin?.on("error", () => void 0);
38867
+ worker.child.stdout?.on("data", (buf) => {
38868
+ const chunk = typeof buf === "string" ? buf : buf.toString("utf8");
38869
+ dispatchEvents(worker.parser.feed(chunk));
38870
+ });
38871
+ worker.child.stderr?.on("data", (buf) => {
38872
+ const chunk = typeof buf === "string" ? buf : buf.toString("utf8");
38873
+ worker.stderrTail = appendTail(worker.stderrTail, chunk);
38874
+ });
38875
+ worker.child.on("error", (err) => {
38876
+ worker.closed = true;
38877
+ onClose(worker);
38878
+ const waiter = worker.activeTurn;
38879
+ if (waiter) {
38880
+ worker.activeTurn = null;
38881
+ waiter.resolve({
38882
+ kind: "exit",
38883
+ code: null,
38884
+ error: err.message
38885
+ });
38886
+ }
38887
+ });
38888
+ worker.child.on("close", (code) => {
38889
+ worker.closed = true;
38890
+ dispatchEvents(worker.parser.flush());
38891
+ onClose(worker);
38892
+ const waiter = worker.activeTurn;
38893
+ if (waiter) {
38894
+ worker.activeTurn = null;
38895
+ waiter.resolve({
38896
+ kind: "exit",
38897
+ code
38898
+ });
38899
+ }
38900
+ });
38901
+ }
38902
+ function awaitWorkerTurn(worker, prompt, timeoutMs, signal, onKill) {
38903
+ resetParserTurnStats(worker);
38904
+ return new Promise((resolve) => {
38905
+ let settled = false;
38906
+ let timer = null;
38907
+ const finish = (outcome) => {
38908
+ if (settled) return;
38909
+ settled = true;
38910
+ if (timer !== null) clearTimeout(timer);
38911
+ signal?.removeEventListener("abort", onAbort);
38912
+ worker.activeTurn = null;
38913
+ resolve(outcome);
38914
+ };
38915
+ const onAbort = () => {
38916
+ onKill();
38917
+ finish({
38918
+ kind: "aborted",
38919
+ error: "aborted by caller"
38920
+ });
38921
+ };
38922
+ worker.activeTurn = {
38923
+ deltaText: "",
38924
+ fullStepText: "",
38925
+ resolve: finish
38926
+ };
38927
+ if (signal?.aborted) {
38928
+ onAbort();
38929
+ return;
38930
+ }
38931
+ signal?.addEventListener("abort", onAbort, { once: true });
38932
+ timer = setTimeout(() => {
38933
+ onKill();
38934
+ finish({
38935
+ kind: "timeout",
38936
+ error: "translation timed out after " + timeoutMs + "ms"
38937
+ });
38938
+ }, Math.max(1e3, timeoutMs));
38939
+ timer.unref?.();
38940
+ try {
38941
+ const line = buildStreamInputLine(prompt);
38942
+ if (!worker.child.stdin) throw new Error("translation worker stdin unavailable");
38943
+ worker.child.stdin.write(line, "utf8");
38944
+ } catch (err) {
38945
+ onKill();
38946
+ finish({
38947
+ kind: "exit",
38948
+ code: null,
38949
+ error: err instanceof Error ? err.message : String(err)
38950
+ });
38951
+ }
38952
+ });
38953
+ }
38954
+ function waitForQueueOrAbort(queue, signal) {
38955
+ if (!signal) return queue.then(() => false);
38956
+ if (signal.aborted) return Promise.resolve(true);
38957
+ return new Promise((resolve) => {
38958
+ const onAbort = () => resolve(true);
38959
+ signal.addEventListener("abort", onAbort, { once: true });
38960
+ queue.then(() => {
38961
+ signal.removeEventListener("abort", onAbort);
38962
+ resolve(signal.aborted);
38963
+ });
38964
+ });
38965
+ }
38966
+ var TranslationWorkerPool = class {
38967
+ deps;
38968
+ worker = null;
38969
+ queue = Promise.resolve();
38970
+ disposed = false;
38971
+ constructor(deps) {
38972
+ this.deps = deps;
38973
+ }
38974
+ platform() {
38975
+ return this.deps.platform ?? process.platform;
38976
+ }
38977
+ now() {
38978
+ return this.deps.now?.() ?? Date.now();
38979
+ }
38980
+ /**
38981
+ * Attempt a fast translation via a persistent warm `agy` stream-json worker.
38982
+ * Returns `null` when unavailable (Windows, missing binary, or inside
38983
+ * default test harness without an injected `spawn`) so callers fall back cleanly.
38984
+ */
38985
+ async tryTranslate(req) {
38986
+ if (this.disposed || this.platform() === "win32") return null;
38987
+ if (this.deps.spawn === void 0 && process.env.NODE_TEST_CONTEXT !== void 0) return null;
38988
+ if (!this.deps.bin()) return null;
38989
+ const startedAt = this.now();
38990
+ let releaseQueue;
38991
+ const prevQueue = this.queue;
38992
+ const gate = new Promise((r) => {
38993
+ releaseQueue = r;
38994
+ });
38995
+ this.queue = prevQueue.then(() => gate, () => gate);
38996
+ if (await waitForQueueOrAbort(prevQueue, req.signal) || this.disposed) {
38997
+ releaseQueue();
38998
+ return this.disposed ? null : {
38999
+ ok: false,
39000
+ text: "",
39001
+ code: "ABORTED",
39002
+ error: "aborted by caller",
39003
+ durationMs: this.now() - startedAt
39004
+ };
39005
+ }
39006
+ try {
39007
+ return await this.execute(req, startedAt);
39008
+ } finally {
39009
+ releaseQueue();
39010
+ }
39011
+ }
39012
+ dispose() {
39013
+ this.disposed = true;
39014
+ this.dropWorker(this.worker);
39015
+ }
39016
+ dropWorker(target) {
39017
+ if (!target) return;
39018
+ if (this.worker === target) this.worker = null;
39019
+ killWorkerProcess(target, this.platform());
39020
+ }
39021
+ armIdleTimer(target) {
39022
+ if (target.idleTimer !== null) clearTimeout(target.idleTimer);
39023
+ const ttl = this.deps.idleTtlMs ?? 3e5;
39024
+ target.idleTimer = setTimeout(() => {
39025
+ if (this.worker === target && !target.activeTurn) this.dropWorker(target);
39026
+ }, ttl);
39027
+ target.idleTimer.unref?.();
39028
+ }
39029
+ ensureWorker(bin, cfg, account, model, effort, promptLen) {
39030
+ const key = `${account?.id ?? "default"}|${model}|${effort}`;
39031
+ const maxTurns = this.deps.maxTurns ?? 8;
39032
+ const maxChars = this.deps.maxPromptChars ?? 32e3;
39033
+ const idleTtlMs = this.deps.idleTtlMs ?? 3e5;
39034
+ const cur = this.worker;
39035
+ if (cur && !cur.closed) {
39036
+ const expired = this.now() - cur.lastUsedAt > idleTtlMs;
39037
+ const exhausted = cur.turns >= maxTurns || cur.promptChars + promptLen > maxChars;
39038
+ if (cur.key === key && !expired && !exhausted) {
39039
+ if (cur.idleTimer !== null) {
39040
+ clearTimeout(cur.idleTimer);
39041
+ cur.idleTimer = null;
39042
+ }
39043
+ return cur;
39044
+ }
39045
+ this.dropWorker(cur);
39046
+ }
39047
+ if (account?.dir && !account.systemHome) try {
39048
+ ensureIsolatedKeychain(account.dir);
39049
+ } catch {}
39050
+ const env = withAgyQuietEnv(buildAgyEnv({
39051
+ account,
39052
+ cfg,
39053
+ telemetryFlags: false
39054
+ }));
39055
+ if (cfg.suppressAgyAutoUpdate !== false) preemptAgyAutoUpdate(env, this.now());
39056
+ const args = [
39057
+ "-p",
39058
+ "--output-format",
39059
+ "stream-json",
39060
+ "--input-format",
39061
+ "stream-json",
39062
+ "--mode",
39063
+ "plan",
39064
+ "--model",
39065
+ model,
39066
+ "--print-timeout",
39067
+ PRINT_TIMEOUT_ARG
39068
+ ];
39069
+ if (effort !== "") args.push("--effort", effort);
39070
+ const created = {
39071
+ key,
39072
+ account,
39073
+ model,
39074
+ effort,
39075
+ child: (this.deps.spawn ?? ((cmd, a, opts) => spawn(cmd, a, opts)))(bin, args, {
39076
+ cwd: tmpdir(),
39077
+ env,
39078
+ stdio: [
39079
+ "pipe",
39080
+ "pipe",
39081
+ "pipe"
39082
+ ],
39083
+ detached: this.platform() !== "win32",
39084
+ windowsHide: true
39085
+ }),
39086
+ parser: new StreamJsonParser(),
39087
+ stderrTail: "",
39088
+ turns: 0,
39089
+ promptChars: 0,
39090
+ lastUsedAt: this.now(),
39091
+ idleTimer: null,
39092
+ closed: false,
39093
+ activeTurn: null
39094
+ };
39095
+ attachWorkerStreams(created, (w) => {
39096
+ if (this.worker === w) this.worker = null;
39097
+ });
39098
+ this.worker = created;
39099
+ return created;
39100
+ }
39101
+ async execute(req, startedAt) {
39102
+ if (req.signal?.aborted) return {
39103
+ ok: false,
39104
+ text: "",
39105
+ code: "ABORTED",
39106
+ error: "aborted by caller",
39107
+ durationMs: this.now() - startedAt
39108
+ };
39109
+ const bin = this.deps.bin();
39110
+ if (!bin) return null;
39111
+ const cfg = this.deps.cfg();
39112
+ const resolvedModel = resolveModelSlug(req.model);
39113
+ const family = modelFamilyOf(resolvedModel);
39114
+ const pool = this.deps.pool;
39115
+ let account;
39116
+ if (pool) {
39117
+ const selected = pool.selectAccount(family, resolvedModel);
39118
+ if (!selected) {
39119
+ if (pool.getAccounts().length > 0) return {
39120
+ ok: false,
39121
+ text: "",
39122
+ code: Err.QUOTA,
39123
+ error: "no eligible Antigravity account available",
39124
+ durationMs: this.now() - startedAt
39125
+ };
39126
+ } else account = selected;
39127
+ }
39128
+ const prompt = stripNulBytes(req.prompt);
39129
+ for (let effortAttempt = 0; effortAttempt < 2; effortAttempt++) {
39130
+ const wantedEffort = effortAttempt === 0 ? (req.effort ?? "").trim() : "";
39131
+ const effort = wantedEffort !== "" && !this.deps.isEffortUnsupported?.(resolvedModel) ? wantedEffort : "";
39132
+ const active = this.ensureWorker(bin, cfg, account, resolvedModel, effort, prompt.length);
39133
+ const outcome = await awaitWorkerTurn(active, prompt, req.timeoutMs, req.signal, () => this.dropWorker(active));
39134
+ const res = this.handleOutcome(active, outcome, prompt.length, family, resolvedModel, account, effort, effortAttempt === 0, startedAt);
39135
+ if (res === "retry-without-effort") continue;
39136
+ return res;
39137
+ }
39138
+ return {
39139
+ ok: false,
39140
+ text: "",
39141
+ code: Err.AGY_ERROR,
39142
+ error: "translation failed after effort retry",
39143
+ durationMs: this.now() - startedAt
39144
+ };
39145
+ }
39146
+ handleOutcome(active, outcome, promptLen, family, resolvedModel, account, effort, canRetryEffort, startedAt) {
39147
+ const durationMs = this.now() - startedAt;
39148
+ const pool = this.deps.pool;
39149
+ const sawAuthFailure = active.parser.stats.sawAuthFailure;
39150
+ if (outcome.kind === "result" && outcome.ok) {
39151
+ if (looksLikeTosViolation(outcome.response)) {
39152
+ this.dropWorker(active);
39153
+ return this.mapFailure(outcome.response, pool, account, family, resolvedModel, true, durationMs, sawAuthFailure);
39154
+ }
39155
+ if (outcome.response === "") {
39156
+ this.finishHealthyTurn(active, promptLen);
39157
+ this.deps.log(`translation worker produced empty response: model=${resolvedModel} durationMs=${durationMs}`);
39158
+ return {
39159
+ ok: false,
39160
+ text: "",
39161
+ code: Err.EMPTY_RESPONSE,
39162
+ error: "the translate model returned no text",
39163
+ ...account ? { accountId: account.id } : {},
39164
+ durationMs
39165
+ };
39166
+ }
39167
+ if (account) pool?.recordSuccess(account.id, family);
39168
+ this.finishHealthyTurn(active, promptLen);
39169
+ return {
39170
+ ok: true,
39171
+ text: outcome.response,
39172
+ ...account ? { accountId: account.id } : {},
39173
+ durationMs
39174
+ };
39175
+ }
39176
+ const errText = [
39177
+ ...outcome.kind === "result" ? [outcome.error, outcome.response] : [outcome.error],
39178
+ active.parser.stats.lastResultError,
39179
+ active.parser.stats.authFailureText,
39180
+ active.stderrTail
39181
+ ].filter((s) => typeof s === "string" && s.trim() !== "").join("\n");
39182
+ const refusedModel = parseEffortUnsupported(errText);
39183
+ if (canRetryEffort && effort !== "" && (refusedModel !== null || /--effort/i.test(errText) && /not supported|unsupported/i.test(errText))) {
39184
+ this.deps.rememberEffortUnsupported?.(refusedModel ?? resolvedModel, errText);
39185
+ this.dropWorker(active);
39186
+ return "retry-without-effort";
39187
+ }
39188
+ this.dropWorker(active);
39189
+ if (outcome.kind === "aborted") return {
39190
+ ok: false,
39191
+ text: "",
39192
+ code: "ABORTED",
39193
+ error: outcome.error,
39194
+ durationMs
39195
+ };
39196
+ if (outcome.kind === "timeout") return {
39197
+ ok: false,
39198
+ text: "",
39199
+ code: Err.TIMEOUT,
39200
+ error: outcome.error,
39201
+ durationMs
39202
+ };
39203
+ return this.mapFailure(errText, pool, account, family, resolvedModel, outcome.kind === "result", durationMs, sawAuthFailure);
39204
+ }
39205
+ finishHealthyTurn(active, promptLen) {
39206
+ active.turns += 1;
39207
+ active.promptChars += promptLen;
39208
+ active.lastUsedAt = this.now();
39209
+ const maxTurns = this.deps.maxTurns ?? 8;
39210
+ const maxChars = this.deps.maxPromptChars ?? 32e3;
39211
+ if (active.turns >= maxTurns || active.promptChars >= maxChars) this.dropWorker(active);
39212
+ else if (!active.closed) this.armIdleTimer(active);
39213
+ }
39214
+ mapFailure(errText, pool, account, family, resolvedModel, wasResultEnvelope, durationMs, sawAuthFailure) {
39215
+ const accountPatch = account ? { accountId: account.id } : {};
39216
+ if (looksLikeTosViolation(errText)) {
39217
+ if (account) pool?.markAuthRequired(account.id, errText);
39218
+ return {
39219
+ ok: false,
39220
+ text: "",
39221
+ code: Err.AGY_ERROR,
39222
+ error: errText,
39223
+ ...accountPatch,
39224
+ durationMs
39225
+ };
39226
+ }
39227
+ if (looksLikeValidationRequired(errText)) return {
39228
+ ok: false,
39229
+ text: "",
39230
+ code: Err.AGY_ERROR,
39231
+ error: errText,
39232
+ ...accountPatch,
39233
+ durationMs
39234
+ };
39235
+ if (looksLikeHardRateLimit(errText)) {
39236
+ if (account && pool) {
39237
+ const resetMs = parseResetDurationMs(errText);
39238
+ const resetIso = resetMs ? new Date(this.now() + resetMs).toISOString() : void 0;
39239
+ pool.recordFailure(account.id, family, errText, resetIso);
39240
+ if (pool.getActiveAccountId(family) === account.id) pool.advanceAccount(account.id, family, resolvedModel);
39241
+ }
39242
+ return {
39243
+ ok: false,
39244
+ text: "",
39245
+ code: Err.RATE_LIMIT,
39246
+ error: errText,
39247
+ ...accountPatch,
39248
+ durationMs
39249
+ };
39250
+ }
39251
+ if (looksLikeRateLimit(errText)) return {
39252
+ ok: false,
39253
+ text: "",
39254
+ code: Err.OVERLOADED,
39255
+ error: errText,
39256
+ ...accountPatch,
39257
+ durationMs
39258
+ };
39259
+ if (looksLikeNetworkError(errText) || looksLikeAuthVerificationJitter(errText)) return {
39260
+ ok: false,
39261
+ text: "",
39262
+ code: Err.NETWORK,
39263
+ error: errText,
39264
+ ...accountPatch,
39265
+ durationMs
39266
+ };
39267
+ const unrecog = parseModelNotRecognized(errText);
39268
+ if (unrecog || looksLikeEligibilityFailure(errText)) {
39269
+ if (account && pool) {
39270
+ if (unrecog && typeof pool.markModelUnsupported === "function") pool.markModelUnsupported(account.id, unrecog);
39271
+ pool.advanceAccount(account.id, family, resolvedModel);
39272
+ }
39273
+ return {
39274
+ ok: false,
39275
+ text: "",
39276
+ code: Err.ELIGIBILITY,
39277
+ error: errText,
39278
+ ...accountPatch,
39279
+ durationMs
39280
+ };
39281
+ }
39282
+ if (sawAuthFailure || looksLikeAuthFailure(errText)) {
39283
+ if (account && pool && shouldMarkAuthRequired(Err.AUTH, errText)) {
39284
+ pool.noteAuthFailure(account.id, errText);
39285
+ if (pool.getActiveAccountId(family) === account.id) pool.advanceAccount(account.id, family, resolvedModel);
39286
+ }
39287
+ return {
39288
+ ok: false,
39289
+ text: "",
39290
+ code: Err.AUTH,
39291
+ error: errText,
39292
+ ...accountPatch,
39293
+ durationMs
39294
+ };
39295
+ }
39296
+ return {
39297
+ ok: false,
39298
+ text: "",
39299
+ code: wasResultEnvelope ? Err.AGY_ERROR : Err.PROCESS_EXIT,
39300
+ error: errText || "translation worker failed",
39301
+ ...accountPatch,
39302
+ durationMs
39303
+ };
39304
+ }
39305
+ };
38734
39306
  //#endregion
38735
39307
  //#region src/host/pool-auth.ts
38736
39308
  const DONE_STATUS_TTL_MS = 3e4;
@@ -39578,6 +40150,8 @@ function buildFamilyQuotas(params) {
39578
40150
  /** Map the HTTP verdict onto the account-level marker. */
39579
40151
  function unavailableReason(failure, hasModelData) {
39580
40152
  if (failure === null) return hasModelData ? "partial" : "unreachable";
40153
+ if (failure.kind === "tos_violation") return "tos_violation";
40154
+ if (failure.kind === "validation_required") return "validation_required";
39581
40155
  if (failure.kind === "no_license") return "no_license";
39582
40156
  if (failure.kind === "no_summary_access") return "no_summary_access";
39583
40157
  if (failure.kind === "auth") return "auth";
@@ -39668,23 +40242,28 @@ async function refreshAccountQuotaPipeline(deps, account, force = false) {
39668
40242
  if (info?.email) email = info.email;
39669
40243
  }
39670
40244
  const modelsCatalog = buildModelsCatalog(discovered, userQuota);
40245
+ let currentUnavailReason = account.quotaUnavailable?.reason;
39671
40246
  if (!suppressSummary) {
39672
- if ((summary?.groups?.length ?? 0) > 0 || (summary?.buckets?.length ?? 0) > 0) deps.pool.clearQuotaUnavailable(account.id);
39673
- else {
40247
+ if ((summary?.groups?.length ?? 0) > 0 || (summary?.buckets?.length ?? 0) > 0) {
40248
+ deps.pool.clearQuotaUnavailable(account.id);
40249
+ currentUnavailReason = void 0;
40250
+ } else {
39674
40251
  const failure = deps.summaryFailure?.() ?? null;
39675
40252
  const reason = unavailableReason(failure, Object.keys(modelsCatalog).length > 0);
40253
+ currentUnavailReason = reason;
39676
40254
  const previous = account.quotaUnavailable;
39677
40255
  const retryMs = reason === "no_summary_access" ? QUOTA_FREE_TIER_RETRY_MS : QUOTA_LICENSE_RETRY_MS;
39678
40256
  deps.pool.noteQuotaUnavailable(account.id, {
39679
40257
  reason,
39680
40258
  since: previous?.reason === reason ? previous.since : now,
39681
40259
  retryAfter: now + retryMs,
39682
- ...failure?.detail === void 0 ? {} : { detail: failure.detail }
40260
+ ...failure?.detail === void 0 ? {} : { detail: failure.detail },
40261
+ ...failure?.actionUrl === void 0 ? {} : { actionUrl: failure.actionUrl }
39683
40262
  });
39684
40263
  }
39685
40264
  }
39686
40265
  if (!summary && Object.keys(modelsCatalog).length === 0) return null;
39687
- if (account.authRequired) deps.pool.clearAuthRequired(account.id);
40266
+ if (account.authRequired && currentUnavailReason !== "validation_required" && currentUnavailReason !== "tos_violation") deps.pool.clearAuthRequired(account.id);
39688
40267
  const { familyQuotas, summaryGroups } = buildFamilyQuotas({
39689
40268
  summary,
39690
40269
  modelsCatalog,
@@ -39820,9 +40399,28 @@ function networkFailureCode(error) {
39820
40399
  const cause = error?.cause;
39821
40400
  return typeof cause?.code === "string" ? cause.code : void 0;
39822
40401
  }
40402
+ function extractHttpsActionUrl(bodyText) {
40403
+ try {
40404
+ const details = JSON.parse(bodyText)?.error?.details;
40405
+ if (Array.isArray(details)) for (const d of details) {
40406
+ const meta = d?.metadata;
40407
+ const direct = meta?.validation_url ?? meta?.appeal_url ?? d?.url;
40408
+ if (typeof direct === "string" && direct.startsWith("https://")) return direct;
40409
+ const links = d?.links;
40410
+ if (Array.isArray(links)) for (const l of links) {
40411
+ const u = l?.url;
40412
+ if (typeof u === "string" && u.startsWith("https://")) return u;
40413
+ }
40414
+ }
40415
+ } catch {}
40416
+ const m = bodyText.match(/https:\/\/accounts\.google\.com\/[^\s"'<>]+|https:\/\/support\.google\.com\/[^\s"'<>]+/);
40417
+ return m ? m[0] : void 0;
40418
+ }
39823
40419
  /**
39824
- * Classify a refusal. A 403 that talks about a licence is the one case the
39825
- * account can never retry its way out of, so it gets its own kind.
40420
+ * Classify a refusal. Structured `VALIDATION_REQUIRED` and `TOS_VIOLATION`
40421
+ * share `403 PERMISSION_DENIED` with free-tier refusals, so they MUST be
40422
+ * checked first — otherwise a Pro/Ultra account needing Google verification is
40423
+ * mislabeled as a free-tier account.
39826
40424
  */
39827
40425
  function classifySummaryRefusal(status, bodyText = "") {
39828
40426
  const detail = apiErrorStatus(bodyText);
@@ -39831,6 +40429,24 @@ function classifySummaryRefusal(status, bodyText = "") {
39831
40429
  status,
39832
40430
  ...detail === void 0 ? {} : { detail }
39833
40431
  };
40432
+ if (status === 403 && looksLikeTosViolation(bodyText)) {
40433
+ const actionUrl = extractHttpsActionUrl(bodyText);
40434
+ return {
40435
+ kind: "tos_violation",
40436
+ status,
40437
+ ...detail === void 0 ? {} : { detail },
40438
+ ...actionUrl === void 0 ? {} : { actionUrl }
40439
+ };
40440
+ }
40441
+ if (status === 403 && looksLikeValidationRequired(bodyText)) {
40442
+ const actionUrl = extractHttpsActionUrl(bodyText);
40443
+ return {
40444
+ kind: "validation_required",
40445
+ status,
40446
+ ...detail === void 0 ? {} : { detail },
40447
+ ...actionUrl === void 0 ? {} : { actionUrl }
40448
+ };
40449
+ }
39834
40450
  if (status === 403 && detail === "PERMISSION_DENIED") return {
39835
40451
  kind: "no_summary_access",
39836
40452
  status,
@@ -40204,7 +40820,8 @@ async function getStoredToken(deps, account, allowKeychainFallback = true) {
40204
40820
  function persistRefreshedToken(deps, account, tokens, expectedRefreshToken) {
40205
40821
  const file = quotaTokenFilePath(account);
40206
40822
  try {
40207
- if (expectedRefreshToken && account.dir && !account.systemHome && existsSync(file) && deps.parseCredentialDoc(readFileSync(file, "utf8"))?.refreshToken !== expectedRefreshToken) return;
40823
+ if (expectedRefreshToken && existsSync(file) && deps.parseCredentialDoc(readFileSync(file, "utf8"))?.refreshToken !== expectedRefreshToken) return;
40824
+ if (process.platform !== "win32" && (account.systemHome || !account.dir) && !existsSync(file) && expectedRefreshToken) return;
40208
40825
  mkdirSync(dirname(file), { recursive: true });
40209
40826
  let existing = {};
40210
40827
  if (existsSync(file)) try {
@@ -40290,6 +40907,10 @@ async function getValidAccessTokenUncached(deps, account) {
40290
40907
  if (tok.refreshToken) try {
40291
40908
  const refreshed = await refreshTokens(tok.refreshToken, deps.proxyFor(account), account.id);
40292
40909
  if (!isCurrentAccountGrant(deps, account, tok.refreshToken)) return null;
40910
+ if (process.platform !== "win32" && (account.systemHome || !account.dir)) {
40911
+ const liveKeychain = await deps.readSystemKeychainToken().catch(() => null);
40912
+ if (liveKeychain?.refreshToken && liveKeychain.refreshToken !== tok.refreshToken) return null;
40913
+ }
40293
40914
  if (refreshed?.access_token) {
40294
40915
  deps.persistRefreshedToken(account, {
40295
40916
  access_token: refreshed.access_token,
@@ -41250,7 +41871,11 @@ async function readSessionImage(ctx, dshHomeDir, ref) {
41250
41871
  }
41251
41872
  return null;
41252
41873
  }
41253
- async function runTranslationStream(ctx, getConfig, log, req) {
41874
+ async function runTranslationStream(ctx, getConfig, log, req, workerPool) {
41875
+ if (workerPool !== void 0) {
41876
+ const fast = await workerPool.tryTranslate(req);
41877
+ if (fast !== null) return fast;
41878
+ }
41254
41879
  const startedAt = Date.now();
41255
41880
  const controller = new AbortController();
41256
41881
  const timer = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("translation timed out after " + req.timeoutMs + "ms")), Math.max(1e3, req.timeoutMs));
@@ -41275,7 +41900,7 @@ async function runTranslationStream(ctx, getConfig, log, req) {
41275
41900
  signal,
41276
41901
  ...getConfig().translateBindConversation && req.setup !== void 0 ? { agyTranslateSession: {
41277
41902
  setup: req.setup,
41278
- text: req.prompt
41903
+ text: req.text ?? req.prompt
41279
41904
  } } : {}
41280
41905
  };
41281
41906
  let text = "";
@@ -41420,8 +42045,13 @@ function createHostServices(ctx, entryConfig = {}) {
41420
42045
  if (!targetAcc || !targetAcc.enabled || targetAcc.authRequired) throw new Error(`account ${accountId} is unavailable for model discovery`);
41421
42046
  candidateAccount = targetAcc;
41422
42047
  } else {
41423
- const activeId = pool.getActiveAccountId("google") ?? poolData.lastActiveAccountId ?? poolData.primaryAccountId;
41424
- candidateAccount = (activeId ? pool.getAccount(activeId) : void 0) ?? (poolData.primaryAccountId ? pool.getAccount(poolData.primaryAccountId) : void 0) ?? pool.getAccounts().find((a) => a.enabled && !a.authRequired);
42048
+ const pickEnabled = (id) => {
42049
+ if (!id) return void 0;
42050
+ const acc = pool.getAccount(id);
42051
+ return acc && acc.enabled && !acc.authRequired ? acc : void 0;
42052
+ };
42053
+ candidateAccount = pickEnabled(pool.getActiveAccountId("google")) ?? pickEnabled(poolData.lastActiveAccountId) ?? pickEnabled(poolData.primaryAccountId) ?? pool.getAccounts().find((a) => a.enabled && !a.authRequired);
42054
+ if (!candidateAccount && pool.getAccounts().length > 0) throw new Error("no enabled account available for model discovery");
41425
42055
  }
41426
42056
  const probeModelsFor = async (acc) => {
41427
42057
  const lease = process.platform === "win32" && process.env.NODE_TEST_CONTEXT === void 0 && Boolean(acc && acc.dir && !acc.systemHome) ? await acquireCredentialSlot(acc, pool, {
@@ -41438,18 +42068,23 @@ function createHostServices(ctx, entryConfig = {}) {
41438
42068
  lease?.release();
41439
42069
  }
41440
42070
  };
42071
+ let probedAccount = candidateAccount;
41441
42072
  let out = await probeModelsFor(candidateAccount);
41442
42073
  if (!accountId && (out.code !== 0 || out.stdout.includes("Please sign in") || /sign in|auth|not logged in/i.test(out.stderrTail)) && (!candidateAccount || !candidateAccount.dir)) {
41443
42074
  const secondary = pool.getAccounts().find((a) => a.enabled && !a.authRequired && a.dir);
41444
42075
  if (secondary) {
41445
42076
  const secondaryOut = await probeModelsFor(secondary);
41446
- if (secondaryOut.code === 0 && secondaryOut.stdout.trim() !== "") out = secondaryOut;
42077
+ if (secondaryOut.code === 0 && secondaryOut.stdout.trim() !== "") {
42078
+ out = secondaryOut;
42079
+ probedAccount = secondary;
42080
+ }
41447
42081
  }
41448
42082
  }
41449
42083
  if (out.code !== 0 && out.stdout.trim() === "") throw new Error("agy models failed: " + (out.stderrTail.trim() !== "" ? out.stderrTail.trim().slice(-200) : "exit " + String(out.code)));
41450
42084
  return {
41451
42085
  stdout: out.stdout,
41452
- stderr: out.stderrTail
42086
+ stderr: out.stderrTail,
42087
+ ...probedAccount ? { accountId: probedAccount.id } : {}
41453
42088
  };
41454
42089
  }, getConfig().fallbackModels, getConfig().modelsCacheTtlMs, notifyPicker, {
41455
42090
  cacheFile: join(stateDir(), "model-catalog.json"),
@@ -41493,6 +42128,7 @@ function createHostServices(ctx, entryConfig = {}) {
41493
42128
  refreshQuota: async () => {
41494
42129
  await quota.refreshAllQuotas(false).catch(() => void 0);
41495
42130
  await catalog.forceRefreshAndNotify().catch(() => void 0);
42131
+ await catalog.warmAccounts(pool.getAccounts()).catch(() => void 0);
41496
42132
  },
41497
42133
  effortUnsupported: () => effortStore.read(),
41498
42134
  onEffortUnsupported: (model) => effortStore.remember(model),
@@ -41507,6 +42143,19 @@ function createHostServices(ctx, entryConfig = {}) {
41507
42143
  },
41508
42144
  readImage: (ref) => readSessionImage(ctx, dshHome(), ref)
41509
42145
  });
42146
+ const translationWorkers = new TranslationWorkerPool({
42147
+ cfg: getConfig,
42148
+ bin,
42149
+ pool,
42150
+ log,
42151
+ isEffortUnsupported: (model) => effortStore.read().includes(model),
42152
+ rememberEffortUnsupported: (model) => {
42153
+ if (catalog.advertisedEfforts(model).length === 0) {
42154
+ effortStore.remember(model);
42155
+ notifyPicker();
42156
+ }
42157
+ }
42158
+ });
41510
42159
  const translation = new TranslationService({
41511
42160
  cfg: getConfig,
41512
42161
  catalog: () => catalog.get(),
@@ -41515,7 +42164,7 @@ function createHostServices(ctx, entryConfig = {}) {
41515
42164
  sessionCwd: (id) => sessionWorkspace(id),
41516
42165
  sessionLogPath: (id) => findSessionLogFile(dshHome(), id),
41517
42166
  log,
41518
- run: (req) => runTranslationStream(ctx, getConfig, log, req),
42167
+ run: (req) => runTranslationStream(ctx, getConfig, log, req, translationWorkers),
41519
42168
  appendRecord: async (sessionId, record) => {
41520
42169
  const session = sessionsSvc()?.get(sessionId);
41521
42170
  if (session === void 0) return null;
@@ -41584,6 +42233,7 @@ function createHostServices(ctx, entryConfig = {}) {
41584
42233
  runs,
41585
42234
  adapter,
41586
42235
  translation,
42236
+ translationWorkers,
41587
42237
  setOverride,
41588
42238
  readEffortUnsupported: effortStore.read,
41589
42239
  rememberEffortUnsupported: effortStore.remember,
@@ -41711,6 +42361,14 @@ function handleStatus(services, req, res) {
41711
42361
  let supportedModels;
41712
42362
  if (cfg.poolWideCatalog || !activeAcc || !pool || typeof catalog.getModelsForAccount !== "function") supportedModels = typeof catalog.getUnion === "function" ? catalog.getUnion(pool?.getAccounts ? pool.getAccounts() : [], pool) : typeof catalog.getAllKnownModels === "function" ? catalog.getAllKnownModels(pool?.getAccounts ? pool.getAccounts() : []) : catalog.get().models ?? [];
41713
42363
  else supportedModels = catalog.getModelsForAccount(activeAcc, pool);
42364
+ const sanitizedCatalogModels = sanitizeCatalogEntries(supportedModels).entries;
42365
+ const activeCat = !cfg.poolWideCatalog && activeAcc && typeof catalog.getAccountCatalog === "function" ? catalog.getAccountCatalog(activeAcc.id) ?? cat : cat;
42366
+ const catalogCount = typeof catalog.getModelsForAccount === "function" ? sanitizedCatalogModels.length : activeCat.models.length;
42367
+ const accountModels = {};
42368
+ if (typeof catalog.getAccountCatalog === "function") for (const acc of poolData?.accounts ?? []) {
42369
+ const accCat = catalog.getAccountCatalog(acc.id);
42370
+ if (accCat && accCat.source === "discovered" && accCat.models.length > 0) accountModels[acc.id] = sanitizeCatalogEntries(accCat.models).entries;
42371
+ }
41714
42372
  sendJsonWithEtag(req, res, 200, {
41715
42373
  plugin: "dsh-agy-link",
41716
42374
  bin: bin(),
@@ -41727,11 +42385,12 @@ function handleStatus(services, req, res) {
41727
42385
  pool: poolData,
41728
42386
  quotaRefreshing: typeof quota?.refreshingAccounts === "function" ? quota.refreshingAccounts() : [],
41729
42387
  catalog: {
41730
- source: cat.source,
41731
- count: cat.models.length,
41732
- lastError: cat.lastError ?? null
42388
+ source: activeCat.source,
42389
+ count: catalogCount,
42390
+ lastError: activeCat.lastError ?? cat.lastError ?? null
41733
42391
  },
41734
- catalogModels: sanitizeCatalogEntries(supportedModels).entries,
42392
+ catalogModels: sanitizedCatalogModels,
42393
+ accountModels,
41735
42394
  hiddenModels: cfg.hiddenModels,
41736
42395
  autoWarmup: cfg.autoWarmup,
41737
42396
  warmupModels: cfg.warmupModels,
@@ -42002,7 +42661,11 @@ function handlePoolRefreshQuota(services, req, res) {
42002
42661
  const acc = pool.getAccount(id);
42003
42662
  if (acc) await quota.refreshAccountQuota(acc, true);
42004
42663
  } else await quota.refreshAllQuotas(true);
42005
- await catalog.forceRefresh().catch(() => void 0);
42664
+ if (id) await catalog.forceRefresh(id).catch(() => void 0);
42665
+ else {
42666
+ await catalog.forceRefresh().catch(() => void 0);
42667
+ if (typeof catalog.warmAccounts === "function") await catalog.warmAccounts(pool.getAccounts()).catch(() => void 0);
42668
+ }
42006
42669
  })().catch(() => void 0);
42007
42670
  let releaseTimer;
42008
42671
  const entry = work.finally(() => {
@@ -43492,6 +44155,7 @@ function apply(ctx, entryConfig = {}) {
43492
44155
  ctx.effect(() => {
43493
44156
  return () => {
43494
44157
  bridgeDisposed = true;
44158
+ services.translationWorkers?.dispose();
43495
44159
  auth.dispose();
43496
44160
  poolAuth.cancel();
43497
44161
  if (askToolDispose.current !== null) askToolDispose.current();