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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +18 -19
  2. package/dist/bin/build-rig-binaries.d.ts +2 -0
  3. package/dist/bin/build-rig-binaries.js +22 -10
  4. package/dist/bin/rig.d.ts +72 -0
  5. package/dist/bin/rig.js +15637 -7344
  6. package/dist/config/rig-default-config.yml +5 -0
  7. package/dist/src/app/drone-ui.d.ts +34 -0
  8. package/dist/src/app/drone-ui.js +278 -0
  9. package/dist/src/commands/_async-ui.d.ts +10 -0
  10. package/dist/src/commands/_async-ui.js +121 -0
  11. package/dist/src/commands/_cli-format.d.ts +56 -0
  12. package/dist/src/commands/_cli-format.js +319 -0
  13. package/dist/src/commands/_connection-state.d.ts +54 -0
  14. package/dist/src/commands/_connection-state.js +75 -11
  15. package/dist/src/commands/_doctor-checks.d.ts +46 -0
  16. package/dist/src/commands/_doctor-checks.js +100 -267
  17. package/dist/src/commands/_help-catalog.d.ts +51 -0
  18. package/dist/src/commands/_help-catalog.js +502 -0
  19. package/dist/src/commands/_inprocess-services.d.ts +33 -0
  20. package/dist/src/commands/_inprocess-services.js +102 -0
  21. package/dist/src/commands/_json-output.d.ts +11 -0
  22. package/dist/src/commands/_json-output.js +60 -0
  23. package/dist/src/commands/_lazy-reconcile.d.ts +34 -0
  24. package/dist/src/commands/_lazy-reconcile.js +102 -0
  25. package/dist/src/commands/_parsers.d.ts +15 -0
  26. package/dist/src/commands/_parsers.js +18 -11
  27. package/dist/src/commands/_paths.d.ts +11 -0
  28. package/dist/src/commands/_paths.js +1 -1
  29. package/dist/src/commands/_pi-frontend.d.ts +35 -0
  30. package/dist/src/commands/_pi-frontend.js +64 -0
  31. package/dist/src/commands/_pi-install.d.ts +42 -0
  32. package/dist/src/commands/_pi-install.js +19 -36
  33. package/dist/src/commands/_policy.d.ts +8 -0
  34. package/dist/src/commands/_policy.js +67 -19
  35. package/dist/src/commands/_probes.d.ts +1 -0
  36. package/dist/src/commands/_run-bridge.d.ts +114 -0
  37. package/dist/src/commands/_run-bridge.js +387 -0
  38. package/dist/src/commands/_run-diagnostics.d.ts +9 -0
  39. package/dist/src/commands/_run-diagnostics.js +51 -0
  40. package/dist/src/commands/_run-driver-helpers.d.ts +26 -0
  41. package/dist/src/commands/_run-driver-helpers.js +79 -230
  42. package/dist/src/commands/_run-projection.d.ts +50 -0
  43. package/dist/src/commands/_run-projection.js +349 -0
  44. package/dist/src/commands/_run-subcommands.d.ts +3 -0
  45. package/dist/src/commands/_run-subcommands.js +31 -0
  46. package/dist/src/commands/_spinner.d.ts +25 -0
  47. package/dist/src/commands/_spinner.js +65 -0
  48. package/dist/src/commands/agent.d.ts +3 -0
  49. package/dist/src/commands/agent.js +8575 -236
  50. package/dist/src/commands/dist.d.ts +28 -0
  51. package/dist/src/commands/dist.js +44 -29
  52. package/dist/src/commands/doctor.d.ts +3 -0
  53. package/dist/src/commands/doctor.js +219 -268
  54. package/dist/src/commands/github.d.ts +3 -0
  55. package/dist/src/commands/github.js +236 -188
  56. package/dist/src/commands/inbox.d.ts +28 -0
  57. package/dist/src/commands/inbox.js +530 -111
  58. package/dist/src/commands/init.d.ts +64 -0
  59. package/dist/src/commands/init.js +912 -705
  60. package/dist/src/commands/inspect.d.ts +20 -0
  61. package/dist/src/commands/inspect.js +709 -119
  62. package/dist/src/commands/pi.d.ts +3 -0
  63. package/dist/src/commands/pi.js +177 -0
  64. package/dist/src/commands/plugin.d.ts +16 -0
  65. package/dist/src/commands/plugin.js +576 -29
  66. package/dist/src/commands/profile-and-review.d.ts +4 -0
  67. package/dist/src/commands/profile-and-review.js +112 -67
  68. package/dist/src/commands/queue.d.ts +3 -0
  69. package/dist/src/commands/queue.js +20 -20
  70. package/dist/src/commands/remote.d.ts +3 -0
  71. package/dist/src/commands/remote.js +880 -50
  72. package/dist/src/commands/repo-git-harness.d.ts +5 -0
  73. package/dist/src/commands/repo-git-harness.js +78 -28
  74. package/dist/src/commands/run.d.ts +21 -0
  75. package/dist/src/commands/run.js +17701 -661
  76. package/dist/src/commands/server.d.ts +3 -0
  77. package/dist/src/commands/server.js +166 -303
  78. package/dist/src/commands/setup.d.ts +16 -0
  79. package/dist/src/commands/setup.js +244 -299
  80. package/dist/src/commands/stats.d.ts +15 -0
  81. package/dist/src/commands/stats.js +979 -0
  82. package/dist/src/commands/task-run-driver.d.ts +94 -0
  83. package/dist/src/commands/task-run-driver.js +116 -1961
  84. package/dist/src/commands/task.d.ts +35 -0
  85. package/dist/src/commands/task.js +676 -1201
  86. package/dist/src/commands/test.d.ts +3 -0
  87. package/dist/src/commands/test.js +15 -8
  88. package/dist/src/commands/triage.d.ts +11 -0
  89. package/dist/src/commands/triage.js +227 -0
  90. package/dist/src/commands/workspace.d.ts +3 -0
  91. package/dist/src/commands/workspace.js +18 -11
  92. package/dist/src/commands.d.ts +13 -0
  93. package/dist/src/commands.js +16792 -8055
  94. package/dist/src/index.d.ts +4 -0
  95. package/dist/src/index.js +16862 -8450
  96. package/dist/src/launcher.d.ts +61 -0
  97. package/dist/src/launcher.js +81 -13
  98. package/dist/src/operator-cli.d.ts +2 -0
  99. package/dist/src/operator-cli.js +17837 -0
  100. package/dist/src/operator-entry.d.ts +1 -0
  101. package/dist/src/operator-entry.js +3 -0
  102. package/dist/src/runner.d.ts +47 -0
  103. package/dist/src/runner.js +16 -22
  104. package/dist/src/withMutedConsole.d.ts +2 -0
  105. package/package.json +21 -8
  106. package/dist/src/commands/_authority-runs.js +0 -111
  107. package/dist/src/commands/_operator-view.js +0 -340
  108. package/dist/src/commands/_preflight.js +0 -478
  109. package/dist/src/commands/_server-client.js +0 -382
  110. package/dist/src/commands/_snapshot-upload.js +0 -331
  111. package/dist/src/commands/_task-picker.js +0 -48
  112. package/dist/src/commands/browser.js +0 -890
  113. package/dist/src/commands/connect.js +0 -180
  114. package/dist/src/commands/inspector.js +0 -256
  115. package/dist/src/commands/task-report-bug.js +0 -1083
  116. package/dist/src/report-bug.js +0 -260
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ // packages/cli/src/operator-entry.ts
3
+ throw new Error("@rig/cli/operator-entry is a retired legacy AuthorityRunRecord operator surface. Run the `rig` CLI instead; it launches upstream OMP with the bundled Rig extension.");
@@ -0,0 +1,47 @@
1
+ import { CliError as RuntimeCliError } from "@rig/runtime/control-plane/errors";
2
+ import type { PolicyMode } from "@rig/runtime/control-plane/runtime/guard-types";
3
+ import type { RunnerContext } from "@rig/runtime/control-plane/runtime/runner-context";
4
+ import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
5
+ import type { CommandExecutionResult, OutputMode } from "@rig/runtime/control-plane/runtime/types";
6
+ export type { RunnerContext } from "@rig/runtime/control-plane/runtime/runner-context";
7
+ /**
8
+ * CLI-side error with an optional remediation hint. The hint is rendered on
9
+ * its own line as `Next: <hint>` (and carried in the --json error payload),
10
+ * so every failure names the next command to run. Extends the runtime
11
+ * CliError so `instanceof` checks against either class keep working.
12
+ */
13
+ export declare class CliError extends RuntimeCliError {
14
+ readonly hint?: string;
15
+ constructor(message: string, exitCode?: number, options?: {
16
+ readonly hint?: string;
17
+ });
18
+ }
19
+ export declare function withProjectRoot(projectRoot: string): void;
20
+ export declare function formatCommand(parts: string[]): string;
21
+ type AgentShellBuild = typeof buildBinary;
22
+ type AgentShellMaterializationOptions = {
23
+ readonly env?: Record<string, string | undefined>;
24
+ readonly cwd?: string;
25
+ readonly moduleDir?: string;
26
+ readonly build?: AgentShellBuild;
27
+ };
28
+ export declare function resolveAgentMaterializationSourceRoot(projectRoot: string, options?: AgentShellMaterializationOptions): string;
29
+ export declare function ensureAgentShellBinary(projectRoot: string, options?: AgentShellMaterializationOptions): Promise<string>;
30
+ export declare function initializeRuntime(options: {
31
+ projectRoot: string;
32
+ dryRun: boolean;
33
+ outputMode: OutputMode;
34
+ runId?: string;
35
+ policyMode?: PolicyMode;
36
+ }): Promise<RunnerContext>;
37
+ export declare function runCommand(context: RunnerContext, parts: string[]): Promise<CommandExecutionResult>;
38
+ export declare function takeFlag(args: string[], flag: string): {
39
+ value: boolean;
40
+ rest: string[];
41
+ };
42
+ export declare function takeOption(args: string[], option: string): {
43
+ value: string | undefined;
44
+ rest: string[];
45
+ };
46
+ export declare function requireNoExtraArgs(args: string[], usage: string): void;
47
+ export declare function requireTask(taskId: string | undefined, usage: string): string;
@@ -4,12 +4,19 @@ var {$ } = globalThis.Bun;
4
4
  import { existsSync, mkdirSync } from "fs";
