@h-rig/cli 0.0.6-alpha.90 → 0.0.6-alpha.91

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 (118) hide show
  1. package/README.md +18 -19
  2. package/dist/bin/build-rig-binaries.js +22 -10
  3. package/dist/bin/rig.d.ts +71 -1
  4. package/dist/bin/rig.js +15078 -11169
  5. package/dist/config/rig-default-config.yml +5 -0
  6. package/dist/src/app/drone-ui.d.ts +11 -14
  7. package/dist/src/app/drone-ui.js +70 -86
  8. package/dist/src/commands/_async-ui.d.ts +1 -4
  9. package/dist/src/commands/_async-ui.js +9 -111
  10. package/dist/src/commands/_cli-format.d.ts +16 -9
  11. package/dist/src/commands/_cli-format.js +167 -295
  12. package/dist/src/commands/_connection-state.d.ts +11 -1
  13. package/dist/src/commands/_connection-state.js +50 -5
  14. package/dist/src/commands/_doctor-checks.d.ts +0 -6
  15. package/dist/src/commands/_doctor-checks.js +79 -382
  16. package/dist/src/commands/_help-catalog.d.ts +1 -1
  17. package/dist/src/commands/_help-catalog.js +217 -157
  18. package/dist/src/commands/_inprocess-services.d.ts +33 -0
  19. package/dist/src/commands/_inprocess-services.js +102 -0
  20. package/dist/src/commands/_json-output.js +4 -0
  21. package/dist/src/commands/_lazy-reconcile.d.ts +34 -0
  22. package/dist/src/commands/_lazy-reconcile.js +102 -0
  23. package/dist/src/commands/_paths.js +1 -1
  24. package/dist/src/commands/_pi-frontend.d.ts +18 -10
  25. package/dist/src/commands/_pi-frontend.js +37 -715
  26. package/dist/src/commands/_pi-install.js +18 -36
  27. package/dist/src/commands/_policy.d.ts +1 -1
  28. package/dist/src/commands/_policy.js +56 -15
  29. package/dist/src/commands/_run-bridge.d.ts +114 -0
  30. package/dist/src/commands/_run-bridge.js +387 -0
  31. package/dist/src/commands/_run-diagnostics.d.ts +9 -0
  32. package/dist/src/commands/_run-diagnostics.js +51 -0
  33. package/dist/src/commands/_run-driver-helpers.d.ts +8 -81
  34. package/dist/src/commands/_run-driver-helpers.js +79 -283
  35. package/dist/src/commands/_run-projection.d.ts +50 -0
  36. package/dist/src/commands/_run-projection.js +349 -0
  37. package/dist/src/commands/_run-subcommands.d.ts +3 -0
  38. package/dist/src/commands/_run-subcommands.js +31 -0
  39. package/dist/src/commands/_spinner.js +1 -1
  40. package/dist/src/commands/agent.d.ts +1 -1
  41. package/dist/src/commands/agent.js +8559 -239
  42. package/dist/src/commands/dist.d.ts +1 -1
  43. package/dist/src/commands/dist.js +27 -19
  44. package/dist/src/commands/doctor.d.ts +1 -1
  45. package/dist/src/commands/doctor.js +93 -475
  46. package/dist/src/commands/github.d.ts +1 -1
  47. package/dist/src/commands/github.js +113 -387
  48. package/dist/src/commands/inbox.d.ts +22 -24
  49. package/dist/src/commands/inbox.js +420 -691
  50. package/dist/src/commands/init.d.ts +6 -16
  51. package/dist/src/commands/init.js +334 -971
  52. package/dist/src/commands/inspect.d.ts +19 -2
  53. package/dist/src/commands/inspect.js +644 -610
  54. package/dist/src/commands/pi.d.ts +1 -1
  55. package/dist/src/commands/plugin.d.ts +1 -1
  56. package/dist/src/commands/plugin.js +486 -7
  57. package/dist/src/commands/profile-and-review.d.ts +1 -1
  58. package/dist/src/commands/profile-and-review.js +94 -56
  59. package/dist/src/commands/queue.js +1 -21
  60. package/dist/src/commands/remote.d.ts +1 -1
  61. package/dist/src/commands/remote.js +837 -14
  62. package/dist/src/commands/repo-git-harness.d.ts +1 -1
  63. package/dist/src/commands/repo-git-harness.js +57 -14
  64. package/dist/src/commands/run.d.ts +20 -2
  65. package/dist/src/commands/run.js +17579 -1759
  66. package/dist/src/commands/server.d.ts +2 -6
  67. package/dist/src/commands/server.js +141 -723
  68. package/dist/src/commands/setup.d.ts +1 -1
  69. package/dist/src/commands/setup.js +102 -484
  70. package/dist/src/commands/stats.d.ts +13 -10
  71. package/dist/src/commands/stats.js +689 -761
  72. package/dist/src/commands/task-run-driver.d.ts +50 -88
  73. package/dist/src/commands/task-run-driver.js +116 -2717
  74. package/dist/src/commands/task.d.ts +34 -13
  75. package/dist/src/commands/task.js +668 -2523
  76. package/dist/src/commands/test.d.ts +1 -1
  77. package/dist/src/commands/triage.d.ts +11 -0
  78. package/dist/src/commands/triage.js +227 -0
  79. package/dist/src/commands/workspace.d.ts +1 -1
  80. package/dist/src/commands.d.ts +0 -16
  81. package/dist/src/commands.js +16657 -12250
  82. package/dist/src/index.js +16528 -12497
  83. package/dist/src/launcher.js +4 -0
  84. package/dist/src/operator-cli.d.ts +2 -0
  85. package/dist/src/operator-cli.js +17837 -0
  86. package/dist/src/operator-entry.d.ts +1 -0
  87. package/dist/src/operator-entry.js +3 -0
  88. package/package.json +18 -12
  89. package/dist/src/app/board.d.ts +0 -23
  90. package/dist/src/app/board.js +0 -1786
  91. package/dist/src/app/theme.d.ts +0 -47
  92. package/dist/src/app/theme.js +0 -150
  93. package/dist/src/commands/_authority-runs.d.ts +0 -22
  94. package/dist/src/commands/_authority-runs.js +0 -110
  95. package/dist/src/commands/_operator-surface.d.ts +0 -34
  96. package/dist/src/commands/_operator-surface.js +0 -220
  97. package/dist/src/commands/_operator-view.d.ts +0 -30
  98. package/dist/src/commands/_operator-view.js +0 -1070
  99. package/dist/src/commands/_preflight.d.ts +0 -22
  100. package/dist/src/commands/_preflight.js +0 -540
  101. package/dist/src/commands/_run-replay.d.ts +0 -24
  102. package/dist/src/commands/_run-replay.js +0 -142
  103. package/dist/src/commands/_server-client.d.ts +0 -186
  104. package/dist/src/commands/_server-client.js +0 -681
  105. package/dist/src/commands/_snapshot-upload.d.ts +0 -39
  106. package/dist/src/commands/_snapshot-upload.js +0 -455
  107. package/dist/src/commands/_task-picker.d.ts +0 -9
  108. package/dist/src/commands/_task-picker.js +0 -201
  109. package/dist/src/commands/browser.d.ts +0 -65
  110. package/dist/src/commands/browser.js +0 -1173
  111. package/dist/src/commands/connect.d.ts +0 -7
  112. package/dist/src/commands/connect.js +0 -419
  113. package/dist/src/commands/inspector.d.ts +0 -3
  114. package/dist/src/commands/inspector.js +0 -263
  115. package/dist/src/commands/task-report-bug.d.ts +0 -19
  116. package/dist/src/commands/task-report-bug.js +0 -1281
  117. package/dist/src/report-bug.d.ts +0 -44
  118. package/dist/src/report-bug.js +0 -260
