@h-rig/run-plugin 0.0.6-alpha.186

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 (70) hide show
  1. package/README.md +1 -0
  2. package/dist/src/plugin.d.ts +4 -0
  3. package/dist/src/plugin.js +4319 -0
  4. package/dist/src/read-model/inspect-command.d.ts +19 -0
  5. package/dist/src/read-model/inspect-command.js +341 -0
  6. package/dist/src/read-model/plugin.d.ts +4 -0
  7. package/dist/src/read-model/plugin.js +2550 -0
  8. package/dist/src/read-model/read-model-backend/diagnostics.d.ts +9 -0
  9. package/dist/src/read-model/read-model-backend/diagnostics.js +51 -0
  10. package/dist/src/read-model/read-model-backend/guard.d.ts +4 -0
  11. package/dist/src/read-model/read-model-backend/guard.js +25 -0
  12. package/dist/src/read-model/read-model-backend/inbox.d.ts +23 -0
  13. package/dist/src/read-model/read-model-backend/inbox.js +669 -0
  14. package/dist/src/read-model/read-model-backend/index.d.ts +8 -0
  15. package/dist/src/read-model/read-model-backend/index.js +1163 -0
  16. package/dist/src/read-model/read-model-backend/inspect.d.ts +26 -0
  17. package/dist/src/read-model/read-model-backend/inspect.js +770 -0
  18. package/dist/src/read-model/read-model-backend/projection.d.ts +39 -0
  19. package/dist/src/read-model/read-model-backend/projection.js +669 -0
  20. package/dist/src/read-model/read-model-backend/run-status.d.ts +27 -0
  21. package/dist/src/read-model/read-model-backend/run-status.js +237 -0
  22. package/dist/src/read-model/read-model-backend/stats.d.ts +12 -0
  23. package/dist/src/read-model/read-model-backend/stats.js +800 -0
  24. package/dist/src/read-model/read-model-service.d.ts +2 -0
  25. package/dist/src/read-model/read-model-service.js +1725 -0
  26. package/dist/src/read-model/reconcile.d.ts +23 -0
  27. package/dist/src/read-model/reconcile.js +306 -0
  28. package/dist/src/read-model/run-format.d.ts +23 -0
  29. package/dist/src/read-model/run-format.js +202 -0
  30. package/dist/src/read-model/runs-screen.d.ts +14 -0
  31. package/dist/src/read-model/runs-screen.js +217 -0
  32. package/dist/src/read-model/session-journal.d.ts +26 -0
  33. package/dist/src/read-model/session-journal.js +355 -0
  34. package/dist/src/read-model/stats-command.d.ts +16 -0
  35. package/dist/src/read-model/stats-command.js +88 -0
  36. package/dist/src/read-model/stats-format.d.ts +1 -0
  37. package/dist/src/read-model/stats-format.js +8 -0
  38. package/dist/src/worker/autohost.d.ts +11 -0
  39. package/dist/src/worker/autohost.js +858 -0
  40. package/dist/src/worker/constants.d.ts +3 -0
  41. package/dist/src/worker/constants.js +10 -0
  42. package/dist/src/worker/extension.d.ts +14 -0
  43. package/dist/src/worker/extension.js +881 -0
  44. package/dist/src/worker/host.d.ts +1 -0
  45. package/dist/src/worker/host.js +1 -0
  46. package/dist/src/worker/inbox-command.d.ts +23 -0
  47. package/dist/src/worker/inbox-command.js +163 -0
  48. package/dist/src/worker/index.d.ts +2 -0
  49. package/dist/src/worker/index.js +1767 -0
  50. package/dist/src/worker/local-run-changes.d.ts +3 -0
  51. package/dist/src/worker/local-run-changes.js +65 -0
  52. package/dist/src/worker/notifications.d.ts +1 -0
  53. package/dist/src/worker/notifications.js +27 -0
  54. package/dist/src/worker/notify-cap.d.ts +11 -0
  55. package/dist/src/worker/notify-cap.js +13 -0
  56. package/dist/src/worker/panel-plugin.d.ts +11 -0
  57. package/dist/src/worker/panel-plugin.js +37 -0
  58. package/dist/src/worker/plugin.d.ts +3 -0
  59. package/dist/src/worker/plugin.js +1761 -0
  60. package/dist/src/worker/run-control-service.d.ts +2 -0
  61. package/dist/src/worker/run-control-service.js +210 -0
  62. package/dist/src/worker/session-journal-writer.d.ts +4 -0
  63. package/dist/src/worker/session-journal-writer.js +184 -0
  64. package/dist/src/worker/stall.d.ts +21 -0
  65. package/dist/src/worker/stall.js +55 -0
  66. package/dist/src/worker/utils.d.ts +21 -0
  67. package/dist/src/worker/utils.js +29 -0
  68. package/dist/src/worker/workflow-journal-writer.d.ts +7 -0
  69. package/dist/src/worker/workflow-journal-writer.js +76 -0
  70. package/package.json +47 -0
