@liberseek/boft-cli 0.1.2 → 0.5.0

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 (53) hide show
  1. package/README.md +13 -237
  2. package/bin/boft.js +435 -0
  3. package/bin/codexhost.js +435 -0
  4. package/package.json +30 -32
  5. package/dist/api.d.ts +0 -93
  6. package/dist/api.d.ts.map +0 -1
  7. package/dist/api.js +0 -249
  8. package/dist/api.js.map +0 -1
  9. package/dist/cli.d.ts +0 -19
  10. package/dist/cli.d.ts.map +0 -1
  11. package/dist/cli.js +0 -744
  12. package/dist/cli.js.map +0 -1
  13. package/dist/codex.d.ts +0 -70
  14. package/dist/codex.d.ts.map +0 -1
  15. package/dist/codex.js +0 -664
  16. package/dist/codex.js.map +0 -1
  17. package/dist/config.d.ts +0 -14
  18. package/dist/config.d.ts.map +0 -1
  19. package/dist/config.js +0 -105
  20. package/dist/config.js.map +0 -1
  21. package/dist/index.d.ts +0 -3
  22. package/dist/index.d.ts.map +0 -1
  23. package/dist/index.js +0 -4
  24. package/dist/index.js.map +0 -1
  25. package/dist/output.d.ts +0 -11
  26. package/dist/output.d.ts.map +0 -1
  27. package/dist/output.js +0 -87
  28. package/dist/output.js.map +0 -1
  29. package/dist/platforms.d.ts +0 -63
  30. package/dist/platforms.d.ts.map +0 -1
  31. package/dist/platforms.js +0 -568
  32. package/dist/platforms.js.map +0 -1
  33. package/dist/prompt.d.ts +0 -4
  34. package/dist/prompt.d.ts.map +0 -1
  35. package/dist/prompt.js +0 -49
  36. package/dist/prompt.js.map +0 -1
  37. package/dist/redact.d.ts +0 -3
  38. package/dist/redact.d.ts.map +0 -1
  39. package/dist/redact.js +0 -23
  40. package/dist/redact.js.map +0 -1
  41. package/dist/types.d.ts +0 -116
  42. package/dist/types.d.ts.map +0 -1
  43. package/dist/types.js +0 -2
  44. package/dist/types.js.map +0 -1
  45. package/dist/validate.d.ts +0 -6
  46. package/dist/validate.d.ts.map +0 -1
  47. package/dist/validate.js +0 -47
  48. package/dist/validate.js.map +0 -1
  49. package/dist/version.d.ts +0 -2
  50. package/dist/version.d.ts.map +0 -1
  51. package/dist/version.js +0 -7
  52. package/dist/version.js.map +0 -1
  53. package/docs/HTTP_CONTRACT.md +0 -121
package/README.md CHANGED
@@ -1,250 +1,26 @@
1
- # BOFT CLI
1
+ # @liberseek/boft-cli
2
2
 
3
- `@liberseek/boft-cli` configures supported Agent platforms to use BOFT and provides the secure command-line client for BOFT Agent accounts. It can configure Codex without replacing the user's Codex login, query balances, create self-service recharge payments, render payment QR codes, and manage user API Keys within the Agent Token scopes. It cannot perform administrative operations or directly debit an account.
3
+ BOFT CLI runs Pi and other external harnesses inside Codex Desktop.
4
4
 
5
- ## Requirements and installation
6
-
7
- - Node.js 20 or later
8
- - A dedicated BOFT Agent Token for account and recharge commands
9
-
10
- Install the public npm package:
11
-
12
- ```bash
13
- npm install --global @liberseek/boft-cli
14
- boft --help
15
- ```
16
-
17
- Build and install from this repository:
18
-
19
- ```bash
20
- npm ci
21
- npm run build
22
- npm install --global .
23
- boft --help
24
- ```
25
-
26
- For local development without a global install:
27
-
28
- ```bash
29
- npm run build
30
- node dist/index.js --help
31
- ```
32
-
33
- ## Authentication
34
-
35
- Interactive login verifies the token against the account endpoint before saving it:
5
+ ## Install
36
6
 
