@nightloom/isy 1.0.1 → 1.0.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.
Files changed (152) hide show
  1. package/README.md +1 -1
  2. package/dist/agents/claude.js +18 -7
  3. package/dist/agents/claude.js.map +1 -1
  4. package/dist/agents/codex-records.js +16 -2
  5. package/dist/agents/codex-records.js.map +1 -1
  6. package/dist/agents/index.d.ts +16 -5
  7. package/dist/agents/index.js +21 -6
  8. package/dist/agents/index.js.map +1 -1
  9. package/dist/agents/kimi-cli-wire.d.ts +17 -0
  10. package/dist/agents/kimi-cli-wire.js +312 -0
  11. package/dist/agents/kimi-cli-wire.js.map +1 -0
  12. package/dist/agents/kimi-config.d.ts +29 -0
  13. package/dist/agents/kimi-config.js +193 -0
  14. package/dist/agents/kimi-config.js.map +1 -0
  15. package/dist/agents/kimi-records.d.ts +0 -6
  16. package/dist/agents/kimi-records.js +51 -31
  17. package/dist/agents/kimi-records.js.map +1 -1
  18. package/dist/agents/kimi-tools.d.ts +30 -0
  19. package/dist/agents/kimi-tools.js +100 -0
  20. package/dist/agents/kimi-tools.js.map +1 -0
  21. package/dist/agents/kimi-wire.d.ts +8 -0
  22. package/dist/agents/kimi-wire.js +245 -80
  23. package/dist/agents/kimi-wire.js.map +1 -1
  24. package/dist/agents/kimi.d.ts +13 -2
  25. package/dist/agents/kimi.js +633 -114
  26. package/dist/agents/kimi.js.map +1 -1
  27. package/dist/agents/timeline.d.ts +36 -0
  28. package/dist/agents/timeline.js +61 -0
  29. package/dist/agents/timeline.js.map +1 -0
  30. package/dist/agents/types.d.ts +12 -0
  31. package/dist/api.d.ts +3 -0
  32. package/dist/api.js +1 -1
  33. package/dist/api.js.map +1 -1
  34. package/dist/commands/analyze.d.ts +2 -0
  35. package/dist/commands/analyze.js +63 -6
  36. package/dist/commands/analyze.js.map +1 -1
  37. package/dist/commands/check.js +11 -0
  38. package/dist/commands/check.js.map +1 -1
  39. package/dist/commands/health.js +2 -2
  40. package/dist/commands/health.js.map +1 -1
  41. package/dist/commands/init.js +25 -2
  42. package/dist/commands/init.js.map +1 -1
  43. package/dist/commands/upload.d.ts +2 -0
  44. package/dist/commands/upload.js +38 -7
  45. package/dist/commands/upload.js.map +1 -1
  46. package/dist/detectors.js +40 -5
  47. package/dist/detectors.js.map +1 -1
  48. package/dist/hook.d.ts +12 -5
  49. package/dist/hook.js +73 -17
  50. package/dist/hook.js.map +1 -1
  51. package/dist/lines.d.ts +8 -0
  52. package/dist/lines.js +32 -0
  53. package/dist/lines.js.map +1 -0
  54. package/dist/mask-paths.js +31 -15
  55. package/dist/mask-paths.js.map +1 -1
  56. package/dist/parser.d.ts +41 -0
  57. package/dist/parser.js +345 -36
  58. package/dist/parser.js.map +1 -1
  59. package/dist/paths.d.ts +4 -0
  60. package/dist/paths.js +39 -39
  61. package/dist/paths.js.map +1 -1
  62. package/dist/plan.d.ts +3 -1
  63. package/dist/plan.js +5 -1
  64. package/dist/plan.js.map +1 -1
  65. package/dist/queue.d.ts +14 -2
  66. package/dist/queue.js +25 -3
  67. package/dist/queue.js.map +1 -1
  68. package/dist/redact.d.ts +17 -0
  69. package/dist/redact.js +202 -12
  70. package/dist/redact.js.map +1 -1
  71. package/dist/state.d.ts +15 -6
  72. package/dist/state.js +25 -9
  73. package/dist/state.js.map +1 -1
  74. package/dist/subagents.d.ts +53 -0
  75. package/dist/subagents.js +243 -0
  76. package/dist/subagents.js.map +1 -0
  77. package/dist/test/check.test.js +25 -3
  78. package/dist/test/check.test.js.map +1 -1
  79. package/dist/test/codex.test.js +21 -0
  80. package/dist/test/codex.test.js.map +1 -1
  81. package/dist/test/commit.test.js +9 -1
  82. package/dist/test/commit.test.js.map +1 -1
  83. package/dist/test/hook.test.js +66 -2
  84. package/dist/test/hook.test.js.map +1 -1
  85. package/dist/test/init.test.d.ts +1 -0
  86. package/dist/test/init.test.js +102 -0
  87. package/dist/test/init.test.js.map +1 -0
  88. package/dist/test/kimi-cli.test.d.ts +1 -0
  89. package/dist/test/kimi-cli.test.js +231 -0
  90. package/dist/test/kimi-cli.test.js.map +1 -0
  91. package/dist/test/kimi-code.test.d.ts +1 -0
  92. package/dist/test/kimi-code.test.js +302 -0
  93. package/dist/test/kimi-code.test.js.map +1 -0
  94. package/dist/test/kimi-config.test.d.ts +1 -0
  95. package/dist/test/kimi-config.test.js +224 -0
  96. package/dist/test/kimi-config.test.js.map +1 -0
  97. package/dist/test/kimi-hook.test.d.ts +1 -0
  98. package/dist/test/kimi-hook.test.js +163 -0
  99. package/dist/test/kimi-hook.test.js.map +1 -0
  100. package/dist/test/kimi-listing.test.d.ts +1 -0
  101. package/dist/test/kimi-listing.test.js +193 -0
  102. package/dist/test/kimi-listing.test.js.map +1 -0
  103. package/dist/test/kimi.test.js +52 -7
  104. package/dist/test/kimi.test.js.map +1 -1
  105. package/dist/test/mask-paths.test.js +31 -0
  106. package/dist/test/mask-paths.test.js.map +1 -1
  107. package/dist/test/parser.test.js +208 -5
  108. package/dist/test/parser.test.js.map +1 -1
  109. package/dist/test/plan.test.js +7 -6
  110. package/dist/test/plan.test.js.map +1 -1
  111. package/dist/test/redact.test.js +245 -8
  112. package/dist/test/redact.test.js.map +1 -1
  113. package/dist/test/stage0.test.js +49 -0
  114. package/dist/test/stage0.test.js.map +1 -1
  115. package/dist/test/subagents.test.d.ts +1 -0
  116. package/dist/test/subagents.test.js +290 -0
  117. package/dist/test/subagents.test.js.map +1 -0
  118. package/dist/test/sweep.test.js +25 -0
  119. package/dist/test/sweep.test.js.map +1 -1
  120. package/dist/test/upload.test.js +68 -6
  121. package/dist/test/upload.test.js.map +1 -1
  122. package/dist/types.d.ts +16 -0
  123. package/package.json +5 -3
  124. package/src/agents/claude.ts +17 -7
  125. package/src/agents/codex-records.ts +17 -2
  126. package/src/agents/index.ts +21 -6
  127. package/src/agents/kimi-cli-wire.ts +350 -0
  128. package/src/agents/kimi-config.ts +210 -0
  129. package/src/agents/kimi-records.ts +52 -29
  130. package/src/agents/kimi-tools.ts +128 -0
  131. package/src/agents/kimi-wire.ts +270 -82
  132. package/src/agents/kimi.ts +653 -113
  133. package/src/agents/timeline.ts +68 -0
  134. package/src/agents/types.ts +12 -0
  135. package/src/api.ts +5 -2
  136. package/src/commands/analyze.ts +62 -6
  137. package/src/commands/check.ts +11 -0
  138. package/src/commands/health.ts +2 -2
  139. package/src/commands/init.ts +26 -2
  140. package/src/commands/upload.ts +46 -7
  141. package/src/detectors.ts +39 -5
  142. package/src/hook.ts +81 -24
  143. package/src/lines.ts +31 -0
  144. package/src/mask-paths.ts +31 -14
  145. package/src/parser.ts +356 -35
  146. package/src/paths.ts +36 -33
  147. package/src/plan.ts +4 -1
  148. package/src/queue.ts +30 -4
  149. package/src/redact.ts +218 -15
  150. package/src/state.ts +34 -9
  151. package/src/subagents.ts +292 -0
  152. package/src/types.ts +16 -0
