@nightloom/isy 1.0.0 → 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 (131) 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 +35 -12
  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/stage0.d.ts +7 -1
  58. package/dist/stage0.js +10 -3
  59. package/dist/stage0.js.map +1 -1
  60. package/dist/state.d.ts +6 -3
  61. package/dist/state.js +21 -5
  62. package/dist/state.js.map +1 -1
  63. package/dist/subagents.d.ts +49 -0
  64. package/dist/subagents.js +237 -0
  65. package/dist/subagents.js.map +1 -0
  66. package/dist/test/analyze.test.js +15 -11
  67. package/dist/test/analyze.test.js.map +1 -1
  68. package/dist/test/check.test.js +25 -3
  69. package/dist/test/check.test.js.map +1 -1
  70. package/dist/test/codex.test.js +43 -0
  71. package/dist/test/codex.test.js.map +1 -1
  72. package/dist/test/commit.test.js +9 -1
  73. package/dist/test/commit.test.js.map +1 -1
  74. package/dist/test/hook.test.js +66 -2
  75. package/dist/test/hook.test.js.map +1 -1
  76. package/dist/test/init.test.d.ts +1 -0
  77. package/dist/test/init.test.js +94 -0
  78. package/dist/test/init.test.js.map +1 -0
  79. package/dist/test/kimi-cli.test.d.ts +1 -0
  80. package/dist/test/kimi-cli.test.js +231 -0
  81. package/dist/test/kimi-cli.test.js.map +1 -0
  82. package/dist/test/kimi-code.test.d.ts +1 -0
  83. package/dist/test/kimi-code.test.js +302 -0
  84. package/dist/test/kimi-code.test.js.map +1 -0
  85. package/dist/test/kimi-config.test.d.ts +1 -0
  86. package/dist/test/kimi-config.test.js +224 -0
  87. package/dist/test/kimi-config.test.js.map +1 -0
  88. package/dist/test/kimi-hook.test.d.ts +1 -0
  89. package/dist/test/kimi-hook.test.js +163 -0
  90. package/dist/test/kimi-hook.test.js.map +1 -0
  91. package/dist/test/kimi-listing.test.d.ts +1 -0
  92. package/dist/test/kimi-listing.test.js +193 -0
  93. package/dist/test/kimi-listing.test.js.map +1 -0
  94. package/dist/test/kimi.test.js +52 -7
  95. package/dist/test/kimi.test.js.map +1 -1
  96. package/dist/test/parser.test.js +192 -5
  97. package/dist/test/parser.test.js.map +1 -1
  98. package/dist/test/redact.test.js +71 -7
  99. package/dist/test/redact.test.js.map +1 -1
  100. package/dist/test/stage0.test.js +74 -4
  101. package/dist/test/stage0.test.js.map +1 -1
  102. package/dist/test/subagents.test.d.ts +1 -0
  103. package/dist/test/subagents.test.js +272 -0
  104. package/dist/test/subagents.test.js.map +1 -0
  105. package/dist/types.d.ts +16 -0
  106. package/package.json +3 -2
  107. package/src/agents/claude.ts +17 -7
  108. package/src/agents/codex-records.ts +33 -12
  109. package/src/agents/index.ts +21 -6
  110. package/src/agents/kimi-cli-wire.ts +350 -0
  111. package/src/agents/kimi-config.ts +210 -0
  112. package/src/agents/kimi-records.ts +52 -29
  113. package/src/agents/kimi-tools.ts +128 -0
  114. package/src/agents/kimi-wire.ts +270 -82
  115. package/src/agents/kimi.ts +653 -113
  116. package/src/agents/timeline.ts +68 -0
  117. package/src/agents/types.ts +12 -0
  118. package/src/commands/analyze.ts +62 -6
  119. package/src/commands/check.ts +11 -0
  120. package/src/commands/init.ts +18 -2
  121. package/src/commands/upload.ts +8 -4
  122. package/src/detectors.ts +39 -5
  123. package/src/hook.ts +81 -24
  124. package/src/lines.ts +31 -0
  125. package/src/parser.ts +343 -31
  126. package/src/paths.ts +36 -33
  127. package/src/redact.ts +53 -10
  128. package/src/stage0.ts +9 -2
  129. package/src/state.ts +24 -5
  130. package/src/subagents.ts +283 -0
  131. package/src/types.ts +16 -0
