Skip to content

Commit 070ad37

Browse files
committed
Merge remote-tracking branch 'origin/dev' into lane/pr-8077
2 parents e86d440 + 8a82a46 commit 070ad37

27 files changed

Lines changed: 607 additions & 42 deletions

‎docs-site/src/content/docs/reference/adapters.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,8 @@ For Meta Responses at the exact `api.meta.ai` host, OpenCodex omits the unsuppor
274274
`output.encrypted_content` include requested by Codex Desktop. Meta otherwise rejects the
275275
request before inference. `reasoning.encrypted_content` and other include entries remain
276276
intact, so stateless reasoning replay is preserved. The same exact-entry normalization
277-
applies to xAI; unrelated Responses destinations keep their original include list.
277+
applies to xAI and to Kimi Code at its exact HTTPS Responses endpoint
278+
(`https://api.kimi.com/coding/v1/responses`); unrelated Responses destinations keep their original include list.
278279

279280
These request-shape fixes do not change account entitlements. Meta limits Muse Code
280281
subscription credentials to the Muse Code client; other clients require a separately

‎docs-site/src/content/docs/reference/configuration/server.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -806,7 +806,9 @@ native compaction model.
806806

807807
OpenCodex changes only requests with explicit `request_kind: "compaction"` metadata whose
808808
`compaction.trigger` is one of the values you listed, sent to `/v1/responses/compact` or to
809-
`/v1/responses` with a `compaction_trigger` input item. Later conversation turns keep their
809+
`/v1/responses` with a `compaction_trigger` input item. With `codexClientCompaction` enabled,
810+
the local checkpoint prompt also matches when metadata specifies `compaction.implementation` as
811+
`"responses"`; it remains a normal text summary request. Later conversation turns keep their
810812
original routing and settings. Missing, malformed, or conflicting metadata does not activate the
811813
override, including on older clients without trigger metadata; when several copies of the
812814
metadata are supplied they must name the same trigger. WebSocket requests use each frame's

