@infosupport/huddle-cli 0.0.0-experiment-147.96.1 → 0.0.0-experiment-160.98.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 +14 -32
- package/dist/api.js +5 -11
- package/dist/config.js +2 -5
- package/dist/index.js +12 -69
- package/dist/init.js +23 -23
- package/dist/pipe/command.js +186 -0
- package/dist/pipe/fs-list.js +157 -0
- package/dist/pipe/protocol.js +66 -0
- package/dist/pipe/serve.js +210 -0
- package/dist/pipe/tools.js +228 -0
- package/dist/start.js +8 -9
- package/package.json +3 -7
- package/dist/extension.js +0 -170
- package/dist/host-logs.js +0 -60
- package/dist/indexfolder.js +0 -167
- package/dist/zip.js +0 -74
|
@@ -0,0 +1,157 @@
|
|
|
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
|
+
const fs_1 = __importDefault(require("fs"));
|
|
22
|
+
const os_1 = __importDefault(require("os"));
|
|
23
|
+
const path_1 = __importDefault(require("path"));
|
|
24
|
+
const protocol_1 = require("./protocol");
|
|
25
|
+
/**
|
|
26
|
+
* A host path in Huddle notation: forward slashes, upper-case drive letter, no
|
|
27
|
+
* trailing slash except on a root. One spelling for the whole system, so the
|
|
28
|
+
* gateway can compare and store paths without knowing the host's platform.
|
|
29
|
+
* Duplicated (on purpose) from the gateway's host-path.ts: the CLI must not
|
|
30
|
+
* depend on gateway code.
|
|
31
|
+
*/
|
|
32
|
+
function toHuddlePath(p, platform = process.platform) {
|
|
33
|
+
// A bare drive ('c:') is that drive's root here, not its current directory.
|
|
34
|
+
if (platform === 'win32' && /^[A-Za-z]:$/.test(p))
|
|
35
|
+
return `${p.toUpperCase()}/`;
|
|
36
|
+
const normalized = platform === 'win32' ? path_1.default.win32.normalize(p) : path_1.default.posix.normalize(p);
|
|
37
|
+
let s = normalized.replace(/\\/g, '/');
|
|
38
|
+
s = s.replace(/^([a-z]):/, (_m, d) => `${d.toUpperCase()}:`);
|
|
39
|
+
while (s.length > 1 && s.endsWith('/') && !/^[A-Z]:\/$/.test(s))
|
|
40
|
+
s = s.slice(0, -1);
|
|
41
|
+
return s;
|
|
42
|
+
}
|
|
43
|
+
/** Absolute in the host's own sense: '/x' on POSIX, 'C:/x' or a UNC '//server/share' on Windows. */
|
|
44
|
+
function isAbsoluteHostPath(p, platform = process.platform) {
|
|
45
|
+
if (platform === 'win32')
|
|
46
|
+
return /^[A-Za-z]:[\\/]/.test(p) || /^[\\/]{2}[^\\/]/.test(p);
|
|
47
|
+
return p.startsWith('/');
|
|
48
|
+
}
|
|
49
|
+
function leaf(p) {
|
|
50
|
+
if (p === '/')
|
|
51
|
+
return '/';
|
|
52
|
+
if (/^[A-Z]:\/$/.test(p))
|
|
53
|
+
return p.slice(0, 2);
|
|
54
|
+
return p.slice(p.lastIndexOf('/') + 1);
|
|
55
|
+
}
|
|
56
|
+
// Joins in Huddle notation rather than the platform's, so Windows hands back
|
|
57
|
+
// 'C:/projects/app' and not 'C:\projects\app'.
|
|
58
|
+
function joinHost(parent, segment) {
|
|
59
|
+
return parent.endsWith('/') ? `${parent}${segment}` : `${parent}/${segment}`;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Where browsing starts: the drives (Windows) or `/` (elsewhere), plus the home
|
|
63
|
+
* folder because that is where projects usually live and nobody wants to click
|
|
64
|
+
* through /home/<user> every time.
|
|
65
|
+
*/
|
|
66
|
+
function hostRoots() {
|
|
67
|
+
const out = [];
|
|
68
|
+
const seen = new Set();
|
|
69
|
+
const add = (p, name) => {
|
|
70
|
+
const key = p.toLowerCase();
|
|
71
|
+
if (seen.has(key))
|
|
72
|
+
return;
|
|
73
|
+
seen.add(key);
|
|
74
|
+
out.push({ path: p, name: name ?? leaf(p) });
|
|
75
|
+
};
|
|
76
|
+
if (process.platform === 'win32') {
|
|
77
|
+
// Probing 26 letters is a stat per letter and no slower than the WMI query
|
|
78
|
+
// that answers the same question, without a dependency. A CD drive with no
|
|
79
|
+
// disc exists but throws on read; it is no place for a workspace, so
|
|
80
|
+
// anything unreadable is left out.
|
|
81
|
+
for (let i = 0; i < 26; i++) {
|
|
82
|
+
const letter = String.fromCharCode(65 + i);
|
|
83
|
+
try {
|
|
84
|
+
fs_1.default.readdirSync(`${letter}:/`);
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
add(`${letter}:/`, `${letter}:`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
add('/', '/');
|
|
94
|
+
}
|
|
95
|
+
const home = os_1.default.homedir();
|
|
96
|
+
if (home) {
|
|
97
|
+
try {
|
|
98
|
+
if (fs_1.default.statSync(home).isDirectory())
|
|
99
|
+
add(toHuddlePath(home));
|
|
100
|
+
}
|
|
101
|
+
catch { /* no readable home: the drives/root above are enough */ }
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* The immediate subfolders of `dir`, sorted case-insensitively like a file
|
|
107
|
+
* dialog. Only one level: the portal asks again when it opens a folder.
|
|
108
|
+
*
|
|
109
|
+
* Hidden (dot) folders are included: `.config`, `.local` or a dotted worktree
|
|
110
|
+
* are real places, and a picker that omits a folder the operator sees in their
|
|
111
|
+
* own file manager reads as broken. Symlinked folders are included too; nothing
|
|
112
|
+
* walks, so a link loop is at worst someone clicking in circles.
|
|
113
|
+
*
|
|
114
|
+
* Sorting happens before truncation, so a huge folder shows its first `max`
|
|
115
|
+
* names alphabetically rather than an arbitrary readdir-order slice.
|
|
116
|
+
*/
|
|
117
|
+
async function listHostFolders(dir, max = protocol_1.MAX_FOLDER_ENTRIES) {
|
|
118
|
+
let entries;
|
|
119
|
+
try {
|
|
120
|
+
entries = await fs_1.default.promises.readdir(dir, { withFileTypes: true });
|
|
121
|
+
}
|
|
122
|
+
catch (err) {
|
|
123
|
+
throw new protocol_1.PipeError('not_found', `cannot read folder ${dir}: ${err.code ?? err}`);
|
|
124
|
+
}
|
|
125
|
+
const names = [];
|
|
126
|
+
for (const e of entries) {
|
|
127
|
+
let isDir = e.isDirectory();
|
|
128
|
+
if (!isDir && e.isSymbolicLink()) {
|
|
129
|
+
try {
|
|
130
|
+
isDir = (await fs_1.default.promises.stat(path_1.default.join(dir, e.name))).isDirectory();
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
continue; // dangling link
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (isDir)
|
|
137
|
+
names.push(e.name);
|
|
138
|
+
}
|
|
139
|
+
names.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' }));
|
|
140
|
+
const truncated = names.length > max;
|
|
141
|
+
const folders = names.slice(0, max).map((name) => ({ path: joinHost(dir, name), name }));
|
|
142
|
+
return { path: dir, folders, truncated, max };
|
|
143
|
+
}
|
|
144
|
+
/** The `fs.list` op: no path → the roots, otherwise one folder. */
|
|
145
|
+
async function fsList(args, max = protocol_1.MAX_FOLDER_ENTRIES) {
|
|
146
|
+
const raw = args.path;
|
|
147
|
+
if (raw === undefined || raw === null || raw === '') {
|
|
148
|
+
return { path: '', folders: hostRoots(), truncated: false, max };
|
|
149
|
+
}
|
|
150
|
+
if (typeof raw !== 'string')
|
|
151
|
+
throw new protocol_1.PipeError('bad_request', 'path must be a string');
|
|
152
|
+
if (raw.includes('\0'))
|
|
153
|
+
throw new protocol_1.PipeError('bad_request', 'path contains a NUL byte');
|
|
154
|
+
if (!isAbsoluteHostPath(raw))
|
|
155
|
+
throw new protocol_1.PipeError('bad_request', `not an absolute host path: ${raw}`);
|
|
156
|
+
return listHostFolders(toHuddlePath(raw), max);
|
|
157
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ── Host pipe: shared protocol bits ───────────────────────────────────────────
|
|
3
|
+
// The host pipe is a folder (~/.huddle/pipe on the host, /huddle-home/pipe in the
|
|
4
|
+
// gateway) through which the gateway asks the host for things it cannot do from
|
|
5
|
+
// inside its container. See docs/host-pipe.md — that file is the contract; the
|
|
6
|
+
// names and numbers below mirror it and must not drift.
|
|
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.PipeError = exports.MAX_TOOL_TIMEOUT_MS = exports.DEFAULT_TOOL_TIMEOUT_MS = exports.MAX_OUTPUT_BYTES = exports.MAX_FOLDER_ENTRIES = exports.STALE_FILE_MS = exports.HEARTBEAT_STALE_MS = exports.HEARTBEAT_MS = exports.POLL_MS = exports.LOG_FILE = exports.HEARTBEAT_FILE = exports.PIPE_DIR = exports.PROTOCOL_VERSION = void 0;
|
|
12
|
+
exports.writeJsonAtomic = writeJsonAtomic;
|
|
13
|
+
exports.readHeartbeat = readHeartbeat;
|
|
14
|
+
exports.heartbeatFresh = heartbeatFresh;
|
|
15
|
+
const fs_1 = __importDefault(require("fs"));
|
|
16
|
+
const path_1 = __importDefault(require("path"));
|
|
17
|
+
const config_1 = require("../config");
|
|
18
|
+
exports.PROTOCOL_VERSION = 1;
|
|
19
|
+
/** Where the agent serves by default: inside the ~/.huddle mount the gateway already has. */
|
|
20
|
+
exports.PIPE_DIR = path_1.default.join(config_1.CONFIG_DIR, 'pipe');
|
|
21
|
+
exports.HEARTBEAT_FILE = 'host.json';
|
|
22
|
+
exports.LOG_FILE = 'host.log';
|
|
23
|
+
exports.POLL_MS = 100;
|
|
24
|
+
exports.HEARTBEAT_MS = 2000;
|
|
25
|
+
/** The gateway calls the agent offline when the heartbeat is older than this. */
|
|
26
|
+
exports.HEARTBEAT_STALE_MS = 10_000;
|
|
27
|
+
/** Leftover request/reply files older than this are deleted on start. */
|
|
28
|
+
exports.STALE_FILE_MS = 60 * 60 * 1000;
|
|
29
|
+
exports.MAX_FOLDER_ENTRIES = 2000;
|
|
30
|
+
exports.MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
|
|
31
|
+
exports.DEFAULT_TOOL_TIMEOUT_MS = 30_000;
|
|
32
|
+
exports.MAX_TOOL_TIMEOUT_MS = 15 * 60 * 1000;
|
|
33
|
+
/** Thrown by an op handler to answer with `ok:false` and a specific code. */
|
|
34
|
+
class PipeError extends Error {
|
|
35
|
+
code;
|
|
36
|
+
constructor(code, message) {
|
|
37
|
+
super(message);
|
|
38
|
+
this.code = code;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
exports.PipeError = PipeError;
|
|
42
|
+
/**
|
|
43
|
+
* Writes JSON to `<file>.tmp` and renames it over `<file>`, so the other side
|
|
44
|
+
* never reads a half-written file. Rename within one folder is atomic on every
|
|
45
|
+
* platform, including across the Docker bind mount.
|
|
46
|
+
*/
|
|
47
|
+
function writeJsonAtomic(file, data) {
|
|
48
|
+
const tmp = `${file}.tmp`;
|
|
49
|
+
fs_1.default.writeFileSync(tmp, JSON.stringify(data));
|
|
50
|
+
fs_1.default.renameSync(tmp, file);
|
|
51
|
+
}
|
|
52
|
+
/** The heartbeat in `dir`, or null when there is none (or it is unreadable). */
|
|
53
|
+
function readHeartbeat(dir = exports.PIPE_DIR) {
|
|
54
|
+
try {
|
|
55
|
+
const hb = JSON.parse(fs_1.default.readFileSync(path_1.default.join(dir, exports.HEARTBEAT_FILE), 'utf8'));
|
|
56
|
+
return typeof hb === 'object' && hb !== null && typeof hb.pid === 'number' ? hb : null;
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** Same rule as the gateway: online only while the heartbeat is younger than 10 s. */
|
|
63
|
+
function heartbeatFresh(hb, now = Date.now()) {
|
|
64
|
+
const updated = Date.parse(hb.updatedAt);
|
|
65
|
+
return Number.isFinite(updated) && now - updated < exports.HEARTBEAT_STALE_MS;
|
|
66
|
+
}
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ── Host pipe: the agent's serve loop ─────────────────────────────────────────
|
|
3
|
+
// Polls the pipe folder for `<id>.in`, claims each by renaming it to
|
|
4
|
+
// `<id>.busy` (so it is handled exactly once, even if two agents race), runs it
|
|
5
|
+
// without blocking the loop (a 10-minute `sbx create` must not hold up a folder
|
|
6
|
+
// listing), writes `<id>.out` atomically and deletes the `.busy`. Every request
|
|
7
|
+
// gets a reply, a malformed one included; nothing a request contains can crash
|
|
8
|
+
// the loop. See docs/host-pipe.md for the protocol.
|
|
9
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
10
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
11
|
+
};
|
|
12
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
|
+
exports.cleanStale = cleanStale;
|
|
14
|
+
exports.servePipe = servePipe;
|
|
15
|
+
const fs_1 = __importDefault(require("fs"));
|
|
16
|
+
const os_1 = __importDefault(require("os"));
|
|
17
|
+
const path_1 = __importDefault(require("path"));
|
|
18
|
+
const self_update_1 = require("../self-update");
|
|
19
|
+
const protocol_1 = require("./protocol");
|
|
20
|
+
const fs_list_1 = require("./fs-list");
|
|
21
|
+
const tools_1 = require("./tools");
|
|
22
|
+
// Ids are generated by the gateway (32 hex); anything that does not look like
|
|
23
|
+
// an id is not ours and is left alone rather than turned into a reply path.
|
|
24
|
+
const REQUEST_RE = /^([A-Za-z0-9_-]{1,128})\.in$/;
|
|
25
|
+
const LEFTOVER_RE = /\.(in|busy|out|tmp)$/;
|
|
26
|
+
async function dispatch(req, maxEntries) {
|
|
27
|
+
const args = req.args ?? {};
|
|
28
|
+
switch (req.op) {
|
|
29
|
+
case 'host.info':
|
|
30
|
+
return {
|
|
31
|
+
platform: process.platform,
|
|
32
|
+
version: (0, self_update_1.cliVersion)(),
|
|
33
|
+
home: (0, fs_list_1.toHuddlePath)(os_1.default.homedir()),
|
|
34
|
+
tools: await (0, tools_1.toolsInfo)(),
|
|
35
|
+
};
|
|
36
|
+
case 'fs.list':
|
|
37
|
+
return (0, fs_list_1.fsList)(args, maxEntries);
|
|
38
|
+
case 'tool.run':
|
|
39
|
+
return (0, tools_1.toolRun)(args);
|
|
40
|
+
default:
|
|
41
|
+
throw new protocol_1.PipeError('unknown_op', `unknown op '${req.op}'`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function parseRequest(text) {
|
|
45
|
+
let req;
|
|
46
|
+
try {
|
|
47
|
+
req = JSON.parse(text);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
throw new protocol_1.PipeError('bad_request', 'request is not valid JSON');
|
|
51
|
+
}
|
|
52
|
+
if (typeof req !== 'object' || req === null || Array.isArray(req))
|
|
53
|
+
throw new protocol_1.PipeError('bad_request', 'request must be a JSON object');
|
|
54
|
+
const r = req;
|
|
55
|
+
if (r.v !== protocol_1.PROTOCOL_VERSION)
|
|
56
|
+
throw new protocol_1.PipeError('bad_request', `unsupported protocol version ${JSON.stringify(r.v)} (agent speaks ${protocol_1.PROTOCOL_VERSION})`);
|
|
57
|
+
if (typeof r.op !== 'string' || !r.op)
|
|
58
|
+
throw new protocol_1.PipeError('bad_request', 'op must be a non-empty string');
|
|
59
|
+
if (r.args !== undefined && (typeof r.args !== 'object' || r.args === null || Array.isArray(r.args))) {
|
|
60
|
+
throw new protocol_1.PipeError('bad_request', 'args must be an object');
|
|
61
|
+
}
|
|
62
|
+
return r;
|
|
63
|
+
}
|
|
64
|
+
/** Deletes request/reply leftovers older than STALE_FILE_MS, skipping ids still in flight. */
|
|
65
|
+
function cleanStale(dir, inFlight = new Set(), now = Date.now()) {
|
|
66
|
+
const removed = [];
|
|
67
|
+
let names;
|
|
68
|
+
try {
|
|
69
|
+
names = fs_1.default.readdirSync(dir);
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return removed;
|
|
73
|
+
}
|
|
74
|
+
for (const name of names) {
|
|
75
|
+
if (!LEFTOVER_RE.test(name) || inFlight.has(name.split('.')[0]))
|
|
76
|
+
continue;
|
|
77
|
+
const file = path_1.default.join(dir, name);
|
|
78
|
+
try {
|
|
79
|
+
if (now - fs_1.default.statSync(file).mtimeMs > protocol_1.STALE_FILE_MS) {
|
|
80
|
+
fs_1.default.unlinkSync(file);
|
|
81
|
+
removed.push(name);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
catch { /* gone already, or not ours to delete */ }
|
|
85
|
+
}
|
|
86
|
+
return removed;
|
|
87
|
+
}
|
|
88
|
+
function servePipe(opts) {
|
|
89
|
+
const { dir } = opts;
|
|
90
|
+
const maxEntries = opts.maxEntries ?? protocol_1.MAX_FOLDER_ENTRIES;
|
|
91
|
+
const log = opts.log ?? (() => { });
|
|
92
|
+
fs_1.default.mkdirSync(dir, { recursive: true });
|
|
93
|
+
const startedAt = new Date().toISOString();
|
|
94
|
+
const version = (0, self_update_1.cliVersion)();
|
|
95
|
+
const inFlight = new Map();
|
|
96
|
+
let stopped = false;
|
|
97
|
+
let pollTimer;
|
|
98
|
+
let heartbeatTimer;
|
|
99
|
+
let cleanupTimer;
|
|
100
|
+
const removed = cleanStale(dir);
|
|
101
|
+
if (removed.length)
|
|
102
|
+
log(`removed ${removed.length} stale file(s)`);
|
|
103
|
+
const handle = async (id) => {
|
|
104
|
+
const busy = path_1.default.join(dir, `${id}.busy`);
|
|
105
|
+
let reply;
|
|
106
|
+
let op = '?';
|
|
107
|
+
try {
|
|
108
|
+
const req = parseRequest(await fs_1.default.promises.readFile(busy, 'utf8'));
|
|
109
|
+
op = req.op;
|
|
110
|
+
reply = { ok: true, result: await dispatch(req, maxEntries) };
|
|
111
|
+
}
|
|
112
|
+
catch (err) {
|
|
113
|
+
reply = err instanceof protocol_1.PipeError
|
|
114
|
+
? { ok: false, error: { code: err.code, message: err.message } }
|
|
115
|
+
: { ok: false, error: { code: 'internal', message: err instanceof Error ? err.message : String(err) } };
|
|
116
|
+
}
|
|
117
|
+
try {
|
|
118
|
+
(0, protocol_1.writeJsonAtomic)(path_1.default.join(dir, `${id}.out`), reply);
|
|
119
|
+
}
|
|
120
|
+
catch (err) {
|
|
121
|
+
log(`${id} ${op}: could not write reply: ${err instanceof Error ? err.message : err}`);
|
|
122
|
+
}
|
|
123
|
+
try {
|
|
124
|
+
fs_1.default.unlinkSync(busy);
|
|
125
|
+
}
|
|
126
|
+
catch { /* already gone */ }
|
|
127
|
+
log(`${id} ${op} -> ${reply.ok ? 'ok' : reply.error.code}`);
|
|
128
|
+
};
|
|
129
|
+
const poll = async () => {
|
|
130
|
+
let names = [];
|
|
131
|
+
try {
|
|
132
|
+
names = await fs_1.default.promises.readdir(dir);
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
// The folder went away (e.g. ~/.huddle was removed); recreate and carry on.
|
|
136
|
+
try {
|
|
137
|
+
fs_1.default.mkdirSync(dir, { recursive: true });
|
|
138
|
+
}
|
|
139
|
+
catch { /* retry next tick */ }
|
|
140
|
+
}
|
|
141
|
+
for (const name of names) {
|
|
142
|
+
const m = REQUEST_RE.exec(name);
|
|
143
|
+
if (!m || stopped)
|
|
144
|
+
continue;
|
|
145
|
+
const id = m[1];
|
|
146
|
+
// Claiming is the rename: whoever renames first owns the request. A
|
|
147
|
+
// failure means someone else got it (or the gateway gave up on it).
|
|
148
|
+
try {
|
|
149
|
+
fs_1.default.renameSync(path_1.default.join(dir, name), path_1.default.join(dir, `${id}.busy`));
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
const p = handle(id).finally(() => inFlight.delete(id));
|
|
155
|
+
inFlight.set(id, p);
|
|
156
|
+
}
|
|
157
|
+
if (!stopped)
|
|
158
|
+
pollTimer = setTimeout(() => void poll(), opts.pollMs ?? protocol_1.POLL_MS);
|
|
159
|
+
};
|
|
160
|
+
const heartbeat = () => {
|
|
161
|
+
const file = path_1.default.join(dir, protocol_1.HEARTBEAT_FILE);
|
|
162
|
+
// Another agent (a newer CLI started by `huddle init`) took over: step aside
|
|
163
|
+
// rather than fight over host.json every two seconds.
|
|
164
|
+
const current = (0, protocol_1.readHeartbeat)(dir);
|
|
165
|
+
if (current && current.pid !== process.pid && current.startedAt > startedAt) {
|
|
166
|
+
log(`replaced by pid ${current.pid}; stopping`);
|
|
167
|
+
void stop().then(() => opts.onReplaced?.());
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
const hb = {
|
|
171
|
+
v: protocol_1.PROTOCOL_VERSION,
|
|
172
|
+
pid: process.pid,
|
|
173
|
+
version,
|
|
174
|
+
platform: process.platform,
|
|
175
|
+
tools: (0, tools_1.availableTools)(),
|
|
176
|
+
startedAt,
|
|
177
|
+
updatedAt: new Date().toISOString(),
|
|
178
|
+
};
|
|
179
|
+
try {
|
|
180
|
+
(0, protocol_1.writeJsonAtomic)(file, hb);
|
|
181
|
+
}
|
|
182
|
+
catch (err) {
|
|
183
|
+
log(`could not write heartbeat: ${err instanceof Error ? err.message : err}`);
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
heartbeatTimer = setInterval(heartbeat, opts.heartbeatMs ?? protocol_1.HEARTBEAT_MS);
|
|
187
|
+
heartbeat();
|
|
188
|
+
// Orphaned replies (the gateway timed out and never collected them) would
|
|
189
|
+
// otherwise pile up for as long as the agent runs.
|
|
190
|
+
cleanupTimer = setInterval(() => cleanStale(dir, new Set(inFlight.keys())), protocol_1.STALE_FILE_MS);
|
|
191
|
+
cleanupTimer.unref();
|
|
192
|
+
void poll();
|
|
193
|
+
async function stop() {
|
|
194
|
+
if (!stopped) {
|
|
195
|
+
stopped = true;
|
|
196
|
+
clearTimeout(pollTimer);
|
|
197
|
+
clearInterval(heartbeatTimer);
|
|
198
|
+
clearInterval(cleanupTimer);
|
|
199
|
+
const current = (0, protocol_1.readHeartbeat)(dir);
|
|
200
|
+
if (current && current.pid === process.pid && current.startedAt === startedAt) {
|
|
201
|
+
try {
|
|
202
|
+
fs_1.default.unlinkSync(path_1.default.join(dir, protocol_1.HEARTBEAT_FILE));
|
|
203
|
+
}
|
|
204
|
+
catch { /* already gone */ }
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
await Promise.allSettled([...inFlight.values()]);
|
|
208
|
+
}
|
|
209
|
+
return { stop };
|
|
210
|
+
}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ── Host pipe op `tool.run`: allowlisted host binaries, argv only ─────────────
|
|
3
|
+
// The gateway can ask the host to run a tool such as Docker Sandboxes (`sbx`).
|
|
4
|
+
// Only binaries named in TOOLS can run, always with an argv array and never via
|
|
5
|
+
// a shell, so an argument like `$(whoami)` or `& calc` stays a literal string.
|
|
6
|
+
// Adding the next environment tool is one entry in TOOLS (plus its provider in
|
|
7
|
+
// gateway/src/environments/).
|
|
8
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
9
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.TOOLS = void 0;
|
|
13
|
+
exports.resolveTool = resolveTool;
|
|
14
|
+
exports.execTool = execTool;
|
|
15
|
+
exports.toolRun = toolRun;
|
|
16
|
+
exports.toolVersion = toolVersion;
|
|
17
|
+
exports.toolsInfo = toolsInfo;
|
|
18
|
+
exports.availableTools = availableTools;
|
|
19
|
+
const fs_1 = __importDefault(require("fs"));
|
|
20
|
+
const os_1 = __importDefault(require("os"));
|
|
21
|
+
const path_1 = __importDefault(require("path"));
|
|
22
|
+
const child_process_1 = require("child_process");
|
|
23
|
+
const protocol_1 = require("./protocol");
|
|
24
|
+
exports.TOOLS = {
|
|
25
|
+
sbx: { bins: ['sbx', 'sbx.exe'], env: 'HUDDLE_SBX_BIN' },
|
|
26
|
+
};
|
|
27
|
+
// Windows runs .bat/.cmd through cmd.exe whatever argv we pass, and cmd.exe
|
|
28
|
+
// re-parses the command line, so an argument could inject a command. Only real
|
|
29
|
+
// executables are accepted.
|
|
30
|
+
const REFUSED_EXT = new Set(['.bat', '.cmd']);
|
|
31
|
+
const WIN_RUNNABLE_EXT = new Set(['.exe', '.com']);
|
|
32
|
+
function isRunnableFile(file) {
|
|
33
|
+
try {
|
|
34
|
+
if (!fs_1.default.statSync(file).isFile())
|
|
35
|
+
return false;
|
|
36
|
+
if (process.platform !== 'win32')
|
|
37
|
+
fs_1.default.accessSync(file, fs_1.default.constants.X_OK);
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** Candidate file names for one bin: on Windows `sbx` becomes sbx.COM, sbx.EXE, ... per PATHEXT. */
|
|
45
|
+
function candidates(bin) {
|
|
46
|
+
if (process.platform !== 'win32' || path_1.default.extname(bin))
|
|
47
|
+
return [bin];
|
|
48
|
+
const exts = (process.env.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean);
|
|
49
|
+
return exts.map((ext) => bin + ext.toLowerCase());
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Finds a tool's binary without a shell: the env override if set, otherwise the
|
|
53
|
+
* first runnable match on PATH. A .bat/.cmd hit is skipped, and reported as
|
|
54
|
+
* not_allowed only when nothing else was found.
|
|
55
|
+
*/
|
|
56
|
+
function resolveTool(name) {
|
|
57
|
+
const spec = Object.prototype.hasOwnProperty.call(exports.TOOLS, name) ? exports.TOOLS[name] : undefined;
|
|
58
|
+
if (!spec)
|
|
59
|
+
return { error: new protocol_1.PipeError('not_allowed', `tool '${name}' is not allowlisted on the host`) };
|
|
60
|
+
const override = process.env[spec.env]?.trim();
|
|
61
|
+
const bins = override ? [override] : spec.bins;
|
|
62
|
+
const dirs = (process.env.PATH ?? '').split(path_1.default.delimiter).filter(Boolean);
|
|
63
|
+
let refused;
|
|
64
|
+
for (const bin of bins) {
|
|
65
|
+
// A bin with a directory in it is a path, not a name to look up on PATH.
|
|
66
|
+
const lookups = bin.includes('/') || bin.includes('\\') ? [path_1.default.resolve(bin)] : dirs.map((d) => path_1.default.join(d, bin));
|
|
67
|
+
for (const lookup of lookups) {
|
|
68
|
+
for (const file of candidates(lookup)) {
|
|
69
|
+
const ext = path_1.default.extname(file).toLowerCase();
|
|
70
|
+
// On Windows, skip batch files (they go through cmd.exe) and non-executables.
|
|
71
|
+
if (process.platform === 'win32' && !WIN_RUNNABLE_EXT.has(ext)) {
|
|
72
|
+
if (REFUSED_EXT.has(ext) && isRunnableFile(file))
|
|
73
|
+
refused ??= file;
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (isRunnableFile(file))
|
|
77
|
+
return { path: file };
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (refused) {
|
|
82
|
+
return { error: new protocol_1.PipeError('not_allowed', `refusing to run ${refused}: batch files go through cmd.exe`) };
|
|
83
|
+
}
|
|
84
|
+
const where = override ? `${spec.env}=${override}` : `${spec.bins.join(' / ')} on PATH`;
|
|
85
|
+
return { error: new protocol_1.PipeError('tool_missing', `${name} is not installed on the host (looked for ${where})`) };
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Runs `file` with argv `args`: no shell, stdin closed, no console window, a
|
|
89
|
+
* hard timeout and at most MAX_OUTPUT_BYTES kept per stream (the rest is
|
|
90
|
+
* drained and dropped, so a chatty tool cannot exhaust the agent's memory).
|
|
91
|
+
*/
|
|
92
|
+
function execTool(file, args, timeoutMs, maxBytes = protocol_1.MAX_OUTPUT_BYTES) {
|
|
93
|
+
return new Promise((resolve, reject) => {
|
|
94
|
+
let child;
|
|
95
|
+
try {
|
|
96
|
+
child = (0, child_process_1.spawn)(file, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, shell: false });
|
|
97
|
+
}
|
|
98
|
+
catch (err) {
|
|
99
|
+
reject(err);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
const collect = () => {
|
|
103
|
+
const chunks = [];
|
|
104
|
+
let size = 0;
|
|
105
|
+
let dropped = false;
|
|
106
|
+
return {
|
|
107
|
+
push(chunk) {
|
|
108
|
+
if (size >= maxBytes) {
|
|
109
|
+
dropped = true;
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
const room = maxBytes - size;
|
|
113
|
+
if (chunk.length > room) {
|
|
114
|
+
chunk = chunk.subarray(0, room);
|
|
115
|
+
dropped = true;
|
|
116
|
+
}
|
|
117
|
+
chunks.push(chunk);
|
|
118
|
+
size += chunk.length;
|
|
119
|
+
},
|
|
120
|
+
text() {
|
|
121
|
+
const s = Buffer.concat(chunks).toString('utf8');
|
|
122
|
+
return dropped ? `${s}\n[huddle] output truncated at ${maxBytes} bytes` : s;
|
|
123
|
+
},
|
|
124
|
+
};
|
|
125
|
+
};
|
|
126
|
+
const out = collect();
|
|
127
|
+
const err = collect();
|
|
128
|
+
child.stdout.on('data', (c) => out.push(c));
|
|
129
|
+
child.stderr.on('data', (c) => err.push(c));
|
|
130
|
+
let timedOut = false;
|
|
131
|
+
const timer = setTimeout(() => {
|
|
132
|
+
timedOut = true;
|
|
133
|
+
child.kill('SIGTERM');
|
|
134
|
+
// A tool that ignores SIGTERM still has to go; on Windows kill() is already final.
|
|
135
|
+
setTimeout(() => child.kill('SIGKILL'), 2000).unref();
|
|
136
|
+
}, timeoutMs);
|
|
137
|
+
child.on('error', (e) => {
|
|
138
|
+
clearTimeout(timer);
|
|
139
|
+
reject(e);
|
|
140
|
+
});
|
|
141
|
+
let done = false;
|
|
142
|
+
const finish = (code, signal) => {
|
|
143
|
+
if (done)
|
|
144
|
+
return;
|
|
145
|
+
done = true;
|
|
146
|
+
clearTimeout(timer);
|
|
147
|
+
let stderr = err.text();
|
|
148
|
+
// 124 is what timeout(1) exits with; a signal maps to the shell's 128+n.
|
|
149
|
+
let exit = code ?? (signal ? 128 + (os_1.default.constants.signals[signal] ?? 0) : 1);
|
|
150
|
+
if (timedOut) {
|
|
151
|
+
exit = 124;
|
|
152
|
+
stderr += `${stderr && !stderr.endsWith('\n') ? '\n' : ''}[huddle] timed out after ${timeoutMs} ms`;
|
|
153
|
+
}
|
|
154
|
+
resolve({ code: exit, stdout: out.text(), stderr });
|
|
155
|
+
};
|
|
156
|
+
// 'close' waits for the pipes, which stay open as long as ANY process holds
|
|
157
|
+
// them: a daemon the tool started in the background, or a grandchild that
|
|
158
|
+
// outlived a timeout kill. Once the tool itself has exited, give its output
|
|
159
|
+
// a moment to drain and then stop waiting for the stragglers.
|
|
160
|
+
child.on('exit', (code, signal) => {
|
|
161
|
+
setTimeout(() => {
|
|
162
|
+
child.stdout.destroy();
|
|
163
|
+
child.stderr.destroy();
|
|
164
|
+
finish(code, signal);
|
|
165
|
+
}, 1000);
|
|
166
|
+
});
|
|
167
|
+
child.on('close', finish);
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
/** The `tool.run` op. */
|
|
171
|
+
async function toolRun(args) {
|
|
172
|
+
const { tool, args: argv, timeoutMs } = args;
|
|
173
|
+
if (typeof tool !== 'string' || !tool)
|
|
174
|
+
throw new protocol_1.PipeError('bad_request', 'tool must be a non-empty string');
|
|
175
|
+
if (!Array.isArray(argv) || !argv.every((a) => typeof a === 'string')) {
|
|
176
|
+
throw new protocol_1.PipeError('bad_request', 'args must be an array of strings');
|
|
177
|
+
}
|
|
178
|
+
if (argv.some((a) => a.includes('\0')))
|
|
179
|
+
throw new protocol_1.PipeError('bad_request', 'args must not contain NUL bytes');
|
|
180
|
+
if (timeoutMs !== undefined && (typeof timeoutMs !== 'number' || !Number.isFinite(timeoutMs) || timeoutMs <= 0)) {
|
|
181
|
+
throw new protocol_1.PipeError('bad_request', 'timeoutMs must be a positive number');
|
|
182
|
+
}
|
|
183
|
+
const resolved = resolveTool(tool);
|
|
184
|
+
if ('error' in resolved)
|
|
185
|
+
throw resolved.error;
|
|
186
|
+
const timeout = Math.min(Math.round(timeoutMs ?? protocol_1.DEFAULT_TOOL_TIMEOUT_MS), protocol_1.MAX_TOOL_TIMEOUT_MS);
|
|
187
|
+
try {
|
|
188
|
+
return await execTool(resolved.path, argv, timeout);
|
|
189
|
+
}
|
|
190
|
+
catch (err) {
|
|
191
|
+
const e = err;
|
|
192
|
+
if (e.code === 'ENOENT')
|
|
193
|
+
throw new protocol_1.PipeError('tool_missing', `${tool} disappeared from ${resolved.path}`);
|
|
194
|
+
throw new protocol_1.PipeError('internal', `could not run ${tool}: ${e.message ?? e}`);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
// One probe per binary path per agent run: `sbx version` can take a moment, and
|
|
198
|
+
// host.info is asked for often enough that re-running it every time would show.
|
|
199
|
+
const versionCache = new Map();
|
|
200
|
+
/** First line of `<tool> version`, best effort (undefined on any failure). */
|
|
201
|
+
function toolVersion(file) {
|
|
202
|
+
let cached = versionCache.get(file);
|
|
203
|
+
if (!cached) {
|
|
204
|
+
cached = execTool(file, ['version'], 5000, 64 * 1024)
|
|
205
|
+
.then((r) => (r.code === 0 ? (r.stdout || r.stderr).trim().split(/\r?\n/)[0] || undefined : undefined))
|
|
206
|
+
.catch(() => undefined);
|
|
207
|
+
versionCache.set(file, cached);
|
|
208
|
+
}
|
|
209
|
+
return cached;
|
|
210
|
+
}
|
|
211
|
+
/** Availability of every allowlisted tool, for host.info. */
|
|
212
|
+
async function toolsInfo() {
|
|
213
|
+
const out = {};
|
|
214
|
+
await Promise.all(Object.keys(exports.TOOLS).map(async (name) => {
|
|
215
|
+
const r = resolveTool(name);
|
|
216
|
+
if ('error' in r) {
|
|
217
|
+
out[name] = { available: false };
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
const version = await toolVersion(r.path);
|
|
221
|
+
out[name] = version ? { available: true, path: r.path, version } : { available: true, path: r.path };
|
|
222
|
+
}));
|
|
223
|
+
return out;
|
|
224
|
+
}
|
|
225
|
+
/** Names of the allowlisted tools that are installed, for the heartbeat. */
|
|
226
|
+
function availableTools() {
|
|
227
|
+
return Object.keys(exports.TOOLS).filter((name) => !('error' in resolveTool(name)));
|
|
228
|
+
}
|