package/src/parser.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { createReadStream } from "node:fs";
2
- import { createInterface } from "node:readline";
1
+ import { posix } from "node:path";
2
+ import { fileLines } from "./lines.js";
3
3
  import type {
4
4
  ContentBlock,
5
5
  FileEdit,
@@ -13,20 +13,54 @@ import type {
13
13
  export const EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
14
14
  export const LOOKUP_TOOLS = new Set(["Read", "Grep", "Glob"]);
15
15
 
16
+ /**
17
+ * Every record type Claude Code writes to a session file: the table its 2.1.285
18
+ * session writer routes each append by, plus `progress`, which older builds
19
+ * wrote inline. A type outside it is kept and counted in `skipped.unknownTypes`,
20
+ * which is what `isy status` reports as records it could not place — so a type
21
+ * missing here reads to the user as a transcript this client half-understood.
22
+ */
16
23
  const KNOWN_RECORD_TYPES = new Set([
17
24
  "user",
18
25
  "assistant",
19
26
  "attachment",
20
27
  "system",
28
+ "progress",
29
+ "summary",
30
+ "custom-title",
21
31
  "ai-title",
22
32
  "agent-name",
33
+ "agent-color",
34
+ "agent-setting",
35
+ "tag",
36
+ "relocated",
37
+ "ended-by-model",
38
+ "continued-in",
23
39
  "mode",
24
40
  "permission-mode",
41
+ "memory-mode",
42
+ "isolation-latch",
43
+ "atis-latch",
44
+ "dev-mods",
25
45
  "queue-operation",
26
46
  "last-prompt",
27
47
  "bridge-session",
48
+ "pr-link",
49
+ "frame-link",
50
+ "worktree-state",
51
+ "cost-state",
52
+ "history-suppression",
53
+ "artifact-comment-monitor",
54
+ "artifact-autoreact-ledger",
28
55
  "file-history-snapshot",
29
56
  "file-history-delta",
57
+ "attribution-snapshot",
58
+ "content-replacement",
59
+ "api-request",
60
+ "api-request-shape",
61
+ "api-request-blob",
62
+ "fork-context-ref",
63
+ "observer-ref",
30
64
  ]);
31
65
 
32
66
  interface ParseState {
@@ -38,9 +72,17 @@ interface ParseState {
38
72
  filesRead: Set<string>;
39
73
  skipped: SkipStats;
40
74
  thinkingBlocks: number;
75
+ hiddenThinkingBlocks: number;
41
76
  editToolUses: number;
42
77
  shellWrote: boolean;
43
- sawUnknownTool: boolean;
78
+ /** A call the parser cannot see into that could have written a file (`mayWrite`). */
79
+ opaqueWrite: boolean;
80
+ /** A subagent's result says it edited files, whether or not its own records came along. */
81
+ delegatedEdits: boolean;
82
+ /** Calls whose subagent's own records are in the stream (`parentToolUseID`). */
83
+ delegated: Set<string>;
84
+ /** Calls whose result counted the subagent's edits, whatever the count. */
85
+ counted: Set<string>;
44
86
  }
45
87
 
46
88
  function isObject(value: unknown): value is Record<string, unknown> {
@@ -51,6 +93,11 @@ function asString(value: unknown): string | undefined {
51
93
  return typeof value === "string" && value.length > 0 ? value : undefined;
52
94
  }
53
95
 
96
+ /** A string as written, empty included: `new_string: ""` is how an edit deletes lines. */
97
+ function asText(value: unknown): string | undefined {
98
+ return typeof value === "string" ? value : undefined;
99
+ }
100
+
54
101
  function createState(): ParseState {
55
102
  return {
56
103
  records: [],
@@ -61,9 +108,13 @@ function createState(): ParseState {
61
108
  filesRead: new Set(),
62
109
  skipped: { lines: 0, blank: 0, malformedJson: 0, notAnObject: 0, unknownTypes: {} },
63
110
  thinkingBlocks: 0,
111
+ hiddenThinkingBlocks: 0,
64
112
  editToolUses: 0,
65
113
  shellWrote: false,
66
- sawUnknownTool: false,
114
+ opaqueWrite: false,
115
+ delegatedEdits: false,
116
+ delegated: new Set(),
117
+ counted: new Set(),
67
118
  };
68
119
  }
69
120
 
@@ -129,14 +180,14 @@ function pushFileEdits(state: ParseState, use: ToolUse): void {
129
180
  entries.push({
130
181
  ...base,
131
182
  oldString: asString(edit.old_string),
132
- newString: asString(edit.new_string),
183
+ newString: asText(edit.new_string),
133
184
  });
134
185
  }
135
186
  } else {
136
187
  entries.push({
137
188
  ...base,
138
189
  oldString: asString(use.input.old_string),
139
- newString: asString(use.input.new_string) ?? asString(use.input.new_source),
190
+ newString: asText(use.input.new_string) ?? asText(use.input.new_source),
140
191
  content: asString(use.input.content),
141
192
  });
142
193
  }
@@ -248,20 +299,51 @@ const SHELL_READERS =
248
299
  /^\s*(?:sudo\s+)?(cat|head|tail|less|more|bat|nl|wc|sed|awk|rg|grep|egrep|fgrep|jq|yq|xxd|od|file|stat|diff|git\s+show|git\s+diff|git\s+log|git\s+blame)\b/;
249
300
 
250
301
  /**
251
- * Tools known not to write a file. Anything outside these and the edit tools is
252
- * a name some CLI invented — Kimi's `StrReplaceFile` next to its plain `Grep`,
253
- * the next Codex harness — and the parser cannot say whether it wrote one.
302
+ * Tools known not to write a file: delegation, planning, task lists, schedules,
303
+ * the web, the harness talking to the person. Claude Code's are its 2.1.285
304
+ * inventory together with the names it still accepts for older ones (`Task` is
305
+ * `Agent`, `KillShell` and `KillBash` are `TaskStop`, `Brief` is
306
+ * `SendUserMessage`). A subagent's edits are its own tool calls, spliced into the
307
+ * session (`subagents.ts`), so the call that started it is not one — unless
308
+ * nothing of the subagent came back (`delegatedUnseen`).
254
309
  */
255
310
  const OTHER_KNOWN_TOOLS = new Set([
256
311
  // Claude Code
257
- "Task", "Agent", "TodoWrite", "WebFetch", "WebSearch", "Skill", "AskUserQuestion",
258
- "EnterPlanMode", "ExitPlanMode", "ToolSearch", "BashOutput", "KillShell", "KillBash",
259
- "TaskOutput", "TaskStop", "Monitor", "LS", "NotebookRead", "SlashCommand",
260
- "ListMcpResourcesTool", "ReadMcpResourceTool",
312
+ "Task", "Agent", "SubagentHandback", "SendMessage", "ListAgents", "ListPeers", "Workflow",
313
+ "TodoWrite", "TaskCreate", "TaskUpdate", "TaskGet", "TaskList", "GetTask", "TaskOutput", "TaskStop",
314
+ "BashOutput", "KillShell", "KillBash", "Monitor",
315
+ "WebFetch", "WebSearch", "Skill", "AskUserQuestion", "EnterPlanMode", "ExitPlanMode", "ToolSearch",
316
+ "EnterWorktree", "ExitWorktree", "CronCreate", "CronDelete", "CronList", "ScheduleWakeup", "RemoteTrigger",
317
+ "SendUserMessage", "Brief", "SendUserFile", "SendFile", "PushNotification", "ReadNotifications",
318
+ "FetchInboxMessage", "ReportFindings", "EndConversation", "Poll", "Sleep", "StructuredOutput", "LSP",
319
+ "Artifact", "ArtifactComments", "ArtifactData", "DesignSync", "ClaudeDesign", "Projects",
320
+ "SuggestSkills", "SuggestPluginInstall", "SuggestConnectors", "SearchMcpRegistry", "ListConnectors",
321
+ "ListPlugins", "ListSkills", "SearchPlugins", "SearchSkills", "ShowOnboardingRolePicker",
322
+ "ShareOnboardingGuide", "LS", "NotebookRead", "SlashCommand",
323
+ "ListMcpResources", "ListMcpResourcesTool", "ReadMcpResource", "ReadMcpResourceTool",
324
+ "ReadMcpResourceDir", "ReadMcpResourceDirTool",
261
325
  // Codex, kept under its own name by agents/codex-records.ts
262
326
  "update_plan", "view_image", "web_search", "web__run", "image_gen__imagegen", "wait",
327
+ // Kimi, where agents/kimi-tools.ts has no Claude name to give: `GetGoal`
328
+ // takes no arguments, which alone would read as a possible edit. The Tower
329
+ // tools run Kimi Code's multi-agent workspace: they plan, message and review
330
+ // under `.tower/`, and their workers are subagents like any other.
331
+ "Think", "SendDMail", "AgentSwarm", "WaitFor", "CreateGoal", "GetGoal", "UpdateGoal", "SetGoalBudget",
332
+ "TowerInit", "TowerPlan", "TowerSpawn", "TowerSend", "TowerInbox", "TowerFinding", "TowerReview",
333
+ "TowerMission", "TowerStatus", "TowerTeardown",
263
334
  ]);
264
335
 
336
+ /** Tools that run code of their own, which writes wherever it says: a shell the parser cannot read. */
337
+ const CODE_RUNNERS = new Set(["PowerShell", "REPL", "JavaScript"]);
338
+
339
+ /**
340
+ * Tools that change files without naming them in an argument `mayWrite` reads:
341
+ * Codex's `apply_patch`, as `codex-records.ts` passes it on when the patch
342
+ * would not parse (the files are inside `input`), and Kimi Code's `TowerMerge`,
343
+ * a git merge of a worker's branch into the checkout.
344
+ */
345
+ const UNNAMED_WRITERS = new Set(["apply_patch", "TowerMerge"]);
346
+
265
347
  function isKnownTool(name: string): boolean {
266
348
  return (
267
349
  EDIT_TOOLS.has(name) ||
@@ -272,6 +354,56 @@ function isKnownTool(name: string): boolean {
272
354
  );
273
355
  }
274
356
 
357
+ /**
358
+ * Arguments that say what a call works on. A tool that writes a file has to be
359
+ * told which one, or be handed code that decides; a tool that files a task,
360
+ * messages a teammate or opens a worktree is told neither.
361
+ */
362
+ const TARGET_ARGUMENT =
363
+ /^(?:file_?path|filePath|notebook_path|(?:relative_)?path|paths|file|files|filename|target_file|command|cmd|code|script|patch|edits?)$/;
364
+
365
+ /** Words an MCP tool's name carries when it changes something rather than reads it. */
366
+ const MCP_WRITE_VERBS = new Set([
367
+ "write", "edit", "replace", "insert", "patch", "apply", "create", "update", "delete", "remove", "move", "rename", "push",
368
+ ]);
369
+
370
+ /** A tool name's words, whichever way it is spelled: `replace_symbol_body`, `writeFile`, `edit-file`. */
371
+ function nameWords(name: string): string[] {
372
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase().split(/[^a-z0-9]+/);
373
+ }
374
+
375
+ /**
376
+ * Whether a call the parser has no rule for could have written a file.
377
+ *
378
+ * Every Claude Code release adds tools, nearly all of them bookkeeping —
379
+ * `TaskCreate`, `SendMessage`, `EnterWorktree` — and when any unknown name
380
+ * counted as an edit, every session on 2.1 read as one that edited files. So an
381
+ * unknown tool counts only when its arguments could name a file or carry code,
382
+ * or when there are none to read: arguments an adapter could not parse are not
383
+ * arguments that say nothing. A tool an adapter has no Claude name for,
384
+ * told a `path`, and a Codex `exec {script}` still count; `TaskCreate {subject}`
385
+ * does not.
386
+ *
387
+ * An MCP tool is named by its server, and most of them only read — a
388
+ * filesystem server's `read_file {path}`, GitHub's `get_file_contents {path}`.
389
+ * One counts when its name says it changes something and it is told where:
390
+ * `write_file {path}`, Serena's `replace_symbol_body {relative_path}`.
391
+ *
392
+ * ponytail: judged by names. A writer that takes its file under an argument
393
+ * outside `TARGET_ARGUMENT`, or an MCP writer whose name has none of
394
+ * `MCP_WRITE_VERBS`, reads as no edit; add the name when a CLI or server ships one.
395
+ */
396
+ export function mayWrite(name: string, input: Record<string, unknown>): boolean {
397
+ if (CODE_RUNNERS.has(name) || UNNAMED_WRITERS.has(name)) return true;
398
+ const keys = Object.keys(input);
399
+ const told = keys.some((key) => TARGET_ARGUMENT.test(key));
400
+ if (name.startsWith("mcp__")) {
401
+ return told && nameWords(name.slice(name.lastIndexOf("__") + 2)).some((word) => MCP_WRITE_VERBS.has(word));
402
+ }
403
+ if (isKnownTool(name)) return false;
404
+ return keys.length === 0 || told;
405
+ }
406
+
275
407
  /** A redirect into a file: `> a.ts`, `>> log`, `2> out`. Not `2>&1`, not `/dev/null`. */
276
408
  const REDIRECT_WRITE = /(?:^|[^<>&\d])\d*>>?(?!&)\s*(?!\/dev\/|\/tmp\/)[^\s&|;<>]/;
277
409
  const TEE_WRITE = /\btee\s+(?:-a\s+)?(?!\/dev\/|\/tmp\/)[^\s&|;-]/;
@@ -310,8 +442,12 @@ export function shellWrites(command: string): boolean {
310
442
  return false;
311
443
  }
312
444
 
313
- /** `sed -i` rewrites the file; whatever else it is, it is not a look at it. */
314
- const IN_PLACE = /(?:^|\s)(?:-i(?:\.\S+)?|--in-place)(?:\s|$)/;
445
+ /**
446
+ * `sed -i` rewrites the file; whatever else it is, it is not a look at it. GNU
447
+ * takes any backup suffix (`-i.bak`, `-ie`), the flag rides in a cluster
448
+ * (`-Ei`), and BSD spells it `-I`.
449
+ */
450
+ const IN_PLACE = /(?:^|\s)(?:-[a-zA-Z]*[iI]\S*|--in-place\S*)(?:\s|$)/;
315
451
 
316
452
  /** Tools whose first non-flag argument is a program, not a path. */
317
453
  const SCRIPTED = /^\s*(?:sudo\s+)?(?:sed|awk)\b/;
@@ -321,7 +457,8 @@ export function shellReadPaths(command: string): string[] {
321
457
 
322
458
  for (const segment of commandSegments(withoutHeredocs(command))) {
323
459
  if (!SHELL_READERS.test(segment)) continue;
324
- if (IN_PLACE.test(segment)) continue;
460
+ // Only sed's: `grep -i foo src/a.ts` is a look, and was taken for a write.
461
+ if (SCRIPTED.test(segment) && IN_PLACE.test(segment)) continue;
325
462
 
326
463
  // `sed 's/^/UNPUSHED: /'` has slashes in it and is not a path: read as one
327
464
  // it yields "/", which then matches every absolute path there is.
@@ -337,8 +474,9 @@ export function shellReadPaths(command: string): string[] {
337
474
  continue;
338
475
  }
339
476
 
477
+ // A glob stays one: `cat src/*.js` read every file it expanded to, and
478
+ // `detectors.ts:samePath` matches it against the file edited.
340
479
  const path = token.includes(":") ? token.slice(token.lastIndexOf(":") + 1) : token;
341
- if (path.includes("*") || path.includes("?")) continue;
342
480
  // "/" and "." name no file, and "/" matches every path there is.
343
481
  if (/^[./]+$/.test(path)) continue;
344
482
  if (!/\.[A-Za-z0-9]+$/.test(path) && !path.includes("/")) continue;
@@ -350,6 +488,97 @@ export function shellReadPaths(command: string): string[] {
350
488
  return paths;
351
489
  }
352
490
 
491
+ /** A shell word, quotes and all: `'s/a b/c/'` is one word, not two. */
492
+ const SHELL_WORD = /(?:'[^']*'|"(?:[^"\\]|\\.)*"|[^\s'"])+/g;
493
+
494
+ /**
495
+ * Flags whose next word is the script, not a file. Only the bare ones for sed:
496
+ * `sed -ie` is `-i` with the backup suffix "e", while `perl -pe` is `-p -e`.
497
+ */
498
+ const SED_SCRIPT_FLAG = /^(?:-e|--expression|-f|--file)$/;
499
+ const PERL_SCRIPT_FLAG = /^-[a-zA-Z]*e$/;
500
+
501
+ /**
502
+ * The files `sed -i` and `perl -i` rewrite: every argument after the script.
503
+ * What the edit changed stays unseen — a sed script is a program, not the text
504
+ * it replaces — but where it landed is on the command line, and without it a
505
+ * session editing through sed read to the detectors as one that edited nothing.
506
+ *
507
+ * Given the directory the command ran in, a relative path is resolved against
508
+ * it, `cd` within the command included, so `sed -i` and Edit on one file land
509
+ * under one key — before masking (both absolute) and after (both relative to
510
+ * a working directory of "."). Without it, or past a `cd` it cannot follow
511
+ * (`cd ~`, `cd -`, `cd $DIR`), paths stay as typed, like `shellReadPaths`.
512
+ *
513
+ * ponytail: in-place editors only. A redirect, `tee` or a heredoc into python
514
+ * still names no file to the detectors (`shellWrites` knows only that one was
515
+ * written); a glob names files this cannot list.
516
+ */
517
+ export function shellEditPaths(command: string, cwd?: string): string[] {
518
+ const paths: string[] = [];
519
+ let dir = cwd;
520
+
521
+ for (const segment of commandSegments(withoutHeredocs(command))) {
522
+ if (/^\s*cd(?:\s|$)/.test(segment)) {
523
+ const to = /^\s*cd\s+(\S+)\s*$/.exec(segment)?.[1]?.replace(/["']/g, "");
524
+ if (to?.startsWith("/")) dir = posix.normalize(to);
525
+ else dir = dir === undefined || to === undefined || /^[~$-]/.test(to) ? undefined : posix.join(dir, to);
526
+ continue;
527
+ }
528
+ if (!IN_PLACE_EDITORS.test(segment)) continue;
529
+ const perl = /^\s*(?:sudo\s+)?perl\b/.test(segment);
530
+ // The same test `shellWrites` applies, on the same unquoted text, so the two
531
+ // agree on what was written: `sed 's/ -i //' a.ts` only prints.
532
+ const bare = segment.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, "''");
533
+ if (!(perl ? /\bperl\s+-\w*i/.test(bare) : IN_PLACE.test(bare))) continue;
534
+
535
+ let scriptSeen = false;
536
+ let scriptNext = false;
537
+ const words = segment.replace(/^\s*sudo\s+/, "").match(SHELL_WORD) ?? [];
538
+ for (const word of words.slice(1)) {
539
+ if (/^\d*[<>|]|^&/.test(word)) break;
540
+ const token = word.replace(/["']/g, "");
541
+ if (scriptNext) {
542
+ scriptNext = false;
543
+ continue;
544
+ }
545
+ if ((perl ? PERL_SCRIPT_FLAG : SED_SCRIPT_FLAG).test(token)) {
546
+ scriptSeen = true;
547
+ scriptNext = true;
548
+ continue;
549
+ }
550
+ if (/^--(?:expression|file)=/.test(token)) scriptSeen = true;
551
+ // An empty word is BSD sed's backup suffix: `sed -i '' 's/a/b/' f`.
552
+ if (token.length === 0 || token.startsWith("-") || token.startsWith("$")) continue;
553
+ if (!scriptSeen) {
554
+ scriptSeen = true;
555
+ continue;
556
+ }
557
+ if (/[*?]/.test(token) || /^[./]+$/.test(token)) continue;
558
+ if (dir === undefined || token.startsWith("~")) paths.push(token.replace(/^\.\//, ""));
559
+ else paths.push(token.startsWith("/") ? posix.normalize(token) : posix.join(dir, token));
560
+ }
561
+ }
562
+
563
+ return paths;
564
+ }
565
+
566
+ function pushShellEdits(state: ParseState, use: ToolUse, command: string, cwd: unknown): void {
567
+ for (const filePath of shellEditPaths(command, asString(cwd))) {
568
+ const edit: FileEdit = {
569
+ toolUseId: use.id,
570
+ tool: use.name,
571
+ filePath,
572
+ recordIndex: use.recordIndex,
573
+ uuid: use.uuid,
574
+ timestamp: use.timestamp,
575
+ };
576
+ const existing = state.fileEdits.get(filePath);
577
+ if (existing) existing.push(edit);
578
+ else state.fileEdits.set(filePath, [edit]);
579
+ }
580
+ }
581
+
353
582
  function pushToolUse(
354
583
  state: ParseState,
355
584
  record: TranscriptRecord,
@@ -381,9 +610,10 @@ function pushToolUse(
381
610
  if (name === "Bash" && typeof use.input.command === "string") {
382
611
  for (const path of shellReadPaths(use.input.command)) state.filesRead.add(path);
383
612
  if (shellWrites(use.input.command)) state.shellWrote = true;
613
+ pushShellEdits(state, use, use.input.command, record.cwd);
384
614
  }
385
615
 
386
- if (!isKnownTool(name)) state.sawUnknownTool = true;
616
+ if (mayWrite(name, use.input)) state.opaqueWrite = true;
387
617
  }
388
618
 
389
619
  function pushBlocks(state: ParseState, record: TranscriptRecord, recordIndex: number): void {
@@ -408,16 +638,72 @@ function pushBlocks(state: ParseState, record: TranscriptRecord, recordIndex: nu
408
638
  raw: item,
409
639
  });
410
640
 
411
- if (type === "thinking") state.thinkingBlocks += 1;
641
+ // Reasoning counts when there is something in it to read. Claude Code 2.1
642
+ // records most thinking with the text left out — only the signature — and
643
+ // `redacted_thinking` is encrypted outright: both show the model thought,
644
+ // neither says what, so neither makes `known_gap` reachable.
645
+ if (type === "thinking" && typeof item.thinking === "string" && item.thinking.trim().length > 0) {
646
+ state.thinkingBlocks += 1;
647
+ } else if (type === "thinking" || type === "redacted_thinking") {
648
+ state.hiddenThinkingBlocks += 1;
649
+ }
412
650
  if (type === "tool_use") pushToolUse(state, record, item, recordIndex);
413
651
  if (type === "tool_result") {
414
652
  const target = asString(item.tool_use_id);
415
653
  const use = target ? state.toolUseById.get(target) : undefined;
416
654
  if (use) use.result = buildToolResult(record, item, recordIndex);
655
+ const edited = subagentEdits(record);
656
+ if (edited !== undefined && target) state.counted.add(target);
657
+ if (edited !== undefined && edited > 0) state.delegatedEdits = true;
417
658
  }
418
659
  }
419
660
  }
420
661
 
662
+ /**
663
+ * How many files a subagent's result says it edited. Claude Code 2.1 keeps a
664
+ * subagent's calls in a file of its own and totals them on the call's result
665
+ * (`toolStats.editFileCount`), so a session uploaded without that file — by a
666
+ * client older than the splicing in `subagents.ts` — still says it touched files.
667
+ * Only a subagent that ran to the end is counted: one sent to the background
668
+ * answers at once, with no total (`delegatedUnseen`).
669
+ */
670
+ function subagentEdits(record: TranscriptRecord): number | undefined {
671
+ const detail = isObject(record.toolUseResult) ? record.toolUseResult : undefined;
672
+ const stats = detail && isObject(detail.toolStats) ? detail.toolStats : undefined;
673
+ return typeof stats?.editFileCount === "number" ? stats.editFileCount : undefined;
674
+ }
675
+
676
+ /**
677
+ * Tools that hand work to subagents whose records come back linked to the call
678
+ * (`parentToolUseID`): Claude's, which Kimi's `Agent` is translated to, and
679
+ * Kimi Code's `AgentSwarm` and `TowerSpawn`, whose subagents it links the same way.
680
+ */
681
+ const DELEGATION_TOOLS = new Set(["Agent", "Task", "AgentSwarm", "TowerSpawn"]);
682
+
683
+ /**
684
+ * Whether a subagent was sent off and neither its records nor a count of its
685
+ * edits came back: a background subagent's result is only "launched", and a
686
+ * session uploaded without the subagent's file — by an older client, or with
687
+ * the file gone — carries nothing else of it. What it did cannot be seen, so
688
+ * it may have edited. A call that failed started nothing.
689
+ */
690
+ function delegatedUnseen(state: ParseState): boolean {
691
+ return state.toolUses.some(
692
+ (use) =>
693
+ DELEGATION_TOOLS.has(use.name) &&
694
+ use.result?.isError !== true &&
695
+ !state.delegated.has(use.id) &&
696
+ !state.counted.has(use.id),
697
+ );
698
+ }
699
+
700
+ /**
701
+ * Records of what Claude Code sent to the API, not of what happened: a blob
702
+ * repeats messages already in the session — tool calls and results included —
703
+ * so reading its blocks counted every call it carried a second time.
704
+ */
705
+ const REQUEST_RECORD_TYPES = new Set(["api-request", "api-request-shape", "api-request-blob"]);
706
+
421
707
  function pushLine(state: ParseState, line: string): void {
422
708
  state.skipped.lines += 1;
423
709
 
@@ -447,7 +733,10 @@ function pushLine(state: ParseState, line: string): void {
447
733
 
448
734
  const record = { ...parsed, type } as TranscriptRecord;
449
735
  state.records.push(record);
450
- pushBlocks(state, record, state.records.length - 1);
736
+ if (record.isSidechain === true && typeof record.parentToolUseID === "string") {
737
+ state.delegated.add(record.parentToolUseID);
738
+ }
739
+ if (!REQUEST_RECORD_TYPES.has(type)) pushBlocks(state, record, state.records.length - 1);
451
740
  }
452
741
 
453
742
  function buildByUuid(records: TranscriptRecord[]): Map<string, TranscriptRecord> {
@@ -458,6 +747,18 @@ function buildByUuid(records: TranscriptRecord[]): Map<string, TranscriptRecord>
458
747
  return byUuid;
459
748
  }
460
749
 
750
+ /**
751
+ * The record this one continues. Its parent — or, where a compaction started the
752
+ * chain over, the record the compaction summarised: Claude Code writes the
753
+ * `compact_boundary` with no parent and names what it follows in
754
+ * `logicalParentUuid`. Walking parents alone stopped at the boundary, and the
755
+ * whole session before its last compaction fell off the main path.
756
+ */
757
+ function parentOf(record: TranscriptRecord): string | undefined {
758
+ if (typeof record.parentUuid === "string") return record.parentUuid;
759
+ return typeof record.logicalParentUuid === "string" ? record.logicalParentUuid : undefined;
760
+ }
761
+
461
762
  function buildMainPath(
462
763
  records: TranscriptRecord[],
463
764
  byUuid: Map<string, TranscriptRecord>,
@@ -475,7 +776,8 @@ function buildMainPath(
475
776
  let current = tip;
476
777
  while (current && typeof current.uuid === "string" && !path.has(current.uuid)) {
477
778
  path.add(current.uuid);
478
- current = typeof current.parentUuid === "string" ? byUuid.get(current.parentUuid) : undefined;
779
+ const parent = parentOf(current);
780
+ current = parent === undefined ? undefined : byUuid.get(parent);
479
781
  }
480
782
  return path;
481
783
  }
@@ -523,11 +825,18 @@ function finish(state: ParseState): ParsedSession {
523
825
  endedAt,
524
826
  assistantRecords,
525
827
  thinkingBlocks: state.thinkingBlocks,
828
+ hiddenThinkingBlocks: state.hiddenThinkingBlocks,
526
829
  editToolUses: state.editToolUses,
527
830
  // Not the same question as editToolUses > 0: a file written from the
528
- // shell counts, and a tool this parser does not know is "cannot tell",
529
- // which must not read as "edited nothing".
530
- hasFileEdits: state.editToolUses > 0 || state.shellWrote || state.sawUnknownTool,
831
+ // shell counts, a call the parser cannot see into is "cannot tell", which
832
+ // must not read as "edited nothing", and so is a subagent that says it
833
+ // edited, or whose work never came back to say.
834
+ hasFileEdits:
835
+ state.editToolUses > 0 ||
836
+ state.shellWrote ||
837
+ state.opaqueWrite ||
838
+ state.delegatedEdits ||
839
+ delegatedUnseen(state),
531
840
  sidechainRecords,
532
841
  },
533
842
  skipped: state.skipped,
@@ -540,12 +849,15 @@ export function parseLines(lines: Iterable<string>): ParsedSession {
540
849
  return finish(state);
541
850
  }
542
851
 
543
- export async function parseTranscriptFile(filePath: string): Promise<ParsedSession> {
852
+ /** `parseLines` for lines that arrive one at a time, as a stream or a generator does. */
853
+ export async function parseLineStream(lines: AsyncIterable<string>): Promise<ParsedSession> {
544
854
  const state = createState();
545
- const input = createReadStream(filePath, { encoding: "utf8" });
546
- const reader = createInterface({ input, crlfDelay: Infinity });
547
- for await (const line of reader) pushLine(state, line);
548
- const session = finish(state);
855
+ for await (const line of lines) pushLine(state, line);
856
+ return finish(state);
857
+ }
858
+
859
+ export async function parseTranscriptFile(filePath: string): Promise<ParsedSession> {
860
+ const session = await parseLineStream(fileLines(filePath));
549
861
  session.filePath = filePath;
550
862
  return session;
551
863
  }
@@ -563,8 +875,8 @@ export function onAbandonedBranch(session: ParsedSession, uuid: string | undefin
563
875
 
564
876
  while (current && typeof current.uuid === "string" && !visited.has(current.uuid)) {
565
877
  visited.add(current.uuid);
566
- const parent = current.parentUuid;
567
- if (typeof parent !== "string") return false;
878
+ const parent = parentOf(current);
879
+ if (parent === undefined) return false;
568
880
  if (session.mainPath.has(parent)) return true;
569
881
  current = session.byUuid.get(parent);
570
882
  }
package/src/paths.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { createReadStream } from "node:fs";
2
1
  import { readFile, readdir, stat } from "node:fs/promises";
3
- import { createInterface } from "node:readline";
4
2
  import { homedir } from "node:os";
5
3
  import { basename, join } from "node:path";
4
+ import { fileLines } from "./lines.js";
5
+ import { sessionFingerprint } from "./subagents.js";
6
6
  import type { SessionFile } from "./types.js";
7
7
 
8
8
  export async function packageVersion(): Promise<string> {
@@ -80,11 +80,15 @@ async function sessionsInDir(dir: string): Promise<SessionFile[]> {
80
80
  try {
81
81
  const info = await stat(path);
82
82
  if (!info.isFile()) continue;
83
+ // Size and mtime of the session as a whole: its subagents write files of
84
+ // their own, and a sweep compares against these to decide what grew.
85
+ const whole = await sessionFingerprint(path);
83
86
  sessions.push({
84
87
  sessionId: basename(entry, ".jsonl"),
85
88
  path,
86
- sizeBytes: info.size,
87
- modifiedAt: info.mtime,
89
+ sizeBytes: whole.sizeBytes,
90
+ modifiedAt: whole.modifiedAt,
91
+ activeAt: info.mtime,
88
92
  });
89
93
  } catch {
90
94
  continue;
@@ -94,8 +98,13 @@ async function sessionsInDir(dir: string): Promise<SessionFile[]> {
94
98
  return sessions;
95
99
  }
96
100
 
101
+ /** When a session itself last wrote (`SessionFile.activeAt`), for ordering sessions by recency. */
102
+ export function lastActive(file: SessionFile): number {
103
+ return (file.activeAt ?? file.modifiedAt).getTime();
104
+ }
105
+
97
106
  function newestFirst(sessions: SessionFile[]): SessionFile[] {
98
- return sessions.sort((a, b) => b.modifiedAt.getTime() - a.modifiedAt.getTime());
107
+ return sessions.sort((a, b) => lastActive(b) - lastActive(a));
99
108
  }
100
109
 
101
110
  export async function findSessions(cwd: string): Promise<SessionFile[]> {
@@ -144,41 +153,35 @@ const CWD_SCAN_LINES = 40;
144
153
  * same field `mask-paths` roots its rewriting on.
145
154
  */
146
155
  export async function firstCwd(path: string, limit = CWD_SCAN_LINES): Promise<string | undefined> {
147
- const input = createReadStream(path, { encoding: "utf8" });
148
- const reader = createInterface({ input, crlfDelay: Infinity });
149
-
150
- try {
151
- let seen = 0;
152
- for await (const line of reader) {
153
- if (seen++ >= limit) return undefined;
154
- if (line.length === 0) continue;
155
- try {
156
- const parsed: unknown = JSON.parse(line);
157
- if (typeof parsed !== "object" || parsed === null) continue;
158
- const cwd = (parsed as { cwd?: unknown }).cwd;
159
- if (typeof cwd === "string" && cwd.length > 0) return cwd;
160
- } catch {
161
- continue;
162
- }
156
+ let seen = 0;
157
+ for await (const line of fileLines(path)) {
158
+ if (seen++ >= limit) return undefined;
159
+ if (line.length === 0) continue;
160
+ try {
161
+ const parsed: unknown = JSON.parse(line);
162
+ if (typeof parsed !== "object" || parsed === null) continue;
163
+ const cwd = (parsed as { cwd?: unknown }).cwd;
164
+ if (typeof cwd === "string" && cwd.length > 0) return cwd;
165
+ } catch {
166
+ continue;
163
167
  }
164
- return undefined;
165
- } finally {
166
- reader.close();
167
- input.destroy();
168
168
  }
169
+ return undefined;
169
170
  }
170
171
 
171
172
  /** The first line of a file, without reading the rest: transcripts get large. */
172
173
  export async function firstLine(path: string): Promise<string> {
173
- const input = createReadStream(path, { encoding: "utf8" });
174
- const reader = createInterface({ input, crlfDelay: Infinity });
175
- try {
176
- for await (const line of reader) return line;
177
- return "";
178
- } finally {
179
- reader.close();
180
- input.destroy();
174
+ return (await firstLines(path, 1))[0] ?? "";
175
+ }
176
+
177
+ /** The first `count` lines of a file, without reading the rest. */
178
+ export async function firstLines(path: string, count: number): Promise<string[]> {
179
+ const lines: string[] = [];
180
+ for await (const line of fileLines(path)) {
181
+ lines.push(line);
182
+ if (lines.length >= count) break;
181
183
  }
184
+ return lines;
182
185
  }
183
186
 
184
187
  /**