5
5
  import { resolve } from "path";
6
6
  import { EventBus } from "@rig/runtime/control-plane/runtime/events";
7
- import { CliError } from "@rig/runtime/control-plane/errors";
7
+ import { CliError as RuntimeCliError } from "@rig/runtime/control-plane/errors";
8
8
  import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
9
- import { PluginManager } from "@rig/runtime/control-plane/runtime/plugins";
10
- import { loadRuntimeContextFromEnv } from "@rig/runtime/control-plane/runtime/context";
11
9
  import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
12
- import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
10
+
11
+ class CliError extends RuntimeCliError {
12
+ hint;
13
+ constructor(message, exitCode = 1, options = {}) {
14
+ super(message, exitCode);
15
+ if (options.hint?.trim()) {
16
+ this.hint = options.hint.trim();
17
+ }
18
+ }
19
+ }
13
20
  function withProjectRoot(projectRoot) {
14
21
  $.cwd(projectRoot);
15
22
  }
@@ -61,13 +68,6 @@ async function ensureAgentShellBinary(projectRoot, options = {}) {
61
68
  }
62
69
  async function initializeRuntime(options) {
63
70
  const eventBus = new EventBus({ projectRoot: options.projectRoot, runId: options.runId });
64
- const runtimeContext = loadRuntimeContextFromEnv() ?? undefined;
65
- const plugins = await PluginManager.load({
66
- projectRoot: options.projectRoot,
67
- runId: eventBus.getRunId(),
68
- eventBus,
69
- runtimeContext
70
- });
71
71
  const context = {
72
72
  projectRoot: options.projectRoot,
73
73
  dryRun: options.dryRun,
@@ -75,10 +75,8 @@ async function initializeRuntime(options) {
75
75
  runId: eventBus.getRunId(),
76
76
  policyMode: options.policyMode,
77
77
  eventBus,
78
- plugins,
79
78
  emitEvent: async (type, payload) => {
80
- const event = await eventBus.emit(type, payload);
81
- await plugins.onEvent(event);
79
+ await eventBus.emit(type, payload);
82
80
  }
83
81
  };
84
82
  context.runCommand = async (parts) => runCommand(context, parts);
@@ -87,8 +85,7 @@ async function initializeRuntime(options) {
87
85
  outputMode: context.outputMode,
88
86
  dryRun: context.dryRun,
89
87
  policyMode: context.policyMode ?? loadPolicy(options.projectRoot).mode,
90
- policyFile: resolve(options.projectRoot, "rig/policy/policy.json"),
91
- plugins: context.plugins.list()
88
+ policyFile: resolve(options.projectRoot, "rig/policy/policy.json")
92
89
  });
93
90
  return context;
94
91
  }
