@h-rig/cli 0.0.6-alpha.2 → 0.0.6-alpha.200

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +6 -28
  2. package/package.json +9 -27
  3. package/dist/bin/build-rig-binaries.js +0 -107
  4. package/dist/bin/rig.js +0 -9470
  5. package/dist/src/commands/_authority-runs.js +0 -110
  6. package/dist/src/commands/_connection-state.js +0 -123
  7. package/dist/src/commands/_doctor-checks.js +0 -519
  8. package/dist/src/commands/_operator-view.js +0 -340
  9. package/dist/src/commands/_parsers.js +0 -107
  10. package/dist/src/commands/_paths.js +0 -50
  11. package/dist/src/commands/_pi-install.js +0 -184
  12. package/dist/src/commands/_policy.js +0 -79
  13. package/dist/src/commands/_preflight.js +0 -478
  14. package/dist/src/commands/_probes.js +0 -13
  15. package/dist/src/commands/_run-driver-helpers.js +0 -289
  16. package/dist/src/commands/_server-client.js +0 -382
  17. package/dist/src/commands/_snapshot-upload.js +0 -331
  18. package/dist/src/commands/_task-picker.js +0 -48
  19. package/dist/src/commands/agent.js +0 -497
  20. package/dist/src/commands/browser.js +0 -890
  21. package/dist/src/commands/connect.js +0 -180
  22. package/dist/src/commands/dist.js +0 -402
  23. package/dist/src/commands/doctor.js +0 -529
  24. package/dist/src/commands/github.js +0 -294
  25. package/dist/src/commands/inbox.js +0 -160
  26. package/dist/src/commands/init.js +0 -1334
  27. package/dist/src/commands/inspect.js +0 -174
  28. package/dist/src/commands/inspector.js +0 -256
  29. package/dist/src/commands/plugin.js +0 -167
  30. package/dist/src/commands/profile-and-review.js +0 -178
  31. package/dist/src/commands/queue.js +0 -197
  32. package/dist/src/commands/remote.js +0 -507
  33. package/dist/src/commands/repo-git-harness.js +0 -221
  34. package/dist/src/commands/run.js +0 -771
  35. package/dist/src/commands/server.js +0 -386
  36. package/dist/src/commands/setup.js +0 -699
  37. package/dist/src/commands/task-report-bug.js +0 -1083
  38. package/dist/src/commands/task-run-driver.js +0 -1994
  39. package/dist/src/commands/task.js +0 -1343
  40. package/dist/src/commands/test.js +0 -39
  41. package/dist/src/commands/workspace.js +0 -123
  42. package/dist/src/commands.js +0 -9152
  43. package/dist/src/index.js +0 -9488
  44. package/dist/src/launcher.js +0 -131
  45. package/dist/src/report-bug.js +0 -260
  46. package/dist/src/runner.js +0 -272
  47. package/dist/src/withMutedConsole.js +0 -42
