重构主控编排与运行时预热链路,统一工作区提示词/专家调度协议并补齐 wiki 记忆注入与写回闭环。

同时收敛启动与运维脚本默认行为(含 wiki worker)、更新 Admin 可观测性与相关测试,降低首轮时延并提高运行稳定性。

Made-with: Cursor
This commit is contained in:
oliver 2026-04-26 08:34:33 +08:00
parent 4a23b715a2
commit dbbe3add6a
14438 changed files with 2693620 additions and 2546 deletions

View file

@ -0,0 +1,6 @@
export {
buildKimiCodingProvider,
KIMI_CODING_BASE_URL,
KIMI_CODING_DEFAULT_MODEL_ID,
} from "./provider-catalog.js";
export { KIMI_CODING_MODEL_REF, KIMI_MODEL_REF } from "./onboard.js";

View file

@ -0,0 +1,84 @@
import { describe, expect, it } from "vitest";
import { registerSingleProviderPlugin } from "../../test/helpers/plugins/plugin-registration.js";
import plugin from "./index.js";
async function runKimiCatalog(params: {
apiKey?: string;
explicitProvider?: Record<string, unknown>;
}) {
const provider = await registerSingleProviderPlugin(plugin);
const catalogResult = await provider.catalog?.run({
config: {
models: {
providers: params.explicitProvider
? {
"kimi-coding": params.explicitProvider,
}
: {},
},
},
resolveProviderApiKey: () => ({ apiKey: params.apiKey ?? "" }),
} as never);
return catalogResult ?? null;
}
async function runKimiCatalogProvider(params: {
apiKey: string;
explicitProvider?: Record<string, unknown>;
}) {
const result = await runKimiCatalog(params);
if (!result || !("provider" in result)) {
throw new Error("expected Kimi catalog to return one provider");
}
return result.provider;
}
describe("Kimi implicit provider (#22409)", () => {
it("publishes the env vars used by core api-key auto-detection", async () => {
const provider = await registerSingleProviderPlugin(plugin);
expect(provider.envVars).toEqual(["KIMI_API_KEY", "KIMICODE_API_KEY"]);
});
it("does not publish a provider when no API key is resolved", async () => {
await expect(runKimiCatalog({})).resolves.toBeNull();
});
it("publishes the Kimi provider when an API key is resolved", async () => {
const provider = await runKimiCatalogProvider({ apiKey: "test-key" });
expect(provider).toMatchObject({
apiKey: "test-key",
baseUrl: "https://api.kimi.com/coding/",
api: "anthropic-messages",
});
});
it("uses explicit legacy kimi-coding baseUrl when provided", async () => {
const provider = await runKimiCatalogProvider({
apiKey: "test-key",
explicitProvider: {
baseUrl: "https://kimi.example.test/coding/",
},
});
expect(provider.baseUrl).toBe("https://kimi.example.test/coding/");
});
it("merges explicit legacy kimi-coding headers on top of the built-in user agent", async () => {
const provider = await runKimiCatalogProvider({
apiKey: "test-key",
explicitProvider: {
headers: {
"User-Agent": "custom-kimi-client/1.0",
"X-Kimi-Tenant": "tenant-a",
},
},
});
expect(provider.headers).toEqual({
"User-Agent": "custom-kimi-client/1.0",
"X-Kimi-Tenant": "tenant-a",
});
});
});

View file

@ -0,0 +1,23 @@
import { describe, expect, it } from "vitest";
import { registerSingleProviderPlugin } from "../../test/helpers/plugins/plugin-registration.js";
import plugin from "./index.js";
describe("kimi provider plugin", () => {
it("uses binary thinking with thinking off by default", async () => {
const provider = await registerSingleProviderPlugin(plugin);
expect(
provider.isBinaryThinking?.({
provider: "kimi",
modelId: "kimi-code",
} as never),
).toBe(true);
expect(
provider.resolveDefaultThinkingLevel?.({
provider: "kimi",
modelId: "kimi-code",
reasoning: true,
} as never),
).toBe("off");
});
});

View file