@@ -1,3 +1,3 @@
1
1
  import { type RunnerContext } from "../runner";
2
- import type { CommandOutcome } from "@rig/runtime/control-plane/runtime/types";
2
+ import type { CommandOutcome } from "@rig/runtime";
3
3
  export declare function executeGithub(context: RunnerContext, args: string[]): Promise<CommandOutcome>;
@@ -1,6 +1,8 @@
1
1
  // @bun
2
2
  // packages/cli/src/commands/github.ts
3
3
  import { spawnSync } from "child_process";
4
+ import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
5
+ import { dirname as dirname2, resolve as resolve3 } from "path";
4
6
 
5
7
  // packages/cli/src/runner.ts
6
8
  import { EventBus } from "@rig/runtime/control-plane/runtime/events";
@@ -38,26 +40,53 @@ function takeOption(args, option) {
38
40
  return { value, rest };
39
41
  }
40
42
 
41
- // packages/cli/src/commands/_server-client.ts
42
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
43
- import { resolve as resolve2 } from "path";
44
- import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
43
+ // packages/cli/src/commands/_inprocess-services.ts
44
+ import { resolve } from "path";
45
+ import {
46
+ beginGitHubDeviceFlow,
47
+ checkGitHubRepoPermissions,
48
+ createGitHubAuthStore,
49
+ listGitHubProjects,
50
+ pollGitHubDeviceFlow,
51
+ resolveGitHubAuthStatus,
52
+ resolveProjectStatusField,
53
+ saveGitHubTokenForProject
54
+ } from "@rig/runtime/control-plane/github/index";
55
+ var scopedGitHubBearerTokens = new Map;
56
+ function cleanToken(value) {
57
+ const trimmed = value?.trim();
58
+ return trimmed ? trimmed : null;
59
+ }
60
+ function oauthClientId() {
61
+ return cleanToken(process.env.RIG_GITHUB_OAUTH_CLIENT_ID);
62
+ }
63
+ function setGitHubBearerTokenForCurrentProcess(token, projectRoot) {
64
+ scopedGitHubBearerTokens.set(resolve(projectRoot ?? process.cwd()), cleanToken(token));
65
+ }
66
+ async function getGitHubAuthStatusInProcess(context) {
67
+ return { ok: true, ...resolveGitHubAuthStatus({ projectRoot: context.projectRoot, oauthConfigured: Boolean(oauthClientId()) }) };
68
+ }
69
+ async function postGitHubTokenInProcess(context, token, options = {}) {
70
+ const targetRoot = options.projectRoot?.trim() || context.projectRoot;
71
+ const result = await saveGitHubTokenForProject({
72
+ projectRoot: targetRoot,
73
+ token,
74
+ tokenSource: "manual-token",
75
+ selectedRepo: options.selectedRepo ?? null
76
+ });
77
+ const store = createGitHubAuthStore(targetRoot);
78
+ const session = store.createApiSession();
79
+ if (targetRoot !== context.projectRoot) {
80
+ store.copyToLocalProjectRoot(context.projectRoot);
81
+ }
82
+ return { ...result, authenticated: result.signedIn, apiSessionToken: session.token };
83
+ }
45
84
 
