dsh-agy-link 0.4.99 → 0.5.0

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
@@ -5,7 +5,7 @@ import { accessSync, chmodSync, constants, copyFileSync, createReadStream, exist
5
5
  import { homedir, tmpdir } from "node:os";
6
6
  import { mkdir, mkdtemp, readFile, readdir, rm, stat, unlink, writeFile } from "node:fs/promises";
7
7
  import * as dshLlm from "@deepseek-ai/dsh-llm";
8
- import { LlmAdapter, LlmError } from "@deepseek-ai/dsh-llm";
8
+ import { LlmAdapter, LlmError, createUserMessage } from "@deepseek-ai/dsh-llm";
9
9
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
10
10
  import { defineTool } from "@deepseek-ai/dsh-tools";
11
11
  import { EventEmitter } from "node:events";
@@ -84,7 +84,7 @@ function defaultConfig() {
84
84
  extraArgs: [],
85
85
  permissionMode: "skip",
86
86
  defaultModel: "",
87
- defaultEffort: "",
87
+ defaultEffort: "high",
88
88
  timeoutMs: 6e5,
89
89
  longToolIdleMinutes: 240,
90
90
  /**
@@ -145,7 +145,18 @@ function defaultConfig() {
145
145
  proxyUrl: "",
146
146
  suppressAgyAutoUpdate: process.platform === "win32",
147
147
  autoWarmup: false,
148
- warmupModels: ["gemini-3.8-flash", "claude-sonnet-4-6"]
148
+ warmupModels: ["gemini-3.8-flash", "claude-sonnet-4-6"],
149
+ autoTranslate: false,
150
+ translateModel: "gemini-3.8-flash",
151
+ translateEffort: "high",
152
+ translateTargetLanguage: "中文(简体)",
153
+ translateMaxChars: 8e3,
154
+ translateMaxTokens: 4096,
155
+ translateTimeoutMs: 12e4,
156
+ translateRetries: 2,
157
+ translateBindConversation: true,
158
+ translateSkipSameModel: true,
159
+ translateMinIntervalMs: 3e3
149
160
  };
150
161
  }
151
162
  /**
@@ -325,6 +336,14 @@ const Err = {
325
336
  AUX_DISABLED: "AUX_DISABLED",
326
337
  BUSY: "BUSY",
327
338
  /**
339
+ * The model finished cleanly but emitted no visible text at all. agy/Gemini
340
+ * occasionally returns an empty candidate — observed as a normal `stop`
341
+ * envelope with no text block after ~25s — so this is kept distinct from the
342
+ * deterministic AGY_ERROR failures: it is transient, and the bounded retry
343
+ * almost always gets text on the next attempt.
344
+ */
345
+ EMPTY_RESPONSE: "EMPTY_RESPONSE",
346
+ /**
328
347
  * Canonical provider-neutral code for context window overflow.
329
348
  * Enables DSH agent loop to trigger context auto-compaction rather than aborting.
330
349
  */
@@ -533,7 +552,18 @@ function resolveConfig(entry, env = process.env, overrides = readOverrides()) {
533
552
  proxyUrl: asString(get("proxyUrl")) ?? base.proxyUrl,
534
553
  suppressAgyAutoUpdate: asBool(get("suppressAgyAutoUpdate")) ?? base.suppressAgyAutoUpdate,
535
554
  autoWarmup: asBool(get("autoWarmup")) ?? base.autoWarmup,
536
- warmupModels: asStringArray(get("warmupModels")) ?? base.warmupModels
555
+ warmupModels: asStringArray(get("warmupModels")) ?? base.warmupModels,
556
+ autoTranslate: asBool(get("autoTranslate")) ?? base.autoTranslate,
557
+ translateModel: asString(get("translateModel")) ?? base.translateModel,
558
+ translateEffort: asString(get("translateEffort")) ?? base.translateEffort,
559
+ translateTargetLanguage: asString(get("translateTargetLanguage")) ?? base.translateTargetLanguage,
560
+ translateMaxChars: asNum(get("translateMaxChars")) ?? base.translateMaxChars,
561
+ translateMaxTokens: asNum(get("translateMaxTokens")) ?? base.translateMaxTokens,
562
+ translateTimeoutMs: asNum(get("translateTimeoutMs")) ?? base.translateTimeoutMs,
563
+ translateRetries: asNum(get("translateRetries")) ?? base.translateRetries,
564
+ translateSkipSameModel: asBool(get("translateSkipSameModel")) ?? base.translateSkipSameModel,
565
+ translateBindConversation: asBool(get("translateBindConversation")) ?? base.translateBindConversation,
566
+ translateMinIntervalMs: asNum(get("translateMinIntervalMs")) ?? base.translateMinIntervalMs
537
567
  };
538
568
  if (env.DSH_AGY_ENABLED !== void 0) cfg.enabled = asBool(env.DSH_AGY_ENABLED) ?? cfg.enabled;
539
569
  if (env.DSH_AGY_BIN) cfg.agyBin = env.DSH_AGY_BIN;
@@ -613,6 +643,13 @@ function resolveConfig(entry, env = process.env, overrides = readOverrides()) {
613
643
  const wm = asStringArray(env.DSH_AGY_WARMUP_MODELS.split(","));
614
644
  if (wm) cfg.warmupModels = wm;
615
645
  }
646
+ if (env.DSH_AGY_AUTO_TRANSLATE !== void 0) {
647
+ const at = asBool(env.DSH_AGY_AUTO_TRANSLATE);
648
+ if (at !== void 0) cfg.autoTranslate = at;
649
+ }
650
+ if (env.DSH_AGY_TRANSLATE_MODEL) cfg.translateModel = env.DSH_AGY_TRANSLATE_MODEL;
651
+ if (env.DSH_AGY_TRANSLATE_EFFORT) cfg.translateEffort = env.DSH_AGY_TRANSLATE_EFFORT;
652
+ if (env.DSH_AGY_TRANSLATE_LANG) cfg.translateTargetLanguage = env.DSH_AGY_TRANSLATE_LANG;
616
653
  return cfg;
617
654
  }
618
655
  //#endregion
@@ -1545,7 +1582,7 @@ function presentMirrorResult(args, result) {
1545
1582
  card: "generic",
1546
1583
  content: [{
1547
1584
  type: "text",
1548
- text: clip(text, 4e3)
1585
+ text: clip$1(text, 4e3)
1549
1586
  }]
1550
1587
  };
1551
1588
  }
@@ -1558,7 +1595,7 @@ function resultText$1(content) {
1558
1595
  }
1559
1596
  return parts.join("\n");
1560
1597
  }
