@h-rig/cli 0.0.6-alpha.8 → 0.0.6-alpha.81
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/README.md +1 -1
- package/dist/bin/build-rig-binaries.d.ts +2 -0
- package/dist/bin/rig.d.ts +2 -0
- package/dist/bin/rig.js +18374 -8205
- package/dist/src/app/board.d.ts +23 -0
- package/dist/src/app/board.js +1815 -0
- package/dist/src/app/drone-ui.d.ts +37 -0
- package/dist/src/app/drone-ui.js +294 -0
- package/dist/src/app/theme.d.ts +47 -0
- package/dist/src/app/theme.js +151 -0
- package/dist/src/app-opentui/adapters/common.d.ts +53 -0
- package/dist/src/app-opentui/adapters/common.js +149 -0
- package/dist/src/app-opentui/adapters/doctor.d.ts +11 -0
- package/dist/src/app-opentui/adapters/doctor.js +780 -0
- package/dist/src/app-opentui/adapters/fleet.d.ts +16 -0
- package/dist/src/app-opentui/adapters/fleet.js +874 -0
- package/dist/src/app-opentui/adapters/inbox.d.ts +33 -0
- package/dist/src/app-opentui/adapters/inbox.js +1454 -0
- package/dist/src/app-opentui/adapters/init.d.ts +13 -0
- package/dist/src/app-opentui/adapters/init.js +2357 -0
- package/dist/src/app-opentui/adapters/pi-attach.d.ts +16 -0
- package/dist/src/app-opentui/adapters/pi-attach.js +1295 -0
- package/dist/src/app-opentui/adapters/run-detail.d.ts +20 -0
- package/dist/src/app-opentui/adapters/run-detail.js +893 -0
- package/dist/src/app-opentui/adapters/server.d.ts +14 -0
- package/dist/src/app-opentui/adapters/server.js +798 -0
- package/dist/src/app-opentui/adapters/tasks.d.ts +55 -0
- package/dist/src/app-opentui/adapters/tasks.js +3472 -0
- package/dist/src/app-opentui/bootstrap.d.ts +16 -0
- package/dist/src/app-opentui/bootstrap.js +19509 -0
- package/dist/src/app-opentui/drone.d.ts +12 -0
- package/dist/src/app-opentui/drone.js +227 -0
- package/dist/src/app-opentui/events.d.ts +7 -0
- package/dist/src/app-opentui/events.js +28 -0
- package/dist/src/app-opentui/index.d.ts +8 -0
- package/dist/src/app-opentui/index.js +3477 -0
- package/dist/src/app-opentui/intent.d.ts +3 -0
- package/dist/src/app-opentui/intent.js +211 -0
- package/dist/src/app-opentui/layout.d.ts +15 -0
- package/dist/src/app-opentui/layout.js +44 -0
- package/dist/src/app-opentui/list-search.d.ts +8 -0
- package/dist/src/app-opentui/list-search.js +43 -0
- package/dist/src/app-opentui/pi-host-child.d.ts +2 -0
- package/dist/src/app-opentui/pi-host-child.js +778 -0
- package/dist/src/app-opentui/pi-pty-host.d.ts +64 -0
- package/dist/src/app-opentui/pi-pty-host.js +384 -0
- package/dist/src/app-opentui/registry.d.ts +4 -0
- package/dist/src/app-opentui/registry.js +6835 -0
- package/dist/src/app-opentui/render/graphics.d.ts +39 -0
- package/dist/src/app-opentui/render/graphics.js +537 -0
- package/dist/src/app-opentui/render/image-visual-layer-native-canvas.d.ts +2 -0
- package/dist/src/app-opentui/render/image-visual-layer-native-canvas.js +1480 -0
- package/dist/src/app-opentui/render/image-visual-layer-worker.d.ts +1 -0
- package/dist/src/app-opentui/render/image-visual-layer-worker.js +1541 -0
- package/dist/src/app-opentui/render/image-visual-layer.d.ts +93 -0
- package/dist/src/app-opentui/render/image-visual-layer.js +945 -0
- package/dist/src/app-opentui/render/panels.d.ts +10 -0
- package/dist/src/app-opentui/render/panels.js +201 -0
- package/dist/src/app-opentui/render/scene.d.ts +16 -0
- package/dist/src/app-opentui/render/scene.js +110 -0
- package/dist/src/app-opentui/render/text.d.ts +10 -0
- package/dist/src/app-opentui/render/text.js +121 -0
- package/dist/src/app-opentui/render/type-bar.d.ts +14 -0
- package/dist/src/app-opentui/render/type-bar.js +137 -0
- package/dist/src/app-opentui/runtime.d.ts +2 -0
- package/dist/src/app-opentui/runtime.js +3406 -0
- package/dist/src/app-opentui/scenes/doctor.d.ts +2 -0
- package/dist/src/app-opentui/scenes/doctor.js +91 -0
- package/dist/src/app-opentui/scenes/error.d.ts +2 -0
- package/dist/src/app-opentui/scenes/error.js +190 -0
- package/dist/src/app-opentui/scenes/fleet.d.ts +3 -0
- package/dist/src/app-opentui/scenes/fleet.js +207 -0
- package/dist/src/app-opentui/scenes/handoff.d.ts +2 -0
- package/dist/src/app-opentui/scenes/handoff.js +147 -0
- package/dist/src/app-opentui/scenes/help.d.ts +3 -0
- package/dist/src/app-opentui/scenes/help.js +138 -0
- package/dist/src/app-opentui/scenes/inbox.d.ts +2 -0
- package/dist/src/app-opentui/scenes/inbox.js +118 -0
- package/dist/src/app-opentui/scenes/init.d.ts +2 -0
- package/dist/src/app-opentui/scenes/init.js +94 -0
- package/dist/src/app-opentui/scenes/main.d.ts +2 -0
- package/dist/src/app-opentui/scenes/main.js +96 -0
- package/dist/src/app-opentui/scenes/run-detail.d.ts +2 -0
- package/dist/src/app-opentui/scenes/run-detail.js +139 -0
- package/dist/src/app-opentui/scenes/server.d.ts +2 -0
- package/dist/src/app-opentui/scenes/server.js +88 -0
- package/dist/src/app-opentui/scenes/tasks.d.ts +3 -0
- package/dist/src/app-opentui/scenes/tasks.js +230 -0
- package/dist/src/app-opentui/state.d.ts +4 -0
- package/dist/src/app-opentui/state.js +286 -0
- package/dist/src/app-opentui/theme.d.ts +36 -0
- package/dist/src/app-opentui/theme.js +88 -0
- package/dist/src/app-opentui/types.d.ts +188 -0
- package/dist/src/app-opentui/types.js +1 -0
- package/dist/src/commands/_async-ui.d.ts +13 -0
- package/dist/src/commands/_async-ui.js +223 -0
- package/dist/src/commands/_authority-runs.d.ts +22 -0
- package/dist/src/commands/_authority-runs.js +2 -3
- package/dist/src/commands/_cli-format.d.ts +49 -0
- package/dist/src/commands/_cli-format.js +447 -0
- package/dist/src/commands/_connection-state.d.ts +44 -0
- package/dist/src/commands/_connection-state.js +30 -11
- package/dist/src/commands/_doctor-checks.d.ts +52 -0
- package/dist/src/commands/_doctor-checks.js +180 -44
- package/dist/src/commands/_help-catalog.d.ts +51 -0
- package/dist/src/commands/_help-catalog.js +442 -0
- package/dist/src/commands/_json-output.d.ts +11 -0
- package/dist/src/commands/_json-output.js +56 -0
- package/dist/src/commands/_operator-surface.d.ts +34 -0
- package/dist/src/commands/_operator-surface.js +220 -0
- package/dist/src/commands/_operator-view.d.ts +30 -0
- package/dist/src/commands/_operator-view.js +803 -73
- package/dist/src/commands/_parsers.d.ts +15 -0
- package/dist/src/commands/_parsers.js +18 -11
- package/dist/src/commands/_paths.d.ts +11 -0
- package/dist/src/commands/_pi-frontend.d.ts +27 -0
- package/dist/src/commands/_pi-frontend.js +742 -0
- package/dist/src/commands/_pi-install.d.ts +42 -0
- package/dist/src/commands/_pi-install.js +5 -4
- package/dist/src/commands/_policy.d.ts +8 -0
- package/dist/src/commands/_policy.js +12 -5
- package/dist/src/commands/_preflight.d.ts +22 -0
- package/dist/src/commands/_preflight.js +190 -128
- package/dist/src/commands/_probes.d.ts +1 -0
- package/dist/src/commands/_run-driver-helpers.d.ts +99 -0
- package/dist/src/commands/_run-driver-helpers.js +75 -22
- package/dist/src/commands/_run-replay.d.ts +24 -0
- package/dist/src/commands/_run-replay.js +142 -0
- package/dist/src/commands/_server-client.d.ts +186 -0
- package/dist/src/commands/_server-client.js +360 -61
- package/dist/src/commands/_snapshot-upload.d.ts +39 -0
- package/dist/src/commands/_snapshot-upload.js +163 -39
- package/dist/src/commands/_spinner.d.ts +25 -0
- package/dist/src/commands/_spinner.js +65 -0
- package/dist/src/commands/_task-picker.d.ts +9 -0
- package/dist/src/commands/_task-picker.js +172 -19
- package/dist/src/commands/agent.d.ts +3 -0
- package/dist/src/commands/agent.js +39 -20
- package/dist/src/commands/browser.d.ts +65 -0
- package/dist/src/commands/browser.js +334 -51
- package/dist/src/commands/connect.d.ts +7 -0
- package/dist/src/commands/connect.js +272 -33
- package/dist/src/commands/dist.d.ts +28 -0
- package/dist/src/commands/dist.js +19 -12
- package/dist/src/commands/doctor.d.ts +3 -0
- package/dist/src/commands/doctor.js +378 -45
- package/dist/src/commands/github.d.ts +3 -0
- package/dist/src/commands/github.js +375 -53
- package/dist/src/commands/inbox.d.ts +30 -0
- package/dist/src/commands/inbox.js +760 -70
- package/dist/src/commands/init.d.ts +74 -0
- package/dist/src/commands/init.js +963 -119
- package/dist/src/commands/inspect.d.ts +3 -0
- package/dist/src/commands/inspect.js +588 -32
- package/dist/src/commands/inspector.d.ts +3 -0
- package/dist/src/commands/inspector.js +20 -13
- package/dist/src/commands/pi.d.ts +3 -0
- package/dist/src/commands/pi.js +177 -0
- package/dist/src/commands/plugin.d.ts +16 -0
- package/dist/src/commands/plugin.js +95 -27
- package/dist/src/commands/profile-and-review.d.ts +4 -0
- package/dist/src/commands/profile-and-review.js +26 -19
- package/dist/src/commands/queue.d.ts +3 -0
- package/dist/src/commands/queue.js +32 -12
- package/dist/src/commands/remote.d.ts +3 -0
- package/dist/src/commands/remote.js +43 -36
- package/dist/src/commands/repo-git-harness.d.ts +5 -0
- package/dist/src/commands/repo-git-harness.js +22 -15
- package/dist/src/commands/run.d.ts +3 -0
- package/dist/src/commands/run.js +1379 -159
- package/dist/src/commands/server.d.ts +7 -0
- package/dist/src/commands/server.js +502 -57
- package/dist/src/commands/setup.d.ts +16 -0
- package/dist/src/commands/setup.js +390 -63
- package/dist/src/commands/stats.d.ts +12 -0
- package/dist/src/commands/stats.js +1051 -0
- package/dist/src/commands/task-report-bug.d.ts +19 -0
- package/dist/src/commands/task-report-bug.js +260 -62
- package/dist/src/commands/task-run-driver.d.ts +132 -0
- package/dist/src/commands/task-run-driver.js +886 -130
- package/dist/src/commands/task.d.ts +14 -0
- package/dist/src/commands/task.js +1644 -314
- package/dist/src/commands/test.d.ts +3 -0
- package/dist/src/commands/test.js +15 -8
- package/dist/src/commands/workspace.d.ts +3 -0
- package/dist/src/commands/workspace.js +18 -11
- package/dist/src/commands.d.ts +29 -0
- package/dist/src/commands.js +10996 -6637
- package/dist/src/index.d.ts +4 -0
- package/dist/src/index.js +10197 -5787
- package/dist/src/launcher.d.ts +61 -0
- package/dist/src/launcher.js +77 -13
- package/dist/src/report-bug.d.ts +44 -0
- package/dist/src/report-bug.js +3 -3
- package/dist/src/runner.d.ts +47 -0
- package/dist/src/runner.js +16 -22
- package/dist/src/withMutedConsole.d.ts +2 -0
- package/package.json +16 -6
|
@@ -0,0 +1,3472 @@
|
|
|
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/runner.ts
|
|
19
|
+
import { EventBus } from "@rig/runtime/control-plane/runtime/events";
|
|
20
|
+
import { CliError as RuntimeCliError } from "@rig/runtime/control-plane/errors";
|
|
21
|
+
import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
|
|
22
|
+
import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
|
|
23
|
+
function takeFlag(args, flag) {
|
|
24
|
+
const rest = [];
|
|
25
|
+
let value = false;
|
|
26
|
+
for (const arg of args) {
|
|
27
|
+
if (arg === flag) {
|
|
28
|
+
value = true;
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
rest.push(arg);
|
|
32
|
+
}
|
|
33
|
+
return { value, rest };
|
|
34
|
+
}
|
|
35
|
+
function takeOption(args, option) {
|
|
36
|
+
const rest = [];
|
|
37
|
+
let value;
|
|
38
|
+
for (let index = 0;index < args.length; index += 1) {
|
|
39
|
+
const current = args[index];
|
|
40
|
+
if (current === option) {
|
|
41
|
+
const next = args[index + 1];
|
|
42
|
+
if (!next || next.startsWith("-")) {
|
|
43
|
+
throw new CliError(`Missing value for ${option}`, 1, { hint: `Provide a value after ${option}, e.g. \`${option} <value>\`.` });
|
|
44
|
+
}
|
|
45
|
+
value = next;
|
|
46
|
+
index += 1;
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (current !== undefined) {
|
|
50
|
+
rest.push(current);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return { value, rest };
|
|
54
|
+
}
|
|
55
|
+
function requireNoExtraArgs(args, usage) {
|
|
56
|
+
if (args.length > 0) {
|
|
57
|
+
throw new CliError(`Unexpected arguments: ${args.join(" ")}
|
|
58
|
+
Usage: ${usage}`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function requireTask(taskId, usage) {
|
|
62
|
+
if (!taskId) {
|
|
63
|
+
throw new CliError(`Missing --task option.
|
|
64
|
+
Usage: ${usage}`);
|
|
65
|
+
}
|
|
66
|
+
return taskId;
|
|
67
|
+
}
|
|
68
|
+
var CliError;
|
|
69
|
+
var init_runner = __esm(() => {
|
|
70
|
+
CliError = class CliError extends RuntimeCliError {
|
|
71
|
+
hint;
|
|
72
|
+
constructor(message, exitCode = 1, options = {}) {
|
|
73
|
+
super(message, exitCode);
|
|
74
|
+
if (options.hint?.trim()) {
|
|
75
|
+
this.hint = options.hint.trim();
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
// packages/cli/src/commands/_connection-state.ts
|
|
82
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
83
|
+
import { homedir } from "os";
|
|
84
|
+
import { dirname, resolve } from "path";
|
|
85
|
+
function resolveGlobalConnectionsPath(env = process.env) {
|
|
86
|
+
const explicit = env.RIG_CONNECTIONS_FILE?.trim();
|
|
87
|
+
if (explicit)
|
|
88
|
+
return resolve(explicit);
|
|
89
|
+
const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
|
|
90
|
+
if (stateDir)
|
|
91
|
+
return resolve(stateDir, "connections.json");
|
|
92
|
+
return resolve(homedir(), ".rig", "connections.json");
|
|
93
|
+
}
|
|
94
|
+
function resolveRepoConnectionPath(projectRoot) {
|
|
95
|
+
return resolve(projectRoot, ".rig", "state", "connection.json");
|
|
96
|
+
}
|
|
97
|
+
function readJsonFile(path) {
|
|
98
|
+
if (!existsSync(path))
|
|
99
|
+
return null;
|
|
100
|
+
try {
|
|
101
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
102
|
+
} catch (error) {
|
|
103
|
+
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>`." });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
function writeJsonFile(path, value) {
|
|
107
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
108
|
+
writeFileSync(path, `${JSON.stringify(value, null, 2)}
|
|
109
|
+
`, "utf8");
|
|
110
|
+
}
|
|
111
|
+
function normalizeConnection(value) {
|
|
112
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
113
|
+
return null;
|
|
114
|
+
const record = value;
|
|
115
|
+
if (record.kind === "local")
|
|
116
|
+
return { kind: "local", mode: "auto" };
|
|
117
|
+
if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
|
|
118
|
+
const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
|
|
119
|
+
return { kind: "remote", baseUrl };
|
|
120
|
+
}
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
function readGlobalConnections(options = {}) {
|
|
124
|
+
const path = resolveGlobalConnectionsPath(options.env ?? process.env);
|
|
125
|
+
const payload = readJsonFile(path);
|
|
126
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
127
|
+
return { connections: {} };
|
|
128
|
+
}
|
|
129
|
+
const rawConnections = payload.connections;
|
|
130
|
+
const connections = {};
|
|
131
|
+
if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
|
|
132
|
+
for (const [alias, raw] of Object.entries(rawConnections)) {
|
|
133
|
+
const connection = normalizeConnection(raw);
|
|
134
|
+
if (connection)
|
|
135
|
+
connections[alias] = connection;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return { connections };
|
|
139
|
+
}
|
|
140
|
+
function readRepoConnection(projectRoot) {
|
|
141
|
+
const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
|
|
142
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
143
|
+
return null;
|
|
144
|
+
const record = payload;
|
|
145
|
+
const selected = typeof record.selected === "string" ? record.selected.trim() : "";
|
|
146
|
+
if (!selected)
|
|
147
|
+
return null;
|
|
148
|
+
return {
|
|
149
|
+
selected,
|
|
150
|
+
project: typeof record.project === "string" ? record.project : undefined,
|
|
151
|
+
linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
|
|
152
|
+
serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
function writeRepoConnection(projectRoot, state) {
|
|
156
|
+
writeJsonFile(resolveRepoConnectionPath(projectRoot), state);
|
|
157
|
+
}
|
|
158
|
+
function resolveSelectedConnection(projectRoot, options = {}) {
|
|
159
|
+
const repo = readRepoConnection(projectRoot);
|
|
160
|
+
if (!repo)
|
|
161
|
+
return null;
|
|
162
|
+
if (repo.selected === "local")
|
|
163
|
+
return { alias: "local", connection: { kind: "local", mode: "auto" }, serverProjectRoot: repo.serverProjectRoot };
|
|
164
|
+
const global = readGlobalConnections(options);
|
|
165
|
+
const connection = global.connections[repo.selected];
|
|
166
|
+
if (!connection) {
|
|
167
|
+
throw new CliError(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
|
|
168
|
+
}
|
|
169
|
+
return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
|
|
170
|
+
}
|
|
171
|
+
function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
|
|
172
|
+
const repo = readRepoConnection(projectRoot);
|
|
173
|
+
if (!repo)
|
|
174
|
+
return;
|
|
175
|
+
writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
|
|
176
|
+
}
|
|
177
|
+
var init__connection_state = __esm(() => {
|
|
178
|
+
init_runner();
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
// packages/cli/src/commands/_server-client.ts
|
|
182
|
+
var exports__server_client = {};
|
|
183
|
+
__export(exports__server_client, {
|
|
184
|
+
updateWorkspaceTaskViaServer: () => updateWorkspaceTaskViaServer,
|
|
185
|
+
switchServerProjectRootViaServer: () => switchServerProjectRootViaServer,
|
|
186
|
+
submitTaskRunViaServer: () => submitTaskRunViaServer,
|
|
187
|
+
stopRunViaServer: () => stopRunViaServer,
|
|
188
|
+
steerRunViaServer: () => steerRunViaServer,
|
|
189
|
+
setServerPhaseListener: () => setServerPhaseListener,
|
|
190
|
+
setGitHubBearerTokenForCurrentProcess: () => setGitHubBearerTokenForCurrentProcess,
|
|
191
|
+
sendRunPiShellViaServer: () => sendRunPiShellViaServer,
|
|
192
|
+
sendRunPiPromptViaServer: () => sendRunPiPromptViaServer,
|
|
193
|
+
selectNextWorkspaceTaskViaServer: () => selectNextWorkspaceTaskViaServer,
|
|
194
|
+
runRunPiCommandViaServer: () => runRunPiCommandViaServer,
|
|
195
|
+
resumeRunViaServer: () => resumeRunViaServer,
|
|
196
|
+
respondRunPiExtensionUiViaServer: () => respondRunPiExtensionUiViaServer,
|
|
197
|
+
resolveServerConnectionLabel: () => resolveServerConnectionLabel,
|
|
198
|
+
requestServerJson: () => requestServerJson,
|
|
199
|
+
registerProjectViaServer: () => registerProjectViaServer,
|
|
200
|
+
prepareRemoteCheckoutViaServer: () => prepareRemoteCheckoutViaServer,
|
|
201
|
+
postGitHubTokenViaServer: () => postGitHubTokenViaServer,
|
|
202
|
+
listWorkspaceTasksViaServer: () => listWorkspaceTasksViaServer,
|
|
203
|
+
listRunsViaServer: () => listRunsViaServer,
|
|
204
|
+
listGitHubProjectsViaServer: () => listGitHubProjectsViaServer,
|
|
205
|
+
getWorkspaceTaskViaServer: () => getWorkspaceTaskViaServer,
|
|
206
|
+
getRunTimelineViaServer: () => getRunTimelineViaServer,
|
|
207
|
+
getRunPiStatusViaServer: () => getRunPiStatusViaServer,
|
|
208
|
+
getRunPiSessionViaServer: () => getRunPiSessionViaServer,
|
|
209
|
+
getRunPiMessagesViaServer: () => getRunPiMessagesViaServer,
|
|
210
|
+
getRunPiCommandsViaServer: () => getRunPiCommandsViaServer,
|
|
211
|
+
getRunPiCapabilitiesViaServer: () => getRunPiCapabilitiesViaServer,
|
|
212
|
+
getRunLogsViaServer: () => getRunLogsViaServer,
|
|
213
|
+
getRunDetailsViaServer: () => getRunDetailsViaServer,
|
|
214
|
+
getGitHubProjectStatusFieldViaServer: () => getGitHubProjectStatusFieldViaServer,
|
|
215
|
+
getGitHubAuthStatusViaServer: () => getGitHubAuthStatusViaServer,
|
|
216
|
+
ensureTaskLabelsViaServer: () => ensureTaskLabelsViaServer,
|
|
217
|
+
ensureServerForCli: () => ensureServerForCli,
|
|
218
|
+
buildRunPiEventsWebSocketUrl: () => buildRunPiEventsWebSocketUrl,
|
|
219
|
+
abortRunPiViaServer: () => abortRunPiViaServer
|
|
220
|
+
});
|
|
221
|
+
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
|
|
222
|
+
import { resolve as resolve2 } from "path";
|
|
223
|
+
import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
|
|
224
|
+
function setServerPhaseListener(listener) {
|
|
225
|
+
const previous = serverPhaseListener;
|
|
226
|
+
serverPhaseListener = listener;
|
|
227
|
+
return previous;
|
|
228
|
+
}
|
|
229
|
+
function reportServerPhase(label) {
|
|
230
|
+
serverPhaseListener?.(label);
|
|
231
|
+
}
|
|
232
|
+
function cleanToken(value) {
|
|
233
|
+
const trimmed = value?.trim();
|
|
234
|
+
return trimmed ? trimmed : null;
|
|
235
|
+
}
|
|
236
|
+
function setGitHubBearerTokenForCurrentProcess(token, projectRoot) {
|
|
237
|
+
const scopedKey = resolve2(projectRoot ?? process.cwd());
|
|
238
|
+
scopedGitHubBearerTokens.set(scopedKey, cleanToken(token ?? undefined));
|
|
239
|
+
}
|
|
240
|
+
function readPrivateRemoteSessionToken(projectRoot) {
|
|
241
|
+
const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
|
|
242
|
+
if (!existsSync2(path))
|
|
243
|
+
return null;
|
|
244
|
+
try {
|
|
245
|
+
const parsed = JSON.parse(readFileSync2(path, "utf8"));
|
|
246
|
+
return cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined);
|
|
247
|
+
} catch {
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
function readGitHubBearerTokenForRemote(projectRoot) {
|
|
252
|
+
const scopedKey = resolve2(projectRoot);
|
|
253
|
+
if (scopedGitHubBearerTokens.has(scopedKey))
|
|
254
|
+
return scopedGitHubBearerTokens.get(scopedKey) ?? null;
|
|
255
|
+
const privateSession = readPrivateRemoteSessionToken(projectRoot);
|
|
256
|
+
if (privateSession)
|
|
257
|
+
return privateSession;
|
|
258
|
+
return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
|
|
259
|
+
}
|
|
260
|
+
function readStoredGitHubAuthToken(projectRoot) {
|
|
261
|
+
const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
|
|
262
|
+
if (!existsSync2(path))
|
|
263
|
+
return null;
|
|
264
|
+
try {
|
|
265
|
+
const parsed = JSON.parse(readFileSync2(path, "utf8"));
|
|
266
|
+
return cleanToken(typeof parsed.token === "string" ? parsed.token : undefined);
|
|
267
|
+
} catch {
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
function readLocalConnectionFallbackToken(projectRoot) {
|
|
272
|
+
return readGitHubBearerTokenForRemote(projectRoot) ?? cleanToken(process.env.RIG_GITHUB_TOKEN) ?? readStoredGitHubAuthToken(projectRoot);
|
|
273
|
+
}
|
|
274
|
+
async function ensureServerForCli(projectRoot) {
|
|
275
|
+
try {
|
|
276
|
+
const selected = resolveSelectedConnection(projectRoot);
|
|
277
|
+
if (selected?.connection.kind === "remote") {
|
|
278
|
+
reportServerPhase(`Connecting to ${selected.alias}\u2026`);
|
|
279
|
+
const authToken = readGitHubBearerTokenForRemote(projectRoot);
|
|
280
|
+
const serverProjectRoot = selected.serverProjectRoot ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
|
|
281
|
+
return {
|
|
282
|
+
baseUrl: selected.connection.baseUrl,
|
|
283
|
+
authToken,
|
|
284
|
+
connectionKind: "remote",
|
|
285
|
+
serverProjectRoot
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
reportServerPhase("Starting local Rig server\u2026");
|
|
289
|
+
const connection = await ensureLocalRigServerConnection(projectRoot);
|
|
290
|
+
return {
|
|
291
|
+
baseUrl: connection.baseUrl,
|
|
292
|
+
authToken: connection.authToken ?? readLocalConnectionFallbackToken(projectRoot),
|
|
293
|
+
connectionKind: "local",
|
|
294
|
+
serverProjectRoot: resolve2(projectRoot)
|
|
295
|
+
};
|
|
296
|
+
} catch (error) {
|
|
297
|
+
if (error instanceof Error) {
|
|
298
|
+
throw new CliError(error.message, 1);
|
|
299
|
+
}
|
|
300
|
+
throw error;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
|
|
304
|
+
const repo = readRepoConnection(projectRoot);
|
|
305
|
+
const slug = repo?.project?.trim();
|
|
306
|
+
if (!slug)
|
|
307
|
+
return null;
|
|
308
|
+
try {
|
|
309
|
+
const response = await fetch(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`, {
|
|
310
|
+
headers: mergeHeaders(undefined, authToken)
|
|
311
|
+
});
|
|
312
|
+
if (!response.ok)
|
|
313
|
+
return null;
|
|
314
|
+
const payload = await response.json();
|
|
315
|
+
const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
|
|
316
|
+
const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
|
|
317
|
+
const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
|
|
318
|
+
const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
|
|
319
|
+
if (path)
|
|
320
|
+
writeRepoServerProjectRoot(projectRoot, path);
|
|
321
|
+
return path;
|
|
322
|
+
} catch {
|
|
323
|
+
return null;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
function appendTaskFilterParams(url, filters) {
|
|
327
|
+
if (filters.assignee)
|
|
328
|
+
url.searchParams.set("assignee", filters.assignee);
|
|
329
|
+
if (filters.state)
|
|
330
|
+
url.searchParams.set("state", filters.state);
|
|
331
|
+
if (filters.status)
|
|
332
|
+
url.searchParams.set("status", filters.status);
|
|
333
|
+
if (filters.limit !== undefined)
|
|
334
|
+
url.searchParams.set("limit", String(filters.limit));
|
|
335
|
+
}
|
|
336
|
+
function mergeHeaders(headers, authToken) {
|
|
337
|
+
const merged = new Headers(headers);
|
|
338
|
+
if (authToken) {
|
|
339
|
+
merged.set("authorization", `Bearer ${authToken}`);
|
|
340
|
+
}
|
|
341
|
+
return merged;
|
|
342
|
+
}
|
|
343
|
+
function diagnosticMessage(payload) {
|
|
344
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
345
|
+
return null;
|
|
346
|
+
const record = payload;
|
|
347
|
+
const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
|
|
348
|
+
const messages = diagnostics.flatMap((entry) => {
|
|
349
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry))
|
|
350
|
+
return [];
|
|
351
|
+
const diagnostic = entry;
|
|
352
|
+
const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
|
|
353
|
+
const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
|
|
354
|
+
return message ? [`${kind}: ${message}`] : [];
|
|
355
|
+
});
|
|
356
|
+
return messages.length > 0 ? messages.join("; ") : null;
|
|
357
|
+
}
|
|
358
|
+
async function probeServerReachability(baseUrl, authToken) {
|
|
359
|
+
try {
|
|
360
|
+
const response = await fetch(`${baseUrl.replace(/\/+$/, "")}/api/server/status`, {
|
|
361
|
+
headers: mergeHeaders(undefined, authToken),
|
|
362
|
+
signal: AbortSignal.timeout(1500)
|
|
363
|
+
});
|
|
364
|
+
return response.ok;
|
|
365
|
+
} catch {
|
|
366
|
+
return false;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
function cachedServerReachability(projectRoot, baseUrl, authToken) {
|
|
370
|
+
const key = resolve2(projectRoot);
|
|
371
|
+
const cached = serverReachabilityCache.get(key);
|
|
372
|
+
if (cached)
|
|
373
|
+
return cached;
|
|
374
|
+
const probe = probeServerReachability(baseUrl, authToken);
|
|
375
|
+
serverReachabilityCache.set(key, probe);
|
|
376
|
+
return probe;
|
|
377
|
+
}
|
|
378
|
+
function describeSelectedServer(projectRoot, server) {
|
|
379
|
+
try {
|
|
380
|
+
const selected = resolveSelectedConnection(projectRoot);
|
|
381
|
+
if (selected) {
|
|
382
|
+
return {
|
|
383
|
+
alias: selected.alias,
|
|
384
|
+
target: selected.connection.kind === "remote" ? selected.connection.baseUrl : server.baseUrl
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
} catch {}
|
|
388
|
+
return { alias: server.connectionKind === "remote" ? "remote" : "local", target: server.baseUrl };
|
|
389
|
+
}
|
|
390
|
+
async function buildServerFailureContext(projectRoot, server) {
|
|
391
|
+
const { alias, target } = describeSelectedServer(projectRoot, server);
|
|
392
|
+
const reachable = await cachedServerReachability(projectRoot, server.baseUrl, server.authToken);
|
|
393
|
+
const reachability = reachable ? "server is reachable" : "server is unreachable";
|
|
394
|
+
return {
|
|
395
|
+
contextLine: `Currently connected to: ${alias} at ${target} (${reachability}).`,
|
|
396
|
+
hint: "Check the selected server with `rig server status`, or switch with `rig server use <alias|local>`."
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
async function requestServerJson(context, pathname, init = {}) {
|
|
400
|
+
const server = await ensureServerForCli(context.projectRoot);
|
|
401
|
+
const headers = mergeHeaders(init.headers, server.authToken);
|
|
402
|
+
if (server.serverProjectRoot)
|
|
403
|
+
headers.set("x-rig-project-root", server.serverProjectRoot);
|
|
404
|
+
reportServerPhase(`${(init.method ?? "GET").toUpperCase()} ${pathname.split("?")[0]}\u2026`);
|
|
405
|
+
let response;
|
|
406
|
+
try {
|
|
407
|
+
response = await fetch(`${server.baseUrl}${pathname}`, {
|
|
408
|
+
...init,
|
|
409
|
+
headers
|
|
410
|
+
});
|
|
411
|
+
} catch (error) {
|
|
412
|
+
const failure = await buildServerFailureContext(context.projectRoot, server);
|
|
413
|
+
throw new CliError(`Rig server request failed: ${error instanceof Error ? error.message : String(error)}
|
|
414
|
+
${failure.contextLine}`, 1, { hint: failure.hint });
|
|
415
|
+
}
|
|
416
|
+
const text = await response.text();
|
|
417
|
+
const payload = text.trim().length > 0 ? (() => {
|
|
418
|
+
try {
|
|
419
|
+
return JSON.parse(text);
|
|
420
|
+
} catch {
|
|
421
|
+
return null;
|
|
422
|
+
}
|
|
423
|
+
})() : null;
|
|
424
|
+
if (!response.ok) {
|
|
425
|
+
const diagnostics = diagnosticMessage(payload);
|
|
426
|
+
const rawDetail = diagnostics ?? (text || response.statusText);
|
|
427
|
+
const detail = diagnostics ? rawDetail : rawDetail.split(`
|
|
428
|
+
`).map((line) => line.trim()).find((line) => line.length > 0)?.slice(0, 200) ?? response.statusText;
|
|
429
|
+
const failure = await buildServerFailureContext(context.projectRoot, server);
|
|
430
|
+
throw new CliError(`Rig server request failed (${response.status}): ${detail}
|
|
431
|
+
${failure.contextLine}`, 1, { hint: failure.hint });
|
|
432
|
+
}
|
|
433
|
+
return payload;
|
|
434
|
+
}
|
|
435
|
+
async function listWorkspaceTasksViaServer(context, filters = {}) {
|
|
436
|
+
const url = new URL("http://rig.local/api/workspace/tasks");
|
|
437
|
+
appendTaskFilterParams(url, filters);
|
|
438
|
+
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
439
|
+
if (!Array.isArray(payload)) {
|
|
440
|
+
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`." });
|
|
441
|
+
}
|
|
442
|
+
return payload.flatMap((entry) => entry && typeof entry === "object" && !Array.isArray(entry) ? [entry] : []);
|
|
443
|
+
}
|
|
444
|
+
async function getWorkspaceTaskViaServer(context, taskId) {
|
|
445
|
+
const payload = await requestServerJson(context, `/api/workspace/tasks/${encodeURIComponent(taskId)}`);
|
|
446
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
447
|
+
return null;
|
|
448
|
+
const task = payload.task;
|
|
449
|
+
return task && typeof task === "object" && !Array.isArray(task) ? task : null;
|
|
450
|
+
}
|
|
451
|
+
async function selectNextWorkspaceTaskViaServer(context, filters = {}) {
|
|
452
|
+
const url = new URL("http://rig.local/api/workspace/tasks/next");
|
|
453
|
+
appendTaskFilterParams(url, filters);
|
|
454
|
+
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
455
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
456
|
+
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." });
|
|
457
|
+
}
|
|
458
|
+
const record = payload;
|
|
459
|
+
const rawTask = record.task;
|
|
460
|
+
const task = rawTask && typeof rawTask === "object" && !Array.isArray(rawTask) ? rawTask : null;
|
|
461
|
+
const count = typeof record.count === "number" && Number.isFinite(record.count) ? record.count : task ? 1 : 0;
|
|
462
|
+
return { task, count };
|
|
463
|
+
}
|
|
464
|
+
async function getGitHubAuthStatusViaServer(context) {
|
|
465
|
+
const payload = await requestServerJson(context, "/api/github/auth/status");
|
|
466
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
467
|
+
}
|
|
468
|
+
async function postGitHubTokenViaServer(context, token, options = {}) {
|
|
469
|
+
const payload = await requestServerJson(context, "/api/github/auth/token", {
|
|
470
|
+
method: "POST",
|
|
471
|
+
headers: { "content-type": "application/json" },
|
|
472
|
+
body: JSON.stringify({ token, selectedRepo: options.selectedRepo, projectRoot: options.projectRoot })
|
|
473
|
+
});
|
|
474
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
475
|
+
}
|
|
476
|
+
async function prepareRemoteCheckoutViaServer(context, input) {
|
|
477
|
+
const payload = await requestServerJson(context, `/api/projects/${encodeURIComponent(input.repoSlug)}/prepare-checkout`, {
|
|
478
|
+
method: "POST",
|
|
479
|
+
headers: { "content-type": "application/json" },
|
|
480
|
+
body: JSON.stringify({ checkout: input.checkout, repoUrl: input.repoUrl, baseDir: input.baseDir })
|
|
481
|
+
});
|
|
482
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
483
|
+
}
|
|
484
|
+
async function registerProjectViaServer(context, input) {
|
|
485
|
+
const payload = await requestServerJson(context, "/api/projects", {
|
|
486
|
+
method: "POST",
|
|
487
|
+
headers: { "content-type": "application/json" },
|
|
488
|
+
body: JSON.stringify(input)
|
|
489
|
+
});
|
|
490
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
491
|
+
}
|
|
492
|
+
function sleep(ms) {
|
|
493
|
+
return new Promise((resolve3) => setTimeout(resolve3, ms));
|
|
494
|
+
}
|
|
495
|
+
function isRetryableProjectRootSwitchError(error) {
|
|
496
|
+
if (!(error instanceof Error))
|
|
497
|
+
return false;
|
|
498
|
+
const message = error.message.toLowerCase();
|
|
499
|
+
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");
|
|
500
|
+
}
|
|
501
|
+
async function switchServerProjectRootViaServer(context, projectRoot, options = {}) {
|
|
502
|
+
const timeoutMs = options.timeoutMs ?? 30000;
|
|
503
|
+
const pollMs = options.pollMs ?? 1000;
|
|
504
|
+
const deadline = Date.now() + timeoutMs;
|
|
505
|
+
let lastError;
|
|
506
|
+
let switched = null;
|
|
507
|
+
while (Date.now() < deadline) {
|
|
508
|
+
try {
|
|
509
|
+
switched = await requestServerJson(context, "/api/server/project-root", {
|
|
510
|
+
method: "POST",
|
|
511
|
+
headers: { "content-type": "application/json" },
|
|
512
|
+
body: JSON.stringify({ projectRoot })
|
|
513
|
+
});
|
|
514
|
+
break;
|
|
515
|
+
} catch (error) {
|
|
516
|
+
lastError = error;
|
|
517
|
+
if (!isRetryableProjectRootSwitchError(error))
|
|
518
|
+
throw error;
|
|
519
|
+
await sleep(pollMs);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
if (!switched) {
|
|
523
|
+
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);
|
|
524
|
+
}
|
|
525
|
+
const record = switched && typeof switched === "object" && !Array.isArray(switched) ? switched : {};
|
|
526
|
+
if (record.ok === true) {
|
|
527
|
+
writeRepoServerProjectRoot(context.projectRoot, projectRoot);
|
|
528
|
+
return { ok: true, switched: record };
|
|
529
|
+
}
|
|
530
|
+
throw new CliError(`Rig server rejected project-root scope ${projectRoot}: ${String(record.message ?? record.error ?? "unknown error")}`, 1);
|
|
531
|
+
}
|
|
532
|
+
async function listRunsViaServer(context, options = {}) {
|
|
533
|
+
const url = new URL("http://rig.local/api/runs");
|
|
534
|
+
if (options.limit !== undefined)
|
|
535
|
+
url.searchParams.set("limit", String(options.limit));
|
|
536
|
+
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
537
|
+
const runs = Array.isArray(payload) ? payload : payload && typeof payload === "object" && !Array.isArray(payload) && Array.isArray(payload.runs) ? payload.runs : [];
|
|
538
|
+
return runs.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry)));
|
|
539
|
+
}
|
|
540
|
+
async function getRunDetailsViaServer(context, runId) {
|
|
541
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}`);
|
|
542
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
543
|
+
}
|
|
544
|
+
async function getRunLogsViaServer(context, runId, options = {}) {
|
|
545
|
+
const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/logs`);
|
|
546
|
+
if (options.limit !== undefined)
|
|
547
|
+
url.searchParams.set("limit", String(options.limit));
|
|
548
|
+
if (options.cursor)
|
|
549
|
+
url.searchParams.set("cursor", options.cursor);
|
|
550
|
+
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
551
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
|
|
552
|
+
}
|
|
553
|
+
async function getRunTimelineViaServer(context, runId, options = {}) {
|
|
554
|
+
const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/timeline`);
|
|
555
|
+
if (options.limit !== undefined)
|
|
556
|
+
url.searchParams.set("limit", String(options.limit));
|
|
557
|
+
if (options.cursor)
|
|
558
|
+
url.searchParams.set("cursor", options.cursor);
|
|
559
|
+
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
560
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
|
|
561
|
+
}
|
|
562
|
+
async function ensureTaskLabelsViaServer(context) {
|
|
563
|
+
const payload = await requestServerJson(context, "/api/workspace/task-labels", { method: "POST" });
|
|
564
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
565
|
+
}
|
|
566
|
+
async function listGitHubProjectsViaServer(context, owner) {
|
|
567
|
+
const url = new URL("http://rig.local/api/github/projects");
|
|
568
|
+
url.searchParams.set("owner", owner);
|
|
569
|
+
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
570
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { projects: [] };
|
|
571
|
+
}
|
|
572
|
+
async function getGitHubProjectStatusFieldViaServer(context, projectId) {
|
|
573
|
+
const payload = await requestServerJson(context, `/api/github/projects/${encodeURIComponent(projectId)}/status-field`);
|
|
574
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
575
|
+
}
|
|
576
|
+
async function updateWorkspaceTaskViaServer(context, input) {
|
|
577
|
+
const payload = await requestServerJson(context, "/api/tasks/update", {
|
|
578
|
+
method: "POST",
|
|
579
|
+
headers: { "content-type": "application/json" },
|
|
580
|
+
body: JSON.stringify(input)
|
|
581
|
+
});
|
|
582
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
|
|
583
|
+
}
|
|
584
|
+
async function resumeRunViaServer(context, runId, options) {
|
|
585
|
+
let targetRunId = runId?.trim() || null;
|
|
586
|
+
if (!targetRunId) {
|
|
587
|
+
const candidates = (await listRunsViaServer(context)).filter((run) => RESUMABLE_RUN_STATUSES.has(String(run.status ?? ""))).sort((left, right) => String(right.updatedAt ?? "").localeCompare(String(left.updatedAt ?? "")));
|
|
588
|
+
targetRunId = typeof candidates[0]?.runId === "string" ? candidates[0].runId : null;
|
|
589
|
+
}
|
|
590
|
+
if (!targetRunId) {
|
|
591
|
+
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>`." });
|
|
592
|
+
}
|
|
593
|
+
const payload = await requestServerJson(context, "/api/runs/resume", {
|
|
594
|
+
method: "POST",
|
|
595
|
+
headers: { "content-type": "application/json" },
|
|
596
|
+
body: JSON.stringify({ runId: targetRunId, createdAt: new Date().toISOString(), restart: options.restart })
|
|
597
|
+
});
|
|
598
|
+
const record = payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
599
|
+
if (record.ok === false) {
|
|
600
|
+
const message = typeof record.error === "string" && record.error.trim() ? record.error : "run resume failed";
|
|
601
|
+
throw new CliError(`${options.restart ? "restart" : "resume"} failed for ${targetRunId}: ${message}`, 1);
|
|
602
|
+
}
|
|
603
|
+
return { ok: true, runId: targetRunId, ...record };
|
|
604
|
+
}
|
|
605
|
+
async function resolveServerConnectionLabel(projectRoot) {
|
|
606
|
+
try {
|
|
607
|
+
const selected = resolveSelectedConnection(projectRoot);
|
|
608
|
+
if (!selected)
|
|
609
|
+
return "no server selected";
|
|
610
|
+
if (selected.connection.kind === "remote") {
|
|
611
|
+
return selected.connection.baseUrl.replace(/^https?:\/\//, "");
|
|
612
|
+
}
|
|
613
|
+
return `local (${selected.alias})`;
|
|
614
|
+
} catch {
|
|
615
|
+
return "no server selected";
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
async function stopRunViaServer(context, runId) {
|
|
619
|
+
const payload = await requestServerJson(context, "/api/runs/stop", {
|
|
620
|
+
method: "POST",
|
|
621
|
+
headers: { "content-type": "application/json" },
|
|
622
|
+
body: JSON.stringify({ runId })
|
|
623
|
+
});
|
|
624
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true, runId };
|
|
625
|
+
}
|
|
626
|
+
async function steerRunViaServer(context, runId, message) {
|
|
627
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/steer`, {
|
|
628
|
+
method: "POST",
|
|
629
|
+
headers: { "content-type": "application/json" },
|
|
630
|
+
body: JSON.stringify({ message })
|
|
631
|
+
});
|
|
632
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
|
|
633
|
+
}
|
|
634
|
+
async function getRunPiSessionViaServer(context, runId) {
|
|
635
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi`);
|
|
636
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
637
|
+
}
|
|
638
|
+
async function getRunPiMessagesViaServer(context, runId) {
|
|
639
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/messages`);
|
|
640
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { messages: [] };
|
|
641
|
+
}
|
|
642
|
+
async function getRunPiStatusViaServer(context, runId) {
|
|
643
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/status`);
|
|
644
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
645
|
+
}
|
|
646
|
+
async function getRunPiCommandsViaServer(context, runId) {
|
|
647
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands`);
|
|
648
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { commands: [] };
|
|
649
|
+
}
|
|
650
|
+
async function getRunPiCapabilitiesViaServer(context, runId) {
|
|
651
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/capabilities`);
|
|
652
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { capabilities: null };
|
|
653
|
+
}
|
|
654
|
+
async function sendRunPiPromptViaServer(context, runId, text, streamingBehavior) {
|
|
655
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/prompt`, {
|
|
656
|
+
method: "POST",
|
|
657
|
+
headers: { "content-type": "application/json" },
|
|
658
|
+
body: JSON.stringify({ text, streamingBehavior })
|
|
659
|
+
});
|
|
660
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
661
|
+
}
|
|
662
|
+
async function sendRunPiShellViaServer(context, runId, text) {
|
|
663
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/shell`, {
|
|
664
|
+
method: "POST",
|
|
665
|
+
headers: { "content-type": "application/json" },
|
|
666
|
+
body: JSON.stringify({ text })
|
|
667
|
+
});
|
|
668
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
669
|
+
}
|
|
670
|
+
async function runRunPiCommandViaServer(context, runId, text) {
|
|
671
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands/run`, {
|
|
672
|
+
method: "POST",
|
|
673
|
+
headers: { "content-type": "application/json" },
|
|
674
|
+
body: JSON.stringify({ text })
|
|
675
|
+
});
|
|
676
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { type: "done" };
|
|
677
|
+
}
|
|
678
|
+
async function respondRunPiExtensionUiViaServer(context, runId, requestId, valueOrCancel) {
|
|
679
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/extension-ui/respond`, {
|
|
680
|
+
method: "POST",
|
|
681
|
+
headers: { "content-type": "application/json" },
|
|
682
|
+
body: JSON.stringify({ requestId, ...valueOrCancel })
|
|
683
|
+
});
|
|
684
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
685
|
+
}
|
|
686
|
+
async function abortRunPiViaServer(context, runId) {
|
|
687
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/abort`, { method: "POST" });
|
|
688
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { aborted: true };
|
|
689
|
+
}
|
|
690
|
+
async function buildRunPiEventsWebSocketUrl(context, runId) {
|
|
691
|
+
const server = await ensureServerForCli(context.projectRoot);
|
|
692
|
+
const url = new URL(`${server.baseUrl.replace(/\/+$/, "")}/api/runs/${encodeURIComponent(runId)}/pi/events`);
|
|
693
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
694
|
+
if (server.authToken)
|
|
695
|
+
url.searchParams.set("token", server.authToken);
|
|
696
|
+
if (server.serverProjectRoot)
|
|
697
|
+
url.searchParams.set("rigProjectRoot", server.serverProjectRoot);
|
|
698
|
+
return url.toString();
|
|
699
|
+
}
|
|
700
|
+
async function submitTaskRunViaServer(context, input) {
|
|
701
|
+
const isTaskRun = Boolean(input.taskId);
|
|
702
|
+
const endpoint = isTaskRun ? "/api/runs/task" : "/api/runs/adhoc";
|
|
703
|
+
const payload = await requestServerJson(context, endpoint, {
|
|
704
|
+
method: "POST",
|
|
705
|
+
headers: {
|
|
706
|
+
"content-type": "application/json"
|
|
707
|
+
},
|
|
708
|
+
body: JSON.stringify({
|
|
709
|
+
runId: input.runId,
|
|
710
|
+
taskId: input.taskId,
|
|
711
|
+
title: input.title,
|
|
712
|
+
runtimeAdapter: input.runtimeAdapter,
|
|
713
|
+
model: input.model,
|
|
714
|
+
runtimeMode: input.runtimeMode,
|
|
715
|
+
interactionMode: input.interactionMode,
|
|
716
|
+
initialPrompt: input.initialPrompt,
|
|
717
|
+
baselineMode: input.baselineMode,
|
|
718
|
+
prMode: input.prMode,
|
|
719
|
+
executionTarget: "local"
|
|
720
|
+
})
|
|
721
|
+
});
|
|
722
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
723
|
+
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." });
|
|
724
|
+
}
|
|
725
|
+
const runId = payload.runId;
|
|
726
|
+
if (typeof runId !== "string" || runId.trim().length === 0) {
|
|
727
|
+
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." });
|
|
728
|
+
}
|
|
729
|
+
return { runId };
|
|
730
|
+
}
|
|
731
|
+
var scopedGitHubBearerTokens, serverPhaseListener = null, serverReachabilityCache, RESUMABLE_RUN_STATUSES;
|
|
732
|
+
var init__server_client = __esm(() => {
|
|
733
|
+
init_runner();
|
|
734
|
+
init__connection_state();
|
|
735
|
+
scopedGitHubBearerTokens = new Map;
|
|
736
|
+
serverReachabilityCache = new Map;
|
|
737
|
+
RESUMABLE_RUN_STATUSES = new Set([
|
|
738
|
+
"created",
|
|
739
|
+
"preparing",
|
|
740
|
+
"running",
|
|
741
|
+
"validating",
|
|
742
|
+
"reviewing",
|
|
743
|
+
"stopped",
|
|
744
|
+
"failed",
|
|
745
|
+
"needs-attention",
|
|
746
|
+
"needs_attention"
|
|
747
|
+
]);
|
|
748
|
+
});
|
|
749
|
+
|
|
750
|
+
// packages/cli/src/app/theme.ts
|
|
751
|
+
function hexToRgb(hex) {
|
|
752
|
+
const value = hex.replace("#", "");
|
|
753
|
+
return [
|
|
754
|
+
Number.parseInt(value.slice(0, 2), 16),
|
|
755
|
+
Number.parseInt(value.slice(2, 4), 16),
|
|
756
|
+
Number.parseInt(value.slice(4, 6), 16)
|
|
757
|
+
];
|
|
758
|
+
}
|
|
759
|
+
function fg(hex) {
|
|
760
|
+
const [r, g, b] = hexToRgb(hex);
|
|
761
|
+
return (text) => `\x1B[38;2;${r};${g};${b}m${text}\x1B[39m`;
|
|
762
|
+
}
|
|
763
|
+
function bold(text) {
|
|
764
|
+
return `\x1B[1m${text}\x1B[22m`;
|
|
765
|
+
}
|
|
766
|
+
function microDroneFrame(tick) {
|
|
767
|
+
const blade = MICRO_BLADES[tick % MICRO_BLADES.length];
|
|
768
|
+
const eye = EYE_FRAMES[Math.floor(tick / 2) % EYE_FRAMES.length];
|
|
769
|
+
return `(${blade})${eye}(${blade})`;
|
|
770
|
+
}
|
|
771
|
+
function renderMicroDroneFrame(tick) {
|
|
772
|
+
const blade = MICRO_BLADES[tick % MICRO_BLADES.length];
|
|
773
|
+
const eye = EYE_FRAMES[Math.floor(tick / 2) % EYE_FRAMES.length];
|
|
774
|
+
return `${ink4("(")}${cyan(blade)}${ink4(")")}${bold(accent(eye))}${ink4("(")}${cyan(blade)}${ink4(")")}`;
|
|
775
|
+
}
|
|
776
|
+
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;
|
|
777
|
+
var init_theme = __esm(() => {
|
|
778
|
+
RIG_PALETTE = {
|
|
779
|
+
ink: "#f2f3f6",
|
|
780
|
+
ink2: "#aeb0ba",
|
|
781
|
+
ink3: "#6c6e79",
|
|
782
|
+
ink4: "#44464f",
|
|
783
|
+
accent: "#ccff4d",
|
|
784
|
+
accentDim: "#a9d63f",
|
|
785
|
+
cyan: "#56d8ff",
|
|
786
|
+
red: "#ff5d5d",
|
|
787
|
+
yellow: "#ffd24d"
|
|
788
|
+
};
|
|
789
|
+
ink = fg(RIG_PALETTE.ink);
|
|
790
|
+
ink2 = fg(RIG_PALETTE.ink2);
|
|
791
|
+
ink3 = fg(RIG_PALETTE.ink3);
|
|
792
|
+
ink4 = fg(RIG_PALETTE.ink4);
|
|
793
|
+
accent = fg(RIG_PALETTE.accent);
|
|
794
|
+
accentDim = fg(RIG_PALETTE.accentDim);
|
|
795
|
+
cyan = fg(RIG_PALETTE.cyan);
|
|
796
|
+
red = fg(RIG_PALETTE.red);
|
|
797
|
+
yellow = fg(RIG_PALETTE.yellow);
|
|
798
|
+
DRONE_ART = [
|
|
799
|
+
" .-=-. .-=-. ",
|
|
800
|
+
" ( !!! ) ( !!! ) ",
|
|
801
|
+
" '-=-'._ _.'-=-' ",
|
|
802
|
+
" '._ _.' ",
|
|
803
|
+
" '=$$$$$$$=.' ",
|
|
804
|
+
" =$$$$$$$$$$$= ",
|
|
805
|
+
" $$$@@@@@@@@@@$$$ ",
|
|
806
|
+
" $$$@@ @@$$$ ",
|
|
807
|
+
" $$@ ? @$$$ ",
|
|
808
|
+
" $$$@ '-' @$$$ ",
|
|
809
|
+
" $$$@@ @@$$$ ",
|
|
810
|
+
" $$$@@@@@@@@@@$$$ ",
|
|
811
|
+
" =$$$$$$$$$$$= ",
|
|
812
|
+
" '=$$$$$$$=.' ",
|
|
813
|
+
" _.' '._ ",
|
|
814
|
+
" .-=-.' '.-=-. ",
|
|
815
|
+
" ( !!! ) ( !!! ) ",
|
|
816
|
+
" '-=-' '-=-' "
|
|
817
|
+
];
|
|
818
|
+
EYE_FRAMES = ["@", "o", "."];
|
|
819
|
+
DRONE_WIDTH = DRONE_ART[0].length;
|
|
820
|
+
DRONE_HEIGHT = DRONE_ART.length;
|
|
821
|
+
MICRO_BLADES = ["---", "\\\\\\", "|||", "///"];
|
|
822
|
+
MICRO_DRONE_FRAMES = Array.from({ length: 12 }, (_, index) => microDroneFrame(index));
|
|
823
|
+
});
|
|
824
|
+
|
|
825
|
+
// packages/cli/src/commands/_spinner.ts
|
|
826
|
+
function createTtySpinner(input) {
|
|
827
|
+
const output = input.output ?? process.stdout;
|
|
828
|
+
const isTty = output.isTTY === true;
|
|
829
|
+
const frames = input.frames && input.frames.length > 0 ? input.frames : SPINNER_FRAMES;
|
|
830
|
+
let label = input.label;
|
|
831
|
+
let frame = 0;
|
|
832
|
+
let paused = false;
|
|
833
|
+
let stopped = false;
|
|
834
|
+
let lastPrintedLabel = "";
|
|
835
|
+
const render = () => {
|
|
836
|
+
if (stopped || paused)
|
|
837
|
+
return;
|
|
838
|
+
if (!isTty) {
|
|
839
|
+
if (label !== lastPrintedLabel) {
|
|
840
|
+
output.write(`${label}
|
|
841
|
+
`);
|
|
842
|
+
lastPrintedLabel = label;
|
|
843
|
+
}
|
|
844
|
+
return;
|
|
845
|
+
}
|
|
846
|
+
frame = (frame + 1) % frames.length;
|
|
847
|
+
const glyph = frames[frame] ?? frames[0] ?? "";
|
|
848
|
+
output.write(`\r\x1B[2K${input.styleFrame ? input.styleFrame(glyph) : glyph} ${label}`);
|
|
849
|
+
};
|
|
850
|
+
const clearLine = () => {
|
|
851
|
+
if (isTty)
|
|
852
|
+
output.write("\r\x1B[2K");
|
|
853
|
+
};
|
|
854
|
+
render();
|
|
855
|
+
const timer = isTty ? setInterval(render, input.intervalMs ?? 16) : null;
|
|
856
|
+
return {
|
|
857
|
+
setLabel(next) {
|
|
858
|
+
label = next;
|
|
859
|
+
render();
|
|
860
|
+
},
|
|
861
|
+
pause() {
|
|
862
|
+
paused = true;
|
|
863
|
+
clearLine();
|
|
864
|
+
},
|
|
865
|
+
resume() {
|
|
866
|
+
if (stopped)
|
|
867
|
+
return;
|
|
868
|
+
paused = false;
|
|
869
|
+
render();
|
|
870
|
+
},
|
|
871
|
+
stop(finalLine) {
|
|
872
|
+
if (stopped)
|
|
873
|
+
return;
|
|
874
|
+
stopped = true;
|
|
875
|
+
if (timer)
|
|
876
|
+
clearInterval(timer);
|
|
877
|
+
clearLine();
|
|
878
|
+
if (finalLine)
|
|
879
|
+
output.write(`${finalLine}
|
|
880
|
+
`);
|
|
881
|
+
}
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
var SPINNER_FRAMES;
|
|
885
|
+
var init__spinner = __esm(() => {
|
|
886
|
+
SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
|
|
887
|
+
});
|
|
888
|
+
|
|
889
|
+
// packages/cli/src/app/drone-ui.ts
|
|
890
|
+
import { ProcessTerminal, TUI, Text, Input, SelectList, matchesKey } from "@earendil-works/pi-tui";
|
|
891
|
+
function droneNote(message, title) {
|
|
892
|
+
if (title)
|
|
893
|
+
console.log(` ${accentDim("\u25C7")} ${bold(ink2(title))}`);
|
|
894
|
+
for (const line of message.split(`
|
|
895
|
+
`)) {
|
|
896
|
+
console.log(` ${ink4("\u2502")} ${line}`);
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
function droneCancel(text) {
|
|
900
|
+
console.log(` ${red("\u2716")} ${ink3(text)}`);
|
|
901
|
+
}
|
|
902
|
+
async function runMiniTui(build) {
|
|
903
|
+
const terminal = new ProcessTerminal;
|
|
904
|
+
const tui = new TUI(terminal);
|
|
905
|
+
let settled = false;
|
|
906
|
+
return await new Promise((resolve3) => {
|
|
907
|
+
const finish = (result) => {
|
|
908
|
+
if (settled)
|
|
909
|
+
return;
|
|
910
|
+
settled = true;
|
|
911
|
+
tui.stop();
|
|
912
|
+
resolve3(result);
|
|
913
|
+
};
|
|
914
|
+
build(tui, finish);
|
|
915
|
+
tui.start();
|
|
916
|
+
});
|
|
917
|
+
}
|
|
918
|
+
async function droneSelect(input) {
|
|
919
|
+
if (!isTty() || input.options.length === 0) {
|
|
920
|
+
return input.initialValue ?? input.options[0]?.value ?? null;
|
|
921
|
+
}
|
|
922
|
+
return runMiniTui((tui, finish) => {
|
|
923
|
+
tui.addChild(new Text(` ${accent("\u258D")}${bold(ink(input.message))}`));
|
|
924
|
+
const items = input.options.map((option) => ({
|
|
925
|
+
value: option.value,
|
|
926
|
+
label: option.label,
|
|
927
|
+
...option.hint ? { description: option.hint } : {}
|
|
928
|
+
}));
|
|
929
|
+
const list = new SelectList(items, Math.min(items.length, 12), SELECT_THEME);
|
|
930
|
+
const initialIndex = input.initialValue ? items.findIndex((item) => item.value === input.initialValue) : -1;
|
|
931
|
+
if (initialIndex > 0)
|
|
932
|
+
list.setSelectedIndex(initialIndex);
|
|
933
|
+
list.onSelect = (item) => finish(item.value);
|
|
934
|
+
list.onCancel = () => finish(null);
|
|
935
|
+
tui.addChild(list);
|
|
936
|
+
tui.addChild(new Text(ink4(" \u2191\u2193 navigate \xB7 enter select \xB7 esc cancel")));
|
|
937
|
+
tui.setFocus(list);
|
|
938
|
+
tui.addInputListener((data) => {
|
|
939
|
+
if (matchesKey(data, "ctrl+c") || matchesKey(data, "escape")) {
|
|
940
|
+
finish(null);
|
|
941
|
+
return { consume: true };
|
|
942
|
+
}
|
|
943
|
+
return;
|
|
944
|
+
});
|
|
945
|
+
});
|
|
946
|
+
}
|
|
947
|
+
async function droneConfirm(input) {
|
|
948
|
+
const answer = await droneSelect({
|
|
949
|
+
message: input.message,
|
|
950
|
+
options: [
|
|
951
|
+
{ value: "yes", label: "Yes" },
|
|
952
|
+
{ value: "no", label: "No" }
|
|
953
|
+
],
|
|
954
|
+
initialValue: input.initialValue === false ? "no" : "yes"
|
|
955
|
+
});
|
|
956
|
+
return answer === null ? null : answer === "yes";
|
|
957
|
+
}
|
|
958
|
+
var isTty = () => Boolean(process.stdout.isTTY), SELECT_THEME;
|
|
959
|
+
var init_drone_ui = __esm(() => {
|
|
960
|
+
init_theme();
|
|
961
|
+
init__spinner();
|
|
962
|
+
SELECT_THEME = {
|
|
963
|
+
selectedPrefix: (text) => accent(text),
|
|
964
|
+
selectedText: (text) => bold(ink(text)),
|
|
965
|
+
description: (text) => ink3(text),
|
|
966
|
+
scrollInfo: (text) => ink4(text),
|
|
967
|
+
noMatch: (text) => ink3(text)
|
|
968
|
+
};
|
|
969
|
+
});
|
|
970
|
+
|
|
971
|
+
// packages/cli/src/commands/_paths.ts
|
|
972
|
+
import { resolveMonorepoRoot } from "@rig/runtime/control-plane/native/utils";
|
|
973
|
+
var init__paths = () => {};
|
|
974
|
+
|
|
975
|
+
// packages/cli/src/commands/_authority-runs.ts
|
|
976
|
+
import {
|
|
977
|
+
readAuthorityRun,
|
|
978
|
+
readJsonlFile,
|
|
979
|
+
writeAuthorityRunRecord
|
|
980
|
+
} from "@rig/runtime/control-plane/authority-files";
|
|
981
|
+
function normalizeRuntimeAdapter(value) {
|
|
982
|
+
const normalized = value?.trim().toLowerCase();
|
|
983
|
+
if (!normalized) {
|
|
984
|
+
return "pi";
|
|
985
|
+
}
|
|
986
|
+
if (normalized === "codex" || normalized === "codex-cli" || normalized === "codex-app-server" || normalized === "gpt-codex") {
|
|
987
|
+
return "codex";
|
|
988
|
+
}
|
|
989
|
+
if (normalized === "pi" || normalized === "rig-pi" || normalized === "@rig/pi") {
|
|
990
|
+
return "pi";
|
|
991
|
+
}
|
|
992
|
+
return "claude-code";
|
|
993
|
+
}
|
|
994
|
+
var init__authority_runs = __esm(() => {
|
|
995
|
+
init__paths();
|
|
996
|
+
});
|
|
997
|
+
|
|
998
|
+
// packages/cli/src/commands/_preflight.ts
|
|
999
|
+
import { ensureProjectMainFreshBeforeRun } from "@rig/runtime/control-plane/project-main-pre-run-sync";
|
|
1000
|
+
function preflightCheck(id, label, status, detail, remediation) {
|
|
1001
|
+
return {
|
|
1002
|
+
id,
|
|
1003
|
+
label,
|
|
1004
|
+
status,
|
|
1005
|
+
...detail ? { detail } : {},
|
|
1006
|
+
...remediation ? { remediation } : {}
|
|
1007
|
+
};
|
|
1008
|
+
}
|
|
1009
|
+
function message(error) {
|
|
1010
|
+
return error instanceof Error ? error.message : String(error);
|
|
1011
|
+
}
|
|
1012
|
+
function isAuthenticated(payload) {
|
|
1013
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
1014
|
+
return false;
|
|
1015
|
+
const record = payload;
|
|
1016
|
+
return record.signedIn === true || record.authenticated === true || record.status === "authenticated" || record.ok === true && typeof record.login === "string" && record.login.trim().length > 0;
|
|
1017
|
+
}
|
|
1018
|
+
function taskMatchesId(entry, taskId) {
|
|
1019
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry))
|
|
1020
|
+
return false;
|
|
1021
|
+
const record = entry;
|
|
1022
|
+
if (record.id === taskId || record.taskId === taskId)
|
|
1023
|
+
return true;
|
|
1024
|
+
const raw = record.raw;
|
|
1025
|
+
if (raw && typeof raw === "object" && !Array.isArray(raw)) {
|
|
1026
|
+
const rawRecord = raw;
|
|
1027
|
+
if (String(rawRecord.number ?? "") === taskId.replace(/^#/, ""))
|
|
1028
|
+
return true;
|
|
1029
|
+
}
|
|
1030
|
+
return false;
|
|
1031
|
+
}
|
|
1032
|
+
function isActiveRunStatus(status) {
|
|
1033
|
+
const normalized = String(status ?? "running").toLowerCase();
|
|
1034
|
+
return !["completed", "complete", "done", "merged", "closed", "failed", "cancelled", "canceled", "needs_attention", "needs-attention", "stopped"].includes(normalized);
|
|
1035
|
+
}
|
|
1036
|
+
function permissionAllowsPr(payload) {
|
|
1037
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
1038
|
+
return null;
|
|
1039
|
+
const record = payload;
|
|
1040
|
+
if (record.canOpenPullRequest === true || record.pullRequests === true || record.push === true || record.maintain === true || record.admin === true)
|
|
1041
|
+
return true;
|
|
1042
|
+
if (record.canOpenPullRequest === false || record.pullRequests === false || record.push === false)
|
|
1043
|
+
return false;
|
|
1044
|
+
const permissions = record.permissions;
|
|
1045
|
+
if (permissions && typeof permissions === "object" && !Array.isArray(permissions)) {
|
|
1046
|
+
const p = permissions;
|
|
1047
|
+
if (p.push === true || p.maintain === true || p.admin === true)
|
|
1048
|
+
return true;
|
|
1049
|
+
if (p.push === false && p.maintain !== true && p.admin !== true)
|
|
1050
|
+
return false;
|
|
1051
|
+
}
|
|
1052
|
+
return null;
|
|
1053
|
+
}
|
|
1054
|
+
function isNotFoundError(error) {
|
|
1055
|
+
return /\b(404|not found)\b/i.test(message(error));
|
|
1056
|
+
}
|
|
1057
|
+
function projectCheckoutReady(payload) {
|
|
1058
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
1059
|
+
return null;
|
|
1060
|
+
const record = payload;
|
|
1061
|
+
if (record.checkoutReady === true || record.ready === true)
|
|
1062
|
+
return true;
|
|
1063
|
+
if (record.checkoutReady === false || record.ready === false)
|
|
1064
|
+
return false;
|
|
1065
|
+
const project = record.project;
|
|
1066
|
+
if (project && typeof project === "object" && !Array.isArray(project)) {
|
|
1067
|
+
const checkouts = project.checkouts;
|
|
1068
|
+
if (Array.isArray(checkouts))
|
|
1069
|
+
return checkouts.length > 0;
|
|
1070
|
+
}
|
|
1071
|
+
return null;
|
|
1072
|
+
}
|
|
1073
|
+
function activeDuplicateRun(runs, taskId) {
|
|
1074
|
+
if (!Array.isArray(runs))
|
|
1075
|
+
return null;
|
|
1076
|
+
for (const run of runs) {
|
|
1077
|
+
if (!run || typeof run !== "object" || Array.isArray(run))
|
|
1078
|
+
continue;
|
|
1079
|
+
const record = run;
|
|
1080
|
+
if ((record.taskId === taskId || record.task === taskId) && isActiveRunStatus(record.status))
|
|
1081
|
+
return record;
|
|
1082
|
+
}
|
|
1083
|
+
return null;
|
|
1084
|
+
}
|
|
1085
|
+
async function runFastTaskRunPreflight(context, options = {}) {
|
|
1086
|
+
const checks = [];
|
|
1087
|
+
const request = options.requestJson ?? ((pathname, init) => requestServerJson(context, pathname, init));
|
|
1088
|
+
const taskId = options.taskId?.trim() || null;
|
|
1089
|
+
const requiresCurrentRunApi = Boolean(taskId);
|
|
1090
|
+
const selectedServer = options.requestJson ? null : await ensureServerForCli(context.projectRoot).catch(() => null);
|
|
1091
|
+
const allowLocalLegacyTaskRunCompatibility = selectedServer?.connectionKind === "local";
|
|
1092
|
+
let legacyServerCompatibility = false;
|
|
1093
|
+
try {
|
|
1094
|
+
await request("/api/server/status");
|
|
1095
|
+
checks.push(preflightCheck("server", "Rig server reachable", "pass"));
|
|
1096
|
+
} catch (error) {
|
|
1097
|
+
if (isNotFoundError(error)) {
|
|
1098
|
+
try {
|
|
1099
|
+
await request("/health");
|
|
1100
|
+
legacyServerCompatibility = !requiresCurrentRunApi || allowLocalLegacyTaskRunCompatibility;
|
|
1101
|
+
checks.push(requiresCurrentRunApi && !allowLocalLegacyTaskRunCompatibility ? preflightCheck("server", "Rig server reachable", "fail", "legacy /health endpoint only; current task-run APIs are required", "Upgrade/select the Rig server before launching a task run.") : preflightCheck("server", "Rig server reachable", "pass", allowLocalLegacyTaskRunCompatibility ? "local legacy /health endpoint; submit endpoint will be authoritative" : "legacy /health endpoint"));
|
|
1102
|
+
} catch (healthError) {
|
|
1103
|
+
checks.push(preflightCheck("server", "Rig server reachable", "fail", message(healthError), "Start or select a reachable Rig server."));
|
|
1104
|
+
}
|
|
1105
|
+
} else {
|
|
1106
|
+
checks.push(preflightCheck("server", "Rig server reachable", "fail", message(error), "Start or select a reachable Rig server."));
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
const repo = readRepoConnection(context.projectRoot);
|
|
1110
|
+
checks.push(repo ? preflightCheck("project-link", "project linked to Rig server", repo.project ? "pass" : "warn", `${repo.selected}${repo.project ? ` -> ${repo.project}` : ""}`, "Run `rig init --yes --repo owner/repo` to record the GitHub repo slug.") : preflightCheck("project-link", "project linked to Rig server", legacyServerCompatibility ? "warn" : "fail", "missing .rig/state/connection.json", "Run `rig init` or `rig server use <alias|local>`."));
|
|
1111
|
+
try {
|
|
1112
|
+
const auth = await request("/api/github/auth/status");
|
|
1113
|
+
checks.push(isAuthenticated(auth) ? preflightCheck("github-auth", "GitHub auth valid", "pass") : preflightCheck("github-auth", "GitHub auth valid", legacyServerCompatibility ? "warn" : "fail", "not authenticated", "Run `rig github auth import-gh` or `rig github auth token --token <token>`."));
|
|
1114
|
+
} catch (error) {
|
|
1115
|
+
checks.push(preflightCheck("github-auth", "GitHub auth valid", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix GitHub auth on the selected Rig server."));
|
|
1116
|
+
}
|
|
1117
|
+
try {
|
|
1118
|
+
const projection = await request("/api/workspace/task-projection");
|
|
1119
|
+
checks.push(preflightCheck("task-projection", "task projection ready", "pass", JSON.stringify(projection).slice(0, 120)));
|
|
1120
|
+
} catch (error) {
|
|
1121
|
+
checks.push(preflightCheck("task-projection", "task projection ready", "warn", message(error), "Refresh task projection with `rig task list` before launching."));
|
|
1122
|
+
}
|
|
1123
|
+
try {
|
|
1124
|
+
const permissions = await request("/api/github/repo/permissions");
|
|
1125
|
+
const allowed = permissionAllowsPr(permissions);
|
|
1126
|
+
checks.push(allowed === false ? preflightCheck("github-repo-permissions", "GitHub PR permissions", "fail", JSON.stringify(permissions).slice(0, 120), "Grant the selected GitHub token permission to push branches and open PRs.") : preflightCheck("github-repo-permissions", "GitHub PR permissions", allowed === true ? "pass" : "warn", JSON.stringify(permissions).slice(0, 120), "Confirm the selected token can push branches and open PRs."));
|
|
1127
|
+
} catch (error) {
|
|
1128
|
+
checks.push(preflightCheck("github-repo-permissions", "GitHub PR permissions", "warn", message(error), "Ensure the selected token can push branches and open PRs."));
|
|
1129
|
+
}
|
|
1130
|
+
if (repo?.project) {
|
|
1131
|
+
try {
|
|
1132
|
+
const project = await request(`/api/projects/${encodeURIComponent(repo.project)}`);
|
|
1133
|
+
const ready = projectCheckoutReady(project);
|
|
1134
|
+
checks.push(ready === false ? preflightCheck("remote-checkout", "execution checkout ready", "fail", JSON.stringify(project).slice(0, 120), "Repair the server checkout or rerun `rig init` with a valid checkout strategy.") : preflightCheck("remote-checkout", "execution checkout ready", ready === true ? "pass" : "warn", JSON.stringify(project).slice(0, 120), "Confirm the selected server has a prepared execution checkout."));
|
|
1135
|
+
} catch (error) {
|
|
1136
|
+
checks.push(preflightCheck("remote-checkout", "execution checkout ready", "warn", message(error), "Run `rig init` or repair the server checkout before launch."));
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
if (taskId) {
|
|
1140
|
+
try {
|
|
1141
|
+
const tasks = await request(`/api/workspace/tasks?limit=200&refresh=1`);
|
|
1142
|
+
const found = Array.isArray(tasks) && tasks.some((task) => taskMatchesId(task, taskId));
|
|
1143
|
+
checks.push(found ? preflightCheck("issue", "task/issue accessible", "pass", taskId) : preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", taskId, "Confirm the issue exists and matches the configured task filters."));
|
|
1144
|
+
} catch (error) {
|
|
1145
|
+
checks.push(preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix the task source before launching a run."));
|
|
1146
|
+
}
|
|
1147
|
+
try {
|
|
1148
|
+
const runs = await request("/api/runs?limit=200");
|
|
1149
|
+
const duplicate = activeDuplicateRun(runs, taskId);
|
|
1150
|
+
checks.push(duplicate ? preflightCheck("duplicate-active-run", "one active run per task", "fail", String(duplicate.runId ?? taskId), "Attach to or stop the existing run before starting another one for this task.") : preflightCheck("duplicate-active-run", "one active run per task", "pass", taskId));
|
|
1151
|
+
} catch (error) {
|
|
1152
|
+
checks.push(preflightCheck("duplicate-active-run", "one active run per task", "warn", message(error), "Could not list active runs; the server will still reject conflicting runs if configured."));
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
if ((options.runtimeAdapter ?? "pi") === "pi") {
|
|
1156
|
+
checks.push(preflightCheck("runtime", "worker Pi SDK session daemon", "pass", selectedServer?.connectionKind === "remote" ? "remote worker-owned runtime" : "bundled server-owned runtime"));
|
|
1157
|
+
} else {
|
|
1158
|
+
checks.push(preflightCheck("runtime", "runtime adapter", "pass", options.runtimeAdapter));
|
|
1159
|
+
}
|
|
1160
|
+
const failures = checks.filter((check) => check.status === "fail");
|
|
1161
|
+
if (failures.length > 0) {
|
|
1162
|
+
const summary = failures.map((check) => `${check.label}${check.detail ? `: ${check.detail}` : ""}`).join("; ");
|
|
1163
|
+
if (failures.some((check) => check.id === "duplicate-active-run") && taskId) {
|
|
1164
|
+
throw new CliError(`Task ${taskId} already has an active Rig run. ${summary}`, 1, { hint: `Attach to it with \`rig run attach <run-id> --follow\`, or stop it first with \`rig run stop <run-id>\`.` });
|
|
1165
|
+
}
|
|
1166
|
+
throw new CliError(`Task run preflight failed: ${summary}`, 1, { hint: "Run `rig doctor` to diagnose, then retry `rig task run`." });
|
|
1167
|
+
}
|
|
1168
|
+
return { ok: true, checks };
|
|
1169
|
+
}
|
|
1170
|
+
async function runProjectMainSyncPreflight(context, options) {
|
|
1171
|
+
if (context.dryRun) {
|
|
1172
|
+
if (context.outputMode === "text" && !options.disabled) {
|
|
1173
|
+
console.log("[dry-run] project-rig pre-run sync check");
|
|
1174
|
+
}
|
|
1175
|
+
return;
|
|
1176
|
+
}
|
|
1177
|
+
const result = await ensureProjectMainFreshBeforeRun({
|
|
1178
|
+
projectRoot: context.projectRoot,
|
|
1179
|
+
disabled: options.disabled,
|
|
1180
|
+
runBootstrap: async () => {
|
|
1181
|
+
const bootstrap = await context.runCommand(["bun", "run", "bootstrap"]);
|
|
1182
|
+
if (bootstrap.exitCode !== 0) {
|
|
1183
|
+
throw new CliError(bootstrap.stderr || bootstrap.stdout || "bun run bootstrap failed during project pre-run sync", bootstrap.exitCode || 1);
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
});
|
|
1187
|
+
if (context.outputMode !== "text") {
|
|
1188
|
+
return;
|
|
1189
|
+
}
|
|
1190
|
+
switch (result.status) {
|
|
1191
|
+
case "disabled":
|
|
1192
|
+
console.log("Project pre-run sync skipped (--skip-project-sync).");
|
|
1193
|
+
break;
|
|
1194
|
+
case "skipped_not_main":
|
|
1195
|
+
console.log(`Project pre-run sync skipped (current branch: ${result.branch}).`);
|
|
1196
|
+
break;
|
|
1197
|
+
case "up_to_date":
|
|
1198
|
+
break;
|
|
1199
|
+
case "local_ahead":
|
|
1200
|
+
console.log(`Project pre-run sync skipped (local main ahead by ${result.localAhead} commit(s)).`);
|
|
1201
|
+
break;
|
|
1202
|
+
case "updated":
|
|
1203
|
+
console.log(`Project pre-run sync updated local main from origin/main (+${result.remoteAhead}) and bootstrapped.`);
|
|
1204
|
+
break;
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
var init__preflight = __esm(() => {
|
|
1208
|
+
init_runner();
|
|
1209
|
+
init__connection_state();
|
|
1210
|
+
init__server_client();
|
|
1211
|
+
});
|
|
1212
|
+
|
|
1213
|
+
// packages/cli/src/withMutedConsole.ts
|
|
1214
|
+
function isPromise(value) {
|
|
1215
|
+
if (typeof value !== "object" && typeof value !== "function") {
|
|
1216
|
+
return false;
|
|
1217
|
+
}
|
|
1218
|
+
return value !== null && typeof value.then === "function";
|
|
1219
|
+
}
|
|
1220
|
+
function withMutedConsole(mute, fn) {
|
|
1221
|
+
if (!mute) {
|
|
1222
|
+
return fn();
|
|
1223
|
+
}
|
|
1224
|
+
const originalLog = console.log;
|
|
1225
|
+
const originalWarn = console.warn;
|
|
1226
|
+
const originalInfo = console.info;
|
|
1227
|
+
const restore = () => {
|
|
1228
|
+
console.log = originalLog;
|
|
1229
|
+
console.warn = originalWarn;
|
|
1230
|
+
console.info = originalInfo;
|
|
1231
|
+
};
|
|
1232
|
+
console.log = () => {};
|
|
1233
|
+
console.warn = () => {};
|
|
1234
|
+
console.info = () => {};
|
|
1235
|
+
try {
|
|
1236
|
+
const result = fn();
|
|
1237
|
+
if (isPromise(result)) {
|
|
1238
|
+
return result.finally(restore);
|
|
1239
|
+
}
|
|
1240
|
+
restore();
|
|
1241
|
+
return result;
|
|
1242
|
+
} catch (error) {
|
|
1243
|
+
restore();
|
|
1244
|
+
throw error;
|
|
1245
|
+
} finally {
|
|
1246
|
+
if (console.log === originalLog) {
|
|
1247
|
+
restore();
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
// packages/cli/src/commands/_operator-surface.ts
|
|
1253
|
+
import { createInterface } from "readline";
|
|
1254
|
+
import { createInterface as createPromptInterface } from "readline/promises";
|
|
1255
|
+
function logDetail(log) {
|
|
1256
|
+
return typeof log.detail === "string" ? log.detail.trim() : "";
|
|
1257
|
+
}
|
|
1258
|
+
function parseProviderProtocolLog(title, detail) {
|
|
1259
|
+
if (title.trim().toLowerCase() !== "agent output")
|
|
1260
|
+
return null;
|
|
1261
|
+
if (!detail.startsWith("{") || !detail.endsWith("}"))
|
|
1262
|
+
return null;
|
|
1263
|
+
try {
|
|
1264
|
+
const record = JSON.parse(detail);
|
|
1265
|
+
if (!record || typeof record !== "object" || Array.isArray(record))
|
|
1266
|
+
return null;
|
|
1267
|
+
const type = record.type;
|
|
1268
|
+
return typeof type === "string" && [
|
|
1269
|
+
"assistant",
|
|
1270
|
+
"message_start",
|
|
1271
|
+
"message_update",
|
|
1272
|
+
"message_end",
|
|
1273
|
+
"stream_event",
|
|
1274
|
+
"tool_result",
|
|
1275
|
+
"tool_execution_start",
|
|
1276
|
+
"tool_execution_update",
|
|
1277
|
+
"tool_execution_end",
|
|
1278
|
+
"turn_start",
|
|
1279
|
+
"turn_end"
|
|
1280
|
+
].includes(type) ? record : null;
|
|
1281
|
+
} catch {
|
|
1282
|
+
return null;
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
function renderProviderProtocolLog(record) {
|
|
1286
|
+
const type = typeof record.type === "string" ? record.type : "";
|
|
1287
|
+
if (type === "tool_execution_start" || type === "tool_execution_update" || type === "tool_execution_end") {
|
|
1288
|
+
const toolName = String(record.toolName ?? record.name ?? "tool");
|
|
1289
|
+
const status = type === "tool_execution_start" ? "started" : type === "tool_execution_end" ? record.isError === true || record.result && typeof record.result === "object" && !Array.isArray(record.result) && record.result.isError === true ? "failed" : "completed" : "running";
|
|
1290
|
+
return `[Pi tool] ${toolName} ${status}`;
|
|
1291
|
+
}
|
|
1292
|
+
return null;
|
|
1293
|
+
}
|
|
1294
|
+
function entryId(entry, fallback) {
|
|
1295
|
+
return typeof entry.id === "string" && entry.id.trim() ? entry.id : fallback;
|
|
1296
|
+
}
|
|
1297
|
+
function renderOperatorSnapshot(snapshot) {
|
|
1298
|
+
const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
|
|
1299
|
+
const runId = String(run.runId ?? run.id ?? "run");
|
|
1300
|
+
const status = String(run.status ?? "unknown");
|
|
1301
|
+
const logs = snapshot.logs ?? [];
|
|
1302
|
+
const latestByStage = new Map;
|
|
1303
|
+
for (const log of logs) {
|
|
1304
|
+
const title = String(log.title ?? "").toLowerCase();
|
|
1305
|
+
const stageName = String(log.stage ?? "").toLowerCase();
|
|
1306
|
+
const stage = CANONICAL_STAGES.find((candidate) => candidate.toLowerCase() === title || candidate.toLowerCase() === stageName);
|
|
1307
|
+
if (stage)
|
|
1308
|
+
latestByStage.set(stage, log);
|
|
1309
|
+
}
|
|
1310
|
+
const stageLines = CANONICAL_STAGES.flatMap((stage) => {
|
|
1311
|
+
const match = latestByStage.get(stage);
|
|
1312
|
+
return match ? [`${stage}: ${String(match.status ?? status)}${logDetail(match) ? ` \u2014 ${logDetail(match)}` : ""}`] : [];
|
|
1313
|
+
});
|
|
1314
|
+
return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
|
|
1315
|
+
`);
|
|
1316
|
+
}
|
|
1317
|
+
function createPiRunStreamRenderer(output = process.stdout) {
|
|
1318
|
+
let lastSnapshot = "";
|
|
1319
|
+
const assistantTextById = new Map;
|
|
1320
|
+
const seenTimeline = new Set;
|
|
1321
|
+
const seenLogs = new Set;
|
|
1322
|
+
const writeLine = (line) => output.write(`${line}
|
|
1323
|
+
`);
|
|
1324
|
+
return {
|
|
1325
|
+
renderSnapshot(snapshot) {
|
|
1326
|
+
const rendered = renderOperatorSnapshot(snapshot);
|
|
1327
|
+
if (rendered && rendered !== lastSnapshot) {
|
|
1328
|
+
writeLine(rendered);
|
|
1329
|
+
lastSnapshot = rendered;
|
|
1330
|
+
}
|
|
1331
|
+
},
|
|
1332
|
+
renderTimeline(entries) {
|
|
1333
|
+
for (const [index, entry] of entries.entries()) {
|
|
1334
|
+
const id = entryId(entry, `timeline:${index}:${String(entry.cursor ?? "")}`);
|
|
1335
|
+
if (entry.type === "assistant_message" && typeof entry.text === "string") {
|
|
1336
|
+
const text = entry.text;
|
|
1337
|
+
const previousText = assistantTextById.get(id) ?? "";
|
|
1338
|
+
if (!previousText && text.trim()) {
|
|
1339
|
+
writeLine("[Pi assistant]");
|
|
1340
|
+
}
|
|
1341
|
+
if (text.startsWith(previousText)) {
|
|
1342
|
+
const delta = text.slice(previousText.length);
|
|
1343
|
+
if (delta)
|
|
1344
|
+
output.write(delta);
|
|
1345
|
+
} else if (text.trim() && text !== previousText) {
|
|
1346
|
+
if (previousText)
|
|
1347
|
+
writeLine(`
|
|
1348
|
+
[Pi assistant]`);
|
|
1349
|
+
output.write(text);
|
|
1350
|
+
}
|
|
1351
|
+
assistantTextById.set(id, text);
|
|
1352
|
+
continue;
|
|
1353
|
+
}
|
|
1354
|
+
if (seenTimeline.has(id))
|
|
1355
|
+
continue;
|
|
1356
|
+
seenTimeline.add(id);
|
|
1357
|
+
if (entry.type === "tool_execution_start" || entry.type === "tool_execution_update" || entry.type === "tool_execution_end" || entry.type === "mcp_tool_call") {
|
|
1358
|
+
writeLine(`[Pi tool] ${String(entry.toolName ?? entry.name ?? entry.title ?? entry.type)} ${String(entry.status ?? entry.state ?? "")}`.trim());
|
|
1359
|
+
continue;
|
|
1360
|
+
}
|
|
1361
|
+
if (entry.type === "timeline_warning") {
|
|
1362
|
+
writeLine(`[Rig timeline] ${String(entry.detail ?? entry.message ?? "timeline unavailable")}`);
|
|
1363
|
+
continue;
|
|
1364
|
+
}
|
|
1365
|
+
if (entry.type === "action") {
|
|
1366
|
+
const text = String(entry.detail ?? entry.message ?? entry.title ?? "").trim();
|
|
1367
|
+
if (text)
|
|
1368
|
+
writeLine(`[Rig action] ${text}`);
|
|
1369
|
+
continue;
|
|
1370
|
+
}
|
|
1371
|
+
if (entry.type === "user_message") {
|
|
1372
|
+
const text = String(entry.text ?? entry.message ?? entry.detail ?? "").trim();
|
|
1373
|
+
if (text)
|
|
1374
|
+
writeLine(`[Operator] ${text}`);
|
|
1375
|
+
continue;
|
|
1376
|
+
}
|
|
1377
|
+
const fallback = String(entry.detail ?? entry.message ?? entry.text ?? entry.title ?? "").trim();
|
|
1378
|
+
if (fallback)
|
|
1379
|
+
writeLine(`[${String(entry.type ?? "timeline")}] ${fallback}`);
|
|
1380
|
+
}
|
|
1381
|
+
},
|
|
1382
|
+
renderLogs(entries) {
|
|
1383
|
+
for (const [index, entry] of entries.entries()) {
|
|
1384
|
+
const id = entryId(entry, `log:${index}:${String(entry.createdAt ?? "")}:${String(entry.title ?? "")}`);
|
|
1385
|
+
if (seenLogs.has(id))
|
|
1386
|
+
continue;
|
|
1387
|
+
seenLogs.add(id);
|
|
1388
|
+
const title = String(entry.title ?? "");
|
|
1389
|
+
if (CANONICAL_STAGES.some((stage) => stage.toLowerCase() === title.toLowerCase()))
|
|
1390
|
+
continue;
|
|
1391
|
+
const detail = logDetail(entry);
|
|
1392
|
+
if (!detail)
|
|
1393
|
+
continue;
|
|
1394
|
+
const protocolRecord = parseProviderProtocolLog(title, detail);
|
|
1395
|
+
if (protocolRecord) {
|
|
1396
|
+
const protocolLine = renderProviderProtocolLog(protocolRecord);
|
|
1397
|
+
if (protocolLine)
|
|
1398
|
+
writeLine(protocolLine);
|
|
1399
|
+
continue;
|
|
1400
|
+
}
|
|
1401
|
+
writeLine(`[${title || "Rig log"}] ${detail}`);
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
};
|
|
1405
|
+
}
|
|
1406
|
+
function createOperatorSurface(options = {}) {
|
|
1407
|
+
const input = options.input ?? process.stdin;
|
|
1408
|
+
const output = options.output ?? process.stdout;
|
|
1409
|
+
const errorOutput = options.errorOutput ?? process.stderr;
|
|
1410
|
+
const renderer = createPiRunStreamRenderer(output);
|
|
1411
|
+
const writeLine = (line) => output.write(`${line}
|
|
1412
|
+
`);
|
|
1413
|
+
return {
|
|
1414
|
+
mode: "pi-compatible-text",
|
|
1415
|
+
...renderer,
|
|
1416
|
+
info: writeLine,
|
|
1417
|
+
error: (message2) => errorOutput.write(`${message2}
|
|
1418
|
+
`),
|
|
1419
|
+
attachCommandInput(handler) {
|
|
1420
|
+
if (options.interactive === false || !input.isTTY)
|
|
1421
|
+
return null;
|
|
1422
|
+
const rl = createInterface({ input, output: process.stdout, terminal: false });
|
|
1423
|
+
rl.on("line", (line) => {
|
|
1424
|
+
Promise.resolve(handler(line)).catch((error) => writeLine(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
|
|
1425
|
+
});
|
|
1426
|
+
return { close: () => rl.close() };
|
|
1427
|
+
}
|
|
1428
|
+
};
|
|
1429
|
+
}
|
|
1430
|
+
function taskId(task) {
|
|
1431
|
+
return typeof task.id === "string" && task.id.trim() ? task.id : "<unknown>";
|
|
1432
|
+
}
|
|
1433
|
+
function taskTitle(task) {
|
|
1434
|
+
return typeof task.title === "string" && task.title.trim() ? task.title : "Untitled task";
|
|
1435
|
+
}
|
|
1436
|
+
function taskStatus(task) {
|
|
1437
|
+
return typeof task.status === "string" && task.status.trim() ? task.status : "unknown";
|
|
1438
|
+
}
|
|
1439
|
+
function renderTaskPickerRows(tasks) {
|
|
1440
|
+
return tasks.map((task, index) => `${index + 1}. ${taskId(task)} \xB7 ${taskStatus(task)} \xB7 ${taskTitle(task)}`);
|
|
1441
|
+
}
|
|
1442
|
+
async function promptForTaskSelection(question) {
|
|
1443
|
+
const rl = createPromptInterface({ input: process.stdin, output: process.stdout });
|
|
1444
|
+
try {
|
|
1445
|
+
return await rl.question(question);
|
|
1446
|
+
} finally {
|
|
1447
|
+
rl.close();
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
var CANONICAL_STAGES;
|
|
1451
|
+
var init__operator_surface = __esm(() => {
|
|
1452
|
+
CANONICAL_STAGES = [
|
|
1453
|
+
"Connect",
|
|
1454
|
+
"GitHub/task sync",
|
|
1455
|
+
"Prepare workspace",
|
|
1456
|
+
"Launch Pi",
|
|
1457
|
+
"Plan",
|
|
1458
|
+
"Implement",
|
|
1459
|
+
"Validate",
|
|
1460
|
+
"Commit",
|
|
1461
|
+
"Open PR",
|
|
1462
|
+
"Review/CI",
|
|
1463
|
+
"Merge",
|
|
1464
|
+
"Complete"
|
|
1465
|
+
];
|
|
1466
|
+
});
|
|
1467
|
+
|
|
1468
|
+
// packages/cli/src/commands/_task-picker.ts
|
|
1469
|
+
function taskId2(task) {
|
|
1470
|
+
return typeof task.id === "string" && task.id.trim() ? task.id : "<unknown>";
|
|
1471
|
+
}
|
|
1472
|
+
async function selectTaskWithTextPicker(tasks, io = {}) {
|
|
1473
|
+
if (tasks.length === 0)
|
|
1474
|
+
return null;
|
|
1475
|
+
if (tasks.length === 1)
|
|
1476
|
+
return tasks[0];
|
|
1477
|
+
const isTty2 = io.isTty ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
1478
|
+
if (!isTty2) {
|
|
1479
|
+
throw new Error("task run requires an interactive terminal to pick a task; pass --task <id>, --next, or --detach with a task id.");
|
|
1480
|
+
}
|
|
1481
|
+
if (io.prompt || io.renderer) {
|
|
1482
|
+
const prompt = io.prompt ?? promptForTaskSelection;
|
|
1483
|
+
const renderer = io.renderer ?? { writeLine: (line) => process.stdout.write(`${line}
|
|
1484
|
+
`) };
|
|
1485
|
+
renderer.writeLine("Select Rig task:");
|
|
1486
|
+
for (const row of renderTaskPickerRows(tasks))
|
|
1487
|
+
renderer.writeLine(` ${row}`);
|
|
1488
|
+
const answer2 = (await prompt(`Task [1-${tasks.length}] or id: `)).trim();
|
|
1489
|
+
if (!answer2)
|
|
1490
|
+
return null;
|
|
1491
|
+
if (/^\d+$/.test(answer2)) {
|
|
1492
|
+
const index2 = Number.parseInt(answer2, 10) - 1;
|
|
1493
|
+
return tasks[index2] ?? null;
|
|
1494
|
+
}
|
|
1495
|
+
return tasks.find((task) => taskId2(task) === answer2) ?? null;
|
|
1496
|
+
}
|
|
1497
|
+
const options = tasks.map((task, index2) => ({
|
|
1498
|
+
value: `${index2}`,
|
|
1499
|
+
label: `${taskId2(task)} \xB7 ${typeof task.title === "string" && task.title.trim() ? task.title.trim() : "Untitled task"}`,
|
|
1500
|
+
hint: typeof task.status === "string" && task.status.trim() ? task.status.trim() : undefined
|
|
1501
|
+
}));
|
|
1502
|
+
const answer = await droneSelect({
|
|
1503
|
+
message: "Select Rig task",
|
|
1504
|
+
options
|
|
1505
|
+
});
|
|
1506
|
+
if (answer === null) {
|
|
1507
|
+
droneCancel("No task selected.");
|
|
1508
|
+
return null;
|
|
1509
|
+
}
|
|
1510
|
+
const index = Number.parseInt(String(answer), 10);
|
|
1511
|
+
return Number.isFinite(index) ? tasks[index] ?? null : null;
|
|
1512
|
+
}
|
|
1513
|
+
var init__task_picker = __esm(() => {
|
|
1514
|
+
init_drone_ui();
|
|
1515
|
+
init__operator_surface();
|
|
1516
|
+
});
|
|
1517
|
+
|
|
1518
|
+
// packages/cli/src/commands/_async-ui.ts
|
|
1519
|
+
import pc from "picocolors";
|
|
1520
|
+
async function withSpinner(label, work, options = {}) {
|
|
1521
|
+
if (options.outputMode === "json") {
|
|
1522
|
+
return work(() => {});
|
|
1523
|
+
}
|
|
1524
|
+
if (activeUpdate) {
|
|
1525
|
+
const outer = activeUpdate;
|
|
1526
|
+
outer(label);
|
|
1527
|
+
return work(outer);
|
|
1528
|
+
}
|
|
1529
|
+
const output = options.output ?? process.stderr;
|
|
1530
|
+
const isTty2 = output.isTTY === true;
|
|
1531
|
+
let lastLabel = label;
|
|
1532
|
+
if (!isTty2) {
|
|
1533
|
+
output.write(`${label}
|
|
1534
|
+
`);
|
|
1535
|
+
const update2 = (next) => {
|
|
1536
|
+
lastLabel = next;
|
|
1537
|
+
};
|
|
1538
|
+
activeUpdate = update2;
|
|
1539
|
+
const previousListener2 = setServerPhaseListener(update2);
|
|
1540
|
+
try {
|
|
1541
|
+
return await work(update2);
|
|
1542
|
+
} finally {
|
|
1543
|
+
activeUpdate = null;
|
|
1544
|
+
setServerPhaseListener(previousListener2);
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
const spinner = createTtySpinner({
|
|
1548
|
+
label,
|
|
1549
|
+
output,
|
|
1550
|
+
frames: MICRO_DRONE_FRAMES,
|
|
1551
|
+
styleFrame: (frame) => renderMicroDroneFrame(Math.max(0, MICRO_DRONE_FRAMES.indexOf(frame)))
|
|
1552
|
+
});
|
|
1553
|
+
const update = (next) => {
|
|
1554
|
+
lastLabel = next;
|
|
1555
|
+
spinner.setLabel(next);
|
|
1556
|
+
};
|
|
1557
|
+
activeUpdate = update;
|
|
1558
|
+
const previousListener = setServerPhaseListener(update);
|
|
1559
|
+
try {
|
|
1560
|
+
const result = await work(update);
|
|
1561
|
+
spinner.stop(options.doneLabel ? `${DONE_SYMBOL} ${options.doneLabel}` : undefined);
|
|
1562
|
+
return result;
|
|
1563
|
+
} catch (error) {
|
|
1564
|
+
spinner.stop(`${FAIL_SYMBOL} ${lastLabel}`);
|
|
1565
|
+
throw error;
|
|
1566
|
+
} finally {
|
|
1567
|
+
activeUpdate = null;
|
|
1568
|
+
setServerPhaseListener(previousListener);
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
var DONE_SYMBOL, FAIL_SYMBOL, activeUpdate = null;
|
|
1572
|
+
var init__async_ui = __esm(() => {
|
|
1573
|
+
init__spinner();
|
|
1574
|
+
init__server_client();
|
|
1575
|
+
init_theme();
|
|
1576
|
+
DONE_SYMBOL = pc.green("\u25C7");
|
|
1577
|
+
FAIL_SYMBOL = pc.red("\u25A0");
|
|
1578
|
+
});
|
|
1579
|
+
|
|
1580
|
+
// packages/cli/src/commands/_pi-frontend.ts
|
|
1581
|
+
import { existsSync as existsSync3, mkdirSync as mkdirSync2, mkdtempSync, readFileSync as readFileSync3, rmSync, writeFileSync as writeFileSync2 } from "fs";
|
|
1582
|
+
import { homedir as homedir2, tmpdir } from "os";
|
|
1583
|
+
import { join } from "path";
|
|
1584
|
+
import { main as runPiMain } from "@earendil-works/pi-coding-agent";
|
|
1585
|
+
import createPiRigExtension from "@rig/pi-rig";
|
|
1586
|
+
function setTemporaryEnv(updates) {
|
|
1587
|
+
const previous = new Map;
|
|
1588
|
+
for (const [key, value] of Object.entries(updates)) {
|
|
1589
|
+
previous.set(key, process.env[key]);
|
|
1590
|
+
process.env[key] = value;
|
|
1591
|
+
}
|
|
1592
|
+
return () => {
|
|
1593
|
+
for (const [key, value] of previous) {
|
|
1594
|
+
if (value === undefined)
|
|
1595
|
+
delete process.env[key];
|
|
1596
|
+
else
|
|
1597
|
+
process.env[key] = value;
|
|
1598
|
+
}
|
|
1599
|
+
};
|
|
1600
|
+
}
|
|
1601
|
+
function buildOperatorPiEnv(input) {
|
|
1602
|
+
return {
|
|
1603
|
+
PI_CODING_AGENT_SESSION_DIR: input.sessionDir,
|
|
1604
|
+
PI_SKIP_VERSION_CHECK: "1",
|
|
1605
|
+
PI_HIDDEN_COMMANDS: "import,fork,clone,tree,new,resume,trust",
|
|
1606
|
+
RIG_PI_OPERATOR_SESSION: "1",
|
|
1607
|
+
RIG_RUN_ID: input.runId,
|
|
1608
|
+
RIG_SERVER_URL: input.serverUrl,
|
|
1609
|
+
...input.authToken ? { RIG_AUTH_TOKEN: input.authToken } : {},
|
|
1610
|
+
...input.serverProjectRoot ? { RIG_PROJECT_ROOT: input.serverProjectRoot } : {}
|
|
1611
|
+
};
|
|
1612
|
+
}
|
|
1613
|
+
async function prepareOperatorConsole(context, runId, tempSessionDir) {
|
|
1614
|
+
const server = await ensureServerForCli(context.projectRoot);
|
|
1615
|
+
const localCwd = join(homedir2(), ".rig", "drones", runId.slice(0, 8));
|
|
1616
|
+
mkdirSync2(localCwd, { recursive: true });
|
|
1617
|
+
trustDroneCwd(localCwd);
|
|
1618
|
+
installRigPiTheme();
|
|
1619
|
+
let sessionFileArg = [];
|
|
1620
|
+
try {
|
|
1621
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/session-file`);
|
|
1622
|
+
if (payload?.ok && typeof payload.content === "string" && payload.content.trim()) {
|
|
1623
|
+
const fileName = typeof payload.fileName === "string" && payload.fileName.trim() ? payload.fileName.replace(/[^A-Za-z0-9._-]/g, "_") : `rig-run-${runId}.jsonl`;
|
|
1624
|
+
const localSessionPath = join(tempSessionDir, fileName);
|
|
1625
|
+
const content = payload.content.split(`
|
|
1626
|
+
`).map((line, index) => {
|
|
1627
|
+
if (index > 0 || !line.trim())
|
|
1628
|
+
return line;
|
|
1629
|
+
try {
|
|
1630
|
+
const header = JSON.parse(line);
|
|
1631
|
+
if (header.type === "session" && typeof header.cwd === "string") {
|
|
1632
|
+
return JSON.stringify({ ...header, cwd: localCwd });
|
|
1633
|
+
}
|
|
1634
|
+
} catch {}
|
|
1635
|
+
return line;
|
|
1636
|
+
}).join(`
|
|
1637
|
+
`);
|
|
1638
|
+
writeFileSync2(localSessionPath, content);
|
|
1639
|
+
sessionFileArg = ["--session", localSessionPath];
|
|
1640
|
+
}
|
|
1641
|
+
} catch {}
|
|
1642
|
+
return { server, sessionFileArg };
|
|
1643
|
+
}
|
|
1644
|
+
function trustDroneCwd(localCwd) {
|
|
1645
|
+
try {
|
|
1646
|
+
const agentDir = join(homedir2(), ".pi", "agent");
|
|
1647
|
+
mkdirSync2(agentDir, { recursive: true });
|
|
1648
|
+
const trustPath = join(agentDir, "trust.json");
|
|
1649
|
+
const store = existsSync3(trustPath) ? JSON.parse(readFileSync3(trustPath, "utf8")) : {};
|
|
1650
|
+
if (store[localCwd] !== true) {
|
|
1651
|
+
store[localCwd] = true;
|
|
1652
|
+
writeFileSync2(trustPath, `${JSON.stringify(store, null, "\t")}
|
|
1653
|
+
`);
|
|
1654
|
+
}
|
|
1655
|
+
} catch {}
|
|
1656
|
+
}
|
|
1657
|
+
function installRigPiTheme() {
|
|
1658
|
+
try {
|
|
1659
|
+
const themesDir = join(homedir2(), ".pi", "agent", "themes");
|
|
1660
|
+
mkdirSync2(themesDir, { recursive: true });
|
|
1661
|
+
const themePath = join(themesDir, "rig.json");
|
|
1662
|
+
const next = `${JSON.stringify(RIG_PI_THEME, null, "\t")}
|
|
1663
|
+
`;
|
|
1664
|
+
if (!existsSync3(themePath) || readFileSync3(themePath, "utf8") !== next) {
|
|
1665
|
+
writeFileSync2(themePath, next);
|
|
1666
|
+
}
|
|
1667
|
+
} catch {}
|
|
1668
|
+
}
|
|
1669
|
+
async function attachRunBundledPiFrontend(context, input) {
|
|
1670
|
+
const tempSessionDir = mkdtempSync(join(tmpdir(), "rig-pi-frontend-sessions-"));
|
|
1671
|
+
const { server, sessionFileArg } = await withSpinner(`Opening Pi console for run ${input.runId}\u2026`, () => prepareOperatorConsole(context, input.runId, tempSessionDir), { outputMode: context.outputMode });
|
|
1672
|
+
const restoreEnv = setTemporaryEnv(buildOperatorPiEnv({
|
|
1673
|
+
runId: input.runId,
|
|
1674
|
+
serverUrl: server.baseUrl,
|
|
1675
|
+
authToken: server.authToken,
|
|
1676
|
+
serverProjectRoot: server.serverProjectRoot,
|
|
1677
|
+
sessionDir: tempSessionDir
|
|
1678
|
+
}));
|
|
1679
|
+
const piRigExtensionFactory = (pi) => {
|
|
1680
|
+
createPiRigExtension(pi);
|
|
1681
|
+
};
|
|
1682
|
+
let detached = false;
|
|
1683
|
+
try {
|
|
1684
|
+
await runPiMain([
|
|
1685
|
+
"--no-extensions",
|
|
1686
|
+
"--no-skills",
|
|
1687
|
+
"--no-prompt-templates",
|
|
1688
|
+
"--no-context-files",
|
|
1689
|
+
...sessionFileArg
|
|
1690
|
+
], {
|
|
1691
|
+
extensionFactories: [piRigExtensionFactory]
|
|
1692
|
+
});
|
|
1693
|
+
detached = true;
|
|
1694
|
+
} finally {
|
|
1695
|
+
restoreEnv();
|
|
1696
|
+
rmSync(tempSessionDir, { recursive: true, force: true });
|
|
1697
|
+
}
|
|
1698
|
+
let run = { runId: input.runId, status: "unknown" };
|
|
1699
|
+
try {
|
|
1700
|
+
run = await getRunDetailsViaServer(context, input.runId);
|
|
1701
|
+
} catch {}
|
|
1702
|
+
return {
|
|
1703
|
+
run,
|
|
1704
|
+
logs: [],
|
|
1705
|
+
timeline: [],
|
|
1706
|
+
timelineCursor: null,
|
|
1707
|
+
steered: input.steered === true,
|
|
1708
|
+
detached,
|
|
1709
|
+
rendered: "stock Pi operator console with the pi-rig extension"
|
|
1710
|
+
};
|
|
1711
|
+
}
|
|
1712
|
+
var RIG_PI_THEME;
|
|
1713
|
+
var init__pi_frontend = __esm(() => {
|
|
1714
|
+
init__server_client();
|
|
1715
|
+
init__async_ui();
|
|
1716
|
+
RIG_PI_THEME = {
|
|
1717
|
+
$schema: "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json",
|
|
1718
|
+
name: "rig",
|
|
1719
|
+
vars: {
|
|
1720
|
+
acid: "#ccff4d",
|
|
1721
|
+
acidDim: "#a9d63f",
|
|
1722
|
+
cyan: "#56d8ff",
|
|
1723
|
+
red: "#ff5d5d",
|
|
1724
|
+
yellow: "#ffd24d",
|
|
1725
|
+
ink: "#f2f3f6",
|
|
1726
|
+
ink2: "#aeb0ba",
|
|
1727
|
+
ink3: "#6c6e79",
|
|
1728
|
+
ink4: "#44464f",
|
|
1729
|
+
panel: "#101115",
|
|
1730
|
+
panelUser: "#14161b",
|
|
1731
|
+
toolPending: "#0e1013",
|
|
1732
|
+
toolSuccess: "#10150c",
|
|
1733
|
+
toolError: "#1a0f0f",
|
|
1734
|
+
customMsg: "#0f1410"
|
|
1735
|
+
},
|
|
1736
|
+
colors: {
|
|
1737
|
+
accent: "acid",
|
|
1738
|
+
border: "ink4",
|
|
1739
|
+
borderAccent: "acid",
|
|
1740
|
+
borderMuted: "ink4",
|
|
1741
|
+
success: "acid",
|
|
1742
|
+
error: "red",
|
|
1743
|
+
warning: "yellow",
|
|
1744
|
+
muted: "ink3",
|
|
1745
|
+
dim: "ink4",
|
|
1746
|
+
text: "ink",
|
|
1747
|
+
thinkingText: "ink3",
|
|
1748
|
+
selectedBg: "panel",
|
|
1749
|
+
userMessageBg: "panelUser",
|
|
1750
|
+
userMessageText: "ink",
|
|
1751
|
+
customMessageBg: "customMsg",
|
|
1752
|
+
customMessageText: "ink2",
|
|
1753
|
+
customMessageLabel: "acidDim",
|
|
1754
|
+
toolPendingBg: "toolPending",
|
|
1755
|
+
toolSuccessBg: "toolSuccess",
|
|
1756
|
+
toolErrorBg: "toolError",
|
|
1757
|
+
toolTitle: "ink",
|
|
1758
|
+
toolOutput: "ink3",
|
|
1759
|
+
mdHeading: "acid",
|
|
1760
|
+
mdLink: "cyan",
|
|
1761
|
+
mdLinkUrl: "ink4",
|
|
1762
|
+
mdCode: "acidDim",
|
|
1763
|
+
mdCodeBlock: "ink2",
|
|
1764
|
+
mdCodeBlockBorder: "ink4",
|
|
1765
|
+
mdQuote: "ink3",
|
|
1766
|
+
mdQuoteBorder: "ink4",
|
|
1767
|
+
mdHr: "ink4",
|
|
1768
|
+
mdListBullet: "acid",
|
|
1769
|
+
toolDiffAdded: "acid",
|
|
1770
|
+
toolDiffRemoved: "red",
|
|
1771
|
+
toolDiffContext: "ink3",
|
|
1772
|
+
syntaxComment: "ink3",
|
|
1773
|
+
syntaxKeyword: "cyan",
|
|
1774
|
+
syntaxFunction: "acid",
|
|
1775
|
+
syntaxVariable: "ink",
|
|
1776
|
+
syntaxString: "acidDim",
|
|
1777
|
+
syntaxNumber: "yellow",
|
|
1778
|
+
syntaxType: "cyan",
|
|
1779
|
+
syntaxOperator: "ink2",
|
|
1780
|
+
syntaxPunctuation: "ink3",
|
|
1781
|
+
thinkingOff: "ink4",
|
|
1782
|
+
thinkingMinimal: "ink3",
|
|
1783
|
+
thinkingLow: "ink2",
|
|
1784
|
+
thinkingMedium: "cyan",
|
|
1785
|
+
thinkingHigh: "acidDim",
|
|
1786
|
+
thinkingXhigh: "acid",
|
|
1787
|
+
bashMode: "cyan"
|
|
1788
|
+
}
|
|
1789
|
+
};
|
|
1790
|
+
});
|
|
1791
|
+
|
|
1792
|
+
// packages/cli/src/commands/_operator-view.ts
|
|
1793
|
+
function runStatusFromPayload(payload) {
|
|
1794
|
+
const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
|
|
1795
|
+
return String(run.status ?? "unknown").toLowerCase();
|
|
1796
|
+
}
|
|
1797
|
+
async function applyOperatorCommand(context, input, deps = {}) {
|
|
1798
|
+
const line = input.line.trim();
|
|
1799
|
+
if (!line)
|
|
1800
|
+
return { action: "ignored" };
|
|
1801
|
+
if (line === "/detach" || line === "/quit" || line === "/q") {
|
|
1802
|
+
return { action: "detach", message: "Detached from run." };
|
|
1803
|
+
}
|
|
1804
|
+
if (line === "/stop") {
|
|
1805
|
+
await (deps.stop ?? stopRunViaServer)(context, input.runId);
|
|
1806
|
+
return { action: "stopped", message: "Stop requested." };
|
|
1807
|
+
}
|
|
1808
|
+
const userMessage = line.startsWith("/user ") ? line.slice("/user ".length).trim() : line;
|
|
1809
|
+
if (!userMessage)
|
|
1810
|
+
return { action: "ignored" };
|
|
1811
|
+
await (deps.steer ?? steerRunViaServer)(context, input.runId, userMessage);
|
|
1812
|
+
return { action: "continue", message: "Steering message queued." };
|
|
1813
|
+
}
|
|
1814
|
+
async function readOperatorSnapshot(context, runId, options = {}) {
|
|
1815
|
+
const run = await getRunDetailsViaServer(context, runId);
|
|
1816
|
+
const logsPage = await getRunLogsViaServer(context, runId, { limit: 100 });
|
|
1817
|
+
const timelinePage = await getRunTimelineViaServer(context, runId, { limit: 200, ...options.timelineCursor ? { cursor: options.timelineCursor } : {} }).catch((error) => ({
|
|
1818
|
+
entries: [{
|
|
1819
|
+
id: `timeline-unavailable:${runId}`,
|
|
1820
|
+
type: "timeline_warning",
|
|
1821
|
+
detail: `Selected Rig server did not provide run timeline events: ${error instanceof Error ? error.message : String(error)}`,
|
|
1822
|
+
createdAt: new Date().toISOString()
|
|
1823
|
+
}],
|
|
1824
|
+
nextCursor: options.timelineCursor ?? null
|
|
1825
|
+
}));
|
|
1826
|
+
const logs = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))).toReversed() : [];
|
|
1827
|
+
const timeline = Array.isArray(timelinePage.entries) ? timelinePage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
|
|
1828
|
+
const timelineCursor = typeof timelinePage.nextCursor === "string" ? timelinePage.nextCursor : options.timelineCursor ?? null;
|
|
1829
|
+
return { run, logs, timeline, timelineCursor, rendered: renderOperatorSnapshot({ run, logs, timeline }) };
|
|
1830
|
+
}
|
|
1831
|
+
async function attachRunOperatorView(context, input) {
|
|
1832
|
+
let steered = false;
|
|
1833
|
+
const attachMessage = input.message?.trim();
|
|
1834
|
+
if (attachMessage) {
|
|
1835
|
+
await withSpinner("Queueing steering message\u2026", () => sendRunPiPromptViaServer(context, input.runId, attachMessage, "steer").catch(() => steerRunViaServer(context, input.runId, attachMessage)), { outputMode: context.outputMode });
|
|
1836
|
+
steered = true;
|
|
1837
|
+
}
|
|
1838
|
+
if (!input.once && input.interactive !== false && context.outputMode === "text" && Boolean(process.stdin.isTTY && process.stdout.isTTY)) {
|
|
1839
|
+
return attachRunBundledPiFrontend(context, {
|
|
1840
|
+
runId: input.runId,
|
|
1841
|
+
steered
|
|
1842
|
+
});
|
|
1843
|
+
}
|
|
1844
|
+
const surface = createOperatorSurface({ interactive: input.interactive !== false });
|
|
1845
|
+
let snapshot = await withSpinner(`Connecting to run ${input.runId}\u2026`, () => readOperatorSnapshot(context, input.runId), { outputMode: context.outputMode });
|
|
1846
|
+
if (context.outputMode === "text") {
|
|
1847
|
+
surface.renderSnapshot(snapshot);
|
|
1848
|
+
surface.renderTimeline(snapshot.timeline);
|
|
1849
|
+
surface.renderLogs(snapshot.logs);
|
|
1850
|
+
if (steered)
|
|
1851
|
+
surface.info("Message submitted to worker Pi.");
|
|
1852
|
+
}
|
|
1853
|
+
let detached = false;
|
|
1854
|
+
let commandInput = null;
|
|
1855
|
+
if (input.follow && !input.once && context.outputMode === "text") {
|
|
1856
|
+
if (input.interactive !== false && process.stdin.isTTY) {
|
|
1857
|
+
surface.info("Controls: /user <message>, /stop, /detach");
|
|
1858
|
+
commandInput = surface.attachCommandInput(async (line) => {
|
|
1859
|
+
const result = await applyOperatorCommand(context, { runId: input.runId, line });
|
|
1860
|
+
if (result.message)
|
|
1861
|
+
surface.info(result.message);
|
|
1862
|
+
if (result.action === "detach" || result.action === "stopped") {
|
|
1863
|
+
detached = true;
|
|
1864
|
+
commandInput?.close();
|
|
1865
|
+
}
|
|
1866
|
+
});
|
|
1867
|
+
}
|
|
1868
|
+
const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
|
|
1869
|
+
let timelineCursor = snapshot.timelineCursor;
|
|
1870
|
+
while (!detached && !TERMINAL_RUN_STATUSES.has(runStatusFromPayload(snapshot.run))) {
|
|
1871
|
+
await Bun.sleep(pollMs);
|
|
1872
|
+
snapshot = await readOperatorSnapshot(context, input.runId, { timelineCursor });
|
|
1873
|
+
timelineCursor = snapshot.timelineCursor;
|
|
1874
|
+
surface.renderSnapshot(snapshot);
|
|
1875
|
+
surface.renderTimeline(snapshot.timeline);
|
|
1876
|
+
surface.renderLogs(snapshot.logs);
|
|
1877
|
+
}
|
|
1878
|
+
commandInput?.close();
|
|
1879
|
+
}
|
|
1880
|
+
return { ...snapshot, steered, detached };
|
|
1881
|
+
}
|
|
1882
|
+
var TERMINAL_RUN_STATUSES;
|
|
1883
|
+
var init__operator_view = __esm(() => {
|
|
1884
|
+
init__server_client();
|
|
1885
|
+
init__operator_surface();
|
|
1886
|
+
init__pi_frontend();
|
|
1887
|
+
init__async_ui();
|
|
1888
|
+
TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
|
|
1889
|
+
});
|
|
1890
|
+
|
|
1891
|
+
// packages/cli/src/commands/_cli-format.ts
|
|
1892
|
+
import pc2 from "picocolors";
|
|
1893
|
+
function stringField2(record, key, fallback = "") {
|
|
1894
|
+
const value = record[key];
|
|
1895
|
+
return typeof value === "string" && value.trim() ? value.trim() : fallback;
|
|
1896
|
+
}
|
|
1897
|
+
function numberField(record, key) {
|
|
1898
|
+
const value = record[key];
|
|
1899
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
1900
|
+
}
|
|
1901
|
+
function arrayField(record, key) {
|
|
1902
|
+
const value = record[key];
|
|
1903
|
+
return Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" && entry.trim() ? [entry.trim()] : []) : [];
|
|
1904
|
+
}
|
|
1905
|
+
function rawObject(record) {
|
|
1906
|
+
const raw = record.raw;
|
|
1907
|
+
return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
|
|
1908
|
+
}
|
|
1909
|
+
function truncate(value, width) {
|
|
1910
|
+
if (value.length <= width)
|
|
1911
|
+
return value;
|
|
1912
|
+
if (width <= 1)
|
|
1913
|
+
return "\u2026";
|
|
1914
|
+
return `${value.slice(0, width - 1)}\u2026`;
|
|
1915
|
+
}
|
|
1916
|
+
function pad(value, width) {
|
|
1917
|
+
return value.length >= width ? value : `${value}${" ".repeat(width - value.length)}`;
|
|
1918
|
+
}
|
|
1919
|
+
function statusColor(status) {
|
|
1920
|
+
const normalized = status.toLowerCase();
|
|
1921
|
+
if (["completed", "merged", "closed", "done", "accepted", "pass", "selected", "approved", "running"].includes(normalized))
|
|
1922
|
+
return accent;
|
|
1923
|
+
if (["failed", "needs_attention", "needs-attention", "blocked", "error", "rejected"].includes(normalized))
|
|
1924
|
+
return red;
|
|
1925
|
+
if (["reviewing", "validating", "in_progress", "in-progress", "remote", "preparing", "closing-out"].includes(normalized))
|
|
1926
|
+
return cyan;
|
|
1927
|
+
if (["ready", "open", "queued", "created", "local", "pending"].includes(normalized))
|
|
1928
|
+
return yellow;
|
|
1929
|
+
return themeDim;
|
|
1930
|
+
}
|
|
1931
|
+
function compactValue(value) {
|
|
1932
|
+
if (value === null || value === undefined)
|
|
1933
|
+
return "";
|
|
1934
|
+
if (typeof value === "string")
|
|
1935
|
+
return value;
|
|
1936
|
+
if (typeof value === "number" || typeof value === "boolean")
|
|
1937
|
+
return String(value);
|
|
1938
|
+
if (Array.isArray(value))
|
|
1939
|
+
return value.map(compactValue).filter(Boolean).join(", ");
|
|
1940
|
+
return JSON.stringify(value);
|
|
1941
|
+
}
|
|
1942
|
+
function shouldUseClackOutput() {
|
|
1943
|
+
return Boolean(process.stdout.isTTY) && process.env.RIG_CLI_PLAIN_HELP !== "1";
|
|
1944
|
+
}
|
|
1945
|
+
function printFormattedOutput(message2, options = {}) {
|
|
1946
|
+
if (!shouldUseClackOutput()) {
|
|
1947
|
+
console.log(message2);
|
|
1948
|
+
return;
|
|
1949
|
+
}
|
|
1950
|
+
droneNote(message2, options.title);
|
|
1951
|
+
}
|
|
1952
|
+
function formatStatusPill(status) {
|
|
1953
|
+
const label = status || "unknown";
|
|
1954
|
+
return statusColor(label)(`\u25CF ${label}`);
|
|
1955
|
+
}
|
|
1956
|
+
function formatSection(title, subtitle) {
|
|
1957
|
+
return `${pc2.bold(accent("\u25C6"))} ${pc2.bold(title)}${subtitle ? themeDim(` \u2014 ${subtitle}`) : ""}`;
|
|
1958
|
+
}
|
|
1959
|
+
function formatSuccessCard(title, rows = []) {
|
|
1960
|
+
const body = rows.filter(([, value]) => value !== undefined && value !== null && String(value).length > 0).map(([key, value]) => `${themeFaint("\u2502")} ${themeDim(key.padEnd(12))} ${value}`);
|
|
1961
|
+
return [formatSection(title), ...body].join(`
|
|
1962
|
+
`);
|
|
1963
|
+
}
|
|
1964
|
+
function formatNextSteps(steps) {
|
|
1965
|
+
if (steps.length === 0)
|
|
1966
|
+
return [];
|
|
1967
|
+
return [pc2.bold("Next"), ...steps.map((step) => `${accent("\u203A")} ${step}`)];
|
|
1968
|
+
}
|
|
1969
|
+
function formatTaskList(tasks, options = {}) {
|
|
1970
|
+
if (options.raw)
|
|
1971
|
+
return tasks.map((task) => JSON.stringify(task)).join(`
|
|
1972
|
+
`);
|
|
1973
|
+
if (tasks.length === 0)
|
|
1974
|
+
return [formatSection("Tasks", "none found"), ...formatNextSteps(["Try `rig server status` to confirm the selected server.", "Relax filters or run `rig task run --title ... --initial-prompt ...` for ad hoc work."])].join(`
|
|
1975
|
+
`);
|
|
1976
|
+
const rows = tasks.map((task) => {
|
|
1977
|
+
const raw = rawObject(task);
|
|
1978
|
+
const id = stringField2(task, "id", "<unknown>");
|
|
1979
|
+
const status = stringField2(task, "status", "unknown");
|
|
1980
|
+
const title = stringField2(task, "title", "Untitled task");
|
|
1981
|
+
const source = stringField2(task, "source", stringField2(raw, "source", ""));
|
|
1982
|
+
const labels = arrayField(task, "labels").length > 0 ? arrayField(task, "labels") : arrayField(raw, "labels");
|
|
1983
|
+
return { id, status, title, source, labels };
|
|
1984
|
+
});
|
|
1985
|
+
const idWidth = Math.min(18, Math.max(4, ...rows.map((row) => row.id.length)));
|
|
1986
|
+
const statusWidth = Math.min(16, Math.max(6, ...rows.map((row) => row.status.length)));
|
|
1987
|
+
const header = `${pc2.bold(pad("TASK", idWidth))} ${pc2.bold(pad("STATUS", statusWidth))} ${pc2.bold("TITLE")}`;
|
|
1988
|
+
const body = rows.map((row) => {
|
|
1989
|
+
const labels = row.labels.length > 0 ? themeDim(` ${row.labels.slice(0, 4).map((label) => `#${label}`).join(" ")}`) : "";
|
|
1990
|
+
const source = row.source ? themeDim(` ${row.source}`) : "";
|
|
1991
|
+
return [
|
|
1992
|
+
pc2.bold(pad(truncate(row.id, idWidth), idWidth)),
|
|
1993
|
+
statusColor(row.status)(pad(truncate(row.status, statusWidth), statusWidth)),
|
|
1994
|
+
`${row.title}${labels}${source}`
|
|
1995
|
+
].join(" ");
|
|
1996
|
+
});
|
|
1997
|
+
return [formatSection("Tasks", `${rows.length} shown`), header, ...body, "", ...formatNextSteps(["Run one: `rig task run <id>` or `rig task run --next`", "Attach later: `rig run attach <run-id> --follow`"])].join(`
|
|
1998
|
+
`);
|
|
1999
|
+
}
|
|
2000
|
+
function formatTaskCard(task, options = {}) {
|
|
2001
|
+
const raw = rawObject(task);
|
|
2002
|
+
const id = stringField2(task, "id", stringField2(raw, "id", "<unknown>"));
|
|
2003
|
+
const status = stringField2(task, "status", stringField2(raw, "status", "unknown"));
|
|
2004
|
+
const title = stringField2(task, "title", stringField2(raw, "title", "Untitled task"));
|
|
2005
|
+
const source = stringField2(task, "source", stringField2(raw, "source", ""));
|
|
2006
|
+
const url = stringField2(task, "url", stringField2(raw, "url", ""));
|
|
2007
|
+
const number = numberField(task, "number") ?? numberField(raw, "number");
|
|
2008
|
+
const labels = arrayField(task, "labels").length > 0 ? arrayField(task, "labels") : arrayField(raw, "labels");
|
|
2009
|
+
const assignees = arrayField(task, "assignees").length > 0 ? arrayField(task, "assignees") : arrayField(raw, "assignees");
|
|
2010
|
+
const readiness = compactValue(task.readiness ?? raw.readiness);
|
|
2011
|
+
const validators = compactValue(task.validators ?? raw.validators ?? task.validation ?? raw.validation);
|
|
2012
|
+
const rows = [
|
|
2013
|
+
["task", pc2.bold(id)],
|
|
2014
|
+
["status", formatStatusPill(status)],
|
|
2015
|
+
["title", title],
|
|
2016
|
+
["source", source],
|
|
2017
|
+
["number", number],
|
|
2018
|
+
["labels", labels.length ? labels.map((label) => `#${label}`).join(" ") : ""],
|
|
2019
|
+
["assignees", assignees.join(", ")],
|
|
2020
|
+
["readiness", readiness],
|
|
2021
|
+
["validators", validators],
|
|
2022
|
+
["url", url]
|
|
2023
|
+
];
|
|
2024
|
+
return [
|
|
2025
|
+
formatSuccessCard(options.title ?? (options.selected ? "Selected task" : "Task"), rows),
|
|
2026
|
+
"",
|
|
2027
|
+
...formatNextSteps([`Start: \`rig task run ${id}\``, `Details: \`rig task show ${id} --raw\``])
|
|
2028
|
+
].join(`
|
|
2029
|
+
`);
|
|
2030
|
+
}
|
|
2031
|
+
function formatTaskDetails(task) {
|
|
2032
|
+
return formatTaskCard(task, { title: "Task details" });
|
|
2033
|
+
}
|
|
2034
|
+
function formatSubmittedRun(input) {
|
|
2035
|
+
const rows = [["run", pc2.bold(input.runId)]];
|
|
2036
|
+
if (input.task) {
|
|
2037
|
+
const id = stringField2(input.task, "id", "<unknown>");
|
|
2038
|
+
const status = stringField2(input.task, "status", "unknown");
|
|
2039
|
+
const title = stringField2(input.task, "title", "Untitled task");
|
|
2040
|
+
rows.push(["task", `${pc2.bold(id)} ${formatStatusPill(status)} ${title}`]);
|
|
2041
|
+
}
|
|
2042
|
+
const runtime = [input.runtimeAdapter || "pi", input.runtimeMode || "full-access", input.interactionMode || "default"].filter(Boolean).join(" \xB7 ");
|
|
2043
|
+
rows.push(["runtime", runtime]);
|
|
2044
|
+
return [
|
|
2045
|
+
formatSuccessCard("Run submitted", rows),
|
|
2046
|
+
"",
|
|
2047
|
+
...formatNextSteps([
|
|
2048
|
+
`Attach: \`rig run attach ${input.runId} --follow\``,
|
|
2049
|
+
`Inspect: \`rig run show ${input.runId}\``,
|
|
2050
|
+
input.detached ? "Submitted detached; attach when you are ready." : "Interactive mode opens the enriched bundled Pi (native UI + Rig layers, worker brain)."
|
|
2051
|
+
])
|
|
2052
|
+
].join(`
|
|
2053
|
+
`);
|
|
2054
|
+
}
|
|
2055
|
+
var themeDim = (value) => ink3(value), themeFaint = (value) => ink4(value);
|
|
2056
|
+
var init__cli_format = __esm(() => {
|
|
2057
|
+
init_drone_ui();
|
|
2058
|
+
init_theme();
|
|
2059
|
+
});
|
|
2060
|
+
|
|
2061
|
+
// packages/cli/src/commands/inbox.ts
|
|
2062
|
+
async function listInboxRecords(context, kind, filters) {
|
|
2063
|
+
const params = new URLSearchParams;
|
|
2064
|
+
if (filters.run)
|
|
2065
|
+
params.set("runId", filters.run);
|
|
2066
|
+
if (filters.task)
|
|
2067
|
+
params.set("taskId", filters.task);
|
|
2068
|
+
const query = params.size > 0 ? `?${params.toString()}` : "";
|
|
2069
|
+
const payload = await requestServerJson(context, `/api/inbox/${kind}${query}`);
|
|
2070
|
+
const records = Array.isArray(payload) ? payload : [];
|
|
2071
|
+
return filters.pendingOnly ? records.filter((entry) => (entry.status ?? "pending") !== "resolved") : records;
|
|
2072
|
+
}
|
|
2073
|
+
async function readPendingInboxCounts(context) {
|
|
2074
|
+
try {
|
|
2075
|
+
const [approvals, inputs] = await Promise.all([
|
|
2076
|
+
listInboxRecords(context, "approvals", { pendingOnly: true }),
|
|
2077
|
+
listInboxRecords(context, "inputs", { pendingOnly: true })
|
|
2078
|
+
]);
|
|
2079
|
+
return { approvals: approvals.length, inputs: inputs.length };
|
|
2080
|
+
} catch {
|
|
2081
|
+
return null;
|
|
2082
|
+
}
|
|
2083
|
+
}
|
|
2084
|
+
async function printPendingInboxFooter(context) {
|
|
2085
|
+
if (context.outputMode !== "text")
|
|
2086
|
+
return;
|
|
2087
|
+
const counts = await readPendingInboxCounts(context);
|
|
2088
|
+
if (!counts || counts.approvals === 0 && counts.inputs === 0)
|
|
2089
|
+
return;
|
|
2090
|
+
const parts = [];
|
|
2091
|
+
if (counts.approvals > 0)
|
|
2092
|
+
parts.push(`${counts.approvals} approval${counts.approvals === 1 ? "" : "s"}`);
|
|
2093
|
+
if (counts.inputs > 0)
|
|
2094
|
+
parts.push(`${counts.inputs} input request${counts.inputs === 1 ? "" : "s"}`);
|
|
2095
|
+
console.log(`
|
|
2096
|
+
\u26A0 ${parts.join(" and ")} pending \u2014 run \`rig inbox\` to review.`);
|
|
2097
|
+
}
|
|
2098
|
+
var init_inbox = __esm(() => {
|
|
2099
|
+
init_runner();
|
|
2100
|
+
init__cli_format();
|
|
2101
|
+
init__server_client();
|
|
2102
|
+
init__async_ui();
|
|
2103
|
+
});
|
|
2104
|
+
|
|
2105
|
+
// packages/cli/src/commands/_help-catalog.ts
|
|
2106
|
+
import pc3 from "picocolors";
|
|
2107
|
+
function heading(title) {
|
|
2108
|
+
return pc3.bold(pc3.cyan(title));
|
|
2109
|
+
}
|
|
2110
|
+
function commandLine(command, description) {
|
|
2111
|
+
const commandColumn = command.length >= 38 ? `${command} ` : command.padEnd(38);
|
|
2112
|
+
return `${pc3.dim("\u2502")} ${pc3.bold(commandColumn)} ${description}`;
|
|
2113
|
+
}
|
|
2114
|
+
function renderCommandBlock(commands) {
|
|
2115
|
+
return commands.map((entry) => commandLine(entry.command, entry.description)).join(`
|
|
2116
|
+
`);
|
|
2117
|
+
}
|
|
2118
|
+
function renderGroup(group) {
|
|
2119
|
+
const lines = [
|
|
2120
|
+
`${heading(`rig ${group.name}`)} \u2014 ${group.summary}`,
|
|
2121
|
+
"",
|
|
2122
|
+
pc3.bold("Usage"),
|
|
2123
|
+
...group.usage.map((line) => ` ${line}`),
|
|
2124
|
+
"",
|
|
2125
|
+
pc3.bold("Commands"),
|
|
2126
|
+
...group.commands.map((entry) => commandLine(entry.command, entry.description))
|
|
2127
|
+
];
|
|
2128
|
+
if (group.examples?.length) {
|
|
2129
|
+
lines.push("", pc3.bold("Examples"), ...group.examples.map((line) => ` ${pc3.dim("$")} ${line}`));
|
|
2130
|
+
}
|
|
2131
|
+
if (group.next?.length) {
|
|
2132
|
+
lines.push("", pc3.bold("Next steps"), ...group.next.map((line) => ` ${pc3.dim("\u203A")} ${line}`));
|
|
2133
|
+
}
|
|
2134
|
+
if (group.advanced?.length) {
|
|
2135
|
+
lines.push("", pc3.bold("Compatibility / advanced"), ...group.advanced.map((line) => ` ${pc3.dim("\u203A")} ${line}`));
|
|
2136
|
+
}
|
|
2137
|
+
return lines.join(`
|
|
2138
|
+
`);
|
|
2139
|
+
}
|
|
2140
|
+
function renderTopLevelHelp() {
|
|
2141
|
+
return [
|
|
2142
|
+
`${heading("rig")} ${pc3.dim("\u2014 server-owned task/run control plane for Pi-backed engineering work")}`,
|
|
2143
|
+
pc3.dim("The loop: pick a task, dispatch an agent, open its Pi console (`rig run attach <id>`) to watch and steer it live, clear inbox gates, merge."),
|
|
2144
|
+
"",
|
|
2145
|
+
...TOP_LEVEL_SECTIONS.flatMap((section) => [
|
|
2146
|
+
`${pc3.bold(pc3.magenta(`\u25C7 ${section.title}`))} \u2014 ${pc3.dim(section.subtitle)}`,
|
|
2147
|
+
renderCommandBlock(section.commands),
|
|
2148
|
+
""
|
|
2149
|
+
]),
|
|
2150
|
+
pc3.dim("More: `rig help --advanced` for dev/compatibility commands; `rig <group> --help` for rich per-group help; `rig --version` for the installed version."),
|
|
2151
|
+
"",
|
|
2152
|
+
pc3.bold("Global options"),
|
|
2153
|
+
commandLine("--project <path>", "Use a project root instead of auto-discovery."),
|
|
2154
|
+
commandLine("--json", "Emit structured output for scripts/agents."),
|
|
2155
|
+
commandLine("--dry-run", "Print the command plan without mutating state.")
|
|
2156
|
+
].join(`
|
|
2157
|
+
`).trimEnd();
|
|
2158
|
+
}
|
|
2159
|
+
function renderGroupHelp(groupName) {
|
|
2160
|
+
const group = ALL_GROUPS.find((candidate) => candidate.name === groupName);
|
|
2161
|
+
return group ? renderGroup(group) : null;
|
|
2162
|
+
}
|
|
2163
|
+
function printGroupHelpDocument(groupName) {
|
|
2164
|
+
console.log(renderGroupHelp(groupName) ?? renderTopLevelHelp());
|
|
2165
|
+
}
|
|
2166
|
+
var TOP_LEVEL_SECTIONS, PRIMARY_GROUPS, ADVANCED_GROUPS, ALL_GROUPS;
|
|
2167
|
+
var init__help_catalog = __esm(() => {
|
|
2168
|
+
TOP_LEVEL_SECTIONS = [
|
|
2169
|
+
{
|
|
2170
|
+
title: "Pi console",
|
|
2171
|
+
subtitle: "the operator surface \u2014 every attach opens the run's FULL Pi session",
|
|
2172
|
+
commands: [
|
|
2173
|
+
{ command: "rig run attach <run-id>", description: "Open the run's Pi console: complete transcript (live AND finished runs), worker turns streaming in live." },
|
|
2174
|
+
{ command: "type a message", description: "Inside the console, plain text steers the worker mid-turn \u2014 it lands in the agent's context, not a local model." },
|
|
2175
|
+
{ command: "!<command>", description: "Inside the console, runs shell in the WORKER's workspace; output streams back into the transcript." },
|
|
2176
|
+
{ command: "/<command>", description: "The palette includes the WORKER session's slash commands ([worker]-tagged) next to /rig." },
|
|
2177
|
+
{ command: "/rig abort | /rig stop", description: "Abort the worker's current turn, or stop the whole run, from inside the console." },
|
|
2178
|
+
{ command: "rig run steer <id> --message <text>", description: "Steer without attaching \u2014 queue a message; the worker picks it up within seconds." }
|
|
2179
|
+
]
|
|
2180
|
+
},
|
|
2181
|
+
{
|
|
2182
|
+
title: "Start here",
|
|
2183
|
+
subtitle: "one-time setup, pick a server",
|
|
2184
|
+
commands: [
|
|
2185
|
+
{ command: "rig init", description: "Wizard: config, GitHub auth, task source, server, Pi wiring." },
|
|
2186
|
+
{ command: "rig server use <alias|local>", description: "Pick which Rig server owns this repo (`rig server list` to see them)." },
|
|
2187
|
+
{ command: "rig server status", description: "Show the selected server for this repo." }
|
|
2188
|
+
]
|
|
2189
|
+
},
|
|
2190
|
+
{
|
|
2191
|
+
title: "Work",
|
|
2192
|
+
subtitle: "find a task, put an agent on it, answer what it asks",
|
|
2193
|
+
commands: [
|
|
2194
|
+
{ command: "rig task list", description: "What's on the board (from the selected source/server)." },
|
|
2195
|
+
{ command: "rig task run --next", description: "Dispatch an agent on the next ready task; interactive mode drops you into its Pi console." },
|
|
2196
|
+
{ command: "rig run status", description: "Active and recent runs at a glance." },
|
|
2197
|
+
{ command: "rig run attach <id> --follow", description: "Same as plain attach \u2014 the Pi console is always the interactive surface." },
|
|
2198
|
+
{ command: "rig inbox approvals", description: "Approvals workers are waiting on (then `rig inbox approve \u2026`)." }
|
|
2199
|
+
]
|
|
2200
|
+
},
|
|
2201
|
+
{
|
|
2202
|
+
title: "Watch",
|
|
2203
|
+
subtitle: "fleet metrics and per-task forensics",
|
|
2204
|
+
commands: [
|
|
2205
|
+
{ command: "rig stats [--since 7d]", description: "Fleet metrics: completion/failure rates, median run time, steering, stalls." },
|
|
2206
|
+
{ command: "rig inspect logs --task <id>", description: "Latest run log for a task." },
|
|
2207
|
+
{ command: "rig inspect diff --task <id>", description: "Changed files for a task." }
|
|
2208
|
+
]
|
|
2209
|
+
},
|
|
2210
|
+
{
|
|
2211
|
+
title: "Unblock",
|
|
2212
|
+
subtitle: "diagnose wiring, fix auth",
|
|
2213
|
+
commands: [
|
|
2214
|
+
{ command: "rig doctor", description: "Check every part of the wiring \u2014 run this when anything feels off." },
|
|
2215
|
+
{ command: "rig github auth status", description: "GitHub auth state on the selected server." }
|
|
2216
|
+
]
|
|
2217
|
+
},
|
|
2218
|
+
{
|
|
2219
|
+
title: "Extend",
|
|
2220
|
+
subtitle: "plugins contribute validators, hooks, task sources, commands",
|
|
2221
|
+
commands: [
|
|
2222
|
+
{ command: "rig plugin list", description: "What the rig.config.ts plugins contribute." },
|
|
2223
|
+
{ command: "rig plugin run <command-id>", description: "Execute a plugin-contributed CLI command." }
|
|
2224
|
+
]
|
|
2225
|
+
}
|
|
2226
|
+
];
|
|
2227
|
+
PRIMARY_GROUPS = [
|
|
2228
|
+
{
|
|
2229
|
+
name: "server",
|
|
2230
|
+
summary: "Choose, inspect, and start the Rig server that owns tasks and runs.",
|
|
2231
|
+
usage: ["rig server <status|list|add|use|start> [options]"],
|
|
2232
|
+
commands: [
|
|
2233
|
+
{ command: "status", description: "Show the selected server for this repo.", primary: true },
|
|
2234
|
+
{ command: "use local", description: "Switch this repo to the local Rig server.", primary: true },
|
|
2235
|
+
{ command: "add <alias> <url>", description: "Save a remote Rig server URL.", primary: true },
|
|
2236
|
+
{ command: "use <alias>", description: "Select a saved remote server alias.", primary: true },
|
|
2237
|
+
{ command: "list", description: "List saved local/remote server aliases.", primary: true },
|
|
2238
|
+
{ command: "start [--host <host>] [--port <n>]", description: "Start a local rig-server process." }
|
|
2239
|
+
],
|
|
2240
|
+
examples: [
|
|
2241
|
+
"rig server status",
|
|
2242
|
+
"rig server add prod https://where.rig-does.work",
|
|
2243
|
+
"rig server use prod",
|
|
2244
|
+
"rig server use local",
|
|
2245
|
+
"rig server start --port 3773"
|
|
2246
|
+
],
|
|
2247
|
+
next: ["Use `rig task list` to see server-owned work.", "Use `rig run list` or `rig run attach <id> --follow` to monitor runs."]
|
|
2248
|
+
},
|
|
2249
|
+
{
|
|
2250
|
+
name: "task",
|
|
2251
|
+
summary: "Find work, start Pi-backed runs, and validate task results.",
|
|
2252
|
+
usage: ["rig task <list|next|show|run> [options]"],
|
|
2253
|
+
commands: [
|
|
2254
|
+
{ command: "list [--assignee <login|me|@me>] [--state open|closed]", description: "List tasks from the selected server/source.", primary: true },
|
|
2255
|
+
{ command: "next [filters]", description: "Render the next matching task as a selected-task card.", primary: true },
|
|
2256
|
+
{ command: "show <id>|--task <id> [--raw]", description: "Show a human task summary; --raw prints the full payload.", primary: true },
|
|
2257
|
+
{ command: "run [#<issue>|<task-id>|--next|--task <id>]", description: "Submit a task run; interactive follows with bundled Pi.", primary: true },
|
|
2258
|
+
{ command: "ready", description: "List task IDs that are runnable now." },
|
|
2259
|
+
{ command: "validate|verify [--task <id>]", description: "Run configured task checks/review gates." },
|
|
2260
|
+
{ command: "details --task <id>", description: "Show full task info from the configured source." },
|
|
2261
|
+
{ command: "reopen [--task <id> | --all] [--reason <text>]", description: "Reopen closed task(s) in the configured source." },
|
|
2262
|
+
{ command: "artifacts|artifact-dir|artifact-write", description: "Inspect or write task artifacts." },
|
|
2263
|
+
{ command: "report-bug", description: "Create a structured bug report/task." }
|
|
2264
|
+
],
|
|
2265
|
+
examples: [
|
|
2266
|
+
"rig task list --assignee @me --limit 20",
|
|
2267
|
+
"rig task next",
|
|
2268
|
+
"rig task show 123 --raw",
|
|
2269
|
+
"rig task run --next",
|
|
2270
|
+
"rig task run #123 --runtime-adapter pi",
|
|
2271
|
+
"rig task run --title 'Investigate deploy drift' --initial-prompt 'Check server health'"
|
|
2272
|
+
],
|
|
2273
|
+
next: ["Use `--detach` to submit without attaching.", "Use `rig run attach <run-id> --follow` to rejoin a live run."]
|
|
2274
|
+
},
|
|
2275
|
+
{
|
|
2276
|
+
name: "run",
|
|
2277
|
+
summary: "Observe, attach to, and control Rig runs. `attach` opens the Pi console \u2014 the full worker session, live.",
|
|
2278
|
+
usage: ["rig run <list|status|show|attach|steer|stop|resume|restart> [options]"],
|
|
2279
|
+
commands: [
|
|
2280
|
+
{ command: "list", description: "List recent runs from the selected server or local state.", primary: true },
|
|
2281
|
+
{ command: "status", description: "Render active and recent run groups.", primary: true },
|
|
2282
|
+
{ command: "show <id>|--run <id> [--raw]", description: "Show a human run summary; --raw prints the full payload.", primary: true },
|
|
2283
|
+
{ command: "attach <run-id>|--run <id>", description: "Open the run's Pi console \u2014 see 'Inside the console' below. Works on live AND finished runs.", primary: true },
|
|
2284
|
+
{ command: "steer <run-id> --message <text>", description: "Queue a steering message into a live worker without attaching \u2014 delivered into the agent's context within seconds.", primary: true },
|
|
2285
|
+
{ command: "stop [<run-id>|--run <id>]", description: "Request stop for one run or local active runs.", primary: true },
|
|
2286
|
+
{ command: "resume [<run-id>]", description: "Resume an interrupted run on the selected server (defaults to the most recent resumable)." },
|
|
2287
|
+
{ command: "restart [<run-id>]", description: "Re-dispatch a run from a clean runtime, reopening its Pi session where possible." },
|
|
2288
|
+
{ command: "timeline --run <id> [--follow]", description: "Stream raw run timeline events (scripts; humans should attach)." },
|
|
2289
|
+
{ command: "replay <run-id>|--run <id> [--with-session]", description: "Print the run's consolidated run.jsonl as a merged timeline; --with-session interleaves the Pi session log." },
|
|
2290
|
+
{ command: "delete|cleanup", description: "Remove completed run records/artifacts." }
|
|
2291
|
+
],
|
|
2292
|
+
examples: [
|
|
2293
|
+
"rig run attach <run-id> # full session console \u2014 live mirror, steering, worker shell",
|
|
2294
|
+
"rig run steer <run-id> --message 'focus on the failing test first'",
|
|
2295
|
+
"rig run list",
|
|
2296
|
+
"rig run show <run-id>",
|
|
2297
|
+
"rig run stop <run-id>"
|
|
2298
|
+
],
|
|
2299
|
+
next: [
|
|
2300
|
+
"Inside the console: the run's COMPLETE transcript loads on open (finished runs too), and new worker turns stream in live.",
|
|
2301
|
+
"Inside the console: plain text = steering into the worker's context \xB7 !<cmd> = shell in the WORKER workspace \xB7 /<cmd> includes the worker session's commands \xB7 /rig abort stops the current turn.",
|
|
2302
|
+
"The console is read-write but remote-only: nothing runs on your machine; the worker keeps running when you exit.",
|
|
2303
|
+
"Use `rig task run --next` to create a new run; interactive mode drops you straight into its console.",
|
|
2304
|
+
"Use `--json` when scripts need the full structured record."
|
|
2305
|
+
]
|
|
2306
|
+
},
|
|
2307
|
+
{
|
|
2308
|
+
name: "inbox",
|
|
2309
|
+
summary: "Review approval and user-input requests that block worker runs.",
|
|
2310
|
+
usage: ["rig inbox <approvals|approve|inputs|respond> [options]"],
|
|
2311
|
+
commands: [
|
|
2312
|
+
{ command: "approvals [--run <id>] [--task <id>]", description: "List pending approvals.", primary: true },
|
|
2313
|
+
{ command: "inputs [--run <id>] [--task <id>]", description: "List pending user-input requests.", primary: true },
|
|
2314
|
+
{ command: "approve --run <id> --request <id> --decision approve|reject", description: "Resolve an approval request." },
|
|
2315
|
+
{ command: "respond --run <id> --request <id> --answer key=value", description: "Answer a user-input request." }
|
|
2316
|
+
],
|
|
2317
|
+
examples: [
|
|
2318
|
+
"rig inbox approvals",
|
|
2319
|
+
"rig inbox inputs --run <run-id>",
|
|
2320
|
+
"rig inbox approve --run <run-id> --request <request-id> --decision approve"
|
|
2321
|
+
],
|
|
2322
|
+
next: ["Rejoin the run after resolving a block: `rig run attach <run-id> --follow`."]
|
|
2323
|
+
},
|
|
2324
|
+
{
|
|
2325
|
+
name: "stats",
|
|
2326
|
+
summary: "Fleet metrics computed from on-disk run journals (no server required).",
|
|
2327
|
+
usage: ["rig stats [show] [--since <7d|30d|ISO date>]"],
|
|
2328
|
+
commands: [
|
|
2329
|
+
{ command: "show [--since <window>]", description: "Total runs, completion/failure/needs-attention rates, median run time, steering, stalls, approvals.", primary: true }
|
|
2330
|
+
],
|
|
2331
|
+
examples: [
|
|
2332
|
+
"rig stats",
|
|
2333
|
+
"rig stats --since 7d",
|
|
2334
|
+
"rig stats --since 2026-06-01 --json"
|
|
2335
|
+
],
|
|
2336
|
+
next: ["Inspect outliers with `rig run list` and `rig run show <run-id>`.", "Use `--json` for the schema'd envelope (see docs/cli-json.md)."]
|
|
2337
|
+
},
|
|
2338
|
+
{
|
|
2339
|
+
name: "inspect",
|
|
2340
|
+
summary: "Inspect logs, artifacts, graphs, failures for a task.",
|
|
2341
|
+
usage: ["rig inspect <logs|artifacts|failures|graph|audit|diff> --task <id>"],
|
|
2342
|
+
commands: [
|
|
2343
|
+
{ command: "logs --task <id>", description: "Latest run log for a task (local or selected server).", primary: true },
|
|
2344
|
+
{ command: "artifacts --task <id>", description: "List the task's completion artifacts.", primary: true },
|
|
2345
|
+
{ command: "failures --task <id>", description: "Recorded failures for a task.", primary: true },
|
|
2346
|
+
{ command: "diff --task <id>", description: "Changed files for a task.", primary: true },
|
|
2347
|
+
{ command: "graph", description: "Task dependency graph." },
|
|
2348
|
+
{ command: "audit", description: "Controlled-command audit trail." }
|
|
2349
|
+
],
|
|
2350
|
+
examples: ["rig inspect logs --task <id>", "rig inspect diff --task <id>"],
|
|
2351
|
+
next: ["Use `rig stats` for fleet-level metrics across runs."]
|
|
2352
|
+
},
|
|
2353
|
+
{
|
|
2354
|
+
name: "repo",
|
|
2355
|
+
summary: "Repository sync/baseline helpers for the Rig-managed checkout.",
|
|
2356
|
+
usage: ["rig repo <sync|reset-baseline>"],
|
|
2357
|
+
commands: [
|
|
2358
|
+
{ command: "sync", description: "Sync project repository state.", primary: true },
|
|
2359
|
+
{ command: "reset-baseline", description: "Reset the managed baseline for the repo." }
|
|
2360
|
+
],
|
|
2361
|
+
examples: ["rig repo sync"]
|
|
2362
|
+
},
|
|
2363
|
+
{
|
|
2364
|
+
name: "plugin",
|
|
2365
|
+
summary: "Plugin listing, validation, and plugin-contributed commands.",
|
|
2366
|
+
usage: ["rig plugin <list|validate|run> [options]"],
|
|
2367
|
+
commands: [
|
|
2368
|
+
{ command: "list", description: "List plugins declared in rig.config.ts and their contributions.", primary: true },
|
|
2369
|
+
{ command: "validate --task <id>", description: "Run plugin-contributed validators for a task.", primary: true },
|
|
2370
|
+
{ command: "run <command-id> [args...]", description: "Execute a plugin-contributed CLI command (also callable as `rig <command-id>`)." }
|
|
2371
|
+
],
|
|
2372
|
+
examples: ["rig plugin list", "rig plugin run <command-id>"]
|
|
2373
|
+
},
|
|
2374
|
+
{
|
|
2375
|
+
name: "init",
|
|
2376
|
+
summary: "Set up Rig for this repo: server, GitHub auth, checkout strategy, task source, and Pi wiring.",
|
|
2377
|
+
usage: ["rig init [--yes] [--server local|remote] [--repo owner/repo] [--remote-url <url>]"],
|
|
2378
|
+
commands: [
|
|
2379
|
+
{ command: "init", description: "Interactive setup wizard for a new or existing Rig repo.", primary: true },
|
|
2380
|
+
{ command: "init --demo", description: "Offline demo project: files task source + 3 sample tasks, zero GitHub.", primary: true },
|
|
2381
|
+
{ command: "init --yes", description: "Non-interactive setup using detected/default settings.", primary: true },
|
|
2382
|
+
{ command: "init --server remote --remote-url <url>", description: "Link this repo to a remote Rig server.", primary: true },
|
|
2383
|
+
{ command: "init --repair", description: "Repair missing private state without replacing project config." }
|
|
2384
|
+
],
|
|
2385
|
+
examples: [
|
|
2386
|
+
"rig init",
|
|
2387
|
+
"rig init --demo",
|
|
2388
|
+
"rig init --yes --repo humanity-org/humanwork",
|
|
2389
|
+
"rig init --server remote --remote-url https://where.rig-does.work --repo owner/repo"
|
|
2390
|
+
],
|
|
2391
|
+
next: ["After init, run `rig server status`.", "Then use `rig task list` and `rig task run --next` for day-to-day work."]
|
|
2392
|
+
},
|
|
2393
|
+
{
|
|
2394
|
+
name: "doctor",
|
|
2395
|
+
summary: "Diagnostics for project/server/GitHub/Pi state.",
|
|
2396
|
+
usage: ["rig doctor"],
|
|
2397
|
+
commands: [
|
|
2398
|
+
{ command: "doctor", description: "Run setup and runtime diagnostics.", primary: true },
|
|
2399
|
+
{ command: "check", description: "Compatibility spelling for diagnostics." }
|
|
2400
|
+
],
|
|
2401
|
+
examples: ["rig doctor", "rig doctor --json"],
|
|
2402
|
+
next: ["Use `rig server status` and `rig github auth status` to inspect common failure points."]
|
|
2403
|
+
},
|
|
2404
|
+
{
|
|
2405
|
+
name: "github",
|
|
2406
|
+
summary: "GitHub auth helpers for the selected Rig server.",
|
|
2407
|
+
usage: ["rig github auth <status|import-gh|token>"],
|
|
2408
|
+
commands: [
|
|
2409
|
+
{ command: "auth status", description: "Show GitHub auth state.", primary: true },
|
|
2410
|
+
{ command: "auth import-gh", description: "Import the current `gh` token into the selected server." },
|
|
2411
|
+
{ command: "auth token --token <token>", description: "Store a token on the selected server." }
|
|
2412
|
+
],
|
|
2413
|
+
examples: ["rig github auth status", "rig github auth import-gh"],
|
|
2414
|
+
next: ["After auth is valid, use `rig task run --next`."]
|
|
2415
|
+
}
|
|
2416
|
+
];
|
|
2417
|
+
ADVANCED_GROUPS = [
|
|
2418
|
+
{ name: "setup", summary: "Bootstrap/check local setup.", usage: ["rig setup <bootstrap|check|preflight>"], commands: [{ command: "bootstrap|check|preflight", description: "Setup helpers." }] },
|
|
2419
|
+
{ name: "profile", summary: "Runtime profile/model defaults.", usage: ["rig profile <show|set>"], commands: [{ command: "show", description: "Show active profile." }] },
|
|
2420
|
+
{
|
|
2421
|
+
name: "review",
|
|
2422
|
+
summary: "Inspect or change completion review gate policy.",
|
|
2423
|
+
usage: ["rig review <show|set>"],
|
|
2424
|
+
commands: [
|
|
2425
|
+
{ command: "show", description: "Show current review gate settings." },
|
|
2426
|
+
{ command: "set <off|advisory|required> [--provider greptile]", description: "Change review strictness/provider." }
|
|
2427
|
+
],
|
|
2428
|
+
examples: ["rig review show", "rig review set required --provider greptile"],
|
|
2429
|
+
next: ["Use `rig inbox approvals` for blocked run handoffs."]
|
|
2430
|
+
},
|
|
2431
|
+
{
|
|
2432
|
+
name: "browser",
|
|
2433
|
+
summary: "Browser/app diagnostics for browser-required tasks.",
|
|
2434
|
+
usage: ["rig browser <help|explain|demo|app|hp-next> [options]"],
|
|
2435
|
+
commands: [
|
|
2436
|
+
{ command: "help", description: "Rich browser command help (canonical: `rig browser help`)." },
|
|
2437
|
+
{ command: "explain", description: "Explain the browser-required task contract." },
|
|
2438
|
+
{ command: "demo", description: "Run browser demo flows against a local page." },
|
|
2439
|
+
{ command: "app", description: "Launch the Rig Browser workstation app." },
|
|
2440
|
+
{ command: "hp-next <dev|check|e2e|reset>", description: "Drive the hp-next browser test harness." }
|
|
2441
|
+
]
|
|
2442
|
+
},
|
|
2443
|
+
{
|
|
2444
|
+
name: "pi",
|
|
2445
|
+
summary: "Manage Pi extension packages for this project (community extensions from npm/git).",
|
|
2446
|
+
usage: ["rig pi <list|add|remove|search> [args]"],
|
|
2447
|
+
commands: [
|
|
2448
|
+
{ command: "list", description: "Show project and user Pi extension packages." },
|
|
2449
|
+
{ command: "add <source>", description: "Add an npm/git Pi extension to .pi/settings.json (auto-installs at next session)." },
|
|
2450
|
+
{ command: "remove <source>", description: "Remove an operator-added Pi extension." },
|
|
2451
|
+
{ command: "search [term]", description: "Discover Pi extension packages on the npm registry." }
|
|
2452
|
+
],
|
|
2453
|
+
examples: ["rig pi search subagents", "rig pi add pi-subagents", "rig pi list"],
|
|
2454
|
+
next: ["Config-managed extensions: declare `runtime: { pi: { packages: [...] } }` in rig.config.ts \u2014 workers pick them up automatically."]
|
|
2455
|
+
},
|
|
2456
|
+
{ name: "queue", summary: "Run task queues locally.", usage: ["rig queue run [options]"], commands: [{ command: "run", description: "Process queue work." }] },
|
|
2457
|
+
{ name: "agent", summary: "Runtime agent workspace helpers.", usage: ["rig agent <list|prepare|run|cleanup>"], commands: [{ command: "list", description: "List prepared agents." }] },
|
|
2458
|
+
{ name: "inspector", summary: "Event stream and drift scanners.", usage: ["rig inspector <stream|scan-upstream-drift>"], commands: [{ command: "stream", description: "Stream events." }] },
|
|
2459
|
+
{ name: "dist", summary: "Build/install packaged Rig CLI.", usage: ["rig dist <build|install|doctor>"], commands: [{ command: "build", description: "Build distribution." }] },
|
|
2460
|
+
{ name: "workspace", summary: "Workspace topology/service helpers.", usage: ["rig workspace <summary|topology|remote-hosts>"], commands: [{ command: "summary", description: "Show workspace summary." }] },
|
|
2461
|
+
{ name: "remote", summary: "Compatibility remote orchestration controls.", usage: ["rig remote <status|watch|pause|resume|...>"], commands: [{ command: "status", description: "Show remote state." }] },
|
|
2462
|
+
{ name: "git", summary: "Pass through to Rig git-flow helper.", usage: ["rig git <args...>"], commands: [{ command: "<args...>", description: "Advanced git flow operations." }] },
|
|
2463
|
+
{ name: "harness", summary: "Pass through to runtime harness CLI.", usage: ["rig harness <args...>"], commands: [{ command: "<args...>", description: "Advanced harness operations." }] },
|
|
2464
|
+
{ name: "test", summary: "Project test wrappers.", usage: ["rig test <unit|e2e|all>"], commands: [{ command: "all", description: "Run configured project tests." }] }
|
|
2465
|
+
];
|
|
2466
|
+
ALL_GROUPS = [...PRIMARY_GROUPS, ...ADVANCED_GROUPS];
|
|
2467
|
+
});
|
|
2468
|
+
|
|
2469
|
+
// packages/cli/src/commands/task.ts
|
|
2470
|
+
var exports_task = {};
|
|
2471
|
+
__export(exports_task, {
|
|
2472
|
+
loadTaskRunProjectDefaults: () => loadTaskRunProjectDefaults,
|
|
2473
|
+
executeTask: () => executeTask
|
|
2474
|
+
});
|
|
2475
|
+
import { readFileSync as readFileSync4 } from "fs";
|
|
2476
|
+
import { spawnSync } from "child_process";
|
|
2477
|
+
import { resolve as resolve3 } from "path";
|
|
2478
|
+
import {
|
|
2479
|
+
taskArtifactDir,
|
|
2480
|
+
taskArtifacts,
|
|
2481
|
+
taskArtifactWrite,
|
|
2482
|
+
taskDeps,
|
|
2483
|
+
taskInfo,
|
|
2484
|
+
taskLookup,
|
|
2485
|
+
taskReady,
|
|
2486
|
+
taskRecord,
|
|
2487
|
+
taskReopen,
|
|
2488
|
+
taskScope,
|
|
2489
|
+
taskStatus as taskStatus2,
|
|
2490
|
+
taskValidate,
|
|
2491
|
+
taskVerify
|
|
2492
|
+
} from "@rig/runtime/control-plane/native/task-ops";
|
|
2493
|
+
import { buildPluginHostContext } from "@rig/runtime/control-plane/plugin-host-context";
|
|
2494
|
+
import { loadConfig } from "@rig/core/load-config";
|
|
2495
|
+
async function readStdin() {
|
|
2496
|
+
const chunks = [];
|
|
2497
|
+
for await (const chunk of process.stdin) {
|
|
2498
|
+
chunks.push(Buffer.from(chunk));
|
|
2499
|
+
}
|
|
2500
|
+
return Buffer.concat(chunks).toString("utf-8");
|
|
2501
|
+
}
|
|
2502
|
+
function normalizeAssigneeAlias(value) {
|
|
2503
|
+
if (!value)
|
|
2504
|
+
return;
|
|
2505
|
+
return value.trim().toLowerCase() === "me" ? "@me" : value;
|
|
2506
|
+
}
|
|
2507
|
+
function parseTaskFilters(args) {
|
|
2508
|
+
let pending = args;
|
|
2509
|
+
const assigneeResult = takeOption(pending, "--assignee");
|
|
2510
|
+
pending = assigneeResult.rest;
|
|
2511
|
+
const stateResult = takeOption(pending, "--state");
|
|
2512
|
+
pending = stateResult.rest;
|
|
2513
|
+
const statusResult = takeOption(pending, "--status");
|
|
2514
|
+
pending = statusResult.rest;
|
|
2515
|
+
const limitResult = takeOption(pending, "--limit");
|
|
2516
|
+
pending = limitResult.rest;
|
|
2517
|
+
const assignee = normalizeAssigneeAlias(assigneeResult.value);
|
|
2518
|
+
const limit = (() => {
|
|
2519
|
+
if (!limitResult.value)
|
|
2520
|
+
return;
|
|
2521
|
+
const parsed = Number.parseInt(limitResult.value, 10);
|
|
2522
|
+
if (!Number.isFinite(parsed) || parsed < 1) {
|
|
2523
|
+
throw new CliError("--limit must be a positive integer.", 2, { hint: "Re-run with a positive number, e.g. `rig task list --limit 20`." });
|
|
2524
|
+
}
|
|
2525
|
+
return parsed;
|
|
2526
|
+
})();
|
|
2527
|
+
const filters = {
|
|
2528
|
+
...assignee ? { assignee } : {},
|
|
2529
|
+
...stateResult.value ? { state: stateResult.value } : {},
|
|
2530
|
+
...statusResult.value ? { status: statusResult.value } : {},
|
|
2531
|
+
...limit !== undefined ? { limit } : {}
|
|
2532
|
+
};
|
|
2533
|
+
return { filters, rest: pending };
|
|
2534
|
+
}
|
|
2535
|
+
function mapConfiguredRuntimeMode(mode) {
|
|
2536
|
+
if (!mode)
|
|
2537
|
+
return;
|
|
2538
|
+
return mode === "yolo" ? "full-access" : mode;
|
|
2539
|
+
}
|
|
2540
|
+
async function loadTaskRunProjectDefaults(projectRoot) {
|
|
2541
|
+
try {
|
|
2542
|
+
const config = await loadConfig(projectRoot);
|
|
2543
|
+
return {
|
|
2544
|
+
runtimeAdapter: config.runtime?.harness,
|
|
2545
|
+
model: config.runtime?.model,
|
|
2546
|
+
runtimeMode: mapConfiguredRuntimeMode(config.runtime?.mode),
|
|
2547
|
+
prMode: config.pr?.mode
|
|
2548
|
+
};
|
|
2549
|
+
} catch {
|
|
2550
|
+
return {};
|
|
2551
|
+
}
|
|
2552
|
+
}
|
|
2553
|
+
function normalizePrMode(value) {
|
|
2554
|
+
if (!value)
|
|
2555
|
+
return;
|
|
2556
|
+
if (value === "auto" || value === "ask" || value === "off")
|
|
2557
|
+
return value;
|
|
2558
|
+
throw new CliError("--pr must be auto, ask, or off.", 2, { hint: "Re-run with `--pr auto|ask|off`, or pass `--no-pr` to disable the PR." });
|
|
2559
|
+
}
|
|
2560
|
+
function detectLocalDirtyState(projectRoot) {
|
|
2561
|
+
const result = spawnSync("git", ["-C", projectRoot, "status", "--porcelain"], { encoding: "utf8", timeout: 5000 });
|
|
2562
|
+
if (result.status !== 0)
|
|
2563
|
+
return { dirty: false, modified: 0, untracked: 0, lines: [] };
|
|
2564
|
+
const lines = result.stdout.split(/\r?\n/).map((line) => line.trimEnd()).filter(Boolean);
|
|
2565
|
+
return {
|
|
2566
|
+
dirty: lines.length > 0,
|
|
2567
|
+
modified: lines.filter((line) => !line.startsWith("?? ")).length,
|
|
2568
|
+
untracked: lines.filter((line) => line.startsWith("?? ")).length,
|
|
2569
|
+
lines
|
|
2570
|
+
};
|
|
2571
|
+
}
|
|
2572
|
+
function selectedServerKind(projectRoot) {
|
|
2573
|
+
try {
|
|
2574
|
+
return resolveSelectedConnection(projectRoot)?.connection.kind === "remote" ? "remote" : "local";
|
|
2575
|
+
} catch {
|
|
2576
|
+
return "local";
|
|
2577
|
+
}
|
|
2578
|
+
}
|
|
2579
|
+
async function resolveDirtyBaselineForTaskRun(context, explicit) {
|
|
2580
|
+
if (explicit && explicit !== "head" && explicit !== "dirty-snapshot") {
|
|
2581
|
+
throw new CliError("--dirty-baseline must be head or dirty-snapshot.", 2, { hint: "Re-run with `--dirty-baseline head` or `--dirty-baseline dirty-snapshot`." });
|
|
2582
|
+
}
|
|
2583
|
+
if (selectedServerKind(context.projectRoot) !== "local") {
|
|
2584
|
+
return { mode: explicit === "dirty-snapshot" ? "dirty-snapshot" : "head", state: null };
|
|
2585
|
+
}
|
|
2586
|
+
const state = detectLocalDirtyState(context.projectRoot);
|
|
2587
|
+
if (!state.dirty)
|
|
2588
|
+
return { mode: "head", state };
|
|
2589
|
+
if (context.outputMode === "text") {
|
|
2590
|
+
console.log(`Repo state: dirty (${state.modified} modified, ${state.untracked} untracked).`);
|
|
2591
|
+
}
|
|
2592
|
+
if (explicit)
|
|
2593
|
+
return { mode: explicit, state };
|
|
2594
|
+
if (context.outputMode === "text" && process.stdin.isTTY && process.stdout.isTTY) {
|
|
2595
|
+
const answer = await droneConfirm({
|
|
2596
|
+
message: "Include current uncommitted changes in run baseline?",
|
|
2597
|
+
initialValue: false
|
|
2598
|
+
});
|
|
2599
|
+
if (answer === null) {
|
|
2600
|
+
droneCancel("Run cancelled.");
|
|
2601
|
+
throw new CliError("Run cancelled by user.", 1);
|
|
2602
|
+
}
|
|
2603
|
+
return { mode: answer ? "dirty-snapshot" : "head", state };
|
|
2604
|
+
}
|
|
2605
|
+
return { mode: "head", state };
|
|
2606
|
+
}
|
|
2607
|
+
function normalizeTaskRunTaskId(value) {
|
|
2608
|
+
const trimmed = value?.trim() ?? "";
|
|
2609
|
+
if (!trimmed)
|
|
2610
|
+
return null;
|
|
2611
|
+
const issueNumber = trimmed.match(/^#(\d+)$/)?.[1];
|
|
2612
|
+
return issueNumber ?? trimmed;
|
|
2613
|
+
}
|
|
2614
|
+
function readTaskId(task) {
|
|
2615
|
+
return typeof task.id === "string" && task.id.trim().length > 0 ? task.id : null;
|
|
2616
|
+
}
|
|
2617
|
+
function readTaskString(task, key) {
|
|
2618
|
+
const value = task[key];
|
|
2619
|
+
return typeof value === "string" && value.trim().length > 0 ? value : null;
|
|
2620
|
+
}
|
|
2621
|
+
function summarizeTask(task, options = {}) {
|
|
2622
|
+
const raw = task.raw && typeof task.raw === "object" && !Array.isArray(task.raw) ? task.raw : null;
|
|
2623
|
+
return {
|
|
2624
|
+
id: readTaskId(task),
|
|
2625
|
+
title: readTaskString(task, "title"),
|
|
2626
|
+
status: readTaskString(task, "status"),
|
|
2627
|
+
source: typeof task.source === "string" ? task.source : undefined,
|
|
2628
|
+
url: typeof raw?.url === "string" ? raw.url : undefined,
|
|
2629
|
+
number: typeof raw?.number === "number" ? raw.number : undefined,
|
|
2630
|
+
labels: Array.isArray(task.labels) ? task.labels : Array.isArray(raw?.labels) ? raw.labels : undefined,
|
|
2631
|
+
assignees: Array.isArray(raw?.assignees) ? raw.assignees : undefined,
|
|
2632
|
+
readiness: typeof task.readiness === "string" || typeof task.readiness === "boolean" ? task.readiness : undefined,
|
|
2633
|
+
validators: Array.isArray(task.validators) ? task.validators : Array.isArray(task.validation) ? task.validation : undefined,
|
|
2634
|
+
...options.raw ? { raw: raw ?? task } : {}
|
|
2635
|
+
};
|
|
2636
|
+
}
|
|
2637
|
+
async function validatorRegistryForTaskCommands(projectRoot) {
|
|
2638
|
+
return buildPluginHostContext(projectRoot).then((ctx) => ctx?.validatorRegistry ?? undefined).catch(() => {
|
|
2639
|
+
return;
|
|
2640
|
+
});
|
|
2641
|
+
}
|
|
2642
|
+
async function executeTask(context, args, options) {
|
|
2643
|
+
if (args.length === 0) {
|
|
2644
|
+
if (context.outputMode === "text") {
|
|
2645
|
+
printGroupHelpDocument("task");
|
|
2646
|
+
}
|
|
2647
|
+
return { ok: true, group: "task", command: "help" };
|
|
2648
|
+
}
|
|
2649
|
+
const [command = "help", ...rest] = args;
|
|
2650
|
+
switch (command) {
|
|
2651
|
+
case "list": {
|
|
2652
|
+
let pending = rest;
|
|
2653
|
+
const rawResult = takeFlag(pending, "--raw");
|
|
2654
|
+
pending = rawResult.rest;
|
|
2655
|
+
const { filters, rest: remaining } = parseTaskFilters(pending);
|
|
2656
|
+
requireNoExtraArgs(remaining, "rig task list [--raw] [--assignee <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
|
|
2657
|
+
const tasks = await withSpinner("Reading tasks from server\u2026", () => listWorkspaceTasksViaServer(context, filters), { outputMode: context.outputMode });
|
|
2658
|
+
if (context.outputMode === "text") {
|
|
2659
|
+
const renderedTasks = rawResult.value ? tasks.map((task) => summarizeTask(task, { raw: true })) : tasks.map((task) => summarizeTask(task));
|
|
2660
|
+
printFormattedOutput(formatTaskList(renderedTasks, { raw: rawResult.value }));
|
|
2661
|
+
await printPendingInboxFooter(context);
|
|
2662
|
+
}
|
|
2663
|
+
return {
|
|
2664
|
+
ok: true,
|
|
2665
|
+
group: "task",
|
|
2666
|
+
command,
|
|
2667
|
+
details: { count: tasks.length, filters, raw: rawResult.value, tasks: tasks.map((task) => summarizeTask(task, { raw: rawResult.value })) }
|
|
2668
|
+
};
|
|
2669
|
+
}
|
|
2670
|
+
case "show": {
|
|
2671
|
+
let pending = rest;
|
|
2672
|
+
const rawResult = takeFlag(pending, "--raw");
|
|
2673
|
+
pending = rawResult.rest;
|
|
2674
|
+
const taskOption = takeOption(pending, "--task");
|
|
2675
|
+
const positional = taskOption.rest.length > 0 && taskOption.rest[0] && !taskOption.rest[0].startsWith("-") ? taskOption.rest[0] : undefined;
|
|
2676
|
+
const remaining = positional ? taskOption.rest.slice(1) : taskOption.rest;
|
|
2677
|
+
requireNoExtraArgs(remaining, "rig task show <id>|--task <id> [--raw]");
|
|
2678
|
+
const taskId3 = normalizeTaskRunTaskId(taskOption.value ?? positional);
|
|
2679
|
+
if (!taskId3)
|
|
2680
|
+
throw new CliError("task show requires a task id.", 2, { hint: "Run `rig task list` to find ids, then `rig task show <id>`." });
|
|
2681
|
+
const task = await withSpinner(`Reading task ${taskId3} from server\u2026`, () => getWorkspaceTaskViaServer(context, taskId3), { outputMode: context.outputMode });
|
|
2682
|
+
if (!task)
|
|
2683
|
+
throw new CliError(`Task not found: ${taskId3}`, 3, { hint: "Run `rig task list` to see available tasks." });
|
|
2684
|
+
const summary = summarizeTask(task, { raw: true });
|
|
2685
|
+
if (context.outputMode === "text") {
|
|
2686
|
+
printFormattedOutput(rawResult.value ? JSON.stringify(summary, null, 2) : formatTaskDetails(summary));
|
|
2687
|
+
}
|
|
2688
|
+
return { ok: true, group: "task", command, details: { task: summary, raw: rawResult.value } };
|
|
2689
|
+
}
|
|
2690
|
+
case "next": {
|
|
2691
|
+
const { filters, rest: remaining } = parseTaskFilters(rest);
|
|
2692
|
+
requireNoExtraArgs(remaining, "rig task next [--assignee <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
|
|
2693
|
+
const selected = await withSpinner("Selecting next ready task\u2026", () => selectNextWorkspaceTaskViaServer(context, filters), { outputMode: context.outputMode });
|
|
2694
|
+
if (context.outputMode === "text") {
|
|
2695
|
+
if (selected.task) {
|
|
2696
|
+
printFormattedOutput(formatTaskCard(summarizeTask(selected.task, { raw: true }), { title: "Selected task", selected: true }));
|
|
2697
|
+
} else {
|
|
2698
|
+
printFormattedOutput("No matching tasks.\n\nNext\n\u203A Try `rig task list` to inspect available work.\n\u203A Check server: `rig server status`");
|
|
2699
|
+
}
|
|
2700
|
+
}
|
|
2701
|
+
return {
|
|
2702
|
+
ok: true,
|
|
2703
|
+
group: "task",
|
|
2704
|
+
command,
|
|
2705
|
+
details: {
|
|
2706
|
+
count: selected.count,
|
|
2707
|
+
filters,
|
|
2708
|
+
task: selected.task ? summarizeTask(selected.task) : null
|
|
2709
|
+
}
|
|
2710
|
+
};
|
|
2711
|
+
}
|
|
2712
|
+
case "info": {
|
|
2713
|
+
const { value: task, rest: remaining } = takeOption(rest, "--task");
|
|
2714
|
+
requireNoExtraArgs(remaining, "rig task info [--task <task-id>]");
|
|
2715
|
+
await withMutedConsole(context.outputMode === "json", () => taskInfo(context.projectRoot, task || undefined));
|
|
2716
|
+
return { ok: true, group: "task", command, details: { task: task || null } };
|
|
2717
|
+
}
|
|
2718
|
+
case "scope": {
|
|
2719
|
+
const filesFlag = takeFlag(rest, "--files");
|
|
2720
|
+
const { value: task, rest: remaining } = takeOption(filesFlag.rest, "--task");
|
|
2721
|
+
requireNoExtraArgs(remaining, "rig task scope [--task <id>] [--files]");
|
|
2722
|
+
await withMutedConsole(context.outputMode === "json", () => taskScope(context.projectRoot, filesFlag.value, task || undefined));
|
|
2723
|
+
return { ok: true, group: "task", command, details: { files: filesFlag.value, task: task || null } };
|
|
2724
|
+
}
|
|
2725
|
+
case "deps":
|
|
2726
|
+
requireNoExtraArgs(rest, "rig task deps");
|
|
2727
|
+
await withMutedConsole(context.outputMode === "json", () => taskDeps(context.projectRoot));
|
|
2728
|
+
return { ok: true, group: "task", command };
|
|
2729
|
+
case "status":
|
|
2730
|
+
requireNoExtraArgs(rest, "rig task status");
|
|
2731
|
+
withMutedConsole(context.outputMode === "json", () => taskStatus2(context.projectRoot));
|
|
2732
|
+
return { ok: true, group: "task", command };
|
|
2733
|
+
case "artifacts":
|
|
2734
|
+
requireNoExtraArgs(rest, "rig task artifacts");
|
|
2735
|
+
withMutedConsole(context.outputMode === "json", () => taskArtifacts(context.projectRoot));
|
|
2736
|
+
return { ok: true, group: "task", command };
|
|
2737
|
+
case "artifact-dir": {
|
|
2738
|
+
requireNoExtraArgs(rest, "rig task artifact-dir");
|
|
2739
|
+
const path = taskArtifactDir(context.projectRoot);
|
|
2740
|
+
if (context.outputMode === "text") {
|
|
2741
|
+
console.log(path);
|
|
2742
|
+
}
|
|
2743
|
+
return { ok: true, group: "task", command, details: { path } };
|
|
2744
|
+
}
|
|
2745
|
+
case "artifact-write": {
|
|
2746
|
+
if (rest.length < 1) {
|
|
2747
|
+
throw new CliError(`Usage: rig task artifact-write <filename> [--file <path>]
|
|
2748
|
+
` + ` Reads content from stdin (or --file), writes to the active task artifact dir.
|
|
2749
|
+
` + " Example: echo '...' | rig task artifact-write collection-audit.md");
|
|
2750
|
+
}
|
|
2751
|
+
const artifactFilename = rest[0];
|
|
2752
|
+
const fileFlag = takeOption(rest.slice(1), "--file");
|
|
2753
|
+
let content;
|
|
2754
|
+
if (fileFlag.value) {
|
|
2755
|
+
content = readFileSync4(resolve3(context.projectRoot, fileFlag.value), "utf-8");
|
|
2756
|
+
} else {
|
|
2757
|
+
content = await readStdin();
|
|
2758
|
+
}
|
|
2759
|
+
if (!artifactFilename) {
|
|
2760
|
+
throw new CliError("Usage: rig task artifact-write <filename> [--file path]");
|
|
2761
|
+
}
|
|
2762
|
+
withMutedConsole(context.outputMode === "json", () => taskArtifactWrite(context.projectRoot, artifactFilename, content));
|
|
2763
|
+
return { ok: true, group: "task", command, details: { filename: artifactFilename } };
|
|
2764
|
+
}
|
|
2765
|
+
case "report-bug":
|
|
2766
|
+
return options.executeTaskReportBug(context, rest);
|
|
2767
|
+
case "lookup": {
|
|
2768
|
+
if (rest.length !== 1) {
|
|
2769
|
+
throw new CliError("Usage: rig task lookup <task-id>");
|
|
2770
|
+
}
|
|
2771
|
+
const lookupId = rest[0];
|
|
2772
|
+
if (!lookupId) {
|
|
2773
|
+
throw new CliError("Usage: rig task lookup <task-id>");
|
|
2774
|
+
}
|
|
2775
|
+
const result = taskLookup(context.projectRoot, lookupId);
|
|
2776
|
+
if (context.outputMode === "text") {
|
|
2777
|
+
console.log(result);
|
|
2778
|
+
}
|
|
2779
|
+
return { ok: true, group: "task", command, details: { id: lookupId, result } };
|
|
2780
|
+
}
|
|
2781
|
+
case "record": {
|
|
2782
|
+
if (rest.length < 2) {
|
|
2783
|
+
throw new CliError("Usage: rig task record <decision|failure> <text>");
|
|
2784
|
+
}
|
|
2785
|
+
const type = rest[0];
|
|
2786
|
+
if (type !== "decision" && type !== "failure") {
|
|
2787
|
+
throw new CliError("Usage: rig task record <decision|failure> <text>");
|
|
2788
|
+
}
|
|
2789
|
+
withMutedConsole(context.outputMode === "json", () => taskRecord(context.projectRoot, type, rest.slice(1).join(" ")));
|
|
2790
|
+
return { ok: true, group: "task", command, details: { type: rest[0] } };
|
|
2791
|
+
}
|
|
2792
|
+
case "ready":
|
|
2793
|
+
requireNoExtraArgs(rest, "rig task ready");
|
|
2794
|
+
await withMutedConsole(context.outputMode === "json", () => taskReady(context.projectRoot));
|
|
2795
|
+
return { ok: true, group: "task", command };
|
|
2796
|
+
case "run": {
|
|
2797
|
+
let pending = rest;
|
|
2798
|
+
const nextResult = takeFlag(pending, "--next");
|
|
2799
|
+
pending = nextResult.rest;
|
|
2800
|
+
const taskResult = takeOption(pending, "--task");
|
|
2801
|
+
pending = taskResult.rest;
|
|
2802
|
+
const titleResult = takeOption(pending, "--title");
|
|
2803
|
+
pending = titleResult.rest;
|
|
2804
|
+
const runtimeAdapterResult = takeOption(pending, "--runtime-adapter");
|
|
2805
|
+
pending = runtimeAdapterResult.rest;
|
|
2806
|
+
const modelResult = takeOption(pending, "--model");
|
|
2807
|
+
pending = modelResult.rest;
|
|
2808
|
+
const runtimeModeResult = takeOption(pending, "--runtime-mode");
|
|
2809
|
+
pending = runtimeModeResult.rest;
|
|
2810
|
+
const interactionModeResult = takeOption(pending, "--interaction-mode");
|
|
2811
|
+
pending = interactionModeResult.rest;
|
|
2812
|
+
const initialPromptResult = takeOption(pending, "--initial-prompt");
|
|
2813
|
+
pending = initialPromptResult.rest;
|
|
2814
|
+
const prResult = takeOption(pending, "--pr");
|
|
2815
|
+
pending = prResult.rest;
|
|
2816
|
+
const noPrResult = takeFlag(pending, "--no-pr");
|
|
2817
|
+
pending = noPrResult.rest;
|
|
2818
|
+
const dirtyBaselineResult = takeOption(pending, "--dirty-baseline");
|
|
2819
|
+
pending = dirtyBaselineResult.rest;
|
|
2820
|
+
const skipProjectSyncResult = takeFlag(pending, "--skip-project-sync");
|
|
2821
|
+
pending = skipProjectSyncResult.rest;
|
|
2822
|
+
const detachResult = takeFlag(pending, "--detach");
|
|
2823
|
+
pending = detachResult.rest;
|
|
2824
|
+
const filterResult = parseTaskFilters(pending);
|
|
2825
|
+
pending = filterResult.rest;
|
|
2826
|
+
const positionalTaskId = pending.length > 0 && pending[0] && !pending[0].startsWith("-") ? normalizeTaskRunTaskId(pending[0]) : null;
|
|
2827
|
+
if (positionalTaskId) {
|
|
2828
|
+
pending = pending.slice(1);
|
|
2829
|
+
}
|
|
2830
|
+
requireNoExtraArgs(pending, "rig task run [#<issue>|<task-id>] [--next] [--task <id>] [--detach] [--assignee <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>] [--title <text>] [--runtime-adapter claude-code|codex|pi] [--model <model>] [--runtime-mode <mode>] [--interaction-mode <mode>] [--initial-prompt <text>] [--pr auto|ask|off] [--no-pr] [--dirty-baseline head|dirty-snapshot] [--skip-project-sync]");
|
|
2831
|
+
if (nextResult.value && (taskResult.value || positionalTaskId)) {
|
|
2832
|
+
throw new CliError("task run cannot combine --next with an explicit task id.", 2, { hint: "Use either `rig task run --next` or `rig task run <id>`." });
|
|
2833
|
+
}
|
|
2834
|
+
if (taskResult.value && positionalTaskId) {
|
|
2835
|
+
throw new CliError("task run cannot combine positional task id with --task <id>.", 2, { hint: "Pass the id once, e.g. `rig task run <id>`." });
|
|
2836
|
+
}
|
|
2837
|
+
if (prResult.value && noPrResult.value) {
|
|
2838
|
+
throw new CliError("task run cannot combine --pr with --no-pr.", 2, { hint: "Use `--pr auto|ask|off` or `--no-pr`, not both." });
|
|
2839
|
+
}
|
|
2840
|
+
let selectedTask = null;
|
|
2841
|
+
let selectedTaskId = normalizeTaskRunTaskId(taskResult.value) ?? positionalTaskId;
|
|
2842
|
+
if (nextResult.value) {
|
|
2843
|
+
const selected = await withSpinner("Selecting next ready task\u2026", () => selectNextWorkspaceTaskViaServer(context, filterResult.filters), { outputMode: context.outputMode });
|
|
2844
|
+
selectedTask = selected.task;
|
|
2845
|
+
selectedTaskId = selected.task ? readTaskId(selected.task) : null;
|
|
2846
|
+
if (!selectedTaskId) {
|
|
2847
|
+
throw new CliError("No matching task found for task run --next.", 3, { hint: "Run `rig task list` to inspect available work, or relax the filters." });
|
|
2848
|
+
}
|
|
2849
|
+
}
|
|
2850
|
+
if (!selectedTaskId && !initialPromptResult.value && !titleResult.value) {
|
|
2851
|
+
if (context.outputMode !== "text" || !process.stdin.isTTY || !process.stdout.isTTY) {
|
|
2852
|
+
throw new CliError("task run requires an interactive terminal to pick a task; pass --next, --task <id>, or --initial-prompt/--title for an ad hoc run.", 2);
|
|
2853
|
+
}
|
|
2854
|
+
const tasks = await withSpinner("Reading tasks from server\u2026", () => listWorkspaceTasksViaServer(context, filterResult.filters), { outputMode: context.outputMode });
|
|
2855
|
+
selectedTask = await selectTaskWithTextPicker(tasks);
|
|
2856
|
+
selectedTaskId = selectedTask ? readTaskId(selectedTask) : null;
|
|
2857
|
+
if (!selectedTaskId) {
|
|
2858
|
+
throw new CliError("No task selected.", 3, { hint: "Run `rig task run --next` for the next ready task, or `rig task run --task <id>`." });
|
|
2859
|
+
}
|
|
2860
|
+
}
|
|
2861
|
+
await runProjectMainSyncPreflight(context, { disabled: skipProjectSyncResult.value });
|
|
2862
|
+
const projectDefaults = await loadTaskRunProjectDefaults(context.projectRoot);
|
|
2863
|
+
const runtimeAdapter = normalizeRuntimeAdapter(runtimeAdapterResult.value ?? projectDefaults.runtimeAdapter);
|
|
2864
|
+
await withSpinner("Running task-run preflight\u2026", () => runFastTaskRunPreflight(context, {
|
|
2865
|
+
taskId: selectedTaskId,
|
|
2866
|
+
runtimeAdapter
|
|
2867
|
+
}), { outputMode: context.outputMode });
|
|
2868
|
+
const dirtyBaseline = await resolveDirtyBaselineForTaskRun(context, dirtyBaselineResult.value);
|
|
2869
|
+
const prMode = noPrResult.value ? "off" : normalizePrMode(prResult.value) ?? projectDefaults.prMode;
|
|
2870
|
+
const submitted = await withSpinner("Dispatching run\u2026", () => submitTaskRunViaServer(context, {
|
|
2871
|
+
runId: context.runId,
|
|
2872
|
+
taskId: selectedTaskId ?? undefined,
|
|
2873
|
+
title: titleResult.value ?? undefined,
|
|
2874
|
+
runtimeAdapter,
|
|
2875
|
+
model: modelResult.value ?? projectDefaults.model,
|
|
2876
|
+
runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
|
|
2877
|
+
interactionMode: interactionModeResult.value || "default",
|
|
2878
|
+
initialPrompt: initialPromptResult.value ?? undefined,
|
|
2879
|
+
baselineMode: dirtyBaseline.mode,
|
|
2880
|
+
prMode
|
|
2881
|
+
}), { outputMode: context.outputMode });
|
|
2882
|
+
let attachDetails = null;
|
|
2883
|
+
if (!detachResult.value && context.outputMode === "text") {
|
|
2884
|
+
printFormattedOutput(formatSubmittedRun({
|
|
2885
|
+
runId: submitted.runId,
|
|
2886
|
+
task: selectedTask ? summarizeTask(selectedTask) : null,
|
|
2887
|
+
runtimeAdapter,
|
|
2888
|
+
runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
|
|
2889
|
+
interactionMode: interactionModeResult.value || "default",
|
|
2890
|
+
detached: false
|
|
2891
|
+
}));
|
|
2892
|
+
attachDetails = await attachRunOperatorView(context, { runId: submitted.runId, follow: true });
|
|
2893
|
+
} else if (context.outputMode === "text") {
|
|
2894
|
+
printFormattedOutput(formatSubmittedRun({
|
|
2895
|
+
runId: submitted.runId,
|
|
2896
|
+
task: selectedTask ? summarizeTask(selectedTask) : null,
|
|
2897
|
+
runtimeAdapter,
|
|
2898
|
+
runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
|
|
2899
|
+
interactionMode: interactionModeResult.value || "default",
|
|
2900
|
+
detached: true
|
|
2901
|
+
}));
|
|
2902
|
+
}
|
|
2903
|
+
return {
|
|
2904
|
+
ok: true,
|
|
2905
|
+
group: "task",
|
|
2906
|
+
command,
|
|
2907
|
+
details: {
|
|
2908
|
+
runId: submitted.runId,
|
|
2909
|
+
taskId: selectedTaskId,
|
|
2910
|
+
title: titleResult.value ?? null,
|
|
2911
|
+
selectedTask: selectedTask ? summarizeTask(selectedTask) : null,
|
|
2912
|
+
filters: nextResult.value ? filterResult.filters : undefined,
|
|
2913
|
+
attached: Boolean(attachDetails),
|
|
2914
|
+
attach: attachDetails,
|
|
2915
|
+
runtimeAdapter,
|
|
2916
|
+
model: modelResult.value ?? projectDefaults.model ?? null,
|
|
2917
|
+
runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
|
|
2918
|
+
prMode: prMode ?? null,
|
|
2919
|
+
dirtyBaseline: { mode: dirtyBaseline.mode, dirty: dirtyBaseline.state?.dirty ?? false }
|
|
2920
|
+
}
|
|
2921
|
+
};
|
|
2922
|
+
}
|
|
2923
|
+
case "validate": {
|
|
2924
|
+
const { value: task, rest: remaining } = takeOption(rest, "--task");
|
|
2925
|
+
requireNoExtraArgs(remaining, "rig task validate [--task <task-id>]");
|
|
2926
|
+
if (context.dryRun) {
|
|
2927
|
+
await context.runCommand(["rig", "task", "validate", ...task ? ["--task", task] : []]);
|
|
2928
|
+
return { ok: true, group: "task", command, details: { task: task || "active" } };
|
|
2929
|
+
}
|
|
2930
|
+
const ok = await withMutedConsole(context.outputMode === "json", async () => taskValidate(context.projectRoot, task || undefined, await validatorRegistryForTaskCommands(context.projectRoot)));
|
|
2931
|
+
if (!ok) {
|
|
2932
|
+
throw new CliError(`Validation failed for ${task || "active task"}.`, 2, { hint: "Inspect failures with `rig inspect failures --task <id>`, fix, then re-run `rig task validate --task <id>`." });
|
|
2933
|
+
}
|
|
2934
|
+
return { ok: true, group: "task", command, details: { task: task || "active" } };
|
|
2935
|
+
}
|
|
2936
|
+
case "verify": {
|
|
2937
|
+
const { value: task, rest: remaining } = takeOption(rest, "--task");
|
|
2938
|
+
requireNoExtraArgs(remaining, "rig task verify [--task <task-id>]");
|
|
2939
|
+
if (context.dryRun) {
|
|
2940
|
+
await context.runCommand(["rig", "task", "verify", ...task ? ["--task", task] : []]);
|
|
2941
|
+
return { ok: true, group: "task", command, details: { task: task || "active" } };
|
|
2942
|
+
}
|
|
2943
|
+
const ok = await withMutedConsole(context.outputMode === "json", () => taskVerify(context.projectRoot, task || undefined));
|
|
2944
|
+
if (!ok) {
|
|
2945
|
+
throw new CliError(`Verification rejected for ${task || "active task"}.`, 2, { hint: "Check `rig inspect logs --task <id>`, address the rejection, then re-run `rig task verify --task <id>`." });
|
|
2946
|
+
}
|
|
2947
|
+
return { ok: true, group: "task", command, details: { task: task || "active" } };
|
|
2948
|
+
}
|
|
2949
|
+
case "details": {
|
|
2950
|
+
const { value: task, rest: remaining } = takeOption(rest, "--task");
|
|
2951
|
+
requireNoExtraArgs(remaining, "rig task details --task <task-id>");
|
|
2952
|
+
const requiredTask = requireTask(task, "rig task details --task <task-id>");
|
|
2953
|
+
await withMutedConsole(context.outputMode === "json", () => taskInfo(context.projectRoot, requiredTask));
|
|
2954
|
+
return { ok: true, group: "task", command, details: { task: requiredTask } };
|
|
2955
|
+
}
|
|
2956
|
+
case "reopen": {
|
|
2957
|
+
const { value: task, rest: rest1 } = takeOption(rest, "--task");
|
|
2958
|
+
const allFlag = takeFlag(rest1, "--all");
|
|
2959
|
+
const { rest: remaining } = takeOption(allFlag.rest, "--reason");
|
|
2960
|
+
requireNoExtraArgs(remaining, "rig task reopen [--task <id> | --all] [--reason <text>]");
|
|
2961
|
+
if (!allFlag.value && !task) {
|
|
2962
|
+
throw new CliError("Usage: rig task reopen [--task <id> | --all] [--reason <text>]");
|
|
2963
|
+
}
|
|
2964
|
+
const summary = withMutedConsole(context.outputMode === "json", () => taskReopen(context.projectRoot, {
|
|
2965
|
+
all: allFlag.value,
|
|
2966
|
+
taskId: task || undefined,
|
|
2967
|
+
dryRun: false
|
|
2968
|
+
}));
|
|
2969
|
+
return { ok: true, group: "task", command, details: summary };
|
|
2970
|
+
}
|
|
2971
|
+
default:
|
|
2972
|
+
if (command === "reset") {
|
|
2973
|
+
throw new CliError("Unknown task command: reset", 1, { hint: "Use `rig task reopen --task <id>`." });
|
|
2974
|
+
}
|
|
2975
|
+
throw new CliError(`Unknown task command: ${command}`, 1, { hint: "Run `rig task --help` to list available task commands." });
|
|
2976
|
+
}
|
|
2977
|
+
}
|
|
2978
|
+
var init_task = __esm(() => {
|
|
2979
|
+
init_drone_ui();
|
|
2980
|
+
init_runner();
|
|
2981
|
+
init__authority_runs();
|
|
2982
|
+
init__preflight();
|
|
2983
|
+
init__server_client();
|
|
2984
|
+
init__task_picker();
|
|
2985
|
+
init__async_ui();
|
|
2986
|
+
init__operator_view();
|
|
2987
|
+
init__cli_format();
|
|
2988
|
+
init_inbox();
|
|
2989
|
+
init__help_catalog();
|
|
2990
|
+
init__connection_state();
|
|
2991
|
+
});
|
|
2992
|
+
|
|
2993
|
+
// packages/cli/src/app-opentui/adapters/tasks.ts
|
|
2994
|
+
import { randomUUID } from "crypto";
|
|
2995
|
+
|
|
2996
|
+
// packages/cli/src/app-opentui/adapters/common.ts
|
|
2997
|
+
function adapterContextFromRuntime(runtime, renderer) {
|
|
2998
|
+
return {
|
|
2999
|
+
projectRoot: runtime.getState().projectRoot,
|
|
3000
|
+
renderer,
|
|
3001
|
+
ensureRuntime: () => runtime.getRunnerContext(),
|
|
3002
|
+
emit: (event) => runtime.emit(event),
|
|
3003
|
+
getState: () => runtime.getState()
|
|
3004
|
+
};
|
|
3005
|
+
}
|
|
3006
|
+
function projectRootOf(ctx) {
|
|
3007
|
+
const root = ctx.rig?.projectRoot ?? ctx.projectRoot ?? ctx.getState().projectRoot;
|
|
3008
|
+
if (typeof root === "string" && root.trim())
|
|
3009
|
+
return root;
|
|
3010
|
+
throw new Error("Rig app adapter requires a projectRoot.");
|
|
3011
|
+
}
|
|
3012
|
+
async function runtimeOf(ctx) {
|
|
3013
|
+
if (ctx.rig && "runId" in ctx.rig && ctx.ensureRuntime === undefined) {
|
|
3014
|
+
return ctx.rig;
|
|
3015
|
+
}
|
|
3016
|
+
if (ctx.ensureRuntime)
|
|
3017
|
+
return ctx.ensureRuntime();
|
|
3018
|
+
throw new Error("Rig app adapter requires ensureRuntime() before this action can run.");
|
|
3019
|
+
}
|
|
3020
|
+
function normalizeAppError(error) {
|
|
3021
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
3022
|
+
const rawHint = error instanceof Error ? error.hint : undefined;
|
|
3023
|
+
return {
|
|
3024
|
+
message,
|
|
3025
|
+
...typeof rawHint === "string" && rawHint.trim() ? { hint: rawHint.trim() } : {}
|
|
3026
|
+
};
|
|
3027
|
+
}
|
|
3028
|
+
function emitStarted(ctx, label, optimistic) {
|
|
3029
|
+
ctx.emit({ type: "action.started", label, ...optimistic ? { optimistic } : {} });
|
|
3030
|
+
}
|
|
3031
|
+
function emitProgress(ctx, label, detail, data) {
|
|
3032
|
+
ctx.emit({ type: "action.progress", label, ...detail ? { detail } : {}, ...data ? { data } : {} });
|
|
3033
|
+
}
|
|
3034
|
+
function emitCompleted(ctx, label, data) {
|
|
3035
|
+
ctx.emit({ type: "action.completed", label, ...data ? { data } : {} });
|
|
3036
|
+
}
|
|
3037
|
+
function emitFailed(ctx, label, error, data) {
|
|
3038
|
+
if (data)
|
|
3039
|
+
patchData(ctx, data);
|
|
3040
|
+
const normalized = normalizeAppError(error);
|
|
3041
|
+
ctx.emit({
|
|
3042
|
+
type: "action.failed",
|
|
3043
|
+
label,
|
|
3044
|
+
message: normalized.message,
|
|
3045
|
+
...normalized.hint ? { hint: normalized.hint } : {},
|
|
3046
|
+
cause: error
|
|
3047
|
+
});
|
|
3048
|
+
}
|
|
3049
|
+
function patchData(ctx, data) {
|
|
3050
|
+
ctx.emit({ type: "data.patch", data });
|
|
3051
|
+
}
|
|
3052
|
+
function patchFooter(ctx, footer) {
|
|
3053
|
+
ctx.emit({ type: "footer.patch", footer });
|
|
3054
|
+
}
|
|
3055
|
+
function stringField(record, keys, fallback = "") {
|
|
3056
|
+
for (const key of keys) {
|
|
3057
|
+
const value = record[key];
|
|
3058
|
+
if (typeof value === "string" && value.trim())
|
|
3059
|
+
return value.trim();
|
|
3060
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
3061
|
+
return String(value);
|
|
3062
|
+
}
|
|
3063
|
+
return fallback;
|
|
3064
|
+
}
|
|
3065
|
+
function compactRecord(record, keys) {
|
|
3066
|
+
const out = {};
|
|
3067
|
+
for (const key of keys) {
|
|
3068
|
+
const value = record[key];
|
|
3069
|
+
if (value !== undefined && value !== null && value !== "")
|
|
3070
|
+
out[key] = value;
|
|
3071
|
+
}
|
|
3072
|
+
return out;
|
|
3073
|
+
}
|
|
3074
|
+
function payloadString(intent, key) {
|
|
3075
|
+
const value = intent.action.payload?.[key];
|
|
3076
|
+
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
|
3077
|
+
}
|
|
3078
|
+
|
|
3079
|
+
// packages/cli/src/app-opentui/adapters/tasks.ts
|
|
3080
|
+
function createTasksAdapter() {
|
|
3081
|
+
return {
|
|
3082
|
+
id: "tasks",
|
|
3083
|
+
async handleIntent(runtime, intent) {
|
|
3084
|
+
if (intent.scene !== "tasks" && intent.action.kind !== "task-run-next" && intent.action.kind !== "task-run-id")
|
|
3085
|
+
return false;
|
|
3086
|
+
const ctx = adapterContextFromRuntime(runtime);
|
|
3087
|
+
if (intent.action.kind === "task-run-next") {
|
|
3088
|
+
await submitNextTaskRun(ctx);
|
|
3089
|
+
return true;
|
|
3090
|
+
}
|
|
3091
|
+
if (intent.action.kind === "task-run-id") {
|
|
3092
|
+
await submitTaskRun(ctx, { taskId: payloadString(intent, "task") });
|
|
3093
|
+
return true;
|
|
3094
|
+
}
|
|
3095
|
+
if (intent.action.kind === "refresh" || intent.action.kind === "navigate") {
|
|
3096
|
+
await refreshTasks(ctx, { limit: 20 });
|
|
3097
|
+
return true;
|
|
3098
|
+
}
|
|
3099
|
+
return false;
|
|
3100
|
+
}
|
|
3101
|
+
};
|
|
3102
|
+
}
|
|
3103
|
+
function rawRecord(record, key) {
|
|
3104
|
+
const direct = record[key];
|
|
3105
|
+
if (direct !== undefined && direct !== null)
|
|
3106
|
+
return direct;
|
|
3107
|
+
const raw = record.raw;
|
|
3108
|
+
return raw && typeof raw === "object" && !Array.isArray(raw) ? raw[key] : undefined;
|
|
3109
|
+
}
|
|
3110
|
+
function optionalString(record, keys) {
|
|
3111
|
+
for (const key of keys) {
|
|
3112
|
+
const value = rawRecord(record, key);
|
|
3113
|
+
if (typeof value === "string" && value.trim())
|
|
3114
|
+
return value.trim();
|
|
3115
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
3116
|
+
return String(value);
|
|
3117
|
+
}
|
|
3118
|
+
return;
|
|
3119
|
+
}
|
|
3120
|
+
function optionalNumber(record, keys) {
|
|
3121
|
+
for (const key of keys) {
|
|
3122
|
+
const value = rawRecord(record, key);
|
|
3123
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
3124
|
+
return value;
|
|
3125
|
+
if (typeof value === "string" && value.trim()) {
|
|
3126
|
+
const parsed = Number(value);
|
|
3127
|
+
if (Number.isFinite(parsed))
|
|
3128
|
+
return parsed;
|
|
3129
|
+
}
|
|
3130
|
+
}
|
|
3131
|
+
return;
|
|
3132
|
+
}
|
|
3133
|
+
function stringList(value) {
|
|
3134
|
+
if (!Array.isArray(value))
|
|
3135
|
+
return [];
|
|
3136
|
+
return value.flatMap((entry) => {
|
|
3137
|
+
if (typeof entry === "string" && entry.trim())
|
|
3138
|
+
return [entry.trim()];
|
|
3139
|
+
if (entry && typeof entry === "object" && !Array.isArray(entry)) {
|
|
3140
|
+
const record = entry;
|
|
3141
|
+
const name = typeof record.name === "string" ? record.name : typeof record.login === "string" ? record.login : undefined;
|
|
3142
|
+
return name?.trim() ? [name.trim()] : [];
|
|
3143
|
+
}
|
|
3144
|
+
return [];
|
|
3145
|
+
});
|
|
3146
|
+
}
|
|
3147
|
+
function labelsFor(record) {
|
|
3148
|
+
return stringList(rawRecord(record, "labels"));
|
|
3149
|
+
}
|
|
3150
|
+
function assigneesFor(record) {
|
|
3151
|
+
return stringList(rawRecord(record, "assignees"));
|
|
3152
|
+
}
|
|
3153
|
+
function normalizeTaskRecord(record) {
|
|
3154
|
+
const id = stringField(record, ["id", "taskId", "number"]);
|
|
3155
|
+
if (!id)
|
|
3156
|
+
return null;
|
|
3157
|
+
const priority = optionalNumber(record, ["priority", "rank", "score"]);
|
|
3158
|
+
const updatedAt = optionalString(record, ["updatedAt", "updated_at", "modifiedAt"]);
|
|
3159
|
+
const createdAt = optionalString(record, ["createdAt", "created_at"]);
|
|
3160
|
+
return {
|
|
3161
|
+
id,
|
|
3162
|
+
status: stringField(record, ["status", "state"], "unknown"),
|
|
3163
|
+
title: stringField(record, ["title", "name", "summary"], "Untitled task"),
|
|
3164
|
+
...priority !== undefined ? { priority } : {},
|
|
3165
|
+
...updatedAt ? { updatedAt } : {},
|
|
3166
|
+
...createdAt ? { createdAt } : {},
|
|
3167
|
+
labels: labelsFor(record),
|
|
3168
|
+
assignees: assigneesFor(record),
|
|
3169
|
+
raw: record
|
|
3170
|
+
};
|
|
3171
|
+
}
|
|
3172
|
+
function currentTaskView(ctx) {
|
|
3173
|
+
const value = ctx.getState().data?.tasks;
|
|
3174
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
3175
|
+
}
|
|
3176
|
+
function taskPayload(ctx) {
|
|
3177
|
+
const intent = ctx.getState().data?.lastIntent;
|
|
3178
|
+
return intent && typeof intent === "object" && !Array.isArray(intent) ? intent.action?.payload ?? {} : {};
|
|
3179
|
+
}
|
|
3180
|
+
function stringPayload(payload, key) {
|
|
3181
|
+
const value = payload[key];
|
|
3182
|
+
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
|
3183
|
+
}
|
|
3184
|
+
function numericPayload(payload, key) {
|
|
3185
|
+
const value = payload[key];
|
|
3186
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
3187
|
+
return value;
|
|
3188
|
+
if (typeof value === "string" && value.trim()) {
|
|
3189
|
+
const parsed = Number(value);
|
|
3190
|
+
if (Number.isFinite(parsed))
|
|
3191
|
+
return parsed;
|
|
3192
|
+
}
|
|
3193
|
+
return;
|
|
3194
|
+
}
|
|
3195
|
+
function normalizeSort(value, fallback = "priority") {
|
|
3196
|
+
const normalized = value?.trim().toLowerCase();
|
|
3197
|
+
if (normalized === "recent" || normalized === "recency" || normalized === "updated" || normalized === "updated-at")
|
|
3198
|
+
return "recency";
|
|
3199
|
+
if (normalized === "status" || normalized === "state")
|
|
3200
|
+
return "status";
|
|
3201
|
+
if (normalized === "id" || normalized === "number")
|
|
3202
|
+
return "id";
|
|
3203
|
+
if (normalized === "priority" || normalized === "prio" || normalized === "rank")
|
|
3204
|
+
return "priority";
|
|
3205
|
+
return fallback;
|
|
3206
|
+
}
|
|
3207
|
+
function normalizeAssigneeAlias2(value) {
|
|
3208
|
+
if (!value)
|
|
3209
|
+
return;
|
|
3210
|
+
const trimmed = value.trim();
|
|
3211
|
+
return trimmed.toLowerCase() === "me" ? "@me" : trimmed;
|
|
3212
|
+
}
|
|
3213
|
+
function filtersFromPreset(preset) {
|
|
3214
|
+
switch (preset?.trim().toLowerCase()) {
|
|
3215
|
+
case "all":
|
|
3216
|
+
return { preset: "all" };
|
|
3217
|
+
case "ready":
|
|
3218
|
+
return { preset: "ready", status: "ready" };
|
|
3219
|
+
case "blocked":
|
|
3220
|
+
return { preset: "blocked", status: "blocked" };
|
|
3221
|
+
case "closed":
|
|
3222
|
+
case "done":
|
|
3223
|
+
return { preset: "closed", state: "closed" };
|
|
3224
|
+
case "mine":
|
|
3225
|
+
case "me":
|
|
3226
|
+
return { preset: "mine", state: "open", assignee: "@me" };
|
|
3227
|
+
case "open":
|
|
3228
|
+
case undefined:
|
|
3229
|
+
case "":
|
|
3230
|
+
return { preset: "open", state: "open" };
|
|
3231
|
+
default:
|
|
3232
|
+
return { preset: "custom", status: preset };
|
|
3233
|
+
}
|
|
3234
|
+
}
|
|
3235
|
+
function effectiveTaskViewOptions(ctx, input = {}) {
|
|
3236
|
+
const current = currentTaskView(ctx);
|
|
3237
|
+
const payload = taskPayload(ctx);
|
|
3238
|
+
const preset = input.preset ?? stringPayload(payload, "taskFilterPreset");
|
|
3239
|
+
const baseFilters = preset !== undefined ? filtersFromPreset(preset) : current?.filters ?? filtersFromPreset("open");
|
|
3240
|
+
const payloadLimit = numericPayload(payload, "taskLimit");
|
|
3241
|
+
const mergedFilters = {
|
|
3242
|
+
...baseFilters,
|
|
3243
|
+
...input,
|
|
3244
|
+
...stringPayload(payload, "taskState") ? { state: stringPayload(payload, "taskState") } : {},
|
|
3245
|
+
...stringPayload(payload, "taskStatus") ? { status: stringPayload(payload, "taskStatus") } : {},
|
|
3246
|
+
...stringPayload(payload, "taskAssignee") ? { assignee: stringPayload(payload, "taskAssignee") } : {},
|
|
3247
|
+
...stringPayload(payload, "taskLabel") ? { label: stringPayload(payload, "taskLabel") } : {},
|
|
3248
|
+
...stringPayload(payload, "taskSearch") ? { search: stringPayload(payload, "taskSearch") } : {},
|
|
3249
|
+
...payloadLimit ? { limit: payloadLimit } : {}
|
|
3250
|
+
};
|
|
3251
|
+
const normalizedFilters = {
|
|
3252
|
+
...mergedFilters,
|
|
3253
|
+
...mergedFilters.assignee ? { assignee: normalizeAssigneeAlias2(mergedFilters.assignee) } : {}
|
|
3254
|
+
};
|
|
3255
|
+
const filters = !normalizedFilters.state && !normalizedFilters.status && !normalizedFilters.assignee && !normalizedFilters.label && !normalizedFilters.search && !normalizedFilters.preset ? { ...normalizedFilters, preset: "open", state: "open" } : normalizedFilters;
|
|
3256
|
+
const sort = normalizeSort(typeof input.sort === "string" ? input.sort : stringPayload(payload, "taskSort"), current?.sort ?? "priority");
|
|
3257
|
+
return { filters, sort };
|
|
3258
|
+
}
|
|
3259
|
+
function matchesSearch(task, search) {
|
|
3260
|
+
const needle = search?.trim().toLowerCase();
|
|
3261
|
+
if (!needle)
|
|
3262
|
+
return true;
|
|
3263
|
+
const raw = task.raw;
|
|
3264
|
+
const haystack = [
|
|
3265
|
+
task.id,
|
|
3266
|
+
task.title,
|
|
3267
|
+
task.status,
|
|
3268
|
+
task.labels.join(" "),
|
|
3269
|
+
task.assignees.join(" "),
|
|
3270
|
+
optionalString(raw, ["externalRef", "sourceIssueId", "url", "description", "acceptanceCriteria"])
|
|
3271
|
+
].filter(Boolean).join(" ").toLowerCase();
|
|
3272
|
+
return haystack.includes(needle);
|
|
3273
|
+
}
|
|
3274
|
+
function matchesLabel(task, label) {
|
|
3275
|
+
const wanted = label?.trim().toLowerCase();
|
|
3276
|
+
if (!wanted)
|
|
3277
|
+
return true;
|
|
3278
|
+
return task.labels.some((entry) => entry.toLowerCase() === wanted);
|
|
3279
|
+
}
|
|
3280
|
+
function timestamp(task) {
|
|
3281
|
+
const parsed = Date.parse(task.updatedAt ?? task.createdAt ?? "");
|
|
3282
|
+
return Number.isFinite(parsed) ? parsed : 0;
|
|
3283
|
+
}
|
|
3284
|
+
function statusRank(status) {
|
|
3285
|
+
switch (status.toLowerCase().replace(/-/g, "_")) {
|
|
3286
|
+
case "ready":
|
|
3287
|
+
return 0;
|
|
3288
|
+
case "open":
|
|
3289
|
+
return 1;
|
|
3290
|
+
case "in_progress":
|
|
3291
|
+
return 2;
|
|
3292
|
+
case "blocked":
|
|
3293
|
+
return 3;
|
|
3294
|
+
case "closed":
|
|
3295
|
+
case "completed":
|
|
3296
|
+
return 4;
|
|
3297
|
+
default:
|
|
3298
|
+
return 5;
|
|
3299
|
+
}
|
|
3300
|
+
}
|
|
3301
|
+
function sortTasks(tasks, sort) {
|
|
3302
|
+
return [...tasks].sort((left, right) => {
|
|
3303
|
+
if (sort === "recency")
|
|
3304
|
+
return timestamp(right) - timestamp(left) || left.id.localeCompare(right.id);
|
|
3305
|
+
if (sort === "status")
|
|
3306
|
+
return statusRank(left.status) - statusRank(right.status) || left.id.localeCompare(right.id);
|
|
3307
|
+
if (sort === "id")
|
|
3308
|
+
return left.id.localeCompare(right.id, undefined, { numeric: true });
|
|
3309
|
+
const leftPriority = left.priority ?? Number.NEGATIVE_INFINITY;
|
|
3310
|
+
const rightPriority = right.priority ?? Number.NEGATIVE_INFINITY;
|
|
3311
|
+
return rightPriority - leftPriority || statusRank(left.status) - statusRank(right.status) || left.id.localeCompare(right.id, undefined, { numeric: true });
|
|
3312
|
+
});
|
|
3313
|
+
}
|
|
3314
|
+
function applyLocalTaskView(records, filters, sort) {
|
|
3315
|
+
const sorted = sortTasks(records.filter((task) => matchesSearch(task, filters.search) && matchesLabel(task, filters.label)), sort);
|
|
3316
|
+
return filters.limit && filters.limit > 0 ? sorted.slice(0, filters.limit) : sorted;
|
|
3317
|
+
}
|
|
3318
|
+
function serverFilters(filters) {
|
|
3319
|
+
return {
|
|
3320
|
+
...filters.state ? { state: filters.state } : {},
|
|
3321
|
+
...filters.status ? { status: filters.status } : {},
|
|
3322
|
+
...filters.assignee ? { assignee: filters.assignee } : {}
|
|
3323
|
+
};
|
|
3324
|
+
}
|
|
3325
|
+
async function refreshTasks(ctx, input = {}) {
|
|
3326
|
+
const { filters, sort } = effectiveTaskViewOptions(ctx, input);
|
|
3327
|
+
const label = "Loading tasks";
|
|
3328
|
+
emitStarted(ctx, label);
|
|
3329
|
+
try {
|
|
3330
|
+
const { listWorkspaceTasksViaServer: listWorkspaceTasksViaServer2 } = await Promise.resolve().then(() => (init__server_client(), exports__server_client));
|
|
3331
|
+
emitProgress(ctx, label, `reading workspace tasks \xB7 filter ${filters.preset ?? filters.status ?? filters.state ?? "custom"} \xB7 sort ${sort}`);
|
|
3332
|
+
const tasks = await listWorkspaceTasksViaServer2({ projectRoot: projectRootOf(ctx) }, serverFilters(filters));
|
|
3333
|
+
const allRecords = tasks.flatMap((task) => {
|
|
3334
|
+
const entry = normalizeTaskRecord(task);
|
|
3335
|
+
return entry ? [entry] : [];
|
|
3336
|
+
});
|
|
3337
|
+
const records = applyLocalTaskView(allRecords, filters, sort);
|
|
3338
|
+
const view = {
|
|
3339
|
+
records,
|
|
3340
|
+
allRecords,
|
|
3341
|
+
filters,
|
|
3342
|
+
sort,
|
|
3343
|
+
refreshedAt: new Date().toISOString(),
|
|
3344
|
+
totalCount: allRecords.length,
|
|
3345
|
+
visibleCount: records.length
|
|
3346
|
+
};
|
|
3347
|
+
patchData(ctx, { tasks: view, selectedTaskId: records[0]?.id });
|
|
3348
|
+
patchFooter(ctx, { tasks: `${records.length}/${allRecords.length}` });
|
|
3349
|
+
emitCompleted(ctx, label, { count: records.length, totalCount: allRecords.length, sort, filters });
|
|
3350
|
+
return records;
|
|
3351
|
+
} catch (error) {
|
|
3352
|
+
emitFailed(ctx, label, error);
|
|
3353
|
+
throw error;
|
|
3354
|
+
}
|
|
3355
|
+
}
|
|
3356
|
+
async function loadRunDefaults(projectRoot) {
|
|
3357
|
+
try {
|
|
3358
|
+
const { loadTaskRunProjectDefaults: loadTaskRunProjectDefaults2 } = await Promise.resolve().then(() => (init_task(), exports_task));
|
|
3359
|
+
const defaults = await loadTaskRunProjectDefaults2(projectRoot);
|
|
3360
|
+
return {
|
|
3361
|
+
runtimeAdapter: defaults.runtimeAdapter ?? "pi",
|
|
3362
|
+
...defaults.model ? { model: defaults.model } : {},
|
|
3363
|
+
runtimeMode: defaults.runtimeMode ?? "full-access",
|
|
3364
|
+
...defaults.prMode ? { prMode: defaults.prMode } : {}
|
|
3365
|
+
};
|
|
3366
|
+
} catch {
|
|
3367
|
+
return { runtimeAdapter: "pi", runtimeMode: "full-access" };
|
|
3368
|
+
}
|
|
3369
|
+
}
|
|
3370
|
+
async function submitTaskRun(ctx, input = {}) {
|
|
3371
|
+
const projectRoot = projectRootOf(ctx);
|
|
3372
|
+
const stateRunId = ctx.getState().runId;
|
|
3373
|
+
const taskId3 = input.taskId?.trim();
|
|
3374
|
+
const title = input.title?.trim();
|
|
3375
|
+
const initialPrompt = input.initialPrompt?.trim();
|
|
3376
|
+
if (!taskId3 && !title && !initialPrompt) {
|
|
3377
|
+
const error = new Error("Select a task, then press Enter; or use run next.");
|
|
3378
|
+
emitFailed(ctx, "Dispatching task", error);
|
|
3379
|
+
throw error;
|
|
3380
|
+
}
|
|
3381
|
+
const runId = input.runId?.trim() || ctx.rig?.runId || (typeof stateRunId === "string" ? stateRunId : undefined) || randomUUID();
|
|
3382
|
+
const label = taskId3 ? `Dispatching ${taskId3}` : "Dispatching ad-hoc run";
|
|
3383
|
+
emitStarted(ctx, label, {
|
|
3384
|
+
dispatch: { runId, taskId: taskId3 ?? null, status: "dispatching" }
|
|
3385
|
+
});
|
|
3386
|
+
const optimisticTitle = title ?? taskId3 ?? "ad hoc run";
|
|
3387
|
+
patchData(ctx, {
|
|
3388
|
+
selectedRunId: runId,
|
|
3389
|
+
dispatchingRun: { runId, taskId: taskId3 ?? null, status: "dispatching", title: optimisticTitle },
|
|
3390
|
+
runDetail: { runId, status: "dispatching", title: optimisticTitle, run: {}, logs: [], timeline: [], timelineCursor: null }
|
|
3391
|
+
});
|
|
3392
|
+
patchFooter(ctx, { run: `${runId.slice(0, 8)} dispatching` });
|
|
3393
|
+
try {
|
|
3394
|
+
const { submitTaskRunViaServer: submitTaskRunViaServer2 } = await Promise.resolve().then(() => (init__server_client(), exports__server_client));
|
|
3395
|
+
const defaults = await loadRunDefaults(projectRoot);
|
|
3396
|
+
emitProgress(ctx, label, "submitting run to selected Rig server", { runId, taskId: taskId3 ?? null });
|
|
3397
|
+
const submitted = await submitTaskRunViaServer2({ projectRoot }, {
|
|
3398
|
+
runId,
|
|
3399
|
+
taskId: taskId3 || undefined,
|
|
3400
|
+
title,
|
|
3401
|
+
runtimeAdapter: defaults.runtimeAdapter,
|
|
3402
|
+
model: defaults.model,
|
|
3403
|
+
runtimeMode: defaults.runtimeMode,
|
|
3404
|
+
interactionMode: "default",
|
|
3405
|
+
initialPrompt,
|
|
3406
|
+
baselineMode: "head",
|
|
3407
|
+
prMode: defaults.prMode
|
|
3408
|
+
});
|
|
3409
|
+
emitCompleted(ctx, label, { runId: submitted.runId, taskId: taskId3 ?? null });
|
|
3410
|
+
patchData(ctx, {
|
|
3411
|
+
selectedRunId: submitted.runId,
|
|
3412
|
+
dispatchingRun: null,
|
|
3413
|
+
latestSubmittedRun: { runId: submitted.runId, taskId: taskId3 ?? null },
|
|
3414
|
+
runDetail: { runId: submitted.runId, status: "submitted", title: optimisticTitle, run: submitted, logs: [], timeline: [], timelineCursor: null }
|
|
3415
|
+
});
|
|
3416
|
+
patchFooter(ctx, { run: `${submitted.runId.slice(0, 8)} submitted` });
|
|
3417
|
+
return submitted;
|
|
3418
|
+
} catch (error) {
|
|
3419
|
+
emitFailed(ctx, label, error, { runId, taskId: taskId3 ?? null, revert: { dispatchingRun: null } });
|
|
3420
|
+
throw error;
|
|
3421
|
+
}
|
|
3422
|
+
}
|
|
3423
|
+
async function submitNextTaskRun(ctx, filters = {}) {
|
|
3424
|
+
const label = "Selecting next task";
|
|
3425
|
+
emitStarted(ctx, label, { dispatch: { status: "selecting-next" } });
|
|
3426
|
+
try {
|
|
3427
|
+
const { selectNextWorkspaceTaskViaServer: selectNextWorkspaceTaskViaServer2 } = await Promise.resolve().then(() => (init__server_client(), exports__server_client));
|
|
3428
|
+
const projectRoot = projectRootOf(ctx);
|
|
3429
|
+
emitProgress(ctx, label, "asking server for next runnable task");
|
|
3430
|
+
const selected = await selectNextWorkspaceTaskViaServer2({ projectRoot }, filters);
|
|
3431
|
+
const task = selected.task ? normalizeTaskRecord(selected.task) : null;
|
|
3432
|
+
patchData(ctx, { nextTask: task, nextTaskCount: selected.count });
|
|
3433
|
+
if (!task) {
|
|
3434
|
+
const error = new Error("No runnable task is available.");
|
|
3435
|
+
emitFailed(ctx, label, error, { count: selected.count });
|
|
3436
|
+
throw error;
|
|
3437
|
+
}
|
|
3438
|
+
emitCompleted(ctx, label, { taskId: task.id, count: selected.count });
|
|
3439
|
+
const submitted = await submitTaskRun(ctx, { taskId: task.id, title: task.title });
|
|
3440
|
+
return { ...submitted, task };
|
|
3441
|
+
} catch (error) {
|
|
3442
|
+
emitFailed(ctx, label, error);
|
|
3443
|
+
throw error;
|
|
3444
|
+
}
|
|
3445
|
+
}
|
|
3446
|
+
async function loadTaskPreview(ctx, taskId3) {
|
|
3447
|
+
const label = `Loading task ${taskId3}`;
|
|
3448
|
+
emitStarted(ctx, label);
|
|
3449
|
+
try {
|
|
3450
|
+
const { getWorkspaceTaskViaServer: getWorkspaceTaskViaServer2 } = await Promise.resolve().then(() => (init__server_client(), exports__server_client));
|
|
3451
|
+
const task = await getWorkspaceTaskViaServer2({ projectRoot: projectRootOf(ctx) }, taskId3);
|
|
3452
|
+
const normalized = task ? normalizeTaskRecord(task) : null;
|
|
3453
|
+
patchData(ctx, { selectedTaskId: taskId3, taskPreview: normalized, taskPreviewRaw: task ? compactRecord(task, ["id", "title", "status", "body", "url"]) : null });
|
|
3454
|
+
emitCompleted(ctx, label, { taskId: taskId3, found: Boolean(normalized) });
|
|
3455
|
+
return normalized;
|
|
3456
|
+
} catch (error) {
|
|
3457
|
+
emitFailed(ctx, label, error, { taskId: taskId3 });
|
|
3458
|
+
throw error;
|
|
3459
|
+
}
|
|
3460
|
+
}
|
|
3461
|
+
async function ensureTaskRuntime(ctx) {
|
|
3462
|
+
await runtimeOf(ctx);
|
|
3463
|
+
}
|
|
3464
|
+
export {
|
|
3465
|
+
submitTaskRun,
|
|
3466
|
+
submitNextTaskRun,
|
|
3467
|
+
refreshTasks,
|
|
3468
|
+
normalizeTaskRecord,
|
|
3469
|
+
loadTaskPreview,
|
|
3470
|
+
ensureTaskRuntime,
|
|
3471
|
+
createTasksAdapter
|
|
3472
|
+
};
|