@eddyskywalker/dsh-chatgpt-subscription 0.66.0 → 0.66.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/lib/client.js +137 -9
- package/lib/client.js.map +1 -1
- package/lib/index.js +753 -97
- package/lib/types/client/antigravity/styles.d.ts.map +1 -1
- package/lib/types/client/glm-coding-plan/styles.d.ts.map +1 -1
- package/lib/types/client/kimi-code/KimiCodeSection.d.ts.map +1 -1
- package/lib/types/client/kimi-code/locales.d.ts +44 -2
- package/lib/types/client/kimi-code/locales.d.ts.map +1 -1
- package/lib/types/client/kimi-code/styles.d.ts.map +1 -1
- package/lib/types/client/locales-ru/kimi-code.d.ts.map +1 -1
- package/lib/types/client/workbuddy/styles.d.ts.map +1 -1
- package/lib/types/compat.d.ts +1 -1
- package/lib/types/host/cache-warmup/contracts.d.ts +1 -1
- package/lib/types/host/cache-warmup/contracts.d.ts.map +1 -1
- package/lib/types/host/cache-warmup/install.d.ts.map +1 -1
- package/lib/types/host/cache-warmup/projection.d.ts.map +1 -1
- package/lib/types/host/common/request-images.d.ts +13 -1
- package/lib/types/host/common/request-images.d.ts.map +1 -1
- package/lib/types/host/glm-coding-plan/adapter.d.ts +11 -0
- package/lib/types/host/glm-coding-plan/adapter.d.ts.map +1 -1
- package/lib/types/host/kimi-code/adapter.d.ts +4 -10
- package/lib/types/host/kimi-code/adapter.d.ts.map +1 -1
- package/lib/types/host/kimi-code/mapper.d.ts +11 -1
- package/lib/types/host/kimi-code/mapper.d.ts.map +1 -1
- package/lib/types/host/kimi-code/routes.d.ts.map +1 -1
- package/lib/types/host/kimi-code/session-cache-state.d.ts +19 -2
- package/lib/types/host/kimi-code/session-cache-state.d.ts.map +1 -1
- package/lib/types/host/kimi-code/tool-argument-guard.d.ts +36 -0
- package/lib/types/host/kimi-code/tool-argument-guard.d.ts.map +1 -0
- package/lib/types/host/kimi-code/tool-argument-recovery.d.ts +16 -0
- package/lib/types/host/kimi-code/tool-argument-recovery.d.ts.map +1 -0
- package/lib/types/index.d.ts.map +1 -1
- package/lib/types/shared/kimi-code-contracts.d.ts +63 -0
- package/lib/types/shared/kimi-code-contracts.d.ts.map +1 -1
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -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.
|
|
812
|
+
const PLUGIN_VERSION = "0.66.2";
|
|
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`;
|
|
@@ -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
|
|
@@ -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
|
-
|
|
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;
|
|
@@ -15092,7 +15112,7 @@ async function* parseResponsesStream(response, signal, _legacyHiddenSandboxContr
|
|
|
15092
15112
|
const tools = /* @__PURE__ */ new Map();
|
|
15093
15113
|
const toolFor = (event, item) => {
|
|
15094
15114
|
const itemId = string(event.item_id) ?? string(item?.id);
|
|
15095
|
-
const outputIndex = number(event.output_index);
|
|
15115
|
+
const outputIndex = number$1(event.output_index);
|
|
15096
15116
|
const key = itemId ?? (outputIndex === void 0 ? `tool-${tools.size}` : `index-${outputIndex}`);
|
|
15097
15117
|
let tool = tools.get(key);
|
|
15098
15118
|
if (tool === void 0) {
|
|
@@ -15421,12 +15441,12 @@ function visibleReasoningDelta(delta, currentVisibleChars, alreadyTruncated) {
|
|
|
15421
15441
|
*/
|
|
15422
15442
|
function mapUsage$2(value) {
|
|
15423
15443
|
if (value === null) return null;
|
|
15424
|
-
const totalInput = number(value.input_tokens) ?? 0;
|
|
15425
|
-
const outputTokens = number(value.output_tokens) ?? 0;
|
|
15444
|
+
const totalInput = number$1(value.input_tokens) ?? 0;
|
|
15445
|
+
const outputTokens = number$1(value.output_tokens) ?? 0;
|
|
15426
15446
|
const details = record$3(value.input_tokens_details);
|
|
15427
|
-
const cached = number(details?.cached_tokens);
|
|
15428
|
-
const written = number(details?.cache_write_tokens);
|
|
15429
|
-
const reasoning = number(record$3(value.output_tokens_details)?.reasoning_tokens);
|
|
15447
|
+
const cached = number$1(details?.cached_tokens);
|
|
15448
|
+
const written = number$1(details?.cache_write_tokens);
|
|
15449
|
+
const reasoning = number$1(record$3(value.output_tokens_details)?.reasoning_tokens);
|
|
15430
15450
|
return {
|
|
15431
15451
|
inputTokens: Math.max(0, totalInput - (cached ?? 0) - (written ?? 0)),
|
|
15432
15452
|
outputTokens,
|
|
@@ -15481,7 +15501,7 @@ function record$3(value) {
|
|
|
15481
15501
|
function string(value) {
|
|
15482
15502
|
return typeof value === "string" ? value : void 0;
|
|
15483
15503
|
}
|
|
15484
|
-
function number(value) {
|
|
15504
|
+
function number$1(value) {
|
|
15485
15505
|
const parsed = Number(value);
|
|
15486
15506
|
return Number.isFinite(parsed) ? parsed : void 0;
|
|
15487
15507
|
}
|
|
@@ -16579,8 +16599,8 @@ function parseCodexUsage(value) {
|
|
|
16579
16599
|
for (const [index, value] of additional.entries()) {
|
|
16580
16600
|
const limit = record$2(value);
|
|
16581
16601
|
if (limit === null) continue;
|
|
16582
|
-
const idSource = text$
|
|
16583
|
-
addBucket(buckets, usedIds, uniqueId(slug(idSource), usedIds), readableLimitName(text$
|
|
16602
|
+
const idSource = text$5(limit.limit_name) ?? text$5(limit.metered_feature) ?? `additional-${index + 1}`;
|
|
16603
|
+
addBucket(buckets, usedIds, uniqueId(slug(idSource), usedIds), readableLimitName(text$5(limit.limit_name) ?? text$5(limit.metered_feature) ?? idSource), planType, limit.rate_limit);
|
|
16584
16604
|
}
|
|
16585
16605
|
return {
|
|
16586
16606
|
buckets,
|
|
@@ -16665,7 +16685,7 @@ function parseResetCredits(value) {
|
|
|
16665
16685
|
availableCreditIds: []
|
|
16666
16686
|
};
|
|
16667
16687
|
const available = (Array.isArray(data.credits) ? data.credits : []).map(record$2).filter((credit) => credit !== null && credit.status === "available").map((credit) => ({
|
|
16668
|
-
id: text$
|
|
16688
|
+
id: text$5(credit.id),
|
|
16669
16689
|
expiresAt: timestamp(credit.expires_at)
|
|
16670
16690
|
})).filter((credit) => credit.id !== null).sort((left, right) => (left.expiresAt ?? Number.MAX_SAFE_INTEGER) - (right.expiresAt ?? Number.MAX_SAFE_INTEGER));
|
|
16671
16691
|
const reported = numeric(data.available_count);
|
|
@@ -16699,7 +16719,7 @@ function decimalText(value) {
|
|
|
16699
16719
|
const trimmed = value.trim();
|
|
16700
16720
|
return trimmed !== "" ? trimmed : null;
|
|
16701
16721
|
}
|
|
16702
|
-
function text$
|
|
16722
|
+
function text$5(value) {
|
|
16703
16723
|
return typeof value === "string" && value.trim() !== "" ? value.trim() : null;
|
|
16704
16724
|
}
|
|
16705
16725
|
function slug(value) {
|
|
@@ -24922,7 +24942,7 @@ function classifyCommandCodeFailure(status, detail) {
|
|
|
24922
24942
|
};
|
|
24923
24943
|
}
|
|
24924
24944
|
/** Cooldown one rate-limited key takes when the provider states no delay. */
|
|
24925
|
-
const POOL_COOLDOWN_MS$
|
|
24945
|
+
const POOL_COOLDOWN_MS$6 = 15 * 6e4;
|
|
24926
24946
|
var CommandCodeAdapter = class extends LlmAdapter {
|
|
24927
24947
|
store;
|
|
24928
24948
|
modelSettings;
|
|
@@ -25110,7 +25130,7 @@ var CommandCodeAdapter = class extends LlmAdapter {
|
|
|
25110
25130
|
}
|
|
25111
25131
|
if (response.status === 429) {
|
|
25112
25132
|
const after = retryAfterMs$1(response.headers);
|
|
25113
|
-
await pool.markCooldown(accountId, after ?? POOL_COOLDOWN_MS$
|
|
25133
|
+
await pool.markCooldown(accountId, after ?? POOL_COOLDOWN_MS$6, `${PROVIDER_NAME$10} 429`).catch(() => void 0);
|
|
25114
25134
|
if (await pool.hasAnotherAvailableAccount(tried)) continue;
|
|
25115
25135
|
break;
|
|
25116
25136
|
}
|
|
@@ -25185,7 +25205,7 @@ var CommandCodeAdapter = class extends LlmAdapter {
|
|
|
25185
25205
|
const reclassified = reclassifyInBandStreamError(error, inBand);
|
|
25186
25206
|
if (reclassified.code === "RATE_LIMIT" && pool !== null && accountId !== void 0) {
|
|
25187
25207
|
const after = retryAfterMs$1(response.headers);
|
|
25188
|
-
await pool.markCooldown(accountId, after ?? POOL_COOLDOWN_MS$
|
|
25208
|
+
await pool.markCooldown(accountId, after ?? POOL_COOLDOWN_MS$6, `${PROVIDER_NAME$10} in-stream 429`).catch(() => void 0);
|
|
25189
25209
|
}
|
|
25190
25210
|
throw reclassified;
|
|
25191
25211
|
}
|
|
@@ -26371,7 +26391,7 @@ const STREAM_IDLE_TIMEOUT_MS$5 = 3e5;
|
|
|
26371
26391
|
* A 429 here is a real quota or rate limit, not a blip, so the account is parked
|
|
26372
26392
|
* for long enough that the next request goes to a different one.
|
|
26373
26393
|
*/
|
|
26374
|
-
const POOL_COOLDOWN_MS$
|
|
26394
|
+
const POOL_COOLDOWN_MS$5 = 15 * 6e4;
|
|
26375
26395
|
/**
|
|
26376
26396
|
* NO fallback model names.
|
|
26377
26397
|
*
|
|
@@ -27766,7 +27786,7 @@ var OllamaAdapter = class extends LlmAdapter {
|
|
|
27766
27786
|
break;
|
|
27767
27787
|
}
|
|
27768
27788
|
if (lastStatus === 429) {
|
|
27769
|
-
await pool.markCooldown(accountId, POOL_COOLDOWN_MS$
|
|
27789
|
+
await pool.markCooldown(accountId, POOL_COOLDOWN_MS$5, `${PROVIDER_NAME$9} 429`).catch(() => void 0);
|
|
27770
27790
|
if (await pool.hasAnotherAvailableAccount(tried)) continue;
|
|
27771
27791
|
break;
|
|
27772
27792
|
}
|
|
@@ -29294,7 +29314,7 @@ function consecutiveWarmupHits(reports) {
|
|
|
29294
29314
|
}
|
|
29295
29315
|
}
|
|
29296
29316
|
/** 把任意输入归一成一条用量报告;形状不对返回 undefined(绝不抛)。 */
|
|
29297
|
-
function normalizeUsage(input) {
|
|
29317
|
+
function normalizeUsage$1(input) {
|
|
29298
29318
|
if (input === null || input === void 0 || typeof input !== "object") return void 0;
|
|
29299
29319
|
const sessionId = input.sessionId;
|
|
29300
29320
|
if (typeof sessionId !== "string" || sessionId.trim() === "") return void 0;
|
|
@@ -29335,7 +29355,7 @@ function recordCacheWarmupUsage(input) {
|
|
|
29335
29355
|
let sessionId = "";
|
|
29336
29356
|
let provider;
|
|
29337
29357
|
try {
|
|
29338
|
-
const usage = normalizeUsage(input);
|
|
29358
|
+
const usage = normalizeUsage$1(input);
|
|
29339
29359
|
if (usage === void 0) return neutralState("");
|
|
29340
29360
|
sessionId = usage.sessionId;
|
|
29341
29361
|
provider = usage.provider;
|
|
@@ -30799,6 +30819,57 @@ function planMultiSectionProjection(text) {
|
|
|
30799
30819
|
sections
|
|
30800
30820
|
};
|
|
30801
30821
|
}
|
|
30822
|
+
/**
|
|
30823
|
+
* PTC 工具目录:保留完整的 namespace/name 索引,重 schema 由原文 ref 补读。
|
|
30824
|
+
*
|
|
30825
|
+
* 只认 code_tools_list / code_tools_search 的根对象形状。任意字段缺失、额外根成员
|
|
30826
|
+
* 或非 PTC 调用都回退原文,避免把业务 JSON 里的 tools 数组误当成工具发现结果。
|
|
30827
|
+
*/
|
|
30828
|
+
function planToolCatalogProjection(text, toolName) {
|
|
30829
|
+
if (!isPtcTransportName(toolName)) return void 0;
|
|
30830
|
+
const candidate = parseJsonCandidate(text);
|
|
30831
|
+
if (candidate?.kind !== "object") return void 0;
|
|
30832
|
+
const record = candidate.record;
|
|
30833
|
+
if (Object.keys(record).some((key) => key !== "tools" && key !== "fallback")) return void 0;
|
|
30834
|
+
if (!Array.isArray(record.tools) || record.tools.length === 0) return void 0;
|
|
30835
|
+
const lines = [];
|
|
30836
|
+
for (const entry of record.tools) {
|
|
30837
|
+
if (!isPlainRecord$1(entry)) return void 0;
|
|
30838
|
+
if (typeof entry.name !== "string" || entry.name.trim() === "") return void 0;
|
|
30839
|
+
if (typeof entry.namespace !== "string" || entry.namespace.trim() === "") return void 0;
|
|
30840
|
+
if (typeof entry.description !== "string") return void 0;
|
|
30841
|
+
const name = entry.name.trim();
|
|
30842
|
+
const namespace = entry.namespace.trim();
|
|
30843
|
+
const description = entry.description.replace(/\s+/g, " ").trim();
|
|
30844
|
+
lines.push(` ${namespace}/${name}: ${clip(description, 180)}`);
|
|
30845
|
+
}
|
|
30846
|
+
const header = [`tools: ${record.tools.length} (complete name index; descriptions clipped)`];
|
|
30847
|
+
if (typeof record.fallback === "string" && record.fallback.trim() !== "") header.push("fallback: " + clip(record.fallback.replace(/\s+/g, " ").trim(), 240));
|
|
30848
|
+
return {
|
|
30849
|
+
kind: "preview",
|
|
30850
|
+
strategy: "tool-catalog",
|
|
30851
|
+
sections: [{ lines: header }, { lines }]
|
|
30852
|
+
};
|
|
30853
|
+
}
|
|
30854
|
+
/** 成功测试日志必须有明确通过汇总,且没有任何可识别的失败证据。 */
|
|
30855
|
+
function isSuccessfulTestEvidence(text, evidence) {
|
|
30856
|
+
if (evidence.failures.length > 0 || evidence.summary.length === 0) return false;
|
|
30857
|
+
if (!evidence.summary.some((line) => /\b\d+\s+passed\b/i.test(line))) return false;
|
|
30858
|
+
if (/(?:^|\s)[1-9]\d*\s+failed\b/i.test(text)) return false;
|
|
30859
|
+
const exitMatch = /(?:exit code|exited with code|process exited with code)[:=\s]+(-?\d+)/i.exec(text) ?? /\[exit code: (-?\d+)\]/i.exec(text);
|
|
30860
|
+
if (exitMatch !== null && Number(exitMatch[1]) !== 0) return false;
|
|
30861
|
+
for (const raw of text.split("\n")) {
|
|
30862
|
+
const trimmed = raw.trim();
|
|
30863
|
+
if (trimmed === "" || /^npm notice\b/i.test(trimmed)) continue;
|
|
30864
|
+
if (/^(?:PASS\b|[✓✔]|ok\s+\d+)/i.test(trimmed)) continue;
|
|
30865
|
+
if (/^(?:stdout|stderr)\s*\|/i.test(trimmed)) continue;
|
|
30866
|
+
if (/^\(node:\d+\).*Warning:/i.test(trimmed)) continue;
|
|
30867
|
+
if (/^\s*(?:0|no)\s+(?:errors?|failures?|failed)\b/i.test(trimmed)) continue;
|
|
30868
|
+
if (/\b\d+\s+passed\b/i.test(trimmed)) continue;
|
|
30869
|
+
if (SHELL_ERROR_LINE.test(trimmed)) return false;
|
|
30870
|
+
}
|
|
30871
|
+
return true;
|
|
30872
|
+
}
|
|
30802
30873
|
/** 对一段纯文本(非 JSON 文档)做投影计划判定。 */
|
|
30803
30874
|
function planPlainTextProjection(rawText, toolName) {
|
|
30804
30875
|
const text = stripAnsi(rawText);
|
|
@@ -30816,6 +30887,11 @@ function planPlainTextProjection(rawText, toolName) {
|
|
|
30816
30887
|
strategy: "test-failure",
|
|
30817
30888
|
sections: buildTestSections(test)
|
|
30818
30889
|
};
|
|
30890
|
+
if (test !== void 0 && isSuccessfulTestEvidence(text, test)) return {
|
|
30891
|
+
kind: "preview",
|
|
30892
|
+
strategy: "test-success",
|
|
30893
|
+
sections: buildTestSections(test)
|
|
30894
|
+
};
|
|
30819
30895
|
const grep = extractGrepEvidence(text);
|
|
30820
30896
|
if (grep !== void 0) return {
|
|
30821
30897
|
kind: "preview",
|
|
@@ -30886,6 +30962,10 @@ function planProjection(text, toolName, navigation, retrievalOnly, spilled = fal
|
|
|
30886
30962
|
const multiSection = planMultiSectionProjection(text);
|
|
30887
30963
|
if (multiSection !== void 0) return multiSection;
|
|
30888
30964
|
}
|
|
30965
|
+
if (isJsonDocument(text)) {
|
|
30966
|
+
const toolCatalog = planToolCatalogProjection(text, toolName);
|
|
30967
|
+
if (toolCatalog !== void 0) return toolCatalog;
|
|
30968
|
+
}
|
|
30889
30969
|
if (looksLikeContract(text)) return {
|
|
30890
30970
|
kind: "verbatim",
|
|
30891
30971
|
strategy: "verbatim-contract"
|
|
@@ -34470,6 +34550,150 @@ function videoBlockToInline(block, videos, videoAccepted, omit) {
|
|
|
34470
34550
|
} } : { omission: omit("unsupported-container", label) };
|
|
34471
34551
|
}
|
|
34472
34552
|
//#endregion
|
|
34553
|
+
//#region src/host/kimi-code/tool-argument-guard.ts
|
|
34554
|
+
const TOOL_ARGUMENT_BYTES_EXCEEDED_CODE = "KIMI_TOOL_ARGUMENT_BYTES_EXCEEDED";
|
|
34555
|
+
const TOOL_ARGUMENT_REPEATED_KEY_CODE = "KIMI_TOOL_ARGUMENT_REPEATED_KEY";
|
|
34556
|
+
/** Whether one adapter failure belongs to the recoverable argument guard. */
|
|
34557
|
+
function isKimiToolArgumentGuardCode(code) {
|
|
34558
|
+
return code === "KIMI_TOOL_ARGUMENT_BYTES_EXCEEDED" || code === "KIMI_TOOL_ARGUMENT_REPEATED_KEY";
|
|
34559
|
+
}
|
|
34560
|
+
const ASK_USER_ARGUMENT_LIMIT = 32 * 1024;
|
|
34561
|
+
const LARGE_PROGRAM_ARGUMENT_LIMIT = 1024 * 1024;
|
|
34562
|
+
const DEFAULT_ARGUMENT_LIMIT = 256 * 1024;
|
|
34563
|
+
const REPEATED_KEY_LIMIT = 8;
|
|
34564
|
+
const MAX_TRACKED_KEY_GROUPS = 64;
|
|
34565
|
+
const MAX_SCANNED_KEY_CHARS = 1024;
|
|
34566
|
+
/** Large source/file payloads need a different ceiling from coordination cards. */
|
|
34567
|
+
function toolArgumentLimit(toolName) {
|
|
34568
|
+
if (toolName === "ask_user_question") return ASK_USER_ARGUMENT_LIMIT;
|
|
34569
|
+
if (toolName === "write" || toolName === "edit" || toolName === "code_run" || toolName === "run_code") return LARGE_PROGRAM_ARGUMENT_LIMIT;
|
|
34570
|
+
return DEFAULT_ARGUMENT_LIMIT;
|
|
34571
|
+
}
|
|
34572
|
+
/** Split `header_comment`, `header_unused`, and `header___` into one family. */
|
|
34573
|
+
function keyFamily(key) {
|
|
34574
|
+
const suffix = /_(?:comment|unused)$|_+$/.exec(key);
|
|
34575
|
+
if (suffix === null || suffix.index === 0) return {
|
|
34576
|
+
stem: key,
|
|
34577
|
+
variant: false
|
|
34578
|
+
};
|
|
34579
|
+
return {
|
|
34580
|
+
stem: key.slice(0, suffix.index),
|
|
34581
|
+
variant: true
|
|
34582
|
+
};
|
|
34583
|
+
}
|
|
34584
|
+
var KimiToolArgumentGuard = class {
|
|
34585
|
+
toolName;
|
|
34586
|
+
bytes = 0;
|
|
34587
|
+
inString = false;
|
|
34588
|
+
escaped = false;
|
|
34589
|
+
afterString = false;
|
|
34590
|
+
stringRaw = "";
|
|
34591
|
+
stringTooLong = false;
|
|
34592
|
+
highSurrogate = "";
|
|
34593
|
+
keyGroups = /* @__PURE__ */ new Map();
|
|
34594
|
+
violation;
|
|
34595
|
+
constructor(toolName) {
|
|
34596
|
+
this.toolName = toolName;
|
|
34597
|
+
}
|
|
34598
|
+
observe(delta) {
|
|
34599
|
+
if (this.violation !== void 0) return this.violation;
|
|
34600
|
+
const text = this.highSurrogate + delta;
|
|
34601
|
+
this.highSurrogate = "";
|
|
34602
|
+
if (text === "") return void 0;
|
|
34603
|
+
const last = text.charCodeAt(text.length - 1);
|
|
34604
|
+
const complete = last >= 55296 && last <= 56319 ? text.slice(0, -1) : text;
|
|
34605
|
+
if (complete.length !== text.length) this.highSurrogate = text.at(-1) ?? "";
|
|
34606
|
+
this.bytes += Buffer.byteLength(complete, "utf8");
|
|
34607
|
+
if (this.bytes > toolArgumentLimit(this.toolName)) return this.fail("argument-bytes");
|
|
34608
|
+
for (const char of complete) {
|
|
34609
|
+
const violation = this.observeChar(char);
|
|
34610
|
+
if (violation !== void 0) return violation;
|
|
34611
|
+
}
|
|
34612
|
+
}
|
|
34613
|
+
/** Account for a trailing unmatched surrogate without leaving it unbudgeted. */
|
|
34614
|
+
finish() {
|
|
34615
|
+
if (this.highSurrogate !== "") {
|
|
34616
|
+
this.highSurrogate = "";
|
|
34617
|
+
this.bytes += Buffer.byteLength("\ud800", "utf8");
|
|
34618
|
+
if (this.bytes > toolArgumentLimit(this.toolName)) return this.fail("argument-bytes");
|
|
34619
|
+
}
|
|
34620
|
+
return this.violation;
|
|
34621
|
+
}
|
|
34622
|
+
fail(rule) {
|
|
34623
|
+
this.violation = {
|
|
34624
|
+
toolName: this.toolName || "unknown",
|
|
34625
|
+
rule,
|
|
34626
|
+
bytes: this.bytes
|
|
34627
|
+
};
|
|
34628
|
+
return this.violation;
|
|
34629
|
+
}
|
|
34630
|
+
observeChar(char) {
|
|
34631
|
+
if (this.inString) {
|
|
34632
|
+
if (this.escaped) {
|
|
34633
|
+
this.escaped = false;
|
|
34634
|
+
if (!this.stringTooLong) this.stringRaw += char;
|
|
34635
|
+
return;
|
|
34636
|
+
}
|
|
34637
|
+
if (char === "\\") {
|
|
34638
|
+
this.escaped = true;
|
|
34639
|
+
if (!this.stringTooLong) this.stringRaw += char;
|
|
34640
|
+
return;
|
|
34641
|
+
}
|
|
34642
|
+
if (char === "\"") {
|
|
34643
|
+
this.inString = false;
|
|
34644
|
+
this.afterString = true;
|
|
34645
|
+
return;
|
|
34646
|
+
}
|
|
34647
|
+
if (!this.stringTooLong) {
|
|
34648
|
+
this.stringRaw += char;
|
|
34649
|
+
if (this.stringRaw.length > MAX_SCANNED_KEY_CHARS) {
|
|
34650
|
+
this.stringTooLong = true;
|
|
34651
|
+
this.stringRaw = "";
|
|
34652
|
+
}
|
|
34653
|
+
}
|
|
34654
|
+
return;
|
|
34655
|
+
}
|
|
34656
|
+
if (this.afterString) {
|
|
34657
|
+
if (/\s/.test(char)) return void 0;
|
|
34658
|
+
this.afterString = false;
|
|
34659
|
+
if (char === ":") {
|
|
34660
|
+
this.observeKey();
|
|
34661
|
+
return this.violation;
|
|
34662
|
+
}
|
|
34663
|
+
this.stringRaw = "";
|
|
34664
|
+
this.stringTooLong = false;
|
|
34665
|
+
}
|
|
34666
|
+
if (char === "\"") {
|
|
34667
|
+
this.inString = true;
|
|
34668
|
+
this.escaped = false;
|
|
34669
|
+
this.stringRaw = "";
|
|
34670
|
+
this.stringTooLong = false;
|
|
34671
|
+
}
|
|
34672
|
+
}
|
|
34673
|
+
observeKey() {
|
|
34674
|
+
if (this.stringTooLong || this.stringRaw === "") return;
|
|
34675
|
+
try {
|
|
34676
|
+
const key = JSON.parse("\"" + this.stringRaw + "\"");
|
|
34677
|
+
if (typeof key !== "string" || key === "") return;
|
|
34678
|
+
const family = keyFamily(key);
|
|
34679
|
+
if (family.stem === "") return;
|
|
34680
|
+
const group = this.keyGroups.get(family.stem) ?? {
|
|
34681
|
+
count: 0,
|
|
34682
|
+
sawVariant: false
|
|
34683
|
+
};
|
|
34684
|
+
group.count += 1;
|
|
34685
|
+
group.sawVariant ||= family.variant;
|
|
34686
|
+
this.keyGroups.delete(family.stem);
|
|
34687
|
+
this.keyGroups.set(family.stem, group);
|
|
34688
|
+
while (this.keyGroups.size > MAX_TRACKED_KEY_GROUPS) {
|
|
34689
|
+
const oldest = this.keyGroups.keys().next();
|
|
34690
|
+
if (oldest.done !== true) this.keyGroups.delete(oldest.value);
|
|
34691
|
+
}
|
|
34692
|
+
if (group.sawVariant && group.count >= REPEATED_KEY_LIMIT) this.fail("repeated-key");
|
|
34693
|
+
} catch {}
|
|
34694
|
+
}
|
|
34695
|
+
};
|
|
34696
|
+
//#endregion
|
|
34473
34697
|
//#region src/host/kimi-code/mapper.ts
|
|
34474
34698
|
/**
|
|
34475
34699
|
* Provider-wire mapping for the Kimi Code coding endpoints.
|
|
@@ -36154,6 +36378,9 @@ function createStreamState$5(wire, sessionId, sideChannel = false) {
|
|
|
36154
36378
|
cacheWrite5mTokens: 0,
|
|
36155
36379
|
cacheWrite1hTokens: 0,
|
|
36156
36380
|
reasoningTokens: 0,
|
|
36381
|
+
cacheReadReported: false,
|
|
36382
|
+
cacheWriteReported: false,
|
|
36383
|
+
reasoningReported: false,
|
|
36157
36384
|
sawUsage: false,
|
|
36158
36385
|
toolCallIds: new ToolCallIdNormalizer()
|
|
36159
36386
|
};
|
|
@@ -36176,9 +36403,22 @@ function closeCurrent$5(state) {
|
|
|
36176
36403
|
block
|
|
36177
36404
|
}];
|
|
36178
36405
|
}
|
|
36406
|
+
function throwToolGuardViolation(state, call, violation) {
|
|
36407
|
+
if (violation === void 0) return;
|
|
36408
|
+
state.toolGuard = violation;
|
|
36409
|
+
const reason = violation.rule === "argument-bytes" ? `arguments exceeded the ${violation.rule} safety budget` : "arguments contained a runaway repeated-key family";
|
|
36410
|
+
throw new LlmError$1(`Kimi Code stopped tool call "${violation.toolName}": ${reason} at ${violation.bytes} bytes. The tool was not executed.`, violation.rule === "argument-bytes" ? TOOL_ARGUMENT_BYTES_EXCEEDED_CODE : TOOL_ARGUMENT_REPEATED_KEY_CODE);
|
|
36411
|
+
}
|
|
36412
|
+
function appendGuardedArguments(state, call, delta) {
|
|
36413
|
+
if (delta === "") return;
|
|
36414
|
+
call.arguments += delta;
|
|
36415
|
+
call.guard ??= new KimiToolArgumentGuard(call.name);
|
|
36416
|
+
throwToolGuardViolation(state, call, call.guard.observe(delta));
|
|
36417
|
+
}
|
|
36179
36418
|
function closeToolCalls$5(state) {
|
|
36180
36419
|
const out = [];
|
|
36181
36420
|
for (const [wireIndex, call] of [...state.toolCalls.entries()].sort((a, b) => a[0] - b[0])) {
|
|
36421
|
+
throwToolGuardViolation(state, call, call.guard?.finish());
|
|
36182
36422
|
const block = {
|
|
36183
36423
|
type: "tool-call",
|
|
36184
36424
|
id: toToolCallId(state.toolCallIds.normalize(call.id)),
|
|
@@ -36247,8 +36487,14 @@ function processOpenAIStreamLine(line, state) {
|
|
|
36247
36487
|
state.inputTokens = Math.max(0, prompt - cached - written);
|
|
36248
36488
|
state.cacheReadTokens = cached;
|
|
36249
36489
|
state.cacheWriteTokens = written;
|
|
36490
|
+
state.cacheReadReported = details !== void 0 && typeof details.cached_tokens === "number" && Number.isFinite(details.cached_tokens);
|
|
36491
|
+
state.cacheWriteReported = details !== void 0 && typeof details.cache_write_tokens === "number" && Number.isFinite(details.cache_write_tokens);
|
|
36250
36492
|
state.outputTokens = numberOr$8(usage.completion_tokens, state.outputTokens);
|
|
36251
|
-
if (isRecord$53(usage.completion_tokens_details))
|
|
36493
|
+
if (isRecord$53(usage.completion_tokens_details)) {
|
|
36494
|
+
const reasoning = usage.completion_tokens_details.reasoning_tokens;
|
|
36495
|
+
state.reasoningReported = typeof reasoning === "number" && Number.isFinite(reasoning);
|
|
36496
|
+
state.reasoningTokens = numberOr$8(reasoning, state.reasoningTokens);
|
|
36497
|
+
} else state.reasoningReported = false;
|
|
36252
36498
|
}
|
|
36253
36499
|
const choices = Array.isArray(chunk.choices) ? chunk.choices : [];
|
|
36254
36500
|
const choice = isRecord$53(choices[0]) ? choices[0] : void 0;
|
|
@@ -36352,7 +36598,7 @@ function applyOpenAIToolDelta(entry, state) {
|
|
|
36352
36598
|
if (name !== void 0 && name !== "") call.name = name;
|
|
36353
36599
|
}
|
|
36354
36600
|
const argsDelta = asString$21(fn.arguments) ?? "";
|
|
36355
|
-
|
|
36601
|
+
appendGuardedArguments(state, call, argsDelta);
|
|
36356
36602
|
if (!call.started) {
|
|
36357
36603
|
call.started = true;
|
|
36358
36604
|
state.hasToolCall = true;
|
|
@@ -36390,7 +36636,13 @@ function processAnthropicStreamLine(line, state) {
|
|
|
36390
36636
|
state.inputTokens = numberOr$8(usage.input_tokens, 0);
|
|
36391
36637
|
state.cacheReadTokens = numberOr$8(usage.cache_read_input_tokens, 0);
|
|
36392
36638
|
state.cacheWriteTokens = numberOr$8(usage.cache_creation_input_tokens, 0);
|
|
36639
|
+
state.cacheReadReported = typeof usage.cache_read_input_tokens === "number" && Number.isFinite(usage.cache_read_input_tokens);
|
|
36640
|
+
state.cacheWriteReported = typeof usage.cache_creation_input_tokens === "number" && Number.isFinite(usage.cache_creation_input_tokens);
|
|
36393
36641
|
state.outputTokens = numberOr$8(usage.output_tokens, 0);
|
|
36642
|
+
const reasoningDetails = isRecord$53(usage.output_tokens_details) ? usage.output_tokens_details : void 0;
|
|
36643
|
+
const reasoning = usage.reasoning_tokens ?? reasoningDetails?.reasoning_tokens;
|
|
36644
|
+
state.reasoningReported = typeof reasoning === "number" && Number.isFinite(reasoning);
|
|
36645
|
+
state.reasoningTokens = numberOr$8(reasoning, state.reasoningTokens);
|
|
36394
36646
|
}
|
|
36395
36647
|
const stop = message ? asString$21(message.stop_reason) : void 0;
|
|
36396
36648
|
if (stop !== void 0) state.finishReason = stop;
|
|
@@ -36454,7 +36706,7 @@ function processAnthropicStreamLine(line, state) {
|
|
|
36454
36706
|
const pending = state.toolCalls.get(contentIndex);
|
|
36455
36707
|
const partial = asString$21(delta.partial_json) ?? "";
|
|
36456
36708
|
if (pending !== void 0) {
|
|
36457
|
-
pending
|
|
36709
|
+
appendGuardedArguments(state, pending, partial);
|
|
36458
36710
|
out.push({
|
|
36459
36711
|
type: "tool-call-delta",
|
|
36460
36712
|
index: pending.blockIndex,
|
|
@@ -36502,6 +36754,7 @@ function processAnthropicStreamLine(line, state) {
|
|
|
36502
36754
|
const contentIndex = numberOr$8(event.index, 0);
|
|
36503
36755
|
const pending = state.toolCalls.get(contentIndex);
|
|
36504
36756
|
if (pending !== void 0) {
|
|
36757
|
+
throwToolGuardViolation(state, pending, pending.guard?.finish());
|
|
36505
36758
|
state.toolCalls.delete(contentIndex);
|
|
36506
36759
|
const block = {
|
|
36507
36760
|
type: "tool-call",
|
|
@@ -36528,6 +36781,12 @@ function processAnthropicStreamLine(line, state) {
|
|
|
36528
36781
|
if (usage) {
|
|
36529
36782
|
state.sawUsage = true;
|
|
36530
36783
|
state.outputTokens = numberOr$8(usage.output_tokens, state.outputTokens);
|
|
36784
|
+
const reasoningDetails = isRecord$53(usage.output_tokens_details) ? usage.output_tokens_details : void 0;
|
|
36785
|
+
const reasoning = usage.reasoning_tokens ?? reasoningDetails?.reasoning_tokens;
|
|
36786
|
+
if (typeof reasoning === "number" && Number.isFinite(reasoning)) {
|
|
36787
|
+
state.reasoningReported = true;
|
|
36788
|
+
state.reasoningTokens = reasoning;
|
|
36789
|
+
}
|
|
36531
36790
|
}
|
|
36532
36791
|
return out;
|
|
36533
36792
|
}
|
|
@@ -36971,7 +37230,7 @@ function closeStream$4(state, accountId) {
|
|
|
36971
37230
|
state.finished = true;
|
|
36972
37231
|
const out = [...closeCurrent$5(state), ...closeToolCalls$5(state)];
|
|
36973
37232
|
if (state.sawUsage) {
|
|
36974
|
-
recordCacheStats(state, state.sessionId, accountId);
|
|
37233
|
+
recordCacheStats(state, state.sessionId, accountId ?? state.accountId);
|
|
36975
37234
|
out.push({
|
|
36976
37235
|
type: "usage",
|
|
36977
37236
|
usage: tokenUsage$5(state)
|
|
@@ -37119,6 +37378,27 @@ var SessionCacheStateStore = class extends CommonSessionCacheStateStore {
|
|
|
37119
37378
|
normalizeRecord: normalizeRecord$2
|
|
37120
37379
|
});
|
|
37121
37380
|
}
|
|
37381
|
+
/** Append bounded request evidence, including a first request that failed before usage. */
|
|
37382
|
+
noteRequest(sessionId, request) {
|
|
37383
|
+
const base = this.read(sessionId) ?? {
|
|
37384
|
+
lastActiveAt: request.startedAt,
|
|
37385
|
+
totalTokens: 0,
|
|
37386
|
+
requests: 0,
|
|
37387
|
+
cachedTokens: 0,
|
|
37388
|
+
freshTokens: 0,
|
|
37389
|
+
outputTokens: 0,
|
|
37390
|
+
cacheWriteTokens: 0,
|
|
37391
|
+
cacheWrite5mTokens: 0,
|
|
37392
|
+
cacheWrite1hTokens: 0,
|
|
37393
|
+
updatedAt: request.endedAt
|
|
37394
|
+
};
|
|
37395
|
+
this.write(sessionId, {
|
|
37396
|
+
...base,
|
|
37397
|
+
lastActiveAt: Math.max(base.lastActiveAt, request.endedAt),
|
|
37398
|
+
recentRequests: [...base.recentRequests ?? [], request].slice(-20),
|
|
37399
|
+
updatedAt: request.endedAt
|
|
37400
|
+
});
|
|
37401
|
+
}
|
|
37122
37402
|
/** Update the warmup streak without creating a record for an unknown session. */
|
|
37123
37403
|
noteWarmupStreak(sessionId, consecutiveHits) {
|
|
37124
37404
|
this.update(sessionId, (existing) => {
|
|
@@ -37133,6 +37413,94 @@ var SessionCacheStateStore = class extends CommonSessionCacheStateStore {
|
|
|
37133
37413
|
});
|
|
37134
37414
|
}
|
|
37135
37415
|
};
|
|
37416
|
+
function optionalText(value, maxLength = 256) {
|
|
37417
|
+
return typeof value === "string" && value.trim() !== "" ? value.trim().slice(0, maxLength) : void 0;
|
|
37418
|
+
}
|
|
37419
|
+
function nullableCount(value) {
|
|
37420
|
+
return value === null ? null : nonNegative(value);
|
|
37421
|
+
}
|
|
37422
|
+
function normalizeAttempt(value) {
|
|
37423
|
+
if (!isRecord$52(value)) return void 0;
|
|
37424
|
+
const startedAt = finite(value.startedAt);
|
|
37425
|
+
if (startedAt === void 0) return void 0;
|
|
37426
|
+
const poolAction = value.poolAction === "retry-same-account" || value.poolAction === "cooldown-and-rotate" || value.poolAction === "mark-auth-failed" || value.poolAction === "none" ? value.poolAction : void 0;
|
|
37427
|
+
const status = nonNegative(value.status);
|
|
37428
|
+
const endedAt = finite(value.endedAt);
|
|
37429
|
+
const retryAfterMs = nonNegative(value.retryAfterMs);
|
|
37430
|
+
const accountId = optionalText(value.accountId);
|
|
37431
|
+
const code = optionalText(value.code);
|
|
37432
|
+
const providerRequestId = optionalText(value.providerRequestId, 128);
|
|
37433
|
+
return {
|
|
37434
|
+
startedAt,
|
|
37435
|
+
...accountId === void 0 ? {} : { accountId },
|
|
37436
|
+
...endedAt === void 0 ? {} : { endedAt },
|
|
37437
|
+
...status === void 0 ? {} : { status },
|
|
37438
|
+
...code === void 0 ? {} : { code },
|
|
37439
|
+
...poolAction === void 0 ? {} : { poolAction },
|
|
37440
|
+
...retryAfterMs === void 0 ? {} : { retryAfterMs },
|
|
37441
|
+
...providerRequestId === void 0 ? {} : { providerRequestId }
|
|
37442
|
+
};
|
|
37443
|
+
}
|
|
37444
|
+
function normalizeUsage(value) {
|
|
37445
|
+
if (!isRecord$52(value)) return void 0;
|
|
37446
|
+
const freshTokens = nonNegative(value.freshTokens);
|
|
37447
|
+
const outputTokens = nonNegative(value.outputTokens);
|
|
37448
|
+
const cacheReadTokens = nullableCount(value.cacheReadTokens);
|
|
37449
|
+
const cacheWriteTokens = nullableCount(value.cacheWriteTokens);
|
|
37450
|
+
const reasoningTokens = nullableCount(value.reasoningTokens);
|
|
37451
|
+
if (freshTokens === void 0 || outputTokens === void 0 || cacheReadTokens === void 0 || cacheWriteTokens === void 0 || reasoningTokens === void 0) return void 0;
|
|
37452
|
+
return {
|
|
37453
|
+
freshTokens,
|
|
37454
|
+
cacheReadTokens,
|
|
37455
|
+
cacheWriteTokens,
|
|
37456
|
+
outputTokens,
|
|
37457
|
+
reasoningTokens
|
|
37458
|
+
};
|
|
37459
|
+
}
|
|
37460
|
+
function normalizeRequestDiagnostic(value) {
|
|
37461
|
+
if (!isRecord$52(value)) return void 0;
|
|
37462
|
+
const id = optionalText(value.id, 128);
|
|
37463
|
+
const model = optionalText(value.model, 256);
|
|
37464
|
+
const startedAt = finite(value.startedAt);
|
|
37465
|
+
const endedAt = finite(value.endedAt);
|
|
37466
|
+
const wire = value.wire === "openai" || value.wire === "anthropic" ? value.wire : void 0;
|
|
37467
|
+
const outcome = value.outcome === "success" || value.outcome === "error" || value.outcome === "aborted" ? value.outcome : void 0;
|
|
37468
|
+
if (id === void 0 || model === void 0 || startedAt === void 0 || endedAt === void 0 || wire === void 0 || outcome === void 0) return void 0;
|
|
37469
|
+
const usage = normalizeUsage(value.usage);
|
|
37470
|
+
const attempts = (Array.isArray(value.attempts) ? value.attempts : []).map(normalizeAttempt).filter((attempt) => attempt !== void 0);
|
|
37471
|
+
const accountId = optionalText(value.accountId);
|
|
37472
|
+
const previousAccountId = optionalText(value.previousAccountId);
|
|
37473
|
+
const code = optionalText(value.code);
|
|
37474
|
+
const finishReason = optionalText(value.finishReason);
|
|
37475
|
+
const guard = isRecord$52(value.toolGuard) ? value.toolGuard : void 0;
|
|
37476
|
+
const guardName = optionalText(guard?.toolName);
|
|
37477
|
+
const guardBytes = nonNegative(guard?.bytes);
|
|
37478
|
+
const guardRule = guard?.rule === "argument-bytes" || guard?.rule === "repeated-key" ? guard.rule : void 0;
|
|
37479
|
+
return {
|
|
37480
|
+
id,
|
|
37481
|
+
startedAt,
|
|
37482
|
+
endedAt,
|
|
37483
|
+
model,
|
|
37484
|
+
wire,
|
|
37485
|
+
accountChanged: value.accountChanged === true,
|
|
37486
|
+
outcome,
|
|
37487
|
+
attempts,
|
|
37488
|
+
...accountId === void 0 ? {} : { accountId },
|
|
37489
|
+
...previousAccountId === void 0 ? {} : { previousAccountId },
|
|
37490
|
+
...code === void 0 ? {} : { code },
|
|
37491
|
+
...finishReason === void 0 ? {} : { finishReason },
|
|
37492
|
+
...usage === void 0 ? {} : { usage },
|
|
37493
|
+
...guardName === void 0 || guardBytes === void 0 || guardRule === void 0 ? {} : { toolGuard: {
|
|
37494
|
+
toolName: guardName,
|
|
37495
|
+
bytes: guardBytes,
|
|
37496
|
+
rule: guardRule
|
|
37497
|
+
} }
|
|
37498
|
+
};
|
|
37499
|
+
}
|
|
37500
|
+
function normalizeRecentRequests(value) {
|
|
37501
|
+
if (!Array.isArray(value)) return [];
|
|
37502
|
+
return value.map(normalizeRequestDiagnostic).filter((request) => request !== void 0).slice(-20);
|
|
37503
|
+
}
|
|
37136
37504
|
function normalizeRecord$2(value) {
|
|
37137
37505
|
if (!isRecord$52(value)) return void 0;
|
|
37138
37506
|
const lastActiveAt = finite(value.lastActiveAt);
|
|
@@ -37141,10 +37509,16 @@ function normalizeRecord$2(value) {
|
|
|
37141
37509
|
const drift = typeof value.lastDrift === "string" && value.lastDrift !== "" ? value.lastDrift : void 0;
|
|
37142
37510
|
const firstRequestCachedTokens = nonNegative(value.firstRequestCachedTokens);
|
|
37143
37511
|
const firstRequestPromptTokens = nonNegative(value.firstRequestPromptTokens);
|
|
37512
|
+
const lastRequestCachedTokens = nonNegative(value.lastRequestCachedTokens);
|
|
37513
|
+
const lastRequestFreshTokens = nonNegative(value.lastRequestFreshTokens);
|
|
37514
|
+
const previousRequestPromptTokens = nonNegative(value.previousRequestPromptTokens);
|
|
37515
|
+
const lastAccountId = typeof value.lastAccountId === "string" && value.lastAccountId.trim() !== "" ? value.lastAccountId.trim() : void 0;
|
|
37516
|
+
const lastAccountAt = nonNegative(value.lastAccountAt);
|
|
37144
37517
|
const warmupStreak = count$1(value.warmupConsecutiveHits);
|
|
37145
37518
|
const budgetDropped = droppedImageKeys(value.budgetDropped);
|
|
37146
37519
|
const lastRequestImageBytes = nonNegative(value.lastRequestImageBytes);
|
|
37147
37520
|
const lastDroppedImages = nonNegative(value.lastDroppedImages);
|
|
37521
|
+
const recentRequests = normalizeRecentRequests(value.recentRequests);
|
|
37148
37522
|
return {
|
|
37149
37523
|
lastActiveAt,
|
|
37150
37524
|
updatedAt,
|
|
@@ -37159,6 +37533,12 @@ function normalizeRecord$2(value) {
|
|
|
37159
37533
|
...drift === void 0 ? {} : { lastDrift: drift },
|
|
37160
37534
|
...firstRequestCachedTokens === void 0 ? {} : { firstRequestCachedTokens },
|
|
37161
37535
|
...firstRequestPromptTokens === void 0 ? {} : { firstRequestPromptTokens },
|
|
37536
|
+
...lastRequestCachedTokens === void 0 ? {} : { lastRequestCachedTokens },
|
|
37537
|
+
...lastRequestFreshTokens === void 0 ? {} : { lastRequestFreshTokens },
|
|
37538
|
+
...previousRequestPromptTokens === void 0 ? {} : { previousRequestPromptTokens },
|
|
37539
|
+
...lastAccountId === void 0 ? {} : { lastAccountId },
|
|
37540
|
+
...lastAccountAt === void 0 ? {} : { lastAccountAt },
|
|
37541
|
+
...recentRequests.length > 0 ? { recentRequests } : {},
|
|
37162
37542
|
...warmupStreak > 0 ? { warmupConsecutiveHits: warmupStreak } : {},
|
|
37163
37543
|
...budgetDropped.length > 0 ? { budgetDropped } : {},
|
|
37164
37544
|
...lastRequestImageBytes === void 0 ? {} : { lastRequestImageBytes },
|
|
@@ -38259,6 +38639,7 @@ function classifyKimiFailure(status, bodyText) {
|
|
|
38259
38639
|
const detail = summarizeFailureBody$1(bodyText);
|
|
38260
38640
|
if (isHttpContextOverflow(status, bodyText)) return {
|
|
38261
38641
|
code: CONTEXT_OVERFLOW_CODE,
|
|
38642
|
+
poolAction: "none",
|
|
38262
38643
|
retryable: false,
|
|
38263
38644
|
accountScoped: false,
|
|
38264
38645
|
upstreamOverload: false,
|
|
@@ -38266,6 +38647,7 @@ function classifyKimiFailure(status, bodyText) {
|
|
|
38266
38647
|
};
|
|
38267
38648
|
if (status === 400 && isKimiBodySizeRefusal(detail)) return {
|
|
38268
38649
|
code: CONTEXT_OVERFLOW_CODE,
|
|
38650
|
+
poolAction: "none",
|
|
38269
38651
|
retryable: false,
|
|
38270
38652
|
accountScoped: false,
|
|
38271
38653
|
upstreamOverload: false,
|
|
@@ -38273,6 +38655,7 @@ function classifyKimiFailure(status, bodyText) {
|
|
|
38273
38655
|
};
|
|
38274
38656
|
if (status === 402) return {
|
|
38275
38657
|
code: "SERVER",
|
|
38658
|
+
poolAction: "retry-same-account",
|
|
38276
38659
|
retryable: true,
|
|
38277
38660
|
accountScoped: false,
|
|
38278
38661
|
upstreamOverload: false,
|
|
@@ -38281,6 +38664,7 @@ function classifyKimiFailure(status, bodyText) {
|
|
|
38281
38664
|
if (status === 401 || status === 403) {
|
|
38282
38665
|
if (matchesAny$1(detail, ENTITLEMENT_PATTERNS)) return {
|
|
38283
38666
|
code: "PROVIDER_ERROR",
|
|
38667
|
+
poolAction: "none",
|
|
38284
38668
|
retryable: false,
|
|
38285
38669
|
accountScoped: false,
|
|
38286
38670
|
upstreamOverload: false,
|
|
@@ -38290,6 +38674,7 @@ function classifyKimiFailure(status, bodyText) {
|
|
|
38290
38674
|
const limitReached = matchesAny$1(detail, ACCOUNT_LIMIT_PATTERNS);
|
|
38291
38675
|
return {
|
|
38292
38676
|
code: "PROVIDER_ERROR",
|
|
38677
|
+
poolAction: "cooldown-and-rotate",
|
|
38293
38678
|
retryable: false,
|
|
38294
38679
|
accountScoped: true,
|
|
38295
38680
|
upstreamOverload: false,
|
|
@@ -38298,6 +38683,7 @@ function classifyKimiFailure(status, bodyText) {
|
|
|
38298
38683
|
}
|
|
38299
38684
|
return {
|
|
38300
38685
|
code: "INVALID_CREDENTIAL",
|
|
38686
|
+
poolAction: "mark-auth-failed",
|
|
38301
38687
|
retryable: false,
|
|
38302
38688
|
accountScoped: false,
|
|
38303
38689
|
upstreamOverload: false,
|
|
@@ -38307,6 +38693,7 @@ function classifyKimiFailure(status, bodyText) {
|
|
|
38307
38693
|
if (status === 429) {
|
|
38308
38694
|
if (matchesAny$1(detail, QUOTA_EXHAUSTED_PATTERNS$1)) return {
|
|
38309
38695
|
code: "PROVIDER_ERROR",
|
|
38696
|
+
poolAction: "cooldown-and-rotate",
|
|
38310
38697
|
retryable: false,
|
|
38311
38698
|
accountScoped: true,
|
|
38312
38699
|
upstreamOverload: false,
|
|
@@ -38314,6 +38701,7 @@ function classifyKimiFailure(status, bodyText) {
|
|
|
38314
38701
|
};
|
|
38315
38702
|
if (matchesAny$1(detail, UPSTREAM_OVERLOAD_PATTERNS)) return {
|
|
38316
38703
|
code: "SERVER",
|
|
38704
|
+
poolAction: "retry-same-account",
|
|
38317
38705
|
retryable: true,
|
|
38318
38706
|
accountScoped: false,
|
|
38319
38707
|
upstreamOverload: true,
|
|
@@ -38321,6 +38709,7 @@ function classifyKimiFailure(status, bodyText) {
|
|
|
38321
38709
|
};
|
|
38322
38710
|
return {
|
|
38323
38711
|
code: "RATE_LIMIT",
|
|
38712
|
+
poolAction: "retry-same-account",
|
|
38324
38713
|
retryable: true,
|
|
38325
38714
|
accountScoped: false,
|
|
38326
38715
|
upstreamOverload: false,
|
|
@@ -38329,6 +38718,7 @@ function classifyKimiFailure(status, bodyText) {
|
|
|
38329
38718
|
}
|
|
38330
38719
|
if (status >= 500) return {
|
|
38331
38720
|
code: "SERVER",
|
|
38721
|
+
poolAction: "retry-same-account",
|
|
38332
38722
|
retryable: true,
|
|
38333
38723
|
accountScoped: false,
|
|
38334
38724
|
upstreamOverload: matchesAny$1(detail, UPSTREAM_OVERLOAD_PATTERNS),
|
|
@@ -38336,6 +38726,7 @@ function classifyKimiFailure(status, bodyText) {
|
|
|
38336
38726
|
};
|
|
38337
38727
|
if (status === 400) return {
|
|
38338
38728
|
code: "PROVIDER_ERROR",
|
|
38729
|
+
poolAction: "none",
|
|
38339
38730
|
retryable: false,
|
|
38340
38731
|
accountScoped: false,
|
|
38341
38732
|
upstreamOverload: false,
|
|
@@ -38343,6 +38734,7 @@ function classifyKimiFailure(status, bodyText) {
|
|
|
38343
38734
|
};
|
|
38344
38735
|
return {
|
|
38345
38736
|
code: "PROVIDER_ERROR",
|
|
38737
|
+
poolAction: "none",
|
|
38346
38738
|
retryable: false,
|
|
38347
38739
|
accountScoped: false,
|
|
38348
38740
|
upstreamOverload: false,
|
|
@@ -38378,18 +38770,33 @@ function accountLimitCooldownMs(bodyText, now = Date.now()) {
|
|
|
38378
38770
|
resetAtMs: field !== null ? parseTimestamp(Number(field[1])) : instant !== null ? Date.parse(instant[0].replace(" ", "T")) : null,
|
|
38379
38771
|
now,
|
|
38380
38772
|
fallbackMs: BILLING_CYCLE_PATTERN.test(bodyText) ? BILLING_CYCLE_COOLDOWN_MS : ACCOUNT_LIMIT_COOLDOWN_MS,
|
|
38381
|
-
minimumMs:
|
|
38773
|
+
minimumMs: MIN_ACCOUNT_LIMIT_COOLDOWN_MS,
|
|
38382
38774
|
maximumMs: MAX_ACCOUNT_LIMIT_COOLDOWN_MS
|
|
38383
38775
|
});
|
|
38384
38776
|
}
|
|
38777
|
+
/** Minimum cooldown for a proven account-owned usage limit near its reset. */
|
|
38778
|
+
const MIN_ACCOUNT_LIMIT_COOLDOWN_MS = 15 * 6e4;
|
|
38385
38779
|
/**
|
|
38386
|
-
*
|
|
38780
|
+
* The account a shared/transient failure should use on the harness's next attempt.
|
|
38387
38781
|
*
|
|
38388
|
-
*
|
|
38389
|
-
*
|
|
38390
|
-
*
|
|
38782
|
+
* DSH rebuilds GenerateOptions for a retry, but keeps the step's original abort
|
|
38783
|
+
* signal. Keying by that signal avoids a process-global session latch: concurrent
|
|
38784
|
+
* sessions cannot affect one another, and an abandoned retry chain disappears by GC.
|
|
38391
38785
|
*/
|
|
38392
|
-
const
|
|
38786
|
+
const sameAccountRetryBySignal = /* @__PURE__ */ new WeakMap();
|
|
38787
|
+
function rememberSameAccountRetry(signal, accountId) {
|
|
38788
|
+
if (signal !== void 0 && accountId !== void 0 && !signal.aborted) sameAccountRetryBySignal.set(signal, accountId);
|
|
38789
|
+
}
|
|
38790
|
+
function clearSameAccountRetry(signal) {
|
|
38791
|
+
if (signal !== void 0) sameAccountRetryBySignal.delete(signal);
|
|
38792
|
+
}
|
|
38793
|
+
/** Only these non-secret, bounded upstream identities may enter durable diagnostics. */
|
|
38794
|
+
function upstreamRequestId(headers) {
|
|
38795
|
+
for (const name of ["x-request-id", "msh-request-id"]) {
|
|
38796
|
+
const value = headers.get(name)?.trim() ?? "";
|
|
38797
|
+
if (/^[A-Za-z0-9._:-]{1,128}$/.test(value)) return value;
|
|
38798
|
+
}
|
|
38799
|
+
}
|
|
38393
38800
|
/**
|
|
38394
38801
|
* Fallback cooldown for an account whose usage window is spent.
|
|
38395
38802
|
*
|
|
@@ -38525,30 +38932,39 @@ function reportDriftCause(sessionId, cause) {
|
|
|
38525
38932
|
if (driftWarned.size > 256) driftWarned.clear();
|
|
38526
38933
|
console.warn("[kimi-code] prompt cache rebuilt for session " + sessionId + ": the " + cause + " changed mid-conversation, so the whole prompt was reprocessed once.");
|
|
38527
38934
|
}
|
|
38528
|
-
function noteSessionCacheState(sessionId, state) {
|
|
38935
|
+
function noteSessionCacheState(sessionId, state, successful, requestDiagnostic) {
|
|
38529
38936
|
if (sessionId === void 0 || sessionId.trim() === "") return;
|
|
38530
38937
|
const stats = getCacheStats(sessionId);
|
|
38531
|
-
if (stats.requests === 0) return;
|
|
38938
|
+
if (stats.requests === 0 && requestDiagnostic === void 0) return;
|
|
38532
38939
|
const lastDrift = getLastDriftCause(sessionId);
|
|
38533
38940
|
reportDriftCause(sessionId, lastDrift);
|
|
38534
38941
|
const now = Date.now();
|
|
38535
38942
|
const imageBudget = getSessionImageBudgetStats(sessionId);
|
|
38536
38943
|
const priorRecord = sessionCacheState.read(sessionId);
|
|
38944
|
+
const previousRequestPromptTokens = priorRecord?.totalTokens;
|
|
38537
38945
|
const budgetDropped = imageBudget !== void 0 && imageBudget.droppedKeys.length > 0 ? imageBudget.droppedKeys : priorRecord?.budgetDropped;
|
|
38538
38946
|
const liveBytes = imageBudget?.requestImageBytes ?? 0;
|
|
38539
38947
|
const liveDropped = imageBudget?.droppedImages ?? 0;
|
|
38540
38948
|
const lastRequestImageBytes = liveBytes > 0 ? liveBytes : priorRecord?.lastRequestImageBytes;
|
|
38541
38949
|
const lastDroppedImages = liveDropped > 0 ? liveDropped : priorRecord?.lastDroppedImages;
|
|
38950
|
+
const recentRequests = requestDiagnostic === void 0 ? priorRecord?.recentRequests : [...priorRecord?.recentRequests ?? [], requestDiagnostic].slice(-20);
|
|
38951
|
+
const accountObservation = successful && state.accountId !== void 0 ? {
|
|
38952
|
+
lastAccountId: state.accountId,
|
|
38953
|
+
lastAccountAt: now
|
|
38954
|
+
} : {
|
|
38955
|
+
...priorRecord?.lastAccountId === void 0 ? {} : { lastAccountId: priorRecord.lastAccountId },
|
|
38956
|
+
...priorRecord?.lastAccountAt === void 0 ? {} : { lastAccountAt: priorRecord.lastAccountAt }
|
|
38957
|
+
};
|
|
38542
38958
|
const firstRequest = stats.requests === 1 ? {
|
|
38543
38959
|
firstRequestCachedTokens: state.cacheReadTokens,
|
|
38544
|
-
firstRequestPromptTokens: state.cacheReadTokens + state.inputTokens
|
|
38960
|
+
firstRequestPromptTokens: state.cacheReadTokens + state.inputTokens + state.cacheWriteTokens
|
|
38545
38961
|
} : {
|
|
38546
38962
|
...priorRecord?.firstRequestCachedTokens === void 0 ? {} : { firstRequestCachedTokens: priorRecord.firstRequestCachedTokens },
|
|
38547
38963
|
...priorRecord?.firstRequestPromptTokens === void 0 ? {} : { firstRequestPromptTokens: priorRecord.firstRequestPromptTokens }
|
|
38548
38964
|
};
|
|
38549
38965
|
sessionCacheState.write(sessionId, {
|
|
38550
38966
|
lastActiveAt: now,
|
|
38551
|
-
totalTokens: state.cacheReadTokens + state.inputTokens,
|
|
38967
|
+
totalTokens: state.cacheReadTokens + state.inputTokens + state.cacheWriteTokens,
|
|
38552
38968
|
requests: stats.requests,
|
|
38553
38969
|
cachedTokens: stats.cachedTokens,
|
|
38554
38970
|
freshTokens: stats.freshTokens,
|
|
@@ -38556,6 +38972,11 @@ function noteSessionCacheState(sessionId, state) {
|
|
|
38556
38972
|
cacheWriteTokens: stats.cacheWriteTokens,
|
|
38557
38973
|
cacheWrite5mTokens: stats.cacheWrite5mTokens,
|
|
38558
38974
|
cacheWrite1hTokens: stats.cacheWrite1hTokens,
|
|
38975
|
+
lastRequestCachedTokens: state.cacheReadTokens,
|
|
38976
|
+
lastRequestFreshTokens: state.inputTokens,
|
|
38977
|
+
...accountObservation,
|
|
38978
|
+
...recentRequests === void 0 ? {} : { recentRequests },
|
|
38979
|
+
...previousRequestPromptTokens === void 0 ? {} : { previousRequestPromptTokens },
|
|
38559
38980
|
...lastDrift === void 0 ? {} : { lastDrift },
|
|
38560
38981
|
...budgetDropped === void 0 ? {} : { budgetDropped },
|
|
38561
38982
|
...lastRequestImageBytes === void 0 ? {} : { lastRequestImageBytes },
|
|
@@ -38569,7 +38990,7 @@ function noteSessionCacheState(sessionId, state) {
|
|
|
38569
38990
|
inputTokens: state.inputTokens,
|
|
38570
38991
|
cacheReadTokens: state.cacheReadTokens,
|
|
38571
38992
|
outputTokens: state.outputTokens,
|
|
38572
|
-
totalTokens: state.cacheReadTokens + state.inputTokens,
|
|
38993
|
+
totalTokens: state.cacheReadTokens + state.inputTokens + state.cacheWriteTokens,
|
|
38573
38994
|
at: now,
|
|
38574
38995
|
...lastDrift === void 0 ? {} : { driftCause: lastDrift }
|
|
38575
38996
|
});
|
|
@@ -38737,13 +39158,18 @@ var KimiCodeAdapter = class extends LlmAdapter {
|
|
|
38737
39158
|
warm: true
|
|
38738
39159
|
});
|
|
38739
39160
|
}
|
|
38740
|
-
if (candidates.length === 0) return void 0;
|
|
38741
39161
|
const remainingShareById = {};
|
|
38742
39162
|
for (const candidate of candidates) remainingShareById[candidate.id] = remainingQuotaShare(cachedQuotaFor$1(candidate.id));
|
|
38743
|
-
const
|
|
39163
|
+
const warmAccountIds = orderAffinityCandidates({
|
|
38744
39164
|
candidates,
|
|
38745
39165
|
remainingShareById
|
|
38746
39166
|
});
|
|
39167
|
+
const sessionId = typeof options.sessionId === "string" ? options.sessionId.trim() : "";
|
|
39168
|
+
const durable = sessionId === "" ? void 0 : sessionCacheState.read(sessionId);
|
|
39169
|
+
const previousAccountId = durable?.lastAccountId;
|
|
39170
|
+
const previousAge = durable?.lastAccountAt === void 0 ? Infinity : Date.now() - durable.lastAccountAt;
|
|
39171
|
+
const previousIsWarm = previousAccountId !== void 0 && scopes.some((scope) => scope.id === previousAccountId) && previousAge >= 0 && previousAge < 15e5;
|
|
39172
|
+
const preferAccountIds = [.../* @__PURE__ */ new Set([...previousIsWarm ? [previousAccountId] : [], ...warmAccountIds])];
|
|
38747
39173
|
return preferAccountIds.length === 0 ? void 0 : { preferAccountIds };
|
|
38748
39174
|
}
|
|
38749
39175
|
/**
|
|
@@ -38852,14 +39278,51 @@ var KimiCodeAdapter = class extends LlmAdapter {
|
|
|
38852
39278
|
const normalized = normalizeGenerateOptions(options);
|
|
38853
39279
|
const sideChannel = isAuxiliaryRequest(normalized) || isSideChannelTitleRequest(normalized);
|
|
38854
39280
|
const sessionKey = typeof options.sessionId === "string" ? options.sessionId.trim() : "";
|
|
39281
|
+
const retrySignal = options.signal;
|
|
39282
|
+
const sameAccountRetryId = sideChannel || retrySignal === void 0 ? void 0 : sameAccountRetryBySignal.get(retrySignal);
|
|
39283
|
+
const previousAccountId = sideChannel || sessionKey === "" ? void 0 : sessionCacheState.read(sessionKey)?.lastAccountId;
|
|
39284
|
+
const requestDiagnostic = {
|
|
39285
|
+
id: randomUUID(),
|
|
39286
|
+
startedAt: Date.now(),
|
|
39287
|
+
endedAt: Date.now(),
|
|
39288
|
+
model: options.model,
|
|
39289
|
+
wire: "openai",
|
|
39290
|
+
...previousAccountId === void 0 ? {} : { previousAccountId },
|
|
39291
|
+
accountChanged: false,
|
|
39292
|
+
outcome: "error",
|
|
39293
|
+
attempts: []
|
|
39294
|
+
};
|
|
39295
|
+
let diagnosticState;
|
|
39296
|
+
let requestError;
|
|
38855
39297
|
const mainHeaderRelease = !sideChannel && sessionKey !== "" ? registerInFlightMainSessionHeader(sessionKey) : () => void 0;
|
|
38856
39298
|
try {
|
|
38857
39299
|
const catalog = await this.catalog().catch(() => []);
|
|
38858
39300
|
const wire = wireForCatalogEntry(options.model, catalog);
|
|
39301
|
+
requestDiagnostic.wire = wire;
|
|
38859
39302
|
const entry = catalog.find((model) => model.id === options.model);
|
|
38860
39303
|
const images = await resolveRequestImages$2(normalized, this.options.attachments, signal, KIMI_CODE_REQUEST_IMAGE_MAX_EDGE);
|
|
39304
|
+
const settings = await this.settings();
|
|
39305
|
+
const modalities = inputModalitiesForEntry(options.model, catalog);
|
|
39306
|
+
/**
|
|
39307
|
+
* Which readable image occurrences the reference path would cover.
|
|
39308
|
+
*
|
|
39309
|
+
* Planned BEFORE the image budget: a durable image this OpenAI request will
|
|
39310
|
+
* cite as `ms://` carries no inline base64 bytes, exactly as in Kimi's own
|
|
39311
|
+
* media resolver. Nothing is uploaded here; the actual references are still
|
|
39312
|
+
* checked after upload so a failed upload cannot escape the inline budget.
|
|
39313
|
+
* Videos stay out of this early plan: their own oldest-first pass runs
|
|
39314
|
+
* before their bytes are read, just as it did before this change.
|
|
39315
|
+
*/
|
|
39316
|
+
const plannedImages = planMediaReferences({
|
|
39317
|
+
wire,
|
|
39318
|
+
imageAccepted: modalities.includes("image"),
|
|
39319
|
+
videoAccepted: false,
|
|
39320
|
+
images,
|
|
39321
|
+
videos: /* @__PURE__ */ new Map()
|
|
39322
|
+
});
|
|
39323
|
+
const plannedInlineImageKeys = new Set(plannedImages.map((item) => `attachment:${item.attachmentId}`));
|
|
38861
39324
|
const priorDroppedKeys = getSessionDroppedImageKeys(options.sessionId, options.sessionId === void 0 ? void 0 : sessionCacheState.read(options.sessionId)?.budgetDropped);
|
|
38862
|
-
const stickyOffload = offloadRequestImagesWithStickyBudget(normalized, maxRequestImageBytes$1(), lowRequestImageBytes(), images, priorDroppedKeys);
|
|
39325
|
+
const stickyOffload = offloadRequestImagesWithStickyBudget(normalized, maxRequestImageBytes$1(), lowRequestImageBytes(), images, priorDroppedKeys, plannedInlineImageKeys);
|
|
38863
39326
|
const imageTrimmed = stickyOffload.options;
|
|
38864
39327
|
if (!sideChannel) markPendingImageOffload(options.sessionId, stickyOffload.newlyDroppedKeys.length);
|
|
38865
39328
|
const gatedEffort = coerceThinkingEffort(options.model, mapReasoningEffort(options.reasoningEffort === void 0 || options.reasoningEffort === null ? void 0 : String(options.reasoningEffort)));
|
|
@@ -38875,8 +39338,6 @@ var KimiCodeAdapter = class extends LlmAdapter {
|
|
|
38875
39338
|
reasoningEffort: ReasoningEffortId(gatedEffort.effort)
|
|
38876
39339
|
};
|
|
38877
39340
|
const videos = await resolveRequestVideos(requestOptions, this.options.videos, signal);
|
|
38878
|
-
const settings = await this.settings();
|
|
38879
|
-
const modalities = inputModalitiesForEntry(options.model, catalog);
|
|
38880
39341
|
/**
|
|
38881
39342
|
* Everything every attempt shares: the media reads and the capability gates.
|
|
38882
39343
|
*
|
|
@@ -38896,13 +39357,14 @@ var KimiCodeAdapter = class extends LlmAdapter {
|
|
|
38896
39357
|
* be sent; nothing is uploaded, and no network is touched, until that guard
|
|
38897
39358
|
* has accepted the request (see the rotation loop).
|
|
38898
39359
|
*/
|
|
38899
|
-
const
|
|
39360
|
+
const plannedVideos = planMediaReferences({
|
|
38900
39361
|
wire,
|
|
38901
|
-
imageAccepted:
|
|
39362
|
+
imageAccepted: false,
|
|
38902
39363
|
videoAccepted: baseMedia.videoAccepted === true,
|
|
38903
|
-
images,
|
|
39364
|
+
images: /* @__PURE__ */ new Map(),
|
|
38904
39365
|
videos
|
|
38905
39366
|
});
|
|
39367
|
+
const planned = [...plannedImages, ...plannedVideos];
|
|
38906
39368
|
const contextWindow = this.contextWindowFor(options.model, entry, settings.contextWindowOverrides);
|
|
38907
39369
|
const requestedMax = options.maxTokens ?? maxOutputTokensFor$4(options.model, contextWindow);
|
|
38908
39370
|
const inputCap = maxInputTokensForEntry(options.model, catalog);
|
|
@@ -38921,13 +39383,15 @@ var KimiCodeAdapter = class extends LlmAdapter {
|
|
|
38921
39383
|
* references), the real reference build after the upload, and the all-inline
|
|
38922
39384
|
* rebuild the missing-resource fallback re-sends.
|
|
38923
39385
|
*
|
|
38924
|
-
*
|
|
38925
|
-
*
|
|
38926
|
-
*
|
|
38927
|
-
*
|
|
39386
|
+
* Calls normally restart from `boundedOptions`; the post-upload pass may
|
|
39387
|
+
* supply the same options after budgeting the images that really stayed
|
|
39388
|
+
* inline. Re-fitting from that baseline is load bearing: the inline fallback
|
|
39389
|
+
* must not inherit an omission made for a different, much smaller body, and
|
|
39390
|
+
* its positional drop loop must not mistake non-contiguous budget omissions
|
|
39391
|
+
* for the oldest remaining images.
|
|
38928
39392
|
*/
|
|
38929
|
-
const buildBodyWithinLimit = (media) => {
|
|
38930
|
-
let buildOptions =
|
|
39393
|
+
const buildBodyWithinLimit = (media, baseline = boundedOptions) => {
|
|
39394
|
+
let buildOptions = baseline;
|
|
38931
39395
|
for (let attempt = 0;; attempt++) {
|
|
38932
39396
|
const built = buildRequest(buildOptions, wire, images, void 0, media);
|
|
38933
39397
|
const body = JSON.stringify(built);
|
|
@@ -38937,7 +39401,7 @@ var KimiCodeAdapter = class extends LlmAdapter {
|
|
|
38937
39401
|
options: buildOptions
|
|
38938
39402
|
};
|
|
38939
39403
|
const context = () => ({
|
|
38940
|
-
droppedImages: countOmitted(buildOptions,
|
|
39404
|
+
droppedImages: countOmitted(buildOptions, baseline, images),
|
|
38941
39405
|
sendableImagesRemaining: requestImagePayloadLengths(buildOptions, images).length,
|
|
38942
39406
|
excessBytes: bytes - bodyLimit
|
|
38943
39407
|
});
|
|
@@ -38945,7 +39409,7 @@ var KimiCodeAdapter = class extends LlmAdapter {
|
|
|
38945
39409
|
assertRequestBodyFits$1(built, carriesVideo, context(), bodyLimit);
|
|
38946
39410
|
throw new Error("unreachable: assertRequestBodyFits returns or throws");
|
|
38947
39411
|
}
|
|
38948
|
-
const drop = dropOldestImagesUntilFits(buildOptions, images, bytes - bodyLimit,
|
|
39412
|
+
const drop = dropOldestImagesUntilFits(buildOptions, images, bytes - bodyLimit, baseline);
|
|
38949
39413
|
if (drop.dropped === 0) {
|
|
38950
39414
|
assertRequestBodyFits$1(built, carriesVideo, context(), bodyLimit);
|
|
38951
39415
|
throw new Error("unreachable: assertRequestBodyFits returns or throws");
|
|
@@ -38965,9 +39429,11 @@ var KimiCodeAdapter = class extends LlmAdapter {
|
|
|
38965
39429
|
*/
|
|
38966
39430
|
let measured;
|
|
38967
39431
|
let sentBuild;
|
|
39432
|
+
let sentImageReferenceKeys;
|
|
38968
39433
|
const pool = this.accountPool;
|
|
38969
39434
|
const tried = /* @__PURE__ */ new Set();
|
|
38970
|
-
const
|
|
39435
|
+
const cacheAffinity = sideChannel ? void 0 : await this.cacheAffinityHint(pool, requestOptions);
|
|
39436
|
+
const affinity = sameAccountRetryId === void 0 ? cacheAffinity : { preferAccountIds: [.../* @__PURE__ */ new Set([sameAccountRetryId, ...cacheAffinity?.preferAccountIds ?? []])] };
|
|
38971
39437
|
let servedByAccountId;
|
|
38972
39438
|
let response;
|
|
38973
39439
|
while (true) {
|
|
@@ -38994,6 +39460,11 @@ var KimiCodeAdapter = class extends LlmAdapter {
|
|
|
38994
39460
|
tried.add(accountId);
|
|
38995
39461
|
apiCredentials = effective.credentials;
|
|
38996
39462
|
}
|
|
39463
|
+
const attemptDiagnostic = {
|
|
39464
|
+
startedAt: Date.now(),
|
|
39465
|
+
...accountId === void 0 ? {} : { accountId }
|
|
39466
|
+
};
|
|
39467
|
+
if (!sideChannel) requestDiagnostic.attempts.push(attemptDiagnostic);
|
|
38997
39468
|
const region = apiCredentials.region ?? await resolveRegion();
|
|
38998
39469
|
const base = (apiCredentials.baseUrl ?? codingBaseUrl(region)).replace(/\/+$/, "");
|
|
38999
39470
|
const endpoint = wire === "anthropic" ? `${base}/v1/messages?beta=true` : `${base}/v1/chat/completions`;
|
|
@@ -39020,12 +39491,18 @@ var KimiCodeAdapter = class extends LlmAdapter {
|
|
|
39020
39491
|
accountScope,
|
|
39021
39492
|
signal
|
|
39022
39493
|
});
|
|
39023
|
-
|
|
39494
|
+
const imageReferenceKeys = /* @__PURE__ */ new Set();
|
|
39495
|
+
if (uploads !== void 0) for (const id of uploads.imageReferences.keys()) imageReferenceKeys.add(`attachment:${id}`);
|
|
39496
|
+
const postUploadOffload = offloadRequestImagesWithStickyBudget(boundedOptions, maxRequestImageBytes$1(), lowRequestImageBytes(), images, stickyOffload.allDroppedKeys, imageReferenceKeys);
|
|
39497
|
+
const finalBaseline = postUploadOffload.options;
|
|
39498
|
+
if (!sideChannel) markPendingImageOffload(options.sessionId, stickyOffload.newlyDroppedKeys.length + postUploadOffload.newlyDroppedKeys.length);
|
|
39499
|
+
let finalBuild = uploads === void 0 ? planned.length === 0 ? measured : buildBodyWithinLimit(baseMedia, finalBaseline) : buildBodyWithinLimit({
|
|
39024
39500
|
...baseMedia,
|
|
39025
39501
|
imageReferences: uploads.imageReferences,
|
|
39026
39502
|
videoReferences: uploads.videoReferences
|
|
39027
|
-
});
|
|
39503
|
+
}, finalBaseline);
|
|
39028
39504
|
sentBuild = finalBuild;
|
|
39505
|
+
sentImageReferenceKeys = uploads === void 0 ? void 0 : imageReferenceKeys;
|
|
39029
39506
|
let body = finalBuild.body;
|
|
39030
39507
|
const post = async (payload) => {
|
|
39031
39508
|
try {
|
|
@@ -39075,34 +39552,46 @@ var KimiCodeAdapter = class extends LlmAdapter {
|
|
|
39075
39552
|
data: item.data
|
|
39076
39553
|
});
|
|
39077
39554
|
let inlineBuild;
|
|
39555
|
+
const inlineOffload = offloadRequestImagesWithStickyBudget(boundedOptions, maxRequestImageBytes$1(), lowRequestImageBytes(), images, stickyOffload.allDroppedKeys);
|
|
39556
|
+
if (!sideChannel) markPendingImageOffload(options.sessionId, stickyOffload.newlyDroppedKeys.length + inlineOffload.newlyDroppedKeys.length);
|
|
39078
39557
|
try {
|
|
39079
|
-
inlineBuild = buildBodyWithinLimit(baseMedia);
|
|
39558
|
+
inlineBuild = buildBodyWithinLimit(baseMedia, inlineOffload.options);
|
|
39080
39559
|
} catch {
|
|
39081
39560
|
inlineBuild = void 0;
|
|
39082
39561
|
}
|
|
39083
39562
|
if (inlineBuild !== void 0) {
|
|
39084
39563
|
finalBuild = inlineBuild;
|
|
39085
39564
|
sentBuild = inlineBuild;
|
|
39565
|
+
sentImageReferenceKeys = void 0;
|
|
39086
39566
|
body = inlineBuild.body;
|
|
39087
39567
|
response = await post(body);
|
|
39088
39568
|
detail = response.ok ? "" : (await response.text().catch(() => "")).slice(0, 2e3);
|
|
39089
39569
|
}
|
|
39090
39570
|
}
|
|
39091
|
-
|
|
39571
|
+
attemptDiagnostic.status = response.status;
|
|
39572
|
+
const providerRequestId = upstreamRequestId(response.headers);
|
|
39573
|
+
if (providerRequestId !== void 0) attemptDiagnostic.providerRequestId = providerRequestId;
|
|
39574
|
+
if (response.ok) {
|
|
39575
|
+
attemptDiagnostic.endedAt = Date.now();
|
|
39576
|
+
if (accountId !== void 0) requestDiagnostic.accountId = accountId;
|
|
39577
|
+
clearSameAccountRetry(retrySignal);
|
|
39578
|
+
break;
|
|
39579
|
+
}
|
|
39092
39580
|
const failure = classifyKimiFailure(response.status, detail);
|
|
39581
|
+
attemptDiagnostic.code = failure.code;
|
|
39582
|
+
attemptDiagnostic.poolAction = failure.poolAction;
|
|
39583
|
+
attemptDiagnostic.endedAt = Date.now();
|
|
39093
39584
|
const after = response.status === 429 ? retryAfterMs$1(response.headers) : void 0;
|
|
39585
|
+
if (after !== void 0) attemptDiagnostic.retryAfterMs = after;
|
|
39586
|
+
if (failure.poolAction === "retry-same-account") rememberSameAccountRetry(retrySignal, accountId);
|
|
39587
|
+
else clearSameAccountRetry(retrySignal);
|
|
39094
39588
|
if (pool !== null && accountId !== void 0) {
|
|
39095
|
-
|
|
39096
|
-
|
|
39097
|
-
const cooldownMs = failure.accountScoped ? accountLimitCooldownMs(detail) : after ?? POOL_COOLDOWN_MS$5;
|
|
39098
|
-
await pool.markCooldown(accountId, cooldownMs, `${PROVIDER_NAME$8} 429`).catch(() => void 0);
|
|
39589
|
+
if (failure.poolAction === "cooldown-and-rotate") {
|
|
39590
|
+
await pool.markCooldown(accountId, accountLimitCooldownMs(detail), `${PROVIDER_NAME$8} ${response.status}`).catch(() => void 0);
|
|
39099
39591
|
if (await pool.hasAnotherAvailableAccount(tried)) continue;
|
|
39100
|
-
} else if (failure.
|
|
39592
|
+
} else if (failure.poolAction === "mark-auth-failed") {
|
|
39101
39593
|
await pool.markAuthFailed(accountId, failure.message).catch(() => void 0);
|
|
39102
39594
|
if (await pool.hasAnotherAvailableAccount(tried)) continue;
|
|
39103
|
-
} else if (failure.accountScoped) {
|
|
39104
|
-
await pool.markCooldown(accountId, accountLimitCooldownMs(detail), `${PROVIDER_NAME$8} 403`).catch(() => void 0);
|
|
39105
|
-
if (await pool.hasAnotherAvailableAccount(tried)) continue;
|
|
39106
39595
|
}
|
|
39107
39596
|
}
|
|
39108
39597
|
throw new LlmError(failure.message, failure.code, {
|
|
@@ -39111,7 +39600,7 @@ var KimiCodeAdapter = class extends LlmAdapter {
|
|
|
39111
39600
|
});
|
|
39112
39601
|
}
|
|
39113
39602
|
if (sentBuild !== void 0 && !sideChannel) {
|
|
39114
|
-
const requestImageBytes =
|
|
39603
|
+
const requestImageBytes = requestInlineImageBytes(sentBuild.options, images, sentImageReferenceKeys);
|
|
39115
39604
|
const trimmedKeys = new Set(collectRemainingImageKeys(imageTrimmed, images));
|
|
39116
39605
|
const sentKeys = new Set(collectRemainingImageKeys(sentBuild.options, images));
|
|
39117
39606
|
const bodyFitDroppedKeys = [...trimmedKeys].filter((key) => !sentKeys.has(key));
|
|
@@ -39127,6 +39616,8 @@ var KimiCodeAdapter = class extends LlmAdapter {
|
|
|
39127
39616
|
const reader = response.body.getReader();
|
|
39128
39617
|
const decoder = new TextDecoder();
|
|
39129
39618
|
const state = createStreamState$5(wire, requestOptions.sessionId, sideChannel);
|
|
39619
|
+
state.accountId = servedByAccountId;
|
|
39620
|
+
diagnosticState = state;
|
|
39130
39621
|
applyCacheWriteTiers(state, response.headers);
|
|
39131
39622
|
if (!sideChannel) markSessionActive(requestOptions.sessionId);
|
|
39132
39623
|
let buffer = "";
|
|
@@ -39170,14 +39661,42 @@ var KimiCodeAdapter = class extends LlmAdapter {
|
|
|
39170
39661
|
}
|
|
39171
39662
|
} catch (error) {
|
|
39172
39663
|
const inBand = state.streamError;
|
|
39173
|
-
if (error instanceof LlmError && !outputStarted && error.code === "PROVIDER_ERROR" && inBand !== void 0) throw await this.inBandStreamFailure(error, inBand, servedByAccountId);
|
|
39664
|
+
if (error instanceof LlmError && !outputStarted && error.code === "PROVIDER_ERROR" && inBand !== void 0) throw await this.inBandStreamFailure(error, inBand, servedByAccountId, retrySignal, requestDiagnostic.attempts.at(-1));
|
|
39174
39665
|
throw streamFailure(error, signal);
|
|
39175
39666
|
}
|
|
39176
39667
|
} finally {
|
|
39177
|
-
if (state.sawUsage && !sideChannel) noteSessionCacheState(requestOptions.sessionId ?? state.sessionId, state);
|
|
39178
39668
|
reader.cancel().catch(() => void 0);
|
|
39179
39669
|
}
|
|
39670
|
+
} catch (error) {
|
|
39671
|
+
if (error instanceof LlmError && isKimiToolArgumentGuardCode(error.code)) rememberSameAccountRetry(retrySignal, diagnosticState?.accountId);
|
|
39672
|
+
requestError = error;
|
|
39673
|
+
throw error;
|
|
39180
39674
|
} finally {
|
|
39675
|
+
const endedAt = Date.now();
|
|
39676
|
+
const finalAccountId = diagnosticState?.accountId ?? requestDiagnostic.accountId ?? requestDiagnostic.attempts.at(-1)?.accountId;
|
|
39677
|
+
const errorCode = requestError instanceof LlmError ? requestError.code : requestError === void 0 ? void 0 : "UNKNOWN";
|
|
39678
|
+
const lastAttempt = requestDiagnostic.attempts.at(-1);
|
|
39679
|
+
if (lastAttempt !== void 0 && errorCode !== void 0) {
|
|
39680
|
+
lastAttempt.code = errorCode;
|
|
39681
|
+
lastAttempt.endedAt ??= endedAt;
|
|
39682
|
+
}
|
|
39683
|
+
requestDiagnostic.endedAt = endedAt;
|
|
39684
|
+
if (finalAccountId !== void 0) requestDiagnostic.accountId = finalAccountId;
|
|
39685
|
+
requestDiagnostic.accountChanged = previousAccountId !== void 0 && finalAccountId !== void 0 && previousAccountId !== finalAccountId;
|
|
39686
|
+
requestDiagnostic.outcome = retrySignal?.aborted === true || errorCode === "ABORTED" ? "aborted" : requestError === void 0 && diagnosticState?.finished === true ? "success" : "error";
|
|
39687
|
+
if (errorCode !== void 0) requestDiagnostic.code = errorCode;
|
|
39688
|
+
else if (requestDiagnostic.outcome === "error") requestDiagnostic.code = "INCOMPLETE_STREAM";
|
|
39689
|
+
if (diagnosticState?.finishReason !== null && diagnosticState?.finishReason !== void 0) requestDiagnostic.finishReason = diagnosticState.finishReason;
|
|
39690
|
+
if (diagnosticState?.sawUsage === true) requestDiagnostic.usage = {
|
|
39691
|
+
freshTokens: diagnosticState.inputTokens,
|
|
39692
|
+
cacheReadTokens: diagnosticState.cacheReadReported ? diagnosticState.cacheReadTokens : null,
|
|
39693
|
+
cacheWriteTokens: diagnosticState.cacheWriteReported ? diagnosticState.cacheWriteTokens : null,
|
|
39694
|
+
outputTokens: diagnosticState.outputTokens,
|
|
39695
|
+
reasoningTokens: diagnosticState.reasoningReported ? diagnosticState.reasoningTokens : null
|
|
39696
|
+
};
|
|
39697
|
+
if (diagnosticState?.toolGuard !== void 0) requestDiagnostic.toolGuard = diagnosticState.toolGuard;
|
|
39698
|
+
if (!sideChannel && sessionKey !== "") if (diagnosticState?.sawUsage === true) noteSessionCacheState(diagnosticState.sessionId, diagnosticState, requestError === void 0 && diagnosticState.finished, requestDiagnostic);
|
|
39699
|
+
else sessionCacheState.noteRequest(sessionKey, requestDiagnostic);
|
|
39181
39700
|
mainHeaderRelease();
|
|
39182
39701
|
}
|
|
39183
39702
|
}
|
|
@@ -39197,37 +39716,32 @@ var KimiCodeAdapter = class extends LlmAdapter {
|
|
|
39197
39716
|
* re-issued: its body is already open and part-read, and the harness retry
|
|
39198
39717
|
* policy owns the repeat.
|
|
39199
39718
|
*/
|
|
39200
|
-
async inBandStreamFailure(thrown, inBand, accountId) {
|
|
39719
|
+
async inBandStreamFailure(thrown, inBand, accountId, retrySignal, attemptDiagnostic) {
|
|
39201
39720
|
const bodyText = JSON.stringify({ error: inBand.error });
|
|
39202
39721
|
const reclassified = inBand.vocabulary === "anthropic" ? reclassifyInBandError(thrown, inBand.error, classifyKimiFailure) : reclassifyInBandResponsesError(thrown, inBand.error, inBand.message, classifyKimiFailure);
|
|
39203
39722
|
const pool = this.accountPool;
|
|
39204
39723
|
if (pool === null || accountId === void 0) return reclassified;
|
|
39724
|
+
let action = "none";
|
|
39205
39725
|
if (inBand.vocabulary === "anthropic") {
|
|
39206
39726
|
const status = inBandAnthropicStatus(inBand.error);
|
|
39207
39727
|
if (status === null) return reclassified;
|
|
39208
|
-
|
|
39209
|
-
|
|
39210
|
-
|
|
39211
|
-
|
|
39212
|
-
|
|
39728
|
+
action = classifyKimiFailure(status, bodyText).poolAction;
|
|
39729
|
+
} else if (reclassified.code === "RATE_LIMIT" || matchesAny$1(bodyText, QUOTA_EXHAUSTED_PATTERNS$1)) action = classifyKimiFailure(429, bodyText).poolAction;
|
|
39730
|
+
else if (reclassified.code === "SERVER") action = "retry-same-account";
|
|
39731
|
+
if (attemptDiagnostic !== void 0) {
|
|
39732
|
+
attemptDiagnostic.code = reclassified.code;
|
|
39733
|
+
attemptDiagnostic.poolAction = action;
|
|
39734
|
+
attemptDiagnostic.endedAt = Date.now();
|
|
39735
|
+
}
|
|
39736
|
+
if (action === "retry-same-account") {
|
|
39737
|
+
rememberSameAccountRetry(retrySignal, accountId);
|
|
39213
39738
|
return reclassified;
|
|
39214
39739
|
}
|
|
39215
|
-
|
|
39740
|
+
clearSameAccountRetry(retrySignal);
|
|
39741
|
+
if (action === "cooldown-and-rotate") await pool.markCooldown(accountId, accountLimitCooldownMs(bodyText), `${PROVIDER_NAME$8} in-stream limit`).catch(() => void 0);
|
|
39742
|
+
else if (action === "mark-auth-failed") await pool.markAuthFailed(accountId, reclassified.message).catch(() => void 0);
|
|
39216
39743
|
return reclassified;
|
|
39217
39744
|
}
|
|
39218
|
-
/**
|
|
39219
|
-
* Cool the account whose own rate limit the stream reported.
|
|
39220
|
-
*
|
|
39221
|
-
* The window this route already defaults to, never a Retry-After: there is no
|
|
39222
|
-
* 429 response to read one from, and a delay stated on the 200 belongs to a
|
|
39223
|
-
* different message. An account-scoped verdict takes its own window instead,
|
|
39224
|
-
* because a spent balance is not back-pressure and 15 minutes would put the
|
|
39225
|
-
* account back into rotation four times inside the window that refused it.
|
|
39226
|
-
*/
|
|
39227
|
-
async coolInBandRateLimit(pool, accountId, accountScoped, bodyText) {
|
|
39228
|
-
const cooldownMs = accountScoped ? accountLimitCooldownMs(bodyText) : POOL_COOLDOWN_MS$5;
|
|
39229
|
-
await pool.markCooldown(accountId, cooldownMs, `${PROVIDER_NAME$8} in-stream 429`).catch(() => void 0);
|
|
39230
|
-
}
|
|
39231
39745
|
};
|
|
39232
39746
|
function isRefreshTimeout(error) {
|
|
39233
39747
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -39756,17 +40270,45 @@ function openingInheritanceOf(sessionId) {
|
|
|
39756
40270
|
hitRatio: Math.min(1, Math.max(0, cachedTokens / promptTokens))
|
|
39757
40271
|
};
|
|
39758
40272
|
}
|
|
40273
|
+
/**
|
|
40274
|
+
* Latest request's continuity against the previous prompt's observed 256-token
|
|
40275
|
+
* alignment baseline. Raw counts travel with the ratio so an above-baseline
|
|
40276
|
+
* reading stays visible instead of being hidden by clamping.
|
|
40277
|
+
*/
|
|
40278
|
+
function continuationOf(sessionId) {
|
|
40279
|
+
const durable = sessionCacheState.read(sessionId);
|
|
40280
|
+
const cachedTokens = durable?.lastRequestCachedTokens;
|
|
40281
|
+
const freshTokens = durable?.lastRequestFreshTokens;
|
|
40282
|
+
const previousPromptTokens = durable?.previousRequestPromptTokens;
|
|
40283
|
+
if (cachedTokens === void 0 || freshTokens === void 0 || previousPromptTokens === void 0) return void 0;
|
|
40284
|
+
const expectedCachedTokens = Math.floor(previousPromptTokens / 256) * 256;
|
|
40285
|
+
if (expectedCachedTokens <= 0) return void 0;
|
|
40286
|
+
return {
|
|
40287
|
+
cachedTokens,
|
|
40288
|
+
freshTokens,
|
|
40289
|
+
previousPromptTokens,
|
|
40290
|
+
expectedCachedTokens,
|
|
40291
|
+
retentionRatio: Math.min(1, Math.max(0, cachedTokens / expectedCachedTokens))
|
|
40292
|
+
};
|
|
40293
|
+
}
|
|
40294
|
+
function lastRequestDiagnosticOf(sessionId) {
|
|
40295
|
+
return sessionCacheState.read(sessionId)?.recentRequests?.at(-1);
|
|
40296
|
+
}
|
|
39759
40297
|
function cacheStatsOrNull(sessionId) {
|
|
39760
40298
|
const stats = getCacheStats(sessionId);
|
|
39761
40299
|
if (stats.requests === 0) return durableCacheStats(sessionId);
|
|
39762
40300
|
const lastDrift = getLastDriftCause(sessionId);
|
|
39763
40301
|
const warmup = warmupStatusOf(sessionId);
|
|
39764
40302
|
const opening = openingInheritanceOf(sessionId);
|
|
40303
|
+
const continuation = continuationOf(sessionId);
|
|
40304
|
+
const lastRequest = lastRequestDiagnosticOf(sessionId);
|
|
39765
40305
|
return {
|
|
39766
40306
|
...stats,
|
|
39767
40307
|
...lastDrift === void 0 ? {} : { lastDrift },
|
|
39768
40308
|
...warmup === void 0 ? {} : { warmup },
|
|
39769
40309
|
...opening === void 0 ? {} : { opening },
|
|
40310
|
+
...continuation === void 0 ? {} : { continuation },
|
|
40311
|
+
...lastRequest === void 0 ? {} : { lastRequest },
|
|
39770
40312
|
imageBudget: imageBudgetOf(sessionId),
|
|
39771
40313
|
cacheWriteTokens: stats.cacheWriteTokens,
|
|
39772
40314
|
cacheWrite5mTokens: stats.cacheWrite5mTokens,
|
|
@@ -39807,10 +40349,12 @@ function cacheHintOrNull(sessionId) {
|
|
|
39807
40349
|
*/
|
|
39808
40350
|
function durableCacheStats(sessionId) {
|
|
39809
40351
|
const durable = sessionCacheState.read(sessionId);
|
|
39810
|
-
if (durable === void 0 || durable.requests === 0) return null;
|
|
40352
|
+
if (durable === void 0 || durable.requests === 0 && durable.recentRequests === void 0) return null;
|
|
39811
40353
|
const lastDrift = driftCauseOf(durable.lastDrift);
|
|
39812
40354
|
const warmup = warmupStatusOf(sessionId);
|
|
39813
40355
|
const opening = openingInheritanceOf(sessionId);
|
|
40356
|
+
const continuation = continuationOf(sessionId);
|
|
40357
|
+
const lastRequest = lastRequestDiagnosticOf(sessionId);
|
|
39814
40358
|
return {
|
|
39815
40359
|
requests: durable.requests,
|
|
39816
40360
|
cachedTokens: durable.cachedTokens,
|
|
@@ -39823,6 +40367,8 @@ function durableCacheStats(sessionId) {
|
|
|
39823
40367
|
...lastDrift === void 0 ? {} : { lastDrift },
|
|
39824
40368
|
...warmup === void 0 ? {} : { warmup },
|
|
39825
40369
|
...opening === void 0 ? {} : { opening },
|
|
40370
|
+
...continuation === void 0 ? {} : { continuation },
|
|
40371
|
+
...lastRequest === void 0 ? {} : { lastRequest },
|
|
39826
40372
|
imageBudget: imageBudgetOf(sessionId)
|
|
39827
40373
|
};
|
|
39828
40374
|
}
|
|
@@ -49761,6 +50307,83 @@ function installKimiRepeatBreaker(ctx, options = {}) {
|
|
|
49761
50307
|
};
|
|
49762
50308
|
}
|
|
49763
50309
|
//#endregion
|
|
50310
|
+
//#region src/host/kimi-code/tool-argument-recovery.ts
|
|
50311
|
+
/**
|
|
50312
|
+
* One guided retry after a Kimi tool-argument stream enters a runaway shape.
|
|
50313
|
+
*
|
|
50314
|
+
* The failed attempt is already settled before `agent/request-error` runs. The
|
|
50315
|
+
* recovery notice is appended AFTER it, so the next same-step deriveMessages()
|
|
50316
|
+
* sees the instruction without changing the system prompt or tool declarations.
|
|
50317
|
+
* `agent.steer()` is deliberately not used: it targets a later step boundary.
|
|
50318
|
+
*/
|
|
50319
|
+
const MAX_RECOVERY_STEPS = 256;
|
|
50320
|
+
function text$4(value) {
|
|
50321
|
+
return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
|
|
50322
|
+
}
|
|
50323
|
+
function number(value) {
|
|
50324
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
|
|
50325
|
+
}
|
|
50326
|
+
/** The model-facing recovery instruction; raw tool arguments never enter it. */
|
|
50327
|
+
function createKimiToolArgumentRecoveryMessage(code) {
|
|
50328
|
+
const repeated = code === TOOL_ARGUMENT_REPEATED_KEY_CODE;
|
|
50329
|
+
return createUserMessage$1({
|
|
50330
|
+
content: [{
|
|
50331
|
+
type: "text",
|
|
50332
|
+
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."
|
|
50333
|
+
}],
|
|
50334
|
+
source: {
|
|
50335
|
+
kind: PLUGIN_MESSAGE_SOURCE_KIND,
|
|
50336
|
+
form: "notice",
|
|
50337
|
+
summary: boundContextSummary(repeated ? "Runaway tool arguments: retry once with fresh minimal JSON." : "Oversized tool arguments: retry once with a smaller payload.")
|
|
50338
|
+
}
|
|
50339
|
+
});
|
|
50340
|
+
}
|
|
50341
|
+
/** Install the one-per-step request recovery hook. */
|
|
50342
|
+
function installKimiToolArgumentRecovery(ctx) {
|
|
50343
|
+
const attempted = /* @__PURE__ */ new Set();
|
|
50344
|
+
const clearAgent = (raw) => {
|
|
50345
|
+
const agent = raw;
|
|
50346
|
+
const sessionId = text$4(agent?.session?.id) ?? text$4(agent?.id);
|
|
50347
|
+
if (sessionId === void 0) return;
|
|
50348
|
+
const prefix = sessionId + ":";
|
|
50349
|
+
for (const key of [...attempted]) if (key.startsWith(prefix)) attempted.delete(key);
|
|
50350
|
+
};
|
|
50351
|
+
const disposeRequestError = ctx.on?.("agent/request-error", (async (payload, next) => {
|
|
50352
|
+
const code = payload.failure?.code;
|
|
50353
|
+
if (payload.provider !== "kimi-code" || !isKimiToolArgumentGuardCode(code)) return await next();
|
|
50354
|
+
if (payload.signal?.aborted === true) return await next();
|
|
50355
|
+
const agent = payload.agent;
|
|
50356
|
+
const sessionId = text$4(agent?.session?.id) ?? text$4(agent?.id);
|
|
50357
|
+
const turn = number(payload.turn);
|
|
50358
|
+
const step = number(payload.step);
|
|
50359
|
+
const session = agent?.session;
|
|
50360
|
+
const append = session?.append;
|
|
50361
|
+
if (sessionId === void 0 || turn === void 0 || step === void 0 || session === void 0 || append === void 0) return await next();
|
|
50362
|
+
const key = `${sessionId}:${turn}:${step}`;
|
|
50363
|
+
if (attempted.has(key)) return await next();
|
|
50364
|
+
const message = createKimiToolArgumentRecoveryMessage(code);
|
|
50365
|
+
try {
|
|
50366
|
+
append.call(session, "user/message", message, { surfaceOp: "append" });
|
|
50367
|
+
} catch {
|
|
50368
|
+
return await next();
|
|
50369
|
+
}
|
|
50370
|
+
attempted.add(key);
|
|
50371
|
+
while (attempted.size > MAX_RECOVERY_STEPS) {
|
|
50372
|
+
const oldest = attempted.keys().next();
|
|
50373
|
+
if (oldest.done !== true) attempted.delete(oldest.value);
|
|
50374
|
+
}
|
|
50375
|
+
return { kind: "retry" };
|
|
50376
|
+
}));
|
|
50377
|
+
const disposeDisposed = ctx.on?.("agent/disposed", ((payload) => {
|
|
50378
|
+
clearAgent(payload?.agent);
|
|
50379
|
+
}));
|
|
50380
|
+
return () => {
|
|
50381
|
+
disposeRequestError?.();
|
|
50382
|
+
disposeDisposed?.();
|
|
50383
|
+
attempted.clear();
|
|
50384
|
+
};
|
|
50385
|
+
}
|
|
50386
|
+
//#endregion
|
|
49764
50387
|
//#region src/host/minimax-code/account-pool.ts
|
|
49765
50388
|
/**
|
|
49766
50389
|
* MiniMax Code 号池:the account pool for the MiniMax Code (编程订阅) line.
|
|
@@ -64533,6 +65156,7 @@ var GlmCodingPlanAdapter = class extends LlmAdapter {
|
|
|
64533
65156
|
preferences;
|
|
64534
65157
|
accountPool;
|
|
64535
65158
|
options;
|
|
65159
|
+
catalogRegionSnapshot;
|
|
64536
65160
|
constructor(store = new GlmCodingPlanCredentialStore(), modelSettings = new GlmCodingPlanModelSettingsStore(), preferences, options = {}) {
|
|
64537
65161
|
super();
|
|
64538
65162
|
this.store = store;
|
|
@@ -64565,6 +65189,38 @@ var GlmCodingPlanAdapter = class extends LlmAdapter {
|
|
|
64565
65189
|
return cached.length > 0 ? cached : modelsForRegion(region, GLM_MODEL_CATALOG);
|
|
64566
65190
|
}
|
|
64567
65191
|
/**
|
|
65192
|
+
* 模型目录只需要区域,不需要一把可发请求的凭据。
|
|
65193
|
+
*
|
|
65194
|
+
* 这里刻意不调用 credentialFor:那是真实请求的选号入口,会重复解密号池并回写
|
|
65195
|
+
* lastUsedAt。目录构建会为每个模型并发调用 resolveModel,把它放在这里会让一次
|
|
65196
|
+
* 选择器刷新放大成一串 DPAPI 读写。区域快照按号池 revision 与指定账号失效,
|
|
65197
|
+
* 同一代的并发调用共享同一次只读;读不到或尚未登录时不缓存,登录后即可重试。
|
|
65198
|
+
*/
|
|
65199
|
+
catalogRegion(settings) {
|
|
65200
|
+
const pool = this.accountPool;
|
|
65201
|
+
if (pool === null) return this.readCatalogRegion(settings).catch(() => null);
|
|
65202
|
+
const revision = pool.currentIdentityRevision();
|
|
65203
|
+
const selectedAccountId = settings.selectedAccountId;
|
|
65204
|
+
const cached = this.catalogRegionSnapshot;
|
|
65205
|
+
if (cached !== void 0 && cached.revision === revision && cached.selectedAccountId === selectedAccountId) return cached.region;
|
|
65206
|
+
const snapshot = {
|
|
65207
|
+
revision,
|
|
65208
|
+
selectedAccountId,
|
|
65209
|
+
region: this.readCatalogRegion(settings).catch(() => null)
|
|
65210
|
+
};
|
|
65211
|
+
this.catalogRegionSnapshot = snapshot;
|
|
65212
|
+
snapshot.region.then((region) => {
|
|
65213
|
+
if (region === null && this.catalogRegionSnapshot === snapshot) this.catalogRegionSnapshot = void 0;
|
|
65214
|
+
});
|
|
65215
|
+
return snapshot.region;
|
|
65216
|
+
}
|
|
65217
|
+
async readCatalogRegion(settings) {
|
|
65218
|
+
if (this.accountPool === null) return (await this.store.read())?.codingPlan.region ?? null;
|
|
65219
|
+
const data = await this.accountPool.read();
|
|
65220
|
+
const usable = data.accounts.filter((account) => account.authStatus === void 0 || account.authStatus === "ok");
|
|
65221
|
+
return (usable.find((account) => account.id === settings.selectedAccountId) ?? usable.find((account) => account.id === data.activeAccountId) ?? usable.find((account) => account.isPrimary) ?? usable[0])?.credentials.codingPlan.region ?? null;
|
|
65222
|
+
}
|
|
65223
|
+
/**
|
|
64568
65224
|
* 这一行请求用哪份凭据。
|
|
64569
65225
|
*
|
|
64570
65226
|
* 有池时轮转;没有池时读单凭据存储(无头 host 与测试的形态)。
|
|
@@ -64589,10 +65245,9 @@ var GlmCodingPlanAdapter = class extends LlmAdapter {
|
|
|
64589
65245
|
async listModels(provider) {
|
|
64590
65246
|
const prov = provider || PROVIDER_ID$1;
|
|
64591
65247
|
const settings = await this.settings();
|
|
64592
|
-
if (settings.enabled === false) return [];
|
|
64593
|
-
const
|
|
64594
|
-
if (
|
|
64595
|
-
const region = pick.credentials.codingPlan.region;
|
|
65248
|
+
if (settings.enabled === false || settings.enabledModelIds.length === 0) return [];
|
|
65249
|
+
const region = await this.catalogRegion(settings);
|
|
65250
|
+
if (region === null) return [];
|
|
64596
65251
|
const available = this.catalog(region);
|
|
64597
65252
|
const enabled = new Set(settings.enabledModelIds);
|
|
64598
65253
|
return available.filter((model) => model.wire !== null && enabled.has(model.id)).map((model) => ({
|
|
@@ -64605,7 +65260,7 @@ var GlmCodingPlanAdapter = class extends LlmAdapter {
|
|
|
64605
65260
|
async resolveModel(provider, model, signal) {
|
|
64606
65261
|
if (signal?.aborted) throw new LlmError(t("glm.modelResolveAborted", { provider: PROVIDER_NAME$1 }), "ABORTED");
|
|
64607
65262
|
const settings = await this.settings();
|
|
64608
|
-
const region =
|
|
65263
|
+
const region = await this.catalogRegion(settings) ?? "intl";
|
|
64609
65264
|
const entry = resolveGlmModel(model, this.catalog(region));
|
|
64610
65265
|
const override = settings.contextWindowOverrides[model];
|
|
64611
65266
|
const contextWindow = typeof override === "number" && Number.isFinite(override) && override > 0 ? override : entry.defaultContextWindow;
|
|
@@ -97338,10 +97993,10 @@ function installCacheWarmup(ctx, options) {
|
|
|
97338
97993
|
const blocks = decision.content ?? result.content;
|
|
97339
97994
|
if (blocks.length === 0) return decision;
|
|
97340
97995
|
const baseNavigation = retrievalTool || ptcRetrieval ? cacheWarmupNavigationIntentOf(exec.agent) : void 0;
|
|
97341
|
-
const
|
|
97996
|
+
const isSearchPreviewCandidate = (exec.name === "grep" || exec.name === "glob") && blocks.reduce((sum, block) => {
|
|
97342
97997
|
return sum + (typeof block === "object" && block !== null && typeof block.text === "string" ? block.text : "").length;
|
|
97343
|
-
}, 0) >=
|
|
97344
|
-
const navigation = baseNavigation === true ||
|
|
97998
|
+
}, 0) >= CACHE_WARMUP_DEFAULTS.warmupMaxChars;
|
|
97999
|
+
const navigation = baseNavigation === true || isSearchPreviewCandidate ? true : baseNavigation;
|
|
97345
98000
|
if (retrievalTool && navigation !== true) return decision;
|
|
97346
98001
|
if (sourceTool && !settings.enabled && navigation !== true) return decision;
|
|
97347
98002
|
const route = cacheWarmupRouteOf(exec.agent);
|
|
@@ -105967,6 +106622,7 @@ function apply(ctx, pluginConfig = {}) {
|
|
|
105967
106622
|
providers: CONTROLLED_PROVIDERS.filter((provider) => provider !== "minimax-code"),
|
|
105968
106623
|
globalEnabled: () => resolveToolRunawayGuardEnabled(pluginConfig)
|
|
105969
106624
|
}), "dsh-chatgpt-subscription: shared tool runaway guard");
|
|
106625
|
+
ctx.effect(() => installKimiToolArgumentRecovery(ctx), "dsh-chatgpt-subscription: Kimi tool argument recovery");
|
|
105970
106626
|
ctx.effect(() => installDispatchExecutionGuard(ctx, { enabled: () => resolveDispatchExecutionGuardEnabled(pluginConfig) }), "dsh-chatgpt-subscription: dispatch execution guard");
|
|
105971
106627
|
ctx.effect(() => installDispatchLedger(ctx, {
|
|
105972
106628
|
enabled: () => resolveDispatchExecutionGuardEnabled(pluginConfig),
|