@ -0,0 +1,104 @@
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
import { createProviderApiKeyAuthMethod } from "openclaw/plugin-sdk/provider-auth-api-key";
import { normalizeProviderId } from "openclaw/plugin-sdk/provider-model-shared";
import type { SecretInput } from "openclaw/plugin-sdk/secret-input";
import { isRecord, normalizeOptionalString } from "openclaw/plugin-sdk/text-runtime";
import { applyKimiCodeConfig, KIMI_CODING_MODEL_REF } from "./onboard.js";
import { buildKimiCodingProvider } from "./provider-catalog.js";
import { KIMI_REPLAY_POLICY } from "./replay-policy.js";
import { wrapKimiProviderStream } from "./stream.js";
const PLUGIN_ID = "kimi";
const PROVIDER_ID = "kimi";
function findExplicitProviderConfig(
providers: Record<string, unknown> | undefined,
providerId: string,
): Record<string, unknown> | undefined {
if (!providers) {
return undefined;
}
const normalizedProviderId = normalizeProviderId(providerId);
const match = Object.entries(providers).find(
([configuredProviderId]) => normalizeProviderId(configuredProviderId) === normalizedProviderId,
);
return isRecord(match?.[1]) ? match[1] : undefined;
}
export default definePluginEntry({
id: PLUGIN_ID,
name: "Kimi Provider",
description: "Bundled Kimi provider plugin",
register(api) {
api.registerProvider({
id: PROVIDER_ID,
label: "Kimi",
aliases: ["kimi-code", "kimi-coding"],
docsPath: "/providers/moonshot",
envVars: ["KIMI_API_KEY", "KIMICODE_API_KEY"],
auth: [
createProviderApiKeyAuthMethod({
providerId: PROVIDER_ID,
methodId: "api-key",
label: "Kimi Code API key (subscription)",
hint: "Kimi K2.5 + Kimi",
optionKey: "kimiCodeApiKey",
flagName: "--kimi-code-api-key",
envVar: "KIMI_API_KEY",
promptMessage: "Enter Kimi API key",
defaultModel: KIMI_CODING_MODEL_REF,
expectedProviders: ["kimi", "kimi-code", "kimi-coding"],
applyConfig: (cfg) => applyKimiCodeConfig(cfg),
noteMessage: [
"Kimi uses a dedicated coding endpoint and API key.",
"Get your API key at: https://www.kimi.com/code/en",
].join("\n"),
noteTitle: "Kimi",
wizard: {
choiceId: "kimi-code-api-key",
choiceLabel: "Kimi Code API key (subscription)",
groupId: "moonshot",
groupLabel: "Moonshot AI (Kimi K2.5)",
groupHint: "Kimi K2.5",
},
}),
],
catalog: {
order: "simple",
run: async (ctx) => {
const apiKey = ctx.resolveProviderApiKey(PROVIDER_ID).apiKey;
if (!apiKey) {
return null;
}
const explicitProvider = findExplicitProviderConfig(
ctx.config.models?.providers as Record<string, unknown> | undefined,
PROVIDER_ID,
);
const builtInProvider = buildKimiCodingProvider();
const explicitBaseUrl = normalizeOptionalString(explicitProvider?.baseUrl) ?? "";
const explicitHeaders = isRecord(explicitProvider?.headers)
? (explicitProvider.headers as Record<string, SecretInput>)
: undefined;
return {
provider: {
...builtInProvider,
...(explicitBaseUrl ? { baseUrl: explicitBaseUrl } : {}),
...(explicitHeaders
? {
headers: {
...builtInProvider.headers,
...explicitHeaders,
},
}
: {}),
apiKey,
},
};
},
},
buildReplayPolicy: () => KIMI_REPLAY_POLICY,
isBinaryThinking: () => true,
resolveDefaultThinkingLevel: () => "off",
wrapStreamFn: wrapKimiProviderStream,
});
},
});

View file

