dsh-agy-link 0.6.46 → 0.6.48

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
@@ -162,7 +162,7 @@ function defaultConfig() {
162
162
  warmupModels: [PREFERRED_GEMINI_FLASH, PREFERRED_CLAUDE],
163
163
  autoTranslate: false,
164
164
  translateModel: PREFERRED_GEMINI_FLASH,
165
- translateEffort: "medium",
165
+ translateEffort: "low",
166
166
  translateTargetLanguage: "中文(简体)",
167
167
  translateMaxChars: 8e3,
168
168
  translateMaxTokens: 4096,
@@ -569,28 +569,27 @@ function modelFamilyOf(modelId) {
569
569
  /**
570
570
  * True when the unattended quota probe must skip this account's summary call.
571
571
  *
572
- * Only a licence refusal suppresses: it is the one verdict the network cannot
573
- * fix on its own, and re-probing it every hour is pure risk-control exposure.
574
- * `auth` stays on the existing authRequired lifecycle, and network faults must
575
- * 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.
576
575
  */
577
576
  function quotaSummarySuppressed(account, now = Date.now()) {
578
577
  const state = account.quotaUnavailable;
579
578
  if (state === void 0) return false;
580
- 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;
581
580
  return state.retryAfter > now;
582
581
  }
583
582
  /**
584
583
  * Whether the account should leave the background poll ENTIRELY.
585
584
  *
586
- * Only a licence-less account qualifies: it can produce no quota data at all.
587
- * A free-tier account whose SUMMARY is refused still refreshes its model list
588
- * 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).
589
588
  */
590
589
  function accountPollSuppressed(account, now = Date.now()) {
591
590
  const state = account.quotaUnavailable;
592
591
  if (state === void 0) return false;
593
- if (state.reason !== "no_license") return false;
592
+ if (state.reason !== "no_license" && state.reason !== "validation_required" && state.reason !== "tos_violation") return false;
594
593
  return state.retryAfter > now;
595
594
  }
596
595
  /**
@@ -611,7 +610,7 @@ function accountHasArgon(acc, pool, catalog) {
611
610
  if (catalog && catalog.source === "discovered") return catalog.models?.some((m) => isArgonModel(m.id)) ?? false;
612
611
  return false;
613
612
  }
614
- const EFFORT_SUFFIX_RE = /-(?:low|medium|high|tiered|thinking)$/i;
613
+ const EFFORT_SUFFIX_RE = /-(?:tiered-)?(?:low|medium|high|xhigh|tiered|thinking)$/i;
615
614
  /**
616
615
  * Return the un-tiered base model slug (e.g. claude-opus-4-6-thinking -> claude-opus-4-6,
617
616
  * claude-opus-5-5-high -> claude-opus-5-5).
@@ -633,6 +632,14 @@ function modelMatches(requestedModel, candidateModelId) {
633
632
  if (r === c) return true;
634
633
  return baseModelSlug(r) === baseModelSlug(c);
635
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
+ }
636
643
  /**
637
644
  * Determine whether a managed account supports a specific model.
638
645
  * If the account's quota or discovered catalog enumerates models for that family,
@@ -645,14 +652,13 @@ function accountSupportsModel(acc, model, pool, catalog) {
645
652
  if (isArgonModel(clean)) return accountHasArgon(acc, pool, catalog);
646
653
  if (catalog && catalog.source === "discovered" && Array.isArray(catalog.models) && catalog.models.length > 0) {
647
654
  if (catalog.models.some((m) => modelMatches(clean, m.id))) return true;
648
- const familyQuotaModels = acc.quotas?.[modelFamilyOf(clean)]?.models;
649
- if (Array.isArray(familyQuotaModels) && familyQuotaModels.some((m) => modelMatches(clean, m.modelId))) return true;
655
+ if (quotaSupportsModel(acc, clean, pool, catalog)) return true;
650
656
  return false;
651
657
  }
652
658
  const family = modelFamilyOf(clean);
653
659
  const familyQuota = acc.quotas?.[family];
654
660
  if (familyQuota) {
655
- 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);
656
662
  return true;
657
663
  }
658
664
  if (acc.quotas && Object.keys(acc.quotas).length > 0 && acc.quotas.google !== void 0) return false;
@@ -1294,7 +1300,7 @@ var ModelCatalog = class ModelCatalog {
1294
1300
  const ac = new AbortController();
1295
1301
  const timer = setTimeout(() => ac.abort(), 3e4);
1296
1302
  try {
1297
- const { stdout, stderr } = await this.discover(ac.signal, accountId);
1303
+ const { stdout, stderr, accountId: probedAccountId } = await this.discover(ac.signal, accountId);
1298
1304
  if (isUnauthenticatedModelsFallback(stdout, stderr)) {
1299
1305
  const msg = "agy models returned unauthenticated fallback output";
1300
1306
  if (accountId) {
@@ -1323,7 +1329,10 @@ var ModelCatalog = class ModelCatalog {
1323
1329
  if (accountId) {
1324
1330
  this.accountCatalogs.set(accountId, newCatalog);
1325
1331
  if (this.current.source !== "discovered") this.current = newCatalog;
1326
- } else this.current = newCatalog;
1332
+ } else {
1333
+ this.current = newCatalog;
1334
+ if (probedAccountId) this.accountCatalogs.set(probedAccountId, newCatalog);
1335
+ }
1327
1336
  this.persistToDisk();
1328
1337
  if (changed && announce) this.onUpdate?.();
1329
1338
  return;
@@ -3234,7 +3243,7 @@ function describeAgyAutoUpdate(env = process.env, now = Date.now()) {
3234
3243
  * boundary cut the line), which keeps the conservative "arm the grace" path.
3235
3244
  */
3236
3245
  function backgroundTasksFrom(text) {
3237
- const match = /root agent idle;\s*waiting\s+for\s+(\d+)\s+background/i.exec(text);
3246
+ const match = /root agent idle;\s*waiting(?:\s+up\s+to\s+\S+)?\s+for\s+(\d+)\s+background/i.exec(text);
3238
3247
  if (match === null) return null;
3239
3248
  const count = Number(match[1]);
3240
3249
  return Number.isSafeInteger(count) && count >= 0 ? count : null;
@@ -30925,6 +30934,27 @@ var RunRecording = class {
30925
30934
  get hasResult() {
30926
30935
  return this.events.some((e) => e.kind === "result");
30927
30936
  }
30937
+ /** Whether a result event that EventMapper will finish on (ok, or non-empty error response) was recorded. */
30938
+ get hasConsumableResult() {
30939
+ const r = this.getResultEvent();
30940
+ return r !== null && (r.ok || r.response !== "");
30941
+ }
30942
+ /**
30943
+ * Whether any recorded event at or after `from` can finish a span cleanly
30944
+ * (a consumable result envelope, or a completed tool step when `cutOnTool`
30945
+ * is enabled). A settled recording with `failureInfo === null` and no such
30946
+ * event would otherwise replay `INVALID_OUTPUT: agy stream ended without a
30947
+ * result event` on every continuation retry.
30948
+ */
30949
+ hasFinishableEventFrom(from, cutOnTool = true) {
30950
+ for (let i = Math.max(0, from); i < this.events.length; i++) {
30951
+ const ev = this.events[i];
30952
+ if (ev === void 0) continue;
30953
+ if (ev.kind === "result" && (ev.ok || ev.response !== "")) return true;
30954
+ if (cutOnTool && ev.kind === "step" && ev.stepKind === "tool" && ev.tool !== void 0 && (ev.state === "DONE" || ev.state === "ERROR" || ev.state === "RUNNING" || ev.state === void 0 && (ev.tool.output !== void 0 || ev.tool.error !== void 0))) return true;
30955
+ }
30956
+ return false;
30957
+ }
30928
30958
  /** The last result envelope's finish-relevant projection, when one arrived. */
30929
30959
  getResultEvent() {
30930
30960
  for (let i = this.events.length - 1; i >= 0; i--) {
@@ -30936,6 +30966,20 @@ var RunRecording = class {
30936
30966
  }
30937
30967
  return null;
30938
30968
  }
30969
+ /**
30970
+ * True when at least one consumable `result` event (`ok` or non-empty
30971
+ * `response`) exists at index >= `from`. A settled recording with
30972
+ * `failureInfo === null` and no consumable result at `>= from` would always
30973
+ * fail with `agy stream ended without a result event` if re-driven.
30974
+ */
30975
+ hasConsumableResultFrom(from) {
30976
+ const start = Math.max(0, from);
30977
+ for (let i = start; i < this.events.length; i++) {
30978
+ const ev = this.events[i];
30979
+ if (ev !== void 0 && ev.kind === "result" && (ev.ok || ev.response !== "")) return true;
30980
+ }
30981
+ return false;
30982
+ }
30939
30983
  /** Event at an absolute index (bounds-checked). */
30940
30984
  eventAt(index) {
30941
30985
  return this.events[index];
@@ -32299,7 +32343,7 @@ async function resolveEventToolArgs(rec, ev, i, resolved) {
32299
32343
  }
32300
32344
  }
32301
32345
  }
32302
- async function* driveSpan(deps, rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal, compactionNotice) {
32346
+ async function* driveSpan(deps, rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal, compactionNotice, skipDbEnrichment = false) {
32303
32347
  if (signal?.aborted) {
32304
32348
  rec.requestAbort?.();
32305
32349
  yield {
@@ -32317,14 +32361,14 @@ async function* driveSpan(deps, rec, from, cutOnTool, useCodeWrapper, goalContex
32317
32361
  deps.runs.remember(rec);
32318
32362
  deps.runs.pin(rec.runId);
32319
32363
  try {
32320
- yield* driveSpanBody(deps, rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal, compactionNotice);
32364
+ yield* driveSpanBody(deps, rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal, compactionNotice, skipDbEnrichment);
32321
32365
  } finally {
32322
32366
  deps.runs.unpin(rec.runId);
32323
32367
  deps.runs.remember(rec);
32324
32368
  }
32325
32369
  }
32326
32370
  /** Body of {@link driveSpan}: map recorded events until the span finishes. */
32327
- async function* driveSpanBody(deps, rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal, compactionNotice) {
32371
+ async function* driveSpanBody(deps, rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal, compactionNotice, skipDbEnrichment = false) {
32328
32372
  const queue = new ChunkQueue();
32329
32373
  let abortedLocally = false;
32330
32374
  const onAbort = () => {
@@ -32365,9 +32409,11 @@ async function* driveSpanBody(deps, rec, from, cutOnTool, useCodeWrapper, goalCo
32365
32409
  try {
32366
32410
  for await (const ev of rec.eventsFrom(from)) {
32367
32411
  if (abortedLocally || signal?.aborted) break;
32368
- await resolveEventThought(rec, ev, i, resolvedThoughts, pendingThoughtSteps);
32369
- if (pendingThoughtSteps.size > 0) await resolvePendingThoughts(rec, ev, resolvedThoughts, pendingThoughtSteps);
32370
- await resolveEventToolArgs(rec, ev, i, resolved);
32412
+ if (!skipDbEnrichment) {
32413
+ await resolveEventThought(rec, ev, i, resolvedThoughts, pendingThoughtSteps);
32414
+ if (pendingThoughtSteps.size > 0) await resolvePendingThoughts(rec, ev, resolvedThoughts, pendingThoughtSteps);
32415
+ await resolveEventToolArgs(rec, ev, i, resolved);
32416
+ }
32371
32417
  for (const ch of mapper.map(ev, i)) queue.push(ch);
32372
32418
  i++;
32373
32419
  if (mapper.isFinished) {
@@ -34894,7 +34940,7 @@ function buildSpawnArgs(input, printTimeoutMinutes, log) {
34894
34940
  };
34895
34941
  }
34896
34942
  /** Create the recording, parser, HOME snapshot and tool watchdog for one run. */
34897
- function createAttemptRecorder(deps, cfg, account, initialConversationId) {
34943
+ function createAttemptRecorder(deps, cfg, account, initialConversationId, trackSubagents = true) {
34898
34944
  const rec = deps.runs.create();
34899
34945
  rec.accountHome = account && account.dir ? account.dir : void 0;
34900
34946
  const conversationsDir = conversationsDirFor(rec.accountHome);
@@ -34902,7 +34948,7 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId) {
34902
34948
  const parser = new StreamJsonParser();
34903
34949
  deps.onParser?.(parser);
34904
34950
  const watchdog = createToolWatchdog(deps.log, cfg);
34905
- const tracker = new SubagentTracker({
34951
+ const tracker = trackSubagents ? new SubagentTracker({
34906
34952
  conversationId: initialConversationId,
34907
34953
  resumed: Boolean(initialConversationId),
34908
34954
  accountHome: rec.accountHome,
@@ -34913,7 +34959,7 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId) {
34913
34959
  noteActivity: () => {
34914
34960
  watchdog.markEvent();
34915
34961
  }
34916
- });
34962
+ }) : void 0;
34917
34963
  const state = {
34918
34964
  rec,
34919
34965
  parser,
@@ -34923,8 +34969,8 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId) {
34923
34969
  printTimeoutMinutes: watchdog.printTimeoutMinutes,
34924
34970
  attachProcess: (proc) => {
34925
34971
  watchdog.attach(proc);
34926
- tracker.start();
34927
- proc.outcome.finally(() => tracker.stop());
34972
+ tracker?.start();
34973
+ proc.outcome.finally(() => tracker?.stop());
34928
34974
  },
34929
34975
  feedLine: (line, onEvent, onFirstEvent) => {
34930
34976
  watchdog.markEvent();
@@ -34932,11 +34978,11 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId) {
34932
34978
  for (const ev of parser.feed(line + "\n")) {
34933
34979
  if (ev.kind === "init" && ev.conversationId) {
34934
34980
  state.streamCid = ev.conversationId;
34935
- tracker.setConversationId(ev.conversationId);
34981
+ tracker?.setConversationId(ev.conversationId);
34936
34982
  }
34937
34983
  if (ev.kind === "result" && ev.conversationId !== "") {
34938
34984
  state.streamCid = ev.conversationId;
34939
- tracker.setConversationId(ev.conversationId);
34985
+ tracker?.setConversationId(ev.conversationId);
34940
34986
  }
34941
34987
  watchdog.trackStep(ev);
34942
34988
  rec.append(ev);
@@ -34949,7 +34995,7 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId) {
34949
34995
  for (const ev of parser.flush()) {
34950
34996
  if (ev.kind === "result" && ev.conversationId !== "") {
34951
34997
  state.streamCid = ev.conversationId;
34952
- tracker.setConversationId(ev.conversationId);
34998
+ tracker?.setConversationId(ev.conversationId);
34953
34999
  }
34954
35000
  rec.append(ev);
34955
35001
  if (typeof onEvent === "function") try {
@@ -34959,7 +35005,7 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId) {
34959
35005
  },
34960
35006
  stop: () => {
34961
35007
  watchdog.stop();
34962
- tracker.stop();
35008
+ tracker?.stop();
34963
35009
  },
34964
35010
  conversationId: () => state.streamCid ?? diffConversations(before, conversationsDir).conversationId
34965
35011
  };
@@ -35023,6 +35069,19 @@ async function waitForRunSettle(run, timeoutMs) {
35023
35069
  }
35024
35070
  return run.isSettled;
35025
35071
  }
35072
+ function persistBindingOnResult(deps, input, recorder, ev) {
35073
+ if (ev.kind !== "result" || !ev.ok || looksLikeTosViolation(ev.response) || !input.persistBinding || input.sessionAccountKey === "" || deps.isSuperseded(input.sessionKey, recorder.rec)) return;
35074
+ const finalId = input.binding !== void 0 ? input.binding.conversationId : ev.conversationId || recorder.streamCid;
35075
+ if (!finalId) return;
35076
+ const mergedImages = input.binding?.sentImageIds || input.newlySentImageIds.length > 0 ? [.../* @__PURE__ */ new Set([...input.binding?.sentImageIds ?? [], ...input.newlySentImageIds])] : void 0;
35077
+ deps.store.set(input.sessionAccountKey, {
35078
+ conversationId: finalId,
35079
+ lastMessageCount: input.messages.length,
35080
+ updatedAt: Date.now(),
35081
+ model: input.activeModel,
35082
+ ...mergedImages && mergedImages.length > 0 ? { sentImageIds: mergedImages } : {}
35083
+ });
35084
+ }
35026
35085
  /**
35027
35086
  * Spawn the child under the held slot. Installs the line callback (parser feed
35028
35087
  * + tool watchdog + first-event hand-off), registers the run for steer
@@ -35066,9 +35125,10 @@ async function startAttemptProcess(deps, input, spawn, recorder, slot) {
35066
35125
  stdinPayload: spawn.stdinPayload,
35067
35126
  preemptAutoUpdate: cfg.suppressAgyAutoUpdate,
35068
35127
  stderrKeepalive: true,
35069
- onLine: (line) => {
35070
- recorder.feedLine(line, input.agyOnEvent, () => slotHandoff?.onFirstEvent());
35071
- }
35128
+ onLine: (line) => recorder.feedLine(line, (ev) => {
35129
+ persistBindingOnResult(deps, input, recorder, ev);
35130
+ input.agyOnEvent?.(ev);
35131
+ }, () => slotHandoff?.onFirstEvent())
35072
35132
  });
35073
35133
  spawned = true;
35074
35134
  recorder.attachProcess(proc);
@@ -35578,7 +35638,7 @@ async function handleAttemptOutcome(deps, input, ctx) {
35578
35638
  deps.clearInFlightPrompt(sessionKey, spawn.prompt);
35579
35639
  recorder.drain(input.agyOnEvent);
35580
35640
  const conversationId = recorder.conversationId();
35581
- if (!rec.hasResult && outcome.idleGraceTerminated) {
35641
+ if (!rec.hasConsumableResult && outcome.idleGraceTerminated) {
35582
35642
  const recovered = conversationId === null ? "" : recoverFinalReply(conversationId, rec.accountHome);
35583
35643
  const synthResult = {
35584
35644
  kind: "result",
@@ -35884,13 +35944,14 @@ var AgyAdapter = class extends LlmAdapter {
35884
35944
  if (continuation !== null) {
35885
35945
  const rec = this.deps.runs.get(continuation.runId);
35886
35946
  const deadFailure = rec !== void 0 && rec.isSettled ? rec.failureInfo : null;
35887
- if (rec !== void 0 && !(deadFailure !== null && this.claimFailover(sessionKey, deadFailure.code))) {
35947
+ const deadNoResult = rec !== void 0 && rec.isSettled && deadFailure === null && !rec.hasFinishableEventFrom(continuation.eventIndex + 1, hasToolSupport);
35948
+ if (rec !== void 0 && !deadNoResult && !(deadFailure !== null && this.claimFailover(sessionKey, deadFailure.code))) {
35888
35949
  yield* driveSpan(this.deps, rec, continuation.eventIndex + 1, hasToolSupport, isCodeMode, goalContext, supportsGoalUpdate, supportsPlanExit, options.signal);
35889
35950
  return;
35890
35951
  }
35891
35952
  if (rec !== void 0) {
35892
35953
  this.deps.runs.forget(continuation.runId);
35893
- 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"));
35954
+ this.warnOnce("dead-continuation:" + continuation.runId, deadNoResult ? "agy run " + continuation.runId + " settled without a consumable result — retrying this step instead of replaying it" : "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"));
35894
35955
  } 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");
35895
35956
  }
35896
35957
  const catalog = this.deps.catalog.get();
@@ -38773,6 +38834,495 @@ var TranslationService = class {
38773
38834
  }
38774
38835
  }
38775
38836
  };
38837
+ const STDERR_TAIL_CAP = 2048;
38838
+ const PRINT_TIMEOUT_ARG = "30m";
38839
+ function appendTail(prev, chunk) {
38840
+ const next = prev + chunk;
38841
+ return next.length > STDERR_TAIL_CAP ? next.slice(-2048) : next;
38842
+ }
38843
+ function killWorkerProcess(worker, platform) {
38844
+ if (worker.idleTimer !== null) {
38845
+ clearTimeout(worker.idleTimer);
38846
+ worker.idleTimer = null;
38847
+ }
38848
+ worker.closed = true;
38849
+ const child = worker.child;
38850
+ try {
38851
+ child.stdin?.end();
38852
+ } catch {}
38853
+ if (platform !== "win32" && typeof child.pid === "number" && child.pid > 0) try {
38854
+ process.kill(-child.pid, "SIGKILL");
38855
+ return;
38856
+ } catch {}
38857
+ try {
38858
+ child.kill("SIGKILL");
38859
+ } catch {}
38860
+ }
38861
+ function resetParserTurnStats(worker) {
38862
+ worker.stderrTail = "";
38863
+ worker.parser.stats.lastResultError = void 0;
38864
+ worker.parser.stats.sawAuthFailure = false;
38865
+ worker.parser.stats.authFailureText = void 0;
38866
+ }
38867
+ function attachWorkerStreams(worker, onClose) {
38868
+ const dispatchEvents = (events) => {
38869
+ const waiter = worker.activeTurn;
38870
+ if (!waiter) return;
38871
+ for (const ev of events) if (ev.kind === "step" && ev.stepKind === "text") {
38872
+ if (ev.fragment) waiter.deltaText += ev.text;
38873
+ else if (ev.text !== "") waiter.fullStepText = ev.text;
38874
+ } else if (ev.kind === "result") {
38875
+ worker.activeTurn = null;
38876
+ const text = (ev.response || waiter.deltaText || waiter.fullStepText).trim();
38877
+ waiter.resolve({
38878
+ kind: "result",
38879
+ ok: ev.ok,
38880
+ response: text,
38881
+ ...ev.error === void 0 ? {} : { error: ev.error }
38882
+ });
38883
+ return;
38884
+ }
38885
+ };
38886
+ worker.child.stdin?.on("error", () => void 0);
38887
+ worker.child.stdout?.on("data", (buf) => {
38888
+ const chunk = typeof buf === "string" ? buf : buf.toString("utf8");
38889
+ dispatchEvents(worker.parser.feed(chunk));
38890
+ });
38891
+ worker.child.stderr?.on("data", (buf) => {
38892
+ const chunk = typeof buf === "string" ? buf : buf.toString("utf8");
38893
+ worker.stderrTail = appendTail(worker.stderrTail, chunk);
38894
+ });
38895
+ worker.child.on("error", (err) => {
38896
+ worker.closed = true;
38897
+ onClose(worker);
38898
+ const waiter = worker.activeTurn;
38899
+ if (waiter) {
38900
+ worker.activeTurn = null;
38901
+ waiter.resolve({
38902
+ kind: "exit",
38903
+ code: null,
38904
+ error: err.message
38905
+ });
38906
+ }
38907
+ });
38908
+ worker.child.on("close", (code) => {
38909
+ worker.closed = true;
38910
+ dispatchEvents(worker.parser.flush());
38911
+ onClose(worker);
38912
+ const waiter = worker.activeTurn;
38913
+ if (waiter) {
38914
+ worker.activeTurn = null;
38915
+ waiter.resolve({
38916
+ kind: "exit",
38917
+ code
38918
+ });
38919
+ }
38920
+ });
38921
+ }
38922
+ function awaitWorkerTurn(worker, prompt, timeoutMs, signal, onKill) {
38923
+ resetParserTurnStats(worker);
38924
+ return new Promise((resolve) => {
38925
+ let settled = false;
38926
+ let timer = null;
38927
+ const finish = (outcome) => {
38928
+ if (settled) return;
38929
+ settled = true;
38930
+ if (timer !== null) clearTimeout(timer);
38931
+ signal?.removeEventListener("abort", onAbort);
38932
+ worker.activeTurn = null;
38933
+ resolve(outcome);
38934
+ };
38935
+ const onAbort = () => {
38936
+ onKill();
38937
+ finish({
38938
+ kind: "aborted",
38939
+ error: "aborted by caller"
38940
+ });
38941
+ };
38942
+ worker.activeTurn = {
38943
+ deltaText: "",
38944
+ fullStepText: "",
38945
+ resolve: finish
38946
+ };
38947
+ if (signal?.aborted) {
38948
+ onAbort();
38949
+ return;
38950
+ }
38951
+ signal?.addEventListener("abort", onAbort, { once: true });
38952
+ timer = setTimeout(() => {
38953
+ onKill();
38954
+ finish({
38955
+ kind: "timeout",
38956
+ error: "translation timed out after " + timeoutMs + "ms"
38957
+ });
38958
+ }, Math.max(1e3, timeoutMs));
38959
+ timer.unref?.();
38960
+ try {
38961
+ const line = buildStreamInputLine(prompt);
38962
+ if (!worker.child.stdin) throw new Error("translation worker stdin unavailable");
38963
+ worker.child.stdin.write(line, "utf8");
38964
+ } catch (err) {
38965
+ onKill();
38966
+ finish({
38967
+ kind: "exit",
38968
+ code: null,
38969
+ error: err instanceof Error ? err.message : String(err)
38970
+ });
38971
+ }
38972
+ });
38973
+ }
38974
+ function waitForQueueOrAbort(queue, signal) {
38975
+ if (!signal) return queue.then(() => false);
38976
+ if (signal.aborted) return Promise.resolve(true);
38977
+ return new Promise((resolve) => {
38978
+ const onAbort = () => resolve(true);
38979
+ signal.addEventListener("abort", onAbort, { once: true });
38980
+ queue.then(() => {
38981
+ signal.removeEventListener("abort", onAbort);
38982
+ resolve(signal.aborted);
38983
+ });
38984
+ });
38985
+ }
38986
+ var TranslationWorkerPool = class {
38987
+ deps;
38988
+ worker = null;
38989
+ queue = Promise.resolve();
38990
+ disposed = false;
38991
+ constructor(deps) {
38992
+ this.deps = deps;
38993
+ }
38994
+ platform() {
38995
+ return this.deps.platform ?? process.platform;
38996
+ }
38997
+ now() {
38998
+ return this.deps.now?.() ?? Date.now();
38999
+ }
39000
+ /**
39001
+ * Attempt a fast translation via a persistent warm `agy` stream-json worker.
39002
+ * Returns `null` when unavailable (Windows, missing binary, or inside
39003
+ * default test harness without an injected `spawn`) so callers fall back cleanly.
39004
+ */
39005
+ async tryTranslate(req) {
39006
+ if (this.disposed || this.platform() === "win32") return null;
39007
+ if (this.deps.spawn === void 0 && process.env.NODE_TEST_CONTEXT !== void 0) return null;
39008
+ if (!this.deps.bin()) return null;
39009
+ const startedAt = this.now();
39010
+ let releaseQueue;
39011
+ const prevQueue = this.queue;
39012
+ const gate = new Promise((r) => {
39013
+ releaseQueue = r;
39014
+ });
39015
+ this.queue = prevQueue.then(() => gate, () => gate);
39016
+ if (await waitForQueueOrAbort(prevQueue, req.signal) || this.disposed) {
39017
+ releaseQueue();
39018
+ return this.disposed ? null : {
39019
+ ok: false,
39020
+ text: "",
39021
+ code: "ABORTED",
39022
+ error: "aborted by caller",
39023
+ durationMs: this.now() - startedAt
39024
+ };
39025
+ }
39026
+ try {
39027
+ return await this.execute(req, startedAt);
39028
+ } finally {
39029
+ releaseQueue();
39030
+ }
39031
+ }
39032
+ dispose() {
39033
+ this.disposed = true;
39034
+ this.dropWorker(this.worker);
39035
+ }
39036
+ dropWorker(target) {
39037
+ if (!target) return;
39038
+ if (this.worker === target) this.worker = null;
39039
+ killWorkerProcess(target, this.platform());
39040
+ }
39041
+ armIdleTimer(target) {
39042
+ if (target.idleTimer !== null) clearTimeout(target.idleTimer);
39043
+ const ttl = this.deps.idleTtlMs ?? 3e5;
39044
+ target.idleTimer = setTimeout(() => {
39045
+ if (this.worker === target && !target.activeTurn) this.dropWorker(target);
39046
+ }, ttl);
39047
+ target.idleTimer.unref?.();
39048
+ }
39049
+ ensureWorker(bin, cfg, account, model, effort, promptLen) {
39050
+ const key = `${account?.id ?? "default"}|${model}|${effort}`;
39051
+ const maxTurns = this.deps.maxTurns ?? 8;
39052
+ const maxChars = this.deps.maxPromptChars ?? 32e3;
39053
+ const idleTtlMs = this.deps.idleTtlMs ?? 3e5;
39054
+ const cur = this.worker;
39055
+ if (cur && !cur.closed) {
39056
+ const expired = this.now() - cur.lastUsedAt > idleTtlMs;
39057
+ const exhausted = cur.turns >= maxTurns || cur.promptChars + promptLen > maxChars;
39058
+ if (cur.key === key && !expired && !exhausted) {
39059
+ if (cur.idleTimer !== null) {
39060
+ clearTimeout(cur.idleTimer);
39061
+ cur.idleTimer = null;
39062
+ }
39063
+ return cur;
39064
+ }
39065
+ this.dropWorker(cur);
39066
+ }
39067
+ if (account?.dir && !account.systemHome) try {
39068
+ ensureIsolatedKeychain(account.dir);
39069
+ } catch {}
39070
+ const env = withAgyQuietEnv(buildAgyEnv({
39071
+ account,
39072
+ cfg,
39073
+ telemetryFlags: false
39074
+ }));
39075
+ if (cfg.suppressAgyAutoUpdate !== false) preemptAgyAutoUpdate(env, this.now());
39076
+ const args = [
39077
+ "-p",
39078
+ "--output-format",
39079
+ "stream-json",
39080
+ "--input-format",
39081
+ "stream-json",
39082
+ "--mode",
39083
+ "plan",
39084
+ "--model",
39085
+ model,
39086
+ "--print-timeout",
39087
+ PRINT_TIMEOUT_ARG
39088
+ ];
39089
+ if (effort !== "") args.push("--effort", effort);
39090
+ const created = {
39091
+ key,
39092
+ account,
39093
+ model,
39094
+ effort,
39095
+ child: (this.deps.spawn ?? ((cmd, a, opts) => spawn(cmd, a, opts)))(bin, args, {
39096
+ cwd: tmpdir(),
39097
+ env,
39098
+ stdio: [
39099
+ "pipe",
39100
+ "pipe",
39101
+ "pipe"
39102
+ ],
39103
+ detached: this.platform() !== "win32",
39104
+ windowsHide: true
39105
+ }),
39106
+ parser: new StreamJsonParser(),
39107
+ stderrTail: "",
39108
+ turns: 0,
39109
+ promptChars: 0,
39110
+ lastUsedAt: this.now(),
39111
+ idleTimer: null,
39112
+ closed: false,
39113
+ activeTurn: null
39114
+ };
39115
+ attachWorkerStreams(created, (w) => {
39116
+ if (this.worker === w) this.worker = null;
39117
+ });
39118
+ this.worker = created;
39119
+ return created;
39120
+ }
39121
+ async execute(req, startedAt) {
39122
+ if (req.signal?.aborted) return {
39123
+ ok: false,
39124
+ text: "",
39125
+ code: "ABORTED",
39126
+ error: "aborted by caller",
39127
+ durationMs: this.now() - startedAt
39128
+ };
39129
+ const bin = this.deps.bin();
39130
+ if (!bin) return null;
39131
+ const cfg = this.deps.cfg();
39132
+ const resolvedModel = resolveModelSlug(req.model);
39133
+ const family = modelFamilyOf(resolvedModel);
39134
+ const pool = this.deps.pool;
39135
+ let account;
39136
+ if (pool) {
39137
+ const selected = pool.selectAccount(family, resolvedModel);
39138
+ if (!selected) {
39139
+ if (pool.getAccounts().length > 0) return {
39140
+ ok: false,
39141
+ text: "",
39142
+ code: Err.QUOTA,
39143
+ error: "no eligible Antigravity account available",
39144
+ durationMs: this.now() - startedAt
39145
+ };
39146
+ } else account = selected;
39147
+ }
39148
+ const prompt = stripNulBytes(req.prompt);
39149
+ for (let effortAttempt = 0; effortAttempt < 2; effortAttempt++) {
39150
+ const wantedEffort = effortAttempt === 0 ? (req.effort ?? "").trim() : "";
39151
+ const effort = wantedEffort !== "" && !this.deps.isEffortUnsupported?.(resolvedModel) ? wantedEffort : "";
39152
+ const active = this.ensureWorker(bin, cfg, account, resolvedModel, effort, prompt.length);
39153
+ const outcome = await awaitWorkerTurn(active, prompt, req.timeoutMs, req.signal, () => this.dropWorker(active));
39154
+ const res = this.handleOutcome(active, outcome, prompt.length, family, resolvedModel, account, effort, effortAttempt === 0, startedAt);
39155
+ if (res === "retry-without-effort") continue;
39156
+ return res;
39157
+ }
39158
+ return {
39159
+ ok: false,
39160
+ text: "",
39161
+ code: Err.AGY_ERROR,
39162
+ error: "translation failed after effort retry",
39163
+ durationMs: this.now() - startedAt
39164
+ };
39165
+ }
39166
+ handleOutcome(active, outcome, promptLen, family, resolvedModel, account, effort, canRetryEffort, startedAt) {
39167
+ const durationMs = this.now() - startedAt;
39168
+ const pool = this.deps.pool;
39169
+ const sawAuthFailure = active.parser.stats.sawAuthFailure;
39170
+ if (outcome.kind === "result" && outcome.ok) {
39171
+ if (looksLikeTosViolation(outcome.response)) {
39172
+ this.dropWorker(active);
39173
+ return this.mapFailure(outcome.response, pool, account, family, resolvedModel, true, durationMs, sawAuthFailure);
39174
+ }
39175
+ if (outcome.response === "") {
39176
+ this.finishHealthyTurn(active, promptLen);
39177
+ this.deps.log(`translation worker produced empty response: model=${resolvedModel} durationMs=${durationMs}`);
39178
+ return {
39179
+ ok: false,
39180
+ text: "",
39181
+ code: Err.EMPTY_RESPONSE,
39182
+ error: "the translate model returned no text",
39183
+ ...account ? { accountId: account.id } : {},
39184
+ durationMs
39185
+ };
39186
+ }
39187
+ if (account) pool?.recordSuccess(account.id, family);
39188
+ this.finishHealthyTurn(active, promptLen);
39189
+ return {
39190
+ ok: true,
39191
+ text: outcome.response,
39192
+ ...account ? { accountId: account.id } : {},
39193
+ durationMs
39194
+ };
39195
+ }
39196
+ const errText = [
39197
+ ...outcome.kind === "result" ? [outcome.error, outcome.response] : [outcome.error],
39198
+ active.parser.stats.lastResultError,
39199
+ active.parser.stats.authFailureText,
39200
+ active.stderrTail
39201
+ ].filter((s) => typeof s === "string" && s.trim() !== "").join("\n");
39202
+ const refusedModel = parseEffortUnsupported(errText);
39203
+ if (canRetryEffort && effort !== "" && (refusedModel !== null || /--effort/i.test(errText) && /not supported|unsupported/i.test(errText))) {
39204
+ this.deps.rememberEffortUnsupported?.(refusedModel ?? resolvedModel, errText);
39205
+ this.dropWorker(active);
39206
+ return "retry-without-effort";
39207
+ }
39208
+ this.dropWorker(active);
39209
+ if (outcome.kind === "aborted") return {
39210
+ ok: false,
39211
+ text: "",
39212
+ code: "ABORTED",
39213
+ error: outcome.error,
39214
+ durationMs
39215
+ };
39216
+ if (outcome.kind === "timeout") return {
39217
+ ok: false,
39218
+ text: "",
39219
+ code: Err.TIMEOUT,
39220
+ error: outcome.error,
39221
+ durationMs
39222
+ };
39223
+ return this.mapFailure(errText, pool, account, family, resolvedModel, outcome.kind === "result", durationMs, sawAuthFailure);
39224
+ }
39225
+ finishHealthyTurn(active, promptLen) {
39226
+ active.turns += 1;
39227
+ active.promptChars += promptLen;
39228
+ active.lastUsedAt = this.now();
39229
+ const maxTurns = this.deps.maxTurns ?? 8;
39230
+ const maxChars = this.deps.maxPromptChars ?? 32e3;
39231
+ if (active.turns >= maxTurns || active.promptChars >= maxChars) this.dropWorker(active);
39232
+ else if (!active.closed) this.armIdleTimer(active);
39233
+ }
39234
+ mapFailure(errText, pool, account, family, resolvedModel, wasResultEnvelope, durationMs, sawAuthFailure) {
39235
+ const accountPatch = account ? { accountId: account.id } : {};
39236
+ if (looksLikeTosViolation(errText)) {
39237
+ if (account) pool?.markAuthRequired(account.id, errText);
39238
+ return {
39239
+ ok: false,
39240
+ text: "",
39241
+ code: Err.AGY_ERROR,
39242
+ error: errText,
39243
+ ...accountPatch,
39244
+ durationMs
39245
+ };
39246
+ }
39247
+ if (looksLikeValidationRequired(errText)) return {
39248
+ ok: false,
39249
+ text: "",
39250
+ code: Err.AGY_ERROR,
39251
+ error: errText,
39252
+ ...accountPatch,
39253
+ durationMs
39254
+ };
39255
+ if (looksLikeHardRateLimit(errText)) {
39256
+ if (account && pool) {
39257
+ const resetMs = parseResetDurationMs(errText);
39258
+ const resetIso = resetMs ? new Date(this.now() + resetMs).toISOString() : void 0;
39259
+ pool.recordFailure(account.id, family, errText, resetIso);
39260
+ if (pool.getActiveAccountId(family) === account.id) pool.advanceAccount(account.id, family, resolvedModel);
39261
+ }
39262
+ return {
39263
+ ok: false,
39264
+ text: "",
39265
+ code: Err.RATE_LIMIT,
39266
+ error: errText,
39267
+ ...accountPatch,
39268
+ durationMs
39269
+ };
39270
+ }
39271
+ if (looksLikeRateLimit(errText)) return {
39272
+ ok: false,
39273
+ text: "",
39274
+ code: Err.OVERLOADED,
39275
+ error: errText,
39276
+ ...accountPatch,
39277
+ durationMs
39278
+ };
39279
+ if (looksLikeNetworkError(errText) || looksLikeAuthVerificationJitter(errText)) return {
39280
+ ok: false,
39281
+ text: "",
39282
+ code: Err.NETWORK,
39283
+ error: errText,
39284
+ ...accountPatch,
39285
+ durationMs
39286
+ };
39287
+ const unrecog = parseModelNotRecognized(errText);
39288
+ if (unrecog || looksLikeEligibilityFailure(errText)) {
39289
+ if (account && pool) {
39290
+ if (unrecog && typeof pool.markModelUnsupported === "function") pool.markModelUnsupported(account.id, unrecog);
39291
+ pool.advanceAccount(account.id, family, resolvedModel);
39292
+ }
39293
+ return {
39294
+ ok: false,
39295
+ text: "",
39296
+ code: Err.ELIGIBILITY,
39297
+ error: errText,
39298
+ ...accountPatch,
39299
+ durationMs
39300
+ };
39301
+ }
39302
+ if (sawAuthFailure || looksLikeAuthFailure(errText)) {
39303
+ if (account && pool && shouldMarkAuthRequired(Err.AUTH, errText)) {
39304
+ pool.noteAuthFailure(account.id, errText);
39305
+ if (pool.getActiveAccountId(family) === account.id) pool.advanceAccount(account.id, family, resolvedModel);
39306
+ }
39307
+ return {
39308
+ ok: false,
39309
+ text: "",
39310
+ code: Err.AUTH,
39311
+ error: errText,
39312
+ ...accountPatch,
39313
+ durationMs
39314
+ };
39315
+ }
39316
+ return {
39317
+ ok: false,
39318
+ text: "",
39319
+ code: wasResultEnvelope ? Err.AGY_ERROR : Err.PROCESS_EXIT,
39320
+ error: errText || "translation worker failed",
39321
+ ...accountPatch,
39322
+ durationMs
39323
+ };
39324
+ }
39325
+ };
38776
39326
  //#endregion
38777
39327
  //#region src/host/pool-auth.ts
38778
39328
  const DONE_STATUS_TTL_MS = 3e4;
@@ -39620,6 +40170,8 @@ function buildFamilyQuotas(params) {
39620
40170
  /** Map the HTTP verdict onto the account-level marker. */
39621
40171
  function unavailableReason(failure, hasModelData) {
39622
40172
  if (failure === null) return hasModelData ? "partial" : "unreachable";
40173
+ if (failure.kind === "tos_violation") return "tos_violation";
40174
+ if (failure.kind === "validation_required") return "validation_required";
39623
40175
  if (failure.kind === "no_license") return "no_license";
39624
40176
  if (failure.kind === "no_summary_access") return "no_summary_access";
39625
40177
  if (failure.kind === "auth") return "auth";
@@ -39710,23 +40262,28 @@ async function refreshAccountQuotaPipeline(deps, account, force = false) {
39710
40262
  if (info?.email) email = info.email;
39711
40263
  }
39712
40264
  const modelsCatalog = buildModelsCatalog(discovered, userQuota);
40265
+ let currentUnavailReason = account.quotaUnavailable?.reason;
39713
40266
  if (!suppressSummary) {
39714
- if ((summary?.groups?.length ?? 0) > 0 || (summary?.buckets?.length ?? 0) > 0) deps.pool.clearQuotaUnavailable(account.id);
39715
- else {
40267
+ if ((summary?.groups?.length ?? 0) > 0 || (summary?.buckets?.length ?? 0) > 0) {
40268
+ deps.pool.clearQuotaUnavailable(account.id);
40269
+ currentUnavailReason = void 0;
40270
+ } else {
39716
40271
  const failure = deps.summaryFailure?.() ?? null;
39717
40272
  const reason = unavailableReason(failure, Object.keys(modelsCatalog).length > 0);
40273
+ currentUnavailReason = reason;
39718
40274
  const previous = account.quotaUnavailable;
39719
40275
  const retryMs = reason === "no_summary_access" ? QUOTA_FREE_TIER_RETRY_MS : QUOTA_LICENSE_RETRY_MS;
39720
40276
  deps.pool.noteQuotaUnavailable(account.id, {
39721
40277
  reason,
39722
40278
  since: previous?.reason === reason ? previous.since : now,
39723
40279
  retryAfter: now + retryMs,
39724
- ...failure?.detail === void 0 ? {} : { detail: failure.detail }
40280
+ ...failure?.detail === void 0 ? {} : { detail: failure.detail },
40281
+ ...failure?.actionUrl === void 0 ? {} : { actionUrl: failure.actionUrl }
39725
40282
  });
39726
40283
  }
39727
40284
  }
39728
40285
  if (!summary && Object.keys(modelsCatalog).length === 0) return null;
39729
- if (account.authRequired) deps.pool.clearAuthRequired(account.id);
40286
+ if (account.authRequired && currentUnavailReason !== "validation_required" && currentUnavailReason !== "tos_violation") deps.pool.clearAuthRequired(account.id);
39730
40287
  const { familyQuotas, summaryGroups } = buildFamilyQuotas({
39731
40288
  summary,
39732
40289
  modelsCatalog,
@@ -39862,9 +40419,28 @@ function networkFailureCode(error) {
39862
40419
  const cause = error?.cause;
39863
40420
  return typeof cause?.code === "string" ? cause.code : void 0;
39864
40421
  }
40422
+ function extractHttpsActionUrl(bodyText) {
40423
+ try {
40424
+ const details = JSON.parse(bodyText)?.error?.details;
40425
+ if (Array.isArray(details)) for (const d of details) {
40426
+ const meta = d?.metadata;
40427
+ const direct = meta?.validation_url ?? meta?.appeal_url ?? d?.url;
40428
+ if (typeof direct === "string" && direct.startsWith("https://")) return direct;
40429
+ const links = d?.links;
40430
+ if (Array.isArray(links)) for (const l of links) {
40431
+ const u = l?.url;
40432
+ if (typeof u === "string" && u.startsWith("https://")) return u;
40433
+ }
40434
+ }
40435
+ } catch {}
40436
+ const m = bodyText.match(/https:\/\/accounts\.google\.com\/[^\s"'<>]+|https:\/\/support\.google\.com\/[^\s"'<>]+/);
40437
+ return m ? m[0] : void 0;
40438
+ }
39865
40439
  /**
39866
- * Classify a refusal. A 403 that talks about a licence is the one case the
39867
- * account can never retry its way out of, so it gets its own kind.
40440
+ * Classify a refusal. Structured `VALIDATION_REQUIRED` and `TOS_VIOLATION`
40441
+ * share `403 PERMISSION_DENIED` with free-tier refusals, so they MUST be
40442
+ * checked first — otherwise a Pro/Ultra account needing Google verification is
40443
+ * mislabeled as a free-tier account.
39868
40444
  */
39869
40445
  function classifySummaryRefusal(status, bodyText = "") {
39870
40446
  const detail = apiErrorStatus(bodyText);
@@ -39873,6 +40449,24 @@ function classifySummaryRefusal(status, bodyText = "") {
39873
40449
  status,
39874
40450
  ...detail === void 0 ? {} : { detail }
39875
40451
  };
40452
+ if (status === 403 && looksLikeTosViolation(bodyText)) {
40453
+ const actionUrl = extractHttpsActionUrl(bodyText);
40454
+ return {
40455
+ kind: "tos_violation",
40456
+ status,
40457
+ ...detail === void 0 ? {} : { detail },
40458
+ ...actionUrl === void 0 ? {} : { actionUrl }
40459
+ };
40460
+ }
40461
+ if (status === 403 && looksLikeValidationRequired(bodyText)) {
40462
+ const actionUrl = extractHttpsActionUrl(bodyText);
40463
+ return {
40464
+ kind: "validation_required",
40465
+ status,
40466
+ ...detail === void 0 ? {} : { detail },
40467
+ ...actionUrl === void 0 ? {} : { actionUrl }
40468
+ };
40469
+ }
39876
40470
  if (status === 403 && detail === "PERMISSION_DENIED") return {
39877
40471
  kind: "no_summary_access",
39878
40472
  status,
@@ -40246,7 +40840,8 @@ async function getStoredToken(deps, account, allowKeychainFallback = true) {
40246
40840
  function persistRefreshedToken(deps, account, tokens, expectedRefreshToken) {
40247
40841
  const file = quotaTokenFilePath(account);
40248
40842
  try {
40249
- if (expectedRefreshToken && account.dir && !account.systemHome && existsSync(file) && deps.parseCredentialDoc(readFileSync(file, "utf8"))?.refreshToken !== expectedRefreshToken) return;
40843
+ if (expectedRefreshToken && existsSync(file) && deps.parseCredentialDoc(readFileSync(file, "utf8"))?.refreshToken !== expectedRefreshToken) return;
40844
+ if (process.platform !== "win32" && (account.systemHome || !account.dir) && !existsSync(file) && expectedRefreshToken) return;
40250
40845
  mkdirSync(dirname(file), { recursive: true });
40251
40846
  let existing = {};
40252
40847
  if (existsSync(file)) try {
@@ -40332,6 +40927,10 @@ async function getValidAccessTokenUncached(deps, account) {
40332
40927
  if (tok.refreshToken) try {
40333
40928
  const refreshed = await refreshTokens(tok.refreshToken, deps.proxyFor(account), account.id);
40334
40929
  if (!isCurrentAccountGrant(deps, account, tok.refreshToken)) return null;
40930
+ if (process.platform !== "win32" && (account.systemHome || !account.dir)) {
40931
+ const liveKeychain = await deps.readSystemKeychainToken().catch(() => null);
40932
+ if (liveKeychain?.refreshToken && liveKeychain.refreshToken !== tok.refreshToken) return null;
40933
+ }
40335
40934
  if (refreshed?.access_token) {
40336
40935
  deps.persistRefreshedToken(account, {
40337
40936
  access_token: refreshed.access_token,
@@ -41292,7 +41891,11 @@ async function readSessionImage(ctx, dshHomeDir, ref) {
41292
41891
  }
41293
41892
  return null;
41294
41893
  }
41295
- async function runTranslationStream(ctx, getConfig, log, req) {
41894
+ async function runTranslationStream(ctx, getConfig, log, req, workerPool) {
41895
+ if (workerPool !== void 0) {
41896
+ const fast = await workerPool.tryTranslate(req);
41897
+ if (fast !== null) return fast;
41898
+ }
41296
41899
  const startedAt = Date.now();
41297
41900
  const controller = new AbortController();
41298
41901
  const timer = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("translation timed out after " + req.timeoutMs + "ms")), Math.max(1e3, req.timeoutMs));
@@ -41317,7 +41920,7 @@ async function runTranslationStream(ctx, getConfig, log, req) {
41317
41920
  signal,
41318
41921
  ...getConfig().translateBindConversation && req.setup !== void 0 ? { agyTranslateSession: {
41319
41922
  setup: req.setup,
41320
- text: req.prompt
41923
+ text: req.text ?? req.prompt
41321
41924
  } } : {}
41322
41925
  };
41323
41926
  let text = "";
@@ -41462,8 +42065,13 @@ function createHostServices(ctx, entryConfig = {}) {
41462
42065
  if (!targetAcc || !targetAcc.enabled || targetAcc.authRequired) throw new Error(`account ${accountId} is unavailable for model discovery`);
41463
42066
  candidateAccount = targetAcc;
41464
42067
  } else {
41465
- const activeId = pool.getActiveAccountId("google") ?? poolData.lastActiveAccountId ?? poolData.primaryAccountId;
41466
- candidateAccount = (activeId ? pool.getAccount(activeId) : void 0) ?? (poolData.primaryAccountId ? pool.getAccount(poolData.primaryAccountId) : void 0) ?? pool.getAccounts().find((a) => a.enabled && !a.authRequired);
42068
+ const pickEnabled = (id) => {
42069
+ if (!id) return void 0;
42070
+ const acc = pool.getAccount(id);
42071
+ return acc && acc.enabled && !acc.authRequired ? acc : void 0;
42072
+ };
42073
+ candidateAccount = pickEnabled(pool.getActiveAccountId("google")) ?? pickEnabled(poolData.lastActiveAccountId) ?? pickEnabled(poolData.primaryAccountId) ?? pool.getAccounts().find((a) => a.enabled && !a.authRequired);
42074
+ if (!candidateAccount && pool.getAccounts().length > 0) throw new Error("no enabled account available for model discovery");
41467
42075
  }
41468
42076
  const probeModelsFor = async (acc) => {
41469
42077
  const lease = process.platform === "win32" && process.env.NODE_TEST_CONTEXT === void 0 && Boolean(acc && acc.dir && !acc.systemHome) ? await acquireCredentialSlot(acc, pool, {
@@ -41480,18 +42088,23 @@ function createHostServices(ctx, entryConfig = {}) {
41480
42088
  lease?.release();
41481
42089
  }
41482
42090
  };
42091
+ let probedAccount = candidateAccount;
41483
42092
  let out = await probeModelsFor(candidateAccount);
41484
42093
  if (!accountId && (out.code !== 0 || out.stdout.includes("Please sign in") || /sign in|auth|not logged in/i.test(out.stderrTail)) && (!candidateAccount || !candidateAccount.dir)) {
41485
42094
  const secondary = pool.getAccounts().find((a) => a.enabled && !a.authRequired && a.dir);
41486
42095
  if (secondary) {
41487
42096
  const secondaryOut = await probeModelsFor(secondary);
41488
- if (secondaryOut.code === 0 && secondaryOut.stdout.trim() !== "") out = secondaryOut;
42097
+ if (secondaryOut.code === 0 && secondaryOut.stdout.trim() !== "") {
42098
+ out = secondaryOut;
42099
+ probedAccount = secondary;
42100
+ }
41489
42101
  }
41490
42102
  }
41491
42103
  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)));
41492
42104
  return {
41493
42105
  stdout: out.stdout,
41494
- stderr: out.stderrTail
42106
+ stderr: out.stderrTail,
42107
+ ...probedAccount ? { accountId: probedAccount.id } : {}
41495
42108
  };
41496
42109
  }, getConfig().fallbackModels, getConfig().modelsCacheTtlMs, notifyPicker, {
41497
42110
  cacheFile: join(stateDir(), "model-catalog.json"),
@@ -41535,6 +42148,7 @@ function createHostServices(ctx, entryConfig = {}) {
41535
42148
  refreshQuota: async () => {
41536
42149
  await quota.refreshAllQuotas(false).catch(() => void 0);
41537
42150
  await catalog.forceRefreshAndNotify().catch(() => void 0);
42151
+ await catalog.warmAccounts(pool.getAccounts()).catch(() => void 0);
41538
42152
  },
41539
42153
  effortUnsupported: () => effortStore.read(),
41540
42154
  onEffortUnsupported: (model) => effortStore.remember(model),
@@ -41549,6 +42163,19 @@ function createHostServices(ctx, entryConfig = {}) {
41549
42163
  },
41550
42164
  readImage: (ref) => readSessionImage(ctx, dshHome(), ref)
41551
42165
  });
42166
+ const translationWorkers = new TranslationWorkerPool({
42167
+ cfg: getConfig,
42168
+ bin,
42169
+ pool,
42170
+ log,
42171
+ isEffortUnsupported: (model) => effortStore.read().includes(model),
42172
+ rememberEffortUnsupported: (model) => {
42173
+ if (catalog.advertisedEfforts(model).length === 0) {
42174
+ effortStore.remember(model);
42175
+ notifyPicker();
42176
+ }
42177
+ }
42178
+ });
41552
42179
  const translation = new TranslationService({
41553
42180
  cfg: getConfig,
41554
42181
  catalog: () => catalog.get(),
@@ -41557,7 +42184,7 @@ function createHostServices(ctx, entryConfig = {}) {
41557
42184
  sessionCwd: (id) => sessionWorkspace(id),
41558
42185
  sessionLogPath: (id) => findSessionLogFile(dshHome(), id),
41559
42186
  log,
41560
- run: (req) => runTranslationStream(ctx, getConfig, log, req),
42187
+ run: (req) => runTranslationStream(ctx, getConfig, log, req, translationWorkers),
41561
42188
  appendRecord: async (sessionId, record) => {
41562
42189
  const session = sessionsSvc()?.get(sessionId);
41563
42190
  if (session === void 0) return null;
@@ -41626,6 +42253,7 @@ function createHostServices(ctx, entryConfig = {}) {
41626
42253
  runs,
41627
42254
  adapter,
41628
42255
  translation,
42256
+ translationWorkers,
41629
42257
  setOverride,
41630
42258
  readEffortUnsupported: effortStore.read,
41631
42259
  rememberEffortUnsupported: effortStore.remember,
@@ -41753,6 +42381,14 @@ function handleStatus(services, req, res) {
41753
42381
  let supportedModels;
41754
42382
  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 ?? [];
41755
42383
  else supportedModels = catalog.getModelsForAccount(activeAcc, pool);
42384
+ const sanitizedCatalogModels = sanitizeCatalogEntries(supportedModels).entries;
42385
+ const activeCat = !cfg.poolWideCatalog && activeAcc && typeof catalog.getAccountCatalog === "function" ? catalog.getAccountCatalog(activeAcc.id) ?? cat : cat;
42386
+ const catalogCount = typeof catalog.getModelsForAccount === "function" ? sanitizedCatalogModels.length : activeCat.models.length;
42387
+ const accountModels = {};
42388
+ if (typeof catalog.getAccountCatalog === "function") for (const acc of poolData?.accounts ?? []) {
42389
+ const accCat = catalog.getAccountCatalog(acc.id);
42390
+ if (accCat && accCat.source === "discovered" && accCat.models.length > 0) accountModels[acc.id] = sanitizeCatalogEntries(accCat.models).entries;
42391
+ }
41756
42392
  sendJsonWithEtag(req, res, 200, {
41757
42393
  plugin: "dsh-agy-link",
41758
42394
  bin: bin(),
@@ -41769,11 +42405,12 @@ function handleStatus(services, req, res) {
41769
42405
  pool: poolData,
41770
42406
  quotaRefreshing: typeof quota?.refreshingAccounts === "function" ? quota.refreshingAccounts() : [],
41771
42407
  catalog: {
41772
- source: cat.source,
41773
- count: cat.models.length,
41774
- lastError: cat.lastError ?? null
42408
+ source: activeCat.source,
42409
+ count: catalogCount,
42410
+ lastError: activeCat.lastError ?? cat.lastError ?? null
41775
42411
  },
41776
- catalogModels: sanitizeCatalogEntries(supportedModels).entries,
42412
+ catalogModels: sanitizedCatalogModels,
42413
+ accountModels,
41777
42414
  hiddenModels: cfg.hiddenModels,
41778
42415
  autoWarmup: cfg.autoWarmup,
41779
42416
  warmupModels: cfg.warmupModels,
@@ -42044,7 +42681,11 @@ function handlePoolRefreshQuota(services, req, res) {
42044
42681
  const acc = pool.getAccount(id);
42045
42682
  if (acc) await quota.refreshAccountQuota(acc, true);
42046
42683
  } else await quota.refreshAllQuotas(true);
42047
- await catalog.forceRefresh().catch(() => void 0);
42684
+ if (id) await catalog.forceRefresh(id).catch(() => void 0);
42685
+ else {
42686
+ await catalog.forceRefresh().catch(() => void 0);
42687
+ if (typeof catalog.warmAccounts === "function") await catalog.warmAccounts(pool.getAccounts()).catch(() => void 0);
42688
+ }
42048
42689
  })().catch(() => void 0);
42049
42690
  let releaseTimer;
42050
42691
  const entry = work.finally(() => {
@@ -43534,6 +44175,7 @@ function apply(ctx, entryConfig = {}) {
43534
44175
  ctx.effect(() => {
43535
44176
  return () => {
43536
44177
  bridgeDisposed = true;
44178
+ services.translationWorkers?.dispose();
43537
44179
  auth.dispose();
43538
44180
  poolAuth.cancel();
43539
44181
  if (askToolDispose.current !== null) askToolDispose.current();