@companyhelm/cli 0.0.8 → 0.0.11

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.
package/LICENSE CHANGED
@@ -1,201 +1,21 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship, whether in Source or
36
- Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work
38
- (an example is provided in the Appendix below).
39
-
40
- "Derivative Works" shall mean any work, whether in Source or Object
41
- form, that is based on (or derived from) the Work and for which the
42
- editorial revisions, annotations, elaborations, or other modifications
43
- represent, as a whole, an original work of authorship. For the purposes
44
- of this License, Derivative Works shall not include works that remain
45
- separable from, or merely link (or bind by name) to the interfaces of,
46
- the Work and Derivative Works thereof.
47
-
48
- "Contribution" shall mean any work of authorship, including
49
- the original version of the Work and any modifications or additions
50
- to that Work or Derivative Works thereof, that is intentionally
51
- submitted to Licensor for inclusion in the Work by the copyright owner
52
- or by an individual or Legal Entity authorized to submit on behalf of
53
- the copyright owner. For the purposes of this definition, "submitted"
54
- means any form of electronic, verbal, or written communication sent
55
- to the Licensor or its representatives, including but not limited to
56
- communication on electronic mailing lists, source code control systems,
57
- and issue tracking systems that are managed by, or on behalf of, the
58
- Licensor for the purpose of discussing and improving the Work, but
59
- excluding communication that is conspicuously marked or otherwise
60
- designated in writing by the copyright owner as "Not a Contribution."
61
-
62
- "Contributor" shall mean Licensor and any individual or Legal Entity
63
- on behalf of whom a Contribution has been received by Licensor and
64
- subsequently incorporated within the Work.
65
-
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
67
- this License, each Contributor hereby grants to You a perpetual,
68
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
- copyright license to reproduce, prepare Derivative Works of,
70
- publicly display, publicly perform, sublicense, and distribute the
71
- Work and such Derivative Works in Source or Object form.
72
-
73
- 3. Grant of Patent License. Subject to the terms and conditions of
74
- this License, each Contributor hereby grants to You a perpetual,
75
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
- (except as stated in this section) patent license to make, have made,
77
- use, offer to sell, sell, import, and otherwise transfer the Work,
78
- where such license applies only to those patent claims licensable
79
- by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by combination of their Contribution(s)
81
- with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a
83
- cross-claim or counterclaim in a lawsuit) alleging that the Work
84
- or a Contribution incorporated within the Work constitutes direct
85
- or contributory patent infringement, then any patent licenses
86
- granted to You under this License for that Work shall terminate
87
- as of the date such litigation is filed.
88
-
89
- 4. Redistribution. You may reproduce and distribute copies of the
90
- Work or Derivative Works thereof in any medium, with or without
91
- modifications, and in Source or Object form, provided that You
92
- meet the following conditions:
93
-
94
- (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
96
-
97
- (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
99
-
100
- (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
105
-
106
- (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
122
-
123
- You may add Your own copyright statement to Your modifications and
124
- may provide additional or different license terms and conditions
125
- for use, reproduction, or distribution of Your modifications, or
126
- for any such Derivative Works as a whole, provided Your use,
127
- reproduction, and distribution of the Work otherwise complies with
128
- the conditions stated in this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work
132
- by You to the Licensor shall be under the terms and conditions of
133
- this License, without any additional terms or conditions.
134
- Notwithstanding the above, nothing herein shall supersede or modify
135
- the terms of any separate license agreement you may have executed
136
- with Licensor regarding such Contributions.
137
-
138
- 6. Trademarks. This License does not grant permission to use the trade
139
- names, trademarks, service marks, or product names of the Licensor,
140
- except as required for reasonable and customary use in describing the
141
- origin of the Work and reproducing the content of the NOTICE file.
142
-
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
144
- agreed to in writing, Licensor provides the Work (and each
145
- Contributor provides its Contributions) on an "AS IS" BASIS,
146
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
- implied, including, without limitation, any warranties or conditions
148
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
- PARTICULAR PURPOSE. You are solely responsible for determining the
150
- appropriateness of using or redistributing the Work and assume any
151
- risks associated with Your exercise of permissions under this License.
152
-
153
- 8. Limitation of Liability. In no event and under no legal theory,
154
- whether in tort (including negligence), contract, or otherwise,
155
- unless required by applicable law (such as deliberate and grossly
156
- negligent acts) or agreed to in writing, shall any Contributor be
157
- liable to You for damages, including any direct, indirect, special,
158
- incidental, or consequential damages of any character arising as a
159
- result of this License or out of the use or inability to use the
160
- Work (including but not limited to damages for loss of goodwill,
161
- work stoppage, computer failure or malfunction, or any and all
162
- other commercial damages or losses), even if such Contributor
163
- has been advised of the possibility of such damages.
164
-
165
- 9. Accepting Warranty or Additional Liability. While redistributing
166
- the Work or Derivative Works thereof, You may choose to offer,
167
- and charge a fee for, acceptance of support, warranty, indemnity,
168
- or other liability obligations and/or rights consistent with this
169
- License. However, in accepting such obligations, You may act only
170
- on Your own behalf and on Your sole responsibility, not on behalf
171
- of any other Contributor, and only if You agree to indemnify,
172
- defend, and hold each Contributor harmless for any liability
173
- incurred by, or claims asserted against, such Contributor by reason
174
- of your accepting any such warranty or additional liability.
175
-
176
- END OF TERMS AND CONDITIONS
177
-
178
- APPENDIX: How to apply the Apache License to your work.
179
-
180
- To apply the Apache License to your work, attach the following
181
- boilerplate notice, with the fields enclosed by brackets "[]"
182
- replaced with your own identifying information. (Don't include
183
- the brackets!) The text should be enclosed in the appropriate
184
- comment syntax for the file format. We also recommend that a
185
- file or class name and description of purpose be included on the
186
- same "printed page" as the copyright notice for easier
187
- identification within third-party archives.
188
-
189
- Copyright [yyyy] [name of copyright owner]
190
-
191
- Licensed under the Apache License, Version 2.0 (the "License");
192
- you may not use this file except in compliance with the License.
193
- You may obtain a copy of the License at
194
-
195
- http://www.apache.org/licenses/LICENSE-2.0
196
-
197
- Unless required by applicable law or agreed to in writing, software
198
- distributed under the License is distributed on an "AS IS" BASIS,
199
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
- See the License for the specific language governing permissions and
201
- limitations under the License.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 CompanyHelm
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -55,4 +55,4 @@ Development and maintenance notes live in [DEVELOPING.md](./DEVELOPING.md).
55
55
 
56
56
  ## License
57
57
 
58
- Apache-2.0
58
+ MIT
@@ -1 +1 @@
1
- 0.0.8
1
+ 0.0.9
package/dist/cli.js CHANGED
@@ -4,6 +4,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
4
4
  const node_fs_1 = require("node:fs");
5
5
  const node_path_1 = require("node:path");
6
6
  const commander_1 = require("commander");
7
+ const global_options_js_1 = require("./commands/global-options.js");
7
8
  const register_commands_js_1 = require("./commands/register-commands.js");
8
9
  function getVersion() {
9
10
  try {
@@ -20,7 +21,11 @@ program
20
21
  .name("companyhelm")
21
22
  .description("Run coding agents in fully isolated Docker sandboxes, locally.")
22
23
  .version(getVersion());
24
+ (0, global_options_js_1.addGlobalOptions)(program);
23
25
  (0, register_commands_js_1.registerCommands)(program);
26
+ program.hook("preAction", (_thisCommand, actionCommand) => {
27
+ (0, global_options_js_1.applyGlobalOptionEnvironment)(actionCommand);
28
+ });
24
29
  function formatCliError(error) {
25
30
  if (error instanceof commander_1.CommanderError) {
26
31
  return {
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CONFIG_PATH_OPTION_DESCRIPTION = void 0;
4
+ exports.addGlobalOptions = addGlobalOptions;
5
+ exports.applyGlobalOptionEnvironment = applyGlobalOptionEnvironment;
6
+ const config_js_1 = require("../config.js");
7
+ exports.CONFIG_PATH_OPTION_DESCRIPTION = `Config directory override (defaults to $${config_js_1.CONFIG_PATH_ENV} or ${config_js_1.DEFAULT_CONFIG_DIRECTORY}).`;
8
+ function addGlobalOptions(program) {
9
+ return program.option("--config-path <path>", exports.CONFIG_PATH_OPTION_DESCRIPTION);
10
+ }
11
+ function applyGlobalOptionEnvironment(command) {
12
+ const options = command.optsWithGlobals();
13
+ if (typeof options.configPath !== "string") {
14
+ return;
15
+ }
16
+ const configPath = options.configPath.trim();
17
+ if (configPath.length > 0) {
18
+ process.env[config_js_1.CONFIG_PATH_ENV] = configPath;
19
+ }
20
+ }
@@ -43,6 +43,7 @@ exports.isNoRunningTurnInterruptError = isNoRunningTurnInterruptError;
43
43
  exports.normalizeThreadAgentApiUrlForRuntime = normalizeThreadAgentApiUrlForRuntime;
44
44
  exports.extractThreadNameUpdateFromNotification = extractThreadNameUpdateFromNotification;
45
45
  exports.extractServerMessageRequestId = extractServerMessageRequestId;
46
+ exports.runCommandLoop = runCommandLoop;
46
47
  exports.isInternalDaemonChildProcess = isInternalDaemonChildProcess;
47
48
  exports.runDetachedDaemonProcess = runDetachedDaemonProcess;
48
49
  exports.sendDaemonParentMessage = sendDaemonParentMessage;
@@ -73,6 +74,8 @@ const db_js_1 = require("../state/db.js");
73
74
  const schema_js_1 = require("../state/schema.js");
74
75
  const daemon_js_1 = require("../utils/daemon.js");
75
76
  const logger_js_1 = require("../utils/logger.js");
77
+ const path_js_1 = require("../utils/path.js");
78
+ const terminal_js_1 = require("../utils/terminal.js");
76
79
  const workspace_agents_js_1 = require("../service/workspace_agents.js");
77
80
  const COMMAND_CHANNEL_CONNECT_RETRY_DELAY_MS = 1000;
78
81
  const COMMAND_CHANNEL_OPEN_TIMEOUT_MS = 5000;
@@ -94,6 +97,12 @@ const YOLO_SANDBOX_POLICY = { type: "dangerFullAccess" };
94
97
  const DOCKER_INTERNAL_HOSTNAME = "host.docker.internal";
95
98
  const LOCALHOST_HOSTNAMES = new Set(["localhost", "127.0.0.1", "0.0.0.0", "::1"]);
96
99
  const DAEMON_STARTUP_TIMEOUT_MS = 15000;
100
+ class RootCommandInterruptedError extends Error {
101
+ constructor(message = "Root command interrupted.") {
102
+ super(message);
103
+ this.name = "RootCommandInterruptedError";
104
+ }
105
+ }
97
106
  const threadAppServerSessions = new Map();
98
107
  const threadRolloutPaths = new Map();
99
108
  function rememberThreadRolloutPath(threadId, rolloutPath) {
@@ -1369,6 +1378,16 @@ async function sendRequestError(commandChannel, errorMessage, requestId) {
1369
1378
  });
1370
1379
  await commandChannel.send(message);
1371
1380
  }
1381
+ async function sendHeartbeatResponse(commandChannel, requestId) {
1382
+ const message = (0, protobuf_1.create)(protos_1.ClientMessageSchema, {
1383
+ requestId,
1384
+ payload: {
1385
+ case: "heartbeatResponse",
1386
+ value: {},
1387
+ },
1388
+ });
1389
+ await commandChannel.send(message);
1390
+ }
1372
1391
  async function sendThreadUpdate(commandChannel, threadId, status, requestId) {
1373
1392
  const message = (0, protobuf_1.create)(protos_1.ClientMessageSchema, {
1374
1393
  requestId,
@@ -2166,6 +2185,9 @@ async function runCommandLoop(cfg, commandChannel, commandMessageSink, apiClient
2166
2185
  case "interruptTurnRequest":
2167
2186
  await handleInterruptTurnRequest(cfg, commandMessageSink, serverMessage.request.value, logger);
2168
2187
  break;
2188
+ case "heartbeatRequest":
2189
+ await sendHeartbeatResponse(commandMessageSink, requestId);
2190
+ break;
2169
2191
  default:
2170
2192
  break;
2171
2193
  }
@@ -2182,16 +2204,104 @@ function buildGrpcAuthCallOptions(secret) {
2182
2204
  function isInternalDaemonChildProcess() {
2183
2205
  return process.env[daemon_js_1.DAEMON_CHILD_ENV] === "1";
2184
2206
  }
2207
+ function abortErrorFromSignal(signal) {
2208
+ return signal.reason instanceof Error ? signal.reason : new RootCommandInterruptedError();
2209
+ }
2210
+ function throwIfAborted(signal) {
2211
+ if (signal.aborted) {
2212
+ throw abortErrorFromSignal(signal);
2213
+ }
2214
+ }
2215
+ function raceWithAbort(promise, signal) {
2216
+ if (signal.aborted) {
2217
+ return Promise.reject(abortErrorFromSignal(signal));
2218
+ }
2219
+ return Promise.race([
2220
+ promise,
2221
+ new Promise((_, reject) => {
2222
+ const onAbort = () => {
2223
+ signal.removeEventListener("abort", onAbort);
2224
+ reject(abortErrorFromSignal(signal));
2225
+ };
2226
+ signal.addEventListener("abort", onAbort, { once: true });
2227
+ }),
2228
+ ]);
2229
+ }
2230
+ function delayWithAbort(delayMs, signal) {
2231
+ if (signal.aborted) {
2232
+ return Promise.reject(abortErrorFromSignal(signal));
2233
+ }
2234
+ return new Promise((resolve, reject) => {
2235
+ const timeout = setTimeout(() => {
2236
+ signal.removeEventListener("abort", onAbort);
2237
+ resolve();
2238
+ }, delayMs);
2239
+ const onAbort = () => {
2240
+ clearTimeout(timeout);
2241
+ signal.removeEventListener("abort", onAbort);
2242
+ reject(abortErrorFromSignal(signal));
2243
+ };
2244
+ signal.addEventListener("abort", onAbort, { once: true });
2245
+ });
2246
+ }
2247
+ function installRootInterruptHandlers(logger, onInterrupt) {
2248
+ const controller = new AbortController();
2249
+ const requestInterrupt = (reason) => {
2250
+ if (controller.signal.aborted) {
2251
+ return;
2252
+ }
2253
+ (0, terminal_js_1.restoreInteractiveTerminalState)();
2254
+ process.exitCode = 130;
2255
+ logger.info(`${reason} received. Shutting down root command.`);
2256
+ try {
2257
+ onInterrupt();
2258
+ }
2259
+ catch {
2260
+ // Best-effort shutdown hook.
2261
+ }
2262
+ controller.abort(new RootCommandInterruptedError(reason));
2263
+ };
2264
+ const handleSigint = () => {
2265
+ requestInterrupt("SIGINT");
2266
+ };
2267
+ const handleSigterm = () => {
2268
+ requestInterrupt("SIGTERM");
2269
+ };
2270
+ const handleStdinData = (chunk) => {
2271
+ const input = typeof chunk === "string" ? chunk : chunk.toString("utf8");
2272
+ if ((0, terminal_js_1.containsCtrlCInterruptInput)(input)) {
2273
+ requestInterrupt("Ctrl-C");
2274
+ }
2275
+ };
2276
+ process.on("SIGINT", handleSigint);
2277
+ process.on("SIGTERM", handleSigterm);
2278
+ if (process.stdin.isTTY) {
2279
+ process.stdin.on("data", handleStdinData);
2280
+ process.stdin.resume();
2281
+ }
2282
+ return {
2283
+ signal: controller.signal,
2284
+ dispose: () => {
2285
+ process.off("SIGINT", handleSigint);
2286
+ process.off("SIGTERM", handleSigterm);
2287
+ if (process.stdin.isTTY) {
2288
+ process.stdin.off("data", handleStdinData);
2289
+ }
2290
+ },
2291
+ };
2292
+ }
2185
2293
  function resolveEffectiveDaemonLogPath(cfg) {
2186
2294
  const envPath = process.env[daemon_js_1.DAEMON_LOG_PATH_ENV];
2187
2295
  if (envPath && envPath.trim().length > 0) {
2188
- return envPath;
2296
+ return (0, path_js_1.expandHome)(envPath);
2189
2297
  }
2190
2298
  return (0, daemon_js_1.resolveDaemonLogPath)(cfg.state_db_path);
2191
2299
  }
2192
2300
  async function runDetachedDaemonProcess(options) {
2193
2301
  const cfg = buildRootConfig(options);
2194
- const logPath = (0, daemon_js_1.resolveDaemonLogPath)(cfg.state_db_path);
2302
+ const logPath = options.logPath && options.logPath.trim().length > 0
2303
+ ? (0, path_js_1.expandHome)(options.logPath)
2304
+ : (0, daemon_js_1.resolveDaemonLogPath)(cfg.state_db_path);
2195
2305
  (0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(logPath), { recursive: true });
2196
2306
  const logFd = (0, node_fs_1.openSync)(logPath, "a");
2197
2307
  try {
@@ -2274,6 +2384,7 @@ async function runRootCommand(options, runtimeOptions) {
2274
2384
  }
2275
2385
  if (!configuredSdks) {
2276
2386
  await (0, startup_js_1.startup)(cfg);
2387
+ (0, terminal_js_1.restoreInteractiveTerminalState)();
2277
2388
  }
2278
2389
  await refreshCodexModelsForRegistration(cfg, logger);
2279
2390
  const registerRequest = await buildRegisterRunnerRequest(cfg);
@@ -2287,16 +2398,25 @@ async function runRootCommand(options, runtimeOptions) {
2287
2398
  logger,
2288
2399
  });
2289
2400
  let reconnectAttempt = 0;
2401
+ let activeApiClient = null;
2402
+ let activeCommandChannel = null;
2403
+ const interruptState = installRootInterruptHandlers(logger, () => {
2404
+ activeCommandChannel?.cancel();
2405
+ activeApiClient?.close();
2406
+ });
2290
2407
  try {
2291
2408
  while (true) {
2409
+ throwIfAborted(interruptState.signal);
2292
2410
  const apiClient = new companyhelm_api_client_js_1.CompanyhelmApiClient({ apiUrl: cfg.companyhelm_api_url, logger });
2411
+ activeApiClient = apiClient;
2293
2412
  let commandChannel = null;
2294
2413
  let githubInstallationsSyncAbortController = null;
2295
2414
  let githubInstallationsSyncTask = null;
2296
2415
  try {
2297
2416
  reconnectAttempt += 1;
2298
2417
  commandChannel = await apiClient.connect(registerRequest, apiCallOptions);
2299
- await commandChannel.waitForOpen(COMMAND_CHANNEL_OPEN_TIMEOUT_MS);
2418
+ activeCommandChannel = commandChannel;
2419
+ await raceWithAbort(commandChannel.waitForOpen(COMMAND_CHANNEL_OPEN_TIMEOUT_MS), interruptState.signal);
2300
2420
  commandMessageSink.bind(commandChannel);
2301
2421
  const bufferedMessages = commandMessageSink.getBufferedMessageCount();
2302
2422
  if (bufferedMessages > 0) {
@@ -2312,10 +2432,13 @@ async function runRootCommand(options, runtimeOptions) {
2312
2432
  logger.warn(`GitHub installation sync loop exited unexpectedly: ${toErrorMessage(error)}`);
2313
2433
  }
2314
2434
  });
2315
- await runCommandLoop(cfg, commandChannel, commandMessageSink, apiClient, apiCallOptions, logger);
2435
+ await raceWithAbort(runCommandLoop(cfg, commandChannel, commandMessageSink, apiClient, apiCallOptions, logger), interruptState.signal);
2316
2436
  logger.warn("CompanyHelm API command channel closed. Reconnecting...");
2317
2437
  }
2318
2438
  catch (error) {
2439
+ if (error instanceof RootCommandInterruptedError) {
2440
+ return;
2441
+ }
2319
2442
  const failureMessage = formatApiConnectionFailureMessage(error, cfg.companyhelm_api_url, options.secret);
2320
2443
  const diagnostics = formatApiConnectionFailureDiagnostics(error);
2321
2444
  if (diagnostics) {
@@ -2333,17 +2456,25 @@ async function runRootCommand(options, runtimeOptions) {
2333
2456
  }
2334
2457
  void githubInstallationsSyncTask;
2335
2458
  if (commandChannel) {
2459
+ commandChannel.cancel();
2336
2460
  commandMessageSink.unbind(commandChannel);
2337
2461
  }
2338
2462
  else {
2339
2463
  commandMessageSink.unbind();
2340
2464
  }
2465
+ if (activeCommandChannel === commandChannel) {
2466
+ activeCommandChannel = null;
2467
+ }
2468
+ if (activeApiClient === apiClient) {
2469
+ activeApiClient = null;
2470
+ }
2341
2471
  apiClient.close();
2342
2472
  }
2343
- await new Promise((resolve) => setTimeout(resolve, COMMAND_CHANNEL_CONNECT_RETRY_DELAY_MS));
2473
+ await delayWithAbort(COMMAND_CHANNEL_CONNECT_RETRY_DELAY_MS, interruptState.signal);
2344
2474
  }
2345
2475
  }
2346
2476
  finally {
2477
+ interruptState.dispose();
2347
2478
  const droppedMessages = commandMessageSink.getDroppedMessageCount();
2348
2479
  if (droppedMessages > 0) {
2349
2480
  logger.warn(`Dropped ${droppedMessages} outbound client message(s) while command channel was disconnected.`);
@@ -1,13 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.addRunnerStartOptions = addRunnerStartOptions;
4
+ const global_options_js_1 = require("../global-options.js");
4
5
  function addRunnerStartOptions(command) {
5
6
  return command
6
- .option("--config-path <path>", "Config directory override (defaults to ~/.config/companyhelm).")
7
+ .option("--config-path <path>", global_options_js_1.CONFIG_PATH_OPTION_DESCRIPTION)
7
8
  .option("--server-url <url>", "CompanyHelm gRPC API URL override.")
8
9
  .option("--agent-api-url <url>", "Agent gRPC API URL for companyhelm-agent in runtime containers (localhost is rewritten to http://host.docker.internal).")
9
10
  .option("--secret <secret>", "Bearer secret used as gRPC Authorization header.")
10
- .option("--state-db-path <path>", "State database path override (defaults to ~/.local/share/companyhelm/state.db).")
11
+ .option("--state-db-path <path>", "State database path override (defaults to state.db under the active config directory).")
12
+ .option("--log-path <path>", "Daemon log file override.")
11
13
  .option("--use-host-docker-runtime", "Mount host Docker socket into runtime containers instead of creating DinD sidecars.")
12
14
  .option("--host-docker-path <path>", "Host Docker endpoint when --use-host-docker-runtime is enabled (unix:///<socket-path> or tcp://localhost:<port>).")
13
15
  .option("--thread-git-skills-directory <path>", "Container path where thread git skill repositories are cloned before linking into ~/.codex/skills.")
@@ -48,7 +48,7 @@ function registerRunnerStopCommand(runnerCommand) {
48
48
  runnerCommand
49
49
  .command("stop")
50
50
  .description("Stop the local CompanyHelm runner daemon.")
51
- .option("--state-db-path <path>", "State database path override (defaults to ~/.local/share/companyhelm/state.db).")
51
+ .option("--state-db-path <path>", "State database path override (defaults to state.db under the active config directory).")
52
52
  .action(async (options) => {
53
53
  await runRunnerStopCommand(options);
54
54
  });
@@ -0,0 +1,200 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defaultUseDedicatedCodexAuthDependencies = exports.defaultSetCodexHostAuthDependencies = void 0;
4
+ exports.isErrnoException = isErrnoException;
5
+ exports.buildDockerMissingError = buildDockerMissingError;
6
+ exports.ensureDockerAvailable = ensureDockerAvailable;
7
+ exports.listCodexStartupAuthOptions = listCodexStartupAuthOptions;
8
+ exports.setCodexHostAuthInDb = setCodexHostAuthInDb;
9
+ exports.setCodexDedicatedAuthInDb = setCodexDedicatedAuthInDb;
10
+ exports.runSetCodexHostAuth = runSetCodexHostAuth;
11
+ exports.runDedicatedCodexAuth = runDedicatedCodexAuth;
12
+ exports.runUseDedicatedCodexAuth = runUseDedicatedCodexAuth;
13
+ const node_child_process_1 = require("node:child_process");
14
+ const node_fs_1 = require("node:fs");
15
+ const node_path_1 = require("node:path");
16
+ const drizzle_orm_1 = require("drizzle-orm");
17
+ const host_js_1 = require("../../../service/host.js");
18
+ const db_js_1 = require("../../../state/db.js");
19
+ const schema_js_1 = require("../../../state/schema.js");
20
+ const path_js_1 = require("../../../utils/path.js");
21
+ exports.defaultSetCodexHostAuthDependencies = {
22
+ getHostInfoFn: host_js_1.getHostInfo,
23
+ initDbFn: db_js_1.initDb,
24
+ };
25
+ exports.defaultUseDedicatedCodexAuthDependencies = {
26
+ initDbFn: db_js_1.initDb,
27
+ logInfo: console.log,
28
+ logSuccess: console.log,
29
+ spawnCommand: node_child_process_1.spawn,
30
+ spawnSyncCommand: node_child_process_1.spawnSync,
31
+ };
32
+ function isErrnoException(error) {
33
+ return error instanceof Error && "code" in error;
34
+ }
35
+ function buildDockerMissingError() {
36
+ return new Error("Docker is not installed or not available on PATH. Install Docker and retry.");
37
+ }
38
+ function ensureDockerAvailable(spawnSyncCommand) {
39
+ const result = spawnSyncCommand("docker", ["--version"], { stdio: "ignore" });
40
+ if (isErrnoException(result.error) && result.error.code === "ENOENT") {
41
+ throw buildDockerMissingError();
42
+ }
43
+ }
44
+ function listCodexStartupAuthOptions(cfg, getHostInfoFn = host_js_1.getHostInfo) {
45
+ const options = [
46
+ {
47
+ value: "dedicated",
48
+ label: "Dedicated",
49
+ hint: "recommended -- runs Codex login inside a container",
50
+ },
51
+ ];
52
+ const hostInfo = getHostInfoFn(cfg.codex.codex_auth_path);
53
+ if (hostInfo.codexAuthExists) {
54
+ options.push({
55
+ value: "host",
56
+ label: "Host",
57
+ hint: `reuse existing credentials from ${cfg.codex.codex_auth_path}`,
58
+ });
59
+ }
60
+ return options;
61
+ }
62
+ async function setCodexHostAuthInDb(db) {
63
+ const existingSdk = await db.select().from(schema_js_1.agentSdks).where((0, drizzle_orm_1.eq)(schema_js_1.agentSdks.name, "codex")).get();
64
+ if (existingSdk) {
65
+ await db
66
+ .update(schema_js_1.agentSdks)
67
+ .set({ authentication: "host" })
68
+ .where((0, drizzle_orm_1.eq)(schema_js_1.agentSdks.name, "codex"));
69
+ return;
70
+ }
71
+ await db.insert(schema_js_1.agentSdks).values({ name: "codex", authentication: "host" });
72
+ }
73
+ async function setCodexDedicatedAuthInDb(db) {
74
+ const existingSdk = await db.select().from(schema_js_1.agentSdks).where((0, drizzle_orm_1.eq)(schema_js_1.agentSdks.name, "codex")).get();
75
+ if (existingSdk) {
76
+ await db
77
+ .update(schema_js_1.agentSdks)
78
+ .set({ authentication: "dedicated" })
79
+ .where((0, drizzle_orm_1.eq)(schema_js_1.agentSdks.name, "codex"));
80
+ return;
81
+ }
82
+ await db.insert(schema_js_1.agentSdks).values({ name: "codex", authentication: "dedicated" });
83
+ }
84
+ async function runSetCodexHostAuth(cfg, overrides = {}) {
85
+ const deps = { ...exports.defaultSetCodexHostAuthDependencies, ...overrides };
86
+ const authPath = (0, path_js_1.expandHome)(cfg.codex.codex_auth_path);
87
+ const hostInfo = deps.getHostInfoFn(cfg.codex.codex_auth_path);
88
+ if (!hostInfo.codexAuthExists) {
89
+ throw new Error(`Codex host auth file not found at ${authPath}.`);
90
+ }
91
+ const { db, client } = await deps.initDbFn(cfg.state_db_path);
92
+ try {
93
+ await setCodexHostAuthInDb(db);
94
+ }
95
+ finally {
96
+ client.close();
97
+ }
98
+ return authPath;
99
+ }
100
+ async function runDedicatedCodexAuth(cfg, db, deps) {
101
+ ensureDockerAvailable(deps.spawnSyncCommand);
102
+ const port = cfg.codex.codex_auth_port;
103
+ const socatPort = port + 1;
104
+ const containerName = `companyhelm-codex-auth-${Date.now()}`;
105
+ deps.logInfo("Starting Codex login inside a container...");
106
+ deps.logInfo("A browser URL will appear -- open it to complete authentication.");
107
+ const configDir = (0, path_js_1.expandHome)(cfg.config_directory);
108
+ if (!(0, node_fs_1.existsSync)(configDir)) {
109
+ (0, node_fs_1.mkdirSync)(configDir, { recursive: true });
110
+ }
111
+ const destPath = (0, node_path_1.join)(configDir, cfg.codex.codex_auth_file_path);
112
+ let authCopied = false;
113
+ await new Promise((resolve, reject) => {
114
+ let settled = false;
115
+ let poll;
116
+ const rejectOnce = (error) => {
117
+ if (settled) {
118
+ return;
119
+ }
120
+ settled = true;
121
+ if (poll) {
122
+ clearInterval(poll);
123
+ }
124
+ deps.spawnSyncCommand("docker", ["rm", "-f", containerName], { stdio: "ignore" });
125
+ reject(error);
126
+ };
127
+ const resolveOnce = () => {
128
+ if (settled) {
129
+ return;
130
+ }
131
+ settled = true;
132
+ if (poll) {
133
+ clearInterval(poll);
134
+ }
135
+ resolve();
136
+ };
137
+ const child = deps.spawnCommand("docker", [
138
+ "run",
139
+ "-it",
140
+ "--name",
141
+ containerName,
142
+ "-p",
143
+ `${port}:${socatPort}`,
144
+ "--entrypoint",
145
+ "bash",
146
+ cfg.runtime_image,
147
+ "-c",
148
+ `source "$NVM_DIR/nvm.sh"; socat TCP-LISTEN:${socatPort},fork,bind=0.0.0.0,reuseaddr TCP:127.0.0.1:${port} 2>/dev/null & codex`,
149
+ ], { stdio: "inherit" });
150
+ child.on("error", (error) => {
151
+ if (isErrnoException(error) && error.code === "ENOENT") {
152
+ rejectOnce(buildDockerMissingError());
153
+ return;
154
+ }
155
+ rejectOnce(new Error(`Failed to start Codex login container: ${error.message}`));
156
+ });
157
+ poll = setInterval(() => {
158
+ if (settled) {
159
+ return;
160
+ }
161
+ const check = deps.spawnSyncCommand("docker", ["exec", containerName, "sh", "-c", `test -f ${cfg.codex.codex_auth_path}`], {
162
+ stdio: "ignore",
163
+ });
164
+ if (check.status === 0) {
165
+ const resolveResult = deps.spawnSyncCommand("docker", ["exec", containerName, "sh", "-c", `echo ${cfg.codex.codex_auth_path}`], {
166
+ encoding: "utf-8",
167
+ });
168
+ const containerAuthAbsPath = resolveResult.stdout.trim();
169
+ const cpResult = deps.spawnSyncCommand("docker", ["cp", `${containerName}:${containerAuthAbsPath}`, destPath], {
170
+ stdio: "ignore",
171
+ });
172
+ if (cpResult.status !== 0) {
173
+ rejectOnce(new Error("Failed to extract auth file from container."));
174
+ return;
175
+ }
176
+ authCopied = true;
177
+ deps.spawnSyncCommand("docker", ["rm", "-f", containerName], { stdio: "ignore" });
178
+ resolveOnce();
179
+ }
180
+ }, 1000);
181
+ child.on("exit", () => {
182
+ if (!authCopied) {
183
+ rejectOnce(new Error("Codex login failed or was cancelled."));
184
+ }
185
+ });
186
+ });
187
+ await setCodexDedicatedAuthInDb(db);
188
+ deps.logSuccess(`Codex auth saved to ${destPath}`);
189
+ return destPath;
190
+ }
191
+ async function runUseDedicatedCodexAuth(cfg, overrides = {}) {
192
+ const deps = { ...exports.defaultUseDedicatedCodexAuthDependencies, ...overrides };
193
+ const { db, client } = await deps.initDbFn(cfg.state_db_path);
194
+ try {
195
+ return await runDedicatedCodexAuth(cfg, db, deps);
196
+ }
197
+ finally {
198
+ client.close();
199
+ }
200
+ }
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.registerCodexSdkCommands = registerCodexSdkCommands;
4
+ const use_dedicated_auth_js_1 = require("./use-dedicated-auth.js");
5
+ const use_host_auth_js_1 = require("./use-host-auth.js");
6
+ function registerCodexSdkCommands(sdkCommand) {
7
+ const codexCommand = sdkCommand
8
+ .command("codex")
9
+ .description("Manage Codex SDK authentication.");
10
+ (0, use_host_auth_js_1.registerSdkCodexUseHostAuthCommand)(codexCommand);
11
+ (0, use_dedicated_auth_js_1.registerSdkCodexUseDedicatedAuthCommand)(codexCommand);
12
+ }
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runSdkCodexUseDedicatedAuthCommand = runSdkCodexUseDedicatedAuthCommand;
4
+ exports.registerSdkCodexUseDedicatedAuthCommand = registerSdkCodexUseDedicatedAuthCommand;
5
+ const config_js_1 = require("../../../config.js");
6
+ const auth_js_1 = require("./auth.js");
7
+ async function runSdkCodexUseDedicatedAuthCommand(cfg = config_js_1.config.parse({}), overrides = {}) {
8
+ const deps = { ...auth_js_1.defaultUseDedicatedCodexAuthDependencies, ...overrides };
9
+ await (0, auth_js_1.runUseDedicatedCodexAuth)(cfg, deps);
10
+ }
11
+ function registerSdkCodexUseDedicatedAuthCommand(codexCommand) {
12
+ codexCommand
13
+ .command("use-dedicated-auth")
14
+ .description("Configure the Codex SDK to use dedicated authentication.")
15
+ .action(async () => {
16
+ await runSdkCodexUseDedicatedAuthCommand();
17
+ });
18
+ }
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runSdkCodexUseHostAuthCommand = runSdkCodexUseHostAuthCommand;
4
+ exports.registerSdkCodexUseHostAuthCommand = registerSdkCodexUseHostAuthCommand;
5
+ const config_js_1 = require("../../../config.js");
6
+ const auth_js_1 = require("./auth.js");
7
+ async function runSdkCodexUseHostAuthCommand(cfg = config_js_1.config.parse({}), overrides = {}) {
8
+ const deps = { ...auth_js_1.defaultSetCodexHostAuthDependencies, ...overrides };
9
+ const authPath = await (0, auth_js_1.runSetCodexHostAuth)(cfg, deps);
10
+ console.log(`Codex SDK configured with host authentication using ${authPath}.`);
11
+ }
12
+ function registerSdkCodexUseHostAuthCommand(codexCommand) {
13
+ codexCommand
14
+ .command("use-host-auth")
15
+ .description("Configure the Codex SDK to use host authentication.")
16
+ .action(async () => {
17
+ await runSdkCodexUseHostAuthCommand();
18
+ });
19
+ }
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.registerSdkCommands = registerSdkCommands;
4
+ const register_codex_sdk_commands_js_1 = require("./codex/register-codex-sdk-commands.js");
4
5
  const list_js_1 = require("./list.js");
5
6
  const refresh_models_js_1 = require("./refresh-models.js");
6
7
  function registerSdkCommands(program) {
@@ -9,4 +10,5 @@ function registerSdkCommands(program) {
9
10
  .description("Manage configured SDKs and their model capabilities.");
10
11
  (0, list_js_1.registerSdkListCommand)(sdkCommand);
11
12
  (0, refresh_models_js_1.registerSdkRefreshModelsCommand)(sdkCommand);
13
+ (0, register_codex_sdk_commands_js_1.registerCodexSdkCommands)(sdkCommand);
12
14
  }
@@ -37,66 +37,34 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.startup = startup;
40
- const node_fs_1 = require("node:fs");
41
- const node_path_1 = require("node:path");
42
40
  const node_child_process_1 = require("node:child_process");
43
41
  const p = __importStar(require("@clack/prompts"));
44
42
  const figlet_1 = __importDefault(require("figlet"));
45
43
  const config_js_1 = require("../config.js");
46
44
  const db_js_1 = require("../state/db.js");
47
45
  const schema_js_1 = require("../state/schema.js");
48
- const host_js_1 = require("../service/host.js");
49
46
  const refresh_models_js_1 = require("../service/sdk/refresh_models.js");
50
- const path_js_1 = require("../utils/path.js");
47
+ const terminal_js_1 = require("../utils/terminal.js");
48
+ const auth_js_1 = require("./sdk/codex/auth.js");
51
49
  function banner() {
52
50
  console.log();
53
51
  console.log(figlet_1.default.textSync("CompanyHelm", { font: "Small" }));
54
52
  console.log();
55
53
  }
56
- function isErrnoException(error) {
57
- return error instanceof Error && "code" in error;
58
- }
59
- function buildDockerMissingError() {
60
- return new Error("Docker is not installed or not available on PATH. Install Docker and retry.");
61
- }
62
54
  const defaultStartupDependencies = {
63
- getHostInfoFn: host_js_1.getHostInfo,
55
+ getHostInfoFn: auth_js_1.defaultSetCodexHostAuthDependencies.getHostInfoFn,
64
56
  initDbFn: db_js_1.initDb,
65
57
  promptApi: p,
66
58
  refreshSdkModelsFn: refresh_models_js_1.refreshSdkModels,
67
59
  spawnCommand: node_child_process_1.spawn,
68
60
  spawnSyncCommand: node_child_process_1.spawnSync,
69
61
  };
70
- function ensureDockerAvailable(spawnSyncCommand) {
71
- const result = spawnSyncCommand("docker", ["--version"], { stdio: "ignore" });
72
- if (isErrnoException(result.error) && result.error.code === "ENOENT") {
73
- throw buildDockerMissingError();
74
- }
75
- }
76
- function restoreInteractiveTerminalState() {
77
- try {
78
- if (process.stdin.isTTY && typeof process.stdin.setRawMode === "function") {
79
- process.stdin.setRawMode(false);
80
- }
81
- }
82
- catch {
83
- // Best-effort prompt cleanup.
84
- }
85
- try {
86
- if (process.stdout.isTTY) {
87
- process.stdout.write("\u001B[?25h");
88
- }
89
- }
90
- catch {
91
- // Best-effort prompt cleanup.
92
- }
93
- }
94
62
  function exitStartup(code) {
95
- restoreInteractiveTerminalState();
63
+ (0, terminal_js_1.restoreInteractiveTerminalState)();
96
64
  process.exit(code);
97
65
  }
98
66
  async function refreshCodexModelsInStartup(deps) {
99
- ensureDockerAvailable(deps.spawnSyncCommand);
67
+ (0, auth_js_1.ensureDockerAvailable)(deps.spawnSyncCommand);
100
68
  const spinner = deps.promptApi.spinner();
101
69
  const seenStatusMessages = new Set();
102
70
  spinner.start("Preparing Codex runtime image and refreshing model catalog via app-server");
@@ -113,96 +81,6 @@ async function refreshCodexModelsInStartup(deps) {
113
81
  const count = results[0]?.modelCount ?? 0;
114
82
  spinner.stop(`Codex model catalog refreshed (${count} models).`);
115
83
  }
116
- async function dedicatedAuth(cfg, db, deps) {
117
- ensureDockerAvailable(deps.spawnSyncCommand);
118
- const port = cfg.codex.codex_auth_port;
119
- const socatPort = port + 1;
120
- const containerName = `companyhelm-codex-auth-${Date.now()}`;
121
- deps.promptApi.log.info("Starting Codex login inside a container...");
122
- deps.promptApi.log.info("A browser URL will appear -- open it to complete authentication.");
123
- const configDir = (0, path_js_1.expandHome)(cfg.config_directory);
124
- if (!(0, node_fs_1.existsSync)(configDir)) {
125
- (0, node_fs_1.mkdirSync)(configDir, { recursive: true });
126
- }
127
- const destPath = (0, node_path_1.join)(configDir, cfg.codex.codex_auth_file_path);
128
- let authCopied = false;
129
- await new Promise((resolve, reject) => {
130
- let settled = false;
131
- let poll;
132
- const rejectOnce = (error) => {
133
- if (settled) {
134
- return;
135
- }
136
- settled = true;
137
- if (poll) {
138
- clearInterval(poll);
139
- }
140
- deps.spawnSyncCommand("docker", ["rm", "-f", containerName], { stdio: "ignore" });
141
- reject(error);
142
- };
143
- const resolveOnce = () => {
144
- if (settled) {
145
- return;
146
- }
147
- settled = true;
148
- if (poll) {
149
- clearInterval(poll);
150
- }
151
- resolve();
152
- };
153
- const child = deps.spawnCommand("docker", [
154
- "run",
155
- "-it",
156
- "--name",
157
- containerName,
158
- "-p",
159
- `${port}:${socatPort}`,
160
- "--entrypoint",
161
- "bash",
162
- cfg.runtime_image,
163
- "-c",
164
- `source "$NVM_DIR/nvm.sh"; socat TCP-LISTEN:${socatPort},fork,bind=0.0.0.0,reuseaddr TCP:127.0.0.1:${port} 2>/dev/null & codex`,
165
- ], { stdio: "inherit" });
166
- child.on("error", (error) => {
167
- if (isErrnoException(error) && error.code === "ENOENT") {
168
- rejectOnce(buildDockerMissingError());
169
- return;
170
- }
171
- rejectOnce(new Error(`Failed to start Codex login container: ${error.message}`));
172
- });
173
- poll = setInterval(() => {
174
- if (settled) {
175
- return;
176
- }
177
- const check = deps.spawnSyncCommand("docker", ["exec", containerName, "sh", "-c", `test -f ${cfg.codex.codex_auth_path}`], {
178
- stdio: "ignore",
179
- });
180
- if (check.status === 0) {
181
- const resolveResult = deps.spawnSyncCommand("docker", ["exec", containerName, "sh", "-c", `echo ${cfg.codex.codex_auth_path}`], {
182
- encoding: "utf-8",
183
- });
184
- const containerAuthAbsPath = resolveResult.stdout.trim();
185
- const cpResult = deps.spawnSyncCommand("docker", ["cp", `${containerName}:${containerAuthAbsPath}`, destPath], {
186
- stdio: "ignore",
187
- });
188
- if (cpResult.status !== 0) {
189
- rejectOnce(new Error("Failed to extract auth file from container."));
190
- return;
191
- }
192
- authCopied = true;
193
- deps.spawnSyncCommand("docker", ["rm", "-f", containerName], { stdio: "ignore" });
194
- resolveOnce();
195
- }
196
- }, 1000);
197
- child.on("exit", () => {
198
- if (!authCopied) {
199
- rejectOnce(new Error("Codex login failed or was cancelled."));
200
- }
201
- });
202
- });
203
- await db.insert(schema_js_1.agentSdks).values({ name: "codex", authentication: "dedicated" });
204
- deps.promptApi.log.success(`Codex auth saved to ${destPath}`);
205
- }
206
84
  async function selectStartupAuthMode(options, deps) {
207
85
  if (options.length === 1) {
208
86
  return options[0].value;
@@ -230,30 +108,21 @@ async function startup(cfg = config_js_1.config.parse({}), overrides = {}) {
230
108
  return;
231
109
  }
232
110
  deps.promptApi.intro("No agent SDK configured. Let's set up Codex authentication.");
233
- const hostInfo = deps.getHostInfoFn(cfg.codex.codex_auth_path);
234
- const options = [
235
- {
236
- value: "dedicated",
237
- label: "Dedicated",
238
- hint: "recommended -- runs Codex login inside a container",
239
- },
240
- ];
241
- if (hostInfo.codexAuthExists) {
242
- options.push({
243
- value: "host",
244
- label: "Host",
245
- hint: `reuse existing credentials from ${cfg.codex.codex_auth_path}`,
246
- });
247
- }
111
+ const options = (0, auth_js_1.listCodexStartupAuthOptions)(cfg, deps.getHostInfoFn);
248
112
  try {
249
113
  const authMode = await selectStartupAuthMode(options, deps);
250
114
  if (authMode === "host") {
251
- await db.insert(schema_js_1.agentSdks).values({ name: "codex", authentication: "host" });
115
+ await (0, auth_js_1.setCodexHostAuthInDb)(db);
252
116
  await refreshCodexModelsInStartup(deps);
253
117
  deps.promptApi.outro("Codex SDK configured with host authentication.");
254
118
  return;
255
119
  }
256
- await dedicatedAuth(cfg, db, deps);
120
+ await (0, auth_js_1.runDedicatedCodexAuth)(cfg, db, {
121
+ logInfo: deps.promptApi.log.info,
122
+ logSuccess: deps.promptApi.log.success,
123
+ spawnCommand: deps.spawnCommand,
124
+ spawnSyncCommand: deps.spawnSyncCommand,
125
+ });
257
126
  await refreshCodexModelsInStartup(deps);
258
127
  deps.promptApi.outro("Codex login successful!");
259
128
  }
@@ -263,6 +132,6 @@ async function startup(cfg = config_js_1.config.parse({}), overrides = {}) {
263
132
  exitStartup(1);
264
133
  }
265
134
  finally {
266
- restoreInteractiveTerminalState();
135
+ (0, terminal_js_1.restoreInteractiveTerminalState)();
267
136
  }
268
137
  }
@@ -10,7 +10,7 @@ function registerStatusCommand(program) {
10
10
  program
11
11
  .command("status")
12
12
  .description("Show whether the local CompanyHelm daemon is running.")
13
- .option("--state-db-path <path>", "State database path override (defaults to ~/.local/share/companyhelm/state.db).")
13
+ .option("--state-db-path <path>", "State database path override (defaults to state.db under the active config directory).")
14
14
  .action(async (options) => {
15
15
  const cfg = config_js_1.config.parse({
16
16
  state_db_path: options.stateDbPath,
package/dist/config.js CHANGED
@@ -1,9 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.config = exports.codexConfig = void 0;
3
+ exports.config = exports.codexConfig = exports.DEFAULT_CONFIG_DIRECTORY = exports.CONFIG_PATH_ENV = void 0;
4
4
  const node_fs_1 = require("node:fs");
5
5
  const node_path_1 = require("node:path");
6
6
  const zod_1 = require("zod");
7
+ const path_js_1 = require("./utils/path.js");
8
+ exports.CONFIG_PATH_ENV = "COMPANYHELM_CONFIG_PATH";
9
+ exports.DEFAULT_CONFIG_DIRECTORY = "~/.config/companyhelm";
7
10
  const DEFAULT_RUNTIME_IMAGE_REPOSITORY = "companyhelm/runner";
8
11
  const FALLBACK_RUNTIME_IMAGE_VERSION = "latest";
9
12
  function loadRuntimeImageVersion() {
@@ -19,6 +22,19 @@ function loadRuntimeImageVersion() {
19
22
  return FALLBACK_RUNTIME_IMAGE_VERSION;
20
23
  }
21
24
  const DEFAULT_RUNTIME_IMAGE = `${DEFAULT_RUNTIME_IMAGE_REPOSITORY}:${loadRuntimeImageVersion()}`;
25
+ function resolveConfigRelativePath(configDirectory, pathValue) {
26
+ if ((0, node_path_1.isAbsolute)((0, path_js_1.expandHome)(pathValue))) {
27
+ return pathValue;
28
+ }
29
+ return (0, node_path_1.join)(configDirectory, pathValue);
30
+ }
31
+ function resolveConfigDirectoryDefault() {
32
+ const envValue = process.env[exports.CONFIG_PATH_ENV]?.trim();
33
+ if (envValue && envValue.length > 0) {
34
+ return envValue;
35
+ }
36
+ return exports.DEFAULT_CONFIG_DIRECTORY;
37
+ }
22
38
  exports.codexConfig = zod_1.z.object({
23
39
  codex_auth_file_path: zod_1.z.string()
24
40
  .describe("The path to the Codex authentication file on the host, relative to config_directory.")
@@ -36,13 +52,13 @@ exports.codexConfig = zod_1.z.object({
36
52
  exports.config = zod_1.z.object({
37
53
  config_directory: zod_1.z.string()
38
54
  .describe("The directory where the config files are stored.")
39
- .default("~/.config/companyhelm"),
55
+ .default(resolveConfigDirectoryDefault),
40
56
  workspaces_directory: zod_1.z.string()
41
57
  .describe("The directory where thread workspaces are stored, relative to config_directory when not absolute.")
42
58
  .default("workspaces"),
43
59
  state_db_path: zod_1.z.string()
44
- .describe("The path to the state database.")
45
- .default("~/.local/share/companyhelm/state.db"),
60
+ .describe("The path to the state database, relative to the config directory.")
61
+ .default("state.db"),
46
62
  companyhelm_api_url: zod_1.z.string()
47
63
  .describe("CompanyHelm control plane gRPC endpoint URL.")
48
64
  .default("https://api.companyhelm.com:50051"),
@@ -83,4 +99,7 @@ exports.config = zod_1.z.object({
83
99
  .describe("Default git author email used when runtime repositories are missing user.email.")
84
100
  .default("agent@companyhelm.com"),
85
101
  codex: exports.codexConfig.default(() => exports.codexConfig.parse({})),
86
- });
102
+ }).transform((value) => ({
103
+ ...value,
104
+ state_db_path: resolveConfigRelativePath(value.config_directory, value.state_db_path),
105
+ }));
@@ -1,12 +1,73 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseProcStatState = parseProcStatState;
4
+ exports.isZombieProcessState = isZombieProcessState;
3
5
  exports.isProcessRunning = isProcessRunning;
6
+ const node_child_process_1 = require("node:child_process");
7
+ const node_fs_1 = require("node:fs");
8
+ function parseProcStatState(statLine) {
9
+ const trimmed = statLine.trim();
10
+ if (trimmed.length === 0) {
11
+ return null;
12
+ }
13
+ const closingParenIndex = trimmed.lastIndexOf(")");
14
+ if (closingParenIndex < 0) {
15
+ return null;
16
+ }
17
+ const suffix = trimmed.slice(closingParenIndex + 1).trim();
18
+ if (suffix.length === 0) {
19
+ return null;
20
+ }
21
+ const state = suffix[0]?.trim();
22
+ return state && state.length > 0 ? state : null;
23
+ }
24
+ function isZombieProcessState(state) {
25
+ return state === "Z";
26
+ }
27
+ function readProcessState(pid) {
28
+ if (process.platform === "linux") {
29
+ try {
30
+ return parseProcStatState((0, node_fs_1.readFileSync)(`/proc/${pid}/stat`, "utf8"));
31
+ }
32
+ catch (error) {
33
+ const code = typeof error === "object" && error && "code" in error ? error.code : undefined;
34
+ if (code === "ENOENT") {
35
+ return null;
36
+ }
37
+ return undefined;
38
+ }
39
+ }
40
+ if (process.platform === "darwin" || process.platform === "freebsd" || process.platform === "openbsd" || process.platform === "sunos") {
41
+ try {
42
+ const status = (0, node_child_process_1.execFileSync)("ps", ["-o", "stat=", "-p", String(pid)], { encoding: "utf8" }).trim();
43
+ if (!status) {
44
+ return null;
45
+ }
46
+ return status[0] ?? null;
47
+ }
48
+ catch (error) {
49
+ const status = typeof error === "object" && error && "status" in error ? error.status : undefined;
50
+ if (status === 1) {
51
+ return null;
52
+ }
53
+ return undefined;
54
+ }
55
+ }
56
+ return undefined;
57
+ }
4
58
  function isProcessRunning(pid) {
5
59
  if (!Number.isInteger(pid) || pid <= 0) {
6
60
  return false;
7
61
  }
8
62
  try {
9
63
  process.kill(pid, 0);
64
+ const state = readProcessState(pid);
65
+ if (state === null) {
66
+ return false;
67
+ }
68
+ if (isZombieProcessState(state)) {
69
+ return false;
70
+ }
10
71
  return true;
11
72
  }
12
73
  catch (error) {
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.containsCtrlCInterruptInput = containsCtrlCInterruptInput;
4
+ exports.restoreInteractiveTerminalState = restoreInteractiveTerminalState;
5
+ const CTRL_C_ETX = "\u0003";
6
+ const CTRL_C_CSI_U_PATTERN = /\u001b\[99;5(?::\d+)?u/;
7
+ const CTRL_C_MODIFY_OTHER_KEYS_PATTERN = /\u001b\[27;5;99~/;
8
+ const RESTORE_KEYBOARD_PROTOCOL_SEQUENCE = "\u001b[<u";
9
+ const SHOW_CURSOR_SEQUENCE = "\u001b[?25h";
10
+ function containsCtrlCInterruptInput(input) {
11
+ return input.includes(CTRL_C_ETX) ||
12
+ CTRL_C_CSI_U_PATTERN.test(input) ||
13
+ CTRL_C_MODIFY_OTHER_KEYS_PATTERN.test(input);
14
+ }
15
+ function restoreInteractiveTerminalState(stdin = process.stdin, stdout = process.stdout) {
16
+ try {
17
+ if (stdin.isTTY && typeof stdin.setRawMode === "function") {
18
+ stdin.setRawMode(false);
19
+ }
20
+ }
21
+ catch {
22
+ // Best-effort prompt cleanup.
23
+ }
24
+ try {
25
+ if (stdout.isTTY) {
26
+ // Restore normal keyboard reporting if a prompt enabled kitty/xterm CSI-u handling.
27
+ stdout.write(RESTORE_KEYBOARD_PROTOCOL_SEQUENCE);
28
+ stdout.write(SHOW_CURSOR_SEQUENCE);
29
+ }
30
+ }
31
+ catch {
32
+ // Best-effort prompt cleanup.
33
+ }
34
+ }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@companyhelm/cli",
3
- "version": "0.0.8",
3
+ "version": "0.0.11",
4
4
  "description": "Run coding agents in fully isolated Docker sandboxes, locally.",
5
- "license": "Apache-2.0",
5
+ "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
8
8
  "url": "https://github.com/CompanyHelm/companyhelm-cli"
@@ -31,7 +31,7 @@
31
31
  "dependencies": {
32
32
  "@bufbuild/protobuf": "^2.11.0",
33
33
  "@clack/prompts": "^1.0.1",
34
- "@companyhelm/protos": "0.5.13",
34
+ "@companyhelm/protos": "0.5.16",
35
35
  "@grpc/grpc-js": "^1.14.3",
36
36
  "@libsql/client": "^0.17.0",
37
37
  "commander": "^14.0.0",