@h-rig/cli 0.0.6-alpha.89 → 0.0.6-alpha.90
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.
- package/dist/bin/build-rig-binaries.js +8 -40
- package/dist/bin/rig.js +12519 -26675
- package/dist/src/app/board.js +74 -693
- package/dist/src/app/drone-ui.js +1 -1
- package/dist/src/app/theme.js +0 -1
- package/dist/src/commands/_async-ui.js +1 -1
- package/dist/src/commands/_authority-runs.d.ts +1 -1
- package/dist/src/commands/_authority-runs.js +12 -2
- package/dist/src/commands/_cli-format.d.ts +1 -10
- package/dist/src/commands/_cli-format.js +2 -5
- package/dist/src/commands/_connection-state.d.ts +1 -11
- package/dist/src/commands/_connection-state.js +5 -50
- package/dist/src/commands/_doctor-checks.js +40 -501
- package/dist/src/commands/_help-catalog.js +17 -99
- package/dist/src/commands/_json-output.js +0 -4
- package/dist/src/commands/_operator-view.js +54 -575
- package/dist/src/commands/_pi-frontend.d.ts +0 -27
- package/dist/src/commands/_pi-frontend.js +52 -576
- package/dist/src/commands/_preflight.js +66 -553
- package/dist/src/commands/_server-client.d.ts +0 -33
- package/dist/src/commands/_server-client.js +46 -541
- package/dist/src/commands/_snapshot-upload.js +42 -503
- package/dist/src/commands/_spinner.js +1 -1
- package/dist/src/commands/agent.js +12 -2
- package/dist/src/commands/browser.js +1 -1
- package/dist/src/commands/connect.js +15 -626
- package/dist/src/commands/doctor.js +41 -502
- package/dist/src/commands/github.js +51 -584
- package/dist/src/commands/inbox.js +41 -502
- package/dist/src/commands/init.js +74 -561
- package/dist/src/commands/inspect.js +41 -502
- package/dist/src/commands/run.js +54 -578
- package/dist/src/commands/server.js +163 -692
- package/dist/src/commands/setup.js +46 -507
- package/dist/src/commands/stats.js +58 -601
- package/dist/src/commands/task-run-driver.js +58 -509
- package/dist/src/commands/task.js +110 -729
- package/dist/src/commands.js +237 -1112
- package/dist/src/index.js +244 -1123
- package/dist/src/launcher.js +0 -4
- package/package.json +9 -13
- package/dist/src/app-opentui/adapters/command.d.ts +0 -2
- package/dist/src/app-opentui/adapters/command.js +0 -329
- package/dist/src/app-opentui/adapters/common.d.ts +0 -56
- package/dist/src/app-opentui/adapters/common.js +0 -153
- package/dist/src/app-opentui/adapters/doctor.d.ts +0 -9
- package/dist/src/app-opentui/adapters/doctor.js +0 -1217
- package/dist/src/app-opentui/adapters/family.d.ts +0 -62
- package/dist/src/app-opentui/adapters/family.js +0 -14855
- package/dist/src/app-opentui/adapters/fleet.d.ts +0 -14
- package/dist/src/app-opentui/adapters/fleet.js +0 -1335
- package/dist/src/app-opentui/adapters/inbox.d.ts +0 -43
- package/dist/src/app-opentui/adapters/inbox.js +0 -1944
- package/dist/src/app-opentui/adapters/init.d.ts +0 -11
- package/dist/src/app-opentui/adapters/init.js +0 -2818
- package/dist/src/app-opentui/adapters/inspect.d.ts +0 -52
- package/dist/src/app-opentui/adapters/inspect.js +0 -1455
- package/dist/src/app-opentui/adapters/pi-attach.d.ts +0 -32
- package/dist/src/app-opentui/adapters/pi-attach.js +0 -2101
- package/dist/src/app-opentui/adapters/pi.d.ts +0 -23
- package/dist/src/app-opentui/adapters/pi.js +0 -363
- package/dist/src/app-opentui/adapters/plugin.d.ts +0 -84
- package/dist/src/app-opentui/adapters/plugin.js +0 -544
- package/dist/src/app-opentui/adapters/repo.d.ts +0 -37
- package/dist/src/app-opentui/adapters/repo.js +0 -186
- package/dist/src/app-opentui/adapters/run-detail.d.ts +0 -27
- package/dist/src/app-opentui/adapters/run-detail.js +0 -1441
- package/dist/src/app-opentui/adapters/server.d.ts +0 -48
- package/dist/src/app-opentui/adapters/server.js +0 -1561
- package/dist/src/app-opentui/adapters/tasks.d.ts +0 -64
- package/dist/src/app-opentui/adapters/tasks.js +0 -4524
- package/dist/src/app-opentui/adapters/workspace.d.ts +0 -49
- package/dist/src/app-opentui/adapters/workspace.js +0 -333
- package/dist/src/app-opentui/autocomplete.d.ts +0 -20
- package/dist/src/app-opentui/autocomplete.js +0 -578
- package/dist/src/app-opentui/bootstrap.d.ts +0 -11
- package/dist/src/app-opentui/bootstrap.js +0 -27833
- package/dist/src/app-opentui/command-palette.d.ts +0 -3
- package/dist/src/app-opentui/command-palette.js +0 -1038
- package/dist/src/app-opentui/command-pty-host.d.ts +0 -62
- package/dist/src/app-opentui/command-pty-host.js +0 -248
- package/dist/src/app-opentui/drone.d.ts +0 -12
- package/dist/src/app-opentui/drone.js +0 -230
- package/dist/src/app-opentui/events.d.ts +0 -7
- package/dist/src/app-opentui/events.js +0 -28
- package/dist/src/app-opentui/fleet-stats.d.ts +0 -32
- package/dist/src/app-opentui/fleet-stats.js +0 -114
- package/dist/src/app-opentui/focus-manager.d.ts +0 -14
- package/dist/src/app-opentui/focus-manager.js +0 -24
- package/dist/src/app-opentui/index.d.ts +0 -8
- package/dist/src/app-opentui/index.js +0 -5260
- package/dist/src/app-opentui/intent.d.ts +0 -3
- package/dist/src/app-opentui/intent.js +0 -365
- package/dist/src/app-opentui/keymap.d.ts +0 -21
- package/dist/src/app-opentui/keymap.js +0 -1377
- package/dist/src/app-opentui/launch-routing.d.ts +0 -16
- package/dist/src/app-opentui/launch-routing.js +0 -55
- package/dist/src/app-opentui/layout.d.ts +0 -22
- package/dist/src/app-opentui/layout.js +0 -51
- package/dist/src/app-opentui/list-search.d.ts +0 -36
- package/dist/src/app-opentui/list-search.js +0 -130
- package/dist/src/app-opentui/pi-host-child.d.ts +0 -2
- package/dist/src/app-opentui/pi-host-child.js +0 -1299
- package/dist/src/app-opentui/pi-pty-host.d.ts +0 -28
- package/dist/src/app-opentui/pi-pty-host.js +0 -10
- package/dist/src/app-opentui/react/App.d.ts +0 -9
- package/dist/src/app-opentui/react/App.js +0 -3866
- package/dist/src/app-opentui/react/Backdrop.d.ts +0 -5
- package/dist/src/app-opentui/react/Backdrop.js +0 -823
- package/dist/src/app-opentui/react/ChromeHost.d.ts +0 -5
- package/dist/src/app-opentui/react/ChromeHost.js +0 -1539
- package/dist/src/app-opentui/react/SceneFrameView.d.ts +0 -7
- package/dist/src/app-opentui/react/SceneFrameView.js +0 -579
- package/dist/src/app-opentui/react/context.d.ts +0 -17
- package/dist/src/app-opentui/react/context.js +0 -37
- package/dist/src/app-opentui/react/launch.d.ts +0 -2
- package/dist/src/app-opentui/react/launch.js +0 -4897
- package/dist/src/app-opentui/react/nav.d.ts +0 -18
- package/dist/src/app-opentui/react/nav.js +0 -54
- package/dist/src/app-opentui/react/scroll.d.ts +0 -12
- package/dist/src/app-opentui/react/scroll.js +0 -21
- package/dist/src/app-opentui/react/syntax.d.ts +0 -2
- package/dist/src/app-opentui/react/syntax.js +0 -65
- package/dist/src/app-opentui/registry.d.ts +0 -4
- package/dist/src/app-opentui/registry.js +0 -22876
- package/dist/src/app-opentui/remote-link.d.ts +0 -10
- package/dist/src/app-opentui/remote-link.js +0 -47
- package/dist/src/app-opentui/render/ascii-fleet.d.ts +0 -15
- package/dist/src/app-opentui/render/ascii-fleet.js +0 -82
- package/dist/src/app-opentui/render/constants.d.ts +0 -30
- package/dist/src/app-opentui/render/constants.js +0 -64
- package/dist/src/app-opentui/render/graphics.d.ts +0 -40
- package/dist/src/app-opentui/render/graphics.js +0 -713
- package/dist/src/app-opentui/render/hover.d.ts +0 -11
- package/dist/src/app-opentui/render/hover.js +0 -34
- package/dist/src/app-opentui/render/native-host.d.ts +0 -37
- package/dist/src/app-opentui/render/native-host.js +0 -180
- package/dist/src/app-opentui/render/panel-layout.d.ts +0 -38
- package/dist/src/app-opentui/render/panel-layout.js +0 -48
- package/dist/src/app-opentui/render/panels.d.ts +0 -12
- package/dist/src/app-opentui/render/panels.js +0 -288
- package/dist/src/app-opentui/render/preloader.d.ts +0 -10
- package/dist/src/app-opentui/render/preloader.js +0 -166
- package/dist/src/app-opentui/render/scene.d.ts +0 -68
- package/dist/src/app-opentui/render/scene.js +0 -300
- package/dist/src/app-opentui/render/terminal-handoff.d.ts +0 -16
- package/dist/src/app-opentui/render/terminal-handoff.js +0 -14
- package/dist/src/app-opentui/render/text.d.ts +0 -29
- package/dist/src/app-opentui/render/text.js +0 -177
- package/dist/src/app-opentui/render/type-bar.d.ts +0 -15
- package/dist/src/app-opentui/render/type-bar.js +0 -212
- package/dist/src/app-opentui/runtime-resources.d.ts +0 -16
- package/dist/src/app-opentui/runtime-resources.js +0 -62
- package/dist/src/app-opentui/runtime.d.ts +0 -45
- package/dist/src/app-opentui/runtime.js +0 -5232
- package/dist/src/app-opentui/scenes/command.d.ts +0 -3
- package/dist/src/app-opentui/scenes/command.js +0 -118
- package/dist/src/app-opentui/scenes/doctor.d.ts +0 -3
- package/dist/src/app-opentui/scenes/doctor.js +0 -296
- package/dist/src/app-opentui/scenes/error.d.ts +0 -2
- package/dist/src/app-opentui/scenes/error.js +0 -277
- package/dist/src/app-opentui/scenes/family-domains/agent.d.ts +0 -2
- package/dist/src/app-opentui/scenes/family-domains/agent.js +0 -349
- package/dist/src/app-opentui/scenes/family-domains/browser.d.ts +0 -2
- package/dist/src/app-opentui/scenes/family-domains/browser.js +0 -196
- package/dist/src/app-opentui/scenes/family-domains/dist.d.ts +0 -2
- package/dist/src/app-opentui/scenes/family-domains/dist.js +0 -244
- package/dist/src/app-opentui/scenes/family-domains/git.d.ts +0 -2
- package/dist/src/app-opentui/scenes/family-domains/git.js +0 -196
- package/dist/src/app-opentui/scenes/family-domains/github.d.ts +0 -2
- package/dist/src/app-opentui/scenes/family-domains/github.js +0 -275
- package/dist/src/app-opentui/scenes/family-domains/harness.d.ts +0 -2
- package/dist/src/app-opentui/scenes/family-domains/harness.js +0 -153
- package/dist/src/app-opentui/scenes/family-domains/index.d.ts +0 -4
- package/dist/src/app-opentui/scenes/family-domains/index.js +0 -1680
- package/dist/src/app-opentui/scenes/family-domains/kit.d.ts +0 -76
- package/dist/src/app-opentui/scenes/family-domains/kit.js +0 -306
- package/dist/src/app-opentui/scenes/family-domains/profile.d.ts +0 -2
- package/dist/src/app-opentui/scenes/family-domains/profile.js +0 -213
- package/dist/src/app-opentui/scenes/family-domains/queue.d.ts +0 -2
- package/dist/src/app-opentui/scenes/family-domains/queue.js +0 -147
- package/dist/src/app-opentui/scenes/family-domains/remote.d.ts +0 -2
- package/dist/src/app-opentui/scenes/family-domains/remote.js +0 -519
- package/dist/src/app-opentui/scenes/family-domains/review.d.ts +0 -2
- package/dist/src/app-opentui/scenes/family-domains/review.js +0 -281
- package/dist/src/app-opentui/scenes/family-domains/setup.d.ts +0 -2
- package/dist/src/app-opentui/scenes/family-domains/setup.js +0 -268
- package/dist/src/app-opentui/scenes/family-domains/stats.d.ts +0 -2
- package/dist/src/app-opentui/scenes/family-domains/stats.js +0 -371
- package/dist/src/app-opentui/scenes/family.d.ts +0 -3
- package/dist/src/app-opentui/scenes/family.js +0 -2199
- package/dist/src/app-opentui/scenes/fleet.d.ts +0 -3
- package/dist/src/app-opentui/scenes/fleet.js +0 -766
- package/dist/src/app-opentui/scenes/handoff.d.ts +0 -2
- package/dist/src/app-opentui/scenes/handoff.js +0 -455
- package/dist/src/app-opentui/scenes/help.d.ts +0 -3
- package/dist/src/app-opentui/scenes/help.js +0 -725
- package/dist/src/app-opentui/scenes/inbox.d.ts +0 -3
- package/dist/src/app-opentui/scenes/inbox.js +0 -427
- package/dist/src/app-opentui/scenes/init.d.ts +0 -3
- package/dist/src/app-opentui/scenes/init.js +0 -181
- package/dist/src/app-opentui/scenes/inspect.d.ts +0 -3
- package/dist/src/app-opentui/scenes/inspect.js +0 -794
- package/dist/src/app-opentui/scenes/main.d.ts +0 -3
- package/dist/src/app-opentui/scenes/main.js +0 -332
- package/dist/src/app-opentui/scenes/pi.d.ts +0 -3
- package/dist/src/app-opentui/scenes/pi.js +0 -509
- package/dist/src/app-opentui/scenes/plugin.d.ts +0 -3
- package/dist/src/app-opentui/scenes/plugin.js +0 -487
- package/dist/src/app-opentui/scenes/repo.d.ts +0 -3
- package/dist/src/app-opentui/scenes/repo.js +0 -425
- package/dist/src/app-opentui/scenes/run-detail.d.ts +0 -3
- package/dist/src/app-opentui/scenes/run-detail.js +0 -467
- package/dist/src/app-opentui/scenes/server.d.ts +0 -3
- package/dist/src/app-opentui/scenes/server.js +0 -378
- package/dist/src/app-opentui/scenes/tasks.d.ts +0 -3
- package/dist/src/app-opentui/scenes/tasks.js +0 -768
- package/dist/src/app-opentui/scenes/workspace.d.ts +0 -3
- package/dist/src/app-opentui/scenes/workspace.js +0 -427
- package/dist/src/app-opentui/selectable.d.ts +0 -19
- package/dist/src/app-opentui/selectable.js +0 -80
- package/dist/src/app-opentui/state.d.ts +0 -4
- package/dist/src/app-opentui/state.js +0 -399
- package/dist/src/app-opentui/surface-catalog.d.ts +0 -20
- package/dist/src/app-opentui/surface-catalog.js +0 -542
- package/dist/src/app-opentui/theme.d.ts +0 -59
- package/dist/src/app-opentui/theme.js +0 -142
- package/dist/src/app-opentui/types.d.ts +0 -313
- package/dist/src/app-opentui/types.js +0 -1
- package/dist/src/commands/_server-events.d.ts +0 -26
- package/dist/src/commands/_server-events.js +0 -715
|
@@ -1,4524 +0,0 @@
|
|
|
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
|
-
|
|
18
|
-
// packages/cli/src/app-opentui/adapters/common.ts
|
|
19
|
-
function projectRootOf(ctx) {
|
|
20
|
-
const root = ctx.rig?.projectRoot ?? ctx.projectRoot ?? ctx.getState().projectRoot;
|
|
21
|
-
if (typeof root === "string" && root.trim())
|
|
22
|
-
return root;
|
|
23
|
-
throw new Error("App adapter requires a projectRoot.");
|
|
24
|
-
}
|
|
25
|
-
async function runtimeOf(ctx) {
|
|
26
|
-
if (ctx.rig && "runId" in ctx.rig && ctx.ensureRuntime === undefined) {
|
|
27
|
-
return ctx.rig;
|
|
28
|
-
}
|
|
29
|
-
if (ctx.ensureRuntime)
|
|
30
|
-
return ctx.ensureRuntime();
|
|
31
|
-
throw new Error("App adapter requires ensureRuntime() before this action can run.");
|
|
32
|
-
}
|
|
33
|
-
function normalizeAppError(error) {
|
|
34
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
35
|
-
const rawHint = error instanceof Error ? error.hint : undefined;
|
|
36
|
-
return {
|
|
37
|
-
message,
|
|
38
|
-
...typeof rawHint === "string" && rawHint.trim() ? { hint: rawHint.trim() } : {}
|
|
39
|
-
};
|
|
40
|
-
}
|
|
41
|
-
function emitStarted(ctx, label, optimistic) {
|
|
42
|
-
ctx.emit({ type: "action.started", label, ...optimistic ? { optimistic } : {} });
|
|
43
|
-
}
|
|
44
|
-
function emitProgress(ctx, label, detail, data) {
|
|
45
|
-
ctx.emit({ type: "action.progress", label, ...detail ? { detail } : {}, ...data ? { data } : {} });
|
|
46
|
-
}
|
|
47
|
-
function emitCompleted(ctx, label, data) {
|
|
48
|
-
ctx.emit({ type: "action.completed", label, ...data ? { data } : {} });
|
|
49
|
-
}
|
|
50
|
-
function emitFailed(ctx, label, error, data) {
|
|
51
|
-
if (data)
|
|
52
|
-
patchData(ctx, data);
|
|
53
|
-
const normalized = normalizeAppError(error);
|
|
54
|
-
ctx.emit({
|
|
55
|
-
type: "action.failed",
|
|
56
|
-
label,
|
|
57
|
-
message: normalized.message,
|
|
58
|
-
...normalized.hint ? { hint: normalized.hint } : {},
|
|
59
|
-
cause: error
|
|
60
|
-
});
|
|
61
|
-
}
|
|
62
|
-
function patchData(ctx, data) {
|
|
63
|
-
ctx.emit({ type: "data.patch", data });
|
|
64
|
-
}
|
|
65
|
-
function patchFooter(ctx, footer) {
|
|
66
|
-
ctx.emit({ type: "footer.patch", footer });
|
|
67
|
-
}
|
|
68
|
-
async function releaseRendererForExternalTui(ctx) {
|
|
69
|
-
const renderer = ctx.renderer;
|
|
70
|
-
if (!renderer)
|
|
71
|
-
return;
|
|
72
|
-
if (renderer.suspend) {
|
|
73
|
-
await renderer.suspend();
|
|
74
|
-
return;
|
|
75
|
-
}
|
|
76
|
-
if (renderer.destroy) {
|
|
77
|
-
await renderer.destroy();
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
async function resumeRendererAfterExternalTui(ctx) {
|
|
81
|
-
await ctx.renderer?.resume?.();
|
|
82
|
-
}
|
|
83
|
-
function arrayFromPayload(value) {
|
|
84
|
-
if (Array.isArray(value)) {
|
|
85
|
-
return value.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry)));
|
|
86
|
-
}
|
|
87
|
-
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
88
|
-
const entries = value.entries;
|
|
89
|
-
if (Array.isArray(entries))
|
|
90
|
-
return arrayFromPayload(entries);
|
|
91
|
-
}
|
|
92
|
-
return [];
|
|
93
|
-
}
|
|
94
|
-
function stringField(record, keys, fallback = "") {
|
|
95
|
-
for (const key of keys) {
|
|
96
|
-
const value = record[key];
|
|
97
|
-
if (typeof value === "string" && value.trim())
|
|
98
|
-
return value.trim();
|
|
99
|
-
if (typeof value === "number" && Number.isFinite(value))
|
|
100
|
-
return String(value);
|
|
101
|
-
}
|
|
102
|
-
return fallback;
|
|
103
|
-
}
|
|
104
|
-
function compactRecord(record, keys) {
|
|
105
|
-
const out = {};
|
|
106
|
-
for (const key of keys) {
|
|
107
|
-
const value = record[key];
|
|
108
|
-
if (value !== undefined && value !== null && value !== "")
|
|
109
|
-
out[key] = value;
|
|
110
|
-
}
|
|
111
|
-
return out;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
// packages/cli/src/runner.ts
|
|
115
|
-
import { EventBus } from "@rig/runtime/control-plane/runtime/events";
|
|
116
|
-
import { CliError as RuntimeCliError } from "@rig/runtime/control-plane/errors";
|
|
117
|
-
import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
|
|
118
|
-
import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
|
|
119
|
-
function takeFlag(args, flag) {
|
|
120
|
-
const rest = [];
|
|
121
|
-
let value = false;
|
|
122
|
-
for (const arg of args) {
|
|
123
|
-
if (arg === flag) {
|
|
124
|
-
value = true;
|
|
125
|
-
continue;
|
|
126
|
-
}
|
|
127
|
-
rest.push(arg);
|
|
128
|
-
}
|
|
129
|
-
return { value, rest };
|
|
130
|
-
}
|
|
131
|
-
function takeOption(args, option) {
|
|
132
|
-
const rest = [];
|
|
133
|
-
let value;
|
|
134
|
-
for (let index = 0;index < args.length; index += 1) {
|
|
135
|
-
const current = args[index];
|
|
136
|
-
if (current === option) {
|
|
137
|
-
const next = args[index + 1];
|
|
138
|
-
if (!next || next.startsWith("-")) {
|
|
139
|
-
throw new CliError(`Missing value for ${option}`, 1, { hint: `Provide a value after ${option}, e.g. \`${option} <value>\`.` });
|
|
140
|
-
}
|
|
141
|
-
value = next;
|
|
142
|
-
index += 1;
|
|
143
|
-
continue;
|
|
144
|
-
}
|
|
145
|
-
if (current !== undefined) {
|
|
146
|
-
rest.push(current);
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
return { value, rest };
|
|
150
|
-
}
|
|
151
|
-
function requireNoExtraArgs(args, usage) {
|
|
152
|
-
if (args.length > 0) {
|
|
153
|
-
throw new CliError(`Unexpected arguments: ${args.join(" ")}
|
|
154
|
-
Usage: ${usage}`);
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
function requireTask(taskId, usage) {
|
|
158
|
-
if (!taskId) {
|
|
159
|
-
throw new CliError(`Missing --task option.
|
|
160
|
-
Usage: ${usage}`);
|
|
161
|
-
}
|
|
162
|
-
return taskId;
|
|
163
|
-
}
|
|
164
|
-
var CliError;
|
|
165
|
-
var init_runner = __esm(() => {
|
|
166
|
-
CliError = class CliError extends RuntimeCliError {
|
|
167
|
-
hint;
|
|
168
|
-
constructor(message, exitCode = 1, options = {}) {
|
|
169
|
-
super(message, exitCode);
|
|
170
|
-
if (options.hint?.trim()) {
|
|
171
|
-
this.hint = options.hint.trim();
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
};
|
|
175
|
-
});
|
|
176
|
-
|
|
177
|
-
// packages/cli/src/commands/_connection-state.ts
|
|
178
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
179
|
-
import { homedir } from "os";
|
|
180
|
-
import { dirname, resolve } from "path";
|
|
181
|
-
function resolveGlobalConnectionsPath(env = process.env) {
|
|
182
|
-
const explicit = env.RIG_CONNECTIONS_FILE?.trim();
|
|
183
|
-
if (explicit)
|
|
184
|
-
return resolve(explicit);
|
|
185
|
-
const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
|
|
186
|
-
if (stateDir)
|
|
187
|
-
return resolve(stateDir, "connections.json");
|
|
188
|
-
return resolve(homedir(), ".rig", "connections.json");
|
|
189
|
-
}
|
|
190
|
-
function resolveRepoConnectionPath(projectRoot) {
|
|
191
|
-
return resolve(projectRoot, ".rig", "state", "connection.json");
|
|
192
|
-
}
|
|
193
|
-
function readJsonFile(path) {
|
|
194
|
-
if (!existsSync(path))
|
|
195
|
-
return null;
|
|
196
|
-
try {
|
|
197
|
-
return JSON.parse(readFileSync(path, "utf8"));
|
|
198
|
-
} catch (error) {
|
|
199
|
-
throw new CliError(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1, { hint: "Fix or delete that file, then re-select a server with `rig server use <alias|local>`." });
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
function writeJsonFile(path, value) {
|
|
203
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
204
|
-
writeFileSync(path, `${JSON.stringify(value, null, 2)}
|
|
205
|
-
`, "utf8");
|
|
206
|
-
}
|
|
207
|
-
function normalizeConnection(value) {
|
|
208
|
-
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
209
|
-
return null;
|
|
210
|
-
const record = value;
|
|
211
|
-
if (record.kind === "local")
|
|
212
|
-
return { kind: "local", mode: "auto" };
|
|
213
|
-
if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
|
|
214
|
-
const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
|
|
215
|
-
return { kind: "remote", baseUrl };
|
|
216
|
-
}
|
|
217
|
-
return null;
|
|
218
|
-
}
|
|
219
|
-
function readGlobalConnections(options = {}) {
|
|
220
|
-
const path = resolveGlobalConnectionsPath(options.env ?? process.env);
|
|
221
|
-
const payload = readJsonFile(path);
|
|
222
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
223
|
-
return { connections: {} };
|
|
224
|
-
}
|
|
225
|
-
const rawConnections = payload.connections;
|
|
226
|
-
const connections = {};
|
|
227
|
-
if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
|
|
228
|
-
for (const [alias, raw] of Object.entries(rawConnections)) {
|
|
229
|
-
const connection = normalizeConnection(raw);
|
|
230
|
-
if (connection)
|
|
231
|
-
connections[alias] = connection;
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
return { connections };
|
|
235
|
-
}
|
|
236
|
-
function readRepoConnection(projectRoot) {
|
|
237
|
-
const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
|
|
238
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
239
|
-
return null;
|
|
240
|
-
const record = payload;
|
|
241
|
-
const selected = typeof record.selected === "string" ? record.selected.trim() : "";
|
|
242
|
-
if (!selected)
|
|
243
|
-
return null;
|
|
244
|
-
return {
|
|
245
|
-
selected,
|
|
246
|
-
project: typeof record.project === "string" ? record.project : undefined,
|
|
247
|
-
linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
|
|
248
|
-
serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined,
|
|
249
|
-
serverProjectRootAlias: typeof record.serverProjectRootAlias === "string" && record.serverProjectRootAlias.trim() ? record.serverProjectRootAlias.trim() : undefined,
|
|
250
|
-
serverProjectRootBaseUrl: typeof record.serverProjectRootBaseUrl === "string" && record.serverProjectRootBaseUrl.trim() ? record.serverProjectRootBaseUrl.trim().replace(/\/+$/, "") : undefined
|
|
251
|
-
};
|
|
252
|
-
}
|
|
253
|
-
function writeRepoConnection(projectRoot, state) {
|
|
254
|
-
writeJsonFile(resolveRepoConnectionPath(projectRoot), state);
|
|
255
|
-
}
|
|
256
|
-
function rootAllowedForSelection(repo, connection) {
|
|
257
|
-
const root = repo.serverProjectRoot?.trim();
|
|
258
|
-
if (!root)
|
|
259
|
-
return;
|
|
260
|
-
if (connection.kind === "remote") {
|
|
261
|
-
if (repo.serverProjectRootAlias !== repo.selected)
|
|
262
|
-
return;
|
|
263
|
-
if (repo.serverProjectRootBaseUrl !== connection.baseUrl)
|
|
264
|
-
return;
|
|
265
|
-
} else if (repo.serverProjectRootAlias && repo.serverProjectRootAlias !== repo.selected) {
|
|
266
|
-
return;
|
|
267
|
-
}
|
|
268
|
-
return root;
|
|
269
|
-
}
|
|
270
|
-
function resolveSelectedConnection(projectRoot, options = {}) {
|
|
271
|
-
const repo = readRepoConnection(projectRoot);
|
|
272
|
-
if (!repo)
|
|
273
|
-
return null;
|
|
274
|
-
if (repo.selected === "local")
|
|
275
|
-
return { alias: "local", connection: { kind: "local", mode: "auto" }, serverProjectRoot: repo.serverProjectRoot };
|
|
276
|
-
const global = readGlobalConnections(options);
|
|
277
|
-
const connection = global.connections[repo.selected];
|
|
278
|
-
if (!connection) {
|
|
279
|
-
throw new CliError(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
|
|
280
|
-
}
|
|
281
|
-
return { alias: repo.selected, connection, serverProjectRoot: rootAllowedForSelection(repo, connection) };
|
|
282
|
-
}
|
|
283
|
-
function writeRepoServerProjectRoot(projectRoot, serverProjectRoot, metadata = {}) {
|
|
284
|
-
const repo = readRepoConnection(projectRoot);
|
|
285
|
-
if (!repo)
|
|
286
|
-
return;
|
|
287
|
-
let inferred = metadata;
|
|
288
|
-
if (!inferred.alias || !inferred.baseUrl) {
|
|
289
|
-
try {
|
|
290
|
-
const selected = resolveSelectedConnection(projectRoot);
|
|
291
|
-
if (selected?.connection.kind === "remote") {
|
|
292
|
-
inferred = {
|
|
293
|
-
alias: inferred.alias ?? selected.alias,
|
|
294
|
-
baseUrl: inferred.baseUrl ?? selected.connection.baseUrl
|
|
295
|
-
};
|
|
296
|
-
}
|
|
297
|
-
} catch {}
|
|
298
|
-
}
|
|
299
|
-
writeRepoConnection(projectRoot, {
|
|
300
|
-
...repo,
|
|
301
|
-
...metadata.project ? { project: metadata.project } : {},
|
|
302
|
-
serverProjectRoot,
|
|
303
|
-
...inferred.alias ? { serverProjectRootAlias: inferred.alias } : {},
|
|
304
|
-
...inferred.baseUrl ? { serverProjectRootBaseUrl: inferred.baseUrl.replace(/\/+$/, "") } : {}
|
|
305
|
-
});
|
|
306
|
-
}
|
|
307
|
-
function clearRepoServerProjectRoot(projectRoot) {
|
|
308
|
-
const repo = readRepoConnection(projectRoot);
|
|
309
|
-
if (!repo)
|
|
310
|
-
return;
|
|
311
|
-
writeRepoConnection(projectRoot, {
|
|
312
|
-
selected: repo.selected,
|
|
313
|
-
...repo.project ? { project: repo.project } : {},
|
|
314
|
-
...repo.linkedAt ? { linkedAt: repo.linkedAt } : {}
|
|
315
|
-
});
|
|
316
|
-
}
|
|
317
|
-
var init__connection_state = __esm(() => {
|
|
318
|
-
init_runner();
|
|
319
|
-
});
|
|
320
|
-
|
|
321
|
-
// packages/cli/src/commands/_server-client.ts
|
|
322
|
-
var exports__server_client = {};
|
|
323
|
-
__export(exports__server_client, {
|
|
324
|
-
updateWorkspaceTaskViaServer: () => updateWorkspaceTaskViaServer,
|
|
325
|
-
switchServerProjectRootViaServer: () => switchServerProjectRootViaServer,
|
|
326
|
-
submitTaskRunViaServer: () => submitTaskRunViaServer,
|
|
327
|
-
stopRunViaServer: () => stopRunViaServer,
|
|
328
|
-
steerRunViaServer: () => steerRunViaServer,
|
|
329
|
-
setServerPhaseListener: () => setServerPhaseListener,
|
|
330
|
-
setGitHubBearerTokenForCurrentProcess: () => setGitHubBearerTokenForCurrentProcess,
|
|
331
|
-
sendRunPiShellViaServer: () => sendRunPiShellViaServer,
|
|
332
|
-
sendRunPiPromptViaServer: () => sendRunPiPromptViaServer,
|
|
333
|
-
selectNextWorkspaceTaskViaServer: () => selectNextWorkspaceTaskViaServer,
|
|
334
|
-
runRunPiCommandViaServer: () => runRunPiCommandViaServer,
|
|
335
|
-
resumeRunViaServer: () => resumeRunViaServer,
|
|
336
|
-
respondRunPiExtensionUiViaServer: () => respondRunPiExtensionUiViaServer,
|
|
337
|
-
resolveServerConnectionLabel: () => resolveServerConnectionLabel,
|
|
338
|
-
requestServerJson: () => requestServerJson,
|
|
339
|
-
repairRemoteProjectRootLink: () => repairRemoteProjectRootLink,
|
|
340
|
-
registerProjectViaServer: () => registerProjectViaServer,
|
|
341
|
-
prepareRemoteCheckoutViaServer: () => prepareRemoteCheckoutViaServer,
|
|
342
|
-
postGitHubTokenViaServer: () => postGitHubTokenViaServer,
|
|
343
|
-
normalizeRepoSlug: () => normalizeRepoSlug,
|
|
344
|
-
listWorkspaceTasksViaServer: () => listWorkspaceTasksViaServer,
|
|
345
|
-
listRunsViaServer: () => listRunsViaServer,
|
|
346
|
-
listGitHubProjectsViaServer: () => listGitHubProjectsViaServer,
|
|
347
|
-
isRemoteProjectRootLinkError: () => isRemoteProjectRootLinkError,
|
|
348
|
-
inspectRemoteProjectLink: () => inspectRemoteProjectLink,
|
|
349
|
-
getWorkspaceTaskViaServer: () => getWorkspaceTaskViaServer,
|
|
350
|
-
getRunTimelineViaServer: () => getRunTimelineViaServer,
|
|
351
|
-
getRunPiStatusViaServer: () => getRunPiStatusViaServer,
|
|
352
|
-
getRunPiSessionViaServer: () => getRunPiSessionViaServer,
|
|
353
|
-
getRunPiMessagesViaServer: () => getRunPiMessagesViaServer,
|
|
354
|
-
getRunPiCommandsViaServer: () => getRunPiCommandsViaServer,
|
|
355
|
-
getRunPiCapabilitiesViaServer: () => getRunPiCapabilitiesViaServer,
|
|
356
|
-
getRunLogsViaServer: () => getRunLogsViaServer,
|
|
357
|
-
getRunDetailsViaServer: () => getRunDetailsViaServer,
|
|
358
|
-
getGitHubProjectStatusFieldViaServer: () => getGitHubProjectStatusFieldViaServer,
|
|
359
|
-
getGitHubAuthStatusViaServer: () => getGitHubAuthStatusViaServer,
|
|
360
|
-
formatRemoteProjectLinkHint: () => formatRemoteProjectLinkHint,
|
|
361
|
-
ensureTaskLabelsViaServer: () => ensureTaskLabelsViaServer,
|
|
362
|
-
ensureServerForCli: () => ensureServerForCli,
|
|
363
|
-
ensureRemoteProjectRootLink: () => ensureRemoteProjectRootLink,
|
|
364
|
-
buildRunPiEventsWebSocketUrl: () => buildRunPiEventsWebSocketUrl,
|
|
365
|
-
abortRunPiViaServer: () => abortRunPiViaServer
|
|
366
|
-
});
|
|
367
|
-
import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
368
|
-
import { dirname as dirname2, isAbsolute, resolve as resolve2 } from "path";
|
|
369
|
-
import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
|
|
370
|
-
function setServerPhaseListener(listener) {
|
|
371
|
-
const previous = serverPhaseListener;
|
|
372
|
-
serverPhaseListener = listener;
|
|
373
|
-
return previous;
|
|
374
|
-
}
|
|
375
|
-
function reportServerPhase(label) {
|
|
376
|
-
serverPhaseListener?.(label);
|
|
377
|
-
}
|
|
378
|
-
function cleanToken(value) {
|
|
379
|
-
const trimmed = value?.trim();
|
|
380
|
-
return trimmed ? trimmed : null;
|
|
381
|
-
}
|
|
382
|
-
function setGitHubBearerTokenForCurrentProcess(token, projectRoot) {
|
|
383
|
-
const scopedKey = resolve2(projectRoot ?? process.cwd());
|
|
384
|
-
scopedGitHubBearerTokens.set(scopedKey, cleanToken(token ?? undefined));
|
|
385
|
-
}
|
|
386
|
-
function readRemoteAuthState(projectRoot) {
|
|
387
|
-
const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
|
|
388
|
-
if (!existsSync2(path))
|
|
389
|
-
return null;
|
|
390
|
-
try {
|
|
391
|
-
const parsed = JSON.parse(readFileSync2(path, "utf8"));
|
|
392
|
-
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
|
|
393
|
-
} catch {
|
|
394
|
-
return null;
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
function readPrivateRemoteSessionToken(projectRoot) {
|
|
398
|
-
const parsed = readRemoteAuthState(projectRoot);
|
|
399
|
-
return parsed ? cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined) : null;
|
|
400
|
-
}
|
|
401
|
-
function readGitHubBearerTokenForRemote(projectRoot) {
|
|
402
|
-
const scopedKey = resolve2(projectRoot);
|
|
403
|
-
if (scopedGitHubBearerTokens.has(scopedKey))
|
|
404
|
-
return scopedGitHubBearerTokens.get(scopedKey) ?? null;
|
|
405
|
-
const privateSession = readPrivateRemoteSessionToken(projectRoot);
|
|
406
|
-
if (privateSession)
|
|
407
|
-
return privateSession;
|
|
408
|
-
return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
|
|
409
|
-
}
|
|
410
|
-
function readStoredGitHubAuthToken(projectRoot) {
|
|
411
|
-
const parsed = readRemoteAuthState(projectRoot);
|
|
412
|
-
return parsed ? cleanToken(typeof parsed.token === "string" ? parsed.token : undefined) : null;
|
|
413
|
-
}
|
|
414
|
-
function inferRemoteServerProjectRootCandidateFromAuthState(projectRoot, repoSlug) {
|
|
415
|
-
if (!/^[^/]+\/[^/]+$/.test(repoSlug))
|
|
416
|
-
return null;
|
|
417
|
-
const repo = readRepoConnection(projectRoot);
|
|
418
|
-
const auth = readRemoteAuthState(projectRoot);
|
|
419
|
-
const authUpdatedAt = typeof auth?.updatedAt === "string" ? Date.parse(auth.updatedAt) : Number.NaN;
|
|
420
|
-
const repoLinkedAt = typeof repo?.linkedAt === "string" ? Date.parse(repo.linkedAt) : Number.NaN;
|
|
421
|
-
if (Number.isFinite(authUpdatedAt) && Number.isFinite(repoLinkedAt) && authUpdatedAt + 1000 < repoLinkedAt)
|
|
422
|
-
return null;
|
|
423
|
-
const checkoutBaseDir = typeof auth?.checkoutBaseDir === "string" && auth.checkoutBaseDir.trim() ? auth.checkoutBaseDir.trim() : null;
|
|
424
|
-
if (!checkoutBaseDir)
|
|
425
|
-
return null;
|
|
426
|
-
return `${checkoutBaseDir.replace(/\/+$/, "")}/${repoSlug}`;
|
|
427
|
-
}
|
|
428
|
-
function readLocalConnectionFallbackToken(projectRoot) {
|
|
429
|
-
return readGitHubBearerTokenForRemote(projectRoot) ?? cleanToken(process.env.RIG_GITHUB_TOKEN) ?? readStoredGitHubAuthToken(projectRoot);
|
|
430
|
-
}
|
|
431
|
-
function normalizeRepoSlug(value) {
|
|
432
|
-
const slug = value?.trim();
|
|
433
|
-
return slug && /^[^/\s]+\/[^/\s]+$/.test(slug) ? slug : null;
|
|
434
|
-
}
|
|
435
|
-
function readProjectLinkSlug(projectRoot) {
|
|
436
|
-
const path = resolve2(projectRoot, ".rig", "state", "project-link.json");
|
|
437
|
-
if (!existsSync2(path))
|
|
438
|
-
return null;
|
|
439
|
-
try {
|
|
440
|
-
const parsed = JSON.parse(readFileSync2(path, "utf8"));
|
|
441
|
-
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
442
|
-
return null;
|
|
443
|
-
return normalizeRepoSlug(typeof parsed.repoSlug === "string" ? String(parsed.repoSlug) : null);
|
|
444
|
-
} catch {
|
|
445
|
-
return null;
|
|
446
|
-
}
|
|
447
|
-
}
|
|
448
|
-
function writeProjectLinkConnection(projectRoot, repoSlug, alias) {
|
|
449
|
-
const path = resolve2(projectRoot, ".rig", "state", "project-link.json");
|
|
450
|
-
mkdirSync2(dirname2(path), { recursive: true });
|
|
451
|
-
writeFileSync2(path, `${JSON.stringify({ repoSlug, connection: alias, linkedAt: new Date().toISOString() }, null, 2)}
|
|
452
|
-
`, "utf8");
|
|
453
|
-
}
|
|
454
|
-
function remoteLinkRepairCommand(repoSlug) {
|
|
455
|
-
return repoSlug ? `rig server repair-link --repo ${repoSlug}` : "rig server repair-link --repo owner/repo";
|
|
456
|
-
}
|
|
457
|
-
function isRemoteProjectRootLinkError(error) {
|
|
458
|
-
const text = error instanceof Error ? error.message : String(error ?? "");
|
|
459
|
-
return /no server-host project root link|remote project(?:-root)? link|x-rig-project-root|serverProjectRoot/i.test(text);
|
|
460
|
-
}
|
|
461
|
-
function formatRemoteProjectLinkHint(resolution) {
|
|
462
|
-
const repair = remoteLinkRepairCommand(resolution.repoSlug);
|
|
463
|
-
if (resolution.status === "auth_required") {
|
|
464
|
-
return `Authenticate the selected remote${resolution.alias ? ` (${resolution.alias})` : ""}, then run \`${repair}\`. Use \`rig github auth import-gh\` or \`rig init --repair --server remote --github-auth device${resolution.repoSlug ? ` --repo ${resolution.repoSlug}` : ""}\`.`;
|
|
465
|
-
}
|
|
466
|
-
if (resolution.status === "missing_project") {
|
|
467
|
-
return `Record the repo slug, then run \`${repair}\` (or \`rig init --repo owner/repo --server remote --github-auth device\`).`;
|
|
468
|
-
}
|
|
469
|
-
if (resolution.status === "not_remote")
|
|
470
|
-
return "Select a remote server with `rig server use <alias>` before repairing a remote project link.";
|
|
471
|
-
return `Run \`${repair}\` to backfill or prepare a server-host checkout for the selected remote${resolution.alias ? ` (${resolution.alias})` : ""}.`;
|
|
472
|
-
}
|
|
473
|
-
function remoteProjectLinkFailure(input) {
|
|
474
|
-
const partial = {
|
|
475
|
-
status: input.status,
|
|
476
|
-
alias: input.alias,
|
|
477
|
-
baseUrl: input.baseUrl,
|
|
478
|
-
repoSlug: input.repoSlug
|
|
479
|
-
};
|
|
480
|
-
return {
|
|
481
|
-
ok: false,
|
|
482
|
-
...input,
|
|
483
|
-
hint: formatRemoteProjectLinkHint(partial),
|
|
484
|
-
next: remoteLinkRepairCommand(input.repoSlug)
|
|
485
|
-
};
|
|
486
|
-
}
|
|
487
|
-
function remoteProjectLinkSuccess(input) {
|
|
488
|
-
return {
|
|
489
|
-
ok: true,
|
|
490
|
-
status: input.status,
|
|
491
|
-
alias: input.alias,
|
|
492
|
-
baseUrl: input.baseUrl,
|
|
493
|
-
repoSlug: input.repoSlug,
|
|
494
|
-
serverProjectRoot: input.serverProjectRoot,
|
|
495
|
-
source: input.source,
|
|
496
|
-
prepared: input.prepared ?? input.status === "prepared",
|
|
497
|
-
validated: input.validated ?? false,
|
|
498
|
-
message: input.message ?? `Remote project link ready for ${input.repoSlug}.`,
|
|
499
|
-
hint: "Remote-scoped task/run/status requests will send x-rig-project-root for this server-host checkout.",
|
|
500
|
-
next: "rig task list"
|
|
501
|
-
};
|
|
502
|
-
}
|
|
503
|
-
function localCheckoutPathCandidate(projectRoot, candidate) {
|
|
504
|
-
try {
|
|
505
|
-
const local = resolve2(projectRoot);
|
|
506
|
-
const resolved = resolve2(candidate);
|
|
507
|
-
return resolved === local || resolved.startsWith(`${local}/`);
|
|
508
|
-
} catch {
|
|
509
|
-
return false;
|
|
510
|
-
}
|
|
511
|
-
}
|
|
512
|
-
async function requestRemoteProjectLinkJson(baseUrl, pathname, authToken, init = {}) {
|
|
513
|
-
const requestUrl = new URL(`${baseUrl}${pathname}`);
|
|
514
|
-
if (authToken && queryAuthFallbackEnabled())
|
|
515
|
-
requestUrl.searchParams.set("rt", authToken);
|
|
516
|
-
const response = await fetch(requestUrl, {
|
|
517
|
-
...init,
|
|
518
|
-
headers: mergeHeaders(init.headers, authToken)
|
|
519
|
-
});
|
|
520
|
-
const text = await response.text();
|
|
521
|
-
const payload = text.trim().length > 0 ? (() => {
|
|
522
|
-
try {
|
|
523
|
-
return JSON.parse(text);
|
|
524
|
-
} catch {
|
|
525
|
-
return null;
|
|
526
|
-
}
|
|
527
|
-
})() : null;
|
|
528
|
-
return { ok: response.ok, status: response.status, payload, text };
|
|
529
|
-
}
|
|
530
|
-
function payloadError(payload, fallback) {
|
|
531
|
-
if (payload && typeof payload === "object" && !Array.isArray(payload)) {
|
|
532
|
-
const record = payload;
|
|
533
|
-
const value = record.error ?? record.message ?? record.reason;
|
|
534
|
-
if (typeof value === "string" && value.trim())
|
|
535
|
-
return value.trim();
|
|
536
|
-
}
|
|
537
|
-
return fallback;
|
|
538
|
-
}
|
|
539
|
-
function checkoutPathsFromProjectPayload(payload) {
|
|
540
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
541
|
-
return [];
|
|
542
|
-
const project = payload.project;
|
|
543
|
-
if (!project || typeof project !== "object" || Array.isArray(project))
|
|
544
|
-
return [];
|
|
545
|
-
const checkouts = project.checkouts;
|
|
546
|
-
if (!Array.isArray(checkouts))
|
|
547
|
-
return [];
|
|
548
|
-
return [...checkouts].reverse().flatMap((entry) => {
|
|
549
|
-
if (!entry || typeof entry !== "object" || Array.isArray(entry))
|
|
550
|
-
return [];
|
|
551
|
-
const path = entry.path;
|
|
552
|
-
return typeof path === "string" && path.trim() ? [path.trim()] : [];
|
|
553
|
-
});
|
|
554
|
-
}
|
|
555
|
-
function checkoutPathFromPreparePayload(payload) {
|
|
556
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
557
|
-
return null;
|
|
558
|
-
const checkout = payload.checkout;
|
|
559
|
-
if (!checkout || typeof checkout !== "object" || Array.isArray(checkout))
|
|
560
|
-
return null;
|
|
561
|
-
const path = checkout.path;
|
|
562
|
-
return typeof path === "string" && path.trim() ? path.trim() : null;
|
|
563
|
-
}
|
|
564
|
-
async function validateAndPersistRemoteRoot(input) {
|
|
565
|
-
const candidate = input.candidate.trim();
|
|
566
|
-
if (!candidate || !isAbsolute(candidate)) {
|
|
567
|
-
return remoteProjectLinkFailure({
|
|
568
|
-
status: "invalid_root",
|
|
569
|
-
alias: input.alias,
|
|
570
|
-
baseUrl: input.baseUrl,
|
|
571
|
-
repoSlug: input.repoSlug,
|
|
572
|
-
message: `Remote project root candidate is not an absolute server-host path: ${candidate || "(empty)"}.`
|
|
573
|
-
});
|
|
574
|
-
}
|
|
575
|
-
if (localCheckoutPathCandidate(input.projectRoot, candidate)) {
|
|
576
|
-
return remoteProjectLinkFailure({
|
|
577
|
-
status: "invalid_root",
|
|
578
|
-
alias: input.alias,
|
|
579
|
-
baseUrl: input.baseUrl,
|
|
580
|
-
repoSlug: input.repoSlug,
|
|
581
|
-
message: `Refusing to use local checkout path ${candidate} as a remote server project root.`
|
|
582
|
-
});
|
|
583
|
-
}
|
|
584
|
-
let response;
|
|
585
|
-
try {
|
|
586
|
-
response = await requestRemoteProjectLinkJson(input.baseUrl, "/api/server/project-root", input.authToken, {
|
|
587
|
-
method: "POST",
|
|
588
|
-
headers: { "content-type": "application/json" },
|
|
589
|
-
body: JSON.stringify({ projectRoot: candidate })
|
|
590
|
-
});
|
|
591
|
-
} catch (error) {
|
|
592
|
-
return remoteProjectLinkFailure({
|
|
593
|
-
status: "error",
|
|
594
|
-
alias: input.alias,
|
|
595
|
-
baseUrl: input.baseUrl,
|
|
596
|
-
repoSlug: input.repoSlug,
|
|
597
|
-
message: `Could not validate remote project root ${candidate}: ${error instanceof Error ? error.message : String(error)}`
|
|
598
|
-
});
|
|
599
|
-
}
|
|
600
|
-
if (response.status === 401 || response.status === 403) {
|
|
601
|
-
return remoteProjectLinkFailure({
|
|
602
|
-
status: "auth_required",
|
|
603
|
-
alias: input.alias,
|
|
604
|
-
baseUrl: input.baseUrl,
|
|
605
|
-
repoSlug: input.repoSlug,
|
|
606
|
-
statusCode: response.status,
|
|
607
|
-
message: `Remote server ${input.alias} requires authentication before validating project root ${candidate}.`
|
|
608
|
-
});
|
|
609
|
-
}
|
|
610
|
-
if (!response.ok) {
|
|
611
|
-
return remoteProjectLinkFailure({
|
|
612
|
-
status: "invalid_root",
|
|
613
|
-
alias: input.alias,
|
|
614
|
-
baseUrl: input.baseUrl,
|
|
615
|
-
repoSlug: input.repoSlug,
|
|
616
|
-
statusCode: response.status,
|
|
617
|
-
message: `Remote server rejected project root ${candidate} (${response.status}): ${payloadError(response.payload, response.text || "project-root validation failed")}`
|
|
618
|
-
});
|
|
619
|
-
}
|
|
620
|
-
const record = response.payload && typeof response.payload === "object" && !Array.isArray(response.payload) ? response.payload : {};
|
|
621
|
-
if (record.ok !== true) {
|
|
622
|
-
return remoteProjectLinkFailure({
|
|
623
|
-
status: "invalid_root",
|
|
624
|
-
alias: input.alias,
|
|
625
|
-
baseUrl: input.baseUrl,
|
|
626
|
-
repoSlug: input.repoSlug,
|
|
627
|
-
message: `Remote server did not accept project root ${candidate}: ${payloadError(response.payload, "project-root validation failed")}`
|
|
628
|
-
});
|
|
629
|
-
}
|
|
630
|
-
const accepted = typeof record.projectRoot === "string" && record.projectRoot.trim() ? record.projectRoot.trim() : typeof record.requestedProjectRoot === "string" && record.requestedProjectRoot.trim() ? record.requestedProjectRoot.trim() : candidate;
|
|
631
|
-
writeRepoServerProjectRoot(input.projectRoot, accepted, { alias: input.alias, baseUrl: input.baseUrl, project: input.repoSlug });
|
|
632
|
-
writeProjectLinkConnection(input.projectRoot, input.repoSlug, input.alias);
|
|
633
|
-
const status = input.status ?? (input.prepared ? "prepared" : "backfilled");
|
|
634
|
-
return remoteProjectLinkSuccess({
|
|
635
|
-
status,
|
|
636
|
-
alias: input.alias,
|
|
637
|
-
baseUrl: input.baseUrl,
|
|
638
|
-
repoSlug: input.repoSlug,
|
|
639
|
-
serverProjectRoot: accepted,
|
|
640
|
-
source: input.source,
|
|
641
|
-
prepared: input.prepared,
|
|
642
|
-
validated: true,
|
|
643
|
-
message: status === "ready" ? `Remote project link already points to ${accepted} and was validated on ${input.alias}.` : input.prepared ? `Prepared and linked remote checkout ${accepted} for ${input.repoSlug}.` : `Backfilled remote checkout ${accepted} for ${input.repoSlug}.`
|
|
644
|
-
});
|
|
645
|
-
}
|
|
646
|
-
async function ensureRemoteProjectRootLink(projectRoot, options = {}) {
|
|
647
|
-
let selected;
|
|
648
|
-
try {
|
|
649
|
-
selected = resolveSelectedConnection(projectRoot);
|
|
650
|
-
} catch (error) {
|
|
651
|
-
return remoteProjectLinkFailure({ status: "error", message: error instanceof Error ? error.message : String(error) });
|
|
652
|
-
}
|
|
653
|
-
if (!selected || selected.connection.kind !== "remote") {
|
|
654
|
-
return remoteProjectLinkFailure({ status: "not_remote", message: "No remote Rig server is selected for this repo." });
|
|
655
|
-
}
|
|
656
|
-
const repo = readRepoConnection(projectRoot);
|
|
657
|
-
const explicitRepoRequested = options.repoSlug !== undefined;
|
|
658
|
-
const explicitRepoSlug = explicitRepoRequested ? normalizeRepoSlug(options.repoSlug) : null;
|
|
659
|
-
const repoProjectSlug = normalizeRepoSlug(repo?.project);
|
|
660
|
-
const repoSlug = explicitRepoSlug ?? repoProjectSlug ?? readProjectLinkSlug(projectRoot);
|
|
661
|
-
const alias = selected.alias;
|
|
662
|
-
const baseUrl = selected.connection.baseUrl;
|
|
663
|
-
const authToken = options.authToken === undefined ? readGitHubBearerTokenForRemote(projectRoot) : options.authToken;
|
|
664
|
-
const mode = options.mode ?? "backfill-only";
|
|
665
|
-
if (explicitRepoRequested && !explicitRepoSlug) {
|
|
666
|
-
return remoteProjectLinkFailure({
|
|
667
|
-
status: "missing_project",
|
|
668
|
-
alias,
|
|
669
|
-
baseUrl,
|
|
670
|
-
message: `Invalid --repo value ${JSON.stringify(options.repoSlug)}. Expected owner/repo.`
|
|
671
|
-
});
|
|
672
|
-
}
|
|
673
|
-
if (!repoSlug) {
|
|
674
|
-
return remoteProjectLinkFailure({
|
|
675
|
-
status: "missing_project",
|
|
676
|
-
alias,
|
|
677
|
-
baseUrl,
|
|
678
|
-
message: `Remote server ${alias} is selected, but this checkout has no GitHub repo slug recorded.`
|
|
679
|
-
});
|
|
680
|
-
}
|
|
681
|
-
const skippedCandidates = [];
|
|
682
|
-
const storedRoot = selected.serverProjectRoot?.trim() || null;
|
|
683
|
-
const storedRootMatchesResolvedRepo = repoProjectSlug === repoSlug;
|
|
684
|
-
if (storedRoot && storedRootMatchesResolvedRepo) {
|
|
685
|
-
if (localCheckoutPathCandidate(projectRoot, storedRoot)) {
|
|
686
|
-
clearRepoServerProjectRoot(projectRoot);
|
|
687
|
-
skippedCandidates.push(storedRoot);
|
|
688
|
-
} else {
|
|
689
|
-
const storedResult = await validateAndPersistRemoteRoot({
|
|
690
|
-
projectRoot,
|
|
691
|
-
alias,
|
|
692
|
-
baseUrl,
|
|
693
|
-
authToken,
|
|
694
|
-
repoSlug,
|
|
695
|
-
candidate: storedRoot,
|
|
696
|
-
source: "stored",
|
|
697
|
-
status: "ready"
|
|
698
|
-
});
|
|
699
|
-
if (storedResult.ok || storedResult.status === "auth_required" || storedResult.status === "error")
|
|
700
|
-
return storedResult;
|
|
701
|
-
clearRepoServerProjectRoot(projectRoot);
|
|
702
|
-
skippedCandidates.push(storedRoot);
|
|
703
|
-
}
|
|
704
|
-
} else if (storedRoot) {
|
|
705
|
-
skippedCandidates.push(storedRoot);
|
|
706
|
-
}
|
|
707
|
-
const authCandidate = inferRemoteServerProjectRootCandidateFromAuthState(projectRoot, repoSlug);
|
|
708
|
-
if (authCandidate) {
|
|
709
|
-
const authResult = await validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate: authCandidate, source: "auth-state" });
|
|
710
|
-
if (authResult.ok || authResult.status === "auth_required")
|
|
711
|
-
return authResult;
|
|
712
|
-
}
|
|
713
|
-
let registryResponse;
|
|
714
|
-
try {
|
|
715
|
-
registryResponse = await requestRemoteProjectLinkJson(baseUrl, `/api/projects/${encodeURIComponent(repoSlug)}`, authToken);
|
|
716
|
-
} catch (error) {
|
|
717
|
-
return remoteProjectLinkFailure({
|
|
718
|
-
status: "error",
|
|
719
|
-
alias,
|
|
720
|
-
baseUrl,
|
|
721
|
-
repoSlug,
|
|
722
|
-
message: `Could not read remote project registry for ${repoSlug} on ${alias}: ${error instanceof Error ? error.message : String(error)}`
|
|
723
|
-
});
|
|
724
|
-
}
|
|
725
|
-
if (registryResponse.status === 401 || registryResponse.status === 403) {
|
|
726
|
-
return remoteProjectLinkFailure({
|
|
727
|
-
status: "auth_required",
|
|
728
|
-
alias,
|
|
729
|
-
baseUrl,
|
|
730
|
-
repoSlug,
|
|
731
|
-
statusCode: registryResponse.status,
|
|
732
|
-
message: `Remote server ${alias} requires authentication before reading the ${repoSlug} project registry.`
|
|
733
|
-
});
|
|
734
|
-
}
|
|
735
|
-
if (registryResponse.ok) {
|
|
736
|
-
const candidates = checkoutPathsFromProjectPayload(registryResponse.payload);
|
|
737
|
-
for (const candidate of candidates) {
|
|
738
|
-
const result = await validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate, source: "registry" });
|
|
739
|
-
if (result.ok || result.status === "auth_required")
|
|
740
|
-
return result;
|
|
741
|
-
skippedCandidates.push(candidate);
|
|
742
|
-
}
|
|
743
|
-
if (mode === "backfill-only") {
|
|
744
|
-
return remoteProjectLinkFailure({
|
|
745
|
-
status: candidates.length > 0 ? "invalid_root" : "no_server_checkout",
|
|
746
|
-
alias,
|
|
747
|
-
baseUrl,
|
|
748
|
-
repoSlug,
|
|
749
|
-
message: candidates.length > 0 ? `Remote registry has checkout candidates for ${repoSlug}, but none validated for ${alias}.` : `Remote registry has ${repoSlug}, but no server checkout path is linked yet.`,
|
|
750
|
-
skippedCandidates
|
|
751
|
-
});
|
|
752
|
-
}
|
|
753
|
-
} else if (registryResponse.status === 404) {
|
|
754
|
-
if (mode === "backfill-only") {
|
|
755
|
-
return remoteProjectLinkFailure({
|
|
756
|
-
status: "project_not_registered",
|
|
757
|
-
alias,
|
|
758
|
-
baseUrl,
|
|
759
|
-
repoSlug,
|
|
760
|
-
statusCode: registryResponse.status,
|
|
761
|
-
message: `Remote server ${alias} has no registered project record for ${repoSlug}.`
|
|
762
|
-
});
|
|
763
|
-
}
|
|
764
|
-
} else {
|
|
765
|
-
return remoteProjectLinkFailure({
|
|
766
|
-
status: "error",
|
|
767
|
-
alias,
|
|
768
|
-
baseUrl,
|
|
769
|
-
repoSlug,
|
|
770
|
-
statusCode: registryResponse.status,
|
|
771
|
-
message: `Could not backfill ${repoSlug} from remote registry (${registryResponse.status}): ${payloadError(registryResponse.payload, registryResponse.text || "registry lookup failed")}`,
|
|
772
|
-
skippedCandidates
|
|
773
|
-
});
|
|
774
|
-
}
|
|
775
|
-
let prepareResponse;
|
|
776
|
-
try {
|
|
777
|
-
prepareResponse = await requestRemoteProjectLinkJson(baseUrl, `/api/projects/${encodeURIComponent(repoSlug)}/prepare-checkout`, authToken, {
|
|
778
|
-
method: "POST",
|
|
779
|
-
headers: { "content-type": "application/json" },
|
|
780
|
-
body: JSON.stringify({ checkout: { kind: "managed-clone" }, repoUrl: `https://github.com/${repoSlug}.git` })
|
|
781
|
-
});
|
|
782
|
-
} catch (error) {
|
|
783
|
-
return remoteProjectLinkFailure({
|
|
784
|
-
status: "error",
|
|
785
|
-
alias,
|
|
786
|
-
baseUrl,
|
|
787
|
-
repoSlug,
|
|
788
|
-
message: `Could not prepare remote checkout for ${repoSlug} on ${alias}: ${error instanceof Error ? error.message : String(error)}`
|
|
789
|
-
});
|
|
790
|
-
}
|
|
791
|
-
if (prepareResponse.status === 401 || prepareResponse.status === 403) {
|
|
792
|
-
return remoteProjectLinkFailure({
|
|
793
|
-
status: "auth_required",
|
|
794
|
-
alias,
|
|
795
|
-
baseUrl,
|
|
796
|
-
repoSlug,
|
|
797
|
-
statusCode: prepareResponse.status,
|
|
798
|
-
message: `Remote server ${alias} requires authentication before preparing ${repoSlug}.`
|
|
799
|
-
});
|
|
800
|
-
}
|
|
801
|
-
if (!prepareResponse.ok) {
|
|
802
|
-
return remoteProjectLinkFailure({
|
|
803
|
-
status: "error",
|
|
804
|
-
alias,
|
|
805
|
-
baseUrl,
|
|
806
|
-
repoSlug,
|
|
807
|
-
statusCode: prepareResponse.status,
|
|
808
|
-
message: `Remote checkout prepare failed for ${repoSlug} (${prepareResponse.status}): ${payloadError(prepareResponse.payload, prepareResponse.text || "prepare-checkout failed")}`,
|
|
809
|
-
skippedCandidates
|
|
810
|
-
});
|
|
811
|
-
}
|
|
812
|
-
const preparedPath = checkoutPathFromPreparePayload(prepareResponse.payload);
|
|
813
|
-
if (!preparedPath) {
|
|
814
|
-
return remoteProjectLinkFailure({
|
|
815
|
-
status: "invalid_root",
|
|
816
|
-
alias,
|
|
817
|
-
baseUrl,
|
|
818
|
-
repoSlug,
|
|
819
|
-
message: `Remote checkout prepare for ${repoSlug} did not return a checkout.path.`,
|
|
820
|
-
skippedCandidates
|
|
821
|
-
});
|
|
822
|
-
}
|
|
823
|
-
return validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate: preparedPath, source: "prepare", prepared: true });
|
|
824
|
-
}
|
|
825
|
-
async function inspectRemoteProjectLink(projectRoot) {
|
|
826
|
-
return ensureRemoteProjectRootLink(projectRoot, { mode: "backfill-only" });
|
|
827
|
-
}
|
|
828
|
-
async function repairRemoteProjectRootLink(context, options = {}) {
|
|
829
|
-
const resolution = await ensureRemoteProjectRootLink(context.projectRoot, { mode: options.mode ?? "prepare-if-missing", repoSlug: options.repoSlug });
|
|
830
|
-
if (!resolution.ok)
|
|
831
|
-
throw new CliError(resolution.message, 1, { hint: resolution.hint });
|
|
832
|
-
return resolution;
|
|
833
|
-
}
|
|
834
|
-
async function ensureServerForCli(projectRoot) {
|
|
835
|
-
try {
|
|
836
|
-
const selected = resolveSelectedConnection(projectRoot);
|
|
837
|
-
if (selected?.connection.kind === "remote") {
|
|
838
|
-
reportServerPhase(`Connecting to ${selected.alias}\u2026`);
|
|
839
|
-
const authToken = readGitHubBearerTokenForRemote(projectRoot);
|
|
840
|
-
const link = await ensureRemoteProjectRootLink(projectRoot, { mode: "backfill-only", authToken });
|
|
841
|
-
return {
|
|
842
|
-
baseUrl: selected.connection.baseUrl,
|
|
843
|
-
authToken,
|
|
844
|
-
connectionKind: "remote",
|
|
845
|
-
serverProjectRoot: link.ok ? link.serverProjectRoot ?? null : null
|
|
846
|
-
};
|
|
847
|
-
}
|
|
848
|
-
reportServerPhase("Starting local Rig server\u2026");
|
|
849
|
-
const connection = await ensureLocalRigServerConnection(projectRoot);
|
|
850
|
-
return {
|
|
851
|
-
baseUrl: connection.baseUrl,
|
|
852
|
-
authToken: connection.authToken ?? readLocalConnectionFallbackToken(projectRoot),
|
|
853
|
-
connectionKind: "local",
|
|
854
|
-
serverProjectRoot: resolve2(projectRoot)
|
|
855
|
-
};
|
|
856
|
-
} catch (error) {
|
|
857
|
-
if (error instanceof Error) {
|
|
858
|
-
throw new CliError(error.message, 1);
|
|
859
|
-
}
|
|
860
|
-
throw error;
|
|
861
|
-
}
|
|
862
|
-
}
|
|
863
|
-
function appendTaskFilterParams(url, filters) {
|
|
864
|
-
if (filters.assignee)
|
|
865
|
-
url.searchParams.set("assignee", filters.assignee);
|
|
866
|
-
if (filters.state)
|
|
867
|
-
url.searchParams.set("state", filters.state);
|
|
868
|
-
if (filters.status)
|
|
869
|
-
url.searchParams.set("status", filters.status);
|
|
870
|
-
if (filters.limit !== undefined)
|
|
871
|
-
url.searchParams.set("limit", String(filters.limit));
|
|
872
|
-
}
|
|
873
|
-
function mergeCookie(existing, name, value) {
|
|
874
|
-
const encoded = `${name}=${encodeURIComponent(value)}`;
|
|
875
|
-
if (!existing?.trim())
|
|
876
|
-
return encoded;
|
|
877
|
-
const parts = existing.split(";").map((part) => part.trim()).filter((part) => part && !part.startsWith(`${name}=`));
|
|
878
|
-
return [...parts, encoded].join("; ");
|
|
879
|
-
}
|
|
880
|
-
function queryAuthFallbackEnabled(env = process.env) {
|
|
881
|
-
return env.RIG_ENABLE_QUERY_AUTH_FALLBACK === "1" || env.RIG_QUERY_AUTH_FALLBACK === "1";
|
|
882
|
-
}
|
|
883
|
-
function mergeHeaders(headers, authToken) {
|
|
884
|
-
const merged = new Headers(headers);
|
|
885
|
-
if (authToken) {
|
|
886
|
-
const bearer = `Bearer ${authToken}`;
|
|
887
|
-
merged.set("authorization", bearer);
|
|
888
|
-
merged.set("x-auth", bearer);
|
|
889
|
-
merged.set("cookie", mergeCookie(merged.get("cookie"), "rig_auth", authToken));
|
|
890
|
-
}
|
|
891
|
-
return merged;
|
|
892
|
-
}
|
|
893
|
-
function diagnosticMessage(payload) {
|
|
894
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
895
|
-
return null;
|
|
896
|
-
const record = payload;
|
|
897
|
-
const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
|
|
898
|
-
const messages = diagnostics.flatMap((entry) => {
|
|
899
|
-
if (!entry || typeof entry !== "object" || Array.isArray(entry))
|
|
900
|
-
return [];
|
|
901
|
-
const diagnostic = entry;
|
|
902
|
-
const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
|
|
903
|
-
const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
|
|
904
|
-
return message ? [`${kind}: ${message}`] : [];
|
|
905
|
-
});
|
|
906
|
-
return messages.length > 0 ? messages.join("; ") : null;
|
|
907
|
-
}
|
|
908
|
-
async function probeServerReachability(baseUrl, authToken) {
|
|
909
|
-
try {
|
|
910
|
-
const response = await fetch(`${baseUrl.replace(/\/+$/, "")}/api/server/status`, {
|
|
911
|
-
headers: mergeHeaders(undefined, authToken),
|
|
912
|
-
signal: AbortSignal.timeout(1500)
|
|
913
|
-
});
|
|
914
|
-
return response.ok;
|
|
915
|
-
} catch {
|
|
916
|
-
return false;
|
|
917
|
-
}
|
|
918
|
-
}
|
|
919
|
-
function cachedServerReachability(projectRoot, baseUrl, authToken) {
|
|
920
|
-
const key = resolve2(projectRoot);
|
|
921
|
-
const cached = serverReachabilityCache.get(key);
|
|
922
|
-
if (cached)
|
|
923
|
-
return cached;
|
|
924
|
-
const probe = probeServerReachability(baseUrl, authToken);
|
|
925
|
-
serverReachabilityCache.set(key, probe);
|
|
926
|
-
return probe;
|
|
927
|
-
}
|
|
928
|
-
function describeSelectedServer(projectRoot, server) {
|
|
929
|
-
try {
|
|
930
|
-
const selected = resolveSelectedConnection(projectRoot);
|
|
931
|
-
if (selected) {
|
|
932
|
-
return {
|
|
933
|
-
alias: selected.alias,
|
|
934
|
-
target: selected.connection.kind === "remote" ? selected.connection.baseUrl : server.baseUrl
|
|
935
|
-
};
|
|
936
|
-
}
|
|
937
|
-
} catch {}
|
|
938
|
-
return { alias: server.connectionKind === "remote" ? "remote" : "local", target: server.baseUrl };
|
|
939
|
-
}
|
|
940
|
-
async function buildServerFailureContext(projectRoot, server) {
|
|
941
|
-
const { alias, target } = describeSelectedServer(projectRoot, server);
|
|
942
|
-
const reachable = await cachedServerReachability(projectRoot, server.baseUrl, server.authToken);
|
|
943
|
-
const reachability = reachable ? "server is reachable" : "server is unreachable";
|
|
944
|
-
return {
|
|
945
|
-
contextLine: `Currently connected to: ${alias} at ${target} (${reachability}).`,
|
|
946
|
-
hint: "Check the selected server with `rig server status`, or switch with `rig server use <alias|local>`."
|
|
947
|
-
};
|
|
948
|
-
}
|
|
949
|
-
function isLoopbackRemoteBaseUrl(baseUrl) {
|
|
950
|
-
try {
|
|
951
|
-
const host = new URL(baseUrl).hostname.toLowerCase();
|
|
952
|
-
return host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]";
|
|
953
|
-
} catch {
|
|
954
|
-
return false;
|
|
955
|
-
}
|
|
956
|
-
}
|
|
957
|
-
function canUseRemoteWithoutProjectRoot(pathname) {
|
|
958
|
-
return pathname === "/health" || pathname === "/api/health" || pathname === "/api/server/status" || pathname === "/api/server/project-root" || pathname.startsWith("/api/github/auth/") || pathname === "/api/projects" || pathname.startsWith("/api/projects/");
|
|
959
|
-
}
|
|
960
|
-
async function requestServerJson(context, pathname, init = {}) {
|
|
961
|
-
const server = await ensureServerForCli(context.projectRoot);
|
|
962
|
-
const requestUrl = new URL(`${server.baseUrl}${pathname}`);
|
|
963
|
-
let scopedServerProjectRoot = server.serverProjectRoot;
|
|
964
|
-
if (server.connectionKind === "remote" && !scopedServerProjectRoot && !canUseRemoteWithoutProjectRoot(requestUrl.pathname) && (server.authToken || !isLoopbackRemoteBaseUrl(server.baseUrl))) {
|
|
965
|
-
const link = await ensureRemoteProjectRootLink(context.projectRoot, { mode: "backfill-only", authToken: server.authToken });
|
|
966
|
-
if (link.ok && link.serverProjectRoot) {
|
|
967
|
-
scopedServerProjectRoot = link.serverProjectRoot;
|
|
968
|
-
} else {
|
|
969
|
-
const repo = readRepoConnection(context.projectRoot);
|
|
970
|
-
const target = link.alias && link.baseUrl ? `${link.alias} (${link.baseUrl})` : server.baseUrl;
|
|
971
|
-
throw new CliError(`Remote server ${target} is selected for ${link.repoSlug ?? repo?.project ?? "this repo"}, but this checkout has no server-host project root link. ${link.message}`, 1, { hint: link.hint });
|
|
972
|
-
}
|
|
973
|
-
}
|
|
974
|
-
const headers = mergeHeaders(init.headers, server.authToken);
|
|
975
|
-
if (scopedServerProjectRoot)
|
|
976
|
-
headers.set("x-rig-project-root", scopedServerProjectRoot);
|
|
977
|
-
if (server.connectionKind === "remote" && server.authToken && queryAuthFallbackEnabled()) {
|
|
978
|
-
requestUrl.searchParams.set("rt", server.authToken);
|
|
979
|
-
}
|
|
980
|
-
reportServerPhase(`${(init.method ?? "GET").toUpperCase()} ${pathname.split("?")[0]}\u2026`);
|
|
981
|
-
let response;
|
|
982
|
-
try {
|
|
983
|
-
response = await fetch(requestUrl, {
|
|
984
|
-
...init,
|
|
985
|
-
headers
|
|
986
|
-
});
|
|
987
|
-
} catch (error) {
|
|
988
|
-
const failure = await buildServerFailureContext(context.projectRoot, server);
|
|
989
|
-
throw new CliError(`Rig server request failed: ${error instanceof Error ? error.message : String(error)}
|
|
990
|
-
${failure.contextLine}`, 1, { hint: failure.hint });
|
|
991
|
-
}
|
|
992
|
-
const text = await response.text();
|
|
993
|
-
const payload = text.trim().length > 0 ? (() => {
|
|
994
|
-
try {
|
|
995
|
-
return JSON.parse(text);
|
|
996
|
-
} catch {
|
|
997
|
-
return null;
|
|
998
|
-
}
|
|
999
|
-
})() : null;
|
|
1000
|
-
if (!response.ok) {
|
|
1001
|
-
const diagnostics = diagnosticMessage(payload);
|
|
1002
|
-
const rawDetail = diagnostics ?? (text || response.statusText);
|
|
1003
|
-
const detail = diagnostics ? rawDetail : rawDetail.split(`
|
|
1004
|
-
`).map((line) => line.trim()).find((line) => line.length > 0)?.slice(0, 200) ?? response.statusText;
|
|
1005
|
-
const failure = await buildServerFailureContext(context.projectRoot, server);
|
|
1006
|
-
throw new CliError(`Rig server request failed (${response.status}): ${detail}
|
|
1007
|
-
${failure.contextLine}`, 1, { hint: failure.hint });
|
|
1008
|
-
}
|
|
1009
|
-
return payload;
|
|
1010
|
-
}
|
|
1011
|
-
async function listWorkspaceTasksViaServer(context, filters = {}) {
|
|
1012
|
-
const url = new URL("http://rig.local/api/workspace/tasks");
|
|
1013
|
-
appendTaskFilterParams(url, filters);
|
|
1014
|
-
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
1015
|
-
if (!Array.isArray(payload)) {
|
|
1016
|
-
throw new CliError("Rig server returned an invalid task list payload.", 1, { hint: "Check the selected server with `rig server status`; mixed CLI/server versions can mismatch \u2014 try `rig doctor`." });
|
|
1017
|
-
}
|
|
1018
|
-
return payload.flatMap((entry) => entry && typeof entry === "object" && !Array.isArray(entry) ? [entry] : []);
|
|
1019
|
-
}
|
|
1020
|
-
async function getWorkspaceTaskViaServer(context, taskId) {
|
|
1021
|
-
const payload = await requestServerJson(context, `/api/workspace/tasks/${encodeURIComponent(taskId)}`);
|
|
1022
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
1023
|
-
return null;
|
|
1024
|
-
const task = payload.task;
|
|
1025
|
-
return task && typeof task === "object" && !Array.isArray(task) ? task : null;
|
|
1026
|
-
}
|
|
1027
|
-
async function selectNextWorkspaceTaskViaServer(context, filters = {}) {
|
|
1028
|
-
const url = new URL("http://rig.local/api/workspace/tasks/next");
|
|
1029
|
-
appendTaskFilterParams(url, filters);
|
|
1030
|
-
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
1031
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
1032
|
-
throw new CliError("Rig server returned an invalid next-task payload.", 1, { hint: "Check the selected server with `rig server status`; try `rig task list` to see the raw task set." });
|
|
1033
|
-
}
|
|
1034
|
-
const record = payload;
|
|
1035
|
-
const rawTask = record.task;
|
|
1036
|
-
const task = rawTask && typeof rawTask === "object" && !Array.isArray(rawTask) ? rawTask : null;
|
|
1037
|
-
const count = typeof record.count === "number" && Number.isFinite(record.count) ? record.count : task ? 1 : 0;
|
|
1038
|
-
return { task, count };
|
|
1039
|
-
}
|
|
1040
|
-
async function getGitHubAuthStatusViaServer(context) {
|
|
1041
|
-
const payload = await requestServerJson(context, "/api/github/auth/status");
|
|
1042
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
1043
|
-
}
|
|
1044
|
-
async function postGitHubTokenViaServer(context, token, options = {}) {
|
|
1045
|
-
const server = await ensureServerForCli(context.projectRoot);
|
|
1046
|
-
const requestUrl = new URL(`${server.baseUrl}/api/github/auth/token`);
|
|
1047
|
-
reportServerPhase("POST /api/github/auth/token\u2026");
|
|
1048
|
-
let response;
|
|
1049
|
-
try {
|
|
1050
|
-
response = await fetch(requestUrl, {
|
|
1051
|
-
method: "POST",
|
|
1052
|
-
headers: { "content-type": "application/json" },
|
|
1053
|
-
body: JSON.stringify({ token, selectedRepo: options.selectedRepo, projectRoot: options.projectRoot ?? server.serverProjectRoot ?? undefined })
|
|
1054
|
-
});
|
|
1055
|
-
} catch (error) {
|
|
1056
|
-
const failure = await buildServerFailureContext(context.projectRoot, server);
|
|
1057
|
-
throw new CliError(`Rig server auth bootstrap failed: ${error instanceof Error ? error.message : String(error)}
|
|
1058
|
-
${failure.contextLine}`, 1, { hint: failure.hint });
|
|
1059
|
-
}
|
|
1060
|
-
const payload = await response.json().catch(() => null);
|
|
1061
|
-
if (!response.ok) {
|
|
1062
|
-
const detail = payload && typeof payload === "object" && !Array.isArray(payload) ? String(payload.error ?? JSON.stringify(payload)) : `HTTP ${response.status}`;
|
|
1063
|
-
throw new CliError(`Rig server auth bootstrap failed (${response.status}): ${detail}`, 1, { hint: "Re-run `rig github auth import-gh`, or check the selected server with `rig server status`." });
|
|
1064
|
-
}
|
|
1065
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
1066
|
-
}
|
|
1067
|
-
async function prepareRemoteCheckoutViaServer(context, input) {
|
|
1068
|
-
const payload = await requestServerJson(context, `/api/projects/${encodeURIComponent(input.repoSlug)}/prepare-checkout`, {
|
|
1069
|
-
method: "POST",
|
|
1070
|
-
headers: { "content-type": "application/json" },
|
|
1071
|
-
body: JSON.stringify({ checkout: input.checkout, repoUrl: input.repoUrl, baseDir: input.baseDir })
|
|
1072
|
-
});
|
|
1073
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
1074
|
-
}
|
|
1075
|
-
async function registerProjectViaServer(context, input) {
|
|
1076
|
-
const payload = await requestServerJson(context, "/api/projects", {
|
|
1077
|
-
method: "POST",
|
|
1078
|
-
headers: { "content-type": "application/json" },
|
|
1079
|
-
body: JSON.stringify(input)
|
|
1080
|
-
});
|
|
1081
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
1082
|
-
}
|
|
1083
|
-
function sleep(ms) {
|
|
1084
|
-
return new Promise((resolve3) => setTimeout(resolve3, ms));
|
|
1085
|
-
}
|
|
1086
|
-
function isRetryableProjectRootSwitchError(error) {
|
|
1087
|
-
if (!(error instanceof Error))
|
|
1088
|
-
return false;
|
|
1089
|
-
const message = error.message.toLowerCase();
|
|
1090
|
-
return message.includes("rig server request failed (401): auth-required") || message.includes("rig server request failed (401): github-token-required") || message.includes("rig server request failed (502)") || message.includes("rig server request failed (503)") || message.includes("bad gateway") || message.includes("fetch failed") || message.includes("econnrefused") || message.includes("connection refused");
|
|
1091
|
-
}
|
|
1092
|
-
async function switchServerProjectRootViaServer(context, projectRoot, options = {}) {
|
|
1093
|
-
const timeoutMs = options.timeoutMs ?? 30000;
|
|
1094
|
-
const pollMs = options.pollMs ?? 1000;
|
|
1095
|
-
const deadline = Date.now() + timeoutMs;
|
|
1096
|
-
let lastError;
|
|
1097
|
-
let switched = null;
|
|
1098
|
-
while (Date.now() < deadline) {
|
|
1099
|
-
try {
|
|
1100
|
-
switched = await requestServerJson(context, "/api/server/project-root", {
|
|
1101
|
-
method: "POST",
|
|
1102
|
-
headers: { "content-type": "application/json" },
|
|
1103
|
-
body: JSON.stringify({ projectRoot })
|
|
1104
|
-
});
|
|
1105
|
-
break;
|
|
1106
|
-
} catch (error) {
|
|
1107
|
-
lastError = error;
|
|
1108
|
-
if (!isRetryableProjectRootSwitchError(error))
|
|
1109
|
-
throw error;
|
|
1110
|
-
await sleep(pollMs);
|
|
1111
|
-
}
|
|
1112
|
-
}
|
|
1113
|
-
if (!switched) {
|
|
1114
|
-
throw new CliError(`Rig server did not accept project-root switch to ${projectRoot} before timeout (${lastError instanceof Error ? lastError.message : String(lastError ?? "no response")}).`, 1);
|
|
1115
|
-
}
|
|
1116
|
-
const record = switched && typeof switched === "object" && !Array.isArray(switched) ? switched : {};
|
|
1117
|
-
if (record.ok === true) {
|
|
1118
|
-
writeRepoServerProjectRoot(context.projectRoot, projectRoot);
|
|
1119
|
-
return { ok: true, switched: record };
|
|
1120
|
-
}
|
|
1121
|
-
throw new CliError(`Rig server rejected project-root scope ${projectRoot}: ${String(record.message ?? record.error ?? "unknown error")}`, 1);
|
|
1122
|
-
}
|
|
1123
|
-
async function listRunsViaServer(context, options = {}) {
|
|
1124
|
-
const url = new URL("http://rig.local/api/runs");
|
|
1125
|
-
if (options.limit !== undefined)
|
|
1126
|
-
url.searchParams.set("limit", String(options.limit));
|
|
1127
|
-
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
1128
|
-
const runs = Array.isArray(payload) ? payload : payload && typeof payload === "object" && !Array.isArray(payload) && Array.isArray(payload.runs) ? payload.runs : [];
|
|
1129
|
-
return runs.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry)));
|
|
1130
|
-
}
|
|
1131
|
-
async function getRunDetailsViaServer(context, runId) {
|
|
1132
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}`);
|
|
1133
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
1134
|
-
}
|
|
1135
|
-
async function getRunLogsViaServer(context, runId, options = {}) {
|
|
1136
|
-
const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/logs`);
|
|
1137
|
-
if (options.limit !== undefined)
|
|
1138
|
-
url.searchParams.set("limit", String(options.limit));
|
|
1139
|
-
if (options.cursor)
|
|
1140
|
-
url.searchParams.set("cursor", options.cursor);
|
|
1141
|
-
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
1142
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
|
|
1143
|
-
}
|
|
1144
|
-
async function getRunTimelineViaServer(context, runId, options = {}) {
|
|
1145
|
-
const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/timeline`);
|
|
1146
|
-
if (options.limit !== undefined)
|
|
1147
|
-
url.searchParams.set("limit", String(options.limit));
|
|
1148
|
-
if (options.cursor)
|
|
1149
|
-
url.searchParams.set("cursor", options.cursor);
|
|
1150
|
-
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
1151
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
|
|
1152
|
-
}
|
|
1153
|
-
async function ensureTaskLabelsViaServer(context) {
|
|
1154
|
-
const payload = await requestServerJson(context, "/api/workspace/task-labels", { method: "POST" });
|
|
1155
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
1156
|
-
}
|
|
1157
|
-
async function listGitHubProjectsViaServer(context, owner) {
|
|
1158
|
-
const url = new URL("http://rig.local/api/github/projects");
|
|
1159
|
-
url.searchParams.set("owner", owner);
|
|
1160
|
-
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
1161
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { projects: [] };
|
|
1162
|
-
}
|
|
1163
|
-
async function getGitHubProjectStatusFieldViaServer(context, projectId) {
|
|
1164
|
-
const payload = await requestServerJson(context, `/api/github/projects/${encodeURIComponent(projectId)}/status-field`);
|
|
1165
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
1166
|
-
}
|
|
1167
|
-
async function updateWorkspaceTaskViaServer(context, input) {
|
|
1168
|
-
const payload = await requestServerJson(context, "/api/tasks/update", {
|
|
1169
|
-
method: "POST",
|
|
1170
|
-
headers: { "content-type": "application/json" },
|
|
1171
|
-
body: JSON.stringify(input)
|
|
1172
|
-
});
|
|
1173
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
|
|
1174
|
-
}
|
|
1175
|
-
async function resumeRunViaServer(context, runId, options) {
|
|
1176
|
-
let targetRunId = runId?.trim() || null;
|
|
1177
|
-
if (!targetRunId) {
|
|
1178
|
-
const candidates = (await listRunsViaServer(context)).filter((run) => RESUMABLE_RUN_STATUSES.has(String(run.status ?? ""))).sort((left, right) => String(right.updatedAt ?? "").localeCompare(String(left.updatedAt ?? "")));
|
|
1179
|
-
targetRunId = typeof candidates[0]?.runId === "string" ? candidates[0].runId : null;
|
|
1180
|
-
}
|
|
1181
|
-
if (!targetRunId) {
|
|
1182
|
-
throw new CliError(options.restart ? "No run is available to restart." : "No resumable run is available.", 2, { hint: "List runs with `rig run list`, then pass an explicit id: `rig run resume <run-id>`." });
|
|
1183
|
-
}
|
|
1184
|
-
const payload = await requestServerJson(context, "/api/runs/resume", {
|
|
1185
|
-
method: "POST",
|
|
1186
|
-
headers: { "content-type": "application/json" },
|
|
1187
|
-
body: JSON.stringify({ runId: targetRunId, createdAt: new Date().toISOString(), restart: options.restart })
|
|
1188
|
-
});
|
|
1189
|
-
const record = payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
1190
|
-
if (record.ok === false) {
|
|
1191
|
-
const message = typeof record.error === "string" && record.error.trim() ? record.error : "run resume failed";
|
|
1192
|
-
throw new CliError(`${options.restart ? "restart" : "resume"} failed for ${targetRunId}: ${message}`, 1);
|
|
1193
|
-
}
|
|
1194
|
-
return { ok: true, runId: targetRunId, ...record };
|
|
1195
|
-
}
|
|
1196
|
-
async function resolveServerConnectionLabel(projectRoot) {
|
|
1197
|
-
try {
|
|
1198
|
-
const selected = resolveSelectedConnection(projectRoot);
|
|
1199
|
-
if (!selected)
|
|
1200
|
-
return "no server selected";
|
|
1201
|
-
if (selected.connection.kind === "remote") {
|
|
1202
|
-
return selected.connection.baseUrl.replace(/^https?:\/\//, "");
|
|
1203
|
-
}
|
|
1204
|
-
return `local (${selected.alias})`;
|
|
1205
|
-
} catch {
|
|
1206
|
-
return "no server selected";
|
|
1207
|
-
}
|
|
1208
|
-
}
|
|
1209
|
-
async function stopRunViaServer(context, runId) {
|
|
1210
|
-
const payload = await requestServerJson(context, "/api/runs/stop", {
|
|
1211
|
-
method: "POST",
|
|
1212
|
-
headers: { "content-type": "application/json" },
|
|
1213
|
-
body: JSON.stringify({ runId })
|
|
1214
|
-
});
|
|
1215
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true, runId };
|
|
1216
|
-
}
|
|
1217
|
-
async function steerRunViaServer(context, runId, message) {
|
|
1218
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/steer`, {
|
|
1219
|
-
method: "POST",
|
|
1220
|
-
headers: { "content-type": "application/json" },
|
|
1221
|
-
body: JSON.stringify({ message })
|
|
1222
|
-
});
|
|
1223
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
|
|
1224
|
-
}
|
|
1225
|
-
async function getRunPiSessionViaServer(context, runId) {
|
|
1226
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi`);
|
|
1227
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
1228
|
-
}
|
|
1229
|
-
async function getRunPiMessagesViaServer(context, runId) {
|
|
1230
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/messages`);
|
|
1231
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { messages: [] };
|
|
1232
|
-
}
|
|
1233
|
-
async function getRunPiStatusViaServer(context, runId) {
|
|
1234
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/status`);
|
|
1235
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
1236
|
-
}
|
|
1237
|
-
async function getRunPiCommandsViaServer(context, runId) {
|
|
1238
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands`);
|
|
1239
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { commands: [] };
|
|
1240
|
-
}
|
|
1241
|
-
async function getRunPiCapabilitiesViaServer(context, runId) {
|
|
1242
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/capabilities`);
|
|
1243
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { capabilities: null };
|
|
1244
|
-
}
|
|
1245
|
-
async function sendRunPiPromptViaServer(context, runId, text, streamingBehavior) {
|
|
1246
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/prompt`, {
|
|
1247
|
-
method: "POST",
|
|
1248
|
-
headers: { "content-type": "application/json" },
|
|
1249
|
-
body: JSON.stringify({ text, streamingBehavior })
|
|
1250
|
-
});
|
|
1251
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
1252
|
-
}
|
|
1253
|
-
async function sendRunPiShellViaServer(context, runId, text) {
|
|
1254
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/shell`, {
|
|
1255
|
-
method: "POST",
|
|
1256
|
-
headers: { "content-type": "application/json" },
|
|
1257
|
-
body: JSON.stringify({ text })
|
|
1258
|
-
});
|
|
1259
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
1260
|
-
}
|
|
1261
|
-
async function runRunPiCommandViaServer(context, runId, text) {
|
|
1262
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands/run`, {
|
|
1263
|
-
method: "POST",
|
|
1264
|
-
headers: { "content-type": "application/json" },
|
|
1265
|
-
body: JSON.stringify({ text })
|
|
1266
|
-
});
|
|
1267
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { type: "done" };
|
|
1268
|
-
}
|
|
1269
|
-
async function respondRunPiExtensionUiViaServer(context, runId, requestId, valueOrCancel) {
|
|
1270
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/extension-ui/respond`, {
|
|
1271
|
-
method: "POST",
|
|
1272
|
-
headers: { "content-type": "application/json" },
|
|
1273
|
-
body: JSON.stringify({ requestId, ...valueOrCancel })
|
|
1274
|
-
});
|
|
1275
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
1276
|
-
}
|
|
1277
|
-
async function abortRunPiViaServer(context, runId) {
|
|
1278
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/abort`, { method: "POST" });
|
|
1279
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { aborted: true };
|
|
1280
|
-
}
|
|
1281
|
-
async function buildRunPiEventsWebSocketUrl(context, runId) {
|
|
1282
|
-
const server = await ensureServerForCli(context.projectRoot);
|
|
1283
|
-
const url = new URL(`${server.baseUrl.replace(/\/+$/, "")}/api/runs/${encodeURIComponent(runId)}/pi/events`);
|
|
1284
|
-
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
1285
|
-
if (server.authToken)
|
|
1286
|
-
url.searchParams.set("token", server.authToken);
|
|
1287
|
-
if (server.serverProjectRoot)
|
|
1288
|
-
url.searchParams.set("rigProjectRoot", server.serverProjectRoot);
|
|
1289
|
-
return url.toString();
|
|
1290
|
-
}
|
|
1291
|
-
async function submitTaskRunViaServer(context, input) {
|
|
1292
|
-
const isTaskRun = Boolean(input.taskId);
|
|
1293
|
-
const endpoint = isTaskRun ? "/api/runs/task" : "/api/runs/adhoc";
|
|
1294
|
-
const payload = await requestServerJson(context, endpoint, {
|
|
1295
|
-
method: "POST",
|
|
1296
|
-
headers: {
|
|
1297
|
-
"content-type": "application/json"
|
|
1298
|
-
},
|
|
1299
|
-
body: JSON.stringify({
|
|
1300
|
-
runId: input.runId,
|
|
1301
|
-
taskId: input.taskId,
|
|
1302
|
-
title: input.title,
|
|
1303
|
-
runtimeAdapter: input.runtimeAdapter,
|
|
1304
|
-
model: input.model,
|
|
1305
|
-
runtimeMode: input.runtimeMode,
|
|
1306
|
-
interactionMode: input.interactionMode,
|
|
1307
|
-
initialPrompt: input.initialPrompt,
|
|
1308
|
-
baselineMode: input.baselineMode,
|
|
1309
|
-
prMode: input.prMode,
|
|
1310
|
-
executionTarget: "local"
|
|
1311
|
-
})
|
|
1312
|
-
});
|
|
1313
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
1314
|
-
throw new CliError("Rig server returned an invalid run submission payload.", 1, { hint: "Check `rig server status` and retry; `rig run list` shows whether the run was created anyway." });
|
|
1315
|
-
}
|
|
1316
|
-
const runId = payload.runId;
|
|
1317
|
-
if (typeof runId !== "string" || runId.trim().length === 0) {
|
|
1318
|
-
throw new CliError("Rig server returned no runId for the submitted run.", 1, { hint: "Check `rig run list` \u2014 the run may still have been created; otherwise retry the submission." });
|
|
1319
|
-
}
|
|
1320
|
-
return { runId };
|
|
1321
|
-
}
|
|
1322
|
-
var scopedGitHubBearerTokens, serverPhaseListener = null, serverReachabilityCache, RESUMABLE_RUN_STATUSES;
|
|
1323
|
-
var init__server_client = __esm(() => {
|
|
1324
|
-
init_runner();
|
|
1325
|
-
init__connection_state();
|
|
1326
|
-
scopedGitHubBearerTokens = new Map;
|
|
1327
|
-
serverReachabilityCache = new Map;
|
|
1328
|
-
RESUMABLE_RUN_STATUSES = new Set([
|
|
1329
|
-
"created",
|
|
1330
|
-
"preparing",
|
|
1331
|
-
"running",
|
|
1332
|
-
"validating",
|
|
1333
|
-
"reviewing",
|
|
1334
|
-
"stopped",
|
|
1335
|
-
"failed",
|
|
1336
|
-
"needs-attention",
|
|
1337
|
-
"needs_attention"
|
|
1338
|
-
]);
|
|
1339
|
-
});
|
|
1340
|
-
|
|
1341
|
-
// packages/cli/src/app/theme.ts
|
|
1342
|
-
function hexToRgb(hex) {
|
|
1343
|
-
const value = hex.replace("#", "");
|
|
1344
|
-
return [
|
|
1345
|
-
Number.parseInt(value.slice(0, 2), 16),
|
|
1346
|
-
Number.parseInt(value.slice(2, 4), 16),
|
|
1347
|
-
Number.parseInt(value.slice(4, 6), 16)
|
|
1348
|
-
];
|
|
1349
|
-
}
|
|
1350
|
-
function fg(hex) {
|
|
1351
|
-
const [r, g, b] = hexToRgb(hex);
|
|
1352
|
-
return (text) => `\x1B[38;2;${r};${g};${b}m${text}\x1B[39m`;
|
|
1353
|
-
}
|
|
1354
|
-
function bold(text) {
|
|
1355
|
-
return `\x1B[1m${text}\x1B[22m`;
|
|
1356
|
-
}
|
|
1357
|
-
function microDroneFrame(tick) {
|
|
1358
|
-
const blade = MICRO_BLADES[tick % MICRO_BLADES.length];
|
|
1359
|
-
const eye = EYE_FRAMES[Math.floor(tick / 2) % EYE_FRAMES.length];
|
|
1360
|
-
return `(${blade})${eye}(${blade})`;
|
|
1361
|
-
}
|
|
1362
|
-
function renderMicroDroneFrame(tick) {
|
|
1363
|
-
const blade = MICRO_BLADES[tick % MICRO_BLADES.length];
|
|
1364
|
-
const eye = EYE_FRAMES[Math.floor(tick / 2) % EYE_FRAMES.length];
|
|
1365
|
-
return `${ink4("(")}${cyan(blade)}${ink4(")")}${bold(accent(eye))}${ink4("(")}${cyan(blade)}${ink4(")")}`;
|
|
1366
|
-
}
|
|
1367
|
-
var RIG_PALETTE, ink, ink2, ink3, ink4, accent, accentDim, cyan, red, yellow, DRONE_ART, EYE_FRAMES, DRONE_WIDTH, DRONE_HEIGHT, MICRO_BLADES, MICRO_DRONE_FRAMES;
|
|
1368
|
-
var init_theme = __esm(() => {
|
|
1369
|
-
RIG_PALETTE = {
|
|
1370
|
-
ink: "#f2f3f6",
|
|
1371
|
-
ink2: "#aeb0ba",
|
|
1372
|
-
ink3: "#6c6e79",
|
|
1373
|
-
ink4: "#44464f",
|
|
1374
|
-
accent: "#ccff4d",
|
|
1375
|
-
accentDim: "#a9d63f",
|
|
1376
|
-
cyan: "#56d8ff",
|
|
1377
|
-
red: "#ff5d5d",
|
|
1378
|
-
yellow: "#ffd24d"
|
|
1379
|
-
};
|
|
1380
|
-
ink = fg(RIG_PALETTE.ink);
|
|
1381
|
-
ink2 = fg(RIG_PALETTE.ink2);
|
|
1382
|
-
ink3 = fg(RIG_PALETTE.ink3);
|
|
1383
|
-
ink4 = fg(RIG_PALETTE.ink4);
|
|
1384
|
-
accent = fg(RIG_PALETTE.accent);
|
|
1385
|
-
accentDim = fg(RIG_PALETTE.accentDim);
|
|
1386
|
-
cyan = fg(RIG_PALETTE.cyan);
|
|
1387
|
-
red = fg(RIG_PALETTE.red);
|
|
1388
|
-
yellow = fg(RIG_PALETTE.yellow);
|
|
1389
|
-
DRONE_ART = [
|
|
1390
|
-
" .-=-. .-=-. ",
|
|
1391
|
-
" ( !!! ) ( !!! ) ",
|
|
1392
|
-
" '-=-'._ _.'-=-' ",
|
|
1393
|
-
" '._ _.' ",
|
|
1394
|
-
" '=$$$$$$$=.' ",
|
|
1395
|
-
" =$$$$$$$$$$$= ",
|
|
1396
|
-
" $$$@@@@@@@@@@$$$ ",
|
|
1397
|
-
" $$$@@ @@$$$ ",
|
|
1398
|
-
" $$@ ? @$$$ ",
|
|
1399
|
-
" $$$@ '-' @$$$ ",
|
|
1400
|
-
" $$$@@ @@$$$ ",
|
|
1401
|
-
" $$$@@@@@@@@@@$$$ ",
|
|
1402
|
-
" =$$$$$$$$$$$= ",
|
|
1403
|
-
" '=$$$$$$$=.' ",
|
|
1404
|
-
" _.' '._ ",
|
|
1405
|
-
" .-=-.' '.-=-. ",
|
|
1406
|
-
" ( !!! ) ( !!! ) ",
|
|
1407
|
-
" '-=-' '-=-' "
|
|
1408
|
-
];
|
|
1409
|
-
EYE_FRAMES = ["@", "o", "."];
|
|
1410
|
-
DRONE_WIDTH = DRONE_ART[0].length;
|
|
1411
|
-
DRONE_HEIGHT = DRONE_ART.length;
|
|
1412
|
-
MICRO_BLADES = ["---", "\\\\\\", "|||", "///"];
|
|
1413
|
-
MICRO_DRONE_FRAMES = Array.from({ length: 12 }, (_, index) => microDroneFrame(index));
|
|
1414
|
-
});
|
|
1415
|
-
|
|
1416
|
-
// packages/cli/src/commands/_spinner.ts
|
|
1417
|
-
function createTtySpinner(input) {
|
|
1418
|
-
const output = input.output ?? process.stdout;
|
|
1419
|
-
const isTty = output.isTTY === true;
|
|
1420
|
-
const frames = input.frames && input.frames.length > 0 ? input.frames : SPINNER_FRAMES;
|
|
1421
|
-
let label = input.label;
|
|
1422
|
-
let frame = 0;
|
|
1423
|
-
let paused = false;
|
|
1424
|
-
let stopped = false;
|
|
1425
|
-
let lastPrintedLabel = "";
|
|
1426
|
-
const render = () => {
|
|
1427
|
-
if (stopped || paused)
|
|
1428
|
-
return;
|
|
1429
|
-
if (!isTty) {
|
|
1430
|
-
if (label !== lastPrintedLabel) {
|
|
1431
|
-
output.write(`${label}
|
|
1432
|
-
`);
|
|
1433
|
-
lastPrintedLabel = label;
|
|
1434
|
-
}
|
|
1435
|
-
return;
|
|
1436
|
-
}
|
|
1437
|
-
frame = (frame + 1) % frames.length;
|
|
1438
|
-
const glyph = frames[frame] ?? frames[0] ?? "";
|
|
1439
|
-
output.write(`\r\x1B[2K${input.styleFrame ? input.styleFrame(glyph) : glyph} ${label}`);
|
|
1440
|
-
};
|
|
1441
|
-
const clearLine = () => {
|
|
1442
|
-
if (isTty)
|
|
1443
|
-
output.write("\r\x1B[2K");
|
|
1444
|
-
};
|
|
1445
|
-
render();
|
|
1446
|
-
const timer = isTty ? setInterval(render, input.intervalMs ?? 16) : null;
|
|
1447
|
-
return {
|
|
1448
|
-
setLabel(next) {
|
|
1449
|
-
label = next;
|
|
1450
|
-
render();
|
|
1451
|
-
},
|
|
1452
|
-
pause() {
|
|
1453
|
-
paused = true;
|
|
1454
|
-
clearLine();
|
|
1455
|
-
},
|
|
1456
|
-
resume() {
|
|
1457
|
-
if (stopped)
|
|
1458
|
-
return;
|
|
1459
|
-
paused = false;
|
|
1460
|
-
render();
|
|
1461
|
-
},
|
|
1462
|
-
stop(finalLine) {
|
|
1463
|
-
if (stopped)
|
|
1464
|
-
return;
|
|
1465
|
-
stopped = true;
|
|
1466
|
-
if (timer)
|
|
1467
|
-
clearInterval(timer);
|
|
1468
|
-
clearLine();
|
|
1469
|
-
if (finalLine)
|
|
1470
|
-
output.write(`${finalLine}
|
|
1471
|
-
`);
|
|
1472
|
-
}
|
|
1473
|
-
};
|
|
1474
|
-
}
|
|
1475
|
-
var SPINNER_FRAMES;
|
|
1476
|
-
var init__spinner = __esm(() => {
|
|
1477
|
-
SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
|
|
1478
|
-
});
|
|
1479
|
-
|
|
1480
|
-
// packages/cli/src/app/drone-ui.ts
|
|
1481
|
-
import { ProcessTerminal, TUI, Text, Input, SelectList, matchesKey } from "@earendil-works/pi-tui";
|
|
1482
|
-
function droneNote(message, title) {
|
|
1483
|
-
if (title)
|
|
1484
|
-
console.log(` ${accentDim("\u25C7")} ${bold(ink2(title))}`);
|
|
1485
|
-
for (const line of message.split(`
|
|
1486
|
-
`)) {
|
|
1487
|
-
console.log(` ${ink4("\u2502")} ${line}`);
|
|
1488
|
-
}
|
|
1489
|
-
}
|
|
1490
|
-
function droneCancel(text) {
|
|
1491
|
-
console.log(` ${red("\u2716")} ${ink3(text)}`);
|
|
1492
|
-
}
|
|
1493
|
-
async function runMiniTui(build) {
|
|
1494
|
-
const terminal = new ProcessTerminal;
|
|
1495
|
-
const tui = new TUI(terminal);
|
|
1496
|
-
let settled = false;
|
|
1497
|
-
return await new Promise((resolve3) => {
|
|
1498
|
-
const finish = (result) => {
|
|
1499
|
-
if (settled)
|
|
1500
|
-
return;
|
|
1501
|
-
settled = true;
|
|
1502
|
-
tui.stop();
|
|
1503
|
-
resolve3(result);
|
|
1504
|
-
};
|
|
1505
|
-
build(tui, finish);
|
|
1506
|
-
tui.start();
|
|
1507
|
-
});
|
|
1508
|
-
}
|
|
1509
|
-
async function droneSelect(input) {
|
|
1510
|
-
if (!isTty() || input.options.length === 0) {
|
|
1511
|
-
return input.initialValue ?? input.options[0]?.value ?? null;
|
|
1512
|
-
}
|
|
1513
|
-
return runMiniTui((tui, finish) => {
|
|
1514
|
-
tui.addChild(new Text(` ${accent("\u258D")}${bold(ink(input.message))}`));
|
|
1515
|
-
const items = input.options.map((option) => ({
|
|
1516
|
-
value: option.value,
|
|
1517
|
-
label: option.label,
|
|
1518
|
-
...option.hint ? { description: option.hint } : {}
|
|
1519
|
-
}));
|
|
1520
|
-
const list = new SelectList(items, Math.min(items.length, 12), SELECT_THEME);
|
|
1521
|
-
const initialIndex = input.initialValue ? items.findIndex((item) => item.value === input.initialValue) : -1;
|
|
1522
|
-
if (initialIndex > 0)
|
|
1523
|
-
list.setSelectedIndex(initialIndex);
|
|
1524
|
-
list.onSelect = (item) => finish(item.value);
|
|
1525
|
-
list.onCancel = () => finish(null);
|
|
1526
|
-
tui.addChild(list);
|
|
1527
|
-
tui.addChild(new Text(ink4(" \u2191\u2193 navigate \xB7 enter select \xB7 esc cancel")));
|
|
1528
|
-
tui.setFocus(list);
|
|
1529
|
-
tui.addInputListener((data) => {
|
|
1530
|
-
if (matchesKey(data, "ctrl+c") || matchesKey(data, "escape")) {
|
|
1531
|
-
finish(null);
|
|
1532
|
-
return { consume: true };
|
|
1533
|
-
}
|
|
1534
|
-
return;
|
|
1535
|
-
});
|
|
1536
|
-
});
|
|
1537
|
-
}
|
|
1538
|
-
async function droneConfirm(input) {
|
|
1539
|
-
const answer = await droneSelect({
|
|
1540
|
-
message: input.message,
|
|
1541
|
-
options: [
|
|
1542
|
-
{ value: "yes", label: "Yes" },
|
|
1543
|
-
{ value: "no", label: "No" }
|
|
1544
|
-
],
|
|
1545
|
-
initialValue: input.initialValue === false ? "no" : "yes"
|
|
1546
|
-
});
|
|
1547
|
-
return answer === null ? null : answer === "yes";
|
|
1548
|
-
}
|
|
1549
|
-
var isTty = () => Boolean(process.stdout.isTTY), SELECT_THEME;
|
|
1550
|
-
var init_drone_ui = __esm(() => {
|
|
1551
|
-
init_theme();
|
|
1552
|
-
init__spinner();
|
|
1553
|
-
SELECT_THEME = {
|
|
1554
|
-
selectedPrefix: (text) => accent(text),
|
|
1555
|
-
selectedText: (text) => bold(ink(text)),
|
|
1556
|
-
description: (text) => ink3(text),
|
|
1557
|
-
scrollInfo: (text) => ink4(text),
|
|
1558
|
-
noMatch: (text) => ink3(text)
|
|
1559
|
-
};
|
|
1560
|
-
});
|
|
1561
|
-
|
|
1562
|
-
// packages/cli/src/commands/_paths.ts
|
|
1563
|
-
import { resolveMonorepoRoot } from "@rig/runtime/control-plane/native/utils";
|
|
1564
|
-
var init__paths = () => {};
|
|
1565
|
-
|
|
1566
|
-
// packages/cli/src/commands/_authority-runs.ts
|
|
1567
|
-
import {
|
|
1568
|
-
readAuthorityRun,
|
|
1569
|
-
readJsonlFile,
|
|
1570
|
-
writeAuthorityRunRecord
|
|
1571
|
-
} from "@rig/runtime/control-plane/authority-files";
|
|
1572
|
-
function normalizeRuntimeAdapter(_value) {
|
|
1573
|
-
return "pi";
|
|
1574
|
-
}
|
|
1575
|
-
var init__authority_runs = __esm(() => {
|
|
1576
|
-
init__paths();
|
|
1577
|
-
});
|
|
1578
|
-
|
|
1579
|
-
// packages/cli/src/commands/_preflight.ts
|
|
1580
|
-
import { ensureProjectMainFreshBeforeRun } from "@rig/runtime/control-plane/project-main-pre-run-sync";
|
|
1581
|
-
function preflightCheck(id, label, status, detail, remediation) {
|
|
1582
|
-
return {
|
|
1583
|
-
id,
|
|
1584
|
-
label,
|
|
1585
|
-
status,
|
|
1586
|
-
...detail ? { detail } : {},
|
|
1587
|
-
...remediation ? { remediation } : {}
|
|
1588
|
-
};
|
|
1589
|
-
}
|
|
1590
|
-
function message(error) {
|
|
1591
|
-
return error instanceof Error ? error.message : String(error);
|
|
1592
|
-
}
|
|
1593
|
-
function isAuthenticated(payload) {
|
|
1594
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
1595
|
-
return false;
|
|
1596
|
-
const record = payload;
|
|
1597
|
-
return record.signedIn === true || record.authenticated === true || record.status === "authenticated" || record.ok === true && typeof record.login === "string" && record.login.trim().length > 0;
|
|
1598
|
-
}
|
|
1599
|
-
function taskMatchesId(entry, taskId) {
|
|
1600
|
-
if (!entry || typeof entry !== "object" || Array.isArray(entry))
|
|
1601
|
-
return false;
|
|
1602
|
-
const record = entry;
|
|
1603
|
-
if (record.id === taskId || record.taskId === taskId)
|
|
1604
|
-
return true;
|
|
1605
|
-
const raw = record.raw;
|
|
1606
|
-
if (raw && typeof raw === "object" && !Array.isArray(raw)) {
|
|
1607
|
-
const rawRecord = raw;
|
|
1608
|
-
if (String(rawRecord.number ?? "") === taskId.replace(/^#/, ""))
|
|
1609
|
-
return true;
|
|
1610
|
-
}
|
|
1611
|
-
return false;
|
|
1612
|
-
}
|
|
1613
|
-
function isActiveRunStatus(status) {
|
|
1614
|
-
const normalized = String(status ?? "running").toLowerCase();
|
|
1615
|
-
return !["completed", "complete", "done", "merged", "closed", "failed", "cancelled", "canceled", "needs_attention", "needs-attention", "stopped"].includes(normalized);
|
|
1616
|
-
}
|
|
1617
|
-
function permissionAllowsPr(payload) {
|
|
1618
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
1619
|
-
return null;
|
|
1620
|
-
const record = payload;
|
|
1621
|
-
if (record.canOpenPullRequest === true || record.pullRequests === true || record.push === true || record.maintain === true || record.admin === true)
|
|
1622
|
-
return true;
|
|
1623
|
-
if (record.canOpenPullRequest === false || record.pullRequests === false || record.push === false)
|
|
1624
|
-
return false;
|
|
1625
|
-
const permissions = record.permissions;
|
|
1626
|
-
if (permissions && typeof permissions === "object" && !Array.isArray(permissions)) {
|
|
1627
|
-
const p = permissions;
|
|
1628
|
-
if (p.push === true || p.maintain === true || p.admin === true)
|
|
1629
|
-
return true;
|
|
1630
|
-
if (p.push === false && p.maintain !== true && p.admin !== true)
|
|
1631
|
-
return false;
|
|
1632
|
-
}
|
|
1633
|
-
return null;
|
|
1634
|
-
}
|
|
1635
|
-
function isNotFoundError(error) {
|
|
1636
|
-
return /\b(404|not found)\b/i.test(message(error));
|
|
1637
|
-
}
|
|
1638
|
-
function isLoopbackBaseUrl(baseUrl) {
|
|
1639
|
-
try {
|
|
1640
|
-
const host = new URL(baseUrl).hostname.toLowerCase();
|
|
1641
|
-
return host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]";
|
|
1642
|
-
} catch {
|
|
1643
|
-
return false;
|
|
1644
|
-
}
|
|
1645
|
-
}
|
|
1646
|
-
function projectCheckoutReady(payload) {
|
|
1647
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
1648
|
-
return null;
|
|
1649
|
-
const record = payload;
|
|
1650
|
-
if (record.checkoutReady === true || record.ready === true)
|
|
1651
|
-
return true;
|
|
1652
|
-
if (record.checkoutReady === false || record.ready === false)
|
|
1653
|
-
return false;
|
|
1654
|
-
const project = record.project;
|
|
1655
|
-
if (project && typeof project === "object" && !Array.isArray(project)) {
|
|
1656
|
-
const checkouts = project.checkouts;
|
|
1657
|
-
if (Array.isArray(checkouts))
|
|
1658
|
-
return checkouts.length > 0;
|
|
1659
|
-
}
|
|
1660
|
-
return null;
|
|
1661
|
-
}
|
|
1662
|
-
function activeDuplicateRun(runs, taskId) {
|
|
1663
|
-
if (!Array.isArray(runs))
|
|
1664
|
-
return null;
|
|
1665
|
-
for (const run of runs) {
|
|
1666
|
-
if (!run || typeof run !== "object" || Array.isArray(run))
|
|
1667
|
-
continue;
|
|
1668
|
-
const record = run;
|
|
1669
|
-
if ((record.taskId === taskId || record.task === taskId) && isActiveRunStatus(record.status))
|
|
1670
|
-
return record;
|
|
1671
|
-
}
|
|
1672
|
-
return null;
|
|
1673
|
-
}
|
|
1674
|
-
async function runFastTaskRunPreflight(context, options = {}) {
|
|
1675
|
-
const checks = [];
|
|
1676
|
-
const request = options.requestJson ?? ((pathname, init) => requestServerJson(context, pathname, init));
|
|
1677
|
-
const taskId = options.taskId?.trim() || null;
|
|
1678
|
-
const requiresCurrentRunApi = Boolean(taskId);
|
|
1679
|
-
const selectedServer = options.requestJson ? null : await ensureServerForCli(context.projectRoot).catch(() => null);
|
|
1680
|
-
const allowLocalLegacyTaskRunCompatibility = selectedServer?.connectionKind === "local";
|
|
1681
|
-
let legacyServerCompatibility = false;
|
|
1682
|
-
try {
|
|
1683
|
-
await request("/api/server/status");
|
|
1684
|
-
checks.push(preflightCheck("server", "Rig server reachable", "pass"));
|
|
1685
|
-
} catch (error) {
|
|
1686
|
-
if (isNotFoundError(error)) {
|
|
1687
|
-
try {
|
|
1688
|
-
await request("/health");
|
|
1689
|
-
legacyServerCompatibility = !requiresCurrentRunApi || allowLocalLegacyTaskRunCompatibility;
|
|
1690
|
-
checks.push(requiresCurrentRunApi && !allowLocalLegacyTaskRunCompatibility ? preflightCheck("server", "Rig server reachable", "fail", "legacy /health endpoint only; current task-run APIs are required", "Upgrade/select the Rig server before launching a task run.") : preflightCheck("server", "Rig server reachable", "pass", allowLocalLegacyTaskRunCompatibility ? "local legacy /health endpoint; submit endpoint will be authoritative" : "legacy /health endpoint"));
|
|
1691
|
-
} catch (healthError) {
|
|
1692
|
-
checks.push(preflightCheck("server", "Rig server reachable", "fail", message(healthError), "Start or select a reachable Rig server."));
|
|
1693
|
-
}
|
|
1694
|
-
} else {
|
|
1695
|
-
checks.push(preflightCheck("server", "Rig server reachable", "fail", message(error), "Start or select a reachable Rig server."));
|
|
1696
|
-
}
|
|
1697
|
-
}
|
|
1698
|
-
const repo = readRepoConnection(context.projectRoot);
|
|
1699
|
-
const remoteWithoutProjectLink = selectedServer?.connectionKind === "remote" && !repo?.project;
|
|
1700
|
-
let remoteRootBlocked = false;
|
|
1701
|
-
checks.push(repo ? preflightCheck("project-link", "project linked to selected server", repo.project ? "pass" : remoteWithoutProjectLink ? "fail" : "warn", `${repo.selected}${repo.project ? ` -> ${repo.project}` : " (missing project link)"}`, remoteWithoutProjectLink ? "Run `rig server repair-link --repo owner/repo` or `rig init --repo owner/repo --server remote` to restore the remote project link." : "Run `rig init --yes --repo owner/repo` to record the GitHub repo slug.") : preflightCheck("project-link", "project linked to selected server", legacyServerCompatibility ? "warn" : "fail", "missing .rig/state/connection.json", "Run `rig init` or `rig server use <alias|local>`."));
|
|
1702
|
-
if (selectedServer?.connectionKind === "remote" && repo?.project && !selectedServer.serverProjectRoot) {
|
|
1703
|
-
const link = await ensureRemoteProjectRootLink(context.projectRoot, { mode: "backfill-only", authToken: selectedServer.authToken });
|
|
1704
|
-
const loopbackDevRemote = !selectedServer.authToken && isLoopbackBaseUrl(selectedServer.baseUrl);
|
|
1705
|
-
checks.push(preflightCheck("remote-project-root-link", "remote server checkout/root linked", link.ok ? "pass" : loopbackDevRemote ? "warn" : "fail", link.ok ? `${link.repoSlug} -> ${link.serverProjectRoot}` : link.message, link.ok ? undefined : loopbackDevRemote ? "Loopback development remotes may continue without x-rig-project-root; production remotes must run `rig server repair-link`." : link.hint));
|
|
1706
|
-
remoteRootBlocked = !link.ok && !loopbackDevRemote;
|
|
1707
|
-
}
|
|
1708
|
-
try {
|
|
1709
|
-
const auth = await request("/api/github/auth/status");
|
|
1710
|
-
checks.push(isAuthenticated(auth) ? preflightCheck("github-auth", "GitHub auth valid", "pass") : preflightCheck("github-auth", "GitHub auth valid", legacyServerCompatibility ? "warn" : "fail", "not authenticated", "Run `rig github auth import-gh` or `rig github auth token --token <token>`."));
|
|
1711
|
-
} catch (error) {
|
|
1712
|
-
checks.push(preflightCheck("github-auth", "GitHub auth valid", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix GitHub auth on the selected Rig server."));
|
|
1713
|
-
}
|
|
1714
|
-
if (!remoteRootBlocked) {
|
|
1715
|
-
try {
|
|
1716
|
-
const projection = await request("/api/workspace/task-projection");
|
|
1717
|
-
checks.push(preflightCheck("task-projection", "task projection ready", "pass", JSON.stringify(projection).slice(0, 120)));
|
|
1718
|
-
} catch (error) {
|
|
1719
|
-
checks.push(preflightCheck("task-projection", "task projection ready", "warn", message(error), "Refresh task projection with `rig task list` before launching."));
|
|
1720
|
-
}
|
|
1721
|
-
try {
|
|
1722
|
-
const permissions = await request("/api/github/repo/permissions");
|
|
1723
|
-
const allowed = permissionAllowsPr(permissions);
|
|
1724
|
-
checks.push(allowed === false ? preflightCheck("github-repo-permissions", "GitHub PR permissions", "fail", JSON.stringify(permissions).slice(0, 120), "Grant the selected GitHub token permission to push branches and open PRs.") : preflightCheck("github-repo-permissions", "GitHub PR permissions", allowed === true ? "pass" : "warn", JSON.stringify(permissions).slice(0, 120), "Confirm the selected token can push branches and open PRs."));
|
|
1725
|
-
} catch (error) {
|
|
1726
|
-
checks.push(preflightCheck("github-repo-permissions", "GitHub PR permissions", "warn", message(error), "Ensure the selected token can push branches and open PRs."));
|
|
1727
|
-
}
|
|
1728
|
-
} else {
|
|
1729
|
-
checks.push(preflightCheck("task-projection", "task projection ready", "warn", "skipped until remote project-root link is repaired", "Run `rig server repair-link`, then retry."));
|
|
1730
|
-
checks.push(preflightCheck("github-repo-permissions", "GitHub PR permissions", "warn", "skipped until remote project-root link is repaired", "Run `rig server repair-link`, then retry."));
|
|
1731
|
-
}
|
|
1732
|
-
if (repo?.project) {
|
|
1733
|
-
try {
|
|
1734
|
-
const project = await request(`/api/projects/${encodeURIComponent(repo.project)}`);
|
|
1735
|
-
const ready = projectCheckoutReady(project);
|
|
1736
|
-
checks.push(ready === false ? preflightCheck("remote-checkout", "execution checkout ready", "fail", JSON.stringify(project).slice(0, 120), "Repair the server checkout or rerun `rig init` with a valid checkout strategy.") : preflightCheck("remote-checkout", "execution checkout ready", ready === true ? "pass" : "warn", JSON.stringify(project).slice(0, 120), "Confirm the selected server has a prepared execution checkout."));
|
|
1737
|
-
} catch (error) {
|
|
1738
|
-
checks.push(preflightCheck("remote-checkout", "execution checkout ready", "warn", message(error), "Run `rig init` or repair the server checkout before launch."));
|
|
1739
|
-
}
|
|
1740
|
-
}
|
|
1741
|
-
if (taskId) {
|
|
1742
|
-
if (!remoteRootBlocked) {
|
|
1743
|
-
try {
|
|
1744
|
-
const tasks = await request(`/api/workspace/tasks?limit=200&refresh=1`);
|
|
1745
|
-
const found = Array.isArray(tasks) && tasks.some((task) => taskMatchesId(task, taskId));
|
|
1746
|
-
checks.push(found ? preflightCheck("issue", "task/issue accessible", "pass", taskId) : preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", taskId, "Confirm the issue exists and matches the configured task filters."));
|
|
1747
|
-
} catch (error) {
|
|
1748
|
-
checks.push(preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix the task source before launching a run."));
|
|
1749
|
-
}
|
|
1750
|
-
try {
|
|
1751
|
-
const runs = await request("/api/runs?limit=200");
|
|
1752
|
-
const duplicate = activeDuplicateRun(runs, taskId);
|
|
1753
|
-
checks.push(duplicate ? preflightCheck("duplicate-active-run", "one active run per task", "fail", String(duplicate.runId ?? taskId), "Attach to or stop the existing run before starting another one for this task.") : preflightCheck("duplicate-active-run", "one active run per task", "pass", taskId));
|
|
1754
|
-
} catch (error) {
|
|
1755
|
-
checks.push(preflightCheck("duplicate-active-run", "one active run per task", "warn", message(error), "Could not list active runs; the server will still reject conflicting runs if configured."));
|
|
1756
|
-
}
|
|
1757
|
-
} else {
|
|
1758
|
-
checks.push(preflightCheck("issue", "task/issue accessible", "fail", "skipped until remote project-root link is repaired", "Run `rig server repair-link`, then retry."));
|
|
1759
|
-
checks.push(preflightCheck("duplicate-active-run", "one active run per task", "warn", "skipped until remote project-root link is repaired", "Run `rig server repair-link`, then retry."));
|
|
1760
|
-
}
|
|
1761
|
-
}
|
|
1762
|
-
if ((options.runtimeAdapter ?? "pi") === "pi") {
|
|
1763
|
-
checks.push(preflightCheck("runtime", "worker Pi SDK session daemon", "pass", selectedServer?.connectionKind === "remote" ? "remote worker-owned runtime" : "bundled server-owned runtime"));
|
|
1764
|
-
} else {
|
|
1765
|
-
checks.push(preflightCheck("runtime", "runtime adapter", "pass", options.runtimeAdapter));
|
|
1766
|
-
}
|
|
1767
|
-
const failures = checks.filter((check) => check.status === "fail");
|
|
1768
|
-
if (failures.length > 0) {
|
|
1769
|
-
const summary = failures.map((check) => `${check.label}${check.detail ? `: ${check.detail}` : ""}`).join("; ");
|
|
1770
|
-
if (failures.some((check) => check.id === "duplicate-active-run") && taskId) {
|
|
1771
|
-
throw new CliError(`Task ${taskId} already has an active Rig run. ${summary}`, 1, { hint: `Attach to it with \`rig run attach <run-id> --follow\`, or stop it first with \`rig run stop <run-id>\`.` });
|
|
1772
|
-
}
|
|
1773
|
-
throw new CliError(`Task run preflight failed: ${summary}`, 1, { hint: "Run `rig doctor` to diagnose, then retry `rig task run`." });
|
|
1774
|
-
}
|
|
1775
|
-
return { ok: true, checks };
|
|
1776
|
-
}
|
|
1777
|
-
async function runProjectMainSyncPreflight(context, options) {
|
|
1778
|
-
if (context.dryRun) {
|
|
1779
|
-
if (context.outputMode === "text" && !options.disabled) {
|
|
1780
|
-
console.log("[dry-run] project-rig pre-run sync check");
|
|
1781
|
-
}
|
|
1782
|
-
return;
|
|
1783
|
-
}
|
|
1784
|
-
const result = await ensureProjectMainFreshBeforeRun({
|
|
1785
|
-
projectRoot: context.projectRoot,
|
|
1786
|
-
disabled: options.disabled,
|
|
1787
|
-
runBootstrap: async () => {
|
|
1788
|
-
const bootstrap = await context.runCommand(["bun", "run", "bootstrap"]);
|
|
1789
|
-
if (bootstrap.exitCode !== 0) {
|
|
1790
|
-
throw new CliError(bootstrap.stderr || bootstrap.stdout || "bun run bootstrap failed during project pre-run sync", bootstrap.exitCode || 1);
|
|
1791
|
-
}
|
|
1792
|
-
}
|
|
1793
|
-
});
|
|
1794
|
-
if (context.outputMode !== "text") {
|
|
1795
|
-
return;
|
|
1796
|
-
}
|
|
1797
|
-
switch (result.status) {
|
|
1798
|
-
case "disabled":
|
|
1799
|
-
console.log("Project pre-run sync skipped (--skip-project-sync).");
|
|
1800
|
-
break;
|
|
1801
|
-
case "skipped_not_main":
|
|
1802
|
-
console.log(`Project pre-run sync skipped (current branch: ${result.branch}).`);
|
|
1803
|
-
break;
|
|
1804
|
-
case "up_to_date":
|
|
1805
|
-
break;
|
|
1806
|
-
case "local_ahead":
|
|
1807
|
-
console.log(`Project pre-run sync skipped (local main ahead by ${result.localAhead} commit(s)).`);
|
|
1808
|
-
break;
|
|
1809
|
-
case "updated":
|
|
1810
|
-
console.log(`Project pre-run sync updated local main from origin/main (+${result.remoteAhead}) and bootstrapped.`);
|
|
1811
|
-
break;
|
|
1812
|
-
}
|
|
1813
|
-
}
|
|
1814
|
-
var init__preflight = __esm(() => {
|
|
1815
|
-
init_runner();
|
|
1816
|
-
init__connection_state();
|
|
1817
|
-
init__server_client();
|
|
1818
|
-
});
|
|
1819
|
-
|
|
1820
|
-
// packages/cli/src/withMutedConsole.ts
|
|
1821
|
-
function isPromise(value) {
|
|
1822
|
-
if (typeof value !== "object" && typeof value !== "function") {
|
|
1823
|
-
return false;
|
|
1824
|
-
}
|
|
1825
|
-
return value !== null && typeof value.then === "function";
|
|
1826
|
-
}
|
|
1827
|
-
function withMutedConsole(mute, fn) {
|
|
1828
|
-
if (!mute) {
|
|
1829
|
-
return fn();
|
|
1830
|
-
}
|
|
1831
|
-
const originalLog = console.log;
|
|
1832
|
-
const originalWarn = console.warn;
|
|
1833
|
-
const originalInfo = console.info;
|
|
1834
|
-
const restore = () => {
|
|
1835
|
-
console.log = originalLog;
|
|
1836
|
-
console.warn = originalWarn;
|
|
1837
|
-
console.info = originalInfo;
|
|
1838
|
-
};
|
|
1839
|
-
console.log = () => {};
|
|
1840
|
-
console.warn = () => {};
|
|
1841
|
-
console.info = () => {};
|
|
1842
|
-
try {
|
|
1843
|
-
const result = fn();
|
|
1844
|
-
if (isPromise(result)) {
|
|
1845
|
-
return result.finally(restore);
|
|
1846
|
-
}
|
|
1847
|
-
restore();
|
|
1848
|
-
return result;
|
|
1849
|
-
} catch (error) {
|
|
1850
|
-
restore();
|
|
1851
|
-
throw error;
|
|
1852
|
-
} finally {
|
|
1853
|
-
if (console.log === originalLog) {
|
|
1854
|
-
restore();
|
|
1855
|
-
}
|
|
1856
|
-
}
|
|
1857
|
-
}
|
|
1858
|
-
|
|
1859
|
-
// packages/cli/src/commands/_operator-surface.ts
|
|
1860
|
-
import { createInterface } from "readline";
|
|
1861
|
-
import { createInterface as createPromptInterface } from "readline/promises";
|
|
1862
|
-
function logDetail(log) {
|
|
1863
|
-
return typeof log.detail === "string" ? log.detail.trim() : "";
|
|
1864
|
-
}
|
|
1865
|
-
function parseProviderProtocolLog(title, detail) {
|
|
1866
|
-
if (title.trim().toLowerCase() !== "agent output")
|
|
1867
|
-
return null;
|
|
1868
|
-
if (!detail.startsWith("{") || !detail.endsWith("}"))
|
|
1869
|
-
return null;
|
|
1870
|
-
try {
|
|
1871
|
-
const record = JSON.parse(detail);
|
|
1872
|
-
if (!record || typeof record !== "object" || Array.isArray(record))
|
|
1873
|
-
return null;
|
|
1874
|
-
const type = record.type;
|
|
1875
|
-
return typeof type === "string" && [
|
|
1876
|
-
"assistant",
|
|
1877
|
-
"message_start",
|
|
1878
|
-
"message_update",
|
|
1879
|
-
"message_end",
|
|
1880
|
-
"stream_event",
|
|
1881
|
-
"tool_result",
|
|
1882
|
-
"tool_execution_start",
|
|
1883
|
-
"tool_execution_update",
|
|
1884
|
-
"tool_execution_end",
|
|
1885
|
-
"turn_start",
|
|
1886
|
-
"turn_end"
|
|
1887
|
-
].includes(type) ? record : null;
|
|
1888
|
-
} catch {
|
|
1889
|
-
return null;
|
|
1890
|
-
}
|
|
1891
|
-
}
|
|
1892
|
-
function renderProviderProtocolLog(record) {
|
|
1893
|
-
const type = typeof record.type === "string" ? record.type : "";
|
|
1894
|
-
if (type === "tool_execution_start" || type === "tool_execution_update" || type === "tool_execution_end") {
|
|
1895
|
-
const toolName = String(record.toolName ?? record.name ?? "tool");
|
|
1896
|
-
const status = type === "tool_execution_start" ? "started" : type === "tool_execution_end" ? record.isError === true || record.result && typeof record.result === "object" && !Array.isArray(record.result) && record.result.isError === true ? "failed" : "completed" : "running";
|
|
1897
|
-
return `[Pi tool] ${toolName} ${status}`;
|
|
1898
|
-
}
|
|
1899
|
-
return null;
|
|
1900
|
-
}
|
|
1901
|
-
function entryId(entry, fallback) {
|
|
1902
|
-
return typeof entry.id === "string" && entry.id.trim() ? entry.id : fallback;
|
|
1903
|
-
}
|
|
1904
|
-
function renderOperatorSnapshot(snapshot) {
|
|
1905
|
-
const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
|
|
1906
|
-
const runId = String(run.runId ?? run.id ?? "run");
|
|
1907
|
-
const status = String(run.status ?? "unknown");
|
|
1908
|
-
const logs = snapshot.logs ?? [];
|
|
1909
|
-
const latestByStage = new Map;
|
|
1910
|
-
for (const log of logs) {
|
|
1911
|
-
const title = String(log.title ?? "").toLowerCase();
|
|
1912
|
-
const stageName = String(log.stage ?? "").toLowerCase();
|
|
1913
|
-
const stage = CANONICAL_STAGES.find((candidate) => candidate.toLowerCase() === title || candidate.toLowerCase() === stageName);
|
|
1914
|
-
if (stage)
|
|
1915
|
-
latestByStage.set(stage, log);
|
|
1916
|
-
}
|
|
1917
|
-
const stageLines = CANONICAL_STAGES.flatMap((stage) => {
|
|
1918
|
-
const match = latestByStage.get(stage);
|
|
1919
|
-
return match ? [`${stage}: ${String(match.status ?? status)}${logDetail(match) ? ` \u2014 ${logDetail(match)}` : ""}`] : [];
|
|
1920
|
-
});
|
|
1921
|
-
return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
|
|
1922
|
-
`);
|
|
1923
|
-
}
|
|
1924
|
-
function createPiRunStreamRenderer(output = process.stdout) {
|
|
1925
|
-
let lastSnapshot = "";
|
|
1926
|
-
const assistantTextById = new Map;
|
|
1927
|
-
const seenTimeline = new Set;
|
|
1928
|
-
const seenLogs = new Set;
|
|
1929
|
-
const writeLine = (line) => output.write(`${line}
|
|
1930
|
-
`);
|
|
1931
|
-
return {
|
|
1932
|
-
renderSnapshot(snapshot) {
|
|
1933
|
-
const rendered = renderOperatorSnapshot(snapshot);
|
|
1934
|
-
if (rendered && rendered !== lastSnapshot) {
|
|
1935
|
-
writeLine(rendered);
|
|
1936
|
-
lastSnapshot = rendered;
|
|
1937
|
-
}
|
|
1938
|
-
},
|
|
1939
|
-
renderTimeline(entries) {
|
|
1940
|
-
for (const [index, entry] of entries.entries()) {
|
|
1941
|
-
const id = entryId(entry, `timeline:${index}:${String(entry.cursor ?? "")}`);
|
|
1942
|
-
if (entry.type === "assistant_message" && typeof entry.text === "string") {
|
|
1943
|
-
const text = entry.text;
|
|
1944
|
-
const previousText = assistantTextById.get(id) ?? "";
|
|
1945
|
-
if (!previousText && text.trim()) {
|
|
1946
|
-
writeLine("[Pi assistant]");
|
|
1947
|
-
}
|
|
1948
|
-
if (text.startsWith(previousText)) {
|
|
1949
|
-
const delta = text.slice(previousText.length);
|
|
1950
|
-
if (delta)
|
|
1951
|
-
output.write(delta);
|
|
1952
|
-
} else if (text.trim() && text !== previousText) {
|
|
1953
|
-
if (previousText)
|
|
1954
|
-
writeLine(`
|
|
1955
|
-
[Pi assistant]`);
|
|
1956
|
-
output.write(text);
|
|
1957
|
-
}
|
|
1958
|
-
assistantTextById.set(id, text);
|
|
1959
|
-
continue;
|
|
1960
|
-
}
|
|
1961
|
-
if (seenTimeline.has(id))
|
|
1962
|
-
continue;
|
|
1963
|
-
seenTimeline.add(id);
|
|
1964
|
-
if (entry.type === "tool_execution_start" || entry.type === "tool_execution_update" || entry.type === "tool_execution_end" || entry.type === "mcp_tool_call") {
|
|
1965
|
-
writeLine(`[Pi tool] ${String(entry.toolName ?? entry.name ?? entry.title ?? entry.type)} ${String(entry.status ?? entry.state ?? "")}`.trim());
|
|
1966
|
-
continue;
|
|
1967
|
-
}
|
|
1968
|
-
if (entry.type === "timeline_warning") {
|
|
1969
|
-
writeLine(`[Rig timeline] ${String(entry.detail ?? entry.message ?? "timeline unavailable")}`);
|
|
1970
|
-
continue;
|
|
1971
|
-
}
|
|
1972
|
-
if (entry.type === "action") {
|
|
1973
|
-
const text = String(entry.detail ?? entry.message ?? entry.title ?? "").trim();
|
|
1974
|
-
if (text)
|
|
1975
|
-
writeLine(`[Rig action] ${text}`);
|
|
1976
|
-
continue;
|
|
1977
|
-
}
|
|
1978
|
-
if (entry.type === "user_message") {
|
|
1979
|
-
const text = String(entry.text ?? entry.message ?? entry.detail ?? "").trim();
|
|
1980
|
-
if (text)
|
|
1981
|
-
writeLine(`[Operator] ${text}`);
|
|
1982
|
-
continue;
|
|
1983
|
-
}
|
|
1984
|
-
const fallback = String(entry.detail ?? entry.message ?? entry.text ?? entry.title ?? "").trim();
|
|
1985
|
-
if (fallback)
|
|
1986
|
-
writeLine(`[${String(entry.type ?? "timeline")}] ${fallback}`);
|
|
1987
|
-
}
|
|
1988
|
-
},
|
|
1989
|
-
renderLogs(entries) {
|
|
1990
|
-
for (const [index, entry] of entries.entries()) {
|
|
1991
|
-
const id = entryId(entry, `log:${index}:${String(entry.createdAt ?? "")}:${String(entry.title ?? "")}`);
|
|
1992
|
-
if (seenLogs.has(id))
|
|
1993
|
-
continue;
|
|
1994
|
-
seenLogs.add(id);
|
|
1995
|
-
const title = String(entry.title ?? "");
|
|
1996
|
-
if (CANONICAL_STAGES.some((stage) => stage.toLowerCase() === title.toLowerCase()))
|
|
1997
|
-
continue;
|
|
1998
|
-
const detail = logDetail(entry);
|
|
1999
|
-
if (!detail)
|
|
2000
|
-
continue;
|
|
2001
|
-
const protocolRecord = parseProviderProtocolLog(title, detail);
|
|
2002
|
-
if (protocolRecord) {
|
|
2003
|
-
const protocolLine = renderProviderProtocolLog(protocolRecord);
|
|
2004
|
-
if (protocolLine)
|
|
2005
|
-
writeLine(protocolLine);
|
|
2006
|
-
continue;
|
|
2007
|
-
}
|
|
2008
|
-
writeLine(`[${title || "Rig log"}] ${detail}`);
|
|
2009
|
-
}
|
|
2010
|
-
}
|
|
2011
|
-
};
|
|
2012
|
-
}
|
|
2013
|
-
function createOperatorSurface(options = {}) {
|
|
2014
|
-
const input = options.input ?? process.stdin;
|
|
2015
|
-
const output = options.output ?? process.stdout;
|
|
2016
|
-
const errorOutput = options.errorOutput ?? process.stderr;
|
|
2017
|
-
const renderer = createPiRunStreamRenderer(output);
|
|
2018
|
-
const writeLine = (line) => output.write(`${line}
|
|
2019
|
-
`);
|
|
2020
|
-
return {
|
|
2021
|
-
mode: "pi-compatible-text",
|
|
2022
|
-
...renderer,
|
|
2023
|
-
info: writeLine,
|
|
2024
|
-
error: (message2) => errorOutput.write(`${message2}
|
|
2025
|
-
`),
|
|
2026
|
-
attachCommandInput(handler) {
|
|
2027
|
-
if (options.interactive === false || !input.isTTY)
|
|
2028
|
-
return null;
|
|
2029
|
-
const rl = createInterface({ input, output: process.stdout, terminal: false });
|
|
2030
|
-
rl.on("line", (line) => {
|
|
2031
|
-
Promise.resolve(handler(line)).catch((error) => writeLine(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
|
|
2032
|
-
});
|
|
2033
|
-
return { close: () => rl.close() };
|
|
2034
|
-
}
|
|
2035
|
-
};
|
|
2036
|
-
}
|
|
2037
|
-
function taskId(task) {
|
|
2038
|
-
return typeof task.id === "string" && task.id.trim() ? task.id : "<unknown>";
|
|
2039
|
-
}
|
|
2040
|
-
function taskTitle(task) {
|
|
2041
|
-
return typeof task.title === "string" && task.title.trim() ? task.title : "Untitled task";
|
|
2042
|
-
}
|
|
2043
|
-
function taskStatus(task) {
|
|
2044
|
-
return typeof task.status === "string" && task.status.trim() ? task.status : "unknown";
|
|
2045
|
-
}
|
|
2046
|
-
function renderTaskPickerRows(tasks) {
|
|
2047
|
-
return tasks.map((task, index) => `${index + 1}. ${taskId(task)} \xB7 ${taskStatus(task)} \xB7 ${taskTitle(task)}`);
|
|
2048
|
-
}
|
|
2049
|
-
async function promptForTaskSelection(question) {
|
|
2050
|
-
const rl = createPromptInterface({ input: process.stdin, output: process.stdout });
|
|
2051
|
-
try {
|
|
2052
|
-
return await rl.question(question);
|
|
2053
|
-
} finally {
|
|
2054
|
-
rl.close();
|
|
2055
|
-
}
|
|
2056
|
-
}
|
|
2057
|
-
var CANONICAL_STAGES;
|
|
2058
|
-
var init__operator_surface = __esm(() => {
|
|
2059
|
-
CANONICAL_STAGES = [
|
|
2060
|
-
"Connect",
|
|
2061
|
-
"GitHub/task sync",
|
|
2062
|
-
"Prepare workspace",
|
|
2063
|
-
"Launch Pi",
|
|
2064
|
-
"Plan",
|
|
2065
|
-
"Implement",
|
|
2066
|
-
"Validate",
|
|
2067
|
-
"Commit",
|
|
2068
|
-
"Open PR",
|
|
2069
|
-
"Review/CI",
|
|
2070
|
-
"Merge",
|
|
2071
|
-
"Complete"
|
|
2072
|
-
];
|
|
2073
|
-
});
|
|
2074
|
-
|
|
2075
|
-
// packages/cli/src/commands/_task-picker.ts
|
|
2076
|
-
function taskId2(task) {
|
|
2077
|
-
return typeof task.id === "string" && task.id.trim() ? task.id : "<unknown>";
|
|
2078
|
-
}
|
|
2079
|
-
async function selectTaskWithTextPicker(tasks, io = {}) {
|
|
2080
|
-
if (tasks.length === 0)
|
|
2081
|
-
return null;
|
|
2082
|
-
if (tasks.length === 1)
|
|
2083
|
-
return tasks[0];
|
|
2084
|
-
const isTty2 = io.isTty ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
2085
|
-
if (!isTty2) {
|
|
2086
|
-
throw new Error("task run requires an interactive terminal to pick a task; pass --task <id>, --next, or --detach with a task id.");
|
|
2087
|
-
}
|
|
2088
|
-
if (io.prompt || io.renderer) {
|
|
2089
|
-
const prompt = io.prompt ?? promptForTaskSelection;
|
|
2090
|
-
const renderer = io.renderer ?? { writeLine: (line) => process.stdout.write(`${line}
|
|
2091
|
-
`) };
|
|
2092
|
-
renderer.writeLine("Select Rig task:");
|
|
2093
|
-
for (const row of renderTaskPickerRows(tasks))
|
|
2094
|
-
renderer.writeLine(` ${row}`);
|
|
2095
|
-
const answer2 = (await prompt(`Task [1-${tasks.length}] or id: `)).trim();
|
|
2096
|
-
if (!answer2)
|
|
2097
|
-
return null;
|
|
2098
|
-
if (/^\d+$/.test(answer2)) {
|
|
2099
|
-
const index2 = Number.parseInt(answer2, 10) - 1;
|
|
2100
|
-
return tasks[index2] ?? null;
|
|
2101
|
-
}
|
|
2102
|
-
return tasks.find((task) => taskId2(task) === answer2) ?? null;
|
|
2103
|
-
}
|
|
2104
|
-
const options = tasks.map((task, index2) => ({
|
|
2105
|
-
value: `${index2}`,
|
|
2106
|
-
label: `${taskId2(task)} \xB7 ${typeof task.title === "string" && task.title.trim() ? task.title.trim() : "Untitled task"}`,
|
|
2107
|
-
hint: typeof task.status === "string" && task.status.trim() ? task.status.trim() : undefined
|
|
2108
|
-
}));
|
|
2109
|
-
const answer = await droneSelect({
|
|
2110
|
-
message: "Select Rig task",
|
|
2111
|
-
options
|
|
2112
|
-
});
|
|
2113
|
-
if (answer === null) {
|
|
2114
|
-
droneCancel("No task selected.");
|
|
2115
|
-
return null;
|
|
2116
|
-
}
|
|
2117
|
-
const index = Number.parseInt(String(answer), 10);
|
|
2118
|
-
return Number.isFinite(index) ? tasks[index] ?? null : null;
|
|
2119
|
-
}
|
|
2120
|
-
var init__task_picker = __esm(() => {
|
|
2121
|
-
init_drone_ui();
|
|
2122
|
-
init__operator_surface();
|
|
2123
|
-
});
|
|
2124
|
-
|
|
2125
|
-
// packages/cli/src/commands/_async-ui.ts
|
|
2126
|
-
import pc from "picocolors";
|
|
2127
|
-
async function withSpinner(label, work, options = {}) {
|
|
2128
|
-
if (options.outputMode === "json") {
|
|
2129
|
-
return work(() => {});
|
|
2130
|
-
}
|
|
2131
|
-
if (activeUpdate) {
|
|
2132
|
-
const outer = activeUpdate;
|
|
2133
|
-
outer(label);
|
|
2134
|
-
return work(outer);
|
|
2135
|
-
}
|
|
2136
|
-
const output = options.output ?? process.stderr;
|
|
2137
|
-
const isTty2 = output.isTTY === true;
|
|
2138
|
-
let lastLabel = label;
|
|
2139
|
-
if (!isTty2) {
|
|
2140
|
-
output.write(`${label}
|
|
2141
|
-
`);
|
|
2142
|
-
const update2 = (next) => {
|
|
2143
|
-
lastLabel = next;
|
|
2144
|
-
};
|
|
2145
|
-
activeUpdate = update2;
|
|
2146
|
-
const previousListener2 = setServerPhaseListener(update2);
|
|
2147
|
-
try {
|
|
2148
|
-
return await work(update2);
|
|
2149
|
-
} finally {
|
|
2150
|
-
activeUpdate = null;
|
|
2151
|
-
setServerPhaseListener(previousListener2);
|
|
2152
|
-
}
|
|
2153
|
-
}
|
|
2154
|
-
const spinner = createTtySpinner({
|
|
2155
|
-
label,
|
|
2156
|
-
output,
|
|
2157
|
-
frames: MICRO_DRONE_FRAMES,
|
|
2158
|
-
styleFrame: (frame) => renderMicroDroneFrame(Math.max(0, MICRO_DRONE_FRAMES.indexOf(frame)))
|
|
2159
|
-
});
|
|
2160
|
-
const update = (next) => {
|
|
2161
|
-
lastLabel = next;
|
|
2162
|
-
spinner.setLabel(next);
|
|
2163
|
-
};
|
|
2164
|
-
activeUpdate = update;
|
|
2165
|
-
const previousListener = setServerPhaseListener(update);
|
|
2166
|
-
try {
|
|
2167
|
-
const result = await work(update);
|
|
2168
|
-
spinner.stop(options.doneLabel ? `${DONE_SYMBOL} ${options.doneLabel}` : undefined);
|
|
2169
|
-
return result;
|
|
2170
|
-
} catch (error) {
|
|
2171
|
-
spinner.stop(`${FAIL_SYMBOL} ${lastLabel}`);
|
|
2172
|
-
throw error;
|
|
2173
|
-
} finally {
|
|
2174
|
-
activeUpdate = null;
|
|
2175
|
-
setServerPhaseListener(previousListener);
|
|
2176
|
-
}
|
|
2177
|
-
}
|
|
2178
|
-
var DONE_SYMBOL, FAIL_SYMBOL, activeUpdate = null;
|
|
2179
|
-
var init__async_ui = __esm(() => {
|
|
2180
|
-
init__spinner();
|
|
2181
|
-
init__server_client();
|
|
2182
|
-
init_theme();
|
|
2183
|
-
DONE_SYMBOL = pc.green("\u25C7");
|
|
2184
|
-
FAIL_SYMBOL = pc.red("\u25A0");
|
|
2185
|
-
});
|
|
2186
|
-
|
|
2187
|
-
// packages/cli/src/commands/_pi-frontend.ts
|
|
2188
|
-
var exports__pi_frontend = {};
|
|
2189
|
-
__export(exports__pi_frontend, {
|
|
2190
|
-
shouldRequireOperatorTranscript: () => shouldRequireOperatorTranscript,
|
|
2191
|
-
runWithProcessExitGuard: () => runWithProcessExitGuard,
|
|
2192
|
-
missingOperatorTranscriptMessage: () => missingOperatorTranscriptMessage,
|
|
2193
|
-
buildOperatorPiEnv: () => buildOperatorPiEnv,
|
|
2194
|
-
attachRunBundledPiFrontend: () => attachRunBundledPiFrontend
|
|
2195
|
-
});
|
|
2196
|
-
import { existsSync as existsSync3, mkdirSync as mkdirSync3, mkdtempSync, readFileSync as readFileSync3, rmSync, writeFileSync as writeFileSync3 } from "fs";
|
|
2197
|
-
import { homedir as homedir2, tmpdir } from "os";
|
|
2198
|
-
import { join } from "path";
|
|
2199
|
-
import { main as runPiMain } from "@earendil-works/pi-coding-agent";
|
|
2200
|
-
import createPiRigExtension from "@rig/pi-rig";
|
|
2201
|
-
function setTemporaryEnv(updates) {
|
|
2202
|
-
const previous = new Map;
|
|
2203
|
-
for (const [key, value] of Object.entries(updates)) {
|
|
2204
|
-
previous.set(key, process.env[key]);
|
|
2205
|
-
process.env[key] = value;
|
|
2206
|
-
}
|
|
2207
|
-
return () => {
|
|
2208
|
-
for (const [key, value] of previous) {
|
|
2209
|
-
if (value === undefined)
|
|
2210
|
-
delete process.env[key];
|
|
2211
|
-
else
|
|
2212
|
-
process.env[key] = value;
|
|
2213
|
-
}
|
|
2214
|
-
};
|
|
2215
|
-
}
|
|
2216
|
-
function buildOperatorPiEnv(input) {
|
|
2217
|
-
return {
|
|
2218
|
-
PI_CODING_AGENT_SESSION_DIR: input.sessionDir,
|
|
2219
|
-
PI_SKIP_VERSION_CHECK: "1",
|
|
2220
|
-
PI_HIDDEN_COMMANDS: "import,fork,clone,tree,new,resume,trust",
|
|
2221
|
-
RIG_PI_OPERATOR_SESSION: "1",
|
|
2222
|
-
RIG_RUN_ID: input.runId,
|
|
2223
|
-
RIG_SERVER_URL: input.serverUrl,
|
|
2224
|
-
...input.authToken ? { RIG_AUTH_TOKEN: input.authToken } : {},
|
|
2225
|
-
...input.serverProjectRoot ? { RIG_PROJECT_ROOT: input.serverProjectRoot } : {}
|
|
2226
|
-
};
|
|
2227
|
-
}
|
|
2228
|
-
function shouldRequireOperatorTranscript(status) {
|
|
2229
|
-
return typeof status === "string" && TERMINAL_RUN_STATUSES.has(status.trim().toLowerCase());
|
|
2230
|
-
}
|
|
2231
|
-
function missingOperatorTranscriptMessage(runId, status) {
|
|
2232
|
-
const shortRun = runId.trim().slice(0, 8) || "unknown";
|
|
2233
|
-
const statusText = typeof status === "string" && status.trim() ? status.trim() : "terminal";
|
|
2234
|
-
return `Run ${shortRun} is ${statusText}, but no worker Pi session transcript is recorded for this run. It likely failed before Pi started or predates full-session capture. Use \`rig run show ${runId}\` and \`rig run logs ${runId}\` for the lifecycle details.`;
|
|
2235
|
-
}
|
|
2236
|
-
function statusFromRunDetails(run) {
|
|
2237
|
-
if (!run || typeof run !== "object" || Array.isArray(run))
|
|
2238
|
-
return;
|
|
2239
|
-
const record = run;
|
|
2240
|
-
if (typeof record.status === "string")
|
|
2241
|
-
return record.status;
|
|
2242
|
-
const nested = record.run;
|
|
2243
|
-
return nested && typeof nested === "object" && !Array.isArray(nested) ? nested.status : undefined;
|
|
2244
|
-
}
|
|
2245
|
-
async function prepareOperatorConsole(context, runId, tempSessionDir) {
|
|
2246
|
-
const server = await ensureServerForCli(context.projectRoot);
|
|
2247
|
-
const localCwd = join(homedir2(), ".rig", "drones", runId.slice(0, 8));
|
|
2248
|
-
mkdirSync3(localCwd, { recursive: true });
|
|
2249
|
-
trustDroneCwd(localCwd);
|
|
2250
|
-
installRigPiTheme();
|
|
2251
|
-
let sessionFileArg = [];
|
|
2252
|
-
try {
|
|
2253
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/session-file`);
|
|
2254
|
-
if (payload?.ok && typeof payload.content === "string" && payload.content.trim()) {
|
|
2255
|
-
const fileName = typeof payload.fileName === "string" && payload.fileName.trim() ? payload.fileName.replace(/[^A-Za-z0-9._-]/g, "_") : `rig-run-${runId}.jsonl`;
|
|
2256
|
-
const localSessionPath = join(tempSessionDir, fileName);
|
|
2257
|
-
const content = payload.content.split(`
|
|
2258
|
-
`).map((line, index) => {
|
|
2259
|
-
if (index > 0 || !line.trim())
|
|
2260
|
-
return line;
|
|
2261
|
-
try {
|
|
2262
|
-
const header = JSON.parse(line);
|
|
2263
|
-
if (header.type === "session" && typeof header.cwd === "string") {
|
|
2264
|
-
return JSON.stringify({ ...header, cwd: localCwd });
|
|
2265
|
-
}
|
|
2266
|
-
} catch {}
|
|
2267
|
-
return line;
|
|
2268
|
-
}).join(`
|
|
2269
|
-
`);
|
|
2270
|
-
writeFileSync3(localSessionPath, content);
|
|
2271
|
-
sessionFileArg = ["--session", localSessionPath];
|
|
2272
|
-
}
|
|
2273
|
-
} catch {}
|
|
2274
|
-
if (sessionFileArg.length === 0) {
|
|
2275
|
-
const run = await getRunDetailsViaServer(context, runId).catch(() => null);
|
|
2276
|
-
const status = statusFromRunDetails(run);
|
|
2277
|
-
if (shouldRequireOperatorTranscript(status)) {
|
|
2278
|
-
throw new OperatorTranscriptUnavailableError(missingOperatorTranscriptMessage(runId, status));
|
|
2279
|
-
}
|
|
2280
|
-
}
|
|
2281
|
-
return { server, sessionFileArg };
|
|
2282
|
-
}
|
|
2283
|
-
function trustDroneCwd(localCwd) {
|
|
2284
|
-
try {
|
|
2285
|
-
const agentDir = join(homedir2(), ".pi", "agent");
|
|
2286
|
-
mkdirSync3(agentDir, { recursive: true });
|
|
2287
|
-
const trustPath = join(agentDir, "trust.json");
|
|
2288
|
-
const store = existsSync3(trustPath) ? JSON.parse(readFileSync3(trustPath, "utf8")) : {};
|
|
2289
|
-
if (store[localCwd] !== true) {
|
|
2290
|
-
store[localCwd] = true;
|
|
2291
|
-
writeFileSync3(trustPath, `${JSON.stringify(store, null, "\t")}
|
|
2292
|
-
`);
|
|
2293
|
-
}
|
|
2294
|
-
} catch {}
|
|
2295
|
-
}
|
|
2296
|
-
function installRigPiTheme() {
|
|
2297
|
-
try {
|
|
2298
|
-
const themesDir = join(homedir2(), ".pi", "agent", "themes");
|
|
2299
|
-
mkdirSync3(themesDir, { recursive: true });
|
|
2300
|
-
const themePath = join(themesDir, "rig.json");
|
|
2301
|
-
const next = `${JSON.stringify(RIG_PI_THEME, null, "\t")}
|
|
2302
|
-
`;
|
|
2303
|
-
if (!existsSync3(themePath) || readFileSync3(themePath, "utf8") !== next) {
|
|
2304
|
-
writeFileSync3(themePath, next);
|
|
2305
|
-
}
|
|
2306
|
-
} catch {}
|
|
2307
|
-
}
|
|
2308
|
-
async function runWithProcessExitGuard(body) {
|
|
2309
|
-
const realExit = process.exit;
|
|
2310
|
-
let exitCode = 0;
|
|
2311
|
-
let signalQuit = () => {};
|
|
2312
|
-
const quit = new Promise((resolve3) => {
|
|
2313
|
-
signalQuit = resolve3;
|
|
2314
|
-
});
|
|
2315
|
-
const guardedExit = (code) => {
|
|
2316
|
-
exitCode = typeof code === "number" ? code : 0;
|
|
2317
|
-
signalQuit();
|
|
2318
|
-
return;
|
|
2319
|
-
};
|
|
2320
|
-
process.exit = guardedExit;
|
|
2321
|
-
try {
|
|
2322
|
-
await Promise.race([Promise.resolve().then(body), quit]);
|
|
2323
|
-
} finally {
|
|
2324
|
-
process.exit = realExit;
|
|
2325
|
-
}
|
|
2326
|
-
return exitCode;
|
|
2327
|
-
}
|
|
2328
|
-
function runPiMainReturningOnQuit(args, options) {
|
|
2329
|
-
return runWithProcessExitGuard(() => runPiMain(args, options));
|
|
2330
|
-
}
|
|
2331
|
-
async function attachRunBundledPiFrontend(context, input) {
|
|
2332
|
-
const tempSessionDir = mkdtempSync(join(tmpdir(), "rig-pi-frontend-sessions-"));
|
|
2333
|
-
const { server, sessionFileArg } = await withSpinner(`Opening Pi console for run ${input.runId}\u2026`, () => prepareOperatorConsole(context, input.runId, tempSessionDir), { outputMode: context.outputMode });
|
|
2334
|
-
const restoreEnv = setTemporaryEnv(buildOperatorPiEnv({
|
|
2335
|
-
runId: input.runId,
|
|
2336
|
-
serverUrl: server.baseUrl,
|
|
2337
|
-
authToken: server.authToken,
|
|
2338
|
-
serverProjectRoot: server.serverProjectRoot,
|
|
2339
|
-
sessionDir: tempSessionDir
|
|
2340
|
-
}));
|
|
2341
|
-
const piRigExtensionFactory = (pi) => {
|
|
2342
|
-
createPiRigExtension(pi);
|
|
2343
|
-
};
|
|
2344
|
-
let detached = false;
|
|
2345
|
-
try {
|
|
2346
|
-
const piArgs = [
|
|
2347
|
-
"--offline",
|
|
2348
|
-
"--no-extensions",
|
|
2349
|
-
"--no-skills",
|
|
2350
|
-
"--no-prompt-templates",
|
|
2351
|
-
"--no-context-files",
|
|
2352
|
-
...sessionFileArg
|
|
2353
|
-
];
|
|
2354
|
-
const piOptions = { extensionFactories: [piRigExtensionFactory] };
|
|
2355
|
-
if (input.returnOnQuit) {
|
|
2356
|
-
await runPiMainReturningOnQuit(piArgs, piOptions);
|
|
2357
|
-
} else {
|
|
2358
|
-
await runPiMain(piArgs, piOptions);
|
|
2359
|
-
}
|
|
2360
|
-
detached = true;
|
|
2361
|
-
} finally {
|
|
2362
|
-
restoreEnv();
|
|
2363
|
-
rmSync(tempSessionDir, { recursive: true, force: true });
|
|
2364
|
-
}
|
|
2365
|
-
let run = { runId: input.runId, status: "unknown" };
|
|
2366
|
-
try {
|
|
2367
|
-
run = await getRunDetailsViaServer(context, input.runId);
|
|
2368
|
-
} catch {}
|
|
2369
|
-
return {
|
|
2370
|
-
run,
|
|
2371
|
-
logs: [],
|
|
2372
|
-
timeline: [],
|
|
2373
|
-
timelineCursor: null,
|
|
2374
|
-
steered: input.steered === true,
|
|
2375
|
-
detached,
|
|
2376
|
-
rendered: "stock Pi operator console with the pi-rig extension"
|
|
2377
|
-
};
|
|
2378
|
-
}
|
|
2379
|
-
var TERMINAL_RUN_STATUSES, OperatorTranscriptUnavailableError, RIG_PI_THEME;
|
|
2380
|
-
var init__pi_frontend = __esm(() => {
|
|
2381
|
-
init__server_client();
|
|
2382
|
-
init__async_ui();
|
|
2383
|
-
TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
|
|
2384
|
-
OperatorTranscriptUnavailableError = class OperatorTranscriptUnavailableError extends Error {
|
|
2385
|
-
constructor(message2) {
|
|
2386
|
-
super(message2);
|
|
2387
|
-
this.name = "OperatorTranscriptUnavailableError";
|
|
2388
|
-
}
|
|
2389
|
-
};
|
|
2390
|
-
RIG_PI_THEME = {
|
|
2391
|
-
$schema: "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json",
|
|
2392
|
-
name: "rig",
|
|
2393
|
-
vars: {
|
|
2394
|
-
acid: "#ccff4d",
|
|
2395
|
-
acidDim: "#a9d63f",
|
|
2396
|
-
cyan: "#56d8ff",
|
|
2397
|
-
red: "#ff5d5d",
|
|
2398
|
-
yellow: "#ffd24d",
|
|
2399
|
-
ink: "#f2f3f6",
|
|
2400
|
-
ink2: "#aeb0ba",
|
|
2401
|
-
ink3: "#6c6e79",
|
|
2402
|
-
ink4: "#44464f",
|
|
2403
|
-
panel: "#101115",
|
|
2404
|
-
panelUser: "#14161b",
|
|
2405
|
-
toolPending: "#0e1013",
|
|
2406
|
-
toolSuccess: "#10150c",
|
|
2407
|
-
toolError: "#1a0f0f",
|
|
2408
|
-
customMsg: "#0f1410"
|
|
2409
|
-
},
|
|
2410
|
-
colors: {
|
|
2411
|
-
accent: "acid",
|
|
2412
|
-
border: "ink4",
|
|
2413
|
-
borderAccent: "acid",
|
|
2414
|
-
borderMuted: "ink4",
|
|
2415
|
-
success: "acid",
|
|
2416
|
-
error: "red",
|
|
2417
|
-
warning: "yellow",
|
|
2418
|
-
muted: "ink3",
|
|
2419
|
-
dim: "ink4",
|
|
2420
|
-
text: "ink",
|
|
2421
|
-
thinkingText: "ink3",
|
|
2422
|
-
selectedBg: "panel",
|
|
2423
|
-
userMessageBg: "panelUser",
|
|
2424
|
-
userMessageText: "ink",
|
|
2425
|
-
customMessageBg: "customMsg",
|
|
2426
|
-
customMessageText: "ink2",
|
|
2427
|
-
customMessageLabel: "acidDim",
|
|
2428
|
-
toolPendingBg: "toolPending",
|
|
2429
|
-
toolSuccessBg: "toolSuccess",
|
|
2430
|
-
toolErrorBg: "toolError",
|
|
2431
|
-
toolTitle: "ink",
|
|
2432
|
-
toolOutput: "ink3",
|
|
2433
|
-
mdHeading: "acid",
|
|
2434
|
-
mdLink: "cyan",
|
|
2435
|
-
mdLinkUrl: "ink4",
|
|
2436
|
-
mdCode: "acidDim",
|
|
2437
|
-
mdCodeBlock: "ink2",
|
|
2438
|
-
mdCodeBlockBorder: "ink4",
|
|
2439
|
-
mdQuote: "ink3",
|
|
2440
|
-
mdQuoteBorder: "ink4",
|
|
2441
|
-
mdHr: "ink4",
|
|
2442
|
-
mdListBullet: "acid",
|
|
2443
|
-
toolDiffAdded: "acid",
|
|
2444
|
-
toolDiffRemoved: "red",
|
|
2445
|
-
toolDiffContext: "ink3",
|
|
2446
|
-
syntaxComment: "ink3",
|
|
2447
|
-
syntaxKeyword: "cyan",
|
|
2448
|
-
syntaxFunction: "acid",
|
|
2449
|
-
syntaxVariable: "ink",
|
|
2450
|
-
syntaxString: "acidDim",
|
|
2451
|
-
syntaxNumber: "yellow",
|
|
2452
|
-
syntaxType: "cyan",
|
|
2453
|
-
syntaxOperator: "ink2",
|
|
2454
|
-
syntaxPunctuation: "ink3",
|
|
2455
|
-
thinkingOff: "ink4",
|
|
2456
|
-
thinkingMinimal: "ink3",
|
|
2457
|
-
thinkingLow: "ink2",
|
|
2458
|
-
thinkingMedium: "cyan",
|
|
2459
|
-
thinkingHigh: "acidDim",
|
|
2460
|
-
thinkingXhigh: "acid",
|
|
2461
|
-
bashMode: "cyan"
|
|
2462
|
-
}
|
|
2463
|
-
};
|
|
2464
|
-
});
|
|
2465
|
-
|
|
2466
|
-
// packages/cli/src/commands/_operator-view.ts
|
|
2467
|
-
function runStatusFromPayload(payload) {
|
|
2468
|
-
const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
|
|
2469
|
-
return String(run.status ?? "unknown").toLowerCase();
|
|
2470
|
-
}
|
|
2471
|
-
async function applyOperatorCommand(context, input, deps = {}) {
|
|
2472
|
-
const line = input.line.trim();
|
|
2473
|
-
if (!line)
|
|
2474
|
-
return { action: "ignored" };
|
|
2475
|
-
if (line === "/detach" || line === "/quit" || line === "/q") {
|
|
2476
|
-
return { action: "detach", message: "Detached from run." };
|
|
2477
|
-
}
|
|
2478
|
-
if (line === "/stop") {
|
|
2479
|
-
await (deps.stop ?? stopRunViaServer)(context, input.runId);
|
|
2480
|
-
return { action: "stopped", message: "Stop requested." };
|
|
2481
|
-
}
|
|
2482
|
-
const userMessage = line.startsWith("/user ") ? line.slice("/user ".length).trim() : line;
|
|
2483
|
-
if (!userMessage)
|
|
2484
|
-
return { action: "ignored" };
|
|
2485
|
-
await (deps.steer ?? steerRunViaServer)(context, input.runId, userMessage);
|
|
2486
|
-
return { action: "continue", message: "Steering message queued." };
|
|
2487
|
-
}
|
|
2488
|
-
async function readOperatorSnapshot(context, runId, options = {}) {
|
|
2489
|
-
const run = await getRunDetailsViaServer(context, runId);
|
|
2490
|
-
const logsPage = await getRunLogsViaServer(context, runId, { limit: 100 });
|
|
2491
|
-
const timelinePage = await getRunTimelineViaServer(context, runId, { limit: 200, ...options.timelineCursor ? { cursor: options.timelineCursor } : {} }).catch((error) => ({
|
|
2492
|
-
entries: [{
|
|
2493
|
-
id: `timeline-unavailable:${runId}`,
|
|
2494
|
-
type: "timeline_warning",
|
|
2495
|
-
detail: `Selected Rig server did not provide run timeline events: ${error instanceof Error ? error.message : String(error)}`,
|
|
2496
|
-
createdAt: new Date().toISOString()
|
|
2497
|
-
}],
|
|
2498
|
-
nextCursor: options.timelineCursor ?? null
|
|
2499
|
-
}));
|
|
2500
|
-
const logs = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))).toReversed() : [];
|
|
2501
|
-
const timeline = Array.isArray(timelinePage.entries) ? timelinePage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
|
|
2502
|
-
const timelineCursor = typeof timelinePage.nextCursor === "string" ? timelinePage.nextCursor : options.timelineCursor ?? null;
|
|
2503
|
-
return { run, logs, timeline, timelineCursor, rendered: renderOperatorSnapshot({ run, logs, timeline }) };
|
|
2504
|
-
}
|
|
2505
|
-
async function attachRunOperatorView(context, input) {
|
|
2506
|
-
let steered = false;
|
|
2507
|
-
const attachMessage = input.message?.trim();
|
|
2508
|
-
if (attachMessage) {
|
|
2509
|
-
await withSpinner("Queueing steering message\u2026", () => sendRunPiPromptViaServer(context, input.runId, attachMessage, "steer").catch(() => steerRunViaServer(context, input.runId, attachMessage)), { outputMode: context.outputMode });
|
|
2510
|
-
steered = true;
|
|
2511
|
-
}
|
|
2512
|
-
if (!input.once && input.interactive !== false && context.outputMode === "text" && Boolean(process.stdin.isTTY && process.stdout.isTTY)) {
|
|
2513
|
-
return attachRunBundledPiFrontend(context, {
|
|
2514
|
-
runId: input.runId,
|
|
2515
|
-
steered
|
|
2516
|
-
});
|
|
2517
|
-
}
|
|
2518
|
-
const surface = createOperatorSurface({ interactive: input.interactive !== false });
|
|
2519
|
-
let snapshot = await withSpinner(`Connecting to run ${input.runId}\u2026`, () => readOperatorSnapshot(context, input.runId), { outputMode: context.outputMode });
|
|
2520
|
-
if (context.outputMode === "text") {
|
|
2521
|
-
surface.renderSnapshot(snapshot);
|
|
2522
|
-
surface.renderTimeline(snapshot.timeline);
|
|
2523
|
-
surface.renderLogs(snapshot.logs);
|
|
2524
|
-
if (steered)
|
|
2525
|
-
surface.info("Message submitted to worker Pi.");
|
|
2526
|
-
}
|
|
2527
|
-
let detached = false;
|
|
2528
|
-
let commandInput = null;
|
|
2529
|
-
if (input.follow && !input.once && context.outputMode === "text") {
|
|
2530
|
-
if (input.interactive !== false && process.stdin.isTTY) {
|
|
2531
|
-
surface.info("Controls: /user <message>, /stop, /detach");
|
|
2532
|
-
commandInput = surface.attachCommandInput(async (line) => {
|
|
2533
|
-
const result = await applyOperatorCommand(context, { runId: input.runId, line });
|
|
2534
|
-
if (result.message)
|
|
2535
|
-
surface.info(result.message);
|
|
2536
|
-
if (result.action === "detach" || result.action === "stopped") {
|
|
2537
|
-
detached = true;
|
|
2538
|
-
commandInput?.close();
|
|
2539
|
-
}
|
|
2540
|
-
});
|
|
2541
|
-
}
|
|
2542
|
-
const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
|
|
2543
|
-
let timelineCursor = snapshot.timelineCursor;
|
|
2544
|
-
while (!detached && !TERMINAL_RUN_STATUSES2.has(runStatusFromPayload(snapshot.run))) {
|
|
2545
|
-
await Bun.sleep(pollMs);
|
|
2546
|
-
snapshot = await readOperatorSnapshot(context, input.runId, { timelineCursor });
|
|
2547
|
-
timelineCursor = snapshot.timelineCursor;
|
|
2548
|
-
surface.renderSnapshot(snapshot);
|
|
2549
|
-
surface.renderTimeline(snapshot.timeline);
|
|
2550
|
-
surface.renderLogs(snapshot.logs);
|
|
2551
|
-
}
|
|
2552
|
-
commandInput?.close();
|
|
2553
|
-
}
|
|
2554
|
-
return { ...snapshot, steered, detached };
|
|
2555
|
-
}
|
|
2556
|
-
var TERMINAL_RUN_STATUSES2;
|
|
2557
|
-
var init__operator_view = __esm(() => {
|
|
2558
|
-
init__server_client();
|
|
2559
|
-
init__operator_surface();
|
|
2560
|
-
init__pi_frontend();
|
|
2561
|
-
init__async_ui();
|
|
2562
|
-
TERMINAL_RUN_STATUSES2 = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
|
|
2563
|
-
});
|
|
2564
|
-
|
|
2565
|
-
// packages/cli/src/commands/_cli-format.ts
|
|
2566
|
-
import pc2 from "picocolors";
|
|
2567
|
-
function stringField2(record, key, fallback = "") {
|
|
2568
|
-
const value = record[key];
|
|
2569
|
-
return typeof value === "string" && value.trim() ? value.trim() : fallback;
|
|
2570
|
-
}
|
|
2571
|
-
function numberField(record, key) {
|
|
2572
|
-
const value = record[key];
|
|
2573
|
-
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
2574
|
-
}
|
|
2575
|
-
function arrayField(record, key) {
|
|
2576
|
-
const value = record[key];
|
|
2577
|
-
return Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" && entry.trim() ? [entry.trim()] : []) : [];
|
|
2578
|
-
}
|
|
2579
|
-
function rawObject(record) {
|
|
2580
|
-
const raw = record.raw;
|
|
2581
|
-
return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
|
|
2582
|
-
}
|
|
2583
|
-
function truncate(value, width) {
|
|
2584
|
-
if (value.length <= width)
|
|
2585
|
-
return value;
|
|
2586
|
-
if (width <= 1)
|
|
2587
|
-
return "\u2026";
|
|
2588
|
-
return `${value.slice(0, width - 1)}\u2026`;
|
|
2589
|
-
}
|
|
2590
|
-
function pad(value, width) {
|
|
2591
|
-
return value.length >= width ? value : `${value}${" ".repeat(width - value.length)}`;
|
|
2592
|
-
}
|
|
2593
|
-
function statusColor(status) {
|
|
2594
|
-
const normalized = status.toLowerCase();
|
|
2595
|
-
if (["completed", "merged", "closed", "done", "accepted", "pass", "selected", "approved", "running"].includes(normalized))
|
|
2596
|
-
return accent;
|
|
2597
|
-
if (["failed", "needs_attention", "needs-attention", "blocked", "error", "rejected"].includes(normalized))
|
|
2598
|
-
return red;
|
|
2599
|
-
if (["reviewing", "validating", "in_progress", "in-progress", "remote", "preparing", "closing-out"].includes(normalized))
|
|
2600
|
-
return cyan;
|
|
2601
|
-
if (["ready", "open", "queued", "created", "local", "pending"].includes(normalized))
|
|
2602
|
-
return yellow;
|
|
2603
|
-
return themeDim;
|
|
2604
|
-
}
|
|
2605
|
-
function compactValue(value) {
|
|
2606
|
-
if (value === null || value === undefined)
|
|
2607
|
-
return "";
|
|
2608
|
-
if (typeof value === "string")
|
|
2609
|
-
return value;
|
|
2610
|
-
if (typeof value === "number" || typeof value === "boolean")
|
|
2611
|
-
return String(value);
|
|
2612
|
-
if (Array.isArray(value))
|
|
2613
|
-
return value.map(compactValue).filter(Boolean).join(", ");
|
|
2614
|
-
return JSON.stringify(value);
|
|
2615
|
-
}
|
|
2616
|
-
function shouldUseClackOutput() {
|
|
2617
|
-
return Boolean(process.stdout.isTTY) && process.env.RIG_CLI_PLAIN_HELP !== "1";
|
|
2618
|
-
}
|
|
2619
|
-
function printFormattedOutput(message2, options = {}) {
|
|
2620
|
-
if (!shouldUseClackOutput()) {
|
|
2621
|
-
console.log(message2);
|
|
2622
|
-
return;
|
|
2623
|
-
}
|
|
2624
|
-
droneNote(message2, options.title);
|
|
2625
|
-
}
|
|
2626
|
-
function formatStatusPill(status) {
|
|
2627
|
-
const label = status || "unknown";
|
|
2628
|
-
return statusColor(label)(`\u25CF ${label}`);
|
|
2629
|
-
}
|
|
2630
|
-
function formatSection(title, subtitle) {
|
|
2631
|
-
return `${pc2.bold(accent("\u25C6"))} ${pc2.bold(title)}${subtitle ? themeDim(` \u2014 ${subtitle}`) : ""}`;
|
|
2632
|
-
}
|
|
2633
|
-
function formatSuccessCard(title, rows = []) {
|
|
2634
|
-
const body = rows.filter(([, value]) => value !== undefined && value !== null && String(value).length > 0).map(([key, value]) => `${themeFaint("\u2502")} ${themeDim(key.padEnd(12))} ${value}`);
|
|
2635
|
-
return [formatSection(title), ...body].join(`
|
|
2636
|
-
`);
|
|
2637
|
-
}
|
|
2638
|
-
function formatNextSteps(steps) {
|
|
2639
|
-
if (steps.length === 0)
|
|
2640
|
-
return [];
|
|
2641
|
-
return [pc2.bold("Next"), ...steps.map((step) => `${accent("\u203A")} ${step}`)];
|
|
2642
|
-
}
|
|
2643
|
-
function formatTaskList(tasks, options = {}) {
|
|
2644
|
-
if (options.raw)
|
|
2645
|
-
return tasks.map((task) => JSON.stringify(task)).join(`
|
|
2646
|
-
`);
|
|
2647
|
-
if (tasks.length === 0)
|
|
2648
|
-
return [formatSection("Tasks", "none found"), ...formatNextSteps(["Try `rig server status` to confirm the selected server.", "Relax filters or run `rig task run --title ... --initial-prompt ...` for ad hoc work."])].join(`
|
|
2649
|
-
`);
|
|
2650
|
-
const rows = tasks.map((task) => {
|
|
2651
|
-
const raw = rawObject(task);
|
|
2652
|
-
const id = stringField2(task, "id", "<unknown>");
|
|
2653
|
-
const status = stringField2(task, "status", "unknown");
|
|
2654
|
-
const title = stringField2(task, "title", "Untitled task");
|
|
2655
|
-
const source = stringField2(task, "source", stringField2(raw, "source", ""));
|
|
2656
|
-
const labels = arrayField(task, "labels").length > 0 ? arrayField(task, "labels") : arrayField(raw, "labels");
|
|
2657
|
-
return { id, status, title, source, labels };
|
|
2658
|
-
});
|
|
2659
|
-
const idWidth = Math.min(18, Math.max(4, ...rows.map((row) => row.id.length)));
|
|
2660
|
-
const statusWidth = Math.min(16, Math.max(6, ...rows.map((row) => row.status.length)));
|
|
2661
|
-
const header = `${pc2.bold(pad("TASK", idWidth))} ${pc2.bold(pad("STATUS", statusWidth))} ${pc2.bold("TITLE")}`;
|
|
2662
|
-
const body = rows.map((row) => {
|
|
2663
|
-
const labels = row.labels.length > 0 ? themeDim(` ${row.labels.slice(0, 4).map((label) => `#${label}`).join(" ")}`) : "";
|
|
2664
|
-
const source = row.source ? themeDim(` ${row.source}`) : "";
|
|
2665
|
-
return [
|
|
2666
|
-
pc2.bold(pad(truncate(row.id, idWidth), idWidth)),
|
|
2667
|
-
statusColor(row.status)(pad(truncate(row.status, statusWidth), statusWidth)),
|
|
2668
|
-
`${row.title}${labels}${source}`
|
|
2669
|
-
].join(" ");
|
|
2670
|
-
});
|
|
2671
|
-
return [formatSection("Tasks", `${rows.length} shown`), header, ...body, "", ...formatNextSteps(["Run one: `rig task run <id>` or `rig task run --next`", "Attach later: `rig run attach <run-id> --follow`"])].join(`
|
|
2672
|
-
`);
|
|
2673
|
-
}
|
|
2674
|
-
function formatTaskCard(task, options = {}) {
|
|
2675
|
-
const raw = rawObject(task);
|
|
2676
|
-
const id = stringField2(task, "id", stringField2(raw, "id", "<unknown>"));
|
|
2677
|
-
const status = stringField2(task, "status", stringField2(raw, "status", "unknown"));
|
|
2678
|
-
const title = stringField2(task, "title", stringField2(raw, "title", "Untitled task"));
|
|
2679
|
-
const source = stringField2(task, "source", stringField2(raw, "source", ""));
|
|
2680
|
-
const url = stringField2(task, "url", stringField2(raw, "url", ""));
|
|
2681
|
-
const number = numberField(task, "number") ?? numberField(raw, "number");
|
|
2682
|
-
const labels = arrayField(task, "labels").length > 0 ? arrayField(task, "labels") : arrayField(raw, "labels");
|
|
2683
|
-
const assignees = arrayField(task, "assignees").length > 0 ? arrayField(task, "assignees") : arrayField(raw, "assignees");
|
|
2684
|
-
const readiness = compactValue(task.readiness ?? raw.readiness);
|
|
2685
|
-
const validators = compactValue(task.validators ?? raw.validators ?? task.validation ?? raw.validation);
|
|
2686
|
-
const rows = [
|
|
2687
|
-
["task", pc2.bold(id)],
|
|
2688
|
-
["status", formatStatusPill(status)],
|
|
2689
|
-
["title", title],
|
|
2690
|
-
["source", source],
|
|
2691
|
-
["number", number],
|
|
2692
|
-
["labels", labels.length ? labels.map((label) => `#${label}`).join(" ") : ""],
|
|
2693
|
-
["assignees", assignees.join(", ")],
|
|
2694
|
-
["readiness", readiness],
|
|
2695
|
-
["validators", validators],
|
|
2696
|
-
["url", url]
|
|
2697
|
-
];
|
|
2698
|
-
return [
|
|
2699
|
-
formatSuccessCard(options.title ?? (options.selected ? "Selected task" : "Task"), rows),
|
|
2700
|
-
"",
|
|
2701
|
-
...formatNextSteps([`Start: \`rig task run ${id}\``, `Details: \`rig task show ${id} --raw\``])
|
|
2702
|
-
].join(`
|
|
2703
|
-
`);
|
|
2704
|
-
}
|
|
2705
|
-
function formatTaskDetails(task) {
|
|
2706
|
-
return formatTaskCard(task, { title: "Task details" });
|
|
2707
|
-
}
|
|
2708
|
-
function formatSubmittedRun(input) {
|
|
2709
|
-
const rows = [["run", pc2.bold(input.runId)]];
|
|
2710
|
-
if (input.task) {
|
|
2711
|
-
const id = stringField2(input.task, "id", "<unknown>");
|
|
2712
|
-
const status = stringField2(input.task, "status", "unknown");
|
|
2713
|
-
const title = stringField2(input.task, "title", "Untitled task");
|
|
2714
|
-
rows.push(["task", `${pc2.bold(id)} ${formatStatusPill(status)} ${title}`]);
|
|
2715
|
-
}
|
|
2716
|
-
const runtime = [input.runtimeAdapter || "pi", input.runtimeMode || "full-access", input.interactionMode || "default"].filter(Boolean).join(" \xB7 ");
|
|
2717
|
-
rows.push(["runtime", runtime]);
|
|
2718
|
-
return [
|
|
2719
|
-
formatSuccessCard("Run submitted", rows),
|
|
2720
|
-
"",
|
|
2721
|
-
...formatNextSteps([
|
|
2722
|
-
`Attach: \`rig run attach ${input.runId} --follow\``,
|
|
2723
|
-
`Inspect: \`rig run show ${input.runId}\``,
|
|
2724
|
-
input.detached ? "Submitted detached; attach when you are ready." : "Interactive mode opens the enriched bundled Pi (native UI + Rig layers, worker brain)."
|
|
2725
|
-
])
|
|
2726
|
-
].join(`
|
|
2727
|
-
`);
|
|
2728
|
-
}
|
|
2729
|
-
var themeDim = (value) => ink3(value), themeFaint = (value) => ink4(value);
|
|
2730
|
-
var init__cli_format = __esm(() => {
|
|
2731
|
-
init_drone_ui();
|
|
2732
|
-
init_theme();
|
|
2733
|
-
});
|
|
2734
|
-
|
|
2735
|
-
// packages/cli/src/commands/inbox.ts
|
|
2736
|
-
async function listInboxRecords(context, kind, filters) {
|
|
2737
|
-
const params = new URLSearchParams;
|
|
2738
|
-
if (filters.run)
|
|
2739
|
-
params.set("runId", filters.run);
|
|
2740
|
-
if (filters.task)
|
|
2741
|
-
params.set("taskId", filters.task);
|
|
2742
|
-
const query = params.size > 0 ? `?${params.toString()}` : "";
|
|
2743
|
-
const payload = await requestServerJson(context, `/api/inbox/${kind}${query}`);
|
|
2744
|
-
const records = Array.isArray(payload) ? payload : [];
|
|
2745
|
-
return filters.pendingOnly ? records.filter((entry) => (entry.status ?? "pending") !== "resolved") : records;
|
|
2746
|
-
}
|
|
2747
|
-
async function readPendingInboxCounts(context) {
|
|
2748
|
-
try {
|
|
2749
|
-
const [approvals, inputs] = await Promise.all([
|
|
2750
|
-
listInboxRecords(context, "approvals", { pendingOnly: true }),
|
|
2751
|
-
listInboxRecords(context, "inputs", { pendingOnly: true })
|
|
2752
|
-
]);
|
|
2753
|
-
return { approvals: approvals.length, inputs: inputs.length };
|
|
2754
|
-
} catch {
|
|
2755
|
-
return null;
|
|
2756
|
-
}
|
|
2757
|
-
}
|
|
2758
|
-
async function printPendingInboxFooter(context) {
|
|
2759
|
-
if (context.outputMode !== "text")
|
|
2760
|
-
return;
|
|
2761
|
-
const counts = await readPendingInboxCounts(context);
|
|
2762
|
-
if (!counts || counts.approvals === 0 && counts.inputs === 0)
|
|
2763
|
-
return;
|
|
2764
|
-
const parts = [];
|
|
2765
|
-
if (counts.approvals > 0)
|
|
2766
|
-
parts.push(`${counts.approvals} approval${counts.approvals === 1 ? "" : "s"}`);
|
|
2767
|
-
if (counts.inputs > 0)
|
|
2768
|
-
parts.push(`${counts.inputs} input request${counts.inputs === 1 ? "" : "s"}`);
|
|
2769
|
-
console.log(`
|
|
2770
|
-
\u26A0 ${parts.join(" and ")} pending \u2014 run \`rig inbox\` to review.`);
|
|
2771
|
-
}
|
|
2772
|
-
var init_inbox = __esm(() => {
|
|
2773
|
-
init_runner();
|
|
2774
|
-
init__cli_format();
|
|
2775
|
-
init__server_client();
|
|
2776
|
-
init__async_ui();
|
|
2777
|
-
});
|
|
2778
|
-
|
|
2779
|
-
// packages/cli/src/commands/_help-catalog.ts
|
|
2780
|
-
import pc3 from "picocolors";
|
|
2781
|
-
function heading(title) {
|
|
2782
|
-
return pc3.bold(pc3.cyan(title));
|
|
2783
|
-
}
|
|
2784
|
-
function commandLine(command, description) {
|
|
2785
|
-
const commandColumn = command.length >= 38 ? `${command} ` : command.padEnd(38);
|
|
2786
|
-
return `${pc3.dim("\u2502")} ${pc3.bold(commandColumn)} ${description}`;
|
|
2787
|
-
}
|
|
2788
|
-
function renderCommandBlock(commands) {
|
|
2789
|
-
return commands.map((entry) => commandLine(entry.command, entry.description)).join(`
|
|
2790
|
-
`);
|
|
2791
|
-
}
|
|
2792
|
-
function renderGroup(group) {
|
|
2793
|
-
const lines = [
|
|
2794
|
-
`${heading(`rig ${group.name}`)} \u2014 ${group.summary}`,
|
|
2795
|
-
"",
|
|
2796
|
-
pc3.bold("Usage"),
|
|
2797
|
-
...group.usage.map((line) => ` ${line}`),
|
|
2798
|
-
"",
|
|
2799
|
-
pc3.bold("Commands"),
|
|
2800
|
-
...group.commands.map((entry) => commandLine(entry.command, entry.description))
|
|
2801
|
-
];
|
|
2802
|
-
if (group.examples?.length) {
|
|
2803
|
-
lines.push("", pc3.bold("Examples"), ...group.examples.map((line) => ` ${pc3.dim("$")} ${line}`));
|
|
2804
|
-
}
|
|
2805
|
-
if (group.next?.length) {
|
|
2806
|
-
lines.push("", pc3.bold("Next steps"), ...group.next.map((line) => ` ${pc3.dim("\u203A")} ${line}`));
|
|
2807
|
-
}
|
|
2808
|
-
if (group.advanced?.length) {
|
|
2809
|
-
lines.push("", pc3.bold("Compatibility / advanced"), ...group.advanced.map((line) => ` ${pc3.dim("\u203A")} ${line}`));
|
|
2810
|
-
}
|
|
2811
|
-
return lines.join(`
|
|
2812
|
-
`);
|
|
2813
|
-
}
|
|
2814
|
-
function renderTopLevelHelp() {
|
|
2815
|
-
return [
|
|
2816
|
-
`${heading("rig")} ${pc3.dim("\u2014 server-owned task/run control plane for Pi-backed engineering work")}`,
|
|
2817
|
-
pc3.dim("The loop: pick a task, dispatch an agent, open its Pi console (`rig run attach <id>`) to watch and steer it live, clear inbox gates, merge."),
|
|
2818
|
-
"",
|
|
2819
|
-
...TOP_LEVEL_SECTIONS.flatMap((section) => [
|
|
2820
|
-
`${pc3.bold(pc3.magenta(`\u25C7 ${section.title}`))} \u2014 ${pc3.dim(section.subtitle)}`,
|
|
2821
|
-
renderCommandBlock(section.commands),
|
|
2822
|
-
""
|
|
2823
|
-
]),
|
|
2824
|
-
pc3.dim("More: `rig help --advanced` for dev/compatibility commands; `rig <group> --help` for rich per-group help; `rig --version` for the installed version."),
|
|
2825
|
-
"",
|
|
2826
|
-
pc3.bold("Global options"),
|
|
2827
|
-
commandLine("--project <path>", "Use a project root instead of auto-discovery."),
|
|
2828
|
-
commandLine("--json", "Emit structured output for scripts/agents."),
|
|
2829
|
-
commandLine("--dry-run", "Print the command plan without mutating state.")
|
|
2830
|
-
].join(`
|
|
2831
|
-
`).trimEnd();
|
|
2832
|
-
}
|
|
2833
|
-
function renderGroupHelp(groupName) {
|
|
2834
|
-
const group = ALL_GROUPS.find((candidate) => candidate.name === groupName);
|
|
2835
|
-
return group ? renderGroup(group) : null;
|
|
2836
|
-
}
|
|
2837
|
-
function printGroupHelpDocument(groupName) {
|
|
2838
|
-
console.log(renderGroupHelp(groupName) ?? renderTopLevelHelp());
|
|
2839
|
-
}
|
|
2840
|
-
var TOP_LEVEL_SECTIONS, PRIMARY_GROUPS, ADVANCED_GROUPS, ALL_GROUPS;
|
|
2841
|
-
var init__help_catalog = __esm(() => {
|
|
2842
|
-
TOP_LEVEL_SECTIONS = [
|
|
2843
|
-
{
|
|
2844
|
-
title: "Pi console",
|
|
2845
|
-
subtitle: "the operator surface \u2014 every attach opens the run's FULL Pi session",
|
|
2846
|
-
commands: [
|
|
2847
|
-
{ command: "rig run attach <run-id>", description: "Open the run's Pi console: complete transcript (live AND finished runs), worker turns streaming in live." },
|
|
2848
|
-
{ command: "type a message", description: "Inside the console, plain text steers the worker mid-turn \u2014 it lands in the agent's context, not a local model." },
|
|
2849
|
-
{ command: "!<command>", description: "Inside the console, runs shell in the WORKER's workspace; output streams back into the transcript." },
|
|
2850
|
-
{ command: "/<command>", description: "The palette includes the WORKER session's slash commands ([worker]-tagged) next to /rig." },
|
|
2851
|
-
{ command: "/rig abort | /rig stop", description: "Abort the worker's current turn, or stop the whole run, from inside the console." },
|
|
2852
|
-
{ command: "rig run steer <id> --message <text>", description: "Steer without attaching \u2014 queue a message; the worker picks it up within seconds." }
|
|
2853
|
-
]
|
|
2854
|
-
},
|
|
2855
|
-
{
|
|
2856
|
-
title: "Start here",
|
|
2857
|
-
subtitle: "one-time setup, pick a server",
|
|
2858
|
-
commands: [
|
|
2859
|
-
{ command: "rig init", description: "Wizard: config, GitHub auth, task source, server, Pi wiring." },
|
|
2860
|
-
{ command: "rig server use <alias|local>", description: "Pick which Rig server owns this repo (`rig server list` to see them)." },
|
|
2861
|
-
{ command: "rig server status", description: "Show the selected server for this repo." }
|
|
2862
|
-
]
|
|
2863
|
-
},
|
|
2864
|
-
{
|
|
2865
|
-
title: "Work",
|
|
2866
|
-
subtitle: "find a task, put an agent on it, answer what it asks",
|
|
2867
|
-
commands: [
|
|
2868
|
-
{ command: "rig task list", description: "What's on the board (from the selected source/server)." },
|
|
2869
|
-
{ command: "rig task run --next", description: "Dispatch an agent on the next ready task; interactive mode drops you into its Pi console." },
|
|
2870
|
-
{ command: "rig run status", description: "Active and recent runs at a glance." },
|
|
2871
|
-
{ command: "rig run attach <id> --follow", description: "Same as plain attach \u2014 the Pi console is always the interactive surface." },
|
|
2872
|
-
{ command: "rig inbox approvals", description: "Approvals workers are waiting on (then `rig inbox approve \u2026`)." }
|
|
2873
|
-
]
|
|
2874
|
-
},
|
|
2875
|
-
{
|
|
2876
|
-
title: "Watch",
|
|
2877
|
-
subtitle: "fleet metrics and per-task forensics",
|
|
2878
|
-
commands: [
|
|
2879
|
-
{ command: "rig stats [--since 7d]", description: "Fleet metrics: completion/failure rates, median run time, steering, stalls." },
|
|
2880
|
-
{ command: "rig inspect logs --task <id>", description: "Latest run log for a task." },
|
|
2881
|
-
{ command: "rig inspect diff --task <id>", description: "Changed files for a task." }
|
|
2882
|
-
]
|
|
2883
|
-
},
|
|
2884
|
-
{
|
|
2885
|
-
title: "Unblock",
|
|
2886
|
-
subtitle: "diagnose wiring, fix auth",
|
|
2887
|
-
commands: [
|
|
2888
|
-
{ command: "rig doctor", description: "Check every part of the wiring \u2014 run this when anything feels off." },
|
|
2889
|
-
{ command: "rig github auth status", description: "GitHub auth state on the selected server." }
|
|
2890
|
-
]
|
|
2891
|
-
},
|
|
2892
|
-
{
|
|
2893
|
-
title: "Extend",
|
|
2894
|
-
subtitle: "plugins contribute validators, hooks, task sources, commands",
|
|
2895
|
-
commands: [
|
|
2896
|
-
{ command: "rig plugin list", description: "What the rig.config.ts plugins contribute." },
|
|
2897
|
-
{ command: "rig plugin run <command-id>", description: "Execute a plugin-contributed CLI command." }
|
|
2898
|
-
]
|
|
2899
|
-
}
|
|
2900
|
-
];
|
|
2901
|
-
PRIMARY_GROUPS = [
|
|
2902
|
-
{
|
|
2903
|
-
name: "server",
|
|
2904
|
-
summary: "Choose, inspect, and start the Rig server that owns tasks and runs.",
|
|
2905
|
-
usage: ["rig server <status|list|add|use|repair-link|start> [options]"],
|
|
2906
|
-
commands: [
|
|
2907
|
-
{ command: "status", description: "Show the selected server and remote project-root link for this repo.", primary: true },
|
|
2908
|
-
{ command: "use local", description: "Switch this repo to the local Rig server.", primary: true },
|
|
2909
|
-
{ command: "add <alias> <url>", description: "Save a remote Rig server URL.", primary: true },
|
|
2910
|
-
{ command: "use <alias>", description: "Select a saved remote server alias.", primary: true },
|
|
2911
|
-
{ command: "repair-link [--prepare|--backfill-only] [--repo owner/repo]", description: "Backfill or prepare the selected remote's server-host checkout link.", primary: true },
|
|
2912
|
-
{ command: "list", description: "List saved local/remote server aliases.", primary: true },
|
|
2913
|
-
{ command: "start [--host <host>] [--port <n>]", description: "Start a local rig-server process." }
|
|
2914
|
-
],
|
|
2915
|
-
examples: [
|
|
2916
|
-
"rig server status",
|
|
2917
|
-
"rig server add prod https://where.rig-does.work",
|
|
2918
|
-
"rig server use prod",
|
|
2919
|
-
"rig server repair-link --repo owner/repo",
|
|
2920
|
-
"rig server use local",
|
|
2921
|
-
"rig server start --port 3773"
|
|
2922
|
-
],
|
|
2923
|
-
next: ["Use `rig task list` to see server-owned work.", "Use `rig run list` or `rig run attach <id> --follow` to monitor runs."]
|
|
2924
|
-
},
|
|
2925
|
-
{
|
|
2926
|
-
name: "task",
|
|
2927
|
-
summary: "Find work, start Pi-backed runs, and validate task results.",
|
|
2928
|
-
usage: ["rig task <list|next|show|run> [options]"],
|
|
2929
|
-
commands: [
|
|
2930
|
-
{ command: "list [--assignee <login|me|@me>] [--state open|closed]", description: "List tasks from the selected server/source.", primary: true },
|
|
2931
|
-
{ command: "next [filters]", description: "Render the next matching task as a selected-task card.", primary: true },
|
|
2932
|
-
{ command: "show <id>|--task <id> [--raw]", description: "Show a human task summary; --raw prints the full payload.", primary: true },
|
|
2933
|
-
{ command: "run [#<issue>|<task-id>|--next|--task <id>]", description: "Submit a task run; interactive follows with bundled Pi.", primary: true },
|
|
2934
|
-
{ command: "ready", description: "List task IDs that are runnable now." },
|
|
2935
|
-
{ command: "validate|verify [--task <id>]", description: "Run configured task checks/review gates." },
|
|
2936
|
-
{ command: "details --task <id>", description: "Show full task info from the configured source." },
|
|
2937
|
-
{ command: "reopen [--task <id> | --all] [--reason <text>]", description: "Reopen closed task(s) in the configured source." },
|
|
2938
|
-
{ command: "artifacts|artifact-dir|artifact-write", description: "Inspect or write task artifacts." },
|
|
2939
|
-
{ command: "report-bug", description: "Create a structured bug report/task." }
|
|
2940
|
-
],
|
|
2941
|
-
examples: [
|
|
2942
|
-
"rig task list --assignee @me --limit 20",
|
|
2943
|
-
"rig task next",
|
|
2944
|
-
"rig task show 123 --raw",
|
|
2945
|
-
"rig task run --next",
|
|
2946
|
-
"rig task run #123 --runtime-adapter pi",
|
|
2947
|
-
"rig task run --title 'Investigate deploy drift' --initial-prompt 'Check server health'"
|
|
2948
|
-
],
|
|
2949
|
-
next: ["Use `--detach` to submit without attaching.", "Use `rig run attach <run-id> --follow` to rejoin a live run."]
|
|
2950
|
-
},
|
|
2951
|
-
{
|
|
2952
|
-
name: "run",
|
|
2953
|
-
summary: "Observe, attach to, and control Rig runs. `attach` opens the Pi console \u2014 the full worker session, live.",
|
|
2954
|
-
usage: ["rig run <list|status|show|attach|steer|stop|resume|restart> [options]"],
|
|
2955
|
-
commands: [
|
|
2956
|
-
{ command: "list", description: "List recent runs from the selected server or local state.", primary: true },
|
|
2957
|
-
{ command: "status", description: "Render active and recent run groups.", primary: true },
|
|
2958
|
-
{ command: "show <id>|--run <id> [--raw]", description: "Show a human run summary; --raw prints the full payload.", primary: true },
|
|
2959
|
-
{ command: "attach <run-id>|--run <id>", description: "Open the run's Pi console \u2014 see 'Inside the console' below. Works on live AND finished runs.", primary: true },
|
|
2960
|
-
{ command: "steer <run-id> --message <text>", description: "Queue a steering message into a live worker without attaching \u2014 delivered into the agent's context within seconds.", primary: true },
|
|
2961
|
-
{ command: "stop [<run-id>|--run <id>]", description: "Request stop for one run or local active runs.", primary: true },
|
|
2962
|
-
{ command: "resume [<run-id>]", description: "Resume an interrupted run on the selected server (defaults to the most recent resumable)." },
|
|
2963
|
-
{ command: "restart [<run-id>]", description: "Re-dispatch a run from a clean runtime, reopening its Pi session where possible." },
|
|
2964
|
-
{ command: "timeline --run <id> [--follow]", description: "Stream raw run timeline events (scripts; humans should attach)." },
|
|
2965
|
-
{ command: "replay <run-id>|--run <id> [--with-session]", description: "Print the run's consolidated run.jsonl as a merged timeline; --with-session interleaves the Pi session log." },
|
|
2966
|
-
{ command: "delete|cleanup", description: "Remove completed run records/artifacts." }
|
|
2967
|
-
],
|
|
2968
|
-
examples: [
|
|
2969
|
-
"rig run attach <run-id> # full session console \u2014 live mirror, steering, worker shell",
|
|
2970
|
-
"rig run steer <run-id> --message 'focus on the failing test first'",
|
|
2971
|
-
"rig run list",
|
|
2972
|
-
"rig run show <run-id>",
|
|
2973
|
-
"rig run stop <run-id>"
|
|
2974
|
-
],
|
|
2975
|
-
next: [
|
|
2976
|
-
"Inside the console: the run's COMPLETE transcript loads on open (finished runs too), and new worker turns stream in live.",
|
|
2977
|
-
"Inside the console: plain text = steering into the worker's context \xB7 !<cmd> = shell in the WORKER workspace \xB7 /<cmd> includes the worker session's commands \xB7 /rig abort stops the current turn.",
|
|
2978
|
-
"The console is read-write but remote-only: nothing runs on your machine; the worker keeps running when you exit.",
|
|
2979
|
-
"Use `rig task run --next` to create a new run; interactive mode drops you straight into its console.",
|
|
2980
|
-
"Use `--json` when scripts need the full structured record."
|
|
2981
|
-
]
|
|
2982
|
-
},
|
|
2983
|
-
{
|
|
2984
|
-
name: "inbox",
|
|
2985
|
-
summary: "Review approval and user-input requests that block worker runs.",
|
|
2986
|
-
usage: ["rig inbox <approvals|approve|inputs|respond> [options]"],
|
|
2987
|
-
commands: [
|
|
2988
|
-
{ command: "approvals [--run <id>] [--task <id>]", description: "List pending approvals.", primary: true },
|
|
2989
|
-
{ command: "inputs [--run <id>] [--task <id>]", description: "List pending user-input requests.", primary: true },
|
|
2990
|
-
{ command: "approve --run <id> --request <id> --decision approve|reject", description: "Resolve an approval request." },
|
|
2991
|
-
{ command: "respond --run <id> --request <id> --answer key=value", description: "Answer a user-input request." }
|
|
2992
|
-
],
|
|
2993
|
-
examples: [
|
|
2994
|
-
"rig inbox approvals",
|
|
2995
|
-
"rig inbox inputs --run <run-id>",
|
|
2996
|
-
"rig inbox approve --run <run-id> --request <request-id> --decision approve"
|
|
2997
|
-
],
|
|
2998
|
-
next: ["Rejoin the run after resolving a block: `rig run attach <run-id> --follow`."]
|
|
2999
|
-
},
|
|
3000
|
-
{
|
|
3001
|
-
name: "stats",
|
|
3002
|
-
summary: "Fleet metrics computed from on-disk run journals (no server required).",
|
|
3003
|
-
usage: ["rig stats [show] [--since <7d|30d|ISO date>]"],
|
|
3004
|
-
commands: [
|
|
3005
|
-
{ command: "show [--since <window>]", description: "Total runs, completion/failure/needs-attention rates, median run time, steering, stalls, approvals.", primary: true }
|
|
3006
|
-
],
|
|
3007
|
-
examples: [
|
|
3008
|
-
"rig stats",
|
|
3009
|
-
"rig stats --since 7d",
|
|
3010
|
-
"rig stats --since 2026-06-01 --json"
|
|
3011
|
-
],
|
|
3012
|
-
next: ["Inspect outliers with `rig run list` and `rig run show <run-id>`.", "Use `--json` for the schema'd envelope (see docs/cli-json.md)."]
|
|
3013
|
-
},
|
|
3014
|
-
{
|
|
3015
|
-
name: "inspect",
|
|
3016
|
-
summary: "Inspect logs, artifacts, graphs, failures for a task.",
|
|
3017
|
-
usage: ["rig inspect <logs|artifacts|failures|graph|audit|diff> --task <id>"],
|
|
3018
|
-
commands: [
|
|
3019
|
-
{ command: "logs --task <id>", description: "Latest run log for a task (local or selected server).", primary: true },
|
|
3020
|
-
{ command: "artifacts --task <id>", description: "List the task's completion artifacts.", primary: true },
|
|
3021
|
-
{ command: "failures --task <id>", description: "Recorded failures for a task.", primary: true },
|
|
3022
|
-
{ command: "diff --task <id>", description: "Changed files for a task.", primary: true },
|
|
3023
|
-
{ command: "graph", description: "Task dependency graph." },
|
|
3024
|
-
{ command: "audit", description: "Controlled-command audit trail." }
|
|
3025
|
-
],
|
|
3026
|
-
examples: ["rig inspect logs --task <id>", "rig inspect diff --task <id>"],
|
|
3027
|
-
next: ["Use `rig stats` for fleet-level metrics across runs."]
|
|
3028
|
-
},
|
|
3029
|
-
{
|
|
3030
|
-
name: "repo",
|
|
3031
|
-
summary: "Repository sync/baseline helpers for the Rig-managed checkout.",
|
|
3032
|
-
usage: ["rig repo <sync|reset-baseline>"],
|
|
3033
|
-
commands: [
|
|
3034
|
-
{ command: "sync", description: "Sync project repository state.", primary: true },
|
|
3035
|
-
{ command: "reset-baseline", description: "Reset the managed baseline for the repo." }
|
|
3036
|
-
],
|
|
3037
|
-
examples: ["rig repo sync"]
|
|
3038
|
-
},
|
|
3039
|
-
{
|
|
3040
|
-
name: "plugin",
|
|
3041
|
-
summary: "Plugin listing, validation, and plugin-contributed commands.",
|
|
3042
|
-
usage: ["rig plugin <list|validate|run> [options]"],
|
|
3043
|
-
commands: [
|
|
3044
|
-
{ command: "list", description: "List plugins declared in rig.config.ts and their contributions.", primary: true },
|
|
3045
|
-
{ command: "validate --task <id>", description: "Run plugin-contributed validators for a task.", primary: true },
|
|
3046
|
-
{ command: "run <command-id> [args...]", description: "Execute a plugin-contributed CLI command (also callable as `rig <command-id>`)." }
|
|
3047
|
-
],
|
|
3048
|
-
examples: ["rig plugin list", "rig plugin run <command-id>"]
|
|
3049
|
-
},
|
|
3050
|
-
{
|
|
3051
|
-
name: "init",
|
|
3052
|
-
summary: "Set up Rig for this repo: server, GitHub auth, checkout strategy, task source, and Pi wiring.",
|
|
3053
|
-
usage: ["rig init [--yes] [--server local|remote] [--repo owner/repo] [--remote-url <url>]"],
|
|
3054
|
-
commands: [
|
|
3055
|
-
{ command: "init", description: "Interactive setup wizard for a new or existing Rig repo.", primary: true },
|
|
3056
|
-
{ command: "init --demo", description: "Offline demo project: files task source + 3 sample tasks, zero GitHub.", primary: true },
|
|
3057
|
-
{ command: "init --yes", description: "Non-interactive setup using detected/default settings.", primary: true },
|
|
3058
|
-
{ command: "init --server remote --remote-url <url>", description: "Link this repo to a remote Rig server.", primary: true },
|
|
3059
|
-
{ command: "init --repair", description: "Repair missing private state without replacing project config." }
|
|
3060
|
-
],
|
|
3061
|
-
examples: [
|
|
3062
|
-
"rig init",
|
|
3063
|
-
"rig init --demo",
|
|
3064
|
-
"rig init --yes --repo humanity-org/humanwork",
|
|
3065
|
-
"rig init --server remote --remote-url https://where.rig-does.work --repo owner/repo"
|
|
3066
|
-
],
|
|
3067
|
-
next: ["After init, run `rig server status`.", "Then use `rig task list` and `rig task run --next` for day-to-day work."]
|
|
3068
|
-
},
|
|
3069
|
-
{
|
|
3070
|
-
name: "doctor",
|
|
3071
|
-
summary: "Diagnostics for project/server/GitHub/Pi state.",
|
|
3072
|
-
usage: ["rig doctor"],
|
|
3073
|
-
commands: [
|
|
3074
|
-
{ command: "doctor", description: "Run setup and runtime diagnostics.", primary: true },
|
|
3075
|
-
{ command: "check", description: "Compatibility spelling for diagnostics." }
|
|
3076
|
-
],
|
|
3077
|
-
examples: ["rig doctor", "rig doctor --json"],
|
|
3078
|
-
next: ["Use `rig server status` and `rig github auth status` to inspect common failure points."]
|
|
3079
|
-
},
|
|
3080
|
-
{
|
|
3081
|
-
name: "github",
|
|
3082
|
-
summary: "GitHub auth helpers for the selected Rig server.",
|
|
3083
|
-
usage: ["rig github auth <status|import-gh|token>"],
|
|
3084
|
-
commands: [
|
|
3085
|
-
{ command: "auth status", description: "Show GitHub auth state.", primary: true },
|
|
3086
|
-
{ command: "auth import-gh", description: "Import the current `gh` token into the selected server." },
|
|
3087
|
-
{ command: "auth token --token <token>", description: "Store a token on the selected server." }
|
|
3088
|
-
],
|
|
3089
|
-
examples: ["rig github auth status", "rig github auth import-gh"],
|
|
3090
|
-
next: ["After auth is valid, use `rig task run --next`."]
|
|
3091
|
-
}
|
|
3092
|
-
];
|
|
3093
|
-
ADVANCED_GROUPS = [
|
|
3094
|
-
{
|
|
3095
|
-
name: "setup",
|
|
3096
|
-
summary: "Bootstrap/check local setup.",
|
|
3097
|
-
usage: ["rig setup <bootstrap|check|preflight>"],
|
|
3098
|
-
commands: [
|
|
3099
|
-
{ command: "bootstrap", description: "Bootstrap local setup dependencies.", primary: true },
|
|
3100
|
-
{ command: "check", description: "Check local setup state (toolchain, deps, config).", primary: true },
|
|
3101
|
-
{ command: "preflight", description: "Run preflight checks before a run.", primary: true }
|
|
3102
|
-
]
|
|
3103
|
-
},
|
|
3104
|
-
{
|
|
3105
|
-
name: "profile",
|
|
3106
|
-
summary: "Runtime profile/model defaults.",
|
|
3107
|
-
usage: ["rig profile <show|set>"],
|
|
3108
|
-
commands: [
|
|
3109
|
-
{ command: "show", description: "Show the active execution profile.", primary: true },
|
|
3110
|
-
{ command: "set [--model <model>] [--runtime <runtime>] [--plugin <plugin>]", description: "Set model/runtime/plugin profile defaults.", primary: true }
|
|
3111
|
-
]
|
|
3112
|
-
},
|
|
3113
|
-
{
|
|
3114
|
-
name: "review",
|
|
3115
|
-
summary: "Inspect or change completion review gate policy.",
|
|
3116
|
-
usage: ["rig review <show|set>"],
|
|
3117
|
-
commands: [
|
|
3118
|
-
{ command: "show", description: "Show current review gate settings." },
|
|
3119
|
-
{ command: "set <off|advisory|required> [--provider <provider>]", description: "Change review strictness/provider (e.g. --provider greptile)." }
|
|
3120
|
-
],
|
|
3121
|
-
examples: ["rig review show", "rig review set required --provider greptile"],
|
|
3122
|
-
next: ["Use `rig inbox approvals` for blocked run handoffs."]
|
|
3123
|
-
},
|
|
3124
|
-
{
|
|
3125
|
-
name: "browser",
|
|
3126
|
-
summary: "Browser workstation actions for browser-required tasks: launch, check, CDP probe, profile reset, and app-specific smokes.",
|
|
3127
|
-
usage: ["rig browser <help|explain|demo|hp-next|cdp-probe|profile-persistence|profile-lock-check|smoke-test> [options]"],
|
|
3128
|
-
commands: [
|
|
3129
|
-
{ command: "help", description: "Rich browser command help (canonical: `rig browser help`).", primary: true },
|
|
3130
|
-
{ command: "explain", description: "Explain the browser-required task contract and runtime helper commands.", primary: true },
|
|
3131
|
-
{ command: "demo [--port <n>] [--profile <name>] [--state-dir <path>] [--target-url <url>] [--keep-open] [--no-build]", description: "Run a guided real browser/agent demo flow.", primary: true },
|
|
3132
|
-
{ command: "hp-next dev", description: "Start hp-next Rig Browser in dev/watch mode.", primary: true },
|
|
3133
|
-
{ command: "hp-next start", description: "Build/start the hp-next browser workstation without watch mode.", primary: true },
|
|
3134
|
-
{ command: "hp-next check", description: "Validate the hp-next CDP endpoint on the configured port.", primary: true },
|
|
3135
|
-
{ command: "hp-next e2e", description: "Run hp-next browser e2e smoke checks through Rig Browser.", primary: true },
|
|
3136
|
-
{ command: "hp-next reset", description: "Reset the hp-next browser profile when stale browser state is suspected.", primary: true },
|
|
3137
|
-
{ command: "cdp-probe", description: "Run an isolated CDP attach/evaluate/layout probe." },
|
|
3138
|
-
{ command: "profile-persistence", description: "Verify a named browser profile persists browser state." },
|
|
3139
|
-
{ command: "profile-lock-check", description: "Verify concurrent launches reject the same profile." },
|
|
3140
|
-
{ command: "smoke-test", description: "Run the browser package smoke test." }
|
|
3141
|
-
],
|
|
3142
|
-
examples: [
|
|
3143
|
-
"rig browser help",
|
|
3144
|
-
"rig browser hp-next check",
|
|
3145
|
-
"rig browser hp-next e2e",
|
|
3146
|
-
"rig browser cdp-probe",
|
|
3147
|
-
"rig browser profile-lock-check"
|
|
3148
|
-
],
|
|
3149
|
-
next: ["Inside a task run, use rig-browser-launch, rig-browser-check, and rig-browser-attach-info from the worker PATH."]
|
|
3150
|
-
},
|
|
3151
|
-
{
|
|
3152
|
-
name: "pi",
|
|
3153
|
-
summary: "Manage Pi extension packages for this project (community extensions from npm/git).",
|
|
3154
|
-
usage: ["rig pi <list|add|remove|search> [args]"],
|
|
3155
|
-
commands: [
|
|
3156
|
-
{ command: "list", description: "Show project and user Pi extension packages." },
|
|
3157
|
-
{ command: "add <source>", description: "Add an npm/git Pi extension to .pi/settings.json (auto-installs at next session)." },
|
|
3158
|
-
{ command: "remove <source>", description: "Remove an operator-added Pi extension." },
|
|
3159
|
-
{ command: "search [term]", description: "Discover Pi extension packages on the npm registry." }
|
|
3160
|
-
],
|
|
3161
|
-
examples: ["rig pi search subagents", "rig pi add pi-subagents", "rig pi list"],
|
|
3162
|
-
next: ["Config-managed extensions: declare `runtime: { pi: { packages: [...] } }` in rig.config.ts \u2014 workers pick them up automatically."]
|
|
3163
|
-
},
|
|
3164
|
-
{
|
|
3165
|
-
name: "queue",
|
|
3166
|
-
summary: "Run task queues locally.",
|
|
3167
|
-
usage: ["rig queue run [--workers <n>] [--max-tasks <n>] [--action validate|verify|pipeline] [--isolation off|worktree] [--no-runtime-reuse] [--fail-fast] [--skip-project-sync]"],
|
|
3168
|
-
commands: [
|
|
3169
|
-
{ command: "run [--workers <n>] [--max-tasks <n>] [--action validate|verify|pipeline] [--isolation off|worktree] [--no-runtime-reuse] [--fail-fast] [--skip-project-sync]", description: "Process queue work: drain matching tasks with N workers, optional per-task action and isolation.", primary: true }
|
|
3170
|
-
]
|
|
3171
|
-
},
|
|
3172
|
-
{
|
|
3173
|
-
name: "agent",
|
|
3174
|
-
summary: "Runtime agent workspace helpers.",
|
|
3175
|
-
usage: ["rig agent <list|prepare|run|cleanup>"],
|
|
3176
|
-
commands: [
|
|
3177
|
-
{ command: "list", description: "List prepared agent runtimes.", primary: true },
|
|
3178
|
-
{ command: "prepare [--id <id>] [--mode <mode>] [--task <task>]", description: "Prepare an isolated agent runtime workspace.", primary: true },
|
|
3179
|
-
{ command: "run [--id <id>] [--mode <mode>] [--task <task>] [--skip-project-sync]", description: "Prepare (if needed) and run an agent in its workspace.", primary: true },
|
|
3180
|
-
{ command: "cleanup [--all] [--id <id>]", description: "Remove prepared agent workspaces.", primary: true }
|
|
3181
|
-
]
|
|
3182
|
-
},
|
|
3183
|
-
{ name: "inspector", summary: "Event stream and drift scanners.", usage: ["rig inspector <stream|scan-upstream-drift>"], commands: [{ command: "stream", description: "Stream events." }] },
|
|
3184
|
-
{
|
|
3185
|
-
name: "dist",
|
|
3186
|
-
summary: "Build/install packaged Rig CLI.",
|
|
3187
|
-
usage: ["rig dist <build|install|doctor|rebuild-agent>"],
|
|
3188
|
-
commands: [
|
|
3189
|
-
{ command: "build [--output-dir <dir>]", description: "Build the distributable Rig CLI.", primary: true },
|
|
3190
|
-
{ command: "install [--scope <scope>] [--path <path>]", description: "Install the built CLI to a scope/path.", primary: true },
|
|
3191
|
-
{ command: "doctor", description: "Diagnose the dist toolchain and install state.", primary: true },
|
|
3192
|
-
{ command: "rebuild-agent", description: "Rebuild the agent runtime image, pruning stale images.", primary: true }
|
|
3193
|
-
]
|
|
3194
|
-
},
|
|
3195
|
-
{ name: "workspace", summary: "Workspace topology/service helpers.", usage: ["rig workspace <summary|topology|remote-hosts>"], commands: [{ command: "summary", description: "Show workspace summary." }] },
|
|
3196
|
-
{
|
|
3197
|
-
name: "remote",
|
|
3198
|
-
summary: "Compatibility remote orchestration controls.",
|
|
3199
|
-
usage: ["rig remote <status|tasks|watch|pause|resume|continue|stop|refresh|add-iterations|remove-iterations|endpoint ...>"],
|
|
3200
|
-
commands: [
|
|
3201
|
-
{ command: "status [--remote <alias>]", description: "Show the remote orchestration state.", primary: true },
|
|
3202
|
-
{ command: "tasks [--remote <alias>]", description: "List the remote's tracked tasks.", primary: true },
|
|
3203
|
-
{ command: "watch [--remote <alias>] [--seconds <n>] [--event <type>]", description: "Stream remote orchestration events.", primary: true },
|
|
3204
|
-
{ command: "pause [--remote <alias>]", description: "Pause the running remote orchestration.", primary: true },
|
|
3205
|
-
{ command: "resume [--remote <alias>] [--max-workers <n>] [--max-iterations <n>] [--direct-merge]", description: "Resume the remote with optional tuning.", primary: true },
|
|
3206
|
-
{ command: "continue [--remote <alias>]", description: "Continue a paused remote orchestration.", primary: true },
|
|
3207
|
-
{ command: "stop [--remote <alias>]", description: "Stop the remote orchestration.", primary: true },
|
|
3208
|
-
{ command: "refresh [--remote <alias>]", description: "Refresh remote state.", primary: true },
|
|
3209
|
-
{ command: "add-iterations [--count <n>] [--remote <alias>]", description: "Grant the remote more iterations.", primary: true },
|
|
3210
|
-
{ command: "remove-iterations [--count <n>] [--remote <alias>]", description: "Reduce the remote's iteration budget.", primary: true },
|
|
3211
|
-
{ command: "endpoint list", description: "List configured remote endpoints.", primary: true },
|
|
3212
|
-
{ command: "endpoint add --alias <alias> --host <host> --port <n> [--token <token>]", description: "Register a remote endpoint.", primary: true },
|
|
3213
|
-
{ command: "endpoint remove --alias <alias>", description: "Remove a remote endpoint.", primary: true },
|
|
3214
|
-
{ command: "endpoint test [--alias <alias>]", description: "Test connectivity to a remote endpoint.", primary: true },
|
|
3215
|
-
{ command: "endpoint doctor", description: "Diagnose remote endpoint configuration.", primary: true }
|
|
3216
|
-
]
|
|
3217
|
-
},
|
|
3218
|
-
{ name: "git", summary: "Pass through to Rig git-flow helper.", usage: ["rig git <args...>"], commands: [{ command: "<args...>", description: "Advanced git flow operations." }] },
|
|
3219
|
-
{ name: "harness", summary: "Pass through to runtime harness CLI.", usage: ["rig harness <args...>"], commands: [{ command: "<args...>", description: "Advanced harness operations." }] },
|
|
3220
|
-
{ name: "test", summary: "Project test wrappers.", usage: ["rig test <unit|e2e|all>"], commands: [{ command: "all", description: "Run configured project tests." }] }
|
|
3221
|
-
];
|
|
3222
|
-
ALL_GROUPS = [...PRIMARY_GROUPS, ...ADVANCED_GROUPS];
|
|
3223
|
-
});
|
|
3224
|
-
|
|
3225
|
-
// packages/cli/src/commands/task.ts
|
|
3226
|
-
var exports_task = {};
|
|
3227
|
-
__export(exports_task, {
|
|
3228
|
-
loadTaskRunProjectDefaults: () => loadTaskRunProjectDefaults,
|
|
3229
|
-
executeTask: () => executeTask
|
|
3230
|
-
});
|
|
3231
|
-
import { readFileSync as readFileSync4 } from "fs";
|
|
3232
|
-
import { spawnSync } from "child_process";
|
|
3233
|
-
import { resolve as resolve3 } from "path";
|
|
3234
|
-
import {
|
|
3235
|
-
taskArtifactDir,
|
|
3236
|
-
taskArtifacts,
|
|
3237
|
-
taskArtifactWrite,
|
|
3238
|
-
taskDeps,
|
|
3239
|
-
taskInfo,
|
|
3240
|
-
taskLookup,
|
|
3241
|
-
taskReady,
|
|
3242
|
-
taskRecord,
|
|
3243
|
-
taskReopen,
|
|
3244
|
-
taskScope,
|
|
3245
|
-
taskStatus as taskStatus2,
|
|
3246
|
-
taskValidate,
|
|
3247
|
-
taskVerify
|
|
3248
|
-
} from "@rig/runtime/control-plane/native/task-ops";
|
|
3249
|
-
import { buildPluginHostContext } from "@rig/runtime/control-plane/plugin-host-context";
|
|
3250
|
-
import { loadConfig } from "@rig/core/load-config";
|
|
3251
|
-
async function readStdin() {
|
|
3252
|
-
const chunks = [];
|
|
3253
|
-
for await (const chunk of process.stdin) {
|
|
3254
|
-
chunks.push(Buffer.from(chunk));
|
|
3255
|
-
}
|
|
3256
|
-
return Buffer.concat(chunks).toString("utf-8");
|
|
3257
|
-
}
|
|
3258
|
-
function normalizeAssigneeAlias(value) {
|
|
3259
|
-
if (!value)
|
|
3260
|
-
return;
|
|
3261
|
-
return value.trim().toLowerCase() === "me" ? "@me" : value;
|
|
3262
|
-
}
|
|
3263
|
-
function parseTaskFilters(args) {
|
|
3264
|
-
let pending = args;
|
|
3265
|
-
const assigneeResult = takeOption(pending, "--assignee");
|
|
3266
|
-
pending = assigneeResult.rest;
|
|
3267
|
-
const stateResult = takeOption(pending, "--state");
|
|
3268
|
-
pending = stateResult.rest;
|
|
3269
|
-
const statusResult = takeOption(pending, "--status");
|
|
3270
|
-
pending = statusResult.rest;
|
|
3271
|
-
const limitResult = takeOption(pending, "--limit");
|
|
3272
|
-
pending = limitResult.rest;
|
|
3273
|
-
const assignee = normalizeAssigneeAlias(assigneeResult.value);
|
|
3274
|
-
const limit = (() => {
|
|
3275
|
-
if (!limitResult.value)
|
|
3276
|
-
return;
|
|
3277
|
-
const parsed = Number.parseInt(limitResult.value, 10);
|
|
3278
|
-
if (!Number.isFinite(parsed) || parsed < 1) {
|
|
3279
|
-
throw new CliError("--limit must be a positive integer.", 2, { hint: "Re-run with a positive number, e.g. `rig task list --limit 20`." });
|
|
3280
|
-
}
|
|
3281
|
-
return parsed;
|
|
3282
|
-
})();
|
|
3283
|
-
const filters = {
|
|
3284
|
-
...assignee ? { assignee } : {},
|
|
3285
|
-
...stateResult.value ? { state: stateResult.value } : {},
|
|
3286
|
-
...statusResult.value ? { status: statusResult.value } : {},
|
|
3287
|
-
...limit !== undefined ? { limit } : {}
|
|
3288
|
-
};
|
|
3289
|
-
return { filters, rest: pending };
|
|
3290
|
-
}
|
|
3291
|
-
function mapConfiguredRuntimeMode(mode) {
|
|
3292
|
-
if (!mode)
|
|
3293
|
-
return;
|
|
3294
|
-
return mode === "yolo" ? "full-access" : mode;
|
|
3295
|
-
}
|
|
3296
|
-
async function loadTaskRunProjectDefaults(projectRoot) {
|
|
3297
|
-
try {
|
|
3298
|
-
const config = await loadConfig(projectRoot);
|
|
3299
|
-
return {
|
|
3300
|
-
runtimeAdapter: config.runtime?.harness,
|
|
3301
|
-
model: config.runtime?.model,
|
|
3302
|
-
runtimeMode: mapConfiguredRuntimeMode(config.runtime?.mode),
|
|
3303
|
-
prMode: config.pr?.mode
|
|
3304
|
-
};
|
|
3305
|
-
} catch {
|
|
3306
|
-
return {};
|
|
3307
|
-
}
|
|
3308
|
-
}
|
|
3309
|
-
function normalizePrMode(value) {
|
|
3310
|
-
if (!value)
|
|
3311
|
-
return;
|
|
3312
|
-
if (value === "auto" || value === "ask" || value === "off")
|
|
3313
|
-
return value;
|
|
3314
|
-
throw new CliError("--pr must be auto, ask, or off.", 2, { hint: "Re-run with `--pr auto|ask|off`, or pass `--no-pr` to disable the PR." });
|
|
3315
|
-
}
|
|
3316
|
-
function detectLocalDirtyState(projectRoot) {
|
|
3317
|
-
const result = spawnSync("git", ["-C", projectRoot, "status", "--porcelain"], { encoding: "utf8", timeout: 5000 });
|
|
3318
|
-
if (result.status !== 0)
|
|
3319
|
-
return { dirty: false, modified: 0, untracked: 0, lines: [] };
|
|
3320
|
-
const lines = result.stdout.split(/\r?\n/).map((line) => line.trimEnd()).filter(Boolean);
|
|
3321
|
-
return {
|
|
3322
|
-
dirty: lines.length > 0,
|
|
3323
|
-
modified: lines.filter((line) => !line.startsWith("?? ")).length,
|
|
3324
|
-
untracked: lines.filter((line) => line.startsWith("?? ")).length,
|
|
3325
|
-
lines
|
|
3326
|
-
};
|
|
3327
|
-
}
|
|
3328
|
-
function selectedServerKind(projectRoot) {
|
|
3329
|
-
try {
|
|
3330
|
-
return resolveSelectedConnection(projectRoot)?.connection.kind === "remote" ? "remote" : "local";
|
|
3331
|
-
} catch {
|
|
3332
|
-
return "local";
|
|
3333
|
-
}
|
|
3334
|
-
}
|
|
3335
|
-
async function resolveDirtyBaselineForTaskRun(context, explicit) {
|
|
3336
|
-
if (explicit && explicit !== "head" && explicit !== "dirty-snapshot") {
|
|
3337
|
-
throw new CliError("--dirty-baseline must be head or dirty-snapshot.", 2, { hint: "Re-run with `--dirty-baseline head` or `--dirty-baseline dirty-snapshot`." });
|
|
3338
|
-
}
|
|
3339
|
-
if (selectedServerKind(context.projectRoot) !== "local") {
|
|
3340
|
-
return { mode: explicit === "dirty-snapshot" ? "dirty-snapshot" : "head", state: null };
|
|
3341
|
-
}
|
|
3342
|
-
const state = detectLocalDirtyState(context.projectRoot);
|
|
3343
|
-
if (!state.dirty)
|
|
3344
|
-
return { mode: "head", state };
|
|
3345
|
-
if (context.outputMode === "text") {
|
|
3346
|
-
console.log(`Repo state: dirty (${state.modified} modified, ${state.untracked} untracked).`);
|
|
3347
|
-
}
|
|
3348
|
-
if (explicit)
|
|
3349
|
-
return { mode: explicit, state };
|
|
3350
|
-
if (context.outputMode === "text" && process.stdin.isTTY && process.stdout.isTTY) {
|
|
3351
|
-
const answer = await droneConfirm({
|
|
3352
|
-
message: "Include current uncommitted changes in run baseline?",
|
|
3353
|
-
initialValue: false
|
|
3354
|
-
});
|
|
3355
|
-
if (answer === null) {
|
|
3356
|
-
droneCancel("Run cancelled.");
|
|
3357
|
-
throw new CliError("Run cancelled by user.", 1);
|
|
3358
|
-
}
|
|
3359
|
-
return { mode: answer ? "dirty-snapshot" : "head", state };
|
|
3360
|
-
}
|
|
3361
|
-
return { mode: "head", state };
|
|
3362
|
-
}
|
|
3363
|
-
function normalizeTaskRunTaskId(value) {
|
|
3364
|
-
const trimmed = value?.trim() ?? "";
|
|
3365
|
-
if (!trimmed)
|
|
3366
|
-
return null;
|
|
3367
|
-
const issueNumber = trimmed.match(/^#(\d+)$/)?.[1];
|
|
3368
|
-
return issueNumber ?? trimmed;
|
|
3369
|
-
}
|
|
3370
|
-
function readTaskId(task) {
|
|
3371
|
-
return typeof task.id === "string" && task.id.trim().length > 0 ? task.id : null;
|
|
3372
|
-
}
|
|
3373
|
-
function readTaskString(task, key) {
|
|
3374
|
-
const value = task[key];
|
|
3375
|
-
return typeof value === "string" && value.trim().length > 0 ? value : null;
|
|
3376
|
-
}
|
|
3377
|
-
function summarizeTask(task, options = {}) {
|
|
3378
|
-
const raw = task.raw && typeof task.raw === "object" && !Array.isArray(task.raw) ? task.raw : null;
|
|
3379
|
-
return {
|
|
3380
|
-
id: readTaskId(task),
|
|
3381
|
-
title: readTaskString(task, "title"),
|
|
3382
|
-
status: readTaskString(task, "status"),
|
|
3383
|
-
source: typeof task.source === "string" ? task.source : undefined,
|
|
3384
|
-
url: typeof raw?.url === "string" ? raw.url : undefined,
|
|
3385
|
-
number: typeof raw?.number === "number" ? raw.number : undefined,
|
|
3386
|
-
labels: Array.isArray(task.labels) ? task.labels : Array.isArray(raw?.labels) ? raw.labels : undefined,
|
|
3387
|
-
assignees: Array.isArray(raw?.assignees) ? raw.assignees : undefined,
|
|
3388
|
-
readiness: typeof task.readiness === "string" || typeof task.readiness === "boolean" ? task.readiness : undefined,
|
|
3389
|
-
validators: Array.isArray(task.validators) ? task.validators : Array.isArray(task.validation) ? task.validation : undefined,
|
|
3390
|
-
...options.raw ? { raw: raw ?? task } : {}
|
|
3391
|
-
};
|
|
3392
|
-
}
|
|
3393
|
-
async function validatorRegistryForTaskCommands(projectRoot) {
|
|
3394
|
-
return buildPluginHostContext(projectRoot).then((ctx) => ctx?.validatorRegistry ?? undefined).catch(() => {
|
|
3395
|
-
return;
|
|
3396
|
-
});
|
|
3397
|
-
}
|
|
3398
|
-
async function executeTask(context, args, options) {
|
|
3399
|
-
if (args.length === 0) {
|
|
3400
|
-
if (context.outputMode === "text") {
|
|
3401
|
-
printGroupHelpDocument("task");
|
|
3402
|
-
}
|
|
3403
|
-
return { ok: true, group: "task", command: "help" };
|
|
3404
|
-
}
|
|
3405
|
-
const [command = "help", ...rest] = args;
|
|
3406
|
-
switch (command) {
|
|
3407
|
-
case "list": {
|
|
3408
|
-
let pending = rest;
|
|
3409
|
-
const rawResult = takeFlag(pending, "--raw");
|
|
3410
|
-
pending = rawResult.rest;
|
|
3411
|
-
const { filters, rest: remaining } = parseTaskFilters(pending);
|
|
3412
|
-
requireNoExtraArgs(remaining, "rig task list [--raw] [--assignee <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
|
|
3413
|
-
const tasks = await withSpinner("Reading tasks from server\u2026", () => listWorkspaceTasksViaServer(context, filters), { outputMode: context.outputMode });
|
|
3414
|
-
if (context.outputMode === "text") {
|
|
3415
|
-
const renderedTasks = rawResult.value ? tasks.map((task) => summarizeTask(task, { raw: true })) : tasks.map((task) => summarizeTask(task));
|
|
3416
|
-
printFormattedOutput(formatTaskList(renderedTasks, { raw: rawResult.value }));
|
|
3417
|
-
await printPendingInboxFooter(context);
|
|
3418
|
-
}
|
|
3419
|
-
return {
|
|
3420
|
-
ok: true,
|
|
3421
|
-
group: "task",
|
|
3422
|
-
command,
|
|
3423
|
-
details: { count: tasks.length, filters, raw: rawResult.value, tasks: tasks.map((task) => summarizeTask(task, { raw: rawResult.value })) }
|
|
3424
|
-
};
|
|
3425
|
-
}
|
|
3426
|
-
case "show": {
|
|
3427
|
-
let pending = rest;
|
|
3428
|
-
const rawResult = takeFlag(pending, "--raw");
|
|
3429
|
-
pending = rawResult.rest;
|
|
3430
|
-
const taskOption = takeOption(pending, "--task");
|
|
3431
|
-
const positional = taskOption.rest.length > 0 && taskOption.rest[0] && !taskOption.rest[0].startsWith("-") ? taskOption.rest[0] : undefined;
|
|
3432
|
-
const remaining = positional ? taskOption.rest.slice(1) : taskOption.rest;
|
|
3433
|
-
requireNoExtraArgs(remaining, "rig task show <id>|--task <id> [--raw]");
|
|
3434
|
-
const taskId3 = normalizeTaskRunTaskId(taskOption.value ?? positional);
|
|
3435
|
-
if (!taskId3)
|
|
3436
|
-
throw new CliError("task show requires a task id.", 2, { hint: "Run `rig task list` to find ids, then `rig task show <id>`." });
|
|
3437
|
-
const task = await withSpinner(`Reading task ${taskId3} from server\u2026`, () => getWorkspaceTaskViaServer(context, taskId3), { outputMode: context.outputMode });
|
|
3438
|
-
if (!task)
|
|
3439
|
-
throw new CliError(`Task not found: ${taskId3}`, 3, { hint: "Run `rig task list` to see available tasks." });
|
|
3440
|
-
const summary = summarizeTask(task, { raw: true });
|
|
3441
|
-
if (context.outputMode === "text") {
|
|
3442
|
-
printFormattedOutput(rawResult.value ? JSON.stringify(summary, null, 2) : formatTaskDetails(summary));
|
|
3443
|
-
}
|
|
3444
|
-
return { ok: true, group: "task", command, details: { task: summary, raw: rawResult.value } };
|
|
3445
|
-
}
|
|
3446
|
-
case "next": {
|
|
3447
|
-
const { filters, rest: remaining } = parseTaskFilters(rest);
|
|
3448
|
-
requireNoExtraArgs(remaining, "rig task next [--assignee <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
|
|
3449
|
-
const selected = await withSpinner("Selecting next ready task\u2026", () => selectNextWorkspaceTaskViaServer(context, filters), { outputMode: context.outputMode });
|
|
3450
|
-
if (context.outputMode === "text") {
|
|
3451
|
-
if (selected.task) {
|
|
3452
|
-
printFormattedOutput(formatTaskCard(summarizeTask(selected.task, { raw: true }), { title: "Selected task", selected: true }));
|
|
3453
|
-
} else {
|
|
3454
|
-
printFormattedOutput("No matching tasks.\n\nNext\n\u203A Try `rig task list` to inspect available work.\n\u203A Check server: `rig server status`");
|
|
3455
|
-
}
|
|
3456
|
-
}
|
|
3457
|
-
return {
|
|
3458
|
-
ok: true,
|
|
3459
|
-
group: "task",
|
|
3460
|
-
command,
|
|
3461
|
-
details: {
|
|
3462
|
-
count: selected.count,
|
|
3463
|
-
filters,
|
|
3464
|
-
task: selected.task ? summarizeTask(selected.task) : null
|
|
3465
|
-
}
|
|
3466
|
-
};
|
|
3467
|
-
}
|
|
3468
|
-
case "info": {
|
|
3469
|
-
const { value: task, rest: remaining } = takeOption(rest, "--task");
|
|
3470
|
-
requireNoExtraArgs(remaining, "rig task info [--task <task-id>]");
|
|
3471
|
-
await withMutedConsole(context.outputMode === "json", () => taskInfo(context.projectRoot, task || undefined));
|
|
3472
|
-
return { ok: true, group: "task", command, details: { task: task || null } };
|
|
3473
|
-
}
|
|
3474
|
-
case "scope": {
|
|
3475
|
-
const filesFlag = takeFlag(rest, "--files");
|
|
3476
|
-
const { value: task, rest: remaining } = takeOption(filesFlag.rest, "--task");
|
|
3477
|
-
requireNoExtraArgs(remaining, "rig task scope [--task <id>] [--files]");
|
|
3478
|
-
await withMutedConsole(context.outputMode === "json", () => taskScope(context.projectRoot, filesFlag.value, task || undefined));
|
|
3479
|
-
return { ok: true, group: "task", command, details: { files: filesFlag.value, task: task || null } };
|
|
3480
|
-
}
|
|
3481
|
-
case "deps":
|
|
3482
|
-
requireNoExtraArgs(rest, "rig task deps");
|
|
3483
|
-
await withMutedConsole(context.outputMode === "json", () => taskDeps(context.projectRoot));
|
|
3484
|
-
return { ok: true, group: "task", command };
|
|
3485
|
-
case "status":
|
|
3486
|
-
requireNoExtraArgs(rest, "rig task status");
|
|
3487
|
-
withMutedConsole(context.outputMode === "json", () => taskStatus2(context.projectRoot));
|
|
3488
|
-
return { ok: true, group: "task", command };
|
|
3489
|
-
case "artifacts":
|
|
3490
|
-
requireNoExtraArgs(rest, "rig task artifacts");
|
|
3491
|
-
withMutedConsole(context.outputMode === "json", () => taskArtifacts(context.projectRoot));
|
|
3492
|
-
return { ok: true, group: "task", command };
|
|
3493
|
-
case "artifact-dir": {
|
|
3494
|
-
requireNoExtraArgs(rest, "rig task artifact-dir");
|
|
3495
|
-
const path = taskArtifactDir(context.projectRoot);
|
|
3496
|
-
if (context.outputMode === "text") {
|
|
3497
|
-
console.log(path);
|
|
3498
|
-
}
|
|
3499
|
-
return { ok: true, group: "task", command, details: { path } };
|
|
3500
|
-
}
|
|
3501
|
-
case "artifact-write": {
|
|
3502
|
-
if (rest.length < 1) {
|
|
3503
|
-
throw new CliError(`Usage: rig task artifact-write <filename> [--file <path>]
|
|
3504
|
-
` + ` Reads content from stdin (or --file), writes to the active task artifact dir.
|
|
3505
|
-
` + " Example: echo '...' | rig task artifact-write collection-audit.md");
|
|
3506
|
-
}
|
|
3507
|
-
const artifactFilename = rest[0];
|
|
3508
|
-
const fileFlag = takeOption(rest.slice(1), "--file");
|
|
3509
|
-
let content;
|
|
3510
|
-
if (fileFlag.value) {
|
|
3511
|
-
content = readFileSync4(resolve3(context.projectRoot, fileFlag.value), "utf-8");
|
|
3512
|
-
} else {
|
|
3513
|
-
content = await readStdin();
|
|
3514
|
-
}
|
|
3515
|
-
if (!artifactFilename) {
|
|
3516
|
-
throw new CliError("Usage: rig task artifact-write <filename> [--file path]");
|
|
3517
|
-
}
|
|
3518
|
-
withMutedConsole(context.outputMode === "json", () => taskArtifactWrite(context.projectRoot, artifactFilename, content));
|
|
3519
|
-
return { ok: true, group: "task", command, details: { filename: artifactFilename } };
|
|
3520
|
-
}
|
|
3521
|
-
case "report-bug":
|
|
3522
|
-
return options.executeTaskReportBug(context, rest);
|
|
3523
|
-
case "lookup": {
|
|
3524
|
-
if (rest.length !== 1) {
|
|
3525
|
-
throw new CliError("Usage: rig task lookup <task-id>");
|
|
3526
|
-
}
|
|
3527
|
-
const lookupId = rest[0];
|
|
3528
|
-
if (!lookupId) {
|
|
3529
|
-
throw new CliError("Usage: rig task lookup <task-id>");
|
|
3530
|
-
}
|
|
3531
|
-
const result = taskLookup(context.projectRoot, lookupId);
|
|
3532
|
-
if (context.outputMode === "text") {
|
|
3533
|
-
console.log(result);
|
|
3534
|
-
}
|
|
3535
|
-
return { ok: true, group: "task", command, details: { id: lookupId, result } };
|
|
3536
|
-
}
|
|
3537
|
-
case "record": {
|
|
3538
|
-
if (rest.length < 2) {
|
|
3539
|
-
throw new CliError("Usage: rig task record <decision|failure> <text>");
|
|
3540
|
-
}
|
|
3541
|
-
const type = rest[0];
|
|
3542
|
-
if (type !== "decision" && type !== "failure") {
|
|
3543
|
-
throw new CliError("Usage: rig task record <decision|failure> <text>");
|
|
3544
|
-
}
|
|
3545
|
-
withMutedConsole(context.outputMode === "json", () => taskRecord(context.projectRoot, type, rest.slice(1).join(" ")));
|
|
3546
|
-
return { ok: true, group: "task", command, details: { type: rest[0] } };
|
|
3547
|
-
}
|
|
3548
|
-
case "ready":
|
|
3549
|
-
requireNoExtraArgs(rest, "rig task ready");
|
|
3550
|
-
await withMutedConsole(context.outputMode === "json", () => taskReady(context.projectRoot));
|
|
3551
|
-
return { ok: true, group: "task", command };
|
|
3552
|
-
case "run": {
|
|
3553
|
-
let pending = rest;
|
|
3554
|
-
const nextResult = takeFlag(pending, "--next");
|
|
3555
|
-
pending = nextResult.rest;
|
|
3556
|
-
const taskResult = takeOption(pending, "--task");
|
|
3557
|
-
pending = taskResult.rest;
|
|
3558
|
-
const titleResult = takeOption(pending, "--title");
|
|
3559
|
-
pending = titleResult.rest;
|
|
3560
|
-
const runtimeAdapterResult = takeOption(pending, "--runtime-adapter");
|
|
3561
|
-
pending = runtimeAdapterResult.rest;
|
|
3562
|
-
const modelResult = takeOption(pending, "--model");
|
|
3563
|
-
pending = modelResult.rest;
|
|
3564
|
-
const runtimeModeResult = takeOption(pending, "--runtime-mode");
|
|
3565
|
-
pending = runtimeModeResult.rest;
|
|
3566
|
-
const interactionModeResult = takeOption(pending, "--interaction-mode");
|
|
3567
|
-
pending = interactionModeResult.rest;
|
|
3568
|
-
const initialPromptResult = takeOption(pending, "--initial-prompt");
|
|
3569
|
-
pending = initialPromptResult.rest;
|
|
3570
|
-
const prResult = takeOption(pending, "--pr");
|
|
3571
|
-
pending = prResult.rest;
|
|
3572
|
-
const noPrResult = takeFlag(pending, "--no-pr");
|
|
3573
|
-
pending = noPrResult.rest;
|
|
3574
|
-
const dirtyBaselineResult = takeOption(pending, "--dirty-baseline");
|
|
3575
|
-
pending = dirtyBaselineResult.rest;
|
|
3576
|
-
const skipProjectSyncResult = takeFlag(pending, "--skip-project-sync");
|
|
3577
|
-
pending = skipProjectSyncResult.rest;
|
|
3578
|
-
const detachResult = takeFlag(pending, "--detach");
|
|
3579
|
-
pending = detachResult.rest;
|
|
3580
|
-
const filterResult = parseTaskFilters(pending);
|
|
3581
|
-
pending = filterResult.rest;
|
|
3582
|
-
const positionalTaskId = pending.length > 0 && pending[0] && !pending[0].startsWith("-") ? normalizeTaskRunTaskId(pending[0]) : null;
|
|
3583
|
-
if (positionalTaskId) {
|
|
3584
|
-
pending = pending.slice(1);
|
|
3585
|
-
}
|
|
3586
|
-
requireNoExtraArgs(pending, "rig task run [#<issue>|<task-id>] [--next] [--task <id>] [--detach] [--assignee <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>] [--title <text>] [--runtime-adapter claude-code|codex|pi] [--model <model>] [--runtime-mode <mode>] [--interaction-mode <mode>] [--initial-prompt <text>] [--pr auto|ask|off] [--no-pr] [--dirty-baseline head|dirty-snapshot] [--skip-project-sync]");
|
|
3587
|
-
if (nextResult.value && (taskResult.value || positionalTaskId)) {
|
|
3588
|
-
throw new CliError("task run cannot combine --next with an explicit task id.", 2, { hint: "Use either `rig task run --next` or `rig task run <id>`." });
|
|
3589
|
-
}
|
|
3590
|
-
if (taskResult.value && positionalTaskId) {
|
|
3591
|
-
throw new CliError("task run cannot combine positional task id with --task <id>.", 2, { hint: "Pass the id once, e.g. `rig task run <id>`." });
|
|
3592
|
-
}
|
|
3593
|
-
if (prResult.value && noPrResult.value) {
|
|
3594
|
-
throw new CliError("task run cannot combine --pr with --no-pr.", 2, { hint: "Use `--pr auto|ask|off` or `--no-pr`, not both." });
|
|
3595
|
-
}
|
|
3596
|
-
let selectedTask = null;
|
|
3597
|
-
let selectedTaskId = normalizeTaskRunTaskId(taskResult.value) ?? positionalTaskId;
|
|
3598
|
-
if (nextResult.value) {
|
|
3599
|
-
const selected = await withSpinner("Selecting next ready task\u2026", () => selectNextWorkspaceTaskViaServer(context, filterResult.filters), { outputMode: context.outputMode });
|
|
3600
|
-
selectedTask = selected.task;
|
|
3601
|
-
selectedTaskId = selected.task ? readTaskId(selected.task) : null;
|
|
3602
|
-
if (!selectedTaskId) {
|
|
3603
|
-
throw new CliError("No matching task found for task run --next.", 3, { hint: "Run `rig task list` to inspect available work, or relax the filters." });
|
|
3604
|
-
}
|
|
3605
|
-
}
|
|
3606
|
-
if (!selectedTaskId && !initialPromptResult.value && !titleResult.value) {
|
|
3607
|
-
if (context.outputMode !== "text" || !process.stdin.isTTY || !process.stdout.isTTY) {
|
|
3608
|
-
throw new CliError("task run requires an interactive terminal to pick a task; pass --next, --task <id>, or --initial-prompt/--title for an ad hoc run.", 2);
|
|
3609
|
-
}
|
|
3610
|
-
const tasks = await withSpinner("Reading tasks from server\u2026", () => listWorkspaceTasksViaServer(context, filterResult.filters), { outputMode: context.outputMode });
|
|
3611
|
-
selectedTask = await selectTaskWithTextPicker(tasks);
|
|
3612
|
-
selectedTaskId = selectedTask ? readTaskId(selectedTask) : null;
|
|
3613
|
-
if (!selectedTaskId) {
|
|
3614
|
-
throw new CliError("No task selected.", 3, { hint: "Run `rig task run --next` for the next ready task, or `rig task run --task <id>`." });
|
|
3615
|
-
}
|
|
3616
|
-
}
|
|
3617
|
-
await runProjectMainSyncPreflight(context, { disabled: skipProjectSyncResult.value });
|
|
3618
|
-
const projectDefaults = await loadTaskRunProjectDefaults(context.projectRoot);
|
|
3619
|
-
const runtimeAdapter = normalizeRuntimeAdapter(runtimeAdapterResult.value ?? projectDefaults.runtimeAdapter);
|
|
3620
|
-
await withSpinner("Running task-run preflight\u2026", () => runFastTaskRunPreflight(context, {
|
|
3621
|
-
taskId: selectedTaskId,
|
|
3622
|
-
runtimeAdapter
|
|
3623
|
-
}), { outputMode: context.outputMode });
|
|
3624
|
-
const dirtyBaseline = await resolveDirtyBaselineForTaskRun(context, dirtyBaselineResult.value);
|
|
3625
|
-
const prMode = noPrResult.value ? "off" : normalizePrMode(prResult.value) ?? projectDefaults.prMode;
|
|
3626
|
-
const submitted = await withSpinner("Dispatching run\u2026", () => submitTaskRunViaServer(context, {
|
|
3627
|
-
runId: context.runId,
|
|
3628
|
-
taskId: selectedTaskId ?? undefined,
|
|
3629
|
-
title: titleResult.value ?? undefined,
|
|
3630
|
-
runtimeAdapter,
|
|
3631
|
-
model: modelResult.value ?? projectDefaults.model,
|
|
3632
|
-
runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
|
|
3633
|
-
interactionMode: interactionModeResult.value || "default",
|
|
3634
|
-
initialPrompt: initialPromptResult.value ?? undefined,
|
|
3635
|
-
baselineMode: dirtyBaseline.mode,
|
|
3636
|
-
prMode
|
|
3637
|
-
}), { outputMode: context.outputMode });
|
|
3638
|
-
let attachDetails = null;
|
|
3639
|
-
if (!detachResult.value && context.outputMode === "text") {
|
|
3640
|
-
printFormattedOutput(formatSubmittedRun({
|
|
3641
|
-
runId: submitted.runId,
|
|
3642
|
-
task: selectedTask ? summarizeTask(selectedTask) : null,
|
|
3643
|
-
runtimeAdapter,
|
|
3644
|
-
runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
|
|
3645
|
-
interactionMode: interactionModeResult.value || "default",
|
|
3646
|
-
detached: false
|
|
3647
|
-
}));
|
|
3648
|
-
attachDetails = await attachRunOperatorView(context, { runId: submitted.runId, follow: true });
|
|
3649
|
-
} else if (context.outputMode === "text") {
|
|
3650
|
-
printFormattedOutput(formatSubmittedRun({
|
|
3651
|
-
runId: submitted.runId,
|
|
3652
|
-
task: selectedTask ? summarizeTask(selectedTask) : null,
|
|
3653
|
-
runtimeAdapter,
|
|
3654
|
-
runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
|
|
3655
|
-
interactionMode: interactionModeResult.value || "default",
|
|
3656
|
-
detached: true
|
|
3657
|
-
}));
|
|
3658
|
-
}
|
|
3659
|
-
return {
|
|
3660
|
-
ok: true,
|
|
3661
|
-
group: "task",
|
|
3662
|
-
command,
|
|
3663
|
-
details: {
|
|
3664
|
-
runId: submitted.runId,
|
|
3665
|
-
taskId: selectedTaskId,
|
|
3666
|
-
title: titleResult.value ?? null,
|
|
3667
|
-
selectedTask: selectedTask ? summarizeTask(selectedTask) : null,
|
|
3668
|
-
filters: nextResult.value ? filterResult.filters : undefined,
|
|
3669
|
-
attached: Boolean(attachDetails),
|
|
3670
|
-
attach: attachDetails,
|
|
3671
|
-
runtimeAdapter,
|
|
3672
|
-
model: modelResult.value ?? projectDefaults.model ?? null,
|
|
3673
|
-
runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
|
|
3674
|
-
prMode: prMode ?? null,
|
|
3675
|
-
dirtyBaseline: { mode: dirtyBaseline.mode, dirty: dirtyBaseline.state?.dirty ?? false }
|
|
3676
|
-
}
|
|
3677
|
-
};
|
|
3678
|
-
}
|
|
3679
|
-
case "validate": {
|
|
3680
|
-
const { value: task, rest: remaining } = takeOption(rest, "--task");
|
|
3681
|
-
requireNoExtraArgs(remaining, "rig task validate [--task <task-id>]");
|
|
3682
|
-
if (context.dryRun) {
|
|
3683
|
-
await context.runCommand(["rig", "task", "validate", ...task ? ["--task", task] : []]);
|
|
3684
|
-
return { ok: true, group: "task", command, details: { task: task || "active" } };
|
|
3685
|
-
}
|
|
3686
|
-
const ok = await withMutedConsole(context.outputMode === "json", async () => taskValidate(context.projectRoot, task || undefined, await validatorRegistryForTaskCommands(context.projectRoot)));
|
|
3687
|
-
if (!ok) {
|
|
3688
|
-
throw new CliError(`Validation failed for ${task || "active task"}.`, 2, { hint: "Inspect failures with `rig inspect failures --task <id>`, fix, then re-run `rig task validate --task <id>`." });
|
|
3689
|
-
}
|
|
3690
|
-
return { ok: true, group: "task", command, details: { task: task || "active" } };
|
|
3691
|
-
}
|
|
3692
|
-
case "verify": {
|
|
3693
|
-
const { value: task, rest: remaining } = takeOption(rest, "--task");
|
|
3694
|
-
requireNoExtraArgs(remaining, "rig task verify [--task <task-id>]");
|
|
3695
|
-
if (context.dryRun) {
|
|
3696
|
-
await context.runCommand(["rig", "task", "verify", ...task ? ["--task", task] : []]);
|
|
3697
|
-
return { ok: true, group: "task", command, details: { task: task || "active" } };
|
|
3698
|
-
}
|
|
3699
|
-
const ok = await withMutedConsole(context.outputMode === "json", () => taskVerify(context.projectRoot, task || undefined));
|
|
3700
|
-
if (!ok) {
|
|
3701
|
-
throw new CliError(`Verification rejected for ${task || "active task"}.`, 2, { hint: "Check `rig inspect logs --task <id>`, address the rejection, then re-run `rig task verify --task <id>`." });
|
|
3702
|
-
}
|
|
3703
|
-
return { ok: true, group: "task", command, details: { task: task || "active" } };
|
|
3704
|
-
}
|
|
3705
|
-
case "details": {
|
|
3706
|
-
const { value: task, rest: remaining } = takeOption(rest, "--task");
|
|
3707
|
-
requireNoExtraArgs(remaining, "rig task details --task <task-id>");
|
|
3708
|
-
const requiredTask = requireTask(task, "rig task details --task <task-id>");
|
|
3709
|
-
await withMutedConsole(context.outputMode === "json", () => taskInfo(context.projectRoot, requiredTask));
|
|
3710
|
-
return { ok: true, group: "task", command, details: { task: requiredTask } };
|
|
3711
|
-
}
|
|
3712
|
-
case "reopen": {
|
|
3713
|
-
const { value: task, rest: rest1 } = takeOption(rest, "--task");
|
|
3714
|
-
const allFlag = takeFlag(rest1, "--all");
|
|
3715
|
-
const { rest: remaining } = takeOption(allFlag.rest, "--reason");
|
|
3716
|
-
requireNoExtraArgs(remaining, "rig task reopen [--task <id> | --all] [--reason <text>]");
|
|
3717
|
-
if (!allFlag.value && !task) {
|
|
3718
|
-
throw new CliError("Usage: rig task reopen [--task <id> | --all] [--reason <text>]");
|
|
3719
|
-
}
|
|
3720
|
-
const summary = withMutedConsole(context.outputMode === "json", () => taskReopen(context.projectRoot, {
|
|
3721
|
-
all: allFlag.value,
|
|
3722
|
-
taskId: task || undefined,
|
|
3723
|
-
dryRun: false
|
|
3724
|
-
}));
|
|
3725
|
-
return { ok: true, group: "task", command, details: summary };
|
|
3726
|
-
}
|
|
3727
|
-
default:
|
|
3728
|
-
if (command === "reset") {
|
|
3729
|
-
throw new CliError("Unknown task command: reset", 1, { hint: "Use `rig task reopen --task <id>`." });
|
|
3730
|
-
}
|
|
3731
|
-
throw new CliError(`Unknown task command: ${command}`, 1, { hint: "Run `rig task --help` to list available task commands." });
|
|
3732
|
-
}
|
|
3733
|
-
}
|
|
3734
|
-
var init_task = __esm(() => {
|
|
3735
|
-
init_drone_ui();
|
|
3736
|
-
init_runner();
|
|
3737
|
-
init__authority_runs();
|
|
3738
|
-
init__preflight();
|
|
3739
|
-
init__server_client();
|
|
3740
|
-
init__task_picker();
|
|
3741
|
-
init__async_ui();
|
|
3742
|
-
init__operator_view();
|
|
3743
|
-
init__cli_format();
|
|
3744
|
-
init_inbox();
|
|
3745
|
-
init__help_catalog();
|
|
3746
|
-
init__connection_state();
|
|
3747
|
-
});
|
|
3748
|
-
|
|
3749
|
-
// packages/cli/src/app-opentui/adapters/fleet.ts
|
|
3750
|
-
function normalizeRunRecord(record) {
|
|
3751
|
-
const runId = stringField(record, ["runId", "id"]);
|
|
3752
|
-
if (!runId)
|
|
3753
|
-
return null;
|
|
3754
|
-
const title = stringField(record, ["title", "taskTitle", "taskId"], "untitled run");
|
|
3755
|
-
const taskId3 = stringField(record, ["taskId"]);
|
|
3756
|
-
const updatedAt = stringField(record, ["updatedAt", "createdAt"]);
|
|
3757
|
-
return {
|
|
3758
|
-
runId,
|
|
3759
|
-
status: stringField(record, ["status", "state"], "unknown"),
|
|
3760
|
-
title,
|
|
3761
|
-
raw: record,
|
|
3762
|
-
...taskId3 ? { taskId: taskId3 } : {},
|
|
3763
|
-
...updatedAt ? { updatedAt } : {}
|
|
3764
|
-
};
|
|
3765
|
-
}
|
|
3766
|
-
async function refreshFleet(ctx, options = {}) {
|
|
3767
|
-
const label = "Refreshing fleet";
|
|
3768
|
-
emitStarted(ctx, label);
|
|
3769
|
-
try {
|
|
3770
|
-
const { listRunsViaServer: listRunsViaServer2, resolveServerConnectionLabel: resolveServerConnectionLabel2 } = await Promise.resolve().then(() => (init__server_client(), exports__server_client));
|
|
3771
|
-
const projectRoot = projectRootOf(ctx);
|
|
3772
|
-
emitProgress(ctx, label, "contacting selected server");
|
|
3773
|
-
const [runs, serverLabel] = await Promise.all([
|
|
3774
|
-
listRunsViaServer2({ projectRoot }, { limit: options.limit ?? 50 }),
|
|
3775
|
-
resolveServerConnectionLabel2(projectRoot)
|
|
3776
|
-
]);
|
|
3777
|
-
const normalized = runs.flatMap((run) => {
|
|
3778
|
-
const entry = normalizeRunRecord(run);
|
|
3779
|
-
return entry ? [entry] : [];
|
|
3780
|
-
});
|
|
3781
|
-
patchData(ctx, { fleet: { runs: normalized, refreshedAt: new Date().toISOString() }, lastRefreshError: undefined });
|
|
3782
|
-
patchFooter(ctx, { server: serverLabel, runs: String(normalized.length) });
|
|
3783
|
-
emitCompleted(ctx, label, { count: normalized.length });
|
|
3784
|
-
return normalized;
|
|
3785
|
-
} catch (error) {
|
|
3786
|
-
emitFailed(ctx, label, error);
|
|
3787
|
-
throw error;
|
|
3788
|
-
}
|
|
3789
|
-
}
|
|
3790
|
-
var init_fleet = () => {};
|
|
3791
|
-
|
|
3792
|
-
// packages/cli/src/app-opentui/adapters/inspect.ts
|
|
3793
|
-
var exports_inspect = {};
|
|
3794
|
-
__export(exports_inspect, {
|
|
3795
|
-
loadInspectRuns: () => loadInspectRuns,
|
|
3796
|
-
loadInspect: () => loadInspect,
|
|
3797
|
-
INSPECT_VIEWS: () => INSPECT_VIEWS
|
|
3798
|
-
});
|
|
3799
|
-
import { execFile } from "child_process";
|
|
3800
|
-
import { existsSync as existsSync4, readFileSync as readFileSync5, readdirSync, statSync } from "fs";
|
|
3801
|
-
import { resolve as resolve4 } from "path";
|
|
3802
|
-
import { promisify } from "util";
|
|
3803
|
-
import { resolveTaskArtifactDirs } from "@rig/runtime/control-plane/authority-files";
|
|
3804
|
-
import { readTaskArtifactPreview } from "@rig/runtime/control-plane/native/workspace-ops";
|
|
3805
|
-
import { resolveHarnessPaths, resolveMonorepoRoot as resolveMonorepoRoot2, runCapture } from "@rig/runtime/control-plane/native/utils";
|
|
3806
|
-
function isFailureEntry(entry) {
|
|
3807
|
-
const status = `${entry.status ?? entry.level ?? entry.type ?? ""}`.toLowerCase();
|
|
3808
|
-
return status.includes("fail") || status.includes("error");
|
|
3809
|
-
}
|
|
3810
|
-
async function gitDiff(projectRoot) {
|
|
3811
|
-
try {
|
|
3812
|
-
const { stdout } = await execFileAsync("git", ["diff", "--no-color"], { cwd: projectRoot, maxBuffer: 8 * 1024 * 1024 });
|
|
3813
|
-
return { diff: stdout };
|
|
3814
|
-
} catch (error) {
|
|
3815
|
-
return { diff: "", error: normalizeAppError(error).message };
|
|
3816
|
-
}
|
|
3817
|
-
}
|
|
3818
|
-
function listArtifacts(projectRoot, taskId3) {
|
|
3819
|
-
if (!taskId3)
|
|
3820
|
-
return { artifacts: [], error: "run has no task id \u2014 artifacts are resolved per task" };
|
|
3821
|
-
try {
|
|
3822
|
-
const dirs = resolveTaskArtifactDirs(projectRoot, taskId3).filter((dir) => existsSync4(dir));
|
|
3823
|
-
const out = [];
|
|
3824
|
-
const seen = new Set;
|
|
3825
|
-
for (const dir of dirs) {
|
|
3826
|
-
for (const name of readdirSync(dir)) {
|
|
3827
|
-
if (seen.has(name))
|
|
3828
|
-
continue;
|
|
3829
|
-
seen.add(name);
|
|
3830
|
-
const path = resolve4(dir, name);
|
|
3831
|
-
try {
|
|
3832
|
-
const stat = statSync(path);
|
|
3833
|
-
out.push({ name, path, sizeBytes: stat.size, isDir: stat.isDirectory() });
|
|
3834
|
-
} catch {
|
|
3835
|
-
out.push({ name, path, sizeBytes: 0, isDir: false });
|
|
3836
|
-
}
|
|
3837
|
-
}
|
|
3838
|
-
}
|
|
3839
|
-
out.sort((left, right) => left.name.localeCompare(right.name));
|
|
3840
|
-
return { artifacts: out };
|
|
3841
|
-
} catch (error) {
|
|
3842
|
-
return { artifacts: [], error: normalizeAppError(error).message };
|
|
3843
|
-
}
|
|
3844
|
-
}
|
|
3845
|
-
function readArtifact(projectRoot, taskId3, fileName) {
|
|
3846
|
-
if (!taskId3)
|
|
3847
|
-
return;
|
|
3848
|
-
try {
|
|
3849
|
-
const preview = readTaskArtifactPreview(projectRoot, taskId3, fileName);
|
|
3850
|
-
return { name: fileName, contents: preview.contents, truncated: preview.truncated, sizeBytes: preview.sizeBytes };
|
|
3851
|
-
} catch (error) {
|
|
3852
|
-
return { name: fileName, contents: `Failed to read artifact: ${normalizeAppError(error).message}`, truncated: false, sizeBytes: 0 };
|
|
3853
|
-
}
|
|
3854
|
-
}
|
|
3855
|
-
function loadGraph(projectRoot) {
|
|
3856
|
-
try {
|
|
3857
|
-
const result = runCapture(["br", "--no-db", "list", "--pretty"], resolveMonorepoRoot2(projectRoot));
|
|
3858
|
-
if (result.exitCode !== 0)
|
|
3859
|
-
return { graph: "", error: result.stderr || result.stdout || "failed to inspect graph" };
|
|
3860
|
-
return { graph: result.stdout };
|
|
3861
|
-
} catch (error) {
|
|
3862
|
-
return { graph: "", error: normalizeAppError(error).message };
|
|
3863
|
-
}
|
|
3864
|
-
}
|
|
3865
|
-
function loadAudit(projectRoot) {
|
|
3866
|
-
try {
|
|
3867
|
-
const auditPath = resolve4(resolveHarnessPaths(projectRoot).logsDir, "audit.jsonl");
|
|
3868
|
-
if (!existsSync4(auditPath))
|
|
3869
|
-
return [];
|
|
3870
|
-
return readFileSync5(auditPath, "utf-8").split(/\r?\n/).filter(Boolean).slice(-50).flatMap((raw) => {
|
|
3871
|
-
try {
|
|
3872
|
-
const parsed = JSON.parse(raw);
|
|
3873
|
-
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? [parsed] : [{ detail: raw }];
|
|
3874
|
-
} catch {
|
|
3875
|
-
return [{ detail: raw }];
|
|
3876
|
-
}
|
|
3877
|
-
});
|
|
3878
|
-
} catch {
|
|
3879
|
-
return [];
|
|
3880
|
-
}
|
|
3881
|
-
}
|
|
3882
|
-
async function loadInspectRuns(ctx, options = {}) {
|
|
3883
|
-
const label = "Loading runs to inspect";
|
|
3884
|
-
emitStarted(ctx, label);
|
|
3885
|
-
try {
|
|
3886
|
-
const projectRoot = projectRootOf(ctx);
|
|
3887
|
-
const { listRunsViaServer: listRunsViaServer2 } = await Promise.resolve().then(() => (init__server_client(), exports__server_client));
|
|
3888
|
-
emitProgress(ctx, label, "listing recent runs");
|
|
3889
|
-
const runs = await listRunsViaServer2({ projectRoot }, { limit: options.limit ?? 50 });
|
|
3890
|
-
const options_ = runs.flatMap((record) => {
|
|
3891
|
-
const runId = stringField(record, ["runId", "id"]);
|
|
3892
|
-
if (!runId)
|
|
3893
|
-
return [];
|
|
3894
|
-
const taskId3 = stringField(record, ["taskId"]);
|
|
3895
|
-
const updatedAt = stringField(record, ["updatedAt", "createdAt"]);
|
|
3896
|
-
return [{
|
|
3897
|
-
runId,
|
|
3898
|
-
status: stringField(record, ["status", "state"], "unknown"),
|
|
3899
|
-
title: stringField(record, ["title", "taskTitle", "taskId"], "untitled run"),
|
|
3900
|
-
...taskId3 ? { taskId: taskId3 } : {},
|
|
3901
|
-
...updatedAt ? { updatedAt } : {}
|
|
3902
|
-
}];
|
|
3903
|
-
});
|
|
3904
|
-
patchData(ctx, { inspectRuns: options_, lastRefreshError: undefined });
|
|
3905
|
-
emitCompleted(ctx, label, { count: options_.length });
|
|
3906
|
-
return options_;
|
|
3907
|
-
} catch (error) {
|
|
3908
|
-
emitFailed(ctx, label, error);
|
|
3909
|
-
throw error;
|
|
3910
|
-
}
|
|
3911
|
-
}
|
|
3912
|
-
async function loadInspect(ctx, runId) {
|
|
3913
|
-
const cleanRunId = runId.trim();
|
|
3914
|
-
const label = `Inspecting run ${cleanRunId.slice(0, 8)}`;
|
|
3915
|
-
if (!cleanRunId) {
|
|
3916
|
-
await loadInspectRuns(ctx).catch(() => []);
|
|
3917
|
-
const error = new Error("Inspect requires a run id.");
|
|
3918
|
-
throw error;
|
|
3919
|
-
}
|
|
3920
|
-
emitStarted(ctx, label);
|
|
3921
|
-
try {
|
|
3922
|
-
const projectRoot = projectRootOf(ctx);
|
|
3923
|
-
const { getRunDetailsViaServer: getRunDetailsViaServer2, getRunLogsViaServer: getRunLogsViaServer2, getRunTimelineViaServer: getRunTimelineViaServer2 } = await Promise.resolve().then(() => (init__server_client(), exports__server_client));
|
|
3924
|
-
const context = { projectRoot };
|
|
3925
|
-
emitProgress(ctx, label, "loading logs, timeline, diff, artifacts, graph, and audit");
|
|
3926
|
-
const [runPayload, logsPayload, timelinePayload, diffResult] = await Promise.all([
|
|
3927
|
-
getRunDetailsViaServer2(context, cleanRunId).catch((error) => ({ error: normalizeAppError(error).message })),
|
|
3928
|
-
getRunLogsViaServer2(context, cleanRunId, { limit: 500 }).catch(() => []),
|
|
3929
|
-
getRunTimelineViaServer2(context, cleanRunId, { limit: 500 }).catch(() => []),
|
|
3930
|
-
gitDiff(projectRoot)
|
|
3931
|
-
]);
|
|
3932
|
-
const run = runPayload && typeof runPayload === "object" && "run" in runPayload && runPayload.run && typeof runPayload.run === "object" ? runPayload.run : runPayload;
|
|
3933
|
-
const logs = arrayFromPayload(logsPayload);
|
|
3934
|
-
const timeline = arrayFromPayload(timelinePayload);
|
|
3935
|
-
const taskId3 = stringField(run, ["taskId"]) || undefined;
|
|
3936
|
-
const { artifacts, error: artifactsError } = listArtifacts(projectRoot, taskId3);
|
|
3937
|
-
const { graph, error: graphError } = loadGraph(projectRoot);
|
|
3938
|
-
const audit = loadAudit(projectRoot);
|
|
3939
|
-
const state = ctx.getState();
|
|
3940
|
-
const selectedArtifact = typeof state.data?.inspectArtifact === "string" ? state.data.inspectArtifact : undefined;
|
|
3941
|
-
const artifactView = selectedArtifact ? readArtifact(projectRoot, taskId3, selectedArtifact) : undefined;
|
|
3942
|
-
const snapshot = {
|
|
3943
|
-
runId: cleanRunId,
|
|
3944
|
-
status: stringField(run, ["status", "state"], "unknown"),
|
|
3945
|
-
title: stringField(run, ["title", "taskId", "id"], "untitled run"),
|
|
3946
|
-
logs,
|
|
3947
|
-
timeline,
|
|
3948
|
-
diff: diffResult.diff,
|
|
3949
|
-
failures: [...logs, ...timeline].filter(isFailureEntry),
|
|
3950
|
-
artifacts,
|
|
3951
|
-
graph,
|
|
3952
|
-
audit,
|
|
3953
|
-
refreshedAt: Date.now(),
|
|
3954
|
-
...taskId3 ? { taskId: taskId3 } : {},
|
|
3955
|
-
...artifactView ? { artifactView } : {},
|
|
3956
|
-
...diffResult.error ? { diffError: diffResult.error } : {},
|
|
3957
|
-
...graphError ? { graphError } : {},
|
|
3958
|
-
...artifactsError ? { artifactsError } : {}
|
|
3959
|
-
};
|
|
3960
|
-
patchData(ctx, { inspect: snapshot, lastRefreshError: undefined });
|
|
3961
|
-
emitCompleted(ctx, label, {
|
|
3962
|
-
runId: cleanRunId,
|
|
3963
|
-
logs: logs.length,
|
|
3964
|
-
timeline: timeline.length,
|
|
3965
|
-
diffBytes: snapshot.diff.length,
|
|
3966
|
-
artifacts: artifacts.length,
|
|
3967
|
-
audit: audit.length
|
|
3968
|
-
});
|
|
3969
|
-
return snapshot;
|
|
3970
|
-
} catch (error) {
|
|
3971
|
-
emitFailed(ctx, label, error, { runId: cleanRunId });
|
|
3972
|
-
throw error;
|
|
3973
|
-
}
|
|
3974
|
-
}
|
|
3975
|
-
var execFileAsync, INSPECT_VIEWS;
|
|
3976
|
-
var init_inspect = __esm(() => {
|
|
3977
|
-
execFileAsync = promisify(execFile);
|
|
3978
|
-
INSPECT_VIEWS = [
|
|
3979
|
-
"logs",
|
|
3980
|
-
"timeline",
|
|
3981
|
-
"artifacts",
|
|
3982
|
-
"artifact",
|
|
3983
|
-
"diff",
|
|
3984
|
-
"failures",
|
|
3985
|
-
"graph",
|
|
3986
|
-
"audit"
|
|
3987
|
-
];
|
|
3988
|
-
});
|
|
3989
|
-
|
|
3990
|
-
// packages/cli/src/app-opentui/adapters/pi-attach.ts
|
|
3991
|
-
var exports_pi_attach = {};
|
|
3992
|
-
__export(exports_pi_attach, {
|
|
3993
|
-
preparePiAttachHandoff: () => preparePiAttachHandoff,
|
|
3994
|
-
attachRunWithBundledPi: () => attachRunWithBundledPi
|
|
3995
|
-
});
|
|
3996
|
-
function currentAttachState(ctx, runId) {
|
|
3997
|
-
const value = ctx.getState().data?.piAttach;
|
|
3998
|
-
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
3999
|
-
return null;
|
|
4000
|
-
const state = value;
|
|
4001
|
-
return state.runId === runId ? state : null;
|
|
4002
|
-
}
|
|
4003
|
-
function recordStep(ctx, runId, label, emitLabel) {
|
|
4004
|
-
const now = Date.now();
|
|
4005
|
-
const previous = currentAttachState(ctx, runId);
|
|
4006
|
-
const priorSteps = previous?.steps ?? [];
|
|
4007
|
-
const settled = priorSteps.map((step) => step.status === "running" ? { ...step, status: "done", endedAtMs: step.endedAtMs ?? now } : step);
|
|
4008
|
-
const steps = [...settled, { label, startedAtMs: now, status: "running" }];
|
|
4009
|
-
patchData(ctx, {
|
|
4010
|
-
piAttach: { ...previous ?? { runId, status: "preparing", message: label }, runId, steps }
|
|
4011
|
-
});
|
|
4012
|
-
emitProgress(ctx, emitLabel, label);
|
|
4013
|
-
}
|
|
4014
|
-
async function preparePiAttachHandoff(ctx, runId) {
|
|
4015
|
-
const cleanRunId = runId.trim();
|
|
4016
|
-
const label = `Preparing Pi ${cleanRunId.slice(0, 8)}`;
|
|
4017
|
-
emitStarted(ctx, label, { piAttach: { runId: cleanRunId, status: "preparing" } });
|
|
4018
|
-
try {
|
|
4019
|
-
const { getRunDetailsViaServer: getRunDetailsViaServer2, getRunPiStatusViaServer: getRunPiStatusViaServer2, resolveServerConnectionLabel: resolveServerConnectionLabel2 } = await Promise.resolve().then(() => (init__server_client(), exports__server_client));
|
|
4020
|
-
const projectRoot = projectRootOf(ctx);
|
|
4021
|
-
recordStep(ctx, cleanRunId, "connecting to server \xB7 checking run and Pi session readiness", label);
|
|
4022
|
-
const [run, piStatus, server] = await Promise.all([
|
|
4023
|
-
getRunDetailsViaServer2({ projectRoot }, cleanRunId).catch((error) => ({ error: error instanceof Error ? error.message : String(error) })),
|
|
4024
|
-
getRunPiStatusViaServer2({ projectRoot }, cleanRunId).catch((error) => ({ error: error instanceof Error ? error.message : String(error) })),
|
|
4025
|
-
resolveServerConnectionLabel2(projectRoot)
|
|
4026
|
-
]);
|
|
4027
|
-
const state = {
|
|
4028
|
-
runId: cleanRunId,
|
|
4029
|
-
status: "preparing",
|
|
4030
|
-
message: "ready to enter worker Pi",
|
|
4031
|
-
result: { run, piStatus, server },
|
|
4032
|
-
ready: true,
|
|
4033
|
-
...currentAttachState(ctx, cleanRunId)?.steps ? { steps: currentAttachState(ctx, cleanRunId).steps } : {}
|
|
4034
|
-
};
|
|
4035
|
-
patchData(ctx, { piAttach: state, lastRefreshError: undefined });
|
|
4036
|
-
emitCompleted(ctx, label, { runId: cleanRunId, server });
|
|
4037
|
-
return state;
|
|
4038
|
-
} catch (error) {
|
|
4039
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
4040
|
-
const state = {
|
|
4041
|
-
runId: cleanRunId,
|
|
4042
|
-
status: "failed",
|
|
4043
|
-
message: reason,
|
|
4044
|
-
failureReason: reason,
|
|
4045
|
-
...currentAttachState(ctx, cleanRunId)?.steps ? { steps: currentAttachState(ctx, cleanRunId).steps } : {}
|
|
4046
|
-
};
|
|
4047
|
-
patchData(ctx, { piAttach: state });
|
|
4048
|
-
emitFailed(ctx, label, error, { runId: cleanRunId });
|
|
4049
|
-
throw error;
|
|
4050
|
-
}
|
|
4051
|
-
}
|
|
4052
|
-
async function attachRunWithBundledPi(ctx, runId) {
|
|
4053
|
-
const cleanRunId = runId.trim();
|
|
4054
|
-
const label = `Entering Pi ${cleanRunId.slice(0, 8)}`;
|
|
4055
|
-
if (!cleanRunId) {
|
|
4056
|
-
const error = new Error("Attach requires a run id.");
|
|
4057
|
-
emitFailed(ctx, label, error);
|
|
4058
|
-
throw error;
|
|
4059
|
-
}
|
|
4060
|
-
emitStarted(ctx, label, { piAttach: { runId: cleanRunId, status: "entering-pi" } });
|
|
4061
|
-
patchData(ctx, { piAttach: { runId: cleanRunId, status: "entering-pi", message: "handing the terminal to worker Pi\u2026" } });
|
|
4062
|
-
const projectRoot = projectRootOf(ctx);
|
|
4063
|
-
const outputMode = ctx.rig?.outputMode ?? "text";
|
|
4064
|
-
await releaseRendererForExternalTui(ctx);
|
|
4065
|
-
let outcome = null;
|
|
4066
|
-
let attachError = null;
|
|
4067
|
-
try {
|
|
4068
|
-
const { attachRunBundledPiFrontend: attachRunBundledPiFrontend2 } = await Promise.resolve().then(() => (init__pi_frontend(), exports__pi_frontend));
|
|
4069
|
-
outcome = await attachRunBundledPiFrontend2({ projectRoot, outputMode }, { runId: cleanRunId, returnOnQuit: true });
|
|
4070
|
-
} catch (error) {
|
|
4071
|
-
attachError = error;
|
|
4072
|
-
} finally {
|
|
4073
|
-
await resumeRendererAfterExternalTui(ctx);
|
|
4074
|
-
}
|
|
4075
|
-
if (attachError) {
|
|
4076
|
-
const reason = normalizeAppError(attachError).message;
|
|
4077
|
-
patchData(ctx, {
|
|
4078
|
-
piTerminal: undefined,
|
|
4079
|
-
piAttach: { runId: cleanRunId, status: "failed", message: reason, failureReason: reason }
|
|
4080
|
-
});
|
|
4081
|
-
Promise.resolve().then(() => (init_inspect(), exports_inspect)).then(({ loadInspect: loadInspect2 }) => loadInspect2(ctx, cleanRunId)).catch(() => null);
|
|
4082
|
-
emitFailed(ctx, label, attachError, { runId: cleanRunId });
|
|
4083
|
-
throw attachError;
|
|
4084
|
-
}
|
|
4085
|
-
const detached = outcome?.detached === true;
|
|
4086
|
-
patchData(ctx, {
|
|
4087
|
-
piTerminal: undefined,
|
|
4088
|
-
piAttach: { runId: cleanRunId, status: "returned", message: detached ? "detached from worker Pi" : "returned from worker Pi" }
|
|
4089
|
-
});
|
|
4090
|
-
emitCompleted(ctx, label, { runId: cleanRunId, result: { runId: cleanRunId, detached } });
|
|
4091
|
-
ctx.emit({ type: "scene.change", scene: "fleet", intent: { scene: "fleet", argv: ["runs"], action: { kind: "refresh", label: "Opening runs" } } });
|
|
4092
|
-
refreshFleet(ctx).catch((error) => emitFailed(ctx, "Refresh runs", error));
|
|
4093
|
-
return { runId: cleanRunId, status: "returned", detached };
|
|
4094
|
-
}
|
|
4095
|
-
var init_pi_attach = __esm(() => {
|
|
4096
|
-
init_fleet();
|
|
4097
|
-
});
|
|
4098
|
-
|
|
4099
|
-
// packages/cli/src/app-opentui/adapters/tasks.ts
|
|
4100
|
-
import { randomUUID } from "crypto";
|
|
4101
|
-
function rawRecord(record, key) {
|
|
4102
|
-
const direct = record[key];
|
|
4103
|
-
if (direct !== undefined && direct !== null)
|
|
4104
|
-
return direct;
|
|
4105
|
-
const raw = record.raw;
|
|
4106
|
-
return raw && typeof raw === "object" && !Array.isArray(raw) ? raw[key] : undefined;
|
|
4107
|
-
}
|
|
4108
|
-
function optionalString(record, keys) {
|
|
4109
|
-
for (const key of keys) {
|
|
4110
|
-
const value = rawRecord(record, key);
|
|
4111
|
-
if (typeof value === "string" && value.trim())
|
|
4112
|
-
return value.trim();
|
|
4113
|
-
if (typeof value === "number" && Number.isFinite(value))
|
|
4114
|
-
return String(value);
|
|
4115
|
-
}
|
|
4116
|
-
return;
|
|
4117
|
-
}
|
|
4118
|
-
function optionalNumber(record, keys) {
|
|
4119
|
-
for (const key of keys) {
|
|
4120
|
-
const value = rawRecord(record, key);
|
|
4121
|
-
if (typeof value === "number" && Number.isFinite(value))
|
|
4122
|
-
return value;
|
|
4123
|
-
if (typeof value === "string" && value.trim()) {
|
|
4124
|
-
const parsed = Number(value);
|
|
4125
|
-
if (Number.isFinite(parsed))
|
|
4126
|
-
return parsed;
|
|
4127
|
-
}
|
|
4128
|
-
}
|
|
4129
|
-
return;
|
|
4130
|
-
}
|
|
4131
|
-
function stringList(value) {
|
|
4132
|
-
if (!Array.isArray(value))
|
|
4133
|
-
return [];
|
|
4134
|
-
return value.flatMap((entry) => {
|
|
4135
|
-
if (typeof entry === "string" && entry.trim())
|
|
4136
|
-
return [entry.trim()];
|
|
4137
|
-
if (entry && typeof entry === "object" && !Array.isArray(entry)) {
|
|
4138
|
-
const record = entry;
|
|
4139
|
-
const name = typeof record.name === "string" ? record.name : typeof record.login === "string" ? record.login : undefined;
|
|
4140
|
-
return name?.trim() ? [name.trim()] : [];
|
|
4141
|
-
}
|
|
4142
|
-
return [];
|
|
4143
|
-
});
|
|
4144
|
-
}
|
|
4145
|
-
function labelsFor(record) {
|
|
4146
|
-
return stringList(rawRecord(record, "labels"));
|
|
4147
|
-
}
|
|
4148
|
-
function assigneesFor(record) {
|
|
4149
|
-
return stringList(rawRecord(record, "assignees"));
|
|
4150
|
-
}
|
|
4151
|
-
function activeRunForRecord(record) {
|
|
4152
|
-
const value = rawRecord(record, "activeRun");
|
|
4153
|
-
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
4154
|
-
return;
|
|
4155
|
-
const activeRun = value;
|
|
4156
|
-
const runId = optionalString(activeRun, ["runId", "id"]);
|
|
4157
|
-
if (!runId)
|
|
4158
|
-
return;
|
|
4159
|
-
const status = optionalString(activeRun, ["status", "state"]);
|
|
4160
|
-
const stage = optionalString(activeRun, ["stage", "phase"]);
|
|
4161
|
-
return {
|
|
4162
|
-
runId,
|
|
4163
|
-
...status ? { status } : {},
|
|
4164
|
-
...stage ? { stage } : {}
|
|
4165
|
-
};
|
|
4166
|
-
}
|
|
4167
|
-
function activeRunIdFromTaskLike(task) {
|
|
4168
|
-
return activeRunForRecord(task)?.runId;
|
|
4169
|
-
}
|
|
4170
|
-
function activeRunIdFromTaskRunError(error) {
|
|
4171
|
-
const message2 = error instanceof Error ? error.message : String(error);
|
|
4172
|
-
const match = message2.match(/already has an active (?:Rig )?run:\s*([^\s"'}]+)/i);
|
|
4173
|
-
return match?.[1]?.replace(/[),.;]+$/g, "") ?? null;
|
|
4174
|
-
}
|
|
4175
|
-
function normalizeTaskRecord(record) {
|
|
4176
|
-
const id = stringField(record, ["id", "taskId", "number"]);
|
|
4177
|
-
if (!id)
|
|
4178
|
-
return null;
|
|
4179
|
-
const priority = optionalNumber(record, ["priority", "rank", "score"]);
|
|
4180
|
-
const updatedAt = optionalString(record, ["updatedAt", "updated_at", "modifiedAt"]);
|
|
4181
|
-
const createdAt = optionalString(record, ["createdAt", "created_at"]);
|
|
4182
|
-
const activeRun = activeRunForRecord(record);
|
|
4183
|
-
return {
|
|
4184
|
-
id,
|
|
4185
|
-
status: stringField(record, ["status", "state"], "unknown"),
|
|
4186
|
-
title: stringField(record, ["title", "name", "summary"], "Untitled task"),
|
|
4187
|
-
...priority !== undefined ? { priority } : {},
|
|
4188
|
-
...updatedAt ? { updatedAt } : {},
|
|
4189
|
-
...createdAt ? { createdAt } : {},
|
|
4190
|
-
labels: labelsFor(record),
|
|
4191
|
-
assignees: assigneesFor(record),
|
|
4192
|
-
...activeRun ? { activeRun } : {},
|
|
4193
|
-
raw: record
|
|
4194
|
-
};
|
|
4195
|
-
}
|
|
4196
|
-
function currentTaskView(ctx) {
|
|
4197
|
-
const value = ctx.getState().data?.tasks;
|
|
4198
|
-
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
4199
|
-
}
|
|
4200
|
-
function taskPayload(ctx) {
|
|
4201
|
-
const intent = ctx.getState().data?.lastIntent;
|
|
4202
|
-
return intent && typeof intent === "object" && !Array.isArray(intent) ? intent.action?.payload ?? {} : {};
|
|
4203
|
-
}
|
|
4204
|
-
function stringPayload(payload, key) {
|
|
4205
|
-
const value = payload[key];
|
|
4206
|
-
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
|
4207
|
-
}
|
|
4208
|
-
function numericPayload(payload, key) {
|
|
4209
|
-
const value = payload[key];
|
|
4210
|
-
if (typeof value === "number" && Number.isFinite(value))
|
|
4211
|
-
return value;
|
|
4212
|
-
if (typeof value === "string" && value.trim()) {
|
|
4213
|
-
const parsed = Number(value);
|
|
4214
|
-
if (Number.isFinite(parsed))
|
|
4215
|
-
return parsed;
|
|
4216
|
-
}
|
|
4217
|
-
return;
|
|
4218
|
-
}
|
|
4219
|
-
function normalizeSort(value, fallback = "priority") {
|
|
4220
|
-
const normalized = value?.trim().toLowerCase();
|
|
4221
|
-
if (normalized === "recent" || normalized === "recency" || normalized === "updated" || normalized === "updated-at")
|
|
4222
|
-
return "recency";
|
|
4223
|
-
if (normalized === "status" || normalized === "state")
|
|
4224
|
-
return "status";
|
|
4225
|
-
if (normalized === "id" || normalized === "number")
|
|
4226
|
-
return "id";
|
|
4227
|
-
if (normalized === "priority" || normalized === "prio" || normalized === "rank")
|
|
4228
|
-
return "priority";
|
|
4229
|
-
return fallback;
|
|
4230
|
-
}
|
|
4231
|
-
function normalizeAssigneeAlias2(value) {
|
|
4232
|
-
if (!value)
|
|
4233
|
-
return;
|
|
4234
|
-
const trimmed = value.trim();
|
|
4235
|
-
return trimmed.toLowerCase() === "me" ? "@me" : trimmed;
|
|
4236
|
-
}
|
|
4237
|
-
function filtersFromPreset(preset) {
|
|
4238
|
-
switch (preset?.trim().toLowerCase()) {
|
|
4239
|
-
case "all":
|
|
4240
|
-
return { preset: "all" };
|
|
4241
|
-
case "ready":
|
|
4242
|
-
return { preset: "ready", status: "ready" };
|
|
4243
|
-
case "blocked":
|
|
4244
|
-
return { preset: "blocked", status: "blocked" };
|
|
4245
|
-
case "closed":
|
|
4246
|
-
case "done":
|
|
4247
|
-
return { preset: "closed", state: "closed" };
|
|
4248
|
-
case "mine":
|
|
4249
|
-
case "me":
|
|
4250
|
-
return { preset: "mine", state: "open", assignee: "@me" };
|
|
4251
|
-
case "open":
|
|
4252
|
-
case undefined:
|
|
4253
|
-
case "":
|
|
4254
|
-
return { preset: "open", state: "open" };
|
|
4255
|
-
default:
|
|
4256
|
-
return { preset: "custom", status: preset };
|
|
4257
|
-
}
|
|
4258
|
-
}
|
|
4259
|
-
function effectiveTaskViewOptions(ctx, input = {}) {
|
|
4260
|
-
const current = currentTaskView(ctx);
|
|
4261
|
-
const payload = taskPayload(ctx);
|
|
4262
|
-
const preset = input.preset ?? stringPayload(payload, "taskFilterPreset");
|
|
4263
|
-
const baseFilters = preset !== undefined ? filtersFromPreset(preset) : current?.filters ?? filtersFromPreset("open");
|
|
4264
|
-
const payloadLimit = numericPayload(payload, "taskLimit");
|
|
4265
|
-
const mergedFilters = {
|
|
4266
|
-
...baseFilters,
|
|
4267
|
-
...input,
|
|
4268
|
-
...stringPayload(payload, "taskState") ? { state: stringPayload(payload, "taskState") } : {},
|
|
4269
|
-
...stringPayload(payload, "taskStatus") ? { status: stringPayload(payload, "taskStatus") } : {},
|
|
4270
|
-
...stringPayload(payload, "taskAssignee") ? { assignee: stringPayload(payload, "taskAssignee") } : {},
|
|
4271
|
-
...stringPayload(payload, "taskLabel") ? { label: stringPayload(payload, "taskLabel") } : {},
|
|
4272
|
-
...stringPayload(payload, "taskSearch") ? { search: stringPayload(payload, "taskSearch") } : {},
|
|
4273
|
-
...payloadLimit ? { limit: payloadLimit } : {}
|
|
4274
|
-
};
|
|
4275
|
-
const normalizedFilters = {
|
|
4276
|
-
...mergedFilters,
|
|
4277
|
-
...mergedFilters.assignee ? { assignee: normalizeAssigneeAlias2(mergedFilters.assignee) } : {}
|
|
4278
|
-
};
|
|
4279
|
-
const filters = !normalizedFilters.state && !normalizedFilters.status && !normalizedFilters.assignee && !normalizedFilters.label && !normalizedFilters.search && !normalizedFilters.preset ? { ...normalizedFilters, preset: "open", state: "open" } : normalizedFilters;
|
|
4280
|
-
const sort = normalizeSort(typeof input.sort === "string" ? input.sort : stringPayload(payload, "taskSort"), current?.sort ?? "priority");
|
|
4281
|
-
return { filters, sort };
|
|
4282
|
-
}
|
|
4283
|
-
function matchesSearch(task, search) {
|
|
4284
|
-
const needle = search?.trim().toLowerCase();
|
|
4285
|
-
if (!needle)
|
|
4286
|
-
return true;
|
|
4287
|
-
const raw = task.raw;
|
|
4288
|
-
const haystack = [
|
|
4289
|
-
task.id,
|
|
4290
|
-
task.title,
|
|
4291
|
-
task.status,
|
|
4292
|
-
task.labels.join(" "),
|
|
4293
|
-
task.assignees.join(" "),
|
|
4294
|
-
optionalString(raw, ["externalRef", "sourceIssueId", "url", "description", "acceptanceCriteria"])
|
|
4295
|
-
].filter(Boolean).join(" ").toLowerCase();
|
|
4296
|
-
return haystack.includes(needle);
|
|
4297
|
-
}
|
|
4298
|
-
function matchesLabel(task, label) {
|
|
4299
|
-
const wanted = label?.trim().toLowerCase();
|
|
4300
|
-
if (!wanted)
|
|
4301
|
-
return true;
|
|
4302
|
-
return task.labels.some((entry) => entry.toLowerCase() === wanted);
|
|
4303
|
-
}
|
|
4304
|
-
function timestamp(task) {
|
|
4305
|
-
const parsed = Date.parse(task.updatedAt ?? task.createdAt ?? "");
|
|
4306
|
-
return Number.isFinite(parsed) ? parsed : 0;
|
|
4307
|
-
}
|
|
4308
|
-
function statusRank(status) {
|
|
4309
|
-
switch (status.toLowerCase().replace(/-/g, "_")) {
|
|
4310
|
-
case "ready":
|
|
4311
|
-
return 0;
|
|
4312
|
-
case "open":
|
|
4313
|
-
return 1;
|
|
4314
|
-
case "in_progress":
|
|
4315
|
-
return 2;
|
|
4316
|
-
case "blocked":
|
|
4317
|
-
return 3;
|
|
4318
|
-
case "closed":
|
|
4319
|
-
case "completed":
|
|
4320
|
-
return 4;
|
|
4321
|
-
default:
|
|
4322
|
-
return 5;
|
|
4323
|
-
}
|
|
4324
|
-
}
|
|
4325
|
-
function sortTasks(tasks, sort) {
|
|
4326
|
-
return [...tasks].sort((left, right) => {
|
|
4327
|
-
if (sort === "recency")
|
|
4328
|
-
return timestamp(right) - timestamp(left) || left.id.localeCompare(right.id);
|
|
4329
|
-
if (sort === "status")
|
|
4330
|
-
return statusRank(left.status) - statusRank(right.status) || left.id.localeCompare(right.id);
|
|
4331
|
-
if (sort === "id")
|
|
4332
|
-
return left.id.localeCompare(right.id, undefined, { numeric: true });
|
|
4333
|
-
const leftPriority = left.priority ?? Number.NEGATIVE_INFINITY;
|
|
4334
|
-
const rightPriority = right.priority ?? Number.NEGATIVE_INFINITY;
|
|
4335
|
-
return rightPriority - leftPriority || statusRank(left.status) - statusRank(right.status) || left.id.localeCompare(right.id, undefined, { numeric: true });
|
|
4336
|
-
});
|
|
4337
|
-
}
|
|
4338
|
-
function applyLocalTaskView(records, filters, sort) {
|
|
4339
|
-
const sorted = sortTasks(records.filter((task) => matchesSearch(task, filters.search) && matchesLabel(task, filters.label)), sort);
|
|
4340
|
-
return filters.limit && filters.limit > 0 ? sorted.slice(0, filters.limit) : sorted;
|
|
4341
|
-
}
|
|
4342
|
-
function serverFilters(filters) {
|
|
4343
|
-
return {
|
|
4344
|
-
...filters.state ? { state: filters.state } : {},
|
|
4345
|
-
...filters.status ? { status: filters.status } : {},
|
|
4346
|
-
...filters.assignee ? { assignee: filters.assignee } : {}
|
|
4347
|
-
};
|
|
4348
|
-
}
|
|
4349
|
-
async function refreshTasks(ctx, input = {}) {
|
|
4350
|
-
const { filters, sort } = effectiveTaskViewOptions(ctx, input);
|
|
4351
|
-
const label = "Loading tasks";
|
|
4352
|
-
emitStarted(ctx, label);
|
|
4353
|
-
try {
|
|
4354
|
-
const { listWorkspaceTasksViaServer: listWorkspaceTasksViaServer2 } = await Promise.resolve().then(() => (init__server_client(), exports__server_client));
|
|
4355
|
-
emitProgress(ctx, label, `reading workspace tasks \xB7 filter ${filters.preset ?? filters.status ?? filters.state ?? "custom"} \xB7 sort ${sort}`);
|
|
4356
|
-
const tasks = await listWorkspaceTasksViaServer2({ projectRoot: projectRootOf(ctx) }, serverFilters(filters));
|
|
4357
|
-
const allRecords = tasks.flatMap((task) => {
|
|
4358
|
-
const entry = normalizeTaskRecord(task);
|
|
4359
|
-
return entry ? [entry] : [];
|
|
4360
|
-
});
|
|
4361
|
-
const records = applyLocalTaskView(allRecords, filters, sort);
|
|
4362
|
-
const view = {
|
|
4363
|
-
records,
|
|
4364
|
-
allRecords,
|
|
4365
|
-
filters,
|
|
4366
|
-
sort,
|
|
4367
|
-
refreshedAt: new Date().toISOString(),
|
|
4368
|
-
totalCount: allRecords.length,
|
|
4369
|
-
visibleCount: records.length
|
|
4370
|
-
};
|
|
4371
|
-
patchData(ctx, { tasks: view, selectedTaskId: records[0]?.id });
|
|
4372
|
-
patchFooter(ctx, { tasks: `${records.length}/${allRecords.length}` });
|
|
4373
|
-
emitCompleted(ctx, label, { count: records.length, totalCount: allRecords.length, sort, filters });
|
|
4374
|
-
return records;
|
|
4375
|
-
} catch (error) {
|
|
4376
|
-
emitFailed(ctx, label, error);
|
|
4377
|
-
throw error;
|
|
4378
|
-
}
|
|
4379
|
-
}
|
|
4380
|
-
async function loadRunDefaults(projectRoot) {
|
|
4381
|
-
try {
|
|
4382
|
-
const { loadTaskRunProjectDefaults: loadTaskRunProjectDefaults2 } = await Promise.resolve().then(() => (init_task(), exports_task));
|
|
4383
|
-
const defaults = await loadTaskRunProjectDefaults2(projectRoot);
|
|
4384
|
-
return {
|
|
4385
|
-
runtimeAdapter: defaults.runtimeAdapter ?? "pi",
|
|
4386
|
-
...defaults.model ? { model: defaults.model } : {},
|
|
4387
|
-
runtimeMode: defaults.runtimeMode ?? "full-access",
|
|
4388
|
-
...defaults.prMode ? { prMode: defaults.prMode } : {}
|
|
4389
|
-
};
|
|
4390
|
-
} catch {
|
|
4391
|
-
return { runtimeAdapter: "pi", runtimeMode: "full-access" };
|
|
4392
|
-
}
|
|
4393
|
-
}
|
|
4394
|
-
async function submitTaskRun(ctx, input = {}) {
|
|
4395
|
-
const projectRoot = projectRootOf(ctx);
|
|
4396
|
-
const stateRunId = ctx.getState().runId;
|
|
4397
|
-
const taskId3 = input.taskId?.trim();
|
|
4398
|
-
const title = input.title?.trim();
|
|
4399
|
-
const initialPrompt = input.initialPrompt?.trim();
|
|
4400
|
-
if (!taskId3 && !title && !initialPrompt) {
|
|
4401
|
-
const error = new Error("Select a task, then press Enter; or use run next.");
|
|
4402
|
-
emitFailed(ctx, "Dispatching task", error);
|
|
4403
|
-
throw error;
|
|
4404
|
-
}
|
|
4405
|
-
const runId = input.runId?.trim() || ctx.rig?.runId || (typeof stateRunId === "string" ? stateRunId : undefined) || randomUUID();
|
|
4406
|
-
const label = taskId3 ? `Dispatching ${taskId3}` : "Dispatching ad-hoc run";
|
|
4407
|
-
emitStarted(ctx, label, {
|
|
4408
|
-
dispatch: { runId, taskId: taskId3 ?? null, status: "dispatching" }
|
|
4409
|
-
});
|
|
4410
|
-
const optimisticTitle = title ?? taskId3 ?? "ad hoc run";
|
|
4411
|
-
patchData(ctx, {
|
|
4412
|
-
selectedRunId: runId,
|
|
4413
|
-
dispatchingRun: { runId, taskId: taskId3 ?? null, status: "dispatching", title: optimisticTitle },
|
|
4414
|
-
runDetail: { runId, status: "dispatching", title: optimisticTitle, run: {}, logs: [], timeline: [], timelineCursor: null }
|
|
4415
|
-
});
|
|
4416
|
-
patchFooter(ctx, { run: `${runId.slice(0, 8)} dispatching` });
|
|
4417
|
-
try {
|
|
4418
|
-
const { submitTaskRunViaServer: submitTaskRunViaServer2 } = await Promise.resolve().then(() => (init__server_client(), exports__server_client));
|
|
4419
|
-
const defaults = await loadRunDefaults(projectRoot);
|
|
4420
|
-
emitProgress(ctx, label, "submitting run to selected server", { runId, taskId: taskId3 ?? null });
|
|
4421
|
-
const submitted = await submitTaskRunViaServer2({ projectRoot }, {
|
|
4422
|
-
runId,
|
|
4423
|
-
taskId: taskId3 || undefined,
|
|
4424
|
-
title,
|
|
4425
|
-
runtimeAdapter: defaults.runtimeAdapter,
|
|
4426
|
-
model: defaults.model,
|
|
4427
|
-
runtimeMode: defaults.runtimeMode,
|
|
4428
|
-
interactionMode: "default",
|
|
4429
|
-
initialPrompt,
|
|
4430
|
-
baselineMode: "head",
|
|
4431
|
-
prMode: defaults.prMode
|
|
4432
|
-
});
|
|
4433
|
-
emitCompleted(ctx, label, { runId: submitted.runId, taskId: taskId3 ?? null });
|
|
4434
|
-
patchData(ctx, {
|
|
4435
|
-
selectedRunId: submitted.runId,
|
|
4436
|
-
dispatchingRun: null,
|
|
4437
|
-
latestSubmittedRun: { runId: submitted.runId, taskId: taskId3 ?? null },
|
|
4438
|
-
runDetail: { runId: submitted.runId, status: "submitted", title: optimisticTitle, run: submitted, logs: [], timeline: [], timelineCursor: null }
|
|
4439
|
-
});
|
|
4440
|
-
patchFooter(ctx, { run: `${submitted.runId.slice(0, 8)} ${input.detach ? "submitted" : "attaching"}` });
|
|
4441
|
-
if (!input.detach) {
|
|
4442
|
-
ctx.emit({
|
|
4443
|
-
type: "scene.change",
|
|
4444
|
-
scene: "handoff",
|
|
4445
|
-
intent: { scene: "handoff", argv: ["attach", submitted.runId], action: { kind: "run-attach", payload: { runId: submitted.runId }, label: `Attach Pi ${submitted.runId.slice(0, 8)}` } }
|
|
4446
|
-
});
|
|
4447
|
-
const { attachRunWithBundledPi: attachRunWithBundledPi2 } = await Promise.resolve().then(() => (init_pi_attach(), exports_pi_attach));
|
|
4448
|
-
await attachRunWithBundledPi2(ctx, submitted.runId);
|
|
4449
|
-
}
|
|
4450
|
-
return submitted;
|
|
4451
|
-
} catch (error) {
|
|
4452
|
-
const activeRunId = activeRunIdFromTaskRunError(error);
|
|
4453
|
-
if (activeRunId) {
|
|
4454
|
-
emitProgress(ctx, label, `task already has active run ${activeRunId.slice(0, 8)}; attaching Pi`, {
|
|
4455
|
-
selectedRunId: activeRunId,
|
|
4456
|
-
dispatchingRun: null,
|
|
4457
|
-
latestSubmittedRun: { runId: activeRunId, taskId: taskId3 ?? null }
|
|
4458
|
-
});
|
|
4459
|
-
patchData(ctx, { selectedRunId: activeRunId, dispatchingRun: null });
|
|
4460
|
-
patchFooter(ctx, { run: `${activeRunId.slice(0, 8)} active` });
|
|
4461
|
-
ctx.emit({
|
|
4462
|
-
type: "scene.change",
|
|
4463
|
-
scene: "handoff",
|
|
4464
|
-
intent: { scene: "handoff", argv: ["attach", activeRunId], action: { kind: "run-attach", payload: { runId: activeRunId }, label: `Attach Pi ${activeRunId.slice(0, 8)}` } }
|
|
4465
|
-
});
|
|
4466
|
-
const { attachRunWithBundledPi: attachRunWithBundledPi2 } = await Promise.resolve().then(() => (init_pi_attach(), exports_pi_attach));
|
|
4467
|
-
await attachRunWithBundledPi2(ctx, activeRunId);
|
|
4468
|
-
return { runId: activeRunId };
|
|
4469
|
-
}
|
|
4470
|
-
emitFailed(ctx, label, error, { runId, taskId: taskId3 ?? null, revert: { dispatchingRun: null } });
|
|
4471
|
-
throw error;
|
|
4472
|
-
}
|
|
4473
|
-
}
|
|
4474
|
-
async function submitNextTaskRun(ctx, filters = {}, options = {}) {
|
|
4475
|
-
const label = "Selecting next task";
|
|
4476
|
-
emitStarted(ctx, label, { dispatch: { status: "selecting-next" } });
|
|
4477
|
-
try {
|
|
4478
|
-
const { selectNextWorkspaceTaskViaServer: selectNextWorkspaceTaskViaServer2 } = await Promise.resolve().then(() => (init__server_client(), exports__server_client));
|
|
4479
|
-
const projectRoot = projectRootOf(ctx);
|
|
4480
|
-
emitProgress(ctx, label, "asking server for next runnable task");
|
|
4481
|
-
const selected = await selectNextWorkspaceTaskViaServer2({ projectRoot }, filters);
|
|
4482
|
-
const task = selected.task ? normalizeTaskRecord(selected.task) : null;
|
|
4483
|
-
patchData(ctx, { nextTask: task, nextTaskCount: selected.count });
|
|
4484
|
-
if (!task) {
|
|
4485
|
-
const error = new Error("No runnable task is available.");
|
|
4486
|
-
emitFailed(ctx, label, error, { count: selected.count });
|
|
4487
|
-
throw error;
|
|
4488
|
-
}
|
|
4489
|
-
emitCompleted(ctx, label, { taskId: task.id, count: selected.count });
|
|
4490
|
-
const submitted = await submitTaskRun(ctx, { taskId: task.id, title: task.title, detach: options.detach });
|
|
4491
|
-
return { ...submitted, task };
|
|
4492
|
-
} catch (error) {
|
|
4493
|
-
emitFailed(ctx, label, error);
|
|
4494
|
-
throw error;
|
|
4495
|
-
}
|
|
4496
|
-
}
|
|
4497
|
-
async function loadTaskPreview(ctx, taskId3) {
|
|
4498
|
-
const label = `Loading task ${taskId3}`;
|
|
4499
|
-
emitStarted(ctx, label);
|
|
4500
|
-
try {
|
|
4501
|
-
const { getWorkspaceTaskViaServer: getWorkspaceTaskViaServer2 } = await Promise.resolve().then(() => (init__server_client(), exports__server_client));
|
|
4502
|
-
const task = await getWorkspaceTaskViaServer2({ projectRoot: projectRootOf(ctx) }, taskId3);
|
|
4503
|
-
const normalized = task ? normalizeTaskRecord(task) : null;
|
|
4504
|
-
patchData(ctx, { selectedTaskId: taskId3, taskDetailId: taskId3, taskPreview: normalized, taskPreviewRaw: task ? compactRecord(task, ["id", "title", "status", "body", "url"]) : null });
|
|
4505
|
-
emitCompleted(ctx, label, { taskId: taskId3, found: Boolean(normalized) });
|
|
4506
|
-
return normalized;
|
|
4507
|
-
} catch (error) {
|
|
4508
|
-
emitFailed(ctx, label, error, { taskId: taskId3 });
|
|
4509
|
-
throw error;
|
|
4510
|
-
}
|
|
4511
|
-
}
|
|
4512
|
-
async function ensureTaskRuntime(ctx) {
|
|
4513
|
-
await runtimeOf(ctx);
|
|
4514
|
-
}
|
|
4515
|
-
export {
|
|
4516
|
-
submitTaskRun,
|
|
4517
|
-
submitNextTaskRun,
|
|
4518
|
-
refreshTasks,
|
|
4519
|
-
normalizeTaskRecord,
|
|
4520
|
-
loadTaskPreview,
|
|
4521
|
-
ensureTaskRuntime,
|
|
4522
|
-
activeRunIdFromTaskRunError,
|
|
4523
|
-
activeRunIdFromTaskLike
|
|
4524
|
-
};
|