@nathanstephenson/flow 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/README.md +641 -0
  2. package/build/workflow-runtime.cjs +213964 -0
  3. package/dist/backend/claude/async-queue.js +44 -0
  4. package/dist/backend/claude/auto-compaction.js +10 -0
  5. package/dist/backend/claude/background-calls.js +116 -0
  6. package/dist/backend/claude/enquiries.js +162 -0
  7. package/dist/backend/claude/index.js +1138 -0
  8. package/dist/backend/claude/mcp.js +55 -0
  9. package/dist/backend/claude/permissions.js +106 -0
  10. package/dist/backend/claude/streamed-message.js +120 -0
  11. package/dist/backend/claude/subagents.js +128 -0
  12. package/dist/backend/claude/workflow-parent.js +12 -0
  13. package/dist/backend/claude/workflow-processes.js +95 -0
  14. package/dist/backend/claude/workflow-subagent.js +234 -0
  15. package/dist/backend/effort.js +30 -0
  16. package/dist/backend/fake/index.js +570 -0
  17. package/dist/backend/mcp.js +190 -0
  18. package/dist/backend/pi/auto-compaction.js +16 -0
  19. package/dist/backend/pi/background-calls.js +56 -0
  20. package/dist/backend/pi/enquiries.js +63 -0
  21. package/dist/backend/pi/index.js +597 -0
  22. package/dist/backend/pi/mcp.js +35 -0
  23. package/dist/backend/pi/subagents.js +23 -0
  24. package/dist/backend/pi/work.js +104 -0
  25. package/dist/backend/pi/workflow-parent.js +21 -0
  26. package/dist/backend/pi/workflow-subagent.js +199 -0
  27. package/dist/backend/registry.js +34 -0
  28. package/dist/backend/types.js +1 -0
  29. package/dist/backend/workflow-tools.js +25 -0
  30. package/dist/build-id +1 -0
  31. package/dist/cli/application.js +397 -0
  32. package/dist/cli/bootstrap.js +535 -0
  33. package/dist/cli/host-control.js +100 -0
  34. package/dist/cli/install-guard.js +270 -0
  35. package/dist/cli/install-process.js +52 -0
  36. package/dist/cli/main.js +12 -0
  37. package/dist/cli/update.js +128 -0
  38. package/dist/client/connection.js +183 -0
  39. package/dist/client/context-usage.js +66 -0
  40. package/dist/client/diff.js +36 -0
  41. package/dist/client/enquiry.js +105 -0
  42. package/dist/client/markdown.js +192 -0
  43. package/dist/client/model-choices.js +32 -0
  44. package/dist/client/permission.js +60 -0
  45. package/dist/client/project-name.js +19 -0
  46. package/dist/client/reduce.js +463 -0
  47. package/dist/client/relative-time.js +30 -0
  48. package/dist/client/scope-kind.js +28 -0
  49. package/dist/client/search.js +136 -0
  50. package/dist/client/session-label.js +9 -0
  51. package/dist/client/status.js +84 -0
  52. package/dist/client/tool-chains.js +52 -0
  53. package/dist/client/tool-summary.js +98 -0
  54. package/dist/daemon/auth.js +590 -0
  55. package/dist/daemon/config-store.js +183 -0
  56. package/dist/daemon/config.js +687 -0
  57. package/dist/daemon/credential-redaction.js +9 -0
  58. package/dist/daemon/git.js +312 -0
  59. package/dist/daemon/host-control-routes.js +29 -0
  60. package/dist/daemon/host.js +2343 -0
  61. package/dist/daemon/http.js +19 -0
  62. package/dist/daemon/log.js +44 -0
  63. package/dist/daemon/mcp-auth.js +164 -0
  64. package/dist/daemon/models.js +85 -0
  65. package/dist/daemon/ownership.js +104 -0
  66. package/dist/daemon/projects.js +317 -0
  67. package/dist/daemon/publish.js +289 -0
  68. package/dist/daemon/pull-request.js +198 -0
  69. package/dist/daemon/runtime.js +100 -0
  70. package/dist/daemon/secret-store.js +65 -0
  71. package/dist/daemon/server.js +827 -0
  72. package/dist/daemon/shell.js +220 -0
  73. package/dist/daemon/skills.js +104 -0
  74. package/dist/daemon/stack-metadata.js +24 -0
  75. package/dist/daemon/stack.js +743 -0
  76. package/dist/daemon/store.js +130 -0
  77. package/dist/daemon/summariser.js +476 -0
  78. package/dist/daemon/workflow-execution-routes.js +105 -0
  79. package/dist/daemon/workflow-executions.js +1018 -0
  80. package/dist/daemon/workflow-mcp.js +20 -0
  81. package/dist/daemon/workflow-routes.js +102 -0
  82. package/dist/protocol/attachments.js +59 -0
  83. package/dist/protocol/commands.js +1 -0
  84. package/dist/protocol/events.js +20 -0
  85. package/dist/protocol/fonts.js +26 -0
  86. package/dist/protocol/git.js +12 -0
  87. package/dist/protocol/mcp.js +51 -0
  88. package/dist/protocol/projects.js +21 -0
  89. package/dist/protocol/publish.js +1 -0
  90. package/dist/protocol/pull-request.js +1 -0
  91. package/dist/protocol/secrets.js +4 -0
  92. package/dist/protocol/settings.js +63 -0
  93. package/dist/protocol/shells.js +8 -0
  94. package/dist/protocol/skills.js +16 -0
  95. package/dist/protocol/stack.js +41 -0
  96. package/dist/protocol/workflow-executions.js +1 -0
  97. package/dist/protocol/workflows.js +1 -0
  98. package/dist/tui/app.js +518 -0
  99. package/dist/tui/keys.js +54 -0
  100. package/dist/tui/render.js +366 -0
  101. package/dist/web/assets.js +10 -0
  102. package/dist/web/embedded.js +12 -0
  103. package/dist/web/manifest.js +70 -0
  104. package/dist/workflows/decisions.js +65 -0
  105. package/dist/workflows/executors.js +132 -0
  106. package/dist/workflows/graph.js +276 -0
  107. package/dist/workflows/json-schema.js +49 -0
  108. package/dist/workflows/loops.js +102 -0
  109. package/dist/workflows/mcp.js +18 -0
  110. package/dist/workflows/records.js +111 -0
  111. package/dist/workflows/recovery.js +25 -0
  112. package/dist/workflows/runtime-asset.js +17 -0
  113. package/dist/workflows/runtime-libs.js +1 -0
  114. package/dist/workflows/runtime-settings.js +23 -0
  115. package/dist/workflows/runtime.js +343 -0
  116. package/dist/workflows/scheduler.js +573 -0
  117. package/dist/workflows/schema.js +161 -0
  118. package/dist/workflows/store.js +93 -0
  119. package/package.json +87 -0
  120. package/web/dist/assets/__vite-browser-external-2447137e-BvRk9kiK.js +0 -0
  121. package/web/dist/assets/ghostty-vt-DOMeXDrv.wasm +0 -0
  122. package/web/dist/assets/index-BC0gLS53.js +106 -0
  123. package/web/dist/assets/index-CCeZYKES.css +2 -0
  124. package/web/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  125. package/web/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  126. package/web/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  127. package/web/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  128. package/web/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  129. package/web/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  130. package/web/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  131. package/web/dist/assets/rolldown-runtime-B0Z9INg1.js +1 -0
  132. package/web/dist/assets/select-6i3wxovH.js +1 -0
  133. package/web/dist/assets/settings-mcp-CcT0ADJR.js +1 -0
  134. package/web/dist/assets/settings-secrets-CK4uF7fd.js +1 -0
  135. package/web/dist/assets/settings-workflows-CrbZF-nM.js +23 -0
  136. package/web/dist/assets/switch-ftZleVB8.js +6 -0
  137. package/web/dist/assets/workflow-editors-naPqAmYO.js +65 -0
  138. package/web/dist/assets/workflows-D4T4Gy_7.css +1 -0
  139. package/web/dist/assets/workflows-hh6ioeEA.js +7 -0
  140. package/web/dist/assets/workflows-pane-Db-MHf7Z.js +1 -0
  141. package/web/dist/index.html +31 -0