46
85
  // packages/cli/src/commands/_connection-state.ts
47
86
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
48
- import { homedir } from "os";
49
- import { dirname, resolve } from "path";
50
- function resolveGlobalConnectionsPath(env = process.env) {
51
- const explicit = env.RIG_CONNECTIONS_FILE?.trim();
52
- if (explicit)
53
- return resolve(explicit);
54
- const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
55
- if (stateDir)
56
- return resolve(stateDir, "connections.json");
57
- return resolve(homedir(), ".rig", "connections.json");
58
- }
87
+ import { dirname, resolve as resolve2 } from "path";
59
88
  function resolveRepoConnectionPath(projectRoot) {
60
- return resolve(projectRoot, ".rig", "state", "connection.json");
89
+ return resolve2(projectRoot, ".rig", "state", "connection.json");
61
90
  }
62
91
  function readJsonFile(path) {
63
92
  if (!existsSync(path))
@@ -68,40 +97,6 @@ function readJsonFile(path) {
68
97
  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>`." });
69
98
  }
70
99
  }
71
- function writeJsonFile(path, value) {
72
- mkdirSync(dirname(path), { recursive: true });
73
- writeFileSync(path, `${JSON.stringify(value, null, 2)}
74
- `, "utf8");
75
- }
76
- function normalizeConnection(value) {
77
- if (!value || typeof value !== "object" || Array.isArray(value))
78
- return null;
79
- const record = value;
80
- if (record.kind === "local")
81
- return { kind: "local", mode: "auto" };
82
- if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
83
- const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
84
- return { kind: "remote", baseUrl };
85
- }
86
- return null;
87
- }
88
- function readGlobalConnections(options = {}) {
89
- const path = resolveGlobalConnectionsPath(options.env ?? process.env);
90
- const payload = readJsonFile(path);
91
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
92
- return { connections: {} };
93
- }
94
- const rawConnections = payload.connections;
95
- const connections = {};
96
- if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
97
- for (const [alias, raw] of Object.entries(rawConnections)) {
98
- const connection = normalizeConnection(raw);
99
- if (connection)
100
- connections[alias] = connection;
101
- }
102
- }
103
- return { connections };
104
- }
105
100
  function readRepoConnection(projectRoot) {
106
101
  const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
107
102
  if (!payload || typeof payload !== "object" || Array.isArray(payload))
@@ -114,256 +109,11 @@ function readRepoConnection(projectRoot) {
114
109
  selected,
115
110
  project: typeof record.project === "string" ? record.project : undefined,
116
111
  linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
117
- serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
112
+ serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined,
113
+ serverProjectRootAlias: typeof record.serverProjectRootAlias === "string" && record.serverProjectRootAlias.trim() ? record.serverProjectRootAlias.trim() : undefined,
114
+ serverProjectRootBaseUrl: typeof record.serverProjectRootBaseUrl === "string" && record.serverProjectRootBaseUrl.trim() ? record.serverProjectRootBaseUrl.trim().replace(/\/+$/, "") : undefined
118
115
  };
119
116
  }
120
- function writeRepoConnection(projectRoot, state) {
121
- writeJsonFile(resolveRepoConnectionPath(projectRoot), state);
122
- }
123
- function resolveSelectedConnection(projectRoot, options = {}) {
124
- const repo = readRepoConnection(projectRoot);
125
- if (!repo)
126
- return null;
127
- if (repo.selected === "local")
128
- return { alias: "local", connection: { kind: "local", mode: "auto" }, serverProjectRoot: repo.serverProjectRoot };
129
- const global = readGlobalConnections(options);
130
- const connection = global.connections[repo.selected];
131
- if (!connection) {
132
- throw new CliError(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
133
- }
134
- return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
135
- }
136
- function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
137
- const repo = readRepoConnection(projectRoot);
138
- if (!repo)
139
- return;
140
- writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
141
- }
142
-
143
- // packages/cli/src/commands/_server-client.ts
144
- var scopedGitHubBearerTokens = new Map;
145
- var serverPhaseListener = null;
146
- function setServerPhaseListener(listener) {
147
- const previous = serverPhaseListener;
148
- serverPhaseListener = listener;
149
- return previous;
150
- }
151
- function reportServerPhase(label) {
152
- serverPhaseListener?.(label);
153
- }
154
- function cleanToken(value) {
155
- const trimmed = value?.trim();
156
- return trimmed ? trimmed : null;
157
- }
158
- function readPrivateRemoteSessionToken(projectRoot) {
159
- const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
160
- if (!existsSync2(path))
161
- return null;
162
- try {
163
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
164
- return cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined);
165
- } catch {
166
- return null;
167
- }
168
- }
169
- function readGitHubBearerTokenForRemote(projectRoot) {
170
- const scopedKey = resolve2(projectRoot);
171
- if (scopedGitHubBearerTokens.has(scopedKey))
172
- return scopedGitHubBearerTokens.get(scopedKey) ?? null;
173
- const privateSession = readPrivateRemoteSessionToken(projectRoot);
174
- if (privateSession)
175
- return privateSession;
176
- return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
177
- }
178
- function readStoredGitHubAuthToken(projectRoot) {
179
- const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
180
- if (!existsSync2(path))
181
- return null;
182
- try {
183
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
184
- return cleanToken(typeof parsed.token === "string" ? parsed.token : undefined);
185
- } catch {
186
- return null;
187
- }
188
- }
189
- function readLocalConnectionFallbackToken(projectRoot) {
190
- return readGitHubBearerTokenForRemote(projectRoot) ?? cleanToken(process.env.RIG_GITHUB_TOKEN) ?? readStoredGitHubAuthToken(projectRoot);
191
- }
192
- async function ensureServerForCli(projectRoot) {
193
- try {
194
- const selected = resolveSelectedConnection(projectRoot);
195
- if (selected?.connection.kind === "remote") {
196
- reportServerPhase(`Connecting to ${selected.alias}\u2026`);
197
- const authToken = readGitHubBearerTokenForRemote(projectRoot);
198
- const serverProjectRoot = selected.serverProjectRoot ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
199
- return {
200
- baseUrl: selected.connection.baseUrl,
201
- authToken,
202
- connectionKind: "remote",
203
- serverProjectRoot
204
- };
205
- }
206
- reportServerPhase("Starting local Rig server\u2026");
207
- const connection = await ensureLocalRigServerConnection(projectRoot);
208
- return {
209
- baseUrl: connection.baseUrl,
210
- authToken: connection.authToken ?? readLocalConnectionFallbackToken(projectRoot),
211
- connectionKind: "local",
212
- serverProjectRoot: resolve2(projectRoot)
213
- };
214
- } catch (error) {
215
- if (error instanceof Error) {
216
- throw new CliError(error.message, 1);
217
- }
218
- throw error;
219
- }
220
- }
221
- async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
222
- const repo = readRepoConnection(projectRoot);
223
- const slug = repo?.project?.trim();
224
- if (!slug)
225
- return null;
226
- try {
227
- const response = await fetch(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`, {
228
- headers: mergeHeaders(undefined, authToken)
229
- });
230
- if (!response.ok)
231
- return null;
232
- const payload = await response.json();
233
- const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
234
- const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
235
- const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
236
- const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
237
- if (path)
238
- writeRepoServerProjectRoot(projectRoot, path);
239
- return path;
240
- } catch {
241
- return null;
242
- }
243
- }
244
- function mergeHeaders(headers, authToken) {
245
- const merged = new Headers(headers);
246
- if (authToken) {
247
- merged.set("authorization", `Bearer ${authToken}`);
248
- }
249
- return merged;
250
- }
251
- function diagnosticMessage(payload) {
252
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
253
- return null;
254
- const record = payload;
255
- const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
256
- const messages = diagnostics.flatMap((entry) => {
257
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
258
- return [];
259
- const diagnostic = entry;
260
- const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
261
- const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
262
- return message ? [`${kind}: ${message}`] : [];
263
- });
264
- return messages.length > 0 ? messages.join("; ") : null;
265
- }
266
- var serverReachabilityCache = new Map;
267
- async function probeServerReachability(baseUrl, authToken) {
268
- try {
269
- const response = await fetch(`${baseUrl.replace(/\/+$/, "")}/api/server/status`, {
270
- headers: mergeHeaders(undefined, authToken),
271
- signal: AbortSignal.timeout(1500)
272
- });
273
- return response.ok;
274
- } catch {
275
- return false;
276
- }
277
- }
278
- function cachedServerReachability(projectRoot, baseUrl, authToken) {
279
- const key = resolve2(projectRoot);
280
- const cached = serverReachabilityCache.get(key);
281
- if (cached)
282
- return cached;
283
- const probe = probeServerReachability(baseUrl, authToken);
284
- serverReachabilityCache.set(key, probe);
285
- return probe;
286
- }
287
- function describeSelectedServer(projectRoot, server) {
288
- try {
289
- const selected = resolveSelectedConnection(projectRoot);
290
- if (selected) {
291
- return {
292
- alias: selected.alias,
293
- target: selected.connection.kind === "remote" ? selected.connection.baseUrl : server.baseUrl
294
- };
295
- }
296
- } catch {}
297
- return { alias: server.connectionKind === "remote" ? "remote" : "local", target: server.baseUrl };
298
- }
299
- async function buildServerFailureContext(projectRoot, server) {
300
- const { alias, target } = describeSelectedServer(projectRoot, server);
301
- const reachable = await cachedServerReachability(projectRoot, server.baseUrl, server.authToken);
302
- const reachability = reachable ? "server is reachable" : "server is unreachable";
303
- return {
304
- contextLine: `Currently connected to: ${alias} at ${target} (${reachability}).`,
305
- hint: "Check the selected server with `rig server status`, or switch with `rig server use <alias|local>`."
306
- };
307
- }
308
- async function requestServerJson(context, pathname, init = {}) {
309
- const server = await ensureServerForCli(context.projectRoot);
310
- const headers = mergeHeaders(init.headers, server.authToken);
311
- if (server.serverProjectRoot)
312
- headers.set("x-rig-project-root", server.serverProjectRoot);
313
- reportServerPhase(`${(init.method ?? "GET").toUpperCase()} ${pathname.split("?")[0]}\u2026`);
314
- let response;
315
- try {
316
- response = await fetch(`${server.baseUrl}${pathname}`, {
317
- ...init,
318
- headers
319
- });
320
- } catch (error) {
321
- const failure = await buildServerFailureContext(context.projectRoot, server);
322
- throw new CliError(`Rig server request failed: ${error instanceof Error ? error.message : String(error)}
323
- ${failure.contextLine}`, 1, { hint: failure.hint });
324
- }
325
- const text = await response.text();
326
- const payload = text.trim().length > 0 ? (() => {
327
- try {
328
- return JSON.parse(text);
329
- } catch {
330
- return null;
331
- }
332
- })() : null;
333
- if (!response.ok) {
334
- const diagnostics = diagnosticMessage(payload);
335
- const rawDetail = diagnostics ?? (text || response.statusText);
336
- const detail = diagnostics ? rawDetail : rawDetail.split(`
337
- `).map((line) => line.trim()).find((line) => line.length > 0)?.slice(0, 200) ?? response.statusText;
338
- const failure = await buildServerFailureContext(context.projectRoot, server);
339
- throw new CliError(`Rig server request failed (${response.status}): ${detail}
340
- ${failure.contextLine}`, 1, { hint: failure.hint });
341
- }
342
- return payload;
343
- }
344
- async function getGitHubAuthStatusViaServer(context) {
345
- const payload = await requestServerJson(context, "/api/github/auth/status");
346
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
347
- }
348
- async function postGitHubTokenViaServer(context, token, options = {}) {
349
- const payload = await requestServerJson(context, "/api/github/auth/token", {
350
- method: "POST",
351
- headers: { "content-type": "application/json" },
352
- body: JSON.stringify({ token, selectedRepo: options.selectedRepo, projectRoot: options.projectRoot })
353
- });
354
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
355
- }
356
- var RESUMABLE_RUN_STATUSES = new Set([
357
- "created",
358
- "preparing",
359
- "running",
360
- "validating",
361
- "reviewing",
362
- "stopped",
363
- "failed",
364
- "needs-attention",
365
- "needs_attention"
366
- ]);
367
117
 
