@nightloom/isy 1.0.0

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 (223) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +69 -0
  3. package/dist/agents/claude.d.ts +6 -0
  4. package/dist/agents/claude.js +66 -0
  5. package/dist/agents/claude.js.map +1 -0
  6. package/dist/agents/codex-records.d.ts +34 -0
  7. package/dist/agents/codex-records.js +492 -0
  8. package/dist/agents/codex-records.js.map +1 -0
  9. package/dist/agents/codex.d.ts +5 -0
  10. package/dist/agents/codex.js +205 -0
  11. package/dist/agents/codex.js.map +1 -0
  12. package/dist/agents/index.d.ts +25 -0
  13. package/dist/agents/index.js +50 -0
  14. package/dist/agents/index.js.map +1 -0
  15. package/dist/agents/kimi-records.d.ts +24 -0
  16. package/dist/agents/kimi-records.js +252 -0
  17. package/dist/agents/kimi-records.js.map +1 -0
  18. package/dist/agents/kimi-wire.d.ts +8 -0
  19. package/dist/agents/kimi-wire.js +158 -0
  20. package/dist/agents/kimi-wire.js.map +1 -0
  21. package/dist/agents/kimi.d.ts +6 -0
  22. package/dist/agents/kimi.js +332 -0
  23. package/dist/agents/kimi.js.map +1 -0
  24. package/dist/agents/types.d.ts +83 -0
  25. package/dist/agents/types.js +2 -0
  26. package/dist/agents/types.js.map +1 -0
  27. package/dist/alert.d.ts +24 -0
  28. package/dist/alert.js +68 -0
  29. package/dist/alert.js.map +1 -0
  30. package/dist/api.d.ts +103 -0
  31. package/dist/api.js +171 -0
  32. package/dist/api.js.map +1 -0
  33. package/dist/commands/analyze.d.ts +61 -0
  34. package/dist/commands/analyze.js +198 -0
  35. package/dist/commands/analyze.js.map +1 -0
  36. package/dist/commands/check.d.ts +55 -0
  37. package/dist/commands/check.js +180 -0
  38. package/dist/commands/check.js.map +1 -0
  39. package/dist/commands/commit.d.ts +26 -0
  40. package/dist/commands/commit.js +130 -0
  41. package/dist/commands/commit.js.map +1 -0
  42. package/dist/commands/health.d.ts +47 -0
  43. package/dist/commands/health.js +366 -0
  44. package/dist/commands/health.js.map +1 -0
  45. package/dist/commands/init.d.ts +3 -0
  46. package/dist/commands/init.js +173 -0
  47. package/dist/commands/init.js.map +1 -0
  48. package/dist/commands/logout.d.ts +1 -0
  49. package/dist/commands/logout.js +30 -0
  50. package/dist/commands/logout.js.map +1 -0
  51. package/dist/commands/notes.d.ts +11 -0
  52. package/dist/commands/notes.js +49 -0
  53. package/dist/commands/notes.js.map +1 -0
  54. package/dist/commands/scan.d.ts +47 -0
  55. package/dist/commands/scan.js +199 -0
  56. package/dist/commands/scan.js.map +1 -0
  57. package/dist/commands/settings.d.ts +15 -0
  58. package/dist/commands/settings.js +94 -0
  59. package/dist/commands/settings.js.map +1 -0
  60. package/dist/commands/status.d.ts +61 -0
  61. package/dist/commands/status.js +151 -0
  62. package/dist/commands/status.js.map +1 -0
  63. package/dist/commands/upload.d.ts +42 -0
  64. package/dist/commands/upload.js +429 -0
  65. package/dist/commands/upload.js.map +1 -0
  66. package/dist/config.d.ts +4 -0
  67. package/dist/config.js +32 -0
  68. package/dist/config.js.map +1 -0
  69. package/dist/detectors.d.ts +43 -0
  70. package/dist/detectors.js +1026 -0
  71. package/dist/detectors.js.map +1 -0
  72. package/dist/git.d.ts +22 -0
  73. package/dist/git.js +68 -0
  74. package/dist/git.js.map +1 -0
  75. package/dist/githook.d.ts +71 -0
  76. package/dist/githook.js +238 -0
  77. package/dist/githook.js.map +1 -0
  78. package/dist/hook.d.ts +39 -0
  79. package/dist/hook.js +173 -0
  80. package/dist/hook.js.map +1 -0
  81. package/dist/index.d.ts +2 -0
  82. package/dist/index.js +205 -0
  83. package/dist/index.js.map +1 -0
  84. package/dist/log.d.ts +19 -0
  85. package/dist/log.js +97 -0
  86. package/dist/log.js.map +1 -0
  87. package/dist/mask-paths.d.ts +75 -0
  88. package/dist/mask-paths.js +364 -0
  89. package/dist/mask-paths.js.map +1 -0
  90. package/dist/pairing.d.ts +60 -0
  91. package/dist/pairing.js +137 -0
  92. package/dist/pairing.js.map +1 -0
  93. package/dist/parser.d.ts +48 -0
  94. package/dist/parser.js +516 -0
  95. package/dist/parser.js.map +1 -0
  96. package/dist/paths.d.ts +41 -0
  97. package/dist/paths.js +181 -0
  98. package/dist/paths.js.map +1 -0
  99. package/dist/plan.d.ts +25 -0
  100. package/dist/plan.js +39 -0
  101. package/dist/plan.js.map +1 -0
  102. package/dist/queue.d.ts +26 -0
  103. package/dist/queue.js +120 -0
  104. package/dist/queue.js.map +1 -0
  105. package/dist/redact.d.ts +29 -0
  106. package/dist/redact.js +254 -0
  107. package/dist/redact.js.map +1 -0
  108. package/dist/spawn.d.ts +13 -0
  109. package/dist/spawn.js +32 -0
  110. package/dist/spawn.js.map +1 -0
  111. package/dist/stage0.d.ts +20 -0
  112. package/dist/stage0.js +90 -0
  113. package/dist/stage0.js.map +1 -0
  114. package/dist/state.d.ts +84 -0
  115. package/dist/state.js +150 -0
  116. package/dist/state.js.map +1 -0
  117. package/dist/test/analyze.test.d.ts +1 -0
  118. package/dist/test/analyze.test.js +408 -0
  119. package/dist/test/analyze.test.js.map +1 -0
  120. package/dist/test/check.test.d.ts +1 -0
  121. package/dist/test/check.test.js +193 -0
  122. package/dist/test/check.test.js.map +1 -0
  123. package/dist/test/cli.test.d.ts +1 -0
  124. package/dist/test/cli.test.js +132 -0
  125. package/dist/test/cli.test.js.map +1 -0
  126. package/dist/test/codex.test.d.ts +1 -0
  127. package/dist/test/codex.test.js +585 -0
  128. package/dist/test/codex.test.js.map +1 -0
  129. package/dist/test/commit.test.d.ts +1 -0
  130. package/dist/test/commit.test.js +430 -0
  131. package/dist/test/commit.test.js.map +1 -0
  132. package/dist/test/git.test.d.ts +1 -0
  133. package/dist/test/git.test.js +75 -0
  134. package/dist/test/git.test.js.map +1 -0
  135. package/dist/test/health.test.d.ts +1 -0
  136. package/dist/test/health.test.js +156 -0
  137. package/dist/test/health.test.js.map +1 -0
  138. package/dist/test/hook.test.d.ts +1 -0
  139. package/dist/test/hook.test.js +144 -0
  140. package/dist/test/hook.test.js.map +1 -0
  141. package/dist/test/kimi.test.d.ts +1 -0
  142. package/dist/test/kimi.test.js +349 -0
  143. package/dist/test/kimi.test.js.map +1 -0
  144. package/dist/test/mask-paths.test.d.ts +1 -0
  145. package/dist/test/mask-paths.test.js +230 -0
  146. package/dist/test/mask-paths.test.js.map +1 -0
  147. package/dist/test/notes.test.d.ts +1 -0
  148. package/dist/test/notes.test.js +41 -0
  149. package/dist/test/notes.test.js.map +1 -0
  150. package/dist/test/pairing.test.d.ts +1 -0
  151. package/dist/test/pairing.test.js +138 -0
  152. package/dist/test/pairing.test.js.map +1 -0
  153. package/dist/test/parser.test.d.ts +1 -0
  154. package/dist/test/parser.test.js +312 -0
  155. package/dist/test/parser.test.js.map +1 -0
  156. package/dist/test/plan.test.d.ts +1 -0
  157. package/dist/test/plan.test.js +34 -0
  158. package/dist/test/plan.test.js.map +1 -0
  159. package/dist/test/redact.test.d.ts +1 -0
  160. package/dist/test/redact.test.js +303 -0
  161. package/dist/test/redact.test.js.map +1 -0
  162. package/dist/test/settings.test.d.ts +1 -0
  163. package/dist/test/settings.test.js +32 -0
  164. package/dist/test/settings.test.js.map +1 -0
  165. package/dist/test/stage0.test.d.ts +1 -0
  166. package/dist/test/stage0.test.js +607 -0
  167. package/dist/test/stage0.test.js.map +1 -0
  168. package/dist/test/sweep.test.d.ts +1 -0
  169. package/dist/test/sweep.test.js +298 -0
  170. package/dist/test/sweep.test.js.map +1 -0
  171. package/dist/test/update.test.d.ts +1 -0
  172. package/dist/test/update.test.js +26 -0
  173. package/dist/test/update.test.js.map +1 -0
  174. package/dist/test/upload.test.d.ts +1 -0
  175. package/dist/test/upload.test.js +331 -0
  176. package/dist/test/upload.test.js.map +1 -0
  177. package/dist/types.d.ts +142 -0
  178. package/dist/types.js +2 -0
  179. package/dist/types.js.map +1 -0
  180. package/dist/update.d.ts +17 -0
  181. package/dist/update.js +46 -0
  182. package/dist/update.js.map +1 -0
  183. package/package.json +60 -0
  184. package/src/agents/claude.ts +89 -0
  185. package/src/agents/codex-records.ts +533 -0
  186. package/src/agents/codex.ts +238 -0
  187. package/src/agents/index.ts +58 -0
  188. package/src/agents/kimi-records.ts +274 -0
  189. package/src/agents/kimi-wire.ts +179 -0
  190. package/src/agents/kimi.ts +390 -0
  191. package/src/agents/types.ts +92 -0
  192. package/src/alert.ts +68 -0
  193. package/src/api.ts +269 -0
  194. package/src/commands/analyze.ts +308 -0
  195. package/src/commands/check.ts +239 -0
  196. package/src/commands/commit.ts +179 -0
  197. package/src/commands/health.ts +444 -0
  198. package/src/commands/init.ts +186 -0
  199. package/src/commands/logout.ts +33 -0
  200. package/src/commands/notes.ts +57 -0
  201. package/src/commands/scan.ts +278 -0
  202. package/src/commands/settings.ts +107 -0
  203. package/src/commands/status.ts +236 -0
  204. package/src/commands/upload.ts +524 -0
  205. package/src/config.ts +33 -0
  206. package/src/detectors.ts +1138 -0
  207. package/src/git.ts +86 -0
  208. package/src/githook.ts +269 -0
  209. package/src/hook.ts +237 -0
  210. package/src/index.ts +229 -0
  211. package/src/log.ts +113 -0
  212. package/src/mask-paths.ts +434 -0
  213. package/src/pairing.ts +190 -0
  214. package/src/parser.ts +581 -0
  215. package/src/paths.ts +191 -0
  216. package/src/plan.ts +56 -0
  217. package/src/queue.ts +145 -0
  218. package/src/redact.ts +335 -0
  219. package/src/spawn.ts +33 -0
  220. package/src/stage0.ts +121 -0
  221. package/src/state.ts +208 -0
  222. package/src/types.ts +165 -0
  223. package/src/update.ts +46 -0
