@h-rig/run-worker 0.0.6-alpha.156 → 0.0.6-alpha.158

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 (47) hide show
  1. package/dist/src/autohost.d.ts +8 -10
  2. package/dist/src/autohost.js +683 -95
  3. package/dist/src/constants.d.ts +0 -1
  4. package/dist/src/constants.js +0 -2
  5. package/dist/src/extension.js +683 -95
  6. package/dist/src/host-kernel.d.ts +22 -0
  7. package/dist/src/host-kernel.js +78 -0
  8. package/dist/src/host.d.ts +2 -0
  9. package/dist/src/host.js +419 -0
  10. package/dist/src/index.d.ts +0 -6
  11. package/dist/src/index.js +1913 -133
  12. package/dist/src/local-run-changes.d.ts +3 -0
  13. package/dist/src/local-run-changes.js +65 -0
  14. package/dist/src/notifications.js +13 -5
  15. package/dist/src/notify-cap.d.ts +11 -0
  16. package/dist/src/notify-cap.js +13 -0
  17. package/dist/src/panel-plugin.js +3 -7
  18. package/dist/src/plugin.d.ts +0 -11
  19. package/dist/src/plugin.js +1910 -101
  20. package/dist/src/{runs → read-model-backend}/control.d.ts +0 -1
  21. package/dist/src/{runs → read-model-backend}/control.js +361 -38
  22. package/dist/src/{runs → read-model-backend}/diagnostics.d.ts +0 -1
  23. package/dist/src/{runs → read-model-backend}/diagnostics.js +1 -3
  24. package/dist/src/{runs → read-model-backend}/guard.js +2 -3
  25. package/dist/src/{runs → read-model-backend}/inbox.js +366 -36
  26. package/dist/src/{runs → read-model-backend}/index.js +552 -223
  27. package/dist/src/{runs → read-model-backend}/inspect.d.ts +0 -1
  28. package/dist/src/{runs → read-model-backend}/inspect.js +350 -34
  29. package/dist/src/{runs → read-model-backend}/projection.d.ts +21 -7
  30. package/dist/src/{runs → read-model-backend}/projection.js +349 -31
  31. package/dist/src/{runs → read-model-backend}/run-status.d.ts +6 -3
  32. package/dist/src/{runs → read-model-backend}/run-status.js +53 -33
  33. package/dist/src/{runs → read-model-backend}/stats.d.ts +0 -1
  34. package/dist/src/{runs → read-model-backend}/stats.js +373 -58
  35. package/dist/src/read-model-service.d.ts +2 -0
  36. package/dist/src/read-model-service.js +1433 -0
  37. package/dist/src/session-journal.d.ts +60 -0
  38. package/dist/src/session-journal.js +471 -0
  39. package/dist/src/stall.d.ts +8 -3
  40. package/dist/src/stall.js +0 -1
  41. package/dist/src/utils.js +282 -3
  42. package/package.json +9 -12
  43. package/dist/src/journal.d.ts +0 -33
  44. package/dist/src/journal.js +0 -31
  45. /package/dist/src/{runs → read-model-backend}/guard.d.ts +0 -0
  46. /package/dist/src/{runs → read-model-backend}/inbox.d.ts +0 -0
  47. /package/dist/src/{runs → read-model-backend}/index.d.ts +0 -0
@@ -14,17 +14,408 @@ var __export = (target, all) => {
14
14
  });
15
15
  };
16
16
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
17
+ var __require = import.meta.require;
17
18
 
