@zyro-sec/session-ui 0.0.0-stage → 1.0.4

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 (261) hide show
  1. package/AGENTS.md +25 -0
  2. package/bunfig.toml +2 -0
  3. package/component-tests/basic-tool.fixture.tsx +46 -0
  4. package/component-tests/basic-tool.spec.ts +63 -0
  5. package/component-tests/file-media.fixture.tsx +39 -0
  6. package/component-tests/file-media.spec.ts +13 -0
  7. package/component-tests/file-tool.spec.ts +62 -0
  8. package/component-tests/file-viewer.fixture.tsx +109 -0
  9. package/component-tests/file-viewer.spec.ts +134 -0
  10. package/component-tests/file.spec.ts +33 -0
  11. package/component-tests/line-comment-v2.spec.ts +15 -0
  12. package/component-tests/markdown-code-wrap.spec.ts +94 -0
  13. package/component-tests/markdown-readiness.spec.ts +95 -0
  14. package/component-tests/markdown.fixture.tsx +104 -0
  15. package/component-tests/markdown.spec.ts +1564 -0
  16. package/component-tests/mermaid-preview.spec.ts +43 -0
  17. package/component-tests/patch-group.spec.ts +79 -0
  18. package/component-tests/read-group.spec.ts +72 -0
  19. package/component-tests/read-image.fixture.tsx +66 -0
  20. package/component-tests/read-image.spec.ts +154 -0
  21. package/component-tests/session-compaction.spec.ts +254 -0
  22. package/component-tests/session-lifecycle.spec.ts +190 -0
  23. package/component-tests/session-message-projection.spec.ts +639 -0
  24. package/component-tests/session-notice-projection.spec.ts +20 -0
  25. package/component-tests/session-review-comments.spec.ts +179 -0
  26. package/component-tests/session-shell.spec.ts +93 -0
  27. package/component-tests/session-timeline-mobile.spec.ts +201 -0
  28. package/component-tests/session-timeline-notices.spec.ts +38 -0
  29. package/component-tests/session-timeline-reasoning.spec.ts +107 -0
  30. package/component-tests/session-timeline.spec.ts +157 -0
  31. package/component-tests/session-tool-projection.spec.ts +323 -0
  32. package/component-tests/text-lifecycle.fixture.tsx +26 -0
  33. package/component-tests/text-lifecycle.spec.ts +42 -0
  34. package/component-tests/timeline-subagent-rows.spec.ts +33 -0
  35. package/component-tests/tool-disclosure.spec.ts +48 -0
  36. package/component-tests/tool-group-sticky.spec.ts +37 -0
  37. package/component-tests/tool-group.spec.ts +290 -0
  38. package/component-tests/tool-status-title.fixture.tsx +22 -0
  39. package/component-tests/tool-status-title.spec.ts +30 -0
  40. package/component-tests/user-message-quotes.spec.ts +111 -0
  41. package/package.json +91 -4
  42. package/playwright.components.config.ts +4 -0
  43. package/playwright.local.config.ts +2 -0
  44. package/src/actions.ts +54 -0
  45. package/src/components/apply-patch-file.ts +122 -0
  46. package/src/components/basic-tool.css +487 -0
  47. package/src/components/basic-tool.tsx +258 -0
  48. package/src/components/copy-machine.ts +78 -0
  49. package/src/components/copy.ts +85 -0
  50. package/src/components/diagram-preview.tsx +28 -0
  51. package/src/components/disclosure-machine.ts +188 -0
  52. package/src/components/disclosure.ts +129 -0
  53. package/src/components/dock-prompt.stories.tsx +73 -0
  54. package/src/components/dock-prompt.tsx +29 -0
  55. package/src/components/file-comment-selection.tsx +146 -0
  56. package/src/components/file-media-machine.ts +165 -0
  57. package/src/components/file-media.stories.tsx +112 -0
  58. package/src/components/file-media.tsx +323 -0
  59. package/src/components/file-search.tsx +73 -0
  60. package/src/components/file.css +59 -0
  61. package/src/components/file.tsx +1300 -0
  62. package/src/components/image-preview.tsx +35 -0
  63. package/src/components/line-comment-annotations.tsx +580 -0
  64. package/src/components/line-comment-machine.ts +262 -0
  65. package/src/components/line-comment-styles.ts +293 -0
  66. package/src/components/line-comment.stories.tsx +152 -0
  67. package/src/components/line-comment.tsx +448 -0
  68. package/src/components/link-segments.ts +20 -0
  69. package/src/components/linked-text.tsx +21 -0
  70. package/src/components/markdown-cache-machine.ts +257 -0
  71. package/src/components/markdown-cache.tsx +556 -0
  72. package/src/components/markdown-clipboard.ts +101 -0
  73. package/src/components/markdown-code-machine.ts +200 -0
  74. package/src/components/markdown-code-state.ts +22 -0
  75. package/src/components/markdown-fragment-links.ts +74 -0
  76. package/src/components/markdown-github.svg +3 -0
  77. package/src/components/markdown-globe.svg +5 -0
  78. package/src/components/markdown-image-machine.ts +170 -0
  79. package/src/components/markdown-image.ts +156 -0
  80. package/src/components/markdown-inline-code-kind.ts +39 -0
  81. package/src/components/markdown-mermaid.ts +18 -0
  82. package/src/components/markdown-phase-machine.ts +102 -0
  83. package/src/components/markdown-projection.ts +13 -0
  84. package/src/components/markdown-session-links.ts +183 -0
  85. package/src/components/markdown-solid.test.tsx +92 -0
  86. package/src/components/markdown-solid.tsx +113 -0
  87. package/src/components/markdown-stream.ts +95 -0
  88. package/src/components/markdown-worker-machine.ts +516 -0
  89. package/src/components/markdown-worker-protocol.ts +73 -0
  90. package/src/components/markdown-worker.ts +250 -0
  91. package/src/components/markdown.css +672 -0
  92. package/src/components/markdown.stories.tsx +199 -0
  93. package/src/components/markdown.tsx +1612 -0
  94. package/src/components/markdown.worker.ts +188 -0
  95. package/src/components/message-file.ts +102 -0
  96. package/src/components/message-nav.css +134 -0
  97. package/src/components/message-nav.tsx +159 -0
  98. package/src/components/message-part.css +2109 -0
  99. package/src/components/message-part.tsx +3 -0
  100. package/src/components/question-prompt-experimental.css +576 -0
  101. package/src/components/question-prompt.css +527 -0
  102. package/src/components/quote-highlight.css +59 -0
  103. package/src/components/review-focus-driver.ts +142 -0
  104. package/src/components/review-focus-machine.ts +95 -0
  105. package/src/components/session-compaction.css +270 -0
  106. package/src/components/session-diff.ts +358 -0
  107. package/src/components/session-error.tsx +41 -0
  108. package/src/components/session-retry.tsx +92 -0
  109. package/src/components/session-review-machine.ts +241 -0
  110. package/src/components/session-review.css +264 -0
  111. package/src/components/session-review.stories.tsx +232 -0
  112. package/src/components/session-review.tsx +733 -0
  113. package/src/components/session-turn.css +282 -0
  114. package/src/components/shell-submessage.css +24 -0
  115. package/src/components/timeline-separator.tsx +69 -0
  116. package/src/components/tool-count-label.css +57 -0
  117. package/src/components/tool-count-label.tsx +76 -0
  118. package/src/components/tool-count-summary.css +102 -0
  119. package/src/components/tool-count-summary.stories.tsx +99 -0
  120. package/src/components/tool-count-summary.tsx +44 -0
  121. package/src/components/tool-error-card.css +178 -0
  122. package/src/components/tool-error-card.stories.tsx +113 -0
  123. package/src/components/tool-error-card.tsx +202 -0
  124. package/src/components/tool-status-title-machine.ts +128 -0
  125. package/src/components/tool-status-title.css +89 -0
  126. package/src/components/tool-status-title.tsx +163 -0
  127. package/src/context/data.tsx +107 -0
  128. package/src/context/index.ts +1 -0
  129. package/src/context/markdown.tsx +129 -0
  130. package/src/context/sources.tsx +34 -0
  131. package/src/document.ts +8 -0
  132. package/src/file-presentation.ts +34 -0
  133. package/src/message/action-machine.ts +72 -0
  134. package/src/message/agent-label.ts +3 -0
  135. package/src/message/attachment-card.css +119 -0
  136. package/src/message/attachment-card.tsx +40 -0
  137. package/src/message/attachment-media-machine.ts +213 -0
  138. package/src/message/comment-card.tsx +155 -0
  139. package/src/message/compaction-entrance-machine.ts +93 -0
  140. package/src/message/current-message.tsx +157 -0
  141. package/src/message/current-tool-state.ts +161 -0
  142. package/src/message/message-content.tsx +1391 -0
  143. package/src/message/paced-text-machine.ts +73 -0
  144. package/src/message/prompt-message.stories.tsx +149 -0
  145. package/src/message/relative-time.ts +45 -0
  146. package/src/message/user-message-quote-parts.ts +16 -0
  147. package/src/message/user-message-quotes.stories.tsx +797 -0
  148. package/src/message/user-message-quotes.tsx +135 -0
  149. package/src/pierre/comment-hover-machine.ts +53 -0
  150. package/src/pierre/comment-hover.ts +131 -0
  151. package/src/pierre/comment-selection-machine.ts +257 -0
  152. package/src/pierre/commented-lines.ts +106 -0
  153. package/src/pierre/diff-selection.ts +91 -0
  154. package/src/pierre/file-find-machine.ts +323 -0
  155. package/src/pierre/file-find.ts +537 -0
  156. package/src/pierre/file-runtime.ts +42 -0
  157. package/src/pierre/file-selection.ts +140 -0
  158. package/src/pierre/index.ts +344 -0
  159. package/src/pierre/media.ts +140 -0
  160. package/src/pierre/render-machine.ts +381 -0
  161. package/src/pierre/selection-bridge.ts +82 -0
  162. package/src/pierre/selection-machine.ts +198 -0
  163. package/src/pierre/virtualizer.ts +114 -0
  164. package/src/pierre/worker.ts +46 -0
  165. package/src/sources/experiment.ts +59 -0
  166. package/src/sources/site-icon.tsx +53 -0
  167. package/src/sources/sources-chip.tsx +57 -0
  168. package/src/sources/sources-expand-machine.ts +101 -0
  169. package/src/sources/sources-panel.tsx +249 -0
  170. package/src/sources/sources-title.tsx +21 -0
  171. package/src/sources/sources.css +266 -0
  172. package/src/sources/sources.ts +141 -0
  173. package/src/storybook/current-session-fixtures.ts +1492 -0
  174. package/src/storybook/current-session-scenarios.ts +76 -0
  175. package/src/storybook/current-session-story.tsx +154 -0
  176. package/src/storybook/index.ts +43 -0
  177. package/src/styles/index.css +19 -0
  178. package/src/timeline/__snapshots__/group-labels.test.ts.snap +110 -0
  179. package/src/timeline/__snapshots__/placement.test.ts.snap +1041 -0
  180. package/src/timeline/code-blocks.stories.tsx +105 -0
  181. package/src/timeline/commentary.stories.tsx +70 -0
  182. package/src/timeline/commentary.ts +38 -0
  183. package/src/timeline/detail.ts +111 -0
  184. package/src/timeline/error-card.stories.tsx +134 -0
  185. package/src/timeline/error-spacing.stories.tsx +71 -0
  186. package/src/timeline/facts.ts +493 -0
  187. package/src/timeline/file-changes.stories.tsx +436 -0
  188. package/src/timeline/group-label-fixtures.ts +97 -0
  189. package/src/timeline/mermaid.stories.tsx +131 -0
  190. package/src/timeline/place.ts +280 -0
  191. package/src/timeline/placement-fixtures.ts +365 -0
  192. package/src/timeline/placement-reactivity.ts +133 -0
  193. package/src/timeline/projection.ts +1261 -0
  194. package/src/timeline/research-and-agents.stories.tsx +461 -0
  195. package/src/timeline/session-timeline-row.tsx +1675 -0
  196. package/src/timeline/session-timeline.tsx +68 -0
  197. package/src/timeline/steer-arrival-machine.ts +134 -0
  198. package/src/timeline/terminal-work.stories.tsx +464 -0
  199. package/src/timeline/timeline-row.stories.tsx +1069 -0
  200. package/src/timeline/timeline-row.ts +238 -0
  201. package/src/timeline/turn-phase-machine.ts +112 -0
  202. package/src/timeline/user-message-fold.stories.tsx +194 -0
  203. package/src/timeline/user-runs.ts +87 -0
  204. package/src/timeline-next/__snapshots__/placement.test.ts.snap +990 -0
  205. package/src/timeline-next/compaction.tsx +236 -0
  206. package/src/timeline-next/errors.ts +101 -0
  207. package/src/timeline-next/event-row.tsx +168 -0
  208. package/src/timeline-next/events.ts +103 -0
  209. package/src/timeline-next/index.ts +10 -0
  210. package/src/timeline-next/nested-rail.ts +125 -0
  211. package/src/timeline-next/projection.ts +1028 -0
  212. package/src/timeline-next/row.tsx +1728 -0
  213. package/src/timeline-next/rules.ts +89 -0
  214. package/src/timeline-next/separator.tsx +73 -0
  215. package/src/timeline-next/spacing.ts +127 -0
  216. package/src/timeline-next/status-line.tsx +41 -0
  217. package/src/timeline-next/status.ts +33 -0
  218. package/src/timeline-next/stories/compare-renderer.stories.tsx +190 -0
  219. package/src/timeline-next/stories/compare-sessions/.gitignore +3 -0
  220. package/src/timeline-next/stories/compare.stories.tsx +486 -0
  221. package/src/timeline-next/stories/playground.stories.tsx +297 -0
  222. package/src/timeline-next/stories/session-replay.ts +1156 -0
  223. package/src/timeline-next/stories/session-timeline.tsx +50 -0
  224. package/src/timeline-next/stories/subagent-status.stories.tsx +132 -0
  225. package/src/timeline-next/timeline-next.css +649 -0
  226. package/src/timeline-next/tools/__snapshots__/activity-label.test.ts.snap +39 -0
  227. package/src/timeline-next/tools/activity-label.ts +166 -0
  228. package/src/timeline-next/tools/assistant-content.tsx +84 -0
  229. package/src/timeline-next/tools/context-group.tsx +619 -0
  230. package/src/timeline-next/tools/error-card.tsx +147 -0
  231. package/src/timeline-next/tools/explore.tsx +119 -0
  232. package/src/timeline-next/tools/file-group.tsx +128 -0
  233. package/src/timeline-next/tools/patch.tsx +174 -0
  234. package/src/timeline-next/tools/shell.tsx +186 -0
  235. package/src/timeline-next/tools/thought.tsx +87 -0
  236. package/src/timeline-next/tools/tool-display.tsx +119 -0
  237. package/src/tools/ansi.ts +8 -0
  238. package/src/tools/context-group-label.ts +123 -0
  239. package/src/tools/file-runs.ts +35 -0
  240. package/src/tools/project-path.ts +18 -0
  241. package/src/tools/read-group.stories.tsx +159 -0
  242. package/src/tools/run-machine.ts +185 -0
  243. package/src/tools/shell-output-machine.ts +233 -0
  244. package/src/tools/shell-output.ts +91 -0
  245. package/src/tools/subagent-row-variants.stories.tsx +129 -0
  246. package/src/tools/tool-group.stories.tsx +345 -0
  247. package/src/tools/tool-renderer.tsx +2876 -0
  248. package/src/v2/components/line-comment-annotations-v2.tsx +215 -0
  249. package/src/v2/components/session-file-panel-v2.tsx +149 -0
  250. package/src/v2/components/session-progress-indicator-v2.css +5 -0
  251. package/src/v2/components/session-progress-indicator-v2.stories.tsx +86 -0
  252. package/src/v2/components/session-progress-indicator-v2.tsx +16 -0
  253. package/src/v2/components/session-review-empty-changes-v2.tsx +17 -0
  254. package/src/v2/components/session-review-empty-no-git-v2.tsx +28 -0
  255. package/src/v2/components/session-review-file-preview-v2-virtualize.ts +5 -0
  256. package/src/v2/components/session-review-file-preview-v2.tsx +266 -0
  257. package/src/v2/components/session-review-v2.css +653 -0
  258. package/src/v2/components/session-review-v2.tsx +422 -0
  259. package/src/v2/components/sidebar-presence-machine.ts +69 -0
  260. package/tsconfig.json +20 -0
  261. package/README.md +0 -3
