@coda-console/kimi 0.0.0-stage → 1.2.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,39 @@
1
+ // What the「Kimi」panel shows (docs/plugins.md「内置插件:Kimi Code」): the signed-in account and its quota, from what the
2
+ // Kimi CLI's local server says (`/oauth/userinfo`, `/oauth/usage`, the same getManagedUsage its /status uses).
3
+ const line = (value, max = 80) => typeof value === 'string' ? [...value.replace(/\s+/g, ' ').trim()].slice(0, max).join('') : '';
4
+ const instant = value => typeof value === 'string' && Number.isFinite(Date.parse(value)) ? new Date(value).toISOString() : null;
5
+
6
+ // Who is signed in, as the CLI's own page shows it: the nickname and membership level, never the phone number or email
7
+ // that come with them. Null when Kimi refuses the login (revoked though the file is still there).
8
+ export function account(data) {
9
+ if (data?.kind === 'error' && data.status === 401) return null;
10
+ if (data?.kind !== 'ok' || !data.userInfo) throw new Error('Kimi 没有说明是谁登录的');
11
+ const id = typeof data.userInfo.userId === 'string' || typeof data.userInfo.userId === 'number' ? line(String(data.userInfo.userId), 120) : '';
12
+ return { name: line(data.userInfo.nickname), plan: line(data.userInfo.userLevelName), ...(id ? { id } : {}) };
13
+ }
14
+ // The windows the plan has (5 hours, 7 days, monthly; those it has not are skipped), then the booster balance. Bars of what
15
+ // is left; a used ratio unknown draws none.
16
+ export function windows(data) {
17
+ if (data?.kind !== 'ok' || !data.quota) return null;
18
+ const usages = data.quota.usages && typeof data.quota.usages === 'object' ? data.quota.usages : {};
19
+ const ratio = value => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
20
+ const meters = [['limit5h', '5 小时'], ['limit7d', '7 天'], ['monthTotal', '月度']].flatMap(([key, label]) => {
21
+ const used = ratio(usages[key]?.usedRatio);
22
+ if (used === null) return [];
23
+ const left = Math.round(100 - Math.min(100, used * 100)), resets = instant(usages[key].resetAt);
24
+ return [{ type: 'meter', label, value: `剩余 ${left}%`, fraction: left / 100, ...(resets ? { time: resets, timeLabel: '重置' } : {}) }];
25
+ });
26
+ const wallet = data.quota.extraUsage;
27
+ const [total, left] = [wallet?.totalCents, wallet?.balanceCents].map(v => typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : null);
28
+ if (wallet && total !== null && left !== null) {
29
+ const share = total > 0 ? Math.round(Math.min(1, left / total) * 100) : 0;
30
+ meters.push({ type: 'meter', label: 'Extra Usage 余额', value: `剩余 ${share}%`, fraction: share / 100 });
31
+ }
32
+ return meters;
33
+ }
34
+ export function card(who, usage) {
35
+ const items = usage.error ? [{ type: 'error', text: `暂时无法获取额度:${usage.error}` }] : windows(usage.data) ?? [{ type: 'error', text: '暂时无法获取额度:Kimi 没有给出额度' }];
36
+ // The account, compared across machines by Coda's group view: its user ID, which the card does not show.
37
+ return { type: 'card', title: who.name || 'Kimi', ...(who.plan ? { subtitle: who.plan } : {}), ...(who.id ? { identity: `kimi:${who.id}` } : {}),
38
+ items: items.length ? items : [{ type: 'error', text: '暂时无法获取额度:Kimi 没有给出额度' }] };
39
+ }
@@ -0,0 +1,41 @@
1
+ // The plugin's setup (`contributes.setup`), which Coda runs on each machine when the user installs or updates the plugin: it
2
+ // ends well once the machine can run the agent. Without a Kimi CLI that runs, or with one older than MINIMUM (the file layout
3
+ // the relay reads, agent/observe.mjs), Kimi's own installer (install.sh) puts the latest in ~/.kimi-code/bin, where the agent
4
+ // looks first; a newer one is kept. Why the machine is not ready is said in one line on standard error.
5
+ import { spawnSync } from 'node:child_process';
6
+ import { realpathSync } from 'node:fs';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { kimiBinary } from '../agent/binary.mjs';
9
+
10
+ export const MINIMUM = '2.1.1';
11
+ // The first x.y.z a version command prints; whether one is older than another.
12
+ export const versionIn = text => /(\d+)\.(\d+)\.(\d+)/.exec(text ?? '')?.slice(1).join('.') ?? null;
13
+ export function older(version, than) {
14
+ const a = version.split('.').map(Number), b = than.split('.').map(Number), i = a.findIndex((n, k) => n !== b[k]);
15
+ return i >= 0 && a[i] < b[i];
16
+ }
17
+ const asked = binary => spawnSync(binary, ['--version'], { encoding: 'utf8', timeout: 30_000, stdio: ['ignore', 'pipe', 'pipe'] });
18
+
19
+ // What the machine needs, given the CLI found (`binary`, null for none) and how its `--version` runs (`run`):
20
+ // `install`, `upgrade` or `none`, and why.
21
+ export function needed(binary, run = asked) {
22
+ if (!binary) return { action: 'install', reason: '这台机器上没有 Kimi CLI' };
23
+ const ran = run(binary);
24
+ if (ran.status !== 0) return { action: 'install', reason: `Kimi CLI 无法运行(${binary})` };
25
+ const version = versionIn(`${ran.stdout ?? ''}\n${ran.stderr ?? ''}`);
26
+ if (!version) return { action: 'upgrade', reason: `读不出 Kimi CLI 的版本(${binary})` };
27
+ if (older(version, MINIMUM)) return { action: 'upgrade', reason: `Kimi CLI ${version} 低于所需的 ${MINIMUM}` };
28
+ return { action: 'none', version };
29
+ }
30
+
31
+ if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) {
32
+ const before = needed(kimiBinary());
33
+ if (before.action !== 'none') {
34
+ // What the installer prints goes to standard error with the rest of its story.
35
+ const installed = spawnSync('sh', [fileURLToPath(new URL('./install.sh', import.meta.url))], { stdio: ['ignore', 2, 2] });
36
+ if (installed.status !== 0) { console.error(`${before.reason},安装失败(退出码 ${installed.status ?? installed.signal})`); process.exit(1); }
37
+ }
38
+ const after = needed(kimiBinary());
39
+ if (after.action !== 'none') { console.error(after.reason); process.exit(1); }
40
+ console.log(`Kimi CLI ${after.version}`);
41
+ }
@@ -0,0 +1,72 @@
1
+ // Answers from the Kimi CLI's own local server (`kimi web`), started for them alone and closed after. The CLI renews its
2
+ // login itself on the way; its tokens are never read here. Each path's JSON `data`, in order; one Kimi does not answer
3
+ // with `code: 0` is an error of its own. The server not starting, or not in time, fails them all.
4
+ import { spawn } from 'node:child_process';
5
+ import { mkdtemp, rm } from 'node:fs/promises';
6
+ import { tmpdir } from 'node:os';
7
+ import { join } from 'node:path';
8
+
9
+ export class KimiUnavailable extends Error {}
10
+
11
+ export async function kimiWeb(paths, { binary, home, timeoutMs = 20000, closeTimeoutMs = 4000 }) {
12
+ const cwd = await mkdtemp(join(tmpdir(), 'coda-kimi-web-'));
13
+ const controller = new AbortController();
14
+ let child, closed, timer;
15
+ try {
16
+ child = spawn(binary, ['web', '--no-open', '--host', '127.0.0.1', '--port', '0'], {
17
+ cwd, env: { ...process.env, ...(home ? { KIMI_CODE_HOME: home } : {}), NO_COLOR: '1' }, stdio: ['ignore', 'pipe', 'ignore'] });
18
+ closed = new Promise(resolve => child.once('close', resolve));
19
+ let fail;
20
+ const failed = new Promise((_, reject) => { fail = message => reject(new KimiUnavailable(message)); });
21
+ child.once('error', () => fail('Kimi CLI 没能启动'));
22
+ child.once('exit', () => fail('Kimi CLI 提前退出了'));
23
+ timer = setTimeout(() => { controller.abort(); fail('Kimi CLI 没有答复'); }, timeoutMs);
24
+ const ready = new Promise(resolve => {
25
+ let buffer = '', size = 0;
26
+ child.stdout.setEncoding('utf8');
27
+ child.stdout.on('data', chunk => {
28
+ size += Buffer.byteLength(chunk);
29
+ if (size > 65536) return fail('Kimi CLI 的输出不对');
30
+ buffer += chunk;
31
+ for (let end; (end = buffer.indexOf('\n')) >= 0;) {
32
+ const line = buffer.slice(0, end).replace(/\x1b\[[0-9;]*m/g, '');
33
+ buffer = buffer.slice(end + 1);
34
+ const match = line.match(/http:\/\/127\.0\.0\.1:\d+\/?#token=([^\s]+)/);
35
+ if (!match) continue;
36
+ try {
37
+ const url = new URL(match[0]), token = new URLSearchParams(url.hash.slice(1)).get('token');
38
+ if (Number(url.port) > 0 && token) resolve({ origin: url.origin, token });
39
+ } catch { fail('Kimi CLI 的输出不对'); }
40
+ }
41
+ });
42
+ });
43
+ return await Promise.race([failed, (async () => {
44
+ const { origin, token } = await ready;
45
+ const answers = [];
46
+ for (const path of paths) {
47
+ try {
48
+ const response = await fetch(`${origin}${path}`, { headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' }, redirect: 'error', signal: controller.signal });
49
+ if (!response.ok) throw new Error(`Kimi 本地服务返回 ${response.status}`);
50
+ const text = await response.text();
51
+ if (text.length > 2 * 1024 * 1024) throw new Error('Kimi 的答复太大');
52
+ const result = JSON.parse(text);
53
+ if (result?.code !== 0) throw new Error('Kimi 没有给出结果');
54
+ answers.push({ data: result.data });
55
+ } catch (error) {
56
+ if (controller.signal.aborted) throw new KimiUnavailable('Kimi CLI 没有答复');
57
+ answers.push({ error: error.message });
58
+ }
59
+ }
60
+ return answers;
61
+ })()]);
62
+ } finally {
63
+ clearTimeout(timer); controller.abort();
64
+ if (child) {
65
+ child.kill('SIGTERM');
66
+ const killTimer = setTimeout(() => child.kill('SIGKILL'), closeTimeoutMs);
67
+ await closed;
68
+ clearTimeout(killTimer);
69
+ }
70
+ await rm(cwd, { recursive: true, force: true });
71
+ }
72
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.