18
- // packages/run-worker/src/journal.ts
19
- import { createJournalSessionProvider } from "@rig/kernel/journal-session-provider";
20
- import { RunSessionJournal } from "@rig/runtime/control-plane/run-session-writer";
19
+ // packages/run-worker/src/session-journal.ts
20
+ import { Schema } from "effect";
21
+ import {
22
+ CUSTOM_TYPE_FOR,
23
+ RIG_CONTROL_SENTINEL_END,
24
+ RIG_INBOX_RESOLUTION_SENTINEL,
25
+ RIG_PAUSE_SENTINEL,
26
+ RIG_RESUME_SENTINEL,
27
+ RIG_STOP_SENTINEL,
28
+ RIG_STOP_SENTINEL_END,
29
+ RIG_WORKFLOW_STATUS_CHANGED,
30
+ RunJournalEvent,
31
+ TYPE_FOR_CUSTOM
32
+ } from "@rig/contracts";
33
+ function isTerminalRunStatus(status) {
34
+ return TERMINAL_RUN_STATUSES.includes(status);
35
+ }
36
+ function canTransitionRunStatus(from, to) {
37
+ if (from === null)
38
+ return true;
39
+ if (from === to)
40
+ return true;
41
+ return RUN_STATUS_TRANSITIONS[from].includes(to);
42
+ }
43
+ function assertRunStatusTransition(from, to) {
44
+ if (!canTransitionRunStatus(from, to)) {
45
+ throw new Error(`Illegal run status transition: ${from ?? "(none)"} -> ${to}. ` + `Allowed from ${from ?? "(none)"}: ${from ? RUN_STATUS_TRANSITIONS[from].join(", ") : "(any)"}.`);
46
+ }
47
+ }
48
+ function reduceRunJournal(events, runId = null) {
49
+ let record = {};
50
+ let status = null;
51
+ const statusHistory = [];
52
+ const pendingApprovals = new Map;
53
+ const resolvedApprovals = [];
54
+ const pendingUserInputs = new Map;
55
+ const resolvedUserInputs = [];
56
+ const closeoutPhases = [];
57
+ let resolvedPipeline = null;
58
+ const stageOutcomes = [];
59
+ const anomalies = [];
60
+ let steeringCount = 0;
61
+ let stallCount = 0;
62
+ let lastSeq = 0;
63
+ let lastEventAt = null;
64
+ const projectedRunId = runId ?? events[0]?.runId ?? null;
65
+ for (const event of events) {
66
+ lastSeq = event.seq;
67
+ lastEventAt = event.at;
68
+ switch (event.type) {
69
+ case "status-changed": {
70
+ if (!canTransitionRunStatus(status, event.to)) {
71
+ anomalies.push({ seq: event.seq, kind: "illegal-transition", detail: `${status ?? "(none)"} -> ${event.to}` });
72
+ }
73
+ statusHistory.push({ seq: event.seq, at: event.at, from: status, to: event.to, reason: event.reason ?? null });
74
+ const wasTerminal = status !== null && isTerminalRunStatus(status);
75
+ status = event.to;
76
+ record = { ...record, updatedAt: event.at };
77
+ if (isTerminalRunStatus(event.to) && !record.completedAt)
78
+ record = { ...record, completedAt: event.at };
79
+ if (!isTerminalRunStatus(event.to) && wasTerminal)
80
+ record = { ...record, completedAt: null };
81
+ if (event.to === "running" && !record.startedAt)
82
+ record = { ...record, startedAt: event.at };
83
+ break;
84
+ }
85
+ case "record-patch": {
86
+ const next = { ...record };
87
+ for (const [key, value] of Object.entries(event.patch)) {
88
+ if (value !== undefined)
89
+ next[key] = value;
90
+ }
91
+ next.updatedAt = event.patch.updatedAt ?? event.at;
92
+ record = next;
93
+ break;
94
+ }
95
+ case "approval-requested": {
96
+ pendingApprovals.set(event.requestId, {
97
+ requestId: event.requestId,
98
+ requestKind: event.requestKind,
99
+ actionId: event.actionId ?? null,
100
+ payload: event.payload,
101
+ requestedAt: event.at
102
+ });
103
+ break;
104
+ }
105
+ case "approval-resolved": {
106
+ const pending = pendingApprovals.get(event.requestId);
107
+ if (!pending) {
108
+ const alreadyResolved = resolvedApprovals.some((entry) => entry.requestId === event.requestId);
109
+ anomalies.push({ seq: event.seq, kind: alreadyResolved ? "duplicate-resolution" : "unknown-request", detail: `approval ${event.requestId}` });
110
+ break;
111
+ }
112
+ pendingApprovals.delete(event.requestId);
113
+ resolvedApprovals.push({ ...pending, decision: event.decision, note: event.note ?? null, actor: event.actor, resolvedAt: event.at });
114
+ break;
115
+ }
116
+ case "input-requested": {
117
+ pendingUserInputs.set(event.requestId, {
118
+ requestId: event.requestId,
119
+ requestKind: "user-input",
120
+ actionId: null,
121
+ payload: event.payload,
122
+ requestedAt: event.at
123
+ });
124
+ break;
125
+ }
126
+ case "input-resolved": {
127
+ const pending = pendingUserInputs.get(event.requestId);
128
+ if (!pending) {
129
+ const alreadyResolved = resolvedUserInputs.some((entry) => entry.requestId === event.requestId);
130
+ anomalies.push({ seq: event.seq, kind: alreadyResolved ? "duplicate-resolution" : "unknown-request", detail: `user-input ${event.requestId}` });
131
+ break;
132
+ }
133
+ pendingUserInputs.delete(event.requestId);
134
+ resolvedUserInputs.push({ ...pending, answers: event.answers, actor: event.actor, resolvedAt: event.at });
135
+ break;
136
+ }
137
+ case "steering":
138
+ steeringCount += 1;
139
+ break;
140
+ case "adopted":
141
+ record = { ...record, pid: event.pid, updatedAt: event.at };
142
+ break;
143
+ case "stall-detected":
144
+ stallCount += 1;
145
+ break;
146
+ case "closeout-phase":
147
+ closeoutPhases.push({ seq: event.seq, at: event.at, phase: event.phase, outcome: event.outcome, detail: event.detail ?? null });
148
+ break;
149
+ case "pipeline-resolved":
150
+ resolvedPipeline = event.pipeline;
151
+ break;
152
+ case "stage-outcome":
153
+ stageOutcomes.push({ seq: event.seq, at: event.at, outcome: event.outcome });
154
+ break;
155
+ case "timeline-entry":
156
+ case "log-entry":
157
+ break;
158
+ }
159
+ }
160
+ return {
161
+ runId: projectedRunId,
162
+ record,
163
+ status,
164
+ statusHistory,
165
+ pendingApprovals: [...pendingApprovals.values()],
166
+ resolvedApprovals,
167
+ pendingUserInputs: [...pendingUserInputs.values()],
168
+ resolvedUserInputs,
169
+ steeringCount,
170
+ stallCount,
171
+ closeoutPhases,
172
+ resolvedPipeline,
173
+ stageOutcomes,
174
+ lastSeq,
175
+ lastEventAt,
176
+ anomalies
177
+ };
178
+ }
179
+ function sessionIdFromSessionFile(sessionPath) {
180
+ if (!sessionPath)
181
+ return null;
182
+ const file = sessionPath.split(/[\\/]/).pop() ?? "";
183
+ const match = file.match(/_([0-9a-fA-F][0-9a-fA-F-]{7,})\.jsonl$/);
184
+ return match?.[1] ?? null;
185
+ }
186
+ function isRunSessionCustomType(customType) {
187
+ return customType !== undefined && Object.hasOwn(TYPE_FOR_CUSTOM, customType);
188
+ }
189
+ function foldRunSessionEntries(entries, runId) {
190
+ const events = [];
191
+ entries.forEach((entry, index) => {
192
+ if (entry.type !== "custom" || !isRunSessionCustomType(entry.customType))
193
+ return;
194
+ const data = entry.data !== null && typeof entry.data === "object" ? entry.data : {};
195
+ const stamped = {
196
+ v: 1,
197
+ seq: index + 1,
198
+ at: typeof data.at === "string" ? data.at : new Date(0).toISOString(),
199
+ runId,
200
+ ...data,
201
+ type: TYPE_FOR_CUSTOM[entry.customType]
202
+ };
203
+ try {
204
+ events.push(decodeRunJournalEvent(stamped));
205
+ } catch {}
206
+ });
207
+ return reduceRunJournal(events, runId);
208
+ }
209
+ function projectRunFromSession(source, runId) {
210
+ const entries = "getEntries" in source ? source.getEntries() : source;
211
+ return foldRunSessionEntries(entries, runId);
212
+ }
213
+ function isRecord(value) {
214
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
215
+ }
216
+ function timelineEntryFromCustomEntry(entry) {
217
+ if (entry.customType !== CUSTOM_TYPE_FOR["timeline-entry"] || !isRecord(entry.data))
218
+ return null;
219
+ const payload = isRecord(entry.data.payload) ? entry.data.payload : entry.data;
220
+ const type = typeof payload.type === "string" ? payload.type : "timeline";
221
+ const stage = typeof payload.stage === "string" ? payload.stage : typeof payload.name === "string" ? payload.name : null;
222
+ const status = typeof payload.status === "string" ? payload.status : typeof payload.outcome === "string" ? payload.outcome : null;
223
+ const detail = typeof payload.detail === "string" ? payload.detail : typeof payload.message === "string" ? payload.message : null;
224
+ const at = typeof entry.data.at === "string" ? entry.data.at : typeof payload.at === "string" ? payload.at : null;
225
+ return { at, type, stage, status, detail };
226
+ }
227
+ function timelineEntriesFromCustomEntries(entries) {
228
+ return entries.flatMap((entry) => {
229
+ const timelineEntry = timelineEntryFromCustomEntry(entry);
230
+ return timelineEntry ? [timelineEntry] : [];
231
+ });
232
+ }
233
+ function latestTimelineEntriesFromCustomEntries(entries, limit) {
234
+ if (limit <= 0)
235
+ return [];
236
+ const timeline = [];
237
+ for (let index = entries.length - 1;index >= 0 && timeline.length < limit; index -= 1) {
238
+ const timelineEntry = timelineEntryFromCustomEntry(entries[index]);
239
+ if (timelineEntry)
240
+ timeline.push(timelineEntry);
241
+ }
242
+ timeline.reverse();
243
+ return timeline;
244
+ }
245
+ function parseStopSentinel(text, expectedRunId) {
246
+ const start = text.indexOf(RIG_STOP_SENTINEL);
247
+ if (start < 0)
248
+ return null;
249
+ const end = text.indexOf(RIG_STOP_SENTINEL_END, start);
250
+ const body = text.slice(start + RIG_STOP_SENTINEL.length, end >= 0 ? end : undefined).trim();
251
+ const runId = body.match(/(?:^|\s)runId=([^\s>]+)/)?.[1] ?? "";
252
+ if (runId && runId !== expectedRunId)
253
+ return null;
254
+ const reason = body.match(/(?:^|\s)reason=(.+)$/)?.[1]?.trim() ?? null;
255
+ return { reason };
256
+ }
257
+ function parseControlSentinel(marker, text, expectedRunId) {
258
+ const start = text.indexOf(marker);
259
+ if (start < 0)
260
+ return null;
261
+ const end = text.indexOf(RIG_CONTROL_SENTINEL_END, start);
262
+ const body = text.slice(start + marker.length, end >= 0 ? end : undefined).trim();
263
+ const runId = body.match(/(?:^|\s)runId=([^\s>]+)/)?.[1] ?? "";
264
+ if (runId && runId !== expectedRunId)
265
+ return null;
266
+ const requestedBy = body.match(/(?:^|\s)requestedBy=([^\s>]+)/)?.[1] ?? null;
267
+ return { requestedBy };
268
+ }
269
+ function parsePauseSentinel(text, expectedRunId) {
270
+ return parseControlSentinel(RIG_PAUSE_SENTINEL, text, expectedRunId);
271
+ }
272
+ function parseResumeSentinel(text, expectedRunId) {
273
+ return parseControlSentinel(RIG_RESUME_SENTINEL, text, expectedRunId);
274
+ }
275
+ function decodeInboxResolutionPayload(payload) {
276
+ try {
277
+ const parsed = JSON.parse(decodeURIComponent(payload));
278
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
279
+ return null;
280
+ const record = parsed;
281
+ if (record.kind === "approval") {
282
+ const requestId = typeof record.requestId === "string" ? record.requestId.trim() : "";
283
+ const decision = record.decision === "approve" || record.decision === "reject" ? record.decision : null;
284
+ const note = typeof record.note === "string" ? record.note : record.note === null ? null : undefined;
285
+ if (!requestId || !decision)
286
+ return null;
287
+ return { kind: "approval", requestId, decision, ...note !== undefined ? { note } : {} };
288
+ }
289
+ if (record.kind === "input") {
290
+ const requestId = typeof record.requestId === "string" ? record.requestId.trim() : "";
291
+ const answers = record.answers && typeof record.answers === "object" && !Array.isArray(record.answers) ? Object.fromEntries(Object.entries(record.answers).filter((entry) => typeof entry[1] === "string")) : null;
292
+ if (!requestId || !answers)
293
+ return null;
294
+ return { kind: "input", requestId, answers };
295
+ }
296
+ } catch {
297
+ return null;
298
+ }
299
+ return null;
300
+ }
301
+ function parseInboxResolutionSentinel(text, expectedRunId) {
302
+ const start = text.indexOf(RIG_INBOX_RESOLUTION_SENTINEL);
303
+ if (start < 0)
304
+ return null;
305
+ const end = text.indexOf(RIG_CONTROL_SENTINEL_END, start);
306
+ const body = text.slice(start + RIG_INBOX_RESOLUTION_SENTINEL.length, end >= 0 ? end : undefined).trim();
307
+ const runId = body.match(/(?:^|\s)runId=([^\s>]+)/)?.[1] ?? "";
308
+ if (runId && runId !== expectedRunId)
309
+ return null;
310
+ const requestedBy = body.match(/(?:^|\s)requestedBy=([^\s>]+)/)?.[1] ?? null;
311
+ const payload = body.match(/(?:^|\s)data=([^\s>]+)/)?.[1] ?? "";
312
+ const decoded = decodeInboxResolutionPayload(payload);
313
+ if (!decoded)
314
+ return null;
315
+ return { ...decoded, requestedBy };
316
+ }
317
+ function asCustomEntries(entries) {
318
+ return entries.filter((entry) => entry.type === "custom");
319
+ }
320
+
321
+ class RunSessionJournal {
322
+ sm;
323
+ runId;
324
+ constructor(sm, runId) {
325
+ this.sm = sm;
326
+ this.runId = runId;
327
+ }
328
+ #append(init) {
329
+ this.sm.appendCustomEntry(CUSTOM_TYPE_FOR[init.type], { ...init, at: new Date().toISOString() });
330
+ }
331
+ appendStatus(to, opts = {}) {
332
+ const from = foldRunSessionEntries(asCustomEntries(this.sm.getEntries()), this.runId).status;
333
+ if (!opts.force)
334
+ assertRunStatusTransition(from, to);
335
+ if (opts.errorText !== undefined)
336
+ this.#append({ type: "record-patch", patch: { errorText: opts.errorText } });
337
+ this.#append({
338
+ type: "status-changed",
339
+ from,
340
+ to,
341
+ ...opts.reason !== undefined ? { reason: opts.reason } : {},
342
+ ...opts.actor !== undefined ? { actor: opts.actor } : {}
343
+ });
344
+ }
345
+ appendTimeline(payload) {
346
+ this.#append({ type: "timeline-entry", payload });
347
+ }
348
+ appendCloseoutPhase(input) {
349
+ this.#append({
350
+ type: "closeout-phase",
351
+ phase: input.phase,
352
+ outcome: input.outcome,
353
+ ...input.detail !== undefined ? { detail: input.detail } : {}
354
+ });
355
+ }
356
+ appendApprovalResolved(input) {
357
+ this.#append({
358
+ type: "approval-resolved",
359
+ requestId: input.requestId,
360
+ decision: input.decision,
361
+ actor: input.actor,
362
+ ...input.note !== undefined ? { note: input.note } : {}
363
+ });
364
+ }
365
+ appendInputResolved(input) {
366
+ this.#append({ type: "input-resolved", requestId: input.requestId, answers: input.answers, actor: input.actor });
367
+ }
368
+ appendStall(input) {
369
+ this.#append({ type: "stall-detected", detail: input.detail });
370
+ }
371
+ }
372
+ function isRunJournalEventInit(event) {
373
+ if (event === null || typeof event !== "object")
374
+ return false;
375
+ const type = event.type;
376
+ return typeof type === "string" && Object.hasOwn(CUSTOM_TYPE_FOR, type);
377
+ }
378
+ function createJournalSessionProvider(options) {
379
+ const now = options.now ?? (() => new Date);
380
+ const appendRunEvent = async (event, runId = options.runId) => {
381
+ options.store.appendCustomEntry(CUSTOM_TYPE_FOR[event.type], { ...event, runId, at: now().toISOString() });
382
+ };
383
+ const readEntries = () => asCustomEntries(options.store.getEntries());
384
+ const entriesForRun = (runId) => readEntries().filter((entry) => {
385
+ const data = entry.data;
386
+ if (data === null || typeof data !== "object")
387
+ return runId === options.runId;
388
+ const candidate = data.runId;
389
+ return candidate === undefined ? runId === options.runId : candidate === runId;
390
+ });
391
+ return {
392
+ runId: options.runId,
393
+ async append(event) {
394
+ if (isRunJournalEventInit(event))
395
+ await appendRunEvent(event);
396
+ },
397
+ appendRunEvent,
398
+ async recordPipeline(runId, pipeline) {
399
+ await appendRunEvent({ type: "pipeline-resolved", pipeline }, runId);
400
+ },
401
+ async recordStageOutcome(runId, outcome) {
402
+ await appendRunEvent({ type: "stage-outcome", outcome }, runId);
403
+ },
404
+ async read(runId) {
405
+ return entriesForRun(runId);
406
+ },
407
+ readEntries,
408
+ readProjection: () => foldRunSessionEntries(entriesForRun(options.runId), options.runId)
409
+ };
410
+ }
21
411
  async function createRunJournal(sessionManager, runId) {
22
412
  try {
23
- const journal = new RunSessionJournal(sessionManager, runId);
413
+ const writableSessionManager = sessionManager;
414
+ const journal = new RunSessionJournal(writableSessionManager, runId);
24
415
  const kernel = createJournalSessionProvider({
25
416
  runId,
26
417
  store: {
27
- appendCustomEntry: (customType, data) => sessionManager.appendCustomEntry(customType, data),
418
+ appendCustomEntry: (customType, data) => writableSessionManager.appendCustomEntry(customType, data),
28
419
  getEntries: () => sessionManager.getEntries?.() ?? sessionManager.getBranch?.() ?? []
29
420
  }
30
421
  });
@@ -42,29 +433,1386 @@ async function createRunJournal(sessionManager, runId) {
42
433
  return null;
43
434
  }
44
435
  }
45
- var init_journal = () => {};
436
+ var decodeRunJournalEvent, RUN_STATUS_TRANSITIONS, TERMINAL_RUN_STATUSES;
437
+ var init_session_journal = __esm(() => {
438
+ decodeRunJournalEvent = Schema.decodeUnknownSync(RunJournalEvent);
439
+ RUN_STATUS_TRANSITIONS = {
440
+ created: ["queued", "preparing", "running", "failed", "stopped"],
441
+ queued: ["preparing", "running", "failed", "stopped"],
442
+ preparing: ["queued", "running", "needs-attention", "failed", "stopped"],
443
+ running: [
444
+ "queued",
445
+ "waiting-approval",
446
+ "waiting-user-input",
447
+ "paused",
448
+ "validating",
449
+ "reviewing",
450
+ "closing-out",
451
+ "needs-attention",
452
+ "completed",
453
+ "failed",
454
+ "stopped"
455
+ ],
456
+ "waiting-approval": ["running", "needs-attention", "failed", "stopped"],
457
+ "waiting-user-input": ["running", "needs-attention", "failed", "stopped"],
458
+ paused: ["running", "failed", "stopped"],
459
+ validating: ["running", "reviewing", "closing-out", "needs-attention", "completed", "failed", "stopped"],
460
+ reviewing: ["running", "validating", "closing-out", "needs-attention", "completed", "failed", "stopped"],
461
+ "closing-out": ["running", "needs-attention", "completed", "failed", "stopped"],
462
+ "needs-attention": ["queued", "preparing", "running", "closing-out", "completed", "failed", "stopped"],
463
+ completed: [],
464
+ failed: ["queued", "preparing", "running", "closing-out"],
465
+ stopped: ["queued", "preparing", "running", "closing-out"]
466
+ };
467
+ TERMINAL_RUN_STATUSES = ["completed", "failed", "stopped"];
468
+ });
469
+
470
+ // packages/run-worker/src/read-model-backend/run-status.ts
471
+ import { OPERATOR_INACTIVE_RUN_STATUSES } from "@rig/contracts";
472
+ function isTerminalRunStatus2(status) {
473
+ return TERMINAL_RUN_STATUSES2.includes(status);
474
+ }
475
+ function isActiveRunStatus(status) {
476
+ return !isTerminalRunStatus2(status);
477
+ }
478
+ function normalizeRunStatusToken(status) {
479
+ return String(status ?? "").trim().toLowerCase().replace(/[\s_]+/g, "-");
480
+ }
481
+ function canonicalStatusToken(status) {
482
+ const normalized = normalizeRunStatusToken(status);
483
+ if (normalized === "waiting-input")
484
+ return "waiting-user-input";
485
+ return normalized;
486
+ }
487
+ function asRunStatus(status) {
488
+ return KNOWN_RUN_STATUS[status] ? status : null;
489
+ }
490
+ function statusColorRole(status) {
491
+ switch (canonicalStatusToken(status)) {
492
+ case "done":
493
+ case "completed":
494
+ case "ready":
495
+ case "healthy":
496
+ case "approved":
497
+ case "merged":
498
+ return "success";
499
+ case "needs-attention":
500
+ case "waiting-approval":
501
+ case "waiting-user-input":
502
+ case "blocked":
503
+ case "paused":
504
+ return "action-yellow";
505
+ case "running":
506
+ case "adopted":
507
+ case "preparing":
508
+ case "created":
509
+ case "queued":
510
+ case "starting":
511
+ case "pending":
512
+ case "in-progress":
513
+ case "active":
514
+ case "booting":
515
+ case "validating":
516
+ case "reviewing":
517
+ case "closing-out":
518
+ return "active-cyan";
519
+ case "failed":
520
+ case "error":
521
+ case "rejected":
522
+ return "failure";
523
+ case "stopped":
524
+ case "cancelled":
525
+ case "canceled":
526
+ case "stale":
527
+ return "muted";
528
+ default:
529
+ return "neutral";
530
+ }
531
+ }
532
+ function isNeedsAttention(run) {
533
+ return canonicalStatusToken(run.status) === "needs-attention" || run.pendingApprovals + run.pendingInputs > 0 || run.stallCount > 0;
534
+ }
535
+ function phaseForStatus(status, runStatus, needsAttention) {
536
+ if (runStatus && isTerminalRunStatus2(runStatus))
537
+ return runStatus === "completed" || runStatus === "failed" || runStatus === "stopped" ? runStatus : "stopped";
538
+ if (needsAttention)
539
+ return "needs-attention";
540
+ switch (status) {
541
+ case "created":
542
+ case "queued":
543
+ case "preparing":
544
+ case "starting":
545
+ case "booting":
546
+ return "starting";
547
+ case "waiting-approval":
548
+ case "waiting-user-input":
549
+ return "waiting";
550
+ case "paused":
551
+ return "paused";
552
+ case "running":
553
+ case "validating":
554
+ case "reviewing":
555
+ case "closing-out":
556
+ return "active";
557
+ default:
558
+ return runStatus && isActiveRunStatus(runStatus) ? "active" : "unknown";
559
+ }
560
+ }
561
+ function classifyRun(run) {
562
+ const status = canonicalStatusToken(run.status) || (run.live && !run.stale ? "starting" : "unknown");
563
+ const runStatus = asRunStatus(status);
564
+ const isTerminal = runStatus ? isTerminalRunStatus2(runStatus) : false;
565
+ const isNeedsAttentionValue = isNeedsAttention(run);
566
+ return {
567
+ status,
568
+ phase: phaseForStatus(status, runStatus, isNeedsAttentionValue),
569
+ isActive: runStatus ? isActiveRunStatus(runStatus) : !isTerminal && status !== "unknown",
570
+ isTerminal,
571
+ isNeedsAttention: isNeedsAttentionValue
572
+ };
573
+ }
574
+ function runStatusColorRole(run) {
575
+ const classification = classifyRun(run);
576
+ return classification.isNeedsAttention && !classification.isTerminal ? "action-yellow" : statusColorRole(classification.status);
577
+ }
578
+ function statusRank(run) {
579
+ const classification = classifyRun(run);
580
+ if (classification.isNeedsAttention)
581
+ return 0;
582
+ switch (classification.phase) {
583
+ case "needs-attention":
584
+ return 0;
585
+ case "active":
586
+ case "waiting":
587
+ case "paused":
588
+ return 1;
589
+ case "starting":
590
+ return 2;
591
+ case "completed":
592
+ return 3;
593
+ case "failed":
594
+ return 4;
595
+ case "stopped":
596
+ return 5;
597
+ case "unknown":
598
+ return 6;
599
+ }
600
+ }
601
+ var TERMINAL_RUN_STATUSES2, ACTIVE_RUN_STATUSES, KNOWN_RUN_STATUS;
602
+ var init_run_status = __esm(() => {
603
+ TERMINAL_RUN_STATUSES2 = ["completed", "failed", "stopped"];
604
+ ACTIVE_RUN_STATUSES = [
605
+ "created",
606
+ "queued",
607
+ "preparing",
608
+ "running",
609
+ "waiting-approval",
610
+ "waiting-user-input",
611
+ "paused",
612
+ "validating",
613
+ "reviewing",
614
+ "closing-out",
615
+ "needs-attention"
616
+ ];
617
+ KNOWN_RUN_STATUS = Object.fromEntries([...ACTIVE_RUN_STATUSES, ...TERMINAL_RUN_STATUSES2].map((status) => [status, true]));
618
+ });
619
+
620
+ // packages/run-worker/src/read-model-backend/diagnostics.ts
621
+ function normalizeString(value) {
622
+ if (typeof value !== "string")
623
+ return null;
624
+ const normalized = value.replace(/\s+/g, " ").trim();
625
+ return normalized.length > 0 ? normalized : null;
626
+ }
627
+ function isGenericRunFailure(value) {
628
+ const text = normalizeString(value);
629
+ return Boolean(text && /^Task run failed \([^)]*\)$/i.test(text));
630
+ }
631
+ function appendCandidate(candidates, value) {
632
+ const text = normalizeString(value);
633
+ if (text && !candidates.includes(text))
634
+ candidates.push(text);
635
+ }
636
+ function categorizeUsefulRunError(lines) {
637
+ const taskSourceFailure = lines.find((line) => /failed to update task source/i.test(line));
638
+ if (taskSourceFailure)
639
+ return `Task source update failed: ${taskSourceFailure}`;
640
+ const moduleFailure = lines.find((line) => /cannot find module/i.test(line));
641
+ if (moduleFailure)
642
+ return `Runtime module resolution failed: ${moduleFailure}`;
643
+ const providerFailure = lines.find((line) => /no api key found|unauthorized|authentication failed|invalid api key/i.test(line));
644
+ if (providerFailure)
645
+ return `Provider authentication failed: ${providerFailure}`;
646
+ return null;
647
+ }
648
+ function summarizeRunError(projection) {
649
+ if (projection.status !== "failed")
650
+ return null;
651
+ const candidates = [];
652
+ for (const anomaly of projection.anomalies) {
653
+ appendCandidate(candidates, `Journal anomaly (${anomaly.kind}): ${anomaly.detail}`);
654
+ }
655
+ for (const phase of projection.closeoutPhases) {
656
+ if (phase.outcome === "failed")
657
+ appendCandidate(candidates, phase.detail);
658
+ }
659
+ for (const entry of projection.statusHistory) {
660
+ appendCandidate(candidates, entry.reason);
661
+ }
662
+ appendCandidate(candidates, projection.record.statusDetail);
663
+ appendCandidate(candidates, projection.record.errorText);
664
+ const nonGeneric = candidates.filter((candidate) => !isGenericRunFailure(candidate));
665
+ return categorizeUsefulRunError(nonGeneric) ?? nonGeneric.at(-1) ?? normalizeString(projection.record.errorText);
666
+ }
667
+
668
+ // packages/run-worker/src/read-model-backend/projection.ts
669
+ var exports_projection = {};
670
+ __export(exports_projection, {
671
+ selectRunProjection: () => selectRunProjection,
672
+ runRecordsFromCollab: () => runRecordsFromCollab,
673
+ runRecordFromRegistryEntry: () => runRecordFromRegistryEntry,
674
+ resolveRunJoinTarget: () => resolveRunJoinTarget,
675
+ resolveJoinTarget: () => resolveJoinTarget,
676
+ readSessionRunEntries: () => readSessionRunEntries,
677
+ listRuns: () => listRuns,
678
+ listRunProjections: () => listRunProjections,
679
+ getRunProjection: () => getRunProjection,
680
+ getRun: () => getRun,
681
+ discoveryDiagnosticRunRecord: () => discoveryDiagnosticRunRecord
682
+ });
683
+ import { existsSync, readFileSync } from "fs";
684
+ import { isAbsolute, relative, resolve } from "path";
685
+ import { RUN_DISCOVERY } from "@rig/contracts";
686
+ import { loadCapabilityForRoot } from "@rig/core/capability-loaders";
687
+ import { defineCapability } from "@rig/core/capability";
688
+ function registryEntryFromCollab(collab) {
689
+ const record = collab;
690
+ return {
691
+ roomId: collab.sessionId,
692
+ title: collab.title,
693
+ status: record.registryStatus ?? (collab.stale ? "stale" : "running"),
694
+ startedAt: collab.startedAt ?? null,
695
+ heartbeatAt: collab.updatedAt ?? null,
696
+ sessionPath: collab.sessionPath ?? null,
697
+ cwd: collab.cwd ?? null,
698
+ joinLink: collab.joinLink ?? null,
699
+ webLink: collab.webLink ?? null,
700
+ relayUrl: collab.relayUrl ?? null,
701
+ stale: collab.stale,
702
+ repo: collab.selectedRepo ?? null,
703
+ ...collab.pid === undefined ? {} : { pid: collab.pid },
704
+ projection: record.registryProjection ?? null
705
+ };
706
+ }
707
+ function readSessionRunEntries(sessionPath) {
708
+ if (!sessionPath || !existsSync(sessionPath))
709
+ return [];
710
+ try {
711
+ return parseSessionRunEntries(readFileSync(sessionPath, "utf8"));
712
+ } catch {
713
+ return [];
714
+ }
715
+ }
716
+ function parseSessionRunEntries(raw) {
717
+ const entries = [];
718
+ for (const line of raw.split(`
719
+ `)) {
720
+ if (!line.trim())
721
+ continue;
722
+ try {
723
+ const parsed = JSON.parse(line);
724
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
725
+ continue;
726
+ entries.push({
727
+ type: "type" in parsed && typeof parsed.type === "string" ? parsed.type : "",
728
+ ..."customType" in parsed && typeof parsed.customType === "string" ? { customType: parsed.customType } : {},
729
+ ..."data" in parsed ? { data: parsed.data } : {}
730
+ });
731
+ } catch {
732
+ continue;
733
+ }
734
+ }
735
+ return entries;
736
+ }
737
+ function stringOrNull(value) {
738
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
739
+ }
740
+ function numberOrNull(value) {
741
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
742
+ }
743
+ function objectRecord(value) {
744
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
745
+ }
746
+ function registryStatusAsRunStatus(status) {
747
+ if (status === "waiting-input")
748
+ return "waiting-user-input";
749
+ if (status === "starting")
750
+ return "preparing";
751
+ return typeof status === "string" ? asRunStatus(status) : null;
752
+ }
753
+ function payloadString(payload, keys) {
754
+ if (!payload || typeof payload !== "object")
755
+ return null;
756
+ const record = payload;
757
+ for (const key of keys) {
758
+ const value = record[key];
759
+ if (typeof value === "string" && value.trim())
760
+ return value.trim();
761
+ }
762
+ return null;
763
+ }
764
+ function payloadOptions(payload) {
765
+ if (!payload || typeof payload !== "object")
766
+ return;
767
+ const record = payload;
768
+ const options = Array.isArray(record.options) ? record.options : Array.isArray(record.choices) ? record.choices : null;
769
+ const values = options?.filter((value) => typeof value === "string" && value.trim().length > 0) ?? [];
770
+ return values.length > 0 ? values : undefined;
771
+ }
772
+ function inboxRequest(request, kind) {
773
+ const fallback = kind === "approval" ? "Approval requested" : "Input requested";
774
+ const body = payloadString(request.payload, ["body", "description", "detail", "details"]);
775
+ const options = payloadOptions(request.payload);
776
+ return {
777
+ requestId: request.requestId,
778
+ kind,
779
+ title: payloadString(request.payload, ["title", "message", "reason", "prompt", "summary"]) ?? fallback,
780
+ ...body !== undefined ? { body } : {},
781
+ ...options ? { options } : {},
782
+ requestedAt: request.requestedAt ?? null,
783
+ source: "run"
784
+ };
785
+ }
786
+ function inboxFromProjection(projection) {
787
+ return [
788
+ ...projection.pendingApprovals.map((request) => inboxRequest(request, "approval")),
789
+ ...projection.pendingUserInputs.map((request) => inboxRequest(request, "input"))
790
+ ].sort((a, b) => (Date.parse(a.requestedAt ?? "") || 0) - (Date.parse(b.requestedAt ?? "") || 0));
791
+ }
792
+ function isProjectPath(projectRoot, cwd) {
793
+ const root = resolve(projectRoot);
794
+ const candidate = resolve(cwd);
795
+ const pathFromRoot = relative(root, candidate);
796
+ return pathFromRoot === "" || !pathFromRoot.startsWith("../") && pathFromRoot !== ".." && !isAbsolute(pathFromRoot);
797
+ }
798
+ function sourceFromEntry(projectRoot, projection, entry) {
799
+ const candidates = [
800
+ stringOrNull(projection.collabCwd),
801
+ stringOrNull(projection.cwd),
802
+ stringOrNull(entry.cwd),
803
+ stringOrNull(projection.worktreePath)
804
+ ].filter((cwd) => cwd !== null);
805
+ return candidates.some((cwd) => isProjectPath(projectRoot, cwd)) ? "local" : "remote";
806
+ }
807
+ function pendingRequests(value, fallbackKind) {
808
+ if (!Array.isArray(value))
809
+ return [];
810
+ return value.flatMap((item) => {
811
+ const record = objectRecord(item);
812
+ const requestId = stringOrNull(record?.requestId) ?? stringOrNull(record?.id);
813
+ if (!record || !requestId)
814
+ return [];
815
+ return [{
816
+ requestId,
817
+ requestKind: stringOrNull(record.requestKind) ?? stringOrNull(record.kind) ?? fallbackKind,
818
+ actionId: stringOrNull(record.actionId),
819
+ payload: "payload" in record ? record.payload : record,
820
+ requestedAt: stringOrNull(record.requestedAt) ?? stringOrNull(record.at) ?? ""
821
+ }];
822
+ });
823
+ }
824
+ function emptyFoldedProjection(runId, projection) {
825
+ const projectionRecord = projection;
826
+ const nestedProjection = objectRecord(projectionRecord.projection);
827
+ const pendingApprovals = pendingRequests(nestedProjection?.pendingApprovals ?? projectionRecord.pendingApprovals, "approval");
828
+ const pendingUserInputs = pendingRequests(nestedProjection?.pendingUserInputs ?? nestedProjection?.pendingInputs ?? projectionRecord.pendingUserInputs ?? (Array.isArray(projectionRecord.pendingInputs) ? projectionRecord.pendingInputs : undefined), "user-input");
829
+ const nestedRecord = objectRecord(nestedProjection?.record);
830
+ const nestedFolded = nestedProjection;
831
+ return {
832
+ ...EMPTY_PROJECTION,
833
+ ...nestedFolded ?? {},
834
+ record: {
835
+ ...nestedRecord ?? {},
836
+ runId,
837
+ ...projection.taskId ? { taskId: projection.taskId } : {},
838
+ ...projection.title ? { title: projection.title } : {},
839
+ ...projection.startedAt ? { startedAt: projection.startedAt } : {},
840
+ ...projection.updatedAt ? { updatedAt: projection.updatedAt } : {},
841
+ ...projection.completedAt ? { completedAt: projection.completedAt } : {},
842
+ ...projection.sessionPath ? { sessionPath: projection.sessionPath } : {},
843
+ ...projection.worktreePath ? { worktreePath: projection.worktreePath } : {},
844
+ ...projection.prUrl ? { prUrl: projection.prUrl } : {}
845
+ },
846
+ status: registryStatusAsRunStatus(projection.status) ?? registryStatusAsRunStatus(nestedProjection?.status),
847
+ pendingApprovals,
848
+ pendingUserInputs,
849
+ steeringCount: projection.steeringCount ?? numberOrNull(nestedProjection?.steeringCount) ?? 0,
850
+ stallCount: projection.stallCount ?? numberOrNull(nestedProjection?.stallCount) ?? 0,
851
+ lastEventAt: projection.updatedAt ?? stringOrNull(nestedProjection?.lastEventAt)
852
+ };
853
+ }
854
+ function runRecordFromRegistryEntry(projectRoot, entry) {
855
+ const projection = entry.projection && typeof entry.projection === "object" ? entry.projection : {};
856
+ const runId = stringOrNull(projection.runId) ?? entry.roomId;
857
+ const folded = emptyFoldedProjection(runId, projection);
858
+ const pushedStatus = registryStatusAsRunStatus(projection.status) ?? folded.status ?? registryStatusAsRunStatus(entry.status);
859
+ const status = entry.stale ? pushedStatus && isTerminalRunStatus(pushedStatus) ? pushedStatus : "stale" : pushedStatus ?? "running";
860
+ const sessionPath = stringOrNull(projection.sessionPath) ?? stringOrNull(entry.sessionPath) ?? null;
861
+ const collabCwd = stringOrNull(projection.collabCwd) ?? stringOrNull(projection.cwd) ?? stringOrNull(entry.cwd) ?? stringOrNull(projection.worktreePath);
862
+ return {
863
+ runId,
864
+ taskId: stringOrNull(projection.taskId),
865
+ title: stringOrNull(projection.title) ?? entry.title,
866
+ status,
867
+ source: sourceFromEntry(projectRoot, projection, entry),
868
+ live: !entry.stale,
869
+ stale: entry.stale,
870
+ startedAt: stringOrNull(projection.startedAt) ?? entry.startedAt ?? null,
871
+ updatedAt: stringOrNull(projection.updatedAt) ?? entry.heartbeatAt ?? null,
872
+ completedAt: stringOrNull(projection.completedAt),
873
+ joinLink: stringOrNull(projection.joinLink) ?? entry.joinLink ?? null,
874
+ webLink: stringOrNull(projection.webLink) ?? entry.webLink ?? null,
875
+ relayUrl: stringOrNull(projection.relayUrl) ?? entry.relayUrl ?? null,
876
+ sessionPath,
877
+ prUrl: stringOrNull(projection.prUrl),
878
+ worktreePath: stringOrNull(projection.worktreePath) ?? collabCwd,
879
+ pendingApprovals: numberOrNull(projection.pendingApprovals) ?? folded.pendingApprovals.length,
880
+ pendingInputs: numberOrNull(projection.pendingInputs) ?? folded.pendingUserInputs.length,
881
+ steeringCount: projection.steeringCount ?? 0,
882
+ stallCount: projection.stallCount ?? 0,
883
+ errorSummary: stringOrNull(projection.errorSummary) ?? summarizeRunError(folded),
884
+ timeline: Array.isArray(projection.timeline) ? [...projection.timeline] : [...timelineEntriesFromCustomEntries([])],
885
+ inbox: inboxFromProjection(folded),
886
+ collabCwd: collabCwd ?? null,
887
+ projection: folded
888
+ };
889
+ }
890
+ function runRecordsFromCollab(projectRoot, collabs) {
891
+ return sortByRecency(collabs.map((collab) => runRecordFromRegistryEntry(projectRoot, registryEntryFromCollab(collab))).filter((record) => record !== null));
892
+ }
893
+ function sortByRecency(records) {
894
+ return [...records].sort((a, b) => {
895
+ const at = Date.parse(b.updatedAt ?? b.startedAt ?? "") || 0;
896
+ const bt = Date.parse(a.updatedAt ?? a.startedAt ?? "") || 0;
897
+ return at - bt;
898
+ });
899
+ }
900
+ function discoveryDiagnosticRunRecord(projectRoot, error) {
901
+ const detail = error instanceof Error ? error.message : String(error);
902
+ const runId = DISCOVERY_DIAGNOSTIC_RUN_ID;
903
+ const projection = {
904
+ ...EMPTY_PROJECTION,
905
+ record: { runId, title: "Registry discovery unavailable" },
906
+ status: "needs-attention",
907
+ stallCount: 1
908
+ };
909
+ return {
910
+ runId,
911
+ taskId: null,
912
+ title: "Registry discovery unavailable",
913
+ status: "needs-attention",
914
+ source: "remote",
915
+ live: false,
916
+ stale: true,
917
+ startedAt: null,
918
+ updatedAt: null,
919
+ completedAt: null,
920
+ joinLink: null,
921
+ webLink: null,
922
+ relayUrl: null,
923
+ sessionPath: null,
924
+ prUrl: null,
925
+ worktreePath: null,
926
+ pendingApprovals: 0,
927
+ pendingInputs: 0,
928
+ steeringCount: 0,
929
+ stallCount: 1,
930
+ errorSummary: `registry discovery unavailable: ${detail}`,
931
+ timeline: [],
932
+ inbox: [],
933
+ collabCwd: null,
934
+ projection
935
+ };
936
+ }
937
+ async function listRunProjections(projectRoot, filter = {}) {
938
+ try {
939
+ const discovery = await loadCapabilityForRoot(projectRoot, RunDiscoveryCap);
940
+ if (!discovery)
941
+ return [discoveryDiagnosticRunRecord(projectRoot, "run discovery capability unavailable")];
942
+ const collabs = await discovery.listActiveRunCollab(projectRoot, filter);
943
+ return runRecordsFromCollab(projectRoot, collabs);
944
+ } catch (error) {
945
+ return [discoveryDiagnosticRunRecord(projectRoot, error)];
946
+ }
947
+ }
948
+ function selectRunProjection(runs, runId) {
949
+ const exactRun = runs.find((run) => run.runId === runId);
950
+ if (exactRun)
951
+ return exactRun;
952
+ const exactTask = runs.find((run) => run.taskId === runId);
953
+ if (exactTask)
954
+ return exactTask;
955
+ const prefixMatches = runs.filter((run) => run.runId.startsWith(runId));
956
+ if (prefixMatches.length === 1)
957
+ return prefixMatches[0] ?? null;
958
+ if (prefixMatches.length > 1) {
959
+ const matches = prefixMatches.map((run) => run.runId).join(", ");
960
+ throw new Error(`Ambiguous run id prefix "${runId}" matched ${prefixMatches.length} runs: ${matches}`);
961
+ }
962
+ return runs.find((run) => run.runId === DISCOVERY_DIAGNOSTIC_RUN_ID) ?? null;
963
+ }
964
+ async function getRunProjection(projectRoot, runId, filter = {}) {
965
+ const runs = await listRunProjections(projectRoot, filter);
966
+ return selectRunProjection(runs, runId);
967
+ }
968
+ async function resolveRunJoinTarget(projectRoot, runId, filter = {}) {
969
+ const run = await getRunProjection(projectRoot, runId, filter);
970
+ if (!run || !run.joinLink)
971
+ return null;
972
+ return { runId: run.runId, taskId: run.taskId, joinLink: run.joinLink, cwd: run.collabCwd ?? run.sessionPath, stale: run.stale };
973
+ }
974
+ var RunDiscoveryCap, EMPTY_PROJECTION, DISCOVERY_DIAGNOSTIC_RUN_ID = "__registry_discovery_error__", listRuns, getRun, resolveJoinTarget;
975
+ var init_projection = __esm(() => {
976
+ init_session_journal();
977
+ init_run_status();
978
+ RunDiscoveryCap = defineCapability(RUN_DISCOVERY);
979
+ EMPTY_PROJECTION = foldRunSessionEntries([], "");
980
+ listRuns = listRunProjections;
981
+ getRun = getRunProjection;
982
+ resolveJoinTarget = resolveRunJoinTarget;
983
+ });
984
+
985
+ // packages/run-worker/src/read-model-backend/control.ts
986
+ import { RIG_CONTROL_SENTINEL_END as RIG_CONTROL_SENTINEL_END2, RIG_PAUSE_SENTINEL as RIG_PAUSE_SENTINEL2, RIG_RESUME_SENTINEL as RIG_RESUME_SENTINEL2, RIG_STOP_SENTINEL as RIG_STOP_SENTINEL2, RIG_STOP_SENTINEL_END as RIG_STOP_SENTINEL_END2 } from "@rig/contracts";
987
+ function buildPauseSentinel(runId) {
988
+ return `${RIG_PAUSE_SENTINEL2} runId=${runId} requestedBy=operator ${RIG_CONTROL_SENTINEL_END2}`;
989
+ }
990
+ function buildResumeSentinel(runId) {
991
+ return `${RIG_RESUME_SENTINEL2} runId=${runId} requestedBy=operator ${RIG_CONTROL_SENTINEL_END2}`;
992
+ }
993
+ function buildStopSentinel(runId, reason) {
994
+ return `${RIG_STOP_SENTINEL2} runId=${runId} reason=${reason} ${RIG_STOP_SENTINEL_END2}`;
995
+ }
996
+ async function loadCollabControlDeps() {
997
+ const [{ importRoomKey, seal }, { COLLAB_PROTO, packEnvelope, parseCollabLink }] = await Promise.all([
998
+ import("@oh-my-pi/pi-coding-agent/collab/crypto"),
999
+ import("@oh-my-pi/pi-coding-agent/collab/protocol")
1000
+ ]);
1001
+ return { importRoomKey, seal, COLLAB_PROTO, packEnvelope, parseCollabLink };
1002
+ }
1003
+ function collabControlFrames(runId, control) {
1004
+ switch (control.kind) {
1005
+ case "steer":
1006
+ return [{ t: "prompt", text: control.message }];
1007
+ case "resume":
1008
+ return [{ t: "prompt", text: `${buildResumeSentinel(runId)}
1009
+ Continue the run from where it paused.` }];
1010
+ case "pause":
1011
+ return [
1012
+ { t: "prompt", text: `${buildPauseSentinel(runId)}
1013
+ Pause this run after the current interruption settles.` },
1014
+ { t: "abort" }
1015
+ ];
1016
+ case "stop":
1017
+ return [
1018
+ { t: "prompt", text: `${buildStopSentinel(runId, control.reason)}
1019
+ Stop this run and do not continue after the interruption settles.` },
1020
+ { t: "abort" }
1021
+ ];
1022
+ }
1023
+ }
1024
+ async function sendSealedCollabFrames(joinLink, frames, deps = {}) {
1025
+ const { importRoomKey, seal, COLLAB_PROTO, packEnvelope, parseCollabLink } = await loadCollabControlDeps();
1026
+ const parsed = parseCollabLink(joinLink);
1027
+ if ("error" in parsed)
1028
+ throw new Error(parsed.error);
1029
+ if (!parsed.writeToken)
1030
+ throw new Error("Run collab link is read-only; cannot send control.");
1031
+ const key = await importRoomKey(parsed.key);
1032
+ const WebSocketCtor = deps.WebSocket ?? WebSocket;
1033
+ const ws = new WebSocketCtor(`${parsed.wsUrl}?role=guest`);
1034
+ await new Promise((resolveOpen, rejectOpen) => {
1035
+ ws.addEventListener("open", () => resolveOpen(), { once: true });
1036
+ ws.addEventListener("error", () => rejectOpen(new Error("collab websocket error")), { once: true });
1037
+ });
1038
+ const hello = {
1039
+ t: "hello",
1040
+ proto: COLLAB_PROTO,
1041
+ name: "rig-operator",
1042
+ writeToken: Buffer.from(parsed.writeToken).toString("base64url")
1043
+ };
1044
+ ws.send(packEnvelope(0, await seal(key, hello)));
1045
+ for (const frame of frames)
1046
+ ws.send(packEnvelope(0, await seal(key, frame)));
1047
+ try {
1048
+ ws.close();
1049
+ } catch {}
1050
+ }
1051
+ async function deliverRemoteRunControl(projectRoot, target, control, deps = {}) {
1052
+ const record = typeof target === "string" ? await getRun(projectRoot, target) : target;
1053
+ const runId = typeof target === "string" ? target : target.runId;
1054
+ if (!record)
1055
+ throw new Error(`Run not found: ${runId}`);
1056
+ if (!record.joinLink)
1057
+ throw new Error(`Run ${record.runId} has no writable collab join link.`);
1058
+ await sendSealedCollabFrames(record.joinLink, collabControlFrames(record.runId, control), deps);
1059
+ }
1060
+ async function deliverRunControl(projectRoot, target, control, deps = {}) {
1061
+ const record = typeof target === "string" ? await (deps.getRun ?? getRun)(projectRoot, target) : target;
1062
+ const runId = typeof target === "string" ? target : target.runId;
1063
+ if (!record)
1064
+ throw new Error(`Run not found: ${runId}`);
1065
+ if (!record.joinLink)
1066
+ throw new Error(`Run ${record.runId} has no writable collab join link; attach interactively to ${control.kind}.`);
1067
+ try {
1068
+ await (deps.deliverRemote ?? deliverRemoteRunControl)(projectRoot, record, control);
1069
+ } catch (error) {
1070
+ const detail = error instanceof Error ? error.message : `Attach to ${control.kind} interactively: rig run attach ${record.runId}`;
1071
+ throw new Error(`Could not ${control.kind} run ${record.runId}. ${detail}`);
1072
+ }
1073
+ }
1074
+ var init_control = __esm(() => {
1075
+ init_projection();
1076
+ });
1077
+
1078
+ // packages/run-worker/src/read-model-backend/guard.ts
1079
+ var TERMINAL;
1080
+ var init_guard = __esm(() => {
1081
+ TERMINAL = new Set(["completed", "failed", "stopped"]);
1082
+ });
1083
+
1084
+ // packages/run-worker/src/read-model-backend/inbox.ts
1085
+ import { RIG_CONTROL_SENTINEL_END as RIG_CONTROL_SENTINEL_END3, RIG_INBOX_RESOLUTION_SENTINEL as RIG_INBOX_RESOLUTION_SENTINEL2 } from "@rig/contracts";
1086
+ function buildInboxResolutionSentinel(runId, payload) {
1087
+ return `${RIG_INBOX_RESOLUTION_SENTINEL2} runId=${runId} data=${encodeURIComponent(JSON.stringify(payload))} requestedBy=operator ${RIG_CONTROL_SENTINEL_END3}`;
1088
+ }
1089
+ function promptFromPayload(payload, fallback) {
1090
+ if (payload && typeof payload === "object") {
1091
+ const record = payload;
1092
+ for (const key of ["title", "message", "reason", "prompt", "summary"]) {
1093
+ const value = record[key];
1094
+ if (typeof value === "string" && value.trim().length > 0)
1095
+ return value.trim();
1096
+ }
1097
+ }
1098
+ return fallback;
1099
+ }
1100
+ function recordsFromRun(run, kind) {
1101
+ const pending = kind === "approvals" ? run.projection.pendingApprovals : run.projection.pendingUserInputs;
1102
+ return pending.map((request) => ({
1103
+ runId: run.runId,
1104
+ taskId: run.taskId,
1105
+ requestId: request.requestId,
1106
+ status: "pending",
1107
+ prompt: promptFromPayload(request.payload, kind === "approvals" ? "Approval requested" : "Input requested"),
1108
+ requestedAt: request.requestedAt,
1109
+ payload: request.payload,
1110
+ kind: kind === "approvals" ? "approval" : "input"
1111
+ }));
1112
+ }
1113
+ async function listInboxRecords(context, kind, filters = {}, deps = {}) {
1114
+ const projectRoot = typeof context === "string" ? context : context.projectRoot;
1115
+ const runs = await (deps.listRuns ?? listRuns)(projectRoot);
1116
+ const out = [];
1117
+ for (const run of runs) {
1118
+ if (filters.run && run.runId !== filters.run)
1119
+ continue;
1120
+ if (filters.task && run.taskId !== filters.task)
1121
+ continue;
1122
+ out.push(...recordsFromRun(run, kind));
1123
+ }
1124
+ return out;
1125
+ }
1126
+ function normalizedApprovalDecision(decision) {
1127
+ return decision === "approved" || decision === "approve" ? "approve" : "reject";
1128
+ }
1129
+ function inputAnswers(answer) {
1130
+ return typeof answer === "string" ? { answer } : answer;
1131
+ }
1132
+ function decisionText(runId, requestId, decision) {
1133
+ if (decision.kind === "approval") {
1134
+ const normalized = normalizedApprovalDecision(decision.decision);
1135
+ const label = normalized === "approve" ? "approved" : "rejected";
1136
+ return [
1137
+ buildInboxResolutionSentinel(runId, { kind: "approval", requestId, decision: normalized, note: decision.note ?? null }),
1138
+ `Rig inbox approval ${requestId} was ${label}.`,
1139
+ decision.note ? `Operator note: ${decision.note}` : null,
1140
+ "Continue using this approval decision."
1141
+ ].filter((line) => Boolean(line)).join(`
1142
+ `);
1143
+ }
1144
+ const answers = inputAnswers(decision.answer);
1145
+ return [
1146
+ buildInboxResolutionSentinel(runId, { kind: "input", requestId, answers }),
1147
+ `Rig inbox input ${requestId} was answered with:`,
1148
+ JSON.stringify(answers),
1149
+ "Continue using this input answer."
1150
+ ].join(`
1151
+ `);
1152
+ }
1153
+ async function resolveInboxRequest(projectRoot, runId, requestId, decision, deps = {}) {
1154
+ await (deps.deliverRunControl ?? deliverRunControl)(projectRoot, runId, { kind: "steer", message: decisionText(runId, requestId, decision) });
1155
+ }
1156
+ var init_inbox = __esm(() => {
1157
+ init_control();
1158
+ init_projection();
1159
+ });
1160
+
1161
+ // packages/run-worker/src/read-model-backend/inspect.ts
1162
+ import { RIG_RUN_LOG_ENTRY } from "@rig/contracts";
1163
+ function asRecord(value) {
1164
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
1165
+ }
1166
+ function firstString(record, keys) {
1167
+ for (const key of keys) {
1168
+ const value = record[key];
1169
+ if (typeof value === "string" && value.trim().length > 0)
1170
+ return value;
1171
+ }
1172
+ return null;
1173
+ }
1174
+ function stringifyLogPayload(value) {
1175
+ if (typeof value === "string")
1176
+ return value;
1177
+ if (typeof value === "number" || typeof value === "boolean")
1178
+ return String(value);
1179
+ const record = asRecord(value);
1180
+ if (!record)
1181
+ return null;
1182
+ const direct = firstString(record, ["line", "message", "text", "content", "output", "summary", "detail"]);
1183
+ if (direct)
1184
+ return direct;
1185
+ try {
1186
+ return JSON.stringify(record);
1187
+ } catch {
1188
+ return String(record);
1189
+ }
1190
+ }
1191
+ function logLineFromValue(value) {
1192
+ const record = asRecord(value);
1193
+ if (!record)
1194
+ return stringifyLogPayload(value);
1195
+ const direct = firstString(record, ["line", "message", "text", "content", "output", "summary", "detail"]);
1196
+ if (direct)
1197
+ return direct;
1198
+ if ("payload" in record)
1199
+ return stringifyLogPayload(record.payload);
1200
+ if ("data" in record)
1201
+ return stringifyLogPayload(record.data);
1202
+ return stringifyLogPayload(record);
1203
+ }
1204
+ function logLineFromSessionEntry(entry) {
1205
+ if (entry.type !== "custom" || entry.customType !== RIG_RUN_LOG_ENTRY)
1206
+ return null;
1207
+ return logLineFromValue(entry.data);
1208
+ }
1209
+ function logLinesFromProjection(projection) {
1210
+ const projected = projection;
1211
+ const lines = [];
1212
+ for (const key of ["logs", "logEntries", "journalLogs", "runLogs"]) {
1213
+ const entries = projected[key];
1214
+ if (!Array.isArray(entries))
1215
+ continue;
1216
+ for (const entry of entries) {
1217
+ const line = logLineFromValue(entry);
1218
+ if (line !== null)
1219
+ lines.push(line);
1220
+ }
1221
+ }
1222
+ return lines;
1223
+ }
1224
+ function extractRunLogs(run, deps = {}) {
1225
+ const projectedLines = logLinesFromProjection(run.projection);
1226
+ if (projectedLines.length > 0)
1227
+ return projectedLines;
1228
+ return (deps.readSessionRunEntries ?? readSessionRunEntries)(run.sessionPath).map(logLineFromSessionEntry).filter((line) => line !== null);
1229
+ }
1230
+ function summarizeRunFailures(run) {
1231
+ const failures = [];
1232
+ const useful = summarizeRunError(run.projection);
1233
+ if (useful)
1234
+ failures.push(`${run.runId}: ${useful}`);
1235
+ if (run.status === "failed" || run.projection.status === "failed")
1236
+ failures.push(`${run.runId}: run status failed`);
1237
+ for (const phase of run.projection.closeoutPhases) {
1238
+ if (phase.outcome === "failed")
1239
+ failures.push(`${run.runId}: closeout ${phase.phase} failed${phase.detail ? ` \u2014 ${phase.detail}` : ""}`);
1240
+ }
1241
+ for (const anomaly of run.projection.anomalies) {
1242
+ failures.push(`${run.runId}: anomaly ${anomaly.kind}${anomaly.detail ? ` \u2014 ${anomaly.detail}` : ""}`);
1243
+ }
1244
+ return failures;
1245
+ }
1246
+ function runInspectSummaryRows(runs, options = {}) {
1247
+ const attachable = runs.filter((run) => Boolean(run.joinLink && !run.stale)).length;
1248
+ const pendingInbox = options.pendingInbox ?? runs.reduce((total, run) => total + run.pendingApprovals + run.pendingInputs, 0);
1249
+ return [
1250
+ { id: "title", label: "Inspect", currentValue: "runtime", heading: true, description: "session/runtime inspection rows from @rig/client" },
1251
+ { id: "inspect:sessions", label: "RUNS", currentValue: String(runs.length), heading: true, description: `${attachable} attachable OMP collab links` },
1252
+ { id: "inspect:cwd", label: "PROJECT ROOT", currentValue: options.projectRoot ?? "", heading: true, description: "selected target/project root used by Rig chrome" },
1253
+ { id: "inspect:inbox", label: "INBOX", currentValue: String(pendingInbox), values: ["open"], description: "pending run gates; open Inbox to resolve" },
1254
+ { id: "inspect:runs", label: "RUNS", currentValue: String(runs.length), values: ["open"], description: "open Runs to inspect individual run detail, logs, and attach controls" },
1255
+ { id: "inspect:audit", label: "AUDIT", currentValue: "unavailable", heading: true, description: "CLI inspect audit has no cockpit equivalent; use rig inspect audit" }
1256
+ ];
1257
+ }
1258
+ var init_inspect = __esm(() => {
1259
+ init_projection();
1260
+ });
1261
+
1262
+ // packages/run-worker/src/read-model-backend/stats.ts
1263
+ function parseTimestamp(value) {
1264
+ if (!value)
1265
+ return null;
1266
+ const parsed = Date.parse(value);
1267
+ return Number.isFinite(parsed) ? parsed : null;
1268
+ }
1269
+ function median(values) {
1270
+ if (values.length === 0)
1271
+ return null;
1272
+ const sorted = [...values].sort((left, right) => left - right);
1273
+ const middle = Math.floor(sorted.length / 2);
1274
+ return sorted.length % 2 === 1 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
1275
+ }
1276
+ function rate(part, total) {
1277
+ return total === 0 ? null : part / total;
1278
+ }
1279
+ function completedDuration(run) {
1280
+ if (run.status !== "completed")
1281
+ return null;
1282
+ const startedAt = parseTimestamp(run.startedAt);
1283
+ const completedAt = parseTimestamp(run.completedAt);
1284
+ if (startedAt === null || completedAt === null || completedAt < startedAt)
1285
+ return null;
1286
+ return completedAt - startedAt;
1287
+ }
1288
+ async function computeStats(projectRootOrRuns, options = {}) {
1289
+ const sinceMs = options.since ? options.since.getTime() : null;
1290
+ const allRuns = typeof projectRootOrRuns === "string" ? await (options.listRuns ?? (await Promise.resolve().then(() => (init_projection(), exports_projection))).listRuns)(projectRootOrRuns) : projectRootOrRuns;
1291
+ const runs = allRuns.filter((run) => {
1292
+ if (sinceMs === null)
1293
+ return true;
1294
+ const startedAt = parseTimestamp(run.startedAt);
1295
+ return startedAt !== null && startedAt >= sinceMs;
1296
+ });
1297
+ const statusCounts = {};
1298
+ const completionDurations = [];
1299
+ let completedRuns = 0;
1300
+ let failedRuns = 0;
1301
+ let needsAttentionRuns = 0;
1302
+ let steeringTotal = 0;
1303
+ let stallTotal = 0;
1304
+ let approvalsPending = 0;
1305
+ for (const run of runs) {
1306
+ const status = run.status || "unknown";
1307
+ statusCounts[status] = (statusCounts[status] ?? 0) + 1;
1308
+ if (status === "completed")
1309
+ completedRuns += 1;
1310
+ if (status === "failed")
1311
+ failedRuns += 1;
1312
+ if (isNeedsAttention(run))
1313
+ needsAttentionRuns += 1;
1314
+ const duration = completedDuration(run);
1315
+ if (duration !== null)
1316
+ completionDurations.push(duration);
1317
+ steeringTotal += run.steeringCount;
1318
+ stallTotal += run.stallCount;
1319
+ approvalsPending += run.pendingApprovals;
1320
+ }
1321
+ const totalRuns = runs.length;
1322
+ return {
1323
+ since: options.since ? options.since.toISOString() : null,
1324
+ totalRuns,
1325
+ statusCounts,
1326
+ completedRuns,
1327
+ failedRuns,
1328
+ needsAttentionRuns,
1329
+ completionRate: rate(completedRuns, totalRuns),
1330
+ failureRate: rate(failedRuns, totalRuns),
1331
+ needsAttentionRate: rate(needsAttentionRuns, totalRuns),
1332
+ medianCompletionMs: median(completionDurations),
1333
+ steeringTotal,
1334
+ steeringPerRun: totalRuns === 0 ? null : steeringTotal / totalRuns,
1335
+ stallTotal,
1336
+ approvalsRequested: approvalsPending,
1337
+ approvalsApproved: 0,
1338
+ approvalsRejected: 0,
1339
+ approvalsPending
1340
+ };
1341
+ }
1342
+ var init_stats = __esm(() => {
1343
+ init_run_status();
1344
+ init_run_status();
1345
+ });
1346
+
1347
+ // packages/run-worker/src/read-model-backend/index.ts
1348
+ var init_read_model_backend = __esm(() => {
1349
+ init_projection();
1350
+ init_control();
1351
+ init_guard();
1352
+ init_inbox();
1353
+ init_inspect();
1354
+ init_run_status();
1355
+ init_stats();
1356
+ });
1357
+
1358
+ // packages/run-worker/src/read-model-service.ts
1359
+ var exports_read_model_service = {};
1360
+ __export(exports_read_model_service, {
1361
+ runReadModelService: () => runReadModelService
1362
+ });
1363
+ import { RUN_REGISTRY_BACKBONE } from "@rig/contracts";
1364
+ import { loadCapabilityForRoot as loadCapabilityForRoot2 } from "@rig/core/capability-loaders";
1365
+ import { defineCapability as defineCapability2 } from "@rig/core/capability";
1366
+ import { resolveOwnerNamespaceKey, resolveRegistryBaseUrl } from "@rig/core/remote-config";
1367
+ function discoveryFilter(filter) {
1368
+ return filter ?? {};
1369
+ }
1370
+ function requestedKinds(kind) {
1371
+ if (kind === "approval")
1372
+ return ["approvals"];
1373
+ if (kind === "input")
1374
+ return ["inputs"];
1375
+ return ["approvals", "inputs"];
1376
+ }
1377
+ function sourceMatches(run, source) {
1378
+ return !source || source === "all" || run.source === source;
1379
+ }
1380
+ function failureSummaries(run) {
1381
+ return summarizeRunFailures(run).map((summary) => ({ kind: "run", summary }));
1382
+ }
1383
+ function inboxRecord(record) {
1384
+ return {
1385
+ runId: record.runId,
1386
+ taskId: record.taskId,
1387
+ requestId: record.requestId,
1388
+ kind: record.kind,
1389
+ status: record.status,
1390
+ title: record.prompt,
1391
+ prompt: record.prompt,
1392
+ requestedAt: record.requestedAt,
1393
+ payload: record.payload,
1394
+ source: "run"
1395
+ };
1396
+ }
1397
+ function inboxDecision(resolution) {
1398
+ if (resolution.kind === "approval") {
1399
+ return { kind: "approval", decision: resolution.decision, ...resolution.note === undefined ? {} : { note: resolution.note } };
1400
+ }
1401
+ return { kind: "input", answer: resolution.answers };
1402
+ }
1403
+ async function listedRuns(input) {
1404
+ const runs = await listRuns(input.projectRoot, discoveryFilter(input.discoveryFilter));
1405
+ return runs.filter((run) => {
1406
+ if (input.taskId && run.taskId !== input.taskId && run.runId !== input.taskId)
1407
+ return false;
1408
+ return sourceMatches(run, input.source);
1409
+ });
1410
+ }
1411
+ async function selectedRun(input) {
1412
+ return getRun(input.projectRoot, input.id, discoveryFilter(input.discoveryFilter));
1413
+ }
1414
+ async function readDetails(input) {
1415
+ const run = await selectedRun(input);
1416
+ if (!run)
1417
+ return null;
1418
+ const pendingInbox = run.inbox;
1419
+ const inboxCounts = {
1420
+ approvals: run.pendingApprovals,
1421
+ inputs: run.pendingInputs,
1422
+ total: run.pendingApprovals + run.pendingInputs
1423
+ };
1424
+ const sessionEntries = run.sessionPath ? readSessionRunEntries(run.sessionPath) : undefined;
1425
+ return {
1426
+ run,
1427
+ projection: run.projection,
1428
+ pendingInbox,
1429
+ inboxCounts,
1430
+ sourceTask: null,
1431
+ ...sessionEntries ? { sessionEntries } : {},
1432
+ failures: failureSummaries(run),
1433
+ logs: input.includeLogs ? extractRunLogs(run) : []
1434
+ };
1435
+ }
1436
+ async function inboxRecords(input) {
1437
+ const out = [];
1438
+ for (const kind of requestedKinds(input.kind)) {
1439
+ const records = await listInboxRecords({ projectRoot: input.projectRoot }, kind, { ...input.runId ? { run: input.runId } : {}, ...input.taskId ? { task: input.taskId } : {} }, { listRuns: (projectRoot) => listedRuns({ projectRoot, discoveryFilter: input.discoveryFilter }) });
1440
+ out.push(...records.map(inboxRecord));
1441
+ }
1442
+ return out;
1443
+ }
1444
+ function classify(run) {
1445
+ const classification = classifyRun(run);
1446
+ return {
1447
+ ...classification,
1448
+ role: runStatusColorRole(run),
1449
+ rank: statusRank(run)
1450
+ };
1451
+ }
1452
+ async function controlTarget(input) {
1453
+ const run = await selectedRun({ projectRoot: input.projectRoot, id: input.runId, discoveryFilter: input.discoveryFilter });
1454
+ if (!run)
1455
+ return null;
1456
+ const canDeliver = Boolean(run.joinLink && !run.stale);
1457
+ return {
1458
+ runId: run.runId,
1459
+ taskId: run.taskId,
1460
+ sessionId: run.runId,
1461
+ sessionPath: run.sessionPath,
1462
+ joinLink: run.joinLink,
1463
+ webLink: run.webLink,
1464
+ relayUrl: run.relayUrl,
1465
+ collabCwd: run.collabCwd,
1466
+ live: run.live,
1467
+ stale: run.stale,
1468
+ canDeliver,
1469
+ reason: canDeliver ? null : run.stale ? "run is stale" : "run has no join link"
1470
+ };
1471
+ }
1472
+ async function removeRegistryEntry(projectRoot, runId) {
1473
+ const namespaceKey = resolveOwnerNamespaceKey(projectRoot);
1474
+ if (!namespaceKey)
1475
+ return false;
1476
+ try {
1477
+ const registryBackbone = await loadCapabilityForRoot2(projectRoot, RunRegistryBackboneCap);
1478
+ if (!registryBackbone)
1479
+ return false;
1480
+ await registryBackbone.createRegistryClient({ baseUrl: resolveRegistryBaseUrl(projectRoot), namespaceKey }).removeRoom(runId);
1481
+ return true;
1482
+ } catch {
1483
+ return false;
1484
+ }
1485
+ }
1486
+ var RunRegistryBackboneCap, runReadModelService;
1487
+ var init_read_model_service = __esm(() => {
1488
+ init_read_model_backend();
1489
+ RunRegistryBackboneCap = defineCapability2(RUN_REGISTRY_BACKBONE);
1490
+ runReadModelService = {
1491
+ async listRuns(input) {
1492
+ return listedRuns(input);
1493
+ },
1494
+ async getRun(input) {
1495
+ return selectedRun({ projectRoot: input.projectRoot, id: input.selector.id, discoveryFilter: input.discoveryFilter });
1496
+ },
1497
+ async getRunProjection(input) {
1498
+ const run = await selectedRun({ projectRoot: input.projectRoot, id: input.runId, discoveryFilter: input.discoveryFilter });
1499
+ return run?.projection ?? null;
1500
+ },
1501
+ async getRunDetails(input) {
1502
+ return readDetails({
1503
+ projectRoot: input.projectRoot,
1504
+ id: input.selector.id,
1505
+ includeLogs: input.includeLogs,
1506
+ discoveryFilter: input.discoveryFilter
1507
+ });
1508
+ },
1509
+ async inspectRun(input) {
1510
+ const details = await readDetails({
1511
+ projectRoot: input.projectRoot,
1512
+ id: input.selector.id,
1513
+ includeLogs: input.includeLogs,
1514
+ discoveryFilter: input.discoveryFilter
1515
+ });
1516
+ if (!details)
1517
+ return null;
1518
+ return {
1519
+ details,
1520
+ classification: classify(details.run),
1521
+ rows: runInspectSummaryRows([details.run], { projectRoot: input.projectRoot, pendingInbox: details.inboxCounts.total })
1522
+ };
1523
+ },
1524
+ listInboxRecords: inboxRecords,
1525
+ async getInboxCounts(input) {
1526
+ const records = await inboxRecords(input);
1527
+ const approvals = records.filter((record) => record.kind === "approval").length;
1528
+ const inputs = records.filter((record) => record.kind === "input").length;
1529
+ return { approvals, inputs, total: approvals + inputs };
1530
+ },
1531
+ async resolveInboxRequest(input) {
1532
+ const target = await controlTarget({ projectRoot: input.projectRoot, runId: input.runId, discoveryFilter: input.discoveryFilter });
1533
+ if (!target) {
1534
+ return {
1535
+ runId: input.runId,
1536
+ requestId: input.resolution.requestId,
1537
+ kind: input.resolution.kind,
1538
+ status: "not-found",
1539
+ delivered: false,
1540
+ detail: "run not found"
1541
+ };
1542
+ }
1543
+ if (!target.canDeliver) {
1544
+ return {
1545
+ runId: target.runId,
1546
+ requestId: input.resolution.requestId,
1547
+ kind: input.resolution.kind,
1548
+ status: "not-live",
1549
+ delivered: false,
1550
+ detail: target.reason ?? "run is not deliverable"
1551
+ };
1552
+ }
1553
+ await resolveInboxRequest(input.projectRoot, target.runId, input.resolution.requestId, inboxDecision(input.resolution));
1554
+ return {
1555
+ runId: target.runId,
1556
+ requestId: input.resolution.requestId,
1557
+ kind: input.resolution.kind,
1558
+ status: "resolved",
1559
+ delivered: true
1560
+ };
1561
+ },
1562
+ async getStats(input) {
1563
+ const since = input.since ? new Date(input.since) : null;
1564
+ const runs = input.runs ?? await listedRuns({ projectRoot: input.projectRoot, discoveryFilter: input.discoveryFilter });
1565
+ return computeStats(runs, { since });
1566
+ },
1567
+ async getInspectRows(input) {
1568
+ const runs = input.runs ?? await listedRuns({ projectRoot: input.projectRoot, discoveryFilter: input.discoveryFilter });
1569
+ return runInspectSummaryRows(runs, { projectRoot: input.projectRoot, pendingInbox: input.pendingInbox ?? null });
1570
+ },
1571
+ async deliverControl(input) {
1572
+ const run = await selectedRun({ projectRoot: input.projectRoot, id: input.runId, discoveryFilter: input.discoveryFilter });
1573
+ if (!run) {
1574
+ return {
1575
+ runId: input.runId,
1576
+ kind: input.control.kind,
1577
+ status: "not-found",
1578
+ delivered: false,
1579
+ detail: "run not found"
1580
+ };
1581
+ }
1582
+ if (!run.joinLink) {
1583
+ return {
1584
+ runId: run.runId,
1585
+ kind: input.control.kind,
1586
+ status: "not-live",
1587
+ delivered: false,
1588
+ detail: `Run ${run.runId} has no writable collab join link.`
1589
+ };
1590
+ }
1591
+ try {
1592
+ await deliverRunControl(input.projectRoot, run, input.control);
1593
+ return {
1594
+ runId: run.runId,
1595
+ kind: input.control.kind,
1596
+ status: "delivered",
1597
+ delivered: true
1598
+ };
1599
+ } catch (error) {
1600
+ return {
1601
+ runId: run.runId,
1602
+ kind: input.control.kind,
1603
+ status: "unsupported",
1604
+ delivered: false,
1605
+ detail: error instanceof Error ? error.message : String(error)
1606
+ };
1607
+ }
1608
+ },
1609
+ classifyRun: classify,
1610
+ resolveControlTarget: controlTarget,
1611
+ async removeRunRegistryEntry(input) {
1612
+ return { runId: input.runId, removed: await removeRegistryEntry(input.projectRoot, input.runId) };
1613
+ }
1614
+ };
1615
+ });
1616
+
1617
+ // packages/run-worker/src/host-kernel.ts
1618
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
1619
+ import { resolve as resolve2 } from "path";
1620
+ import { applyConfigEnv } from "@rig/core/config-env";
1621
+ import { loadConfig } from "@rig/core/load-config";
1622
+ import { bootDefaultKernelIntoProcess } from "@rig/kernel-seed/boot-default";
1623
+ import { createPlacementTransportPlugin } from "@rig/kernel-seed/default-kernel";
1624
+ function unquoteDotenvValue(value) {
1625
+ const trimmed = value.trim();
1626
+ if (trimmed.length >= 2 && (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'"))) {
1627
+ return trimmed.slice(1, -1);
1628
+ }
1629
+ return trimmed;
1630
+ }
1631
+ function hydrateDotenv(path, env) {
1632
+ if (!existsSync2(path))
1633
+ return false;
1634
+ const source = readFileSync2(path, "utf8");
1635
+ for (const rawLine of source.split(/\r?\n/)) {
1636
+ const line = rawLine.trim();
1637
+ if (!line || line.startsWith("#"))
1638
+ continue;
1639
+ const assignment = line.startsWith("export ") ? line.slice("export ".length).trim() : line;
1640
+ const equals = assignment.indexOf("=");
1641
+ if (equals <= 0)
1642
+ continue;
1643
+ const key = assignment.slice(0, equals).trim();
1644
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || env[key])
1645
+ continue;
1646
+ env[key] = unquoteDotenvValue(assignment.slice(equals + 1));
1647
+ }
1648
+ return true;
1649
+ }
1650
+ function createRunWorkerPlacementTransportPlugin(transport) {
1651
+ return createPlacementTransportPlugin(transport);
1652
+ }
1653
+ async function hydrateRunWorkerProjectEnv(projectRoot, options = {}) {
1654
+ const normalizedRoot = resolve2(projectRoot);
1655
+ const env = options.env ?? process.env;
1656
+ const errors = [];
1657
+ let dotenvLoaded = false;
1658
+ let configLoaded = false;
1659
+ try {
1660
+ dotenvLoaded = hydrateDotenv(resolve2(normalizedRoot, options.dotenvPath ?? ".env"), env);
1661
+ } catch (error) {
1662
+ errors.push(`dotenv: ${error instanceof Error ? error.message : String(error)}`);
1663
+ }
1664
+ try {
1665
+ applyConfigEnv(await loadConfig(normalizedRoot), env);
1666
+ configLoaded = true;
1667
+ } catch (error) {
1668
+ const message = error instanceof Error ? error.message : String(error);
1669
+ if (!message.includes("no rig.config"))
1670
+ errors.push(`config: ${message}`);
1671
+ }
1672
+ return { projectRoot: normalizedRoot, dotenvLoaded, configLoaded, errors };
1673
+ }
1674
+ async function adoptRunWorkerKernel(root, options = {}) {
1675
+ if (options.hydrateEnv === true && root !== undefined) {
1676
+ await hydrateRunWorkerProjectEnv(root, options);
1677
+ }
1678
+ const bootInput = {
1679
+ ...options.entrypoint !== undefined ? { entrypoint: options.entrypoint } : {},
1680
+ ...options.journal !== undefined ? { journal: options.journal } : {}
1681
+ };
1682
+ if (options.transport === undefined)
1683
+ return await bootDefaultKernelIntoProcess(bootInput);
1684
+ return await bootDefaultKernelIntoProcess({
1685
+ ...bootInput,
1686
+ extraPlugins: [createRunWorkerPlacementTransportPlugin(options.transport)]
1687
+ });
1688
+ }
1689
+ var init_host_kernel = () => {};
1690
+
1691
+ // packages/run-worker/src/local-run-changes.ts
1692
+ import { existsSync as existsSync3, mkdirSync, watch } from "fs";
1693
+ import { dirname, resolve as resolve3 } from "path";
1694
+ import { Effect, Queue, Stream } from "effect";
1695
+ function findNearestGitCheckoutRoot(startDir) {
1696
+ let current = resolve3(startDir);
1697
+ for (;; ) {
1698
+ if (existsSync3(resolve3(current, ".git")))
1699
+ return current;
1700
+ const parent = dirname(current);
1701
+ if (parent === current)
1702
+ return null;
1703
+ current = parent;
1704
+ }
1705
+ }
1706
+ function resolveCheckoutRoot(projectRoot) {
1707
+ const normalizedProjectRoot = resolve3(projectRoot);
1708
+ const explicit = process.env.MONOREPO_ROOT?.trim();
1709
+ if (explicit) {
1710
+ const explicitRoot = resolve3(explicit);
1711
+ const gitRoot = findNearestGitCheckoutRoot(explicitRoot);
1712
+ if (gitRoot)
1713
+ return gitRoot;
1714
+ throw new Error(`MONOREPO_ROOT points to ${explicitRoot}, but no git checkout was found there or above it.`);
1715
+ }
1716
+ return findNearestGitCheckoutRoot(normalizedProjectRoot) ?? normalizedProjectRoot;
1717
+ }
1718
+ function isRelevantLocalRunChange(filename) {
1719
+ if (filename === null || filename === undefined)
1720
+ return true;
1721
+ const raw = filename.toString();
1722
+ if (!raw.trim())
1723
+ return true;
1724
+ const segments = raw.split(/[\\/]+/).filter(Boolean);
1725
+ if (segments.some((segment) => segment === ".git" || segment === "node_modules" || segment === "build" || segment === "dist" || segment === "out" || segment === ".next" || segment === "coverage")) {
1726
+ return false;
1727
+ }
1728
+ const rigIndex = segments.lastIndexOf(".rig");
1729
+ if (rigIndex < 0)
1730
+ return false;
1731
+ const rigChild = segments[rigIndex + 1];
1732
+ if (rigChild === "session")
1733
+ return true;
1734
+ return rigChild === "runtime-context.json" && segments[rigIndex + 2] === undefined;
1735
+ }
1736
+ var localRunChanges = (projectRoot) => Stream.callback((queue) => Effect.gen(function* () {
1737
+ const worktreesRoot = resolve3(resolveCheckoutRoot(projectRoot), ".worktrees");
1738
+ if (!existsSync3(worktreesRoot)) {
1739
+ try {
1740
+ mkdirSync(worktreesRoot, { recursive: true });
1741
+ } catch {}
1742
+ }
1743
+ const watcher = watch(worktreesRoot, { recursive: true }, (_event, filename) => {
1744
+ if (!isRelevantLocalRunChange(filename))
1745
+ return;
1746
+ Queue.offerUnsafe(queue, undefined);
1747
+ });
1748
+ watcher.on("error", () => {});
1749
+ yield* Effect.addFinalizer(() => Effect.sync(() => watcher.close()));
1750
+ }), { bufferSize: 1, strategy: "sliding" });
1751
+ var init_local_run_changes = () => {};
1752
+
1753
+ // packages/run-worker/src/notify-cap.ts
1754
+ import { NOTIFY_SERVICE_CAPABILITY } from "@rig/contracts";
1755
+ import { defineCapability as defineCapability3 } from "@rig/core/capability";
1756
+ import { resolvePluginHost } from "@rig/core/project-plugins";
1757
+ async function resolveNotifyService(projectRoot) {
1758
+ const { host } = await resolvePluginHost(projectRoot);
1759
+ return NotifyCap.resolve(host);
1760
+ }
1761
+ var NotifyCap;
1762
+ var init_notify_cap = __esm(() => {
1763
+ NotifyCap = defineCapability3(NOTIFY_SERVICE_CAPABILITY);
1764
+ });
46
1765
 
