pi-provider-kimi-code 0.5.1 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,256 @@
1
+ // Tool schema deduplication: extract repeated sub-schemas into $defs/$ref
2
+ // to stay under Moonshot's ~15 KB per-tool function.parameters limit.
3
+
4
+ import { createHash } from "node:crypto";
5
+
6
+ import type { JsonRecord } from "./payload.ts";
7
+
8
+ const TOOL_SCHEMA_SIZE_THRESHOLD = 14_000;
9
+ const MIN_FRAGMENT_SIZE = 50;
10
+ const MAX_DEDUP_PASSES = 5;
11
+
12
+ // ---------------------------------------------------------------------------
13
+ // Internals
14
+ // ---------------------------------------------------------------------------
15
+
16
+ function isRecord(v: unknown): v is JsonRecord {
17
+ return typeof v === "object" && v !== null && !Array.isArray(v);
18
+ }
19
+
20
+ function jsonSize(v: unknown): number {
21
+ return Buffer.byteLength(JSON.stringify(v));
22
+ }
23
+
24
+ type PathSegment = string | number;
25
+ type FragmentMap = Map<string, PathSegment[][]>;
26
+
27
+ function collectFragments(
28
+ node: unknown,
29
+ path: PathSegment[],
30
+ map: FragmentMap,
31
+ minSize: number,
32
+ ): void {
33
+ if (node === null || typeof node !== "object") return;
34
+ if (Array.isArray(node)) {
35
+ node.forEach((item, i) => collectFragments(item, [...path, i], map, minSize));
36
+ return;
37
+ }
38
+ const serialized = JSON.stringify(node);
39
+ if (serialized.length >= minSize) {
40
+ let paths = map.get(serialized);
41
+ if (!paths) {
42
+ paths = [];
43
+ map.set(serialized, paths);
44
+ }
45
+ paths.push(path);
46
+ }
47
+ for (const [key, value] of Object.entries(node as JsonRecord)) {
48
+ collectFragments(value, [...path, key], map, minSize);
49
+ }
50
+ }
51
+
52
+ function setAtPath(root: JsonRecord, path: PathSegment[], value: unknown): void {
53
+ let current: unknown = root;
54
+ for (let i = 0; i < path.length - 1; i++) {
55
+ if (!isRecord(current) && !Array.isArray(current)) return;
56
+ current = (current as Record<string, unknown>)[path[i]];
57
+ }
58
+ if (isRecord(current) || Array.isArray(current)) {
59
+ (current as Record<string, unknown>)[path[path.length - 1]] = value;
60
+ }
61
+ }
62
+
63
+ function isDescendant(child: PathSegment[], ancestor: PathSegment[]): boolean {
64
+ if (child.length <= ancestor.length) return false;
65
+ for (let i = 0; i < ancestor.length; i++) {
66
+ if (child[i] !== ancestor[i]) return false;
67
+ }
68
+ return true;
69
+ }
70
+
71
+ function nextDefKey(existing: Set<string>, index: number): string {
72
+ let key = `d${index}`;
73
+ while (existing.has(key)) key = `d${++index}`;
74
+ return key;
75
+ }
76
+
77
+ // ---------------------------------------------------------------------------
78
+ // Core dedup
79
+ // ---------------------------------------------------------------------------
80
+
81
+ function deduplicateSchema(schema: JsonRecord): JsonRecord {
82
+ const originalSize = jsonSize(schema);
83
+ const result: JsonRecord = JSON.parse(JSON.stringify(schema));
84
+ const defs: JsonRecord = isRecord(result.$defs) ? (result.$defs as JsonRecord) : {};
85
+ const existingKeys = new Set(Object.keys(defs));
86
+ let defIndex = 0;
87
+ const replaced: PathSegment[][] = [];
88
+
89
+ for (let pass = 0; pass < MAX_DEDUP_PASSES; pass++) {
90
+ const fragments: FragmentMap = new Map();
91
+ collectFragments(result, [], fragments, MIN_FRAGMENT_SIZE);
92
+
93
+ const candidates = [...fragments.entries()]
94
+ .filter(([, paths]) => paths.length >= 2)
95
+ .sort((a, b) => b[0].length - a[0].length);
96
+
97
+ let progress = false;
98
+ for (const [serialized, paths] of candidates) {
99
+ const active = paths.filter((p) => !replaced.some((r) => isDescendant(p, r)));
100
+ if (active.length < 2) continue;
101
+
102
+ const key = nextDefKey(existingKeys, defIndex++);
103
+ const refObject = JSON.stringify({ $ref: `#/$defs/${key}` });
104
+ const refSize = Buffer.byteLength(refObject);
105
+ const fragmentSize = Buffer.byteLength(serialized);
106
+ const defsEntryOverhead = Buffer.byteLength(JSON.stringify(key)) + 1;
107
+ const savings =
108
+ active.length * fragmentSize - (fragmentSize + defsEntryOverhead + active.length * refSize);
109
+ if (savings <= 0) continue;
110
+
111
+ existingKeys.add(key);
112
+ defs[key] = JSON.parse(serialized);
113
+
114
+ for (const p of active) {
115
+ setAtPath(result, p, { $ref: `#/$defs/${key}` });
116
+ replaced.push(p);
117
+ }
118
+ progress = true;
119
+ }
120
+ if (!progress) break;
121
+ }
122
+
123
+ if (Object.keys(defs).length > 0) {
124
+ result.$defs = defs;
125
+ }
126
+
127
+ if (jsonSize(result) >= originalSize) return schema;
128
+ return result;
129
+ }
130
+
131
+ // ---------------------------------------------------------------------------
132
+ // Public API with caching
133
+ // ---------------------------------------------------------------------------
134
+
135
+ let cachedFingerprint: string | null = null;
136
+ let cachedTools: unknown[] | null = null;
137
+
138
+ const objectIds = new WeakMap<object, number>();
139
+ const symbolIds = new Map<symbol, number>();
140
+ let nextOpaqueId = 0;
141
+
142
+ function identityId(t: object): number {
143
+ let id = objectIds.get(t);
144
+ if (id === undefined) {
145
+ id = nextOpaqueId++;
146
+ objectIds.set(t, id);
147
+ }
148
+ return id;
149
+ }
150
+
151
+ function symbolId(t: symbol): number {
152
+ let id = symbolIds.get(t);
153
+ if (id === undefined) {
154
+ id = nextOpaqueId++;
155
+ symbolIds.set(t, id);
156
+ }
157
+ return id;
158
+ }
159
+
160
+ function isPlainObject(v: object): boolean {
161
+ const proto = Object.getPrototypeOf(v);
162
+ return proto === null || proto === Object.prototype;
163
+ }
164
+
165
+ function hashValue(hash: ReturnType<typeof createHash>, value: unknown, seen: Set<unknown>): void {
166
+ if (value === null) {
167
+ hash.update("z");
168
+ return;
169
+ }
170
+ if (value === undefined) {
171
+ hash.update("u");
172
+ return;
173
+ }
174
+ const t = typeof value;
175
+ switch (t) {
176
+ case "boolean":
177
+ hash.update(value ? "T" : "F");
178
+ return;
179
+ case "string":
180
+ hash.update(`s${(value as string).length}:${value as string}`);
181
+ return;
182
+ case "number":
183
+ hash.update(`n:${Object.is(value, -0) ? "-0" : String(value)}`);
184
+ return;
185
+ case "bigint":
186
+ hash.update(`B:${value}`);
187
+ return;
188
+ case "symbol":
189
+ hash.update(`Y:${symbolId(value as symbol)}`);
190
+ return;
191
+ case "function":
192
+ hash.update(`f:${identityId(value as object)}`);
193
+ return;
194
+ }
195
+ if (seen.has(value)) {
196
+ hash.update(`R:${identityId(value as object)}`);
197
+ return;
198
+ }
199
+ seen.add(value);
200
+ if (Array.isArray(value)) {
201
+ hash.update("[");
202
+ for (let i = 0; i < value.length; i++) hashValue(hash, value[i], seen);
203
+ hash.update("]");
204
+ return;
205
+ }
206
+ if (!isPlainObject(value as object)) {
207
+ hash.update(`O:${identityId(value as object)}`);
208
+ return;
209
+ }
210
+ hash.update("{");
211
+ const entries = Object.entries(value as Record<string, unknown>);
212
+ for (const [k, v] of entries) {
213
+ hash.update(`k${k.length}:${k}`);
214
+ hashValue(hash, v, seen);
215
+ }
216
+ hash.update("}");
217
+ }
218
+
219
+ function toolsFingerprint(tools: unknown[]): string {
220
+ const hash = createHash("sha256");
221
+ const seen = new Set<unknown>();
222
+ for (const t of tools) {
223
+ hashValue(hash, t, seen);
224
+ hash.update("|");
225
+ }
226
+ return hash.digest("hex");
227
+ }
228
+
229
+ export function optimizeToolSchemas(tools: unknown[]): unknown[] {
230
+ const fp = toolsFingerprint(tools);
231
+ if (fp === cachedFingerprint && cachedTools) return cachedTools;
232
+
233
+ let changed = false;
234
+ const result = tools.map((tool) => {
235
+ if (!isRecord(tool) || !isRecord(tool.function)) return tool;
236
+ const fn = tool.function as JsonRecord;
237
+ const params = fn.parameters;
238
+ if (!isRecord(params)) return tool;
239
+
240
+ const size = jsonSize(params);
241
+ if (size <= TOOL_SCHEMA_SIZE_THRESHOLD) return tool;
242
+
243
+ const optimized = deduplicateSchema(params);
244
+ changed = true;
245
+ return { ...tool, function: { ...fn, parameters: optimized } };
246
+ });
247
+
248
+ cachedFingerprint = fp;
249
+ cachedTools = changed ? result : tools;
250
+ return cachedTools;
251
+ }
252
+
253
+ export function resetToolSchemaCache(): void {
254
+ cachedFingerprint = null;
255
+ cachedTools = null;
256
+ }
package/src/stream.ts CHANGED
@@ -17,18 +17,35 @@ import {
17
17
  streamSimpleAnthropic,
18
18
  streamSimpleOpenAICompletions,
19
19
  } from "@earendil-works/pi-ai";
