@h-rig/cli 0.0.6-alpha.100 → 0.0.6-alpha.101

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 (112) hide show
  1. package/README.md +6 -27
  2. package/bin/rig.js +16 -0
  3. package/package.json +14 -40
  4. package/dist/bin/build-rig-binaries.d.ts +0 -2
  5. package/dist/bin/build-rig-binaries.js +0 -119
  6. package/dist/bin/rig.d.ts +0 -72
  7. package/dist/bin/rig.js +0 -17875
  8. package/dist/config/rig-default-config.yml +0 -5
  9. package/dist/src/app/drone-ui.d.ts +0 -34
  10. package/dist/src/app/drone-ui.js +0 -278
  11. package/dist/src/commands/_async-ui.d.ts +0 -10
  12. package/dist/src/commands/_async-ui.js +0 -121
  13. package/dist/src/commands/_cli-format.d.ts +0 -56
  14. package/dist/src/commands/_cli-format.js +0 -319
  15. package/dist/src/commands/_config-env.d.ts +0 -18
  16. package/dist/src/commands/_config-env.js +0 -22
  17. package/dist/src/commands/_connection-state.d.ts +0 -54
  18. package/dist/src/commands/_connection-state.js +0 -187
  19. package/dist/src/commands/_doctor-checks.d.ts +0 -46
  20. package/dist/src/commands/_doctor-checks.js +0 -352
  21. package/dist/src/commands/_help-catalog.d.ts +0 -29
  22. package/dist/src/commands/_help-catalog.js +0 -146
  23. package/dist/src/commands/_inprocess-services.d.ts +0 -33
  24. package/dist/src/commands/_inprocess-services.js +0 -102
  25. package/dist/src/commands/_json-output.d.ts +0 -11
  26. package/dist/src/commands/_json-output.js +0 -60
  27. package/dist/src/commands/_lazy-reconcile.d.ts +0 -34
  28. package/dist/src/commands/_lazy-reconcile.js +0 -102
  29. package/dist/src/commands/_parsers.d.ts +0 -15
  30. package/dist/src/commands/_parsers.js +0 -114
  31. package/dist/src/commands/_paths.d.ts +0 -11
  32. package/dist/src/commands/_paths.js +0 -50
  33. package/dist/src/commands/_pi-frontend.d.ts +0 -35
  34. package/dist/src/commands/_pi-frontend.js +0 -64
  35. package/dist/src/commands/_pi-install.d.ts +0 -42
  36. package/dist/src/commands/_pi-install.js +0 -167
  37. package/dist/src/commands/_policy.d.ts +0 -8
  38. package/dist/src/commands/_policy.js +0 -127
  39. package/dist/src/commands/_probes.d.ts +0 -1
  40. package/dist/src/commands/_probes.js +0 -13
  41. package/dist/src/commands/_run-bridge.d.ts +0 -114
  42. package/dist/src/commands/_run-bridge.js +0 -387
  43. package/dist/src/commands/_run-diagnostics.d.ts +0 -9
  44. package/dist/src/commands/_run-diagnostics.js +0 -51
  45. package/dist/src/commands/_run-driver-helpers.d.ts +0 -26
  46. package/dist/src/commands/_run-driver-helpers.js +0 -138
  47. package/dist/src/commands/_run-projection.d.ts +0 -50
  48. package/dist/src/commands/_run-projection.js +0 -349
  49. package/dist/src/commands/_run-subcommands.d.ts +0 -3
  50. package/dist/src/commands/_run-subcommands.js +0 -31
  51. package/dist/src/commands/_spinner.d.ts +0 -25
  52. package/dist/src/commands/_spinner.js +0 -65
  53. package/dist/src/commands/agent.d.ts +0 -3
  54. package/dist/src/commands/agent.js +0 -8952
  55. package/dist/src/commands/config.d.ts +0 -3
  56. package/dist/src/commands/config.js +0 -181
  57. package/dist/src/commands/dist.d.ts +0 -28
  58. package/dist/src/commands/dist.js +0 -417
  59. package/dist/src/commands/doctor.d.ts +0 -3
  60. package/dist/src/commands/doctor.js +0 -480
  61. package/dist/src/commands/github.d.ts +0 -3
  62. package/dist/src/commands/github.js +0 -342
  63. package/dist/src/commands/inbox.d.ts +0 -28
  64. package/dist/src/commands/inbox.js +0 -579
  65. package/dist/src/commands/init.d.ts +0 -64
  66. package/dist/src/commands/init.js +0 -1541
  67. package/dist/src/commands/inspect.d.ts +0 -20
  68. package/dist/src/commands/inspect.js +0 -764
  69. package/dist/src/commands/pi.d.ts +0 -3
  70. package/dist/src/commands/pi.js +0 -177
  71. package/dist/src/commands/plugin.d.ts +0 -16
  72. package/dist/src/commands/plugin.js +0 -714
  73. package/dist/src/commands/profile-and-review.d.ts +0 -4
  74. package/dist/src/commands/profile-and-review.js +0 -223
  75. package/dist/src/commands/queue.d.ts +0 -3
  76. package/dist/src/commands/queue.js +0 -197
  77. package/dist/src/commands/remote.d.ts +0 -3
  78. package/dist/src/commands/remote.js +0 -1340
  79. package/dist/src/commands/repo-git-harness.d.ts +0 -5
  80. package/dist/src/commands/repo-git-harness.js +0 -271
  81. package/dist/src/commands/run.d.ts +0 -21
  82. package/dist/src/commands/run.js +0 -17867
  83. package/dist/src/commands/server.d.ts +0 -3
  84. package/dist/src/commands/server.js +0 -249
  85. package/dist/src/commands/setup.d.ts +0 -16
  86. package/dist/src/commands/setup.js +0 -644
  87. package/dist/src/commands/stats.d.ts +0 -15
  88. package/dist/src/commands/stats.js +0 -632
  89. package/dist/src/commands/task-run-driver.d.ts +0 -94
  90. package/dist/src/commands/task-run-driver.js +0 -203
  91. package/dist/src/commands/task.d.ts +0 -35
  92. package/dist/src/commands/task.js +0 -818
  93. package/dist/src/commands/test.d.ts +0 -3
  94. package/dist/src/commands/test.js +0 -46
  95. package/dist/src/commands/triage.d.ts +0 -11
  96. package/dist/src/commands/triage.js +0 -227
  97. package/dist/src/commands/workspace.d.ts +0 -3
  98. package/dist/src/commands/workspace.js +0 -130
  99. package/dist/src/commands.d.ts +0 -13
  100. package/dist/src/commands.js +0 -17999
  101. package/dist/src/index.d.ts +0 -4
  102. package/dist/src/index.js +0 -18011
  103. package/dist/src/launcher.d.ts +0 -61
  104. package/dist/src/launcher.js +0 -199
  105. package/dist/src/operator-cli.d.ts +0 -2
  106. package/dist/src/operator-cli.js +0 -17867
  107. package/dist/src/operator-entry.d.ts +0 -1
  108. package/dist/src/operator-entry.js +0 -3
  109. package/dist/src/runner.d.ts +0 -47
  110. package/dist/src/runner.js +0 -267
  111. package/dist/src/withMutedConsole.d.ts +0 -2
  112. package/dist/src/withMutedConsole.js +0 -42