@@ -0,0 +1,493 @@
1
+ import type { SessionMessageAssistant } from "@zyro-sec/client/promise"
2
+ import { getFilename } from "@zyro-sec/util/path"
3
+ import { Option, Predicate, Schema } from "effect"
4
+ import {
5
+ currentToolFailed,
6
+ currentToolHasLoadedFiles,
7
+ currentToolInput,
8
+ currentToolMetadata,
9
+ readImagePath,
10
+ } from "../message/current-tool-state"
11
+ import { isInterruptedError } from "./turn-phase-machine"
12
+
13
+ /**
14
+ * What the agent did, read only from message parts. Every count or summary a timeline shows comes from `summarize`,
15
+ * never from the rows and groups the timeline happens to draw.
16
+ */
17
+
18
+ type Content = SessionMessageAssistant["content"][number]
19
+
20
+ type Tool = Extract<Content, { type: "tool" }>
21
+
22
+ export type FactMode = "explore" | "edit" | "run" | "tool"
23
+
24
+ export type FactVerb = "started" | "ran" | "finished" | "stopped" | "updated"
25
+
26
+ /** Work that reports back where it ends: a background shell or a subagent. */
27
+ export type FactOutcome = { kind: "shell" | "subagent"; verb: FactVerb; failed: boolean; key?: string }
28
+
29
+ /** What facts are read from: a message part, a user's shell command, or what background work reported. */
30
+ export type FactPart =
31
+ | (Tool & { id?: string; messageID?: string })
32
+ | { type: "text"; id?: string; messageID?: string; text?: string }
33
+ | { type: "reasoning"; id?: string; messageID?: string; text?: string }
34
+ | { type: "shell"; id: string; messageID?: string }
35
+ | { type: "notice"; id: string; messageID?: string }
36
+ | { type: "outcome"; id: string; messageID?: string; outcome: FactOutcome }
37
+
38
+ /** What placing a call reads: where it shows, which group it joins and whether it starts open. */
39
+ export type PlaceFact = {
40
+ kind: "call"
41
+ id: string
42
+ /** The tool's current name; `tool` keeps the name the call used. */
43
+ name: string
44
+ tool: string
45
+ mode: FactMode
46
+ status: Tool["state"]["status"] | "user"
47
+ failed: boolean
48
+ /** The user stopped it, by stopping the turn or cancelling its command. */
49
+ stopped: boolean
50
+ /** The model finished writing what to call it with. */
51
+ called: boolean
52
+ /** A plain file read, which reads well beside the reads around it. */
53
+ groupedRead: boolean
54
+ /** Runs on after the call returns, reporting back as an outcome. */
55
+ background: boolean
56
+ /** The changes a finished foreground script made to files, each placed like a direct edit's file. */
57
+ changes: number
58
+ }
59
+
60
+ export type CallFact = PlaceFact & {
61
+ path?: string
62
+ provider?: string
63
+ /** How a call that launches background work ended, or undefined while it is still written. */
64
+ launch?: FactOutcome
65
+ time?: { started?: number; completed?: number }
66
+ toolCalls?: number
67
+ matches?: number
68
+ }
69
+
70
+ export type FileFact = {
71
+ kind: "file"
72
+ id: string
73
+ path: string
74
+ status: Tool["state"]["status"]
75
+ additions?: number
76
+ deletions?: number
77
+ /** How the file changed, and its diff, where the call recorded them. */
78
+ change?: "added" | "deleted" | "modified"
79
+ patch?: string
80
+ by: string
81
+ /** A call that edits files, or a script that changed them as it ran. */
82
+ via: "direct" | "script"
83
+ }
84
+
85
+ export type Fact =
86
+ | CallFact
87
+ | FileFact
88
+ | { kind: "thought"; id: string }
89
+ | { kind: "text"; id: string }
90
+ | { kind: "outcome"; id: string; outcome: FactOutcome }
91
+ | { kind: "error"; id: string }
92
+
93
+ const renamed = new Map([
94
+ ["bash", "shell"],
95
+ ["task", "subagent"],
96
+ ["apply_patch", "patch"],
97
+ ])
98
+
99
+ /** A tool's current name. Sessions migrated from v1 keep the tools' old names. */
100
+ export function toolName(name: string) {
101
+ return renamed.get(name) ?? name
102
+ }
103
+
104
+ const modes = new Map<string, FactMode>(
105
+ Object.entries({
106
+ read: "explore",
107
+ list: "explore",
108
+ glob: "explore",
109
+ grep: "explore",
110
+ webfetch: "explore",
111
+ websearch: "explore",
112
+ skill: "explore",
113
+ edit: "edit",
114
+ write: "edit",
115
+ patch: "edit",
116
+ shell: "run",
117
+ execute: "run",
118
+ } satisfies Record<string, FactMode>),
119
+ )
120
+
121
+ /**
122
+ * The facts in a list of parts, in order. Not cached: stores update a part in place as it streams, so its identity
123
+ * says nothing about whether its facts changed. Callers read it inside a memo.
124
+ */
125
+ export function factsOf(parts: readonly FactPart[]): Fact[] {
126
+ return parts.flatMap(partFacts)
127
+ }
128
+
129
+ function partFacts(part: FactPart): Fact[] {
130
+ const id = part.messageID ? `${part.messageID}:${part.id ?? ""}` : (part.id ?? "")
131
+
132
+ if (part.type === "text") return [{ kind: "text", id }]
133
+
134
+ if (part.type === "reasoning") return [{ kind: "thought", id }]
135
+
136
+ if (part.type === "notice") return []
137
+
138
+ if (part.type === "outcome") return [{ kind: "outcome", id, outcome: part.outcome }]
139
+
140
+ if (part.type === "shell")
141
+ return [
142
+ {
143
+ kind: "call",
144
+ id,
145
+ name: "shell",
146
+ tool: "shell",
147
+ mode: "run",
148
+ status: "user",
149
+ failed: false,
150
+ stopped: false,
151
+ called: true,
152
+ groupedRead: false,
153
+ background: false,
154
+ changes: 0,
155
+ },
156
+ ]
157
+
158
+ return toolFacts(part, id)
159
+ }
160
+
161
+ const decodeFile = Schema.decodeUnknownOption(
162
+ Schema.Struct({
163
+ file: Schema.String,
164
+ additions: Schema.optional(Schema.Number),
165
+ deletions: Schema.optional(Schema.Number),
166
+ status: Schema.optional(Schema.Literals(["added", "deleted", "modified"])),
167
+ patch: Schema.optional(Schema.String),
168
+ }),
169
+ )
170
+
171
+ const decodeScript = Schema.decodeUnknownOption(
172
+ Schema.Struct({ background: Schema.optional(Schema.Unknown), jobID: Schema.optional(Schema.Unknown) }),
173
+ )
174
+
175
+ const decodeFiles = Schema.decodeUnknownOption(Schema.Array(Schema.Unknown))
176
+
177
+ const decodeText = Schema.decodeUnknownOption(Schema.NonEmptyString)
178
+
179
+ type Reads = { input: () => Schema.JsonObject; metadata: () => Schema.JsonObject }
180
+
181
+ // Input changes with every streamed delta and metadata with every progress report, so each is read only where it is
182
+ // needed, and once.
183
+ function reads(tool: Tool): Reads {
184
+ let input: Schema.JsonObject | undefined
185
+ let metadata: Schema.JsonObject | undefined
186
+
187
+ return {
188
+ input: () => (input ??= currentToolInput(tool)),
189
+ metadata: () => (metadata ??= currentToolMetadata(tool)),
190
+ }
191
+ }
192
+
193
+ /** What placing a call reads of it. Reads input and metadata only where they can move the call or open it. */
194
+ export function placeFactOf(tool: Tool, id = tool.id): PlaceFact {
195
+ return placeFact(tool, id, reads(tool))
196
+ }
197
+
198
+ function placeFact(tool: Tool, id: string, read: Reads): PlaceFact {
199
+ const name = toolName(tool.name)
200
+ const state = tool.state
201
+ const stopped = toolStopped(tool)
202
+
203
+ return {
204
+ kind: "call",
205
+ id,
206
+ name,
207
+ tool: tool.name,
208
+ mode: modes.get(name) ?? "tool",
209
+ status: state.status,
210
+ failed: !stopped && currentToolFailed({ ...tool, name }),
211
+ stopped,
212
+ called: state.status !== "streaming" && (state.status !== "error" || Object.keys(read.input()).length > 0),
213
+ groupedRead:
214
+ tool.name === "read" &&
215
+ state.status !== "error" &&
216
+ !readImagePath(read.input()) &&
217
+ !currentToolHasLoadedFiles(tool),
218
+ background: name === "subagent" || (name === "shell" && read.input().background === true),
219
+ changes: name === "execute" ? scriptChanges(tool, read).length : 0,
220
+ }
221
+ }
222
+
223
+ // Whether a script that fails or is stopped keeps the changes it made, which really happened.
224
+ const keepFailedScriptChanges = true
225
+
226
+ // A script reports the files it changes as it runs and when it ends in the foreground; one moved to the background has
227
+ // none. Placement reads only their count, so progress reports that add no change never move it. Entries that don't
228
+ // decode are dropped here, so every reader numbers the changes alike.
229
+ function scriptChanges(tool: Tool, read: Reads) {
230
+ const status = tool.state.status
231
+
232
+ if (status !== "running" && status !== "completed" && !(status === "error" && keepFailedScriptChanges)) return []
233
+ const metadata = read.metadata()
234
+ const script = Option.getOrUndefined(decodeScript(metadata))
235
+
236
+ // Until a script finishes, its background flag says only that it can move there: one stopped or declined keeps it.
237
+ if (script?.jobID !== undefined || (status === "completed" && script?.background === true)) return []
238
+
239
+ return Option.getOrElse(decodeFiles(metadata.files), () => [])
240
+ .flatMap((file) => Option.toArray(decodeFile(file)))
241
+ .filter((file) => file.file !== "")
242
+ }
243
+
244
+ /** The paths of the changes a finished script made, in order. */
245
+ export function scriptChangePaths(tool: Tool) {
246
+ return scriptChanges(tool, reads(tool)).map((file) => file.file)
247
+ }
248
+
249
+ /** How a call that launches background work ended, or undefined for any other call or while it is still written. */
250
+ export function launchOf(tool: Tool) {
251
+ const read = reads(tool)
252
+
253
+ return placeFact(tool, tool.id, read).background ? launch(tool, toolName(tool.name), read) : undefined
254
+ }
255
+
256
+ function toolFacts(tool: Tool, id: string): Fact[] {
257
+ const read = reads(tool)
258
+ const fact = placeFact(tool, id, read)
259
+ const raw = read.input().path
260
+ const path = Predicate.isString(raw) && raw ? raw : undefined
261
+ const metadata = read.metadata()
262
+ const state = tool.state
263
+ const call: CallFact = { ...fact }
264
+
265
+ if (path) call.path = path
266
+
267
+ // Each field is read on its own, so one of the wrong type leaves the others.
268
+ if (Predicate.isString(metadata.provider) && metadata.provider) call.provider = metadata.provider
269
+
270
+ if (fact.background) call.launch = launch(tool, fact.name, read)
271
+
272
+ if ("time" in state && state.time) call.time = state.time
273
+
274
+ // A script lists the calls it made; their count is how many it made.
275
+ if (Array.isArray(metadata.toolCalls)) call.toolCalls = metadata.toolCalls.length
276
+
277
+ if (Predicate.isNumber(metadata.matches)) call.matches = metadata.matches
278
+
279
+ if (fact.name === "execute")
280
+ return [
281
+ call,
282
+ // One fact per change, in order: a script can change the same file more than once.
283
+ ...scriptChanges(tool, read).map((file, index) => scriptFileFactOf(file, index, id, state.status)),
284
+ ]
285
+
286
+ if (fact.mode !== "edit") return [call]
287
+
288
+ const changed = Option.getOrElse(decodeFiles(metadata.files), () => []).flatMap((file) =>
289
+ Option.toArray(decodeFile(file)),
290
+ )
291
+
292
+ const files = changed.length ? changed : path ? [{ file: path }] : []
293
+
294
+ return [call, ...files.map((file) => fileFact(file, id, state.status, "direct"))]
295
+ }
296
+
297
+ function fileFact(
298
+ file: { file: string; additions?: number; deletions?: number; status?: FileFact["change"]; patch?: string },
299
+ by: string,
300
+ status: Tool["state"]["status"],
301
+ via: FileFact["via"],
302
+ ): FileFact {
303
+ const fact: FileFact = { kind: "file", id: `${by}:file:${file.file}`, path: file.file, status, by, via }
304
+
305
+ if (file.additions !== undefined) fact.additions = file.additions
306
+
307
+ if (file.deletions !== undefined) fact.deletions = file.deletions
308
+
309
+ if (file.status !== undefined) fact.change = file.status
310
+
311
+ if (file.patch !== undefined) fact.patch = file.patch
312
+
313
+ return fact
314
+ }
315
+
316
+ // How a call that launches background work ended. Older sessions marked a foreground subagent's result as completed.
317
+ function launch(tool: Tool, name: string, read: Reads): FactOutcome | undefined {
318
+ const kind = name === "shell" ? "shell" : "subagent"
319
+ const state = tool.state
320
+
321
+ if (state.status === "streaming") return undefined
322
+ const input = read.input()
323
+ const metadata = read.metadata()
324
+ const followUp = kind === "subagent" ? Option.getOrUndefined(decodeText(input.sessionID)) : undefined
325
+
326
+ const id =
327
+ kind === "shell"
328
+ ? Option.getOrUndefined(decodeText(metadata.shellID))
329
+ : (Option.getOrUndefined(decodeText(metadata.sessionID)) ?? followUp)
330
+
331
+ const key = id ? `${kind}:${id}` : undefined
332
+
333
+ if (state.status === "running") return { kind, key, verb: followUp ? "updated" : "started", failed: false }
334
+
335
+ const background =
336
+ kind === "subagent" ? metadata.status !== "completed" : metadata.status === "running" || input.background === true
337
+
338
+ if (state.status === "error") {
339
+ if (state.error.type === "aborted") return { kind, key, verb: "stopped", failed: false }
340
+
341
+ return { kind, key, verb: background ? "started" : "ran", failed: true }
342
+ }
343
+
344
+ if (followUp) return { kind, key, verb: "updated", failed: false }
345
+
346
+ return { kind, key, verb: background ? "started" : "ran", failed: false }
347
+ }
348
+
349
+ /**
350
+ * Whether the user stopped a call, by stopping the turn or cancelling its command. The shell reports a cancelled
351
+ * command as its own error, "Command cancelled".
352
+ */
353
+ export function toolStopped(tool: Tool) {
354
+ if (tool.state.status !== "error") return false
355
+
356
+ return isInterruptedError(tool.state.error) || tool.state.error.message === "Command cancelled"
357
+ }
358
+
359
+ export type ShellVerb = Exclude<FactVerb, "updated">
360
+
361
+ export type Summary = {
362
+ /** Every call, a user's shell command included. */
363
+ calls: number
364
+ /** Each call's tool once, as the call named it, in order. */
365
+ toolNames: { tool: string; provider?: string }[]
366
+ /** Calls by mode, leaving out work that runs on in the background. */
367
+ modes: Record<FactMode, number>
368
+ /** The current names of the other tools used, once each. */
369
+ tools: string[]
370
+ /** Paths read, once each. A read still being written counts once, without a path. */
371
+ reads: number
372
+ /** Named files read, once each. */
373
+ readFiles: string[]
374
+ searches: number
375
+ pages: number
376
+ webSearches: number
377
+ skills: number
378
+ commands: number
379
+ /** Files changed, once each. */
380
+ files: string[]
381
+ thoughts: number
382
+ /** Background shells by how they ended, in the order they happened. Each one counts once. */
383
+ background: { verbs: { verb: ShellVerb; count: number }[]; failed: number }
384
+ failed: number
385
+ }
386
+
387
+ /** Counts what a list of facts did. Nothing else counts. */
388
+ export function summarize(facts: readonly Fact[]): Summary {
389
+ const calls = facts.flatMap((fact) => (fact.kind === "call" ? [fact] : []))
390
+ const foreground = calls.filter((call) => !call.background)
391
+ const count = (names: string[]) => foreground.filter((call) => names.includes(call.name)).length
392
+ const reads = foreground.filter((call) => call.tool === "read")
393
+
394
+ const toolNames = new Map(
395
+ calls.map((call) => [`${call.tool}:${call.provider ?? ""}`, { tool: call.tool, provider: call.provider }]),
396
+ )
397
+
398
+ return {
399
+ calls: calls.length,
400
+ toolNames: [...toolNames.values()],
401
+ modes: {
402
+ explore: foreground.filter((call) => call.mode === "explore").length,
403
+ edit: foreground.filter((call) => call.mode === "edit").length,
404
+ run: foreground.filter((call) => call.mode === "run").length,
405
+ tool: foreground.filter((call) => call.mode === "tool").length,
406
+ },
407
+ tools: [...new Set(foreground.flatMap((call) => (call.mode === "tool" ? [call.name] : [])))],
408
+ reads: new Set(reads.map((call) => call.path)).size,
409
+ readFiles: [...new Set(reads.flatMap((call) => (call.path && getFilename(call.path) ? [call.path] : [])))],
410
+ searches: count(["glob", "grep", "list"]),
411
+ pages: count(["webfetch"]),
412
+ webSearches: count(["websearch"]),
413
+ skills: count(["skill"]),
414
+ commands: foreground.filter((call) => call.mode === "run").length,
415
+ files: [...new Set(facts.flatMap((fact) => (fact.kind === "file" ? [fact.path] : [])))],
416
+ thoughts: facts.filter((fact) => fact.kind === "thought").length,
417
+ background: shells(facts),
418
+ failed: calls.filter((call) => call.failed).length,
419
+ }
420
+ }
421
+
422
+ // Work that reports back in the same facts that launched it counts once, as how it ended.
423
+ function shells(facts: readonly Fact[]) {
424
+ const launched = new Set(facts.flatMap((fact) => (fact.kind === "call" && fact.launch?.key ? [fact.launch.key] : [])))
425
+
426
+ const reports = new Map(
427
+ facts.flatMap((fact) =>
428
+ fact.kind === "outcome" && fact.outcome.key ? [[fact.outcome.key, fact.outcome] as const] : [],
429
+ ),
430
+ )
431
+
432
+ const outcomes = facts.flatMap((fact): FactOutcome[] => {
433
+ if (fact.kind === "outcome") return fact.outcome.key && launched.has(fact.outcome.key) ? [] : [fact.outcome]
434
+
435
+ if (fact.kind !== "call" || !fact.launch) return []
436
+ const report = fact.launch.key ? reports.get(fact.launch.key) : undefined
437
+
438
+ return [
439
+ report && fact.launch.verb === "started"
440
+ ? { ...fact.launch, verb: report.verb, failed: report.failed }
441
+ : fact.launch,
442
+ ]
443
+ })
444
+
445
+ const counts = new Map<ShellVerb, number>()
446
+ const list = outcomes.filter((outcome) => outcome.kind === "shell")
447
+
448
+ list.forEach(({ verb }) => {
449
+ if (verb !== "updated") counts.set(verb, (counts.get(verb) ?? 0) + 1)
450
+ })
451
+
452
+ return {
453
+ verbs: Array.from(counts, ([verb, count]) => ({ verb, count })),
454
+ failed: list.filter((outcome) => outcome.failed).length,
455
+ }
456
+ }
457
+
458
+ /** Where a script's change stands in a message: its part id is the script's, then the change's place and path. */
459
+ export function scriptFilePartID(scriptID: string, index: number, path: string) {
460
+ return `${scriptID}:file:${index}:${path}`
461
+ }
462
+
463
+ function scriptFileFactOf(
464
+ file: Parameters<typeof fileFact>[0],
465
+ index: number,
466
+ by: string,
467
+ status: Tool["state"]["status"],
468
+ ): FileFact {
469
+ return { ...fileFact(file, by, status, "script"), id: `${by}:file:${index}:${file.file}` }
470
+ }
471
+
472
+ const fileFactKeys = ["id", "path", "status", "additions", "deletions", "change", "patch", "by", "via"] as const
473
+
474
+ /** Whether two reads of a change show the same: a script's changes never change once made, only its status does. */
475
+ export function sameFileFact(previous: FileFact, next: FileFact) {
476
+ return fileFactKeys.every((key) => previous[key] === next[key])
477
+ }
478
+
479
+ const scriptFilePart = /^(.*?):file:(\d+):/
480
+
481
+ /** The change a script made that a part id names, read from that one entry of the script's part in the message. */
482
+ export function scriptFileFact(content: readonly Content[], messageID: string, partID: string) {
483
+ const match = scriptFilePart.exec(partID)
484
+
485
+ if (!match) return undefined
486
+ const [, scriptID, index] = match
487
+ const tool = content.find((item) => item.type === "tool" && item.id === scriptID)
488
+
489
+ if (tool?.type !== "tool") return undefined
490
+ const file = scriptChanges(tool, reads(tool))[Number(index)]
491
+
492
+ return file ? scriptFileFactOf(file, Number(index), `${messageID}:${scriptID}`, tool.state.status) : undefined
493
+ }