@ -0,0 +1,42 @@
import {
createDefaultModelPresetAppliers,
type OpenClawConfig,
} from "openclaw/plugin-sdk/provider-onboard";
import {
buildKimiCodingProvider,
KIMI_CODING_BASE_URL,
KIMI_CODING_DEFAULT_MODEL_ID,
} from "./provider-catalog.js";
export const KIMI_MODEL_REF = `kimi/${KIMI_CODING_DEFAULT_MODEL_ID}`;
export const KIMI_CODING_MODEL_REF = KIMI_MODEL_REF;
function resolveKimiCodingDefaultModel() {
return buildKimiCodingProvider().models[0];
}
const kimiCodingPresetAppliers = createDefaultModelPresetAppliers({
primaryModelRef: KIMI_MODEL_REF,
resolveParams: (_cfg: OpenClawConfig) => {
const defaultModel = resolveKimiCodingDefaultModel();
if (!defaultModel) {
return null;
}
return {
providerId: "kimi",
api: "anthropic-messages",
baseUrl: KIMI_CODING_BASE_URL,
defaultModel,
defaultModelId: KIMI_CODING_DEFAULT_MODEL_ID,
aliases: [{ modelRef: KIMI_MODEL_REF, alias: "Kimi" }],
};
},
});
export function applyKimiCodeProviderConfig(cfg: OpenClawConfig): OpenClawConfig {
return kimiCodingPresetAppliers.applyProviderConfig(cfg);
}
export function applyKimiCodeConfig(cfg: OpenClawConfig): OpenClawConfig {
return kimiCodingPresetAppliers.applyConfig(cfg);
}

View file

@ -0,0 +1,29 @@
{
"id": "kimi",
"enabledByDefault": true,
"providers": ["kimi", "kimi-coding"],
"providerAuthEnvVars": {
"kimi": ["KIMI_API_KEY", "KIMICODE_API_KEY"],
"kimi-coding": ["KIMI_API_KEY", "KIMICODE_API_KEY"]
},
"providerAuthChoices": [
{
"provider": "kimi",
"method": "api-key",
"choiceId": "kimi-code-api-key",
"choiceLabel": "Kimi Code API key (subscription)",
"groupId": "moonshot",
"groupLabel": "Moonshot AI (Kimi K2.5)",
"groupHint": "Kimi K2.5",
"optionKey": "kimiCodeApiKey",
"cliFlag": "--kimi-code-api-key",
"cliOption": "--kimi-code-api-key <key>",
"cliDescription": "Kimi Code API key (subscription)"
}
],
"configSchema": {
"type": "object",
"additionalProperties": false,
"properties": {}
}
}

View file

@ -0,0 +1,15 @@
{
"name": "@openclaw/kimi-provider",
"version": "2026.4.20",
"private": true,
"description": "OpenClaw Kimi provider plugin",
"type": "module",
"devDependencies": {
"@openclaw/plugin-sdk": "workspace:*"
},
"openclaw": {
"extensions": [
"./index.ts"
]
}
}

View file

@ -0,0 +1,13 @@
import { describe, expect, it } from "vitest";
import { buildKimiCodingProvider } from "./provider-catalog.js";
describe("kimi provider catalog", () => {
it("builds the bundled Kimi coding defaults", () => {
const provider = buildKimiCodingProvider();
expect(provider.api).toBe("anthropic-messages");
expect(provider.baseUrl).toBe("https://api.kimi.com/coding/");
expect(provider.headers).toEqual({ "User-Agent": "claude-code/0.1.0" });
expect(provider.models.map((model) => model.id)).toEqual(["kimi-code", "k2p5"]);
});
});

View file

