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

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 (120) 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 +15742 -7203
  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/_config-env.d.ts +18 -0
  14. package/dist/src/commands/_config-env.js +22 -0
  15. package/dist/src/commands/_connection-state.d.ts +54 -0
  16. package/dist/src/commands/_connection-state.js +75 -11
  17. package/dist/src/commands/_doctor-checks.d.ts +46 -0
  18. package/dist/src/commands/_doctor-checks.js +95 -244
  19. package/dist/src/commands/_help-catalog.d.ts +29 -0
  20. package/dist/src/commands/_help-catalog.js +146 -0
  21. package/dist/src/commands/_inprocess-services.d.ts +33 -0
  22. package/dist/src/commands/_inprocess-services.js +102 -0
  23. package/dist/src/commands/_json-output.d.ts +11 -0
  24. package/dist/src/commands/_json-output.js +60 -0
  25. package/dist/src/commands/_lazy-reconcile.d.ts +34 -0
  26. package/dist/src/commands/_lazy-reconcile.js +102 -0
  27. package/dist/src/commands/_parsers.d.ts +15 -0
  28. package/dist/src/commands/_parsers.js +18 -11
  29. package/dist/src/commands/_paths.d.ts +11 -0
  30. package/dist/src/commands/_paths.js +1 -1
  31. package/dist/src/commands/_pi-frontend.d.ts +35 -0
  32. package/dist/src/commands/_pi-frontend.js +64 -0
  33. package/dist/src/commands/_pi-install.d.ts +42 -0
  34. package/dist/src/commands/_pi-install.js +19 -36
  35. package/dist/src/commands/_policy.d.ts +8 -0
  36. package/dist/src/commands/_policy.js +67 -19
  37. package/dist/src/commands/_probes.d.ts +1 -0
  38. package/dist/src/commands/_run-bridge.d.ts +114 -0
  39. package/dist/src/commands/_run-bridge.js +387 -0
  40. package/dist/src/commands/_run-diagnostics.d.ts +9 -0
  41. package/dist/src/commands/_run-diagnostics.js +51 -0
  42. package/dist/src/commands/_run-driver-helpers.d.ts +26 -0
  43. package/dist/src/commands/_run-driver-helpers.js +79 -230
  44. package/dist/src/commands/_run-projection.d.ts +50 -0
  45. package/dist/src/commands/_run-projection.js +349 -0
  46. package/dist/src/commands/_run-subcommands.d.ts +3 -0
  47. package/dist/src/commands/_run-subcommands.js +31 -0
  48. package/dist/src/commands/_spinner.d.ts +25 -0
  49. package/dist/src/commands/_spinner.js +65 -0
  50. package/dist/src/commands/agent.d.ts +3 -0
  51. package/dist/src/commands/agent.js +8690 -235
  52. package/dist/src/commands/config.d.ts +3 -0
  53. package/dist/src/commands/config.js +181 -0
  54. package/dist/src/commands/dist.d.ts +28 -0
  55. package/dist/src/commands/dist.js +44 -29
  56. package/dist/src/commands/doctor.d.ts +3 -0
  57. package/dist/src/commands/doctor.js +214 -245
  58. package/dist/src/commands/github.d.ts +3 -0
  59. package/dist/src/commands/github.js +237 -171
  60. package/dist/src/commands/inbox.d.ts +28 -0
  61. package/dist/src/commands/inbox.js +530 -111
  62. package/dist/src/commands/init.d.ts +64 -0
  63. package/dist/src/commands/init.js +941 -654
  64. package/dist/src/commands/inspect.d.ts +20 -0
  65. package/dist/src/commands/inspect.js +709 -119
  66. package/dist/src/commands/pi.d.ts +3 -0
  67. package/dist/src/commands/pi.js +177 -0
  68. package/dist/src/commands/plugin.d.ts +16 -0
  69. package/dist/src/commands/plugin.js +576 -29
  70. package/dist/src/commands/profile-and-review.d.ts +4 -0
  71. package/dist/src/commands/profile-and-review.js +112 -67
  72. package/dist/src/commands/queue.d.ts +3 -0
  73. package/dist/src/commands/queue.js +20 -20
  74. package/dist/src/commands/remote.d.ts +3 -0
  75. package/dist/src/commands/remote.js +883 -50
  76. package/dist/src/commands/repo-git-harness.d.ts +5 -0
  77. package/dist/src/commands/repo-git-harness.js +78 -28
  78. package/dist/src/commands/run.d.ts +21 -0
  79. package/dist/src/commands/run.js +17732 -618
  80. package/dist/src/commands/server.d.ts +3 -0
  81. package/dist/src/commands/server.js +166 -285
  82. package/dist/src/commands/setup.d.ts +16 -0
  83. package/dist/src/commands/setup.js +230 -267
  84. package/dist/src/commands/stats.d.ts +15 -0
  85. package/dist/src/commands/stats.js +632 -0
  86. package/dist/src/commands/task-run-driver.d.ts +94 -0
  87. package/dist/src/commands/task-run-driver.js +120 -1856
  88. package/dist/src/commands/task.d.ts +35 -0
  89. package/dist/src/commands/task.js +676 -1183
  90. package/dist/src/commands/test.d.ts +3 -0
  91. package/dist/src/commands/test.js +15 -8
  92. package/dist/src/commands/triage.d.ts +11 -0
  93. package/dist/src/commands/triage.js +227 -0
  94. package/dist/src/commands/workspace.d.ts +3 -0
  95. package/dist/src/commands/workspace.js +18 -11
  96. package/dist/src/commands.d.ts +13 -0
  97. package/dist/src/commands.js +16760 -7779
  98. package/dist/src/index.d.ts +4 -0
  99. package/dist/src/index.js +16880 -8223
  100. package/dist/src/launcher.d.ts +61 -0
  101. package/dist/src/launcher.js +81 -13
  102. package/dist/src/operator-cli.d.ts +2 -0
  103. package/dist/src/operator-cli.js +17867 -0
  104. package/dist/src/operator-entry.d.ts +1 -0
  105. package/dist/src/operator-entry.js +3 -0
  106. package/dist/src/runner.d.ts +47 -0
  107. package/dist/src/runner.js +19 -24
  108. package/dist/src/withMutedConsole.d.ts +2 -0
  109. package/package.json +21 -7
  110. package/dist/src/commands/_authority-runs.js +0 -110
  111. package/dist/src/commands/_operator-view.js +0 -322
  112. package/dist/src/commands/_preflight.js +0 -460
  113. package/dist/src/commands/_server-client.js +0 -364
  114. package/dist/src/commands/_snapshot-upload.js +0 -313
  115. package/dist/src/commands/_task-picker.js +0 -48
  116. package/dist/src/commands/browser.js +0 -890
  117. package/dist/src/commands/connect.js +0 -180
  118. package/dist/src/commands/inspector.js +0 -256
  119. package/dist/src/commands/task-report-bug.js +0 -1083
  120. 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
  }
