@osolmaz/pi-workflows 0.15.3 → 0.16.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 (118) hide show
  1. package/README.md +6 -6
  2. package/dist/client/activity.d.ts +2 -0
  3. package/dist/client/activity.js +6 -0
  4. package/dist/client/activity.js.map +1 -0
  5. package/dist/client/client.d.ts +101 -0
  6. package/dist/client/client.js +733 -0
  7. package/dist/client/client.js.map +1 -0
  8. package/dist/client/index.d.ts +3 -0
  9. package/dist/client/index.js +3 -0
  10. package/dist/client/index.js.map +1 -0
  11. package/dist/client/materialize.d.ts +7 -0
  12. package/dist/client/materialize.js +177 -0
  13. package/dist/client/materialize.js.map +1 -0
  14. package/dist/client/protocol.d.ts +60 -0
  15. package/dist/client/protocol.js +269 -0
  16. package/dist/client/protocol.js.map +1 -0
  17. package/dist/client/resolver.d.ts +23 -0
  18. package/dist/client/resolver.js +2 -0
  19. package/dist/client/resolver.js.map +1 -0
  20. package/dist/client/view.d.ts +118 -0
  21. package/dist/client/view.js +3 -0
  22. package/dist/client/view.js.map +1 -0
  23. package/dist/controllers/sqlite.d.ts +43 -0
  24. package/dist/controllers/sqlite.js +137 -2
  25. package/dist/controllers/sqlite.js.map +1 -1
  26. package/dist/extension/index.d.ts +1 -0
  27. package/dist/extension/index.js +278 -183
  28. package/dist/extension/index.js.map +1 -1
  29. package/dist/extension/session-view.d.ts +7 -2
  30. package/dist/extension/session-view.js +60 -52
  31. package/dist/extension/session-view.js.map +1 -1
  32. package/dist/extension/widget.d.ts +2 -1
  33. package/dist/extension/widget.js +14 -7
  34. package/dist/extension/widget.js.map +1 -1
  35. package/dist/host/child-worker-supervisor.js +1 -1
  36. package/dist/host/child-worker-supervisor.js.map +1 -1
  37. package/dist/host/resolver-entry.d.ts +2 -23
  38. package/dist/host/resolver-entry.js +1 -1
  39. package/dist/host/resolver-entry.js.map +1 -1
  40. package/dist/host/runner.d.ts +11 -0
  41. package/dist/host/runner.js +473 -17
  42. package/dist/host/runner.js.map +1 -1
  43. package/dist/host/state.d.ts +6 -3
  44. package/dist/host/state.js +52 -26
  45. package/dist/host/state.js.map +1 -1
  46. package/dist/host/view.d.ts +73 -0
  47. package/dist/host/view.js +871 -0
  48. package/dist/host/view.js.map +1 -0
  49. package/dist/host/worker-protocol.js +1 -1
  50. package/dist/host/worker-protocol.js.map +1 -1
  51. package/dist/state/database.d.ts +1 -0
  52. package/dist/state/database.js +15 -0
  53. package/dist/state/database.js.map +1 -1
  54. package/dist/state/prune.d.ts +3 -1
  55. package/dist/state/prune.js +6 -8
  56. package/dist/state/prune.js.map +1 -1
  57. package/dist/state/schema.js +12 -1
  58. package/dist/state/schema.js.map +1 -1
  59. package/dist/viewer/backup.d.ts +2 -0
  60. package/dist/viewer/backup.js +28 -0
  61. package/dist/viewer/backup.js.map +1 -0
  62. package/dist/viewer/cli.d.ts +4 -0
  63. package/dist/viewer/cli.js +150 -170
  64. package/dist/viewer/cli.js.map +1 -1
  65. package/dist/viewer/tui.d.ts +5 -7
  66. package/dist/viewer/tui.js +188 -108
  67. package/dist/viewer/tui.js.map +1 -1
  68. package/dist/workflows/store.d.ts +62 -1
  69. package/dist/workflows/store.js +350 -44
  70. package/dist/workflows/store.js.map +1 -1
  71. package/docs/2026-09-01-unified-workflow-client-plan.md +381 -0
  72. package/docs/2026-09-02-installed-live-e2e-plan.md +225 -0
  73. package/docs/SQLITE_STATE.md +13 -11
  74. package/docs/WORKFLOW_HOST.md +74 -61
  75. package/docs/development.md +2 -1
  76. package/docs/live-replay-protocol.md +70 -132
  77. package/docs/tui-viewer.md +10 -14
  78. package/docs/workflows.md +44 -1
  79. package/herdr-plugin.toml +1 -1
  80. package/package.json +9 -3
  81. package/protocol/client.v1.schema.json +137 -0
  82. package/protocol/fixtures/client-v1.json +23 -0
  83. package/src/client/activity.ts +6 -0
  84. package/src/client/client.ts +935 -0
  85. package/src/client/index.ts +24 -0
  86. package/src/client/materialize.ts +228 -0
  87. package/src/client/protocol.ts +327 -0
  88. package/src/client/resolver.ts +26 -0
  89. package/src/client/view.ts +138 -0
  90. package/src/controllers/sqlite.ts +213 -2
  91. package/src/extension/index.ts +349 -208
  92. package/src/extension/session-view.ts +73 -50
  93. package/src/extension/widget.ts +16 -8
  94. package/src/host/child-worker-supervisor.ts +1 -1
  95. package/src/host/resolver-entry.ts +11 -26
  96. package/src/host/runner.ts +648 -48
  97. package/src/host/state.ts +71 -43
  98. package/src/host/view.ts +1084 -0
  99. package/src/host/worker-protocol.ts +1 -1
  100. package/src/state/database.ts +13 -0
  101. package/src/state/prune.ts +11 -11
  102. package/src/state/schema.ts +12 -1
  103. package/src/viewer/backup.ts +29 -0
  104. package/src/viewer/cli.ts +171 -185
  105. package/src/viewer/tui.ts +196 -124
  106. package/src/workflows/store.ts +500 -45
  107. package/dist/host/client.d.ts +0 -48
  108. package/dist/host/client.js +0 -216
  109. package/dist/host/client.js.map +0 -1
  110. package/dist/host/protocol.d.ts +0 -38
  111. package/dist/host/protocol.js +0 -156
  112. package/dist/host/protocol.js.map +0 -1
  113. package/dist/viewer/watch.d.ts +0 -6
  114. package/dist/viewer/watch.js +0 -46
  115. package/dist/viewer/watch.js.map +0 -1
  116. package/src/host/client.ts +0 -293
  117. package/src/host/protocol.ts +0 -196
  118. package/src/viewer/watch.ts +0 -51
