@osolmaz/pi-workflows 0.16.0 → 0.16.1

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 (154) hide show
  1. package/README.md +18 -2
  2. package/dist/channels/adapter-entry.d.ts +3 -0
  3. package/dist/channels/adapter-entry.js +203 -0
  4. package/dist/channels/adapter-entry.js.map +1 -0
  5. package/dist/channels/config.d.ts +43 -0
  6. package/dist/channels/config.js +234 -0
  7. package/dist/channels/config.js.map +1 -0
  8. package/dist/channels/protocol.d.ts +94 -0
  9. package/dist/channels/protocol.js +219 -0
  10. package/dist/channels/protocol.js.map +1 -0
  11. package/dist/channels/telegram.d.ts +46 -0
  12. package/dist/channels/telegram.js +285 -0
  13. package/dist/channels/telegram.js.map +1 -0
  14. package/dist/client/client.d.ts +1 -0
  15. package/dist/client/client.js +5 -1
  16. package/dist/client/client.js.map +1 -1
  17. package/dist/client/index.d.ts +1 -1
  18. package/dist/client/protocol.d.ts +1 -1
  19. package/dist/client/protocol.js +11 -5
  20. package/dist/client/protocol.js.map +1 -1
  21. package/dist/client/view.d.ts +42 -16
  22. package/dist/client/view.js.map +1 -1
  23. package/dist/controllers/index.d.ts +1 -1
  24. package/dist/controllers/index.js.map +1 -1
  25. package/dist/controllers/sqlite.d.ts +12 -165
  26. package/dist/controllers/sqlite.js +124 -435
  27. package/dist/controllers/sqlite.js.map +1 -1
  28. package/dist/extension/index.d.ts +23 -2
  29. package/dist/extension/index.js +619 -535
  30. package/dist/extension/index.js.map +1 -1
  31. package/dist/extension/recorder.d.ts +95 -0
  32. package/dist/extension/recorder.js +530 -0
  33. package/dist/extension/recorder.js.map +1 -0
  34. package/dist/extension/remote-recorder-store.d.ts +25 -0
  35. package/dist/extension/remote-recorder-store.js +81 -0
  36. package/dist/extension/remote-recorder-store.js.map +1 -0
  37. package/dist/extension/session-events.d.ts +134 -0
  38. package/dist/extension/session-events.js +60 -0
  39. package/dist/extension/session-events.js.map +1 -0
  40. package/dist/extension/session-view.d.ts +2 -0
  41. package/dist/extension/session-view.js +60 -2
  42. package/dist/extension/session-view.js.map +1 -1
  43. package/dist/extension/step-message.d.ts +6 -4
  44. package/dist/extension/step-message.js +12 -6
  45. package/dist/extension/step-message.js.map +1 -1
  46. package/dist/extension/widget.d.ts +2 -2
  47. package/dist/extension/widget.js +28 -18
  48. package/dist/extension/widget.js.map +1 -1
  49. package/dist/extension/workflow-message-coordinator.d.ts +27 -0
  50. package/dist/extension/workflow-message-coordinator.js +294 -0
  51. package/dist/extension/workflow-message-coordinator.js.map +1 -0
  52. package/dist/host/channel-effects.d.ts +72 -0
  53. package/dist/host/channel-effects.js +271 -0
  54. package/dist/host/channel-effects.js.map +1 -0
  55. package/dist/host/channel-supervisor.d.ts +21 -0
  56. package/dist/host/channel-supervisor.js +54 -0
  57. package/dist/host/channel-supervisor.js.map +1 -0
  58. package/dist/host/runner.d.ts +43 -8
  59. package/dist/host/runner.js +1567 -331
  60. package/dist/host/runner.js.map +1 -1
  61. package/dist/host/state.d.ts +19 -16
  62. package/dist/host/state.js +251 -63
  63. package/dist/host/state.js.map +1 -1
  64. package/dist/host/view.d.ts +19 -9
  65. package/dist/host/view.js +222 -118
  66. package/dist/host/view.js.map +1 -1
  67. package/dist/state/prune.js +3 -25
  68. package/dist/state/prune.js.map +1 -1
  69. package/dist/state/schema.js +76 -97
  70. package/dist/state/schema.js.map +1 -1
  71. package/dist/state/workflow-messages.d.ts +96 -0
  72. package/dist/state/workflow-messages.js +335 -0
  73. package/dist/state/workflow-messages.js.map +1 -0
  74. package/dist/viewer/render.js +1 -1
  75. package/dist/viewer/render.js.map +1 -1
  76. package/dist/viewer/tui.d.ts +1 -1
  77. package/dist/viewer/tui.js +65 -8
  78. package/dist/viewer/tui.js.map +1 -1
  79. package/dist/workflows/human-decision.d.ts +2 -0
  80. package/dist/workflows/human-decision.js +8 -2
  81. package/dist/workflows/human-decision.js.map +1 -1
  82. package/dist/workflows/index.d.ts +1 -1
  83. package/dist/workflows/index.js.map +1 -1
  84. package/dist/workflows/settings.d.ts +1 -8
  85. package/dist/workflows/settings.js.map +1 -1
  86. package/dist/workflows/store.d.ts +5 -19
  87. package/dist/workflows/store.js +121 -354
  88. package/dist/workflows/store.js.map +1 -1
  89. package/dist/workflows/tool-input.d.ts +21 -0
  90. package/dist/workflows/tool-input.js +23 -1
  91. package/dist/workflows/tool-input.js.map +1 -1
  92. package/dist/workflows/types.d.ts +5 -5
  93. package/dist/workflows/workflow-message-content.d.ts +38 -0
  94. package/dist/workflows/workflow-message-content.js +157 -0
  95. package/dist/workflows/workflow-message-content.js.map +1 -0
  96. package/docs/2026-08-18-herdr-piw-plan.md +2 -1
  97. package/docs/2026-08-20-durable-workflow-launch-plan.md +1 -1
  98. package/docs/2026-08-25-workflow-follow-ups.md +26 -50
  99. package/docs/2026-08-30-out-of-process-workflow-host-plan.md +3 -3
  100. package/docs/2026-09-01-restore-session-delivery-controls-plan.md +4 -0
  101. package/docs/2026-09-01-unified-workflow-client-plan.md +5 -1
  102. package/docs/2026-09-02-installed-live-e2e-plan.md +15 -1
  103. package/docs/2026-09-02-unify-workflow-messages-plan.md +562 -0
  104. package/docs/DEFERRED_TURNS.md +66 -294
  105. package/docs/HUMAN_DECISIONS.md +29 -30
  106. package/docs/HUMAN_DECISION_PRESENTATIONS.md +4 -11
  107. package/docs/SQLITE_STATE.md +19 -15
  108. package/docs/WORKFLOW_HOST.md +93 -28
  109. package/docs/WORKFLOW_STEP_MESSAGES.md +166 -75
  110. package/docs/live-replay-protocol.md +8 -4
  111. package/docs/tui-viewer.md +3 -1
  112. package/docs/workflows.md +34 -27
  113. package/herdr-plugin.toml +1 -1
  114. package/package.json +1 -1
  115. package/plugins/herdr/viewer.mjs +14 -5
  116. package/src/channels/adapter-entry.ts +220 -0
  117. package/src/channels/config.ts +296 -0
  118. package/src/channels/protocol.ts +333 -0
  119. package/src/channels/telegram.ts +335 -0
  120. package/src/client/client.ts +6 -2
  121. package/src/client/index.ts +2 -1
  122. package/src/client/protocol.ts +11 -5
  123. package/src/client/view.ts +43 -18
  124. package/src/controllers/index.ts +0 -1
  125. package/src/controllers/sqlite.ts +164 -844
  126. package/src/extension/index.ts +693 -646
  127. package/src/extension/recorder.ts +687 -0
  128. package/src/extension/remote-recorder-store.ts +126 -0
  129. package/src/extension/session-events.ts +119 -0
  130. package/src/extension/session-view.ts +86 -3
  131. package/src/extension/step-message.ts +19 -9
  132. package/src/extension/widget.ts +37 -17
  133. package/src/extension/workflow-message-coordinator.ts +334 -0
  134. package/src/host/channel-effects.ts +465 -0
  135. package/src/host/channel-supervisor.ts +73 -0
  136. package/src/host/runner.ts +2120 -531
  137. package/src/host/state.ts +333 -94
  138. package/src/host/view.ts +249 -121
  139. package/src/state/prune.ts +3 -31
  140. package/src/state/schema.ts +76 -97
  141. package/src/state/workflow-messages.ts +548 -0
  142. package/src/viewer/render.ts +1 -5
  143. package/src/viewer/tui.ts +71 -6
  144. package/src/workflows/human-decision.ts +18 -2
  145. package/src/workflows/index.ts +0 -1
  146. package/src/workflows/settings.ts +1 -20
  147. package/src/workflows/store.ts +173 -489
  148. package/src/workflows/tool-input.ts +36 -1
  149. package/src/workflows/types.ts +5 -5
  150. package/src/workflows/workflow-message-content.ts +197 -0
  151. package/dist/extension/decision-channels.d.ts +0 -134
  152. package/dist/extension/decision-channels.js +0 -1307
  153. package/dist/extension/decision-channels.js.map +0 -1
  154. package/src/extension/decision-channels.ts +0 -1826