@@ -1,1340 +0,0 @@
1
- // @bun
2
- // packages/cli/src/runner.ts
3
- import { EventBus } from "@rig/runtime/control-plane/runtime/events";
4
- import { CliError as RuntimeCliError } from "@rig/runtime/control-plane/errors";
5
- import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
6
- import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
7
-
8
- class CliError extends RuntimeCliError {
9
- hint;
10
- constructor(message, exitCode = 1, options = {}) {
11
- super(message, exitCode);
12
- if (options.hint?.trim()) {
13
- this.hint = options.hint.trim();
14
- }
15
- }
16
- }
17
- function takeFlag(args, flag) {
18
- const rest = [];
19
- let value = false;
20
- for (const arg of args) {
21
- if (arg === flag) {
22
- value = true;
23
- continue;
24
- }
25
- rest.push(arg);
26
- }
27
- return { value, rest };
28
- }
29
- function takeOption(args, option) {
30
- const rest = [];
31
- let value;
32
- for (let index = 0;index < args.length; index += 1) {
33
- const current = args[index];
34
- if (current === option) {
35
- const next = args[index + 1];
36
- if (!next || next.startsWith("-")) {
37
- throw new CliError(`Missing value for ${option}`, 1, { hint: `Provide a value after ${option}, e.g. \`${option} <value>\`.` });
38
- }
39
- value = next;
40
- index += 1;
41
- continue;
42
- }
43
- if (current !== undefined) {
44
- rest.push(current);
45
- }
46
- }
47
- return { value, rest };
48
- }
49
- function requireNoExtraArgs(args, usage) {
50
- if (args.length > 0) {
51
- throw new CliError(`Unexpected arguments: ${args.join(" ")}
52
- Usage: ${usage}`);
53
- }
54
- }
55
- function requireTask(taskId, usage) {
56
- if (!taskId) {
57
- throw new CliError(`Missing --task option.
58
- Usage: ${usage}`);
59
- }
60
- return taskId;
61
- }
62
-
63
- // packages/runtime/src/control-plane/remote.ts
64
- import { randomUUID } from "crypto";
65
- import { chmodSync, existsSync as existsSync2, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "fs";
66
- import { homedir, tmpdir } from "os";
67
- import { dirname as dirname2, join, resolve as resolve2 } from "path";
68
- import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
69
-
70
- // packages/runtime/src/control-plane/server-paths.ts
71
- import { existsSync } from "fs";
72
- import { dirname, resolve, relative } from "path";
73
- import { assertPathInsideRoot, assertSafeRunId, safePathSegment } from "@rig/shared/safe-identifiers";
74
- function normalizeOptionalString(value) {
75
- return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
76
- }
77
- function resolveAuthorityPaths(projectRoot) {
78
- const normalizedRoot = resolve(projectRoot);
79
- const stateRoot = resolveAuthorityStateRoot(normalizedRoot);
80
- const stateDir = resolveAuthorityStateDir(normalizedRoot);
81
- return {
82
- projectRoot: normalizedRoot,
83
- harnessRoot: resolve(normalizedRoot, "rig"),
84
- runsDir: resolve(stateRoot, "runs"),
85
- remoteDir: resolve(stateRoot, "remote"),
86
- stateDir,
87
- remoteEndpointsPath: resolve(stateRoot, "remote", "endpoints.toml"),
88
- remoteSecretsPath: resolve(stateDir, "remote-secrets.toml")
89
- };
90
- }
91
- function resolveAuthorityStateRoot(projectRoot) {
92
- const normalizedRoot = resolve(projectRoot);
93
- const taskWorkspace = normalizeOptionalString(process.env.RIG_TASK_WORKSPACE);
94
- if (taskWorkspace) {
95
- return resolve(taskWorkspace, ".rig");
96
- }
97
- const stateDir = normalizeOptionalString(process.env.RIG_STATE_DIR);
98
- if (stateDir) {
99
- return dirname(resolve(stateDir));
100
- }
101
- const logsDir = normalizeOptionalString(process.env.RIG_LOGS_DIR);
102
- if (logsDir) {
103
- return dirname(resolve(logsDir));
104
- }
105
- const sessionFile = normalizeOptionalString(process.env.RIG_SESSION_FILE);
106
- if (sessionFile) {
107
- return dirname(dirname(resolve(sessionFile)));
108
- }
109
- const projectStateRoot = resolve(normalizedRoot, ".rig");
110
- if (existsSync(projectStateRoot)) {
111
- return projectStateRoot;
112
- }
113
- return resolve(normalizedRoot, ".rig");
114
- }
115
- function resolveAuthorityStateDir(projectRoot) {
116
- const explicit = normalizeOptionalString(process.env.RIG_STATE_DIR);
117
- if (explicit) {
118
- return resolve(explicit);
119
- }
120
- return resolve(resolveAuthorityStateRoot(projectRoot), "state");
121
- }
122
-
123
- // packages/runtime/src/control-plane/remote.ts
124
- var DEFAULT_REMOTE_PORT = 7890;
125
- var DEFAULT_RIG_BACKBONE_HOST = "where.rig-does.work";
126
- var DEFAULT_RIG_RELAY_URL = `wss://${DEFAULT_RIG_BACKBONE_HOST}`;
127
- var DEFAULT_RIG_REGISTRY_URL = `https://${DEFAULT_RIG_BACKBONE_HOST}/registry`;
128
- var DEFAULT_TIMEOUTS = {
129
- connectMs: 5000,
130
- authMs: 5000,
131
- requestMs: 30000,
132
- subscriptionMs: 1e4
133
- };
134
- var REMOTES_CONFIG_PATH = join(homedir(), ".config", "rig", "remotes.toml");
135
-
136
- class RemoteCliError extends Error {
137
- code;
138
- exitCode;
139
- details;
140
- constructor(code, message, exitCode = 1, details) {
141
- super(message);
142
- this.name = "RemoteCliError";
143
- this.code = code;
144
- this.exitCode = exitCode;
145
- this.details = details;
146
- }
147
- }
148
- function loadRemotesConfig(configPath = REMOTES_CONFIG_PATH) {
149
- if (!existsSync2(configPath)) {
150
- return { version: 1, remotes: {} };
151
- }
152
- try {
153
- const content = readFileSync(configPath, "utf-8");
154
- if (!content.trim()) {
155
- return { version: 1, remotes: {} };
156
- }
157
- const parsed = parseToml(content);
158
- return {
159
- version: parsed.version ?? 1,
160
- remotes: parsed.remotes ?? {}
161
- };
162
- } catch (error) {
163
- throw new RemoteCliError("RIG_REMOTE_CONFIG_PARSE_ERROR", `Failed to parse remotes config at ${configPath}: ${error instanceof Error ? error.message : String(error)}`, 2, { configPath });
164
- }
165
- }
166
- function saveRemotesConfig(config, configPath = REMOTES_CONFIG_PATH) {
167
- mkdirSync(dirname2(configPath), { recursive: true });
168
- writeFileSync(configPath, `${stringifyToml(config).trimEnd()}
169
- `, "utf-8");
170
- try {
171
- chmodSync(configPath, 384);
172
- } catch {}
173
- }
174
- function readTomlFile(path, fallback) {
175
- if (!existsSync2(path))
176
- return fallback;
177
- const raw = readFileSync(path, "utf8");
178
- if (!raw.trim())
179
- return fallback;
180
- return parseToml(raw);
181
- }
182
- function writeTomlFile(path, value) {
183
- mkdirSync(dirname2(path), { recursive: true });
184
- writeFileSync(path, `${stringifyToml(value).trimEnd()}
185
- `, "utf8");
186
- }
187
- function normalizeStringArray(value) {
188
- if (!Array.isArray(value))
189
- return [];
190
- return value.map((entry) => normalizeString(entry)).filter((entry) => entry !== "");
191
- }
192
- function normalizePort(value) {
193
- const port = typeof value === "number" ? value : Number(value);
194
- return Number.isInteger(port) && port > 0 && port <= 65535 ? port : DEFAULT_REMOTE_PORT;
195
- }
196
- function loadRemoteEndpointsToml(projectRoot) {
197
- const paths = resolveAuthorityPaths(projectRoot);
198
- const parsed = readTomlFile(paths.remoteEndpointsPath, { version: 1, endpoints: {} });
199
- return {
200
- version: parsed.version ?? 1,
201
- endpoints: parsed.endpoints ?? {}
202
- };
203
- }
204
- function loadRemoteSecretsToml(projectRoot) {
205
- const paths = resolveAuthorityPaths(projectRoot);
206
- const parsed = readTomlFile(paths.remoteSecretsPath, { version: 1, secrets: {} });
207
- return {
208
- version: parsed.version ?? 1,
209
- secrets: parsed.secrets ?? {}
210
- };
211
- }
212
- function saveRemoteEndpointsToml(projectRoot, payload) {
213
- writeTomlFile(resolveAuthorityPaths(projectRoot).remoteEndpointsPath, payload);
214
- }
215
- function saveRemoteSecretsToml(projectRoot, payload) {
216
- const paths = resolveAuthorityPaths(projectRoot);
217
- writeTomlFile(paths.remoteSecretsPath, payload);
218
- try {
219
- chmodSync(paths.remoteSecretsPath, 384);
220
- } catch {}
221
- }
222
- function listAuthorityRemoteEndpoints(projectRoot) {
223
- const endpoints = loadRemoteEndpointsToml(projectRoot).endpoints ?? {};
224
- const secrets = loadRemoteSecretsToml(projectRoot).secrets ?? {};
225
- return Object.values(endpoints).map((entry) => {
226
- const token = secrets[entry.secret_ref] ?? "";
227
- return {
228
- id: entry.id,
229
- alias: entry.alias,
230
- host: entry.host,
231
- port: normalizePort(entry.port),
232
- token,
233
- autoConnect: Boolean(entry.auto_connect),
234
- addedAt: entry.created_at,
235
- updatedAt: entry.updated_at,
236
- lastConnectedAt: normalizeString(entry.last_connected_at) || null,
237
- labels: normalizeStringArray(entry.labels),
238
- capabilities: normalizeStringArray(entry.capabilities),
239
- transport: normalizeString(entry.transport) || "websocket",
240
- secretRef: entry.secret_ref
241
- };
242
- }).sort((left, right) => left.alias.localeCompare(right.alias));
243
- }
244
- function nextRemoteEndpointRecord(input) {
245
- const timestamp = new Date().toISOString();
246
- const secretRef = input.existing?.secret_ref ?? randomUUID();
247
- return {
248
- record: {
249
- id: input.endpointId ?? input.existing?.id ?? randomUUID(),
250
- alias: input.alias,
251
- host: input.host,
252
- port: normalizePort(input.port),
253
- transport: normalizeString(input.transport) || normalizeString(input.existing?.transport) || "websocket",
254
- auto_connect: input.autoConnect ?? input.existing?.auto_connect ?? false,
255
- labels: input.labels ?? normalizeStringArray(input.existing?.labels),
256
- capabilities: input.capabilities ?? normalizeStringArray(input.existing?.capabilities),
257
- secret_ref: secretRef,
258
- created_at: input.existing?.created_at ?? timestamp,
259
- updated_at: timestamp,
260
- last_connected_at: input.existing?.last_connected_at ?? null
261
- },
262
- secretRef
263
- };
264
- }
265
- function upsertAuthorityRemoteEndpoint(projectRoot, input) {
266
- const endpointsToml = loadRemoteEndpointsToml(projectRoot);
267
- const secretsToml = loadRemoteSecretsToml(projectRoot);
268
- const existing = Object.values(endpointsToml.endpoints ?? {}).find((entry) => entry.alias === input.alias) ?? null;
269
- const { record, secretRef } = nextRemoteEndpointRecord({
270
- endpointId: input.endpointId,
271
- existing,
272
- alias: input.alias,
273
- host: input.host,
274
- port: input.port,
275
- token: input.token,
276
- autoConnect: input.autoConnect,
277
- transport: input.transport,
278
- labels: input.labels,
279
- capabilities: input.capabilities
280
- });
281
- endpointsToml.endpoints = {
282
- ...endpointsToml.endpoints ?? {},
283
- [record.id]: record
284
- };
285
- secretsToml.secrets = {
286
- ...secretsToml.secrets ?? {},
287
- [secretRef]: input.token
288
- };
289
- saveRemoteEndpointsToml(projectRoot, endpointsToml);
290
- saveRemoteSecretsToml(projectRoot, secretsToml);
291
- return listAuthorityRemoteEndpoints(projectRoot).find((entry) => entry.id === record.id);
292
- }
293
- function updateAuthorityRemoteEndpoint(projectRoot, input) {
294
- const endpointsToml = loadRemoteEndpointsToml(projectRoot);
295
- const secretsToml = loadRemoteSecretsToml(projectRoot);
296
- const current = Object.values(endpointsToml.endpoints ?? {}).find((entry) => input.endpointId && entry.id === input.endpointId || input.alias && entry.alias === input.alias);
297
- if (!current)
298
- return null;
299
- const record = {
300
- ...current,
301
- alias: normalizeString(input.alias) || current.alias,
302
- host: normalizeString(input.host) || current.host,
303
- port: input.port !== undefined ? normalizePort(input.port) : current.port,
304
- auto_connect: input.autoConnect ?? current.auto_connect,
305
- transport: normalizeString(input.transport) || current.transport,
306
- labels: input.labels ?? normalizeStringArray(current.labels),
307
- capabilities: input.capabilities ?? normalizeStringArray(current.capabilities),
308
- updated_at: new Date().toISOString()
309
- };
310
- endpointsToml.endpoints = {
311
- ...endpointsToml.endpoints ?? {},
312
- [record.id]: record
313
- };
314
- if (input.token !== undefined) {
315
- secretsToml.secrets = {
316
- ...secretsToml.secrets ?? {},
317
- [record.secret_ref]: input.token
318
- };
319
- }
320
- saveRemoteEndpointsToml(projectRoot, endpointsToml);
321
- saveRemoteSecretsToml(projectRoot, secretsToml);
322
- return listAuthorityRemoteEndpoints(projectRoot).find((entry) => entry.id === record.id) ?? null;
323
- }
324
- function removeAuthorityRemoteEndpoint(projectRoot, endpointIdOrAlias) {
325
- const endpointsToml = loadRemoteEndpointsToml(projectRoot);
326
- const secretsToml = loadRemoteSecretsToml(projectRoot);
327
- const entry = Object.values(endpointsToml.endpoints ?? {}).find((candidate) => candidate.id === endpointIdOrAlias || candidate.alias === endpointIdOrAlias);
328
- if (!entry)
329
- return false;
330
- const nextEndpoints = { ...endpointsToml.endpoints ?? {} };
331
- delete nextEndpoints[entry.id];
332
- const nextSecrets = { ...secretsToml.secrets ?? {} };
333
- delete nextSecrets[entry.secret_ref];
334
- saveRemoteEndpointsToml(projectRoot, { version: endpointsToml.version ?? 1, endpoints: nextEndpoints });
335
- saveRemoteSecretsToml(projectRoot, { version: secretsToml.version ?? 1, secrets: nextSecrets });
336
- return true;
337
- }
338
- function markAuthorityRemoteEndpointConnected(projectRoot, endpointId, connectedAt = new Date().toISOString()) {
339
- const endpointsToml = loadRemoteEndpointsToml(projectRoot);
340
- const entry = endpointsToml.endpoints?.[endpointId];
341
- if (!entry)
342
- return;
343
- endpointsToml.endpoints = {
344
- ...endpointsToml.endpoints ?? {},
345
- [endpointId]: {
346
- ...entry,
347
- last_connected_at: connectedAt,
348
- updated_at: connectedAt
349
- }
350
- };
351
- saveRemoteEndpointsToml(projectRoot, endpointsToml);
352
- }
353
- function importLegacyRemoteEndpoints(projectRoot, legacyPath = REMOTES_CONFIG_PATH) {
354
- if (!existsSync2(legacyPath)) {
355
- return { imported: 0, skipped: 0, sourcePath: legacyPath };
356
- }
357
- const parsed = readTomlFile(legacyPath, { version: 1, remotes: {} });
358
- let imported = 0;
359
- let skipped = 0;
360
- for (const [alias, entry] of Object.entries(parsed.remotes ?? {})) {
361
- const host = normalizeString(entry.host);
362
- const token = normalizeString(entry.token);
363
- if (!host || !token) {
364
- skipped += 1;
365
- continue;
366
- }
367
- upsertAuthorityRemoteEndpoint(projectRoot, {
368
- alias,
369
- host,
370
- port: normalizePort(entry.port),
371
- token
372
- });
373
- imported += 1;
374
- }
375
- return { imported, skipped, sourcePath: legacyPath };
376
- }
377
- function doctorAuthorityRemoteEndpoints(projectRoot) {
378
- const paths = resolveAuthorityPaths(projectRoot);
379
- const endpoints = loadRemoteEndpointsToml(projectRoot).endpoints ?? {};
380
- const secrets = loadRemoteSecretsToml(projectRoot).secrets ?? {};
381
- const missingSecrets = Object.values(endpoints).filter((entry) => !normalizeString(secrets[entry.secret_ref])).map((entry) => entry.alias);
382
- const warnings = [];
383
- if (!existsSync2(paths.remoteEndpointsPath)) {
384
- warnings.push("Remote endpoint manifest is missing.");
385
- }
386
- if (!existsSync2(paths.remoteSecretsPath)) {
387
- warnings.push("Remote secret store is missing.");
388
- }
389
- return {
390
- manifestPath: paths.remoteEndpointsPath,
391
- secretsPath: paths.remoteSecretsPath,
392
- endpointCount: Object.keys(endpoints).length,
393
- missingSecrets,
394
- warnings
395
- };
396
- }
397
- function listManagedRemoteEndpoints(configPath = REMOTES_CONFIG_PATH, projectRoot) {
398
- if (projectRoot) {
399
- return listAuthorityRemoteEndpoints(projectRoot).map((entry) => ({
400
- id: entry.id,
401
- alias: entry.alias,
402
- host: entry.host,
403
- port: entry.port,
404
- token: entry.token,
405
- addedAt: entry.addedAt,
406
- lastConnected: entry.lastConnectedAt
407
- }));
408
- }
409
- const config = loadRemotesConfig(configPath);
410
- return Object.entries(config.remotes ?? {}).map(([alias, entry]) => ({
411
- id: alias,
412
- alias,
413
- host: normalizeString(entry.host) || "",
414
- port: Number.isFinite(entry.port) ? Number(entry.port) : DEFAULT_REMOTE_PORT,
415
- token: normalizeString(entry.token) || "",
416
- addedAt: normalizeString(entry.addedAt) || null,
417
- lastConnected: normalizeString(entry.lastConnected) || null
418
- })).sort((left, right) => left.alias.localeCompare(right.alias));
419
- }
420
- function upsertManagedRemoteEndpoint(input, configPath = REMOTES_CONFIG_PATH, projectRoot) {
421
- if (projectRoot) {
422
- const saved = upsertAuthorityRemoteEndpoint(projectRoot, {
423
- ...input,
424
- token: input.token ?? ""
425
- });
426
- return {
427
- id: saved.id,
428
- alias: saved.alias,
429
- host: saved.host,
430
- port: saved.port,
431
- token: saved.token,
432
- addedAt: saved.addedAt,
433
- lastConnected: saved.lastConnectedAt
434
- };
435
- }
436
- const config = loadRemotesConfig(configPath);
437
- const existing = config.remotes?.[input.alias];
438
- const nextEntry = {
439
- host: input.host,
440
- port: input.port,
441
- token: input.token,
442
- addedAt: normalizeString(existing?.addedAt) || new Date().toISOString(),
443
- ...normalizeString(existing?.lastConnected) ? { lastConnected: normalizeString(existing?.lastConnected) } : {}
444
- };
445
- const nextConfig = {
446
- version: config.version ?? 1,
447
- remotes: {
448
- ...config.remotes ?? {},
449
- [input.alias]: nextEntry
450
- }
451
- };
452
- saveRemotesConfig(nextConfig, configPath);
453
- return {
454
- id: input.alias,
455
- alias: input.alias,
456
- host: input.host,
457
- port: input.port,
458
- token: input.token ?? "",
459
- addedAt: nextEntry.addedAt ?? null,
460
- lastConnected: nextEntry.lastConnected ?? null
461
- };
462
- }
463
- function removeManagedRemoteEndpoint(alias, configPath = REMOTES_CONFIG_PATH, projectRoot) {
464
- if (projectRoot) {
465
- return removeAuthorityRemoteEndpoint(projectRoot, alias);
466
- }
467
- const config = loadRemotesConfig(configPath);
468
- if (!config.remotes?.[alias]) {
469
- return false;
470
- }
471
- const nextRemotes = { ...config.remotes ?? {} };
472
- delete nextRemotes[alias];
473
- saveRemotesConfig({
474
- version: config.version ?? 1,
475
- remotes: nextRemotes
476
- }, configPath);
477
- return true;
478
- }
479
- function resolveRemoteEndpoint(options) {
480
- const env = options.env ?? process.env;
481
- const envHost = normalizeString(env.RIG_REMOTE_HOST);
482
- const envToken = normalizeString(env.RIG_REMOTE_TOKEN);
483
- const envPort = parsePort(normalizeString(env.RIG_REMOTE_PORT), "RIG_REMOTE_PORT");
484
- const envAlias = normalizeString(env.RIG_REMOTE_ALIAS);
485
- const explicitHost = normalizeString(options.host);
486
- const explicitToken = normalizeString(options.token);
487
- const explicitPort = parsePort(normalizeString(options.port), "--port");
488
- const explicitProvided = Boolean(explicitHost || explicitToken || explicitPort !== null);
489
- const requestedAlias = normalizeString(options.remoteAlias) || envAlias;
490
- let endpoint = {
491
- source: "env",
492
- host: envHost || "",
493
- port: envPort ?? DEFAULT_REMOTE_PORT,
494
- token: envToken || "",
495
- configPath: REMOTES_CONFIG_PATH
496
- };
497
- if (requestedAlias) {
498
- if (options.projectRoot) {
499
- const remote = listAuthorityRemoteEndpoints(options.projectRoot).find((entry) => entry.alias === requestedAlias);
500
- if (!remote) {
501
- const configPath = resolveAuthorityPaths(options.projectRoot).remoteEndpointsPath;
502
- throw new RemoteCliError("RIG_REMOTE_ALIAS_NOT_FOUND", `Remote alias '${requestedAlias}' was not found in ${configPath}.`, 2, { alias: requestedAlias, configPath });
503
- }
504
- endpoint = {
505
- source: "alias",
506
- alias: requestedAlias,
507
- host: remote.host,
508
- port: remote.port,
509
- token: remote.token,
510
- configPath: resolveAuthorityPaths(options.projectRoot).remoteEndpointsPath
511
- };
512
- } else {
513
- const config = loadRemotesConfig();
514
- const remote = config.remotes?.[requestedAlias];
515
- if (!remote) {
516
- throw new RemoteCliError("RIG_REMOTE_ALIAS_NOT_FOUND", `Remote alias '${requestedAlias}' was not found in ${REMOTES_CONFIG_PATH}.`, 2, { alias: requestedAlias, configPath: REMOTES_CONFIG_PATH });
517
- }
518
- endpoint = {
519
- source: "alias",
520
- alias: requestedAlias,
521
- host: normalizeString(remote.host) || "",
522
- port: Number.isFinite(remote.port) ? Number(remote.port) : DEFAULT_REMOTE_PORT,
523
- token: normalizeString(remote.token) || "",
524
- configPath: REMOTES_CONFIG_PATH
525
- };
526
- }
527
- }
528
- if (explicitProvided) {
529
- endpoint = {
530
- ...endpoint,
531
- source: "flags",
532
- host: explicitHost || endpoint.host,
533
- port: explicitPort ?? endpoint.port,
534
- token: explicitToken || endpoint.token
535
- };
536
- }
537
- if (!endpoint.host) {
538
- throw new RemoteCliError("RIG_REMOTE_HOST_REQUIRED", "Remote host is required. Pass --host, --remote <alias>, or set RIG_REMOTE_HOST.", 2);
539
- }
540
- if (!Number.isFinite(endpoint.port) || endpoint.port <= 0 || endpoint.port > 65535) {
541
- throw new RemoteCliError("RIG_REMOTE_INVALID_PORT", `Invalid remote port: ${endpoint.port}.`, 2);
542
- }
543
- return endpoint;
544
- }
545
-
546
- class RemoteWsClient {
547
- endpoint;
548
- ws = null;
549
- connected = false;
550
- pending = new Map;
551
- onEvent;
552
- requestTimeoutMs;
553
- connectTimeoutMs;
554
- authTimeoutMs;
555
- subscriptionTimeoutMs;
556
- connectionToken = null;
557
- connectionTokenExpiresAt = null;
558
- tokenRefreshTimer = null;
559
- constructor(endpoint, options = {}) {
560
- this.endpoint = endpoint;
561
- this.onEvent = options.onEvent;
562
- this.connectTimeoutMs = options.connectTimeoutMs ?? DEFAULT_TIMEOUTS.connectMs;
563
- this.authTimeoutMs = options.authTimeoutMs ?? DEFAULT_TIMEOUTS.authMs;
564
- this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_TIMEOUTS.requestMs;
565
- this.subscriptionTimeoutMs = options.subscriptionTimeoutMs ?? DEFAULT_TIMEOUTS.subscriptionMs;
566
- }
567
- setEventHandler(handler) {
568
- this.onEvent = handler;
569
- }
570
- async connect() {
571
- if (this.connected) {
572
- return;
573
- }
574
- const url = `ws://${this.endpoint.host}:${this.endpoint.port}`;
575
- await new Promise((resolve3, reject) => {
576
- let authResolved = false;
577
- let connectTimer = setTimeout(() => {
578
- connectTimer = null;
579
- reject(new RemoteCliError("RIG_REMOTE_CONNECT_TIMEOUT", `Timed out connecting to ${url} after ${this.connectTimeoutMs}ms.`, 3, { host: this.endpoint.host, port: this.endpoint.port, timeoutMs: this.connectTimeoutMs }));
580
- }, this.connectTimeoutMs);
581
- const ws = new WebSocket(url);
582
- this.ws = ws;
583
- ws.onopen = () => {
584
- const authMessage = {
585
- type: "auth",
586
- id: crypto.randomUUID(),
587
- timestamp: new Date().toISOString(),
588
- token: this.connectionToken || this.endpoint.token,
589
- tokenType: this.connectionToken ? "connection" : "server"
590
- };
591
- let authTimer = setTimeout(() => {
592
- authTimer = null;
593
- reject(new RemoteCliError("RIG_REMOTE_AUTH_TIMEOUT", `Timed out waiting for auth response from ${url} after ${this.authTimeoutMs}ms.`, 3, { host: this.endpoint.host, port: this.endpoint.port, timeoutMs: this.authTimeoutMs }));
594
- }, this.authTimeoutMs);
595
- ws.send(JSON.stringify(authMessage));
596
- const originalOnMessage = ws.onmessage;
597
- ws.onmessage = (event) => {
598
- const message = parseIncomingMessage(event.data);
599
- if (!message) {
600
- return;
601
- }
602
- if (message.type === "auth_response" && !authResolved) {
603
- authResolved = true;
604
- if (connectTimer) {
605
- clearTimeout(connectTimer);
606
- connectTimer = null;
607
- }
608
- if (authTimer) {
609
- clearTimeout(authTimer);
610
- authTimer = null;
611
- }
612
- const auth = message;
613
- if (!auth.success) {
614
- reject(new RemoteCliError("RIG_REMOTE_AUTH_FAILED", auth.error || "Remote authentication failed.", 3, { host: this.endpoint.host, port: this.endpoint.port }));
615
- return;
616
- }
617
- if (auth.connectionToken && auth.connectionTokenExpiresAt) {
618
- this.connectionToken = auth.connectionToken;
619
- this.connectionTokenExpiresAt = auth.connectionTokenExpiresAt;
620
- this.scheduleTokenRefresh();
621
- }
622
- if (this.endpoint.configPath.endsWith("endpoints.toml")) {
623
- const projectRoot = dirname2(dirname2(dirname2(this.endpoint.configPath)));
624
- try {
625
- markAuthorityRemoteEndpointConnected(projectRoot, this.endpoint.alias ? listAuthorityRemoteEndpoints(projectRoot).find((entry) => entry.alias === this.endpoint.alias)?.id ?? "" : "");
626
- } catch {}
627
- }
628
- this.connected = true;
629
- ws.onmessage = (event2) => {
630
- const next = parseIncomingMessage(event2.data);
631
- if (!next) {
632
- return;
633
- }
634
- this.routeMessage(next);
635
- };
636
- resolve3();
637
- return;
638
- }
639
- if (typeof originalOnMessage === "function") {
640
- originalOnMessage.call(ws, event);
641
- }
642
- };
643
- };
644
- ws.onerror = () => {
645
- if (connectTimer) {
646
- clearTimeout(connectTimer);
647
- connectTimer = null;
648
- }
649
- if (!authResolved) {
650
- reject(new RemoteCliError("RIG_REMOTE_CONNECT_FAILED", `Failed to connect to ${url}.`, 3, { host: this.endpoint.host, port: this.endpoint.port }));
651
- }
652
- };
653
- ws.onclose = () => {
654
- this.connected = false;
655
- this.clearPending("Connection closed");
656
- };
657
- });
658
- }
659
- disconnect() {
660
- this.connected = false;
661
- this.clearTokenRefreshTimer();
662
- this.clearPending("Connection closed");
663
- if (this.ws) {
664
- try {
665
- this.ws.close();
666
- } catch {}
667
- this.ws = null;
668
- }
669
- }
670
- async subscribe(eventTypes = []) {
671
- const message = { type: "subscribe" };
672
- if (eventTypes.length > 0) {
673
- message.eventTypes = eventTypes;
674
- }
675
- const response = await this.request(message, this.subscriptionTimeoutMs);
676
- return expectType(response, "operation_result");
677
- }
678
- async unsubscribe() {
679
- return expectType(await this.request({ type: "unsubscribe" }), "operation_result");
680
- }
681
- async getState() {
682
- return expectType(await this.request({ type: "get_state" }), "state_response");
683
- }
684
- async getTasks() {
685
- return expectType(await this.request({ type: "get_tasks" }), "tasks_response");
686
- }
687
- async pause() {
688
- return expectType(await this.request({ type: "pause" }), "operation_result");
689
- }
690
- async resume() {
691
- return expectType(await this.request({ type: "resume" }), "operation_result");
692
- }
693
- async interrupt() {
694
- return expectType(await this.request({ type: "interrupt" }), "operation_result");
695
- }
696
- async continueExecution() {
697
- return expectType(await this.request({ type: "continue" }), "operation_result");
698
- }
699
- async refreshTasks() {
700
- return expectType(await this.request({ type: "refresh_tasks" }), "operation_result");
701
- }
702
- async addIterations(count) {
703
- return expectType(await this.request({ type: "add_iterations", count }), "operation_result");
704
- }
705
- async removeIterations(count) {
706
- return expectType(await this.request({ type: "remove_iterations", count }), "operation_result");
707
- }
708
- async getPromptPreview(taskId) {
709
- return expectType(await this.request({ type: "get_prompt_preview", taskId }), "prompt_preview_response");
710
- }
711
- async getIterationOutput(taskId) {
712
- return expectType(await this.request({ type: "get_iteration_output", taskId }), "iteration_output_response");
713
- }
714
- async startOrchestration(options) {
715
- return expectType(await this.request({
716
- type: "orchestrate:start",
717
- maxWorkers: options.maxWorkers,
718
- maxIterations: options.maxIterations,
719
- directMerge: options.directMerge
720
- }), "orchestrate:start_response");
721
- }
722
- async pauseOrchestration(orchestrationId) {
723
- return expectType(await this.request({ type: "orchestrate:pause", orchestrationId }), "operation_result");
724
- }
725
- async resumeOrchestration(orchestrationId) {
726
- return expectType(await this.request({ type: "orchestrate:resume", orchestrationId }), "operation_result");
727
- }
728
- async stopOrchestration(orchestrationId) {
729
- return expectType(await this.request({ type: "orchestrate:stop", orchestrationId }), "operation_result");
730
- }
731
- async getOrchestrationState(orchestrationId) {
732
- return expectType(await this.request({ type: "orchestrate:get_state", orchestrationId }), "orchestrate:state_response");
733
- }
734
- async ping() {
735
- return this.request({ type: "ping" });
736
- }
737
- async request(payload, timeoutMs = this.requestTimeoutMs) {
738
- if (!this.connected || !this.ws) {
739
- throw new RemoteCliError("RIG_REMOTE_NOT_CONNECTED", "Remote client is not connected.", 3);
740
- }
741
- const id = crypto.randomUUID();
742
- const message = {
743
- ...payload,
744
- id,
745
- timestamp: new Date().toISOString()
746
- };
747
- return await new Promise((resolve3, reject) => {
748
- const timeout = setTimeout(() => {
749
- this.pending.delete(id);
750
- reject(new RemoteCliError("RIG_REMOTE_REQUEST_TIMEOUT", `Timed out waiting for response to '${String(payload.type)}' after ${timeoutMs}ms.`, 3, { requestType: payload.type, requestId: id, timeoutMs }));
751
- }, timeoutMs);
752
- this.pending.set(id, { resolve: resolve3, reject, timeout });
753
- this.ws?.send(JSON.stringify(message));
754
- });
755
- }
756
- routeMessage(message) {
757
- if (message.id && this.pending.has(message.id)) {
758
- const pending = this.pending.get(message.id);
759
- if (pending) {
760
- clearTimeout(pending.timeout);
761
- this.pending.delete(message.id);
762
- pending.resolve(message);
763
- }
764
- return;
765
- }
766
- if (message.type === "token_refresh_response") {
767
- const token = normalizeString(message.connectionToken);
768
- const expiresAt = normalizeString(message.connectionTokenExpiresAt);
769
- if (token && expiresAt) {
770
- this.connectionToken = token;
771
- this.connectionTokenExpiresAt = expiresAt;
772
- this.scheduleTokenRefresh();
773
- }
774
- }
775
- this.onEvent?.({ receivedAt: new Date().toISOString(), message });
776
- }
777
- scheduleTokenRefresh() {
778
- this.clearTokenRefreshTimer();
779
- if (!this.connectionToken || !this.connectionTokenExpiresAt || !this.ws || !this.connected) {
780
- return;
781
- }
782
- const expiresAt = new Date(this.connectionTokenExpiresAt).getTime();
783
- if (!Number.isFinite(expiresAt)) {
784
- return;
785
- }
786
- const refreshAt = expiresAt - 60 * 60 * 1000;
787
- const delay = Math.max(0, refreshAt - Date.now());
788
- this.tokenRefreshTimer = setTimeout(() => {
789
- if (!this.connected || !this.ws || !this.connectionToken) {
790
- return;
791
- }
792
- const refreshMessage = {
793
- type: "token_refresh",
794
- id: crypto.randomUUID(),
795
- timestamp: new Date().toISOString(),
796
- connectionToken: this.connectionToken
797
- };
798
- this.ws.send(JSON.stringify(refreshMessage));
799
- }, delay);
800
- }
801
- clearTokenRefreshTimer() {
802
- if (this.tokenRefreshTimer) {
803
- clearTimeout(this.tokenRefreshTimer);
804
- this.tokenRefreshTimer = null;
805
- }
806
- }
807
- clearPending(reason) {
808
- for (const [requestId, pending] of this.pending.entries()) {
809
- clearTimeout(pending.timeout);
810
- pending.reject(new RemoteCliError("RIG_REMOTE_REQUEST_CANCELLED", `${reason} (request ${requestId}).`, 3, { requestId }));
811
- this.pending.delete(requestId);
812
- }
813
- }
814
- }
815
- function matchesEventFilter(message, expectedType) {
816
- if (!expectedType) {
817
- return true;
818
- }
819
- if (message.type === expectedType) {
820
- return true;
821
- }
822
- if (message.type === "engine_event") {
823
- const eventType = normalizeString(message.event?.type);
824
- return eventType === expectedType;
825
- }
826
- if (message.type === "parallel_event") {
827
- const eventType = normalizeString(message.event?.type);
828
- return eventType === expectedType;
829
- }
830
- return false;
831
- }
832
- function summarizeMessage(message) {
833
- if (message.type === "pong") {
834
- return "pong";
835
- }
836
- if (message.type === "engine_event") {
837
- const eventType = normalizeString(message.event?.type);
838
- return eventType ? `engine_event:${eventType}` : "engine_event";
839
- }
840
- if (message.type === "parallel_event") {
841
- const eventType = normalizeString(message.event?.type);
842
- const orchestrationId = normalizeString(message.orchestrationId);
843
- return orchestrationId ? `parallel_event:${eventType || "unknown"}:${orchestrationId}` : `parallel_event:${eventType || "unknown"}`;
844
- }
845
- return message.type;
846
- }
847
- function migrateManagedRemoteEndpoints(projectRoot, legacyPath = REMOTES_CONFIG_PATH) {
848
- return importLegacyRemoteEndpoints(projectRoot, legacyPath);
849
- }
850
- function doctorManagedRemoteEndpoints(projectRoot) {
851
- return doctorAuthorityRemoteEndpoints(projectRoot);
852
- }
853
- function updateManagedRemoteEndpointInAuthority(projectRoot, input) {
854
- const updated = updateAuthorityRemoteEndpoint(projectRoot, input);
855
- if (!updated)
856
- return null;
857
- return {
858
- id: updated.id,
859
- alias: updated.alias,
860
- host: updated.host,
861
- port: updated.port,
862
- token: updated.token,
863
- addedAt: updated.addedAt,
864
- lastConnected: updated.lastConnectedAt
865
- };
866
- }
867
- function normalizeString(value) {
868
- if (!value) {
869
- return "";
870
- }
871
- return value.trim();
872
- }
873
- function parsePort(value, label) {
874
- if (!value) {
875
- return null;
876
- }
877
- const parsed = Number.parseInt(value, 10);
878
- if (!Number.isFinite(parsed) || parsed <= 0 || parsed > 65535) {
879
- throw new RemoteCliError("RIG_REMOTE_INVALID_PORT", `Invalid port for ${label}: ${value}.`, 2, { label, value });
880
- }
881
- return parsed;
882
- }
883
- function parseIncomingMessage(raw) {
884
- if (typeof raw !== "string") {
885
- return null;
886
- }
887
- try {
888
- const parsed = JSON.parse(raw);
889
- if (!parsed || typeof parsed !== "object" || typeof parsed.type !== "string") {
890
- return null;
891
- }
892
- return parsed;
893
- } catch {
894
- return null;
895
- }
896
- }
897
- function expectType(message, expectedType) {
898
- if (message.type !== expectedType) {
899
- throw new RemoteCliError("RIG_REMOTE_UNEXPECTED_RESPONSE", `Unexpected response type: ${message.type}. Expected ${expectedType}.`, 3, { expectedType, actualType: message.type, message });
900
- }
901
- return message;
902
- }
903
-
904
- // packages/cli/src/commands/_parsers.ts
905
- function parseOptionalPositiveInt(value, option) {
906
- if (!value) {
907
- return;
908
- }
909
- const parsed = Number.parseInt(value, 10);
910
- if (!Number.isFinite(parsed) || parsed <= 0) {
911
- throw new CliError(`Invalid ${option} value: ${value}`, 1, { hint: `Pass a positive integer, e.g. \`${option} 10\`.` });
912
- }
913
- return parsed;
914
- }
915
- function parseRequiredPositiveInt(value, option) {
916
- if (!value) {
917
- throw new CliError(`Missing value for ${option}.`, 1, { hint: `Provide a value after ${option}, e.g. \`${option} 10\`.` });
918
- }
919
- const parsed = Number.parseInt(value, 10);
920
- if (!Number.isFinite(parsed) || parsed <= 0) {
921
- throw new CliError(`Invalid ${option} value: ${value}`, 1, { hint: `Pass a positive integer, e.g. \`${option} 10\`.` });
922
- }
923
- return parsed;
924
- }
925
-
926
- // packages/cli/src/commands/remote.ts
927
- function assertRemoteOperationSuccess(command, response) {
928
- if (!("success" in response)) {
929
- return;
930
- }
931
- if (response.success === false) {
932
- const error = typeof response.error === "string" && response.error || `${command} failed without explicit error detail from remote server.`;
933
- throw new RemoteCliError("RIG_REMOTE_OPERATION_FAILED", error, 3, { command, response: redactSecretFields(response) });
934
- }
935
- }
936
- function redactRemoteEndpoint(endpoint) {
937
- const { token, ...rest } = endpoint;
938
- return {
939
- ...rest,
940
- token: "",
941
- tokenConfigured: token.trim().length > 0
942
- };
943
- }
944
- function isRecord(value) {
945
- return value !== null && typeof value === "object" && !Array.isArray(value);
946
- }
947
- function isSecretKey(key) {
948
- const normalized = key.toLowerCase();
949
- return normalized === "token" || normalized === "authtoken" || normalized === "authorization" || normalized === "connectiontoken" || normalized === "access_token" || normalized === "secret";
950
- }
951
- function redactSecretFields(value) {
952
- if (Array.isArray(value)) {
953
- return value.map((entry) => redactSecretFields(entry));
954
- }
955
- if (!isRecord(value)) {
956
- return value;
957
- }
958
- const redacted = {};
959
- for (const [key, entry] of Object.entries(value)) {
960
- redacted[key] = isSecretKey(key) && typeof entry === "string" ? entry.trim().length > 0 ? "[redacted]" : "" : redactSecretFields(entry);
961
- }
962
- return redacted;
963
- }
964
- async function executeRemote(context, args) {
965
- const [command = "status", ...rest] = args;
966
- if (command === "endpoint" || command === "endpoints") {
967
- const [subcommand = "list", ...subRest] = rest;
968
- switch (subcommand) {
969
- case "list": {
970
- requireNoExtraArgs(subRest, "rig remote endpoint list");
971
- const endpoints = listManagedRemoteEndpoints(undefined, context.projectRoot);
972
- const redactedEndpoints = endpoints.map((endpoint2) => redactRemoteEndpoint(endpoint2));
973
- if (context.outputMode === "text") {
974
- if (endpoints.length === 0) {
975
- console.log("No remote endpoints configured.");
976
- } else {
977
- for (const endpoint2 of endpoints) {
978
- console.log(`- ${endpoint2.alias} \xB7 ${endpoint2.host}:${endpoint2.port}${endpoint2.lastConnected ? ` \xB7 last connected ${endpoint2.lastConnected}` : ""}`);
979
- }
980
- }
981
- }
982
- return { ok: true, group: "remote", command: "endpoint list", details: { endpoints: redactedEndpoints } };
983
- }
984
- case "add": {
985
- let pending2 = subRest;
986
- const alias = takeOption(pending2, "--alias");
987
- pending2 = alias.rest;
988
- const host = takeOption(pending2, "--host");
989
- pending2 = host.rest;
990
- const port = takeOption(pending2, "--port");
991
- pending2 = port.rest;
992
- const token = takeOption(pending2, "--token");
993
- pending2 = token.rest;
994
- requireNoExtraArgs(pending2, "rig remote endpoint add --alias <a> --host <h> --port <n> --token <t>");
995
- if (!alias.value || !host.value || !token.value || !port.value) {
996
- throw new CliError("remote endpoint add requires --alias, --host, --port, and --token.", 1, { hint: "Re-run as `rig remote endpoint add --alias <a> --host <h> --port <n> --token <t>`." });
997
- }
998
- const created = upsertManagedRemoteEndpoint({
999
- alias: alias.value,
1000
- host: host.value,
1001
- port: parseRequiredPositiveInt(port.value, "--port"),
1002
- token: token.value
1003
- }, undefined, context.projectRoot);
1004
- if (context.outputMode === "text") {
1005
- console.log(`Saved remote endpoint ${created.alias} -> ${created.host}:${created.port}`);
1006
- }
1007
- return { ok: true, group: "remote", command: "endpoint add", details: redactRemoteEndpoint(created) };
1008
- }
1009
- case "update": {
1010
- let pending2 = subRest;
1011
- const endpointId = takeOption(pending2, "--id");
1012
- pending2 = endpointId.rest;
1013
- const alias = takeOption(pending2, "--alias");
1014
- pending2 = alias.rest;
1015
- const host = takeOption(pending2, "--host");
1016
- pending2 = host.rest;
1017
- const port = takeOption(pending2, "--port");
1018
- pending2 = port.rest;
1019
- const token = takeOption(pending2, "--token");
1020
- pending2 = token.rest;
1021
- requireNoExtraArgs(pending2, "rig remote endpoint update --id <id> [--alias <a>] [--host <h>] [--port <n>] [--token <t>]");
1022
- if (!endpointId.value && !alias.value) {
1023
- throw new CliError("remote endpoint update requires --id <id> or --alias <a>.", 1, { hint: "List endpoints with `rig remote endpoint list`, then pass --id or --alias." });
1024
- }
1025
- const updated = updateManagedRemoteEndpointInAuthority(context.projectRoot, {
1026
- endpointId: endpointId.value || undefined,
1027
- alias: alias.value || undefined,
1028
- host: host.value || undefined,
1029
- port: port.value ? parseRequiredPositiveInt(port.value, "--port") : undefined,
1030
- token: token.value || undefined
1031
- });
1032
- if (!updated) {
1033
- throw new CliError("Remote endpoint not found.", 2, { hint: "Run `rig remote endpoint list` to see configured endpoints." });
1034
- }
1035
- if (context.outputMode === "text") {
1036
- console.log(`Updated remote endpoint ${updated.alias} -> ${updated.host}:${updated.port}`);
1037
- }
1038
- return { ok: true, group: "remote", command: "endpoint update", details: redactRemoteEndpoint(updated) };
1039
- }
1040
- case "remove": {
1041
- let pending2 = subRest;
1042
- const alias = takeOption(pending2, "--alias");
1043
- pending2 = alias.rest;
1044
- requireNoExtraArgs(pending2, "rig remote endpoint remove --alias <a>");
1045
- if (!alias.value) {
1046
- throw new CliError("remote endpoint remove requires --alias.", 1, { hint: "Run `rig remote endpoint list` to find the alias, then `rig remote endpoint remove --alias <a>`." });
1047
- }
1048
- const removed = removeManagedRemoteEndpoint(alias.value, undefined, context.projectRoot);
1049
- if (!removed) {
1050
- throw new CliError(`Remote endpoint alias not found: ${alias.value}`, 2, { hint: "Run `rig remote endpoint list` to see configured endpoint aliases." });
1051
- }
1052
- if (context.outputMode === "text") {
1053
- console.log(`Removed remote endpoint ${alias.value}`);
1054
- }
1055
- return { ok: true, group: "remote", command: "endpoint remove", details: { alias: alias.value } };
1056
- }
1057
- case "test": {
1058
- let pending2 = subRest;
1059
- const alias = takeOption(pending2, "--alias");
1060
- pending2 = alias.rest;
1061
- requireNoExtraArgs(pending2, "rig remote endpoint test --alias <a>");
1062
- if (!alias.value) {
1063
- throw new CliError("remote endpoint test requires --alias.", 1, { hint: "Run `rig remote endpoint list` to find the alias, then `rig remote endpoint test --alias <a>`." });
1064
- }
1065
- const endpoint2 = resolveRemoteEndpoint({ remoteAlias: alias.value, projectRoot: context.projectRoot });
1066
- const client = new RemoteWsClient(endpoint2);
1067
- const startedAt = Date.now();
1068
- try {
1069
- await client.connect();
1070
- const response = await client.ping();
1071
- const latencyMs = Date.now() - startedAt;
1072
- if (context.outputMode === "text") {
1073
- console.log(`Remote endpoint ${alias.value} responded in ${latencyMs}ms.`);
1074
- }
1075
- return {
1076
- ok: true,
1077
- group: "remote",
1078
- command: "endpoint test",
1079
- details: {
1080
- alias: alias.value,
1081
- host: endpoint2.host,
1082
- port: endpoint2.port,
1083
- latencyMs,
1084
- response: redactSecretFields(response)
1085
- }
1086
- };
1087
- } finally {
1088
- client.disconnect();
1089
- }
1090
- }
1091
- case "migrate": {
1092
- requireNoExtraArgs(subRest, "rig remote endpoint migrate");
1093
- const result = migrateManagedRemoteEndpoints(context.projectRoot);
1094
- if (context.outputMode === "text") {
1095
- console.log(`Imported ${result.imported} endpoint(s) from ${result.sourcePath}${result.skipped > 0 ? `, skipped ${result.skipped}` : ""}.`);
1096
- }
1097
- return { ok: true, group: "remote", command: "endpoint migrate", details: result };
1098
- }
1099
- case "doctor": {
1100
- requireNoExtraArgs(subRest, "rig remote endpoint doctor");
1101
- const result = doctorManagedRemoteEndpoints(context.projectRoot);
1102
- if (context.outputMode === "text") {
1103
- console.log(JSON.stringify(result, null, 2));
1104
- }
1105
- return { ok: true, group: "remote", command: "endpoint doctor", details: result };
1106
- }
1107
- default:
1108
- throw new CliError(`Unknown remote endpoint command: ${subcommand}`, 1, { hint: "Run `rig remote --help` for endpoint commands (list|add|update|remove|test)." });
1109
- }
1110
- }
1111
- let pending = rest;
1112
- const remoteAliasResult = takeOption(pending, "--remote");
1113
- pending = remoteAliasResult.rest;
1114
- const hostResult = takeOption(pending, "--host");
1115
- pending = hostResult.rest;
1116
- const portResult = takeOption(pending, "--port");
1117
- pending = portResult.rest;
1118
- const tokenResult = takeOption(pending, "--token");
1119
- pending = tokenResult.rest;
1120
- const endpoint = resolveRemoteEndpoint({
1121
- host: hostResult.value,
1122
- port: portResult.value,
1123
- token: tokenResult.value,
1124
- remoteAlias: remoteAliasResult.value,
1125
- projectRoot: context.projectRoot
1126
- });
1127
- const remoteMeta = {
1128
- source: endpoint.source,
1129
- alias: endpoint.alias || null,
1130
- host: endpoint.host,
1131
- port: endpoint.port
1132
- };
1133
- const withClient = async (runner) => {
1134
- const client = new RemoteWsClient(endpoint);
1135
- try {
1136
- await client.connect();
1137
- return await runner(client);
1138
- } finally {
1139
- client.disconnect();
1140
- }
1141
- };
1142
- const toDetails = (response) => ({
1143
- command: `remote ${command}`,
1144
- remote: remoteMeta,
1145
- requestId: response.id || null,
1146
- messageType: response.type,
1147
- payload: redactSecretFields(response),
1148
- error: null
1149
- });
1150
- try {
1151
- switch (command) {
1152
- case "test": {
1153
- requireNoExtraArgs(pending, "rig remote test [--remote <alias>] [--host <host>] [--port <n>] [--token <token>]");
1154
- const response = await withClient((client) => client.ping());
1155
- return { ok: true, group: "remote", command, details: toDetails(response) };
1156
- }
1157
- case "status": {
1158
- requireNoExtraArgs(pending, "rig remote status [--remote <alias>] [--host <host>] [--port <n>] [--token <token>]");
1159
- const response = await withClient((client) => client.getState());
1160
- return { ok: true, group: "remote", command, details: toDetails(response) };
1161
- }
1162
- case "tasks": {
1163
- requireNoExtraArgs(pending, "rig remote tasks [--remote <alias>] [--host <host>] [--port <n>] [--token <token>]");
1164
- const response = await withClient((client) => client.getTasks());
1165
- return { ok: true, group: "remote", command, details: toDetails(response) };
1166
- }
1167
- case "watch": {
1168
- let watchPending = pending;
1169
- const secondsResult = takeOption(watchPending, "--seconds");
1170
- watchPending = secondsResult.rest;
1171
- const eventResult = takeOption(watchPending, "--event");
1172
- watchPending = eventResult.rest;
1173
- requireNoExtraArgs(watchPending, "rig remote watch [--seconds <n>] [--event <type>] [--remote <alias>] [--host <host>] [--port <n>] [--token <token>]");
1174
- const seconds = parseOptionalPositiveInt(secondsResult.value, "--seconds");
1175
- const eventFilter = eventResult.value || undefined;
1176
- if (context.outputMode === "json" && !seconds) {
1177
- throw new CliError("--json remote watch requires --seconds <n> to produce bounded output.", 2, { hint: "Re-run as `rig remote watch --seconds 10 --json`." });
1178
- }
1179
- const captured = [];
1180
- let dropped = 0;
1181
- let received = 0;
1182
- let stop = false;
1183
- const onSignal = () => {
1184
- stop = true;
1185
- };
1186
- process.once("SIGINT", onSignal);
1187
- process.once("SIGTERM", onSignal);
1188
- try {
1189
- await withClient(async (client) => {
1190
- client.setEventHandler((event) => {
1191
- if (!matchesEventFilter(event.message, eventFilter)) {
1192
- return;
1193
- }
1194
- received += 1;
1195
- if (context.outputMode === "text") {
1196
- console.log(`[${event.receivedAt}] ${summarizeMessage(event.message)}`);
1197
- } else if (captured.length < 200) {
1198
- captured.push(event.message);
1199
- } else {
1200
- dropped += 1;
1201
- }
1202
- });
1203
- const subscribed = await client.subscribe(eventFilter ? [eventFilter] : []);
1204
- if (!subscribed.success) {
1205
- throw new RemoteCliError("RIG_REMOTE_SUBSCRIBE_FAILED", subscribed.error || "Failed to subscribe to remote events.", 3);
1206
- }
1207
- if (seconds) {
1208
- await Bun.sleep(seconds * 1000);
1209
- return;
1210
- }
1211
- while (!stop) {
1212
- await Bun.sleep(250);
1213
- }
1214
- });
1215
- } finally {
1216
- process.off("SIGINT", onSignal);
1217
- process.off("SIGTERM", onSignal);
1218
- }
1219
- return {
1220
- ok: true,
1221
- group: "remote",
1222
- command,
1223
- details: {
1224
- command: "remote watch",
1225
- remote: remoteMeta,
1226
- messageType: "stream",
1227
- requestId: null,
1228
- payload: context.outputMode === "json" ? captured : null,
1229
- error: null,
1230
- received,
1231
- dropped,
1232
- event: eventFilter || null,
1233
- seconds: seconds || null
1234
- }
1235
- };
1236
- }
1237
- case "pause":
1238
- case "resume":
1239
- case "stop":
1240
- case "continue":
1241
- case "refresh": {
1242
- requireNoExtraArgs(pending, `rig remote ${command} [--remote <alias>] [--host <host>] [--port <n>] [--token <token>]`);
1243
- const response = await withClient(async (client) => {
1244
- switch (command) {
1245
- case "pause":
1246
- return await client.pause();
1247
- case "resume":
1248
- return await client.resume();
1249
- case "stop":
1250
- return await client.interrupt();
1251
- case "continue":
1252
- return await client.continueExecution();
1253
- default:
1254
- return await client.refreshTasks();
1255
- }
1256
- });
1257
- assertRemoteOperationSuccess(command, response);
1258
- return { ok: true, group: "remote", command, details: toDetails(response) };
1259
- }
1260
- case "add-iterations":
1261
- case "remove-iterations": {
1262
- let countPending = pending;
1263
- const countResult = takeOption(countPending, "--count");
1264
- countPending = countResult.rest;
1265
- requireNoExtraArgs(countPending, `rig remote ${command} --count <n> [--remote <alias>] [--host <host>] [--port <n>] [--token <token>]`);
1266
- const count = parseRequiredPositiveInt(countResult.value, "--count");
1267
- const response = await withClient(async (client) => command === "add-iterations" ? await client.addIterations(count) : await client.removeIterations(count));
1268
- assertRemoteOperationSuccess(command, response);
1269
- return { ok: true, group: "remote", command, details: toDetails(response) };
1270
- }
1271
- case "prompt-preview":
1272
- case "iteration-output": {
1273
- let taskPending = pending;
1274
- const taskResult = takeOption(taskPending, "--task");
1275
- taskPending = taskResult.rest;
1276
- requireNoExtraArgs(taskPending, `rig remote ${command} --task <id> [--remote <alias>] [--host <host>] [--port <n>] [--token <token>]`);
1277
- const taskId = requireTask(taskResult.value, `rig remote ${command} --task <id>`);
1278
- const response = await withClient(async (client) => command === "prompt-preview" ? await client.getPromptPreview(taskId) : await client.getIterationOutput(taskId));
1279
- assertRemoteOperationSuccess(command, response);
1280
- return { ok: true, group: "remote", command, details: toDetails(response) };
1281
- }
1282
- case "orchestrate-start": {
1283
- let orchestrationPending = pending;
1284
- const maxWorkersResult = takeOption(orchestrationPending, "--max-workers");
1285
- orchestrationPending = maxWorkersResult.rest;
1286
- const maxIterationsResult = takeOption(orchestrationPending, "--max-iterations");
1287
- orchestrationPending = maxIterationsResult.rest;
1288
- const directMergeResult = takeFlag(orchestrationPending, "--direct-merge");
1289
- orchestrationPending = directMergeResult.rest;
1290
- requireNoExtraArgs(orchestrationPending, "rig remote orchestrate-start [--max-workers <n>] [--max-iterations <n>] [--direct-merge]");
1291
- const response = await withClient((client) => client.startOrchestration({
1292
- maxWorkers: parseOptionalPositiveInt(maxWorkersResult.value, "--max-workers"),
1293
- maxIterations: parseOptionalPositiveInt(maxIterationsResult.value, "--max-iterations"),
1294
- directMerge: directMergeResult.value
1295
- }));
1296
- assertRemoteOperationSuccess(command, response);
1297
- return {
1298
- ok: true,
1299
- group: "remote",
1300
- command,
1301
- details: toDetails(response)
1302
- };
1303
- }
1304
- case "orchestrate-pause":
1305
- case "orchestrate-resume":
1306
- case "orchestrate-stop":
1307
- case "orchestrate-state": {
1308
- let orchestrationPending = pending;
1309
- const idResult = takeOption(orchestrationPending, "--id");
1310
- orchestrationPending = idResult.rest;
1311
- requireNoExtraArgs(orchestrationPending, `rig remote ${command} --id <orch-id> [--remote <alias>] [--host <host>] [--port <n>] [--token <token>]`);
1312
- const orchestrationId = requireTask(idResult.value, `rig remote ${command} --id <orch-id> [--remote <alias>] [--host <host>] [--port <n>] [--token <token>]`);
1313
- const response = await withClient(async (client) => {
1314
- switch (command) {
1315
- case "orchestrate-pause":
1316
- return await client.pauseOrchestration(orchestrationId);
1317
- case "orchestrate-resume":
1318
- return await client.resumeOrchestration(orchestrationId);
1319
- case "orchestrate-stop":
1320
- return await client.stopOrchestration(orchestrationId);
1321
- default:
1322
- return await client.getOrchestrationState(orchestrationId);
1323
- }
1324
- });
1325
- assertRemoteOperationSuccess(command, response);
1326
- return { ok: true, group: "remote", command, details: toDetails(response) };
1327
- }
1328
- default:
1329
- throw new CliError(`Unknown remote command: ${command}`, 1, { hint: "Run `rig remote --help` to list remote commands." });
1330
- }
1331
- } catch (error) {
1332
- if (error instanceof RemoteCliError) {
1333
- throw new CliError(`[${error.code}] ${error.message}`, error.exitCode);
1334
- }
1335
- throw error;
1336
- }
1337
- }
1338
- export {
1339
- executeRemote
1340
- };