@@ -0,0 +1,463 @@
1
+ import { compactTokens } from "./context-usage.js";
2
+ import { deriveStatus } from "./status.js";
3
+ function combinedSpend(values) {
4
+ const result = { tokens: 0, cached: 0, costUSD: 0, models: [] };
5
+ for (const value of values) {
6
+ result.tokens += value.tokens;
7
+ result.cached += value.cached;
8
+ result.costUSD += value.costUSD;
9
+ for (const model of value.models) {
10
+ const prior = result.models.find(item => item.id === model.id);
11
+ if (prior) {
12
+ prior.tokens += model.tokens;
13
+ prior.cached += model.cached;
14
+ prior.costUSD += model.costUSD;
15
+ }
16
+ else
17
+ result.models.push({ ...model });
18
+ }
19
+ }
20
+ return result;
21
+ }
22
+ export function initialState() {
23
+ return {
24
+ status: "idle",
25
+ lifecycle: "live",
26
+ turnInFlight: false,
27
+ entries: [],
28
+ queue: [],
29
+ activeSubagents: 0,
30
+ activeBackgroundCalls: 0,
31
+ lastSeq: 0,
32
+ };
33
+ }
34
+ /** Running and waiting are both live work; the three terminal states are not. */
35
+ function isActive(status) {
36
+ return status === "running" || status === "waiting";
37
+ }
38
+ export function reduceAll(entries, from = initialState()) {
39
+ let state = from;
40
+ for (const entry of entries)
41
+ state = reduce(state, entry);
42
+ return state;
43
+ }
44
+ export function reduce(state, entry) {
45
+ /*
46
+ * The cast is deliberate. `applyEvent`'s switch is exhaustive over `AgentEvent` and has no
47
+ * `default` arm, which is what makes a new event type a compile error in every front-end — the
48
+ * property the Entry union's comment relies on, and worth keeping.
49
+ *
50
+ * But a Presentation Transcript is durable and replayed in full forever (ADR 0001), so at runtime
51
+ * it can hold an event *this build* has never heard of: one written before a rename, or by a newer
52
+ * daemon against an older client. Such an event falls through the switch and `applyEvent` returns
53
+ * undefined — and spreading that replaced the entire view with `{ lastSeq }`. No status, no
54
+ * entries, no scope: one unrecognised line silently emptied a session.
55
+ *
56
+ * `lastSeq` still advances, because the event *was* consumed. Only its meaning is unavailable.
57
+ */
58
+ const next = applyEvent(state, entry.event, entry.at);
59
+ if (next === undefined)
60
+ return { ...state, lastSeq: entry.seq };
61
+ if (next === state)
62
+ return state;
63
+ /*
64
+ * Derived here rather than in the arms, through the function the Session Host also calls, so the
65
+ * rail and the pane cannot disagree about what a session is doing. They used to be two switch
66
+ * statements maintained by hand, which is what let the rail say settled while the pane said idle.
67
+ */
68
+ return {
69
+ ...next,
70
+ status: deriveStatus({
71
+ lifecycle: next.lifecycle,
72
+ turnInFlight: next.turnInFlight,
73
+ awaiting: next.asking !== undefined || next.authorising !== undefined,
74
+ }),
75
+ lastSeq: entry.seq,
76
+ };
77
+ }
78
+ function applyEvent(state, event, at) {
79
+ switch (event.type) {
80
+ case "session_started":
81
+ return {
82
+ ...state,
83
+ backend: event.backend,
84
+ scope: event.scope,
85
+ capabilities: event.capabilities,
86
+ ...(event.worktree === undefined ? {} : { worktree: event.worktree }),
87
+ };
88
+ case "capabilities_changed":
89
+ return { ...state, capabilities: event.capabilities };
90
+ case "user_message":
91
+ return {
92
+ ...state,
93
+ spoken: true,
94
+ entries: upsert(state.entries, {
95
+ kind: "user",
96
+ id: event.id,
97
+ text: event.text,
98
+ ...(event.attachments === undefined ? {} : { attachments: event.attachments }),
99
+ }),
100
+ };
101
+ case "turn_started":
102
+ return { ...state, turnInFlight: true };
103
+ case "message":
104
+ return {
105
+ ...state,
106
+ entries: upsert(state.entries, {
107
+ kind: "assistant",
108
+ id: event.id,
109
+ text: event.text,
110
+ final: event.final,
111
+ ...producerOf(event),
112
+ }),
113
+ };
114
+ case "thinking":
115
+ return {
116
+ ...state,
117
+ entries: upsert(state.entries, {
118
+ kind: "thinking",
119
+ id: event.id,
120
+ text: event.text,
121
+ final: event.final,
122
+ ...producerOf(event),
123
+ }),
124
+ };
125
+ case "tool_started":
126
+ return {
127
+ ...state,
128
+ entries: upsert(state.entries, {
129
+ kind: "tool",
130
+ id: event.callId,
131
+ name: event.name,
132
+ input: event.input,
133
+ status: "running",
134
+ ...producerOf(event),
135
+ }),
136
+ };
137
+ case "tool_updated":
138
+ return { ...state, entries: patchTool(state.entries, event.callId, (tool) => ({ ...tool, update: event.update })) };
139
+ case "tool_ended":
140
+ return {
141
+ ...state,
142
+ entries: patchTool(state.entries, event.callId, (tool) => ({
143
+ ...tool,
144
+ result: event.result,
145
+ status: event.isError ? "error" : "complete",
146
+ })),
147
+ };
148
+ case "subagent": {
149
+ // Snapshots repeat, so the count moves on the *transition* rather than on each arrival: a
150
+ // Subagent reporting `running` twice must not count twice.
151
+ const previous = state.entries.find((entry) => entry.kind === "subagent" && entry.id === event.subagentId);
152
+ const wasActive = previous !== undefined && isActive(previous.status);
153
+ const nowActive = isActive(event.state);
154
+ // Carried forward, not re-read: a running Subagent reports repeatedly, and taking `at` each
155
+ // time would keep resetting when it started. Cleared if it somehow resumes, so a live
156
+ // Subagent never shows an end.
157
+ const endedAt = nowActive ? undefined : (previous?.endedAt ?? at);
158
+ return {
159
+ ...state,
160
+ activeSubagents: state.activeSubagents + (nowActive ? 1 : 0) - (wasActive ? 1 : 0),
161
+ entries: upsert(state.entries, {
162
+ kind: "subagent",
163
+ id: event.subagentId,
164
+ name: event.name,
165
+ ...(event.description === undefined ? {} : { description: event.description }),
166
+ status: event.state,
167
+ // Only ever set alongside "waiting", so a Subagent that resumes drops it rather than
168
+ // carrying a stale object it is no longer waiting on.
169
+ ...(event.state === "waiting" ? { waitingOn: event.on } : {}),
170
+ startedAt: previous?.startedAt ?? at,
171
+ ...(endedAt === undefined ? {} : { endedAt }),
172
+ }),
173
+ };
174
+ }
175
+ case "background_call": {
176
+ const previous = state.entries.find((entry) => entry.kind === "background_call" && entry.id === event.callId);
177
+ // The same transition rule the arm above spells out, and for the same reason: a Background
178
+ // Call settles through two messages in one tick, so a terminal snapshot arrives twice.
179
+ const wasActive = previous?.status === "running";
180
+ const nowActive = event.state === "running";
181
+ const endedAt = nowActive ? undefined : (previous?.endedAt ?? at);
182
+ return {
183
+ ...state,
184
+ activeBackgroundCalls: state.activeBackgroundCalls + (nowActive ? 1 : 0) - (wasActive ? 1 : 0),
185
+ entries: upsert(state.entries, {
186
+ kind: "background_call",
187
+ id: event.callId,
188
+ tool: event.tool,
189
+ status: event.state,
190
+ ...producerOf(event),
191
+ startedAt: previous?.startedAt ?? at,
192
+ ...(endedAt === undefined ? {} : { endedAt }),
193
+ }),
194
+ };
195
+ }
196
+ case "enquiry": {
197
+ const open = event.state === "asked";
198
+ /*
199
+ * Minted once and then held by reference, which is what makes it safe on a shallow-compared
200
+ * snapshot: a repeated `asked` snapshot must not produce a fresh object, or the web client's
201
+ * chrome would republish on every one. Compared on the id rather than deep-equality because
202
+ * the id is what identifies an Enquiry and its questions cannot change under it.
203
+ */
204
+ const asking = open && state.asking?.askId === event.askId
205
+ ? state.asking
206
+ : open
207
+ ? { askId: event.askId, questions: event.questions, ...(event.context === undefined ? {} : { context: event.context }) }
208
+ : state.asking?.askId === event.askId
209
+ ? undefined
210
+ : state.asking;
211
+ return {
212
+ ...state,
213
+ ...(asking === undefined ? { asking: undefined } : { asking }),
214
+ entries: upsert(state.entries, {
215
+ kind: "enquiry",
216
+ id: event.askId,
217
+ questions: event.questions,
218
+ status: event.state,
219
+ ...(event.state === "answered" ? { answers: event.answers } : {}),
220
+ ...(event.context === undefined ? {} : { context: event.context }),
221
+ ...(event.producer === undefined ? {} : { producer: event.producer }),
222
+ }),
223
+ };
224
+ }
225
+ case "permission": {
226
+ const open = event.state === "asked";
227
+ /*
228
+ * Held by reference exactly as `asking` is, and for the same reason — a repeated `asked`
229
+ * snapshot must not mint a fresh object, or the web client's chrome republishes on each one.
230
+ *
231
+ * The difference is the promotion. Several prompts can be open at once, so a decision on the
232
+ * one in hand hands over to the next still-open call rather than clearing outright: `entries`
233
+ * is scanned for a `tool` row still `asked`, which is the transcript's own record of what is
234
+ * waiting. That scan runs a few times a turn, not per frame. A prompt arriving while another is
235
+ * in hand changes nothing here — it is already in `entries`, and will be promoted in its turn.
236
+ */
237
+ const authorising = open
238
+ ? (state.authorising ?? {
239
+ callId: event.callId,
240
+ tool: event.tool,
241
+ ...(event.context === undefined ? {} : { context: event.context }),
242
+ ...(event.allowAlways === undefined ? {} : { allowAlways: event.allowAlways }),
243
+ ...(event.authorizationScope === undefined ? {} : { authorizationScope: event.authorizationScope }),
244
+ })
245
+ : state.authorising?.callId === event.callId
246
+ ? nextAwaiting(state.entries, event.callId)
247
+ : state.authorising;
248
+ return {
249
+ ...state,
250
+ ...(authorising === undefined ? { authorising: undefined } : { authorising }),
251
+ entries: patchTool(state.entries, event.callId, (tool) => ({
252
+ ...tool,
253
+ authorisation: authorisationOf(event),
254
+ ...(event.context === undefined ? {} : { permissionContext: event.context }),
255
+ ...(event.allowAlways === undefined ? {} : { allowAlways: event.allowAlways }),
256
+ ...(event.authorizationScope === undefined ? {} : { authorizationScope: event.authorizationScope }),
257
+ })),
258
+ };
259
+ }
260
+ case "turn_ended":
261
+ // `asking` and `authorising` cleared here as well as on their own terminal snapshots. A backend
262
+ // that tore down without emitting one would otherwise leave the composer locked out for good —
263
+ // see ViewState.asking. Clearing twice costs nothing; clearing never is unrecoverable.
264
+ return { ...state, turnInFlight: false, asking: undefined, authorising: undefined };
265
+ case "queue_changed":
266
+ return {
267
+ ...state,
268
+ queue: [...event.pending],
269
+ queuedMessages: state.queuedMessages?.length === event.pending.length &&
270
+ state.queuedMessages.every((message, index) => message.text === event.pending[index] && message.id === event.ids?.[index] &&
271
+ (message.attachments?.length ?? 0) === (event.attachments?.[index]?.length ?? 0) &&
272
+ (message.attachments ?? []).every((id, attachmentIndex) => id === event.attachments?.[index]?.[attachmentIndex]))
273
+ ? state.queuedMessages
274
+ : event.pending.map((text, index) => ({
275
+ id: event.ids?.[index], text,
276
+ ...(event.attachments?.[index]?.length ? { attachments: event.attachments[index] } : {}),
277
+ })),
278
+ };
279
+ case 'workflow_spend': {
280
+ const workflowSpend = { ...state.workflowSpend, [event.executionId]: event.spend };
281
+ const spend = combinedSpend([...(state.parentSpend ? [state.parentSpend] : []), ...Object.values(workflowSpend)]);
282
+ return { ...state, workflowSpend, spend, ...(state.contextUsage ? { contextUsage: { ...state.contextUsage, spend } } : {}) };
283
+ }
284
+ case "context_usage": {
285
+ const spend = event.spend || state.workflowSpend ? combinedSpend([...(event.spend ? [event.spend] : []), ...Object.values(state.workflowSpend ?? {})]) : undefined;
286
+ return {
287
+ ...state,
288
+ ...(event.spend ? { parentSpend: event.spend } : {}),
289
+ ...(spend ? { spend } : {}),
290
+ contextUsage: {
291
+ used: event.used,
292
+ window: event.window,
293
+ ...(spend === undefined ? {} : { spend }),
294
+ },
295
+ };
296
+ }
297
+ case "model_changed":
298
+ return { ...state, model: event.model };
299
+ case "effort_changed":
300
+ return { ...state, effort: event.effort };
301
+ case "branch_changed":
302
+ return { ...state, branch: event.branch };
303
+ case "notice":
304
+ return {
305
+ ...state,
306
+ entries: [...state.entries, { kind: "notice", id: `notice-${state.entries.length}`, level: event.level, text: event.text }],
307
+ };
308
+ case "compacting":
309
+ // Absent rather than `false`, so Chrome's identity comparison sees the same value it saw
310
+ // before a compaction as after one, rather than a new object every time this arrives.
311
+ return event.active ? { ...state, compacting: true } : omitCompacting(state);
312
+ case "compacted":
313
+ return {
314
+ ...omitCompacting(state),
315
+ entries: [
316
+ ...state.entries,
317
+ {
318
+ kind: "marker",
319
+ id: `compacted-${state.entries.length}`,
320
+ marker: "compacted",
321
+ text: compactedLabel(event.trigger, event.before, event.after),
322
+ },
323
+ ],
324
+ };
325
+ case "session_dormant":
326
+ return {
327
+ ...state,
328
+ lifecycle: "dormant",
329
+ turnInFlight: false,
330
+ queue: [],
331
+ queuedMessages: [],
332
+ // Neither an Enquiry nor a Permission Prompt can survive its Backend Session: the promise a
333
+ // human would have settled died with it. Same for the two below.
334
+ asking: undefined,
335
+ authorising: undefined,
336
+ entries: [
337
+ ...state.entries,
338
+ { kind: "marker", id: `dormant-${state.entries.length}`, marker: "dormant", text: `Dormant: ${event.reason}` },
339
+ ],
340
+ };
341
+ case "session_settled":
342
+ return {
343
+ ...state,
344
+ lifecycle: "settled",
345
+ turnInFlight: false,
346
+ queue: [],
347
+ queuedMessages: [],
348
+ asking: undefined,
349
+ authorising: undefined,
350
+ entries: [
351
+ ...state.entries,
352
+ { kind: "marker", id: `settled-${state.entries.length}`, marker: "settled", text: "Settled" },
353
+ ],
354
+ };
355
+ case "revived":
356
+ return {
357
+ ...state,
358
+ lifecycle: "live",
359
+ turnInFlight: false,
360
+ entries: [
361
+ ...state.entries,
362
+ { kind: "marker", id: `revived-${event.fromSeq}`, marker: "revived", text: `Revived from seq ${event.fromSeq}` },
363
+ ],
364
+ };
365
+ case "session_ended":
366
+ return {
367
+ ...state,
368
+ lifecycle: "ended",
369
+ turnInFlight: false,
370
+ endedReason: event.reason,
371
+ asking: undefined,
372
+ authorising: undefined,
373
+ };
374
+ }
375
+ }
376
+ /**
377
+ * `compacting` dropped, without leaving an explicit `undefined` behind for the spread to carry.
378
+ *
379
+ * `compacted` clears it as well as `compacting: false` does: a backend that reports the boundary but
380
+ * never says it stopped would otherwise leave the chrome saying so forever.
381
+ */
382
+ function omitCompacting(state) {
383
+ if (!state.compacting)
384
+ return state;
385
+ const { compacting: _dropped, ...rest } = state;
386
+ return rest;
387
+ }
388
+ /**
389
+ * What a compaction marker says.
390
+ *
391
+ * The before-and-after is the whole point of showing it: "Compacted" alone tells a reader something
392
+ * happened without telling them what it bought, and the number they are watching — occupancy — is
393
+ * about to drop for a reason nothing else in the transcript explains. A backend that does not report
394
+ * what it ended at gets the honest half rather than a fabricated arrow.
395
+ *
396
+ * Automatic is the case that needs naming, because it is the one nobody asked for.
397
+ */
398
+ function compactedLabel(trigger, before, after) {
399
+ const how = trigger === "auto" ? "Compacted automatically" : "Compacted";
400
+ if (after === undefined)
401
+ return `${how}, from ${compactTokens(before)} tokens`;
402
+ return `${how}, ${compactTokens(before)} → ${compactTokens(after)} tokens`;
403
+ }
404
+ /**
405
+ * One `permission` snapshot as the word that goes on the tool row.
406
+ *
407
+ * `always` is kept apart from `allow` rather than flattened to it, because they are not the same
408
+ * thing to a reader scrolling back: one authorised a call, the other authorised every call of that
409
+ * tool on this machine, and only the transcript ever says which click did that.
410
+ */
411
+ function authorisationOf(event) {
412
+ if (event.state === "asked")
413
+ return "asked";
414
+ // An abandoned prompt *is* a refusal, and the model was told so — see `abandonAll` in the adapter.
415
+ // Recording it as anything softer would leave a row saying "waiting" over a session that has gone.
416
+ if (event.state === "aborted")
417
+ return "denied";
418
+ return event.decision === "deny" ? "denied" : event.decision === "always" ? "always" : "allowed";
419
+ }
420
+ /**
421
+ * The next call still waiting to be authorised, once the one in hand is decided.
422
+ *
423
+ * Read off `entries` rather than tracked, because the transcript is already the record of what is
424
+ * open: a `tool` row still marked `asked` is a prompt nobody has answered. `except` is the call just
425
+ * decided, whose own patch has not been applied yet at the point this runs.
426
+ *
427
+ * Returns the *first* such row, so prompts are decided oldest-first — which is the order they were
428
+ * raised in and the order a human works through them.
429
+ */
430
+ function nextAwaiting(entries, except) {
431
+ const next = entries.find((entry) => entry.kind === "tool" && entry.id !== except && entry.authorisation === "asked");
432
+ return next?.kind === "tool" ? {
433
+ callId: next.id,
434
+ tool: next.name,
435
+ ...(next.permissionContext === undefined ? {} : { context: next.permissionContext }),
436
+ ...(next.allowAlways === undefined ? {} : { allowAlways: next.allowAlways }),
437
+ ...(next.authorizationScope === undefined ? {} : { authorizationScope: next.authorizationScope }),
438
+ } : undefined;
439
+ }
440
+ /** Spread onto an Entry, so an unattributed event does not carry an explicit `producer: undefined`. */
441
+ function producerOf(event) {
442
+ return event.producer === undefined ? {} : { producer: event.producer };
443
+ }
444
+ /** Upsert by id — the snapshot semantics the event union is built on. */
445
+ function upsert(entries, entry) {
446
+ const index = entries.findIndex((candidate) => candidate.kind === entry.kind && candidate.id === entry.id);
447
+ if (index < 0)
448
+ return [...entries, entry];
449
+ const copy = [...entries];
450
+ copy[index] = entry;
451
+ return copy;
452
+ }
453
+ function patchTool(entries, callId, patch) {
454
+ const index = entries.findIndex((candidate) => candidate.kind === "tool" && candidate.id === callId);
455
+ if (index < 0)
456
+ return entries;
457
+ const existing = entries[index];
458
+ if (!existing || existing.kind !== "tool")
459
+ return entries;
460
+ const copy = [...entries];
461
+ copy[index] = patch(existing);
462
+ return copy;
463
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * How long ago something happened, for the "last updated" badge both front-ends show.
3
+ *
4
+ * Shared with the browser the same way the reducer is: types only, so stripping leaves standalone
5
+ * ESM. The TUI and the web UI must agree about what "2h" means, and the only way to guarantee that
6
+ * is for there to be one implementation.
7
+ *
8
+ * `now` is a parameter rather than a call to the clock so a frame renders the same way twice.
9
+ */
10
+ const MINUTE = 60_000;
11
+ const HOUR = 60 * MINUTE;
12
+ const DAY = 24 * HOUR;
13
+ export function relativeTime(iso, now = Date.now()) {
14
+ if (!iso)
15
+ return "";
16
+ const at = Date.parse(iso);
17
+ if (Number.isNaN(at))
18
+ return "";
19
+ // Clock skew between writing the timestamp and reading it should read as recent, not negative.
20
+ const elapsed = Math.max(0, now - at);
21
+ if (elapsed < MINUTE)
22
+ return "just now";
23
+ if (elapsed < HOUR)
24
+ return `${Math.floor(elapsed / MINUTE)}m`;
25
+ if (elapsed < DAY)
26
+ return `${Math.floor(elapsed / HOUR)}h`;
27
+ // Past a day the exact age stops being what anyone wants to know; the date is. ISO because it is
28
+ // unambiguous and locale-independent, which matters when the same string renders in a terminal.
29
+ return new Date(at).toISOString().slice(0, 10);
30
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * What kind of Scope an Agent Session is bound to, in words.
3
+ *
4
+ * Here rather than in either front-end for the reason `context-usage.ts` is: this is one sentence
5
+ * both of them have to say identically, and the last time wording like this lived in two places the
6
+ * two places drifted.
7
+ *
8
+ * **Not "Local checkout".** That phrase contrasts with a remote or hosted one, and Flow has
9
+ * no such thing — local mode is the only mode there is (README), so "Local" would distinguish
10
+ * nothing today and would be actively wrong on the day it does. The contrast that is real is
11
+ * between the Project's own checkout and a Worktree cut from it, so that is the one named.
12
+ */
13
+ export function scopeKindLabel(scope) {
14
+ return scope.worktree ? "Worktree" : "Project checkout";
15
+ }
16
+ /**
17
+ * Why the checkout is a label and never a control.
18
+ *
19
+ * A Scope is fixed for an Agent Session's whole life, so there is no version of this someone could
20
+ * change from here — a different directory is a different Agent Session. Exported as prose because
21
+ * both front-ends want to say it: the web client as a tooltip, and it is the reason the TUI's
22
+ * branch overlay offers no way to move between checkouts.
23
+ */
24
+ export function scopeKindHint(scope) {
25
+ return scope.worktree
26
+ ? "A worktree the Session Host made for this Agent Session. It is bound to it for its whole life."
27
+ : "The Project's own checkout. This Agent Session is bound to it for its whole life.";
28
+ }
@@ -0,0 +1,136 @@
1
+ import { editDiff } from "./diff.js";
2
+ /**
3
+ * Finding text in a Presentation Transcript.
4
+ *
5
+ * DOM-free deliberately rather than incidentally: `highlightSegments` returns segments and not
6
+ * nodes, which is what keeps this module compiling under the root config's `lib: ["ES2023"]`, and so
7
+ * what lets the TUI match the way the web UI matches instead of growing a second rule.
8
+ *
9
+ * Case-insensitive substring, and nothing else. No regex (a reader typing `(` into a filter box does
10
+ * not mean a group) and no fuzzy matching (which finds things nobody asked for and hides the reason).
11
+ */
12
+ /**
13
+ * Everything about an Entry that a reader could reasonably expect a search to look at.
14
+ *
15
+ * The previous client searched a tool call's name and result but not its **input**, so searching for
16
+ * a path you had just watched being edited did not match the Edit call that edited it — even though
17
+ * the path was on screen in the rendered diff, because it is in `input.file_path`. The arguments are
18
+ * the half of a tool call a reader is most likely to remember, so they are in the haystack.
19
+ *
20
+ * A Subagent has no `text` at all, so the early return had to learn about it: what a reader
21
+ * remembers of one is what it was called and what it was asked to do.
22
+ */
23
+ export function entryHaystack(entry) {
24
+ if (entry.kind === "subagent") {
25
+ return [entry.name, entry.description].filter((part) => part !== undefined && part !== "").join("\n");
26
+ }
27
+ /*
28
+ * An Enquiry has no `text` either, and what a reader remembers of one is the decision it put to
29
+ * them: the question, the options offered, and — most of all — what they chose. Searching for the
30
+ * answer you gave is the likeliest way anyone comes back to one of these.
31
+ */
32
+ if (entry.kind === "enquiry") {
33
+ return entry.questions
34
+ .flatMap((question, index) => [
35
+ question.header,
36
+ question.question,
37
+ ...question.options.map((option) => option.label),
38
+ ...(entry.answers?.[index] ?? []),
39
+ ])
40
+ .filter((part) => part !== "")
41
+ .join("\n");
42
+ }
43
+ /*
44
+ * A Background Call has no `text` either, and only its tool name to be remembered by. Its
45
+ * arguments are deliberately not repeated here — they are on the `tool` row sharing its id, which
46
+ * this same function already indexes through the stringified input, so the command stays findable
47
+ * without being stored twice.
48
+ */
49
+ if (entry.kind === "background_call")
50
+ return entry.tool;
51
+ if (entry.kind !== "tool")
52
+ return entry.text;
53
+ const diff = editDiff(entry.input);
54
+ // The diff's path is already inside the stringified input; it is repeated here so that a query
55
+ // still matches when editDiff has recognised a path this haystack's JSON has escaped.
56
+ return [entry.name, stringify(entry.input), stringify(entry.result), diff?.path]
57
+ .filter((part) => part !== undefined && part !== "")
58
+ .join("\n");
59
+ }
60
+ /**
61
+ * Whether an Entry matches. The query arrives already lowercased, so a keystroke lowercases once
62
+ * rather than once per Entry, and an empty query matches everything — a filter nobody has typed into
63
+ * hides nothing.
64
+ */
65
+ export function entryMatches(entry, lowercasedQuery) {
66
+ if (lowercasedQuery === "")
67
+ return true;
68
+ return entryHaystack(entry).toLowerCase().includes(lowercasedQuery);
69
+ }
70
+ export function highlightSegments(text, lowercasedQuery) {
71
+ if (text === "")
72
+ return [];
73
+ if (lowercasedQuery === "")
74
+ return [{ text, match: false }];
75
+ const lowered = text.toLowerCase();
76
+ // Lowercasing can change a string's length — `İ`.toLowerCase() is two code units — and then an
77
+ // index into the lowered copy no longer addresses the same character in the original. Rather than
78
+ // slice at the wrong offset and mangle the text, drop the highlight and keep the text intact.
79
+ if (lowered.length !== text.length)
80
+ return [{ text, match: false }];
81
+ const segments = [];
82
+ let cursor = 0;
83
+ for (let at = lowered.indexOf(lowercasedQuery); at !== -1; at = lowered.indexOf(lowercasedQuery, cursor)) {
84
+ if (at > cursor)
85
+ segments.push({ text: text.slice(cursor, at), match: false });
86
+ cursor = at + lowercasedQuery.length;
87
+ const previous = segments[segments.length - 1];
88
+ // Two matches that touch are one highlight to whoever is looking at it, so they are one segment;
89
+ // emitting them separately would put a seam in the middle of a `<mark>` for no reason.
90
+ if (previous?.match)
91
+ previous.text += text.slice(at, cursor);
92
+ else
93
+ segments.push({ text: text.slice(at, cursor), match: true });
94
+ }
95
+ if (cursor < text.length)
96
+ segments.push({ text: text.slice(cursor), match: false });
97
+ return segments;
98
+ }
99
+ export function createHaystackCache() {
100
+ // Keyed on the Entry object, which is what makes this cache free of invalidation: `upsert`
101
+ // produces a NEW Entry on every change (reduce.ts:169-172), so an Entry whose snapshot has grown
102
+ // is a different key and the stale value is unreachable by construction. It is also why the cache
103
+ // stays correct mid-stream — a growing snapshot that *newly* matches starts matching on the tick
104
+ // it does, which a useMemo keyed on the key list would miss, because the key list did not change.
105
+ const lowered = new WeakMap();
106
+ return {
107
+ matches(entry, lowercasedQuery) {
108
+ if (lowercasedQuery === "")
109
+ return true;
110
+ let haystack = lowered.get(entry);
111
+ if (haystack === undefined) {
112
+ haystack = entryHaystack(entry).toLowerCase();
113
+ lowered.set(entry, haystack);
114
+ }
115
+ return haystack.includes(lowercasedQuery);
116
+ },
117
+ };
118
+ }
119
+ /**
120
+ * Strings verbatim, everything else as JSON — which is how a tool payload is rendered anyway, so the
121
+ * haystack matches what is on screen. JSON escaping is the one gap: a query containing a backslash
122
+ * or a double quote will not match inside a stringified payload.
123
+ */
124
+ function stringify(value) {
125
+ if (value === undefined || value === null)
126
+ return "";
127
+ if (typeof value === "string")
128
+ return value;
129
+ try {
130
+ return JSON.stringify(value) ?? "";
131
+ }
132
+ catch {
133
+ // Circular, or carrying a BigInt. Nothing about a keystroke is worth a throw.
134
+ return "";
135
+ }
136
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * What to call an Agent Session on screen. The title is always derived, never authored: the first
3
+ * line of the first message (`host.ts` `firstLine`), replaced seconds later by the Summary Model's
4
+ * name where one is configured (ADR 0020). So an Agent Session nobody has written to yet has an
5
+ * empty one — and an empty string renders as nothing at all rather than as something you can click.
6
+ */
7
+ export function sessionLabel(summary) {
8
+ return summary.title || summary.id;
9
+ }