@@ -99,12 +96,13 @@ async function runCommand(context, parts) {
99
96
  const envMode = process.env.RIG_BASH_MODE;
100
97
  const effectiveMode = context.policyMode || (envMode === "off" || envMode === "observe" || envMode === "enforce" ? envMode : loadPolicy(context.projectRoot).mode);
101
98
  const controlledPath = `${resolve(context.projectRoot, ".rig", "bin")}:${context.projectRoot}/rig/tools:${process.env.PATH ?? ""}`;
102
- const controlledBash = await ensureAgentShellBinary(context.projectRoot);
99
+ const usesInfrastructureBinary = parts[0] === "rig-server";
100
+ const controlledBash = usesInfrastructureBinary ? null : await ensureAgentShellBinary(context.projectRoot);
103
101
  const commandEnv = [
104
102
  "env",
105
103
  `PATH=${controlledPath}`,
106
104
  `PROJECT_RIG_ROOT=${context.projectRoot}`,
107
- `BASH=${controlledBash}`,
105
+ ...controlledBash ? [`BASH=${controlledBash}`] : [],
108
106
  `RIG_BASH_MODE=${effectiveMode}`,
109
107
  `RIG_POLICY_FILE=${resolve(context.projectRoot, "rig/policy/policy.json")}`,
110
108
  ...context.eventBus.getEventsFile() ? [`RIG_EVENTS_FILE=${context.eventBus.getEventsFile()}`] : []
@@ -136,9 +134,8 @@ async function runCommand(context, parts) {
136
134
  matchedRuleIds: guardDecision.matchedRules.map((r) => r.id),
137
135
  mode: effectiveMode
138
136
  });
139
- 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." });
140
138
  }