37
7
  ```bash
38
- boft auth login
39
- boft auth status
40
- boft auth logout
41
- ```
42
-
43
- The prompt does not echo the token. Saved credentials use `$XDG_CONFIG_HOME/boft/credentials.json`, or `~/.config/boft/credentials.json` when `XDG_CONFIG_HOME` is unset. The directory is mode `0700` and the file is mode `0600`.
44
-
45
- For CI, Codex, MCP servers, and other Agents, inject the token without writing it to disk:
46
-
47
- ```bash
48
- export BOFT_AGENT_TOKEN='your-dedicated-agent-token'
49
- export BOFT_BASE_URL='https://api.boft.ai' # optional
50
- boft --json balance
51
- ```
52
-
53
- `BOFT_AGENT_TOKEN` always takes precedence over saved credentials. The CLI never prints the complete token; `auth status` exposes only a short prefix/suffix hint. Avoid putting tokens in command arguments, prompts, logs, or source-controlled files.
54
-
55
- ## Commands
56
-
57
- Global options must be placed before the command:
58
-
59
- ```text
60
- --json Machine-readable JSON, with no QR or labels
61
- --base-url <url> API base URL (default https://api.boft.ai)
62
- --timeout <milliseconds> Request timeout, 1000-120000 (default 15000)
8
+ npm install -g @liberseek/boft-cli@0.5.0
63
9
  ```
64
10
 
65
- ## Configure Codex
11
+ npm automatically installs the matching macOS, Windows, or Linux platform package. Node.js 22 or 24 and the official ChatGPT/Codex Desktop are required.
66
12
 
67
- The BOFT website can create a short-lived, single-use client access code. Run the command shown by the website, then paste the client access code into the hidden prompt:
13
+ ## Usage
68
14
 
69
15
  ```bash
70
- npx --yes @liberseek/boft-cli@latest setup codex
16
+ boft --version
17
+ boft
18
+ boft remote install
19
+ boft remote status
71
20
  ```
72
21
 
73
- The setup command:
22
+ The `boft` command starts Codex Desktop. `codexhost` remains available as a compatibility alias. On macOS and Linux it returns immediately while the packaged Launcher keeps supervising in the background. On Windows, the command remains attached until Codex Desktop exits so shells that clean up process trees of completed commands cannot discard the supervisor. Re-running `boft` attaches to the same controlled instance.
74
23
 
75
- - detects `CODEX_HOME` and otherwise uses `~/.codex`
76
- - verifies the Codex CLI is installed before consuming the one-time client access code
77
- - preserves unrelated fields in the existing `auth.json`
78
- - merges the BOFT API Key into `auth.json` as `OPENAI_API_KEY`
79
- - configures the `OpenAI` provider exactly like the BOFT website's manual Codex instructions
80
- - preserves unrelated TOML settings and comments
81
- - creates a backup of `config.toml`, `auth.json`, and prior BOFT CLI state before every change
24
+ On macOS, `remote install` installs a current-user Aqua Harness broker so Background SSH Hosts can use native Claude Code login without reading, copying, or unlocking Keychain credentials.
82
25
 