@@ -0,0 +1,669 @@
1
+ // @bun
2
+ // packages/run-plugin/src/read-model/read-model-backend/projection.ts
3
+ import { existsSync, readFileSync } from "fs";
4
+ import { isAbsolute, relative, resolve } from "path";
5
+ import { RUN_DISCOVERY, RUN_REGISTRY_BACKBONE } from "@rig/contracts";
6
+
7
+ // packages/run-plugin/src/read-model/session-journal.ts
8
+ import { Schema } from "effect";
9
+ import {
10
+ CUSTOM_TYPE_FOR,
11
+ RIG_CONTROL_SENTINEL_END,
12
+ RIG_INBOX_RESOLUTION_SENTINEL,
13
+ RIG_PAUSE_SENTINEL,
14
+ RIG_RESUME_SENTINEL,
15
+ RIG_STOP_SENTINEL,
16
+ RIG_STOP_SENTINEL_END,
17
+ RunJournalEvent,
18
+ TYPE_FOR_CUSTOM
19
+ } from "@rig/contracts";
20
+ var decodeRunJournalEvent = (value) => Schema.decodeUnknownSync(RunJournalEvent)(value);
21
+ var RUN_STATUS_TRANSITIONS = {
22
+ created: ["queued", "preparing", "running", "failed", "stopped"],
23
+ queued: ["preparing", "running", "failed", "stopped"],
24
+ preparing: ["queued", "running", "needs-attention", "failed", "stopped"],
25
+ running: [
26
+ "queued",
27
+ "waiting-approval",
28
+ "waiting-user-input",
29
+ "paused",
30
+ "validating",
31
+ "reviewing",
32
+ "closing-out",
33
+ "needs-attention",
34
+ "completed",
35
+ "failed",
36
+ "stopped"
37
+ ],
38
+ "waiting-approval": ["running", "needs-attention", "failed", "stopped"],
39
+ "waiting-user-input": ["running", "needs-attention", "failed", "stopped"],
40
+ paused: ["running", "failed", "stopped"],
41
+ validating: ["running", "reviewing", "closing-out", "needs-attention", "completed", "failed", "stopped"],
42
+ reviewing: ["running", "validating", "closing-out", "needs-attention", "completed", "failed", "stopped"],
43
+ "closing-out": ["running", "needs-attention", "completed", "failed", "stopped"],
44
+ "needs-attention": ["queued", "preparing", "running", "closing-out", "completed", "failed", "stopped"],
45
+ completed: [],
46
+ failed: ["queued", "preparing", "running", "closing-out"],
47
+ stopped: ["queued", "preparing", "running", "closing-out"]
48
+ };
49
+ var TERMINAL_RUN_STATUSES = ["completed", "failed", "stopped"];
50
+ function isTerminalRunStatus(status) {
51
+ return TERMINAL_RUN_STATUSES.includes(status);
52
+ }
53
+ function canTransitionRunStatus(from, to) {
54
+ if (from === null)
55
+ return true;
56
+ if (from === to)
57
+ return true;
58
+ return RUN_STATUS_TRANSITIONS[from].includes(to);
59
+ }
60
+ function reduceRunJournal(events, runId = null) {
61
+ let record = {};
62
+ let status = null;
63
+ const statusHistory = [];
64
+ const pendingApprovals = new Map;
65
+ const resolvedApprovals = [];
66
+ const pendingUserInputs = new Map;
67
+ const resolvedUserInputs = [];
68
+ const closeoutPhases = [];
69
+ let resolvedPipeline = null;
70
+ const stageOutcomes = [];
71
+ const anomalies = [];
72
+ let steeringCount = 0;
73
+ let stallCount = 0;
74
+ let lastSeq = 0;
75
+ let lastEventAt = null;
76
+ const projectedRunId = runId ?? events[0]?.runId ?? null;
77
+ for (const event of events) {
78
+ lastSeq = event.seq;
79
+ lastEventAt = event.at;
80
+ switch (event.type) {
81
+ case "status-changed": {
82
+ if (!canTransitionRunStatus(status, event.to)) {
83
+ anomalies.push({ seq: event.seq, kind: "illegal-transition", detail: `${status ?? "(none)"} -> ${event.to}` });
84
+ }
85
+ statusHistory.push({ seq: event.seq, at: event.at, from: status, to: event.to, reason: event.reason ?? null });
86
+ const wasTerminal = status !== null && isTerminalRunStatus(status);
87
+ status = event.to;
88
+ record = { ...record, updatedAt: event.at };
89
+ if (isTerminalRunStatus(event.to) && !record.completedAt)
90
+ record = { ...record, completedAt: event.at };
91
+ if (!isTerminalRunStatus(event.to) && wasTerminal)
92
+ record = { ...record, completedAt: null };
93
+ if (event.to === "running" && !record.startedAt)
94
+ record = { ...record, startedAt: event.at };
95
+ break;
96
+ }
97
+ case "record-patch": {
98
+ const next = { ...record };
99
+ for (const [key, value] of Object.entries(event.patch)) {
100
+ if (value !== undefined)
101
+ next[key] = value;
102
+ }
103
+ next.updatedAt = event.patch.updatedAt ?? event.at;
104
+ record = next;
105
+ break;
106
+ }
107
+ case "approval-requested": {
108
+ pendingApprovals.set(event.requestId, {
109
+ requestId: event.requestId,
110
+ requestKind: event.requestKind,
111
+ actionId: event.actionId ?? null,
112
+ payload: event.payload,
113
+ requestedAt: event.at
114
+ });
115
+ break;
116
+ }
117
+ case "approval-resolved": {
118
+ const pending = pendingApprovals.get(event.requestId);
119
+ if (!pending) {
120
+ const alreadyResolved = resolvedApprovals.some((entry) => entry.requestId === event.requestId);
121
+ anomalies.push({ seq: event.seq, kind: alreadyResolved ? "duplicate-resolution" : "unknown-request", detail: `approval ${event.requestId}` });
122
+ break;
123
+ }
124
+ pendingApprovals.delete(event.requestId);
125
+ resolvedApprovals.push({ ...pending, decision: event.decision, note: event.note ?? null, actor: event.actor, resolvedAt: event.at });
126
+ break;
127
+ }
128
+ case "input-requested": {
129
+ pendingUserInputs.set(event.requestId, {
130
+ requestId: event.requestId,
131
+ requestKind: "user-input",
132
+ actionId: null,
133
+ payload: event.payload,
134
+ requestedAt: event.at
135
+ });
136
+ break;
137
+ }
138
+ case "input-resolved": {
139
+ const pending = pendingUserInputs.get(event.requestId);
140
+ if (!pending) {
141
+ const alreadyResolved = resolvedUserInputs.some((entry) => entry.requestId === event.requestId);
142
+ anomalies.push({ seq: event.seq, kind: alreadyResolved ? "duplicate-resolution" : "unknown-request", detail: `user-input ${event.requestId}` });
143
+ break;
144
+ }
145
+ pendingUserInputs.delete(event.requestId);
146
+ resolvedUserInputs.push({ ...pending, answers: event.answers, actor: event.actor, resolvedAt: event.at });
147
+ break;
148
+ }
149
+ case "steering":
150
+ steeringCount += 1;
151
+ break;
152
+ case "adopted":
153
+ record = { ...record, pid: event.pid, updatedAt: event.at };
154
+ break;
155
+ case "stall-detected":
156
+ stallCount += 1;
157
+ break;
158
+ case "closeout-phase":
159
+ closeoutPhases.push({ seq: event.seq, at: event.at, phase: event.phase, outcome: event.outcome, detail: event.detail ?? null });
160
+ break;
161
+ case "pipeline-resolved":
162
+ resolvedPipeline = event.pipeline;
163
+ break;
164
+ case "stage-outcome":
165
+ stageOutcomes.push({ seq: event.seq, at: event.at, outcome: event.outcome });
166
+ break;
167
+ case "timeline-entry":
168
+ case "log-entry":
169
+ break;
170
+ }
171
+ }
172
+ return {
173
+ runId: projectedRunId,
174
+ record,
175
+ status,
176
+ statusHistory,
177
+ pendingApprovals: [...pendingApprovals.values()],
178
+ resolvedApprovals,
179
+ pendingUserInputs: [...pendingUserInputs.values()],
180
+ resolvedUserInputs,
181
+ steeringCount,
182
+ stallCount,
183
+ closeoutPhases,
184
+ resolvedPipeline,
185
+ stageOutcomes,
186
+ lastSeq,
187
+ lastEventAt,
188
+ anomalies
189
+ };
190
+ }
191
+ function isRunSessionCustomType(customType) {
192
+ return customType !== undefined && Object.hasOwn(TYPE_FOR_CUSTOM, customType);
193
+ }
194
+ function foldRunSessionEntries(entries, runId) {
195
+ const events = [];
196
+ entries.forEach((entry, index) => {
197
+ if (entry.type !== "custom" || !isRunSessionCustomType(entry.customType))
198
+ return;
199
+ const data = entry.data !== null && typeof entry.data === "object" ? entry.data : {};
200
+ const stamped = {
201
+ v: 1,
202
+ seq: index + 1,
203
+ at: typeof data.at === "string" ? data.at : new Date(0).toISOString(),
204
+ runId,
205
+ ...data,
206
+ type: TYPE_FOR_CUSTOM[entry.customType]
207
+ };
208
+ try {
209
+ events.push(decodeRunJournalEvent(stamped));
210
+ } catch {}
211
+ });
212
+ return reduceRunJournal(events, runId);
213
+ }
214
+ function isRecord(value) {
215
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
216
+ }
217
+ function timelineEntryFromCustomEntry(entry) {
218
+ if (entry.customType !== CUSTOM_TYPE_FOR["timeline-entry"] || !isRecord(entry.data))
219
+ return null;
220
+ const payload = isRecord(entry.data.payload) ? entry.data.payload : entry.data;
221
+ const type = typeof payload.type === "string" ? payload.type : "timeline";
222
+ const stage = typeof payload.stage === "string" ? payload.stage : typeof payload.name === "string" ? payload.name : null;
223
+ const status = typeof payload.status === "string" ? payload.status : typeof payload.outcome === "string" ? payload.outcome : null;
224
+ const detail = typeof payload.detail === "string" ? payload.detail : typeof payload.message === "string" ? payload.message : null;
225
+ const at = typeof entry.data.at === "string" ? entry.data.at : typeof payload.at === "string" ? payload.at : null;
226
+ return { at, type, stage, status, detail };
227
+ }
228
+ function timelineEntriesFromCustomEntries(entries) {
229
+ return entries.flatMap((entry) => {
230
+ const timelineEntry = timelineEntryFromCustomEntry(entry);
231
+ return timelineEntry ? [timelineEntry] : [];
232
+ });
233
+ }
234
+
235
+ // packages/run-plugin/src/read-model/read-model-backend/projection.ts
236
+ import { loadCapabilityForRoot } from "@rig/core/capability-loaders";
237
+ import { defineCapability } from "@rig/core/capability";
238
+
239
+ // packages/run-plugin/src/read-model/read-model-backend/run-status.ts
240
+ var OPERATOR_INACTIVE_RUN_STATUSES = new Set([
241
+ "completed",
242
+ "complete",
243
+ "done",
244
+ "success",
245
+ "succeeded",
246
+ "passed",
247
+ "failed",
248
+ "failure",
249
+ "error",
250
+ "errored",
251
+ "stopped",
252
+ "cancelled",
253
+ "canceled",
254
+ "aborted",
255
+ "abort",
256
+ "merged",
257
+ "closed",
258
+ "skipped",
259
+ "needs-attention",
260
+ "needs_attention"
261
+ ]);
262
+ var TERMINAL_RUN_STATUSES2 = ["completed", "failed", "stopped"];
263
+ var RUNTIME_ACTIVE_STATUSES = new Set([
264
+ "created",
265
+ "preparing",
266
+ "running",
267
+ "validating",
268
+ "reviewing",
269
+ "closing-out"
270
+ ]);
271
+ var ACTIVE_RUN_STATUSES = [
272
+ "created",
273
+ "queued",
274
+ "preparing",
275
+ "running",
276
+ "waiting-approval",
277
+ "waiting-user-input",
278
+ "paused",
279
+ "validating",
280
+ "reviewing",
281
+ "closing-out",
282
+ "needs-attention"
283
+ ];
284
+ var KNOWN_RUN_STATUS = Object.fromEntries([...ACTIVE_RUN_STATUSES, ...TERMINAL_RUN_STATUSES2].map((status) => [status, true]));
285
+ function isRuntimeActiveStatus(status) {
286
+ return RUNTIME_ACTIVE_STATUSES.has(normalizeRunStatusToken(status));
287
+ }
288
+ function normalizeRunStatusToken(status) {
289
+ return String(status ?? "").trim().toLowerCase().replace(/[\s_]+/g, "-");
290
+ }
291
+
292
+ // packages/run-plugin/src/read-model/read-model-backend/diagnostics.ts
293
+ function normalizeString(value) {
294
+ if (typeof value !== "string")
295
+ return null;
296
+ const normalized = value.replace(/\s+/g, " ").trim();
297
+ return normalized.length > 0 ? normalized : null;
298
+ }
299
+ function isGenericRunFailure(value) {
300
+ const text = normalizeString(value);
301
+ return Boolean(text && /^Task run failed \([^)]*\)$/i.test(text));
302
+ }
303
+ function appendCandidate(candidates, value) {
304
+ const text = normalizeString(value);
305
+ if (text && !candidates.includes(text))
306
+ candidates.push(text);
307
+ }
308
+ function categorizeUsefulRunError(lines) {
309
+ const taskSourceFailure = lines.find((line) => /failed to update task source/i.test(line));
310
+ if (taskSourceFailure)
311
+ return `Task source update failed: ${taskSourceFailure}`;
312
+ const moduleFailure = lines.find((line) => /cannot find module/i.test(line));
313
+ if (moduleFailure)
314
+ return `Runtime module resolution failed: ${moduleFailure}`;
315
+ const providerFailure = lines.find((line) => /no api key found|unauthorized|authentication failed|invalid api key/i.test(line));
316
+ if (providerFailure)
317
+ return `Provider authentication failed: ${providerFailure}`;
318
+ return null;
319
+ }
320
+ function summarizeRunError(projection) {
321
+ if (projection.status !== "failed")
322
+ return null;
323
+ const candidates = [];
324
+ for (const anomaly of projection.anomalies) {
325
+ appendCandidate(candidates, `Journal anomaly (${anomaly.kind}): ${anomaly.detail}`);
326
+ }
327
+ for (const phase of projection.closeoutPhases) {
328
+ if (phase.outcome === "failed")
329
+ appendCandidate(candidates, phase.detail);
330
+ }
331
+ for (const entry of projection.statusHistory) {
332
+ appendCandidate(candidates, entry.reason);
333
+ }
334
+ appendCandidate(candidates, projection.record.statusDetail);
335
+ appendCandidate(candidates, projection.record.errorText);
336
+ const nonGeneric = candidates.filter((candidate) => !isGenericRunFailure(candidate));
337
+ return categorizeUsefulRunError(nonGeneric) ?? nonGeneric.at(-1) ?? normalizeString(projection.record.errorText);
338
+ }
339
+
340
+ // packages/run-plugin/src/read-model/read-model-backend/projection.ts
341
+ var RunDiscoveryCap = defineCapability(RUN_DISCOVERY);
342
+ var RunRegistryBackboneCap = defineCapability(RUN_REGISTRY_BACKBONE);
343
+ function registryEntryFromCollab(collab) {
344
+ const record = collab;
345
+ return {
346
+ roomId: collab.sessionId,
347
+ title: collab.title,
348
+ status: record.registryStatus ?? (collab.stale ? "stale" : "running"),
349
+ startedAt: collab.startedAt ?? null,
350
+ heartbeatAt: collab.updatedAt ?? null,
351
+ sessionPath: collab.sessionPath ?? null,
352
+ cwd: collab.cwd ?? null,
353
+ joinLink: collab.joinLink ?? null,
354
+ webLink: collab.webLink ?? null,
355
+ relayUrl: collab.relayUrl ?? null,
356
+ stale: collab.stale,
357
+ repo: collab.selectedRepo ?? null,
358
+ ...collab.pid === undefined ? {} : { pid: collab.pid },
359
+ projection: record.registryProjection ?? null
360
+ };
361
+ }
362
+ var EMPTY_PROJECTION = foldRunSessionEntries([], "");
363
+ var DISCOVERY_DIAGNOSTIC_RUN_ID = "__registry_discovery_error__";
364
+ function readSessionRunEntries(sessionPath) {
365
+ if (!sessionPath || !existsSync(sessionPath))
366
+ return [];
367
+ try {
368
+ return parseSessionRunEntries(readFileSync(sessionPath, "utf8"));
369
+ } catch {
370
+ return [];
371
+ }
372
+ }
373
+ function parseSessionRunEntries(raw) {
374
+ const entries = [];
375
+ for (const line of raw.split(`
376
+ `)) {
377
+ if (!line.trim())
378
+ continue;
379
+ try {
380
+ const parsed = JSON.parse(line);
381
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
382
+ continue;
383
+ entries.push({
384
+ type: "type" in parsed && typeof parsed.type === "string" ? parsed.type : "",
385
+ ..."customType" in parsed && typeof parsed.customType === "string" ? { customType: parsed.customType } : {},
386
+ ..."data" in parsed ? { data: parsed.data } : {}
387
+ });
388
+ } catch {
389
+ continue;
390
+ }
391
+ }
392
+ return entries;
393
+ }
394
+ function stringOrNull(value) {
395
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
396
+ }
397
+ function numberOrNull(value) {
398
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
399
+ }
400
+ function objectRecord(value) {
401
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
402
+ }
403
+ function payloadString(payload, keys) {
404
+ if (!payload || typeof payload !== "object")
405
+ return null;
406
+ const record = payload;
407
+ for (const key of keys) {
408
+ const value = record[key];
409
+ if (typeof value === "string" && value.trim())
410
+ return value.trim();
411
+ }
412
+ return null;
413
+ }
414
+ function payloadOptions(payload) {
415
+ if (!payload || typeof payload !== "object")
416
+ return;
417
+ const record = payload;
418
+ const options = Array.isArray(record.options) ? record.options : Array.isArray(record.choices) ? record.choices : null;
419
+ const values = options?.filter((value) => typeof value === "string" && value.trim().length > 0) ?? [];
420
+ return values.length > 0 ? values : undefined;
421
+ }
422
+ function inboxRequest(request, kind) {
423
+ const fallback = kind === "approval" ? "Approval requested" : "Input requested";
424
+ const body = payloadString(request.payload, ["body", "description", "detail", "details"]);
425
+ const options = payloadOptions(request.payload);
426
+ return {
427
+ requestId: request.requestId,
428
+ kind,
429
+ title: payloadString(request.payload, ["title", "message", "reason", "prompt", "summary"]) ?? fallback,
430
+ ...body !== undefined ? { body } : {},
431
+ ...options ? { options } : {},
432
+ requestedAt: request.requestedAt ?? null,
433
+ source: "run"
434
+ };
435
+ }
436
+ function inboxFromProjection(projection) {
437
+ return [
438
+ ...projection.pendingApprovals.map((request) => inboxRequest(request, "approval")),
439
+ ...projection.pendingUserInputs.map((request) => inboxRequest(request, "input"))
440
+ ].sort((a, b) => (Date.parse(a.requestedAt ?? "") || 0) - (Date.parse(b.requestedAt ?? "") || 0));
441
+ }
442
+ function isProjectPath(projectRoot, cwd) {
443
+ const root = resolve(projectRoot);
444
+ const candidate = resolve(cwd);
445
+ const pathFromRoot = relative(root, candidate);
446
+ return pathFromRoot === "" || !pathFromRoot.startsWith("../") && pathFromRoot !== ".." && !isAbsolute(pathFromRoot);
447
+ }
448
+ function sourceFromEntry(projectRoot, projection, entry) {
449
+ const candidates = [
450
+ stringOrNull(projection.collabCwd),
451
+ stringOrNull(projection.cwd),
452
+ stringOrNull(entry.cwd),
453
+ stringOrNull(projection.worktreePath)
454
+ ].filter((cwd) => cwd !== null);
455
+ return candidates.some((cwd) => isProjectPath(projectRoot, cwd)) ? "local" : "remote";
456
+ }
457
+ function pendingRequests(value, fallbackKind) {
458
+ if (!Array.isArray(value))
459
+ return [];
460
+ return value.flatMap((item) => {
461
+ const record = objectRecord(item);
462
+ const requestId = stringOrNull(record?.requestId) ?? stringOrNull(record?.id);
463
+ if (!record || !requestId)
464
+ return [];
465
+ return [{
466
+ requestId,
467
+ requestKind: stringOrNull(record.requestKind) ?? stringOrNull(record.kind) ?? fallbackKind,
468
+ actionId: stringOrNull(record.actionId),
469
+ payload: "payload" in record ? record.payload : record,
470
+ requestedAt: stringOrNull(record.requestedAt) ?? stringOrNull(record.at) ?? ""
471
+ }];
472
+ });
473
+ }
474
+ function emptyFoldedProjection(runId, projection, toRunStatus) {
475
+ const projectionRecord = projection;
476
+ const nestedProjection = objectRecord(projectionRecord.projection);
477
+ const pendingApprovals = pendingRequests(nestedProjection?.pendingApprovals ?? projectionRecord.pendingApprovals, "approval");
478
+ const pendingUserInputs = pendingRequests(nestedProjection?.pendingUserInputs ?? nestedProjection?.pendingInputs ?? projectionRecord.pendingUserInputs ?? (Array.isArray(projectionRecord.pendingInputs) ? projectionRecord.pendingInputs : undefined), "user-input");
479
+ const nestedRecord = objectRecord(nestedProjection?.record);
480
+ const nestedFolded = nestedProjection;
481
+ return {
482
+ ...EMPTY_PROJECTION,
483
+ ...nestedFolded ?? {},
484
+ record: {
485
+ ...nestedRecord ?? {},
486
+ runId,
487
+ ...projection.taskId ? { taskId: projection.taskId } : {},
488
+ ...projection.title ? { title: projection.title } : {},
489
+ ...projection.startedAt ? { startedAt: projection.startedAt } : {},
490
+ ...projection.updatedAt ? { updatedAt: projection.updatedAt } : {},
491
+ ...projection.completedAt ? { completedAt: projection.completedAt } : {},
492
+ ...projection.sessionPath ? { sessionPath: projection.sessionPath } : {},
493
+ ...projection.worktreePath ? { worktreePath: projection.worktreePath } : {},
494
+ ...projection.prUrl ? { prUrl: projection.prUrl } : {}
495
+ },
496
+ status: toRunStatus(projection.status) ?? toRunStatus(nestedProjection?.status),
497
+ pendingApprovals,
498
+ pendingUserInputs,
499
+ steeringCount: projection.steeringCount ?? numberOrNull(nestedProjection?.steeringCount) ?? 0,
500
+ stallCount: projection.stallCount ?? numberOrNull(nestedProjection?.stallCount) ?? 0,
501
+ lastEventAt: projection.updatedAt ?? stringOrNull(nestedProjection?.lastEventAt)
502
+ };
503
+ }
504
+ function foldedProjectionForRun(runId, projection, sessionPath, toRunStatus) {
505
+ const registryFolded = emptyFoldedProjection(runId, projection, toRunStatus);
506
+ const sessionEntries = readSessionRunEntries(sessionPath);
507
+ if (sessionEntries.length === 0)
508
+ return { projection: registryFolded, hasSessionEntries: false };
509
+ const sessionFolded = foldRunSessionEntries(sessionEntries, runId);
510
+ if (sessionFolded.lastSeq === 0)
511
+ return { projection: registryFolded, hasSessionEntries: false };
512
+ return {
513
+ projection: {
514
+ ...registryFolded,
515
+ ...sessionFolded,
516
+ record: {
517
+ ...registryFolded.record,
518
+ ...sessionFolded.record,
519
+ runId
520
+ },
521
+ status: sessionFolded.status ?? registryFolded.status,
522
+ lastEventAt: sessionFolded.lastEventAt ?? registryFolded.lastEventAt
523
+ },
524
+ hasSessionEntries: true
525
+ };
526
+ }
527
+ function runRecordFromRegistryEntry(projectRoot, entry, toRunStatus) {
528
+ const projection = entry.projection && typeof entry.projection === "object" ? entry.projection : {};
529
+ const projectionRecord = projection;
530
+ const runId = stringOrNull(projection.runId) ?? entry.roomId;
531
+ const sessionPath = stringOrNull(projection.sessionPath) ?? stringOrNull(entry.sessionPath) ?? null;
532
+ const foldedResult = foldedProjectionForRun(runId, projection, sessionPath, toRunStatus);
533
+ const folded = foldedResult.projection;
534
+ const pushedStatus = folded.status ?? toRunStatus(projection.status) ?? toRunStatus(entry.status);
535
+ const status = entry.stale ? pushedStatus && isTerminalRunStatus(pushedStatus) ? pushedStatus : "stale" : pushedStatus ?? "running";
536
+ const collabCwd = stringOrNull(projection.collabCwd) ?? stringOrNull(projection.cwd) ?? stringOrNull(entry.cwd) ?? stringOrNull(projection.worktreePath);
537
+ const pendingApprovals = foldedResult.hasSessionEntries ? folded.pendingApprovals.length : numberOrNull(projectionRecord.pendingApprovals) ?? folded.pendingApprovals.length;
538
+ const pendingInputs = foldedResult.hasSessionEntries ? folded.pendingUserInputs.length : numberOrNull(projectionRecord.pendingInputs) ?? folded.pendingUserInputs.length;
539
+ return {
540
+ runId,
541
+ taskId: stringOrNull(projection.taskId),
542
+ title: stringOrNull(projection.title) ?? entry.title,
543
+ status,
544
+ source: sourceFromEntry(projectRoot, projection, entry),
545
+ live: !entry.stale,
546
+ stale: entry.stale,
547
+ startedAt: stringOrNull(projection.startedAt) ?? entry.startedAt ?? null,
548
+ updatedAt: stringOrNull(projection.updatedAt) ?? entry.heartbeatAt ?? null,
549
+ completedAt: stringOrNull(projection.completedAt),
550
+ joinLink: stringOrNull(projection.joinLink) ?? entry.joinLink ?? null,
551
+ webLink: stringOrNull(projection.webLink) ?? entry.webLink ?? null,
552
+ relayUrl: stringOrNull(projection.relayUrl) ?? entry.relayUrl ?? null,
553
+ sessionPath,
554
+ prUrl: stringOrNull(projection.prUrl),
555
+ worktreePath: stringOrNull(projection.worktreePath) ?? collabCwd,
556
+ pendingApprovals,
557
+ pendingInputs,
558
+ steeringCount: projection.steeringCount ?? folded.steeringCount ?? 0,
559
+ stallCount: projection.stallCount ?? folded.stallCount ?? 0,
560
+ errorSummary: stringOrNull(projection.errorSummary) ?? summarizeRunError(folded),
561
+ timeline: Array.isArray(projection.timeline) ? [...projection.timeline] : [...timelineEntriesFromCustomEntries([])],
562
+ inbox: inboxFromProjection(folded),
563
+ collabCwd: collabCwd ?? null,
564
+ projection: folded
565
+ };
566
+ }
567
+ function runRecordsFromCollab(projectRoot, collabs, toRunStatus) {
568
+ return sortByRecency(collabs.map((collab) => runRecordFromRegistryEntry(projectRoot, registryEntryFromCollab(collab), toRunStatus)).filter((record) => record !== null));
569
+ }
570
+ function sortByRecency(records) {
571
+ return [...records].sort((a, b) => {
572
+ const at = Date.parse(b.updatedAt ?? b.startedAt ?? "") || 0;
573
+ const bt = Date.parse(a.updatedAt ?? a.startedAt ?? "") || 0;
574
+ return at - bt;
575
+ });
576
+ }
577
+ function discoveryDiagnosticRunRecord(projectRoot, error) {
578
+ const detail = error instanceof Error ? error.message : String(error);
579
+ const runId = DISCOVERY_DIAGNOSTIC_RUN_ID;
580
+ const projection = {
581
+ ...EMPTY_PROJECTION,
582
+ record: { runId, title: "Registry discovery unavailable" },
583
+ status: "needs-attention",
584
+ stallCount: 1
585
+ };
586
+ return {
587
+ runId,
588
+ taskId: null,
589
+ title: "Registry discovery unavailable",
590
+ status: "needs-attention",
591
+ source: "remote",
592
+ live: false,
593
+ stale: true,
594
+ startedAt: null,
595
+ updatedAt: null,
596
+ completedAt: null,
597
+ joinLink: null,
598
+ webLink: null,
599
+ relayUrl: null,
600
+ sessionPath: null,
601
+ prUrl: null,
602
+ worktreePath: null,
603
+ pendingApprovals: 0,
604
+ pendingInputs: 0,
605
+ steeringCount: 0,
606
+ stallCount: 1,
607
+ errorSummary: `registry discovery unavailable: ${detail}`,
608
+ timeline: [],
609
+ inbox: [],
610
+ collabCwd: null,
611
+ projection
612
+ };
613
+ }
614
+ async function listRunProjections(projectRoot, filter = {}) {
615
+ try {
616
+ const discovery = await loadCapabilityForRoot(projectRoot, RunDiscoveryCap);
617
+ if (!discovery)
618
+ return [discoveryDiagnosticRunRecord(projectRoot, "run discovery capability unavailable")];
619
+ const backbone = await loadCapabilityForRoot(projectRoot, RunRegistryBackboneCap);
620
+ if (!backbone)
621
+ return [discoveryDiagnosticRunRecord(projectRoot, "run registry backbone capability unavailable")];
622
+ const collabs = await discovery.listActiveRunCollab(projectRoot, filter, { isRuntimeActiveStatus });
623
+ return runRecordsFromCollab(projectRoot, collabs, backbone.registryStatusToRunStatus);
624
+ } catch (error) {
625
+ return [discoveryDiagnosticRunRecord(projectRoot, error)];
626
+ }
627
+ }
628
+ var listRuns = listRunProjections;
629
+
630
+ // packages/run-plugin/src/read-model/read-model-backend/inbox.ts
631
+ function promptFromPayload(payload, fallback) {
632
+ if (payload && typeof payload === "object") {
633
+ const record = payload;
634
+ for (const key of ["title", "message", "reason", "prompt", "summary"]) {
635
+ const value = record[key];
636
+ if (typeof value === "string" && value.trim().length > 0)
637
+ return value.trim();
638
+ }
639
+ }
640
+ return fallback;
641
+ }
642
+ function recordsFromRun(run, kind) {
643
+ const pending = kind === "approvals" ? run.projection.pendingApprovals : run.projection.pendingUserInputs;
644
+ return pending.map((request) => ({
645
+ runId: run.runId,
646
+ taskId: run.taskId,
647
+ requestId: request.requestId,
648
+ status: "pending",
649
+ prompt: promptFromPayload(request.payload, kind === "approvals" ? "Approval requested" : "Input requested"),
650
+ requestedAt: request.requestedAt,
651
+ payload: request.payload,
652
+ kind: kind === "approvals" ? "approval" : "input"
653
+ }));
654
+ }
655
+ function matchesFilters(run, filters) {
656
+ if (filters.run && run.runId !== filters.run)
657
+ return false;
658
+ if (filters.task && run.taskId !== filters.task && run.runId !== filters.task)
659
+ return false;
660
+ return true;
661
+ }
662
+ async function listInboxRecords(input, kind, filters = {}, deps = {}) {
663
+ const runs = await (deps.listRuns ?? listRuns)(input.projectRoot);
664
+ return runs.filter((run) => matchesFilters(run, filters)).flatMap((run) => recordsFromRun(run, kind));
665
+ }
666
+ export {
667
+ recordsFromRun,
668
+ listInboxRecords
669
+ };
@@ -0,0 +1,8 @@
1
+ export * from "./guard";
2
+ export * from "./inbox";
3
+ export * from "./inspect";
4
+ export * from "./run-status";
5
+ export * from "./stats";
6
+ export { listRuns, getRun, resolveJoinTarget, resolveRunJoinTarget, readSessionRunEntries, } from "./projection";
7
+ export { summarizeRunError } from "./diagnostics";
8
+ export type { RunRecord, RunJoinTarget, UnifiedInboxRequest } from "./projection";