@openape/apes 0.6.1 → 0.7.2

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,"sources":["../src/shell/orchestrator.ts","../src/shell/grant-dispatch.ts","../src/shell/pty-bridge.ts","../src/shell/repl.ts","../src/shell/multi-line.ts","../src/shell/session.ts"],"sourcesContent":["import { hostname } from 'node:os'\nimport consola from 'consola'\nimport { loadAuth } from '../config.js'\nimport { requestGrantForShellLine } from './grant-dispatch.js'\nimport { PtyBridge } from './pty-bridge.js'\nimport { ShellRepl } from './repl.js'\nimport { ShellSession } from './session.js'\n\n/**\n * Orchestrates the interactive ape-shell session by wiring the user-facing\n * REPL to a persistent bash child via the PtyBridge. Keeps both components\n * decoupled so each can be unit-tested in isolation.\n *\n * Flow per user-entered line:\n * 1. ShellRepl emits onLine with the completed (possibly multi-line) buffer\n * 2. Line goes through the grant flow. If denied: session logs the denial,\n * we surface the reason, and return without touching bash.\n * 3. On approval we enter \"output mode\" (raw stdin passthrough so TUI apps\n * like vim/less/top receive raw keystrokes) and write the line to bash.\n * 4. bash output streams back to stdout live via PtyBridge.onOutput\n * 5. When the marker-bearing PS1 reappears we resolve the pending promise,\n * readline takes back the terminal, and the next prompt is drawn.\n *\n * The orchestrator also owns the lifecycle niceties:\n * - SIGWINCH is forwarded to the pty so TUI apps re-render at the right size\n * - SIGTERM / SIGHUP trigger a clean shutdown (kill bash, restore TTY mode,\n * close the audit session)\n * - An emergency process.on('exit') handler restores the terminal out of\n * raw mode in case a crash left it there\n *\n * Every line is recorded in the audit log via the ShellSession — granted,\n * denied, and done events with seq numbers correlating each event to its\n * parent line within the session.\n */\nexport async function runInteractiveShell(): Promise<void> {\n /**\n * When a line is written into the bash pty, handleLine stashes a\n * resolver here so the PtyBridge's onLineDone can wake it up.\n */\n let pendingResolve: (() => void) | null = null\n let lastExitCode = 0\n let shuttingDown = false\n // Forward reference to the REPL so the bridge's onExit can stop it when\n // bash dies. Assigned after construction below.\n let repl: ShellRepl | null = null\n\n // Spawn the bash child up-front so the REPL can write to it as soon as the\n // first line is accepted. Output from bash goes straight to the terminal.\n const bridge = new PtyBridge(\n {\n onOutput: (chunk) => {\n // Live streaming to the user's terminal. Always written straight\n // through so TUI apps (vim, less, top) get their escape sequences\n // on time.\n process.stdout.write(chunk)\n },\n onLineDone: (frame) => {\n if (pendingResolve) {\n const r = pendingResolve\n pendingResolve = null\n lastExitCode = frame.exitCode\n r()\n }\n },\n onExit: (exitCode) => {\n // bash itself died — typically because the user ran `exit`.\n // Tear down the REPL so run() returns cleanly.\n if (!shuttingDown) {\n process.stdout.write(`\\n[bash exited with code ${exitCode}]\\n`)\n repl?.stop()\n }\n },\n },\n )\n\n await bridge.waitForReady()\n\n const targetHost = hostname()\n const auth = loadAuth()\n const session = new ShellSession({\n host: targetHost,\n requester: auth?.email ?? 'unknown',\n })\n\n repl = new ShellRepl(\n {\n onLine: async (line) => {\n // --- 1. Gate the line through the grant flow BEFORE bash sees it ---\n const grant = await requestGrantForShellLine(line, {\n targetHost,\n approval: 'once',\n })\n\n if (grant.kind === 'denied') {\n session.logLineDenied({ line, reason: grant.reason })\n consola.error(grant.reason)\n return\n }\n\n const seq = session.logLineGranted({\n line,\n grantId: grant.grantId,\n grantMode: grant.mode,\n })\n\n // --- 2. Raw-mode stdin passthrough while bash runs the line ---\n const wasRaw = process.stdin.isTTY && (process.stdin as NodeJS.ReadStream).isRaw\n if (process.stdin.isTTY && !wasRaw)\n (process.stdin as NodeJS.ReadStream).setRawMode(true)\n\n const forward = (chunk: Buffer) => {\n bridge.writeRaw(chunk.toString())\n }\n const rawInputAvailable = process.stdin.isTTY === true\n if (rawInputAvailable)\n process.stdin.on('data', forward)\n\n try {\n await new Promise<void>((resolve) => {\n pendingResolve = resolve\n bridge.writeLine(line)\n })\n }\n finally {\n if (rawInputAvailable) {\n process.stdin.off('data', forward)\n if (!wasRaw && process.stdin.isTTY)\n (process.stdin as NodeJS.ReadStream).setRawMode(false)\n }\n }\n\n session.logLineDone({ seq, exitCode: lastExitCode })\n\n if (lastExitCode !== 0) {\n consola.debug(`(exit ${lastExitCode})`)\n }\n },\n onExit: () => {\n shuttingDown = true\n session.close()\n try {\n bridge.kill()\n }\n catch {}\n },\n },\n )\n\n // SIGWINCH forwarding so TUI apps re-render at the right dimensions.\n const onResize = () => {\n const cols = process.stdout.columns ?? 80\n const rows = process.stdout.rows ?? 24\n try {\n bridge.resize(cols, rows)\n }\n catch {}\n }\n process.stdout.on('resize', onResize)\n\n // Emergency TTY restore — if a crash leaves stdin in raw mode, subsequent\n // terminal input becomes unusable until the user manually runs `reset`.\n // This handler fires on clean exit and on uncaught exceptions.\n const restoreTty = () => {\n if (process.stdin.isTTY && (process.stdin as NodeJS.ReadStream).isRaw) {\n try {\n (process.stdin as NodeJS.ReadStream).setRawMode(false)\n }\n catch {}\n }\n }\n process.on('exit', restoreTty)\n\n // Clean shutdown on termination signals. kill() is idempotent in node-pty,\n // and session.close() swallows audit-log errors internally, so this is safe\n // to call even if already shutting down.\n const gracefulShutdown = () => {\n if (shuttingDown)\n return\n shuttingDown = true\n restoreTty()\n try {\n session.close()\n }\n catch {}\n try {\n bridge.kill()\n }\n catch {}\n try {\n repl?.stop()\n }\n catch {}\n }\n process.on('SIGTERM', gracefulShutdown)\n process.on('SIGHUP', gracefulShutdown)\n\n try {\n await repl.run()\n }\n finally {\n process.stdout.off('resize', onResize)\n process.off('exit', restoreTty)\n process.off('SIGTERM', gracefulShutdown)\n process.off('SIGHUP', gracefulShutdown)\n }\n}\n","import { basename } from 'node:path'\nimport consola from 'consola'\nimport { loadAuth } from '../config.js'\nimport { apiFetch, getGrantsEndpoint } from '../http.js'\nimport {\n createShapesGrant,\n fetchGrantToken,\n findExistingGrant,\n loadOrInstallAdapter,\n parseShellCommand,\n resolveCommand,\n verifyAndConsume,\n waitForGrantStatus,\n} from '../shapes/index.js'\n\n/**\n * Result of attempting to obtain a grant for a shell line. On success the\n * REPL may proceed to execute the line in its persistent bash pty. On\n * failure the caller should surface `reason` and discard the line.\n */\nexport type GrantLineResult =\n | { kind: 'approved', grantId: string, mode: 'adapter' | 'session' }\n | { kind: 'denied', reason: string }\n\n/**\n * Options the orchestrator passes to `requestGrantForShellLine`. They\n * mirror what the `apes run --shell` path reads from its citty args, but\n * come directly from the shell session context instead.\n */\nexport interface GrantLineOptions {\n /** Target host name. Usually `os.hostname()`. */\n targetHost: string\n /** Approval mode — almost always 'once' for interactive shell lines. */\n approval?: 'once' | 'timed' | 'always'\n}\n\n/**\n * Obtain a grant for a shell line so the interactive REPL may execute it\n * against its persistent bash child.\n *\n * Dispatch strategy mirrors the existing one-shot `tryAdapterModeFromShell`\n * flow:\n * 1. Try to resolve the line as an adapter-backed command (structured\n * grant with resource chain / permission).\n * 2. If the adapter path succeeds, reuse an existing matching grant or\n * request a new one, verify + consume it.\n * 3. If the adapter path fails (compound line, no matching adapter,\n * resolve failure) fall back to a generic `ape-shell` session grant\n * for the target host.\n *\n * Returns without executing anything. The caller (the orchestrator)\n * decides how to run the line — typically by writing it to bash's pty.\n */\nexport async function requestGrantForShellLine(\n line: string,\n options: GrantLineOptions,\n): Promise<GrantLineResult> {\n const auth = loadAuth()\n if (!auth) {\n return { kind: 'denied', reason: 'Not logged in. Run `apes login` first.' }\n }\n const idp = auth.idp\n if (!idp) {\n return { kind: 'denied', reason: 'No IdP URL configured. Run `apes login` first.' }\n }\n\n // --- 1. Adapter path ---\n const parsed = parseShellCommand(line)\n if (parsed && !parsed.isCompound) {\n try {\n const loaded = await loadOrInstallAdapter(parsed.executable)\n if (loaded) {\n const normalizedExecutable = basename(parsed.executable)\n const resolved = await resolveCommand(loaded, [normalizedExecutable, ...parsed.argv])\n\n // Try to reuse an existing matching grant first.\n try {\n const existingGrantId = await findExistingGrant(resolved, idp)\n if (existingGrantId) {\n consola.info(`Reusing grant ${existingGrantId} for: ${resolved.detail.display}`)\n const token = await fetchGrantToken(idp, existingGrantId)\n await verifyAndConsume(token, resolved)\n return { kind: 'approved', grantId: existingGrantId, mode: 'adapter' }\n }\n }\n catch (err) {\n consola.debug(`ape-shell: findExistingGrant failed, will request new grant:`, err)\n }\n\n // Request a new adapter-backed grant.\n consola.info(`Requesting grant for: ${resolved.detail.display}`)\n const grant = await createShapesGrant(resolved, {\n idp,\n approval: options.approval ?? 'once',\n reason: `ape-shell: ${resolved.detail.display}`,\n })\n consola.info(`Approve at: ${idp}/grant-approval?grant_id=${grant.id}`)\n\n const status = await waitForGrantStatus(idp, grant.id)\n if (status !== 'approved') {\n return { kind: 'denied', reason: `Grant ${status}` }\n }\n\n const token = await fetchGrantToken(idp, grant.id)\n await verifyAndConsume(token, resolved)\n return { kind: 'approved', grantId: grant.id, mode: 'adapter' }\n }\n }\n catch (err) {\n // Adapter resolution failed — debug-log and fall through to the\n // generic session grant path.\n consola.debug(`ape-shell: adapter resolve failed, falling back to session grant:`, err)\n }\n }\n\n // --- 2. Generic session grant (ape-shell audience) ---\n const grantsUrl = await getGrantsEndpoint(idp)\n\n // Try to reuse an existing timed/always session grant first.\n try {\n const grants = await apiFetch<{ data: Array<{ id: string, status: string, request: { audience: string, target_host: string, grant_type: string } }> }>(\n `${grantsUrl}?requester=${encodeURIComponent(auth.email)}&status=approved&limit=20`,\n )\n const sessionGrant = grants.data.find(g =>\n g.request.audience === 'ape-shell'\n && g.request.target_host === options.targetHost\n && g.request.grant_type !== 'once',\n )\n if (sessionGrant) {\n return { kind: 'approved', grantId: sessionGrant.id, mode: 'session' }\n }\n }\n catch (err) {\n consola.debug(`ape-shell: session grant lookup failed:`, err)\n }\n\n // Request a new session grant. The approver sees the literal shell line.\n consola.info(`Requesting ape-shell session grant on ${options.targetHost}`)\n try {\n const grant = await apiFetch<{ id: string, status: string }>(grantsUrl, {\n method: 'POST',\n body: {\n requester: auth.email,\n target_host: options.targetHost,\n audience: 'ape-shell',\n grant_type: options.approval ?? 'once',\n command: ['bash', '-c', line],\n reason: `Shell session: ${line.slice(0, 100)}`,\n },\n })\n consola.info(`Approve at: ${idp}/grant-approval?grant_id=${grant.id}`)\n\n const maxWait = 300_000\n const interval = 3_000\n const start = Date.now()\n\n while (Date.now() - start < maxWait) {\n const status = await apiFetch<{ status: string }>(`${grantsUrl}/${grant.id}`)\n if (status.status === 'approved')\n return { kind: 'approved', grantId: grant.id, mode: 'session' }\n if (status.status === 'denied' || status.status === 'revoked')\n return { kind: 'denied', reason: `Grant ${status.status}` }\n await new Promise(r => setTimeout(r, interval))\n }\n\n return { kind: 'denied', reason: 'Grant approval timed out after 5 minutes' }\n }\n catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n return { kind: 'denied', reason: `Grant request failed: ${msg}` }\n }\n}\n","import { randomBytes } from 'node:crypto'\nimport type { IPty } from 'node-pty'\nimport * as pty from 'node-pty'\n\n/**\n * Frame returned when the bash child finishes executing a line and is ready\n * for the next one. The `output` is everything bash printed since the last\n * frame, with the marker line stripped.\n */\nexport interface CompletedLineFrame {\n output: string\n exitCode: number\n}\n\n/**\n * Callbacks the PtyBridge delivers to its owner. `onOutput` fires with\n * streaming pty output chunks (marker content already stripped). `onLineDone`\n * fires once per completed shell line with the cumulative output and the\n * exit code extracted from the prompt marker. `onExit` fires when the bash\n * child itself has terminated (user typed `exit`, or the process died).\n */\nexport interface PtyBridgeEvents {\n onOutput: (chunk: string) => void\n onLineDone: (frame: CompletedLineFrame) => void\n onExit: (exitCode: number, signal: number | undefined) => void\n}\n\n/**\n * Wraps a persistent bash child running inside a pty. Each time the frontend\n * feeds a line via `writeLine`, the bridge streams bash's stdout back through\n * `onOutput` until it detects the marker-bearing PS1 — at which point the\n * line is considered complete and `onLineDone` fires with the captured\n * output and the exit code.\n *\n * The marker format embedded in PS1 is:\n * __APES_<random-hex>__:<exit-code>:__END__\n * The leading token is a 32-char random hex so output collisions are\n * effectively impossible. `<exit-code>` is `$?` at prompt render time.\n *\n * The marker itself is stripped from the output stream before it is\n * forwarded to the caller, so consumers never see it on their terminal.\n */\nexport class PtyBridge {\n private readonly marker: string\n /** Compiled once. Captures the exit code in group 1. */\n private readonly markerRegex: RegExp\n private readonly term: IPty\n private readonly events: PtyBridgeEvents\n /** Bytes received since the last completed line. Searched for the marker. */\n private pending = ''\n /**\n * Accumulated output for the current in-flight line. Streams to `onOutput`\n * live as chunks arrive, and is handed to `onLineDone` in full when the\n * marker is matched. Resets at that point.\n */\n private currentLineBuffer = ''\n /** True until bash prints its first marker-prompt. */\n private readyForFirstLine = false\n private awaitingInitialPrompt: ((value: void) => void) | null = null\n\n constructor(events: PtyBridgeEvents, options: { cols?: number, rows?: number, cwd?: string } = {}) {\n this.events = events\n this.marker = randomBytes(16).toString('hex')\n // Example match: __APES_abc123…__:0:__END__\n // The `\\r?\\n?` tolerates line endings around the marker depending on\n // how bash renders PS1 on a fresh line.\n this.markerRegex = new RegExp(\n `__APES_${this.marker}__:(-?\\\\d+):__END__\\\\r?\\\\n?`,\n )\n\n const cols = options.cols ?? process.stdout.columns ?? 80\n const rows = options.rows ?? process.stdout.rows ?? 24\n\n // We spawn bash as `--login -i` so the user's ~/.bash_profile / ~/.bashrc\n // runs and they get their aliases/functions. Trade-off: if the user\n // overrides PS1 in their rcfile, our marker detection breaks. We protect\n // against that by re-exporting PS1 via PROMPT_COMMAND on every prompt.\n //\n // PROMPT_COMMAND also runs `stty -echo` so the pty line discipline stops\n // echoing user input back to us. Without this, every line the frontend\n // writes to the pty gets echoed into the output stream — causing the\n // command to appear twice in the user's terminal (once from readline,\n // once from the pty echo). The frontend already owns its own display of\n // what the user typed; the pty echo is redundant and surprising.\n // Interactive TUI apps (vim/less/top) set their own termios when they\n // start, so they are unaffected.\n this.term = pty.spawn('bash', ['--login', '-i'], {\n name: 'xterm-256color',\n cols,\n rows,\n cwd: options.cwd ?? process.cwd(),\n env: {\n ...process.env,\n // Force our marker PS1 on every prompt and keep pty echo off —\n // both survive .bashrc overrides because PROMPT_COMMAND runs\n // before each prompt.\n PROMPT_COMMAND: `stty -echo 2>/dev/null; PS1='__APES_${this.marker}__:$?:__END__'`,\n // Also set it initially so the very first prompt carries the marker.\n PS1: `__APES_${this.marker}__:$?:__END__`,\n PS2: '> ',\n // Silence bash-specific onboarding that would pollute our output.\n BASH_SILENCE_DEPRECATION_WARNING: '1',\n },\n })\n\n this.term.onData(chunk => this.handleData(chunk))\n this.term.onExit(({ exitCode, signal }) => {\n this.events.onExit(exitCode, signal)\n })\n }\n\n /**\n * Resolves once bash has printed its very first marker-bearing prompt,\n * which means it has finished sourcing ~/.bashrc and is ready to accept\n * input. Callers should await this before sending the first line.\n */\n waitForReady(): Promise<void> {\n if (this.readyForFirstLine)\n return Promise.resolve()\n return new Promise((resolve) => {\n this.awaitingInitialPrompt = resolve\n })\n }\n\n /**\n * Write a shell command line to bash's stdin. The caller must ensure the\n * line has already been approved by the grant flow. The bridge does NOT\n * validate or filter the line.\n */\n writeLine(line: string): void {\n // Trim trailing newlines and always append exactly one, so pasting a\n // multi-line string works naturally.\n const clean = line.replace(/\\r?\\n+$/, '')\n this.term.write(`${clean}\\n`)\n }\n\n /**\n * Raw passthrough write — used for forwarding user keystrokes during\n * interactive output mode (e.g. while vim is running).\n */\n writeRaw(data: string): void {\n this.term.write(data)\n }\n\n /** Resize the underlying pty. Called on SIGWINCH. */\n resize(cols: number, rows: number): void {\n this.term.resize(cols, rows)\n }\n\n /** Kill the bash child. Called on Ctrl-D / shell exit. */\n kill(signal?: string): void {\n this.term.kill(signal)\n }\n\n /** Process id of the bash child, for logging / debugging. */\n get pid(): number {\n return this.term.pid\n }\n\n /** Exposed for tests that want to look at the raw marker. */\n getMarkerForTest(): string {\n return this.marker\n }\n\n // ----- internals -----\n\n private handleData(chunk: string): void {\n this.pending += chunk\n\n // Walk through any complete marker matches. Each marker ends the current\n // in-flight line; the `before` slice is its final output.\n for (;;) {\n const match = this.pending.match(this.markerRegex)\n if (!match || match.index === undefined)\n break\n\n const before = this.pending.slice(0, match.index)\n const exitCode = Number(match[1])\n // Stream the pre-marker portion live (for REPL display) AND fold it\n // into the per-line buffer so the `onLineDone` frame is complete.\n if (before.length > 0) {\n this.currentLineBuffer += before\n if (this.readyForFirstLine)\n this.events.onOutput(before)\n }\n // Drop the matched marker and everything before it from the buffer\n this.pending = this.pending.slice(match.index + match[0].length)\n\n if (!this.readyForFirstLine) {\n // Bootstrap prompt: discard any bash startup noise we captured and\n // signal readiness. onLineDone does NOT fire for the implicit\n // first prompt — that would confuse consumers.\n this.readyForFirstLine = true\n this.currentLineBuffer = ''\n const resolve = this.awaitingInitialPrompt\n this.awaitingInitialPrompt = null\n if (resolve)\n resolve()\n continue\n }\n\n // Real command completion: hand over the accumulated line buffer.\n const frame = { output: this.currentLineBuffer, exitCode }\n this.currentLineBuffer = ''\n this.events.onLineDone(frame)\n }\n\n // No more markers in the buffer. If we're past bootstrap, stream any\n // complete lines that have accumulated so the user sees live output,\n // and keep any partial tail in `pending` in case the marker is still\n // mid-chunk.\n if (!this.readyForFirstLine)\n return\n\n const lastNewline = this.pending.lastIndexOf('\\n')\n if (lastNewline >= 0) {\n const ready = this.pending.slice(0, lastNewline + 1)\n this.pending = this.pending.slice(lastNewline + 1)\n if (ready.length > 0) {\n this.currentLineBuffer += ready\n this.events.onOutput(ready)\n }\n }\n }\n}\n","import { createInterface } from 'node:readline'\nimport type { Interface as ReadlineInterface } from 'node:readline'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport consola from 'consola'\nimport { checkMultiLineStatus } from './multi-line.js'\n\n/**\n * Where the REPL persists its input history across sessions. Lives alongside\n * the existing apes config so we don't add a new top-level dotfile.\n */\nconst HISTORY_FILE = join(homedir(), '.config', 'apes', 'shell-history')\n\n/**\n * Primary and continuation prompts. PS1 shows when the REPL is ready for a\n * fresh command; PS2 shows when bash syntax is incomplete and the user needs\n * to keep typing (e.g., inside a for-loop or heredoc).\n */\nconst PS1 = 'apes$ '\nconst PS2 = '> '\n\n/**\n * Event sink for the REPL. Keeps the loop decoupled from I/O sinks so tests\n * can feed lines and observe outcomes without touching real stdin/stdout.\n */\nexport interface ReplEvents {\n /**\n * Fires when a complete shell line has been accumulated (possibly across\n * multiple input lines via continuation). The handler is responsible for\n * actually running the line — typically by handing it to the grant flow\n * and then to the pty bridge. In M2 this is just logged; the real wiring\n * lands in M3/M4.\n */\n onLine: (line: string) => void | Promise<void>\n\n /**\n * Fires when the REPL is about to exit (user pressed Ctrl-D or called\n * `stop`). Gives owners a chance to tear down resources.\n */\n onExit: () => void | Promise<void>\n}\n\n/**\n * Optional overrides for tests. Real usage defaults to `process.stdin`,\n * `process.stdout`, and the standard history file path.\n */\nexport interface ReplOptions {\n input?: NodeJS.ReadableStream\n output?: NodeJS.WritableStream\n historyFile?: string\n /** Disables the session-start banner — handy in tests. */\n quiet?: boolean\n}\n\n/**\n * Interactive REPL loop for `ape-shell`. Implements the state machine:\n *\n * PROMPT → (line entered) → MULTILINE? → (continue) → PROMPT\n * │\n * └─── complete → emit onLine → PROMPT\n *\n * The loop uses node:readline for line editing, history, and signal\n * handling. Multi-line detection runs a `bash -n` dry-parse on Enter to\n * decide whether to fold the input into a longer buffer or submit it.\n *\n * The REPL does NOT know about pty, grants, or bash internals. Owners wire\n * those in via the `onLine` callback. This keeps M2 independently testable.\n */\nexport class ShellRepl {\n private readonly events: ReplEvents\n private readonly input: NodeJS.ReadableStream\n private readonly output: NodeJS.WritableStream\n private readonly quiet: boolean\n private rl: ReadlineInterface | null = null\n /** Accumulated input across multi-line continuations. */\n private buffer = ''\n /** Whether the REPL has called `stop`. */\n private stopped = false\n\n constructor(events: ReplEvents, options: ReplOptions = {}) {\n this.events = events\n this.input = options.input ?? process.stdin\n this.output = options.output ?? process.stdout\n this.quiet = options.quiet ?? false\n }\n\n /**\n * Start the REPL. Resolves when the user ends the session (Ctrl-D) or\n * `stop()` is called from outside. Errors bubble out of `onLine` and\n * cause the line to be rejected, but do NOT tear down the REPL.\n */\n async run(): Promise<void> {\n if (this.stopped)\n return\n\n this.rl = createInterface({\n input: this.input,\n output: this.output,\n prompt: PS1,\n historySize: 1000,\n // Enable tab completion fallback (file names + history) via default.\n terminal: true,\n })\n\n if (!this.quiet)\n this.writeBanner()\n\n this.safePrompt(PS1)\n\n return new Promise<void>((resolve) => {\n this.rl!.on('line', async (line) => {\n try {\n await this.handleLine(line)\n }\n catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n consola.error(`Shell error: ${msg}`)\n this.resetBuffer()\n this.safePrompt(PS1)\n }\n })\n\n this.rl!.on('SIGINT', () => {\n // Ctrl-C in prompt mode: clear the buffer, draw a new prompt.\n if (this.buffer.length > 0)\n this.output.write('\\n')\n this.resetBuffer()\n this.safePrompt(PS1)\n })\n\n this.rl!.on('close', async () => {\n // Ctrl-D or stop() — we're done.\n this.stopped = true\n await this.events.onExit()\n resolve()\n })\n })\n }\n\n /**\n * Request the REPL to stop cleanly. Equivalent to the user pressing\n * Ctrl-D. Typically called during shutdown or after a fatal error.\n */\n stop(): void {\n if (this.rl)\n this.rl.close()\n }\n\n // ----- internals -----\n\n private writeBanner(): void {\n this.output.write('apes interactive shell\\n')\n this.output.write('Ctrl-D to exit.\\n')\n this.output.write('\\n')\n }\n\n private async handleLine(rawLine: string): Promise<void> {\n // Append the new line to the existing buffer. Use a literal newline so\n // bash sees the multi-line structure correctly on `bash -n`.\n this.buffer = this.buffer.length === 0\n ? rawLine\n : `${this.buffer}\\n${rawLine}`\n\n const status = checkMultiLineStatus(this.buffer)\n\n if (status.kind === 'continue') {\n this.safePrompt(PS2)\n return\n }\n\n if (status.kind === 'error') {\n this.output.write(`${status.message}\\n`)\n this.resetBuffer()\n this.safePrompt(PS1)\n return\n }\n\n // Complete. Hand off to the owner.\n const completeLine = this.buffer\n this.resetBuffer()\n\n // If the buffer was pure whitespace, skip the callback and re-prompt.\n if (completeLine.trim().length === 0) {\n this.safePrompt(PS1)\n return\n }\n\n await this.events.onLine(completeLine)\n\n // Back to prompt mode. Owners of onLine can await and drive their own\n // output before we show the next prompt.\n this.safePrompt(PS1)\n }\n\n /**\n * Draw a prompt, but only if the readline interface is still alive.\n * The onLine callback may have triggered `stop()` (e.g., bash exited),\n * in which case setPrompt/prompt would throw ERR_USE_AFTER_CLOSE.\n */\n private safePrompt(prompt: string): void {\n if (this.stopped || !this.rl)\n return\n try {\n this.rl.setPrompt(prompt)\n this.rl.prompt()\n }\n catch (err) {\n // Swallow ERR_USE_AFTER_CLOSE which races with shutdown.\n const code = (err as NodeJS.ErrnoException)?.code\n if (code !== 'ERR_USE_AFTER_CLOSE')\n throw err\n }\n }\n\n private resetBuffer(): void {\n this.buffer = ''\n }\n}\n\nexport { HISTORY_FILE }\n","import { spawnSync } from 'node:child_process'\n\n/**\n * Result of checking whether a shell command buffer is syntactically\n * complete. The REPL uses this to decide whether to submit the line for\n * execution or to keep reading more lines with a continuation prompt.\n */\nexport type MultiLineStatus =\n | { kind: 'complete' }\n | { kind: 'continue' }\n | { kind: 'error', message: string }\n\n/**\n * Patterns that bash writes to stderr when it encounters a syntax error\n * caused by an incomplete construct (missing `done`, unterminated quote,\n * unclosed `$(` or heredoc, etc.). If any of these patterns match, the\n * buffer is treated as incomplete and the REPL shows a continuation prompt\n * instead of reporting an error.\n */\nconst CONTINUE_PATTERNS: RegExp[] = [\n /syntax error: unexpected end of file/i,\n /unexpected end of file/i,\n /here-document.+delimited by end-of-file/i,\n /unexpected EOF while looking for matching/i,\n]\n\n/**\n * Detects an unterminated here-document in the buffer. `bash -n` accepts\n * these as \"complete\" (it treats end-of-input as the delimiter) so we have\n * to catch them ourselves to match interactive bash's behavior of showing\n * a continuation prompt until the user types the delimiter on its own line.\n *\n * Matches `<<` or `<<-` followed by an optionally-quoted identifier. For\n * each match we scan the remaining lines of the buffer for a line whose\n * content (after leading tabs, which `<<-` strips) equals the delimiter.\n * If no closing line is found, the heredoc is unterminated → continue.\n */\nfunction hasUnterminatedHeredoc(buffer: string): boolean {\n // Match <<-? optional whitespace, optional ' or \" around the word.\n // We deliberately don't try to parse bash quoting fully — this is a\n // best-effort heuristic that catches the common cases.\n const pattern = /<<(-?)\\s*(['\"]?)([A-Z_]\\w*)\\2/gi\n for (const match of buffer.matchAll(pattern)) {\n const stripTabs = match[1] === '-'\n const delimiter = match[3]!\n // Look at every line AFTER the match start\n const afterMatch = buffer.slice((match.index ?? 0) + match[0].length)\n const lines = afterMatch.split('\\n').slice(1) // skip the rest of the opening line\n const terminated = lines.some((line) => {\n const compare = stripTabs ? line.replace(/^\\t+/, '') : line\n return compare === delimiter\n })\n if (!terminated)\n return true\n }\n return false\n}\n\n/**\n * Check whether a (possibly multi-line) shell command buffer forms a\n * complete statement. Runs `bash -n -c <buffer>` in a separate process —\n * `-n` makes bash parse without executing, so there are no side effects.\n *\n * Design note: we spawn bash once per check. That's typically <10ms on\n * modern machines and only happens when the user presses Enter, not per\n * keystroke, so the cost is negligible.\n */\nexport function checkMultiLineStatus(buffer: string): MultiLineStatus {\n if (buffer.trim().length === 0)\n return { kind: 'complete' } // empty line is a no-op, treat as complete\n\n // Heredoc check first — bash -n accepts unterminated heredocs but an\n // interactive shell should ask for more input until the delimiter line.\n if (hasUnterminatedHeredoc(buffer))\n return { kind: 'continue' }\n\n const result = spawnSync('bash', ['-n', '-c', buffer], {\n stdio: ['ignore', 'ignore', 'pipe'],\n encoding: 'utf-8',\n })\n\n if (result.error) {\n // Bash itself couldn't be spawned — treat as a hard error so the REPL\n // can surface it. This should be vanishingly rare.\n return { kind: 'error', message: `Failed to spawn bash for syntax check: ${result.error.message}` }\n }\n\n if (result.status === 0)\n return { kind: 'complete' }\n\n const stderr = result.stderr || ''\n for (const pattern of CONTINUE_PATTERNS) {\n if (pattern.test(stderr))\n return { kind: 'continue' }\n }\n\n // Anything else is a genuine syntax error — caller should show it and\n // reset the buffer instead of accumulating more lines.\n return { kind: 'error', message: stderr.trim() || 'Syntax error' }\n}\n","import { randomBytes } from 'node:crypto'\nimport { appendAuditLog } from '../shapes/index.js'\n\n/**\n * A single interactive ape-shell session. Tracks a stable session id plus a\n * monotonic sequence number so individual lines can be correlated back to\n * their session in the audit log.\n */\nexport class ShellSession {\n readonly id: string\n readonly startedAt: number\n private lineSeq = 0\n\n constructor(options: { host: string, requester: string }) {\n this.id = randomBytes(8).toString('hex')\n this.startedAt = Date.now()\n appendAuditLog({\n action: 'shell-session-start',\n session_id: this.id,\n host: options.host,\n requester: options.requester,\n })\n }\n\n /**\n * Record a granted line that was approved for execution. Called after the\n * grant flow returns approval but before (or right after) bash runs the\n * command. Stores the grant id so the line can be traced back to the\n * specific grant that authorized it.\n */\n logLineGranted(params: {\n line: string\n grantId: string\n grantMode: 'adapter' | 'session'\n }): number {\n const seq = ++this.lineSeq\n appendAuditLog({\n action: 'shell-session-line',\n session_id: this.id,\n seq,\n line: params.line,\n grant_id: params.grantId,\n grant_mode: params.grantMode,\n status: 'executing',\n })\n return seq\n }\n\n /** Record the final exit code of a previously-granted line. */\n logLineDone(params: { seq: number, exitCode: number }): void {\n appendAuditLog({\n action: 'shell-session-line-done',\n session_id: this.id,\n seq: params.seq,\n exit_code: params.exitCode,\n })\n }\n\n /** Record that a line was denied by the grant flow and never reached bash. */\n logLineDenied(params: { line: string, reason: string }): void {\n const seq = ++this.lineSeq\n appendAuditLog({\n action: 'shell-session-line',\n session_id: this.id,\n seq,\n line: params.line,\n status: 'denied',\n reason: params.reason,\n })\n }\n\n /** Record session termination. Fires on clean Ctrl-D or bash death. */\n close(): void {\n appendAuditLog({\n action: 'shell-session-end',\n session_id: this.id,\n duration_ms: Date.now() - this.startedAt,\n lines: this.lineSeq,\n })\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,OAAOA,cAAa;;;ACDpB,SAAS,gBAAgB;AACzB,OAAO,aAAa;AAoDpB,eAAsB,yBACpB,MACA,SAC0B;AAC1B,QAAM,OAAO,SAAS;AACtB,MAAI,CAAC,MAAM;AACT,WAAO,EAAE,MAAM,UAAU,QAAQ,yCAAyC;AAAA,EAC5E;AACA,QAAM,MAAM,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ola","randomBytes","randomBytes","consola"]}
@@ -3,14 +3,16 @@ import {
3
3
  apiFetch,
4
4
  createShapesGrant,
5
5
  fetchGrantToken,
6
- getAuthToken,
7
6
  getGrantsEndpoint,
8
- getIdpUrl,
9
- getRequesterIdentity,
10
7
  loadAdapter,
11
8
  resolveCommand,
12
9
  verifyAndExecute
13
- } from "./chunk-G3Q2TMAI.js";
10
+ } from "./chunk-B32ZQP5K.js";
11
+ import {
12
+ getAuthToken,
13
+ getIdpUrl,
14
+ getRequesterIdentity
15
+ } from "./chunk-TBYYREL6.js";
14
16
 
