@infosupport/huddle-cli 0.0.0-experiment-147.95.1 → 0.0.0-experiment-160.97.1

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/README.md CHANGED
@@ -44,43 +44,25 @@ huddle --ide vscode \
44
44
 
45
45
  Default API URL: `http://localhost:3000`. Override it with `--url` or `HUDDLE_URL`.
46
46
 
47
- ## Making host folders selectable in the portal
47
+ ## Browsing host folders from the portal
48
48
 
49
- Huddle's portal runs inside a container, so it cannot open a folder dialog on your
50
- host: every host path had to be typed from memory. `huddle indexfolder` scans your
51
- host once and stores what it finds, and every host-path field in the portal grows a
52
- **Browse** button that opens those folders as a tree — starting a devcontainer, the
53
- folder mappings, and the team-managed folders. Starting a devcontainer, Ctrl-click picks
54
- several folders at once and each becomes its own worktree. Typing a path by hand keeps working:
55
- the index is a snapshot, so a folder created after the last scan must not be
56
- unreachable.
49
+ Huddle's portal runs inside a container, so it cannot see your host by itself. `huddle init`
50
+ (and `huddle restart`) therefore also start the **host pipe** in the background: a small agent,
51
+ part of this CLI, that answers the gateway through files in `~/.huddle/pipe`. Through it every
52
+ host-path field in the portal gets a **Browse** button with a live folder tree of your host —
53
+ starting a devcontainer, the folder mappings, and the team-managed folders — and the portal can
54
+ drive allowlisted host tools such as Docker Sandboxes (`sbx`, argv only, never a shell). Starting a
55
+ devcontainer, Ctrl-click picks several folders at once and each becomes its own worktree.
57
56
 
58
57
  ```bash
59
- cd T:/projects
60
- huddle indexfolder # this folder + 2 levels below it
61
- huddle indexfolder T:/projects --depth 3
62
- huddle indexfolder --all # also index node_modules, dist, target, ...
63
- huddle indexfolder --replace # re-scan: drop the earlier entries under this folder first
64
- huddle indexfolder --list # show what is indexed
65
- huddle indexfolder --clear # empty the index (with a folder: only that subtree)
58
+ huddle pipe status # online/offline, pid, CLI version, available tools
59
+ huddle pipe start # start in the background (replaces a running one)
60
+ huddle pipe stop
61
+ huddle pipe serve # run in the foreground, for debugging
66
62
  ```
67
63
 
68
- Hidden (dot) folders and the usual build folders (`node_modules`, `dist`, `target`,
69
- `obj`, …) are skipped, which is what keeps a scan of a projects folder in the
70
- hundreds instead of the tens of thousands; `--all` turns that off. The scan stops
71
- at 1500 folders and the index holds at most 2000 — index a more specific folder if
72
- you hit that.
73
-
74
- The index is a **snapshot**, not a live view: the gateway cannot read your host, so
75
- re-run the command after adding projects. Every input keeps accepting a typed path,
76
- so a folder you created a minute ago works without re-indexing first. Windows paths
77
- may be typed either way (`T:\projects\app` or `T:/projects/app`) — they are stored
78
- in one canonical form, and the two spellings are the same entry.
79
-
80
- Individual folders can also be added or removed under **Settings > Indexed
81
- folders** in the portal. The index lives in Huddle's database, not in
82
- `~/.huddle/config.json`: it describes this machine, so unlike the team-managed
83
- settings it is not something to share in version control.
64
+ The agent logs to `~/.huddle/pipe/host.log`. Typing a path by hand keeps working when the pipe
65
+ is offline. The protocol is described in [docs/host-pipe.md](../docs/host-pipe.md).
84
66
 
85
67
  ## Experiments
86
68
 
package/dist/api.js CHANGED
@@ -3,7 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.del = exports.put = exports.post = exports.get = exports.ApiError = void 0;
4
4
  exports.setBaseUrl = setBaseUrl;