@@ -1,289 +0,0 @@
1
- // @bun
2
- // packages/cli/src/commands/_run-driver-helpers.ts
3
- import { readFileSync } from "fs";
4
- import { resolve as resolve3 } from "path";
5
-
6
- // packages/cli/src/runner.ts
7
- import { EventBus } from "@rig/runtime/control-plane/runtime/events";
8
- import { CliError } from "@rig/runtime/control-plane/errors";
9
- import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
10
- import { PluginManager } from "@rig/runtime/control-plane/runtime/plugins";
11
- import { loadRuntimeContextFromEnv } from "@rig/runtime/control-plane/runtime/context";
12
- import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
13
- import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
14
-
15
- // packages/cli/src/commands/_run-driver-helpers.ts
16
- import {
17
- appendJsonlRecord,
18
- readAuthorityRun as readAuthorityRun2,
19
- resolveAuthorityRunDir as resolveAuthorityRunDir2,
20
- writeJsonFile as writeJsonFile2
21
- } from "@rig/runtime/control-plane/authority-files";
22
- import { taskLookup } from "@rig/runtime/control-plane/native/task-ops";
23
- import { buildProviderTaskRunInstructionLines } from "@rig/runtime/control-plane/provider/runtime-instructions";
24
- import { loadRigTaskRunSkillBody } from "@rig/runtime/control-plane/provider/rig-task-run-skill";
25
-
26
- // packages/cli/src/commands/_authority-runs.ts
27
- import { existsSync } from "fs";
28
- import { resolve as resolve2 } from "path";
29
- import {
30
- readAuthorityRun,
31
- readJsonlFile,
32
- resolveAuthorityRunDir,
33
- writeJsonFile
34
- } from "@rig/runtime/control-plane/authority-files";
35
-
36
- // packages/cli/src/commands/_paths.ts
37
- import { resolve } from "path";
38
- import { resolveMonorepoRoot } from "@rig/runtime/control-plane/native/utils";
39
- function resolveControlPlaneMonorepoRoot(projectRoot) {
40
- return resolveMonorepoRoot(projectRoot);
41
- }
42
- function resolveControlPlaneTaskConfigPath(projectRoot) {
43
- return resolve(resolveControlPlaneMonorepoRoot(projectRoot), ".rig", "task-config.json");
44
- }
45
-
46
- // packages/cli/src/commands/_authority-runs.ts
47
- function readLatestBeadRecord(projectRoot, taskId) {
48
- const issuesPath = resolve2(resolveControlPlaneMonorepoRoot(projectRoot), ".beads", "issues.jsonl");
49
- if (!existsSync(issuesPath)) {
50
- return null;
51
- }
52
- let latest = null;
53
- for (const issue of readJsonlFile(issuesPath)) {
54
- if (!issue || typeof issue !== "object") {
55
- continue;
56
- }
57
- const record = issue;
58
- if (record.id === taskId) {
59
- latest = record;
60
- }
61
- }
62
- return latest;
63
- }
64
-
65
- // packages/cli/src/commands/_run-driver-helpers.ts
66
- function patchAuthorityRun(projectRoot, runId, patch) {
67
- const current = readAuthorityRun2(projectRoot, runId);
68
- if (!current) {
69
- throw new CliError2(`Run not found: ${runId}`, 2);
70
- }
71
- const next = {
72
- ...current,
73
- ...patch,
74
- updatedAt: new Date().toISOString()
75
- };
76
- writeJsonFile2(resolve3(resolveAuthorityRunDir2(projectRoot, runId), "run.json"), next);
77
- return next;
78
- }
79
- function touchAuthorityRun(projectRoot, runId) {
80
- const current = readAuthorityRun2(projectRoot, runId);
81
- if (!current) {
82
- return;
83
- }
84
- writeJsonFile2(resolve3(resolveAuthorityRunDir2(projectRoot, runId), "run.json"), {
85
- ...current,
86
- updatedAt: new Date().toISOString()
87
- });
88
- }
89
- function appendRunTimeline(projectRoot, runId, value) {
90
- appendJsonlRecord(resolve3(resolveAuthorityRunDir2(projectRoot, runId), "timeline.jsonl"), value);
91
- touchAuthorityRun(projectRoot, runId);
92
- }
93
- function appendRunLog(projectRoot, runId, value) {
94
- appendJsonlRecord(resolve3(resolveAuthorityRunDir2(projectRoot, runId), "logs.jsonl"), value);
95
- touchAuthorityRun(projectRoot, runId);
96
- }
97
- function appendRunAction(projectRoot, runId, value) {
98
- appendJsonlRecord(resolve3(resolveAuthorityRunDir2(projectRoot, runId), "timeline.jsonl"), {
99
- id: value.id,
100
- type: "action",
101
- actionType: value.actionType,
102
- title: value.title,
103
- detail: value.detail ?? null,
104
- state: value.state,
105
- createdAt: value.startedAt,
106
- completedAt: value.completedAt ?? null,
107
- payload: value.payload ?? {}
108
- });
109
- }
110
- function startRunAction(projectRoot, runId, input) {
111
- const startedAt = new Date().toISOString();
112
- appendRunAction(projectRoot, runId, {
113
- id: input.actionId,
114
- actionType: input.actionType,
115
- title: input.title,
116
- detail: input.detail,
117
- state: "running",
118
- startedAt,
119
- payload: input.payload
120
- });
121
- emitServerRunEvent({ type: "timeline", runId });
122
- return {
123
- startedAt,
124
- complete: (detail, payload) => {
125
- appendRunAction(projectRoot, runId, {
126
- id: input.actionId,
127
- actionType: input.actionType,
128
- title: input.title,
129
- detail: detail ?? input.detail ?? null,
130
- state: "completed",
131
- startedAt,
132
- completedAt: new Date().toISOString(),
133
- payload: payload ?? input.payload
134
- });
135
- emitServerRunEvent({ type: "timeline", runId });
136
- },
137
- fail: (detail, payload) => {
138
- appendRunAction(projectRoot, runId, {
139
- id: input.actionId,
140
- actionType: input.actionType,
141
- title: input.title,
142
- detail,
143
- state: "failed",
144
- startedAt,
145
- completedAt: new Date().toISOString(),
146
- payload: payload ?? input.payload
147
- });
148
- emitServerRunEvent({ type: "timeline", runId });
149
- }
150
- };
151
- }
152
- function emitServerRunEvent(event) {
153
- console.log(`__RIG_RUN_EVENT__${JSON.stringify({ ...event, at: new Date().toISOString() })}`);
154
- }
155
- function buildRunPrompt(input) {
156
- const initialPrompt = input.initialPrompt?.trim() || null;
157
- if (!input.taskId) {
158
- return initialPrompt ?? input.fallbackTitle?.trim() ?? "Continue the requested Rig run and complete the work.";
159
- }
160
- const issues = (() => {
161
- try {
162
- return taskLookup(input.projectRoot, input.taskId);
163
- } catch {
164
- return "";
165
- }
166
- })();
167
- const scopeText = (() => {
168
- try {
169
- const parsed = JSON.parse(readFileSync(resolveControlPlaneTaskConfigPath(input.projectRoot), "utf8"));
170
- const entry = parsed[input.taskId] ?? {};
171
- const scope = Array.isArray(entry.scope) ? entry.scope.filter((item) => typeof item === "string") : [];
172
- const validation = Array.isArray(entry.validation) ? entry.validation.filter((item) => typeof item === "string") : [];
173
- const lines = [];
174
- if (scope.length > 0)
175
- lines.push(`Scope:
176
- - ${scope.join(`
177
- - `)}`);
178
- if (validation.length > 0)
179
- lines.push(`Validation:
180
- - ${validation.join(`
181
- - `)}`);
182
- return lines.join(`
183
-
184
- `);
185
- } catch {
186
- return "";
187
- }
188
- })();
189
- const bead = readLatestBeadRecord(input.projectRoot, input.taskId);
190
- const sourceTask = input.sourceTask ?? null;
191
- const sourceDescription = firstPromptString(sourceTask?.description, sourceTask?.body);
192
- const sourceAcceptance = firstPromptString(sourceTask?.acceptanceCriteria, sourceTask?.acceptance_criteria);
193
- const sourceValidation = uniqueStrings([...sourceTask?.validation ?? [], ...sourceTask?.validators ?? []]);
194
- const title = (bead && typeof bead === "object" && typeof bead.title === "string" ? bead.title : null) ?? firstPromptString(sourceTask?.title) ?? input.fallbackTitle ?? issues ?? input.taskId;
195
- const description = (bead && typeof bead === "object" && typeof bead.description === "string" ? bead.description : null) ?? sourceDescription ?? input.fallbackDescription ?? "";
196
- const acceptance = bead && typeof bead === "object" && typeof bead.acceptance_criteria === "string" ? bead.acceptance_criteria : sourceAcceptance ?? input.fallbackAcceptanceCriteria ?? "";
197
- const sourceContractLines = renderSourceTaskContract(sourceTask, sourceValidation);
198
- const providerLines = buildProviderTaskRunInstructionLines(input.runtimeAdapter);
199
- const skillBody = loadRigTaskRunSkillBody();
200
- return [
201
- `You are working on task ${input.taskId}: ${title}.`,
202
- description ? `Description:
203
- ${description}` : null,
204
- acceptance ? `Acceptance criteria:
205
- ${acceptance}` : null,
206
- sourceContractLines.length > 0 ? `Source task contract:
207
- ${sourceContractLines.join(`
208
- `)}` : null,
209
- scopeText || renderSourceScopeValidation(sourceTask, sourceValidation) || null,
210
- initialPrompt ? `Additional operator guidance:
211
- ${initialPrompt}` : null,
212
- providerLines.length > 0 ? `Provider-specific runtime tooling:
213
- ${providerLines.join(" ")}` : null,
214
- skillBody || null
215
- ].filter((value) => Boolean(value)).join(`
216
-
217
- `);
218
- }
219
- function firstPromptString(...values) {
220
- for (const value of values) {
221
- const trimmed = typeof value === "string" ? value.trim() : "";
222
- if (trimmed.length > 0) {
223
- return trimmed;
224
- }
225
- }
226
- return null;
227
- }
228
- function uniqueStrings(values) {
229
- return Array.from(new Set(values.map((value) => value.trim()).filter(Boolean)));
230
- }
231
- function renderSourceTaskContract(task, validation) {
232
- if (!task) {
233
- return [];
234
- }
235
- const lines = [];
236
- const sourceIssueId = firstPromptString(task.sourceIssueId);
237
- if (sourceIssueId)
238
- lines.push(`Source issue: ${sourceIssueId}`);
239
- const status = firstPromptString(task.status);
240
- if (status)
241
- lines.push(`Source status: ${status}`);
242
- const issueType = firstPromptString(task.issueType);
243
- if (issueType)
244
- lines.push(`Issue type: ${issueType}`);
245
- const role = firstPromptString(task.role);
246
- if (role)
247
- lines.push(`Role: ${role}`);
248
- const externalRef = firstPromptString(task.externalRef);
249
- if (externalRef)
250
- lines.push(`External ref: ${externalRef}`);
251
- const labels = uniqueStrings(task.labels ?? []);
252
- if (labels.length > 0)
253
- lines.push(`Labels:
254
- - ${labels.join(`
255
- - `)}`);
256
- if (validation.length > 0)
257
- lines.push(`Validators:
258
- - ${validation.join(`
259
- - `)}`);
260
- return lines;
261
- }
262
- function renderSourceScopeValidation(task, validation) {
263
- if (!task) {
264
- return "";
265
- }
266
- const lines = [];
267
- const scope = uniqueStrings(task.scope ?? []);
268
- if (scope.length > 0)
269
- lines.push(`Scope:
270
- - ${scope.join(`
271
- - `)}`);
272
- if (validation.length > 0)
273
- lines.push(`Validation:
274
- - ${validation.join(`
275
- - `)}`);
276
- return lines.join(`
277
-
278
- `);
279
- }
280
- export {
281
- touchAuthorityRun,
282
- startRunAction,
283
- patchAuthorityRun,
284
- emitServerRunEvent,
285
- buildRunPrompt,
286
- appendRunTimeline,
287
- appendRunLog,
288
- appendRunAction
289
- };
@@ -1,382 +0,0 @@
1
- // @bun
2
- // packages/cli/src/commands/_server-client.ts
3
- import { spawnSync } from "child_process";
4
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
5
- import { resolve as resolve2 } from "path";
6
-
7
- // packages/cli/src/runner.ts
8
- import { EventBus } from "@rig/runtime/control-plane/runtime/events";
9
- import { CliError } from "@rig/runtime/control-plane/errors";
10
- import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
11
- import { PluginManager } from "@rig/runtime/control-plane/runtime/plugins";
12
- import { loadRuntimeContextFromEnv } from "@rig/runtime/control-plane/runtime/context";
13
- import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
14
- import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
15
-
16
- // packages/cli/src/commands/_server-client.ts
17
- import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
18
-
19
- // packages/cli/src/commands/_connection-state.ts
20
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
21
- import { homedir } from "os";
22
- import { dirname, resolve } from "path";
23
- function resolveGlobalConnectionsPath(env = process.env) {
24
- const explicit = env.RIG_CONNECTIONS_FILE?.trim();
25
- if (explicit)
26
- return resolve(explicit);
27
- const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
28
- if (stateDir)
29
- return resolve(stateDir, "connections.json");
30
- return resolve(homedir(), ".rig", "connections.json");
31
- }
32
- function resolveRepoConnectionPath(projectRoot) {
33
- return resolve(projectRoot, ".rig", "state", "connection.json");
34
- }
35
- function readJsonFile(path) {
36
- if (!existsSync(path))
37
- return null;
38
- try {
39
- return JSON.parse(readFileSync(path, "utf8"));
40
- } catch (error) {
41
- throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
42
- }
43
- }
44
- function normalizeConnection(value) {
45
- if (!value || typeof value !== "object" || Array.isArray(value))
46
- return null;
47
- const record = value;
48
- if (record.kind === "local")
49
- return { kind: "local", mode: "auto" };
50
- if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
51
- const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
52
- return { kind: "remote", baseUrl };
53
- }
54
- return null;
55
- }
56
- function readGlobalConnections(options = {}) {
57
- const path = resolveGlobalConnectionsPath(options.env ?? process.env);
58
- const payload = readJsonFile(path);
59
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
60
- return { connections: {} };
61
- }
62
- const rawConnections = payload.connections;
63
- const connections = {};
64
- if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
65
- for (const [alias, raw] of Object.entries(rawConnections)) {
66
- const connection = normalizeConnection(raw);
67
- if (connection)
68
- connections[alias] = connection;
69
- }
70
- }
71
- return { connections };
72
- }
73
- function readRepoConnection(projectRoot) {
74
- const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
75
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
76
- return null;
77
- const record = payload;
78
- const selected = typeof record.selected === "string" ? record.selected.trim() : "";
79
- if (!selected)
80
- return null;
81
- return {
82
- selected,
83
- project: typeof record.project === "string" ? record.project : undefined,
84
- linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined
85
- };
86
- }
87
- function resolveSelectedConnection(projectRoot, options = {}) {
88
- const repo = readRepoConnection(projectRoot);
89
- if (!repo)
90
- return null;
91
- if (repo.selected === "local")
92
- return { alias: "local", connection: { kind: "local", mode: "auto" } };
93
- const global = readGlobalConnections(options);
94
- const connection = global.connections[repo.selected];
95
- if (!connection) {
96
- throw new CliError2(`Selected Rig connection "${repo.selected}" was not found. Run \`rig connect list\` or \`rig connect use local\`.`, 1);
97
- }
98
- return { alias: repo.selected, connection };
99
- }
100
-
101
- // packages/cli/src/commands/_server-client.ts
102
- var cachedGitHubBearerToken;
103
- function cleanToken(value) {
104
- const trimmed = value?.trim();
105
- return trimmed ? trimmed : null;
106
- }
107
- function setGitHubBearerTokenForCurrentProcess(token) {
108
- cachedGitHubBearerToken = cleanToken(token ?? undefined);
109
- }
110
- function readPrivateRemoteSessionToken(projectRoot) {
111
- const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
112
- if (!existsSync2(path))
113
- return null;
114
- try {
115
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
116
- return cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined);
117
- } catch {
118
- return null;
119
- }
120
- }
121
- function readGitHubBearerTokenForRemote(projectRoot) {
122
- if (cachedGitHubBearerToken !== undefined)
123
- return cachedGitHubBearerToken;
124
- const privateSession = readPrivateRemoteSessionToken(projectRoot);
125
- if (privateSession) {
126
- cachedGitHubBearerToken = privateSession;
127
- return cachedGitHubBearerToken;
128
- }
129
- const envToken = cleanToken(process.env.RIG_GITHUB_TOKEN) ?? cleanToken(process.env.GITHUB_TOKEN) ?? cleanToken(process.env.GH_TOKEN);
130
- if (envToken) {
131
- cachedGitHubBearerToken = envToken;
132
- return cachedGitHubBearerToken;
133
- }
134
- const result = spawnSync("gh", ["auth", "token"], {
135
- encoding: "utf8",
136
- timeout: 5000,
137
- stdio: ["ignore", "pipe", "ignore"]
138
- });
139
- cachedGitHubBearerToken = result.status === 0 ? cleanToken(result.stdout) : null;
140
- return cachedGitHubBearerToken;
141
- }
142
- async function ensureServerForCli(projectRoot) {
143
- try {
144
- const selected = resolveSelectedConnection(projectRoot);
145
- if (selected?.connection.kind === "remote") {
146
- return {
147
- baseUrl: selected.connection.baseUrl,
148
- authToken: readGitHubBearerTokenForRemote(projectRoot),
149
- connectionKind: "remote"
150
- };
151
- }
152
- const connection = await ensureLocalRigServerConnection(projectRoot);
153
- return {
154
- baseUrl: connection.baseUrl,
155
- authToken: connection.authToken,
156
- connectionKind: "local"
157
- };
158
- } catch (error) {
159
- if (error instanceof Error) {
160
- throw new CliError2(error.message, 1);
161
- }
162
- throw error;
163
- }
164
- }
165
- function appendTaskFilterParams(url, filters) {
166
- if (filters.assignee)
167
- url.searchParams.set("assignee", filters.assignee);
168
- if (filters.state)
169
- url.searchParams.set("state", filters.state);
170
- if (filters.status)
171
- url.searchParams.set("status", filters.status);
172
- if (filters.limit !== undefined)
173
- url.searchParams.set("limit", String(filters.limit));
174
- }
175
- function mergeHeaders(headers, authToken) {
176
- const merged = new Headers(headers);
177
- if (authToken) {
178
- merged.set("authorization", `Bearer ${authToken}`);
179
- }
180
- return merged;
181
- }
182
- function diagnosticMessage(payload) {
183
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
184
- return null;
185
- const record = payload;
186
- const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
187
- const messages = diagnostics.flatMap((entry) => {
188
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
189
- return [];
190
- const diagnostic = entry;
191
- const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
192
- const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
193
- return message ? [`${kind}: ${message}`] : [];
194
- });
195
- return messages.length > 0 ? messages.join("; ") : null;
196
- }
197
- async function requestServerJson(context, pathname, init = {}) {
198
- const server = await ensureServerForCli(context.projectRoot);
199
- const response = await fetch(`${server.baseUrl}${pathname}`, {
200
- ...init,
201
- headers: mergeHeaders(init.headers, server.authToken)
202
- });
203
- const text = await response.text();
204
- const payload = text.trim().length > 0 ? (() => {
205
- try {
206
- return JSON.parse(text);
207
- } catch {
208
- return null;
209
- }
210
- })() : null;
211
- if (!response.ok) {
212
- const diagnostics = diagnosticMessage(payload);
213
- const detail = diagnostics ?? (text || response.statusText);
214
- throw new CliError2(`Rig server request failed (${response.status}): ${detail}`, 1);
215
- }
216
- return payload;
217
- }
218
- async function listWorkspaceTasksViaServer(context, filters = {}) {
219
- const url = new URL("http://rig.local/api/workspace/tasks");
220
- appendTaskFilterParams(url, filters);
221
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
222
- if (!Array.isArray(payload)) {
223
- throw new CliError2("Rig server returned an invalid task list payload.", 1);
224
- }
225
- return payload.flatMap((entry) => entry && typeof entry === "object" && !Array.isArray(entry) ? [entry] : []);
226
- }
227
- async function getWorkspaceTaskViaServer(context, taskId) {
228
- const payload = await requestServerJson(context, `/api/workspace/tasks/${encodeURIComponent(taskId)}`);
229
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
230
- return null;
231
- const task = payload.task;
232
- return task && typeof task === "object" && !Array.isArray(task) ? task : null;
233
- }
234
- async function selectNextWorkspaceTaskViaServer(context, filters = {}) {
235
- const url = new URL("http://rig.local/api/workspace/tasks/next");
236
- appendTaskFilterParams(url, filters);
237
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
238
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
239
- throw new CliError2("Rig server returned an invalid next-task payload.", 1);
240
- }
241
- const record = payload;
242
- const rawTask = record.task;
243
- const task = rawTask && typeof rawTask === "object" && !Array.isArray(rawTask) ? rawTask : null;
244
- const count = typeof record.count === "number" && Number.isFinite(record.count) ? record.count : task ? 1 : 0;
245
- return { task, count };
246
- }
247
- async function getGitHubAuthStatusViaServer(context) {
248
- const payload = await requestServerJson(context, "/api/github/auth/status");
249
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
250
- }
251
- async function postGitHubTokenViaServer(context, token, options = {}) {
252
- const payload = await requestServerJson(context, "/api/github/auth/token", {
253
- method: "POST",
254
- headers: { "content-type": "application/json" },
255
- body: JSON.stringify({ token, selectedRepo: options.selectedRepo, projectRoot: options.projectRoot })
256
- });
257
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
258
- }
259
- async function prepareRemoteCheckoutViaServer(context, input) {
260
- const payload = await requestServerJson(context, `/api/projects/${encodeURIComponent(input.repoSlug)}/prepare-checkout`, {
261
- method: "POST",
262
- headers: { "content-type": "application/json" },
263
- body: JSON.stringify({ checkout: input.checkout, repoUrl: input.repoUrl, baseDir: input.baseDir })
264
- });
265
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
266
- }
267
- async function registerProjectViaServer(context, input) {
268
- const payload = await requestServerJson(context, "/api/projects", {
269
- method: "POST",
270
- headers: { "content-type": "application/json" },
271
- body: JSON.stringify(input)
272
- });
273
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
274
- }
275
- function sleep(ms) {
276
- return new Promise((resolve3) => setTimeout(resolve3, ms));
277
- }
278
- async function switchServerProjectRootViaServer(context, projectRoot, options = {}) {
279
- const switched = await requestServerJson(context, "/api/server/project-root", {
280
- method: "POST",
281
- headers: { "content-type": "application/json" },
282
- body: JSON.stringify({ projectRoot })
283
- });
284
- const timeoutMs = options.timeoutMs ?? 30000;
285
- const pollMs = options.pollMs ?? 1000;
286
- const deadline = Date.now() + timeoutMs;
287
- let lastError;
288
- while (Date.now() < deadline) {
289
- try {
290
- const status = await requestServerJson(context, "/api/server/status");
291
- if (status && typeof status === "object" && !Array.isArray(status)) {
292
- const record = status;
293
- if (record.projectRoot === projectRoot) {
294
- return { ok: true, switched, status: record };
295
- }
296
- lastError = `server projectRoot=${String(record.projectRoot ?? "unknown")}`;
297
- }
298
- } catch (error) {
299
- lastError = error;
300
- }
301
- await sleep(pollMs);
302
- }
303
- throw new CliError2(`Rig server did not switch to ${projectRoot} before timeout (${lastError instanceof Error ? lastError.message : String(lastError ?? "no status")}).`, 1);
304
- }
305
- async function getRunDetailsViaServer(context, runId) {
306
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}`);
307
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
308
- }
309
- async function getRunLogsViaServer(context, runId, options = {}) {
310
- const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/logs`);
311
- if (options.limit !== undefined)
312
- url.searchParams.set("limit", String(options.limit));
313
- if (options.cursor)
314
- url.searchParams.set("cursor", options.cursor);
315
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
316
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
317
- }
318
- async function stopRunViaServer(context, runId) {
319
- const payload = await requestServerJson(context, "/api/runs/stop", {
320
- method: "POST",
321
- headers: { "content-type": "application/json" },
322
- body: JSON.stringify({ runId })
323
- });
324
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true, runId };
325
- }
326
- async function steerRunViaServer(context, runId, message) {
327
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/steer`, {
328
- method: "POST",
329
- headers: { "content-type": "application/json" },
330
- body: JSON.stringify({ message })
331
- });
332
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
333
- }
334
- async function submitTaskRunViaServer(context, input) {
335
- const isTaskRun = Boolean(input.taskId);
336
- const endpoint = isTaskRun ? "/api/runs/task" : "/api/runs/adhoc";
337
- const payload = await requestServerJson(context, endpoint, {
338
- method: "POST",
339
- headers: {
340
- "content-type": "application/json"
341
- },
342
- body: JSON.stringify({
343
- runId: input.runId,
344
- taskId: input.taskId,
345
- title: input.title,
346
- runtimeAdapter: input.runtimeAdapter,
347
- model: input.model,
348
- runtimeMode: input.runtimeMode,
349
- interactionMode: input.interactionMode,
350
- initialPrompt: input.initialPrompt,
351
- baselineMode: input.baselineMode,
352
- prMode: input.prMode,
353
- executionTarget: "local"
354
- })
355
- });
356
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
357
- throw new CliError2("Rig server returned an invalid run submission payload.", 1);
358
- }
359
- const runId = payload.runId;
360
- if (typeof runId !== "string" || runId.trim().length === 0) {
361
- throw new CliError2("Rig server returned no runId for the submitted run.", 1);
362
- }
363
- return { runId };
364
- }
365
- export {
366
- switchServerProjectRootViaServer,
367
- submitTaskRunViaServer,
368
- stopRunViaServer,
369
- steerRunViaServer,
370
- setGitHubBearerTokenForCurrentProcess,
371
- selectNextWorkspaceTaskViaServer,
372
- requestServerJson,
373
- registerProjectViaServer,
374
- prepareRemoteCheckoutViaServer,
375
- postGitHubTokenViaServer,
376
- listWorkspaceTasksViaServer,
377
- getWorkspaceTaskViaServer,
378
- getRunLogsViaServer,
379
- getRunDetailsViaServer,
380
- getGitHubAuthStatusViaServer,
381
- ensureServerForCli
382
- };