@nightloom/isy 1.0.1 → 1.0.3

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