20
+ import {
21
+ DEFAULT_KIMI_CODE_CONFIG,
22
+ type KimiCodeConfig,
23
+ type KimiResolvedModelConfig,
24
+ } from "./config.ts";
20
25
 
21
- import { IS_OPENAI_PROTOCOL, PROTOCOL } from "./constants.ts";
26
+ import { ENV_KIMI_CODE_PROTOCOL, getApiProtocol, getBaseUrl } from "./constants.ts";
27
+ import { getCommonHeaders } from "./device.ts";
22
28
  import { isKimiAuthErrorMessage, refreshKimiAuthToken } from "./oauth.ts";
23
29
  import {
24
30
  type Uploader,
25
31
  applyKimiPayloadMutations,
26
32
  isRecord,
27
- readEnvOverrides,
28
33
  resolveCacheRetention,
29
34
  uploadKimiFile,
30
35
  } from "./payload.ts";
31
36
 
37
+ interface KimiStreamRuntimeConfig {
38
+ model: KimiResolvedModelConfig;
39
+ protocol: KimiCodeConfig["protocol"];
40
+ uploads: KimiCodeConfig["uploads"];
41
+ }
42
+
43
+ let resolvedStore: KimiStreamRuntimeConfig | null = null;
44
+
45
+ export function setStoreResolvedKimiConfig(config: KimiStreamRuntimeConfig): void {
46
+ resolvedStore = config;
47
+ }
48
+
32
49
  // =============================================================================