@@ -0,0 +1,871 @@
1
+ import { createHash } from "node:crypto";
2
+ import { ORIGIN_ACTIVITY_LEASE_MS } from "../client/activity.js";
3
+ import { RUN_VIEW_SCHEMA, SESSION_VIEW_SCHEMA, } from "../client/view.js";
4
+ import { canonicalJson, parseJson } from "../state/json.js";
5
+ export const WORKFLOW_PAGE_KINDS = [
6
+ "steps",
7
+ "trace",
8
+ "trace_at_step",
9
+ "session_entries",
10
+ "session_events",
11
+ "settings",
12
+ "follow_ups",
13
+ "updates",
14
+ ];
15
+ const INLINE_CONTENT_BYTES = 16 * 1024;
16
+ const VIEW_PAGE_BYTES = 64 * 1024;
17
+ const VIEW_PAGE_ITEMS = 256;
18
+ const CONTENT_CHUNK_BYTES = 192 * 1024;
19
+ const CONTENT_CACHE_BYTES = 64 * 1024 * 1024;
20
+ const VIEW_CACHE_ITEMS = 64;
21
+ export class HostViewStore {
22
+ state;
23
+ queue;
24
+ hostState;
25
+ runs;
26
+ hasLiveWorker;
27
+ activity = new Map();
28
+ contentRecords = new Map();
29
+ listCache = new Map();
30
+ runCache = new Map();
31
+ sessionCache = new Map();
32
+ contentBytes = 0;
33
+ activityRevision = 0;
34
+ constructor(state, queue, hostState, runs, hasLiveWorker) {
35
+ this.state = state;
36
+ this.queue = queue;
37
+ this.hostState = hostState;
38
+ this.runs = runs;
39
+ this.hasLiveWorker = hasLiveWorker;
40
+ }
41
+ list(cursor = 0, limit) {
42
+ this.expireActivity();
43
+ return this.state.readTransaction(() => {
44
+ const pageSize = Math.min(limit ?? VIEW_PAGE_ITEMS, VIEW_PAGE_ITEMS);
45
+ const current = this.queue.workflowRunListRevision();
46
+ const revision = `${current.revision}:${this.activityRevision}`;
47
+ const cacheKey = `${cursor}:${pageSize}`;
48
+ const cached = this.listCache.get(cacheKey);
49
+ if (cached?.revision === revision) {
50
+ refreshCacheEntry(this.listCache, cacheKey, cached);
51
+ return cached.page;
52
+ }
53
+ const loaded = this.queue.listWorkflowRunViews({ offset: cursor, limit: pageSize });
54
+ const summaries = loaded.runs.map((run) => {
55
+ const display = this.projectDisplay(run.runId, this.display(run, {
56
+ status: run.runStateStatus,
57
+ paused: run.paused,
58
+ error: run.errorMessage,
59
+ }));
60
+ return {
61
+ runId: run.runId,
62
+ workflowName: run.workflowName,
63
+ originSessionId: run.originSessionId,
64
+ createdAt: run.createdAt,
65
+ updatedAt: run.updatedAt,
66
+ display,
67
+ manifest: manifest(run, display.status),
68
+ live: display.status === "running" || display.status === "waiting",
69
+ possiblyInterrupted: run.status === "parked" && display.status !== "paused",
70
+ };
71
+ });
72
+ const items = byteBoundedForwardPage(summaries, (summary) => toJson(summary)).map((item) => item);
73
+ const page = {
74
+ schema: "pi-workflows.run-list-page.v1",
75
+ revision,
76
+ start: cursor,
77
+ total: loaded.total,
78
+ items,
79
+ };
80
+ rememberCacheEntry(this.listCache, cacheKey, { revision, page });
81
+ return page;
82
+ });
83
+ }
84
+ run(runId) {
85
+ this.expireActivity();
86
+ return this.state.readTransaction(() => {
87
+ const version = this.runVersion(runId);
88
+ const cached = this.runCache.get(runId);
89
+ if (cached?.version === version) {
90
+ refreshCacheEntry(this.runCache, runId, cached);
91
+ return cached.view;
92
+ }
93
+ const view = this.readRun(runId);
94
+ rememberCacheEntry(this.runCache, runId, { version, view });
95
+ return view;
96
+ });
97
+ }
98
+ page(runId, request) {
99
+ this.expireActivity();
100
+ return this.state.readTransaction(() => this.readRun(runId, request));
101
+ }
102
+ readRun(runId, page) {
103
+ const queue = this.queue.getWorkflowRunView(runId);
104
+ const counts = this.runs.readRunViewCounts(runId);
105
+ if (queue === undefined || counts === null)
106
+ return null;
107
+ const graphCursor = page?.kind === "steps"
108
+ ? clampCursor(page.cursor, counts.steps)
109
+ : Math.max(0, counts.steps - 1);
110
+ const traceCursor = page?.kind === "trace_at_step"
111
+ ? this.runs.traceCursorForStep(runId, page.cursor, counts.trace)
112
+ : page?.kind === "trace"
113
+ ? page.cursor
114
+ : undefined;
115
+ const stepRange = viewRange(counts.steps, page?.kind === "steps" ? page.cursor : undefined);
116
+ const traceRange = viewRange(counts.trace, traceCursor);
117
+ const entryRange = viewRange(counts.sessionEntries, page?.kind === "session_entries" ? page.cursor : undefined);
118
+ const eventRange = viewRange(counts.sessionEvents, page?.kind === "session_events" ? page.cursor : undefined);
119
+ const settingsRange = viewRange(counts.settings, page?.kind === "settings" ? page.cursor : undefined);
120
+ const followUpRange = viewRange(counts.followUps, page?.kind === "follow_ups" ? page.cursor : undefined);
121
+ const updateRange = viewRange(counts.updates, page?.kind === "updates" ? page.cursor : undefined);
122
+ const loaded = this.runs.readRunView(runId, {
123
+ steps: stepRange,
124
+ trace: traceRange,
125
+ sessionEntries: entryRange,
126
+ sessionEvents: eventRange,
127
+ settings: settingsRange,
128
+ followUps: followUpRange,
129
+ updates: updateRange,
130
+ graphCursor,
131
+ });
132
+ if (loaded === null)
133
+ return null;
134
+ const stepPage = byteBoundedCandidatePage(loaded.state.steps, stepRange.start, counts.steps, page?.kind === "steps" ? page.cursor : undefined, (step) => this.projectStep(runId, step));
135
+ const tracePage = byteBoundedCandidatePage(loaded.traceEvents, traceRange.start, counts.trace, traceCursor, (event) => this.projectTraceEvent(runId, event));
136
+ const entryPage = byteBoundedCandidatePage(loaded.sessionEntries, entryRange.start, counts.sessionEntries, page?.kind === "session_entries" ? page.cursor : undefined, (entry) => this.projectSessionEntry(runId, entry));
137
+ const eventPage = byteBoundedCandidatePage(loaded.sessionEvents, eventRange.start, counts.sessionEvents, page?.kind === "session_events" ? page.cursor : undefined, (event) => this.projectSessionEvent(runId, event));
138
+ const settingsPage = byteBoundedCandidatePage(loaded.settingsScopes, settingsRange.start, counts.settings, page?.kind === "settings" ? page.cursor : undefined, (scope) => this.projectRecordField(runId, scope, "settings"));
139
+ const followUps = loaded.followUpQueue?.followUps ?? [];
140
+ const followUpPage = byteBoundedCandidatePage(followUps, followUpRange.start, counts.followUps, page?.kind === "follow_ups" ? page.cursor : undefined, (followUp) => this.projectRecordField(runId, followUp, "prompt"));
141
+ const updates = loaded.state.updates ?? [];
142
+ const updatePage = byteBoundedCandidatePage(updates, updateRange.start, counts.updates, page?.kind === "updates" ? page.cursor : undefined, (update) => this.projectUpdate(runId, update));
143
+ const followUpQueue = loaded.followUpQueue === null
144
+ ? null
145
+ : projectFollowUpQueue(loaded.followUpQueue, followUpPage.items);
146
+ const completeGraphSteps = loaded.graphSteps.map((step) => toCompactStepJson(step));
147
+ const completeTakenTransitions = loaded.takenTransitions.map((transition) => toJson(transition));
148
+ const graphSteps = byteBoundedForwardPage(completeGraphSteps, (step) => step);
149
+ const takenTransitions = byteBoundedForwardPage(completeTakenTransitions, (transition) => transition).filter((transition) => typeof transition === "string");
150
+ const graphHistory = this.projectValue(runId, {
151
+ steps: completeGraphSteps,
152
+ transitions: completeTakenTransitions,
153
+ });
154
+ const revision = this.presentationRevision(runId);
155
+ const display = this.projectDisplay(runId, this.display(queue, loaded.state));
156
+ return {
157
+ schema: RUN_VIEW_SCHEMA,
158
+ runId,
159
+ revision,
160
+ display,
161
+ manifest: manifest(queue, display.status),
162
+ state: this.projectState(runId, loaded.state, stepPage.items, updatePage.items),
163
+ workflow: this.projectWorkflow(runId, loaded.snapshot),
164
+ queue: projectQueue(queue),
165
+ updates: updatePage.items,
166
+ graphSteps,
167
+ graphStepStart: 0,
168
+ graphStepTotal: loaded.graphSteps.length,
169
+ takenTransitions,
170
+ graphHistory,
171
+ takenTransitionStart: 0,
172
+ takenTransitionTotal: loaded.takenTransitions.length,
173
+ graphCursor,
174
+ stepStart: stepPage.start,
175
+ stepTotal: stepPage.total,
176
+ tracePage,
177
+ session: {
178
+ binding: toJson(loaded.sessionBinding),
179
+ entryPage,
180
+ eventPage,
181
+ capture: toJson(loaded.sessionCapture),
182
+ integrity: toJson(loaded.sessionIntegrity),
183
+ replayCheckpoint: this.projectReplayCheckpoint(runId, this.runs.readSessionReplayCheckpoint(runId, eventPage.start)),
184
+ },
185
+ settingsScopes: settingsPage.items,
186
+ settingsStart: settingsPage.start,
187
+ settingsTotal: settingsPage.total,
188
+ followUpQueue: toJson(followUpQueue),
189
+ followUpStart: followUpPage.start,
190
+ followUpTotal: followUpPage.total,
191
+ updateStart: updatePage.start,
192
+ updateTotal: updatePage.total,
193
+ live: display.status === "running" || display.status === "waiting",
194
+ possiblyInterrupted: queue.status === "parked" && display.status !== "paused",
195
+ };
196
+ }
197
+ session(sessionId) {
198
+ this.expireActivity();
199
+ return this.state.readTransaction(() => {
200
+ const queue = this.queue.findSessionReservationView(sessionId);
201
+ const deliveries = {
202
+ notification: this.queue.hasClaimableWorkflowNotification({ targetSessionId: sessionId }),
203
+ turn: this.queue.hasClaimableWorkflowTurnIntent({ targetSessionId: sessionId }),
204
+ };
205
+ const version = [
206
+ queue === undefined ? "none" : this.runVersion(queue.runId),
207
+ this.pendingSessionRevision(sessionId),
208
+ deliveries.notification,
209
+ deliveries.turn,
210
+ ].join(":");
211
+ const cached = this.sessionCache.get(sessionId);
212
+ if (cached?.version === version) {
213
+ refreshCacheEntry(this.sessionCache, sessionId, cached);
214
+ return cached.view;
215
+ }
216
+ const pending = this.hostState.listPendingInteractions(sessionId);
217
+ const pendingInteractions = byteBoundedForwardPage(pending, (request) => this.projectRecordField(request.runId, request, "contract"));
218
+ const view = {
219
+ schema: SESSION_VIEW_SCHEMA,
220
+ sessionId,
221
+ run: queue === undefined ? null : this.run(queue.runId),
222
+ pendingInteractions,
223
+ pendingInteractionStart: 0,
224
+ pendingInteractionTotal: pending.length,
225
+ deliveries,
226
+ };
227
+ rememberCacheEntry(this.sessionCache, sessionId, { version, view });
228
+ return view;
229
+ });
230
+ }
231
+ content(runId, contentPath, offset) {
232
+ const key = contentKey(runId, contentPath);
233
+ const record = this.contentRecords.get(key) ?? this.recoverContent(runId, contentPath);
234
+ if (record === undefined)
235
+ return null;
236
+ this.contentRecords.delete(key);
237
+ this.contentRecords.set(key, record);
238
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset > record.bytes.byteLength) {
239
+ throw new Error("Workflow content offset is outside the content range");
240
+ }
241
+ const nextOffset = Math.min(record.bytes.byteLength, offset + CONTENT_CHUNK_BYTES);
242
+ return {
243
+ schema: "pi-workflows.content-chunk.v1",
244
+ runId,
245
+ path: record.path,
246
+ mediaType: record.mediaType,
247
+ bytes: record.bytes.byteLength,
248
+ sha256: record.sha256,
249
+ offset,
250
+ nextOffset,
251
+ complete: nextOffset === record.bytes.byteLength,
252
+ data: record.bytes.subarray(offset, nextOffset).toString("base64"),
253
+ };
254
+ }
255
+ projectStep(runId, step) {
256
+ const projected = toJson(step);
257
+ if (!isJsonObject(projected))
258
+ return projected;
259
+ for (const field of ["prompt", "output", "assistantMessage"]) {
260
+ const value = projected[field];
261
+ if (value !== undefined)
262
+ projected[field] = this.projectValue(runId, value);
263
+ }
264
+ return projected;
265
+ }
266
+ projectTraceEvent(runId, event) {
267
+ return this.projectRecordField(runId, event, "payload");
268
+ }
269
+ projectSessionEntry(runId, entry) {
270
+ return this.projectRecordField(runId, entry, "entry");
271
+ }
272
+ projectSessionEvent(runId, event) {
273
+ return this.projectRecordField(runId, event, "payload");
274
+ }
275
+ projectUpdate(runId, update) {
276
+ return this.projectRecordField(runId, update, "data");
277
+ }
278
+ projectReplayCheckpoint(runId, value) {
279
+ return value === null ? null : this.projectValue(runId, value);
280
+ }
281
+ projectRecordField(runId, value, field) {
282
+ const projected = toJson(value);
283
+ if (isJsonObject(projected)) {
284
+ const fieldValue = projected[field];
285
+ if (fieldValue !== undefined)
286
+ projected[field] = this.projectValue(runId, fieldValue);
287
+ }
288
+ return projected;
289
+ }
290
+ projectState(runId, stateValue, steps, updates) {
291
+ const state = toJson(stateValue);
292
+ if (!isJsonObject(state))
293
+ return state;
294
+ for (const field of ["input", "outputs", "results", "humanDecision", "finalOutput"]) {
295
+ const value = state[field];
296
+ if (value !== undefined)
297
+ state[field] = this.projectValue(runId, value);
298
+ }
299
+ state.steps = steps;
300
+ state.updates = updates;
301
+ return state;
302
+ }
303
+ projectWorkflow(runId, value) {
304
+ const original = toJson(value);
305
+ const workflow = escapeArtifactSentinels(original);
306
+ if (Buffer.byteLength(canonicalJson(workflow)) <= VIEW_PAGE_BYTES * 2)
307
+ return workflow;
308
+ if (!isJsonObject(workflow) ||
309
+ !isJsonObject(workflow.nodes) ||
310
+ typeof workflow.schema !== "string" ||
311
+ typeof workflow.name !== "string" ||
312
+ typeof workflow.startAt !== "string" ||
313
+ !Array.isArray(workflow.edges)) {
314
+ return this.registerContent(runId, original, "application/json");
315
+ }
316
+ const nodeEntries = Object.entries(workflow.nodes);
317
+ const boundedNodeEntries = byteBoundedForwardPage(nodeEntries, ([nodeId, node]) => [
318
+ nodeId,
319
+ this.projectWorkflowNode(runId, node),
320
+ ]);
321
+ const nodes = Object.fromEntries(boundedNodeEntries.flatMap((entry) => Array.isArray(entry) && typeof entry[0] === "string" && entry[1] !== undefined
322
+ ? [[entry[0], entry[1]]]
323
+ : []));
324
+ const edges = byteBoundedForwardPage(workflow.edges, (edge) => this.projectValue(runId, edge));
325
+ return {
326
+ schema: workflow.schema,
327
+ name: workflow.name,
328
+ startAt: workflow.startAt,
329
+ nodes,
330
+ nodeStart: 0,
331
+ nodeTotal: nodeEntries.length,
332
+ edges,
333
+ edgeStart: 0,
334
+ edgeTotal: workflow.edges.length,
335
+ content: this.registerContent(runId, original, "application/json"),
336
+ };
337
+ }
338
+ projectWorkflowNode(runId, value) {
339
+ if (!isJsonObject(value))
340
+ return this.projectValue(runId, value);
341
+ const projected = {};
342
+ for (const field of [
343
+ "nodeType",
344
+ "timeoutMs",
345
+ "statusDetail",
346
+ "actionExecution",
347
+ "settingsRoute",
348
+ "effect",
349
+ "mountPath",
350
+ "localNodeId",
351
+ "includeTransition",
352
+ ]) {
353
+ const fieldValue = value[field];
354
+ if (fieldValue !== undefined)
355
+ projected[field] = this.projectValue(runId, fieldValue);
356
+ }
357
+ return projected;
358
+ }
359
+ projectDisplay(runId, display) {
360
+ if (display.reason === null ||
361
+ Buffer.byteLength(display.reason, "utf8") <= INLINE_CONTENT_BYTES) {
362
+ return display;
363
+ }
364
+ return {
365
+ ...display,
366
+ reason: "Complete workflow failure details are available.",
367
+ reasonContent: this.registerContent(runId, display.reason, "text/plain"),
368
+ };
369
+ }
370
+ projectValue(runId, value) {
371
+ const safeValue = escapeArtifactSentinels(value);
372
+ const mediaType = typeof value === "string" ? "text/plain" : "application/json";
373
+ const bytes = mediaType === "text/plain"
374
+ ? Buffer.from(value, "utf8")
375
+ : Buffer.from(canonicalJson(value), "utf8");
376
+ return bytes.byteLength <= INLINE_CONTENT_BYTES
377
+ ? safeValue
378
+ : this.registerContent(runId, value, mediaType);
379
+ }
380
+ registerContent(runId, value, mediaType) {
381
+ const bytes = Buffer.from(mediaType === "text/plain" ? value : canonicalJson(value), "utf8");
382
+ const sha256 = createHash("sha256").update(bytes).digest("hex");
383
+ const persistedDigest = this.runs.persistViewContent(runId, bytes, mediaType);
384
+ if (persistedDigest !== sha256)
385
+ throw new Error("Workflow view content digest changed");
386
+ const extension = mediaType === "text/plain" ? "txt" : "json";
387
+ const contentPath = `artifacts/sha256/${sha256}.${extension}`;
388
+ this.rememberContent({
389
+ runId,
390
+ path: contentPath,
391
+ mediaType,
392
+ bytes,
393
+ sha256,
394
+ });
395
+ return {
396
+ $artifact: {
397
+ path: contentPath,
398
+ mediaType,
399
+ bytes: bytes.byteLength,
400
+ sha256,
401
+ opaque: true,
402
+ },
403
+ };
404
+ }
405
+ rememberContent(record) {
406
+ const key = contentKey(record.runId, record.path);
407
+ const previous = this.contentRecords.get(key);
408
+ if (previous !== undefined)
409
+ this.contentBytes -= previous.bytes.byteLength;
410
+ this.contentRecords.delete(key);
411
+ this.contentRecords.set(key, record);
412
+ this.contentBytes += record.bytes.byteLength;
413
+ while (this.contentBytes > CONTENT_CACHE_BYTES && this.contentRecords.size > 1) {
414
+ const oldest = this.contentRecords.entries().next().value;
415
+ if (oldest === undefined)
416
+ break;
417
+ this.contentRecords.delete(oldest[0]);
418
+ this.contentBytes -= oldest[1].bytes.byteLength;
419
+ }
420
+ return record;
421
+ }
422
+ recoverContent(runId, contentPath) {
423
+ const match = /^artifacts\/sha256\/([0-9a-f]{64})\.(json|txt)$/u.exec(contentPath);
424
+ if (match === null)
425
+ return undefined;
426
+ const mediaType = match[2] === "txt" ? "text/plain" : "application/json";
427
+ const blob = this.runs.readContentBlob(runId, match[1], mediaType);
428
+ if (blob === undefined)
429
+ return undefined;
430
+ return this.rememberContent({
431
+ runId,
432
+ path: contentPath,
433
+ mediaType,
434
+ bytes: blob.content,
435
+ sha256: match[1],
436
+ });
437
+ }
438
+ reportActivity(connectionId, report) {
439
+ if (report.deliveryId !== `interaction:${report.requestId}`) {
440
+ throw new Error("Origin activity delivery does not match the interactive request");
441
+ }
442
+ const key = activityKey(connectionId, report.requestId);
443
+ const previous = this.activity.get(key);
444
+ if (report.state === "settled") {
445
+ if (previous === undefined)
446
+ return;
447
+ if (previous.sessionId !== report.sessionId ||
448
+ previous.runId !== report.runId ||
449
+ previous.requestId !== report.requestId ||
450
+ previous.deliveryId !== report.deliveryId ||
451
+ previous.sessionEntryId !== report.sessionEntryId) {
452
+ throw new Error("Origin activity identity changed");
453
+ }
454
+ if (report.sequence <= previous.sequence) {
455
+ throw new Error("Origin activity sequence must increase");
456
+ }
457
+ this.activity.delete(key);
458
+ this.activityRevision += 1;
459
+ return;
460
+ }
461
+ const request = this.hostState
462
+ .listPendingInteractions(report.sessionId)
463
+ .find((candidate) => candidate.requestId === report.requestId);
464
+ validateActivityRequest(request, report);
465
+ if (previous !== undefined) {
466
+ if (previous.sessionId !== report.sessionId ||
467
+ previous.runId !== report.runId ||
468
+ previous.requestId !== report.requestId ||
469
+ previous.deliveryId !== report.deliveryId ||
470
+ previous.sessionEntryId !== report.sessionEntryId) {
471
+ throw new Error("Origin activity identity changed");
472
+ }
473
+ if (report.sequence <= previous.sequence) {
474
+ throw new Error("Origin activity sequence must increase");
475
+ }
476
+ }
477
+ else if (report.state !== "started") {
478
+ throw new Error("Origin activity must start before refresh");
479
+ }
480
+ this.activity.set(key, {
481
+ ...report,
482
+ connectionId,
483
+ expiresAt: Date.now() + ORIGIN_ACTIVITY_LEASE_MS,
484
+ });
485
+ if (previous === undefined)
486
+ this.activityRevision += 1;
487
+ }
488
+ clearConnection(connectionId) {
489
+ let changed = false;
490
+ for (const [key, value] of this.activity) {
491
+ if (value.connectionId !== connectionId)
492
+ continue;
493
+ this.activity.delete(key);
494
+ changed = true;
495
+ }
496
+ if (changed)
497
+ this.activityRevision += 1;
498
+ }
499
+ expireActivity(now = Date.now()) {
500
+ let changed = false;
501
+ for (const [key, value] of this.activity) {
502
+ if (value.expiresAt > now)
503
+ continue;
504
+ this.activity.delete(key);
505
+ changed = true;
506
+ }
507
+ if (changed)
508
+ this.activityRevision += 1;
509
+ }
510
+ display(queue, state) {
511
+ return reduceWorkflowDisplay({
512
+ queueStatus: queue.status,
513
+ durableStatus: state?.status,
514
+ paused: state?.paused === true,
515
+ ambiguous: this.hasAmbiguousEffect(queue.runId),
516
+ workerActive: this.hasLiveWorker(queue.runId),
517
+ originTurnActive: this.hasActivity(queue.runId),
518
+ pendingInteraction: this.hasPendingInteraction(queue.runId),
519
+ errorMessage: state?.error ?? queue.errorMessage,
520
+ });
521
+ }
522
+ hasActivity(runId) {
523
+ for (const activity of this.activity.values()) {
524
+ if (activity.runId === runId)
525
+ return true;
526
+ }
527
+ return false;
528
+ }
529
+ hasPendingInteraction(runId) {
530
+ const row = this.state.connection
531
+ .prepare(`SELECT 1 AS present FROM interactive_requests
532
+ WHERE run_id = ? AND status IN ('pending', 'presenting') LIMIT 1`)
533
+ .get(runId);
534
+ return row !== undefined;
535
+ }
536
+ hasAmbiguousEffect(runId) {
537
+ const row = this.state.connection
538
+ .prepare(`SELECT 1 AS present FROM effects e JOIN runs r ON r.resource_id = e.source_resource_id
539
+ WHERE r.run_id = ? AND e.status = 'ambiguous' LIMIT 1`)
540
+ .get(runId);
541
+ return row !== undefined;
542
+ }
543
+ runVersion(runId) {
544
+ const row = this.state.connection
545
+ .prepare(`SELECT res.revision, r.status AS runStatus, r.paused,
546
+ q.updated_at AS updatedAt,
547
+ COALESCE(v.presentation_revision, 0) AS presentationRevision
548
+ FROM runs r JOIN resources res ON res.resource_id = r.resource_id
549
+ JOIN run_queue q ON q.run_id = r.run_id
550
+ LEFT JOIN viewer_runs v ON v.run_id = r.run_id
551
+ WHERE r.run_id = ?`)
552
+ .get(runId);
553
+ if (!isRunVersionRow(row))
554
+ return "missing";
555
+ return [
556
+ row.revision,
557
+ row.updatedAt,
558
+ row.presentationRevision,
559
+ row.runStatus,
560
+ row.paused,
561
+ this.activityRevision,
562
+ this.hasLiveWorker(runId),
563
+ this.hasActivity(runId),
564
+ this.hasPendingInteraction(runId),
565
+ this.hasAmbiguousEffect(runId),
566
+ ].join(":");
567
+ }
568
+ pendingSessionRevision(sessionId) {
569
+ const row = this.state.connection
570
+ .prepare(`SELECT count(*) AS count, COALESCE(sum(revision), 0) AS revisionSum,
571
+ COALESCE(max(updated_at), 0) AS updatedAt
572
+ FROM interactive_requests
573
+ WHERE target_session_id = ? AND status IN ('pending', 'presenting')`)
574
+ .get(sessionId);
575
+ if (!isSessionRevisionRow(row))
576
+ throw new Error("Session view revision is invalid");
577
+ return `${row.count}:${row.revisionSum}:${row.updatedAt}`;
578
+ }
579
+ presentationRevision(runId) {
580
+ const row = this.state.connection
581
+ .prepare(`SELECT presentation_revision AS revision FROM viewer_runs WHERE run_id = ?`)
582
+ .get(runId);
583
+ return isRevisionRow(row) ? row.revision : 0;
584
+ }
585
+ }
586
+ export function reduceWorkflowDisplay(facts) {
587
+ let status;
588
+ let activity = null;
589
+ let reason = null;
590
+ if (facts.ambiguous) {
591
+ status = "ambiguous";
592
+ reason = "An external effect needs explicit recovery.";
593
+ }
594
+ else if (facts.durableStatus === "completed" ||
595
+ facts.durableStatus === "failed" ||
596
+ facts.durableStatus === "timed_out" ||
597
+ facts.durableStatus === "cancelled") {
598
+ status = facts.durableStatus;
599
+ reason = facts.errorMessage;
600
+ }
601
+ else if (facts.paused) {
602
+ status = "paused";
603
+ reason = "The workflow is durably paused.";
604
+ }
605
+ else if (facts.workerActive || facts.originTurnActive) {
606
+ status = "running";
607
+ activity = facts.workerActive ? "supervised_worker" : "origin_turn";
608
+ }
609
+ else if (facts.pendingInteraction || facts.durableStatus === "waiting") {
610
+ status = "waiting";
611
+ reason = "The workflow is waiting for origin-session input.";
612
+ }
613
+ else if (facts.queueStatus === "parked" || facts.queueStatus === "queued") {
614
+ status = "queued";
615
+ reason = facts.queueStatus === "parked" ? "The workflow is ready to resume." : null;
616
+ }
617
+ else if (facts.queueStatus === "done") {
618
+ status = "completed";
619
+ }
620
+ else if (facts.queueStatus === "failed" || facts.queueStatus === "cancelled") {
621
+ status = facts.queueStatus;
622
+ reason = facts.errorMessage;
623
+ }
624
+ else {
625
+ status = "running";
626
+ }
627
+ const controls = [];
628
+ if (status === "running" || status === "waiting")
629
+ controls.push("pause", "cancel");
630
+ else if (status === "paused")
631
+ controls.push("resume", "cancel");
632
+ else if (status === "queued") {
633
+ if (facts.queueStatus === "parked")
634
+ controls.push("resume");
635
+ controls.push("cancel");
636
+ }
637
+ if (status === "waiting")
638
+ controls.push("answer");
639
+ if (status === "ambiguous")
640
+ controls.push("review");
641
+ return { status, activity, controls, reason };
642
+ }
643
+ function manifest(run, status) {
644
+ return {
645
+ schema: "pi-workflows.run-manifest.v1",
646
+ runId: run.runId,
647
+ workflowName: run.workflowName,
648
+ workflowSource: workflowRootSource(run.workflowSource),
649
+ startedAt: run.startedAt ?? run.createdAt,
650
+ ...(run.finishedAt === null ? {} : { finishedAt: run.finishedAt }),
651
+ status,
652
+ traceSchema: "pi-workflows.trace-event.v1",
653
+ paths: {
654
+ workflow: "host",
655
+ state: "host",
656
+ trace: "host",
657
+ },
658
+ };
659
+ }
660
+ function projectQueue(run) {
661
+ return {
662
+ runId: run.runId,
663
+ workflowName: run.workflowName,
664
+ workflowSourceRef: run.workflowSourceRef,
665
+ initialized: run.initialized,
666
+ definitionDigest: run.definitionDigest,
667
+ status: run.status,
668
+ originSessionId: run.originSessionId,
669
+ executionMode: run.executionMode,
670
+ parentRunId: run.parentRunId,
671
+ errorCode: run.errorCode,
672
+ createdAt: run.createdAt,
673
+ updatedAt: run.updatedAt,
674
+ startedAt: run.startedAt,
675
+ finishedAt: run.finishedAt,
676
+ };
677
+ }
678
+ function workflowRootSource(value) {
679
+ const sourceSet = toJson(value);
680
+ if (!isJsonObject(sourceSet))
681
+ throw new Error("Workflow queue source set is invalid");
682
+ const root = sourceSet.root;
683
+ if (root === undefined || !isJsonObject(root)) {
684
+ throw new Error("Workflow queue source set is invalid");
685
+ }
686
+ return root;
687
+ }
688
+ function validateActivityRequest(request, report) {
689
+ if (request === undefined)
690
+ throw new Error("Origin activity request is not pending");
691
+ if (request.runId !== report.runId || request.targetSessionId !== report.sessionId) {
692
+ throw new Error("Origin activity target does not match the interactive request");
693
+ }
694
+ if (request.presentationSessionEntryId !== report.sessionEntryId) {
695
+ throw new Error("Origin activity session entry was not durably presented");
696
+ }
697
+ if (!Number.isSafeInteger(report.sequence) || report.sequence < 0) {
698
+ throw new Error("Origin activity sequence must be a non-negative integer");
699
+ }
700
+ }
701
+ function activityKey(connectionId, requestId) {
702
+ return `${connectionId}\u0000${requestId}`;
703
+ }
704
+ function contentKey(runId, contentPath) {
705
+ return `${runId}\u0000${contentPath}`;
706
+ }
707
+ function escapeArtifactSentinels(value) {
708
+ if (Array.isArray(value))
709
+ return value.map(escapeArtifactSentinels);
710
+ if (!isJsonObject(value))
711
+ return value;
712
+ const escaped = Object.fromEntries(Object.entries(value).map(([key, item]) => [key, escapeArtifactSentinels(item)]));
713
+ return Object.keys(value).length === 1 &&
714
+ (Object.hasOwn(value, "$artifact") || Object.hasOwn(value, "$escaped"))
715
+ ? { $escaped: escaped }
716
+ : escaped;
717
+ }
718
+ function projectFollowUpQueue(value, items) {
719
+ const queue = toJson(value);
720
+ if (!isJsonObject(queue))
721
+ return queue;
722
+ delete queue.followUps;
723
+ queue.items = items;
724
+ return queue;
725
+ }
726
+ function refreshCacheEntry(cache, key, value) {
727
+ cache.delete(key);
728
+ cache.set(key, value);
729
+ }
730
+ function rememberCacheEntry(cache, key, value) {
731
+ refreshCacheEntry(cache, key, value);
732
+ while (cache.size > VIEW_CACHE_ITEMS) {
733
+ const oldest = cache.keys().next().value;
734
+ if (oldest === undefined)
735
+ break;
736
+ cache.delete(oldest);
737
+ }
738
+ }
739
+ function viewRange(total, cursor) {
740
+ const start = workflowPageStart(total, cursor);
741
+ return { start, limit: Math.min(VIEW_PAGE_ITEMS, Math.max(0, total - start)) };
742
+ }
743
+ function byteBoundedForwardPage(values, project) {
744
+ const items = [];
745
+ let bytes = 0;
746
+ for (const value of values) {
747
+ if (items.length >= VIEW_PAGE_ITEMS)
748
+ break;
749
+ const item = project(value);
750
+ const itemBytes = Buffer.byteLength(canonicalJson(item)) + (items.length === 0 ? 0 : 1);
751
+ if (items.length > 0 && bytes + itemBytes > VIEW_PAGE_BYTES)
752
+ break;
753
+ items.push(item);
754
+ bytes += itemBytes;
755
+ }
756
+ return items;
757
+ }
758
+ function byteBoundedCandidatePage(values, candidateStart, total, requestedCursor, project) {
759
+ if (values.length === 0)
760
+ return { start: candidateStart, total, items: [] };
761
+ const globalCursor = clampCursor(requestedCursor ?? Math.max(0, total - 1), total);
762
+ const localCursor = Math.min(Math.max(0, globalCursor - candidateStart), values.length - 1);
763
+ const page = byteBoundedPage(values, localCursor, project);
764
+ return { start: candidateStart + page.start, total, items: page.items };
765
+ }
766
+ function byteBoundedPage(values, requestedCursor, project) {
767
+ const total = values.length;
768
+ if (total === 0)
769
+ return { start: 0, total: 0, items: [] };
770
+ const cursor = clampCursor(requestedCursor ?? total - 1, total);
771
+ const selected = project(values[cursor]);
772
+ const selectedBytes = Buffer.byteLength(canonicalJson(selected));
773
+ const indexed = new Map([[cursor, selected]]);
774
+ let pageBytes = selectedBytes;
775
+ let left = cursor - 1;
776
+ let right = cursor + 1;
777
+ let leftBlocked = false;
778
+ let rightBlocked = false;
779
+ let preferLeft = true;
780
+ while (indexed.size < VIEW_PAGE_ITEMS && (!leftBlocked || !rightBlocked)) {
781
+ const index = preferLeft ? left : right;
782
+ const inRange = index >= 0 && index < total;
783
+ if (!inRange) {
784
+ if (preferLeft)
785
+ leftBlocked = true;
786
+ else
787
+ rightBlocked = true;
788
+ }
789
+ else {
790
+ const item = project(values[index]);
791
+ const itemBytes = Buffer.byteLength(canonicalJson(item)) + 1;
792
+ if (pageBytes + itemBytes > VIEW_PAGE_BYTES) {
793
+ if (preferLeft)
794
+ leftBlocked = true;
795
+ else
796
+ rightBlocked = true;
797
+ }
798
+ else {
799
+ indexed.set(index, item);
800
+ pageBytes += itemBytes;
801
+ if (preferLeft)
802
+ left -= 1;
803
+ else
804
+ right += 1;
805
+ }
806
+ }
807
+ preferLeft = !preferLeft;
808
+ }
809
+ const ordered = [...indexed.entries()].sort(([leftIndex], [rightIndex]) => leftIndex - rightIndex);
810
+ return {
811
+ start: ordered[0]?.[0] ?? cursor,
812
+ total,
813
+ items: ordered.map(([, item]) => item),
814
+ };
815
+ }
816
+ export function toCompactStepJson(step) {
817
+ return toJson({
818
+ attemptId: step.attemptId,
819
+ nodeId: step.nodeId,
820
+ nodeType: step.nodeType,
821
+ outcome: step.outcome,
822
+ startedAt: step.startedAt,
823
+ finishedAt: step.finishedAt,
824
+ prompt: null,
825
+ output: null,
826
+ ...(step.settingsScopeId === undefined ? {} : { settingsScopeId: step.settingsScopeId }),
827
+ ...(step.settingsChangeNumber === undefined
828
+ ? {}
829
+ : { settingsChangeNumber: step.settingsChangeNumber }),
830
+ ...(step.settingsHash === undefined ? {} : { settingsHash: step.settingsHash }),
831
+ });
832
+ }
833
+ export function workflowPageStart(total, cursor) {
834
+ if (total <= 256)
835
+ return 0;
836
+ if (cursor === undefined)
837
+ return total - 256;
838
+ const center = clampCursor(cursor, total);
839
+ return Math.min(Math.max(0, center - 128), total - 256);
840
+ }
841
+ function clampCursor(cursor, total) {
842
+ return total === 0 ? 0 : Math.min(cursor, total - 1);
843
+ }
844
+ function toJson(value) {
845
+ return parseJson(canonicalJson(value));
846
+ }
847
+ function isJsonObject(value) {
848
+ return typeof value === "object" && value !== null && !Array.isArray(value);
849
+ }
850
+ function isRunVersionRow(value) {
851
+ return (typeof value === "object" &&
852
+ value !== null &&
853
+ typeof value.revision === "number" &&
854
+ typeof value.updatedAt === "number" &&
855
+ typeof value.presentationRevision === "number" &&
856
+ typeof value.runStatus === "string" &&
857
+ typeof value.paused === "number");
858
+ }
859
+ function isSessionRevisionRow(value) {
860
+ return (typeof value === "object" &&
861
+ value !== null &&
862
+ typeof value.count === "number" &&
863
+ typeof value.revisionSum === "number" &&
864
+ typeof value.updatedAt === "number");
865
+ }
866
+ function isRevisionRow(value) {
867
+ return (typeof value === "object" &&
868
+ value !== null &&
869
+ typeof value.revision === "number");
870
+ }
871
+ //# sourceMappingURL=view.js.map