@buildaharness/app-node 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../src/paths.ts","../src/fs-backend.ts","../src/atomic-write.ts","../src/json-config-store.ts","../src/settings-store.ts","../src/consent-store.ts","../src/network-containment.ts","../src/shell.ts","../src/git-exclude.ts","../src/resolver.ts","../src/terminal.ts","../src/line-queue.ts","../src/prompts.ts","../src/non-interactive.ts","../src/commands.ts","../src/args.ts","../src/host.ts","../src/render.ts","../src/app-render.ts","../src/claude-cli-node.ts","../src/self-update-node.ts"],"sourcesContent":["import { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport type { AppIdentity } from '@buildaharness/runtime'\n\n/** The folder in the user's home under which every app built from these parts keeps its data. */\nexport const BUILDAHARNESS_DIR = '.buildaharness'\n\n/** Where an app keeps its data and settings: `~/.buildaharness/<legacy.dataDirName or id>`. */\nexport function appPaths(identity: AppIdentity, home: string = homedir()): { dataDir: string; configFile: string } {\n const dataDir = join(home, BUILDAHARNESS_DIR, identity.legacy?.dataDirName ?? identity.id)\n return { dataDir, configFile: join(dataDir, 'config.json') }\n}\n","import { createHash } from 'node:crypto'\nimport { mkdir, readFile, writeFile, readdir, unlink, realpath, stat, rename, chmod } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport type { FsBackend } from '@buildaharness/runtime'\nimport { BUILDAHARNESS_DIR } from './paths.js'\n\nfunction isEnoent(err: unknown): boolean {\n return (err as NodeJS.ErrnoException)?.code === 'ENOENT'\n}\n\n/**\n * node:fs/promises-backed FsBackend.\n *\n * The same backend writes both an app's own state (transcripts, checkpoints, experience, reminders) and\n * the user's workspace files. Only paths under a private root are made owner-only, like the config and\n * activity log; other files keep the permissions they would get anyway.\n */\nexport function nodeFsBackend(options: { privateRoots?: string[] } = {}): FsBackend {\n const roots = (options.privateRoots ?? [join(homedir(), BUILDAHARNESS_DIR)]).map((root) => resolve(root))\n const isPrivate = (path: string): boolean =>\n roots.some((root) => {\n const rel = relative(root, resolve(path))\n return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)\n })\n // Best effort: a file system without permission bits, or a file owned by someone else, still gets written.\n const restrict = (path: string, mode: number): Promise<void> => chmod(path, mode).catch(() => {})\n\n return {\n async readTextFile(path) {\n try {\n return await readFile(path, 'utf-8')\n } catch (err) {\n if (isEnoent(err)) return undefined\n throw err\n }\n },\n async writeTextFile(path, contents) {\n if (!isPrivate(path)) return writeFile(path, contents, 'utf-8')\n await writeFile(path, contents, { encoding: 'utf-8', mode: 0o600 })\n await restrict(path, 0o600)\n },\n async removeFile(path) {\n try {\n await unlink(path)\n } catch (err) {\n if (!isEnoent(err)) throw err\n }\n },\n async mkdir(path) {\n if (!isPrivate(path)) {\n await mkdir(path, { recursive: true })\n return\n }\n await mkdir(path, { recursive: true, mode: 0o700 })\n await restrict(path, 0o700)\n },\n async readDir(path) {\n try {\n return await readdir(path)\n } catch (err) {\n if (isEnoent(err)) return []\n throw err\n }\n },\n async realpath(path) {\n return realpath(path)\n },\n async stat(path) {\n try {\n const info = await stat(path)\n return { isDirectory: info.isDirectory(), size: info.size }\n } catch (err) {\n if (isEnoent(err)) return undefined\n throw err\n }\n },\n async rename(from, to) {\n await rename(from, to)\n },\n }\n}\n\n/**\n * Size and SHA-256 of a file's bytes, `undefined` when it does not exist. For `createFileMover`'s `fingerprint`: unlike a text reading it\n * tells two different binary files (Word, PDF, images) apart. Reads the whole file, so the caller limits what it asks about.\n */\nexport async function nodeFileFingerprint(path: string): Promise<string | undefined> {\n try {\n const bytes = await readFile(path)\n return `${bytes.length}:${createHash('sha256').update(bytes).digest('hex')}`\n } catch (err) {\n if (isEnoent(err)) return undefined\n throw err\n }\n}\n","import { writeFile, rename, mkdir } from 'node:fs/promises'\nimport { randomBytes } from 'node:crypto'\nimport { dirname } from 'node:path'\n\n/**\n * Writes `text` to `path` through a temp file in the same folder and a rename, so a crash mid-write never leaves half a file.\n * The folder is made owner-only when it is new, and the file is owner-only (0600): the temp file is new each time, so the mode\n * always applies and the rename carries it over an older, possibly world-readable, file.\n */\nexport async function writeFileAtomic(path: string, text: string): Promise<void> {\n await mkdir(dirname(path), { recursive: true, mode: 0o700 })\n const tempPath = `${path}.tmp-${process.pid}-${randomBytes(6).toString('hex')}`\n await writeFile(tempPath, text, { encoding: 'utf-8', mode: 0o600 })\n await rename(tempPath, path)\n}\n","import { readFile } from 'node:fs/promises'\nimport type { ConfigStore } from '@buildaharness/runtime'\nimport { writeFileAtomic } from './atomic-write.js'\n\nfunction isEnoent(err: unknown): boolean {\n return (err as NodeJS.ErrnoException)?.code === 'ENOENT'\n}\n\n/**\n * JSON-file-backed ConfigStore at a single `config.json` path (typically `appPaths(identity).configFile`).\n *\n * save() merges the patch onto whatever's already persisted (never a blind overwrite of\n * unrelated keys) and writes through a temp-file-then-rename so a crash mid-write can never\n * leave a half-written config.json behind. Setting a key to `undefined` in a\n * patch removes it from the persisted file (JSON.stringify drops undefined-valued\n * properties), which is what a settings reset relies on. A corrupt file warns and reads as empty.\n *\n * Concurrent save() calls on the same instance are serialized through an internal queue —\n * a command line may not wait for one command to finish before dispatching\n * the next (e.g. piped stdin with two settings lines back to back), so without this a\n * second save()'s load-modify-write could race the first's: reading stale state before the\n * first's write lands and silently clobbering it, or (with a timestamp-only temp filename)\n * colliding on the exact same temp path within the same millisecond.\n */\nexport function jsonConfigStore<C extends object>(path: string, opts: { warn?(message: string): void } = {}): ConfigStore<C> {\n const warn = opts.warn ?? ((message: string) => console.error(message))\n let queue: Promise<unknown> = Promise.resolve()\n\n const load = async (): Promise<Partial<C>> => {\n let raw: string\n try {\n raw = await readFile(path, 'utf-8')\n } catch (err) {\n if (isEnoent(err)) return {}\n throw err\n }\n try {\n const parsed: unknown = JSON.parse(raw)\n // `null`, a number or an array parses fine but is not a config object; treat it like corrupt JSON.\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) throw new Error('not an object')\n return parsed as Partial<C>\n } catch {\n warn(`Warning: ${path} is not valid JSON — ignoring it and falling back to defaults.`)\n return {}\n }\n }\n\n const writePatch = async (patch: Partial<C>): Promise<void> => {\n const existing = await load()\n const merged = { ...existing, ...patch }\n // The file may hold API keys and passwords in plain text: owner-only, never world-readable.\n await writeFileAtomic(path, JSON.stringify(merged, null, 2))\n }\n\n return {\n load,\n save(patch) {\n const task = queue.then(() => writePatch(patch))\n // A failed save must not poison the queue for saves queued after it.\n queue = task.catch(() => {})\n return task\n },\n }\n}\n","import { readFile } from 'node:fs/promises'\nimport type { SettingsStore } from '@buildaharness/runtime'\nimport { writeFileAtomic } from './atomic-write.js'\n\n/**\n * A SettingsStore kept in one JSON file (owner-only, written through a temp file and a rename), for values that must survive a\n * restart: a spending total, a running-job marker, an activity log. Values are what JSON keeps, so a Date comes back as text.\n *\n * Writes of one store object are applied one after the other, so two at once do not lose each other. A second process writing\n * the same file is not coordinated with. A missing file reads as empty; a file that is not a JSON object warns and reads as\n * empty, and the next write replaces it. Writing `undefined` removes the key.\n */\nexport function fileSettingsStore(path: string, opts: { warn?(message: string): void } = {}): SettingsStore {\n const warn = opts.warn ?? ((message: string) => console.error(message))\n let queue: Promise<unknown> = Promise.resolve()\n\n async function load(): Promise<Record<string, unknown>> {\n let raw: string\n try {\n raw = await readFile(path, 'utf-8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') return {}\n throw error\n }\n try {\n const parsed: unknown = JSON.parse(raw)\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) throw new Error('not an object')\n return parsed as Record<string, unknown>\n } catch {\n warn(`Warning: ${path} is not valid JSON, so its saved values are ignored.`)\n return {}\n }\n }\n\n return {\n async getSetting(key) {\n await queue.catch(() => {})\n const values = await load()\n return Object.hasOwn(values, key) ? values[key] : undefined\n },\n setSetting(key, value) {\n const task = queue.then(async () => {\n const values = await load()\n if (value === undefined) delete values[key]\n else values[key] = value\n await writeFileAtomic(path, JSON.stringify(values, null, 2))\n })\n queue = task.catch(() => {})\n return task\n },\n }\n}\n","import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport type { ConsentStore } from '@buildaharness/runtime'\n\n/**\n * Keeps the accepted terms version in a JSON file: `{ \"version\": \"...\", \"acceptedAt\": \"<ISO time>\" }`. A missing or unreadable\n * file reads as \"none\". The folder is made when it is missing.\n */\nexport function fileConsentStore(path: string): ConsentStore {\n return {\n read: () => {\n try {\n const version = (JSON.parse(readFileSync(path, 'utf8')) as { version?: unknown }).version\n return typeof version === 'string' ? version : undefined\n } catch {\n return undefined\n }\n },\n write: (version, acceptedAt) => {\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, JSON.stringify({ version, acceptedAt }))\n },\n }\n}\n","import { createServer, connect as netConnect, type Socket, type Server } from 'node:net'\n\n/**\n * Node-level network containment for an approved run_shell_command execution — Decision 6 of\n * the internal plan (Phase 4 step 2). This is the network-reachability\n * half of that decision; the env-stripping half already existed in shell.ts's\n * allowlistedEnv(). Deliberately not a real OS sandbox (see the plan's Decision 6 for why that\n * tradeoff was chosen): a minimal loopback-only forward proxy that relays a CONNECT tunnel\n * (HTTPS) or a plain-HTTP proxy request only when its target host matches an entry in the\n * caller-supplied allowlist (exact match or subdomain), and otherwise closes the connection with\n * a 403. The spawned subprocess's HTTP(S)_PROXY env vars are forced to point here, so a tool that\n * honors those (curl, wget, most language HTTP clients) can only reach an allowlisted host. This\n * does NOT stop a tool that opens raw sockets and ignores proxy env vars entirely — that\n * limitation is Decision 6's explicitly accepted tradeoff for a dependency-free, Node-only\n * implementation identical across CLI and desktop.\n */\n\nexport interface NetworkContainmentProxy {\n port: number\n close: () => Promise<void>\n}\n\nconst MAX_HEADER_BYTES = 16_384\n\nfunction hostAllowed(host: string, allowlist: readonly string[]): boolean {\n const normalized = host.toLowerCase()\n return allowlist.some((entry) => {\n const allowed = entry.toLowerCase()\n return normalized === allowed || normalized.endsWith(`.${allowed}`)\n })\n}\n\nfunction parseConnectTarget(requestLine: string): { host: string; port: number } | null {\n const match = /^CONNECT\\s+([^:\\s]+):(\\d+)\\s+HTTP/i.exec(requestLine)\n return match ? { host: match[1], port: Number(match[2]) } : null\n}\n\nfunction parsePlainHttpTarget(requestLine: string, headerText: string): { host: string; port: number } | null {\n const absoluteUri = /^[A-Z]+\\s+https?:\\/\\/([^/:\\s]+)(?::(\\d+))?/i.exec(requestLine)\n if (absoluteUri) return { host: absoluteUri[1], port: Number(absoluteUri[2] ?? 80) }\n\n const hostHeader = /^host:\\s*([^\\s:]+)(?::(\\d+))?/im.exec(headerText)\n return hostHeader ? { host: hostHeader[1], port: Number(hostHeader[2] ?? 80) } : null\n}\n\nfunction handleConnection(clientSocket: Socket, allowlist: readonly string[]): void {\n let buffered = Buffer.alloc(0)\n\n const onData = (chunk: Buffer): void => {\n buffered = Buffer.concat([buffered, chunk])\n const headerEnd = buffered.indexOf('\\r\\n\\r\\n')\n if (headerEnd === -1) {\n if (buffered.length > MAX_HEADER_BYTES) clientSocket.destroy()\n return\n }\n clientSocket.removeListener('data', onData)\n // With no 'data' listener a flowing socket silently drops what arrives next; hold it (e.g. the\n // rest of a plain-HTTP request body) until the upstream connection exists and pipe() resumes it.\n clientSocket.pause()\n\n const headerText = buffered.slice(0, headerEnd).toString('utf-8')\n const requestLine = headerText.split('\\r\\n')[0] ?? ''\n const isConnect = /^CONNECT\\s/i.test(requestLine)\n const target = isConnect ? parseConnectTarget(requestLine) : parsePlainHttpTarget(requestLine, headerText)\n\n if (!target || !hostAllowed(target.host, allowlist)) {\n clientSocket.end('HTTP/1.1 403 Forbidden\\r\\nContent-Length: 0\\r\\n\\r\\n')\n return\n }\n\n const upstream = netConnect(target.port, target.host, () => {\n if (isConnect) {\n clientSocket.write('HTTP/1.1 200 Connection Established\\r\\n\\r\\n')\n const tunnelBytes = buffered.slice(headerEnd + 4)\n if (tunnelBytes.length > 0) upstream.write(tunnelBytes)\n } else {\n upstream.write(buffered)\n }\n clientSocket.pipe(upstream)\n upstream.pipe(clientSocket)\n })\n upstream.on('error', () => clientSocket.destroy())\n // pipe() does not tear down the other side on an error or a premature close; without this a\n // client that vanishes leaves its upstream socket open indefinitely.\n clientSocket.on('close', () => upstream.destroy())\n }\n\n clientSocket.on('data', onData)\n clientSocket.on('error', () => clientSocket.destroy())\n}\n\nfunction startProxyServer(allowlist: readonly string[]): Promise<NetworkContainmentProxy> {\n return new Promise((resolveStart, rejectStart) => {\n const server: Server = createServer((socket) => handleConnection(socket, allowlist))\n server.on('error', rejectStart)\n server.listen(0, '127.0.0.1', () => {\n const address = server.address()\n if (address === null || typeof address === 'string') {\n rejectStart(new Error('Failed to bind network containment proxy to a loopback port'))\n return\n }\n resolveStart({\n port: address.port,\n close: () => new Promise((resolveClose) => server.close(() => resolveClose())),\n })\n })\n })\n}\n\n/** Starts a new loopback-only proxy scoped to `allowlist`. The caller closes it. */\nexport function startNetworkContainment(allowlist: readonly string[]): Promise<NetworkContainmentProxy> {\n return startProxyServer([...allowlist])\n}\n\n/**\n * Lazily starts (or reuses) a loopback-only proxy scoped to `allowlist`, keyed by its\n * (order-independent, case-insensitive) contents so repeated calls with the same allowlist reuse\n * one long-lived proxy instead of spawning a new server per shell command. Left running for the\n * process's lifetime — acceptable for a CLI/desktop session, not meant to be torn down mid-run.\n */\nconst proxyCache = new Map<string, Promise<NetworkContainmentProxy>>()\n\nexport function getNetworkContainmentProxy(allowlist: readonly string[]): Promise<NetworkContainmentProxy> {\n const key = JSON.stringify([...allowlist].map((host) => host.toLowerCase()).sort())\n let proxy = proxyCache.get(key)\n if (!proxy) {\n proxy = startProxyServer(allowlist)\n proxyCache.set(key, proxy)\n }\n return proxy\n}\n\n/** Test-only: drops all cached proxies so a test's allowlist doesn't leak into another test's expectations. */\nexport async function resetNetworkContainmentProxiesForTests(): Promise<void> {\n const proxies = [...proxyCache.values()]\n proxyCache.clear()\n for (const proxyPromise of proxies) {\n const proxy = await proxyPromise\n await proxy.close()\n }\n}\n","import { spawn } from 'node:child_process'\nimport type { ShellExecutionResult } from '@buildaharness/runtime'\nimport { getNetworkContainmentProxy } from './network-containment.js'\n\nconst DEFAULT_TIMEOUT_MS = 30_000\nconst DEFAULT_MAX_OUTPUT_BYTES = 20_000\n/** Never the parent process's full env (which would carry API keys and tokens into the command) — only these. */\nconst ALLOWED_ENV_VARS = ['PATH', 'HOME', 'LANG'] as const\n\nfunction allowlistedEnv(names: readonly string[]): NodeJS.ProcessEnv {\n const env: NodeJS.ProcessEnv = {}\n for (const key of names) {\n const value = process.env[key]\n if (value !== undefined) env[key] = value\n }\n return env\n}\n\n/**\n * Forces the child's HTTP(S)_PROXY env vars at a loopback-only containment proxy scoped to\n * `networkAllowlist` (see network-containment.ts) — Decision 6's network-reachability half,\n * alongside allowlistedEnv()'s existing secret-stripping half. An empty/undefined allowlist still\n * starts the proxy, just with nothing in it, so every attempt is refused with a 403 rather than\n * skipping containment entirely — deny-all is the safe default until the user opts a host in.\n *\n * Deliberately does NOT set NO_PROXY/no_proxy for 127.0.0.1/localhost: most HTTP clients (curl\n * included) skip the configured proxy entirely for any host listed in NO_PROXY, which would let a\n * command reach an arbitrary loopback service (a local metadata endpoint, an unauthenticated\n * internal API, a Docker socket proxy) without ever going through the allowlist check — a\n * loopback target is not inherently safe and must be subject to the same allowlist as anything\n * else. The one loopback address that does need to stay reachable unconditionally is the\n * containment proxy's own listener, which this env never routes through itself (a client connects\n * to it directly via the proxy env vars, not through the proxy), so no exemption is needed there.\n */\nasync function networkContainmentEnv(networkAllowlist: readonly string[]): Promise<NodeJS.ProcessEnv> {\n const proxy = await getNetworkContainmentProxy(networkAllowlist)\n const proxyUrl = `http://127.0.0.1:${proxy.port}`\n return {\n HTTP_PROXY: proxyUrl,\n http_proxy: proxyUrl,\n HTTPS_PROXY: proxyUrl,\n https_proxy: proxyUrl,\n }\n}\n\nfunction truncateOutput(text: string, maxBytes: number): string {\n const encoded = new TextEncoder().encode(text)\n if (encoded.length <= maxBytes) return text\n const truncated = new TextDecoder('utf-8', { fatal: false }).decode(encoded.slice(0, maxBytes))\n return `${truncated}\\n… (truncated)`\n}\n\nexport interface ShellCommandOptions {\n timeoutMs?: number\n maxOutputBytes?: number\n /** Hosts the command may reach through the containment proxy. None by default. */\n networkAllowlist?: readonly string[]\n /** Names of the parent's environment variables passed to the command, instead of PATH, HOME and LANG. */\n env?: readonly string[]\n}\n\n/**\n * Runs a command in a shell. It asks no one and checks no path: call it only for a command already approved, with an\n * already validated `cwd`. The environment is reduced to an explicit allowlist so a\n * secret like an API key can't leak into the command's environment,\n * plus network-containment.ts's loopback-only proxy forced via HTTP(S)_PROXY (Decision 6 — see\n * networkContainmentEnv's doc comment). A hard timeout SIGKILLs the whole process group (not just\n * the immediate child — `detached: true` + a negative-pid kill reaches anything the shell itself\n * spawned) rather than leaving it running. A non-zero exit code is not a thrown error — it's\n * reported normally, same as a real shell; only a spawn failure (e.g. the shell itself couldn't\n * start) throws.\n */\nexport async function runShellCommand(command: string, cwd: string, options: ShellCommandOptions = {}): Promise<ShellExecutionResult> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES\n const containmentEnv = await networkContainmentEnv(options.networkAllowlist ?? [])\n\n return new Promise((resolvePromise, reject) => {\n const proc = spawn(command, {\n shell: true,\n cwd,\n env: { ...allowlistedEnv(options.env ?? ALLOWED_ENV_VARS), ...containmentEnv },\n detached: true,\n stdio: ['ignore', 'pipe', 'pipe'],\n })\n\n let output = ''\n let timedOut = false\n let settled = false\n\n const finish = (exitCode: number | null): void => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n resolvePromise({\n output: truncateOutput(output, maxOutputBytes),\n exitCode: timedOut ? null : exitCode,\n timedOut,\n })\n }\n\n const timer = setTimeout(() => {\n timedOut = true\n try {\n if (proc.pid) process.kill(-proc.pid, 'SIGKILL')\n else proc.kill('SIGKILL')\n } catch {\n proc.kill('SIGKILL')\n }\n // 'close' waits for every stdout/stderr pipe to end; a descendant that left the process group\n // (setsid) keeps them open and would otherwise leave this promise pending forever.\n setTimeout(() => {\n proc.stdout?.destroy()\n proc.stderr?.destroy()\n finish(null)\n }, 2000).unref?.()\n }, timeoutMs)\n\n // Keep only what truncateOutput could ever return (plus a little slack for multi-byte chars):\n // a command that floods stdout for the whole timeout must not grow this string without bound.\n const append = (chunk: Buffer): void => {\n if (output.length <= maxOutputBytes * 2) output += chunk.toString('utf-8')\n }\n proc.stdout?.on('data', append)\n proc.stderr?.on('data', append)\n proc.on('error', (err: Error) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n reject(err)\n })\n proc.on('close', (exitCode: number | null) => finish(exitCode))\n })\n}\n","import { existsSync, mkdirSync, readFileSync, statSync, appendFileSync } from 'node:fs'\nimport { dirname, isAbsolute, join, resolve } from 'node:path'\n\n/** The git directory of the repository containing `start` (walking up), following a `.git` file (worktrees/submodules). */\nfunction findGitDir(start: string): string | undefined {\n let dir = resolve(start)\n for (;;) {\n const dotGit = join(dir, '.git')\n if (existsSync(dotGit)) {\n const stat = statSync(dotGit)\n if (stat.isDirectory()) return dotGit\n const line = readFileSync(dotGit, 'utf8').split('\\n').find((l) => l.startsWith('gitdir:'))\n if (!line) return undefined\n const target = line.slice('gitdir:'.length).trim()\n const gitDir = isAbsolute(target) ? target : resolve(dir, target)\n // A linked worktree's info/exclude lives in the shared (common) git directory.\n const commonFile = join(gitDir, 'commondir')\n if (existsSync(commonFile)) return resolve(gitDir, readFileSync(commonFile, 'utf8').trim())\n return gitDir\n }\n const parent = dirname(dir)\n if (parent === dir) return undefined\n dir = parent\n }\n}\n\n/**\n * Keeps an app's own state directories out of version control when the workspace is inside a git repo, by adding them to\n * `<gitdir>/info/exclude` — the per-clone ignore file git itself provides for this. The user's tracked `.gitignore` is never\n * touched, and a non-git directory is left exactly as it was. Idempotent and best-effort: resolves with the entries it added\n * and never rejects (a read-only .git must not stop the app from starting). The file work is done before the call returns.\n */\nexport async function excludeFromGit(workspaceRoot: string, dirs: readonly string[], options: { appName?: string } = {}): Promise<string[]> {\n try {\n const gitDir = findGitDir(workspaceRoot)\n if (!gitDir) return []\n const excludeFile = join(gitDir, 'info', 'exclude')\n const existing = existsSync(excludeFile) ? readFileSync(excludeFile, 'utf8') : ''\n const present = new Set(existing.split('\\n').map((l) => l.trim()))\n const missing = dirs.map((d) => `${d}/`).filter((entry) => !present.has(entry) && !present.has(entry.slice(0, -1)))\n if (missing.length === 0) return []\n mkdirSync(dirname(excludeFile), { recursive: true })\n const prefix = existing === '' || existing.endsWith('\\n') ? '' : '\\n'\n appendFileSync(excludeFile, `${prefix}# ${options.appName ?? 'App'} state (added automatically)\\n${missing.join('\\n')}\\n`)\n return missing\n } catch {\n return []\n }\n}\n","import { lookup } from 'node:dns/promises'\nimport type { AddressResolver } from '@buildaharness/runtime'\n\n/** Resolves a host name to all its addresses with the operating system's resolver. */\nexport function nodeResolver(): AddressResolver {\n return async (hostname) => (await lookup(hostname, { all: true })).map((record) => record.address)\n}\n","// What may reach a terminal. Escapes are written as \\u sequences so this file holds none of the characters it removes.\n\n// Complete escape sequences first (so no stray \"[31m\" is left behind), then any remaining control character\n// except \\n and \\t, the C1 range (8-bit CSI/OSC introducers) and bidi override characters.\nconst ESCAPE_SEQUENCE = /\\u001b\\][^\\u0007\\u001b]*(?:\\u0007|\\u001b\\\\)?|\\u001b\\[[0-?]*[ -/]*[@-~]|\\u001b[@-Z\\\\-_]|\\u001b/g\nconst UNSAFE_CHARS = /[\\u0000-\\u0008\\u000b-\\u001f\\u007f-\\u009f\\u061c\\u200b-\\u200f\\u202a-\\u202e\\u2066-\\u2069\\ufeff]/g\n\n/**\n * Text that came from the model, a tool result, a file or a web page must not reach the terminal raw: an\n * embedded escape sequence can clear the screen, rewrite earlier lines (hiding what an approval prompt is\n * really asking), set the window title or write the clipboard (OSC 52). Newlines and tabs survive; everything\n * that could drive the terminal is removed. Plain text is returned unchanged.\n */\nexport function stripTerminalControls(text: string): string {\n return text.replace(ESCAPE_SEQUENCE, '').replace(UNSAFE_CHARS, '')\n}\n\n/** Untrusted text as one line: filtered, and newlines and tabs become spaces so it cannot start a line of its own. */\nexport function oneLine(text: string): string {\n return stripTerminalControls(text).replace(/[\\n\\t\\u2028\\u2029]+/g, ' ')\n}\n\n/** Untrusted text as a block: filtered, and every line prefixed so none can pass for the program's own. */\nexport function indentBlock(text: string, prefix = ' | '): string {\n return stripTerminalControls(text).split(/\\n|\\u2028|\\u2029/).map((line) => `${prefix}${line}`).join('\\n')\n}\n","/**\n * Handles lines one at a time, in arrival order. A 'line' event does not wait for the previous line's async handler,\n * so piped or pasted input would otherwise run several commands at once.\n */\nexport function createLineQueue(\n handle: (line: string) => Promise<void>,\n onError: (error: unknown) => void,\n): { enqueue(line: string): Promise<void>; idle(): Promise<void> } {\n let tail: Promise<void> = Promise.resolve()\n return {\n /** Resolves when this line has been handled. Never rejects: a throw goes to `onError` and later lines still run. */\n enqueue(line) {\n tail = tail.then(() => handle(line)).catch(onError)\n return tail\n },\n /** Resolves when nothing is queued, including lines queued while waiting. */\n async idle() {\n let seen: Promise<void> | undefined\n while (seen !== tail) {\n seen = tail\n await seen\n }\n },\n }\n}\n","// Prompts that fail closed: when no real answer can be read the result is \"no\", never \"yes\".\nimport { stripTerminalControls } from './terminal.js'\n\n/** The part of a readline interface the prompts use. */\nexport interface PromptSource {\n question(query: string, callback: (answer: string) => void): void\n on(event: 'close', listener: () => void): unknown\n}\n\nexport interface SelectOption {\n key: string\n label: string\n}\n\n/** `none`: nothing could be read (input closed or broken). Never treat it as consent. */\nexport type YesNoAnswer = 'yes' | 'no' | 'none'\n\nexport interface PrompterOptions {\n source: PromptSource\n /** Prints the prompter's own notices. */\n say(text: string): void\n /** True: `confirm` and `select` answer \"no\" without reading input. */\n decline?: boolean\n declineNotice?: string\n /** Which typed answers count as yes. Default: `y` or `yes`, any case. */\n isYes?(answer: string): boolean\n /**\n * What happens to a prompt that is waiting when the input closes. `decline` (default) answers it with \"no\";\n * `leave` never settles it (nothing is approved, and the process can end with the work unfinished).\n */\n pendingAtClose?: 'decline' | 'leave'\n}\n\nexport interface Prompter {\n confirm(question: string): Promise<boolean>\n /** Like `confirm`, but tells a typed \"no\" apart from no answer at all. */\n yesNo(question: string): Promise<YesNoAnswer>\n /** The trimmed line, or undefined when nothing could be read. Reads input even when `decline` is set. */\n ask(question: string): Promise<string | undefined>\n /**\n * The chosen option's `key`, typed as the key or its number. Order the options with the safe one LAST: it is the\n * result of any other answer, of no answer, and of `decline`.\n */\n select(question: string, options: readonly SelectOption[]): Promise<string>\n}\n\nconst DEFAULT_DECLINE_NOTICE = '[non-interactive mode: auto-declining]'\nconst defaultIsYes = (answer: string): boolean => ['y', 'yes'].includes(answer.trim().toLowerCase())\n\nexport function createPrompter(o: PrompterOptions): Prompter {\n const isYes = o.isYes ?? defaultIsYes\n let closed = false\n let waiting: (() => void) | undefined\n o.source.on('close', () => {\n closed = true\n if ((o.pendingAtClose ?? 'decline') === 'decline') waiting?.()\n })\n\n /** One question to the source; undefined when it cannot be answered. The question is asked synchronously, so no line slips past. */\n function read(query: string, failureNotice: string): Promise<string | undefined> {\n return new Promise((resolve) => {\n const fail = (): void => {\n waiting = undefined\n o.say(`\\n[could not read a response — ${failureNotice}]`)\n resolve(undefined)\n }\n // A second question while one is waiting would be dropped by readline and never settle.\n if (closed || waiting) {\n o.say(`\\n[could not read a response — ${failureNotice}]`)\n return resolve(undefined)\n }\n waiting = fail\n try {\n o.source.question(stripTerminalControls(query), (answer) => {\n waiting = undefined\n resolve(answer.trim())\n })\n } catch {\n fail()\n }\n })\n }\n\n const declined = (): boolean => {\n if (!o.decline) return false\n o.say(`\\n${o.declineNotice ?? DEFAULT_DECLINE_NOTICE}`)\n return true\n }\n\n function yesNo(question: string): Promise<YesNoAnswer> {\n if (declined()) return Promise.resolve('no')\n return read(question, 'treating as declined').then((answer) => (answer === undefined ? 'none' : isYes(answer) ? 'yes' : 'no'))\n }\n\n return {\n yesNo,\n confirm: (question) => yesNo(question).then((answer) => answer === 'yes'),\n ask: (question) => read(question, 'treating as blank'),\n select(question, options) {\n const last = options[options.length - 1]\n if (!last) throw new Error('select() needs at least one option')\n if (declined()) return Promise.resolve(last.key)\n const lines = options.map((option, i) => ` ${i + 1}) [${option.key}] ${option.label.replace(/\\n/g, ' ')}`).join('\\n')\n return read(`${question}\\n${lines}\\n> `, 'treating as declined').then((answer) => {\n if (answer === undefined) return last.key\n const typed = answer.toLowerCase()\n const byKey = options.find((option) => option.key.toLowerCase() === typed)\n const byIndex = /^\\d+$/.test(typed) ? options[Number(typed) - 1] : undefined\n return (byKey ?? byIndex)?.key ?? last.key\n })\n },\n }\n}\n","/**\n * What a run does when nobody may be there to answer. `decline`: every approval is refused without touching input.\n * `require-tty`: refuse to start unless input is a terminal, instead of failing at the first approval.\n */\nexport type NonInteractiveMode = 'decline' | 'require-tty'\n\n/** Reads the mode from `env[variable]`. An unrecognised value warns and counts as unset, so a typo is never silent. */\nexport function resolveNonInteractiveMode(\n env: Record<string, string | undefined>,\n variable: string,\n warn: (message: string) => void = (message) => console.error(message),\n): NonInteractiveMode | undefined {\n const raw = env[variable]\n if (raw === undefined) return undefined\n if (raw === 'decline' || raw === 'require-tty') return raw\n warn(`[warning] ${variable}=\"${raw}\" is not \"decline\" or \"require-tty\" — ignoring.`)\n return undefined\n}\n","// A list of slash commands, the keys they dispatch on, and the help text made from the same list.\nimport { oneLine } from './terminal.js'\n\nexport interface CommandSpec {\n /** The command and any fixed subcommand words, no arguments: '/memory export'. The first word is the dispatch key. */\n name: string\n /** What help prints for it, arguments included. */\n usage: string\n description: string\n /** Other dispatch keys that run the same command ('/new' for '/clear'). */\n aliases?: string[]\n}\n\n/** First word of a command name: the key a dispatch table matches on. */\nexport function commandKey(name: string): string {\n return name.split(' ')[0]!\n}\n\n/** One line per command: usage, padded, then the description. */\nexport function formatCommandHelp(commands: readonly CommandSpec[]): string {\n const width = Math.max(0, ...commands.map((c) => c.usage.length))\n return commands.map((c) => ` ${c.usage.padEnd(width + 2)} ${oneLine(c.description)}`).join('\\n')\n}\n\nconst QUIT_WORDS: ReadonlySet<string> = new Set(['exit', 'quit', '/exit', '/quit'])\n\n/** A bare `exit` / `quit` (with or without a leading slash, any case) ends the session; anything longer is an ordinary message. An exact command match, not a reading of the message. */\nexport function isQuitCommand(message: string): boolean {\n return QUIT_WORDS.has(message.trim().toLowerCase())\n}\n","// Command-line arguments: `app [command] [options] [--] [words]`. Strict: an unknown option is an error, never ignored.\nimport { parseArgs } from 'node:util'\n\nexport interface ArgOption {\n type: 'boolean' | 'string'\n /** One letter. */\n short?: string\n help: string\n}\n\nexport interface ArgCommand {\n help: string\n options?: Record<string, ArgOption>\n}\n\nexport interface ArgSpec {\n name: string\n version: string\n summary?: string\n /** Accepted with or without a command. `--help` and `--version` are built in. */\n options?: Record<string, ArgOption>\n /** A command is recognised only as the first argument. */\n commands?: Record<string, ArgCommand>\n}\n\nexport type ParsedArgs =\n | { kind: 'help' }\n | { kind: 'version' }\n | { kind: 'error'; message: string }\n | { kind: 'run'; command?: string; options: Record<string, string | boolean | undefined>; words: string[] }\n\n/** `argv` is the user's arguments only, i.e. `process.argv.slice(2)`. */\nexport function parseCommandLine(argv: readonly string[], spec: ArgSpec): ParsedArgs {\n const commands = spec.commands ?? {}\n const first = argv[0]\n const command = first !== undefined && Object.hasOwn(commands, first) ? first : undefined\n const declared = { ...spec.options, ...(command ? commands[command]!.options : {}) }\n const options: Record<string, { type: 'boolean' | 'string'; short?: string }> = {\n help: { type: 'boolean', short: 'h' },\n version: { type: 'boolean', short: 'v' },\n }\n for (const [name, o] of Object.entries(declared)) options[name] = { type: o.type, ...(o.short ? { short: o.short } : {}) }\n try {\n const { values, positionals } = parseArgs({ args: argv.slice(command ? 1 : 0), options, allowPositionals: true, strict: true })\n if (values.help) return { kind: 'help' }\n if (values.version) return { kind: 'version' }\n return { kind: 'run', ...(command ? { command } : {}), options: { ...values } as Record<string, string | boolean | undefined>, words: positionals }\n } catch (e) {\n return { kind: 'error', message: e instanceof Error ? e.message : String(e) }\n }\n}\n\nexport function commandLineHelp(spec: ArgSpec): string {\n const rows = (entries: [string, string][]): string[] => {\n const width = Math.max(0, ...entries.map(([left]) => left.length))\n return entries.map(([left, help]) => ` ${left.padEnd(width + 2)} ${help}`)\n }\n const optionRows = (options: Record<string, ArgOption>, indent = ''): [string, string][] =>\n Object.entries(options).map(([name, o]) => [`${indent}${o.short ? `-${o.short}, ` : ''}--${name}${o.type === 'string' ? ' <value>' : ''}`, o.help])\n const commands = Object.entries(spec.commands ?? {}).flatMap(([name, c]): [string, string][] => [[name, c.help], ...optionRows(c.options ?? {}, ' ')])\n return [\n `${spec.name} ${spec.version}${spec.summary ? ` — ${spec.summary}` : ''}`,\n '',\n `Usage: ${spec.name}${commands.length ? ' [command]' : ''} [options]`,\n ...(commands.length ? ['', 'Commands:', ...rows(commands)] : []),\n '',\n 'Options:',\n ...rows([...optionRows(spec.options ?? {}), ['-h, --help', 'show this help'], ['-v, --version', 'print the version']]),\n ].join('\\n')\n}\n","// The command-line front end of an app: safe output, fail-closed prompts, slash commands and a one-at-a-time line loop.\nimport { createInterface, type Interface } from 'node:readline'\nimport type { AppIdentity } from '@buildaharness/runtime'\nimport { commandKey, formatCommandHelp, isQuitCommand, type CommandSpec } from './commands.js'\nimport { createLineQueue } from './line-queue.js'\nimport { resolveNonInteractiveMode, type NonInteractiveMode } from './non-interactive.js'\nimport { createPrompter, type Prompter, type SelectOption, type YesNoAnswer } from './prompts.js'\nimport { oneLine, stripTerminalControls } from './terminal.js'\n\nexport interface HostCommand extends CommandSpec {\n /** Without `run`, the entry only appears in help (a subcommand of an entry that has it). */\n run?(args: string[]): void | Promise<void>\n}\n\n/** A reason the app refuses to start; show the message to the user as it is. */\nexport class StartupError extends Error {}\n\nexport interface CliHost {\n /** One line or block, control sequences removed. */\n print(text: string): void\n /** The same filter, without the newline: for streamed output. */\n write(text: string): void\n /** False when no answer can be read, and always in `decline` mode. */\n confirm(question: string): Promise<boolean>\n /** `none`: no answer could be read. In `decline` mode the answer is `no`. */\n yesNo(question: string): Promise<YesNoAnswer>\n /** Free text. Undefined when nothing could be read, and in `decline` mode (input is not touched). */\n ask(question: string): Promise<string | undefined>\n /** The last option on any answer that names none. Put the safe choice last. */\n select(question: string, options: readonly SelectOption[]): Promise<string>\n /**\n * Handles input until it closes or the user types `exit`/`quit`: registered commands run, every other non-empty line\n * goes to `handle`, one at a time. Resolves when the queued lines have been handled, and closes the host.\n */\n serve(handle?: (line: string) => Promise<void>): Promise<void>\n /** Ctrl+C goes to the newest listener instead of ending the session, while the host is reading a terminal. Returns the remover. */\n onInterrupt(listener: () => void): () => void\n help(): string\n readonly nonInteractive: NonInteractiveMode | undefined\n close(): void\n}\n\nexport interface CliHostOptions {\n identity: AppIdentity\n commands?: HostCommand[]\n input?: NodeJS.ReadableStream\n output?: NodeJS.WritableStream\n /** Default: the `<envPrefix>_NON_INTERACTIVE_APPROVAL` environment variable, if set. */\n nonInteractive?: NonInteractiveMode\n env?: Record<string, string | undefined>\n /** Shown by `serve` when input is a terminal. Default `> `. */\n prompt?: string\n}\n\nexport function createCliHost(o: CliHostOptions): CliHost {\n const input = o.input ?? process.stdin\n const output = o.output ?? process.stdout\n const isTty = (input as { isTTY?: boolean }).isTTY === true\n const write = (text: string): void => void output.write(stripTerminalControls(text))\n const print = (text: string): void => write(`${text}\\n`)\n\n const variable = `${o.identity.envPrefix}_NON_INTERACTIVE_APPROVAL`\n const mode = o.nonInteractive ?? resolveNonInteractiveMode(o.env ?? process.env, variable, print)\n if (mode === 'require-tty' && !isTty) {\n throw new StartupError(`${o.identity.name} is set to require a terminal (require-tty), but input is not one. Run it in a terminal, or use ${variable}=decline to refuse every approval.`)\n }\n\n const own = o.commands ?? []\n const builtIn: HostCommand[] = [\n { name: '/help', usage: '/help', description: 'Show this list', run: () => print(help()) },\n { name: '/exit', usage: '/exit (/quit, exit, quit)', description: 'End the session' },\n ]\n // An app's own entry replaces the built-in one of the same name.\n const commands = [...builtIn.filter((b) => !own.some((c) => c.name === b.name)), ...own]\n const help = (): string => formatCommandHelp(commands)\n const table = new Map<string, (args: string[]) => void | Promise<void>>()\n for (const command of commands) {\n if (!command.run) continue\n for (const key of [commandKey(command.name), ...(command.aliases ?? [])]) {\n if (table.has(key)) throw new Error(`Two commands handle \"${key}\"`)\n table.set(key, command.run)\n }\n }\n\n // The interface is made on first use, so an app that never reads input does not hold the process open.\n let rl: Interface | undefined\n let prompter: Prompter | undefined\n let closed = false\n let onLine: ((line: string) => void) | undefined\n let onClose: (() => void) | undefined\n /** Lines that arrived before `serve`: they are commands waiting their turn, never answers to a later question. */\n const backlog: string[] = []\n const interrupts: (() => void)[] = []\n\n function open(): Prompter {\n if (prompter) return prompter\n // An input that already ended never emits 'close' again.\n const ended = closed || (input as { readableEnded?: boolean }).readableEnded === true\n rl = createInterface({ input, output, prompt: o.prompt ?? '> ' })\n rl.on('line', (line) => (onLine ? onLine(line) : void backlog.push(line)))\n rl.on('close', () => {\n closed = true\n onClose?.()\n })\n rl.on('SIGINT', () => {\n const listener = interrupts[interrupts.length - 1]\n if (listener) listener()\n else rl?.close()\n })\n prompter = createPrompter({\n source: rl,\n say: print,\n decline: mode === 'decline',\n declineNotice: `[non-interactive mode: auto-declining — ${variable}=decline]`,\n })\n if (ended) rl.close()\n return prompter\n }\n\n function close(): void {\n closed = true\n rl?.close()\n }\n\n async function dispatch(line: string, handle: ((line: string) => Promise<void>) | undefined): Promise<void> {\n const [token = '', ...args] = line.split(/\\s+/)\n const run = table.get(token)\n if (run) await run(args)\n else if (handle) await handle(line)\n else print(`Unknown command \"${oneLine(token)}\". /help lists the commands.`)\n }\n\n return {\n print,\n write,\n help,\n nonInteractive: mode,\n close,\n yesNo: (question) => open().yesNo(question),\n confirm: (question) => open().confirm(question),\n ask: (question) => (mode === 'decline' ? Promise.resolve(undefined) : open().ask(question)),\n select: (question, options) => open().select(question, options),\n onInterrupt(listener) {\n interrupts.push(listener)\n return () => {\n const at = interrupts.lastIndexOf(listener)\n if (at >= 0) interrupts.splice(at, 1)\n }\n },\n serve(handle) {\n if (onLine) throw new Error('serve() is already running')\n return new Promise((resolve) => {\n let quitting = false\n const showPrompt = (): void => {\n if (isTty && !closed) rl?.prompt()\n }\n const queue = createLineQueue(\n async (line) => {\n if (quitting) return\n if (isQuitCommand(line)) {\n quitting = true\n close()\n return\n }\n await dispatch(line, handle)\n },\n (error) => print(`[error] ${error instanceof Error ? error.message : String(error)}`),\n )\n const take = (raw: string): void => {\n const line = raw.trim()\n if (!line) return showPrompt()\n void queue.enqueue(line).then(showPrompt)\n }\n let finishing = false\n const finish = (): void => {\n if (finishing) return\n finishing = true\n void queue.idle().then(() => {\n onLine = onClose = undefined\n resolve()\n })\n }\n const alreadyClosed = closed\n onClose = finish\n onLine = take\n open()\n for (const line of backlog.splice(0)) take(line)\n if (alreadyClosed || closed) finish()\n else showPrompt()\n })\n },\n }\n}\n","// The shared job and approval events as terminal text. Everything in them may come from a model or a file.\nimport { progressText, type Approvals, type ApproveResult, type Job, type JobEvent, type JobOutcome, type Pending } from '@buildaharness/runtime'\nimport type { CliHost } from './host.js'\nimport { indentBlock, oneLine, stripTerminalControls } from './terminal.js'\n\nconst TONES = { good: 'ok', warn: 'warning', bad: 'failed' } as const\nconst ENDS = { done: 'Done.', stopped: 'Stopped.', failed: 'Failed.' } as const\n\n/** One line for an event; a `text` event is a chunk of streamed output and has no newline of its own. */\nexport function formatJobEvent(event: JobEvent): string {\n switch (event.kind) {\n case 'count':\n case 'stage':\n return ` ${oneLine(progressText(event))}`\n case 'text':\n return stripTerminalControls(event.chunk)\n case 'note':\n return ` ${event.tone ? `${TONES[event.tone]}: ` : ''}${oneLine(event.text)}`\n case 'stop':\n return event.how === 'soft' ? 'Stopping after the current step. Press Ctrl+C again to stop now.' : 'Stopping now.'\n case 'end':\n return ENDS[event.outcome]\n }\n}\n\n/** Prints a job's events until it ends. Ctrl+C asks it to stop after the current step, a second one stops it at once. */\nexport async function runJob<R>(host: CliHost, job: Job<R>): Promise<JobOutcome<R>> {\n let midLine = false\n let asked = false\n let last = ''\n const unsubscribe = job.subscribe((event) => {\n const text = formatJobEvent(event)\n if (event.kind === 'text') {\n host.write(text)\n if (text) midLine = !text.endsWith('\\n')\n return\n }\n if (midLine) host.write('\\n')\n midLine = false\n if (text !== last) host.print(text)\n last = text\n })\n const release = host.onInterrupt(() => {\n job.stop(asked ? 'hard' : 'soft')\n asked = true\n })\n try {\n const outcome = await job.done\n if (outcome.status === 'failed') host.print(indentBlock(outcome.error instanceof Error ? outcome.error.message : String(outcome.error)))\n return outcome\n } finally {\n release()\n unsubscribe()\n }\n}\n\n/** What is about to be done. Details and warnings are indented so they cannot pass for the program's own lines. */\nexport function formatPending(pending: Pending): string {\n const { shown } = pending\n return [\n `Needs approval: ${oneLine(shown.summary)}`,\n ...(shown.details ? [indentBlock(shown.details)] : []),\n ...(shown.items ?? []).map((item, i) => ` ${i + 1}) ${oneLine(item.label)}`),\n ...(shown.warnings ?? []).map((warning) => ` Warning: ${oneLine(warning)}`),\n ...(shown.reversible ? [] : [' This cannot be undone.']),\n ].join('\\n')\n}\n\nexport function formatApproveResult(result: ApproveResult<unknown>): string {\n switch (result.status) {\n case 'applied':\n return 'Done.'\n case 'not_applied':\n return `Not done: ${oneLine(result.error)} It is still waiting for approval.`\n case 'outcome_unknown':\n return `This may or may not have been done: ${oneLine(result.error)} Check before trying again.`\n case 'refused': {\n const why = { unknown: 'there is no such action', in_progress: 'it is already being handled', changed: 'it changed since it was shown', invalid: 'it cannot be checked' }[result.reason]\n return `Not done: ${why}.${result.error ? ` ${oneLine(result.error)}` : ''}`\n }\n }\n}\n\nexport type ReviewOutcome =\n /** The person said yes; `result` says what then happened. */\n | { decision: 'approved'; result: ApproveResult<unknown> }\n /** The person (or `decline` mode) said no; the action was rejected. */\n | { decision: 'declined' }\n /** No answer could be read; the action is still pending and nothing was done. */\n | { decision: 'unanswered' }\n /** There was nothing that could be asked about. */\n | { decision: 'not_asked'; reason: 'unknown' | 'claimed' | 'cannot_be_checked' }\n\n/** How often a changed action is shown again before giving up. */\nconst MAX_ASKS = 3\n\n/**\n * Shows a staged action as it is now and applies it only on a yes to that preview. If it changed meanwhile, the new\n * preview is shown and asked about again.\n */\nexport async function reviewApproval(host: CliHost, approvals: Approvals, id: string): Promise<ReviewOutcome> {\n let pending = await approvals.get(id)\n for (let attempt = 1; ; attempt++) {\n const reason = !pending ? 'unknown' : pending.claimed ? 'claimed' : pending.fingerprint === '' ? 'cannot_be_checked' : undefined\n if (pending) host.print(formatPending(pending))\n if (reason || !pending) {\n host.print({ unknown: 'There is no such action.', claimed: 'This is being applied, or an earlier attempt did not finish. It is not run again.', cannot_be_checked: 'This cannot be checked, so it cannot be approved.' }[reason ?? 'unknown'])\n return { decision: 'not_asked', reason: reason ?? 'unknown' }\n }\n\n let items: string[] | undefined\n const shownItems = pending.shown.items\n if (shownItems && shownItems.length > 1 && !host.nonInteractive) {\n const typed = await host.ask('Numbers to leave out (comma-separated, Enter for none): ')\n if (typed === undefined) return { decision: 'unanswered' }\n const numbers = typed.split(/[\\s,]+/).filter(Boolean).map(Number)\n // A number that names no item means the person meant something else: ask for nothing to be done.\n if (numbers.some((n) => !Number.isInteger(n) || n < 1 || n > shownItems.length)) {\n host.print('Not one of the numbers shown; nothing was done.')\n return { decision: 'unanswered' }\n }\n items = shownItems.filter((_, i) => !numbers.includes(i + 1)).map((item) => item.id)\n if (items.length === 0) {\n await approvals.reject(id)\n host.print('Everything was left out; nothing was done.')\n return { decision: 'declined' }\n }\n }\n\n const answer = await host.yesNo('Approve? (y/N) ')\n if (answer === 'none') return { decision: 'unanswered' }\n if (answer === 'no') {\n await approvals.reject(id)\n host.print('Declined; nothing was done.')\n return { decision: 'declined' }\n }\n const result = await approvals.approve(id, pending.fingerprint, items ? { items } : {})\n host.print(formatApproveResult(result))\n if (result.status === 'refused' && result.reason === 'changed' && result.current && attempt < MAX_ASKS) {\n pending = result.current\n continue\n }\n return { decision: 'approved', result }\n }\n}\n","// A runtime app session (`createAppSession`) on a terminal: progress while an action runs, and each decision it staged shown and\n// answered. The runtime's `runJob` / `reviewApproval` (in render.ts) do the same for a bare Job and for Approvals.\n// Everything in an event or a decision may come from a model or a file, so every line goes through `oneLine` or `indentBlock`.\n// Names the shared parts show are already escaped there (`escapeFileName`), so they are not escaped again.\nimport type { AppEvent, AppJob, AppOutcome, AppSession, Decision } from '@buildaharness/runtime'\nimport type { JobEvent } from '@buildaharness/runtime'\nimport type { CliHost } from './host.js'\nimport { formatJobEvent } from './render.js'\nimport { indentBlock, oneLine } from './terminal.js'\n\n/** What a person sees while an action runs (progress, stages, notes). Other events (decisions, the end) are for the caller. */\nexport function formatAppEvent(event: AppEvent): string | undefined {\n return event.kind === 'count' || event.kind === 'stage' || event.kind === 'note' ? formatJobEvent(event as JobEvent) : undefined\n}\n\n/** A decision as the person is asked about it. */\nexport function formatDecision(decision: Decision): string {\n const d = decision\n return [\n `Needs approval: ${oneLine(d.summary)}`,\n ...(d.details ? [indentBlock(d.details)] : []),\n ...(d.items ?? []).map((item, i) => ` ${i + 1}) ${oneLine(item.label)}`),\n ...(d.warnings ?? []).map((w) => ` Warning: ${oneLine(w)}`),\n ...(d.reversible ? [] : [' This cannot be undone.']),\n ].join('\\n')\n}\n\nexport interface AppJobRun<R> {\n outcome: AppOutcome<R>\n /** Every decision the action staged, in order. Answer them with `reviewDecision`. */\n decisions: Decision[]\n}\n\n/**\n * Prints an action's progress until it ends and collects its decisions. Ctrl+C asks it to stop after the current step, a second\n * one stops it at once. A stop or a failure is printed (\"Stopped.\", \"Failed: ...\") and comes back in `outcome`.\n */\nexport async function runAppJob<R>(host: CliHost, job: AppJob<R>): Promise<AppJobRun<R>> {\n const decisions: Decision[] = []\n let last = ''\n let asked = false\n const unsubscribe = job.subscribe((event) => {\n if (event.kind === 'decision') return void decisions.push(event.request)\n const line = formatAppEvent(event)\n if (line !== undefined && line !== last) host.print(line)\n last = line ?? last\n })\n const release = host.onInterrupt(() => {\n job.stop(asked ? 'hard' : 'soft')\n asked = true\n })\n try {\n const outcome = await job.done\n if (outcome.status === 'stopped') host.print('Stopped.')\n else if (outcome.status === 'failed') host.print(`Failed: ${oneLine(outcome.message)}`)\n return { outcome, decisions }\n } finally {\n release()\n unsubscribe()\n }\n}\n\n/** What is said of the result of an approved decision. Shapes are those of the shared file move and its undo. */\nexport function formatDecisionResult(result: unknown, o: { undoHint?: string } = {}): string[] {\n const r = (result ?? {}) as { declined?: boolean; moved?: string[]; failed?: { id: string; reason: string }[]; restored?: string[]; conflicts?: { id: string; reason: string }[]; refused?: string }\n const files = (n: number): string => `${n} file${n === 1 ? '' : 's'}`\n if (r.declined) return ['Declined; nothing was done.']\n if (Array.isArray(r.moved)) {\n return [`Moved ${files(r.moved.length)}.${o.undoHint ? ` ${o.undoHint}` : ''}`, ...(r.failed ?? []).map((f) => ` not moved: ${oneLine(f.id)}: ${oneLine(f.reason)}`)]\n }\n if (Array.isArray(r.restored)) {\n return [`Moved back ${files(r.restored.length)}.`, ...(r.conflicts ?? []).map((c) => ` left alone: ${oneLine(c.id)}: ${oneLine(c.reason.replace('_', ' '))}`), ...(r.refused ? [`Not undone: ${oneLine(r.refused)}`] : [])]\n }\n return ['Done.']\n}\n\n/** How often a decision that changed is shown again before giving up. */\nconst MAX_ASKS = 3\n\n/**\n * Shows a decision as it is now and applies it only on a yes to what was shown. With more than one item the person may leave\n * some out. With nobody to ask (no terminal, or the non-interactive mode `decline`) it is declined. If it changed meanwhile the\n * new one is shown instead, up to three times. Prints the outcome and returns it: `done` also when the person declined.\n */\nexport async function reviewDecision(host: CliHost, session: AppSession, decision: Decision, o: { undoHint?: string } = {}): Promise<AppOutcome<unknown>> {\n let outcome: AppOutcome<unknown> = { status: 'failed', message: 'Not answered.', retryable: false, partial: false, unread: [] }\n for (let attempt = 1; attempt <= MAX_ASKS; attempt++) {\n host.print(formatDecision(decision))\n let items: string[] | undefined\n let approve = false\n const shown = decision.items ?? []\n if (shown.length > 1 && !host.nonInteractive) {\n const typed = await host.ask('Numbers to leave out (comma-separated, Enter for none): ')\n const numbers = (typed ?? '').split(/[\\s,]+/).filter(Boolean).map(Number)\n // A number that names no item means the person meant something else: nothing is approved.\n if (typed === undefined || numbers.some((n) => !Number.isInteger(n) || n < 1 || n > shown.length)) {\n host.print('Nothing was approved.')\n } else {\n items = shown.filter((_, i) => !numbers.includes(i + 1)).map((item) => item.id)\n approve = items.length > 0\n }\n } else {\n approve = (await host.yesNo('Approve? (y/N) ')) === 'yes'\n }\n let next: Decision | undefined\n const answer = session.resolve(decision.id, { choice: approve ? 'approve' : 'decline', fingerprint: decision.fingerprint, ...(items ? { items } : {}) })\n answer.subscribe((e) => {\n if (e.kind === 'decision') next = e.request\n })\n outcome = await answer.done\n if (outcome.status === 'done') {\n for (const line of formatDecisionResult(outcome.result, o)) host.print(line)\n return outcome\n }\n host.print(outcome.status === 'failed' ? `Not done: ${oneLine(outcome.message)}` : 'Stopped.')\n if (!next) return outcome\n decision = next\n }\n return outcome\n}\n","// The Node ports of the claude_cli_client part: a process runner over node:child_process and the tool gate's loopback TCP server.\nimport { spawn } from 'node:child_process'\nimport { createServer } from 'node:net'\nimport type { ProcessRunner, ToolGateHost } from '@buildaharness/runtime'\n\n/** Runs a command with no stdin and piped output. Output is decoded a chunk at a time as UTF-8. */\nexport const createNodeProcessRunner = (): ProcessRunner => ({\n spawn(command, args, options, events) {\n const proc = spawn(command, args, { cwd: options.cwd, stdio: ['ignore', 'pipe', 'pipe'] })\n proc.stdout.on('data', (chunk: Buffer | string) => events.onStdout(typeof chunk === 'string' ? chunk : chunk.toString('utf-8')))\n proc.stderr.on('data', (chunk: Buffer | string) => events.onStderr(typeof chunk === 'string' ? chunk : chunk.toString('utf-8')))\n proc.on('error', events.onError)\n proc.on('close', events.onClose)\n return { kill: () => { proc.kill() } }\n },\n})\n\n/** Listens on an ephemeral loopback port: newline-delimited requests, one reply line each. */\nexport const createNodeToolGateHost = (): ToolGateHost => ({\n listen(handle) {\n return new Promise((resolvePromise, reject) => {\n const server = createServer((socket) => {\n // A peer that dies mid-request emits 'error'; with no listener that is an uncaught exception that would crash the process.\n socket.on('error', () => {})\n let buffer = ''\n socket.on('data', (chunk: Buffer) => {\n buffer += chunk.toString('utf-8')\n let newlineIndex: number\n while ((newlineIndex = buffer.indexOf('\\n')) !== -1) {\n const line = buffer.slice(0, newlineIndex)\n buffer = buffer.slice(newlineIndex + 1)\n if (!line.trim()) continue\n void handle(line).then((reply) => { socket.write(`${reply}\\n`) })\n }\n })\n })\n server.on('error', reject)\n server.listen(0, '127.0.0.1', () => {\n const address = server.address()\n if (address === null || typeof address === 'string') {\n reject(new Error('tool gate server failed to bind to a loopback TCP port'))\n return\n }\n resolvePromise({ port: address.port, close: () => { server.close() } })\n })\n })\n }})\n","/**\n * The Node side of the shared self-update (`runUpdate`, `checkForUpdate` in `@buildaharness/runtime`): the file port\n * (streamed download with a hash, hash of the file on disk, atomic replace with rollback), the cache file, and the\n * clean-up of leftovers. The decisions are in the runtime part; this file only touches the machine.\n */\nimport { createHash } from 'node:crypto'\nimport { createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync, renameSync, chmodSync, rmSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { Readable } from 'node:stream'\nimport { pipeline } from 'node:stream/promises'\nimport type { ReadableStream as WebReadableStream } from 'node:stream/web'\nimport { assertHttps, parseUpdateCache, UPDATE_DOWNLOAD_TIMEOUT_MS, type UpdateCacheStore, type UpdateFiles } from '@buildaharness/runtime'\n\n/**\n * Replaces the binary at `execPath` with the already-verified file at `newFile` (same directory).\n * Unix: `rename` over the running binary (POSIX lets a still-open inode be replaced). Windows cannot overwrite a running\n * exe, so the current one is renamed aside to `.old` first (cleaned up on the next launch by `cleanupStaleUpdateFiles`),\n * rolling back if the second rename fails.\n */\nexport function replaceBinary(execPath: string, newFile: string, platform: string = process.platform): void {\n if (platform === 'win32') {\n const aside = `${execPath}.old`\n rmSync(aside, { force: true })\n renameSync(execPath, aside)\n try {\n renameSync(newFile, execPath)\n } catch (err) {\n renameSync(aside, execPath)\n throw err\n }\n return\n }\n chmodSync(newFile, 0o755)\n renameSync(newFile, execPath)\n}\n\n/** Removes leftovers of a previous update (the Windows `.old` copy, an interrupted temp download). Never throws. */\nexport function cleanupStaleUpdateFiles(execPath: string = process.execPath): void {\n for (const stale of [`${execPath}.old`, `${execPath}.update.tmp`]) {\n try {\n if (existsSync(stale)) rmSync(stale, { force: true })\n } catch {\n // Still locked (the previous process has not fully exited): the next launch retries.\n }\n }\n}\n\n/** Streams `url` to `dest`, returning the lowercase hex sha256 of exactly the bytes written. */\nasync function downloadTo(fetchFn: typeof fetch, url: string, dest: string, allowInsecureHttp = false): Promise<string> {\n const res = await fetchFn(url, { signal: AbortSignal.timeout(UPDATE_DOWNLOAD_TIMEOUT_MS), redirect: 'follow' })\n if (!res.ok || !res.body) throw new Error(`Download failed: HTTP ${res.status} for ${url}`)\n // fetch follows redirects, and the HTTPS check before the call only saw the first URL: refuse a response that ended\n // up served over plain http (a downgrade redirect).\n if (res.url) assertHttps(res.url, allowInsecureHttp)\n const hash = createHash('sha256')\n // Start from nothing and refuse to write through anything already at the path (a planted symlink, or another update\n // mid-download): 'wx' fails instead of following or sharing it.\n rmSync(dest, { force: true })\n await pipeline(\n Readable.fromWeb(res.body as unknown as WebReadableStream<Uint8Array>),\n async function* (source: AsyncIterable<Buffer>) {\n for await (const chunk of source) {\n hash.update(chunk)\n yield chunk\n }\n },\n createWriteStream(dest, { flags: 'wx' }),\n )\n return hash.digest('hex')\n}\n\n/** sha256 of the file as it is on disk right now: what `replaceBinary` will actually install, not what the stream carried. */\nasync function sha256OfFile(path: string): Promise<string> {\n const hash = createHash('sha256')\n for await (const chunk of createReadStream(path)) hash.update(chunk)\n return hash.digest('hex')\n}\n\nexport function createNodeUpdateFiles(): UpdateFiles {\n return {\n download: downloadTo,\n sha256OfFile,\n remove: (path) => rmSync(path, { force: true }),\n makeDir: (dir) => { mkdirSync(dir, { recursive: true }) },\n replace: replaceBinary,\n dirname,\n }\n}\n\n/** The throttle cache as `<dataDir>/<fileName>` (`update-check.json`). */\nexport function createFileUpdateCache(dataDir: string, fileName = 'update-check.json'): UpdateCacheStore {\n const path = join(dataDir, fileName)\n return {\n read: () => {\n try {\n return parseUpdateCache(readFileSync(path, 'utf8'))\n } catch {\n return null\n }\n },\n write: (cache) => {\n try {\n mkdirSync(dataDir, { recursive: true })\n writeFileSync(path, JSON.stringify(cache))\n } catch {\n // A read-only home dir just means the check is not throttled: never worth failing a session over.\n }\n },\n }\n}\n"],"names":["isEnoent","netConnect","_b","_a","stat","resolve","MAX_ASKS"],"mappings":";;;;;;;;;;;;;AAKO,MAAM,oBAAoB;AAG1B,SAAS,SAAS,UAAuB,OAAe,WAAoD;;AACjH,QAAM,UAAU,KAAK,MAAM,qBAAmB,cAAS,WAAT,mBAAiB,gBAAe,SAAS,EAAE;AACzF,SAAO,EAAE,SAAS,YAAY,KAAK,SAAS,aAAa,EAAA;AAC3D;ACJA,SAASA,WAAS,KAAuB;AACvC,UAAQ,2BAA+B,UAAS;AAClD;AASO,SAAS,cAAc,UAAuC,IAAe;AAClF,QAAM,SAAS,QAAQ,gBAAgB,CAAC,KAAK,QAAA,GAAW,iBAAiB,CAAC,GAAG,IAAI,CAAC,SAAS,QAAQ,IAAI,CAAC;AACxG,QAAM,YAAY,CAAC,SACjB,MAAM,KAAK,CAAC,SAAS;AACnB,UAAM,MAAM,SAAS,MAAM,QAAQ,IAAI,CAAC;AACxC,WAAO,QAAQ,QAAQ,CAAC,IAAI,WAAW,KAAK,GAAG,EAAE,KAAK,CAAC,WAAW,GAAG;AAAA,EACvE,CAAC;AAEH,QAAM,WAAW,CAAC,MAAc,SAAgC,MAAM,MAAM,IAAI,EAAE,MAAM,MAAM;AAAA,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AM,EAAE,OAAO,MAAM;AAAA,EAAA;AAEzC,SAAO,KAAK,OAAO,KAAK;AAC1B;AAGA,eAAe,aAAa,MAA+B;AACzD,QAAM,OAAO,WAAW,QAAQ;AAChC,mBAAiB,SAAS,iBAAiB,IAAI,EAAG,MAAK,OAAO,KAAK;AACnE,SAAO,KAAK,OAAO,KAAK;AAC1B;AAEO,SAAS,wBAAqC;AACnD,SAAO;AAAA,IACL,UAAU;AAAA,IACV;AAAA,IACA,QAAQ,CAAC,SAAS,OAAO,MAAM,EAAE,OAAO,MAAM;AAAA,IAC9C,SAAS,CAAC,QAAQ;AAAE,gBAAU,KAAK,EAAE,WAAW,KAAA,CAAM;AAAA,IAAE;AAAA,IACxD,SAAS;AAAA,IACT;AAAA,EAAA;AAEJ;AAGO,SAAS,sBAAsB,SAAiB,WAAW,qBAAuC;AACvG,QAAM,OAAO,KAAK,SAAS,QAAQ;AACnC,SAAO;AAAA,IACL,MAAM,MAAM;AACV,UAAI;AACF,eAAO,iBAAiB,aAAa,MAAM,MAAM,CAAC;AAAA,MACpD,QAAQ;AACN,eAAO;AAAA,MACT;AAAA,IACF;AAAA,IACA,OAAO,CAAC,UAAU;AAChB,UAAI;AACF,kBAAU,SAAS,EAAE,WAAW,KAAA,CAAM;AACtC,sBAAc,MAAM,KAAK,UAAU,KAAK,CAAC;AAAA,MAC3C,QAAQ;AAAA,MAER;AAAA,IACF;AAAA,EAAA;AAEJ;"}
@@ -0,0 +1,20 @@
1
+ import { ConfigStore } from '@buildaharness/runtime';
2
+ /**
3
+ * JSON-file-backed ConfigStore at a single `config.json` path (typically `appPaths(identity).configFile`).
4
+ *
5
+ * save() merges the patch onto whatever's already persisted (never a blind overwrite of
6
+ * unrelated keys) and writes through a temp-file-then-rename so a crash mid-write can never
7
+ * leave a half-written config.json behind. Setting a key to `undefined` in a
8
+ * patch removes it from the persisted file (JSON.stringify drops undefined-valued
9
+ * properties), which is what a settings reset relies on. A corrupt file warns and reads as empty.
10
+ *
11
+ * Concurrent save() calls on the same instance are serialized through an internal queue —
12
+ * a command line may not wait for one command to finish before dispatching
13
+ * the next (e.g. piped stdin with two settings lines back to back), so without this a
14
+ * second save()'s load-modify-write could race the first's: reading stale state before the
15
+ * first's write lands and silently clobbering it, or (with a timestamp-only temp filename)
16
+ * colliding on the exact same temp path within the same millisecond.
17
+ */
18
+ export declare function jsonConfigStore<C extends object>(path: string, opts?: {
19
+ warn?(message: string): void;
20
+ }): ConfigStore<C>;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Handles lines one at a time, in arrival order. A 'line' event does not wait for the previous line's async handler,
3
+ * so piped or pasted input would otherwise run several commands at once.
4
+ */
5
+ export declare function createLineQueue(handle: (line: string) => Promise<void>, onError: (error: unknown) => void): {
6
+ enqueue(line: string): Promise<void>;
7
+ idle(): Promise<void>;
8
+ };
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Node-level network containment for an approved run_shell_command execution — Decision 6 of
3
+ * the internal plan (Phase 4 step 2). This is the network-reachability
4
+ * half of that decision; the env-stripping half already existed in shell.ts's
5
+ * allowlistedEnv(). Deliberately not a real OS sandbox (see the plan's Decision 6 for why that
6
+ * tradeoff was chosen): a minimal loopback-only forward proxy that relays a CONNECT tunnel
7
+ * (HTTPS) or a plain-HTTP proxy request only when its target host matches an entry in the
8
+ * caller-supplied allowlist (exact match or subdomain), and otherwise closes the connection with
9
+ * a 403. The spawned subprocess's HTTP(S)_PROXY env vars are forced to point here, so a tool that
10
+ * honors those (curl, wget, most language HTTP clients) can only reach an allowlisted host. This
11
+ * does NOT stop a tool that opens raw sockets and ignores proxy env vars entirely — that
12
+ * limitation is Decision 6's explicitly accepted tradeoff for a dependency-free, Node-only
13
+ * implementation identical across CLI and desktop.
14
+ */
15
+ export interface NetworkContainmentProxy {
16
+ port: number;
17
+ close: () => Promise<void>;
18
+ }
19
+ /** Starts a new loopback-only proxy scoped to `allowlist`. The caller closes it. */
20
+ export declare function startNetworkContainment(allowlist: readonly string[]): Promise<NetworkContainmentProxy>;
21
+ export declare function getNetworkContainmentProxy(allowlist: readonly string[]): Promise<NetworkContainmentProxy>;
22
+ /** Test-only: drops all cached proxies so a test's allowlist doesn't leak into another test's expectations. */
23
+ export declare function resetNetworkContainmentProxiesForTests(): Promise<void>;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * What a run does when nobody may be there to answer. `decline`: every approval is refused without touching input.
3
+ * `require-tty`: refuse to start unless input is a terminal, instead of failing at the first approval.
4
+ */
5
+ export type NonInteractiveMode = 'decline' | 'require-tty';
6
+ /** Reads the mode from `env[variable]`. An unrecognised value warns and counts as unset, so a typo is never silent. */
7
+ export declare function resolveNonInteractiveMode(env: Record<string, string | undefined>, variable: string, warn?: (message: string) => void): NonInteractiveMode | undefined;
@@ -0,0 +1,8 @@
1
+ import { AppIdentity } from '@buildaharness/runtime';
2
+ /** The folder in the user's home under which every app built from these parts keeps its data. */
3
+ export declare const BUILDAHARNESS_DIR = ".buildaharness";
4
+ /** Where an app keeps its data and settings: `~/.buildaharness/<legacy.dataDirName or id>`. */
5
+ export declare function appPaths(identity: AppIdentity, home?: string): {
6
+ dataDir: string;
7
+ configFile: string;
8
+ };
@@ -0,0 +1,39 @@
1
+ /** The part of a readline interface the prompts use. */
2
+ export interface PromptSource {
3
+ question(query: string, callback: (answer: string) => void): void;
4
+ on(event: 'close', listener: () => void): unknown;
5
+ }
6
+ export interface SelectOption {
7
+ key: string;
8
+ label: string;
9
+ }
10
+ /** `none`: nothing could be read (input closed or broken). Never treat it as consent. */
11
+ export type YesNoAnswer = 'yes' | 'no' | 'none';
12
+ export interface PrompterOptions {
13
+ source: PromptSource;
14
+ /** Prints the prompter's own notices. */
15
+ say(text: string): void;
16
+ /** True: `confirm` and `select` answer "no" without reading input. */
17
+ decline?: boolean;
18
+ declineNotice?: string;
19
+ /** Which typed answers count as yes. Default: `y` or `yes`, any case. */
20
+ isYes?(answer: string): boolean;
21
+ /**
22
+ * What happens to a prompt that is waiting when the input closes. `decline` (default) answers it with "no";
23
+ * `leave` never settles it (nothing is approved, and the process can end with the work unfinished).
24
+ */
25
+ pendingAtClose?: 'decline' | 'leave';
26
+ }
27
+ export interface Prompter {
28
+ confirm(question: string): Promise<boolean>;
29
+ /** Like `confirm`, but tells a typed "no" apart from no answer at all. */
30
+ yesNo(question: string): Promise<YesNoAnswer>;
31
+ /** The trimmed line, or undefined when nothing could be read. Reads input even when `decline` is set. */
32
+ ask(question: string): Promise<string | undefined>;
33
+ /**
34
+ * The chosen option's `key`, typed as the key or its number. Order the options with the safe one LAST: it is the
35
+ * result of any other answer, of no answer, and of `decline`.
36
+ */
37
+ select(question: string, options: readonly SelectOption[]): Promise<string>;
38
+ }
39
+ export declare function createPrompter(o: PrompterOptions): Prompter;
@@ -0,0 +1,33 @@
1
+ import { Approvals, ApproveResult, Job, JobEvent, JobOutcome, Pending } from '@buildaharness/runtime';
2
+ import { CliHost } from './host.js';
3
+ /** One line for an event; a `text` event is a chunk of streamed output and has no newline of its own. */
4
+ export declare function formatJobEvent(event: JobEvent): string;
5
+ /** Prints a job's events until it ends. Ctrl+C asks it to stop after the current step, a second one stops it at once. */
6
+ export declare function runJob<R>(host: CliHost, job: Job<R>): Promise<JobOutcome<R>>;
7
+ /** What is about to be done. Details and warnings are indented so they cannot pass for the program's own lines. */
8
+ export declare function formatPending(pending: Pending): string;
9
+ export declare function formatApproveResult(result: ApproveResult<unknown>): string;
10
+ export type ReviewOutcome =
11
+ /** The person said yes; `result` says what then happened. */
12
+ {
13
+ decision: 'approved';
14
+ result: ApproveResult<unknown>;
15
+ }
16
+ /** The person (or `decline` mode) said no; the action was rejected. */
17
+ | {
18
+ decision: 'declined';
19
+ }
20
+ /** No answer could be read; the action is still pending and nothing was done. */
21
+ | {
22
+ decision: 'unanswered';
23
+ }
24
+ /** There was nothing that could be asked about. */
25
+ | {
26
+ decision: 'not_asked';
27
+ reason: 'unknown' | 'claimed' | 'cannot_be_checked';
28
+ };
29
+ /**
30
+ * Shows a staged action as it is now and applies it only on a yes to that preview. If it changed meanwhile, the new
31
+ * preview is shown and asked about again.
32
+ */
33
+ export declare function reviewApproval(host: CliHost, approvals: Approvals, id: string): Promise<ReviewOutcome>;
@@ -0,0 +1,3 @@
1
+ import { AddressResolver } from '@buildaharness/runtime';
2
+ /** Resolves a host name to all its addresses with the operating system's resolver. */
3
+ export declare function nodeResolver(): AddressResolver;
@@ -0,0 +1,13 @@
1
+ import { UpdateCacheStore, UpdateFiles } from '@buildaharness/runtime';
2
+ /**
3
+ * Replaces the binary at `execPath` with the already-verified file at `newFile` (same directory).
4
+ * Unix: `rename` over the running binary (POSIX lets a still-open inode be replaced). Windows cannot overwrite a running
5
+ * exe, so the current one is renamed aside to `.old` first (cleaned up on the next launch by `cleanupStaleUpdateFiles`),
6
+ * rolling back if the second rename fails.
7
+ */
8
+ export declare function replaceBinary(execPath: string, newFile: string, platform?: string): void;
9
+ /** Removes leftovers of a previous update (the Windows `.old` copy, an interrupted temp download). Never throws. */
10
+ export declare function cleanupStaleUpdateFiles(execPath?: string): void;
11
+ export declare function createNodeUpdateFiles(): UpdateFiles;
12
+ /** The throttle cache as `<dataDir>/<fileName>` (`update-check.json`). */
13
+ export declare function createFileUpdateCache(dataDir: string, fileName?: string): UpdateCacheStore;
@@ -0,0 +1,12 @@
1
+ import { SettingsStore } from '@buildaharness/runtime';
2
+ /**
3
+ * A SettingsStore kept in one JSON file (owner-only, written through a temp file and a rename), for values that must survive a
4
+ * restart: a spending total, a running-job marker, an activity log. Values are what JSON keeps, so a Date comes back as text.
5
+ *
6
+ * Writes of one store object are applied one after the other, so two at once do not lose each other. A second process writing
7
+ * the same file is not coordinated with. A missing file reads as empty; a file that is not a JSON object warns and reads as
8
+ * empty, and the next write replaces it. Writing `undefined` removes the key.
9
+ */
10
+ export declare function fileSettingsStore(path: string, opts?: {
11
+ warn?(message: string): void;
12
+ }): SettingsStore;
@@ -0,0 +1,21 @@
1
+ import { ShellExecutionResult } from '@buildaharness/runtime';
2
+ export interface ShellCommandOptions {
3
+ timeoutMs?: number;
4
+ maxOutputBytes?: number;
5
+ /** Hosts the command may reach through the containment proxy. None by default. */
6
+ networkAllowlist?: readonly string[];
7
+ /** Names of the parent's environment variables passed to the command, instead of PATH, HOME and LANG. */
8
+ env?: readonly string[];
9
+ }
10
+ /**
11
+ * Runs a command in a shell. It asks no one and checks no path: call it only for a command already approved, with an
12
+ * already validated `cwd`. The environment is reduced to an explicit allowlist so a
13
+ * secret like an API key can't leak into the command's environment,
14
+ * plus network-containment.ts's loopback-only proxy forced via HTTP(S)_PROXY (Decision 6 — see
15
+ * networkContainmentEnv's doc comment). A hard timeout SIGKILLs the whole process group (not just
16
+ * the immediate child — `detached: true` + a negative-pid kill reaches anything the shell itself
17
+ * spawned) rather than leaving it running. A non-zero exit code is not a thrown error — it's
18
+ * reported normally, same as a real shell; only a spawn failure (e.g. the shell itself couldn't
19
+ * start) throws.
20
+ */
21
+ export declare function runShellCommand(command: string, cwd: string, options?: ShellCommandOptions): Promise<ShellExecutionResult>;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Text that came from the model, a tool result, a file or a web page must not reach the terminal raw: an
3
+ * embedded escape sequence can clear the screen, rewrite earlier lines (hiding what an approval prompt is
4
+ * really asking), set the window title or write the clipboard (OSC 52). Newlines and tabs survive; everything
5
+ * that could drive the terminal is removed. Plain text is returned unchanged.
6
+ */
7
+ export declare function stripTerminalControls(text: string): string;
8
+ /** Untrusted text as one line: filtered, and newlines and tabs become spaces so it cannot start a line of its own. */
9
+ export declare function oneLine(text: string): string;
10
+ /** Untrusted text as a block: filtered, and every line prefixed so none can pass for the program's own. */
11
+ export declare function indentBlock(text: string, prefix?: string): string;
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@buildaharness/app-node",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Node.js ports for apps built from Build A Harness parts (files, config, shell, command line). The browser-safe parts are in @buildaharness/runtime.",
5
+ "license": "Apache-2.0",
6
+ "homepage": "https://buildaharness.com",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/3IVIS/buildaharness.git",
10
+ "directory": "packages/app-node"
11
+ },
12
+ "keywords": [
13
+ "buildaharness",
14
+ "agent-harness",
15
+ "ai-agent",
16
+ "node"
17
+ ],
18
+ "type": "module",
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "exports": {
23
+ ".": {
24
+ "import": "./dist/index.js",
25
+ "types": "./dist/index.d.ts"
26
+ }
27
+ },
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "scripts": {
32
+ "build": "vite build --config vite.config.lib.ts",
33
+ "test": "vitest run",
34
+ "typecheck": "tsc --noEmit"
35
+ },
36
+ "dependencies": {
37
+ "@buildaharness/runtime": "^0.4.0"
38
+ },
39
+ "devDependencies": {
40
+ "@types/node": "^20.14.0",
41
+ "typescript": "^5.4.5",
42
+ "vite": "^5.3.4",
43
+ "vite-plugin-dts": "^4.5.4",
44
+ "vitest": "^1.6.0"
45
+ }
46
+ }