83
- Inspect, diagnose, roll back, or completely remove the integration:
84
-
85
- ```bash
86
- boft status codex
87
- boft doctor codex
88
- boft rollback codex
89
- boft remove codex
90
- ```
91
-
92
- For local testing before the website client-access-code endpoint is available, pass the API Key over stdin. Never place the key directly in a command argument:
93
-
94
- ```bash
95
- printf '%s\n' "$BOFT_API_KEY" | boft setup codex --api-key-stdin \
96
- --endpoint https://supply.boft.ai/v1
97
- ```
98
-
99
- Add `--websocket` for the Codex Responses WebSocket v2 variant. `--dry-run` is available with `--api-key-stdin`; it validates the configuration without writing files. Dry-run intentionally rejects client access codes so it cannot consume a one-time code without applying it.
100
-
101
- Both Responses variants use `[model_providers.OpenAI]` with `name = "BANK OF TOKEN"`. The WebSocket variant additionally sets `supports_websockets = true` and `responses_websockets_v2 = true`, matching `UserUseKeyModal.vue`.
102
-
103
- Codex reads the API Key from `~/.codex/auth.json` (or `%USERPROFILE%\\.codex\\auth.json` on Windows). BOFT CLI merges `OPENAI_API_KEY` into that JSON object without removing unrelated fields, writes it atomically with mode `0600` on POSIX systems, and restores the exact previous file during rollback. Backup metadata is kept below the BOFT configuration directory. The complete API Key is never included in command output or `config.toml`.
104
-
105
- The client access code is not an Agent Token and is not used for later API calls. It is only a fifteen-minute, one-use delivery code that lets BOFT CLI retrieve the selected API Key and endpoint for this local setup.
106
-
107
- ## Configure Claude Code, Gemini CLI, and OpenCode
108
-
109
- The BOFT website creates the same short-lived client access code for the other supported clients. The command is target-specific and asks for the client access code interactively:
110
-
111
- ```bash
112
- npx --yes @liberseek/boft-cli@latest setup claude
113
- npx --yes @liberseek/boft-cli@latest setup gemini
114
- npx --yes @liberseek/boft-cli@latest setup opencode
115
- ```
116
-
117
- `--code BOFT-CLIENT-ACCESS-CODE` remains available for controlled automation, but the interactive prompt is the safer default because the code does not enter shell history or process arguments.
118
-
119
- Claude Code is configured in `~/.claude/settings.json`, Gemini CLI in `~/.gemini/.env`, and OpenCode in its global `opencode.json` (`OPENCODE_CONFIG` is honored when set). Existing unrelated settings are preserved. OpenCode setup uses the provider selected in the BOFT key page, including OpenAI-compatible providers such as DeepSeek, Grok, DashScope, Z.AI, and MiniMax.
120
-
121
- The same lifecycle commands are available for every target:
122
-
123
- ```bash
124
- boft status claude|gemini|opencode
125
- boft doctor claude|gemini|opencode
126
- boft rollback claude|gemini|opencode
127
- boft remove claude|gemini|opencode
128
- ```
129
-
130
- For local testing, API Keys are read from stdin and never need to appear in shell history:
131
-
132
- ```bash
133
- printf '%s\\n' "$BOFT_API_KEY" | boft setup claude --api-key-stdin --endpoint https://supply.boft.ai
134
- printf '%s\\n' "$BOFT_API_KEY" | boft setup gemini --api-key-stdin --endpoint https://supply.boft.ai
135
- printf '%s\\n' "$BOFT_API_KEY" | boft setup opencode --api-key-stdin --provider openai --endpoint https://supply.boft.ai/v1
136
- ```
137
-
138
- Account and payment methods:
139
-
140
- ```bash
141
- boft balance
142
- boft payment methods
143
- ```
144
-
145
- Create a recharge payment. Supplying your own idempotency key is recommended when an orchestration layer may retry the same intent:
146
-
147
- ```bash
148
- boft recharge create --amount 100.00 --method alipay --idempotency-key order-20260802-001
149
- ```
150
-
151
- In a terminal, the create command prints the payment ID, status, scan-ready QR code, payment link when returned by BOFT, and a `Retry key`. In JSON mode the same key is returned as `idempotency_key` alongside the server payment object. Reuse that key with `--idempotency-key` if a timeout or network failure leaves the original request outcome uncertain.
152
-
153
- Query, long-poll, or cancel a pending payment:
154
-
155
- ```bash
156
- boft recharge status pay_123
157
- boft recharge status pay_123 --wait # wait_seconds=25
158
- boft recharge status pay_123 --wait 25
159
- boft recharge cancel pay_123
160
- ```
161
-
162
- `--wait` performs one server-side long-poll and returns the status received. It does not create an unbounded local polling loop.
163
-
164
- Inspect key groups and user-specific multipliers:
165
-
166
- ```bash
167
- boft group available
168
- boft group available --scope agent
169
- ```
170
-
171
- Create or move a regular API Key. Creation uses an idempotency key, and any returned key secret is sensitive:
172
-
173
- ```bash
174
- boft key list
175
- boft key create --name "Production" --group-id 12 --idempotency-key key-20260803-001
176
- boft key set-group 42 --group-id 18
177
- ```
178
-
179
- Create and tune AUTO Keys:
180
-
181
- ```bash
182
- boft auto-key list
183
- boft auto-key create --name "AUTO Production" --model gpt-4.1 claude-sonnet-4 --strategy balanced --idempotency-key auto-20260803-001
184
- boft auto-key set-routing 42 --strategy cost --disable-provider openai --fallback-enabled false
185
- boft auto-key preview 42
186
- ```
187
-
188
- Provider group constraints are accepted as JSON so orchestration layers can pass exact server-shaped data:
189
-
190
- ```bash
191
- boft auto-key set-routing 42 \
192
- --provider-groups '[{"provider":"openai","mode":"specific","group_ids":[12,18]}]'
193
- ```
194
-
195
- ## Agent integration
196
-
197
- An Agent can invoke the CLI as a subprocess and parse stdout:
198
-
199
- ```bash
200
- boft --json payment methods
201
- boft --json recharge create --amount 50.00 --method wechat_pay --idempotency-key "$REQUEST_ID"
202
- boft --json recharge status "$PAYMENT_ID" --wait 25
203
- boft --json group available
204
- boft --json auto-key set-routing "$AUTO_KEY_ID" --strategy efficiency
205
- ```
206
-
207
- Successful JSON output goes to stdout. Structured errors go to stderr and the process exits nonzero:
208
-
209
- ```json
210
- {"error":{"message":"Agent Token has expired","status":401,"code":"TOKEN_REVOKED"}}
211
- ```
212
-
213
- Secrets in known error formats and the active token value are redacted before output.
214
-
215
- ## Base URL security
216
-
217
- Remote endpoints must use HTTPS. Plain HTTP is accepted only for `localhost`, `127.0.0.1`, or `[::1]`, which supports local contract tests without allowing a production Agent Token to be sent over a plaintext remote connection. Base URLs containing user information, query parameters, or fragments are rejected.
218
-
219
- ## Development checks
220
-
221
- ```bash
222
- npm run lint
223
- npm run typecheck
224
- npm test
225
- npm run build
226
- ```
227
-
228
- Tests use injected mock HTTP transports. They do not initiate real payments or require a live BOFT account.
229
-
230
- ## Maintainer release
231
-
232
- The package is published as the public scoped package `@liberseek/boft-cli`. The repository's `Publish npm package` workflow runs only for a pushed version tag such as `v0.1.1`.
233
-
234
- Configure the repository secret `NPM_TOKEN` with an npm automation token that has publish permission for the `@liberseek` scope. Do not commit the token or place it in a workflow file. GitHub Actions injects it only into the publish step and also creates npm provenance metadata.
235
-
236
- For a normal patch release:
237
-
238
- ```bash
239
- npm version patch
240
- git push origin main --follow-tags
241
- ```
242
-
243
- `npm version` updates `package.json` and `package-lock.json`, creates the matching `v*` tag, and the tag push starts the release workflow. The workflow refuses to publish when the tag version and package version differ.
244
-
245
- Before the first release, make sure the npm `liberseek` organization/scope exists and that the publishing account or automation token can publish public packages under `@liberseek`. The current package version is `0.1.0`; publish it with:
246
-
247
- ```bash
248
- git tag v0.1.0
249
- git push origin v0.1.0
250
- ```
26
+ If installation used `--omit=optional`, reinstall without that option so npm can select the native package for the current architecture.
package/bin/boft.js ADDED
@@ -0,0 +1,435 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from "node:child_process";
3
+ import { existsSync, realpathSync } from "node:fs";
4
+ import { createRequire } from "node:module";
5
+ import { homedir } from "node:os";
6
+ import path from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ const version = "0.5.0";
10
+ const userArguments = process.argv.slice(2);
11
+ const startupTraceStartedAt = Date.now();
12
+ function startupTrace(stage) {
13
+ if (process.env.CODEXHOST_STARTUP_TRACE !== "1") return;
14
+ console.error(
15
+ "[codexhost startup +" + (Date.now() - startupTraceStartedAt) + "ms] npm: " + stage,
16
+ );
17
+ }
18
+ if (
19
+ userArguments.length === 1 &&
20
+ (userArguments[0] === "--version" || userArguments[0] === "-v")
21
+ ) {
22
+ console.log(version);
23
+ process.exit(0);
24
+ }
25
+ startupTrace("entry");
26
+
27
+ const platformPackages = {
28
+ "darwin-arm64": "@liberseek/boft-cli-darwin-arm64",
29
+ "darwin-x64": "@liberseek/boft-cli-darwin-x64",
30
+ "win32-x64": "@liberseek/boft-cli-win32-x64",
31
+ "win32-arm64": "@liberseek/boft-cli-win32-arm64",
32
+ "linux-x64": "@liberseek/boft-cli-linux-x64",
33
+ "linux-arm64": "@liberseek/boft-cli-linux-arm64"
34
+ };
35
+ const platformKey = `${process.platform}-${process.arch}`;
36
+ const platformPackage = platformPackages[platformKey];
37
+ if (!platformPackage) fail(`unsupported platform '${platformKey}'`);
38
+
39
+ const require = createRequire(import.meta.url);
40
+ let packageRoot;
41
+ try {
42
+ packageRoot = path.dirname(require.resolve(`${platformPackage}/package.json`));
43
+ } catch {
44
+ // Local folder installs symlink packages into the source tree; Node realpaths
45
+ // the entry script, so the sibling platform package drops off the resolution
46
+ // chain. Fall back to the npm global layout derived from the bin symlink.
47
+ packageRoot = null;
48
+ if (process.platform !== "win32" && process.argv[1]) {
49
+ const prefix = path.dirname(path.dirname(path.resolve(process.argv[1])));
50
+ const globalPackage = path.join(
51
+ prefix,
52
+ "lib",
53
+ "node_modules",
54
+ platformPackage,
55
+ "package.json",
56
+ );
57
+ if (existsSync(globalPackage)) packageRoot = path.dirname(globalPackage);
58
+ }
59
+ if (!packageRoot) {
60
+ fail(
61
+ `missing optional platform package '${platformPackage}'. Reinstall @liberseek/boft-cli without --omit=optional.`,
62
+ );
63
+ }
64
+ }
65
+
66
+ startupTrace("platform package resolved");
67
+ const executableSuffix = process.platform === "win32" ? ".exe" : "";
68
+ const launcher = path.join(packageRoot, "bin", `codexhost${executableSuffix}`);
69
+ const shim = path.join(packageRoot, "libexec", `codexhost-shim${executableSuffix}`);
70
+ const hostRuntime = path.join(packageRoot, "app", "host-runtime.mjs");
71
+ const desktopController = path.join(packageRoot, "app", "desktop-controller.mjs");
72
+ const rendererExtension = path.join(packageRoot, "app", "renderer-extension.js");
73
+
74
+ function fail(message) {
75
+ console.error(`codexhost: ${message}`);
76
+ process.exit(1);
77
+ }
78
+
79
+ for (const [label, filePath] of [
80
+ ["launcher", launcher],
81
+ ["shim", shim],
82
+ ["host runtime", hostRuntime],
83
+ ["desktop controller", desktopController],
84
+ ["renderer extension", rendererExtension],
85
+ ]) {
86
+ if (!existsSync(filePath)) fail(`missing ${label}: ${filePath}`);
87
+ }
88
+
89
+ function existingFile(filePath) {
90
+ return typeof filePath === "string" && filePath.length > 0 && existsSync(filePath)
91
+ ? filePath
92
+ : undefined;
93
+ }
94
+ function officialNpmCliPath(nodePath) {
95
+ return process.platform === "win32"
96
+ ? path.join(path.dirname(nodePath), "node_modules", "npm", "bin", "npm-cli.js")
97
+ : path.join(
98
+ path.dirname(path.dirname(nodePath)),
99
+ "lib",
100
+ "node_modules",
101
+ "npm",
102
+ "bin",
103
+ "npm-cli.js",
104
+ );
105
+ }
106
+ function homebrewNpmCliPath(nodePath) {
107
+ if (process.platform === "win32") return undefined;
108
+ const segments = nodePath.split(path.sep);
109
+ const cellarIndex = segments.lastIndexOf("Cellar");
110
+ if (
111
+ cellarIndex >= 1 &&
112
+ segments[cellarIndex + 1] === "node" &&
113
+ segments.at(-2) === "bin" &&
114
+ segments.at(-1) === "node"
115
+ ) {
116
+ const brewPrefix = segments.slice(0, cellarIndex).join(path.sep);
117
+ return (
118
+ existingFile(
119
+ path.join(brewPrefix, "lib", "node_modules", "npm", "bin", "npm-cli.js"),
120
+ ) ??
121
+ existingFile(
122
+ path.join(
123
+ path.dirname(path.dirname(nodePath)),
124
+ "libexec",
125
+ "lib",
126
+ "node_modules",
127
+ "npm",
128
+ "bin",
129
+ "npm-cli.js",
130
+ ),
131
+ )
132
+ );
133
+ }
134
+ const brewPrefix = process.env.HOMEBREW_PREFIX;
135
+ if (typeof brewPrefix === "string" && brewPrefix.length > 0) {
136
+ return existingFile(
137
+ path.join(brewPrefix, "lib", "node_modules", "npm", "bin", "npm-cli.js"),
138
+ );
139
+ }
140
+ return undefined;
141
+ }
142
+ function pathNpmCliPath() {
143
+ const pathValue = process.env.PATH;
144
+ if (typeof pathValue !== "string" || pathValue.length === 0) return undefined;
145
+ const npmName = process.platform === "win32" ? "npm.cmd" : "npm";
146
+ for (const directory of pathValue.split(path.delimiter)) {
147
+ if (!directory) continue;
148
+ const candidate = path.join(directory, npmName);
149
+ if (!existsSync(candidate)) continue;
150
+ try {
151
+ const resolved = realpathSync(candidate);
152
+ if (path.basename(resolved) === "npm-cli.js") return resolved;
153
+ } catch {
154
+ continue;
155
+ }
156
+ }
157
+ return undefined;
158
+ }
159
+ const npmCliPath =
160
+ existingFile(process.env.npm_execpath) ??
161
+ existingFile(officialNpmCliPath(process.execPath)) ??
162
+ homebrewNpmCliPath(process.execPath) ??
163
+ pathNpmCliPath();
164
+ if (!npmCliPath) fail("could not locate the npm CLI used to update this global installation");
165
+ const updateEnvironment = {
166
+ ...process.env,
167
+ CODEXHOST_NPM_NODE_PATH: process.execPath,
168
+ CODEXHOST_NPM_CLI_PATH: path.resolve(npmCliPath),
169
+ CODEXHOST_NPM_LAUNCHER_PATH: fileURLToPath(import.meta.url),
170
+ CODEXHOST_NPM_PACKAGE_ROOT: packageRoot,
171
+ };
172
+ // A managed SSH installation deliberately exports these variables from the
173
+ // remote login profile so stock Codex can enter the remote Host. When this npm
174
+ // command starts the local Desktop on that same machine, replace the remote
175
+ // bootstrap with a local data root. CODEXHOST_CLAUDE_COMMAND is intentionally
176
+ // shared and therefore preserved.
177
+ const remoteSshBootstrapEnvironment = [
178
+ "CODEX_INSTALL_DIR",
179
+ "CODEXHOST_DATA_DIR",
180
+ "CODEXHOST_DEFAULT_AGENT",
181
+ "CODEXHOST_HOST_NODE_PATH",
182
+ "CODEXHOST_HOST_RUNTIME_PATH",
183
+ "CODEXHOST_REMOTE_SSH_MANAGED",
184
+ "CODEXHOST_STOCK_CODEX_PATH",
185
+ ];
186
+ if (updateEnvironment.CODEXHOST_REMOTE_SSH_MANAGED === "1") {
187
+ for (const name of remoteSshBootstrapEnvironment) delete updateEnvironment[name];
188
+ updateEnvironment.CODEXHOST_DATA_DIR = path.join(homedir(), ".codexhost");
189
+ }
190
+
191
+ let launchArguments;
192
+ let remoteArguments = null;
193
+ let brokerArguments = null;
194
+ let delegationArguments = null;
195
+ if (userArguments.length === 0) {
196
+ launchArguments = ["launch"];
197
+ } else if (userArguments[0] === "launch") {
198
+ launchArguments = userArguments;
199
+ } else if (userArguments[0] === "inspect") {
200
+ launchArguments = userArguments;
201
+ } else if (userArguments[0] === "remote") {
202
+ launchArguments = null;
203
+ remoteArguments = userArguments.slice(1);
204
+ } else if (userArguments[0] === "broker") {
205
+ launchArguments = null;
206
+ brokerArguments = userArguments.slice(1);
207
+ } else if (
208
+ userArguments[0] === "harness" ||
209
+ userArguments[0] === "delegate" ||
210
+ userArguments[0] === "thread"
211
+ ) {
212
+ launchArguments = null;
213
+ delegationArguments = userArguments;
214
+ } else if (userArguments[0] === "--help" || userArguments[0] === "-h") {
215
+ console.log(
216
+ [
217
+ "usage:",
218
+ " codexhost",
219
+ " codexhost --version",
220
+ " codexhost inspect",
221
+ " codexhost launch [launcher options]",
222
+ " codexhost remote install|start|stop|status|uninstall",
223
+ " codexhost broker install|status|stop|uninstall",
224
+ " codexhost delegate --help",
225
+ " codexhost harness inspect ...",
226
+ " codexhost delegate start ...",
227
+ " codexhost thread send|cancel|read|wait|list ...",
228
+ "",
229
+ "This npm package uses the current Node.js runtime and the packaged",
230
+ "Rust launcher/shim. Codex Desktop must already be installed.",
231
+ ].join("\n"),
232
+ );
233
+ process.exit(0);
234
+ } else {
235
+ fail(
236
+ `unknown command '${userArguments[0]}'. Run 'codexhost --help' for usage.`,
237
+ );
238
+ }
239
+
240
+ if (launchArguments?.[0] === "launch") {
241
+ const injected = new Set();
242
+ for (let index = 1; index < launchArguments.length; index += 1) {
243
+ const argument = launchArguments[index];
244
+ if (
245
+ argument === "--node" ||
246
+ argument === "--shim" ||
247
+ argument === "--host-runtime" ||
248
+ argument === "--desktop-controller" ||
249
+ argument === "--renderer"
250
+ ) {
251
+ injected.add(argument);
252
+ index += 1;
253
+ }
254
+ }
255
+ const extras = [];
256
+ if (!injected.has("--node")) extras.push("--node", process.execPath);
257
+ if (!injected.has("--shim")) extras.push("--shim", shim);
258
+ if (!injected.has("--host-runtime")) extras.push("--host-runtime", hostRuntime);
259
+ if (!injected.has("--desktop-controller")) {
260
+ extras.push("--desktop-controller", desktopController);
261
+ }
262
+ if (!injected.has("--renderer")) extras.push("--renderer", rendererExtension);
263
+ launchArguments = ["launch", ...extras, ...launchArguments.slice(1)];
264
+ }
265
+
266
+ if (delegationArguments !== null) {
267
+ const child = spawn(
268
+ process.execPath,
269
+ [hostRuntime, "--codexhost-delegation-cli", ...delegationArguments],
270
+ {
271
+ env: {
272
+ ...updateEnvironment,
273
+ CODEXHOST_CLI_PATH: fileURLToPath(import.meta.url),
274
+ },
275
+ stdio: "inherit",
276
+ windowsHide: true,
277
+ },
278
+ );
279
+ child.on("error", (error) => fail(error.message));
280
+ child.on("exit", (code, signal) => {
281
+ if (signal) {
282
+ process.kill(process.pid, signal);
283
+ return;
284
+ }
285
+ process.exit(code ?? 1);
286
+ });
287
+ } else if (brokerArguments !== null) {
288
+ const child = spawn(
289
+ launcher,
290
+ [
291
+ "broker",
292
+ ...brokerArguments,
293
+ "--node", process.execPath, "--host-runtime", hostRuntime,
294
+ ],
295
+ {
296
+ env: updateEnvironment,
297
+ stdio: "inherit",
298
+ windowsHide: true,
299
+ },
300
+ );
301
+ child.on("error", (error) => fail(error.message));
302
+ child.on("exit", (code, signal) => {
303
+ if (signal) {
304
+ process.kill(process.pid, signal);
305
+ return;
306
+ }
307
+ process.exit(code ?? 1);
308
+ });
309
+ } else if (remoteArguments !== null) {
310
+ const runNativeBroker = (command) => {
311
+ const broker = spawn(
312
+ launcher,
313
+ ["broker", command, "--node", process.execPath, "--host-runtime", hostRuntime],
314
+ {
315
+ env: updateEnvironment,
316
+ // remote status is a stable JSON stdout surface. Keep the broker's
317
+ // human-readable status beside it on stderr instead of corrupting JSON.
318
+ stdio: command === "status" ? ["inherit", process.stderr, "inherit"] : "inherit",
319
+ windowsHide: true,
320
+ },
321
+ );
322
+ broker.on("error", (error) => fail(error.message));
323
+ broker.on("exit", (code, signal) => {
324
+ if (signal) {
325
+ process.kill(process.pid, signal);
326
+ return;
327
+ }
328
+ process.exit(code ?? 1);
329
+ });
330
+ };
331
+ const child = spawn(
332
+ process.execPath,
333
+ [
334
+ hostRuntime,
335
+ "--codexhost-remote",
336
+ ...remoteArguments,
337
+ "--node",
338
+ process.execPath,
339
+ "--shim",
340
+ shim,
341
+ "--host-runtime",
342
+ hostRuntime,
343
+ ],
344
+ {
345
+ env: updateEnvironment,
346
+ stdio: "inherit",
347
+ windowsHide: true,
348
+ },
349
+ );
350
+ child.on("error", (error) => fail(error.message));
351
+ child.on("exit", (code, signal) => {
352
+ if (signal) {
353
+ process.kill(process.pid, signal);
354
+ return;
355
+ }
356
+ if (code === 0 && process.platform === "darwin") {
357
+ if (remoteArguments[0] === "install") {
358
+ runNativeBroker("install");
359
+ return;
360
+ }
361
+ if (remoteArguments[0] === "status") {
362
+ runNativeBroker("status");
363
+ return;
364
+ }
365
+ if (remoteArguments[0] === "uninstall") {
366
+ runNativeBroker("uninstall");
367
+ return;
368
+ }
369
+ }
370
+ process.exit(code ?? 1);
371
+ });
372
+ } else if (launchArguments?.[0] === "launch") {
373
+ // The Launcher prints "ready" once the Desktop, Controller, and Host chain
374
+ // are up, then detaches from the terminal to keep supervising. Windows
375
+ // command hosts may clean up a completed command's process tree, so keep the
376
+ // npm parent alive there until the managed Desktop exits. Other platforms
377
+ // return immediately after startup as before.
378
+ startupTrace("spawning Launcher");
379
+ const keepLauncherForeground = process.platform === "win32";
380
+ const child = spawn(launcher, launchArguments, {
381
+ env: updateEnvironment,
382
+ stdio: ["ignore", "pipe", "inherit"],
383
+ windowsHide: true,
384
+ });
385
+ let finished = false;
386
+ const finish = (code) => {
387
+ if (finished) return;
388
+ finished = true;
389
+ startupTrace("Launcher finished startup with code " + code);
390
+ process.exit(code);
391
+ };
392
+ child.stdout.setEncoding("utf8");
393
+ let ready = false;
394
+ let launcherOutput = "";
395
+ const readyMarker = "ready\n";
396
+ child.stdout.on("data", (chunk) => {
397
+ if (ready) return;
398
+ const output = launcherOutput + chunk;
399
+ if (output.includes(readyMarker)) {
400
+ ready = true;
401
+ launcherOutput = "";
402
+ startupTrace("received Launcher ready");
403
+ if (!keepLauncherForeground) finish(0);
404
+ return;
405
+ }
406
+ // Only retain the tail needed to recognize a marker split across chunks.
407
+ launcherOutput = output.slice(1 - readyMarker.length);
408
+ });
409
+ child.on("error", (error) => {
410
+ startupTrace("Launcher spawn failed: " + error.message);
411
+ fail(error.message);
412
+ });
413
+ child.on("exit", (code, signal) => {
414
+ startupTrace(ready ? "Launcher exited after ready" : "Launcher exited before ready");
415
+ if (signal) {
416
+ process.kill(process.pid, signal);
417
+ return;
418
+ }
419
+ finish(code ?? 1);
420
+ });
421
+ } else {
422
+ const child = spawn(launcher, launchArguments, {
423
+ env: updateEnvironment,
424
+ stdio: "inherit",
425
+ windowsHide: true,
426
+ });
427
+ child.on("error", (error) => fail(error.message));
428
+ child.on("exit", (code, signal) => {
429
+ if (signal) {
430
+ process.kill(process.pid, signal);
431
+ return;
432
+ }
433
+ process.exit(code ?? 1);
434
+ });
435
+ }