@infosupport/huddle-cli 0.0.0-experiment-167.144.1 → 0.0.0-experiment-137.147.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
@@ -24,6 +24,7 @@ Pulls `ghcr.io/infosupport/huddle:latest` and starts the container. Works with D
24
24
  huddle # start an IntelliJ devcontainer for the current directory
25
25
  huddle ./project # start for a specific directory
26
26
  huddle --ide rider
27
+ huddle --ide webstorm
27
28
  huddle --ide vscode --name devcontainer-demo
28
29
  huddle --ide vscode --mount ../docker-corpa=/workspaces/backend --mount ../frontend-real-estate-info=/workspaces/frontend --name corpa-dev
29
30
  huddle fw list
@@ -108,7 +109,7 @@ npm run install-global
108
109
  Main flags:
109
110
 
110
111
  ```text
111
- --ide <intellij|rider|vscode>
112
+ --ide <intellij|rider|webstorm|vscode>
112
113
  --workspace <path>
113
114
  --mount <host>=<container> (repeatable, container path must be absolute)
114
115
  --workspace-root <path> (container path the IDE opens; requires --mount)
@@ -0,0 +1,345 @@
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.hostText = exports.inActions = exports.tail = exports.isInterrupted = void 0;
7
+ exports.run = run;
8
+ exports.must = must;
9
+ exports.runAsync = runAsync;
10
+ exports.withInterruptHandler = withInterruptHandler;
11
+ exports.quoteUntrusted = quoteUntrusted;
12
+ exports.printUntrusted = printUntrusted;
13
+ exports.actionsRunUrl = actionsRunUrl;
14
+ exports.claudeCredential = claudeCredential;
15
+ exports.fetchPrompt = fetchPrompt;
16
+ exports.startAgent = startAgent;
17
+ exports.parseClaudeOutput = parseClaudeOutput;
18
+ exports.networkLog = networkLog;
19
+ exports.saveNetworkLog = saveNetworkLog;
20
+ exports.runFacts = runFacts;
21
+ exports.containerExists = containerExists;
22
+ exports.wipeWorkspace = wipeWorkspace;
23
+ exports.removeDir = removeDir;
24
+ exports.cleanup = cleanup;
25
+ const crypto_1 = __importDefault(require("crypto"));
26
+ const fs_1 = __importDefault(require("fs"));
27
+ const path_1 = __importDefault(require("path"));
28
+ const child_process_1 = require("child_process");
29
+ const api_1 = require("./api");
30
+ const update_agent_guard_1 = require("./update-agent-guard");
31
+ const utils_1 = require("./utils");
32
+ function run(cmd, args, opts = {}) {
33
+ const r = (0, child_process_1.spawnSync)(cmd, args, { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, ...opts });
34
+ const timedOut = r.error?.code === 'ETIMEDOUT';
35
+ if (r.error && !timedOut)
36
+ throw new Error(`${cmd} ${args[0] ?? ''}: ${r.error.message}`);
37
+ return { status: timedOut ? null : r.status, timedOut, stdout: r.stdout ?? '', stderr: r.stderr ?? '' };
38
+ }
39
+ function must(cmd, args, opts = {}) {
40
+ const r = run(cmd, args, opts);
41
+ if (r.status !== 0)
42
+ throw new Error(`${cmd} ${args.slice(0, 3).join(' ')} failed: ${(r.stderr || r.stdout).trim().slice(-2000)}`);
43
+ return r.stdout;
44
+ }
45
+ // The long-running container commands (Claude, verification) run async, so a
46
+ // Ctrl+C reaches the SIGINT handler while they run: it stops them, and the
47
+ // normal `finally` cleanup removes the container, rules and placeholder.
48
+ let interrupted = false;
49
+ const interruptHooks = new Set();
50
+ const OUTPUT_CAP = 1024 * 1024;
51
+ const isInterrupted = () => interrupted;
52
+ exports.isInterrupted = isInterrupted;
53
+ function runAsync(cmd, args, opts = {}) {
54
+ return new Promise((resolve, reject) => {
55
+ const child = (0, child_process_1.spawn)(cmd, args, { stdio: [opts.input === undefined ? 'ignore' : 'pipe', 'pipe', opts.liveStderr ? 'inherit' : 'pipe'] });
56
+ let stdout = '';
57
+ let stderr = '';
58
+ let timedOut = false;
59
+ child.stdout?.setEncoding('utf8').on('data', (d) => { stdout = (stdout + d).slice(-OUTPUT_CAP); });
60
+ child.stderr?.setEncoding('utf8').on('data', (d) => { stderr = (stderr + d).slice(-OUTPUT_CAP); });
61
+ child.stdin?.on('error', () => { });
62
+ child.stdin?.end(opts.input);
63
+ const timer = opts.timeout ? setTimeout(() => { timedOut = true; child.kill(); }, opts.timeout) : undefined;
64
+ const stop = () => child.kill();
65
+ interruptHooks.add(stop);
66
+ const done = () => { if (timer)
67
+ clearTimeout(timer); interruptHooks.delete(stop); };
68
+ child.on('error', (err) => { done(); reject(new Error(`${cmd} ${args[0] ?? ''}: ${err.message}`)); });
69
+ child.on('close', (status) => { done(); resolve({ status: timedOut ? null : status, timedOut, stdout, stderr }); });
70
+ });
71
+ }
72
+ function onSigint() {
73
+ if (interrupted)
74
+ process.exit(130);
75
+ interrupted = true;
76
+ console.log((0, utils_1.yellow)('\nInterrupted: stopping the agent and cleaning up. Press Ctrl+C again to quit right away.'));
77
+ for (const stop of interruptHooks)
78
+ stop();
79
+ }
80
+ /** Runs fn with the Ctrl+C handler installed: the first Ctrl+C stops the agent and lets cleanup run. */
81
+ async function withInterruptHandler(fn) {
82
+ process.on('SIGINT', onSigint);
83
+ try {
84
+ return await fn();
85
+ }
86
+ finally {
87
+ process.off('SIGINT', onSigint);
88
+ }
89
+ }
90
+ // ── untrusted text ───────────────────────────────────────────────────────────
91
+ /**
92
+ * Agent-written text for a public comment, inside a code fence: no links,
93
+ * images, HTML or @mentions are rendered from it.
94
+ */
95
+ function quoteUntrusted(text) {
96
+ return ['````text', text.replace(/`{3,}/g, (m) => "'".repeat(m.length)), '````'].join('\n');
97
+ }
98
+ const tail = (s, n) => (s.length > n ? `[…truncated…]\n${s.slice(-n)}` : s);
99
+ exports.tail = tail;
100
+ const inActions = () => process.env.GITHUB_ACTIONS === 'true';
101
+ exports.inActions = inActions;
102
+ /**
103
+ * Prints text the agent may have shaped (its answers, its diff and commit
104
+ * message, errors carrying container output). In GitHub Actions, workflow
105
+ * commands are switched off around it, so a line like `::add-mask::` or
106
+ * `::error::` in it does nothing in the public log.
107
+ */
108
+ function printUntrusted(text, color = utils_1.dim, max = 4_000, toStderr = false) {
109
+ const stop = crypto_1.default.randomBytes(16).toString('hex');
110
+ if ((0, exports.inActions)())
111
+ console.log(`::stop-commands::${stop}`);
112
+ (toStderr ? console.error : console.log)(color((0, exports.tail)(text, max)));
113
+ if ((0, exports.inActions)())
114
+ console.log(`::${stop}::`);
115
+ }
116
+ /** The link to this GitHub Actions run, or null outside Actions. */
117
+ function actionsRunUrl() {
118
+ const { GITHUB_ACTIONS, GITHUB_SERVER_URL, GITHUB_REPOSITORY, GITHUB_RUN_ID } = process.env;
119
+ if (GITHUB_ACTIONS === 'true' && GITHUB_SERVER_URL && GITHUB_REPOSITORY && /^\d+$/.test(GITHUB_RUN_ID ?? '')) {
120
+ return `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}`;
121
+ }
122
+ return null;
123
+ }
124
+ function claudeCredential() {
125
+ const oauth = process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim();
126
+ const key = process.env.ANTHROPIC_API_KEY?.trim();
127
+ // Only the gateway gets it; no child process of this CLI inherits it.
128
+ delete process.env.CLAUDE_CODE_OAUTH_TOKEN;
129
+ delete process.env.ANTHROPIC_API_KEY;
130
+ if (oauth)
131
+ return { env: 'CLAUDE_CODE_OAUTH_TOKEN', secret: oauth };
132
+ if (key)
133
+ return { env: 'ANTHROPIC_API_KEY', secret: key };
134
+ throw new Error('No Claude credential found. Set CLAUDE_CODE_OAUTH_TOKEN (create one with `claude setup-token`) ' +
135
+ 'or ANTHROPIC_API_KEY in this shell. It is handed to the Huddle gateway, never to the container.');
136
+ }
137
+ /**
138
+ * The prompt always comes from the default branch, so a PR branch cannot
139
+ * rewrite its own instructions. The variable named by refEnv (for example
140
+ * HUDDLE_UPDATE_AGENT_PROMPT_REF) is for trying out prompt changes before
141
+ * they are merged.
142
+ */
143
+ function fetchPrompt(repo, promptPath, refEnv, agentName) {
144
+ const branch = process.env[refEnv]?.trim() ||
145
+ must('gh', ['repo', 'view', repo, '--json', 'defaultBranchRef', '-q', '.defaultBranchRef.name']).trim();
146
+ const r = run('gh', ['api', '-H', 'Accept: application/vnd.github.raw', `repos/${repo}/contents/${promptPath}?ref=${encodeURIComponent(branch)}`]);
147
+ if (r.status !== 0 || !r.stdout.trim()) {
148
+ throw new Error(`Could not read ${promptPath} from ${repo}@${branch}. Is the ${agentName} merged there?`);
149
+ }
150
+ return r.stdout;
151
+ }
152
+ const CONTAINER_ENV = [
153
+ // The mounted repo is owned by another uid; without this git refuses it ("dubious ownership").
154
+ '-e', 'GIT_CONFIG_COUNT=1', '-e', 'GIT_CONFIG_KEY_0=safe.directory', '-e', 'GIT_CONFIG_VALUE_0=/workspace/repo',
155
+ // No telemetry or other non-essential calls from Claude Code; the airlock would block them anyway.
156
+ '-e', 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1',
157
+ ];
158
+ /**
159
+ * Starts an airlocked, isolated devcontainer with /workspace mounted and the
160
+ * Claude credential behind the token exchange. The caller removes it with
161
+ * cleanup(), also when this throws halfway.
162
+ */
163
+ async function startAgent(spec) {
164
+ const { name, engine, credential } = spec;
165
+ console.log((0, utils_1.dim)(` starting ${name} (${spec.description})`));
166
+ await (0, api_1.post)(`/api/docker/containers/${name}/airlock`, { airlocked: true });
167
+ await (0, api_1.post)(`/api/rules/import?container=${encodeURIComponent(name)}`, { mode: 'replace', rules: spec.rules });
168
+ await (0, api_1.post)('/api/docker/start', {
169
+ imageName: spec.imageName,
170
+ containerName: name,
171
+ ideName: 'vscode',
172
+ mounts: [{ hostPath: spec.workspace.replace(/\\/g, '/'), containerPath: '/workspace' }],
173
+ containerWorkspace: '/workspace/repo',
174
+ // No folder mappings from the portal, and no Docker or sudo rights left
175
+ // over from an earlier container with this name.
176
+ isolated: true,
177
+ });
178
+ const { placeholder } = await (0, api_1.post)(`/api/docker/containers/${name}/token`, { secret: credential.secret });
179
+ const root = (script) => run(engine, ['exec', '-u', 'root', name, 'sh', '-c', script]);
180
+ // The gateway hands the repo to vscode; input and out are siblings the agent
181
+ // writes to as well (summary, commit message, verification logs). Without
182
+ // this they stay owned by the host user, which is not vscode on every host.
183
+ const own = root('chown -R vscode:vscode /workspace/input /workspace/out');
184
+ if (own.status !== 0)
185
+ throw new Error(`could not prepare /workspace for the agent in ${name}: ${own.stderr.trim()}`);
186
+ const stopAll = () => {
187
+ // pkill exits 1 when nothing was left to kill; anything else means it failed.
188
+ const kill = root('pkill -KILL -u vscode');
189
+ if (kill.status !== 0 && kill.status !== 1)
190
+ throw new Error(`Could not stop the agent's processes in ${name}.`);
191
+ // The container's keep-alive runs as vscode too. A Huddle from before the
192
+ // fix in its keep-alive loop stops the container here.
193
+ if (root('true').status !== 0) {
194
+ throw new Error(`${name} stopped when the agent's processes were stopped. Update Huddle (\`huddle init\`) and run again.`);
195
+ }
196
+ };
197
+ // A timeout only kills the local `docker exec` client, not the process in the
198
+ // container, so every exec that timed out or was interrupted stops them all.
199
+ const exec = async (args, workdir, extra = {}) => {
200
+ const stdin = extra.input === undefined ? [] : ['-i'];
201
+ const r = await runAsync(engine, ['exec', ...stdin, '-u', 'vscode', '-w', workdir, '-e', `${credential.env}=${placeholder}`, ...CONTAINER_ENV, name, ...args], extra);
202
+ if (r.timedOut || interrupted)
203
+ stopAll();
204
+ if (interrupted)
205
+ throw new Error('interrupted');
206
+ return r;
207
+ };
208
+ const readFile = async (file) => {
209
+ const r = await exec(['sh', '-c', 'if [ -f "$1" ]; then head -c 200000 "$1"; fi', 'sh', file], '/workspace');
210
+ if (r.status !== 0)
211
+ throw new Error(`could not read ${file} in ${name}: ${r.stderr.trim()}`);
212
+ return r.stdout;
213
+ };
214
+ const writeFile = async (file, content) => {
215
+ const r = await exec(['sh', '-c', 'cat > "$1"', 'sh', file], '/workspace', { input: content });
216
+ if (r.status !== 0)
217
+ throw new Error(`could not write ${file} in ${name}: ${r.stderr.trim()}`);
218
+ };
219
+ return { name, exec, root, stopAll, readFile, writeFile };
220
+ }
221
+ /**
222
+ * Claude Code's `--output-format json` answer: its final text, cost, turns and
223
+ * refused tool calls (null when it failed before answering).
224
+ */
225
+ function parseClaudeOutput(stdout) {
226
+ let out = null;
227
+ try {
228
+ out = JSON.parse(stdout.trim());
229
+ }
230
+ catch {
231
+ return null;
232
+ }
233
+ if (!out || typeof out !== 'object')
234
+ return null;
235
+ return {
236
+ result: typeof out.result === 'string' ? out.result.trim() : '',
237
+ costUsd: typeof out.total_cost_usd === 'number' ? out.total_cost_usd : 0,
238
+ turns: typeof out.num_turns === 'number' ? out.num_turns : 0,
239
+ denials: Array.isArray(out.permission_denials) ? out.permission_denials.map(denial) : [],
240
+ };
241
+ }
242
+ function denial(d) {
243
+ const o = (d && typeof d === 'object' ? d : {});
244
+ const input = (o.tool_input && typeof o.tool_input === 'object' ? o.tool_input : {});
245
+ // Bash has `command`, the file tools `file_path`; anything else as JSON.
246
+ const text = typeof input.command === 'string' ? input.command
247
+ : typeof input.file_path === 'string' ? input.file_path
248
+ : JSON.stringify(o.tool_input ?? null);
249
+ return { tool: typeof o.tool_name === 'string' ? o.tool_name : '?', input: text.replace(/\s+/g, ' ').trim().slice(0, 300) };
250
+ }
251
+ const AUDIT_PAGE = 1000;
252
+ const AUDIT_MAX = 20_000;
253
+ /** The container's traffic from Huddle's audit log: no headers or bodies, only what went where. */
254
+ async function networkLog(name) {
255
+ if (!name)
256
+ return null;
257
+ try {
258
+ const requests = [];
259
+ for (let offset = 0; offset < AUDIT_MAX; offset += AUDIT_PAGE) {
260
+ const page = await (0, api_1.get)(`/api/audit?container=${encodeURIComponent(name)}&limit=${AUDIT_PAGE}&offset=${offset}`);
261
+ requests.push(...page.map(({ ts, domain, port, method, path: p, action, res_status }) => ({ ts, domain, port, method, path: p, action, res_status })));
262
+ if (page.length < AUDIT_PAGE)
263
+ break;
264
+ }
265
+ const rules = await (0, api_1.get)(`/api/rules?container=${encodeURIComponent(name)}&status=requested`);
266
+ return { requests: requests.reverse(), requested: [...new Set(rules.map((r) => r.domain))] };
267
+ }
268
+ catch (err) {
269
+ console.log((0, utils_1.yellow)(` could not read the network log of ${name}: ${err instanceof Error ? err.message : String(err)}`));
270
+ return null;
271
+ }
272
+ }
273
+ /** Writes the container's network log as JSON to file, with `header` fields first. */
274
+ async function saveNetworkLog(name, file, header) {
275
+ const log = await networkLog(name);
276
+ if (!log)
277
+ return;
278
+ fs_1.default.mkdirSync(path_1.default.dirname(file), { recursive: true });
279
+ fs_1.default.writeFileSync(file, `${JSON.stringify({ ...header, container: name, ...log }, null, 2)}\n`);
280
+ console.log((0, utils_1.dim)(` network log: ${file}`));
281
+ }
282
+ /** A host name as text for a public comment; anything else is not shown as-is. */
283
+ const hostText = (d) => (/^[A-Za-z0-9.-]{1,253}$/.test(d) ? `\`${d}\`` : '_(invalid host name)_');
284
+ exports.hostText = hostText;
285
+ /** Usage and network lines for a PR comment. */
286
+ async function runFacts(name, usage) {
287
+ const lines = [];
288
+ if (usage.turns)
289
+ lines.push(`**Claude Code:** ${usage.turns} turns, $${usage.costUsd.toFixed(2)}`);
290
+ const log = await networkLog(name);
291
+ if (log) {
292
+ const hosts = (0, update_agent_guard_1.requestsByHost)(log.requests).slice(0, 15);
293
+ lines.push(`**Network:** ${hosts.length ? hosts.map(([d, h]) => `${(0, exports.hostText)(d)} ${h.allowed}${h.denied ? ` (+${h.denied} blocked)` : ''}`).join(', ') : 'no requests logged'}`);
294
+ if (log.requested.length) {
295
+ lines.push(`**Blocked hosts it asked for:** ${log.requested.slice(0, 15).map(exports.hostText).join(', ')}. A dependency that suddenly needs a new host deserves a look.`);
296
+ }
297
+ }
298
+ return lines.length ? ['', ...lines] : [];
299
+ }
300
+ // ── cleanup ──────────────────────────────────────────────────────────────────
301
+ async function containerExists(name) {
302
+ try {
303
+ await (0, api_1.get)(`/api/docker/containers/${encodeURIComponent(name)}`);
304
+ return true;
305
+ }
306
+ catch (err) {
307
+ if (err instanceof api_1.ApiError && err.status === 404)
308
+ return false;
309
+ throw err;
310
+ }
311
+ }
312
+ /**
313
+ * Empties the mounted /workspace from inside the container, as root. On Linux
314
+ * the files the agent wrote belong to the container's vscode user, which the
315
+ * host user cannot delete. rm never follows symlinks, and only the container's
316
+ * view of the mount is touched. Best effort: removeDir reports what is left.
317
+ */
318
+ function wipeWorkspace(engine, name) {
319
+ run(engine, ['exec', '-u', 'root', name, 'sh', '-c',
320
+ 'pkill -KILL -u vscode; find /workspace -mindepth 1 -maxdepth 1 -exec rm -rf {} +']);
321
+ }
322
+ /** rmSync removes symlinks themselves and never follows them. */
323
+ function removeDir(dir) {
324
+ try {
325
+ fs_1.default.rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 500 });
326
+ }
327
+ catch (err) {
328
+ console.log((0, utils_1.yellow)(` could not remove ${dir}: ${err instanceof Error ? err.message : String(err)}`));
329
+ }
330
+ }
331
+ /** Revokes the placeholder and, unless keep, removes the container, its rules and its airlock. */
332
+ async function cleanup(name, keep) {
333
+ const quiet = async (fn) => { try {
334
+ await fn();
335
+ }
336
+ catch { /* best effort */ } };
337
+ await quiet(() => (0, api_1.del)(`/api/docker/containers/${name}/token`)); // always: no redeemable placeholder left behind
338
+ if (keep) {
339
+ console.log((0, utils_1.dim)(` kept container ${name} and its folder for inspection`));
340
+ return;
341
+ }
342
+ await quiet(() => (0, api_1.del)(`/api/docker/containers/${name}`)); // also after a half-finished start
343
+ await quiet(() => (0, api_1.post)(`/api/rules/import?container=${encodeURIComponent(name)}`, { mode: 'replace', rules: [] }));
344
+ await quiet(() => (0, api_1.post)(`/api/docker/containers/${name}/airlock`, { airlocked: false }));
345
+ }
@@ -0,0 +1,162 @@
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.STAGED_DIR = exports.BASE_NAME = exports.IDES = void 0;
7
+ exports.localImageName = localImageName;
8
+ exports.buildPlan = buildPlan;
9
+ exports.stageDockerfiles = stageDockerfiles;
10
+ exports.readStatus = readStatus;
11
+ exports.buildImages = buildImages;
12
+ exports.startBackgroundBuild = startBackgroundBuild;
13
+ exports.printStatus = printStatus;
14
+ const child_process_1 = require("child_process");
15
+ const fs_1 = __importDefault(require("fs"));
16
+ const path_1 = __importDefault(require("path"));
17
+ const config_1 = require("./config");
18
+ const utils_1 = require("./utils");
19
+ /**
20
+ * Devcontainer base images are built on the user's machine instead of pulled
21
+ * from a registry. That way nobody has to publish a new image for every Claude
22
+ * Code (or Codex/Copilot) release: `huddle images build --refresh` picks up the
23
+ * latest versions.
24
+ *
25
+ * Names live under `localhost/` so a missing image can never be resolved to a
26
+ * public registry (e.g. a Docker Hub namespace called "huddle"); Podman also
27
+ * uses `localhost/` for local images.
28
+ */
29
+ exports.IDES = ['vscode', 'intellij', 'rider', 'webstorm'];
30
+ exports.BASE_NAME = 'base-devimage';
31
+ /** Local image for the shared base or one IDE, for a channel tag (`latest` or `experiment-<nr>`). */
32
+ function localImageName(ide, tag) {
33
+ return `localhost/huddle/${ide ? `${exports.BASE_NAME}-${ide}` : exports.BASE_NAME}:${tag}`;
34
+ }
35
+ /** Where `huddle init` stages the Dockerfiles; mounted into the gateway as /huddle-home/images. */
36
+ exports.STAGED_DIR = path_1.default.join(config_1.CONFIG_DIR, 'images');
37
+ const LOG_PATH = path_1.default.join(exports.STAGED_DIR, 'build.log');
38
+ const STATUS_PATH = path_1.default.join(exports.STAGED_DIR, 'build-status.json');
39
+ /**
40
+ * The images to build, base first (the IDE images build on top of it). Pure, so
41
+ * it is unit-tested. With `refresh` every image is rebuilt; otherwise images that
42
+ * already exist are skipped, except that a rebuilt base forces its IDE images.
43
+ */
44
+ function buildPlan(tag, ides, exists, refresh) {
45
+ const base = localImageName(undefined, tag);
46
+ const steps = [];
47
+ const baseNeeded = refresh || !exists(base);
48
+ if (baseNeeded)
49
+ steps.push({ name: exports.BASE_NAME, image: base, buildArgs: {} });
50
+ for (const ide of ides) {
51
+ const image = localImageName(ide, tag);
52
+ if (baseNeeded || !exists(image)) {
53
+ steps.push({ name: `${exports.BASE_NAME}-${ide}`, ide, image, buildArgs: { BASE_IMAGE: base } });
54
+ }
55
+ }
56
+ return steps;
57
+ }
58
+ /** The Dockerfiles shipped with the CLI package (copied there by scripts/copy-dockerfiles.js). */
59
+ function packagedDir() {
60
+ return path_1.default.resolve(__dirname, '..', 'images');
61
+ }
62
+ /**
63
+ * Copies the packaged Dockerfiles to ~/.huddle/images, so the gateway (which
64
+ * mounts ~/.huddle) can build a missing image itself on the first start.
65
+ */
66
+ function stageDockerfiles() {
67
+ const src = packagedDir();
68
+ if (!fs_1.default.existsSync(src))
69
+ throw new Error(`Dockerfiles not found in ${src}; is the CLI package complete?`);
70
+ for (const name of fs_1.default.readdirSync(src)) {
71
+ const from = path_1.default.join(src, name, 'Dockerfile');
72
+ if (!fs_1.default.existsSync(from))
73
+ continue;
74
+ fs_1.default.mkdirSync(path_1.default.join(exports.STAGED_DIR, name), { recursive: true });
75
+ fs_1.default.copyFileSync(from, path_1.default.join(exports.STAGED_DIR, name, 'Dockerfile'));
76
+ }
77
+ }
78
+ function imageExists(rt, image) {
79
+ return (0, child_process_1.spawnSync)(rt, ['image', 'inspect', image], { stdio: 'ignore' }).status === 0;
80
+ }
81
+ function writeStatus(status) {
82
+ fs_1.default.mkdirSync(exports.STAGED_DIR, { recursive: true });
83
+ fs_1.default.writeFileSync(STATUS_PATH, JSON.stringify({ ...status, updatedAt: new Date().toISOString() }, null, 2));
84
+ }
85
+ function readStatus() {
86
+ try {
87
+ return JSON.parse(fs_1.default.readFileSync(STATUS_PATH, 'utf8'));
88
+ }
89
+ catch {
90
+ return undefined;
91
+ }
92
+ }
93
+ /**
94
+ * Builds the images in the foreground (output to stdout/stderr). Returns false
95
+ * when a build failed; the rest of the plan is then skipped, because the IDE
96
+ * images cannot build without their base.
97
+ */
98
+ function buildImages(opts) {
99
+ stageDockerfiles();
100
+ const ides = opts.ides ?? exports.IDES;
101
+ const plan = buildPlan(opts.tag, ides, (img) => imageExists(opts.rt, img), !!opts.refresh);
102
+ if (plan.length === 0) {
103
+ console.log((0, utils_1.green)('[OK] All devcontainer base images are present.') + (0, utils_1.dim)(' Use --refresh to rebuild with the latest tools.'));
104
+ writeStatus({ state: 'done', tag: opts.tag });
105
+ return true;
106
+ }
107
+ for (const step of plan) {
108
+ console.log((0, utils_1.bold)(`Building ${step.image}`));
109
+ writeStatus({ state: 'building', tag: opts.tag, image: step.image });
110
+ const dir = path_1.default.join(exports.STAGED_DIR, step.name);
111
+ const args = ['build', '-t', step.image];
112
+ for (const [k, v] of Object.entries(step.buildArgs))
113
+ args.push('--build-arg', `${k}=${v}`);
114
+ // --pull refreshes the upstream images (Debian, devcontainers) but never our own
115
+ // localhost/ base, which only exists locally.
116
+ if (opts.refresh)
117
+ args.push('--no-cache', ...(step.ide ? [] : ['--pull']));
118
+ args.push('-f', path_1.default.join(dir, 'Dockerfile'), dir);
119
+ const res = (0, child_process_1.spawnSync)(opts.rt, args, { stdio: 'inherit' });
120
+ if (res.status !== 0) {
121
+ const error = `build of ${step.image} failed (exit ${res.status ?? res.signal})`;
122
+ console.log((0, utils_1.yellow)(`[!] ${error}`));
123
+ writeStatus({ state: 'failed', tag: opts.tag, image: step.image, error });
124
+ return false;
125
+ }
126
+ }
127
+ console.log((0, utils_1.green)(`[OK] Built ${plan.length} image(s).`));
128
+ writeStatus({ state: 'done', tag: opts.tag });
129
+ return true;
130
+ }
131
+ /**
132
+ * Starts the build in a detached process so `huddle init` does not wait for it.
133
+ * The gateway waits for a running build before it builds a missing image itself.
134
+ */
135
+ function startBackgroundBuild(rt, tag) {
136
+ stageDockerfiles();
137
+ writeStatus({ state: 'building', tag });
138
+ const out = fs_1.default.openSync(LOG_PATH, 'w');
139
+ const child = (0, child_process_1.spawn)(process.execPath, [process.argv[1], 'images', 'build', '--runtime', rt], {
140
+ detached: true,
141
+ stdio: ['ignore', out, out],
142
+ env: { ...process.env, HUDDLE_IMAGES_TAG: tag },
143
+ });
144
+ child.unref();
145
+ fs_1.default.closeSync(out);
146
+ console.log((0, utils_1.dim)(`Building devcontainer base images in the background (log: ${LOG_PATH})`));
147
+ console.log((0, utils_1.dim)(' The first start of a devcontainer waits for it; check progress with "huddle images status".'));
148
+ }
149
+ function printStatus(rt, tag) {
150
+ const status = readStatus();
151
+ console.log(`Channel tag: ${tag}`);
152
+ if (status) {
153
+ const detail = status.state === 'building' && status.image ? ` (${status.image})` : status.error ? ` (${status.error})` : '';
154
+ console.log(`Last build: ${status.state}${detail}, ${status.updatedAt}`);
155
+ }
156
+ for (const ide of [undefined, ...exports.IDES]) {
157
+ const image = localImageName(ide, tag);
158
+ console.log(` ${imageExists(rt, image) ? (0, utils_1.green)('present') : (0, utils_1.yellow)('missing')} ${image}`);
159
+ }
160
+ if (fs_1.default.existsSync(LOG_PATH))
161
+ console.log((0, utils_1.dim)(`Log: ${LOG_PATH}`));
162
+ }
@@ -0,0 +1,108 @@
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.GithubApp = exports.APP_PERMISSIONS = void 0;
7
+ exports.appConfigFromEnv = appConfigFromEnv;
8
+ exports.appJwt = appJwt;
9
+ const crypto_1 = __importDefault(require("crypto"));
10
+ // `huddle update-agent` as a GitHub App, for CI (.github/workflows/update-agent.yml).
11
+ // Pushes made with the workflow's own GITHUB_TOKEN do not start CI again, so
12
+ // the agent pushes as an App. Its installation tokens live one hour, shorter
13
+ // than an agent run, so the CLI mints a fresh one when it needs GitHub instead
14
+ // of taking one token from the workflow at the start.
15
+ //
16
+ // The token goes into GH_TOKEN of this process only: `gh` reads it, and git
17
+ // gets it through `gh auth git-credential`. The agent container never sees it.
18
+ const REFRESH_AFTER_MS = 30 * 60 * 1000;
19
+ /** What the agent needs, and no more. "Workflows" is left out on purpose, so GitHub itself refuses a push that edits .github/workflows. */
20
+ exports.APP_PERMISSIONS = {
21
+ contents: 'write',
22
+ pull_requests: 'write',
23
+ issues: 'write',
24
+ actions: 'read',
25
+ };
26
+ /** The App from HUDDLE_GITHUB_APP_CLIENT_ID and HUDDLE_GITHUB_APP_PRIVATE_KEY, or null to use the developer's own `gh` login. */
27
+ function appConfigFromEnv(env = process.env) {
28
+ const clientId = env.HUDDLE_GITHUB_APP_CLIENT_ID?.trim();
29
+ const privateKey = env.HUDDLE_GITHUB_APP_PRIVATE_KEY?.trim();
30
+ if (!clientId && !privateKey)
31
+ return null;
32
+ if (!clientId || !privateKey) {
33
+ throw new Error('Set both HUDDLE_GITHUB_APP_CLIENT_ID and HUDDLE_GITHUB_APP_PRIVATE_KEY, or neither.');
34
+ }
35
+ const repo = (env.GITHUB_REPOSITORY || env.GH_REPO || '').trim();
36
+ if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo)) {
37
+ throw new Error('Running as a GitHub App needs the repository: set GITHUB_REPOSITORY to owner/name.');
38
+ }
39
+ return { clientId, privateKey, repo };
40
+ }
41
+ /** A JWT that authenticates as the App itself, valid for 9 minutes (GitHub allows 10). */
42
+ function appJwt(clientId, privateKey, now = Date.now()) {
43
+ const part = (o) => Buffer.from(JSON.stringify(o)).toString('base64url');
44
+ const iat = Math.floor(now / 1000) - 60; // allow for clock drift
45
+ const data = `${part({ alg: 'RS256', typ: 'JWT' })}.${part({ iat, exp: iat + 600, iss: clientId })}`;
46
+ const signature = crypto_1.default.createSign('RSA-SHA256').update(data).sign(privateKey).toString('base64url');
47
+ return `${data}.${signature}`;
48
+ }
49
+ async function github(method, path, bearer, body) {
50
+ const api = (process.env.GITHUB_API_URL || 'https://api.github.com').replace(/\/+$/, '');
51
+ const res = await fetch(`${api}${path}`, {
52
+ method,
53
+ headers: {
54
+ authorization: `Bearer ${bearer}`,
55
+ accept: 'application/vnd.github+json',
56
+ 'x-github-api-version': '2022-11-28',
57
+ 'user-agent': 'huddle-update-agent',
58
+ ...(body === undefined ? {} : { 'content-type': 'application/json' }),
59
+ },
60
+ body: body === undefined ? undefined : JSON.stringify(body),
61
+ // A stalled API call must not hold the run (and its CI job) until the job timeout.
62
+ signal: AbortSignal.timeout(30_000),
63
+ });
64
+ if (!res.ok)
65
+ throw new Error(`GitHub App: ${method} ${path} -> ${res.status} ${(await res.text()).slice(0, 300)}`);
66
+ return (await res.json());
67
+ }
68
+ class GithubApp {
69
+ cfg;
70
+ permissions;
71
+ token = '';
72
+ mintedAt = 0;
73
+ installationId;
74
+ /** permissions: what each installation token may do; the update agent's by default. */
75
+ constructor(cfg, permissions = exports.APP_PERMISSIONS) {
76
+ this.cfg = cfg;
77
+ this.permissions = permissions;
78
+ }
79
+ get repo() {
80
+ return this.cfg.repo;
81
+ }
82
+ /** Makes sure GH_TOKEN holds an installation token with at least 30 minutes left. */
83
+ async refresh() {
84
+ if (this.token && Date.now() - this.mintedAt < REFRESH_AFTER_MS)
85
+ return;
86
+ const jwt = appJwt(this.cfg.clientId, this.cfg.privateKey);
87
+ this.installationId ??= (await github('GET', `/repos/${this.cfg.repo}/installation`, jwt)).id;
88
+ // Scoped to this one repository and these permissions, whatever else the App may do.
89
+ const { token } = await github('POST', `/app/installations/${this.installationId}/access_tokens`, jwt, {
90
+ repositories: [this.cfg.repo.split('/')[1]],
91
+ permissions: this.permissions,
92
+ });
93
+ if (process.env.GITHUB_ACTIONS === 'true')
94
+ console.log(`::add-mask::${token}`);
95
+ this.token = token;
96
+ this.mintedAt = Date.now();
97
+ process.env.GH_TOKEN = token;
98
+ }
99
+ /** The App's bot account as git author: `<slug>[bot]` with its noreply address, as GitHub shows it. */
100
+ async identity() {
101
+ await this.refresh();
102
+ const { slug } = await github('GET', '/app', appJwt(this.cfg.clientId, this.cfg.privateKey));
103
+ const login = `${slug}[bot]`;
104
+ const { id } = await github('GET', `/users/${encodeURIComponent(login)}`, this.token);
105
+ return { name: login, email: `${id}+${login}@users.noreply.github.com` };
106
+ }
107
+ }
108
+ exports.GithubApp = GithubApp;