Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 3 additions & 0 deletions scripts/check-dist-import-annotations.d.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export declare function findRelativeImportRefs(text: string): string[];

export declare function checkDistImportAnnotations(distDir: string): Array<{ file: string; refs: string[] }>;
2 changes: 1 addition & 1 deletion src/agent/dsh-native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ type ToolDefinition = {

type CommandOutcome = { kind: "success" | "error"; text: string };

type PluginContext = {
export type PluginContext = {
tools: { register: (definition: ToolDefinition) => unknown };
commands: { register: (command: { name: string; description: string; handler: (invocation?: CommandInvocation) => Promise<CommandOutcome> }) => unknown };
agents: { currentInitiator?: () => AgentLike | undefined };
Expand Down
2 changes: 1 addition & 1 deletion src/agent/opencode-native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ export function _resetNativeStateForTest(): void {

// ———— OpenCode 1.x native surface (V1 `.server()`) ————————————————————

type ZodLike = typeof import("zod");
export type ZodLike = typeof import("zod");

interface V1ToolContext {
sessionID: string;
Expand Down
6 changes: 3 additions & 3 deletions src/agent/opencode-v2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,14 +105,14 @@ interface V2CatalogModelEntry {

export interface V2PluginContext {
session?: {
hook?: (name: string, cb: (e: V2HttpRequestEvent) => void | Promise<void>) => void | Promise<V2Registration | undefined>;
hook?: (name: string, cb: (e: V2HttpRequestEvent) => void | Promise<void>) => V2Registration | void | Promise<V2Registration | undefined>;
synthetic?: (input: { sessionID: string; text: string; description?: string; resume?: boolean }) => Promise<unknown>;
};
tool?: {
transform?: (cb: (editor: V2ToolEditor) => void) => void | Promise<V2Registration | undefined>;
transform?: (cb: (editor: V2ToolEditor) => void) => V2Registration | void | Promise<V2Registration | undefined>;
};
command?: {
transform?: (cb: (editor: V2CommandEditor) => void) => void | Promise<V2Registration | undefined>;
transform?: (cb: (editor: V2CommandEditor) => void) => V2Registration | void | Promise<V2Registration | undefined>;
};
event?: { subscribe?: (opts?: { signal?: AbortSignal }) => AsyncIterable<{ type?: unknown; data?: Record<string, unknown> }> | undefined };
/** v2.0.x stable (probed @opencode/cli 2.0.18): ModelApi.list() →
Expand Down
4 changes: 2 additions & 2 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -598,7 +598,7 @@ export async function main(): Promise<void> {
// affected range (rollback-form advisories cover latest too).
advisoryBlocksVersion,
onStaleInstall: createAutoRestartHandler({
enabled: opts.autoRestartOnUpdate,
enabled: opts.autoRestartOnUpdate ?? false,
packageName: PACKAGE_NAME,
server,
host: opts.host,
Expand All @@ -619,7 +619,7 @@ export async function main(): Promise<void> {
advisoryUrl: opts.advisoryUrl,
resolveProxy: (url) => resolveProxy(opts.routes, opts.proxy, url, opts.proxyFallback),
onStaleInstall: createAutoRestartHandler({
enabled: opts.autoRestartOnUpdate,
enabled: opts.autoRestartOnUpdate ?? false,
packageName: PACKAGE_NAME,
server,
host: opts.host,
Expand Down
18 changes: 11 additions & 7 deletions src/client-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,9 @@ export interface OmpProvider {
}

export interface OmpConfig {
providers: Record<string, OmpProvider>;
/** Discovery tolerates a lane with no discovered providers (`?? {}` at
* every read site) — optional here matches that (#1991 item 5). */
providers?: Record<string, OmpProvider>;
}

export interface OpencodeProvider {
Expand All @@ -86,7 +88,9 @@ export interface OpencodeProvider {
}

export interface OpencodeConfig {
providers: Record<string, OpencodeProvider>;
/** Discovery tolerates a lane with no discovered providers (`?? {}` at
* every read site) — optional here matches that (#1991 item 5). */
providers?: Record<string, OpencodeProvider>;
}

/** opencode's built-in "zen" gateway (`opencode auth login`): the baseURL
Expand Down Expand Up @@ -1037,7 +1041,7 @@ export function readPiConfig(piHome: string): PiConfig {
* so it tolerates the file's base indent.
*/
export function parseOmpYaml(text: string): OmpConfig {
const result: OmpConfig = { providers: {} };
const providers: Record<string, OmpProvider> = {};
let providersIndent = -1;
let providerIndent = -1;
let currentProvider: string | null = null;
Expand All @@ -1050,7 +1054,7 @@ export function parseOmpYaml(text: string): OmpConfig {
if (pending === undefined || currentProvider === null) { pending = undefined; return; }
const win = toModelWindow(pending.id, pending.contextWindow, pending.maxOutput);
if (win) {
const prov = result.providers[currentProvider]!;
const prov = providers[currentProvider]!;
prov.models = [...(prov.models ?? []), win];
}
pending = undefined;
Expand All @@ -1072,7 +1076,7 @@ export function parseOmpYaml(text: string): OmpConfig {
const m = /^([A-Za-z0-9_.-]+):/.exec(trimmed);
if (m) {
currentProvider = m[1];
if (!result.providers[currentProvider]) result.providers[currentProvider] = {};
if (!providers[currentProvider]) providers[currentProvider] = {};
} else {
currentProvider = null;
}
Expand All @@ -1093,12 +1097,12 @@ export function parseOmpYaml(text: string): OmpConfig {
flushPending();
} else if (modelsIndent < 0 || indent <= modelsIndent) {
const m = /^baseUrl:\s*(\S+)/.exec(trimmed);
if (m) result.providers[currentProvider]!.baseUrl = m[1];
if (m) providers[currentProvider]!.baseUrl = m[1];
}
}
}
flushPending();
return result;
return { providers };
}

export function readOmpConfig(ompHome: string): OmpConfig {
Expand Down
2 changes: 2 additions & 0 deletions src/compress-settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { findRoute, type CompressSettings, type ProviderRoutes } from "./config.
import { configDir } from "./paths.js";
import { log as loggerLog } from "./logger.js";

export type { CompressSettings } from "./config.js";

/** Host-side policy default for `compress.stripImagesKeepRecent` (#617): how
* many of the most recent messages keep their image payloads when stripping
* is enabled. The strip mechanism itself lives in acp-kernel's wire layer
Expand Down
14 changes: 7 additions & 7 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -630,13 +630,13 @@ export type ProxyOptions = {
* plain-object key paths of client-fixed fields to strip before forward
* for strict-schema gateways that 400 on unknown fields; per-provider
* lists union onto it additively. Empty = byte-for-byte transparent. */
compat: { roles: Record<string, string>; dropFields?: string[] };
compat?: { roles: Record<string, string>; dropFields?: string[] };
/** #1455: how upstream stream failures are presented to the client on the
* anthropic/openai wire — "protocol" (default) = protocol-native error
* frames; "completion" = legacy synthesized-completion shape for hosts
* whose SDK cannot surface in-band errors. Env BILI_STREAM_ERROR_SHAPE
* wins over the file's compat.streamErrorShape. */
streamErrorShape: "protocol" | "completion";
streamErrorShape?: "protocol" | "completion";
/** Global-level image billing mode (#767); per-provider route entries
* override it, env BILI_IMAGE_BILLING overrides both. undefined = auto
* (= pixels for every host since #1843). */
Expand All @@ -653,20 +653,20 @@ export type ProxyOptions = {
/** Where `passthrough` came from: "env" (ACP_PASSTHROUGH or --passthrough
* flag), "file" (config `passthrough: true`), or null (default off).
* Drives the #405 boot warning and the web panel's source display. */
passthroughSource: "env" | "file" | null;
passthroughSource?: "env" | "file" | null;
autoUpdate: boolean;
/** Opt-in self-restart when a newer version is already installed on disk
* (#811): re-exec at zero in-flight requests. Default OFF. */
autoRestartOnUpdate: boolean;
autoRestartOnUpdate?: boolean;
/** Dist-tag channel the auto-updater follows (default "latest"). */
updateTag: string;
updateTag?: string;
/** Critical-defect advisory watcher (#1481): runs INDEPENDENTLY of
* autoUpdate and force-installs the owner-recommended version when the
* local version falls inside an affected range. Default ON. */
advisoryCheck: boolean;
advisoryCheck?: boolean;
/** Tiered release-notes visibility (#1870): fetch + cache only — never
* installs, never restarts. Default ON. */
releaseNotesCheck: boolean;
releaseNotesCheck?: boolean;
/** Override for the advisory document URL (env BILI_ADVISORY_URL wins). */
advisoryUrl?: string;
/** Override for the release-notes document URL (env
Expand Down
2 changes: 1 addition & 1 deletion src/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ type RegistryShape = Record<string, ModelEntry>;
// providers.<host>.models.<id>.cost ($/Mtok). Only rows with a usable input
// price are stored — without an input anchor there is nothing to normalize
// against, and half-inventing a profile would misprice every fold.
type CostRow = { input: number; output?: number; cache_read?: number; cache_write?: number };
export type CostRow = { input: number; output?: number; cache_read?: number; cache_write?: number };
type CostsShape = Record<string, CostRow>;
type LoadedRegistry = { reg: RegistryShape; costs: CostsShape | null };

Expand Down
31 changes: 30 additions & 1 deletion src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,29 @@ export type Session = {
lockChain?: Promise<unknown>;
};

/** Server-stamped anonymous-prefix-affinity record (#1115/#1486 lane, written
* in src/server.ts when an anonymous request resolves onto a pfa-* chain or
* mints a fresh one). Typed here so readers don't cast the Record bag. */
export type AnonymousPrefixAffinityStamp = {
depth: number;
tailHash: string;
via: "prefix" | "new";
lineage?: { parents: string[]; reason: "truncated" | "forked"; sharedPrefix?: number };
};

export function peekAnonymousPrefixAffinity(session: Session): AnonymousPrefixAffinityStamp | undefined {
const v = session.metadata.anonymousPrefixAffinity;
if (!v || typeof v !== "object") return undefined;
return v as AnonymousPrefixAffinityStamp;
}

/** Per-request-resolved context limit stamped by the server (src/server.ts) —
* the window actually in force for this session's traffic. */
export function peekEffectiveContextLimit(session: Session): number | undefined {
const v = session.metadata.effectiveContextLimit;
return typeof v === "number" ? v : undefined;
}

// #833: wire paths resolve the kernel Config per request (global → provider →
// model compress settings + self-heal + output headroom), while the plugin
// status/tool API reads sessions with no request context and was falling back
Expand Down Expand Up @@ -466,6 +489,12 @@ export async function initSessions(): Promise<void> {
}
}

/** Zero-valued stats for a fresh session (#1991) — exported so test fixtures
* can build sessions without retyping every field. */
export function zeroStats(): Session["stats"] {
return { requests: 0, tokensSaved: 0, inputTokens: 0, cachedTokens: 0, outputTokens: 0, cacheSamples: 0, lastInputTokens: 0, compressCreditTokens: 0, contextTokens: 0, retrieveCalls: 0, retrieveHits: 0, retrieveMisses: 0, retrieveDropped: 0, retrieveDelivered: 0, storedBytes: 0, storeBytesSaved: 0, rangeRestores: 0 };
}

export function getSession(id: string, meta?: { protocol?: Session["meta"]["protocol"]; upstreamOrigin?: string; label?: string }): Session {
const existing = sessions.get(id);
if (existing) {
Expand Down Expand Up @@ -508,7 +537,7 @@ export function getSession(id: string, meta?: { protocol?: Session["meta"]["prot
const session: Session = {
id,
meta: { protocol: meta?.protocol, upstreamOrigin: meta?.upstreamOrigin, label: meta?.label },
stats: { requests: 0, tokensSaved: 0, inputTokens: 0, cachedTokens: 0, outputTokens: 0, cacheSamples: 0, lastInputTokens: 0, compressCreditTokens: 0, contextTokens: 0, retrieveCalls: 0, retrieveHits: 0, retrieveMisses: 0, retrieveDropped: 0, retrieveDelivered: 0, storedBytes: 0, storeBytesSaved: 0, rangeRestores: 0 },
stats: zeroStats(),
metadata: {},
state: createInitialState(),
createdAt: Date.now(),
Expand Down
4 changes: 2 additions & 2 deletions tests/launcher-max-outputs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ test("parseOmpYaml: maxTokens at model-entry depth completes the entry (#971)",
" contextWindow: 131072",
].join("\n");
const cfg = parseOmpYaml(yml);
assert.deepEqual(cfg.providers.sglang?.models, [
assert.deepEqual(cfg.providers?.sglang?.models, [
{ id: "qwen3.8-27b", contextWindow: 262144, maxOutput: 32768 },
{ id: "other-model", contextWindow: 131072 },
]);
Expand All @@ -89,7 +89,7 @@ test("parseOpencodeProviders: limit object shape {context, output} (#971)", () =
},
},
});
assert.deepEqual(cfg.providers.sglang?.models, [
assert.deepEqual(cfg.providers?.sglang?.models, [
{ id: "qwen3.8-27b", contextWindow: 262144, maxOutput: 32768 },
{ id: "legacy", contextWindow: 131072 },
]);
Expand Down
20 changes: 10 additions & 10 deletions tests/launcher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2601,10 +2601,10 @@ test("parseOmpYaml: reads providers.<name>.baseUrl (skips non-matching)", () =>
" default: sglang-responses/qwen3.8-27b:high",
].join("\n");
const cfg = parseOmpYaml(yml);
assert.equal(cfg.providers["sglang-responses"].baseUrl, "http://127.0.0.1:8199/v1");
assert.equal(cfg.providers["zhipuai"].baseUrl, "https://open.bigmodel.cn/api/coding/paas/v4");
assert.equal(cfg.providers["ollama-chat"].baseUrl, "http://127.0.0.1:11435/v1");
assert.equal(Object.keys(cfg.providers).length, 3);
assert.equal(cfg.providers?.["sglang-responses"]?.baseUrl, "http://127.0.0.1:8199/v1");
assert.equal(cfg.providers?.["zhipuai"]?.baseUrl, "https://open.bigmodel.cn/api/coding/paas/v4");
assert.equal(cfg.providers?.["ollama-chat"]?.baseUrl, "http://127.0.0.1:11435/v1");
assert.equal(Object.keys(cfg.providers ?? {}).length, 3);
});

test("parseOmpYaml: no providers key → {}", () => {
Expand All @@ -2617,7 +2617,7 @@ test("readOmpConfig: reads models.yml from omp home", () => {
try {
fs.writeFileSync(path.join(home, "models.yml"), "providers:\n a:\n baseUrl: http://x:1/v1\n");
const cfg = readOmpConfig(home);
assert.equal(cfg.providers.a.baseUrl, "http://x:1/v1");
assert.equal(cfg.providers?.a?.baseUrl, "http://x:1/v1");
} finally {
rmrf(home);
}
Expand Down Expand Up @@ -2668,10 +2668,10 @@ test("readOpencodeConfig: reads provider baseURLs from opencode.json", () => {
}),
);
const cfg = readOpencodeConfig(cfgFile);
assert.deepEqual(cfg.providers["local"], { baseURL: "http://127.0.0.1:18081/v1" });
assert.deepEqual(cfg.providers["remote"], { baseURL: "https://api.example.com/v1" });
assert.equal(cfg.providers["noUrl"], undefined);
assert.equal(readOpencodeConfig(path.join(dir, "missing.json")).providers["local"], undefined);
assert.deepEqual(cfg.providers?.["local"], { baseURL: "http://127.0.0.1:18081/v1" });
assert.deepEqual(cfg.providers?.["remote"], { baseURL: "https://api.example.com/v1" });
assert.equal(cfg.providers?.["noUrl"], undefined);
assert.equal(readOpencodeConfig(path.join(dir, "missing.json")).providers?.["local"], undefined);
} finally {
rmrf(dir);
}
Expand Down Expand Up @@ -2711,7 +2711,7 @@ test("readOpencodeConfig: parses JSONC (comments + trailing commas)", () => {
].join("\n"),
);
const cfg = readOpencodeConfig(cfgFile);
assert.deepEqual(cfg.providers["local"], { baseURL: "http://127.0.0.1:18081/v1" });
assert.deepEqual(cfg.providers?.["local"], { baseURL: "http://127.0.0.1:18081/v1" });
} finally {
rmrf(dir);
}
Expand Down
16 changes: 8 additions & 8 deletions tests/model-windows.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ test("parseOmpYaml: captures per-model contextWindow (models after baseUrl)", ()
" maxTokens: 32768",
].join("\n");
const cfg = parseOmpYaml(yml);
assert.equal(cfg.providers["sglang-responses"]?.baseUrl, "http://127.0.0.1:8199/v1");
assert.equal(cfg.providers?.["sglang-responses"]?.baseUrl, "http://127.0.0.1:8199/v1");
// #971: maxTokens at model-entry depth now completes the entry as maxOutput.
assert.deepEqual(cfg.providers["sglang-responses"]?.models, [{ id: "qwen3.8-27b", contextWindow: 262144, maxOutput: 32768 }]);
assert.deepEqual(cfg.providers?.["sglang-responses"]?.models, [{ id: "qwen3.8-27b", contextWindow: 262144, maxOutput: 32768 }]);
});

test("parseOmpYaml: baseUrl AFTER models: is still captured", () => {
Expand All @@ -46,8 +46,8 @@ test("parseOmpYaml: baseUrl AFTER models: is still captured", () => {
" baseUrl: http://after.example/v1",
].join("\n");
const cfg = parseOmpYaml(yml);
assert.equal(cfg.providers.prov?.baseUrl, "http://after.example/v1");
assert.deepEqual(cfg.providers.prov?.models, [{ id: "m1", contextWindow: 32768 }]);
assert.equal(cfg.providers?.prov?.baseUrl, "http://after.example/v1");
assert.deepEqual(cfg.providers?.prov?.models, [{ id: "m1", contextWindow: 32768 }]);
});

test("parseOmpYaml: multiple models + multiple providers", () => {
Expand All @@ -67,8 +67,8 @@ test("parseOmpYaml: multiple models + multiple providers", () => {
" contextWindow: 3000",
].join("\n");
const cfg = parseOmpYaml(yml);
assert.deepEqual(cfg.providers.a?.models, [{ id: "m1", contextWindow: 1000 }, { id: "m2", contextWindow: 2000 }]);
assert.deepEqual(cfg.providers.b?.models, [{ id: "m1", contextWindow: 3000 }]);
assert.deepEqual(cfg.providers?.a?.models, [{ id: "m1", contextWindow: 1000 }, { id: "m2", contextWindow: 2000 }]);
assert.deepEqual(cfg.providers?.b?.models, [{ id: "m1", contextWindow: 3000 }]);
});

test("readPiConfig: captures models[].contextWindow from models.json", () => {
Expand Down Expand Up @@ -111,8 +111,8 @@ test("readOpencodeConfig: captures models.<id>.limit", () => {
}),
);
const cfg = readOpencodeConfig(file);
assert.equal(cfg.providers.prov?.baseURL, "http://prov/v1");
assert.deepEqual(cfg.providers.prov?.models, [{ id: "glm-5.2", contextWindow: 1000000 }]);
assert.equal(cfg.providers?.prov?.baseURL, "http://prov/v1");
assert.deepEqual(cfg.providers?.prov?.models, [{ id: "glm-5.2", contextWindow: 1000000 }]);
});

test("parseCodexToml: model + model_context_window pair captured", () => {
Expand Down
Loading