Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
67 commits
Select commit Hold shift + click to select a range
fe9fe3f
fix: ignore stale keepalive response bodies after rearming
Afloat16 Nov 10, 2026
850ce16
fix: collect expired witness rings during record-only traffic
Afloat16 Nov 10, 2026
c9e9152
docs: clarify witness hash index lifecycle
Afloat16 Nov 10, 2026
2480d88
fix: scope image encodes to their resize policy
Afloat16 Nov 10, 2026
1eb3843
fix: repair incomplete image spills when originals are resent
Afloat16 Nov 10, 2026
c7e39ee
fix: separate IPv6 socket hosts from CONNECT authorities
Afloat16 Nov 10, 2026
d016f55
fix: select the requested prompt pack from npm dependencies
Afloat16 Nov 10, 2026
ba57b82
test: register pack installer subprocess suite
Afloat16 Nov 10, 2026
6ce4cdb
fix: refresh upstream CA cache on configured path changes
Afloat16 Nov 10, 2026
9664b82
fix: strip credentials from loopback diagnostic URLs
Afloat16 Nov 10, 2026
1c9c015
fix: recognize legal JPEG marker fill during image billing
Afloat16 Nov 10, 2026
f04031c
fix: parse summary SSE data fields as complete events
Afloat16 Nov 10, 2026
9d0f00a
fix: preserve runaway guard frame boundaries across chunks
Afloat16 Nov 10, 2026
ecd228a
test: pin the NDJSON opening-token gate with a discriminating case
Awork Nov 10, 2026
ff1a5c5
fix: harden runaway guard NDJSON mode selection; document framing rules
Nov 10, 2026
267d3b2
fix: avoid recursive runaway guard traversal of provider JSON
Afloat16 Nov 10, 2026
4a94a8f
test: pin leaf feed order in the deep-JSON runaway-guard tests
Nov 10, 2026
cafe414
fix: propagate upstream error-body failures without replay
Afloat16 Nov 11, 2026
269b821
fix: honor native compaction JSON terminal status
Afloat16 Nov 10, 2026
be1b8a7
test(#6135): pin that a completed claim carrying a real error still f…
Nov 10, 2026
bfda2f1
fix: classify native compaction only from complete SSE events
Afloat16 Nov 10, 2026
c31fd99
fix: repair overlapping tool groups with a linear sweep
Afloat16 Nov 10, 2026
ed11b64
fix(storage): retain malformed records during session garbage collection
Afloat16 Nov 10, 2026
f19df89
fix(server): validate catalog identity before replaying 304 responses
Afloat16 Nov 10, 2026
9faf34b
fix(google): account for images nested in tool responses
Afloat16 Nov 10, 2026
fb85a22
test(google): pin the image/* note gate negative direction for nested…
Nov 10, 2026
01e8159
fix: index Gemini inline images referenced by function responses
Afloat16 Nov 11, 2026
42ec722
fix: stabilize identity for requests carrying multiple credentials
Afloat16 Nov 11, 2026
cceb76c
fix: bracket IPv6 addresses in port-holder health probes
Afloat16 Nov 11, 2026
6b00739
fix: give every automatic decompression spill a unique file
Afloat16 Nov 11, 2026
368f29e
docs: restore #1207-F4 provenance and 0600 rationale in the range-spi…
Nov 11, 2026
69a547c
docs: point the range-spill comment at #6191 (was #6175, an unrelated…
Nov 11, 2026
ee81005
fix: limit Google inline media shedding to declared images
Afloat16 Nov 11, 2026
6c6b803
fix: select image downscale work after archiving
Afloat16 Nov 11, 2026
4bb1216
fix: decode BMP dimensions by DIB header layout
Afloat16 Nov 11, 2026
b0f263b
fix: correct CORE header offsets so real spec-valid BMPs parse (#6179)
Nov 11, 2026
3cb1158
fix: ground BMP CORE dimensions in encoder output
Afloat16 Nov 11, 2026
217070e
docs: record BMP DIB field offsets in bmpDims (#6179)
Nov 11, 2026
d300f4b
fix(kimi): preserve TOML integer model limits
Afloat16 Nov 11, 2026
b8f3053
fix(config): apply strict TOML integers to sibling model readers
Afloat16 Nov 11, 2026
baf19a1
docs: register shared TOML integer reader in architecture map
Afloat16 Nov 11, 2026
78c6c22
fix: restore archive content ownership per reference
Afloat16 Nov 11, 2026
5adb837
fix: replace archive logs atomically after restore
Afloat16 Nov 11, 2026
468b9f5
test: scope archive permission checks to POSIX
Afloat16 Nov 11, 2026
851c57f
fix: enforce extension storage validation across backends
Afloat16 Nov 11, 2026
81724e1
fix: accept completed summaries with empty tool call arrays
Afloat16 Nov 11, 2026
7b615ed
fix: bound uncovered message range queries
Afloat16 Nov 11, 2026
6407af8
fix: honor output paths for JSONL exports
Afloat16 Nov 11, 2026
0064fb4
test: accept platform-specific export destination errors
Afloat16 Nov 11, 2026
9c09ed2
fix: honor leading Windows proxy bypass wildcards
Afloat16 Nov 11, 2026
b27b5fe
fix: preserve deferred WebSocket listener options and close state
Afloat16 Nov 11, 2026
3390724
fix: expand Responses WebSocket history in linear time
Afloat16 Nov 11, 2026
f72e13a
fix: recover Responses turns with string input
Afloat16 Nov 11, 2026
185ad09
fix(storage): include prototype-named JSON fields in verification dig…
Afloat16 Nov 11, 2026
6250e07
fix: redact JSON-escaped home paths in published diagnostics
Afloat16 Nov 11, 2026
cad59f3
fix: recognize valid JSON layouts in raw media accounting
Afloat16 Nov 11, 2026
e895255
fix(storage): preserve extension timestamps across archive restore
Afloat16 Nov 11, 2026
56d979b
fix: exclude tool data from keepalive TTL detection
Afloat16 Nov 11, 2026
4e7e3b1
fix(storage): treat malformed integrity caches as misses
Afloat16 Nov 11, 2026
2d145b4
fix: enforce readable byte limit before credential store replacement
Afloat16 Nov 11, 2026
8e7c804
perf(storage): append split media without copying prior entries
Afloat16 Nov 11, 2026
c6fa0c9
fix(summary): keep exponential backoff for blank Retry-After headers
Afloat16 Nov 11, 2026
23bcd2e
fix(storage): skip non-object JSONL entries when locating archives
Afloat16 Nov 11, 2026
853cb9c
fix(render): avoid argument limits when locating large fold anchors
Afloat16 Nov 11, 2026
702b5b0
perf(affinity): construct only sampled SimHash shingles
Afloat16 Nov 11, 2026
87611b3
fix(storage): match KV key prefixes literally
Afloat16 Nov 11, 2026
65f036c
fix(ci): preserve live fork PR runs during janitor cleanup
Afloat16 Nov 11, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions .github/workflows/ci-janitor.yml
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ jobs:
warned=0

collect() {
gh api --paginate --jq '.workflow_runs[] | [.id, .status, .created_at, .event, (.head_branch // "")] | @tsv' \
gh api --paginate --jq '.workflow_runs[] | [.id, .status, .created_at, .event, (.head_branch // "-"), (.head_repository.full_name // "-")] | @tsv' \
"repos/$REPO/actions/runs?status=$1&per_page=100"
}
{ collect queued; collect in_progress; } | sort -u > /tmp/janitor-runs.tsv
Expand Down Expand Up @@ -111,7 +111,7 @@ jobs:
# Actions job, so EVERY rule below (zombie reap, age limits, master
# warnings) was dead code from day one (2026-10-30). Feed the collected
# list explicitly.
while IFS=$'\t' read -r id status created event branch; do
while IFS=$'\t' read -r id status created event branch head_repo; do
if [ "$id" = "$SELF_ID" ]; then continue; fi
age_min=$(( (now - $(date -d "$created" +%s)) / 60 ))

Expand All @@ -122,9 +122,12 @@ jobs:
fi

reason=""
if [ "$event" = "pull_request" ] && [ -n "$branch" ]; then
if ! gh api "repos/$REPO/branches/$branch" >/dev/null 2>&1; then
reason="head branch '$branch' deleted"
if [ "$event" = "pull_request" ] && [ "$branch" != "-" ] && [ "$head_repo" != "-" ]; then
branch_ref=$(jq -rn --arg ref "$branch" '$ref | @uri')
branch_response=$(gh api --include "repos/$head_repo/branches/$branch_ref" 2>/dev/null) || true
branch_status=$(printf '%s\n' "$branch_response" | awk 'NR == 1 { print $2 }')
if [ "$branch_status" = "404" ] && gh api "repos/$head_repo" >/dev/null 2>&1; then
reason="head branch '$head_repo:$branch' deleted"
fi
fi
if [ -z "$reason" ] && [ "$status" = "queued" ] && [ "$starve_mode" = "1" ] && [ "$STARVED_QUEUE_MAX" -gt 0 ]; then
Expand Down
1 change: 1 addition & 0 deletions reference/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ billion-context/
│ ├── kiro.ts # Kiro CLI: model-gateway hosts, built-in developer/system→user roles, kiro:conversation_id identity
│ ├── launcher.ts # `bili <client>` launcher (auto-proxies both schemes)
│ ├── client-config.ts # Read-only discovery of each client's own upstream config
│ ├── toml-integer.ts # Shared strict TOML integer reader for model token limits
│ ├── plugin.ts # Cooperative plugin protocol (x-bili-plugin lane, legacy marker #920)
│ ├── plugin-install.ts # `bili plugin install` driving host channels
│ ├── dsh-channel.ts # dsh profile bundle management (refreshDshProfileCopy, #1196)
Expand Down
35 changes: 35 additions & 0 deletions scripts/bench-media-split.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Run with: node --expose-gc --import tsx scripts/bench-media-split.mjs [count]
import { createHash } from "node:crypto";
import { performance } from "node:perf_hooks";
import { splitMediaContent } from "../src/storage/identity.ts";

const count = Number(process.argv[2] ?? 20_000);
if (!Number.isSafeInteger(count) || count < 1 || count > 0xffff_ffff) {
throw new Error("count must be a positive 32-bit integer");
}
const urls = Array.from({ length: count }, (_, i) => {
const prefix = Buffer.alloc(6);
prefix.writeUInt32BE(i, 2);
return `data:image/png;base64,${prefix.toString("base64")}${"A".repeat(2040)}`;
});
const content = JSON.stringify({ rawResponsesItem: urls });
const timings = [];
let digest;
for (let i = 0; i < 4; i++) {
global.gc?.();
const started = performance.now();
const result = splitMediaContent(content);
const ms = performance.now() - started;
if (result.media.length !== count) throw new Error(`expected ${count} media rows`);
const signature = createHash("sha256").update(JSON.stringify(result)).digest("hex");
if (digest && digest !== signature) throw new Error("non-deterministic output");
digest = signature;
if (i > 0) timings.push(ms);
}
console.log(JSON.stringify({
count,
bytes: Buffer.byteLength(content),
timings_ms: timings,
median_ms: [...timings].sort((a, b) => a - b)[1],
digest,
}));
26 changes: 26 additions & 0 deletions scripts/bench-simhash-sampling.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Run with: node --max-old-space-size=512 --expose-gc --import tsx scripts/bench-simhash-sampling.mjs [tokens]
import { performance } from "node:perf_hooks";
import { simhashHex } from "../src/affinity-simhash.ts";

const count = Number(process.argv[2] ?? 1_000_000);
if (!Number.isSafeInteger(count) || count < 1) throw new Error("tokens must be a positive safe integer");
const canonical = Array.from({ length: count }, (_, i) => `word${i % 997}`).join(" ");
const timings = [];
let sketch;
for (let i = 0; i < 4; i++) {
global.gc?.();
const start = performance.now();
const result = simhashHex(canonical);
const elapsed = performance.now() - start;
if (sketch !== undefined && sketch !== result) throw new Error("unstable sketch");
sketch = result;
if (i > 0) timings.push(elapsed);
}
console.log(JSON.stringify({
count,
bytes: Buffer.byteLength(canonical),
sketch,
timings_ms: timings,
median_ms: [...timings].sort((a, b) => a - b)[1],
max_rss_kib: process.resourceUsage().maxRSS,
}));
27 changes: 27 additions & 0 deletions scripts/bench-ws-history.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import assert from "node:assert/strict";
import { ResponsesWsHistory } from "../src/responses-ws.ts";

const turns = 6_000;
const history = new ResponsesWsHistory();
const expected: unknown[] = [];
for (let i = 0; i < turns; i++) {
const tail = [{ type: "message", role: "user", content: `question-${i}` }];
const output = [{ type: "message", role: "assistant", content: `answer-${i}` }];
expected.push(...tail, ...output);
history.commit({ model: "m", input: tail }, { id: `r${i}`, status: "completed", output },
i === 0 ? undefined : { continuedId: `r${i - 1}`, tail });
}
const frame = { type: "response.create", previous_response_id: `r${turns - 1}`, input: [] };
assert.deepEqual(history.expand(frame).input, expected);
const milliseconds: number[] = [];
for (let sample = 0; sample < 7; sample++) {
const start = process.hrtime.bigint();
const expanded = history.expand(frame);
milliseconds.push(Number(process.hrtime.bigint() - start) / 1e6);
assert.deepEqual(expanded.input, expected);
}
console.log(JSON.stringify({
turns, outputItems: expected.length, milliseconds,
medianMs: [...milliseconds].sort((a, b) => a - b)[3],
exactOrderChecked: true,
}, null, 2));
5 changes: 5 additions & 0 deletions scripts/live-files.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,11 @@ export const LIVE_FILES = [
// child binds no port and does no network I/O, so no zone band is needed —
// the entry is for the tripwire alone, like #3890/#5114
"tests/integrity-worker-stderr.test.ts",
// Real npm pack/install children use mkdtemp package fixtures and the
// preload's per-process XDG roots; they bind no listener ports.
"tests/pack-install.test.ts",
// Runs the Linux janitor shell against per-case local API fixtures; no ports or credentials.
"tests/ci-janitor-fork-heads.test.ts",
];

/** Band width per live file: the zone ladder drifts +1 per EADDRINUSE retry;
Expand Down
23 changes: 8 additions & 15 deletions src/affinity-simhash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,22 +54,15 @@ function fnv1a32(text: string, basis: number): number {
* so a short message still yields a stable, comparable sketch. */
export function simhashHex(canonical: string): string {
const tokens = canonical.match(/[\p{L}\p{N}_]+/gu) ?? [];
const features: string[] = [];
if (tokens.length < 2) {
for (const t of tokens) features.push(t);
} else {
for (let i = 0; i + 1 < tokens.length; i++) features.push(`${tokens[i]}\u0001${tokens[i + 1]}`);
}
if (features.length === 0) {
// No word tokens at all (pure punctuation/whitespace): hash the raw
// string so even that degenerate case is deterministic and comparable.
features.push(canonical);
}
const stride = Math.max(1, Math.ceil(features.length / MAX_FEATURES));
const featureCount = Math.max(1, tokens.length - 1);
const stride = Math.max(1, Math.ceil(featureCount / MAX_FEATURES));
const v = new Int16Array(64);
for (let f = 0; f < features.length; f += stride) {
const h1 = fnv1a32(features[f]!, 2166136261);
const h2 = fnv1a32(features[f]!, 2166136261 ^ 0x9e3779b9);
for (let f = 0; f < featureCount; f += stride) {
// Construct only sampled shingles, not an additional full-size array
// for a long message. No-token inputs still hash the raw string.
const feature = tokens.length < 2 ? (tokens[0] ?? canonical) : `${tokens[f]}\u0001${tokens[f + 1]}`;
const h1 = fnv1a32(feature, 2166136261);
const h2 = fnv1a32(feature, 2166136261 ^ 0x9e3779b9);
for (let b = 0; b < 64; b++) {
const bit = b < 32 ? (h1 >>> b) & 1 : (h2 >>> (b - 32)) & 1;
v[b] += bit === 1 ? 1 : -1;
Expand Down
49 changes: 40 additions & 9 deletions src/agent/native-ws-intercept.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,15 @@ interface EventListenerObject {
}
type WsEventTargetOptions = { capture?: boolean; once?: boolean; passive?: boolean; signal?: AbortSignal } | boolean;

interface DeferredListener {
el: EventListener | EventListenerObject;
capture: boolean;
once: boolean;
passive?: boolean;
signal?: AbortSignal;
onAbort?: () => void;
}

const WS_INTERCEPT_FLAG = Symbol.for("billion-context.native-ws-intercept");
const OWN_MARKER = Symbol.for("billion-context.native-ws-intercept.own");

Expand Down Expand Up @@ -219,7 +228,7 @@ class DeferredWebSocket {
private cancelled = false;
private closed = false;
private settled = false;
private listeners = new Map<string, Array<{ el: EventListener | EventListenerObject; once: boolean }>>();
private listeners = new Map<string, DeferredListener[]>();
private handlers: Partial<Record<"onopen" | "onerror" | "onclose" | "onmessage", EventListener | null>> = {};
private binaryTypeOverride: string | undefined;

Expand Down Expand Up @@ -260,8 +269,14 @@ class DeferredWebSocket {
if (this.real !== undefined) return;
this.real = real;
for (const [type, entries] of this.listeners) {
for (const entry of entries) real.addEventListener(type, entry.el, { once: entry.once });
for (const entry of entries) {
if (entry.onAbort) entry.signal?.removeEventListener("abort", entry.onAbort);
real.addEventListener(type, entry.el, {
capture: entry.capture, once: entry.once, passive: entry.passive, signal: entry.signal,
});
}
}
this.listeners.clear();
for (const key of ["onopen", "onerror", "onclose", "onmessage"] as const) {
const handler = this.handlers[key];
if (handler !== undefined) real[key] = handler;
Expand All @@ -275,32 +290,47 @@ class DeferredWebSocket {
return;
}
if (listener === null) return;
const once = typeof options === "object" && options !== null ? options.once === true : options === true;
const detail = typeof options === "object" && options !== null ? options : undefined;
if (detail?.signal?.aborted) return;
const capture = typeof options === "boolean" ? options : detail?.capture === true;
const list = this.listeners.get(type) ?? [];
list.push({ el: listener, once });
if (list.some(entry => entry.el === listener && entry.capture === capture)) return;
const entry: DeferredListener = {
el: listener, capture, once: detail?.once === true, passive: detail?.passive, signal: detail?.signal,
};
if (entry.signal) {
entry.onAbort = () => this.removeEventListener(type, listener, { capture });
entry.signal.addEventListener("abort", entry.onAbort, { once: true });
}
list.push(entry);
this.listeners.set(type, list);
}

removeEventListener(type: string, listener: EventListener | EventListenerObject | null, _options?: WsEventTargetOptions): void {
removeEventListener(type: string, listener: EventListener | EventListenerObject | null, options?: WsEventTargetOptions): void {
if (this.real !== undefined) {
this.real.removeEventListener(type, listener, _options);
this.real.removeEventListener(type, listener, options);
return;
}
if (listener === null) return;
const capture = typeof options === "boolean" ? options : options?.capture === true;
const list = this.listeners.get(type);
if (list !== undefined) {
const at = list.findIndex((entry) => entry.el === listener);
if (at >= 0) list.splice(at, 1);
const at = list.findIndex((entry) => entry.el === listener && entry.capture === capture);
if (at >= 0) {
const [entry] = list.splice(at, 1);
if (entry.onAbort) entry.signal?.removeEventListener("abort", entry.onAbort);
}
if (list.length === 0) this.listeners.delete(type);
}
}

dispatchEvent(event: Event): boolean {
if (this.real !== undefined) return this.real.dispatchEvent(event);
for (const entry of [...(this.listeners.get(event.type) ?? [])]) {
if (!this.listeners.get(event.type)?.includes(entry)) continue;
if (entry.once) this.removeEventListener(event.type, entry.el, { capture: entry.capture });
if (typeof entry.el === "function") entry.el.call(this, event);
else entry.el.handleEvent(event);
if (entry.once) this.removeEventListener(event.type, entry.el);
}
// A real EventTarget fires the on* handler property alongside listeners —
// a client registered via ws.onclose = fn must not miss a window-phase
Expand All @@ -326,6 +356,7 @@ class DeferredWebSocket {
if (this.cancelled || this.closed) return;
this.cancelled = true;
queueMicrotask(() => {
this.closed = true;
const event = new Event("close");
Object.assign(event, { code: 1006, reason: "", wasClean: false });
this.dispatchEvent(event);
Expand Down
12 changes: 9 additions & 3 deletions src/cache-keepalive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,9 @@ export function resolveCacheKeepalive(routes: ProviderRoutes | undefined, upstre
};
}

/** Pure: the TTL tier declared by the snapshot's cache_control breakpoints —
* any "1h" wins over "5m"; undefined when the body carries none. */
/** Pure: the TTL tier declared by the snapshot's cache_control breakpoints.
* Tool inputs and schema examples are data, not directives. Any "1h" wins
* over "5m"; undefined when the body carries no breakpoint. */
export function detectKeepaliveTier(body: unknown): "5m" | "1h" | undefined {
let found: "5m" | "1h" | undefined;
const walk = (n: unknown): void => {
Expand All @@ -137,7 +138,11 @@ export function detectKeepaliveTier(body: unknown): "5m" | "1h" | undefined {
// explicit "1h" lifts the tier.
found = "5m";
}
for (const v of Object.values(o)) walk(v);
for (const [key, value] of Object.entries(o)) {
if (key === "input_schema") continue;
if (key === "input" && (o.type === "tool_use" || o.type === "server_tool_use")) continue;
walk(value);
}
};
walk(body);
return found;
Expand Down Expand Up @@ -379,6 +384,7 @@ async function firePing(entry: KeepaliveEntry): Promise<void> {
entry.pingInFlight = false;
if (registry.get(entry.sessionId) !== entry) return;
const text = await resp.text().catch(() => "");
if (registry.get(entry.sessionId) !== entry) return;
if (!resp.ok) {
if (resp.status === 429) {
disarm(entry.sessionId, "rate-limited(429)");
Expand Down
15 changes: 11 additions & 4 deletions src/cache-ledger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -658,7 +658,8 @@ export const CREDENTIAL_HEADER_NAMES = ["authorization", "x-api-key", "api-key",
* returns undefined when the lane sent no recognized credential header. */
export function credentialFingerprint(headers: Record<string, string> | undefined | null): string | undefined {
if (!headers) return undefined;
let cred: string | undefined;
const values = new Set<string>();
const fields = new Set<string>();
for (const [name, value] of Object.entries(headers)) {
const n = name.toLowerCase();
if ((CREDENTIAL_HEADER_NAMES as readonly string[]).includes(n)) {
Expand All @@ -677,12 +678,18 @@ export function credentialFingerprint(headers: Record<string, string> | undefine
// per request. The STABLE credential on that line is the
// Access key id — fingerprint only that.
const m = /^SDK-HMAC-SHA256\s+Access=([^\s,]+)/i.exec(v);
cred = m !== null ? `sdk-hmac:${m[1]!}` : v;
break;
const credential = m !== null ? `sdk-hmac:${m[1]!}` : v;
values.add(credential);
fields.add(JSON.stringify([n, credential]));
}
}
}
if (cred === undefined) return undefined;
if (values.size === 0) return undefined;
// Keep existing single-key identities, including aliases carrying the
// same key. Distinct credentials form an order-independent identity so
// header iteration order cannot bypass or cross-clear a throttle hold.
const cred = values.size === 1 ? values.values().next().value!
: `credential-set:${JSON.stringify([...fields].sort())}`;
return "sha256:" + createHash("sha256").update(cred, "utf8").digest("hex").slice(0, 12);
}

Expand Down
15 changes: 9 additions & 6 deletions src/client-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import os from "node:os";
import path from "node:path";
import { parse as parseJsonc, type ParseError } from "jsonc-parser";
import { vertexEnabled } from "./vertex.js";
import { nonNegativeTomlInteger } from "./toml-integer.js";

export interface ClaudeSettings {
anthropicBaseUrl?: string;
Expand Down Expand Up @@ -720,7 +721,7 @@ export function parseCodexToml(text: string): CodexConfig {
continue;
}
const strMatch = /^([A-Za-z0-9_.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/.exec(line);
const numMatch = /^([A-Za-z0-9_.-]+)\s*=\s*([0-9]+)\b/.exec(line);
const numMatch = /^([A-Za-z0-9_.-]+)\s*=\s*([^\s#]+)\s*(?:#.*)?$/.exec(line);
if (strMatch) {
const key = strMatch[1];
const val = strMatch[2] !== undefined ? strMatch[2] : strMatch[3];
Expand All @@ -733,9 +734,11 @@ export function parseCodexToml(text: string): CodexConfig {
result.providers[curProvider].baseUrl = val;
}
} else if (numMatch && table === "") {
if (numMatch[1] === "model_context_window") codexContextWindow = Number(numMatch[2]);
else if (numMatch[1] === "model_auto_compact_token_limit") codexAutoCompactLimit = Number(numMatch[2]);
else if (numMatch[1] === "model_max_output_tokens") codexMaxOutput = Number(numMatch[2]);
const numVal = nonNegativeTomlInteger(numMatch[2]);
if (numVal === undefined) continue;
if (numMatch[1] === "model_context_window") codexContextWindow = numVal;
else if (numMatch[1] === "model_auto_compact_token_limit") codexAutoCompactLimit = numVal;
else if (numMatch[1] === "model_max_output_tokens") codexMaxOutput = numVal;
}
}
if (codexModel) result.model = codexModel;
Expand Down Expand Up @@ -1079,11 +1082,11 @@ export function parseKimiToml(text: string): KimiConfig {
continue;
}
const strMatch = /^([A-Za-z0-9_.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/.exec(line);
const numMatch = /^([A-Za-z0-9_.-]+)\s*=\s*([0-9]+)\b/.exec(line);
const numMatch = /^([A-Za-z0-9_.-]+)\s*=\s*([^\s#]+)\s*(?:#.*)?$/.exec(line);
if (!strMatch && !numMatch) continue;
const key = (strMatch ?? numMatch)![1];
const strVal = strMatch ? (strMatch[2] !== undefined ? strMatch[2] : strMatch[3]) : undefined;
const numVal = numMatch ? Number(numMatch[2]) : undefined;
const numVal = numMatch ? nonNegativeTomlInteger(numMatch[2]) : undefined;
if (parts.length === 0) {
if (key === "default_model" && strVal !== undefined) result.defaultModel = strVal;
} else if (parts[0] === "providers") {
Expand Down
Loading
Loading