@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,179 @@
1
+ import { renameArgs } from "./kimi-records.js";
2
+
3
+ /**
4
+ * The second shape a Kimi session can take on disk. Newer builds keep no
5
+ * `context.jsonl` at all: the whole session is one append-only event log at
6
+ * `agents/<name>/wire.jsonl`, whose records are wrapper events rather than
7
+ * messages.
8
+ *
9
+ * Kept apart from the `context.jsonl` reader rather than folded into it: the
10
+ * two formats share no field, and a reader that tried to serve both would
11
+ * guess. Which one a session uses is decided by sniffing its first line.
12
+ *
13
+ * ponytail: a rewind has no representation here that this corpus shows, so the
14
+ * output is one linear chain and `onAbandonedBranch` finds nothing — the
15
+ * content-revert detectors still fire. Graft the branch once a real rewound
16
+ * session shows what marks the fork.
17
+ */
18
+
19
+ const CONTENT_EVENTS = new Set(["content.part", "tool.call", "tool.result"]);
20
+
21
+ function isObject(value: unknown): value is Record<string, unknown> {
22
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23
+ }
24
+
25
+ function asString(value: unknown): string | undefined {
26
+ return typeof value === "string" && value.length > 0 ? value : undefined;
27
+ }
28
+
29
+ /** A wire log opens with its own protocol metadata. */
30
+ export function isKimiWireTranscript(firstLine: string): boolean {
31
+ try {
32
+ const parsed: unknown = JSON.parse(firstLine);
33
+ return isObject(parsed) && parsed.type === "metadata" && "protocol_version" in parsed;
34
+ } catch {
35
+ return false;
36
+ }
37
+ }
38
+
39
+ function stamp(time: unknown): string | undefined {
40
+ if (typeof time !== "number" || !Number.isFinite(time)) return undefined;
41
+ return new Date(time).toISOString();
42
+ }
43
+
44
+ /** Text out of a tool result, which carries `output` and an optional `note`. */
45
+ function resultText(result: unknown): string {
46
+ if (typeof result === "string") return result;
47
+ if (!isObject(result)) return "";
48
+ return asString(result.output) ?? asString(result.note) ?? "";
49
+ }
50
+
51
+ export interface KimiWireOptions {
52
+ sessionId: string;
53
+ cwd?: string;
54
+ version?: string;
55
+ }
56
+
57
+ export function wireToClaudeRecords(
58
+ lines: Iterable<string>,
59
+ options: KimiWireOptions,
60
+ ): string[] {
61
+ const out: string[] = [];
62
+ let index = 0;
63
+ let parent: string | null = null;
64
+
65
+ const emit = (record: Record<string, unknown>): void => {
66
+ const uuid = `kimi-${index}`;
67
+ out.push(
68
+ JSON.stringify({
69
+ ...record,
70
+ uuid,
71
+ parentUuid: parent,
72
+ sessionId: options.sessionId,
73
+ cwd: options.cwd,
74
+ version: options.version ?? "kimi",
75
+ isSidechain: false,
76
+ }),
77
+ );
78
+ parent = uuid;
79
+ index += 1;
80
+ };
81
+
82
+ for (const line of lines) {
83
+ const text = line.trim();
84
+ if (!text) continue;
85
+
86
+ let event: unknown;
87
+ try {
88
+ event = JSON.parse(text);
89
+ } catch {
90
+ // A half-written last line while the session is still running.
91
+ continue;
92
+ }
93
+ if (!isObject(event)) continue;
94
+
95
+ const timestamp = stamp(event.time);
96
+
97
+ // A whole user or assistant message, appended outside the agent loop.
98
+ if (event.type === "context.append_message" && isObject(event.message)) {
99
+ const message = event.message;
100
+ const role = asString(message.role);
101
+ if (role !== "user" && role !== "assistant") continue;
102
+
103
+ const content = Array.isArray(message.content)
104
+ ? message.content
105
+ .filter((part): part is Record<string, unknown> => isObject(part) && part.type === "text")
106
+ .map((part) => ({ type: "text", text: asString(part.text) ?? "" }))
107
+ .filter((part) => part.text.length > 0)
108
+ : typeof message.content === "string" && message.content.length > 0
109
+ ? [{ type: "text", text: message.content }]
110
+ : [];
111
+ if (content.length === 0) continue;
112
+
113
+ emit({ type: role, timestamp, message: { role, content } });
114
+ continue;
115
+ }
116
+
117
+ if (event.type !== "context.append_loop_event" || !isObject(event.event)) continue;
118
+
119
+ const inner = event.event;
120
+ const kind = asString(inner.type);
121
+ if (!kind || !CONTENT_EVENTS.has(kind)) continue;
122
+
123
+ if (kind === "content.part" && isObject(inner.part)) {
124
+ const part = inner.part;
125
+ // Kimi calls reasoning "think"; the detectors look for Claude's "thinking".
126
+ const thinking = asString(part.think) ?? asString(part.thinking);
127
+ const said = asString(part.text);
128
+ const block =
129
+ part.type === "think" && thinking
130
+ ? { type: "thinking", thinking }
131
+ : said
132
+ ? { type: "text", text: said }
133
+ : undefined;
134
+ if (!block) continue;
135
+
136
+ emit({ type: "assistant", timestamp, message: { role: "assistant", content: [block] } });
137
+ continue;
138
+ }
139
+
140
+ if (kind === "tool.call") {
141
+ const name = asString(inner.name);
142
+ const id = asString(inner.toolCallId);
143
+ if (!name || !id) continue;
144
+ const args = isObject(inner.args) ? inner.args : {};
145
+
146
+ emit({
147
+ type: "assistant",
148
+ timestamp,
149
+ message: {
150
+ role: "assistant",
151
+ // Kimi names the file argument `path`; every downstream detector
152
+ // reads `file_path`, so the rename happens once, here.
153
+ content: [{ type: "tool_use", id, name, input: renameArgs(name, args) }],
154
+ },
155
+ });
156
+ continue;
157
+ }
158
+
159
+ const id = asString(inner.toolCallId);
160
+ if (!id) continue;
161
+ const output = resultText(inner.result);
162
+ // Kimi 0.38 flags a failed call with `isError`.
163
+ const failed = isObject(inner.result) && (inner.result.isError === true || inner.result.error !== undefined);
164
+
165
+ emit({
166
+ type: "user",
167
+ timestamp,
168
+ message: {
169
+ role: "user",
170
+ content: [
171
+ { type: "tool_result", tool_use_id: id, content: output, ...(failed ? { is_error: true } : {}) },
172
+ ],
173
+ },
174
+ toolUseResult: { stdout: output },
175
+ });
176
+ }
177
+
178
+ return out;
179
+ }
@@ -0,0 +1,390 @@
1
+ import { existsSync } from "node:fs";
2
+ import { access, mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { basename, dirname, join } from "node:path";
5
+ import { parkAlert } from "../alert.js";
6
+ import { parseLines } from "../parser.js";
7
+ import { pendingAlertPath } from "../paths.js";
8
+ import { redactLines } from "../redact.js";
9
+ import type { DiscoveredSession, ParsedSession, SessionFile } from "../types.js";
10
+ import { toClaudeRecords } from "./kimi-records.js";
11
+ import { isKimiWireTranscript, wireToClaudeRecords } from "./kimi-wire.js";
12
+ import type { Agent, AgentHook, HookInput } from "./types.js";
13
+
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
+ const override = process.env.KIMI_HOME;
19
+ if (override) return override;
20
+
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]!);
26
+ }
27
+
28
+ export function kimiConfigPath(): string {
29
+ return join(kimiHome(), "config.toml");
30
+ }
31
+
32
+ /** Every workspace's sessions, whatever Kimi decides to name the folders. */
33
+ export function kimiSessionsRoot(): string {
34
+ return join(kimiHome(), "sessions");
35
+ }
36
+
37
+ /**
38
+ * One session on disk, found by reading its own metadata rather than by
39
+ * computing where it ought to be.
40
+ *
41
+ * Kimi has already changed both halves of that layout once — the workspace
42
+ * folder went from a bare hash to `wd_<name>_<hash>` and the hash from MD5 to
43
+ * SHA-256, and the transcript moved from `context.jsonl` beside `state.json`
44
+ * down into `agents/<name>/wire.jsonl`. Anything that derives the path from the
45
+ * working directory is one Kimi release away from silently finding nothing, and
46
+ * finding nothing looks exactly like having no sessions. `state.json` records
47
+ * the `cwd` outright, so matching on it survives any renaming.
48
+ */
49
+ interface KimiSession {
50
+ sessionId: string;
51
+ transcript: string;
52
+ cwd?: string;
53
+ }
54
+
55
+ function isObject(value: unknown): value is Record<string, unknown> {
56
+ return typeof value === "object" && value !== null && !Array.isArray(value);
57
+ }
58
+
59
+ async function subdirectories(dir: string): Promise<string[]> {
60
+ try {
61
+ const entries = await readdir(dir, { withFileTypes: true });
62
+ return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
63
+ } catch {
64
+ return [];
65
+ }
66
+ }
67
+
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> {
70
+ const agents = isObject(state.agents) ? state.agents : {};
71
+
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");
77
+
78
+ for (const candidate of [join(home, "wire.jsonl"), join(dir, "context.jsonl")]) {
79
+ try {
80
+ if ((await stat(candidate)).isFile()) return candidate;
81
+ } catch {
82
+ continue;
83
+ }
84
+ }
85
+ return undefined;
86
+ }
87
+
88
+ /** Everything Kimi records about a session outside its transcript. */
89
+ async function readState(dir: string): Promise<Record<string, unknown> | undefined> {
90
+ try {
91
+ const parsed: unknown = JSON.parse(await readFile(join(dir, "state.json"), "utf8"));
92
+ return isObject(parsed) ? parsed : undefined;
93
+ } catch {
94
+ return undefined;
95
+ }
96
+ }
97
+
98
+ /**
99
+ * What the session calls itself: `state.json` first, the folder it sits in
100
+ * second. One rule, because a session listed under one name and parsed under
101
+ * another is a session nothing can match up.
102
+ */
103
+ function sessionIdOf(state: Record<string, unknown> | undefined, dir: string): string {
104
+ const id = state?.id;
105
+ return typeof id === "string" && id.length > 0 ? id : basename(dir);
106
+ }
107
+
108
+ /** Where the session ran, which is the root every path in it is relative to. */
109
+ function recordedCwd(state: Record<string, unknown> | undefined): string | undefined {
110
+ return typeof state?.cwd === "string" ? state.cwd : undefined;
111
+ }
112
+
113
+ async function readSession(dir: string): Promise<KimiSession | undefined> {
114
+ const state = await readState(dir);
115
+ if (!state) return undefined;
116
+
117
+ const transcript = await transcriptIn(dir, state);
118
+ if (!transcript) return undefined;
119
+
120
+ return { sessionId: sessionIdOf(state, dir), transcript, cwd: recordedCwd(state) };
121
+ }
122
+
123
+ /**
124
+ * Kimi sessions as the rest of isy sees one: newest first, with the working
125
+ * directory `state.json` recorded already attached, because reading it is what
126
+ * listing a Kimi session costs anyway.
127
+ *
128
+ * Takes the sessions rather than finding them, so a caller that only wants one
129
+ * directory filters first and pays no `stat` for the rest.
130
+ */
131
+ async function discovered(sessions: readonly KimiSession[]): Promise<DiscoveredSession[]> {
132
+ const found: DiscoveredSession[] = [];
133
+
134
+ for (const session of sessions) {
135
+ try {
136
+ const info = await stat(session.transcript);
137
+ found.push({
138
+ sessionId: session.sessionId,
139
+ path: session.transcript,
140
+ sizeBytes: info.size,
141
+ modifiedAt: info.mtime,
142
+ cwd: session.cwd,
143
+ });
144
+ } catch {
145
+ continue;
146
+ }
147
+ }
148
+
149
+ found.sort((a, b) => b.modifiedAt.getTime() - a.modifiedAt.getTime());
150
+ return found;
151
+ }
152
+
153
+ /** Every session on this machine, in no particular order. */
154
+ async function allSessions(): Promise<KimiSession[]> {
155
+ const root = kimiSessionsRoot();
156
+ const found: KimiSession[] = [];
157
+
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);
163
+ }
164
+ }
165
+
166
+ return found;
167
+ }
168
+
169
+ const BEGIN = "# isy:begin — managed by isy, do not edit inside this block";
170
+ const END = "# isy:end";
171
+
172
+ function drainCommand(): string {
173
+ const path = pendingAlertPath();
174
+ return `if [ -s "${path}" ]; then cat "${path}"; : > "${path}"; fi`;
175
+ }
176
+
177
+ function kimiHooks(): AgentHook[] {
178
+ 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.
185
+ {
186
+ event: "SessionEnd",
187
+ command: "npx @nightloom/isy upload --hook --agent kimi",
188
+ superseded: ["npx isy upload --hook", "npx isy upload --hook --agent kimi"],
189
+ },
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.
195
+ { event: "UserPromptSubmit", command: drainCommand() },
196
+ ];
197
+ }
198
+
199
+ function managedBlock(): string {
200
+ const entries = kimiHooks()
201
+ .map((hook) => `[[hooks]]\nevent = "${hook.event}"\ncommand = '${hook.command}'\ntimeout = 30`)
202
+ .join("\n\n");
203
+ return `${BEGIN}\n${entries}\n${END}`;
204
+ }
205
+
206
+ async function readConfigToml(): Promise<string> {
207
+ try {
208
+ return await readFile(kimiConfigPath(), "utf8");
209
+ } catch {
210
+ return "";
211
+ }
212
+ }
213
+
214
+ /**
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.
217
+ */
218
+ /**
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.
222
+ */
223
+ function sessionDirFor(path: string): string {
224
+ const dir = dirname(path);
225
+ return basename(path) === "wire.jsonl" ? dirname(dirname(dir)) : dir;
226
+ }
227
+
228
+ /**
229
+ * Kimi puts nothing in the transcript itself, so the id and the working
230
+ * directory both come off the `state.json` beside it — read here through the
231
+ * same two rules `readSession` uses, so a session cannot be called one thing
232
+ * when it is listed and another when it is parsed. Without a working directory
233
+ * no path in the transcript can be made repository-relative
234
+ * (`mask-paths.ts`), so a caller that knows it wins and one that does not,
235
+ * such as `isy analyze`, still gets it here.
236
+ */
237
+ async function kimiRecords(path: string, given?: string): Promise<string[]> {
238
+ const lines = (await readFile(path, "utf8")).split("\n");
239
+ const dir = sessionDirFor(path);
240
+ const state = await readState(dir);
241
+ 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.
246
+ if (isKimiWireTranscript(lines[0] ?? "")) {
247
+ return wireToClaudeRecords(lines, { sessionId, cwd });
248
+ }
249
+
250
+ let wire: string[] | undefined;
251
+ try {
252
+ wire = (await readFile(join(dirname(path), "wire.jsonl"), "utf8")).split("\n");
253
+ } catch {
254
+ wire = undefined;
255
+ }
256
+
257
+ return toClaudeRecords(lines, { sessionId, cwd, wire });
258
+ }
259
+
260
+ export const kimiAgent: Agent = {
261
+ id: "kimi",
262
+ label: "Kimi CLI",
263
+
264
+ async present(): Promise<boolean> {
265
+ try {
266
+ await access(kimiHome());
267
+ return true;
268
+ } catch {
269
+ return false;
270
+ }
271
+ },
272
+
273
+ configLocation(): string {
274
+ return kimiConfigPath();
275
+ },
276
+
277
+ hooks: kimiHooks,
278
+
279
+ // Sessions are found by reading each one's cwd, not by deriving a path, so
280
+ // there is no per-directory folder to name. The root is what must be readable.
281
+ transcriptDir(): string {
282
+ return kimiSessionsRoot();
283
+ },
284
+
285
+ transcriptRoot: kimiSessionsRoot,
286
+
287
+ async parsedSession(path: string, cwd?: string): Promise<ParsedSession> {
288
+ const session = parseLines(await kimiRecords(path, cwd));
289
+ session.filePath = path;
290
+ return session;
291
+ },
292
+
293
+ async sessionsIn(cwd: string): Promise<SessionFile[]> {
294
+ return discovered((await allSessions()).filter((session) => session.cwd === cwd));
295
+ },
296
+
297
+ // Kimi reads `state.json` to list anything at all, so unlike the other two
298
+ // adapters the working directory comes for free with the listing — which is
299
+ // why `DiscoveredSession` carries it and a sweep never asks `cwdOf` again.
300
+ async allSessions(): Promise<DiscoveredSession[]> {
301
+ return discovered(await allSessions());
302
+ },
303
+
304
+ async cwdOf(path: string): Promise<string | undefined> {
305
+ return recordedCwd(await readState(sessionDirFor(path)));
306
+ },
307
+
308
+ // Kimi's hook payload carries no transcript path, so compose it from the
309
+ // session id and cwd it does send, and fall back to the newest session.
310
+ async transcriptFor(hook: HookInput | undefined, cwd: string): Promise<string | undefined> {
311
+ const sessionId = hook?.session_id;
312
+ if (sessionId) {
313
+ // Matched by id across every workspace: a session resumed from another
314
+ // directory keeps its id but moves, and the id is the thing we were told.
315
+ const exact = (await allSessions()).find((session) => session.sessionId === sessionId);
316
+ if (exact) return exact.transcript;
317
+ }
318
+ return (await kimiAgent.sessionsIn(hook?.cwd ?? cwd))[0]?.path;
319
+ },
320
+
321
+ async redactedLines(
322
+ path: string,
323
+ options: { extraPatterns?: readonly string[]; cwd?: string },
324
+ ): Promise<string[]> {
325
+ const records = await kimiRecords(path, options.cwd);
326
+ return redactLines(records, { extraPatterns: options.extraPatterns, cwd: options.cwd }).lines;
327
+ },
328
+
329
+ 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);
334
+ },
335
+
336
+ 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
+ }
350
+ }
351
+
352
+ const separator = contents.length === 0 || contents.endsWith("\n") ? "" : "\n";
353
+ await writeConfigToml(`${contents}${separator}${contents.length > 0 ? "\n" : ""}${desired}\n`);
354
+ return "installed";
355
+ },
356
+
357
+ 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";
369
+ },
370
+
371
+ // Kimi discards hook stdout on the events we care about, so write straight to
372
+ // the terminal. SessionEnd fires after the session closes, so the TUI is down
373
+ // and the line lands in the shell. With no terminal to write to — CI, a piped
374
+ // run — park it for the UserPromptSubmit drain instead of losing it.
375
+ async deliver(message: string): Promise<void> {
376
+ try {
377
+ await writeFile("/dev/tty", `${message}\n`);
378
+ return;
379
+ } catch {
380
+ // No controlling terminal.
381
+ }
382
+
383
+ await parkAlert(message);
384
+ },
385
+ };
386
+
387
+ async function writeConfigToml(contents: string): Promise<void> {
388
+ await mkdir(kimiHome(), { recursive: true });
389
+ await writeFile(kimiConfigPath(), contents, "utf8");
390
+ }
@@ -0,0 +1,92 @@
1
+ import type { DiscoveredSession, ParsedSession, SessionFile } from "../types.js";
2
+
3
+ export type AgentId = "claude" | "kimi" | "codex";
4
+
5
+ /**
6
+ * What a CLI hands us on stdin when it fires a hook. Claude Code and Codex CLI
7
+ * both send `transcript_path` under the same field names; Kimi sends no path,
8
+ * and only its older builds name themselves in `client_type` (see `detectAgent`).
9
+ * Because Codex's payload is indistinguishable from Claude's, its hooks pass
10
+ * `--agent codex` explicitly.
11
+ */
12
+ export interface HookInput {
13
+ session_id?: string;
14
+ transcript_path?: string;
15
+ cwd?: string;
16
+ hook_event_name?: string;
17
+ client_type?: string;
18
+ }
19
+
20
+ export interface AgentHook {
21
+ event: string;
22
+ command: string;
23
+ /** Commands an older isy wrote for the same job: replace, never stack. */
24
+ superseded?: string[];
25
+ }
26
+
27
+ /**
28
+ * One coding CLI ISY can watch. Only the parts that genuinely differ between
29
+ * CLIs live here — parsing, redaction, detectors and upload are shared.
30
+ */
31
+ export interface Agent {
32
+ id: AgentId;
33
+ label: string;
34
+
35
+ /** Is this CLI actually installed? We never write config for one that is not. */
36
+ present(): Promise<boolean>;
37
+ /** Where this agent's hooks live, for messages to the user. */
38
+ configLocation(): string;
39
+ hooks(): AgentHook[];
40
+
41
+ /** Where this agent keeps transcripts for a working directory. */
42
+ transcriptDir(cwd: string): string;
43
+ /**
44
+ * The directory every session of this agent lives under, whatever directory
45
+ * it ran in. For Claude that is the parent of the per-project folders; for
46
+ * the other two it is the same thing `transcriptDir` already returns.
47
+ */
48
+ transcriptRoot(): string;
49
+ /** Every session recorded for a working directory, newest first. */
50
+ sessionsIn(cwd: string): Promise<SessionFile[]>;
51
+ /**
52
+ * Every session this CLI recorded on this machine, newest first, without
53
+ * opening any of them. What a sweep starts from: a desktop app fires no hook
54
+ * and names no working directory, so there is nothing to scope the scan to.
55
+ *
56
+ * `cwd` comes back set only where listing already had to read it (Kimi).
57
+ */
58
+ allSessions(): Promise<DiscoveredSession[]>;
59
+ /**
60
+ * Where one session ran, for the adapters whose listing does not know. Separate
61
+ * from `allSessions` on purpose: it costs a read, and a sweep only needs it for
62
+ * the sessions that grew since last time.
63
+ */
64
+ cwdOf(path: string): Promise<string | undefined>;
65
+ /** Parse one transcript without redacting it — for local inspection only. */
66
+ parsedSession(path: string, cwd?: string): Promise<ParsedSession>;
67
+ /** Resolve the transcript this hook invocation is about. */
68
+ transcriptFor(hook: HookInput | undefined, cwd: string): Promise<string | undefined>;
69
+ /**
70
+ * Redacted, Claude-record-shaped JSONL lines, ready for parseLines and upload.
71
+ * Agents whose native format differs normalize here, so everything downstream
72
+ * — including the server's own parseLines — sees one shape.
73
+ */
74
+ redactedLines(
75
+ path: string,
76
+ options: { extraPatterns?: readonly string[]; cwd?: string },
77
+ ): Promise<string[]>;
78
+
79
+ /** Anything the user must still do after hooks are written, if anything. */
80
+ afterInstall?: string;
81
+
82
+ hooksInstalled(): Promise<string[]>;
83
+ installHooks(): Promise<"installed" | "already-present">;
84
+ removeHooks(): Promise<"removed" | "absent">;
85
+
86
+ /**
87
+ * Show one line to the user. Each CLI displays text its own way, and the same
88
+ * CLI can differ per event: Codex renders a hook's stdout at SessionStart but
89
+ * discards it at SessionEnd, so the event decides the route.
90
+ */
91
+ deliver(message: string, event?: string): Promise<void>;
92
+ }