Vendor OpenClaw source as Adolf fork baseline
Some checks failed
ClawSweeper Dispatch / dispatch (push) Has been cancelled
CodeQL / Security High (actions) (push) Has been cancelled
CodeQL / Security High (channel-runtime-boundary) (push) Has been cancelled
CodeQL / Security High (core-auth-secrets) (push) Has been cancelled
CodeQL / Security High (mcp-process-tool-boundary) (push) Has been cancelled
CodeQL / Security High (network-ssrf-boundary) (push) Has been cancelled
CodeQL / Security High (plugin-trust-boundary) (push) Has been cancelled
CodeQL / Security High (process-exec-boundary) (push) Has been cancelled
Docs Sync Publish Repo / sync-publish-repo (push) Has been cancelled
Docs / docs (push) Has been cancelled
OpenClaw Stable Main Closeout / Resolve stable release closeout inputs (push) Has been cancelled
OpenClaw Stable Main Closeout / Verify stable main closeout (push) Has been cancelled
Workflow Sanity / no-tabs (push) Has been cancelled
Workflow Sanity / actionlint (push) Has been cancelled
Workflow Sanity / generated-doc-baselines (push) Has been cancelled
CI / runner-admission (push) Has been cancelled
CI / preflight (push) Has been cancelled
CI / security-fast (push) Has been cancelled
CI / pnpm-store-warmup (push) Has been cancelled
CI / build-artifacts (push) Has been cancelled
CI / native-i18n (push) Has been cancelled
CI / ${{ matrix.check_name }} (push) Has been cancelled
CI / ${{ matrix.checkName }} (push) Has been cancelled
CI / checks-node-compat-node22 (push) Has been cancelled
CI / check-bundled-channel-config-metadata (push) Has been cancelled
CI / check-dependencies (push) Has been cancelled
CI / check-guards (push) Has been cancelled
CI / check-lint (push) Has been cancelled
CI / check-prod-types (push) Has been cancelled
CI / check-shrinkwrap (push) Has been cancelled
CI / check-test-types (push) Has been cancelled
CI / check-additional-boundaries-a (push) Has been cancelled
CI / check-additional-boundaries-bcd (push) Has been cancelled
CI / check-additional-extension-bundled (push) Has been cancelled
CI / check-additional-extension-channels (push) Has been cancelled
CI / check-additional-extension-package-boundary (push) Has been cancelled
CI / check-additional-runtime-topology-architecture (push) Has been cancelled
CI / check-session-accessor-boundary (push) Has been cancelled
CI / check-session-transcript-reader-boundary (push) Has been cancelled
CI / check-docs (push) Has been cancelled
CI / skills-python (push) Has been cancelled
CI / macos-swift (push) Has been cancelled
CI / ios-build (push) Has been cancelled
CI / ci-timings-summary (push) Has been cancelled
Native App Locale Refresh / Refresh native fa (push) Has been cancelled
Native App Locale Refresh / Refresh native fr (push) Has been cancelled
Native App Locale Refresh / Refresh native hi (push) Has been cancelled
Native App Locale Refresh / Refresh native id (push) Has been cancelled
Native App Locale Refresh / Refresh native it (push) Has been cancelled
Native App Locale Refresh / Refresh native ja-JP (push) Has been cancelled
Control UI Locale Refresh / plan (push) Has been cancelled
Control UI Locale Refresh / Refresh ${{ matrix.locale }} (push) Has been cancelled
Control UI Locale Refresh / Commit control UI locale refresh (push) Has been cancelled
Live Media Runner Image / Build live media runner image (push) Has been cancelled
Native App Locale Refresh / Refresh native ar (push) Has been cancelled
Native App Locale Refresh / Refresh native de (push) Has been cancelled
Native App Locale Refresh / Refresh native es (push) Has been cancelled
Native App Locale Refresh / Refresh native ko (push) Has been cancelled
Native App Locale Refresh / Refresh native nl (push) Has been cancelled
Native App Locale Refresh / Refresh native pl (push) Has been cancelled
Native App Locale Refresh / Refresh native pt-BR (push) Has been cancelled
Native App Locale Refresh / Refresh native ru (push) Has been cancelled
Native App Locale Refresh / Refresh native sv (push) Has been cancelled
Native App Locale Refresh / Refresh native th (push) Has been cancelled
Native App Locale Refresh / Refresh native tr (push) Has been cancelled
Native App Locale Refresh / Refresh native uk (push) Has been cancelled
Native App Locale Refresh / Refresh native vi (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-CN (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-TW (push) Has been cancelled
Native App Locale Refresh / Commit native locale refresh (push) Has been cancelled
Plugin Init Scaffold Validation / Validate provider scaffold (push) Has been cancelled
Plugin NPM Release / preview_plugins_npm (push) Has been cancelled
Plugin NPM Release / Validate release publish approval (push) Has been cancelled
Plugin NPM Release / preview_plugin_pack (push) Has been cancelled
Plugin NPM Release / publish_plugins_npm (push) Has been cancelled
Sandbox Common Smoke / sandbox-common-smoke (push) Has been cancelled
Website Installer Sync / static (push) Has been cancelled
Website Installer Sync / linux-docker (push) Has been cancelled
Website Installer Sync / macos-installer (push) Has been cancelled
Website Installer Sync / windows-installer (push) Has been cancelled
Website Installer Sync / sync-website (push) Has been cancelled
Some checks failed
ClawSweeper Dispatch / dispatch (push) Has been cancelled
CodeQL / Security High (actions) (push) Has been cancelled
CodeQL / Security High (channel-runtime-boundary) (push) Has been cancelled
CodeQL / Security High (core-auth-secrets) (push) Has been cancelled
CodeQL / Security High (mcp-process-tool-boundary) (push) Has been cancelled
CodeQL / Security High (network-ssrf-boundary) (push) Has been cancelled
CodeQL / Security High (plugin-trust-boundary) (push) Has been cancelled
CodeQL / Security High (process-exec-boundary) (push) Has been cancelled
Docs Sync Publish Repo / sync-publish-repo (push) Has been cancelled
Docs / docs (push) Has been cancelled
OpenClaw Stable Main Closeout / Resolve stable release closeout inputs (push) Has been cancelled
OpenClaw Stable Main Closeout / Verify stable main closeout (push) Has been cancelled
Workflow Sanity / no-tabs (push) Has been cancelled
Workflow Sanity / actionlint (push) Has been cancelled
Workflow Sanity / generated-doc-baselines (push) Has been cancelled
CI / runner-admission (push) Has been cancelled
CI / preflight (push) Has been cancelled
CI / security-fast (push) Has been cancelled
CI / pnpm-store-warmup (push) Has been cancelled
CI / build-artifacts (push) Has been cancelled
CI / native-i18n (push) Has been cancelled
CI / ${{ matrix.check_name }} (push) Has been cancelled
CI / ${{ matrix.checkName }} (push) Has been cancelled
CI / checks-node-compat-node22 (push) Has been cancelled
CI / check-bundled-channel-config-metadata (push) Has been cancelled
CI / check-dependencies (push) Has been cancelled
CI / check-guards (push) Has been cancelled
CI / check-lint (push) Has been cancelled
CI / check-prod-types (push) Has been cancelled
CI / check-shrinkwrap (push) Has been cancelled
CI / check-test-types (push) Has been cancelled
CI / check-additional-boundaries-a (push) Has been cancelled
CI / check-additional-boundaries-bcd (push) Has been cancelled
CI / check-additional-extension-bundled (push) Has been cancelled
CI / check-additional-extension-channels (push) Has been cancelled
CI / check-additional-extension-package-boundary (push) Has been cancelled
CI / check-additional-runtime-topology-architecture (push) Has been cancelled
CI / check-session-accessor-boundary (push) Has been cancelled
CI / check-session-transcript-reader-boundary (push) Has been cancelled
CI / check-docs (push) Has been cancelled
CI / skills-python (push) Has been cancelled
CI / macos-swift (push) Has been cancelled
CI / ios-build (push) Has been cancelled
CI / ci-timings-summary (push) Has been cancelled
Native App Locale Refresh / Refresh native fa (push) Has been cancelled
Native App Locale Refresh / Refresh native fr (push) Has been cancelled
Native App Locale Refresh / Refresh native hi (push) Has been cancelled
Native App Locale Refresh / Refresh native id (push) Has been cancelled
Native App Locale Refresh / Refresh native it (push) Has been cancelled
Native App Locale Refresh / Refresh native ja-JP (push) Has been cancelled
Control UI Locale Refresh / plan (push) Has been cancelled
Control UI Locale Refresh / Refresh ${{ matrix.locale }} (push) Has been cancelled
Control UI Locale Refresh / Commit control UI locale refresh (push) Has been cancelled
Live Media Runner Image / Build live media runner image (push) Has been cancelled
Native App Locale Refresh / Refresh native ar (push) Has been cancelled
Native App Locale Refresh / Refresh native de (push) Has been cancelled
Native App Locale Refresh / Refresh native es (push) Has been cancelled
Native App Locale Refresh / Refresh native ko (push) Has been cancelled
Native App Locale Refresh / Refresh native nl (push) Has been cancelled
Native App Locale Refresh / Refresh native pl (push) Has been cancelled
Native App Locale Refresh / Refresh native pt-BR (push) Has been cancelled
Native App Locale Refresh / Refresh native ru (push) Has been cancelled
Native App Locale Refresh / Refresh native sv (push) Has been cancelled
Native App Locale Refresh / Refresh native th (push) Has been cancelled
Native App Locale Refresh / Refresh native tr (push) Has been cancelled
Native App Locale Refresh / Refresh native uk (push) Has been cancelled
Native App Locale Refresh / Refresh native vi (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-CN (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-TW (push) Has been cancelled
Native App Locale Refresh / Commit native locale refresh (push) Has been cancelled
Plugin Init Scaffold Validation / Validate provider scaffold (push) Has been cancelled
Plugin NPM Release / preview_plugins_npm (push) Has been cancelled
Plugin NPM Release / Validate release publish approval (push) Has been cancelled
Plugin NPM Release / preview_plugin_pack (push) Has been cancelled
Plugin NPM Release / publish_plugins_npm (push) Has been cancelled
Sandbox Common Smoke / sandbox-common-smoke (push) Has been cancelled
Website Installer Sync / static (push) Has been cancelled
Website Installer Sync / linux-docker (push) Has been cancelled
Website Installer Sync / macos-installer (push) Has been cancelled
Website Installer Sync / windows-installer (push) Has been cancelled
Website Installer Sync / sync-website (push) Has been cancelled
Adolf is a fork/vendored clone of github.com/openclaw/openclaw (v2026.6.11), free to diverge. Tree copied sans upstream .git; upstream remote added for future syncs. Node pinned to 24 (.nvmrc); engines already require >=22.19. Preserves docs/ARCHITECTURE.md. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LeqyaxJF2nbRXJtae2kNB2
This commit is contained in:
12
extensions/kimi-coding/README.md
Normal file
12
extensions/kimi-coding/README.md
Normal file
@@ -0,0 +1,12 @@
|
||||
# OpenClaw Kimi Coding Provider
|
||||
|
||||
Official OpenClaw provider plugin for Kimi Coding.
|
||||
|
||||
Install from OpenClaw:
|
||||
|
||||
```bash
|
||||
openclaw plugins install @openclaw/kimi-provider
|
||||
openclaw gateway restart
|
||||
```
|
||||
|
||||
See <https://docs.openclaw.ai/providers/moonshot> for setup and configuration.
|
||||
9
extensions/kimi-coding/api.ts
Normal file
9
extensions/kimi-coding/api.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
// Kimi Coding API module exposes the plugin public contract.
|
||||
export {
|
||||
buildKimiCodingProvider,
|
||||
KIMI_CODING_BASE_URL,
|
||||
KIMI_CODING_DEFAULT_MODEL_ID,
|
||||
KIMI_CODING_LEGACY_MODEL_IDS,
|
||||
normalizeKimiCodingModelId,
|
||||
} from "./provider-catalog.js";
|
||||
export { KIMI_CODING_MODEL_REF, KIMI_MODEL_REF } from "./onboard.js";
|
||||
104
extensions/kimi-coding/implicit-provider.test.ts
Normal file
104
extensions/kimi-coding/implicit-provider.test.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
// Kimi Coding tests cover implicit provider plugin behavior.
|
||||
import { registerSingleProviderPlugin } from "openclaw/plugin-sdk/plugin-test-runtime";
|
||||
import { describe, expect, it } from "vitest";
|
||||
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).toEqual({
|
||||
baseUrl: "https://api.kimi.com/coding/",
|
||||
api: "anthropic-messages",
|
||||
headers: {
|
||||
"User-Agent": "claude-code/0.1.0",
|
||||
},
|
||||
models: [
|
||||
{
|
||||
id: "kimi-for-coding",
|
||||
name: "Kimi Code",
|
||||
reasoning: true,
|
||||
input: ["text", "image"],
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
contextWindow: 262144,
|
||||
maxTokens: 32768,
|
||||
},
|
||||
{
|
||||
id: "kimi-code",
|
||||
name: "Kimi Code (legacy kimi-code)",
|
||||
reasoning: true,
|
||||
input: ["text", "image"],
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
contextWindow: 262144,
|
||||
maxTokens: 32768,
|
||||
},
|
||||
{
|
||||
id: "k2p5",
|
||||
name: "Kimi Code (legacy k2p5)",
|
||||
reasoning: true,
|
||||
input: ["text", "image"],
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
contextWindow: 262144,
|
||||
maxTokens: 32768,
|
||||
},
|
||||
],
|
||||
apiKey: "test-key",
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores retired kimi-coding provider overrides", async () => {
|
||||
const provider = await runKimiCatalogProvider({
|
||||
apiKey: "test-key",
|
||||
explicitProvider: {
|
||||
baseUrl: "https://kimi.example.test/coding/",
|
||||
headers: {
|
||||
"User-Agent": "custom-kimi-client/1.0",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(provider.baseUrl).toBe("https://api.kimi.com/coding/");
|
||||
expect(provider.headers).toEqual({ "User-Agent": "claude-code/0.1.0" });
|
||||
});
|
||||
});
|
||||
46
extensions/kimi-coding/index.test.ts
Normal file
46
extensions/kimi-coding/index.test.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
// Kimi Coding tests cover index plugin behavior.
|
||||
import { registerSingleProviderPlugin } from "openclaw/plugin-sdk/plugin-test-runtime";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import plugin from "./index.js";
|
||||
|
||||
describe("kimi provider plugin", () => {
|
||||
it("normalizes legacy Kimi Code ids to the stable API model id", async () => {
|
||||
const provider = await registerSingleProviderPlugin(plugin);
|
||||
|
||||
expect(
|
||||
provider.normalizeResolvedModel?.({
|
||||
provider: "kimi",
|
||||
modelId: "kimi-code",
|
||||
model: {
|
||||
id: "kimi-code",
|
||||
name: "Kimi Code",
|
||||
provider: "kimi",
|
||||
api: "anthropic-messages",
|
||||
},
|
||||
} as never),
|
||||
).toEqual({
|
||||
id: "kimi-for-coding",
|
||||
name: "Kimi Code",
|
||||
provider: "kimi",
|
||||
api: "anthropic-messages",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses binary thinking with thinking off by default", async () => {
|
||||
const provider = await registerSingleProviderPlugin(plugin);
|
||||
|
||||
expect(
|
||||
provider.resolveThinkingProfile?.({
|
||||
provider: "kimi",
|
||||
modelId: "kimi-code",
|
||||
reasoning: true,
|
||||
} as never),
|
||||
).toEqual({
|
||||
levels: [
|
||||
{ id: "off", label: "off" },
|
||||
{ id: "low", label: "on" },
|
||||
],
|
||||
defaultLevel: "off",
|
||||
});
|
||||
});
|
||||
});
|
||||
114
extensions/kimi-coding/index.ts
Normal file
114
extensions/kimi-coding/index.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
// Kimi Coding plugin entrypoint registers its OpenClaw integration.
|
||||
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/string-coerce-runtime";
|
||||
import { applyKimiCodeConfig, KIMI_CODING_MODEL_REF } from "./onboard.js";
|
||||
import { buildKimiCodingProvider, normalizeKimiCodingModelId } 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.6 + 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.6)",
|
||||
groupHint: "Kimi K2.6",
|
||||
},
|
||||
}),
|
||||
],
|
||||
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,
|
||||
normalizeResolvedModel: ({ model }) => {
|
||||
const normalizedId = normalizeKimiCodingModelId(model.id);
|
||||
return normalizedId === model.id ? undefined : { ...model, id: normalizedId };
|
||||
},
|
||||
resolveThinkingProfile: () => ({
|
||||
levels: [
|
||||
{ id: "off", label: "off" },
|
||||
{ id: "low", label: "on" },
|
||||
],
|
||||
defaultLevel: "off",
|
||||
}),
|
||||
wrapStreamFn: wrapKimiProviderStream,
|
||||
});
|
||||
},
|
||||
});
|
||||
12
extensions/kimi-coding/npm-shrinkwrap.json
generated
Normal file
12
extensions/kimi-coding/npm-shrinkwrap.json
generated
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "@openclaw/kimi-provider",
|
||||
"version": "2026.6.11",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@openclaw/kimi-provider",
|
||||
"version": "2026.6.11"
|
||||
}
|
||||
}
|
||||
}
|
||||
44
extensions/kimi-coding/onboard.test.ts
Normal file
44
extensions/kimi-coding/onboard.test.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
// Kimi Coding tests cover onboard plugin behavior.
|
||||
import { resolveAgentModelPrimaryValue } from "openclaw/plugin-sdk/provider-onboard";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
applyKimiCodeConfig,
|
||||
KIMI_CODING_MODEL_REF,
|
||||
KIMI_MODEL_REF,
|
||||
} from "./onboard.js";
|
||||
|
||||
describe("kimi coding onboard", () => {
|
||||
it("keeps the historical Kimi model ref alias pointed at the coding default", () => {
|
||||
expect(KIMI_MODEL_REF).toBe("kimi/kimi-for-coding");
|
||||
expect(KIMI_CODING_MODEL_REF).toBe(KIMI_MODEL_REF);
|
||||
});
|
||||
|
||||
it("adds the Kimi coding provider defaults", () => {
|
||||
const cfg = applyKimiCodeConfig({});
|
||||
const provider = cfg.models?.providers?.kimi;
|
||||
|
||||
expect(provider).toEqual({
|
||||
api: "anthropic-messages",
|
||||
baseUrl: "https://api.kimi.com/coding/",
|
||||
models: [
|
||||
{
|
||||
id: "kimi-for-coding",
|
||||
name: "Kimi Code",
|
||||
reasoning: true,
|
||||
input: ["text", "image"],
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
contextWindow: 262144,
|
||||
maxTokens: 32768,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(provider?.models?.map((model) => model.id)).toEqual(["kimi-for-coding"]);
|
||||
expect(cfg.agents?.defaults?.models?.[KIMI_MODEL_REF]?.alias).toBe("Kimi");
|
||||
});
|
||||
|
||||
it("sets the agent primary model when applying the full Kimi coding preset", () => {
|
||||
const cfg = applyKimiCodeConfig({});
|
||||
|
||||
expect(resolveAgentModelPrimaryValue(cfg.agents?.defaults?.model)).toBe(KIMI_MODEL_REF);
|
||||
});
|
||||
});
|
||||
39
extensions/kimi-coding/onboard.ts
Normal file
39
extensions/kimi-coding/onboard.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
// Kimi Coding setup module handles plugin onboarding behavior.
|
||||
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 applyKimiCodeConfig(cfg: OpenClawConfig): OpenClawConfig {
|
||||
return kimiCodingPresetAppliers.applyConfig(cfg);
|
||||
}
|
||||
72
extensions/kimi-coding/openclaw.plugin.json
Normal file
72
extensions/kimi-coding/openclaw.plugin.json
Normal file
@@ -0,0 +1,72 @@
|
||||
{
|
||||
"id": "kimi",
|
||||
"activation": {
|
||||
"onStartup": false
|
||||
},
|
||||
"enabledByDefault": true,
|
||||
"providers": ["kimi", "kimi-coding"],
|
||||
"providerRequest": {
|
||||
"providers": {
|
||||
"kimi": {
|
||||
"family": "moonshot",
|
||||
"compatibilityFamily": "moonshot"
|
||||
},
|
||||
"kimi-coding": {
|
||||
"family": "moonshot",
|
||||
"compatibilityFamily": "moonshot"
|
||||
}
|
||||
}
|
||||
},
|
||||
"modelPricing": {
|
||||
"providers": {
|
||||
"kimi": {
|
||||
"openRouter": {
|
||||
"provider": "moonshotai"
|
||||
},
|
||||
"liteLLM": {
|
||||
"provider": "moonshot"
|
||||
}
|
||||
},
|
||||
"kimi-coding": {
|
||||
"openRouter": {
|
||||
"provider": "moonshotai"
|
||||
},
|
||||
"liteLLM": {
|
||||
"provider": "moonshot"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"setup": {
|
||||
"providers": [
|
||||
{
|
||||
"id": "kimi",
|
||||
"envVars": ["KIMI_API_KEY", "KIMICODE_API_KEY"]
|
||||
},
|
||||
{
|
||||
"id": "kimi-coding",
|
||||
"envVars": ["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.6)",
|
||||
"groupHint": "Kimi K2.6",
|
||||
"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": {}
|
||||
}
|
||||
}
|
||||
35
extensions/kimi-coding/package.json
Normal file
35
extensions/kimi-coding/package.json
Normal file
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"name": "@openclaw/kimi-provider",
|
||||
"version": "2026.6.11",
|
||||
"description": "OpenClaw Kimi provider plugin.",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/openclaw/openclaw"
|
||||
},
|
||||
"type": "module",
|
||||
"devDependencies": {
|
||||
"@openclaw/plugin-sdk": "workspace:*"
|
||||
},
|
||||
"openclaw": {
|
||||
"extensions": [
|
||||
"./index.ts"
|
||||
],
|
||||
"install": {
|
||||
"clawhubSpec": "clawhub:@openclaw/kimi-provider",
|
||||
"npmSpec": "@openclaw/kimi-provider",
|
||||
"defaultChoice": "npm",
|
||||
"minHostVersion": ">=2026.6.8"
|
||||
},
|
||||
"compat": {
|
||||
"pluginApi": ">=2026.6.11"
|
||||
},
|
||||
"build": {
|
||||
"openclawVersion": "2026.6.11",
|
||||
"bundledDist": false
|
||||
},
|
||||
"release": {
|
||||
"publishToClawHub": true,
|
||||
"publishToNpm": true
|
||||
}
|
||||
}
|
||||
}
|
||||
24
extensions/kimi-coding/provider-catalog.test.ts
Normal file
24
extensions/kimi-coding/provider-catalog.test.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
// Kimi Coding tests cover provider catalog plugin behavior.
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildKimiCodingProvider, normalizeKimiCodingModelId } 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-for-coding",
|
||||
"kimi-code",
|
||||
"k2p5",
|
||||
]);
|
||||
});
|
||||
|
||||
it("normalizes legacy Kimi coding model ids to the stable API model id", () => {
|
||||
expect(normalizeKimiCodingModelId("kimi-code")).toBe("kimi-for-coding");
|
||||
expect(normalizeKimiCodingModelId("k2p5")).toBe("kimi-for-coding");
|
||||
expect(normalizeKimiCodingModelId("kimi-for-coding")).toBe("kimi-for-coding");
|
||||
});
|
||||
});
|
||||
59
extensions/kimi-coding/provider-catalog.ts
Normal file
59
extensions/kimi-coding/provider-catalog.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
// Kimi Coding provider module implements model/runtime integration.
|
||||
import type {
|
||||
ModelDefinitionConfig,
|
||||
ModelProviderConfig,
|
||||
} from "openclaw/plugin-sdk/provider-model-shared";
|
||||
|
||||
const KIMI_BASE_URL = "https://api.kimi.com/coding/";
|
||||
const KIMI_CODING_USER_AGENT = "claude-code/0.1.0";
|
||||
const KIMI_DEFAULT_MODEL_ID = "kimi-for-coding";
|
||||
const KIMI_LEGACY_MODEL_IDS = ["kimi-code", "k2p5"] as const;
|
||||
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,
|
||||
};
|
||||
const KIMI_CODING_INPUT = ["text", "image"] satisfies NonNullable<ModelDefinitionConfig["input"]>;
|
||||
|
||||
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: [...KIMI_CODING_INPUT],
|
||||
cost: KIMI_CODING_DEFAULT_COST,
|
||||
contextWindow: KIMI_CODING_DEFAULT_CONTEXT_WINDOW,
|
||||
maxTokens: KIMI_CODING_DEFAULT_MAX_TOKENS,
|
||||
},
|
||||
...KIMI_LEGACY_MODEL_IDS.map((id) => ({
|
||||
id,
|
||||
name: `Kimi Code (legacy ${id})`,
|
||||
reasoning: true,
|
||||
input: [...KIMI_CODING_INPUT],
|
||||
cost: KIMI_CODING_DEFAULT_COST,
|
||||
contextWindow: KIMI_CODING_DEFAULT_CONTEXT_WINDOW,
|
||||
maxTokens: KIMI_CODING_DEFAULT_MAX_TOKENS,
|
||||
})),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeKimiCodingModelId(modelId: string): string {
|
||||
return KIMI_LEGACY_MODEL_IDS.includes(modelId as (typeof KIMI_LEGACY_MODEL_IDS)[number])
|
||||
? KIMI_DEFAULT_MODEL_ID
|
||||
: modelId;
|
||||
}
|
||||
|
||||
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_IDS = KIMI_LEGACY_MODEL_IDS;
|
||||
11
extensions/kimi-coding/replay-policy.test.ts
Normal file
11
extensions/kimi-coding/replay-policy.test.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
// Kimi Coding tests cover replay policy plugin behavior.
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { KIMI_REPLAY_POLICY } from "./replay-policy.js";
|
||||
|
||||
describe("kimi replay policy", () => {
|
||||
it("disables signature preservation for replay repair", () => {
|
||||
expect(KIMI_REPLAY_POLICY).toEqual({
|
||||
preserveSignatures: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
4
extensions/kimi-coding/replay-policy.ts
Normal file
4
extensions/kimi-coding/replay-policy.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
// Kimi Coding plugin module implements replay policy behavior.
|
||||
export const KIMI_REPLAY_POLICY = {
|
||||
preserveSignatures: false,
|
||||
};
|
||||
680
extensions/kimi-coding/stream.test.ts
Normal file
680
extensions/kimi-coding/stream.test.ts
Normal file
@@ -0,0 +1,680 @@
|
||||
// Kimi Coding tests cover stream plugin behavior.
|
||||
import type { StreamFn } from "openclaw/plugin-sdk/agent-core";
|
||||
import type { Context, Model } from "openclaw/plugin-sdk/llm";
|
||||
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|>';
|
||||
const KIMI_MODEL = {
|
||||
api: "anthropic-messages",
|
||||
provider: "kimi",
|
||||
id: "k2p5",
|
||||
} as Model<"anthropic-messages">;
|
||||
const KIMI_CONTEXT = { messages: [] } as Context;
|
||||
|
||||
function createReadToolCall() {
|
||||
return {
|
||||
type: "toolCall",
|
||||
id: "functions.read:0",
|
||||
name: "functions.read",
|
||||
arguments: { file_path: "./package.json" },
|
||||
};
|
||||
}
|
||||
|
||||
function createAssistantTextMessage(text: string) {
|
||||
return {
|
||||
role: "assistant",
|
||||
content: [{ type: "text", text }],
|
||||
stopReason: "stop",
|
||||
};
|
||||
}
|
||||
|
||||
function createResultStreamFn(resultMessage: unknown): StreamFn {
|
||||
return () =>
|
||||
createFakeStream({
|
||||
events: [],
|
||||
resultMessage,
|
||||
}) as ReturnType<StreamFn>;
|
||||
}
|
||||
|
||||
async function callKimiStream(wrapped: StreamFn): Promise<FakeStream> {
|
||||
return (await wrapped(KIMI_MODEL, KIMI_CONTEXT, {})) as FakeStream;
|
||||
}
|
||||
|
||||
function createPayloadCapturingStream(initialPayload: Record<string, unknown> = {}) {
|
||||
let capturedPayload: Record<string, unknown> | undefined;
|
||||
const streamFn: StreamFn = (model, _context, options) => {
|
||||
const payload: Record<string, unknown> = { ...initialPayload };
|
||||
options?.onPayload?.(payload as never, model as never);
|
||||
capturedPayload = payload;
|
||||
return createFakeStream({
|
||||
events: [],
|
||||
resultMessage: { role: "assistant", content: [] },
|
||||
}) as never;
|
||||
};
|
||||
return { streamFn, getCapturedPayload: () => capturedPayload };
|
||||
}
|
||||
|
||||
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: [
|
||||
{
|
||||
...createReadToolCall(),
|
||||
},
|
||||
],
|
||||
stopReason: "toolUse",
|
||||
},
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
...createReadToolCall(),
|
||||
},
|
||||
],
|
||||
stopReason: "toolUse",
|
||||
},
|
||||
},
|
||||
]);
|
||||
expect(result).toEqual({
|
||||
role: "assistant",
|
||||
content: [
|
||||
{ type: "thinking", thinking: "Need to read the file first." },
|
||||
{
|
||||
...createReadToolCall(),
|
||||
},
|
||||
],
|
||||
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 = createAssistantTextMessage(KIMI_TOOL_TEXT);
|
||||
const baseStreamFn: StreamFn = async (model, context, options) =>
|
||||
createResultStreamFn(finalMessage)(model, context, options);
|
||||
|
||||
const wrapped = createKimiToolCallMarkupWrapper(baseStreamFn);
|
||||
const stream = await callKimiStream(wrapped);
|
||||
|
||||
await expect(stream.result()).resolves.toEqual({
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
...createReadToolCall(),
|
||||
},
|
||||
],
|
||||
stopReason: "toolUse",
|
||||
});
|
||||
});
|
||||
|
||||
it("parses multiple tagged tool calls in one section", async () => {
|
||||
const finalMessage = createAssistantTextMessage(KIMI_MULTI_TOOL_TEXT);
|
||||
const baseStreamFn = createResultStreamFn(finalMessage);
|
||||
|
||||
const wrapped = createKimiToolCallMarkupWrapper(baseStreamFn);
|
||||
const stream = await callKimiStream(wrapped);
|
||||
|
||||
await expect(stream.result()).resolves.toEqual({
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
...createReadToolCall(),
|
||||
},
|
||||
{
|
||||
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 = createAssistantTextMessage(KIMI_TOOL_TEXT);
|
||||
const baseStreamFn = createResultStreamFn(finalMessage);
|
||||
|
||||
const wrapped = wrapKimiProviderStream({
|
||||
streamFn: baseStreamFn,
|
||||
} as never);
|
||||
const stream = await callKimiStream(wrapped);
|
||||
|
||||
await expect(stream.result()).resolves.toEqual({
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
...createReadToolCall(),
|
||||
},
|
||||
],
|
||||
stopReason: "toolUse",
|
||||
});
|
||||
});
|
||||
|
||||
it("forces Kimi thinking disabled and strips proxy reasoning fields", () => {
|
||||
const { streamFn: baseStreamFn, getCapturedPayload } = createPayloadCapturingStream({
|
||||
reasoning: { effort: "high" },
|
||||
reasoning_effort: "high",
|
||||
reasoningEffort: "high",
|
||||
});
|
||||
|
||||
const wrapped = createKimiThinkingWrapper(baseStreamFn, "disabled");
|
||||
void wrapped(
|
||||
{
|
||||
api: "anthropic-messages",
|
||||
provider: "kimi",
|
||||
id: "kimi-code",
|
||||
} as Model<"anthropic-messages">,
|
||||
{ messages: [] } as Context,
|
||||
{},
|
||||
);
|
||||
|
||||
expect(getCapturedPayload()).toEqual({
|
||||
thinking: { type: "disabled" },
|
||||
});
|
||||
});
|
||||
|
||||
it("strips Anthropic cache_control markers before Kimi requests are sent", () => {
|
||||
const { streamFn: baseStreamFn, getCapturedPayload } = createPayloadCapturingStream({
|
||||
system: [{ type: "text", text: "stable", cache_control: { type: "ephemeral", ttl: "1h" } }],
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "text", text: "hello", cache_control: { type: "ephemeral" } },
|
||||
{
|
||||
type: "tool_result",
|
||||
tool_use_id: "tool_1",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "done",
|
||||
cache_control: { type: "ephemeral" },
|
||||
},
|
||||
],
|
||||
cache_control: { type: "ephemeral" },
|
||||
},
|
||||
{
|
||||
type: "tool_use",
|
||||
id: "tool_2",
|
||||
name: "persist",
|
||||
input: {
|
||||
cache_control: "tool argument",
|
||||
nested: { cache_control: "nested argument" },
|
||||
},
|
||||
cache_control: { type: "ephemeral" },
|
||||
},
|
||||
{ type: "text", text: "bye" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const wrapped = createKimiThinkingWrapper(baseStreamFn, "enabled");
|
||||
void wrapped(
|
||||
{
|
||||
api: "anthropic-messages",
|
||||
provider: "kimi",
|
||||
id: "kimi-code",
|
||||
} as Model<"anthropic-messages">,
|
||||
{ messages: [] } as Context,
|
||||
{},
|
||||
);
|
||||
|
||||
expect(getCapturedPayload()).toEqual({
|
||||
system: [{ type: "text", text: "stable" }],
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "text", text: "hello" },
|
||||
{
|
||||
type: "tool_result",
|
||||
tool_use_id: "tool_1",
|
||||
content: [{ type: "text", text: "done" }],
|
||||
},
|
||||
{
|
||||
type: "tool_use",
|
||||
id: "tool_2",
|
||||
name: "persist",
|
||||
input: {
|
||||
cache_control: "tool argument",
|
||||
nested: { cache_control: "nested argument" },
|
||||
},
|
||||
},
|
||||
{ type: "text", text: "bye" },
|
||||
],
|
||||
},
|
||||
],
|
||||
thinking: { type: "enabled" },
|
||||
});
|
||||
});
|
||||
|
||||
it("lets explicit model params keep Kimi thinking disabled even when session thinking is on", () => {
|
||||
const { streamFn: baseStreamFn, getCapturedPayload } = createPayloadCapturingStream();
|
||||
|
||||
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(getCapturedPayload()).toEqual({
|
||||
thinking: { type: "disabled" },
|
||||
});
|
||||
});
|
||||
|
||||
it("backfills Kimi OpenAI-compatible tool-call reasoning_content when thinking is enabled", () => {
|
||||
const { streamFn: baseStreamFn, getCapturedPayload } = createPayloadCapturingStream({
|
||||
messages: [
|
||||
{ role: "user", content: "run pwd" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: null,
|
||||
tool_calls: [
|
||||
{
|
||||
id: "call_1",
|
||||
type: "function",
|
||||
function: { name: "exec", arguments: '{"command":"pwd"}' },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: "assistant",
|
||||
content: "kept",
|
||||
reasoning_content: "native reasoning",
|
||||
tool_calls: [
|
||||
{
|
||||
id: "call_2",
|
||||
type: "function",
|
||||
function: { name: "read", arguments: "{}" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const wrapped = createKimiThinkingWrapper(baseStreamFn, "enabled");
|
||||
void wrapped(
|
||||
{
|
||||
api: "openai-completions",
|
||||
provider: "kimi",
|
||||
id: "kimi-for-coding",
|
||||
} as Model<"openai-completions">,
|
||||
{ messages: [] } as Context,
|
||||
{},
|
||||
);
|
||||
|
||||
expect(getCapturedPayload()).toEqual({
|
||||
messages: [
|
||||
{ role: "user", content: "run pwd" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: null,
|
||||
reasoning_content: "",
|
||||
tool_calls: [
|
||||
{
|
||||
id: "call_1",
|
||||
type: "function",
|
||||
function: { name: "exec", arguments: '{"command":"pwd"}' },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: "assistant",
|
||||
content: "kept",
|
||||
reasoning_content: "native reasoning",
|
||||
tool_calls: [
|
||||
{
|
||||
id: "call_2",
|
||||
type: "function",
|
||||
function: { name: "read", arguments: "{}" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
thinking: { type: "enabled" },
|
||||
});
|
||||
});
|
||||
|
||||
it("strips Kimi OpenAI-compatible replay reasoning_content when thinking is disabled", () => {
|
||||
const { streamFn: baseStreamFn, getCapturedPayload } = createPayloadCapturingStream({
|
||||
messages: [
|
||||
{
|
||||
role: "assistant",
|
||||
content: null,
|
||||
reasoning_content: "old reasoning",
|
||||
tool_calls: [
|
||||
{
|
||||
id: "call_1",
|
||||
type: "function",
|
||||
function: { name: "exec", arguments: '{"command":"pwd"}' },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const wrapped = createKimiThinkingWrapper(baseStreamFn, "disabled");
|
||||
void wrapped(
|
||||
{
|
||||
api: "openai-completions",
|
||||
provider: "kimi",
|
||||
id: "kimi-for-coding",
|
||||
} as Model<"openai-completions">,
|
||||
{ messages: [] } as Context,
|
||||
{},
|
||||
);
|
||||
|
||||
expect(getCapturedPayload()).toEqual({
|
||||
messages: [
|
||||
{
|
||||
role: "assistant",
|
||||
content: null,
|
||||
tool_calls: [
|
||||
{
|
||||
id: "call_1",
|
||||
type: "function",
|
||||
function: { name: "exec", arguments: '{"command":"pwd"}' },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
thinking: { type: "disabled" },
|
||||
});
|
||||
});
|
||||
|
||||
it("enables Kimi Anthropic thinking with a high budget and enough output room", () => {
|
||||
const { streamFn: baseStreamFn, getCapturedPayload } = createPayloadCapturingStream();
|
||||
|
||||
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(getCapturedPayload()).toEqual({
|
||||
max_tokens: 16000,
|
||||
thinking: { type: "enabled", budget_tokens: 8192 },
|
||||
});
|
||||
});
|
||||
|
||||
it("adds the default Kimi Anthropic thinking budget for explicit enabled params", () => {
|
||||
const cases = ["enabled", true, { type: "enabled" }] as const;
|
||||
|
||||
for (const configuredThinking of cases) {
|
||||
const { streamFn: baseStreamFn, getCapturedPayload } = createPayloadCapturingStream();
|
||||
const wrapped = wrapKimiProviderStream({
|
||||
provider: "kimi",
|
||||
modelId: "kimi-code",
|
||||
extraParams: { thinking: configuredThinking },
|
||||
streamFn: baseStreamFn,
|
||||
} as never);
|
||||
|
||||
void wrapped(
|
||||
{
|
||||
api: "anthropic-messages",
|
||||
provider: "kimi",
|
||||
id: "kimi-code",
|
||||
} as Model<"anthropic-messages">,
|
||||
{ messages: [] } as Context,
|
||||
{},
|
||||
);
|
||||
|
||||
expect(getCapturedPayload()).toEqual({
|
||||
max_tokens: 16000,
|
||||
thinking: { type: "enabled", budget_tokens: 1024 },
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("uses the session Kimi Anthropic budget for explicit enabled params when available", () => {
|
||||
const { streamFn: baseStreamFn, getCapturedPayload } = createPayloadCapturingStream();
|
||||
|
||||
const wrapped = wrapKimiProviderStream({
|
||||
provider: "kimi",
|
||||
modelId: "kimi-code",
|
||||
extraParams: { thinking: "enabled" },
|
||||
thinkingLevel: "medium",
|
||||
streamFn: baseStreamFn,
|
||||
} as never);
|
||||
|
||||
void wrapped(
|
||||
{
|
||||
api: "anthropic-messages",
|
||||
provider: "kimi",
|
||||
id: "kimi-code",
|
||||
} as Model<"anthropic-messages">,
|
||||
{ messages: [] } as Context,
|
||||
{},
|
||||
);
|
||||
|
||||
expect(getCapturedPayload()).toEqual({
|
||||
max_tokens: 16000,
|
||||
thinking: { type: "enabled", budget_tokens: 4096 },
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves explicit Kimi Anthropic thinking budgets", () => {
|
||||
const { streamFn: baseStreamFn, getCapturedPayload } = createPayloadCapturingStream();
|
||||
|
||||
const wrapped = wrapKimiProviderStream({
|
||||
provider: "kimi",
|
||||
modelId: "kimi-code",
|
||||
extraParams: { thinking: { type: "enabled", budget_tokens: 4096 } },
|
||||
thinkingLevel: "high",
|
||||
streamFn: baseStreamFn,
|
||||
} as never);
|
||||
|
||||
void wrapped(
|
||||
{
|
||||
api: "anthropic-messages",
|
||||
provider: "kimi",
|
||||
id: "kimi-code",
|
||||
} as Model<"anthropic-messages">,
|
||||
{ messages: [] } as Context,
|
||||
{},
|
||||
);
|
||||
|
||||
expect(getCapturedPayload()).toEqual({
|
||||
max_tokens: 16000,
|
||||
thinking: { type: "enabled", budget_tokens: 4096 },
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves larger Kimi Anthropic max_tokens values", () => {
|
||||
const { streamFn: baseStreamFn, getCapturedPayload } = createPayloadCapturingStream({
|
||||
max_tokens: 32768,
|
||||
});
|
||||
|
||||
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(getCapturedPayload()).toEqual({
|
||||
max_tokens: 32768,
|
||||
thinking: { type: "enabled", budget_tokens: 8192 },
|
||||
});
|
||||
});
|
||||
|
||||
it("bounds Kimi Anthropic thinking for session thinking levels", () => {
|
||||
const cases = [
|
||||
["minimal", 1024],
|
||||
["low", 1024],
|
||||
["medium", 4096],
|
||||
["high", 8192],
|
||||
["adaptive", 8192],
|
||||
["xhigh", 8192],
|
||||
["max", 8192],
|
||||
] as const;
|
||||
|
||||
for (const [thinkingLevel, budgetTokens] of cases) {
|
||||
const { streamFn: baseStreamFn, getCapturedPayload } = createPayloadCapturingStream();
|
||||
const wrapped = wrapKimiProviderStream({
|
||||
provider: "kimi",
|
||||
modelId: "kimi-code",
|
||||
thinkingLevel,
|
||||
streamFn: baseStreamFn,
|
||||
} as never);
|
||||
|
||||
void wrapped(
|
||||
{
|
||||
api: "anthropic-messages",
|
||||
provider: "kimi",
|
||||
id: "kimi-code",
|
||||
} as Model<"anthropic-messages">,
|
||||
{ messages: [] } as Context,
|
||||
{},
|
||||
);
|
||||
|
||||
expect(getCapturedPayload()).toEqual({
|
||||
max_tokens: 16000,
|
||||
thinking: { type: "enabled", budget_tokens: budgetTokens },
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
449
extensions/kimi-coding/stream.ts
Normal file
449
extensions/kimi-coding/stream.ts
Normal file
@@ -0,0 +1,449 @@
|
||||
// Kimi Coding plugin module implements stream behavior.
|
||||
import type { StreamFn } from "openclaw/plugin-sdk/agent-core";
|
||||
import {
|
||||
streamSimple,
|
||||
type AssistantMessage,
|
||||
type AssistantMessageEvent,
|
||||
} from "openclaw/plugin-sdk/llm";
|
||||
import type { ProviderWrapStreamFnContext } from "openclaw/plugin-sdk/plugin-entry";
|
||||
import { streamWithPayloadPatch } from "openclaw/plugin-sdk/provider-stream-shared";
|
||||
import { normalizeOptionalLowercaseString } from "openclaw/plugin-sdk/string-coerce-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";
|
||||
interface MutableAssistantMessageEventStream extends AsyncIterable<AssistantMessageEvent> {
|
||||
result: () => Promise<AssistantMessage>;
|
||||
}
|
||||
type KimiThinkingConfig = {
|
||||
type: KimiThinkingType;
|
||||
budget_tokens?: number;
|
||||
};
|
||||
type KimiThinkingLevel =
|
||||
| "off"
|
||||
| "minimal"
|
||||
| "low"
|
||||
| "medium"
|
||||
| "high"
|
||||
| "xhigh"
|
||||
| "adaptive"
|
||||
| "max";
|
||||
|
||||
const KIMI_ANTHROPIC_THINKING_BUDGETS: Record<Exclude<KimiThinkingLevel, "off">, number> = {
|
||||
minimal: 1024,
|
||||
low: 1024,
|
||||
medium: 4096,
|
||||
high: 8192,
|
||||
adaptive: 8192,
|
||||
xhigh: 8192,
|
||||
max: 8192,
|
||||
};
|
||||
const KIMI_ANTHROPIC_VISIBLE_OUTPUT_RESERVE_TOKENS = 1024;
|
||||
const KIMI_ANTHROPIC_MIN_OUTPUT_TOKENS = 16000;
|
||||
|
||||
function normalizeKimiThinkingBudgetTokens(value: unknown): number | undefined {
|
||||
if (typeof value !== "number" || !Number.isFinite(value)) {
|
||||
return undefined;
|
||||
}
|
||||
const normalized = Math.floor(value);
|
||||
return normalized >= 1024 ? normalized : undefined;
|
||||
}
|
||||
|
||||
function normalizeKimiAnthropicMaxTokens(value: unknown): number | undefined {
|
||||
if (typeof value !== "number" || !Number.isFinite(value)) {
|
||||
return undefined;
|
||||
}
|
||||
const normalized = Math.floor(value);
|
||||
return normalized > 0 ? normalized : undefined;
|
||||
}
|
||||
|
||||
function ensureKimiAnthropicMaxTokens(
|
||||
payloadObj: Record<string, unknown>,
|
||||
thinkingConfig: KimiThinkingConfig,
|
||||
): void {
|
||||
if (thinkingConfig.type !== "enabled" || thinkingConfig.budget_tokens === undefined) {
|
||||
return;
|
||||
}
|
||||
const required = Math.max(
|
||||
KIMI_ANTHROPIC_MIN_OUTPUT_TOKENS,
|
||||
thinkingConfig.budget_tokens + KIMI_ANTHROPIC_VISIBLE_OUTPUT_RESERVE_TOKENS,
|
||||
);
|
||||
const current = normalizeKimiAnthropicMaxTokens(payloadObj.max_tokens);
|
||||
payloadObj.max_tokens = current === undefined ? required : Math.max(current, required);
|
||||
}
|
||||
|
||||
function messageHasOpenAIToolCalls(message: Record<string, unknown>): boolean {
|
||||
return Array.isArray(message.tool_calls) && message.tool_calls.length > 0;
|
||||
}
|
||||
|
||||
function ensureKimiOpenAIReasoningContent(payloadObj: Record<string, unknown>): void {
|
||||
if (!Array.isArray(payloadObj.messages)) {
|
||||
return;
|
||||
}
|
||||
for (const message of payloadObj.messages) {
|
||||
if (!message || typeof message !== "object") {
|
||||
continue;
|
||||
}
|
||||
const record = message as Record<string, unknown>;
|
||||
if (record.role !== "assistant" || !messageHasOpenAIToolCalls(record)) {
|
||||
continue;
|
||||
}
|
||||
if (!("reasoning_content" in record)) {
|
||||
record.reasoning_content = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function stripKimiOpenAIReasoningContent(payloadObj: Record<string, unknown>): void {
|
||||
if (!Array.isArray(payloadObj.messages)) {
|
||||
return;
|
||||
}
|
||||
for (const message of payloadObj.messages) {
|
||||
if (message && typeof message === "object") {
|
||||
delete (message as Record<string, unknown>).reasoning_content;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
function normalizeKimiThinkingConfig(value: unknown): KimiThinkingConfig | undefined {
|
||||
const type = normalizeKimiThinkingType(value);
|
||||
if (!type) {
|
||||
return undefined;
|
||||
}
|
||||
if (type === "disabled") {
|
||||
return { type: "disabled" };
|
||||
}
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
return { type: "enabled" };
|
||||
}
|
||||
const record = value as Record<string, unknown>;
|
||||
const budgetTokens = normalizeKimiThinkingBudgetTokens(
|
||||
record.budget_tokens ?? record.budgetTokens,
|
||||
);
|
||||
return budgetTokens === undefined
|
||||
? { type: "enabled" }
|
||||
: { type: "enabled", budget_tokens: budgetTokens };
|
||||
}
|
||||
|
||||
function resolveKimiAnthropicThinkingBudgetTokens(
|
||||
thinkingLevel: KimiThinkingLevel | undefined,
|
||||
): number | undefined {
|
||||
if (!thinkingLevel || thinkingLevel === "off") {
|
||||
return undefined;
|
||||
}
|
||||
return KIMI_ANTHROPIC_THINKING_BUDGETS[thinkingLevel];
|
||||
}
|
||||
|
||||
export function resolveKimiThinkingConfig(params: {
|
||||
configuredThinking: unknown;
|
||||
thinkingLevel?: KimiThinkingLevel;
|
||||
}): KimiThinkingConfig {
|
||||
const configured = normalizeKimiThinkingConfig(params.configuredThinking);
|
||||
const levelBudgetTokens = resolveKimiAnthropicThinkingBudgetTokens(params.thinkingLevel);
|
||||
if (configured) {
|
||||
return configured.type === "enabled" && configured.budget_tokens === undefined
|
||||
? { type: "enabled", budget_tokens: levelBudgetTokens ?? 1024 }
|
||||
: configured;
|
||||
}
|
||||
if (!params.thinkingLevel || params.thinkingLevel === "off") {
|
||||
return { type: "disabled" };
|
||||
}
|
||||
return levelBudgetTokens === undefined
|
||||
? { type: "enabled" }
|
||||
: { type: "enabled", budget_tokens: levelBudgetTokens };
|
||||
}
|
||||
|
||||
export function resolveKimiThinkingType(params: {
|
||||
configuredThinking: unknown;
|
||||
thinkingLevel?: KimiThinkingLevel;
|
||||
}): KimiThinkingType {
|
||||
return resolveKimiThinkingConfig(params).type;
|
||||
}
|
||||
|
||||
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 transformKimiStreamEvent(
|
||||
value: unknown,
|
||||
transformMessage: (message: unknown) => void,
|
||||
): void {
|
||||
const event =
|
||||
value && typeof value === "object"
|
||||
? (value as { partial?: unknown; message?: unknown })
|
||||
: undefined;
|
||||
if (!event) {
|
||||
return;
|
||||
}
|
||||
for (const message of [event.partial, event.message]) {
|
||||
transformMessage(message);
|
||||
}
|
||||
}
|
||||
|
||||
function wrapStreamMessageObjects(
|
||||
stream: MutableAssistantMessageEventStream,
|
||||
transformMessage: (message: unknown) => void,
|
||||
): MutableAssistantMessageEventStream {
|
||||
const readFinalMessage = stream.result.bind(stream);
|
||||
Object.assign(stream, {
|
||||
async result() {
|
||||
const message = await readFinalMessage();
|
||||
transformMessage(message);
|
||||
return message;
|
||||
},
|
||||
});
|
||||
|
||||
const createIterator = stream[Symbol.asyncIterator].bind(stream);
|
||||
stream[Symbol.asyncIterator] = () => {
|
||||
const iterator = createIterator();
|
||||
return {
|
||||
async next() {
|
||||
const step = await iterator.next();
|
||||
if (!step.done) {
|
||||
transformKimiStreamEvent(step.value, transformMessage);
|
||||
}
|
||||
return step;
|
||||
},
|
||||
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) =>
|
||||
wrapStreamMessageObjects(stream, rewriteKimiTaggedToolCallsInMessage),
|
||||
);
|
||||
}
|
||||
return wrapStreamMessageObjects(maybeStream, rewriteKimiTaggedToolCallsInMessage);
|
||||
};
|
||||
}
|
||||
|
||||
export function createKimiThinkingWrapper(
|
||||
baseStreamFn: StreamFn | undefined,
|
||||
thinkingConfig: KimiThinkingConfig | KimiThinkingType,
|
||||
): StreamFn {
|
||||
const underlying = baseStreamFn ?? streamSimple;
|
||||
return (model, context, options) =>
|
||||
streamWithPayloadPatch(underlying, model, context, options, (payloadObj) => {
|
||||
const normalized =
|
||||
typeof thinkingConfig === "string" ? { type: thinkingConfig } : thinkingConfig;
|
||||
payloadObj.thinking =
|
||||
model.api === "anthropic-messages" ? { ...normalized } : { type: normalized.type };
|
||||
if (model.api === "anthropic-messages") {
|
||||
ensureKimiAnthropicMaxTokens(payloadObj, normalized);
|
||||
} else if (normalized.type === "enabled") {
|
||||
ensureKimiOpenAIReasoningContent(payloadObj);
|
||||
} else {
|
||||
stripKimiOpenAIReasoningContent(payloadObj);
|
||||
}
|
||||
delete payloadObj.reasoning;
|
||||
delete payloadObj.reasoning_effort;
|
||||
delete payloadObj.reasoningEffort;
|
||||
stripAnthropicCacheControlMarkers(payloadObj);
|
||||
});
|
||||
}
|
||||
|
||||
function stripContentBlockCacheControl(block: unknown): void {
|
||||
if (!block || typeof block !== "object") {
|
||||
return;
|
||||
}
|
||||
|
||||
const record = block as Record<string, unknown>;
|
||||
delete record.cache_control;
|
||||
|
||||
if (record.type === "tool_result" && Array.isArray(record.content)) {
|
||||
for (const nestedBlock of record.content) {
|
||||
stripContentBlockCacheControl(nestedBlock);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function stripContentArrayCacheControl(value: unknown): void {
|
||||
if (!Array.isArray(value)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const block of value) {
|
||||
stripContentBlockCacheControl(block);
|
||||
}
|
||||
}
|
||||
|
||||
function stripAnthropicCacheControlMarkers(payloadObj: Record<string, unknown>): void {
|
||||
stripContentArrayCacheControl(payloadObj.system);
|
||||
|
||||
if (!Array.isArray(payloadObj.messages)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const message of payloadObj.messages) {
|
||||
if (!message || typeof message !== "object") {
|
||||
continue;
|
||||
}
|
||||
|
||||
stripContentArrayCacheControl((message as Record<string, unknown>).content);
|
||||
}
|
||||
}
|
||||
|
||||
export function wrapKimiProviderStream(ctx: ProviderWrapStreamFnContext): StreamFn {
|
||||
const thinkingConfig = resolveKimiThinkingConfig({
|
||||
configuredThinking: ctx.extraParams?.thinking,
|
||||
thinkingLevel: ctx.thinkingLevel,
|
||||
});
|
||||
return createKimiToolCallMarkupWrapper(createKimiThinkingWrapper(ctx.streamFn, thinkingConfig));
|
||||
}
|
||||
16
extensions/kimi-coding/tsconfig.json
Normal file
16
extensions/kimi-coding/tsconfig.json
Normal 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"
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user