@nightloom/isy 1.0.1 → 1.0.2

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