@coda-console/kimi 0.0.0 → 1.2.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.
- package/agent/binary.mjs +11 -0
- package/agent/entry.mjs +20 -0
- package/agent/errors.mjs +16 -0
- package/agent/instructions.mjs +68 -0
- package/agent/lines.mjs +42 -0
- package/agent/observe.mjs +327 -0
- package/agent/relay.mjs +106 -0
- package/agent/subagents.mjs +323 -0
- package/agent/waits.mjs +153 -0
- package/icons/README.md +15 -0
- package/icons/kimi-dark.pdf +0 -0
- package/icons/kimi-dark.svg +5 -0
- package/icons/kimi-light.pdf +0 -0
- package/icons/kimi-light.svg +5 -0
- package/package.json +52 -3
- package/scripts/install.sh +6 -0
- package/scripts/login.sh +8 -0
- package/scripts/panel.mjs +37 -0
- package/scripts/quota.mjs +39 -0
- package/scripts/setup.mjs +41 -0
- package/scripts/web.mjs +72 -0
- package/README.md +0 -3
package/agent/binary.mjs
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// Which Kimi CLI runs: the one its installer puts in ~/.kimi-code/bin, else the first `kimi` on the PATH; the same the
|
|
2
|
+
// 「Kimi」panel signs in and reads the quota with (scripts/).
|
|
3
|
+
import { existsSync } from 'node:fs';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
|
|
7
|
+
export function kimiBinary(env = process.env) {
|
|
8
|
+
const installed = join(homedir(), '.kimi-code/bin/kimi');
|
|
9
|
+
if (existsSync(installed)) return installed;
|
|
10
|
+
return (env.PATH ?? '').split(':').filter(Boolean).map(dir => join(dir, 'kimi')).find(path => existsSync(path)) ?? null;
|
|
11
|
+
}
|
package/agent/entry.mjs
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// The Kimi agent as Coda starts it (the plugin's `contributes.agents`): `kimi acp` as a child in this process's group, with a relay
|
|
2
|
+
// between it and Coda that speaks Coda's protocol for it (relay.mjs, docs/agent-protocol.md). It ends as Kimi ends.
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import { readLines } from './lines.mjs';
|
|
5
|
+
import { kimiBinary } from './binary.mjs';
|
|
6
|
+
import { KimiRelay } from './relay.mjs';
|
|
7
|
+
|
|
8
|
+
const startedAt = Date.now();
|
|
9
|
+
const kimi = spawn(kimiBinary() ?? 'kimi', ['acp'], { stdio: ['pipe', 'pipe', 'ignore'] });
|
|
10
|
+
kimi.stdin.on('error', () => {});
|
|
11
|
+
const parse = line => { try { const value = JSON.parse(line); return value && typeof value === 'object' && !Array.isArray(value) ? value : null; } catch { return null; } };
|
|
12
|
+
const relay = new KimiRelay({ startedAt, say: message => process.stdout.write(`${JSON.stringify(message)}\n`),
|
|
13
|
+
tell: message => kimi.stdin.write(`${JSON.stringify(message)}\n`) });
|
|
14
|
+
readLines(process.stdin).on('line', line => { const message = parse(line); if (message) relay.fromCoda(message); }).on('close', () => kimi.stdin.end());
|
|
15
|
+
readLines(kimi.stdout).on('line', line => { const message = parse(line); if (message) relay.fromAgent(message); });
|
|
16
|
+
// What Kimi said before it ended reaches Coda before this process ends.
|
|
17
|
+
let ended = false;
|
|
18
|
+
const end = code => { if (ended) return; ended = true; relay.close(); void relay.drained().then(() => process.stdout.write('', () => process.exit(code))); };
|
|
19
|
+
kimi.on('close', code => end(code ?? 1));
|
|
20
|
+
kimi.on('error', () => end(1));
|
package/agent/errors.mjs
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
const record = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
2
|
+
|
|
3
|
+
// Kimi 2.1.1 maps this quota response to ACP auth_required. Keep the provider's reason, but report an execution failure
|
|
4
|
+
// so clients do not send the user to sign in again. A 403 or provider.auth_error alone does not establish quota exhaustion.
|
|
5
|
+
export function classifyKimiError(message) {
|
|
6
|
+
const error = message.error;
|
|
7
|
+
if (error?.code !== -32000 || typeof error.message !== 'string') return message;
|
|
8
|
+
const reason = error.message.replace(/^Authentication required:\s*/, '');
|
|
9
|
+
if (!/^403 You've reached your 5-hour usage limit\.(?:\s|$)/.test(reason)) return message;
|
|
10
|
+
const data = record(error.data) ? error.data : error.data == null ? {} : { details: error.data };
|
|
11
|
+
const meta = record(data._meta) ? data._meta : {};
|
|
12
|
+
const coda = record(meta.coda) ? meta.coda : {};
|
|
13
|
+
return { ...message, error: { ...error, code: -32603,
|
|
14
|
+
message: reason,
|
|
15
|
+
data: { ...data, _meta: { ...meta, coda: { ...coda, failure: { kind: 'quota_exhausted' } } } } } };
|
|
16
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// Coda's session instructions (docs/agent-protocol.md「会话指令」) for an agent whose own ACP does not take `systemPrompt`: the
|
|
2
|
+
// entry declares that it does, keeps the parameter from the agent, and puts the text in front of the first prompt of a
|
|
3
|
+
// session the agent opened new, as a part of its own; a session it loaded has had them. A slash command is the agent's to
|
|
4
|
+
// read as one: the instructions wait for the next prompt. Kept the same in every plugin that relays a CLI's ACP.
|
|
5
|
+
const record = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
6
|
+
|
|
7
|
+
// ACP's `systemPrompt`: its text, '' when there is none; throws on anything but text appended to the agent's own.
|
|
8
|
+
export function sessionInstructions(systemPrompt) {
|
|
9
|
+
if (systemPrompt === undefined || systemPrompt === null) return '';
|
|
10
|
+
if (systemPrompt.mode !== 'append') throw new Error('会话指令只支持 append 模式');
|
|
11
|
+
const { content } = systemPrompt;
|
|
12
|
+
if (!Array.isArray(content) || content.some(block => block?.type !== 'text' || typeof block.text !== 'string')) throw new Error('会话指令只接受文本块');
|
|
13
|
+
return content.map(block => block.text).join('\n\n');
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// The part in front of the user's input: delimited, and said to be the client's, not the user's.
|
|
17
|
+
const OPENING = '<coda-session-instructions>';
|
|
18
|
+
export const instructionsBlock = text => ({ type: 'text', text: `${OPENING}\n`
|
|
19
|
+
+ 'Instructions from Coda, the client this session runs in, for the whole session. They are not part of the user\'s message.\n\n'
|
|
20
|
+
+ `${text}\n</coda-session-instructions>\n` });
|
|
21
|
+
|
|
22
|
+
export class SessionInstructions {
|
|
23
|
+
// Coda's requests whose answers are read here, by id; the instructions of a session yet to have its first prompt.
|
|
24
|
+
constructor() { this.asked = new Map(); this.waiting = new Map(); }
|
|
25
|
+
// What Coda says: `agent`, what the agent is told, or `coda`, Coda's answer given here instead.
|
|
26
|
+
fromCoda(message) {
|
|
27
|
+
const { id, method, params } = message;
|
|
28
|
+
if (!record(params)) return { agent: message };
|
|
29
|
+
if (method === 'initialize' && id !== undefined) this.asked.set(id, { initialize: true });
|
|
30
|
+
if (method === 'session/new' || method === 'session/load') {
|
|
31
|
+
let text;
|
|
32
|
+
try { text = sessionInstructions(params.systemPrompt); }
|
|
33
|
+
catch (error) { return { coda: { jsonrpc: '2.0', id, error: { code: -32602, message: error.message } } }; }
|
|
34
|
+
const { systemPrompt, ...rest } = params;
|
|
35
|
+
if (method === 'session/new' && text && id !== undefined) this.asked.set(id, { text });
|
|
36
|
+
return { agent: { ...message, params: rest } };
|
|
37
|
+
}
|
|
38
|
+
if (method === 'session/prompt' && Array.isArray(params.prompt) && this.waiting.has(params.sessionId)) {
|
|
39
|
+
const first = params.prompt.find(block => block?.type === 'text');
|
|
40
|
+
if (typeof first?.text === 'string' && first.text.trimStart().startsWith('/')) return { agent: message };
|
|
41
|
+
const text = this.waiting.get(params.sessionId);
|
|
42
|
+
this.waiting.delete(params.sessionId);
|
|
43
|
+
return { agent: { ...message, params: { ...params, prompt: [instructionsBlock(text), ...params.prompt] } } };
|
|
44
|
+
}
|
|
45
|
+
return { agent: message };
|
|
46
|
+
}
|
|
47
|
+
// What the agent says, as said to Coda. A title the agent took from the first prompt's text begins with the instructions,
|
|
48
|
+
// not with what the user asked: it is left out, and the session keeps the title Coda gives it.
|
|
49
|
+
fromAgent(message) {
|
|
50
|
+
const update = message?.method === 'session/update' && record(message.params) ? message.params.update : null;
|
|
51
|
+
if (record(update) && update.sessionUpdate === 'session_info_update' && typeof update.title === 'string' && update.title.trimStart().startsWith(OPENING)) {
|
|
52
|
+
const { title, ...rest } = update;
|
|
53
|
+
return { ...message, params: { ...message.params, update: rest } };
|
|
54
|
+
}
|
|
55
|
+
if (!record(message) || !('id' in message) || 'method' in message) return message;
|
|
56
|
+
const asked = this.asked.get(message.id);
|
|
57
|
+
if (!asked) return message;
|
|
58
|
+
this.asked.delete(message.id);
|
|
59
|
+
if (!record(message.result)) return message;
|
|
60
|
+
if (asked.text) {
|
|
61
|
+
if (typeof message.result.sessionId === 'string') this.waiting.set(message.result.sessionId, asked.text);
|
|
62
|
+
return message;
|
|
63
|
+
}
|
|
64
|
+
const capabilities = record(message.result.agentCapabilities) ? message.result.agentCapabilities : {};
|
|
65
|
+
const sessions = record(capabilities.sessionCapabilities) ? capabilities.sessionCapabilities : {};
|
|
66
|
+
return { ...message, result: { ...message.result, agentCapabilities: { ...capabilities, sessionCapabilities: { ...sessions, systemPrompt: {} } } } };
|
|
67
|
+
}
|
|
68
|
+
}
|
package/agent/lines.mjs
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// A copy of Coda's backend/src/adapters/json-lines.mjs: an agent plugin's entry imports nothing of Coda's (docs/plugins.md「Agent」).
|
|
2
|
+
// Reads newline-delimited JSON from a stream. Only \n ends a message: readline also
|
|
3
|
+
// ends lines at a lone \r and at U+2028/U+2029, which JSON leaves unescaped inside
|
|
4
|
+
// strings, so a tool output carrying them would split one message into pieces.
|
|
5
|
+
import { EventEmitter } from 'node:events';
|
|
6
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
7
|
+
|
|
8
|
+
// Emits 'line' for each message (a trailing \r is dropped) and 'close' once, when the
|
|
9
|
+
// input ends or closes or close() is called. Only a clean end delivers an unterminated
|
|
10
|
+
// last line; a destroyed input drops it. Input errors stay with the input's own handlers.
|
|
11
|
+
export function readLines(input) {
|
|
12
|
+
const reader = new EventEmitter(), decoder = new StringDecoder('utf8');
|
|
13
|
+
// The unfinished message stays in pieces until its \n arrives: appending each chunk to one
|
|
14
|
+
// string and searching it would copy a large message over and over.
|
|
15
|
+
let pending = [], closed = false;
|
|
16
|
+
const emit = line => reader.emit('line', line.endsWith('\r') ? line.slice(0, -1) : line);
|
|
17
|
+
const take = text => {
|
|
18
|
+
let start = 0, end;
|
|
19
|
+
while (!closed && (end = text.indexOf('\n', start)) >= 0) {
|
|
20
|
+
pending.push(text.slice(start, end)); start = end + 1;
|
|
21
|
+
const line = pending.join(''); pending = [];
|
|
22
|
+
emit(line);
|
|
23
|
+
}
|
|
24
|
+
if (!closed && start < text.length) pending.push(text.slice(start));
|
|
25
|
+
};
|
|
26
|
+
const data = chunk => take(typeof chunk === 'string' ? chunk : decoder.write(chunk));
|
|
27
|
+
const finish = () => {
|
|
28
|
+
if (closed) return;
|
|
29
|
+
take(decoder.end());
|
|
30
|
+
if (pending.length && !closed) { const rest = pending.join(''); pending = []; emit(rest); }
|
|
31
|
+
reader.close();
|
|
32
|
+
};
|
|
33
|
+
reader.close = () => {
|
|
34
|
+
if (closed) return;
|
|
35
|
+
closed = true;
|
|
36
|
+
input.off('data', data); input.off('end', finish); input.off('close', reader.close);
|
|
37
|
+
input.pause?.();
|
|
38
|
+
reader.emit('close');
|
|
39
|
+
};
|
|
40
|
+
input.on('data', data); input.on('end', finish); input.on('close', reader.close);
|
|
41
|
+
return reader;
|
|
42
|
+
}
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
import { constants, watch } from 'node:fs';
|
|
2
|
+
import { open, readdir, realpath } from 'node:fs/promises';
|
|
3
|
+
import { isAbsolute, join, relative, sep } from 'node:path';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { KimiSubagentBridge } from './subagents.mjs';
|
|
6
|
+
|
|
7
|
+
const object = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
8
|
+
const identifier = value => typeof value === 'string' && /^[\w-]+$/.test(value);
|
|
9
|
+
const unread = () => null;
|
|
10
|
+
|
|
11
|
+
// What Kimi keeps of a session in its own files (KIMI_CODE_HOME): its tasks, its main agent's turns, the crons it scheduled
|
|
12
|
+
// (`cron.add` / `cron.delete` / `cron.cursor` on the main wire) and its subagents' own conversations, which its ACP does
|
|
13
|
+
// not tell. These files are an implementation detail, not an ACP contract. Accept only the layout inspected in 2.1.1; a
|
|
14
|
+
// new version simply loses this observation.
|
|
15
|
+
export const SUPPORTED = '2.1.1';
|
|
16
|
+
// Bounded ordinary-file reads also prevent a broken index/FIFO from holding up
|
|
17
|
+
// the entry. No paths, prompts, task output or credentials leave this module.
|
|
18
|
+
async function read(path, limit, signal) {
|
|
19
|
+
signal.throwIfAborted();
|
|
20
|
+
const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
21
|
+
try {
|
|
22
|
+
const stat = await file.stat();
|
|
23
|
+
if (!stat.isFile() || stat.size > limit) throw new Error('Unsupported file');
|
|
24
|
+
const buffer = Buffer.alloc(stat.size + 1);
|
|
25
|
+
let length = 0;
|
|
26
|
+
while (length < buffer.length) {
|
|
27
|
+
signal.throwIfAborted();
|
|
28
|
+
const { bytesRead } = await file.read(buffer, length, buffer.length - length, length);
|
|
29
|
+
if (!bytesRead) break;
|
|
30
|
+
length += bytesRead;
|
|
31
|
+
}
|
|
32
|
+
if (length > stat.size) throw new Error('File changed during observation');
|
|
33
|
+
return buffer.toString('utf8', 0, length);
|
|
34
|
+
} finally { await file.close(); }
|
|
35
|
+
}
|
|
36
|
+
async function contained(root, path) {
|
|
37
|
+
const actual = await realpath(path), rel = relative(root, actual);
|
|
38
|
+
if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) throw new Error('Foreign path');
|
|
39
|
+
return actual;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// The session `sessionId` that Kimi keeps for `cwd`. `startedAt`: when this agent process started; a subagent's run from
|
|
43
|
+
// before it is another process's, whose conversation is not told again.
|
|
44
|
+
export function kimiSession({ sessionId, cwd, env = {}, version, startedAt = 0 }) {
|
|
45
|
+
const home = env.KIMI_CODE_HOME || join(env.HOME || homedir(), '.kimi-code');
|
|
46
|
+
let directory;
|
|
47
|
+
let subagents;
|
|
48
|
+
return {
|
|
49
|
+
// Calls `changed` whenever the session's files may have changed, and once its watches are in place; `lost` if one
|
|
50
|
+
// breaks. Its directory is watched whole; its main agent's wire is a file appended to, whose watch (that of a file) is
|
|
51
|
+
// in place once the event loop has polled after it was asked for, so the main turn's end is heard even before the
|
|
52
|
+
// directory's watch has begun. Nothing is watched before an observation found the directory.
|
|
53
|
+
watch(changed, lost) {
|
|
54
|
+
if (!directory) return null;
|
|
55
|
+
const watchers = [];
|
|
56
|
+
let closed = false;
|
|
57
|
+
const close = () => { closed = true; for (const watcher of watchers) watcher.close(); };
|
|
58
|
+
const follow = (path, options) => {
|
|
59
|
+
const watcher = watch(path, options, () => { if (!closed) changed(); });
|
|
60
|
+
watcher.on('error', () => { if (closed) return; close(); lost(); });
|
|
61
|
+
watcher.unref();
|
|
62
|
+
watchers.push(watcher);
|
|
63
|
+
};
|
|
64
|
+
try { follow(directory, { recursive: true }); } catch { close(); return null; }
|
|
65
|
+
try { follow(join(directory, 'agents/main/wire.jsonl'), {}); } catch {}
|
|
66
|
+
setImmediate(() => setImmediate(() => { if (!closed) changed(); }));
|
|
67
|
+
return { close };
|
|
68
|
+
},
|
|
69
|
+
// What the files say now: every task record of its agents and the subagent runs its main agent's wire tells of (`tasks`),
|
|
70
|
+
// when its main agent last ended a turn (`turnEndedAt`, 0 for never), every cron the wire still tells of (`crons`, each
|
|
71
|
+
// `waiting`, `handling`, `done` or `cancelled`, with the created time and fire cursor its next fire is counted from) and
|
|
72
|
+
// the schedule config that count uses (`schedule`), and what its subagents said since the last look, to `emit` as their
|
|
73
|
+
// own sessions' updates. A cron's prompt does not leave here, only a short title cut from its first line. Null when the
|
|
74
|
+
// files are not this session's, or not laid out as understood; a read that fails (a file being written) throws. A cron
|
|
75
|
+
// event that is not the shape understood is skipped, so one of them cannot hide the tasks.
|
|
76
|
+
async observe({ signal, emit = () => {} }) {
|
|
77
|
+
if (version !== SUPPORTED) return unread('unsupported_version');
|
|
78
|
+
if (!identifier(sessionId) || !isAbsolute(home ?? '') || !isAbsolute(cwd ?? '')) return unread('unbound_session');
|
|
79
|
+
const root = await realpath(join(home, 'sessions')), workspace = await realpath(cwd);
|
|
80
|
+
if (!directory) {
|
|
81
|
+
const index = await read(join(home, 'session_index.jsonl'), 16 * 1024 * 1024, signal);
|
|
82
|
+
let match;
|
|
83
|
+
for (const line of index.split('\n')) {
|
|
84
|
+
if (!line.trim()) continue;
|
|
85
|
+
let entry;
|
|
86
|
+
try { entry = JSON.parse(line); } catch { continue; }
|
|
87
|
+
if (entry?.sessionId === sessionId) match = entry;
|
|
88
|
+
}
|
|
89
|
+
if (!match || typeof match.sessionDir !== 'string' || typeof match.workDir !== 'string' ||
|
|
90
|
+
await realpath(match.workDir) !== workspace) return unread('unbound_session');
|
|
91
|
+
directory = await contained(root, match.sessionDir);
|
|
92
|
+
}
|
|
93
|
+
const session = await contained(root, directory);
|
|
94
|
+
const state = JSON.parse(await read(join(session, 'state.json'), 1024 * 1024, signal));
|
|
95
|
+
if (state.version !== 2 || state.id !== sessionId || typeof state.cwd !== 'string' ||
|
|
96
|
+
await realpath(state.cwd) !== workspace || !object(state.agents) || !object(state.agents.main)) return unread('unsupported_layout');
|
|
97
|
+
const agents = Object.keys(state.agents);
|
|
98
|
+
if (agents.length > 256 || !agents.every(identifier)) return unread('unsupported_layout');
|
|
99
|
+
|
|
100
|
+
const records = [];
|
|
101
|
+
for (const id of agents) {
|
|
102
|
+
const agent = await contained(session, join(session, 'agents', id));
|
|
103
|
+
let tasks;
|
|
104
|
+
try { tasks = await contained(agent, join(agent, 'tasks')); }
|
|
105
|
+
catch (error) { if (error.code === 'ENOENT') continue; throw error; }
|
|
106
|
+
const files = await readdir(tasks, { withFileTypes: true });
|
|
107
|
+
if (files.length > 4096) return unread('unsupported_layout');
|
|
108
|
+
for (const file of files) {
|
|
109
|
+
signal.throwIfAborted();
|
|
110
|
+
if (!file.name.endsWith('.json')) continue;
|
|
111
|
+
if (!file.isFile()) return unread('unsupported_layout');
|
|
112
|
+
const task = JSON.parse(await read(join(tasks, file.name), 1024 * 1024, signal));
|
|
113
|
+
if (!object(task) || !identifier(task.taskId) || file.name !== `${task.taskId}.json` ||
|
|
114
|
+
!['agent', 'process'].includes(task.kind) || typeof task.status !== 'string') return unread('unsupported_layout');
|
|
115
|
+
if (task.status !== 'running' && (!['completed', 'failed', 'killed', 'lost', 'timed_out'].includes(task.status) ||
|
|
116
|
+
!Number.isSafeInteger(task.endedAt) || task.endedAt <= 0)) return unread('unsupported_layout');
|
|
117
|
+
records.push(task);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
subagents ??= new KimiSubagentBridge({ session, root, readBounded: read, contained, startedAt });
|
|
122
|
+
let tasks = records;
|
|
123
|
+
try { tasks = await subagents.sync({ agents, state, tasks: records, signal, emit }); } catch {}
|
|
124
|
+
// A task's end can enqueue a notification that starts another main turn: what it ended with is handled once a turn of
|
|
125
|
+
// the main agent ended after it.
|
|
126
|
+
const wire = await read(join(session, 'agents/main/wire.jsonl'), 32 * 1024 * 1024, signal);
|
|
127
|
+
const lines = wire.trimEnd().split('\n');
|
|
128
|
+
const metadata = JSON.parse(lines.shift());
|
|
129
|
+
if (metadata.type !== 'metadata' || metadata.protocol_version !== '1.5') return unread('unsupported_layout');
|
|
130
|
+
// `cron.delete` is written when a fire is delivered and when CronDelete removes a job during a turn that is not that
|
|
131
|
+
// fire. Which one it was is kept with the job: the open `cron_job` turn, that turn once it ended, or the delete that
|
|
132
|
+
// landed inside some other turn already going. A delete before any such turn is not a cancel: the fire's turn.prompt
|
|
133
|
+
// is written after the delete. `cron.cursor` is the ideal minute that fire advanced to.
|
|
134
|
+
const crons = new Map();
|
|
135
|
+
const span = { turn: null };
|
|
136
|
+
let turnId = null, turnEndedAt = 0;
|
|
137
|
+
for (const line of lines) {
|
|
138
|
+
signal.throwIfAborted();
|
|
139
|
+
const event = JSON.parse(line);
|
|
140
|
+
if (event.type === 'cron.add') noteCron(crons, event);
|
|
141
|
+
else if (event.type === 'cron.delete') dropCron(crons, event, span.turn);
|
|
142
|
+
else if (event.type === 'cron.cursor') noteCursor(crons, event);
|
|
143
|
+
else if (event.type === 'agent.turn.started' || (event.type === 'turn.prompt' && event.agentId === 'main')) {
|
|
144
|
+
if (!span.turn || span.turn.turnId !== event.turnId) span.turn = { turnId: event.turnId, time: event.time, prompted: false, jobId: undefined };
|
|
145
|
+
turnId = event.turnId;
|
|
146
|
+
if (event.type === 'turn.prompt') noteFire(crons, event, span.turn);
|
|
147
|
+
} else if (event.type === 'turn.ended') {
|
|
148
|
+
if (event.agentId !== 'main' || event.turnId !== turnId || !['completed', 'cancelled', 'failed', 'blocked'].includes(event.reason) ||
|
|
149
|
+
!Number.isSafeInteger(event.time) || event.time <= 0) return unread('unsupported_layout');
|
|
150
|
+
turnEndedAt = event.time;
|
|
151
|
+
for (const cron of crons.values()) if (cron.fireTurn === event.turnId) cron.fireEnded = true;
|
|
152
|
+
span.turn = null;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return { tasks, turnEndedAt, schedule: await cronClock(home, env, signal),
|
|
156
|
+
crons: [...crons.values()].map(publishCron) };
|
|
157
|
+
} };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// A cron.add that is not the shape from 2.1.1 is ignored. A later add of the same id replaces it.
|
|
161
|
+
function noteCron(crons, event) {
|
|
162
|
+
const task = event.task;
|
|
163
|
+
if (!object(task) || !identifier(task.id) || typeof task.cron !== 'string' || !task.cron.trim() || task.cron.length > 200 ||
|
|
164
|
+
typeof task.recurring !== 'boolean' || !Number.isSafeInteger(task.createdAt) || task.createdAt <= 0) return;
|
|
165
|
+
const lastFiredAt = Number.isFinite(task.lastFiredAt) && task.lastFiredAt > 0 ? task.lastFiredAt : undefined;
|
|
166
|
+
crons.set(task.id, { id: task.id, schedule: task.cron.trim(), recurring: task.recurring, title: cronTitle(task.prompt),
|
|
167
|
+
createdAt: task.createdAt, lastFiredAt, deletedAt: undefined, fireTurn: undefined, fireEnded: false, explicitCancel: false });
|
|
168
|
+
}
|
|
169
|
+
function dropCron(crons, event, turn) {
|
|
170
|
+
if (!Array.isArray(event.ids) || !Number.isSafeInteger(event.time) || event.time <= 0) return;
|
|
171
|
+
for (const id of event.ids) {
|
|
172
|
+
const cron = crons.get(id);
|
|
173
|
+
if (!cron) continue;
|
|
174
|
+
cron.deletedAt = event.time;
|
|
175
|
+
// CronDelete runs inside a turn that has already started and is not this job's fire. The fire's own delete is written
|
|
176
|
+
// while no such turn is open, before `turn.prompt`.
|
|
177
|
+
if (cron.fireTurn === undefined && turn?.prompted && turn.jobId !== id && Number.isSafeInteger(turn.time) && turn.time <= event.time) cron.explicitCancel = true;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
function noteCursor(crons, event) {
|
|
181
|
+
if (!identifier(event.id) || !Number.isFinite(event.lastFiredAt) || event.lastFiredAt <= 0) return;
|
|
182
|
+
const cron = crons.get(event.id);
|
|
183
|
+
if (cron) cron.lastFiredAt = event.lastFiredAt;
|
|
184
|
+
}
|
|
185
|
+
function noteFire(crons, event, turn) {
|
|
186
|
+
if (Number.isSafeInteger(event.time)) turn.time = event.time;
|
|
187
|
+
turn.prompted = true;
|
|
188
|
+
const origin = event.origin;
|
|
189
|
+
if (!object(origin) || origin.kind !== 'cron_job' || !identifier(origin.jobId)) return;
|
|
190
|
+
const cron = crons.get(origin.jobId);
|
|
191
|
+
if (!cron) return;
|
|
192
|
+
cron.fireTurn = event.turnId;
|
|
193
|
+
cron.fireEnded = false;
|
|
194
|
+
cron.explicitCancel = false;
|
|
195
|
+
turn.jobId = origin.jobId;
|
|
196
|
+
}
|
|
197
|
+
// The first clause of the prompt, without the command that follows it. Empty when there is nothing to show.
|
|
198
|
+
function cronTitle(prompt) {
|
|
199
|
+
if (typeof prompt !== 'string') return '';
|
|
200
|
+
return prompt.split(/\r?\n/, 1)[0].trim().split(/[`((::]/, 1)[0].trim().slice(0, 100);
|
|
201
|
+
}
|
|
202
|
+
function publishCron(cron) {
|
|
203
|
+
const firing = cron.fireTurn !== undefined && !cron.fireEnded;
|
|
204
|
+
// A one-shot's fire, and a recurring one removed as it fired, finished with that turn. Said even when the turn was never
|
|
205
|
+
// seen open, so a look that finds only the end does not report it cancelled.
|
|
206
|
+
const finished = cron.fireEnded && (!cron.recurring || cron.deletedAt !== undefined);
|
|
207
|
+
const phase = firing ? 'handling' : (finished ? 'done' : (cron.explicitCancel ? 'cancelled' : 'waiting'));
|
|
208
|
+
return { id: cron.id, schedule: cron.schedule, recurring: cron.recurring, title: cron.title, phase, createdAt: cron.createdAt,
|
|
209
|
+
...(cron.lastFiredAt !== undefined ? { lastFiredAt: cron.lastFiredAt } : {}) };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Kimi's `[cron]` table (config.toml, keys snake_cased) and the cron env vars, as 2.1.1 reads them. `noJitter` only when
|
|
213
|
+
// the env is exactly `1` or the file says true. A clock `file:` of a relative path, or a table that cannot be read, is
|
|
214
|
+
// not reliable: the caller then leaves `at` off. A missing file is the default, which is reliable. `disabled` and
|
|
215
|
+
// `manualTick` do not fire on the schedule.
|
|
216
|
+
async function cronClock(home, env, signal) {
|
|
217
|
+
let text = '';
|
|
218
|
+
try { text = await read(join(home, 'config.toml'), 1024 * 1024, signal); }
|
|
219
|
+
catch (error) {
|
|
220
|
+
if (error.name === 'AbortError') throw error;
|
|
221
|
+
if (error.code !== 'ENOENT') return { reliable: false };
|
|
222
|
+
}
|
|
223
|
+
const table = parseCronTable(text);
|
|
224
|
+
if (!table.reliable) return { reliable: false };
|
|
225
|
+
const file = table.values;
|
|
226
|
+
const noJitter = env.KIMI_CRON_NO_JITTER === '1' ? true : file.noJitter === true;
|
|
227
|
+
const disabled = env.KIMI_DISABLE_CRON === '1' ? true : file.disabled === true;
|
|
228
|
+
const manualTick = env.KIMI_CRON_MANUAL_TICK === '1' ? true : file.manualTick === true;
|
|
229
|
+
if (disabled || manualTick) return { reliable: false };
|
|
230
|
+
const clock = typeof env.KIMI_CRON_CLOCK === 'string' ? env.KIMI_CRON_CLOCK : typeof file.clock === 'string' ? file.clock : undefined;
|
|
231
|
+
const asOf = await clockNow(clock, signal);
|
|
232
|
+
if (asOf === null) return { reliable: false };
|
|
233
|
+
return { reliable: true, noJitter, ...(asOf === undefined ? {} : { asOf }) };
|
|
234
|
+
}
|
|
235
|
+
// The `[cron]` table only. Other tables are skipped, so a config without one keeps the default. A value of a key the
|
|
236
|
+
// schedule depends on that is not a scalar makes the table unusable.
|
|
237
|
+
function parseCronTable(text) {
|
|
238
|
+
let inCron = false, reliable = true;
|
|
239
|
+
const values = {};
|
|
240
|
+
for (let line of text.split('\n')) {
|
|
241
|
+
if (line.endsWith('\r')) line = line.slice(0, -1);
|
|
242
|
+
if (line.trim().startsWith('[')) {
|
|
243
|
+
const header = tomlHeader(line);
|
|
244
|
+
if (!header) { if (inCron) reliable = false; continue; }
|
|
245
|
+
inCron = !header.array && header.name === 'cron';
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
if (!inCron || /^\s*(?:#.*)?$/.test(line)) continue;
|
|
249
|
+
const keyValue = /^\s*([A-Za-z0-9_-]+)\s*=\s*(.*)$/.exec(line);
|
|
250
|
+
if (!keyValue) { reliable = false; continue; }
|
|
251
|
+
const key = keyValue[1].replace(/_([a-z])/g, (_, ch) => ch.toUpperCase());
|
|
252
|
+
const value = parseTomlScalar(stripTomlComment(keyValue[2]).trim());
|
|
253
|
+
if (value === undefined) { if (key === 'noJitter' || key === 'clock' || key === 'disabled' || key === 'manualTick') reliable = false; continue; }
|
|
254
|
+
values[key] = value;
|
|
255
|
+
}
|
|
256
|
+
return { reliable, values };
|
|
257
|
+
}
|
|
258
|
+
function tomlHeader(line) {
|
|
259
|
+
const body = stripTomlComment(line).trim();
|
|
260
|
+
const array = /^\[\[(.+)\]\]$/.exec(body), table = array ? null : /^\[(.+)\]$/.exec(body);
|
|
261
|
+
if (!array && !table) return null;
|
|
262
|
+
return { array: Boolean(array), name: (array ?? table)[1].trim() };
|
|
263
|
+
}
|
|
264
|
+
function stripTomlComment(value) {
|
|
265
|
+
let quote = '';
|
|
266
|
+
for (let i = 0; i < value.length; i++) {
|
|
267
|
+
const ch = value[i];
|
|
268
|
+
if (quote) {
|
|
269
|
+
if (quote === '"' && ch === '\\') { i += 1; continue; }
|
|
270
|
+
if (ch === quote) quote = '';
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
if (ch === '"' || ch === "'") { quote = ch; continue; }
|
|
274
|
+
if (ch === '#') return value.slice(0, i);
|
|
275
|
+
}
|
|
276
|
+
return value;
|
|
277
|
+
}
|
|
278
|
+
function parseTomlScalar(raw) {
|
|
279
|
+
if (raw === 'true') return true;
|
|
280
|
+
if (raw === 'false') return false;
|
|
281
|
+
if (raw.startsWith("'")) { const literal = /^'([^'\n]*)'$/.exec(raw); return literal ? literal[1] : undefined; }
|
|
282
|
+
if (raw.startsWith('"')) return parseBasicString(raw);
|
|
283
|
+
if (/^[+-]?(?:\d+\.\d*|\d*\.\d+|\d+)(?:[eE][+-]?\d+)?$/.test(raw)) { const n = Number(raw); return Number.isFinite(n) ? n : undefined; }
|
|
284
|
+
return undefined;
|
|
285
|
+
}
|
|
286
|
+
function parseBasicString(raw) {
|
|
287
|
+
if (!raw.endsWith('"') || raw.length < 2) return undefined;
|
|
288
|
+
let out = '';
|
|
289
|
+
for (let i = 1; i < raw.length - 1; i++) {
|
|
290
|
+
if (raw[i] === '"') return undefined;
|
|
291
|
+
if (raw[i] !== '\\') { out += raw[i]; continue; }
|
|
292
|
+
const esc = raw[++i];
|
|
293
|
+
const map = { b: '\b', t: '\t', n: '\n', f: '\f', r: '\r', '"': '"', '\\': '\\' };
|
|
294
|
+
if (Object.hasOwn(map, esc)) { out += map[esc]; continue; }
|
|
295
|
+
if (esc === 'u') {
|
|
296
|
+
const hex = raw.slice(i + 1, i + 5);
|
|
297
|
+
if (!/^[0-9a-fA-F]{4}$/.test(hex)) return undefined;
|
|
298
|
+
out += String.fromCharCode(Number.parseInt(hex, 16));
|
|
299
|
+
i += 4;
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
return undefined;
|
|
303
|
+
}
|
|
304
|
+
return out;
|
|
305
|
+
}
|
|
306
|
+
// 2.1.1: empty, `system` or an unknown scheme is the system clock (`undefined` here, so the caller uses its own now).
|
|
307
|
+
// `file:` of an absolute path is that file's first line, and Date.now() when it cannot be read — except a relative
|
|
308
|
+
// path, which depends on Kimi's cwd and is `null` (not reliable).
|
|
309
|
+
async function clockNow(spec, signal) {
|
|
310
|
+
if (spec === undefined || spec === '' || spec === 'system' || !spec.startsWith('file:')) return undefined;
|
|
311
|
+
const path = spec.slice('file:'.length);
|
|
312
|
+
if (path === '') return undefined;
|
|
313
|
+
if (!isAbsolute(path)) return null;
|
|
314
|
+
signal.throwIfAborted();
|
|
315
|
+
let file;
|
|
316
|
+
try { file = await open(path, constants.O_RDONLY); }
|
|
317
|
+
catch { return undefined; }
|
|
318
|
+
try {
|
|
319
|
+
const buffer = Buffer.alloc(64);
|
|
320
|
+
const { bytesRead } = await file.read(buffer, 0, 64, 0);
|
|
321
|
+
const line = buffer.toString('utf8', 0, bytesRead).split('\n', 1)[0]?.trim() ?? '';
|
|
322
|
+
if (!line) return undefined;
|
|
323
|
+
const parsed = Number(line);
|
|
324
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
325
|
+
} catch { return undefined; }
|
|
326
|
+
finally { await file.close(); }
|
|
327
|
+
}
|
package/agent/relay.mjs
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// Between Coda and `kimi acp`, a message at a time: everything passes as said, in order, and what Kimi keeps going beside a
|
|
2
|
+
// turn, read from its files (observe.mjs), is told to Coda as waits (waits.mjs). Its files are read once the session is
|
|
3
|
+
// known, again whenever they change, at most once every `every`, and before Kimi's answer to a prompt is passed on, so
|
|
4
|
+
// that what that turn took up is not left as if Kimi still had it to handle. A message Kimi sends outside a prompt while
|
|
5
|
+
// nothing is handled may begin a turn of its own: it waits for a look too, so that what Kimi handles there is told first.
|
|
6
|
+
// Nothing waits on a look longer than `hold`. CODA_DISABLE_RUNTIME_PATCHES=kimi leaves a plain relay, but for Coda's session
|
|
7
|
+
// instructions, which go in front of a new session's first prompt either way (instructions.mjs). A known quota error in
|
|
8
|
+
// a prompt's answer is classified at this boundary (errors.mjs), without retrying or changing other errors.
|
|
9
|
+
import { SessionInstructions } from './instructions.mjs';
|
|
10
|
+
import { classifyKimiError } from './errors.mjs';
|
|
11
|
+
import { SUPPORTED, kimiSession } from './observe.mjs';
|
|
12
|
+
import { KimiWaits } from './waits.mjs';
|
|
13
|
+
|
|
14
|
+
const record = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
15
|
+
|
|
16
|
+
export class KimiRelay {
|
|
17
|
+
// `say`: a message to Coda; `tell`: one to Kimi.
|
|
18
|
+
constructor({ say, tell, env = process.env, startedAt = Date.now(), every = 2_000, hold = 500, session = kimiSession }) {
|
|
19
|
+
this.say = say; this.tell = tell; this.env = env; this.startedAt = startedAt; this.every = every; this.hold = hold; this.makeSession = session;
|
|
20
|
+
this.plain = (env.CODA_DISABLE_RUNTIME_PATCHES ?? '').split(',').map(s => s.trim()).includes('kimi');
|
|
21
|
+
// Coda's requests whose answers are read here, by id; the prompts going.
|
|
22
|
+
this.asked = new Map(); this.prompts = new Set();
|
|
23
|
+
this.version = null; this.session = null; this.waits = null; this.content = []; this.instructions = new SessionInstructions();
|
|
24
|
+
// What Kimi said, passed on in order behind any message that waits for a look.
|
|
25
|
+
this.queue = Promise.resolve();
|
|
26
|
+
this.looking = null; this.again = false; this.lookedAt = -Infinity; this.timer = null; this.watching = null; this.closed = false;
|
|
27
|
+
}
|
|
28
|
+
fromCoda(message) {
|
|
29
|
+
const { agent, coda } = this.instructions.fromCoda(message);
|
|
30
|
+
if (coda) { this.queue = this.queue.then(() => this.say(coda)); return; }
|
|
31
|
+
message = agent;
|
|
32
|
+
if (!this.plain && 'id' in message && typeof message.method === 'string') {
|
|
33
|
+
if (message.method === 'initialize') this.asked.set(message.id, { initialize: true });
|
|
34
|
+
else if (['session/new', 'session/load'].includes(message.method)) this.asked.set(message.id, { cwd: message.params?.cwd, sessionId: message.params?.sessionId });
|
|
35
|
+
else if (message.method === 'session/prompt') { this.asked.set(message.id, { prompt: true }); this.prompts.add(message.id); }
|
|
36
|
+
}
|
|
37
|
+
this.tell(message);
|
|
38
|
+
}
|
|
39
|
+
fromAgent(message) {
|
|
40
|
+
if (!record(message)) return;
|
|
41
|
+
message = this.instructions.fromAgent(message);
|
|
42
|
+
const answer = 'id' in message && !('method' in message), asked = answer ? this.asked.get(message.id) : undefined;
|
|
43
|
+
if (asked) this.asked.delete(message.id);
|
|
44
|
+
if (asked?.initialize && record(message.result)) {
|
|
45
|
+
this.version = message.result.agentInfo?.version ?? null;
|
|
46
|
+
// It reports its waits, for the version whose files are understood.
|
|
47
|
+
if (this.version === SUPPORTED) {
|
|
48
|
+
const capabilities = record(message.result.agentCapabilities) ? message.result.agentCapabilities : {};
|
|
49
|
+
const meta = record(capabilities._meta) ? capabilities._meta : {};
|
|
50
|
+
message = { ...message, result: { ...message.result, agentCapabilities: { ...capabilities, _meta: { ...meta, coda: { waits: {} } } } } };
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (asked?.prompt) { this.prompts.delete(message.id); message = classifyKimiError(message); }
|
|
54
|
+
const waiting = asked?.prompt || (!answer && !this.prompts.size && this.waits && !this.waits.handling && Date.now() >= this.lookedAt + this.every);
|
|
55
|
+
this.queue = this.queue.then(async () => {
|
|
56
|
+
if (waiting) await this.look({ fresh: !!asked?.prompt });
|
|
57
|
+
this.say(message);
|
|
58
|
+
const sessionId = asked && !('error' in message) ? message.result?.sessionId ?? asked.sessionId : undefined;
|
|
59
|
+
if (typeof sessionId === 'string') this.begin(sessionId, asked.cwd);
|
|
60
|
+
}).catch(() => {});
|
|
61
|
+
}
|
|
62
|
+
begin(sessionId, cwd) {
|
|
63
|
+
this.unfollow();
|
|
64
|
+
this.session = this.makeSession({ sessionId, cwd, env: this.env, version: this.version, startedAt: this.startedAt });
|
|
65
|
+
this.waits = new KimiWaits({ sessionId, startedAt: this.startedAt });
|
|
66
|
+
this.observe();
|
|
67
|
+
}
|
|
68
|
+
// Waits, at most `hold`, for a look at the files: one begun after this, when `fresh`.
|
|
69
|
+
look({ fresh = false } = {}) {
|
|
70
|
+
if (!this.session) return;
|
|
71
|
+
const looked = fresh && this.looking ? this.looking.then(() => this.observe()) : this.observe();
|
|
72
|
+
let timer;
|
|
73
|
+
return Promise.race([looked, new Promise(resolve => { timer = setTimeout(resolve, this.hold); })]).finally(() => clearTimeout(timer));
|
|
74
|
+
}
|
|
75
|
+
// The look going, or a new one. What it finds is told as soon as it is found.
|
|
76
|
+
observe() {
|
|
77
|
+
if (this.looking || this.closed || !this.session) return this.looking;
|
|
78
|
+
const session = this.session, waits = this.waits, promptActive = this.prompts.size > 0;
|
|
79
|
+
this.lookedAt = Date.now();
|
|
80
|
+
this.looking = session.observe({ signal: new AbortController().signal, emit: (update, sessionId, taskId) => this.content.push({ update, sessionId, taskId }) })
|
|
81
|
+
.then(facts => {
|
|
82
|
+
if (this.closed || session !== this.session) return;
|
|
83
|
+
for (const message of facts ? waits.read(facts, this.content.splice(0), { promptActive }) : waits.lost()) this.say(message);
|
|
84
|
+
if (facts) this.follow();
|
|
85
|
+
}, () => {})
|
|
86
|
+
.finally(() => {
|
|
87
|
+
this.looking = null;
|
|
88
|
+
if (this.again) { this.again = false; this.noticed(); }
|
|
89
|
+
});
|
|
90
|
+
return this.looking;
|
|
91
|
+
}
|
|
92
|
+
// Once a look found its files, their changes have them looked at again.
|
|
93
|
+
follow() {
|
|
94
|
+
if (this.watching || this.closed) return;
|
|
95
|
+
this.watching = this.session.watch?.(() => this.noticed(), () => { this.watching = null; this.noticed(); }) ?? null;
|
|
96
|
+
}
|
|
97
|
+
unfollow() { this.watching?.close(); this.watching = null; }
|
|
98
|
+
noticed() {
|
|
99
|
+
if (this.closed || this.timer) return;
|
|
100
|
+
if (this.looking) { this.again = true; return; }
|
|
101
|
+
this.timer = setTimeout(() => { this.timer = null; this.observe(); }, Math.max(0, this.lookedAt + this.every - Date.now()));
|
|
102
|
+
}
|
|
103
|
+
// Everything Kimi said has been passed on.
|
|
104
|
+
drained() { return this.queue; }
|
|
105
|
+
close() { this.closed = true; this.unfollow(); clearTimeout(this.timer); this.timer = null; }
|
|
106
|
+
}
|