@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.
Files changed (198) hide show
  1. package/README.md +1 -1
  2. package/dist/bin/build-rig-binaries.d.ts +2 -0
  3. package/dist/bin/rig.d.ts +2 -0
  4. package/dist/bin/rig.js +18374 -8205
  5. package/dist/src/app/board.d.ts +23 -0
  6. package/dist/src/app/board.js +1815 -0
  7. package/dist/src/app/drone-ui.d.ts +37 -0
  8. package/dist/src/app/drone-ui.js +294 -0
  9. package/dist/src/app/theme.d.ts +47 -0
  10. package/dist/src/app/theme.js +151 -0
  11. package/dist/src/app-opentui/adapters/common.d.ts +53 -0
  12. package/dist/src/app-opentui/adapters/common.js +149 -0
  13. package/dist/src/app-opentui/adapters/doctor.d.ts +11 -0
  14. package/dist/src/app-opentui/adapters/doctor.js +780 -0
  15. package/dist/src/app-opentui/adapters/fleet.d.ts +16 -0
  16. package/dist/src/app-opentui/adapters/fleet.js +874 -0
  17. package/dist/src/app-opentui/adapters/inbox.d.ts +33 -0
  18. package/dist/src/app-opentui/adapters/inbox.js +1454 -0
  19. package/dist/src/app-opentui/adapters/init.d.ts +13 -0
  20. package/dist/src/app-opentui/adapters/init.js +2357 -0
  21. package/dist/src/app-opentui/adapters/pi-attach.d.ts +16 -0
  22. package/dist/src/app-opentui/adapters/pi-attach.js +1295 -0
  23. package/dist/src/app-opentui/adapters/run-detail.d.ts +20 -0
  24. package/dist/src/app-opentui/adapters/run-detail.js +893 -0
  25. package/dist/src/app-opentui/adapters/server.d.ts +14 -0
  26. package/dist/src/app-opentui/adapters/server.js +798 -0
  27. package/dist/src/app-opentui/adapters/tasks.d.ts +55 -0
  28. package/dist/src/app-opentui/adapters/tasks.js +3472 -0
  29. package/dist/src/app-opentui/bootstrap.d.ts +16 -0
  30. package/dist/src/app-opentui/bootstrap.js +19509 -0
  31. package/dist/src/app-opentui/drone.d.ts +12 -0
  32. package/dist/src/app-opentui/drone.js +227 -0
  33. package/dist/src/app-opentui/events.d.ts +7 -0
  34. package/dist/src/app-opentui/events.js +28 -0
  35. package/dist/src/app-opentui/index.d.ts +8 -0
  36. package/dist/src/app-opentui/index.js +3477 -0
  37. package/dist/src/app-opentui/intent.d.ts +3 -0
  38. package/dist/src/app-opentui/intent.js +211 -0
  39. package/dist/src/app-opentui/layout.d.ts +15 -0
  40. package/dist/src/app-opentui/layout.js +44 -0
  41. package/dist/src/app-opentui/list-search.d.ts +8 -0
  42. package/dist/src/app-opentui/list-search.js +43 -0
  43. package/dist/src/app-opentui/pi-host-child.d.ts +2 -0
  44. package/dist/src/app-opentui/pi-host-child.js +778 -0
  45. package/dist/src/app-opentui/pi-pty-host.d.ts +64 -0
  46. package/dist/src/app-opentui/pi-pty-host.js +384 -0
  47. package/dist/src/app-opentui/registry.d.ts +4 -0
  48. package/dist/src/app-opentui/registry.js +6835 -0
  49. package/dist/src/app-opentui/render/graphics.d.ts +39 -0
  50. package/dist/src/app-opentui/render/graphics.js +537 -0
  51. package/dist/src/app-opentui/render/image-visual-layer-native-canvas.d.ts +2 -0
  52. package/dist/src/app-opentui/render/image-visual-layer-native-canvas.js +1480 -0
  53. package/dist/src/app-opentui/render/image-visual-layer-worker.d.ts +1 -0
  54. package/dist/src/app-opentui/render/image-visual-layer-worker.js +1541 -0
  55. package/dist/src/app-opentui/render/image-visual-layer.d.ts +93 -0
  56. package/dist/src/app-opentui/render/image-visual-layer.js +945 -0
  57. package/dist/src/app-opentui/render/panels.d.ts +10 -0
  58. package/dist/src/app-opentui/render/panels.js +201 -0
  59. package/dist/src/app-opentui/render/scene.d.ts +16 -0
  60. package/dist/src/app-opentui/render/scene.js +110 -0
  61. package/dist/src/app-opentui/render/text.d.ts +10 -0
  62. package/dist/src/app-opentui/render/text.js +121 -0
  63. package/dist/src/app-opentui/render/type-bar.d.ts +14 -0
  64. package/dist/src/app-opentui/render/type-bar.js +137 -0
  65. package/dist/src/app-opentui/runtime.d.ts +2 -0
  66. package/dist/src/app-opentui/runtime.js +3406 -0
  67. package/dist/src/app-opentui/scenes/doctor.d.ts +2 -0
  68. package/dist/src/app-opentui/scenes/doctor.js +91 -0
  69. package/dist/src/app-opentui/scenes/error.d.ts +2 -0
  70. package/dist/src/app-opentui/scenes/error.js +190 -0
  71. package/dist/src/app-opentui/scenes/fleet.d.ts +3 -0
  72. package/dist/src/app-opentui/scenes/fleet.js +207 -0
  73. package/dist/src/app-opentui/scenes/handoff.d.ts +2 -0
  74. package/dist/src/app-opentui/scenes/handoff.js +147 -0
  75. package/dist/src/app-opentui/scenes/help.d.ts +3 -0
  76. package/dist/src/app-opentui/scenes/help.js +138 -0
  77. package/dist/src/app-opentui/scenes/inbox.d.ts +2 -0
  78. package/dist/src/app-opentui/scenes/inbox.js +118 -0
  79. package/dist/src/app-opentui/scenes/init.d.ts +2 -0
  80. package/dist/src/app-opentui/scenes/init.js +94 -0
  81. package/dist/src/app-opentui/scenes/main.d.ts +2 -0
  82. package/dist/src/app-opentui/scenes/main.js +96 -0
  83. package/dist/src/app-opentui/scenes/run-detail.d.ts +2 -0
  84. package/dist/src/app-opentui/scenes/run-detail.js +139 -0
  85. package/dist/src/app-opentui/scenes/server.d.ts +2 -0
  86. package/dist/src/app-opentui/scenes/server.js +88 -0
  87. package/dist/src/app-opentui/scenes/tasks.d.ts +3 -0
  88. package/dist/src/app-opentui/scenes/tasks.js +230 -0
  89. package/dist/src/app-opentui/state.d.ts +4 -0
  90. package/dist/src/app-opentui/state.js +286 -0
  91. package/dist/src/app-opentui/theme.d.ts +36 -0
  92. package/dist/src/app-opentui/theme.js +88 -0
  93. package/dist/src/app-opentui/types.d.ts +188 -0
  94. package/dist/src/app-opentui/types.js +1 -0
  95. package/dist/src/commands/_async-ui.d.ts +13 -0
  96. package/dist/src/commands/_async-ui.js +223 -0
  97. package/dist/src/commands/_authority-runs.d.ts +22 -0
  98. package/dist/src/commands/_authority-runs.js +2 -3
  99. package/dist/src/commands/_cli-format.d.ts +49 -0
  100. package/dist/src/commands/_cli-format.js +447 -0
  101. package/dist/src/commands/_connection-state.d.ts +44 -0
  102. package/dist/src/commands/_connection-state.js +30 -11
  103. package/dist/src/commands/_doctor-checks.d.ts +52 -0
  104. package/dist/src/commands/_doctor-checks.js +180 -44
  105. package/dist/src/commands/_help-catalog.d.ts +51 -0
  106. package/dist/src/commands/_help-catalog.js +442 -0
  107. package/dist/src/commands/_json-output.d.ts +11 -0
  108. package/dist/src/commands/_json-output.js +56 -0
  109. package/dist/src/commands/_operator-surface.d.ts +34 -0
  110. package/dist/src/commands/_operator-surface.js +220 -0
  111. package/dist/src/commands/_operator-view.d.ts +30 -0
  112. package/dist/src/commands/_operator-view.js +803 -73
  113. package/dist/src/commands/_parsers.d.ts +15 -0
  114. package/dist/src/commands/_parsers.js +18 -11
  115. package/dist/src/commands/_paths.d.ts +11 -0
  116. package/dist/src/commands/_pi-frontend.d.ts +27 -0
  117. package/dist/src/commands/_pi-frontend.js +742 -0
  118. package/dist/src/commands/_pi-install.d.ts +42 -0
  119. package/dist/src/commands/_pi-install.js +5 -4
  120. package/dist/src/commands/_policy.d.ts +8 -0
  121. package/dist/src/commands/_policy.js +12 -5
  122. package/dist/src/commands/_preflight.d.ts +22 -0
  123. package/dist/src/commands/_preflight.js +190 -128
  124. package/dist/src/commands/_probes.d.ts +1 -0
  125. package/dist/src/commands/_run-driver-helpers.d.ts +99 -0
  126. package/dist/src/commands/_run-driver-helpers.js +75 -22
  127. package/dist/src/commands/_run-replay.d.ts +24 -0
  128. package/dist/src/commands/_run-replay.js +142 -0
  129. package/dist/src/commands/_server-client.d.ts +186 -0
  130. package/dist/src/commands/_server-client.js +360 -61
  131. package/dist/src/commands/_snapshot-upload.d.ts +39 -0
  132. package/dist/src/commands/_snapshot-upload.js +163 -39
  133. package/dist/src/commands/_spinner.d.ts +25 -0
  134. package/dist/src/commands/_spinner.js +65 -0
  135. package/dist/src/commands/_task-picker.d.ts +9 -0
  136. package/dist/src/commands/_task-picker.js +172 -19
  137. package/dist/src/commands/agent.d.ts +3 -0
  138. package/dist/src/commands/agent.js +39 -20
  139. package/dist/src/commands/browser.d.ts +65 -0
  140. package/dist/src/commands/browser.js +334 -51
  141. package/dist/src/commands/connect.d.ts +7 -0
  142. package/dist/src/commands/connect.js +272 -33
  143. package/dist/src/commands/dist.d.ts +28 -0
  144. package/dist/src/commands/dist.js +19 -12
  145. package/dist/src/commands/doctor.d.ts +3 -0
  146. package/dist/src/commands/doctor.js +378 -45
  147. package/dist/src/commands/github.d.ts +3 -0
  148. package/dist/src/commands/github.js +375 -53
  149. package/dist/src/commands/inbox.d.ts +30 -0
  150. package/dist/src/commands/inbox.js +760 -70
  151. package/dist/src/commands/init.d.ts +74 -0
  152. package/dist/src/commands/init.js +963 -119
  153. package/dist/src/commands/inspect.d.ts +3 -0
  154. package/dist/src/commands/inspect.js +588 -32
  155. package/dist/src/commands/inspector.d.ts +3 -0
  156. package/dist/src/commands/inspector.js +20 -13
  157. package/dist/src/commands/pi.d.ts +3 -0
  158. package/dist/src/commands/pi.js +177 -0
  159. package/dist/src/commands/plugin.d.ts +16 -0
  160. package/dist/src/commands/plugin.js +95 -27
  161. package/dist/src/commands/profile-and-review.d.ts +4 -0
  162. package/dist/src/commands/profile-and-review.js +26 -19
  163. package/dist/src/commands/queue.d.ts +3 -0
  164. package/dist/src/commands/queue.js +32 -12
  165. package/dist/src/commands/remote.d.ts +3 -0
  166. package/dist/src/commands/remote.js +43 -36
  167. package/dist/src/commands/repo-git-harness.d.ts +5 -0
  168. package/dist/src/commands/repo-git-harness.js +22 -15
  169. package/dist/src/commands/run.d.ts +3 -0
  170. package/dist/src/commands/run.js +1379 -159
  171. package/dist/src/commands/server.d.ts +7 -0
  172. package/dist/src/commands/server.js +502 -57
  173. package/dist/src/commands/setup.d.ts +16 -0
  174. package/dist/src/commands/setup.js +390 -63
  175. package/dist/src/commands/stats.d.ts +12 -0
  176. package/dist/src/commands/stats.js +1051 -0
  177. package/dist/src/commands/task-report-bug.d.ts +19 -0
  178. package/dist/src/commands/task-report-bug.js +260 -62
  179. package/dist/src/commands/task-run-driver.d.ts +132 -0
  180. package/dist/src/commands/task-run-driver.js +886 -130
  181. package/dist/src/commands/task.d.ts +14 -0
  182. package/dist/src/commands/task.js +1644 -314
  183. package/dist/src/commands/test.d.ts +3 -0
  184. package/dist/src/commands/test.js +15 -8
  185. package/dist/src/commands/workspace.d.ts +3 -0
  186. package/dist/src/commands/workspace.js +18 -11
  187. package/dist/src/commands.d.ts +29 -0
  188. package/dist/src/commands.js +10996 -6637
  189. package/dist/src/index.d.ts +4 -0
  190. package/dist/src/index.js +10197 -5787
  191. package/dist/src/launcher.d.ts +61 -0
  192. package/dist/src/launcher.js +77 -13
  193. package/dist/src/report-bug.d.ts +44 -0
  194. package/dist/src/report-bug.js +3 -3
  195. package/dist/src/runner.d.ts +47 -0
  196. package/dist/src/runner.js +16 -22
  197. package/dist/src/withMutedConsole.d.ts +2 -0
  198. package/package.json +16 -6
