@infosupport/huddle-cli 0.0.0-experiment-44.143.1 → 0.0.0-experiment-137.146.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,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;
package/dist/images.js CHANGED
@@ -14,6 +14,7 @@ function resolveImages() {
14
14
  { image: process.env.BASE_IMAGE ?? `ghcr.io/infosupport/base-devimage:${tag}` },
15
15
  { image: process.env.BASE_IMAGE_RIDER ?? `ghcr.io/infosupport/base-devimage-rider:${tag}`, gatewayEnv: 'BASE_IMAGE_RIDER' },
16
16
  { image: process.env.BASE_IMAGE_INTELLIJ ?? `ghcr.io/infosupport/base-devimage-intellij:${tag}`, gatewayEnv: 'BASE_IMAGE_INTELLIJ' },
17
+ { image: process.env.BASE_IMAGE_WEBSTORM ?? `ghcr.io/infosupport/base-devimage-webstorm:${tag}`, gatewayEnv: 'BASE_IMAGE_WEBSTORM' },
17
18
  { image: process.env.BASE_IMAGE_VSCODE ?? `ghcr.io/infosupport/base-devimage-vscode:${tag}`, gatewayEnv: 'BASE_IMAGE_VSCODE' },
18
19
  ],
19
20
  };
package/dist/index.js CHANGED
@@ -12,13 +12,15 @@ const firewall_1 = require("./firewall");
12
12
  const init_1 = require("./init");
13
13
  const migrate_1 = require("./migrate");
14
14
  const indexfolder_1 = require("./indexfolder");
15
+ const triage_agent_1 = require("./triage-agent");
16
+ const update_agent_1 = require("./update-agent");
15
17
  const images_1 = require("./images");
16
18
  const self_update_1 = require("./self-update");
17
19
  const utils_1 = require("./utils");
18
20
  const experiment_1 = require("./experiment");
19
21
  const VALUE_FLAGS = new Set(['url', 'ide', 'name', 'image', 'workspace', 'container', 'status', 'runtime', 'experiment', 'path', 'ca-path', 'output', 'out', 'workspace-root', 'depth']);
20
22
  const BOOLEAN_FLAGS = new Set(['help', 'h', 'empty', 'i', 'interactive', 'version', 'v', 'deny', 'docker-socket', 'force', 'replace', 'all', 'list', 'clear']);
21
- const COMMANDS = new Set(['start', 'firewall', 'fw', 'init', 'restart', 'experiment', 'migrate', 'indexfolder', 'indexfolders', 'help', 'version']);
23
+ const COMMANDS = new Set(['start', 'firewall', 'fw', 'init', 'restart', 'experiment', 'migrate', 'indexfolder', 'indexfolders', 'update-agent', 'triage-agent', 'help', 'version']);
22
24
  function parseArgs(argv) {
23
25
  const positional = [];
24
26
  const flags = {};
@@ -142,6 +144,12 @@ Usage:
142
144
  huddle firewall folder set <path> Set the team-managed rules folder
143
145
  huddle firewall folder reload Re-read the team-managed rules folder
144
146
  huddle firewall folder sync Write the portal's groups back to the folder
147
+ huddle update-agent [PR] Let Claude fix Renovate PRs whose CI is red,
148
+ inside an airlocked devcontainer (needs gh and
149
+ CLAUDE_CODE_OAUTH_TOKEN or ANTHROPIC_API_KEY)
150
+ huddle triage-agent [PR] Let Claude analyse open PRs labelled security
151
+ and comment its impact analysis, inside an
152
+ airlocked devcontainer (same requirements)
145
153
  huddle experiment use <nr> Activate the experimental build of issue/PR <nr>
146
154
  and run init
147
155
  huddle experiment reset Back to the stable release
@@ -154,7 +162,7 @@ Init options:
154
162
  (same as "huddle experiment use <nr>")
155
163
 
156
164
  Start options:
157
- --ide <intellij|rider|vscode> IDE (default: intellij)
165
+ --ide <intellij|rider|webstorm|vscode> IDE (default: intellij)
158
166
  --workspace <path> Workspace directory (default: current directory)
159
167
  --mount <host>=<container> Mount a host folder at an absolute container path, e.g.
160
168
  C:/projects/my-repo/backend=/workspace/backend
@@ -165,6 +173,23 @@ Start options:
165
173
  --image <image> Use a specific image
166
174
  --empty Empty container without a workspace
167
175
 
176
+ Update-agent options:
177
+ --dry-run Fix and verify, but print the diff instead of
178
+ pushing or commenting
179
+ --keep Keep the agent container and its folder
180
+ (~/.huddle/update-agent) for inspection
181
+ --skip-majors Skip PRs Renovate labelled 'major'
182
+ --out <dir> Write each run's network log to <dir>
183
+ (pr-<n>-network.json)
184
+
185
+ Triage-agent options:
186
+ --dry-run Analyse, but print the comment instead of posting it
187
+ --keep Keep the agent container and its folder
188
+ (~/.huddle/triage-agent) for inspection
189
+ --out <dir> Write each run's network log (pr-<n>-network.json)
190
+ and any analysis that must stay private
191
+ (pr-<n>-private.md) to <dir>
192
+
168
193
  Migrate options:
169
194
  --ca-path <path> Where the Huddle CA lands in the container
170
195
  (NODE_EXTRA_CA_CERTS; default /home/vscode/.huddle-ca.crt)
@@ -363,6 +388,27 @@ async function main() {
363
388
  });
364
389
  return;
365
390
  }
391
+ if (cmd === 'update-agent') {
392
+ await (0, update_agent_1.runUpdateAgent)({
393
+ pr: positional[1] !== undefined ? (0, experiment_1.parseIssueNumber)(positional[1]) : undefined,
394
+ dryRun: flagBool(flags, 'dry-run'),
395
+ keep: flagBool(flags, 'keep'),
396
+ skipMajors: flagBool(flags, 'skip-majors'),
397
+ out: flagString(flags, 'out'),
398
+ runtime: flagString(flags, 'runtime'),
399
+ });
400
+ return;
401
+ }
402
+ if (cmd === 'triage-agent') {
403
+ await (0, triage_agent_1.runTriageAgent)({
404
+ pr: positional[1] !== undefined ? (0, experiment_1.parseIssueNumber)(positional[1]) : undefined,
405
+ dryRun: flagBool(flags, 'dry-run'),
406
+ keep: flagBool(flags, 'keep'),
407
+ out: flagString(flags, 'out'),
408
+ runtime: flagString(flags, 'runtime'),
409
+ });
410
+ return;
411
+ }
366
412
  if (cmd === 'migrate') {
367
413
  await (0, migrate_1.runMigrate)({
368
414
  path: positional[1],
package/dist/start.js CHANGED
@@ -132,7 +132,9 @@ function parseIde(value) {
132
132
  return 'rider';
133
133
  if (normalized === 'vscode' || normalized === 'code')
134
134
  return 'vscode';
135
+ if (normalized === 'webstorm' || normalized === 'ws')
136
+ return 'webstorm';
135
137
  if (normalized === 'intellij' || normalized === 'intelij' || normalized === 'idea')
136
138
  return 'intellij';
137
- throw new Error(`Unknown IDE: ${value}. Choose intellij, rider, or vscode.`);
139
+ throw new Error(`Unknown IDE: ${value}. Choose intellij, rider, webstorm, or vscode.`);
138
140
  }