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

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.
@@ -0,0 +1,990 @@
1
+ // @bun
2
+ var __defProp = Object.defineProperty;
3
+ var __returnValue = (v) => v;
4
+ function __exportSetter(name, newValue) {
5
+ this[name] = __returnValue.bind(null, newValue);
6
+ }
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, {
10
+ get: all[name],
11
+ enumerable: true,
12
+ configurable: true,
13
+ set: __exportSetter.bind(all, name)
14
+ });
15
+ };
16
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
17
+ var __require = import.meta.require;
18
+
19
+ // packages/run-worker/src/runs/diagnostics.ts
20
+ function normalizeString(value) {
21
+ if (typeof value !== "string")
22
+ return null;
23
+ const normalized = value.replace(/\s+/g, " ").trim();
24
+ return normalized.length > 0 ? normalized : null;
25
+ }
26
+ function isGenericRunFailure(value) {
27
+ const text = normalizeString(value);
28
+ return Boolean(text && /^Task run failed \([^)]*\)$/i.test(text));
29
+ }
30
+ function appendCandidate(candidates, value) {
31
+ const text = normalizeString(value);
32
+ if (text && !candidates.includes(text))
33
+ candidates.push(text);
34
+ }
35
+ function categorizeUsefulRunError(lines) {
36
+ const taskSourceFailure = lines.find((line) => /failed to update task source/i.test(line));
37
+ if (taskSourceFailure)
38
+ return `Task source update failed: ${taskSourceFailure}`;
39
+ const moduleFailure = lines.find((line) => /cannot find module/i.test(line));
40
+ if (moduleFailure)
41
+ return `Runtime module resolution failed: ${moduleFailure}`;
42
+ const providerFailure = lines.find((line) => /no api key found|unauthorized|authentication failed|invalid api key/i.test(line));
43
+ if (providerFailure)
44
+ return `Provider authentication failed: ${providerFailure}`;
45
+ return null;
46
+ }
47
+ function summarizeRunError(projection) {
48
+ if (projection.status !== "failed")
49
+ return null;
50
+ const candidates = [];
51
+ for (const anomaly of projection.anomalies) {
52
+ appendCandidate(candidates, `Journal anomaly (${anomaly.kind}): ${anomaly.detail}`);
53
+ }
54
+ for (const phase of projection.closeoutPhases) {
55
+ if (phase.outcome === "failed")
56
+ appendCandidate(candidates, phase.detail);
57
+ }
58
+ for (const entry of projection.statusHistory) {
59
+ appendCandidate(candidates, entry.reason);
60
+ }
61
+ appendCandidate(candidates, projection.record.statusDetail);
62
+ appendCandidate(candidates, projection.record.errorText);
63
+ const nonGeneric = candidates.filter((candidate) => !isGenericRunFailure(candidate));
64
+ return categorizeUsefulRunError(nonGeneric) ?? nonGeneric.at(-1) ?? normalizeString(projection.record.errorText);
65
+ }
66
+ var init_diagnostics = () => {};
67
+
68
+ // packages/run-worker/src/runs/projection.ts
69
+ var exports_projection = {};
70
+ __export(exports_projection, {
71
+ selectRunProjection: () => selectRunProjection,
72
+ runRecordsFromRegistrySnapshot: () => runRecordsFromRegistrySnapshot,
73
+ runRecordFromRegistryEntry: () => runRecordFromRegistryEntry,
74
+ resolveRunJoinTarget: () => resolveRunJoinTarget,
75
+ resolveJoinTarget: () => resolveJoinTarget,
76
+ readSessionRunEntries: () => readSessionRunEntries,
77
+ listRuns: () => listRuns,
78
+ listRunProjections: () => listRunProjections,
79
+ getRunProjection: () => getRunProjection,
80
+ getRun: () => getRun,
81
+ discoveryDiagnosticRunRecord: () => discoveryDiagnosticRunRecord
82
+ });
83
+ import { existsSync, readFileSync } from "fs";
84
+ import { isAbsolute, relative, resolve } from "path";
85
+ import { Duration, Effect, Option, Stream } from "effect";
86
+ import {
87
+ foldRunSessionEntries,
88
+ isTerminalRunStatus,
89
+ timelineEntriesFromCustomEntries
90
+ } from "@rig/contracts";
91
+ import { registrySnapshotStream } from "@rig/runtime/control-plane/discovery";
92
+ function readSessionRunEntries(sessionPath) {
93
+ if (!sessionPath || !existsSync(sessionPath))
94
+ return [];
95
+ try {
96
+ return parseSessionRunEntries(readFileSync(sessionPath, "utf8"));
97
+ } catch {
98
+ return [];
99
+ }
100
+ }
101
+ function parseSessionRunEntries(raw) {
102
+ const entries = [];
103
+ for (const line of raw.split(`
104
+ `)) {
105
+ if (!line.trim())
106
+ continue;
107
+ try {
108
+ const parsed = JSON.parse(line);
109
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
110
+ continue;
111
+ entries.push({
112
+ type: "type" in parsed && typeof parsed.type === "string" ? parsed.type : "",
113
+ ..."customType" in parsed && typeof parsed.customType === "string" ? { customType: parsed.customType } : {},
114
+ ..."data" in parsed ? { data: parsed.data } : {}
115
+ });
116
+ } catch {
117
+ continue;
118
+ }
119
+ }
120
+ return entries;
121
+ }
122
+ function stringOrNull(value) {
123
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
124
+ }
125
+ function numberOrNull(value) {
126
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
127
+ }
128
+ function objectRecord(value) {
129
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
130
+ }
131
+ function registryStatusAsRunStatus(status) {
132
+ if (status === "waiting-input")
133
+ return "waiting-user-input";
134
+ if (status === "starting")
135
+ return "preparing";
136
+ return typeof status === "string" && [
137
+ "created",
138
+ "queued",
139
+ "preparing",
140
+ "running",
141
+ "waiting-approval",
142
+ "waiting-user-input",
143
+ "paused",
144
+ "validating",
145
+ "reviewing",
146
+ "closing-out",
147
+ "needs-attention",
148
+ "completed",
149
+ "failed",
150
+ "stopped"
151
+ ].includes(status) ? status : null;
152
+ }
153
+ function payloadString(payload, keys) {
154
+ if (!payload || typeof payload !== "object")
155
+ return null;
156
+ const record = payload;
157
+ for (const key of keys) {
158
+ const value = record[key];
159
+ if (typeof value === "string" && value.trim())
160
+ return value.trim();
161
+ }
162
+ return null;
163
+ }
164
+ function payloadOptions(payload) {
165
+ if (!payload || typeof payload !== "object")
166
+ return;
167
+ const record = payload;
168
+ const options = Array.isArray(record.options) ? record.options : Array.isArray(record.choices) ? record.choices : null;
169
+ const values = options?.filter((value) => typeof value === "string" && value.trim().length > 0) ?? [];
170
+ return values.length > 0 ? values : undefined;
171
+ }
172
+ function inboxRequest(request, kind) {
173
+ const fallback = kind === "approval" ? "Approval requested" : "Input requested";
174
+ return {
175
+ requestId: request.requestId,
176
+ kind,
177
+ title: payloadString(request.payload, ["title", "message", "reason", "prompt", "summary"]) ?? fallback,
178
+ body: payloadString(request.payload, ["body", "description", "detail", "details"]),
179
+ ...payloadOptions(request.payload) ? { options: payloadOptions(request.payload) } : {},
180
+ requestedAt: request.requestedAt ?? null,
181
+ source: "run"
182
+ };
183
+ }
184
+ function inboxFromProjection(projection) {
185
+ return [
186
+ ...projection.pendingApprovals.map((request) => inboxRequest(request, "approval")),
187
+ ...projection.pendingUserInputs.map((request) => inboxRequest(request, "input"))
188
+ ].sort((a, b) => (Date.parse(a.requestedAt ?? "") || 0) - (Date.parse(b.requestedAt ?? "") || 0));
189
+ }
190
+ function isProjectPath(projectRoot, cwd) {
191
+ const root = resolve(projectRoot);
192
+ const candidate = resolve(cwd);
193
+ const pathFromRoot = relative(root, candidate);
194
+ return pathFromRoot === "" || !pathFromRoot.startsWith("../") && pathFromRoot !== ".." && !isAbsolute(pathFromRoot);
195
+ }
196
+ function sourceFromEntry(projectRoot, projection, entry) {
197
+ const candidates = [
198
+ stringOrNull(projection.collabCwd),
199
+ stringOrNull(projection.cwd),
200
+ stringOrNull(entry.cwd),
201
+ stringOrNull(projection.worktreePath)
202
+ ].filter((cwd) => cwd !== null);
203
+ return candidates.some((cwd) => isProjectPath(projectRoot, cwd)) ? "local" : "remote";
204
+ }
205
+ function pendingRequests(value, fallbackKind) {
206
+ if (!Array.isArray(value))
207
+ return [];
208
+ return value.flatMap((item) => {
209
+ const record = objectRecord(item);
210
+ const requestId = stringOrNull(record?.requestId) ?? stringOrNull(record?.id);
211
+ if (!record || !requestId)
212
+ return [];
213
+ return [{
214
+ requestId,
215
+ requestKind: stringOrNull(record.requestKind) ?? stringOrNull(record.kind) ?? fallbackKind,
216
+ actionId: stringOrNull(record.actionId),
217
+ payload: "payload" in record ? record.payload : record,
218
+ requestedAt: stringOrNull(record.requestedAt) ?? stringOrNull(record.at) ?? ""
219
+ }];
220
+ });
221
+ }
222
+ function emptyFoldedProjection(runId, projection) {
223
+ const projectionRecord = projection;
224
+ const nestedProjection = objectRecord(projectionRecord.projection);
225
+ const pendingApprovals = pendingRequests(nestedProjection?.pendingApprovals ?? projectionRecord.pendingApprovals, "approval");
226
+ const pendingUserInputs = pendingRequests(nestedProjection?.pendingUserInputs ?? nestedProjection?.pendingInputs ?? projectionRecord.pendingUserInputs ?? (Array.isArray(projectionRecord.pendingInputs) ? projectionRecord.pendingInputs : undefined), "user-input");
227
+ const nestedRecord = objectRecord(nestedProjection?.record);
228
+ const nestedFolded = nestedProjection;
229
+ return {
230
+ ...EMPTY_PROJECTION,
231
+ ...nestedFolded ?? {},
232
+ record: {
233
+ ...nestedRecord ?? {},
234
+ runId,
235
+ ...projection.taskId ? { taskId: projection.taskId } : {},
236
+ ...projection.title ? { title: projection.title } : {},
237
+ ...projection.startedAt ? { startedAt: projection.startedAt } : {},
238
+ ...projection.updatedAt ? { updatedAt: projection.updatedAt } : {},
239
+ ...projection.completedAt ? { completedAt: projection.completedAt } : {},
240
+ ...projection.sessionPath ? { sessionPath: projection.sessionPath } : {},
241
+ ...projection.worktreePath ? { worktreePath: projection.worktreePath } : {},
242
+ ...projection.prUrl ? { prUrl: projection.prUrl } : {}
243
+ },
244
+ status: registryStatusAsRunStatus(projection.status) ?? registryStatusAsRunStatus(nestedProjection?.status),
245
+ pendingApprovals,
246
+ pendingUserInputs,
247
+ steeringCount: projection.steeringCount ?? numberOrNull(nestedProjection?.steeringCount) ?? 0,
248
+ stallCount: projection.stallCount ?? numberOrNull(nestedProjection?.stallCount) ?? 0,
249
+ lastEventAt: projection.updatedAt ?? stringOrNull(nestedProjection?.lastEventAt)
250
+ };
251
+ }
252
+ function runRecordFromRegistryEntry(projectRoot, entry) {
253
+ const projection = entry.projection && typeof entry.projection === "object" ? entry.projection : {};
254
+ const runId = stringOrNull(projection.runId) ?? entry.roomId;
255
+ const folded = emptyFoldedProjection(runId, projection);
256
+ const pushedStatus = registryStatusAsRunStatus(projection.status) ?? folded.status ?? registryStatusAsRunStatus(entry.status);
257
+ const status = entry.stale ? pushedStatus && isTerminalRunStatus(pushedStatus) ? pushedStatus : "stale" : pushedStatus ?? "running";
258
+ const sessionPath = stringOrNull(projection.sessionPath) ?? stringOrNull(entry.sessionPath) ?? null;
259
+ const collabCwd = stringOrNull(projection.collabCwd) ?? stringOrNull(projection.cwd) ?? stringOrNull(entry.cwd) ?? stringOrNull(projection.worktreePath);
260
+ return {
261
+ runId,
262
+ taskId: stringOrNull(projection.taskId),
263
+ title: stringOrNull(projection.title) ?? entry.title,
264
+ status,
265
+ source: sourceFromEntry(projectRoot, projection, entry),
266
+ live: !entry.stale,
267
+ stale: entry.stale,
268
+ startedAt: stringOrNull(projection.startedAt) ?? entry.startedAt ?? null,
269
+ updatedAt: stringOrNull(projection.updatedAt) ?? entry.heartbeatAt ?? null,
270
+ completedAt: stringOrNull(projection.completedAt),
271
+ joinLink: stringOrNull(projection.joinLink) ?? entry.joinLink ?? null,
272
+ webLink: stringOrNull(projection.webLink) ?? entry.webLink ?? null,
273
+ relayUrl: stringOrNull(projection.relayUrl) ?? entry.relayUrl ?? null,
274
+ sessionPath,
275
+ prUrl: stringOrNull(projection.prUrl),
276
+ worktreePath: stringOrNull(projection.worktreePath) ?? collabCwd,
277
+ pendingApprovals: numberOrNull(projection.pendingApprovals) ?? folded.pendingApprovals.length,
278
+ pendingInputs: numberOrNull(projection.pendingInputs) ?? folded.pendingUserInputs.length,
279
+ steeringCount: projection.steeringCount ?? 0,
280
+ stallCount: projection.stallCount ?? 0,
281
+ errorSummary: stringOrNull(projection.errorSummary) ?? summarizeRunError(folded),
282
+ timeline: Array.isArray(projection.timeline) ? [...projection.timeline] : [...timelineEntriesFromCustomEntries([])],
283
+ inbox: inboxFromProjection(folded),
284
+ collabCwd: collabCwd ?? null,
285
+ projection: folded
286
+ };
287
+ }
288
+ function runRecordsFromRegistrySnapshot(projectRoot, snapshot) {
289
+ return sortByRecency(snapshot.entries.map((entry) => runRecordFromRegistryEntry(projectRoot, entry)).filter((record) => record !== null));
290
+ }
291
+ function sortByRecency(records) {
292
+ return [...records].sort((a, b) => {
293
+ const at = Date.parse(b.updatedAt ?? b.startedAt ?? "") || 0;
294
+ const bt = Date.parse(a.updatedAt ?? a.startedAt ?? "") || 0;
295
+ return at - bt;
296
+ });
297
+ }
298
+ function discoveryDiagnosticRunRecord(projectRoot, error) {
299
+ const detail = error instanceof Error ? error.message : String(error);
300
+ const runId = DISCOVERY_DIAGNOSTIC_RUN_ID;
301
+ const projection = {
302
+ ...EMPTY_PROJECTION,
303
+ record: { runId, title: "Registry discovery unavailable" },
304
+ status: "needs-attention",
305
+ stallCount: 1
306
+ };
307
+ return {
308
+ runId,
309
+ taskId: null,
310
+ title: "Registry discovery unavailable",
311
+ status: "needs-attention",
312
+ source: "remote",
313
+ live: false,
314
+ stale: true,
315
+ startedAt: null,
316
+ updatedAt: null,
317
+ completedAt: null,
318
+ joinLink: null,
319
+ webLink: null,
320
+ relayUrl: null,
321
+ sessionPath: null,
322
+ prUrl: null,
323
+ worktreePath: null,
324
+ pendingApprovals: 0,
325
+ pendingInputs: 0,
326
+ steeringCount: 0,
327
+ stallCount: 1,
328
+ errorSummary: `registry discovery unavailable: ${detail}`,
329
+ timeline: [],
330
+ inbox: [],
331
+ collabCwd: null,
332
+ projection
333
+ };
334
+ }
335
+ async function listRunProjections(projectRoot, filter = {}) {
336
+ try {
337
+ const snapshot = await Effect.runPromise(registrySnapshotStream(projectRoot, filter).pipe(Stream.runHead, Effect.timeout(Duration.seconds(15)), Effect.map(Option.getOrNull)));
338
+ return snapshot ? runRecordsFromRegistrySnapshot(projectRoot, snapshot) : [discoveryDiagnosticRunRecord(projectRoot, "registry discovery stream ended without a snapshot")];
339
+ } catch (error) {
340
+ return [discoveryDiagnosticRunRecord(projectRoot, error)];
341
+ }
342
+ }
343
+ function selectRunProjection(runs, runId) {
344
+ const exactRun = runs.find((run) => run.runId === runId);
345
+ if (exactRun)
346
+ return exactRun;
347
+ const exactTask = runs.find((run) => run.taskId === runId);
348
+ if (exactTask)
349
+ return exactTask;
350
+ const prefixMatches = runs.filter((run) => run.runId.startsWith(runId));
351
+ if (prefixMatches.length === 1)
352
+ return prefixMatches[0] ?? null;
353
+ if (prefixMatches.length > 1) {
354
+ const matches = prefixMatches.map((run) => run.runId).join(", ");
355
+ throw new Error(`Ambiguous run id prefix "${runId}" matched ${prefixMatches.length} runs: ${matches}`);
356
+ }
357
+ return runs.find((run) => run.runId === DISCOVERY_DIAGNOSTIC_RUN_ID) ?? null;
358
+ }
359
+ async function getRunProjection(projectRoot, runId, filter = {}) {
360
+ const runs = await listRunProjections(projectRoot, filter);
361
+ return selectRunProjection(runs, runId);
362
+ }
363
+ async function resolveRunJoinTarget(projectRoot, runId, filter = {}) {
364
+ const run = await getRunProjection(projectRoot, runId, filter);
365
+ if (!run || !run.joinLink)
366
+ return null;
367
+ return { runId: run.runId, taskId: run.taskId, joinLink: run.joinLink, cwd: run.collabCwd ?? run.sessionPath, stale: run.stale };
368
+ }
369
+ var EMPTY_PROJECTION, DISCOVERY_DIAGNOSTIC_RUN_ID = "__registry_discovery_error__", listRuns, getRun, resolveJoinTarget;
370
+ var init_projection = __esm(() => {
371
+ init_diagnostics();
372
+ EMPTY_PROJECTION = foldRunSessionEntries([], "");
373
+ listRuns = listRunProjections;
374
+ getRun = getRunProjection;
375
+ resolveJoinTarget = resolveRunJoinTarget;
376
+ });
377
+
378
+ // packages/run-worker/src/runs/control.ts
379
+ init_projection();
380
+ import { buildPauseSentinel, buildResumeSentinel, buildStopSentinel } from "@rig/contracts";
381
+ async function loadCollabControlDeps() {
382
+ const [{ importRoomKey, seal }, { COLLAB_PROTO, packEnvelope, parseCollabLink }] = await Promise.all([
383
+ import("@oh-my-pi/pi-coding-agent/collab/crypto"),
384
+ import("@oh-my-pi/pi-coding-agent/collab/protocol")
385
+ ]);
386
+ return { importRoomKey, seal, COLLAB_PROTO, packEnvelope, parseCollabLink };
387
+ }
388
+ function collabControlFrames(runId, control) {
389
+ switch (control.kind) {
390
+ case "steer":
391
+ return [{ t: "prompt", text: control.message }];
392
+ case "resume":
393
+ return [{ t: "prompt", text: `${buildResumeSentinel(runId)}
394
+ Continue the run from where it paused.` }];
395
+ case "pause":
396
+ return [
397
+ { t: "prompt", text: `${buildPauseSentinel(runId)}
398
+ Pause this run after the current interruption settles.` },
399
+ { t: "abort" }
400
+ ];
401
+ case "stop":
402
+ return [
403
+ { t: "prompt", text: `${buildStopSentinel(runId, control.reason)}
404
+ Stop this run and do not continue after the interruption settles.` },
405
+ { t: "abort" }
406
+ ];
407
+ }
408
+ }
409
+ function collabControlFrame(runId, control) {
410
+ return collabControlFrames(runId, control)[0];
411
+ }
412
+ async function sendSealedCollabFrames(joinLink, frames, deps = {}) {
413
+ const { importRoomKey, seal, COLLAB_PROTO, packEnvelope, parseCollabLink } = await loadCollabControlDeps();
414
+ const parsed = parseCollabLink(joinLink);
415
+ if ("error" in parsed)
416
+ throw new Error(parsed.error);
417
+ if (!parsed.writeToken)
418
+ throw new Error("Run collab link is read-only; cannot send control.");
419
+ const key = await importRoomKey(parsed.key);
420
+ const WebSocketCtor = deps.WebSocket ?? WebSocket;
421
+ const ws = new WebSocketCtor(`${parsed.wsUrl}?role=guest`);
422
+ await new Promise((resolveOpen, rejectOpen) => {
423
+ ws.addEventListener("open", () => resolveOpen(), { once: true });
424
+ ws.addEventListener("error", () => rejectOpen(new Error("collab websocket error")), { once: true });
425
+ });
426
+ const hello = {
427
+ t: "hello",
428
+ proto: COLLAB_PROTO,
429
+ name: "rig-operator",
430
+ writeToken: Buffer.from(parsed.writeToken).toString("base64url")
431
+ };
432
+ ws.send(packEnvelope(0, await seal(key, hello)));
433
+ for (const frame of frames)
434
+ ws.send(packEnvelope(0, await seal(key, frame)));
435
+ try {
436
+ ws.close();
437
+ } catch {}
438
+ }
439
+ async function deliverRemoteRunControl(projectRoot, target, control, deps = {}) {
440
+ const record = typeof target === "string" ? await getRun(projectRoot, target) : target;
441
+ const runId = typeof target === "string" ? target : target.runId;
442
+ if (!record)
443
+ throw new Error(`Run not found: ${runId}`);
444
+ if (!record.joinLink)
445
+ throw new Error(`Run ${record.runId} has no writable collab join link.`);
446
+ await sendSealedCollabFrames(record.joinLink, collabControlFrames(record.runId, control), deps);
447
+ }
448
+ async function deliverRunControl(projectRoot, target, control, deps = {}) {
449
+ const record = typeof target === "string" ? await (deps.getRun ?? getRun)(projectRoot, target) : target;
450
+ const runId = typeof target === "string" ? target : target.runId;
451
+ if (!record)
452
+ throw new Error(`Run not found: ${runId}`);
453
+ if (!record.joinLink)
454
+ throw new Error(`Run ${record.runId} has no writable collab join link; attach interactively to ${control.kind}.`);
455
+ try {
456
+ await (deps.deliverRemote ?? deliverRemoteRunControl)(projectRoot, record, control);
457
+ } catch (error) {
458
+ const detail = error instanceof Error ? error.message : `Attach to ${control.kind} interactively: rig run attach ${record.runId}`;
459
+ throw new Error(`Could not ${control.kind} run ${record.runId}. ${detail}`);
460
+ }
461
+ }
462
+ // packages/run-worker/src/runs/guard.ts
463
+ import { TERMINAL_RUN_STATUSES } from "@rig/contracts";
464
+ var TERMINAL = new Set(TERMINAL_RUN_STATUSES);
465
+ function runBlocksNewRunForTask(run) {
466
+ return run.live && !run.stale && !TERMINAL.has(run.status) && run.status !== "needs-attention" && run.status !== "needs_attention";
467
+ }
468
+ async function activeRunByTaskId(listRuns2, projectRoot) {
469
+ const active = new Map;
470
+ for (const run of await listRuns2(projectRoot)) {
471
+ if (run.taskId && runBlocksNewRunForTask(run) && !active.has(run.taskId))
472
+ active.set(run.taskId, run.runId);
473
+ }
474
+ return active;
475
+ }
476
+ async function assertNoActiveRunForTask(listRuns2, projectRoot, taskId) {
477
+ const existing = (await activeRunByTaskId(listRuns2, projectRoot)).get(taskId);
478
+ if (existing) {
479
+ throw new Error(`Task ${taskId} already has an active run: ${existing}. Attach instead: rig run attach ${existing} \u2014 or re-dispatch anyway with --force.`);
480
+ }
481
+ }
482
+ // packages/run-worker/src/runs/inbox.ts
483
+ import { buildInboxResolutionSentinel } from "@rig/contracts";
484
+ init_projection();
485
+ function promptFromPayload(payload, fallback) {
486
+ if (payload && typeof payload === "object") {
487
+ const record = payload;
488
+ for (const key of ["title", "message", "reason", "prompt", "summary"]) {
489
+ const value = record[key];
490
+ if (typeof value === "string" && value.trim().length > 0)
491
+ return value.trim();
492
+ }
493
+ }
494
+ return fallback;
495
+ }
496
+ function recordsFromRun(run, kind) {
497
+ const pending = kind === "approvals" ? run.projection.pendingApprovals : run.projection.pendingUserInputs;
498
+ return pending.map((request) => ({
499
+ runId: run.runId,
500
+ taskId: run.taskId,
501
+ requestId: request.requestId,
502
+ status: "pending",
503
+ prompt: promptFromPayload(request.payload, kind === "approvals" ? "Approval requested" : "Input requested"),
504
+ requestedAt: request.requestedAt,
505
+ payload: request.payload,
506
+ kind: kind === "approvals" ? "approval" : "input"
507
+ }));
508
+ }
509
+ async function listInboxRecords(context, kind, filters = {}, deps = {}) {
510
+ const projectRoot = typeof context === "string" ? context : context.projectRoot;
511
+ const runs = await (deps.listRuns ?? listRuns)(projectRoot);
512
+ const out = [];
513
+ for (const run of runs) {
514
+ if (filters.run && run.runId !== filters.run)
515
+ continue;
516
+ if (filters.task && run.taskId !== filters.task)
517
+ continue;
518
+ out.push(...recordsFromRun(run, kind));
519
+ }
520
+ return out;
521
+ }
522
+ async function listInbox(projectRoot, filters = {}, deps = {}) {
523
+ const runs = await (deps.listRuns ?? listRuns)(projectRoot);
524
+ const out = [];
525
+ for (const run of runs) {
526
+ if (filters.run && run.runId !== filters.run)
527
+ continue;
528
+ if (filters.task && run.taskId !== filters.task)
529
+ continue;
530
+ for (const request of run.inbox ?? []) {
531
+ if (request.source !== "run")
532
+ continue;
533
+ out.push(request);
534
+ }
535
+ }
536
+ return out;
537
+ }
538
+ async function readPendingInboxCounts(context, deps = {}) {
539
+ try {
540
+ const projectRoot = typeof context === "string" ? context : context.projectRoot;
541
+ const [approvals, inputs] = await Promise.all([
542
+ listInboxRecords(projectRoot, "approvals", {}, deps),
543
+ listInboxRecords(projectRoot, "inputs", {}, deps)
544
+ ]);
545
+ return { approvals: approvals.length, inputs: inputs.length };
546
+ } catch {
547
+ return null;
548
+ }
549
+ }
550
+ var readInboxCounts = readPendingInboxCounts;
551
+ function normalizedApprovalDecision(decision) {
552
+ return decision === "approved" || decision === "approve" ? "approve" : "reject";
553
+ }
554
+ function inputAnswers(answer) {
555
+ return typeof answer === "string" ? { answer } : answer;
556
+ }
557
+ function decisionText(runId, requestId, decision) {
558
+ if (decision.kind === "approval") {
559
+ const normalized = normalizedApprovalDecision(decision.decision);
560
+ const label = normalized === "approve" ? "approved" : "rejected";
561
+ return [
562
+ buildInboxResolutionSentinel(runId, { kind: "approval", requestId, decision: normalized, note: decision.note ?? null }),
563
+ `Rig inbox approval ${requestId} was ${label}.`,
564
+ decision.note ? `Operator note: ${decision.note}` : null,
565
+ "Continue using this approval decision."
566
+ ].filter((line) => Boolean(line)).join(`
567
+ `);
568
+ }
569
+ const answers = inputAnswers(decision.answer);
570
+ return [
571
+ buildInboxResolutionSentinel(runId, { kind: "input", requestId, answers }),
572
+ `Rig inbox input ${requestId} was answered with:`,
573
+ JSON.stringify(answers),
574
+ "Continue using this input answer."
575
+ ].join(`
576
+ `);
577
+ }
578
+ async function resolveInboxRequest(projectRoot, runId, requestId, decision, deps = {}) {
579
+ await (deps.deliverRunControl ?? deliverRunControl)(projectRoot, runId, { kind: "steer", message: decisionText(runId, requestId, decision) });
580
+ }
581
+ // packages/run-worker/src/runs/inspect.ts
582
+ init_projection();
583
+ init_diagnostics();
584
+ import { RIG_RUN_LOG_ENTRY } from "@rig/contracts";
585
+ function asRecord(value) {
586
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
587
+ }
588
+ function firstString(record, keys) {
589
+ for (const key of keys) {
590
+ const value = record[key];
591
+ if (typeof value === "string" && value.trim().length > 0)
592
+ return value;
593
+ }
594
+ return null;
595
+ }
596
+ function stringifyLogPayload(value) {
597
+ if (typeof value === "string")
598
+ return value;
599
+ if (typeof value === "number" || typeof value === "boolean")
600
+ return String(value);
601
+ const record = asRecord(value);
602
+ if (!record)
603
+ return null;
604
+ const direct = firstString(record, ["line", "message", "text", "content", "output", "summary", "detail"]);
605
+ if (direct)
606
+ return direct;
607
+ try {
608
+ return JSON.stringify(record);
609
+ } catch {
610
+ return String(record);
611
+ }
612
+ }
613
+ function logLineFromValue(value) {
614
+ const record = asRecord(value);
615
+ if (!record)
616
+ return stringifyLogPayload(value);
617
+ const direct = firstString(record, ["line", "message", "text", "content", "output", "summary", "detail"]);
618
+ if (direct)
619
+ return direct;
620
+ if ("payload" in record)
621
+ return stringifyLogPayload(record.payload);
622
+ if ("data" in record)
623
+ return stringifyLogPayload(record.data);
624
+ return stringifyLogPayload(record);
625
+ }
626
+ function logLineFromSessionEntry(entry) {
627
+ if (entry.type !== "custom" || entry.customType !== RIG_RUN_LOG_ENTRY)
628
+ return null;
629
+ return logLineFromValue(entry.data);
630
+ }
631
+ function logLinesFromProjection(projection) {
632
+ const projected = projection;
633
+ const lines = [];
634
+ for (const key of ["logs", "logEntries", "journalLogs", "runLogs"]) {
635
+ const entries = projected[key];
636
+ if (!Array.isArray(entries))
637
+ continue;
638
+ for (const entry of entries) {
639
+ const line = logLineFromValue(entry);
640
+ if (line !== null)
641
+ lines.push(line);
642
+ }
643
+ }
644
+ return lines;
645
+ }
646
+ function extractRunLogs(run, deps = {}) {
647
+ const projectedLines = logLinesFromProjection(run.projection);
648
+ if (projectedLines.length > 0)
649
+ return projectedLines;
650
+ return (deps.readSessionRunEntries ?? readSessionRunEntries)(run.sessionPath).map(logLineFromSessionEntry).filter((line) => line !== null);
651
+ }
652
+ function summarizeRunFailures(run) {
653
+ const failures = [];
654
+ const useful = summarizeRunError(run.projection);
655
+ if (useful)
656
+ failures.push(`${run.runId}: ${useful}`);
657
+ if (run.status === "failed" || run.projection.status === "failed")
658
+ failures.push(`${run.runId}: run status failed`);
659
+ for (const phase of run.projection.closeoutPhases) {
660
+ if (phase.outcome === "failed")
661
+ failures.push(`${run.runId}: closeout ${phase.phase} failed${phase.detail ? ` \u2014 ${phase.detail}` : ""}`);
662
+ }
663
+ for (const anomaly of run.projection.anomalies) {
664
+ failures.push(`${run.runId}: anomaly ${anomaly.kind}${anomaly.detail ? ` \u2014 ${anomaly.detail}` : ""}`);
665
+ }
666
+ return failures;
667
+ }
668
+ var summarizeProjectionFailures = summarizeRunFailures;
669
+ async function runsForTask(projectRoot, taskId, deps = {}) {
670
+ const list = deps.listRuns ?? listRuns;
671
+ try {
672
+ const runs = await list(projectRoot);
673
+ const filtered = runs.filter((run2) => run2.taskId === taskId || run2.runId === taskId);
674
+ if (filtered.length > 0)
675
+ return [...filtered];
676
+ } catch {}
677
+ const run = await (deps.getRun ?? getRun)(projectRoot, taskId);
678
+ return run ? [run] : [];
679
+ }
680
+ function runInspectSummaryRows(runs, options = {}) {
681
+ const attachable = runs.filter((run) => Boolean(run.joinLink && !run.stale)).length;
682
+ const pendingInbox = options.pendingInbox ?? runs.reduce((total, run) => total + run.pendingApprovals + run.pendingInputs, 0);
683
+ return [
684
+ { id: "title", label: "Inspect", currentValue: "runtime", heading: true, description: "session/runtime inspection rows from @rig/client" },
685
+ { id: "inspect:sessions", label: "RUNS", currentValue: String(runs.length), heading: true, description: `${attachable} attachable OMP collab links` },
686
+ { id: "inspect:cwd", label: "PROJECT ROOT", currentValue: options.projectRoot ?? "", heading: true, description: "selected target/project root used by Rig chrome" },
687
+ { id: "inspect:inbox", label: "INBOX", currentValue: String(pendingInbox), values: ["open"], description: "pending run gates; open Inbox to resolve" },
688
+ { id: "inspect:runs", label: "RUNS", currentValue: String(runs.length), values: ["open"], description: "open Runs to inspect individual run detail, logs, and attach controls" },
689
+ { id: "inspect:audit", label: "AUDIT", currentValue: "unavailable", heading: true, description: "CLI inspect audit has no cockpit equivalent; use rig inspect audit" }
690
+ ];
691
+ }
692
+ // packages/run-worker/src/runs/run-status.ts
693
+ import {
694
+ ACTIVE_RUN_STATUSES,
695
+ TERMINAL_RUN_STATUSES as TERMINAL_RUN_STATUSES2,
696
+ isActiveRunStatus,
697
+ isTerminalRunStatus as isTerminalRunStatus2,
698
+ normalizeRunStatusToken
699
+ } from "@rig/contracts";
700
+ var KNOWN_RUN_STATUS = Object.fromEntries([...ACTIVE_RUN_STATUSES, ...TERMINAL_RUN_STATUSES2].map((status) => [status, true]));
701
+ function canonicalStatusToken(status) {
702
+ const normalized = normalizeRunStatusToken(status);
703
+ if (normalized === "waiting-input")
704
+ return "waiting-user-input";
705
+ return normalized;
706
+ }
707
+ function asRunStatus(status) {
708
+ return KNOWN_RUN_STATUS[status] ? status : null;
709
+ }
710
+ function statusColorRole(status) {
711
+ switch (canonicalStatusToken(status)) {
712
+ case "done":
713
+ case "completed":
714
+ case "ready":
715
+ case "healthy":
716
+ case "approved":
717
+ case "merged":
718
+ return "success";
719
+ case "needs-attention":
720
+ case "needs_attention":
721
+ case "waiting-approval":
722
+ case "waiting-user-input":
723
+ case "waiting-input":
724
+ case "waiting_input":
725
+ case "blocked":
726
+ case "paused":
727
+ return "action-yellow";
728
+ case "running":
729
+ case "adopted":
730
+ case "preparing":
731
+ case "created":
732
+ case "queued":
733
+ case "starting":
734
+ case "pending":
735
+ case "in_progress":
736
+ case "in-progress":
737
+ case "active":
738
+ case "booting":
739
+ case "validating":
740
+ case "reviewing":
741
+ case "closing-out":
742
+ case "closing_out":
743
+ return "active-cyan";
744
+ case "failed":
745
+ case "error":
746
+ case "rejected":
747
+ return "failure";
748
+ case "stopped":
749
+ case "cancelled":
750
+ case "canceled":
751
+ case "stale":
752
+ return "muted";
753
+ default:
754
+ return "neutral";
755
+ }
756
+ }
757
+ function runStatusColorRole(run) {
758
+ const classification = classifyRun(run);
759
+ return classification.isNeedsAttention && !classification.isTerminal ? "action-yellow" : statusColorRole(classification.status);
760
+ }
761
+ function isSteerableStatus(status) {
762
+ switch (status) {
763
+ case "needs-attention":
764
+ case "waiting-approval":
765
+ case "waiting-user-input":
766
+ case "paused":
767
+ return false;
768
+ default: {
769
+ const runStatus = asRunStatus(status);
770
+ return runStatus ? isActiveRunStatus(runStatus) : false;
771
+ }
772
+ }
773
+ }
774
+ function isNeedsAttention(run) {
775
+ return canonicalStatusToken(run.status) === "needs-attention" || run.pendingApprovals + run.pendingInputs > 0 || run.stallCount > 0;
776
+ }
777
+ function phaseForStatus(status, runStatus, needsAttention) {
778
+ if (runStatus && isTerminalRunStatus2(runStatus))
779
+ return runStatus === "completed" || runStatus === "failed" || runStatus === "stopped" ? runStatus : "stopped";
780
+ if (needsAttention)
781
+ return "needs-attention";
782
+ switch (status) {
783
+ case "created":
784
+ case "queued":
785
+ case "preparing":
786
+ case "starting":
787
+ case "booting":
788
+ return "starting";
789
+ case "waiting-approval":
790
+ case "waiting-user-input":
791
+ return "waiting";
792
+ case "paused":
793
+ return "paused";
794
+ case "running":
795
+ case "validating":
796
+ case "reviewing":
797
+ case "closing-out":
798
+ return "active";
799
+ default:
800
+ return runStatus && isActiveRunStatus(runStatus) ? "active" : "unknown";
801
+ }
802
+ }
803
+ function classifyRun(run) {
804
+ const status = canonicalStatusToken(run.status) || (run.live && !run.stale ? "starting" : "unknown");
805
+ const runStatus = asRunStatus(status);
806
+ const isTerminal = runStatus ? isTerminalRunStatus2(runStatus) : false;
807
+ const isNeedsAttentionValue = isNeedsAttention(run);
808
+ const phase = phaseForStatus(status, runStatus, isNeedsAttentionValue);
809
+ return {
810
+ status,
811
+ phase,
812
+ isActive: runStatus ? isActiveRunStatus(runStatus) : !isTerminal && status !== "unknown",
813
+ isTerminal,
814
+ isNeedsAttention: isNeedsAttentionValue
815
+ };
816
+ }
817
+ function runStatusText(run) {
818
+ return classifyRun(run).status;
819
+ }
820
+ function statusRank(run) {
821
+ const classification = classifyRun(run);
822
+ if (classification.isNeedsAttention)
823
+ return 0;
824
+ switch (classification.phase) {
825
+ case "needs-attention":
826
+ return 0;
827
+ case "active":
828
+ case "waiting":
829
+ case "paused":
830
+ return 1;
831
+ case "starting":
832
+ return 2;
833
+ case "completed":
834
+ return 3;
835
+ case "failed":
836
+ return 4;
837
+ case "stopped":
838
+ return 5;
839
+ case "unknown":
840
+ return 6;
841
+ }
842
+ }
843
+ function canSteer(run) {
844
+ const classification = classifyRun(run);
845
+ if (classification.phase === "active" || classification.phase === "starting")
846
+ return true;
847
+ return classification.isNeedsAttention && isSteerableStatus(classification.status);
848
+ }
849
+ function canStop(run) {
850
+ const classification = classifyRun(run);
851
+ return classification.isActive && !classification.isTerminal;
852
+ }
853
+ function canPause(run) {
854
+ const phase = classifyRun(run).phase;
855
+ return phase === "active" || phase === "starting";
856
+ }
857
+ function canResume(run) {
858
+ return classifyRun(run).phase === "paused";
859
+ }
860
+ // packages/run-worker/src/runs/stats.ts
861
+ function parseTimestamp(value) {
862
+ if (!value)
863
+ return null;
864
+ const parsed = Date.parse(value);
865
+ return Number.isFinite(parsed) ? parsed : null;
866
+ }
867
+ function median(values) {
868
+ if (values.length === 0)
869
+ return null;
870
+ const sorted = [...values].sort((left, right) => left - right);
871
+ const middle = Math.floor(sorted.length / 2);
872
+ return sorted.length % 2 === 1 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
873
+ }
874
+ function rate(part, total) {
875
+ return total === 0 ? null : part / total;
876
+ }
877
+ function completedDuration(run) {
878
+ if (run.status !== "completed")
879
+ return null;
880
+ const startedAt = parseTimestamp(run.startedAt);
881
+ const completedAt = parseTimestamp(run.completedAt);
882
+ if (startedAt === null || completedAt === null || completedAt < startedAt)
883
+ return null;
884
+ return completedAt - startedAt;
885
+ }
886
+ async function computeStats(projectRootOrRuns, options = {}) {
887
+ const sinceMs = options.since ? options.since.getTime() : null;
888
+ const allRuns = typeof projectRootOrRuns === "string" ? await (options.listRuns ?? (await Promise.resolve().then(() => (init_projection(), exports_projection))).listRuns)(projectRootOrRuns) : projectRootOrRuns;
889
+ const runs = allRuns.filter((run) => {
890
+ if (sinceMs === null)
891
+ return true;
892
+ const startedAt = parseTimestamp(run.startedAt);
893
+ return startedAt !== null && startedAt >= sinceMs;
894
+ });
895
+ const statusCounts = {};
896
+ const completionDurations = [];
897
+ let completedRuns = 0;
898
+ let failedRuns = 0;
899
+ let needsAttentionRuns = 0;
900
+ let steeringTotal = 0;
901
+ let stallTotal = 0;
902
+ let approvalsPending = 0;
903
+ for (const run of runs) {
904
+ const status = run.status || "unknown";
905
+ statusCounts[status] = (statusCounts[status] ?? 0) + 1;
906
+ if (status === "completed")
907
+ completedRuns += 1;
908
+ if (status === "failed")
909
+ failedRuns += 1;
910
+ if (isNeedsAttention(run))
911
+ needsAttentionRuns += 1;
912
+ const duration = completedDuration(run);
913
+ if (duration !== null)
914
+ completionDurations.push(duration);
915
+ steeringTotal += run.steeringCount;
916
+ stallTotal += run.stallCount;
917
+ approvalsPending += run.pendingApprovals;
918
+ }
919
+ const totalRuns = runs.length;
920
+ return {
921
+ since: options.since ? options.since.toISOString() : null,
922
+ totalRuns,
923
+ statusCounts,
924
+ completedRuns,
925
+ failedRuns,
926
+ needsAttentionRuns,
927
+ completionRate: rate(completedRuns, totalRuns),
928
+ failureRate: rate(failedRuns, totalRuns),
929
+ needsAttentionRate: rate(needsAttentionRuns, totalRuns),
930
+ medianCompletionMs: median(completionDurations),
931
+ steeringTotal,
932
+ steeringPerRun: totalRuns === 0 ? null : steeringTotal / totalRuns,
933
+ stallTotal,
934
+ approvalsRequested: approvalsPending,
935
+ approvalsApproved: 0,
936
+ approvalsRejected: 0,
937
+ approvalsPending
938
+ };
939
+ }
940
+ var computeRigStats = computeStats;
941
+
942
+ // packages/run-worker/src/runs/index.ts
943
+ init_projection();
944
+ init_diagnostics();
945
+ export {
946
+ summarizeRunFailures,
947
+ summarizeRunError,
948
+ summarizeProjectionFailures,
949
+ stringifyLogPayload,
950
+ statusRank,
951
+ statusColorRole,
952
+ runsForTask,
953
+ runStatusText,
954
+ runStatusColorRole,
955
+ runInspectSummaryRows,
956
+ runBlocksNewRunForTask,
957
+ resolveRunJoinTarget,
958
+ resolveJoinTarget,
959
+ resolveInboxRequest,
960
+ recordsFromRun,
961
+ readSessionRunEntries,
962
+ readPendingInboxCounts,
963
+ readInboxCounts,
964
+ rate,
965
+ parseTimestamp,
966
+ median,
967
+ logLinesFromProjection,
968
+ logLineFromValue,
969
+ logLineFromSessionEntry,
970
+ listRuns,
971
+ listInboxRecords,
972
+ listInbox,
973
+ isNeedsAttention,
974
+ getRun,
975
+ extractRunLogs,
976
+ deliverRunControl,
977
+ deliverRemoteRunControl,
978
+ computeStats,
979
+ computeRigStats,
980
+ completedDuration,
981
+ collabControlFrames,
982
+ collabControlFrame,
983
+ classifyRun,
984
+ canStop,
985
+ canSteer,
986
+ canResume,
987
+ canPause,
988
+ assertNoActiveRunForTask,
989
+ activeRunByTaskId
990
+ };