pi-provider-kimi-code 0.1.0

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.
Files changed (3) hide show
  1. package/LICENSE +21 -0
  2. package/index.ts +306 -0
  3. package/package.json +33 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/index.ts ADDED
@@ -0,0 +1,306 @@
1
+ /**
2
+ * Kimi Code Provider Extension
3
+ *
4
+ * Provides access to Kimi models via OAuth device code flow.
5
+ * API endpoint: https://api.kimi.com/coding (Anthropic Messages compatible)
6
+ *
7
+ * Usage:
8
+ * pi -e ~/workshop/pi-provider-kimi-code
9
+ * # Then /login kimi-coding, or set KIMI_API_KEY=...
10
+ */
11
+
12
+ import { randomBytes } from "node:crypto";
13
+ import type { OAuthCredentials, OAuthLoginCallbacks } from "@mariozechner/pi-ai";
14
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
15
+
16
+ // =============================================================================
17
+ // Constants
18
+ // =============================================================================
19
+
20
+ const CLIENT_ID = "17e5f671-d194-4dfb-9706-5516cb48c098";
21
+ const OAUTH_HOST = "https://auth.kimi.com";
22
+ const KIMI_CLI_USER_AGENT = "kimi-cli/1.0.0 (external, cli)";
23
+ const KIMI_PLATFORM = "kimi_cli";
24
+
25
+ // =============================================================================
26
+ // Device identification
27
+ // =============================================================================
28
+
29
+ function createDeviceId(): string {
30
+ return randomBytes(16).toString("hex");
31
+ }
32
+
33
+ function getDeviceModel(): string {
34
+ const platform = process.platform;
35
+ const arch = process.arch;
36
+ if (platform === "darwin") {
37
+ return `macOS ${arch}`;
38
+ }
39
+ if (platform === "win32") {
40
+ return `Windows ${arch}`;
41
+ }
42
+ return `${platform} ${arch}`;
43
+ }
44
+
45
+ const DEVICE_MODEL = getDeviceModel();
46
+ let DEVICE_ID: string | null = null;
47
+
48
+ function getStableDeviceId(): string {
49
+ if (!DEVICE_ID) {
50
+ DEVICE_ID = createDeviceId();
51
+ }
52
+ return DEVICE_ID;
53
+ }
54
+
55
+ function getCommonHeaders(): Record<string, string> {
56
+ return {
57
+ "User-Agent": KIMI_CLI_USER_AGENT,
58
+ "X-Msh-Platform": KIMI_PLATFORM,
59
+ "X-Msh-Device-Model": DEVICE_MODEL,
60
+ "X-Msh-Device-Id": getStableDeviceId(),
61
+ };
62
+ }
63
+
64
+ // =============================================================================
65
+ // OAuth Implementation
66
+ // =============================================================================
67
+
68
+ interface DeviceAuthorization {
69
+ user_code: string;
70
+ device_code: string;
71
+ verification_uri: string;
72
+ verification_uri_complete: string;
73
+ expires_in: number;
74
+ interval: number;
75
+ }
76
+
77
+ interface TokenResponse {
78
+ access_token: string;
79
+ refresh_token: string;
80
+ expires_in: number;
81
+ scope: string;
82
+ token_type: string;
83
+ }
84
+
85
+ async function requestDeviceAuthorization(): Promise<DeviceAuthorization> {
86
+ const response = await fetch(`${OAUTH_HOST}/api/oauth/device_authorization`, {
87
+ method: "POST",
88
+ headers: {
89
+ "Content-Type": "application/x-www-form-urlencoded",
90
+ ...getCommonHeaders(),
91
+ },
92
+ body: new URLSearchParams({
93
+ client_id: CLIENT_ID,
94
+ }),
95
+ });
96
+
97
+ if (!response.ok) {
98
+ const text = await response.text().catch(() => "");
99
+ throw new Error(`Device authorization failed: ${response.status} ${text}`);
100
+ }
101
+
102
+ const data = (await response.json()) as {
103
+ user_code?: string;
104
+ device_code?: string;
105
+ verification_uri?: string;
106
+ verification_uri_complete?: string;
107
+ expires_in?: number;
108
+ interval?: number;
109
+ };
110
+
111
+ if (!data.user_code || !data.device_code || !data.verification_uri_complete) {
112
+ throw new Error("Invalid device authorization response");
113
+ }
114
+
115
+ return {
116
+ user_code: data.user_code,
117
+ device_code: data.device_code,
118
+ verification_uri: data.verification_uri || "",
119
+ verification_uri_complete: data.verification_uri_complete,
120
+ expires_in: data.expires_in || 1800,
121
+ interval: data.interval || 5,
122
+ };
123
+ }
124
+
125
+ async function requestDeviceToken(auth: DeviceAuthorization): Promise<TokenResponse | null> {
126
+ const response = await fetch(`${OAUTH_HOST}/api/oauth/token`, {
127
+ method: "POST",
128
+ headers: {
129
+ "Content-Type": "application/x-www-form-urlencoded",
130
+ ...getCommonHeaders(),
131
+ },
132
+ body: new URLSearchParams({
133
+ client_id: CLIENT_ID,
134
+ device_code: auth.device_code,
135
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
136
+ }),
137
+ });
138
+
139
+ if (response.status === 200) {
140
+ const data = (await response.json()) as TokenResponse;
141
+ if (data.access_token && data.refresh_token) {
142
+ return data;
143
+ }
144
+ throw new Error("Token response missing required fields");
145
+ }
146
+
147
+ if (response.status === 400) {
148
+ const data = (await response.json()) as { error?: string; error_description?: string };
149
+ if (data.error === "authorization_pending") {
150
+ return null; // Still waiting for user
151
+ }
152
+ if (data.error === "expired_token") {
153
+ throw new Error("expired_token");
154
+ }
155
+ throw new Error(`Token request failed: ${data.error_description || data.error || "unknown"}`);
156
+ }
157
+
158
+ const text = await response.text().catch(() => "");
159
+ throw new Error(`Token request failed: ${response.status} ${text}`);
160
+ }
161
+
162
+ async function refreshAccessToken(refreshToken: string): Promise<TokenResponse> {
163
+ const response = await fetch(`${OAUTH_HOST}/api/oauth/token`, {
164
+ method: "POST",
165
+ headers: {
166
+ "Content-Type": "application/x-www-form-urlencoded",
167
+ ...getCommonHeaders(),
168
+ },
169
+ body: new URLSearchParams({
170
+ client_id: CLIENT_ID,
171
+ grant_type: "refresh_token",
172
+ refresh_token: refreshToken,
173
+ }),
174
+ });
175
+
176
+ if (!response.ok) {
177
+ const text = await response.text().catch(() => "");
178
+ if (response.status === 401 || response.status === 403) {
179
+ throw new Error(`Token refresh unauthorized: ${text}`);
180
+ }
181
+ throw new Error(`Token refresh failed: ${response.status} ${text}`);
182
+ }
183
+
184
+ const data = (await response.json()) as TokenResponse;
185
+ if (!data.access_token || !data.refresh_token) {
186
+ throw new Error("Token refresh response missing required fields");
187
+ }
188
+
189
+ return data;
190
+ }
191
+
192
+ // =============================================================================
193
+ // OAuth login / refresh for extension registration
194
+ // =============================================================================
195
+
196
+ async function loginKimiCode(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
197
+ // Keep trying until we get a token (handles expired device codes)
198
+ while (true) {
199
+ const auth = await requestDeviceAuthorization();
200
+
201
+ callbacks.onAuth({
202
+ url: auth.verification_uri_complete,
203
+ instructions: `Please visit the URL to authorize. Your code: ${auth.user_code}`,
204
+ });
205
+
206
+ const interval = Math.max(auth.interval, 1) * 1000;
207
+ const expiresAt = Date.now() + auth.expires_in * 1000;
208
+
209
+ let token: TokenResponse | null = null;
210
+ let printedWaiting = false;
211
+
212
+ while (Date.now() < expiresAt) {
213
+ try {
214
+ token = await requestDeviceToken(auth);
215
+ if (token) break;
216
+ } catch (error) {
217
+ if (error instanceof Error && error.message === "expired_token") {
218
+ // Device code expired, restart the flow
219
+ if (callbacks.onProgress) {
220
+ callbacks.onProgress("Device code expired, restarting...");
221
+ }
222
+ break;
223
+ }
224
+ throw error;
225
+ }
226
+
227
+ if (!printedWaiting) {
228
+ if (callbacks.onProgress) {
229
+ callbacks.onProgress("Waiting for authorization...");
230
+ }
231
+ printedWaiting = true;
232
+ }
233
+
234
+ // Check for abort
235
+ if (callbacks.signal?.aborted) {
236
+ throw new Error("Authorization aborted");
237
+ }
238
+
239
+ await new Promise((resolve) => setTimeout(resolve, interval));
240
+ }
241
+
242
+ if (token) {
243
+ return {
244
+ access: token.access_token,
245
+ refresh: token.refresh_token,
246
+ expires: Date.now() + token.expires_in * 1000,
247
+ };
248
+ }
249
+
250
+ // If we get here without a token, the device code expired - loop will retry
251
+ }
252
+ }
253
+
254
+ async function refreshKimiCodeToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {
255
+ const token = await refreshAccessToken(credentials.refresh);
256
+ return {
257
+ access: token.access_token,
258
+ refresh: token.refresh_token,
259
+ expires: Date.now() + token.expires_in * 1000,
260
+ };
261
+ }
262
+
263
+ // =============================================================================
264
+ // Extension Entry Point
265
+ // =============================================================================
266
+
267
+ export default function (pi: ExtensionAPI) {
268
+ pi.registerProvider("kimi-coding", {
269
+ baseUrl: "https://api.kimi.com/coding",
270
+ apiKey: "KIMI_API_KEY",
271
+ api: "anthropic-messages",
272
+
273
+ headers: {
274
+ "User-Agent": KIMI_CLI_USER_AGENT,
275
+ "X-Msh-Platform": KIMI_PLATFORM,
276
+ },
277
+
278
+ models: [
279
+ {
280
+ id: "kimi-k2-thinking",
281
+ name: "Kimi K2 Thinking",
282
+ reasoning: true,
283
+ input: ["text"],
284
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
285
+ contextWindow: 262144,
286
+ maxTokens: 32768,
287
+ },
288
+ {
289
+ id: "k2p5",
290
+ name: "Kimi K2.5",
291
+ reasoning: true,
292
+ input: ["text", "image"],
293
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
294
+ contextWindow: 262144,
295
+ maxTokens: 32768,
296
+ },
297
+ ],
298
+
299
+ oauth: {
300
+ name: "Kimi Code (OAuth)",
301
+ login: loginKimiCode,
302
+ refreshToken: refreshKimiCodeToken,
303
+ getApiKey: (cred) => cred.access,
304
+ },
305
+ });
306
+ }
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "pi-provider-kimi-code",
3
+ "version": "0.1.0",
4
+ "description": "pi custom provider extension for Kimi Code models with OAuth device-code login",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/Leechael/pi-provider-kimi-code"
10
+ },
11
+ "keywords": [
12
+ "pi",
13
+ "pi-extension",
14
+ "kimi",
15
+ "kimi-code",
16
+ "llm",
17
+ "coding-agent"
18
+ ],
19
+ "files": [
20
+ "index.ts",
21
+ "package.json"
22
+ ],
23
+ "scripts": {
24
+ "clean": "echo 'nothing to clean'",
25
+ "build": "echo 'nothing to build'",
26
+ "check": "echo 'nothing to check'"
27
+ },
28
+ "pi": {
29
+ "extensions": [
30
+ "./index.ts"
31
+ ]
32
+ }
33
+ }