15
17
  // src/commands/mcp/server.ts
16
18
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
@@ -299,7 +301,7 @@ function registerAdapterTools(server) {
299
301
  async function startMcpServer(transport, port) {
300
302
  const server = new McpServer({
301
303
  name: "apes",
302
- version: true ? "0.6.1" : "0.1.0"
304
+ version: true ? "0.7.2" : "0.1.0"
303
305
  });
304
306
  registerStaticTools(server);
305
307
  registerAdapterTools(server);
@@ -327,4 +329,4 @@ async function startMcpServer(transport, port) {
327
329
  export {
328
330
  startMcpServer
329
331
  };
330
- //# sourceMappingURL=server-FR6GFS3S.js.map
332
+ //# sourceMappingURL=server-GPETT3ON.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/commands/mcp/server.ts","../src/commands/mcp/tools.ts","../src/commands/mcp/adapter-tools.ts"],"sourcesContent":["import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js'\nimport { createServer } from 'node:http'\nimport consola from 'consola'\nimport { registerAdapterTools, registerStaticTools } from './tools'\n\ndeclare const __VERSION__: string\n\nexport async function startMcpServer(transport: 'stdio' | 'sse', port: number) {\n const server = new McpServer({\n name: 'apes',\n version: typeof __VERSION__ !== 'undefined' ? __VERSION__ : '0.1.0',\n })\n\n // Register static tools\n registerStaticTools(server)\n\n // Register adapter-derived tools\n registerAdapterTools(server)\n\n if (transport === 'stdio') {\n const stdioTransport = new StdioServerTransport()\n await server.connect(stdioTransport)\n }\n else if (transport === 'sse') {\n const httpServer = createServer(async (req, res) => {\n if (req.url === '/sse' && req.method === 'GET') {\n const sseTransport = new SSEServerTransport('/messages', res)\n await server.connect(sseTransport)\n }\n else if (req.url === '/messages' && req.method === 'POST') {\n // SSE message handling is done by the transport\n res.writeHead(200)\n res.end()\n }\n else {\n res.writeHead(404)\n res.end('Not found')\n }\n })\n\n httpServer.listen(port, () => {\n consola.info(`MCP SSE server listening on http://localhost:${port}/sse`)\n })\n }\n}\n","import { hostname } from 'node:os'\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport {\n createShapesGrant,\n fetchGrantToken,\n loadAdapter,\n resolveCommand,\n verifyAndExecute,\n} from '../../shapes/index.js'\nimport { z } from 'zod'\nimport { getAuthToken, getIdpUrl, getRequesterIdentity } from '../../config'\nimport { apiFetch, getGrantsEndpoint } from '../../http'\nimport { loadAdapterTools } from './adapter-tools'\n\nexport function registerStaticTools(server: McpServer) {\n server.registerTool('apes.grants.list', {\n description: 'List grants',\n inputSchema: {\n status: z.string().optional().describe('Filter by status: pending, approved, denied, revoked, used'),\n limit: z.string().optional().describe('Max results'),\n },\n }, async ({ status, limit }) => {\n const idp = getIdpUrl()\n if (!idp)\n return { content: [{ type: 'text' as const, text: 'Not configured. Run `apes login` first.' }] }\n\n const grantsUrl = await getGrantsEndpoint(idp)\n const params = new URLSearchParams()\n if (status)\n params.set('status', status)\n if (limit)\n params.set('limit', limit)\n const query = params.toString() ? `?${params.toString()}` : ''\n const response = await apiFetch(`${grantsUrl}${query}`)\n return { content: [{ type: 'text' as const, text: JSON.stringify(response, null, 2) }] }\n })\n\n server.registerTool('apes.grants.request', {\n description: 'Request a grant for a command',\n inputSchema: {\n command: z.string().describe('Command to request permission for'),\n audience: z.string().describe('Service identifier (e.g. escapes, proxy, shapes)'),\n approval: z.string().optional().describe('once, timed, or always'),\n reason: z.string().optional().describe('Reason for the request'),\n },\n }, async ({ command, audience, approval, reason }) => {\n const idp = getIdpUrl()\n const requester = getRequesterIdentity()\n if (!idp || !requester)\n return { content: [{ type: 'text' as const, text: 'Not authenticated. Run `apes login` first.' }] }\n\n const grantsUrl = await getGrantsEndpoint(idp)\n const cmdParts = command.split(' ')\n const grant = await apiFetch<{ id: string, status: string }>(grantsUrl, {\n method: 'POST',\n body: {\n requester,\n target_host: hostname(),\n audience,\n grant_type: approval || 'once',\n command: cmdParts,\n reason: reason || command,\n },\n })\n\n return {\n content: [{\n type: 'text' as const,\n text: JSON.stringify({\n status: 'pending_approval',\n grant_id: grant.id,\n approve_url: `${idp}/grant-approval?grant_id=${grant.id}`,\n message: 'Grant needs approval. Approve via URL or `apes grants approve <id>`, then retry with grant_id.',\n }, null, 2),\n }],\n }\n })\n\n server.registerTool('apes.config.get', {\n description: 'Get apes configuration value',\n inputSchema: {\n key: z.string().describe('Config key: idp, email'),\n },\n }, ({ key }) => {\n if (key === 'idp') {\n const idp = getIdpUrl()\n return { content: [{ type: 'text' as const, text: idp || 'Not configured' }] }\n }\n if (key === 'email') {\n const email = getRequesterIdentity()\n return { content: [{ type: 'text' as const, text: email || 'Not logged in' }] }\n }\n return { content: [{ type: 'text' as const, text: `Unknown key: ${key}` }] }\n })\n\n server.registerTool('apes.explain', {\n description: 'Show what permissions a command would need',\n inputSchema: {\n command: z.array(z.string()).describe('Command as array of strings (e.g. [\"gh\", \"repo\", \"list\"])'),\n adapter: z.string().optional().describe('Explicit adapter TOML path'),\n },\n }, async ({ command, adapter }) => {\n try {\n const loaded = loadAdapter(command[0]!, adapter)\n const resolved = await resolveCommand(loaded, command)\n return {\n content: [{\n type: 'text' as const,\n text: JSON.stringify({\n adapter: resolved.adapter.cli.id,\n operation: resolved.detail.operation_id,\n display: resolved.detail.display,\n permission: resolved.permission,\n resource_chain: resolved.detail.resource_chain,\n exact_command: resolved.detail.constraints?.exact_command ?? false,\n adapter_digest: resolved.digest,\n }, null, 2),\n }],\n }\n }\n catch (err) {\n return { content: [{ type: 'text' as const, text: `Error: ${err instanceof Error ? err.message : String(err)}` }], isError: true }\n }\n })\n\n server.registerTool('apes.adapter.list', {\n description: 'List installed CLI adapters',\n }, () => {\n const tools = loadAdapterTools()\n const adapters = [...new Set(tools.map(t => t.adapterId))]\n return {\n content: [{\n type: 'text' as const,\n text: adapters.length > 0\n ? `Installed adapters: ${adapters.join(', ')}`\n : 'No adapters installed.',\n }],\n }\n })\n\n server.registerTool('apes.fetch', {\n description: 'Make an authenticated HTTP request',\n inputSchema: {\n method: z.string().describe('HTTP method (GET, POST, PUT, DELETE)'),\n url: z.string().describe('URL to fetch'),\n body: z.string().optional().describe('Request body (JSON string)'),\n },\n }, async ({ method, url, body }) => {\n const token = getAuthToken()\n if (!token)\n return { content: [{ type: 'text' as const, text: 'Not authenticated. Run `apes login` first.' }], isError: true }\n\n const response = await fetch(url, {\n method,\n headers: {\n 'Authorization': `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: body || undefined,\n })\n const text = await response.text()\n try {\n return { content: [{ type: 'text' as const, text: JSON.stringify(JSON.parse(text), null, 2) }] }\n }\n catch {\n return { content: [{ type: 'text' as const, text }] }\n }\n })\n}\n\nexport function registerAdapterTools(server: McpServer) {\n const adapterTools = loadAdapterTools()\n\n for (const tool of adapterTools) {\n // Build Zod schema from adapter operation\n const schemaShape: Record<string, z.ZodType> = {\n grant_id: z.string().optional().describe('Grant ID from a previous pending_approval response'),\n }\n\n if (tool.inputSchema && typeof tool.inputSchema === 'object') {\n const props = (tool.inputSchema as { properties?: Record<string, { description?: string }> }).properties\n if (props) {\n for (const [key, val] of Object.entries(props)) {\n schemaShape[key] = z.string().optional().describe(val.description || key)\n }\n }\n }\n\n server.registerTool(tool.name, {\n description: tool.description,\n inputSchema: schemaShape,\n }, async (args) => {\n const idp = getIdpUrl()\n if (!idp)\n return { content: [{ type: 'text' as const, text: 'Not configured. Run `apes login` first.' }], isError: true }\n\n try {\n const loaded = loadAdapter(tool.adapterId)\n const op = loaded.adapter.operations.find(o => o.id === tool.operationId)\n if (!op)\n return { content: [{ type: 'text' as const, text: `Operation ${tool.operationId} not found` }], isError: true }\n\n const argv = [loaded.adapter.cli.executable, ...op.command]\n if (op.positionals) {\n for (const pos of op.positionals) {\n if (args[pos])\n argv.push(String(args[pos]))\n }\n }\n if (op.required_options) {\n for (const opt of op.required_options) {\n const name = opt.replace(/^--/, '')\n if (args[name])\n argv.push(opt, String(args[name]))\n }\n }\n\n const resolved = await resolveCommand(loaded, argv)\n\n if (args.grant_id) {\n const token = await fetchGrantToken(idp, String(args.grant_id))\n await verifyAndExecute(token, resolved)\n return { content: [{ type: 'text' as const, text: 'Command executed successfully.' }] }\n }\n\n const grant = await createShapesGrant(resolved, { idp, approval: 'once' })\n return {\n content: [{\n type: 'text' as const,\n text: JSON.stringify({\n status: 'pending_approval',\n grant_id: grant.id,\n approve_url: `${idp}/grant-approval?grant_id=${grant.id}`,\n message: 'Grant needs approval. Approve, then call this tool again with grant_id.',\n }, null, 2),\n }],\n }\n }\n catch (err) {\n return { content: [{ type: 'text' as const, text: `Error: ${err instanceof Error ? err.message : String(err)}` }], isError: true }\n }\n })\n }\n}\n","import { readdirSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { loadAdapter } from '../../shapes/index.js'\nimport type { ShapesOperation } from '../../shapes/index.js'\n\nexport interface AdapterToolDef {\n name: string\n description: string\n inputSchema: Record<string, unknown>\n adapterId: string\n operationId: string\n}\n\nfunction operationToInputSchema(op: ShapesOperation): Record<string, unknown> {\n const properties: Record<string, unknown> = {}\n const required: string[] = []\n\n if (op.positionals) {\n for (const pos of op.positionals) {\n properties[pos] = { type: 'string', description: `Positional argument: ${pos}` }\n required.push(pos)\n }\n }\n\n if (op.required_options) {\n for (const opt of op.required_options) {\n const name = opt.replace(/^--/, '')\n properties[name] = { type: 'string', description: `Required option: ${opt}` }\n required.push(name)\n }\n }\n\n return {\n type: 'object',\n properties,\n required: required.length > 0 ? required : undefined,\n }\n}\n\nfunction scanAdapterDir(dir: string): string[] {\n try {\n return readdirSync(dir)\n .filter(f => f.endsWith('.toml'))\n .map(f => f.replace('.toml', ''))\n }\n catch {\n return []\n }\n}\n\nexport function loadAdapterTools(): AdapterToolDef[] {\n const tools: AdapterToolDef[] = []\n const seen = new Set<string>()\n\n const adapterDirs = [\n join(process.cwd(), '.openape', 'shapes', 'adapters'),\n join(homedir(), '.openape', 'shapes', 'adapters'),\n '/etc/openape/shapes/adapters',\n ]\n\n for (const dir of adapterDirs) {\n for (const id of scanAdapterDir(dir)) {\n if (seen.has(id))\n continue\n seen.add(id)\n\n try {\n const loaded = loadAdapter(id)\n for (const op of loaded.adapter.operations) {\n tools.push({\n name: `apes.run.${id}.${op.id}`,\n description: op.display || `${id}: ${op.id}`,\n inputSchema: operationToInputSchema(op),\n adapterId: id,\n operationId: op.id,\n })\n }\n }\n catch {\n // Skip adapters that fail to load\n }\n }\n }\n\n return tools\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;AACrC,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;AAC7B,OAAO,aAAa;;;ACJpB,SAAS,gBAAgB;AASzB,SAAS,SAAS;;;ACTlB,SAAS,mBAAmB;AAC5B,SAAS,eAAe;AACxB,SAAS,YAAY;AAYrB,SAAS,uBAAuB,IAA8C;AAC5E,QAAM,aAAsC,CAAC;AAC7C,QAAM,WAAqB,CAAC;AAE5B,MAAI,GAAG,aAAa;AAClB,eAAW,OAAO,GAAG,aAAa;AAChC,iBAAW,GAAG,IAAI,EAAE,MAAM,UAAU,aAAa,wBAAwB,GAAG,GAAG;AAC/E,eAAS,KAAK,GAAG;AAAA,IACnB;AAAA,EACF;AAEA,MAAI,GAAG,kBAAkB;AACvB,eAAW,OAAO,GAAG,kBAAkB;AACrC,YAAM,OAAO,IAAI,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names":[]}
1
+ {"version":3,"sources":["../src/commands/mcp/server.ts","../src/commands/mcp/tools.ts","../src/commands/mcp/adapter-tools.ts"],"sourcesContent":["import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js'\nimport { createServer } from 'node:http'\nimport consola from 'consola'\nimport { registerAdapterTools, registerStaticTools } from './tools'\n\ndeclare const __VERSION__: string\n\nexport async function startMcpServer(transport: 'stdio' | 'sse', port: number) {\n const server = new McpServer({\n name: 'apes',\n version: typeof __VERSION__ !== 'undefined' ? __VERSION__ : '0.1.0',\n })\n\n // Register static tools\n registerStaticTools(server)\n\n // Register adapter-derived tools\n registerAdapterTools(server)\n\n if (transport === 'stdio') {\n const stdioTransport = new StdioServerTransport()\n await server.connect(stdioTransport)\n }\n else if (transport === 'sse') {\n const httpServer = createServer(async (req, res) => {\n if (req.url === '/sse' && req.method === 'GET') {\n const sseTransport = new SSEServerTransport('/messages', res)\n await server.connect(sseTransport)\n }\n else if (req.url === '/messages' && req.method === 'POST') {\n // SSE message handling is done by the transport\n res.writeHead(200)\n res.end()\n }\n else {\n res.writeHead(404)\n res.end('Not found')\n }\n })\n\n httpServer.listen(port, () => {\n consola.info(`MCP SSE server listening on http://localhost:${port}/sse`)\n })\n }\n}\n","import { hostname } from 'node:os'\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport {\n createShapesGrant,\n fetchGrantToken,\n loadAdapter,\n resolveCommand,\n verifyAndExecute,\n} from '../../shapes/index.js'\nimport { z } from 'zod'\nimport { getAuthToken, getIdpUrl, getRequesterIdentity } from '../../config'\nimport { apiFetch, getGrantsEndpoint } from '../../http'\nimport { loadAdapterTools } from './adapter-tools'\n\nexport function registerStaticTools(server: McpServer) {\n server.registerTool('apes.grants.list', {\n description: 'List grants',\n inputSchema: {\n status: z.string().optional().describe('Filter by status: pending, approved, denied, revoked, used'),\n limit: z.string().optional().describe('Max results'),\n },\n }, async ({ status, limit }) => {\n const idp = getIdpUrl()\n if (!idp)\n return { content: [{ type: 'text' as const, text: 'Not configured. Run `apes login` first.' }] }\n\n const grantsUrl = await getGrantsEndpoint(idp)\n const params = new URLSearchParams()\n if (status)\n params.set('status', status)\n if (limit)\n params.set('limit', limit)\n const query = params.toString() ? `?${params.toString()}` : ''\n const response = await apiFetch(`${grantsUrl}${query}`)\n return { content: [{ type: 'text' as const, text: JSON.stringify(response, null, 2) }] }\n })\n\n server.registerTool('apes.grants.request', {\n description: 'Request a grant for a command',\n inputSchema: {\n command: z.string().describe('Command to request permission for'),\n audience: z.string().describe('Service identifier (e.g. escapes, proxy, shapes)'),\n approval: z.string().optional().describe('once, timed, or always'),\n reason: z.string().optional().describe('Reason for the request'),\n },\n }, async ({ command, audience, approval, reason }) => {\n const idp = getIdpUrl()\n const requester = getRequesterIdentity()\n if (!idp || !requester)\n return { content: [{ type: 'text' as const, text: 'Not authenticated. Run `apes login` first.' }] }\n\n const grantsUrl = await getGrantsEndpoint(idp)\n const cmdParts = command.split(' ')\n const grant = await apiFetch<{ id: string, status: string }>(grantsUrl, {\n method: 'POST',\n body: {\n requester,\n target_host: hostname(),\n audience,\n grant_type: approval || 'once',\n command: cmdParts,\n reason: reason || command,\n },\n })\n\n return {\n content: [{\n type: 'text' as const,\n text: JSON.stringify({\n status: 'pending_approval',\n grant_id: grant.id,\n approve_url: `${idp}/grant-approval?grant_id=${grant.id}`,\n message: 'Grant needs approval. Approve via URL or `apes grants approve <id>`, then retry with grant_id.',\n }, null, 2),\n }],\n }\n })\n\n server.registerTool('apes.config.get', {\n description: 'Get apes configuration value',\n inputSchema: {\n key: z.string().describe('Config key: idp, email'),\n },\n }, ({ key }) => {\n if (key === 'idp') {\n const idp = getIdpUrl()\n return { content: [{ type: 'text' as const, text: idp || 'Not configured' }] }\n }\n if (key === 'email') {\n const email = getRequesterIdentity()\n return { content: [{ type: 'text' as const, text: email || 'Not logged in' }] }\n }\n return { content: [{ type: 'text' as const, text: `Unknown key: ${key}` }] }\n })\n\n server.registerTool('apes.explain', {\n description: 'Show what permissions a command would need',\n inputSchema: {\n command: z.array(z.string()).describe('Command as array of strings (e.g. [\"gh\", \"repo\", \"list\"])'),\n adapter: z.string().optional().describe('Explicit adapter TOML path'),\n },\n }, async ({ command, adapter }) => {\n try {\n const loaded = loadAdapter(command[0]!, adapter)\n const resolved = await resolveCommand(loaded, command)\n return {\n content: [{\n type: 'text' as const,\n text: JSON.stringify({\n adapter: resolved.adapter.cli.id,\n operation: resolved.detail.operation_id,\n display: resolved.detail.display,\n permission: resolved.permission,\n resource_chain: resolved.detail.resource_chain,\n exact_command: resolved.detail.constraints?.exact_command ?? false,\n adapter_digest: resolved.digest,\n }, null, 2),\n }],\n }\n }\n catch (err) {\n return { content: [{ type: 'text' as const, text: `Error: ${err instanceof Error ? err.message : String(err)}` }], isError: true }\n }\n })\n\n server.registerTool('apes.adapter.list', {\n description: 'List installed CLI adapters',\n }, () => {\n const tools = loadAdapterTools()\n const adapters = [...new Set(tools.map(t => t.adapterId))]\n return {\n content: [{\n type: 'text' as const,\n text: adapters.length > 0\n ? `Installed adapters: ${adapters.join(', ')}`\n : 'No adapters installed.',\n }],\n }\n })\n\n server.registerTool('apes.fetch', {\n description: 'Make an authenticated HTTP request',\n inputSchema: {\n method: z.string().describe('HTTP method (GET, POST, PUT, DELETE)'),\n url: z.string().describe('URL to fetch'),\n body: z.string().optional().describe('Request body (JSON string)'),\n },\n }, async ({ method, url, body }) => {\n const token = getAuthToken()\n if (!token)\n return { content: [{ type: 'text' as const, text: 'Not authenticated. Run `apes login` first.' }], isError: true }\n\n const response = await fetch(url, {\n method,\n headers: {\n 'Authorization': `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: body || undefined,\n })\n const text = await response.text()\n try {\n return { content: [{ type: 'text' as const, text: JSON.stringify(JSON.parse(text), null, 2) }] }\n }\n catch {\n return { content: [{ type: 'text' as const, text }] }\n }\n })\n}\n\nexport function registerAdapterTools(server: McpServer) {\n const adapterTools = loadAdapterTools()\n\n for (const tool of adapterTools) {\n // Build Zod schema from adapter operation\n const schemaShape: Record<string, z.ZodType> = {\n grant_id: z.string().optional().describe('Grant ID from a previous pending_approval response'),\n }\n\n if (tool.inputSchema && typeof tool.inputSchema === 'object') {\n const props = (tool.inputSchema as { properties?: Record<string, { description?: string }> }).properties\n if (props) {\n for (const [key, val] of Object.entries(props)) {\n schemaShape[key] = z.string().optional().describe(val.description || key)\n }\n }\n }\n\n server.registerTool(tool.name, {\n description: tool.description,\n inputSchema: schemaShape,\n }, async (args) => {\n const idp = getIdpUrl()\n if (!idp)\n return { content: [{ type: 'text' as const, text: 'Not configured. Run `apes login` first.' }], isError: true }\n\n try {\n const loaded = loadAdapter(tool.adapterId)\n const op = loaded.adapter.operations.find(o => o.id === tool.operationId)\n if (!op)\n return { content: [{ type: 'text' as const, text: `Operation ${tool.operationId} not found` }], isError: true }\n\n const argv = [loaded.adapter.cli.executable, ...op.command]\n if (op.positionals) {\n for (const pos of op.positionals) {\n if (args[pos])\n argv.push(String(args[pos]))\n }\n }\n if (op.required_options) {\n for (const opt of op.required_options) {\n const name = opt.replace(/^--/, '')\n if (args[name])\n argv.push(opt, String(args[name]))\n }\n }\n\n const resolved = await resolveCommand(loaded, argv)\n\n if (args.grant_id) {\n const token = await fetchGrantToken(idp, String(args.grant_id))\n await verifyAndExecute(token, resolved)\n return { content: [{ type: 'text' as const, text: 'Command executed successfully.' }] }\n }\n\n const grant = await createShapesGrant(resolved, { idp, approval: 'once' })\n return {\n content: [{\n type: 'text' as const,\n text: JSON.stringify({\n status: 'pending_approval',\n grant_id: grant.id,\n approve_url: `${idp}/grant-approval?grant_id=${grant.id}`,\n message: 'Grant needs approval. Approve, then call this tool again with grant_id.',\n }, null, 2),\n }],\n }\n }\n catch (err) {\n return { content: [{ type: 'text' as const, text: `Error: ${err instanceof Error ? err.message : String(err)}` }], isError: true }\n }\n })\n }\n}\n","import { readdirSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { loadAdapter } from '../../shapes/index.js'\nimport type { ShapesOperation } from '../../shapes/index.js'\n\nexport interface AdapterToolDef {\n name: string\n description: string\n inputSchema: Record<string, unknown>\n adapterId: string\n operationId: string\n}\n\nfunction operationToInputSchema(op: ShapesOperation): Record<string, unknown> {\n const properties: Record<string, unknown> = {}\n const required: string[] = []\n\n if (op.positionals) {\n for (const pos of op.positionals) {\n properties[pos] = { type: 'string', description: `Positional argument: ${pos}` }\n required.push(pos)\n }\n }\n\n if (op.required_options) {\n for (const opt of op.required_options) {\n const name = opt.replace(/^--/, '')\n properties[name] = { type: 'string', description: `Required option: ${opt}` }\n required.push(name)\n }\n }\n\n return {\n type: 'object',\n properties,\n required: required.length > 0 ? required : undefined,\n }\n}\n\nfunction scanAdapterDir(dir: string): string[] {\n try {\n return readdirSync(dir)\n .filter(f => f.endsWith('.toml'))\n .map(f => f.replace('.toml', ''))\n }\n catch {\n return []\n }\n}\n\nexport function loadAdapterTools(): AdapterToolDef[] {\n const tools: AdapterToolDef[] = []\n const seen = new Set<string>()\n\n const adapterDirs = [\n join(process.cwd(), '.openape', 'shapes', 'adapters'),\n join(homedir(), '.openape', 'shapes', 'adapters'),\n '/etc/openape/shapes/adapters',\n ]\n\n for (const dir of adapterDirs) {\n for (const id of scanAdapterDir(dir)) {\n if (seen.has(id))\n continue\n seen.add(id)\n\n try {\n const loaded = loadAdapter(id)\n for (const op of loaded.adapter.operations) {\n tools.push({\n name: `apes.run.${id}.${op.id}`,\n description: op.display || `${id}: ${op.id}`,\n inputSchema: operationToInputSchema(op),\n adapterId: id,\n operationId: op.id,\n })\n }\n }\n catch {\n // Skip adapters that fail to load\n }\n }\n }\n\n return tools\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;AACrC,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;A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UAAM,aAAa,aAAa,OAAO,KAAK,QAAQ;AAClD,UAAI,IAAI,QAAQ,UAAU,IAAI,WAAW,OAAO;AAC9C,cAAM,eAAe,IAAI,mBAAmB,aAAa,GAAG;AAC5D,cAAM,OAAO,QAAQ,YAAY;AAAA,MACnC,WACS,IAAI,QAAQ,eAAe,IAAI,WAAW,QAAQ;AAEzD,YAAI,UAAU,GAAG;AACjB,YAAI,IAAI;AAAA,MACV,OACK;AACH,YAAI,UAAU,GAAG;AACjB,YAAI,IAAI,WAAW;AAAA,MACrB;AAAA,IACF,CAAC;AAED,eAAW,OAAO,MAAM,MAAM;AAC5B,cAAQ,KAAK,gDAAgD,IAAI,MAAM;AAAA,IACzE,CAAC;AAAA,EACH;AACF;","names":[]}
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ loadEd25519PrivateKey,
4
+ readPublicKeyComment
5
+ } from "./chunk-ION3CWD5.js";
6
+ export {
7
+ loadEd25519PrivateKey,
8
+ readPublicKeyComment
9
+ };
10
+ //# sourceMappingURL=ssh-key-YBNNG5K5.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openape/apes",
3
- "version": "0.6.1",
3
+ "version": "0.7.2",
4
4
  "turbo": {
5
5
  "tags": [
6
6
  "publishable"
@@ -20,6 +20,7 @@
20
20
  },
21
21
  "files": [
22
22
  "dist",
23
+ "scripts",
23
24
  "README.md"
24
25
  ],
25
26
  "dependencies": {
@@ -27,6 +28,7 @@
27
28
  "citty": "^0.1.6",
28
29
  "consola": "^3.4.2",
29
30
  "giget": "^2.0.0",
31
+ "node-pty": "^1.1.0",
30
32
  "shell-quote": "^1.8.3",
31
33
  "zod": "^4.3.6",
32
34
  "@openape/core": "0.12.0",
@@ -58,6 +60,7 @@
58
60
  "lint": "eslint .",
59
61
  "typecheck": "tsc --noEmit",
60
62
  "test": "vitest run --coverage",
61
- "test:coverage": "vitest run --coverage"
63
+ "test:coverage": "vitest run --coverage",
64
+ "postinstall": "node scripts/fix-node-pty-perms.mjs"
62
65
  }
63
66
  }
@@ -0,0 +1,103 @@
1
+ #!/bin/bash
2
+ # -----------------------------------------------------------------------------
3
+ # ape-shell login-shell wrapper
4
+ # -----------------------------------------------------------------------------
5
+ #
6
+ # The `@openape/apes` CLI is a Node.js script with a `#!/usr/bin/env node`
7
+ # shebang. When `ape-shell` is set as a user's login shell via `chsh`, the
8
+ # kernel invokes it BEFORE any rc file has run — so only the system default
9
+ # PATH is visible, which typically does NOT include Homebrew or nvm paths.
10
+ # The shebang then fails with:
11
+ #
12
+ # env: node: No such file or directory
13
+ #
14
+ # This wrapper is the actual file pointed at by `chsh` and by the
15
+ # `/usr/local/bin/ape-shell` symlink. It:
16
+ #
17
+ # 1. Prepends known node install locations to PATH (Homebrew, nvm)
18
+ # 2. Sets APES_SHELL_WRAPPER=1 so the CLI knows it was invoked via this
19
+ # wrapper (because argv[0]/argv[1] inspection gets clobbered when we
20
+ # exec Node through the wrapper)
21
+ # 3. Exec's node with the real dist/cli.js path, preserving the original
22
+ # argv[0] via `exec -a "$0"` so login-shell detection ("-ape-shell"
23
+ # prefix) still works inside the CLI
24
+ #
25
+ # To install, point a symlink at this file:
26
+ #
27
+ # sudo ln -sf /path/to/ape-shell-wrapper.sh /usr/local/bin/ape-shell
28
+ # sudo chsh -s /usr/local/bin/ape-shell <user>
29
+ #
30
+ # You can override the node binary via APES_SHELL_NODE, and the CLI entry
31
+ # point via APES_SHELL_CLI_JS, for environments where the defaults don't
32
+ # apply.
33
+ # -----------------------------------------------------------------------------
34
+
35
+ set -e
36
+
37
+ # Known node install locations searched in order. The first one found wins.
38
+ # Users with exotic setups can override via APES_SHELL_NODE env var.
39
+ _node_candidates=(
40
+ "${APES_SHELL_NODE:-}"
41
+ "/opt/homebrew/bin/node"
42
+ "/usr/local/bin/node"
43
+ "/usr/bin/node"
44
+ )
45
+
46
+ _node_bin=""
47
+ for candidate in "${_node_candidates[@]}"; do
48
+ if [ -n "$candidate" ] && [ -x "$candidate" ]; then
49
+ _node_bin="$candidate"
50
+ break
51
+ fi
52
+ done
53
+
54
+ if [ -z "$_node_bin" ]; then
55
+ echo "ape-shell: no node binary found. Install Node.js or set APES_SHELL_NODE." >&2
56
+ exit 127
57
+ fi
58
+
59
+ # Locate the CLI JS. Default: sibling of this wrapper script via a known
60
+ # relative path (assumes the wrapper lives in packages/apes/scripts). Can be
61
+ # overridden via APES_SHELL_CLI_JS for production installs where the paths
62
+ # might differ.
63
+ #
64
+ # Symlink resolution: when the wrapper is installed as a symlink (e.g.
65
+ # /usr/local/bin/ape-shell → /path/to/packages/apes/scripts/ape-shell-wrapper.sh)
66
+ # BASH_SOURCE[0] points at the symlink, not the real file. We must walk the
67
+ # symlink chain before computing the relative `../dist/cli.js` path, otherwise
68
+ # it ends up as `/usr/local/bin/../dist/cli.js` = `/usr/local/dist/cli.js`
69
+ # which doesn't exist. macOS's readlink lacks `-f`, so use the portable
70
+ # loop idiom.
71
+ if [ -z "${APES_SHELL_CLI_JS:-}" ]; then
72
+ _source="${BASH_SOURCE[0]}"
73
+ while [ -L "$_source" ]; do
74
+ _target="$(readlink "$_source")"
75
+ case "$_target" in
76
+ /*) _source="$_target" ;;
77
+ *) _source="$(cd -P "$(dirname "$_source")" >/dev/null && pwd)/$_target" ;;
78
+ esac
79
+ done
80
+ _wrapper_dir="$(cd -P "$(dirname "$_source")" >/dev/null && pwd)"
81
+ _cli_js="$_wrapper_dir/../dist/cli.js"
82
+ else
83
+ _cli_js="$APES_SHELL_CLI_JS"
84
+ fi
85
+
86
+ if [ ! -f "$_cli_js" ]; then
87
+ echo "ape-shell: cli.js not found at $_cli_js. Set APES_SHELL_CLI_JS to override." >&2
88
+ exit 127
89
+ fi
90
+
91
+ # Prepend common node install dirs to PATH so anything spawned inside the
92
+ # shell (or by the interactive REPL's bash child) can also find node.
93
+ export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"
94
+
95
+ # Signal to the CLI that it was invoked via this wrapper, so invocation-mode
96
+ # detection can fall back to this hint when argv-based detection fails (the
97
+ # argv[1] basename check becomes `cli.js` once we exec node directly).
98
+ export APES_SHELL_WRAPPER=1
99
+
100
+ # exec -a preserves the original argv[0] that login/sshd/su gave us — notably
101
+ # the leading "-" prefix for a login shell. The CLI still sees it via
102
+ # process.argv0, so its login-shell detection keeps working.
103
+ exec -a "$0" "$_node_bin" "$_cli_js" "$@"
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Workaround for pnpm 10 losing execute permissions on `spawn-helper`
4
+ * binaries shipped in node-pty prebuilds.
5
+ *
6
+ * Without exec bit, `pty.spawn(...)` fails at runtime with
7
+ * Error: posix_spawnp failed.
8
+ *
9
+ * This script runs after `pnpm install` and chmods the helper for every
10
+ * platform's prebuild directory that it can find. Missing directories are
11
+ * ignored silently so it's safe to run on any host.
12
+ */
13
+ import { chmodSync, existsSync } from 'node:fs'
14
+ import { createRequire } from 'node:module'
15
+ import { dirname, join } from 'node:path'
16
+
17
+ const require = createRequire(import.meta.url)
18
+
19
+ let ptyRoot
20
+ try {
21
+ ptyRoot = dirname(require.resolve('node-pty/package.json'))
22
+ }
23
+ catch {
24
+ // node-pty not installed yet (prepare runs before install in some flows) — nothing to do.
25
+ process.exit(0)
26
+ }
27
+
28
+ const platforms = ['darwin-arm64', 'darwin-x64', 'linux-x64', 'linux-arm64']
29
+ for (const platform of platforms) {
30
+ const helper = join(ptyRoot, 'prebuilds', platform, 'spawn-helper')
31
+ if (existsSync(helper)) {
32
+ try {
33
+ chmodSync(helper, 0o755)
34
+ }
35
+ catch (err) {
36
+ console.warn(`[fix-node-pty-perms] failed to chmod ${helper}:`, err instanceof Error ? err.message : String(err))
37
+ }
38
+ }
39
+ }