@@ -0,0 +1,2357 @@
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
+ var __require = import.meta.require;
18
+
19
+ // packages/cli/src/runner.ts
20
+ import { EventBus } from "@rig/runtime/control-plane/runtime/events";
21
+ import { CliError as RuntimeCliError } from "@rig/runtime/control-plane/errors";
22
+ import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
23
+ import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
24
+ function takeFlag(args, flag) {
25
+ const rest = [];
26
+ let value = false;
27
+ for (const arg of args) {
28
+ if (arg === flag) {
29
+ value = true;
30
+ continue;
31
+ }
32
+ rest.push(arg);
33
+ }
34
+ return { value, rest };
35
+ }
36
+ function takeOption(args, option) {
37
+ const rest = [];
38
+ let value;
39
+ for (let index = 0;index < args.length; index += 1) {
40
+ const current = args[index];
41
+ if (current === option) {
42
+ const next = args[index + 1];
43
+ if (!next || next.startsWith("-")) {
44
+ throw new CliError(`Missing value for ${option}`, 1, { hint: `Provide a value after ${option}, e.g. \`${option} <value>\`.` });
45
+ }
46
+ value = next;
47
+ index += 1;
48
+ continue;
49
+ }
50
+ if (current !== undefined) {
51
+ rest.push(current);
52
+ }
53
+ }
54
+ return { value, rest };
55
+ }
56
+ var CliError;
57
+ var init_runner = __esm(() => {
58
+ CliError = class CliError extends RuntimeCliError {
59
+ hint;
60
+ constructor(message, exitCode = 1, options = {}) {
61
+ super(message, exitCode);
62
+ if (options.hint?.trim()) {
63
+ this.hint = options.hint.trim();
64
+ }
65
+ }
66
+ };
67
+ });
68
+
69
+ // packages/cli/src/commands/_connection-state.ts
70
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
71
+ import { homedir } from "os";
72
+ import { dirname, resolve } from "path";
73
+ function resolveGlobalConnectionsPath(env = process.env) {
74
+ const explicit = env.RIG_CONNECTIONS_FILE?.trim();
75
+ if (explicit)
76
+ return resolve(explicit);
77
+ const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
78
+ if (stateDir)
79
+ return resolve(stateDir, "connections.json");
80
+ return resolve(homedir(), ".rig", "connections.json");
81
+ }
82
+ function resolveRepoConnectionPath(projectRoot) {
83
+ return resolve(projectRoot, ".rig", "state", "connection.json");
84
+ }
85
+ function readJsonFile(path) {
86
+ if (!existsSync(path))
87
+ return null;
88
+ try {
89
+ return JSON.parse(readFileSync(path, "utf8"));
90
+ } catch (error) {
91
+ 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>`." });
92
+ }
93
+ }
94
+ function writeJsonFile(path, value) {
95
+ mkdirSync(dirname(path), { recursive: true });
96
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}
97
+ `, "utf8");
98
+ }
99
+ function normalizeConnection(value) {
100
+ if (!value || typeof value !== "object" || Array.isArray(value))
101
+ return null;
102
+ const record = value;
103
+ if (record.kind === "local")
104
+ return { kind: "local", mode: "auto" };
105
+ if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
106
+ const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
107
+ return { kind: "remote", baseUrl };
108
+ }
109
+ return null;
110
+ }
111
+ function readGlobalConnections(options = {}) {
112
+ const path = resolveGlobalConnectionsPath(options.env ?? process.env);
113
+ const payload = readJsonFile(path);
114
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
115
+ return { connections: {} };
116
+ }
117
+ const rawConnections = payload.connections;
118
+ const connections = {};
119
+ if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
120
+ for (const [alias, raw] of Object.entries(rawConnections)) {
121
+ const connection = normalizeConnection(raw);
122
+ if (connection)
123
+ connections[alias] = connection;
124
+ }
125
+ }
126
+ return { connections };
127
+ }
128
+ function writeGlobalConnections(state, options = {}) {
129
+ writeJsonFile(resolveGlobalConnectionsPath(options.env ?? process.env), state);
130
+ }
131
+ function upsertGlobalConnection(alias, connection, options = {}) {
132
+ const cleanAlias = alias.trim();
133
+ if (!cleanAlias)
134
+ throw new CliError("Connection alias is required.", 1, { hint: "Save a server with `rig server add <alias> <url>`." });
135
+ const state = readGlobalConnections(options);
136
+ state.connections[cleanAlias] = connection;
137
+ writeGlobalConnections(state, options);
138
+ return state;
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
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
183
+ import { resolve as resolve2 } from "path";
184
+ import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
185
+ function reportServerPhase(label) {
186
+ serverPhaseListener?.(label);
187
+ }
188
+ function cleanToken(value) {
189
+ const trimmed = value?.trim();
190
+ return trimmed ? trimmed : null;
191
+ }
192
+ function setGitHubBearerTokenForCurrentProcess(token, projectRoot) {
193
+ const scopedKey = resolve2(projectRoot ?? process.cwd());
194
+ scopedGitHubBearerTokens.set(scopedKey, cleanToken(token ?? undefined));
195
+ }
196
+ function readPrivateRemoteSessionToken(projectRoot) {
197
+ const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
198
+ if (!existsSync2(path))
199
+ return null;
200
+ try {
201
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
202
+ return cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined);
203
+ } catch {
204
+ return null;
205
+ }
206
+ }
207
+ function readGitHubBearerTokenForRemote(projectRoot) {
208
+ const scopedKey = resolve2(projectRoot);
209
+ if (scopedGitHubBearerTokens.has(scopedKey))
210
+ return scopedGitHubBearerTokens.get(scopedKey) ?? null;
211
+ const privateSession = readPrivateRemoteSessionToken(projectRoot);
212
+ if (privateSession)
213
+ return privateSession;
214
+ return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
215
+ }
216
+ function readStoredGitHubAuthToken(projectRoot) {
217
+ const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
218
+ if (!existsSync2(path))
219
+ return null;
220
+ try {
221
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
222
+ return cleanToken(typeof parsed.token === "string" ? parsed.token : undefined);
223
+ } catch {
224
+ return null;
225
+ }
226
+ }
227
+ function readLocalConnectionFallbackToken(projectRoot) {
228
+ return readGitHubBearerTokenForRemote(projectRoot) ?? cleanToken(process.env.RIG_GITHUB_TOKEN) ?? readStoredGitHubAuthToken(projectRoot);
229
+ }
230
+ async function ensureServerForCli(projectRoot) {
231
+ try {
232
+ const selected = resolveSelectedConnection(projectRoot);
233
+ if (selected?.connection.kind === "remote") {
234
+ reportServerPhase(`Connecting to ${selected.alias}\u2026`);
235
+ const authToken = readGitHubBearerTokenForRemote(projectRoot);
236
+ const serverProjectRoot = selected.serverProjectRoot ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
237
+ return {
238
+ baseUrl: selected.connection.baseUrl,
239
+ authToken,
240
+ connectionKind: "remote",
241
+ serverProjectRoot
242
+ };
243
+ }
244
+ reportServerPhase("Starting local Rig server\u2026");
245
+ const connection = await ensureLocalRigServerConnection(projectRoot);
246
+ return {
247
+ baseUrl: connection.baseUrl,
248
+ authToken: connection.authToken ?? readLocalConnectionFallbackToken(projectRoot),
249
+ connectionKind: "local",
250
+ serverProjectRoot: resolve2(projectRoot)
251
+ };
252
+ } catch (error) {
253
+ if (error instanceof Error) {
254
+ throw new CliError(error.message, 1);
255
+ }
256
+ throw error;
257
+ }
258
+ }
259
+ async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
260
+ const repo = readRepoConnection(projectRoot);
261
+ const slug = repo?.project?.trim();
262
+ if (!slug)
263
+ return null;
264
+ try {
265
+ const response = await fetch(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`, {
266
+ headers: mergeHeaders(undefined, authToken)
267
+ });
268
+ if (!response.ok)
269
+ return null;
270
+ const payload = await response.json();
271
+ const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
272
+ const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
273
+ const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
274
+ const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
275
+ if (path)
276
+ writeRepoServerProjectRoot(projectRoot, path);
277
+ return path;
278
+ } catch {
279
+ return null;
280
+ }
281
+ }
282
+ function mergeHeaders(headers, authToken) {
283
+ const merged = new Headers(headers);
284
+ if (authToken) {
285
+ merged.set("authorization", `Bearer ${authToken}`);
286
+ }
287
+ return merged;
288
+ }
289
+ function diagnosticMessage(payload) {
290
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
291
+ return null;
292
+ const record = payload;
293
+ const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
294
+ const messages = diagnostics.flatMap((entry) => {
295
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
296
+ return [];
297
+ const diagnostic = entry;
298
+ const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
299
+ const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
300
+ return message ? [`${kind}: ${message}`] : [];
301
+ });
302
+ return messages.length > 0 ? messages.join("; ") : null;
303
+ }
304
+ async function probeServerReachability(baseUrl, authToken) {
305
+ try {
306
+ const response = await fetch(`${baseUrl.replace(/\/+$/, "")}/api/server/status`, {
307
+ headers: mergeHeaders(undefined, authToken),
308
+ signal: AbortSignal.timeout(1500)
309
+ });
310
+ return response.ok;
311
+ } catch {
312
+ return false;
313
+ }
314
+ }
315
+ function cachedServerReachability(projectRoot, baseUrl, authToken) {
316
+ const key = resolve2(projectRoot);
317
+ const cached = serverReachabilityCache.get(key);
318
+ if (cached)
319
+ return cached;
320
+ const probe = probeServerReachability(baseUrl, authToken);
321
+ serverReachabilityCache.set(key, probe);
322
+ return probe;
323
+ }
324
+ function describeSelectedServer(projectRoot, server) {
325
+ try {
326
+ const selected = resolveSelectedConnection(projectRoot);
327
+ if (selected) {
328
+ return {
329
+ alias: selected.alias,
330
+ target: selected.connection.kind === "remote" ? selected.connection.baseUrl : server.baseUrl
331
+ };
332
+ }
333
+ } catch {}
334
+ return { alias: server.connectionKind === "remote" ? "remote" : "local", target: server.baseUrl };
335
+ }
336
+ async function buildServerFailureContext(projectRoot, server) {
337
+ const { alias, target } = describeSelectedServer(projectRoot, server);
338
+ const reachable = await cachedServerReachability(projectRoot, server.baseUrl, server.authToken);
339
+ const reachability = reachable ? "server is reachable" : "server is unreachable";
340
+ return {
341
+ contextLine: `Currently connected to: ${alias} at ${target} (${reachability}).`,
342
+ hint: "Check the selected server with `rig server status`, or switch with `rig server use <alias|local>`."
343
+ };
344
+ }
345
+ async function requestServerJson(context, pathname, init = {}) {
346
+ const server = await ensureServerForCli(context.projectRoot);
347
+ const headers = mergeHeaders(init.headers, server.authToken);
348
+ if (server.serverProjectRoot)
349
+ headers.set("x-rig-project-root", server.serverProjectRoot);
350
+ reportServerPhase(`${(init.method ?? "GET").toUpperCase()} ${pathname.split("?")[0]}\u2026`);
351
+ let response;
352
+ try {
353
+ response = await fetch(`${server.baseUrl}${pathname}`, {
354
+ ...init,
355
+ headers
356
+ });
357
+ } catch (error) {
358
+ const failure = await buildServerFailureContext(context.projectRoot, server);
359
+ throw new CliError(`Rig server request failed: ${error instanceof Error ? error.message : String(error)}
360
+ ${failure.contextLine}`, 1, { hint: failure.hint });
361
+ }
362
+ const text = await response.text();
363
+ const payload = text.trim().length > 0 ? (() => {
364
+ try {
365
+ return JSON.parse(text);
366
+ } catch {
367
+ return null;
368
+ }
369
+ })() : null;
370
+ if (!response.ok) {
371
+ const diagnostics = diagnosticMessage(payload);
372
+ const rawDetail = diagnostics ?? (text || response.statusText);
373
+ const detail = diagnostics ? rawDetail : rawDetail.split(`
374
+ `).map((line) => line.trim()).find((line) => line.length > 0)?.slice(0, 200) ?? response.statusText;
375
+ const failure = await buildServerFailureContext(context.projectRoot, server);
376
+ throw new CliError(`Rig server request failed (${response.status}): ${detail}
377
+ ${failure.contextLine}`, 1, { hint: failure.hint });
378
+ }
379
+ return payload;
380
+ }
381
+ async function postGitHubTokenViaServer(context, token, options = {}) {
382
+ const payload = await requestServerJson(context, "/api/github/auth/token", {
383
+ method: "POST",
384
+ headers: { "content-type": "application/json" },
385
+ body: JSON.stringify({ token, selectedRepo: options.selectedRepo, projectRoot: options.projectRoot })
386
+ });
387
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
388
+ }
389
+ async function prepareRemoteCheckoutViaServer(context, input) {
390
+ const payload = await requestServerJson(context, `/api/projects/${encodeURIComponent(input.repoSlug)}/prepare-checkout`, {
391
+ method: "POST",
392
+ headers: { "content-type": "application/json" },
393
+ body: JSON.stringify({ checkout: input.checkout, repoUrl: input.repoUrl, baseDir: input.baseDir })
394
+ });
395
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
396
+ }
397
+ async function registerProjectViaServer(context, input) {
398
+ const payload = await requestServerJson(context, "/api/projects", {
399
+ method: "POST",
400
+ headers: { "content-type": "application/json" },
401
+ body: JSON.stringify(input)
402
+ });
403
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
404
+ }
405
+ function sleep(ms) {
406
+ return new Promise((resolve3) => setTimeout(resolve3, ms));
407
+ }
408
+ function isRetryableProjectRootSwitchError(error) {
409
+ if (!(error instanceof Error))
410
+ return false;
411
+ const message = error.message.toLowerCase();
412
+ 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");
413
+ }
414
+ async function switchServerProjectRootViaServer(context, projectRoot, options = {}) {
415
+ const timeoutMs = options.timeoutMs ?? 30000;
416
+ const pollMs = options.pollMs ?? 1000;
417
+ const deadline = Date.now() + timeoutMs;
418
+ let lastError;
419
+ let switched = null;
420
+ while (Date.now() < deadline) {
421
+ try {
422
+ switched = await requestServerJson(context, "/api/server/project-root", {
423
+ method: "POST",
424
+ headers: { "content-type": "application/json" },
425
+ body: JSON.stringify({ projectRoot })
426
+ });
427
+ break;
428
+ } catch (error) {
429
+ lastError = error;
430
+ if (!isRetryableProjectRootSwitchError(error))
431
+ throw error;
432
+ await sleep(pollMs);
433
+ }
434
+ }
435
+ if (!switched) {
436
+ 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);
437
+ }
438
+ const record = switched && typeof switched === "object" && !Array.isArray(switched) ? switched : {};
439
+ if (record.ok === true) {
440
+ writeRepoServerProjectRoot(context.projectRoot, projectRoot);
441
+ return { ok: true, switched: record };
442
+ }
443
+ throw new CliError(`Rig server rejected project-root scope ${projectRoot}: ${String(record.message ?? record.error ?? "unknown error")}`, 1);
444
+ }
445
+ async function ensureTaskLabelsViaServer(context) {
446
+ const payload = await requestServerJson(context, "/api/workspace/task-labels", { method: "POST" });
447
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
448
+ }
449
+ async function listGitHubProjectsViaServer(context, owner) {
450
+ const url = new URL("http://rig.local/api/github/projects");
451
+ url.searchParams.set("owner", owner);
452
+ const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
453
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { projects: [] };
454
+ }
455
+ async function getGitHubProjectStatusFieldViaServer(context, projectId) {
456
+ const payload = await requestServerJson(context, `/api/github/projects/${encodeURIComponent(projectId)}/status-field`);
457
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
458
+ }
459
+ var scopedGitHubBearerTokens, serverPhaseListener = null, serverReachabilityCache, RESUMABLE_RUN_STATUSES;
460
+ var init__server_client = __esm(() => {
461
+ init_runner();
462
+ init__connection_state();
463
+ scopedGitHubBearerTokens = new Map;
464
+ serverReachabilityCache = new Map;
465
+ RESUMABLE_RUN_STATUSES = new Set([
466
+ "created",
467
+ "preparing",
468
+ "running",
469
+ "validating",
470
+ "reviewing",
471
+ "stopped",
472
+ "failed",
473
+ "needs-attention",
474
+ "needs_attention"
475
+ ]);
476
+ });
477
+
478
+ // packages/cli/src/commands/_pi-install.ts
479
+ import { existsSync as existsSync3, readFileSync as readFileSync3, rmSync } from "fs";
480
+ import { homedir as homedir2 } from "os";
481
+ import { resolve as resolve3 } from "path";
482
+ async function defaultCommandRunner(command, options = {}) {
483
+ const proc = Bun.spawn(command, { cwd: options.cwd, stdout: "pipe", stderr: "pipe" });
484
+ const [stdout, stderr, exitCode] = await Promise.all([
485
+ new Response(proc.stdout).text(),
486
+ new Response(proc.stderr).text(),
487
+ proc.exited
488
+ ]);
489
+ return { exitCode, stdout, stderr };
490
+ }
491
+ function resolvePiRigExtensionPath(homeDir) {
492
+ return resolve3(homeDir, ".pi", "agent", "extensions", "pi-rig");
493
+ }
494
+ function resolvePiRigPackageSource(projectRoot, exists = existsSync3) {
495
+ const localPackage = resolve3(projectRoot, "packages", "pi-rig");
496
+ if (exists(resolve3(localPackage, "package.json")))
497
+ return localPackage;
498
+ return `npm:${PI_RIG_PACKAGE_NAME}`;
499
+ }
500
+ function resolvePiHomeDir(inputHomeDir) {
501
+ return inputHomeDir ?? process.env.RIG_PI_HOME_DIR?.trim() ?? homedir2();
502
+ }
503
+ function piListContainsPiRig(output) {
504
+ return output.split(/\r?\n/).some((line) => {
505
+ const normalized = line.trim();
506
+ return normalized.includes(PI_RIG_PACKAGE_NAME) || normalized.includes(LEGACY_PI_RIG_PACKAGE_NAME) || /(?:^|[\\/])packages[\\/]pi-rig(?:$|\s)/.test(normalized);
507
+ });
508
+ }
509
+ async function safeRun(runner, command, options) {
510
+ try {
511
+ return await runner(command, options);
512
+ } catch (error) {
513
+ return { exitCode: 1, stdout: "", stderr: error instanceof Error ? error.message : String(error) };
514
+ }
515
+ }
516
+ function splitInstallCommand(value) {
517
+ return value.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g)?.map((part) => part.replace(/^['"]|['"]$/g, "")) ?? [];
518
+ }
519
+ async function ensurePiBinaryAvailable(input) {
520
+ const current = await safeRun(input.runner, ["pi", "--version"]);
521
+ if (current.exitCode === 0) {
522
+ const updateCommand = process.env.RIG_PI_UPDATE_COMMAND?.trim();
523
+ if (updateCommand) {
524
+ const parts2 = splitInstallCommand(updateCommand);
525
+ if (parts2.length > 0)
526
+ await safeRun(input.runner, parts2, input.projectRoot ? { cwd: input.projectRoot } : undefined);
527
+ }
528
+ return { ok: true, detail: (current.stdout || current.stderr).trim() || undefined };
529
+ }
530
+ const installCommand = process.env.RIG_PI_INSTALL_COMMAND?.trim() || "bunx @earendil-works/pi-coding-agent@latest install";
531
+ const parts = splitInstallCommand(installCommand);
532
+ if (parts.length === 0) {
533
+ return { ok: false, error: (current.stderr || current.stdout).trim() || "pi --version failed" };
534
+ }
535
+ const install = await safeRun(input.runner, parts, input.projectRoot ? { cwd: input.projectRoot } : undefined);
536
+ if (install.exitCode !== 0) {
537
+ return { ok: false, installedOrUpdated: true, error: (install.stderr || install.stdout).trim() || `Pi install command failed (${install.exitCode})` };
538
+ }
539
+ const next = await safeRun(input.runner, ["pi", "--version"]);
540
+ return {
541
+ ok: next.exitCode === 0,
542
+ installedOrUpdated: true,
543
+ detail: (next.stdout || next.stderr).trim() || undefined,
544
+ ...next.exitCode === 0 ? {} : { error: (next.stderr || next.stdout).trim() || "pi --version failed after install" }
545
+ };
546
+ }
547
+ function removeManagedLegacyPiRigBridge(homeDir, exists = existsSync3) {
548
+ const extensionPath = resolvePiRigExtensionPath(homeDir);
549
+ const indexPath = resolve3(extensionPath, "index.ts");
550
+ if (!exists(indexPath))
551
+ return;
552
+ try {
553
+ const content = readFileSync3(indexPath, "utf8");
554
+ if (content === LEGACY_PI_RIG_MARKER || content.includes("Managed by Rig. Source package: @rig/pi-rig")) {
555
+ rmSync(extensionPath, { recursive: true, force: true });
556
+ }
557
+ } catch {}
558
+ }
559
+ async function checkPiRigInstall(input = {}) {
560
+ const home = resolvePiHomeDir(input.homeDir);
561
+ const extensionPath = resolvePiRigExtensionPath(home);
562
+ if (process.env.RIG_TEST_FAKE_PI_INSTALL === "1") {
563
+ return {
564
+ extensionPath,
565
+ pi: { ok: true, label: "pi", detail: "fake-pi" },
566
+ piRig: { ok: true, label: "pi-rig global extension", detail: extensionPath }
567
+ };
568
+ }
569
+ const exists = input.exists ?? existsSync3;
570
+ const runner = input.commandRunner ?? defaultCommandRunner;
571
+ const piResult = await safeRun(runner, ["pi", "--version"]);
572
+ const piListResult = piResult.exitCode === 0 ? await safeRun(runner, ["pi", "list"]) : { exitCode: 1, stdout: "", stderr: "" };
573
+ const listedPiRig = piListResult.exitCode === 0 && piListContainsPiRig(`${piListResult.stdout}
574
+ ${piListResult.stderr}`);
575
+ const legacyBridge = exists(resolve3(extensionPath, "index.ts"));
576
+ const hasPiRig = listedPiRig;
577
+ return {
578
+ extensionPath,
579
+ pi: {
580
+ ok: piResult.exitCode === 0,
581
+ label: "pi",
582
+ detail: (piResult.stdout || piResult.stderr).trim() || undefined,
583
+ hint: piResult.exitCode === 0 ? undefined : "Install Pi or run `rig init --yes` to install/update the Pi runtime."
584
+ },
585
+ piRig: {
586
+ ok: hasPiRig,
587
+ label: "pi-rig global extension",
588
+ detail: hasPiRig ? piListResult.stdout.trim() || PI_RIG_PACKAGE_NAME : legacyBridge ? `${extensionPath} (legacy bridge; reinstall required)` : undefined,
589
+ hint: hasPiRig ? undefined : "Run `rig init --yes` to install/enable the global pi-rig package with `pi install`."
590
+ }
591
+ };
592
+ }
593
+ async function ensurePiRigInstalled(input) {
594
+ const home = resolvePiHomeDir(input.homeDir);
595
+ if (process.env.RIG_TEST_FAKE_PI_INSTALL === "1") {
596
+ const status2 = await checkPiRigInstall({ homeDir: home, commandRunner: input.commandRunner });
597
+ return { ...status2, installedPath: status2.extensionPath };
598
+ }
599
+ const runner = input.commandRunner ?? defaultCommandRunner;
600
+ const piAvailable = await ensurePiBinaryAvailable({ runner, projectRoot: input.projectRoot });
601
+ const status = piAvailable.ok ? await checkPiRigInstall({ homeDir: home, commandRunner: runner }) : {
602
+ extensionPath: resolvePiRigExtensionPath(home),
603
+ pi: { ok: false, label: "pi", detail: piAvailable.error, hint: "Install/update Pi with RIG_PI_INSTALL_COMMAND or install Pi manually." },
604
+ piRig: { ok: false, label: "pi-rig global extension", hint: "Pi is required before pi-rig can be installed." }
605
+ };
606
+ if (!piAvailable.ok) {
607
+ throw new Error(`Pi install/update failed: ${piAvailable.error ?? "pi unavailable"}`);
608
+ }
609
+ const packageSource = resolvePiRigPackageSource(input.projectRoot);
610
+ removeManagedLegacyPiRigBridge(home);
611
+ const install = await runner(["pi", "install", packageSource], { cwd: input.projectRoot });
612
+ if (install.exitCode !== 0) {
613
+ throw new Error(`pi-rig install failed: ${(install.stderr || install.stdout).trim() || `exit ${install.exitCode}`}`);
614
+ }
615
+ const next = await checkPiRigInstall({ homeDir: home, commandRunner: runner });
616
+ return { ...next, installedPath: packageSource };
617
+ }
618
+ async function ensureRemotePiRigInstalled(input) {
619
+ const payload = await input.requestJson("/api/pi-rig/install", {
620
+ method: "POST",
621
+ headers: { "content-type": "application/json" },
622
+ body: JSON.stringify({ package: PI_RIG_PACKAGE_NAME, scope: "global" })
623
+ });
624
+ const record = payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
625
+ const piOk = record.piOk === true || record.ok === true;
626
+ const piRigOk = record.piRigOk === true || record.installed === true || record.ok === true;
627
+ const extensionPath = typeof record.extensionPath === "string" ? record.extensionPath : "remote:~/.pi/agent/extensions/pi-rig";
628
+ return {
629
+ remote: true,
630
+ extensionPath,
631
+ pi: {
632
+ ok: piOk,
633
+ label: "pi",
634
+ detail: typeof record.piVersion === "string" ? record.piVersion : undefined,
635
+ hint: piOk ? undefined : "Install/update Pi on the selected remote Rig server."
636
+ },
637
+ piRig: {
638
+ ok: piRigOk,
639
+ label: "pi-rig global extension",
640
+ detail: extensionPath,
641
+ hint: piRigOk ? undefined : "Install/enable pi-rig on the selected remote Rig server."
642
+ }
643
+ };
644
+ }
645
+ async function buildPiSetupChecks(input = {}) {
646
+ const status = await checkPiRigInstall(input);
647
+ return [status.pi, status.piRig];
648
+ }
649
+ var PI_RIG_PACKAGE_NAME = "@h-rig/pi-rig", LEGACY_PI_RIG_PACKAGE_NAME = "@rig/pi-rig", LEGACY_PI_RIG_MARKER = `// Managed by Rig. Source package: @rig/pi-rig.
650
+ export { default } from '@rig/pi-rig';
651
+ `;
652
+ var init__pi_install = () => {};
653
+
654
+ // packages/cli/src/commands/_snapshot-upload.ts
655
+ import { mkdir, readdir, readFile, writeFile } from "fs/promises";
656
+ import { dirname as dirname2, resolve as resolve4, relative, sep } from "path";
657
+ function toPosixPath(path) {
658
+ return path.split(sep).join("/");
659
+ }
660
+ function assertManifestPath(root, relativePath) {
661
+ if (!relativePath || relativePath.startsWith("/") || relativePath.includes("\x00")) {
662
+ throw new Error(`Invalid snapshot path: ${relativePath}`);
663
+ }
664
+ const resolved = resolve4(root, relativePath);
665
+ const relativeToRoot = relative(root, resolved);
666
+ if (relativeToRoot.startsWith("..") || relativeToRoot === ".." || resolve4(relativeToRoot) === resolved) {
667
+ throw new Error(`Snapshot path escapes project root: ${relativePath}`);
668
+ }
669
+ return resolved;
670
+ }
671
+ async function buildSnapshotUploadManifest(projectRoot, options = {}) {
672
+ const root = resolve4(projectRoot);
673
+ const excludedDirectories = [...new Set([
674
+ ...DEFAULT_EXCLUDED_DIRECTORIES,
675
+ ...options.excludedDirectories ?? []
676
+ ])];
677
+ const excludedSet = new Set(excludedDirectories);
678
+ const files = [];
679
+ async function visit(dir) {
680
+ const entries = await readdir(dir, { withFileTypes: true });
681
+ for (const entry of entries) {
682
+ if (entry.isDirectory() && excludedSet.has(entry.name))
683
+ continue;
684
+ const fullPath = resolve4(dir, entry.name);
685
+ if (entry.isDirectory()) {
686
+ await visit(fullPath);
687
+ continue;
688
+ }
689
+ if (!entry.isFile())
690
+ continue;
691
+ files.push(toPosixPath(relative(root, fullPath)));
692
+ }
693
+ }
694
+ await visit(root);
695
+ files.sort();
696
+ return { root, files, excludedDirectories };
697
+ }
698
+ async function createSnapshotUploadArchive(projectRoot, options = {}) {
699
+ const manifest = await buildSnapshotUploadManifest(projectRoot, options);
700
+ const files = await Promise.all(manifest.files.map(async (path) => {
701
+ const fullPath = assertManifestPath(manifest.root, path);
702
+ return {
703
+ path,
704
+ contentBase64: (await readFile(fullPath)).toString("base64")
705
+ };
706
+ }));
707
+ return {
708
+ version: SNAPSHOT_ARCHIVE_VERSION,
709
+ root: manifest.root,
710
+ files,
711
+ excludedDirectories: manifest.excludedDirectories,
712
+ createdAt: (options.now?.() ?? new Date).toISOString()
713
+ };
714
+ }
715
+ function encodeSnapshotUploadArchive(archive) {
716
+ return Buffer.from(JSON.stringify(archive), "utf8").toString("base64");
717
+ }
718
+ async function uploadSnapshotArchiveViaServer(context, input) {
719
+ const payload = await requestServerJson(context, `/api/projects/${encodeURIComponent(input.repoSlug)}/upload-snapshot`, {
720
+ method: "POST",
721
+ headers: { "content-type": "application/json" },
722
+ body: JSON.stringify({
723
+ archiveContentBase64: encodeSnapshotUploadArchive(input.archive),
724
+ contentType: SNAPSHOT_ARCHIVE_CONTENT_TYPE,
725
+ baseDir: input.baseDir
726
+ })
727
+ });
728
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
729
+ }
730
+ var SNAPSHOT_ARCHIVE_VERSION = 1, SNAPSHOT_ARCHIVE_CONTENT_TYPE = "application/vnd.rig.snapshot+json", DEFAULT_EXCLUDED_DIRECTORIES;
731
+ var init__snapshot_upload = __esm(() => {
732
+ init__server_client();
733
+ DEFAULT_EXCLUDED_DIRECTORIES = new Set([
734
+ ".git",
735
+ ".rig",
736
+ "node_modules",
737
+ ".turbo",
738
+ ".next",
739
+ ".cache",
740
+ "coverage",
741
+ "dist",
742
+ "build",
743
+ "out"
744
+ ]);
745
+ });
746
+
747
+ // packages/cli/src/commands/_parsers.ts
748
+ async function loadRigConfigOrNull(projectRoot) {
749
+ try {
750
+ const { loadConfig } = await import("@rig/core/load-config");
751
+ return await loadConfig(projectRoot);
752
+ } catch {
753
+ return null;
754
+ }
755
+ }
756
+ var init__parsers = __esm(() => {
757
+ init_runner();
758
+ });
759
+
760
+ // packages/cli/src/commands/_doctor-checks.ts
761
+ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
762
+ import { resolve as resolve5 } from "path";
763
+ import { isSupportedBunVersion, MIN_SUPPORTED_BUN_VERSION } from "@rig/runtime/control-plane/setup-version";
764
+ function check(id, label, status, detail, remediation) {
765
+ return {
766
+ id,
767
+ label,
768
+ status,
769
+ ...detail ? { detail } : {},
770
+ ...remediation ? { remediation } : {}
771
+ };
772
+ }
773
+ function errorMessage(error) {
774
+ return error instanceof Error ? error.message : String(error);
775
+ }
776
+ function isAuthenticated(payload) {
777
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
778
+ return false;
779
+ const record = payload;
780
+ return record.signedIn === true || record.authenticated === true || record.status === "authenticated" || record.ok === true && typeof record.login === "string" && record.login.trim().length > 0;
781
+ }
782
+ function repoSlugFromConfig(config) {
783
+ const project = config?.project;
784
+ if (project && typeof project === "object" && !Array.isArray(project)) {
785
+ const record = project;
786
+ if (typeof record.repo === "string" && /^([^/\s]+)\/([^/\s]+)$/.test(record.repo))
787
+ return record.repo;
788
+ if (typeof record.name === "string" && /^([^/\s]+)\/([^/\s]+)$/.test(record.name))
789
+ return record.name;
790
+ }
791
+ const taskSource = config?.taskSource;
792
+ if (taskSource && typeof taskSource === "object" && !Array.isArray(taskSource)) {
793
+ const source = taskSource;
794
+ if (typeof source.owner === "string" && typeof source.repo === "string")
795
+ return `${source.owner}/${source.repo}`;
796
+ }
797
+ return null;
798
+ }
799
+ function loadFallbackConfig(projectRoot) {
800
+ const candidates = ["rig.config.ts", "rig.config.mts", "rig.config.json"];
801
+ for (const name of candidates) {
802
+ const path = resolve5(projectRoot, name);
803
+ if (!existsSync4(path))
804
+ continue;
805
+ try {
806
+ const source = readFileSync4(path, "utf8");
807
+ if (name.endsWith(".json"))
808
+ return JSON.parse(source);
809
+ const owner = source.match(/owner\s*:\s*["']([^"']+)["']/)?.[1];
810
+ const repo = source.match(/repo\s*:\s*["']([^"']+)["']/)?.[1];
811
+ const projectRepo = source.match(/project\s*:\s*\{[^}]*repo\s*:\s*["']([^"']+)["']/s)?.[1] ?? (owner && repo ? `${owner}/${repo}` : undefined);
812
+ const taskKind = source.match(/taskSource\s*:\s*\{[^}]*kind\s*:\s*["']([^"']+)["']/s)?.[1];
813
+ if (projectRepo || taskKind) {
814
+ return {
815
+ ...projectRepo ? { project: { name: projectRepo, repo: projectRepo } } : {},
816
+ ...taskKind ? { taskSource: { kind: taskKind, ...owner ? { owner } : {}, ...repo ? { repo } : {} } } : {}
817
+ };
818
+ }
819
+ } catch {
820
+ return null;
821
+ }
822
+ }
823
+ return null;
824
+ }
825
+ function projectStatusSlug(projectRoot, config) {
826
+ return readRepoConnection(projectRoot)?.project ?? repoSlugFromConfig(config);
827
+ }
828
+ function githubProjectsCheck(config) {
829
+ const github = config?.github;
830
+ const projects = github?.projects;
831
+ if (!projects?.enabled) {
832
+ return check("github-projects", "GitHub Projects status sync", "warn", "disabled or not configured", "Run `rig init --github-project <project>` or configure github.projects when Project status sync should be authoritative.");
833
+ }
834
+ if (projects.projectId && projects.statusFieldId) {
835
+ return check("github-projects", "GitHub Projects status sync", "pass", `project ${projects.projectId}`);
836
+ }
837
+ return check("github-projects", "GitHub Projects status sync", "fail", "enabled but projectId/statusFieldId is incomplete", "Configure github.projects.projectId and github.projects.statusFieldId, or disable github.projects.enabled.");
838
+ }
839
+ function permissionAllowsPr(payload) {
840
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
841
+ return null;
842
+ const record = payload;
843
+ if (record.canOpenPullRequest === true || record.pullRequests === true || record.push === true || record.maintain === true || record.admin === true)
844
+ return true;
845
+ if (record.canOpenPullRequest === false || record.pullRequests === false || record.push === false)
846
+ return false;
847
+ const permissions = record.permissions;
848
+ if (permissions && typeof permissions === "object" && !Array.isArray(permissions)) {
849
+ const p = permissions;
850
+ if (p.push === true || p.maintain === true || p.admin === true)
851
+ return true;
852
+ if (p.push === false && p.maintain !== true && p.admin !== true)
853
+ return false;
854
+ }
855
+ return null;
856
+ }
857
+ function labelsReady(payload) {
858
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
859
+ return null;
860
+ const record = payload;
861
+ if (record.ok === true || record.ready === true || record.labelsReady === true)
862
+ return true;
863
+ if (record.ok === false || record.ready === false || record.labelsReady === false)
864
+ return false;
865
+ return null;
866
+ }
867
+ function prMergeCheck(config) {
868
+ const pr = config?.pr;
869
+ const merge = config?.merge;
870
+ if (pr?.mode === "off" || merge?.mode === "off") {
871
+ return check("pr-merge", "PR/merge automation", "warn", "automatic PR or merge is disabled", "Set pr.mode and merge.mode to auto for autonomous YOLO runs.");
872
+ }
873
+ return check("pr-merge", "PR/merge automation", "pass", `pr=${pr?.mode ?? "auto"}, merge=${merge?.mode ?? "auto"}, method=${merge?.method ?? "repo-default"}`);
874
+ }
875
+ async function runRigDoctorChecks(options) {
876
+ const projectRoot = options.projectRoot;
877
+ const checks = [];
878
+ const which = options.which ?? ((binary) => Bun.which(binary));
879
+ const bunVersion = options.bunVersion ?? Bun.version;
880
+ const request = options.requestJson ?? ((pathname, init) => requestServerJson({ projectRoot }, pathname, init));
881
+ const loadConfig = options.loadConfig ?? loadRigConfigOrNull;
882
+ const progress = options.onProgress ?? (() => {});
883
+ progress("Checking local toolchain\u2026");
884
+ checks.push(check("bun", `bun >= ${MIN_SUPPORTED_BUN_VERSION}`, isSupportedBunVersion(bunVersion) ? "pass" : "fail", `found ${bunVersion}`, `Install Bun ${MIN_SUPPORTED_BUN_VERSION} or newer.`), check("git", "git", which("git") ? "pass" : "fail", which("git") ?? undefined, "Install git and ensure it is on PATH."), check("jq", "jq", which("jq") ? "pass" : "warn", which("jq") ?? undefined, "Install jq (for example `brew install jq`)."));
885
+ progress("Loading rig.config\u2026");
886
+ const loadedConfig = await loadConfig(projectRoot).catch(() => null);
887
+ const config = loadedConfig ?? loadFallbackConfig(projectRoot);
888
+ const hasConfigFile = ["rig.config.ts", "rig.config.mts", "rig.config.json"].some((name) => existsSync4(resolve5(projectRoot, name)));
889
+ checks.push(config ? check("config", "rig.config loadable", "pass") : check("config", "rig.config loadable", hasConfigFile ? "fail" : "fail", hasConfigFile ? "config file exists but failed to load" : "missing rig.config.ts/json", "Run `rig init` or fix the config error."));
890
+ const taskSourceKind = config?.taskSource?.kind;
891
+ checks.push(taskSourceKind ? check("task-source", "task source configured", "pass", taskSourceKind) : check("task-source", "task source configured", "fail", "missing taskSource", "Configure taskSource in rig.config.ts."));
892
+ const repo = readRepoConnection(projectRoot);
893
+ checks.push(repo ? check("project-link", "repo selected Rig server", repo.project ? "pass" : "warn", `${repo.selected}${repo.project ? ` -> ${repo.project}` : ""}`, "Run `rig init --yes --repo owner/repo` to link this checkout to a GitHub repo slug.") : check("project-link", "repo selected Rig server", "fail", "missing .rig/state/connection.json", "Run `rig init` or `rig server use <alias|local>`."));
894
+ const selected = (() => {
895
+ try {
896
+ return resolveSelectedConnection(projectRoot);
897
+ } catch {
898
+ return null;
899
+ }
900
+ })();
901
+ checks.push(selected ? check("connection", "selected server connection", "pass", selected.connection.kind === "remote" ? selected.connection.baseUrl : "local auto") : check("connection", "selected server", repo ? "fail" : "warn", repo ? "selected alias is missing" : "will auto-start local server", repo ? "Run `rig server list` and `rig server use <alias|local>`." : undefined));
902
+ let server = null;
903
+ try {
904
+ progress("Connecting to the selected Rig server\u2026");
905
+ server = await (options.resolveServer ?? ensureServerForCli)(projectRoot);
906
+ checks.push(check("server", "Rig server reachable", "pass", `${server.connectionKind} ${server.baseUrl}`));
907
+ } catch (error) {
908
+ checks.push(check("server", "Rig server reachable", "fail", errorMessage(error), "Start the local Rig server or fix the selected remote connection."));
909
+ }
910
+ if (server || options.requestJson) {
911
+ try {
912
+ progress("Checking server status\u2026");
913
+ const status = await request("/api/server/status");
914
+ checks.push(check("server-status", "server project status", "pass", JSON.stringify(status).slice(0, 180)));
915
+ } catch (error) {
916
+ checks.push(check("server-status", "server project status", "fail", errorMessage(error), "Run `rig doctor` after the selected server is reachable."));
917
+ }
918
+ try {
919
+ progress("Checking GitHub auth\u2026");
920
+ const auth = await request("/api/github/auth/status");
921
+ checks.push(isAuthenticated(auth) ? check("github-auth", "GitHub auth", "pass") : check("github-auth", "GitHub auth", "fail", "not authenticated", "Run `rig github auth import-gh` or `rig github auth token --token <token>`."));
922
+ } catch (error) {
923
+ checks.push(check("github-auth", "GitHub auth", "fail", errorMessage(error), "Authenticate GitHub through Rig and ensure the server exposes auth status."));
924
+ }
925
+ try {
926
+ progress("Checking GitHub repo permissions\u2026");
927
+ const permissions = await request("/api/github/repo/permissions");
928
+ const allowed = permissionAllowsPr(permissions);
929
+ checks.push(allowed === true ? check("github-repo-permissions", "GitHub repo PR permissions", "pass", JSON.stringify(permissions).slice(0, 180)) : allowed === false ? check("github-repo-permissions", "GitHub repo PR permissions", "fail", JSON.stringify(permissions).slice(0, 180), "Grant the selected GitHub token permission to push branches, open PRs, and merge according to repo rules.") : check("github-repo-permissions", "GitHub repo PR permissions", "warn", JSON.stringify(permissions).slice(0, 180), "Confirm the selected token can push branches and open PRs."));
930
+ } catch (error) {
931
+ checks.push(check("github-repo-permissions", "GitHub repo PR permissions", "warn", errorMessage(error), "Ensure the server exposes repo permission checks and the token can open PRs."));
932
+ }
933
+ try {
934
+ progress("Checking GitHub issue labels\u2026");
935
+ const labels = await request("/api/workspace/task-labels");
936
+ const ready = labelsReady(labels);
937
+ checks.push(ready === false ? check("task-labels", "GitHub issue labels", "fail", JSON.stringify(labels).slice(0, 180), "Let Rig create required labels or create the configured lifecycle labels manually.") : check("task-labels", "GitHub issue labels", ready === true ? "pass" : "warn", JSON.stringify(labels).slice(0, 180), "Confirm required Rig lifecycle labels exist."));
938
+ } catch (error) {
939
+ checks.push(check("task-labels", "GitHub issue labels", "warn", errorMessage(error), "Run `rig init`/`rig doctor` after label setup is wired on the server."));
940
+ }
941
+ try {
942
+ progress("Checking task projection\u2026");
943
+ const projection = await request("/api/workspace/task-projection");
944
+ checks.push(check("task-projection", "task projection", "pass", JSON.stringify(projection).slice(0, 180)));
945
+ } catch (error) {
946
+ checks.push(check("task-projection", "task projection", "warn", errorMessage(error), "Refresh task projection with `rig task list` or fix the task source."));
947
+ }
948
+ const slug = projectStatusSlug(projectRoot, config);
949
+ if (slug) {
950
+ try {
951
+ progress("Checking server project checkout\u2026");
952
+ const project = await request(`/api/projects/${encodeURIComponent(slug)}`);
953
+ checks.push(check("remote-checkout", "server project checkout", "pass", JSON.stringify(project).slice(0, 180)));
954
+ } catch (error) {
955
+ checks.push(check("remote-checkout", "server project checkout", "warn", errorMessage(error), "Run `rig init --yes --repo owner/repo` to register/link the server project checkout."));
956
+ }
957
+ } else {
958
+ checks.push(check("remote-checkout", "server project checkout", "warn", "repo slug unknown", "Set project.repo or run `rig init --repo owner/repo`."));
959
+ }
960
+ }
961
+ if (taskSourceKind === "github-issues") {
962
+ checks.push(check("gh", "gh CLI fallback", which("gh") ? "pass" : "warn", which("gh") ?? undefined, "Install gh for local/dev GitHub fallback operations."));
963
+ }
964
+ checks.push(githubProjectsCheck(config));
965
+ checks.push(prMergeCheck(config));
966
+ progress("Checking Pi installation\u2026");
967
+ const piChecks = await (options.piChecks ?? (() => buildPiSetupChecks()))().catch((error) => [{
968
+ ok: false,
969
+ label: "pi/pi-rig checks",
970
+ hint: errorMessage(error)
971
+ }]);
972
+ for (const pi of piChecks) {
973
+ checks.push(check(pi.label === "pi" ? "pi" : "pi-rig", pi.label, pi.ok ? "pass" : "warn", pi.detail, pi.hint ?? (pi.ok ? undefined : "Run `rig init --yes` to install/update Pi and enable pi-rig.")));
974
+ }
975
+ return checks;
976
+ }
977
+ function countDoctorFailures(checks) {
978
+ return checks.filter((entry) => entry.status === "fail").length;
979
+ }
980
+ var init__doctor_checks = __esm(() => {
981
+ init_runner();
982
+ init__connection_state();
983
+ init__server_client();
984
+ init__parsers();
985
+ init__pi_install();
986
+ });
987
+
988
+ // packages/cli/src/app/theme.ts
989
+ function hexToRgb(hex) {
990
+ const value = hex.replace("#", "");
991
+ return [
992
+ Number.parseInt(value.slice(0, 2), 16),
993
+ Number.parseInt(value.slice(2, 4), 16),
994
+ Number.parseInt(value.slice(4, 6), 16)
995
+ ];
996
+ }
997
+ function fg(hex) {
998
+ const [r, g, b] = hexToRgb(hex);
999
+ return (text) => `\x1B[38;2;${r};${g};${b}m${text}\x1B[39m`;
1000
+ }
1001
+ function bold(text) {
1002
+ return `\x1B[1m${text}\x1B[22m`;
1003
+ }
1004
+ function microDroneFrame(tick) {
1005
+ const blade = MICRO_BLADES[tick % MICRO_BLADES.length];
1006
+ const eye = EYE_FRAMES[Math.floor(tick / 2) % EYE_FRAMES.length];
1007
+ return `(${blade})${eye}(${blade})`;
1008
+ }
1009
+ function renderMicroDroneFrame(tick) {
1010
+ const blade = MICRO_BLADES[tick % MICRO_BLADES.length];
1011
+ const eye = EYE_FRAMES[Math.floor(tick / 2) % EYE_FRAMES.length];
1012
+ return `${ink4("(")}${cyan(blade)}${ink4(")")}${bold(accent(eye))}${ink4("(")}${cyan(blade)}${ink4(")")}`;
1013
+ }
1014
+ 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;
1015
+ var init_theme = __esm(() => {
1016
+ RIG_PALETTE = {
1017
+ ink: "#f2f3f6",
1018
+ ink2: "#aeb0ba",
1019
+ ink3: "#6c6e79",
1020
+ ink4: "#44464f",
1021
+ accent: "#ccff4d",
1022
+ accentDim: "#a9d63f",
1023
+ cyan: "#56d8ff",
1024
+ red: "#ff5d5d",
1025
+ yellow: "#ffd24d"
1026
+ };
1027
+ ink = fg(RIG_PALETTE.ink);
1028
+ ink2 = fg(RIG_PALETTE.ink2);
1029
+ ink3 = fg(RIG_PALETTE.ink3);
1030
+ ink4 = fg(RIG_PALETTE.ink4);
1031
+ accent = fg(RIG_PALETTE.accent);
1032
+ accentDim = fg(RIG_PALETTE.accentDim);
1033
+ cyan = fg(RIG_PALETTE.cyan);
1034
+ red = fg(RIG_PALETTE.red);
1035
+ yellow = fg(RIG_PALETTE.yellow);
1036
+ DRONE_ART = [
1037
+ " .-=-. .-=-. ",
1038
+ " ( !!! ) ( !!! ) ",
1039
+ " '-=-'._ _.'-=-' ",
1040
+ " '._ _.' ",
1041
+ " '=$$$$$$$=.' ",
1042
+ " =$$$$$$$$$$$= ",
1043
+ " $$$@@@@@@@@@@$$$ ",
1044
+ " $$$@@ @@$$$ ",
1045
+ " $$@ ? @$$$ ",
1046
+ " $$$@ '-' @$$$ ",
1047
+ " $$$@@ @@$$$ ",
1048
+ " $$$@@@@@@@@@@$$$ ",
1049
+ " =$$$$$$$$$$$= ",
1050
+ " '=$$$$$$$=.' ",
1051
+ " _.' '._ ",
1052
+ " .-=-.' '.-=-. ",
1053
+ " ( !!! ) ( !!! ) ",
1054
+ " '-=-' '-=-' "
1055
+ ];
1056
+ EYE_FRAMES = ["@", "o", "."];
1057
+ DRONE_WIDTH = DRONE_ART[0].length;
1058
+ DRONE_HEIGHT = DRONE_ART.length;
1059
+ MICRO_BLADES = ["---", "\\\\\\", "|||", "///"];
1060
+ MICRO_DRONE_FRAMES = Array.from({ length: 12 }, (_, index) => microDroneFrame(index));
1061
+ });
1062
+
1063
+ // packages/cli/src/commands/_spinner.ts
1064
+ function createTtySpinner(input) {
1065
+ const output = input.output ?? process.stdout;
1066
+ const isTty = output.isTTY === true;
1067
+ const frames = input.frames && input.frames.length > 0 ? input.frames : SPINNER_FRAMES;
1068
+ let label = input.label;
1069
+ let frame = 0;
1070
+ let paused = false;
1071
+ let stopped = false;
1072
+ let lastPrintedLabel = "";
1073
+ const render = () => {
1074
+ if (stopped || paused)
1075
+ return;
1076
+ if (!isTty) {
1077
+ if (label !== lastPrintedLabel) {
1078
+ output.write(`${label}
1079
+ `);
1080
+ lastPrintedLabel = label;
1081
+ }
1082
+ return;
1083
+ }
1084
+ frame = (frame + 1) % frames.length;
1085
+ const glyph = frames[frame] ?? frames[0] ?? "";
1086
+ output.write(`\r\x1B[2K${input.styleFrame ? input.styleFrame(glyph) : glyph} ${label}`);
1087
+ };
1088
+ const clearLine = () => {
1089
+ if (isTty)
1090
+ output.write("\r\x1B[2K");
1091
+ };
1092
+ render();
1093
+ const timer = isTty ? setInterval(render, input.intervalMs ?? 16) : null;
1094
+ return {
1095
+ setLabel(next) {
1096
+ label = next;
1097
+ render();
1098
+ },
1099
+ pause() {
1100
+ paused = true;
1101
+ clearLine();
1102
+ },
1103
+ resume() {
1104
+ if (stopped)
1105
+ return;
1106
+ paused = false;
1107
+ render();
1108
+ },
1109
+ stop(finalLine) {
1110
+ if (stopped)
1111
+ return;
1112
+ stopped = true;
1113
+ if (timer)
1114
+ clearInterval(timer);
1115
+ clearLine();
1116
+ if (finalLine)
1117
+ output.write(`${finalLine}
1118
+ `);
1119
+ }
1120
+ };
1121
+ }
1122
+ var SPINNER_FRAMES;
1123
+ var init__spinner = __esm(() => {
1124
+ SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
1125
+ });
1126
+
1127
+ // packages/cli/src/app/drone-ui.ts
1128
+ var exports_drone_ui = {};
1129
+ __export(exports_drone_ui, {
1130
+ droneWarn: () => droneWarn,
1131
+ droneText: () => droneText,
1132
+ droneStep: () => droneStep,
1133
+ droneSpinner: () => droneSpinner,
1134
+ droneSelect: () => droneSelect,
1135
+ droneOutro: () => droneOutro,
1136
+ droneNote: () => droneNote,
1137
+ droneIntro: () => droneIntro,
1138
+ droneInfo: () => droneInfo,
1139
+ droneError: () => droneError,
1140
+ droneConfirm: () => droneConfirm,
1141
+ droneCancel: () => droneCancel
1142
+ });
1143
+ import { ProcessTerminal, TUI, Text, Input, SelectList, matchesKey } from "@earendil-works/pi-tui";
1144
+ function hairline(width = Math.min(process.stdout.columns ?? 80, 100)) {
1145
+ return ink4("\u2500".repeat(Math.max(10, width)));
1146
+ }
1147
+ function droneIntro(title, subtitle) {
1148
+ console.log("");
1149
+ console.log(` ${accent("\u258D")}${bold(ink(title))}${subtitle ? ink3(` \u2014 ${subtitle}`) : ""}`);
1150
+ console.log(hairline());
1151
+ }
1152
+ function droneOutro(text) {
1153
+ console.log(hairline());
1154
+ console.log(` ${accent("\u25C6")} ${ink2(text)}`);
1155
+ console.log("");
1156
+ }
1157
+ function droneNote(message, title) {
1158
+ if (title)
1159
+ console.log(` ${accentDim("\u25C7")} ${bold(ink2(title))}`);
1160
+ for (const line of message.split(`
1161
+ `)) {
1162
+ console.log(` ${ink4("\u2502")} ${line}`);
1163
+ }
1164
+ }
1165
+ function droneStep(text) {
1166
+ console.log(` ${accent("\u203A")} ${ink(text)}`);
1167
+ }
1168
+ function droneInfo(text) {
1169
+ console.log(` ${cyan("\xB7")} ${ink2(text)}`);
1170
+ }
1171
+ function droneWarn(text) {
1172
+ console.log(` ${yellow("\u25B2")} ${ink2(text)}`);
1173
+ }
1174
+ function droneError(text) {
1175
+ console.log(` ${red("\u2716")} ${ink2(text)}`);
1176
+ }
1177
+ function droneCancel(text) {
1178
+ console.log(` ${red("\u2716")} ${ink3(text)}`);
1179
+ }
1180
+ function droneSpinner() {
1181
+ let active = null;
1182
+ return {
1183
+ start(message) {
1184
+ active = createTtySpinner({
1185
+ label: message,
1186
+ frames: MICRO_DRONE_FRAMES,
1187
+ styleFrame: (frame) => renderMicroDroneFrame(Math.max(0, MICRO_DRONE_FRAMES.indexOf(frame)))
1188
+ });
1189
+ },
1190
+ stop(message) {
1191
+ active?.stop(message ? ` ${accent("\u25C6")} ${ink2(message)}` : undefined);
1192
+ active = null;
1193
+ },
1194
+ error(message) {
1195
+ active?.stop(message ? ` ${red("\u2716")} ${ink2(message)}` : undefined);
1196
+ active = null;
1197
+ }
1198
+ };
1199
+ }
1200
+ async function runMiniTui(build) {
1201
+ const terminal = new ProcessTerminal;
1202
+ const tui = new TUI(terminal);
1203
+ let settled = false;
1204
+ return await new Promise((resolve6) => {
1205
+ const finish = (result) => {
1206
+ if (settled)
1207
+ return;
1208
+ settled = true;
1209
+ tui.stop();
1210
+ resolve6(result);
1211
+ };
1212
+ build(tui, finish);
1213
+ tui.start();
1214
+ });
1215
+ }
1216
+ async function droneSelect(input) {
1217
+ if (!isTty() || input.options.length === 0) {
1218
+ return input.initialValue ?? input.options[0]?.value ?? null;
1219
+ }
1220
+ return runMiniTui((tui, finish) => {
1221
+ tui.addChild(new Text(` ${accent("\u258D")}${bold(ink(input.message))}`));
1222
+ const items = input.options.map((option) => ({
1223
+ value: option.value,
1224
+ label: option.label,
1225
+ ...option.hint ? { description: option.hint } : {}
1226
+ }));
1227
+ const list = new SelectList(items, Math.min(items.length, 12), SELECT_THEME);
1228
+ const initialIndex = input.initialValue ? items.findIndex((item) => item.value === input.initialValue) : -1;
1229
+ if (initialIndex > 0)
1230
+ list.setSelectedIndex(initialIndex);
1231
+ list.onSelect = (item) => finish(item.value);
1232
+ list.onCancel = () => finish(null);
1233
+ tui.addChild(list);
1234
+ tui.addChild(new Text(ink4(" \u2191\u2193 navigate \xB7 enter select \xB7 esc cancel")));
1235
+ tui.setFocus(list);
1236
+ tui.addInputListener((data) => {
1237
+ if (matchesKey(data, "ctrl+c") || matchesKey(data, "escape")) {
1238
+ finish(null);
1239
+ return { consume: true };
1240
+ }
1241
+ return;
1242
+ });
1243
+ });
1244
+ }
1245
+ async function droneText(input) {
1246
+ if (!isTty())
1247
+ return input.initialValue ?? null;
1248
+ return runMiniTui((tui, finish) => {
1249
+ tui.addChild(new Text(` ${accent("\u258D")}${bold(ink(input.message))}${input.placeholder ? ink4(` (${input.placeholder})`) : ""}`));
1250
+ const field = new Input;
1251
+ if (input.initialValue)
1252
+ field.setValue(input.initialValue);
1253
+ field.onSubmit = (value) => finish(value);
1254
+ field.onEscape = () => finish(null);
1255
+ tui.addChild(field);
1256
+ tui.addChild(new Text(ink4(" enter submit \xB7 esc cancel")));
1257
+ tui.setFocus(field);
1258
+ tui.addInputListener((data) => {
1259
+ if (matchesKey(data, "ctrl+c")) {
1260
+ finish(null);
1261
+ return { consume: true };
1262
+ }
1263
+ return;
1264
+ });
1265
+ });
1266
+ }
1267
+ async function droneConfirm(input) {
1268
+ const answer = await droneSelect({
1269
+ message: input.message,
1270
+ options: [
1271
+ { value: "yes", label: "Yes" },
1272
+ { value: "no", label: "No" }
1273
+ ],
1274
+ initialValue: input.initialValue === false ? "no" : "yes"
1275
+ });
1276
+ return answer === null ? null : answer === "yes";
1277
+ }
1278
+ var isTty = () => Boolean(process.stdout.isTTY), SELECT_THEME;
1279
+ var init_drone_ui = __esm(() => {
1280
+ init_theme();
1281
+ init__spinner();
1282
+ SELECT_THEME = {
1283
+ selectedPrefix: (text) => accent(text),
1284
+ selectedText: (text) => bold(ink(text)),
1285
+ description: (text) => ink3(text),
1286
+ scrollInfo: (text) => ink4(text),
1287
+ noMatch: (text) => ink3(text)
1288
+ };
1289
+ });
1290
+
1291
+ // packages/cli/src/commands/init.ts
1292
+ var exports_init = {};
1293
+ __export(exports_init, {
1294
+ runInteractiveControlPlaneInit: () => runInteractiveControlPlaneInit,
1295
+ runDemoInit: () => runDemoInit,
1296
+ executeInit: () => executeInit,
1297
+ buildRigInitConfigSource: () => buildRigInitConfigSource,
1298
+ DEMO_TASKS_RELATIVE_DIR: () => DEMO_TASKS_RELATIVE_DIR,
1299
+ DEMO_TASKS: () => DEMO_TASKS
1300
+ });
1301
+ import { appendFileSync, existsSync as existsSync5, mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "fs";
1302
+ import { spawnSync } from "child_process";
1303
+ import { basename, resolve as resolve6 } from "path";
1304
+ import { buildRigInitConfigSource } from "@rig/core";
1305
+ import { listGitHubProjects as listGitHubProjectsDirect, resolveProjectStatusField as resolveProjectStatusFieldDirect } from "@rig/server";
1306
+ function parseRepoSlugFromRemote(remoteUrl) {
1307
+ const trimmed = remoteUrl.trim();
1308
+ const gitHubMatch = trimmed.match(/github\.com[:/]([^/]+)\/([^/.]+)(?:\.git)?$/i);
1309
+ return gitHubMatch ? `${gitHubMatch[1]}/${gitHubMatch[2]}` : null;
1310
+ }
1311
+ function detectOriginRepoSlug(projectRoot) {
1312
+ const result = spawnSync("git", ["-C", projectRoot, "remote", "get-url", "origin"], { encoding: "utf8" });
1313
+ if (result.status !== 0)
1314
+ return null;
1315
+ return parseRepoSlugFromRemote(result.stdout.trim());
1316
+ }
1317
+ function parseRepoSlug(value) {
1318
+ const match = value.trim().match(/^([^/\s]+)\/([^/\s]+)$/);
1319
+ if (!match)
1320
+ throw new CliError(`Invalid GitHub repo slug: ${value}. Expected owner/repo.`, 1, { hint: "Pass the slug as owner/repo, e.g. `rig init --repo acme/widgets`." });
1321
+ return { owner: match[1], repo: match[2], slug: `${match[1]}/${match[2]}` };
1322
+ }
1323
+ function ensureRigPrivateDirs(projectRoot) {
1324
+ const rigDir = resolve6(projectRoot, ".rig");
1325
+ mkdirSync2(resolve6(rigDir, "state"), { recursive: true });
1326
+ mkdirSync2(resolve6(rigDir, "logs"), { recursive: true });
1327
+ mkdirSync2(resolve6(rigDir, "runs"), { recursive: true });
1328
+ mkdirSync2(resolve6(rigDir, "tmp"), { recursive: true });
1329
+ mkdirSync2(resolve6(projectRoot, "artifacts"), { recursive: true });
1330
+ const taskConfigPath = resolve6(rigDir, "task-config.json");
1331
+ if (!existsSync5(taskConfigPath))
1332
+ writeFileSync2(taskConfigPath, `{}
1333
+ `, "utf-8");
1334
+ }
1335
+ function ensureGitignoreEntries(projectRoot) {
1336
+ const path = resolve6(projectRoot, ".gitignore");
1337
+ const existing = existsSync5(path) ? readFileSync5(path, "utf8") : "";
1338
+ const entries = [".rig/state/", ".rig/logs/", ".rig/runs/", ".rig/tmp/"];
1339
+ const missing = entries.filter((entry) => !existing.split(/\r?\n/).includes(entry));
1340
+ if (missing.length === 0)
1341
+ return;
1342
+ const prefix = existing.length > 0 && !existing.endsWith(`
1343
+ `) ? `
1344
+ ` : "";
1345
+ appendFileSync(path, `${prefix}${missing.join(`
1346
+ `)}
1347
+ `, "utf8");
1348
+ }
1349
+ function ensureRigConfigPackageDependencies(projectRoot) {
1350
+ const path = resolve6(projectRoot, "package.json");
1351
+ const existing = existsSync5(path) ? JSON.parse(readFileSync5(path, "utf8")) : {};
1352
+ const devDependencies = existing.devDependencies && typeof existing.devDependencies === "object" && !Array.isArray(existing.devDependencies) ? { ...existing.devDependencies } : {};
1353
+ for (const [name, spec] of Object.entries(RIG_CONFIG_DEV_DEPENDENCIES)) {
1354
+ devDependencies[name] = spec;
1355
+ }
1356
+ const next = {
1357
+ ...existsSync5(path) ? existing : { name: "rig-project", private: true },
1358
+ devDependencies
1359
+ };
1360
+ writeFileSync2(path, `${JSON.stringify(next, null, 2)}
1361
+ `, "utf8");
1362
+ }
1363
+ function applyGitHubProjectConfig(source, options) {
1364
+ if (!options.githubProject || options.githubProject === "off")
1365
+ return source;
1366
+ const projectId = JSON.stringify(options.githubProject);
1367
+ const statusFieldId = JSON.stringify(options.githubProjectStatusField ?? "Status");
1368
+ const statuses = options.githubProjectStatuses && Object.keys(options.githubProjectStatuses).length > 0 ? `
1369
+ statuses: ${JSON.stringify(options.githubProjectStatuses, null, 8).replace(/\n/g, `
1370
+ `)},` : "";
1371
+ return source.replace(` projects: { enabled: false },`, [
1372
+ ` projects: {`,
1373
+ ` enabled: true,`,
1374
+ ` projectId: ${projectId},`,
1375
+ ` statusFieldId: ${statusFieldId},${statuses}`,
1376
+ ` },`
1377
+ ].join(`
1378
+ `));
1379
+ }
1380
+ function checkoutForInit(projectRoot, serverKind, strategy) {
1381
+ if (serverKind === "local")
1382
+ return { kind: "local", path: projectRoot };
1383
+ const selected = strategy ?? { kind: "managed-clone" };
1384
+ switch (selected.kind) {
1385
+ case "managed-clone":
1386
+ return { kind: "managed-clone", path: projectRoot };
1387
+ case "current-ref":
1388
+ return { kind: "current-ref", path: projectRoot, ...selected.ref ? { ref: selected.ref } : {} };
1389
+ case "uploaded-snapshot":
1390
+ return { kind: "uploaded-snapshot", path: projectRoot, source: "local-working-tree" };
1391
+ case "existing-path":
1392
+ return { kind: "existing-path", path: selected.path };
1393
+ }
1394
+ }
1395
+ function detectGhLogin() {
1396
+ const result = spawnSync("gh", ["api", "user", "--jq", ".login"], { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"] });
1397
+ return result.status === 0 && result.stdout.trim() ? result.stdout.trim() : null;
1398
+ }
1399
+ function readGhAuthToken() {
1400
+ const result = spawnSync("gh", ["auth", "token"], { encoding: "utf8" });
1401
+ if (result.status !== 0 || !result.stdout.trim()) {
1402
+ throw new CliError(result.stderr.trim() || "Could not read GitHub token from `gh auth token`.", result.status || 1, { hint: "Sign in with `gh auth login`, or pass a token directly: `rig init --github-auth token --github-token <token>`." });
1403
+ }
1404
+ return result.stdout.trim();
1405
+ }
1406
+ function refreshGhProjectScopesAndReadToken() {
1407
+ const result = spawnSync("gh", ["auth", "refresh", "--scopes", "read:project"], {
1408
+ encoding: "utf8",
1409
+ stdio: ["inherit", "pipe", "pipe"]
1410
+ });
1411
+ if (result.status !== 0)
1412
+ return null;
1413
+ try {
1414
+ return readGhAuthToken();
1415
+ } catch {
1416
+ return null;
1417
+ }
1418
+ }
1419
+ async function loadClackPrompts() {
1420
+ const drone = await Promise.resolve().then(() => (init_drone_ui(), exports_drone_ui));
1421
+ return {
1422
+ intro: (message) => drone.droneIntro(message),
1423
+ outro: (message) => drone.droneOutro(message),
1424
+ cancel: (message) => drone.droneCancel(message),
1425
+ isCancel: (value) => value === DRONE_CANCEL,
1426
+ text: async (options) => {
1427
+ const value = await drone.droneText({
1428
+ message: options.message,
1429
+ ...options.placeholder ? { placeholder: options.placeholder } : {},
1430
+ ...(options.initialValue ?? options.defaultValue)?.trim() ? { initialValue: (options.initialValue ?? options.defaultValue).trim() } : {}
1431
+ });
1432
+ return value === null ? DRONE_CANCEL : value;
1433
+ },
1434
+ select: async (options) => {
1435
+ const value = await drone.droneSelect({
1436
+ message: options.message,
1437
+ options: options.options,
1438
+ ...options.initialValue ? { initialValue: options.initialValue } : {}
1439
+ });
1440
+ return value === null ? DRONE_CANCEL : value;
1441
+ },
1442
+ confirm: async (options) => {
1443
+ const value = await drone.droneConfirm(options);
1444
+ return value === null ? DRONE_CANCEL : value;
1445
+ }
1446
+ };
1447
+ }
1448
+ async function promptRequiredText(prompts, options) {
1449
+ const value = await prompts.text(options);
1450
+ if (prompts.isCancel(value))
1451
+ throw new CliError("Init cancelled.", 1);
1452
+ const text = String(value ?? "").trim();
1453
+ if (!text)
1454
+ throw new CliError(`${options.message} is required.`, 1);
1455
+ return text;
1456
+ }
1457
+ async function promptOptionalText(prompts, options) {
1458
+ const value = await prompts.text(options);
1459
+ if (prompts.isCancel(value))
1460
+ throw new CliError("Init cancelled.", 1);
1461
+ return String(value ?? "").trim();
1462
+ }
1463
+ async function promptSelect(prompts, options) {
1464
+ const value = await prompts.select(options);
1465
+ if (prompts.isCancel(value))
1466
+ throw new CliError("Init cancelled.", 1);
1467
+ return String(value);
1468
+ }
1469
+ function repoOwnerFromSlug(repoSlug) {
1470
+ return repoSlug.trim().match(/^([^/]+)\/[^/]+$/)?.[1] ?? null;
1471
+ }
1472
+ function recordArray(value, key) {
1473
+ if (!value || typeof value !== "object" || Array.isArray(value))
1474
+ return [];
1475
+ const raw = value[key];
1476
+ return Array.isArray(raw) ? raw.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
1477
+ }
1478
+ async function listGitHubProjectsForInit(context, owner, token) {
1479
+ if (token?.trim()) {
1480
+ try {
1481
+ return { ok: true, projects: await listGitHubProjectsDirect({ owner, token: token.trim() }) };
1482
+ } catch (directError) {
1483
+ const serverPayload = await listGitHubProjectsViaServer(context, owner).catch(() => null);
1484
+ if (recordArray(serverPayload, "projects").length > 0)
1485
+ return serverPayload;
1486
+ return { ok: false, error: directError instanceof Error ? directError.message : String(directError), projects: [] };
1487
+ }
1488
+ }
1489
+ return listGitHubProjectsViaServer(context, owner);
1490
+ }
1491
+ async function getGitHubProjectStatusFieldForInit(context, projectId, token) {
1492
+ if (token?.trim()) {
1493
+ try {
1494
+ return { ok: true, field: await resolveProjectStatusFieldDirect({ projectId, token: token.trim() }) };
1495
+ } catch (directError) {
1496
+ const serverPayload = await getGitHubProjectStatusFieldViaServer(context, projectId).catch(() => null);
1497
+ if (serverPayload && typeof serverPayload === "object" && !Array.isArray(serverPayload) && "field" in serverPayload) {
1498
+ return serverPayload;
1499
+ }
1500
+ return { ok: false, error: directError instanceof Error ? directError.message : String(directError) };
1501
+ }
1502
+ }
1503
+ return getGitHubProjectStatusFieldViaServer(context, projectId);
1504
+ }
1505
+ async function promptManualProjectStatusMapping(prompts) {
1506
+ const statuses = {};
1507
+ for (const [key, label] of Object.entries(PROJECT_STATUS_PROMPTS)) {
1508
+ const defaultLabel = DEFAULT_PROJECT_STATUS_OPTIONS[key] ?? label;
1509
+ const value = await promptOptionalText(prompts, {
1510
+ message: `Project status option id/name for ${label} (blank for ${defaultLabel})`,
1511
+ placeholder: defaultLabel
1512
+ });
1513
+ statuses[key] = value || defaultLabel;
1514
+ }
1515
+ return statuses;
1516
+ }
1517
+ function projectScopeError(value) {
1518
+ const text = typeof value === "string" ? value : JSON.stringify(value ?? "");
1519
+ return /INSUFFICIENT_SCOPES|read:project|required scopes/i.test(text);
1520
+ }
1521
+ function optionName(option) {
1522
+ return String(option.name ?? option.label ?? option.id ?? "").trim();
1523
+ }
1524
+ function autoProjectStatusValue(options, key, label) {
1525
+ const candidates = [DEFAULT_PROJECT_STATUS_OPTIONS[key], label].filter((value) => Boolean(value)).map((value) => value.trim().toLowerCase());
1526
+ const match = options.find((option) => candidates.includes(optionName(option).toLowerCase()));
1527
+ if (!match)
1528
+ return null;
1529
+ return String(match.id ?? match.name);
1530
+ }
1531
+ async function promptGitHubProjectConfig(context, prompts, repoSlug, githubToken, refreshProjectToken) {
1532
+ const projectChoice = await promptSelect(prompts, {
1533
+ message: "GitHub Projects status sync",
1534
+ initialValue: "select",
1535
+ options: [
1536
+ { value: "select", label: "Select accessible ProjectV2" },
1537
+ { value: "off", label: "Off" },
1538
+ { value: "manual", label: "Enter ProjectV2 ids manually" }
1539
+ ]
1540
+ });
1541
+ if (projectChoice === "off")
1542
+ return { githubProject: "off" };
1543
+ if (projectChoice === "manual") {
1544
+ return {
1545
+ githubProject: await promptRequiredText(prompts, { message: "GitHub ProjectV2 id", placeholder: "PVT_..." }),
1546
+ githubProjectStatusField: await promptRequiredText(prompts, { message: "Project Status field id", placeholder: "field_status" }),
1547
+ githubProjectStatuses: await promptManualProjectStatusMapping(prompts)
1548
+ };
1549
+ }
1550
+ const owner = repoOwnerFromSlug(repoSlug);
1551
+ if (!owner)
1552
+ throw new CliError(`Cannot derive GitHub owner from repo slug ${repoSlug}.`, 1, { hint: "Pass the slug as owner/repo, e.g. `rig init --repo acme/widgets`." });
1553
+ let activeToken = githubToken?.trim() || null;
1554
+ let projectsPayload = await listGitHubProjectsForInit(context, owner, activeToken).catch((error) => ({ ok: false, error: error instanceof Error ? error.message : String(error), projects: [] }));
1555
+ let projects = recordArray(projectsPayload, "projects");
1556
+ if (projects.length === 0 && projectScopeError(projectsPayload.error) && refreshProjectToken) {
1557
+ prompts.outro?.("GitHub token is missing read:project; refreshing gh auth scopes and retrying Projects.");
1558
+ const refreshedToken = refreshProjectToken();
1559
+ if (refreshedToken) {
1560
+ activeToken = refreshedToken;
1561
+ projectsPayload = await listGitHubProjectsForInit(context, owner, activeToken).catch((error) => ({ ok: false, error: error instanceof Error ? error.message : String(error), projects: [] }));
1562
+ projects = recordArray(projectsPayload, "projects");
1563
+ }
1564
+ }
1565
+ if (projects.length === 0) {
1566
+ const error = typeof projectsPayload.error === "string" ? ` (${String(projectsPayload.error).replace(/\s+/g, " ").slice(0, 240)})` : "";
1567
+ prompts.outro?.(`No accessible GitHub Projects were returned${error}; continuing with GitHub Projects status sync off.`);
1568
+ return { githubProject: "off", ...activeToken ? { githubToken: activeToken } : {} };
1569
+ }
1570
+ const selectedProjectId = await promptSelect(prompts, {
1571
+ message: "GitHub ProjectV2 project",
1572
+ options: [
1573
+ ...projects.map((project) => ({
1574
+ value: String(project.id),
1575
+ label: `${String(project.title ?? "Untitled project")} (#${String(project.number ?? "?")})`,
1576
+ hint: typeof project.url === "string" ? project.url : undefined
1577
+ })),
1578
+ { value: "manual", label: "Enter ProjectV2 id manually" }
1579
+ ]
1580
+ });
1581
+ const projectId = selectedProjectId === "manual" ? await promptRequiredText(prompts, { message: "GitHub ProjectV2 id", placeholder: "PVT_..." }) : selectedProjectId;
1582
+ const fieldPayload = await getGitHubProjectStatusFieldForInit(context, projectId, activeToken).catch((error) => ({ ok: false, error: error instanceof Error ? error.message : String(error) }));
1583
+ const fieldPayloadRecord = fieldPayload && typeof fieldPayload === "object" && !Array.isArray(fieldPayload) ? fieldPayload : {};
1584
+ const rawField = fieldPayloadRecord.field;
1585
+ const field = rawField && typeof rawField === "object" && !Array.isArray(rawField) ? rawField : null;
1586
+ const fieldId = typeof field?.id === "string" && field.id.trim() ? field.id : await promptRequiredText(prompts, { message: "Project Status field id", placeholder: "field_status" });
1587
+ const options = Array.isArray(field?.options) ? field.options.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
1588
+ if (options.length === 0) {
1589
+ return {
1590
+ githubProject: projectId,
1591
+ githubProjectStatusField: fieldId,
1592
+ githubProjectStatuses: await promptManualProjectStatusMapping(prompts),
1593
+ ...activeToken ? { githubToken: activeToken } : {}
1594
+ };
1595
+ }
1596
+ const statuses = {};
1597
+ for (const [key, label] of Object.entries(PROJECT_STATUS_PROMPTS)) {
1598
+ const auto = autoProjectStatusValue(options, key, label);
1599
+ statuses[key] = auto ?? await promptSelect(prompts, {
1600
+ message: `Project status option for ${label}`,
1601
+ options: options.map((option) => ({ value: String(option.id ?? option.name), label: optionName(option) }))
1602
+ });
1603
+ }
1604
+ return {
1605
+ githubProject: projectId,
1606
+ githubProjectStatusField: fieldId,
1607
+ githubProjectStatuses: Object.keys(statuses).length > 0 ? statuses : undefined,
1608
+ ...activeToken ? { githubToken: activeToken } : {}
1609
+ };
1610
+ }
1611
+ function sleep2(ms) {
1612
+ return new Promise((resolve7) => setTimeout(resolve7, ms));
1613
+ }
1614
+ function positiveIntFromEnv(name, fallback) {
1615
+ const value = Number.parseInt(process.env[name] ?? "", 10);
1616
+ return Number.isFinite(value) && value >= 0 ? value : fallback;
1617
+ }
1618
+ function apiSessionTokenFrom(payload) {
1619
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
1620
+ return null;
1621
+ const token = payload.apiSessionToken;
1622
+ return typeof token === "string" && token.trim() ? token.trim() : null;
1623
+ }
1624
+ function cleanPayloadString(value) {
1625
+ return typeof value === "string" && value.trim() ? value.trim() : null;
1626
+ }
1627
+ function remoteGitHubAuthMetadata(payload) {
1628
+ if (!payload)
1629
+ return {};
1630
+ const userNamespace = payload.userNamespace && typeof payload.userNamespace === "object" && !Array.isArray(payload.userNamespace) ? payload.userNamespace : null;
1631
+ return {
1632
+ ...cleanPayloadString(payload.login) ? { login: cleanPayloadString(payload.login) } : {},
1633
+ ...cleanPayloadString(payload.userId) ? { userId: cleanPayloadString(payload.userId) } : {},
1634
+ ...cleanPayloadString(userNamespace?.key) ? { userNamespaceKey: cleanPayloadString(userNamespace?.key) } : {},
1635
+ ...cleanPayloadString(userNamespace?.root) ? { userNamespaceRoot: cleanPayloadString(userNamespace?.root) } : {},
1636
+ ...cleanPayloadString(userNamespace?.checkoutBaseDir) ? { checkoutBaseDir: cleanPayloadString(userNamespace?.checkoutBaseDir) } : {},
1637
+ ...cleanPayloadString(userNamespace?.snapshotBaseDir) ? { snapshotBaseDir: cleanPayloadString(userNamespace?.snapshotBaseDir) } : {}
1638
+ };
1639
+ }
1640
+ function writeRemoteGitHubAuthState(projectRoot, input) {
1641
+ writeFileSync2(resolve6(projectRoot, ".rig", "state", "github-auth.json"), `${JSON.stringify({
1642
+ authenticated: true,
1643
+ source: input.source,
1644
+ storedOnServer: true,
1645
+ selectedRepo: input.selectedRepo,
1646
+ ...remoteGitHubAuthMetadata(input.authPayload ?? null),
1647
+ ...input.apiSessionToken ? { apiSessionToken: input.apiSessionToken } : {},
1648
+ updatedAt: new Date().toISOString()
1649
+ }, null, 2)}
1650
+ `, "utf8");
1651
+ }
1652
+ async function pollDeviceAuthUntilComplete(context, pollId, firstPayload) {
1653
+ if (typeof pollId !== "string" || !pollId.trim())
1654
+ return null;
1655
+ const intervalSeconds = typeof firstPayload.interval === "number" && Number.isFinite(firstPayload.interval) && firstPayload.interval > 0 ? firstPayload.interval : 5;
1656
+ const timeoutMs = positiveIntFromEnv("RIG_DEVICE_AUTH_POLL_TIMEOUT_MS", 300000);
1657
+ const intervalMs = positiveIntFromEnv("RIG_DEVICE_AUTH_POLL_INTERVAL_MS", Math.max(1000, intervalSeconds * 1000));
1658
+ const deadline = Date.now() + timeoutMs;
1659
+ let last = null;
1660
+ do {
1661
+ const payload = await requestServerJson(context, "/api/github/auth/device/poll", {
1662
+ method: "POST",
1663
+ headers: { "content-type": "application/json" },
1664
+ body: JSON.stringify({ pollId })
1665
+ }).catch(() => null);
1666
+ last = payload && typeof payload === "object" && !Array.isArray(payload) ? payload : null;
1667
+ const status = typeof last?.status === "string" ? last.status : null;
1668
+ if (status === "signed-in" || status === "expired" || status === "cancelled" || status === "failed") {
1669
+ return last;
1670
+ }
1671
+ if (timeoutMs <= 0)
1672
+ return last;
1673
+ await sleep2(intervalMs);
1674
+ } while (Date.now() < deadline);
1675
+ return last;
1676
+ }
1677
+ function runLocalFilesInit(context, options) {
1678
+ const projectRoot = context.projectRoot;
1679
+ ensureRigPrivateDirs(projectRoot);
1680
+ ensureGitignoreEntries(projectRoot);
1681
+ writeRepoConnection(projectRoot, { selected: "local", linkedAt: new Date().toISOString() });
1682
+ const configTsPath = resolve6(projectRoot, "rig.config.ts");
1683
+ const configExists = existsSync5(configTsPath) || existsSync5(resolve6(projectRoot, "rig.config.json"));
1684
+ if (configExists && !options.repair) {
1685
+ if (context.outputMode !== "json")
1686
+ console.log("rig.config already exists; leaving it unchanged. Pass --repair to rewrite it.");
1687
+ } else {
1688
+ const projectName = basename(projectRoot) || "rig-project";
1689
+ writeFileSync2(configTsPath, buildRigInitConfigSource({
1690
+ projectName,
1691
+ taskSource: { kind: "files", path: "tasks" },
1692
+ useStandardPlugin: true
1693
+ }), "utf-8");
1694
+ }
1695
+ ensureRigConfigPackageDependencies(projectRoot);
1696
+ const tasksDir = resolve6(projectRoot, "tasks");
1697
+ if (!existsSync5(tasksDir)) {
1698
+ mkdirSync2(tasksDir, { recursive: true });
1699
+ writeFileSync2(resolve6(tasksDir, "T-1.json"), `${JSON.stringify({ id: "T-1", title: "My first Rig task", body: "Describe the change you want an agent to make." }, null, 2)}
1700
+ `, "utf-8");
1701
+ }
1702
+ if (context.outputMode !== "json") {
1703
+ console.log("Initialized a local files-source Rig project (no GitHub).");
1704
+ console.log(" tasks live in tasks/*.json \xB7 server: local");
1705
+ console.log("Next: `rig task list`, then `rig task run T-1`.");
1706
+ console.log("To wire GitHub later: `rig init --repair --repo owner/repo --github-auth gh`.");
1707
+ }
1708
+ return { ok: true, group: "init", command: "init", details: { mode: "local-files", projectRoot, taskSourcePath: "tasks" } };
1709
+ }
1710
+ function runDemoInit(context, options) {
1711
+ const projectRoot = context.projectRoot;
1712
+ ensureRigPrivateDirs(projectRoot);
1713
+ ensureGitignoreEntries(projectRoot);
1714
+ writeRepoConnection(projectRoot, { selected: "local", linkedAt: new Date().toISOString() });
1715
+ const configTsPath = resolve6(projectRoot, "rig.config.ts");
1716
+ const configExists = existsSync5(configTsPath) || existsSync5(resolve6(projectRoot, "rig.config.json"));
1717
+ let configWritten = false;
1718
+ if (configExists && !options.repair) {
1719
+ if (context.outputMode !== "json") {
1720
+ console.log("rig.config already exists; leaving it unchanged. Pass --repair to rewrite it for the demo.");
1721
+ }
1722
+ } else {
1723
+ writeFileSync2(configTsPath, buildRigInitConfigSource({
1724
+ projectName: basename(projectRoot) || "rig-demo",
1725
+ taskSource: { kind: "files", path: DEMO_TASKS_RELATIVE_DIR },
1726
+ useStandardPlugin: true
1727
+ }), "utf-8");
1728
+ configWritten = true;
1729
+ }
1730
+ ensureRigConfigPackageDependencies(projectRoot);
1731
+ const demoTasksDir = resolve6(projectRoot, DEMO_TASKS_RELATIVE_DIR);
1732
+ mkdirSync2(demoTasksDir, { recursive: true });
1733
+ const taskIds = [];
1734
+ for (const task of DEMO_TASKS) {
1735
+ const id = String(task.id);
1736
+ taskIds.push(id);
1737
+ const taskPath = resolve6(demoTasksDir, `${id}.json`);
1738
+ if (!existsSync5(taskPath)) {
1739
+ writeFileSync2(taskPath, `${JSON.stringify(task, null, 2)}
1740
+ `, "utf-8");
1741
+ }
1742
+ }
1743
+ if (context.outputMode !== "json") {
1744
+ console.log(`Demo Rig project ready (offline, no GitHub).`);
1745
+ console.log(` config: rig.config.ts (files task source -> ${DEMO_TASKS_RELATIVE_DIR}/)`);
1746
+ console.log(` tasks: ${taskIds.join(", ")}`);
1747
+ console.log("Next steps:");
1748
+ console.log(" 1. rig task list");
1749
+ console.log(" 2. rig task run --next");
1750
+ }
1751
+ return {
1752
+ ok: true,
1753
+ group: "init",
1754
+ command: "init",
1755
+ details: {
1756
+ mode: "demo",
1757
+ projectRoot,
1758
+ taskSourcePath: DEMO_TASKS_RELATIVE_DIR,
1759
+ demoTasksDir,
1760
+ tasks: taskIds,
1761
+ configWritten
1762
+ }
1763
+ };
1764
+ }
1765
+ async function runControlPlaneInit(context, options) {
1766
+ const projectRoot = context.projectRoot;
1767
+ const detectedSlug = options.repoSlug ?? detectOriginRepoSlug(projectRoot);
1768
+ if (!detectedSlug) {
1769
+ const authMethod2 = options.githubAuthMethod ?? (options.githubToken ? "token" : "skip");
1770
+ if ((options.server ?? "local") === "local" && authMethod2 === "skip") {
1771
+ return runLocalFilesInit(context, options);
1772
+ }
1773
+ throw new CliError("Could not detect GitHub repo slug from origin. Pass --repo owner/repo \u2014 or run `rig init --yes --server local --github-auth skip` for a local files-source project without GitHub.", 1);
1774
+ }
1775
+ const repo = parseRepoSlug(detectedSlug);
1776
+ const serverKind = options.server ?? "local";
1777
+ const connectionAlias = options.connectionAlias ?? (serverKind === "local" ? "local" : "remote");
1778
+ if (serverKind === "remote") {
1779
+ if (!options.remoteUrl)
1780
+ throw new CliError("Missing --remote-url for --server remote.", 1, { hint: "Re-run as `rig init --server remote --remote-url https://your-rig-server`." });
1781
+ upsertGlobalConnection(connectionAlias, { kind: "remote", baseUrl: options.remoteUrl });
1782
+ }
1783
+ writeRepoConnection(projectRoot, {
1784
+ selected: connectionAlias,
1785
+ project: repo.slug,
1786
+ linkedAt: new Date().toISOString()
1787
+ });
1788
+ ensureRigPrivateDirs(projectRoot);
1789
+ ensureGitignoreEntries(projectRoot);
1790
+ const configTsPath = resolve6(projectRoot, "rig.config.ts");
1791
+ const configJsonPath = resolve6(projectRoot, "rig.config.json");
1792
+ const configExists = existsSync5(configTsPath) || existsSync5(configJsonPath);
1793
+ if (!options.privateStateOnly) {
1794
+ if (configExists && !options.repair) {
1795
+ if (context.outputMode !== "json")
1796
+ console.log("rig.config already exists; leaving it unchanged. Pass --repair to rewrite it.");
1797
+ } else {
1798
+ const source = applyGitHubProjectConfig(buildRigInitConfigSource({
1799
+ projectName: repo.slug,
1800
+ projectRepo: repo.slug,
1801
+ taskSource: { kind: "github-issues", owner: repo.owner, repo: repo.repo },
1802
+ useStandardPlugin: true
1803
+ }), options);
1804
+ writeFileSync2(configTsPath, source, "utf-8");
1805
+ }
1806
+ ensureRigConfigPackageDependencies(projectRoot);
1807
+ }
1808
+ writeFileSync2(resolve6(projectRoot, ".rig", "state", "project-link.json"), `${JSON.stringify({ repoSlug: repo.slug, connection: connectionAlias, linkedAt: new Date().toISOString() }, null, 2)}
1809
+ `, "utf8");
1810
+ const checkout = checkoutForInit(projectRoot, serverKind, options.remoteCheckout);
1811
+ let uploadedSnapshot = null;
1812
+ if (serverKind === "remote" && options.remoteCheckout?.kind === "uploaded-snapshot") {
1813
+ const archive = await createSnapshotUploadArchive(projectRoot);
1814
+ uploadedSnapshot = await uploadSnapshotArchiveViaServer(context, { repoSlug: repo.slug, archive });
1815
+ const uploadedCheckout = uploadedSnapshot.checkout;
1816
+ if (uploadedCheckout && typeof uploadedCheckout === "object" && !Array.isArray(uploadedCheckout)) {
1817
+ Object.assign(checkout, uploadedCheckout);
1818
+ }
1819
+ }
1820
+ let githubAuth = null;
1821
+ let deviceAuth = null;
1822
+ const authMethod = options.githubAuthMethod ?? (options.githubToken ? "token" : "skip");
1823
+ const remoteGhTokenWarning = serverKind === "remote" && authMethod === "gh" ? `This sends a GitHub token from this machine to ${options.remoteUrl ?? "the remote Rig server"}.` : null;
1824
+ if (remoteGhTokenWarning && !options.yes) {
1825
+ throw new CliError(`${remoteGhTokenWarning} Re-run with --yes to confirm this explicit token transfer.`, 1);
1826
+ }
1827
+ const token = authMethod === "gh" && !options.githubToken ? readGhAuthToken() : options.githubToken?.trim();
1828
+ if (token) {
1829
+ githubAuth = await postGitHubTokenViaServer(context, token, { selectedRepo: repo.slug });
1830
+ const apiSessionToken = apiSessionTokenFrom(githubAuth);
1831
+ setGitHubBearerTokenForCurrentProcess(apiSessionToken ?? token, projectRoot);
1832
+ if (serverKind === "remote") {
1833
+ writeRemoteGitHubAuthState(projectRoot, {
1834
+ source: authMethod === "gh" ? "gh" : "init-token",
1835
+ selectedRepo: repo.slug,
1836
+ apiSessionToken,
1837
+ authPayload: githubAuth
1838
+ });
1839
+ }
1840
+ } else if (authMethod === "device") {
1841
+ const payload = await requestServerJson(context, "/api/github/auth/device/start", {
1842
+ method: "POST",
1843
+ headers: { "content-type": "application/json" },
1844
+ body: JSON.stringify({ repoSlug: repo.slug })
1845
+ });
1846
+ deviceAuth = payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
1847
+ if (context.outputMode !== "json") {
1848
+ const verificationUri = String(deviceAuth.verificationUri ?? deviceAuth.verification_uri ?? deviceAuth.verification_uri_complete ?? "the verification URL returned by the server");
1849
+ const userCode = String(deviceAuth.userCode ?? deviceAuth.user_code ?? "the returned user code");
1850
+ console.log(`GitHub device flow: open ${verificationUri} and enter ${userCode}. Waiting for authorization...`);
1851
+ }
1852
+ const completed = await pollDeviceAuthUntilComplete(context, deviceAuth.pollId, deviceAuth);
1853
+ if (completed) {
1854
+ const apiSessionToken = apiSessionTokenFrom(completed);
1855
+ if (apiSessionToken) {
1856
+ setGitHubBearerTokenForCurrentProcess(apiSessionToken, projectRoot);
1857
+ if (serverKind === "remote") {
1858
+ writeRemoteGitHubAuthState(projectRoot, { source: "device", selectedRepo: repo.slug, apiSessionToken, authPayload: completed });
1859
+ }
1860
+ }
1861
+ deviceAuth = { ...deviceAuth, poll: completed, completed: completed.status === "signed-in" };
1862
+ }
1863
+ }
1864
+ let remoteCheckoutPreparation = null;
1865
+ if (serverKind === "remote" && options.remoteCheckout?.kind !== "uploaded-snapshot") {
1866
+ remoteCheckoutPreparation = await prepareRemoteCheckoutViaServer(context, {
1867
+ repoSlug: repo.slug,
1868
+ checkout,
1869
+ repoUrl: `https://github.com/${repo.slug}.git`
1870
+ });
1871
+ const preparedCheckout = remoteCheckoutPreparation.checkout;
1872
+ if (preparedCheckout && typeof preparedCheckout === "object" && !Array.isArray(preparedCheckout)) {
1873
+ Object.assign(checkout, preparedCheckout);
1874
+ }
1875
+ }
1876
+ const checkoutPath = typeof checkout.path === "string" ? checkout.path : null;
1877
+ if (serverKind === "remote" && checkoutPath && token) {
1878
+ githubAuth = await postGitHubTokenViaServer(context, token, { selectedRepo: repo.slug, projectRoot: checkoutPath });
1879
+ const apiSessionToken = apiSessionTokenFrom(githubAuth);
1880
+ setGitHubBearerTokenForCurrentProcess(apiSessionToken ?? token, projectRoot);
1881
+ writeRemoteGitHubAuthState(projectRoot, { source: authMethod === "gh" ? "gh" : "init-token", selectedRepo: repo.slug, apiSessionToken, authPayload: githubAuth });
1882
+ }
1883
+ const registered = await registerProjectViaServer(context, {
1884
+ repoSlug: repo.slug,
1885
+ checkout
1886
+ });
1887
+ const serverRootSwitch = serverKind === "remote" && checkoutPath ? await switchServerProjectRootViaServer(context, checkoutPath) : null;
1888
+ const activeProjectRegistration = serverRootSwitch ? await registerProjectViaServer(context, { repoSlug: repo.slug, checkout }) : null;
1889
+ const labelSetup = await ensureTaskLabelsViaServer(context).catch((error) => ({
1890
+ ok: false,
1891
+ ready: false,
1892
+ labelsReady: false,
1893
+ error: error instanceof Error ? error.message : String(error)
1894
+ }));
1895
+ const pi = serverKind === "remote" ? await ensureRemotePiRigInstalled({ requestJson: (pathname, init) => requestServerJson(context, pathname, init) }).catch((error) => ({
1896
+ remote: true,
1897
+ pi: { ok: false, label: "pi", hint: error instanceof Error ? error.message : String(error) },
1898
+ piRig: { ok: false, label: "pi-rig global extension", hint: "Remote server did not complete pi-rig installation." },
1899
+ extensionPath: "remote:~/.pi/agent/extensions/pi-rig"
1900
+ })) : await ensurePiRigInstalled({ projectRoot, homeDir: process.env.RIG_PI_HOME_DIR }).catch((error) => ({
1901
+ pi: { ok: false, label: "pi", hint: error instanceof Error ? error.message : String(error) },
1902
+ piRig: { ok: false, label: "pi-rig global extension", hint: "Local pi-rig installation failed." },
1903
+ extensionPath: null,
1904
+ installedPath: null
1905
+ }));
1906
+ const doctor = await runRigDoctorChecks({ projectRoot }).then((checks) => ({
1907
+ ok: countDoctorFailures(checks) === 0,
1908
+ failures: countDoctorFailures(checks),
1909
+ checks
1910
+ }));
1911
+ const details = {
1912
+ repoSlug: repo.slug,
1913
+ server: serverKind,
1914
+ connection: connectionAlias,
1915
+ githubProject: options.githubProject ?? "off",
1916
+ checkout,
1917
+ remoteCheckoutPreparation,
1918
+ uploadedSnapshot,
1919
+ projectRegistration: registered,
1920
+ activeProjectRegistration,
1921
+ serverRootSwitch,
1922
+ githubAuth,
1923
+ deviceAuth,
1924
+ githubAuthWarning: remoteGhTokenWarning,
1925
+ labelSetup,
1926
+ pi,
1927
+ doctor
1928
+ };
1929
+ if (context.outputMode === "json")
1930
+ console.log(JSON.stringify(details, null, 2));
1931
+ else
1932
+ console.log(`Initialized Rig control-plane project ${repo.slug}. Next: rig doctor && rig task list`);
1933
+ return { ok: true, group: "init", command: "init", details };
1934
+ }
1935
+ function parseInitOptions(args) {
1936
+ let rest = [...args];
1937
+ const demo = takeFlag(rest, "--demo");
1938
+ rest = demo.rest;
1939
+ const yes = takeFlag(rest, "--yes");
1940
+ rest = yes.rest;
1941
+ const repair = takeFlag(rest, "--repair");
1942
+ rest = repair.rest;
1943
+ const privateStateOnly = takeFlag(rest, "--private-state-only");
1944
+ rest = privateStateOnly.rest;
1945
+ const server = takeOption(rest, "--server");
1946
+ rest = server.rest;
1947
+ const remoteUrl = takeOption(rest, "--remote-url");
1948
+ rest = remoteUrl.rest;
1949
+ const connectionAlias = takeOption(rest, "--connection");
1950
+ rest = connectionAlias.rest;
1951
+ const repoSlug = takeOption(rest, "--repo");
1952
+ rest = repoSlug.rest;
1953
+ const githubToken = takeOption(rest, "--github-token");
1954
+ rest = githubToken.rest;
1955
+ const githubProject = takeOption(rest, "--github-project");
1956
+ rest = githubProject.rest;
1957
+ const githubProjectStatusField = takeOption(rest, "--github-project-status-field");
1958
+ rest = githubProjectStatusField.rest;
1959
+ const githubAuth = takeOption(rest, "--github-auth");
1960
+ rest = githubAuth.rest;
1961
+ const remoteCheckout = takeOption(rest, "--remote-checkout");
1962
+ rest = remoteCheckout.rest;
1963
+ const existingPath = takeOption(rest, "--existing-path");
1964
+ rest = existingPath.rest;
1965
+ const ref = takeOption(rest, "--ref");
1966
+ rest = ref.rest;
1967
+ const options = {
1968
+ demo: demo.value,
1969
+ yes: yes.value,
1970
+ repair: repair.value,
1971
+ privateStateOnly: privateStateOnly.value,
1972
+ server: server.value === "remote" ? "remote" : server.value === "local" ? "local" : undefined,
1973
+ remoteUrl: remoteUrl.value,
1974
+ connectionAlias: connectionAlias.value,
1975
+ repoSlug: repoSlug.value,
1976
+ githubToken: githubToken.value,
1977
+ githubAuthMethod: githubAuth.value,
1978
+ githubProject: githubProject.value,
1979
+ githubProjectStatusField: githubProjectStatusField.value
1980
+ };
1981
+ if (server.value && options.server === undefined) {
1982
+ throw new CliError("--server must be local or remote.", 1);
1983
+ }
1984
+ if (githubAuth.value && !["gh", "token", "device", "skip"].includes(githubAuth.value)) {
1985
+ throw new CliError("--github-auth must be gh, token, device, or skip.", 1);
1986
+ }
1987
+ if (remoteCheckout.value) {
1988
+ if (remoteCheckout.value === "managed-clone")
1989
+ options.remoteCheckout = { kind: "managed-clone" };
1990
+ else if (remoteCheckout.value === "current-ref")
1991
+ options.remoteCheckout = { kind: "current-ref", ref: ref.value };
1992
+ else if (remoteCheckout.value === "uploaded-snapshot")
1993
+ options.remoteCheckout = { kind: "uploaded-snapshot" };
1994
+ else if (remoteCheckout.value === "existing-path") {
1995
+ if (!existingPath.value)
1996
+ throw new CliError("--remote-checkout existing-path requires --existing-path <path>.", 1);
1997
+ options.remoteCheckout = { kind: "existing-path", path: existingPath.value };
1998
+ } else {
1999
+ throw new CliError("--remote-checkout must be managed-clone, current-ref, uploaded-snapshot, or existing-path.", 1);
2000
+ }
2001
+ }
2002
+ return { options, rest };
2003
+ }
2004
+ async function runInteractiveControlPlaneInit(context, prompts) {
2005
+ prompts.intro?.("Initialize a Rig control-plane project");
2006
+ const projectRoot = context.projectRoot;
2007
+ const existingConfig = existsSync5(resolve6(projectRoot, "rig.config.ts")) || existsSync5(resolve6(projectRoot, "rig.config.json"));
2008
+ let repair = false;
2009
+ let privateStateOnly = false;
2010
+ if (existingConfig) {
2011
+ const action = await promptSelect(prompts, {
2012
+ message: "rig.config already exists. What should rig init do?",
2013
+ options: [
2014
+ { value: "repair", label: "Verify/repair generated config" },
2015
+ { value: "reconfigure", label: "Reconfigure project and rewrite config" },
2016
+ { value: "private-state-only", label: "Leave config unchanged; update private connection/auth state only" },
2017
+ { value: "cancel", label: "Cancel" }
2018
+ ]
2019
+ });
2020
+ if (action === "cancel") {
2021
+ prompts.cancel?.("Init cancelled.");
2022
+ return { ok: false, group: "init", command: "init", details: { cancelled: true } };
2023
+ }
2024
+ repair = action === "repair" || action === "reconfigure";
2025
+ privateStateOnly = action === "private-state-only";
2026
+ }
2027
+ const detectedRepo = detectOriginRepoSlug(projectRoot) ?? undefined;
2028
+ const repoSlug = await promptRequiredText(prompts, {
2029
+ message: "GitHub repo slug",
2030
+ placeholder: "owner/repo",
2031
+ defaultValue: detectedRepo
2032
+ });
2033
+ const serverChoice = await promptSelect(prompts, {
2034
+ message: "Rig server",
2035
+ initialValue: "remote",
2036
+ options: [
2037
+ { value: "remote", label: "Remote server", hint: "connect to an HTTPS Rig server" },
2038
+ { value: "local", label: "Local server", hint: "run on this machine" }
2039
+ ]
2040
+ });
2041
+ const remoteUrl = serverChoice === "remote" ? await promptRequiredText(prompts, { message: "Remote Rig server URL", placeholder: DEFAULT_REMOTE_RIG_URL, initialValue: DEFAULT_REMOTE_RIG_URL }) : undefined;
2042
+ let remoteCheckout;
2043
+ if (serverChoice === "remote") {
2044
+ const checkout = await promptSelect(prompts, {
2045
+ message: "Remote checkout strategy",
2046
+ options: [
2047
+ { value: "managed-clone", label: "Server-managed clone (recommended)" },
2048
+ { value: "current-ref", label: "Clone current branch/ref" },
2049
+ { value: "uploaded-snapshot", label: "Upload current working-tree snapshot" },
2050
+ { value: "existing-path", label: "Use existing server path" }
2051
+ ]
2052
+ });
2053
+ if (checkout === "existing-path") {
2054
+ remoteCheckout = { kind: "existing-path", path: await promptRequiredText(prompts, { message: "Existing server checkout path", placeholder: "/srv/rig/checkouts/repo" }) };
2055
+ } else if (checkout === "current-ref") {
2056
+ remoteCheckout = { kind: "current-ref", ref: await promptOptionalText(prompts, { message: "Branch/ref to clone (blank for current HEAD)", placeholder: "main" }) || undefined };
2057
+ } else if (checkout === "uploaded-snapshot") {
2058
+ remoteCheckout = { kind: "uploaded-snapshot" };
2059
+ } else {
2060
+ remoteCheckout = { kind: "managed-clone" };
2061
+ }
2062
+ }
2063
+ const detectedGhLogin = detectGhLogin();
2064
+ const authMethod = await promptSelect(prompts, {
2065
+ message: `GitHub auth method${detectedGhLogin ? ` (detected gh login: ${detectedGhLogin})` : ""}`,
2066
+ options: [
2067
+ { value: "gh", label: "Import token from gh auth token", hint: serverChoice === "local" ? "recommended for local" : "sends this machine's token to the remote server" },
2068
+ { value: "device", label: "Start server GitHub device flow", hint: serverChoice === "remote" ? "recommended for remote" : undefined },
2069
+ { value: "token", label: "Paste token" },
2070
+ { value: "skip", label: "Skip for now" }
2071
+ ]
2072
+ });
2073
+ let remoteGhTokenConfirmed = false;
2074
+ if (serverChoice === "remote" && authMethod === "gh") {
2075
+ if (!prompts.confirm)
2076
+ throw new CliError("Remote gh-token import requires explicit confirmation.", 1);
2077
+ const confirmed = await prompts.confirm({
2078
+ message: `This sends a GitHub token from this machine to ${remoteUrl}. Continue?`,
2079
+ initialValue: true
2080
+ });
2081
+ if (prompts.isCancel(confirmed) || confirmed !== true) {
2082
+ throw new CliError("Remote gh-token import cancelled.", 1);
2083
+ }
2084
+ remoteGhTokenConfirmed = true;
2085
+ }
2086
+ const githubToken = authMethod === "token" ? await promptRequiredText(prompts, { message: "GitHub token", placeholder: "ghp_..." }) : authMethod === "gh" ? readGhAuthToken() : undefined;
2087
+ const projectConfig = await promptGitHubProjectConfig(context, prompts, repoSlug, githubToken, authMethod === "gh" ? refreshGhProjectScopesAndReadToken : undefined);
2088
+ const effectiveGithubToken = projectConfig.githubToken ?? githubToken;
2089
+ const result = await runControlPlaneInit(context, {
2090
+ server: serverChoice,
2091
+ remoteUrl,
2092
+ repoSlug,
2093
+ githubToken: effectiveGithubToken,
2094
+ githubAuthMethod: authMethod,
2095
+ githubProject: projectConfig.githubProject,
2096
+ githubProjectStatusField: projectConfig.githubProjectStatusField,
2097
+ githubProjectStatuses: projectConfig.githubProjectStatuses,
2098
+ remoteCheckout,
2099
+ repair,
2100
+ privateStateOnly,
2101
+ yes: remoteGhTokenConfirmed || undefined
2102
+ });
2103
+ const details = result.details && typeof result.details === "object" && !Array.isArray(result.details) ? result.details : {};
2104
+ const deviceAuth = details.deviceAuth && typeof details.deviceAuth === "object" && !Array.isArray(details.deviceAuth) ? details.deviceAuth : null;
2105
+ const deviceMessage = deviceAuth ? ` GitHub device flow: open ${String(deviceAuth.verificationUri ?? deviceAuth.verification_uri ?? deviceAuth.verification_uri_complete ?? "the verification URL returned by the server")} and enter ${String(deviceAuth.userCode ?? deviceAuth.user_code ?? "the returned user code")}.` : "";
2106
+ prompts.outro?.(`Rig project initialized.${deviceMessage} Next: rig doctor && rig task list`);
2107
+ return result;
2108
+ }
2109
+ async function executeInit(context, args) {
2110
+ const parsed = parseInitOptions(args);
2111
+ if (parsed.options.demo) {
2112
+ if (parsed.rest.length > 0) {
2113
+ throw new CliError(`Unexpected arguments: ${parsed.rest.join(" ")}
2114
+ Usage: rig init --demo [--yes] [--repair]`, 1, { hint: "Run `rig init --demo` (optionally with --repair to rewrite an existing rig.config)." });
2115
+ }
2116
+ return runDemoInit(context, parsed.options);
2117
+ }
2118
+ if (parsed.options.yes || parsed.options.server || parsed.options.repoSlug || parsed.options.githubToken || parsed.options.privateStateOnly || parsed.options.repair || parsed.options.githubAuthMethod || parsed.options.remoteCheckout) {
2119
+ if (parsed.rest.length > 0)
2120
+ throw new CliError(`Unexpected arguments: ${parsed.rest.join(" ")}
2121
+ Usage: rig init [--demo] [--server local|remote] [--remote-url <url>] [--repo owner/repo] [--github-auth gh|token|device|skip] [--github-token <token>] [--github-project off|<project-id>] [--remote-checkout managed-clone|current-ref|uploaded-snapshot|existing-path] [--yes]`, 1);
2122
+ return runControlPlaneInit(context, parsed.options);
2123
+ }
2124
+ if (parsed.rest.length > 0)
2125
+ throw new CliError(`Unexpected arguments: ${parsed.rest.join(" ")}
2126
+ Usage: rig init`, 1);
2127
+ if (!process.stdin.isTTY) {
2128
+ throw new CliError("rig init is interactive and needs a terminal. For scripts, pass flags: rig init --yes --server local --github-auth skip [--repo owner/repo].", 1);
2129
+ }
2130
+ return runInteractiveControlPlaneInit(context, await loadClackPrompts());
2131
+ }
2132
+ var RIG_CONFIG_PACKAGE_DIST_TAG = "latest", DEFAULT_REMOTE_RIG_URL = "https://where.rig-does.work", RIG_CONFIG_DEV_DEPENDENCIES, DRONE_CANCEL, PROJECT_STATUS_PROMPTS, DEFAULT_PROJECT_STATUS_OPTIONS, DEMO_TASKS_RELATIVE_DIR = ".rig/demo-tasks", DEMO_TASKS;
2133
+ var init_init = __esm(() => {
2134
+ init_runner();
2135
+ init__connection_state();
2136
+ init__server_client();
2137
+ init__pi_install();
2138
+ init__snapshot_upload();
2139
+ init__doctor_checks();
2140
+ RIG_CONFIG_DEV_DEPENDENCIES = {
2141
+ "@rig/core": `npm:@h-rig/core@${RIG_CONFIG_PACKAGE_DIST_TAG}`,
2142
+ "@rig/standard-plugin": `npm:@h-rig/standard-plugin@${RIG_CONFIG_PACKAGE_DIST_TAG}`
2143
+ };
2144
+ DRONE_CANCEL = Symbol("drone-cancel");
2145
+ PROJECT_STATUS_PROMPTS = {
2146
+ running: "Running/In progress",
2147
+ prOpen: "PR open/review",
2148
+ ciFixing: "CI/review fixing",
2149
+ merging: "Merging",
2150
+ done: "Done",
2151
+ needsAttention: "Needs attention"
2152
+ };
2153
+ DEFAULT_PROJECT_STATUS_OPTIONS = {
2154
+ running: "In Progress",
2155
+ prOpen: "In Review",
2156
+ ciFixing: "In Review",
2157
+ merging: "Merging",
2158
+ done: "Done",
2159
+ needsAttention: "Needs Attention"
2160
+ };
2161
+ DEMO_TASKS = [
2162
+ {
2163
+ id: "demo-1",
2164
+ title: "Add a hello CLI script",
2165
+ body: [
2166
+ "Create `scripts/hello.ts` that prints `Hello from Rig!` plus the current date,",
2167
+ "and add a `hello` script entry to package.json that runs it with bun.",
2168
+ "Keep it dependency-free."
2169
+ ].join(`
2170
+ `),
2171
+ status: "ready",
2172
+ labels: ["demo"]
2173
+ },
2174
+ {
2175
+ id: "demo-2",
2176
+ title: "Write a README section about this project",
2177
+ body: [
2178
+ "Add (or extend) README.md with a short `## What this is` section:",
2179
+ "two or three sentences describing the repository and how to run it.",
2180
+ "Plain prose, no badges."
2181
+ ].join(`
2182
+ `),
2183
+ status: "ready",
2184
+ labels: ["demo"]
2185
+ },
2186
+ {
2187
+ id: "demo-3",
2188
+ title: "Add a unit test for the hello script",
2189
+ body: [
2190
+ "Add `scripts/hello.test.ts` with a bun test that imports the greeting",
2191
+ "helper from the hello script and asserts it contains `Hello from Rig!`.",
2192
+ "Refactor the script to export that helper if needed."
2193
+ ].join(`
2194
+ `),
2195
+ status: "ready",
2196
+ labels: ["demo"]
2197
+ }
2198
+ ];
2199
+ });
2200
+
2201
+ // packages/cli/src/app-opentui/adapters/init.ts
2202
+ import { existsSync as existsSync6 } from "fs";
2203
+ import { resolve as resolve7 } from "path";
2204
+
2205
+ // packages/cli/src/app-opentui/adapters/common.ts
2206
+ function adapterContextFromRuntime(runtime, renderer) {
2207
+ return {
2208
+ projectRoot: runtime.getState().projectRoot,
2209
+ renderer,
2210
+ ensureRuntime: () => runtime.getRunnerContext(),
2211
+ emit: (event) => runtime.emit(event),
2212
+ getState: () => runtime.getState()
2213
+ };
2214
+ }
2215
+ function projectRootOf(ctx) {
2216
+ const root = ctx.rig?.projectRoot ?? ctx.projectRoot ?? ctx.getState().projectRoot;
2217
+ if (typeof root === "string" && root.trim())
2218
+ return root;
2219
+ throw new Error("Rig app adapter requires a projectRoot.");
2220
+ }
2221
+ async function runtimeOf(ctx) {
2222
+ if (ctx.rig && "runId" in ctx.rig && ctx.ensureRuntime === undefined) {
2223
+ return ctx.rig;
2224
+ }
2225
+ if (ctx.ensureRuntime)
2226
+ return ctx.ensureRuntime();
2227
+ throw new Error("Rig app adapter requires ensureRuntime() before this action can run.");
2228
+ }
2229
+ function normalizeAppError(error) {
2230
+ const message = error instanceof Error ? error.message : String(error);
2231
+ const rawHint = error instanceof Error ? error.hint : undefined;
2232
+ return {
2233
+ message,
2234
+ ...typeof rawHint === "string" && rawHint.trim() ? { hint: rawHint.trim() } : {}
2235
+ };
2236
+ }
2237
+ function emitStarted(ctx, label, optimistic) {
2238
+ ctx.emit({ type: "action.started", label, ...optimistic ? { optimistic } : {} });
2239
+ }
2240
+ function emitProgress(ctx, label, detail, data) {
2241
+ ctx.emit({ type: "action.progress", label, ...detail ? { detail } : {}, ...data ? { data } : {} });
2242
+ }
2243
+ function emitCompleted(ctx, label, data) {
2244
+ ctx.emit({ type: "action.completed", label, ...data ? { data } : {} });
2245
+ }
2246
+ function emitFailed(ctx, label, error, data) {
2247
+ if (data)
2248
+ patchData(ctx, data);
2249
+ const normalized = normalizeAppError(error);
2250
+ ctx.emit({
2251
+ type: "action.failed",
2252
+ label,
2253
+ message: normalized.message,
2254
+ ...normalized.hint ? { hint: normalized.hint } : {},
2255
+ cause: error
2256
+ });
2257
+ }
2258
+ function patchData(ctx, data) {
2259
+ ctx.emit({ type: "data.patch", data });
2260
+ }
2261
+ async function captureConsole(fn) {
2262
+ const output = [];
2263
+ const original = {
2264
+ log: console.log,
2265
+ info: console.info,
2266
+ warn: console.warn,
2267
+ error: console.error
2268
+ };
2269
+ const capture = (...parts) => {
2270
+ output.push(parts.map((part) => typeof part === "string" ? part : JSON.stringify(part)).join(" "));
2271
+ };
2272
+ console.log = capture;
2273
+ console.info = capture;
2274
+ console.warn = capture;
2275
+ console.error = capture;
2276
+ try {
2277
+ const result = await fn();
2278
+ return { result, output };
2279
+ } finally {
2280
+ console.log = original.log;
2281
+ console.info = original.info;
2282
+ console.warn = original.warn;
2283
+ console.error = original.error;
2284
+ }
2285
+ }
2286
+
2287
+ // packages/cli/src/app-opentui/adapters/init.ts
2288
+ function createInitAdapter() {
2289
+ return {
2290
+ id: "init",
2291
+ async handleIntent(runtime, intent) {
2292
+ if (intent.scene !== "init" && intent.action.kind !== "init-start")
2293
+ return false;
2294
+ const ctx = adapterContextFromRuntime(runtime);
2295
+ if (intent.action.kind === "init-start" && intent.argv.includes("--yes")) {
2296
+ await runInitYes(ctx, ["--yes"]);
2297
+ return true;
2298
+ }
2299
+ await loadInitFacts(ctx);
2300
+ return true;
2301
+ }
2302
+ };
2303
+ }
2304
+ function readInitFacts(ctx) {
2305
+ const projectRoot = projectRootOf(ctx);
2306
+ const configNames = ["rig.config.ts", "rig.config.mts", "rig.config.json"];
2307
+ const configPath = configNames.map((name) => resolve7(projectRoot, name)).find((path) => existsSync6(path));
2308
+ return {
2309
+ hasConfig: Boolean(configPath),
2310
+ ...configPath ? { configPath } : {},
2311
+ hasGit: existsSync6(resolve7(projectRoot, ".git")),
2312
+ suggestedCommand: configPath ? "doctor" : "init"
2313
+ };
2314
+ }
2315
+ async function loadInitFacts(ctx) {
2316
+ const label = "Inspecting project";
2317
+ emitStarted(ctx, label);
2318
+ try {
2319
+ const facts = readInitFacts(ctx);
2320
+ patchData(ctx, { init: { facts } });
2321
+ emitCompleted(ctx, label, facts);
2322
+ return facts;
2323
+ } catch (error) {
2324
+ emitFailed(ctx, label, error);
2325
+ throw error;
2326
+ }
2327
+ }
2328
+ async function runInitYes(ctx, args = ["--yes"]) {
2329
+ const label = "Initializing Rig project";
2330
+ emitStarted(ctx, label, { init: { status: "writing-config" } });
2331
+ try {
2332
+ const runtime = await runtimeOf(ctx);
2333
+ emitProgress(ctx, label, "running existing init side effects without legacy output");
2334
+ const { executeInit: executeInit2 } = await Promise.resolve().then(() => (init_init(), exports_init));
2335
+ const { result, output } = await captureConsole(() => executeInit2({ ...runtime, outputMode: "json" }, [...args]));
2336
+ const record = result && typeof result === "object" && !Array.isArray(result) ? result : { ok: true };
2337
+ patchData(ctx, { init: { status: "done", result: record, capturedOutput: output } });
2338
+ emitCompleted(ctx, label, { result: record });
2339
+ return record;
2340
+ } catch (error) {
2341
+ patchData(ctx, { init: { status: "failed", error: error instanceof Error ? error.message : String(error) } });
2342
+ emitFailed(ctx, label, error);
2343
+ throw error;
2344
+ }
2345
+ }
2346
+ function buildInitTypeBarSuggestions(facts) {
2347
+ if (facts.hasConfig)
2348
+ return ["doctor", "tasks", "server"];
2349
+ return ["init --yes", "init --server remote", "help init"];
2350
+ }
2351
+ export {
2352
+ runInitYes,
2353
+ readInitFacts,
2354
+ loadInitFacts,
2355
+ createInitAdapter,
2356
+ buildInitTypeBarSuggestions
2357
+ };