@@ -1,37 +1,54 @@
1
- import { existsSync } from "node:fs";
2
- import { access, mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
1
+ import { createHash } from "node:crypto";
2
+ import { constants, existsSync } from "node:fs";
3
+ import { access, mkdir, readFile, readdir, realpath, stat, writeFile } from "node:fs/promises";
3
4
  import { homedir } from "node:os";
4
- import { basename, dirname, join } from "node:path";
5
+ import { basename, delimiter, dirname, join } from "node:path";
5
6
  import { parkAlert } from "../alert.js";
6
7
  import { parseLines } from "../parser.js";
7
- import { pendingAlertPath } from "../paths.js";
8
+ import { firstLine, firstLines, lastActive, pendingAlertPath } from "../paths.js";
8
9
  import { redactLines } from "../redact.js";
9
10
  import type { DiscoveredSession, ParsedSession, SessionFile } from "../types.js";
11
+ import { isKimiCliWire, kimiCliWireToClaudeRecords } from "./kimi-cli-wire.js";
12
+ import { basicString, hookTables } from "./kimi-config.js";
13
+ import type { HookTable } from "./kimi-config.js";
10
14
  import { toClaudeRecords } from "./kimi-records.js";
11
15
  import { isKimiWireTranscript, wireToClaudeRecords } from "./kimi-wire.js";
12
16
  import type { Agent, AgentHook, HookInput } from "./types.js";
13
17
 
14
- /** Builds have shipped under both names; take whichever this machine has. */
15
- const HOME_CANDIDATES = [".kimi", ".kimi-code"];
16
-
17
- export function kimiHome(): string {
18
+ /**
19
+ * Where Kimi keeps its state. Two CLIs have shipped under the name: the Python
20
+ * Kimi CLI, archived at 1.52, in `~/.kimi` (`KIMI_SHARE_DIR` moves it), and
21
+ * Kimi Code, the TypeScript CLI that replaced it, in `~/.kimi-code`
22
+ * (`KIMI_CODE_HOME` moves it). A machine that upgraded has both, and sessions
23
+ * in both, so every home that exists is read — taking the first one found left
24
+ * the other CLI's sessions unseen. `KIMI_HOME` pins a single home, which is
25
+ * what tests do.
26
+ */
27
+ export function kimiHomes(): string[] {
18
28
  const override = process.env.KIMI_HOME;
19
- if (override) return override;
29
+ if (override) return [override];
20
30
 
21
- for (const name of HOME_CANDIDATES) {
22
- const candidate = join(homedir(), name);
23
- if (existsSync(candidate)) return candidate;
24
- }
25
- return join(homedir(), HOME_CANDIDATES[0]!);
31
+ const candidates = [process.env.KIMI_SHARE_DIR || join(homedir(), ".kimi"), kimiCodeHome()];
32
+ const present = [...new Set(candidates)].filter((candidate) => existsSync(candidate));
33
+ return present.length > 0 ? present : [candidates[0]!];
26
34
  }
27
35
 
28
- export function kimiConfigPath(): string {
29
- return join(kimiHome(), "config.toml");
36
+ function kimiCodeHome(): string {
37
+ return process.env.KIMI_CODE_HOME || join(homedir(), ".kimi-code");
38
+ }
39
+
40
+ /** The home named first — where a message to the user points. */
41
+ export function kimiHome(): string {
42
+ return kimiHomes()[0]!;
43
+ }
44
+
45
+ export function kimiConfigPath(home = kimiHome()): string {
46
+ return join(home, "config.toml");
30
47
  }
31
48
 
32
49
  /** Every workspace's sessions, whatever Kimi decides to name the folders. */
33
- export function kimiSessionsRoot(): string {
34
- return join(kimiHome(), "sessions");
50
+ export function kimiSessionsRoot(home = kimiHome()): string {
51
+ return join(home, "sessions");
35
52
  }
36
53
 
37
54
  /**
@@ -49,6 +66,8 @@ export function kimiSessionsRoot(): string {
49
66
  interface KimiSession {
50
67
  sessionId: string;
51
68
  transcript: string;
69
+ /** The session folder: its subagents' logs are in it too. */
70
+ dir: string;
52
71
  cwd?: string;
53
72
  }
54
73
 
@@ -65,24 +84,98 @@ async function subdirectories(dir: string): Promise<string[]> {
65
84
  }
66
85
  }
67
86
 
68
- /** The transcript inside a session folder, whichever layout this build uses. */
69
- async function transcriptIn(dir: string, state: Record<string, unknown>): Promise<string | undefined> {
87
+ async function isFile(path: string): Promise<boolean> {
88
+ try {
89
+ return (await stat(path)).isFile();
90
+ } catch {
91
+ return false;
92
+ }
93
+ }
94
+
95
+ /**
96
+ * The first few lines of a file, enough to tell its format by, and no more:
97
+ * listing reads this for every Kimi CLI session there is, and a whole log read
98
+ * each time made listing cost what every transcript on the machine weighs.
99
+ */
100
+ async function head(path: string, count = 3): Promise<string[]> {
101
+ try {
102
+ return await firstLines(path, count);
103
+ } catch {
104
+ return [];
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Where one of Kimi Code's agents keeps its log: `agents/<id>/wire.jsonl` in
110
+ * the session folder, or wherever `state.json` says its home is. The folder
111
+ * comes first, because `state.json` records an absolute path, and a session
112
+ * folder that was moved or copied still holds its logs.
113
+ */
114
+ async function agentLog(dir: string, state: Record<string, unknown>, id: string): Promise<string | undefined> {
70
115
  const agents = isObject(state.agents) ? state.agents : {};
116
+ const agent = agents[id];
117
+ const homes = [join(dir, "agents", id)];
118
+ if (isObject(agent) && typeof agent.homedir === "string") homes.push(agent.homedir);
71
119
 
72
- // `main` is the session's own agent; the rest are sub-agents, whose logs are
73
- // sidechains and not this session's transcript.
74
- const home = isObject(agents.main) && typeof agents.main.homedir === "string"
75
- ? agents.main.homedir
76
- : join(dir, "agents", "main");
120
+ for (const home of homes) if (await isFile(join(home, "wire.jsonl"))) return join(home, "wire.jsonl");
121
+ return undefined;
122
+ }
123
+
124
+ /**
125
+ * The transcript inside a session folder, whichever layout wrote it:
126
+ * - Kimi Code: `agents/main/wire.jsonl` (`main` is the session's own agent; the
127
+ * rest are subagents, read into it by `subagentLogs`);
128
+ * - Kimi CLI 1.x: `wire.jsonl` beside `state.json`, the whole session as an
129
+ * event log (`kimi-cli-wire.ts`) — its subagents included;
130
+ * - older builds: `context.jsonl`, the conversation alone.
131
+ */
132
+ async function transcriptIn(dir: string, state: Record<string, unknown>): Promise<string | undefined> {
133
+ const main = await agentLog(dir, state, "main");
134
+ if (main) return main;
135
+ if (isKimiCliWire(await head(join(dir, "wire.jsonl")))) return join(dir, "wire.jsonl");
136
+ if (await isFile(join(dir, "context.jsonl"))) return join(dir, "context.jsonl");
137
+ return undefined;
138
+ }
77
139
 
78
- for (const candidate of [join(home, "wire.jsonl"), join(dir, "context.jsonl")]) {
140
+ /**
141
+ * Every subagent's log in a Kimi Code session, by agent id: each writes its own
142
+ * (`agents/agent-<n>/wire.jsonl`), and the main log only says where it started
143
+ * (`kimi-wire.ts`). Read without them, a session that delegated its edits
144
+ * showed stage 0 none of them. `state.json` lists the agents; a folder it has
145
+ * not caught up with yet is read too, since the log is what the agent did.
146
+ */
147
+ async function subagentLogs(dir: string, state: Record<string, unknown>): Promise<Map<string, string[]>> {
148
+ const listed = isObject(state.agents) ? Object.keys(state.agents) : [];
149
+ const ids = [...new Set([...listed, ...(await subdirectories(join(dir, "agents")))])].filter((id) => id !== "main");
150
+
151
+ const logs = new Map<string, string[]>();
152
+ for (const id of ids) {
153
+ const log = await agentLog(dir, state, id);
154
+ if (!log) continue;
79
155
  try {
80
- if ((await stat(candidate)).isFile()) return candidate;
156
+ logs.set(id, (await readFile(log, "utf8")).split("\n"));
81
157
  } catch {
82
158
  continue;
83
159
  }
84
160
  }
85
- return undefined;
161
+ return logs;
162
+ }
163
+
164
+ /**
165
+ * Every subagent's own log in a Kimi CLI session, by agent id:
166
+ * `subagents/<id>/wire.jsonl`. A background subagent writes only there; the
167
+ * reader tells which of them the session's own log already carries.
168
+ */
169
+ async function kimiCliSubagentLogs(dir: string): Promise<Map<string, string[]>> {
170
+ const logs = new Map<string, string[]>();
171
+ for (const id of await subdirectories(join(dir, "subagents"))) {
172
+ try {
173
+ logs.set(id, (await readFile(join(dir, "subagents", id, "wire.jsonl"), "utf8")).split("\n"));
174
+ } catch {
175
+ continue;
176
+ }
177
+ }
178
+ return logs;
86
179
  }
87
180
 
88
181
  /** Everything Kimi records about a session outside its transcript. */
@@ -105,19 +198,110 @@ function sessionIdOf(state: Record<string, unknown> | undefined, dir: string): s
105
198
  return typeof id === "string" && id.length > 0 ? id : basename(dir);
106
199
  }
107
200
 
201
+ /**
202
+ * Which directory each workspace folder belongs to, from `kimi.json` in the
203
+ * home. Kimi CLI names a workspace folder after the MD5 of its path and writes
204
+ * the path itself only there — its `state.json` has no `cwd` at all, so a
205
+ * session of it matched no directory and was never uploaded from one.
206
+ */
207
+ async function workspaces(home: string): Promise<Map<string, string>> {
208
+ const found = new Map<string, string>();
209
+ let parsed: unknown;
210
+ try {
211
+ parsed = JSON.parse(await readFile(join(home, "kimi.json"), "utf8"));
212
+ } catch {
213
+ return found;
214
+ }
215
+ const dirs = isObject(parsed) && Array.isArray(parsed.work_dirs) ? parsed.work_dirs : [];
216
+ for (const entry of dirs) {
217
+ if (!isObject(entry) || typeof entry.path !== "string") continue;
218
+ const hash = createHash("md5").update(entry.path, "utf8").digest("hex");
219
+ // A workspace on another backend is filed as `<kaos>_<md5>`.
220
+ const kaos = typeof entry.kaos === "string" && entry.kaos !== "local" ? `${entry.kaos}_` : "";
221
+ found.set(`${kaos}${hash}`, entry.path);
222
+ }
223
+ return found;
224
+ }
225
+
226
+ /**
227
+ * The working directory Kimi CLI states to the model in its system prompt —
228
+ * the first line of `context.jsonl` — for a session whose home lost `kimi.json`.
229
+ */
230
+ async function promptedCwd(dir: string): Promise<string | undefined> {
231
+ const first = await firstLine(join(dir, "context.jsonl")).catch(() => "");
232
+ const stated = /The current working directory is `([^`]+)`/.exec(first);
233
+ return stated?.[1];
234
+ }
235
+
108
236
  /** Where the session ran, which is the root every path in it is relative to. */
109
237
  function recordedCwd(state: Record<string, unknown> | undefined): string | undefined {
110
238
  return typeof state?.cwd === "string" ? state.cwd : undefined;
111
239
  }
112
240
 
113
- async function readSession(dir: string): Promise<KimiSession | undefined> {
114
- const state = await readState(dir);
115
- if (!state) return undefined;
241
+ /** Where a session ran, by whichever record of it this build keeps. */
242
+ async function cwdOfSession(
243
+ dir: string,
244
+ state: Record<string, unknown> | undefined,
245
+ known?: Map<string, string>,
246
+ ): Promise<string | undefined> {
247
+ return (
248
+ recordedCwd(state) ??
249
+ (known ?? (await workspaces(dirname(dirname(dirname(dir)))))).get(basename(dirname(dir))) ??
250
+ (await promptedCwd(dir))
251
+ );
252
+ }
116
253
 
117
- const transcript = await transcriptIn(dir, state);
254
+ /** A time `state.json` records, as epoch milliseconds: a number, or a date string. */
255
+ function epochOf(value: unknown): number | undefined {
256
+ const at = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
257
+ return Number.isFinite(at) ? at : undefined;
258
+ }
259
+
260
+ /**
261
+ * Up to when a Kimi Code session's logs hold another session's work, if they
262
+ * do. A session Kimi Code imported from Kimi CLI holds that session up to the
263
+ * import (`custom.imported_at`), written again under a new id with the old
264
+ * times or none; a session forked off with `/fork` holds its source up to the
265
+ * fork (`forkedFrom`, created then), every call copied with its time. That
266
+ * part goes up as the session it came from; what came after it is this one's.
267
+ * An import whose time does not read is taken as holding everything.
268
+ */
269
+ function copiedUntil(state: Record<string, unknown> | undefined): number | undefined {
270
+ const custom = isObject(state?.custom) ? state.custom : undefined;
271
+ const imported = custom?.imported_from_kimi_cli === true ? (epochOf(custom.imported_at) ?? Infinity) : undefined;
272
+ const forked = typeof state?.forkedFrom === "string" ? epochOf(state.createdAt) : undefined;
273
+ if (imported === undefined && forked === undefined) return undefined;
274
+ return Math.max(imported ?? -Infinity, forked ?? -Infinity);
275
+ }
276
+
277
+ async function modifiedAfter(path: string, at: number): Promise<boolean> {
278
+ try {
279
+ return (await stat(path)).mtimeMs > at;
280
+ } catch {
281
+ return false;
282
+ }
283
+ }
284
+
285
+ async function readSession(dir: string, known: Map<string, string>): Promise<KimiSession | undefined> {
286
+ const state = await readState(dir);
287
+ const transcript = await transcriptIn(dir, state ?? {});
118
288
  if (!transcript) return undefined;
119
289
 
120
- return { sessionId: sessionIdOf(state, dir), transcript, cwd: recordedCwd(state) };
290
+ // Kimi CLI writes `state.json` only once a turn completes or a setting
291
+ // changes, so a first turn cancelled, failed or cut off at its step limit
292
+ // leaves none — after edits, as often as not. Its log names the session:
293
+ // the folder is its id. Kimi Code writes `state.json` as it starts, and a
294
+ // folder of its without one is a copy that never finished.
295
+ const kimiCli = transcript === join(dir, "wire.jsonl") || transcript === join(dir, "context.jsonl");
296
+ if (!state && !kimiCli) return undefined;
297
+
298
+ // A copy nobody went on with — imported from Kimi CLI, or forked off — is
299
+ // the session it was copied from again. A sweep sent every imported one a
300
+ // second time, and as text alone, since the import keeps no tool calls.
301
+ const copied = copiedUntil(state);
302
+ if (copied !== undefined && !(await modifiedAfter(transcript, copied))) return undefined;
303
+
304
+ return { sessionId: sessionIdOf(state, dir), transcript, dir, cwd: await cwdOfSession(dir, state, known) };
121
305
  }
122
306
 
123
307
  /**
@@ -134,11 +318,26 @@ async function discovered(sessions: readonly KimiSession[]): Promise<DiscoveredS
134
318
  for (const session of sessions) {
135
319
  try {
136
320
  const info = await stat(session.transcript);
321
+ // Size and mtime with the subagents' logs: one sent to the background
322
+ // goes on writing its own after the session's went quiet, and by the
323
+ // session's log alone that work never read as new.
324
+ let sizeBytes = info.size;
325
+ let modified = info.mtimeMs;
326
+ for (const log of await subagentLogPaths(session.dir)) {
327
+ try {
328
+ const agent = await stat(log);
329
+ sizeBytes += agent.size;
330
+ modified = Math.max(modified, agent.mtimeMs);
331
+ } catch {
332
+ continue;
333
+ }
334
+ }
137
335
  found.push({
138
336
  sessionId: session.sessionId,
139
337
  path: session.transcript,
140
- sizeBytes: info.size,
141
- modifiedAt: info.mtime,
338
+ sizeBytes,
339
+ modifiedAt: new Date(modified),
340
+ activeAt: info.mtime,
142
341
  cwd: session.cwd,
143
342
  });
144
343
  } catch {
@@ -146,20 +345,33 @@ async function discovered(sessions: readonly KimiSession[]): Promise<DiscoveredS
146
345
  }
147
346
  }
148
347
 
149
- found.sort((a, b) => b.modifiedAt.getTime() - a.modifiedAt.getTime());
348
+ found.sort((a, b) => lastActive(b) - lastActive(a));
150
349
  return found;
151
350
  }
152
351
 
153
- /** Every session on this machine, in no particular order. */
352
+ /** Every subagent's log in a session folder, whichever Kimi wrote it: `agents/<id>/` or `subagents/<id>/`. */
353
+ async function subagentLogPaths(dir: string): Promise<string[]> {
354
+ const logs: string[] = [];
355
+ for (const id of await subdirectories(join(dir, "agents"))) {
356
+ if (id !== "main") logs.push(join(dir, "agents", id, "wire.jsonl"));
357
+ }
358
+ for (const id of await subdirectories(join(dir, "subagents"))) logs.push(join(dir, "subagents", id, "wire.jsonl"));
359
+ return logs;
360
+ }
361
+
362
+ /** Every session on this machine, in every Kimi home, in no particular order. */
154
363
  async function allSessions(): Promise<KimiSession[]> {
155
- const root = kimiSessionsRoot();
156
364
  const found: KimiSession[] = [];
157
365
 
158
- for (const workspace of await subdirectories(root)) {
159
- const dir = join(root, workspace);
160
- for (const name of await subdirectories(dir)) {
161
- const session = await readSession(join(dir, name));
162
- if (session) found.push(session);
366
+ for (const home of kimiHomes()) {
367
+ const root = kimiSessionsRoot(home);
368
+ const known = await workspaces(home);
369
+ for (const workspace of await subdirectories(root)) {
370
+ const dir = join(root, workspace);
371
+ for (const name of await subdirectories(dir)) {
372
+ const session = await readSession(join(dir, name), known);
373
+ if (session) found.push(session);
374
+ }
163
375
  }
164
376
  }
165
377
 
@@ -168,61 +380,352 @@ async function allSessions(): Promise<KimiSession[]> {
168
380
 
169
381
  const BEGIN = "# isy:begin — managed by isy, do not edit inside this block";
170
382
  const END = "# isy:end";
383
+ /** What every hook isy writes asks for; Kimi CLI's SessionEnd hooks get five seconds whatever it says. */
384
+ const HOOK_TIMEOUT = 30;
385
+
386
+ /** A path as one word to a POSIX shell, whatever quotes or `$` it holds. */
387
+ function shellQuote(value: string): string {
388
+ return `'${value.replaceAll("'", "'\\''")}'`;
389
+ }
171
390
 
172
391
  function drainCommand(): string {
173
- const path = pendingAlertPath();
174
- return `if [ -s "${path}" ]; then cat "${path}"; : > "${path}"; fi`;
392
+ const path = shellQuote(pendingAlertPath());
393
+ return `if [ -s ${path} ]; then cat ${path}; : > ${path}; fi`;
394
+ }
395
+
396
+ /** Whether a home is Kimi Code's rather than the Python Kimi CLI's: they run hooks differently. */
397
+ function isKimiCodeHome(home: string): boolean {
398
+ return basename(home) === ".kimi-code" || home === process.env.KIMI_CODE_HOME;
175
399
  }
176
400
 
177
- function kimiHooks(): AgentHook[] {
401
+ /** The commands an older isy wrote for the upload, in any home. */
402
+ const OLDER_UPLOADS = [
403
+ "npx isy upload --hook",
404
+ "npx isy upload --hook --agent kimi",
405
+ "npx @nightloom/isy upload --hook --agent kimi",
406
+ ];
407
+
408
+ const START_COMMAND = "npx @nightloom/isy check --hook --agent kimi";
409
+ const KIMI_CLI_UPLOAD = "exec 3<&0; nohup npx @nightloom/isy upload --hook --agent kimi <&3 >/dev/null 2>&1 &";
410
+ const KIMI_CODE_UPLOAD = "npx @nightloom/isy upload --hook --agent kimi";
411
+
412
+ /**
413
+ * Every command an isy has written into a Kimi config, for either CLI — Kimi
414
+ * Code's migration copies Kimi CLI's hooks into its own config, so either
415
+ * CLI's can turn up in either home.
416
+ */
417
+ const ISY_COMMANDS = new Set([
418
+ START_COMMAND,
419
+ "npx isy check --hook --agent kimi",
420
+ KIMI_CLI_UPLOAD,
421
+ KIMI_CODE_UPLOAD,
422
+ ...OLDER_UPLOADS,
423
+ "npx isy upload --silent",
424
+ ]);
425
+
426
+ /** The drain of parked alerts, however an isy quoted the path to them. */
427
+ const DRAIN = /^if \[ -s .+ \]; then cat .+; : > .+; fi$/;
428
+
429
+ function isIsyCommand(command: string | undefined): boolean {
430
+ if (command === undefined) return false;
431
+ return ISY_COMMANDS.has(command) || (DRAIN.test(command) && command.includes("pending-alert"));
432
+ }
433
+
434
+ function kimiHooks(home = kimiHome()): AgentHook[] {
435
+ const start: AgentHook = {
436
+ event: "SessionStart",
437
+ command: START_COMMAND,
438
+ superseded: ["npx isy check --hook --agent kimi"],
439
+ };
440
+
441
+ if (!isKimiCodeHome(home)) {
442
+ return [
443
+ start,
444
+ // Kimi CLI gives the SessionEnd hooks five seconds between them, whatever
445
+ // `timeout` says, and kills what is still running — an upload is often
446
+ // not done by then. So the hook shell returns at once and the upload
447
+ // outlives it; the payload is handed over on fd 3 first, because a
448
+ // background job's stdin is /dev/null. Its session ids are bare UUIDs,
449
+ // like Claude's, so the command says which CLI it belongs to.
450
+ //
451
+ // No UserPromptSubmit drain here: Kimi CLI shows no hook's stdout at all,
452
+ // so draining parked alerts into it only threw them away.
453
+ //
454
+ // ponytail: POSIX. Kimi CLI runs hooks through the platform shell, cmd.exe
455
+ // on Windows, where this fails and the upload waits for the sweep at the
456
+ // next session start. A `cmd /c start /b` form is the way up if Windows
457
+ // users turn up on a CLI that is no longer released.
458
+ {
459
+ event: "SessionEnd",
460
+ command: KIMI_CLI_UPLOAD,
461
+ superseded: OLDER_UPLOADS,
462
+ },
463
+ ];
464
+ }
465
+
178
466
  return [
179
- {
180
- event: "SessionStart",
181
- command: "npx @nightloom/isy check --hook --agent kimi",
182
- superseded: ["npx isy check --hook --agent kimi"],
183
- },
184
- // Kimi 0.38 sends no `client_type`, so the hook says who fired it.
467
+ start,
468
+ // Kimi Code 0.38 sends no `client_type`, so the hook says who fired it.
185
469
  {
186
470
  event: "SessionEnd",
187
- command: "npx @nightloom/isy upload --hook --agent kimi",
188
- superseded: ["npx isy upload --hook", "npx isy upload --hook --agent kimi"],
471
+ command: KIMI_CODE_UPLOAD,
472
+ superseded: OLDER_UPLOADS.slice(0, 2),
189
473
  },
190
- // SessionStart and SessionEnd are observation-only in Kimi and their stdout
191
- // is discarded, so an alert that could not reach the terminal directly is
192
- // parked in a file. UserPromptSubmit *is* blockable, so its stdout is shown:
193
- // this drains the backlog. Kept as shell — it runs on every prompt, and
194
- // `npx @nightloom/isy` would add ~380ms of node startup to each one.
474
+ // SessionStart and SessionEnd are observation-only in Kimi Code and their
475
+ // stdout is discarded, so an alert that could not reach the terminal
476
+ // directly is parked in a file. UserPromptSubmit *is* blockable, so its
477
+ // stdout is shown: this drains the backlog. Kept as shell — it runs on every
478
+ // prompt, and `npx @nightloom/isy` would add ~380ms of node startup to each one.
195
479
  { event: "UserPromptSubmit", command: drainCommand() },
196
480
  ];
197
481
  }
198
482
 
199
- function managedBlock(): string {
200
- const entries = kimiHooks()
201
- .map((hook) => `[[hooks]]\nevent = "${hook.event}"\ncommand = '${hook.command}'\ntimeout = 30`)
483
+ /** isy's hooks for one home, as the block `installHooks` writes. */
484
+ function managedBlock(home: string): string {
485
+ // Basic strings, escaped: a literal string cannot hold a `'`, and the drain
486
+ // carries a path that can.
487
+ const entries = kimiHooks(home)
488
+ .map(
489
+ (hook) =>
490
+ `[[hooks]]\nevent = ${basicString(hook.event)}\ncommand = ${basicString(hook.command)}\ntimeout = ${HOOK_TIMEOUT}`,
491
+ )
202
492
  .join("\n\n");
203
493
  return `${BEGIN}\n${entries}\n${END}`;
204
494
  }
205
495
 
206
- async function readConfigToml(): Promise<string> {
496
+ /**
497
+ * isy's hook tables in a config: every one whose command an isy wrote, wherever
498
+ * it stands. Not the tables between isy's markers — a Kimi rewrite drops the
499
+ * markers, and a block that lost its end marker would take the user's own
500
+ * hooks after it along.
501
+ */
502
+ function isyTables(contents: string): HookTable[] {
503
+ return hookTables(contents).filter((table) => isIsyCommand(table.command));
504
+ }
505
+
506
+ /** isy's marker comment lines, as `[start, stop)` offsets, newline included. */
507
+ function markerLines(contents: string): { start: number; stop: number }[] {
508
+ const lines: { start: number; stop: number }[] = [];
509
+ let start = 0;
510
+ while (start < contents.length) {
511
+ const newline = contents.indexOf("\n", start);
512
+ const stop = newline < 0 ? contents.length : newline + 1;
513
+ const line = contents.slice(start, stop).trim();
514
+ if (line === BEGIN || line === END) lines.push({ start, stop });
515
+ start = stop;
516
+ }
517
+ return lines;
518
+ }
519
+
520
+ /** Whether a home's config holds isy's hooks exactly as they should be, and nothing an older isy left. */
521
+ function upToDate(ours: readonly HookTable[], desired: readonly AgentHook[]): boolean {
522
+ return (
523
+ ours.length === desired.length &&
524
+ desired.every((hook) =>
525
+ ours.some((table) => table.event === hook.event && table.command === hook.command && table.timeout === HOOK_TIMEOUT),
526
+ )
527
+ );
528
+ }
529
+
530
+ /**
531
+ * The config with isy's tables and markers cut out and `block` written where
532
+ * the first of them stood — at the end when there were none, and nowhere when
533
+ * `block` is undefined. What lies between isy's tables stays unless it is
534
+ * blank: an older isy's block cut short had the user's `[ui]` after it.
535
+ */
536
+ function withBlock(contents: string, block: string | undefined): string {
537
+ const cuts = [...isyTables(contents), ...markerLines(contents)].sort((a, b) => a.start - b.start);
538
+ const merged: { start: number; stop: number }[] = [];
539
+ for (const cut of cuts) {
540
+ const last = merged.at(-1);
541
+ if (last && contents.slice(last.stop, cut.start).trim() === "") last.stop = Math.max(last.stop, cut.stop);
542
+ else merged.push({ start: cut.start, stop: cut.stop });
543
+ }
544
+
545
+ // A cut leaves the blank lines on both sides of it: one is enough.
546
+ const join = (before: string, after: string): string =>
547
+ before.length === 0 || before.endsWith("\n\n") ? before + after.replace(/^\n+/, "") : before + after;
548
+
549
+ let rest = "";
550
+ let at: number | undefined;
551
+ let from = 0;
552
+ for (const cut of merged) {
553
+ rest = join(rest, contents.slice(from, cut.start));
554
+ at ??= rest.length;
555
+ from = cut.stop;
556
+ }
557
+ rest = join(rest, contents.slice(from));
558
+ if (block === undefined) return rest;
559
+
560
+ if (at === undefined) {
561
+ const separator = rest.length === 0 || rest.endsWith("\n\n") ? "" : rest.endsWith("\n") ? "\n" : "\n\n";
562
+ return `${rest}${separator}${block}\n`;
563
+ }
564
+ const before = rest.slice(0, at);
565
+ const after = rest.slice(at);
566
+ const lead = before.length === 0 || before.endsWith("\n\n") ? "" : before.endsWith("\n") ? "\n" : "\n\n";
567
+ const trail = after.length === 0 || after.startsWith("\n") ? "" : "\n";
568
+ return `${before}${lead}${block}\n${trail}${after}`;
569
+ }
570
+
571
+ async function readConfigToml(home = kimiHome()): Promise<string> {
572
+ try {
573
+ return await readFile(kimiConfigPath(home), "utf8");
574
+ } catch (error) {
575
+ // No config yet is an empty one. Anything else is a config that is there
576
+ // and could not be read this time — read as empty, installing over it
577
+ // wrote away every setting in it.
578
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return "";
579
+ throw error;
580
+ }
581
+ }
582
+
583
+ /** The lines of Kimi CLI's log that open a session's run, and the ones worth reading in it. */
584
+ const RUN_OPENS = /\|\s+-\s+(?:Created new session|Continuing previous session|Resuming session): (\S+)/;
585
+ const RUN_MODEL = /\|\s+-\s+Using LLM model: .*?\bmodel='([^']+)'/;
586
+ const RUN_AGENT = /\|\s+-\s+Loading agent: (.+)$/;
587
+
588
+ /**
589
+ * The Kimi CLI version and the model a session last ran with.
590
+ *
591
+ * Neither is in the session: not in `state.json`, not in either log. Kimi CLI's
592
+ * own log (`<home>/logs/kimi.log`, rotated daily, kept ten days) says both, run
593
+ * by run — `Created new session: <id>`, then `Using LLM model: … model='…'` and
594
+ * `Loading agent: <site-packages>/kimi_cli/agents/…`, whose `kimi_cli-<version>.dist-info`
595
+ * beside it names the version installed. The last run of the session wins: a
596
+ * resumed session runs on whatever was configured the day it resumed.
597
+ *
598
+ * ponytail: the version is the package installed now, so a session last run
599
+ * before an upgrade reports the upgrade. Only reachable while the log keeps the
600
+ * run; older sessions go up without either, rather than with a guess.
601
+ */
602
+ async function kimiRuntime(home: string, sessionId: string): Promise<{ version?: string; model?: string }> {
603
+ const dir = join(home, "logs");
604
+ let files: { path: string; modified: number }[] = [];
207
605
  try {
208
- return await readFile(kimiConfigPath(), "utf8");
606
+ for (const name of await readdir(dir)) {
607
+ if (!name.endsWith(".log")) continue;
608
+ const path = join(dir, name);
609
+ files.push({ path, modified: (await stat(path)).mtimeMs });
610
+ }
209
611
  } catch {
210
- return "";
612
+ return {};
211
613
  }
614
+ files = files.sort((a, b) => b.modified - a.modified);
615
+
616
+ for (const { path } of files) {
617
+ let text: string;
618
+ try {
619
+ text = await readFile(path, "utf8");
620
+ } catch {
621
+ continue;
622
+ }
623
+ if (!text.includes(sessionId)) continue;
624
+
625
+ let run: Run | undefined;
626
+ let last: Run | undefined;
627
+ for (const line of text.split("\n")) {
628
+ const opens = RUN_OPENS.exec(line);
629
+ if (opens) {
630
+ const next: Run = { session: opens[1]!, at: Date.parse(line.slice(0, 23).replace(" ", "T")) };
631
+ // Two processes started together write into the one log at once, and
632
+ // the lines that open a run name no session and no process. A run
633
+ // opening before the one before it named its model leaves the lines
634
+ // after both impossible to tell apart: neither run gets them, rather
635
+ // than one getting the other's.
636
+ if (run && run.model === undefined && next.at - run.at < RUNS_OVERLAP_MS) {
637
+ run.tangled = true;
638
+ next.tangled = true;
639
+ }
640
+ run = next;
641
+ if (run.session === sessionId) last = run;
642
+ continue;
643
+ }
644
+ if (!run || run.tangled) continue;
645
+ run.model ??= RUN_MODEL.exec(line)?.[1];
646
+ run.agent ??= RUN_AGENT.exec(line)?.[1];
647
+ }
648
+ if (last?.tangled) return {};
649
+ if (last) return { model: last.model, version: last.agent ? await installedVersion(last.agent) : undefined };
650
+ }
651
+ return {};
652
+ }
653
+
654
+ /** One run as Kimi CLI's log opened it: which session, when, and what it read out after. */
655
+ interface Run {
656
+ session: string;
657
+ at: number;
658
+ model?: string;
659
+ agent?: string;
660
+ /** Opened alongside another run, so that the lines after it could be either's. */
661
+ tangled?: boolean;
662
+ }
663
+
664
+ /** How far apart two runs can open and still write the lines after them in turn: one names its model within a second. */
665
+ const RUNS_OVERLAP_MS = 10_000;
666
+
667
+ /** `1.52.0` for an agent file under `…/site-packages/kimi_cli/agents/`, from the dist-info beside the package. */
668
+ async function installedVersion(agentFile: string): Promise<string | undefined> {
669
+ const at = agentFile.lastIndexOf("/kimi_cli/");
670
+ if (at < 0) return undefined;
671
+ try {
672
+ for (const name of await readdir(agentFile.slice(0, at))) {
673
+ const found = /^kimi_cli-(.+)\.dist-info$/.exec(name);
674
+ if (found) return found[1];
675
+ }
676
+ } catch {
677
+ return undefined;
678
+ }
679
+ return undefined;
212
680
  }
213
681
 
214
682
  /**
215
- * One session as Claude-shaped record lines. context.jsonl is the surviving
216
- * conversation; wire.jsonl, when present, still holds turns a rewind discarded.
683
+ * The Kimi Code version installed now, from the npm package the `kimi` on PATH
684
+ * belongs to. Like Kimi CLI, Kimi Code writes its version into no session
685
+ * file, and it keeps no log that names it.
686
+ *
687
+ * ponytail: the standalone build (`~/.kimi-code/bin/kimi`, from Kimi's install
688
+ * script) is one binary with no manifest beside it, so its sessions go up
689
+ * without a version. `kimi --version` would say, at the cost of a process on
690
+ * every upload.
217
691
  */
692
+ async function kimiCodeVersion(): Promise<string | undefined> {
693
+ for (const dir of (process.env.PATH ?? "").split(delimiter)) {
694
+ if (!dir) continue;
695
+ let file: string;
696
+ try {
697
+ file = await realpath(join(dir, "kimi"));
698
+ // What a shell runs is the first `kimi` that is a file it may execute: a
699
+ // folder of that name, or a file without the bit, is passed over.
700
+ if (!(await stat(file)).isFile()) continue;
701
+ await access(file, constants.X_OK);
702
+ } catch {
703
+ continue;
704
+ }
705
+ // The first `kimi` on PATH is the one that runs: `<package>/dist/main.mjs` for npm.
706
+ for (let at = dirname(file), depth = 0; depth < 3; at = dirname(at), depth += 1) {
707
+ try {
708
+ const manifest: unknown = JSON.parse(await readFile(join(at, "package.json"), "utf8"));
709
+ if (isObject(manifest) && manifest.name === "@moonshot-ai/kimi-code" && typeof manifest.version === "string") {
710
+ return manifest.version;
711
+ }
712
+ } catch {
713
+ continue;
714
+ }
715
+ }
716
+ return undefined;
717
+ }
718
+ return undefined;
719
+ }
720
+
218
721
  /**
219
- * The session id for a transcript path. `wire.jsonl` sits two levels below the
220
- * session folder (`<session>/agents/main/wire.jsonl`), `context.jsonl` sits
221
- * directly in it, so the folder to name the session after differs by layout.
722
+ * The session folder for a transcript path. Kimi Code's `wire.jsonl` sits two
723
+ * levels below it (`<session>/agents/<name>/wire.jsonl`); Kimi CLI's `wire.jsonl`
724
+ * and every `context.jsonl` sit directly in it.
222
725
  */
223
726
  function sessionDirFor(path: string): string {
224
727
  const dir = dirname(path);
225
- return basename(path) === "wire.jsonl" ? dirname(dirname(dir)) : dir;
728
+ return basename(path) === "wire.jsonl" && basename(dirname(dir)) === "agents" ? dirname(dirname(dir)) : dir;
226
729
  }
227
730
 
228
731
  /**
@@ -239,12 +742,26 @@ async function kimiRecords(path: string, given?: string): Promise<string[]> {
239
742
  const dir = sessionDirFor(path);
240
743
  const state = await readState(dir);
241
744
  const sessionId = sessionIdOf(state, dir);
242
- const cwd = given ?? recordedCwd(state);
243
-
244
- // Newer builds keep the whole session as one event log and write no
245
- // `context.jsonl` at all. The first line says which format this is.
745
+ const cwd = given ?? (await cwdOfSession(dir, state));
746
+
747
+ // Kimi CLI's event log and Kimi Code's open with the same metadata header, so
748
+ // the events after it decide which reader this is.
749
+ if (isKimiCliWire(lines.slice(0, 3))) {
750
+ const runtime = await kimiRuntime(dirname(dirname(dirname(dir))), sessionId);
751
+ const subagents = await kimiCliSubagentLogs(dir);
752
+ return kimiCliWireToClaudeRecords(lines, { sessionId, cwd, ...runtime, subagents });
753
+ }
246
754
  if (isKimiWireTranscript(lines[0] ?? "")) {
247
- return wireToClaudeRecords(lines, { sessionId, cwd });
755
+ // A subagent's own log, asked about alone, is all there is to read.
756
+ const subagents = basename(dirname(path)) === "main" ? await subagentLogs(dir, state ?? {}) : undefined;
757
+ const copied = copiedUntil(state);
758
+ return wireToClaudeRecords(lines, {
759
+ sessionId,
760
+ cwd,
761
+ version: await kimiCodeVersion(),
762
+ subagents,
763
+ ...(copied !== undefined ? { copiedUntil: copied } : {}),
764
+ });
248
765
  }
249
766
 
250
767
  let wire: string[] | undefined;
@@ -270,11 +787,14 @@ export const kimiAgent: Agent = {
270
787
  }
271
788
  },
272
789
 
790
+ // Every home gets hooks, so every home's config is where they went.
273
791
  configLocation(): string {
274
- return kimiConfigPath();
792
+ return kimiHomes()
793
+ .map((home) => kimiConfigPath(home))
794
+ .join(" and ");
275
795
  },
276
796
 
277
- hooks: kimiHooks,
797
+ hooks: allKimiHooks,
278
798
 
279
799
  // Sessions are found by reading each one's cwd, not by deriving a path, so
280
800
  // there is no per-directory folder to name. The root is what must be readable.
@@ -302,7 +822,8 @@ export const kimiAgent: Agent = {
302
822
  },
303
823
 
304
824
  async cwdOf(path: string): Promise<string | undefined> {
305
- return recordedCwd(await readState(sessionDirFor(path)));
825
+ const dir = sessionDirFor(path);
826
+ return cwdOfSession(dir, await readState(dir));
306
827
  },
307
828
 
308
829
  // Kimi's hook payload carries no transcript path, so compose it from the
@@ -326,46 +847,58 @@ export const kimiAgent: Agent = {
326
847
  return redactLines(records, { extraPatterns: options.extraPatterns, cwd: options.cwd }).lines;
327
848
  },
328
849
 
850
+ // Every Kimi home gets its own hooks, as its CLI runs them: a hook counts as
851
+ // installed only when every home that should have it does.
329
852
  async hooksInstalled(): Promise<string[]> {
330
- const contents = await readConfigToml();
331
- return kimiHooks()
332
- .filter((hook) => [hook.command, ...(hook.superseded ?? [])].some((command) => contents.includes(command)))
333
- .map((hook) => hook.event);
853
+ const missing = new Set<string>();
854
+ for (const home of kimiHomes()) {
855
+ const tables = hookTables(await readConfigToml(home));
856
+ for (const hook of kimiHooks(home)) {
857
+ if (!tables.some((table) => table.event === hook.event && table.command === hook.command)) missing.add(hook.event);
858
+ }
859
+ }
860
+ return allKimiHooks()
861
+ .map((hook) => hook.event)
862
+ .filter((event) => !missing.has(event));
334
863
  },
335
864
 
336
865
  async installHooks(): Promise<"installed" | "already-present"> {
337
- const contents = await readConfigToml();
338
- const desired = managedBlock();
339
-
340
- const start = contents.indexOf(BEGIN);
341
- if (start >= 0) {
342
- const stop = contents.indexOf(END, start);
343
- const existing = stop >= 0 ? contents.slice(start, stop + END.length) : undefined;
344
- if (existing === desired) return "already-present";
345
- if (existing !== undefined) {
346
- // An older isy wrote different commands for the same job: replace them.
347
- await writeConfigToml(contents.replace(existing, desired));
348
- return "installed";
349
- }
866
+ let changed = false;
867
+ for (const home of kimiHomes()) {
868
+ const contents = await readConfigToml(home);
869
+ if (upToDate(isyTables(contents), kimiHooks(home))) continue;
870
+ // An older isy wrote different commands for the same job, a Kimi rewrite
871
+ // dropped the markers, or the migration copied the other CLI's hooks in:
872
+ // one block, where the first of isy's tables stood.
873
+ await writeConfigToml(home, withBlock(contents, managedBlock(home)));
874
+ changed = true;
350
875
  }
876
+ return changed ? "installed" : "already-present";
877
+ },
351
878
 
352
- const separator = contents.length === 0 || contents.endsWith("\n") ? "" : "\n";
353
- await writeConfigToml(`${contents}${separator}${contents.length > 0 ? "\n" : ""}${desired}\n`);
354
- return "installed";
879
+ // Only homes where an isy already wrote hooks: a home the reader left
880
+ // without them stays that way.
881
+ async repairHooks(): Promise<boolean> {
882
+ let changed = false;
883
+ for (const home of kimiHomes()) {
884
+ const contents = await readConfigToml(home);
885
+ const ours = isyTables(contents);
886
+ if (ours.length === 0 || upToDate(ours, kimiHooks(home))) continue;
887
+ await writeConfigToml(home, withBlock(contents, managedBlock(home)));
888
+ changed = true;
889
+ }
890
+ return changed;
355
891
  },
356
892
 
357
893
  async removeHooks(): Promise<"removed" | "absent"> {
358
- const contents = await readConfigToml();
359
- const start = contents.indexOf(BEGIN);
360
- if (start < 0) return "absent";
361
-
362
- const stop = contents.indexOf(END, start);
363
- if (stop < 0) return "absent";
364
-
365
- const before = contents.slice(0, start).replace(/\n+$/, "\n");
366
- const after = contents.slice(stop + END.length).replace(/^\n+/, "");
367
- await writeConfigToml(`${before}${after}`);
368
- return "removed";
894
+ let removed = false;
895
+ for (const home of kimiHomes()) {
896
+ const contents = await readConfigToml(home);
897
+ if (isyTables(contents).length === 0 && markerLines(contents).length === 0) continue;
898
+ await writeConfigToml(home, withBlock(contents, undefined));
899
+ removed = true;
900
+ }
901
+ return removed ? "removed" : "absent";
369
902
  },
370
903
 
371
904
  // Kimi discards hook stdout on the events we care about, so write straight to
@@ -384,7 +917,14 @@ export const kimiAgent: Agent = {
384
917
  },
385
918
  };
386
919
 
387
- async function writeConfigToml(contents: string): Promise<void> {
388
- await mkdir(kimiHome(), { recursive: true });
389
- await writeFile(kimiConfigPath(), contents, "utf8");
920
+ async function writeConfigToml(home: string, contents: string): Promise<void> {
921
+ await mkdir(home, { recursive: true });
922
+ await writeFile(kimiConfigPath(home), contents, "utf8");
923
+ }
924
+
925
+ /** Every hook some Kimi home on this machine takes, once per event. */
926
+ function allKimiHooks(): AgentHook[] {
927
+ const byEvent = new Map<string, AgentHook>();
928
+ for (const home of kimiHomes()) for (const hook of kimiHooks(home)) if (!byEvent.has(hook.event)) byEvent.set(hook.event, hook);
929
+ return [...byEvent.values()];
390
930
  }