@coda-console/kimi 1.2.3 → 1.2.4

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/observe.mjs CHANGED
@@ -2,7 +2,7 @@ import { constants, watch } from 'node:fs';
2
2
  import { open, readdir, realpath } from 'node:fs/promises';
3
3
  import { isAbsolute, join, relative, sep } from 'node:path';
4
4
  import { homedir } from 'node:os';
5
- import { KimiSubagentBridge } from './subagents.mjs';
5
+ 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);
@@ -45,6 +45,9 @@ export function kimiSession({ sessionId, cwd, env = {}, version, startedAt = 0 }
45
45
  const home = env.KIMI_CODE_HOME || join(env.HOME || homedir(), '.kimi-code');
46
46
  let directory;
47
47
  let subagents;
48
+ // Lines of the main wire whose goal and turns were already given (`main`). The first look gives what it finds as of
49
+ // its end: the wire before it is another process's, or this one's from before it looked.
50
+ let given = null;
48
51
  return {
49
52
  // Calls `changed` whenever the session's files may have changed, and once its watches are in place; `lost` if one
50
53
  // breaks. Its directory is watched whole; its main agent's wire is a file appended to, whose watch (that of a file) is
@@ -70,9 +73,12 @@ export function kimiSession({ sessionId, cwd, env = {}, version, startedAt = 0 }
70
73
  // when its main agent last ended a turn (`turnEndedAt`, 0 for never), every cron the wire still tells of (`crons`, each
71
74
  // `waiting`, `handling`, `done` or `cancelled`, with the created time and fire cursor its next fire is counted from) and
72
75
  // 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
+ // own sessions' updates. `main` is what the main wire added since the last look, in its order, for turns.mjs: the goal
77
+ // as it changes, each main turn as it begins and ends, and what is said in a goal's or Coda's prompt's turn (as ACP
78
+ // updates); it opens with the goal and the turns still going as of the last look. A cron's prompt and a goal's objective
79
+ // do not leave here, only a short title cut from the first line. Null when the files are not this session's, or not laid
80
+ // out as understood; a read that fails (a file being written) throws. A cron or goal event that is not the shape
81
+ // understood is skipped, so one of them cannot hide the tasks.
76
82
  async observe({ signal, emit = () => {} }) {
77
83
  if (version !== SUPPORTED) return unread('unsupported_version');
78
84
  if (!identifier(sessionId) || !isAbsolute(home ?? '') || !isAbsolute(cwd ?? '')) return unread('unbound_session');
@@ -133,30 +139,80 @@ export function kimiSession({ sessionId, cwd, env = {}, version, startedAt = 0 }
133
139
  // is written after the delete. `cron.cursor` is the ideal minute that fire advanced to.
134
140
  const crons = new Map();
135
141
  const span = { turn: null };
136
- let turnId = null, turnEndedAt = 0;
137
- for (const line of lines) {
142
+ // Main turns begun and not yet ended. Kimi writes the next turn's start before the end of the one it follows.
143
+ const going = new Map();
144
+ const main = [];
145
+ let turnEndedAt = 0, goal = null, loopTurn = null;
146
+ const since = () => {
147
+ if (goal) main.push({ type: 'goal', id: goal.id, title: goal.title, active: goal.active });
148
+ for (const [turnId, turn] of going) if (turn.kind) main.push({ type: 'turn', turnId, ...turn });
149
+ };
150
+ const from = given ?? lines.length;
151
+ for (let i = 0; i < lines.length; i++) {
138
152
  signal.throwIfAborted();
139
- const event = JSON.parse(line);
153
+ if (i === from) since();
154
+ const fresh = i >= from, event = JSON.parse(lines[i]);
140
155
  if (event.type === 'cron.add') noteCron(crons, event);
141
156
  else if (event.type === 'cron.delete') dropCron(crons, event, span.turn);
142
157
  else if (event.type === 'cron.cursor') noteCursor(crons, event);
143
158
  else if (event.type === 'agent.turn.started' || (event.type === 'turn.prompt' && event.agentId === 'main')) {
144
159
  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);
160
+ if (!going.has(event.turnId)) going.set(event.turnId, {});
161
+ if (event.type === 'turn.prompt') {
162
+ noteFire(crons, event, span.turn);
163
+ const turn = { kind: turnKind(event.origin), time: event.time };
164
+ going.set(event.turnId, turn);
165
+ if (fresh) main.push({ type: 'turn', turnId: event.turnId, ...turn });
166
+ }
147
167
  } else if (event.type === 'turn.ended') {
148
- if (event.agentId !== 'main' || event.turnId !== turnId || !['completed', 'cancelled', 'failed', 'blocked'].includes(event.reason) ||
168
+ if (event.agentId !== 'main' || !going.has(event.turnId) || !['completed', 'cancelled', 'failed', 'blocked'].includes(event.reason) ||
149
169
  !Number.isSafeInteger(event.time) || event.time <= 0) return unread('unsupported_layout');
170
+ going.delete(event.turnId);
150
171
  turnEndedAt = event.time;
151
172
  for (const cron of crons.values()) if (cron.fireTurn === event.turnId) cron.fireEnded = true;
152
- span.turn = null;
173
+ if (span.turn?.turnId === event.turnId) span.turn = null;
174
+ if (fresh) main.push({ type: 'ended', turnId: event.turnId, reason: event.reason });
175
+ } else if (event.type === 'goal.create' || event.type === 'goal.update' || event.type === 'goal.clear') {
176
+ const next = noteGoal(goal, event);
177
+ if (next === goal) continue;
178
+ goal = next;
179
+ if (fresh) main.push({ type: 'goal', id: goal.id, title: goal.title, active: goal.active });
180
+ } else if (event.type === 'context.append_loop_event' && event.agentId === 'main' && object(event.event)) {
181
+ // A call's result names no turn: it is of the turn its call was made in, the one the loop is in.
182
+ if (event.event.turnId !== undefined) loopTurn = Number(event.event.turnId);
183
+ const kind = going.get(loopTurn)?.kind;
184
+ if (!fresh || (kind !== 'goal' && kind !== 'user')) continue;
185
+ const update = loopUpdate(event.event, { messageId: event.event.uuid, toolCallId: `${loopTurn}:${event.event.toolCallId}` });
186
+ if (update) main.push({ type: 'update', turnId: loopTurn, update });
153
187
  }
154
188
  }
155
- return { tasks, turnEndedAt, schedule: await cronClock(home, env, signal),
189
+ if (from >= lines.length) since();
190
+ given = lines.length;
191
+ return { tasks, turnEndedAt, main, schedule: await cronClock(home, env, signal),
156
192
  crons: [...crons.values()].map(publishCron) };
157
193
  } };
158
194
  }
159
195
 
196
+ // Who began a main turn: Coda's prompt (`user`), the goal (`goal`), or something else Kimi took up.
197
+ function turnKind(origin) {
198
+ if (origin?.kind === 'user') return 'user';
199
+ return origin?.kind === 'system_trigger' && origin.name === 'goal_continuation' ? 'goal' : 'other';
200
+ }
201
+ // Kimi's goal as its wire leaves it: `active` while Kimi keeps continuing toward it. Each time it turns active it is
202
+ // waited on afresh (`id`), since a wait that ended cannot begin again. A clear ends it.
203
+ function noteGoal(goal, event) {
204
+ if (event.type === 'goal.clear') return goal?.active ? { ...goal, active: false } : goal;
205
+ if (event.type === 'goal.create') {
206
+ if (!identifier(event.goalId) || typeof event.objective !== 'string') return goal;
207
+ return { goalId: event.goalId, runs: 1, id: event.goalId, title: event.objective.split(/\r?\n/, 1)[0].trim().slice(0, 100),
208
+ active: event.status === undefined || event.status === 'active' };
209
+ }
210
+ if (!goal || typeof event.status !== 'string' || (event.goalId !== undefined && event.goalId !== goal.goalId)) return goal;
211
+ const active = event.status === 'active';
212
+ if (active === goal.active) return goal;
213
+ return active ? { ...goal, runs: goal.runs + 1, id: `${goal.goalId}:${goal.runs + 1}`, active } : { ...goal, active };
214
+ }
215
+
160
216
  // A cron.add that is not the shape from 2.1.1 is ignored. A later add of the same id replaces it.
161
217
  function noteCron(crons, event) {
162
218
  const task = event.task;
package/agent/relay.mjs CHANGED
@@ -4,6 +4,9 @@ import { kimiDisplayNames } from './display.mjs';
4
4
  // known, again whenever they change, at most once every `every`, and before Kimi's answer to a prompt is passed on, so
5
5
  // 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
6
6
  // 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.
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
+ // (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
+ // has not run the prompt yet.
7
10
  // Nothing waits on a look longer than `hold`. CODA_DISABLE_RUNTIME_PATCHES=kimi leaves a plain relay, but for Coda's session
8
11
  // instructions, which go in front of a new session's first prompt either way (instructions.mjs). A known quota error in
9
12
  // a prompt's answer is classified at this boundary (errors.mjs), without retrying or changing other errors.
@@ -11,17 +14,21 @@ import { SessionInstructions } from './instructions.mjs';
11
14
  import { classifyKimiError } from './errors.mjs';
12
15
  import { SUPPORTED, kimiSession } from './observe.mjs';
13
16
  import { KimiWaits } from './waits.mjs';
17
+ import { KimiTurns } from './turns.mjs';
14
18
 
15
19
  const record = value => value && typeof value === 'object' && !Array.isArray(value);
20
+ // What Kimi says in a turn, as opposed to what it says of the session.
21
+ const SAID = new Set(['agent_message_chunk', 'agent_thought_chunk', 'tool_call', 'tool_call_update', 'plan']);
16
22
 
17
23
  export class KimiRelay {
18
24
  // `say`: a message to Coda; `tell`: one to Kimi.
19
25
  constructor({ say, tell, env = process.env, startedAt = Date.now(), every = 2_000, hold = 500, session = kimiSession }) {
20
26
  this.say = say; this.tell = tell; this.env = env; this.startedAt = startedAt; this.every = every; this.hold = hold; this.makeSession = session;
21
27
  this.plain = (env.CODA_DISABLE_RUNTIME_PATCHES ?? '').split(',').map(s => s.trim()).includes('kimi');
22
- // Coda's requests whose answers are read here, by id; the prompts going.
23
- this.asked = new Map(); this.prompts = new Set();
24
- this.version = null; this.session = null; this.waits = null; this.content = []; this.instructions = new SessionInstructions();
28
+ // Coda's requests whose answers are read here, by id; the prompts going, each with when it was sent and whether Kimi
29
+ // said nothing in it yet.
30
+ this.asked = new Map(); this.prompts = new Set(); this.sent = new Map();
31
+ this.version = null; this.session = null; this.waits = null; this.turns = null; this.content = []; this.instructions = new SessionInstructions();
25
32
  // What Kimi said, passed on in order behind any message that waits for a look.
26
33
  this.queue = Promise.resolve();
27
34
  this.looking = null; this.again = false; this.lookedAt = -Infinity; this.timer = null; this.watching = null; this.closed = false;
@@ -33,9 +40,15 @@ export class KimiRelay {
33
40
  if (!this.plain && 'id' in message && typeof message.method === 'string') {
34
41
  if (message.method === 'initialize') this.asked.set(message.id, { initialize: true });
35
42
  else if (['session/new', 'session/load'].includes(message.method)) this.asked.set(message.id, { cwd: message.params?.cwd, sessionId: message.params?.sessionId });
36
- else if (message.method === 'session/prompt') { this.asked.set(message.id, { prompt: true }); this.prompts.add(message.id); }
43
+ else if (message.method === 'session/prompt') {
44
+ this.asked.set(message.id, { prompt: true }); this.prompts.add(message.id); this.sent.set(message.id, { at: Date.now(), quiet: true });
45
+ }
37
46
  }
38
47
  this.tell(message);
48
+ if (message.method === 'session/cancel' && this.turns) for (const answer of this.turns.cancel()) {
49
+ this.prompts.delete(answer.id);
50
+ this.queue = this.queue.then(() => this.say(answer));
51
+ }
39
52
  }
40
53
  fromAgent(message) {
41
54
  if (!record(message)) return;
@@ -51,10 +64,13 @@ export class KimiRelay {
51
64
  message = { ...message, result: { ...message.result, agentCapabilities: { ...capabilities, _meta: { ...meta, coda: { waits: {} } } } } };
52
65
  }
53
66
  }
54
- if (asked?.prompt) { this.prompts.delete(message.id); message = classifyKimiError(message); }
67
+ const sent = asked?.prompt ? this.sent.get(message.id) : undefined;
68
+ if (asked?.prompt) { this.prompts.delete(message.id); this.sent.delete(message.id); message = classifyKimiError(message); }
69
+ else if (message.method === 'session/update' && SAID.has(message.params?.update?.sessionUpdate)) for (const going of this.sent.values()) going.quiet = false;
55
70
  const waiting = asked?.prompt || (!answer && !this.prompts.size && this.waits && !this.waits.handling && Date.now() >= this.lookedAt + this.every);
56
71
  this.queue = this.queue.then(async () => {
57
72
  if (waiting) await this.look({ fresh: !!asked?.prompt });
73
+ if (sent?.quiet && message.result?.stopReason === 'end_turn' && this.turns?.hold(sent.at, message)) { this.prompts.add(message.id); return; }
58
74
  this.say(message);
59
75
  const sessionId = asked && !('error' in message) ? message.result?.sessionId ?? asked.sessionId : undefined;
60
76
  if (typeof sessionId === 'string') this.begin(sessionId, asked.cwd);
@@ -64,6 +80,7 @@ export class KimiRelay {
64
80
  this.unfollow();
65
81
  this.session = this.makeSession({ sessionId, cwd, env: this.env, version: this.version, startedAt: this.startedAt });
66
82
  this.waits = new KimiWaits({ sessionId, startedAt: this.startedAt });
83
+ this.turns = new KimiTurns({ sessionId, startedAt: this.startedAt });
67
84
  this.observe();
68
85
  }
69
86
  // Waits, at most `hold`, for a look at the files: one begun after this, when `fresh`.
@@ -76,12 +93,17 @@ export class KimiRelay {
76
93
  // The look going, or a new one. What it finds is told as soon as it is found.
77
94
  observe() {
78
95
  if (this.looking || this.closed || !this.session) return this.looking;
79
- const session = this.session, waits = this.waits, promptActive = this.prompts.size > 0;
96
+ const session = this.session, waits = this.waits, turns = this.turns, promptActive = this.prompts.size > 0;
80
97
  this.lookedAt = Date.now();
81
98
  this.looking = session.observe({ signal: new AbortController().signal, emit: (update, sessionId, taskId) => this.content.push({ update, sessionId, taskId }) })
82
99
  .then(facts => {
83
100
  if (this.closed || session !== this.session) return;
84
- for (const message of facts ? waits.read(facts, this.content.splice(0), { promptActive }) : waits.lost()) this.say(message);
101
+ const told = facts ? [...waits.read(facts, this.content.splice(0), { promptActive }), ...turns.read(facts.main)] : [...waits.lost(), ...turns.lost()];
102
+ for (const message of told) {
103
+ // A held prompt's answer, now due.
104
+ if ('id' in message) this.prompts.delete(message.id);
105
+ this.say(message);
106
+ }
85
107
  if (facts) this.follow();
86
108
  }, () => {})
87
109
  .finally(() => {
@@ -9,6 +9,29 @@ function toolKind(name) {
9
9
  return 'other';
10
10
  }
11
11
 
12
+ // What one of Kimi's loop events says, as an ACP update: a thought, a reply, a tool call or a call's result; null for what
13
+ // says nothing. `messageId` names a thought or reply, `toolCallId` the call, in the session it is told in.
14
+ export function loopUpdate(event, { messageId, toolCallId }) {
15
+ const type = event?.type;
16
+ if (type === 'content.part' && event.part) {
17
+ const part = event.part;
18
+ if (part.type === 'think' && typeof part.think === 'string' && part.think.trim())
19
+ return { sessionUpdate: 'agent_thought_chunk', messageId, content: { type: 'text', text: part.think } };
20
+ if (part.type === 'text' && typeof part.text === 'string' && part.text.trim())
21
+ return { sessionUpdate: 'agent_message_chunk', messageId, content: { type: 'text', text: part.text } };
22
+ } else if (type === 'tool.call' && event.toolCallId) {
23
+ return { sessionUpdate: 'tool_call', toolCallId, title: event.name ?? '工具', kind: toolKind(event.name), status: 'in_progress', rawInput: event.args ?? {} };
24
+ } else if (type === 'tool.result' && event.toolCallId) {
25
+ const isError = Boolean(event.result?.isError || event.result?.error);
26
+ const output = typeof event.result?.output === 'string'
27
+ ? event.result.output
28
+ : (typeof event.result?.error === 'string' ? event.result.error : (event.result !== undefined ? JSON.stringify(event.result) : ''));
29
+ return { sessionUpdate: 'tool_call_update', toolCallId, status: isError ? 'failed' : 'completed',
30
+ content: [{ type: 'content', content: { type: 'text', text: output } }], rawOutput: event.result?.output ?? event.result };
31
+ }
32
+ return null;
33
+ }
34
+
12
35
  function findTaskForTime(taskList, time) {
13
36
  if (!taskList.length) return null;
14
37
  if (!Number.isFinite(time)) {
@@ -271,53 +294,14 @@ export class KimiSubagentBridge {
271
294
 
272
295
  // `subagentSessionId` names the run, for what it said; it is said in the subagent's session, `agentId`.
273
296
  processLoopEvent(agentId, subagentSessionId, event, sub, gen) {
274
- const type = event?.type;
275
- if (type === 'content.part' && event.part) {
276
- const part = event.part;
277
- if (part.type === 'think' && typeof part.think === 'string' && part.think.trim()) {
278
- const id = event.uuid || `${subagentSessionId}:think:${event.step ?? ''}:${event.turnId ?? ''}`;
279
- if (!sub.emittedIds.has(id)) {
280
- sub.emittedIds.add(id);
281
- this.emit({ sessionUpdate: 'agent_thought_chunk', messageId: id, content: { type: 'text', text: part.think } }, agentId, gen?.taskId);
282
- }
283
- } else if (part.type === 'text' && typeof part.text === 'string' && part.text.trim()) {
284
- const id = event.uuid || `${subagentSessionId}:text:${event.step ?? ''}:${event.turnId ?? ''}`;
285
- if (!sub.emittedIds.has(id)) {
286
- sub.emittedIds.add(id);
287
- this.emit({ sessionUpdate: 'agent_message_chunk', messageId: id, content: { type: 'text', text: part.text } }, agentId, gen?.taskId);
288
- if (gen) gen.hasAssistantMessage = true;
289
- }
290
- }
291
- } else if (type === 'tool.call' && event.toolCallId) {
292
- const callId = event.toolCallId;
293
- if (!sub.emittedIds.has(callId)) {
294
- sub.emittedIds.add(callId);
295
- this.emit({
296
- sessionUpdate: 'tool_call',
297
- toolCallId: callId,
298
- title: event.name ?? '工具',
299
- kind: toolKind(event.name),
300
- status: 'in_progress',
301
- rawInput: event.args ?? {},
302
- }, agentId, gen?.taskId);
303
- }
304
- } else if (type === 'tool.result' && event.toolCallId) {
305
- const callId = event.toolCallId;
306
- const resKey = `${callId}:result`;
307
- if (!sub.emittedIds.has(resKey)) {
308
- sub.emittedIds.add(resKey);
309
- const isError = Boolean(event.result?.isError || event.result?.error);
310
- const output = typeof event.result?.output === 'string'
311
- ? event.result.output
312
- : (typeof event.result?.error === 'string' ? event.result.error : (event.result !== undefined ? JSON.stringify(event.result) : ''));
313
- this.emit({
314
- sessionUpdate: 'tool_call_update',
315
- toolCallId: callId,
316
- status: isError ? 'failed' : 'completed',
317
- content: [{ type: 'content', content: { type: 'text', text: output } }],
318
- rawOutput: event.result?.output ?? event.result,
319
- }, agentId, gen?.taskId);
320
- }
321
- }
297
+ const kind = event?.type === 'content.part' ? event.part?.type : undefined;
298
+ const key = event?.type === 'tool.call' ? event.toolCallId
299
+ : event?.type === 'tool.result' ? `${event.toolCallId}:result`
300
+ : event.uuid || `${subagentSessionId}:${kind}:${event.step ?? ''}:${event.turnId ?? ''}`;
301
+ const update = loopUpdate(event, { messageId: key, toolCallId: event.toolCallId });
302
+ if (!update || sub.emittedIds.has(key)) return;
303
+ sub.emittedIds.add(key);
304
+ this.emit(update, agentId, gen?.taskId);
305
+ if (gen && update.sessionUpdate === 'agent_message_chunk') gen.hasAssistantMessage = true;
322
306
  }
323
307
  }
@@ -0,0 +1,111 @@
1
+ // The main turns Kimi's ACP does not tell, from its main wire (observe.mjs `main`). Its ACP passes on only the turn its own
2
+ // prompt drives. While Kimi has a goal it begins a turn of its own after each turn ends, toward that goal; a prompt that
3
+ // reaches it while such a turn is going is queued, and its ACP answers it at once though it runs later.
4
+ // So the goal is told as a timer that fires again after each turn (docs/agent-protocol.md「_coda/wait」): `handling` through
5
+ // each of its turns, which Coda takes up as turns of their own, `waiting` between them, `done` once the goal is no longer
6
+ // active. A Coda prompt Kimi answered at once without running it is held: its answer waits for the turn that runs it, the
7
+ // first of Coda's prompts' turns that began after it was sent. What is said in a goal's turn or a held prompt's is told as
8
+ // this session's updates; a turn from before this agent process (`startedAt`) is another process's and is not told.
9
+ const CONTINUES = '目标未完成前,每轮结束后自动继续';
10
+ // How Kimi's ACP answers a turn that ended so.
11
+ const STOPPED = { cancelled: 'cancelled', blocked: 'refusal' };
12
+
13
+ export class KimiTurns {
14
+ constructor({ sessionId, startedAt = 0 }) {
15
+ this.sessionId = sessionId; this.startedAt = startedAt;
16
+ // The goal as told ({ id, active, state, turn }) and as the wire last left it. Main turns going, those whose content is
17
+ // told, the last Coda prompt's turn seen, and the prompts held.
18
+ this.goal = null; this.latest = null; this.going = new Set(); this.telling = new Set(); this.user = null; this.held = [];
19
+ }
20
+ // Holds `answer`, Kimi's answer to the prompt sent at `sentAt`, when Kimi did not run that prompt yet: no turn of Coda's
21
+ // prompts began since, or the one that did is still going, while some turn is. False when it is to be passed on now.
22
+ hold(sentAt, answer) {
23
+ const user = this.user && !this.user.claimed && this.user.time >= sentAt ? this.user : null;
24
+ if (user ? user.ended : !this.going.size) return false;
25
+ if (user) { user.claimed = true; this.telling.add(user.turnId); }
26
+ this.held.push({ sentAt, answer, turnId: user?.turnId });
27
+ return true;
28
+ }
29
+ // What `main` tells Coda, in order: the goal's waits, what its turns and held prompts' turns said, and held answers due.
30
+ read(main = []) {
31
+ const told = [];
32
+ for (const entry of main) {
33
+ if (entry.type === 'goal') this.noteGoal(entry, told);
34
+ else if (entry.type === 'turn') this.begin(entry, told);
35
+ else if (entry.type === 'ended') this.end(entry, told);
36
+ else if (entry.type === 'update' && this.telling.has(entry.turnId)) told.push(update(this.sessionId, entry.update));
37
+ }
38
+ return told;
39
+ }
40
+ // The goal as the wire now leaves it. The one told goes on while it is this one and active; otherwise it ends, once its
41
+ // turn did, and this one is told if active.
42
+ noteGoal(entry, told) {
43
+ this.latest = entry;
44
+ const goal = this.goal;
45
+ if (open(goal)) {
46
+ goal.active = goal.id === entry.id && entry.active;
47
+ if (goal.active || goal.turn !== undefined) return;
48
+ this.say(told, 'done');
49
+ }
50
+ this.start(told);
51
+ }
52
+ start(told) {
53
+ const latest = this.latest;
54
+ if (!latest?.active || this.goal?.id === latest.id) return;
55
+ this.goal = { id: latest.id, active: true, state: 'waiting', turn: undefined };
56
+ told.push(wait({ sessionId: this.sessionId, waitId: latest.id, state: 'waiting', kind: 'timer', title: latest.title || 'Kimi 目标',
57
+ detail: CONTINUES, recurring: true, stoppable: false }));
58
+ }
59
+ begin({ turnId, kind, time }, told) {
60
+ if (time < this.startedAt || this.going.has(turnId)) return;
61
+ this.going.add(turnId);
62
+ if (kind === 'goal') {
63
+ // The goal's turn before it ended, though Kimi writes that end after this start.
64
+ if (open(this.goal) && this.goal.turn !== undefined) this.settle(told);
65
+ if (!open(this.goal)) return;
66
+ this.goal.turn = turnId;
67
+ this.telling.add(turnId);
68
+ this.say(told, 'handling');
69
+ } else if (kind === 'user') {
70
+ this.user = { turnId, time, ended: false, claimed: false };
71
+ const held = this.held.find(h => h.turnId === undefined && h.sentAt <= time);
72
+ if (held) { held.turnId = turnId; this.user.claimed = true; this.telling.add(turnId); }
73
+ }
74
+ }
75
+ end({ turnId, reason }, told) {
76
+ if (!this.going.delete(turnId)) return;
77
+ this.telling.delete(turnId);
78
+ if (this.user?.turnId === turnId) this.user.ended = true;
79
+ if (this.goal?.turn === turnId) this.settle(told);
80
+ const i = this.held.findIndex(h => h.turnId === turnId);
81
+ if (i >= 0) told.push(answered(this.held.splice(i, 1)[0].answer, STOPPED[reason] ?? 'end_turn'));
82
+ }
83
+ // The goal's turn is over: it waits for the next, or ends, and the goal that replaced it is told.
84
+ settle(told) {
85
+ this.goal.turn = undefined;
86
+ this.say(told, this.goal.active ? 'waiting' : 'done');
87
+ this.start(told);
88
+ }
89
+ say(told, state) {
90
+ this.goal.state = state;
91
+ told.push(wait({ sessionId: this.sessionId, waitId: this.goal.id, state }));
92
+ }
93
+ // Coda stopped: Kimi's ACP cannot stop a turn it does not drive, so a held prompt is answered as stopped now, and what its
94
+ // turn says if it still runs is not told.
95
+ cancel() {
96
+ for (const held of this.held) this.telling.delete(held.turnId);
97
+ return this.held.splice(0).map(held => answered(held.answer, 'cancelled'));
98
+ }
99
+ // The files no longer read as understood: the goal ends, and held answers are passed on as Kimi gave them.
100
+ lost() {
101
+ const told = [];
102
+ if (open(this.goal)) { this.goal.turn = undefined; this.say(told, 'failed'); }
103
+ this.going.clear(); this.telling.clear(); this.user = null;
104
+ return [...told, ...this.held.splice(0).map(held => held.answer)];
105
+ }
106
+ }
107
+
108
+ const open = goal => goal?.state === 'waiting' || goal?.state === 'handling';
109
+ const wait = params => ({ jsonrpc: '2.0', method: '_coda/wait', params });
110
+ const update = (sessionId, value) => ({ jsonrpc: '2.0', method: 'session/update', params: { sessionId, update: value } });
111
+ const answered = (answer, stopReason) => ({ ...answer, result: { ...answer.result, stopReason } });
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "id": "kimi",
4
4
  "displayName": "Kimi Code",
5
5
  "description": "Kimi Code Agent:Coda 的入口在运行机的 kimi acp 与 Coda 之间转发,读 Kimi 的会话文件报出后台命令与子 Agent;资源页的「Kimi」面板显示账号与额度,可从 Coda 安装和登录。",
6
- "version": "1.2.3",
6
+ "version": "1.2.4",
7
7
  "categories": [
8
8
  "Agent"
9
9
  ],