141
- await context.plugins.beforeCommand({ command: commandWithEnv, formattedCommand: formatted });
142
139
  const startedAt = new Date;
143
140
  await context.emitEvent("command.started", {
144
141
  command: commandWithEnv,
@@ -158,7 +155,6 @@ async function runCommand(context, parts) {
158
155
  if (context.outputMode === "text") {
159
156
  console.log(`$ ${formatted}`);
160
157
  }
161
- await context.plugins.afterCommand(dryResult);
162
158
  await context.emitEvent("command.finished", {
163
159
  ...dryResult,
164
160
  dryRun: true
@@ -198,7 +194,6 @@ async function runCommand(context, parts) {
198
194
  stdout: context.outputMode === "json" ? stdout : undefined,
199
195
  stderr: context.outputMode === "json" ? stderr : undefined
200
196
  };
201
- await context.plugins.afterCommand(result);
202
197
  if (exitCode !== 0) {
203
198
  await context.emitEvent("command.failed", {
204
199
  ...result
@@ -232,7 +227,7 @@ function takeOption(args, option) {
232
227
  if (current === option) {
233
228
  const next = args[index + 1];
234
229
  if (!next || next.startsWith("-")) {
235
- 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>\`.` });
236
231
  }
237
232
  value = next;
238
233
  index += 1;
@@ -268,5 +263,5 @@ export {
268
263
  initializeRuntime,
269
264
  formatCommand,
270
265
  ensureAgentShellBinary,
271
- CliError2 as CliError
266
+ CliError
272
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.1",
3
+ "version": "0.0.6-alpha.100",
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,14 +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.1",
27
- "@rig/runtime": "npm:@h-rig/runtime@0.0.6-alpha.1",
28
- "@rig/client": "npm:@h-rig/client@0.0.6-alpha.1",
29
- "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.100",
32
+ "@rig/contracts": "npm:@h-rig/contracts@0.0.6-alpha.100",
33
+ "@rig/core": "npm:@h-rig/core@0.0.6-alpha.100",
34
+ "@rig/relay-registry": "npm:@h-rig/relay-registry@0.0.6-alpha.100",
35
+ "@rig/rig-extension": "npm:@h-rig/rig-extension@0.0.6-alpha.100",
36
+ "@rig/rig-host": "npm:@h-rig/rig-host@0.0.6-alpha.100",
37
+ "@rig/runtime": "npm:@h-rig/runtime@0.0.6-alpha.100",
38
+ "@rig/shared": "npm:@h-rig/shared@0.0.6-alpha.100",
39
+ "@rig/standard-plugin": "npm:@h-rig/standard-plugin@0.0.6-alpha.100",
40
+ "@xterm/headless": "^6.0.0",
41
+ "effect": "4.0.0-beta.78",
42
+ "picocolors": "^1.1.1",
43
+ "react": "^19.2.0"
30
44
  }
31
45
  }
@@ -1,110 +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
- runId: input.runId,
71
- projectRoot,
72
- workspaceId: existing?.workspaceId ?? RIG_WORKSPACE_ID,
73
- taskId: input.taskId,
74
- threadId: existing?.threadId ?? null,
75
- mode: "local",
76
- runtimeAdapter,
77
- status: input.status,
78
- createdAt,
79
- startedAt: input.startedAt ?? existing?.startedAt ?? null,
80
- completedAt: input.completedAt ?? existing?.completedAt ?? null,
81
- endpointId: existing?.endpointId ?? null,
82
- hostId: existing?.hostId ?? null,
83
- worktreePath: input.worktreePath ?? existing?.worktreePath ?? null,
84
- artifactRoot: input.artifactRoot ?? existing?.artifactRoot ?? null,
85
- logRoot: input.logRoot ?? existing?.logRoot ?? null,
86
- sessionPath: input.sessionPath ?? existing?.sessionPath ?? null,
87
- sessionLogPath: input.sessionLogPath ?? existing?.sessionLogPath ?? null,
88
- pid: input.pid ?? existing?.pid ?? null,
89
- updatedAt: input.createdAt,
90
- title,
91
- model: typeof existing?.model === "string" ? existing.model : null,
92
- runtimeMode,
93
- interactionMode,
94
- runMode,
95
- initialPrompt: typeof existing?.initialPrompt === "string" ? existing.initialPrompt : null
96
- };
97
- if (input.errorText !== undefined) {
98
- next.errorText = input.errorText;
99
- } else if ("errorText" in next) {
100
- delete next.errorText;
101
- }
102
- writeJsonFile(resolve(resolveAuthorityRunDir(projectRoot, input.runId), "run.json"), next);
103
- return next;
104
- }
105
- export {
106
- upsertAgentAuthorityRun,
107
- readLatestBeadRecord,
108
- normalizeRuntimeAdapter,
109
- RIG_WORKSPACE_ID
110
- };
@@ -1,322 +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
-
8
- // packages/cli/src/runner.ts
9
- import { EventBus } from "@rig/runtime/control-plane/runtime/events";
10
- import { CliError } from "@rig/runtime/control-plane/errors";
11
- import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
12
- import { PluginManager } from "@rig/runtime/control-plane/runtime/plugins";
13
- import { loadRuntimeContextFromEnv } from "@rig/runtime/control-plane/runtime/context";
14
- import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
15
- import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
16
-
17
- // packages/cli/src/commands/_server-client.ts
18
- import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
19
-
20
- // packages/cli/src/commands/_connection-state.ts
21
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
22
- import { homedir } from "os";
23
- import { dirname, resolve } from "path";
24
- function resolveGlobalConnectionsPath(env = process.env) {
25
- const explicit = env.RIG_CONNECTIONS_FILE?.trim();
26
- if (explicit)
27
- return resolve(explicit);
28
- const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
29
- if (stateDir)
30
- return resolve(stateDir, "connections.json");
31
- return resolve(homedir(), ".rig", "connections.json");
32
- }
33
- function resolveRepoConnectionPath(projectRoot) {
34
- return resolve(projectRoot, ".rig", "state", "connection.json");
35
- }
36
- function readJsonFile(path) {
37
- if (!existsSync(path))
38
- return null;
39
- try {
40
- return JSON.parse(readFileSync(path, "utf8"));
41
- } catch (error) {
42
- throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
43
- }
44
- }
45
- function normalizeConnection(value) {
46
- if (!value || typeof value !== "object" || Array.isArray(value))
47
- return null;
48
- const record = value;
49
- if (record.kind === "local")
50
- return { kind: "local", mode: "auto" };
51
- if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
52
- const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
53
- return { kind: "remote", baseUrl };
54
- }
55
- return null;
56
- }
57
- function readGlobalConnections(options = {}) {
58
- const path = resolveGlobalConnectionsPath(options.env ?? process.env);
59
- const payload = readJsonFile(path);
60
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
61
- return { connections: {} };
62
- }
63
- const rawConnections = payload.connections;
64
- const connections = {};
65
- if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
66
- for (const [alias, raw] of Object.entries(rawConnections)) {
67
- const connection = normalizeConnection(raw);
68
- if (connection)
69
- connections[alias] = connection;
70
- }
71
- }
72
- return { connections };
73
- }
74
- function readRepoConnection(projectRoot) {
75
- const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
76
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
77
- return null;
78
- const record = payload;
79
- const selected = typeof record.selected === "string" ? record.selected.trim() : "";
80
- if (!selected)
81
- return null;
82
- return {
83
- selected,
84
- project: typeof record.project === "string" ? record.project : undefined,
85
- linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined
86
- };
87
- }
88
- function resolveSelectedConnection(projectRoot, options = {}) {
89
- const repo = readRepoConnection(projectRoot);
90
- if (!repo)
91
- return null;
92
- if (repo.selected === "local")
93
- return { alias: "local", connection: { kind: "local", mode: "auto" } };
94
- const global = readGlobalConnections(options);
95
- const connection = global.connections[repo.selected];
96
- if (!connection) {
97
- throw new CliError2(`Selected Rig connection "${repo.selected}" was not found. Run \`rig connect list\` or \`rig connect use local\`.`, 1);
98
- }
99
- return { alias: repo.selected, connection };
100
- }
101
-
102
- // packages/cli/src/commands/_server-client.ts
103
- var cachedGitHubBearerToken;
104
- function cleanToken(value) {
105
- const trimmed = value?.trim();
106
- return trimmed ? trimmed : null;
107
- }
108
- function readGitHubBearerTokenForRemote() {
109
- if (cachedGitHubBearerToken !== undefined)
110
- return cachedGitHubBearerToken;
111
- const envToken = cleanToken(process.env.RIG_GITHUB_TOKEN) ?? cleanToken(process.env.GITHUB_TOKEN) ?? cleanToken(process.env.GH_TOKEN);
112
- if (envToken) {
113
- cachedGitHubBearerToken = envToken;
114
- return cachedGitHubBearerToken;
115
- }
116
- const result = spawnSync("gh", ["auth", "token"], {
117
- encoding: "utf8",
118
- timeout: 5000,
119
- stdio: ["ignore", "pipe", "ignore"]
120
- });
121
- cachedGitHubBearerToken = result.status === 0 ? cleanToken(result.stdout) : null;
122
- return cachedGitHubBearerToken;
123
- }
124
- async function ensureServerForCli(projectRoot) {
125
- try {
126
- const selected = resolveSelectedConnection(projectRoot);
127
- if (selected?.connection.kind === "remote") {
128
- return {
129
- baseUrl: selected.connection.baseUrl,
130
- authToken: readGitHubBearerTokenForRemote(),
131
- connectionKind: "remote"
132
- };
133
- }
134
- const connection = await ensureLocalRigServerConnection(projectRoot);
135
- return {
136
- baseUrl: connection.baseUrl,
137
- authToken: connection.authToken,
138
- connectionKind: "local"
139
- };
140
- } catch (error) {
141
- if (error instanceof Error) {
142
- throw new CliError2(error.message, 1);
143
- }
144
- throw error;
145
- }
146
- }
147
- function mergeHeaders(headers, authToken) {
148
- const merged = new Headers(headers);
149
- if (authToken) {
150
- merged.set("authorization", `Bearer ${authToken}`);
151
- }
152
- return merged;
153
- }
154
- function diagnosticMessage(payload) {
155
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
156
- return null;
157
- const record = payload;
158
- const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
159
- const messages = diagnostics.flatMap((entry) => {
160
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
161
- return [];
162
- const diagnostic = entry;
163
- const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
164
- const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
165
- return message ? [`${kind}: ${message}`] : [];
166
- });
167
- return messages.length > 0 ? messages.join("; ") : null;
168
- }
169
- async function requestServerJson(context, pathname, init = {}) {
170
- const server = await ensureServerForCli(context.projectRoot);
171
- const response = await fetch(`${server.baseUrl}${pathname}`, {
172
- ...init,
173
- headers: mergeHeaders(init.headers, server.authToken)
174
- });
175
- const text = await response.text();
176
- const payload = text.trim().length > 0 ? (() => {
177
- try {
178
- return JSON.parse(text);
179
- } catch {
180
- return null;
181
- }
182
- })() : null;
183
- if (!response.ok) {
184
- const diagnostics = diagnosticMessage(payload);
185
- const detail = diagnostics ?? (text || response.statusText);
186
- throw new CliError2(`Rig server request failed (${response.status}): ${detail}`, 1);
187
- }
188
- return payload;
189
- }
190
- async function getRunDetailsViaServer(context, runId) {
191
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}`);
192
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
193
- }
194
- async function getRunLogsViaServer(context, runId, options = {}) {
195
- const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/logs`);
196
- if (options.limit !== undefined)
197
- url.searchParams.set("limit", String(options.limit));
198
- if (options.cursor)
199
- url.searchParams.set("cursor", options.cursor);
200
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
201
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
202
- }
203
- async function stopRunViaServer(context, runId) {
204
- const payload = await requestServerJson(context, "/api/runs/stop", {
205
- method: "POST",
206
- headers: { "content-type": "application/json" },
207
- body: JSON.stringify({ runId })
208
- });
209
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true, runId };
210
- }
211
- async function steerRunViaServer(context, runId, message) {
212
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/steer`, {
213
- method: "POST",
214
- headers: { "content-type": "application/json" },
215
- body: JSON.stringify({ message })
216
- });
217
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
218
- }
219
-
220
- // packages/cli/src/commands/_operator-view.ts
221
- var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
222
- var CANONICAL_STAGES = [
223
- "Connect",
224
- "GitHub/task sync",
225
- "Prepare workspace",
226
- "Launch Pi",
227
- "Plan",
228
- "Implement",
229
- "Validate",
230
- "Commit",
231
- "Open PR",
232
- "Review/CI",
233
- "Merge",
234
- "Complete"
235
- ];
236
- function renderOperatorSnapshot(snapshot) {
237
- const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
238
- const runId = String(run.runId ?? run.id ?? "run");
239
- const status = String(run.status ?? "unknown");
240
- const logs = snapshot.logs ?? [];
241
- const stageLines = CANONICAL_STAGES.flatMap((stage) => {
242
- const match = logs.find((log) => String(log.title ?? "").toLowerCase() === stage.toLowerCase() || String(log.stage ?? "").toLowerCase() === stage.toLowerCase());
243
- return match ? [`${stage}: ${String(match.status ?? status)}`] : [];
244
- });
245
- return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
246
- `);
247
- }
248
- function runStatusFromPayload(payload) {
249
- const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
250
- return String(run.status ?? "unknown").toLowerCase();
251
- }
252
- async function applyOperatorCommand(context, input, deps = {}) {
253
- const line = input.line.trim();
254
- if (!line)
255
- return { action: "ignored" };
256
- if (line === "/detach" || line === "/quit" || line === "/q") {
257
- return { action: "detach", message: "Detached from run." };
258
- }
259
- if (line === "/stop") {
260
- await (deps.stop ?? stopRunViaServer)(context, input.runId);
261
- return { action: "stopped", message: "Stop requested." };
262
- }
263
- const userMessage = line.startsWith("/user ") ? line.slice("/user ".length).trim() : line;
264
- if (!userMessage)
265
- return { action: "ignored" };
266
- await (deps.steer ?? steerRunViaServer)(context, input.runId, userMessage);
267
- return { action: "continue", message: "Steering message queued." };
268
- }
269
- async function readOperatorSnapshot(context, runId) {
270
- const run = await getRunDetailsViaServer(context, runId);
271
- const logsPage = await getRunLogsViaServer(context, runId, { limit: 100 });
272
- const entries = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
273
- return { run, logs: entries, rendered: renderOperatorSnapshot({ run, logs: entries }) };
274
- }
275
- async function attachRunOperatorView(context, input) {
276
- let steered = false;
277
- if (input.message?.trim()) {
278
- await steerRunViaServer(context, input.runId, input.message.trim());
279
- steered = true;
280
- }
281
- let snapshot = await readOperatorSnapshot(context, input.runId);
282
- if (context.outputMode === "text") {
283
- console.log(snapshot.rendered);
284
- if (steered)
285
- console.log("Steering message queued.");
286
- }
287
- let detached = false;
288
- let rl = null;
289
- if (input.follow && !input.once && context.outputMode === "text") {
290
- if (input.interactive !== false && process.stdin.isTTY) {
291
- console.log("Controls: /user <message>, /stop, /detach");
292
- rl = createInterface({ input: process.stdin, output: process.stdout, terminal: false });
293
- rl.on("line", (line) => {
294
- applyOperatorCommand(context, { runId: input.runId, line }).then((result) => {
295
- if (result.message)
296
- console.log(result.message);
297
- if (result.action === "detach" || result.action === "stopped") {
298
- detached = true;
299
- rl?.close();
300
- }
301
- }).catch((error) => console.log(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
302
- });
303
- }
304
- let lastRendered = snapshot.rendered;
305
- const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
306
- while (!detached && !TERMINAL_RUN_STATUSES.has(runStatusFromPayload(snapshot.run))) {
307
- await Bun.sleep(pollMs);
308
- snapshot = await readOperatorSnapshot(context, input.runId);
309
- if (snapshot.rendered !== lastRendered) {
310
- console.log(snapshot.rendered);
311
- lastRendered = snapshot.rendered;
312
- }
313
- }
314
- rl?.close();
315
- }
316
- return { ...snapshot, steered, detached };
317
- }
318
- export {
319
- renderOperatorSnapshot,
320
- attachRunOperatorView,
321
- applyOperatorCommand
322
- };