@infosupport/huddle-cli 0.0.0-experiment-160.131.1 → 0.0.0-experiment-44.133.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/dist/start.js CHANGED
@@ -80,20 +80,18 @@ async function runStart(opts) {
80
80
  console.log(`Open in VS Code: ${(0, utils_1.cyan)('Dev Containers: Attach to Running Container')} -> ${(0, utils_1.bold)(result.containerName)}`);
81
81
  return;
82
82
  }
83
- await tryPrintSshLink(result.containerName);
83
+ console.log(`Open in JetBrains Gateway: ${(0, utils_1.cyan)('Remote Development > Dev Containers')} -> ${(0, utils_1.bold)(result.containerName)}`);
84
+ await tryPrintIdeLink(result.containerName);
84
85
  }
85
- // Same link as the portal's Connect IDE button: sets up sshd, the localhost
86
- // relay and the `<name>.huddle` ssh alias (key made by the host agent), and
87
- // returns a JetBrains Toolbox link. Best-effort: without the host agent, or on an
88
- // older image, the portal button explains what is missing.
89
- async function tryPrintSshLink(containerName) {
86
+ async function tryPrintIdeLink(containerName) {
87
+ await new Promise((resolve) => setTimeout(resolve, 3000));
90
88
  try {
91
- const res = await (0, api_1.get)(`/api/docker/containers/${encodeURIComponent(containerName)}/ssh-link`);
89
+ const res = await (0, api_1.get)(`/api/docker/containers/${encodeURIComponent(containerName)}/ide-link`);
92
90
  if (res?.link)
93
- console.log(`Open in JetBrains Toolbox: ${(0, utils_1.cyan)(res.link)} (or: ssh ${containerName}.huddle)`);
91
+ console.log((0, utils_1.dim)(`Gateway-link: ${res.link}`));
94
92
  }
95
- catch (err) {
96
- console.log((0, utils_1.dim)(`No SSH link yet (${err?.message ?? err}); use Connect IDE in the Huddle portal.`));
93
+ catch {
94
+ // The IDE link is best-effort; JetBrains may still be starting the backend.
97
95
  }
98
96
  }
99
97
  function resolveWorkspace(workspace) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infosupport/huddle-cli",
3
- "version": "0.0.0-experiment-160.131.1",
3
+ "version": "0.0.0-experiment-44.133.1",
4
4
  "description": "Huddle CLI — start devcontainers and manage firewall rules",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "author": "Info Support B.V.",
@@ -20,15 +20,11 @@
20
20
  "build": "tsc",
21
21
  "dev": "tsc --watch",
22
22
  "install-global": "npm run build && npm install -g .",
23
- "typecheck": "tsc --noEmit",
24
- "test": "vitest run"
23
+ "typecheck": "tsc --noEmit"
25
24
  },
26
25
  "devDependencies": {
27
- "@types/adm-zip": "^0.5.8",
28
26
  "@types/node": "^22.0.0",
29
- "adm-zip": "^0.5.18",
30
- "typescript": "^5.0.0",
31
- "vitest": "^4.1.11"
27
+ "typescript": "^5.0.0"
32
28
  },
33
29
  "engines": {
34
30
  "node": ">=18"
package/dist/extension.js DELETED
@@ -1,170 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.isExtensionId = exports.MAX_FOLDER_DEPTH = void 0;
7
- exports.insideFolder = insideFolder;
8
- exports.collectExtensionFiles = collectExtensionFiles;
9
- exports.planInstall = planInstall;
10
- exports.asExtensionList = asExtensionList;
11
- exports.runExtensionList = runExtensionList;
12
- exports.restartRuntime = restartRuntime;
13
- exports.runExtensionInstall = runExtensionInstall;
14
- exports.runExtensionRemove = runExtensionRemove;
15
- const fs_1 = __importDefault(require("fs"));
16
- const path_1 = __importDefault(require("path"));
17
- const child_process_1 = require("child_process");
18
- const api_1 = require("./api");
19
- const zip_1 = require("./zip");
20
- const init_1 = require("./init");
21
- const runtime_1 = require("./runtime");
22
- const utils_1 = require("./utils");
23
- const SKIPPED = new Set(['node_modules']);
24
- exports.MAX_FOLDER_DEPTH = 32;
25
- /** The gateway's own id rule: one lowercase path component, so it can never point outside the extensions folder. */
26
- const isExtensionId = (id) => typeof id === 'string' && /^[a-z0-9-]+$/.test(id);
27
- exports.isExtensionId = isExtensionId;
28
- /** Resolves `rel` within `root` and refuses anything that lands outside it (`..`, absolute paths). */
29
- function insideFolder(root, rel) {
30
- const base = path_1.default.resolve(root);
31
- const abs = path_1.default.resolve(base, rel);
32
- if (abs !== base && !abs.startsWith(base + path_1.default.sep))
33
- throw new Error(`${rel} is outside the extension folder`);
34
- return abs;
35
- }
36
- /**
37
- * Reads a regular file of the folder; a symlink is refused, so the zip can never carry a file from outside it.
38
- * @param root the resolved extension folder @param rel a path relative to it, from readdir
39
- */
40
- function readPlainFile(root, rel) {
41
- const abs = insideFolder(root, rel);
42
- const stat = fs_1.default.lstatSync(abs);
43
- if (stat.isSymbolicLink())
44
- throw new Error(`${rel} is a symlink; extensions are packaged without symlinks`);
45
- if (!stat.isFile())
46
- throw new Error(`${rel} is not a regular file`);
47
- return fs_1.default.readFileSync(abs);
48
- }
49
- /** Reads an extension folder into zip entries; the manifest must pass the gateway's own id rule. */
50
- function collectExtensionFiles(dir) {
51
- const root = path_1.default.resolve(dir);
52
- for (const required of ['manifest.json', 'index.js']) {
53
- if (!fs_1.default.lstatSync(insideFolder(root, required), { throwIfNoEntry: false }))
54
- throw new Error(`${required} missing in ${root}`);
55
- }
56
- const manifest = JSON.parse(readPlainFile(root, 'manifest.json').toString('utf8'));
57
- if (!(0, exports.isExtensionId)(manifest.id)) {
58
- throw new Error(`manifest id ${JSON.stringify(manifest.id)} must be lowercase letters, digits and -`);
59
- }
60
- if (typeof manifest.name !== 'string' || !manifest.name)
61
- throw new Error('manifest name is required');
62
- readPlainFile(root, 'index.js');
63
- const entries = [];
64
- const walk = (rel, depth) => {
65
- if (depth > exports.MAX_FOLDER_DEPTH)
66
- throw new Error(`${rel} is nested deeper than ${exports.MAX_FOLDER_DEPTH} folders`);
67
- for (const item of fs_1.default.readdirSync(insideFolder(root, rel), { withFileTypes: true })) {
68
- if (item.name.startsWith('.') || SKIPPED.has(item.name))
69
- continue;
70
- const childRel = rel ? `${rel}/${item.name}` : item.name;
71
- if (item.isSymbolicLink())
72
- throw new Error(`${childRel} is a symlink; extensions are packaged without symlinks`);
73
- if (item.isDirectory())
74
- walk(childRel, depth + 1);
75
- else if (item.isFile())
76
- entries.push({ name: childRel, data: readPlainFile(root, childRel) });
77
- }
78
- };
79
- walk('', 0);
80
- return { manifest, entries };
81
- }
82
- /** An id already taken by an extension with another name is someone else's; only --force replaces it. */
83
- function planInstall(incoming, installed, force) {
84
- const existing = installed.find((e) => e.id === incoming.id);
85
- if (!existing)
86
- return { action: 'install' };
87
- const from = existing.version ?? 'unknown';
88
- if (existing.name !== incoming.name && !force) {
89
- return {
90
- action: 'refuse',
91
- reason: `id '${incoming.id}' belongs to "${existing.name}" (v${from}), not "${incoming.name}". Use --force to replace it.`,
92
- };
93
- }
94
- return { action: 'update', from };
95
- }
96
- /** The answer of /api/extensions, or an error when another service holds Huddle's address. */
97
- function asExtensionList(value) {
98
- if (!Array.isArray(value))
99
- throw new Error('could not reach Huddle: the address answered, but not with its extensions. Check HUDDLE_URL.');
100
- return value;
101
- }
102
- async function runExtensionList() {
103
- const installed = asExtensionList(await (0, api_1.get)('/api/extensions'));
104
- if (!installed.length) {
105
- console.log('No extensions installed.');
106
- return;
107
- }
108
- (0, utils_1.printTable)(['ID', 'NAME', 'VERSION', 'ENABLED'], installed.map((e) => [e.id, e.name, e.version ?? '-', e.enabled === false ? 'no' : 'yes']));
109
- }
110
- function hasHuddleContainer(rt) {
111
- try {
112
- (0, child_process_1.execFileSync)(rt, ['container', 'inspect', init_1.CONTAINER], { stdio: 'ignore' });
113
- return true;
114
- }
115
- catch {
116
- return false;
117
- }
118
- }
119
- /**
120
- * The engine whose huddle container gets restarted after an install. An explicit
121
- * --runtime / HUDDLE_RUNTIME wins; otherwise the engine that actually runs the
122
- * container. Plain auto-detection prefers Docker, so with Podman owning Huddle
123
- * it would restart an unrelated `huddle` container (or none) and leave the new
124
- * extension inactive.
125
- */
126
- function restartRuntime(explicit, hasContainer = hasHuddleContainer, detect = () => (0, runtime_1.resolveRuntime)().name) {
127
- const requested = explicit ?? process.env.HUDDLE_RUNTIME;
128
- if (requested !== undefined) {
129
- // An empty value is a typo, not a request to auto-detect: probing could pick another engine's container.
130
- if (!requested)
131
- throw new Error('--runtime must not be empty; choose docker or podman.');
132
- return (0, runtime_1.resolveRuntime)(requested).name;
133
- }
134
- const owners = ['docker', 'podman'].filter((rt) => hasContainer(rt));
135
- if (owners.length === 1)
136
- return owners[0];
137
- if (owners.length === 0) {
138
- throw new Error(`No ${init_1.CONTAINER} container found under docker or podman. Run huddle init first.`);
139
- }
140
- // Both commands see a huddle container: either `docker` is a Podman shim
141
- // (one engine, detection reports podman) or two engines each run one.
142
- if (detect() === 'podman')
143
- return 'podman';
144
- throw new Error(`Both docker and podman run a ${init_1.CONTAINER} container; pick one with --runtime <docker|podman>.`);
145
- }
146
- async function runExtensionInstall(dir, opts) {
147
- const { manifest, entries } = collectExtensionFiles(dir);
148
- const plan = planInstall(manifest, asExtensionList(await (0, api_1.get)('/api/extensions')), opts.force);
149
- if (plan.action === 'refuse')
150
- throw new Error(plan.reason);
151
- const result = await (0, api_1.uploadFile)('/api/extensions/upload', `${manifest.id}.zip`, (0, zip_1.createZip)(entries));
152
- const verb = plan.action === 'update' ? `Updated ${manifest.id} v${plan.from} → v${manifest.version ?? '?'}` : `Installed ${manifest.id} v${manifest.version ?? '?'}`;
153
- console.log((0, utils_1.green)(`[OK] ${verb}`));
154
- if (!result.restartRequired)
155
- return;
156
- if (!opts.restart) {
157
- console.log((0, utils_1.yellow)('The gateway keeps running the old code until it restarts. Re-run with --restart, or restart the huddle container.'));
158
- return;
159
- }
160
- const rt = restartRuntime(opts.runtime);
161
- console.log((0, utils_1.dim)(`Restarting the gateway process (${rt} restart ${init_1.CONTAINER}); the container itself is kept.`));
162
- (0, child_process_1.execFileSync)(rt, ['restart', init_1.CONTAINER], { stdio: 'ignore' });
163
- console.log((0, utils_1.green)('[OK] Gateway restarted with the new extension code.'));
164
- }
165
- async function runExtensionRemove(id) {
166
- if (!(0, exports.isExtensionId)(id))
167
- throw new Error(`invalid extension id: ${id}`);
168
- await (0, api_1.del)(`/api/extensions/${id}`);
169
- console.log((0, utils_1.green)(`[OK] Removed ${id}`));
170
- }
package/dist/host-logs.js DELETED
@@ -1,60 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.HOST_CODEX_INDEX_MOUNT = exports.HOST_CODEX_LOGS_MOUNT = exports.HOST_AGENT_LOGS_MOUNT = void 0;
7
- exports.hostAgentLogsMountArgs = hostAgentLogsMountArgs;
8
- exports.hostCodexLogsMountArgs = hostCodexLogsMountArgs;
9
- exports.hostCodexIndexMountArgs = hostCodexIndexMountArgs;
10
- const fs_1 = __importDefault(require("fs"));
11
- const path_1 = __importDefault(require("path"));
12
- /** Must match HOST_AGENT_LOGS_MOUNT in gateway/src/host-config.ts. */
13
- exports.HOST_AGENT_LOGS_MOUNT = '/host-logs/claude/projects';
14
- /** Must match HOST_CODEX_LOGS_MOUNT in gateway/src/host-config.ts. */
15
- exports.HOST_CODEX_LOGS_MOUNT = '/host-logs/codex/sessions';
16
- /** Extensions read the Codex index here; the gateway itself never opens it. */
17
- exports.HOST_CODEX_INDEX_MOUNT = '/host-logs/codex/session_index.jsonl';
18
- /** A real directory only: Docker follows a symlinked source, which could point the mount at ~/.claude itself. */
19
- const isPlainDir = (p) => {
20
- try {
21
- return fs_1.default.lstatSync(p).isDirectory();
22
- }
23
- catch {
24
- return false;
25
- }
26
- };
27
- /**
28
- * `docker run` args that expose the host's Claude session logs to extensions:
29
- * only ~/.claude/projects, read-only — never ~/.claude itself, which holds credentials.
30
- */
31
- function hostAgentLogsMountArgs(cfg, homeDir, exists = isPlainDir) {
32
- if (cfg.hostAgentLogs !== true)
33
- return [];
34
- const projects = path_1.default.join(homeDir, '.claude', 'projects');
35
- return exists(projects) ? ['-v', `${projects}:${exports.HOST_AGENT_LOGS_MOUNT}:ro`] : [];
36
- }
37
- /** The same for Codex: only ~/.codex/sessions, read-only — never ~/.codex itself, which holds auth.json. */
38
- function hostCodexLogsMountArgs(cfg, homeDir, exists = isPlainDir) {
39
- if (cfg.hostAgentLogs !== true)
40
- return [];
41
- const sessions = path_1.default.join(homeDir, '.codex', 'sessions');
42
- return exists(sessions) ? ['-v', `${sessions}:${exports.HOST_CODEX_LOGS_MOUNT}:ro`] : [];
43
- }
44
- /** A plain file only: a symlink or hard link here could point the mount at auth.json. */
45
- const isPlainFile = (p) => {
46
- try {
47
- const stat = fs_1.default.lstatSync(p);
48
- return stat.isFile() && stat.nlink === 1;
49
- }
50
- catch {
51
- return false;
52
- }
53
- };
54
- /** Codex keeps thread names in ~/.codex/session_index.jsonl; only that file is mounted, read-only. */
55
- function hostCodexIndexMountArgs(cfg, homeDir, exists = isPlainFile) {
56
- if (cfg.hostAgentLogs !== true)
57
- return [];
58
- const index = path_1.default.join(homeDir, '.codex', 'session_index.jsonl');
59
- return exists(index) ? ['-v', `${index}:${exports.HOST_CODEX_INDEX_MOUNT}:ro`] : [];
60
- }
@@ -1,186 +0,0 @@
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
- (0, protocol_1.ensurePrivateDir)(protocol_1.PIPE_DIR);
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', 0o600);
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
- }
@@ -1,181 +0,0 @@
1
- "use strict";
2
- // ── Host pipe op `fs.list`: browsing the host, one folder at a time ───────────
3
- // Replaces the old folder *index* (`huddle indexfolder`), which existed only
4
- // because the portal runs in a container and cannot see the host: an operator
5
- // had to walk the host from a shell and push a snapshot of folder names into the
6
- // database. Through the host pipe the portal can just look, and a live look is
7
- // strictly better than a snapshot that went stale the moment a folder was made.
8
- //
9
- // Nothing is stored and nothing walks: each call reads exactly one directory,
10
- // which keeps a drive root cheap and a folder created five seconds ago visible.
11
- // Port of host-browse.ts from feat/sbx-sandboxes-rebased.
12
- var __importDefault = (this && this.__importDefault) || function (mod) {
13
- return (mod && mod.__esModule) ? mod : { "default": mod };
14
- };
15
- Object.defineProperty(exports, "__esModule", { value: true });
16
- exports.toHuddlePath = toHuddlePath;
17
- exports.isAbsoluteHostPath = isAbsoluteHostPath;
18
- exports.hostRoots = hostRoots;
19
- exports.listHostFolders = listHostFolders;
20
- exports.fsList = fsList;
21
- exports.fsResolve = fsResolve;
22
- const fs_1 = __importDefault(require("fs"));
23
- const os_1 = __importDefault(require("os"));
24
- const path_1 = __importDefault(require("path"));
25
- const protocol_1 = require("./protocol");
26
- /**
27
- * A host path in Huddle notation: forward slashes, upper-case drive letter, no
28
- * trailing slash except on a root. One spelling for the whole system, so the
29
- * gateway can compare and store paths without knowing the host's platform.
30
- * Duplicated (on purpose) from the gateway's host-path.ts: the CLI must not
31
- * depend on gateway code.
32
- */
33
- function toHuddlePath(p, platform = process.platform) {
34
- // A bare drive ('c:') is that drive's root here, not its current directory.
35
- if (platform === 'win32' && /^[A-Za-z]:$/.test(p))
36
- return `${p.toUpperCase()}/`;
37
- const normalized = platform === 'win32' ? path_1.default.win32.normalize(p) : path_1.default.posix.normalize(p);
38
- let s = normalized.replace(/\\/g, '/');
39
- s = s.replace(/^([a-z]):/, (_m, d) => `${d.toUpperCase()}:`);
40
- while (s.length > 1 && s.endsWith('/') && !/^[A-Z]:\/$/.test(s))
41
- s = s.slice(0, -1);
42
- return s;
43
- }
44
- /** Absolute in the host's own sense: '/x' on POSIX, 'C:/x' or a UNC '//server/share' on Windows. */
45
- function isAbsoluteHostPath(p, platform = process.platform) {
46
- if (platform === 'win32')
47
- return /^[A-Za-z]:[\\/]/.test(p) || /^[\\/]{2}[^\\/]/.test(p);
48
- return p.startsWith('/');
49
- }
50
- function leaf(p) {
51
- if (p === '/')
52
- return '/';
53
- if (/^[A-Z]:\/$/.test(p))
54
- return p.slice(0, 2);
55
- return p.slice(p.lastIndexOf('/') + 1);
56
- }
57
- // Joins in Huddle notation rather than the platform's, so Windows hands back
58
- // 'C:/projects/app' and not 'C:\projects\app'.
59
- function joinHost(parent, segment) {
60
- return parent.endsWith('/') ? `${parent}${segment}` : `${parent}/${segment}`;
61
- }
62
- /**
63
- * Where browsing starts: the drives (Windows) or `/` (elsewhere), plus the home
64
- * folder because that is where projects usually live and nobody wants to click
65
- * through /home/<user> every time.
66
- */
67
- function hostRoots() {
68
- const out = [];
69
- const seen = new Set();
70
- const add = (p, name) => {
71
- const key = p.toLowerCase();
72
- if (seen.has(key))
73
- return;
74
- seen.add(key);
75
- out.push({ path: p, name: name ?? leaf(p) });
76
- };
77
- if (process.platform === 'win32') {
78
- // Probing 26 letters is a stat per letter and no slower than the WMI query
79
- // that answers the same question, without a dependency. A CD drive with no
80
- // disc exists but throws on read; it is no place for a workspace, so
81
- // anything unreadable is left out.
82
- for (let i = 0; i < 26; i++) {
83
- const letter = String.fromCharCode(65 + i);
84
- try {
85
- fs_1.default.readdirSync(`${letter}:/`);
86
- }
87
- catch {
88
- continue;
89
- }
90
- add(`${letter}:/`, `${letter}:`);
91
- }
92
- }
93
- else {
94
- add('/', '/');
95
- }
96
- const home = os_1.default.homedir();
97
- if (home) {
98
- try {
99
- if (fs_1.default.statSync(home).isDirectory())
100
- add(toHuddlePath(home));
101
- }
102
- catch { /* no readable home: the drives/root above are enough */ }
103
- }
104
- return out;
105
- }
106
- /**
107
- * The immediate subfolders of `dir`, sorted case-insensitively like a file
108
- * dialog. Only one level: the portal asks again when it opens a folder.
109
- *
110
- * Hidden (dot) folders are included: `.config`, `.local` or a dotted worktree
111
- * are real places, and a picker that omits a folder the operator sees in their
112
- * own file manager reads as broken. Symlinked folders are included too; nothing
113
- * walks, so a link loop is at worst someone clicking in circles.
114
- *
115
- * Sorting happens before truncation, so a huge folder shows its first `max`
116
- * names alphabetically rather than an arbitrary readdir-order slice.
117
- */
118
- async function listHostFolders(dir, max = protocol_1.MAX_FOLDER_ENTRIES) {
119
- let entries;
120
- try {
121
- entries = await fs_1.default.promises.readdir(dir, { withFileTypes: true });
122
- }
123
- catch (err) {
124
- throw new protocol_1.PipeError('not_found', `cannot read folder ${dir}: ${err.code ?? err}`);
125
- }
126
- const names = [];
127
- for (const e of entries) {
128
- let isDir = e.isDirectory();
129
- if (!isDir && e.isSymbolicLink()) {
130
- try {
131
- isDir = (await fs_1.default.promises.stat(path_1.default.join(dir, e.name))).isDirectory();
132
- }
133
- catch {
134
- continue; // dangling link
135
- }
136
- }
137
- if (isDir)
138
- names.push(e.name);
139
- }
140
- names.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' }));
141
- const truncated = names.length > max;
142
- const folders = names.slice(0, max).map((name) => ({ path: joinHost(dir, name), name }));
143
- return { path: dir, folders, truncated, max };
144
- }
145
- /** The `fs.list` op: no path → the roots, otherwise one folder. */
146
- async function fsList(args, max = protocol_1.MAX_FOLDER_ENTRIES) {
147
- const raw = args.path;
148
- if (raw === undefined || raw === null || raw === '') {
149
- return { path: '', folders: hostRoots(), truncated: false, max };
150
- }
151
- if (typeof raw !== 'string')
152
- throw new protocol_1.PipeError('bad_request', 'path must be a string');
153
- if (raw.includes('\0'))
154
- throw new protocol_1.PipeError('bad_request', 'path contains a NUL byte');
155
- if (!isAbsoluteHostPath(raw))
156
- throw new protocol_1.PipeError('bad_request', `not an absolute host path: ${raw}`);
157
- return listHostFolders(toHuddlePath(raw), max);
158
- }
159
- const MAX_RESOLVE_PATHS = 64;
160
- /**
161
- * The `fs.resolve` op: where each path really is (links followed), or null when
162
- * it does not exist. The portal cannot see host links, and a workspace that is a
163
- * link into ~/.huddle would otherwise pass its lexical mount check.
164
- */
165
- async function fsResolve(args) {
166
- const raw = args.paths;
167
- if (!Array.isArray(raw) || raw.length > MAX_RESOLVE_PATHS)
168
- throw new protocol_1.PipeError('bad_request', `paths must be an array of at most ${MAX_RESOLVE_PATHS}`);
169
- const paths = [];
170
- for (const p of raw) {
171
- if (typeof p !== 'string' || p.includes('\0') || !isAbsoluteHostPath(p))
172
- throw new protocol_1.PipeError('bad_request', 'paths must be absolute host paths');
173
- try {
174
- paths.push(toHuddlePath(await fs_1.default.promises.realpath(p)));
175
- }
176
- catch {
177
- paths.push(null);
178
- }
179
- }
180
- return { paths };
181
- }