@eddyskywalker/dsh-chatgpt-subscription 0.72.0 → 0.74.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.
Files changed (80) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/lib/client.js +47 -12
  3. package/lib/client.js.map +1 -1
  4. package/lib/codemode.js +125 -60
  5. package/lib/{entry-plan-mode-5DBZA4Il.js → entry-plan-mode-EShP3ndV.js} +34 -8
  6. package/lib/index.js +1035 -535
  7. package/lib/{llm-compat-u9mor0uu.js → llm-compat--WsaC9K6.js} +25 -1
  8. package/lib/plan-mode.js +2 -2
  9. package/lib/types/client/antigravity-acp/AntigravityAcpSection.d.ts.map +1 -1
  10. package/lib/types/client/antigravity-acp/locales.d.ts +42 -18
  11. package/lib/types/client/antigravity-acp/locales.d.ts.map +1 -1
  12. package/lib/types/client/locales-ru/antigravity-acp.d.ts.map +1 -1
  13. package/lib/types/compat.d.ts +1 -1
  14. package/lib/types/entry-codemode.d.ts.map +1 -1
  15. package/lib/types/entry-plan-mode.d.ts +14 -0
  16. package/lib/types/entry-plan-mode.d.ts.map +1 -1
  17. package/lib/types/host/antigravity-acp/adapter.d.ts +31 -0
  18. package/lib/types/host/antigravity-acp/adapter.d.ts.map +1 -1
  19. package/lib/types/host/antigravity-acp/catalog.d.ts.map +1 -1
  20. package/lib/types/host/antigravity-acp/errors.d.ts +1 -1
  21. package/lib/types/host/antigravity-acp/errors.d.ts.map +1 -1
  22. package/lib/types/host/antigravity-acp/mcp-bridge.d.ts +16 -0
  23. package/lib/types/host/antigravity-acp/mcp-bridge.d.ts.map +1 -1
  24. package/lib/types/host/antigravity-acp/routes.d.ts.map +1 -1
  25. package/lib/types/host/antigravity-acp/settings.d.ts +13 -2
  26. package/lib/types/host/antigravity-acp/settings.d.ts.map +1 -1
  27. package/lib/types/host/antigravity-acp/types.d.ts +12 -7
  28. package/lib/types/host/antigravity-acp/types.d.ts.map +1 -1
  29. package/lib/types/host/cache-warmup/contracts.d.ts +19 -3
  30. package/lib/types/host/cache-warmup/contracts.d.ts.map +1 -1
  31. package/lib/types/host/cache-warmup/install.d.ts.map +1 -1
  32. package/lib/types/host/cache-warmup/projection.d.ts.map +1 -1
  33. package/lib/types/host/cache-warmup/result-tool.d.ts +4 -0
  34. package/lib/types/host/cache-warmup/result-tool.d.ts.map +1 -1
  35. package/lib/types/host/cache-warmup/store.d.ts.map +1 -1
  36. package/lib/types/host/claude/adapter.d.ts +2 -1
  37. package/lib/types/host/claude/adapter.d.ts.map +1 -1
  38. package/lib/types/host/cline-pass/adapter.d.ts.map +1 -1
  39. package/lib/types/host/cline-pass/mapper.d.ts +1 -1
  40. package/lib/types/host/cline-pass/mapper.d.ts.map +1 -1
  41. package/lib/types/host/codemode/rules.d.ts.map +1 -1
  42. package/lib/types/host/codemode/transport.d.ts +23 -1
  43. package/lib/types/host/codemode/transport.d.ts.map +1 -1
  44. package/lib/types/host/command-code/adapter.d.ts.map +1 -1
  45. package/lib/types/host/common/i18n/en.d.ts.map +1 -1
  46. package/lib/types/host/common/i18n/ru.d.ts.map +1 -1
  47. package/lib/types/host/common/i18n/zh.d.ts +1 -0
  48. package/lib/types/host/common/i18n/zh.d.ts.map +1 -1
  49. package/lib/types/host/common/llm-compat.d.ts +15 -2
  50. package/lib/types/host/common/llm-compat.d.ts.map +1 -1
  51. package/lib/types/host/common/stream-error.d.ts +1 -1
  52. package/lib/types/host/common/stream-error.d.ts.map +1 -1
  53. package/lib/types/host/common/tool-runaway.d.ts +91 -3
  54. package/lib/types/host/common/tool-runaway.d.ts.map +1 -1
  55. package/lib/types/host/compaction-policy-guard.d.ts.map +1 -1
  56. package/lib/types/host/glm-coding-plan/adapter.d.ts.map +1 -1
  57. package/lib/types/host/kimi-code/adapter.d.ts.map +1 -1
  58. package/lib/types/host/kimi-code/repeat-breaker.d.ts +3 -1
  59. package/lib/types/host/kimi-code/repeat-breaker.d.ts.map +1 -1
  60. package/lib/types/host/minimax-code/adapter.d.ts.map +1 -1
  61. package/lib/types/host/minimax-code/runtime-enhancements.d.ts +10 -97
  62. package/lib/types/host/minimax-code/runtime-enhancements.d.ts.map +1 -1
  63. package/lib/types/host/ollama/adapter.d.ts.map +1 -1
  64. package/lib/types/host/opendesign/adapter.d.ts.map +1 -1
  65. package/lib/types/host/opendesign/mapper.d.ts +1 -1
  66. package/lib/types/host/opendesign/mapper.d.ts.map +1 -1
  67. package/lib/types/host/qoder/adapter.d.ts.map +1 -1
  68. package/lib/types/host/responses-client.d.ts.map +1 -1
  69. package/lib/types/host/step-code/adapter.d.ts.map +1 -1
  70. package/lib/types/host/workbuddy/account-pool.d.ts +1 -1
  71. package/lib/types/host/workbuddy/account-pool.d.ts.map +1 -1
  72. package/lib/types/host/workbuddy/adapter.d.ts +2 -1
  73. package/lib/types/host/workbuddy/adapter.d.ts.map +1 -1
  74. package/lib/types/index.d.ts +2 -2
  75. package/lib/types/index.d.ts.map +1 -1
  76. package/lib/types/shared/antigravity-acp-contracts.d.ts +12 -0
  77. package/lib/types/shared/antigravity-acp-contracts.d.ts.map +1 -1
  78. package/package.json +42 -42
  79. package/presets/dispatch/README.md +2 -2
  80. package/presets/dispatch/agent.cordis.yml +2 -2
package/lib/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { a as resolveProgressUpdatesSettings, n as attachProgressSettings } from "./entry-progress-updates-DMLVID9V.js";
2
2
  import { attachPlanModePipelineSettings, resolvePlanModePipelineEnabled } from "./plan-mode-pipeline.js";
3
- import { n as PLUGIN_MESSAGE_SOURCE_KIND, r as normalizeGenerateOptions, t as LlmError$1 } from "./llm-compat-u9mor0uu.js";
3
+ import { n as PLUGIN_MESSAGE_SOURCE_KIND, r as normalizeGenerateOptions, t as LlmError$1 } from "./llm-compat--WsaC9K6.js";
4
4
  import { DEFAULT_SKIP_PROVIDERS, PRUNER_SERVICE_NAME, resolveSkipProviders, shouldSkipPruningForSession } from "./tool-result-pruner.js";
5
- import { b as installDispatchExecutionGuard, h as installPlanModeExitReminder, l as PLAN_PROJECTION_KEY, p as createPlanNotice, v as registeredPlanControllerActive, x as resolveDispatchExecutionGuardEnabled } from "./entry-plan-mode-5DBZA4Il.js";
5
+ import { S as resolveDispatchExecutionGuardEnabled, g as installPlanModeExitReminder, l as PLAN_PROJECTION_KEY, m as createPlanNotice, x as installDispatchExecutionGuard, y as registeredPlanControllerActive } from "./entry-plan-mode-EShP3ndV.js";
6
6
  import { createRequire } from "node:module";
7
7
  import * as LlmModule from "@deepseek-ai/dsh-llm";
8
8
  import { EMPTY_RESPONSE_CODE, HarnessError, LlmAdapter, LlmError, ProviderRequestId, ReasoningEffortId, ToolCallId, attributionHeaders, createUserMessage, errorChain, resolveRetryPolicy } from "@deepseek-ai/dsh-llm";
@@ -292,7 +292,8 @@ const en = {
292
292
  "glm.notSignedIn": "No {provider} account is signed in yet.",
293
293
  "provider.antigravity-acp": "Antigravity (ACP)",
294
294
  "antigravityAcp.notSignedIn": "Antigravity is not signed in. Start the sign-in from this card, or run agy acp --login in a terminal.",
295
- "antigravityAcp.noBinary": "No usable Antigravity CLI (agy) was found and the official ACP server has not been downloaded."
295
+ "antigravityAcp.noBinary": "No usable Antigravity CLI (agy) was found and the official ACP server has not been downloaded.",
296
+ "antigravityAcp.nativeTool": "[Antigravity ran its own tool outside DSH permissions: {call}]\n"
296
297
  };
297
298
  //#endregion
298
299
  //#region src/host/common/i18n/ru.ts
@@ -450,7 +451,8 @@ const ru = {
450
451
  "glm.notSignedIn": "Вход в аккаунт {provider} ещё не выполнен.",
451
452
  "provider.antigravity-acp": "Antigravity (ACP)",
452
453
  "antigravityAcp.notSignedIn": "Вход в Antigravity не выполнен. Начните его на этой карточке или выполните agy acp --login в терминале.",
453
- "antigravityAcp.noBinary": "Рабочий Antigravity CLI (agy) не найден, и официальный ACP-сервер ещё не загружен."
454
+ "antigravityAcp.noBinary": "Рабочий Antigravity CLI (agy) не найден, и официальный ACP-сервер ещё не загружен.",
455
+ "antigravityAcp.nativeTool": "[Antigravity использовал собственный инструмент в обход разрешений DSH: {call}]\n"
454
456
  };
455
457
  //#endregion
456
458
  //#region src/host/common/i18n/zh.ts
@@ -617,7 +619,8 @@ const zh = {
617
619
  "glm.notSignedIn": "还没有登录 {provider} 账号。",
618
620
  "provider.antigravity-acp": "Antigravity(ACP)",
619
621
  "antigravityAcp.notSignedIn": "还没有登录 Antigravity:请在设置页发起登录,或在终端执行 agy acp --login。",
620
- "antigravityAcp.noBinary": "未找到可用的 Antigravity CLI(agy),且官方 ACP 服务端尚未下载。"
622
+ "antigravityAcp.noBinary": "未找到可用的 Antigravity CLI(agy),且官方 ACP 服务端尚未下载。",
623
+ "antigravityAcp.nativeTool": "[Antigravity 使用了它自带的工具,这次调用没有经过 DSH 权限:{call}]\n"
621
624
  };
622
625
  //#endregion
623
626
  //#region src/host/common/i18n/t.ts
@@ -814,7 +817,7 @@ const ROUTE_PREFIX$5 = "/api/dsh-chatgpt-subscription";
814
817
  * `test/responses-client.test.ts` asserts the two agree, so a release that
815
818
  * forgets this constant fails the suite instead of shipping quietly.
816
819
  */
817
- const PLUGIN_VERSION = "0.72.0";
820
+ const PLUGIN_VERSION = "0.74.0";
818
821
  const CODEX_CHATGPT_PROVIDER_ID = "codex-chatgpt";
819
822
  const CODEX_API_BASE = "https://chatgpt.com/backend-api/codex";
820
823
  const CODEX_RESPONSES_URL = `${CODEX_API_BASE}/responses`;
@@ -4483,8 +4486,8 @@ var OAuthService = class {
4483
4486
  }
4484
4487
  const payload = await response.json().catch(() => null);
4485
4488
  const record = isRecord$69(payload) ? payload : {};
4486
- const authId = nonEmptyString$11(record.device_auth_id);
4487
- const userCode = nonEmptyString$11(record.user_code) ?? nonEmptyString$11(record.usercode);
4489
+ const authId = nonEmptyString$12(record.device_auth_id);
4490
+ const userCode = nonEmptyString$12(record.user_code) ?? nonEmptyString$12(record.usercode);
4488
4491
  if (authId === void 0 || userCode === void 0) throw new OAuthServiceError("oauth-token-exchange-failed", "ChatGPT returned no device code.");