@ -0,0 +1,50 @@
import type { ModelProviderConfig } from "openclaw/plugin-sdk/provider-model-shared";
export const KIMI_BASE_URL = "https://api.kimi.com/coding/";
const KIMI_CODING_USER_AGENT = "claude-code/0.1.0";
export const KIMI_DEFAULT_MODEL_ID = "kimi-code";
export const KIMI_UPSTREAM_MODEL_ID = "kimi-for-coding";
export const KIMI_LEGACY_MODEL_ID = "k2p5";
const KIMI_CODING_DEFAULT_CONTEXT_WINDOW = 262144;
const KIMI_CODING_DEFAULT_MAX_TOKENS = 32768;
const KIMI_CODING_DEFAULT_COST = {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0,
};
export function buildKimiCodingProvider(): ModelProviderConfig {
return {
baseUrl: KIMI_BASE_URL,
api: "anthropic-messages",
headers: {
"User-Agent": KIMI_CODING_USER_AGENT,
},
models: [
{
id: KIMI_DEFAULT_MODEL_ID,
name: "Kimi Code",
reasoning: true,
input: ["text", "image"],
cost: KIMI_CODING_DEFAULT_COST,
contextWindow: KIMI_CODING_DEFAULT_CONTEXT_WINDOW,
maxTokens: KIMI_CODING_DEFAULT_MAX_TOKENS,
},
{
id: KIMI_LEGACY_MODEL_ID,
name: "Kimi Code (legacy model id)",
reasoning: true,
input: ["text", "image"],
cost: KIMI_CODING_DEFAULT_COST,
contextWindow: KIMI_CODING_DEFAULT_CONTEXT_WINDOW,
maxTokens: KIMI_CODING_DEFAULT_MAX_TOKENS,
},
],
};
}
export const KIMI_CODING_BASE_URL = KIMI_BASE_URL;
export const KIMI_CODING_DEFAULT_MODEL_ID = KIMI_DEFAULT_MODEL_ID;
export const KIMI_CODING_LEGACY_MODEL_ID = KIMI_LEGACY_MODEL_ID;
export const buildKimiProvider = buildKimiCodingProvider;

View file

@ -0,0 +1,3 @@
export const KIMI_REPLAY_POLICY = {
preserveSignatures: false,
};

View file