33
50
  // Event stream filter: suppress Kimi "(Empty response: ...)" text blocks
34
51
  // =============================================================================
@@ -136,21 +153,47 @@ export async function* filterEmptyResponseStream(
136
153
  // Stream wrapper: orchestrates payload mutation + event filter
137
154
  // =============================================================================
138
155
 
156
+ const KIMI_API_KEY_ENV_REFERENCES = new Set(["$KIMI_API_KEY", "${KIMI_API_KEY}"]);
157
+
158
+ export function resolveKimiApiKey(apiKey: string | undefined): string {
159
+ if (apiKey !== undefined && KIMI_API_KEY_ENV_REFERENCES.has(apiKey)) {
160
+ return process.env.KIMI_API_KEY?.trim() || "";
161
+ }
162
+ return apiKey || process.env.KIMI_API_KEY || "";
163
+ }
164
+
165
+ export function mergeKimiRequestHeaders(headers?: Record<string, string>): Record<string, string> {
166
+ return { ...getCommonHeaders(), ...headers };
167
+ }
168
+
139
169
  export function streamSimpleKimi(
140
170
  model: Model<Api>,
141
171
  context: Context,
142
172
  options?: SimpleStreamOptions,
143
173
  ): AssistantMessageEventStream {
144
174
  const filtered = createAssistantMessageEventStream();
145
- const initialKey = options?.apiKey || process.env.KIMI_API_KEY || "";
175
+ const initialKey = resolveKimiApiKey(options?.apiKey);
146
176
 
147
177
  const cacheKeyOverride = (
148
178
  options as (SimpleStreamOptions & { prompt_cache_key?: unknown }) | undefined
149
179
  )?.prompt_cache_key;
150
180
  const cacheKey = (typeof cacheKeyOverride === "string" && cacheKeyOverride) || options?.sessionId;
151
181
  const cacheRetention = resolveCacheRetention(options?.cacheRetention);
152
- const envOverrides = readEnvOverrides();
153
- const thinkingKeep = process.env.KIMI_MODEL_THINKING_KEEP;
182
+ const streamConfig = resolvedStore ?? {
183
+ model: {
184
+ contextWindow: model.contextWindow,
185
+ maxTokens: model.maxTokens,
186
+ input: ["text"],
187
+ reasoning: model.reasoning,
188
+ reasoningMap: {},
189
+ thinkingKeep: null,
190
+ generation: {},
191
+ },
192
+ protocol: ENV_KIMI_CODE_PROTOCOL,
193
+ uploads: DEFAULT_KIMI_CODE_CONFIG.uploads,
194
+ };
195
+ const modelConfig = streamConfig.model;
196
+ const apiProtocol = getApiProtocol(streamConfig.protocol);
154
197
  const originalOnPayload = options?.onPayload;
155
198
  // The pi-side model id ("kimi-for-coding") is what users select via /model
156
199
  // and what gets persisted into sessions. The wire model id discovered at
@@ -158,10 +201,10 @@ export function streamSimpleKimi(
158
201
  // the model object via modifyModels and rewritten into the request payload
159
202
  // here so /v1/chat/completions and /v1/messages see the real wire id.
160
203
  const wireModelId = (model as Model<Api> & { wireModelId?: unknown }).wireModelId;
161
-
162
204
  const buildPatchedOptions = (apiKey: string): SimpleStreamOptions => {
163
205
  const upload: Uploader | undefined = apiKey
164
- ? (mimeType, data) => uploadKimiFile(apiKey, mimeType, data)
206
+ ? (mimeType, data) =>
207
+ uploadKimiFile(apiKey, mimeType, data, streamConfig.uploads.thresholdBytes)
165
208
  : undefined;
166
209
  // Only forward apiKey if we actually have one — never override the
167
210
  // caller's credential (e.g. Claude Code OAuth token) with an empty string.
@@ -169,18 +212,18 @@ export function streamSimpleKimi(
169
212
  return {
170
213
  ...options,
171
214
  ...apiKeyOverride,
215
+ headers: mergeKimiRequestHeaders(options?.headers),
172
216
  onPayload: async (payload, modelData) => {
173
217
  let nextPayload: unknown = payload;
174
218
 
175
219
  if (isRecord(nextPayload)) {
176
220
  await applyKimiPayloadMutations(nextPayload, {
177
- api: PROTOCOL,
221
+ api: apiProtocol,
178
222
  upload,
179
223
  cacheKey,
180
224
  cacheRetention,
181
225
  reasoning: options?.reasoning,
182
- thinkingKeep,
183
- envOverrides,
226
+ modelConfig,
184
227
  });
185
228
  if (
186
229
  typeof wireModelId === "string" &&
@@ -211,13 +254,23 @@ export function streamSimpleKimi(
211
254
  // register with a custom api type (kimi-openai-completions /
212
255
  // kimi-anthropic-messages) to avoid overriding the built-in
213
256
  // Anthropic/OpenAI stream handlers.
214
- const upstream = IS_OPENAI_PROTOCOL
215
- ? streamSimpleOpenAICompletions(
216
- model as Model<"openai-completions">,
217
- context,
218
- patchedOptions,
219
- )
220
- : streamSimpleAnthropic(model as Model<"anthropic-messages">, context, patchedOptions);
257
+ const runtimeModel = {
258
+ ...model,
259
+ api: apiProtocol,
260
+ baseUrl: getBaseUrl(streamConfig.protocol),
261
+ } as Model<Api>;
262
+ const upstream =
263
+ streamConfig.protocol === "openai"
264
+ ? streamSimpleOpenAICompletions(
265
+ runtimeModel as Model<"openai-completions">,
266
+ context,
267
+ patchedOptions,
268
+ )
269
+ : streamSimpleAnthropic(
270
+ runtimeModel as Model<"anthropic-messages">,
271
+ context,
272
+ patchedOptions,
273
+ );
221
274
 
222
275
  let shouldRetry = false;
223
276
  let prefixBuffer: AssistantMessageEvent[] = [];
@@ -0,0 +1,115 @@
1
+ import { AuthStorage, type AgentToolResult } from "@earendil-works/pi-coding-agent";
2
+ import { truncateToWidth } from "@earendil-works/pi-tui";
3
+
4
+ import { PROVIDER_ID, getBaseUrl } from "../constants.ts";
5
+ import { getCommonHeaders } from "../device.ts";
6
+ import { refreshKimiAuthToken } from "../oauth.ts";
7
+
8
+ export const KIMI_TOOL_TIMEOUT_MS = 180_000;
9
+
10
+ export interface KimiToolDeps {
11
+ fetch: typeof fetch;
12
+ getAccessToken: () => string | null;
13
+ refreshAccessToken: (currentToken: string) => Promise<string | null>;
14
+ }
15
+
16
+ export interface BuildKimiToolOptions {
17
+ deps?: Partial<KimiToolDeps>;
18
+ defaultCollapsed?: boolean;
19
+ }
20
+
21
+ function defaultGetAccessToken(): string | null {
22
+ const credential = AuthStorage.create().get(PROVIDER_ID);
23
+ if (!credential || credential.type !== "oauth") return null;
24
+ return credential.access;
25
+ }
26
+
27
+ export function buildKimiToolDeps(options: BuildKimiToolOptions = {}): KimiToolDeps {
28
+ return {
29
+ fetch: options.deps?.fetch ?? fetch,
30
+ getAccessToken: options.deps?.getAccessToken ?? defaultGetAccessToken,
31
+ refreshAccessToken: options.deps?.refreshAccessToken ?? refreshKimiAuthToken,
32
+ };
33
+ }
34
+
35
+ export function buildTimeoutSignal(signal: AbortSignal | undefined): {
36
+ signal: AbortSignal;
37
+ cleanup: () => void;
38
+ } {
39
+ const controller = new AbortController();
40
+ const timeout = setTimeout(() => controller.abort(), KIMI_TOOL_TIMEOUT_MS);
41
+ const abort = () => controller.abort();
42
+ if (signal?.aborted) {
43
+ controller.abort();
44
+ } else {
45
+ signal?.addEventListener("abort", abort, { once: true });
46
+ }
47
+
48
+ return {
49
+ signal: controller.signal,
50
+ cleanup: () => {
51
+ clearTimeout(timeout);
52
+ signal?.removeEventListener("abort", abort);
53
+ },
54
+ };
55
+ }
56
+
57
+ export function getKimiBaseV1(): string {
58
+ const base = getBaseUrl().replace(/\/+$/, "");
59
+ return base.endsWith("/v1") ? base : `${base}/v1`;
60
+ }
61
+
62
+ export function getKimiDatasourceUrl(): string {
63
+ const explicit = process.env.KIMI_DATASOURCE_API_URL?.trim();
64
+ if (explicit) return explicit;
65
+ return `${getKimiBaseV1()}/tools`;
66
+ }
67
+
68
+ export function buildHeaders(accessToken: string, toolCallId: string): Record<string, string> {
69
+ return {
70
+ ...getCommonHeaders(),
71
+ Authorization: `Bearer ${accessToken}`,
72
+ "Content-Type": "application/json",
73
+ "X-Msh-Tool-Call-Id": toolCallId,
74
+ };
75
+ }
76
+
77
+ export function errorResult<T>(message: string): AgentToolResult<T> {
78
+ return {
79
+ content: [{ type: "text", text: message }],
80
+ details: undefined as T,
81
+ };
82
+ }
83
+
84
+ export async function readErrorBody(response: Response): Promise<string> {
85
+ return response.text().catch(() => "");
86
+ }
87
+
88
+ export async function fetchWithAuthRetry(
89
+ deps: KimiToolDeps,
90
+ accessToken: string,
91
+ request: (token: string) => Promise<Response>,
92
+ ): Promise<Response> {
93
+ const response = await request(accessToken);
94
+ if (response.status !== 401) return response;
95
+
96
+ const refreshed = await deps.refreshAccessToken(accessToken);
97
+ if (!refreshed || refreshed === accessToken) return response;
98
+ return request(refreshed);
99
+ }
100
+
101
+ export function textComponent(text: string) {
102
+ return {
103
+ render: (width: number) => text.split("\n").map((line) => truncateToWidth(line, width, "…")),
104
+ invalidate: () => {},
105
+ };
106
+ }
107
+
108
+ export function firstText(result: AgentToolResult<unknown>): string {
109
+ const first = result.content[0];
110
+ return first?.type === "text" ? first.text : "";
111
+ }
112
+
113
+ export function shouldCollapse(defaultCollapsed: boolean, expanded: boolean | undefined): boolean {
114
+ return defaultCollapsed && expanded !== true;
115
+ }