@coda-console/kimi 1.4.1 → 1.4.3

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/README.md CHANGED
@@ -1,3 +1,5 @@
1
1
  # Kimi Code
2
2
 
3
3
  Kimi Code Agent:Coda 的入口在运行机的 kimi acp 与 Coda 之间转发,读 Kimi 的会话文件报出后台命令与子 Agent;资源页的「Kimi」显示账号与额度,可从 Coda 安装和登录。
4
+
5
+ 不声明 `systemPrompt`;会话指令由 Coda 后端在新会话第一次非斜杠命令的用户输入前送入单独的文本块,恢复会话不再送,插件不用处理。
package/agent/observe.mjs CHANGED
@@ -6,12 +6,12 @@ import { KimiSubagentBridge, loopUpdate } from './subagents.mjs';
6
6
 
7
7
  const object = value => value && typeof value === 'object' && !Array.isArray(value);
8
8
  const identifier = value => typeof value === 'string' && /^[\w-]+$/.test(value);
9
- const unread = () => null;
10
9
 
11
10
  // 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
11
  // (`cron.add` / `cron.delete` / `cron.cursor` on the main wire) and its subagents' own conversations, which its ACP does
13
12
  // 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.
13
+ // new version simply loses this observation, and says which way its files are not as understood (`unread`, relay.mjs).
14
+ // The one place the version checked is written: setup installs it (scripts/setup.mjs).
15
15
  export const SUPPORTED = '2.1.1';
16
16
  // Bounded ordinary-file reads also prevent a broken index/FIFO from holding up
17
17
  // the entry. No paths, prompts, task output or credentials leave this module.
@@ -40,8 +40,9 @@ async function contained(root, path) {
40
40
  }
41
41
 
