@openape/apes 0.9.2 → 0.9.3

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/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/ape-shell.ts","../src/commands/auth/login.ts","../src/commands/auth/resolve-login.ts","../src/commands/auth/logout.ts","../src/commands/auth/whoami.ts","../src/commands/grants/list.ts","../src/commands/grants/inbox.ts","../src/commands/grants/status.ts","../src/commands/grants/request.ts","../src/commands/grants/request-capability.ts","../src/commands/grants/approve.ts","../src/commands/grants/deny.ts","../src/commands/grants/revoke.ts","../src/commands/grants/run.ts","../src/commands/grants/token.ts","../src/commands/grants/delegate.ts","../src/commands/grants/delegations.ts","../src/commands/grants/delegation-revoke.ts","../src/commands/admin/index.ts","../src/commands/admin/users.ts","../src/commands/admin/ssh-keys.ts","../src/commands/adapter/index.ts","../src/commands/run.ts","../src/commands/explain.ts","../src/commands/config/get.ts","../src/commands/config/set.ts","../src/commands/fetch/index.ts","../src/commands/mcp/index.ts","../src/commands/init/index.ts","../src/commands/enroll.ts","../src/commands/register-user.ts","../src/commands/dns-check.ts","../src/commands/health.ts","../src/commands/workflows.ts","../src/guides/index.ts"],"sourcesContent":["import consola from 'consola'\nimport { rewriteApeShellArgs } from './ape-shell'\nimport { defineCommand, runMain } from 'citty'\nimport { loginCommand } from './commands/auth/login'\nimport { logoutCommand } from './commands/auth/logout'\nimport { whoamiCommand } from './commands/auth/whoami'\nimport { listCommand } from './commands/grants/list'\nimport { inboxCommand } from './commands/grants/inbox'\nimport { statusCommand } from './commands/grants/status'\nimport { requestCommand } from './commands/grants/request'\nimport { requestCapabilityCommand } from './commands/grants/request-capability'\nimport { approveCommand } from './commands/grants/approve'\nimport { denyCommand } from './commands/grants/deny'\nimport { revokeCommand } from './commands/grants/revoke'\nimport { runGrantCommand } from './commands/grants/run'\nimport { tokenCommand } from './commands/grants/token'\nimport { delegateCommand } from './commands/grants/delegate'\nimport { delegationsCommand } from './commands/grants/delegations'\nimport { delegationRevokeCommand } from './commands/grants/delegation-revoke'\nimport { adminCommand } from './commands/admin/index'\nimport { adapterCommand } from './commands/adapter/index'\nimport { runCommand } from './commands/run'\nimport { explainCommand } from './commands/explain'\nimport { configGetCommand } from './commands/config/get'\nimport { configSetCommand } from './commands/config/set'\nimport { fetchCommand } from './commands/fetch/index'\nimport { mcpCommand } from './commands/mcp/index'\nimport { initCommand } from './commands/init/index'\nimport { enrollCommand } from './commands/enroll'\nimport { registerUserCommand } from './commands/register-user'\nimport { dnsCheckCommand } from './commands/dns-check'\nimport { healthCommand } from './commands/health'\nimport { workflowsCommand } from './commands/workflows'\nimport { ApiError } from './http'\nimport { CliError, CliExit } from './errors'\n\n// Gracefully handle EPIPE when stdout is closed early (e.g. piped to `head`)\nprocess.stdout.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EPIPE') process.exit(0)\n throw err\n})\n\ndeclare const __VERSION__: string\n\n// ape-shell mode:\n// • `ape-shell -c <command>` rewrites to `apes run --shell -- bash -c <command>` (one-shot)\n// • `ape-shell` (no args), `-i`, `-l`, or invoked as a login shell → interactive REPL\n// Pass `process.argv0` explicitly so the wrapper script path (which uses\n// bash's `exec -a \"$0\"` to preserve the original argv[0] from login/sshd)\n// still benefits from login-shell detection when the cli.js is invoked\n// indirectly via the ape-shell-wrapper.sh shim.\nconst shellRewrite = rewriteApeShellArgs(process.argv, process.argv0)\nif (shellRewrite) {\n if (shellRewrite.action === 'rewrite') {\n process.argv = shellRewrite.argv\n }\n else if (shellRewrite.action === 'version') {\n console.log(`ape-shell ${__VERSION__} (OpenApe DDISA shell wrapper)`)\n process.exit(0)\n }\n else if (shellRewrite.action === 'help') {\n console.log(`ape-shell ${__VERSION__} — OpenApe DDISA shell wrapper`)\n console.log('')\n console.log('Usage:')\n console.log(' ape-shell Start interactive grant-mediated REPL')\n console.log(' ape-shell -c <command> Run a single command through the grant flow')\n console.log(' ape-shell -i | -l Force interactive mode')\n console.log('')\n console.log('Options:')\n console.log(' -c <command> Execute <command> via the apes grant flow and exit')\n console.log(' -i Interactive REPL (default when no args are given)')\n console.log(' -l, --login Login shell semantics — currently same as -i')\n console.log(' --version, -v Show ape-shell version')\n console.log(' --help, -h Show this help message')\n process.exit(0)\n }\n else if (shellRewrite.action === 'interactive') {\n // Hand control to the interactive REPL orchestrator. Never returns to\n // citty dispatch. Dynamic import so the startup path for `ape-shell -c`\n // stays lean (node-pty native module is only loaded when needed).\n const { runInteractiveShell } = await import('./shell/orchestrator.js')\n await runInteractiveShell()\n process.exit(0)\n }\n else {\n console.error('ape-shell: unsupported invocation. Try `ape-shell --help`.')\n process.exit(1)\n }\n}\n\nconst debug = process.argv.includes('--debug')\n\nconst grantsCommand = defineCommand({\n meta: {\n name: 'grants',\n description: 'Grant management',\n },\n subCommands: {\n list: listCommand,\n inbox: inboxCommand,\n status: statusCommand,\n request: requestCommand,\n 'request-capability': requestCapabilityCommand,\n approve: approveCommand,\n deny: denyCommand,\n revoke: revokeCommand,\n run: runGrantCommand,\n token: tokenCommand,\n delegate: delegateCommand,\n delegations: delegationsCommand,\n 'delegation-revoke': delegationRevokeCommand,\n },\n})\n\nconst configCommand = defineCommand({\n meta: {\n name: 'config',\n description: 'Configuration management',\n },\n subCommands: {\n get: configGetCommand,\n set: configSetCommand,\n },\n})\n\nconst main = defineCommand({\n meta: {\n name: 'apes',\n version: __VERSION__,\n description: 'Unified CLI for OpenApe',\n },\n subCommands: {\n init: initCommand,\n enroll: enrollCommand,\n 'register-user': registerUserCommand,\n 'dns-check': dnsCheckCommand,\n login: loginCommand,\n logout: logoutCommand,\n whoami: whoamiCommand,\n health: healthCommand,\n grants: grantsCommand,\n admin: adminCommand,\n run: runCommand,\n explain: explainCommand,\n adapter: adapterCommand,\n config: configCommand,\n fetch: fetchCommand,\n mcp: mcpCommand,\n workflows: workflowsCommand,\n },\n})\n\nrunMain(main).catch((err) => {\n if (err instanceof CliExit) {\n process.exit(err.exitCode)\n }\n if (err instanceof CliError) {\n consola.error(err.message)\n process.exit(err.exitCode)\n }\n if (debug) {\n consola.error(err)\n }\n else {\n consola.error(err instanceof ApiError ? err.message : err instanceof Error ? err.message : String(err))\n }\n process.exit(1)\n})\n","import path from 'node:path'\n\n/**\n * Possible actions emitted by `rewriteApeShellArgs` for the caller to\n * dispatch. `rewrite` means argv has been transformed and the normal CLI\n * command dispatch should continue with the new argv. `interactive` means\n * the caller should hand control to the interactive REPL. The other\n * actions print version/help/error text and exit.\n */\nexport type ApeShellAction =\n | { action: 'rewrite', argv: string[] }\n | { action: 'version' }\n | { action: 'help' }\n | { action: 'error' }\n | { action: 'interactive' }\n\n/**\n * Decides how `ape-shell` was invoked and what the caller should do next.\n * Backward compatibility is strict: any invocation with `-c \"<command>\"`\n * keeps the historical rewrite behavior so `SHELL=$(which ape-shell) <prog>`\n * patterns (e.g. `SHELL=ape-shell openclaw tui`) continue to work.\n *\n * Detection strategy:\n * 1. `process.env.APES_SHELL_WRAPPER === '1'` is the strongest signal —\n * it means we were invoked via the ape-shell-wrapper.sh shell script,\n * which hoists node onto PATH before exec-ing cli.js. In that case\n * argv[1] becomes `cli.js` (or some dist/chunk file) and the old\n * basename check fails, so we trust the wrapper's declaration.\n * 2. Otherwise fall back to `argv[1]` basename matching literal\n * `ape-shell` / `ape-shell.js` (the direct-symlink invocation path).\n *\n * After detection, the rest of the rules decide the action (first match):\n * • `-c <command>` → rewrite to `apes run --shell -- bash -c <command>`.\n * • `--version` / `-v` → version action.\n * • `--help` / `-h` → help action.\n * • no args, `-i`, `-l`, `--login`, or a login-shell convention dash\n * prefix (on argv[1] or argv0) → interactive REPL.\n * • anything else → error action.\n */\nexport function rewriteApeShellArgs(argv: string[], argv0?: string): ApeShellAction | null {\n const rawInvokedAs = argv[1] ?? ''\n // sshd/login use a leading dash on argv[0] to signal \"login shell\".\n // Strip it for the basename comparison, but remember the flag. The dash\n // may appear on argv[1] (direct invocation) or on the separately-passed\n // argv0 parameter (wrapper invocation — shell `exec -a \"$0\"` sets node's\n // actual argv[0] / `process.argv0` independently from argv[1]).\n const dashFromArgv1 = rawInvokedAs.startsWith('-')\n const dashFromArgv0 = typeof argv0 === 'string' && argv0.startsWith('-')\n const looksLikeLoginShell = dashFromArgv1 || dashFromArgv0\n const normalizedInvokedAs = dashFromArgv1 ? rawInvokedAs.slice(1) : rawInvokedAs\n const invokedAs = path.basename(normalizedInvokedAs)\n\n // Primary detection: explicit wrapper signal via env var. Takes\n // precedence because argv-based detection gets clobbered when the\n // wrapper execs node directly and argv[1] becomes cli.js.\n const wrapperEnv = typeof process !== 'undefined' && process.env?.APES_SHELL_WRAPPER === '1'\n\n // Secondary detection: argv[1] basename matches literal `ape-shell` or\n // `ape-shell.js` — the direct-symlink invocation path.\n const argvMatch = invokedAs === 'ape-shell' || invokedAs === 'ape-shell.js'\n\n if (!wrapperEnv && !argvMatch)\n return null\n\n const shellArgs = argv.slice(2)\n\n // -c <command> is the historical one-shot path — must stay untouched so\n // programs that use `$SHELL -c \"<cmd>\"` (openclaw tui, xargs, git hooks,\n // sshd non-interactive, etc.) continue to work unchanged.\n if (shellArgs[0] === '-c' && shellArgs.length > 1) {\n return { action: 'rewrite', argv: [argv[0]!, argv[1]!, 'run', '--shell', '--', 'bash', '-c', ...shellArgs.slice(1)] }\n }\n\n if (shellArgs[0] === '--version' || shellArgs[0] === '-v')\n return { action: 'version' }\n\n if (shellArgs[0] === '--help' || shellArgs[0] === '-h')\n return { action: 'help' }\n\n // No positional args, explicit interactive flag, or login-shell\n // convention (`looksLikeLoginShell` detected from the dash-prefixed\n // argv[1] above) → enter the interactive REPL.\n if (\n shellArgs.length === 0\n || shellArgs[0] === '-i'\n || shellArgs[0] === '-l'\n || shellArgs[0] === '--login'\n || looksLikeLoginShell\n ) {\n return { action: 'interactive' }\n }\n\n return { action: 'error' }\n}\n","import { Buffer } from 'node:buffer'\nimport { execFile } from 'node:child_process'\nimport { createServer } from 'node:http'\nimport { homedir } from 'node:os'\nimport { resolve as resolvePath } from 'node:path'\nimport { defineCommand } from 'citty'\nimport { generateCodeChallenge, generateCodeVerifier } from '@openape/core'\nimport consola from 'consola'\nimport { loadConfig, saveAuth, saveConfig } from '../../config'\nimport { getAgentAuthenticateEndpoint, getAgentChallengeEndpoint } from '../../http'\nimport { CliError } from '../../errors'\nimport { resolveLoginInputs } from './resolve-login'\n\nconst CALLBACK_PORT = 9876\nconst CLIENT_ID = 'grapes-cli'\n\nexport const loginCommand = defineCommand({\n meta: {\n name: 'login',\n description: 'Authenticate with an OpenApe IdP',\n },\n args: {\n idp: {\n type: 'string',\n description: 'IdP URL (e.g. https://id.openape.at). Auto-discovered via DDISA DNS if omitted.',\n },\n key: {\n type: 'string',\n description: 'Path to agent private key. Defaults to ~/.ssh/id_ed25519 if present.',\n },\n email: {\n type: 'string',\n description: 'Agent email. Extracted from <key>.pub comment if omitted.',\n },\n browser: {\n type: 'boolean',\n description: 'Force browser (PKCE) login even if an SSH key exists',\n },\n },\n async run({ args }) {\n const resolved = await resolveLoginInputs({\n key: args.key,\n idp: args.idp,\n email: args.email,\n browser: args.browser,\n })\n\n if (resolved.keyPath) {\n if (!resolved.email) {\n throw new CliError(\n `Agent email required for key-based login. Add an email comment to `\n + `${resolved.keyPath}.pub (ssh-keygen -C <email>) or pass --email <agent-email>.`,\n )\n }\n if (!resolved.idp) {\n const domain = resolved.email.split('@')[1]\n throw new CliError(\n `No IdP found for ${resolved.email}.\\n\\n`\n + `There is no DDISA TXT record for ${domain} and no --idp was provided.\\n\\n`\n + `Options:\\n`\n + ` • Run your own IdP (recommended for production)\\n`\n + ` See: https://docs.openape.at\\n`\n + ` • Publish a DDISA TXT record for your domain:\\n`\n + ` _ddisa.${domain} TXT \"v=ddisa1 idp=https://your-idp.example\"\\n`\n + ` • Use OpenApe's free hosted IdP for testing:\\n`\n + ` apes login --idp https://id.openape.at`,\n )\n }\n await loginWithKey(resolved.idp, resolved.keyPath, resolved.email)\n }\n else {\n if (!resolved.idp) {\n throw new CliError('IdP URL required for browser login. Use --idp <url> or set APES_IDP.')\n }\n await loginWithPKCE(resolved.idp)\n }\n },\n})\n\nfunction openBrowser(url: string) {\n const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open'\n execFile(cmd, [url], () => {})\n}\n\nasync function loginWithPKCE(idp: string) {\n const codeVerifier = generateCodeVerifier()\n const codeChallenge = await generateCodeChallenge(codeVerifier)\n const redirectUri = `http://localhost:${CALLBACK_PORT}/callback`\n\n const state = crypto.randomUUID()\n const nonce = crypto.randomUUID()\n\n const authUrl = new URL(`${idp}/authorize`)\n authUrl.searchParams.set('response_type', 'code')\n authUrl.searchParams.set('client_id', CLIENT_ID)\n authUrl.searchParams.set('redirect_uri', redirectUri)\n authUrl.searchParams.set('code_challenge', codeChallenge)\n authUrl.searchParams.set('code_challenge_method', 'S256')\n authUrl.searchParams.set('state', state)\n authUrl.searchParams.set('nonce', nonce)\n authUrl.searchParams.set('scope', 'openid email profile offline_access')\n\n // Start local callback server\n const code = await new Promise<string>((resolve, reject) => {\n const server = createServer((req, res) => {\n const url = new URL(req.url!, `http://localhost:${CALLBACK_PORT}`)\n if (url.pathname === '/callback') {\n const authCode = url.searchParams.get('code')\n const error = url.searchParams.get('error')\n\n if (error) {\n res.writeHead(200, { 'Content-Type': 'text/html' })\n res.end('<h1>Login failed</h1><p>You can close this window.</p>')\n server.close()\n reject(new Error(`Auth error: ${error}`))\n return\n }\n\n if (authCode) {\n res.writeHead(200, { 'Content-Type': 'text/html' })\n res.end('<h1>Login successful!</h1><p>You can close this window.</p>')\n server.close()\n resolve(authCode)\n return\n }\n\n res.writeHead(400)\n res.end('Missing code')\n }\n else {\n res.writeHead(404)\n res.end()\n }\n })\n\n server.listen(CALLBACK_PORT, () => {\n // Always print the URL so the user can copy it manually — headless SSH\n // sessions, containers, and restricted-user shells cannot open a browser.\n // The `open` attempt below is fire-and-forget convenience only.\n console.log('')\n console.log('Visit the following URL in a browser to authenticate:')\n console.log('')\n console.log(` ${authUrl.toString()}`)\n console.log('')\n consola.info(`Waiting for authentication callback on ${redirectUri} ...`)\n openBrowser(authUrl.toString())\n })\n\n // Timeout after 5 minutes\n const timeout = setTimeout(() => {\n server.close()\n reject(new Error('Login timed out'))\n }, 300_000)\n timeout.unref()\n })\n\n // Exchange code for tokens\n const tokenResponse = await fetch(`${idp}/token`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n grant_type: 'authorization_code',\n code,\n code_verifier: codeVerifier,\n redirect_uri: redirectUri,\n client_id: CLIENT_ID,\n }),\n })\n\n if (!tokenResponse.ok) {\n const text = await tokenResponse.text()\n throw new CliError(`Token exchange failed: ${text}`)\n }\n\n const tokens = await tokenResponse.json() as {\n access_token?: string\n id_token?: string\n refresh_token?: string\n expires_in?: number\n assertion?: string\n }\n\n const accessToken = tokens.access_token || tokens.id_token || tokens.assertion\n if (!accessToken) {\n throw new CliError('No access token received')\n }\n\n // Decode JWT to get email\n const payload = JSON.parse(atob(accessToken.split('.')[1]!))\n\n saveAuth({\n idp,\n access_token: accessToken,\n ...(tokens.refresh_token ? { refresh_token: tokens.refresh_token } : {}),\n email: payload.email || payload.sub,\n expires_at: Math.floor(Date.now() / 1000) + (tokens.expires_in || 3600),\n })\n\n consola.success(`Logged in as ${payload.email || payload.sub}`)\n}\n\nasync function loginWithKey(idp: string, keyPath: string, agentEmail: string) {\n const { readFileSync } = await import('node:fs')\n const { sign } = await import('node:crypto')\n const { loadEd25519PrivateKey } = await import('../../ssh-key.js')\n\n // Use challenge-response auth (endpoint resolved via OIDC discovery)\n const challengeUrl = await getAgentChallengeEndpoint(idp)\n const challengeResp = await fetch(challengeUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ agent_id: agentEmail }),\n })\n\n if (!challengeResp.ok) {\n throw new CliError(`Challenge failed: ${await challengeResp.text()}`)\n }\n\n const { challenge } = await challengeResp.json() as { challenge: string }\n\n // Sign challenge with Ed25519 private key (supports OpenSSH + PKCS8 format)\n const keyContent = readFileSync(keyPath, 'utf-8')\n const privateKey = loadEd25519PrivateKey(keyContent)\n const signature = sign(null, Buffer.from(challenge), privateKey).toString('base64')\n\n // Authenticate (endpoint resolved via OIDC discovery)\n const authenticateUrl = await getAgentAuthenticateEndpoint(idp)\n const authResp = await fetch(authenticateUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n agent_id: agentEmail,\n challenge,\n signature,\n }),\n })\n\n if (!authResp.ok) {\n throw new CliError(`Authentication failed: ${await authResp.text()}`)\n }\n\n const { token, expires_in } = await authResp.json() as { token: string, expires_in: number }\n\n saveAuth({\n idp,\n access_token: token,\n email: agentEmail,\n expires_at: Math.floor(Date.now() / 1000) + (expires_in || 3600),\n })\n\n // Persist the resolved key path + email to config.toml so future apes/ape-shell\n // invocations can auto-refresh via Ed25519 challenge-response without a new\n // `apes login`. Merge with existing config so [defaults] is preserved.\n const absoluteKeyPath = resolvePath(keyPath.replace(/^~/, homedir()))\n const existingConfig = loadConfig()\n saveConfig({\n ...existingConfig,\n agent: {\n ...existingConfig.agent,\n key: absoluteKeyPath,\n email: agentEmail,\n },\n })\n\n consola.success(`Logged in as ${agentEmail}`)\n consola.info(`Auto-refresh enabled (key path saved to ~/.config/apes/config.toml)`)\n}\n","import { existsSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { resolveDDISA } from '@openape/core'\nimport consola from 'consola'\nimport { loadConfig } from '../../config'\nimport { readPublicKeyComment } from '../../ssh-key'\n\nexport interface LoginInputs {\n key?: string\n idp?: string\n email?: string\n browser?: boolean\n}\n\nexport interface ResolvedLoginInputs {\n keyPath?: string\n email?: string\n idp?: string\n}\n\nconst DEFAULT_KEY = join(homedir(), '.ssh', 'id_ed25519')\n\n/**\n * Resolve login inputs by walking a fallback cascade:\n * 1. explicit flag\n * 2. environment variable\n * 3. ~/.config/apes/config.toml\n * 4. derivation (default key path, pub key comment, DDISA DNS)\n *\n * When `browser` is true, no key is resolved so the caller falls back to PKCE.\n */\nexport async function resolveLoginInputs(\n flags: LoginInputs,\n): Promise<ResolvedLoginInputs> {\n const config = loadConfig()\n\n // 1. Key path — skipped entirely in forced browser mode\n let keyPath: string | undefined\n if (!flags.browser) {\n if (flags.key) {\n keyPath = flags.key\n }\n else if (process.env.APES_KEY) {\n keyPath = process.env.APES_KEY\n consola.info(`Using key from APES_KEY: ${keyPath}`)\n }\n else if (config.agent?.key) {\n keyPath = config.agent.key\n consola.info(`Using key from config: ${keyPath}`)\n }\n else if (existsSync(DEFAULT_KEY)) {\n keyPath = DEFAULT_KEY\n consola.info(`Using default key: ${keyPath}`)\n }\n }\n\n // 2. Email\n let email: string | undefined\n if (flags.email) {\n email = flags.email\n }\n else if (process.env.APES_EMAIL) {\n email = process.env.APES_EMAIL\n }\n else if (config.agent?.email) {\n email = config.agent.email\n }\n else if (keyPath) {\n const comment = readPublicKeyComment(`${keyPath}.pub`)\n if (comment && comment.includes('@')) {\n email = comment\n consola.info(`Using email from ${keyPath}.pub comment: ${email}`)\n }\n }\n\n // 3. IdP\n let idp: string | undefined\n if (flags.idp) {\n idp = flags.idp\n }\n else if (process.env.APES_IDP) {\n idp = process.env.APES_IDP\n }\n else if (process.env.GRAPES_IDP) {\n idp = process.env.GRAPES_IDP\n }\n else if (config.defaults?.idp) {\n idp = config.defaults.idp\n }\n else if (email && email.includes('@')) {\n const domain = email.split('@')[1]!\n try {\n const record = await resolveDDISA(domain)\n if (record?.idp) {\n idp = record.idp\n consola.info(`Discovered IdP via DDISA (_ddisa.${domain}): ${idp}`)\n }\n }\n catch {\n // DNS failure is non-fatal — caller will surface a clear error\n }\n }\n\n return { keyPath, email, idp }\n}\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { clearAuth } from '../../config'\n\nexport const logoutCommand = defineCommand({\n meta: {\n name: 'logout',\n description: 'Clear stored credentials',\n },\n run() {\n clearAuth()\n consola.success('Logged out.')\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { loadAuth } from '../../config'\nimport { CliError } from '../../errors'\n\nexport const whoamiCommand = defineCommand({\n meta: {\n name: 'whoami',\n description: 'Show current identity',\n },\n run() {\n const auth = loadAuth()\n if (!auth) {\n throw new CliError('Not logged in. Run `apes login` first.')\n }\n\n const isAgent = auth.email.includes('agent+')\n const expiresAt = new Date(auth.expires_at * 1000).toISOString()\n const isExpired = Date.now() / 1000 > auth.expires_at\n\n console.log(`Email: ${auth.email}`)\n console.log(`Type: ${isAgent ? 'agent' : 'human'}`)\n console.log(`IdP: ${auth.idp}`)\n console.log(`Token: ${isExpired ? '⚠ EXPIRED' : 'valid'} (until ${expiresAt})`)\n\n if (isExpired) {\n consola.warn('Token is expired. Run `apes login` to re-authenticate.')\n }\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl, loadAuth } from '../../config'\nimport { apiFetch, getGrantsEndpoint } from '../../http'\nimport { CliError } from '../../errors'\n\ninterface Grant {\n id: string\n type: string\n status: string\n requester: string\n owner: string\n request: {\n command?: string[]\n grant_type?: string\n reason?: string\n }\n created_at?: string\n}\n\ninterface PaginatedGrants {\n data: Grant[]\n pagination: {\n cursor: string | null\n has_more: boolean\n }\n}\n\nexport const listCommand = defineCommand({\n meta: {\n name: 'list',\n description: 'List your grants (as requester)',\n },\n args: {\n status: {\n type: 'string',\n description: 'Filter by status (pending, approved, denied, revoked, used)',\n },\n all: {\n type: 'boolean',\n description: 'Show all visible grants (not just your own)',\n default: false,\n },\n json: {\n type: 'boolean',\n description: 'Output as JSON',\n default: false,\n },\n limit: {\n type: 'string',\n description: 'Max results (default 20, max 100)',\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()\n if (!idp) {\n throw new CliError('No IdP URL configured. Run `apes login` first or pass --idp.')\n }\n\n const auth = loadAuth()\n\n const grantsUrl = await getGrantsEndpoint(idp)\n const params = new URLSearchParams()\n if (args.status)\n params.set('status', args.status)\n if (args.limit)\n params.set('limit', args.limit)\n const query = params.toString() ? `?${params.toString()}` : ''\n\n const response = await apiFetch<PaginatedGrants>(`${grantsUrl}${query}`)\n\n let grants = response.data\n\n // Filter to own grants unless --all\n if (!args.all && auth?.email) {\n grants = grants.filter(g => g.requester === auth.email)\n }\n\n if (args.json) {\n console.log(JSON.stringify(args.all ? response : { ...response, data: grants }, null, 2))\n return\n }\n\n if (grants.length === 0) {\n consola.info(args.all ? 'No grants found.' : 'No grants found. Use --all to see all visible grants.')\n return\n }\n\n for (const grant of grants) {\n const cmd = grant.request?.command?.join(' ') || '(no command)'\n const type = grant.request?.grant_type || grant.type\n console.log(`${grant.id} ${grant.status.padEnd(8)} ${type.padEnd(6)} ${cmd}`)\n if (grant.request?.reason) {\n console.log(` Reason: ${grant.request.reason}`)\n }\n }\n\n if (response.pagination.has_more) {\n consola.info('More results available. Use --limit or pagination cursor.')\n }\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl, loadAuth } from '../../config'\nimport { apiFetch, getGrantsEndpoint } from '../../http'\nimport { CliError } from '../../errors'\n\ninterface Grant {\n id: string\n type: string\n status: string\n requester: string\n owner: string\n request: {\n command?: string[]\n grant_type?: string\n reason?: string\n }\n created_at?: string\n}\n\ninterface PaginatedGrants {\n data: Grant[]\n pagination: {\n cursor: string | null\n has_more: boolean\n }\n}\n\nexport const inboxCommand = defineCommand({\n meta: {\n name: 'inbox',\n description: 'Show grants awaiting your approval',\n },\n args: {\n json: {\n type: 'boolean',\n description: 'Output as JSON',\n default: false,\n },\n limit: {\n type: 'string',\n description: 'Max results (default 20, max 100)',\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()\n if (!idp) {\n throw new CliError('No IdP URL configured. Run `apes login` first.')\n }\n\n const auth = loadAuth()\n if (!auth) {\n throw new CliError('Not logged in. Run `apes login` first.')\n }\n\n const grantsUrl = await getGrantsEndpoint(idp)\n const params = new URLSearchParams()\n params.set('status', 'pending')\n if (args.limit)\n params.set('limit', args.limit)\n const query = `?${params.toString()}`\n\n const response = await apiFetch<PaginatedGrants>(`${grantsUrl}${query}`)\n\n // Filter out own requests — inbox shows only grants from others\n const grants = response.data.filter(g => g.requester !== auth.email)\n\n if (args.json) {\n console.log(JSON.stringify({ ...response, data: grants }, null, 2))\n return\n }\n\n if (grants.length === 0) {\n consola.info('No pending grants to approve.')\n return\n }\n\n consola.info(`${grants.length} grant(s) awaiting approval:\\n`)\n\n for (const grant of grants) {\n const cmd = grant.request?.command?.join(' ') || '(no command)'\n const type = grant.request?.grant_type || grant.type\n console.log(`${grant.id} ${type.padEnd(6)} from ${grant.requester}`)\n console.log(` Command: ${cmd}`)\n if (grant.request?.reason) {\n console.log(` Reason: ${grant.request.reason}`)\n }\n if (grant.created_at) {\n console.log(` Created: ${grant.created_at}`)\n }\n console.log()\n }\n\n consola.info('Use `apes grants approve <id>` or `apes grants deny <id>` to respond.')\n },\n})\n","import { defineCommand } from 'citty'\nimport { getIdpUrl } from '../../config'\nimport { apiFetch, getGrantsEndpoint } from '../../http'\n\n/**\n * Shape returned by `GET /grants/<id>` on the OpenApe IdP. Matches the\n * free-idp response as of 2026-04: `requester`, `target_host`, `audience`,\n * `grant_type`, etc. all live under the nested `request` object. Top-level\n * `type` is a legacy field that is currently always `null`. Timestamps are\n * unix seconds (numbers), not ISO strings.\n */\ninterface GrantDetail {\n id: string\n type?: string | null\n status: string\n request?: {\n requester?: string\n target_host?: string\n audience?: string\n grant_type?: string\n command?: string[]\n reason?: string\n }\n created_at?: number\n decided_at?: number\n decided_by?: string\n used_at?: number\n expires_at?: number\n}\n\n/** Unix seconds → ISO-8601 with graceful fallback for bogus values. */\nfunction formatTs(ts: number | undefined): string | undefined {\n if (ts === undefined || ts === null)\n return undefined\n const ms = ts * 1000\n if (!Number.isFinite(ms))\n return undefined\n return new Date(ms).toISOString()\n}\n\nexport const statusCommand = defineCommand({\n meta: {\n name: 'status',\n description: 'Show grant status',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Grant ID',\n required: true,\n },\n json: {\n type: 'boolean',\n description: 'Output as JSON',\n default: false,\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()!\n const grantsUrl = await getGrantsEndpoint(idp)\n const grant = await apiFetch<GrantDetail>(`${grantsUrl}/${args.id}`)\n\n if (args.json) {\n console.log(JSON.stringify(grant, null, 2))\n return\n }\n\n console.log(`Grant: ${grant.id}`)\n console.log(`Status: ${grant.status}`)\n if (grant.request?.audience)\n console.log(`Audience: ${grant.request.audience}`)\n if (grant.request?.requester)\n console.log(`Requester: ${grant.request.requester}`)\n if (grant.request?.target_host)\n console.log(`Host: ${grant.request.target_host}`)\n if (grant.request?.command)\n console.log(`Command: ${grant.request.command.join(' ')}`)\n if (grant.request?.grant_type)\n console.log(`Approval: ${grant.request.grant_type}`)\n if (grant.request?.reason)\n console.log(`Reason: ${grant.request.reason}`)\n const createdAt = formatTs(grant.created_at)\n if (createdAt)\n console.log(`Created: ${createdAt}`)\n if (grant.decided_by)\n console.log(`Decided by: ${grant.decided_by}`)\n const decidedAt = formatTs(grant.decided_at)\n if (decidedAt)\n console.log(`Decided at: ${decidedAt}`)\n const usedAt = formatTs(grant.used_at)\n if (usedAt)\n console.log(`Used at: ${usedAt}`)\n const expiresAt = formatTs(grant.expires_at)\n if (expiresAt)\n console.log(`Expires: ${expiresAt}`)\n },\n})\n","import { hostname } from 'node:os'\nimport { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl, loadAuth } from '../../config'\nimport { parseDuration } from '../../duration'\nimport { apiFetch, getGrantsEndpoint } from '../../http'\nimport { CliError } from '../../errors'\n\nexport const requestCommand = defineCommand({\n meta: {\n name: 'request',\n description: 'Request a new grant',\n },\n args: {\n command: {\n type: 'positional',\n description: 'Command to request permission for',\n required: true,\n },\n audience: {\n type: 'string',\n description: 'Service identifier (e.g. \"escapes\", \"proxy\")',\n required: true,\n },\n host: {\n type: 'string',\n description: 'Target host (default: system hostname)',\n },\n reason: {\n type: 'string',\n description: 'Reason for the request',\n },\n approval: {\n type: 'string',\n description: 'Approval type: once, timed, always',\n default: 'once',\n },\n duration: {\n type: 'string',\n description: 'Duration for timed grants (e.g. 30m, 1h, 7d)',\n },\n 'run-as': {\n type: 'string',\n description: 'Execute as this user (e.g. openclaw, root)',\n },\n wait: {\n type: 'boolean',\n description: 'Wait for approval',\n default: false,\n },\n },\n async run({ args }) {\n const auth = loadAuth()\n if (!auth) {\n throw new CliError('Not logged in. Run `apes login` first.')\n }\n\n const idp = getIdpUrl()!\n const grantsUrl = await getGrantsEndpoint(idp)\n const command = args.command.split(' ')\n const targetHost = args.host || hostname()\n\n const duration = args.duration ? parseDuration(args.duration) : undefined\n\n const grant = await apiFetch<{ id: string, status: string }>(grantsUrl, {\n method: 'POST',\n body: {\n requester: auth.email,\n target_host: targetHost,\n audience: args.audience,\n grant_type: args.approval,\n command,\n reason: args.reason || command.join(' '),\n ...(duration != null ? { duration } : {}),\n ...(args['run-as'] ? { run_as: args['run-as'] } : {}),\n },\n })\n\n consola.success(`Grant requested: ${grant.id} (status: ${grant.status})`)\n\n if (args.wait) {\n consola.info('Waiting for approval...')\n await waitForApproval(grantsUrl, grant.id)\n }\n },\n})\n\nasync function waitForApproval(grantsUrl: string, grantId: string): Promise<void> {\n const maxWait = 300_000 // 5 minutes\n const interval = 3_000\n const start = Date.now()\n\n while (Date.now() - start < maxWait) {\n const grant = await apiFetch<{ status: string }>(`${grantsUrl}/${grantId}`)\n\n if (grant.status === 'approved') {\n consola.success('Grant approved!')\n return\n }\n if (grant.status === 'denied') {\n throw new CliError('Grant denied.')\n }\n if (grant.status === 'revoked') {\n throw new CliError('Grant revoked.')\n }\n\n await new Promise(r => setTimeout(r, interval))\n }\n\n throw new CliError('Timed out waiting for approval.')\n}\n","import { hostname } from 'node:os'\nimport { buildStructuredCliGrantRequest, loadAdapter, resolveCapabilityRequest } from '../../shapes/index.js'\nimport { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl, loadAuth } from '../../config'\nimport { parseDuration } from '../../duration'\nimport { apiFetch, getGrantsEndpoint } from '../../http'\nimport { CliError } from '../../errors'\n\nfunction parseCapabilityArgs(rawArgs: string[]): {\n cliId: string\n adapter?: string\n idp?: string\n approval: 'once' | 'timed' | 'always'\n reason?: string\n duration?: number\n runAs?: string\n wait: boolean\n resources: string[]\n selectors: string[]\n actions: string[]\n} {\n const tokens = [...rawArgs]\n if (tokens[0] === 'request-capability') {\n tokens.shift()\n }\n\n const cliId = tokens.shift()\n if (!cliId || cliId.startsWith('-')) {\n throw new Error('Missing CLI identifier')\n }\n\n const resources: string[] = []\n const selectors: string[] = []\n const actions: string[] = []\n let adapter: string | undefined\n let idp: string | undefined\n let approval: 'once' | 'timed' | 'always' = 'once'\n let reason: string | undefined\n let duration: number | undefined\n let runAs: string | undefined\n let wait = false\n\n for (let index = 0; index < tokens.length; index += 1) {\n const token = tokens[index]!\n const next = tokens[index + 1]\n switch (token) {\n case '--resource':\n if (!next)\n throw new Error('Missing value for --resource')\n resources.push(next)\n index += 1\n break\n case '--selector':\n if (!next)\n throw new Error('Missing value for --selector')\n selectors.push(next)\n index += 1\n break\n case '--action':\n if (!next)\n throw new Error('Missing value for --action')\n actions.push(next)\n index += 1\n break\n case '--adapter':\n if (!next)\n throw new Error('Missing value for --adapter')\n adapter = next\n index += 1\n break\n case '--idp':\n if (!next)\n throw new Error('Missing value for --idp')\n idp = next\n index += 1\n break\n case '--approval':\n if (!next || !['once', 'timed', 'always'].includes(next)) {\n throw new Error('Approval must be one of: once, timed, always')\n }\n approval = next as 'once' | 'timed' | 'always'\n index += 1\n break\n case '--reason':\n if (!next)\n throw new Error('Missing value for --reason')\n reason = next\n index += 1\n break\n case '--duration':\n if (!next)\n throw new Error('Missing value for --duration')\n duration = parseDuration(next)\n index += 1\n break\n case '--run-as':\n if (!next)\n throw new Error('Missing value for --run-as')\n runAs = next\n index += 1\n break\n case '--wait':\n wait = true\n break\n default:\n throw new Error(`Unknown argument: ${token}`)\n }\n }\n\n return {\n cliId,\n adapter,\n idp,\n approval,\n reason,\n duration,\n runAs,\n wait,\n resources,\n selectors,\n actions,\n }\n}\n\nasync function waitForApproval(grantsUrl: string, grantId: string): Promise<void> {\n const maxWait = 300_000\n const interval = 3_000\n const start = Date.now()\n\n while (Date.now() - start < maxWait) {\n const grant = await apiFetch<{ status: string }>(`${grantsUrl}/${grantId}`)\n if (grant.status === 'approved') {\n consola.success('Grant approved!')\n return\n }\n if (grant.status === 'denied') {\n throw new CliError('Grant denied.')\n }\n if (grant.status === 'revoked') {\n throw new CliError('Grant revoked.')\n }\n await new Promise(resolve => setTimeout(resolve, interval))\n }\n\n throw new CliError('Timed out waiting for approval.')\n}\n\nexport const requestCapabilityCommand = defineCommand({\n meta: {\n name: 'request-capability',\n description: 'Request a structured CLI capability grant',\n },\n args: {\n 'cliId': {\n type: 'positional',\n description: 'CLI adapter identifier (e.g. docker, kubectl)',\n required: true,\n },\n 'resource': {\n type: 'string',\n description: 'Resource scope (repeatable)',\n },\n 'selector': {\n type: 'string',\n description: 'Selector filter (repeatable)',\n },\n 'action': {\n type: 'string',\n description: 'Action to permit (repeatable)',\n },\n 'adapter': {\n type: 'string',\n description: 'Explicit path to adapter TOML file',\n },\n 'idp': {\n type: 'string',\n description: 'IdP URL',\n },\n 'approval': {\n type: 'string',\n description: 'Approval type: once, timed, always',\n default: 'once',\n },\n 'reason': {\n type: 'string',\n description: 'Reason for the request',\n },\n 'duration': {\n type: 'string',\n description: 'Duration for timed grants (e.g. 30m, 1h, 7d)',\n },\n 'run-as': {\n type: 'string',\n description: 'Execute as this user (e.g. root)',\n },\n 'wait': {\n type: 'boolean',\n description: 'Wait for approval before returning',\n default: false,\n },\n },\n async run({ rawArgs }) {\n const auth = loadAuth()\n if (!auth) {\n throw new CliError('Not logged in. Run `apes login` first.')\n }\n\n const parsed = parseCapabilityArgs(rawArgs)\n const idp = getIdpUrl(parsed.idp)\n if (!idp) {\n throw new CliError('No IdP URL configured. Use --idp or log in first.')\n }\n\n const loaded = loadAdapter(parsed.cliId, parsed.adapter)\n const resolved = resolveCapabilityRequest(loaded, {\n resources: parsed.resources,\n selectors: parsed.selectors,\n actions: parsed.actions,\n })\n\n const { request } = await buildStructuredCliGrantRequest(resolved, {\n requester: auth.email,\n target_host: hostname(),\n grant_type: parsed.approval,\n ...(parsed.reason ? { reason: parsed.reason } : {}),\n })\n\n if (parsed.duration != null) {\n request.duration = parsed.duration\n }\n if (parsed.runAs) {\n request.run_as = parsed.runAs\n }\n\n const grantsUrl = await getGrantsEndpoint(idp)\n const grant = await apiFetch<{ id: string, status: string }>(grantsUrl, {\n method: 'POST',\n idp,\n body: request,\n })\n\n consola.success(`Grant requested: ${grant.id} (status: ${grant.status})`)\n\n if (parsed.wait) {\n consola.info('Waiting for approval...')\n await waitForApproval(grantsUrl, grant.id)\n }\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl } from '../../config'\nimport { apiFetch, getGrantsEndpoint } from '../../http'\n\nexport const approveCommand = defineCommand({\n meta: {\n name: 'approve',\n description: 'Approve a grant request',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Grant ID',\n required: true,\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()!\n const grantsUrl = await getGrantsEndpoint(idp)\n await apiFetch(`${grantsUrl}/${args.id}/approve`, {\n method: 'POST',\n })\n consola.success(`Grant ${args.id} approved.`)\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl } from '../../config'\nimport { apiFetch, getGrantsEndpoint } from '../../http'\n\nexport const denyCommand = defineCommand({\n meta: {\n name: 'deny',\n description: 'Deny a grant request',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Grant ID',\n required: true,\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()!\n const grantsUrl = await getGrantsEndpoint(idp)\n await apiFetch(`${grantsUrl}/${args.id}/deny`, {\n method: 'POST',\n })\n consola.success(`Grant ${args.id} denied.`)\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getAuthToken, getIdpUrl, loadAuth } from '../../config'\nimport { apiFetch, getGrantsEndpoint } from '../../http'\nimport { CliError } from '../../errors'\n\ninterface Grant {\n id: string\n status: string\n // Some list endpoints return requester nested under request\n requester?: string\n request?: { requester?: string, command?: string[] }\n}\n\ninterface PaginatedGrants {\n data: Grant[]\n pagination: { cursor: string | null, has_more: boolean }\n}\n\ninterface BatchResult {\n id: string\n status: string\n success: boolean\n error?: { title: string }\n}\n\nexport const revokeCommand = defineCommand({\n meta: {\n name: 'revoke',\n description: 'Revoke one or more grants',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Grant ID(s) to revoke',\n required: false,\n },\n allPending: {\n type: 'boolean',\n description: 'Revoke all own pending grants',\n default: false,\n },\n debug: {\n type: 'boolean',\n description: 'Print debug information (does not include full tokens)',\n default: false,\n },\n },\n async run({ args }) {\n const auth = loadAuth()\n const token = getAuthToken()\n const idp = getIdpUrl()!\n const grantsUrl = await getGrantsEndpoint(idp)\n\n if (args.debug) {\n consola.debug(`idp: ${idp}`)\n consola.debug(`grantsUrl: ${grantsUrl}`)\n consola.debug(`auth.email: ${auth?.email}`)\n consola.debug(`auth.expires_at: ${auth?.expires_at} (now: ${Math.floor(Date.now() / 1000)})`)\n consola.debug(`getAuthToken(): ${token ? `${token.substring(0, 20)}...` : 'NULL'}`)\n }\n\n if (!auth || !token) {\n throw new CliError('Authentication required. Run `apes login` and try again.')\n }\n\n const explicitIds = args.id\n ? [String(args.id), ...args._].filter(Boolean)\n : []\n\n if (args.allPending && explicitIds.length > 0) {\n throw new CliError('Use either --all-pending or grant IDs, not both.')\n }\n\n let ids: string[]\n\n if (args.allPending) {\n const auth = loadAuth()\n const response = await apiFetch<PaginatedGrants>(\n `${grantsUrl}?status=pending&limit=100`,\n { token },\n )\n const ownPending = auth?.email\n ? response.data.filter(g => g.request?.requester === auth.email)\n : response.data\n if (ownPending.length === 0) {\n consola.info('No pending grants to revoke.')\n return\n }\n ids = ownPending.map(g => g.id)\n consola.info(`Found ${ids.length} pending grant(s) to revoke.`)\n }\n else if (explicitIds.length > 0) {\n ids = explicitIds\n }\n else {\n throw new CliError('Provide grant ID(s) or use --all-pending.')\n }\n\n // Single grant: use direct endpoint\n if (ids.length === 1) {\n await apiFetch(`${grantsUrl}/${ids[0]}/revoke`, { method: 'POST', token })\n consola.success(`Grant ${ids[0]} revoked.`)\n return\n }\n\n // Multiple grants: use batch endpoint\n const operations = ids.map(id => ({ id, action: 'revoke' as const }))\n const { results } = await apiFetch<{ results: BatchResult[] }>(\n `${grantsUrl}/batch`,\n { method: 'POST', body: { operations }, token },\n )\n\n let succeeded = 0\n for (const r of results) {\n if (r.success) {\n consola.success(`Grant ${r.id} revoked.`)\n succeeded++\n }\n else {\n consola.error(`Grant ${r.id}: ${r.error?.title || 'Failed'}`)\n }\n }\n\n if (succeeded < results.length) {\n throw new CliError(`Revoked ${succeeded} of ${results.length} grants.`)\n }\n else {\n consola.success(`All ${succeeded} grants revoked.`)\n }\n },\n})\n","import { execFileSync } from 'node:child_process'\nimport { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl } from '../../config'\nimport { CliError, CliExit } from '../../errors'\nimport { apiFetch, getGrantsEndpoint } from '../../http'\nimport { fetchGrantToken, resolveFromGrant, verifyAndExecute } from '../../shapes/index.js'\n\ninterface GrantDetail {\n id: string\n type: string\n status: string\n requester: string\n owner: string\n request: {\n command?: string[]\n audience?: string\n grant_type?: string\n target_host?: string\n execution_context?: { adapter_digest?: string, argv_hash?: string }\n authorization_details?: Array<{ type?: string, permission?: string }>\n }\n}\n\nexport const runGrantCommand = defineCommand({\n meta: {\n name: 'run',\n description: 'Execute a previously-approved grant by ID',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Grant ID',\n required: true,\n },\n 'escapes-path': {\n type: 'string',\n description: 'Path to escapes binary (audience=escapes only)',\n default: 'escapes',\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()\n if (!idp)\n throw new CliError('No IdP URL configured. Run `apes login` first or pass --idp.')\n\n const grantsUrl = await getGrantsEndpoint(idp)\n const grant = await apiFetch<GrantDetail>(`${grantsUrl}/${args.id}`)\n\n // --- status gate ---\n if (grant.status === 'pending')\n throw new CliError(`Grant ${grant.id} is still pending. Approve at: ${idp}/grant-approval?grant_id=${grant.id}`)\n if (grant.status === 'denied' || grant.status === 'revoked')\n throw new CliError(`Grant ${grant.id} is ${grant.status}. Request a new one.`)\n if (grant.status === 'used')\n throw new CliError(`Grant ${grant.id} has already been used. Request a new one (single-use grants cannot be re-executed).`)\n if (grant.status !== 'approved')\n throw new CliError(`Grant ${grant.id} has unexpected status: ${grant.status}`)\n\n // --- dispatch by grant shape ---\n const audience = grant.request?.audience\n const authDetails = grant.request?.authorization_details ?? []\n const hasOpenApeCliDetail = authDetails.some(d => d?.type === 'openape_cli')\n const isShapesGrant = hasOpenApeCliDetail || audience === 'shapes'\n\n if (isShapesGrant) {\n // Re-resolve locally from the recorded command + adapter digest.\n let resolved\n try {\n resolved = await resolveFromGrant(grant)\n }\n catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n throw new CliError(`Cannot re-resolve grant: ${msg}`)\n }\n const token = await fetchGrantToken(idp, grant.id)\n await verifyAndExecute(token, resolved)\n return\n }\n\n if (audience === 'escapes') {\n const { authz_jwt } = await apiFetch<{ authz_jwt: string }>(`${grantsUrl}/${grant.id}/token`, { method: 'POST' })\n const command = grant.request?.command ?? []\n if (command.length === 0)\n throw new CliError(`Grant ${grant.id} has no command to execute.`)\n consola.info(`Executing via escapes: ${command.join(' ')}`)\n try {\n execFileSync(args['escapes-path'] as string, ['--grant', authz_jwt, '--', ...command], { stdio: 'inherit' })\n }\n catch (err: unknown) {\n const exitCode = (err as { status?: number }).status || 1\n throw new CliExit(exitCode)\n }\n return\n }\n\n if (audience === 'ape-shell') {\n // Legacy shell-session grants can't be re-executed standalone — they\n // were created for a specific bash -c line that only made sense inside\n // the original apes run --shell invocation.\n throw new CliError(\n `Grant ${grant.id} is an ape-shell session grant and cannot be re-executed via \\`apes grants run\\`. `\n + `Re-run the original command — if the grant was approved as timed/always, the REPL will reuse it automatically.`,\n )\n }\n\n throw new CliError(`Grant ${grant.id} has unsupported audience \"${audience}\" — no execution path available.`)\n },\n})\n","import { defineCommand } from 'citty'\nimport { getIdpUrl } from '../../config'\nimport { apiFetch, getGrantsEndpoint } from '../../http'\nimport { CliError } from '../../errors'\n\nexport const tokenCommand = defineCommand({\n meta: {\n name: 'token',\n description: 'Get grant token JWT',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Grant ID',\n required: true,\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()!\n const grantsUrl = await getGrantsEndpoint(idp)\n const result = await apiFetch<{ authz_jwt: string }>(`${grantsUrl}/${args.id}/token`, {\n method: 'POST',\n })\n\n if (!result.authz_jwt) {\n throw new CliError('No token received. Grant may not be approved.')\n }\n\n // Output raw token to stdout (pipeable)\n process.stdout.write(result.authz_jwt)\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl, loadAuth } from '../../config'\nimport { apiFetch, getDelegationsEndpoint } from '../../http'\nimport { CliError } from '../../errors'\n\nexport const delegateCommand = defineCommand({\n meta: {\n name: 'delegate',\n description: 'Create a delegation',\n },\n args: {\n to: {\n type: 'string',\n description: 'Delegate email (who can act on your behalf)',\n required: true,\n },\n at: {\n type: 'string',\n description: 'Service/audience where delegation applies',\n required: true,\n },\n scopes: {\n type: 'string',\n description: 'Comma-separated scopes',\n },\n approval: {\n type: 'string',\n description: 'Approval type: once, timed, always',\n default: 'once',\n },\n expires: {\n type: 'string',\n description: 'Expiration date (ISO 8601)',\n },\n },\n async run({ args }) {\n const auth = loadAuth()\n if (!auth) {\n throw new CliError('Not logged in. Run `apes login` first.')\n }\n\n const idp = getIdpUrl()!\n const delegationsUrl = await getDelegationsEndpoint(idp)\n\n const body: Record<string, unknown> = {\n delegate: args.to,\n audience: args.at,\n approval: args.approval,\n }\n\n if (args.scopes) {\n body.scopes = args.scopes.split(',').map(s => s.trim())\n }\n\n if (args.expires) {\n body.expires_at = args.expires\n }\n\n const result = await apiFetch<{ id: string }>(delegationsUrl, {\n method: 'POST',\n body,\n })\n\n consola.success(`Delegation created: ${result.id}`)\n console.log(` Delegate: ${args.to}`)\n console.log(` Audience: ${args.at}`)\n if (args.scopes)\n console.log(` Scopes: ${args.scopes}`)\n console.log(` Approval: ${args.approval}`)\n if (args.expires)\n console.log(` Expires: ${args.expires}`)\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl } from '../../config'\nimport { apiFetch, getDelegationsEndpoint } from '../../http'\n\ninterface Delegation {\n id: string\n delegator: string\n delegate: string\n audience: string\n scopes?: string[]\n approval: string\n created_at?: string\n expires_at?: string\n}\n\ninterface PaginatedDelegations {\n data: Delegation[]\n pagination: { cursor: string | null, has_more: boolean }\n}\n\nexport const delegationsCommand = defineCommand({\n meta: {\n name: 'delegations',\n description: 'List delegations',\n },\n args: {\n json: {\n type: 'boolean',\n description: 'Output as JSON',\n default: false,\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()!\n const delegationsUrl = await getDelegationsEndpoint(idp)\n const response = await apiFetch<PaginatedDelegations>(delegationsUrl)\n\n // Support both paginated and legacy plain-array responses\n const delegations = Array.isArray(response) ? response : response.data\n\n if (args.json) {\n console.log(JSON.stringify(delegations, null, 2))\n return\n }\n\n if (delegations.length === 0) {\n consola.info('No delegations found.')\n return\n }\n\n for (const d of delegations) {\n const scopes = d.scopes?.join(', ') || '(all)'\n const expires = d.expires_at ? ` expires ${d.expires_at}` : ''\n console.log(`${d.id} ${d.delegator} → ${d.delegate} at ${d.audience} [${scopes}]${expires}`)\n }\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl } from '../../config'\nimport { apiFetch, getDelegationsEndpoint } from '../../http'\nimport { CliError } from '../../errors'\n\nexport const delegationRevokeCommand = defineCommand({\n meta: {\n name: 'delegation-revoke',\n description: 'Revoke a delegation',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Delegation ID to revoke',\n required: true,\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()\n if (!idp) {\n throw new CliError('No IdP URL configured. Run `apes login` first or pass --idp.')\n }\n\n const delegationsUrl = await getDelegationsEndpoint(idp)\n const id = String(args.id)\n\n const result = await apiFetch<{ id: string, status: string }>(\n `${delegationsUrl}/${id}`,\n { method: 'DELETE' },\n )\n\n consola.success(`Delegation ${result.id} revoked.`)\n },\n})\n","import { defineCommand } from 'citty'\nimport { usersListCommand, usersCreateCommand, usersDeleteCommand } from './users'\nimport { sshKeysListCommand, sshKeysAddCommand, sshKeysDeleteCommand } from './ssh-keys'\n\nconst usersCommand = defineCommand({\n meta: {\n name: 'users',\n description: 'Manage users',\n },\n subCommands: {\n list: usersListCommand,\n create: usersCreateCommand,\n delete: usersDeleteCommand,\n },\n})\n\nconst sshKeysCommand = defineCommand({\n meta: {\n name: 'ssh-keys',\n description: 'Manage SSH keys',\n },\n subCommands: {\n list: sshKeysListCommand,\n add: sshKeysAddCommand,\n delete: sshKeysDeleteCommand,\n },\n})\n\nexport const adminCommand = defineCommand({\n meta: {\n name: 'admin',\n description: 'Admin commands (requires APES_MANAGEMENT_TOKEN)',\n },\n subCommands: {\n users: usersCommand,\n 'ssh-keys': sshKeysCommand,\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl } from '../../config'\nimport { apiFetch } from '../../http'\nimport { CliError } from '../../errors'\n\ninterface AdminUser {\n email: string\n name: string\n isActive: boolean\n owner?: string\n createdAt: number\n}\n\nfunction getManagementToken(): string {\n const token = process.env.APES_MANAGEMENT_TOKEN\n if (!token) {\n throw new CliError('Management token required. Set APES_MANAGEMENT_TOKEN environment variable.')\n }\n return token\n}\n\ninterface UserListResponse {\n data: AdminUser[]\n pagination: {\n cursor: string | null\n has_more: boolean\n }\n}\n\nexport const usersListCommand = defineCommand({\n meta: {\n name: 'list',\n description: 'List all users',\n },\n args: {\n json: {\n type: 'boolean',\n description: 'Output as JSON',\n default: false,\n },\n limit: {\n type: 'string',\n description: 'Max number of users to return (1-100, default 50)',\n },\n cursor: {\n type: 'string',\n description: 'Pagination cursor (email of last item from previous page)',\n },\n search: {\n type: 'string',\n description: 'Filter by email or name (case-insensitive)',\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()\n if (!idp) {\n throw new CliError('No IdP URL configured. Run `apes login` first or pass --idp.')\n }\n\n const token = getManagementToken()\n const params = new URLSearchParams()\n if (args.limit) params.set('limit', args.limit)\n if (args.cursor) params.set('cursor', args.cursor)\n if (args.search) params.set('search', args.search)\n const qs = params.toString()\n const url = qs ? `${idp}/api/admin/users?${qs}` : `${idp}/api/admin/users`\n\n const result = await apiFetch<UserListResponse>(url, { token })\n\n if (args.json) {\n console.log(JSON.stringify(result, null, 2))\n return\n }\n\n if (result.data.length === 0) {\n consola.info('No users found.')\n return\n }\n\n for (const u of result.data) {\n const owner = u.owner ? ` (agent of ${u.owner})` : ''\n const active = u.isActive ? '' : ' [inactive]'\n console.log(`${u.email} ${u.name}${owner}${active}`)\n }\n\n if (result.pagination.has_more) {\n consola.info(`More results available. Use --cursor=\"${result.pagination.cursor}\" to see next page.`)\n }\n },\n})\n\nexport const usersCreateCommand = defineCommand({\n meta: {\n name: 'create',\n description: 'Create a user',\n },\n args: {\n email: {\n type: 'string',\n description: 'User email',\n required: true,\n },\n name: {\n type: 'string',\n description: 'User name',\n required: true,\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()\n if (!idp) {\n throw new CliError('No IdP URL configured. Run `apes login` first or pass --idp.')\n }\n\n const token = getManagementToken()\n\n const result = await apiFetch<{ ok: boolean, email: string, name: string }>(\n `${idp}/api/admin/users`,\n {\n method: 'POST',\n body: { email: args.email, name: args.name },\n token,\n },\n )\n\n consola.success(`User created: ${result.email} (${result.name})`)\n },\n})\n\nexport const usersDeleteCommand = defineCommand({\n meta: {\n name: 'delete',\n description: 'Delete a user',\n },\n args: {\n email: {\n type: 'positional',\n description: 'User email',\n required: true,\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()\n if (!idp) {\n throw new CliError('No IdP URL configured. Run `apes login` first or pass --idp.')\n }\n\n const token = getManagementToken()\n const email = String(args.email)\n\n await apiFetch(`${idp}/api/admin/users/${encodeURIComponent(email)}`, {\n method: 'DELETE',\n token,\n })\n\n consola.success(`User deleted: ${email}`)\n },\n})\n","import { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { homedir } from 'node:os'\nimport { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl } from '../../config'\nimport { apiFetch } from '../../http'\nimport { CliError } from '../../errors'\n\ninterface SshKey {\n keyId: string\n userEmail: string\n publicKey: string\n name: string\n createdAt: number\n}\n\nfunction getManagementToken(): string {\n const token = process.env.APES_MANAGEMENT_TOKEN\n if (!token) {\n throw new CliError('Management token required. Set APES_MANAGEMENT_TOKEN environment variable.')\n }\n return token\n}\n\nexport const sshKeysListCommand = defineCommand({\n meta: {\n name: 'list',\n description: 'List SSH keys for a user',\n },\n args: {\n email: {\n type: 'positional',\n description: 'User email',\n required: true,\n },\n json: {\n type: 'boolean',\n description: 'Output as JSON',\n default: false,\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()\n if (!idp) {\n throw new CliError('No IdP URL configured. Run `apes login` first or pass --idp.')\n }\n\n const token = getManagementToken()\n const email = String(args.email)\n const keys = await apiFetch<SshKey[]>(\n `${idp}/api/admin/users/${encodeURIComponent(email)}/ssh-keys`,\n { token },\n )\n\n if (args.json) {\n console.log(JSON.stringify(keys, null, 2))\n return\n }\n\n if (keys.length === 0) {\n consola.info(`No SSH keys found for ${email}.`)\n return\n }\n\n for (const k of keys) {\n console.log(`${k.keyId} ${k.name} ${k.publicKey.substring(0, 40)}...`)\n }\n },\n})\n\nexport const sshKeysAddCommand = defineCommand({\n meta: {\n name: 'add',\n description: 'Add an SSH key for a user',\n },\n args: {\n email: {\n type: 'string',\n description: 'User email',\n required: true,\n },\n key: {\n type: 'string',\n description: 'Path to public key file or key string',\n required: true,\n },\n name: {\n type: 'string',\n description: 'Key name/label',\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()\n if (!idp) {\n throw new CliError('No IdP URL configured. Run `apes login` first or pass --idp.')\n }\n\n const token = getManagementToken()\n\n // Read key from file if path exists, otherwise treat as key string\n let publicKey = args.key\n const resolved = resolve(args.key.replace(/^~/, homedir()))\n if (existsSync(resolved)) {\n publicKey = readFileSync(resolved, 'utf-8').trim()\n }\n\n const body: Record<string, string> = { publicKey }\n if (args.name) {\n body.name = args.name\n }\n\n const result = await apiFetch<SshKey>(\n `${idp}/api/admin/users/${encodeURIComponent(args.email)}/ssh-keys`,\n {\n method: 'POST',\n body,\n token,\n },\n )\n\n consola.success(`SSH key added: ${result.keyId} (${result.name})`)\n },\n})\n\nexport const sshKeysDeleteCommand = defineCommand({\n meta: {\n name: 'delete',\n description: 'Delete an SSH key',\n },\n args: {\n email: {\n type: 'string',\n description: 'User email',\n required: true,\n },\n keyId: {\n type: 'positional',\n description: 'Key ID',\n required: true,\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()\n if (!idp) {\n throw new CliError('No IdP URL configured. Run `apes login` first or pass --idp.')\n }\n\n const token = getManagementToken()\n const keyId = String(args.keyId)\n\n await apiFetch(\n `${idp}/api/admin/users/${encodeURIComponent(args.email)}/ssh-keys/${keyId}`,\n {\n method: 'DELETE',\n token,\n },\n )\n\n consola.success(`SSH key deleted: ${keyId}`)\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport {\n fetchRegistry,\n findAdapter,\n findConflictingAdapters,\n getInstalledDigest,\n installAdapter,\n isInstalled,\n loadAdapter,\n removeAdapter,\n searchAdapters,\n} from '../../shapes/index.js'\nimport { CliError } from '../../errors'\n\nexport const adapterCommand = defineCommand({\n meta: {\n name: 'adapter',\n description: 'Manage CLI adapters',\n },\n subCommands: {\n list: defineCommand({\n meta: {\n name: 'list',\n description: 'List available adapters',\n },\n args: {\n remote: {\n type: 'boolean',\n description: 'List adapters from the remote registry',\n default: false,\n },\n json: {\n type: 'boolean',\n description: 'Output as JSON',\n default: false,\n },\n refresh: {\n type: 'boolean',\n description: 'Force refresh the registry cache',\n default: false,\n },\n },\n async run({ args }) {\n const forceRefresh = Boolean(args.refresh)\n if (args.remote) {\n const index = await fetchRegistry(forceRefresh)\n if (args.json) {\n process.stdout.write(`${JSON.stringify(index.adapters, null, 2)}\\n`)\n return\n }\n consola.info(`Registry: ${index.adapters.length} adapters (${index.generated_at})`)\n for (const a of index.adapters) {\n const installed = isInstalled(a.id, false) ? ' [installed]' : ''\n console.log(` ${a.id.padEnd(12)} ${a.name.padEnd(24)} ${a.category}${installed}`)\n }\n return\n }\n\n const index = await fetchRegistry(forceRefresh)\n const local: { id: string, source: string, digest: string }[] = []\n for (const a of index.adapters) {\n try {\n const loaded = loadAdapter(a.id)\n local.push({ id: a.id, source: loaded.source, digest: loaded.digest })\n }\n catch {\n // not installed locally\n }\n }\n\n if (args.json) {\n process.stdout.write(`${JSON.stringify(local, null, 2)}\\n`)\n return\n }\n\n if (local.length === 0) {\n consola.info('No adapters installed. Use `apes adapter list --remote` to see available adapters.')\n return\n }\n\n for (const a of local) {\n console.log(` ${a.id.padEnd(12)} ${a.source}`)\n }\n },\n }),\n\n install: defineCommand({\n meta: {\n name: 'install',\n description: 'Install an adapter from the registry',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Adapter ID to install',\n required: true,\n },\n local: {\n type: 'boolean',\n description: 'Install to project-local .openape/ instead of ~/.openape/',\n default: false,\n },\n refresh: {\n type: 'boolean',\n description: 'Force refresh the registry cache',\n default: false,\n },\n },\n async run({ args }) {\n const ids = [String(args.id), ...args._].filter(Boolean)\n const local = Boolean(args.local)\n const index = await fetchRegistry(Boolean(args.refresh))\n\n for (const id of ids) {\n const entry = findAdapter(index, id)\n if (!entry) {\n consola.error(`Adapter \"${id}\" not found in registry. Use \\`apes adapter search ${id}\\` to search.`)\n continue\n }\n\n const conflicts = findConflictingAdapters(entry.executable, id)\n if (conflicts.length > 0) {\n for (const c of conflicts) {\n consola.warn(`Conflicting adapter found: ${c.path} (id: ${c.adapterId}, executable: ${c.executable})`)\n consola.warn(` Remove it with: apes adapter remove ${c.adapterId}`)\n }\n }\n\n const result = await installAdapter(entry, { local })\n const verb = result.updated ? 'Updated' : 'Installed'\n consola.success(`${verb} ${result.id} → ${result.path}`)\n consola.info(`Digest: ${result.digest}`)\n }\n },\n }),\n\n remove: defineCommand({\n meta: {\n name: 'remove',\n description: 'Remove an installed adapter',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Adapter ID to remove',\n required: true,\n },\n local: {\n type: 'boolean',\n description: 'Remove from project-local .openape/',\n default: false,\n },\n },\n async run({ args }) {\n const ids = [String(args.id), ...args._].filter(Boolean)\n const local = Boolean(args.local)\n let failed = false\n\n for (const id of ids) {\n if (removeAdapter(id, local)) {\n consola.success(`Removed adapter: ${id}`)\n }\n else {\n consola.error(`Adapter \"${id}\" is not installed${local ? ' locally' : ''}`)\n failed = true\n }\n }\n\n if (failed)\n throw new CliError('Some adapters could not be removed')\n },\n }),\n\n info: defineCommand({\n meta: {\n name: 'info',\n description: 'Show detailed adapter information',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Adapter ID',\n required: true,\n },\n refresh: {\n type: 'boolean',\n description: 'Force refresh the registry cache',\n default: false,\n },\n },\n async run({ args }) {\n const id = String(args.id)\n const index = await fetchRegistry(Boolean(args.refresh))\n const entry = findAdapter(index, id)\n if (!entry)\n throw new Error(`Adapter \"${id}\" not found in registry`)\n\n console.log(`ID: ${entry.id}`)\n console.log(`Name: ${entry.name}`)\n console.log(`Description: ${entry.description}`)\n console.log(`Category: ${entry.category}`)\n console.log(`Tags: ${entry.tags.join(', ')}`)\n console.log(`Author: ${entry.author}`)\n console.log(`Executable: ${entry.executable}`)\n console.log(`Digest: ${entry.digest}`)\n console.log(`Min version: ${entry.min_shapes_version}`)\n console.log(`URL: ${entry.download_url}`)\n\n const localDigest = getInstalledDigest(id, false)\n if (localDigest) {\n const upToDate = localDigest === entry.digest\n console.log(`Installed: yes${upToDate ? ' (up to date)' : ' (update available)'}`)\n }\n else {\n console.log(`Installed: no`)\n }\n },\n }),\n\n search: defineCommand({\n meta: {\n name: 'search',\n description: 'Search adapters in the registry',\n },\n args: {\n query: {\n type: 'positional',\n description: 'Search query',\n required: true,\n },\n json: {\n type: 'boolean',\n description: 'Output as JSON',\n default: false,\n },\n refresh: {\n type: 'boolean',\n description: 'Force refresh the registry cache',\n default: false,\n },\n },\n async run({ args }) {\n const query = String(args.query)\n const index = await fetchRegistry(Boolean(args.refresh))\n const results = searchAdapters(index, query)\n\n if (args.json) {\n process.stdout.write(`${JSON.stringify(results, null, 2)}\\n`)\n return\n }\n\n if (results.length === 0) {\n consola.info(`No adapters matching \"${query}\"`)\n return\n }\n\n for (const a of results) {\n console.log(` ${a.id.padEnd(12)} ${a.name.padEnd(24)} ${a.category}`)\n console.log(` ${a.description}`)\n }\n },\n }),\n\n update: defineCommand({\n meta: {\n name: 'update',\n description: 'Update installed adapters',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Adapter ID (omit to update all)',\n },\n yes: {\n type: 'boolean',\n description: 'Skip confirmation',\n default: false,\n },\n refresh: {\n type: 'boolean',\n description: 'Force refresh the registry cache',\n default: true,\n },\n },\n async run({ args }) {\n const index = await fetchRegistry(Boolean(args.refresh))\n const targetId = args.id ? String(args.id) : undefined\n const targets = targetId\n ? [targetId]\n : index.adapters.map(a => a.id).filter(id => isInstalled(id, false))\n\n if (targets.length === 0) {\n consola.info('No adapters installed to update.')\n return\n }\n\n for (const id of targets) {\n const entry = findAdapter(index, id)\n if (!entry) {\n consola.warn(`${id}: not found in registry, skipping`)\n continue\n }\n\n const localDigest = getInstalledDigest(id, false)\n if (localDigest === entry.digest) {\n consola.info(`${id}: already up to date`)\n continue\n }\n\n if (localDigest && !args.yes) {\n consola.warn(`${id}: digest will change — existing grants for this adapter will be invalidated`)\n consola.info(` Old: ${localDigest}`)\n consola.info(` New: ${entry.digest}`)\n consola.info(' Use --yes to confirm')\n continue\n }\n\n const result = await installAdapter(entry)\n consola.success(`Updated ${result.id} → ${result.path}`)\n }\n },\n }),\n\n verify: defineCommand({\n meta: {\n name: 'verify',\n description: 'Verify installed adapter against registry digest',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Adapter ID',\n required: true,\n },\n local: {\n type: 'boolean',\n description: 'Check project-local adapter',\n default: false,\n },\n refresh: {\n type: 'boolean',\n description: 'Force refresh the registry cache',\n default: false,\n },\n },\n async run({ args }) {\n const id = String(args.id)\n const local = Boolean(args.local)\n const index = await fetchRegistry(Boolean(args.refresh))\n const entry = findAdapter(index, id)\n if (!entry)\n throw new Error(`Adapter \"${id}\" not found in registry`)\n\n const localDigest = getInstalledDigest(id, local)\n if (!localDigest)\n throw new Error(`Adapter \"${id}\" is not installed${local ? ' locally' : ''}`)\n\n if (localDigest === entry.digest) {\n consola.success(`${id}: digest matches registry`)\n }\n else {\n console.log(` Local: ${localDigest}`)\n console.log(` Registry: ${entry.digest}`)\n throw new CliError(`${id}: digest mismatch`)\n }\n },\n }),\n },\n})\n","import { execFileSync } from 'node:child_process'\nimport { hostname } from 'node:os'\nimport { basename } from 'node:path'\nimport { defineCommand } from 'citty'\nimport {\n createShapesGrant,\n extractOption,\n extractShellCommandString,\n extractWrappedCommand,\n fetchGrantToken,\n findExistingGrant,\n loadAdapter,\n loadOrInstallAdapter,\n parseShellCommand,\n resolveCommand,\n verifyAndExecute,\n waitForGrantStatus,\n} from '../shapes/index.js'\nimport consola from 'consola'\nimport { getIdpUrl, loadAuth } from '../config'\nimport { apiFetch, getGrantsEndpoint } from '../http'\nimport { CliError, CliExit } from '../errors'\nimport { notifyGrantPending } from '../notifications'\n\n/**\n * Returns true when the caller asked for the legacy blocking path via\n * `--wait` or `APE_WAIT=1`. Default is non-blocking (async exit).\n */\nfunction shouldWaitForGrant(args: Record<string, unknown>): boolean {\n return args.wait === true || process.env.APE_WAIT === '1'\n}\n\n/**\n * Print the async info block for a freshly created pending grant. This is\n * what the user sees when the non-blocking default path is taken: the grant\n * id, the approval URL, the `grants status` and `grants run` commands.\n */\nfunction printPendingGrantInfo(grant: { id: string }, idp: string): void {\n consola.success(`Grant ${grant.id} erstellt`)\n console.log(` Approve: ${idp}/grant-approval?grant_id=${grant.id}`)\n console.log(` Status: apes grants status ${grant.id}`)\n console.log(` Ausführen: apes grants run ${grant.id}`)\n console.log('')\n console.log(' Tipp: Im Browser \"als timed/always approven\" wählen, um das')\n console.log(' Kommando ohne erneuten Approval wiederzuverwenden.')\n}\n\nexport const runCommand = defineCommand({\n meta: {\n name: 'run',\n description: 'Execute a grant-secured command',\n },\n args: {\n 'approval': {\n type: 'string',\n description: 'Approval type: once, timed, always',\n default: 'once',\n },\n 'reason': {\n type: 'string',\n description: 'Reason for the grant request',\n },\n 'adapter': {\n type: 'string',\n description: 'Explicit path to adapter TOML file',\n },\n 'as': {\n type: 'string',\n description: 'Execute as this user (delegates to escapes)',\n },\n 'host': {\n type: 'string',\n description: 'Target host (default: system hostname)',\n },\n 'escapes-path': {\n type: 'string',\n description: 'Path to escapes binary',\n default: 'escapes',\n },\n 'idp': {\n type: 'string',\n description: 'IdP URL',\n },\n 'shell': {\n type: 'boolean',\n description: 'Shell mode: use session grant with audience ape-shell',\n default: false,\n },\n 'wait': {\n type: 'boolean',\n description: 'Block until grant is approved (default: async, print grant info and exit 0). Equivalent to APE_WAIT=1.',\n default: false,\n },\n '_': {\n type: 'positional',\n description: 'Command to execute (after --)',\n required: false,\n },\n },\n async run({ rawArgs, args }) {\n const wrappedCommand = extractWrappedCommand(rawArgs ?? [])\n\n if (args.shell && wrappedCommand.length > 0) {\n // Shell mode: ape-shell -c \"command\" → apes run --shell -- bash -c \"command\"\n await runShellMode(wrappedCommand, args)\n return\n }\n\n if (wrappedCommand.length > 0) {\n // Adapter mode: apes run [options] -- <cli> <args...>\n await runAdapterMode(wrappedCommand, rawArgs ?? [], args)\n }\n else {\n // Audience mode: apes run <audience> <action>\n // Extract audience and action from rawArgs (before --)\n const positionals = extractPositionals(rawArgs ?? [])\n if (positionals.length < 2)\n throw new Error('Usage: apes run -- <cli> <args...> OR apes run <audience> <action>')\n await runAudienceMode(positionals[0]!, positionals[1]!, args)\n }\n },\n})\n\nasync function runShellMode(\n command: string[],\n args: Record<string, unknown>,\n) {\n const auth = loadAuth()\n if (!auth)\n throw new CliError('Not logged in. Run `apes login` first.')\n\n const idp = getIdpUrl(args.idp as string | undefined)\n if (!idp)\n throw new CliError('No IdP URL configured. Run `apes login` first or pass --idp.')\n\n // Try to handle this command via the shapes adapter system first.\n // This gives us structured grants with resource chains (e.g. \"rm file:/tmp/foo.txt\")\n // instead of opaque \"bash -c …\" grants.\n const adapterHandled = await tryAdapterModeFromShell(command, idp, args)\n if (adapterHandled) return\n\n const grantsUrl = await getGrantsEndpoint(idp)\n const targetHost = (args.host as string) || hostname()\n\n // Try to find an existing timed/always session grant for ape-shell\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 === targetHost\n && g.request.grant_type !== 'once',\n )\n if (sessionGrant) {\n execShellCommand(command)\n return\n }\n }\n catch {\n // Fall through to creating a new grant\n }\n\n // No session grant found — request one. Default: 'once', but the approver\n // can upgrade to 'timed' or 'always' during approval to enable reuse.\n consola.info(`Requesting ape-shell session grant on ${targetHost}`)\n const grant = await apiFetch<{ id: string, status: string }>(grantsUrl, {\n method: 'POST',\n body: {\n requester: auth.email,\n target_host: targetHost,\n audience: 'ape-shell',\n grant_type: 'once',\n command: command.slice(0, 3),\n reason: `Shell session: ${command.join(' ').slice(0, 100)}`,\n },\n })\n\n notifyGrantPending({\n grantId: grant.id,\n approveUrl: `${idp}/grant-approval?grant_id=${grant.id}`,\n command: command.join(' ').slice(0, 200),\n audience: 'ape-shell',\n host: targetHost,\n })\n\n if (shouldWaitForGrant(args)) {\n consola.info(`Grant requested: ${grant.id}`)\n consola.info('Waiting for approval...')\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 break\n if (status.status === 'denied' || status.status === 'revoked')\n throw new CliError(`Grant ${status.status}.`)\n await new Promise(r => setTimeout(r, interval))\n }\n\n execShellCommand(command)\n return\n }\n\n printPendingGrantInfo(grant, idp)\n}\n\n/**\n * Try to handle a shell command via the shapes adapter system.\n *\n * Flow:\n * 1. Extract the command string from `bash -c \"…\"` argv\n * 2. Parse into executable + argv (bail out on compound commands)\n * 3. Load adapter locally, or auto-install from registry\n * 4. Resolve the command against adapter operations → structured CLI grant detail\n * 5. Reuse an existing matching grant, or request a new one and execute\n *\n * Returns true when the command was handled (executed or failed hard).\n * Returns false for any reason — caller should fall back to the generic session grant.\n */\nasync function tryAdapterModeFromShell(\n command: string[],\n idp: string,\n args: Record<string, unknown>,\n): Promise<boolean> {\n const cmdString = extractShellCommandString(command)\n if (!cmdString) return false\n\n const parsed = parseShellCommand(cmdString)\n if (!parsed) return false\n if (parsed.isCompound) return false\n\n const loaded = await loadOrInstallAdapter(parsed.executable)\n if (!loaded) return false\n\n // resolveCommand does a strict comparison against `adapter.cli.executable`,\n // which is always the bare binary name. When the user typed an absolute\n // path we must pass the basename, not the full path.\n const normalizedExecutable = basename(parsed.executable)\n\n let resolved\n try {\n resolved = await resolveCommand(loaded, [normalizedExecutable, ...parsed.argv])\n }\n catch (err) {\n consola.debug(`ape-shell: adapter resolve failed for \"${parsed.raw}\":`, err)\n return false\n }\n\n // Try to reuse an existing matching grant (with widening support)\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 verifyAndExecute(token, resolved)\n return true\n }\n }\n catch {\n // Fall through to request a new grant\n }\n\n // Request a new grant for this specific command\n const approval = (args.approval ?? 'once') as 'once' | 'timed' | 'always'\n consola.info(`Requesting grant for: ${resolved.detail.display}`)\n const grant = await createShapesGrant(resolved, {\n idp,\n approval,\n reason: (args.reason as string) || `ape-shell: ${resolved.detail.display}`,\n })\n\n if (grant.similar_grants?.similar_grants?.length) {\n const n = grant.similar_grants.similar_grants.length\n consola.info('')\n consola.info(` Similar grant(s) found (${n}). Your approver can extend an existing grant to cover this request.`)\n }\n\n notifyGrantPending({\n grantId: grant.id,\n approveUrl: `${idp}/grant-approval?grant_id=${grant.id}`,\n command: resolved.detail?.display || parsed?.raw || 'unknown',\n audience: resolved.adapter?.cli?.audience ?? 'shapes',\n host: (args.host as string) || hostname(),\n })\n\n if (shouldWaitForGrant(args)) {\n consola.info(`Grant requested: ${grant.id}`)\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 throw new CliError(`Grant ${status}`)\n\n const token = await fetchGrantToken(idp, grant.id)\n await verifyAndExecute(token, resolved)\n return true\n }\n\n printPendingGrantInfo(grant, idp)\n return true\n}\n\n/** Execute a shell command as [shell, '-c', command_string] via execFileSync */\nfunction execShellCommand(command: string[]): void {\n if (command.length === 0)\n throw new CliError('No command to execute')\n try {\n execFileSync(command[0]!, command.slice(1), { stdio: 'inherit' })\n }\n catch (err: unknown) {\n const exitCode = (err as { status?: number }).status || 1\n throw new CliExit(exitCode)\n }\n}\n\nfunction extractPositionals(rawArgs: string[]): string[] {\n const positionals: string[] = []\n const delimiter = rawArgs.indexOf('--')\n const args = delimiter >= 0 ? rawArgs.slice(0, delimiter) : rawArgs\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i]!\n if (arg === 'run')\n continue\n if (arg.startsWith('--')) {\n i++ // skip flag value\n continue\n }\n positionals.push(arg)\n }\n return positionals\n}\n\nasync function runAdapterMode(\n command: string[],\n rawArgs: string[],\n args: Record<string, unknown>,\n) {\n const idp = getIdpUrl(args.idp as string | undefined)\n if (!idp)\n throw new Error('No IdP URL configured. Run `apes login` first or pass --idp.')\n\n // If caller wants to run as another user (e.g. root), auto-switch to the escapes audience flow.\n // Adapter mode (Shapes) is user-level and cannot elevate privileges.\n if (args.as) {\n await runAudienceMode('escapes', command.join(' '), args)\n return\n }\n\n const adapterOpt = extractOption(rawArgs, 'adapter')\n const loaded = loadAdapter(command[0]!, adapterOpt)\n const resolved = await resolveCommand(loaded, command)\n const approval = (args.approval ?? 'once') as 'once' | 'timed' | 'always'\n\n // Try reusing an existing timed/always grant (findExistingGrant skips once grants)\n try {\n const existingGrantId = await findExistingGrant(resolved, idp)\n if (existingGrantId) {\n consola.info(`Reusing existing grant: ${existingGrantId}`)\n const token = await fetchGrantToken(idp, existingGrantId)\n await verifyAndExecute(token, resolved)\n return\n }\n }\n catch {\n // Fall through to creating a new grant\n }\n\n const grant = await createShapesGrant(resolved, {\n idp,\n approval,\n ...(args.reason ? { reason: args.reason as string } : {}),\n })\n\n if (grant.similar_grants?.similar_grants?.length) {\n const n = grant.similar_grants.similar_grants.length\n consola.info('')\n consola.info(` Similar grant(s) found (${n}). Your approver can extend an existing grant to cover this request.`)\n if (grant.similar_grants.widened_details?.length) {\n const wider = grant.similar_grants.widened_details.map(d => d.permission).join(', ')\n consola.info(` Broader scope: ${wider}`)\n }\n consola.info('')\n }\n\n if (shouldWaitForGrant(args)) {\n consola.info(`Grant requested: ${grant.id}`)\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 throw new Error(`Grant ${status}`)\n\n const token = await fetchGrantToken(idp, grant.id)\n await verifyAndExecute(token, resolved)\n return\n }\n\n printPendingGrantInfo(grant, idp)\n}\n\nasync function runAudienceMode(\n audience: string,\n action: string,\n args: Record<string, unknown>,\n) {\n const auth = loadAuth()\n if (!auth) {\n throw new CliError('Not logged in. Run `apes login` first.')\n }\n\n const idp = getIdpUrl(args.idp as string | undefined)!\n const grantsUrl = await getGrantsEndpoint(idp)\n const command = action.split(' ')\n const targetHost = (args.host as string) || hostname()\n\n // Step 1: Request grant\n consola.info(`Requesting ${audience} grant on ${targetHost}: ${command.join(' ')}`)\n const grant = await apiFetch<{ id: string, status: string }>(grantsUrl, {\n method: 'POST',\n body: {\n requester: auth.email,\n target_host: targetHost,\n audience,\n grant_type: args.approval,\n command,\n reason: (args.reason as string) || command.join(' '),\n ...(args.as ? { run_as: args.as } : {}),\n },\n })\n if (!shouldWaitForGrant(args)) {\n printPendingGrantInfo(grant, idp)\n return\n }\n\n consola.success(`Grant requested: ${grant.id}`)\n\n // Step 2: Wait for approval\n consola.info('Waiting for approval...')\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 consola.success('Grant approved!')\n break\n }\n if (status.status === 'denied' || status.status === 'revoked') {\n throw new CliError(`Grant ${status.status}.`)\n }\n await new Promise(r => setTimeout(r, interval))\n }\n\n // Step 3: Get grant token\n consola.info('Fetching grant token...')\n const { authz_jwt } = await apiFetch<{ authz_jwt: string }>(`${grantsUrl}/${grant.id}/token`, {\n method: 'POST',\n })\n\n // Step 4: Execute or output token\n if (audience === 'escapes') {\n consola.info(`Executing: ${command.join(' ')}`)\n try {\n execFileSync((args['escapes-path'] as string) || 'escapes', ['--grant', authz_jwt, '--', ...command], {\n stdio: 'inherit',\n })\n }\n catch (err: unknown) {\n const exitCode = (err as { status?: number }).status || 1\n throw new CliExit(exitCode)\n }\n }\n else {\n process.stdout.write(authz_jwt)\n }\n}\n","import { defineCommand } from 'citty'\nimport { extractOption, extractWrappedCommand, loadAdapter, resolveCommand } from '../shapes/index.js'\n\nexport const explainCommand = defineCommand({\n meta: {\n name: 'explain',\n description: 'Show what permission a 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: apes 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","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl, loadAuth, loadConfig } from '../../config'\nimport { CliError } from '../../errors'\n\nexport const configGetCommand = defineCommand({\n meta: {\n name: 'get',\n description: 'Get a configuration value',\n },\n args: {\n key: {\n type: 'positional',\n description: 'Config key: idp, email, defaults.idp, defaults.approval, agent.key, agent.email',\n required: true,\n },\n },\n run({ args }) {\n const key = args.key\n\n switch (key) {\n case 'idp': {\n const idp = getIdpUrl()\n if (idp)\n console.log(idp)\n else\n consola.info('No IdP configured.')\n break\n }\n case 'email': {\n const auth = loadAuth()\n if (auth?.email)\n console.log(auth.email)\n else\n consola.info('Not logged in.')\n break\n }\n default: {\n // Dot-notation: defaults.idp, defaults.approval, agent.key, agent.email\n const config = loadConfig()\n const parts = key.split('.')\n if (parts.length === 2) {\n const section = parts[0] as keyof typeof config\n const field = parts[1]!\n const sectionObj = config[section] as Record<string, string> | undefined\n if (sectionObj && field in sectionObj) {\n console.log(sectionObj[field])\n }\n else {\n consola.info(`Key \"${key}\" not set.`)\n }\n }\n else {\n throw new CliError(`Unknown key: \"${key}\". Use: idp, email, defaults.idp, defaults.approval, agent.key, agent.email`)\n }\n }\n }\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { loadConfig, saveConfig } from '../../config'\nimport { CliError } from '../../errors'\n\nexport const configSetCommand = defineCommand({\n meta: {\n name: 'set',\n description: 'Set a configuration value',\n },\n args: {\n key: {\n type: 'positional',\n description: 'Config key: defaults.idp, defaults.approval, agent.key, agent.email',\n required: true,\n },\n value: {\n type: 'positional',\n description: 'Value to set',\n required: true,\n },\n },\n run({ args }) {\n const key = args.key\n const value = args.value\n const config = loadConfig()\n\n const parts = key.split('.')\n if (parts.length !== 2) {\n throw new CliError(`Invalid key: \"${key}\". Use: defaults.idp, defaults.approval, agent.key, agent.email`)\n }\n\n const [section, field] = parts as [string, string]\n\n if (section === 'defaults') {\n config.defaults = config.defaults || {}\n ;(config.defaults as Record<string, string>)[field] = value\n }\n else if (section === 'agent') {\n config.agent = config.agent || {}\n ;(config.agent as Record<string, string>)[field] = value\n }\n else {\n throw new CliError(`Unknown section: \"${section}\". Use: defaults, agent`)\n }\n\n saveConfig(config)\n consola.success(`Set ${key} = ${value}`)\n },\n})\n","import { defineCommand } from 'citty'\nimport { getAuthToken } from '../../config'\nimport { CliError } from '../../errors'\n\nasync function doRequest(method: string, url: string, body: string | undefined, contentType: string, raw: boolean, showHeaders: boolean) {\n const token = getAuthToken()\n if (!token) {\n throw new CliError('Not authenticated. Run `apes login` first.')\n }\n\n const response = await fetch(url, {\n method,\n headers: {\n 'Authorization': `Bearer ${token}`,\n 'Content-Type': contentType,\n },\n body: body || undefined,\n })\n\n if (showHeaders) {\n console.log(`HTTP ${response.status} ${response.statusText}`)\n for (const [key, value] of response.headers.entries()) {\n console.log(`${key}: ${value}`)\n }\n console.log()\n }\n\n const respContentType = response.headers.get('content-type') || ''\n const text = await response.text()\n\n if (raw || !respContentType.includes('json')) {\n process.stdout.write(text)\n }\n else {\n try {\n console.log(JSON.stringify(JSON.parse(text), null, 2))\n }\n catch {\n process.stdout.write(text)\n }\n }\n\n if (!response.ok) {\n throw new CliError(`HTTP ${response.status} ${response.statusText}`)\n }\n}\n\nexport const fetchCommand = defineCommand({\n meta: {\n name: 'fetch',\n description: 'Make authenticated HTTP requests',\n },\n subCommands: {\n get: defineCommand({\n meta: {\n name: 'get',\n description: 'GET request with auth token',\n },\n args: {\n url: {\n type: 'positional',\n description: 'URL to fetch',\n required: true,\n },\n raw: {\n type: 'boolean',\n description: 'Output raw response body',\n default: false,\n },\n headers: {\n type: 'boolean',\n description: 'Show response headers',\n default: false,\n },\n },\n async run({ args }) {\n await doRequest('GET', String(args.url), undefined, 'application/json', Boolean(args.raw), Boolean(args.headers))\n },\n }),\n\n post: defineCommand({\n meta: {\n name: 'post',\n description: 'POST request with auth token',\n },\n args: {\n url: {\n type: 'positional',\n description: 'URL to fetch',\n required: true,\n },\n body: {\n type: 'string',\n description: 'Request body (JSON string)',\n },\n 'content-type': {\n type: 'string',\n description: 'Content-Type header',\n default: 'application/json',\n },\n raw: {\n type: 'boolean',\n description: 'Output raw response body',\n default: false,\n },\n headers: {\n type: 'boolean',\n description: 'Show response headers',\n default: false,\n },\n },\n async run({ args }) {\n await doRequest('POST', String(args.url), args.body as string | undefined, String(args['content-type'] || 'application/json'), Boolean(args.raw), Boolean(args.headers))\n },\n }),\n },\n})\n","import { defineCommand } from 'citty'\n\nexport const mcpCommand = defineCommand({\n meta: {\n name: 'mcp',\n description: 'Start MCP server for AI agents',\n },\n args: {\n transport: {\n type: 'string',\n description: 'Transport type: stdio or sse',\n default: 'stdio',\n },\n port: {\n type: 'string',\n description: 'Port for SSE transport',\n default: '3001',\n },\n },\n async run({ args }) {\n const transport = (args.transport || 'stdio') as 'stdio' | 'sse'\n const port = Number.parseInt(String(args.port), 10)\n\n if (transport !== 'stdio' && transport !== 'sse') {\n throw new Error('Transport must be \"stdio\" or \"sse\"')\n }\n\n const { startMcpServer } = await import('./server.js')\n await startMcpServer(transport, port)\n },\n})\n","import { existsSync, copyFileSync, writeFileSync } from 'node:fs'\nimport { randomBytes } from 'node:crypto'\nimport { execFileSync } from 'node:child_process'\nimport { join } from 'node:path'\nimport { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { CliError, CliExit } from '../../errors'\n\nconst DEFAULT_IDP_URL = 'https://id.openape.at'\n\nasync function downloadTemplate(repo: string, targetDir: string) {\n const { downloadTemplate: gigetDownload } = await import('giget')\n await gigetDownload(`gh:${repo}`, { dir: targetDir, force: false })\n}\n\nfunction installDeps(dir: string) {\n const hasLockFile = (name: string) => existsSync(join(dir, name))\n\n if (hasLockFile('pnpm-lock.yaml')) {\n execFileSync('pnpm', ['install'], { cwd: dir, stdio: 'inherit' })\n }\n else if (hasLockFile('bun.lockb')) {\n execFileSync('bun', ['install'], { cwd: dir, stdio: 'inherit' })\n }\n else {\n execFileSync('npm', ['install'], { cwd: dir, stdio: 'inherit' })\n }\n}\n\nasync function promptChoice(message: string, choices: string[]): Promise<string> {\n const result = await consola.prompt(message, { type: 'select', options: choices })\n if (typeof result === 'symbol') {\n throw new CliExit(0)\n }\n return result as string\n}\n\nasync function promptText(message: string, defaultValue?: string): Promise<string> {\n const result = await consola.prompt(message, { type: 'text', default: defaultValue, placeholder: defaultValue })\n if (typeof result === 'symbol') {\n throw new CliExit(0)\n }\n return (result as string) || defaultValue || ''\n}\n\nexport const initCommand = defineCommand({\n meta: {\n name: 'init',\n description: 'Scaffold a new OpenApe project',\n },\n args: {\n sp: {\n type: 'boolean',\n description: 'Create a Service Provider app',\n },\n idp: {\n type: 'boolean',\n description: 'Create an Identity Provider app',\n },\n dir: {\n type: 'positional',\n description: 'Target directory',\n required: false,\n },\n },\n async run({ args }) {\n let mode: 'sp' | 'idp'\n\n if (args.sp) {\n mode = 'sp'\n }\n else if (args.idp) {\n mode = 'idp'\n }\n else {\n const choice = await promptChoice('What do you want to set up?', [\n 'SP — Add login to my app',\n 'IdP — Run my own Identity Provider',\n ])\n mode = choice.startsWith('SP') ? 'sp' : 'idp'\n }\n\n if (mode === 'sp') {\n await initSP(args.dir)\n }\n else {\n await initIdP(args.dir)\n }\n },\n})\n\nasync function initSP(targetDir?: string) {\n const dir = targetDir || 'my-app'\n\n if (existsSync(join(dir, 'package.json'))) {\n throw new CliError(`Directory \"${dir}\" already contains a project.`)\n }\n\n consola.start('Scaffolding SP starter...')\n await downloadTemplate('openape-ai/openape-sp-starter', dir)\n consola.success('Scaffolded from openape-sp-starter')\n\n consola.start('Installing dependencies...')\n installDeps(dir)\n consola.success('Dependencies installed')\n\n // Create .env from .env.example\n const envExample = join(dir, '.env.example')\n const envFile = join(dir, '.env')\n if (existsSync(envExample) && !existsSync(envFile)) {\n copyFileSync(envExample, envFile)\n consola.success(`\\`.env\\` created (using Free IdP at ${DEFAULT_IDP_URL})`)\n }\n\n console.log('')\n consola.box([\n `cd ${dir}`,\n 'npm run dev',\n '',\n 'Then open http://localhost:3001/login',\n ].join('\\n'))\n}\n\nasync function initIdP(targetDir?: string) {\n const dir = targetDir || 'my-idp'\n\n if (existsSync(join(dir, 'package.json'))) {\n throw new CliError(`Directory \"${dir}\" already contains a project.`)\n }\n\n // Interactive questions\n const domain = await promptText('Domain for the IdP', 'localhost')\n const storage = await promptChoice('Storage backend', [\n 'memory (dev only, data lost on restart)',\n 'fs (local filesystem)',\n 's3 (S3-compatible)',\n ])\n const adminEmail = await promptText('Admin email')\n\n consola.start('Scaffolding IdP starter...')\n await downloadTemplate('openape-ai/openape-idp-starter', dir)\n consola.success('Scaffolded from openape-idp-starter')\n\n consola.start('Installing dependencies...')\n installDeps(dir)\n consola.success('Dependencies installed')\n\n // Generate secrets\n const sessionSecret = randomBytes(32).toString('hex')\n const managementToken = randomBytes(32).toString('hex')\n consola.success('Secrets generated')\n\n // Determine origin/issuer\n const isLocalhost = domain === 'localhost'\n const origin = isLocalhost ? 'http://localhost:3000' : `https://${domain}`\n\n // Write .env\n const envContent = [\n '# Generated by apes init --idp',\n '',\n `NUXT_OPENAPE_SESSION_SECRET=${sessionSecret}`,\n `NUXT_OPENAPE_ADMIN_EMAILS=${adminEmail}`,\n `NUXT_OPENAPE_MANAGEMENT_TOKEN=${managementToken}`,\n `NUXT_OPENAPE_ISSUER=${origin}`,\n `NUXT_OPENAPE_RP_NAME=My Identity Provider`,\n `NUXT_OPENAPE_RP_ID=${domain}`,\n `NUXT_OPENAPE_RP_ORIGIN=${origin}`,\n ].join('\\n')\n\n writeFileSync(join(dir, '.env'), `${envContent}\\n`, { mode: 0o600 })\n consola.success('.env created')\n\n console.log('')\n consola.box([\n `cd ${dir}`,\n 'npm run dev',\n '',\n 'Then open http://localhost:3000/admin',\n '',\n ...(isLocalhost\n ? []\n : [\n 'For production:',\n ` 1. DNS TXT Record: _ddisa.${domain.replace(/^id\\./, '')} → \"v=ddisa1 idp=${origin}\"`,\n ` 2. Storage: switch to ${storage.includes('s3') ? 's3' : 'fs'} in nuxt.config.ts`,\n ' 3. Deploy: vercel deploy',\n ]),\n ].join('\\n'))\n}\n","import { Buffer } from 'node:buffer'\nimport { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'\nimport { execFile } from 'node:child_process'\nimport { generateKeyPairSync, sign } from 'node:crypto'\nimport { dirname, resolve } from 'node:path'\nimport { homedir } from 'node:os'\nimport { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { loadEd25519PrivateKey } from '../ssh-key'\nimport { getAgentChallengeEndpoint, getAgentAuthenticateEndpoint } from '../http'\nimport { saveAuth, saveConfig, loadConfig } from '../config'\nimport { CliError, CliExit } from '../errors'\n\nconst DEFAULT_IDP_URL = 'https://id.openape.at'\nconst DEFAULT_KEY_PATH = '~/.ssh/id_ed25519'\nconst POLL_INTERVAL = 3000\nconst POLL_TIMEOUT = 300_000 // 5 minutes\n\nfunction resolvePath(p: string): string {\n return resolve(p.replace(/^~/, homedir()))\n}\n\nfunction openBrowser(url: string) {\n const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open'\n execFile(cmd, [url], () => {})\n}\n\nfunction readPublicKey(keyPath: string): string {\n const pubPath = `${keyPath}.pub`\n if (existsSync(pubPath)) {\n return readFileSync(pubPath, 'utf-8').trim()\n }\n\n // Derive public key from private key\n const keyContent = readFileSync(keyPath, 'utf-8')\n const privateKey = loadEd25519PrivateKey(keyContent)\n const jwk = privateKey.export({ format: 'jwk' }) as { x: string }\n const pubBytes = Buffer.from(jwk.x, 'base64url')\n\n // Format as OpenSSH public key\n const keyTypeStr = 'ssh-ed25519'\n const keyTypeLen = Buffer.alloc(4)\n keyTypeLen.writeUInt32BE(keyTypeStr.length)\n const pubKeyLen = Buffer.alloc(4)\n pubKeyLen.writeUInt32BE(pubBytes.length)\n const blob = Buffer.concat([keyTypeLen, Buffer.from(keyTypeStr), pubKeyLen, pubBytes])\n\n return `ssh-ed25519 ${blob.toString('base64')}`\n}\n\nfunction generateAndSaveKey(keyPath: string): string {\n const resolved = resolvePath(keyPath)\n const dir = dirname(resolved)\n\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true })\n }\n\n // Generate Ed25519 key pair\n const { publicKey, privateKey } = generateKeyPairSync('ed25519')\n\n // Export private key in PKCS8 PEM format (universally readable)\n const privatePem = privateKey.export({ type: 'pkcs8', format: 'pem' }) as string\n writeFileSync(resolved, privatePem, { mode: 0o600 })\n\n // Export public key in OpenSSH format\n const jwk = publicKey.export({ format: 'jwk' }) as { x: string }\n const pubBytes = Buffer.from(jwk.x, 'base64url')\n const keyTypeStr = 'ssh-ed25519'\n const keyTypeLen = Buffer.alloc(4)\n keyTypeLen.writeUInt32BE(keyTypeStr.length)\n const pubKeyLen = Buffer.alloc(4)\n pubKeyLen.writeUInt32BE(pubBytes.length)\n const blob = Buffer.concat([keyTypeLen, Buffer.from(keyTypeStr), pubKeyLen, pubBytes])\n const pubKeyStr = `ssh-ed25519 ${blob.toString('base64')}`\n\n writeFileSync(`${resolved}.pub`, `${pubKeyStr}\\n`, { mode: 0o644 })\n\n return pubKeyStr\n}\n\nasync function pollForEnrollment(\n idp: string,\n agentEmail: string,\n keyPath: string,\n): Promise<{ token: string, expiresIn: number }> {\n const resolvedKey = resolvePath(keyPath)\n const keyContent = readFileSync(resolvedKey, 'utf-8')\n const privateKey = loadEd25519PrivateKey(keyContent)\n\n const challengeUrl = await getAgentChallengeEndpoint(idp)\n const authenticateUrl = await getAgentAuthenticateEndpoint(idp)\n const startTime = Date.now()\n\n while (Date.now() - startTime < POLL_TIMEOUT) {\n try {\n // Try to get a challenge — if it works, agent is enrolled\n const challengeResp = await fetch(challengeUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ agent_id: agentEmail }),\n })\n\n if (challengeResp.ok) {\n const { challenge } = await challengeResp.json() as { challenge: string }\n const signature = sign(null, Buffer.from(challenge), privateKey).toString('base64')\n\n const authResp = await fetch(authenticateUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ agent_id: agentEmail, challenge, signature }),\n })\n\n if (authResp.ok) {\n const result = await authResp.json() as { token: string, expires_in: number }\n return { token: result.token, expiresIn: result.expires_in }\n }\n }\n }\n catch {\n // Ignore network errors during polling\n }\n\n await new Promise(resolve => setTimeout(resolve, POLL_INTERVAL))\n }\n\n throw new Error('Enrollment timed out. Please check the browser and try again.')\n}\n\nexport const enrollCommand = defineCommand({\n meta: {\n name: 'enroll',\n description: 'Enroll an agent with an Identity Provider',\n },\n args: {\n idp: {\n type: 'string',\n description: `IdP URL (default: ${DEFAULT_IDP_URL})`,\n },\n name: {\n type: 'string',\n description: 'Agent name',\n },\n key: {\n type: 'string',\n description: `Path to Ed25519 key (default: ${DEFAULT_KEY_PATH})`,\n },\n },\n async run({ args }) {\n // 1. Gather inputs\n const idp = args.idp\n || await consola.prompt('IdP URL', { type: 'text', default: DEFAULT_IDP_URL, placeholder: DEFAULT_IDP_URL }).then((r) => { if (typeof r === 'symbol') throw new CliExit(0); return r }) as string\n || DEFAULT_IDP_URL\n\n const agentName = args.name\n || await consola.prompt('Agent name', { type: 'text', placeholder: 'deploy-bot' }).then((r) => { if (typeof r === 'symbol') throw new CliExit(0); return r }) as string\n\n if (!agentName) {\n throw new CliError('Agent name is required.')\n }\n\n const keyPath = args.key\n || await consola.prompt('Ed25519 key', { type: 'text', default: DEFAULT_KEY_PATH, placeholder: DEFAULT_KEY_PATH }).then((r) => { if (typeof r === 'symbol') throw new CliExit(0); return r }) as string\n || DEFAULT_KEY_PATH\n\n // 2. Handle key\n const resolvedKey = resolvePath(keyPath)\n let publicKey: string\n\n if (existsSync(resolvedKey)) {\n publicKey = readPublicKey(resolvedKey)\n consola.success(`Using existing key ${keyPath}`)\n }\n else {\n consola.start(`Generating Ed25519 key pair at ${keyPath}...`)\n publicKey = generateAndSaveKey(keyPath)\n consola.success(`Key pair generated at ${keyPath}`)\n }\n\n // 3. Open browser for enrollment\n const encodedKey = encodeURIComponent(publicKey)\n const enrollUrl = `${idp}/enroll?name=${encodeURIComponent(agentName)}&key=${encodedKey}`\n\n consola.info('Opening browser for enrollment...')\n consola.info(`→ ${idp}/enroll`)\n openBrowser(enrollUrl)\n\n // 4. Determine expected agent email\n // For the free IdP, the email format is: {name}+{user_local}+{user_domain}@id.openape.at\n // For custom IdPs, the format varies. We'll try common patterns.\n // The polling will try the challenge endpoint which accepts email as agent_id.\n // We need to guess the email, or poll without knowing it.\n // Best approach: ask the user to confirm the email shown in browser.\n console.log('')\n const agentEmail = await consola.prompt(\n 'Agent email (shown in browser after enrollment)',\n { type: 'text', placeholder: `agent+${agentName}@...` },\n ).then((r) => { if (typeof r === 'symbol') throw new CliExit(0); return r }) as string\n\n if (!agentEmail) {\n throw new CliError('Agent email is required to verify enrollment.')\n }\n\n // 5. Poll for enrollment confirmation via challenge endpoint\n consola.start('Verifying enrollment...')\n const { token, expiresIn } = await pollForEnrollment(idp, agentEmail, keyPath)\n\n // 6. Save auth + config\n saveAuth({\n idp,\n access_token: token,\n email: agentEmail,\n expires_at: Math.floor(Date.now() / 1000) + (expiresIn || 3600),\n })\n\n const config = loadConfig()\n config.defaults = { ...config.defaults, idp }\n config.agent = { key: keyPath, email: agentEmail }\n saveConfig(config)\n\n consola.success(`Agent enrolled as ${agentEmail}`)\n consola.success('Config saved to ~/.config/apes/')\n\n console.log('')\n consola.info('Verify with: apes whoami')\n },\n})\n","import { existsSync, readFileSync } from 'node:fs'\nimport { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { apiFetch } from '../http'\nimport { loadAuth, getIdpUrl } from '../config'\nimport { CliError } from '../errors'\n\nexport const registerUserCommand = defineCommand({\n meta: {\n name: 'register-user',\n description: 'Register a sub-user with SSH key',\n },\n args: {\n email: {\n type: 'string',\n description: 'Email for the new user',\n required: true,\n },\n name: {\n type: 'string',\n description: 'Name for the new user',\n required: true,\n },\n key: {\n type: 'string',\n description: 'Path to SSH public key file or key string',\n required: true,\n },\n type: {\n type: 'string',\n description: 'User type: human or agent (default: agent)',\n },\n },\n async run({ args }) {\n const auth = loadAuth()\n if (!auth) {\n throw new CliError('Not authenticated. Run `apes login` first.')\n }\n\n const idp = getIdpUrl()\n if (!idp) {\n throw new CliError('No IdP URL configured. Run `apes login` first.')\n }\n\n // Read key from file or use as string\n let publicKey = args.key\n if (existsSync(args.key)) {\n publicKey = readFileSync(args.key, 'utf-8').trim()\n }\n\n if (!publicKey.startsWith('ssh-ed25519 ')) {\n throw new CliError('Public key must be in ssh-ed25519 format.')\n }\n\n const userType = args.type as 'human' | 'agent' | undefined\n if (userType && userType !== 'human' && userType !== 'agent') {\n throw new CliError('Type must be \"human\" or \"agent\".')\n }\n\n const result = await apiFetch<{\n email: string\n name: string\n owner: string\n type: string\n }>(`${idp}/api/auth/enroll`, {\n method: 'POST',\n body: {\n email: args.email,\n name: args.name,\n publicKey,\n ...(userType ? { type: userType } : {}),\n },\n })\n\n consola.success(`User registered: ${result.email} (type: ${result.type}, owner: ${result.owner})`)\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { resolveDDISA } from '@openape/core'\nimport { CliError } from '../errors'\n\nexport const dnsCheckCommand = defineCommand({\n meta: {\n name: 'dns-check',\n description: 'Validate DDISA DNS TXT records for a domain',\n },\n args: {\n domain: {\n type: 'positional',\n description: 'Domain to check (e.g. example.com)',\n required: true,\n },\n },\n async run({ args }) {\n const domain = args.domain\n\n consola.start(`Checking _ddisa.${domain}...`)\n\n try {\n const result = await resolveDDISA(domain)\n\n if (!result) {\n console.log('')\n console.log('To set up DDISA, add a DNS TXT record:')\n console.log(` _ddisa.${domain} TXT \"v=ddisa1 idp=https://id.${domain}\"`)\n throw new CliError(`No DDISA record found for ${domain}`)\n }\n\n consola.success(`_ddisa.${domain} → ${result.idp}`)\n console.log('')\n console.log(` Version: ${result.version || 'ddisa1'}`)\n console.log(` IdP URL: ${result.idp}`)\n if (result.mode)\n console.log(` Mode: ${result.mode}`)\n if (result.priority !== undefined)\n console.log(` Priority: ${result.priority}`)\n\n // Try OIDC discovery on the IdP\n console.log('')\n consola.start(`Verifying IdP at ${result.idp}...`)\n\n const discoResp = await fetch(`${result.idp}/.well-known/openid-configuration`)\n\n if (!discoResp.ok) {\n consola.warn(`IdP discovery failed (${discoResp.status}). Is the IdP running at ${result.idp}?`)\n return\n }\n\n const disco = await discoResp.json() as Record<string, unknown>\n\n consola.success(`IdP is reachable`)\n console.log(` Issuer: ${disco.issuer}`)\n console.log(` DDISA: v${disco.ddisa_version || '?'}`)\n\n if (disco.ddisa_auth_methods_supported) {\n console.log(` Auth: ${(disco.ddisa_auth_methods_supported as string[]).join(', ')}`)\n }\n\n if (disco.openape_grant_types_supported) {\n console.log(` Grants: ${(disco.openape_grant_types_supported as string[]).join(', ')}`)\n }\n }\n catch (err) {\n throw new CliError(`DNS check failed: ${err instanceof Error ? err.message : String(err)}`)\n }\n },\n})\n","import { exec } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport { defineCommand } from 'citty'\nimport { AUTH_FILE, CONFIG_DIR, loadAuth } from '../config'\nimport { apiFetch, getGrantsEndpoint } from '../http'\nimport { CliError } from '../errors'\n\ndeclare const __VERSION__: string\n\ninterface HealthArgs {\n json: boolean\n}\n\ninterface HealthReport {\n version: string\n config: { dir: string }\n auth: {\n file: string\n present: boolean\n email?: string\n type?: 'human' | 'agent'\n idp?: string\n expires_at_iso?: string\n expires_at_local?: string\n expired?: boolean\n }\n idp: { url?: string, reachable: boolean, error?: string }\n grants: { count?: number, error?: string }\n ape_shell_binary: string | null\n ok: boolean\n}\n\nconst execAsync = promisify(exec)\n\nasync function resolveApeShellPath(): Promise<string | null> {\n try {\n const { stdout } = await execAsync('command -v ape-shell', { shell: '/bin/bash' })\n const trimmed = stdout.trim()\n return trimmed.length > 0 ? trimmed : null\n }\n catch {\n return null\n }\n}\n\nasync function probeIdp(url: string): Promise<{ reachable: true } | { reachable: false, error: string }> {\n const ctrl = new AbortController()\n const timeout = setTimeout(() => ctrl.abort(), 3000)\n try {\n // Plain fetch — we don't want apiFetch's bearer token or retry logic.\n // HEAD may not be supported; fall back to GET if needed.\n await fetch(url, { method: 'GET', signal: ctrl.signal })\n return { reachable: true }\n }\n catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n return { reachable: false, error: message }\n }\n finally {\n clearTimeout(timeout)\n }\n}\n\nasync function bestEffortGrantCount(idp: string): Promise<{ count: number } | { error: string }> {\n try {\n const grantsUrl = await getGrantsEndpoint(idp)\n const res = await apiFetch<{ data: unknown[] }>(`${grantsUrl}?limit=1`)\n const count = Array.isArray(res?.data) ? res.data.length : 0\n return { count }\n }\n catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n return { error: message }\n }\n}\n\nexport async function runHealth(args: HealthArgs): Promise<void> {\n const version = typeof __VERSION__ === 'string' ? __VERSION__ : '0.0.0'\n\n const auth = loadAuth()\n if (!auth) {\n throw new CliError('Not logged in. Run `apes login` first.', 1)\n }\n\n const isAgent = auth.email.includes('agent+')\n const expiresDate = new Date(auth.expires_at * 1000)\n const isExpired = Date.now() / 1000 > auth.expires_at\n\n if (isExpired) {\n throw new CliError(`Token expired at ${expiresDate.toISOString()}. Run \\`apes login\\`.`, 1)\n }\n\n const idpProbe = await probeIdp(auth.idp)\n const grantInfo = await bestEffortGrantCount(auth.idp)\n const apeShellPath = await resolveApeShellPath()\n\n const report: HealthReport = {\n version,\n config: { dir: CONFIG_DIR },\n auth: {\n file: AUTH_FILE,\n present: true,\n email: auth.email,\n type: isAgent ? 'agent' : 'human',\n idp: auth.idp,\n expires_at_iso: expiresDate.toISOString(),\n expires_at_local: expiresDate.toLocaleString(),\n expired: false,\n },\n idp: {\n url: auth.idp,\n reachable: idpProbe.reachable,\n ...('error' in idpProbe ? { error: idpProbe.error } : {}),\n },\n grants: 'count' in grantInfo\n ? { count: grantInfo.count }\n : { error: grantInfo.error },\n ape_shell_binary: apeShellPath,\n ok: idpProbe.reachable,\n }\n\n if (args.json) {\n console.log(JSON.stringify(report, null, 2))\n }\n else {\n console.log(`apes ${version}`)\n console.log('')\n console.log(`Config: ${CONFIG_DIR}`)\n console.log(`Auth: ${AUTH_FILE}`)\n console.log(` ${auth.email} (${isAgent ? 'agent' : 'human'})`)\n console.log(` IdP: ${auth.idp}`)\n console.log(` Token: valid until ${expiresDate.toISOString()} (local: ${expiresDate.toLocaleString()})`)\n console.log('')\n if (idpProbe.reachable) {\n console.log('IdP: reachable')\n }\n else {\n console.log(`IdP: <unreachable: ${idpProbe.error}>`)\n }\n if ('count' in grantInfo) {\n console.log(`Grants: ${grantInfo.count}`)\n }\n else {\n console.log(`Grants: <unreachable: ${grantInfo.error}>`)\n }\n console.log(`ape-shell: ${apeShellPath ?? '(not on PATH)'}`)\n }\n\n if (!idpProbe.reachable) {\n throw new CliError(`IdP ${auth.idp} unreachable: ${idpProbe.error}`, 1)\n }\n}\n\nexport const healthCommand = defineCommand({\n meta: {\n name: 'health',\n description: 'Report CLI diagnostic state (auth, IdP, grants, binaries)',\n },\n args: {\n json: {\n type: 'boolean',\n description: 'Emit a machine-readable JSON report',\n default: false,\n },\n },\n async run({ args }) {\n await runHealth({ json: Boolean(args.json) })\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { guides } from '../guides'\nimport { CliError } from '../errors'\n\nexport const workflowsCommand = defineCommand({\n meta: {\n name: 'workflows',\n description: 'Discover workflow guides',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Guide ID to show (omit for list)',\n required: false,\n },\n json: {\n type: 'boolean',\n description: 'Output as JSON',\n default: false,\n },\n },\n run({ args }) {\n if (args.id) {\n const guide = guides.find(g => g.id === String(args.id))\n if (!guide) {\n consola.info(`Available: ${guides.map(g => g.id).join(', ')}`)\n throw new CliError(`Guide not found: ${args.id}`)\n }\n\n if (args.json) {\n console.log(JSON.stringify(guide, null, 2))\n return\n }\n\n console.log(`\\n ${guide.title}`)\n console.log(` ${guide.description}\\n`)\n for (let i = 0; i < guide.steps.length; i++) {\n const step = guide.steps[i]!\n if (step.note) {\n console.log(` Note: ${step.note}`)\n }\n else {\n console.log(` ${i + 1}. ${step.description}`)\n if (step.command) {\n console.log(` $ ${step.command}`)\n }\n }\n }\n console.log()\n return\n }\n\n // List mode\n if (args.json) {\n console.log(JSON.stringify(guides.map(g => ({ id: g.id, title: g.title, description: g.description })), null, 2))\n return\n }\n\n console.log('\\n Workflow Guides\\n')\n for (const guide of guides) {\n console.log(` ${guide.id.padEnd(24)} ${guide.title}`)\n }\n console.log(`\\n Show a guide: apes workflows <id>\\n`)\n },\n})\n","export interface WorkflowStep {\n description?: string\n command?: string\n note?: string\n}\n\nexport interface WorkflowGuide {\n id: string\n title: string\n description: string\n steps: WorkflowStep[]\n}\n\nexport const guides: WorkflowGuide[] = [\n {\n id: 'timed-session',\n title: 'Timed maintenance session',\n description: 'Request a timed grant for multiple commands without per-command approval.',\n steps: [\n { description: 'Request a timed grant (e.g. 1 hour)', command: 'apes run --approval timed -- <your-command>' },\n { description: 'Approve the grant in the browser (link is printed)' },\n { description: 'Subsequent commands reuse the timed grant until it expires' },\n { note: 'Use --approval always for standing permissions (revoke manually when done)' },\n ],\n },\n {\n id: 'agent-onboarding',\n title: 'Onboard a new agent',\n description: 'Register an AI agent with a DDISA identity in under 3 minutes.',\n steps: [\n { description: 'Initialize a new project (optional)', command: 'apes init --sp my-app' },\n { description: 'Enroll the agent at an IdP', command: 'apes enroll' },\n { description: 'Verify enrollment', command: 'apes whoami' },\n { description: 'Check DNS discovery', command: 'apes dns-check' },\n ],\n },\n {\n id: 'delegation',\n title: 'Delegate permissions',\n description: 'Let an agent act on your behalf at a specific service.',\n steps: [\n { description: 'Create a delegation', command: 'apes grants delegate --to agent@example.com --at api.example.com' },\n { description: 'List active delegations', command: 'apes grants delegations' },\n { description: 'Revoke when no longer needed', command: 'apes grants revoke <delegation-id>' },\n ],\n },\n {\n id: 'privilege-escalation',\n title: 'Run commands as root (escapes)',\n description: 'Execute privileged commands with grant-verified escalation.',\n steps: [\n { description: 'Request a grant to run a command as root', command: 'apes run --as root -- apt-get upgrade' },\n { description: 'Approve the grant in the browser' },\n { description: 'The command executes via escapes with verified authorization' },\n { note: 'escapes must be installed on the target machine (cargo build && sudo make install)' },\n ],\n },\n]\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAOA,eAAa;;;ACApB,OAAO,UAAU;AAuCV,SAAS,oBAAoB,MAAgB,OAAuC;AACzF,QAAM,eAAe,KAAK,CAAC,KAAK;AAMhC,QAAM,gBAAgB,aAAa,WAAW,GAAG;AACjD,QAAM,gBAAgB,OAAO,UAAU,YAAY,MAAM,WAAW,GAAG;AACvE,QAAM,sBAAsB,iBAAiB;AAC7C,QAAM,sBAAsB,gBAAgB,aAAa,MAAM,CAAC,IAAI;AACpE,QAAM,YAAY,KAAK,SAAS,mBAAmB;AAKnD,QAAM,aAAa,OAAO,YAAY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a;AAAA,IACX,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,iBAAiB;AAAA,IACjB,aAAa;AAAA,IACb,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,KAAK;AAAA,IACL,SAAS;AAAA,IACT,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,KAAK;AAAA,IACL,WAAW;AAAA,EACb;AACF,CAAC;AAED,QAAQ,IAAI,EAAE,MAAM,CAAC,QAAQ;AAC3B,MAAI,eAAe,SAAS;AAC1B,YAAQ,KAAK,IAAI,QAAQ;AAAA,EAC3B;AACA,MAAI,eAAe,UAAU;AAC3B,IAAAC,UAAQ,MAAM,IAAI,OAAO;AACzB,YAAQ,KAAK,IAAI,QAAQ;AAAA,EAC3B;AACA,MAAI,OAAO;AACT,IAAAA,UAAQ,MAAM,GAAG;AAAA,EACnB,OACK;AACH,IAAAA,UAAQ,MAAM,eAAe,WAAW,IAAI,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,EACxG;AACA,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["consola","defineCommand","homedir","consola","resolve","consola","readFileSync","sign","loadEd25519PrivateKey","homedir","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","defineCommand","defineCommand","consola","defineCommand","consola","hostname","defineCommand","consola","waitForApproval","consola","resolve","defineCommand","hostname","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","auth","defineCommand","consola","defineCommand","consola","defineCommand","defineCommand","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","defineCommand","consola","defineCommand","consola","existsSync","homedir","defineCommand","consola","getManagementToken","defineCommand","consola","homedir","existsSync","defineCommand","defineCommand","consola","defineCommand","index","consola","execFileSync","hostname","defineCommand","consola","consola","defineCommand","hostname","execFileSync","defineCommand","defineCommand","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","defineCommand","defineCommand","existsSync","execFileSync","join","defineCommand","consola","existsSync","join","execFileSync","consola","defineCommand","Buffer","existsSync","readFileSync","writeFileSync","execFile","resolve","homedir","defineCommand","consola","DEFAULT_IDP_URL","resolvePath","resolve","homedir","openBrowser","execFile","existsSync","readFileSync","Buffer","writeFileSync","defineCommand","consola","existsSync","readFileSync","defineCommand","consola","defineCommand","existsSync","readFileSync","consola","defineCommand","consola","resolveDDISA","defineCommand","consola","resolveDDISA","defineCommand","defineCommand","defineCommand","consola","defineCommand","consola","defineCommand","consola"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/ape-shell.ts","../src/commands/auth/login.ts","../src/commands/auth/resolve-login.ts","../src/commands/auth/logout.ts","../src/commands/auth/whoami.ts","../src/commands/grants/list.ts","../src/commands/grants/inbox.ts","../src/commands/grants/status.ts","../src/commands/grants/request.ts","../src/commands/grants/request-capability.ts","../src/commands/grants/approve.ts","../src/commands/grants/deny.ts","../src/commands/grants/revoke.ts","../src/commands/grants/run.ts","../src/commands/grants/token.ts","../src/commands/grants/delegate.ts","../src/commands/grants/delegations.ts","../src/commands/grants/delegation-revoke.ts","../src/commands/admin/index.ts","../src/commands/admin/users.ts","../src/commands/admin/ssh-keys.ts","../src/commands/adapter/index.ts","../src/commands/run.ts","../src/commands/explain.ts","../src/commands/config/get.ts","../src/commands/config/set.ts","../src/commands/fetch/index.ts","../src/commands/mcp/index.ts","../src/commands/init/index.ts","../src/commands/enroll.ts","../src/commands/register-user.ts","../src/commands/dns-check.ts","../src/commands/health.ts","../src/commands/workflows.ts","../src/guides/index.ts"],"sourcesContent":["import consola from 'consola'\nimport { rewriteApeShellArgs } from './ape-shell'\nimport { defineCommand, runMain } from 'citty'\nimport { loginCommand } from './commands/auth/login'\nimport { logoutCommand } from './commands/auth/logout'\nimport { whoamiCommand } from './commands/auth/whoami'\nimport { listCommand } from './commands/grants/list'\nimport { inboxCommand } from './commands/grants/inbox'\nimport { statusCommand } from './commands/grants/status'\nimport { requestCommand } from './commands/grants/request'\nimport { requestCapabilityCommand } from './commands/grants/request-capability'\nimport { approveCommand } from './commands/grants/approve'\nimport { denyCommand } from './commands/grants/deny'\nimport { revokeCommand } from './commands/grants/revoke'\nimport { runGrantCommand } from './commands/grants/run'\nimport { tokenCommand } from './commands/grants/token'\nimport { delegateCommand } from './commands/grants/delegate'\nimport { delegationsCommand } from './commands/grants/delegations'\nimport { delegationRevokeCommand } from './commands/grants/delegation-revoke'\nimport { adminCommand } from './commands/admin/index'\nimport { adapterCommand } from './commands/adapter/index'\nimport { runCommand } from './commands/run'\nimport { explainCommand } from './commands/explain'\nimport { configGetCommand } from './commands/config/get'\nimport { configSetCommand } from './commands/config/set'\nimport { fetchCommand } from './commands/fetch/index'\nimport { mcpCommand } from './commands/mcp/index'\nimport { initCommand } from './commands/init/index'\nimport { enrollCommand } from './commands/enroll'\nimport { registerUserCommand } from './commands/register-user'\nimport { dnsCheckCommand } from './commands/dns-check'\nimport { healthCommand } from './commands/health'\nimport { workflowsCommand } from './commands/workflows'\nimport { ApiError } from './http'\nimport { CliError, CliExit } from './errors'\n\n// Gracefully handle EPIPE when stdout is closed early (e.g. piped to `head`)\nprocess.stdout.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EPIPE') process.exit(0)\n throw err\n})\n\ndeclare const __VERSION__: string\n\n// ape-shell mode:\n// • `ape-shell -c <command>` rewrites to `apes run --shell -- bash -c <command>` (one-shot)\n// • `ape-shell` (no args), `-i`, `-l`, or invoked as a login shell → interactive REPL\n// Pass `process.argv0` explicitly so the wrapper script path (which uses\n// bash's `exec -a \"$0\"` to preserve the original argv[0] from login/sshd)\n// still benefits from login-shell detection when the cli.js is invoked\n// indirectly via the ape-shell-wrapper.sh shim.\nconst shellRewrite = rewriteApeShellArgs(process.argv, process.argv0)\nif (shellRewrite) {\n if (shellRewrite.action === 'rewrite') {\n process.argv = shellRewrite.argv\n }\n else if (shellRewrite.action === 'version') {\n console.log(`ape-shell ${__VERSION__} (OpenApe DDISA shell wrapper)`)\n process.exit(0)\n }\n else if (shellRewrite.action === 'help') {\n console.log(`ape-shell ${__VERSION__} — OpenApe DDISA shell wrapper`)\n console.log('')\n console.log('Usage:')\n console.log(' ape-shell Start interactive grant-mediated REPL')\n console.log(' ape-shell -c <command> Run a single command through the grant flow')\n console.log(' ape-shell -i | -l Force interactive mode')\n console.log('')\n console.log('Options:')\n console.log(' -c <command> Execute <command> via the apes grant flow and exit')\n console.log(' -i Interactive REPL (default when no args are given)')\n console.log(' -l, --login Login shell semantics — currently same as -i')\n console.log(' --version, -v Show ape-shell version')\n console.log(' --help, -h Show this help message')\n process.exit(0)\n }\n else if (shellRewrite.action === 'interactive') {\n // Hand control to the interactive REPL orchestrator. Never returns to\n // citty dispatch. Dynamic import so the startup path for `ape-shell -c`\n // stays lean (node-pty native module is only loaded when needed).\n const { runInteractiveShell } = await import('./shell/orchestrator.js')\n await runInteractiveShell()\n process.exit(0)\n }\n else {\n console.error('ape-shell: unsupported invocation. Try `ape-shell --help`.')\n process.exit(1)\n }\n}\n\nconst debug = process.argv.includes('--debug')\n\nconst grantsCommand = defineCommand({\n meta: {\n name: 'grants',\n description: 'Grant management',\n },\n subCommands: {\n list: listCommand,\n inbox: inboxCommand,\n status: statusCommand,\n request: requestCommand,\n 'request-capability': requestCapabilityCommand,\n approve: approveCommand,\n deny: denyCommand,\n revoke: revokeCommand,\n run: runGrantCommand,\n token: tokenCommand,\n delegate: delegateCommand,\n delegations: delegationsCommand,\n 'delegation-revoke': delegationRevokeCommand,\n },\n})\n\nconst configCommand = defineCommand({\n meta: {\n name: 'config',\n description: 'Configuration management',\n },\n subCommands: {\n get: configGetCommand,\n set: configSetCommand,\n },\n})\n\nconst main = defineCommand({\n meta: {\n name: 'apes',\n version: __VERSION__,\n description: 'Unified CLI for OpenApe',\n },\n subCommands: {\n init: initCommand,\n enroll: enrollCommand,\n 'register-user': registerUserCommand,\n 'dns-check': dnsCheckCommand,\n login: loginCommand,\n logout: logoutCommand,\n whoami: whoamiCommand,\n health: healthCommand,\n grants: grantsCommand,\n admin: adminCommand,\n run: runCommand,\n explain: explainCommand,\n adapter: adapterCommand,\n config: configCommand,\n fetch: fetchCommand,\n mcp: mcpCommand,\n workflows: workflowsCommand,\n },\n})\n\nrunMain(main).catch((err) => {\n if (err instanceof CliExit) {\n process.exit(err.exitCode)\n }\n if (err instanceof CliError) {\n consola.error(err.message)\n process.exit(err.exitCode)\n }\n if (debug) {\n consola.error(err)\n }\n else {\n consola.error(err instanceof ApiError ? err.message : err instanceof Error ? err.message : String(err))\n }\n process.exit(1)\n})\n","import path from 'node:path'\n\n/**\n * Possible actions emitted by `rewriteApeShellArgs` for the caller to\n * dispatch. `rewrite` means argv has been transformed and the normal CLI\n * command dispatch should continue with the new argv. `interactive` means\n * the caller should hand control to the interactive REPL. The other\n * actions print version/help/error text and exit.\n */\nexport type ApeShellAction =\n | { action: 'rewrite', argv: string[] }\n | { action: 'version' }\n | { action: 'help' }\n | { action: 'error' }\n | { action: 'interactive' }\n\n/**\n * Decides how `ape-shell` was invoked and what the caller should do next.\n * Backward compatibility is strict: any invocation with `-c \"<command>\"`\n * keeps the historical rewrite behavior so `SHELL=$(which ape-shell) <prog>`\n * patterns (e.g. `SHELL=ape-shell openclaw tui`) continue to work.\n *\n * Detection strategy:\n * 1. `process.env.APES_SHELL_WRAPPER === '1'` is the strongest signal —\n * it means we were invoked via the ape-shell-wrapper.sh shell script,\n * which hoists node onto PATH before exec-ing cli.js. In that case\n * argv[1] becomes `cli.js` (or some dist/chunk file) and the old\n * basename check fails, so we trust the wrapper's declaration.\n * 2. Otherwise fall back to `argv[1]` basename matching literal\n * `ape-shell` / `ape-shell.js` (the direct-symlink invocation path).\n *\n * After detection, the rest of the rules decide the action (first match):\n * • `-c <command>` → rewrite to `apes run --shell -- bash -c <command>`.\n * • `--version` / `-v` → version action.\n * • `--help` / `-h` → help action.\n * • no args, `-i`, `-l`, `--login`, or a login-shell convention dash\n * prefix (on argv[1] or argv0) → interactive REPL.\n * • anything else → error action.\n */\nexport function rewriteApeShellArgs(argv: string[], argv0?: string): ApeShellAction | null {\n const rawInvokedAs = argv[1] ?? ''\n // sshd/login use a leading dash on argv[0] to signal \"login shell\".\n // Strip it for the basename comparison, but remember the flag. The dash\n // may appear on argv[1] (direct invocation) or on the separately-passed\n // argv0 parameter (wrapper invocation — shell `exec -a \"$0\"` sets node's\n // actual argv[0] / `process.argv0` independently from argv[1]).\n const dashFromArgv1 = rawInvokedAs.startsWith('-')\n const dashFromArgv0 = typeof argv0 === 'string' && argv0.startsWith('-')\n const looksLikeLoginShell = dashFromArgv1 || dashFromArgv0\n const normalizedInvokedAs = dashFromArgv1 ? rawInvokedAs.slice(1) : rawInvokedAs\n const invokedAs = path.basename(normalizedInvokedAs)\n\n // Primary detection: explicit wrapper signal via env var. Takes\n // precedence because argv-based detection gets clobbered when the\n // wrapper execs node directly and argv[1] becomes cli.js.\n const wrapperEnv = typeof process !== 'undefined' && process.env?.APES_SHELL_WRAPPER === '1'\n\n // Secondary detection: argv[1] basename matches literal `ape-shell` or\n // `ape-shell.js` — the direct-symlink invocation path.\n const argvMatch = invokedAs === 'ape-shell' || invokedAs === 'ape-shell.js'\n\n if (!wrapperEnv && !argvMatch)\n return null\n\n const shellArgs = argv.slice(2)\n\n // -c <command> is the historical one-shot path — must stay untouched so\n // programs that use `$SHELL -c \"<cmd>\"` (openclaw tui, xargs, git hooks,\n // sshd non-interactive, etc.) continue to work unchanged.\n if (shellArgs[0] === '-c' && shellArgs.length > 1) {\n return { action: 'rewrite', argv: [argv[0]!, argv[1]!, 'run', '--shell', '--', 'bash', '-c', ...shellArgs.slice(1)] }\n }\n\n if (shellArgs[0] === '--version' || shellArgs[0] === '-v')\n return { action: 'version' }\n\n if (shellArgs[0] === '--help' || shellArgs[0] === '-h')\n return { action: 'help' }\n\n // No positional args, explicit interactive flag, or login-shell\n // convention (`looksLikeLoginShell` detected from the dash-prefixed\n // argv[1] above) → enter the interactive REPL.\n if (\n shellArgs.length === 0\n || shellArgs[0] === '-i'\n || shellArgs[0] === '-l'\n || shellArgs[0] === '--login'\n || looksLikeLoginShell\n ) {\n return { action: 'interactive' }\n }\n\n return { action: 'error' }\n}\n","import { Buffer } from 'node:buffer'\nimport { execFile } from 'node:child_process'\nimport { createServer } from 'node:http'\nimport { homedir } from 'node:os'\nimport { resolve as resolvePath } from 'node:path'\nimport { defineCommand } from 'citty'\nimport { generateCodeChallenge, generateCodeVerifier } from '@openape/core'\nimport consola from 'consola'\nimport { loadConfig, saveAuth, saveConfig } from '../../config'\nimport { getAgentAuthenticateEndpoint, getAgentChallengeEndpoint } from '../../http'\nimport { CliError } from '../../errors'\nimport { resolveLoginInputs } from './resolve-login'\n\nconst CALLBACK_PORT = 9876\nconst CLIENT_ID = 'grapes-cli'\n\nexport const loginCommand = defineCommand({\n meta: {\n name: 'login',\n description: 'Authenticate with an OpenApe IdP',\n },\n args: {\n idp: {\n type: 'string',\n description: 'IdP URL (e.g. https://id.openape.at). Auto-discovered via DDISA DNS if omitted.',\n },\n key: {\n type: 'string',\n description: 'Path to agent private key. Defaults to ~/.ssh/id_ed25519 if present.',\n },\n email: {\n type: 'string',\n description: 'Agent email. Extracted from <key>.pub comment if omitted.',\n },\n browser: {\n type: 'boolean',\n description: 'Force browser (PKCE) login even if an SSH key exists',\n },\n },\n async run({ args }) {\n const resolved = await resolveLoginInputs({\n key: args.key,\n idp: args.idp,\n email: args.email,\n browser: args.browser,\n })\n\n if (resolved.keyPath) {\n if (!resolved.email) {\n throw new CliError(\n `Agent email required for key-based login. Add an email comment to `\n + `${resolved.keyPath}.pub (ssh-keygen -C <email>) or pass --email <agent-email>.`,\n )\n }\n if (!resolved.idp) {\n const domain = resolved.email.split('@')[1]\n throw new CliError(\n `No IdP found for ${resolved.email}.\\n\\n`\n + `There is no DDISA TXT record for ${domain} and no --idp was provided.\\n\\n`\n + `Options:\\n`\n + ` • Run your own IdP (recommended for production)\\n`\n + ` See: https://docs.openape.at\\n`\n + ` • Publish a DDISA TXT record for your domain:\\n`\n + ` _ddisa.${domain} TXT \"v=ddisa1 idp=https://your-idp.example\"\\n`\n + ` • Use OpenApe's free hosted IdP for testing:\\n`\n + ` apes login --idp https://id.openape.at`,\n )\n }\n await loginWithKey(resolved.idp, resolved.keyPath, resolved.email)\n }\n else {\n if (!resolved.idp) {\n throw new CliError('IdP URL required for browser login. Use --idp <url> or set APES_IDP.')\n }\n await loginWithPKCE(resolved.idp)\n }\n },\n})\n\nfunction openBrowser(url: string) {\n const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open'\n execFile(cmd, [url], () => {})\n}\n\nasync function loginWithPKCE(idp: string) {\n const codeVerifier = generateCodeVerifier()\n const codeChallenge = await generateCodeChallenge(codeVerifier)\n const redirectUri = `http://localhost:${CALLBACK_PORT}/callback`\n\n const state = crypto.randomUUID()\n const nonce = crypto.randomUUID()\n\n const authUrl = new URL(`${idp}/authorize`)\n authUrl.searchParams.set('response_type', 'code')\n authUrl.searchParams.set('client_id', CLIENT_ID)\n authUrl.searchParams.set('redirect_uri', redirectUri)\n authUrl.searchParams.set('code_challenge', codeChallenge)\n authUrl.searchParams.set('code_challenge_method', 'S256')\n authUrl.searchParams.set('state', state)\n authUrl.searchParams.set('nonce', nonce)\n authUrl.searchParams.set('scope', 'openid email profile offline_access')\n\n // Start local callback server\n const code = await new Promise<string>((resolve, reject) => {\n const server = createServer((req, res) => {\n const url = new URL(req.url!, `http://localhost:${CALLBACK_PORT}`)\n if (url.pathname === '/callback') {\n const authCode = url.searchParams.get('code')\n const error = url.searchParams.get('error')\n\n if (error) {\n res.writeHead(200, { 'Content-Type': 'text/html' })\n res.end('<h1>Login failed</h1><p>You can close this window.</p>')\n server.close()\n reject(new Error(`Auth error: ${error}`))\n return\n }\n\n if (authCode) {\n res.writeHead(200, { 'Content-Type': 'text/html' })\n res.end('<h1>Login successful!</h1><p>You can close this window.</p>')\n server.close()\n resolve(authCode)\n return\n }\n\n res.writeHead(400)\n res.end('Missing code')\n }\n else {\n res.writeHead(404)\n res.end()\n }\n })\n\n server.listen(CALLBACK_PORT, () => {\n // Always print the URL so the user can copy it manually — headless SSH\n // sessions, containers, and restricted-user shells cannot open a browser.\n // The `open` attempt below is fire-and-forget convenience only.\n console.log('')\n console.log('Visit the following URL in a browser to authenticate:')\n console.log('')\n console.log(` ${authUrl.toString()}`)\n console.log('')\n consola.info(`Waiting for authentication callback on ${redirectUri} ...`)\n openBrowser(authUrl.toString())\n })\n\n // Timeout after 5 minutes\n const timeout = setTimeout(() => {\n server.close()\n reject(new Error('Login timed out'))\n }, 300_000)\n timeout.unref()\n })\n\n // Exchange code for tokens\n const tokenResponse = await fetch(`${idp}/token`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n grant_type: 'authorization_code',\n code,\n code_verifier: codeVerifier,\n redirect_uri: redirectUri,\n client_id: CLIENT_ID,\n }),\n })\n\n if (!tokenResponse.ok) {\n const text = await tokenResponse.text()\n throw new CliError(`Token exchange failed: ${text}`)\n }\n\n const tokens = await tokenResponse.json() as {\n access_token?: string\n id_token?: string\n refresh_token?: string\n expires_in?: number\n assertion?: string\n }\n\n const accessToken = tokens.access_token || tokens.id_token || tokens.assertion\n if (!accessToken) {\n throw new CliError('No access token received')\n }\n\n // Decode JWT to get email\n const payload = JSON.parse(atob(accessToken.split('.')[1]!))\n\n saveAuth({\n idp,\n access_token: accessToken,\n ...(tokens.refresh_token ? { refresh_token: tokens.refresh_token } : {}),\n email: payload.email || payload.sub,\n expires_at: Math.floor(Date.now() / 1000) + (tokens.expires_in || 3600),\n })\n\n consola.success(`Logged in as ${payload.email || payload.sub}`)\n}\n\nasync function loginWithKey(idp: string, keyPath: string, agentEmail: string) {\n const { readFileSync } = await import('node:fs')\n const { sign } = await import('node:crypto')\n const { loadEd25519PrivateKey } = await import('../../ssh-key.js')\n\n // Use challenge-response auth (endpoint resolved via OIDC discovery)\n const challengeUrl = await getAgentChallengeEndpoint(idp)\n const challengeResp = await fetch(challengeUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ agent_id: agentEmail }),\n })\n\n if (!challengeResp.ok) {\n throw new CliError(`Challenge failed: ${await challengeResp.text()}`)\n }\n\n const { challenge } = await challengeResp.json() as { challenge: string }\n\n // Sign challenge with Ed25519 private key (supports OpenSSH + PKCS8 format)\n const keyContent = readFileSync(keyPath, 'utf-8')\n const privateKey = loadEd25519PrivateKey(keyContent)\n const signature = sign(null, Buffer.from(challenge), privateKey).toString('base64')\n\n // Authenticate (endpoint resolved via OIDC discovery)\n const authenticateUrl = await getAgentAuthenticateEndpoint(idp)\n const authResp = await fetch(authenticateUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n agent_id: agentEmail,\n challenge,\n signature,\n }),\n })\n\n if (!authResp.ok) {\n throw new CliError(`Authentication failed: ${await authResp.text()}`)\n }\n\n const { token, expires_in } = await authResp.json() as { token: string, expires_in: number }\n\n saveAuth({\n idp,\n access_token: token,\n email: agentEmail,\n expires_at: Math.floor(Date.now() / 1000) + (expires_in || 3600),\n })\n\n // Persist the resolved key path + email to config.toml so future apes/ape-shell\n // invocations can auto-refresh via Ed25519 challenge-response without a new\n // `apes login`. Merge with existing config so [defaults] is preserved.\n const absoluteKeyPath = resolvePath(keyPath.replace(/^~/, homedir()))\n const existingConfig = loadConfig()\n saveConfig({\n ...existingConfig,\n agent: {\n ...existingConfig.agent,\n key: absoluteKeyPath,\n email: agentEmail,\n },\n })\n\n consola.success(`Logged in as ${agentEmail}`)\n consola.info(`Auto-refresh enabled (key path saved to ~/.config/apes/config.toml)`)\n}\n","import { existsSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { resolveDDISA } from '@openape/core'\nimport consola from 'consola'\nimport { loadConfig } from '../../config'\nimport { readPublicKeyComment } from '../../ssh-key'\n\nexport interface LoginInputs {\n key?: string\n idp?: string\n email?: string\n browser?: boolean\n}\n\nexport interface ResolvedLoginInputs {\n keyPath?: string\n email?: string\n idp?: string\n}\n\nconst DEFAULT_KEY = join(homedir(), '.ssh', 'id_ed25519')\n\n/**\n * Resolve login inputs by walking a fallback cascade:\n * 1. explicit flag\n * 2. environment variable\n * 3. ~/.config/apes/config.toml\n * 4. derivation (default key path, pub key comment, DDISA DNS)\n *\n * When `browser` is true, no key is resolved so the caller falls back to PKCE.\n */\nexport async function resolveLoginInputs(\n flags: LoginInputs,\n): Promise<ResolvedLoginInputs> {\n const config = loadConfig()\n\n // 1. Key path — skipped entirely in forced browser mode\n let keyPath: string | undefined\n if (!flags.browser) {\n if (flags.key) {\n keyPath = flags.key\n }\n else if (process.env.APES_KEY) {\n keyPath = process.env.APES_KEY\n consola.info(`Using key from APES_KEY: ${keyPath}`)\n }\n else if (config.agent?.key) {\n keyPath = config.agent.key\n consola.info(`Using key from config: ${keyPath}`)\n }\n else if (existsSync(DEFAULT_KEY)) {\n keyPath = DEFAULT_KEY\n consola.info(`Using default key: ${keyPath}`)\n }\n }\n\n // 2. Email\n let email: string | undefined\n if (flags.email) {\n email = flags.email\n }\n else if (process.env.APES_EMAIL) {\n email = process.env.APES_EMAIL\n }\n else if (config.agent?.email) {\n email = config.agent.email\n }\n else if (keyPath) {\n const comment = readPublicKeyComment(`${keyPath}.pub`)\n if (comment && comment.includes('@')) {\n email = comment\n consola.info(`Using email from ${keyPath}.pub comment: ${email}`)\n }\n }\n\n // 3. IdP\n let idp: string | undefined\n if (flags.idp) {\n idp = flags.idp\n }\n else if (process.env.APES_IDP) {\n idp = process.env.APES_IDP\n }\n else if (process.env.GRAPES_IDP) {\n idp = process.env.GRAPES_IDP\n }\n else if (config.defaults?.idp) {\n idp = config.defaults.idp\n }\n else if (email && email.includes('@')) {\n const domain = email.split('@')[1]!\n try {\n const record = await resolveDDISA(domain)\n if (record?.idp) {\n idp = record.idp\n consola.info(`Discovered IdP via DDISA (_ddisa.${domain}): ${idp}`)\n }\n }\n catch {\n // DNS failure is non-fatal — caller will surface a clear error\n }\n }\n\n return { keyPath, email, idp }\n}\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { clearAuth } from '../../config'\n\nexport const logoutCommand = defineCommand({\n meta: {\n name: 'logout',\n description: 'Clear stored credentials',\n },\n run() {\n clearAuth()\n consola.success('Logged out.')\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { loadAuth } from '../../config'\nimport { CliError } from '../../errors'\n\nexport const whoamiCommand = defineCommand({\n meta: {\n name: 'whoami',\n description: 'Show current identity',\n },\n run() {\n const auth = loadAuth()\n if (!auth) {\n throw new CliError('Not logged in. Run `apes login` first.')\n }\n\n const isAgent = auth.email.includes('agent+')\n const expiresAt = new Date(auth.expires_at * 1000).toISOString()\n const isExpired = Date.now() / 1000 > auth.expires_at\n\n console.log(`Email: ${auth.email}`)\n console.log(`Type: ${isAgent ? 'agent' : 'human'}`)\n console.log(`IdP: ${auth.idp}`)\n console.log(`Token: ${isExpired ? '⚠ EXPIRED' : 'valid'} (until ${expiresAt})`)\n\n if (isExpired) {\n consola.warn('Token is expired. Run `apes login` to re-authenticate.')\n }\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl, loadAuth } from '../../config'\nimport { apiFetch, getGrantsEndpoint } from '../../http'\nimport { CliError } from '../../errors'\n\ninterface Grant {\n id: string\n type: string\n status: string\n requester: string\n owner: string\n request: {\n command?: string[]\n grant_type?: string\n reason?: string\n }\n created_at?: string\n}\n\ninterface PaginatedGrants {\n data: Grant[]\n pagination: {\n cursor: string | null\n has_more: boolean\n }\n}\n\nexport const listCommand = defineCommand({\n meta: {\n name: 'list',\n description: 'List your grants (as requester)',\n },\n args: {\n status: {\n type: 'string',\n description: 'Filter by status (pending, approved, denied, revoked, used)',\n },\n all: {\n type: 'boolean',\n description: 'Show all visible grants (not just your own)',\n default: false,\n },\n json: {\n type: 'boolean',\n description: 'Output as JSON',\n default: false,\n },\n limit: {\n type: 'string',\n description: 'Max results (default 20, max 100)',\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()\n if (!idp) {\n throw new CliError('No IdP URL configured. Run `apes login` first or pass --idp.')\n }\n\n const auth = loadAuth()\n\n const grantsUrl = await getGrantsEndpoint(idp)\n const params = new URLSearchParams()\n if (args.status)\n params.set('status', args.status)\n if (args.limit)\n params.set('limit', args.limit)\n const query = params.toString() ? `?${params.toString()}` : ''\n\n const response = await apiFetch<PaginatedGrants>(`${grantsUrl}${query}`)\n\n let grants = response.data\n\n // Filter to own grants unless --all\n if (!args.all && auth?.email) {\n grants = grants.filter(g => g.requester === auth.email)\n }\n\n if (args.json) {\n console.log(JSON.stringify(args.all ? response : { ...response, data: grants }, null, 2))\n return\n }\n\n if (grants.length === 0) {\n consola.info(args.all ? 'No grants found.' : 'No grants found. Use --all to see all visible grants.')\n return\n }\n\n for (const grant of grants) {\n const cmd = grant.request?.command?.join(' ') || '(no command)'\n const type = grant.request?.grant_type || grant.type\n console.log(`${grant.id} ${grant.status.padEnd(8)} ${type.padEnd(6)} ${cmd}`)\n if (grant.request?.reason) {\n console.log(` Reason: ${grant.request.reason}`)\n }\n }\n\n if (response.pagination.has_more) {\n consola.info('More results available. Use --limit or pagination cursor.')\n }\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl, loadAuth } from '../../config'\nimport { apiFetch, getGrantsEndpoint } from '../../http'\nimport { CliError } from '../../errors'\n\ninterface Grant {\n id: string\n type: string\n status: string\n requester: string\n owner: string\n request: {\n command?: string[]\n grant_type?: string\n reason?: string\n }\n created_at?: string\n}\n\ninterface PaginatedGrants {\n data: Grant[]\n pagination: {\n cursor: string | null\n has_more: boolean\n }\n}\n\nexport const inboxCommand = defineCommand({\n meta: {\n name: 'inbox',\n description: 'Show grants awaiting your approval',\n },\n args: {\n json: {\n type: 'boolean',\n description: 'Output as JSON',\n default: false,\n },\n limit: {\n type: 'string',\n description: 'Max results (default 20, max 100)',\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()\n if (!idp) {\n throw new CliError('No IdP URL configured. Run `apes login` first.')\n }\n\n const auth = loadAuth()\n if (!auth) {\n throw new CliError('Not logged in. Run `apes login` first.')\n }\n\n const grantsUrl = await getGrantsEndpoint(idp)\n const params = new URLSearchParams()\n params.set('status', 'pending')\n if (args.limit)\n params.set('limit', args.limit)\n const query = `?${params.toString()}`\n\n const response = await apiFetch<PaginatedGrants>(`${grantsUrl}${query}`)\n\n // Filter out own requests — inbox shows only grants from others\n const grants = response.data.filter(g => g.requester !== auth.email)\n\n if (args.json) {\n console.log(JSON.stringify({ ...response, data: grants }, null, 2))\n return\n }\n\n if (grants.length === 0) {\n consola.info('No pending grants to approve.')\n return\n }\n\n consola.info(`${grants.length} grant(s) awaiting approval:\\n`)\n\n for (const grant of grants) {\n const cmd = grant.request?.command?.join(' ') || '(no command)'\n const type = grant.request?.grant_type || grant.type\n console.log(`${grant.id} ${type.padEnd(6)} from ${grant.requester}`)\n console.log(` Command: ${cmd}`)\n if (grant.request?.reason) {\n console.log(` Reason: ${grant.request.reason}`)\n }\n if (grant.created_at) {\n console.log(` Created: ${grant.created_at}`)\n }\n console.log()\n }\n\n consola.info('Use `apes grants approve <id>` or `apes grants deny <id>` to respond.')\n },\n})\n","import { defineCommand } from 'citty'\nimport { getIdpUrl } from '../../config'\nimport { apiFetch, getGrantsEndpoint } from '../../http'\n\n/**\n * Shape returned by `GET /grants/<id>` on the OpenApe IdP. Matches the\n * free-idp response as of 2026-04: `requester`, `target_host`, `audience`,\n * `grant_type`, etc. all live under the nested `request` object. Top-level\n * `type` is a legacy field that is currently always `null`. Timestamps are\n * unix seconds (numbers), not ISO strings.\n */\ninterface GrantDetail {\n id: string\n type?: string | null\n status: string\n request?: {\n requester?: string\n target_host?: string\n audience?: string\n grant_type?: string\n command?: string[]\n reason?: string\n }\n created_at?: number\n decided_at?: number\n decided_by?: string\n used_at?: number\n expires_at?: number\n}\n\n/** Unix seconds → ISO-8601 with graceful fallback for bogus values. */\nfunction formatTs(ts: number | undefined): string | undefined {\n if (ts === undefined || ts === null)\n return undefined\n const ms = ts * 1000\n if (!Number.isFinite(ms))\n return undefined\n return new Date(ms).toISOString()\n}\n\nexport const statusCommand = defineCommand({\n meta: {\n name: 'status',\n description: 'Show grant status',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Grant ID',\n required: true,\n },\n json: {\n type: 'boolean',\n description: 'Output as JSON',\n default: false,\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()!\n const grantsUrl = await getGrantsEndpoint(idp)\n const grant = await apiFetch<GrantDetail>(`${grantsUrl}/${args.id}`)\n\n if (args.json) {\n console.log(JSON.stringify(grant, null, 2))\n return\n }\n\n console.log(`Grant: ${grant.id}`)\n console.log(`Status: ${grant.status}`)\n if (grant.request?.audience)\n console.log(`Audience: ${grant.request.audience}`)\n if (grant.request?.requester)\n console.log(`Requester: ${grant.request.requester}`)\n if (grant.request?.target_host)\n console.log(`Host: ${grant.request.target_host}`)\n if (grant.request?.command)\n console.log(`Command: ${grant.request.command.join(' ')}`)\n if (grant.request?.grant_type)\n console.log(`Approval: ${grant.request.grant_type}`)\n if (grant.request?.reason)\n console.log(`Reason: ${grant.request.reason}`)\n const createdAt = formatTs(grant.created_at)\n if (createdAt)\n console.log(`Created: ${createdAt}`)\n if (grant.decided_by)\n console.log(`Decided by: ${grant.decided_by}`)\n const decidedAt = formatTs(grant.decided_at)\n if (decidedAt)\n console.log(`Decided at: ${decidedAt}`)\n const usedAt = formatTs(grant.used_at)\n if (usedAt)\n console.log(`Used at: ${usedAt}`)\n const expiresAt = formatTs(grant.expires_at)\n if (expiresAt)\n console.log(`Expires: ${expiresAt}`)\n },\n})\n","import { hostname } from 'node:os'\nimport { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl, loadAuth } from '../../config'\nimport { parseDuration } from '../../duration'\nimport { apiFetch, getGrantsEndpoint } from '../../http'\nimport { CliError } from '../../errors'\n\nexport const requestCommand = defineCommand({\n meta: {\n name: 'request',\n description: 'Request a new grant',\n },\n args: {\n command: {\n type: 'positional',\n description: 'Command to request permission for',\n required: true,\n },\n audience: {\n type: 'string',\n description: 'Service identifier (e.g. \"escapes\", \"proxy\")',\n required: true,\n },\n host: {\n type: 'string',\n description: 'Target host (default: system hostname)',\n },\n reason: {\n type: 'string',\n description: 'Reason for the request',\n },\n approval: {\n type: 'string',\n description: 'Approval type: once, timed, always',\n default: 'once',\n },\n duration: {\n type: 'string',\n description: 'Duration for timed grants (e.g. 30m, 1h, 7d)',\n },\n 'run-as': {\n type: 'string',\n description: 'Execute as this user (e.g. openclaw, root)',\n },\n wait: {\n type: 'boolean',\n description: 'Wait for approval',\n default: false,\n },\n },\n async run({ args }) {\n const auth = loadAuth()\n if (!auth) {\n throw new CliError('Not logged in. Run `apes login` first.')\n }\n\n const idp = getIdpUrl()!\n const grantsUrl = await getGrantsEndpoint(idp)\n const command = args.command.split(' ')\n const targetHost = args.host || hostname()\n\n const duration = args.duration ? parseDuration(args.duration) : undefined\n\n const grant = await apiFetch<{ id: string, status: string }>(grantsUrl, {\n method: 'POST',\n body: {\n requester: auth.email,\n target_host: targetHost,\n audience: args.audience,\n grant_type: args.approval,\n command,\n reason: args.reason || command.join(' '),\n ...(duration != null ? { duration } : {}),\n ...(args['run-as'] ? { run_as: args['run-as'] } : {}),\n },\n })\n\n consola.success(`Grant requested: ${grant.id} (status: ${grant.status})`)\n\n if (args.wait) {\n consola.info('Waiting for approval...')\n await waitForApproval(grantsUrl, grant.id)\n }\n },\n})\n\nasync function waitForApproval(grantsUrl: string, grantId: string): Promise<void> {\n const maxWait = 300_000 // 5 minutes\n const interval = 3_000\n const start = Date.now()\n\n while (Date.now() - start < maxWait) {\n const grant = await apiFetch<{ status: string }>(`${grantsUrl}/${grantId}`)\n\n if (grant.status === 'approved') {\n consola.success('Grant approved!')\n return\n }\n if (grant.status === 'denied') {\n throw new CliError('Grant denied.')\n }\n if (grant.status === 'revoked') {\n throw new CliError('Grant revoked.')\n }\n\n await new Promise(r => setTimeout(r, interval))\n }\n\n throw new CliError('Timed out waiting for approval.')\n}\n","import { hostname } from 'node:os'\nimport { buildStructuredCliGrantRequest, loadAdapter, resolveCapabilityRequest } from '../../shapes/index.js'\nimport { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl, loadAuth } from '../../config'\nimport { parseDuration } from '../../duration'\nimport { apiFetch, getGrantsEndpoint } from '../../http'\nimport { CliError } from '../../errors'\n\nfunction parseCapabilityArgs(rawArgs: string[]): {\n cliId: string\n adapter?: string\n idp?: string\n approval: 'once' | 'timed' | 'always'\n reason?: string\n duration?: number\n runAs?: string\n wait: boolean\n resources: string[]\n selectors: string[]\n actions: string[]\n} {\n const tokens = [...rawArgs]\n if (tokens[0] === 'request-capability') {\n tokens.shift()\n }\n\n const cliId = tokens.shift()\n if (!cliId || cliId.startsWith('-')) {\n throw new Error('Missing CLI identifier')\n }\n\n const resources: string[] = []\n const selectors: string[] = []\n const actions: string[] = []\n let adapter: string | undefined\n let idp: string | undefined\n let approval: 'once' | 'timed' | 'always' = 'once'\n let reason: string | undefined\n let duration: number | undefined\n let runAs: string | undefined\n let wait = false\n\n for (let index = 0; index < tokens.length; index += 1) {\n const token = tokens[index]!\n const next = tokens[index + 1]\n switch (token) {\n case '--resource':\n if (!next)\n throw new Error('Missing value for --resource')\n resources.push(next)\n index += 1\n break\n case '--selector':\n if (!next)\n throw new Error('Missing value for --selector')\n selectors.push(next)\n index += 1\n break\n case '--action':\n if (!next)\n throw new Error('Missing value for --action')\n actions.push(next)\n index += 1\n break\n case '--adapter':\n if (!next)\n throw new Error('Missing value for --adapter')\n adapter = next\n index += 1\n break\n case '--idp':\n if (!next)\n throw new Error('Missing value for --idp')\n idp = next\n index += 1\n break\n case '--approval':\n if (!next || !['once', 'timed', 'always'].includes(next)) {\n throw new Error('Approval must be one of: once, timed, always')\n }\n approval = next as 'once' | 'timed' | 'always'\n index += 1\n break\n case '--reason':\n if (!next)\n throw new Error('Missing value for --reason')\n reason = next\n index += 1\n break\n case '--duration':\n if (!next)\n throw new Error('Missing value for --duration')\n duration = parseDuration(next)\n index += 1\n break\n case '--run-as':\n if (!next)\n throw new Error('Missing value for --run-as')\n runAs = next\n index += 1\n break\n case '--wait':\n wait = true\n break\n default:\n throw new Error(`Unknown argument: ${token}`)\n }\n }\n\n return {\n cliId,\n adapter,\n idp,\n approval,\n reason,\n duration,\n runAs,\n wait,\n resources,\n selectors,\n actions,\n }\n}\n\nasync function waitForApproval(grantsUrl: string, grantId: string): Promise<void> {\n const maxWait = 300_000\n const interval = 3_000\n const start = Date.now()\n\n while (Date.now() - start < maxWait) {\n const grant = await apiFetch<{ status: string }>(`${grantsUrl}/${grantId}`)\n if (grant.status === 'approved') {\n consola.success('Grant approved!')\n return\n }\n if (grant.status === 'denied') {\n throw new CliError('Grant denied.')\n }\n if (grant.status === 'revoked') {\n throw new CliError('Grant revoked.')\n }\n await new Promise(resolve => setTimeout(resolve, interval))\n }\n\n throw new CliError('Timed out waiting for approval.')\n}\n\nexport const requestCapabilityCommand = defineCommand({\n meta: {\n name: 'request-capability',\n description: 'Request a structured CLI capability grant',\n },\n args: {\n 'cliId': {\n type: 'positional',\n description: 'CLI adapter identifier (e.g. docker, kubectl)',\n required: true,\n },\n 'resource': {\n type: 'string',\n description: 'Resource scope (repeatable)',\n },\n 'selector': {\n type: 'string',\n description: 'Selector filter (repeatable)',\n },\n 'action': {\n type: 'string',\n description: 'Action to permit (repeatable)',\n },\n 'adapter': {\n type: 'string',\n description: 'Explicit path to adapter TOML file',\n },\n 'idp': {\n type: 'string',\n description: 'IdP URL',\n },\n 'approval': {\n type: 'string',\n description: 'Approval type: once, timed, always',\n default: 'once',\n },\n 'reason': {\n type: 'string',\n description: 'Reason for the request',\n },\n 'duration': {\n type: 'string',\n description: 'Duration for timed grants (e.g. 30m, 1h, 7d)',\n },\n 'run-as': {\n type: 'string',\n description: 'Execute as this user (e.g. root)',\n },\n 'wait': {\n type: 'boolean',\n description: 'Wait for approval before returning',\n default: false,\n },\n },\n async run({ rawArgs }) {\n const auth = loadAuth()\n if (!auth) {\n throw new CliError('Not logged in. Run `apes login` first.')\n }\n\n const parsed = parseCapabilityArgs(rawArgs)\n const idp = getIdpUrl(parsed.idp)\n if (!idp) {\n throw new CliError('No IdP URL configured. Use --idp or log in first.')\n }\n\n const loaded = loadAdapter(parsed.cliId, parsed.adapter)\n const resolved = resolveCapabilityRequest(loaded, {\n resources: parsed.resources,\n selectors: parsed.selectors,\n actions: parsed.actions,\n })\n\n const { request } = await buildStructuredCliGrantRequest(resolved, {\n requester: auth.email,\n target_host: hostname(),\n grant_type: parsed.approval,\n ...(parsed.reason ? { reason: parsed.reason } : {}),\n })\n\n if (parsed.duration != null) {\n request.duration = parsed.duration\n }\n if (parsed.runAs) {\n request.run_as = parsed.runAs\n }\n\n const grantsUrl = await getGrantsEndpoint(idp)\n const grant = await apiFetch<{ id: string, status: string }>(grantsUrl, {\n method: 'POST',\n idp,\n body: request,\n })\n\n consola.success(`Grant requested: ${grant.id} (status: ${grant.status})`)\n\n if (parsed.wait) {\n consola.info('Waiting for approval...')\n await waitForApproval(grantsUrl, grant.id)\n }\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl } from '../../config'\nimport { apiFetch, getGrantsEndpoint } from '../../http'\n\nexport const approveCommand = defineCommand({\n meta: {\n name: 'approve',\n description: 'Approve a grant request',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Grant ID',\n required: true,\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()!\n const grantsUrl = await getGrantsEndpoint(idp)\n await apiFetch(`${grantsUrl}/${args.id}/approve`, {\n method: 'POST',\n })\n consola.success(`Grant ${args.id} approved.`)\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl } from '../../config'\nimport { apiFetch, getGrantsEndpoint } from '../../http'\n\nexport const denyCommand = defineCommand({\n meta: {\n name: 'deny',\n description: 'Deny a grant request',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Grant ID',\n required: true,\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()!\n const grantsUrl = await getGrantsEndpoint(idp)\n await apiFetch(`${grantsUrl}/${args.id}/deny`, {\n method: 'POST',\n })\n consola.success(`Grant ${args.id} denied.`)\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getAuthToken, getIdpUrl, loadAuth } from '../../config'\nimport { apiFetch, getGrantsEndpoint } from '../../http'\nimport { CliError } from '../../errors'\n\ninterface Grant {\n id: string\n status: string\n // Some list endpoints return requester nested under request\n requester?: string\n request?: { requester?: string, command?: string[] }\n}\n\ninterface PaginatedGrants {\n data: Grant[]\n pagination: { cursor: string | null, has_more: boolean }\n}\n\ninterface BatchResult {\n id: string\n status: string\n success: boolean\n error?: { title: string }\n}\n\nexport const revokeCommand = defineCommand({\n meta: {\n name: 'revoke',\n description: 'Revoke one or more grants',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Grant ID(s) to revoke',\n required: false,\n },\n allPending: {\n type: 'boolean',\n description: 'Revoke all own pending grants',\n default: false,\n },\n debug: {\n type: 'boolean',\n description: 'Print debug information (does not include full tokens)',\n default: false,\n },\n },\n async run({ args }) {\n const auth = loadAuth()\n const token = getAuthToken()\n const idp = getIdpUrl()!\n const grantsUrl = await getGrantsEndpoint(idp)\n\n if (args.debug) {\n consola.debug(`idp: ${idp}`)\n consola.debug(`grantsUrl: ${grantsUrl}`)\n consola.debug(`auth.email: ${auth?.email}`)\n consola.debug(`auth.expires_at: ${auth?.expires_at} (now: ${Math.floor(Date.now() / 1000)})`)\n consola.debug(`getAuthToken(): ${token ? `${token.substring(0, 20)}...` : 'NULL'}`)\n }\n\n if (!auth || !token) {\n throw new CliError('Authentication required. Run `apes login` and try again.')\n }\n\n const explicitIds = args.id\n ? [String(args.id), ...args._].filter(Boolean)\n : []\n\n if (args.allPending && explicitIds.length > 0) {\n throw new CliError('Use either --all-pending or grant IDs, not both.')\n }\n\n let ids: string[]\n\n if (args.allPending) {\n const auth = loadAuth()\n const response = await apiFetch<PaginatedGrants>(\n `${grantsUrl}?status=pending&limit=100`,\n { token },\n )\n const ownPending = auth?.email\n ? response.data.filter(g => g.request?.requester === auth.email)\n : response.data\n if (ownPending.length === 0) {\n consola.info('No pending grants to revoke.')\n return\n }\n ids = ownPending.map(g => g.id)\n consola.info(`Found ${ids.length} pending grant(s) to revoke.`)\n }\n else if (explicitIds.length > 0) {\n ids = explicitIds\n }\n else {\n throw new CliError('Provide grant ID(s) or use --all-pending.')\n }\n\n // Single grant: use direct endpoint\n if (ids.length === 1) {\n await apiFetch(`${grantsUrl}/${ids[0]}/revoke`, { method: 'POST', token })\n consola.success(`Grant ${ids[0]} revoked.`)\n return\n }\n\n // Multiple grants: use batch endpoint\n const operations = ids.map(id => ({ id, action: 'revoke' as const }))\n const { results } = await apiFetch<{ results: BatchResult[] }>(\n `${grantsUrl}/batch`,\n { method: 'POST', body: { operations }, token },\n )\n\n let succeeded = 0\n for (const r of results) {\n if (r.success) {\n consola.success(`Grant ${r.id} revoked.`)\n succeeded++\n }\n else {\n consola.error(`Grant ${r.id}: ${r.error?.title || 'Failed'}`)\n }\n }\n\n if (succeeded < results.length) {\n throw new CliError(`Revoked ${succeeded} of ${results.length} grants.`)\n }\n else {\n consola.success(`All ${succeeded} grants revoked.`)\n }\n },\n})\n","import { execFileSync } from 'node:child_process'\nimport { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl } from '../../config'\nimport { CliError, CliExit } from '../../errors'\nimport { apiFetch, getGrantsEndpoint } from '../../http'\nimport { fetchGrantToken, resolveFromGrant, verifyAndExecute } from '../../shapes/index.js'\n\ninterface GrantDetail {\n id: string\n type: string\n status: string\n requester: string\n owner: string\n request: {\n command?: string[]\n audience?: string\n grant_type?: string\n target_host?: string\n execution_context?: { adapter_digest?: string, argv_hash?: string }\n authorization_details?: Array<{ type?: string, permission?: string }>\n }\n}\n\nexport const runGrantCommand = defineCommand({\n meta: {\n name: 'run',\n description: 'Execute a previously-approved grant by ID',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Grant ID',\n required: true,\n },\n 'escapes-path': {\n type: 'string',\n description: 'Path to escapes binary (audience=escapes only)',\n default: 'escapes',\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()\n if (!idp)\n throw new CliError('No IdP URL configured. Run `apes login` first or pass --idp.')\n\n const grantsUrl = await getGrantsEndpoint(idp)\n const grant = await apiFetch<GrantDetail>(`${grantsUrl}/${args.id}`)\n\n // --- status gate ---\n if (grant.status === 'pending')\n throw new CliError(`Grant ${grant.id} is still pending. Approve at: ${idp}/grant-approval?grant_id=${grant.id}`)\n if (grant.status === 'denied' || grant.status === 'revoked')\n throw new CliError(`Grant ${grant.id} is ${grant.status}. Request a new one.`)\n if (grant.status === 'used')\n throw new CliError(`Grant ${grant.id} has already been used. Request a new one (single-use grants cannot be re-executed).`)\n if (grant.status !== 'approved')\n throw new CliError(`Grant ${grant.id} has unexpected status: ${grant.status}`)\n\n // --- dispatch by grant shape ---\n const audience = grant.request?.audience\n const authDetails = grant.request?.authorization_details ?? []\n const hasOpenApeCliDetail = authDetails.some(d => d?.type === 'openape_cli')\n const isShapesGrant = hasOpenApeCliDetail || audience === 'shapes'\n\n if (isShapesGrant) {\n // Re-resolve locally from the recorded command + adapter digest.\n let resolved\n try {\n resolved = await resolveFromGrant(grant)\n }\n catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n throw new CliError(`Cannot re-resolve grant: ${msg}`)\n }\n const token = await fetchGrantToken(idp, grant.id)\n await verifyAndExecute(token, resolved)\n return\n }\n\n if (audience === 'escapes') {\n const { authz_jwt } = await apiFetch<{ authz_jwt: string }>(`${grantsUrl}/${grant.id}/token`, { method: 'POST' })\n const command = grant.request?.command ?? []\n if (command.length === 0)\n throw new CliError(`Grant ${grant.id} has no command to execute.`)\n consola.info(`Executing via escapes: ${command.join(' ')}`)\n try {\n execFileSync(args['escapes-path'] as string, ['--grant', authz_jwt, '--', ...command], { stdio: 'inherit' })\n }\n catch (err: unknown) {\n const exitCode = (err as { status?: number }).status || 1\n throw new CliExit(exitCode)\n }\n return\n }\n\n if (audience === 'ape-shell') {\n // Legacy shell-session grants can't be re-executed standalone — they\n // were created for a specific bash -c line that only made sense inside\n // the original apes run --shell invocation.\n throw new CliError(\n `Grant ${grant.id} is an ape-shell session grant and cannot be re-executed via \\`apes grants run\\`. `\n + `Re-run the original command — if the grant was approved as timed/always, the REPL will reuse it automatically.`,\n )\n }\n\n throw new CliError(`Grant ${grant.id} has unsupported audience \"${audience}\" — no execution path available.`)\n },\n})\n","import { defineCommand } from 'citty'\nimport { getIdpUrl } from '../../config'\nimport { apiFetch, getGrantsEndpoint } from '../../http'\nimport { CliError } from '../../errors'\n\nexport const tokenCommand = defineCommand({\n meta: {\n name: 'token',\n description: 'Get grant token JWT',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Grant ID',\n required: true,\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()!\n const grantsUrl = await getGrantsEndpoint(idp)\n const result = await apiFetch<{ authz_jwt: string }>(`${grantsUrl}/${args.id}/token`, {\n method: 'POST',\n })\n\n if (!result.authz_jwt) {\n throw new CliError('No token received. Grant may not be approved.')\n }\n\n // Output raw token to stdout (pipeable)\n process.stdout.write(result.authz_jwt)\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl, loadAuth } from '../../config'\nimport { apiFetch, getDelegationsEndpoint } from '../../http'\nimport { CliError } from '../../errors'\n\nexport const delegateCommand = defineCommand({\n meta: {\n name: 'delegate',\n description: 'Create a delegation',\n },\n args: {\n to: {\n type: 'string',\n description: 'Delegate email (who can act on your behalf)',\n required: true,\n },\n at: {\n type: 'string',\n description: 'Service/audience where delegation applies',\n required: true,\n },\n scopes: {\n type: 'string',\n description: 'Comma-separated scopes',\n },\n approval: {\n type: 'string',\n description: 'Approval type: once, timed, always',\n default: 'once',\n },\n expires: {\n type: 'string',\n description: 'Expiration date (ISO 8601)',\n },\n },\n async run({ args }) {\n const auth = loadAuth()\n if (!auth) {\n throw new CliError('Not logged in. Run `apes login` first.')\n }\n\n const idp = getIdpUrl()!\n const delegationsUrl = await getDelegationsEndpoint(idp)\n\n const body: Record<string, unknown> = {\n delegate: args.to,\n audience: args.at,\n approval: args.approval,\n }\n\n if (args.scopes) {\n body.scopes = args.scopes.split(',').map(s => s.trim())\n }\n\n if (args.expires) {\n body.expires_at = args.expires\n }\n\n const result = await apiFetch<{ id: string }>(delegationsUrl, {\n method: 'POST',\n body,\n })\n\n consola.success(`Delegation created: ${result.id}`)\n console.log(` Delegate: ${args.to}`)\n console.log(` Audience: ${args.at}`)\n if (args.scopes)\n console.log(` Scopes: ${args.scopes}`)\n console.log(` Approval: ${args.approval}`)\n if (args.expires)\n console.log(` Expires: ${args.expires}`)\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl } from '../../config'\nimport { apiFetch, getDelegationsEndpoint } from '../../http'\n\ninterface Delegation {\n id: string\n delegator: string\n delegate: string\n audience: string\n scopes?: string[]\n approval: string\n created_at?: string\n expires_at?: string\n}\n\ninterface PaginatedDelegations {\n data: Delegation[]\n pagination: { cursor: string | null, has_more: boolean }\n}\n\nexport const delegationsCommand = defineCommand({\n meta: {\n name: 'delegations',\n description: 'List delegations',\n },\n args: {\n json: {\n type: 'boolean',\n description: 'Output as JSON',\n default: false,\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()!\n const delegationsUrl = await getDelegationsEndpoint(idp)\n const response = await apiFetch<PaginatedDelegations>(delegationsUrl)\n\n // Support both paginated and legacy plain-array responses\n const delegations = Array.isArray(response) ? response : response.data\n\n if (args.json) {\n console.log(JSON.stringify(delegations, null, 2))\n return\n }\n\n if (delegations.length === 0) {\n consola.info('No delegations found.')\n return\n }\n\n for (const d of delegations) {\n const scopes = d.scopes?.join(', ') || '(all)'\n const expires = d.expires_at ? ` expires ${d.expires_at}` : ''\n console.log(`${d.id} ${d.delegator} → ${d.delegate} at ${d.audience} [${scopes}]${expires}`)\n }\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl } from '../../config'\nimport { apiFetch, getDelegationsEndpoint } from '../../http'\nimport { CliError } from '../../errors'\n\nexport const delegationRevokeCommand = defineCommand({\n meta: {\n name: 'delegation-revoke',\n description: 'Revoke a delegation',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Delegation ID to revoke',\n required: true,\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()\n if (!idp) {\n throw new CliError('No IdP URL configured. Run `apes login` first or pass --idp.')\n }\n\n const delegationsUrl = await getDelegationsEndpoint(idp)\n const id = String(args.id)\n\n const result = await apiFetch<{ id: string, status: string }>(\n `${delegationsUrl}/${id}`,\n { method: 'DELETE' },\n )\n\n consola.success(`Delegation ${result.id} revoked.`)\n },\n})\n","import { defineCommand } from 'citty'\nimport { usersListCommand, usersCreateCommand, usersDeleteCommand } from './users'\nimport { sshKeysListCommand, sshKeysAddCommand, sshKeysDeleteCommand } from './ssh-keys'\n\nconst usersCommand = defineCommand({\n meta: {\n name: 'users',\n description: 'Manage users',\n },\n subCommands: {\n list: usersListCommand,\n create: usersCreateCommand,\n delete: usersDeleteCommand,\n },\n})\n\nconst sshKeysCommand = defineCommand({\n meta: {\n name: 'ssh-keys',\n description: 'Manage SSH keys',\n },\n subCommands: {\n list: sshKeysListCommand,\n add: sshKeysAddCommand,\n delete: sshKeysDeleteCommand,\n },\n})\n\nexport const adminCommand = defineCommand({\n meta: {\n name: 'admin',\n description: 'Admin commands (requires APES_MANAGEMENT_TOKEN)',\n },\n subCommands: {\n users: usersCommand,\n 'ssh-keys': sshKeysCommand,\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl } from '../../config'\nimport { apiFetch } from '../../http'\nimport { CliError } from '../../errors'\n\ninterface AdminUser {\n email: string\n name: string\n isActive: boolean\n owner?: string\n createdAt: number\n}\n\nfunction getManagementToken(): string {\n const token = process.env.APES_MANAGEMENT_TOKEN\n if (!token) {\n throw new CliError('Management token required. Set APES_MANAGEMENT_TOKEN environment variable.')\n }\n return token\n}\n\ninterface UserListResponse {\n data: AdminUser[]\n pagination: {\n cursor: string | null\n has_more: boolean\n }\n}\n\nexport const usersListCommand = defineCommand({\n meta: {\n name: 'list',\n description: 'List all users',\n },\n args: {\n json: {\n type: 'boolean',\n description: 'Output as JSON',\n default: false,\n },\n limit: {\n type: 'string',\n description: 'Max number of users to return (1-100, default 50)',\n },\n cursor: {\n type: 'string',\n description: 'Pagination cursor (email of last item from previous page)',\n },\n search: {\n type: 'string',\n description: 'Filter by email or name (case-insensitive)',\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()\n if (!idp) {\n throw new CliError('No IdP URL configured. Run `apes login` first or pass --idp.')\n }\n\n const token = getManagementToken()\n const params = new URLSearchParams()\n if (args.limit) params.set('limit', args.limit)\n if (args.cursor) params.set('cursor', args.cursor)\n if (args.search) params.set('search', args.search)\n const qs = params.toString()\n const url = qs ? `${idp}/api/admin/users?${qs}` : `${idp}/api/admin/users`\n\n const result = await apiFetch<UserListResponse>(url, { token })\n\n if (args.json) {\n console.log(JSON.stringify(result, null, 2))\n return\n }\n\n if (result.data.length === 0) {\n consola.info('No users found.')\n return\n }\n\n for (const u of result.data) {\n const owner = u.owner ? ` (agent of ${u.owner})` : ''\n const active = u.isActive ? '' : ' [inactive]'\n console.log(`${u.email} ${u.name}${owner}${active}`)\n }\n\n if (result.pagination.has_more) {\n consola.info(`More results available. Use --cursor=\"${result.pagination.cursor}\" to see next page.`)\n }\n },\n})\n\nexport const usersCreateCommand = defineCommand({\n meta: {\n name: 'create',\n description: 'Create a user',\n },\n args: {\n email: {\n type: 'string',\n description: 'User email',\n required: true,\n },\n name: {\n type: 'string',\n description: 'User name',\n required: true,\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()\n if (!idp) {\n throw new CliError('No IdP URL configured. Run `apes login` first or pass --idp.')\n }\n\n const token = getManagementToken()\n\n const result = await apiFetch<{ ok: boolean, email: string, name: string }>(\n `${idp}/api/admin/users`,\n {\n method: 'POST',\n body: { email: args.email, name: args.name },\n token,\n },\n )\n\n consola.success(`User created: ${result.email} (${result.name})`)\n },\n})\n\nexport const usersDeleteCommand = defineCommand({\n meta: {\n name: 'delete',\n description: 'Delete a user',\n },\n args: {\n email: {\n type: 'positional',\n description: 'User email',\n required: true,\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()\n if (!idp) {\n throw new CliError('No IdP URL configured. Run `apes login` first or pass --idp.')\n }\n\n const token = getManagementToken()\n const email = String(args.email)\n\n await apiFetch(`${idp}/api/admin/users/${encodeURIComponent(email)}`, {\n method: 'DELETE',\n token,\n })\n\n consola.success(`User deleted: ${email}`)\n },\n})\n","import { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { homedir } from 'node:os'\nimport { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl } from '../../config'\nimport { apiFetch } from '../../http'\nimport { CliError } from '../../errors'\n\ninterface SshKey {\n keyId: string\n userEmail: string\n publicKey: string\n name: string\n createdAt: number\n}\n\nfunction getManagementToken(): string {\n const token = process.env.APES_MANAGEMENT_TOKEN\n if (!token) {\n throw new CliError('Management token required. Set APES_MANAGEMENT_TOKEN environment variable.')\n }\n return token\n}\n\nexport const sshKeysListCommand = defineCommand({\n meta: {\n name: 'list',\n description: 'List SSH keys for a user',\n },\n args: {\n email: {\n type: 'positional',\n description: 'User email',\n required: true,\n },\n json: {\n type: 'boolean',\n description: 'Output as JSON',\n default: false,\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()\n if (!idp) {\n throw new CliError('No IdP URL configured. Run `apes login` first or pass --idp.')\n }\n\n const token = getManagementToken()\n const email = String(args.email)\n const keys = await apiFetch<SshKey[]>(\n `${idp}/api/admin/users/${encodeURIComponent(email)}/ssh-keys`,\n { token },\n )\n\n if (args.json) {\n console.log(JSON.stringify(keys, null, 2))\n return\n }\n\n if (keys.length === 0) {\n consola.info(`No SSH keys found for ${email}.`)\n return\n }\n\n for (const k of keys) {\n console.log(`${k.keyId} ${k.name} ${k.publicKey.substring(0, 40)}...`)\n }\n },\n})\n\nexport const sshKeysAddCommand = defineCommand({\n meta: {\n name: 'add',\n description: 'Add an SSH key for a user',\n },\n args: {\n email: {\n type: 'string',\n description: 'User email',\n required: true,\n },\n key: {\n type: 'string',\n description: 'Path to public key file or key string',\n required: true,\n },\n name: {\n type: 'string',\n description: 'Key name/label',\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()\n if (!idp) {\n throw new CliError('No IdP URL configured. Run `apes login` first or pass --idp.')\n }\n\n const token = getManagementToken()\n\n // Read key from file if path exists, otherwise treat as key string\n let publicKey = args.key\n const resolved = resolve(args.key.replace(/^~/, homedir()))\n if (existsSync(resolved)) {\n publicKey = readFileSync(resolved, 'utf-8').trim()\n }\n\n const body: Record<string, string> = { publicKey }\n if (args.name) {\n body.name = args.name\n }\n\n const result = await apiFetch<SshKey>(\n `${idp}/api/admin/users/${encodeURIComponent(args.email)}/ssh-keys`,\n {\n method: 'POST',\n body,\n token,\n },\n )\n\n consola.success(`SSH key added: ${result.keyId} (${result.name})`)\n },\n})\n\nexport const sshKeysDeleteCommand = defineCommand({\n meta: {\n name: 'delete',\n description: 'Delete an SSH key',\n },\n args: {\n email: {\n type: 'string',\n description: 'User email',\n required: true,\n },\n keyId: {\n type: 'positional',\n description: 'Key ID',\n required: true,\n },\n },\n async run({ args }) {\n const idp = getIdpUrl()\n if (!idp) {\n throw new CliError('No IdP URL configured. Run `apes login` first or pass --idp.')\n }\n\n const token = getManagementToken()\n const keyId = String(args.keyId)\n\n await apiFetch(\n `${idp}/api/admin/users/${encodeURIComponent(args.email)}/ssh-keys/${keyId}`,\n {\n method: 'DELETE',\n token,\n },\n )\n\n consola.success(`SSH key deleted: ${keyId}`)\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport {\n fetchRegistry,\n findAdapter,\n findConflictingAdapters,\n getInstalledDigest,\n installAdapter,\n isInstalled,\n loadAdapter,\n removeAdapter,\n searchAdapters,\n} from '../../shapes/index.js'\nimport { CliError } from '../../errors'\n\nexport const adapterCommand = defineCommand({\n meta: {\n name: 'adapter',\n description: 'Manage CLI adapters',\n },\n subCommands: {\n list: defineCommand({\n meta: {\n name: 'list',\n description: 'List available adapters',\n },\n args: {\n remote: {\n type: 'boolean',\n description: 'List adapters from the remote registry',\n default: false,\n },\n json: {\n type: 'boolean',\n description: 'Output as JSON',\n default: false,\n },\n refresh: {\n type: 'boolean',\n description: 'Force refresh the registry cache',\n default: false,\n },\n },\n async run({ args }) {\n const forceRefresh = Boolean(args.refresh)\n if (args.remote) {\n const index = await fetchRegistry(forceRefresh)\n if (args.json) {\n process.stdout.write(`${JSON.stringify(index.adapters, null, 2)}\\n`)\n return\n }\n consola.info(`Registry: ${index.adapters.length} adapters (${index.generated_at})`)\n for (const a of index.adapters) {\n const installed = isInstalled(a.id, false) ? ' [installed]' : ''\n console.log(` ${a.id.padEnd(12)} ${a.name.padEnd(24)} ${a.category}${installed}`)\n }\n return\n }\n\n const index = await fetchRegistry(forceRefresh)\n const local: { id: string, source: string, digest: string }[] = []\n for (const a of index.adapters) {\n try {\n const loaded = loadAdapter(a.id)\n local.push({ id: a.id, source: loaded.source, digest: loaded.digest })\n }\n catch {\n // not installed locally\n }\n }\n\n if (args.json) {\n process.stdout.write(`${JSON.stringify(local, null, 2)}\\n`)\n return\n }\n\n if (local.length === 0) {\n consola.info('No adapters installed. Use `apes adapter list --remote` to see available adapters.')\n return\n }\n\n for (const a of local) {\n console.log(` ${a.id.padEnd(12)} ${a.source}`)\n }\n },\n }),\n\n install: defineCommand({\n meta: {\n name: 'install',\n description: 'Install an adapter from the registry',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Adapter ID to install',\n required: true,\n },\n local: {\n type: 'boolean',\n description: 'Install to project-local .openape/ instead of ~/.openape/',\n default: false,\n },\n refresh: {\n type: 'boolean',\n description: 'Force refresh the registry cache',\n default: false,\n },\n },\n async run({ args }) {\n const ids = [String(args.id), ...args._].filter(Boolean)\n const local = Boolean(args.local)\n const index = await fetchRegistry(Boolean(args.refresh))\n\n for (const id of ids) {\n const entry = findAdapter(index, id)\n if (!entry) {\n consola.error(`Adapter \"${id}\" not found in registry. Use \\`apes adapter search ${id}\\` to search.`)\n continue\n }\n\n const conflicts = findConflictingAdapters(entry.executable, id)\n if (conflicts.length > 0) {\n for (const c of conflicts) {\n consola.warn(`Conflicting adapter found: ${c.path} (id: ${c.adapterId}, executable: ${c.executable})`)\n consola.warn(` Remove it with: apes adapter remove ${c.adapterId}`)\n }\n }\n\n const result = await installAdapter(entry, { local })\n const verb = result.updated ? 'Updated' : 'Installed'\n consola.success(`${verb} ${result.id} → ${result.path}`)\n consola.info(`Digest: ${result.digest}`)\n }\n },\n }),\n\n remove: defineCommand({\n meta: {\n name: 'remove',\n description: 'Remove an installed adapter',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Adapter ID to remove',\n required: true,\n },\n local: {\n type: 'boolean',\n description: 'Remove from project-local .openape/',\n default: false,\n },\n },\n async run({ args }) {\n const ids = [String(args.id), ...args._].filter(Boolean)\n const local = Boolean(args.local)\n let failed = false\n\n for (const id of ids) {\n if (removeAdapter(id, local)) {\n consola.success(`Removed adapter: ${id}`)\n }\n else {\n consola.error(`Adapter \"${id}\" is not installed${local ? ' locally' : ''}`)\n failed = true\n }\n }\n\n if (failed)\n throw new CliError('Some adapters could not be removed')\n },\n }),\n\n info: defineCommand({\n meta: {\n name: 'info',\n description: 'Show detailed adapter information',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Adapter ID',\n required: true,\n },\n refresh: {\n type: 'boolean',\n description: 'Force refresh the registry cache',\n default: false,\n },\n },\n async run({ args }) {\n const id = String(args.id)\n const index = await fetchRegistry(Boolean(args.refresh))\n const entry = findAdapter(index, id)\n if (!entry)\n throw new Error(`Adapter \"${id}\" not found in registry`)\n\n console.log(`ID: ${entry.id}`)\n console.log(`Name: ${entry.name}`)\n console.log(`Description: ${entry.description}`)\n console.log(`Category: ${entry.category}`)\n console.log(`Tags: ${entry.tags.join(', ')}`)\n console.log(`Author: ${entry.author}`)\n console.log(`Executable: ${entry.executable}`)\n console.log(`Digest: ${entry.digest}`)\n console.log(`Min version: ${entry.min_shapes_version}`)\n console.log(`URL: ${entry.download_url}`)\n\n const localDigest = getInstalledDigest(id, false)\n if (localDigest) {\n const upToDate = localDigest === entry.digest\n console.log(`Installed: yes${upToDate ? ' (up to date)' : ' (update available)'}`)\n }\n else {\n console.log(`Installed: no`)\n }\n },\n }),\n\n search: defineCommand({\n meta: {\n name: 'search',\n description: 'Search adapters in the registry',\n },\n args: {\n query: {\n type: 'positional',\n description: 'Search query',\n required: true,\n },\n json: {\n type: 'boolean',\n description: 'Output as JSON',\n default: false,\n },\n refresh: {\n type: 'boolean',\n description: 'Force refresh the registry cache',\n default: false,\n },\n },\n async run({ args }) {\n const query = String(args.query)\n const index = await fetchRegistry(Boolean(args.refresh))\n const results = searchAdapters(index, query)\n\n if (args.json) {\n process.stdout.write(`${JSON.stringify(results, null, 2)}\\n`)\n return\n }\n\n if (results.length === 0) {\n consola.info(`No adapters matching \"${query}\"`)\n return\n }\n\n for (const a of results) {\n console.log(` ${a.id.padEnd(12)} ${a.name.padEnd(24)} ${a.category}`)\n console.log(` ${a.description}`)\n }\n },\n }),\n\n update: defineCommand({\n meta: {\n name: 'update',\n description: 'Update installed adapters',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Adapter ID (omit to update all)',\n },\n yes: {\n type: 'boolean',\n description: 'Skip confirmation',\n default: false,\n },\n refresh: {\n type: 'boolean',\n description: 'Force refresh the registry cache',\n default: true,\n },\n },\n async run({ args }) {\n const index = await fetchRegistry(Boolean(args.refresh))\n const targetId = args.id ? String(args.id) : undefined\n const targets = targetId\n ? [targetId]\n : index.adapters.map(a => a.id).filter(id => isInstalled(id, false))\n\n if (targets.length === 0) {\n consola.info('No adapters installed to update.')\n return\n }\n\n for (const id of targets) {\n const entry = findAdapter(index, id)\n if (!entry) {\n consola.warn(`${id}: not found in registry, skipping`)\n continue\n }\n\n const localDigest = getInstalledDigest(id, false)\n if (localDigest === entry.digest) {\n consola.info(`${id}: already up to date`)\n continue\n }\n\n if (localDigest && !args.yes) {\n consola.warn(`${id}: digest will change — existing grants for this adapter will be invalidated`)\n consola.info(` Old: ${localDigest}`)\n consola.info(` New: ${entry.digest}`)\n consola.info(' Use --yes to confirm')\n continue\n }\n\n const result = await installAdapter(entry)\n consola.success(`Updated ${result.id} → ${result.path}`)\n }\n },\n }),\n\n verify: defineCommand({\n meta: {\n name: 'verify',\n description: 'Verify installed adapter against registry digest',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Adapter ID',\n required: true,\n },\n local: {\n type: 'boolean',\n description: 'Check project-local adapter',\n default: false,\n },\n refresh: {\n type: 'boolean',\n description: 'Force refresh the registry cache',\n default: false,\n },\n },\n async run({ args }) {\n const id = String(args.id)\n const local = Boolean(args.local)\n const index = await fetchRegistry(Boolean(args.refresh))\n const entry = findAdapter(index, id)\n if (!entry)\n throw new Error(`Adapter \"${id}\" not found in registry`)\n\n const localDigest = getInstalledDigest(id, local)\n if (!localDigest)\n throw new Error(`Adapter \"${id}\" is not installed${local ? ' locally' : ''}`)\n\n if (localDigest === entry.digest) {\n consola.success(`${id}: digest matches registry`)\n }\n else {\n console.log(` Local: ${localDigest}`)\n console.log(` Registry: ${entry.digest}`)\n throw new CliError(`${id}: digest mismatch`)\n }\n },\n }),\n },\n})\n","import { execFileSync } from 'node:child_process'\nimport { hostname } from 'node:os'\nimport { basename } from 'node:path'\nimport { defineCommand } from 'citty'\nimport {\n createShapesGrant,\n extractOption,\n extractShellCommandString,\n extractWrappedCommand,\n fetchGrantToken,\n findExistingGrant,\n loadAdapter,\n loadOrInstallAdapter,\n parseShellCommand,\n resolveCommand,\n verifyAndExecute,\n waitForGrantStatus,\n} from '../shapes/index.js'\nimport consola from 'consola'\nimport { getIdpUrl, loadAuth, loadConfig } from '../config'\nimport { apiFetch, getGrantsEndpoint } from '../http'\nimport { CliError, CliExit } from '../errors'\nimport { notifyGrantPending } from '../notifications'\n\n/**\n * Returns true when the caller asked for the legacy blocking path via\n * `--wait` or `APE_WAIT=1`. Default is non-blocking (async exit).\n */\nfunction shouldWaitForGrant(args: Record<string, unknown>): boolean {\n return args.wait === true || process.env.APE_WAIT === '1'\n}\n\n/**\n * Audience of the `apes run` async info block. Drives whether the output\n * targets a human reader (short, friendly) or an AI agent (verbose, with\n * explicit polling protocol).\n *\n * Default is `'agent'` — zero-config for agent ecosystems (openclaw, Claude,\n * etc.), and humans who want brevity just set `APES_USER=human` once in\n * their shell rc. Env var wins over config.toml; unknown values fall back\n * to the agent default.\n */\ntype ApesUserMode = 'agent' | 'human'\n\nfunction getUserMode(): ApesUserMode {\n const envValue = process.env.APES_USER\n if (envValue === 'human')\n return 'human'\n if (envValue === 'agent')\n return 'agent'\n const cfg = loadConfig()\n if (cfg.defaults?.user === 'human')\n return 'human'\n return 'agent'\n}\n\n/** Poll interval (seconds) embedded in the agent-mode instructions. */\nfunction getPollIntervalSeconds(): number {\n const envValue = process.env.APES_GRANT_POLL_INTERVAL\n if (envValue) {\n const n = Number(envValue)\n if (Number.isFinite(n) && n > 0)\n return Math.floor(n)\n }\n const cfg = loadConfig()\n const cfgValue = cfg.defaults?.grant_poll_interval_seconds\n if (cfgValue) {\n const n = Number(cfgValue)\n if (Number.isFinite(n) && n > 0)\n return Math.floor(n)\n }\n return 10\n}\n\n/** Poll max minutes embedded in the agent-mode instructions. */\nfunction getPollMaxMinutes(): number {\n const envValue = process.env.APES_GRANT_POLL_MAX_MINUTES\n if (envValue) {\n const n = Number(envValue)\n if (Number.isFinite(n) && n > 0)\n return Math.floor(n)\n }\n const cfg = loadConfig()\n const cfgValue = cfg.defaults?.grant_poll_max_minutes\n if (cfgValue) {\n const n = Number(cfgValue)\n if (Number.isFinite(n) && n > 0)\n return Math.floor(n)\n }\n return 5\n}\n\n/**\n * Print the async info block for a freshly created pending grant. Two\n * output modes:\n *\n * - **agent** (default): verbose, with an explicit polling protocol so\n * the consuming LLM knows exactly what to do next. Tells the agent to\n * poll `apes grants status <id> --json` every N seconds for up to M\n * minutes, handle each terminal status, and run `apes grants run <id>`\n * once approved. Every agent in every ecosystem sees the same text\n * without needing a per-tool skill integration.\n *\n * - **human** (opt-in via `APES_USER=human` or `config.toml` defaults.user):\n * short, friendly, no polling block. Humans at a terminal know to wait\n * for approval and then come back.\n *\n * Both modes keep the same core Approve / Status / Execute lines so\n * external scripts that grep for those labels keep working.\n */\nfunction printPendingGrantInfo(grant: { id: string }, idp: string): void {\n const mode = getUserMode()\n const approveUrl = `${idp}/grant-approval?grant_id=${grant.id}`\n const statusCmd = `apes grants status ${grant.id}`\n const executeCmd = `apes grants run ${grant.id}`\n\n if (mode === 'human') {\n consola.success(`Grant ${grant.id} created — awaiting your approval`)\n console.log(` Approve in browser: ${approveUrl}`)\n console.log(` Check status: ${statusCmd}`)\n console.log(` Run after approval: ${executeCmd}`)\n console.log('')\n console.log(' Tip: Approve as \"timed\" or \"always\" in the browser to reuse')\n console.log(' this grant without re-approval on the next invocation.')\n return\n }\n\n // agent mode (default)\n const pollSec = getPollIntervalSeconds()\n const maxMin = getPollMaxMinutes()\n consola.success(`Grant ${grant.id} created (pending approval)`)\n console.log(` Approve: ${approveUrl}`)\n console.log(` Status: ${statusCmd} [--json]`)\n console.log(` Execute: ${executeCmd}`)\n console.log('')\n console.log(` For agents: poll \\`${statusCmd} --json\\` every ${pollSec}s, wait up to ${maxMin} minutes.`)\n console.log(` When .status == \"approved\", run \\`${executeCmd}\\` to execute.`)\n console.log(` On \"denied\" or \"revoked\", stop and report to the user.`)\n console.log(` On timeout, stop and notify the user that approval has not happened.`)\n console.log('')\n console.log(' Tip: Approve as \"timed\" or \"always\" in the browser to let this')\n console.log(' grant be reused on subsequent invocations without re-approval.')\n}\n\nexport const runCommand = defineCommand({\n meta: {\n name: 'run',\n description: 'Execute a grant-secured command',\n },\n args: {\n 'approval': {\n type: 'string',\n description: 'Approval type: once, timed, always',\n default: 'once',\n },\n 'reason': {\n type: 'string',\n description: 'Reason for the grant request',\n },\n 'adapter': {\n type: 'string',\n description: 'Explicit path to adapter TOML file',\n },\n 'as': {\n type: 'string',\n description: 'Execute as this user (delegates to escapes)',\n },\n 'host': {\n type: 'string',\n description: 'Target host (default: system hostname)',\n },\n 'escapes-path': {\n type: 'string',\n description: 'Path to escapes binary',\n default: 'escapes',\n },\n 'idp': {\n type: 'string',\n description: 'IdP URL',\n },\n 'shell': {\n type: 'boolean',\n description: 'Shell mode: use session grant with audience ape-shell',\n default: false,\n },\n 'wait': {\n type: 'boolean',\n description: 'Block until grant is approved (default: async, print grant info and exit 0). Equivalent to APE_WAIT=1.',\n default: false,\n },\n '_': {\n type: 'positional',\n description: 'Command to execute (after --)',\n required: false,\n },\n },\n async run({ rawArgs, args }) {\n const wrappedCommand = extractWrappedCommand(rawArgs ?? [])\n\n if (args.shell && wrappedCommand.length > 0) {\n // Shell mode: ape-shell -c \"command\" → apes run --shell -- bash -c \"command\"\n await runShellMode(wrappedCommand, args)\n return\n }\n\n if (wrappedCommand.length > 0) {\n // Adapter mode: apes run [options] -- <cli> <args...>\n await runAdapterMode(wrappedCommand, rawArgs ?? [], args)\n }\n else {\n // Audience mode: apes run <audience> <action>\n // Extract audience and action from rawArgs (before --)\n const positionals = extractPositionals(rawArgs ?? [])\n if (positionals.length < 2)\n throw new Error('Usage: apes run -- <cli> <args...> OR apes run <audience> <action>')\n await runAudienceMode(positionals[0]!, positionals[1]!, args)\n }\n },\n})\n\nasync function runShellMode(\n command: string[],\n args: Record<string, unknown>,\n) {\n const auth = loadAuth()\n if (!auth)\n throw new CliError('Not logged in. Run `apes login` first.')\n\n const idp = getIdpUrl(args.idp as string | undefined)\n if (!idp)\n throw new CliError('No IdP URL configured. Run `apes login` first or pass --idp.')\n\n // Try to handle this command via the shapes adapter system first.\n // This gives us structured grants with resource chains (e.g. \"rm file:/tmp/foo.txt\")\n // instead of opaque \"bash -c …\" grants.\n const adapterHandled = await tryAdapterModeFromShell(command, idp, args)\n if (adapterHandled) return\n\n const grantsUrl = await getGrantsEndpoint(idp)\n const targetHost = (args.host as string) || hostname()\n\n // Try to find an existing timed/always session grant for ape-shell\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 === targetHost\n && g.request.grant_type !== 'once',\n )\n if (sessionGrant) {\n execShellCommand(command)\n return\n }\n }\n catch {\n // Fall through to creating a new grant\n }\n\n // No session grant found — request one. Default: 'once', but the approver\n // can upgrade to 'timed' or 'always' during approval to enable reuse.\n consola.info(`Requesting ape-shell session grant on ${targetHost}`)\n const grant = await apiFetch<{ id: string, status: string }>(grantsUrl, {\n method: 'POST',\n body: {\n requester: auth.email,\n target_host: targetHost,\n audience: 'ape-shell',\n grant_type: 'once',\n command: command.slice(0, 3),\n reason: `Shell session: ${command.join(' ').slice(0, 100)}`,\n },\n })\n\n notifyGrantPending({\n grantId: grant.id,\n approveUrl: `${idp}/grant-approval?grant_id=${grant.id}`,\n command: command.join(' ').slice(0, 200),\n audience: 'ape-shell',\n host: targetHost,\n })\n\n if (shouldWaitForGrant(args)) {\n consola.info(`Grant requested: ${grant.id}`)\n consola.info('Waiting for approval...')\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 break\n if (status.status === 'denied' || status.status === 'revoked')\n throw new CliError(`Grant ${status.status}.`)\n await new Promise(r => setTimeout(r, interval))\n }\n\n execShellCommand(command)\n return\n }\n\n printPendingGrantInfo(grant, idp)\n}\n\n/**\n * Try to handle a shell command via the shapes adapter system.\n *\n * Flow:\n * 1. Extract the command string from `bash -c \"…\"` argv\n * 2. Parse into executable + argv (bail out on compound commands)\n * 3. Load adapter locally, or auto-install from registry\n * 4. Resolve the command against adapter operations → structured CLI grant detail\n * 5. Reuse an existing matching grant, or request a new one and execute\n *\n * Returns true when the command was handled (executed or failed hard).\n * Returns false for any reason — caller should fall back to the generic session grant.\n */\nasync function tryAdapterModeFromShell(\n command: string[],\n idp: string,\n args: Record<string, unknown>,\n): Promise<boolean> {\n const cmdString = extractShellCommandString(command)\n if (!cmdString) return false\n\n const parsed = parseShellCommand(cmdString)\n if (!parsed) return false\n if (parsed.isCompound) return false\n\n const loaded = await loadOrInstallAdapter(parsed.executable)\n if (!loaded) return false\n\n // resolveCommand does a strict comparison against `adapter.cli.executable`,\n // which is always the bare binary name. When the user typed an absolute\n // path we must pass the basename, not the full path.\n const normalizedExecutable = basename(parsed.executable)\n\n let resolved\n try {\n resolved = await resolveCommand(loaded, [normalizedExecutable, ...parsed.argv])\n }\n catch (err) {\n consola.debug(`ape-shell: adapter resolve failed for \"${parsed.raw}\":`, err)\n return false\n }\n\n // Try to reuse an existing matching grant (with widening support)\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 verifyAndExecute(token, resolved)\n return true\n }\n }\n catch {\n // Fall through to request a new grant\n }\n\n // Request a new grant for this specific command\n const approval = (args.approval ?? 'once') as 'once' | 'timed' | 'always'\n consola.info(`Requesting grant for: ${resolved.detail.display}`)\n const grant = await createShapesGrant(resolved, {\n idp,\n approval,\n reason: (args.reason as string) || `ape-shell: ${resolved.detail.display}`,\n })\n\n if (grant.similar_grants?.similar_grants?.length) {\n const n = grant.similar_grants.similar_grants.length\n consola.info('')\n consola.info(` Similar grant(s) found (${n}). Your approver can extend an existing grant to cover this request.`)\n }\n\n notifyGrantPending({\n grantId: grant.id,\n approveUrl: `${idp}/grant-approval?grant_id=${grant.id}`,\n command: resolved.detail?.display || parsed?.raw || 'unknown',\n audience: resolved.adapter?.cli?.audience ?? 'shapes',\n host: (args.host as string) || hostname(),\n })\n\n if (shouldWaitForGrant(args)) {\n consola.info(`Grant requested: ${grant.id}`)\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 throw new CliError(`Grant ${status}`)\n\n const token = await fetchGrantToken(idp, grant.id)\n await verifyAndExecute(token, resolved)\n return true\n }\n\n printPendingGrantInfo(grant, idp)\n return true\n}\n\n/** Execute a shell command as [shell, '-c', command_string] via execFileSync */\nfunction execShellCommand(command: string[]): void {\n if (command.length === 0)\n throw new CliError('No command to execute')\n try {\n execFileSync(command[0]!, command.slice(1), { stdio: 'inherit' })\n }\n catch (err: unknown) {\n const exitCode = (err as { status?: number }).status || 1\n throw new CliExit(exitCode)\n }\n}\n\nfunction extractPositionals(rawArgs: string[]): string[] {\n const positionals: string[] = []\n const delimiter = rawArgs.indexOf('--')\n const args = delimiter >= 0 ? rawArgs.slice(0, delimiter) : rawArgs\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i]!\n if (arg === 'run')\n continue\n if (arg.startsWith('--')) {\n i++ // skip flag value\n continue\n }\n positionals.push(arg)\n }\n return positionals\n}\n\nasync function runAdapterMode(\n command: string[],\n rawArgs: string[],\n args: Record<string, unknown>,\n) {\n const idp = getIdpUrl(args.idp as string | undefined)\n if (!idp)\n throw new Error('No IdP URL configured. Run `apes login` first or pass --idp.')\n\n // If caller wants to run as another user (e.g. root), auto-switch to the escapes audience flow.\n // Adapter mode (Shapes) is user-level and cannot elevate privileges.\n if (args.as) {\n await runAudienceMode('escapes', command.join(' '), args)\n return\n }\n\n const adapterOpt = extractOption(rawArgs, 'adapter')\n const loaded = loadAdapter(command[0]!, adapterOpt)\n const resolved = await resolveCommand(loaded, command)\n const approval = (args.approval ?? 'once') as 'once' | 'timed' | 'always'\n\n // Try reusing an existing timed/always grant (findExistingGrant skips once grants)\n try {\n const existingGrantId = await findExistingGrant(resolved, idp)\n if (existingGrantId) {\n consola.info(`Reusing existing grant: ${existingGrantId}`)\n const token = await fetchGrantToken(idp, existingGrantId)\n await verifyAndExecute(token, resolved)\n return\n }\n }\n catch {\n // Fall through to creating a new grant\n }\n\n const grant = await createShapesGrant(resolved, {\n idp,\n approval,\n ...(args.reason ? { reason: args.reason as string } : {}),\n })\n\n if (grant.similar_grants?.similar_grants?.length) {\n const n = grant.similar_grants.similar_grants.length\n consola.info('')\n consola.info(` Similar grant(s) found (${n}). Your approver can extend an existing grant to cover this request.`)\n if (grant.similar_grants.widened_details?.length) {\n const wider = grant.similar_grants.widened_details.map(d => d.permission).join(', ')\n consola.info(` Broader scope: ${wider}`)\n }\n consola.info('')\n }\n\n if (shouldWaitForGrant(args)) {\n consola.info(`Grant requested: ${grant.id}`)\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 throw new Error(`Grant ${status}`)\n\n const token = await fetchGrantToken(idp, grant.id)\n await verifyAndExecute(token, resolved)\n return\n }\n\n printPendingGrantInfo(grant, idp)\n}\n\nasync function runAudienceMode(\n audience: string,\n action: string,\n args: Record<string, unknown>,\n) {\n const auth = loadAuth()\n if (!auth) {\n throw new CliError('Not logged in. Run `apes login` first.')\n }\n\n const idp = getIdpUrl(args.idp as string | undefined)!\n const grantsUrl = await getGrantsEndpoint(idp)\n const command = action.split(' ')\n const targetHost = (args.host as string) || hostname()\n\n // Step 1: Request grant\n consola.info(`Requesting ${audience} grant on ${targetHost}: ${command.join(' ')}`)\n const grant = await apiFetch<{ id: string, status: string }>(grantsUrl, {\n method: 'POST',\n body: {\n requester: auth.email,\n target_host: targetHost,\n audience,\n grant_type: args.approval,\n command,\n reason: (args.reason as string) || command.join(' '),\n ...(args.as ? { run_as: args.as } : {}),\n },\n })\n if (!shouldWaitForGrant(args)) {\n printPendingGrantInfo(grant, idp)\n return\n }\n\n consola.success(`Grant requested: ${grant.id}`)\n\n // Step 2: Wait for approval\n consola.info('Waiting for approval...')\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 consola.success('Grant approved!')\n break\n }\n if (status.status === 'denied' || status.status === 'revoked') {\n throw new CliError(`Grant ${status.status}.`)\n }\n await new Promise(r => setTimeout(r, interval))\n }\n\n // Step 3: Get grant token\n consola.info('Fetching grant token...')\n const { authz_jwt } = await apiFetch<{ authz_jwt: string }>(`${grantsUrl}/${grant.id}/token`, {\n method: 'POST',\n })\n\n // Step 4: Execute or output token\n if (audience === 'escapes') {\n consola.info(`Executing: ${command.join(' ')}`)\n try {\n execFileSync((args['escapes-path'] as string) || 'escapes', ['--grant', authz_jwt, '--', ...command], {\n stdio: 'inherit',\n })\n }\n catch (err: unknown) {\n const exitCode = (err as { status?: number }).status || 1\n throw new CliExit(exitCode)\n }\n }\n else {\n process.stdout.write(authz_jwt)\n }\n}\n","import { defineCommand } from 'citty'\nimport { extractOption, extractWrappedCommand, loadAdapter, resolveCommand } from '../shapes/index.js'\n\nexport const explainCommand = defineCommand({\n meta: {\n name: 'explain',\n description: 'Show what permission a 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: apes 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","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { getIdpUrl, loadAuth, loadConfig } from '../../config'\nimport { CliError } from '../../errors'\n\nexport const configGetCommand = defineCommand({\n meta: {\n name: 'get',\n description: 'Get a configuration value',\n },\n args: {\n key: {\n type: 'positional',\n description: 'Config key: idp, email, defaults.idp, defaults.approval, agent.key, agent.email',\n required: true,\n },\n },\n run({ args }) {\n const key = args.key\n\n switch (key) {\n case 'idp': {\n const idp = getIdpUrl()\n if (idp)\n console.log(idp)\n else\n consola.info('No IdP configured.')\n break\n }\n case 'email': {\n const auth = loadAuth()\n if (auth?.email)\n console.log(auth.email)\n else\n consola.info('Not logged in.')\n break\n }\n default: {\n // Dot-notation: defaults.idp, defaults.approval, agent.key, agent.email\n const config = loadConfig()\n const parts = key.split('.')\n if (parts.length === 2) {\n const section = parts[0] as keyof typeof config\n const field = parts[1]!\n const sectionObj = config[section] as Record<string, string> | undefined\n if (sectionObj && field in sectionObj) {\n console.log(sectionObj[field])\n }\n else {\n consola.info(`Key \"${key}\" not set.`)\n }\n }\n else {\n throw new CliError(`Unknown key: \"${key}\". Use: idp, email, defaults.idp, defaults.approval, agent.key, agent.email`)\n }\n }\n }\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { loadConfig, saveConfig } from '../../config'\nimport { CliError } from '../../errors'\n\nexport const configSetCommand = defineCommand({\n meta: {\n name: 'set',\n description: 'Set a configuration value',\n },\n args: {\n key: {\n type: 'positional',\n description: 'Config key: defaults.idp, defaults.approval, agent.key, agent.email',\n required: true,\n },\n value: {\n type: 'positional',\n description: 'Value to set',\n required: true,\n },\n },\n run({ args }) {\n const key = args.key\n const value = args.value\n const config = loadConfig()\n\n const parts = key.split('.')\n if (parts.length !== 2) {\n throw new CliError(`Invalid key: \"${key}\". Use: defaults.idp, defaults.approval, agent.key, agent.email`)\n }\n\n const [section, field] = parts as [string, string]\n\n if (section === 'defaults') {\n config.defaults = config.defaults || {}\n ;(config.defaults as Record<string, string>)[field] = value\n }\n else if (section === 'agent') {\n config.agent = config.agent || {}\n ;(config.agent as Record<string, string>)[field] = value\n }\n else {\n throw new CliError(`Unknown section: \"${section}\". Use: defaults, agent`)\n }\n\n saveConfig(config)\n consola.success(`Set ${key} = ${value}`)\n },\n})\n","import { defineCommand } from 'citty'\nimport { getAuthToken } from '../../config'\nimport { CliError } from '../../errors'\n\nasync function doRequest(method: string, url: string, body: string | undefined, contentType: string, raw: boolean, showHeaders: boolean) {\n const token = getAuthToken()\n if (!token) {\n throw new CliError('Not authenticated. Run `apes login` first.')\n }\n\n const response = await fetch(url, {\n method,\n headers: {\n 'Authorization': `Bearer ${token}`,\n 'Content-Type': contentType,\n },\n body: body || undefined,\n })\n\n if (showHeaders) {\n console.log(`HTTP ${response.status} ${response.statusText}`)\n for (const [key, value] of response.headers.entries()) {\n console.log(`${key}: ${value}`)\n }\n console.log()\n }\n\n const respContentType = response.headers.get('content-type') || ''\n const text = await response.text()\n\n if (raw || !respContentType.includes('json')) {\n process.stdout.write(text)\n }\n else {\n try {\n console.log(JSON.stringify(JSON.parse(text), null, 2))\n }\n catch {\n process.stdout.write(text)\n }\n }\n\n if (!response.ok) {\n throw new CliError(`HTTP ${response.status} ${response.statusText}`)\n }\n}\n\nexport const fetchCommand = defineCommand({\n meta: {\n name: 'fetch',\n description: 'Make authenticated HTTP requests',\n },\n subCommands: {\n get: defineCommand({\n meta: {\n name: 'get',\n description: 'GET request with auth token',\n },\n args: {\n url: {\n type: 'positional',\n description: 'URL to fetch',\n required: true,\n },\n raw: {\n type: 'boolean',\n description: 'Output raw response body',\n default: false,\n },\n headers: {\n type: 'boolean',\n description: 'Show response headers',\n default: false,\n },\n },\n async run({ args }) {\n await doRequest('GET', String(args.url), undefined, 'application/json', Boolean(args.raw), Boolean(args.headers))\n },\n }),\n\n post: defineCommand({\n meta: {\n name: 'post',\n description: 'POST request with auth token',\n },\n args: {\n url: {\n type: 'positional',\n description: 'URL to fetch',\n required: true,\n },\n body: {\n type: 'string',\n description: 'Request body (JSON string)',\n },\n 'content-type': {\n type: 'string',\n description: 'Content-Type header',\n default: 'application/json',\n },\n raw: {\n type: 'boolean',\n description: 'Output raw response body',\n default: false,\n },\n headers: {\n type: 'boolean',\n description: 'Show response headers',\n default: false,\n },\n },\n async run({ args }) {\n await doRequest('POST', String(args.url), args.body as string | undefined, String(args['content-type'] || 'application/json'), Boolean(args.raw), Boolean(args.headers))\n },\n }),\n },\n})\n","import { defineCommand } from 'citty'\n\nexport const mcpCommand = defineCommand({\n meta: {\n name: 'mcp',\n description: 'Start MCP server for AI agents',\n },\n args: {\n transport: {\n type: 'string',\n description: 'Transport type: stdio or sse',\n default: 'stdio',\n },\n port: {\n type: 'string',\n description: 'Port for SSE transport',\n default: '3001',\n },\n },\n async run({ args }) {\n const transport = (args.transport || 'stdio') as 'stdio' | 'sse'\n const port = Number.parseInt(String(args.port), 10)\n\n if (transport !== 'stdio' && transport !== 'sse') {\n throw new Error('Transport must be \"stdio\" or \"sse\"')\n }\n\n const { startMcpServer } = await import('./server.js')\n await startMcpServer(transport, port)\n },\n})\n","import { existsSync, copyFileSync, writeFileSync } from 'node:fs'\nimport { randomBytes } from 'node:crypto'\nimport { execFileSync } from 'node:child_process'\nimport { join } from 'node:path'\nimport { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { CliError, CliExit } from '../../errors'\n\nconst DEFAULT_IDP_URL = 'https://id.openape.at'\n\nasync function downloadTemplate(repo: string, targetDir: string) {\n const { downloadTemplate: gigetDownload } = await import('giget')\n await gigetDownload(`gh:${repo}`, { dir: targetDir, force: false })\n}\n\nfunction installDeps(dir: string) {\n const hasLockFile = (name: string) => existsSync(join(dir, name))\n\n if (hasLockFile('pnpm-lock.yaml')) {\n execFileSync('pnpm', ['install'], { cwd: dir, stdio: 'inherit' })\n }\n else if (hasLockFile('bun.lockb')) {\n execFileSync('bun', ['install'], { cwd: dir, stdio: 'inherit' })\n }\n else {\n execFileSync('npm', ['install'], { cwd: dir, stdio: 'inherit' })\n }\n}\n\nasync function promptChoice(message: string, choices: string[]): Promise<string> {\n const result = await consola.prompt(message, { type: 'select', options: choices })\n if (typeof result === 'symbol') {\n throw new CliExit(0)\n }\n return result as string\n}\n\nasync function promptText(message: string, defaultValue?: string): Promise<string> {\n const result = await consola.prompt(message, { type: 'text', default: defaultValue, placeholder: defaultValue })\n if (typeof result === 'symbol') {\n throw new CliExit(0)\n }\n return (result as string) || defaultValue || ''\n}\n\nexport const initCommand = defineCommand({\n meta: {\n name: 'init',\n description: 'Scaffold a new OpenApe project',\n },\n args: {\n sp: {\n type: 'boolean',\n description: 'Create a Service Provider app',\n },\n idp: {\n type: 'boolean',\n description: 'Create an Identity Provider app',\n },\n dir: {\n type: 'positional',\n description: 'Target directory',\n required: false,\n },\n },\n async run({ args }) {\n let mode: 'sp' | 'idp'\n\n if (args.sp) {\n mode = 'sp'\n }\n else if (args.idp) {\n mode = 'idp'\n }\n else {\n const choice = await promptChoice('What do you want to set up?', [\n 'SP — Add login to my app',\n 'IdP — Run my own Identity Provider',\n ])\n mode = choice.startsWith('SP') ? 'sp' : 'idp'\n }\n\n if (mode === 'sp') {\n await initSP(args.dir)\n }\n else {\n await initIdP(args.dir)\n }\n },\n})\n\nasync function initSP(targetDir?: string) {\n const dir = targetDir || 'my-app'\n\n if (existsSync(join(dir, 'package.json'))) {\n throw new CliError(`Directory \"${dir}\" already contains a project.`)\n }\n\n consola.start('Scaffolding SP starter...')\n await downloadTemplate('openape-ai/openape-sp-starter', dir)\n consola.success('Scaffolded from openape-sp-starter')\n\n consola.start('Installing dependencies...')\n installDeps(dir)\n consola.success('Dependencies installed')\n\n // Create .env from .env.example\n const envExample = join(dir, '.env.example')\n const envFile = join(dir, '.env')\n if (existsSync(envExample) && !existsSync(envFile)) {\n copyFileSync(envExample, envFile)\n consola.success(`\\`.env\\` created (using Free IdP at ${DEFAULT_IDP_URL})`)\n }\n\n console.log('')\n consola.box([\n `cd ${dir}`,\n 'npm run dev',\n '',\n 'Then open http://localhost:3001/login',\n ].join('\\n'))\n}\n\nasync function initIdP(targetDir?: string) {\n const dir = targetDir || 'my-idp'\n\n if (existsSync(join(dir, 'package.json'))) {\n throw new CliError(`Directory \"${dir}\" already contains a project.`)\n }\n\n // Interactive questions\n const domain = await promptText('Domain for the IdP', 'localhost')\n const storage = await promptChoice('Storage backend', [\n 'memory (dev only, data lost on restart)',\n 'fs (local filesystem)',\n 's3 (S3-compatible)',\n ])\n const adminEmail = await promptText('Admin email')\n\n consola.start('Scaffolding IdP starter...')\n await downloadTemplate('openape-ai/openape-idp-starter', dir)\n consola.success('Scaffolded from openape-idp-starter')\n\n consola.start('Installing dependencies...')\n installDeps(dir)\n consola.success('Dependencies installed')\n\n // Generate secrets\n const sessionSecret = randomBytes(32).toString('hex')\n const managementToken = randomBytes(32).toString('hex')\n consola.success('Secrets generated')\n\n // Determine origin/issuer\n const isLocalhost = domain === 'localhost'\n const origin = isLocalhost ? 'http://localhost:3000' : `https://${domain}`\n\n // Write .env\n const envContent = [\n '# Generated by apes init --idp',\n '',\n `NUXT_OPENAPE_SESSION_SECRET=${sessionSecret}`,\n `NUXT_OPENAPE_ADMIN_EMAILS=${adminEmail}`,\n `NUXT_OPENAPE_MANAGEMENT_TOKEN=${managementToken}`,\n `NUXT_OPENAPE_ISSUER=${origin}`,\n `NUXT_OPENAPE_RP_NAME=My Identity Provider`,\n `NUXT_OPENAPE_RP_ID=${domain}`,\n `NUXT_OPENAPE_RP_ORIGIN=${origin}`,\n ].join('\\n')\n\n writeFileSync(join(dir, '.env'), `${envContent}\\n`, { mode: 0o600 })\n consola.success('.env created')\n\n console.log('')\n consola.box([\n `cd ${dir}`,\n 'npm run dev',\n '',\n 'Then open http://localhost:3000/admin',\n '',\n ...(isLocalhost\n ? []\n : [\n 'For production:',\n ` 1. DNS TXT Record: _ddisa.${domain.replace(/^id\\./, '')} → \"v=ddisa1 idp=${origin}\"`,\n ` 2. Storage: switch to ${storage.includes('s3') ? 's3' : 'fs'} in nuxt.config.ts`,\n ' 3. Deploy: vercel deploy',\n ]),\n ].join('\\n'))\n}\n","import { Buffer } from 'node:buffer'\nimport { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'\nimport { execFile } from 'node:child_process'\nimport { generateKeyPairSync, sign } from 'node:crypto'\nimport { dirname, resolve } from 'node:path'\nimport { homedir } from 'node:os'\nimport { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { loadEd25519PrivateKey } from '../ssh-key'\nimport { getAgentChallengeEndpoint, getAgentAuthenticateEndpoint } from '../http'\nimport { saveAuth, saveConfig, loadConfig } from '../config'\nimport { CliError, CliExit } from '../errors'\n\nconst DEFAULT_IDP_URL = 'https://id.openape.at'\nconst DEFAULT_KEY_PATH = '~/.ssh/id_ed25519'\nconst POLL_INTERVAL = 3000\nconst POLL_TIMEOUT = 300_000 // 5 minutes\n\nfunction resolvePath(p: string): string {\n return resolve(p.replace(/^~/, homedir()))\n}\n\nfunction openBrowser(url: string) {\n const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open'\n execFile(cmd, [url], () => {})\n}\n\nfunction readPublicKey(keyPath: string): string {\n const pubPath = `${keyPath}.pub`\n if (existsSync(pubPath)) {\n return readFileSync(pubPath, 'utf-8').trim()\n }\n\n // Derive public key from private key\n const keyContent = readFileSync(keyPath, 'utf-8')\n const privateKey = loadEd25519PrivateKey(keyContent)\n const jwk = privateKey.export({ format: 'jwk' }) as { x: string }\n const pubBytes = Buffer.from(jwk.x, 'base64url')\n\n // Format as OpenSSH public key\n const keyTypeStr = 'ssh-ed25519'\n const keyTypeLen = Buffer.alloc(4)\n keyTypeLen.writeUInt32BE(keyTypeStr.length)\n const pubKeyLen = Buffer.alloc(4)\n pubKeyLen.writeUInt32BE(pubBytes.length)\n const blob = Buffer.concat([keyTypeLen, Buffer.from(keyTypeStr), pubKeyLen, pubBytes])\n\n return `ssh-ed25519 ${blob.toString('base64')}`\n}\n\nfunction generateAndSaveKey(keyPath: string): string {\n const resolved = resolvePath(keyPath)\n const dir = dirname(resolved)\n\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true })\n }\n\n // Generate Ed25519 key pair\n const { publicKey, privateKey } = generateKeyPairSync('ed25519')\n\n // Export private key in PKCS8 PEM format (universally readable)\n const privatePem = privateKey.export({ type: 'pkcs8', format: 'pem' }) as string\n writeFileSync(resolved, privatePem, { mode: 0o600 })\n\n // Export public key in OpenSSH format\n const jwk = publicKey.export({ format: 'jwk' }) as { x: string }\n const pubBytes = Buffer.from(jwk.x, 'base64url')\n const keyTypeStr = 'ssh-ed25519'\n const keyTypeLen = Buffer.alloc(4)\n keyTypeLen.writeUInt32BE(keyTypeStr.length)\n const pubKeyLen = Buffer.alloc(4)\n pubKeyLen.writeUInt32BE(pubBytes.length)\n const blob = Buffer.concat([keyTypeLen, Buffer.from(keyTypeStr), pubKeyLen, pubBytes])\n const pubKeyStr = `ssh-ed25519 ${blob.toString('base64')}`\n\n writeFileSync(`${resolved}.pub`, `${pubKeyStr}\\n`, { mode: 0o644 })\n\n return pubKeyStr\n}\n\nasync function pollForEnrollment(\n idp: string,\n agentEmail: string,\n keyPath: string,\n): Promise<{ token: string, expiresIn: number }> {\n const resolvedKey = resolvePath(keyPath)\n const keyContent = readFileSync(resolvedKey, 'utf-8')\n const privateKey = loadEd25519PrivateKey(keyContent)\n\n const challengeUrl = await getAgentChallengeEndpoint(idp)\n const authenticateUrl = await getAgentAuthenticateEndpoint(idp)\n const startTime = Date.now()\n\n while (Date.now() - startTime < POLL_TIMEOUT) {\n try {\n // Try to get a challenge — if it works, agent is enrolled\n const challengeResp = await fetch(challengeUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ agent_id: agentEmail }),\n })\n\n if (challengeResp.ok) {\n const { challenge } = await challengeResp.json() as { challenge: string }\n const signature = sign(null, Buffer.from(challenge), privateKey).toString('base64')\n\n const authResp = await fetch(authenticateUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ agent_id: agentEmail, challenge, signature }),\n })\n\n if (authResp.ok) {\n const result = await authResp.json() as { token: string, expires_in: number }\n return { token: result.token, expiresIn: result.expires_in }\n }\n }\n }\n catch {\n // Ignore network errors during polling\n }\n\n await new Promise(resolve => setTimeout(resolve, POLL_INTERVAL))\n }\n\n throw new Error('Enrollment timed out. Please check the browser and try again.')\n}\n\nexport const enrollCommand = defineCommand({\n meta: {\n name: 'enroll',\n description: 'Enroll an agent with an Identity Provider',\n },\n args: {\n idp: {\n type: 'string',\n description: `IdP URL (default: ${DEFAULT_IDP_URL})`,\n },\n name: {\n type: 'string',\n description: 'Agent name',\n },\n key: {\n type: 'string',\n description: `Path to Ed25519 key (default: ${DEFAULT_KEY_PATH})`,\n },\n },\n async run({ args }) {\n // 1. Gather inputs\n const idp = args.idp\n || await consola.prompt('IdP URL', { type: 'text', default: DEFAULT_IDP_URL, placeholder: DEFAULT_IDP_URL }).then((r) => { if (typeof r === 'symbol') throw new CliExit(0); return r }) as string\n || DEFAULT_IDP_URL\n\n const agentName = args.name\n || await consola.prompt('Agent name', { type: 'text', placeholder: 'deploy-bot' }).then((r) => { if (typeof r === 'symbol') throw new CliExit(0); return r }) as string\n\n if (!agentName) {\n throw new CliError('Agent name is required.')\n }\n\n const keyPath = args.key\n || await consola.prompt('Ed25519 key', { type: 'text', default: DEFAULT_KEY_PATH, placeholder: DEFAULT_KEY_PATH }).then((r) => { if (typeof r === 'symbol') throw new CliExit(0); return r }) as string\n || DEFAULT_KEY_PATH\n\n // 2. Handle key\n const resolvedKey = resolvePath(keyPath)\n let publicKey: string\n\n if (existsSync(resolvedKey)) {\n publicKey = readPublicKey(resolvedKey)\n consola.success(`Using existing key ${keyPath}`)\n }\n else {\n consola.start(`Generating Ed25519 key pair at ${keyPath}...`)\n publicKey = generateAndSaveKey(keyPath)\n consola.success(`Key pair generated at ${keyPath}`)\n }\n\n // 3. Open browser for enrollment\n const encodedKey = encodeURIComponent(publicKey)\n const enrollUrl = `${idp}/enroll?name=${encodeURIComponent(agentName)}&key=${encodedKey}`\n\n consola.info('Opening browser for enrollment...')\n consola.info(`→ ${idp}/enroll`)\n openBrowser(enrollUrl)\n\n // 4. Determine expected agent email\n // For the free IdP, the email format is: {name}+{user_local}+{user_domain}@id.openape.at\n // For custom IdPs, the format varies. We'll try common patterns.\n // The polling will try the challenge endpoint which accepts email as agent_id.\n // We need to guess the email, or poll without knowing it.\n // Best approach: ask the user to confirm the email shown in browser.\n console.log('')\n const agentEmail = await consola.prompt(\n 'Agent email (shown in browser after enrollment)',\n { type: 'text', placeholder: `agent+${agentName}@...` },\n ).then((r) => { if (typeof r === 'symbol') throw new CliExit(0); return r }) as string\n\n if (!agentEmail) {\n throw new CliError('Agent email is required to verify enrollment.')\n }\n\n // 5. Poll for enrollment confirmation via challenge endpoint\n consola.start('Verifying enrollment...')\n const { token, expiresIn } = await pollForEnrollment(idp, agentEmail, keyPath)\n\n // 6. Save auth + config\n saveAuth({\n idp,\n access_token: token,\n email: agentEmail,\n expires_at: Math.floor(Date.now() / 1000) + (expiresIn || 3600),\n })\n\n const config = loadConfig()\n config.defaults = { ...config.defaults, idp }\n config.agent = { key: keyPath, email: agentEmail }\n saveConfig(config)\n\n consola.success(`Agent enrolled as ${agentEmail}`)\n consola.success('Config saved to ~/.config/apes/')\n\n console.log('')\n consola.info('Verify with: apes whoami')\n },\n})\n","import { existsSync, readFileSync } from 'node:fs'\nimport { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { apiFetch } from '../http'\nimport { loadAuth, getIdpUrl } from '../config'\nimport { CliError } from '../errors'\n\nexport const registerUserCommand = defineCommand({\n meta: {\n name: 'register-user',\n description: 'Register a sub-user with SSH key',\n },\n args: {\n email: {\n type: 'string',\n description: 'Email for the new user',\n required: true,\n },\n name: {\n type: 'string',\n description: 'Name for the new user',\n required: true,\n },\n key: {\n type: 'string',\n description: 'Path to SSH public key file or key string',\n required: true,\n },\n type: {\n type: 'string',\n description: 'User type: human or agent (default: agent)',\n },\n },\n async run({ args }) {\n const auth = loadAuth()\n if (!auth) {\n throw new CliError('Not authenticated. Run `apes login` first.')\n }\n\n const idp = getIdpUrl()\n if (!idp) {\n throw new CliError('No IdP URL configured. Run `apes login` first.')\n }\n\n // Read key from file or use as string\n let publicKey = args.key\n if (existsSync(args.key)) {\n publicKey = readFileSync(args.key, 'utf-8').trim()\n }\n\n if (!publicKey.startsWith('ssh-ed25519 ')) {\n throw new CliError('Public key must be in ssh-ed25519 format.')\n }\n\n const userType = args.type as 'human' | 'agent' | undefined\n if (userType && userType !== 'human' && userType !== 'agent') {\n throw new CliError('Type must be \"human\" or \"agent\".')\n }\n\n const result = await apiFetch<{\n email: string\n name: string\n owner: string\n type: string\n }>(`${idp}/api/auth/enroll`, {\n method: 'POST',\n body: {\n email: args.email,\n name: args.name,\n publicKey,\n ...(userType ? { type: userType } : {}),\n },\n })\n\n consola.success(`User registered: ${result.email} (type: ${result.type}, owner: ${result.owner})`)\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { resolveDDISA } from '@openape/core'\nimport { CliError } from '../errors'\n\nexport const dnsCheckCommand = defineCommand({\n meta: {\n name: 'dns-check',\n description: 'Validate DDISA DNS TXT records for a domain',\n },\n args: {\n domain: {\n type: 'positional',\n description: 'Domain to check (e.g. example.com)',\n required: true,\n },\n },\n async run({ args }) {\n const domain = args.domain\n\n consola.start(`Checking _ddisa.${domain}...`)\n\n try {\n const result = await resolveDDISA(domain)\n\n if (!result) {\n console.log('')\n console.log('To set up DDISA, add a DNS TXT record:')\n console.log(` _ddisa.${domain} TXT \"v=ddisa1 idp=https://id.${domain}\"`)\n throw new CliError(`No DDISA record found for ${domain}`)\n }\n\n consola.success(`_ddisa.${domain} → ${result.idp}`)\n console.log('')\n console.log(` Version: ${result.version || 'ddisa1'}`)\n console.log(` IdP URL: ${result.idp}`)\n if (result.mode)\n console.log(` Mode: ${result.mode}`)\n if (result.priority !== undefined)\n console.log(` Priority: ${result.priority}`)\n\n // Try OIDC discovery on the IdP\n console.log('')\n consola.start(`Verifying IdP at ${result.idp}...`)\n\n const discoResp = await fetch(`${result.idp}/.well-known/openid-configuration`)\n\n if (!discoResp.ok) {\n consola.warn(`IdP discovery failed (${discoResp.status}). Is the IdP running at ${result.idp}?`)\n return\n }\n\n const disco = await discoResp.json() as Record<string, unknown>\n\n consola.success(`IdP is reachable`)\n console.log(` Issuer: ${disco.issuer}`)\n console.log(` DDISA: v${disco.ddisa_version || '?'}`)\n\n if (disco.ddisa_auth_methods_supported) {\n console.log(` Auth: ${(disco.ddisa_auth_methods_supported as string[]).join(', ')}`)\n }\n\n if (disco.openape_grant_types_supported) {\n console.log(` Grants: ${(disco.openape_grant_types_supported as string[]).join(', ')}`)\n }\n }\n catch (err) {\n throw new CliError(`DNS check failed: ${err instanceof Error ? err.message : String(err)}`)\n }\n },\n})\n","import { exec } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport { defineCommand } from 'citty'\nimport { AUTH_FILE, CONFIG_DIR, loadAuth } from '../config'\nimport { apiFetch, getGrantsEndpoint } from '../http'\nimport { CliError } from '../errors'\n\ndeclare const __VERSION__: string\n\ninterface HealthArgs {\n json: boolean\n}\n\ninterface HealthReport {\n version: string\n config: { dir: string }\n auth: {\n file: string\n present: boolean\n email?: string\n type?: 'human' | 'agent'\n idp?: string\n expires_at_iso?: string\n expires_at_local?: string\n expired?: boolean\n }\n idp: { url?: string, reachable: boolean, error?: string }\n grants: { count?: number, error?: string }\n ape_shell_binary: string | null\n ok: boolean\n}\n\nconst execAsync = promisify(exec)\n\nasync function resolveApeShellPath(): Promise<string | null> {\n try {\n const { stdout } = await execAsync('command -v ape-shell', { shell: '/bin/bash' })\n const trimmed = stdout.trim()\n return trimmed.length > 0 ? trimmed : null\n }\n catch {\n return null\n }\n}\n\nasync function probeIdp(url: string): Promise<{ reachable: true } | { reachable: false, error: string }> {\n const ctrl = new AbortController()\n const timeout = setTimeout(() => ctrl.abort(), 3000)\n try {\n // Plain fetch — we don't want apiFetch's bearer token or retry logic.\n // HEAD may not be supported; fall back to GET if needed.\n await fetch(url, { method: 'GET', signal: ctrl.signal })\n return { reachable: true }\n }\n catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n return { reachable: false, error: message }\n }\n finally {\n clearTimeout(timeout)\n }\n}\n\nasync function bestEffortGrantCount(idp: string): Promise<{ count: number } | { error: string }> {\n try {\n const grantsUrl = await getGrantsEndpoint(idp)\n const res = await apiFetch<{ data: unknown[] }>(`${grantsUrl}?limit=1`)\n const count = Array.isArray(res?.data) ? res.data.length : 0\n return { count }\n }\n catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n return { error: message }\n }\n}\n\nexport async function runHealth(args: HealthArgs): Promise<void> {\n const version = typeof __VERSION__ === 'string' ? __VERSION__ : '0.0.0'\n\n const auth = loadAuth()\n if (!auth) {\n throw new CliError('Not logged in. Run `apes login` first.', 1)\n }\n\n const isAgent = auth.email.includes('agent+')\n const expiresDate = new Date(auth.expires_at * 1000)\n const isExpired = Date.now() / 1000 > auth.expires_at\n\n if (isExpired) {\n throw new CliError(`Token expired at ${expiresDate.toISOString()}. Run \\`apes login\\`.`, 1)\n }\n\n const idpProbe = await probeIdp(auth.idp)\n const grantInfo = await bestEffortGrantCount(auth.idp)\n const apeShellPath = await resolveApeShellPath()\n\n const report: HealthReport = {\n version,\n config: { dir: CONFIG_DIR },\n auth: {\n file: AUTH_FILE,\n present: true,\n email: auth.email,\n type: isAgent ? 'agent' : 'human',\n idp: auth.idp,\n expires_at_iso: expiresDate.toISOString(),\n expires_at_local: expiresDate.toLocaleString(),\n expired: false,\n },\n idp: {\n url: auth.idp,\n reachable: idpProbe.reachable,\n ...('error' in idpProbe ? { error: idpProbe.error } : {}),\n },\n grants: 'count' in grantInfo\n ? { count: grantInfo.count }\n : { error: grantInfo.error },\n ape_shell_binary: apeShellPath,\n ok: idpProbe.reachable,\n }\n\n if (args.json) {\n console.log(JSON.stringify(report, null, 2))\n }\n else {\n console.log(`apes ${version}`)\n console.log('')\n console.log(`Config: ${CONFIG_DIR}`)\n console.log(`Auth: ${AUTH_FILE}`)\n console.log(` ${auth.email} (${isAgent ? 'agent' : 'human'})`)\n console.log(` IdP: ${auth.idp}`)\n console.log(` Token: valid until ${expiresDate.toISOString()} (local: ${expiresDate.toLocaleString()})`)\n console.log('')\n if (idpProbe.reachable) {\n console.log('IdP: reachable')\n }\n else {\n console.log(`IdP: <unreachable: ${idpProbe.error}>`)\n }\n if ('count' in grantInfo) {\n console.log(`Grants: ${grantInfo.count}`)\n }\n else {\n console.log(`Grants: <unreachable: ${grantInfo.error}>`)\n }\n console.log(`ape-shell: ${apeShellPath ?? '(not on PATH)'}`)\n }\n\n if (!idpProbe.reachable) {\n throw new CliError(`IdP ${auth.idp} unreachable: ${idpProbe.error}`, 1)\n }\n}\n\nexport const healthCommand = defineCommand({\n meta: {\n name: 'health',\n description: 'Report CLI diagnostic state (auth, IdP, grants, binaries)',\n },\n args: {\n json: {\n type: 'boolean',\n description: 'Emit a machine-readable JSON report',\n default: false,\n },\n },\n async run({ args }) {\n await runHealth({ json: Boolean(args.json) })\n },\n})\n","import { defineCommand } from 'citty'\nimport consola from 'consola'\nimport { guides } from '../guides'\nimport { CliError } from '../errors'\n\nexport const workflowsCommand = defineCommand({\n meta: {\n name: 'workflows',\n description: 'Discover workflow guides',\n },\n args: {\n id: {\n type: 'positional',\n description: 'Guide ID to show (omit for list)',\n required: false,\n },\n json: {\n type: 'boolean',\n description: 'Output as JSON',\n default: false,\n },\n },\n run({ args }) {\n if (args.id) {\n const guide = guides.find(g => g.id === String(args.id))\n if (!guide) {\n consola.info(`Available: ${guides.map(g => g.id).join(', ')}`)\n throw new CliError(`Guide not found: ${args.id}`)\n }\n\n if (args.json) {\n console.log(JSON.stringify(guide, null, 2))\n return\n }\n\n console.log(`\\n ${guide.title}`)\n console.log(` ${guide.description}\\n`)\n for (let i = 0; i < guide.steps.length; i++) {\n const step = guide.steps[i]!\n if (step.note) {\n console.log(` Note: ${step.note}`)\n }\n else {\n console.log(` ${i + 1}. ${step.description}`)\n if (step.command) {\n console.log(` $ ${step.command}`)\n }\n }\n }\n console.log()\n return\n }\n\n // List mode\n if (args.json) {\n console.log(JSON.stringify(guides.map(g => ({ id: g.id, title: g.title, description: g.description })), null, 2))\n return\n }\n\n console.log('\\n Workflow Guides\\n')\n for (const guide of guides) {\n console.log(` ${guide.id.padEnd(24)} ${guide.title}`)\n }\n console.log(`\\n Show a guide: apes workflows <id>\\n`)\n },\n})\n","export interface WorkflowStep {\n description?: string\n command?: string\n note?: string\n}\n\nexport interface WorkflowGuide {\n id: string\n title: string\n description: string\n steps: WorkflowStep[]\n}\n\nexport const guides: WorkflowGuide[] = [\n {\n id: 'timed-session',\n title: 'Timed maintenance session',\n description: 'Request a timed grant for multiple commands without per-command approval.',\n steps: [\n { description: 'Request a timed grant (e.g. 1 hour)', command: 'apes run --approval timed -- <your-command>' },\n { description: 'Approve the grant in the browser (link is printed)' },\n { description: 'Subsequent commands reuse the timed grant until it expires' },\n { note: 'Use --approval always for standing permissions (revoke manually when done)' },\n ],\n },\n {\n id: 'agent-onboarding',\n title: 'Onboard a new agent',\n description: 'Register an AI agent with a DDISA identity in under 3 minutes.',\n steps: [\n { description: 'Initialize a new project (optional)', command: 'apes init --sp my-app' },\n { description: 'Enroll the agent at an IdP', command: 'apes enroll' },\n { description: 'Verify enrollment', command: 'apes whoami' },\n { description: 'Check DNS discovery', command: 'apes dns-check' },\n ],\n },\n {\n id: 'delegation',\n title: 'Delegate permissions',\n description: 'Let an agent act on your behalf at a specific service.',\n steps: [\n { description: 'Create a delegation', command: 'apes grants delegate --to agent@example.com --at api.example.com' },\n { description: 'List active delegations', command: 'apes grants delegations' },\n { description: 'Revoke when no longer needed', command: 'apes grants revoke <delegation-id>' },\n ],\n },\n {\n id: 'privilege-escalation',\n title: 'Run commands as root (escapes)',\n description: 'Execute privileged commands with grant-verified escalation.',\n steps: [\n { description: 'Request a grant to run a command as root', command: 'apes run --as root -- apt-get upgrade' },\n { description: 'Approve the grant in the browser' },\n { description: 'The command executes via escapes with verified authorization' },\n { note: 'escapes must be installed on the target machine (cargo build && sudo make install)' },\n ],\n },\n]\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAOA,eAAa;;;ACApB,OAAO,UAAU;AAuCV,SAAS,oBAAoB,MAAgB,OAAuC;AACzF,QAAM,eAAe,KAAK,CAAC,KAAK;AAMhC,QAAM,gBAAgB,aAAa,WAAW,GAAG;AACjD,QAAM,gBAAgB,OAAO,UAAU,YAAY,MAAM,WAAW,GAAG;AACvE,QAAM,sBAAsB,iBAAiB;AAC7C,QAAM,sBAAsB,gBAAgB,aAAa,MAAM,CAAC,IAAI;AACpE,QAAM,YAAY,KAAK,SAAS,mBAAmB;AAKnD,QAAM,aAAa,OAAO,YAAY,eAAe,QAAQ,KAAK,uBAAuB;AAIzF,QAAM,YAAY,cAAc,eAAe,cAAc;AAE7D,MAAI,CAAC,cAAc,CAAC;AAClB,WAAO;AAET,QAAM,YAAY,KAAK,MAAM,CAAC;AAK9B,MAAI,UAAU,CAAC,MAAM,QAAQ,UAAU,SAAS,GAAG;AACjD,WAAO,EAAE,QAAQ,WAAW,MAAM,CAAC,KAAK,CAAC,GAAI,KAAK,CAAC,GAAI,OAAO,WAAW,MAAM,QAAQ,M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Ac;AAAA,EACzB,MAAM;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,aAAa;AAAA,EACf;AAAA,EACA,aAAa;AAAA,IACX,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,iBAAiB;AAAA,IACjB,aAAa;AAAA,IACb,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,KAAK;AAAA,IACL,SAAS;AAAA,IACT,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,KAAK;AAAA,IACL,WAAW;AAAA,EACb;AACF,CAAC;AAED,QAAQ,IAAI,EAAE,MAAM,CAAC,QAAQ;AAC3B,MAAI,eAAe,SAAS;AAC1B,YAAQ,KAAK,IAAI,QAAQ;AAAA,EAC3B;AACA,MAAI,eAAe,UAAU;AAC3B,IAAAC,UAAQ,MAAM,IAAI,OAAO;AACzB,YAAQ,KAAK,IAAI,QAAQ;AAAA,EAC3B;AACA,MAAI,OAAO;AACT,IAAAA,UAAQ,MAAM,GAAG;AAAA,EACnB,OACK;AACH,IAAAA,UAAQ,MAAM,eAAe,WAAW,IAAI,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,EACxG;AACA,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["consola","defineCommand","homedir","consola","resolve","consola","readFileSync","sign","loadEd25519PrivateKey","homedir","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","defineCommand","defineCommand","consola","defineCommand","consola","hostname","defineCommand","consola","waitForApproval","consola","resolve","defineCommand","hostname","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","auth","defineCommand","consola","defineCommand","consola","defineCommand","defineCommand","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","defineCommand","consola","defineCommand","consola","existsSync","homedir","defineCommand","consola","getManagementToken","defineCommand","consola","homedir","existsSync","defineCommand","defineCommand","consola","defineCommand","index","consola","execFileSync","hostname","defineCommand","consola","consola","defineCommand","hostname","execFileSync","defineCommand","defineCommand","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","consola","defineCommand","defineCommand","defineCommand","existsSync","execFileSync","join","defineCommand","consola","existsSync","join","execFileSync","consola","defineCommand","Buffer","existsSync","readFileSync","writeFileSync","execFile","resolve","homedir","defineCommand","consola","DEFAULT_IDP_URL","resolvePath","resolve","homedir","openBrowser","execFile","existsSync","readFileSync","Buffer","writeFileSync","defineCommand","consola","existsSync","readFileSync","defineCommand","consola","defineCommand","existsSync","readFileSync","consola","defineCommand","consola","resolveDDISA","defineCommand","consola","resolveDDISA","defineCommand","defineCommand","defineCommand","consola","defineCommand","consola","defineCommand","consola"]}