@@ -137,9 +134,8 @@ async function runCommand(context, parts) {
137
134
  matchedRuleIds: guardDecision.matchedRules.map((r) => r.id),
138
135
  mode: effectiveMode
139
136
  });
140
- throw new CliError(`Policy blocked command: ${formatted}`, 126);
137
+ throw new CliError(`Policy blocked command: ${formatted}`, 126, { hint: "Review rig/policy/policy.json, or re-run with `--policy-mode observe` to log instead of block." });
141
138
  }
142
- await context.plugins.beforeCommand({ command: commandWithEnv, formattedCommand: formatted });
143
139
  const startedAt = new Date;
144
140
  await context.emitEvent("command.started", {
145
141
  command: commandWithEnv,
@@ -159,7 +155,6 @@ async function runCommand(context, parts) {
159
155
  if (context.outputMode === "text") {
160
156
  console.log(`$ ${formatted}`);
161
157
  }
162
- await context.plugins.afterCommand(dryResult);
163
158
  await context.emitEvent("command.finished", {
164
159
  ...dryResult,
165
160
  dryRun: true
@@ -199,7 +194,6 @@ async function runCommand(context, parts) {
199
194
  stdout: context.outputMode === "json" ? stdout : undefined,
200
195
  stderr: context.outputMode === "json" ? stderr : undefined
201
196
  };
202
- await context.plugins.afterCommand(result);
203
197
  if (exitCode !== 0) {
204
198
  await context.emitEvent("command.failed", {
205
199
  ...result
@@ -233,7 +227,7 @@ function takeOption(args, option) {
233
227
  if (current === option) {
234
228
  const next = args[index + 1];
235
229
  if (!next || next.startsWith("-")) {
236
- throw new CliError(`Missing value for ${option}`);
230
+ throw new CliError(`Missing value for ${option}`, 1, { hint: `Provide a value after ${option}, e.g. \`${option} <value>\`.` });
237
231
  }
238
232
  value = next;
239
233
  index += 1;
@@ -269,5 +263,5 @@ export {
269
263
  initializeRuntime,
270
264
  formatCommand,
271
265
  ensureAgentShellBinary,
272
- CliError2 as CliError
266
+ CliError
273
267
  };
@@ -0,0 +1,2 @@
1
+ export declare function withMutedConsole<T>(mute: boolean, fn: () => Promise<T>): Promise<T>;
2
+ export declare function withMutedConsole<T>(mute: boolean, fn: () => T): T;
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@h-rig/cli",
3
- "version": "0.0.6-alpha.9",
3
+ "version": "0.0.6-alpha.91",
4
4
  "type": "module",
5
- "description": "Rig package",
5
+ "description": "Rig CLI launcher for upstream OMP collab; legacy operator entrypoints are retired.",
6
6
  "license": "UNLICENSED",
7
7
  "files": [
8
8
  "dist",
@@ -10,6 +10,7 @@
10
10
  ],
11
11
  "exports": {
12
12
  ".": {
13
+ "types": "./dist/src/index.d.ts",
13
14
  "import": "./dist/src/index.js"
14
15
  }
15
16
  },
@@ -18,15 +19,27 @@
18
19
  },
19
20
  "main": "./dist/src/index.js",
20
21
  "module": "./dist/src/index.js",
22
+ "types": "./dist/src/index.d.ts",
21
23
  "bin": {
22
24
  "rig": "./dist/bin/rig.js"
23
25
  },
24
26
  "dependencies": {
25
- "@clack/prompts": "^1.2.0",
26
- "@rig/core": "npm:@h-rig/core@0.0.6-alpha.9",
27
- "@rig/runtime": "npm:@h-rig/runtime@0.0.6-alpha.9",
28
- "@rig/client": "npm:@h-rig/client@0.0.6-alpha.9",
29
- "@rig/server": "npm:@h-rig/server@0.0.6-alpha.9",
30
- "picocolors": "^1.1.1"
27
+ "@oh-my-pi/omp-stats": "16.0.4",
28
+ "@oh-my-pi/pi-coding-agent": "16.0.4",
29
+ "@oh-my-pi/pi-tui": "16.0.4",
30
+ "@oh-my-pi/pi-utils": "16.0.4",
31
+ "@rig/client": "npm:@h-rig/client@0.0.6-alpha.91",
32
+ "@rig/contracts": "npm:@h-rig/contracts@0.0.6-alpha.91",
33
+ "@rig/core": "npm:@h-rig/core@0.0.6-alpha.91",
34
+ "@rig/relay-registry": "0.0.6-alpha.91",
35
+ "@rig/rig-extension": "npm:@h-rig/rig-extension@0.0.6-alpha.91",
36
+ "@rig/rig-host": "npm:@h-rig/rig-host@0.0.6-alpha.91",
37
+ "@rig/runtime": "npm:@h-rig/runtime@0.0.6-alpha.91",
38
+ "@rig/shared": "npm:@h-rig/shared@0.0.6-alpha.91",
39
+ "@rig/standard-plugin": "npm:@h-rig/standard-plugin@0.0.6-alpha.91",
40
+ "@xterm/headless": "^6.0.0",
41
+ "effect": "4.0.0-beta.78",
42
+ "picocolors": "^1.1.1",
43
+ "react": "^19.2.0"
31
44
  }
32
45
  }
@@ -1,111 +0,0 @@
1
- // @bun
2
- // packages/cli/src/commands/_authority-runs.ts
3
- import { existsSync } from "fs";
4
- import { resolve } from "path";
5
- import {
6
- readAuthorityRun,
7
- readJsonlFile,
8
- resolveAuthorityRunDir,
9
- writeJsonFile
10
- } from "@rig/runtime/control-plane/authority-files";
11
-
12
- // packages/cli/src/commands/_paths.ts
13
- import { resolveMonorepoRoot } from "@rig/runtime/control-plane/native/utils";
14
- function resolveControlPlaneMonorepoRoot(projectRoot) {
15
- return resolveMonorepoRoot(projectRoot);
16
- }
17
-
18
- // packages/cli/src/commands/_authority-runs.ts
19
- var RIG_WORKSPACE_ID = "rig-local-workspace";
20
- function normalizeRuntimeAdapter(value) {
21
- const normalized = value?.trim().toLowerCase();
22
- if (!normalized) {
23
- return "pi";
24
- }
25
- if (normalized === "codex" || normalized === "codex-cli" || normalized === "codex-app-server" || normalized === "gpt-codex") {
26
- return "codex";
27
- }
28
- if (normalized === "pi" || normalized === "rig-pi" || normalized === "@rig/pi") {
29
- return "pi";
30
- }
31
- return "claude-code";
32
- }
33
- function readLatestBeadRecord(projectRoot, taskId) {
34
- const issuesPath = resolve(resolveControlPlaneMonorepoRoot(projectRoot), ".beads", "issues.jsonl");
35
- if (!existsSync(issuesPath)) {
36
- return null;
37
- }
38
- let latest = null;
39
- for (const issue of readJsonlFile(issuesPath)) {
40
- if (!issue || typeof issue !== "object") {
41
- continue;
42
- }
43
- const record = issue;
44
- if (record.id === taskId) {
45
- latest = record;
46
- }
47
- }
48
- return latest;
49
- }
50
- function resolveTaskTitleForAuthorityRun(projectRoot, taskId) {
51
- try {
52
- const record = readLatestBeadRecord(projectRoot, taskId);
53
- const title = record && typeof record.title === "string" ? record.title.trim() : "";
54
- if (title) {
55
- return title;
56
- }
57
- } catch {}
58
- return null;
59
- }
60
- function upsertAgentAuthorityRun(projectRoot, input) {
61
- const current = readAuthorityRun(projectRoot, input.runId);
62
- const existing = current;
63
- const createdAt = existing?.createdAt ?? input.createdAt;
64
- const runtimeMode = typeof existing?.runtimeMode === "string" ? existing.runtimeMode : "full-access";
65
- const interactionMode = typeof existing?.interactionMode === "string" ? existing.interactionMode : "default";
66
- const runMode = typeof existing?.runMode === "string" ? existing.runMode : "autonomous";
67
- const runtimeAdapter = normalizeRuntimeAdapter(input.runtimeAdapter ?? existing?.runtimeAdapter ?? "claude-code");
68
- const title = resolveTaskTitleForAuthorityRun(projectRoot, input.taskId) ?? input.taskId;
69
- const next = {
70
- ...existing ?? {},
71
- runId: input.runId,
72
- projectRoot,
73
- workspaceId: existing?.workspaceId ?? RIG_WORKSPACE_ID,
74
- taskId: input.taskId,
75
- threadId: existing?.threadId ?? null,
76
- mode: "local",
77
- runtimeAdapter,
78
- status: input.status,
79
- createdAt,
80
- startedAt: input.startedAt ?? existing?.startedAt ?? null,
81
- completedAt: input.completedAt ?? existing?.completedAt ?? null,
82
- endpointId: existing?.endpointId ?? null,
83
- hostId: existing?.hostId ?? null,
84
- worktreePath: input.worktreePath ?? existing?.worktreePath ?? null,
85
- artifactRoot: input.artifactRoot ?? existing?.artifactRoot ?? null,
86
- logRoot: input.logRoot ?? existing?.logRoot ?? null,
87
- sessionPath: input.sessionPath ?? existing?.sessionPath ?? null,
88
- sessionLogPath: input.sessionLogPath ?? existing?.sessionLogPath ?? null,
89
- pid: input.pid ?? existing?.pid ?? null,
90
- updatedAt: input.createdAt,
91
- title,
92
- model: typeof existing?.model === "string" ? existing.model : null,
93
- runtimeMode,
94
- interactionMode,
95
- runMode,
96
- initialPrompt: typeof existing?.initialPrompt === "string" ? existing.initialPrompt : null
97
- };
98
- if (input.errorText !== undefined) {
99
- next.errorText = input.errorText;
100
- } else if ("errorText" in next) {
101
- delete next.errorText;
102
- }
103
- writeJsonFile(resolve(resolveAuthorityRunDir(projectRoot, input.runId), "run.json"), next);
104
- return next;
105
- }
106
- export {
107
- upsertAgentAuthorityRun,
108
- readLatestBeadRecord,
109
- normalizeRuntimeAdapter,
110
- RIG_WORKSPACE_ID
111
- };
@@ -1,340 +0,0 @@
1
- // @bun
2
- // packages/cli/src/commands/_operator-view.ts
3
- import { createInterface } from "readline";
4
-
5
- // packages/cli/src/commands/_server-client.ts
6
- import { spawnSync } from "child_process";
7
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
8
- import { resolve as resolve2 } from "path";
9
-
10
- // packages/cli/src/runner.ts
11
- import { EventBus } from "@rig/runtime/control-plane/runtime/events";
12
- import { CliError } from "@rig/runtime/control-plane/errors";
13
- import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
14
- import { PluginManager } from "@rig/runtime/control-plane/runtime/plugins";
15
- import { loadRuntimeContextFromEnv } from "@rig/runtime/control-plane/runtime/context";
16
- import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
17
- import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
18
-
19
- // packages/cli/src/commands/_server-client.ts
20
- import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
21
-
22
- // packages/cli/src/commands/_connection-state.ts
23
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
24
- import { homedir } from "os";
25
- import { dirname, resolve } from "path";
26
- function resolveGlobalConnectionsPath(env = process.env) {
27
- const explicit = env.RIG_CONNECTIONS_FILE?.trim();
28
- if (explicit)
29
- return resolve(explicit);
30
- const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
31
- if (stateDir)
32
- return resolve(stateDir, "connections.json");
33
- return resolve(homedir(), ".rig", "connections.json");
34
- }
35
- function resolveRepoConnectionPath(projectRoot) {
36
- return resolve(projectRoot, ".rig", "state", "connection.json");
37
- }
38
- function readJsonFile(path) {
39
- if (!existsSync(path))
40
- return null;
41
- try {
42
- return JSON.parse(readFileSync(path, "utf8"));
43
- } catch (error) {
44
- throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
45
- }
46
- }
47
- function normalizeConnection(value) {
48
- if (!value || typeof value !== "object" || Array.isArray(value))
49
- return null;
50
- const record = value;
51
- if (record.kind === "local")
52
- return { kind: "local", mode: "auto" };
53
- if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
54
- const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
55
- return { kind: "remote", baseUrl };
56
- }
57
- return null;
58
- }
59
- function readGlobalConnections(options = {}) {
60
- const path = resolveGlobalConnectionsPath(options.env ?? process.env);
61
- const payload = readJsonFile(path);
62
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
63
- return { connections: {} };
64
- }
65
- const rawConnections = payload.connections;
66
- const connections = {};
67
- if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
68
- for (const [alias, raw] of Object.entries(rawConnections)) {
69
- const connection = normalizeConnection(raw);
70
- if (connection)
71
- connections[alias] = connection;
72
- }
73
- }
74
- return { connections };
75
- }
76
- function readRepoConnection(projectRoot) {
77
- const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
78
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
79
- return null;
80
- const record = payload;
81
- const selected = typeof record.selected === "string" ? record.selected.trim() : "";
82
- if (!selected)
83
- return null;
84
- return {
85
- selected,
86
- project: typeof record.project === "string" ? record.project : undefined,
87
- linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined
88
- };
89
- }
90
- function resolveSelectedConnection(projectRoot, options = {}) {
91
- const repo = readRepoConnection(projectRoot);
92
- if (!repo)
93
- return null;
94
- if (repo.selected === "local")
95
- return { alias: "local", connection: { kind: "local", mode: "auto" } };
96
- const global = readGlobalConnections(options);
97
- const connection = global.connections[repo.selected];
98
- if (!connection) {
99
- throw new CliError2(`Selected Rig connection "${repo.selected}" was not found. Run \`rig connect list\` or \`rig connect use local\`.`, 1);
100
- }
101
- return { alias: repo.selected, connection };
102
- }
103
-
104
- // packages/cli/src/commands/_server-client.ts
105
- var cachedGitHubBearerToken;
106
- function cleanToken(value) {
107
- const trimmed = value?.trim();
108
- return trimmed ? trimmed : null;
109
- }
110
- function readPrivateRemoteSessionToken(projectRoot) {
111
- const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
112
- if (!existsSync2(path))
113
- return null;
114
- try {
115
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
116
- return cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined);
117
- } catch {
118
- return null;
119
- }
120
- }
121
- function readGitHubBearerTokenForRemote(projectRoot) {
122
- if (cachedGitHubBearerToken !== undefined)
123
- return cachedGitHubBearerToken;
124
- const privateSession = readPrivateRemoteSessionToken(projectRoot);
125
- if (privateSession) {
126
- cachedGitHubBearerToken = privateSession;
127
- return cachedGitHubBearerToken;
128
- }
129
- const envToken = cleanToken(process.env.RIG_GITHUB_TOKEN) ?? cleanToken(process.env.GITHUB_TOKEN) ?? cleanToken(process.env.GH_TOKEN);
130
- if (envToken) {
131
- cachedGitHubBearerToken = envToken;
132
- return cachedGitHubBearerToken;
133
- }
134
- const result = spawnSync("gh", ["auth", "token"], {
135
- encoding: "utf8",
136
- timeout: 5000,
137
- stdio: ["ignore", "pipe", "ignore"]
138
- });
139
- cachedGitHubBearerToken = result.status === 0 ? cleanToken(result.stdout) : null;
140
- return cachedGitHubBearerToken;
141
- }
142
- async function ensureServerForCli(projectRoot) {
143
- try {
144
- const selected = resolveSelectedConnection(projectRoot);
145
- if (selected?.connection.kind === "remote") {
146
- return {
147
- baseUrl: selected.connection.baseUrl,
148
- authToken: readGitHubBearerTokenForRemote(projectRoot),
149
- connectionKind: "remote"
150
- };
151
- }
152
- const connection = await ensureLocalRigServerConnection(projectRoot);
153
- return {
154
- baseUrl: connection.baseUrl,
155
- authToken: connection.authToken,
156
- connectionKind: "local"
157
- };
158
- } catch (error) {
159
- if (error instanceof Error) {
160
- throw new CliError2(error.message, 1);
161
- }
162
- throw error;
163
- }
164
- }
165
- function mergeHeaders(headers, authToken) {
166
- const merged = new Headers(headers);
167
- if (authToken) {
168
- merged.set("authorization", `Bearer ${authToken}`);
169
- }
170
- return merged;
171
- }
172
- function diagnosticMessage(payload) {
173
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
174
- return null;
175
- const record = payload;
176
- const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
177
- const messages = diagnostics.flatMap((entry) => {
178
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
179
- return [];
180
- const diagnostic = entry;
181
- const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
182
- const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
183
- return message ? [`${kind}: ${message}`] : [];
184
- });
185
- return messages.length > 0 ? messages.join("; ") : null;
186
- }
187
- async function requestServerJson(context, pathname, init = {}) {
188
- const server = await ensureServerForCli(context.projectRoot);
189
- const response = await fetch(`${server.baseUrl}${pathname}`, {
190
- ...init,
191
- headers: mergeHeaders(init.headers, server.authToken)
192
- });
193
- const text = await response.text();
194
- const payload = text.trim().length > 0 ? (() => {
195
- try {
196
- return JSON.parse(text);
197
- } catch {
198
- return null;
199
- }
200
- })() : null;
201
- if (!response.ok) {
202
- const diagnostics = diagnosticMessage(payload);
203
- const detail = diagnostics ?? (text || response.statusText);
204
- throw new CliError2(`Rig server request failed (${response.status}): ${detail}`, 1);
205
- }
206
- return payload;
207
- }
208
- async function getRunDetailsViaServer(context, runId) {
209
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}`);
210
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
211
- }
212
- async function getRunLogsViaServer(context, runId, options = {}) {
213
- const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/logs`);
214
- if (options.limit !== undefined)
215
- url.searchParams.set("limit", String(options.limit));
216
- if (options.cursor)
217
- url.searchParams.set("cursor", options.cursor);
218
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
219
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
220
- }
221
- async function stopRunViaServer(context, runId) {
222
- const payload = await requestServerJson(context, "/api/runs/stop", {
223
- method: "POST",
224
- headers: { "content-type": "application/json" },
225
- body: JSON.stringify({ runId })
226
- });
227
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true, runId };
228
- }
229
- async function steerRunViaServer(context, runId, message) {
230
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/steer`, {
231
- method: "POST",
232
- headers: { "content-type": "application/json" },
233
- body: JSON.stringify({ message })
234
- });
235
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
236
- }
237
-
238
- // packages/cli/src/commands/_operator-view.ts
239
- var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
240
- var CANONICAL_STAGES = [
241
- "Connect",
242
- "GitHub/task sync",
243
- "Prepare workspace",
244
- "Launch Pi",
245
- "Plan",
246
- "Implement",
247
- "Validate",
248
- "Commit",
249
- "Open PR",
250
- "Review/CI",
251
- "Merge",
252
- "Complete"
253
- ];
254
- function renderOperatorSnapshot(snapshot) {
255
- const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
256
- const runId = String(run.runId ?? run.id ?? "run");
257
- const status = String(run.status ?? "unknown");
258
- const logs = snapshot.logs ?? [];
259
- const stageLines = CANONICAL_STAGES.flatMap((stage) => {
260
- const match = logs.find((log) => String(log.title ?? "").toLowerCase() === stage.toLowerCase() || String(log.stage ?? "").toLowerCase() === stage.toLowerCase());
261
- return match ? [`${stage}: ${String(match.status ?? status)}`] : [];
262
- });
263
- return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
264
- `);
265
- }
266
- function runStatusFromPayload(payload) {
267
- const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
268
- return String(run.status ?? "unknown").toLowerCase();
269
- }
270
- async function applyOperatorCommand(context, input, deps = {}) {
271
- const line = input.line.trim();
272
- if (!line)
273
- return { action: "ignored" };
274
- if (line === "/detach" || line === "/quit" || line === "/q") {
275
- return { action: "detach", message: "Detached from run." };
276
- }
277
- if (line === "/stop") {
278
- await (deps.stop ?? stopRunViaServer)(context, input.runId);
279
- return { action: "stopped", message: "Stop requested." };
280
- }
281
- const userMessage = line.startsWith("/user ") ? line.slice("/user ".length).trim() : line;
282
- if (!userMessage)
283
- return { action: "ignored" };
284
- await (deps.steer ?? steerRunViaServer)(context, input.runId, userMessage);
285
- return { action: "continue", message: "Steering message queued." };
286
- }
287
- async function readOperatorSnapshot(context, runId) {
288
- const run = await getRunDetailsViaServer(context, runId);
289
- const logsPage = await getRunLogsViaServer(context, runId, { limit: 100 });
290
- const entries = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
291
- return { run, logs: entries, rendered: renderOperatorSnapshot({ run, logs: entries }) };
292
- }
293
- async function attachRunOperatorView(context, input) {
294
- let steered = false;
295
- if (input.message?.trim()) {
296
- await steerRunViaServer(context, input.runId, input.message.trim());
297
- steered = true;
298
- }
299
- let snapshot = await readOperatorSnapshot(context, input.runId);
300
- if (context.outputMode === "text") {
301
- console.log(snapshot.rendered);
302
- if (steered)
303
- console.log("Steering message queued.");
304
- }
305
- let detached = false;
306
- let rl = null;
307
- if (input.follow && !input.once && context.outputMode === "text") {
308
- if (input.interactive !== false && process.stdin.isTTY) {
309
- console.log("Controls: /user <message>, /stop, /detach");
310
- rl = createInterface({ input: process.stdin, output: process.stdout, terminal: false });
311
- rl.on("line", (line) => {
312
- applyOperatorCommand(context, { runId: input.runId, line }).then((result) => {
313
- if (result.message)
314
- console.log(result.message);
315
- if (result.action === "detach" || result.action === "stopped") {
316
- detached = true;
317
- rl?.close();
318
- }
319
- }).catch((error) => console.log(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
320
- });
321
- }
322
- let lastRendered = snapshot.rendered;
323
- const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
324
- while (!detached && !TERMINAL_RUN_STATUSES.has(runStatusFromPayload(snapshot.run))) {
325
- await Bun.sleep(pollMs);
326
- snapshot = await readOperatorSnapshot(context, input.runId);
327
- if (snapshot.rendered !== lastRendered) {
328
- console.log(snapshot.rendered);
329
- lastRendered = snapshot.rendered;
330
- }
331
- }
332
- rl?.close();
333
- }
334
- return { ...snapshot, steered, detached };
335
- }
336
- export {
337
- renderOperatorSnapshot,
338
- attachRunOperatorView,
339
- applyOperatorCommand
340
- };