368
118
  // packages/cli/src/commands/_async-ui.ts
369
119
  import pc from "picocolors";
@@ -399,7 +149,7 @@ function createTtySpinner(input) {
399
149
  output.write("\r\x1B[2K");
400
150
  };
401
151
  render();
402
- const timer = isTty ? setInterval(render, input.intervalMs ?? 120) : null;
152
+ const timer = isTty ? setInterval(render, input.intervalMs ?? 16) : null;
403
153
  return {
404
154
  setLabel(next) {
405
155
  label = next;
@@ -429,90 +179,20 @@ function createTtySpinner(input) {
429
179
  };
430
180
  }
431
181
 
432
- // packages/cli/src/app/theme.ts
433
- var RIG_PALETTE = {
434
- ink: "#f2f3f6",
435
- ink2: "#aeb0ba",
436
- ink3: "#6c6e79",
437
- ink4: "#44464f",
438
- accent: "#ccff4d",
439
- accentDim: "#a9d63f",
440
- cyan: "#56d8ff",
441
- red: "#ff5d5d",
442
- yellow: "#ffd24d"
443
- };
444
- function hexToRgb(hex) {
445
- const value = hex.replace("#", "");
446
- return [
447
- Number.parseInt(value.slice(0, 2), 16),
448
- Number.parseInt(value.slice(2, 4), 16),
449
- Number.parseInt(value.slice(4, 6), 16)
450
- ];
451
- }
452
- function fg(hex) {
453
- const [r, g, b] = hexToRgb(hex);
454
- return (text) => `\x1B[38;2;${r};${g};${b}m${text}\x1B[39m`;
455
- }
456
- var ink = fg(RIG_PALETTE.ink);
457
- var ink2 = fg(RIG_PALETTE.ink2);
458
- var ink3 = fg(RIG_PALETTE.ink3);
459
- var ink4 = fg(RIG_PALETTE.ink4);
460
- var accent = fg(RIG_PALETTE.accent);
461
- var accentDim = fg(RIG_PALETTE.accentDim);
462
- var cyan = fg(RIG_PALETTE.cyan);
463
- var red = fg(RIG_PALETTE.red);
464
- var yellow = fg(RIG_PALETTE.yellow);
465
- function bold(text) {
466
- return `\x1B[1m${text}\x1B[22m`;
467
- }
468
- var DRONE_ART = [
469
- " .-=-. .-=-. ",
470
- " ( !!! ) ( !!! ) ",
471
- " '-=-'._ _.'-=-' ",
472
- " '._ _.' ",
473
- " '=$$$$$$$=.' ",
474
- " =$$$$$$$$$$$= ",
475
- " $$$@@@@@@@@@@$$$ ",
476
- " $$$@@ @@$$$ ",
477
- " $$@ ? @$$$ ",
478
- " $$$@ '-' @$$$ ",
479
- " $$$@@ @@$$$ ",
480
- " $$$@@@@@@@@@@$$$ ",
481
- " =$$$$$$$$$$$= ",
482
- " '=$$$$$$$=.' ",
483
- " _.' '._ ",
484
- " .-=-.' '.-=-. ",
485
- " ( !!! ) ( !!! ) ",
486
- " '-=-' '-=-' "
487
- ];
488
- var EYE_FRAMES = ["@", "o", "."];
489
- var DRONE_WIDTH = DRONE_ART[0].length;
490
- var DRONE_HEIGHT = DRONE_ART.length;
491
- var MICRO_BLADES = ["---", "\\\\\\", "|||", "///"];
492
- function microDroneFrame(tick) {
493
- const blade = MICRO_BLADES[tick % MICRO_BLADES.length];
494
- const eye = EYE_FRAMES[Math.floor(tick / 2) % EYE_FRAMES.length];
495
- return `(${blade})${eye}(${blade})`;
496
- }
497
- var MICRO_DRONE_FRAMES = Array.from({ length: 12 }, (_, index) => microDroneFrame(index));
498
- function renderMicroDroneFrame(tick) {
499
- const blade = MICRO_BLADES[tick % MICRO_BLADES.length];
500
- const eye = EYE_FRAMES[Math.floor(tick / 2) % EYE_FRAMES.length];
501
- return `${ink4("(")}${cyan(blade)}${ink4(")")}${bold(accent(eye))}${ink4("(")}${cyan(blade)}${ink4(")")}`;
502
- }
503
-
504
182
  // packages/cli/src/commands/_async-ui.ts
183
+ var FRAMES = ["\u25D0", "\u25D3", "\u25D1", "\u25D2"];
505
184
  var DONE_SYMBOL = pc.green("\u25C7");
506
185
  var FAIL_SYMBOL = pc.red("\u25A0");
507
186
  var activeUpdate = null;
508
187
  async function withSpinner(label, work, options = {}) {
509
188
  if (options.outputMode === "json") {
510
- return work(() => {});
189
+ return work(() => {
190
+ return;
191
+ });
511
192
  }
512
193
  if (activeUpdate) {
513
- const outer = activeUpdate;
514
- outer(label);
515
- return work(outer);
194
+ activeUpdate(label);
195
+ return work(activeUpdate);
516
196
  }
517
197
  const output = options.output ?? process.stderr;
518
198
  const isTty = output.isTTY === true;
@@ -524,26 +204,23 @@ async function withSpinner(label, work, options = {}) {
524
204
  lastLabel = next;
525
205
  };
526
206
  activeUpdate = update2;
527
- const previousListener2 = setServerPhaseListener(update2);
528
207
  try {
529
208
  return await work(update2);
530
209
  } finally {
531
210
  activeUpdate = null;
532
- setServerPhaseListener(previousListener2);
533
211
  }
534
212
  }
535
213
  const spinner = createTtySpinner({
536
214
  label,
537
215
  output,
538
- frames: MICRO_DRONE_FRAMES,
539
- styleFrame: (frame) => renderMicroDroneFrame(Math.max(0, MICRO_DRONE_FRAMES.indexOf(frame)))
216
+ frames: FRAMES,
217
+ styleFrame: (frame) => pc.cyan(frame)
540
218
  });
541
219
  const update = (next) => {
542
220
  lastLabel = next;
543
221
  spinner.setLabel(next);
544
222
  };
545
223
  activeUpdate = update;
546
- const previousListener = setServerPhaseListener(update);
547
224
  try {
548
225
  const result = await work(update);
549
226
  spinner.stop(options.doneLabel ? `${DONE_SYMBOL} ${options.doneLabel}` : undefined);
@@ -553,7 +230,6 @@ async function withSpinner(label, work, options = {}) {
553
230
  throw error;
554
231
  } finally {
555
232
  activeUpdate = null;
556
- setServerPhaseListener(previousListener);
557
233
  }
558
234
  }
559
235
 
@@ -564,6 +240,52 @@ function printPayload(context, payload, fallback) {
564
240
  else
565
241
  console.log(fallback);
566
242
  }
243
+ function apiSessionTokenFrom(payload) {
244
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
245
+ return null;
246
+ return payloadString(payload, "apiSessionToken");
247
+ }
248
+ function payloadString(payload, key) {
249
+ const value = Reflect.get(payload, key);
250
+ return typeof value === "string" && value.trim() ? value.trim() : null;
251
+ }
252
+ function payloadRecord(payload, key) {
253
+ const value = Reflect.get(payload, key);
254
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
255
+ }
256
+ function remoteNamespaceMetadata(result) {
257
+ const namespace = payloadRecord(result, "userNamespace");
258
+ return {
259
+ ...payloadString(result, "login") ? { login: payloadString(result, "login") } : {},
260
+ ...payloadString(result, "userId") ? { userId: payloadString(result, "userId") } : {},
261
+ ...namespace && payloadString(namespace, "key") ? { userNamespaceKey: payloadString(namespace, "key") } : {},
262
+ ...namespace && payloadString(namespace, "root") ? { userNamespaceRoot: payloadString(namespace, "root") } : {},
263
+ ...namespace && payloadString(namespace, "checkoutBaseDir") ? { checkoutBaseDir: payloadString(namespace, "checkoutBaseDir") } : {},
264
+ ...namespace && payloadString(namespace, "snapshotBaseDir") ? { snapshotBaseDir: payloadString(namespace, "snapshotBaseDir") } : {}
265
+ };
266
+ }
267
+ function persistRemoteAuthSession(context, source, result, fallbackToken) {
268
+ const apiSessionToken = result.apiSessionToken || apiSessionTokenFrom(result);
269
+ setGitHubBearerTokenForCurrentProcess(apiSessionToken ?? fallbackToken, context.projectRoot);
270
+ if (!apiSessionToken)
271
+ return;
272
+ const repo = readRepoConnection(context.projectRoot);
273
+ const path = resolve3(context.projectRoot, ".rig", "state", "github-auth.json");
274
+ mkdirSync2(dirname2(path), { recursive: true });
275
+ writeFileSync2(path, `${JSON.stringify({
276
+ authenticated: true,
277
+ source,
278
+ storedOnServer: true,
279
+ ...repo?.project ? { selectedRepo: repo.project } : {},
280
+ ...remoteNamespaceMetadata(result),
281
+ apiSessionToken,
282
+ updatedAt: new Date().toISOString()
283
+ }, null, 2)}
284
+ `, "utf8");
285
+ }
286
+ function isSignedIn(status) {
287
+ return status.signedIn === true;
288
+ }
567
289
  function readGhToken() {
568
290
  const result = spawnSync("gh", ["auth", "token"], { encoding: "utf8" });
569
291
  if (result.status !== 0) {
@@ -584,8 +306,8 @@ async function executeGithub(context, args) {
584
306
  case "status": {
585
307
  if (rest.length > 0)
586
308
  throw new CliError("Usage: rig github auth status", 1);
587
- const status = await withSpinner("Checking GitHub auth on the server\u2026", () => getGitHubAuthStatusViaServer(context), { outputMode: context.outputMode });
588
- printPayload(context, status, `GitHub auth: ${status.authenticated ? "authenticated" : "unauthenticated"}`);
309
+ const status = await withSpinner("Checking GitHub auth on the server\u2026", () => getGitHubAuthStatusInProcess(context), { outputMode: context.outputMode });
310
+ printPayload(context, status, `GitHub auth: ${isSignedIn(status) ? "authenticated" : "unauthenticated"}`);
589
311
  return { ok: true, group: "github", command: "auth status", details: status };
590
312
  }
591
313
  case "token": {
@@ -595,16 +317,20 @@ async function executeGithub(context, args) {
595
317
  const token = parsed.value?.trim();
596
318
  if (!token)
597
319
  throw new CliError("Missing --token value.", 1, { hint: "Re-run as `rig github auth token --token <token>`." });
598
- const result = await withSpinner("Storing GitHub token on the server\u2026", () => postGitHubTokenViaServer(context, token), { outputMode: context.outputMode });
599
- printPayload(context, result, "GitHub token stored on the selected Rig server.");
320
+ const repo = readRepoConnection(context.projectRoot);
321
+ const result = await withSpinner("Storing GitHub token on the server\u2026", () => postGitHubTokenInProcess(context, token, repo?.project ? { selectedRepo: repo.project } : {}), { outputMode: context.outputMode });
322
+ persistRemoteAuthSession(context, "token", result, token);
323
+ printPayload(context, result, "GitHub token stored on the selected server.");
600
324
  return { ok: true, group: "github", command: "auth token", details: result };
601
325
  }
602
326
  case "import-gh": {
603
327
  if (rest.length > 0)
604
328
  throw new CliError("Usage: rig github auth import-gh", 1);
605
329
  const importedToken = readGhToken();
606
- const result = await withSpinner("Storing GitHub token on the server\u2026", () => postGitHubTokenViaServer(context, importedToken), { outputMode: context.outputMode });
607
- printPayload(context, result, "GitHub token imported from gh and stored on the selected Rig server.");
330
+ const repo = readRepoConnection(context.projectRoot);
331
+ const result = await withSpinner("Storing GitHub token on the server\u2026", () => postGitHubTokenInProcess(context, importedToken, repo?.project ? { selectedRepo: repo.project } : {}), { outputMode: context.outputMode });
332
+ persistRemoteAuthSession(context, "gh", result, importedToken);
333
+ printPayload(context, result, "GitHub token imported from gh and stored on the selected server.");
608
334
  return { ok: true, group: "github", command: "auth import-gh", details: result };
609
335
  }
610
336
  default:
@@ -1,30 +1,28 @@
1
1
  import { type RunnerContext } from "../runner";
2
- import type { CommandOutcome } from "@rig/runtime/control-plane/runtime/types";
2
+ import type { CommandOutcome } from "@rig/runtime";
3
+ import { type RunProjectionRecord } from "./_run-projection";
3
4
  export type InboxKind = "approvals" | "inputs";
4
- export type InboxRecord = {
5
- runId?: string;
6
- taskId?: string | null;
7
- requestId?: string | null;
8
- status?: string | null;
9
- record?: Record<string, unknown>;
10
- };
11
- /** Exported for the board's inbox view — same records `rig inbox` renders. */
12
- export declare function listInboxRecords(context: Pick<RunnerContext, "projectRoot">, kind: InboxKind, filters: {
13
- run?: string;
14
- task?: string;
15
- pendingOnly?: boolean;
16
- }): Promise<InboxRecord[]>;
17
- /**
18
- * Pending-gate counts for proactive surfacing. Returns null when the server
19
- * is unreachable footer callers must never break the primary command.
20
- */
5
+ export interface InboxFilters {
6
+ readonly run?: string;
7
+ readonly task?: string;
8
+ }
9
+ export interface InboxRecord {
10
+ readonly runId: string;
11
+ readonly taskId: string | null;
12
+ readonly requestId: string;
13
+ readonly status: "pending";
14
+ readonly prompt: string;
15
+ readonly requestedAt: string;
16
+ readonly payload: unknown;
17
+ }
18
+ /** Every pending inbox request across discoverable runs, optionally filtered by run/task. */
19
+ export interface InboxDeps {
20
+ readonly listRuns?: (projectRoot: string) => Promise<RunProjectionRecord[]>;
21
+ }
22
+ export declare function listInboxRecords(context: Pick<RunnerContext, "projectRoot">, kind: InboxKind, filters?: InboxFilters, deps?: InboxDeps): Promise<InboxRecord[]>;
23
+ /** Pending-gate counts for proactive surfacing; null-safe for footer callers. */
21
24
  export declare function readPendingInboxCounts(context: Pick<RunnerContext, "projectRoot">): Promise<{
22
25
  approvals: number;
23
26
  inputs: number;
24
27
  } | null>;
25
- /**
26
- * One-line warning under task/run command output when human gates are
27
- * waiting. Silent when there is nothing pending or the server is down.
28
- */
29
- export declare function printPendingInboxFooter(context: RunnerContext): Promise<void>;
30
- export declare function executeInbox(context: RunnerContext, args: string[]): Promise<CommandOutcome>;
28
+ export declare function executeInbox(context: RunnerContext, args: string[], deps?: InboxDeps): Promise<CommandOutcome>;