@eddyskywalker/dsh-chatgpt-subscription 0.66.1 → 0.67.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 (39) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/lib/client.js +57 -0
  3. package/lib/client.js.map +1 -1
  4. package/lib/codemode.js +28 -7
  5. package/lib/{entry-plan-mode-CLRKkgYG.js → entry-plan-mode-gqE4UeU5.js} +5 -2
  6. package/lib/{entry-progress-updates-DZ0ZRus4.js → entry-progress-updates-DpzbX1GP.js} +5 -1
  7. package/lib/index.js +334 -214
  8. package/lib/plan-mode-pipeline.js +1 -1
  9. package/lib/plan-mode.js +1 -1
  10. package/lib/progress-updates.js +1 -1
  11. package/lib/types/client/locales-ru/progress-updates.d.ts.map +1 -1
  12. package/lib/types/client/progress-updates/locales.d.ts +8 -2
  13. package/lib/types/client/progress-updates/locales.d.ts.map +1 -1
  14. package/lib/types/client/progress-updates/settings-binding.d.ts +3 -1
  15. package/lib/types/client/progress-updates/settings-binding.d.ts.map +1 -1
  16. package/lib/types/client/progress-updates/settings-section.d.ts.map +1 -1
  17. package/lib/types/compat.d.ts +1 -1
  18. package/lib/types/entry-codemode.d.ts.map +1 -1
  19. package/lib/types/entry-plan-mode-pipeline.d.ts.map +1 -1
  20. package/lib/types/entry-plan-mode.d.ts.map +1 -1
  21. package/lib/types/host/agent-preset.d.ts.map +1 -1
  22. package/lib/types/host/codemode/rules.d.ts +13 -5
  23. package/lib/types/host/codemode/rules.d.ts.map +1 -1
  24. package/lib/types/host/command-code/adapter.d.ts.map +1 -1
  25. package/lib/types/host/common/request-images.d.ts +13 -1
  26. package/lib/types/host/common/request-images.d.ts.map +1 -1
  27. package/lib/types/host/dispatch-execution-guard.d.ts.map +1 -1
  28. package/lib/types/host/kimi-code/adapter.d.ts.map +1 -1
  29. package/lib/types/host/kimi-code/mapper.d.ts.map +1 -1
  30. package/lib/types/host/kimi-code/tool-argument-guard.d.ts +7 -0
  31. package/lib/types/host/kimi-code/tool-argument-guard.d.ts.map +1 -1
  32. package/lib/types/host/kimi-code/tool-argument-recovery.d.ts.map +1 -1
  33. package/lib/types/host/progress-updates/prompt.d.ts.map +1 -1
  34. package/lib/types/host/progress-updates/tool.d.ts.map +1 -1
  35. package/lib/types/index.d.ts +10 -0
  36. package/lib/types/index.d.ts.map +1 -1
  37. package/package.json +1 -1
  38. package/presets/dispatch/README.md +9 -9
  39. package/presets/dispatch/agent.cordis.yml +26 -18
package/lib/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import { a as resolveProgressUpdatesSettings, n as attachProgressSettings } from "./entry-progress-updates-DZ0ZRus4.js";
1
+ import { a as resolveProgressUpdatesSettings, n as attachProgressSettings } from "./entry-progress-updates-DpzbX1GP.js";
2
2
  import { attachPlanModePipelineSettings, resolvePlanModePipelineEnabled } from "./plan-mode-pipeline.js";
3
3
  import { n as PLUGIN_MESSAGE_SOURCE_KIND, r as normalizeGenerateOptions, t as LlmError$1 } from "./llm-compat-u9mor0uu.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-CLRKkgYG.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-gqE4UeU5.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";
@@ -809,7 +809,7 @@ const ROUTE_PREFIX$5 = "/api/dsh-chatgpt-subscription";
809
809
  * `test/responses-client.test.ts` asserts the two agree, so a release that
810
810
  * forgets this constant fails the suite instead of shipping quietly.
811
811
  */
812
- const PLUGIN_VERSION = "0.66.1";
812
+ const PLUGIN_VERSION = "0.67.0";
813
813
  const CODEX_CHATGPT_PROVIDER_ID = "codex-chatgpt";
814
814
  const CODEX_API_BASE = "https://chatgpt.com/backend-api/codex";
815
815
  const CODEX_RESPONSES_URL = `${CODEX_API_BASE}/responses`;
@@ -4488,7 +4488,7 @@ var OAuthService = class {
4488
4488
  throw new OAuthServiceError("oauth-token-exchange-failed", `The ChatGPT device code could not be issued (${response.status}${detail === null ? "" : `, ${detail}`}).`, response.status);
4489
4489
  }
4490
4490
  const payload = await response.json().catch(() => null);
4491
- const record = isRecord$70(payload) ? payload : {};
4491
+ const record = isRecord$71(payload) ? payload : {};
4492
4492
  const authId = nonEmptyString$11(record.device_auth_id);
4493
4493
  const userCode = nonEmptyString$11(record.user_code) ?? nonEmptyString$11(record.usercode);
4494
4494
  if (authId === void 0 || userCode === void 0) throw new OAuthServiceError("oauth-token-exchange-failed", "ChatGPT returned no device code.");
@@ -4555,7 +4555,7 @@ var OAuthService = class {
4555
4555
  const detail = deviceErrorIdentifier(payload);
4556
4556
  throw new OAuthServiceError("oauth-token-exchange-failed", `The ChatGPT device confirmation was refused (${response.status}${detail === void 0 ? "" : `, ${detail}`}).`, response.status);
4557
4557
  }
4558
- const record = isRecord$70(payload) ? payload : {};
4558
+ const record = isRecord$71(payload) ? payload : {};
4559
4559
  const authorizationCode = nonEmptyString$11(record.authorization_code);
4560
4560
  const codeVerifier = nonEmptyString$11(record.code_verifier);
4561
4561
  if (authorizationCode === void 0 || codeVerifier === void 0) throw new OAuthServiceError("oauth-token-exchange-failed", "ChatGPT confirmed the device code but returned no authorization code.");