‎scripts/test-layout/layout.json‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@
9494
"codex-config-preservation.test.ts": "codex-integration",
9595
"codex-credits.test.ts": "codex-integration",
9696
"codex-credits-settings.test.ts": "codex-integration",
97-
"codex-credits-probes.test.ts": "codex-integration",
97+
"codex-credits-probes.test.ts": "codex-integration", "pool-monthly-window-retirement.test.ts": "codex-integration",
9898
"codex-credits-after-limit.test.ts": "codex-integration",
9999
"codex-pool-credit-policy.test.ts": "codex-integration", "codex-credit-retry-after.test.ts": "codex-integration", "codex-credit-scoped-retry.test.ts": "codex-integration",
100100
"codex-sidecar-credit-policy.test.ts": "codex-integration",
@@ -1330,11 +1330,11 @@
13301330
"ocx-launcher-desktop-handoff.test.ts": "cli", "cli-path-diagnostics.test.ts": "cli",
13311331
"ocx-launcher-source.test.ts": "cli",
13321332
"ocx-run.test.ts": "cli",
1333-
"ollama-native-parser.test.ts": "providers/ollama", "ollama-native-reasoning-wire.test.ts": "providers/ollama", "ollama-native-structured-output.test.ts": "providers/ollama", "ollama-native-tool-continuations.test.ts": "providers/ollama",
1333+
"ollama-native-parser.test.ts": "providers/ollama", "ollama-native-cached-usage.test.ts": "providers/ollama", "ollama-native-reasoning-wire.test.ts": "providers/ollama", "ollama-native-structured-output.test.ts": "providers/ollama", "ollama-native-tool-continuations.test.ts": "providers/ollama",
13341334
"ollama-native-v4.test.ts": "providers/ollama", "ollama-native-scaling.test.ts": "providers/ollama", "ollama-native.test.ts": "providers/ollama", "ollama-show-enrichment-v7.test.ts": "providers/ollama", "ollama-show-enrichment.test.ts": "providers/ollama",
13351335
"ollama-show-ignore-abort.test.ts": "providers/ollama",
13361336
"opaque-blob-wrapped-rejection.test.ts": "responses", "openai-api-virtual-models.test.ts": "adapters/openai", "openai-chat-bounded-tool-names.test.ts": "adapters/openai", "openai-chat-dangling-toolcalls.test.ts": "adapters/openai",
1337-
"openai-chat-developer-position.test.ts": "adapters/openai", "openai-chat-eof.test.ts": "adapters/openai", "openai-chat-hardening.test.ts": "adapters/openai", "openai-empty-assistant-history.test.ts": "adapters/openai", "openai-chat-image-normalization.test.ts": "adapters/openai",
1337+
"openai-chat-developer-position.test.ts": "adapters/openai", "openai-chat-eof.test.ts": "adapters/openai", "openai-chat-hardening.test.ts": "adapters/openai", "openai-empty-assistant-history.test.ts": "adapters/openai", "kimi-coding-output-include.test.ts": "providers", "openai-chat-image-normalization.test.ts": "adapters/openai",
13381338
"openai-chat-inline-think-tags.test.ts": "adapters/openai", "openai-chat-invalid-tool-call-diagnostics.test.ts": "adapters/openai", "openai-chat-mistral-content.test.ts": "adapters/openai", "openai-chat-model-suffix.test.ts": "adapters/openai", "openai-chat-native-policy.test.ts": "adapters/openai",
13391339
"openai-chat-parallel-stream.test.ts": "adapters/openai", "openai-chat-path-override.test.ts": "adapters/openai", "openai-chat-qwen38-leading-system.test.ts": "adapters/openai", "openai-chat-reasoning-wire-policy.test.ts": "adapters/openai",
13401340
"openai-chat-sanitization-review-regressions.test.ts": "adapters/openai", "openai-chat-serialized-tool-call-content.test.ts": "adapters/openai", "openai-chat-serialized-tool-call-hold-bound.test.ts": "adapters/openai", "openai-chat-serialized-tool-call-think.test.ts": "adapters/openai",
@@ -1537,7 +1537,7 @@
15371537
"responses-code-mode-patch-compile.test.ts": "responses",
15381538
"responses-code-mode-shell-compile.test.ts": "responses",
15391539
"responses-compact-handoff-admission.test.ts": "responses",
1540-
"responses-compaction-override.test.ts": "responses",
1540+
"responses-compaction-override.test.ts": "responses", "local-checkpoint-routing.test.ts": "responses",
15411541
"responses-compaction-policy-identity.test.ts": "responses",
15421542
"responses-compaction-http-isolation.test.ts": "responses", "responses-compaction-routing.test.ts": "responses",
15431543
"native-compaction-gateway.test.ts": "responses", "native-compaction-gateway-policy.test.ts": "responses", "native-compaction-provenance.test.ts": "responses", "native-compaction-oauth.test.ts": "responses", "native-compaction-gateway-credentials.test.ts": "responses", "responses-compaction.test.ts": "responses",

‎src/adapters/ollama-native.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -641,7 +641,17 @@ function usageFromNative(value: JsonRecord | undefined): OcxUsage | undefined {
641641
const input = isFiniteNonNegativeInteger(value.prompt_eval_count) ? value.prompt_eval_count : undefined;
642642
const output = isFiniteNonNegativeInteger(value.eval_count) ? value.eval_count : undefined;
643643
if (input === undefined && output === undefined) return undefined;
644-
return { inputTokens: input ?? 0, outputTokens: output ?? 0 };
644+
// Ollama reports prompt_eval_cached_count as the cached subset of prompt_eval_count (api/types.go;
645+
// its CLI prints prompt_eval_count - cached as the uncached share), which is OCX's cache-read
646+
// convention. Omitted means unknown, so no cache field is invented; a count that exceeds the
647+
// prompt is not a subset and is ignored rather than clamped (#8101).
648+
const cached = input !== undefined && isFiniteNonNegativeInteger(value.prompt_eval_cached_count)
649+
&& value.prompt_eval_cached_count <= input ? value.prompt_eval_cached_count : undefined;
650+
return {
651+
inputTokens: input ?? 0,
652+
outputTokens: output ?? 0,
653+
...(cached !== undefined ? { cachedInputTokens: cached, cacheReadInputTokens: cached } : {}),
654+
};
645655
}
646656