@ -0,0 +1,365 @@
import type { StreamFn } from "@mariozechner/pi-agent-core";
import type { Context, Model } from "@mariozechner/pi-ai";
import { describe, expect, it } from "vitest";
import {
createKimiThinkingWrapper,
createKimiToolCallMarkupWrapper,
resolveKimiThinkingType,
wrapKimiProviderStream,
} from "./stream.js";
type FakeStream = {
result: () => Promise<unknown>;
[Symbol.asyncIterator]: () => AsyncIterator<unknown>;
};
function createFakeStream(params: { events: unknown[]; resultMessage: unknown }): FakeStream {
return {
async result() {
return params.resultMessage;
},
[Symbol.asyncIterator]() {
return (async function* () {
for (const event of params.events) {
yield event;
}
})();
},
};
}
const KIMI_TOOL_TEXT =
' <|tool_calls_section_begin|> <|tool_call_begin|> functions.read:0 <|tool_call_argument_begin|> {"file_path":"./package.json"} <|tool_call_end|> <|tool_calls_section_end|>';
const KIMI_MULTI_TOOL_TEXT =
' <|tool_calls_section_begin|> <|tool_call_begin|> functions.read:0 <|tool_call_argument_begin|> {"file_path":"./package.json"} <|tool_call_end|> <|tool_call_begin|> functions.write:1 <|tool_call_argument_begin|> {"file_path":"./out.txt","content":"done"} <|tool_call_end|> <|tool_calls_section_end|>';
describe("kimi tool-call markup wrapper", () => {
it("defaults Kimi thinking to disabled unless explicitly enabled", () => {
expect(resolveKimiThinkingType({ configuredThinking: undefined })).toBe("disabled");
expect(resolveKimiThinkingType({ configuredThinking: undefined, thinkingLevel: "high" })).toBe(
"enabled",
);
expect(resolveKimiThinkingType({ configuredThinking: "off", thinkingLevel: "high" })).toBe(
"disabled",
);
expect(resolveKimiThinkingType({ configuredThinking: "enabled", thinkingLevel: "off" })).toBe(
"enabled",
);
});
it("converts tagged Kimi tool-call text into structured tool calls", async () => {
const partial = {
role: "assistant",
content: [{ type: "text", text: KIMI_TOOL_TEXT }],
stopReason: "stop",
};
const message = {
role: "assistant",
content: [{ type: "text", text: KIMI_TOOL_TEXT }],
stopReason: "stop",
};
const finalMessage = {
role: "assistant",
content: [
{ type: "thinking", thinking: "Need to read the file first." },
{ type: "text", text: KIMI_TOOL_TEXT },
],
stopReason: "stop",
};
const baseStreamFn: StreamFn = () =>
createFakeStream({
events: [{ type: "message_end", partial, message }],
resultMessage: finalMessage,
}) as ReturnType<StreamFn>;
const wrapped = createKimiToolCallMarkupWrapper(baseStreamFn);
const stream = wrapped(
{ api: "anthropic-messages", provider: "kimi", id: "k2p5" } as Model<"anthropic-messages">,
{ messages: [] } as Context,
{},
) as FakeStream;
const events: unknown[] = [];
for await (const event of stream) {
events.push(event);
}
const result = (await stream.result()) as {
content: unknown[];
stopReason: string;
};
expect(events).toEqual([
{
type: "message_end",
partial: {
role: "assistant",
content: [
{
type: "toolCall",
id: "functions.read:0",
name: "functions.read",
arguments: { file_path: "./package.json" },
},
],
stopReason: "toolUse",
},
message: {
role: "assistant",
content: [
{
type: "toolCall",
id: "functions.read:0",
name: "functions.read",
arguments: { file_path: "./package.json" },
},
],
stopReason: "toolUse",
},
},
]);
expect(result).toEqual({
role: "assistant",
content: [
{ type: "thinking", thinking: "Need to read the file first." },
{
type: "toolCall",
id: "functions.read:0",
name: "functions.read",
arguments: { file_path: "./package.json" },
},
],
stopReason: "toolUse",
});
});
it("leaves normal assistant text unchanged", async () => {
const finalMessage = {
role: "assistant",
content: [{ type: "text", text: "normal response" }],
stopReason: "stop",
};
const baseStreamFn: StreamFn = () =>
createFakeStream({
events: [],
resultMessage: finalMessage,
}) as ReturnType<StreamFn>;
const wrapped = createKimiToolCallMarkupWrapper(baseStreamFn);
const stream = wrapped(
{ api: "anthropic-messages", provider: "kimi", id: "k2p5" } as Model<"anthropic-messages">,
{ messages: [] } as Context,
{},
) as FakeStream;
await expect(stream.result()).resolves.toBe(finalMessage);
});
it("supports async stream functions", async () => {
const finalMessage = {
role: "assistant",
content: [{ type: "text", text: KIMI_TOOL_TEXT }],
stopReason: "stop",
};
const baseStreamFn: StreamFn = async () =>
createFakeStream({
events: [],
resultMessage: finalMessage,
}) as ReturnType<StreamFn>;
const wrapped = createKimiToolCallMarkupWrapper(baseStreamFn);
const stream = (await wrapped(
{ api: "anthropic-messages", provider: "kimi", id: "k2p5" } as Model<"anthropic-messages">,
{ messages: [] } as Context,
{},
)) as FakeStream;
await expect(stream.result()).resolves.toEqual({
role: "assistant",
content: [
{
type: "toolCall",
id: "functions.read:0",
name: "functions.read",
arguments: { file_path: "./package.json" },
},
],
stopReason: "toolUse",
});
});
it("parses multiple tagged tool calls in one section", async () => {
const finalMessage = {
role: "assistant",
content: [{ type: "text", text: KIMI_MULTI_TOOL_TEXT }],
stopReason: "stop",
};
const baseStreamFn: StreamFn = () =>
createFakeStream({
events: [],
resultMessage: finalMessage,
}) as ReturnType<StreamFn>;
const wrapped = createKimiToolCallMarkupWrapper(baseStreamFn);
const stream = wrapped(
{ api: "anthropic-messages", provider: "kimi", id: "k2p5" } as Model<"anthropic-messages">,
{ messages: [] } as Context,
{},
) as FakeStream;
await expect(stream.result()).resolves.toEqual({
role: "assistant",
content: [
{
type: "toolCall",
id: "functions.read:0",
name: "functions.read",
arguments: { file_path: "./package.json" },
},
{
type: "toolCall",
id: "functions.write:1",
name: "functions.write",
arguments: { file_path: "./out.txt", content: "done" },
},
],
stopReason: "toolUse",
});
});
it("adapts provider stream context without changing wrapper behavior", async () => {
const finalMessage = {
role: "assistant",
content: [{ type: "text", text: KIMI_TOOL_TEXT }],
stopReason: "stop",
};
const baseStreamFn: StreamFn = () =>
createFakeStream({
events: [],
resultMessage: finalMessage,
}) as ReturnType<StreamFn>;
const wrapped = wrapKimiProviderStream({
streamFn: baseStreamFn,
} as never);
const stream = wrapped(
{ api: "anthropic-messages", provider: "kimi", id: "k2p5" } as Model<"anthropic-messages">,
{ messages: [] } as Context,
{},
) as FakeStream;
await expect(stream.result()).resolves.toEqual({
role: "assistant",
content: [
{
type: "toolCall",
id: "functions.read:0",
name: "functions.read",
arguments: { file_path: "./package.json" },
},
],
stopReason: "toolUse",
});
});
it("forces Kimi thinking disabled and strips proxy reasoning fields", () => {
let capturedPayload: Record<string, unknown> | undefined;
const baseStreamFn: StreamFn = (model, _context, options) => {
const payload: Record<string, unknown> = {
reasoning: { effort: "high" },
reasoning_effort: "high",
reasoningEffort: "high",
};
options?.onPayload?.(payload as never, model as never);
capturedPayload = payload;
return createFakeStream({
events: [],
resultMessage: { role: "assistant", content: [] },
}) as never;
};
const wrapped = createKimiThinkingWrapper(baseStreamFn, "disabled");
void wrapped(
{
api: "anthropic-messages",
provider: "kimi",
id: "kimi-code",
} as Model<"anthropic-messages">,
{ messages: [] } as Context,
{},
);
expect(capturedPayload).toEqual({
thinking: { type: "disabled" },
});
});
it("lets explicit model params keep Kimi thinking disabled even when session thinking is on", () => {
let capturedPayload: Record<string, unknown> | undefined;
const baseStreamFn: StreamFn = (model, _context, options) => {
const payload: Record<string, unknown> = {};
options?.onPayload?.(payload as never, model as never);
capturedPayload = payload;
return createFakeStream({
events: [],
resultMessage: { role: "assistant", content: [] },
}) as never;
};
const wrapped = wrapKimiProviderStream({
provider: "kimi",
modelId: "kimi-code",
extraParams: { thinking: "off" },
thinkingLevel: "high",
streamFn: baseStreamFn,
} as never);
void wrapped(
{
api: "anthropic-messages",
provider: "kimi",
id: "kimi-code",
} as Model<"anthropic-messages">,
{ messages: [] } as Context,
{},
);
expect(capturedPayload).toEqual({
thinking: { type: "disabled" },
});
});
it("enables Kimi thinking only when explicitly requested", () => {
let capturedPayload: Record<string, unknown> | undefined;
const baseStreamFn: StreamFn = (model, _context, options) => {
const payload: Record<string, unknown> = {};
options?.onPayload?.(payload as never, model as never);
capturedPayload = payload;
return createFakeStream({
events: [],
resultMessage: { role: "assistant", content: [] },
}) as never;
};
const wrapped = wrapKimiProviderStream({
provider: "kimi",
modelId: "kimi-code",
thinkingLevel: "high",
streamFn: baseStreamFn,
} as never);
void wrapped(
{
api: "anthropic-messages",
provider: "kimi",
id: "kimi-code",
} as Model<"anthropic-messages">,
{ messages: [] } as Context,
{},
);
expect(capturedPayload).toEqual({
thinking: { type: "enabled" },
});
});
});