@@ -0,0 +1,238 @@
1
+ import type { Dirent } from "node:fs";
2
+ import { access, readFile, readdir, stat } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { basename, join } from "node:path";
5
+ import { parkAlert, withParkedAlerts } from "../alert.js";
6
+ import { installHookIn, installedHooksIn, removeHookIn } from "../hook.js";
7
+ import type { HookFile } from "../hook.js";
8
+ import { parseLines } from "../parser.js";
9
+ import { firstLine } from "../paths.js";
10
+ import { redactLines } from "../redact.js";
11
+ import type { ParsedSession, SessionFile } from "../types.js";
12
+ import { toClaudeRecords } from "./codex-records.js";
13
+ import type { Agent, AgentHook, HookInput } from "./types.js";
14
+
15
+ export function codexHome(): string {
16
+ return process.env.CODEX_HOME ?? join(homedir(), ".codex");
17
+ }
18
+
19
+ export function codexHooksPath(): string {
20
+ return join(codexHome(), "hooks.json");
21
+ }
22
+
23
+ export function codexSessionsDir(): string {
24
+ return join(codexHome(), "sessions");
25
+ }
26
+
27
+ /**
28
+ * Codex files sessions by date (`sessions/2026/08/20/rollout-<time>-<id>.jsonl`)
29
+ * with no index by working directory, so finding a project's sessions means
30
+ * opening rollouts and reading the `cwd` off their first line. Newest first,
31
+ * and only this many are looked at.
32
+ *
33
+ * ponytail: linear scan capped at the newest rollouts; build an index if a
34
+ * machine ever has enough sessions for this to show up.
35
+ */
36
+ const SCAN_LIMIT = 500;
37
+
38
+ const ROLLOUT_ID = /^rollout-.*?-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
39
+
40
+ function codexHooks(): AgentHook[] {
41
+ // Codex's hook payload is field-for-field Claude Code's, so the agent cannot
42
+ // be told from the payload: these say which CLI they belong to outright.
43
+ return [
44
+ {
45
+ event: "SessionStart",
46
+ command: "npx @nightloom/isy check --hook --agent codex",
47
+ superseded: ["npx isy check --hook --agent codex"],
48
+ },
49
+ {
50
+ event: "SessionEnd",
51
+ // Detached on purpose. An upload has a 30s budget of its own, and Codex
52
+ // is tearing the session down while this runs, so the hook shell returns
53
+ // at once and the upload outlives it. A background job's stdin is
54
+ // /dev/null, so the payload is handed over on fd 3 first: without it the
55
+ // upload took the newest rollout in the cwd, which is the wrong session
56
+ // whenever two share a directory.
57
+ //
58
+ // ponytail: POSIX `&`, so no Windows. Codex's own `commandWindows`
59
+ // override is the way up if anyone runs ISY there.
60
+ command: "exec 3<&0; nohup npx @nightloom/isy upload --hook --agent codex <&3 >/dev/null 2>&1 &",
61
+ superseded: [
62
+ "npx isy upload --hook --agent codex",
63
+ "nohup npx isy upload --hook --agent codex >/dev/null 2>&1 </dev/null &",
64
+ "exec 3<&0; nohup npx isy upload --hook --agent codex <&3 >/dev/null 2>&1 &",
65
+ ],
66
+ },
67
+ ];
68
+ }
69
+
70
+ function hookFile(): HookFile {
71
+ return { path: codexHooksPath(), hooks: codexHooks() };
72
+ }
73
+
74
+ /** Every rollout file on this machine, newest first. */
75
+ async function rolloutPaths(): Promise<string[]> {
76
+ // The tree is sessions/YYYY/MM/DD and rollout names open with an ISO
77
+ // timestamp, so sorting names descending at every level is chronological.
78
+ // Depth is not assumed: any directory under the root is walked.
79
+ const descend = async (dir: string): Promise<string[]> => {
80
+ let entries: Dirent[];
81
+ try {
82
+ entries = await readdir(dir, { withFileTypes: true });
83
+ } catch {
84
+ return [];
85
+ }
86
+
87
+ const names = (keep: (entry: Dirent) => boolean): string[] =>
88
+ entries.filter(keep).map((entry) => entry.name).sort().reverse();
89
+
90
+ const found = names(
91
+ (entry) => entry.isFile() && entry.name.startsWith("rollout-") && entry.name.endsWith(".jsonl"),
92
+ ).map((name) => join(dir, name));
93
+
94
+ for (const name of names((entry) => entry.isDirectory())) {
95
+ found.push(...(await descend(join(dir, name))));
96
+ }
97
+ return found;
98
+ };
99
+
100
+ return descend(codexSessionsDir());
101
+ }
102
+
103
+ async function sessionCwd(path: string): Promise<string | undefined> {
104
+ try {
105
+ const parsed: unknown = JSON.parse(await firstLine(path));
106
+ if (typeof parsed !== "object" || parsed === null) return undefined;
107
+ const payload = (parsed as { payload?: unknown }).payload;
108
+ if (typeof payload !== "object" || payload === null) return undefined;
109
+ const cwd = (payload as { cwd?: unknown }).cwd;
110
+ return typeof cwd === "string" ? cwd : undefined;
111
+ } catch {
112
+ return undefined;
113
+ }
114
+ }
115
+
116
+ function sessionIdOf(path: string): string {
117
+ const name = basename(path, ".jsonl");
118
+ return ROLLOUT_ID.exec(name)?.[1] ?? name;
119
+ }
120
+
121
+ /**
122
+ * The newest rollouts as the rest of isy sees a session, newest first.
123
+ *
124
+ * Rollout names open with an ISO timestamp under a date tree, so the paths
125
+ * arrive in creation order — but mtime is what a sweep compares against, and a
126
+ * resumed session is appended to long after it was named, so the sort is by
127
+ * mtime. `keep` runs before the `stat`, which is what lets a per-directory
128
+ * listing cost one first line per rollout rather than a first line and a stat.
129
+ */
130
+ async function scanRollouts(keep?: (path: string) => Promise<boolean>): Promise<SessionFile[]> {
131
+ const sessions: SessionFile[] = [];
132
+
133
+ for (const path of (await rolloutPaths()).slice(0, SCAN_LIMIT)) {
134
+ if (keep && !(await keep(path))) continue;
135
+ try {
136
+ const info = await stat(path);
137
+ if (!info.isFile()) continue;
138
+ sessions.push({
139
+ sessionId: sessionIdOf(path),
140
+ path,
141
+ sizeBytes: info.size,
142
+ modifiedAt: info.mtime,
143
+ });
144
+ } catch {
145
+ continue;
146
+ }
147
+ }
148
+
149
+ sessions.sort((a, b) => b.modifiedAt.getTime() - a.modifiedAt.getTime());
150
+ return sessions;
151
+ }
152
+
153
+ async function codexRecords(path: string, cwd?: string): Promise<string[]> {
154
+ const rollout = (await readFile(path, "utf8")).split("\n");
155
+ return toClaudeRecords(rollout, { cwd });
156
+ }
157
+
158
+ export const codexAgent: Agent = {
159
+ id: "codex",
160
+ label: "Codex CLI",
161
+
162
+ async present(): Promise<boolean> {
163
+ try {
164
+ await access(codexHome());
165
+ return true;
166
+ } catch {
167
+ return false;
168
+ }
169
+ },
170
+
171
+ configLocation(): string {
172
+ return codexHooksPath();
173
+ },
174
+
175
+ hooks: codexHooks,
176
+
177
+ // Codex keeps every project's sessions in one date tree, so this is the tree
178
+ // itself rather than a per-project directory.
179
+ transcriptDir(): string {
180
+ return codexSessionsDir();
181
+ },
182
+
183
+ transcriptRoot: codexSessionsDir,
184
+
185
+ // Filtered before the `stat`, never after: this runs on every post-commit and
186
+ // every pre-push, and the first line is what decides which rollouts are even
187
+ // this directory's.
188
+ sessionsIn(cwd: string): Promise<SessionFile[]> {
189
+ return scanRollouts(async (path) => (await sessionCwd(path)) === cwd);
190
+ },
191
+
192
+ allSessions: () => scanRollouts(),
193
+
194
+ cwdOf: sessionCwd,
195
+
196
+ async parsedSession(path: string, cwd?: string): Promise<ParsedSession> {
197
+ const session = parseLines(await codexRecords(path, cwd));
198
+ session.filePath = path;
199
+ return session;
200
+ },
201
+
202
+ // Codex sends `transcript_path` under the same name Claude Code does.
203
+ async transcriptFor(hook: HookInput | undefined, cwd: string): Promise<string | undefined> {
204
+ return hook?.transcript_path ?? (await codexAgent.sessionsIn(cwd))[0]?.path;
205
+ },
206
+
207
+ async redactedLines(
208
+ path: string,
209
+ options: { extraPatterns?: readonly string[]; cwd?: string },
210
+ ): Promise<string[]> {
211
+ const records = await codexRecords(path, options.cwd);
212
+ return redactLines(records, { extraPatterns: options.extraPatterns, cwd: options.cwd }).lines;
213
+ },
214
+
215
+ hooksInstalled: () => installedHooksIn(hookFile()),
216
+ installHooks: () => installHookIn(hookFile()),
217
+ removeHooks: () => removeHookIn(hookFile()),
218
+
219
+ // Codex only trusts a hook it has seen the user approve, and records the
220
+ // approval in config.toml keyed by the hook's position in hooks.json.
221
+ afterInstall: "Codex will ask you to approve these hooks the next time it starts.",
222
+
223
+ /**
224
+ * Codex renders a SessionStart hook's stdout as `systemMessage`, but has no
225
+ * output schema for SessionEnd at all — whatever an upload has to say is
226
+ * dropped there. So a SessionEnd line is parked and shown at the next
227
+ * SessionStart. The park file is shared with Kimi and with the sweep on
228
+ * purpose: they write the same wording for the same human, and whichever CLI
229
+ * starts first shows it.
230
+ *
231
+ * ponytail: if Codex itself discards the systemMessage the alert is still
232
+ * lost — no client-side signal says whether it was shown.
233
+ */
234
+ async deliver(message: string, event?: string): Promise<void> {
235
+ if (event === "SessionEnd") return parkAlert(message);
236
+ console.log(JSON.stringify({ systemMessage: await withParkedAlerts(message) }));
237
+ },
238
+ };
@@ -0,0 +1,58 @@
1
+ import { claudeAgent } from "./claude.js";
2
+ import { codexAgent } from "./codex.js";
3
+ import { kimiAgent } from "./kimi.js";
4
+ import type { SessionFile } from "../types.js";
5
+ import type { Agent, AgentId, HookInput } from "./types.js";
6
+
7
+ export { claudeAgent } from "./claude.js";
8
+ export { codexAgent } from "./codex.js";
9
+ export { kimiAgent } from "./kimi.js";
10
+ export type { Agent, AgentHook, AgentId, HookInput } from "./types.js";
11
+
12
+ export const AGENTS: Agent[] = [claudeAgent, kimiAgent, codexAgent];
13
+
14
+ export function agentById(id: AgentId): Agent {
15
+ return AGENTS.find((agent) => agent.id === id) ?? claudeAgent;
16
+ }
17
+
18
+ export function isAgentId(value: string | undefined): value is AgentId {
19
+ return value === "claude" || value === "kimi" || value === "codex";
20
+ }
21
+
22
+ /**
23
+ * Which CLI fired this hook. Codex sends the same fields Claude Code does and so
24
+ * cannot be told apart from it, which is why its hooks pass `--agent codex`.
25
+ * Older Kimi builds said so in `client_type`; 0.38 dropped the field, but its
26
+ * session ids keep their own shape (`session_<uuid>`, where Claude and Codex use
27
+ * a bare UUID). A hook installed before `--agent kimi` relies on that. Claude
28
+ * Code is the default, which keeps every existing install working untouched.
29
+ */
30
+ export function detectAgent(hook: HookInput | undefined, override?: string): Agent {
31
+ if (isAgentId(override)) return agentById(override);
32
+ if (hook?.client_type?.startsWith("kimi") || hook?.session_id?.startsWith("session_")) return kimiAgent;
33
+ return claudeAgent;
34
+ }
35
+
36
+ /** Agents actually installed on this machine — we never configure an absent CLI. */
37
+ export async function presentAgents(): Promise<Agent[]> {
38
+ const present: Agent[] = [];
39
+ for (const agent of AGENTS) if (await agent.present()) present.push(agent);
40
+ return present;
41
+ }
42
+
43
+ /** Newest session for this directory across every CLI installed here. */
44
+ export async function newestSession(
45
+ cwd: string,
46
+ ): Promise<{ agent: Agent; file: SessionFile } | undefined> {
47
+ let best: { agent: Agent; file: SessionFile } | undefined;
48
+
49
+ for (const agent of await presentAgents()) {
50
+ const file = (await agent.sessionsIn(cwd))[0];
51
+ if (!file) continue;
52
+ if (!best || file.modifiedAt.getTime() > best.file.modifiedAt.getTime()) {
53
+ best = { agent, file };
54
+ }
55
+ }
56
+
57
+ return best;
58
+ }
@@ -0,0 +1,274 @@
1
+ import { EDIT_TOOLS } from "../parser.js";
2
+
3
+ /**
4
+ * Kimi CLI keeps a session as `context.jsonl` (kosong Message records) plus an
5
+ * append-only `wire.jsonl` event log. Neither is documented field by field, so
6
+ * everything here is deliberately tolerant: an unrecognised shape yields no
7
+ * record rather than a wrong one.
8
+ *
9
+ * Output is Claude-Code-record-shaped JSONL, because the server re-parses the
10
+ * uploaded transcript with the same parseLines this package exports. One shape
11
+ * downstream, one adapter here.
12
+ */
13
+
14
+ /** Kimi's own bookkeeping roles, which are not conversation turns. */
15
+ const CONTROL_ROLES = new Set(["_system_prompt", "_usage", "_checkpoint"]);
16
+
17
+ /** Tools whose file argument Claude calls `file_path` and Kimi calls `path`. */
18
+ const PATH_ARG_TOOLS = new Set([...EDIT_TOOLS, "Read"]);
19
+
20
+ function isObject(value: unknown): value is Record<string, unknown> {
21
+ return typeof value === "object" && value !== null && !Array.isArray(value);
22
+ }
23
+
24
+ function asString(value: unknown): string | undefined {
25
+ return typeof value === "string" && value.length > 0 ? value : undefined;
26
+ }
27
+
28
+ /** A Kimi transcript opens with the frozen system prompt record. */
29
+ export function isKimiTranscript(firstLine: string): boolean {
30
+ try {
31
+ const parsed: unknown = JSON.parse(firstLine);
32
+ return isObject(parsed) && parsed.role === "_system_prompt";
33
+ } catch {
34
+ return false;
35
+ }
36
+ }
37
+
38
+ /** Text out of `content`, which may be a plain string or an array of parts. */
39
+ function contentText(content: unknown): string {
40
+ if (typeof content === "string") return content;
41
+ if (!Array.isArray(content)) return "";
42
+
43
+ const parts: string[] = [];
44
+ for (const part of content) {
45
+ if (typeof part === "string") parts.push(part);
46
+ else if (isObject(part) && typeof part.text === "string") parts.push(part.text);
47
+ }
48
+ return parts.join("\n");
49
+ }
50
+
51
+ /** Reasoning, wherever this Kimi build happens to put it. */
52
+ function reasoningText(line: Record<string, unknown>): string | undefined {
53
+ const direct = asString(line.reasoning_content) ?? asString(line.reasoning);
54
+ if (direct) return direct;
55
+
56
+ const content = line.content;
57
+ if (!Array.isArray(content)) return undefined;
58
+
59
+ const parts: string[] = [];
60
+ for (const part of content) {
61
+ if (!isObject(part)) continue;
62
+ if (part.type !== "thinking" && part.type !== "reasoning") continue;
63
+ const text = asString(part.thinking) ?? asString(part.text) ?? asString(part.reasoning);
64
+ if (text) parts.push(text);
65
+ }
66
+ return parts.length > 0 ? parts.join("\n") : undefined;
67
+ }
68
+
69
+ /**
70
+ * Kimi names the file argument `path` where Claude names it `file_path`.
71
+ * Renaming here keeps parser.ts and detectors.ts free of Kimi knowledge.
72
+ * Grep and Glob keep `path`, exactly as they do in Claude Code.
73
+ */
74
+ export function renameArgs(tool: string, input: Record<string, unknown>): Record<string, unknown> {
75
+ if (!PATH_ARG_TOOLS.has(tool)) return input;
76
+ if (typeof input.path !== "string" || typeof input.file_path === "string") return input;
77
+
78
+ const { path, ...rest } = input;
79
+ return { ...rest, file_path: path };
80
+ }
81
+
82
+ /** Tool calls, whether OpenAI-style `tool_calls` or inline content parts. */
83
+ function toolUseBlocks(line: Record<string, unknown>): Record<string, unknown>[] {
84
+ const raw: unknown[] = Array.isArray(line.tool_calls)
85
+ ? line.tool_calls
86
+ : Array.isArray(line.content)
87
+ ? line.content.filter(
88
+ (part) => isObject(part) && (part.type === "tool_call" || part.type === "tool_use"),
89
+ )
90
+ : [];
91
+
92
+ const blocks: Record<string, unknown>[] = [];
93
+ for (const call of raw) {
94
+ if (!isObject(call)) continue;
95
+
96
+ const fn = isObject(call.function) ? call.function : call;
97
+ const name = asString(fn.name);
98
+ const id = asString(call.id) ?? asString(call.tool_call_id);
99
+ if (!name || !id) continue;
100
+
101
+ const rawArgs = fn.arguments ?? fn.input ?? call.input;
102
+ let input: Record<string, unknown> = {};
103
+ if (isObject(rawArgs)) {
104
+ input = rawArgs;
105
+ } else if (typeof rawArgs === "string") {
106
+ try {
107
+ const parsed: unknown = JSON.parse(rawArgs);
108
+ if (isObject(parsed)) input = parsed;
109
+ } catch {
110
+ // A truncated or streaming-partial argument string: keep the call,
111
+ // lose the arguments. Better than dropping the tool use entirely.
112
+ }
113
+ }
114
+
115
+ blocks.push({ type: "tool_use", id, name, input: renameArgs(name, input) });
116
+ }
117
+ return blocks;
118
+ }
119
+
120
+ export interface KimiOptions {
121
+ sessionId: string;
122
+ cwd?: string;
123
+ version?: string;
124
+ /** `wire.jsonl` lines, if present: they hold turns a rewind discarded. */
125
+ wire?: Iterable<string>;
126
+ }
127
+
128
+ /** Identity of a turn, used to tell surviving context from discarded wire. */
129
+ function digest(line: Record<string, unknown>): string {
130
+ const tools = toolUseBlocks(line)
131
+ .map((block) => `${String(block.name)}(${JSON.stringify(block.input)})`)
132
+ .join(",");
133
+ return `${String(line.role)}|${contentText(line.content).trim().replace(/\s+/g, " ")}|${tools}`;
134
+ }
135
+
136
+ function parseLines(lines: Iterable<string>): Record<string, unknown>[] {
137
+ const parsed: Record<string, unknown>[] = [];
138
+ for (const line of lines) {
139
+ const trimmed = line.trim();
140
+ if (trimmed.length === 0) continue;
141
+ try {
142
+ const value: unknown = JSON.parse(trimmed);
143
+ if (isObject(value)) parsed.push(value);
144
+ } catch {
145
+ continue;
146
+ }
147
+ }
148
+ return parsed;
149
+ }
150
+
151
+ /**
152
+ * Pull message-shaped payloads out of wire events. The wire schema is not
153
+ * documented, so we look for a `role` at the top level or under the handful of
154
+ * keys an event stream plausibly nests one in. An unrecognised event yields
155
+ * nothing, which degrades this to context-only rather than to wrong output.
156
+ */
157
+ function wireMessages(lines: Iterable<string>): Record<string, unknown>[] {
158
+ const found: Record<string, unknown>[] = [];
159
+ for (const event of parseLines(lines)) {
160
+ for (const candidate of [event, event.message, event.data, event.payload]) {
161
+ if (!isObject(candidate)) continue;
162
+ if (typeof candidate.role !== "string") continue;
163
+ if (CONTROL_ROLES.has(candidate.role)) continue;
164
+ found.push(candidate);
165
+ break;
166
+ }
167
+ }
168
+ return found;
169
+ }
170
+
171
+ /**
172
+ * Turn one Kimi session into Claude-shaped transcript records.
173
+ *
174
+ * Surviving `context.jsonl` turns form the main path. Turns that appear only in
175
+ * `wire.jsonl` were discarded by a `_checkpoint` rewind: they hang off the fork
176
+ * point as a side branch, which is exactly the shape onAbandonedBranch already
177
+ * understands, so abandoned_approach works here as it does on Claude.
178
+ */
179
+ export function toClaudeRecords(context: Iterable<string>, options: KimiOptions): string[] {
180
+ const lines = parseLines(context);
181
+ const surviving = new Set(lines.filter((line) => !CONTROL_ROLES.has(String(line.role))).map(digest));
182
+
183
+ const discarded = options.wire
184
+ ? wireMessages(options.wire).filter((message) => !surviving.has(digest(message)))
185
+ : [];
186
+
187
+ const firstCheckpoint = lines.findIndex((line) => line.role === "_checkpoint");
188
+ // Only graft a branch when real work follows the fork, so the session's last
189
+ // record — the tip buildMainPath walks back from — is always a surviving one.
190
+ const forkAt = firstCheckpoint >= 0 && firstCheckpoint < lines.length - 1 ? firstCheckpoint : -1;
191
+
192
+ const out: string[] = [];
193
+ let index = 0;
194
+ let tail: string | null = null;
195
+
196
+ const emit = (record: Record<string, unknown>, parent: string | null): string => {
197
+ const uuid = `kimi-${index}`;
198
+ out.push(
199
+ JSON.stringify({
200
+ ...record,
201
+ uuid,
202
+ parentUuid: parent,
203
+ sessionId: options.sessionId,
204
+ cwd: options.cwd,
205
+ version: options.version ?? "kimi",
206
+ isSidechain: false,
207
+ }),
208
+ );
209
+ index += 1;
210
+ return uuid;
211
+ };
212
+
213
+ const emitTurn = (line: Record<string, unknown>, parent: string | null): string | undefined => {
214
+ const role = String(line.role);
215
+ const timestamp = asString(line.timestamp) ?? asString(line.created_at);
216
+
217
+ if (role === "tool") {
218
+ const id = asString(line.tool_call_id);
219
+ if (!id) return undefined;
220
+ const text = contentText(line.content);
221
+ return emit(
222
+ {
223
+ type: "user",
224
+ timestamp,
225
+ message: {
226
+ role: "user",
227
+ content: [{ type: "tool_result", tool_use_id: id, content: text }],
228
+ },
229
+ toolUseResult: { stdout: text },
230
+ },
231
+ parent,
232
+ );
233
+ }
234
+
235
+ if (role === "assistant") {
236
+ const blocks: Record<string, unknown>[] = [];
237
+ const reasoning = reasoningText(line);
238
+ if (reasoning) blocks.push({ type: "thinking", thinking: reasoning });
239
+ const text = contentText(line.content);
240
+ if (text) blocks.push({ type: "text", text });
241
+ blocks.push(...toolUseBlocks(line));
242
+ if (blocks.length === 0) return undefined;
243
+
244
+ return emit(
245
+ { type: "assistant", timestamp, message: { role: "assistant", content: blocks } },
246
+ parent,
247
+ );
248
+ }
249
+
250
+ if (role !== "user") return undefined;
251
+ const text = contentText(line.content);
252
+ if (!text) return undefined;
253
+ return emit(
254
+ { type: "user", timestamp, message: { role: "user", content: [{ type: "text", text }] } },
255
+ parent,
256
+ );
257
+ };
258
+
259
+ lines.forEach((line, position) => {
260
+ if (position === forkAt) {
261
+ // The discarded branch forks from the turn before the checkpoint and is
262
+ // deliberately left off the main chain: `tail` does not move.
263
+ let branch = tail;
264
+ for (const message of discarded) branch = emitTurn(message, branch) ?? branch;
265
+ return;
266
+ }
267
+ if (CONTROL_ROLES.has(String(line.role))) return;
268
+
269
+ const uuid = emitTurn(line, tail);
270
+ if (uuid) tail = uuid;
271
+ });
272
+
273
+ return out;
274
+ }