42
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 }) {
43
+ // before it is another process's, whose conversation is not told again. `unread`: why a look found nothing, each time.
44
+ export function kimiSession({ sessionId, cwd, env = {}, version, startedAt = 0, unread: told = () => {} }) {
45
+ const unread = reason => { told(reason); return null; };
45
46
  const home = env.KIMI_CODE_HOME || join(env.HOME || homedir(), '.kimi-code');
46
47
  let directory;
47
48
  let subagents;
@@ -80,7 +81,7 @@ export function kimiSession({ sessionId, cwd, env = {}, version, startedAt = 0 }
80
81
  // out as understood; a read that fails (a file being written) throws. A cron or goal event that is not the shape
81
82
  // understood is skipped, so one of them cannot hide the tasks.
82
83
  async observe({ signal, emit = () => {} }) {
83
- if (version !== SUPPORTED) return unread('unsupported_version');
84
+ if (version !== SUPPORTED) return unread('files:version');
84
85
  if (!identifier(sessionId) || !isAbsolute(home ?? '') || !isAbsolute(cwd ?? '')) return unread('unbound_session');
85
86
  const root = await realpath(join(home, 'sessions')), workspace = await realpath(cwd);
86
87
  if (!directory) {
@@ -98,10 +99,11 @@ export function kimiSession({ sessionId, cwd, env = {}, version, startedAt = 0 }
98
99
  }
99
100
  const session = await contained(root, directory);
100
101
  const state = JSON.parse(await read(join(session, 'state.json'), 1024 * 1024, signal));
101
- if (state.version !== 2 || state.id !== sessionId || typeof state.cwd !== 'string' ||
102
- await realpath(state.cwd) !== workspace || !object(state.agents) || !object(state.agents.main)) return unread('unsupported_layout');
102
+ if (state.version !== 2) return unread('files:state.version');
103
+ if (state.id !== sessionId || typeof state.cwd !== 'string' ||
104
+ await realpath(state.cwd) !== workspace || !object(state.agents) || !object(state.agents.main)) return unread('files:layout');
103
105
  const agents = Object.keys(state.agents);
104
- if (agents.length > 256 || !agents.every(identifier)) return unread('unsupported_layout');
106
+ if (agents.length > 256 || !agents.every(identifier)) return unread('files:layout');
105
107
 
106
108
  const records = [];
107
109
  for (const id of agents) {
@@ -110,16 +112,16 @@ export function kimiSession({ sessionId, cwd, env = {}, version, startedAt = 0 }
110
112
  try { tasks = await contained(agent, join(agent, 'tasks')); }
111
113
  catch (error) { if (error.code === 'ENOENT') continue; throw error; }
112
114
  const files = await readdir(tasks, { withFileTypes: true });
113
- if (files.length > 4096) return unread('unsupported_layout');
115
+ if (files.length > 4096) return unread('files:layout');
114
116
  for (const file of files) {
115
117
  signal.throwIfAborted();
116
118
  if (!file.name.endsWith('.json')) continue;
117
- if (!file.isFile()) return unread('unsupported_layout');
119
+ if (!file.isFile()) return unread('files:layout');
118
120
  const task = JSON.parse(await read(join(tasks, file.name), 1024 * 1024, signal));
119
121
  if (!object(task) || !identifier(task.taskId) || file.name !== `${task.taskId}.json` ||
120
- !['agent', 'process'].includes(task.kind) || typeof task.status !== 'string') return unread('unsupported_layout');
122
+ !['agent', 'process'].includes(task.kind) || typeof task.status !== 'string') return unread('files:layout');
121
123
  if (task.status !== 'running' && (!['completed', 'failed', 'killed', 'lost', 'timed_out'].includes(task.status) ||
122
- !Number.isSafeInteger(task.endedAt) || task.endedAt <= 0)) return unread('unsupported_layout');
124
+ !Number.isSafeInteger(task.endedAt) || task.endedAt <= 0)) return unread('files:layout');
123
125
  records.push(task);
124
126
  }
125
127
  }
@@ -132,7 +134,8 @@ export function kimiSession({ sessionId, cwd, env = {}, version, startedAt = 0 }
132
134
  const wire = await read(join(session, 'agents/main/wire.jsonl'), 32 * 1024 * 1024, signal);
133
135
  const lines = wire.trimEnd().split('\n');
134
136
  const metadata = JSON.parse(lines.shift());
135
- if (metadata.type !== 'metadata' || metadata.protocol_version !== '1.5') return unread('unsupported_layout');
137
+ if (metadata.type !== 'metadata') return unread('files:layout');
138
+ if (metadata.protocol_version !== '1.5') return unread('files:wire.protocol_version');
136
139
  // `cron.delete` is written when a fire is delivered and when CronDelete removes a job during a turn that is not that
137
140
  // fire. Which one it was is kept with the job: the open `cron_job` turn, that turn once it ended, or the delete that
138
141
  // landed inside some other turn already going. A delete before any such turn is not a cancel: the fire's turn.prompt
@@ -166,7 +169,7 @@ export function kimiSession({ sessionId, cwd, env = {}, version, startedAt = 0 }
166
169
  }
167
170
  } else if (event.type === 'turn.ended') {
168
171
  if (event.agentId !== 'main' || !going.has(event.turnId) || !['completed', 'cancelled', 'failed', 'blocked'].includes(event.reason) ||
169
- !Number.isSafeInteger(event.time) || event.time <= 0) return unread('unsupported_layout');
172
+ !Number.isSafeInteger(event.time) || event.time <= 0) return unread('files:layout');
170
173
  going.delete(event.turnId);
171
174
  turnEndedAt = event.time;
172
175
  for (const cron of crons.values()) if (cron.fireTurn === event.turnId) cron.fireEnded = true;
package/agent/relay.mjs CHANGED
@@ -7,11 +7,11 @@ import { kimiDisplayNames } from './display.mjs';
7
7
  // The turns Kimi's ACP does not tell, its goal's and those of prompts it queued behind them, are told from its files too
8
8
  // (turns.mjs): an answer Kimi gave at once to a prompt in which it said nothing waits for that look, and is held if Kimi
9
9
  // has not run the prompt yet.
10
- // Nothing waits on a look longer than `hold`. CODA_DISABLE_RUNTIME_PATCHES=kimi leaves a plain relay, but for Coda's session
11
- // instructions, which go in front of a new session's first prompt either way (instructions.mjs). A known quota error in
10
+ // Nothing waits on a look longer than `hold`. CODA_DISABLE_RUNTIME_PATCHES=kimi leaves a plain relay. A known quota error in
12
11
  // a prompt's answer is classified at this boundary (errors.mjs), without retrying or changing other errors; an `end_turn`
13
- // Kimi gave to a prompt whose turn its files say failed is passed on as that failure.
14
- import { SessionInstructions } from './instructions.mjs';
12
+ // Kimi gave to a prompt whose turn its files say failed is passed on as that failure. A Kimi whose files are not as understood
13
+ // (another version, another layout) is relayed as it would be anyway, but said so once a session and way, to a Coda that takes
14
+ // it (`_coda/unrecognized`, docs/agent-protocol.md「没适配的东西」): the user is told what goes unseen.
15
15
  import { classifyKimiError, failedAnswer } from './errors.mjs';
16
16
  import { SUPPORTED, kimiSession } from './observe.mjs';
17
17
  import { KimiWaits } from './waits.mjs';
@@ -20,6 +20,9 @@ import { KimiTurns } from './turns.mjs';
20
20
  const record = value => value && typeof value === 'object' && !Array.isArray(value);
21
21
  // What Kimi says in a turn, as opposed to what it says of the session.
22
22
  const SAID = new Set(['agent_message_chunk', 'agent_thought_chunk', 'tool_call', 'tool_call_update', 'plan']);
23
+ // Each way Kimi's files are not as understood (observe.mjs), by the name it is told by.
24
+ const UNREAD = { 'files:version': '这个版本的 Kimi 没有核对过', 'files:state.version': '会话的 state.json 版本对不上',
25
+ 'files:wire.protocol_version': '主 Agent 的 wire 协议版本对不上', 'files:layout': '会话文件的布局对不上' };
23
26
 
24
27
  export class KimiRelay {
25
28
  // `say`: a message to Coda; `tell`: one to Kimi.
@@ -29,18 +32,19 @@ export class KimiRelay {
29
32
  // Coda's requests whose answers are read here, by id; the prompts going, each with when it was sent and whether Kimi
30
33
  // said nothing in it yet.
31
34
  this.asked = new Map(); this.prompts = new Set(); this.sent = new Map();
32
- this.version = null; this.session = null; this.waits = null; this.turns = null; this.content = []; this.instructions = new SessionInstructions();
35
+ // Whether Coda takes what is not understood, and what it was told, by session and name.
36
+ this.taken = false; this.told = new Set();
37
+ this.version = null; this.session = null; this.waits = null; this.turns = null; this.content = [];
33
38
  // What Kimi said, passed on in order behind any message that waits for a look.
34
39
  this.queue = Promise.resolve();
35
40
  this.looking = null; this.again = false; this.lookedAt = -Infinity; this.timer = null; this.watching = null; this.closed = false;
36
41
  }
37
42
  fromCoda(message) {
38
- const { agent, coda } = this.instructions.fromCoda(message);
39
- if (coda) { this.queue = this.queue.then(() => this.say(coda)); return; }
40
- message = agent;
41
43
  if (!this.plain && 'id' in message && typeof message.method === 'string') {
42
- if (message.method === 'initialize') this.asked.set(message.id, { initialize: true });
43
- else if (['session/new', 'session/load'].includes(message.method)) this.asked.set(message.id, { cwd: message.params?.cwd, sessionId: message.params?.sessionId });
44
+ if (message.method === 'initialize') {
45
+ this.asked.set(message.id, { initialize: true });
46
+ this.taken = record(message.params?.clientCapabilities?._meta?.coda?.unrecognized);
47
+ } else if (['session/new', 'session/load'].includes(message.method)) this.asked.set(message.id, { cwd: message.params?.cwd, sessionId: message.params?.sessionId });
44
48
  else if (message.method === 'session/prompt') {
45
49
  this.asked.set(message.id, { prompt: true }); this.prompts.add(message.id); this.sent.set(message.id, { at: Date.now(), quiet: true });
46
50
  }
@@ -53,7 +57,7 @@ export class KimiRelay {
53
57
  }
54
58
  fromAgent(message) {
55
59
  if (!record(message)) return;
56
- message = kimiDisplayNames(this.instructions.fromAgent(message));
60
+ message = kimiDisplayNames(message);
57
61
  const answer = 'id' in message && !('method' in message), asked = answer ? this.asked.get(message.id) : undefined;
58
62
  if (asked) this.asked.delete(message.id);
59
63
  if (asked?.initialize && record(message.result)) {
@@ -81,11 +85,20 @@ export class KimiRelay {
81
85
  }
82
86
  begin(sessionId, cwd) {
83
87
  this.unfollow();
84
- this.session = this.makeSession({ sessionId, cwd, env: this.env, version: this.version, startedAt: this.startedAt });
88
+ this.session = this.makeSession({ sessionId, cwd, env: this.env, version: this.version, startedAt: this.startedAt,
89
+ unread: reason => this.unread(sessionId, reason) });
85
90
  this.waits = new KimiWaits({ sessionId, startedAt: this.startedAt });
86
91
  this.turns = new KimiTurns({ sessionId, startedAt: this.startedAt });
87
92
  this.observe();
88
93
  }
94
+ // A look at the session's files that found them not as understood (`name`, observe.mjs), told once.
95
+ unread(sessionId, name) {
96
+ const key = `${sessionId}\n${name}`;
97
+ if (!Object.hasOwn(UNREAD, name) || !this.taken || this.told.has(key)) return;
98
+ this.told.add(key);
99
+ this.say({ jsonrpc: '2.0', method: '_coda/unrecognized', params: { sessionId, kind: 'output', name, lost: true,
100
+ detail: `Kimi ${this.version ?? '(版本未知)'}:${UNREAD[name]}(核对过的是 ${SUPPORTED}),后台任务、子 Agent、定时看不见,失败的一轮可能显示成成功` } });
101
+ }
89
102
  // Waits, at most `hold`, for a look at the files: one begun after this, when `fresh`.
90
103
  look({ fresh = false } = {}) {
91
104
  if (!this.session) return;
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "id": "kimi",
4
4
  "displayName": "Kimi Code",
5
5
  "description": "用 Kimi Code 跑会话",
6
- "version": "1.4.1",
6
+ "version": "1.4.3",
7
7
  "categories": [
8
8
  "Agent"
9
9
  ],
@@ -39,7 +39,7 @@
39
39
  "signIn": {
40
40
  "command": "exec sh \"$CODA_PLUGIN_PATH/scripts/login.sh\"",
41
41
  "installed": "test -x \"$HOME/.kimi-code/bin/kimi\" || command -v kimi >/dev/null",
42
- "install": "exec sh \"$CODA_PLUGIN_PATH/scripts/install.sh\"",
42
+ "install": "exec \"$CODA_NODE\" \"$CODA_PLUGIN_PATH/scripts/setup.mjs\"",
43
43
  "note": "登录保存在这台机器的 Kimi CLI 里,由它自己续期。"
44
44
  }
45
45
  }
@@ -1,6 +1,7 @@
1
1
  #!/bin/sh
2
2
  # The Kimi CLI's own installer, as https://www.kimi.com/code gives it. It puts the CLI in ~/.kimi-code/bin, where Coda looks
3
3
  # first, and would add that to the shell's configuration and rename an older Python `kimi` it finds on the PATH: told not to
4
- # touch the configuration, with that directory not on the PATH, it leaves both alone.
4
+ # touch the configuration, with that directory not on the PATH, it leaves both alone. It installs KIMI_VERSION, which setup.mjs
5
+ # sets to the version the relay was checked against; the latest without it.
5
6
  PATH=$(printf '%s' "$PATH" | tr ':' '\n' | grep -vx "$HOME/.kimi-code/bin" | paste -sd: -)
6
7
  KIMI_NO_MODIFY_PATH=1 PATH="$PATH" exec bash -c 'set -o pipefail; curl -fsSL https://code.kimi.com/kimi-code/install.sh | bash'
package/scripts/setup.mjs CHANGED
@@ -1,13 +1,15 @@
1
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.
2
+ // ends well once the machine can run the agent; the「Kimi」resource type's install runs it too. Without a Kimi CLI that runs, or
3
+ // with one older than MINIMUM (the file layout the relay reads, agent/observe.mjs), Kimi's own installer (install.sh) puts that
4
+ // version (KIMI_VERSION) in ~/.kimi-code/bin, where the agent looks first; a newer one is kept. Why the machine is not ready
5
+ // is said in one line on standard error.
5
6
  import { spawnSync } from 'node:child_process';
6
7
  import { realpathSync } from 'node:fs';
7
8
  import { fileURLToPath } from 'node:url';
8
9
  import { kimiBinary } from '../agent/binary.mjs';
10
+ import { SUPPORTED } from '../agent/observe.mjs';
9
11
 
10
- export const MINIMUM = '2.1.1';
12
+ export const MINIMUM = SUPPORTED;
11
13
  // The first x.y.z a version command prints; whether one is older than another.
12
14
  export const versionIn = text => /(\d+)\.(\d+)\.(\d+)/.exec(text ?? '')?.slice(1).join('.') ?? null;
13
15
  export function older(version, than) {
@@ -32,7 +34,8 @@ if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToP
32
34
  const before = needed(kimiBinary());
33
35
  if (before.action !== 'none') {
34
36
  // 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] });
37
+ const installed = spawnSync('sh', [fileURLToPath(new URL('./install.sh', import.meta.url))], { stdio: ['ignore', 2, 2],
38
+ env: { ...process.env, KIMI_VERSION: MINIMUM } });
36
39
  if (installed.status !== 0) { console.error(`${before.reason},安装失败(退出码 ${installed.status ?? installed.signal})`); process.exit(1); }
37
40
  }
38
41
  const after = needed(kimiBinary());
@@ -1,68 +0,0 @@
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
- }