@openape/apes 0.7.2 → 0.9.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.
- package/dist/{auth-lock-SRUFWJC3.js → auth-lock-6U2G75S6.js} +2 -2
- package/dist/{chunk-TBYYREL6.js → chunk-AZVY3X7Q.js} +13 -1
- package/dist/chunk-AZVY3X7Q.js.map +1 -0
- package/dist/chunk-LSKHTHUY.js +50 -0
- package/dist/chunk-LSKHTHUY.js.map +1 -0
- package/dist/{chunk-B32ZQP5K.js → chunk-UQ673USC.js} +31 -6
- package/dist/chunk-UQ673USC.js.map +1 -0
- package/dist/cli.js +455 -207
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +9 -0
- package/dist/index.js +2 -2
- package/dist/{orchestrator-JAMWD6DD.js → orchestrator-GPNL543L.js} +135 -7
- package/dist/orchestrator-GPNL543L.js.map +1 -0
- package/dist/{server-GPETT3ON.js → server-FFOPFICW.js} +4 -4
- package/package.json +1 -1
- package/dist/chunk-B32ZQP5K.js.map +0 -1
- package/dist/chunk-TBYYREL6.js.map +0 -1
- package/dist/orchestrator-JAMWD6DD.js.map +0 -1
- /package/dist/{auth-lock-SRUFWJC3.js.map → auth-lock-6U2G75S6.js.map} +0 -0
- /package/dist/{server-GPETT3ON.js.map → server-FFOPFICW.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/http.ts","../src/shapes/adapters.ts","../src/shapes/toml.ts","../src/shapes/audit.ts","../src/shapes/installer.ts","../src/shapes/registry.ts","../src/shapes/shell-parser.ts","../src/shapes/capabilities.ts","../src/shapes/parser.ts","../src/shapes/commands/explain.ts","../src/shapes/grants.ts","../src/shapes/config.ts","../src/shapes/http.ts","../src/shapes/request-builders.ts"],"sourcesContent":["import consola from 'consola'\nimport { getAuthToken, getIdpUrl, loadAuth, loadConfig, saveAuth } from './config'\n\nconst debug = process.argv.includes('--debug')\n\nexport class ApiError extends Error {\n constructor(public statusCode: number, message: string, public problemDetails?: Record<string, unknown>) {\n super(message)\n this.name = 'ApiError'\n }\n}\n\n// OIDC Discovery cache (one-time per CLI invocation)\nconst _discoveryCache: Record<string, Record<string, unknown>> = {}\n\nexport async function discoverEndpoints(idpUrl: string): Promise<Record<string, unknown>> {\n if (_discoveryCache[idpUrl]) {\n return _discoveryCache[idpUrl]\n }\n\n try {\n const response = await fetch(`${idpUrl}/.well-known/openid-configuration`)\n if (response.ok) {\n const data = await response.json() as Record<string, unknown>\n _discoveryCache[idpUrl] = data\n return data\n }\n }\n catch {}\n\n // Return empty if discovery fails (graceful degradation)\n _discoveryCache[idpUrl] = {}\n return {}\n}\n\nexport async function getGrantsEndpoint(idpUrl: string): Promise<string> {\n const disco = await discoverEndpoints(idpUrl)\n return (disco.openape_grants_endpoint as string) || `${idpUrl}/api/grants`\n}\n\nexport async function getAgentChallengeEndpoint(idpUrl: string): Promise<string> {\n const disco = await discoverEndpoints(idpUrl)\n return (disco.ddisa_agent_challenge_endpoint as string) || `${idpUrl}/api/agent/challenge`\n}\n\nexport async function getAgentAuthenticateEndpoint(idpUrl: string): Promise<string> {\n const disco = await discoverEndpoints(idpUrl)\n return (disco.ddisa_agent_authenticate_endpoint as string) || `${idpUrl}/api/agent/authenticate`\n}\n\nexport async function getDelegationsEndpoint(idpUrl: string): Promise<string> {\n const disco = await discoverEndpoints(idpUrl)\n return (disco.openape_delegations_endpoint as string) || `${idpUrl}/api/delegations`\n}\n\n/**\n * Re-authenticate an agent using Ed25519 challenge-response.\n * Called automatically when the token is expired.\n */\nasync function refreshAgentToken(): Promise<string | null> {\n const auth = loadAuth()\n if (!auth)\n return null\n\n const config = loadConfig()\n const keyPath = config.agent?.key\n if (!keyPath)\n return null\n\n try {\n const { readFileSync } = await import('node:fs')\n const { sign } = await import('node:crypto')\n const { homedir } = await import('node:os')\n const { loadEd25519PrivateKey } = await import('./ssh-key.js')\n\n const resolved = keyPath.replace(/^~/, homedir())\n const keyContent = readFileSync(resolved, 'utf-8')\n const privateKey = loadEd25519PrivateKey(keyContent)\n\n const challengeUrl = await getAgentChallengeEndpoint(auth.idp)\n const challengeResp = await fetch(challengeUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ agent_id: auth.email }),\n })\n\n if (!challengeResp.ok)\n return null\n\n const { challenge } = await challengeResp.json() as { challenge: string }\n const { Buffer } = await import('node:buffer')\n const signature = sign(null, Buffer.from(challenge), privateKey).toString('base64')\n\n const authenticateUrl = await getAgentAuthenticateEndpoint(auth.idp)\n const authResp = await fetch(authenticateUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ agent_id: auth.email, challenge, signature }),\n })\n\n if (!authResp.ok)\n return null\n\n const { token, expires_in } = await authResp.json() as { token: string, expires_in: number }\n\n saveAuth({\n ...auth,\n access_token: token,\n expires_at: Math.floor(Date.now() / 1000) + (expires_in || 3600),\n })\n\n if (debug) {\n consola.debug('Token refreshed via Ed25519 challenge-response')\n }\n\n return token\n }\n catch {\n return null\n }\n}\n\n/**\n * Refresh an OAuth2 access token using a stored refresh_token. Used for\n * PKCE/browser login sessions where no Ed25519 agent key is configured.\n *\n * Serialized via a file lock so concurrent apes/ape-shell invocations don't\n * both consume the same rotating refresh token (which would revoke the\n * entire family server-side).\n */\nasync function refreshOAuthToken(): Promise<string | null> {\n const auth = loadAuth()\n if (!auth?.refresh_token)\n return null\n\n const { acquireAuthLock, releaseAuthLock } = await import('./auth-lock.js')\n const lock = await acquireAuthLock({ timeoutMs: 5000 })\n if (!lock) {\n // Another process is refreshing. It should have updated auth.json by now;\n // re-read and return whatever fresh token is there (may still be null).\n return getAuthToken()\n }\n\n try {\n // Re-read auth.json inside the lock — another holder may already have\n // refreshed while we were waiting, in which case we reuse the new token.\n const latest = loadAuth()\n if (latest?.expires_at && Date.now() / 1000 < latest.expires_at - 30)\n return latest.access_token\n\n const activeRefreshToken = latest?.refresh_token ?? auth.refresh_token\n if (!activeRefreshToken)\n return null\n\n const disco = await discoverEndpoints(auth.idp)\n const tokenEndpoint = (disco.token_endpoint as string) || `${auth.idp}/token`\n\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: activeRefreshToken,\n })\n\n const resp = await fetch(tokenEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n })\n\n if (!resp.ok) {\n // Family may have been revoked server-side — clear refresh_token to\n // prevent an infinite retry loop on every subsequent apes invocation.\n if (resp.status === 400 || resp.status === 401) {\n const base = latest ?? auth\n saveAuth({ ...base, refresh_token: undefined })\n }\n return null\n }\n\n const tokens = await resp.json() as {\n access_token: string\n refresh_token?: string\n expires_in?: number\n }\n\n const base = latest ?? auth\n saveAuth({\n ...base,\n access_token: tokens.access_token,\n refresh_token: tokens.refresh_token ?? base.refresh_token,\n expires_at: Math.floor(Date.now() / 1000) + (tokens.expires_in || 300),\n })\n\n if (debug)\n consola.debug('Token refreshed via OAuth refresh_token')\n\n return tokens.access_token\n }\n finally {\n await releaseAuthLock(lock)\n }\n}\n\nexport async function apiFetch<T = unknown>(\n path: string,\n options: {\n method?: string\n body?: unknown\n idp?: string\n token?: string\n } = {},\n): Promise<T> {\n let token = options.token || getAuthToken()\n\n // Auto-refresh: priority (1) ed25519 agent key, (2) OAuth refresh_token.\n // Agent-key first because it is concurrency-safe — every challenge is\n // independent server-side, so parallel ape-shell spawns don't race.\n if (!token) {\n token = await refreshAgentToken()\n if (!token)\n token = await refreshOAuthToken()\n }\n\n if (!token) {\n throw new Error('Not authenticated (token expired). Run `apes login` first.')\n }\n\n let url: string\n if (path.startsWith('http')) {\n url = path\n }\n else {\n const idp = options.idp || getIdpUrl()\n if (!idp) {\n throw new Error('No IdP URL configured. Run `apes login` first or pass --idp.')\n }\n url = `${idp}${path}`\n }\n const method = options.method || 'GET'\n const headers: Record<string, string> = {\n 'Authorization': `Bearer ${token}`,\n 'Content-Type': 'application/json',\n }\n\n if (debug) {\n consola.debug(`${method} ${url}`)\n consola.debug(`Token: ${token.substring(0, 20)}...${token.substring(token.length - 10)}`)\n }\n\n const response = await fetch(url, {\n method,\n headers,\n body: options.body ? JSON.stringify(options.body) : undefined,\n })\n\n if (debug) {\n consola.debug(`Response: ${response.status} ${response.statusText}`)\n }\n\n if (!response.ok) {\n const contentType = response.headers.get('content-type') || ''\n\n // Parse RFC 7807 Problem Details\n if (contentType.includes('application/problem+json') || contentType.includes('application/json')) {\n try {\n const problem = await response.json() as Record<string, unknown>\n const message = (problem.detail as string) || (problem.title as string) || (problem.statusMessage as string) || (problem.message as string) || `${response.status} ${response.statusText}`\n throw new ApiError(response.status, message, problem)\n }\n catch (e) {\n if (e instanceof ApiError)\n throw e\n }\n }\n\n const text = await response.text()\n throw new ApiError(response.status, text || `${response.status} ${response.statusText}`)\n }\n\n return response.json() as Promise<T>\n}\n","import { createHash } from 'node:crypto'\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { basename, join } from 'node:path'\nimport type { LoadedAdapter } from './types.js'\nimport { parseAdapterToml } from './toml.js'\n\nfunction digest(content: string): string {\n return `SHA-256:${createHash('sha256').update(content).digest('hex')}`\n}\n\nfunction adapterDirs(): string[] {\n return [\n join(process.cwd(), '.openape', 'shapes', 'adapters'),\n join(homedir(), '.openape', 'shapes', 'adapters'),\n join('/etc', 'openape', 'shapes', 'adapters'),\n ]\n}\n\nfunction findByExecutable(executable: string): string | undefined {\n for (const dir of adapterDirs()) {\n if (!existsSync(dir))\n continue\n try {\n const files = readdirSync(dir).filter(f => f.endsWith('.toml'))\n for (const file of files) {\n const path = join(dir, file)\n const content = readFileSync(path, 'utf-8')\n const match = content.match(/^\\s*executable\\s*=\\s*\"([^\"]+)\"/m)\n if (match && match[1] === executable)\n return path\n }\n }\n catch {\n // directory not readable\n }\n }\n return undefined\n}\n\nexport function resolveAdapterPath(cliId: string, explicitPath?: string): string {\n if (explicitPath) {\n if (existsSync(explicitPath))\n return explicitPath\n throw new Error(`Adapter file not found: ${explicitPath}`)\n }\n\n // Try direct lookup by ID\n const candidates = adapterDirs().map(dir => join(dir, `${cliId}.toml`))\n const match = candidates.find(path => existsSync(path))\n if (match)\n return match\n\n // Fallback: scan for adapter with matching executable name\n const byExec = findByExecutable(cliId)\n if (byExec)\n return byExec\n\n throw new Error(`No adapter found for ${cliId}`)\n}\n\nexport function loadAdapter(cliId: string, explicitPath?: string): LoadedAdapter {\n const source = resolveAdapterPath(cliId, explicitPath)\n const content = readFileSync(source, 'utf-8')\n const adapter = parseAdapterToml(content)\n\n // Accept if either the adapter ID or the executable matches the requested cliId\n const idMatch = adapter.cli.id === cliId\n const fileMatch = basename(source) === `${cliId}.toml`\n const execMatch = adapter.cli.executable === cliId\n if (!idMatch && !fileMatch && !execMatch)\n throw new Error(`Adapter ${source} does not match requested CLI ${cliId}`)\n\n return {\n adapter,\n source,\n digest: digest(content),\n }\n}\n\n/** Try to load an adapter locally, return null instead of throwing when not found. */\nexport function tryLoadAdapter(cliId: string, explicitPath?: string): LoadedAdapter | null {\n try {\n return loadAdapter(cliId, explicitPath)\n }\n catch {\n return null\n }\n}\n","import type { ShapesAdapter, ShapesOperation } from './types.js'\n\ninterface AdapterTomlFile {\n schema?: string\n cli?: ShapesAdapter['cli']\n operation?: ShapesOperation[]\n}\n\nfunction parseKeyValue(line: string): { key: string, value: string } | null {\n const eqIndex = line.indexOf('=')\n if (eqIndex === -1)\n return null\n const key = line.slice(0, eqIndex).trim()\n const value = line.slice(eqIndex + 1).trim()\n if (!key || !value)\n return null\n return { key, value }\n}\n\nfunction parseTomlValue(raw: string): unknown {\n const trimmed = raw.trim()\n\n if (trimmed.startsWith('\"') && trimmed.endsWith('\"'))\n return trimmed.slice(1, -1)\n if (trimmed === 'true')\n return true\n if (trimmed === 'false')\n return false\n if (trimmed.startsWith('[') && trimmed.endsWith(']')) {\n const inner = trimmed.slice(1, -1).trim()\n if (!inner)\n return []\n return inner.split(',').map(value => value.trim().replace(/^\"|\"$/g, ''))\n }\n\n return trimmed\n}\n\nexport function parseAdapterToml(content: string): ShapesAdapter {\n const result: AdapterTomlFile = {}\n const operations: ShapesOperation[] = []\n let currentSection: 'root' | 'cli' | 'operation' = 'root'\n let currentEntry: Record<string, unknown> = {}\n\n const flushOperation = () => {\n if (currentSection === 'operation' && Object.keys(currentEntry).length > 0) {\n operations.push(currentEntry as unknown as ShapesOperation)\n currentEntry = {}\n }\n }\n\n for (const rawLine of content.split('\\n')) {\n const line = rawLine.trim()\n if (!line || line.startsWith('#'))\n continue\n\n if (line === '[cli]') {\n flushOperation()\n currentSection = 'cli'\n result.cli = {} as ShapesAdapter['cli']\n continue\n }\n\n if (line === '[[operation]]') {\n flushOperation()\n currentSection = 'operation'\n currentEntry = {}\n continue\n }\n\n const kv = parseKeyValue(line)\n if (!kv)\n continue\n\n const value = parseTomlValue(kv.value)\n if (currentSection === 'root') {\n ;(result as Record<string, unknown>)[kv.key] = value\n }\n else if (currentSection === 'cli') {\n ;(result.cli as Record<string, unknown>)[kv.key] = value\n }\n else {\n currentEntry[kv.key] = value\n }\n }\n\n flushOperation()\n result.operation = operations\n\n if (result.schema !== 'openape-shapes/v1') {\n throw new Error(`Unsupported adapter schema: ${result.schema ?? 'missing'}`)\n }\n if (!result.cli?.id || !result.cli.executable) {\n throw new Error('Adapter is missing cli.id or cli.executable')\n }\n if (!result.operation?.length) {\n throw new Error('Adapter must define at least one [[operation]] entry')\n }\n\n return {\n schema: result.schema,\n cli: {\n id: String(result.cli.id),\n executable: String(result.cli.executable),\n ...(result.cli.audience ? { audience: String(result.cli.audience) } : {}),\n ...(result.cli.version ? { version: String(result.cli.version) } : {}),\n },\n operations: result.operation.map((operation) => {\n if (!Array.isArray(operation.command) || operation.command.some(token => typeof token !== 'string')) {\n throw new Error(`Operation ${String(operation.id ?? '<unknown>')} is missing command[]`)\n }\n if (!Array.isArray(operation.resource_chain) || operation.resource_chain.some(token => typeof token !== 'string')) {\n throw new Error(`Operation ${String(operation.id ?? '<unknown>')} is missing resource_chain[]`)\n }\n if (typeof operation.id !== 'string' || typeof operation.display !== 'string' || typeof operation.action !== 'string') {\n throw new TypeError('Operation must define id, display, and action')\n }\n return {\n id: operation.id,\n command: operation.command as string[],\n ...(Array.isArray(operation.positionals) ? { positionals: operation.positionals as string[] } : {}),\n ...(Array.isArray(operation.required_options) ? { required_options: operation.required_options as string[] } : {}),\n display: operation.display,\n action: operation.action,\n risk: (operation.risk as ShapesOperation['risk']) || 'low',\n resource_chain: operation.resource_chain as string[],\n ...(operation.exact_command !== undefined ? { exact_command: Boolean(operation.exact_command) } : {}),\n }\n }),\n }\n}\n","import { appendFileSync, existsSync, mkdirSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\n\n/** Single audit log entry. Always includes a timestamp and an action string. */\nexport interface AuditEntry {\n action: string\n timestamp: number\n [key: string]: unknown\n}\n\nfunction auditPath(): string {\n return join(homedir(), '.config', 'apes', 'audit.jsonl')\n}\n\n/**\n * Append a single entry to the audit log at ~/.config/apes/audit.jsonl.\n * Failures are swallowed — the audit log should never break the actual flow.\n */\nexport function appendAuditLog(entry: { action: string, timestamp?: number } & Record<string, unknown>): void {\n const full: AuditEntry = {\n ...entry,\n action: entry.action,\n timestamp: entry.timestamp ?? Date.now(),\n }\n const path = auditPath()\n const dir = dirname(path)\n try {\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true })\n appendFileSync(path, `${JSON.stringify(full)}\\n`)\n }\n catch {\n // intentionally ignored — audit log must never break the flow\n }\n}\n","import { createHash } from 'node:crypto'\nimport { existsSync, mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport type { RegistryEntry } from './types.js'\n\nfunction adapterDir(local: boolean): string {\n const base = local ? process.cwd() : homedir()\n return join(base, '.openape', 'shapes', 'adapters')\n}\n\nfunction adapterPath(id: string, local: boolean): string {\n return join(adapterDir(local), `${id}.toml`)\n}\n\nfunction sha256(content: string): string {\n return `SHA-256:${createHash('sha256').update(content).digest('hex')}`\n}\n\nexport interface InstallResult {\n id: string\n path: string\n digest: string\n updated: boolean\n}\n\nexport async function installAdapter(entry: RegistryEntry, options: { local?: boolean } = {}): Promise<InstallResult> {\n const local = options.local ?? false\n const dest = adapterPath(entry.id, local)\n const dir = adapterDir(local)\n\n const response = await fetch(entry.download_url)\n if (!response.ok)\n throw new Error(`Failed to download adapter ${entry.id}: ${response.status} ${response.statusText}`)\n\n const content = await response.text()\n const digest = sha256(content)\n\n if (digest !== entry.digest)\n throw new Error(`Digest mismatch for ${entry.id}: expected ${entry.digest}, got ${digest}`)\n\n const updated = existsSync(dest)\n\n if (!existsSync(dir))\n mkdirSync(dir, { recursive: true })\n\n writeFileSync(dest, content)\n\n return { id: entry.id, path: dest, digest, updated }\n}\n\nexport function getInstalledDigest(id: string, local: boolean): string | null {\n const path = adapterPath(id, local)\n if (!existsSync(path))\n return null\n\n const content = readFileSync(path, 'utf-8')\n return sha256(content)\n}\n\nexport function isInstalled(id: string, local: boolean): boolean {\n return existsSync(adapterPath(id, local))\n}\n\nexport function getInstalledPath(id: string, local: boolean): string {\n return adapterPath(id, local)\n}\n\nexport function removeAdapter(id: string, local: boolean): boolean {\n const path = adapterPath(id, local)\n if (!existsSync(path))\n return false\n unlinkSync(path)\n return true\n}\n\nexport interface ConflictingAdapter {\n file: string\n path: string\n adapterId: string\n executable: string\n}\n\nexport function findConflictingAdapters(executable: string, excludeId: string): ConflictingAdapter[] {\n const conflicts: ConflictingAdapter[] = []\n const dirs = [\n join(process.cwd(), '.openape', 'shapes', 'adapters'),\n join(homedir(), '.openape', 'shapes', 'adapters'),\n ]\n\n for (const dir of dirs) {\n if (!existsSync(dir))\n continue\n try {\n for (const file of readdirSync(dir).filter(f => f.endsWith('.toml'))) {\n const path = join(dir, file)\n const content = readFileSync(path, 'utf-8')\n const execMatch = content.match(/^\\s*executable\\s*=\\s*\"([^\"]+)\"/m)\n const idMatch = content.match(/^\\s*id\\s*=\\s*\"([^\"]+)\"/m)\n if (execMatch?.[1] === executable && idMatch?.[1] !== excludeId) {\n conflicts.push({ file, path, adapterId: idMatch?.[1] ?? file, executable })\n }\n }\n }\n catch {\n // directory not readable\n }\n }\n\n return conflicts\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport type { RegistryEntry, RegistryIndex } from './types.js'\n\nconst REGISTRY_URL = process.env.SHAPES_REGISTRY_URL\n ?? 'https://raw.githubusercontent.com/openape-ai/shapes-registry/main/registry.json'\n\nconst CACHE_TTL_MS = 60 * 60 * 1000 // 1 hour\n\nfunction cacheDir(): string {\n return join(homedir(), '.openape', 'shapes', 'cache')\n}\n\nfunction cachePath(): string {\n return join(cacheDir(), 'registry.json')\n}\n\nfunction readCache(): RegistryIndex | null {\n const path = cachePath()\n if (!existsSync(path))\n return null\n\n try {\n const raw = readFileSync(path, 'utf-8')\n const stat = JSON.parse(raw) as RegistryIndex & { _cached_at?: number }\n if (stat._cached_at && Date.now() - stat._cached_at > CACHE_TTL_MS)\n return null\n return stat\n }\n catch {\n return null\n }\n}\n\nfunction writeCache(index: RegistryIndex): void {\n const dir = cacheDir()\n if (!existsSync(dir))\n mkdirSync(dir, { recursive: true })\n\n writeFileSync(cachePath(), JSON.stringify({ ...index, _cached_at: Date.now() }, null, 2))\n}\n\nexport async function fetchRegistry(forceRefresh = false): Promise<RegistryIndex> {\n if (!forceRefresh) {\n const cached = readCache()\n if (cached)\n return cached\n }\n\n const response = await fetch(REGISTRY_URL)\n if (!response.ok)\n throw new Error(`Failed to fetch registry: ${response.status} ${response.statusText}`)\n\n const index = await response.json() as RegistryIndex\n writeCache(index)\n return index\n}\n\nexport function searchAdapters(index: RegistryIndex, query: string): RegistryEntry[] {\n const q = query.toLowerCase()\n return index.adapters.filter(a =>\n a.id.includes(q)\n || a.name.toLowerCase().includes(q)\n || a.description.toLowerCase().includes(q)\n || a.tags.some(t => t.includes(q))\n || a.category.includes(q),\n )\n}\n\n/**\n * Look up a registry entry by its id or its executable field. This lets callers\n * pass either the registry id (\"o365\") or the binary name (\"o365-cli\"); most\n * adapters have id === executable, but the two can diverge.\n */\nexport function findAdapter(index: RegistryIndex, idOrExecutable: string): RegistryEntry | undefined {\n return index.adapters.find(\n a => a.id === idOrExecutable || a.executable === idOrExecutable,\n )\n}\n","import { basename } from 'node:path'\nimport consola from 'consola'\nimport { parse as shellParse } from 'shell-quote'\nimport { loadAdapter, tryLoadAdapter } from './adapters.js'\nimport { installAdapter } from './installer.js'\nimport { fetchRegistry, findAdapter } from './registry.js'\nimport { appendAuditLog } from './audit.js'\nimport type { LoadedAdapter } from './types.js'\n\n/** A parsed shell command string with the executable and its argv extracted. */\nexport interface ParsedShellCommand {\n /** The program to run (first token, e.g. \"rm\") */\n executable: string\n /** Remaining tokens after the executable (e.g. [\"-f\", \"/tmp/foo.txt\"]) */\n argv: string[]\n /**\n * true if the command contains compound operators (&&, ||, ;, |),\n * subshells ($(...)), or backticks. These cannot be safely handled\n * by the adapter mode and must fall back to the generic shell grant flow.\n */\n isCompound: boolean\n /** The original command string for display/logging */\n raw: string\n}\n\nconst COMPOUND_OPERATORS = new Set(['&&', '||', ';', '|', '&', '>', '>>', '<'])\n\ntype ShellQuoteToken = string | { op: string } | { comment: string } | { pattern: string }\n\n/**\n * Parse a shell command string like `rm /tmp/foo.txt` or `git commit -m \"hello\"` into\n * its executable and argv. Uses `shell-quote` to handle quoting correctly.\n *\n * Returns null for empty/whitespace-only input.\n */\nexport function parseShellCommand(raw: string): ParsedShellCommand | null {\n const trimmed = raw.trim()\n if (trimmed.length === 0) return null\n\n let tokens: ShellQuoteToken[]\n try {\n tokens = shellParse(trimmed) as ShellQuoteToken[]\n }\n catch {\n return null\n }\n\n // Detect compound operators and subshells\n const hasShellExpansion = /\\$\\(|`/.test(trimmed)\n const hasOperatorToken = tokens.some(t => typeof t === 'object' && t !== null && 'op' in t && COMPOUND_OPERATORS.has(t.op))\n const isCompound = hasShellExpansion || hasOperatorToken\n\n // Extract leading string tokens up to the first operator object\n const stringTokens: string[] = []\n for (const t of tokens) {\n if (typeof t === 'string') {\n stringTokens.push(t)\n }\n else {\n break\n }\n }\n\n if (stringTokens.length === 0) return null\n\n return {\n executable: stringTokens[0]!,\n argv: stringTokens.slice(1),\n isCompound,\n raw: trimmed,\n }\n}\n\n/**\n * Extract the command string from an `apes run --shell -- bash -c \"…\"` argv.\n * Returns null if the argv does not follow that shape.\n */\nexport function extractShellCommandString(command: string[]): string | null {\n if (command.length < 3) return null\n if (command[0] !== 'bash' && command[0] !== 'sh') return null\n if (command[1] !== '-c') return null\n // Everything after `-c` is the quoted command string\n return command.slice(2).join(' ')\n}\n\n/**\n * Load an adapter for the given CLI id. If the adapter is not installed locally,\n * try to fetch it from the shapes registry and auto-install it.\n *\n * Returns null when no adapter exists in either location, or when any step fails.\n * Failures are logged but never thrown — callers should fall back to the generic flow.\n */\nexport async function loadOrInstallAdapter(cliId: string): Promise<LoadedAdapter | null> {\n // Absolute or relative paths like `/usr/local/bin/o365-cli` must be reduced\n // to the binary name before any lookup — neither the local file scan nor the\n // registry knows how to match a path.\n const lookupId = basename(cliId)\n\n // 1. Try local\n const local = tryLoadAdapter(lookupId)\n if (local) return local\n\n // 2. Remote registry lookup + auto-install.\n // findAdapter matches both `id` and `executable`, so a bare binary name\n // like `o365-cli` resolves to a registry entry whose id is `o365`.\n try {\n const index = await fetchRegistry()\n const entry = findAdapter(index, lookupId)\n if (!entry) return null\n\n consola.info(`Installing shapes adapter for ${entry.id} from registry...`)\n await installAdapter(entry, { local: false })\n appendAuditLog({\n action: 'adapter-auto-install',\n cli_id: entry.id,\n digest: entry.digest,\n source: 'ape-shell',\n })\n\n // Adapters are installed under their registry `id` — always reload by id\n // even if the caller passed the executable name.\n return tryLoadAdapter(entry.id)\n }\n catch (err) {\n consola.debug(`ape-shell adapter auto-install failed for ${lookupId}:`, err)\n return null\n }\n}\n\n// Re-export loadAdapter so callers can import everything from one module\nexport { loadAdapter }\n","import type { OpenApeCliAuthorizationDetail, OpenApeCliResourceRef } from '@openape/core'\nimport { canonicalizeCliPermission } from '@openape/grants'\nimport type { LoadedAdapter, ResolvedCapability, ShapesOperation } from './types.js'\n\ninterface ParsedOperationChainEntry {\n resource: string\n selectorKeys: string[]\n}\n\nfunction parseOperationChainEntry(entry: string): ParsedOperationChainEntry {\n const [resource, selectorSpec = '*'] = entry.split(':', 2)\n if (!resource) {\n throw new Error(`Invalid resource chain entry: ${entry}`)\n }\n\n if (selectorSpec === '*') {\n return { resource, selectorKeys: [] }\n }\n\n const selectorKeys = selectorSpec.split(',')\n .map((segment) => {\n const [key] = segment.split('=', 2)\n if (!key)\n throw new Error(`Invalid selector segment: ${segment}`)\n return key\n })\n\n return { resource, selectorKeys }\n}\n\nfunction operationChain(operation: ShapesOperation): ParsedOperationChainEntry[] {\n return operation.resource_chain.map(parseOperationChainEntry)\n}\n\nfunction knownSelectorKeys(operations: ShapesOperation[], resource: string): string[] {\n const keys = new Set<string>()\n for (const operation of operations) {\n for (const entry of operationChain(operation)) {\n if (entry.resource !== resource)\n continue\n for (const key of entry.selectorKeys) {\n keys.add(key)\n }\n }\n }\n return Array.from(keys).sort()\n}\n\nfunction parseResourceSelector(raw: string): { resource: string, key: string, value: string } {\n const [lhs, value] = raw.split('=', 2)\n if (!lhs || !value) {\n throw new Error(`Invalid selector: ${raw}`)\n }\n\n const [resource, key] = lhs.split('.', 2)\n if (!resource || !key) {\n throw new Error(`Selectors must be in resource.key=value form: ${raw}`)\n }\n\n return { resource, key, value }\n}\n\nfunction formatSelector(selector?: Record<string, string>): string {\n if (!selector || Object.keys(selector).length === 0)\n return '*'\n return Object.entries(selector)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, value]) => `${key}=${value}`)\n .join(',')\n}\n\nfunction summarizeDetail(detail: OpenApeCliAuthorizationDetail): string {\n const chain = detail.resource_chain\n .map(resource => `${resource.resource}[${formatSelector(resource.selector)}]`)\n .join(' -> ')\n return `Allow ${detail.action} on ${detail.cli_id} ${chain}`\n}\n\nexport function resolveCapabilityRequest(\n loaded: LoadedAdapter,\n params: {\n resources: string[]\n selectors?: string[]\n actions: string[]\n },\n): ResolvedCapability {\n if (params.resources.length === 0) {\n throw new Error('At least one --resource is required')\n }\n if (params.actions.length === 0) {\n throw new Error('At least one --action is required')\n }\n\n const selectorMap = new Map<string, Record<string, string>>()\n for (const rawSelector of params.selectors ?? []) {\n const { resource, key, value } = parseResourceSelector(rawSelector)\n const current = selectorMap.get(resource) ?? {}\n current[key] = value\n selectorMap.set(resource, current)\n }\n\n const resource_chain: OpenApeCliResourceRef[] = params.resources.map((resource) => {\n const selector = selectorMap.get(resource)\n const knownKeys = knownSelectorKeys(loaded.adapter.operations, resource)\n if (selector) {\n for (const key of Object.keys(selector)) {\n if (!knownKeys.includes(key)) {\n throw new Error(`Unknown selector ${resource}.${key} for adapter ${loaded.adapter.cli.id}`)\n }\n }\n }\n return selector && Object.keys(selector).length > 0 ? { resource, selector } : { resource }\n })\n\n const requestedSequence = params.resources.join('\\0')\n const matchingOperations = loaded.adapter.operations.filter((operation) => {\n const sequence = operationChain(operation).map(entry => entry.resource).join('\\0')\n return sequence === requestedSequence || sequence.startsWith(`${requestedSequence}\\0`)\n })\n\n if (matchingOperations.length === 0) {\n throw new Error(`No adapter operation supports resource chain: ${params.resources.join(' -> ')}`)\n }\n\n const details = params.actions.map((action) => {\n const matchingActionOps = matchingOperations.filter(operation => operation.action === action)\n if (matchingActionOps.length === 0) {\n throw new Error(`Action ${action} is not valid for resource chain: ${params.resources.join(' -> ')}`)\n }\n\n const exact_command = matchingActionOps.every(operation => operation.exact_command === true)\n const risks = ['low', 'medium', 'high', 'critical'] as const\n const risk = matchingActionOps.reduce<typeof risks[number]>((current, operation) => {\n return risks.indexOf(operation.risk) > risks.indexOf(current) ? operation.risk : current\n }, 'low')\n\n const detail: OpenApeCliAuthorizationDetail = {\n type: 'openape_cli',\n cli_id: loaded.adapter.cli.id,\n operation_id: `capability.${action}`,\n resource_chain,\n action,\n permission: '',\n display: '',\n risk,\n ...(exact_command ? { constraints: { exact_command: true } } : {}),\n }\n detail.permission = canonicalizeCliPermission(detail)\n detail.display = summarizeDetail(detail)\n return detail\n })\n\n return {\n adapter: loaded.adapter,\n source: loaded.source,\n digest: loaded.digest,\n executable: loaded.adapter.cli.executable,\n details,\n executionContext: {\n adapter_id: loaded.adapter.cli.id,\n adapter_version: loaded.adapter.cli.version ?? loaded.adapter.schema,\n adapter_digest: loaded.digest,\n resolved_executable: loaded.adapter.cli.executable,\n context_bindings: Object.fromEntries(\n Array.from(selectorMap.entries()).flatMap(([resource, selector]) =>\n Object.entries(selector).map(([key, value]) => [`${resource}.${key}`, value] as const),\n ),\n ),\n },\n permissions: details.map(detail => detail.permission),\n summary: details.map(detail => detail.display).join('; '),\n }\n}\n","import type { OpenApeCliAuthorizationDetail, OpenApeCliResourceRef } from '@openape/core'\nimport { canonicalizeCliPermission, computeArgvHash } from '@openape/grants'\nimport type { LoadedAdapter, ResolvedCommand, ShapesOperation } from './types.js'\n\nfunction parseOptionArgs(tokens: string[], valueOptions?: string[]): { options: Record<string, string>, positionals: string[] } {\n const options: Record<string, string> = {}\n const positionals: string[] = []\n const takesValue = new Set(valueOptions ?? [])\n\n for (let index = 0; index < tokens.length; index += 1) {\n const token = tokens[index]!\n\n if (token.startsWith('--')) {\n // Long option: --name value or --name=value\n const stripped = token.slice(2)\n const eqIndex = stripped.indexOf('=')\n if (eqIndex >= 0) {\n options[stripped.slice(0, eqIndex)] = stripped.slice(eqIndex + 1)\n continue\n }\n\n const next = tokens[index + 1]\n if (next && !next.startsWith('-')) {\n options[stripped] = next\n index += 1\n continue\n }\n\n options[stripped] = 'true'\n }\n else if (token.startsWith('-') && token.length > 1 && !/^-\\d/.test(token)) {\n // Short option: -name value, -f value, or -l (boolean)\n const key = token.slice(1)\n\n if (key.length === 1 && !takesValue.has(key)) {\n // Single-char flag not in required_options → boolean\n options[key] = 'true'\n }\n else {\n // Multi-char option (-name) or known value option (-f) → consume next as value\n const next = tokens[index + 1]\n if (next && !next.startsWith('-')) {\n options[key] = next\n index += 1\n }\n else {\n options[key] = 'true'\n }\n }\n }\n else {\n positionals.push(token)\n }\n }\n\n return { options, positionals }\n}\n\nfunction resolveBindingToken(binding: string, bindings: Record<string, string>): string {\n const match = binding.match(/^\\{([^}|]+)(?:\\|([^}]+))?\\}$/)\n if (!match)\n return binding\n\n const [, name, transform] = match\n const value = bindings[name]\n if (!value)\n throw new Error(`Missing binding: ${name}`)\n if (!transform)\n return value\n\n if (transform === 'owner' || transform === 'name') {\n const [owner, repo] = value.split('/')\n if (!owner || !repo)\n throw new Error(`Binding ${name} must be in owner/name form`)\n return transform === 'owner' ? owner : repo\n }\n\n throw new Error(`Unsupported binding transform: ${transform}`)\n}\n\nfunction renderTemplate(template: string, bindings: Record<string, string>): string {\n return template.replace(/\\{([^}]+)\\}/g, (_, expression: string) => resolveBindingToken(`{${expression}}`, bindings))\n}\n\nfunction parseResourceChain(chain: string[], bindings: Record<string, string>): OpenApeCliResourceRef[] {\n return chain.map((entry) => {\n const [resource, selectorSpec = '*'] = entry.split(':', 2)\n if (!resource)\n throw new Error(`Invalid resource chain entry: ${entry}`)\n\n if (selectorSpec === '*') {\n return { resource }\n }\n\n const selector = Object.fromEntries(\n selectorSpec.split(',').map((segment) => {\n const [key, rawValue] = segment.split('=', 2)\n if (!key || !rawValue)\n throw new Error(`Invalid selector segment: ${segment}`)\n return [key, renderTemplate(rawValue, bindings)]\n }),\n )\n\n return { resource, selector }\n })\n}\n\nfunction matchOperation(operation: ShapesOperation, argv: string[]): Record<string, string> | null {\n if (argv.length < operation.command.length)\n return null\n\n const prefix = argv.slice(0, operation.command.length)\n if (prefix.join('\\0') !== operation.command.join('\\0'))\n return null\n\n const remainder = argv.slice(operation.command.length)\n const { options, positionals } = parseOptionArgs(remainder, operation.required_options)\n\n const expectedPositionals = operation.positionals ?? []\n if (positionals.length !== expectedPositionals.length)\n return null\n\n for (const option of operation.required_options ?? []) {\n if (!options[option])\n return null\n }\n\n const bindings: Record<string, string> = { ...options }\n expectedPositionals.forEach((name, index) => {\n bindings[name] = positionals[index]!\n })\n return bindings\n}\n\nfunction expandCombinedFlags(argv: string[]): string[] {\n return argv.flatMap((token) => {\n // Expand -rl into -r, -l (only single-letter combined flags)\n if (token.startsWith('-') && !token.startsWith('--') && token.length > 2 && /^-[a-z]+$/i.test(token)) {\n return Array.from(token.slice(1), c => `-${c}`)\n }\n return [token]\n })\n}\n\nfunction tryMatch(operations: ShapesOperation[], argv: string[]) {\n return operations.flatMap((operation) => {\n try {\n const bindings = matchOperation(operation, argv)\n return bindings ? [{ operation, bindings }] : []\n }\n catch {\n return []\n }\n })\n}\n\nexport async function resolveCommand(loaded: LoadedAdapter, fullArgv: string[]): Promise<ResolvedCommand> {\n const [executable, ...commandArgv] = fullArgv\n if (!executable) {\n throw new Error('Missing wrapped command')\n }\n if (executable !== loaded.adapter.cli.executable) {\n throw new Error(`Adapter ${loaded.adapter.cli.id} expects executable ${loaded.adapter.cli.executable}, got ${executable}`)\n }\n\n // Pass 1: exact match\n let matches = tryMatch(loaded.adapter.operations, commandArgv)\n\n // Pass 2: try with expanded combined flags (e.g. -rl → -r -l)\n if (matches.length === 0) {\n const expanded = expandCombinedFlags(commandArgv)\n if (expanded.length !== commandArgv.length) {\n matches = tryMatch(loaded.adapter.operations, expanded)\n }\n }\n\n if (matches.length === 0) {\n throw new Error(`No adapter operation matched: ${fullArgv.join(' ')}`)\n }\n if (matches.length > 1) {\n // Prefer the most specific match (longest command prefix)\n matches.sort((a, b) => b.operation.command.length - a.operation.command.length)\n matches = [matches[0]!]\n }\n\n const { operation, bindings } = matches[0]!\n const resource_chain = parseResourceChain(operation.resource_chain, bindings)\n const detail: OpenApeCliAuthorizationDetail = {\n type: 'openape_cli',\n cli_id: loaded.adapter.cli.id,\n operation_id: operation.id,\n resource_chain,\n action: operation.action,\n permission: '',\n display: renderTemplate(operation.display, bindings),\n risk: operation.risk,\n ...(operation.exact_command ? { constraints: { exact_command: true } } : {}),\n }\n detail.permission = canonicalizeCliPermission(detail)\n\n return {\n adapter: loaded.adapter,\n source: loaded.source,\n digest: loaded.digest,\n executable,\n commandArgv,\n bindings,\n detail,\n executionContext: {\n argv: fullArgv,\n argv_hash: await computeArgvHash(fullArgv),\n adapter_id: loaded.adapter.cli.id,\n adapter_version: loaded.adapter.cli.version ?? loaded.adapter.schema,\n adapter_digest: loaded.digest,\n resolved_executable: executable,\n context_bindings: bindings,\n },\n permission: detail.permission,\n }\n}\n","import { defineCommand } from 'citty'\nimport { loadAdapter } from '../adapters.js'\nimport { resolveCommand } from '../parser.js'\n\nexport const explainCommand = defineCommand({\n meta: {\n name: 'explain',\n description: 'Show what permission a wrapped command would need',\n },\n args: {\n adapter: {\n type: 'string',\n description: 'Explicit path to adapter TOML file',\n },\n _: {\n type: 'positional',\n description: 'Wrapped command (after --)',\n required: false,\n },\n },\n async run({ rawArgs }) {\n const command = extractWrappedCommand(rawArgs ?? [])\n if (command.length === 0)\n throw new Error('Missing wrapped command. Usage: shapes explain [--adapter <file>] -- <cli> ...')\n\n const adapterOpt = extractOption(rawArgs ?? [], 'adapter')\n const loaded = loadAdapter(command[0]!, adapterOpt)\n const resolved = await resolveCommand(loaded, command)\n\n process.stdout.write(`${JSON.stringify({\n adapter: resolved.adapter.cli.id,\n source: resolved.source,\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\nexport function extractWrappedCommand(args: string[]): string[] {\n const delimiter = args.indexOf('--')\n return delimiter >= 0 ? args.slice(delimiter + 1) : []\n}\n\nexport function extractOption(args: string[], name: string): string | undefined {\n const delimiter = args.indexOf('--')\n const optionArgs = delimiter >= 0 ? args.slice(0, delimiter) : args\n const index = optionArgs.indexOf(`--${name}`)\n if (index >= 0 && index + 1 < optionArgs.length)\n return optionArgs[index + 1]\n return undefined\n}\n","import type { OpenApeCliAuthorizationDetail, OpenApeGrant } from '@openape/core'\nimport { computeCmdHash } from '@openape/core'\nimport { cliAuthorizationDetailCovers, verifyAuthzJWT } from '@openape/grants'\nimport { execFileSync } from 'node:child_process'\nimport { hostname } from 'node:os'\nimport consola from 'consola'\nimport { getRequesterIdentity } from './config.js'\nimport type { ResolvedCommand } from './types.js'\nimport { apiFetch, discoverEndpoints, getGrantsEndpoint } from './http.js'\n\nfunction decodePayload(token: string): Record<string, unknown> {\n const [, payload] = token.split('.')\n if (!payload)\n throw new Error('Invalid JWT')\n return JSON.parse(Buffer.from(payload, 'base64url').toString('utf-8')) as Record<string, unknown>\n}\n\ninterface SimilarGrantsInfo {\n similar_grants: Array<{ grant: { id: string }, similar_detail_indices: number[] }>\n widened_details: Array<{ permission: string }>\n merged_details: Array<{ permission: string }>\n}\n\nexport async function createShapesGrant(\n resolved: ResolvedCommand,\n params: {\n idp: string\n approval: 'once' | 'timed' | 'always'\n reason?: string\n },\n): Promise<{ id: string, status: string, similar_grants?: SimilarGrantsInfo }> {\n const grantsEndpoint = await getGrantsEndpoint(params.idp)\n const requester = getRequesterIdentity()\n if (!requester) {\n throw new Error('No requester identity available. Run `apes login` first.')\n }\n return apiFetch<{ id: string, status: string, similar_grants?: SimilarGrantsInfo }>(grantsEndpoint, {\n method: 'POST',\n idp: params.idp,\n body: {\n requester,\n target_host: hostname(),\n audience: resolved.adapter.cli.audience ?? 'shapes',\n grant_type: params.approval,\n command: resolved.executionContext.argv,\n reason: params.reason ?? resolved.detail.display,\n permissions: [resolved.permission],\n authorization_details: [resolved.detail],\n execution_context: resolved.executionContext,\n },\n })\n}\n\nexport async function waitForGrantStatus(idp: string, grantId: string): Promise<'approved' | 'denied' | 'revoked'> {\n const grantsEndpoint = await getGrantsEndpoint(idp)\n const deadline = Date.now() + 300_000\n\n while (Date.now() < deadline) {\n const grant = await apiFetch<{ status: 'pending' | 'approved' | 'denied' | 'revoked' }>(`${grantsEndpoint}/${grantId}`, { idp })\n if (grant.status === 'approved' || grant.status === 'denied' || grant.status === 'revoked')\n return grant.status\n await new Promise(resolve => setTimeout(resolve, 3000))\n }\n\n throw new Error('Timed out waiting for grant approval')\n}\n\nexport async function fetchGrantToken(idp: string, grantId: string): Promise<string> {\n const grantsEndpoint = await getGrantsEndpoint(idp)\n const response = await apiFetch<{ authz_jwt: string }>(`${grantsEndpoint}/${grantId}/token`, {\n method: 'POST',\n idp,\n })\n return response.authz_jwt\n}\n\nfunction grantedCliDetails(claims: Record<string, unknown>): OpenApeCliAuthorizationDetail[] {\n const details = claims.authorization_details\n if (!Array.isArray(details))\n return []\n\n return details.filter((detail): detail is OpenApeCliAuthorizationDetail =>\n typeof detail === 'object'\n && detail !== null\n && (detail as Record<string, unknown>).type === 'openape_cli',\n )\n}\n\nfunction hasStructuredCliGrant(claims: Record<string, unknown>): boolean {\n return grantedCliDetails(claims).length > 0\n}\n\n/**\n * Verifies a grant token against the resolved command and marks the grant\n * as consumed on the IdP. Does NOT execute anything — callers that want\n * the one-shot behavior should use `verifyAndExecute`, callers that want\n * to run the command themselves (e.g. the interactive REPL piping through\n * a persistent bash pty) should call this and then do their own execution.\n *\n * Split out so the interactive shell can re-use the verify + consume path\n * without being forced into the `execFileSync`-based one-shot execution.\n */\nexport async function verifyAndConsume(token: string, resolved: ResolvedCommand): Promise<void> {\n const payload = decodePayload(token)\n const issuer = String(payload.iss ?? '')\n if (!issuer)\n throw new Error('Grant token is missing issuer')\n\n const discovery = await discoverEndpoints(issuer)\n const jwksUri = String(discovery.jwks_uri ?? `${issuer}/.well-known/jwks.json`)\n const result = await verifyAuthzJWT(token, {\n expectedIss: issuer,\n expectedAud: resolved.adapter.cli.audience ?? 'shapes',\n jwksUri,\n })\n\n if (!result.valid || !result.claims) {\n throw new Error(result.error ?? 'Grant verification failed')\n }\n\n const claims = result.claims\n const details = grantedCliDetails(claims as unknown as Record<string, unknown>)\n\n if (claims.execution_context?.adapter_digest && claims.execution_context.adapter_digest !== resolved.digest) {\n throw new Error('Adapter digest mismatch')\n }\n\n if (!hasStructuredCliGrant(claims as unknown as Record<string, unknown>)) {\n const argv = resolved.executionContext.argv\n if (!argv?.length) {\n throw new Error('Resolved command is missing argv')\n }\n const expectedCmdHash = await computeCmdHash(argv.join(' '))\n if (claims.command?.join('\\0') !== argv.join('\\0')) {\n throw new Error('Granted command does not match current argv')\n }\n if (claims.cmd_hash && claims.cmd_hash !== expectedCmdHash) {\n throw new Error('Granted command does not match current argv')\n }\n if (!claims.command?.length && !claims.cmd_hash) {\n throw new Error('Grant is not a structured CLI grant and is missing command binding')\n }\n }\n else {\n if (!details.some(detail => cliAuthorizationDetailCovers(detail, resolved.detail))) {\n throw new Error(`Grant does not cover required permission: ${resolved.permission}`)\n }\n\n const exactRequired = details.some(detail =>\n cliAuthorizationDetailCovers(detail, resolved.detail) && detail.constraints?.exact_command,\n )\n\n const isOnce = claims.grant_type === 'once' || claims.approval === 'once'\n const enforceArgvHash = exactRequired || (isOnce && !!claims.execution_context?.argv_hash)\n\n if (enforceArgvHash && claims.execution_context?.argv_hash !== resolved.executionContext.argv_hash) {\n throw new Error('Granted command does not match current argv')\n }\n }\n\n const grantsEndpoint = await getGrantsEndpoint(issuer)\n const consume = await fetch(`${grantsEndpoint}/${claims.grant_id}/consume`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${token}`,\n },\n })\n\n if (!consume.ok) {\n throw new Error(`Consume failed: ${consume.status} ${consume.statusText}`)\n }\n\n const consumeResult = await consume.json() as { error?: string }\n if (consumeResult.error) {\n throw new Error(`Grant rejected at consume step: ${consumeResult.error}`)\n }\n}\n\n/**\n * Execute a verified + consumed resolved command directly via execFileSync,\n * inheriting stdio so the caller's terminal is handed to the child. Used by\n * the one-shot `apes run --shell` path.\n */\nexport function executeResolvedViaExec(resolved: ResolvedCommand): void {\n consola.info(`Executing ${(resolved.executionContext.argv ?? [resolved.executable, ...resolved.commandArgv]).join(' ')}`)\n execFileSync(resolved.executable, resolved.commandArgv, { stdio: 'inherit' })\n}\n\n/**\n * One-shot verify + consume + execute. Preserves the legacy behavior of\n * the `apes run --shell` path so existing callers keep working unchanged.\n */\nexport async function verifyAndExecute(token: string, resolved: ResolvedCommand): Promise<void> {\n await verifyAndConsume(token, resolved)\n executeResolvedViaExec(resolved)\n}\n\nexport async function findExistingGrant(\n resolved: ResolvedCommand,\n idp: string,\n): Promise<string | null> {\n const grantsEndpoint = await getGrantsEndpoint(idp)\n const response = await apiFetch<{ data: OpenApeGrant[] }>(\n `${grantsEndpoint}?status=approved`,\n { idp },\n )\n\n const now = Math.floor(Date.now() / 1000)\n const expectedAudience = resolved.adapter.cli.audience ?? 'shapes'\n\n for (const grant of response.data) {\n const req = grant.request\n if (req.grant_type === 'once')\n continue\n if (req.grant_type === 'timed' && grant.expires_at && grant.expires_at <= now)\n continue\n if (req.audience !== expectedAudience)\n continue\n if (req.execution_context?.adapter_digest && req.execution_context.adapter_digest !== resolved.digest)\n continue\n\n const cliDetails = (req.authorization_details ?? []).filter(\n (d): d is OpenApeCliAuthorizationDetail => d.type === 'openape_cli',\n )\n\n if (cliDetails.length > 0) {\n if (cliDetails.some(detail => cliAuthorizationDetailCovers(detail, resolved.detail)))\n return grant.id\n }\n else if (req.permissions?.includes(resolved.permission)) {\n return grant.id\n }\n }\n\n return null\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\n\ninterface AuthData {\n idp: string\n access_token: string\n email: string\n expires_at: number\n}\n\nconst AUTH_FILE = join(homedir(), '.config', 'apes', 'auth.json')\n\nexport function loadAuth(): AuthData | null {\n if (!existsSync(AUTH_FILE))\n return null\n try {\n return JSON.parse(readFileSync(AUTH_FILE, 'utf-8')) as AuthData\n }\n catch {\n return null\n }\n}\n\nexport function getIdpUrl(explicit?: string): string | null {\n if (explicit)\n return explicit\n if (process.env.APES_IDP)\n return process.env.APES_IDP\n if (process.env.SHAPES_IDP)\n return process.env.SHAPES_IDP\n return loadAuth()?.idp ?? null\n}\n\nexport function getAuthToken(): string | null {\n const auth = loadAuth()\n if (!auth)\n return null\n if (auth.expires_at && Date.now() / 1000 > auth.expires_at - 30)\n return null\n return auth.access_token\n}\n\nexport function getRequesterIdentity(): string | null {\n return loadAuth()?.email ?? null\n}\n","import { getAuthToken, getIdpUrl } from './config.js'\n\nexport async function discoverEndpoints(idpUrl: string): Promise<Record<string, unknown>> {\n const response = await fetch(`${idpUrl}/.well-known/openid-configuration`)\n if (!response.ok)\n return {}\n return response.json() as Promise<Record<string, unknown>>\n}\n\nexport async function getGrantsEndpoint(idpUrl: string): Promise<string> {\n const discovery = await discoverEndpoints(idpUrl)\n return String(discovery.openape_grants_endpoint ?? `${idpUrl}/api/grants`)\n}\n\nexport async function apiFetch<T>(\n path: string,\n options: {\n method?: string\n body?: unknown\n idp?: string\n token?: string\n } = {},\n): Promise<T> {\n const token = options.token ?? getAuthToken()\n if (!token)\n throw new Error('Not authenticated. Run `apes login` first.')\n\n const idp = options.idp ?? getIdpUrl()\n if (!path.startsWith('http') && !idp)\n throw new Error('No IdP URL configured. Use --idp or log in with apes.')\n\n const url = path.startsWith('http') ? path : `${idp}${path}`\n const response = await fetch(url, {\n method: options.method ?? 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: options.body ? JSON.stringify(options.body) : undefined,\n })\n\n if (!response.ok) {\n const text = await response.text()\n throw new Error(text || `${response.status} ${response.statusText}`)\n }\n\n return response.json() as Promise<T>\n}\n","import { computeCmdHash } from '@openape/core'\nimport type { BuiltGrantRequest, GrantRequestOptions, ResolvedCapability, ResolvedCommand } from './types.js'\n\nexport async function buildExactCommandGrantRequest(\n command: string[],\n options: GrantRequestOptions & {\n audience: string\n },\n): Promise<BuiltGrantRequest> {\n return {\n request: {\n requester: options.requester,\n target_host: options.target_host,\n audience: options.audience,\n grant_type: options.grant_type,\n command,\n cmd_hash: await computeCmdHash(command.join(' ')),\n ...(options.reason ? { reason: options.reason } : {}),\n ...(options.run_as ? { run_as: options.run_as } : {}),\n },\n }\n}\n\nexport async function buildStructuredCliGrantRequest(\n resolved: ResolvedCommand | ResolvedCapability,\n options: GrantRequestOptions,\n): Promise<BuiltGrantRequest> {\n const details = 'detail' in resolved ? [resolved.detail] : resolved.details\n const permissions = 'permission' in resolved ? [resolved.permission] : resolved.permissions\n const command = 'executionContext' in resolved && resolved.executionContext.argv?.length\n ? resolved.executionContext.argv\n : undefined\n\n return {\n request: {\n requester: options.requester,\n target_host: options.target_host,\n audience: resolved.adapter.cli.audience ?? 'shapes',\n grant_type: options.grant_type,\n permissions,\n authorization_details: details,\n execution_context: resolved.executionContext,\n ...(command ? { command } : {}),\n ...(options.reason ? { reason: options.reason } : { reason: 'summary' in resolved ? resolved.summary : details[0]?.display }),\n ...(options.run_as ? { run_as: options.run_as } : {}),\n },\n }\n}\n"],"mappings":";;;;;;;;;;AAAA,OAAO,aAAa;AAGpB,IAAM,QAAQ,QAAQ,KAAK,SAAS,SAAS;AAEtC,IAAM,WAAN,cAAuB,MAAM;AAAA,EAClC,YAAmB,YAAoB,SAAwB,gBAA0C;AACvG,UAAM,OAAO;AADI;AAA4C;AAE7D,SAAK,OAAO;AAAA,EACd;AACF;AAGA,IAAM,kBAA2D,CAAC;AAElE,eAAsB,kBAAkB,QAAkD;AACxF,MAAI,gBAAgB,MAAM,GAAG;AAC3B,WAAO,gBAAgB,MAAM;AAAA,EAC/B;AAEA,MAAI;AACF,UAAM,WAAW,MAAM,MAAM,GAAG,MAAM,mCAAmC;AACzE,QAAI,SAAS,IAAI;AACf,YAAM,OAAO,MAAM,SAAS,KAAK;AACjC,sBAAgB,MAAM,IAAI;AAC1B,aAAO;AAAA,IACT;AAAA,EACF,QACM;AAAA,EAAC;AAGP,kBAAgB,MAAM,IAAI,CAAC;A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,SAAO;AAAA,IACL,SAAS;AAAA,MACP,WAAW,QAAQ;AAAA,MACnB,aAAa,QAAQ;AAAA,MACrB,UAAU,QAAQ;AAAA,MAClB,YAAY,QAAQ;AAAA,MACpB;AAAA,MACA,UAAU,MAAMA,gBAAe,QAAQ,KAAK,GAAG,CAAC;AAAA,MAChD,GAAI,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;AAAA,MACnD,GAAI,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;AAAA,IACrD;AAAA,EACF;AACF;AAEA,eAAsB,+BACpB,UACA,SAC4B;AAC5B,QAAM,UAAU,YAAY,WAAW,CAAC,SAAS,MAAM,IAAI,SAAS;AACpE,QAAM,cAAc,gBAAgB,WAAW,CAAC,SAAS,UAAU,IAAI,SAAS;AAChF,QAAM,UAAU,sBAAsB,YAAY,SAAS,iBAAiB,MAAM,SAC9E,SAAS,iBAAiB,OAC1B;AAEJ,SAAO;AAAA,IACL,SAAS;AAAA,MACP,WAAW,QAAQ;AAAA,MACnB,aAAa,QAAQ;AAAA,MACrB,UAAU,SAAS,QAAQ,IAAI,YAAY;AAAA,MAC3C,YAAY,QAAQ;AAAA,MACpB;AAAA,MACA,uBAAuB;AAAA,MACvB,mBAAmB,SAAS;AAAA,MAC5B,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;AAAA,MAC7B,GAAI,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,EAAE,QAAQ,aAAa,WAAW,SAAS,UAAU,QAAQ,CAAC,GAAG,QAAQ;AAAA,MAC3H,GAAI,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;AAAA,IACrD;AAAA,EACF;AACF;","names":["readFileSync","homedir","Buffer","base","existsSync","homedir","join","createHash","existsSync","mkdirSync","readdirSync","readFileSync","homedir","join","digest","existsSync","join","homedir","readdirSync","readFileSync","existsSync","mkdirSync","readFileSync","writeFileSync","homedir","join","basename","consola","basename","consola","canonicalizeCliPermission","consola","existsSync","readFileSync","homedir","join","loadAuth","getIdpUrl","getAuthToken","discoverEndpoints","getGrantsEndpoint","apiFetch","getAuthToken","getIdpUrl","getGrantsEndpoint","apiFetch","discoverEndpoints","consola","computeCmdHash"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/config.ts"],"sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\n\nexport interface AuthData {\n idp: string\n access_token: string\n refresh_token?: string\n email: string\n expires_at: number\n}\n\nexport interface ApesConfig {\n defaults?: {\n idp?: string\n approval?: string\n }\n agent?: {\n key?: string\n email?: string\n }\n}\n\nconst CONFIG_DIR = join(homedir(), '.config', 'apes')\nconst AUTH_FILE = join(CONFIG_DIR, 'auth.json')\nconst CONFIG_FILE = join(CONFIG_DIR, 'config.toml')\n\nfunction ensureDir() {\n if (!existsSync(CONFIG_DIR)) {\n mkdirSync(CONFIG_DIR, { recursive: true })\n }\n}\n\nexport function loadAuth(): AuthData | null {\n if (!existsSync(AUTH_FILE))\n return null\n try {\n return JSON.parse(readFileSync(AUTH_FILE, 'utf-8'))\n }\n catch {\n return null\n }\n}\n\nexport function saveAuth(data: AuthData): void {\n ensureDir()\n writeFileSync(AUTH_FILE, JSON.stringify(data, null, 2), { mode: 0o600 })\n}\n\nexport function clearAuth(): void {\n if (existsSync(AUTH_FILE)) {\n writeFileSync(AUTH_FILE, '', { mode: 0o600 })\n }\n // Also wipe the [agent] section from config.toml so logout disables\n // auto-refresh. Preserves [defaults] so the IdP URL stays configured.\n if (existsSync(CONFIG_FILE)) {\n const existing = loadConfig()\n if (existing.agent) {\n const { agent: _removed, ...rest } = existing\n saveConfig(rest)\n }\n }\n}\n\nexport function loadConfig(): ApesConfig {\n if (!existsSync(CONFIG_FILE))\n return {}\n try {\n return parseTOML(readFileSync(CONFIG_FILE, 'utf-8'))\n }\n catch {\n return {}\n }\n}\n\nfunction parseTOML(content: string): ApesConfig {\n const config: ApesConfig = {}\n let section = ''\n\n for (const line of content.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed || trimmed.startsWith('#'))\n continue\n\n const sectionMatch = trimmed.match(/^\\[(.+)\\]$/)\n if (sectionMatch) {\n section = sectionMatch[1]!\n continue\n }\n\n const kvMatch = trimmed.match(/^(\\w+)\\s*=\\s*\"(.+)\"$/)\n if (kvMatch) {\n const [, key, value] = kvMatch\n if (section === 'defaults') {\n config.defaults = config.defaults || {}\n ;(config.defaults as Record<string, string>)[key!] = value!\n }\n else if (section === 'agent') {\n config.agent = config.agent || {}\n ;(config.agent as Record<string, string>)[key!] = value!\n }\n }\n }\n\n return config\n}\n\nexport function saveConfig(config: ApesConfig): void {\n ensureDir()\n const lines: string[] = []\n\n if (config.defaults) {\n lines.push('[defaults]')\n for (const [key, value] of Object.entries(config.defaults)) {\n if (value)\n lines.push(`${key} = \"${value}\"`)\n }\n lines.push('')\n }\n\n if (config.agent) {\n lines.push('[agent]')\n for (const [key, value] of Object.entries(config.agent)) {\n if (value)\n lines.push(`${key} = \"${value}\"`)\n }\n lines.push('')\n }\n\n writeFileSync(CONFIG_FILE, lines.join('\\n'), { mode: 0o600 })\n}\n\nexport function getIdpUrl(explicit?: string): string | null {\n if (explicit)\n return explicit\n if (process.env.APES_IDP)\n return process.env.APES_IDP\n\n const auth = loadAuth()\n if (auth?.idp)\n return auth.idp\n\n const config = loadConfig()\n if (config.defaults?.idp)\n return config.defaults.idp\n\n return null\n}\n\nexport function getAuthToken(): string | null {\n const auth = loadAuth()\n if (!auth)\n return null\n\n // Check expiry (with 30s buffer)\n if (auth.expires_at && Date.now() / 1000 > auth.expires_at - 30) {\n return null // expired\n }\n\n return auth.access_token\n}\n\nexport function getRequesterIdentity(): string | null {\n return loadAuth()?.email ?? null\n}\n\nexport { CONFIG_DIR, AUTH_FILE }\n"],"mappings":";;;AAAA,SAAS,YAAY,WAAW,cAAc,q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ACnB,WAAO,OAAO,SAAS;AAEzB,SAAO;AACT;AAEO,SAAS,eAA8B;AAC5C,QAAM,OAAO,SAAS;AACtB,MAAI,CAAC;AACH,WAAO;AAGT,MAAI,KAAK,cAAc,KAAK,IAAI,IAAI,MAAO,KAAK,aAAa,IAAI;AAC/D,WAAO;AAAA,EACT;AAEA,SAAO,KAAK;AACd;AAEO,SAAS,uBAAsC;AACpD,SAAO,SAAS,GAAG,SAAS;AAC9B;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
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;;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KAAK,IAAI;AAAA,EACjB,UACA;AACE,YAAQ,OAAO,IAAI,UAAU,QAAQ;AACrC,YAAQ,IAAI,QAAQ,UAAU;AAC9B,YAAQ,IAAI,WAAW,gBAAgB;AACvC,YAAQ,IAAI,UAAU,gBAAgB;AAAA,EACxC;AACF;","names":["consola","token","consola","consola","randomBytes","randomBytes","consola"]}
|
|
File without changes
|
|
File without changes
|