4489
4492
  return {
4490
4493
  authId,
@@ -4550,8 +4553,8 @@ var OAuthService = class {
4550
4553
  throw new OAuthServiceError("oauth-token-exchange-failed", `The ChatGPT device confirmation was refused (${response.status}${detail === void 0 ? "" : `, ${detail}`}).`, response.status);
4551
4554
  }
4552
4555
  const record = isRecord$69(payload) ? payload : {};
4553
- const authorizationCode = nonEmptyString$11(record.authorization_code);
4554
- const codeVerifier = nonEmptyString$11(record.code_verifier);
4556
+ const authorizationCode = nonEmptyString$12(record.authorization_code);
4557
+ const codeVerifier = nonEmptyString$12(record.code_verifier);
4555
4558
  if (authorizationCode === void 0 || codeVerifier === void 0) throw new OAuthServiceError("oauth-token-exchange-failed", "ChatGPT confirmed the device code but returned no authorization code.");
4556
4559
  return {
4557
4560
  authorizationCode,
@@ -4908,7 +4911,7 @@ function deviceErrorIdentifier(payload) {
4908
4911
  candidates.push(payload.status);
4909
4912
  for (const candidate of candidates) if (typeof candidate === "string" && /^[a-z0-9_.-]{1,64}$/i.test(candidate)) return candidate;
4910
4913
  }
4911
- function nonEmptyString$11(value) {
4914
+ function nonEmptyString$12(value) {
4912
4915
  return typeof value === "string" && value !== "" ? value : void 0;
4913
4916
  }
4914
4917
  function isRecord$69(value) {
@@ -5096,7 +5099,7 @@ function isRecord$68(value) {
5096
5099
  return typeof value === "object" && value !== null && !Array.isArray(value);
5097
5100
  }
5098
5101
  /** A trimmed, non-empty string, or nothing. */
5099
- function nonEmptyString$10(value) {
5102
+ function nonEmptyString$11(value) {
5100
5103
  if (typeof value !== "string") return void 0;
5101
5104
  const trimmed = value.trim();
5102
5105
  return trimmed === "" ? void 0 : trimmed;
@@ -5243,9 +5246,9 @@ function parseAdoptedCodexCredential(value, sourcePath) {
5243
5246
  if (value.auth_mode !== "chatgpt") return void 0;
5244
5247
  const tokens = value[CODEX_CLI_TOKENS_KEY];
5245
5248
  if (!isRecord$68(tokens)) return void 0;
5246
- const accessToken = nonEmptyString$10(tokens.access_token);
5249
+ const accessToken = nonEmptyString$11(tokens.access_token);
5247
5250
  if (accessToken === void 0) return void 0;
5248
- const refreshToken = nonEmptyString$10(tokens.refresh_token);
5251
+ const refreshToken = nonEmptyString$11(tokens.refresh_token);
5249
5252
  if (refreshToken === void 0) return void 0;
5250
5253
  const expiresAt = expiryFromAccessToken(accessToken);
5251
5254
  if (expiresAt === void 0) return void 0;
@@ -5254,17 +5257,17 @@ function parseAdoptedCodexCredential(value, sourcePath) {
5254
5257
  refreshToken,
5255
5258
  expiresAt
5256
5259
  };
5257
- const idToken = nonEmptyString$10(tokens.id_token);
5260
+ const idToken = nonEmptyString$11(tokens.id_token);
5258
5261
  if (idToken !== void 0) {
5259
5262
  credentials.idToken = idToken;
5260
5263
  const claims = decodeJwtClaims$1(idToken);
5261
- const email = claims === void 0 ? void 0 : nonEmptyString$10(claims.email);
5264
+ const email = claims === void 0 ? void 0 : nonEmptyString$11(claims.email);
5262
5265
  if (email !== void 0) credentials.email = email;
5263
5266
  const authClaims = claims === void 0 ? void 0 : claims[CODEX_AUTH_CLAIMS_KEY];
5264
- const planType = isRecord$68(authClaims) ? nonEmptyString$10(authClaims.chatgpt_plan_type) : void 0;
5267
+ const planType = isRecord$68(authClaims) ? nonEmptyString$11(authClaims.chatgpt_plan_type) : void 0;
5265
5268
  if (planType !== void 0) credentials.planType = planType;
5266
5269
  }
5267
- const accountId = nonEmptyString$10(tokens.account_id);
5270
+ const accountId = nonEmptyString$11(tokens.account_id);
5268
5271
  if (accountId !== void 0) credentials.accountId = accountId;
5269
5272
  return {
5270
5273
  adopted: true,
@@ -7572,20 +7575,214 @@ function resolveToolRunawayGuardEnabled(config) {
7572
7575
  }
7573
7576
  return field !== false;
7574
7577
  }
7578
+ /** 轮询类工具名(后台任务的结果读取)。 */
7579
+ const POLLING_TOOL_NAMES = Object.freeze(["job_output", "task_output"]);
7580
+ const TURN_ONLY_SUFFIX = " This is a temporary runtime reminder for the current Turn only, not a user preference or a durable rule; do not save this reminder or generalize it into Memory, Skills, or other persistent instruction files for future Turns or sessions.";
7581
+ /** 渲染「同一个动作立刻重复」提醒。 */
7582
+ function renderExactActionRepeatReminder(occurrences) {
7583
+ return `[runaway guard] The immediately repeated tool action has now occurred ${occurrences} times with the same arguments. Do not repeat it unchanged. Inspect the results already available, then either change strategy with a concrete expected state change, or report the blocker. Repetition alone does not establish that the task is complete or impossible.${TURN_ONLY_SUFFIX}`;
7584
+ }
7585
+ /** 渲染「同一族错误连续发生」提醒。 */
7586
+ function renderSameErrorFamilyReminder(occurrences) {
7587
+ return `[runaway guard] The same tool error family has now occurred ${occurrences} times in a row. Do not retry the same route unchanged. Diagnose the cause, change one controlled variable or switch route. Do not infer that the entire task has failed from this signal.${TURN_ONLY_SUFFIX}`;
7588
+ }
7589
+ /** 渲染「反复轮询同一个后台任务」提醒。 */
7590
+ function renderPollingRepeatReminder(occurrences) {
7591
+ return [
7592
+ "<system-reminder>",
7593
+ `${occurrences === 3 ? "Three" : String(occurrences)} task_output reads for the same task have returned an unchanged status and output cursor. Avoid repeated polling; you will be notified automatically and this conversation will resume when the background task completes.`,
7594
+ "This reminder applies only to the current Turn. Do not save or generalize it into Memory, Skills, or other persistent instructions.",
7595
+ "</system-reminder>"
7596
+ ].join("\n");
7597
+ }
7598
+ /** 规范化错误文本,去掉会漂移的数字/id/时间戳,取它的「族」。 */
7599
+ function normalizeToolErrorFamily(text) {
7600
+ if (text === void 0 || text === "") return "unknown";
7601
+ return (text.split(/\r?\n/, 1)[0] ?? "").replace(/\d+/g, "#").slice(0, 200);
7602
+ }
7603
+ function nonEmptyString$10(value) {
7604
+ return typeof value === "string" && value !== "" ? value : void 0;
7605
+ }
7606
+ /** 判断一次工具执行结果是否失败。 */
7607
+ function isToolErrorResult(result) {
7608
+ return isRecord$67(result) && result["isError"] === true;
7609
+ }
7610
+ /** 读一次工具执行结果里的结构化错误码。 */
7611
+ function toolErrorCodeOf(result) {
7612
+ if (!isRecord$67(result)) return void 0;
7613
+ const error = result["error"];
7614
+ if (!isRecord$67(error)) return void 0;
7615
+ const info = error["info"];
7616
+ if (isRecord$67(info)) {
7617
+ const infoCode = nonEmptyString$10(info["code"]);
7618
+ if (infoCode !== void 0) return infoCode;
7619
+ }
7620
+ return nonEmptyString$10(error["code"]);
7621
+ }
7622
+ /** 读一次工具执行结果里的全部文本块。 */
7623
+ function toolResultTextOf(result) {
7624
+ if (!isRecord$67(result)) return "";
7625
+ const content = result["content"];
7626
+ if (!Array.isArray(content)) return "";
7627
+ const parts = [];
7628
+ for (const block of content) if (isRecord$67(block) && block["type"] === "text") parts.push(nonEmptyString$10(block["text"]) ?? "");
7629
+ return parts.join("\n");
7630
+ }
7631
+ /** 读一次工具执行结果里的失败文本(无 `error.message` 且为错误结果时回退读取文本内容)。 */
7632
+ function toolErrorTextOf(result) {
7633
+ if (isRecord$67(result)) {
7634
+ const error = result["error"];
7635
+ if (isRecord$67(error)) {
7636
+ const msg = nonEmptyString$10(error["message"]);
7637
+ if (msg !== void 0) return msg;
7638
+ }
7639
+ }
7640
+ if (!isToolErrorResult(result)) return void 0;
7641
+ const text = toolResultTextOf(result);
7642
+ return text === "" ? void 0 : text;
7643
+ }
7644
+ /** 从一次工具执行与结果中构造失控检测观察量。 */
7645
+ function observationFromToolExecution(toolName, args, result) {
7646
+ return {
7647
+ toolName,
7648
+ arguments: args,
7649
+ isError: isToolErrorResult(result),
7650
+ errorCode: toolErrorCodeOf(result),
7651
+ errorText: toolErrorTextOf(result),
7652
+ resultText: toolResultTextOf(result)
7653
+ };
7654
+ }
7655
+ function isPollingObservation(toolName, args) {
7656
+ if (!POLLING_TOOL_NAMES.includes(toolName)) return false;
7657
+ return (isPlainRecord$2(args) ? args : void 0)?.["wait"] !== true;
7658
+ }
7575
7659
  /**
7576
- * Exact-repeat state machine shared by provider profiles. A missing forceStopAt
7577
- * gives reminders only; no provider inherits Kimi's hard stop accidentally.
7660
+ * 造一台单会话工具级失控守卫。
7661
+ *
7662
+ * 三种可提醒信号(顺序即提醒优先级):
7663
+ * 1. `same_error_family` —— 同一个工具连续报同一族错误;
7664
+ * 2. `exact_action_repeat` —— 同一次动作(同名 + 同参数)立刻重复;
7665
+ * 3. `polling_repeat` —— 连续轮询同一个后台任务而输出没变。
7666
+ */
7667
+ function createToolRunawayGuard(options = {}) {
7668
+ const threshold = options.remindAfterOccurrences ?? 3;
7669
+ const exactActionRepeats = createExactRepeatTracker();
7670
+ const errorStreaks = /* @__PURE__ */ new Map();
7671
+ const pollingStreaks = /* @__PURE__ */ new Map();
7672
+ const recentActions = [];
7673
+ let activeAbabKey;
7674
+ let reminderAttempted = false;
7675
+ const signals = [];
7676
+ const record = (kind, occurrences, toolName) => {
7677
+ signals.push({
7678
+ kind,
7679
+ occurrences,
7680
+ toolName
7681
+ });
7682
+ };
7683
+ return {
7684
+ observe(observation) {
7685
+ const toolName = observation.toolName;
7686
+ const actionKey = canonicalToolCallKey(toolName, observation.arguments);
7687
+ const countsAsAction = !POLLING_TOOL_NAMES.includes(toolName);
7688
+ if (countsAsAction) {
7689
+ const action = exactActionRepeats.observe(toolName, observation.arguments);
7690
+ record("exact_action_repeat", action.count, toolName);
7691
+ }
7692
+ if (countsAsAction) {
7693
+ recentActions.push(actionKey);
7694
+ if (recentActions.length > 4) recentActions.shift();
7695
+ if (recentActions.length === 4) {
7696
+ const [a, b, c, d] = recentActions;
7697
+ if (a !== void 0 && b !== void 0 && a !== b && a === c && b === d) {
7698
+ const episode = `${a}\u0000${b}`;
7699
+ if (activeAbabKey !== episode) {
7700
+ activeAbabKey = episode;
7701
+ record("abab_action_cycle", 2, toolName);
7702
+ }
7703
+ } else activeAbabKey = void 0;
7704
+ }
7705
+ }
7706
+ if (observation.isError === true) {
7707
+ const key = `${toolName}\u0000${observation.errorCode ?? normalizeToolErrorFamily(observation.errorText)}`;
7708
+ const previous = errorStreaks.get(key);
7709
+ const count = previous === void 0 ? 1 : previous.count + 1;
7710
+ errorStreaks.set(key, {
7711
+ toolName,
7712
+ count
7713
+ });
7714
+ record("same_error_family", count, toolName);
7715
+ } else for (const [key, entry] of [...errorStreaks]) if (entry.toolName === toolName) errorStreaks.delete(key);
7716
+ if (isPollingObservation(toolName, observation.arguments)) {
7717
+ const key = `${canonicalToolCallKey(toolName, observation.arguments)}\u0000${observation.resultText ?? ""}`;
7718
+ const previous = pollingStreaks.get(toolName);
7719
+ const count = previous !== void 0 && previous.key === key ? previous.count + 1 : 1;
7720
+ pollingStreaks.set(toolName, {
7721
+ key,
7722
+ count
7723
+ });
7724
+ record("polling_repeat", count, toolName);
7725
+ } else pollingStreaks.delete(toolName);
7726
+ if (reminderAttempted) return void 0;
7727
+ const errorCandidate = [...errorStreaks.values()].find((entry) => entry.count >= threshold);
7728
+ if (errorCandidate !== void 0) {
7729
+ reminderAttempted = true;
7730
+ return {
7731
+ kind: "same_error_family",
7732
+ occurrences: errorCandidate.count,
7733
+ text: renderSameErrorFamilyReminder(errorCandidate.count)
7734
+ };
7735
+ }
7736
+ const actionStreak = exactActionRepeats.current();
7737
+ if (countsAsAction && actionStreak !== void 0 && actionStreak.count >= threshold) {
7738
+ reminderAttempted = true;
7739
+ return {
7740
+ kind: "exact_action_repeat",
7741
+ occurrences: actionStreak.count,
7742
+ text: renderExactActionRepeatReminder(actionStreak.count)
7743
+ };
7744
+ }
7745
+ const pollingCandidate = [...pollingStreaks.values()].find((entry) => entry.count >= threshold);
7746
+ if (pollingCandidate !== void 0) {
7747
+ reminderAttempted = true;
7748
+ return {
7749
+ kind: "polling_repeat",
7750
+ occurrences: pollingCandidate.count,
7751
+ text: renderPollingRepeatReminder(pollingCandidate.count)
7752
+ };
7753
+ }
7754
+ },
7755
+ reset() {
7756
+ exactActionRepeats.reset();
7757
+ errorStreaks.clear();
7758
+ pollingStreaks.clear();
7759
+ recentActions.length = 0;
7760
+ activeAbabKey = void 0;
7761
+ reminderAttempted = false;
7762
+ },
7763
+ get signals() {
7764
+ return signals;
7765
+ }
7766
+ };
7767
+ }
7768
+ /**
7769
+ * Exact-repeat + deterministic zero-progress (same error family / unchanged polling)
7770
+ * state machine shared by provider profiles. A missing forceStopAt gives reminders only;
7771
+ * no provider inherits Kimi's hard stop accidentally.
7578
7772
  */
7579
7773
  function createExactRepeatBreaker(options) {
7580
7774
  const sessions = /* @__PURE__ */ new Map();
7581
7775
  const maxSessions = options.maxSessions ?? 256;
7582
7776
  const exempt = new Set(options.exemptTools ?? TOOL_RUNAWAY_EXEMPT_TOOLS);
7777
+ const errorAndPollingThreshold = options.errorAndPollingThreshold ?? 3;
7583
7778
  const stateOf = (sessionId) => {
7584
7779
  let state = sessions.get(sessionId);
7585
7780
  if (state === void 0) state = {
7586
7781
  tracker: createExactRepeatTracker(),
7587
7782
  count: 0,
7588
- handoffActive: false
7783
+ handoffActive: false,
7784
+ errorStreaks: /* @__PURE__ */ new Map(),
7785
+ pollingStreaks: /* @__PURE__ */ new Map()
7589
7786
  };
7590
7787
  sessions.delete(sessionId);
7591
7788
  sessions.set(sessionId, state);
@@ -7595,11 +7792,26 @@ function createExactRepeatBreaker(options) {
7595
7792
  }
7596
7793
  return state;
7597
7794
  };
7795
+ const updateErrorStreaks = (state, toolName, observation) => {
7796
+ if (observation.isError === true) {
7797
+ const key = `${toolName}\u0000${observation.errorCode ?? normalizeToolErrorFamily(observation.errorText)}`;
7798
+ const previous = state.errorStreaks.get(key);
7799
+ const count = previous === void 0 ? 1 : previous.count + 1;
7800
+ state.errorStreaks.set(key, {
7801
+ toolName,
7802
+ count
7803
+ });
7804
+ return count;
7805
+ }
7806
+ for (const [key, entry] of [...state.errorStreaks]) if (entry.toolName === toolName) state.errorStreaks.delete(key);
7807
+ return 0;
7808
+ };
7598
7809
  return {
7599
7810
  checkBeforeExecute(sessionId, toolName, args) {
7600
7811
  if (options.forceStopAt === void 0) return void 0;
7601
7812
  const state = stateOf(sessionId);
7602
7813
  if (state.handoffActive) return options.handoffVeto ?? options.handoffReminder;
7814
+ if (POLLING_TOOL_NAMES.includes(toolName)) return void 0;
7603
7815
  const key = canonicalToolCallKey(toolName, args);
7604
7816
  if (state.tracker.current()?.key === key && state.count + 1 >= options.forceStopAt) {
7605
7817
  state.count += 1;
@@ -7607,16 +7819,37 @@ function createExactRepeatBreaker(options) {
7607
7819
  return options.handoffVeto ?? options.handoffReminder;
7608
7820
  }
7609
7821
  },
7610
- recordAfterExecute(sessionId, toolName, args) {
7822
+ recordAfterExecute(sessionId, toolName, args, observation) {
7611
7823
  if (exempt.has(toolName)) return void 0;
7612
7824
  const state = stateOf(sessionId);
7613
7825
  if (state.handoffActive) return options.handoffReminder ?? options.reminder(state.count);
7826
+ if (POLLING_TOOL_NAMES.includes(toolName) && observation !== void 0) {
7827
+ const errorCount = updateErrorStreaks(state, toolName, observation);
7828
+ const isPolling = isPollingObservation(toolName, args);
7829
+ let pollCount = 0;
7830
+ if (isPolling) {
7831
+ const key = `${canonicalToolCallKey(toolName, args)}\u0000${observation.resultText ?? ""}`;
7832
+ const previous = state.pollingStreaks.get(toolName);
7833
+ pollCount = previous !== void 0 && previous.key === key ? previous.count + 1 : 1;
7834
+ state.pollingStreaks.set(toolName, {
7835
+ key,
7836
+ count: pollCount
7837
+ });
7838
+ } else state.pollingStreaks.delete(toolName);
7839
+ if (observation.isError === true && errorCount >= errorAndPollingThreshold) return renderSameErrorFamilyReminder(errorCount);
7840
+ if (isPolling && pollCount >= errorAndPollingThreshold) return renderPollingRepeatReminder(pollCount);
7841
+ return;
7842
+ }
7843
+ if (!POLLING_TOOL_NAMES.includes(toolName)) state.pollingStreaks.clear();
7614
7844
  state.count = state.tracker.observe(toolName, args).count;
7615
7845
  if (options.forceStopAt !== void 0 && state.count >= options.forceStopAt) {
7616
7846
  state.handoffActive = true;
7617
7847
  return options.handoffReminder ?? options.reminder(state.count);
7618
7848
  }
7619
- return options.reminder(state.count);
7849
+ const errorCount = observation !== void 0 ? updateErrorStreaks(state, toolName, observation) : 0;
7850
+ const exactReminder = options.reminder(state.count);
7851
+ if (exactReminder !== void 0) return exactReminder;
7852
+ if (errorCount >= errorAndPollingThreshold) return renderSameErrorFamilyReminder(errorCount);
7620
7853
  },
7621
7854
  resetSession(sessionId) {
7622
7855
  sessions.delete(sessionId);
@@ -10192,7 +10425,7 @@ var ResponsesClient = class {
10192
10425
  release = opened.release;
10193
10426
  break;
10194
10427
  } catch (error) {
10195
- if (error instanceof LlmError && (error.code === "NOT_FOUND" || error.status === 404)) {
10428
+ if (error instanceof LlmError$1 && (error.code === "NOT_FOUND" || error.status === 404)) {
10196
10429
  const fallback = resolveCodexFallbackModel(currentModel);
10197
10430
  if (fallback && fallback.id !== currentModel) {
10198
10431
  currentModel = fallback.id;
@@ -10318,7 +10551,7 @@ var ResponsesClient = class {
10318
10551
  await pool.markAuthFailed(account.id, error instanceof Error ? error.message : "ChatGPT sign-in expired.").catch(() => void 0);
10319
10552
  free();
10320
10553
  if (await pool.hasAnotherAvailableAccount(tried)) continue;
10321
- throw new LlmError("ChatGPT sign-in has expired. Sign in again.", "AUTH", {
10554
+ throw new LlmError$1("ChatGPT sign-in has expired. Sign in again.", "AUTH", {
10322
10555
  status: 401,
10323
10556
  cause: error
10324
10557
  });
@@ -10330,7 +10563,7 @@ var ResponsesClient = class {
10330
10563
  await pool.markCooldown(account.id, after ?? DEFAULT_POOL_COOLDOWN_MS, "Codex 429").catch(() => void 0);
10331
10564
  free();
10332
10565
  if (await pool.hasAnotherAvailableAccount(tried)) continue;
10333
- throw new LlmError("Codex rate limit reached.", "RATE_LIMIT", {
10566
+ throw new LlmError$1("Codex rate limit reached.", "RATE_LIMIT", {
10334
10567
  status: 429,
10335
10568
  ...after === void 0 ? {} : { providerRetryAfterMs: after }
10336
10569
  });
@@ -10379,7 +10612,7 @@ var ResponsesClient = class {
10379
10612
  continue;
10380
10613
  }
10381
10614
  const chain = errorChain(cause).trim();
10382
- throw new LlmError(`Codex request failed: ${chain === "" ? "the connection failed before any response arrived" : chain.slice(0, 500)}${isPreConnectionFailure$2(cause) ? " The request never reached ChatGPT. Check the network, proxy/VPN/TUN, or the plugin proxy settings." : ""}`, "NETWORK", { cause });
10615
+ throw new LlmError$1(`Codex request failed: ${chain === "" ? "the connection failed before any response arrived" : chain.slice(0, 500)}${isPreConnectionFailure$2(cause) ? " The request never reached ChatGPT. Check the network, proxy/VPN/TUN, or the plugin proxy settings." : ""}`, "NETWORK", { cause });
10383
10616
  }
10384
10617
  }
10385
10618
  };
@@ -10425,10 +10658,10 @@ function isPreConnectionFailure$2(error) {
10425
10658
  * so retrying can neither repeat committed output nor re-run a tool.
10426
10659
  */
10427
10660
  function streamFailure$2(error, signal) {
10428
- if (error instanceof LlmError) return error;
10429
- if (signal?.aborted) return new LlmError("Codex request aborted", "ABORTED", { cause: error });
10661
+ if (error instanceof LlmError$1) return error;
10662
+ if (signal?.aborted) return new LlmError$1("Codex request aborted", "ABORTED", { cause: error });
10430
10663
  const chain = errorChain(error).trim();
10431
- return new LlmError(`Codex stream failed: ${chain === "" ? "the response stream ended unexpectedly" : chain.slice(0, 500)}`, "TRANSPORT", { cause: error });
10664
+ return new LlmError$1(`Codex stream failed: ${chain === "" ? "the response stream ended unexpectedly" : chain.slice(0, 500)}`, "TRANSPORT", { cause: error });
10432
10665
  }
10433
10666
  /**
10434
10667
  * Prompt cache key for one conversation.
@@ -10452,7 +10685,7 @@ function perRequestNonce() {
10452
10685
  return requestCounter;
10453
10686
  }
10454
10687
  async function* parseResponsesStream(response, signal, _legacyHiddenSandboxControls = /* @__PURE__ */ new Set(), activity) {
10455
- if (response.body === null) throw new LlmError("Codex returned no response stream.", "PROVIDER_ERROR");
10688
+ if (response.body === null) throw new LlmError$1("Codex returned no response stream.", "PROVIDER_ERROR");
10456
10689
  const reader = response.body.getReader();
10457
10690
  const abortReader = () => {
10458
10691
  reader.cancel(signal?.reason).catch(() => void 0);
@@ -10648,7 +10881,7 @@ async function* parseResponsesStream(response, signal, _legacyHiddenSandboxContr
10648
10881
  const message = string(error?.message) ?? "Codex generation failed.";
10649
10882
  const rawCode = string(error?.code)?.toLowerCase();
10650
10883
  const isOverload = message.toLowerCase().includes("overload") || message.toLowerCase().includes("server error") || rawCode === "server_error" || rawCode === "service_unavailable" || rawCode === "internal_error";
10651
- throw new LlmError(message, message.toLowerCase().includes("rate limit") || rawCode === "rate_limit" ? "RATE_LIMIT" : isOverload ? "SERVER_ERROR" : isContextOverflow(error) ? CONTEXT_OVERFLOW_CODE : string(error?.code)?.toUpperCase() ?? "PROVIDER_ERROR");
10884
+ throw new LlmError$1(message, message.toLowerCase().includes("rate limit") || rawCode === "rate_limit" ? "RATE_LIMIT" : isOverload ? "SERVER_ERROR" : isContextOverflow(error) ? CONTEXT_OVERFLOW_CODE : string(error?.code)?.toUpperCase() ?? "PROVIDER_ERROR");
10652
10885
  }
10653
10886
  };
10654
10887
  try {
@@ -10668,7 +10901,7 @@ async function* parseResponsesStream(response, signal, _legacyHiddenSandboxContr
10668
10901
  try {
10669
10902
  event = JSON.parse(data);
10670
10903
  } catch {
10671
- throw new LlmError("Codex returned malformed streaming JSON.", "PROTOCOL_ERROR");
10904
+ throw new LlmError$1("Codex returned malformed streaming JSON.", "PROTOCOL_ERROR");
10672
10905
  }
10673
10906
  const valueRecord = record$3(event);
10674
10907
  if (valueRecord !== null) yield* consume(valueRecord);
@@ -10679,7 +10912,7 @@ async function* parseResponsesStream(response, signal, _legacyHiddenSandboxContr
10679
10912
  reader.releaseLock();
10680
10913
  }
10681
10914
  if (signal?.aborted) throw signal.reason ?? new DOMException("Aborted", "AbortError");
10682
- if (terminal === null) throw new LlmError("Codex stream ended before a terminal event.", "PROTOCOL_ERROR");
10915
+ if (terminal === null) throw new LlmError$1("Codex stream ended before a terminal event.", "PROTOCOL_ERROR");
10683
10916
  const finalReason = terminal;
10684
10917
  if (reasoningIndex !== null) {
10685
10918
  if (pendingReasoningDelta !== "") {
@@ -10715,7 +10948,7 @@ async function* parseResponsesStream(response, signal, _legacyHiddenSandboxContr
10715
10948
  const replayedToolCallIds = new Set(replayOutput.flatMap((item) => item.type === "function_call" && typeof item.call_id === "string" ? [item.call_id] : []));
10716
10949
  for (const tool of tools.values()) {
10717
10950
  if (!tool.started) continue;
10718
- if (!isSafeJsonArguments(tool.arguments) || tool.name === "") throw new LlmError(`Codex returned invalid JSON arguments for tool ${tool.name || "(unnamed)"}.`, "INVALID_TOOL_ARGUMENTS");
10951
+ if (!isSafeJsonArguments(tool.arguments) || tool.name === "") throw new LlmError$1(`Codex returned invalid JSON arguments for tool ${tool.name || "(unnamed)"}.`, "INVALID_TOOL_ARGUMENTS");
10719
10952
  validToolCount++;
10720
10953
  if (!replayedToolCallIds.has(tool.id)) {
10721
10954
  replayOutput.push({
@@ -10772,7 +11005,7 @@ function incompleteFinishReason(response) {
10772
11005
  if (reason === "steered") return { kind: "stop" };
10773
11006
  const detail = JSON.stringify(reason);
10774
11007
  const message = string(record$3(response?.error)?.message);
10775
- throw new LlmError(`Codex returned an incomplete response (${detail})${message ? `: ${message}` : "."}`, reason === "content_filter" ? "CONTENT_FILTER" : "PROVIDER_INCOMPLETE");
11008
+ throw new LlmError$1(`Codex returned an incomplete response (${detail})${message ? `: ${message}` : "."}`, reason === "content_filter" ? "CONTENT_FILTER" : "PROVIDER_INCOMPLETE");
10776
11009
  }
10777
11010
  function visibleReasoningDelta(delta, currentVisibleChars, alreadyTruncated) {
10778
11011
  if (delta === "" || alreadyTruncated) return {
@@ -10834,12 +11067,12 @@ async function responseError(response) {
10834
11067
  ...requestId ? { requestId: ProviderRequestId(requestId) } : {},
10835
11068
  ...response.status === 429 ? { providerRetryAfterMs: retryAfterMs$1(response.headers) } : {}
10836
11069
  };
10837
- if (isHttpContextOverflow(response.status, detail)) return new LlmError(`Codex context window exceeded: ${detail}`, CONTEXT_OVERFLOW_CODE, options);
10838
- if (response.status === 401) return new LlmError("ChatGPT sign-in has expired. Sign in again.", "AUTH", options);
10839
- if (response.status === 404) return new LlmError(`Codex model or resource not found (${response.status})${detail ? `: ${detail}` : "."}`, "NOT_FOUND", options);
10840
- if (response.status === 429) return new LlmError("Codex rate limit reached.", "RATE_LIMIT", options);
10841
- if (response.status >= 500) return new LlmError(`Codex service error (${response.status}).`, "SERVER_ERROR", options);
10842
- return new LlmError(`Codex request failed (${response.status})${detail ? `: ${detail}` : "."}`, "PROVIDER_ERROR", options);
11070
+ if (isHttpContextOverflow(response.status, detail)) return new LlmError$1(`Codex context window exceeded: ${detail}`, CONTEXT_OVERFLOW_CODE, options);
11071
+ if (response.status === 401) return new LlmError$1("ChatGPT sign-in has expired. Sign in again.", "AUTH", options);
11072
+ if (response.status === 404) return new LlmError$1(`Codex model or resource not found (${response.status})${detail ? `: ${detail}` : "."}`, "NOT_FOUND", options);
11073
+ if (response.status === 429) return new LlmError$1("Codex rate limit reached.", "RATE_LIMIT", options);
11074
+ if (response.status >= 500) return new LlmError$1(`Codex service error (${response.status}).`, "SERVER_ERROR", options);
11075
+ return new LlmError$1(`Codex request failed (${response.status})${detail ? `: ${detail}` : "."}`, "PROVIDER_ERROR", options);
10843
11076
  }
10844
11077
  /**
10845
11078
  * Concatenated assistant text a non-delta `message` output item carries, which
@@ -19621,7 +19854,7 @@ function reclassifyInBandError(thrown, rawError, classify, statusFor = inBandAnt
19621
19854
  if (status === null) return thrown;
19622
19855
  const failure = classify(status, JSON.stringify({ error: rawError }));
19623
19856
  if (!failure.retryable) return thrown;
19624
- return new LlmError(thrown.message, failure.code, { cause: thrown });
19857
+ return new LlmError$1(thrown.message, failure.code, { cause: thrown });
19625
19858
  }
19626
19859
  /**
19627
19860
  * {@link reclassifyInBandError} for a line whose classifier reads a status, fed
@@ -19644,7 +19877,7 @@ function reclassifyInBandResponsesError(thrown, rawError, message, classify) {
19644
19877
  message
19645
19878
  }));
19646
19879
  if (!failure.retryable) return thrown;
19647
- return new LlmError(thrown.message, failure.code, { cause: thrown });
19880
+ return new LlmError$1(thrown.message, failure.code, { cause: thrown });
19648
19881
  }
19649
19882
  /** The wire `error` object of an in-band event, read defensively. */
19650
19883
  function readErrorType(error) {
@@ -20064,7 +20297,7 @@ var CommandCodeAdapter = class extends LlmAdapter {
20064
20297
  }));
20065
20298
  }
20066
20299
  async resolveModel(provider, modelId, signal) {
20067
- if (signal?.aborted) throw new LlmError("Command Code model resolution aborted", "ABORTED");
20300
+ if (signal?.aborted) throw new LlmError$1("Command Code model resolution aborted", "ABORTED");
20068
20301
  const settings = await this.settings();
20069
20302
  const entry = (await this.catalog()).find((model) => model.id === modelId);
20070
20303
  const efforts = reasoningEffortsFor$1(modelId);
@@ -20133,7 +20366,7 @@ var CommandCodeAdapter = class extends LlmAdapter {
20133
20366
  let apiEnv;
20134
20367
  if (pool === null) {
20135
20368
  const credentials = await this.store.read();
20136
- if (credentials === null) throw new LlmError(`Not signed in to ${PROVIDER_NAME$11}. Sign in from Settings > Command Code, or paste an API key there.`, "MISSING_CREDENTIAL");
20369
+ if (credentials === null) throw new LlmError$1(`Not signed in to ${PROVIDER_NAME$11}. Sign in from Settings > Command Code, or paste an API key there.`, "MISSING_CREDENTIAL");
20137
20370
  apiKey = credentials.apiKey;
20138
20371
  apiEnv = credentials.apiEnv ?? resolveApiEnv();
20139
20372
  } else {
@@ -20163,13 +20396,13 @@ var CommandCodeAdapter = class extends LlmAdapter {
20163
20396
  });
20164
20397
  activity?.pulse();
20165
20398
  } catch (error) {
20166
- if (signal.aborted) throw new LlmError("Command Code request aborted", "ABORTED", { cause: error });
20167
- throw new LlmError(`Command Code request failed: ${error instanceof Error ? error.message : String(error)}`, "TRANSPORT", { cause: error });
20399
+ if (signal.aborted) throw new LlmError$1("Command Code request aborted", "ABORTED", { cause: error });
20400
+ throw new LlmError$1(`Command Code request failed: ${error instanceof Error ? error.message : String(error)}`, "TRANSPORT", { cause: error });
20168
20401
  }
20169
20402
  if (response.ok) break;
20170
20403
  detail = (await response.text().catch(() => "")).slice(0, 600);
20171
20404
  if (response.status === 422) {
20172
- if (detail.includes("cmd_zdr_no_providers")) throw new LlmError(`${PROVIDER_NAME$11} rejected request under Zero Data Retention: no ZDR-capable upstream is available for this model (${detail || "cmd_zdr_no_providers"}).`, "PROVIDER_ERROR", { status: 422 });
20405
+ if (detail.includes("cmd_zdr_no_providers")) throw new LlmError$1(`${PROVIDER_NAME$11} rejected request under Zero Data Retention: no ZDR-capable upstream is available for this model (${detail || "cmd_zdr_no_providers"}).`, "PROVIDER_ERROR", { status: 422 });
20173
20406
  break;
20174
20407
  }
20175
20408
  if (pool === null || accountId === void 0) break;
@@ -20191,22 +20424,22 @@ var CommandCodeAdapter = class extends LlmAdapter {
20191
20424
  const status = response?.status ?? 500;
20192
20425
  const { code } = classifyCommandCodeFailure(status, detail);
20193
20426
  if (status === 422) {
20194
- if (detail.includes("cmd_zdr_no_providers")) throw new LlmError(`${PROVIDER_NAME$11} rejected request under Zero Data Retention: no ZDR-capable upstream is available for this model (${detail || "cmd_zdr_no_providers"}).`, code, { status: 422 });
20195
- throw new LlmError(`${PROVIDER_NAME$11} validation error (422): ${detail || "Unprocessable Entity"}`, code, { status: 422 });
20427
+ if (detail.includes("cmd_zdr_no_providers")) throw new LlmError$1(`${PROVIDER_NAME$11} rejected request under Zero Data Retention: no ZDR-capable upstream is available for this model (${detail || "cmd_zdr_no_providers"}).`, code, { status: 422 });
20428
+ throw new LlmError$1(`${PROVIDER_NAME$11} validation error (422): ${detail || "Unprocessable Entity"}`, code, { status: 422 });
20196
20429
  }
20197
- if (isCommandCodeModelAccessDenied(status, detail)) throw new LlmError(`${PROVIDER_NAME$11} access denied for model ${options.model}: this model is not included in the plan or requires higher entitlement (${status}).${detail ? ` ${detail}` : ""}`, code, { status });
20198
- if (isCommandCodeCredentialInvalid(status, detail) || status === 401) throw new LlmError(`${PROVIDER_NAME$11} rejected the stored API key (${status}). Sign in again from Settings > Command Code.${detail ? ` ${detail}` : ""}`, code, { status });
20430
+ if (isCommandCodeModelAccessDenied(status, detail)) throw new LlmError$1(`${PROVIDER_NAME$11} access denied for model ${options.model}: this model is not included in the plan or requires higher entitlement (${status}).${detail ? ` ${detail}` : ""}`, code, { status });
20431
+ if (isCommandCodeCredentialInvalid(status, detail) || status === 401) throw new LlmError$1(`${PROVIDER_NAME$11} rejected the stored API key (${status}). Sign in again from Settings > Command Code.${detail ? ` ${detail}` : ""}`, code, { status });
20199
20432
  if (status === 429) {
20200
20433
  const after = response === void 0 ? void 0 : retryAfterMs$1(response.headers);
20201
- throw new LlmError(`${PROVIDER_NAME$11} rate limit or plan quota reached (429). Check the quota card in Settings > Command Code.${detail ? ` ${detail}` : ""}`, code, {
20434
+ throw new LlmError$1(`${PROVIDER_NAME$11} rate limit or plan quota reached (429). Check the quota card in Settings > Command Code.${detail ? ` ${detail}` : ""}`, code, {
20202
20435
  status: 429,
20203
20436
  ...after === void 0 ? {} : { providerRetryAfterMs: after }
20204
20437
  });
20205
20438
  }
20206
- if (status >= 500) throw new LlmError(`${PROVIDER_NAME$11} upstream server error (${status}): ${detail || "No response"}`, code, { status });
20207
- throw new LlmError(`${PROVIDER_NAME$11} API error (${status}): ${detail || "No response"}`, code, { status });
20439
+ if (status >= 500) throw new LlmError$1(`${PROVIDER_NAME$11} upstream server error (${status}): ${detail || "No response"}`, code, { status });
20440
+ throw new LlmError$1(`${PROVIDER_NAME$11} API error (${status}): ${detail || "No response"}`, code, { status });
20208
20441
  }
20209
- if (response.body === null) throw new LlmError("Command Code returned an empty response body", "PROVIDER_ERROR");
20442
+ if (response.body === null) throw new LlmError$1("Command Code returned an empty response body", "PROVIDER_ERROR");
20210
20443
  const reader = response.body.getReader();
20211
20444
  const decoder = new TextDecoder();
20212
20445
  const state = createStreamState$7(wire);
@@ -20252,7 +20485,7 @@ var CommandCodeAdapter = class extends LlmAdapter {
20252
20485
  }
20253
20486
  } catch (error) {
20254
20487
  const inBand = state.streamError;
20255
- if (error instanceof LlmError && !outputStarted && inBand !== void 0 && error.code === "PROVIDER_ERROR") {
20488
+ if (error instanceof LlmError$1 && !outputStarted && inBand !== void 0 && error.code === "PROVIDER_ERROR") {
20256
20489
  const reclassified = reclassifyInBandStreamError(error, inBand);
20257
20490
  if (reclassified.code === "RATE_LIMIT" && pool !== null && accountId !== void 0) {
20258
20491
  const after = retryAfterMs$1(response.headers);
@@ -20274,10 +20507,10 @@ var CommandCodeAdapter = class extends LlmAdapter {
20274
20507
  * body-read failure as TRANSPORT and retain its cause chain in the message.
20275
20508
  */
20276
20509
  function streamFailure$1(error, signal) {
20277
- if (error instanceof LlmError) return error;
20278
- if (signal.aborted) return new LlmError("Command Code stream aborted", "ABORTED", { cause: error });
20510
+ if (error instanceof LlmError$1) return error;
20511
+ if (signal.aborted) return new LlmError$1("Command Code stream aborted", "ABORTED", { cause: error });
20279
20512
  const chain = errorChain(error).trim();
20280
- return new LlmError(`Command Code stream failed: ${chain === "" ? "the response stream ended unexpectedly" : chain.slice(0, 500)}`, "TRANSPORT", { cause: error });
20513
+ return new LlmError$1(`Command Code stream failed: ${chain === "" ? "the response stream ended unexpectedly" : chain.slice(0, 500)}`, "TRANSPORT", { cause: error });
20281
20514
  }
20282
20515
  /**
20283
20516
  * The error one recorded in-band failure becomes, or the mapper's own verdict.
@@ -22784,7 +23017,7 @@ var OllamaAdapter = class extends LlmAdapter {
22784
23017
  }));
22785
23018
  }
22786
23019
  async resolveModel(provider, modelId, signal) {
22787
- if (signal?.aborted) throw new LlmError("Ollama model resolution aborted", "ABORTED");
23020
+ if (signal?.aborted) throw new LlmError$1("Ollama model resolution aborted", "ABORTED");
22788
23021
  const settings = await this.settings();
22789
23022
  const entry = (await this.catalog()).find((model) => model.id === modelId);
22790
23023
  const declared = signal?.aborted ? void 0 : await this.thinkingCapability(modelId);
@@ -22852,7 +23085,7 @@ var OllamaAdapter = class extends LlmAdapter {
22852
23085
  let credentials;
22853
23086
  if (pool === null) {
22854
23087
  const stored = await this.store.read();
22855
- if (stored === null) throw new LlmError(`No ${PROVIDER_NAME$10} API key configured. Add one from Settings > ${PROVIDER_NAME$10} (create a key at https://ollama.com/settings/keys).`, "MISSING_CREDENTIAL");
23088
+ if (stored === null) throw new LlmError$1(`No ${PROVIDER_NAME$10} API key configured. Add one from Settings > ${PROVIDER_NAME$10} (create a key at https://ollama.com/settings/keys).`, "MISSING_CREDENTIAL");
22856
23089
  credentials = stored;
22857
23090
  } else {
22858
23091
  const effective = await pool.getEffectiveCredential(tried, fetchFn);
@@ -22913,9 +23146,9 @@ var OllamaAdapter = class extends LlmAdapter {
22913
23146
  break;
22914
23147
  }
22915
23148
  const status = lastStatus;
22916
- if (status === 401 || status === 403) throw new LlmError(`${PROVIDER_NAME$10} rejected the API key (${status}). Replace it from Settings > ${PROVIDER_NAME$10}.${lastDetail ? ` ${lastDetail}` : ""}`, "INVALID_CREDENTIAL", { status });
22917
- if (status === 429) throw new LlmError(`${PROVIDER_NAME$10} rate limit or plan quota reached (429). Add another key, or wait for the cooldown shown in Settings > ${PROVIDER_NAME$10}.${lastDetail ? ` ${lastDetail}` : ""}`, "RATE_LIMIT", { status: 429 });
22918
- throw new LlmError(`${PROVIDER_NAME$10} request failed${status === void 0 ? "" : ` (${status})`}.${lastDetail}`, lastInBandCode ?? (status !== void 0 && status >= 500 ? "SERVER" : "INVALID_REQUEST"), status === void 0 ? {} : { status });
23149
+ if (status === 401 || status === 403) throw new LlmError$1(`${PROVIDER_NAME$10} rejected the API key (${status}). Replace it from Settings > ${PROVIDER_NAME$10}.${lastDetail ? ` ${lastDetail}` : ""}`, "INVALID_CREDENTIAL", { status });
23150
+ if (status === 429) throw new LlmError$1(`${PROVIDER_NAME$10} rate limit or plan quota reached (429). Add another key, or wait for the cooldown shown in Settings > ${PROVIDER_NAME$10}.${lastDetail ? ` ${lastDetail}` : ""}`, "RATE_LIMIT", { status: 429 });
23151
+ throw new LlmError$1(`${PROVIDER_NAME$10} request failed${status === void 0 ? "" : ` (${status})`}.${lastDetail}`, lastInBandCode ?? (status !== void 0 && status >= 500 ? "SERVER" : "INVALID_REQUEST"), status === void 0 ? {} : { status });
22919
23152
  }
22920
23153
  };
22921
23154
  /**
@@ -24896,11 +25129,21 @@ var McpBridge = class {
24896
25129
  await new Promise((resolve) => {
24897
25130
  this.pendingResponses.set(callId, resolve);
24898
25131
  }).then((outcome) => {
25132
+ const images = outcome.images ?? [];
25133
+ const content = images.length > 0 && outcome.text === "" ? [{
25134
+ type: "text",
25135
+ text: "[tool result carried an image]"
25136
+ }] : [{
25137
+ type: "text",
25138
+ text: outcome.text
25139
+ }];
25140
+ for (const image of images) content.push({
25141
+ type: "image",
25142
+ data: image.data,
25143
+ mimeType: image.mediaType
25144
+ });
24899
25145
  respond(response, 200, jsonRpcResult(id, {
24900
- content: [{
24901
- type: "text",
24902
- text: outcome.text
24903
- }],
25146
+ content,
24904
25147
  ...outcome.isError ? { isError: true } : {}
24905
25148
  }));
24906
25149
  });
@@ -25038,7 +25281,7 @@ const ACP_ERROR_CODES = {
25038
25281
  */
25039
25282
  function acpError(code, detail) {
25040
25283
  const base = ACP_ERROR_CODES[code];
25041
- return new LlmError(detail === void 0 ? base : `${base} ${detail}`, code);
25284
+ return new LlmError$1(detail === void 0 ? base : `${base} ${detail}`, code);
25042
25285
  }
25043
25286
  //#endregion
25044
25287
  //#region src/host/antigravity-acp/history.ts
@@ -25247,25 +25490,29 @@ function isEffort(value) {
25247
25490
  * - `availableModels` - the tier ids the model picker itself shows
25248
25491
  * (`gemini-4-carbon-low`).
25249
25492
  *
25250
- * A model's own ladder is the set of tier suffixes published for it, intersected
25251
- * with the levels the server separately accepts. A model with no suffixes
25252
- * (its id already carries the tier, such as `gpt-oss-120b-medium`) publishes no
25253
- * ladder, and this function says so with an empty list rather than borrowing a
25254
- * global one: `reasoning` is then simply not offered for it.
25493
+ * A model's own ladder is the set of tier suffixes published for it. A model
25494
+ * with no suffixes (its id already carries the tier, such as
25495
+ * `gpt-oss-120b-medium`) publishes no ladder, and this function says so with an
25496
+ * empty list rather than borrowing a global one: `reasoning` is then simply not
25497
+ * offered for it.
25498
+ *
25499
+ * The `thought_level` option is deliberately NOT consulted here. That option
25500
+ * describes the levels of whichever model the session currently has selected -
25501
+ * Argon publishes low/medium/high - so intersecting every model's ladder with
25502
+ * it silently dropped the fourth level a newer model publishes for itself
25503
+ * (`gemini-4-hydrogen-xhigh` never reached the picker).
25255
25504
  *
25256
25505
  * @param options - The `model` option values, in server order.
25257
25506
  * @param availableModels - The tier ids, in server order.
25258
- * @param acceptedLevels - Levels the server's `thought_level` option accepts; empty when it published none.
25259
25507
  * @returns One entry per selectable model, with its ladder least to greatest.
25260
25508
  */
25261
- function collapseModels(options, availableModels, acceptedLevels) {
25509
+ function collapseModels(options, availableModels) {
25262
25510
  const byBase = /* @__PURE__ */ new Map();
25263
25511
  for (const option of options) for (const candidate of availableModels) {
25264
25512
  const id = candidate.modelId;
25265
25513
  if (!id.startsWith(option.value + "-")) continue;
25266
25514
  const suffix = id.slice(option.value.length + 1);
25267
25515
  if (!isEffort(suffix)) continue;
25268
- if (acceptedLevels.length > 0 && !acceptedLevels.includes(suffix)) continue;
25269
25516
  const levels = byBase.get(option.value) ?? /* @__PURE__ */ new Set();
25270
25517
  levels.add(suffix);
25271
25518
  byBase.set(option.value, levels);
@@ -25517,7 +25764,7 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
25517
25764
  const images = await resolveRequestImages$1(options, this.options.attachments, signal).catch(() => NO_RESOLVED_IMAGES$3);
25518
25765
  const effort = options.reasoningEffort === void 0 ? settings.defaultReasoningEffort ?? void 0 : String(options.reasoningEffort);
25519
25766
  const live = this.live.get(dshSessionId);
25520
- if (live !== void 0 && live.model === options.model && live.effort === effort && canContinue(options.messages, live.covered, live.fingerprint)) return this.continueTurn(live, options, signal, activity);
25767
+ if (live !== void 0 && live.model === options.model && live.effort === effort && canContinue(options.messages, live.covered, live.fingerprint)) return this.continueTurn(live, options, images, signal, activity);
25521
25768
  if (live !== void 0) await this.closeTurn(live);
25522
25769
  return this.startTurn(dshSessionId, options, settings, images, effort, signal, activity);
25523
25770
  }
@@ -25540,8 +25787,7 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
25540
25787
  } else client = this.spawn(launch, queue, activity);
25541
25788
  const descriptor = await bridge.start();
25542
25789
  const sessionId = await this.openSession(client, options, [descriptor], settings);
25543
- if (effort !== void 0) await this.applyConfigQuietly(client, sessionId, "thought_level", effort);
25544
- await this.applyConfig(client, sessionId, "model", options.model);
25790
+ await this.applyModelAndEffort(client, sessionId, options.model, effort);
25545
25791
  const prompt = buildPrompt(options, images, 0);
25546
25792
  if ((options.tools ?? []).length > 0) prompt.blocks.unshift({
25547
25793
  type: "text",
@@ -25559,6 +25805,8 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
25559
25805
  queue,
25560
25806
  settled: void 0,
25561
25807
  surfaced: /* @__PURE__ */ new Set(),
25808
+ notedNative: /* @__PURE__ */ new Set(),
25809
+ nativeToolPolicy: settings.nativeToolPolicy,
25562
25810
  startedAt: this.now(),
25563
25811
  awaitingHarness: false,
25564
25812
  sessionsUsed: reusedSessions + 1
@@ -25574,8 +25822,8 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
25574
25822
  }
25575
25823
  }
25576
25824
  /** Continue the live turn after the harness executed its tools. */
25577
- continueTurn(turn, options, signal, activity) {
25578
- const results = collectToolResults(options.messages.slice(turn.covered));
25825
+ continueTurn(turn, options, images, signal, activity) {
25826
+ const results = collectToolResults(options.messages.slice(turn.covered), images);
25579
25827
  for (const callId of [...turn.surfaced]) {
25580
25828
  const outcome = results.get(callId);
25581
25829
  turn.bridge.settle(callId, outcome === void 0 ? {
@@ -25690,8 +25938,31 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
25690
25938
  }
25691
25939
  continue;
25692
25940
  }
25693
- if (type === "tool_call") assertNoNativeTool(update);
25694
- if (type === "tool_call_update") assertNoNativeTool(update);
25941
+ if (type === "tool_call" || type === "tool_call_update") {
25942
+ const native = readNativeToolCall(update);
25943
+ if (native !== void 0) {
25944
+ if (turn.nativeToolPolicy === "cancel") throw acpError("ACP_NATIVE_TOOLS_UNSUPPORTED", `Tool: ${native.name}.`);
25945
+ if (type === "tool_call" && !turn.notedNative.has(native.callId)) {
25946
+ turn.notedNative.add(native.callId);
25947
+ const note = nativeToolNote(native, readNativeToolArguments(update));
25948
+ if (textIndex === void 0) {
25949
+ textIndex = nextIndex;
25950
+ nextIndex += 1;
25951
+ yield {
25952
+ type: "block-start",
25953
+ index: textIndex,
25954
+ blockType: "text"
25955
+ };
25956
+ }
25957
+ text += note;
25958
+ yield {
25959
+ type: "text-delta",
25960
+ index: textIndex,
25961
+ text: note
25962
+ };
25963
+ }
25964
+ }
25965
+ }
25695
25966
  continue;
25696
25967
  }
25697
25968
  const parked = turn.bridge.takeParked();
@@ -25773,17 +26044,33 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
25773
26044
  }
25774
26045
  }
25775
26046
  }
26047
+ /**
26048
+ * Answer one `session/request_permission`.
26049
+ *
26050
+ * Two different requests arrive here and they do not deserve the same answer.
26051
+ * A request for a call the agent makes on the bridge is the agent asking to run
26052
+ * a DSH tool; the bridge already hands that call to the harness, which applies
26053
+ * its own permission presets, so refusing it here would deny the very route
26054
+ * this line exists to provide. A request for the agent's own tool is answered
26055
+ * by `permissionPolicy`, because nothing downstream of it is governed by DSH.
26056
+ *
26057
+ * @param params - The request payload, including the tool call it is about.
26058
+ * @returns The option id to select, or undefined to answer `cancelled`.
26059
+ */
26060
+ async answerPermission(params) {
26061
+ const options = readPermissionOptions(params);
26062
+ const answer = () => options.find((option) => option.kind === "allow_once")?.optionId ?? options.find((option) => option.kind === "allow_always")?.optionId;
26063
+ const toolCall = asRecord$19(params.toolCall);
26064
+ if ((typeof toolCall?.name === "string" ? toolCall.name : "").startsWith(`mcp_dsh-bridge_`)) return answer();
26065
+ return (await this.options.settings.read()).permissionPolicy === "allow" ? answer() : void 0;
26066
+ }
25776
26067
  spawn(launch, queue, activity) {
25777
26068
  const handlers = {
25778
26069
  onSessionUpdate: (_sessionId, update) => {
25779
26070
  queue.push(update);
25780
26071
  activity.pulse();
25781
26072
  },
25782
- onPermissionRequest: async (_sessionId, params) => {
25783
- if ((await this.options.settings.read()).permissionPolicy !== "allow") return void 0;
25784
- const options = readPermissionOptions(params);
25785
- return options.find((option) => option.kind === "allow_once")?.optionId ?? options.find((option) => option.kind === "allow_always")?.optionId;
25786
- },
26073
+ onPermissionRequest: async (_sessionId, params) => this.answerPermission(params),
25787
26074
  onExit: (detail) => {
25788
26075
  queue.push({
25789
26076
  sessionUpdate: "process_exit",
@@ -25841,15 +26128,41 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
25841
26128
  }
25842
26129
  async applyConfig(client, sessionId, configId, value) {
25843
26130
  try {
25844
- await client.request("session/set_config_option", {
26131
+ return asRecord$19(await client.request("session/set_config_option", {
25845
26132
  sessionId,
25846
26133
  configId,
25847
26134
  value
25848
- });
26135
+ }));
25849
26136
  } catch (error) {
25850
26137
  throw new LlmError(`Antigravity ACP rejected ${configId} "${value}": ${error instanceof Error ? error.message : String(error)}`, "UNSUPPORTED_OPTION");
25851
26138
  }
25852
26139
  }
26140
+ /**
26141
+ * Select the model, then the thinking level, falling back to the model variant
26142
+ * the server publishes for a level the current model does not list.
26143
+ *
26144
+ * `thought_level` is scoped to the model the session already has selected, so
26145
+ * it is applied after the model. The previous order set the level first and
26146
+ * replaced the model after it, which kept the level of the model the session
26147
+ * started on. Some models publish a level as a model variant instead of a
26148
+ * thinking level (`gemini-4-hydrogen-xhigh`): selecting that variant is what
26149
+ * makes the server accept the fourth level.
26150
+ *
26151
+ * @param client - The connection running this turn.
26152
+ * @param sessionId - The ACP session the turn belongs to.
26153
+ * @param model - The model the caller asked for.
26154
+ * @param effort - The requested thinking level, when the caller or settings named one.
26155
+ */
26156
+ async applyModelAndEffort(client, sessionId, model, effort) {
26157
+ const afterModel = await this.applyConfig(client, sessionId, "model", model);
26158
+ if (effort === void 0) return;
26159
+ const levels = configOptionValues(afterModel, "thought_level");
26160
+ if (levels === void 0 || levels.includes(effort)) {
26161
+ await this.applyConfigQuietly(client, sessionId, "thought_level", effort);
26162
+ return;
26163
+ }
26164
+ await this.applyConfigQuietly(client, sessionId, "model", `${model}-${effort}`);
26165
+ }
25853
26166
  async applyConfigQuietly(client, sessionId, configId, value) {
25854
26167
  await client.request("session/set_config_option", {
25855
26168
  sessionId,
@@ -25922,11 +26235,7 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
25922
26235
  queue.push(update);
25923
26236
  activity.pulse();
25924
26237
  },
25925
- onPermissionRequest: async (_sessionId, params) => {
25926
- if ((await this.options.settings.read()).permissionPolicy !== "allow") return void 0;
25927
- const options = readPermissionOptions(params);
25928
- return options.find((option) => option.kind === "allow_once")?.optionId ?? options.find((option) => option.kind === "allow_always")?.optionId;
25929
- },
26238
+ onPermissionRequest: async (_sessionId, params) => this.answerPermission(params),
25930
26239
  onExit: (detail) => {
25931
26240
  queue.push({
25932
26241
  sessionUpdate: "process_exit",
@@ -25997,15 +26306,43 @@ const BRIDGE_ONLY_INSTRUCTION = [
25997
26306
  "For every file read, file change, command or other action, call one of the provided tools instead.",
25998
26307
  "If no provided tool covers what you need, stop and say so rather than acting directly."
25999
26308
  ].join(" ");
26000
- /** Tool results keyed by the call id they answer, from the newly appended messages. */
26001
- function collectToolResults(messages) {
26309
+ /**
26310
+ * Tool results keyed by the call id they answer, from the newly appended messages.
26311
+ *
26312
+ * A result is not always text. `read_image` and a screenshot tool answer with an
26313
+ * image block, and keeping only the text half of that handed the agent an empty
26314
+ * string - a successful call it could not tell from a tool that returned
26315
+ * nothing. Image blocks are therefore resolved and carried back as MCP `image`
26316
+ * content; the byte budget is the same one the prompt uses, because both paths
26317
+ * end up inline in the agent's context.
26318
+ *
26319
+ * @param messages - The messages appended since the turn last handed work over.
26320
+ * @param images - Images resolved for this request, keyed by attachment id.
26321
+ * @returns One outcome per answered call id.
26322
+ */
26323
+ function collectToolResults(messages, images) {
26002
26324
  const results = /* @__PURE__ */ new Map();
26003
26325
  for (const message of messages) for (const block of message.content) {
26004
26326
  if (block.type !== "tool-result") continue;
26005
26327
  const result = block;
26006
26328
  const text = result.content.map((entry) => entry.type === "text" ? entry.text : "").filter((part) => part !== "").join("\n");
26329
+ const carried = [];
26330
+ let budget = ACP_MAX_INLINE_IMAGE_BYTES;
26331
+ for (const entry of result.content) {
26332
+ if (entry.type !== "image") continue;
26333
+ const inline = imageBlockToInline$2(entry, images);
26334
+ if (inline === void 0) continue;
26335
+ const bytes = Math.ceil(inline.data.length * .75);
26336
+ if (bytes > budget) continue;
26337
+ budget -= bytes;
26338
+ carried.push({
26339
+ mediaType: inline.mediaType,
26340
+ data: inline.data
26341
+ });
26342
+ }
26007
26343
  results.set(result.toolCallId, {
26008
26344
  text,
26345
+ ...carried.length === 0 ? {} : { images: carried },
26009
26346
  isError: result.isError === true
26010
26347
  });
26011
26348
  }
@@ -26014,32 +26351,78 @@ function collectToolResults(messages) {
26014
26351
  /**
26015
26352
  * Refuse the sampling controls ACP cannot express.
26016
26353
  *
26354
+ * `temperature` and `stop` change what the model produces, so accepting a request
26355
+ * that carries one and then ignoring it would answer a different question than
26356
+ * the caller asked. `maxTokens` is deliberately not in that set: it bounds an
26357
+ * answer the caller still reads in full, and the harness's own auxiliary calls
26358
+ * (session titles, compaction) always send one. Refusing it made every title on
26359
+ * this line fail; dropping it costs only the bound, and the bound is the one
26360
+ * thing ACP genuinely cannot express.
26361
+ *
26017
26362
  * @param options - The normalized request.
26018
26363
  */
26019
26364
  function assertNoSamplingControls(options) {
26020
26365
  const unsupported = [];
26021
26366
  if (options.temperature !== void 0) unsupported.push("temperature");
26022
- if (options.maxTokens !== void 0) unsupported.push("maxTokens");
26023
26367
  if (options.stop !== void 0 && options.stop.length > 0) unsupported.push("stop");
26024
26368
  if (unsupported.length === 0) return;
26025
- throw acpError("ACP_UNSUPPORTED_OPTION", `Unsupported: ${unsupported.join(", ")}. Antigravity through ACP has no sampling controls; choose a model variant instead of a token cap or stop sequence.`);
26369
+ throw acpError("ACP_UNSUPPORTED_OPTION", `Unsupported: ${unsupported.join(", ")}. Antigravity through ACP has no sampling controls; choose a model variant instead of a stop sequence.`);
26026
26370
  }
26027
26371
  /**
26028
- * Throw when one `tool_call` update names something other than the bridge.
26372
+ * Read one `tool_call`/`tool_call_update` as the agent's own tool, or as the bridge.
26029
26373
  *
26030
26374
  * The official server prefixes its MCP tool names with the server name it was
26031
- * given (`mcp_dsh-bridge_<tool>`); everything else is the agent's own tool.
26032
- * A completed native call has already happened by the time it is reported - the
26033
- * turn is cancelled and reported, and the user is told the action was outside
26034
- * this harness's control. That is the honest limit: ACP has no way to refuse a
26035
- * native tool in advance.
26375
+ * given (`mcp_dsh-bridge_<tool>`); everything else is the agent's own tool. What
26376
+ * the caller does with that answer depends on `nativeToolPolicy`: this function
26377
+ * only classifies, so the two policies share one definition of "native".
26036
26378
  *
26037
26379
  * @param update - One `session/update` payload.
26380
+ * @returns The call's id and name when it is a native call; undefined for the bridge.
26038
26381
  */
26039
- function assertNoNativeTool(update) {
26382
+ function readNativeToolCall(update) {
26040
26383
  const name = typeof update.name === "string" ? update.name : "";
26041
- if (name === "" || name.startsWith(`mcp_dsh-bridge_`)) return;
26042
- throw acpError("ACP_NATIVE_TOOLS_UNSUPPORTED", `Tool: ${name}.`);
26384
+ if (name === "" || name.startsWith(`mcp_dsh-bridge_`)) return void 0;
26385
+ return {
26386
+ callId: typeof update.toolCallId === "string" ? update.toolCallId : "",
26387
+ name
26388
+ };
26389
+ }
26390
+ /**
26391
+ * The transcript line that records one native tool call.
26392
+ *
26393
+ * Written into the answer rather than logged, because the user is the one who
26394
+ * has to know the action did not pass through DSH. It names the tool and its
26395
+ * arguments and nothing else: a note that paraphrased the arguments would be a
26396
+ * second, unverified account of what the agent did.
26397
+ *
26398
+ * @param native - The call being reported.
26399
+ * @param args - Its raw argument text, when the update carried one.
26400
+ * @returns One sentence, ending in a newline so the model's own text starts fresh.
26401
+ */
26402
+ function nativeToolNote(native, args) {
26403
+ return t("antigravityAcp.nativeTool", { call: args === "" ? native.name : `${native.name} ${args}` });
26404
+ }
26405
+ /**
26406
+ * The raw argument text one native call was reported with.
26407
+ *
26408
+ * ACP spells the arguments `rawInput` on `tool_call`, and the live server also
26409
+ * sends `title` (a one-line description of the action) rather than a JSON body.
26410
+ * Both are read, in that order, and neither is invented: a call reported without
26411
+ * either is shown by name alone.
26412
+ *
26413
+ * @param update - One `session/update` payload.
26414
+ * @returns The argument or title text, or an empty string when it carried none.
26415
+ */
26416
+ function readNativeToolArguments(update) {
26417
+ const raw = update.rawInput;
26418
+ if (typeof raw === "string" && raw !== "") return raw;
26419
+ if (typeof raw === "object" && raw !== null) try {
26420
+ return JSON.stringify(raw);
26421
+ } catch {
26422
+ return "";
26423
+ }
26424
+ const title = update.title;
26425
+ return typeof title === "string" ? title : "";
26043
26426
  }
26044
26427
  /**
26045
26428
  * Read one `usage_update` as context occupancy.
@@ -26175,6 +26558,27 @@ function delay(ms) {
26175
26558
  function asRecord$19(value) {
26176
26559
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
26177
26560
  }
26561
+ /**
26562
+ * The values one `session/set_config_option` result lists for a config option.
26563
+ *
26564
+ * @param result - The response payload, when the server sent one.
26565
+ * @param configId - Option id to read, such as `thought_level`.
26566
+ * @returns The accepted values, or undefined when the answer carried no options.
26567
+ */
26568
+ function configOptionValues(result, configId) {
26569
+ const options = result?.configOptions;
26570
+ if (!Array.isArray(options)) return void 0;
26571
+ for (const entry of options) {
26572
+ const record = asRecord$19(entry);
26573
+ if (record?.id !== configId) continue;
26574
+ const values = record.options;
26575
+ if (!Array.isArray(values)) return void 0;
26576
+ return values.flatMap((option) => {
26577
+ const value = asRecord$19(option)?.value;
26578
+ return typeof value === "string" ? [value] : [];
26579
+ });
26580
+ }
26581
+ }
26178
26582
  /** Where the settings document lives. */
26179
26583
  function antigravityAcpSettingsPath() {
26180
26584
  return path.join(dshHomeDir(), "storages", "antigravity-acp-settings.json");
@@ -26185,7 +26589,8 @@ function defaultAntigravityAcpSettings() {
26185
26589
  enabled: true,
26186
26590
  enabledModelIds: null,
26187
26591
  defaultReasoningEffort: null,
26188
- permissionPolicy: "reject",
26592
+ permissionPolicy: "allow",
26593
+ nativeToolPolicy: "allow",
26189
26594
  binaryPath: null
26190
26595
  };
26191
26596
  }
@@ -26194,7 +26599,9 @@ function defaultAntigravityAcpSettings() {
26194
26599
  *
26195
26600
  * A field that is present but of the wrong type is treated as absent rather than
26196
26601
  * as its zero value: a corrupt `enabledModelIds` must not become "every model
26197
- * off", and a corrupt `permissionPolicy` must not become "allow".
26602
+ * off", and a corrupt policy field falls back to that policy's own default
26603
+ * instead of to whichever value a `=== 'x' ? … : …` happens to have in the
26604
+ * negative branch.
26198
26605
  *
26199
26606
  * @param value - Parsed JSON.
26200
26607
  * @returns The settings the document describes, with defaults for anything unreadable.
@@ -26208,7 +26615,8 @@ function parseAntigravityAcpSettings(value) {
26208
26615
  enabled: typeof record.enabled === "boolean" ? record.enabled : false,
26209
26616
  enabledModelIds,
26210
26617
  defaultReasoningEffort: typeof record.defaultReasoningEffort === "string" ? record.defaultReasoningEffort : null,
26211
- permissionPolicy: record.permissionPolicy === "allow" ? "allow" : "reject",
26618
+ permissionPolicy: record.permissionPolicy === "reject" ? "reject" : "allow",
26619
+ nativeToolPolicy: record.nativeToolPolicy === "cancel" ? "cancel" : "allow",
26212
26620
  binaryPath: typeof record.binaryPath === "string" && record.binaryPath !== "" ? record.binaryPath : null,
26213
26621
  ...typeof record.lastTurnAt === "number" && Number.isFinite(record.lastTurnAt) ? { lastTurnAt: record.lastTurnAt } : {}
26214
26622
  };
@@ -26267,6 +26675,7 @@ var AntigravityAcpSettingsStore = class {
26267
26675
  ...patch.enabledModelIds === void 0 ? {} : { enabledModelIds: patch.enabledModelIds },
26268
26676
  ...patch.defaultReasoningEffort === void 0 ? {} : { defaultReasoningEffort: patch.defaultReasoningEffort },
26269
26677
  ...patch.permissionPolicy === void 0 ? {} : { permissionPolicy: patch.permissionPolicy },
26678
+ ...patch.nativeToolPolicy === void 0 ? {} : { nativeToolPolicy: patch.nativeToolPolicy },
26270
26679
  ...patch.binaryPath === void 0 ? {} : { binaryPath: patch.binaryPath },
26271
26680
  ...patch.lastTurnAt === void 0 ? {} : { lastTurnAt: patch.lastTurnAt }
26272
26681
  };
@@ -26394,10 +26803,7 @@ async function readCatalogFrom(client, signal) {
26394
26803
  session = await create();
26395
26804
  }
26396
26805
  const availableModels = readAvailableModels(asRecord$18(session.models)?.availableModels ?? session.availableModels);
26397
- const configOptions = Array.isArray(session.configOptions) ? session.configOptions : [];
26398
- const modelOption = configOptions.find((entry) => typeof entry === "object" && entry !== null && entry.id === "model");
26399
- const thoughtOption = configOptions.find((entry) => typeof entry === "object" && entry !== null && entry.id === "thought_level");
26400
- const models = collapseModels(readOptionValues(modelOption), availableModels, readOptionValues(thoughtOption).map((option) => option.value));
26806
+ const models = collapseModels(readOptionValues((Array.isArray(session.configOptions) ? session.configOptions : []).find((entry) => typeof entry === "object" && entry !== null && entry.id === "model")), availableModels);
26401
26807
  const tier = readTier$1(session._meta);
26402
26808
  return {
26403
26809
  models,
@@ -26920,6 +27326,7 @@ async function readStatus(options) {
26920
27326
  enabledModelIds: settings.enabledModelIds,
26921
27327
  defaultReasoningEffort: settings.defaultReasoningEffort,
26922
27328
  permissionPolicy: settings.permissionPolicy,
27329
+ nativeToolPolicy: settings.nativeToolPolicy,
26923
27330
  catalogSynced: catalog !== void 0 && (catalog.fromSnapshot === false || Date.now() - catalog.fetchedAt < CATALOG_FRESHNESS_MS),
26924
27331
  ...options.usage() === void 0 ? {} : { usage: options.usage() },
26925
27332
  ...options.occupancy?.() === void 0 ? {} : { occupancy: options.occupancy() },
@@ -27092,13 +27499,18 @@ function readSettingsUpdate(body) {
27092
27499
  if (policy !== "reject" && policy !== "allow") return void 0;
27093
27500
  update.permissionPolicy = policy;
27094
27501
  }
27502
+ if (body.nativeToolPolicy !== void 0) {
27503
+ const policy = body.nativeToolPolicy;
27504
+ if (policy !== "allow" && policy !== "cancel") return void 0;
27505
+ update.nativeToolPolicy = policy;
27506
+ }
27095
27507
  if (body.binaryPath !== void 0) if (body.binaryPath === null) update.binaryPath = null;
27096
27508
  else if (typeof body.binaryPath === "string") update.binaryPath = body.binaryPath;
27097
27509
  else return;
27098
27510
  return update;
27099
27511
  }
27100
27512
  function sameSettings(left, right) {
27101
- return left.enabled === right.enabled && left.defaultReasoningEffort === right.defaultReasoningEffort && left.permissionPolicy === right.permissionPolicy && left.binaryPath === right.binaryPath && JSON.stringify(left.enabledModelIds) === JSON.stringify(right.enabledModelIds);
27513
+ return left.enabled === right.enabled && left.defaultReasoningEffort === right.defaultReasoningEffort && left.permissionPolicy === right.permissionPolicy && left.nativeToolPolicy === right.nativeToolPolicy && left.binaryPath === right.binaryPath && JSON.stringify(left.enabledModelIds) === JSON.stringify(right.enabledModelIds);
27102
27514
  }
27103
27515
  function sendJson$10(response, status, body) {
27104
27516
  const payload = JSON.stringify(body);
@@ -27529,8 +27941,14 @@ const CACHE_WARMUP_DEFAULTS = {
27529
27941
  pageLimitMax: 512,
27530
27942
  /** 分页 maxBytes 默认值(字节)。 */
27531
27943
  pageMaxBytesDefault: 16 * 1024,
27532
- /** 分页 maxBytes 上限(字节)。 */
27533
- pageMaxBytesMax: 64 * 1024,
27944
+ /**
27945
+ * 分页 maxBytes 上限(字节)。
27946
+ *
27947
+ * 25 KB,不是越大越好:补读的每一页都会原样进入下一轮的提示,一次 45 KB 的
27948
+ * 整页重读等于把「省下来的」又付一遍。分页的用途是**精确补读**,不是把整份
27949
+ * 原文再抄一遍;真需要看完全文就多翻几页,每页都要过模型的门。
27950
+ */
27951
+ pageMaxBytesMax: 25 * 1024,
27534
27952
  /** usage registry 的 session 数上限。 */
27535
27953
  maxUsageSessions: 256,
27536
27954
  /** 每 session 保留的用量报告条数上限。 */
@@ -27767,7 +28185,25 @@ function countLines(text, escapedMode = usesEscapedNewlines(text)) {
27767
28185
  return text.endsWith("\n") || escapedMode && text.endsWith("n") && isEscapedNewlineAt(text, text.length - 1) ? lines : lines + 1;
27768
28186
  }
27769
28187
  /**
27770
- * 按 UTF-8 字节安全分页。
28188
+ * 向上查找某 UTF-8 字节偏移所在逻辑行的行首字节偏移。
28189
+ *
28190
+ * 与 {@link countLines} / {@link pageText} 保持一致:支持真实换行 `\n` 以及
28191
+ * 单行 JSON 里的转义换行 `\n`(前面紧邻奇数个 `\`)。
28192
+ */
28193
+ function findLineStartByte(buffer, fromByte, escapedMode) {
28194
+ for (let cursor = fromByte - 1; cursor >= 0; cursor -= 1) {
28195
+ const byte = buffer[cursor];
28196
+ if (byte === 10) return cursor + 1;
28197
+ if (escapedMode && byte === 110) {
28198
+ let backslashes = 0;
28199
+ for (let probe = cursor - 1; probe >= 0 && buffer[probe] === 92; probe -= 1) backslashes += 1;
28200
+ if ((backslashes & 1) === 1) return cursor + 1;
28201
+ }
28202
+ }
28203
+ return 0;
28204
+ }
28205
+ /**
28206
+ * 按 UTF-8 字节安全分页(可选按字面量 `query` 定位首个匹配行)。
27771
28207
  *
27772
28208
  * `offset` 是字节偏移,必须落在字符边界上(上一页的 `nextOffset` 天然满足);
27773
28209
  * 每页最多 `limit` 行且不超过 `maxBytes` 字节,任何一页都不会把一个字符切成两半。
@@ -27775,13 +28211,52 @@ function countLines(text, escapedMode = usesEscapedNewlines(text)) {
27775
28211
  * 「两次翻页拼起来等于原文」是构造出来的性质,不是巧合。
27776
28212
  */
27777
28213
  function pageText(args) {
27778
- const { sessionId, refId, text, buffer, offset, limit, maxBytes } = args;
28214
+ const { sessionId, refId, text, buffer, offset, limit, maxBytes, query } = args;
27779
28215
  const totalBytes = buffer.length;
27780
28216
  if (!Number.isInteger(offset) || offset < 0) throw new CacheWarmupStoreError("offset must be a non-negative integer byte offset", "OFFSET_OUT_OF_RANGE");
27781
28217
  if (offset > totalBytes) throw new CacheWarmupStoreError(`offset ${offset} is past the ${totalBytes}-byte result`, "OFFSET_OUT_OF_RANGE");
27782
28218
  if (offset < totalBytes && (buffer[offset] & 192) === 128) throw new CacheWarmupStoreError("offset is not on a UTF-8 character boundary", "OFFSET_INVALID");
27783
28219
  const escapedMode = usesEscapedNewlines(text);
27784
- const rest = offset === 0 ? text : new TextDecoder("utf-8").decode(buffer.subarray(offset));
28220
+ let sliceOffset = offset;
28221
+ let matchMeta;
28222
+ if (query !== void 0) {
28223
+ const queryBytes = Buffer.from(query, "utf8");
28224
+ const hitByteOffset = offset === totalBytes ? -1 : buffer.indexOf(queryBytes, offset);
28225
+ if (hitByteOffset < 0) return {
28226
+ sessionId,
28227
+ refId,
28228
+ mode: "text",
28229
+ content: "",
28230
+ offset,
28231
+ nextOffset: null,
28232
+ complete: true,
28233
+ matched: false,
28234
+ omitted: {
28235
+ reason: "none",
28236
+ chars: 0,
28237
+ lines: 0,
28238
+ rows: 0,
28239
+ bytes: 0
28240
+ },
28241
+ totalChars: text.length,
28242
+ totalBytes,
28243
+ limit,
28244
+ maxBytes
28245
+ };
28246
+ const lineStartByte = findLineStartByte(buffer, hitByteOffset, escapedMode);
28247
+ const maxLeadBytes = maxBytes >= 8 ? Math.min(2048, Math.floor(maxBytes / 4)) : 0;
28248
+ sliceOffset = lineStartByte;
28249
+ if (hitByteOffset - lineStartByte > maxLeadBytes) {
28250
+ let pos = hitByteOffset - maxLeadBytes;
28251
+ while (pos < hitByteOffset && (buffer[pos] & 192) === 128) pos += 1;
28252
+ sliceOffset = pos;
28253
+ }
28254
+ matchMeta = {
28255
+ matched: true,
28256
+ matchOffset: hitByteOffset
28257
+ };
28258
+ }
28259
+ const rest = sliceOffset === 0 ? text : new TextDecoder("utf-8").decode(buffer.subarray(sliceOffset));
27785
28260
  let content = "";
27786
28261
  let contentBytes = 0;
27787
28262
  let lines = 0;
@@ -27806,7 +28281,8 @@ function pageText(args) {
27806
28281
  if (char === "\n") lines += 1;
27807
28282
  else if (escapedMode && char === "n" && isEscapedNewlineAt(content, content.length - 1)) lines += 1;
27808
28283
  }
27809
- const nextOffset = offset + Buffer.byteLength(content, "utf8");
28284
+ const consumedBytes = Buffer.byteLength(content, "utf8");
28285
+ const nextOffset = sliceOffset + consumedBytes;
27810
28286
  const complete = nextOffset >= totalBytes;
27811
28287
  const remaining = rest.slice(content.length);
27812
28288
  return {
@@ -27814,9 +28290,10 @@ function pageText(args) {
27814
28290
  refId,
27815
28291
  mode: "text",
27816
28292
  content,
27817
- offset,
28293
+ offset: sliceOffset,
27818
28294
  nextOffset: complete ? null : nextOffset,
27819
28295
  complete,
28296
+ ...matchMeta ?? {},
27820
28297
  omitted: {
27821
28298
  reason: complete ? "none" : stoppedByBytes ? "bytes" : stoppedByLines ? "lines" : "bytes",
27822
28299
  chars: remaining.length,
@@ -28038,22 +28515,26 @@ var FileResultReferenceStore = class {
28038
28515
  if (stats === void 0 || !stats.isFile()) throw new CacheWarmupStoreError("stored result is missing; it was released or evicted", "RESULT_NOT_FOUND");
28039
28516
  const ttlMs = this.options.ttlMs;
28040
28517
  if (ttlMs !== void 0 && ttlMs > 0 && this.now() - stats.mtimeMs > ttlMs) throw new CacheWarmupStoreError("stored result expired", "RESULT_EXPIRED");
28518
+ if (input.query !== void 0 && (typeof input.query !== "string" || input.query.length === 0)) throw new CacheWarmupStoreError("query must be a non-empty string", "QUERY_INVALID");
28041
28519
  const buffer = await fs.readFile(file);
28042
28520
  const text = new TextDecoder("utf-8").decode(buffer);
28043
28521
  const limit = clampLimit(input.limit);
28044
28522
  const maxBytes = clampMaxBytes(input.maxBytes);
28045
28523
  const offset = input.offset ?? 0;
28046
- if (input.fields !== void 0 || input.equals !== void 0) return pageStructured({
28047
- sessionId,
28048
- refId: input.refId,
28049
- text,
28050
- buffer,
28051
- offset,
28052
- limit,
28053
- maxBytes,
28054
- fields: input.fields,
28055
- equals: input.equals
28056
- });
28524
+ if (input.fields !== void 0 || input.equals !== void 0) {
28525
+ if (input.query !== void 0) throw new CacheWarmupStoreError("query applies to text mode only; omit fields and equals when using query", "QUERY_INVALID");
28526
+ return pageStructured({
28527
+ sessionId,
28528
+ refId: input.refId,
28529
+ text,
28530
+ buffer,
28531
+ offset,
28532
+ limit,
28533
+ maxBytes,
28534
+ fields: input.fields,
28535
+ equals: input.equals
28536
+ });
28537
+ }
28057
28538
  return pageText({
28058
28539
  sessionId,
28059
28540
  refId: input.refId,
@@ -28061,7 +28542,8 @@ var FileResultReferenceStore = class {
28061
28542
  buffer,
28062
28543
  offset,
28063
28544
  limit,
28064
- maxBytes
28545
+ maxBytes,
28546
+ query: input.query
28065
28547
  });
28066
28548
  }
28067
28549
  /**
@@ -29616,6 +30098,197 @@ function buildCompositeSections(entries) {
29616
30098
  return sections;
29617
30099
  }
29618
30100
  /**
30101
+ * 识别 `code_run` 里 `tools.read` 的批量返回:`[{ path, offset?, lines: [{ number, text }] }]`。
30102
+ *
30103
+ * 只认**完整、连续、递增**的行号数组;任何一条记录形状不符就整批放弃。
30104
+ * @param value - 候选数组。
30105
+ * @returns 识别出的记录,或 undefined。
30106
+ */
30107
+ function canonicalBatchReadRecords(value) {
30108
+ const records = [];
30109
+ for (const entry of value) {
30110
+ if (!isPlainRecord$1(entry)) return void 0;
30111
+ if (typeof entry.path !== "string" || entry.path.trim() === "") return void 0;
30112
+ if (!Array.isArray(entry.lines) || entry.lines.length === 0) return void 0;
30113
+ let first = Number.POSITIVE_INFINITY;
30114
+ let last = Number.NEGATIVE_INFINITY;
30115
+ let previous = -1;
30116
+ for (const line of entry.lines) {
30117
+ if (!isPlainRecord$1(line)) return void 0;
30118
+ if (!Number.isSafeInteger(line.number)) return void 0;
30119
+ if (typeof line.text !== "string") return void 0;
30120
+ const number = line.number;
30121
+ if (number <= previous) return void 0;
30122
+ previous = number;
30123
+ if (number < first) first = number;
30124
+ if (number > last) last = number;
30125
+ }
30126
+ records.push({
30127
+ path: entry.path,
30128
+ first,
30129
+ last,
30130
+ lineCount: entry.lines.length
30131
+ });
30132
+ }
30133
+ return records.length > 0 ? records : void 0;
30134
+ }
30135
+ /**
30136
+ * 识别 `code_run` 里批量改写的返回:`[{ path, before, after }]`。
30137
+ *
30138
+ * `before`/`after` 是模型自己刚写进程序的入参,回显它们不携带任何新信息:
30139
+ * 这正是「同一条内容在上下文里出现两次」的那一类浪费。只保留路径与篇幅,
30140
+ * 需要正文时用 `read` 或 ref 补读。
30141
+ * @param value - 候选数组。
30142
+ * @returns 识别出的记录,或 undefined。
30143
+ */
30144
+ function canonicalBatchEditRecords(value) {
30145
+ const records = [];
30146
+ for (const entry of value) {
30147
+ if (!isPlainRecord$1(entry)) return void 0;
30148
+ if (typeof entry.path !== "string" || entry.path.trim() === "") return void 0;
30149
+ if (typeof entry.before !== "string" || typeof entry.after !== "string") return void 0;
30150
+ if (entry.before === "" && entry.after === "") return void 0;
30151
+ records.push({
30152
+ path: entry.path,
30153
+ beforeChars: entry.before.length,
30154
+ afterChars: entry.after.length
30155
+ });
30156
+ }
30157
+ return records.length > 0 ? records : void 0;
30158
+ }
30159
+ /** 批量读取的预览:每个文件的路径、行范围与行数(完整集合)。 */
30160
+ function buildBatchReadSections(records, maxChars) {
30161
+ const lines = [];
30162
+ let used = 0;
30163
+ let shown = 0;
30164
+ for (const record of records) {
30165
+ const line = ` ${clip(record.path, 140)} lines ${record.first}-${record.last} (${record.lineCount})`;
30166
+ if (shown > 0 && used + line.length + 1 > maxChars) break;
30167
+ lines.push(line);
30168
+ used += line.length + 1;
30169
+ shown += 1;
30170
+ }
30171
+ const sections = [{ lines: [`reads: ${records.length} (complete set; source kept verbatim in the ref)`] }, { lines }];
30172
+ if (shown < records.length) sections.push({ lines: [` … ${records.length - shown} more files (full list via ref)`] });
30173
+ return sections;
30174
+ }
30175
+ /** 批量改写的预览:每个文件的路径与前后篇幅(完整集合,正文不回显)。 */
30176
+ function buildBatchEditSections(records, maxChars) {
30177
+ const lines = [];
30178
+ let used = 0;
30179
+ let shown = 0;
30180
+ for (const record of records) {
30181
+ const line = ` ${clip(record.path, 140)} before ${record.beforeChars}ch → after ${record.afterChars}ch`;
30182
+ if (shown > 0 && used + line.length + 1 > maxChars) break;
30183
+ lines.push(line);
30184
+ used += line.length + 1;
30185
+ shown += 1;
30186
+ }
30187
+ const sections = [{ lines: [`edits: ${records.length} (complete set; before/after bodies kept verbatim in the ref)`] }, { lines }];
30188
+ if (shown < records.length) sections.push({ lines: [` … ${records.length - shown} more files (full list via ref)`] });
30189
+ return sections;
30190
+ }
30191
+ /** 一行带行号的源码(`1: ...`、`1\t...`)。用于识别「路径 → 带行号正文」映射。 */
30192
+ function numberedTextRange(text) {
30193
+ let first = Number.POSITIVE_INFINITY;
30194
+ let last = Number.NEGATIVE_INFINITY;
30195
+ let count = 0;
30196
+ let previous = 0;
30197
+ for (const raw of text.split("\n")) {
30198
+ if (raw.trim() === "") continue;
30199
+ const matched = READ_NUMBERED_LINE.exec(raw);
30200
+ if (matched === null) return void 0;
30201
+ const number = Number(matched[1]);
30202
+ if (!Number.isSafeInteger(number) || number <= previous) return void 0;
30203
+ previous = number;
30204
+ if (number < first) first = number;
30205
+ if (number > last) last = number;
30206
+ count += 1;
30207
+ }
30208
+ if (count === 0) return void 0;
30209
+ return {
30210
+ first,
30211
+ last,
30212
+ lines: count
30213
+ };
30214
+ }
30215
+ /**
30216
+ * `code_run` 批量工具的投影:数组与「路径 → 正文」映射。
30217
+ *
30218
+ * 真实会话里最贵的工具结果几乎全是这一种:模型在程序里批量 `tools.grep` /
30219
+ * `tools.read` / 批量改写,然后把整个数组 `return` 出来,恰好撞上宿主 50K 字符
30220
+ * 渲染上限。它们不是「无法解析的大文本」,而是**结构完全已知的批量结果**。
30221
+ *
30222
+ * 四条闸门(任何一条不满足就交回原文):
30223
+ * - 只认 PTC 家族的程序传输工具,别的工具的同形 JSON 与我们无关;
30224
+ * - 批量读取只认行号完整、连续递增的记录;源码正文只在两种情况下换成大纲:
30225
+ * 明确导航任务,或这条结果**已经被宿主截断**(尾部早已不在上下文里,
30226
+ * 此时「完整索引 + ref 全文」严格优于「半截正文」);
30227
+ * - 批量改写必须是 `{ path, before, after }` 三字段都在的字符串;
30228
+ * - 结果必须真的超过当前预算 —— 小结果不动,避免无谓地扰动前缀。
30229
+ * @param text - 工具结果原文。
30230
+ * @param toolName - 工具名。
30231
+ * @param budgetMaxChars - 当前预览预算的字符上限。
30232
+ * @param navigation - 是否明确导航任务。
30233
+ * @param spilled - 原文是否已被宿主截断并留有 spill 提示。
30234
+ * @returns 投影计划,或 undefined(交回原文)。
30235
+ */
30236
+ function planBatchToolResult(text, toolName, budgetMaxChars, navigation, spilled) {
30237
+ if (!isPtcTransportName(toolName)) return void 0;
30238
+ if (text.length <= budgetMaxChars) return void 0;
30239
+ let value;
30240
+ try {
30241
+ value = JSON.parse(text);
30242
+ } catch {
30243
+ return;
30244
+ }
30245
+ if (Array.isArray(value)) {
30246
+ const grep = canonicalGrepMatches(value);
30247
+ if (grep !== void 0) return {
30248
+ kind: "preview",
30249
+ strategy: "grep-results",
30250
+ sections: buildGrepEnvelopeSections(grep)
30251
+ };
30252
+ const edits = canonicalBatchEditRecords(value);
30253
+ if (edits !== void 0) return {
30254
+ kind: "preview",
30255
+ strategy: "batch-results",
30256
+ sections: buildBatchEditSections(edits, Math.max(400, budgetMaxChars - 200))
30257
+ };
30258
+ if (navigation === true || spilled) {
30259
+ const reads = canonicalBatchReadRecords(value);
30260
+ if (reads !== void 0) return {
30261
+ kind: "preview",
30262
+ strategy: "batch-results",
30263
+ sections: buildBatchReadSections(reads, Math.max(400, budgetMaxChars - 200))
30264
+ };
30265
+ }
30266
+ return;
30267
+ }
30268
+ if (!isPlainRecord$1(value)) return void 0;
30269
+ if (navigation !== true && !spilled) return void 0;
30270
+ const keys = Object.keys(value);
30271
+ if (keys.length < 2) return void 0;
30272
+ const records = [];
30273
+ for (const key of keys) {
30274
+ const body = value[key];
30275
+ if (typeof body !== "string") return void 0;
30276
+ const range = numberedTextRange(body);
30277
+ if (range === void 0) return void 0;
30278
+ records.push({
30279
+ path: key,
30280
+ first: range.first,
30281
+ last: range.last,
30282
+ lineCount: range.lines
30283
+ });
30284
+ }
30285
+ return {
30286
+ kind: "preview",
30287
+ strategy: "batch-results",
30288
+ sections: buildBatchReadSections(records, Math.max(400, budgetMaxChars - 200))
30289
+ };
30290
+ }
30291
+ /**
29619
30292
  * 复合 JSON 信封的投影计划。
29620
30293
  *
29621
30294
  * 一份结果里混着多个成员(grep + read + glob + log)时,逐个成员摘要:
@@ -29854,6 +30527,10 @@ function planProjection(text, toolName, navigation, retrievalOnly, spilled = fal
29854
30527
  const toolCatalog = planToolCatalogProjection(text, toolName);
29855
30528
  if (toolCatalog !== void 0) return toolCatalog;
29856
30529
  }
30530
+ if (isPtcTransportName(toolName)) {
30531
+ const batch = planBatchToolResult(text, toolName, budgetMaxChars, navigation, spilled);
30532
+ if (batch !== void 0) return batch;
30533
+ }
29857
30534
  if (looksLikeContract(text)) return {
29858
30535
  kind: "verbatim",
29859
30536
  strategy: "verbatim-contract"
@@ -29897,7 +30574,7 @@ function planProjection(text, toolName, navigation, retrievalOnly, spilled = fal
29897
30574
  }
29898
30575
  /** 预览尾部:把「怎么读全文」写死在预览里,模型不用猜。 */
29899
30576
  function footerFor(refId) {
29900
- return `[full result: ${refId} · page with offset/limit(default 64 lines)/maxBytes(default 16384 bytes)]`;
30577
+ return `[full result: ${refId} · page with query/offset/limit(default 64 lines)/maxBytes(default 16384 bytes)]`;
29901
30578
  }
29902
30579
  /**
29903
30580
  * 核心决策:预算 → 计划 → 装配 → 入库。
@@ -38024,7 +38701,7 @@ var KimiCodeAdapter = class extends LlmAdapter {
38024
38701
  (item.kind === "image" ? imageReferences : videoReferences).set(item.attachmentId, reference);
38025
38702
  cited.push(item);
38026
38703
  } catch (error) {
38027
- if (input.signal.aborted || isAbortError(error)) throw new LlmError("Kimi Code media upload aborted", "ABORTED", { cause: error });
38704
+ if (input.signal.aborted || isAbortError(error)) throw new LlmError$1("Kimi Code media upload aborted", "ABORTED", { cause: error });
38028
38705
  }
38029
38706
  }));
38030
38707
  return {
@@ -38180,7 +38857,7 @@ var KimiCodeAdapter = class extends LlmAdapter {
38180
38857
  }));
38181
38858
  }
38182
38859
  async resolveModel(provider, modelId, signal) {
38183
- if (signal?.aborted) throw new LlmError("Kimi Code model resolution aborted", "ABORTED");
38860
+ if (signal?.aborted) throw new LlmError$1("Kimi Code model resolution aborted", "ABORTED");
38184
38861
  const settings = await this.settings();
38185
38862
  const catalog = await this.catalog();
38186
38863
  const entry = catalog.find((model) => model.id === modelId);
@@ -38465,13 +39142,13 @@ var KimiCodeAdapter = class extends LlmAdapter {
38465
39142
  activity?.pulse();
38466
39143
  return response;
38467
39144
  } catch (error) {
38468
- if (signal.aborted) throw new LlmError("Kimi Code request aborted", "ABORTED", { cause: error });
38469
- throw new LlmError(`Kimi Code request failed: ${error instanceof Error ? error.message : String(error)}`, "TRANSPORT", { cause: error });
39145
+ if (signal.aborted) throw new LlmError$1("Kimi Code request aborted", "ABORTED", { cause: error });
39146
+ throw new LlmError$1(`Kimi Code request failed: ${error instanceof Error ? error.message : String(error)}`, "TRANSPORT", { cause: error });
38470
39147
  }
38471
39148
  };
38472
39149
  if (sideChannel && sessionKey !== "") {
38473
39150
  await prefixRequests.waitForMainSession(sessionKey, signal);
38474
- if (signal.aborted) throw new LlmError("Kimi Code request aborted", "ABORTED");
39151
+ if (signal.aborted) throw new LlmError$1("Kimi Code request aborted", "ABORTED");
38475
39152
  }
38476
39153
  const coldGroupKey = sideChannel ? void 0 : coldStartGroupKey(region, requestOptions, accountScope);
38477
39154
  const coldGate = coldGroupKey === void 0 ? void 0 : await acquireColdStartWarmup(coldGroupKey, signal);
@@ -38544,7 +39221,7 @@ var KimiCodeAdapter = class extends LlmAdapter {
38544
39221
  if (await pool.hasAnotherAvailableAccount(tried)) continue;
38545
39222
  }
38546
39223
  }
38547
- throw new LlmError(failure.message, failure.code, {
39224
+ throw new LlmError$1(failure.message, failure.code, {
38548
39225
  status: response.status,
38549
39226
  ...after === void 0 ? {} : { providerRetryAfterMs: after }
38550
39227
  });
@@ -38562,7 +39239,7 @@ var KimiCodeAdapter = class extends LlmAdapter {
38562
39239
  droppedImages: stickyOffload.droppedCount + bodyFitDroppedKeys.length
38563
39240
  }, requestOptions);
38564
39241
  }
38565
- if (response.body === null) throw new LlmError("Kimi Code returned an empty response body", "PROVIDER_ERROR");
39242
+ if (response.body === null) throw new LlmError$1("Kimi Code returned an empty response body", "PROVIDER_ERROR");
38566
39243
  const reader = response.body.getReader();
38567
39244
  const decoder = new TextDecoder();
38568
39245
  const state = createStreamState$5(wire, requestOptions.sessionId, sideChannel);
@@ -38611,20 +39288,20 @@ var KimiCodeAdapter = class extends LlmAdapter {
38611
39288
  }
38612
39289
  } catch (error) {
38613
39290
  const inBand = state.streamError;
38614
- if (error instanceof LlmError && !outputStarted && error.code === "PROVIDER_ERROR" && inBand !== void 0) throw await this.inBandStreamFailure(error, inBand, servedByAccountId, retrySignal, requestDiagnostic.attempts.at(-1));
39291
+ if (error instanceof LlmError$1 && !outputStarted && error.code === "PROVIDER_ERROR" && inBand !== void 0) throw await this.inBandStreamFailure(error, inBand, servedByAccountId, retrySignal, requestDiagnostic.attempts.at(-1));
38615
39292
  throw streamFailure(error, signal);
38616
39293
  }
38617
39294
  } finally {
38618
39295
  reader.cancel().catch(() => void 0);
38619
39296
  }
38620
39297
  } catch (error) {
38621
- if (error instanceof LlmError && isKimiToolArgumentGuardCode(error.code)) rememberSameAccountRetry(retrySignal, diagnosticState?.accountId);
39298
+ if (error instanceof LlmError$1 && isKimiToolArgumentGuardCode(error.code)) rememberSameAccountRetry(retrySignal, diagnosticState?.accountId);
38622
39299
  requestError = error;
38623
39300
  throw error;
38624
39301
  } finally {
38625
39302
  const endedAt = Date.now();
38626
39303
  const finalAccountId = diagnosticState?.accountId ?? requestDiagnostic.accountId ?? requestDiagnostic.attempts.at(-1)?.accountId;
38627
- const errorCode = requestError instanceof LlmError ? requestError.code : requestError === void 0 ? void 0 : "UNKNOWN";
39304
+ const errorCode = requestError instanceof LlmError$1 ? requestError.code : requestError === void 0 ? void 0 : "UNKNOWN";
38628
39305
  const lastAttempt = requestDiagnostic.attempts.at(-1);
38629
39306
  if (lastAttempt !== void 0 && errorCode !== void 0) {
38630
39307
  lastAttempt.code = errorCode;
@@ -38705,22 +39382,22 @@ function isRefreshTimeout(error) {
38705
39382
  }
38706
39383
  /** Preserve OAuth failure semantics before the first model request. */
38707
39384
  function credentialFailure(error, signal) {
38708
- if (signal.aborted) return new LlmError("Kimi Code credential preparation aborted", "ABORTED", { cause: error });
38709
- if (error instanceof LlmError) return error;
38710
- if (error instanceof KimiCodeUnauthorizedError) return new LlmError(error.message, "INVALID_CREDENTIAL", { cause: error });
38711
- if (error instanceof KimiCodeOAuthError) return new LlmError(error.message, "INVALID_REQUEST", {
39385
+ if (signal.aborted) return new LlmError$1("Kimi Code credential preparation aborted", "ABORTED", { cause: error });
39386
+ if (error instanceof LlmError$1) return error;
39387
+ if (error instanceof KimiCodeUnauthorizedError) return new LlmError$1(error.message, "INVALID_CREDENTIAL", { cause: error });
39388
+ if (error instanceof KimiCodeOAuthError) return new LlmError$1(error.message, "INVALID_REQUEST", {
38712
39389
  cause: error,
38713
39390
  status: error.status
38714
39391
  });
38715
39392
  if (error instanceof KimiCodeRetryableError) {
38716
39393
  const detail = errorChain(error).trim().slice(0, 500);
38717
39394
  const code = error.status === 429 ? "RATE_LIMIT" : error.status !== void 0 ? "SERVER" : isRefreshTimeout(error) ? "TIMEOUT" : "TRANSPORT";
38718
- return new LlmError(`Kimi Code credential refresh failed: ${detail}`, code, {
39395
+ return new LlmError$1(`Kimi Code credential refresh failed: ${detail}`, code, {
38719
39396
  cause: error,
38720
39397
  ...error.status === void 0 ? {} : { status: error.status }
38721
39398
  });
38722
39399
  }
38723
- return new LlmError(`Kimi Code credential could not be prepared: ${error instanceof Error ? error.message : String(error)}`, "MISSING_CREDENTIAL", { cause: error });
39400
+ return new LlmError$1(`Kimi Code credential could not be prepared: ${error instanceof Error ? error.message : String(error)}`, "MISSING_CREDENTIAL", { cause: error });
38724
39401
  }
38725
39402
  /**
38726
39403
  * The failure a stream that died mid-body is reported as.
@@ -38748,10 +39425,10 @@ function credentialFailure(error, signal) {
38748
39425
  * retried one.
38749
39426
  */
38750
39427
  function streamFailure(error, signal) {
38751
- if (error instanceof LlmError) return error;
38752
- if (signal.aborted) return new LlmError("Kimi Code stream aborted", "ABORTED", { cause: error });
39428
+ if (error instanceof LlmError$1) return error;
39429
+ if (signal.aborted) return new LlmError$1("Kimi Code stream aborted", "ABORTED", { cause: error });
38753
39430
  const chain = errorChain(error).trim();
38754
- return new LlmError(`Kimi Code stream failed: ${chain === "" ? "the response stream ended unexpectedly" : chain.slice(0, 500)}`, "TRANSPORT", { cause: error });
39431
+ return new LlmError$1(`Kimi Code stream failed: ${chain === "" ? "the response stream ended unexpectedly" : chain.slice(0, 500)}`, "TRANSPORT", { cause: error });
38755
39432
  }
38756
39433
  function processLine(line, state, wire) {
38757
39434
  return wire === "anthropic" ? processAnthropicStreamLine(line, state) : processOpenAIStreamLine(line, state);
@@ -40918,204 +41595,13 @@ function renderDirectCallReminder(toolNames) {
40918
41595
  ].join("\n");
40919
41596
  }
40920
41597
  /**
40921
- * 官方提醒文案的后缀:提醒只对当前这一轮有效。
40922
- * @returns 后缀正文。
40923
- */
40924
- const TURN_ONLY_SUFFIX = " This is a temporary runtime reminder for the current Turn only, not a user preference or a durable rule; do not save this reminder or generalize it into Memory, Skills, or other persistent instruction files for future Turns or sessions.";
40925
- /**
40926
- * 渲染「同一个动作立刻重复」提醒。
40927
- *
40928
- * 与官方 `packages/agent-modules/runaway-guard/src/reminder.ts` 逐字一致。
40929
- * @param occurrences - 连击次数。
40930
- * @returns 提醒正文。
40931
- */
40932
- function renderExactActionRepeatReminder(occurrences) {
40933
- return `[runaway guard] The immediately repeated tool action has now occurred ${occurrences} times with the same arguments. Do not repeat it unchanged. Inspect the results already available, then either change strategy with a concrete expected state change, or report the blocker. Repetition alone does not establish that the task is complete or impossible.${TURN_ONLY_SUFFIX}`;
40934
- }
40935
- /**
40936
- * 渲染「同一族错误连续发生」提醒。
40937
- *
40938
- * 与官方 `packages/agent-modules/runaway-guard/src/reminder.ts` 逐字一致。
40939
- * @param occurrences - 连击次数。
40940
- * @returns 提醒正文。
40941
- */
40942
- function renderSameErrorFamilyReminder(occurrences) {
40943
- return `[runaway guard] The same tool error family has now occurred ${occurrences} times in a row. Do not retry the same route unchanged. Diagnose the cause, change one controlled variable or switch route. Do not infer that the entire task has failed from this signal.${TURN_ONLY_SUFFIX}`;
40944
- }
40945
- /**
40946
- * 渲染「反复轮询同一个后台任务」提醒。
40947
- *
40948
- * 与官方 `packages/agent-modules/runaway-guard/src/reminder.ts` 逐字一致:
40949
- * 三次读同一个任务时写的是 `Three`,其它次数写数字。
40950
- * @param occurrences - 连击次数。
40951
- * @returns 提醒正文。
40952
- */
40953
- function renderPollingRepeatReminder(occurrences) {
40954
- return [
40955
- "<system-reminder>",
40956
- `${occurrences === 3 ? "Three" : String(occurrences)} task_output reads for the same task have returned an unchanged status and output cursor. Avoid repeated polling; you will be notified automatically and this conversation will resume when the background task completes.`,
40957
- "This reminder applies only to the current Turn. Do not save or generalize it into Memory, Skills, or other persistent instructions.",
40958
- "</system-reminder>"
40959
- ].join("\n");
40960
- }
40961
- /**
40962
- * 轮询类工具名(后台任务的结果读取)。
40963
- *
40964
- * 这两个工具读的是后台任务的状态;反复读同一个任务而输出没变,就是官方说的
40965
- * 「polling repeat」。
40966
- */
40967
- const POLLING_TOOL_NAMES = Object.freeze(["job_output", "task_output"]);
40968
- /**
40969
- * 规范化一段错误文本,取它的「族」。
40970
- *
40971
- * 族的作用是**把同一类错误认成同一类**:路径里的数字、id、时间戳都不该让
40972
- * 两次一模一样的失败看起来是两回事。
40973
- * @param text - 错误文本。
40974
- * @returns 族标识。
40975
- */
40976
- function errorFamilyOf(text) {
40977
- if (text === void 0 || text === "") return "unknown";
40978
- return (text.split(/\r?\n/, 1)[0] ?? "").replace(/\d+/g, "#").slice(0, 200);
40979
- }
40980
- /**
40981
- * 造一台工具级失控守卫。
40982
- *
40983
- * 三种可提醒信号(顺序即官方提醒优先级):
40984
- *
40985
- * 1. `same_error_family` —— 同一个工具连续报同一族错误;
40986
- * 2. `exact_action_repeat` —— 同一次动作(同名 + 同参数)立刻重复;
40987
- * 3. `polling_repeat` —— 连续轮询同一个后台任务而输出没变。
40988
- *
40989
- * `abab_action_cycle`(A B A B 的循环)**只记录不提醒**:官方把它排在提醒
40990
- * 候选之外——模型在两个动作之间来回跳时,提醒它「别重复」是没有意义的。
40991
- *
40992
- * 每轮**至多一条**提醒:官方在发出第一条后就把本轮的提醒机会用掉了。
41598
+ * 造一台 MiniMax Code 会话的工具级失控守卫(实现已下沉至共享内核 `tool-runaway.ts`)。
40993
41599
  *
40994
41600
  * @param options - 守卫选项。
40995
41601
  * @returns 守卫。
40996
41602
  */
40997
41603
  function createMinimaxRunawayGuard(options = {}) {
40998
- const threshold = options.remindAfterOccurrences ?? 3;
40999
- /** 同一次动作的连击,由所有线路共享的规范键与跟踪器计算。 */
41000
- const exactActionRepeats = createExactRepeatTracker();
41001
- /** 同一族错误的连击(键是工具名 + 错误族)。 */
41002
- const errorStreaks = /* @__PURE__ */ new Map();
41003
- /** 轮询连击(键是工具名)。 */
41004
- const pollingStreaks = /* @__PURE__ */ new Map();
41005
- /** 最近几次动作,用来认 A B A B 的循环。 */
41006
- const recentActions = [];
41007
- /** 当前正在计数的 A B 循环对。 */
41008
- let activeAbabKey;
41009
- /** 本轮是否已经提醒过。 */
41010
- let reminderAttempted = false;
41011
- /** 观察到的信号。 */
41012
- const signals = [];
41013
- /**
41014
- * 记一条信号。
41015
- * @param kind - 信号种类。
41016
- * @param occurrences - 连击次数。
41017
- * @param toolName - 工具名。
41018
- */
41019
- const record = (kind, occurrences, toolName) => {
41020
- signals.push({
41021
- kind,
41022
- occurrences,
41023
- toolName
41024
- });
41025
- };
41026
- /**
41027
- * 判断这次执行是不是一次「原地不动」的轮询。
41028
- * @param observation - 观察事实。
41029
- * @returns 是轮询时为 true。
41030
- */
41031
- const isPolling = (observation) => {
41032
- if (!POLLING_TOOL_NAMES.includes(observation.toolName)) return false;
41033
- return (isPlainRecord(observation.arguments) ? observation.arguments : void 0)?.["wait"] !== true;
41034
- };
41035
- return {
41036
- observe(observation) {
41037
- const toolName = observation.toolName;
41038
- const actionKey = canonicalToolCallKey(toolName, observation.arguments);
41039
- const countsAsAction = !POLLING_TOOL_NAMES.includes(toolName);
41040
- if (countsAsAction) {
41041
- const action = exactActionRepeats.observe(toolName, observation.arguments);
41042
- record("exact_action_repeat", action.count, toolName);
41043
- }
41044
- if (countsAsAction) {
41045
- recentActions.push(actionKey);
41046
- if (recentActions.length > 4) recentActions.shift();
41047
- if (recentActions.length === 4) {
41048
- const [a, b, c, d] = recentActions;
41049
- if (a !== void 0 && b !== void 0 && a !== b && a === c && b === d) {
41050
- const episode = `${a}\u0000${b}`;
41051
- if (activeAbabKey !== episode) {
41052
- activeAbabKey = episode;
41053
- record("abab_action_cycle", 2, toolName);
41054
- }
41055
- } else activeAbabKey = void 0;
41056
- }
41057
- }
41058
- if (observation.isError === true) {
41059
- const key = `${toolName}\u0000${observation.errorCode ?? errorFamilyOf(observation.errorText)}`;
41060
- const previous = errorStreaks.get(key);
41061
- const count = previous === void 0 ? 1 : previous.count + 1;
41062
- errorStreaks.set(key, {
41063
- toolName,
41064
- count
41065
- });
41066
- record("same_error_family", count, toolName);
41067
- } else for (const [key, entry] of [...errorStreaks]) if (entry.toolName === toolName) errorStreaks.delete(key);
41068
- if (isPolling(observation)) {
41069
- const key = `${canonicalToolCallKey(toolName, observation.arguments)}\u0000${observation.resultText ?? ""}`;
41070
- const previous = pollingStreaks.get(toolName);
41071
- const count = previous !== void 0 && previous.key === key ? previous.count + 1 : 1;
41072
- pollingStreaks.set(toolName, {
41073
- key,
41074
- count
41075
- });
41076
- record("polling_repeat", count, toolName);
41077
- } else pollingStreaks.delete(toolName);
41078
- if (reminderAttempted) return void 0;
41079
- const errorCandidate = [...errorStreaks.values()].find((entry) => entry.count >= threshold);
41080
- if (errorCandidate !== void 0) {
41081
- reminderAttempted = true;
41082
- return {
41083
- kind: "same_error_family",
41084
- occurrences: errorCandidate.count,
41085
- text: renderSameErrorFamilyReminder(errorCandidate.count)
41086
- };
41087
- }
41088
- const actionStreak = exactActionRepeats.current();
41089
- if (countsAsAction && actionStreak !== void 0 && actionStreak.count >= threshold) {
41090
- reminderAttempted = true;
41091
- return {
41092
- kind: "exact_action_repeat",
41093
- occurrences: actionStreak.count,
41094
- text: renderExactActionRepeatReminder(actionStreak.count)
41095
- };
41096
- }
41097
- const pollingCandidate = [...pollingStreaks.values()].find((entry) => entry.count >= threshold);
41098
- if (pollingCandidate !== void 0) {
41099
- reminderAttempted = true;
41100
- return {
41101
- kind: "polling_repeat",
41102
- occurrences: pollingCandidate.count,
41103
- text: renderPollingRepeatReminder(pollingCandidate.count)
41104
- };
41105
- }
41106
- },
41107
- reset() {
41108
- exactActionRepeats.reset();
41109
- errorStreaks.clear();
41110
- pollingStreaks.clear();
41111
- recentActions.length = 0;
41112
- activeAbabKey = void 0;
41113
- reminderAttempted = false;
41114
- },
41115
- get signals() {
41116
- return signals;
41117
- }
41118
- };
41604
+ return createToolRunawayGuard(options);
41119
41605
  }
41120
41606
  /**
41121
41607
  * 读宿主上下文上的工具注册面。
@@ -41300,51 +41786,6 @@ function createRunawayReminder(reminder) {
41300
41786
  });
41301
41787
  }
41302
41788
  /**
41303
- * 读一次执行的结果是不是失败。
41304
- * @param result - 工具执行结果。
41305
- * @returns 失败时为 true。
41306
- */
41307
- function isErrorResult(result) {
41308
- return isRecord$50(result) && result["isError"] === true;
41309
- }
41310
- /**
41311
- * 读一次执行的结构化错误码。
41312
- * @param result - 工具执行结果。
41313
- * @returns 错误码;没有时为 undefined。
41314
- */
41315
- function errorCodeOf$1(result) {
41316
- if (!isRecord$50(result)) return void 0;
41317
- const error = result["error"];
41318
- if (!isRecord$50(error)) return void 0;
41319
- const info = error["info"];
41320
- if (!isRecord$50(info)) return void 0;
41321
- return stringOf$4(info["code"]);
41322
- }
41323
- /**
41324
- * 读一次执行的失败文本。
41325
- * @param result - 工具执行结果。
41326
- * @returns 失败文本;没有时为 undefined。
41327
- */
41328
- function errorTextOf(result) {
41329
- if (!isRecord$50(result)) return void 0;
41330
- const error = result["error"];
41331
- if (!isRecord$50(error)) return void 0;
41332
- return stringOf$4(error["message"]);
41333
- }
41334
- /**
41335
- * 读一次执行的结果文本(轮询判定用)。
41336
- * @param result - 工具执行结果。
41337
- * @returns 结果文本;没有时是空串。
41338
- */
41339
- function resultTextOf(result) {
41340
- if (!isRecord$50(result)) return "";
41341
- const content = result["content"];
41342
- if (!Array.isArray(content)) return "";
41343
- const parts = [];
41344
- for (const block of content) if (isRecord$50(block) && block["type"] === "text") parts.push(stringOf$4(block["text"]) ?? "");
41345
- return parts.join("\n");
41346
- }
41347
- /**
41348
41789
  * 找一次工具调用的参数 schema。
41349
41790
  * @param tools - 工具注册面。
41350
41791
  * @param name - 工具名。
@@ -41450,15 +41891,16 @@ function installMinimaxRuntimeEnhancements(ctx, options = {}) {
41450
41891
  const contexts = [];
41451
41892
  const directName = directCallToolNameOf(exec);
41452
41893
  if (directName !== void 0 && isPtcSessionOf(agent, tools)) contexts.push(createDirectCallReminder(directName));
41453
- const reminder = guardOf(agent).observe({
41454
- toolName: exec.name,
41455
- arguments: exec.arguments,
41456
- isError: isErrorResult(result),
41457
- errorCode: errorCodeOf$1(result),
41458
- errorText: errorTextOf(result),
41459
- resultText: resultTextOf(result)
41460
- });
41461
- if (reminder !== void 0) contexts.push(createRunawayReminder(reminder));
41894
+ if ((() => {
41895
+ try {
41896
+ return options.runawayEnabled?.() !== false;
41897
+ } catch {
41898
+ return true;
41899
+ }
41900
+ })()) {
41901
+ const reminder = guardOf(agent).observe(observationFromToolExecution(exec.name, exec.arguments, result));
41902
+ if (reminder !== void 0) contexts.push(createRunawayReminder(reminder));
41903
+ }
41462
41904
  if (contexts.length === 0) return decision;
41463
41905
  return withAdditionalContexts$1(decision, contexts);
41464
41906
  } catch {
@@ -45594,7 +46036,7 @@ function sameModelId(requested, answered) {
45594
46036
  * substitution means this id no longer routes, so the selection has to change.
45595
46037
  */
45596
46038
  function modelSubstitutedFailure(requested, answered) {
45597
- return new LlmError("MiniMax Code(编程订阅) answered with a different model than the one requested: the request asked for \"" + requested + "\", and the service answered as \"" + answered + "\". This endpoint does not reject a model id it cannot route — it silently runs another one — so the id \"" + requested + "\" is not being served and the request was billed at the answering model's rate instead. Nothing was retried, because the same request would be answered the same way. Pick a different model for this line, or check whether \"" + requested + "\" is still offered, then send the request again.", MODEL_SUBSTITUTED_CODE, { status: 200 });
46039
+ return new LlmError$1("MiniMax Code(编程订阅) answered with a different model than the one requested: the request asked for \"" + requested + "\", and the service answered as \"" + answered + "\". This endpoint does not reject a model id it cannot route — it silently runs another one — so the id \"" + requested + "\" is not being served and the request was billed at the answering model's rate instead. Nothing was retried, because the same request would be answered the same way. Pick a different model for this line, or check whether \"" + requested + "\" is still offered, then send the request again.", MODEL_SUBSTITUTED_CODE, { status: 200 });
45598
46040
  }
45599
46041
  var MinimaxCodeAdapter = class extends LlmAdapter {
45600
46042
  store;
@@ -45725,7 +46167,7 @@ var MinimaxCodeAdapter = class extends LlmAdapter {
45725
46167
  * deliberately not exposed as a fixed defaultMaxTokens reservation here.
45726
46168
  */
45727
46169
  async resolveModel(provider, modelId, signal) {
45728
- if (signal?.aborted === true) throw new LlmError("MiniMax Code model resolution aborted", "ABORTED");
46170
+ if (signal?.aborted === true) throw new LlmError$1("MiniMax Code model resolution aborted", "ABORTED");
45729
46171
  const settings = await this.settings();
45730
46172
  const entry = minimaxCodeModelDef(modelId);
45731
46173
  const efforts = orderReasoningEfforts(effortsForModel(modelId), [
@@ -45819,8 +46261,8 @@ var MinimaxCodeAdapter = class extends LlmAdapter {
45819
46261
  credentials = selection.credentials;
45820
46262
  accountId = selection.accountId;
45821
46263
  } catch (error) {
45822
- if (error instanceof MinimaxCodeUnauthorizedError) throw new LlmError(error.message, "INVALID_CREDENTIAL", { cause: error });
45823
- throw new LlmError("MiniMax Code(编程订阅) credential could not be prepared: " + (error instanceof Error ? error.message : String(error)), "MISSING_CREDENTIAL", { cause: error });
46264
+ if (error instanceof MinimaxCodeUnauthorizedError) throw new LlmError$1(error.message, "INVALID_CREDENTIAL", { cause: error });
46265
+ throw new LlmError$1("MiniMax Code(编程订阅) credential could not be prepared: " + (error instanceof Error ? error.message : String(error)), "MISSING_CREDENTIAL", { cause: error });
45824
46266
  }
45825
46267
  if (accountId !== void 0) tried.add(accountId);
45826
46268
  authOwner = computeMinimaxAuthOwner(credentials, accountId);
@@ -45869,8 +46311,8 @@ var MinimaxCodeAdapter = class extends LlmAdapter {
45869
46311
  });
45870
46312
  activity?.pulse();
45871
46313
  } catch (error) {
45872
- if (signal.aborted) throw new LlmError("MiniMax Code request aborted", "ABORTED", { cause: error });
45873
- throw new LlmError("MiniMax Code(编程订阅) request failed: " + (error instanceof Error ? error.message : String(error)), "TRANSPORT", { cause: error });
46314
+ if (signal.aborted) throw new LlmError$1("MiniMax Code request aborted", "ABORTED", { cause: error });
46315
+ throw new LlmError$1("MiniMax Code(编程订阅) request failed: " + (error instanceof Error ? error.message : String(error)), "TRANSPORT", { cause: error });
45874
46316
  }
45875
46317
  refusedBody = void 0;
45876
46318
  if (response.ok) break;
@@ -45883,8 +46325,8 @@ var MinimaxCodeAdapter = class extends LlmAdapter {
45883
46325
  authOwner = computeMinimaxAuthOwner(credentials, accountId);
45884
46326
  body = buildBodyForOwner(authOwner);
45885
46327
  } catch (error) {
45886
- if (error instanceof MinimaxCodeUnauthorizedError) throw new LlmError(error.message, "INVALID_CREDENTIAL", { cause: error });
45887
- throw new LlmError("MiniMax Code(编程订阅) credential could not be renewed after the service refused " + redactToken(refused) + ": " + (error instanceof Error ? error.message : String(error)), "INVALID_CREDENTIAL", { cause: error });
46328
+ if (error instanceof MinimaxCodeUnauthorizedError) throw new LlmError$1(error.message, "INVALID_CREDENTIAL", { cause: error });
46329
+ throw new LlmError$1("MiniMax Code(编程订阅) credential could not be renewed after the service refused " + redactToken(refused) + ": " + (error instanceof Error ? error.message : String(error)), "INVALID_CREDENTIAL", { cause: error });
45888
46330
  }
45889
46331
  }
45890
46332
  if (response.ok) break;
@@ -45899,12 +46341,12 @@ var MinimaxCodeAdapter = class extends LlmAdapter {
45899
46341
  }
45900
46342
  }
45901
46343
  const hint = failure.code === "INVALID_CREDENTIAL" ? " (credential " + redactToken(credentials.accessToken) + ")" : "";
45902
- throw new LlmError(failure.message + hint, failure.code, {
46344
+ throw new LlmError$1(failure.message + hint, failure.code, {
45903
46345
  status: response.status,
45904
46346
  ...after === void 0 ? {} : { providerRetryAfterMs: after }
45905
46347
  });
45906
46348
  }
45907
- if (response.body === null) throw new LlmError("MiniMax Code(编程订阅) returned an empty response body", "PROVIDER_ERROR");
46349
+ if (response.body === null) throw new LlmError$1("MiniMax Code(编程订阅) returned an empty response body", "PROVIDER_ERROR");
45908
46350
  const reader = response.body.getReader();
45909
46351
  const decoder = new TextDecoder();
45910
46352
  const state = createStreamState({
@@ -45995,7 +46437,7 @@ var MinimaxCodeAdapter = class extends LlmAdapter {
45995
46437
  yield chunk;
45996
46438
  }
45997
46439
  } catch (error) {
45998
- if (error instanceof LlmError && !outputStarted && error.code === "PROVIDER_ERROR" && state.streamError !== void 0) {
46440
+ if (error instanceof LlmError$1 && !outputStarted && error.code === "PROVIDER_ERROR" && state.streamError !== void 0) {
45999
46441
  const reclassified = reclassifyInBandError(error, state.streamError, classifyMinimaxFailure);
46000
46442
  if (pool !== void 0 && accountId !== void 0) {
46001
46443
  const inBandBody = JSON.stringify({ error: state.streamError });
@@ -49222,7 +49664,14 @@ function installKimiRepeatBreaker(ctx, options = {}) {
49222
49664
  if (target === void 0) return decision;
49223
49665
  const toolName = stringOf$3(exec.name);
49224
49666
  if (toolName === void 0) return decision;
49225
- const reminder = target.breaker.recordAfterExecute(target.key, toolName, exec.arguments);
49667
+ const args = exec.arguments;
49668
+ const obs = observationFromToolExecution(toolName, args, result);
49669
+ const reminder = target.breaker.recordAfterExecute(target.key, toolName, args, {
49670
+ isError: obs.isError,
49671
+ errorCode: obs.errorCode,
49672
+ errorText: obs.errorText,
49673
+ resultText: obs.resultText
49674
+ });
49226
49675
  if (reminder === void 0) return decision;
49227
49676
  return withAdditionalContexts(decision, [createRepeatBreakerReminder(reminder)]);
49228
49677
  } catch {
@@ -56746,7 +57195,7 @@ function assertClaudeCliVersionMeetsFloor(modelId, catalog = FALLBACK_MODELS) {
56746
57195
  if (floor === void 0) return;
56747
57196
  const effective = claudeCliVersion();
56748
57197
  if (meetsDottedVersionFloor(effective, floor)) return;
56749
- throw new LlmError("Claude(订阅) will not serve " + modelId + " to a client reporting version " + effective + ": upstream requires " + floor + " or newer for this model, and a lower claim is refused with claude_code_version_too_old. This was caught locally, before the request was sent. Raise the reported version with the DSH_CLAUDE_CLI_VERSION environment variable, or with a setClaudeCliVersion pin, then retry. The stored sign-in is still valid — this is not a credential problem and signing in again will not change it.", "PROVIDER_ERROR");
57198
+ throw new LlmError$1("Claude(订阅) will not serve " + modelId + " to a client reporting version " + effective + ": upstream requires " + floor + " or newer for this model, and a lower claim is refused with claude_code_version_too_old. This was caught locally, before the request was sent. Raise the reported version with the DSH_CLAUDE_CLI_VERSION environment variable, or with a setClaudeCliVersion pin, then retry. The stored sign-in is still valid — this is not a credential problem and signing in again will not change it.", "PROVIDER_ERROR");
56750
57199
  }
56751
57200
  const claudePrefixRequests = new PrefixRequestCoordinator();
56752
57201
  const claudeStickyImages = new StickyImageBudgetStore("claude");
@@ -56894,7 +57343,7 @@ var ClaudeAdapter = class ClaudeAdapter extends LlmAdapter {
56894
57343
  }));
56895
57344
  }
56896
57345
  async resolveModel(provider, modelId, signal) {
56897
- if (signal?.aborted) throw new LlmError("Claude model resolution aborted", "ABORTED");
57346
+ if (signal?.aborted) throw new LlmError$1("Claude model resolution aborted", "ABORTED");
56898
57347
  const settings = await this.settings();
56899
57348
  const record = await this.primaryAccount(settings);
56900
57349
  const catalog = record === null ? FALLBACK_MODELS : await this.catalog(record.credentials);
@@ -56943,7 +57392,7 @@ var ClaudeAdapter = class ClaudeAdapter extends LlmAdapter {
56943
57392
  async resolveCredential(pool, tried, fetchFn, signal) {
56944
57393
  if (pool === null) {
56945
57394
  const record = await this.primaryAccount(await this.settings());
56946
- if (record === null) throw new LlmError(MISSING_CREDENTIAL_MESSAGE, "MISSING_CREDENTIAL");
57395
+ if (record === null) throw new LlmError$1(MISSING_CREDENTIAL_MESSAGE, "MISSING_CREDENTIAL");
56947
57396
  try {
56948
57397
  return {
56949
57398
  credentials: await ensureAccessToken(new ClaudeAccountTokenStore(this.store, record.internalId), {
@@ -56953,8 +57402,8 @@ var ClaudeAdapter = class ClaudeAdapter extends LlmAdapter {
56953
57402
  accountId: void 0
56954
57403
  };
56955
57404
  } catch (error) {
56956
- if (error instanceof ClaudeUnauthorizedError) throw new LlmError(error.message, "INVALID_CREDENTIAL", { cause: error });
56957
- throw new LlmError("Claude credential could not be prepared: " + (error instanceof Error ? error.message : String(error)), "MISSING_CREDENTIAL", { cause: error });
57405
+ if (error instanceof ClaudeUnauthorizedError) throw new LlmError$1(error.message, "INVALID_CREDENTIAL", { cause: error });
57406
+ throw new LlmError$1("Claude credential could not be prepared: " + (error instanceof Error ? error.message : String(error)), "MISSING_CREDENTIAL", { cause: error });
56958
57407
  }
56959
57408
  }
56960
57409
  try {
@@ -56965,8 +57414,8 @@ var ClaudeAdapter = class ClaudeAdapter extends LlmAdapter {
56965
57414
  accountId: effective.account.id
56966
57415
  };
56967
57416
  } catch (error) {
56968
- if (error instanceof LlmError) throw error;
56969
- throw new LlmError(error instanceof Error ? error.message : MISSING_CREDENTIAL_MESSAGE, "MISSING_CREDENTIAL", { cause: error });
57417
+ if (error instanceof LlmError$1) throw error;
57418
+ throw new LlmError$1(error instanceof Error ? error.message : MISSING_CREDENTIAL_MESSAGE, "MISSING_CREDENTIAL", { cause: error });
56970
57419
  }
56971
57420
  }
56972
57421
  /**
@@ -57019,7 +57468,7 @@ var ClaudeAdapter = class ClaudeAdapter extends LlmAdapter {
57019
57468
  signal
57020
57469
  });
57021
57470
  } catch (error) {
57022
- if (signal.aborted) throw new LlmError("Claude request aborted", "ABORTED", { cause: error });
57471
+ if (signal.aborted) throw new LlmError$1("Claude request aborted", "ABORTED", { cause: error });
57023
57472
  throw toLlmError(networkFailure(error));
57024
57473
  }
57025
57474
  }
@@ -57078,8 +57527,8 @@ var ClaudeAdapter = class ClaudeAdapter extends LlmAdapter {
57078
57527
  }
57079
57528
  throw toLlmError(failure);
57080
57529
  }
57081
- if (response === void 0) throw new LlmError("Claude produced no response", "PROVIDER_ERROR");
57082
- if (response.body === null) throw new LlmError("Claude returned an empty response body", "PROVIDER_ERROR");
57530
+ if (response === void 0) throw new LlmError$1("Claude produced no response", "PROVIDER_ERROR");
57531
+ if (response.body === null) throw new LlmError$1("Claude returned an empty response body", "PROVIDER_ERROR");
57083
57532
  const reader = response.body.getReader();
57084
57533
  const decoder = new TextDecoder();
57085
57534
  const state = createStreamState$4(toolNames);
@@ -57114,14 +57563,14 @@ var ClaudeAdapter = class ClaudeAdapter extends LlmAdapter {
57114
57563
  yield chunk;
57115
57564
  }
57116
57565
  } catch (error) {
57117
- if (error instanceof LlmError) {
57566
+ if (error instanceof LlmError$1) {
57118
57567
  if (outputStarted || error.code !== "PROVIDER_ERROR" || state.streamError === void 0) throw error;
57119
57568
  const verdict = inBandStreamVerdict(error, state.streamError, response.headers);
57120
57569
  if (verdict.failure !== null && shouldRotateAccount(verdict.failure, outputStarted) && usedAccountId !== void 0) await pool?.markCooldown(usedAccountId, cooldownMsFor(verdict.failure), "Claude(订阅) in-stream 429").catch(() => void 0);
57121
57570
  throw verdict.error;
57122
57571
  }
57123
- if (signal.aborted) throw new LlmError("Claude request aborted", "ABORTED", { cause: error });
57124
- throw new LlmError("Claude stream failed: " + (error instanceof Error ? error.message : String(error)), outputStarted ? "PROVIDER_ERROR" : "TRANSPORT", { cause: error });
57572
+ if (signal.aborted) throw new LlmError$1("Claude request aborted", "ABORTED", { cause: error });
57573
+ throw new LlmError$1("Claude stream failed: " + (error instanceof Error ? error.message : String(error)), outputStarted ? "PROVIDER_ERROR" : "TRANSPORT", { cause: error });
57125
57574
  }
57126
57575
  } finally {
57127
57576
  reader.cancel().catch(() => void 0);
@@ -57247,7 +57696,7 @@ function inBandStreamVerdict(thrown, streamError, headers) {
57247
57696
  };
57248
57697
  const retryAfter = failure.retryAfterMs !== null && failure.retryAfterMs > 0 ? failure.retryAfterMs : void 0;
57249
57698
  return {
57250
- error: new LlmError(thrown.message, codeForFailure(failure), retryAfter === void 0 ? {} : { providerRetryAfterMs: retryAfter }),
57699
+ error: new LlmError$1(thrown.message, codeForFailure(failure), retryAfter === void 0 ? {} : { providerRetryAfterMs: retryAfter }),
57251
57700
  failure
57252
57701
  };
57253
57702
  }
@@ -57267,16 +57716,16 @@ function toLlmError(failure) {
57267
57716
  ...retryAfter === void 0 ? {} : { providerRetryAfterMs: retryAfter }
57268
57717
  };
57269
57718
  const detail = failure.message === "" ? "" : " " + failure.message;
57270
- if (failure.clientVersionTooOld) return new LlmError("Claude(订阅) refused this request because the client version it was told is below the server's floor (claude_code_version_too_old). Raise it with the DSH_CLAUDE_CLI_VERSION environment variable (or a setClaudeCliVersion pin), then retry — the stored sign-in is still valid." + detail, "PROVIDER_ERROR", options);
57271
- if (failure.kind === "request" && isHttpContextOverflow(failure.status, failure.message)) return new LlmError("Claude(订阅) context window exceeded." + detail, CONTEXT_OVERFLOW_CODE, options);
57719
+ if (failure.clientVersionTooOld) return new LlmError$1("Claude(订阅) refused this request because the client version it was told is below the server's floor (claude_code_version_too_old). Raise it with the DSH_CLAUDE_CLI_VERSION environment variable (or a setClaudeCliVersion pin), then retry — the stored sign-in is still valid." + detail, "PROVIDER_ERROR", options);
57720
+ if (failure.kind === "request" && isHttpContextOverflow(failure.status, failure.message)) return new LlmError$1("Claude(订阅) context window exceeded." + detail, CONTEXT_OVERFLOW_CODE, options);
57272
57721
  switch (failure.kind) {
57273
- case "credential": return new LlmError("Claude(订阅) rejected the stored credential. Sign in again from Settings > Claude." + detail, "INVALID_CREDENTIAL", options);
57722
+ case "credential": return new LlmError$1("Claude(订阅) rejected the stored credential. Sign in again from Settings > Claude." + detail, "INVALID_CREDENTIAL", options);
57274
57723
  case "rate_limit_account":
57275
- case "rate_limit_global": return new LlmError("Claude(订阅) rate limit reached" + (failure.accountScoped ? " for this account" : "") + (failure.resetsAt === null ? "" : ", resets at " + failure.resetsAt) + ". Check the quota card in Settings > Claude." + detail, "RATE_LIMIT", options);
57276
- case "overloaded": return new LlmError("Claude(订阅) is temporarily overloaded." + detail, "SERVER", options);
57277
- case "server": return new LlmError("Claude(订阅) upstream server error (" + failure.status + ")." + detail, "SERVER", options);
57278
- case "request": return new LlmError("Claude(订阅) rejected the request." + detail, "PROVIDER_ERROR", options);
57279
- default: return new LlmError("Claude(订阅) request failed before a response arrived." + detail, "TRANSPORT", options);
57724
+ case "rate_limit_global": return new LlmError$1("Claude(订阅) rate limit reached" + (failure.accountScoped ? " for this account" : "") + (failure.resetsAt === null ? "" : ", resets at " + failure.resetsAt) + ". Check the quota card in Settings > Claude." + detail, "RATE_LIMIT", options);
57725
+ case "overloaded": return new LlmError$1("Claude(订阅) is temporarily overloaded." + detail, "SERVER", options);
57726
+ case "server": return new LlmError$1("Claude(订阅) upstream server error (" + failure.status + ")." + detail, "SERVER", options);
57727
+ case "request": return new LlmError$1("Claude(订阅) rejected the request." + detail, "PROVIDER_ERROR", options);
57728
+ default: return new LlmError$1("Claude(订阅) request failed before a response arrived." + detail, "TRANSPORT", options);
57280
57729
  }
57281
57730
  }
57282
57731
  //#endregion
@@ -64062,7 +64511,7 @@ function glmCooldownDecision(input) {
64062
64511
  function requireWire(modelId, entry) {
64063
64512
  const wire = entry.wire;
64064
64513
  if (wire === "anthropic" || wire === "openai") return wire;
64065
- throw new LlmError("GLM(ZCode 账号) 的模型目录里没有 " + modelId + " 的协议声明,无法选择调用面。请在设置页刷新模型目录;若这是上游新增的模型,本插件还没记录它走哪个面。", "NOT_FOUND");
64514
+ throw new LlmError$1("GLM(ZCode 账号) 的模型目录里没有 " + modelId + " 的协议声明,无法选择调用面。请在设置页刷新模型目录;若这是上游新增的模型,本插件还没记录它走哪个面。", "NOT_FOUND");
64066
64515
  }
64067
64516
  /**
64068
64517
  * 构造一次请求。**不联网、不读设置**,所以可以被单独测。
@@ -64186,7 +64635,7 @@ var GlmCodingPlanAdapter = class extends LlmAdapter {
64186
64635
  };
64187
64636
  }
64188
64637
  const stored = await this.store.read();
64189
- if (stored === null) throw new LlmError("还没有登录 GLM(ZCode 账号) 账号。请在设置页点击登录,或先在 ZCode 客户端登录后使用 adopt。", "MISSING_CREDENTIAL");
64638
+ if (stored === null) throw new LlmError$1("还没有登录 GLM(ZCode 账号) 账号。请在设置页点击登录,或先在 ZCode 客户端登录后使用 adopt。", "MISSING_CREDENTIAL");
64190
64639
  return {
64191
64640
  accountId: null,
64192
64641
  credentials: stored
@@ -64208,7 +64657,7 @@ var GlmCodingPlanAdapter = class extends LlmAdapter {
64208
64657
  }));
64209
64658
  }
64210
64659
  async resolveModel(provider, model, signal) {
64211
- if (signal?.aborted) throw new LlmError(t("glm.modelResolveAborted", { provider: PROVIDER_NAME$1 }), "ABORTED");
64660
+ if (signal?.aborted) throw new LlmError$1(t("glm.modelResolveAborted", { provider: PROVIDER_NAME$1 }), "ABORTED");
64212
64661
  const settings = await this.settings();
64213
64662
  const region = await this.catalogRegion(settings) ?? "intl";
64214
64663
  const entry = resolveGlmModel(model, this.catalog(region));
@@ -64277,8 +64726,8 @@ var GlmCodingPlanAdapter = class extends LlmAdapter {
64277
64726
  });
64278
64727
  activity?.pulse();
64279
64728
  } catch (error) {
64280
- if (signal.aborted) throw new LlmError(t("glm.requestAborted", { provider: PROVIDER_NAME$1 }), "ABORTED", { cause: error });
64281
- throw new LlmError(t("glm.requestFailed", {
64729
+ if (signal.aborted) throw new LlmError$1(t("glm.requestAborted", { provider: PROVIDER_NAME$1 }), "ABORTED", { cause: error });
64730
+ throw new LlmError$1(t("glm.requestFailed", {
64282
64731
  provider: PROVIDER_NAME$1,
64283
64732
  detail: error instanceof Error ? error.message : String(error)
64284
64733
  }), "TRANSPORT", { cause: error });
@@ -64318,8 +64767,8 @@ var GlmCodingPlanAdapter = class extends LlmAdapter {
64318
64767
  throw failure;
64319
64768
  }
64320
64769
  const settled = plan;
64321
- if (response === void 0) throw new LlmError(t("glm.noResponse", { provider: PROVIDER_NAME$1 }), "PROVIDER_ERROR");
64322
- if (response.body === null) throw new LlmError(t("glm.emptyBody", { provider: PROVIDER_NAME$1 }), "PROVIDER_ERROR");
64770
+ if (response === void 0) throw new LlmError$1(t("glm.noResponse", { provider: PROVIDER_NAME$1 }), "PROVIDER_ERROR");
64771
+ if (response.body === null) throw new LlmError$1(t("glm.emptyBody", { provider: PROVIDER_NAME$1 }), "PROVIDER_ERROR");
64323
64772
  const reader = response.body.getReader();
64324
64773
  const decoder = new TextDecoder();
64325
64774
  let buffer = "";
@@ -64342,7 +64791,7 @@ var GlmCodingPlanAdapter = class extends LlmAdapter {
64342
64791
  buffer += decoder.decode();
64343
64792
  if (buffer.trim() !== "") for (const line of buffer.split("\n")) for (const chunk of processGlmAnthropicStreamLine(line, state)) yield chunk;
64344
64793
  if (state.finished) return;
64345
- if (!glmStreamHasContent(state)) throw new LlmError(t("glm.anthropicEmpty", { provider: PROVIDER_NAME$1 }), "PROVIDER_ERROR");
64794
+ if (!glmStreamHasContent(state)) throw new LlmError$1(t("glm.anthropicEmpty", { provider: PROVIDER_NAME$1 }), "PROVIDER_ERROR");
64346
64795
  assertGlmStreamComplete(state);
64347
64796
  for (const chunk of closeGlmAnthropicStream(state)) yield chunk;
64348
64797
  } finally {
@@ -68862,7 +69311,7 @@ var StepCodeAdapter = class extends LlmAdapter {
68862
69311
  };
68863
69312
  }
68864
69313
  const stored = await this.store.read();
68865
- if (stored === null) throw new LlmError("还没有登录 Step Code(Step Plan 订阅) 账号。请在设置页点击登录、在 stepcode 客户端登录后使用导入,或粘贴一个 Platform API Key。", "MISSING_CREDENTIAL");
69314
+ if (stored === null) throw new LlmError$1("还没有登录 Step Code(Step Plan 订阅) 账号。请在设置页点击登录、在 stepcode 客户端登录后使用导入,或粘贴一个 Platform API Key。", "MISSING_CREDENTIAL");
68866
69315
  return {
68867
69316
  accountId: null,
68868
69317
  credentials: {
@@ -68914,7 +69363,7 @@ var StepCodeAdapter = class extends LlmAdapter {
68914
69363
  }));
68915
69364
  }
68916
69365
  async resolveModel(provider, model, signal) {
68917
- if (signal?.aborted) throw new LlmError(t("sc.modelResolveAborted", { provider: PROVIDER_NAME$6 }), "ABORTED");
69366
+ if (signal?.aborted) throw new LlmError$1(t("sc.modelResolveAborted", { provider: PROVIDER_NAME$6 }), "ABORTED");
68918
69367
  const settings = await this.settings();
68919
69368
  const picked = await this.credentialFor().catch(() => null);
68920
69369
  const catalog = this.catalog(picked?.credentials.profile);
@@ -68984,8 +69433,8 @@ var StepCodeAdapter = class extends LlmAdapter {
68984
69433
  });
68985
69434
  activity?.pulse();
68986
69435
  } catch (error) {
68987
- if (signal.aborted) throw new LlmError(t("sc.requestAborted", { provider: PROVIDER_NAME$6 }), "ABORTED", { cause: error });
68988
- throw new LlmError(t("sc.requestFailed", {
69436
+ if (signal.aborted) throw new LlmError$1(t("sc.requestAborted", { provider: PROVIDER_NAME$6 }), "ABORTED", { cause: error });
69437
+ throw new LlmError$1(t("sc.requestFailed", {
68989
69438
  provider: PROVIDER_NAME$6,
68990
69439
  detail: error instanceof Error ? error.message : String(error)
68991
69440
  }), "TRANSPORT", { cause: error });
@@ -69011,8 +69460,8 @@ var StepCodeAdapter = class extends LlmAdapter {
69011
69460
  }
69012
69461
  throw failure;
69013
69462
  }
69014
- if (response === void 0) throw new LlmError(t("sc.noResponse", { provider: PROVIDER_NAME$6 }), "PROVIDER_ERROR");
69015
- if (response.body === null) throw new LlmError(t("sc.emptyBody", { provider: PROVIDER_NAME$6 }), "PROVIDER_ERROR");
69463
+ if (response === void 0) throw new LlmError$1(t("sc.noResponse", { provider: PROVIDER_NAME$6 }), "PROVIDER_ERROR");
69464
+ if (response.body === null) throw new LlmError$1(t("sc.emptyBody", { provider: PROVIDER_NAME$6 }), "PROVIDER_ERROR");
69016
69465
  const reader = response.body.getReader();
69017
69466
  const decoder = new TextDecoder();
69018
69467
  const state = createStreamState$2();
@@ -72489,7 +72938,7 @@ function serializeMessages(messages, images) {
72489
72938
  * raised locally with the id that has no question.
72490
72939
  */
72491
72940
  const answer = (callId, content) => {
72492
- if (!awaiting.includes(callId)) throw new LlmError(`tool result for call "${callId}" has no tool_call awaiting it: the conversation cannot be expressed as a valid OpenAI message sequence`, "INVALID_REQUEST");
72941
+ if (!awaiting.includes(callId)) throw new LlmError$1(`tool result for call "${callId}" has no tool_call awaiting it: the conversation cannot be expressed as a valid OpenAI message sequence`, "INVALID_REQUEST");
72493
72942
  wire.push({
72494
72943
  role: "tool",
72495
72944
  tool_call_id: callId,
@@ -72712,7 +73161,7 @@ async function* parseServerSentEvents$1(body) {
72712
73161
  yield JSON.parse(payload);
72713
73162
  } catch {}
72714
73163
  }
72715
- throw new LlmError("stream ended without [DONE]", "STREAM_CLOSED");
73164
+ throw new LlmError$1("stream ended without [DONE]", "STREAM_CLOSED");
72716
73165
  }
72717
73166
  /** Assemble the terminal content block for one open block. */
72718
73167
  function closeBlock$1(block) {
@@ -72846,7 +73295,7 @@ async function* translate(payloads) {
72846
73295
  return;
72847
73296
  }
72848
73297
  const chunk = unwrapEnvelope(payload);
72849
- if (chunk.error !== void 0 && chunk.choices === void 0) throw new LlmError(errorText$1(chunk.error), streamErrorCode$1(errorText$1(chunk.error)));
73298
+ if (chunk.error !== void 0 && chunk.choices === void 0) throw new LlmError$1(errorText$1(chunk.error), streamErrorCode$1(errorText$1(chunk.error)));
72850
73299
  const choices = Array.isArray(chunk.choices) ? chunk.choices : [];
72851
73300
  for (const choice of choices) {
72852
73301
  if (!isRecord$26(choice)) continue;
@@ -72921,7 +73370,7 @@ async function* translate(payloads) {
72921
73370
  for (const chunk of closing()) yield chunk;
72922
73371
  return;
72923
73372
  }
72924
- throw new LlmError("stream ended without [DONE]", "STREAM_CLOSED");
73373
+ throw new LlmError$1("stream ended without [DONE]", "STREAM_CLOSED");
72925
73374
  }
72926
73375
  //#endregion
72927
73376
  //#region src/host/cline-pass/adapter.ts
@@ -73064,7 +73513,7 @@ var ClinePassAdapter = class extends LlmAdapter {
73064
73513
  }));
73065
73514
  }
73066
73515
  async resolveModel(provider, modelId, signal) {
73067
- if (signal?.aborted) throw new LlmError("Cline Pass model resolution aborted", "ABORTED");
73516
+ if (signal?.aborted) throw new LlmError$1("Cline Pass model resolution aborted", "ABORTED");
73068
73517
  const info = await this.modelInfo(modelId);
73069
73518
  return {
73070
73519
  provider,
@@ -73091,10 +73540,10 @@ var ClinePassAdapter = class extends LlmAdapter {
73091
73540
  yield* wrapStreamWithWatchdog((watchdogSignal, activity) => this.requestStream(options, settings, watchdogSignal, activity), options.signal, settings.streamIdleTimeoutMs, STREAM_IDLE_TIMEOUT_CODE$6, PROVIDER_NAME$5);
73092
73541
  }
73093
73542
  async *requestStream(rawOptions, settings, signal, activity) {
73094
- if (settings.enabled === false) throw new LlmError(`${PROVIDER_NAME$5} is disabled in Settings > Subscription. Enable the line there, then retry.`, "INVALID_REQUEST");
73543
+ if (settings.enabled === false) throw new LlmError$1(`${PROVIDER_NAME$5} is disabled in Settings > Subscription. Enable the line there, then retry.`, "INVALID_REQUEST");
73095
73544
  const normalized = normalizeGenerateOptions(rawOptions);
73096
73545
  const images = await resolveRequestImages$1(normalized, this.options.attachments, signal).catch((error) => {
73097
- if (signal.aborted) throw new LlmError("Cline Pass request aborted by caller", "ABORTED", { cause: error });
73546
+ if (signal.aborted) throw new LlmError$1("Cline Pass request aborted by caller", "ABORTED", { cause: error });
73098
73547
  return NO_RESOLVED_IMAGES$3;
73099
73548
  });
73100
73549
  const options = offloadOldestRequestImages$1(normalized, void 0, images);
@@ -73131,7 +73580,7 @@ var ClinePassAdapter = class extends LlmAdapter {
73131
73580
  try {
73132
73581
  release = await this.gate.acquire(account.id, upstream);
73133
73582
  } catch (error) {
73134
- if (signal.aborted) throw new LlmError("Cline Pass request aborted by caller", "ABORTED", { cause: error });
73583
+ if (signal.aborted) throw new LlmError$1("Cline Pass request aborted by caller", "ABORTED", { cause: error });
73135
73584
  throw error;
73136
73585
  }
73137
73586
  const attemptLabel = "(auto)";
@@ -73147,13 +73596,13 @@ var ClinePassAdapter = class extends LlmAdapter {
73147
73596
  break;
73148
73597
  } catch (error) {
73149
73598
  headerDeadline.clear();
73150
- if (signal.aborted) throw new LlmError("Cline Pass request aborted by caller", "ABORTED", { cause: error });
73599
+ if (signal.aborted) throw new LlmError$1("Cline Pass request aborted by caller", "ABORTED", { cause: error });
73151
73600
  transportError = error;
73152
73601
  if (transportTry < TRANSPORT_RETRIES$1 && isPreConnectionFailure$1(error)) {
73153
73602
  try {
73154
73603
  await setTimeout$1(TRANSPORT_RETRY_BASE_MS$1 * (transportTry + 1), void 0, { signal: upstream });
73155
73604
  } catch (waitError) {
73156
- if (signal.aborted) throw new LlmError("Cline Pass request aborted by caller", "ABORTED", { cause: waitError });
73605
+ if (signal.aborted) throw new LlmError$1("Cline Pass request aborted by caller", "ABORTED", { cause: waitError });
73157
73606
  throw waitError;
73158
73607
  }
73159
73608
  continue;
@@ -73165,7 +73614,7 @@ var ClinePassAdapter = class extends LlmAdapter {
73165
73614
  const note = errorChain$2(transportError);
73166
73615
  const hint = isPreConnectionFailure$1(transportError) ? ` The request never reached the gateway: ${account.baseURL} failed during TLS/connect. Check the network, proxy or TUN, or set a custom proxy in the plugin.` : "";
73167
73616
  trace.push(attemptLabel);
73168
- lastError = new LlmError(note + hint, "TRANSPORT", { cause: transportError });
73617
+ lastError = new LlmError$1(note + hint, "TRANSPORT", { cause: transportError });
73169
73618
  continue;
73170
73619
  }
73171
73620
  if (!response.ok) {
@@ -73176,7 +73625,7 @@ var ClinePassAdapter = class extends LlmAdapter {
73176
73625
  } catch {}
73177
73626
  trace.push(attemptLabel);
73178
73627
  const code = streamErrorCode$1(detail, response.status);
73179
- lastError = new LlmError(`${detail || `HTTP ${response.status}`} [model=${options.model}]`, code, { status: response.status });
73628
+ lastError = new LlmError$1(`${detail || `HTTP ${response.status}`} [model=${options.model}]`, code, { status: response.status });
73180
73629
  if (code === "AUTH" || code === "QUOTA") {
73181
73630
  refused.add(account.id);
73182
73631
  await this.standDown(account.id, code, detail);
@@ -73195,7 +73644,7 @@ var ClinePassAdapter = class extends LlmAdapter {
73195
73644
  continue;
73196
73645
  }
73197
73646
  if (response.body === null) {
73198
- lastError = new LlmError("gateway returned no response body", "EMPTY_RESPONSE", { status: response.status });
73647
+ lastError = new LlmError$1("gateway returned no response body", "EMPTY_RESPONSE", { status: response.status });
73199
73648
  continue;
73200
73649
  }
73201
73650
  const observed = {
@@ -73245,9 +73694,9 @@ var ClinePassAdapter = class extends LlmAdapter {
73245
73694
  yield chunk;
73246
73695
  }
73247
73696
  } catch (error) {
73248
- if (signal.aborted) throw new LlmError("Cline Pass request aborted by caller", "ABORTED", { cause: error });
73249
- const note = error instanceof LlmError ? error.message : errorChain$2(error);
73250
- const code = error instanceof LlmError ? error.code : "TRANSPORT";
73697
+ if (signal.aborted) throw new LlmError$1("Cline Pass request aborted by caller", "ABORTED", { cause: error });
73698
+ const note = error instanceof LlmError$1 ? error.message : errorChain$2(error);
73699
+ const code = error instanceof LlmError$1 ? error.code : "TRANSPORT";
73251
73700
  trace.push(attemptLabel);
73252
73701
  if (yielded) {
73253
73702
  this.store.record({
@@ -73263,7 +73712,7 @@ var ClinePassAdapter = class extends LlmAdapter {
73263
73712
  code,
73264
73713
  account: account.name
73265
73714
  });
73266
- throw error instanceof LlmError ? error : new LlmError(note, "TRANSPORT", { cause: error });
73715
+ throw error instanceof LlmError$1 ? error : new LlmError$1(note, "TRANSPORT", { cause: error });
73267
73716
  }
73268
73717
  if (code === "AUTH" || code === "QUOTA") {
73269
73718
  refused.add(account.id);
@@ -73283,7 +73732,7 @@ var ClinePassAdapter = class extends LlmAdapter {
73283
73732
  account: account.name
73284
73733
  });
73285
73734
  }
73286
- lastError = error instanceof LlmError ? error : new LlmError(note, "TRANSPORT", { cause: error });
73735
+ lastError = error instanceof LlmError$1 ? error : new LlmError$1(note, "TRANSPORT", { cause: error });
73287
73736
  continue;
73288
73737
  } finally {
73289
73738
  consumer.abort("Cline Pass stream consumer stopped");
@@ -73295,7 +73744,7 @@ var ClinePassAdapter = class extends LlmAdapter {
73295
73744
  try {
73296
73745
  await setTimeout$1(EMPTY_REPLY_DELAY_MS, void 0, { signal });
73297
73746
  } catch (waitError) {
73298
- if (signal.aborted) throw new LlmError("Cline Pass request aborted by caller", "ABORTED", { cause: waitError });
73747
+ if (signal.aborted) throw new LlmError$1("Cline Pass request aborted by caller", "ABORTED", { cause: waitError });
73299
73748
  throw waitError;
73300
73749
  }
73301
73750
  attemptIndex -= 1;
@@ -73357,7 +73806,7 @@ var ClinePassAdapter = class extends LlmAdapter {
73357
73806
  error: message.slice(0, 200),
73358
73807
  account: ""
73359
73808
  });
73360
- throw lastError ?? new LlmError(`${message} [model=${options.model}]`, "UPSTREAM");
73809
+ throw lastError ?? new LlmError$1(`${message} [model=${options.model}]`, "UPSTREAM");
73361
73810
  }
73362
73811
  }
73363
73812
  /** Park an account that refused a request, for the reason it refused. */
@@ -79024,7 +79473,7 @@ var QoderAdapter = class extends LlmAdapter {
79024
79473
  };
79025
79474
  }
79026
79475
  const stored = await this.store.read();
79027
- if (stored === null) throw new LlmError("还没有登录 Qoder(订阅) 账号。请在设置页点击登录(全球区)、粘贴 PAT,或在本机 qodercli 登录后使用导入。", "MISSING_CREDENTIAL");
79476
+ if (stored === null) throw new LlmError$1("还没有登录 Qoder(订阅) 账号。请在设置页点击登录(全球区)、粘贴 PAT,或在本机 qodercli 登录后使用导入。", "MISSING_CREDENTIAL");
79028
79477
  return {
79029
79478
  accountId: null,
79030
79479
  credentials: upstreamCredentialOf$1(stored)
@@ -79048,7 +79497,7 @@ var QoderAdapter = class extends LlmAdapter {
79048
79497
  }));
79049
79498
  }
79050
79499
  async resolveModel(provider, model, signal) {
79051
- if (signal?.aborted) throw new LlmError(t("qo.modelResolveAborted", { provider: PROVIDER_NAME$4 }), "ABORTED");
79500
+ if (signal?.aborted) throw new LlmError$1(t("qo.modelResolveAborted", { provider: PROVIDER_NAME$4 }), "ABORTED");
79052
79501
  const settings = await this.settings();
79053
79502
  const region = (await this.credentialFor().catch(() => null))?.credentials.region ?? "global";
79054
79503
  const catalog = this.catalog(region);
@@ -79195,8 +79644,8 @@ var QoderAdapter = class extends LlmAdapter {
79195
79644
  });
79196
79645
  activity?.pulse();
79197
79646
  } catch (error) {
79198
- if (signal.aborted) throw new LlmError(t("qo.requestAborted", { provider: PROVIDER_NAME$4 }), "ABORTED", { cause: error });
79199
- throw new LlmError(t("qo.requestFailed", {
79647
+ if (signal.aborted) throw new LlmError$1(t("qo.requestAborted", { provider: PROVIDER_NAME$4 }), "ABORTED", { cause: error });
79648
+ throw new LlmError$1(t("qo.requestFailed", {
79200
79649
  provider: PROVIDER_NAME$4,
79201
79650
  detail: error instanceof Error ? error.message : String(error)
79202
79651
  }), "TRANSPORT", { cause: error });
@@ -79207,7 +79656,7 @@ var QoderAdapter = class extends LlmAdapter {
79207
79656
  if (await handlePreContentFailure(failure, response.headers)) continue;
79208
79657
  throw failure;
79209
79658
  }
79210
- if (response.body === null) throw new LlmError(t("qo.emptyBody", { provider: PROVIDER_NAME$4 }), "PROVIDER_ERROR");
79659
+ if (response.body === null) throw new LlmError$1(t("qo.emptyBody", { provider: PROVIDER_NAME$4 }), "PROVIDER_ERROR");
79211
79660
  const reader = response.body.getReader();
79212
79661
  const decoder = new TextDecoder();
79213
79662
  const state = createQoderStreamState();
@@ -79243,7 +79692,7 @@ var QoderAdapter = class extends LlmAdapter {
79243
79692
  }
79244
79693
  return;
79245
79694
  } catch (error) {
79246
- if (!yielded && error instanceof LlmError) {
79695
+ if (!yielded && error instanceof LlmError$1) {
79247
79696
  if (await handlePreContentFailure(error, response.headers)) continue;
79248
79697
  }
79249
79698
  throw error;
@@ -83179,7 +83628,7 @@ function serializeMessages$1(messages, images) {
83179
83628
  };
83180
83629
  /** A tool answer: it closes its own id, and the group when it was the last. */
83181
83630
  const answer = (callId, content) => {
83182
- if (!awaiting.includes(callId)) throw new LlmError(`OpenDesign request is invalid: the tool result for call id "${callId}" has no pending tool call to answer, so the message list would carry a tool message that no assistant tool_calls message introduced. Nothing was sent.`, "INVALID_REQUEST");
83631
+ if (!awaiting.includes(callId)) throw new LlmError$1(`OpenDesign request is invalid: the tool result for call id "${callId}" has no pending tool call to answer, so the message list would carry a tool message that no assistant tool_calls message introduced. Nothing was sent.`, "INVALID_REQUEST");
83183
83632
  wire.push({
83184
83633
  role: "tool",
83185
83634
  tool_call_id: callId,
@@ -83531,7 +83980,7 @@ async function* parseServerSentEvents(body) {
83531
83980
  yield JSON.parse(payload);
83532
83981
  } catch {}
83533
83982
  }
83534
- throw new LlmError("stream ended without [DONE]", "STREAM_CLOSED");
83983
+ throw new LlmError$1("stream ended without [DONE]", "STREAM_CLOSED");
83535
83984
  }
83536
83985
  /**
83537
83986
  * Whether one failure is the SSE parser's own "the body ended without [DONE]".
@@ -83667,7 +84116,7 @@ async function* translate$1(payloads) {
83667
84116
  for (const chunk of terminal(reason)) yield chunk;
83668
84117
  return;
83669
84118
  }
83670
- if (isErrorPayload(payload)) throw new LlmError(errorText(payload.error), streamErrorCode(errorText(payload.error)));
84119
+ if (isErrorPayload(payload)) throw new LlmError$1(errorText(payload.error), streamErrorCode(errorText(payload.error)));
83671
84120
  const chunk = isRecord$17(payload) ? payload : {};
83672
84121
  const choices = Array.isArray(chunk.choices) ? chunk.choices : [];
83673
84122
  for (const choice of choices) {
@@ -83743,7 +84192,7 @@ async function* translate$1(payloads) {
83743
84192
  for (const chunk of terminal(pendingFinish)) yield chunk;
83744
84193
  return;
83745
84194
  }
83746
- throw new LlmError("stream ended without [DONE]", "STREAM_CLOSED");
84195
+ throw new LlmError$1("stream ended without [DONE]", "STREAM_CLOSED");
83747
84196
  }
83748
84197
  //#endregion
83749
84198
  //#region src/host/opendesign/adapter.ts
@@ -83871,7 +84320,7 @@ var OpenDesignAdapter = class extends LlmAdapter {
83871
84320
  }));
83872
84321
  }
83873
84322
  async resolveModel(provider, modelId, signal) {
83874
- if (signal?.aborted) throw new LlmError("OpenDesign model resolution aborted", "ABORTED");
84323
+ if (signal?.aborted) throw new LlmError$1("OpenDesign model resolution aborted", "ABORTED");
83875
84324
  const info = await this.modelInfo(modelId);
83876
84325
  return {
83877
84326
  provider,
@@ -83902,13 +84351,13 @@ var OpenDesignAdapter = class extends LlmAdapter {
83902
84351
  }
83903
84352
  /** The message the pool's empty state should raise, in this line's words. */
83904
84353
  noAccountError(cause) {
83905
- return new LlmError(`${PROVIDER_NAME$2} has no usable account: ${cause instanceof Error ? cause.message : String(cause)} Add an API key from the OpenDesign Cloud console in Settings > Subscription.`, "AUTH", { cause });
84354
+ return new LlmError$1(`${PROVIDER_NAME$2} has no usable account: ${cause instanceof Error ? cause.message : String(cause)} Add an API key from the OpenDesign Cloud console in Settings > Subscription.`, "AUTH", { cause });
83906
84355
  }
83907
84356
  async *requestStream(rawOptions, settings, signal, activity) {
83908
- if (settings.enabled === false) throw new LlmError(`${PROVIDER_NAME$2} is disabled in Settings > Subscription. Enable the line there, then retry.`, "INVALID_REQUEST");
84357
+ if (settings.enabled === false) throw new LlmError$1(`${PROVIDER_NAME$2} is disabled in Settings > Subscription. Enable the line there, then retry.`, "INVALID_REQUEST");
83909
84358
  const normalized = normalizeGenerateOptions(rawOptions);
83910
84359
  const images = await resolveRequestImages$1(normalized, this.options.attachments, signal).catch((error) => {
83911
- if (signal.aborted) throw new LlmError("OpenDesign request aborted by caller", "ABORTED", { cause: error });
84360
+ if (signal.aborted) throw new LlmError$1("OpenDesign request aborted by caller", "ABORTED", { cause: error });
83912
84361
  return NO_RESOLVED_IMAGES$3;
83913
84362
  });
83914
84363
  const options = offloadOldestRequestImages$1(normalized, MAX_REQUEST_IMAGE_BYTES$1, images);
@@ -83933,7 +84382,7 @@ var OpenDesignAdapter = class extends LlmAdapter {
83933
84382
  this.gate.setLimit(account.id, settings.maxConcurrentRequests);
83934
84383
  release = await this.gate.acquire(account.id, upstream);
83935
84384
  } catch (error) {
83936
- if (signal.aborted) throw new LlmError("OpenDesign request aborted by caller", "ABORTED", { cause: error });
84385
+ if (signal.aborted) throw new LlmError$1("OpenDesign request aborted by caller", "ABORTED", { cause: error });
83937
84386
  throw error;
83938
84387
  }
83939
84388
  try {
@@ -83954,13 +84403,13 @@ var OpenDesignAdapter = class extends LlmAdapter {
83954
84403
  break;
83955
84404
  } catch (error) {
83956
84405
  headerDeadline.clear();
83957
- if (signal.aborted) throw new LlmError("OpenDesign request aborted by caller", "ABORTED", { cause: error });
84406
+ if (signal.aborted) throw new LlmError$1("OpenDesign request aborted by caller", "ABORTED", { cause: error });
83958
84407
  transportError = error;
83959
84408
  if (transportTry < TRANSPORT_RETRIES && isPreConnectionFailure(error)) {
83960
84409
  try {
83961
84410
  await setTimeout$1(TRANSPORT_RETRY_BASE_MS * (transportTry + 1), void 0, { signal: upstream });
83962
84411
  } catch (waitError) {
83963
- if (signal.aborted) throw new LlmError("OpenDesign request aborted by caller", "ABORTED", { cause: waitError });
84412
+ if (signal.aborted) throw new LlmError$1("OpenDesign request aborted by caller", "ABORTED", { cause: waitError });
83964
84413
  throw waitError;
83965
84414
  }
83966
84415
  continue;
@@ -83969,7 +84418,7 @@ var OpenDesignAdapter = class extends LlmAdapter {
83969
84418
  }
83970
84419
  }
83971
84420
  if (response === void 0) {
83972
- lastError = new LlmError(`${errorChain$1(transportError)} The request never reached the gateway: ${baseURL} failed during TLS/connect. Check the network or proxy.`, "TRANSPORT", { cause: transportError });
84421
+ lastError = new LlmError$1(`${errorChain$1(transportError)} The request never reached the gateway: ${baseURL} failed during TLS/connect. Check the network or proxy.`, "TRANSPORT", { cause: transportError });
83973
84422
  break;
83974
84423
  }
83975
84424
  if (!response.ok) {
@@ -83984,7 +84433,7 @@ var OpenDesignAdapter = class extends LlmAdapter {
83984
84433
  continue;
83985
84434
  }
83986
84435
  const code = streamErrorCode(detail, response.status);
83987
- lastError = new LlmError(`${detail || `HTTP ${response.status}`} [model=${options.model}]`, code, { status: response.status });
84436
+ lastError = new LlmError$1(`${detail || `HTTP ${response.status}`} [model=${options.model}]`, code, { status: response.status });
83988
84437
  if (code === "AUTH" || code === "QUOTA") {
83989
84438
  refused.add(account.id);
83990
84439
  await this.standDown(account.id, code, detail);
@@ -83997,7 +84446,7 @@ var OpenDesignAdapter = class extends LlmAdapter {
83997
84446
  break;
83998
84447
  }
83999
84448
  if (response.body === null) {
84000
- lastError = new LlmError("gateway returned no response body", "EMPTY_RESPONSE", { status: response.status });
84449
+ lastError = new LlmError$1("gateway returned no response body", "EMPTY_RESPONSE", { status: response.status });
84001
84450
  break;
84002
84451
  }
84003
84452
  const iterator = translate$1(parseServerSentEvents(tapChunks(response.body, () => activity?.pulse())))[Symbol.asyncIterator]();
@@ -84010,17 +84459,17 @@ var OpenDesignAdapter = class extends LlmAdapter {
84010
84459
  yield next.value;
84011
84460
  }
84012
84461
  } catch (error) {
84013
- if (signal.aborted) throw new LlmError("OpenDesign request aborted by caller", "ABORTED", { cause: error });
84014
- const note = error instanceof LlmError ? error.message : errorChain$1(error);
84015
- const code = error instanceof LlmError ? error.code : "TRANSPORT";
84016
- if (yielded) throw error instanceof LlmError ? error : new LlmError(note, "TRANSPORT", { cause: error });
84462
+ if (signal.aborted) throw new LlmError$1("OpenDesign request aborted by caller", "ABORTED", { cause: error });
84463
+ const note = error instanceof LlmError$1 ? error.message : errorChain$1(error);
84464
+ const code = error instanceof LlmError$1 ? error.code : "TRANSPORT";
84465
+ if (yielded) throw error instanceof LlmError$1 ? error : new LlmError$1(note, "TRANSPORT", { cause: error });
84017
84466
  if (code === "AUTH" || code === "QUOTA") {
84018
84467
  refused.add(account.id);
84019
84468
  await this.standDown(account.id, code, note);
84020
- lastError = error instanceof LlmError ? error : new LlmError(note, "TRANSPORT", { cause: error });
84469
+ lastError = error instanceof LlmError$1 ? error : new LlmError$1(note, "TRANSPORT", { cause: error });
84021
84470
  continue;
84022
84471
  }
84023
- lastError = error instanceof LlmError ? error : new LlmError(note, "TRANSPORT", { cause: error });
84472
+ lastError = error instanceof LlmError$1 ? error : new LlmError$1(note, "TRANSPORT", { cause: error });
84024
84473
  break;
84025
84474
  } finally {
84026
84475
  consumer.abort("OpenDesign stream consumer stopped");
@@ -84032,7 +84481,7 @@ var OpenDesignAdapter = class extends LlmAdapter {
84032
84481
  release();
84033
84482
  }
84034
84483
  }
84035
- throw lastError ?? new LlmError(`no account could serve the request [model=${options.model}]`, "UPSTREAM");
84484
+ throw lastError ?? new LlmError$1(`no account could serve the request [model=${options.model}]`, "UPSTREAM");
84036
84485
  }
84037
84486
  /** Park an account that refused a request, for the reason it refused. */
84038
84487
  async standDown(accountId, code, detail) {
@@ -88990,6 +89439,31 @@ function installCompactionPolicyGuard(ctx, options = {}) {
88990
89439
  if (isRecord$11(optionsField)) observe(readString(optionsField["provider"]), readString(optionsField["model"]));
88991
89440
  const config = source["config"];
88992
89441
  if (isRecord$11(config)) observe(readString(config["provider"]), readString(config["model"]));
89442
+ const modelField = source["model"];
89443
+ if (isRecord$11(modelField) && typeof modelField["current"] === "function") {
89444
+ let current;
89445
+ try {
89446
+ current = modelField["current"].call(modelField);
89447
+ } catch {
89448
+ current = void 0;
89449
+ }
89450
+ if (isRecord$11(current)) observe(readString(current["provider"]), readString(current["model"]));
89451
+ }
89452
+ const messages = source["messages"];
89453
+ if (Array.isArray(messages)) for (let i = messages.length - 1; i >= 0; i -= 1) {
89454
+ const msg = messages[i];
89455
+ if (!isRecord$11(msg)) continue;
89456
+ const role = msg["role"];
89457
+ if (role !== void 0 && role !== "assistant") continue;
89458
+ const msgSource = msg["source"];
89459
+ if (!isRecord$11(msgSource)) continue;
89460
+ const provider = readString(msgSource["provider"]);
89461
+ const model = readString(msgSource["model"]);
89462
+ if (provider !== void 0 && model !== void 0) {
89463
+ observe(provider, model);
89464
+ break;
89465
+ }
89466
+ }
88993
89467
  };
88994
89468
  /**
88995
89469
  * 读一个字符串字段。
@@ -92873,7 +93347,7 @@ Determine tier by semantic impact and uncertainty (write a brief "Tier + Rationa
92873
93347
  - L1 Moderate: unambiguous module-local or mechanical multi-file work; edits at most 5 files (5 is a cap, not a range and not a target), no external contract break or unsettled product/UI decision, at most 2 open points. -> Ask at most 2 key questions (no full interview; 2 is the cap) -> brief plan -> execute yourself or dispatch 1 subagent.
92874
93348
  - L2 Complex / Multi-step: cross-module/contract changes, multi-part work, unsettled decisions, or major irreversible risk. -> L2-Clear (settled, reversible): brief decision-complete plan -> R1 -> R6, without full interview/Plan Mode. L2-Governed (unsettled product/UI/external contract or major irreversible risk): R-G Interview -> R9 Plan & Approval -> R1 -> R6.
92875
93349
  - [Stop by Impact, Not by Effort] Within Boundary, a subagent fixes all affected call sites, types, and tests, but pauses with status: hand_back immediately if a change would break an external contract, alter cross-module responsibilities, or require an unsettled product/UI decision—even for a single line.
92876
- - [Execution Economy] Use one cheap probe, the smallest complete change, batched independent reads/searches, and incremental edits. Stop after at most 2 consecutive model steps without progress to change approach or escalate; re-triage if complexity grows mid-task.
93350
+ - [Execution Economy] Use one cheap probe, the smallest complete change, batched reads of known, independent paths (probe before reading unknown paths), and incremental edits; with no code/config change since a check passed, do not re-run that same equivalent check (still run distinct unexecuted checks such as typecheck/build). Stop after at most 2 consecutive model steps without progress to change approach or escalate; re-triage if complexity grows mid-task.
92877
93351
 
92878
93352
  ## R-G · Clarification Interview (L2-Governed Only, Before R9)
92879
93353
  - G1 Design Tree & G2 Frontier: Model requirements as a decision dependency tree; ask the entire current frontier (decisions whose prerequisites are settled) in one round, wait for answers, and recompute. Never ask one question per round or dependent questions together.
@@ -92904,7 +93378,7 @@ Every task brief covers six elements: Goal / Boundary / Constraints / Limits (se
92904
93378
  - [Limits] Each override states **what it bounds, in what unit, the cap, and whether it accumulates**. Use explicit caps ("at most 3 runs", "edits at most 5 files"), never ranges ("2–5 files"); silence is read as a limit of zero, and a quota that resets per cycle is lost, not banked. Do not ask the child to restate your rules back as a correctness check. Dispatch independent tasks concurrently through code_run Promise.all once decisions are settled.
92905
93379
 
92906
93380
  ## R6 · Lead Acceptance
92907
- One acceptance layer owned by Lead: subagents supply implementation/evidence; Lead reads the final diff, checks every criterion, and runs risk-relevant verification. The completion notification is a post-hoc signal: a child stopped, not that the work passed.
93381
+ One acceptance layer owned by Lead: subagents supply implementation/evidence; Lead reads the final diff, checks every criterion, and runs risk-relevant verification without re-running an already-passed equivalent check when no code/config changed. The completion notification is a post-hoc signal: a child stopped, not that the work passed.
92908
93382
  - Re-dispatch budget per brief: 1 first attempt + at most 2 re-dispatches = at most 3 runs total. Count runs, not failures; the number belongs in the task list item for that brief (R7). Only after the third run ends without acceptance, transition to R8 Fallback.
92909
93383
  - [Non-Penalized hand_back] Clean status: hand_back with a valid hand_back_reason and no out-of-boundary mutation does not increment a failure count or trigger R8 by itself (each run still counts toward the 3-run cap). Re-scope or answer via send_message({ agent }) on the existing child to preserve its warm prefix cache.
92910
93384
  - [Noticed but not handled] Every defect found in review: the defect goes back out on a re-dispatch with evidence or goes to the user via R-W (or fix and re-verify on Lead-Core/Hybrid core). Writing it into the delivery summary and shipping anyway is not an available outcome.
@@ -94757,6 +95231,8 @@ function pageValue(raw, refId, sessionId) {
94757
95231
  const nextOffset = complete ? void 0 : numberOf$2(page.nextOffset);
94758
95232
  const omitted = omittedCharsOf(page.omitted);
94759
95233
  const totalChars = numberOf$2(page.totalChars);
95234
+ const matched = booleanOf$1(page.matched);
95235
+ const matchOffset = numberOf$2(page.matchOffset);
94760
95236
  return {
94761
95237
  ok: true,
94762
95238
  action: "page",
@@ -94767,6 +95243,8 @@ function pageValue(raw, refId, sessionId) {
94767
95243
  ...nextOffset === void 0 ? {} : { nextOffset },
94768
95244
  ...omitted === void 0 ? {} : { omitted },
94769
95245
  ...totalChars === void 0 ? {} : { totalChars },
95246
+ ...matched === void 0 ? {} : { matched },
95247
+ ...matchOffset === void 0 ? {} : { matchOffset },
94770
95248
  ...text === void 0 ? {} : {
94771
95249
  text,
94772
95250
  chars: text.length
@@ -94789,7 +95267,8 @@ function createCacheWarmupResultTool(deps) {
94789
95267
  name: CACHE_WARMUP_RESULT_TOOL,
94790
95268
  description: [
94791
95269
  "Read back a result that was replaced by a preview, using the `ref://<session>/<sha256>` handle written in that preview.",
94792
- "Use `action: \"page\"` to read a slice: pass `offset`, and optionally `limit`, `maxBytes`, `fields` and `equals`.",
95270
+ "Use `action: \"page\"` to read a slice: pass `offset` (or `query` to locate a literal substring in text results), and optionally `limit`, `maxBytes`, `fields` and `equals`.",
95271
+ "Keep slices small (a page defaults to 64 lines / 16 KB and is capped at 25 KB): every character a page returns is processed again on the next turn, so read only the slice you need.",
94793
95272
  "Every page reports `complete`, `nextOffset`, `omitted` and `totalChars`, so you can see whether more remains instead of assuming a slice is the whole thing.",
94794
95273
  "Use `action: \"release\"` when the stored copy is no longer needed."
94795
95274
  ].join(" "),
@@ -94809,9 +95288,13 @@ function createCacheWarmupResultTool(deps) {
94809
95288
  type: "integer",
94810
95289
  description: "Where to start: a UTF-8 byte offset for text results, a row index for structured ones."
94811
95290
  },
95291
+ query: {
95292
+ type: "string",
95293
+ description: "Case-sensitive literal substring to locate in a text result starting from `offset` (default 0); returns a page starting at the matched line, or `matched: false` when absent."
95294
+ },
94812
95295
  limit: {
94813
95296
  type: "integer",
94814
- description: "Maximum number of rows for a structured result."
95297
+ description: "Maximum number of lines (text) or rows (structured) in this page."
94815
95298
  },
94816
95299
  maxBytes: {
94817
95300
  type: "integer",
@@ -94874,6 +95357,14 @@ function createCacheWarmupResultTool(deps) {
94874
95357
  type: "number",
94875
95358
  description: "Characters in the whole stored result."
94876
95359
  },
95360
+ matched: {
95361
+ type: "boolean",
95362
+ description: "Whether `query` matched in a text result."
95363
+ },
95364
+ matchOffset: {
95365
+ type: "number",
95366
+ description: "UTF-8 byte offset of the first `query` match."
95367
+ },
94877
95368
  released: {
94878
95369
  type: "boolean",
94879
95370
  description: "Whether a stored copy was actually released."
@@ -94912,13 +95403,18 @@ function createCacheWarmupResultTool(deps) {
94912
95403
  text: value.released === true ? "Released " + value.refId + ". The preview in your history is unchanged; it can no longer be read back." : "Nothing stored for " + value.refId + "; nothing to release."
94913
95404
  }];
94914
95405
  const at = value.offset ?? 0;
94915
- const span = typeof value.chars === "number" ? value.chars + " chars" : "no content";
94916
95406
  const total = typeof value.totalChars === "number" ? " of " + value.totalChars : "";
95407
+ if (value.matched === false) return [{
95408
+ type: "text",
95409
+ text: value.refId + " from offset " + at + " — no match found" + total + ", complete\n\n(no match)"
95410
+ }];
95411
+ const span = typeof value.chars === "number" ? value.chars + " chars" : "no content";
95412
+ const matchNote = value.matched === true && typeof value.matchOffset === "number" ? " (matched at offset " + value.matchOffset + ")" : "";
94917
95413
  const tail = value.complete === true ? "complete" : "more remains" + (typeof value.nextOffset === "number" ? ", continue at offset " + value.nextOffset : "") + (typeof value.omitted === "number" ? ", " + value.omitted + " chars omitted" : "");
94918
95414
  const body = typeof value.text === "string" && value.text !== "" ? value.text : "(empty page)";
94919
95415
  return [{
94920
95416
  type: "text",
94921
- text: value.refId + " from offset " + at + " — " + span + total + ", " + tail + "\n\n" + body
95417
+ text: value.refId + " from offset " + at + matchNote + " — " + span + total + ", " + tail + "\n\n" + body
94922
95418
  }];
94923
95419
  }
94924
95420
  },
@@ -94961,11 +95457,13 @@ function createCacheWarmupResultTool(deps) {
94961
95457
  ["limit", args.limit],
94962
95458
  ["maxBytes", args.maxBytes]
94963
95459
  ]) if (value !== void 0 && !isCount(value)) return failure(action, refId, sessionId, "BAD_ARGUMENT", name + " must be a non-negative integer");
95460
+ if (args.query !== void 0 && (typeof args.query !== "string" || args.query === "")) return failure(action, refId, sessionId, "BAD_ARGUMENT", "query must be a non-empty string");
94964
95461
  const request = {
94965
95462
  sessionId,
94966
95463
  refId
94967
95464
  };
94968
95465
  if (args.offset !== void 0) request.offset = args.offset;
95466
+ if (args.query !== void 0) request.query = args.query;
94969
95467
  if (args.limit !== void 0) request.limit = args.limit;
94970
95468
  if (args.maxBytes !== void 0) request.maxBytes = args.maxBytes;
94971
95469
  if (args.fields !== void 0) request.fields = args.fields;
@@ -95101,9 +95599,11 @@ const CACHE_WARMUP_GUIDANCE = [
95101
95599
  "On large `run_code`/`code_run` results this line may replace the output with a preview: a short description plus one or more `ref://<session>/<sha256>` handles.",
95102
95600
  "",
95103
95601
  "- A preview is **not** the full result. It states `complete`, `omitted` and `nextOffset` explicitly; treat an incomplete preview as incomplete data, not as the whole output.",
95104
- "- To read the original, call `cache_warmup_result` with `action: \"page\"` and that `refId`, then follow `nextOffset` until `complete` is true.",
95602
+ "- To read the original, call `cache_warmup_result` with `action: \"page\"` and that `refId` (pass `query` to jump directly to a literal keyword/error in text logs, or follow `offset` / `nextOffset` until `complete` is true).",
95603
+ "- Page in small slices (`limit` around 64-120 lines, `maxBytes` at most 8-16 KB) and read only the slice you actually need. Reading a whole stored result back in one call re-sends what the preview just saved.",
95105
95604
  "- `action: \"release\"` drops the stored copy. The preview already in the conversation stays identical; it simply can no longer be read back.",
95106
- "- Source code, type and contract definitions, mixed evidence and anything that could not be parsed reliably are never replaced: they arrive in full."
95605
+ "- Source code, type and contract definitions, mixed evidence and anything that could not be parsed reliably are never replaced: they arrive in full.",
95606
+ "- When a program returns many reads, matches or edits, return a filtered or summarized subset rather than the whole batch: everything you return is processed again on the next turn."
95107
95607
  ].join("\n");
95108
95608
  /**
95109
95609
  * 静态引导词的文本提供者。
@@ -100650,11 +101150,11 @@ async function refreshCredentials(credentials, options = {}) {
100650
101150
  const text = await response.text().catch(() => "");
100651
101151
  if (!response.ok) {
100652
101152
  const detail = text.slice(0, 200);
100653
- throw new LlmError(`${PROVIDER_NAME$3} token refresh failed (${response.status})${detail ? `: ${detail}` : ""}`, response.status === 401 || response.status === 403 ? "INVALID_CREDENTIAL" : "TRANSPORT", { status: response.status });
101153
+ throw new LlmError$1(`${PROVIDER_NAME$3} token refresh failed (${response.status})${detail ? `: ${detail}` : ""}`, response.status === 401 || response.status === 403 ? "INVALID_CREDENTIAL" : "TRANSPORT", { status: response.status });
100654
101154
  }
100655
101155
  const payload = asRecord(JSON.parse(text));
100656
101156
  const data = asRecord(payload?.data);
100657
- if (payload === void 0 || payload.code !== 0 || data === void 0) throw new LlmError(`${PROVIDER_NAME$3} token refresh was rejected: ${asString(payload?.msg) ?? "no detail"}`, "INVALID_CREDENTIAL");
101157
+ if (payload === void 0 || payload.code !== 0 || data === void 0) throw new LlmError$1(`${PROVIDER_NAME$3} token refresh was rejected: ${asString(payload?.msg) ?? "no detail"}`, "INVALID_CREDENTIAL");
100658
101158
  const accessToken = asString(data.accessToken);
100659
101159
  if (accessToken === void 0) throw new Error(`${PROVIDER_NAME$3} token refresh returned no access token`);
100660
101160
  const expiresIn = asNumber(data.expiresIn);
@@ -101287,7 +101787,7 @@ var WorkBuddyAdapter = class extends LlmAdapter {
101287
101787
  }));
101288
101788
  }
101289
101789
  async resolveModel(provider, modelId, signal) {
101290
- if (signal?.aborted) throw new LlmError("WorkBuddy model resolution aborted", "ABORTED");
101790
+ if (signal?.aborted) throw new LlmError$1("WorkBuddy model resolution aborted", "ABORTED");
101291
101791
  const settings = await this.settings();
101292
101792
  const credentials = await this.credentials(settings);
101293
101793
  const catalog = credentials === null ? FALLBACK_MODELS$1 : await this.catalog(credentials);
@@ -101418,7 +101918,7 @@ var WorkBuddyAdapter = class extends LlmAdapter {
101418
101918
  if (pool === null) {
101419
101919
  const currentSettings = await this.settings();
101420
101920
  const stored = await this.credentials(currentSettings);
101421
- if (stored === null) throw new LlmError(`Not signed in to ${PROVIDER_NAME$3}. Sign in with the CodeBuddy desktop client; this route reads its credential from the local auth directory.`, "MISSING_CREDENTIAL");
101921
+ if (stored === null) throw new LlmError$1(`Not signed in to ${PROVIDER_NAME$3}. Sign in with the CodeBuddy desktop client; this route reads its credential from the local auth directory.`, "MISSING_CREDENTIAL");
101422
101922
  credentials = await this.store.ensureFresh(stored, (current) => refreshCredentials(current, { fetchFn }));
101423
101923
  } else {
101424
101924
  let effective;
@@ -101426,8 +101926,8 @@ var WorkBuddyAdapter = class extends LlmAdapter {
101426
101926
  effective = await pool.getEffectiveCredential(tried, fetchFn, options.model);
101427
101927
  } catch (error) {
101428
101928
  if (isPoolPausedError(error)) throw error;
101429
- if (error instanceof LlmError) throw error;
101430
- throw new LlmError(error instanceof Error ? error.message : `Not signed in to ${PROVIDER_NAME$3}.`, "MISSING_CREDENTIAL", { cause: error });
101929
+ if (error instanceof LlmError$1) throw error;
101930
+ throw new LlmError$1(error instanceof Error ? error.message : `Not signed in to ${PROVIDER_NAME$3}.`, "MISSING_CREDENTIAL", { cause: error });
101431
101931
  }
101432
101932
  accountId = effective.account.id;
101433
101933
  servedAccountId = accountId;
@@ -101469,8 +101969,8 @@ var WorkBuddyAdapter = class extends LlmAdapter {
101469
101969
  });
101470
101970
  activity?.pulse();
101471
101971
  } catch (error) {
101472
- if (signal.aborted) throw new LlmError("WorkBuddy request aborted", "ABORTED", { cause: error });
101473
- throw new LlmError(`WorkBuddy request failed: ${error instanceof Error ? error.message : String(error)}`, "TRANSPORT", { cause: error });
101972
+ if (signal.aborted) throw new LlmError$1("WorkBuddy request aborted", "ABORTED", { cause: error });
101973
+ throw new LlmError$1(`WorkBuddy request failed: ${error instanceof Error ? error.message : String(error)}`, "TRANSPORT", { cause: error });
101474
101974
  }
101475
101975
  if (response.ok) break;
101476
101976
  refusedStatus = response.status;
@@ -101499,7 +101999,7 @@ var WorkBuddyAdapter = class extends LlmAdapter {
101499
101999
  credentials = pool !== null && accountId !== void 0 ? await pool.renewCredential(accountId, fetchFn, credentials) : await this.store.renew(credentials, (current) => refreshCredentials(current, { fetchFn }));
101500
102000
  } catch (error) {
101501
102001
  if (isPoolPausedError(error)) throw error;
101502
- const verdict = error instanceof LlmError ? error : new LlmError(`${PROVIDER_NAME$3} credential could not be renewed after the service refused it: ${error instanceof Error ? error.message : String(error)}`, "INVALID_CREDENTIAL", { cause: error });
102002
+ const verdict = error instanceof LlmError$1 ? error : new LlmError$1(`${PROVIDER_NAME$3} credential could not be renewed after the service refused it: ${error instanceof Error ? error.message : String(error)}`, "INVALID_CREDENTIAL", { cause: error });
101503
102003
  if (pool !== null && await pool.hasAnotherAvailableAccount(tried)) continue rotation;
101504
102004
  throw verdict;
101505
102005
  }
@@ -101535,8 +102035,8 @@ var WorkBuddyAdapter = class extends LlmAdapter {
101535
102035
  }
101536
102036
  throw failure;
101537
102037
  }
101538
- if (response === void 0) throw new LlmError("WorkBuddy produced no response", "PROVIDER_ERROR");
101539
- if (response.body === null) throw new LlmError("WorkBuddy returned an empty response body", "PROVIDER_ERROR");
102038
+ if (response === void 0) throw new LlmError$1("WorkBuddy produced no response", "PROVIDER_ERROR");
102039
+ if (response.body === null) throw new LlmError$1("WorkBuddy returned an empty response body", "PROVIDER_ERROR");
101540
102040
  const recorded = { tokens: 0 };
101541
102041
  try {
101542
102042
  if (servedProtocol === "anthropic-messages") {
@@ -101633,7 +102133,7 @@ const SIGNATURE_REFUSED_CODE = 11159;
101633
102133
  * from the service, and no retry can help.
101634
102134
  */
101635
102135
  function accountRestrictedFailure(detail, status) {
101636
- return new LlmError(`${PROVIDER_NAME$3} barred this account (11140): the subscription refused to serve it at all, which is not a model park and not a usage window. Every model of this account is affected; use another account or have this one released by the service.${detail ? ` ${detail}` : ""}`, "ACCOUNT_RESTRICTED", { status });
102136
+ return new LlmError$1(`${PROVIDER_NAME$3} barred this account (11140): the subscription refused to serve it at all, which is not a model park and not a usage window. Every model of this account is affected; use another account or have this one released by the service.${detail ? ` ${detail}` : ""}`, "ACCOUNT_RESTRICTED", { status });
101637
102137
  }
101638
102138
  /**
101639
102139
  * Map one failed HTTP response onto a DSH failure.
@@ -101646,27 +102146,27 @@ function accountRestrictedFailure(detail, status) {
101646
102146
  function classifyFailure$1(status, detail, headers) {
101647
102147
  const code = readErrorCode(detail);
101648
102148
  if (status === 401) {
101649
- if (!namesRejectedCredential(detail)) return new LlmError(`${PROVIDER_NAME$3} refused this request once (401), and neither the renewed credential nor the replay changed that answer. The sign-in was NOT marked invalid: this endpoint also refuses a valid bearer, so a dead credential needs the token endpoint's own word before it is recorded.${detail ? ` ${detail}` : ""}`, "PROVIDER_ERROR", { status });
101650
- return new LlmError(`${PROVIDER_NAME$3} rejected the stored credential (401). Sign in again with the CodeBuddy desktop client.${detail ? ` ${detail}` : ""}`, "INVALID_CREDENTIAL", { status });
102149
+ if (!namesRejectedCredential(detail)) return new LlmError$1(`${PROVIDER_NAME$3} refused this request once (401), and neither the renewed credential nor the replay changed that answer. The sign-in was NOT marked invalid: this endpoint also refuses a valid bearer, so a dead credential needs the token endpoint's own word before it is recorded.${detail ? ` ${detail}` : ""}`, "PROVIDER_ERROR", { status });
102150
+ return new LlmError$1(`${PROVIDER_NAME$3} rejected the stored credential (401). Sign in again with the CodeBuddy desktop client.${detail ? ` ${detail}` : ""}`, "INVALID_CREDENTIAL", { status });
101651
102151
  }
101652
102152
  if (status === 403) {
101653
- if (refusalIsNotCredential(detail)) return new LlmError(`${PROVIDER_NAME$3} refused this request (403) before it reached the model: the refusal did not name a rejected credential, so it most likely came from a proxy, a gateway rule or another component on this lane rather than from the subscription. The stored credential was left untouched.${detail ? ` ${detail}` : ""}`, "PROVIDER_ERROR", { status });
101654
- return new LlmError(`${PROVIDER_NAME$3} rejected the stored credential (${status}). Sign in again with the CodeBuddy desktop client.${detail ? ` ${detail}` : ""}`, "INVALID_CREDENTIAL", { status });
102153
+ if (refusalIsNotCredential(detail)) return new LlmError$1(`${PROVIDER_NAME$3} refused this request (403) before it reached the model: the refusal did not name a rejected credential, so it most likely came from a proxy, a gateway rule or another component on this lane rather than from the subscription. The stored credential was left untouched.${detail ? ` ${detail}` : ""}`, "PROVIDER_ERROR", { status });
102154
+ return new LlmError$1(`${PROVIDER_NAME$3} rejected the stored credential (${status}). Sign in again with the CodeBuddy desktop client.${detail ? ` ${detail}` : ""}`, "INVALID_CREDENTIAL", { status });
101655
102155
  }
101656
102156
  if (status === 429 || code === 6004 || code === 14003) {
101657
102157
  const after = (headers ? retryAfterMs$1(headers) : void 0) ?? readRateLimitReset(detail);
101658
- return new LlmError(`${PROVIDER_NAME$3} rate limit or plan quota reached. Check the quota card in Settings > WorkBuddy.${detail ? ` ${detail}` : ""}`, "RATE_LIMIT", {
102158
+ return new LlmError$1(`${PROVIDER_NAME$3} rate limit or plan quota reached. Check the quota card in Settings > WorkBuddy.${detail ? ` ${detail}` : ""}`, "RATE_LIMIT", {
101659
102159
  status: status === 429 ? 429 : void 0,
101660
102160
  ...after === void 0 ? {} : { providerRetryAfterMs: after }
101661
102161
  });
101662
102162
  }
101663
- if (code === 11102) return new LlmError(`${PROVIDER_NAME$3} does not serve this model for the signed-in account: it is either unavailable in the account's region or not included in its plan. Pick a different model in Settings > WorkBuddy.${detail ? ` ${detail}` : ""}`, "PROVIDER_ERROR", { status });
101664
- if (code === 11135 || code === 11133) return new LlmError(`${PROVIDER_NAME$3} rejected the request parameters (${code}). An image may be unsupported by this model or unreadable.${detail ? ` ${detail}` : ""}`, "PROVIDER_ERROR", { status });
102163
+ if (code === 11102) return new LlmError$1(`${PROVIDER_NAME$3} does not serve this model for the signed-in account: it is either unavailable in the account's region or not included in its plan. Pick a different model in Settings > WorkBuddy.${detail ? ` ${detail}` : ""}`, "PROVIDER_ERROR", { status });
102164
+ if (code === 11135 || code === 11133) return new LlmError$1(`${PROVIDER_NAME$3} rejected the request parameters (${code}). An image may be unsupported by this model or unreadable.${detail ? ` ${detail}` : ""}`, "PROVIDER_ERROR", { status });
101665
102165
  if (code === ERROR_CODE.ACCOUNT_RESTRICTED) return accountRestrictedFailure(detail, status);
101666
- if (code === SIGNATURE_REFUSED_CODE) return new LlmError(`${PROVIDER_NAME$3} refused a thinking block's signature (11159). A replayed reasoning block whose signature this route did not produce cannot be verified, so it has to be dropped rather than replayed.${detail ? ` ${detail}` : ""}`, "PROVIDER_ERROR", { status });
101667
- if (code === 11128) return new LlmError(/conversation id|unapproved channel/i.test(detail) ? `${PROVIDER_NAME$3} blocked the request at its channel check (11128): the gateway did not accept it as an official client request. This is a plugin-side gap, not an account problem.${detail ? ` ${detail}` : ""}` : `${PROVIDER_NAME$3} rejected the message history: the conversation must open with a system prompt.${detail ? ` ${detail}` : ""}`, "PROVIDER_ERROR", { status });
101668
- if (status >= 500 || code === 11134) return new LlmError(`${PROVIDER_NAME$3} upstream server error (${status}): ${detail || "No response"}`, "SERVER", { status });
101669
- return new LlmError(`${PROVIDER_NAME$3} API error (${status}): ${detail || "No response"}`, isHttpContextOverflow(status, detail) ? CONTEXT_OVERFLOW_CODE : "PROVIDER_ERROR", { status });
102166
+ if (code === SIGNATURE_REFUSED_CODE) return new LlmError$1(`${PROVIDER_NAME$3} refused a thinking block's signature (11159). A replayed reasoning block whose signature this route did not produce cannot be verified, so it has to be dropped rather than replayed.${detail ? ` ${detail}` : ""}`, "PROVIDER_ERROR", { status });
102167
+ if (code === 11128) return new LlmError$1(/conversation id|unapproved channel/i.test(detail) ? `${PROVIDER_NAME$3} blocked the request at its channel check (11128): the gateway did not accept it as an official client request. This is a plugin-side gap, not an account problem.${detail ? ` ${detail}` : ""}` : `${PROVIDER_NAME$3} rejected the message history: the conversation must open with a system prompt.${detail ? ` ${detail}` : ""}`, "PROVIDER_ERROR", { status });
102168
+ if (status >= 500 || code === 11134) return new LlmError$1(`${PROVIDER_NAME$3} upstream server error (${status}): ${detail || "No response"}`, "SERVER", { status });
102169
+ return new LlmError$1(`${PROVIDER_NAME$3} API error (${status}): ${detail || "No response"}`, isHttpContextOverflow(status, detail) ? CONTEXT_OVERFLOW_CODE : "PROVIDER_ERROR", { status });
101670
102170
  }
101671
102171
  /**
101672
102172
  * Whether a 403 body carries POSITIVE evidence that the refusal was not a
@@ -101796,7 +102296,7 @@ const WORKBUDDY_POOL_PAUSED_CODE = "WORKBUDDY_POOL_PAUSED";
101796
102296
  * accounts" (wait for the pause, then sign the restricted ones in again) from
101797
102297
  * "this request was rate limited". It is never reported as an upstream 429.
101798
102298
  */
101799
- var WorkBuddyPoolPausedError = class extends LlmError {
102299
+ var WorkBuddyPoolPausedError = class extends LlmError$1 {
101800
102300
  /** Unix milliseconds the pause lifts on its own; absent when nothing named one. */
101801
102301
  pausedUntil;
101802
102302
  constructor(message, pausedUntil) {
@@ -102105,7 +102605,7 @@ var WorkBuddyAccountPool = class extends AccountPoolCore {
102105
102605
  if (refreshed.source === "desktop") await store.writeBack(refreshed);
102106
102606
  return refreshed;
102107
102607
  },
102108
- refreshFailureStatus: (error) => error instanceof LlmError && error.code === "INVALID_CREDENTIAL" ? "expired" : void 0,
102608
+ refreshFailureStatus: (error) => error instanceof LlmError$1 && error.code === "INVALID_CREDENTIAL" ? "expired" : void 0,
102109
102609
  extendSummary: (account, base, now) => ({
102110
102610
  ...base,
102111
102611
  region: account.region ?? account.credentials.region,
@@ -103882,7 +104382,7 @@ const Config = z$1.object({
103882
104382
  ]).default("auto").volatile().description("进展更新的输出语言:auto 跟随对话语言,zh 中文,en 英文。"),
103883
104383
  planModePipeline: z$1.boolean().default(true).volatile().description("启用计划模式管线:允许调度模式在澄清访谈收敛后用 enter_plan_mode 进入计划模式,放弃规划时用 leave_plan_mode 退出。"),
103884
104384
  dispatchExecutionGuard: z$1.boolean().default(true).volatile().description("启用调度执行守卫:在执行期拦截子代理越权调用主控专用工具,并拦截等待子代理期间的纯 sleep 空等命令;不修改工具声明面,零损耗保护 Kimi 缓存。"),
103885
- toolRunawayGuard: z$1.boolean().default(true).volatile().description("启用工具失控治理:重复调用同一工具与参数时分级提醒;Kimi 保留第 12 次强停,其他线路只提醒。"),
104385
+ toolRunawayGuard: z$1.boolean().default(true).volatile().description("启用工具失控治理:对零增量病态信号(同名同参重复、同一工具连续同族报错、后台任务无变化轮询)分级提醒;Kimi 保留第 12 次同参强停,其他线路只提醒。"),
103886
104386
  mediaTools: z$1.boolean().default(true).volatile().description("注册图片/视频工具:Codex 生图、Kimi 视频挂载、MiniMax 视频生成与理解;默认开启。修改后重载插件或重启 DSH,Kimi 既有会话在工具表变化后会重建一次前缀缓存。"),
103887
104387
  teamPolicyCacheGuard: z$1.boolean().default(true).volatile().description("把内置 Agent Teams 的 team:policy 段从 system prompt 摘掉,改为开关切换时以尾部用户消息投递一次,避免中途开团队协作时刷掉整段前缀缓存;默认开启。"),
103888
104388
  cacheWarmup: z$1.boolean().default(true).volatile().description(CACHE_WARMUP_SETTING_DESCRIPTION),
@@ -103969,7 +104469,7 @@ function apply(ctx, pluginConfig = {}) {
103969
104469
  const guard = installCompactionPolicyGuard(ctx);
103970
104470
  return () => guard.dispose();
103971
104471
  }, "dsh-chatgpt-subscription: compaction policy guard");
103972
- ctx.effect(() => installMinimaxRuntimeEnhancements(ctx), "dsh-chatgpt-subscription: MiniMax runtime enhancements");
104472
+ ctx.effect(() => installMinimaxRuntimeEnhancements(ctx, { runawayEnabled: () => resolveToolRunawayGuardEnabled(pluginConfig) }), "dsh-chatgpt-subscription: MiniMax runtime enhancements");
103973
104473
  ctx.effect(() => installKimiRepeatBreaker(ctx, {
103974
104474
  providers: CONTROLLED_PROVIDERS.filter((provider) => provider !== "minimax-code"),
103975
104475
  globalEnabled: () => resolveToolRunawayGuardEnabled(pluginConfig)