5
5
  exports.apiCall = apiCall;
6
- exports.uploadFile = uploadFile;
7
6
  const config_1 = require("./config");
8
7
  let baseUrl = normalizeBaseUrl(process.env.HUDDLE_URL ?? 'http://localhost:3000');
9
8
  class ApiError extends Error {
@@ -22,15 +21,6 @@ async function apiCall(method, path, body) {
22
21
  const headers = {};
23
22
  if (body !== undefined)
24
23
  headers['content-type'] = 'application/json';
25
- return send(method, path, body !== undefined ? JSON.stringify(body) : undefined, headers);
26
- }
27
- /** POSTs one file as multipart/form-data (field `file`), e.g. an extension zip. */
28
- async function uploadFile(path, fileName, data) {
29
- const form = new FormData();
30
- form.append('file', new Blob([new Uint8Array(data)]), fileName);
31
- return send('POST', path, form, {});
32
- }
33
- async function send(method, path, body, headers) {
34
24
  // Operator-auth: stuur het token als Bearer mee zodat de CLI de control-plane
35
25
  // -auth passeert. Zonder token krijgen we een 401 met een duidelijke hint.
36
26
  const token = (0, config_1.operatorToken)();
@@ -38,7 +28,11 @@ async function send(method, path, body, headers) {
38
28
  headers['authorization'] = `Bearer ${token}`;
39
29
  let res;
40
30
  try {
41
- res = await fetch(`${baseUrl}${path}`, { method, headers, body });
31
+ res = await fetch(`${baseUrl}${path}`, {
32
+ method,
33
+ headers,
34
+ body: body !== undefined ? JSON.stringify(body) : undefined,
35
+ });
42
36
  }
43
37
  catch (err) {
44
38
  const detail = err instanceof Error ? err.message : String(err);
package/dist/config.js CHANGED
@@ -139,10 +139,7 @@ let tmpSeq = 0;
139
139
  * config.
140
140
  */
141
141
  function updateConfig(patch) {
142
- // The config holds the operator token: owner-only. chmod as well, because
143
- // mkdir's mode does not tighten a directory created by an older version.
144
- fs_1.default.mkdirSync(exports.CONFIG_DIR, { recursive: true, mode: 0o700 });
145
- fs_1.default.chmodSync(exports.CONFIG_DIR, 0o700);
142
+ fs_1.default.mkdirSync(exports.CONFIG_DIR, { recursive: true });
146
143
  const token = acquireLock();
147
144
  if (token === null) {
148
145
  throw new Error(`Could not lock ${CONFIG_PATH} within ${LOCK_WAIT_MS}ms — another Huddle process ` +
@@ -156,7 +153,7 @@ function updateConfig(patch) {
156
153
  if (v === undefined)
157
154
  delete next[k];
158
155
  }
159
- fs_1.default.writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
156
+ fs_1.default.writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`);
160
157
  fs_1.default.renameSync(tmp, CONFIG_PATH);
161
158
  return next;
162
159
  }
package/dist/index.js CHANGED
@@ -8,18 +8,17 @@ const fs_1 = __importDefault(require("fs"));
8
8
  const path_1 = __importDefault(require("path"));
9
9
  const api_1 = require("./api");
10
10
  const start_1 = require("./start");
11
- const extension_1 = require("./extension");
12
11
  const firewall_1 = require("./firewall");
13
12
  const init_1 = require("./init");
14
13
  const migrate_1 = require("./migrate");
15
- const indexfolder_1 = require("./indexfolder");
14
+ const command_1 = require("./pipe/command");
16
15
  const images_1 = require("./images");
17
16
  const self_update_1 = require("./self-update");
18
17
  const utils_1 = require("./utils");
19
18
  const experiment_1 = require("./experiment");
20
- const VALUE_FLAGS = new Set(['url', 'ide', 'name', 'image', 'workspace', 'container', 'status', 'runtime', 'experiment', 'path', 'ca-path', 'output', 'out', 'workspace-root', 'depth']);
21
- const BOOLEAN_FLAGS = new Set(['help', 'h', 'empty', 'i', 'interactive', 'version', 'v', 'deny', 'docker-socket', 'force', 'replace', 'all', 'list', 'clear']);
22
- const COMMANDS = new Set(['start', 'firewall', 'fw', 'extension', 'ext', 'init', 'restart', 'experiment', 'migrate', 'indexfolder', 'indexfolders', 'help', 'version']);
19
+ const VALUE_FLAGS = new Set(['url', 'ide', 'name', 'image', 'workspace', 'container', 'status', 'runtime', 'experiment', 'path', 'ca-path', 'output', 'out', 'workspace-root']);
20
+ const BOOLEAN_FLAGS = new Set(['help', 'h', 'empty', 'i', 'interactive', 'version', 'v', 'deny', 'docker-socket', 'force', 'replace']);
21
+ const COMMANDS = new Set(['start', 'firewall', 'fw', 'init', 'restart', 'experiment', 'migrate', 'pipe', 'help', 'version']);
23
22
  function parseArgs(argv) {
24
23
  const positional = [];
25
24
  const flags = {};
@@ -124,10 +123,11 @@ Usage:
124
123
  team firewall-rules folder)
125
124
  huddle migrate [folder] Wire an existing docker-compose devcontainer
126
125
  behind Huddle by generating an override file
127
- huddle indexfolder [folder] Index the folders under this one so the portal
128
- can offer them where a host path is needed
129
- (the portal runs in a container and cannot
130
- browse your host)
126
+ huddle pipe status Show whether the host pipe is online (lets the
127
+ portal browse host folders and run sbx)
128
+ huddle pipe start|stop Start (or replace) / stop the host pipe in the
129
+ background (huddle init starts it for you)
130
+ huddle pipe serve Run the host pipe in the foreground (debugging)
131
131
  huddle firewall list [options] Show firewall requests
132
132
  huddle fw list [options] Alias for firewall list
133
133
  huddle firewall add <domain> Add a custom firewall rule (wildcards
@@ -143,13 +143,6 @@ Usage:
143
143
  huddle firewall folder set <path> Set the team-managed rules folder
144
144
  huddle firewall folder reload Re-read the team-managed rules folder
145
145
  huddle firewall folder sync Write the portal's groups back to the folder
146
- huddle extension list List installed gateway extensions
147
- huddle ext list Alias for extension list
148
- huddle extension install <dir> Install or update the extension in a folder
149
- (--force replaces another extension with the
150
- same id, --restart reloads the gateway process
151
- on the engine that runs Huddle, or --runtime)
152
- huddle extension remove <id> Remove an installed extension
153
146
  huddle experiment use <nr> Activate the experimental build of issue/PR <nr>
154
147
  and run init
155
148
  huddle experiment reset Back to the stable release
@@ -170,8 +163,7 @@ Start options:
170
163
  --workspace-root <path> Container path the IDE opens as project root when using
171
164
  --mount (default: common parent of the mount targets)
172
165
  --name <name> Container name (default: devcontainer-<foldername>)
173
- --image <image> Use a specific image. Any Debian/Ubuntu/Alpine image works:
174
- Huddle builds it once with its own layer on top
166
+ --image <image> Use a specific image
175
167
  --empty Empty container without a workspace
176
168
 
177
169
  Migrate options:
@@ -183,16 +175,6 @@ Migrate options:
183
175
  (default: docker-compose.huddle.yml next to the source)
184
176
  --force Overwrite an existing override file
185
177
 
186
- Indexfolder options:
187
- --depth <n> How deep to walk (default: 2, max 8)
188
- --all Also index build folders (node_modules, dist,
189
- target, ...); hidden folders stay skipped
190
- --replace Drop the earlier entries under this folder
191
- first, instead of merging
192
- --list Show the current index and exit
193
- --clear Empty the index (or, with a folder, only the
194
- entries under it)
195
-
196
178
  Firewall options:
197
179
  -i, --interactive Interactively approve/deny (list)
198
180
  --container <name> Filter by (list) / scope to (add) a container
@@ -361,47 +343,8 @@ async function main() {
361
343
  }
362
344
  return;
363
345
  }
364
- if (cmd === 'extension' || cmd === 'ext') {
365
- const subCmd = sub ?? 'list';
366
- if (subCmd === 'list') {
367
- await (0, extension_1.runExtensionList)();
368
- }
369
- else if (subCmd === 'install') {
370
- const dir = positional[2];
371
- if (!dir) {
372
- console.error('Usage: huddle extension install <dir> [--force] [--restart] [--runtime <docker|podman>]');
373
- process.exit(1);
374
- }
375
- await (0, extension_1.runExtensionInstall)(dir, {
376
- force: flagBool(flags, 'force'),
377
- restart: flagBool(flags, 'restart'),
378
- runtime: flagString(flags, 'runtime'),
379
- });
380
- }
381
- else if (subCmd === 'remove' || subCmd === 'rm') {
382
- const id = positional[2];
383
- if (!id) {
384
- console.error('Usage: huddle extension remove <id>');
385
- process.exit(1);
386
- }
387
- await (0, extension_1.runExtensionRemove)(id);
388
- }
389
- else {
390
- console.error(`Unknown extension subcommand: ${subCmd}`);
391
- console.error('Usage: huddle extension <list|install <dir>|remove <id>>');
392
- process.exit(1);
393
- }
394
- return;
395
- }
396
- if (cmd === 'indexfolder' || cmd === 'indexfolders') {
397
- await (0, indexfolder_1.runIndexFolder)({
398
- path: positional[1],
399
- depth: flagString(flags, 'depth'),
400
- all: flagBool(flags, 'all'),
401
- replace: flagBool(flags, 'replace'),
402
- clear: flagBool(flags, 'clear'),
403
- list: flagBool(flags, 'list'),
404
- });
346
+ if (cmd === 'pipe') {
347
+ await (0, command_1.runPipe)({ action: sub });
405
348
  return;
406
349
  }
407
350
  if (cmd === 'migrate') {
package/dist/init.js CHANGED
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.SSH_RELAY_PORTS = exports.HOST_SOCKET_DIR = exports.INTERNAL_NET = exports.CONTAINER = void 0;
6
+ exports.HOST_SOCKET_DIR = exports.INTERNAL_NET = void 0;
7
7
  exports.runInit = runInit;
8
8
  const child_process_1 = require("child_process");
9
9
  const crypto_1 = __importDefault(require("crypto"));
@@ -11,10 +11,10 @@ const utils_1 = require("./utils");
11
11
  const runtime_1 = require("./runtime");
12
12
  const images_1 = require("./images");
13
13
  const config_1 = require("./config");
14
- const os_1 = __importDefault(require("os"));
15
- const host_logs_1 = require("./host-logs");
14
+ const protocol_1 = require("./pipe/protocol");
15
+ const command_1 = require("./pipe/command");
16
16
  const fs_1 = __importDefault(require("fs"));
17
- exports.CONTAINER = 'huddle';
17
+ const CONTAINER = 'huddle';
18
18
  const VOLUME = 'huddle-data';
19
19
  /**
20
20
  * The shared, internal network that `huddle init` creates (`--internal`, so it
@@ -31,12 +31,6 @@ exports.INTERNAL_NET = 'devcontainer-net';
31
31
  */
32
32
  exports.HOST_SOCKET_DIR = '/tmp/dc-sockets';
33
33
  const HOST_PORT = process.env.HUDDLE_PORT ?? '3000';
34
- /**
35
- * Ports of the per-devcontainer SSH relays (JetBrains Gateway over SSH), bound to
36
- * the host's loopback only. Kept in sync with SSH_RELAY_PORT_MIN/MAX in
37
- * gateway/src/ssh-access.ts.
38
- */
39
- exports.SSH_RELAY_PORTS = '2200-2219';
40
34
  // Run a binary with an argv array — NO shell. Values that originate from config
41
35
  // (team-folder paths, which are writable via `huddle firewall folder set` and the
42
36
  // authenticated settings API) must never be interpolated into a shell string, or
@@ -102,7 +96,7 @@ async function runInit(opts, images) {
102
96
  console.log((0, utils_1.dim)(`Network: ${exports.INTERNAL_NET}`));
103
97
  runArgsSilent(rt, ['network', 'inspect', exports.INTERNAL_NET]) || runArgs(rt, ['network', 'create', '--internal', exports.INTERNAL_NET]);
104
98
  console.log((0, utils_1.dim)(`Removing old container if it exists`));
105
- runArgsSilent(rt, ['rm', '-f', exports.CONTAINER]);
99
+ runArgsSilent(rt, ['rm', '-f', CONTAINER]);
106
100
  console.log((0, utils_1.dim)(`Socket directory: /tmp/dc-sockets`));
107
101
  // The mount SOURCE must be the path on the Docker ENGINE host (on Windows:
108
102
  // the WSL2/Linux VM), even when the CLI itself runs on Windows. The gateway
@@ -168,16 +162,18 @@ async function runInit(opts, images) {
168
162
  console.log((0, utils_1.dim)(` Mounting firewall-rules folder: ${fwFolder} -> /firewall-rules`));
169
163
  if (extFolder)
170
164
  console.log((0, utils_1.dim)(` Mounting extensions folder: ${extFolder} -> /extensions`));
165
+ // The host pipe lives inside the ~/.huddle mount; create it now so the
166
+ // gateway sees the folder from its first start, before the agent runs.
167
+ fs_1.default.mkdirSync(protocol_1.PIPE_DIR, { recursive: true });
171
168
  // Build the container command as an argv array (runArgs → execFileSync, no
172
169
  // shell). The folder paths below come from config and are operator-writable via
173
170
  // the settings API, so they must never reach a shell as a string.
174
- const dockerArgs = ['run', '-d', '--name', exports.CONTAINER, '--network', runtime.defaultNetwork];
171
+ const dockerArgs = ['run', '-d', '--name', CONTAINER, '--network', runtime.defaultNetwork];
175
172
  for (const opt of runtime.securityOpts)
176
173
  dockerArgs.push('--security-opt', opt);
177
174
  dockerArgs.push('-e', `HUDDLE_RUNTIME=${runtime.name}`);
178
175
  dockerArgs.push('-e', `HUDDLE_OPERATOR_TOKEN=${operatorToken}`);
179
176
  dockerArgs.push('-p', `${HOST_PORT}:3000`);
180
- dockerArgs.push('-p', `127.0.0.1:${exports.SSH_RELAY_PORTS}:${exports.SSH_RELAY_PORTS}`);
181
177
  dockerArgs.push('-v', `${VOLUME}:/data`);
182
178
  dockerArgs.push('-v', `${runtime.socketPath}:/var/run/docker.sock`);
183
179
  dockerArgs.push('-v', `${hostTmpSockets}:/tmp/dc-sockets`);
@@ -186,15 +182,6 @@ async function runInit(opts, images) {
186
182
  dockerArgs.push('-v', `${fwFolder}:/firewall-rules:rw`);
187
183
  if (extFolder)
188
184
  dockerArgs.push('-v', `${extFolder}:/extensions:ro`);
189
- const hostLogs = (0, host_logs_1.hostAgentLogsMountArgs)(cfg, os_1.default.homedir());
190
- if (hostLogs.length)
191
- console.log((0, utils_1.dim)(' Mounting host Claude logs (read-only) for extensions'));
192
- dockerArgs.push(...hostLogs);
193
- const hostCodexLogs = (0, host_logs_1.hostCodexLogsMountArgs)(cfg, os_1.default.homedir());
194
- if (hostCodexLogs.length)
195
- console.log((0, utils_1.dim)(' Mounting host Codex logs (read-only) for extensions'));
196
- dockerArgs.push(...hostCodexLogs);
197
- dockerArgs.push(...(0, host_logs_1.hostCodexIndexMountArgs)(cfg, os_1.default.homedir()));
198
185
  dockerArgs.push(...(0, images_1.gatewayEnvArgs)(images));
199
186
  dockerArgs.push(IMAGE);
200
187
  runArgs(rt, dockerArgs);
@@ -202,7 +189,17 @@ async function runInit(opts, images) {
202
189
  // resolv.conf on Podman with that network's internal aardvark-DNS; the
203
190
  // gateway cleans that up itself (see dns-egress.ts / the startup sanitize in
204
191
  // index.ts).
205
- runArgsSilent(rt, ['network', 'connect', exports.INTERNAL_NET, exports.CONTAINER]);
192
+ runArgsSilent(rt, ['network', 'connect', exports.INTERNAL_NET, CONTAINER]);
193
+ // The host pipe lets the portal browse host folders and drive host tools
194
+ // (docs/host-pipe.md). Restarting it here means it always runs the CLI that
195
+ // was just installed. It is an extra, so a failure only warns.
196
+ const pipe = await (0, command_1.startPipeAgent)();
197
+ if (pipe.ok) {
198
+ console.log((0, utils_1.dim)(`Host pipe: running (pid ${pipe.pid})`));
199
+ }
200
+ else {
201
+ console.log((0, utils_1.yellow)(`[!] Host pipe did not start: ${pipe.error}. Run: huddle pipe start`));
202
+ }
206
203
  console.log();
207
204
  console.log((0, utils_1.green)(`[OK] Huddle is running at http://localhost:${HOST_PORT}`));
208
205
  console.log();
@@ -0,0 +1,186 @@
1
+ "use strict";
2
+ // ── `huddle pipe serve|start|stop|status` ─────────────────────────────────────
3
+ // Runs and manages the host agent for the host pipe (docs/host-pipe.md).
4
+ // `huddle init` calls startPipeAgent() so the agent always runs the CLI version
5
+ // that was just installed; the commands here are for checking on it and for
6
+ // debugging (`serve` runs it in the foreground with the log on the terminal).
7
+ var __importDefault = (this && this.__importDefault) || function (mod) {
8
+ return (mod && mod.__esModule) ? mod : { "default": mod };
9
+ };
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.startPipeAgent = startPipeAgent;
12
+ exports.runPipe = runPipe;
13
+ const fs_1 = __importDefault(require("fs"));
14
+ const path_1 = __importDefault(require("path"));
15
+ const child_process_1 = require("child_process");
16
+ const utils_1 = require("../utils");
17
+ const protocol_1 = require("./protocol");
18
+ const serve_1 = require("./serve");
19
+ const LOG_PATH = path_1.default.join(protocol_1.PIPE_DIR, protocol_1.LOG_FILE);
20
+ const MAX_LOG_BYTES = 5 * 1024 * 1024;
21
+ const STOP_WAIT_MS = 3000;
22
+ const START_WAIT_MS = 3000;
23
+ function alive(pid) {
24
+ try {
25
+ process.kill(pid, 0);
26
+ return true;
27
+ }
28
+ catch (err) {
29
+ // EPERM: it exists but belongs to someone else.
30
+ return err.code === 'EPERM';
31
+ }
32
+ }
33
+ async function waitFor(check, ms) {
34
+ const deadline = Date.now() + ms;
35
+ while (Date.now() < deadline) {
36
+ if (check())
37
+ return true;
38
+ await new Promise((r) => setTimeout(r, 100));
39
+ }
40
+ return check();
41
+ }
42
+ /**
43
+ * Stops the agent named in the heartbeat. Only a FRESH heartbeat is trusted:
44
+ * pids get reused, and killing whatever now holds the pid of an agent that died
45
+ * last week would be a nasty surprise. A stale heartbeat is just removed.
46
+ */
47
+ async function stopRunning() {
48
+ const hb = (0, protocol_1.readHeartbeat)();
49
+ if (!hb || !(0, protocol_1.heartbeatFresh)(hb) || hb.pid === process.pid || !alive(hb.pid)) {
50
+ try {
51
+ fs_1.default.unlinkSync(path_1.default.join(protocol_1.PIPE_DIR, protocol_1.HEARTBEAT_FILE));
52
+ }
53
+ catch { /* none */ }
54
+ return null;
55
+ }
56
+ try {
57
+ process.kill(hb.pid, 'SIGTERM');
58
+ }
59
+ catch { /* exited meanwhile */ }
60
+ if (!(await waitFor(() => !alive(hb.pid), STOP_WAIT_MS))) {
61
+ try {
62
+ process.kill(hb.pid, 'SIGKILL');
63
+ }
64
+ catch { /* exited meanwhile */ }
65
+ await waitFor(() => !alive(hb.pid), 1000);
66
+ }
67
+ // On Windows kill() is TerminateProcess, so the agent had no chance to clean up.
68
+ const left = (0, protocol_1.readHeartbeat)();
69
+ if (left?.pid === hb.pid) {
70
+ try {
71
+ fs_1.default.unlinkSync(path_1.default.join(protocol_1.PIPE_DIR, protocol_1.HEARTBEAT_FILE));
72
+ }
73
+ catch { /* none */ }
74
+ }
75
+ return hb;
76
+ }
77
+ /** Keeps one previous log; the agent appends for as long as it runs. */
78
+ function rotateLog() {
79
+ try {
80
+ if (fs_1.default.statSync(LOG_PATH).size > MAX_LOG_BYTES)
81
+ fs_1.default.renameSync(LOG_PATH, `${LOG_PATH}.1`);
82
+ }
83
+ catch { /* no log yet */ }
84
+ }
85
+ /**
86
+ * Starts the agent in the background, replacing a running one so the agent
87
+ * always runs this CLI's code. Never throws: `huddle init` must not fail on it.
88
+ */
89
+ async function startPipeAgent() {
90
+ try {
91
+ fs_1.default.mkdirSync(protocol_1.PIPE_DIR, { recursive: true });
92
+ const old = await stopRunning();
93
+ rotateLog();
94
+ // dist/pipe/command.js -> dist/index.js: the entry of THIS install, not
95
+ // whatever `huddle` resolves to on PATH.
96
+ const entry = path_1.default.join(__dirname, '..', 'index.js');
97
+ const logFd = fs_1.default.openSync(LOG_PATH, 'a');
98
+ let pid;
99
+ try {
100
+ const child = (0, child_process_1.spawn)(process.execPath, [entry, 'pipe', 'serve'], {
101
+ detached: true,
102
+ stdio: ['ignore', logFd, logFd],
103
+ windowsHide: true,
104
+ });
105
+ child.on('error', () => { });
106
+ child.unref();
107
+ pid = child.pid;
108
+ }
109
+ finally {
110
+ fs_1.default.closeSync(logFd);
111
+ }
112
+ if (!pid)
113
+ return { ok: false, error: `could not start the host agent (see ${LOG_PATH})` };
114
+ const up = await waitFor(() => {
115
+ const hb = (0, protocol_1.readHeartbeat)();
116
+ return hb !== null && (0, protocol_1.heartbeatFresh)(hb) && hb.pid === pid;
117
+ }, START_WAIT_MS);
118
+ if (!up)
119
+ return { ok: false, pid, error: `the host agent did not report in (see ${LOG_PATH})` };
120
+ return { ok: true, pid, replaced: old?.pid };
121
+ }
122
+ catch (err) {
123
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
124
+ }
125
+ }
126
+ function runServe() {
127
+ const stamp = () => new Date().toISOString();
128
+ const log = (msg) => console.log(`${stamp()} ${msg}`);
129
+ log(`host pipe agent (pid ${process.pid}) serving ${protocol_1.PIPE_DIR}`);
130
+ const handle = (0, serve_1.servePipe)({ dir: protocol_1.PIPE_DIR, log, onReplaced: () => process.exit(0) });
131
+ const shutdown = (signal) => {
132
+ log(`${signal}: stopping`);
133
+ // Removes host.json right away; in-flight requests are abandoned (the
134
+ // gateway times them out) rather than holding up a stop.
135
+ void handle.stop();
136
+ process.exit(0);
137
+ };
138
+ process.on('SIGINT', () => shutdown('SIGINT'));
139
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
140
+ }
141
+ function ago(iso) {
142
+ const s = Math.max(0, Math.round((Date.now() - Date.parse(iso)) / 1000));
143
+ return s < 60 ? `${s}s ago` : s < 3600 ? `${Math.floor(s / 60)}m ago` : `${Math.floor(s / 3600)}h ago`;
144
+ }
145
+ function runStatus() {
146
+ const hb = (0, protocol_1.readHeartbeat)();
147
+ if (hb && (0, protocol_1.heartbeatFresh)(hb)) {
148
+ console.log(`${(0, utils_1.green)('Host pipe: online')} ${(0, utils_1.dim)(`(pid ${hb.pid}, CLI ${hb.version}, ${hb.platform})`)}`);
149
+ console.log((0, utils_1.dim)(` tools: ${hb.tools.length ? hb.tools.join(', ') : 'none installed'}`));
150
+ console.log((0, utils_1.dim)(` started: ${hb.startedAt} · heartbeat ${ago(hb.updatedAt)}`));
151
+ }
152
+ else {
153
+ const last = hb ? ` (last heartbeat ${ago(hb.updatedAt)}, pid ${hb.pid})` : '';
154
+ console.log(`${(0, utils_1.yellow)('Host pipe: offline')}${(0, utils_1.dim)(last)}`);
155
+ console.log((0, utils_1.dim)(' Start it with: huddle pipe start'));
156
+ }
157
+ console.log((0, utils_1.dim)(` folder: ${protocol_1.PIPE_DIR}`));
158
+ console.log((0, utils_1.dim)(` log: ${LOG_PATH}`));
159
+ }
160
+ async function runPipe(opts) {
161
+ const action = opts.action ?? 'status';
162
+ if (action === 'serve') {
163
+ runServe();
164
+ }
165
+ else if (action === 'start') {
166
+ const r = await startPipeAgent();
167
+ if (!r.ok) {
168
+ console.error((0, utils_1.yellow)(`[!] ${r.error}`));
169
+ process.exit(1);
170
+ }
171
+ const replaced = r.replaced ? `, replaced pid ${r.replaced}` : '';
172
+ console.log((0, utils_1.green)('[OK] Host pipe started') + (0, utils_1.dim)(` (pid ${r.pid}${replaced}) · log ${LOG_PATH}`));
173
+ }
174
+ else if (action === 'stop') {
175
+ const stopped = await stopRunning();
176
+ console.log(stopped ? `Host pipe stopped ${(0, utils_1.dim)(`(pid ${stopped.pid})`)}` : (0, utils_1.dim)('Host pipe was not running'));
177
+ }
178
+ else if (action === 'status') {
179
+ runStatus();
180
+ }
181
+ else {
182
+ console.error(`Unknown pipe subcommand: ${action}`);
183
+ console.error('Usage: huddle pipe <status|start|stop|serve>');
184
+ process.exit(1);
185
+ }
186
+ }