47
1766
  // packages/run-worker/src/notifications.ts
48
- import { resolve } from "path";
49
- import { dispatchEventToTargets, loadNotificationConfig } from "@rig/notifications-plugin/notifications";
50
1767
  async function dispatchRunNotifications(projectRoot, runId, taskId, outcome, detail) {
51
1768
  try {
52
- const config = await loadNotificationConfig(resolve(projectRoot, ".rig", "notifications.json"));
53
- if (config.targets.length === 0)
1769
+ const notifier = await resolveNotifyService(projectRoot);
1770
+ if (!notifier)
54
1771
  return;
55
1772
  const event = { runId, type: `run.${outcome}`, timestamp: new Date().toISOString(), payload: { taskId, detail } };
56
1773
  await Promise.race([
57
- dispatchEventToTargets(event, config.targets),
1774
+ notifier.notify(event),
58
1775
  new Promise((resolveCap) => setTimeout(resolveCap, 5000))
59
1776
  ]);
60
1777
  } catch {}
61
1778
  }
62
- var init_notifications = () => {};
1779
+ var init_notifications = __esm(() => {
1780
+ init_notify_cap();
1781
+ });
1782
+
1783
+ // packages/run-worker/src/panel-plugin.ts
1784
+ import { createProjectPluginHost } from "@rig/core/project-plugins";
1785
+ import { RIG_CAPABILITY_PANEL_SLOT, RIG_RUN_STOP_PANEL_ACTION, RIG_SUPERVISOR_PANEL_ID } from "@rig/contracts";
1786
+ async function produceWorkerPanelPayload(producer, context) {
1787
+ if (!producer.produce)
1788
+ return;
1789
+ let timeout;
1790
+ try {
1791
+ return await Promise.race([
1792
+ Promise.resolve(producer.produce(context)),
1793
+ new Promise((resolve4) => {
1794
+ timeout = setTimeout(() => resolve4(undefined), PANEL_PRODUCER_TIMEOUT_MS);
1795
+ })
1796
+ ]);
1797
+ } finally {
1798
+ clearTimeout(timeout);
1799
+ }
1800
+ }
1801
+ async function loadWorkerPanelRegistry(projectRoot) {
1802
+ const { host } = await createProjectPluginHost(projectRoot, {
1803
+ mode: "strict-config-only"
1804
+ });
1805
+ return {
1806
+ registrations: host.listPanels().filter((registration) => registration.slot === RIG_CAPABILITY_PANEL_SLOT),
1807
+ producers: host.listExecutablePanels().filter((registration) => registration.slot === RIG_CAPABILITY_PANEL_SLOT)
1808
+ };
1809
+ }
1810
+ var RIG_PANELS_CUSTOM_MESSAGE_TYPE = "rig-panels", PANEL_PRODUCER_TIMEOUT_MS = 2000;
1811
+ var init_panel_plugin = () => {};
63
1812
 