1561
- function clip(s, max) {
1598
+ function clip$1(s, max) {
1562
1599
  return s.length > max ? s.slice(0, max) + "… (+" + (s.length - max) + " chars)" : s;
1563
1600
  }
1564
1601
  /** Short preview of the recorded step for the degraded-result message. */
@@ -1899,6 +1936,7 @@ var EventMapper = class {
1899
1936
  * banner and the entry is consumed.
1900
1937
  */
1901
1938
  bannerOnlyShown = /* @__PURE__ */ new Set();
1939
+ bannerOnlyIndices = /* @__PURE__ */ new Map();
1902
1940
  bannerOnlyThinkingEmitted = false;
1903
1941
  sawTextStep;
1904
1942
  finished = false;
@@ -1973,7 +2011,10 @@ var EventMapper = class {
1973
2011
  const hasText = text !== void 0 && text.trim() !== "";
1974
2012
  if (!hasText && !allowBannerOnly) return;
1975
2013
  const bannerAlreadyShown = this.bannerOnlyShown.has(stepKey);
1976
- if (hasText) this.bannerOnlyShown.delete(stepKey);
2014
+ if (hasText) {
2015
+ this.bannerOnlyShown.delete(stepKey);
2016
+ this.bannerOnlyIndices.delete(stepKey);
2017
+ } else this.bannerOnlyIndices.set(stepKey, absIndex);
1977
2018
  yield* this.ensureBlock("reasoning");
1978
2019
  const banner = thoughtTokens > 0 ? "[agy · " + thoughtTokens + " tokens]" : "[agy]";
1979
2020
  const combined = !hasText ? `${banner}\n` : bannerAlreadyShown ? `${text.trim()}\n` : `${banner} ${text.trim()}\n`;
@@ -1985,10 +2026,27 @@ var EventMapper = class {
1985
2026
  * it mints the mirror callId and is what continuation detection parses
1986
2027
  * back out of the DSH message list.
1987
2028
  */
2029
+ /**
2030
+ * Flush any thinking prose that resolved in the DB after its banner-only
2031
+ * placeholder already streamed (e.g. tool-heavy steps where thoughts resolved
2032
+ * during tool execution).
2033
+ */
2034
+ *flushBannerOnlyThoughts() {
2035
+ if (this.bannerOnlyShown.size === 0) return;
2036
+ for (const [stepKey, absIdx] of Array.from(this.bannerOnlyIndices.entries())) {
2037
+ if (!this.bannerOnlyShown.has(stepKey)) continue;
2038
+ const text = this.opts.resolvedThoughts?.get(absIdx);
2039
+ if (text !== void 0 && text.trim() !== "") {
2040
+ yield* this.emitThinking(stepKey, absIdx, 0);
2041
+ this.bannerOnlyIndices.delete(stepKey);
2042
+ }
2043
+ }
2044
+ }
1988
2045
  *map(ev, absIndex) {
1989
2046
  if (this.finished) return;
1990
2047
  if (ev.kind === "init") return;
1991
2048
  if (ev.kind === "garbage") return;
2049
+ yield* this.flushBannerOnlyThoughts();
1992
2050
  if (ev.kind === "step") {
1993
2051
  if (ev.usage) this.opts.usage?.noteStepUsage(ev.usage);
1994
2052
  if (ev.stepKind === "text") {
@@ -2075,6 +2133,7 @@ var EventMapper = class {
2075
2133
  if (this.announcedTools.has(ev.stepKey)) return;
2076
2134
  this.announcedTools.add(ev.stepKey);
2077
2135
  if (!this.opts.cutOnTool) return;
2136
+ yield* this.flushBannerOnlyThoughts();
2078
2137
  const close = this.closeOpen();
2079
2138
  if (close) yield close;
2080
2139
  const idx = this.blockIdx;
@@ -2146,6 +2205,7 @@ var EventMapper = class {
2146
2205
  const d = this.appendDelta(ev.response);
2147
2206
  if (d) yield d;
2148
2207
  }
2208
+ yield* this.flushBannerOnlyThoughts();
2149
2209
  const close = this.closeOpen();
2150
2210
  if (close) yield close;
2151
2211
  yield {
@@ -29728,11 +29788,13 @@ function conversationsDirCandidates(accountHome) {
29728
29788
  if (gch !== void 0 && gch !== "") push(join(gch, "antigravity-cli", "conversations"));
29729
29789
  push(AGY_DB_DIR);
29730
29790
  push(join(homedir(), ".gemini", "antigravity-cli", "conversations"));
29731
- const poolBase = join(homedir(), ".dsh", "agy-accounts");
29732
- try {
29733
- for (const ent of readdirSync(poolBase)) {
29791
+ const realHome = process.env.USERPROFILE || process.env.HOME || homedir();
29792
+ const poolBases = [join(homedir(), ".dsh", "agy-accounts")];
29793
+ if (realHome && realHome !== homedir()) poolBases.push(join(realHome, ".dsh", "agy-accounts"));
29794
+ for (const pb of poolBases) try {
29795
+ for (const ent of readdirSync(pb)) {
29734
29796
  if (ent.startsWith(".")) continue;
29735
- push(join(poolBase, ent, ".gemini", "antigravity-cli", "conversations"));
29797
+ push(join(pb, ent, ".gemini", "antigravity-cli", "conversations"));
29736
29798
  }
29737
29799
  } catch {}
29738
29800
  return dirs;
@@ -30213,7 +30275,7 @@ async function readFullToolArgs(conversationId, stepIndex, accountHome) {
30213
30275
  if (cache?.conversationId === conversationId && cache.loaded && now - cacheTime < MAX_CACHE_AGE_MS) {
30214
30276
  const cached = cache.steps.get(stepIndex);
30215
30277
  if (cached !== void 0) return cached;
30216
- if (cache.checkedSteps.has(stepIndex)) return null;
30278
+ if (cache.checkedSteps.has(stepIndex) && now - cacheTime < 500) return null;
30217
30279
  }
30218
30280
  await loadCached(conversationId, accountHome);
30219
30281
  return cache?.steps.get(stepIndex) ?? null;
@@ -30229,7 +30291,7 @@ async function readStepThoughts(conversationId, stepIndex, accountHome) {
30229
30291
  if (cache?.conversationId === conversationId && cache.loaded && now - cacheTime < MAX_CACHE_AGE_MS) {
30230
30292
  const cached = cache.thoughts.get(stepIndex);
30231
30293
  if (cached !== void 0) return cached;
30232
- if (cache.checkedSteps.has(stepIndex)) return null;
30294
+ if (cache.checkedSteps.has(stepIndex) && now - cacheTime < 500) return null;
30233
30295
  }
30234
30296
  await loadCached(conversationId, accountHome);
30235
30297
  return cache?.thoughts.get(stepIndex) ?? null;
@@ -30450,6 +30512,59 @@ function trimToUtf8Bytes(s, maxBytes, note = true) {
30450
30512
  }
30451
30513
  return s.slice(0, lo) + marker;
30452
30514
  }
30515
+ /**
30516
+ * Keep the head and the tail of a long payload, dropping the middle. Command
30517
+ * output and file dumps put the verdict at one end and the setup at the other,
30518
+ * so half the bytes buy nearly all of the signal — the 80/20 cut for tool
30519
+ * results inside a history digest.
30520
+ *
30521
+ * @param text - raw payload.
30522
+ * @param capBytes - UTF-8 byte ceiling for the returned text.
30523
+ * @returns the payload unchanged when it already fits, else head + marker + tail.
30524
+ */
30525
+ function elideMiddle(text, capBytes) {
30526
+ if (capBytes <= 0) return "";
30527
+ if (utf8Bytes(text) <= capBytes) return text;
30528
+ const headBytes = Math.max(1, Math.floor((capBytes - 24) / 2));
30529
+ const marker = "\n…[elided " + (utf8Bytes(text) - capBytes) + "B]…\n";
30530
+ const head = trimToUtf8Bytes(text, headBytes, false);
30531
+ const tailBytes = headBytes;
30532
+ let tailStart = text.length;
30533
+ for (let i = text.length; i >= 0; i--) {
30534
+ if (utf8Bytes(text.slice(i)) > tailBytes) break;
30535
+ tailStart = i;
30536
+ }
30537
+ return head + marker + text.slice(tailStart);
30538
+ }
30539
+ /**
30540
+ * agy refuses the WHOLE invocation when `--effort` is passed to a model that
30541
+ * does not accept one (issue #67, agy 1.4.6 / Windows):
30542
+ *
30543
+ * invalid model selection (--model "gemini-3.8-flash" --effort "medium"):
30544
+ * --effort is not supported for model "gemini-3.8-flash"
30545
+ *
30546
+ * Effort support is a MODEL property, and our catalog only knows it as advisory
30547
+ * (the fallback list is a guess, and agy builds differ). The refusal names the
30548
+ * exact model, which is what makes learning it possible.
30549
+ *
30550
+ * @param text - stdout envelope error, stderr tail, or a mapped failure message.
30551
+ * @returns the refused model id, or null when this is not an effort refusal.
30552
+ */
30553
+ function parseEffortUnsupported(text) {
30554
+ if (text === "" || !/--effort/i.test(text)) return null;
30555
+ const named = text.match(/--effort(?:\s+"?[A-Za-z0-9._-]+"?)?\s+is not supported for model\s+"?([A-Za-z0-9._:\/-]+)"?/i);
30556
+ if (named !== null && named[1] !== void 0 && named[1] !== "") return named[1];
30557
+ if (/invalid model selection/i.test(text)) {
30558
+ const model = text.match(/--model\s+"?([A-Za-z0-9._:\/-]+)"?/i);
30559
+ if (model !== null && model[1] !== void 0 && model[1] !== "") return model[1];
30560
+ }
30561
+ return null;
30562
+ }
30563
+ /** Same-model comparison that ignores a provider prefix and case. */
30564
+ function sameModelId(a, b) {
30565
+ const norm = (s) => s.trim().toLowerCase().replace(/^.*\//, "");
30566
+ return norm(a) === norm(b) && norm(a) !== "";
30567
+ }
30453
30568
  const AGY_PROMPT_SAFE_BYTES = 18e4;
30454
30569
  /**
30455
30570
  * Put the live request at the very head of the prompt so agy's tail-side
@@ -30477,6 +30592,7 @@ async function writeContextTransferFile(sessionKey, body) {
30477
30592
  function buildDigest(messages, fromIdx, maxChars, budgetOpts = {}) {
30478
30593
  const includeTaskLine = budgetOpts.includeTaskLine !== false;
30479
30594
  const perLineCap = budgetOpts.maxLineBytes;
30595
+ const toolLineCap = budgetOpts.toolLineBytes ?? (perLineCap === void 0 ? 800 : Math.min(800, perLineCap));
30480
30596
  const capLine = (line) => perLineCap !== void 0 && utf8Bytes(line) > perLineCap ? trimToUtf8Bytes(line, perLineCap) : line;
30481
30597
  const taskText = stripNulBytes(latestUserTaskText(messages.slice(fromIdx)));
30482
30598
  const taskLine = includeTaskLine && taskText !== "" ? "User: " + taskText : "";
@@ -30488,7 +30604,7 @@ function buildDigest(messages, fromIdx, maxChars, budgetOpts = {}) {
30488
30604
  const text = stripNulBytes(textOf(m));
30489
30605
  if (text === "") continue;
30490
30606
  if (taskLine !== "" && !isToolResultMessage(m) && m.role === "user" && text === taskText) continue;
30491
- otherLines.push(capLine(digestLabel(m) + text));
30607
+ otherLines.push(isToolResultMessage(m) ? capLine(digestLabel(m) + elideMiddle(text, toolLineCap)) : capLine(digestLabel(m) + text));
30492
30608
  }
30493
30609
  let budget = maxChars;
30494
30610
  let taskPart = "";
@@ -30670,6 +30786,40 @@ async function waitForRunSettle(run, timeoutMs) {
30670
30786
  }
30671
30787
  var AgyAdapter = class AgyAdapter extends LlmAdapter {
30672
30788
  deps;
30789
+ /**
30790
+ * Models agy has refused `--effort` for (issue #67). Seeded from the host's
30791
+ * persisted list on first use, then grown by each refusal. Effort support is
30792
+ * advisory in our catalog, so the refusal — not the catalog — is the truth.
30793
+ */
30794
+ effortLessCache = null;
30795
+ /** Models currently known to reject `--effort` (persisted seed + learned). */
30796
+ effortUnsupportedModels() {
30797
+ return [...this.effortLessModels()];
30798
+ }
30799
+ /** True when `--effort` must not be passed to this model. */
30800
+ isEffortUnsupported(model) {
30801
+ if (model === "") return false;
30802
+ for (const known of this.effortLessModels()) if (sameModelId(known, model)) return true;
30803
+ return false;
30804
+ }
30805
+ /** Learn a refusal: remember it, tell the host to persist + refresh the picker. */
30806
+ learnEffortUnsupported(model) {
30807
+ if (model === "") return;
30808
+ const set = this.effortLessModels();
30809
+ if (this.isEffortUnsupported(model)) return;
30810
+ set.add(model);
30811
+ this.deps.log?.("agy refused --effort for model \"" + model + "\" — it is now run without an effort flag (effort support is advisory in the catalog; see issue #67)");
30812
+ try {
30813
+ this.deps.onEffortUnsupported?.(model);
30814
+ } catch {}
30815
+ }
30816
+ effortLessModels() {
30817
+ if (this.effortLessCache === null) {
30818
+ const seeded = this.deps.effortUnsupported?.() ?? [];
30819
+ this.effortLessCache = new Set((Array.isArray(seeded) ? seeded : []).filter((m) => typeof m === "string" && m.trim() !== ""));
30820
+ }
30821
+ return this.effortLessCache;
30822
+ }
30673
30823
  warnedKeys = /* @__PURE__ */ new Set();
30674
30824
  /** sessionKey -> in-flight run, for steer-time preemption. */
30675
30825
  activeRuns = /* @__PURE__ */ new Map();
@@ -30889,7 +31039,7 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
30889
31039
  context: { contextWindow },
30890
31040
  defaultMaxTokens: typeof cfg.maxTokensDefault === "number" && cfg.maxTokensDefault > 0 ? cfg.maxTokensDefault : 8192
30891
31041
  };
30892
- if (entry && Array.isArray(entry.efforts) && entry.efforts.length > 0) {
31042
+ if (this.isEffortUnsupported(cleanId)) {} else if (entry && Array.isArray(entry.efforts) && entry.efforts.length > 0) {
30893
31043
  const cleanEfforts = Array.from(new Set(entry.efforts.filter((e) => typeof e === "string" && e.trim() !== "")));
30894
31044
  if (cleanEfforts.length > 0) {
30895
31045
  const def = defaultEffortFor({
@@ -30972,14 +31122,67 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
30972
31122
  else args.push("-p", opts.prompt);
30973
31123
  return args;
30974
31124
  }
31125
+ /**
31126
+ * Effort self-healing wrapper around {@link streamAttempt} (issue #67).
31127
+ *
31128
+ * agy refuses an ENTIRE invocation when `--effort` is passed to a model that
31129
+ * does not accept one, and that refusal arrives before any output — so the call
31130
+ * is safe to replay. On the refusal the model is learned as effort-less (the
31131
+ * host persists it, so its picker row disappears and later runs never ask) and
31132
+ * the same call is replayed once without `--effort`: a hard turn failure
31133
+ * becomes one extra spawn. The refusal text itself is the evidence that WE
31134
+ * passed the flag, so the replay does not depend on who requested the effort
31135
+ * (an explicit request, `defaultEffort`, or the aux channel's pinning).
31136
+ */
30975
31137
  async *stream(options) {
31138
+ for (let attempt = 0;; attempt++) {
31139
+ let emitted = false;
31140
+ const telemetry = [];
31141
+ let finish = null;
31142
+ for await (const chunk of this.streamAttempt(options, attempt > 0)) {
31143
+ if (chunk.type === "finish") {
31144
+ finish = chunk;
31145
+ continue;
31146
+ }
31147
+ if (chunk.type === "usage") {
31148
+ telemetry.push(chunk);
31149
+ continue;
31150
+ }
31151
+ emitted = true;
31152
+ yield chunk;
31153
+ }
31154
+ if (finish === null) {
31155
+ for (const chunk of telemetry) yield chunk;
31156
+ return;
31157
+ }
31158
+ if (attempt === 0 && !emitted && finish.reason.kind === "error") {
31159
+ const failure = finish.reason.failure;
31160
+ const refused = parseEffortUnsupported(String(failure?.message ?? ""));
31161
+ if (refused !== null) {
31162
+ this.learnEffortUnsupported(refused);
31163
+ continue;
31164
+ }
31165
+ }
31166
+ for (const chunk of telemetry) yield chunk;
31167
+ yield finish;
31168
+ return;
31169
+ }
31170
+ }
31171
+ async *streamAttempt(options, suppressEffort = false) {
30976
31172
  const cfg = this.deps.getConfig();
30977
31173
  const bin = this.deps.bin();
30978
31174
  if (!bin) throw new LlmError("agy binary not found on PATH — install it via https://antigravity.google/docs/cli/install", Err.AGY_NOT_INSTALLED);
30979
31175
  const isReview = typeof options.system === "string" && options.system.includes("REVIEW_POLICY");
30980
31176
  const isTitle = options.purpose === "session-title";
30981
- const isAux = options.purpose === "compaction" || isTitle || isReview;
30982
- if (isAux && !isReview && !cfg.allowAuxiliary) throw new LlmError("auxiliary calls are disabled for the antigravity route (allowAuxiliary: false)", Err.AUX_DISABLED);
31177
+ const isTranslate = options.purpose === "translation";
31178
+ const isAux = options.purpose === "compaction" || isTitle || isReview || isTranslate;
31179
+ const translateSessionRaw = options.agyTranslateSession;
31180
+ const translateSession = isTranslate && typeof translateSessionRaw === "object" && translateSessionRaw !== null ? {
31181
+ setup: String(translateSessionRaw.setup ?? ""),
31182
+ text: String(translateSessionRaw.text ?? "")
31183
+ } : null;
31184
+ const isTranslateSession = translateSession !== null;
31185
+ if (isAux && !isReview && !isTranslate && !cfg.allowAuxiliary) throw new LlmError("auxiliary calls are disabled for the antigravity route (allowAuxiliary: false)", Err.AUX_DISABLED);
30983
31186
  const toolNames = new Set((options.tools ?? []).map((t) => t.name));
30984
31187
  const isCodeMode = toolNames.has("run_code") && !toolNames.has("agy_tool");
30985
31188
  const hasToolSupport = options.tools === void 0 || toolNames.has("agy_tool") || toolNames.has("run_code");
@@ -31035,8 +31238,9 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
31035
31238
  const entry = findEntry(catalog, model);
31036
31239
  const isGemini = (model === "" ? cfg.defaultModel : model).toLowerCase().startsWith("gemini");
31037
31240
  let effort;
31038
- if (isGemini) {
31039
- if (isAux) effort = "low";
31241
+ if (isGemini && !suppressEffort) {
31242
+ if (this.isEffortUnsupported(model)) effort = void 0;
31243
+ else if (isAux && !isTranslate) effort = "low";
31040
31244
  else if (options.reasoningEffort !== void 0) {
31041
31245
  const wanted = String(options.reasoningEffort);
31042
31246
  if (entry && entry.efforts === null) throw new LlmError("model " + model + " has no selectable reasoning efforts", Err.UNSUPPORTED_REASONING_EFFORT);
@@ -31155,12 +31359,14 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
31155
31359
  }
31156
31360
  }
31157
31361
  if (account && !isAux) this.deps.pool?.markAccountActive(account.id);
31158
- const sessionAccountKey = account ? `${sessionKey}:${account.id}` : sessionKey;
31362
+ const bindingKey = isTranslateSession && sessionKey !== "" ? `${sessionKey}#tsl` : sessionKey;
31363
+ const persistBinding = !isAux || isTranslateSession;
31364
+ const sessionAccountKey = account ? `${bindingKey}:${account.id}` : bindingKey;
31159
31365
  let binding = sessionAccountKey !== "" ? this.deps.store.get(sessionAccountKey) : void 0;
31160
- if (binding === void 0 && sessionKey !== "") {
31161
- binding = this.deps.store.get(sessionKey);
31366
+ if (binding === void 0 && bindingKey !== "") {
31367
+ binding = this.deps.store.get(bindingKey);
31162
31368
  if (binding === void 0 && account === void 0) {
31163
- for (const [k, b] of Object.entries(this.deps.store.all())) if (k.startsWith(`${sessionKey}:`)) {
31369
+ for (const [k, b] of Object.entries(this.deps.store.all())) if (k.startsWith(`${bindingKey}:`)) {
31164
31370
  binding = b;
31165
31371
  break;
31166
31372
  }
@@ -31177,12 +31383,12 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
31177
31383
  };
31178
31384
  }
31179
31385
  const currentModel = activeModel === "" ? cfg.defaultModel : activeModel;
31180
- if (!isAux && binding !== void 0 && binding.model && binding.model !== currentModel) {
31386
+ if (persistBinding && binding !== void 0 && binding.model && binding.model !== currentModel) {
31181
31387
  if (sessionAccountKey !== "") this.deps.store.delete(sessionAccountKey);
31182
31388
  binding = void 0;
31183
31389
  }
31184
31390
  const isCompacted = binding !== void 0 && (messages.length <= 4 && binding.lastMessageCount >= 5 || binding.lastMessageCount > 10 && messages.length < Math.floor(binding.lastMessageCount * .8) || binding.lastMessageCount <= 10 && messages.length < binding.lastMessageCount - 2);
31185
- if (!isAux && binding !== void 0 && isCompacted) {
31391
+ if (persistBinding && binding !== void 0 && isCompacted) {
31186
31392
  if (sessionAccountKey !== "") this.deps.store.delete(sessionAccountKey);
31187
31393
  binding = void 0;
31188
31394
  } else if (binding !== void 0 && messages.length < binding.lastMessageCount) {
@@ -31191,7 +31397,11 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
31191
31397
  }
31192
31398
  let stagedDirs = [];
31193
31399
  let prompt = "";
31194
- if (isAux && options.purpose === "compaction") {
31400
+ if (isTranslateSession) {
31401
+ const lastMessage = messages[messages.length - 1] ?? messages[0];
31402
+ const text = translateSession.text !== "" ? translateSession.text : lastMessage === void 0 ? "" : textOf(lastMessage);
31403
+ prompt = binding === void 0 ? translateSession.setup + (translateSession.setup === "" ? "" : "\n\n=====\n\n") + text : text;
31404
+ } else if (isAux && options.purpose === "compaction") {
31195
31405
  const cap = cfg.compactionMaxChars > 0 ? cfg.compactionMaxChars : 8e5;
31196
31406
  const parts = [];
31197
31407
  let used = 0;
@@ -31392,7 +31602,7 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
31392
31602
  prompt,
31393
31603
  model: activeModelForArgs,
31394
31604
  effort,
31395
- conversationId: !isAux && binding !== void 0 ? binding.conversationId : void 0,
31605
+ conversationId: persistBinding && binding !== void 0 ? binding.conversationId : void 0,
31396
31606
  permissionMode: isAux && !isTitle ? "plan" : cfg.permissionMode,
31397
31607
  timeoutMs: cfg.timeoutMs,
31398
31608
  printTimeoutMinutes,
@@ -31404,7 +31614,7 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
31404
31614
  prompt,
31405
31615
  model: activeModelForArgs,
31406
31616
  effort,
31407
- conversationId: !isAux && binding !== void 0 ? binding.conversationId : void 0,
31617
+ conversationId: persistBinding && binding !== void 0 ? binding.conversationId : void 0,
31408
31618
  permissionMode: isAux && !isTitle ? "plan" : cfg.permissionMode,
31409
31619
  timeoutMs: cfg.timeoutMs,
31410
31620
  printTimeoutMinutes,
@@ -31744,7 +31954,7 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
31744
31954
  this.failoverBudget.delete(sessionKey);
31745
31955
  this.rateLimitFailover.delete(sessionKey);
31746
31956
  this.clearNetworkStreak(sessionKey);
31747
- if (!isAux && sessionAccountKey !== "" && !superseded) {
31957
+ if (persistBinding && sessionAccountKey !== "" && !superseded) {
31748
31958
  const finalId = binding !== void 0 ? binding.conversationId : conversationId;
31749
31959
  if (finalId) this.deps.store.set(sessionAccountKey, {
31750
31960
  conversationId: finalId,
@@ -31767,8 +31977,8 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
31767
31977
  }
31768
31978
  const staleConversation = failure.code === Err.AUTH || failure.message !== "" && /conversation.*(not found|invalid|not recognized|expired|does not exist)|session.*(expired|invalid)/i.test(failure.message);
31769
31979
  const interruptedTurn = failure.kind === "aborted" || outcome.timedOut === true;
31770
- if (!isAux && sessionAccountKey !== "" && staleConversation) this.deps.store.delete(sessionAccountKey);
31771
- else if (!isAux && sessionAccountKey !== "" && !superseded) {
31980
+ if (persistBinding && sessionAccountKey !== "" && staleConversation) this.deps.store.delete(sessionAccountKey);
31981
+ else if (persistBinding && sessionAccountKey !== "" && !superseded) {
31772
31982
  const finalId = binding !== void 0 ? binding.conversationId : conversationId;
31773
31983
  if (finalId) this.deps.store.set(sessionAccountKey, {
31774
31984
  conversationId: finalId,
@@ -31867,13 +32077,14 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
31867
32077
  supportsPlanExit
31868
32078
  });
31869
32079
  let i = from;
32080
+ const pendingThoughtSteps = /* @__PURE__ */ new Map();
31870
32081
  try {
31871
32082
  for await (const ev of rec.eventsFrom(from)) {
31872
32083
  if (abortedLocally || signal?.aborted) break;
31873
32084
  const recordedThought = rec.getThoughts(i);
31874
32085
  if (recordedThought !== void 0) resolvedThoughts.set(i, recordedThought);
31875
32086
  else if (ev.kind === "step") {
31876
- const rawObj = ev.raw && typeof ev.raw === "object" ? ev.raw : null;
32087
+ const rawObj = "raw" in ev && ev.raw && typeof ev.raw === "object" ? ev.raw : null;
31877
32088
  const stepUpdate = rawObj?.step_update && typeof rawObj.step_update === "object" ? rawObj.step_update : null;
31878
32089
  const activeConvId = rec.conversationId ?? (typeof rawObj?.conversation_id === "string" ? rawObj.conversation_id : null) ?? (typeof stepUpdate?.conversation_id === "string" ? stepUpdate.conversation_id : null);
31879
32090
  const stepIdx = parseInt(ev.stepKey, 10);
@@ -31890,11 +32101,27 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
31890
32101
  if (th !== null && th.trim() !== "") {
31891
32102
  resolvedThoughts.set(i, th);
31892
32103
  rec.setThoughts(i, th);
31893
- }
32104
+ } else if ((ev.usage?.thinking_tokens ?? 0) > 0 || ev.stepKind === "thinking") pendingThoughtSteps.set(i, ev.stepKey);
31894
32105
  } catch {}
31895
32106
  }
32107
+ if (pendingThoughtSteps.size > 0) {
32108
+ const rawObj = "raw" in ev && ev.raw && typeof ev.raw === "object" ? ev.raw : null;
32109
+ const stepUpdate = rawObj?.step_update && typeof rawObj.step_update === "object" ? rawObj.step_update : null;
32110
+ const activeConvId = rec.conversationId ?? (typeof rawObj?.conversation_id === "string" ? rawObj.conversation_id : null) ?? (typeof stepUpdate?.conversation_id === "string" ? stepUpdate.conversation_id : null);
32111
+ if (activeConvId !== null) for (const [prevI, prevStepKey] of Array.from(pendingThoughtSteps.entries())) {
32112
+ const prevStepIdx = parseInt(prevStepKey, 10);
32113
+ if (Number.isFinite(prevStepIdx)) try {
32114
+ const th = await readStepThoughts(activeConvId, prevStepIdx, rec.accountHome);
32115
+ if (th !== null && th.trim() !== "") {
32116
+ resolvedThoughts.set(prevI, th);
32117
+ rec.setThoughts(prevI, th);
32118
+ pendingThoughtSteps.delete(prevI);
32119
+ }
32120
+ } catch {}
32121
+ }
32122
+ }
31896
32123
  if (ev.kind === "step" && ev.stepKind === "tool" && ev.tool) {
31897
- const rawObj = ev.raw && typeof ev.raw === "object" ? ev.raw : null;
32124
+ const rawObj = "raw" in ev && ev.raw && typeof ev.raw === "object" ? ev.raw : null;
31898
32125
  const stepUpdate = rawObj?.step_update && typeof rawObj.step_update === "object" ? rawObj.step_update : null;
31899
32126
  const activeConvId = rec.conversationId ?? (typeof rawObj?.conversation_id === "string" ? rawObj.conversation_id : null) ?? (typeof stepUpdate?.conversation_id === "string" ? stepUpdate.conversation_id : null);
31900
32127
  const stepIdx = parseInt(ev.stepKey, 10);
@@ -32137,13 +32364,17 @@ async function runAgyOnce(deps, req) {
32137
32364
  error: "agy is not signed in — run /agy auth",
32138
32365
  durationMs: outcome.durationMs
32139
32366
  };
32140
- if (outcome.code !== 0 && text === "") return {
32141
- ok: false,
32142
- text: "",
32143
- conversationId,
32144
- error: "agy exited with code " + outcome.code + ": " + outcome.stderrTail.slice(-300),
32145
- durationMs: outcome.durationMs
32146
- };
32367
+ if (outcome.code !== 0 && text === "") {
32368
+ const envelopeError = parser.stats.lastResultError ?? "";
32369
+ const detail = envelopeError !== "" ? envelopeError : outcome.stderrTail.slice(-300);
32370
+ return {
32371
+ ok: false,
32372
+ text: "",
32373
+ conversationId,
32374
+ error: "agy exited with code " + outcome.code + ": " + detail,
32375
+ durationMs: outcome.durationMs
32376
+ };
32377
+ }
32147
32378
  return {
32148
32379
  ok: text !== "",
32149
32380
  text: text === "" ? "(no output)" : text,
@@ -32179,12 +32410,12 @@ function resolveAskModel(input, catalog, defaultModel) {
32179
32410
  const base = level !== "" ? prefix.replace(/-?(high|medium|low)$/, "") : prefix;
32180
32411
  const candidates = ids.filter((id) => id.startsWith(base));
32181
32412
  if (candidates.length === 0) return defaultModel !== "" ? defaultModel : q;
32182
- const sorted = candidates.slice().sort(compareNatural);
32413
+ const sorted = candidates.slice().sort(compareNatural$1);
32183
32414
  const last = sorted[sorted.length - 1] ?? q;
32184
32415
  if (level === "") return last;
32185
32416
  return sorted.find((id) => id.endsWith("-" + level)) ?? last;
32186
32417
  }
32187
- function compareNatural(a, b) {
32418
+ function compareNatural$1(a, b) {
32188
32419
  const na = a.split(/(\d+)/);
32189
32420
  const nb = b.split(/(\d+)/);
32190
32421
  for (let i = 0; i < Math.max(na.length, nb.length); i++) {
@@ -32253,8 +32484,10 @@ function defineAgyAskTool(deps) {
32253
32484
  }
32254
32485
  const readPaths = typeof args.readPaths === "string" && args.readPaths.trim() !== "" ? args.readPaths.split(/[ ,]+/).filter(Boolean) : [];
32255
32486
  const entry = findEntry(deps.catalog(), model);
32256
- const effort = args.effort ?? (entry?.efforts ? defaultEffortFor(entry, cfg) : void 0);
32257
- const res = await runAgyOnce(deps, {
32487
+ const wanted = args.effort ?? (entry?.efforts ? defaultEffortFor(entry, cfg) : void 0);
32488
+ const learned = deps.effortUnsupported?.() ?? [];
32489
+ const refusedBefore = wanted !== void 0 && learned.some((m) => m !== "" && (m === model || m === entry?.id));
32490
+ const call = (effort) => runAgyOnce(deps, {
32258
32491
  prompt: args.prompt,
32259
32492
  model: model === "" ? void 0 : model,
32260
32493
  effort,
@@ -32264,6 +32497,16 @@ function defineAgyAskTool(deps) {
32264
32497
  readPaths,
32265
32498
  schema: parsedSchema
32266
32499
  });
32500
+ let effort = refusedBefore ? void 0 : wanted;
32501
+ let res = await call(effort);
32502
+ if (!res.ok && effort !== void 0) {
32503
+ const refused = parseEffortUnsupported(String(res.error ?? ""));
32504
+ if (refused !== null) {
32505
+ deps.onEffortUnsupported?.(refused);
32506
+ effort = void 0;
32507
+ res = await call(void 0);
32508
+ }
32509
+ }
32267
32510
  if (!res.ok) throw new Error("agy_ask failed: " + (res.error ?? "unknown error"));
32268
32511
  const footer = res.conversationId ? "\n\n(agy conversation: " + res.conversationId + " — continue it with: agy --conversation " + res.conversationId + ")" : "";
32269
32512
  return res.text + footer + "\n(" + Math.round(res.durationMs / 100) / 10 + "s)";
@@ -32610,6 +32853,8 @@ function writeDoctorReport(deps) {
32610
32853
  lines.push("- plugin config: " + JSON.stringify(cfgDump));
32611
32854
  lines.push("- catalog: " + cat.source + " — " + cat.models.length + " models" + (cat.lastError === void 0 ? "" : " — error: " + cat.lastError));
32612
32855
  for (const m of cat.models) lines.push(" - " + m.id + (m.efforts ? " [" + m.efforts.join("/") + "]" : ""));
32856
+ const effortLess = deps.effortUnsupported?.() ?? [];
32857
+ if (effortLess.length > 0) lines.push("- effort-unsupported (learned from agy refusals): " + effortLess.join(", "));
32613
32858
  lines.push("- conversation bindings: " + Object.keys(bindings).length);
32614
32859
  for (const [k, b] of Object.entries(bindings)) lines.push(" - " + k + " -> " + b.conversationId + " @ " + new Date(b.updatedAt).toISOString());
32615
32860
  lines.push("- node: " + process.version + " — " + process.platform + " " + process.arch);
@@ -32641,7 +32886,7 @@ function writeDoctorReport(deps) {
32641
32886
  }
32642
32887
  //#endregion
32643
32888
  //#region src/host/commands.ts
32644
- const HELP = [
32889
+ const HELP$1 = [
32645
32890
  "**/agy** — Antigravity (agy CLI) bridge",
32646
32891
  "- `/agy status` — binary, version, auth, mode, catalog, bindings",
32647
32892
  "- `/agy pool` / `/agy accounts` — account pool, live quota %, cooldowns",
@@ -32672,18 +32917,18 @@ function agyCommandDefinition(deps) {
32672
32917
  name: "agy",
32673
32918
  description: "Antigravity (agy CLI) bridge: status, login, models, mode, diagnostics, goal",
32674
32919
  input: { hint: "<status|pool|goal|session|enable-account|disable-account|models|mode|effort|dispatch|dispatch-retries|parallel|max-concurrent|workspace|clear|doctor|help>" },
32675
- handler: (invocation) => handle(deps, invocation.rawInput, invocation)
32920
+ handler: (invocation) => handle$1(deps, invocation.rawInput, invocation)
32676
32921
  };
32677
32922
  }
32678
- async function handle(deps, raw, invocation) {
32923
+ async function handle$1(deps, raw, invocation) {
32679
32924
  const parts = raw.trim().split(/\s+/).filter(Boolean);
32680
32925
  const sub = parts[0] ?? "help";
32681
32926
  const arg = parts[1] ?? "";
32682
32927
  try {
32683
- if (sub === "status") return ok(await renderStatus(deps));
32928
+ if (sub === "status") return ok$1(await renderStatus(deps));
32684
32929
  if (sub === "pool" || sub === "accounts") {
32685
32930
  const pool = deps.pool?.();
32686
- if (!pool) return ok("Account pool not enabled.");
32931
+ if (!pool) return ok$1("Account pool not enabled.");
32687
32932
  const accounts = pool.getAccounts();
32688
32933
  const data = pool.getPoolData();
32689
32934
  const lines = [`**Antigravity Account Pool (${accounts.length} accounts, mode: ${data.mode})**`];
@@ -32707,21 +32952,21 @@ async function handle(deps, raw, invocation) {
32707
32952
  else if (cds.length > 0) statusText = ` - ⚠️ ${cds.join("; ")}`;
32708
32953
  lines.push(`${i + 1}. **${a.alias}** (${a.email || a.id})${isPrimary ? " ⭐ primary" : ""}`, ` - Proxy: ${a.proxyUrl ? redactProxyUrl(a.proxyUrl) : deps.cfg().proxyUrl ? redactProxyUrl(deps.cfg().proxyUrl) : "system default"}`, quotaLine, statusText);
32709
32954
  }
32710
- return ok(lines.join("\n"));
32955
+ return ok$1(lines.join("\n"));
32711
32956
  }
32712
32957
  if (sub === "enable-account" || sub === "disable-account") {
32713
- if (!arg) return err(`usage: /agy ${sub} <id>`);
32958
+ if (!arg) return err$1(`usage: /agy ${sub} <id>`);
32714
32959
  const pool = deps.pool?.();
32715
- if (!pool) return err("Account pool not available");
32960
+ if (!pool) return err$1("Account pool not available");
32716
32961
  const enabled = sub === "enable-account";
32717
- return pool.setAccountEnabled(arg, enabled) ? ok(`${enabled ? "Enabled" : "Disabled"} account ${arg}`) : err(`Account ${arg} not found`);
32962
+ return pool.setAccountEnabled(arg, enabled) ? ok$1(`${enabled ? "Enabled" : "Disabled"} account ${arg}`) : err$1(`Account ${arg} not found`);
32718
32963
  }
32719
32964
  if (sub === "add-account") {
32720
32965
  const pool = deps.pool?.();
32721
- if (!pool) return err("Account pool not available");
32966
+ if (!pool) return err$1("Account pool not available");
32722
32967
  const acc = pool.createAccountSlot(arg || void 0);
32723
32968
  pool.markAuthRequired(acc.id, "not signed in yet — complete the terminal login");
32724
- return ok([
32969
+ return ok$1([
32725
32970
  `**Account slot created: [${acc.alias}]** (id: \`${acc.id}\`)`,
32726
32971
  `- Isolated directory: \`${acc.dir}\``,
32727
32972
  `- Run in terminal: \`HOME="${acc.dir}" agy\` to authenticate this Google account.`,
@@ -32731,26 +32976,26 @@ async function handle(deps, raw, invocation) {
32731
32976
  }
32732
32977
  if (sub === "refresh-quota") {
32733
32978
  const quota = deps.quota?.();
32734
- if (!quota) return err("Quota service not available");
32979
+ if (!quota) return err$1("Quota service not available");
32735
32980
  await quota.refreshAllQuotas();
32736
- return ok("Refreshed quota statistics for all accounts in pool.");
32981
+ return ok$1("Refreshed quota statistics for all accounts in pool.");
32737
32982
  }
32738
32983
  if (sub === "clear-cooldown") {
32739
32984
  const pool = deps.pool?.();
32740
- if (!pool) return err("Account pool not available");
32985
+ if (!pool) return err$1("Account pool not available");
32741
32986
  pool.clearCooldown(arg || void 0);
32742
- return ok("Cleared cooldown timers.");
32987
+ return ok$1("Cleared cooldown timers.");
32743
32988
  }
32744
32989
  if (sub === "remove-account") {
32745
- if (!arg) return err("usage: /agy remove-account <id>");
32990
+ if (!arg) return err$1("usage: /agy remove-account <id>");
32746
32991
  const pool = deps.pool?.();
32747
- if (!pool) return err("Account pool not available");
32748
- return pool.deleteAccount(arg) ? ok(`Removed account ${arg}`) : err(`Account ${arg} not found`);
32992
+ if (!pool) return err$1("Account pool not available");
32993
+ return pool.deleteAccount(arg) ? ok$1(`Removed account ${arg}`) : err$1(`Account ${arg} not found`);
32749
32994
  }
32750
32995
  if (sub === "goal") {
32751
32996
  const action = arg || "status";
32752
32997
  const session = invocation?.agent?.session ?? (deps.sessions?.() && invocation?.agent?.id ? deps.sessions().get(invocation.agent.id) : void 0);
32753
- if (!session) return err("No active DSH session available for goal command.");
32998
+ if (!session) return err$1("No active DSH session available for goal command.");
32754
32999
  const events = session.events;
32755
33000
  let latestGoalChange = null;
32756
33001
  if (events) for (let i = events.length - 1; i >= 0; i--) {
@@ -32765,8 +33010,8 @@ async function handle(deps, raw, invocation) {
32765
33010
  }
32766
33011
  const activeGoal = latestGoalChange && latestGoalChange.operation !== "clear" ? latestGoalChange.goal : null;
32767
33012
  if (action === "status") {
32768
- if (!activeGoal || !latestGoalChange) return ok("**DSH Goal Status**: No active goal in this session.");
32769
- return ok([
33013
+ if (!activeGoal || !latestGoalChange) return ok$1("**DSH Goal Status**: No active goal in this session.");
33014
+ return ok$1([
32770
33015
  `**DSH Goal Status** (${{
32771
33016
  active: "🟢",
32772
33017
  paused: "⏸️",
@@ -32780,7 +33025,7 @@ async function handle(deps, raw, invocation) {
32780
33025
  ].join("\n"));
32781
33026
  }
32782
33027
  if (action === "complete") {
32783
- if (!activeGoal || !latestGoalChange) return err("No active goal to complete.");
33028
+ if (!activeGoal || !latestGoalChange) return err$1("No active goal to complete.");
32784
33029
  if (typeof session.append === "function") {
32785
33030
  session.append("goal/change", {
32786
33031
  kind: "goal/change",
@@ -32797,12 +33042,12 @@ async function handle(deps, raw, invocation) {
32797
33042
  createdAt: latestGoalChange.createdAt ?? Date.now(),
32798
33043
  updatedAt: Date.now()
32799
33044
  });
32800
- return ok(`✅ Marked goal \`${activeGoal.id}\` as complete. Automatic continuation rounds stopped.`);
33045
+ return ok$1(`✅ Marked goal \`${activeGoal.id}\` as complete. Automatic continuation rounds stopped.`);
32801
33046
  }
32802
- return err("Session cannot append events.");
33047
+ return err$1("Session cannot append events.");
32803
33048
  }
32804
33049
  if (action === "pause") {
32805
- if (!activeGoal || !latestGoalChange) return err("No active goal to pause.");
33050
+ if (!activeGoal || !latestGoalChange) return err$1("No active goal to pause.");
32806
33051
  if (typeof session.append === "function") {
32807
33052
  session.append("goal/change", {
32808
33053
  kind: "goal/change",
@@ -32819,12 +33064,12 @@ async function handle(deps, raw, invocation) {
32819
33064
  createdAt: latestGoalChange.createdAt ?? Date.now(),
32820
33065
  updatedAt: Date.now()
32821
33066
  });
32822
- return ok(`⏸️ Paused goal \`${activeGoal.id}\`.`);
33067
+ return ok$1(`⏸️ Paused goal \`${activeGoal.id}\`.`);
32823
33068
  }
32824
- return err("Session cannot append events.");
33069
+ return err$1("Session cannot append events.");
32825
33070
  }
32826
33071
  if (action === "resume") {
32827
- if (!activeGoal || !latestGoalChange) return err("No active goal to resume.");
33072
+ if (!activeGoal || !latestGoalChange) return err$1("No active goal to resume.");
32828
33073
  if (typeof session.append === "function") {
32829
33074
  session.append("goal/change", {
32830
33075
  kind: "goal/change",
@@ -32841,12 +33086,12 @@ async function handle(deps, raw, invocation) {
32841
33086
  createdAt: latestGoalChange.createdAt ?? Date.now(),
32842
33087
  updatedAt: Date.now()
32843
33088
  });
32844
- return ok(`▶️ Resumed goal \`${activeGoal.id}\`.`);
33089
+ return ok$1(`▶️ Resumed goal \`${activeGoal.id}\`.`);
32845
33090
  }
32846
- return err("Session cannot append events.");
33091
+ return err$1("Session cannot append events.");
32847
33092
  }
32848
33093
  if (action === "clear") {
32849
- if (!activeGoal) return ok("No active goal to clear.");
33094
+ if (!activeGoal) return ok$1("No active goal to clear.");
32850
33095
  if (typeof session.append === "function") {
32851
33096
  session.append("goal/change", {
32852
33097
  kind: "goal/change",
@@ -32858,11 +33103,11 @@ async function handle(deps, raw, invocation) {
32858
33103
  },
32859
33104
  clearedAt: Date.now()
32860
33105
  });
32861
- return ok(`Cleared goal \`${activeGoal.id}\`.`);
33106
+ return ok$1(`Cleared goal \`${activeGoal.id}\`.`);
32862
33107
  }
32863
- return err("Session cannot append events.");
33108
+ return err$1("Session cannot append events.");
32864
33109
  }
32865
- return err(`Unknown goal action \`${action}\`. Usage: /agy goal [status|complete|pause|resume|clear]`);
33110
+ return err$1(`Unknown goal action \`${action}\`. Usage: /agy goal [status|complete|pause|resume|clear]`);
32866
33111
  }
32867
33112
  if (sub === "session") {
32868
33113
  const action = arg || "info";
@@ -32882,18 +33127,18 @@ async function handle(deps, raw, invocation) {
32882
33127
  } else lines.push("- **Bound agy Conversation**: *(none - next turn starts fresh)*");
32883
33128
  if (session?.events) lines.push(`- **Total Session Events**: ${session.events.length}`);
32884
33129
  } else lines.push("- Current session ID could not be identified from invocation context.");
32885
- return ok(lines.join("\n"));
33130
+ return ok$1(lines.join("\n"));
32886
33131
  }
32887
33132
  if (action === "clear") {
32888
33133
  if (!sessionId) {
32889
33134
  const all = deps.store().all();
32890
33135
  const keys = Object.keys(all);
32891
- if (keys.length === 0) return ok("No conversation bindings yet.");
33136
+ if (keys.length === 0) return ok$1("No conversation bindings yet.");
32892
33137
  const key = keys.reduce((a, b) => (all[a]?.updatedAt ?? 0) >= (all[b]?.updatedAt ?? 0) ? a : b);
32893
33138
  const dropped = all[key];
32894
- if (dropped === void 0) return ok("No conversation bindings yet.");
33139
+ if (dropped === void 0) return ok$1("No conversation bindings yet.");
32895
33140
  deps.store().delete(key);
32896
- return ok(`Dropped binding for session \`${key}\` (agy conversation \`${dropped.conversationId}\`). Next turn starts fresh.`);
33141
+ return ok$1(`Dropped binding for session \`${key}\` (agy conversation \`${dropped.conversationId}\`). Next turn starts fresh.`);
32897
33142
  }
32898
33143
  const bindings = deps.store().all();
32899
33144
  let count = 0;
@@ -32901,48 +33146,48 @@ async function handle(deps, raw, invocation) {
32901
33146
  deps.store().delete(k);
32902
33147
  count++;
32903
33148
  }
32904
- return ok(`Dropped ${count > 0 ? count : "any"} agy conversation binding(s) for session \`${sessionId}\`. Next turn will start a fresh agy conversation.`);
33149
+ return ok$1(`Dropped ${count > 0 ? count : "any"} agy conversation binding(s) for session \`${sessionId}\`. Next turn will start a fresh agy conversation.`);
32905
33150
  }
32906
- return err(`Unknown session action \`${action}\`. Usage: /agy session [info|clear]`);
33151
+ return err$1(`Unknown session action \`${action}\`. Usage: /agy session [info|clear]`);
32907
33152
  }
32908
33153
  if (sub === "auth") {
32909
33154
  const flow = deps.poolAuth?.();
32910
- if (!flow) return err("auth flow not available");
33155
+ if (!flow) return err$1("auth flow not available");
32911
33156
  const st = await flow.beginPrimary();
32912
- if (st.ok && st.url) return ok([
33157
+ if (st.ok && st.url) return ok$1([
32913
33158
  st.browserOpened ? "**浏览器已打开 Google 授权页** — 批准访问后自动完成登录。" : "**请手动打开下面的 URL 完成 Google 授权:**",
32914
33159
  "",
32915
33160
  st.url,
32916
33161
  "",
32917
33162
  "备用:授权完成后运行 `/agy auth-code <授权码或完整回调URL>`。"
32918
33163
  ].join("\n"));
32919
- return err(`failed to start the login flow (${st.code ?? "request_failed"})`);
33164
+ return err$1(`failed to start the login flow (${st.code ?? "request_failed"})`);
32920
33165
  }
32921
33166
  if (sub === "auth-code") {
32922
- if (arg === "") return err("usage: /agy auth-code <code-or-callback-url>");
33167
+ if (arg === "") return err$1("usage: /agy auth-code <code-or-callback-url>");
32923
33168
  const flow = deps.poolAuth?.();
32924
- if (!flow) return err("auth flow not available");
33169
+ if (!flow) return err$1("auth flow not available");
32925
33170
  const st = await flow.submitCode(arg);
32926
33171
  if (st.ok) {
32927
33172
  deps.store().clear();
32928
- return ok("Logged in to Antigravity.");
33173
+ return ok$1("Logged in to Antigravity.");
32929
33174
  }
32930
- return err(`login failed (${st.code ?? "request_failed"})`);
33175
+ return err$1(`login failed (${st.code ?? "request_failed"})`);
32931
33176
  }
32932
33177
  if (sub === "models") {
32933
33178
  const cat = await deps.catalog().forceRefresh();
32934
33179
  const lines = ["**Antigravity models** — source: " + cat.source + (cat.lastError === void 0 ? "" : " — " + cat.lastError) + ":"];
32935
33180
  for (const m of cat.models) lines.push("- `" + m.id + "` — " + m.name + (m.efforts ? " — efforts: " + m.efforts.join(" / ") : ""));
32936
- return ok(lines.join("\n"));
33181
+ return ok$1(lines.join("\n"));
32937
33182
  }
32938
33183
  if (sub === "mode") {
32939
33184
  if (![
32940
33185
  "skip",
32941
33186
  "plan",
32942
33187
  "accept-edits"
32943
- ].includes(arg)) return err("usage: /agy mode <skip|plan|accept-edits>");
33188
+ ].includes(arg)) return err$1("usage: /agy mode <skip|plan|accept-edits>");
32944
33189
  deps.setOverride("permissionMode", arg);
32945
- return ok("Permission mode set to **" + arg + "** — effective next turn.");
33190
+ return ok$1("Permission mode set to **" + arg + "** — effective next turn.");
32946
33191
  }
32947
33192
  if (sub === "effort") {
32948
33193
  if (![
@@ -32950,14 +33195,14 @@ async function handle(deps, raw, invocation) {
32950
33195
  "medium",
32951
33196
  "high",
32952
33197
  "default"
32953
- ].includes(arg)) return err("usage: /agy effort <low|medium|high|default>");
33198
+ ].includes(arg)) return err$1("usage: /agy effort <low|medium|high|default>");
32954
33199
  deps.setOverride("defaultEffort", arg === "default" ? "" : arg);
32955
- return ok("Default effort set to **" + (arg === "default" ? "model default" : arg) + "**.");
33200
+ return ok$1("Default effort set to **" + (arg === "default" ? "model default" : arg) + "**.");
32956
33201
  }
32957
33202
  if (sub === "dispatch" || sub === "dispatch-retries") {
32958
33203
  const cfg = deps.cfg();
32959
33204
  const mutex = credentialSlotMutex;
32960
- if (arg === "") return ok([
33205
+ if (arg === "") return ok$1([
32961
33206
  "**Agy 派发守护(dispatch guards)**",
32962
33207
  `- 硬超时:**${cfg.dispatchTimeoutMinutes > 0 ? `${cfg.dispatchTimeoutMinutes} 分钟/次` : "不限时(无限等待)"}**(重试次数 ${cfg.dispatchRetries}${cfg.dispatchTimeoutMinutes > 0 ? `,总坚持 ≈ ${(1 + cfg.dispatchRetries) * cfg.dispatchTimeoutMinutes} 分钟` : ""})`,
32963
33208
  "- 同账号并行:**" + (cfg.parallelSameAccount ? "开(快路径,多会话并行跑同一账号)" : "关(同一时刻仅 1 个 agy 进程)") + "**",
@@ -32969,43 +33214,43 @@ async function handle(deps, raw, invocation) {
32969
33214
  if (sub === "dispatch") {
32970
33215
  if (arg === "off" || arg === "0") {
32971
33216
  deps.setOverride("dispatchTimeoutMinutes", 0);
32972
- return ok("派发硬超时已关闭:排队将无限等待(仍然 Stop 可停、轮询自愈、心跳可见)。");
33217
+ return ok$1("派发硬超时已关闭:排队将无限等待(仍然 Stop 可停、轮询自愈、心跳可见)。");
32973
33218
  }
32974
33219
  const minutes = Number(arg);
32975
- if (!Number.isFinite(minutes) || minutes <= 0 || !Number.isInteger(minutes)) return err("usage: /agy dispatch <分钟数|off>");
33220
+ if (!Number.isFinite(minutes) || minutes <= 0 || !Number.isInteger(minutes)) return err$1("usage: /agy dispatch <分钟数|off>");
32976
33221
  deps.setOverride("dispatchTimeoutMinutes", minutes);
32977
- return ok(`派发硬超时设为 **${minutes} 分钟/次**(含 ${cfg.dispatchRetries} 次重试,总坚持 ≈ ${(1 + cfg.dispatchRetries) * minutes} 分钟)— 下一个回合生效。`);
33222
+ return ok$1(`派发硬超时设为 **${minutes} 分钟/次**(含 ${cfg.dispatchRetries} 次重试,总坚持 ≈ ${(1 + cfg.dispatchRetries) * minutes} 分钟)— 下一个回合生效。`);
32978
33223
  }
32979
33224
  const retries = Number(arg);
32980
- if (!Number.isFinite(retries) || retries < 0 || !Number.isInteger(retries) || retries > 10) return err("usage: /agy dispatch-retries <0-10>");
33225
+ if (!Number.isFinite(retries) || retries < 0 || !Number.isInteger(retries) || retries > 10) return err$1("usage: /agy dispatch-retries <0-10>");
32981
33226
  deps.setOverride("dispatchRetries", retries);
32982
- return ok(`派发重试次数设为 **${retries}**${cfg.dispatchTimeoutMinutes > 0 ? `,总坚持 ≈ ${(1 + retries) * cfg.dispatchTimeoutMinutes} 分钟` : ""} — 下一个回合生效。`);
33227
+ return ok$1(`派发重试次数设为 **${retries}**${cfg.dispatchTimeoutMinutes > 0 ? `,总坚持 ≈ ${(1 + retries) * cfg.dispatchTimeoutMinutes} 分钟` : ""} — 下一个回合生效。`);
32983
33228
  }
32984
33229
  if (sub === "parallel") {
32985
- if (arg !== "on" && arg !== "off") return err("usage: /agy parallel <on|off>");
33230
+ if (arg !== "on" && arg !== "off") return err$1("usage: /agy parallel <on|off>");
32986
33231
  const on = arg === "on";
32987
33232
  deps.setOverride("parallelSameAccount", on);
32988
- return ok(on ? "同账号并行已**开启**:同一账号的多个会话立即并行跑 agy(无需独占凭据槽位),仅账号切换时串行 — 下一个回合生效。" : "同账号并行已**关闭**:恢复同一时刻仅 1 个 agy 进程(全串行)— 下一个回合生效。");
33233
+ return ok$1(on ? "同账号并行已**开启**:同一账号的多个会话立即并行跑 agy(无需独占凭据槽位),仅账号切换时串行 — 下一个回合生效。" : "同账号并行已**关闭**:恢复同一时刻仅 1 个 agy 进程(全串行)— 下一个回合生效。");
32989
33234
  }
32990
33235
  if (sub === "max-concurrent") {
32991
33236
  if (arg === "off" || arg === "0") {
32992
33237
  deps.setOverride("maxConcurrent", 0);
32993
- return ok("并发上限已移除:**不限制**(原生 agy 并发,Google 速率与账号冷却为天然调节)— 下一个回合生效。");
33238
+ return ok$1("并发上限已移除:**不限制**(原生 agy 并发,Google 速率与账号冷却为天然调节)— 下一个回合生效。");
32994
33239
  }
32995
33240
  const n = Number(arg);
32996
- if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1 || n > 64) return err("usage: /agy max-concurrent <1-64|off>");
33241
+ if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1 || n > 64) return err$1("usage: /agy max-concurrent <1-64|off>");
32997
33242
  deps.setOverride("maxConcurrent", n);
32998
- return ok(`并发上限设为 **${n}** 个请求流 — 下一个回合生效。`);
33243
+ return ok$1(`并发上限设为 **${n}** 个请求流 — 下一个回合生效。`);
32999
33244
  }
33000
33245
  if (sub === "workspace") {
33001
- if (arg === "") return ok("Current workspace: " + (deps.cfg().workspaceRoot !== "" ? deps.cfg().workspaceRoot : "(session cwd / process cwd)"));
33246
+ if (arg === "") return ok$1("Current workspace: " + (deps.cfg().workspaceRoot !== "" ? deps.cfg().workspaceRoot : "(session cwd / process cwd)"));
33002
33247
  if (arg === "default" || arg === "clear") {
33003
33248
  deps.setOverride("workspaceRoot", "");
33004
- return ok("Workspace reset to session cwd / process cwd.");
33249
+ return ok$1("Workspace reset to session cwd / process cwd.");
33005
33250
  }
33006
- if (!isAbsolute(arg)) return err("workspace must be an absolute path (or `default` to clear)");
33251
+ if (!isAbsolute(arg)) return err$1("workspace must be an absolute path (or `default` to clear)");
33007
33252
  deps.setOverride("workspaceRoot", arg);
33008
- return ok("Workspace set to **" + arg + "** — effective next turn.");
33253
+ return ok$1("Workspace set to **" + arg + "** — effective next turn.");
33009
33254
  }
33010
33255
  if (sub === "clear") {
33011
33256
  const sessionId = invocation?.agent?.id ? String(invocation.agent.id) : void 0;
@@ -33014,22 +33259,22 @@ async function handle(deps, raw, invocation) {
33014
33259
  const keys = Object.keys(bindings).filter((k) => k === sessionId || k.startsWith(`${sessionId}:`));
33015
33260
  if (keys.length > 0) {
33016
33261
  for (const k of keys) deps.store().delete(k);
33017
- return ok(`Dropped binding for session \`${sessionId}\`. The next turn starts a fresh agy conversation.`);
33262
+ return ok$1(`Dropped binding for session \`${sessionId}\`. The next turn starts a fresh agy conversation.`);
33018
33263
  }
33019
33264
  }
33020
33265
  const all = deps.store().all();
33021
33266
  const keys = Object.keys(all);
33022
- if (keys.length === 0) return ok("No conversation bindings yet.");
33267
+ if (keys.length === 0) return ok$1("No conversation bindings yet.");
33023
33268
  const key = keys.reduce((a, b) => (all[a]?.updatedAt ?? 0) >= (all[b]?.updatedAt ?? 0) ? a : b);
33024
33269
  const dropped = all[key];
33025
- if (dropped === void 0) return ok("No conversation bindings yet.");
33270
+ if (dropped === void 0) return ok$1("No conversation bindings yet.");
33026
33271
  deps.store().delete(key);
33027
- return ok("Dropped binding for session `" + key + "` — agy conversation " + dropped.conversationId + ". The next turn starts a fresh agy conversation.");
33272
+ return ok$1("Dropped binding for session `" + key + "` — agy conversation " + dropped.conversationId + ". The next turn starts a fresh agy conversation.");
33028
33273
  }
33029
- if (sub === "doctor") return ok("Diagnostic report written to `" + await deps.runDoctor() + "` — attach it when opening an issue.");
33030
- return ok(HELP);
33274
+ if (sub === "doctor") return ok$1("Diagnostic report written to `" + await deps.runDoctor() + "` — attach it when opening an issue.");
33275
+ return ok$1(HELP$1);
33031
33276
  } catch (e) {
33032
- return err(e instanceof Error ? e.message : String(e));
33277
+ return err$1(e instanceof Error ? e.message : String(e));
33033
33278
  }
33034
33279
  }
33035
33280
  async function renderStatus(deps) {
@@ -33068,6 +33313,845 @@ async function renderStatus(deps) {
33068
33313
  ] : []
33069
33314
  ].join("\n");
33070
33315
  }
33316
+ function ok$1(text) {
33317
+ return {
33318
+ kind: "success",
33319
+ text
33320
+ };
33321
+ }
33322
+ function err$1(text) {
33323
+ return {
33324
+ kind: "error",
33325
+ text
33326
+ };
33327
+ }
33328
+ //#endregion
33329
+ //#region src/host/translate.ts
33330
+ /** Durable record type written to the session log (grammar: `plugin:` + lowercase segments). */
33331
+ const TRANSLATION_RECORD_TYPE = "plugin:agy-link/translation";
33332
+ /** Bounded in-memory cache: one entry per (model, effort, language, source text). */
33333
+ const MAX_CACHE_ENTRIES = 200;
33334
+ /** Reasonable lower bound for a translated answer; keeps a runaway model from filling the card. */
33335
+ const MIN_TEXT_LIMIT = 200;
33336
+ /**
33337
+ * The block agy receives ONCE, when its translation conversation is created:
33338
+ * who it is, which DSH session it serves, where that session's history lives and
33339
+ * how to read it, plus a bounded digest so the first translation already has
33340
+ * context. Later translations send only the source text (see the adapter's
33341
+ * `agyTranslateSession` handling).
33342
+ */
33343
+ function buildTranslationSetup(input) {
33344
+ const lang = input.targetLanguage.trim() === "" ? "中文(简体)" : input.targetLanguage.trim();
33345
+ const lines = [
33346
+ "你是「人话翻译器」,长期服务于 DSH 的一个会话。以后我只把需要翻译的原文发给你,你直接把它讲成人话。",
33347
+ "",
33348
+ "- DSH 会话 id:" + (input.sessionId === "" ? "(未知)" : input.sessionId)
33349
+ ];
33350
+ if (input.cwd !== void 0 && input.cwd !== "") lines.push("- 该会话的工作目录:" + input.cwd);
33351
+ if (input.digest !== void 0 && input.digest.trim() !== "") lines.push("", "该会话到目前为止的摘要(供你理解上下文,不必翻译它):", "", "<digest>", input.digest.trim(), "</digest>");
33352
+ if (input.logPath !== void 0 && input.logPath !== "") lines.push("", "需要完整历史时可以自己读:原始日志在 " + input.logPath + "(zstd 压缩的 JSONL,每行一个事件)。读取示例:", " zstd -dc '" + input.logPath + "' | jq -c 'select(.type==\"assistant/message\") | {turn:.data.turn, text:([.data.message.content[]?.text] | join(\"\"))}' | tail -40", "没有 jq 就用 python3 逐行 json.loads 过滤;不要修改这些文件。");
33353
+ lines.push("", "规则:", "1. 说" + lang + "的大白话、短句,别用行话和缩写;别写标题、别分点列条目;别改原意、别加原文没有的内容。", "2. 只输出讲解本身,不要前言、不要复述我发的内容、不要问我问题。", "3. 默认直接翻译我发的这段文字;需要上下文时可以读上面的摘要或日志文件。");
33354
+ return lines.join("\n");
33355
+ }
33356
+ /** Read the event log whichever shape the host exposes. */
33357
+ function sessionEvents(session) {
33358
+ if (!session) return [];
33359
+ if (typeof session.snapshotEvents === "function") try {
33360
+ const list = session.snapshotEvents();
33361
+ if (Array.isArray(list) && list.length > 0) return list;
33362
+ } catch {}
33363
+ if (typeof session.ownEvents === "function") try {
33364
+ const list = session.ownEvents();
33365
+ if (Array.isArray(list) && list.length > 0) return list;
33366
+ } catch {}
33367
+ if (Array.isArray(session.log) && session.log.length > 0) return session.log;
33368
+ if (Array.isArray(session.events) && session.events.length > 0) return session.events;
33369
+ if (Array.isArray(session.log)) return session.log;
33370
+ if (Array.isArray(session.events)) return session.events;
33371
+ return [];
33372
+ }
33373
+ function dataOf(ev) {
33374
+ const data = ev.data;
33375
+ return data !== null && typeof data === "object" ? data : {};
33376
+ }
33377
+ function num$1(v) {
33378
+ return typeof v === "number" && Number.isFinite(v) ? v : void 0;
33379
+ }
33380
+ /** Turns that finished with a normal `completed` reason, ascending. */
33381
+ function completedTurns(events) {
33382
+ const turns = [];
33383
+ for (const ev of events) {
33384
+ if (ev.type !== "turn/end") continue;
33385
+ const d = dataOf(ev);
33386
+ if ((d.reason !== null && typeof d.reason === "object" ? d.reason : {}).kind !== "completed") continue;
33387
+ const turn = num$1(d.turn);
33388
+ if (turn !== void 0) turns.push(turn);
33389
+ }
33390
+ return turns;
33391
+ }
33392
+ function lastCompletedTurn(events) {
33393
+ const turns = completedTurns(events);
33394
+ return turns.length === 0 ? null : turns[turns.length - 1];
33395
+ }
33396
+ /** True when `turn` has no `turn/end` yet (its agent loop is still running). */
33397
+ function isTurnRunning(events, turn) {
33398
+ let started = false;
33399
+ for (const ev of events) {
33400
+ const d = dataOf(ev);
33401
+ if (ev.type === "turn/start" && num$1(d.turn) === turn) started = true;
33402
+ if (ev.type === "turn/end" && num$1(d.turn) === turn) return false;
33403
+ }
33404
+ return started;
33405
+ }
33406
+ function textOfAssistant(ev) {
33407
+ const d = dataOf(ev);
33408
+ const message = d.message !== null && typeof d.message === "object" ? d.message : {};
33409
+ const content = Array.isArray(message.content) ? message.content : [];
33410
+ const parts = [];
33411
+ for (const block of content) {
33412
+ if (block === null || typeof block !== "object") continue;
33413
+ const b = block;
33414
+ if (b.type === "text" && typeof b.text === "string" && b.text.trim() !== "") parts.push(b.text);
33415
+ }
33416
+ return parts.join("\n").trim();
33417
+ }
33418
+ function sourceModelOf(ev) {
33419
+ const d = dataOf(ev);
33420
+ const message = d.message !== null && typeof d.message === "object" ? d.message : {};
33421
+ const source = message.source !== null && typeof message.source === "object" ? message.source : {};
33422
+ return typeof source.model === "string" && source.model !== "" ? source.model : void 0;
33423
+ }
33424
+ function messageIdOf(ev) {
33425
+ const d = dataOf(ev);
33426
+ const message = d.message !== null && typeof d.message === "object" ? d.message : {};
33427
+ if (typeof message.id === "string" && message.id !== "") return message.id;
33428
+ if (typeof d.id === "string" && d.id !== "") return d.id;
33429
+ if (typeof d.messageId === "string" && d.messageId !== "") return d.messageId;
33430
+ const raw = ev;
33431
+ return typeof raw.id === "string" && raw.id !== "" ? raw.id : void 0;
33432
+ }
33433
+ /**
33434
+ * The turn's final answer: the last assistant message with non-empty text.
33435
+ * Intermediate steps that only emit tool calls carry no text, so they are
33436
+ * skipped — translating them would bury the real answer in noise.
33437
+ */
33438
+ function finalAnswerOfTurn(events, turn) {
33439
+ let found = null;
33440
+ for (const ev of events) {
33441
+ if (ev.type !== "assistant/message") continue;
33442
+ if (num$1(dataOf(ev).turn) !== turn) continue;
33443
+ const text = textOfAssistant(ev);
33444
+ if (text === "") continue;
33445
+ found = {
33446
+ text,
33447
+ anchorSeq: num$1(ev.seq) ?? 0,
33448
+ ...messageIdOf(ev) === void 0 ? {} : { messageId: messageIdOf(ev) },
33449
+ ...sourceModelOf(ev) === void 0 ? {} : { sourceModel: sourceModelOf(ev) }
33450
+ };
33451
+ }
33452
+ return found;
33453
+ }
33454
+ /** Every assistant text block of a turn, in order (for `/tsl --full`). */
33455
+ function allTextOfTurn(events, turn) {
33456
+ const parts = [];
33457
+ let anchorSeq = 0;
33458
+ let messageId;
33459
+ let sourceModel;
33460
+ for (const ev of events) {
33461
+ if (ev.type !== "assistant/message") continue;
33462
+ if (num$1(dataOf(ev).turn) !== turn) continue;
33463
+ const text = textOfAssistant(ev);
33464
+ if (text === "") continue;
33465
+ parts.push(text);
33466
+ anchorSeq = num$1(ev.seq) ?? anchorSeq;
33467
+ messageId = messageIdOf(ev) ?? messageId;
33468
+ sourceModel = sourceModelOf(ev) ?? sourceModel;
33469
+ }
33470
+ if (parts.length === 0) return null;
33471
+ return {
33472
+ text: parts.join("\n\n"),
33473
+ anchorSeq,
33474
+ ...messageId === void 0 ? {} : { messageId },
33475
+ ...sourceModel === void 0 ? {} : { sourceModel }
33476
+ };
33477
+ }
33478
+ /** Locate the turn that owns one assistant message id. */
33479
+ function turnOfMessage(events, messageId) {
33480
+ for (const ev of events) {
33481
+ if (ev.type !== "assistant/message") continue;
33482
+ if (messageIdOf(ev) !== messageId) continue;
33483
+ const turn = num$1(dataOf(ev).turn);
33484
+ if (turn === void 0) return null;
33485
+ return {
33486
+ text: textOfAssistant(ev),
33487
+ anchorSeq: num$1(ev.seq) ?? 0,
33488
+ turn,
33489
+ ...messageIdOf(ev) === void 0 ? {} : { messageId: messageIdOf(ev) },
33490
+ ...sourceModelOf(ev) === void 0 ? {} : { sourceModel: sourceModelOf(ev) }
33491
+ };
33492
+ }
33493
+ return null;
33494
+ }
33495
+ /**
33496
+ * The newest durable translation record for one turn (optionally narrowed to an
33497
+ * exact model/effort recipe). Used to dedupe repeated requests so clicking the
33498
+ * per-turn affordance twice can never stack two identical cards.
33499
+ */
33500
+ function findTranslationRecord(events, turn, model, effort) {
33501
+ let found = null;
33502
+ for (const ev of events) {
33503
+ if (ev.type !== "plugin:agy-link/translation") continue;
33504
+ const d = dataOf(ev);
33505
+ if (num$1(d.turn) !== turn) continue;
33506
+ const recordModel = typeof d.model === "string" ? d.model : "";
33507
+ const recordEffort = typeof d.effort === "string" ? d.effort : "";
33508
+ if (model !== void 0 && model !== "" && recordModel !== model) continue;
33509
+ if (effort !== void 0 && recordEffort !== effort) continue;
33510
+ const text = typeof d.text === "string" ? d.text : "";
33511
+ if (text.trim() === "") continue;
33512
+ found = {
33513
+ seq: num$1(ev.seq) ?? 0,
33514
+ text,
33515
+ model: recordModel,
33516
+ effort: recordEffort
33517
+ };
33518
+ }
33519
+ return found;
33520
+ }
33521
+ /** Text of one `user/message` event (the asks that carry the thread). */
33522
+ function userTextOf(ev) {
33523
+ const d = dataOf(ev);
33524
+ const message = d.message !== null && typeof d.message === "object" ? d.message : {};
33525
+ return (Array.isArray(message.content) ? message.content : []).filter((b) => b.type === "text" && typeof b.text === "string").map((b) => String(b.text)).join("\n");
33526
+ }
33527
+ /**
33528
+ * A bounded "what happened so far" digest for the setup block: the session's asks
33529
+ * and final answers, newest kept, each clipped. The full log stays on disk for
33530
+ * agy to read itself when it wants more.
33531
+ */
33532
+ function sessionDigest(events, maxChars) {
33533
+ const cap = Math.max(200, Math.round(maxChars / 4));
33534
+ const parts = [];
33535
+ const done = /* @__PURE__ */ new Set();
33536
+ for (const ev of events) {
33537
+ if (ev.type === "user/message") {
33538
+ const text = userTextOf(ev).trim();
33539
+ if (text !== "") parts.push("用户:" + clip(text, 400));
33540
+ continue;
33541
+ }
33542
+ if (ev.type !== "assistant/message") continue;
33543
+ const turn = num$1(dataOf(ev).turn);
33544
+ if (turn === void 0 || done.has(turn)) continue;
33545
+ const answer = finalAnswerOfTurn(events, turn);
33546
+ if (answer === null || answer.text.trim() === "") continue;
33547
+ done.add(turn);
33548
+ parts.push("回复:" + clip(answer.text, 900));
33549
+ }
33550
+ let kept = "";
33551
+ for (let i = parts.length - 1; i >= 0; i--) {
33552
+ const next = parts[i] + "\n" + kept;
33553
+ if (next.length > cap) break;
33554
+ kept = next;
33555
+ }
33556
+ return kept.trim();
33557
+ }
33558
+ function clip(text, max) {
33559
+ const flat = text.replace(/\s+/g, " ").trim();
33560
+ return flat.length <= max ? flat : flat.slice(0, max) + "…";
33561
+ }
33562
+ /** The translator instruction. Kept in the user message (aux calls drop
33563
+ * `options.system` unless `forwardSystemPrompt` is on), and deliberately
33564
+ * explicit about "never invent facts": a cheerful paraphrase that adds a
33565
+ * promise the agent never made is worse than no translation at all.
33566
+ */
33567
+ function buildTranslationPrompt(text, targetLanguage, maxChars) {
33568
+ const lang = targetLanguage.trim() === "" ? "中文(简体)" : targetLanguage.trim();
33569
+ const limit = Math.max(MIN_TEXT_LIMIT, Math.round(maxChars));
33570
+ const long = text.length > Math.min(2e3, Math.floor(limit / 4));
33571
+ return [
33572
+ "用" + lang + "把下面这段内容通俗易懂地讲一遍,就像跟同事随口解释一样:用大白话、短句,别用行话和缩写,别写标题或分点列表,别改原意、别加原文没有的内容。",
33573
+ ...long ? ["原文有点长,挑重点讲清楚就行,没提到的细节不用硬补。"] : [],
33574
+ "只输出这段讲解本身。",
33575
+ "",
33576
+ "<content>",
33577
+ text,
33578
+ "</content>"
33579
+ ].join("\n");
33580
+ }
33581
+ /**
33582
+ * Split long answers on paragraph boundaries. A single paragraph longer than
33583
+ * the cap is hard-split so one giant code block cannot blow the request limit.
33584
+ */
33585
+ function chunkText(text, maxChars) {
33586
+ const cap = Math.max(MIN_TEXT_LIMIT, Math.round(maxChars));
33587
+ if (text.length <= cap) return [text];
33588
+ const chunks = [];
33589
+ let current = "";
33590
+ for (const para of text.split(/\n{2,}/)) {
33591
+ const piece = para.trim();
33592
+ if (piece === "") continue;
33593
+ if (piece.length > cap) {
33594
+ if (current !== "") {
33595
+ chunks.push(current);
33596
+ current = "";
33597
+ }
33598
+ for (let i = 0; i < piece.length; i += cap) chunks.push(piece.slice(i, i + cap));
33599
+ continue;
33600
+ }
33601
+ const next = current === "" ? piece : current + "\n\n" + piece;
33602
+ if (next.length > cap) {
33603
+ chunks.push(current);
33604
+ current = piece;
33605
+ } else current = next;
33606
+ }
33607
+ if (current !== "") chunks.push(current);
33608
+ return chunks.length === 0 ? [text] : chunks;
33609
+ }
33610
+ /**
33611
+ * Pick the model/effort for a translation.
33612
+ *
33613
+ * An explicit request (command flag) is honoured even when the advisory catalog
33614
+ * has never listed it — the adapter accepts unknown ids. The DEFAULT goes
33615
+ * through a fallback chain so a plan without Gemini 3.8 still translates:
33616
+ * `gemini-3.8-flash` → newest `gemini-*-flash` → `defaultModel` → first model.
33617
+ */
33618
+ function resolveTranslateTarget(cfg, catalog, override) {
33619
+ const requested = (override?.model ?? cfg.translateModel ?? "").trim();
33620
+ const models = catalog.models;
33621
+ let model = "";
33622
+ let entry = requested === "" ? void 0 : findEntry(catalog, requested);
33623
+ if (requested !== "" && entry !== void 0) model = entry.id;
33624
+ else if (requested !== "" && override?.model !== void 0) {
33625
+ model = resolveModelSlug(requested);
33626
+ entry = findEntry(catalog, model);
33627
+ } else {
33628
+ const candidates = ["gemini-3.8-flash"];
33629
+ if (cfg.defaultModel !== "") candidates.push(cfg.defaultModel);
33630
+ for (const cand of candidates) {
33631
+ const found = findEntry(catalog, cand);
33632
+ if (found !== void 0) {
33633
+ model = found.id;
33634
+ entry = found;
33635
+ break;
33636
+ }
33637
+ }
33638
+ if (model === "") {
33639
+ const newest = models.filter((m) => /gemini/i.test(m.id) && /flash/i.test(m.id)).sort((a, b) => compareNatural(b.id, a.id))[0] ?? models[0];
33640
+ if (newest !== void 0) {
33641
+ model = newest.id;
33642
+ entry = newest;
33643
+ }
33644
+ }
33645
+ }
33646
+ const wanted = (override?.effort ?? cfg.translateEffort ?? "").trim();
33647
+ let effort = "";
33648
+ if (entry !== void 0 && Array.isArray(entry.efforts) && entry.efforts.length > 0) effort = wanted !== "" && entry.efforts.includes(wanted) ? wanted : defaultEffortFor({
33649
+ ...entry,
33650
+ efforts: entry.efforts
33651
+ }, cfg) ?? "";
33652
+ return {
33653
+ model,
33654
+ effort
33655
+ };
33656
+ }
33657
+ function compareNatural(a, b) {
33658
+ const na = a.split(/(\d+)/);
33659
+ const nb = b.split(/(\d+)/);
33660
+ for (let i = 0; i < Math.max(na.length, nb.length); i++) {
33661
+ const x = na[i] ?? "";
33662
+ const y = nb[i] ?? "";
33663
+ const xn = Number(x);
33664
+ const yn = Number(y);
33665
+ if (Number.isFinite(xn) && Number.isFinite(yn) && x !== "" && y !== "") {
33666
+ if (xn !== yn) return xn - yn;
33667
+ } else if (x !== y) return x < y ? -1 : 1;
33668
+ }
33669
+ return 0;
33670
+ }
33671
+ /** Codes worth another attempt on a (probably) different account. */
33672
+ const RETRYABLE_CODES = /* @__PURE__ */ new Set([
33673
+ Err.RATE_LIMIT,
33674
+ Err.QUOTA,
33675
+ Err.NETWORK,
33676
+ Err.OVERLOADED,
33677
+ Err.ELIGIBILITY,
33678
+ Err.AUTH,
33679
+ Err.TIMEOUT,
33680
+ Err.PROCESS_EXIT,
33681
+ Err.EMPTY_RESPONSE
33682
+ ]);
33683
+ function failureText(code, message) {
33684
+ if (message !== void 0 && message.trim() !== "") return message;
33685
+ switch (code) {
33686
+ case Err.AGY_NOT_INSTALLED: return "agy binary not found — install it via https://antigravity.google/docs/cli/install";
33687
+ case Err.AUTH: return "agy is not signed in — run /agy auth";
33688
+ case Err.AUX_DISABLED: return "auxiliary calls are disabled for the antigravity route (allowAuxiliary: false)";
33689
+ case Err.RATE_LIMIT:
33690
+ case Err.QUOTA: return "Antigravity quota exhausted on every available account";
33691
+ case Err.EMPTY_RESPONSE: return "the model returned nothing this time — retry";
33692
+ default: return "translation failed";
33693
+ }
33694
+ }
33695
+ function mapCode(raw) {
33696
+ if (raw === Err.RATE_LIMIT || raw === Err.QUOTA) return "NO_ACCOUNT";
33697
+ if (raw === Err.AUTH || raw === Err.NETWORK || raw === Err.ELIGIBILITY) return "AGY_ERROR";
33698
+ if (raw === Err.TIMEOUT) return "TIMEOUT";
33699
+ if (raw === "ABORTED") return "ABORTED";
33700
+ if (raw === Err.AUX_DISABLED) return "AUX_DISABLED";
33701
+ return "AGY_ERROR";
33702
+ }
33703
+ function emptyResult(model, effort) {
33704
+ return {
33705
+ ok: false,
33706
+ text: "",
33707
+ model,
33708
+ effort,
33709
+ cached: false,
33710
+ durationMs: 0
33711
+ };
33712
+ }
33713
+ function delay(ms, signal) {
33714
+ if (ms <= 0) return Promise.resolve();
33715
+ return new Promise((resolve) => {
33716
+ const timer = setTimeout(() => {
33717
+ signal?.removeEventListener("abort", onAbort);
33718
+ resolve();
33719
+ }, ms);
33720
+ const onAbort = () => {
33721
+ clearTimeout(timer);
33722
+ resolve();
33723
+ };
33724
+ signal?.addEventListener("abort", onAbort, { once: true });
33725
+ });
33726
+ }
33727
+ /**
33728
+ * Orchestrates translation: target resolution, chunking, caching, bounded
33729
+ * retry, optional durable record. Session text extraction lives above as pure
33730
+ * functions so the command, the auto hook and the button share one logic.
33731
+ */
33732
+ var TranslationService = class {
33733
+ deps;
33734
+ cache = /* @__PURE__ */ new Map();
33735
+ inflight = /* @__PURE__ */ new Map();
33736
+ pending = /* @__PURE__ */ new Map();
33737
+ lastAutoAt = /* @__PURE__ */ new Map();
33738
+ last = null;
33739
+ count = 0;
33740
+ cacheHits = 0;
33741
+ constructor(deps) {
33742
+ this.deps = deps;
33743
+ }
33744
+ now() {
33745
+ return this.deps.now?.() ?? Date.now();
33746
+ }
33747
+ target(override) {
33748
+ return resolveTranslateTarget(this.deps.cfg(), this.deps.catalog(), override);
33749
+ }
33750
+ stats() {
33751
+ return {
33752
+ count: this.count,
33753
+ cacheHits: this.cacheHits,
33754
+ last: this.last
33755
+ };
33756
+ }
33757
+ pendingFor(sessionId) {
33758
+ if (sessionId !== void 0) {
33759
+ const one = this.pending.get(sessionId);
33760
+ return one === void 0 ? [] : [one];
33761
+ }
33762
+ return [...this.pending.values()];
33763
+ }
33764
+ /** Translate arbitrary text (the shared code path every entry uses). */
33765
+ async translate(req, signal) {
33766
+ const text = req.text ?? "";
33767
+ const target = this.target({
33768
+ ...req.model === void 0 ? {} : { model: req.model },
33769
+ ...req.effort === void 0 ? {} : { effort: req.effort }
33770
+ });
33771
+ if (text.trim() === "") return {
33772
+ ...emptyResult(target.model, target.effort),
33773
+ error: "nothing to translate",
33774
+ code: "EMPTY_TEXT"
33775
+ };
33776
+ const language = req.targetLanguage ?? this.deps.cfg().translateTargetLanguage;
33777
+ const key = cacheKey(target.model, target.effort, language, text);
33778
+ if (req.force !== true) {
33779
+ const hit = this.cache.get(key);
33780
+ if (hit !== void 0) {
33781
+ this.cacheHits++;
33782
+ this.last = {
33783
+ ...hit,
33784
+ cached: true
33785
+ };
33786
+ return this.last;
33787
+ }
33788
+ const running = this.inflight.get(key);
33789
+ if (running !== void 0) return running;
33790
+ }
33791
+ const task = this.runChunked(text, target, language, signal, req.sessionId).finally(() => {
33792
+ this.inflight.delete(key);
33793
+ });
33794
+ this.inflight.set(key, task);
33795
+ return task;
33796
+ }
33797
+ async runChunked(text, target, language, signal, sessionId) {
33798
+ const cfg = this.deps.cfg();
33799
+ const startedAt = this.now();
33800
+ const chunks = chunkText(text, cfg.translateMaxChars);
33801
+ const out = [];
33802
+ let accountId;
33803
+ const setupEvents = sessionId === void 0 ? [] : sessionEvents(this.deps.getSession(sessionId));
33804
+ for (const chunk of chunks) {
33805
+ const res = await this.withRetry({
33806
+ prompt: buildTranslationPrompt(chunk, language, cfg.translateMaxChars),
33807
+ text: chunk,
33808
+ setup: sessionId === void 0 ? void 0 : this.setupFor(sessionId, language, setupEvents),
33809
+ ...sessionId === void 0 ? {} : { sessionId },
33810
+ model: target.model,
33811
+ ...target.effort === "" ? {} : { effort: target.effort },
33812
+ maxTokens: cfg.translateMaxTokens,
33813
+ timeoutMs: cfg.translateTimeoutMs,
33814
+ ...signal === void 0 ? {} : { signal }
33815
+ }, cfg.translateRetries, signal);
33816
+ if (!res.ok) {
33817
+ const result = {
33818
+ ok: false,
33819
+ text: out.join("\n\n---\n\n"),
33820
+ model: target.model,
33821
+ effort: target.effort,
33822
+ cached: false,
33823
+ durationMs: this.now() - startedAt,
33824
+ error: failureText(res.code, res.error),
33825
+ code: mapCode(res.code)
33826
+ };
33827
+ this.last = result;
33828
+ return result;
33829
+ }
33830
+ if (res.accountId !== void 0) accountId = res.accountId;
33831
+ out.push(res.text.trim());
33832
+ }
33833
+ const result = {
33834
+ ok: true,
33835
+ text: out.join("\n\n---\n\n"),
33836
+ model: target.model,
33837
+ effort: target.effort,
33838
+ cached: false,
33839
+ durationMs: this.now() - startedAt,
33840
+ ...accountId === void 0 ? {} : { accountId }
33841
+ };
33842
+ this.count++;
33843
+ this.remember(cacheKey(target.model, target.effort, language, text), { ...result });
33844
+ this.last = result;
33845
+ return result;
33846
+ }
33847
+ remember(key, result) {
33848
+ this.cache.set(key, result);
33849
+ while (this.cache.size > MAX_CACHE_ENTRIES) {
33850
+ const oldest = this.cache.keys().next();
33851
+ if (oldest.done === true) break;
33852
+ this.cache.delete(oldest.value);
33853
+ }
33854
+ }
33855
+ async withRetry(req, retries, signal) {
33856
+ const max = Math.max(0, Math.round(retries));
33857
+ let last = {
33858
+ ok: false,
33859
+ text: "",
33860
+ error: "translation was never attempted",
33861
+ code: Err.AGY_ERROR
33862
+ };
33863
+ for (let attempt = 0; attempt <= max; attempt++) {
33864
+ if (signal?.aborted === true) {
33865
+ last = {
33866
+ ok: false,
33867
+ text: "",
33868
+ error: "aborted",
33869
+ code: "ABORTED"
33870
+ };
33871
+ break;
33872
+ }
33873
+ try {
33874
+ last = await this.deps.run(req);
33875
+ } catch (e) {
33876
+ last = {
33877
+ ok: false,
33878
+ text: "",
33879
+ error: e instanceof Error ? e.message : String(e),
33880
+ code: Err.AGY_ERROR
33881
+ };
33882
+ }
33883
+ if (last.ok) return last;
33884
+ if (last.code === "ABORTED" || last.code !== void 0 && !RETRYABLE_CODES.has(last.code)) break;
33885
+ const pause = last.code === Err.EMPTY_RESPONSE ? 900 * (attempt + 1) : 150 * (attempt + 1);
33886
+ if (attempt < max) await delay(pause, signal);
33887
+ }
33888
+ return last;
33889
+ }
33890
+ /**
33891
+ * Persona block for one DSH session's translation conversation. Built on every
33892
+ * request (pure and cheap) but only USED when that conversation is created, so
33893
+ * a conversation that was lost re-seeds itself with fresh context.
33894
+ */
33895
+ setupFor(sessionId, language, events) {
33896
+ const cwd = this.deps.sessionCwd?.(sessionId);
33897
+ const logPath = this.deps.sessionLogPath?.(sessionId);
33898
+ const digest = sessionDigest(events, this.deps.cfg().translateMaxChars);
33899
+ return buildTranslationSetup({
33900
+ sessionId,
33901
+ targetLanguage: language,
33902
+ ...cwd === void 0 || cwd === "" ? {} : { cwd },
33903
+ ...logPath === void 0 || logPath === "" ? {} : { logPath },
33904
+ ...digest === "" ? {} : { digest }
33905
+ });
33906
+ }
33907
+ /** Translate one turn of a session and (optionally) persist the card record. */
33908
+ async translateTurn(sessionId, turn, opts = {}, signal) {
33909
+ const session = this.deps.getSession(sessionId);
33910
+ const events = sessionEvents(session);
33911
+ if (session === void 0 || events.length === 0) {
33912
+ const target = this.target(opts);
33913
+ return {
33914
+ ...emptyResult(target.model, target.effort),
33915
+ error: "session is not available",
33916
+ code: "SESSION_UNAVAILABLE"
33917
+ };
33918
+ }
33919
+ if (isTurnRunning(events, turn)) {
33920
+ const target = this.target(opts);
33921
+ return {
33922
+ ...emptyResult(target.model, target.effort),
33923
+ error: "the current turn is still running",
33924
+ code: "TRANSIENT"
33925
+ };
33926
+ }
33927
+ const target = this.target(opts);
33928
+ if (opts.force !== true) {
33929
+ const existing = findTranslationRecord(events, turn, target.model, target.effort);
33930
+ if (existing !== null) return {
33931
+ ok: true,
33932
+ text: existing.text,
33933
+ model: existing.model === "" ? target.model : existing.model,
33934
+ effort: existing.effort,
33935
+ cached: true,
33936
+ durationMs: 0,
33937
+ recordSeq: existing.seq,
33938
+ turn
33939
+ };
33940
+ }
33941
+ const answer = opts.full === true ? allTextOfTurn(events, turn) : finalAnswerOfTurn(events, turn);
33942
+ if (answer === null || answer.text.trim() === "") return {
33943
+ ...emptyResult(target.model, target.effort),
33944
+ error: "no assistant text in turn " + turn,
33945
+ code: "TURN_NOT_FOUND"
33946
+ };
33947
+ const res = await this.translate({
33948
+ text: answer.text,
33949
+ sessionId,
33950
+ ...opts.model === void 0 ? {} : { model: opts.model },
33951
+ ...opts.effort === void 0 ? {} : { effort: opts.effort },
33952
+ ...opts.targetLanguage === void 0 ? {} : { targetLanguage: opts.targetLanguage },
33953
+ ...opts.force === void 0 ? {} : { force: opts.force }
33954
+ }, signal);
33955
+ res.turn = turn;
33956
+ if (res.ok && opts.persist !== false) res.recordSeq = await this.appendRecord(sessionId, turn, answer, res);
33957
+ return res;
33958
+ }
33959
+ /** Durable translation already stored for one turn (status route / chip). */
33960
+ existingTurn(sessionId, turn, model, effort) {
33961
+ return findTranslationRecord(sessionEvents(this.deps.getSession(sessionId)), turn, model, effort);
33962
+ }
33963
+ /**
33964
+ * Durable translation already stored for the turn that owns one assistant
33965
+ * message. The per-reply button asks this on mount, so a finished
33966
+ * translation still shows as "done" after a remount, a window switch or a
33967
+ * page reload — the card lives in the session, so the affordance reads its
33968
+ * state from the session too.
33969
+ */
33970
+ existingMessage(sessionId, messageId) {
33971
+ const events = sessionEvents(this.deps.getSession(sessionId));
33972
+ for (const ev of events) {
33973
+ if (ev.type !== "plugin:agy-link/translation") continue;
33974
+ const d = dataOf(ev);
33975
+ if (d.messageId !== messageId) continue;
33976
+ const text = typeof d.text === "string" ? d.text : "";
33977
+ if (text.trim() === "") continue;
33978
+ return {
33979
+ seq: num$1(ev.seq) ?? 0,
33980
+ text,
33981
+ model: typeof d.model === "string" ? d.model : "",
33982
+ effort: typeof d.effort === "string" ? d.effort : ""
33983
+ };
33984
+ }
33985
+ const located = turnOfMessage(events, messageId);
33986
+ if (located === null) return null;
33987
+ return findTranslationRecord(events, located.turn);
33988
+ }
33989
+ /** True while a translation is running for this session. */
33990
+ isPending(sessionId) {
33991
+ return this.pending.has(sessionId);
33992
+ }
33993
+ /** Translate the newest completed turn of a session. */
33994
+ async translateLastTurn(sessionId, opts = {}, signal) {
33995
+ const turn = lastCompletedTurn(sessionEvents(this.deps.getSession(sessionId)));
33996
+ if (turn === null) {
33997
+ const target = this.target(opts);
33998
+ return {
33999
+ ...emptyResult(target.model, target.effort),
34000
+ error: "no completed turn in this session",
34001
+ code: "TURN_NOT_FOUND"
34002
+ };
34003
+ }
34004
+ return this.translateTurn(sessionId, turn, opts, signal);
34005
+ }
34006
+ /** Translate the turn that owns one assistant message (history button). */
34007
+ async translateMessage(sessionId, messageId, opts = {}, signal) {
34008
+ const events = sessionEvents(this.deps.getSession(sessionId));
34009
+ if (events.length === 0) {
34010
+ const target = this.target(opts);
34011
+ return {
34012
+ ...emptyResult(target.model, target.effort),
34013
+ error: "session is not available",
34014
+ code: "SESSION_UNAVAILABLE"
34015
+ };
34016
+ }
34017
+ const located = turnOfMessage(events, messageId);
34018
+ if (located === null) {
34019
+ const last = lastCompletedTurn(events);
34020
+ if (last !== null) return this.translateTurn(sessionId, last, {
34021
+ ...opts,
34022
+ full: false
34023
+ }, signal);
34024
+ const target = this.target(opts);
34025
+ return {
34026
+ ...emptyResult(target.model, target.effort),
34027
+ error: "message not found in this session",
34028
+ code: "MESSAGE_NOT_FOUND"
34029
+ };
34030
+ }
34031
+ return this.translateTurn(sessionId, located.turn, {
34032
+ ...opts,
34033
+ full: false
34034
+ }, signal);
34035
+ }
34036
+ /**
34037
+ * Automatic post-turn translation. Returns the result (or null when the
34038
+ * guards skip this turn) and never throws: a failed translation must not
34039
+ * disturb the agent loop that just finished.
34040
+ */
34041
+ async autoTranslateTurn(sessionId, turn) {
34042
+ const cfg = this.deps.cfg();
34043
+ if (!(this.deps.autoEnabled?.(sessionId) ?? cfg.autoTranslate)) return null;
34044
+ const answer = finalAnswerOfTurn(sessionEvents(this.deps.getSession(sessionId)), turn);
34045
+ if (answer === null) return null;
34046
+ const target = this.target();
34047
+ if (cfg.translateSkipSameModel && answer.sourceModel !== void 0 && sameModel(answer.sourceModel, target.model)) return null;
34048
+ const lastAt = this.lastAutoAt.get(sessionId);
34049
+ const now = this.now();
34050
+ if (lastAt !== void 0 && cfg.translateMinIntervalMs > 0 && now - lastAt < cfg.translateMinIntervalMs) return null;
34051
+ this.lastAutoAt.set(sessionId, now);
34052
+ this.pending.set(sessionId, {
34053
+ turn,
34054
+ startedAt: now
34055
+ });
34056
+ try {
34057
+ return await this.translateTurn(sessionId, turn, { persist: true });
34058
+ } catch (e) {
34059
+ this.deps.log?.("auto-translate failed: " + (e instanceof Error ? e.message : String(e)));
34060
+ return null;
34061
+ } finally {
34062
+ this.pending.delete(sessionId);
34063
+ }
34064
+ }
34065
+ async appendRecord(sessionId, turn, answer, res) {
34066
+ if (this.deps.appendRecord === void 0) return null;
34067
+ const record = {
34068
+ version: 1,
34069
+ turn,
34070
+ anchorSeq: answer.anchorSeq,
34071
+ text: res.text,
34072
+ ...answer.text.trim() === "" ? {} : { original: capOriginal(answer.text) },
34073
+ model: res.model,
34074
+ effort: res.effort,
34075
+ provider: PROVIDER_ID,
34076
+ durationMs: res.durationMs,
34077
+ createdAt: this.now()
34078
+ };
34079
+ if (answer.messageId !== void 0) record.messageId = answer.messageId;
34080
+ if (res.accountId !== void 0) record.accountId = res.accountId;
34081
+ if (answer.sourceModel !== void 0) record.sourceModel = answer.sourceModel;
34082
+ try {
34083
+ return await this.deps.appendRecord(sessionId, record);
34084
+ } catch (e) {
34085
+ this.deps.log?.("failed to persist translation record: " + (e instanceof Error ? e.message : String(e)));
34086
+ return null;
34087
+ }
34088
+ }
34089
+ };
34090
+ /** Keep the durable record bounded: the card only needs the source for a diff-style read. */
34091
+ function capOriginal(text) {
34092
+ return text.length <= 8e3 ? text : text.slice(0, 8e3) + "…";
34093
+ }
34094
+ function cacheKey(model, effort, language, text) {
34095
+ const hash = createHash("sha256").update(text).digest("hex").slice(0, 32);
34096
+ return model + "|" + effort + "|" + language + "|" + hash;
34097
+ }
34098
+ /** `gemini-3.8-flash` vs a provider-qualified id such as `auto/gemini-3.8-flash`. */
34099
+ function sameModel(a, b) {
34100
+ const norm = (s) => s.trim().toLowerCase().replace(/^.*\//, "");
34101
+ return norm(a) === norm(b);
34102
+ }
34103
+ //#endregion
34104
+ //#region src/host/tsl-command.ts
34105
+ const HELP = [
34106
+ "**/tsl** — 用 Gemini 把当前会话的输出翻成人话(默认 `gemini-3.8-flash` · high)",
34107
+ "- `/tsl` — 翻译当前会话**最后一个已完成回合**,并在该回复下方生成译文卡片",
34108
+ "- `/tsl 3` — 翻译第 3 回合(卡片锚在那条回复下方)",
34109
+ "- `/tsl --full` — 连本回合的中间解释一起翻(默认只翻最终答复)",
34110
+ "- `/tsl --text 任意文本…` — 直接翻译给定文本(不落卡片)",
34111
+ "- `/tsl --model <id> --effort <low|medium|high>` — 本次临时换模型/档位",
34112
+ "- `/tsl --print` — 命令结果里也回显译文全文",
34113
+ "- `/tsl --no-persist` / `--force` — 不写卡片 / 忽略缓存重译",
34114
+ "- `/tsl auto [on|off|status]` — 本会话的自动翻译开关(默认跟随插件设置,关闭)",
34115
+ "- `/tsl help` — 本说明"
34116
+ ].join("\n");
34117
+ /** Parse the free-form tail of `/tsl`. Never throws: unknown tokens are text. */
34118
+ function parseTslArgs(raw) {
34119
+ const out = {
34120
+ full: false,
34121
+ print: false,
34122
+ persist: true,
34123
+ force: false,
34124
+ help: false
34125
+ };
34126
+ const tokens = raw.trim().split(/\s+/).filter(Boolean);
34127
+ const loose = [];
34128
+ for (let i = 0; i < tokens.length; i++) {
34129
+ const tok = tokens[i];
34130
+ if (tok === "--full") out.full = true;
34131
+ else if (tok === "--print") out.print = true;
34132
+ else if (tok === "--no-persist") out.persist = false;
34133
+ else if (tok === "--force") out.force = true;
34134
+ else if (tok === "help" || tok === "--help" || tok === "-h") out.help = true;
34135
+ else if (tok === "--model" || tok === "--effort" || tok === "--lang" || tok === "--text") {
34136
+ const value = tokens[++i];
34137
+ if (value === void 0) continue;
34138
+ if (tok === "--model") out.model = value;
34139
+ else if (tok === "--effort") out.effort = value;
34140
+ else if (tok === "--lang") out.lang = value;
34141
+ else out.text = [value, ...tokens.slice(i + 1)].join(" ");
34142
+ if (tok === "--text") break;
34143
+ } else if (tok === "auto") {
34144
+ const mode = tokens[i + 1];
34145
+ if (mode === "on" || mode === "off") {
34146
+ out.auto = mode;
34147
+ i++;
34148
+ } else out.auto = "status";
34149
+ } else if (/^\d+$/.test(tok) && out.turn === void 0) out.turn = Number(tok);
34150
+ else loose.push(tok);
34151
+ }
34152
+ if (out.text === void 0 && loose.length > 0) out.text = loose.join(" ");
34153
+ return out;
34154
+ }
33071
34155
  function ok(text) {
33072
34156
  return {
33073
34157
  kind: "success",
@@ -33080,6 +34164,94 @@ function err(text) {
33080
34164
  text
33081
34165
  };
33082
34166
  }
34167
+ function seconds(ms) {
34168
+ return (Math.round(ms / 100) / 10).toString() + "s";
34169
+ }
34170
+ function headerFor(res) {
34171
+ const bits = ["`" + res.model + "`"];
34172
+ if (res.effort !== "") bits.push(res.effort);
34173
+ if (res.accountId !== void 0 && res.accountId !== "") bits.push("账号 `" + res.accountId + "`");
34174
+ bits.push(seconds(res.durationMs));
34175
+ if (res.cached) bits.push("缓存命中");
34176
+ const turn = res.turn;
34177
+ const where = turn !== void 0 && res.recordSeq !== null && res.recordSeq !== void 0 ? "\n位置:第 " + turn + " 回合最后回复下方(💠 Gemini 译文)" : "";
34178
+ return "✅ 已生成译文 · " + bits.join(" · ") + where;
34179
+ }
34180
+ function tslCommandDefinition(deps) {
34181
+ return {
34182
+ name: "tsl",
34183
+ description: "Gemini 人话翻译:把当前会话的输出改写成大白话(/tsl [回合] [--full] [--print] | /tsl auto on|off)",
34184
+ input: { hint: "[turn] [--full] [--print] [--model id] [--effort x] | auto [on|off|status] | help" },
34185
+ handler: (invocation) => handle(deps, invocation)
34186
+ };
34187
+ }
34188
+ function currentSessionId(invocation) {
34189
+ const id = invocation?.agent?.id;
34190
+ return id === void 0 || id === null || String(id) === "" ? void 0 : String(id);
34191
+ }
34192
+ function sessionOf(deps, invocation) {
34193
+ const direct = invocation?.agent?.session;
34194
+ if (direct !== void 0 && direct !== null) return direct;
34195
+ const id = currentSessionId(invocation);
34196
+ if (id === void 0) return void 0;
34197
+ try {
34198
+ return deps.sessions?.()?.get(id);
34199
+ } catch {
34200
+ return;
34201
+ }
34202
+ }
34203
+ async function handle(deps, invocation) {
34204
+ const args = parseTslArgs(invocation?.rawInput ?? "");
34205
+ const service = deps.translate();
34206
+ const sessionId = currentSessionId(invocation);
34207
+ if (args.help) return ok(HELP);
34208
+ if (args.auto !== void 0) {
34209
+ if (sessionId === void 0) return err("无法识别当前会话,`/tsl auto` 需要在会话内使用。");
34210
+ if (args.auto === "status") {
34211
+ const override = deps.sessionAuto.get(sessionId);
34212
+ return ok("**自动翻译(本会话)**:" + (override ?? deps.cfg().autoTranslate ? "开 🟢" : "关 ⚪") + (override === void 0 ? "(跟随插件设置)" : "(本会话覆盖)") + "\n调整:`/tsl auto on` / `/tsl auto off`;插件默认开关在设置 → Antigravity。");
34213
+ }
34214
+ deps.sessionAuto.set(sessionId, args.auto === "on");
34215
+ if (args.auto === "on") {
34216
+ service.translateLastTurn(sessionId, { persist: true }).catch(() => void 0);
34217
+ return ok("本会话自动翻译已**开启**,正在补译最后一回合(完成后在回复下方出现译文卡片)。");
34218
+ }
34219
+ return ok("本会话自动翻译已**关闭**。");
34220
+ }
34221
+ const opts = {
34222
+ full: args.full,
34223
+ persist: args.persist,
34224
+ force: args.force,
34225
+ ...args.model === void 0 ? {} : { model: args.model },
34226
+ ...args.effort === void 0 ? {} : { effort: args.effort },
34227
+ ...args.lang === void 0 ? {} : { targetLanguage: args.lang }
34228
+ };
34229
+ try {
34230
+ if (args.text !== void 0 && args.text.trim() !== "") {
34231
+ const res = await service.translate({
34232
+ text: args.text,
34233
+ ...opts.model === void 0 ? {} : { model: opts.model },
34234
+ ...opts.effort === void 0 ? {} : { effort: opts.effort },
34235
+ ...opts.targetLanguage === void 0 ? {} : { targetLanguage: opts.targetLanguage },
34236
+ force: opts.force
34237
+ });
34238
+ if (!res.ok) return err("翻译失败:" + (res.error ?? "unknown error"));
34239
+ return ok(headerFor(res) + "\n\n---\n\n" + res.text);
34240
+ }
34241
+ if (sessionId === void 0) return err("无法识别当前会话,`/tsl` 需要在会话内使用。");
34242
+ if (sessionOf(deps, invocation) === void 0) return err("当前会话的日志不可用,请稍后重试。");
34243
+ const res = args.turn === void 0 ? await service.translateLastTurn(sessionId, opts) : await service.translateTurn(sessionId, args.turn, opts);
34244
+ if (!res.ok) {
34245
+ if (res.code === "TURN_NOT_FOUND") return err("没有可翻译的助手回复(该回合可能是空的或还在运行)。");
34246
+ if (res.code === "TRANSIENT") return err("当前回合还没结束,等它输出完再译。");
34247
+ return err("翻译失败:" + (res.error ?? "unknown error"));
34248
+ }
34249
+ const showBody = args.print || res.recordSeq === null || res.recordSeq === void 0;
34250
+ return ok(headerFor(res) + (showBody ? "\n\n---\n\n" + res.text : ""));
34251
+ } catch (e) {
34252
+ return err("翻译失败:" + (e instanceof Error ? e.message : String(e)));
34253
+ }
34254
+ }
33083
34255
  //#endregion
33084
34256
  //#region src/host/pool-auth.ts
33085
34257
  const DONE_STATUS_TTL_MS = 3e4;
@@ -35039,12 +36211,14 @@ function startMcpBridge(opts) {
35039
36211
  res.once("close", () => {
35040
36212
  if (!res.writableEnded) controller.abort();
35041
36213
  });
36214
+ const isPtc = svc.schemas(agent).some((tool) => tool.name === "run_code");
35042
36215
  const result = await svc.execute({
35043
36216
  callId: "agy-mcp-" + callSeq,
35044
36217
  name: dshName,
35045
36218
  arguments: parsed.arguments ?? {},
35046
36219
  signal: controller.signal,
35047
- ...agent === void 0 ? {} : { agent }
36220
+ ...agent === void 0 ? {} : { agent },
36221
+ ...isPtc ? { parent: Symbol("agy-mcp-" + callSeq) } : {}
35048
36222
  });
35049
36223
  audit("ok caller=" + (agent === void 0 ? "none" : "agent"));
35050
36224
  sendJson(res, 200, {
@@ -35540,9 +36714,9 @@ function apply(ctx, entryConfig = {}) {
35540
36714
  log,
35541
36715
  runs,
35542
36716
  getMediaBaseUrl: () => webServerPort.current ? `http://127.0.0.1:${webServerPort.current}/plugins/agy-link/media` : null,
35543
- sessionCwd: (sessionId) => {
35544
- return ctx.get("sessions")?.get(sessionId)?.header?.cwd;
35545
- },
36717
+ effortUnsupported: () => readEffortUnsupported(),
36718
+ onEffortUnsupported: (model) => rememberEffortUnsupported(model),
36719
+ sessionCwd: (sessionId) => sessionWorkspace(sessionId),
35546
36720
  sessionGoal: (sessionId) => {
35547
36721
  try {
35548
36722
  const agents = ctx.get("agents") ?? ctx.agents;
@@ -35616,6 +36790,178 @@ function apply(ctx, entryConfig = {}) {
35616
36790
  return null;
35617
36791
  }
35618
36792
  });
36793
+ const sessionsSvc = () => ctx.get("sessions") ?? ctx.sessions;
36794
+ const sessionAuto = /* @__PURE__ */ new Map();
36795
+ let appendPluginRecordPromise = null;
36796
+ const loadAppendPluginRecord = () => {
36797
+ if (appendPluginRecordPromise === null) appendPluginRecordPromise = (async () => {
36798
+ try {
36799
+ const mod = await import("@deepseek-ai/dsh-session");
36800
+ return typeof mod.appendPluginRecord === "function" ? mod.appendPluginRecord : null;
36801
+ } catch (e) {
36802
+ log("translation records unavailable: " + String(e));
36803
+ return null;
36804
+ }
36805
+ })();
36806
+ return appendPluginRecordPromise;
36807
+ };
36808
+ const effortUnsupportedPath = () => join(stateDir(), "effort-unsupported.json");
36809
+ let effortUnsupportedCache = null;
36810
+ const readEffortUnsupported = () => {
36811
+ if (effortUnsupportedCache !== null) return effortUnsupportedCache;
36812
+ try {
36813
+ const raw = existsSync(effortUnsupportedPath()) ? JSON.parse(readFileSync(effortUnsupportedPath(), "utf8")) : [];
36814
+ effortUnsupportedCache = Array.isArray(raw) ? raw.filter((m) => typeof m === "string" && m.trim() !== "") : [];
36815
+ } catch {
36816
+ effortUnsupportedCache = [];
36817
+ }
36818
+ return effortUnsupportedCache;
36819
+ };
36820
+ const rememberEffortUnsupported = (model) => {
36821
+ const known = readEffortUnsupported();
36822
+ if (known.some((m) => m.trim().toLowerCase() === model.trim().toLowerCase())) return;
36823
+ effortUnsupportedCache = [...known, model];
36824
+ try {
36825
+ mkdirSync(stateDir(), { recursive: true });
36826
+ writeFileSync(effortUnsupportedPath(), JSON.stringify(effortUnsupportedCache, null, 2), "utf8");
36827
+ } catch (e) {
36828
+ log("failed to persist the effort-unsupported list: " + String(e));
36829
+ }
36830
+ notifyPicker();
36831
+ };
36832
+ /** The DSH session's own workspace (agy runs there, per the translation spec). */
36833
+ const sessionWorkspace = (sessionId) => {
36834
+ return ctx.get("sessions")?.get(sessionId)?.header?.cwd;
36835
+ };
36836
+ /**
36837
+ * Absolute path of a DSH session's raw log. Handed to agy in the translation
36838
+ * setup so it can read the conversation itself on demand (the bucket directory
36839
+ * name is derived from the workspace, so the session id is what we search by).
36840
+ */
36841
+ const sessionLogFile = (sessionId) => {
36842
+ if (sessionId === "") return void 0;
36843
+ try {
36844
+ const root = join(dshHome(), "sessions");
36845
+ for (const bucket of readdirSync(root)) {
36846
+ const dir = join(root, bucket, "session-" + sessionId);
36847
+ if (!existsSync(dir)) continue;
36848
+ for (const name of readdirSync(dir)) if (name.startsWith("session.") && name.endsWith(".jsonl.zstd")) return join(dir, name);
36849
+ }
36850
+ } catch {}
36851
+ };
36852
+ const translation = new TranslationService({
36853
+ cfg: getConfig,
36854
+ catalog: () => catalog.get(),
36855
+ getSession: (id) => sessionsSvc()?.get(id),
36856
+ autoEnabled: (id) => sessionAuto.get(id) ?? getConfig().autoTranslate,
36857
+ sessionCwd: (id) => sessionWorkspace(id),
36858
+ sessionLogPath: (id) => sessionLogFile(id),
36859
+ log,
36860
+ run: async (req) => {
36861
+ const startedAt = Date.now();
36862
+ const controller = new AbortController();
36863
+ const timer = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("translation timed out after " + req.timeoutMs + "ms")), Math.max(1e3, req.timeoutMs));
36864
+ timer.unref?.();
36865
+ const signal = req.signal === void 0 ? controller.signal : AbortSignal.any([req.signal, controller.signal]);
36866
+ try {
36867
+ const messages = [createUserMessage({
36868
+ content: [{
36869
+ type: "text",
36870
+ text: req.prompt
36871
+ }],
36872
+ source: { kind: "user" }
36873
+ })];
36874
+ const options = {
36875
+ provider: PROVIDER_ID,
36876
+ model: req.model,
36877
+ ...req.sessionId === void 0 ? {} : { sessionId: req.sessionId },
36878
+ messages,
36879
+ maxTokens: req.maxTokens,
36880
+ ...req.effort === void 0 || req.effort === "" ? {} : { reasoningEffort: req.effort },
36881
+ purpose: "translation",
36882
+ signal,
36883
+ ...getConfig().translateBindConversation && req.setup !== void 0 ? { agyTranslateSession: {
36884
+ setup: req.setup,
36885
+ text: req.prompt
36886
+ } } : {}
36887
+ };
36888
+ let text = "";
36889
+ let failure = null;
36890
+ let finishKind;
36891
+ const stream = ctx.llm.stream(options);
36892
+ for await (const chunk of stream) if (chunk.type === "text-delta") text += chunk.text;
36893
+ else if (chunk.type === "finish") {
36894
+ const reason = chunk.reason;
36895
+ finishKind = reason.kind;
36896
+ if (reason.kind === "error" || reason.kind === "aborted") {
36897
+ const f = reason.failure;
36898
+ failure = {
36899
+ ...f?.code === void 0 ? {} : { code: f.code },
36900
+ ...f?.message === void 0 ? {} : { message: f.message }
36901
+ };
36902
+ }
36903
+ }
36904
+ const durationMs = Date.now() - startedAt;
36905
+ if (failure !== null) return {
36906
+ ok: false,
36907
+ text: text.trim(),
36908
+ durationMs,
36909
+ ...failure.code === void 0 ? {} : { code: failure.code },
36910
+ ...failure.message === void 0 ? {} : { error: failure.message }
36911
+ };
36912
+ const trimmed = text.trim();
36913
+ if (trimmed === "") {
36914
+ const detail = finishKind === void 0 ? "" : " (finish: " + finishKind + ")";
36915
+ log("translation produced no text: model=" + req.model + " effort=" + (req.effort === void 0 || req.effort === "" ? "-" : req.effort) + " durationMs=" + durationMs + detail);
36916
+ return {
36917
+ ok: false,
36918
+ text: "",
36919
+ durationMs,
36920
+ code: Err.EMPTY_RESPONSE,
36921
+ error: "the translate model returned no text" + detail
36922
+ };
36923
+ }
36924
+ return {
36925
+ ok: true,
36926
+ text: trimmed,
36927
+ durationMs
36928
+ };
36929
+ } catch (e) {
36930
+ const err = e;
36931
+ return {
36932
+ ok: false,
36933
+ text: "",
36934
+ durationMs: Date.now() - startedAt,
36935
+ ...err.code === void 0 ? {} : { code: err.code },
36936
+ error: err.message ?? String(e)
36937
+ };
36938
+ } finally {
36939
+ clearTimeout(timer);
36940
+ }
36941
+ },
36942
+ appendRecord: async (sessionId, record) => {
36943
+ const session = sessionsSvc()?.get(sessionId);
36944
+ if (session === void 0) return null;
36945
+ const append = await loadAppendPluginRecord();
36946
+ if (append !== null) try {
36947
+ const res = append(session, TRANSLATION_RECORD_TYPE, record);
36948
+ if (typeof res === "number") return res;
36949
+ } catch (e) {
36950
+ log("failed to persist translation record via appendPluginRecord: " + String(e));
36951
+ }
36952
+ try {
36953
+ if (typeof session.append === "function") {
36954
+ const res = session.append(TRANSLATION_RECORD_TYPE, record);
36955
+ if (typeof res === "number") return res;
36956
+ if (res !== null && typeof res === "object" && typeof res.seq === "number") return res.seq;
36957
+ return 0;
36958
+ }
36959
+ } catch (e) {
36960
+ log("failed to persist translation record via session.append: " + String(e));
36961
+ }
36962
+ return null;
36963
+ }
36964
+ });
35619
36965
  const setOverride = (key, value) => {
35620
36966
  const file = overridesPath();
35621
36967
  const current = readOverrides(file);
@@ -35685,10 +37031,42 @@ function apply(ctx, entryConfig = {}) {
35685
37031
  version,
35686
37032
  catalog: () => catalog,
35687
37033
  store: () => store,
35688
- recentLines: () => lastParser.recentLines
37034
+ recentLines: () => lastParser.recentLines,
37035
+ effortUnsupported: () => adapter.effortUnsupportedModels()
35689
37036
  });
35690
37037
  }
35691
37038
  }));
37039
+ ctx.commands.register(tslCommandDefinition({
37040
+ cfg: getConfig,
37041
+ translate: () => translation,
37042
+ setOverride,
37043
+ sessionAuto: {
37044
+ get: (id) => sessionAuto.get(id),
37045
+ set: (id, value) => {
37046
+ if (value === void 0) sessionAuto.delete(id);
37047
+ else sessionAuto.set(id, value);
37048
+ }
37049
+ },
37050
+ sessions: () => sessionsSvc()
37051
+ }));
37052
+ ctx.effect(() => {
37053
+ const unlisten = ctx.on("session/event", (subject, event) => {
37054
+ try {
37055
+ const ev = event;
37056
+ if (ev === null || ev.type !== "turn/end") return;
37057
+ if (ev.data?.reason?.kind !== "completed") return;
37058
+ const turn = ev.data?.turn;
37059
+ if (typeof turn !== "number") return;
37060
+ const session = subject;
37061
+ const id = session?.id === void 0 || session?.id === null ? "" : String(session.id);
37062
+ if (id === "") return;
37063
+ translation.autoTranslateTurn(id, turn).catch(() => void 0);
37064
+ } catch {}
37065
+ }, { global: true });
37066
+ return () => {
37067
+ if (typeof unlisten === "function") unlisten();
37068
+ };
37069
+ });
35692
37070
  const toolsSvcRef = { current: null };
35693
37071
  const askToolDispose = { current: null };
35694
37072
  const mirrorToolDispose = { current: null };
@@ -35699,7 +37077,9 @@ function apply(ctx, entryConfig = {}) {
35699
37077
  const reg = toolsSvcRef.current.register(defineAgyAskTool({
35700
37078
  cfg: getConfig,
35701
37079
  bin,
35702
- catalog: () => catalog.get()
37080
+ catalog: () => catalog.get(),
37081
+ effortUnsupported: () => readEffortUnsupported(),
37082
+ onEffortUnsupported: (model) => rememberEffortUnsupported(model)
35703
37083
  }));
35704
37084
  askToolDispose.current = typeof reg === "function" ? reg : null;
35705
37085
  } else if (!want && askToolDispose.current !== null) {
@@ -35759,6 +37139,18 @@ function apply(ctx, entryConfig = {}) {
35759
37139
  const m = req.method;
35760
37140
  return typeof m === "string" ? m.toUpperCase() : "GET";
35761
37141
  };
37142
+ const queryParam = (req, key) => {
37143
+ const rawUrl = req.url;
37144
+ if (typeof rawUrl !== "string") return "";
37145
+ const m = new RegExp("[?&]" + key + "=([^&]+)").exec(rawUrl);
37146
+ if (m === null) return "";
37147
+ const raw = m[1] ?? "";
37148
+ try {
37149
+ return decodeURIComponent(raw);
37150
+ } catch {
37151
+ return raw;
37152
+ }
37153
+ };
35762
37154
  reg({
35763
37155
  kind: "exact",
35764
37156
  path: "/plugins/agy-link/status",
@@ -35789,7 +37181,16 @@ function apply(ctx, entryConfig = {}) {
35789
37181
  hiddenModels: cfg.hiddenModels,
35790
37182
  autoWarmup: cfg.autoWarmup,
35791
37183
  warmupModels: cfg.warmupModels,
37184
+ autoTranslate: cfg.autoTranslate,
37185
+ translateModel: cfg.translateModel,
37186
+ translateEffort: cfg.translateEffort,
37187
+ translateTargetLanguage: cfg.translateTargetLanguage,
37188
+ translateState: {
37189
+ pending: translation.pendingFor(),
37190
+ stats: translation.stats()
37191
+ },
35792
37192
  bindings: Object.keys(store.all()).length,
37193
+ effortUnsupported: adapter.effortUnsupportedModels(),
35793
37194
  lastRun
35794
37195
  });
35795
37196
  })();
@@ -36268,7 +37669,15 @@ function apply(ctx, entryConfig = {}) {
36268
37669
  "workspaceRoot",
36269
37670
  "hiddenModels",
36270
37671
  "autoWarmup",
36271
- "warmupModels"
37672
+ "warmupModels",
37673
+ "autoTranslate",
37674
+ "translateModel",
37675
+ "translateEffort",
37676
+ "translateTargetLanguage",
37677
+ "translateMaxChars",
37678
+ "translateSkipSameModel",
37679
+ "translateBindConversation",
37680
+ "translateMinIntervalMs"
36272
37681
  ].includes(key)) {
36273
37682
  sendJson(res, 400, { error: "key not settable" });
36274
37683
  return;
@@ -36293,6 +37702,115 @@ function apply(ctx, entryConfig = {}) {
36293
37702
  })();
36294
37703
  }
36295
37704
  });
37705
+ reg({
37706
+ kind: "exact",
37707
+ path: "/plugins/agy-link/translate",
37708
+ handler: (req, res) => {
37709
+ (async () => {
37710
+ if (methodOf(req) !== "POST") {
37711
+ sendJson(res, 405, { error: "POST only" });
37712
+ return;
37713
+ }
37714
+ const body = await readBody(req, true);
37715
+ if (body.__invalidJson === true) {
37716
+ sendJson(res, 400, { error: "invalid JSON body" });
37717
+ return;
37718
+ }
37719
+ const text = typeof body.text === "string" ? body.text : "";
37720
+ const sessionId = typeof body.sessionId === "string" ? body.sessionId : "";
37721
+ const messageId = typeof body.messageId === "string" ? body.messageId : "";
37722
+ const turn = typeof body.turn === "number" && Number.isFinite(body.turn) ? body.turn : void 0;
37723
+ const force = body.force === true;
37724
+ const full = body.full === true;
37725
+ const persist = body.persist !== false;
37726
+ const model = typeof body.model === "string" && body.model.trim() !== "" ? body.model.trim() : void 0;
37727
+ const effort = typeof body.effort === "string" && body.effort.trim() !== "" ? body.effort.trim() : void 0;
37728
+ const lang = typeof body.lang === "string" && body.lang.trim() !== "" ? body.lang.trim() : void 0;
37729
+ const opts = {
37730
+ force,
37731
+ full,
37732
+ persist,
37733
+ ...model === void 0 ? {} : { model },
37734
+ ...effort === void 0 ? {} : { effort },
37735
+ ...lang === void 0 ? {} : { targetLanguage: lang }
37736
+ };
37737
+ try {
37738
+ let result;
37739
+ if (text.trim() !== "") result = await translation.translate({
37740
+ text,
37741
+ force,
37742
+ ...model === void 0 ? {} : { model },
37743
+ ...effort === void 0 ? {} : { effort },
37744
+ ...lang === void 0 ? {} : { targetLanguage: lang }
37745
+ });
37746
+ else if (sessionId !== "" && messageId !== "") result = await translation.translateMessage(sessionId, messageId, opts);
37747
+ else if (sessionId !== "" && turn !== void 0) result = await translation.translateTurn(sessionId, turn, opts);
37748
+ else if (sessionId !== "") result = await translation.translateLastTurn(sessionId, opts);
37749
+ else {
37750
+ sendJson(res, 400, { error: "text, or sessionId (+ turn/messageId), is required" });
37751
+ return;
37752
+ }
37753
+ const status = result.ok ? 200 : result.code === "TRANSIENT" ? 409 : result.code === "TURN_NOT_FOUND" || result.code === "MESSAGE_NOT_FOUND" || result.code === "EMPTY_TEXT" ? 400 : 502;
37754
+ sendJson(res, status, result);
37755
+ } catch (e) {
37756
+ sendJson(res, 500, { error: String(e) });
37757
+ }
37758
+ })();
37759
+ }
37760
+ });
37761
+ reg({
37762
+ kind: "exact",
37763
+ path: "/plugins/agy-link/translate/pending",
37764
+ handler: (req, res) => {
37765
+ const session = queryParam(req, "session");
37766
+ sendJson(res, 200, {
37767
+ items: translation.pendingFor(session === "" ? void 0 : session),
37768
+ stats: translation.stats()
37769
+ });
37770
+ }
37771
+ });
37772
+ reg({
37773
+ kind: "exact",
37774
+ path: "/plugins/agy-link/translate/turn",
37775
+ handler: (req, res) => {
37776
+ const session = queryParam(req, "session");
37777
+ const turn = Number(queryParam(req, "turn"));
37778
+ if (session === "" || !Number.isFinite(turn)) {
37779
+ sendJson(res, 400, { error: "session and turn are required" });
37780
+ return;
37781
+ }
37782
+ const existing = translation.existingTurn(session, turn);
37783
+ sendJson(res, 200, existing === null ? { state: "idle" } : {
37784
+ state: "ready",
37785
+ seq: existing.seq,
37786
+ model: existing.model,
37787
+ effort: existing.effort
37788
+ });
37789
+ }
37790
+ });
37791
+ reg({
37792
+ kind: "exact",
37793
+ path: "/plugins/agy-link/translate/state",
37794
+ handler: (req, res) => {
37795
+ const session = queryParam(req, "session");
37796
+ const message = queryParam(req, "message");
37797
+ if (session === "" || message === "") {
37798
+ sendJson(res, 400, { error: "session and message are required" });
37799
+ return;
37800
+ }
37801
+ const existing = translation.existingMessage(session, message);
37802
+ if (existing !== null) {
37803
+ sendJson(res, 200, {
37804
+ state: "ready",
37805
+ seq: existing.seq,
37806
+ model: existing.model,
37807
+ effort: existing.effort
37808
+ });
37809
+ return;
37810
+ }
37811
+ sendJson(res, 200, { state: translation.isPending(session) ? "busy" : "idle" });
37812
+ }
37813
+ });
36296
37814
  reg({
36297
37815
  kind: "exact",
36298
37816
  path: "/plugins/agy-link/qr",