@@ -4888,11 +4888,11 @@ const DEVICE_PENDING_STATUSES = /* @__PURE__ */ new Set([
4888
4888
  function isPendingDeviceAnswer(response, payload) {
4889
4889
  if (response.status === 403 || response.status === 404) return true;
4890
4890
  if (!response.ok && response.status !== 400) return false;
4891
- if (!isRecord$70(payload)) return false;
4891
+ if (!isRecord$71(payload)) return false;
4892
4892
  const status = payload.status;
4893
4893
  if (typeof status === "string" && DEVICE_PENDING_STATUSES.has(status.toLowerCase())) return true;
4894
4894
  const error = payload.error;
4895
- if (isRecord$70(error)) {
4895
+ if (isRecord$71(error)) {
4896
4896
  const code = error.code;
4897
4897
  if (typeof code === "string" && DEVICE_PENDING_STATUSES.has(code.toLowerCase())) return true;
4898
4898
  }
@@ -4906,18 +4906,18 @@ function isPendingDeviceAnswer(response, payload) {
4906
4906
  * wrong.
4907
4907
  */
4908
4908
  function deviceErrorIdentifier(payload) {
4909
- if (!isRecord$70(payload)) return void 0;
4909
+ if (!isRecord$71(payload)) return void 0;
4910
4910
  const candidates = [payload.code];
4911
4911
  const error = payload.error;
4912
4912
  if (typeof error === "string") candidates.push(error);
4913
- else if (isRecord$70(error)) candidates.push(error.code, error.type);
4913
+ else if (isRecord$71(error)) candidates.push(error.code, error.type);
4914
4914
  candidates.push(payload.status);
4915
4915
  for (const candidate of candidates) if (typeof candidate === "string" && /^[a-z0-9_.-]{1,64}$/i.test(candidate)) return candidate;
4916
4916
  }
4917
4917
  function nonEmptyString$11(value) {
4918
4918
  return typeof value === "string" && value !== "" ? value : void 0;
4919
4919
  }
4920
- function isRecord$70(value) {
4920
+ function isRecord$71(value) {
4921
4921
  return typeof value === "object" && value !== null && !Array.isArray(value);
4922
4922
  }
4923
4923
  async function oauthErrorIdentifier(response) {
@@ -5098,7 +5098,7 @@ const CODEX_CLI_CREDENTIAL_SOURCE = "codex";
5098
5098
  * here, and the import has to be repeated afterwards.
5099
5099
  */
5100
5100
  const ADOPTED_CODEX_CREDENTIAL_EXPIRED_HINT = "The sign-in imported from the Codex CLI has expired. Sign in again in the Codex CLI, then import it again from this settings card.";
5101
- function isRecord$69(value) {
5101
+ function isRecord$70(value) {
5102
5102
  return typeof value === "object" && value !== null && !Array.isArray(value);
5103
5103
  }
5104
5104
  /** A trimmed, non-empty string, or nothing. */
@@ -5200,7 +5200,7 @@ function decodeJwtClaims$1(token) {
5200
5200
  if (parts.length !== 3) return void 0;
5201
5201
  try {
5202
5202
  const value = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
5203
- return isRecord$69(value) ? value : void 0;
5203
+ return isRecord$70(value) ? value : void 0;
5204
5204
  } catch {
5205
5205
  return;
5206
5206
  }
@@ -5245,10 +5245,10 @@ function expiryFromAccessToken(accessToken) {
5245
5245
  * the file carries cannot reach the result.
5246
5246
  */
5247
5247
  function parseAdoptedCodexCredential(value, sourcePath) {
5248
- if (!isRecord$69(value)) return void 0;
5248
+ if (!isRecord$70(value)) return void 0;
5249
5249
  if (value.auth_mode !== "chatgpt") return void 0;
5250
5250
  const tokens = value[CODEX_CLI_TOKENS_KEY];
5251
- if (!isRecord$69(tokens)) return void 0;
5251
+ if (!isRecord$70(tokens)) return void 0;
5252
5252
  const accessToken = nonEmptyString$10(tokens.access_token);
5253
5253
  if (accessToken === void 0) return void 0;
5254
5254
  const refreshToken = nonEmptyString$10(tokens.refresh_token);
@@ -5267,7 +5267,7 @@ function parseAdoptedCodexCredential(value, sourcePath) {
5267
5267
  const email = claims === void 0 ? void 0 : nonEmptyString$10(claims.email);
5268
5268
  if (email !== void 0) credentials.email = email;
5269
5269
  const authClaims = claims === void 0 ? void 0 : claims[CODEX_AUTH_CLAIMS_KEY];
5270
- const planType = isRecord$69(authClaims) ? nonEmptyString$10(authClaims.chatgpt_plan_type) : void 0;
5270
+ const planType = isRecord$70(authClaims) ? nonEmptyString$10(authClaims.chatgpt_plan_type) : void 0;
5271
5271
  if (planType !== void 0) credentials.planType = planType;
5272
5272
  }
5273
5273
  const accountId = nonEmptyString$10(tokens.account_id);
@@ -8160,7 +8160,7 @@ const schemaFields = /* @__PURE__ */ new Set([
8160
8160
  "required",
8161
8161
  "propertyOrdering"
8162
8162
  ]);
8163
- function isRecord$68(value) {
8163
+ function isRecord$69(value) {
8164
8164
  return typeof value === "object" && value !== null && !Array.isArray(value);
8165
8165
  }
8166
8166
  function mergeSchemas(left, right) {
@@ -8168,7 +8168,7 @@ function mergeSchemas(left, right) {
8168
8168
  ...left,
8169
8169
  ...right
8170
8170
  };
8171
- if (isRecord$68(left.properties) && isRecord$68(right.properties)) merged.properties = {
8171
+ if (isRecord$69(left.properties) && isRecord$69(right.properties)) merged.properties = {
8172
8172
  ...left.properties,
8173
8173
  ...right.properties
8174
8174
  };
@@ -8204,9 +8204,9 @@ const mergedTypeKeys = /* @__PURE__ */ new Set([
8204
8204
  * model with strictly less than the schema it started from.
8205
8205
  */
8206
8206
  function describeBranch(branch) {
8207
- const type = typeof branch.type === "string" ? branch.type : isRecord$68(branch.properties) ? "object" : isRecord$68(branch.items) ? "array" : "value";
8207
+ const type = typeof branch.type === "string" ? branch.type : isRecord$69(branch.properties) ? "object" : isRecord$69(branch.items) ? "array" : "value";
8208
8208
  const details = [];
8209
- if (isRecord$68(branch.properties)) {
8209
+ if (isRecord$69(branch.properties)) {
8210
8210
  const names = Object.keys(branch.properties);
8211
8211
  if (names.length > 0) details.push(`{${names.join(",")}}`);
8212
8212
  }
@@ -8220,7 +8220,7 @@ function describeBranch(branch) {
8220
8220
  }
8221
8221
  /** How well one branch can stand in for a whole union; a named object shape wins. */
8222
8222
  function branchRank(branch) {
8223
- if (isRecord$68(branch.properties)) return 3;
8223
+ if (isRecord$69(branch.properties)) return 3;
8224
8224
  if (branch.type === "object") return 2;
8225
8225
  if (branch.type === "array") return 1;
8226
8226
  return 0;
@@ -8249,7 +8249,7 @@ function unionShape(branches) {
8249
8249
  shape: branches[0],
8250
8250
  folded: false
8251
8251
  };
8252
- if (new Set(branches.map((branch) => branch.type)).size === 1 && branches.every((branch) => !isRecord$68(branch.properties) && !isRecord$68(branch.items))) {
8252
+ if (new Set(branches.map((branch) => branch.type)).size === 1 && branches.every((branch) => !isRecord$69(branch.properties) && !isRecord$69(branch.items))) {
8253
8253
  const shape = { type: branches[0].type };
8254
8254
  if (branches.every((branch) => Array.isArray(branch.enum))) {
8255
8255
  const values = [...new Set(branches.flatMap((branch) => branch.enum))];
@@ -8286,7 +8286,7 @@ function foldOwnFields(node) {
8286
8286
  const out = {};
8287
8287
  for (const [key, value] of Object.entries(node)) {
8288
8288
  if (key === "anyOf" || key === "oneOf" || key === "allOf") continue;
8289
- if (key === "properties" && isRecord$68(value)) {
8289
+ if (key === "properties" && isRecord$69(value)) {
8290
8290
  out.properties = Object.fromEntries(Object.entries(value).map(([name, child]) => [name, foldSchemaUnions(child)]));
8291
8291
  continue;
8292
8292
  }
@@ -8315,15 +8315,15 @@ function foldOwnFields(node) {
8315
8315
  * argument the model sends anyway fails there, naming the actual problem.
8316
8316
  */
8317
8317
  function foldSchemaUnions(node) {
8318
- if (!isRecord$68(node)) return node;
8318
+ if (!isRecord$69(node)) return node;
8319
8319
  let own = foldOwnFields(node);
8320
8320
  if (Array.isArray(node.allOf)) for (const branch of node.allOf) {
8321
8321
  const folded = foldSchemaUnions(branch);
8322
- if (isRecord$68(folded)) own = mergeSchemas(own, folded);
8322
+ if (isRecord$69(folded)) own = mergeSchemas(own, folded);
8323
8323
  }
8324
8324
  const alternatives = Array.isArray(node.anyOf) ? node.anyOf : Array.isArray(node.oneOf) ? node.oneOf : [];
8325
8325
  if (alternatives.length === 0) return own;
8326
- const branches = alternatives.map((branch) => foldSchemaUnions(branch)).filter(isRecord$68);
8326
+ const branches = alternatives.map((branch) => foldSchemaUnions(branch)).filter(isRecord$69);
8327
8327
  if (branches.length === 0) return own;
8328
8328
  const shapes = branches.filter((branch) => branch.type !== "null");
8329
8329
  const acceptsNull = branches.some((branch) => branch.type === "null");
@@ -8339,7 +8339,7 @@ function foldSchemaUnions(node) {
8339
8339
  return merged;
8340
8340
  }
8341
8341
  function toAntigravityToolSchema(schema, options = {}) {
8342
- if (!isRecord$68(schema)) return schema;
8342
+ if (!isRecord$69(schema)) return schema;
8343
8343
  const root = schema;
8344
8344
  function resolveReference(reference) {
8345
8345
  let target = root;
@@ -8347,13 +8347,13 @@ function toAntigravityToolSchema(schema, options = {}) {
8347
8347
  const path = reference === "#" ? [] : reference.slice(2).split("/");
8348
8348
  for (const segment of path) {
8349
8349
  const key = segment.replace(/~1/g, "/").replace(/~0/g, "~");
8350
- target = isRecord$68(target) && Object.hasOwn(target, key) ? target[key] : void 0;
8350
+ target = isRecord$69(target) && Object.hasOwn(target, key) ? target[key] : void 0;
8351
8351
  }
8352
- if (!isRecord$68(target)) throw new LlmError(`Antigravity tool schema reference was not found: ${reference}`, "PROVIDER_ERROR");
8352
+ if (!isRecord$69(target)) throw new LlmError(`Antigravity tool schema reference was not found: ${reference}`, "PROVIDER_ERROR");
8353
8353
  return target;
8354
8354
  }
8355
8355
  function convert(node, references) {
8356
- if (!isRecord$68(node)) return {};
8356
+ if (!isRecord$69(node)) return {};
8357
8357
  let inherited = {};
8358
8358
  if (typeof node.$ref === "string") {
8359
8359
  if (references.has(node.$ref)) throw new LlmError(`Antigravity tool schema contains a recursive reference: ${node.$ref}`, "PROVIDER_ERROR");
@@ -8362,8 +8362,8 @@ function toAntigravityToolSchema(schema, options = {}) {
8362
8362
  if (Array.isArray(node.allOf)) for (const branch of node.allOf) inherited = mergeSchemas(inherited, convert(branch, references));
8363
8363
  const out = {};
8364
8364
  for (const [key, value] of Object.entries(node)) if (schemaFields.has(key)) out[key] = value;
8365
- if (isRecord$68(node.properties)) out.properties = Object.fromEntries(Object.entries(node.properties).map(([name, child]) => [name, convert(child, references)]));
8366
- if (isRecord$68(node.items)) out.items = convert(node.items, references);
8365
+ if (isRecord$69(node.properties)) out.properties = Object.fromEntries(Object.entries(node.properties).map(([name, child]) => [name, convert(child, references)]));
8366
+ if (isRecord$69(node.items)) out.items = convert(node.items, references);
8367
8367
  const alternatives = Array.isArray(node.anyOf) ? node.anyOf : node.oneOf;
8368
8368
  if (Array.isArray(alternatives)) out.anyOf = alternatives.map((child) => convert(child, references));
8369
8369
  if (Array.isArray(node.type)) {
@@ -8399,7 +8399,7 @@ let toolCallCounter = 0;
8399
8399
  function sanitizeText$9(text) {
8400
8400
  return text.replace(/\0/g, "");
8401
8401
  }
8402
- function isRecord$67(value) {
8402
+ function isRecord$68(value) {
8403
8403
  return typeof value === "object" && value !== null && !Array.isArray(value);
8404
8404
  }
8405
8405
  function asString$30(value) {
@@ -8419,25 +8419,25 @@ function toolCallIdNeeded(modelId, runtimeModel) {
8419
8419
  return modelId.startsWith("claude-") || modelId.startsWith("gpt-oss-") || runtimeModel.startsWith("claude-") || runtimeModel.startsWith("gpt-oss-");
8420
8420
  }
8421
8421
  function parseArguments$1(raw) {
8422
- if (isRecord$67(raw)) return raw;
8422
+ if (isRecord$68(raw)) return raw;
8423
8423
  if (raw === void 0 || raw === null || raw === "") return {};
8424
8424
  const parsed = typeof raw === "string" ? safeJsonParse$9(raw) : raw;
8425
- return isRecord$67(parsed) ? parsed : {};
8425
+ return isRecord$68(parsed) ? parsed : {};
8426
8426
  }
8427
8427
  const NO_RESOLVED_IMAGES$5 = /* @__PURE__ */ new Map();
8428
8428
  function attachmentOf$5(block) {
8429
8429
  const attachment = block.attachment;
8430
- if (!isRecord$67(attachment)) return void 0;
8430
+ if (!isRecord$68(attachment)) return void 0;
8431
8431
  return typeof attachment.attachmentId === "string" ? attachment : void 0;
8432
8432
  }
8433
8433
  function attachmentLabel$6(block) {
8434
- const attachment = isRecord$67(block.attachment) ? block.attachment : void 0;
8434
+ const attachment = isRecord$68(block.attachment) ? block.attachment : void 0;
8435
8435
  return asString$30(attachment?.name) || asString$30(attachment?.attachmentId);
8436
8436
  }
8437
8437
  function collectImageRefs$3(content, refs) {
8438
8438
  if (!Array.isArray(content)) return;
8439
8439
  for (const block of content) {
8440
- if (!isRecord$67(block)) continue;
8440
+ if (!isRecord$68(block)) continue;
8441
8441
  if (block.type === "image") {
8442
8442
  const attachment = attachmentOf$5(block);
8443
8443
  if (attachment) refs.set(attachment.attachmentId, attachment);
@@ -8570,7 +8570,7 @@ function unavailableImageText$6(block) {
8570
8570
  }
8571
8571
  function imageBlockToPart(block, images) {
8572
8572
  let data = asString$30(block.data) || asString$30(block.base64);
8573
- const source = isRecord$67(block.source) ? block.source : void 0;
8573
+ const source = isRecord$68(block.source) ? block.source : void 0;
8574
8574
  if (!data && source) data = asString$30(source.data) || asString$30(source.base64);
8575
8575
  let mimeType = asString$30(block.mimeType) || asString$30(block.mediaType) || (source ? asString$30(source.mimeType) || asString$30(source.mediaType) : void 0) || "image/png";
8576
8576
  if (data?.startsWith("data:")) {
@@ -8595,8 +8595,8 @@ function contentToUserParts(content, images) {
8595
8595
  if (typeof content === "string") return [{ text: sanitizeText$9(content) }];
8596
8596
  if (!Array.isArray(content)) return [];
8597
8597
  const parts = [];
8598
- for (const block of content) if (isRecord$67(block) && block.type === "text" && typeof block.text === "string") parts.push({ text: sanitizeText$9(block.text) });
8599
- else if (isRecord$67(block) && block.type === "image") {
8598
+ for (const block of content) if (isRecord$68(block) && block.type === "text" && typeof block.text === "string") parts.push({ text: sanitizeText$9(block.text) });
8599
+ else if (isRecord$68(block) && block.type === "image") {
8600
8600
  const img = imageBlockToPart(block, images);
8601
8601
  parts.push(img ?? { text: unavailableImageText$6(block) });
8602
8602
  }
@@ -8611,7 +8611,7 @@ function toolResultImageParts(blocks, images) {
8611
8611
  if (!Array.isArray(blocks)) return [];
8612
8612
  const parts = [];
8613
8613
  for (const block of blocks) {
8614
- if (!isRecord$67(block)) continue;
8614
+ if (!isRecord$68(block)) continue;
8615
8615
  if (block.type === "image") {
8616
8616
  parts.push(imageBlockToPart(block, images) ?? { text: unavailableImageText$6(block) });
8617
8617
  continue;
@@ -8623,7 +8623,7 @@ function toolResultImageParts(blocks, images) {
8623
8623
  function toolResultText$9(blocks) {
8624
8624
  if (!Array.isArray(blocks)) return "";
8625
8625
  return blocks.map((block) => {
8626
- if (!isRecord$67(block)) return "";
8626
+ if (!isRecord$68(block)) return "";
8627
8627
  if (block.type === "text" && typeof block.text === "string") return sanitizeText$9(block.text);
8628
8628
  if (block.type === "tool-result") return toolResultText$9(block.content);
8629
8629
  if (block.type === "image") {
@@ -8637,9 +8637,9 @@ function replayBlockFor$1(message, index) {
8637
8637
  const source = message.source;
8638
8638
  if (!source || source.kind !== "model" || source.provider !== "antigravity") return void 0;
8639
8639
  const state = source.replayState;
8640
- if (!isRecord$67(state)) return void 0;
8640
+ if (!isRecord$68(state)) return void 0;
8641
8641
  if (Array.isArray(state.blocks)) return state.blocks[index];
8642
- const resp = isRecord$67(state.response) ? state.response : void 0;
8642
+ const resp = isRecord$68(state.response) ? state.response : void 0;
8643
8643
  if (resp) {
8644
8644
  if (Array.isArray(resp.outputItems)) return resp.outputItems[index];
8645
8645
  if (Array.isArray(resp.blocks)) return resp.blocks[index];
@@ -8741,10 +8741,10 @@ function assistantParts(message, model, runtimeModel, toolCalls) {
8741
8741
  if (!Array.isArray(message.content)) return parts;
8742
8742
  for (let index = 0; index < message.content.length; index++) {
8743
8743
  const block = message.content[index];
8744
- if (!isRecord$67(block)) continue;
8744
+ if (!isRecord$68(block)) continue;
8745
8745
  if (block.type === "reasoning" && runtimeModel.startsWith("claude-") && (message.source?.kind !== "model" || message.source.provider !== "antigravity" || !("model" in message.source) || message.source.model !== model.id)) continue;
8746
8746
  const replay = replayBlockFor$1(message, index);
8747
- const originalParts = Array.isArray(replay?.parts) ? replay.parts.filter(isRecord$67) : [];
8747
+ const originalParts = Array.isArray(replay?.parts) ? replay.parts.filter(isRecord$68) : [];
8748
8748
  if ((block.type === "text" || block.type === "reasoning") && originalParts.length > 0 && originalParts.every((part) => !part.functionCall) && originalParts.map((part) => asString$30(part.text) || "").join("") === sanitizeText$9(String(block.text || ""))) {
8749
8749
  parts.push(...originalParts.map(replayPart));
8750
8750
  continue;
@@ -8765,8 +8765,8 @@ function assistantParts(message, model, runtimeModel, toolCalls) {
8765
8765
  } else if (block.type === "tool-call") {
8766
8766
  const toolId = String(block.id || "");
8767
8767
  const toolName = String(block.name || "");
8768
- const originalCall = originalParts.find((part) => isRecord$67(part.functionCall));
8769
- const wireId = asString$30((isRecord$67(originalCall?.functionCall) ? originalCall.functionCall : void 0)?.id) || (toolCallIdNeeded(model.id, runtimeModel) ? sanitizeToolCallId(toolId, toolName) : originalCall ? void 0 : toolId || void 0);
8768
+ const originalCall = originalParts.find((part) => isRecord$68(part.functionCall));
8769
+ const wireId = asString$30((isRecord$68(originalCall?.functionCall) ? originalCall.functionCall : void 0)?.id) || (toolCallIdNeeded(model.id, runtimeModel) ? sanitizeToolCallId(toolId, toolName) : originalCall ? void 0 : toolId || void 0);
8770
8770
  toolCalls.set(toolId, {
8771
8771
  name: toolName,
8772
8772
  id: wireId
@@ -8818,7 +8818,7 @@ function convertMessages(options, model, runtimeModel, images = NO_RESOLVED_IMAG
8818
8818
  continue;
8819
8819
  }
8820
8820
  const content = Array.isArray(message.content) ? message.content : [];
8821
- const userParts = contentToUserParts(content.filter((b) => !isRecord$67(b) || b.type !== "tool-result"), images);
8821
+ const userParts = contentToUserParts(content.filter((b) => !isRecord$68(b) || b.type !== "tool-result"), images);
8822
8822
  if (role === "system") {
8823
8823
  if (userParts.length) contents.push({
8824
8824
  role: GEMINI_ROLE.user,
@@ -8830,7 +8830,7 @@ function convertMessages(options, model, runtimeModel, images = NO_RESOLVED_IMAG
8830
8830
  role: GEMINI_ROLE.user,
8831
8831
  parts: userParts
8832
8832
  });
8833
- for (const b of content) if (isRecord$67(b) && b.type === "tool-result") pushToolResult(contents, b, toolCalls, model, runtimeModel, images);
8833
+ for (const b of content) if (isRecord$68(b) && b.type === "tool-result") pushToolResult(contents, b, toolCalls, model, runtimeModel, images);
8834
8834
  }
8835
8835
  return contents;
8836
8836
  }
@@ -8973,7 +8973,7 @@ const USAGE_FIELDS = [
8973
8973
  "totalTokenCount"
8974
8974
  ];
8975
8975
  function collectUsage(value, state) {
8976
- if (!isRecord$67(value)) return;
8976
+ if (!isRecord$68(value)) return;
8977
8977
  for (const key of USAGE_FIELDS) {
8978
8978
  const count = value[key];
8979
8979
  if (typeof count !== "number" || !Number.isSafeInteger(count) || count < 0) continue;
@@ -9003,17 +9003,17 @@ function processStreamLine$4(line, state) {
9003
9003
  }
9004
9004
  if (!json) return [];
9005
9005
  const chunk = safeJsonParse$9(json);
9006
- if (!isRecord$67(chunk)) return [];
9007
- const responseData = isRecord$67(chunk.response) ? chunk.response : chunk;
9008
- const error = isRecord$67(chunk.error) ? chunk.error : isRecord$67(responseData.error) ? responseData.error : void 0;
9006
+ if (!isRecord$68(chunk)) return [];
9007
+ const responseData = isRecord$68(chunk.response) ? chunk.response : chunk;
9008
+ const error = isRecord$68(chunk.error) ? chunk.error : isRecord$68(responseData.error) ? responseData.error : void 0;
9009
9009
  if (error !== void 0) throw new LlmError$1(`Antigravity stream error: ${asString$30(error.message) ?? "unknown error"}`, isContextOverflow(error) ? CONTEXT_OVERFLOW_CODE : "PROVIDER_ERROR");
9010
9010
  const candidates = Array.isArray(responseData.candidates) ? responseData.candidates : [];
9011
- const candidate = isRecord$67(candidates[0]) ? candidates[0] : void 0;
9012
- const content = isRecord$67(candidate?.content) ? candidate.content : void 0;
9011
+ const candidate = isRecord$68(candidates[0]) ? candidates[0] : void 0;
9012
+ const content = isRecord$68(candidate?.content) ? candidate.content : void 0;
9013
9013
  const parts = Array.isArray(content?.parts) ? content.parts : [];
9014
9014
  const out = [];
9015
9015
  for (const part of parts) {
9016
- if (!isRecord$67(part)) continue;
9016
+ if (!isRecord$68(part)) continue;
9017
9017
  if (typeof part.text === "string" && part.text !== "") {
9018
9018
  const isThinking = Boolean(part.thought);
9019
9019
  const blockType = isThinking ? "reasoning" : "text";
@@ -9045,7 +9045,7 @@ function processStreamLine$4(line, state) {
9045
9045
  index: state.currentBlock.index,
9046
9046
  text: delta
9047
9047
  });
9048
- } else if (!isRecord$67(part.functionCall) && thoughtSignature(part)) {
9048
+ } else if (!isRecord$68(part.functionCall) && thoughtSignature(part)) {
9049
9049
  if (state.replayBlocks.length === 0) {
9050
9050
  const type = part.thought ? "reasoning" : "text";
9051
9051
  state.blocks.push({
@@ -9069,12 +9069,12 @@ function processStreamLine$4(line, state) {
9069
9069
  }
9070
9070
  state.replayBlocks[state.replayBlocks.length - 1].parts.push(replayPart(part));
9071
9071
  }
9072
- if (isRecord$67(part.functionCall)) {
9072
+ if (isRecord$68(part.functionCall)) {
9073
9073
  out.push(...closeCurrentBlock(state));
9074
9074
  const fc = part.functionCall;
9075
9075
  const toolName = asString$30(fc.name) || "";
9076
9076
  const toolId = asString$30(fc.id) || sanitizeToolCallId("", toolName);
9077
- const argsText = JSON.stringify(isRecord$67(fc.args) ? fc.args : {});
9077
+ const argsText = JSON.stringify(isRecord$68(fc.args) ? fc.args : {});
9078
9078
  const index = state.blocks.length;
9079
9079
  const block = {
9080
9080
  type: "tool-call",
@@ -9113,7 +9113,7 @@ function processStreamLine$4(line, state) {
9113
9113
  if (responseData !== chunk) collectUsage(responseData.usageMetadata, state);
9114
9114
  const finishMessage = asString$30(candidate?.finishMessage);
9115
9115
  if (finishMessage) state.finishMessage = finishMessage;
9116
- const blockReason = asString$30((isRecord$67(responseData.promptFeedback) ? responseData.promptFeedback : void 0)?.blockReason);
9116
+ const blockReason = asString$30((isRecord$68(responseData.promptFeedback) ? responseData.promptFeedback : void 0)?.blockReason);
9117
9117
  const finishReason = asString$30(candidate?.finishReason) || asString$30(responseData.finishReason) || (blockReason ? `PROMPT_BLOCKED:${blockReason}` : void 0);
9118
9118
  if (finishReason) {
9119
9119
  state.finishReason = finishReason;
@@ -9186,7 +9186,7 @@ function closeStream$7(state) {
9186
9186
  *
9187
9187
  * @module dsh-chatgpt-subscription/request-images
9188
9188
  */
9189
- function isRecord$66(value) {
9189
+ function isRecord$67(value) {
9190
9190
  return typeof value === "object" && value !== null && !Array.isArray(value);
9191
9191
  }
9192
9192
  function asString$29(value) {
@@ -9245,17 +9245,17 @@ const SUPPORTED_IMAGE_MEDIA_TYPES$4 = /* @__PURE__ */ new Set([
9245
9245
  ]);
9246
9246
  function attachmentOf$4(block) {
9247
9247
  const attachment = block.attachment;
9248
- if (!isRecord$66(attachment)) return void 0;
9248
+ if (!isRecord$67(attachment)) return void 0;
9249
9249
  return typeof attachment.attachmentId === "string" ? attachment : void 0;
9250
9250
  }
9251
9251
  function attachmentLabel$5(block) {
9252
- const attachment = isRecord$66(block.attachment) ? block.attachment : void 0;
9252
+ const attachment = isRecord$67(block.attachment) ? block.attachment : void 0;
9253
9253
  return asString$29(attachment?.name) || asString$29(attachment?.attachmentId);
9254
9254
  }
9255
9255
  function collectImageRefs$2(content, refs) {
9256
9256
  if (!Array.isArray(content)) return;
9257
9257
  for (const block of content) {
9258
- if (!isRecord$66(block)) continue;
9258
+ if (!isRecord$67(block)) continue;
9259
9259
  if (block.type === "image") {
9260
9260
  const attachment = attachmentOf$4(block);
9261
9261
  if (attachment) refs.set(attachment.attachmentId, attachment);
@@ -9285,7 +9285,7 @@ function base64Length$2(bytes) {
9285
9285
  */
9286
9286
  function inlinePayloadOf$1(block) {
9287
9287
  let data = asString$29(block.data) || asString$29(block.base64);
9288
- const source = isRecord$66(block.source) ? block.source : void 0;
9288
+ const source = isRecord$67(block.source) ? block.source : void 0;
9289
9289
  if (!data && source) data = asString$29(source.data) || asString$29(source.base64);
9290
9290
  if (data?.startsWith("data:")) {
9291
9291
  const matched = data.match(/^data:([^;,]+);base64,(.*)$/s);
@@ -9315,7 +9315,7 @@ function requestImagePayloadLength(block, images) {
9315
9315
  function collectRequestImagePayloads(content, images, lengths) {
9316
9316
  if (!Array.isArray(content)) return;
9317
9317
  for (const block of content) {
9318
- if (!isRecord$66(block)) continue;
9318
+ if (!isRecord$67(block)) continue;
9319
9319
  if (block.type === "image") {
9320
9320
  const bytes = requestImagePayloadLength(block, images);
9321
9321
  if (bytes !== void 0) lengths.push(bytes);
@@ -9369,7 +9369,7 @@ function replaceOldestRequestImages(options, count, images) {
9369
9369
  let replaced = false;
9370
9370
  return {
9371
9371
  content: content.map((block) => {
9372
- if (remaining.count === 0 || !isRecord$66(block)) return block;
9372
+ if (remaining.count === 0 || !isRecord$67(block)) return block;
9373
9373
  if (block.type === "image") {
9374
9374
  if (requestImagePayloadLength(block, images) === void 0) return block;
9375
9375
  remaining.count -= 1;
@@ -9511,7 +9511,7 @@ function collectImageOccurrences(options, images) {
9511
9511
  const walk = (content) => {
9512
9512
  if (!Array.isArray(content)) return;
9513
9513
  for (const block of content) {
9514
- if (!isRecord$66(block)) continue;
9514
+ if (!isRecord$67(block)) continue;
9515
9515
  if (block.type === "image") {
9516
9516
  const bytes = requestImagePayloadLength(block, images);
9517
9517
  const key = requestImageKey(block, images);
@@ -9528,6 +9528,22 @@ function collectImageOccurrences(options, images) {
9528
9528
  return occurrences;
9529
9529
  }
9530
9530
  /**
9531
+ * Inline base64 bytes one request actually carries.
9532
+ *
9533
+ * `inlineExcludedKeys` names occurrences serialized as hosted references on
9534
+ * this build. Their original resolution still supplies the identity, but the
9535
+ * reference—not the base64 payload—is what goes on the wire, so those bytes
9536
+ * must not be reported as request image usage.
9537
+ */
9538
+ function requestInlineImageBytes(options, images, inlineExcludedKeys) {
9539
+ let total = 0;
9540
+ for (const occurrence of collectImageOccurrences(options, images)) {
9541
+ if (inlineExcludedKeys?.has(occurrence.key)) continue;
9542
+ total += occurrence.bytes;
9543
+ }
9544
+ return total;
9545
+ }
9546
+ /**
9531
9547
  * The identities of the images one request still carries, each once.
9532
9548
  *
9533
9549
  * The caller compares two of these to learn what a later build gave back: the
@@ -9565,7 +9581,7 @@ function replaceDroppedRequestImages(options, droppedKeys, images) {
9565
9581
  let replaced = false;
9566
9582
  return {
9567
9583
  content: content.map((block) => {
9568
- if (!isRecord$66(block)) return block;
9584
+ if (!isRecord$67(block)) return block;
9569
9585
  if (block.type === "image") {
9570
9586
  const key = requestImageKey(block, images);
9571
9587
  if (key === void 0 || !droppedKeys.has(key)) return block;
@@ -9632,13 +9648,17 @@ function replaceDroppedRequestImages(options, droppedKeys, images) {
9632
9648
  * @param lowBytes - low-water mark; the trimming stops once the request is back under it.
9633
9649
  * @param images - the resolution the request will be sent with.
9634
9650
  * @param priorDroppedKeys - identities dropped by earlier turns.
9651
+ * @param inlineExcludedKeys - identities whose actual wire form is a hosted
9652
+ * reference rather than inline bytes. They stay in request order with a zero
9653
+ * byte weight; only genuinely inline images consume this budget.
9635
9654
  */
9636
- function offloadRequestImagesWithStickyBudget(options, maxBytes = MAX_REQUEST_IMAGE_BYTES$2, lowBytes = Math.max(1, Math.floor(maxBytes / 2)), images, priorDroppedKeys) {
9655
+ function offloadRequestImagesWithStickyBudget(options, maxBytes = MAX_REQUEST_IMAGE_BYTES$2, lowBytes = Math.max(1, Math.floor(maxBytes / 2)), images, priorDroppedKeys, inlineExcludedKeys) {
9637
9656
  const allDroppedKeys = new Set(priorDroppedKeys ?? []);
9638
9657
  const pending = /* @__PURE__ */ new Map();
9639
9658
  for (const occurrence of collectImageOccurrences(options, images)) {
9640
9659
  if (allDroppedKeys.has(occurrence.key)) continue;
9641
- pending.set(occurrence.key, (pending.get(occurrence.key) ?? 0) + occurrence.bytes);
9660
+ const bytes = inlineExcludedKeys?.has(occurrence.key) ? 0 : occurrence.bytes;
9661
+ pending.set(occurrence.key, (pending.get(occurrence.key) ?? 0) + bytes);
9642
9662
  }
9643
9663
  let total = 0;
9644
9664
  for (const bytes of pending.values()) total += bytes;
@@ -9750,7 +9770,7 @@ function unavailableImageText$5(block) {
9750
9770
  }
9751
9771
  function imageBlockToInline$3(block, images) {
9752
9772
  let data = asString$29(block.data) || asString$29(block.base64);
9753
- const source = isRecord$66(block.source) ? block.source : void 0;
9773
+ const source = isRecord$67(block.source) ? block.source : void 0;
9754
9774
  if (!data && source) data = asString$29(source.data) || asString$29(source.base64);
9755
9775
  let mediaType = asString$29(block.mimeType) || asString$29(block.mediaType) || (source ? asString$29(source.mimeType) || asString$29(source.mediaType) : void 0) || "image/png";
9756
9776
  if (data?.startsWith("data:")) {
@@ -9896,12 +9916,12 @@ const BOOLEAN_KEYS = [
9896
9916
  "waitWarmup",
9897
9917
  "hint"
9898
9918
  ];
9899
- function isRecord$65(value) {
9919
+ function isRecord$66(value) {
9900
9920
  return typeof value === "object" && value !== null && !Array.isArray(value);
9901
9921
  }
9902
9922
  /** Validate one provider override without silently dropping unknown keys. */
9903
9923
  function parsePromptCacheOverride(provider, value) {
9904
- if (!isRecord$65(value)) throw new Error(`prompt cache policy for "${provider}" must be an object`);
9924
+ if (!isRecord$66(value)) throw new Error(`prompt cache policy for "${provider}" must be an object`);
9905
9925
  const out = {};
9906
9926
  for (const [key, entry] of Object.entries(value)) {
9907
9927
  if (!OVERRIDE_KEYS.has(key)) throw new Error(`prompt cache policy for "${provider}" has unknown field "${key}"`);
@@ -9922,7 +9942,7 @@ function parsePromptCacheOverride(provider, value) {
9922
9942
  /** Validate a whole config-owned map. Undefined means no overrides. */
9923
9943
  function parsePromptCacheOverrides(value) {
9924
9944
  if (value === void 0) return {};
9925
- if (!isRecord$65(value)) throw new Error("promptCacheOverrides must be an object keyed by provider id");
9945
+ if (!isRecord$66(value)) throw new Error("promptCacheOverrides must be an object keyed by provider id");
9926
9946
  const out = {};
9927
9947
  for (const [provider, override] of Object.entries(value)) {
9928
9948
  if (!/^[a-z0-9][a-z0-9-]*$/.test(provider)) throw new Error(`invalid prompt cache provider id "${provider}"`);
@@ -10104,14 +10124,14 @@ async function fetchWithPrefixCoordination(fetchFn, coordinator, groupKey, warmT
10104
10124
  }
10105
10125
  //#endregion
10106
10126
  //#region src/host/common/prefix-stability.ts
10107
- function isRecord$64(value) {
10127
+ function isRecord$65(value) {
10108
10128
  return typeof value === "object" && value !== null && !Array.isArray(value);
10109
10129
  }
10110
10130
  function firstTextOf$1(content) {
10111
10131
  if (typeof content === "string") return content.trim() === "" ? void 0 : content;
10112
10132
  if (!Array.isArray(content)) return void 0;
10113
10133
  for (const block of content) {
10114
- if (!isRecord$64(block)) continue;
10134
+ if (!isRecord$65(block)) continue;
10115
10135
  if (block.type === "text" && typeof block.text === "string" && block.text !== "") return block.text;
10116
10136
  if (block.type === "tool-result") {
10117
10137
  const nested = firstTextOf$1(block.content);
@@ -10125,7 +10145,7 @@ function isToolResultMessage$9(message) {
10125
10145
  /** Stability tier for an initial bootstrap reminder; null means dynamic/history-bound. */
10126
10146
  function classifyBootstrapUserMessage$1(message) {
10127
10147
  if (message.role !== "user" || isToolResultMessage$9(message)) return null;
10128
- const source = isRecord$64(message.source) ? message.source : void 0;
10148
+ const source = isRecord$65(message.source) ? message.source : void 0;
10129
10149
  const kind = source !== void 0 && typeof source.kind === "string" ? source.kind : void 0;
10130
10150
  const text = firstTextOf$1(message.content)?.trimStart() ?? "";
10131
10151
  if (kind === "progress-updates-language" || text.startsWith("Progress update output language override:")) return 1;
@@ -10136,7 +10156,7 @@ function classifyBootstrapUserMessage$1(message) {
10136
10156
  }
10137
10157
  function isCompactCheckpointMessage(message) {
10138
10158
  if (message === void 0 || message.role !== "user" || isToolResultMessage$9(message)) return false;
10139
- const source = isRecord$64(message.source) ? message.source : void 0;
10159
+ const source = isRecord$65(message.source) ? message.source : void 0;
10140
10160
  if (source !== void 0 && source.kind === "compact-checkpoint") return true;
10141
10161
  return firstTextOf$1(message.content)?.trimStart().startsWith("This is an automatically generated checkpoint condensing") === true;
10142
10162
  }
@@ -10144,7 +10164,7 @@ function isCompactCheckpointMessage(message) {
10144
10164
  function normalizeAgentInstructionsMessage(message) {
10145
10165
  if (!Array.isArray(message.content) || message.content.length !== 1) return message;
10146
10166
  const first = message.content[0];
10147
- if (!isRecord$64(first) || first.type !== "text" || typeof first.text !== "string") return message;
10167
+ if (!isRecord$65(first) || first.type !== "text" || typeof first.text !== "string") return message;
10148
10168
  const raw = first.text;
10149
10169
  const firstIdx = raw.indexOf("\n\nInstructions from: ");
10150
10170
  if (firstIdx < 0) return message;
@@ -10257,7 +10277,7 @@ function allTextOf(content) {
10257
10277
  if (typeof content === "string") return content;
10258
10278
  if (!Array.isArray(content)) return "";
10259
10279
  return content.map((block) => {
10260
- if (!isRecord$64(block)) return "";
10280
+ if (!isRecord$65(block)) return "";
10261
10281
  if (block.type === "text" && typeof block.text === "string") return block.text;
10262
10282
  if (block.type === "tool-result") return allTextOf(block.content);
10263
10283
  return "";
@@ -11040,7 +11060,7 @@ function withoutValidatedToolConfig(body) {
11040
11060
  * a tool call only runs after its stream finishes, so retrying can neither
11041
11061
  * repeat committed output nor re-run a tool.
11042
11062
  */
11043
- function streamFailure$2(error, signal) {
11063
+ function streamFailure$3(error, signal) {
11044
11064
  if (error instanceof LlmError) return error;
11045
11065
  if (signal.aborted) return new LlmError("Antigravity stream aborted", "ABORTED", { cause: error });
11046
11066
  const chain = errorChain(error).trim();
@@ -11320,7 +11340,7 @@ var AntigravityAdapter = class extends LlmAdapter {
11320
11340
  try {
11321
11341
  while (true) {
11322
11342
  const { done, value } = await reader.read().catch((error) => {
11323
- throw streamFailure$2(error, signal);
11343
+ throw streamFailure$3(error, signal);
11324
11344
  });
11325
11345
  if (done) break;
11326
11346
  if (value !== void 0 && value.byteLength > 0) activity?.pulse();
@@ -12738,11 +12758,11 @@ function createControlledModelFetch(baseFetch, options) {
12738
12758
  * text and may opt into a hard handoff threshold; coordination tools are exempt
12739
12759
  * because they are expected to recur while real work continues.
12740
12760
  */
12741
- function isRecord$63(value) {
12761
+ function isRecord$64(value) {
12742
12762
  return typeof value === "object" && value !== null;
12743
12763
  }
12744
12764
  function isPlainRecord$2(value) {
12745
- if (!isRecord$63(value) || Array.isArray(value)) return false;
12765
+ if (!isRecord$64(value) || Array.isArray(value)) return false;
12746
12766
  const prototype = Object.getPrototypeOf(value);
12747
12767
  return prototype === Object.prototype || prototype === null;
12748
12768
  }
@@ -14832,7 +14852,7 @@ var ResponsesClient = class {
14832
14852
  try {
14833
14853
  yield* wrapStreamWithWatchdog((watchdogSignal, activity) => parseResponsesStream(response, watchdogSignal, void 0, activity), options.signal, this.codexStreamIdleTimeoutMs, "LLM_STREAM_IDLE_TIMEOUT", "Codex");
14834
14854
  } catch (error) {
14835
- throw streamFailure$1(error, options.signal);
14855
+ throw streamFailure$2(error, options.signal);
14836
14856
  } finally {
14837
14857
  this.turnStates.delete(turnKey);
14838
14858
  release?.();
@@ -15041,7 +15061,7 @@ function isPreConnectionFailure$2(error) {
15041
15061
  * attempt on retry, and a tool call is only executed after its stream finishes,
15042
15062
  * so retrying can neither repeat committed output nor re-run a tool.
15043
15063
  */
15044
- function streamFailure$1(error, signal) {
15064
+ function streamFailure$2(error, signal) {
15045
15065
  if (error instanceof LlmError) return error;
15046
15066
  if (signal?.aborted) return new LlmError("Codex request aborted", "ABORTED", { cause: error });
15047
15067
  const chain = errorChain(error).trim();
@@ -17130,7 +17150,7 @@ async function compactionCandidates(ctx) {
17130
17150
  };
17131
17151
  }))).filter((provider) => provider.models.length > 0) };
17132
17152
  }
17133
- function isRecord$62(value) {
17153
+ function isRecord$63(value) {
17134
17154
  return typeof value === "object" && value !== null && !Array.isArray(value);
17135
17155
  }
17136
17156
  function readPreferencesUpdate(value, current) {
@@ -17188,7 +17208,7 @@ function readPreferencesUpdate(value, current) {
17188
17208
  patch.subagentAllowParentForkByMainModel = value.subagentAllowParentForkByMainModel;
17189
17209
  }
17190
17210
  if ("contextWindowOverrides" in value) {
17191
- if (!isRecord$62(value.contextWindowOverrides)) throw new PreferenceError("contextWindowOverrides must be an object.");
17211
+ if (!isRecord$63(value.contextWindowOverrides)) throw new PreferenceError("contextWindowOverrides must be an object.");
17192
17212
  const overrides = {};
17193
17213
  for (const [model, contextWindow] of Object.entries(value.contextWindowOverrides)) {
17194
17214
  if (!isCodexModelId(model)) throw new PreferenceError("Unknown Codex model for a context window override.");
@@ -22086,11 +22106,11 @@ function commandCodeHeaders(apiKey, extra = {}) {
22086
22106
  function timeoutSignal$5(signal, ms) {
22087
22107
  return signal ? AbortSignal.any([signal, AbortSignal.timeout(ms)]) : AbortSignal.timeout(ms);
22088
22108
  }
22089
- function isRecord$61(value) {
22109
+ function isRecord$62(value) {
22090
22110
  return typeof value === "object" && value !== null && !Array.isArray(value);
22091
22111
  }
22092
22112
  function asRecord$16(value) {
22093
- return isRecord$61(value) ? value : void 0;
22113
+ return isRecord$62(value) ? value : void 0;
22094
22114
  }
22095
22115
  function asString$28(value) {
22096
22116
  if (typeof value === "string" && value.trim() !== "") return value;
@@ -22134,7 +22154,7 @@ function deepValue(value, keys, depth = 0) {
22134
22154
  }
22135
22155
  return;
22136
22156
  }
22137
- if (!isRecord$61(value)) return void 0;
22157
+ if (!isRecord$62(value)) return void 0;
22138
22158
  for (const key of keys) if (value[key] !== void 0 && value[key] !== null) return value[key];
22139
22159
  for (const nested of Object.values(value)) {
22140
22160
  const hit = deepValue(nested, keys, depth + 1);
@@ -22148,7 +22168,7 @@ function collectRecords(value, keys, depth = 0, out = []) {
22148
22168
  for (const entry of value) collectRecords(entry, keys, depth + 1, out);
22149
22169
  return out;
22150
22170
  }
22151
- if (!isRecord$61(value)) return out;
22171
+ if (!isRecord$62(value)) return out;
22152
22172
  if (keys.some((key) => value[key] !== void 0)) out.push(value);
22153
22173
  for (const nested of Object.values(value)) collectRecords(nested, keys, depth + 1, out);
22154
22174
  return out;
@@ -23044,7 +23064,7 @@ function cleanOrphanedToolCalls(messages, refold) {
23044
23064
  *
23045
23065
  * https://commandcode.ai/blog/command-code-provider-api
23046
23066
  */
23047
- function isRecord$60(value) {
23067
+ function isRecord$61(value) {
23048
23068
  return typeof value === "object" && value !== null && !Array.isArray(value);
23049
23069
  }
23050
23070
  function asString$26(value) {
@@ -23084,17 +23104,17 @@ const SUPPORTED_IMAGE_MEDIA_TYPES$3 = /* @__PURE__ */ new Set([
23084
23104
  ]);
23085
23105
  function attachmentOf$3(block) {
23086
23106
  const attachment = block.attachment;
23087
- if (!isRecord$60(attachment)) return void 0;
23107
+ if (!isRecord$61(attachment)) return void 0;
23088
23108
  return typeof attachment.attachmentId === "string" ? attachment : void 0;
23089
23109
  }
23090
23110
  function attachmentLabel$4(block) {
23091
- const attachment = isRecord$60(block.attachment) ? block.attachment : void 0;
23111
+ const attachment = isRecord$61(block.attachment) ? block.attachment : void 0;
23092
23112
  return asString$26(attachment?.name) || asString$26(attachment?.attachmentId);
23093
23113
  }
23094
23114
  function collectImageRefs$1(content, refs) {
23095
23115
  if (!Array.isArray(content)) return;
23096
23116
  for (const block of content) {
23097
- if (!isRecord$60(block)) continue;
23117
+ if (!isRecord$61(block)) continue;
23098
23118
  if (block.type === "image") {
23099
23119
  const attachment = attachmentOf$3(block);
23100
23120
  if (attachment) refs.set(attachment.attachmentId, attachment);
@@ -23115,7 +23135,7 @@ function requestImageBytes$1(block) {
23115
23135
  function collectRequestImageBytes$1(content, lengths) {
23116
23136
  if (!Array.isArray(content)) return;
23117
23137
  for (const block of content) {
23118
- if (!isRecord$60(block)) continue;
23138
+ if (!isRecord$61(block)) continue;
23119
23139
  if (block.type === "tool-result") {
23120
23140
  collectRequestImageBytes$1(block.content, lengths);
23121
23141
  continue;
@@ -23151,7 +23171,7 @@ function offloadOldestRequestImages$1(options) {
23151
23171
  let replaced = false;
23152
23172
  return {
23153
23173
  content: content.map((block) => {
23154
- if (remaining.count === 0 || !isRecord$60(block)) return block;
23174
+ if (remaining.count === 0 || !isRecord$61(block)) return block;
23155
23175
  if (block.type === "image") {
23156
23176
  if (requestImageBytes$1(block) === void 0) return block;
23157
23177
  remaining.count -= 1;
@@ -23223,7 +23243,7 @@ function unavailableImageText$4(block) {
23223
23243
  }
23224
23244
  function imageBlockToInline$2(block, images) {
23225
23245
  let data = asString$26(block.data) || asString$26(block.base64);
23226
- const source = isRecord$60(block.source) ? block.source : void 0;
23246
+ const source = isRecord$61(block.source) ? block.source : void 0;
23227
23247
  if (!data && source) data = asString$26(source.data) || asString$26(source.base64);
23228
23248
  let mediaType = asString$26(block.mimeType) || asString$26(block.mediaType) || (source ? asString$26(source.mimeType) || asString$26(source.mediaType) : void 0) || "image/png";
23229
23249
  if (data?.startsWith("data:")) {
@@ -23249,7 +23269,7 @@ function textOf$9(content) {
23249
23269
  if (!Array.isArray(content)) return "";
23250
23270
  const parts = [];
23251
23271
  for (const block of content) {
23252
- if (!isRecord$60(block)) continue;
23272
+ if (!isRecord$61(block)) continue;
23253
23273
  if (block.type === "text" && typeof block.text === "string") parts.push(sanitizeText$8(block.text));
23254
23274
  else if (block.type === "tool-result") parts.push(textOf$9(block.content));
23255
23275
  }
@@ -23258,7 +23278,7 @@ function textOf$9(content) {
23258
23278
  function toolResultText$8(blocks) {
23259
23279
  if (!Array.isArray(blocks)) return "";
23260
23280
  return blocks.map((block) => {
23261
- if (!isRecord$60(block)) return "";
23281
+ if (!isRecord$61(block)) return "";
23262
23282
  if (block.type === "text" && typeof block.text === "string") return sanitizeText$8(block.text);
23263
23283
  if (block.type === "tool-result") return toolResultText$8(block.content);
23264
23284
  if (block.type === "image") return `[image: ${attachmentLabel$4(block) ?? "attached image"}]`;
@@ -23276,7 +23296,7 @@ function toolResultBlocks$2(blocks, images) {
23276
23296
  const out = [];
23277
23297
  let hasImage = false;
23278
23298
  for (const block of blocks) {
23279
- if (!isRecord$60(block)) continue;
23299
+ if (!isRecord$61(block)) continue;
23280
23300
  if (block.type === "text" && typeof block.text === "string") {
23281
23301
  out.push({
23282
23302
  type: "text",
@@ -23325,7 +23345,7 @@ function toolResultImageBlocks$5(blocks, images) {
23325
23345
  if (!Array.isArray(blocks)) return [];
23326
23346
  const out = [];
23327
23347
  for (const block of blocks) {
23328
- if (!isRecord$60(block)) continue;
23348
+ if (!isRecord$61(block)) continue;
23329
23349
  if (block.type === "image") {
23330
23350
  const inline = imageBlockToInline$2(block, images);
23331
23351
  if (inline && SUPPORTED_IMAGE_MEDIA_TYPES$3.has(inline.mediaType)) out.push({
@@ -23369,7 +23389,7 @@ function nonSystemMessages$7(options) {
23369
23389
  }
23370
23390
  /** Drop the JSON-Schema keywords provider gateways reject or ignore. */
23371
23391
  function stripMetaSchema$2(schema) {
23372
- if (!isRecord$60(schema)) return {
23392
+ if (!isRecord$61(schema)) return {
23373
23393
  type: "object",
23374
23394
  properties: {}
23375
23395
  };
@@ -23386,7 +23406,7 @@ function openAIUserContent$4(message, images) {
23386
23406
  const parts = [];
23387
23407
  let hasImage = false;
23388
23408
  for (const block of message.content) {
23389
- if (!isRecord$60(block)) continue;
23409
+ if (!isRecord$61(block)) continue;
23390
23410
  if (block.type === "text" && typeof block.text === "string") {
23391
23411
  const text = sanitizeText$8(block.text);
23392
23412
  if (text !== "") parts.push({
@@ -23414,7 +23434,7 @@ function openAIAssistantContent$4(message) {
23414
23434
  const textParts = [];
23415
23435
  const toolCalls = [];
23416
23436
  for (const block of message.content) {
23417
- if (!isRecord$60(block)) continue;
23437
+ if (!isRecord$61(block)) continue;
23418
23438
  if (block.type === "text" && typeof block.text === "string") textParts.push(sanitizeText$8(block.text));
23419
23439
  else if (block.type === "tool-call" && typeof block.name === "string") toolCalls.push({
23420
23440
  id: typeof block.id === "string" && block.id !== "" ? block.id : `call_${toolCalls.length}`,
@@ -23464,7 +23484,7 @@ function buildOpenAIRequest$1(options, images = NO_RESOLVED_IMAGES$3) {
23464
23484
  while (index < conversation.length && isToolResultMessage$8(conversation[index])) {
23465
23485
  const current = conversation[index];
23466
23486
  const block = current.content[0];
23467
- const callId = isRecord$60(block) && typeof block.toolCallId === "string" ? block.toolCallId : "";
23487
+ const callId = isRecord$61(block) && typeof block.toolCallId === "string" ? block.toolCallId : "";
23468
23488
  messages.push({
23469
23489
  role: "tool",
23470
23490
  tool_call_id: callId,
@@ -23525,7 +23545,7 @@ function anthropicUserContent$3(message, images) {
23525
23545
  if (!Array.isArray(message.content)) return [];
23526
23546
  const blocks = [];
23527
23547
  for (const block of message.content) {
23528
- if (!isRecord$60(block)) continue;
23548
+ if (!isRecord$61(block)) continue;
23529
23549
  if (block.type === "text" && typeof block.text === "string") {
23530
23550
  const text = sanitizeText$8(block.text);
23531
23551
  if (text !== "") blocks.push({
@@ -23562,7 +23582,7 @@ function anthropicUserContent$3(message, images) {
23562
23582
  function anthropicAssistantContent$3(message) {
23563
23583
  const blocks = [];
23564
23584
  for (const block of message.content) {
23565
- if (!isRecord$60(block)) continue;
23585
+ if (!isRecord$61(block)) continue;
23566
23586
  if (block.type === "text" && typeof block.text === "string") {
23567
23587
  const text = sanitizeText$8(block.text);
23568
23588
  if (text !== "") blocks.push({
@@ -23575,7 +23595,7 @@ function anthropicAssistantContent$3(message) {
23575
23595
  type: "tool_use",
23576
23596
  id: typeof block.id === "string" && block.id !== "" ? block.id : `toolu_${blocks.length}`,
23577
23597
  name: block.name,
23578
- input: isRecord$60(parsed) ? parsed : {}
23598
+ input: isRecord$61(parsed) ? parsed : {}
23579
23599
  });
23580
23600
  }
23581
23601
  }
@@ -23714,7 +23734,7 @@ function responsesUserContent(message, images) {
23714
23734
  if (!Array.isArray(message.content)) return [];
23715
23735
  const parts = [];
23716
23736
  for (const block of message.content) {
23717
- if (!isRecord$60(block)) continue;
23737
+ if (!isRecord$61(block)) continue;
23718
23738
  if (block.type === "text" && typeof block.text === "string") {
23719
23739
  const text = sanitizeText$8(block.text);
23720
23740
  if (text !== "") parts.push({
@@ -23739,7 +23759,7 @@ function responsesToolResultImageBlocks(blocks, images) {
23739
23759
  if (!Array.isArray(blocks)) return [];
23740
23760
  const out = [];
23741
23761
  for (const block of blocks) {
23742
- if (!isRecord$60(block)) continue;
23762
+ if (!isRecord$61(block)) continue;
23743
23763
  if (block.type === "image") {
23744
23764
  const inline = imageBlockToInline$2(block, images);
23745
23765
  if (inline && SUPPORTED_IMAGE_MEDIA_TYPES$3.has(inline.mediaType)) out.push({
@@ -23766,8 +23786,8 @@ function buildResponsesRequest(options, images = NO_RESOLVED_IMAGES$3) {
23766
23786
  const imageBlocks = [];
23767
23787
  while (index < conversation.length && isToolResultMessage$8(conversation[index])) {
23768
23788
  const current = conversation[index];
23769
- const toolResult = Array.isArray(current.content) ? current.content.find((b) => isRecord$60(b) && b.type === "tool-result") : void 0;
23770
- const callId = (isRecord$60(toolResult) && typeof toolResult.toolCallId === "string" ? toolResult.toolCallId : "") || (typeof current.source?.callId === "string" ? current.source.callId : "");
23789
+ const toolResult = Array.isArray(current.content) ? current.content.find((b) => isRecord$61(b) && b.type === "tool-result") : void 0;
23790
+ const callId = (isRecord$61(toolResult) && typeof toolResult.toolCallId === "string" ? toolResult.toolCallId : "") || (typeof current.source?.callId === "string" ? current.source.callId : "");
23771
23791
  input.push({
23772
23792
  type: "function_call_output",
23773
23793
  call_id: callId,
@@ -23790,7 +23810,7 @@ function buildResponsesRequest(options, images = NO_RESOLVED_IMAGES$3) {
23790
23810
  content
23791
23811
  });
23792
23812
  for (const call of toolCalls) {
23793
- const fn = isRecord$60(call.function) ? call.function : void 0;
23813
+ const fn = isRecord$61(call.function) ? call.function : void 0;
23794
23814
  input.push({
23795
23815
  type: "function_call",
23796
23816
  call_id: call.id,
@@ -23913,9 +23933,9 @@ function processOpenAIStreamLine$1(line, state) {
23913
23933
  }
23914
23934
  if (payload === "") return [];
23915
23935
  const chunk = safeJsonParse$8(payload);
23916
- if (!isRecord$60(chunk)) return [];
23936
+ if (!isRecord$61(chunk)) return [];
23917
23937
  const out = [];
23918
- if (isRecord$60(chunk.error)) {
23938
+ if (isRecord$61(chunk.error)) {
23919
23939
  const message = asString$26(chunk.error.message) ?? "unknown error";
23920
23940
  state.streamError = {
23921
23941
  vocabulary: "openai",
@@ -23924,20 +23944,20 @@ function processOpenAIStreamLine$1(line, state) {
23924
23944
  };
23925
23945
  throw new LlmError$1(`Command Code stream error: ${message}`, isContextOverflow(chunk.error) ? CONTEXT_OVERFLOW_CODE : "PROVIDER_ERROR");
23926
23946
  }
23927
- const usage = isRecord$60(chunk.usage) ? chunk.usage : void 0;
23947
+ const usage = isRecord$61(chunk.usage) ? chunk.usage : void 0;
23928
23948
  if (usage) {
23929
23949
  state.sawUsage = true;
23930
23950
  const prompt = numberOr$9(usage.prompt_tokens, 0);
23931
- const details = isRecord$60(usage.prompt_tokens_details) ? usage.prompt_tokens_details : void 0;
23951
+ const details = isRecord$61(usage.prompt_tokens_details) ? usage.prompt_tokens_details : void 0;
23932
23952
  const cached = details ? numberOr$9(details.cached_tokens, 0) : 0;
23933
23953
  state.inputTokens = Math.max(0, prompt - cached);
23934
23954
  state.cacheReadTokens = cached;
23935
23955
  state.outputTokens = numberOr$9(usage.completion_tokens, state.outputTokens);
23936
- if (isRecord$60(usage.completion_tokens_details)) state.reasoningTokens = numberOr$9(usage.completion_tokens_details.reasoning_tokens, state.reasoningTokens);
23956
+ if (isRecord$61(usage.completion_tokens_details)) state.reasoningTokens = numberOr$9(usage.completion_tokens_details.reasoning_tokens, state.reasoningTokens);
23937
23957
  }
23938
23958
  const choices = Array.isArray(chunk.choices) ? chunk.choices : [];
23939
- const choice = isRecord$60(choices[0]) ? choices[0] : void 0;
23940
- const delta = isRecord$60(choice?.delta) ? choice.delta : void 0;
23959
+ const choice = isRecord$61(choices[0]) ? choices[0] : void 0;
23960
+ const delta = isRecord$61(choice?.delta) ? choice.delta : void 0;
23941
23961
  if (delta) {
23942
23962
  const reasoning = asString$26(delta.reasoning_content) ?? asString$26(delta.reasoning);
23943
23963
  if (reasoning !== void 0 && reasoning !== "") {
@@ -23965,7 +23985,7 @@ function processOpenAIStreamLine$1(line, state) {
23965
23985
  }
23966
23986
  const toolDeltas = Array.isArray(delta.tool_calls) ? delta.tool_calls : [];
23967
23987
  for (const entry of toolDeltas) {
23968
- if (!isRecord$60(entry)) continue;
23988
+ if (!isRecord$61(entry)) continue;
23969
23989
  out.push(...applyOpenAIToolDelta$1(entry, state));
23970
23990
  }
23971
23991
  }
@@ -23979,7 +23999,7 @@ function processOpenAIStreamLine$1(line, state) {
23979
23999
  }
23980
24000
  function applyOpenAIToolDelta$1(entry, state) {
23981
24001
  const wireIndex = typeof entry.index === "number" ? entry.index : 0;
23982
- const fn = isRecord$60(entry.function) ? entry.function : {};
24002
+ const fn = isRecord$61(entry.function) ? entry.function : {};
23983
24003
  const out = [];
23984
24004
  let call = state.toolCalls.get(wireIndex);
23985
24005
  const incomingId = asString$26(entry.id);
@@ -24054,12 +24074,12 @@ function processAnthropicStreamLine$1(line, state) {
24054
24074
  const payload = trimmed.slice(5).trim();
24055
24075
  if (payload === "" || payload === "[DONE]") return [];
24056
24076
  const event = safeJsonParse$8(payload);
24057
- if (!isRecord$60(event)) return [];
24077
+ if (!isRecord$61(event)) return [];
24058
24078
  const type = asString$26(event.type);
24059
24079
  const out = [];
24060
24080
  if (type === "message_start") {
24061
- const message = isRecord$60(event.message) ? event.message : void 0;
24062
- const usage = message && isRecord$60(message.usage) ? message.usage : void 0;
24081
+ const message = isRecord$61(event.message) ? event.message : void 0;
24082
+ const usage = message && isRecord$61(message.usage) ? message.usage : void 0;
24063
24083
  if (usage) {
24064
24084
  state.sawUsage = true;
24065
24085
  state.inputTokens = numberOr$9(usage.input_tokens, 0);
@@ -24073,7 +24093,7 @@ function processAnthropicStreamLine$1(line, state) {
24073
24093
  }
24074
24094
  if (type === "content_block_start") {
24075
24095
  const contentIndex = numberOr$9(event.index, 0);
24076
- const block = isRecord$60(event.content_block) ? event.content_block : {};
24096
+ const block = isRecord$61(event.content_block) ? event.content_block : {};
24077
24097
  const blockType = asString$26(block.type);
24078
24098
  out.push(...closeCurrent$6(state));
24079
24099
  if (blockType === "tool_use") {
@@ -24123,7 +24143,7 @@ function processAnthropicStreamLine$1(line, state) {
24123
24143
  }
24124
24144
  if (type === "content_block_delta") {
24125
24145
  const contentIndex = numberOr$9(event.index, 0);
24126
- const delta = isRecord$60(event.delta) ? event.delta : {};
24146
+ const delta = isRecord$61(event.delta) ? event.delta : {};
24127
24147
  const deltaType = asString$26(delta.type);
24128
24148
  if (deltaType === "input_json_delta") {
24129
24149
  const pending = state.toolCalls.get(contentIndex);
@@ -24196,10 +24216,10 @@ function processAnthropicStreamLine$1(line, state) {
24196
24216
  return out;
24197
24217
  }
24198
24218
  if (type === "message_delta") {
24199
- const delta = isRecord$60(event.delta) ? event.delta : void 0;
24219
+ const delta = isRecord$61(event.delta) ? event.delta : void 0;
24200
24220
  const stop = delta ? asString$26(delta.stop_reason) : void 0;
24201
24221
  if (stop !== void 0 && stop !== "") state.finishReason = stop;
24202
- const usage = isRecord$60(event.usage) ? event.usage : void 0;
24222
+ const usage = isRecord$61(event.usage) ? event.usage : void 0;
24203
24223
  if (usage) {
24204
24224
  state.sawUsage = true;
24205
24225
  state.outputTokens = numberOr$9(usage.output_tokens, state.outputTokens);
@@ -24211,7 +24231,7 @@ function processAnthropicStreamLine$1(line, state) {
24211
24231
  return closeStream$6(state);
24212
24232
  }
24213
24233
  if (type === "error") {
24214
- const error = isRecord$60(event.error) ? event.error : {};
24234
+ const error = isRecord$61(event.error) ? event.error : {};
24215
24235
  const message = asString$26(error.message) ?? "unknown error";
24216
24236
  state.streamError = {
24217
24237
  vocabulary: "anthropic",
@@ -24257,7 +24277,7 @@ function processResponsesStreamLine(line, state) {
24257
24277
  } catch {
24258
24278
  return [];
24259
24279
  }
24260
- if (!isRecord$60(parsed)) return [];
24280
+ if (!isRecord$61(parsed)) return [];
24261
24281
  const type = typeof parsed.type === "string" ? parsed.type : "";
24262
24282
  if (type === "response.output_text.delta") {
24263
24283
  const delta = typeof parsed.delta === "string" ? parsed.delta : "";
@@ -24284,7 +24304,7 @@ function processResponsesStreamLine(line, state) {
24284
24304
  }];
24285
24305
  }
24286
24306
  if (type === "response.output_item.added") {
24287
- const item = isRecord$60(parsed.item) ? parsed.item : null;
24307
+ const item = isRecord$61(parsed.item) ? parsed.item : null;
24288
24308
  if (item === null || item.type !== "function_call") return [];
24289
24309
  return startResponsesToolCall(state, parsed, item);
24290
24310
  }
@@ -24308,11 +24328,11 @@ function processResponsesStreamLine(line, state) {
24308
24328
  return [];
24309
24329
  }
24310
24330
  if (type === "response.completed" || type === "response.incomplete") {
24311
- const response = isRecord$60(parsed.response) ? parsed.response : null;
24331
+ const response = isRecord$61(parsed.response) ? parsed.response : null;
24312
24332
  if (response !== null) {
24313
24333
  if (response.status === "failed") {
24314
24334
  state.done = true;
24315
- const errorObj = isRecord$60(response.error) ? response.error : null;
24335
+ const errorObj = isRecord$61(response.error) ? response.error : null;
24316
24336
  const detail = errorObj && typeof errorObj.message === "string" ? errorObj.message : typeof response.error === "string" ? response.error : "";
24317
24337
  state.streamError = {
24318
24338
  vocabulary: "responses",
@@ -24325,7 +24345,7 @@ function processResponsesStreamLine(line, state) {
24325
24345
  }
24326
24346
  state.done = true;
24327
24347
  if (type === "response.incomplete") {
24328
- const details = response && isRecord$60(response.incomplete_details) ? response.incomplete_details : null;
24348
+ const details = response && isRecord$61(response.incomplete_details) ? response.incomplete_details : null;
24329
24349
  const reason = details && typeof details.reason === "string" ? details.reason : "";
24330
24350
  state.finishReason = reason === "max_output_tokens" || reason === "length" || reason === "max_tokens" ? "length" : reason || "length";
24331
24351
  } else state.finishReason = "stop";
@@ -24333,8 +24353,8 @@ function processResponsesStreamLine(line, state) {
24333
24353
  }
24334
24354
  if (type === "response.failed" || type === "error") {
24335
24355
  state.done = true;
24336
- const errorObj = isRecord$60(parsed.error) ? parsed.error : isRecord$60(parsed.response) && isRecord$60(parsed.response.error) ? parsed.response.error : null;
24337
- const detail = (typeof parsed.message === "string" ? parsed.message : "") || (errorObj && typeof errorObj.message === "string" ? errorObj.message : "") || (isRecord$60(parsed.response) && typeof parsed.response.error === "string" ? parsed.response.error : typeof parsed.error === "string" ? parsed.error : "");
24356
+ const errorObj = isRecord$61(parsed.error) ? parsed.error : isRecord$61(parsed.response) && isRecord$61(parsed.response.error) ? parsed.response.error : null;
24357
+ const detail = (typeof parsed.message === "string" ? parsed.message : "") || (errorObj && typeof errorObj.message === "string" ? errorObj.message : "") || (isRecord$61(parsed.response) && typeof parsed.response.error === "string" ? parsed.response.error : typeof parsed.error === "string" ? parsed.error : "");
24338
24358
  state.streamError = {
24339
24359
  vocabulary: "responses",
24340
24360
  error: errorObj,
@@ -24422,15 +24442,15 @@ function responsesToolCall(state, key) {
24422
24442
  for (const call of state.toolCalls.values()) if (call.id === toToolCallId(key)) return call;
24423
24443
  }
24424
24444
  function readResponsesUsage(response, state) {
24425
- const usage = isRecord$60(response.usage) ? response.usage : null;
24445
+ const usage = isRecord$61(response.usage) ? response.usage : null;
24426
24446
  if (usage === null) return;
24427
- const cached = isRecord$60(usage.input_tokens_details) ? numberOrZero(usage.input_tokens_details.cached_tokens) : 0;
24428
- const written = isRecord$60(usage.input_tokens_details) ? numberOrZero(usage.input_tokens_details.cache_write_tokens) : 0;
24447
+ const cached = isRecord$61(usage.input_tokens_details) ? numberOrZero(usage.input_tokens_details.cached_tokens) : 0;
24448
+ const written = isRecord$61(usage.input_tokens_details) ? numberOrZero(usage.input_tokens_details.cache_write_tokens) : 0;
24429
24449
  state.inputTokens = Math.max(0, numberOrZero(usage.input_tokens) - cached - written);
24430
24450
  state.cacheReadTokens = cached;
24431
24451
  state.cacheWriteTokens = written;
24432
24452
  state.outputTokens = numberOrZero(usage.output_tokens);
24433
- const outputDetails = isRecord$60(usage.output_tokens_details) ? usage.output_tokens_details : null;
24453
+ const outputDetails = isRecord$61(usage.output_tokens_details) ? usage.output_tokens_details : null;
24434
24454
  if (outputDetails !== null) state.reasoningTokens = numberOrZero(outputDetails.reasoning_tokens);
24435
24455
  state.sawUsage = true;
24436
24456
  }
@@ -24518,7 +24538,7 @@ const ANTHROPIC_IN_BAND_STATUS = {
24518
24538
  * Anything not recognized keeps the mapper's verdict.
24519
24539
  */
24520
24540
  function inBandResponsesCode(error, message) {
24521
- const fields = isRecord$59(error) ? error : {};
24541
+ const fields = isRecord$60(error) ? error : {};
24522
24542
  const rawCode = (asString$25(fields.code) ?? asString$25(fields.type) ?? "").toLowerCase();
24523
24543
  const text = message.toLowerCase();
24524
24544
  if (text.includes("rate limit") || rawCode === "rate_limit" || rawCode === "rate_limit_exceeded") return "RATE_LIMIT";
@@ -24577,13 +24597,13 @@ function reclassifyInBandResponsesError(thrown, rawError, message, classify) {
24577
24597
  }
24578
24598
  /** The wire `error` object of an in-band event, read defensively. */
24579
24599
  function readErrorType(error) {
24580
- if (!isRecord$59(error)) return null;
24600
+ if (!isRecord$60(error)) return null;
24581
24601
  return typeof error.type === "string" ? error.type : null;
24582
24602
  }
24583
24603
  function asString$25(value) {
24584
24604
  return typeof value === "string" ? value : void 0;
24585
24605
  }
24586
- function isRecord$59(value) {
24606
+ function isRecord$60(value) {
24587
24607
  return typeof value === "object" && value !== null && !Array.isArray(value);
24588
24608
  }
24589
24609
  //#endregion
@@ -25189,7 +25209,7 @@ var CommandCodeAdapter = class extends LlmAdapter {
25189
25209
  }
25190
25210
  throw reclassified;
25191
25211
  }
25192
- throw error;
25212
+ throw streamFailure$1(error, signal);
25193
25213
  }
25194
25214
  } finally {
25195
25215
  reader.cancel().catch(() => void 0);
@@ -25197,6 +25217,18 @@ var CommandCodeAdapter = class extends LlmAdapter {
25197
25217
  }
25198
25218
  };
25199
25219
  /**
25220
+ * A body severed mid-stream arrives as undici's bare `TypeError: terminated`,
25221
+ * which the harness otherwise normalizes to non-retryable UNKNOWN. Preserve
25222
+ * existing LlmError verdicts and caller cancellation; classify every other
25223
+ * body-read failure as TRANSPORT and retain its cause chain in the message.
25224
+ */
25225
+ function streamFailure$1(error, signal) {
25226
+ if (error instanceof LlmError) return error;
25227
+ if (signal.aborted) return new LlmError("Command Code stream aborted", "ABORTED", { cause: error });
25228
+ const chain = errorChain(error).trim();
25229
+ return new LlmError(`Command Code stream failed: ${chain === "" ? "the response stream ended unexpectedly" : chain.slice(0, 500)}`, "TRANSPORT", { cause: error });
25230
+ }
25231
+ /**
25200
25232
  * The error one recorded in-band failure becomes, or the mapper's own verdict.
25201
25233
  *
25202
25234
  * Two rules, because this line speaks three in-band vocabularies and they do
@@ -27848,14 +27880,14 @@ const IN_BAND_SERVER = [
27848
27880
  function isAbort$2(error, signal) {
27849
27881
  return signal?.aborted === true || error instanceof Error && error.name === "AbortError";
27850
27882
  }
27851
- function isRecord$58(value) {
27883
+ function isRecord$59(value) {
27852
27884
  return typeof value === "object" && value !== null && !Array.isArray(value);
27853
27885
  }
27854
27886
  function asString$24(value) {
27855
27887
  return typeof value === "string" && value !== "" ? value : void 0;
27856
27888
  }
27857
27889
  function attachmentLabel$3(block) {
27858
- const attachment = isRecord$58(block.attachment) ? block.attachment : void 0;
27890
+ const attachment = isRecord$59(block.attachment) ? block.attachment : void 0;
27859
27891
  return asString$24(attachment?.name) || asString$24(attachment?.attachmentId);
27860
27892
  }
27861
27893
  function unavailableImageText$3(block) {
@@ -27891,7 +27923,7 @@ async function processMessageContent(content, model, attachments, signal) {
27891
27923
  textParts.push(part);
27892
27924
  continue;
27893
27925
  }
27894
- if (!isRecord$58(part)) continue;
27926
+ if (!isRecord$59(part)) continue;
27895
27927
  if (part.type === "text") {
27896
27928
  if (typeof part.text === "string" && part.text !== "") textParts.push(part.text);
27897
27929
  continue;
@@ -27920,7 +27952,7 @@ async function processMessageContent(content, model, attachments, signal) {
27920
27952
  continue;
27921
27953
  }
27922
27954
  const inline = part.source;
27923
- if (isRecord$58(inline)) {
27955
+ if (isRecord$59(inline)) {
27924
27956
  const data = inline.data;
27925
27957
  if (typeof data === "string" && data !== "") {
27926
27958
  images.push(encodeImage(data, asMediaType(inline.mediaType)));
@@ -27961,7 +27993,7 @@ async function toOllamaRequest(options, attachments, signal, declared) {
27961
27993
  const toolResultBlocks = message.content.filter((b) => b.type === "tool-result");
27962
27994
  if (toolResultBlocks.length > 0) {
27963
27995
  for (const block of toolResultBlocks) {
27964
- const toolCallId = String(block.toolCallId ?? (isRecord$58(message.source) ? message.source.callId : "") ?? "");
27996
+ const toolCallId = String(block.toolCallId ?? (isRecord$59(message.source) ? message.source.callId : "") ?? "");
27965
27997
  const processed = await processMessageContent(block.content, options.model, attachments, signal);
27966
27998
  messages.push({
27967
27999
  role: "tool",
@@ -32938,11 +32970,11 @@ const MODELS_PATH$2 = "/models";
32938
32970
  const USAGES_PATH = "/usages";
32939
32971
  /** The service reports money in fixed-point units of 1e-6 cents. */
32940
32972
  const FIXED_POINT_CENTS = 1e6;
32941
- function isRecord$57(value) {
32973
+ function isRecord$58(value) {
32942
32974
  return typeof value === "object" && value !== null && !Array.isArray(value);
32943
32975
  }
32944
32976
  function asRecord$14(value) {
32945
- return isRecord$57(value) ? value : void 0;
32977
+ return isRecord$58(value) ? value : void 0;
32946
32978
  }
32947
32979
  function asString$23(value) {
32948
32980
  if (typeof value === "string" && value.trim() !== "") return value;
@@ -34057,12 +34089,12 @@ async function testConnection$1(store, options = {}) {
34057
34089
  *
34058
34090
  * @module dsh-chatgpt-subscription/tool-schema
34059
34091
  */
34060
- function isRecord$56(value) {
34092
+ function isRecord$57(value) {
34061
34093
  return typeof value === "object" && value !== null && !Array.isArray(value);
34062
34094
  }
34063
34095
  function cloneJsonValue(value) {
34064
34096
  if (Array.isArray(value)) return value.map(cloneJsonValue);
34065
- if (isRecord$56(value)) {
34097
+ if (isRecord$57(value)) {
34066
34098
  const res = {};
34067
34099
  for (const [k, v] of Object.entries(value)) res[k] = cloneJsonValue(v);
34068
34100
  return res;
@@ -34077,7 +34109,7 @@ function resolveLocalJsonPointer(root, ref) {
34077
34109
  let current = root;
34078
34110
  for (const rawPart of ref.slice(2).split("/")) {
34079
34111
  const part = rawPart.replaceAll("~1", "/").replaceAll("~0", "~");
34080
- if (isRecord$56(current)) {
34112
+ if (isRecord$57(current)) {
34081
34113
  if (!Object.prototype.hasOwnProperty.call(current, part)) return { found: false };
34082
34114
  current = current[part];
34083
34115
  } else if (Array.isArray(current)) {
@@ -34093,7 +34125,7 @@ function resolveLocalJsonPointer(root, ref) {
34093
34125
  }
34094
34126
  function derefNode(node, root, visited) {
34095
34127
  if (Array.isArray(node)) return node.map((item) => derefNode(item, root, visited));
34096
- if (isRecord$56(node)) {
34128
+ if (isRecord$57(node)) {
34097
34129
  if (typeof node["$ref"] === "string" && (node["$ref"] === "#" || node["$ref"].startsWith("#/"))) {
34098
34130
  const ref = node["$ref"];
34099
34131
  if (visited.has(ref)) return node;
@@ -34102,7 +34134,7 @@ function derefNode(node, root, visited) {
34102
34134
  visited.add(ref);
34103
34135
  const inlined = derefNode(resolved.value, root, visited);
34104
34136
  visited.delete(ref);
34105
- if (isRecord$56(inlined)) {
34137
+ if (isRecord$57(inlined)) {
34106
34138
  const merged = { ...inlined };
34107
34139
  for (const [k, v] of Object.entries(node)) {
34108
34140
  if (k === "$ref") continue;
@@ -34122,7 +34154,7 @@ function derefNode(node, root, visited) {
34122
34154
  }
34123
34155
  function hasUnresolvedDefinitionRef(node, bucketKey) {
34124
34156
  if (Array.isArray(node)) return node.some((child) => hasUnresolvedDefinitionRef(child, bucketKey));
34125
- if (isRecord$56(node)) {
34157
+ if (isRecord$57(node)) {
34126
34158
  const ref = node["$ref"];
34127
34159
  if (typeof ref === "string" && ref.startsWith(`#/${bucketKey}/`)) return true;
34128
34160
  for (const [k, v] of Object.entries(node)) {
@@ -34153,19 +34185,19 @@ function inferTypeFromValues(values) {
34153
34185
  if (types.size === 1) return types.values().next().value;
34154
34186
  }
34155
34187
  function normalizeSchemaProperties(node) {
34156
- if (!isRecord$56(node)) return;
34157
- if (isRecord$56(node.properties)) {
34158
- for (const propSchema of Object.values(node.properties)) if (isRecord$56(propSchema)) {
34188
+ if (!isRecord$57(node)) return;
34189
+ if (isRecord$57(node.properties)) {
34190
+ for (const propSchema of Object.values(node.properties)) if (isRecord$57(propSchema)) {
34159
34191
  if (!propSchema.type && !propSchema.$ref) {
34160
34192
  if (Array.isArray(propSchema.enum) && propSchema.enum.length > 0) propSchema.type = inferTypeFromValues(propSchema.enum) ?? "string";
34161
34193
  else if (propSchema.const !== void 0) propSchema.type = inferValueType(propSchema.const) ?? "string";
34162
- else if (isRecord$56(propSchema.properties)) propSchema.type = "object";
34194
+ else if (isRecord$57(propSchema.properties)) propSchema.type = "object";
34163
34195
  else if (propSchema.items) propSchema.type = "array";
34164
34196
  }
34165
34197
  normalizeSchemaProperties(propSchema);
34166
34198
  }
34167
34199
  }
34168
- if (isRecord$56(node.items)) normalizeSchemaProperties(node.items);
34200
+ if (isRecord$57(node.items)) normalizeSchemaProperties(node.items);
34169
34201
  else if (Array.isArray(node.items)) for (const item of node.items) normalizeSchemaProperties(item);
34170
34202
  }
34171
34203
  /**
@@ -34173,7 +34205,7 @@ function normalizeSchemaProperties(node) {
34173
34205
  * inlining definitions ($defs/definitions/$ref), and ensuring property types for enums/consts.
34174
34206
  */
34175
34207
  function normalizeKimiToolSchema(schema) {
34176
- if (!isRecord$56(schema)) return {
34208
+ if (!isRecord$57(schema)) return {
34177
34209
  type: "object",
34178
34210
  properties: {}
34179
34211
  };
@@ -34191,7 +34223,7 @@ function stripMetaSchema$1(schema) {
34191
34223
  }
34192
34224
  //#endregion
34193
34225
  //#region src/host/common/prompt-estimate.ts
34194
- function isRecord$55(value) {
34226
+ function isRecord$56(value) {
34195
34227
  return typeof value === "object" && value !== null && !Array.isArray(value);
34196
34228
  }
34197
34229
  /** Tool-call arguments as the JSON string a wire carries, whatever shape they arrived in. */
@@ -34224,7 +34256,7 @@ function estimatedInputTokens(options) {
34224
34256
  const contentCharacters = (content) => {
34225
34257
  if (!Array.isArray(content)) return typeof content === "string" ? content.length : 0;
34226
34258
  return content.reduce((total, block) => {
34227
- if (!isRecord$55(block)) return total;
34259
+ if (!isRecord$56(block)) return total;
34228
34260
  if ((block.type === "text" || block.type === "reasoning") && typeof block.text === "string") return total + block.text.length;
34229
34261
  if (block.type === "tool-result") return total + contentCharacters(block.content);
34230
34262
  if (block.type === "tool-call") {
@@ -34367,7 +34399,7 @@ function videoOmissionText$1(reason, label) {
34367
34399
  }
34368
34400
  //#endregion
34369
34401
  //#region src/host/common/video-request.ts
34370
- function isRecord$54(value) {
34402
+ function isRecord$55(value) {
34371
34403
  return typeof value === "object" && value !== null && !Array.isArray(value);
34372
34404
  }
34373
34405
  function asString$22(value) {
@@ -34375,14 +34407,14 @@ function asString$22(value) {
34375
34407
  }
34376
34408
  function videoAttachmentOf(block) {
34377
34409
  const attachment = block.attachment;
34378
- if (!isRecord$54(attachment)) return void 0;
34410
+ if (!isRecord$55(attachment)) return void 0;
34379
34411
  if (typeof attachment.attachmentId !== "string") return void 0;
34380
34412
  return attachment;
34381
34413
  }
34382
34414
  function collectVideoRefs(content, refs) {
34383
34415
  if (!Array.isArray(content)) return;
34384
34416
  for (const block of content) {
34385
- if (!isRecord$54(block) || block.type !== "video") continue;
34417
+ if (!isRecord$55(block) || block.type !== "video") continue;
34386
34418
  const attachment = videoAttachmentOf(block);
34387
34419
  if (attachment) refs.set(attachment.attachmentId, attachment);
34388
34420
  }
@@ -34397,7 +34429,7 @@ function requestVideoBytes(block) {
34397
34429
  function collectRequestVideoBytes(content, lengths) {
34398
34430
  if (!Array.isArray(content)) return;
34399
34431
  for (const block of content) {
34400
- if (!isRecord$54(block) || block.type !== "video") continue;
34432
+ if (!isRecord$55(block) || block.type !== "video") continue;
34401
34433
  const bytes = requestVideoBytes(block);
34402
34434
  if (bytes !== void 0) lengths.push(bytes);
34403
34435
  }
@@ -34441,7 +34473,7 @@ function isAbortLike(error, signal) {
34441
34473
  }
34442
34474
  /** True when the request carries any video occurrence at all. */
34443
34475
  function requestHasVideo(options) {
34444
- return options.messages.some((message) => Array.isArray(message.content) && message.content.some((block) => isRecord$54(block) && block.type === "video"));
34476
+ return options.messages.some((message) => Array.isArray(message.content) && message.content.some((block) => isRecord$55(block) && block.type === "video"));
34445
34477
  }
34446
34478
  function omittedVideoText(omit, block) {
34447
34479
  return omit("unreadable", videoBlockLabel(block));
@@ -34476,7 +34508,7 @@ function offloadOldestRequestVideos(options, maxBytes) {
34476
34508
  if (remaining.count === 0 || !Array.isArray(message.content)) return message;
34477
34509
  let replaced = false;
34478
34510
  const content = message.content.map((block) => {
34479
- if (remaining.count === 0 || !isRecord$54(block) || block.type !== "video") return block;
34511
+ if (remaining.count === 0 || !isRecord$55(block) || block.type !== "video") return block;
34480
34512
  if (requestVideoBytes(block) === void 0) return block;
34481
34513
  remaining.count -= 1;
34482
34514
  replaced = true;
@@ -34549,6 +34581,47 @@ function toolArgumentLimit(toolName) {
34549
34581
  if (toolName === "write" || toolName === "edit" || toolName === "code_run" || toolName === "run_code") return LARGE_PROGRAM_ARGUMENT_LIMIT;
34550
34582
  return DEFAULT_ARGUMENT_LIMIT;
34551
34583
  }
34584
+ function isRecord$54(value) {
34585
+ return typeof value === "object" && value !== null && !Array.isArray(value);
34586
+ }
34587
+ /**
34588
+ * Repair only a complete ask_user_question call whose optional field names carry
34589
+ * surrounding whitespace. One unambiguous source key and the expected value type
34590
+ * are required; collisions, underscore variants, and all other tools stay intact
34591
+ * so the execution guard can still reject payloads whose meaning is unclear.
34592
+ */
34593
+ function repairAskUserQuestionArgumentWhitespace(toolName, argumentText) {
34594
+ if (toolName !== "ask_user_question") return argumentText;
34595
+ let parsed;
34596
+ try {
34597
+ parsed = JSON.parse(argumentText);
34598
+ } catch {
34599
+ return argumentText;
34600
+ }
34601
+ if (!isRecord$54(parsed) || !Array.isArray(parsed.questions)) return argumentText;
34602
+ let changed = false;
34603
+ const questions = parsed.questions.map((candidate) => {
34604
+ if (!isRecord$54(candidate)) return candidate;
34605
+ let repaired;
34606
+ for (const canonical of ["header", "options"]) {
34607
+ if (Object.prototype.hasOwnProperty.call(candidate, canonical)) continue;
34608
+ const sources = Object.keys(candidate).filter((key) => key !== canonical && key.trim() === canonical);
34609
+ if (sources.length !== 1) continue;
34610
+ const source = sources[0];
34611
+ const value = candidate[source];
34612
+ if (canonical === "header" ? typeof value !== "string" : !Array.isArray(value)) continue;
34613
+ repaired ??= { ...candidate };
34614
+ delete repaired[source];
34615
+ repaired[canonical] = value;
34616
+ changed = true;
34617
+ }
34618
+ return repaired ?? candidate;
34619
+ });
34620
+ return changed ? JSON.stringify({
34621
+ ...parsed,
34622
+ questions
34623
+ }) : argumentText;
34624
+ }
34552
34625
  /** Split `header_comment`, `header_unused`, and `header___` into one family. */
34553
34626
  function keyFamily(key) {
34554
34627
  const suffix = /_(?:comment|unused)$|_+$/.exec(key);
@@ -36395,6 +36468,10 @@ function appendGuardedArguments(state, call, delta) {
36395
36468
  call.guard ??= new KimiToolArgumentGuard(call.name);
36396
36469
  throwToolGuardViolation(state, call, call.guard.observe(delta));
36397
36470
  }
36471
+ function completedToolArguments(call) {
36472
+ const argumentText = call.arguments === "" ? "{}" : call.arguments;
36473
+ return repairAskUserQuestionArgumentWhitespace(call.name, argumentText);
36474
+ }
36398
36475
  function closeToolCalls$5(state) {
36399
36476
  const out = [];
36400
36477
  for (const [wireIndex, call] of [...state.toolCalls.entries()].sort((a, b) => a[0] - b[0])) {
@@ -36403,7 +36480,7 @@ function closeToolCalls$5(state) {
36403
36480
  type: "tool-call",
36404
36481
  id: toToolCallId(state.toolCallIds.normalize(call.id)),
36405
36482
  name: call.name,
36406
- arguments: call.arguments === "" ? "{}" : call.arguments
36483
+ arguments: completedToolArguments(call)
36407
36484
  };
36408
36485
  state.blocks[call.blockIndex] = block;
36409
36486
  out.push({
@@ -36542,7 +36619,7 @@ function applyOpenAIToolDelta(entry, state) {
36542
36619
  type: "tool-call",
36543
36620
  id: toToolCallId(state.toolCallIds.normalize(call.id)),
36544
36621
  name: call.name,
36545
- arguments: call.arguments === "" ? "{}" : call.arguments
36622
+ arguments: completedToolArguments(call)
36546
36623
  };
36547
36624
  state.blocks[call.blockIndex] = closedBlock;
36548
36625
  out.push({
@@ -36740,7 +36817,7 @@ function processAnthropicStreamLine(line, state) {
36740
36817
  type: "tool-call",
36741
36818
  id: toToolCallId(state.toolCallIds.normalize(pending.id)),
36742
36819
  name: pending.name,
36743
- arguments: pending.arguments === "" ? "{}" : pending.arguments
36820
+ arguments: completedToolArguments(pending)
36744
36821
  };
36745
36822
  state.blocks[pending.blockIndex] = block;
36746
36823
  out.push({
@@ -39281,8 +39358,28 @@ var KimiCodeAdapter = class extends LlmAdapter {
39281
39358
  requestDiagnostic.wire = wire;
39282
39359
  const entry = catalog.find((model) => model.id === options.model);
39283
39360
  const images = await resolveRequestImages$2(normalized, this.options.attachments, signal, KIMI_CODE_REQUEST_IMAGE_MAX_EDGE);
39361
+ const settings = await this.settings();
39362
+ const modalities = inputModalitiesForEntry(options.model, catalog);
39363
+ /**
39364
+ * Which readable image occurrences the reference path would cover.
39365
+ *
39366
+ * Planned BEFORE the image budget: a durable image this OpenAI request will
39367
+ * cite as `ms://` carries no inline base64 bytes, exactly as in Kimi's own
39368
+ * media resolver. Nothing is uploaded here; the actual references are still
39369
+ * checked after upload so a failed upload cannot escape the inline budget.
39370
+ * Videos stay out of this early plan: their own oldest-first pass runs
39371
+ * before their bytes are read, just as it did before this change.
39372
+ */
39373
+ const plannedImages = planMediaReferences({
39374
+ wire,
39375
+ imageAccepted: modalities.includes("image"),
39376
+ videoAccepted: false,
39377
+ images,
39378
+ videos: /* @__PURE__ */ new Map()
39379
+ });
39380
+ const plannedInlineImageKeys = new Set(plannedImages.map((item) => `attachment:${item.attachmentId}`));
39284
39381
  const priorDroppedKeys = getSessionDroppedImageKeys(options.sessionId, options.sessionId === void 0 ? void 0 : sessionCacheState.read(options.sessionId)?.budgetDropped);
39285
- const stickyOffload = offloadRequestImagesWithStickyBudget(normalized, maxRequestImageBytes$1(), lowRequestImageBytes(), images, priorDroppedKeys);
39382
+ const stickyOffload = offloadRequestImagesWithStickyBudget(normalized, maxRequestImageBytes$1(), lowRequestImageBytes(), images, priorDroppedKeys, plannedInlineImageKeys);
39286
39383
  const imageTrimmed = stickyOffload.options;
39287
39384
  if (!sideChannel) markPendingImageOffload(options.sessionId, stickyOffload.newlyDroppedKeys.length);
39288
39385
  const gatedEffort = coerceThinkingEffort(options.model, mapReasoningEffort(options.reasoningEffort === void 0 || options.reasoningEffort === null ? void 0 : String(options.reasoningEffort)));
@@ -39298,8 +39395,6 @@ var KimiCodeAdapter = class extends LlmAdapter {
39298
39395
  reasoningEffort: ReasoningEffortId(gatedEffort.effort)
39299
39396
  };
39300
39397
  const videos = await resolveRequestVideos(requestOptions, this.options.videos, signal);
39301
- const settings = await this.settings();
39302
- const modalities = inputModalitiesForEntry(options.model, catalog);
39303
39398
  /**
39304
39399
  * Everything every attempt shares: the media reads and the capability gates.
39305
39400
  *
@@ -39319,13 +39414,14 @@ var KimiCodeAdapter = class extends LlmAdapter {
39319
39414
  * be sent; nothing is uploaded, and no network is touched, until that guard
39320
39415
  * has accepted the request (see the rotation loop).
39321
39416
  */
39322
- const planned = planMediaReferences({
39417
+ const plannedVideos = planMediaReferences({
39323
39418
  wire,
39324
- imageAccepted: modalities.includes("image"),
39419
+ imageAccepted: false,
39325
39420
  videoAccepted: baseMedia.videoAccepted === true,
39326
- images,
39421
+ images: /* @__PURE__ */ new Map(),
39327
39422
  videos
39328
39423
  });
39424
+ const planned = [...plannedImages, ...plannedVideos];
39329
39425
  const contextWindow = this.contextWindowFor(options.model, entry, settings.contextWindowOverrides);
39330
39426
  const requestedMax = options.maxTokens ?? maxOutputTokensFor$4(options.model, contextWindow);
39331
39427
  const inputCap = maxInputTokensForEntry(options.model, catalog);
@@ -39344,13 +39440,15 @@ var KimiCodeAdapter = class extends LlmAdapter {
39344
39440
  * references), the real reference build after the upload, and the all-inline
39345
39441
  * rebuild the missing-resource fallback re-sends.
39346
39442
  *
39347
- * Every call restarts from `boundedOptions`. That is load bearing rather than
39348
- * tidy: the inline fallback has to re-fit the inline body from scratch and
39349
- * stay inside the same ceiling instead of inheriting an omission the
39350
- * reference path made to fit a different, much smaller body.
39443
+ * Calls normally restart from `boundedOptions`; the post-upload pass may
39444
+ * supply the same options after budgeting the images that really stayed
39445
+ * inline. Re-fitting from that baseline is load bearing: the inline fallback
39446
+ * must not inherit an omission made for a different, much smaller body, and
39447
+ * its positional drop loop must not mistake non-contiguous budget omissions
39448
+ * for the oldest remaining images.
39351
39449
  */
39352
- const buildBodyWithinLimit = (media) => {
39353
- let buildOptions = boundedOptions;
39450
+ const buildBodyWithinLimit = (media, baseline = boundedOptions) => {
39451
+ let buildOptions = baseline;
39354
39452
  for (let attempt = 0;; attempt++) {
39355
39453
  const built = buildRequest(buildOptions, wire, images, void 0, media);
39356
39454
  const body = JSON.stringify(built);
@@ -39360,7 +39458,7 @@ var KimiCodeAdapter = class extends LlmAdapter {
39360
39458
  options: buildOptions
39361
39459
  };
39362
39460
  const context = () => ({
39363
- droppedImages: countOmitted(buildOptions, requestOptions, images),
39461
+ droppedImages: countOmitted(buildOptions, baseline, images),
39364
39462
  sendableImagesRemaining: requestImagePayloadLengths(buildOptions, images).length,
39365
39463
  excessBytes: bytes - bodyLimit
39366
39464
  });
@@ -39368,7 +39466,7 @@ var KimiCodeAdapter = class extends LlmAdapter {
39368
39466
  assertRequestBodyFits$1(built, carriesVideo, context(), bodyLimit);
39369
39467
  throw new Error("unreachable: assertRequestBodyFits returns or throws");
39370
39468
  }
39371
- const drop = dropOldestImagesUntilFits(buildOptions, images, bytes - bodyLimit, requestOptions);
39469
+ const drop = dropOldestImagesUntilFits(buildOptions, images, bytes - bodyLimit, baseline);
39372
39470
  if (drop.dropped === 0) {
39373
39471
  assertRequestBodyFits$1(built, carriesVideo, context(), bodyLimit);
39374
39472
  throw new Error("unreachable: assertRequestBodyFits returns or throws");
@@ -39388,6 +39486,7 @@ var KimiCodeAdapter = class extends LlmAdapter {
39388
39486
  */
39389
39487
  let measured;
39390
39488
  let sentBuild;
39489
+ let sentImageReferenceKeys;
39391
39490
  const pool = this.accountPool;
39392
39491
  const tried = /* @__PURE__ */ new Set();
39393
39492
  const cacheAffinity = sideChannel ? void 0 : await this.cacheAffinityHint(pool, requestOptions);
@@ -39449,12 +39548,18 @@ var KimiCodeAdapter = class extends LlmAdapter {
39449
39548
  accountScope,
39450
39549
  signal
39451
39550
  });
39452
- let finalBuild = uploads === void 0 ? planned.length === 0 ? measured : buildBodyWithinLimit(baseMedia) : buildBodyWithinLimit({
39551
+ const imageReferenceKeys = /* @__PURE__ */ new Set();
39552
+ if (uploads !== void 0) for (const id of uploads.imageReferences.keys()) imageReferenceKeys.add(`attachment:${id}`);
39553
+ const postUploadOffload = offloadRequestImagesWithStickyBudget(boundedOptions, maxRequestImageBytes$1(), lowRequestImageBytes(), images, stickyOffload.allDroppedKeys, imageReferenceKeys);
39554
+ const finalBaseline = postUploadOffload.options;
39555
+ if (!sideChannel) markPendingImageOffload(options.sessionId, stickyOffload.newlyDroppedKeys.length + postUploadOffload.newlyDroppedKeys.length);
39556
+ let finalBuild = uploads === void 0 ? planned.length === 0 ? measured : buildBodyWithinLimit(baseMedia, finalBaseline) : buildBodyWithinLimit({
39453
39557
  ...baseMedia,
39454
39558
  imageReferences: uploads.imageReferences,
39455
39559
  videoReferences: uploads.videoReferences
39456
- });
39560
+ }, finalBaseline);
39457
39561
  sentBuild = finalBuild;
39562
+ sentImageReferenceKeys = uploads === void 0 ? void 0 : imageReferenceKeys;
39458
39563
  let body = finalBuild.body;
39459
39564
  const post = async (payload) => {
39460
39565
  try {
@@ -39504,14 +39609,17 @@ var KimiCodeAdapter = class extends LlmAdapter {
39504
39609
  data: item.data
39505
39610
  });
39506
39611
  let inlineBuild;
39612
+ const inlineOffload = offloadRequestImagesWithStickyBudget(boundedOptions, maxRequestImageBytes$1(), lowRequestImageBytes(), images, stickyOffload.allDroppedKeys);
39613
+ if (!sideChannel) markPendingImageOffload(options.sessionId, stickyOffload.newlyDroppedKeys.length + inlineOffload.newlyDroppedKeys.length);
39507
39614
  try {
39508
- inlineBuild = buildBodyWithinLimit(baseMedia);
39615
+ inlineBuild = buildBodyWithinLimit(baseMedia, inlineOffload.options);
39509
39616
  } catch {
39510
39617
  inlineBuild = void 0;
39511
39618
  }
39512
39619
  if (inlineBuild !== void 0) {
39513
39620
  finalBuild = inlineBuild;
39514
39621
  sentBuild = inlineBuild;
39622
+ sentImageReferenceKeys = void 0;
39515
39623
  body = inlineBuild.body;
39516
39624
  response = await post(body);
39517
39625
  detail = response.ok ? "" : (await response.text().catch(() => "")).slice(0, 2e3);
@@ -39549,7 +39657,7 @@ var KimiCodeAdapter = class extends LlmAdapter {
39549
39657
  });
39550
39658
  }
39551
39659
  if (sentBuild !== void 0 && !sideChannel) {
39552
- const requestImageBytes = requestImagePayloadLengths(sentBuild.options, images).reduce((sum, bytes) => sum + bytes, 0);
39660
+ const requestImageBytes = requestInlineImageBytes(sentBuild.options, images, sentImageReferenceKeys);
39553
39661
  const trimmedKeys = new Set(collectRemainingImageKeys(imageTrimmed, images));
39554
39662
  const sentKeys = new Set(collectRemainingImageKeys(sentBuild.options, images));
39555
39663
  const bodyFitDroppedKeys = [...trimmedKeys].filter((key) => !sentKeys.has(key));
@@ -50278,7 +50386,7 @@ function createKimiToolArgumentRecoveryMessage(code) {
50278
50386
  return createUserMessage$1({
50279
50387
  content: [{
50280
50388
  type: "text",
50281
- text: repeated ? "The previous tool call was stopped because its JSON arguments contained a runaway repeated-key family. Do not resume, reuse, or repair that payload. If you still need a tool, make one fresh call with minimal valid JSON and only the exact property names in its schema. For ask_user_question, use only questions, id, question, header, options, label, description, and multi_select as applicable; never append documentation annotations or underscores to property names. If no tool call is necessary, continue with the evidence already available or explain the blocker in text." : "The previous tool call was stopped because its arguments exceeded the route byte budget. Do not resend the same payload. If the existing evidence is sufficient, finish in text. Otherwise make one fresh call with the smallest sufficient arguments; for a large file or program, use a legal smaller/chunked approach instead of repeating the oversized content."
50389
+ text: repeated ? "The previous tool call was stopped because its JSON arguments contained a runaway repeated-key family. Do not resume, reuse, or repair that payload. If you still need a tool, make one fresh call with minimal valid JSON and only the exact property names in its schema. For ask_user_question, use only questions, id, question, header, options, label, description, and multi_select as applicable. Property names are case-sensitive and must not carry surrounding whitespace, documentation annotations, or appended underscores. A minimal choices call is {\"questions\":[{\"id\":\"choice\",\"question\":\"Which choice?\",\"options\":[{\"label\":\"A\"}]}]}. If no tool call is necessary, continue with the evidence already available or explain the blocker in text." : "The previous tool call was stopped because its arguments exceeded the route byte budget. Do not resend the same payload. If the existing evidence is sufficient, finish in text. Otherwise make one fresh call with the smallest sufficient arguments; for a large file or program, use a legal smaller/chunked approach instead of repeating the oversized content."
50282
50390
  }],
50283
50391
  source: {
50284
50392
  kind: PLUGIN_MESSAGE_SOURCE_KIND,
@@ -95462,6 +95570,7 @@ const DISPATCH_PRESET = {
95462
95570
 
95463
95571
  [Coordinator Identity] You are the Lead & Dispatch Agent: converge requirements, plan architecture, select R1 topology (Lead-Core / Hybrid / Fan-out), orchestrate subagents where ROI is positive, and own final acceptance.
95464
95572
  [Execution Pipeline] R0 Triage -> (L2) R-G Interview -> R9 Plan -> R1 Topology -> (if delegating: R2 Routing -> R5 Brief -> R-W Wait) -> R6 Acceptance.
95573
+ [Dispatch Native Tool Whitelist] Top-level: only code_run, cache_warmup_result, dispatch_ledger, progress_update, and structured_output. Every task tool—including win_bash—is program-only: use await tools.<name>(...) inside code_run, never top-level. "One call" = ONE code_run with exactly one sub-call; approval = ONE code_run containing only tools.exit_plan_mode(...).
95465
95574
 
95466
95575
  [Agent Teams Board] A current harness adds exactly one Agent Teams surface beside this mode: the shared task board (team_task_create and its list/get/update siblings). It is bookkeeping, not a second dispatcher. The board tools stay declared whether or not the board is on - frozen declaration, not availability - so confirm with team_task_list before relying on it. When it is on, the dispatch ledger stays the dispatch authority and R5 briefs stay the task contract; publish cross-agent dependencies (blocked_by) and write scopes on one team task per brief, claimed and completed by the child that owns it; never start work because a task is ready, and never reassign a task to skip R6.
95467
95576
 
@@ -95476,7 +95585,7 @@ When in doubt, clarify before escalating; if complexity grows mid-task, stop, re
95476
95585
  ## R-G · Clarification Interview (L2 Only, Always Before Planning)
95477
95586
  - G1 Design Tree: Model requirements as a dependency tree of decisions; never list flat questions.
95478
95587
  - G2 Frontier & Rounds: Ask the entire current frontier (decisions whose prerequisites are settled) in one round, wait for answers, recompute the frontier, and repeat. Never ask one question per round, never ask dependent questions together.
95479
- - G3 Execution via Tool: Submit each round in a single ask_user_question call with stable ids, concise headers, and your recommended option first marked "(Recommended)", formatted as "Q1 — Title / Question body / Recommended answer". The same rule covers every decision stop outside the interview; see R-W.
95588
+ - G3 Execution via Tool: Submit each round in ONE code_run program that returns exactly one tools.ask_user_question(...) sub-call with stable ids, concise headers, and your recommended option first marked "(Recommended)", formatted as "Q1 — Title / Question body / Recommended answer". The same rule covers every decision stop outside the interview; see R-W. Copy argument property names verbatim from the schema: Q1/G4 are rule ids, never argument-key suffixes.
95480
95589
  - G4 Facts Are Yours, Decisions Are the User's: Never ask the user for repository facts verifiable by reading code or searching files; inspect read-only yourself or dispatch a read-only subagent per R2 (subagent model routes are provided directly by list_subagent_models) without blocking unrelated frontier questions. The same holds for any technical, naming, layout, or styling choice that an established reference in the repository or in AGENTS.md already settles: treat it as a repository fact (target_basis: existing-standard), follow the existing standard, and do not ask the user. Reserve ask_user_question strictly for unsettled product or design decisions with no established precedent.
95481
95590
  - G5 Convergence: End the interview only when the frontier is empty and the user explicitly confirms shared understanding.
95482
95591
  - G6 Prohibited: Answering your own questions, making product/design decisions for the user, skipping the interview, or treating a casual remark as full sign-off.
@@ -95505,19 +95614,19 @@ A subagent has full authority to plan, execute, and self-verify within its assig
95505
95614
  Every task brief covers six elements: Goal / Boundary (which files or modules may be touched) / Constraints / Limits (see below) / Acceptance Criteria / Required Evidence to Report.
95506
95615
  - [Compact Delta Brief] Standing default limits and the report schema already live in [Role Identification], so use a Compact Delta Brief by default: state Goal, original file/line Source Pointers (do not paraphrase code into long prose), Module-Interface Boundary, Constraints, Acceptance Criteria, and Required Evidence, and omit repeating standing limits unless overriding them.
95507
95616
  - [Limits] When overriding any standing limit, write one line per limit spelling out four things: **what it bounds, in what unit, the cap, and whether it accumulates**. Write explicit caps ("at most 3 attempts", "edits at most 5 files", "test runs: unlimited"), never ranges ("2–5 files"); where an override dimension is left unstated, silence is read as a limit of zero, and a quota that resets per cycle is lost, not banked.
95508
- - Do not ask the child to restate your rules back as a correctness check; if a limit is genuinely unclear, instruct the child to spend one minimal tool call to verify it. Dispatch independent tasks concurrently in one message (native calls; use code_run Promise.all for batch filter/MCP) only after the interview has converged.
95617
+ - Do not ask the child to restate your rules back as a correctness check; if a limit is genuinely unclear, instruct the child to spend one minimal tool call to verify it. Dispatch independent tasks concurrently through code_run Promise.all only after the interview has converged.
95509
95618
 
95510
95619
  ## R6 · Review & Acceptance
95511
95620
  Two layers: subagent self-check -> your independent review (reading diffs, running tests, checking each criterion). The completion notification is a post-hoc signal: it tells you a child stopped, not that the work passed.
95512
95621
  - 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), not in your memory. Only after the third run fails, transition to R8 Fallback.
95513
95622
  - [Non-Penalized hand_back] A subagent that stops cleanly before mutating any out-of-boundary file and reports status: hand_back with a valid hand_back_reason is a scope routing event, not an execution failure, and does not increment the brief’s 3-run failure counter. When re-scoping or answering a child’s hand_back or blocked report, prefer continuing the existing child with send_message({ agent_id }) over spawning a fresh subagent to preserve its warm prefix cache.
95514
- - [Noticed but not handled] Every defect found in review: the defect goes back out on a re-dispatch with evidence or go to the user via ask_user_question (R-W); on Lead-Core/Hybrid core, fix and re-verify before delivery. Writing it into the delivery summary and shipping anyway is not an available outcome.
95623
+ - [Noticed but not handled] Every defect found in review: the defect goes back out on a re-dispatch with evidence or go to the user via tools.ask_user_question inside code_run (R-W); on Lead-Core/Hybrid core, fix and re-verify before delivery. Writing it into the delivery summary and shipping anyway is not an available outcome.
95515
95624
  - [UI Visual Evidence Gate] For any task or subtask that changes visible UI or GUI layout, styling, or components, acceptance requires both Before and After visual evidence—screenshots or live DOM/rendered captures—taken under the same scenario, viewport, and theme. After-only evidence fails R6 review.
95516
95625
 
95517
95626
  ## R-W · Turn Boundary (Waiting / Goals / Questions)
95518
95627
  - [Waiting for Subagents] End your turn and let the subagent completion notification wake you. Treat it as "there is now something to review", never as "this passed". Never run sleep, polling loops, watch, or placeholder long commands to wait; only call job_output({ wait: true }) when genuinely blocked on an immediate collection. State who was dispatched, what you are waiting for, and what you will do next before ending the turn.
95519
95628
  - [Goals] Do not proactively create goals: never call create_goal or /goal unless the user asks; track tasks in todo_write.
95520
- - [Questions] Whenever a decision is missing, hand the question out with a single ask_user_question call. Only two exceptions: plan-mode approval still goes through exit_plan_mode, and a finished task asks nothing.
95629
+ - [Questions] Whenever a decision is missing, hand the question out with ONE code_run program containing exactly one tools.ask_user_question(...) sub-call. Only two exceptions: plan-mode approval still goes through tools.exit_plan_mode inside code_run, and a finished task asks nothing.
95521
95630
 
95522
95631
  ## R7 · Documentation
95523
95632
  Maintain the task list (in todo_write, not create_goal; see R-W), decision log, and interview conclusions; Each task item carries its own run count.
@@ -95528,8 +95637,8 @@ Maintain the task list (in todo_write, not create_goal; see R-W), decision log,
95528
95637
  Fallback is a task-scoped, non-session-wide exception for delegated briefs: it covers only the single task that triggered it. Outside planned direct execution (L0/L1, R1 Lead-Core, or Hybrid core), execute a task yourself only on evidence of: subagent tools unmounted (R2 [State: Unmounted]—An unmounted tool is the only routing condition that permits fallback); non-delegable task; or the same task brief has still not passed review after its third run under R6. Fix trigger conditions on hard rejections (on active child limit -> wait and re-dispatch; on subagent model selection -> pass an explicit authorized route). When the next task begins, always return to R0 to triage anew.
95529
95638
 
95530
95639
  ## R9 · Plan Pipeline (Converged Interview -> Plan Mode -> Plan -> Approval)
95531
- - Trigger: only for L2 once R-G has converged. Call enter_plan_mode immediately once that holds, as the sole action of that step. Read-only exploration and the decision-complete plan belong to the next turn, and exit_plan_mode must be the sole and final tool call of the turn that submits the plan.
95532
- - Rejection & Abandon: on "Keep planning", revise and resubmit via exit_plan_mode; call leave_plan_mode only when the user explicitly says no plan is wanted. When enter_plan_mode is absent, the degraded path is one ask_user_question asking the user to enter /plan.
95640
+ - Trigger: only for L2 once R-G has converged. Call tools.enter_plan_mode inside ONE code_run immediately once that holds, as the sole top-level action of that step. Read-only exploration and the decision-complete plan belong to the next turn, and ONE code_run containing only tools.exit_plan_mode must be the sole and final top-level tool call of the turn that submits the plan.
95641
+ - Rejection & Abandon: on "Keep planning", revise and resubmit via tools.exit_plan_mode inside code_run; call tools.leave_plan_mode inside code_run only when the user explicitly says no plan is wanted. When enter_plan_mode is absent, the degraded path is ONE code_run program containing exactly one tools.ask_user_question(...) sub-call asking the user to enter /plan.
95533
95642
  - Subagent: where the host exposes the live root set (agents.roots()), a call made by a live child is rejected with DELEGATED_CALLER, while an older generation cannot determine roots at all and the bridge lets the call through. Never rely on that rejection: it carries the open decision, including any request to enter Plan Mode, back to its dispatcher.
95534
95643
 
95535
95644
  ## Anti-Patterns (Any Occurrence Is a Violation)
@@ -95537,7 +95646,7 @@ Fallback is a task-scoped, non-session-wide exception for delegated briefs: it c
95537
95646
  2. Switching to teammate vocabulary to keep orchestrating, or Treating the team task board as a substitute for R1 topology, R2 routing, R5 briefs, R6 acceptance, or R-W waiting (R1, R6).
95538
95647
  3. Omitting provider/model under [State: Listed], Second-guessing list_subagent_models output by hunting through local config or source files just to check which subagent models are allowed, or Reporting a route as "authorized", or claiming per-task routing is in force, when the session recorded no allowlist (R2).
95539
95648
  4. Writing a task brief with a range where a cap belongs ("2–5 files", "a few attempts"), or Asking a subagent to restate its rules as a correctness check (R0, R5).
95540
- 5. Running sleep, polling loops, or placeholder long commands to wait, Proactively creating a goal at the start of a task, or Ending with a paragraph of prose to wait for user sign-off instead of calling ask_user_question (R-W).
95649
+ 5. Running sleep, polling loops, or placeholder long commands to wait, Proactively creating a goal at the start of a task, or Ending with a paragraph of prose to wait for user sign-off instead of asking through tools.ask_user_question inside code_run (R-W).
95541
95650
  6. Directly editing a subagent's module, declaring completion without verification, or Shipping a defect you already named in the review, on the grounds that it is recorded in the summary (R6).
95542
95651
  7. Carrying a one-off fallback forward as the default for the rest of the session, or Using a tool hard-rejection as a fallback excuse instead of fixing its trigger condition (R8).
95543
95652
  8. 23. Asking the user about an implementation detail an existing-standard in the repository already settles; 24. Penalizing a clean status: hand_back scope escalation as a failed run, or spawning a cold replacement subagent when send_message can continue the warm child session; 25. Accepting a visible UI change without Before & After comparison evidence (R-G, R6).
@@ -95596,13 +95705,13 @@ Fallback is a task-scoped, non-session-wide exception for delegated briefs: it c
95596
95705
  config: [{
95597
95706
  id: "plan-mode",
95598
95707
  name: "@eddyskywalker/dsh-chatgpt-subscription/plan-mode",
95599
- config: { section: `[Plan Mode] Plan Mode is active. Remain in Plan Mode until a plan is approved via exit_plan_mode or the user manually changes the session mode: treat every instruction to "implement" or "modify" as a request to plan the implementation, not to execute it. Conversational approval in chat (including answers to your questions) confirms a design decision rather than approving the plan and never exits Plan Mode; fold confirmed decisions into the plan and submit via exit_plan_mode.
95708
+ config: { section: `[Plan Mode] Plan Mode is active. Remain in Plan Mode until a plan is approved via exit_plan_mode or the user manually changes the session mode: treat every instruction to "implement" or "modify" as a request to plan the implementation, not to execute it. Conversational approval in chat (including answers to your questions) confirms a design decision rather than approving the plan and never exits Plan Mode; fold confirmed decisions into the plan and submit via tools.exit_plan_mode inside code_run.
95600
95709
 
95601
- [Read-Only Exploration & Clarification Interview] Inspect the repository first using non-mutating reads, searches, and static checks, preferring existing functions, utilities, and patterns; never edit or write files, mutate config, run formatters/codegen that rewrite tracked files, commit, or otherwise enact the plan. To verify repository facts (such as where code lives or how current behavior works), explore read-only yourself or dispatch read-only subagents per R2 (using the routes returned directly by list_subagent_models) without blocking unrelated frontier questions. Before drafting the plan, settle requirements with the user per R0 and R-G: for L2 tasks, work the R-G design tree in rounds—ask the entire current frontier in one ask_user_question call (numbered, titled, with your recommended answer marked first), wait for the answers, and recompute the frontier until it is empty (every branch visited, nothing left silently assumed) and the user explicitly confirms shared understanding; for L0/L1 tasks, keep the interview to at most 2 questions, the ones that actually change the outcome. When a technical, naming, layout, or styling choice can be derived from an established reference in the repository or in AGENTS.md (target_basis: existing-standard), treat it as a repository fact: follow the existing standard and do not ask the user; reserve ask_user_question for unsettled product or design decisions with no established precedent.
95710
+ [Read-Only Exploration & Clarification Interview] Inspect the repository first using non-mutating reads, searches, and static checks, preferring existing functions, utilities, and patterns; never edit or write files, mutate config, run formatters/codegen that rewrite tracked files, commit, or otherwise enact the plan. To verify repository facts (such as where code lives or how current behavior works), explore read-only yourself or dispatch read-only subagents per R2 (using the routes returned directly by list_subagent_models) without blocking unrelated frontier questions. Before drafting the plan, settle requirements with the user per R0 and R-G: for L2 tasks, work the R-G design tree in rounds—ask the entire current frontier in ONE code_run program containing exactly one tools.ask_user_question(...) sub-call (numbered, titled, with your recommended answer marked first), wait for the answers, and recompute the frontier until it is empty (every branch visited, nothing left silently assumed) and the user explicitly confirms shared understanding; for L0/L1 tasks, keep the interview to at most 2 questions, the ones that actually change the outcome. When a technical, naming, layout, or styling choice can be derived from an established reference in the repository or in AGENTS.md (target_basis: existing-standard), treat it as a repository fact: follow the existing standard and do not ask the user; reserve ask_user_question for unsettled product or design decisions with no established precedent.
95602
95711
 
95603
95712
  [Plan Completeness] Make the plan decision-complete: state the goal, success criteria, and R1 execution topology (Lead-Core, Hybrid, or Fan-out with subtask boundaries); group implementation changes by subsystem; specify public API, schema, and data-flow changes; and cover edge cases, failure modes, test strategy, acceptance criteria, and explicit assumptions. Keep it concise enough to scan quickly while detailed enough that an executor or subagent can implement it without making further design decisions. When the plan changes visible UI or GUI layout, styling, or components, it names the Before and After visual evidence acceptance will require (same scenario, viewport, and theme); After-only evidence does not pass review.
95604
95713
 
95605
- [Plan Approval] When ready, call exit_plan_mode with the complete plan Markdown starting with a # Title heading, making exit_plan_mode the sole and final tool call of that turn: implementation or dispatch happens only in subsequent turns after approval. Never paste the final plan into a normal chat response or ask "Should I proceed?" in prose or via ask_user_question. If the user rejects the plan, fold in their feedback and resubmit via exit_plan_mode; if the approval channel is unavailable or aborted, stay in Plan Mode and ask the user to switch modes manually—never start implementing on your own.` }
95714
+ [Plan Approval] When ready, make ONE code_run program whose only sub-call is tools.exit_plan_mode with the complete plan Markdown starting with a # Title heading; that code_run is the sole and final top-level tool call of that turn: implementation or dispatch happens only in subsequent turns after approval. Never paste the final plan into a normal chat response or ask "Should I proceed?" in prose or via tools.ask_user_question inside code_run. If the user rejects the plan, fold in their feedback and resubmit via tools.exit_plan_mode inside code_run; if the approval channel is unavailable or aborted, stay in Plan Mode and ask the user to switch modes manually—never start implementing on your own.` }
95606
95715
  }, {
95607
95716
  id: "plan-mode-pipeline",
95608
95717
  name: "@eddyskywalker/dsh-chatgpt-subscription/plan-mode-pipeline"
@@ -95732,7 +95841,16 @@ Fallback is a task-scoped, non-session-wide exception for delegated briefs: it c
95732
95841
  },
95733
95842
  {
95734
95843
  id: "code-mode",
95735
- name: CODEMODE_PACKAGE
95844
+ name: CODEMODE_PACKAGE,
95845
+ config: {
95846
+ nativeToolsOnly: true,
95847
+ nativeTools: [
95848
+ "cache_warmup_result",
95849
+ "dispatch_ledger",
95850
+ "progress_update",
95851
+ "structured_output"
95852
+ ]
95853
+ }
95736
95854
  },
95737
95855
  {
95738
95856
  id: "present",
@@ -106481,6 +106599,7 @@ const Config = z$1.object({
106481
106599
  planModePipeline: z$1.boolean().default(true).volatile().description("启用计划模式管线:允许调度模式在澄清访谈收敛后用 enter_plan_mode 进入计划模式,放弃规划时用 leave_plan_mode 退出。"),
106482
106600
  dispatchExecutionGuard: z$1.boolean().default(true).volatile().description("启用调度执行守卫:在执行期拦截子代理越权调用主控专用工具,并拦截等待子代理期间的纯 sleep 空等命令;不修改工具声明面,零损耗保护 Kimi 缓存。"),
106483
106601
  toolRunawayGuard: z$1.boolean().default(true).volatile().description("启用工具失控治理:重复调用同一工具与参数时分级提醒;Kimi 保留第 12 次强停,其他线路只提醒。"),
106602
+ mediaTools: z$1.boolean().default(true).volatile().description("注册图片/视频工具:Codex/Antigravity 生图、Kimi 视频挂载、MiniMax 视频生成与理解;默认开启。修改后重载插件或重启 DSH,Kimi 既有会话在工具表变化后会重建一次前缀缓存。"),
106484
106603
  teamPolicyCacheGuard: z$1.boolean().default(true).volatile().description("把内置 Agent Teams 的 team:policy 段从 system prompt 摘掉,改为开关切换时以尾部用户消息投递一次,避免中途开团队协作时刷掉整段前缀缓存;默认开启。"),
106485
106604
  cacheWarmup: z$1.boolean().default(true).volatile().description(CACHE_WARMUP_SETTING_DESCRIPTION),
106486
106605
  cacheWarmupProviders: z$1.array(z$1.string()).default(CONTROLLED_PROVIDERS).volatile().description("允许产生新结果预览的线路;默认覆盖全部受控线路,空数组表示关闭所有新投影。"),
@@ -107254,13 +107373,14 @@ function apply(ctx, pluginConfig = {}) {
107254
107373
  ]);
107255
107374
  const disposeUpdateRoutes = registerUpdateRoutes(ctx, { fetchFn: proxyFetch });
107256
107375
  const disposeAdapter = ctx.llm.registerAdapter([PROVIDER_ID$13], adapter);
107257
- const disposeImageTool = ctx.tools.register(createCodexImageTool(oauth, ctx.attachments, { fetchFn: proxyFetch }));
107258
- const disposeAntigravityImageTool = ctx.tools.register(createAntigravityImageTool(antigravityAccountPool, antigravityStore, ctx.attachments, {
107376
+ const mediaToolsEnabled = pluginConfig.mediaTools?.get() !== false;
107377
+ const disposeImageTool = mediaToolsEnabled ? ctx.tools.register(createCodexImageTool(oauth, ctx.attachments, { fetchFn: proxyFetch })) : () => void 0;
107378
+ const disposeAntigravityImageTool = mediaToolsEnabled ? ctx.tools.register(createAntigravityImageTool(antigravityAccountPool, antigravityStore, ctx.attachments, {
107259
107379
  fetchFn: antigravityProxyFetch,
107260
107380
  isEnabled: () => antigravityPreferences.status().enabled !== false
107261
- }));
107262
- const disposeVideoTool = ctx.tools.register(createKimiVideoTool(ctx, { fetchFn: proxyFetch }));
107263
- const minimaxMediaToolsEnabled = minimaxCodePreferences.status().enabled;
107381
+ })) : () => void 0;
107382
+ const disposeVideoTool = mediaToolsEnabled ? ctx.tools.register(createKimiVideoTool(ctx, { fetchFn: proxyFetch })) : () => void 0;
107383
+ const minimaxMediaToolsEnabled = mediaToolsEnabled && minimaxCodePreferences.status().enabled;
107264
107384
  const disposeMinimaxUnderstandVideoTool = minimaxMediaToolsEnabled ? ctx.tools.register(createMinimaxUnderstandVideoTool(ctx, {
107265
107385
  fetchFn: proxyFetch,
107266
107386
  pool: minimaxCodeAccountPool