@@ -0,0 +1,548 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import type { StateDatabase } from "./database.js";
3
+ import { canonicalJson, type JsonValue } from "./json.js";
4
+
5
+ export const WORKFLOW_MESSAGE_SCHEMA = "pi-workflows.workflow-message.v1" as const;
6
+ export const WORKFLOW_MESSAGE_CONTENT_SCHEMA = "pi-workflows.workflow-message-content.v1" as const;
7
+ export const WORKFLOW_TURN_SCHEMA = "pi-workflows.workflow-turn.v1" as const;
8
+
9
+ export type WorkflowMessageKind = "step" | "decision" | "notification" | "terminal" | "followUp";
10
+ export type WorkflowMessageStatus = "pending" | "sent" | "cancelled";
11
+ export type WorkflowStepReason = "initial" | "reminder" | "resumed";
12
+ export type WorkflowTurnState = "started" | "ended";
13
+ export type WorkflowTurnStopReason = "completed" | "aborted" | "error" | "lost";
14
+
15
+ export type WorkflowMessageContent = {
16
+ schema: typeof WORKFLOW_MESSAGE_CONTENT_SCHEMA;
17
+ customType: string;
18
+ content: string;
19
+ display: boolean;
20
+ details: JsonValue;
21
+ triggerTurn: boolean;
22
+ };
23
+
24
+ export type WorkflowMessage = {
25
+ schema: typeof WORKFLOW_MESSAGE_SCHEMA;
26
+ workflowMessageId: string;
27
+ runId: string;
28
+ targetSessionId: string;
29
+ kind: WorkflowMessageKind;
30
+ sourceId: string;
31
+ contentDigest: string;
32
+ content: WorkflowMessageContent;
33
+ order: number;
34
+ status: WorkflowMessageStatus;
35
+ piSessionEntryId: string | null;
36
+ createdAt: string;
37
+ updatedAt: string;
38
+ };
39
+
40
+ export type WorkflowTurn = {
41
+ schema: typeof WORKFLOW_TURN_SCHEMA;
42
+ workflowTurnId: string;
43
+ workflowMessageId: string;
44
+ runId: string;
45
+ targetSessionId: string;
46
+ state: WorkflowTurnState;
47
+ stopReason: WorkflowTurnStopReason | null;
48
+ responseSessionEntryId: string | null;
49
+ startedAt: string;
50
+ endedAt: string | null;
51
+ };
52
+
53
+ export type WorkflowBranchEntry = {
54
+ workflowMessageId: string;
55
+ piSessionEntryId: string;
56
+ };
57
+
58
+ export type CreateWorkflowMessageOptions = {
59
+ workflowMessageId?: string;
60
+ runId: string;
61
+ targetSessionId: string;
62
+ kind: WorkflowMessageKind;
63
+ sourceId: string;
64
+ idempotencyKey: string;
65
+ content: WorkflowMessageContent;
66
+ now?: number;
67
+ };
68
+
69
+ type WorkflowMessageRow = {
70
+ workflowMessageId: string;
71
+ runId: string;
72
+ targetSessionId: string;
73
+ kind: WorkflowMessageKind;
74
+ sourceId: string;
75
+ contentHash: Buffer;
76
+ orderNumber: number;
77
+ status: WorkflowMessageStatus;
78
+ piSessionEntryId: string | null;
79
+ createdAt: number;
80
+ updatedAt: number;
81
+ };
82
+
83
+ type WorkflowTurnRow = {
84
+ workflowTurnId: string;
85
+ workflowMessageId: string;
86
+ runId: string;
87
+ targetSessionId: string;
88
+ state: WorkflowTurnState;
89
+ stopReason: WorkflowTurnStopReason | null;
90
+ responseSessionEntryId: string | null;
91
+ startedAt: number;
92
+ endedAt: number | null;
93
+ };
94
+
95
+ /** Durable workflow content that the host requires Pi to add to one origin session. */
96
+ export class WorkflowMessageStore {
97
+ constructor(readonly state: StateDatabase) {}
98
+
99
+ create(options: CreateWorkflowMessageOptions): WorkflowMessage {
100
+ validateContent(options.content, options.kind);
101
+ const now = options.now ?? Date.now();
102
+ const workflowMessageId =
103
+ options.workflowMessageId ??
104
+ workflowMessageIdFor(options.kind, options.sourceId, options.idempotencyKey);
105
+ return this.state.transaction(() => {
106
+ const existing = this.get(workflowMessageId);
107
+ if (existing !== undefined) {
108
+ assertSameMessage(existing, options);
109
+ return existing;
110
+ }
111
+ const contentHash = this.state.putJson(options.content, now);
112
+ const order =
113
+ ((
114
+ this.state.connection
115
+ .prepare(
116
+ `SELECT COALESCE(MAX(order_number), 0) AS value
117
+ FROM workflow_messages WHERE target_session_id = ?`,
118
+ )
119
+ .get(options.targetSessionId) as { value: number }
120
+ ).value ?? 0) + 1;
121
+ this.state.connection
122
+ .prepare(
123
+ `INSERT INTO workflow_messages(
124
+ workflow_message_id, run_id, target_session_id, kind, source_id, content_hash,
125
+ order_number, status, pi_session_entry_id, created_at, updated_at
126
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', NULL, ?, ?)`,
127
+ )
128
+ .run(
129
+ workflowMessageId,
130
+ options.runId,
131
+ options.targetSessionId,
132
+ options.kind,
133
+ options.sourceId,
134
+ contentHash,
135
+ order,
136
+ now,
137
+ now,
138
+ );
139
+ return this.require(workflowMessageId);
140
+ });
141
+ }
142
+
143
+ get(workflowMessageId: string): WorkflowMessage | undefined {
144
+ const row = this.state.connection
145
+ .prepare(
146
+ `SELECT workflow_message_id AS workflowMessageId, run_id AS runId,
147
+ target_session_id AS targetSessionId, kind, source_id AS sourceId,
148
+ content_hash AS contentHash, order_number AS orderNumber, status,
149
+ pi_session_entry_id AS piSessionEntryId, created_at AS createdAt,
150
+ updated_at AS updatedAt
151
+ FROM workflow_messages WHERE workflow_message_id = ?`,
152
+ )
153
+ .get(workflowMessageId);
154
+ return isWorkflowMessageRow(row) ? this.mapMessage(row) : undefined;
155
+ }
156
+
157
+ require(workflowMessageId: string): WorkflowMessage {
158
+ const message = this.get(workflowMessageId);
159
+ if (message === undefined) throw new Error(`Workflow message not found: ${workflowMessageId}`);
160
+ return message;
161
+ }
162
+
163
+ listSession(targetSessionId: string): WorkflowMessage[] {
164
+ const rows = this.state.connection
165
+ .prepare(
166
+ `SELECT workflow_message_id AS workflowMessageId, run_id AS runId,
167
+ target_session_id AS targetSessionId, kind, source_id AS sourceId,
168
+ content_hash AS contentHash, order_number AS orderNumber, status,
169
+ pi_session_entry_id AS piSessionEntryId, created_at AS createdAt,
170
+ updated_at AS updatedAt
171
+ FROM workflow_messages WHERE target_session_id = ? ORDER BY order_number`,
172
+ )
173
+ .all(targetSessionId);
174
+ return rows.filter(isWorkflowMessageRow).map((row) => this.mapMessage(row));
175
+ }
176
+
177
+ listRun(runId: string): WorkflowMessage[] {
178
+ const rows = this.state.connection
179
+ .prepare(
180
+ `SELECT workflow_message_id AS workflowMessageId, run_id AS runId,
181
+ target_session_id AS targetSessionId, kind, source_id AS sourceId,
182
+ content_hash AS contentHash, order_number AS orderNumber, status,
183
+ pi_session_entry_id AS piSessionEntryId, created_at AS createdAt,
184
+ updated_at AS updatedAt
185
+ FROM workflow_messages WHERE run_id = ? ORDER BY target_session_id, order_number`,
186
+ )
187
+ .all(runId);
188
+ return rows.filter(isWorkflowMessageRow).map((row) => this.mapMessage(row));
189
+ }
190
+
191
+ latestForSource(kind: WorkflowMessageKind, sourceId: string): WorkflowMessage | undefined {
192
+ const row = this.state.connection
193
+ .prepare(
194
+ `SELECT workflow_message_id AS workflowMessageId, run_id AS runId,
195
+ target_session_id AS targetSessionId, kind, source_id AS sourceId,
196
+ content_hash AS contentHash, order_number AS orderNumber, status,
197
+ pi_session_entry_id AS piSessionEntryId, created_at AS createdAt,
198
+ updated_at AS updatedAt
199
+ FROM workflow_messages WHERE kind = ? AND source_id = ?
200
+ ORDER BY created_at DESC, order_number DESC LIMIT 1`,
201
+ )
202
+ .get(kind, sourceId);
203
+ return isWorkflowMessageRow(row) ? this.mapMessage(row) : undefined;
204
+ }
205
+
206
+ cancelPendingForSource(
207
+ sourceId: string,
208
+ kind?: WorkflowMessageKind,
209
+ now: number = Date.now(),
210
+ ): number {
211
+ return this.state.transaction(
212
+ () =>
213
+ this.state.connection
214
+ .prepare(
215
+ `UPDATE workflow_messages SET status = 'cancelled', updated_at = ?
216
+ WHERE source_id = ? AND status = 'pending'${kind === undefined ? "" : " AND kind = ?"}`,
217
+ )
218
+ .run(...(kind === undefined ? [now, sourceId] : [now, sourceId, kind])).changes,
219
+ );
220
+ }
221
+
222
+ adoptBranch(
223
+ targetSessionId: string,
224
+ entries: readonly WorkflowBranchEntry[],
225
+ allowedMessageIds: ReadonlySet<string>,
226
+ now: number = Date.now(),
227
+ ): WorkflowMessage[] {
228
+ return this.state.transaction(() => {
229
+ const adopted: WorkflowMessage[] = [];
230
+ for (const entry of entries) {
231
+ if (!allowedMessageIds.has(entry.workflowMessageId)) {
232
+ throw new Error(
233
+ `Workflow branch report contains an unknown message: ${entry.workflowMessageId}`,
234
+ );
235
+ }
236
+ const current = this.require(entry.workflowMessageId);
237
+ if (current.targetSessionId !== targetSessionId) {
238
+ throw new Error("Workflow branch report targets the wrong origin session");
239
+ }
240
+ if (
241
+ current.status === "sent" &&
242
+ current.piSessionEntryId !== null &&
243
+ current.piSessionEntryId !== entry.piSessionEntryId
244
+ ) {
245
+ throw new Error("Workflow message has conflicting Pi session entry evidence");
246
+ }
247
+ if (current.status !== "sent") {
248
+ this.state.connection
249
+ .prepare(
250
+ `UPDATE workflow_messages
251
+ SET status = 'sent', pi_session_entry_id = ?, updated_at = ?
252
+ WHERE workflow_message_id = ? AND status IN ('pending', 'cancelled')`,
253
+ )
254
+ .run(entry.piSessionEntryId, now, entry.workflowMessageId);
255
+ }
256
+ adopted.push(this.require(entry.workflowMessageId));
257
+ }
258
+ return adopted;
259
+ });
260
+ }
261
+
262
+ startTurn(options: {
263
+ workflowMessageId: string;
264
+ workflowTurnId?: string;
265
+ runId: string;
266
+ targetSessionId: string;
267
+ now?: number;
268
+ }): WorkflowTurn {
269
+ const now = options.now ?? Date.now();
270
+ const workflowTurnId = options.workflowTurnId ?? `workflow-turn-${randomUUID()}`;
271
+ return this.state.transaction(() => {
272
+ const existing = this.getTurn(workflowTurnId);
273
+ if (existing !== undefined) {
274
+ assertSameTurn(existing, options);
275
+ return existing;
276
+ }
277
+ const message = this.require(options.workflowMessageId);
278
+ if (message.runId !== options.runId || message.targetSessionId !== options.targetSessionId) {
279
+ throw new Error("Workflow turn does not match its message");
280
+ }
281
+ if (message.status !== "sent") throw new Error("Workflow turn requires a sent message");
282
+ this.state.connection
283
+ .prepare(
284
+ `INSERT INTO workflow_turns(
285
+ workflow_turn_id, workflow_message_id, run_id, target_session_id, state,
286
+ stop_reason, response_session_entry_id, started_at, ended_at
287
+ ) VALUES (?, ?, ?, ?, 'started', NULL, NULL, ?, NULL)`,
288
+ )
289
+ .run(
290
+ workflowTurnId,
291
+ options.workflowMessageId,
292
+ options.runId,
293
+ options.targetSessionId,
294
+ now,
295
+ );
296
+ return this.requireTurn(workflowTurnId);
297
+ });
298
+ }
299
+
300
+ endTurn(options: {
301
+ workflowMessageId: string;
302
+ workflowTurnId: string;
303
+ runId: string;
304
+ targetSessionId: string;
305
+ stopReason: WorkflowTurnStopReason;
306
+ responseSessionEntryId?: string | null;
307
+ now?: number;
308
+ }): WorkflowTurn {
309
+ const now = options.now ?? Date.now();
310
+ return this.state.transaction(() => {
311
+ const current = this.requireTurn(options.workflowTurnId);
312
+ assertSameTurn(current, options);
313
+ if (current.state === "ended") {
314
+ if (
315
+ current.stopReason !== options.stopReason ||
316
+ current.responseSessionEntryId !== (options.responseSessionEntryId ?? null)
317
+ ) {
318
+ throw new Error("Workflow turn end report conflicts with its saved result");
319
+ }
320
+ return current;
321
+ }
322
+ const changed = this.state.connection
323
+ .prepare(
324
+ `UPDATE workflow_turns SET state = 'ended', stop_reason = ?,
325
+ response_session_entry_id = ?, ended_at = ?
326
+ WHERE workflow_turn_id = ? AND workflow_message_id = ? AND state = 'started'`,
327
+ )
328
+ .run(
329
+ options.stopReason,
330
+ options.responseSessionEntryId ?? null,
331
+ now,
332
+ options.workflowTurnId,
333
+ options.workflowMessageId,
334
+ );
335
+ if (changed.changes !== 1) throw new Error("Workflow turn changed before its end report");
336
+ return this.requireTurn(options.workflowTurnId);
337
+ });
338
+ }
339
+
340
+ getTurn(workflowTurnId: string): WorkflowTurn | undefined {
341
+ const row = this.state.connection
342
+ .prepare(
343
+ `SELECT workflow_turn_id AS workflowTurnId, workflow_message_id AS workflowMessageId,
344
+ run_id AS runId, target_session_id AS targetSessionId, state,
345
+ stop_reason AS stopReason, response_session_entry_id AS responseSessionEntryId,
346
+ started_at AS startedAt, ended_at AS endedAt
347
+ FROM workflow_turns WHERE workflow_turn_id = ?`,
348
+ )
349
+ .get(workflowTurnId);
350
+ return isWorkflowTurnRow(row) ? mapTurn(row) : undefined;
351
+ }
352
+
353
+ requireTurn(workflowTurnId: string): WorkflowTurn {
354
+ const turn = this.getTurn(workflowTurnId);
355
+ if (turn === undefined) throw new Error(`Workflow turn not found: ${workflowTurnId}`);
356
+ return turn;
357
+ }
358
+
359
+ openTurnForMessage(workflowMessageId: string): WorkflowTurn | undefined {
360
+ const row = this.state.connection
361
+ .prepare(
362
+ `SELECT workflow_turn_id AS workflowTurnId, workflow_message_id AS workflowMessageId,
363
+ run_id AS runId, target_session_id AS targetSessionId, state,
364
+ stop_reason AS stopReason, response_session_entry_id AS responseSessionEntryId,
365
+ started_at AS startedAt, ended_at AS endedAt
366
+ FROM workflow_turns WHERE workflow_message_id = ? AND state = 'started'`,
367
+ )
368
+ .get(workflowMessageId);
369
+ return isWorkflowTurnRow(row) ? mapTurn(row) : undefined;
370
+ }
371
+
372
+ latestTurnForMessage(workflowMessageId: string): WorkflowTurn | undefined {
373
+ const row = this.state.connection
374
+ .prepare(
375
+ `SELECT workflow_turn_id AS workflowTurnId, workflow_message_id AS workflowMessageId,
376
+ run_id AS runId, target_session_id AS targetSessionId, state,
377
+ stop_reason AS stopReason, response_session_entry_id AS responseSessionEntryId,
378
+ started_at AS startedAt, ended_at AS endedAt
379
+ FROM workflow_turns WHERE workflow_message_id = ?
380
+ ORDER BY started_at DESC LIMIT 1`,
381
+ )
382
+ .get(workflowMessageId);
383
+ return isWorkflowTurnRow(row) ? mapTurn(row) : undefined;
384
+ }
385
+
386
+ openTurnsForSession(targetSessionId: string): WorkflowTurn[] {
387
+ const rows = this.state.connection
388
+ .prepare(
389
+ `SELECT workflow_turn_id AS workflowTurnId, workflow_message_id AS workflowMessageId,
390
+ run_id AS runId, target_session_id AS targetSessionId, state,
391
+ stop_reason AS stopReason, response_session_entry_id AS responseSessionEntryId,
392
+ started_at AS startedAt, ended_at AS endedAt
393
+ FROM workflow_turns WHERE target_session_id = ? AND state = 'started'
394
+ ORDER BY started_at`,
395
+ )
396
+ .all(targetSessionId);
397
+ return rows.filter(isWorkflowTurnRow).map(mapTurn);
398
+ }
399
+
400
+ private mapMessage(row: WorkflowMessageRow): WorkflowMessage {
401
+ const content = this.state.readJson(row.contentHash);
402
+ if (!isWorkflowMessageContent(content))
403
+ throw new Error("Stored workflow message content is invalid");
404
+ return {
405
+ schema: WORKFLOW_MESSAGE_SCHEMA,
406
+ workflowMessageId: row.workflowMessageId,
407
+ runId: row.runId,
408
+ targetSessionId: row.targetSessionId,
409
+ kind: row.kind,
410
+ sourceId: row.sourceId,
411
+ contentDigest: row.contentHash.toString("hex"),
412
+ content,
413
+ order: row.orderNumber,
414
+ status: row.status,
415
+ piSessionEntryId: row.piSessionEntryId,
416
+ createdAt: new Date(row.createdAt).toISOString(),
417
+ updatedAt: new Date(row.updatedAt).toISOString(),
418
+ };
419
+ }
420
+ }
421
+
422
+ export function workflowMessageIdFor(
423
+ kind: WorkflowMessageKind,
424
+ sourceId: string,
425
+ idempotencyKey: string,
426
+ ): string {
427
+ const digest = createHash("sha256")
428
+ .update(canonicalJson({ kind, sourceId, idempotencyKey }))
429
+ .digest("hex");
430
+ return `workflow-message-${digest}`;
431
+ }
432
+
433
+ export function isWorkflowMessageContent(value: unknown): value is WorkflowMessageContent {
434
+ return (
435
+ isRecord(value) &&
436
+ value.schema === WORKFLOW_MESSAGE_CONTENT_SCHEMA &&
437
+ typeof value.customType === "string" &&
438
+ value.customType.length > 0 &&
439
+ typeof value.content === "string" &&
440
+ typeof value.display === "boolean" &&
441
+ Object.hasOwn(value, "details") &&
442
+ typeof value.triggerTurn === "boolean"
443
+ );
444
+ }
445
+
446
+ function validateContent(content: WorkflowMessageContent, kind: WorkflowMessageKind): void {
447
+ if (!isWorkflowMessageContent(content)) throw new Error("Workflow message content is invalid");
448
+ const shouldTrigger = kind === "step" || kind === "terminal" || kind === "followUp";
449
+ if (content.triggerTurn !== shouldTrigger) {
450
+ throw new Error(`Workflow message kind ${kind} has invalid turn behavior`);
451
+ }
452
+ canonicalJson(content);
453
+ }
454
+
455
+ function assertSameMessage(message: WorkflowMessage, options: CreateWorkflowMessageOptions): void {
456
+ const digest = createHash("sha256").update(canonicalJson(options.content)).digest("hex");
457
+ if (
458
+ message.runId !== options.runId ||
459
+ message.targetSessionId !== options.targetSessionId ||
460
+ message.kind !== options.kind ||
461
+ message.sourceId !== options.sourceId ||
462
+ message.contentDigest !== digest
463
+ ) {
464
+ throw new Error(`Workflow message idempotency conflict: ${message.workflowMessageId}`);
465
+ }
466
+ }
467
+
468
+ function assertSameTurn(
469
+ turn: WorkflowTurn,
470
+ options: { workflowMessageId: string; runId: string; targetSessionId: string },
471
+ ): void {
472
+ if (
473
+ turn.workflowMessageId !== options.workflowMessageId ||
474
+ turn.runId !== options.runId ||
475
+ turn.targetSessionId !== options.targetSessionId
476
+ ) {
477
+ throw new Error(`Workflow turn identity conflict: ${turn.workflowTurnId}`);
478
+ }
479
+ }
480
+
481
+ function mapTurn(row: WorkflowTurnRow): WorkflowTurn {
482
+ return {
483
+ schema: WORKFLOW_TURN_SCHEMA,
484
+ workflowTurnId: row.workflowTurnId,
485
+ workflowMessageId: row.workflowMessageId,
486
+ runId: row.runId,
487
+ targetSessionId: row.targetSessionId,
488
+ state: row.state,
489
+ stopReason: row.stopReason,
490
+ responseSessionEntryId: row.responseSessionEntryId,
491
+ startedAt: new Date(row.startedAt).toISOString(),
492
+ endedAt: row.endedAt === null ? null : new Date(row.endedAt).toISOString(),
493
+ };
494
+ }
495
+
496
+ function isWorkflowMessageRow(value: unknown): value is WorkflowMessageRow {
497
+ return (
498
+ isRecord(value) &&
499
+ typeof value.workflowMessageId === "string" &&
500
+ typeof value.runId === "string" &&
501
+ typeof value.targetSessionId === "string" &&
502
+ isWorkflowMessageKind(value.kind) &&
503
+ typeof value.sourceId === "string" &&
504
+ Buffer.isBuffer(value.contentHash) &&
505
+ typeof value.orderNumber === "number" &&
506
+ isWorkflowMessageStatus(value.status) &&
507
+ (value.piSessionEntryId === null || typeof value.piSessionEntryId === "string") &&
508
+ typeof value.createdAt === "number" &&
509
+ typeof value.updatedAt === "number"
510
+ );
511
+ }
512
+
513
+ function isWorkflowTurnRow(value: unknown): value is WorkflowTurnRow {
514
+ return (
515
+ isRecord(value) &&
516
+ typeof value.workflowTurnId === "string" &&
517
+ typeof value.workflowMessageId === "string" &&
518
+ typeof value.runId === "string" &&
519
+ typeof value.targetSessionId === "string" &&
520
+ (value.state === "started" || value.state === "ended") &&
521
+ (value.stopReason === null || isWorkflowTurnStopReason(value.stopReason)) &&
522
+ (value.responseSessionEntryId === null || typeof value.responseSessionEntryId === "string") &&
523
+ typeof value.startedAt === "number" &&
524
+ (value.endedAt === null || typeof value.endedAt === "number")
525
+ );
526
+ }
527
+
528
+ function isWorkflowMessageKind(value: unknown): value is WorkflowMessageKind {
529
+ return (
530
+ value === "step" ||
531
+ value === "decision" ||
532
+ value === "notification" ||
533
+ value === "terminal" ||
534
+ value === "followUp"
535
+ );
536
+ }
537
+
538
+ function isWorkflowMessageStatus(value: unknown): value is WorkflowMessageStatus {
539
+ return value === "pending" || value === "sent" || value === "cancelled";
540
+ }
541
+
542
+ function isWorkflowTurnStopReason(value: unknown): value is WorkflowTurnStopReason {
543
+ return value === "completed" || value === "aborted" || value === "error" || value === "lost";
544
+ }
545
+
546
+ function isRecord(value: unknown): value is Record<string, unknown> {
547
+ return typeof value === "object" && value !== null && !Array.isArray(value);
548
+ }
@@ -300,11 +300,7 @@ export function renderRunDetailLines(
300
300
 
301
301
  if ((bundle.followUpQueue?.followUps.length ?? 0) > 0) {
302
302
  lines.push("");
303
- lines.push(
304
- ansi.bold(
305
- `follow-ups · presentation ${bundle.followUpQueue?.presentationState ?? "unknown"}`,
306
- ),
307
- );
303
+ lines.push(ansi.bold("follow-ups"));
308
304
  for (const followUp of bundle.followUpQueue?.followUps ?? []) {
309
305
  lines.push(
310
306
  fitWidth(