pi-provider-kimi-code 0.6.0 → 0.6.2

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,19 +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";
22
27
  import { getCommonHeaders } from "./device.ts";
23
28
  import { isKimiAuthErrorMessage, refreshKimiAuthToken } from "./oauth.ts";
24
29
  import {
25
30
  type Uploader,
26
31
  applyKimiPayloadMutations,
27
32
  isRecord,
28
- readEnvOverrides,
29
33
  resolveCacheRetention,
30
34
  uploadKimiFile,
31
35
  } from "./payload.ts";
32
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
+
33
49
  // =============================================================================
34
50
  // Event stream filter: suppress Kimi "(Empty response: ...)" text blocks
35
51
  // =============================================================================
@@ -163,8 +179,21 @@ export function streamSimpleKimi(
163
179
  )?.prompt_cache_key;
164
180
  const cacheKey = (typeof cacheKeyOverride === "string" && cacheKeyOverride) || options?.sessionId;
165
181
  const cacheRetention = resolveCacheRetention(options?.cacheRetention);
166
- const envOverrides = readEnvOverrides();
167
- 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);
168
197
  const originalOnPayload = options?.onPayload;
169
198
  // The pi-side model id ("kimi-for-coding") is what users select via /model
170
199
  // and what gets persisted into sessions. The wire model id discovered at
@@ -172,13 +201,10 @@ export function streamSimpleKimi(
172
201
  // the model object via modifyModels and rewritten into the request payload
173
202
  // here so /v1/chat/completions and /v1/messages see the real wire id.
174
203
  const wireModelId = (model as Model<Api> & { wireModelId?: unknown }).wireModelId;
175
- const supportsThinkingType = (
176
- model as Model<Api> & { supportsThinkingType?: "only" | "no" | "both" }
177
- ).supportsThinkingType;
178
-
179
204
  const buildPatchedOptions = (apiKey: string): SimpleStreamOptions => {
180
205
  const upload: Uploader | undefined = apiKey
181
- ? (mimeType, data) => uploadKimiFile(apiKey, mimeType, data)
206
+ ? (mimeType, data) =>
207
+ uploadKimiFile(apiKey, mimeType, data, streamConfig.uploads.thresholdBytes)
182
208
  : undefined;
183
209
  // Only forward apiKey if we actually have one — never override the
184
210
  // caller's credential (e.g. Claude Code OAuth token) with an empty string.
@@ -192,14 +218,12 @@ export function streamSimpleKimi(
192
218
 
193
219
  if (isRecord(nextPayload)) {
194
220
  await applyKimiPayloadMutations(nextPayload, {
195
- api: PROTOCOL,
221
+ api: apiProtocol,
196
222
  upload,
197
223
  cacheKey,
198
224
  cacheRetention,
199
225
  reasoning: options?.reasoning,
200
- thinkingKeep,
201
- envOverrides,
202
- supportsThinkingType,
226
+ modelConfig,
203
227
  });
204
228
  if (
205
229
  typeof wireModelId === "string" &&
@@ -230,13 +254,23 @@ export function streamSimpleKimi(
230
254
  // register with a custom api type (kimi-openai-completions /
231
255
  // kimi-anthropic-messages) to avoid overriding the built-in
232
256
  // Anthropic/OpenAI stream handlers.
233
- const upstream = IS_OPENAI_PROTOCOL
234
- ? streamSimpleOpenAICompletions(
235
- model as Model<"openai-completions">,
236
- context,
237
- patchedOptions,
238
- )
239
- : 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
+ );
240
274
 
241
275
  let shouldRetry = false;
242
276
  let prefixBuffer: AssistantMessageEvent[] = [];
@@ -104,6 +104,45 @@ function extractResponseText(data: DatasourceToolResponse): string {
104
104
  return JSON.stringify(data, null, 2);
105
105
  }
106
106
 
107
+ function extractResponseFiles(data: DatasourceToolResponse): string[] {
108
+ const raw = data as Record<string, unknown>;
109
+ if (!Array.isArray(raw.files)) return [];
110
+ const names: string[] = [];
111
+ for (const file of raw.files) {
112
+ if (
113
+ typeof file === "object" &&
114
+ file !== null &&
115
+ typeof (file as Record<string, unknown>).name === "string"
116
+ ) {
117
+ names.push((file as Record<string, unknown>).name as string);
118
+ }
119
+ }
120
+ return names;
121
+ }
122
+
123
+ const REQUEST_ID_HEADERS = [
124
+ "x-request-id",
125
+ "x-trace-id",
126
+ "x-msh-request-id",
127
+ "x-msh-trace-id",
128
+ "request-id",
129
+ ];
130
+
131
+ function extractRequestId(headers: Headers): string | undefined {
132
+ for (const key of REQUEST_ID_HEADERS) {
133
+ const value = headers.get(key);
134
+ if (typeof value === "string" && value.trim()) return value.trim();
135
+ }
136
+ return undefined;
137
+ }
138
+
139
+ function buildTraceLine(toolCallId: string, requestId: string | undefined): string {
140
+ const parts: string[] = [];
141
+ if (requestId) parts.push(`request-id: ${requestId}`);
142
+ parts.push(`tool-call-id: ${toolCallId}`);
143
+ return `\n\n[kimi-datasource] ${parts.join(" · ")}`;
144
+ }
145
+
107
146
  export function buildKimiDatasourceTool(options: BuildKimiToolOptions = {}) {
108
147
  const deps = buildKimiToolDeps(options);
109
148
  const defaultCollapsed = options.defaultCollapsed ?? true;
@@ -138,7 +177,7 @@ export function buildKimiDatasourceTool(options: BuildKimiToolOptions = {}) {
138
177
  }
139
178
  : {
140
179
  method: "get_data_source_desc",
141
- params: { data_source_name: params.data_source_name },
180
+ params: { name: params.data_source_name },
142
181
  };
143
182
 
144
183
  const response = await fetchWithAuthRetry(deps, accessToken, (token) =>
@@ -150,10 +189,13 @@ export function buildKimiDatasourceTool(options: BuildKimiToolOptions = {}) {
150
189
  }),
151
190
  );
152
191
 
192
+ const requestId = extractRequestId(response.headers);
193
+ const trace = buildTraceLine(toolCallId, requestId);
194
+
153
195
  if (!response.ok) {
154
196
  const bodyText = await readErrorBody(response);
155
197
  return errorResult<string>(
156
- `kimi_datasource failed: ${response.status}${bodyText ? ` ${bodyText}` : ""}`,
198
+ `kimi_datasource failed: ${response.status}${bodyText ? ` ${bodyText}` : ""}${trace}`,
157
199
  );
158
200
  }
159
201
 
@@ -163,10 +205,16 @@ export function buildKimiDatasourceTool(options: BuildKimiToolOptions = {}) {
163
205
  typeof data.error === "string"
164
206
  ? data.error
165
207
  : JSON.stringify(data.error ?? data, null, 2);
166
- return errorResult<string>(`kimi_datasource error: ${errorText}`);
208
+ return errorResult<string>(`kimi_datasource error: ${errorText}${trace}`);
209
+ }
210
+
211
+ let text = extractResponseText(data);
212
+ const files = extractResponseFiles(data);
213
+ if (files.length > 0) {
214
+ text += `\n\nNote: the backend returned ${files.length} file(s) that cannot be written in this context: ${files.join(", ")}`;
167
215
  }
216
+ text += trace;
168
217
 
169
- const text = extractResponseText(data);
170
218
  return {
171
219
  content: [{ type: "text", text }],
172
220
  details: text,