64
1813
  // packages/run-worker/src/constants.ts
65
- var RUN_PROCESS_STEER_TIMEOUT_MS, TRACKED_RUN_STALL_MS, RUN_PROCESS_STALL_SWEEP_MS, RUN_PROCESS_STALL_DETAIL = "Run process made no OMP session progress for 20+ minutes; recording a stall so recovery can requeue or resume the session.";
1814
+ var TRACKED_RUN_STALL_MS, RUN_PROCESS_STALL_SWEEP_MS, RUN_PROCESS_STALL_DETAIL = "Run process made no OMP session progress for 20+ minutes; recording a stall so recovery can requeue or resume the session.";
66
1815
  var init_constants = __esm(() => {
67
- RUN_PROCESS_STEER_TIMEOUT_MS = 10 * 60 * 1000;
68
1816
  TRACKED_RUN_STALL_MS = 20 * 60 * 1000;
69
1817
  RUN_PROCESS_STALL_SWEEP_MS = 60 * 1000;
70
1818
  });
@@ -116,43 +1864,9 @@ var init_stall = __esm(() => {
116
1864
  init_constants();
117
1865
  });
118
1866
 
119
- // packages/run-worker/src/panel-plugin.ts
120
- import { createProjectPluginHost, projectPluginResolutionWarningMessages } from "@rig/core/project-plugins";
121
- import { RIG_CAPABILITY_PANEL_SLOT, RIG_RUN_STOP_PANEL_ACTION, RIG_SUPERVISOR_PANEL_ID } from "@rig/contracts";
122
- async function produceWorkerPanelPayload(producer, context) {
123
- if (!producer.produce)
124
- return;
125
- let timeout;
126
- try {
127
- return await Promise.race([
128
- Promise.resolve(producer.produce(context)),
129
- new Promise((resolve2) => {
130
- timeout = setTimeout(() => resolve2(undefined), PANEL_PRODUCER_TIMEOUT_MS);
131
- })
132
- ]);
133
- } finally {
134
- clearTimeout(timeout);
135
- }
136
- }
137
- async function loadWorkerPanelRegistry(projectRoot) {
138
- const { host, resolved } = await createProjectPluginHost(projectRoot, {
139
- mode: "strict-config-only",
140
- surfaceName: "run-worker-panel-registry"
141
- });
142
- for (const message of projectPluginResolutionWarningMessages(resolved)) {
143
- console.warn(`[rig-run] ${message}`);
144
- }
145
- return {
146
- registrations: host.listPanels().filter((registration) => registration.slot === RIG_CAPABILITY_PANEL_SLOT),
147
- producers: host.listExecutablePanels().filter((registration) => registration.slot === RIG_CAPABILITY_PANEL_SLOT)
148
- };
149
- }
150
- var RIG_PANELS_CUSTOM_MESSAGE_TYPE = "rig-panels", PANEL_PRODUCER_TIMEOUT_MS = 2000;
151
- var init_panel_plugin = () => {};
152
-
153
1867
  // packages/run-worker/src/utils.ts
