@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,2101 +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
|
-
function normalizeAppError(error) {
|
|
26
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
27
|
-
const rawHint = error instanceof Error ? error.hint : undefined;
|
|
28
|
-
return {
|
|
29
|
-
message,
|
|
30
|
-
...typeof rawHint === "string" && rawHint.trim() ? { hint: rawHint.trim() } : {}
|
|
31
|
-
};
|
|
32
|
-
}
|
|
33
|
-
function emitStarted(ctx, label, optimistic) {
|
|
34
|
-
ctx.emit({ type: "action.started", label, ...optimistic ? { optimistic } : {} });
|
|
35
|
-
}
|
|
36
|
-
function emitProgress(ctx, label, detail, data) {
|
|
37
|
-
ctx.emit({ type: "action.progress", label, ...detail ? { detail } : {}, ...data ? { data } : {} });
|
|
38
|
-
}
|
|
39
|
-
function emitCompleted(ctx, label, data) {
|
|
40
|
-
ctx.emit({ type: "action.completed", label, ...data ? { data } : {} });
|
|
41
|
-
}
|
|
42
|
-
function emitFailed(ctx, label, error, data) {
|
|
43
|
-
if (data)
|
|
44
|
-
patchData(ctx, data);
|
|
45
|
-
const normalized = normalizeAppError(error);
|
|
46
|
-
ctx.emit({
|
|
47
|
-
type: "action.failed",
|
|
48
|
-
label,
|
|
49
|
-
message: normalized.message,
|
|
50
|
-
...normalized.hint ? { hint: normalized.hint } : {},
|
|
51
|
-
cause: error
|
|
52
|
-
});
|
|
53
|
-
}
|
|
54
|
-
function patchData(ctx, data) {
|
|
55
|
-
ctx.emit({ type: "data.patch", data });
|
|
56
|
-
}
|
|
57
|
-
function patchFooter(ctx, footer) {
|
|
58
|
-
ctx.emit({ type: "footer.patch", footer });
|
|
59
|
-
}
|
|
60
|
-
async function releaseRendererForExternalTui(ctx) {
|
|
61
|
-
const renderer = ctx.renderer;
|
|
62
|
-
if (!renderer)
|
|
63
|
-
return;
|
|
64
|
-
if (renderer.suspend) {
|
|
65
|
-
await renderer.suspend();
|
|
66
|
-
return;
|
|
67
|
-
}
|
|
68
|
-
if (renderer.destroy) {
|
|
69
|
-
await renderer.destroy();
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
async function resumeRendererAfterExternalTui(ctx) {
|
|
73
|
-
await ctx.renderer?.resume?.();
|
|
74
|
-
}
|
|
75
|
-
function arrayFromPayload(value) {
|
|
76
|
-
if (Array.isArray(value)) {
|
|
77
|
-
return value.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry)));
|
|
78
|
-
}
|
|
79
|
-
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
80
|
-
const entries = value.entries;
|
|
81
|
-
if (Array.isArray(entries))
|
|
82
|
-
return arrayFromPayload(entries);
|
|
83
|
-
}
|
|
84
|
-
return [];
|
|
85
|
-
}
|
|
86
|
-
function stringField(record, keys, fallback = "") {
|
|
87
|
-
for (const key of keys) {
|
|
88
|
-
const value = record[key];
|
|
89
|
-
if (typeof value === "string" && value.trim())
|
|
90
|
-
return value.trim();
|
|
91
|
-
if (typeof value === "number" && Number.isFinite(value))
|
|
92
|
-
return String(value);
|
|
93
|
-
}
|
|
94
|
-
return fallback;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
// packages/cli/src/runner.ts
|
|
98
|
-
import { EventBus } from "@rig/runtime/control-plane/runtime/events";
|
|
99
|
-
import { CliError as RuntimeCliError } from "@rig/runtime/control-plane/errors";
|
|
100
|
-
import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
|
|
101
|
-
import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
|
|
102
|
-
var CliError;
|
|
103
|
-
var init_runner = __esm(() => {
|
|
104
|
-
CliError = class CliError extends RuntimeCliError {
|
|
105
|
-
hint;
|
|
106
|
-
constructor(message, exitCode = 1, options = {}) {
|
|
107
|
-
super(message, exitCode);
|
|
108
|
-
if (options.hint?.trim()) {
|
|
109
|
-
this.hint = options.hint.trim();
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
};
|
|
113
|
-
});
|
|
114
|
-
|
|
115
|
-
// packages/cli/src/commands/_connection-state.ts
|
|
116
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
117
|
-
import { homedir } from "os";
|
|
118
|
-
import { dirname, resolve } from "path";
|
|
119
|
-
function resolveGlobalConnectionsPath(env = process.env) {
|
|
120
|
-
const explicit = env.RIG_CONNECTIONS_FILE?.trim();
|
|
121
|
-
if (explicit)
|
|
122
|
-
return resolve(explicit);
|
|
123
|
-
const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
|
|
124
|
-
if (stateDir)
|
|
125
|
-
return resolve(stateDir, "connections.json");
|
|
126
|
-
return resolve(homedir(), ".rig", "connections.json");
|
|
127
|
-
}
|
|
128
|
-
function resolveRepoConnectionPath(projectRoot) {
|
|
129
|
-
return resolve(projectRoot, ".rig", "state", "connection.json");
|
|
130
|
-
}
|
|
131
|
-
function readJsonFile(path) {
|
|
132
|
-
if (!existsSync(path))
|
|
133
|
-
return null;
|
|
134
|
-
try {
|
|
135
|
-
return JSON.parse(readFileSync(path, "utf8"));
|
|
136
|
-
} catch (error) {
|
|
137
|
-
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>`." });
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
function writeJsonFile(path, value) {
|
|
141
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
142
|
-
writeFileSync(path, `${JSON.stringify(value, null, 2)}
|
|
143
|
-
`, "utf8");
|
|
144
|
-
}
|
|
145
|
-
function normalizeConnection(value) {
|
|
146
|
-
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
147
|
-
return null;
|
|
148
|
-
const record = value;
|
|
149
|
-
if (record.kind === "local")
|
|
150
|
-
return { kind: "local", mode: "auto" };
|
|
151
|
-
if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
|
|
152
|
-
const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
|
|
153
|
-
return { kind: "remote", baseUrl };
|
|
154
|
-
}
|
|
155
|
-
return null;
|
|
156
|
-
}
|
|
157
|
-
function readGlobalConnections(options = {}) {
|
|
158
|
-
const path = resolveGlobalConnectionsPath(options.env ?? process.env);
|
|
159
|
-
const payload = readJsonFile(path);
|
|
160
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
161
|
-
return { connections: {} };
|
|
162
|
-
}
|
|
163
|
-
const rawConnections = payload.connections;
|
|
164
|
-
const connections = {};
|
|
165
|
-
if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
|
|
166
|
-
for (const [alias, raw] of Object.entries(rawConnections)) {
|
|
167
|
-
const connection = normalizeConnection(raw);
|
|
168
|
-
if (connection)
|
|
169
|
-
connections[alias] = connection;
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
return { connections };
|
|
173
|
-
}
|
|
174
|
-
function readRepoConnection(projectRoot) {
|
|
175
|
-
const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
|
|
176
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
177
|
-
return null;
|
|
178
|
-
const record = payload;
|
|
179
|
-
const selected = typeof record.selected === "string" ? record.selected.trim() : "";
|
|
180
|
-
if (!selected)
|
|
181
|
-
return null;
|
|
182
|
-
return {
|
|
183
|
-
selected,
|
|
184
|
-
project: typeof record.project === "string" ? record.project : undefined,
|
|
185
|
-
linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
|
|
186
|
-
serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined,
|
|
187
|
-
serverProjectRootAlias: typeof record.serverProjectRootAlias === "string" && record.serverProjectRootAlias.trim() ? record.serverProjectRootAlias.trim() : undefined,
|
|
188
|
-
serverProjectRootBaseUrl: typeof record.serverProjectRootBaseUrl === "string" && record.serverProjectRootBaseUrl.trim() ? record.serverProjectRootBaseUrl.trim().replace(/\/+$/, "") : undefined
|
|
189
|
-
};
|
|
190
|
-
}
|
|
191
|
-
function writeRepoConnection(projectRoot, state) {
|
|
192
|
-
writeJsonFile(resolveRepoConnectionPath(projectRoot), state);
|
|
193
|
-
}
|
|
194
|
-
function rootAllowedForSelection(repo, connection) {
|
|
195
|
-
const root = repo.serverProjectRoot?.trim();
|
|
196
|
-
if (!root)
|
|
197
|
-
return;
|
|
198
|
-
if (connection.kind === "remote") {
|
|
199
|
-
if (repo.serverProjectRootAlias !== repo.selected)
|
|
200
|
-
return;
|
|
201
|
-
if (repo.serverProjectRootBaseUrl !== connection.baseUrl)
|
|
202
|
-
return;
|
|
203
|
-
} else if (repo.serverProjectRootAlias && repo.serverProjectRootAlias !== repo.selected) {
|
|
204
|
-
return;
|
|
205
|
-
}
|
|
206
|
-
return root;
|
|
207
|
-
}
|
|
208
|
-
function resolveSelectedConnection(projectRoot, options = {}) {
|
|
209
|
-
const repo = readRepoConnection(projectRoot);
|
|
210
|
-
if (!repo)
|
|
211
|
-
return null;
|
|
212
|
-
if (repo.selected === "local")
|
|
213
|
-
return { alias: "local", connection: { kind: "local", mode: "auto" }, serverProjectRoot: repo.serverProjectRoot };
|
|
214
|
-
const global = readGlobalConnections(options);
|
|
215
|
-
const connection = global.connections[repo.selected];
|
|
216
|
-
if (!connection) {
|
|
217
|
-
throw new CliError(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
|
|
218
|
-
}
|
|
219
|
-
return { alias: repo.selected, connection, serverProjectRoot: rootAllowedForSelection(repo, connection) };
|
|
220
|
-
}
|
|
221
|
-
function writeRepoServerProjectRoot(projectRoot, serverProjectRoot, metadata = {}) {
|
|
222
|
-
const repo = readRepoConnection(projectRoot);
|
|
223
|
-
if (!repo)
|
|
224
|
-
return;
|
|
225
|
-
let inferred = metadata;
|
|
226
|
-
if (!inferred.alias || !inferred.baseUrl) {
|
|
227
|
-
try {
|
|
228
|
-
const selected = resolveSelectedConnection(projectRoot);
|
|
229
|
-
if (selected?.connection.kind === "remote") {
|
|
230
|
-
inferred = {
|
|
231
|
-
alias: inferred.alias ?? selected.alias,
|
|
232
|
-
baseUrl: inferred.baseUrl ?? selected.connection.baseUrl
|
|
233
|
-
};
|
|
234
|
-
}
|
|
235
|
-
} catch {}
|
|
236
|
-
}
|
|
237
|
-
writeRepoConnection(projectRoot, {
|
|
238
|
-
...repo,
|
|
239
|
-
...metadata.project ? { project: metadata.project } : {},
|
|
240
|
-
serverProjectRoot,
|
|
241
|
-
...inferred.alias ? { serverProjectRootAlias: inferred.alias } : {},
|
|
242
|
-
...inferred.baseUrl ? { serverProjectRootBaseUrl: inferred.baseUrl.replace(/\/+$/, "") } : {}
|
|
243
|
-
});
|
|
244
|
-
}
|
|
245
|
-
function clearRepoServerProjectRoot(projectRoot) {
|
|
246
|
-
const repo = readRepoConnection(projectRoot);
|
|
247
|
-
if (!repo)
|
|
248
|
-
return;
|
|
249
|
-
writeRepoConnection(projectRoot, {
|
|
250
|
-
selected: repo.selected,
|
|
251
|
-
...repo.project ? { project: repo.project } : {},
|
|
252
|
-
...repo.linkedAt ? { linkedAt: repo.linkedAt } : {}
|
|
253
|
-
});
|
|
254
|
-
}
|
|
255
|
-
var init__connection_state = __esm(() => {
|
|
256
|
-
init_runner();
|
|
257
|
-
});
|
|
258
|
-
|
|
259
|
-
// packages/cli/src/commands/_server-client.ts
|
|
260
|
-
var exports__server_client = {};
|
|
261
|
-
__export(exports__server_client, {
|
|
262
|
-
updateWorkspaceTaskViaServer: () => updateWorkspaceTaskViaServer,
|
|
263
|
-
switchServerProjectRootViaServer: () => switchServerProjectRootViaServer,
|
|
264
|
-
submitTaskRunViaServer: () => submitTaskRunViaServer,
|
|
265
|
-
stopRunViaServer: () => stopRunViaServer,
|
|
266
|
-
steerRunViaServer: () => steerRunViaServer,
|
|
267
|
-
setServerPhaseListener: () => setServerPhaseListener,
|
|
268
|
-
setGitHubBearerTokenForCurrentProcess: () => setGitHubBearerTokenForCurrentProcess,
|
|
269
|
-
sendRunPiShellViaServer: () => sendRunPiShellViaServer,
|
|
270
|
-
sendRunPiPromptViaServer: () => sendRunPiPromptViaServer,
|
|
271
|
-
selectNextWorkspaceTaskViaServer: () => selectNextWorkspaceTaskViaServer,
|
|
272
|
-
runRunPiCommandViaServer: () => runRunPiCommandViaServer,
|
|
273
|
-
resumeRunViaServer: () => resumeRunViaServer,
|
|
274
|
-
respondRunPiExtensionUiViaServer: () => respondRunPiExtensionUiViaServer,
|
|
275
|
-
resolveServerConnectionLabel: () => resolveServerConnectionLabel,
|
|
276
|
-
requestServerJson: () => requestServerJson,
|
|
277
|
-
repairRemoteProjectRootLink: () => repairRemoteProjectRootLink,
|
|
278
|
-
registerProjectViaServer: () => registerProjectViaServer,
|
|
279
|
-
prepareRemoteCheckoutViaServer: () => prepareRemoteCheckoutViaServer,
|
|
280
|
-
postGitHubTokenViaServer: () => postGitHubTokenViaServer,
|
|
281
|
-
normalizeRepoSlug: () => normalizeRepoSlug,
|
|
282
|
-
listWorkspaceTasksViaServer: () => listWorkspaceTasksViaServer,
|
|
283
|
-
listRunsViaServer: () => listRunsViaServer,
|
|
284
|
-
listGitHubProjectsViaServer: () => listGitHubProjectsViaServer,
|
|
285
|
-
isRemoteProjectRootLinkError: () => isRemoteProjectRootLinkError,
|
|
286
|
-
inspectRemoteProjectLink: () => inspectRemoteProjectLink,
|
|
287
|
-
getWorkspaceTaskViaServer: () => getWorkspaceTaskViaServer,
|
|
288
|
-
getRunTimelineViaServer: () => getRunTimelineViaServer,
|
|
289
|
-
getRunPiStatusViaServer: () => getRunPiStatusViaServer,
|
|
290
|
-
getRunPiSessionViaServer: () => getRunPiSessionViaServer,
|
|
291
|
-
getRunPiMessagesViaServer: () => getRunPiMessagesViaServer,
|
|
292
|
-
getRunPiCommandsViaServer: () => getRunPiCommandsViaServer,
|
|
293
|
-
getRunPiCapabilitiesViaServer: () => getRunPiCapabilitiesViaServer,
|
|
294
|
-
getRunLogsViaServer: () => getRunLogsViaServer,
|
|
295
|
-
getRunDetailsViaServer: () => getRunDetailsViaServer,
|
|
296
|
-
getGitHubProjectStatusFieldViaServer: () => getGitHubProjectStatusFieldViaServer,
|
|
297
|
-
getGitHubAuthStatusViaServer: () => getGitHubAuthStatusViaServer,
|
|
298
|
-
formatRemoteProjectLinkHint: () => formatRemoteProjectLinkHint,
|
|
299
|
-
ensureTaskLabelsViaServer: () => ensureTaskLabelsViaServer,
|
|
300
|
-
ensureServerForCli: () => ensureServerForCli,
|
|
301
|
-
ensureRemoteProjectRootLink: () => ensureRemoteProjectRootLink,
|
|
302
|
-
buildRunPiEventsWebSocketUrl: () => buildRunPiEventsWebSocketUrl,
|
|
303
|
-
abortRunPiViaServer: () => abortRunPiViaServer
|
|
304
|
-
});
|
|
305
|
-
import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
306
|
-
import { dirname as dirname2, isAbsolute, resolve as resolve2 } from "path";
|
|
307
|
-
import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
|
|
308
|
-
function setServerPhaseListener(listener) {
|
|
309
|
-
const previous = serverPhaseListener;
|
|
310
|
-
serverPhaseListener = listener;
|
|
311
|
-
return previous;
|
|
312
|
-
}
|
|
313
|
-
function reportServerPhase(label) {
|
|
314
|
-
serverPhaseListener?.(label);
|
|
315
|
-
}
|
|
316
|
-
function cleanToken(value) {
|
|
317
|
-
const trimmed = value?.trim();
|
|
318
|
-
return trimmed ? trimmed : null;
|
|
319
|
-
}
|
|
320
|
-
function setGitHubBearerTokenForCurrentProcess(token, projectRoot) {
|
|
321
|
-
const scopedKey = resolve2(projectRoot ?? process.cwd());
|
|
322
|
-
scopedGitHubBearerTokens.set(scopedKey, cleanToken(token ?? undefined));
|
|
323
|
-
}
|
|
324
|
-
function readRemoteAuthState(projectRoot) {
|
|
325
|
-
const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
|
|
326
|
-
if (!existsSync2(path))
|
|
327
|
-
return null;
|
|
328
|
-
try {
|
|
329
|
-
const parsed = JSON.parse(readFileSync2(path, "utf8"));
|
|
330
|
-
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
|
|
331
|
-
} catch {
|
|
332
|
-
return null;
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
function readPrivateRemoteSessionToken(projectRoot) {
|
|
336
|
-
const parsed = readRemoteAuthState(projectRoot);
|
|
337
|
-
return parsed ? cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined) : null;
|
|
338
|
-
}
|
|
339
|
-
function readGitHubBearerTokenForRemote(projectRoot) {
|
|
340
|
-
const scopedKey = resolve2(projectRoot);
|
|
341
|
-
if (scopedGitHubBearerTokens.has(scopedKey))
|
|
342
|
-
return scopedGitHubBearerTokens.get(scopedKey) ?? null;
|
|
343
|
-
const privateSession = readPrivateRemoteSessionToken(projectRoot);
|
|
344
|
-
if (privateSession)
|
|
345
|
-
return privateSession;
|
|
346
|
-
return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
|
|
347
|
-
}
|
|
348
|
-
function readStoredGitHubAuthToken(projectRoot) {
|
|
349
|
-
const parsed = readRemoteAuthState(projectRoot);
|
|
350
|
-
return parsed ? cleanToken(typeof parsed.token === "string" ? parsed.token : undefined) : null;
|
|
351
|
-
}
|
|
352
|
-
function inferRemoteServerProjectRootCandidateFromAuthState(projectRoot, repoSlug) {
|
|
353
|
-
if (!/^[^/]+\/[^/]+$/.test(repoSlug))
|
|
354
|
-
return null;
|
|
355
|
-
const repo = readRepoConnection(projectRoot);
|
|
356
|
-
const auth = readRemoteAuthState(projectRoot);
|
|
357
|
-
const authUpdatedAt = typeof auth?.updatedAt === "string" ? Date.parse(auth.updatedAt) : Number.NaN;
|
|
358
|
-
const repoLinkedAt = typeof repo?.linkedAt === "string" ? Date.parse(repo.linkedAt) : Number.NaN;
|
|
359
|
-
if (Number.isFinite(authUpdatedAt) && Number.isFinite(repoLinkedAt) && authUpdatedAt + 1000 < repoLinkedAt)
|
|
360
|
-
return null;
|
|
361
|
-
const checkoutBaseDir = typeof auth?.checkoutBaseDir === "string" && auth.checkoutBaseDir.trim() ? auth.checkoutBaseDir.trim() : null;
|
|
362
|
-
if (!checkoutBaseDir)
|
|
363
|
-
return null;
|
|
364
|
-
return `${checkoutBaseDir.replace(/\/+$/, "")}/${repoSlug}`;
|
|
365
|
-
}
|
|
366
|
-
function readLocalConnectionFallbackToken(projectRoot) {
|
|
367
|
-
return readGitHubBearerTokenForRemote(projectRoot) ?? cleanToken(process.env.RIG_GITHUB_TOKEN) ?? readStoredGitHubAuthToken(projectRoot);
|
|
368
|
-
}
|
|
369
|
-
function normalizeRepoSlug(value) {
|
|
370
|
-
const slug = value?.trim();
|
|
371
|
-
return slug && /^[^/\s]+\/[^/\s]+$/.test(slug) ? slug : null;
|
|
372
|
-
}
|
|
373
|
-
function readProjectLinkSlug(projectRoot) {
|
|
374
|
-
const path = resolve2(projectRoot, ".rig", "state", "project-link.json");
|
|
375
|
-
if (!existsSync2(path))
|
|
376
|
-
return null;
|
|
377
|
-
try {
|
|
378
|
-
const parsed = JSON.parse(readFileSync2(path, "utf8"));
|
|
379
|
-
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
380
|
-
return null;
|
|
381
|
-
return normalizeRepoSlug(typeof parsed.repoSlug === "string" ? String(parsed.repoSlug) : null);
|
|
382
|
-
} catch {
|
|
383
|
-
return null;
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
function writeProjectLinkConnection(projectRoot, repoSlug, alias) {
|
|
387
|
-
const path = resolve2(projectRoot, ".rig", "state", "project-link.json");
|
|
388
|
-
mkdirSync2(dirname2(path), { recursive: true });
|
|
389
|
-
writeFileSync2(path, `${JSON.stringify({ repoSlug, connection: alias, linkedAt: new Date().toISOString() }, null, 2)}
|
|
390
|
-
`, "utf8");
|
|
391
|
-
}
|
|
392
|
-
function remoteLinkRepairCommand(repoSlug) {
|
|
393
|
-
return repoSlug ? `rig server repair-link --repo ${repoSlug}` : "rig server repair-link --repo owner/repo";
|
|
394
|
-
}
|
|
395
|
-
function isRemoteProjectRootLinkError(error) {
|
|
396
|
-
const text = error instanceof Error ? error.message : String(error ?? "");
|
|
397
|
-
return /no server-host project root link|remote project(?:-root)? link|x-rig-project-root|serverProjectRoot/i.test(text);
|
|
398
|
-
}
|
|
399
|
-
function formatRemoteProjectLinkHint(resolution) {
|
|
400
|
-
const repair = remoteLinkRepairCommand(resolution.repoSlug);
|
|
401
|
-
if (resolution.status === "auth_required") {
|
|
402
|
-
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}` : ""}\`.`;
|
|
403
|
-
}
|
|
404
|
-
if (resolution.status === "missing_project") {
|
|
405
|
-
return `Record the repo slug, then run \`${repair}\` (or \`rig init --repo owner/repo --server remote --github-auth device\`).`;
|
|
406
|
-
}
|
|
407
|
-
if (resolution.status === "not_remote")
|
|
408
|
-
return "Select a remote server with `rig server use <alias>` before repairing a remote project link.";
|
|
409
|
-
return `Run \`${repair}\` to backfill or prepare a server-host checkout for the selected remote${resolution.alias ? ` (${resolution.alias})` : ""}.`;
|
|
410
|
-
}
|
|
411
|
-
function remoteProjectLinkFailure(input) {
|
|
412
|
-
const partial = {
|
|
413
|
-
status: input.status,
|
|
414
|
-
alias: input.alias,
|
|
415
|
-
baseUrl: input.baseUrl,
|
|
416
|
-
repoSlug: input.repoSlug
|
|
417
|
-
};
|
|
418
|
-
return {
|
|
419
|
-
ok: false,
|
|
420
|
-
...input,
|
|
421
|
-
hint: formatRemoteProjectLinkHint(partial),
|
|
422
|
-
next: remoteLinkRepairCommand(input.repoSlug)
|
|
423
|
-
};
|
|
424
|
-
}
|
|
425
|
-
function remoteProjectLinkSuccess(input) {
|
|
426
|
-
return {
|
|
427
|
-
ok: true,
|
|
428
|
-
status: input.status,
|
|
429
|
-
alias: input.alias,
|
|
430
|
-
baseUrl: input.baseUrl,
|
|
431
|
-
repoSlug: input.repoSlug,
|
|
432
|
-
serverProjectRoot: input.serverProjectRoot,
|
|
433
|
-
source: input.source,
|
|
434
|
-
prepared: input.prepared ?? input.status === "prepared",
|
|
435
|
-
validated: input.validated ?? false,
|
|
436
|
-
message: input.message ?? `Remote project link ready for ${input.repoSlug}.`,
|
|
437
|
-
hint: "Remote-scoped task/run/status requests will send x-rig-project-root for this server-host checkout.",
|
|
438
|
-
next: "rig task list"
|
|
439
|
-
};
|
|
440
|
-
}
|
|
441
|
-
function localCheckoutPathCandidate(projectRoot, candidate) {
|
|
442
|
-
try {
|
|
443
|
-
const local = resolve2(projectRoot);
|
|
444
|
-
const resolved = resolve2(candidate);
|
|
445
|
-
return resolved === local || resolved.startsWith(`${local}/`);
|
|
446
|
-
} catch {
|
|
447
|
-
return false;
|
|
448
|
-
}
|
|
449
|
-
}
|
|
450
|
-
async function requestRemoteProjectLinkJson(baseUrl, pathname, authToken, init = {}) {
|
|
451
|
-
const requestUrl = new URL(`${baseUrl}${pathname}`);
|
|
452
|
-
if (authToken && queryAuthFallbackEnabled())
|
|
453
|
-
requestUrl.searchParams.set("rt", authToken);
|
|
454
|
-
const response = await fetch(requestUrl, {
|
|
455
|
-
...init,
|
|
456
|
-
headers: mergeHeaders(init.headers, authToken)
|
|
457
|
-
});
|
|
458
|
-
const text = await response.text();
|
|
459
|
-
const payload = text.trim().length > 0 ? (() => {
|
|
460
|
-
try {
|
|
461
|
-
return JSON.parse(text);
|
|
462
|
-
} catch {
|
|
463
|
-
return null;
|
|
464
|
-
}
|
|
465
|
-
})() : null;
|
|
466
|
-
return { ok: response.ok, status: response.status, payload, text };
|
|
467
|
-
}
|
|
468
|
-
function payloadError(payload, fallback) {
|
|
469
|
-
if (payload && typeof payload === "object" && !Array.isArray(payload)) {
|
|
470
|
-
const record = payload;
|
|
471
|
-
const value = record.error ?? record.message ?? record.reason;
|
|
472
|
-
if (typeof value === "string" && value.trim())
|
|
473
|
-
return value.trim();
|
|
474
|
-
}
|
|
475
|
-
return fallback;
|
|
476
|
-
}
|
|
477
|
-
function checkoutPathsFromProjectPayload(payload) {
|
|
478
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
479
|
-
return [];
|
|
480
|
-
const project = payload.project;
|
|
481
|
-
if (!project || typeof project !== "object" || Array.isArray(project))
|
|
482
|
-
return [];
|
|
483
|
-
const checkouts = project.checkouts;
|
|
484
|
-
if (!Array.isArray(checkouts))
|
|
485
|
-
return [];
|
|
486
|
-
return [...checkouts].reverse().flatMap((entry) => {
|
|
487
|
-
if (!entry || typeof entry !== "object" || Array.isArray(entry))
|
|
488
|
-
return [];
|
|
489
|
-
const path = entry.path;
|
|
490
|
-
return typeof path === "string" && path.trim() ? [path.trim()] : [];
|
|
491
|
-
});
|
|
492
|
-
}
|
|
493
|
-
function checkoutPathFromPreparePayload(payload) {
|
|
494
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
495
|
-
return null;
|
|
496
|
-
const checkout = payload.checkout;
|
|
497
|
-
if (!checkout || typeof checkout !== "object" || Array.isArray(checkout))
|
|
498
|
-
return null;
|
|
499
|
-
const path = checkout.path;
|
|
500
|
-
return typeof path === "string" && path.trim() ? path.trim() : null;
|
|
501
|
-
}
|
|
502
|
-
async function validateAndPersistRemoteRoot(input) {
|
|
503
|
-
const candidate = input.candidate.trim();
|
|
504
|
-
if (!candidate || !isAbsolute(candidate)) {
|
|
505
|
-
return remoteProjectLinkFailure({
|
|
506
|
-
status: "invalid_root",
|
|
507
|
-
alias: input.alias,
|
|
508
|
-
baseUrl: input.baseUrl,
|
|
509
|
-
repoSlug: input.repoSlug,
|
|
510
|
-
message: `Remote project root candidate is not an absolute server-host path: ${candidate || "(empty)"}.`
|
|
511
|
-
});
|
|
512
|
-
}
|
|
513
|
-
if (localCheckoutPathCandidate(input.projectRoot, candidate)) {
|
|
514
|
-
return remoteProjectLinkFailure({
|
|
515
|
-
status: "invalid_root",
|
|
516
|
-
alias: input.alias,
|
|
517
|
-
baseUrl: input.baseUrl,
|
|
518
|
-
repoSlug: input.repoSlug,
|
|
519
|
-
message: `Refusing to use local checkout path ${candidate} as a remote server project root.`
|
|
520
|
-
});
|
|
521
|
-
}
|
|
522
|
-
let response;
|
|
523
|
-
try {
|
|
524
|
-
response = await requestRemoteProjectLinkJson(input.baseUrl, "/api/server/project-root", input.authToken, {
|
|
525
|
-
method: "POST",
|
|
526
|
-
headers: { "content-type": "application/json" },
|
|
527
|
-
body: JSON.stringify({ projectRoot: candidate })
|
|
528
|
-
});
|
|
529
|
-
} catch (error) {
|
|
530
|
-
return remoteProjectLinkFailure({
|
|
531
|
-
status: "error",
|
|
532
|
-
alias: input.alias,
|
|
533
|
-
baseUrl: input.baseUrl,
|
|
534
|
-
repoSlug: input.repoSlug,
|
|
535
|
-
message: `Could not validate remote project root ${candidate}: ${error instanceof Error ? error.message : String(error)}`
|
|
536
|
-
});
|
|
537
|
-
}
|
|
538
|
-
if (response.status === 401 || response.status === 403) {
|
|
539
|
-
return remoteProjectLinkFailure({
|
|
540
|
-
status: "auth_required",
|
|
541
|
-
alias: input.alias,
|
|
542
|
-
baseUrl: input.baseUrl,
|
|
543
|
-
repoSlug: input.repoSlug,
|
|
544
|
-
statusCode: response.status,
|
|
545
|
-
message: `Remote server ${input.alias} requires authentication before validating project root ${candidate}.`
|
|
546
|
-
});
|
|
547
|
-
}
|
|
548
|
-
if (!response.ok) {
|
|
549
|
-
return remoteProjectLinkFailure({
|
|
550
|
-
status: "invalid_root",
|
|
551
|
-
alias: input.alias,
|
|
552
|
-
baseUrl: input.baseUrl,
|
|
553
|
-
repoSlug: input.repoSlug,
|
|
554
|
-
statusCode: response.status,
|
|
555
|
-
message: `Remote server rejected project root ${candidate} (${response.status}): ${payloadError(response.payload, response.text || "project-root validation failed")}`
|
|
556
|
-
});
|
|
557
|
-
}
|
|
558
|
-
const record = response.payload && typeof response.payload === "object" && !Array.isArray(response.payload) ? response.payload : {};
|
|
559
|
-
if (record.ok !== true) {
|
|
560
|
-
return remoteProjectLinkFailure({
|
|
561
|
-
status: "invalid_root",
|
|
562
|
-
alias: input.alias,
|
|
563
|
-
baseUrl: input.baseUrl,
|
|
564
|
-
repoSlug: input.repoSlug,
|
|
565
|
-
message: `Remote server did not accept project root ${candidate}: ${payloadError(response.payload, "project-root validation failed")}`
|
|
566
|
-
});
|
|
567
|
-
}
|
|
568
|
-
const accepted = typeof record.projectRoot === "string" && record.projectRoot.trim() ? record.projectRoot.trim() : typeof record.requestedProjectRoot === "string" && record.requestedProjectRoot.trim() ? record.requestedProjectRoot.trim() : candidate;
|
|
569
|
-
writeRepoServerProjectRoot(input.projectRoot, accepted, { alias: input.alias, baseUrl: input.baseUrl, project: input.repoSlug });
|
|
570
|
-
writeProjectLinkConnection(input.projectRoot, input.repoSlug, input.alias);
|
|
571
|
-
const status = input.status ?? (input.prepared ? "prepared" : "backfilled");
|
|
572
|
-
return remoteProjectLinkSuccess({
|
|
573
|
-
status,
|
|
574
|
-
alias: input.alias,
|
|
575
|
-
baseUrl: input.baseUrl,
|
|
576
|
-
repoSlug: input.repoSlug,
|
|
577
|
-
serverProjectRoot: accepted,
|
|
578
|
-
source: input.source,
|
|
579
|
-
prepared: input.prepared,
|
|
580
|
-
validated: true,
|
|
581
|
-
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}.`
|
|
582
|
-
});
|
|
583
|
-
}
|
|
584
|
-
async function ensureRemoteProjectRootLink(projectRoot, options = {}) {
|
|
585
|
-
let selected;
|
|
586
|
-
try {
|
|
587
|
-
selected = resolveSelectedConnection(projectRoot);
|
|
588
|
-
} catch (error) {
|
|
589
|
-
return remoteProjectLinkFailure({ status: "error", message: error instanceof Error ? error.message : String(error) });
|
|
590
|
-
}
|
|
591
|
-
if (!selected || selected.connection.kind !== "remote") {
|
|
592
|
-
return remoteProjectLinkFailure({ status: "not_remote", message: "No remote Rig server is selected for this repo." });
|
|
593
|
-
}
|
|
594
|
-
const repo = readRepoConnection(projectRoot);
|
|
595
|
-
const explicitRepoRequested = options.repoSlug !== undefined;
|
|
596
|
-
const explicitRepoSlug = explicitRepoRequested ? normalizeRepoSlug(options.repoSlug) : null;
|
|
597
|
-
const repoProjectSlug = normalizeRepoSlug(repo?.project);
|
|
598
|
-
const repoSlug = explicitRepoSlug ?? repoProjectSlug ?? readProjectLinkSlug(projectRoot);
|
|
599
|
-
const alias = selected.alias;
|
|
600
|
-
const baseUrl = selected.connection.baseUrl;
|
|
601
|
-
const authToken = options.authToken === undefined ? readGitHubBearerTokenForRemote(projectRoot) : options.authToken;
|
|
602
|
-
const mode = options.mode ?? "backfill-only";
|
|
603
|
-
if (explicitRepoRequested && !explicitRepoSlug) {
|
|
604
|
-
return remoteProjectLinkFailure({
|
|
605
|
-
status: "missing_project",
|
|
606
|
-
alias,
|
|
607
|
-
baseUrl,
|
|
608
|
-
message: `Invalid --repo value ${JSON.stringify(options.repoSlug)}. Expected owner/repo.`
|
|
609
|
-
});
|
|
610
|
-
}
|
|
611
|
-
if (!repoSlug) {
|
|
612
|
-
return remoteProjectLinkFailure({
|
|
613
|
-
status: "missing_project",
|
|
614
|
-
alias,
|
|
615
|
-
baseUrl,
|
|
616
|
-
message: `Remote server ${alias} is selected, but this checkout has no GitHub repo slug recorded.`
|
|
617
|
-
});
|
|
618
|
-
}
|
|
619
|
-
const skippedCandidates = [];
|
|
620
|
-
const storedRoot = selected.serverProjectRoot?.trim() || null;
|
|
621
|
-
const storedRootMatchesResolvedRepo = repoProjectSlug === repoSlug;
|
|
622
|
-
if (storedRoot && storedRootMatchesResolvedRepo) {
|
|
623
|
-
if (localCheckoutPathCandidate(projectRoot, storedRoot)) {
|
|
624
|
-
clearRepoServerProjectRoot(projectRoot);
|
|
625
|
-
skippedCandidates.push(storedRoot);
|
|
626
|
-
} else {
|
|
627
|
-
const storedResult = await validateAndPersistRemoteRoot({
|
|
628
|
-
projectRoot,
|
|
629
|
-
alias,
|
|
630
|
-
baseUrl,
|
|
631
|
-
authToken,
|
|
632
|
-
repoSlug,
|
|
633
|
-
candidate: storedRoot,
|
|
634
|
-
source: "stored",
|
|
635
|
-
status: "ready"
|
|
636
|
-
});
|
|
637
|
-
if (storedResult.ok || storedResult.status === "auth_required" || storedResult.status === "error")
|
|
638
|
-
return storedResult;
|
|
639
|
-
clearRepoServerProjectRoot(projectRoot);
|
|
640
|
-
skippedCandidates.push(storedRoot);
|
|
641
|
-
}
|
|
642
|
-
} else if (storedRoot) {
|
|
643
|
-
skippedCandidates.push(storedRoot);
|
|
644
|
-
}
|
|
645
|
-
const authCandidate = inferRemoteServerProjectRootCandidateFromAuthState(projectRoot, repoSlug);
|
|
646
|
-
if (authCandidate) {
|
|
647
|
-
const authResult = await validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate: authCandidate, source: "auth-state" });
|
|
648
|
-
if (authResult.ok || authResult.status === "auth_required")
|
|
649
|
-
return authResult;
|
|
650
|
-
}
|
|
651
|
-
let registryResponse;
|
|
652
|
-
try {
|
|
653
|
-
registryResponse = await requestRemoteProjectLinkJson(baseUrl, `/api/projects/${encodeURIComponent(repoSlug)}`, authToken);
|
|
654
|
-
} catch (error) {
|
|
655
|
-
return remoteProjectLinkFailure({
|
|
656
|
-
status: "error",
|
|
657
|
-
alias,
|
|
658
|
-
baseUrl,
|
|
659
|
-
repoSlug,
|
|
660
|
-
message: `Could not read remote project registry for ${repoSlug} on ${alias}: ${error instanceof Error ? error.message : String(error)}`
|
|
661
|
-
});
|
|
662
|
-
}
|
|
663
|
-
if (registryResponse.status === 401 || registryResponse.status === 403) {
|
|
664
|
-
return remoteProjectLinkFailure({
|
|
665
|
-
status: "auth_required",
|
|
666
|
-
alias,
|
|
667
|
-
baseUrl,
|
|
668
|
-
repoSlug,
|
|
669
|
-
statusCode: registryResponse.status,
|
|
670
|
-
message: `Remote server ${alias} requires authentication before reading the ${repoSlug} project registry.`
|
|
671
|
-
});
|
|
672
|
-
}
|
|
673
|
-
if (registryResponse.ok) {
|
|
674
|
-
const candidates = checkoutPathsFromProjectPayload(registryResponse.payload);
|
|
675
|
-
for (const candidate of candidates) {
|
|
676
|
-
const result = await validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate, source: "registry" });
|
|
677
|
-
if (result.ok || result.status === "auth_required")
|
|
678
|
-
return result;
|
|
679
|
-
skippedCandidates.push(candidate);
|
|
680
|
-
}
|
|
681
|
-
if (mode === "backfill-only") {
|
|
682
|
-
return remoteProjectLinkFailure({
|
|
683
|
-
status: candidates.length > 0 ? "invalid_root" : "no_server_checkout",
|
|
684
|
-
alias,
|
|
685
|
-
baseUrl,
|
|
686
|
-
repoSlug,
|
|
687
|
-
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.`,
|
|
688
|
-
skippedCandidates
|
|
689
|
-
});
|
|
690
|
-
}
|
|
691
|
-
} else if (registryResponse.status === 404) {
|
|
692
|
-
if (mode === "backfill-only") {
|
|
693
|
-
return remoteProjectLinkFailure({
|
|
694
|
-
status: "project_not_registered",
|
|
695
|
-
alias,
|
|
696
|
-
baseUrl,
|
|
697
|
-
repoSlug,
|
|
698
|
-
statusCode: registryResponse.status,
|
|
699
|
-
message: `Remote server ${alias} has no registered project record for ${repoSlug}.`
|
|
700
|
-
});
|
|
701
|
-
}
|
|
702
|
-
} else {
|
|
703
|
-
return remoteProjectLinkFailure({
|
|
704
|
-
status: "error",
|
|
705
|
-
alias,
|
|
706
|
-
baseUrl,
|
|
707
|
-
repoSlug,
|
|
708
|
-
statusCode: registryResponse.status,
|
|
709
|
-
message: `Could not backfill ${repoSlug} from remote registry (${registryResponse.status}): ${payloadError(registryResponse.payload, registryResponse.text || "registry lookup failed")}`,
|
|
710
|
-
skippedCandidates
|
|
711
|
-
});
|
|
712
|
-
}
|
|
713
|
-
let prepareResponse;
|
|
714
|
-
try {
|
|
715
|
-
prepareResponse = await requestRemoteProjectLinkJson(baseUrl, `/api/projects/${encodeURIComponent(repoSlug)}/prepare-checkout`, authToken, {
|
|
716
|
-
method: "POST",
|
|
717
|
-
headers: { "content-type": "application/json" },
|
|
718
|
-
body: JSON.stringify({ checkout: { kind: "managed-clone" }, repoUrl: `https://github.com/${repoSlug}.git` })
|
|
719
|
-
});
|
|
720
|
-
} catch (error) {
|
|
721
|
-
return remoteProjectLinkFailure({
|
|
722
|
-
status: "error",
|
|
723
|
-
alias,
|
|
724
|
-
baseUrl,
|
|
725
|
-
repoSlug,
|
|
726
|
-
message: `Could not prepare remote checkout for ${repoSlug} on ${alias}: ${error instanceof Error ? error.message : String(error)}`
|
|
727
|
-
});
|
|
728
|
-
}
|
|
729
|
-
if (prepareResponse.status === 401 || prepareResponse.status === 403) {
|
|
730
|
-
return remoteProjectLinkFailure({
|
|
731
|
-
status: "auth_required",
|
|
732
|
-
alias,
|
|
733
|
-
baseUrl,
|
|
734
|
-
repoSlug,
|
|
735
|
-
statusCode: prepareResponse.status,
|
|
736
|
-
message: `Remote server ${alias} requires authentication before preparing ${repoSlug}.`
|
|
737
|
-
});
|
|
738
|
-
}
|
|
739
|
-
if (!prepareResponse.ok) {
|
|
740
|
-
return remoteProjectLinkFailure({
|
|
741
|
-
status: "error",
|
|
742
|
-
alias,
|
|
743
|
-
baseUrl,
|
|
744
|
-
repoSlug,
|
|
745
|
-
statusCode: prepareResponse.status,
|
|
746
|
-
message: `Remote checkout prepare failed for ${repoSlug} (${prepareResponse.status}): ${payloadError(prepareResponse.payload, prepareResponse.text || "prepare-checkout failed")}`,
|
|
747
|
-
skippedCandidates
|
|
748
|
-
});
|
|
749
|
-
}
|
|
750
|
-
const preparedPath = checkoutPathFromPreparePayload(prepareResponse.payload);
|
|
751
|
-
if (!preparedPath) {
|
|
752
|
-
return remoteProjectLinkFailure({
|
|
753
|
-
status: "invalid_root",
|
|
754
|
-
alias,
|
|
755
|
-
baseUrl,
|
|
756
|
-
repoSlug,
|
|
757
|
-
message: `Remote checkout prepare for ${repoSlug} did not return a checkout.path.`,
|
|
758
|
-
skippedCandidates
|
|
759
|
-
});
|
|
760
|
-
}
|
|
761
|
-
return validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate: preparedPath, source: "prepare", prepared: true });
|
|
762
|
-
}
|
|
763
|
-
async function inspectRemoteProjectLink(projectRoot) {
|
|
764
|
-
return ensureRemoteProjectRootLink(projectRoot, { mode: "backfill-only" });
|
|
765
|
-
}
|
|
766
|
-
async function repairRemoteProjectRootLink(context, options = {}) {
|
|
767
|
-
const resolution = await ensureRemoteProjectRootLink(context.projectRoot, { mode: options.mode ?? "prepare-if-missing", repoSlug: options.repoSlug });
|
|
768
|
-
if (!resolution.ok)
|
|
769
|
-
throw new CliError(resolution.message, 1, { hint: resolution.hint });
|
|
770
|
-
return resolution;
|
|
771
|
-
}
|
|
772
|
-
async function ensureServerForCli(projectRoot) {
|
|
773
|
-
try {
|
|
774
|
-
const selected = resolveSelectedConnection(projectRoot);
|
|
775
|
-
if (selected?.connection.kind === "remote") {
|
|
776
|
-
reportServerPhase(`Connecting to ${selected.alias}\u2026`);
|
|
777
|
-
const authToken = readGitHubBearerTokenForRemote(projectRoot);
|
|
778
|
-
const link = await ensureRemoteProjectRootLink(projectRoot, { mode: "backfill-only", authToken });
|
|
779
|
-
return {
|
|
780
|
-
baseUrl: selected.connection.baseUrl,
|
|
781
|
-
authToken,
|
|
782
|
-
connectionKind: "remote",
|
|
783
|
-
serverProjectRoot: link.ok ? link.serverProjectRoot ?? null : null
|
|
784
|
-
};
|
|
785
|
-
}
|
|
786
|
-
reportServerPhase("Starting local Rig server\u2026");
|
|
787
|
-
const connection = await ensureLocalRigServerConnection(projectRoot);
|
|
788
|
-
return {
|
|
789
|
-
baseUrl: connection.baseUrl,
|
|
790
|
-
authToken: connection.authToken ?? readLocalConnectionFallbackToken(projectRoot),
|
|
791
|
-
connectionKind: "local",
|
|
792
|
-
serverProjectRoot: resolve2(projectRoot)
|
|
793
|
-
};
|
|
794
|
-
} catch (error) {
|
|
795
|
-
if (error instanceof Error) {
|
|
796
|
-
throw new CliError(error.message, 1);
|
|
797
|
-
}
|
|
798
|
-
throw error;
|
|
799
|
-
}
|
|
800
|
-
}
|
|
801
|
-
function appendTaskFilterParams(url, filters) {
|
|
802
|
-
if (filters.assignee)
|
|
803
|
-
url.searchParams.set("assignee", filters.assignee);
|
|
804
|
-
if (filters.state)
|
|
805
|
-
url.searchParams.set("state", filters.state);
|
|
806
|
-
if (filters.status)
|
|
807
|
-
url.searchParams.set("status", filters.status);
|
|
808
|
-
if (filters.limit !== undefined)
|
|
809
|
-
url.searchParams.set("limit", String(filters.limit));
|
|
810
|
-
}
|
|
811
|
-
function mergeCookie(existing, name, value) {
|
|
812
|
-
const encoded = `${name}=${encodeURIComponent(value)}`;
|
|
813
|
-
if (!existing?.trim())
|
|
814
|
-
return encoded;
|
|
815
|
-
const parts = existing.split(";").map((part) => part.trim()).filter((part) => part && !part.startsWith(`${name}=`));
|
|
816
|
-
return [...parts, encoded].join("; ");
|
|
817
|
-
}
|
|
818
|
-
function queryAuthFallbackEnabled(env = process.env) {
|
|
819
|
-
return env.RIG_ENABLE_QUERY_AUTH_FALLBACK === "1" || env.RIG_QUERY_AUTH_FALLBACK === "1";
|
|
820
|
-
}
|
|
821
|
-
function mergeHeaders(headers, authToken) {
|
|
822
|
-
const merged = new Headers(headers);
|
|
823
|
-
if (authToken) {
|
|
824
|
-
const bearer = `Bearer ${authToken}`;
|
|
825
|
-
merged.set("authorization", bearer);
|
|
826
|
-
merged.set("x-auth", bearer);
|
|
827
|
-
merged.set("cookie", mergeCookie(merged.get("cookie"), "rig_auth", authToken));
|
|
828
|
-
}
|
|
829
|
-
return merged;
|
|
830
|
-
}
|
|
831
|
-
function diagnosticMessage(payload) {
|
|
832
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
833
|
-
return null;
|
|
834
|
-
const record = payload;
|
|
835
|
-
const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
|
|
836
|
-
const messages = diagnostics.flatMap((entry) => {
|
|
837
|
-
if (!entry || typeof entry !== "object" || Array.isArray(entry))
|
|
838
|
-
return [];
|
|
839
|
-
const diagnostic = entry;
|
|
840
|
-
const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
|
|
841
|
-
const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
|
|
842
|
-
return message ? [`${kind}: ${message}`] : [];
|
|
843
|
-
});
|
|
844
|
-
return messages.length > 0 ? messages.join("; ") : null;
|
|
845
|
-
}
|
|
846
|
-
async function probeServerReachability(baseUrl, authToken) {
|
|
847
|
-
try {
|
|
848
|
-
const response = await fetch(`${baseUrl.replace(/\/+$/, "")}/api/server/status`, {
|
|
849
|
-
headers: mergeHeaders(undefined, authToken),
|
|
850
|
-
signal: AbortSignal.timeout(1500)
|
|
851
|
-
});
|
|
852
|
-
return response.ok;
|
|
853
|
-
} catch {
|
|
854
|
-
return false;
|
|
855
|
-
}
|
|
856
|
-
}
|
|
857
|
-
function cachedServerReachability(projectRoot, baseUrl, authToken) {
|
|
858
|
-
const key = resolve2(projectRoot);
|
|
859
|
-
const cached = serverReachabilityCache.get(key);
|
|
860
|
-
if (cached)
|
|
861
|
-
return cached;
|
|
862
|
-
const probe = probeServerReachability(baseUrl, authToken);
|
|
863
|
-
serverReachabilityCache.set(key, probe);
|
|
864
|
-
return probe;
|
|
865
|
-
}
|
|
866
|
-
function describeSelectedServer(projectRoot, server) {
|
|
867
|
-
try {
|
|
868
|
-
const selected = resolveSelectedConnection(projectRoot);
|
|
869
|
-
if (selected) {
|
|
870
|
-
return {
|
|
871
|
-
alias: selected.alias,
|
|
872
|
-
target: selected.connection.kind === "remote" ? selected.connection.baseUrl : server.baseUrl
|
|
873
|
-
};
|
|
874
|
-
}
|
|
875
|
-
} catch {}
|
|
876
|
-
return { alias: server.connectionKind === "remote" ? "remote" : "local", target: server.baseUrl };
|
|
877
|
-
}
|
|
878
|
-
async function buildServerFailureContext(projectRoot, server) {
|
|
879
|
-
const { alias, target } = describeSelectedServer(projectRoot, server);
|
|
880
|
-
const reachable = await cachedServerReachability(projectRoot, server.baseUrl, server.authToken);
|
|
881
|
-
const reachability = reachable ? "server is reachable" : "server is unreachable";
|
|
882
|
-
return {
|
|
883
|
-
contextLine: `Currently connected to: ${alias} at ${target} (${reachability}).`,
|
|
884
|
-
hint: "Check the selected server with `rig server status`, or switch with `rig server use <alias|local>`."
|
|
885
|
-
};
|
|
886
|
-
}
|
|
887
|
-
function isLoopbackRemoteBaseUrl(baseUrl) {
|
|
888
|
-
try {
|
|
889
|
-
const host = new URL(baseUrl).hostname.toLowerCase();
|
|
890
|
-
return host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]";
|
|
891
|
-
} catch {
|
|
892
|
-
return false;
|
|
893
|
-
}
|
|
894
|
-
}
|
|
895
|
-
function canUseRemoteWithoutProjectRoot(pathname) {
|
|
896
|
-
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/");
|
|
897
|
-
}
|
|
898
|
-
async function requestServerJson(context, pathname, init = {}) {
|
|
899
|
-
const server = await ensureServerForCli(context.projectRoot);
|
|
900
|
-
const requestUrl = new URL(`${server.baseUrl}${pathname}`);
|
|
901
|
-
let scopedServerProjectRoot = server.serverProjectRoot;
|
|
902
|
-
if (server.connectionKind === "remote" && !scopedServerProjectRoot && !canUseRemoteWithoutProjectRoot(requestUrl.pathname) && (server.authToken || !isLoopbackRemoteBaseUrl(server.baseUrl))) {
|
|
903
|
-
const link = await ensureRemoteProjectRootLink(context.projectRoot, { mode: "backfill-only", authToken: server.authToken });
|
|
904
|
-
if (link.ok && link.serverProjectRoot) {
|
|
905
|
-
scopedServerProjectRoot = link.serverProjectRoot;
|
|
906
|
-
} else {
|
|
907
|
-
const repo = readRepoConnection(context.projectRoot);
|
|
908
|
-
const target = link.alias && link.baseUrl ? `${link.alias} (${link.baseUrl})` : server.baseUrl;
|
|
909
|
-
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 });
|
|
910
|
-
}
|
|
911
|
-
}
|
|
912
|
-
const headers = mergeHeaders(init.headers, server.authToken);
|
|
913
|
-
if (scopedServerProjectRoot)
|
|
914
|
-
headers.set("x-rig-project-root", scopedServerProjectRoot);
|
|
915
|
-
if (server.connectionKind === "remote" && server.authToken && queryAuthFallbackEnabled()) {
|
|
916
|
-
requestUrl.searchParams.set("rt", server.authToken);
|
|
917
|
-
}
|
|
918
|
-
reportServerPhase(`${(init.method ?? "GET").toUpperCase()} ${pathname.split("?")[0]}\u2026`);
|
|
919
|
-
let response;
|
|
920
|
-
try {
|
|
921
|
-
response = await fetch(requestUrl, {
|
|
922
|
-
...init,
|
|
923
|
-
headers
|
|
924
|
-
});
|
|
925
|
-
} catch (error) {
|
|
926
|
-
const failure = await buildServerFailureContext(context.projectRoot, server);
|
|
927
|
-
throw new CliError(`Rig server request failed: ${error instanceof Error ? error.message : String(error)}
|
|
928
|
-
${failure.contextLine}`, 1, { hint: failure.hint });
|
|
929
|
-
}
|
|
930
|
-
const text = await response.text();
|
|
931
|
-
const payload = text.trim().length > 0 ? (() => {
|
|
932
|
-
try {
|
|
933
|
-
return JSON.parse(text);
|
|
934
|
-
} catch {
|
|
935
|
-
return null;
|
|
936
|
-
}
|
|
937
|
-
})() : null;
|
|
938
|
-
if (!response.ok) {
|
|
939
|
-
const diagnostics = diagnosticMessage(payload);
|
|
940
|
-
const rawDetail = diagnostics ?? (text || response.statusText);
|
|
941
|
-
const detail = diagnostics ? rawDetail : rawDetail.split(`
|
|
942
|
-
`).map((line) => line.trim()).find((line) => line.length > 0)?.slice(0, 200) ?? response.statusText;
|
|
943
|
-
const failure = await buildServerFailureContext(context.projectRoot, server);
|
|
944
|
-
throw new CliError(`Rig server request failed (${response.status}): ${detail}
|
|
945
|
-
${failure.contextLine}`, 1, { hint: failure.hint });
|
|
946
|
-
}
|
|
947
|
-
return payload;
|
|
948
|
-
}
|
|
949
|
-
async function listWorkspaceTasksViaServer(context, filters = {}) {
|
|
950
|
-
const url = new URL("http://rig.local/api/workspace/tasks");
|
|
951
|
-
appendTaskFilterParams(url, filters);
|
|
952
|
-
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
953
|
-
if (!Array.isArray(payload)) {
|
|
954
|
-
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`." });
|
|
955
|
-
}
|
|
956
|
-
return payload.flatMap((entry) => entry && typeof entry === "object" && !Array.isArray(entry) ? [entry] : []);
|
|
957
|
-
}
|
|
958
|
-
async function getWorkspaceTaskViaServer(context, taskId) {
|
|
959
|
-
const payload = await requestServerJson(context, `/api/workspace/tasks/${encodeURIComponent(taskId)}`);
|
|
960
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
961
|
-
return null;
|
|
962
|
-
const task = payload.task;
|
|
963
|
-
return task && typeof task === "object" && !Array.isArray(task) ? task : null;
|
|
964
|
-
}
|
|
965
|
-
async function selectNextWorkspaceTaskViaServer(context, filters = {}) {
|
|
966
|
-
const url = new URL("http://rig.local/api/workspace/tasks/next");
|
|
967
|
-
appendTaskFilterParams(url, filters);
|
|
968
|
-
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
969
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
970
|
-
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." });
|
|
971
|
-
}
|
|
972
|
-
const record = payload;
|
|
973
|
-
const rawTask = record.task;
|
|
974
|
-
const task = rawTask && typeof rawTask === "object" && !Array.isArray(rawTask) ? rawTask : null;
|
|
975
|
-
const count = typeof record.count === "number" && Number.isFinite(record.count) ? record.count : task ? 1 : 0;
|
|
976
|
-
return { task, count };
|
|
977
|
-
}
|
|
978
|
-
async function getGitHubAuthStatusViaServer(context) {
|
|
979
|
-
const payload = await requestServerJson(context, "/api/github/auth/status");
|
|
980
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
981
|
-
}
|
|
982
|
-
async function postGitHubTokenViaServer(context, token, options = {}) {
|
|
983
|
-
const server = await ensureServerForCli(context.projectRoot);
|
|
984
|
-
const requestUrl = new URL(`${server.baseUrl}/api/github/auth/token`);
|
|
985
|
-
reportServerPhase("POST /api/github/auth/token\u2026");
|
|
986
|
-
let response;
|
|
987
|
-
try {
|
|
988
|
-
response = await fetch(requestUrl, {
|
|
989
|
-
method: "POST",
|
|
990
|
-
headers: { "content-type": "application/json" },
|
|
991
|
-
body: JSON.stringify({ token, selectedRepo: options.selectedRepo, projectRoot: options.projectRoot ?? server.serverProjectRoot ?? undefined })
|
|
992
|
-
});
|
|
993
|
-
} catch (error) {
|
|
994
|
-
const failure = await buildServerFailureContext(context.projectRoot, server);
|
|
995
|
-
throw new CliError(`Rig server auth bootstrap failed: ${error instanceof Error ? error.message : String(error)}
|
|
996
|
-
${failure.contextLine}`, 1, { hint: failure.hint });
|
|
997
|
-
}
|
|
998
|
-
const payload = await response.json().catch(() => null);
|
|
999
|
-
if (!response.ok) {
|
|
1000
|
-
const detail = payload && typeof payload === "object" && !Array.isArray(payload) ? String(payload.error ?? JSON.stringify(payload)) : `HTTP ${response.status}`;
|
|
1001
|
-
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`." });
|
|
1002
|
-
}
|
|
1003
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
1004
|
-
}
|
|
1005
|
-
async function prepareRemoteCheckoutViaServer(context, input) {
|
|
1006
|
-
const payload = await requestServerJson(context, `/api/projects/${encodeURIComponent(input.repoSlug)}/prepare-checkout`, {
|
|
1007
|
-
method: "POST",
|
|
1008
|
-
headers: { "content-type": "application/json" },
|
|
1009
|
-
body: JSON.stringify({ checkout: input.checkout, repoUrl: input.repoUrl, baseDir: input.baseDir })
|
|
1010
|
-
});
|
|
1011
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
1012
|
-
}
|
|
1013
|
-
async function registerProjectViaServer(context, input) {
|
|
1014
|
-
const payload = await requestServerJson(context, "/api/projects", {
|
|
1015
|
-
method: "POST",
|
|
1016
|
-
headers: { "content-type": "application/json" },
|
|
1017
|
-
body: JSON.stringify(input)
|
|
1018
|
-
});
|
|
1019
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
1020
|
-
}
|
|
1021
|
-
function sleep(ms) {
|
|
1022
|
-
return new Promise((resolve3) => setTimeout(resolve3, ms));
|
|
1023
|
-
}
|
|
1024
|
-
function isRetryableProjectRootSwitchError(error) {
|
|
1025
|
-
if (!(error instanceof Error))
|
|
1026
|
-
return false;
|
|
1027
|
-
const message = error.message.toLowerCase();
|
|
1028
|
-
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");
|
|
1029
|
-
}
|
|
1030
|
-
async function switchServerProjectRootViaServer(context, projectRoot, options = {}) {
|
|
1031
|
-
const timeoutMs = options.timeoutMs ?? 30000;
|
|
1032
|
-
const pollMs = options.pollMs ?? 1000;
|
|
1033
|
-
const deadline = Date.now() + timeoutMs;
|
|
1034
|
-
let lastError;
|
|
1035
|
-
let switched = null;
|
|
1036
|
-
while (Date.now() < deadline) {
|
|
1037
|
-
try {
|
|
1038
|
-
switched = await requestServerJson(context, "/api/server/project-root", {
|
|
1039
|
-
method: "POST",
|
|
1040
|
-
headers: { "content-type": "application/json" },
|
|
1041
|
-
body: JSON.stringify({ projectRoot })
|
|
1042
|
-
});
|
|
1043
|
-
break;
|
|
1044
|
-
} catch (error) {
|
|
1045
|
-
lastError = error;
|
|
1046
|
-
if (!isRetryableProjectRootSwitchError(error))
|
|
1047
|
-
throw error;
|
|
1048
|
-
await sleep(pollMs);
|
|
1049
|
-
}
|
|
1050
|
-
}
|
|
1051
|
-
if (!switched) {
|
|
1052
|
-
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);
|
|
1053
|
-
}
|
|
1054
|
-
const record = switched && typeof switched === "object" && !Array.isArray(switched) ? switched : {};
|
|
1055
|
-
if (record.ok === true) {
|
|
1056
|
-
writeRepoServerProjectRoot(context.projectRoot, projectRoot);
|
|
1057
|
-
return { ok: true, switched: record };
|
|
1058
|
-
}
|
|
1059
|
-
throw new CliError(`Rig server rejected project-root scope ${projectRoot}: ${String(record.message ?? record.error ?? "unknown error")}`, 1);
|
|
1060
|
-
}
|
|
1061
|
-
async function listRunsViaServer(context, options = {}) {
|
|
1062
|
-
const url = new URL("http://rig.local/api/runs");
|
|
1063
|
-
if (options.limit !== undefined)
|
|
1064
|
-
url.searchParams.set("limit", String(options.limit));
|
|
1065
|
-
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
1066
|
-
const runs = Array.isArray(payload) ? payload : payload && typeof payload === "object" && !Array.isArray(payload) && Array.isArray(payload.runs) ? payload.runs : [];
|
|
1067
|
-
return runs.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry)));
|
|
1068
|
-
}
|
|
1069
|
-
async function getRunDetailsViaServer(context, runId) {
|
|
1070
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}`);
|
|
1071
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
1072
|
-
}
|
|
1073
|
-
async function getRunLogsViaServer(context, runId, options = {}) {
|
|
1074
|
-
const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/logs`);
|
|
1075
|
-
if (options.limit !== undefined)
|
|
1076
|
-
url.searchParams.set("limit", String(options.limit));
|
|
1077
|
-
if (options.cursor)
|
|
1078
|
-
url.searchParams.set("cursor", options.cursor);
|
|
1079
|
-
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
1080
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
|
|
1081
|
-
}
|
|
1082
|
-
async function getRunTimelineViaServer(context, runId, options = {}) {
|
|
1083
|
-
const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/timeline`);
|
|
1084
|
-
if (options.limit !== undefined)
|
|
1085
|
-
url.searchParams.set("limit", String(options.limit));
|
|
1086
|
-
if (options.cursor)
|
|
1087
|
-
url.searchParams.set("cursor", options.cursor);
|
|
1088
|
-
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
1089
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
|
|
1090
|
-
}
|
|
1091
|
-
async function ensureTaskLabelsViaServer(context) {
|
|
1092
|
-
const payload = await requestServerJson(context, "/api/workspace/task-labels", { method: "POST" });
|
|
1093
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
1094
|
-
}
|
|
1095
|
-
async function listGitHubProjectsViaServer(context, owner) {
|
|
1096
|
-
const url = new URL("http://rig.local/api/github/projects");
|
|
1097
|
-
url.searchParams.set("owner", owner);
|
|
1098
|
-
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
1099
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { projects: [] };
|
|
1100
|
-
}
|
|
1101
|
-
async function getGitHubProjectStatusFieldViaServer(context, projectId) {
|
|
1102
|
-
const payload = await requestServerJson(context, `/api/github/projects/${encodeURIComponent(projectId)}/status-field`);
|
|
1103
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
1104
|
-
}
|
|
1105
|
-
async function updateWorkspaceTaskViaServer(context, input) {
|
|
1106
|
-
const payload = await requestServerJson(context, "/api/tasks/update", {
|
|
1107
|
-
method: "POST",
|
|
1108
|
-
headers: { "content-type": "application/json" },
|
|
1109
|
-
body: JSON.stringify(input)
|
|
1110
|
-
});
|
|
1111
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
|
|
1112
|
-
}
|
|
1113
|
-
async function resumeRunViaServer(context, runId, options) {
|
|
1114
|
-
let targetRunId = runId?.trim() || null;
|
|
1115
|
-
if (!targetRunId) {
|
|
1116
|
-
const candidates = (await listRunsViaServer(context)).filter((run) => RESUMABLE_RUN_STATUSES.has(String(run.status ?? ""))).sort((left, right) => String(right.updatedAt ?? "").localeCompare(String(left.updatedAt ?? "")));
|
|
1117
|
-
targetRunId = typeof candidates[0]?.runId === "string" ? candidates[0].runId : null;
|
|
1118
|
-
}
|
|
1119
|
-
if (!targetRunId) {
|
|
1120
|
-
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>`." });
|
|
1121
|
-
}
|
|
1122
|
-
const payload = await requestServerJson(context, "/api/runs/resume", {
|
|
1123
|
-
method: "POST",
|
|
1124
|
-
headers: { "content-type": "application/json" },
|
|
1125
|
-
body: JSON.stringify({ runId: targetRunId, createdAt: new Date().toISOString(), restart: options.restart })
|
|
1126
|
-
});
|
|
1127
|
-
const record = payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
1128
|
-
if (record.ok === false) {
|
|
1129
|
-
const message = typeof record.error === "string" && record.error.trim() ? record.error : "run resume failed";
|
|
1130
|
-
throw new CliError(`${options.restart ? "restart" : "resume"} failed for ${targetRunId}: ${message}`, 1);
|
|
1131
|
-
}
|
|
1132
|
-
return { ok: true, runId: targetRunId, ...record };
|
|
1133
|
-
}
|
|
1134
|
-
async function resolveServerConnectionLabel(projectRoot) {
|
|
1135
|
-
try {
|
|
1136
|
-
const selected = resolveSelectedConnection(projectRoot);
|
|
1137
|
-
if (!selected)
|
|
1138
|
-
return "no server selected";
|
|
1139
|
-
if (selected.connection.kind === "remote") {
|
|
1140
|
-
return selected.connection.baseUrl.replace(/^https?:\/\//, "");
|
|
1141
|
-
}
|
|
1142
|
-
return `local (${selected.alias})`;
|
|
1143
|
-
} catch {
|
|
1144
|
-
return "no server selected";
|
|
1145
|
-
}
|
|
1146
|
-
}
|
|
1147
|
-
async function stopRunViaServer(context, runId) {
|
|
1148
|
-
const payload = await requestServerJson(context, "/api/runs/stop", {
|
|
1149
|
-
method: "POST",
|
|
1150
|
-
headers: { "content-type": "application/json" },
|
|
1151
|
-
body: JSON.stringify({ runId })
|
|
1152
|
-
});
|
|
1153
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true, runId };
|
|
1154
|
-
}
|
|
1155
|
-
async function steerRunViaServer(context, runId, message) {
|
|
1156
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/steer`, {
|
|
1157
|
-
method: "POST",
|
|
1158
|
-
headers: { "content-type": "application/json" },
|
|
1159
|
-
body: JSON.stringify({ message })
|
|
1160
|
-
});
|
|
1161
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
|
|
1162
|
-
}
|
|
1163
|
-
async function getRunPiSessionViaServer(context, runId) {
|
|
1164
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi`);
|
|
1165
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
1166
|
-
}
|
|
1167
|
-
async function getRunPiMessagesViaServer(context, runId) {
|
|
1168
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/messages`);
|
|
1169
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { messages: [] };
|
|
1170
|
-
}
|
|
1171
|
-
async function getRunPiStatusViaServer(context, runId) {
|
|
1172
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/status`);
|
|
1173
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
1174
|
-
}
|
|
1175
|
-
async function getRunPiCommandsViaServer(context, runId) {
|
|
1176
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands`);
|
|
1177
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { commands: [] };
|
|
1178
|
-
}
|
|
1179
|
-
async function getRunPiCapabilitiesViaServer(context, runId) {
|
|
1180
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/capabilities`);
|
|
1181
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { capabilities: null };
|
|
1182
|
-
}
|
|
1183
|
-
async function sendRunPiPromptViaServer(context, runId, text, streamingBehavior) {
|
|
1184
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/prompt`, {
|
|
1185
|
-
method: "POST",
|
|
1186
|
-
headers: { "content-type": "application/json" },
|
|
1187
|
-
body: JSON.stringify({ text, streamingBehavior })
|
|
1188
|
-
});
|
|
1189
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
1190
|
-
}
|
|
1191
|
-
async function sendRunPiShellViaServer(context, runId, text) {
|
|
1192
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/shell`, {
|
|
1193
|
-
method: "POST",
|
|
1194
|
-
headers: { "content-type": "application/json" },
|
|
1195
|
-
body: JSON.stringify({ text })
|
|
1196
|
-
});
|
|
1197
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
1198
|
-
}
|
|
1199
|
-
async function runRunPiCommandViaServer(context, runId, text) {
|
|
1200
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands/run`, {
|
|
1201
|
-
method: "POST",
|
|
1202
|
-
headers: { "content-type": "application/json" },
|
|
1203
|
-
body: JSON.stringify({ text })
|
|
1204
|
-
});
|
|
1205
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { type: "done" };
|
|
1206
|
-
}
|
|
1207
|
-
async function respondRunPiExtensionUiViaServer(context, runId, requestId, valueOrCancel) {
|
|
1208
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/extension-ui/respond`, {
|
|
1209
|
-
method: "POST",
|
|
1210
|
-
headers: { "content-type": "application/json" },
|
|
1211
|
-
body: JSON.stringify({ requestId, ...valueOrCancel })
|
|
1212
|
-
});
|
|
1213
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
1214
|
-
}
|
|
1215
|
-
async function abortRunPiViaServer(context, runId) {
|
|
1216
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/abort`, { method: "POST" });
|
|
1217
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { aborted: true };
|
|
1218
|
-
}
|
|
1219
|
-
async function buildRunPiEventsWebSocketUrl(context, runId) {
|
|
1220
|
-
const server = await ensureServerForCli(context.projectRoot);
|
|
1221
|
-
const url = new URL(`${server.baseUrl.replace(/\/+$/, "")}/api/runs/${encodeURIComponent(runId)}/pi/events`);
|
|
1222
|
-
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
1223
|
-
if (server.authToken)
|
|
1224
|
-
url.searchParams.set("token", server.authToken);
|
|
1225
|
-
if (server.serverProjectRoot)
|
|
1226
|
-
url.searchParams.set("rigProjectRoot", server.serverProjectRoot);
|
|
1227
|
-
return url.toString();
|
|
1228
|
-
}
|
|
1229
|
-
async function submitTaskRunViaServer(context, input) {
|
|
1230
|
-
const isTaskRun = Boolean(input.taskId);
|
|
1231
|
-
const endpoint = isTaskRun ? "/api/runs/task" : "/api/runs/adhoc";
|
|
1232
|
-
const payload = await requestServerJson(context, endpoint, {
|
|
1233
|
-
method: "POST",
|
|
1234
|
-
headers: {
|
|
1235
|
-
"content-type": "application/json"
|
|
1236
|
-
},
|
|
1237
|
-
body: JSON.stringify({
|
|
1238
|
-
runId: input.runId,
|
|
1239
|
-
taskId: input.taskId,
|
|
1240
|
-
title: input.title,
|
|
1241
|
-
runtimeAdapter: input.runtimeAdapter,
|
|
1242
|
-
model: input.model,
|
|
1243
|
-
runtimeMode: input.runtimeMode,
|
|
1244
|
-
interactionMode: input.interactionMode,
|
|
1245
|
-
initialPrompt: input.initialPrompt,
|
|
1246
|
-
baselineMode: input.baselineMode,
|
|
1247
|
-
prMode: input.prMode,
|
|
1248
|
-
executionTarget: "local"
|
|
1249
|
-
})
|
|
1250
|
-
});
|
|
1251
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
1252
|
-
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." });
|
|
1253
|
-
}
|
|
1254
|
-
const runId = payload.runId;
|
|
1255
|
-
if (typeof runId !== "string" || runId.trim().length === 0) {
|
|
1256
|
-
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." });
|
|
1257
|
-
}
|
|
1258
|
-
return { runId };
|
|
1259
|
-
}
|
|
1260
|
-
var scopedGitHubBearerTokens, serverPhaseListener = null, serverReachabilityCache, RESUMABLE_RUN_STATUSES;
|
|
1261
|
-
var init__server_client = __esm(() => {
|
|
1262
|
-
init_runner();
|
|
1263
|
-
init__connection_state();
|
|
1264
|
-
scopedGitHubBearerTokens = new Map;
|
|
1265
|
-
serverReachabilityCache = new Map;
|
|
1266
|
-
RESUMABLE_RUN_STATUSES = new Set([
|
|
1267
|
-
"created",
|
|
1268
|
-
"preparing",
|
|
1269
|
-
"running",
|
|
1270
|
-
"validating",
|
|
1271
|
-
"reviewing",
|
|
1272
|
-
"stopped",
|
|
1273
|
-
"failed",
|
|
1274
|
-
"needs-attention",
|
|
1275
|
-
"needs_attention"
|
|
1276
|
-
]);
|
|
1277
|
-
});
|
|
1278
|
-
|
|
1279
|
-
// packages/cli/src/commands/_spinner.ts
|
|
1280
|
-
function createTtySpinner(input) {
|
|
1281
|
-
const output = input.output ?? process.stdout;
|
|
1282
|
-
const isTty = output.isTTY === true;
|
|
1283
|
-
const frames = input.frames && input.frames.length > 0 ? input.frames : SPINNER_FRAMES;
|
|
1284
|
-
let label = input.label;
|
|
1285
|
-
let frame = 0;
|
|
1286
|
-
let paused = false;
|
|
1287
|
-
let stopped = false;
|
|
1288
|
-
let lastPrintedLabel = "";
|
|
1289
|
-
const render = () => {
|
|
1290
|
-
if (stopped || paused)
|
|
1291
|
-
return;
|
|
1292
|
-
if (!isTty) {
|
|
1293
|
-
if (label !== lastPrintedLabel) {
|
|
1294
|
-
output.write(`${label}
|
|
1295
|
-
`);
|
|
1296
|
-
lastPrintedLabel = label;
|
|
1297
|
-
}
|
|
1298
|
-
return;
|
|
1299
|
-
}
|
|
1300
|
-
frame = (frame + 1) % frames.length;
|
|
1301
|
-
const glyph = frames[frame] ?? frames[0] ?? "";
|
|
1302
|
-
output.write(`\r\x1B[2K${input.styleFrame ? input.styleFrame(glyph) : glyph} ${label}`);
|
|
1303
|
-
};
|
|
1304
|
-
const clearLine = () => {
|
|
1305
|
-
if (isTty)
|
|
1306
|
-
output.write("\r\x1B[2K");
|
|
1307
|
-
};
|
|
1308
|
-
render();
|
|
1309
|
-
const timer = isTty ? setInterval(render, input.intervalMs ?? 16) : null;
|
|
1310
|
-
return {
|
|
1311
|
-
setLabel(next) {
|
|
1312
|
-
label = next;
|
|
1313
|
-
render();
|
|
1314
|
-
},
|
|
1315
|
-
pause() {
|
|
1316
|
-
paused = true;
|
|
1317
|
-
clearLine();
|
|
1318
|
-
},
|
|
1319
|
-
resume() {
|
|
1320
|
-
if (stopped)
|
|
1321
|
-
return;
|
|
1322
|
-
paused = false;
|
|
1323
|
-
render();
|
|
1324
|
-
},
|
|
1325
|
-
stop(finalLine) {
|
|
1326
|
-
if (stopped)
|
|
1327
|
-
return;
|
|
1328
|
-
stopped = true;
|
|
1329
|
-
if (timer)
|
|
1330
|
-
clearInterval(timer);
|
|
1331
|
-
clearLine();
|
|
1332
|
-
if (finalLine)
|
|
1333
|
-
output.write(`${finalLine}
|
|
1334
|
-
`);
|
|
1335
|
-
}
|
|
1336
|
-
};
|
|
1337
|
-
}
|
|
1338
|
-
var SPINNER_FRAMES;
|
|
1339
|
-
var init__spinner = __esm(() => {
|
|
1340
|
-
SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
|
|
1341
|
-
});
|
|
1342
|
-
|
|
1343
|
-
// packages/cli/src/app/theme.ts
|
|
1344
|
-
function hexToRgb(hex) {
|
|
1345
|
-
const value = hex.replace("#", "");
|
|
1346
|
-
return [
|
|
1347
|
-
Number.parseInt(value.slice(0, 2), 16),
|
|
1348
|
-
Number.parseInt(value.slice(2, 4), 16),
|
|
1349
|
-
Number.parseInt(value.slice(4, 6), 16)
|
|
1350
|
-
];
|
|
1351
|
-
}
|
|
1352
|
-
function fg(hex) {
|
|
1353
|
-
const [r, g, b] = hexToRgb(hex);
|
|
1354
|
-
return (text) => `\x1B[38;2;${r};${g};${b}m${text}\x1B[39m`;
|
|
1355
|
-
}
|
|
1356
|
-
function bold(text) {
|
|
1357
|
-
return `\x1B[1m${text}\x1B[22m`;
|
|
1358
|
-
}
|
|
1359
|
-
function microDroneFrame(tick) {
|
|
1360
|
-
const blade = MICRO_BLADES[tick % MICRO_BLADES.length];
|
|
1361
|
-
const eye = EYE_FRAMES[Math.floor(tick / 2) % EYE_FRAMES.length];
|
|
1362
|
-
return `(${blade})${eye}(${blade})`;
|
|
1363
|
-
}
|
|
1364
|
-
function renderMicroDroneFrame(tick) {
|
|
1365
|
-
const blade = MICRO_BLADES[tick % MICRO_BLADES.length];
|
|
1366
|
-
const eye = EYE_FRAMES[Math.floor(tick / 2) % EYE_FRAMES.length];
|
|
1367
|
-
return `${ink4("(")}${cyan(blade)}${ink4(")")}${bold(accent(eye))}${ink4("(")}${cyan(blade)}${ink4(")")}`;
|
|
1368
|
-
}
|
|
1369
|
-
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;
|
|
1370
|
-
var init_theme = __esm(() => {
|
|
1371
|
-
RIG_PALETTE = {
|
|
1372
|
-
ink: "#f2f3f6",
|
|
1373
|
-
ink2: "#aeb0ba",
|
|
1374
|
-
ink3: "#6c6e79",
|
|
1375
|
-
ink4: "#44464f",
|
|
1376
|
-
accent: "#ccff4d",
|
|
1377
|
-
accentDim: "#a9d63f",
|
|
1378
|
-
cyan: "#56d8ff",
|
|
1379
|
-
red: "#ff5d5d",
|
|
1380
|
-
yellow: "#ffd24d"
|
|
1381
|
-
};
|
|
1382
|
-
ink = fg(RIG_PALETTE.ink);
|
|
1383
|
-
ink2 = fg(RIG_PALETTE.ink2);
|
|
1384
|
-
ink3 = fg(RIG_PALETTE.ink3);
|
|
1385
|
-
ink4 = fg(RIG_PALETTE.ink4);
|
|
1386
|
-
accent = fg(RIG_PALETTE.accent);
|
|
1387
|
-
accentDim = fg(RIG_PALETTE.accentDim);
|
|
1388
|
-
cyan = fg(RIG_PALETTE.cyan);
|
|
1389
|
-
red = fg(RIG_PALETTE.red);
|
|
1390
|
-
yellow = fg(RIG_PALETTE.yellow);
|
|
1391
|
-
DRONE_ART = [
|
|
1392
|
-
" .-=-. .-=-. ",
|
|
1393
|
-
" ( !!! ) ( !!! ) ",
|
|
1394
|
-
" '-=-'._ _.'-=-' ",
|
|
1395
|
-
" '._ _.' ",
|
|
1396
|
-
" '=$$$$$$$=.' ",
|
|
1397
|
-
" =$$$$$$$$$$$= ",
|
|
1398
|
-
" $$$@@@@@@@@@@$$$ ",
|
|
1399
|
-
" $$$@@ @@$$$ ",
|
|
1400
|
-
" $$@ ? @$$$ ",
|
|
1401
|
-
" $$$@ '-' @$$$ ",
|
|
1402
|
-
" $$$@@ @@$$$ ",
|
|
1403
|
-
" $$$@@@@@@@@@@$$$ ",
|
|
1404
|
-
" =$$$$$$$$$$$= ",
|
|
1405
|
-
" '=$$$$$$$=.' ",
|
|
1406
|
-
" _.' '._ ",
|
|
1407
|
-
" .-=-.' '.-=-. ",
|
|
1408
|
-
" ( !!! ) ( !!! ) ",
|
|
1409
|
-
" '-=-' '-=-' "
|
|
1410
|
-
];
|
|
1411
|
-
EYE_FRAMES = ["@", "o", "."];
|
|
1412
|
-
DRONE_WIDTH = DRONE_ART[0].length;
|
|
1413
|
-
DRONE_HEIGHT = DRONE_ART.length;
|
|
1414
|
-
MICRO_BLADES = ["---", "\\\\\\", "|||", "///"];
|
|
1415
|
-
MICRO_DRONE_FRAMES = Array.from({ length: 12 }, (_, index) => microDroneFrame(index));
|
|
1416
|
-
});
|
|
1417
|
-
|
|
1418
|
-
// packages/cli/src/commands/_async-ui.ts
|
|
1419
|
-
import pc from "picocolors";
|
|
1420
|
-
async function withSpinner(label, work, options = {}) {
|
|
1421
|
-
if (options.outputMode === "json") {
|
|
1422
|
-
return work(() => {});
|
|
1423
|
-
}
|
|
1424
|
-
if (activeUpdate) {
|
|
1425
|
-
const outer = activeUpdate;
|
|
1426
|
-
outer(label);
|
|
1427
|
-
return work(outer);
|
|
1428
|
-
}
|
|
1429
|
-
const output = options.output ?? process.stderr;
|
|
1430
|
-
const isTty = output.isTTY === true;
|
|
1431
|
-
let lastLabel = label;
|
|
1432
|
-
if (!isTty) {
|
|
1433
|
-
output.write(`${label}
|
|
1434
|
-
`);
|
|
1435
|
-
const update2 = (next) => {
|
|
1436
|
-
lastLabel = next;
|
|
1437
|
-
};
|
|
1438
|
-
activeUpdate = update2;
|
|
1439
|
-
const previousListener2 = setServerPhaseListener(update2);
|
|
1440
|
-
try {
|
|
1441
|
-
return await work(update2);
|
|
1442
|
-
} finally {
|
|
1443
|
-
activeUpdate = null;
|
|
1444
|
-
setServerPhaseListener(previousListener2);
|
|
1445
|
-
}
|
|
1446
|
-
}
|
|
1447
|
-
const spinner = createTtySpinner({
|
|
1448
|
-
label,
|
|
1449
|
-
output,
|
|
1450
|
-
frames: MICRO_DRONE_FRAMES,
|
|
1451
|
-
styleFrame: (frame) => renderMicroDroneFrame(Math.max(0, MICRO_DRONE_FRAMES.indexOf(frame)))
|
|
1452
|
-
});
|
|
1453
|
-
const update = (next) => {
|
|
1454
|
-
lastLabel = next;
|
|
1455
|
-
spinner.setLabel(next);
|
|
1456
|
-
};
|
|
1457
|
-
activeUpdate = update;
|
|
1458
|
-
const previousListener = setServerPhaseListener(update);
|
|
1459
|
-
try {
|
|
1460
|
-
const result = await work(update);
|
|
1461
|
-
spinner.stop(options.doneLabel ? `${DONE_SYMBOL} ${options.doneLabel}` : undefined);
|
|
1462
|
-
return result;
|
|
1463
|
-
} catch (error) {
|
|
1464
|
-
spinner.stop(`${FAIL_SYMBOL} ${lastLabel}`);
|
|
1465
|
-
throw error;
|
|
1466
|
-
} finally {
|
|
1467
|
-
activeUpdate = null;
|
|
1468
|
-
setServerPhaseListener(previousListener);
|
|
1469
|
-
}
|
|
1470
|
-
}
|
|
1471
|
-
var DONE_SYMBOL, FAIL_SYMBOL, activeUpdate = null;
|
|
1472
|
-
var init__async_ui = __esm(() => {
|
|
1473
|
-
init__spinner();
|
|
1474
|
-
init__server_client();
|
|
1475
|
-
init_theme();
|
|
1476
|
-
DONE_SYMBOL = pc.green("\u25C7");
|
|
1477
|
-
FAIL_SYMBOL = pc.red("\u25A0");
|
|
1478
|
-
});
|
|
1479
|
-
|
|
1480
|
-
// packages/cli/src/commands/_pi-frontend.ts
|
|
1481
|
-
var exports__pi_frontend = {};
|
|
1482
|
-
__export(exports__pi_frontend, {
|
|
1483
|
-
shouldRequireOperatorTranscript: () => shouldRequireOperatorTranscript,
|
|
1484
|
-
runWithProcessExitGuard: () => runWithProcessExitGuard,
|
|
1485
|
-
missingOperatorTranscriptMessage: () => missingOperatorTranscriptMessage,
|
|
1486
|
-
buildOperatorPiEnv: () => buildOperatorPiEnv,
|
|
1487
|
-
attachRunBundledPiFrontend: () => attachRunBundledPiFrontend
|
|
1488
|
-
});
|
|
1489
|
-
import { existsSync as existsSync3, mkdirSync as mkdirSync3, mkdtempSync, readFileSync as readFileSync3, rmSync, writeFileSync as writeFileSync3 } from "fs";
|
|
1490
|
-
import { homedir as homedir2, tmpdir } from "os";
|
|
1491
|
-
import { join } from "path";
|
|
1492
|
-
import { main as runPiMain } from "@earendil-works/pi-coding-agent";
|
|
1493
|
-
import createPiRigExtension from "@rig/pi-rig";
|
|
1494
|
-
function setTemporaryEnv(updates) {
|
|
1495
|
-
const previous = new Map;
|
|
1496
|
-
for (const [key, value] of Object.entries(updates)) {
|
|
1497
|
-
previous.set(key, process.env[key]);
|
|
1498
|
-
process.env[key] = value;
|
|
1499
|
-
}
|
|
1500
|
-
return () => {
|
|
1501
|
-
for (const [key, value] of previous) {
|
|
1502
|
-
if (value === undefined)
|
|
1503
|
-
delete process.env[key];
|
|
1504
|
-
else
|
|
1505
|
-
process.env[key] = value;
|
|
1506
|
-
}
|
|
1507
|
-
};
|
|
1508
|
-
}
|
|
1509
|
-
function buildOperatorPiEnv(input) {
|
|
1510
|
-
return {
|
|
1511
|
-
PI_CODING_AGENT_SESSION_DIR: input.sessionDir,
|
|
1512
|
-
PI_SKIP_VERSION_CHECK: "1",
|
|
1513
|
-
PI_HIDDEN_COMMANDS: "import,fork,clone,tree,new,resume,trust",
|
|
1514
|
-
RIG_PI_OPERATOR_SESSION: "1",
|
|
1515
|
-
RIG_RUN_ID: input.runId,
|
|
1516
|
-
RIG_SERVER_URL: input.serverUrl,
|
|
1517
|
-
...input.authToken ? { RIG_AUTH_TOKEN: input.authToken } : {},
|
|
1518
|
-
...input.serverProjectRoot ? { RIG_PROJECT_ROOT: input.serverProjectRoot } : {}
|
|
1519
|
-
};
|
|
1520
|
-
}
|
|
1521
|
-
function shouldRequireOperatorTranscript(status) {
|
|
1522
|
-
return typeof status === "string" && TERMINAL_RUN_STATUSES.has(status.trim().toLowerCase());
|
|
1523
|
-
}
|
|
1524
|
-
function missingOperatorTranscriptMessage(runId, status) {
|
|
1525
|
-
const shortRun = runId.trim().slice(0, 8) || "unknown";
|
|
1526
|
-
const statusText = typeof status === "string" && status.trim() ? status.trim() : "terminal";
|
|
1527
|
-
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.`;
|
|
1528
|
-
}
|
|
1529
|
-
function statusFromRunDetails(run) {
|
|
1530
|
-
if (!run || typeof run !== "object" || Array.isArray(run))
|
|
1531
|
-
return;
|
|
1532
|
-
const record = run;
|
|
1533
|
-
if (typeof record.status === "string")
|
|
1534
|
-
return record.status;
|
|
1535
|
-
const nested = record.run;
|
|
1536
|
-
return nested && typeof nested === "object" && !Array.isArray(nested) ? nested.status : undefined;
|
|
1537
|
-
}
|
|
1538
|
-
async function prepareOperatorConsole(context, runId, tempSessionDir) {
|
|
1539
|
-
const server = await ensureServerForCli(context.projectRoot);
|
|
1540
|
-
const localCwd = join(homedir2(), ".rig", "drones", runId.slice(0, 8));
|
|
1541
|
-
mkdirSync3(localCwd, { recursive: true });
|
|
1542
|
-
trustDroneCwd(localCwd);
|
|
1543
|
-
installRigPiTheme();
|
|
1544
|
-
let sessionFileArg = [];
|
|
1545
|
-
try {
|
|
1546
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/session-file`);
|
|
1547
|
-
if (payload?.ok && typeof payload.content === "string" && payload.content.trim()) {
|
|
1548
|
-
const fileName = typeof payload.fileName === "string" && payload.fileName.trim() ? payload.fileName.replace(/[^A-Za-z0-9._-]/g, "_") : `rig-run-${runId}.jsonl`;
|
|
1549
|
-
const localSessionPath = join(tempSessionDir, fileName);
|
|
1550
|
-
const content = payload.content.split(`
|
|
1551
|
-
`).map((line, index) => {
|
|
1552
|
-
if (index > 0 || !line.trim())
|
|
1553
|
-
return line;
|
|
1554
|
-
try {
|
|
1555
|
-
const header = JSON.parse(line);
|
|
1556
|
-
if (header.type === "session" && typeof header.cwd === "string") {
|
|
1557
|
-
return JSON.stringify({ ...header, cwd: localCwd });
|
|
1558
|
-
}
|
|
1559
|
-
} catch {}
|
|
1560
|
-
return line;
|
|
1561
|
-
}).join(`
|
|
1562
|
-
`);
|
|
1563
|
-
writeFileSync3(localSessionPath, content);
|
|
1564
|
-
sessionFileArg = ["--session", localSessionPath];
|
|
1565
|
-
}
|
|
1566
|
-
} catch {}
|
|
1567
|
-
if (sessionFileArg.length === 0) {
|
|
1568
|
-
const run = await getRunDetailsViaServer(context, runId).catch(() => null);
|
|
1569
|
-
const status = statusFromRunDetails(run);
|
|
1570
|
-
if (shouldRequireOperatorTranscript(status)) {
|
|
1571
|
-
throw new OperatorTranscriptUnavailableError(missingOperatorTranscriptMessage(runId, status));
|
|
1572
|
-
}
|
|
1573
|
-
}
|
|
1574
|
-
return { server, sessionFileArg };
|
|
1575
|
-
}
|
|
1576
|
-
function trustDroneCwd(localCwd) {
|
|
1577
|
-
try {
|
|
1578
|
-
const agentDir = join(homedir2(), ".pi", "agent");
|
|
1579
|
-
mkdirSync3(agentDir, { recursive: true });
|
|
1580
|
-
const trustPath = join(agentDir, "trust.json");
|
|
1581
|
-
const store = existsSync3(trustPath) ? JSON.parse(readFileSync3(trustPath, "utf8")) : {};
|
|
1582
|
-
if (store[localCwd] !== true) {
|
|
1583
|
-
store[localCwd] = true;
|
|
1584
|
-
writeFileSync3(trustPath, `${JSON.stringify(store, null, "\t")}
|
|
1585
|
-
`);
|
|
1586
|
-
}
|
|
1587
|
-
} catch {}
|
|
1588
|
-
}
|
|
1589
|
-
function installRigPiTheme() {
|
|
1590
|
-
try {
|
|
1591
|
-
const themesDir = join(homedir2(), ".pi", "agent", "themes");
|
|
1592
|
-
mkdirSync3(themesDir, { recursive: true });
|
|
1593
|
-
const themePath = join(themesDir, "rig.json");
|
|
1594
|
-
const next = `${JSON.stringify(RIG_PI_THEME, null, "\t")}
|
|
1595
|
-
`;
|
|
1596
|
-
if (!existsSync3(themePath) || readFileSync3(themePath, "utf8") !== next) {
|
|
1597
|
-
writeFileSync3(themePath, next);
|
|
1598
|
-
}
|
|
1599
|
-
} catch {}
|
|
1600
|
-
}
|
|
1601
|
-
async function runWithProcessExitGuard(body) {
|
|
1602
|
-
const realExit = process.exit;
|
|
1603
|
-
let exitCode = 0;
|
|
1604
|
-
let signalQuit = () => {};
|
|
1605
|
-
const quit = new Promise((resolve3) => {
|
|
1606
|
-
signalQuit = resolve3;
|
|
1607
|
-
});
|
|
1608
|
-
const guardedExit = (code) => {
|
|
1609
|
-
exitCode = typeof code === "number" ? code : 0;
|
|
1610
|
-
signalQuit();
|
|
1611
|
-
return;
|
|
1612
|
-
};
|
|
1613
|
-
process.exit = guardedExit;
|
|
1614
|
-
try {
|
|
1615
|
-
await Promise.race([Promise.resolve().then(body), quit]);
|
|
1616
|
-
} finally {
|
|
1617
|
-
process.exit = realExit;
|
|
1618
|
-
}
|
|
1619
|
-
return exitCode;
|
|
1620
|
-
}
|
|
1621
|
-
function runPiMainReturningOnQuit(args, options) {
|
|
1622
|
-
return runWithProcessExitGuard(() => runPiMain(args, options));
|
|
1623
|
-
}
|
|
1624
|
-
async function attachRunBundledPiFrontend(context, input) {
|
|
1625
|
-
const tempSessionDir = mkdtempSync(join(tmpdir(), "rig-pi-frontend-sessions-"));
|
|
1626
|
-
const { server, sessionFileArg } = await withSpinner(`Opening Pi console for run ${input.runId}\u2026`, () => prepareOperatorConsole(context, input.runId, tempSessionDir), { outputMode: context.outputMode });
|
|
1627
|
-
const restoreEnv = setTemporaryEnv(buildOperatorPiEnv({
|
|
1628
|
-
runId: input.runId,
|
|
1629
|
-
serverUrl: server.baseUrl,
|
|
1630
|
-
authToken: server.authToken,
|
|
1631
|
-
serverProjectRoot: server.serverProjectRoot,
|
|
1632
|
-
sessionDir: tempSessionDir
|
|
1633
|
-
}));
|
|
1634
|
-
const piRigExtensionFactory = (pi) => {
|
|
1635
|
-
createPiRigExtension(pi);
|
|
1636
|
-
};
|
|
1637
|
-
let detached = false;
|
|
1638
|
-
try {
|
|
1639
|
-
const piArgs = [
|
|
1640
|
-
"--offline",
|
|
1641
|
-
"--no-extensions",
|
|
1642
|
-
"--no-skills",
|
|
1643
|
-
"--no-prompt-templates",
|
|
1644
|
-
"--no-context-files",
|
|
1645
|
-
...sessionFileArg
|
|
1646
|
-
];
|
|
1647
|
-
const piOptions = { extensionFactories: [piRigExtensionFactory] };
|
|
1648
|
-
if (input.returnOnQuit) {
|
|
1649
|
-
await runPiMainReturningOnQuit(piArgs, piOptions);
|
|
1650
|
-
} else {
|
|
1651
|
-
await runPiMain(piArgs, piOptions);
|
|
1652
|
-
}
|
|
1653
|
-
detached = true;
|
|
1654
|
-
} finally {
|
|
1655
|
-
restoreEnv();
|
|
1656
|
-
rmSync(tempSessionDir, { recursive: true, force: true });
|
|
1657
|
-
}
|
|
1658
|
-
let run = { runId: input.runId, status: "unknown" };
|
|
1659
|
-
try {
|
|
1660
|
-
run = await getRunDetailsViaServer(context, input.runId);
|
|
1661
|
-
} catch {}
|
|
1662
|
-
return {
|
|
1663
|
-
run,
|
|
1664
|
-
logs: [],
|
|
1665
|
-
timeline: [],
|
|
1666
|
-
timelineCursor: null,
|
|
1667
|
-
steered: input.steered === true,
|
|
1668
|
-
detached,
|
|
1669
|
-
rendered: "stock Pi operator console with the pi-rig extension"
|
|
1670
|
-
};
|
|
1671
|
-
}
|
|
1672
|
-
var TERMINAL_RUN_STATUSES, OperatorTranscriptUnavailableError, RIG_PI_THEME;
|
|
1673
|
-
var init__pi_frontend = __esm(() => {
|
|
1674
|
-
init__server_client();
|
|
1675
|
-
init__async_ui();
|
|
1676
|
-
TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
|
|
1677
|
-
OperatorTranscriptUnavailableError = class OperatorTranscriptUnavailableError extends Error {
|
|
1678
|
-
constructor(message) {
|
|
1679
|
-
super(message);
|
|
1680
|
-
this.name = "OperatorTranscriptUnavailableError";
|
|
1681
|
-
}
|
|
1682
|
-
};
|
|
1683
|
-
RIG_PI_THEME = {
|
|
1684
|
-
$schema: "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json",
|
|
1685
|
-
name: "rig",
|
|
1686
|
-
vars: {
|
|
1687
|
-
acid: "#ccff4d",
|
|
1688
|
-
acidDim: "#a9d63f",
|
|
1689
|
-
cyan: "#56d8ff",
|
|
1690
|
-
red: "#ff5d5d",
|
|
1691
|
-
yellow: "#ffd24d",
|
|
1692
|
-
ink: "#f2f3f6",
|
|
1693
|
-
ink2: "#aeb0ba",
|
|
1694
|
-
ink3: "#6c6e79",
|
|
1695
|
-
ink4: "#44464f",
|
|
1696
|
-
panel: "#101115",
|
|
1697
|
-
panelUser: "#14161b",
|
|
1698
|
-
toolPending: "#0e1013",
|
|
1699
|
-
toolSuccess: "#10150c",
|
|
1700
|
-
toolError: "#1a0f0f",
|
|
1701
|
-
customMsg: "#0f1410"
|
|
1702
|
-
},
|
|
1703
|
-
colors: {
|
|
1704
|
-
accent: "acid",
|
|
1705
|
-
border: "ink4",
|
|
1706
|
-
borderAccent: "acid",
|
|
1707
|
-
borderMuted: "ink4",
|
|
1708
|
-
success: "acid",
|
|
1709
|
-
error: "red",
|
|
1710
|
-
warning: "yellow",
|
|
1711
|
-
muted: "ink3",
|
|
1712
|
-
dim: "ink4",
|
|
1713
|
-
text: "ink",
|
|
1714
|
-
thinkingText: "ink3",
|
|
1715
|
-
selectedBg: "panel",
|
|
1716
|
-
userMessageBg: "panelUser",
|
|
1717
|
-
userMessageText: "ink",
|
|
1718
|
-
customMessageBg: "customMsg",
|
|
1719
|
-
customMessageText: "ink2",
|
|
1720
|
-
customMessageLabel: "acidDim",
|
|
1721
|
-
toolPendingBg: "toolPending",
|
|
1722
|
-
toolSuccessBg: "toolSuccess",
|
|
1723
|
-
toolErrorBg: "toolError",
|
|
1724
|
-
toolTitle: "ink",
|
|
1725
|
-
toolOutput: "ink3",
|
|
1726
|
-
mdHeading: "acid",
|
|
1727
|
-
mdLink: "cyan",
|
|
1728
|
-
mdLinkUrl: "ink4",
|
|
1729
|
-
mdCode: "acidDim",
|
|
1730
|
-
mdCodeBlock: "ink2",
|
|
1731
|
-
mdCodeBlockBorder: "ink4",
|
|
1732
|
-
mdQuote: "ink3",
|
|
1733
|
-
mdQuoteBorder: "ink4",
|
|
1734
|
-
mdHr: "ink4",
|
|
1735
|
-
mdListBullet: "acid",
|
|
1736
|
-
toolDiffAdded: "acid",
|
|
1737
|
-
toolDiffRemoved: "red",
|
|
1738
|
-
toolDiffContext: "ink3",
|
|
1739
|
-
syntaxComment: "ink3",
|
|
1740
|
-
syntaxKeyword: "cyan",
|
|
1741
|
-
syntaxFunction: "acid",
|
|
1742
|
-
syntaxVariable: "ink",
|
|
1743
|
-
syntaxString: "acidDim",
|
|
1744
|
-
syntaxNumber: "yellow",
|
|
1745
|
-
syntaxType: "cyan",
|
|
1746
|
-
syntaxOperator: "ink2",
|
|
1747
|
-
syntaxPunctuation: "ink3",
|
|
1748
|
-
thinkingOff: "ink4",
|
|
1749
|
-
thinkingMinimal: "ink3",
|
|
1750
|
-
thinkingLow: "ink2",
|
|
1751
|
-
thinkingMedium: "cyan",
|
|
1752
|
-
thinkingHigh: "acidDim",
|
|
1753
|
-
thinkingXhigh: "acid",
|
|
1754
|
-
bashMode: "cyan"
|
|
1755
|
-
}
|
|
1756
|
-
};
|
|
1757
|
-
});
|
|
1758
|
-
|
|
1759
|
-
// packages/cli/src/app-opentui/adapters/inspect.ts
|
|
1760
|
-
var exports_inspect = {};
|
|
1761
|
-
__export(exports_inspect, {
|
|
1762
|
-
loadInspectRuns: () => loadInspectRuns,
|
|
1763
|
-
loadInspect: () => loadInspect,
|
|
1764
|
-
INSPECT_VIEWS: () => INSPECT_VIEWS
|
|
1765
|
-
});
|
|
1766
|
-
import { execFile } from "child_process";
|
|
1767
|
-
import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync, statSync } from "fs";
|
|
1768
|
-
import { resolve as resolve3 } from "path";
|
|
1769
|
-
import { promisify } from "util";
|
|
1770
|
-
import { resolveTaskArtifactDirs } from "@rig/runtime/control-plane/authority-files";
|
|
1771
|
-
import { readTaskArtifactPreview } from "@rig/runtime/control-plane/native/workspace-ops";
|
|
1772
|
-
import { resolveHarnessPaths, resolveMonorepoRoot, runCapture } from "@rig/runtime/control-plane/native/utils";
|
|
1773
|
-
function isFailureEntry(entry) {
|
|
1774
|
-
const status = `${entry.status ?? entry.level ?? entry.type ?? ""}`.toLowerCase();
|
|
1775
|
-
return status.includes("fail") || status.includes("error");
|
|
1776
|
-
}
|
|
1777
|
-
async function gitDiff(projectRoot) {
|
|
1778
|
-
try {
|
|
1779
|
-
const { stdout } = await execFileAsync("git", ["diff", "--no-color"], { cwd: projectRoot, maxBuffer: 8 * 1024 * 1024 });
|
|
1780
|
-
return { diff: stdout };
|
|
1781
|
-
} catch (error) {
|
|
1782
|
-
return { diff: "", error: normalizeAppError(error).message };
|
|
1783
|
-
}
|
|
1784
|
-
}
|
|
1785
|
-
function listArtifacts(projectRoot, taskId) {
|
|
1786
|
-
if (!taskId)
|
|
1787
|
-
return { artifacts: [], error: "run has no task id \u2014 artifacts are resolved per task" };
|
|
1788
|
-
try {
|
|
1789
|
-
const dirs = resolveTaskArtifactDirs(projectRoot, taskId).filter((dir) => existsSync4(dir));
|
|
1790
|
-
const out = [];
|
|
1791
|
-
const seen = new Set;
|
|
1792
|
-
for (const dir of dirs) {
|
|
1793
|
-
for (const name of readdirSync(dir)) {
|
|
1794
|
-
if (seen.has(name))
|
|
1795
|
-
continue;
|
|
1796
|
-
seen.add(name);
|
|
1797
|
-
const path = resolve3(dir, name);
|
|
1798
|
-
try {
|
|
1799
|
-
const stat = statSync(path);
|
|
1800
|
-
out.push({ name, path, sizeBytes: stat.size, isDir: stat.isDirectory() });
|
|
1801
|
-
} catch {
|
|
1802
|
-
out.push({ name, path, sizeBytes: 0, isDir: false });
|
|
1803
|
-
}
|
|
1804
|
-
}
|
|
1805
|
-
}
|
|
1806
|
-
out.sort((left, right) => left.name.localeCompare(right.name));
|
|
1807
|
-
return { artifacts: out };
|
|
1808
|
-
} catch (error) {
|
|
1809
|
-
return { artifacts: [], error: normalizeAppError(error).message };
|
|
1810
|
-
}
|
|
1811
|
-
}
|
|
1812
|
-
function readArtifact(projectRoot, taskId, fileName) {
|
|
1813
|
-
if (!taskId)
|
|
1814
|
-
return;
|
|
1815
|
-
try {
|
|
1816
|
-
const preview = readTaskArtifactPreview(projectRoot, taskId, fileName);
|
|
1817
|
-
return { name: fileName, contents: preview.contents, truncated: preview.truncated, sizeBytes: preview.sizeBytes };
|
|
1818
|
-
} catch (error) {
|
|
1819
|
-
return { name: fileName, contents: `Failed to read artifact: ${normalizeAppError(error).message}`, truncated: false, sizeBytes: 0 };
|
|
1820
|
-
}
|
|
1821
|
-
}
|
|
1822
|
-
function loadGraph(projectRoot) {
|
|
1823
|
-
try {
|
|
1824
|
-
const result = runCapture(["br", "--no-db", "list", "--pretty"], resolveMonorepoRoot(projectRoot));
|
|
1825
|
-
if (result.exitCode !== 0)
|
|
1826
|
-
return { graph: "", error: result.stderr || result.stdout || "failed to inspect graph" };
|
|
1827
|
-
return { graph: result.stdout };
|
|
1828
|
-
} catch (error) {
|
|
1829
|
-
return { graph: "", error: normalizeAppError(error).message };
|
|
1830
|
-
}
|
|
1831
|
-
}
|
|
1832
|
-
function loadAudit(projectRoot) {
|
|
1833
|
-
try {
|
|
1834
|
-
const auditPath = resolve3(resolveHarnessPaths(projectRoot).logsDir, "audit.jsonl");
|
|
1835
|
-
if (!existsSync4(auditPath))
|
|
1836
|
-
return [];
|
|
1837
|
-
return readFileSync4(auditPath, "utf-8").split(/\r?\n/).filter(Boolean).slice(-50).flatMap((raw) => {
|
|
1838
|
-
try {
|
|
1839
|
-
const parsed = JSON.parse(raw);
|
|
1840
|
-
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? [parsed] : [{ detail: raw }];
|
|
1841
|
-
} catch {
|
|
1842
|
-
return [{ detail: raw }];
|
|
1843
|
-
}
|
|
1844
|
-
});
|
|
1845
|
-
} catch {
|
|
1846
|
-
return [];
|
|
1847
|
-
}
|
|
1848
|
-
}
|
|
1849
|
-
async function loadInspectRuns(ctx, options = {}) {
|
|
1850
|
-
const label = "Loading runs to inspect";
|
|
1851
|
-
emitStarted(ctx, label);
|
|
1852
|
-
try {
|
|
1853
|
-
const projectRoot = projectRootOf(ctx);
|
|
1854
|
-
const { listRunsViaServer: listRunsViaServer2 } = await Promise.resolve().then(() => (init__server_client(), exports__server_client));
|
|
1855
|
-
emitProgress(ctx, label, "listing recent runs");
|
|
1856
|
-
const runs = await listRunsViaServer2({ projectRoot }, { limit: options.limit ?? 50 });
|
|
1857
|
-
const options_ = runs.flatMap((record) => {
|
|
1858
|
-
const runId = stringField(record, ["runId", "id"]);
|
|
1859
|
-
if (!runId)
|
|
1860
|
-
return [];
|
|
1861
|
-
const taskId = stringField(record, ["taskId"]);
|
|
1862
|
-
const updatedAt = stringField(record, ["updatedAt", "createdAt"]);
|
|
1863
|
-
return [{
|
|
1864
|
-
runId,
|
|
1865
|
-
status: stringField(record, ["status", "state"], "unknown"),
|
|
1866
|
-
title: stringField(record, ["title", "taskTitle", "taskId"], "untitled run"),
|
|
1867
|
-
...taskId ? { taskId } : {},
|
|
1868
|
-
...updatedAt ? { updatedAt } : {}
|
|
1869
|
-
}];
|
|
1870
|
-
});
|
|
1871
|
-
patchData(ctx, { inspectRuns: options_, lastRefreshError: undefined });
|
|
1872
|
-
emitCompleted(ctx, label, { count: options_.length });
|
|
1873
|
-
return options_;
|
|
1874
|
-
} catch (error) {
|
|
1875
|
-
emitFailed(ctx, label, error);
|
|
1876
|
-
throw error;
|
|
1877
|
-
}
|
|
1878
|
-
}
|
|
1879
|
-
async function loadInspect(ctx, runId) {
|
|
1880
|
-
const cleanRunId = runId.trim();
|
|
1881
|
-
const label = `Inspecting run ${cleanRunId.slice(0, 8)}`;
|
|
1882
|
-
if (!cleanRunId) {
|
|
1883
|
-
await loadInspectRuns(ctx).catch(() => []);
|
|
1884
|
-
const error = new Error("Inspect requires a run id.");
|
|
1885
|
-
throw error;
|
|
1886
|
-
}
|
|
1887
|
-
emitStarted(ctx, label);
|
|
1888
|
-
try {
|
|
1889
|
-
const projectRoot = projectRootOf(ctx);
|
|
1890
|
-
const { getRunDetailsViaServer: getRunDetailsViaServer2, getRunLogsViaServer: getRunLogsViaServer2, getRunTimelineViaServer: getRunTimelineViaServer2 } = await Promise.resolve().then(() => (init__server_client(), exports__server_client));
|
|
1891
|
-
const context = { projectRoot };
|
|
1892
|
-
emitProgress(ctx, label, "loading logs, timeline, diff, artifacts, graph, and audit");
|
|
1893
|
-
const [runPayload, logsPayload, timelinePayload, diffResult] = await Promise.all([
|
|
1894
|
-
getRunDetailsViaServer2(context, cleanRunId).catch((error) => ({ error: normalizeAppError(error).message })),
|
|
1895
|
-
getRunLogsViaServer2(context, cleanRunId, { limit: 500 }).catch(() => []),
|
|
1896
|
-
getRunTimelineViaServer2(context, cleanRunId, { limit: 500 }).catch(() => []),
|
|
1897
|
-
gitDiff(projectRoot)
|
|
1898
|
-
]);
|
|
1899
|
-
const run = runPayload && typeof runPayload === "object" && "run" in runPayload && runPayload.run && typeof runPayload.run === "object" ? runPayload.run : runPayload;
|
|
1900
|
-
const logs = arrayFromPayload(logsPayload);
|
|
1901
|
-
const timeline = arrayFromPayload(timelinePayload);
|
|
1902
|
-
const taskId = stringField(run, ["taskId"]) || undefined;
|
|
1903
|
-
const { artifacts, error: artifactsError } = listArtifacts(projectRoot, taskId);
|
|
1904
|
-
const { graph, error: graphError } = loadGraph(projectRoot);
|
|
1905
|
-
const audit = loadAudit(projectRoot);
|
|
1906
|
-
const state = ctx.getState();
|
|
1907
|
-
const selectedArtifact = typeof state.data?.inspectArtifact === "string" ? state.data.inspectArtifact : undefined;
|
|
1908
|
-
const artifactView = selectedArtifact ? readArtifact(projectRoot, taskId, selectedArtifact) : undefined;
|
|
1909
|
-
const snapshot = {
|
|
1910
|
-
runId: cleanRunId,
|
|
1911
|
-
status: stringField(run, ["status", "state"], "unknown"),
|
|
1912
|
-
title: stringField(run, ["title", "taskId", "id"], "untitled run"),
|
|
1913
|
-
logs,
|
|
1914
|
-
timeline,
|
|
1915
|
-
diff: diffResult.diff,
|
|
1916
|
-
failures: [...logs, ...timeline].filter(isFailureEntry),
|
|
1917
|
-
artifacts,
|
|
1918
|
-
graph,
|
|
1919
|
-
audit,
|
|
1920
|
-
refreshedAt: Date.now(),
|
|
1921
|
-
...taskId ? { taskId } : {},
|
|
1922
|
-
...artifactView ? { artifactView } : {},
|
|
1923
|
-
...diffResult.error ? { diffError: diffResult.error } : {},
|
|
1924
|
-
...graphError ? { graphError } : {},
|
|
1925
|
-
...artifactsError ? { artifactsError } : {}
|
|
1926
|
-
};
|
|
1927
|
-
patchData(ctx, { inspect: snapshot, lastRefreshError: undefined });
|
|
1928
|
-
emitCompleted(ctx, label, {
|
|
1929
|
-
runId: cleanRunId,
|
|
1930
|
-
logs: logs.length,
|
|
1931
|
-
timeline: timeline.length,
|
|
1932
|
-
diffBytes: snapshot.diff.length,
|
|
1933
|
-
artifacts: artifacts.length,
|
|
1934
|
-
audit: audit.length
|
|
1935
|
-
});
|
|
1936
|
-
return snapshot;
|
|
1937
|
-
} catch (error) {
|
|
1938
|
-
emitFailed(ctx, label, error, { runId: cleanRunId });
|
|
1939
|
-
throw error;
|
|
1940
|
-
}
|
|
1941
|
-
}
|
|
1942
|
-
var execFileAsync, INSPECT_VIEWS;
|
|
1943
|
-
var init_inspect = __esm(() => {
|
|
1944
|
-
execFileAsync = promisify(execFile);
|
|
1945
|
-
INSPECT_VIEWS = [
|
|
1946
|
-
"logs",
|
|
1947
|
-
"timeline",
|
|
1948
|
-
"artifacts",
|
|
1949
|
-
"artifact",
|
|
1950
|
-
"diff",
|
|
1951
|
-
"failures",
|
|
1952
|
-
"graph",
|
|
1953
|
-
"audit"
|
|
1954
|
-
];
|
|
1955
|
-
});
|
|
1956
|
-
// packages/cli/src/app-opentui/adapters/fleet.ts
|
|
1957
|
-
function normalizeRunRecord(record) {
|
|
1958
|
-
const runId = stringField(record, ["runId", "id"]);
|
|
1959
|
-
if (!runId)
|
|
1960
|
-
return null;
|
|
1961
|
-
const title = stringField(record, ["title", "taskTitle", "taskId"], "untitled run");
|
|
1962
|
-
const taskId = stringField(record, ["taskId"]);
|
|
1963
|
-
const updatedAt = stringField(record, ["updatedAt", "createdAt"]);
|
|
1964
|
-
return {
|
|
1965
|
-
runId,
|
|
1966
|
-
status: stringField(record, ["status", "state"], "unknown"),
|
|
1967
|
-
title,
|
|
1968
|
-
raw: record,
|
|
1969
|
-
...taskId ? { taskId } : {},
|
|
1970
|
-
...updatedAt ? { updatedAt } : {}
|
|
1971
|
-
};
|
|
1972
|
-
}
|
|
1973
|
-
async function refreshFleet(ctx, options = {}) {
|
|
1974
|
-
const label = "Refreshing fleet";
|
|
1975
|
-
emitStarted(ctx, label);
|
|
1976
|
-
try {
|
|
1977
|
-
const { listRunsViaServer: listRunsViaServer2, resolveServerConnectionLabel: resolveServerConnectionLabel2 } = await Promise.resolve().then(() => (init__server_client(), exports__server_client));
|
|
1978
|
-
const projectRoot = projectRootOf(ctx);
|
|
1979
|
-
emitProgress(ctx, label, "contacting selected server");
|
|
1980
|
-
const [runs, serverLabel] = await Promise.all([
|
|
1981
|
-
listRunsViaServer2({ projectRoot }, { limit: options.limit ?? 50 }),
|
|
1982
|
-
resolveServerConnectionLabel2(projectRoot)
|
|
1983
|
-
]);
|
|
1984
|
-
const normalized = runs.flatMap((run) => {
|
|
1985
|
-
const entry = normalizeRunRecord(run);
|
|
1986
|
-
return entry ? [entry] : [];
|
|
1987
|
-
});
|
|
1988
|
-
patchData(ctx, { fleet: { runs: normalized, refreshedAt: new Date().toISOString() }, lastRefreshError: undefined });
|
|
1989
|
-
patchFooter(ctx, { server: serverLabel, runs: String(normalized.length) });
|
|
1990
|
-
emitCompleted(ctx, label, { count: normalized.length });
|
|
1991
|
-
return normalized;
|
|
1992
|
-
} catch (error) {
|
|
1993
|
-
emitFailed(ctx, label, error);
|
|
1994
|
-
throw error;
|
|
1995
|
-
}
|
|
1996
|
-
}
|
|
1997
|
-
|
|
1998
|
-
// packages/cli/src/app-opentui/adapters/pi-attach.ts
|
|
1999
|
-
function currentAttachState(ctx, runId) {
|
|
2000
|
-
const value = ctx.getState().data?.piAttach;
|
|
2001
|
-
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
2002
|
-
return null;
|
|
2003
|
-
const state = value;
|
|
2004
|
-
return state.runId === runId ? state : null;
|
|
2005
|
-
}
|
|
2006
|
-
function recordStep(ctx, runId, label, emitLabel) {
|
|
2007
|
-
const now = Date.now();
|
|
2008
|
-
const previous = currentAttachState(ctx, runId);
|
|
2009
|
-
const priorSteps = previous?.steps ?? [];
|
|
2010
|
-
const settled = priorSteps.map((step) => step.status === "running" ? { ...step, status: "done", endedAtMs: step.endedAtMs ?? now } : step);
|
|
2011
|
-
const steps = [...settled, { label, startedAtMs: now, status: "running" }];
|
|
2012
|
-
patchData(ctx, {
|
|
2013
|
-
piAttach: { ...previous ?? { runId, status: "preparing", message: label }, runId, steps }
|
|
2014
|
-
});
|
|
2015
|
-
emitProgress(ctx, emitLabel, label);
|
|
2016
|
-
}
|
|
2017
|
-
async function preparePiAttachHandoff(ctx, runId) {
|
|
2018
|
-
const cleanRunId = runId.trim();
|
|
2019
|
-
const label = `Preparing Pi ${cleanRunId.slice(0, 8)}`;
|
|
2020
|
-
emitStarted(ctx, label, { piAttach: { runId: cleanRunId, status: "preparing" } });
|
|
2021
|
-
try {
|
|
2022
|
-
const { getRunDetailsViaServer: getRunDetailsViaServer2, getRunPiStatusViaServer: getRunPiStatusViaServer2, resolveServerConnectionLabel: resolveServerConnectionLabel2 } = await Promise.resolve().then(() => (init__server_client(), exports__server_client));
|
|
2023
|
-
const projectRoot = projectRootOf(ctx);
|
|
2024
|
-
recordStep(ctx, cleanRunId, "connecting to server \xB7 checking run and Pi session readiness", label);
|
|
2025
|
-
const [run, piStatus, server] = await Promise.all([
|
|
2026
|
-
getRunDetailsViaServer2({ projectRoot }, cleanRunId).catch((error) => ({ error: error instanceof Error ? error.message : String(error) })),
|
|
2027
|
-
getRunPiStatusViaServer2({ projectRoot }, cleanRunId).catch((error) => ({ error: error instanceof Error ? error.message : String(error) })),
|
|
2028
|
-
resolveServerConnectionLabel2(projectRoot)
|
|
2029
|
-
]);
|
|
2030
|
-
const state = {
|
|
2031
|
-
runId: cleanRunId,
|
|
2032
|
-
status: "preparing",
|
|
2033
|
-
message: "ready to enter worker Pi",
|
|
2034
|
-
result: { run, piStatus, server },
|
|
2035
|
-
ready: true,
|
|
2036
|
-
...currentAttachState(ctx, cleanRunId)?.steps ? { steps: currentAttachState(ctx, cleanRunId).steps } : {}
|
|
2037
|
-
};
|
|
2038
|
-
patchData(ctx, { piAttach: state, lastRefreshError: undefined });
|
|
2039
|
-
emitCompleted(ctx, label, { runId: cleanRunId, server });
|
|
2040
|
-
return state;
|
|
2041
|
-
} catch (error) {
|
|
2042
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
2043
|
-
const state = {
|
|
2044
|
-
runId: cleanRunId,
|
|
2045
|
-
status: "failed",
|
|
2046
|
-
message: reason,
|
|
2047
|
-
failureReason: reason,
|
|
2048
|
-
...currentAttachState(ctx, cleanRunId)?.steps ? { steps: currentAttachState(ctx, cleanRunId).steps } : {}
|
|
2049
|
-
};
|
|
2050
|
-
patchData(ctx, { piAttach: state });
|
|
2051
|
-
emitFailed(ctx, label, error, { runId: cleanRunId });
|
|
2052
|
-
throw error;
|
|
2053
|
-
}
|
|
2054
|
-
}
|
|
2055
|
-
async function attachRunWithBundledPi(ctx, runId) {
|
|
2056
|
-
const cleanRunId = runId.trim();
|
|
2057
|
-
const label = `Entering Pi ${cleanRunId.slice(0, 8)}`;
|
|
2058
|
-
if (!cleanRunId) {
|
|
2059
|
-
const error = new Error("Attach requires a run id.");
|
|
2060
|
-
emitFailed(ctx, label, error);
|
|
2061
|
-
throw error;
|
|
2062
|
-
}
|
|
2063
|
-
emitStarted(ctx, label, { piAttach: { runId: cleanRunId, status: "entering-pi" } });
|
|
2064
|
-
patchData(ctx, { piAttach: { runId: cleanRunId, status: "entering-pi", message: "handing the terminal to worker Pi\u2026" } });
|
|
2065
|
-
const projectRoot = projectRootOf(ctx);
|
|
2066
|
-
const outputMode = ctx.rig?.outputMode ?? "text";
|
|
2067
|
-
await releaseRendererForExternalTui(ctx);
|
|
2068
|
-
let outcome = null;
|
|
2069
|
-
let attachError = null;
|
|
2070
|
-
try {
|
|
2071
|
-
const { attachRunBundledPiFrontend: attachRunBundledPiFrontend2 } = await Promise.resolve().then(() => (init__pi_frontend(), exports__pi_frontend));
|
|
2072
|
-
outcome = await attachRunBundledPiFrontend2({ projectRoot, outputMode }, { runId: cleanRunId, returnOnQuit: true });
|
|
2073
|
-
} catch (error) {
|
|
2074
|
-
attachError = error;
|
|
2075
|
-
} finally {
|
|
2076
|
-
await resumeRendererAfterExternalTui(ctx);
|
|
2077
|
-
}
|
|
2078
|
-
if (attachError) {
|
|
2079
|
-
const reason = normalizeAppError(attachError).message;
|
|
2080
|
-
patchData(ctx, {
|
|
2081
|
-
piTerminal: undefined,
|
|
2082
|
-
piAttach: { runId: cleanRunId, status: "failed", message: reason, failureReason: reason }
|
|
2083
|
-
});
|
|
2084
|
-
Promise.resolve().then(() => (init_inspect(), exports_inspect)).then(({ loadInspect: loadInspect2 }) => loadInspect2(ctx, cleanRunId)).catch(() => null);
|
|
2085
|
-
emitFailed(ctx, label, attachError, { runId: cleanRunId });
|
|
2086
|
-
throw attachError;
|
|
2087
|
-
}
|
|
2088
|
-
const detached = outcome?.detached === true;
|
|
2089
|
-
patchData(ctx, {
|
|
2090
|
-
piTerminal: undefined,
|
|
2091
|
-
piAttach: { runId: cleanRunId, status: "returned", message: detached ? "detached from worker Pi" : "returned from worker Pi" }
|
|
2092
|
-
});
|
|
2093
|
-
emitCompleted(ctx, label, { runId: cleanRunId, result: { runId: cleanRunId, detached } });
|
|
2094
|
-
ctx.emit({ type: "scene.change", scene: "fleet", intent: { scene: "fleet", argv: ["runs"], action: { kind: "refresh", label: "Opening runs" } } });
|
|
2095
|
-
refreshFleet(ctx).catch((error) => emitFailed(ctx, "Refresh runs", error));
|
|
2096
|
-
return { runId: cleanRunId, status: "returned", detached };
|
|
2097
|
-
}
|
|
2098
|
-
export {
|
|
2099
|
-
preparePiAttachHandoff,
|
|
2100
|
-
attachRunWithBundledPi
|
|
2101
|
-
};
|