647657
function stopReasonFromNative(value: unknown): string | undefined {

‎src/adapters/openai-responses/empty-assistant.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,23 @@ function isEmptyAssistantMessage(item: unknown): boolean {
1616
return item.content === "" || (Array.isArray(item.content) && item.content.every(isEmptyTextPart));
1717
}
1818

19+
/** Exactly Kimi Code's native Responses endpoint; lookalike hosts and other Kimi paths do not match. */
20+
export function isKimiCodingResponsesUrl(responseUrl: string): boolean {
21+
let url: URL;
22+
try { url = new URL(responseUrl); } catch { return false; }
23+
return url.hostname === "api.kimi.com" && /^\/coding\/v1\/responses\/?$/.test(url.pathname);
24+
}
25+
26+
/** The same endpoint over HTTPS on the default port only, for request rewrites scoped to Kimi Code itself. */
27+
export function isKimiCodingResponsesHttpsUrl(responseUrl: string): boolean {
28+
if (!isKimiCodingResponsesUrl(responseUrl)) return false;
29+
const url = new URL(responseUrl);
30+
return url.protocol === "https:" && url.port === "";
31+
}
32+
1933
/** Kimi Code rejects content-empty assistant messages even on its native Responses endpoint. */
2034
export function stripKimiEmptyAssistantMessages(body: unknown, responseUrl: string): unknown {
21-
let url: URL;
22-
try { url = new URL(responseUrl); } catch { return body; }
23-
if (url.hostname !== "api.kimi.com" || !/^\/coding\/v1\/responses\/?$/.test(url.pathname)) return body;
35+
if (!isKimiCodingResponsesUrl(responseUrl)) return body;
2436
if (!isPlainObject(body) || !Array.isArray(body.input)) return body;
2537
const referencedIds = new Set<string>();
2638
for (const item of body.input) {

‎src/adapters/openai-responses/passthrough.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ import { observeOutbound } from "../../usage/cache-diagnostic";
5757
import { normalizeMuseToolCatalog } from "./muse-tool-catalog";
5858
import { normalizeMuseToolChoice } from "./muse-tool-choice";
5959
import { declaresHostedWebSearch, projectHostedSearchHistory, renderCompactionSearchHistoryItems } from "./compaction-search-history";
60-
import { stripKimiEmptyAssistantMessages } from "./empty-assistant";
60+
import { isKimiCodingResponsesHttpsUrl, stripKimiEmptyAssistantMessages } from "./empty-assistant";
6161
import { normalizeOpenGatewayResponsesInput } from "./opengateway-input";
6262

6363
/**
@@ -358,12 +358,13 @@ export function createResponsesPassthroughAdapter(provider: OcxProviderConfig):
358358
// OpenCode Go speaks the same dialect, which the final model id and URL identify.
359359
outBody = normalizeXaiResponsesWebSearch(outBody, provider, { modelId: parsed.modelId, responseUrl: url });
360360
outBody = injectXaiResponsesXSearch(outBody, provider, parsed._replayPrefixLen);
361-
// xAI, Meta and Azure answer 400 for `output.encrypted_content` instead of ignoring it;
362-
// Codex Desktop asks for it on every turn (#7878).
361+
// xAI, Meta, Azure and Kimi Code (#8075) answer 400 for `output.encrypted_content`
362+
// instead of ignoring it; Codex Desktop asks for it on every turn (#7878).
363363
// Azure also rejects this exact include entry, including on plain Responses routes.
364364
const isAzureResponses = provider.adapter === "azure" || provider.adapter === "azure-openai"
365365
|| new URL(url).hostname.toLowerCase().endsWith(".openai.azure.com");
366-
if (isXaiResponsesDestination(provider) || isMetaAiResponsesDestination(url) || isAzureResponses) {
366+
if (isXaiResponsesDestination(provider) || isMetaAiResponsesDestination(url) || isAzureResponses
367+
|| isKimiCodingResponsesHttpsUrl(url)) {
367368
outBody = stripUnsupportedOutputInclude(outBody);
368369
}
369370
// xAI and explicitly classified compatible gateways reject these OpenAI web_search

‎src/adapters/openai-responses/request-strips.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { activateDeferredTool } from "./tool-schema";
88
import { stripOpenAiOnlyWebSearchFields } from "./web-search";
99

1010
/**
11-
* Codex requests output.encrypted_content, which xAI, Meta and Azure reject with HTTP 400.
11+
* Codex requests output.encrypted_content, which xAI, Meta, Azure and Kimi Code reject with HTTP 400.
1212
* The caller gates this on the destination. Preserve reasoning.encrypted_content
1313
* for stateless replay and leave unknown or malformed values for upstream validation.
1414
*/

‎src/codex/quota.ts‎

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ type QuotaDiskFile = {
3838

3939
type MainPolicyQuota = { identityKey: string; quota: StoredAccountQuota };
4040
/** Fresh WHAM topology proof is consumed by the merge, never retained in a cache or DTO. */
41-
type MainPolicyQuotaObservation = Omit<StoredAccountQuota, "updatedAt"> & { shortWindowAbsent?: true };
41+
type MainPolicyQuotaObservation = Omit<StoredAccountQuota, "updatedAt"> & { shortWindowAbsent?: true; monthlyWindowAbsent?: true };
4242
let mainPolicyQuota: MainPolicyQuota | null = null;
4343
let diskHydrated = false;
4444
let persistTimer: ReturnType<typeof setTimeout> | null = null;
@@ -343,9 +343,12 @@ export function setAccountQuotaFromParsed(
343343
// Retiring a short tuple releases a routing block, so it needs the same writer proof as
344344
// history: a live main writer for main, a live captured pool writer for pool requests.
345345
const mayRetireShort = isMain ? mainWriter !== undefined : livePoolEvidence;
346-
const displayQuota: MainPolicyQuotaObservation = mayRetireShort && policyQuota?.shortWindowAbsent === true
347-
? { ...quota, shortWindowAbsent: true }
348-
: quota;
346+
// Monthly-window absence (#8067) comes from the same complete topology and needs the same proof.
347+
const displayQuota: MainPolicyQuotaObservation = {
348+
...quota,
349+
...(mayRetireShort && policyQuota?.shortWindowAbsent === true ? { shortWindowAbsent: true as const } : {}),
350+
...(mayRetireShort && policyQuota?.monthlyWindowAbsent === true ? { monthlyWindowAbsent: true as const } : {}),
351+
};
349352
const next = mergeAccountQuota(displayQuota, legacyExisting, updatedAt);
350353
accountQuota.set(accountId, next);
351354
if (isMain) {
@@ -448,8 +451,11 @@ function mergeAccountQuota(
448451
// while silently dropping `monthlyIsPrimaryWindow` would look like tertiary-only data to
449452
// any future reader, and that failure would be invisible.
450453
if (quota.monthlyIsPrimaryWindow === true) next.monthlyIsPrimaryWindow = true;
451-
} else if ((snapshotHasWeekly(quota) || snapshotHasShort(quota) || snapshotHasCustom(quota))
454+
} else if (quota.monthlyWindowAbsent !== true
455+
&& (snapshotHasWeekly(quota) || snapshotHasShort(quota) || snapshotHasCustom(quota))
452456
&& existing?.monthlyPercent !== undefined) {
457+
// A complete topology with no monthly-length window retires the carried tuple, so a plan
458+
// change away from a monthly primary (Free to Pro Lite) cannot keep its old exhausted reading.
453459
next.monthlyPercent = existing.monthlyPercent;
454460
if (existing.monthlyResetAt !== undefined) next.monthlyResetAt = existing.monthlyResetAt;
455461
if (existing.monthlyIsPrimaryWindow === true) next.monthlyIsPrimaryWindow = true;
@@ -991,7 +997,17 @@ export function poolWhamPolicyObservation(
991997
}
992998
const malformed = readings.some(window => window?.used_percent != null
993999
&& normalizeUsagePercent(window.used_percent) === undefined);
994-
return data.rate_limit?.allowed === false || malformed ? quota : withWhamShortWindowAbsence(data, quota);
1000+
if (data.rate_limit?.allowed === false || malformed) return quota;
1001+
const observation = withWhamShortWindowAbsence(data, quota);
1002+
// #8067: the same complete topology proves a pool account has no monthly window when no window
1003+
// declares a monthly duration and no tertiary window is present, so a plan change away from a
1004+
// monthly primary (Free to Pro Lite) retires the carried tuple. Pool-only: main observations
1005+
// keep their existing retention rules.
1006+
const [primary, secondary, tertiary] = [data.rate_limit?.primary_window, data.rate_limit?.secondary_window, data.rate_limit?.tertiary_window];
1007+
return observation.shortWindowAbsent === true
1008+
&& !isExplicitMonthlyWindow(primary) && !isExplicitMonthlyWindow(secondary) && tertiary == null
1009+
? { ...observation, monthlyWindowAbsent: true }
1010+
: observation;
9951011
}
9961012

9971013
function isMeasuredLongWindow(window: WhamUsageWindow | null | undefined): boolean {

‎src/responses/compaction-history-framing.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@ function plainUserText(item: unknown): string | null {
2121
return texts.join("\n");
2222
}
2323

24+
export function isLocalCompactionCheckpoint(input: unknown): boolean {
25+
return Array.isArray(input) && plainUserText(input.at(-1))?.trim() === COMPACT_PROMPT;
26+
}
27+
2428
function isContext(text: string): boolean {
2529
const head = text.trimStart();
2630
return head.startsWith("<") || head.startsWith("# AGENTS.md") || head.startsWith("# Context from my IDE");
@@ -44,7 +48,7 @@ export function frameCompactionHistory<T extends { input?: unknown; instructions
4448
if (!Array.isArray(input) || input.some(item => isRecord(item) && item.type === "compaction_trigger")) return body;
4549
// Codex local compaction appends this user prompt without a compaction_trigger.
4650
// Keep that summarizer turn free of generation-only continuation instructions.
47-
if (plainUserText(input.at(-1))?.trim() === COMPACT_PROMPT) return body;
51+
if (isLocalCompactionCheckpoint(input)) return body;
4852
let checkpointIndex = -1;
4953
for (let index = input.length - 1; index >= 0; index--) {
5054
if (isCheckpoint(input[index])) {
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import { Buffer } from "node:buffer";
2+
3+
type Frame =
4+
| { items: readonly unknown[]; index: number }
5+
| { record: Record<string, unknown>; keys: readonly string[]; index: number };
6+
7+
/**
8+
* UTF-8 byte length of JSON.stringify(value) for a JSON.parse result, computed without
9+
* recursion: a valid body nested deeper than the call stack must be measured, not crash.
10+
* Each open container keeps one cursor frame, so arrays add no per-element queue; an object
11+
* frame retains its key list, which stays bounded by the input size.
12+
*/
13+
export function serializedJsonByteLength(value: unknown): number {
14+
let bytes = 0;
15+
const stack: Frame[] = [];
16+
const visit = (item: unknown): void => {
17+
if (item === null || typeof item !== "object") {
18+
bytes += Buffer.byteLength(JSON.stringify(item) ?? "null", "utf8");
19+
} else if (Array.isArray(item)) {
20+
bytes += 2 + Math.max(0, item.length - 1);
21+
stack.push({ items: item, index: 0 });
22+
} else {
23+
const record = item as Record<string, unknown>;
24+
const keys = Object.keys(record);
25+
bytes += 2 + Math.max(0, keys.length - 1);
26+
stack.push({ record, keys, index: 0 });
27+
}
28+
};
29+
visit(value);
30+
while (stack.length > 0) {
31+
const frame = stack[stack.length - 1]!;
32+
if ("items" in frame) {
33+
if (frame.index < frame.items.length) visit(frame.items[frame.index++]);
34+
else stack.pop();
35+
} else if (frame.index < frame.keys.length) {
36+
const key = frame.keys[frame.index++]!;
37+
bytes += Buffer.byteLength(JSON.stringify(key), "utf8") + 1;
38+
visit(frame.record[key]);
39+
} else {
40+
stack.pop();
41+
}
42+
}
43+
return bytes;
44+
}

0 commit comments

Comments
 (0)