154
- import { createWorkflowStatusChanged, RIG_WORKFLOW_STATUS_CHANGED } from "@rig/contracts";
155
- import { resolveRegistryBaseUrl, resolveRelayUrl } from "@rig/runtime/control-plane/remote-config";
1868
+ import { RIG_WORKFLOW_STATUS_CHANGED as RIG_WORKFLOW_STATUS_CHANGED2 } from "@rig/contracts";
1869
+ import { resolveRegistryBaseUrl as resolveRegistryBaseUrl2, resolveRelayUrl } from "@rig/core/remote-config";
156
1870
  function customEntries(entries) {
157
1871
  const customs = [];
158
1872
  for (const entry of entries) {
@@ -165,27 +1879,29 @@ function rigProjectRoot() {
165
1879
  return process.env.PROJECT_RIG_ROOT?.trim() || process.env.RIG_HOST_PROJECT_ROOT?.trim() || process.cwd();
166
1880
  }
167
1881
  function registryBaseUrl() {
168
- return resolveRegistryBaseUrl(rigProjectRoot());
1882
+ return resolveRegistryBaseUrl2(rigProjectRoot());
169
1883
  }
170
1884
  function rigRelayUrl() {
171
1885
  return resolveRelayUrl();
172
1886
  }
173
- var init_utils = () => {};
1887
+ var init_utils = __esm(() => {
1888
+ init_session_journal();
1889
+ });
174
1890
 
175
1891
  // packages/run-worker/src/autohost.ts
176
- import { runPipelineCloseout } from "@rig/bundle-default-lifecycle/pipeline-closeout";
177
- import { adoptPlacementKernel } from "@rig/kernel/kernel-entrypoint";
178
- import { latestTimelineEntriesFromCustomEntries, parseInboxResolutionSentinel, parsePauseSentinel, parseResumeSentinel, parseStopSentinel, RIG_RUN_STOP_PANEL_ACTION as RIG_RUN_STOP_PANEL_ACTION2, RIG_SUPERVISOR_PANEL_ID as RIG_SUPERVISOR_PANEL_ID2, sessionIdFromSessionFile } from "@rig/contracts";
179
- import { Duration, Effect, Fiber, Stream } from "effect";
180
- import { createEnvCloseoutRunners } from "@rig/bundle-default-lifecycle/native/closeout-runners";
181
- import { CloseoutValidationError } from "@rig/bundle-default-lifecycle/native/in-process-closeout";
182
- import { projectRunFromSession } from "@rig/runtime/control-plane/run-session-projection";
183
- import { localRunChanges } from "@rig/runtime/control-plane/run-discovery-stream";
184
- import { updateRunTaskSourceLifecycle } from "@rig/runtime/control-plane/tasks/source-lifecycle";
185
- import { resolveOwnerNamespaceKey } from "@rig/runtime/control-plane/remote-config";
186
- import { resolveRigIdentity } from "@rig/runtime/control-plane/identity";
187
- import { connectWorkerProjection, createRegistryClient } from "@rig/relay-registry";
188
- import { coerceRegistryStatus } from "@rig/relay-registry/schema";
1892
+ import {
1893
+ PLACEMENT_RUN_TRANSPORT,
1894
+ RIG_RUN_STOP_PANEL_ACTION as RIG_RUN_STOP_PANEL_ACTION2,
1895
+ RIG_SUPERVISOR_PANEL_ID as RIG_SUPERVISOR_PANEL_ID2,
1896
+ RUN_IDENTITY_ENV,
1897
+ RUN_REGISTRY_BACKBONE as RUN_REGISTRY_BACKBONE2,
1898
+ RUN_CLOSEOUT_CAPABILITY,
1899
+ TASK_DATA_SERVICE_CAPABILITY
1900
+ } from "@rig/contracts";
1901
+ import { Duration, Effect as Effect2, Fiber, Stream as Stream2 } from "effect";
1902
+ import { defineCapability as defineCapability4 } from "@rig/core/capability";
1903
+ import { requireInstalledCapability, loadCapabilityForRoot as loadCapabilityForRoot3 } from "@rig/core/capability-loaders";
1904
+ import { resolveOwnerNamespaceKey as resolveOwnerNamespaceKey2 } from "@rig/core/remote-config";
189
1905
  function syntheticRegistryOwner(namespaceKey) {
190
1906
  const githubUserId = namespaceKey.startsWith("gh:") ? namespaceKey.slice(3) : namespaceKey;
191
1907
  return {
@@ -194,18 +1910,25 @@ function syntheticRegistryOwner(namespaceKey) {
194
1910
  namespaceKey
195
1911
  };
196
1912
  }
1913
+ function coerceRegistryStatus(value, fallback) {
1914
+ if (value === "starting")
1915
+ return "preparing";
1916
+ if (value === "waiting-input")
1917
+ return "waiting-user-input";
1918
+ return typeof value === "string" && REGISTRY_STATUS[value] ? value : fallback;
1919
+ }
197
1920
  async function reflectStoppedRunTaskSource(input) {
198
1921
  const taskId = input.taskId?.trim();
199
1922
  if (!taskId)
200
1923
  return false;
201
1924
  const reason = input.reason?.trim();
202
- await (input.updateLifecycle ?? updateRunTaskSourceLifecycle)(input.projectRoot, {
1925
+ await (input.updateLifecycle ?? taskData().updateRunTaskSourceLifecycle)(input.projectRoot, {
203
1926
  runId: input.runId,
204
1927
  taskId,
205
- sourceTask: input.sourceTask,
206
- worktreePath: input.worktreePath,
207
- logRoot: input.logRoot,
208
- sessionPath: input.sessionPath
1928
+ ...input.sourceTask !== undefined ? { sourceTask: input.sourceTask } : {},
1929
+ ...input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {},
1930
+ ...input.logRoot !== undefined ? { logRoot: input.logRoot } : {},
1931
+ ...input.sessionPath !== undefined ? { sessionPath: input.sessionPath } : {}
209
1932
  }, "cancelled", reason ? `Rig stopped by operator: ${reason}` : "Rig stopped by operator.");
210
1933
  return true;
211
1934
  }
@@ -286,8 +2009,14 @@ async function maybeStartRunProcessAutohost(api, ctx) {
286
2009
  throw new Error("OMP session id is required when RIG_RUN_PROCESS=1; RIG_RUN_ID is only a dispatch handle.");
287
2010
  const projectRoot = process.env.PROJECT_RIG_ROOT ?? process.cwd();
288
2011
  const journal = await createRunJournal(ctx.sessionManager, runId);
289
- await adoptPlacementKernel(projectRoot, {
2012
+ const placementTransport = await loadCapabilityForRoot3(projectRoot, PlacementTransportCap);
2013
+ if (!placementTransport) {
2014
+ throw new Error("placement run transport capability unavailable: ensure @rig/transport-plugin is installed.");
2015
+ }
2016
+ await adoptRunWorkerKernel(projectRoot, {
290
2017
  entrypoint: "run-worker",
2018
+ hydrateEnv: true,
2019
+ transport: placementTransport,
291
2020
  ...journal ? { journal: journal.kernel } : {}
292
2021
  });
293
2022
  if (!ctx.hasUI)
@@ -296,7 +2025,9 @@ async function maybeStartRunProcessAutohost(api, ctx) {
296
2025
  const startHost = collab?.startCollabHost ?? collab?.startHost;
297
2026
  if (!startHost)
298
2027
  throw new Error("OMP collab host facade is unavailable for Rig run process.");
299
- const identity = resolveRigIdentity(ctx);
2028
+ const identityEnv = await loadCapabilityForRoot3(projectRoot, RunIdentityEnvCap);
2029
+ const identity = identityEnv?.resolveRigIdentity(ctx) ?? null;
2030
+ const registryBackbone = await loadCapabilityForRoot3(projectRoot, RunRegistryBackboneCap2);
300
2031
  const panelRegistry = await loadWorkerPanelRegistry(projectRoot);
301
2032
  let runProjection = projectRunFromSession(customEntries(ctx.sessionManager.getBranch()), runId);
302
2033
  const taskIdAtStart = process.env.RIG_TASK_ID?.trim() || runProjection.record.taskId;
@@ -315,10 +2046,10 @@ async function maybeStartRunProcessAutohost(api, ctx) {
315
2046
  let runRegistryRoomId = null;
316
2047
  let workerProjectionConnection = null;
317
2048
  let workerProjectionFiber = null;
318
- const runRegistryNamespace = identity?.owner?.namespaceKey ?? resolveOwnerNamespaceKey(rigProjectRoot()) ?? "anonymous";
2049
+ const runRegistryNamespace = identity?.owner?.namespaceKey ?? resolveOwnerNamespaceKey2(rigProjectRoot()) ?? "anonymous";
319
2050
  const runRegistryOwner = identity?.owner ?? syntheticRegistryOwner(runRegistryNamespace);
320
2051
  const runRegistryRepo = identity?.selectedRepo ?? "";
321
- const runRegistry = createRegistryClient({ baseUrl: registryBaseUrl(), namespaceKey: runRegistryNamespace });
2052
+ const runRegistry = registryBackbone?.createRegistryClient({ baseUrl: registryBaseUrl(), namespaceKey: runRegistryNamespace }) ?? null;
322
2053
  let runRegistryLinks = {};
323
2054
  const processedControlEntryIds = new Set((ctx.sessionManager.getEntries?.() ?? []).map((entry) => entry && typeof entry === "object" && typeof entry.id === "string" ? entry.id : null).filter((id) => id !== null));
324
2055
  const processedControlEntryObjects = new WeakSet;
@@ -352,7 +2083,7 @@ async function maybeStartRunProcessAutohost(api, ctx) {
352
2083
  joinLink: links.joinLink,
353
2084
  webLink: links.webLink,
354
2085
  relayUrl: links.relayUrl,
355
- sessionPath: ctx.sessionManager.getSessionFile(),
2086
+ sessionPath: ctx.sessionManager.getSessionFile() ?? null,
356
2087
  timeline
357
2088
  });
358
2089
  };
@@ -366,7 +2097,7 @@ async function maybeStartRunProcessAutohost(api, ctx) {
366
2097
  projectRoot,
367
2098
  runId,
368
2099
  folded,
369
- taskIdAtStart,
2100
+ ...taskIdAtStart !== undefined ? { taskIdAtStart } : {},
370
2101
  runDisplayTitle
371
2102
  };
372
2103
  const payloadEntries = await Promise.all(panelRegistry.producers.map(async (producer) => {
@@ -426,7 +2157,7 @@ async function maybeStartRunProcessAutohost(api, ctx) {
426
2157
  runRegistryHeartbeat = null;
427
2158
  }
428
2159
  if (workerProjectionFiber) {
429
- Effect.runFork(Fiber.interrupt(workerProjectionFiber));
2160
+ Effect2.runFork(Fiber.interrupt(workerProjectionFiber));
430
2161
  workerProjectionFiber = null;
431
2162
  }
432
2163
  if (workerProjectionConnection) {
@@ -460,26 +2191,26 @@ async function maybeStartRunProcessAutohost(api, ctx) {
460
2191
  journal?.appendTimeline({ type: "inbox-resolution", kind: "input", requestId: resolution.requestId });
461
2192
  };
462
2193
  const applyRunControlText = (text) => {
463
- const control = detectRunControlText(text, runId);
464
- if (!control)
2194
+ const control2 = detectRunControlText(text, runId);
2195
+ if (!control2)
465
2196
  return;
466
2197
  markRunActivity();
467
- if (control.kind === "pause") {
2198
+ if (control2.kind === "pause") {
468
2199
  pendingPause = true;
469
2200
  return;
470
2201
  }
471
- if (control.kind === "resume") {
2202
+ if (control2.kind === "resume") {
472
2203
  pendingPause = false;
473
2204
  pendingStopReason = undefined;
474
2205
  appendRunStatus("running", "operator resumed run", true);
475
2206
  publishRunProjection("running");
476
2207
  return;
477
2208
  }
478
- if (control.kind === "stop") {
479
- pendingStopReason = control.reason ?? "operator requested stop";
2209
+ if (control2.kind === "stop") {
2210
+ pendingStopReason = control2.reason ?? "operator requested stop";
480
2211
  return;
481
2212
  }
482
- applyInboxResolution(control.resolution);
2213
+ applyInboxResolution(control2.resolution);
483
2214
  };
484
2215
  const processRunControlMessages = () => {
485
2216
  for (const entry of ctx.sessionManager.getEntries?.() ?? []) {
@@ -538,7 +2269,7 @@ async function maybeStartRunProcessAutohost(api, ctx) {
538
2269
  if (roomId !== runId) {
539
2270
  throw new Error(`Collab host session id mismatch: expected ${runId}, got ${roomId}`);
540
2271
  }
541
- runRegistryLinks = { joinLink: projection.joinLink, webLink: projection.webLink, relayUrl: projection.relayUrl ?? rigRelayUrl() };
2272
+ runRegistryLinks = { joinLink: projection.joinLink ?? null, webLink: projection.webLink ?? null, relayUrl: projection.relayUrl ?? rigRelayUrl() };
542
2273
  const timeline = {
543
2274
  type: "collab-host-started",
544
2275
  roomId,
@@ -550,10 +2281,11 @@ async function maybeStartRunProcessAutohost(api, ctx) {
550
2281
  console.log(`[rig-run] collab-host-started joinLink=${projection.joinLink || "(empty)"} relayUrl=${projection.relayUrl || "(empty)"}`);
551
2282
  ctx.ui.notify("Rig run collab host started.", "info");
552
2283
  publishRigPanelsSnapshotBestEffort();
553
- if (runRegistry) {
2284
+ if (runRegistry && registryBackbone) {
554
2285
  try {
555
2286
  runRegistryRoomId = roomId;
556
2287
  const initialProjection = buildCurrentRegistryProjection();
2288
+ const sessionPath = ctx.sessionManager.getSessionFile();
557
2289
  await runRegistry.registerRoom({
558
2290
  roomId,
559
2291
  owner: runRegistryOwner,
@@ -565,14 +2297,14 @@ async function maybeStartRunProcessAutohost(api, ctx) {
565
2297
  relayUrl: projection.relayUrl ?? rigRelayUrl(),
566
2298
  startedAt: new Date().toISOString(),
567
2299
  cwd: process.cwd(),
568
- sessionPath: ctx.sessionManager.getSessionFile() ?? undefined,
2300
+ ...sessionPath ? { sessionPath } : {},
569
2301
  pid: process.pid,
570
2302
  projection: initialProjection
571
2303
  });
572
- workerProjectionConnection = connectWorkerProjection({ baseUrl: registryBaseUrl(), namespaceKey: runRegistryNamespace, runId: roomId });
2304
+ workerProjectionConnection = registryBackbone.connectWorkerProjection({ baseUrl: registryBaseUrl(), namespaceKey: runRegistryNamespace, runId: roomId });
573
2305
  workerProjectionConnection.ready.catch((err) => console.error(`[rig-run] worker-projection-degraded (heartbeat remains authoritative): ${err instanceof Error ? err.message : String(err)}`));
574
2306
  pushWorkerProjection();
575
- workerProjectionFiber = Effect.runFork(localRunChanges(projectRoot).pipe(Stream.debounce(Duration.millis(500)), Stream.runForEach(() => Effect.sync(() => pushWorkerProjection()))));
2307
+ workerProjectionFiber = Effect2.runFork(localRunChanges(projectRoot).pipe(Stream2.debounce(Duration.millis(500)), Stream2.runForEach(() => Effect2.sync(() => pushWorkerProjection()))));
576
2308
  journal?.appendTimeline({ type: "registry-registered", roomId });
577
2309
  console.log(`[rig-run] registry-registered roomId=${roomId}`);
578
2310
  runRegistryHeartbeat = setInterval(() => {
@@ -605,7 +2337,7 @@ async function maybeStartRunProcessAutohost(api, ctx) {
605
2337
  if (taskIdAtStart) {
606
2338
  journal?.appendTimeline({ type: "stage", stage: "GitHub-sync", status: "running", detail: "reflecting rig:running to task source" });
607
2339
  try {
608
- await updateRunTaskSourceLifecycle(projectRoot, {
2340
+ await taskData().updateRunTaskSourceLifecycle(projectRoot, {
609
2341
  runId,
610
2342
  taskId: taskIdAtStart,
611
2343
  sourceTask: runProjection.record.sourceTask,
@@ -698,10 +2430,9 @@ async function maybeStartRunProcessAutohost(api, ctx) {
698
2430
  setTimeout(() => process.exit(1), 0);
699
2431
  return;
700
2432
  }
701
- const { command, gitCommand } = createEnvCloseoutRunners(process.env);
702
2433
  let closeoutStatusAdvanced = false;
703
2434
  try {
704
- await runPipelineCloseout({
2435
+ await requireInstalledCapability(RunCloseoutCap, "run-closeout capability unavailable in run-worker autohost: ensure @rig/bundle-default-lifecycle (default bundle) is installed.")({
705
2436
  projectRoot,
706
2437
  runId,
707
2438
  taskId,
@@ -709,8 +2440,6 @@ async function maybeStartRunProcessAutohost(api, ctx) {
709
2440
  workspace: process.cwd(),
710
2441
  artifactRoot: runProjection.record.artifactRoot ?? null,
711
2442
  sourceTask: runProjection.record.sourceTask && typeof runProjection.record.sourceTask === "object" && !Array.isArray(runProjection.record.sourceTask) ? runProjection.record.sourceTask : null,
712
- command,
713
- gitCommand,
714
2443
  steerPi,
715
2444
  onValidationStart: async () => {
716
2445
  journal?.appendStatus("validating", { actor: { kind: "agent" }, reason: "validating task before closeout", force: true });
@@ -726,7 +2455,7 @@ async function maybeStartRunProcessAutohost(api, ctx) {
726
2455
  }
727
2456
  },
728
2457
  reflect: async (status, summary, opts) => {
729
- await updateRunTaskSourceLifecycle(projectRoot, {
2458
+ await taskData().updateRunTaskSourceLifecycle(projectRoot, {
730
2459
  runId,
731
2460
  taskId,
732
2461
  sourceTask: runProjection.record.sourceTask,
@@ -745,7 +2474,7 @@ async function maybeStartRunProcessAutohost(api, ctx) {
745
2474
  setTimeout(() => process.exit(0), 0);
746
2475
  } catch (error) {
747
2476
  const detail = error instanceof Error ? error.message : String(error);
748
- const status = error instanceof CloseoutValidationError ? "needs-attention" : "failed";
2477
+ const status = error instanceof Error && error.name === "CloseoutValidationError" ? "needs-attention" : "failed";
749
2478
  journal?.appendStatus(status, { actor: { kind: "agent" }, errorText: detail, force: true });
750
2479
  await publishRunProjection(status);
751
2480
  await dispatchRunNotifications(projectRoot, runId, taskId, "failed", detail);
@@ -771,7 +2500,7 @@ async function maybeStartSpikeAutohost(ctx) {
771
2500
  const startHost = collab?.startHost ?? collab?.startCollabHost;
772
2501
  if (!startHost)
773
2502
  throw new Error("OMP collab host facade is unavailable for detached PTY spike.");
774
- const identity = resolveRigIdentity(ctx);
2503
+ const identity = (await loadCapabilityForRoot3(rigProjectRoot(), RunIdentityEnvCap))?.resolveRigIdentity(ctx) ?? null;
775
2504
  await startHost.call(collab, {
776
2505
  relayUrl,
777
2506
  title: "Rig detached PTY spike",
@@ -779,13 +2508,38 @@ async function maybeStartSpikeAutohost(ctx) {
779
2508
  ...identity?.selectedRepo ? { selectedRepo: identity.selectedRepo } : {}
780
2509
  });
781
2510
  }
782
- var REGISTRY_PROJECTION_TIMELINE_LIMIT = 100, OPERATOR_ACTOR;
2511
+ var TaskDataCap, PlacementTransportCap, RunIdentityEnvCap, RunRegistryBackboneCap2, RunCloseoutCap, taskData = () => requireInstalledCapability(TaskDataCap, "task-data capability unavailable in run-exec autohost: ensure @rig/task-sources-plugin (default bundle) is installed."), REGISTRY_STATUS, REGISTRY_PROJECTION_TIMELINE_LIMIT = 100, OPERATOR_ACTOR;
783
2512
  var init_autohost = __esm(() => {
784
- init_journal();
2513
+ init_host_kernel();
2514
+ init_local_run_changes();
785
2515
  init_notifications();
786
- init_stall();
787
2516
  init_panel_plugin();
2517
+ init_session_journal();
2518
+ init_stall();
788
2519
  init_utils();
2520
+ TaskDataCap = defineCapability4(TASK_DATA_SERVICE_CAPABILITY);
2521
+ PlacementTransportCap = defineCapability4(PLACEMENT_RUN_TRANSPORT);
2522
+ RunIdentityEnvCap = defineCapability4(RUN_IDENTITY_ENV);
2523
+ RunRegistryBackboneCap2 = defineCapability4(RUN_REGISTRY_BACKBONE2);
2524
+ RunCloseoutCap = defineCapability4(RUN_CLOSEOUT_CAPABILITY);
2525
+ REGISTRY_STATUS = {
2526
+ created: true,
2527
+ queued: true,
2528
+ preparing: true,
2529
+ running: true,
2530
+ "waiting-approval": true,
2531
+ "waiting-user-input": true,
2532
+ paused: true,
2533
+ validating: true,
2534
+ reviewing: true,
2535
+ "closing-out": true,
2536
+ "needs-attention": true,
2537
+ completed: true,
2538
+ failed: true,
2539
+ stopped: true,
2540
+ starting: true,
2541
+ "waiting-input": true
2542
+ };
789
2543
  OPERATOR_ACTOR = { kind: "operator" };
790
2544
  });
791
2545
 
@@ -825,11 +2579,65 @@ var init_extension = __esm(() => {
825
2579
  });
826
2580
 
827
2581
  // packages/run-worker/src/plugin.ts
2582
+ import { defineCapability as defineCapability5 } from "@rig/core/capability";
828
2583
  import { definePlugin } from "@rig/core/config";
2584
+ import { RUN_READ_MODEL } from "@rig/contracts";
2585
+ async function installWorkerInboxIfPresent(parentPort) {
2586
+ if (!parentPort)
2587
+ return;
2588
+ const { installWorkerInbox } = await import("@oh-my-pi/pi-utils/worker-host");
2589
+ installWorkerInbox(parentPort);
2590
+ }
2591
+ var RunReadModelCap = defineCapability5(RUN_READ_MODEL);
2592
+ var RUN_WORKER_SEED_ENTRYPOINTS = [
2593
+ {
2594
+ id: "@rig/run-worker:stats-sync-worker",
2595
+ workerArg: "__omp_worker_stats_sync",
2596
+ description: "OMP stats sync self-exec worker.",
2597
+ run: async () => {
2598
+ const scope = globalThis;
2599
+ const pending = [];
2600
+ const buffer = (event) => {
2601
+ pending.push(event);
2602
+ };
2603
+ scope.onmessage = buffer;
2604
+ await import("@oh-my-pi/omp-stats/sync-worker");
2605
+ const handler = scope.onmessage;
2606
+ if (handler && handler !== buffer) {
2607
+ for (const event of pending)
2608
+ handler.call(scope, event);
2609
+ }
2610
+ }
2611
+ },
2612
+ {
2613
+ id: "@rig/run-worker:tab-worker",
2614
+ workerArg: "__omp_worker_tab",
2615
+ description: "Browser tab tool self-exec worker.",
2616
+ run: async ({ parentPort }) => {
2617
+ await installWorkerInboxIfPresent(parentPort);
2618
+ await import("@oh-my-pi/pi-coding-agent/tools/browser/tab-worker-entry");
2619
+ }
2620
+ },
2621
+ {
2622
+ id: "@rig/run-worker:js-eval-worker",
2623
+ workerArg: "__omp_worker_js_eval",
2624
+ description: "JavaScript eval tool self-exec worker.",
2625
+ run: async ({ parentPort }) => {
2626
+ await installWorkerInboxIfPresent(parentPort);
2627
+ await import("@oh-my-pi/pi-coding-agent/eval/js/worker-entry");
2628
+ }
2629
+ }
2630
+ ];
829
2631
  var runWorkerPlugin = definePlugin({
830
2632
  name: "@rig/run-worker",
831
2633
  version: "0.0.0-alpha.1",
832
2634
  contributes: {
2635
+ capabilities: [
2636
+ RunReadModelCap.provide(async () => (await Promise.resolve().then(() => (init_read_model_service(), exports_read_model_service))).runReadModelService, {
2637
+ title: "Run read-model service",
2638
+ description: "List, inspect, summarize, and target canonical run session projections for operator surfaces."
2639
+ })
2640
+ ],
833
2641
  sessionExtensions: [
834
2642
  {
835
2643
  id: "rig:run-worker",
@@ -839,7 +2647,8 @@ var runWorkerPlugin = definePlugin({
839
2647
  rigWorkerExtension2(api);
840
2648
  }
841
2649
  }
842
- ]
2650
+ ],
2651
+ seedEntrypoints: RUN_WORKER_SEED_ENTRYPOINTS
843
2652
  }
844
2653
  });
845
2654
  function createRunWorkerPlugin() {