View file

@ -0,0 +1,246 @@
import type { StreamFn } from "@mariozechner/pi-agent-core";
import { streamSimple } from "@mariozechner/pi-ai";
import type { ProviderWrapStreamFnContext } from "openclaw/plugin-sdk/plugin-entry";
import { streamWithPayloadPatch } from "openclaw/plugin-sdk/provider-stream-shared";
import { normalizeOptionalLowercaseString } from "openclaw/plugin-sdk/text-runtime";
const TOOL_CALLS_SECTION_BEGIN = "<|tool_calls_section_begin|>";
const TOOL_CALLS_SECTION_END = "<|tool_calls_section_end|>";
const TOOL_CALL_BEGIN = "<|tool_call_begin|>";
const TOOL_CALL_ARGUMENT_BEGIN = "<|tool_call_argument_begin|>";
const TOOL_CALL_END = "<|tool_call_end|>";
type KimiToolCallBlock = {
type: "toolCall";
id: string;
name: string;
arguments: Record<string, unknown>;
};
type KimiThinkingType = "enabled" | "disabled";
type KimiThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "adaptive";
function normalizeKimiThinkingType(value: unknown): KimiThinkingType | undefined {
if (typeof value === "boolean") {
return value ? "enabled" : "disabled";
}
if (typeof value === "string") {
const normalized = normalizeOptionalLowercaseString(value);
if (!normalized) {
return undefined;
}
if (["enabled", "enable", "on", "true"].includes(normalized)) {
return "enabled";
}
if (["disabled", "disable", "off", "false"].includes(normalized)) {
return "disabled";
}
return undefined;
}
if (value && typeof value === "object" && !Array.isArray(value)) {
return normalizeKimiThinkingType((value as Record<string, unknown>).type);
}
return undefined;
}
export function resolveKimiThinkingType(params: {
configuredThinking: unknown;
thinkingLevel?: KimiThinkingLevel;
}): KimiThinkingType {
const configured = normalizeKimiThinkingType(params.configuredThinking);
if (configured) {
return configured;
}
if (!params.thinkingLevel || params.thinkingLevel === "off") {
return "disabled";
}
return "enabled";
}
function stripTaggedToolCallCounter(value: string): string {
return value.trim().replace(/:\d+$/, "");
}
function parseKimiTaggedToolCalls(text: string): KimiToolCallBlock[] | null {
const trimmed = text.trim();
// Kimi emits tagged tool-call sections as standalone text blocks on this path.
if (!trimmed.startsWith(TOOL_CALLS_SECTION_BEGIN) || !trimmed.endsWith(TOOL_CALLS_SECTION_END)) {
return null;
}
let cursor = TOOL_CALLS_SECTION_BEGIN.length;
const sectionEndIndex = trimmed.length - TOOL_CALLS_SECTION_END.length;
const toolCalls: KimiToolCallBlock[] = [];
while (cursor < sectionEndIndex) {
while (cursor < sectionEndIndex && /\s/.test(trimmed[cursor] ?? "")) {
cursor += 1;
}
if (cursor >= sectionEndIndex) {
break;
}
if (!trimmed.startsWith(TOOL_CALL_BEGIN, cursor)) {
return null;
}
const nameStart = cursor + TOOL_CALL_BEGIN.length;
const argMarkerIndex = trimmed.indexOf(TOOL_CALL_ARGUMENT_BEGIN, nameStart);
if (argMarkerIndex < 0 || argMarkerIndex >= sectionEndIndex) {
return null;
}
const rawId = trimmed.slice(nameStart, argMarkerIndex).trim();
if (!rawId) {
return null;
}
const argsStart = argMarkerIndex + TOOL_CALL_ARGUMENT_BEGIN.length;
const callEndIndex = trimmed.indexOf(TOOL_CALL_END, argsStart);
if (callEndIndex < 0 || callEndIndex > sectionEndIndex) {
return null;
}
const rawArgs = trimmed.slice(argsStart, callEndIndex).trim();
let parsedArgs: unknown;
try {
parsedArgs = JSON.parse(rawArgs);
} catch {
return null;
}
if (!parsedArgs || typeof parsedArgs !== "object" || Array.isArray(parsedArgs)) {
return null;
}
const name = stripTaggedToolCallCounter(rawId);
if (!name) {
return null;
}
toolCalls.push({
type: "toolCall",
id: rawId,
name,
arguments: parsedArgs as Record<string, unknown>,
});
cursor = callEndIndex + TOOL_CALL_END.length;
}
return toolCalls.length > 0 ? toolCalls : null;
}
function rewriteKimiTaggedToolCallsInMessage(message: unknown): void {
if (!message || typeof message !== "object") {
return;
}
const content = (message as { content?: unknown }).content;
if (!Array.isArray(content)) {
return;
}
let changed = false;
const nextContent: unknown[] = [];
for (const block of content) {
if (!block || typeof block !== "object") {
nextContent.push(block);
continue;
}
const typedBlock = block as { type?: unknown; text?: unknown };
if (typedBlock.type !== "text" || typeof typedBlock.text !== "string") {
nextContent.push(block);
continue;
}
const parsed = parseKimiTaggedToolCalls(typedBlock.text);
if (!parsed) {
nextContent.push(block);
continue;
}
nextContent.push(...parsed);
changed = true;
}
if (!changed) {
return;
}
(message as { content: unknown[] }).content = nextContent;
const typedMessage = message as { stopReason?: unknown };
if (typedMessage.stopReason === "stop") {
typedMessage.stopReason = "toolUse";
}
}
function wrapKimiTaggedToolCalls(
stream: ReturnType<typeof streamSimple>,
): ReturnType<typeof streamSimple> {
const originalResult = stream.result.bind(stream);
stream.result = async () => {
const message = await originalResult();
rewriteKimiTaggedToolCallsInMessage(message);
return message;
};
const originalAsyncIterator = stream[Symbol.asyncIterator].bind(stream);
(stream as { [Symbol.asyncIterator]: typeof originalAsyncIterator })[Symbol.asyncIterator] =
function () {
const iterator = originalAsyncIterator();
return {
async next() {
const result = await iterator.next();
if (!result.done && result.value && typeof result.value === "object") {
const event = result.value as {
partial?: unknown;
message?: unknown;
};
rewriteKimiTaggedToolCallsInMessage(event.partial);
rewriteKimiTaggedToolCallsInMessage(event.message);
}
return result;
},
async return(value?: unknown) {
return iterator.return?.(value) ?? { done: true as const, value: undefined };
},
async throw(error?: unknown) {
return iterator.throw?.(error) ?? { done: true as const, value: undefined };
},
};
};
return stream;
}
export function createKimiToolCallMarkupWrapper(baseStreamFn: StreamFn | undefined): StreamFn {
const underlying = baseStreamFn ?? streamSimple;
return (model, context, options) => {
const maybeStream = underlying(model, context, options);
if (maybeStream && typeof maybeStream === "object" && "then" in maybeStream) {
return Promise.resolve(maybeStream).then((stream) => wrapKimiTaggedToolCalls(stream));
}
return wrapKimiTaggedToolCalls(maybeStream);
};
}
export function createKimiThinkingWrapper(
baseStreamFn: StreamFn | undefined,
thinkingType: KimiThinkingType,
): StreamFn {
const underlying = baseStreamFn ?? streamSimple;
return (model, context, options) =>
streamWithPayloadPatch(underlying, model, context, options, (payloadObj) => {
payloadObj.thinking = { type: thinkingType };
delete payloadObj.reasoning;
delete payloadObj.reasoning_effort;
delete payloadObj.reasoningEffort;
});
}
export function wrapKimiProviderStream(ctx: ProviderWrapStreamFnContext): StreamFn {
const thinkingType = resolveKimiThinkingType({
configuredThinking: ctx.extraParams?.thinking,
thinkingLevel: ctx.thinkingLevel,
});
return createKimiToolCallMarkupWrapper(createKimiThinkingWrapper(ctx.streamFn, thinkingType));
}

View file

@ -0,0 +1,16 @@
{
"extends": "../tsconfig.package-boundary.base.json",
"compilerOptions": {
"rootDir": "."
},
"include": ["./*.ts", "./src/**/*.ts"],
"exclude": [
"./**/*.test.ts",
"./dist/**",
"./node_modules/**",
"./src/test-support/**",
"./src/**/*test-helpers.ts",
"./src/**/*test-harness.ts",
"./src/**/*test-support.ts"
]
}