@gravity-rail/cli 6.0.0 → 6.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{account-verify-phone-IC7FNUQE.js → account-verify-phone-FUOCVZ55.js} +2 -2
- package/dist/{chunk-VA6G6IBW.js → chunk-HTPFRSPP.js} +2 -2
- package/dist/{chunk-VA6G6IBW.js.map → chunk-HTPFRSPP.js.map} +1 -1
- package/dist/cli-utils.js +1 -1
- package/dist/{errors-YBSCLOHE.js → errors-CBQHNNRI.js} +2 -2
- package/dist/gr.js +5 -5
- package/dist/gr.js.map +1 -1
- package/dist/lib.js +3 -3
- package/package.json +2 -2
- /package/dist/{account-verify-phone-IC7FNUQE.js.map → account-verify-phone-FUOCVZ55.js.map} +0 -0
- /package/dist/{errors-YBSCLOHE.js.map → errors-CBQHNNRI.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli-utils/config.ts","../src/cli-utils/auth.ts","../package.json","../src/cli-utils/credentials-manager.ts","../src/lib/org-session.ts","../src/cli-utils/ui.ts","../src/cli-utils/agui.ts","../src/lib/context.ts","../src/lib/jq.ts","../src/lib/errors.ts","../src/lib/pagination.ts","../src/lib/output.ts","../src/lib/org-auth.ts","../../sandbox/src/index.ts","../../sandbox/src/env.ts","../../sandbox/src/sandbox-fetch.ts","../../sandbox/src/unix-broker-fetch.ts","../../sandbox/src/ask-user.ts","../../sandbox/src/ui.ts","../../sandbox/src/flow.ts","../src/lib/sandbox-fetch.ts","../src/lib/api-transport.ts"],"sourcesContent":["/**\n * CLI configuration for remote environments\n */\n\nimport { existsSync, readFileSync, statSync } from 'fs';\nimport { CORE_SCHEMA, defineSequenceTag, load } from 'js-yaml';\nimport { dirname, join, resolve } from 'path';\n\nexport interface EnvironmentConfig {\n apiUrl: string;\n frontendUrl: string;\n}\n\n/** Optional per-field URL overrides and the checkout to classify. */\nexport interface EnvironmentConfigOptions {\n apiUrl?: string;\n frontendUrl?: string;\n /** Directory to start the worktree walk from. Defaults to `process.cwd()`. */\n startDir?: string;\n}\n\nexport const ENVIRONMENTS: Record<string, EnvironmentConfig> = {\n dev: {\n apiUrl: 'https://api.gravityrail.test:5054',\n frontendUrl: 'https://app.gravityrail.test:3000',\n },\n prod: {\n apiUrl: 'https://api.gravityrail.com',\n frontendUrl: 'https://app.gravityrail.com',\n },\n staging: {\n apiUrl: 'https://api.gr-staging.com',\n frontendUrl: 'https://app.gr-staging.com',\n },\n};\n\n/** `--env dev` from a shell inside a dev-cloud pod: the pod's native services. */\nexport const DEV_CLOUD_POD_DEV: EnvironmentConfig = {\n apiUrl: 'http://127.0.0.1:5050',\n frontendUrl: 'http://127.0.0.1:3000',\n};\n\nexport const CALLBACK_PORT = 31337;\nexport const CALLBACK_PATH = '/oauth/callback';\nexport const REDIRECT_URI = `http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`;\n\nconst API_CONTAINER_PORT = 443;\nconst FRONTEND_CONTAINER_PORT = 3000;\nconst WORKTREE_SETUP_MARKER = 'worktree-setup.sh';\nconst OVERRIDE_FILENAME = 'docker-compose.override.yml';\nconst ENV_FILENAME = '.env';\n\n/**\n * Docker Compose `ports: !override` is an identity sequence tag. Register it\n * so generated worktree overrides load; do not implement merge/replace.\n */\nconst OVERRIDE_SEQUENCE_TAG = defineSequenceTag<unknown[]>('!override', {\n create: () => [],\n addItem: (carrier, item) => {\n // Must not return a value — js-yaml treats a truthy addItem return as a parse error.\n carrier.push(item);\n },\n identify: () => false,\n});\n\nconst COMPOSE_OVERRIDE_SCHEMA = CORE_SCHEMA.withTags(OVERRIDE_SEQUENCE_TAG);\n\nexport type CheckoutClassification =\n | { kind: 'non-worktree'; root?: string }\n | {\n kind: 'resolved-worktree';\n root: string;\n overridePath: string;\n apiPort: number;\n frontendPort: number;\n }\n | {\n kind: 'unresolved-worktree';\n root: string;\n overridePath: string;\n reason: string;\n };\n\nexport class WorktreeConfigError extends Error {\n constructor(\n message: string,\n readonly checkoutRoot: string,\n readonly overridePath: string\n ) {\n super(message);\n this.name = 'WorktreeConfigError';\n }\n}\n\n/** A plain JSON object: not null, not an array. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction parsePortToken(token: string | undefined): number | undefined {\n if (token === undefined || !/^\\d+$/.test(token)) return undefined;\n const value = Number(token);\n if (!Number.isInteger(value) || value <= 0 || value > 65535) return undefined;\n return value;\n}\n\n/**\n * Parse `published` and `target` from the right edge of a short-form mapping.\n * The optional bind-address prefix (including `${DOCKER_BIND_IP:-...}`) stays\n * opaque — it is never interpolated.\n */\nexport function parsePublishedTarget(\n mapping: string\n): { published: number; target: number } | undefined {\n const parts = mapping.split(':');\n if (parts.length < 2) return undefined;\n const target = parsePortToken(parts[parts.length - 1]);\n const published = parsePortToken(parts[parts.length - 2]);\n if (target === undefined || published === undefined) return undefined;\n return { published, target };\n}\n\nfunction publishedPortForTarget(ports: unknown, target: number): number | undefined {\n if (!Array.isArray(ports)) return undefined;\n for (const entry of ports) {\n if (typeof entry !== 'string') continue;\n const parsed = parsePublishedTarget(entry);\n if (parsed?.target === target) return parsed.published;\n }\n return undefined;\n}\n\nfunction servicePorts(services: Record<string, unknown>, name: string): unknown {\n const service = services[name];\n if (!isRecord(service)) return undefined;\n return service['ports'];\n}\n\nfunction findNearestGit(startDir: string): { root: string; gitIsFile: boolean } | undefined {\n let dir = resolve(startDir);\n while (true) {\n const gitPath = join(dir, '.git');\n if (existsSync(gitPath)) {\n try {\n const st = statSync(gitPath);\n return { root: dir, gitIsFile: st.isFile() };\n } catch {\n // Unreadable .git entry — keep walking.\n }\n }\n const parent = dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n}\n\n/**\n * A worktree provisioned for the native runtime (`gr.runtime=native`) has no\n * Compose override: `worktree-setup.sh` writes its ports into `.env` and marks\n * it `GR_PROVISIONED_RUNTIME=native`. Read only those three keys — the file\n * also carries secrets, which are never parsed or returned.\n */\nfunction nativeWorktreePorts(\n envPath: string\n): { envPath: string; ports: { apiPort: number; frontendPort: number } } | undefined {\n let content: string;\n try {\n content = readFileSync(envPath, 'utf-8');\n } catch {\n return undefined;\n }\n const wanted = new Set(['GR_PROVISIONED_RUNTIME', 'API_NGINX_PORT', 'FRONTEND_PORT']);\n const values = new Map<string, string>();\n for (const line of content.split(/\\r?\\n/)) {\n const match = /^\\s*([A-Z_][A-Z0-9_]*)=(.*)$/.exec(line);\n const key = match?.[1];\n const raw = match?.[2];\n if (key === undefined || raw === undefined || !wanted.has(key)) continue;\n values.set(key, raw.trim().replace(/^(['\"])(.*)\\1$/, '$2'));\n }\n if (values.get('GR_PROVISIONED_RUNTIME') !== 'native') return undefined;\n const apiPort = parsePortToken(values.get('API_NGINX_PORT'));\n const frontendPort = parsePortToken(values.get('FRONTEND_PORT'));\n if (apiPort === undefined || frontendPort === undefined) return undefined;\n return { envPath, ports: { apiPort, frontendPort } };\n}\n\nfunction unresolved(\n root: string,\n overridePath: string,\n reason: string\n): Extract<CheckoutClassification, { kind: 'unresolved-worktree' }> {\n return { kind: 'unresolved-worktree', root, overridePath, reason };\n}\n\nfunction loadComposeDocument(content: string): Record<string, unknown> | undefined {\n let loaded: unknown;\n try {\n loaded = load(content, { schema: COMPOSE_OVERRIDE_SCHEMA });\n } catch {\n return undefined;\n }\n return isRecord(loaded) ? loaded : undefined;\n}\n\n/**\n * Classify the checkout rooted at (or above) `startDir`.\n *\n * A linked worktree has a `.git` *file*. A primary checkout has a `.git`\n * directory. No repository is treated as non-worktree so packaged CLI\n * invocations keep environment defaults.\n */\nexport function classifyCheckout(startDir: string = process.cwd()): CheckoutClassification {\n const git = findNearestGit(startDir);\n if (!git || !git.gitIsFile) {\n return { kind: 'non-worktree', root: git?.root };\n }\n\n const overridePath = join(git.root, OVERRIDE_FILENAME);\n // git.root is the checkout found by walking up from cwd to `.git` (as for\n // overridePath above) and the filename is a constant: no caller-supplied path.\n // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal\n const envPath = join(git.root, ENV_FILENAME);\n if (!existsSync(overridePath)) {\n const native = nativeWorktreePorts(envPath);\n if (native) {\n return {\n kind: 'resolved-worktree',\n root: git.root,\n overridePath: native.envPath,\n ...native.ports,\n };\n }\n return unresolved(\n git.root,\n overridePath,\n `docker-compose.override.yml (generated by ${WORKTREE_SETUP_MARKER})`\n );\n }\n\n let content: string;\n try {\n content = readFileSync(overridePath, 'utf-8');\n } catch {\n return unresolved(git.root, overridePath, 'readable generated worktree override');\n }\n\n if (!content.includes(WORKTREE_SETUP_MARKER)) {\n return unresolved(\n git.root,\n overridePath,\n `generated ${WORKTREE_SETUP_MARKER} override marker`\n );\n }\n\n const document = loadComposeDocument(content);\n if (!document) {\n return unresolved(git.root, overridePath, 'valid generated worktree override YAML');\n }\n\n const services = document['services'];\n if (!isRecord(services)) {\n return unresolved(\n git.root,\n overridePath,\n `api-nginx published port for container ${API_CONTAINER_PORT}; frontend published port for container ${FRONTEND_CONTAINER_PORT}`\n );\n }\n\n const apiPort = publishedPortForTarget(servicePorts(services, 'api-nginx'), API_CONTAINER_PORT);\n const frontendPort = publishedPortForTarget(\n servicePorts(services, 'frontend'),\n FRONTEND_CONTAINER_PORT\n );\n const missing: string[] = [];\n if (apiPort === undefined) {\n missing.push(`api-nginx published port for container ${API_CONTAINER_PORT}`);\n }\n if (frontendPort === undefined) {\n missing.push(`frontend published port for container ${FRONTEND_CONTAINER_PORT}`);\n }\n if (apiPort === undefined || frontendPort === undefined) {\n return unresolved(git.root, overridePath, missing.join('; '));\n }\n\n return {\n kind: 'resolved-worktree',\n root: git.root,\n overridePath,\n apiPort,\n frontendPort,\n };\n}\n\nfunction worktreeFailClosed(\n checkout: Extract<CheckoutClassification, { kind: 'unresolved-worktree' }>,\n missingFields: string[]\n): never {\n throw new WorktreeConfigError(\n `Cannot resolve ${missingFields.join(' and ')} URL(s) for this linked worktree.\\n` +\n `Checkout: ${checkout.root}\\n` +\n `Override: ${checkout.overridePath}\\n` +\n `Missing: ${checkout.reason}\\n` +\n `Re-run scripts/worktree-setup.sh . from this checkout, or pass explicit ` +\n `--api-url and GRAVITY_RAIL_FRONTEND_URL (or both GRAVITY_RAIL_API_URL and ` +\n `GRAVITY_RAIL_FRONTEND_URL) so neither URL inherits the primary checkout.`,\n checkout.root,\n checkout.overridePath\n );\n}\n\nfunction worktreeDevUrls(apiPort: number, frontendPort: number): EnvironmentConfig {\n return {\n apiUrl: `https://api.gravityrail.test:${apiPort}`,\n frontendUrl: `https://app.gravityrail.test:${frontendPort}`,\n };\n}\n\nexport function getEnvironmentConfig(\n env: string,\n options: EnvironmentConfigOptions = {}\n): EnvironmentConfig {\n // Handle dev-cloud environments: --env dev-cloud:NAMESPACE\n if (env.startsWith('dev-cloud:')) {\n const namespace = env.slice('dev-cloud:'.length);\n if (!namespace) {\n throw new Error('dev-cloud environment requires a namespace: --env dev-cloud:NAMESPACE');\n }\n return {\n apiUrl:\n options.apiUrl ||\n process.env.GRAVITY_RAIL_API_URL ||\n `https://${namespace}-api.gravityrail-dev.com`,\n frontendUrl:\n options.frontendUrl ||\n process.env.GRAVITY_RAIL_FRONTEND_URL ||\n `https://${namespace}-app.gravityrail-dev.com`,\n };\n }\n\n const config = ENVIRONMENTS[env];\n if (!config) {\n throw new Error(\n `Invalid environment: ${env}. Use 'dev', 'staging', 'prod', or 'dev-cloud:NAMESPACE'.`\n );\n }\n\n const explicitApi = options.apiUrl || process.env.GRAVITY_RAIL_API_URL;\n const explicitFrontend = options.frontendUrl || process.env.GRAVITY_RAIL_FRONTEND_URL;\n\n if (env !== 'dev') {\n return {\n apiUrl: explicitApi || config.apiUrl,\n frontendUrl: explicitFrontend || config.frontendUrl,\n };\n }\n\n // Inside a dev-cloud pod (its chart sets ENVIRONMENT=dev-cloud) the stack\n // runs natively, with no gravityrail.test proxy: the API is on :5050 and the\n // frontend on :3000. `gr auth import-dev` there imports the pod's own\n // dev-realms.json into the dev store, so `--env dev` reaches that API.\n if (process.env.ENVIRONMENT === 'dev-cloud') {\n return {\n apiUrl: explicitApi || DEV_CLOUD_POD_DEV.apiUrl,\n frontendUrl: explicitFrontend || DEV_CLOUD_POD_DEV.frontendUrl,\n };\n }\n\n const checkout = classifyCheckout(options.startDir ?? process.cwd());\n\n if (checkout.kind === 'non-worktree') {\n return {\n apiUrl: explicitApi || config.apiUrl,\n frontendUrl: explicitFrontend || config.frontendUrl,\n };\n }\n\n if (checkout.kind === 'resolved-worktree') {\n const detected = worktreeDevUrls(checkout.apiPort, checkout.frontendPort);\n return {\n apiUrl: explicitApi || detected.apiUrl,\n frontendUrl: explicitFrontend || detected.frontendUrl,\n };\n }\n\n const missingFields: string[] = [];\n if (!explicitApi) missingFields.push('API');\n if (!explicitFrontend) missingFields.push('frontend');\n if (missingFields.length > 0) {\n worktreeFailClosed(checkout, missingFields);\n }\n return { apiUrl: explicitApi!, frontendUrl: explicitFrontend! };\n}\n","/**\n * CLI OAuth2 authentication utilities\n *\n * Provides OAuth2 with PKCE flow for CLI tools, including:\n * - Credential caching (per environment + named profile)\n * - Dynamic client registration\n * - Token refresh\n * - Browser-based authorization\n *\n * Credential persistence lives in `./credentials-manager` (multi-account profiles).\n */\n\nimport { createServer } from 'http';\nimport { createHash, randomBytes } from 'crypto';\nimport { exec } from 'child_process';\nimport { existsSync, mkdirSync } from 'fs';\nimport { dirname } from 'path';\nimport lockfile from 'proper-lockfile';\nimport pkg from '../../package.json';\nimport { EnvironmentConfig, CALLBACK_PORT, CALLBACK_PATH, REDIRECT_URI } from './config';\nimport { CredentialsManager, type CLICredentials } from './credentials-manager';\n\nexport {\n CredentialsManager,\n DEFAULT_PROFILE,\n type CLICredentials,\n type ProfileSummary,\n} from './credentials-manager';\n\nexport interface AuthResult {\n accessToken: string;\n credentials?: CLICredentials;\n}\n\nexport interface NonInteractiveAuthOptions {\n env: string;\n envConfig: EnvironmentConfig;\n credentialsManager: CredentialsManager;\n profile?: string;\n}\n\nconst ACCESS_TOKEN_EXPIRY_BUFFER_MS = 5 * 60 * 1000;\n\n/**\n * Sent on every token grant so reuse investigations can tell CLI releases\n * apart. Self-reported identification, not authentication.\n */\nconst TOKEN_REQUEST_USER_AGENT = `gravityrail-cli/${pkg.version}`;\n\n/** The one timeout on a refresh: the token POST, including reading its body. */\nconst REFRESH_REQUEST_TIMEOUT_MS = 15_000;\n\n/**\n * How long a refresh waits for another process's refresh of the same\n * credential file: 100, 200, 400 and 800 ms, then 1 s per retry — about 20.5 s\n * over 23 retries. That outlasts one whole refresh by the lock holder (bounded\n * by `REFRESH_REQUEST_TIMEOUT_MS`), so a waiter adopts the winner's result\n * instead of giving up. The library keeps a held lock fresh and reclaims one\n * abandoned by a crashed process, so its `stale`/`update` defaults are kept.\n */\nconst REFRESH_LOCK_RETRIES = { retries: 23, factor: 2, minTimeout: 100, maxTimeout: 1000 };\n\n// Refresh failures that are not a verdict on the stored token. Fixed strings\n// by design: never interpolate tokens, response bodies or transport errors.\nconst REFRESH_LOCK_FAILED =\n 'Could not lock the credential store to refresh the access token (another gr process may still be refreshing). Stored credentials were kept; retry the command.';\nconst REFRESH_REQUEST_FAILED =\n 'Token refresh did not complete (network error or timeout). Stored credentials were kept; retry the command.';\nconst REFRESH_FAILED =\n 'Token refresh failed. Stored credentials were kept; retry the command, and log in again if it keeps failing.';\nconst REFRESH_SUPERSEDED =\n 'Token refresh was rejected, but the stored credentials changed meanwhile and were kept. Retry the command.';\nconst REFRESH_BAD_RESPONSE =\n 'Token refresh returned an unusable response. Stored credentials were kept; retry the command.';\nconst REFRESH_SAVE_FAILED =\n 'Token refresh succeeded, but the new credentials could not be saved. Retry the command, and log in again if it keeps failing.';\n\nfunction stderr(msg: string): void {\n process.stderr.write(msg + '\\n');\n}\n\n/**\n * Parse an OAuth error response body, checking the JSON `error` field first,\n * falling back to text matching.\n */\nfunction isOAuthError(body: string, errorCode: string): boolean {\n try {\n const parsed = JSON.parse(body);\n if (parsed.error === errorCode) return true;\n } catch {\n // Not JSON — fall through to text match\n }\n return body.includes(errorCode);\n}\n\n/**\n * Validate and extract fields from an OAuth token response.\n * Throws on malformed responses per RFC 6749 §5.1.\n */\nfunction validateTokenResponse(tokenData: Record<string, unknown>): {\n accessToken: string;\n refreshToken?: string;\n expiresIn: number;\n} {\n if (!tokenData.access_token || typeof tokenData.access_token !== 'string') {\n throw new Error('Token response missing access_token');\n }\n\n if (tokenData.token_type && String(tokenData.token_type).toLowerCase() !== 'bearer') {\n throw new Error(`Unsupported token type: ${tokenData.token_type}`);\n }\n\n let expiresIn = 86400; // default 24h\n if (tokenData.expires_in != null) {\n const raw = Number(tokenData.expires_in);\n if (!Number.isFinite(raw) || raw < 60 || raw > 31536000) {\n stderr(' Warning: unusual expires_in value in the token response, using default');\n } else {\n expiresIn = raw;\n }\n }\n\n return {\n accessToken: tokenData.access_token,\n refreshToken:\n typeof tokenData.refresh_token === 'string' ? tokenData.refresh_token : undefined,\n expiresIn,\n };\n}\n\n/**\n * Generate PKCE code verifier and challenge\n */\nexport function generatePKCE(): { codeVerifier: string; codeChallenge: string } {\n const codeVerifier = randomBytes(64).toString('base64url').slice(0, 128);\n const codeChallenge = createHash('sha256').update(codeVerifier).digest('base64url');\n return { codeVerifier, codeChallenge };\n}\n\n/**\n * Open a URL in the default browser\n */\nexport function openBrowser(url: string): void {\n const platform = process.platform;\n let cmd: string;\n if (platform === 'darwin') {\n cmd = `open \"${url}\"`;\n } else if (platform === 'win32') {\n cmd = `start \"\" \"${url}\"`;\n } else {\n cmd = `xdg-open \"${url}\"`;\n }\n\n exec(cmd, (err) => {\n if (err) {\n stderr(' Could not open browser automatically.');\n }\n });\n}\n\n/**\n * Start a local HTTP server to receive the OAuth callback\n */\nexport function startCallbackServer(): Promise<{ code: string; state: string }> {\n return new Promise((resolve, reject) => {\n let authCode: string | null = null;\n let error: string | null = null;\n let receivedState: string | null = null;\n\n const server = createServer((req, res) => {\n const url = new URL(req.url!, `http://localhost:${CALLBACK_PORT}`);\n\n if (url.pathname !== CALLBACK_PATH) {\n res.writeHead(404);\n res.end('Not found');\n return;\n }\n\n if (url.searchParams.has('error')) {\n error = url.searchParams.get('error');\n const errorDesc = url.searchParams.get('error_description') || 'Unknown error';\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(`\n <html>\n <head><title>Authorization Failed</title></head>\n <body style=\"font-family: system-ui; text-align: center; padding: 50px;\">\n <h1 style=\"color: #dc2626;\">Authorization Failed</h1>\n <p>${errorDesc}</p>\n <p>You can close this window.</p>\n </body>\n </html>\n `);\n server.close();\n reject(new Error(`Authorization failed: ${error}`));\n } else if (url.searchParams.has('code')) {\n authCode = url.searchParams.get('code')!;\n receivedState = url.searchParams.get('state')!;\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(`\n <html>\n <head><title>Authorization Successful</title></head>\n <body style=\"font-family: system-ui; text-align: center; padding: 50px;\">\n <h1 style=\"color: #16a34a;\">Authorization Successful!</h1>\n <p>You can close this window and return to the terminal.</p>\n <script>setTimeout(() => window.close(), 2000);</script>\n </body>\n </html>\n `);\n server.close();\n resolve({ code: authCode, state: receivedState });\n } else {\n res.writeHead(400);\n res.end('Missing code parameter');\n }\n });\n\n server.listen(CALLBACK_PORT, 'localhost', () => {\n // Server started\n });\n\n // Timeout after 5 minutes (unref so it doesn't keep the process alive)\n const timeout = setTimeout(\n () => {\n if (!authCode && !error) {\n server.close();\n reject(new Error('Authorization timeout - no response received'));\n }\n },\n 5 * 60 * 1000\n );\n timeout.unref();\n });\n}\n\n/**\n * Vendor field in the RFC 8414 discovery document naming the server's pinned\n * first-party CLI client. Must match `FIRST_PARTY_CLIENT_METADATA_FIELD` in\n * `lib/routes/oauth/first_party.py`.\n */\nexport const FIRST_PARTY_CLIENT_METADATA_FIELD = 'gravityrail_first_party_cli_client_id';\n\n/**\n * Ask the server for its pinned first-party CLI client id, or null if it has none.\n *\n * Null is the dynamic-registration fallback trigger, and it has to cover two\n * different situations that the CLI cannot and need not tell apart: a server\n * deployed before the pinned client shipped, and a discovery request that\n * failed. Both mean \"we have no pinned identity to use here\", and DCR is the\n * correct answer to both — so every failure mode collapses to null rather than\n * throwing and taking down a login that would otherwise have worked.\n */\nexport async function fetchFirstPartyClientId(\n envConfig: EnvironmentConfig\n): Promise<string | null> {\n try {\n const response = await fetch(`${envConfig.apiUrl}/.well-known/oauth-authorization-server`, {\n headers: { Accept: 'application/json' },\n });\n if (!response.ok) return null;\n const metadata = (await response.json()) as Record<string, unknown>;\n const clientId = metadata[FIRST_PARTY_CLIENT_METADATA_FIELD];\n return typeof clientId === 'string' && clientId.length > 0 ? clientId : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Register a new OAuth client dynamically.\n *\n * Retained for servers that predate the pinned first-party client — older\n * self-hosted and dev deployments — not as the normal path. See\n * `resolveOAuthClient`.\n */\nasync function dynamicClientRegistration(\n envConfig: EnvironmentConfig,\n clientName: string = 'Gravity CLI'\n): Promise<{ client_id: string; client_secret: string }> {\n stderr(' Registering OAuth client...');\n\n const registrationUrl = `${envConfig.apiUrl}/api/v2/oauth/register`;\n\n const registrationData = {\n client_name: clientName,\n redirect_uris: [REDIRECT_URI],\n grant_types: ['authorization_code', 'refresh_token'],\n response_types: ['code'],\n token_endpoint_auth_method: 'client_secret_basic',\n scope: 'workspace:admin',\n };\n\n const response = await fetch(registrationUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(registrationData),\n });\n\n if (!response.ok) {\n throw new Error(`Client registration failed: ${response.status} - ${await response.text()}`);\n }\n\n return (await response.json()) as { client_id: string; client_secret: string };\n}\n\n/**\n * Build the client-authentication half of a token request.\n *\n * A confidential client (one we registered dynamically, which issued us a\n * secret) authenticates with HTTP Basic. The pinned first-party client has no\n * secret and identifies itself with a body `client_id` instead — RFC 6749\n * §2.3.1, and RFC 8252 §8.5 for why a CLI cannot hold one in the first place.\n * The server accepts either and reads the id from the header first.\n */\nfunction tokenRequestAuth(\n clientId: string,\n clientSecret?: string\n): { headers: Record<string, string>; params: Record<string, string> } {\n if (clientSecret) {\n const authHeader = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');\n return {\n headers: { Authorization: `Basic ${authHeader}` },\n params: {},\n };\n }\n return { headers: {}, params: { client_id: clientId } };\n}\n\n/**\n * Decide which OAuth client this login should use.\n *\n * The pinned first-party client wins whenever the server has one, including\n * for profiles that were created by an older CLI against the same server —\n * that is what retires per-login dynamic registration rather than merely\n * stopping new profiles from using it. Swapping is safe precisely here and\n * nowhere else: `performOAuthFlow` mints a fresh token pair anyway, so nothing\n * bound to the old client survives the call. Profiles that are never logged in\n * again keep refreshing against their old client untouched.\n *\n * `forceDynamicRegistration` is the retry path: the server has just answered\n * `invalid_client` for whichever client the branches below chose, so it must\n * skip **both** of the reuse branches, not only discovery. Skipping discovery\n * alone would fall through to the cached branch and hand back the very client\n * that was rejected — and when the rejected client *was* the cached one, that\n * is an identical second attempt. \"Register a fresh client\" is the only\n * response that can differ from the attempt that just failed.\n *\n * Exported so the three branches can be tested directly — `performOAuthFlow`\n * around it opens a browser and binds a loopback port, which no unit test\n * should have to stand up to assert which client was chosen.\n */\nexport async function resolveOAuthClient(\n envConfig: EnvironmentConfig,\n stored: CLICredentials | null,\n clientName: string = 'Gravity CLI',\n forceDynamicRegistration: boolean = false\n): Promise<{ clientId: string; clientSecret?: string }> {\n if (!forceDynamicRegistration) {\n const pinned = await fetchFirstPartyClientId(envConfig);\n if (pinned) {\n stderr(' Using the first-party CLI client');\n return { clientId: pinned };\n }\n\n // No pinned client on this server. Reuse whatever this profile\n // registered before, so an older environment does not accumulate a\n // client per login.\n if (stored?.clientId && stored.clientSecret) {\n stderr(' Using cached client credentials');\n return { clientId: stored.clientId, clientSecret: stored.clientSecret };\n }\n }\n\n const registration = await dynamicClientRegistration(envConfig, clientName);\n return { clientId: registration.client_id, clientSecret: registration.client_secret };\n}\n\nexport interface OAuthFlowOptions {\n env: string;\n envConfig: EnvironmentConfig;\n credentialsManager: CredentialsManager;\n clientName?: string;\n /** Named account profile to store tokens under (default: resolved current). */\n profile?: string;\n /**\n * Test seam: wait for the loopback callback. Defaults to the real server.\n *\n * The two side effects below are the reason this function had no direct\n * tests — one shells out to the system browser and the other binds a fixed\n * port, neither of which a unit test may do. Injecting them is what lets\n * the \"a failed login must not touch the stored profile\" invariant be\n * tested at all. Production never passes either.\n */\n startCallback?: () => Promise<{ code: string; state: string }>;\n /** Test seam: open the authorization URL. Defaults to the real browser. */\n openAuthUrl?: (url: string) => void;\n}\n\n/**\n * Perform the full OAuth2 browser-based flow with PKCE.\n *\n * This always opens the browser for authorization. It never returns a cached\n * token — that's the job of createAuthenticatedContext. The only thing reused\n * is the registered OAuth client ID (which is identity, not auth).\n *\n * **Nothing is written to the credential store until the token exchange has\n * succeeded.** A login can end at the consent screen the member cancels, at a\n * network failure, or at the five-minute callback timeout, and every one of\n * those must leave the profile exactly as it was — see the comment on the\n * single `save` below for what persisting early actually broke.\n */\nexport async function performOAuthFlow(options: OAuthFlowOptions): Promise<AuthResult> {\n const {\n env,\n envConfig,\n credentialsManager,\n clientName = 'Gravity CLI',\n profile,\n startCallback = startCallbackServer,\n openAuthUrl = openBrowser,\n } = options;\n const profileName = credentialsManager.resolveProfileName(profile, env);\n let hasRetried = false;\n let forceDynamicRegistration = false;\n\n while (true) {\n const stored = credentialsManager.load(env, profileName);\n const { clientId, clientSecret } = await resolveOAuthClient(\n envConfig,\n stored,\n clientName,\n forceDynamicRegistration\n );\n\n const { codeVerifier, codeChallenge } = generatePKCE();\n const state = randomBytes(32).toString('base64url');\n\n const authParams = new URLSearchParams({\n response_type: 'code',\n client_id: clientId,\n redirect_uri: REDIRECT_URI,\n scope: 'workspace:admin',\n state: state,\n code_challenge: codeChallenge,\n code_challenge_method: 'S256',\n });\n\n const authUrl = `${envConfig.apiUrl}/api/v2/oauth/authorize?${authParams}`;\n\n const callbackPromise = startCallback();\n\n stderr('\\n Opening browser for authorization...');\n stderr(` Profile: ${profileName}`);\n stderr(` If browser doesn't open, visit:\\n ${authUrl}\\n`);\n openAuthUrl(authUrl);\n\n stderr(' Waiting for authorization (timeout: 5 minutes)...');\n let code: string;\n let receivedState: string;\n try {\n ({ code, state: receivedState } = await callbackPromise);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (!hasRetried && isOAuthError(msg, 'invalid_client')) {\n stderr(' Client rejected by the server, re-registering...');\n hasRetried = true;\n // The rejected client was only ever held in memory, so there is\n // nothing on disk to clean up — `forceDynamicRegistration` alone\n // is what makes the next pass register a fresh one.\n forceDynamicRegistration = true;\n continue;\n }\n throw err;\n }\n\n if (receivedState !== state) {\n throw new Error('State mismatch - possible CSRF attack');\n }\n\n stderr(' Authorization code received!');\n stderr(' Exchanging code for tokens...');\n\n const tokenUrl = `${envConfig.apiUrl}/api/v2/oauth/token`;\n const auth = tokenRequestAuth(clientId, clientSecret);\n\n const tokenResponse = await fetch(tokenUrl, {\n method: 'POST',\n headers: {\n ...auth.headers,\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'User-Agent': TOKEN_REQUEST_USER_AGENT,\n },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n code: code,\n redirect_uri: REDIRECT_URI,\n code_verifier: codeVerifier,\n ...auth.params,\n }),\n });\n\n if (!tokenResponse.ok) {\n const body = await tokenResponse.text();\n if (!hasRetried && isOAuthError(body, 'invalid_client')) {\n stderr(' Client rejected by the server, re-registering...');\n hasRetried = true;\n forceDynamicRegistration = true;\n continue;\n }\n throw new Error(`Token exchange failed: ${tokenResponse.status} - ${body}`);\n }\n\n const tokenData = (await tokenResponse.json()) as Record<string, unknown>;\n const { accessToken, refreshToken, expiresIn } = validateTokenResponse(tokenData);\n\n // The one and only write, and it happens after the exchange has already\n // succeeded. Persisting the client identity before the browser step used\n // to leave a cancelled, failed or timed-out login with the NEW client id\n // sitting next to the OLD tokens — and the refresh grant looks a token\n // up by `refresh_token AND app_id` (`lib/routes/oauth/oauth_token.py`),\n // so that pairing matches no row and the next refresh is a guaranteed\n // `invalid_grant`. A member who simply closed the consent tab lost the\n // session they already had.\n //\n // A refresh token is only carried over when the client identity is\n // unchanged, for the same reason: one minted for the previous client is\n // not merely useless under the new one, it is actively harmful, because\n // the server answers it with `invalid_grant` and `refreshAccessToken`\n // clears the profile on that definitive rejection.\n // Dropping it degrades to \"log in again\", which is the honest outcome.\n //\n // `clientSecret` is written unconditionally, and when it is `undefined`\n // that is load-bearing rather than a no-op: the spread has just copied a\n // stale DCR secret out of `stored`, and this key overwrites it with\n // `undefined`, which `JSON.stringify` then omits entirely from the\n // persisted store. Both halves matter — in memory `tokenRequestAuth`\n // reads `undefined` and takes the body-`client_id` path, and on disk the\n // secret is gone rather than lying in wait for the next load. Dropping\n // this key \"because undefined does nothing\" would put the pinned public\n // client back on the Basic-auth path with a secret it does not have.\n //\n // Everything else on the profile (pinned workspace, cached org sessions)\n // is preserved — only the client identity and the tokens are decided\n // here, and org sessions are keyed to the account, not the client.\n const clientChanged = stored?.clientId !== clientId;\n const creds: CLICredentials = {\n ...(stored ?? {}),\n clientId,\n clientSecret,\n accessToken,\n refreshToken: refreshToken ?? (clientChanged ? undefined : stored?.refreshToken),\n expiresAt: new Date(Date.now() + expiresIn * 1000).toISOString(),\n };\n\n credentialsManager.save(env, creds, profileName);\n credentialsManager.setCurrentProfile(env, profileName);\n stderr(' Authentication successful!');\n\n return { accessToken, credentials: creds };\n }\n}\n\n/**\n * The `error` code of a JSON OAuth error body, or undefined when the body is\n * not one.\n *\n * Unlike `isOAuthError` there is no substring fallback: this decides whether a\n * profile is deleted, and only a structured server verdict may do that.\n */\nfunction parseOAuthErrorCode(body: string): string | undefined {\n try {\n const parsed: unknown = JSON.parse(body);\n if (parsed && typeof parsed === 'object') {\n const code = (parsed as { error?: unknown }).error;\n if (typeof code === 'string') return code;\n }\n } catch {\n // Not JSON — no verdict.\n }\n return undefined;\n}\n\n/**\n * Whether the stored access token has enough life left to run a command on.\n *\n * The same `ACCESS_TOKEN_EXPIRY_BUFFER_MS` horizon the resolver uses, so a\n * single process that entered the refresh with a few minutes left still\n * rotates instead of adopting a token that may expire mid-command. A waiter\n * still adopts the winner's successor without rotating it again: the server\n * mints access tokens for far longer than the buffer (24 h, `oauth_token.py`),\n * so a successor another process just stored always clears this check. A token\n * with no recorded expiry is usable, as everywhere else.\n */\nfunction isFreshEnough(creds: CLICredentials): boolean {\n return (\n !creds.expiresAt ||\n new Date(creds.expiresAt).getTime() > Date.now() + ACCESS_TOKEN_EXPIRY_BUFFER_MS\n );\n}\n\n/**\n * Take the cross-process refresh lock for one credential file.\n *\n * The target is the credential file's own path, so every refresh that shares\n * an environment (and API port) file serializes, whichever profile it is for.\n * The file need not exist: the library locks with a sibling `<path>.lock`\n * directory and `realpath: false` skips resolving the target.\n */\nasync function acquireRefreshLock(credentialsPath: string): Promise<() => Promise<void>> {\n try {\n const cacheDir = dirname(credentialsPath);\n if (!existsSync(cacheDir)) {\n mkdirSync(cacheDir, { recursive: true, mode: 0o700 });\n }\n return await lockfile.lock(credentialsPath, {\n realpath: false,\n retries: REFRESH_LOCK_RETRIES,\n // The library default throws from a timer, which would crash the\n // command. Losing the lock mid-refresh is worth a warning, not that.\n // The library has already dropped its in-process record of the lock\n // by the time this runs, so the `release()` in `refreshAccessToken`'s\n // `finally` is refused (ENOTACQUIRED) and can never remove a lock\n // another process has since taken.\n onCompromised: () => {\n stderr(\n ' Warning: lost the credential refresh lock; another gr process may refresh at the same time'\n );\n },\n });\n } catch {\n // Never fall back to an unlocked refresh: that is exactly the race this\n // lock exists to prevent.\n throw new Error(REFRESH_LOCK_FAILED);\n }\n}\n\n/**\n * Refresh the selected profile's access token, coordinating with other `gr`\n * processes on this machine (GitHub #29807).\n *\n * The server rotates refresh tokens and rejects a spent one as reuse, so two\n * processes presenting the same token race: one wins, the other gets\n * `invalid_grant`. Everything from reading the stored token to saving its\n * successor therefore runs under one lock on the credential file. A process\n * that waited re-reads the store and adopts what the winner saved instead of\n * presenting the spent token.\n *\n * `creds` is the caller's pre-lock snapshot and is deliberately not consulted:\n * every decision — whether a refresh is needed, which token to present, what\n * to save — is made from the profile read under the lock, because the snapshot\n * may already have been rotated away, logged out, or replaced by a login. The\n * parameter stays for the exported signature.\n *\n * Returns the profile's usable credentials, or null when the profile cannot\n * authenticate — including after a definitive rejection, which clears that\n * profile only. Any other failure (network, timeout, server error, malformed\n * response, a busy lock, a failed save) leaves the store untouched and throws a\n * plain Error whose message is fixed: no token, response body, or transport\n * detail ever reaches it.\n */\nexport async function refreshAccessToken(\n envConfig: EnvironmentConfig,\n _creds: CLICredentials,\n credentialsManager: CredentialsManager,\n env: string,\n profile?: string\n): Promise<CLICredentials | null> {\n // Resolved once, before waiting, so a `gr auth switch` in another process\n // cannot redirect this command to a different profile mid-refresh.\n const profileName = credentialsManager.resolveProfileName(profile, env);\n const release = await acquireRefreshLock(credentialsManager.getCredentialsFilePath(env));\n try {\n return await refreshUnderLock(envConfig, credentialsManager, env, profileName);\n } finally {\n // Rejects only when the lock was already lost (see `onCompromised`);\n // there is nothing left to release then.\n await release().catch(() => undefined);\n }\n}\n\nasync function refreshUnderLock(\n envConfig: EnvironmentConfig,\n credentialsManager: CredentialsManager,\n env: string,\n profileName: string\n): Promise<CLICredentials | null> {\n const stored = credentialsManager.load(env, profileName);\n\n // Another process may have refreshed while this one waited for the lock.\n if (stored?.accessToken && isFreshEnough(stored)) {\n return stored;\n }\n // A client secret is no longer part of the requirement: the pinned\n // first-party client is public and has none, and demanding one here would\n // silently strand every profile logged in with it — `context.ts` treats a\n // null return as \"re-login required\", so the CLI would open a browser on\n // every command instead of refreshing.\n if (!stored?.refreshToken || !stored.clientId) {\n stderr(' Cannot refresh: missing credentials (re-login required)');\n return null;\n }\n\n const presentedRefreshToken = stored.refreshToken;\n const auth = tokenRequestAuth(stored.clientId, stored.clientSecret);\n\n let response: Response;\n try {\n response = await fetch(`${envConfig.apiUrl}/api/v2/oauth/token`, {\n method: 'POST',\n headers: {\n ...auth.headers,\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'User-Agent': TOKEN_REQUEST_USER_AGENT,\n },\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: presentedRefreshToken,\n ...auth.params,\n }),\n // Bounds the request and the body reads below. Never retried: a\n // second POST of the same token is itself a reuse.\n //\n // Known residual: an abort only stops *this* side. If the server\n // commits the rotation after the deadline, the response carrying the\n // successor is lost and the stored token is spent; the next refresh\n // of it is a genuine invalid_grant and clears the profile. The client\n // cannot recover an unseen successor; the deadline is long enough\n // that this needs a token endpoint stalled for 15 s, not a slow one.\n signal: AbortSignal.timeout(REFRESH_REQUEST_TIMEOUT_MS),\n });\n } catch {\n throw new Error(REFRESH_REQUEST_FAILED);\n }\n\n if (!response.ok) {\n let body: string;\n try {\n body = await response.text();\n } catch {\n throw new Error(REFRESH_REQUEST_FAILED);\n }\n if (response.status === 400 && parseOAuthErrorCode(body) === 'invalid_grant') {\n // The verdict is about the token presented, not whatever the store\n // holds now. Clear only if that same token is still stored, so a\n // stale rejection can never delete a replacement saved meanwhile.\n const current = credentialsManager.load(env, profileName);\n if (!current) {\n stderr(' The server rejected the stored refresh token; re-login required');\n return null;\n }\n // Two local values from the user's own credential file; no remote\n // party can observe this comparison's timing. FP (CWE-208).\n // bearer:disable javascript_lang_observable_timing\n if (current.refreshToken === presentedRefreshToken) {\n credentialsManager.clear(env, profileName);\n stderr(' The server rejected the stored refresh token; re-login required');\n return null;\n }\n throw new Error(REFRESH_SUPERSEDED);\n }\n if (parseOAuthErrorCode(body) === 'invalid_client') {\n // The OAuth client this profile was issued under no longer exists\n // (`lib/routes/oauth/oauth_token.py` answers 401 invalid_client).\n // Nothing in the profile can authenticate again, so surface the\n // existing re-login path — but it is a verdict on the client, not\n // on the stored tokens, so leave the profile for `gr login` to\n // replace rather than deleting it here.\n stderr(\" The server no longer recognises this profile's OAuth client; re-login required\");\n return null;\n }\n throw new Error(REFRESH_FAILED);\n }\n\n let tokens: ReturnType<typeof validateTokenResponse>;\n try {\n tokens = validateTokenResponse((await response.json()) as Record<string, unknown>);\n } catch {\n throw new Error(REFRESH_BAD_RESPONSE);\n }\n\n // Merge into a fresh read so profile metadata (pinned workspace, cached\n // org sessions) written while the request was in flight survives. Login\n // and logout take no refresh lock, so the profile may also be gone or be\n // a different grant by now; the successor belongs to the grant that was\n // presented and must not be written over either.\n const latest = credentialsManager.load(env, profileName);\n if (!latest) {\n // Logged out while the request was in flight. The successor dies with\n // the grant it belongs to; resurrecting the profile would undo the logout.\n stderr(' Cannot refresh: missing credentials (re-login required)');\n return null;\n }\n // Two local values from the user's own credential file; no remote party\n // can observe this comparison's timing. FP (CWE-208).\n // bearer:disable javascript_lang_observable_timing\n if (latest.clientId !== stored.clientId || latest.refreshToken !== presentedRefreshToken) {\n // A login replaced the profile. Its tokens are a different grant (the\n // server keys them by refresh_token AND client), so writing this\n // successor over them would make the new login's next refresh an\n // invalid_grant. Use the login if it can authenticate; otherwise this\n // refresh has nothing valid to offer.\n if (latest.accessToken && isFreshEnough(latest)) {\n return latest;\n }\n throw new Error(REFRESH_SUPERSEDED);\n }\n\n const updated: CLICredentials = {\n ...latest,\n accessToken: tokens.accessToken,\n // A server may omit `refresh_token` when it does not rotate; the\n // presented token then stays valid.\n refreshToken: tokens.refreshToken ?? presentedRefreshToken,\n expiresAt: new Date(Date.now() + tokens.expiresIn * 1000).toISOString(),\n };\n try {\n credentialsManager.save(env, updated, profileName);\n } catch {\n throw new Error(REFRESH_SAVE_FAILED);\n }\n return updated;\n}\n\n/**\n * Resolve credentials that do not require a browser.\n *\n * Precedence: process API key, then the selected profile's valid access token,\n * then that profile's refresh token. A null result leaves the caller to decide\n * whether interactive OAuth is appropriate for its command.\n */\nexport async function resolveNonInteractiveAuth(\n options: NonInteractiveAuthOptions\n): Promise<AuthResult | null> {\n const { env, envConfig, credentialsManager, profile } = options;\n\n // Process env only — API keys are never persisted in the credential store.\n const apiKey = process.env.GRAVITY_RAIL_API_KEY;\n if (apiKey) {\n return { accessToken: apiKey };\n }\n\n const profileName = credentialsManager.resolveProfileName(profile, env);\n const credentials = credentialsManager.load(env, profileName);\n if (!credentials?.accessToken) return null;\n\n const notExpired =\n !credentials.expiresAt ||\n new Date(credentials.expiresAt) > new Date(Date.now() + ACCESS_TOKEN_EXPIRY_BUFFER_MS);\n if (notExpired) {\n return { accessToken: credentials.accessToken, credentials };\n }\n\n const refreshed = await refreshAccessToken(\n envConfig,\n credentials,\n credentialsManager,\n env,\n profileName\n );\n if (!refreshed?.accessToken) return null;\n\n return { accessToken: refreshed.accessToken, credentials: refreshed };\n}\n","{\n \"name\": \"@gravity-rail/cli\",\n \"version\": \"6.0.0\",\n \"description\": \"Gravity Rail CLI — manage workspaces from the command line\",\n \"type\": \"module\",\n \"bin\": {\n \"gr\": \"./dist/gr.js\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/lib.d.ts\",\n \"import\": \"./dist/lib.js\"\n },\n \"./lib\": {\n \"types\": \"./dist/lib.d.ts\",\n \"import\": \"./dist/lib.js\"\n },\n \"./cli-utils\": {\n \"types\": \"./dist/cli-utils.d.ts\",\n \"import\": \"./dist/cli-utils.js\"\n }\n },\n \"files\": [\n \"dist\"\n ],\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/Gravity-Rail/gravity-team.git\",\n \"directory\": \"packages/cli\"\n },\n \"homepage\": \"https://developer.gravityrail.com\",\n \"keywords\": [\n \"gravity-rail\",\n \"cli\",\n \"healthcare\",\n \"workspace\"\n ],\n \"engines\": {\n \"node\": \">=18\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"generate:skill-docs\": \"tsx scripts/generate-skill-docs.ts\",\n \"clean\": \"rm -rf dist\",\n \"typecheck\": \"bash ../../scripts/tsc-admitted.sh --noEmit\",\n \"test\": \"jest --forceExit\",\n \"test:ci\": \"jest --forceExit --passWithNoTests --coverage --coverageReporters=json-summary --coverageReporters=text-summary\"\n },\n \"dependencies\": {\n \"@gravity-rail/sdk\": \"workspace:^\",\n \"js-yaml\": \"^5.5.0\",\n \"libphonenumber-js\": \"^1.13.16\",\n \"proper-lockfile\": \"^4.1.2\"\n },\n \"devDependencies\": {\n \"@gravity-rail/sandbox\": \"workspace:*\",\n \"@types/jest\": \"^30.0.0\",\n \"@types/node\": \"^26.6.6\",\n \"@types/proper-lockfile\": \"^4.1.4\",\n \"jest\": \"^30.5.2\",\n \"ts-jest\": \"29.4.9\",\n \"tsup\": \"^9.0.0\",\n \"typescript\": \"^6.0.3\",\n \"typescript-native\": \"npm:typescript@7.0.2\",\n \"undici\": \"6.29.1\"\n }\n}\n","/**\n * CLI credential store with multi-account profile support.\n *\n * Store location: `~/.gr-cli/credentials-<env>.json` (mode 0600; dir mode 0700).\n * Format is versioned JSON with named profiles (aws-style). Flat single-credential\n * files from older CLI versions migrate to profile \"default\" on first read/write.\n *\n * Security notes (for operators / security review):\n * - Tokens and client secrets live only on the local filesystem under the user's home.\n * - Files are written mode 0600; the cache directory is created mode 0700.\n * - Profile and environment names are allowlist-validated with a\n * resolve()/relative() containment check so path traversal cannot escape `.gr-cli`.\n * - Callers must never log credential field values (accessToken, refreshToken, secrets).\n * - `GRAVITY_RAIL_API_KEY` is not persisted here; it remains process-env only and\n * overrides stored profiles for non-interactive automation.\n * - Dev profiles imported from `dev-realms.json` store bearer tokens only (no OAuth\n * client secret). They are local-dev conveniences and must never be committed.\n */\n\nimport {\n readFileSync,\n writeFileSync,\n existsSync,\n mkdirSync,\n chmodSync,\n unlinkSync,\n renameSync,\n} from 'fs';\nimport { join, resolve, relative, isAbsolute } from 'path';\nimport { isOrgSessionCredential } from '../lib/org-session';\n\nexport const DEFAULT_PROFILE = 'default';\n\n/** `URL.hostname` spellings of the local machine (IPv6 keeps its brackets). */\nconst LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '[::1]']);\n\n/**\n * Stored credentials for one named profile.\n *\n * OAuth logins have a clientId (+ optional refresh). `clientSecret` is present\n * only for a dynamically registered confidential client; profiles using the\n * pinned first-party public client have none, by design (GRA-7843).\n * Dev profiles imported from dev-realms.json are token-only (accessToken +\n * optional workspaceUuid) — no OAuth client registration.\n */\n/**\n * A cached org-scoped SSO session (`gr_sess_...`) obtained via browser step-up.\n * Replayed as the `X-Org-Session` header so subsequent invocations skip the\n * browser until the session expires (GRA-6995).\n */\nexport interface StoredOrgSession {\n session: string;\n /** ISO expiry; treated as a cache miss once passed. */\n expiresAt?: string;\n}\n\nexport interface CLICredentials {\n clientId?: string;\n clientSecret?: string;\n accessToken?: string;\n refreshToken?: string;\n expiresAt?: string;\n /** Default workspace UUID (workspace/member profiles from dev-realms). */\n workspaceUuid?: string;\n /**\n * Cached org-scoped SSO sessions keyed by organization UUID. Populated by the\n * org-auth step-up handler; independent of the account token's own expiry.\n */\n orgSessions?: Record<string, StoredOrgSession>;\n}\n\nexport interface ProfileSummary {\n name: string;\n current: boolean;\n hasAccessToken: boolean;\n /** ISO timestamp if known; never includes the token itself. */\n expiresAt?: string;\n /** Present when the profile pins a default workspace. */\n workspaceUuid?: string;\n}\n\ninterface CredentialStoreV2 {\n version: 2;\n currentProfile: string;\n profiles: Record<string, CLICredentials>;\n}\n\n/**\n * Manages CLI credentials storage (one file per environment, multi-profile).\n */\nexport class CredentialsManager {\n private cacheDir: string;\n private apiUrl?: string;\n\n constructor(rootDir: string, apiUrl?: string) {\n // `rootDir` is supplied only by CLI bootstrap (context.ts passes\n // os.homedir()) — the local user's own home directory, never remote or\n // request input — joined with the constant '.gr-cli'. FP (CWE-22).\n // bearer:disable javascript_lang_path_traversal\n // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal\n this.cacheDir = join(rootDir, '.gr-cli');\n this.apiUrl = apiUrl;\n }\n\n /**\n * Validate a profile name. Allows the legacy realm path form\n * `workspace/member` so `acme-demo/acme-admin` works as a profile name.\n * Rejects path traversal and absolute paths.\n */\n validateProfileName(profile: string): void {\n if (!profile) {\n throw new Error('Invalid profile name: (empty).');\n }\n if (profile.includes('..') || profile.startsWith('/') || profile.endsWith('/')) {\n throw new Error(\n `Invalid profile name: ${profile}. Do not use \"..\" or leading/trailing \"/\".`\n );\n }\n // Letters, digits, '_', '-', '.', and a single-level '/' for workspace/member.\n if (!/^[a-zA-Z0-9_.-]+(?:\\/[a-zA-Z0-9_.-]+)?$/.test(profile)) {\n throw new Error(\n `Invalid profile name: ${profile}. Use letters, digits, '_', '-', '.', ` +\n `or workspace/member form (one slash).`\n );\n }\n }\n\n /**\n * Resolve which profile to use for this invocation.\n * Precedence: explicit flag → GRAVITY_RAIL_PROFILE → stored current → \"default\".\n */\n resolveProfileName(explicit?: string | null, env?: string): string {\n if (explicit) {\n this.validateProfileName(explicit);\n return explicit;\n }\n const fromEnv = process.env.GRAVITY_RAIL_PROFILE;\n if (fromEnv) {\n this.validateProfileName(fromEnv);\n return fromEnv;\n }\n if (env) {\n return this.getCurrentProfile(env);\n }\n return DEFAULT_PROFILE;\n }\n\n getCurrentProfile(env: string): string {\n const parsed = this.readStore(env);\n if (!parsed) return DEFAULT_PROFILE;\n return parsed.store.currentProfile || DEFAULT_PROFILE;\n }\n\n setCurrentProfile(env: string, profile: string): void {\n this.validateProfileName(profile);\n const store = this.readStore(env)?.store ?? this.emptyStore(profile);\n if (!store.profiles[profile]) {\n throw new Error(\n `Profile \"${profile}\" has no stored credentials for ${env}. ` +\n `Run: gr auth login --name ${profile} (or gr auth import-dev for local tokens)`\n );\n }\n store.currentProfile = profile;\n this.writeStore(env, store);\n }\n\n listProfiles(env: string): ProfileSummary[] {\n const parsed = this.readStore(env);\n if (!parsed) return [];\n const store = parsed.store;\n const current = store.currentProfile || DEFAULT_PROFILE;\n return Object.keys(store.profiles)\n .sort()\n .map((name) => {\n const creds = store.profiles[name]!;\n return {\n name,\n current: name === current,\n hasAccessToken: Boolean(creds.accessToken || creds.refreshToken),\n expiresAt: creds.expiresAt,\n workspaceUuid: creds.workspaceUuid,\n };\n });\n }\n\n private getCredentialsPath(env: string): string {\n // `env` comes from --env and the dev-cloud:NAMESPACE branch accepts an\n // arbitrary namespace, so it could contain `..` or a path separator and\n // escape the cache directory. Validate against an allowlist first (real\n // env names are alphanumerics, `-`, `_`, `.`, and the dev-cloud `:`\n // separator). This rejects path separators outright — including the\n // `foo/bar` case that would otherwise resolve inside .gr-cli but fail\n // later with a cryptic ENOENT from the un-created subdirectory.\n if (!/^[a-zA-Z0-9_:.-]+$/.test(env)) {\n throw new Error(`Invalid environment name: ${env}`);\n }\n // Defense-in-depth: also contain the resolved path before any fs\n // operation, so a future change to buildCredentialsPath can't reintroduce\n // an escape even if the allowlist is loosened.\n const candidate = this.buildCredentialsPath(env);\n // `this.cacheDir` is rooted at os.homedir() (see constructor) — a constant\n // resolve of the user's own dir, no attacker input. FP (CWE-22).\n // bearer:disable javascript_lang_path_traversal\n const resolvedDir = resolve(this.cacheDir);\n // This resolve()/relative() pair IS the containment sanitizer — `env` was\n // already allowlist-validated above. Semgrep's taint tracker flags the\n // resolve() of the env-derived candidate without modelling the guard.\n // bearer:disable javascript_lang_path_traversal\n // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal\n const rel = relative(resolvedDir, resolve(candidate));\n if (rel.startsWith('..') || isAbsolute(rel)) {\n throw new Error(`Invalid environment name: ${env}`);\n }\n return candidate;\n }\n\n private buildCredentialsPath(env: string): string {\n // Isolate credential files by non-default API port so worktrees (shifted\n // ports + separate DBs) do not clobber each other's imported tokens.\n if (this.apiUrl) {\n try {\n const url = new URL(this.apiUrl);\n const port = url.port;\n if (port && port !== '80' && port !== '443') {\n // :5050 on loopback is the native API — a laptop's, and the one\n // inside a dev-cloud pod, whose `gr auth import-dev` writes the\n // unsuffixed store — so every loopback spelling shares it.\n const isCanonicalLocalDev =\n (LOOPBACK_HOSTNAMES.has(url.hostname) && port === '5050') ||\n (url.hostname.endsWith('gravityrail.test') && port === '5054');\n if (!isCanonicalLocalDev) {\n // `env` is allowlist-validated in getCredentialsPath before this\n // builder runs, cacheDir is homedir-rooted, and url.port is a\n // parsed URL port — no traversal component. FP (CWE-22).\n // bearer:disable javascript_lang_path_traversal\n // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal\n return join(this.cacheDir, `credentials-${env}-${port}.json`);\n }\n }\n } catch {\n // ignore invalid URLs\n }\n }\n // `env` is allowlist-validated in getCredentialsPath before this builder\n // runs and cacheDir is homedir-rooted — no traversal component. FP (CWE-22).\n // bearer:disable javascript_lang_path_traversal\n // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal\n return join(this.cacheDir, `credentials-${env}.json`);\n }\n\n private emptyStore(currentProfile = DEFAULT_PROFILE): CredentialStoreV2 {\n return { version: 2, currentProfile, profiles: {} };\n }\n\n private isCredentialShape(value: unknown): value is CLICredentials {\n if (!value || typeof value !== 'object') return false;\n const v = value as Record<string, unknown>;\n // Local JSON shape check only — typeof / field presence, not secret comparison.\n // FP (CWE-208): no secret values are compared; short-circuit cannot leak content.\n // A client id alone is a complete OAuth identity: the pinned first-party\n // client is public and has no secret (GRA-7843). Requiring `clientSecret`\n // here would make every such profile fail the shape check and be silently\n // dropped on read — losing the pinned id and the tokens stored beside it.\n // bearer:disable javascript_lang_observable_timing\n const hasOAuth = typeof v.clientId === 'string' && v.clientId.length > 0;\n // bearer:disable javascript_lang_observable_timing\n const hasToken = typeof v.accessToken === 'string' && v.accessToken.length > 0;\n return hasOAuth || hasToken;\n }\n\n /**\n * Read and normalize the on-disk store (migrating legacy formats in memory).\n * `wasLegacy` is true when the file was not already v2 so callers can rewrite once.\n */\n private readStore(env: string): { store: CredentialStoreV2; wasLegacy: boolean } | null {\n const credsPath = this.getCredentialsPath(env);\n if (!existsSync(credsPath)) {\n return null;\n }\n\n try {\n const raw = JSON.parse(readFileSync(credsPath, 'utf-8')) as Record<string, unknown>;\n\n // v2 multi-profile\n if (raw.version === 2 && raw.profiles && typeof raw.profiles === 'object') {\n const profiles: Record<string, CLICredentials> = {};\n for (const [name, value] of Object.entries(raw.profiles as Record<string, unknown>)) {\n if (this.isCredentialShape(value)) {\n profiles[name] = value;\n }\n }\n const current =\n typeof raw.currentProfile === 'string' && profiles[raw.currentProfile]\n ? raw.currentProfile\n : Object.keys(profiles)[0] || DEFAULT_PROFILE;\n return {\n store: { version: 2, currentProfile: current, profiles },\n wasLegacy: false,\n };\n }\n\n // Flat single-credential format (pre-multi-account)\n if (this.isCredentialShape(raw)) {\n return {\n store: {\n version: 2,\n currentProfile: DEFAULT_PROFILE,\n profiles: { [DEFAULT_PROFILE]: raw },\n },\n wasLegacy: true,\n };\n }\n\n // Old org-namespaced format { default: {...} }\n const legacyDefault = (raw as { default?: unknown }).default;\n if (this.isCredentialShape(legacyDefault)) {\n return {\n store: {\n version: 2,\n currentProfile: DEFAULT_PROFILE,\n profiles: { [DEFAULT_PROFILE]: legacyDefault },\n },\n wasLegacy: true,\n };\n }\n\n return null;\n } catch {\n return null;\n }\n }\n\n private ensureCacheDir(): void {\n if (!existsSync(this.cacheDir)) {\n mkdirSync(this.cacheDir, { recursive: true, mode: 0o700 });\n try {\n chmodSync(this.cacheDir, 0o700);\n } catch {\n // Ignore permission errors on Windows\n }\n }\n }\n\n private writeStore(env: string, store: CredentialStoreV2): void {\n this.ensureCacheDir();\n const credsPath = this.getCredentialsPath(env);\n // Atomic replace: write a sibling temp file, chmod, then rename into place.\n // POSIX rename is atomic, so a crash mid-write cannot leave a partial JSON\n // that would wipe every profile on the next parse failure.\n const tmpPath = `${credsPath}.tmp`;\n writeFileSync(tmpPath, JSON.stringify(store, null, 2) + '\\n', { mode: 0o600 });\n try {\n chmodSync(tmpPath, 0o600);\n } catch {\n // Ignore permission errors on Windows\n }\n renameSync(tmpPath, credsPath);\n try {\n chmodSync(credsPath, 0o600);\n } catch {\n // Ignore permission errors on Windows\n }\n }\n\n private filterExpired(creds: CLICredentials): CLICredentials | null {\n if (creds.expiresAt) {\n const expiresAt = new Date(creds.expiresAt);\n if (expiresAt <= new Date()) {\n if (creds.refreshToken) {\n return creds;\n }\n return null;\n }\n }\n return creds;\n }\n\n /**\n * Load credentials for an environment + profile.\n * When `profile` is omitted, uses the resolved current profile for `env`.\n */\n load(env: string, profile?: string): CLICredentials | null {\n const parsed = this.readStore(env);\n if (!parsed) return null;\n\n const { store, wasLegacy } = parsed;\n const name = profile ?? store.currentProfile ?? DEFAULT_PROFILE;\n if (profile) this.validateProfileName(profile);\n const creds = store.profiles[name];\n if (!creds) return null;\n\n // Persist migration from flat/org formats so subsequent multi-profile ops work.\n // wasLegacy comes from the single parse in readStore — no second file read.\n if (wasLegacy) {\n this.writeStore(env, store);\n }\n\n return this.filterExpired(creds);\n }\n\n /**\n * Save credentials for an environment + profile.\n * When `profile` is omitted, uses the current profile (or \"default\").\n * Sets currentProfile to the saved profile when the store was empty.\n */\n save(env: string, creds: CLICredentials, profile?: string): void {\n if (profile) this.validateProfileName(profile);\n const store = this.readStore(env)?.store ?? this.emptyStore();\n const name = profile ?? store.currentProfile ?? DEFAULT_PROFILE;\n if (profile) {\n // Explicit profile on save also becomes current when first created, or when\n // the caller is logging into a named account.\n store.profiles[name] = creds;\n if (!store.profiles[store.currentProfile] || Object.keys(store.profiles).length === 1) {\n store.currentProfile = name;\n }\n } else {\n store.profiles[name] = creds;\n if (!store.currentProfile) {\n store.currentProfile = name;\n }\n }\n this.writeStore(env, store);\n }\n\n /**\n * Bulk-save many profiles in one write (used by dev-realms import).\n * Does not change currentProfile unless the store was empty — then uses\n * `preferCurrent` if provided and present, else `superadmin`, else first.\n */\n saveMany(env: string, profiles: Record<string, CLICredentials>, preferCurrent?: string): number {\n const names = Object.keys(profiles);\n for (const name of names) {\n this.validateProfileName(name);\n }\n const store = this.readStore(env)?.store ?? this.emptyStore();\n const wasEmpty = Object.keys(store.profiles).length === 0;\n for (const [name, creds] of Object.entries(profiles)) {\n store.profiles[name] = creds;\n }\n if (wasEmpty) {\n if (preferCurrent && store.profiles[preferCurrent]) {\n store.currentProfile = preferCurrent;\n } else if (store.profiles.superadmin) {\n store.currentProfile = 'superadmin';\n } else {\n store.currentProfile = names.sort()[0] ?? DEFAULT_PROFILE;\n }\n }\n this.writeStore(env, store);\n return names.length;\n }\n\n /**\n * Clear one profile (default: current profile). Deletes the file when no profiles remain.\n * Pass a profile name to clear a specific account without touching others.\n */\n clear(env: string, profile?: string): void {\n const parsed = this.readStore(env);\n if (!parsed) return;\n const store = parsed.store;\n\n const name = profile ?? store.currentProfile ?? DEFAULT_PROFILE;\n if (profile) this.validateProfileName(profile);\n delete store.profiles[name];\n\n if (Object.keys(store.profiles).length === 0) {\n const credsPath = this.getCredentialsPath(env);\n if (existsSync(credsPath)) {\n try {\n unlinkSync(credsPath);\n } catch {\n // Ignore\n }\n }\n return;\n }\n\n if (store.currentProfile === name) {\n store.currentProfile = Object.keys(store.profiles).sort()[0]!;\n }\n this.writeStore(env, store);\n }\n\n /**\n * Read a cached org-scoped SSO session for an org, if present and unexpired.\n * Independent of the account token's expiry — a valid org session is reusable\n * even while the account token is being refreshed.\n */\n getOrgSession(env: string, profile: string | undefined, orgUuid: string): string | undefined {\n const parsed = this.readStore(env);\n if (!parsed) return undefined;\n const name = profile ?? parsed.store.currentProfile ?? DEFAULT_PROFILE;\n if (profile) this.validateProfileName(profile);\n const entry = parsed.store.profiles[name]?.orgSessions?.[orgUuid];\n if (!isOrgSessionCredential(entry?.session)) return undefined;\n if (entry.expiresAt && new Date(entry.expiresAt) <= new Date()) return undefined;\n return entry.session;\n }\n\n /**\n * Cache an org-scoped SSO session under an existing profile, keyed by org UUID.\n * No-op when the profile does not exist — org sessions only attach to a\n * logged-in account profile (never create a token-less profile row).\n */\n setOrgSession(\n env: string,\n profile: string | undefined,\n orgUuid: string,\n session: string,\n expiresAt?: string\n ): void {\n if (!isOrgSessionCredential(session)) {\n throw new Error('Invalid organization session. Sign in again.');\n }\n const parsed = this.readStore(env);\n if (!parsed) return;\n const store = parsed.store;\n const name = profile ?? store.currentProfile ?? DEFAULT_PROFILE;\n if (profile) this.validateProfileName(profile);\n const creds = store.profiles[name];\n if (!creds) return;\n creds.orgSessions = {\n ...(creds.orgSessions ?? {}),\n [orgUuid]: { session, ...(expiresAt ? { expiresAt } : {}) },\n };\n this.writeStore(env, store);\n }\n\n /** Remove the entry only when its currently stored token matches the rejected one. */\n removeOrgSession(\n env: string,\n profile: string | undefined,\n orgUuid: string,\n expectedSession: string\n ): void {\n const parsed = this.readStore(env);\n if (!parsed) return;\n const name = profile ?? parsed.store.currentProfile ?? DEFAULT_PROFILE;\n if (profile) this.validateProfileName(profile);\n const sessions = parsed.store.profiles[name]?.orgSessions;\n if (sessions?.[orgUuid]?.session !== expectedSession) return;\n delete sessions[orgUuid];\n this.writeStore(env, parsed.store);\n }\n\n getCacheDir(): string {\n return this.cacheDir;\n }\n\n /** Absolute path of the credentials file for `env` (for docs / `auth list`). */\n getCredentialsFilePath(env: string): string {\n return this.getCredentialsPath(env);\n }\n}\n","/** The opaque org credential accepted by the SDK's X-Org-Session transport. */\nexport function isOrgSessionCredential(value: unknown): value is string {\n return typeof value === 'string' && /^gr_sess_[A-Za-z0-9_-]+$/.test(value);\n}\n","/**\n * CLI terminal UI utilities\n *\n * Provides interactive terminal UI components for CLI tools\n */\n\nimport * as readline from 'readline';\n\nexport interface SelectOption<T> {\n item: T;\n label: string;\n detail?: string;\n}\n\nexport interface SelectFromListOptions<T> {\n title?: string;\n labelFn?: (item: T) => string;\n detailFn?: (item: T) => string | null;\n env?: string;\n emptyMessage?: string;\n allowNew?: boolean;\n newLabel?: string;\n}\n\nexport interface SelectResult<T> {\n item: T | null;\n isNew: boolean;\n}\n\nconst NEW_ITEM_MARKER = Symbol('NEW_ITEM');\n\n/**\n * Interactive list picker using arrow keys\n */\nexport async function selectFromList<T>(\n items: T[],\n options: SelectFromListOptions<T> = {}\n): Promise<SelectResult<T>> {\n const {\n title = 'Select an item',\n labelFn = (item: T) => String((item as any).name || (item as any).title || item),\n detailFn = null,\n env = null,\n emptyMessage = 'No items found.',\n allowNew = false,\n newLabel = 'Create new...',\n } = options;\n\n if ((!items || items.length === 0) && !allowNew) {\n console.log(`\\n ${emptyMessage}`);\n return { item: null, isNew: false };\n }\n\n // Prepend \"Create new\" option if allowed\n const displayItems: (T | typeof NEW_ITEM_MARKER)[] = allowNew\n ? [NEW_ITEM_MARKER, ...items]\n : items;\n\n return new Promise((resolve) => {\n let selectedIndex = allowNew ? 1 : 0;\n let filterText = '';\n\n const getFilteredItems = (): (T | typeof NEW_ITEM_MARKER)[] => {\n if (!filterText) return displayItems;\n const lower = filterText.toLowerCase();\n return displayItems.filter((item) => {\n if (item === NEW_ITEM_MARKER) return true;\n const label = labelFn(item);\n return label.toLowerCase().includes(lower);\n });\n };\n\n const render = (): void => {\n const filtered = getFilteredItems();\n\n // Clear screen and move cursor to top\n process.stdout.write('\\x1B[2J\\x1B[H');\n\n console.log('='.repeat(60));\n console.log(`${title} (↑/↓ to move, Enter to select, Esc to cancel)`);\n console.log('='.repeat(60));\n if (env) {\n console.log(`Environment: ${env}`);\n }\n console.log(`Filter: ${filterText}${filterText ? '' : '(type to filter)'}`);\n console.log('');\n\n if (filtered.length === 0) {\n console.log(` ${emptyMessage}`);\n console.log('');\n return;\n }\n\n // Show up to 15 items around the selected one\n const maxVisible = 15;\n let startIdx = Math.max(0, selectedIndex - Math.floor(maxVisible / 2));\n let endIdx = Math.min(filtered.length, startIdx + maxVisible);\n if (endIdx - startIdx < maxVisible && startIdx > 0) {\n startIdx = Math.max(0, endIdx - maxVisible);\n }\n\n if (startIdx > 0) {\n console.log(` ... ${startIdx} more above ...`);\n }\n\n for (let i = startIdx; i < endIdx; i++) {\n const item = filtered[i]!;\n const prefix = i === selectedIndex ? '> ' : ' ';\n\n let line: string;\n if (item === NEW_ITEM_MARKER) {\n line = `\\x1B[32m${newLabel}\\x1B[0m`; // Green color for \"Create new\"\n } else {\n const typedItem = item as T;\n line = labelFn(typedItem);\n if (detailFn) {\n const detail = detailFn(typedItem);\n if (detail) {\n line = `${line} \\x1B[90m${detail}\\x1B[0m`;\n }\n }\n }\n\n if (i === selectedIndex) {\n console.log(`\\x1B[7m${prefix}${line}\\x1B[0m`);\n } else {\n console.log(`${prefix}${line}`);\n }\n }\n\n if (endIdx < filtered.length) {\n console.log(` ... ${filtered.length - endIdx} more below ...`);\n }\n\n console.log('');\n console.log(` ${filtered.length} item(s)`);\n };\n\n // Set up raw mode for arrow key input\n readline.emitKeypressEvents(process.stdin);\n if (process.stdin.isTTY) {\n process.stdin.setRawMode(true);\n }\n\n render();\n\n const handleKeypress = (str: string | undefined, key: readline.Key): void => {\n const filtered = getFilteredItems();\n\n if (key.name === 'up') {\n selectedIndex = Math.max(0, selectedIndex - 1);\n render();\n } else if (key.name === 'down') {\n selectedIndex = Math.min(filtered.length - 1, selectedIndex + 1);\n render();\n } else if (key.name === 'return') {\n cleanup();\n if (filtered.length > 0 && selectedIndex < filtered.length) {\n const selected = filtered[selectedIndex]!;\n if (selected === NEW_ITEM_MARKER) {\n resolve({ item: null, isNew: true });\n } else {\n resolve({ item: selected as T, isNew: false });\n }\n } else {\n resolve({ item: null, isNew: false });\n }\n } else if (key.name === 'escape' || (key.ctrl && key.name === 'c')) {\n cleanup();\n resolve({ item: null, isNew: false });\n } else if (key.name === 'backspace') {\n filterText = filterText.slice(0, -1);\n selectedIndex = allowNew ? 0 : 0;\n render();\n } else if (str && str.length === 1 && !key.ctrl && !key.meta) {\n filterText += str;\n selectedIndex = allowNew ? 0 : 0;\n render();\n }\n };\n\n const cleanup = (): void => {\n process.stdin.removeListener('keypress', handleKeypress);\n if (process.stdin.isTTY) {\n process.stdin.setRawMode(false);\n }\n process.stdin.pause();\n process.stdout.write('\\x1B[2J\\x1B[H');\n };\n\n process.stdin.on('keypress', handleKeypress);\n process.stdin.resume();\n });\n}\n\n/**\n * Print a table of items\n */\nexport function printTable<T>(\n items: T[],\n columns: Array<{\n header: string;\n getValue: (item: T) => string;\n maxWidth?: number;\n }>,\n options: { title?: string; env?: string } = {}\n): void {\n if (!items || items.length === 0) {\n console.log('\\nNo items found.');\n return;\n }\n\n if (options.title) {\n console.log(`\\n=== ${options.title} ===`);\n }\n if (options.env) {\n console.log(`Environment: ${options.env}`);\n }\n console.log('');\n\n // Calculate column widths\n const widths = columns.map((col) => {\n const maxContent = Math.max(...items.map((item) => String(col.getValue(item) ?? '').length));\n const width = Math.max(col.header.length, maxContent);\n return col.maxWidth ? Math.min(width, col.maxWidth) : width;\n });\n\n // Print header\n const headerLine = columns.map((col, i) => col.header.padEnd(widths[i]!)).join(' ');\n console.log(headerLine);\n console.log(widths.map((w) => '-'.repeat(w)).join(' '));\n\n // Print rows\n for (const item of items) {\n const row = columns\n .map((col, i) => {\n const value = String(col.getValue(item) ?? '');\n const width = widths[i]!;\n return value.slice(0, width).padEnd(width);\n })\n .join(' ');\n console.log(row);\n }\n\n console.log('');\n console.log(`Total: ${items.length} item(s)`);\n}\n\n/**\n * Format a timestamp for display\n */\nexport function formatTimestamp(isoString: string | null | undefined): string {\n if (!isoString) return '';\n const date = new Date(isoString);\n const now = new Date();\n const diff = now.getTime() - date.getTime();\n\n if (diff < 60000) return 'just now';\n if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;\n if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;\n if (diff < 604800000) return `${Math.floor(diff / 86400000)}d ago`;\n\n return date.toLocaleDateString();\n}\n\n/**\n * Wrap text to a maximum width\n */\nexport function wrapText(text: string, width: number = 70): string[] {\n const words = text.split(' ');\n const lines: string[] = [];\n let currentLine = '';\n\n for (const word of words) {\n if (currentLine.length + word.length + 1 <= width) {\n currentLine += (currentLine ? ' ' : '') + word;\n } else {\n if (currentLine) lines.push(currentLine);\n currentLine = word;\n }\n }\n if (currentLine) lines.push(currentLine);\n return lines;\n}\n\n/**\n * Print a chat message with formatting\n */\nexport function printMessage(\n content: string,\n role: 'user' | 'assistant' | 'system',\n indent: string = ' '\n): void {\n const roleColors: Record<string, string> = {\n user: '\\x1B[34m', // Blue\n assistant: '\\x1B[32m', // Green\n system: '\\x1B[90m', // Gray\n };\n const resetColor = '\\x1B[0m';\n const color = roleColors[role] || resetColor;\n\n const label = role === 'user' ? 'You' : role === 'assistant' ? 'Assistant' : 'System';\n console.log(`${indent}${color}[${label}]${resetColor}`);\n\n const lines = content.split('\\n');\n for (const line of lines) {\n const wrapped = wrapText(line, 70);\n for (const wrappedLine of wrapped) {\n console.log(`${indent} ${wrappedLine}`);\n }\n }\n console.log('');\n}\n\n/**\n * Clear the terminal screen\n */\nexport function clearScreen(): void {\n process.stdout.write('\\x1B[2J\\x1B[H');\n}\n","/**\n * AG-UI Client for CLI chat interactions\n *\n * Implements the AG-UI (Agent-User Interaction) protocol for streaming\n * chat responses. See: https://docs.ag-ui.com/concepts/events\n */\n\nimport {\n isProposedMessageSettlementStatus,\n type ProposedMessageSettlementStatus,\n} from '@gravity-rail/sdk';\nimport { apiAuthHeaders, apiFetch } from '../lib/api-transport';\n\nimport type { ConciergeAppContextPayload } from '../lib/cli-client-context';\n\n/** How asking the server to send or discard a drafted message ended. */\nexport type ProposedMessageSettleResult =\n | { kind: 'settled'; status: ProposedMessageSettlementStatus; detail?: string | null }\n | { kind: 'refused'; status: number }\n | { kind: 'transport' };\n\n/**\n * AG-UI event types\n */\nexport type AGUIEventType =\n | 'RUN_STARTED'\n | 'RUN_FINISHED'\n | 'RUN_ERROR'\n | 'TEXT_MESSAGE_START'\n | 'TEXT_MESSAGE_CONTENT'\n | 'TEXT_MESSAGE_END'\n | 'TOOL_CALL_START'\n | 'TOOL_CALL_ARGS'\n | 'TOOL_CALL_END'\n | 'TOOL_CALL_RESULT'\n | 'STATE_SNAPSHOT'\n | 'STATE_DELTA'\n // Lowercase variants (some backends use these)\n | 'run_started'\n | 'run_finished'\n | 'run_error'\n | 'text_message_start'\n | 'text_message_content'\n | 'text_message_end'\n | 'tool_call_start'\n | 'tool_call_args'\n | 'tool_call_end'\n | 'tool_call_result'\n | 'state_snapshot'\n | 'state_delta'\n | 'done';\n\nexport interface AGUIEvent {\n type: AGUIEventType;\n messageId?: string;\n role?: string;\n delta?: string;\n content?: string;\n message?: string;\n code?: string;\n toolCallId?: string;\n toolCallName?: string;\n result?: any;\n snapshot?: any;\n operations?: any[];\n [key: string]: any;\n}\n\nexport interface ChatMessage {\n role: 'user' | 'assistant' | 'system';\n content: string;\n}\n\nexport interface AGUIClientOptions {\n baseUrl: string;\n workspaceUuid?: string;\n chatId?: number | string; // Numeric chat id (documented) or chat uuid (accepted)\n /** Full URL override — when provided, baseUrl/workspaceUuid/chatId are ignored for POST */\n endpointUrl?: string;\n accessToken: string;\n debug?: boolean;\n /** Model field sent in request body (default: 'manager'). Set to undefined to omit. */\n model?: string;\n /** Concierge / client context forwarded to the API (e.g. CLI surface hints). */\n appContext?: ConciergeAppContextPayload;\n}\n\n/**\n * AG-UI Client for streaming chat responses\n */\nexport class AGUIClient {\n private endpointUrl: string;\n private baseUrl: string;\n private workspaceUuid: string;\n private chatId: number | string;\n private accessToken: string;\n private debug: boolean;\n private model: string | undefined;\n private appContext: ConciergeAppContextPayload | undefined;\n\n constructor(options: AGUIClientOptions) {\n this.baseUrl = options.baseUrl;\n this.workspaceUuid = options.workspaceUuid ?? '';\n this.chatId = options.chatId ?? 0;\n if (!options.endpointUrl && (!options.workspaceUuid || options.chatId === undefined)) {\n throw new Error('AGUIClient requires workspaceUuid and chatId, or endpointUrl');\n }\n this.endpointUrl =\n options.endpointUrl ??\n `${options.baseUrl}/api/v2/w/${options.workspaceUuid}/web-chat/${options.chatId}/chat/agui`;\n this.accessToken = options.accessToken;\n this.debug = options.debug ?? false;\n this.model = 'model' in options ? options.model : 'manager';\n this.appContext = options.appContext;\n }\n\n private chatRouteUrl(suffix: string): string | null {\n // Numeric chatId: treat 0 / negative as \"no chat\" (<= 0 rather than a\n // falsy check so a deliberate sentinel of 0 doesn't mean \"valid chat\").\n // String chatId is a uuid; empty string means \"no chat\".\n const noChat = typeof this.chatId === 'number' ? this.chatId <= 0 : this.chatId.length === 0;\n if (!this.workspaceUuid || noChat) return null;\n return `${this.baseUrl}/api/v2/w/${this.workspaceUuid}/chats/${this.chatId}/${suffix}`;\n }\n\n /**\n * The operator's own live inline-connect link for this chat, or null when\n * none is live. The `inline_connect` prompt carries no URL on purpose (it is\n * a bearer, and the tool result is persisted and model-visible), so the\n * terminal fetches it here when the operator chooses to connect.\n */\n async fetchInlineConnectLink(\n appSlug: string\n ): Promise<{ connectUrl: string; expiresInMinutes: number } | null> {\n const url = this.chatRouteUrl(`inline-connect/${encodeURIComponent(appSlug)}/link`);\n if (!url) return null;\n try {\n const res = await apiFetch(url, { headers: apiAuthHeaders(this.accessToken) });\n if (!res.ok) return null;\n const body = (await res.json()) as { connectUrl?: unknown; expiresInMinutes?: unknown };\n if (typeof body.connectUrl !== 'string') return null;\n return {\n connectUrl: body.connectUrl,\n expiresInMinutes: typeof body.expiresInMinutes === 'number' ? body.expiresInMinutes : 0,\n };\n } catch {\n return null;\n }\n }\n\n /**\n * Send or discard a message the Manager proposed as a draft. The three\n * results are different things to tell the operator: `settled` carries how\n * it ended, `refused` is the server saying no (a 409 is a draft settled\n * elsewhere), and `transport` is not knowing — the draft is unchanged as\n * far as this client can tell.\n */\n async settleProposedMessage(\n promptId: string,\n decision: 'send' | 'discard'\n ): Promise<ProposedMessageSettleResult> {\n const url = this.chatRouteUrl(`proposed-messages/${encodeURIComponent(promptId)}/decision`);\n if (!url) return { kind: 'transport' };\n try {\n const res = await apiFetch(url, {\n method: 'POST',\n headers: {\n ...apiAuthHeaders(this.accessToken),\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ decision }),\n });\n if (!res.ok) return { kind: 'refused', status: res.status };\n const body = (await res.json()) as { status?: unknown; detail?: unknown };\n if (!isProposedMessageSettlementStatus(body.status)) return { kind: 'transport' };\n return {\n kind: 'settled',\n status: body.status,\n detail: typeof body.detail === 'string' ? body.detail : null,\n };\n } catch {\n return { kind: 'transport' };\n }\n }\n\n private inferenceStatusUrl(): string | null {\n // Numeric chatId: treat 0 / negative as \"no chat\" (<= 0 rather than a\n // falsy check so a deliberate sentinel of 0 doesn't mean \"valid chat\").\n // String chatId is a uuid; empty string means \"no chat\".\n const noChat = typeof this.chatId === 'number' ? this.chatId <= 0 : this.chatId.length === 0;\n if (!this.workspaceUuid || noChat) return null;\n return `${this.baseUrl}/api/v2/w/${this.workspaceUuid}/chats/${this.chatId}/inference/status`;\n }\n\n private async waitForInferenceInactive(maxWaitMs = 60_000): Promise<boolean> {\n const url = this.inferenceStatusUrl();\n if (!url) return false;\n const deadline = Date.now() + maxWaitMs;\n while (Date.now() < deadline) {\n try {\n const res = await apiFetch(url, {\n headers: apiAuthHeaders(this.accessToken),\n });\n if (res.ok) {\n const body = (await res.json()) as { active?: boolean };\n if (!body.active) return true;\n }\n } catch (err) {\n // Transient network errors (DNS blips, connection resets) shouldn't\n // crash the 409-retry loop. Log under --debug and keep polling\n // until the deadline; the caller will fall back to the original\n // 409 error if we can't confirm inactive in time.\n if (this.debug) {\n console.log(\n `[DEBUG] waitForInferenceInactive fetch failed: ${\n err instanceof Error ? err.message : String(err)\n }`\n );\n }\n }\n await new Promise((r) => setTimeout(r, 2000));\n }\n return false;\n }\n\n /**\n * Send messages and stream the response\n */\n async sendMessage(\n messages: ChatMessage[],\n onEvent: (event: AGUIEvent) => void,\n options?: AguiStreamOptions\n ): Promise<void> {\n return this.streamRequest({ messages }, onEvent, options);\n }\n\n /**\n * Stream an AG-UI request (initial messages or HITL resume).\n */\n async streamRequest(\n request: AguiRequestBody,\n onEvent: (event: AGUIEvent) => void,\n options?: AguiStreamOptions\n ): Promise<void> {\n const body = JSON.stringify({\n ...(this.model ? { model: this.model } : {}),\n messages: request.messages ?? [],\n ...(this.appContext ? { appContext: this.appContext } : {}),\n ...(request.resumeValue !== undefined ? { resumeValue: request.resumeValue } : {}),\n ...(request.resumeInterruptId ? { resumeInterruptId: request.resumeInterruptId } : {}),\n ...(request.resume !== undefined ? { resume: request.resume } : {}),\n ...(options?.autoApprove ? { context: { autoApprove: true } } : {}),\n });\n\n if (this.debug) {\n console.log(`\\n[DEBUG] POST ${this.endpointUrl}`);\n console.log(\n `[DEBUG] Body: ${request.resumeValue !== undefined ? 'resume' : `${(request.messages ?? []).length} message(s)`}`\n );\n }\n\n await this.postStream(body, onEvent, options);\n }\n\n private async postStream(\n body: string,\n onEvent: (event: AGUIEvent) => void,\n options?: AguiStreamOptions,\n conflictRetries = 0\n ): Promise<void> {\n const response = await apiFetch(this.endpointUrl, {\n method: 'POST',\n headers: {\n ...apiAuthHeaders(this.accessToken),\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream',\n },\n body,\n });\n\n if (this.debug) {\n console.log(`[DEBUG] Response status: ${response.status}`);\n }\n\n if (response.status === 409 && conflictRetries < 3) {\n const ready = await this.waitForInferenceInactive();\n if (ready) {\n await this.postStream(body, onEvent, options, conflictRetries + 1);\n return;\n }\n }\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => '');\n if (this.debug) {\n console.log(`[DEBUG] Error response: ${errorText}`);\n }\n throw new Error(\n `Chat request failed: ${response.status}${errorText ? `: ${errorText.slice(0, 200)}` : ''}`\n );\n }\n\n await parseSseStream(response.body!, onEvent);\n }\n\n /**\n * Subscribe to the chat's persistent AG-UI event feed and surface\n * server-initiated turns that arrive while we're idle between our own turns.\n *\n * The feed at ``/chats/{chatId}/events`` replays every AG-UI event for the\n * chat across all turns (assistant events plus user-message echoes). It never\n * self-terminates — it ends only on disconnect. On reconnect we send\n * ``Last-Event-ID`` so the server replays the gap. The loop reconnects with\n * capped exponential backoff and resolves quietly once ``signal`` aborts;\n * it never throws except when required args are missing (callers gate on\n * availability, so that path is a programming error).\n */\n async subscribeToFeed(opts: {\n onEvent: (event: AGUIEvent) => void;\n signal: AbortSignal;\n onDebug?: (msg: string) => void;\n }): Promise<void> {\n const { onEvent, signal, onDebug } = opts;\n\n // Guard even though callers gate on availability: the feed URL needs a\n // real workspace + chat. Mirror inferenceStatusUrl's \"no chat\" logic.\n const noChat = typeof this.chatId === 'number' ? this.chatId <= 0 : this.chatId.length === 0;\n if (!this.baseUrl || !this.workspaceUuid || noChat) {\n throw new Error('subscribeToFeed requires baseUrl, workspaceUuid, and a chatId');\n }\n const feedUrl = `${this.baseUrl}/api/v2/w/${this.workspaceUuid}/chats/${this.chatId}/events`;\n\n let lastEventId: string | undefined;\n let backoffMs = 1000;\n const maxBackoffMs = 15_000;\n // A connection that survived this long was healthy even if the chat\n // stayed silent the whole time — keepalive comment frames are\n // stripped by the parser, so they can never count as received data.\n const healthyConnectionMs = 30_000;\n\n while (!signal.aborted) {\n let receivedData = false;\n const connectedAt = Date.now();\n try {\n const headers: Record<string, string> = {\n ...apiAuthHeaders(this.accessToken),\n Accept: 'text/event-stream',\n };\n if (lastEventId !== undefined) headers['Last-Event-ID'] = lastEventId;\n\n const response = await apiFetch(feedUrl, { method: 'GET', headers, signal });\n if (!response.ok || !response.body) {\n throw new Error(`feed request failed: ${response.status}`);\n }\n onDebug?.(`feed connected${lastEventId ? ` (resume ${lastEventId})` : ''}`);\n\n await parseSseStream(\n response.body,\n (event, eventName) => {\n receivedData = true;\n // Retention lapsed — the server couldn't replay the gap.\n // Detected via the SSE ``event: feed_reset`` name (the\n // payload type is a belt-and-suspenders duplicate). For\n // v1 we just note it; some events may have been missed.\n if (\n eventName === 'feed_reset' ||\n (typeof event.type === 'string' && event.type.toUpperCase() === 'FEED_RESET')\n ) {\n onDebug?.('feed reset — server could not replay missed events');\n return;\n }\n onEvent(event);\n },\n (id) => {\n receivedData = true;\n lastEventId = id;\n }\n );\n // Stream ended (disconnect) — fall through to reconnect with backoff.\n } catch (err) {\n if (signal.aborted) return;\n onDebug?.(`feed error: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n if (signal.aborted) return;\n\n // Reset only on evidence of health (delivered frames, or a\n // long-lived idle connection); otherwise wait out the current\n // backoff and grow it for the NEXT attempt (1s, 2s, 4s … cap).\n // Healthy connections must never escalate — an earlier version\n // doubled unconditionally after the reset, so steady\n // reconnects crept toward the cap.\n const wasHealthy = receivedData || Date.now() - connectedAt >= healthyConnectionMs;\n if (wasHealthy) backoffMs = 1000;\n const completed = await abortableDelay(backoffMs, signal);\n if (!completed) return; // aborted while waiting\n if (!wasHealthy) backoffMs = Math.min(backoffMs * 2, maxBackoffMs);\n }\n }\n}\n\n/**\n * Parse a Server-Sent Events stream body into AG-UI events.\n *\n * Shared by ``AGUIClient.postStream`` (per-turn POST) and ``subscribeToFeed``\n * (persistent GET feed). Surfaces ``data:`` frames as parsed events, ``id:``\n * frames via ``onId`` (feed reconnect uses the last id as ``Last-Event-ID``),\n * and ignores SSE comment frames (``: turn-done``, keepalives). ``onId`` is\n * optional — the POST path has no use for entry ids.\n */\nexport async function parseSseStream(\n body: ReadableStream<Uint8Array>,\n onEvent: (event: AGUIEvent, eventName?: string) => void,\n onId?: (id: string) => void\n): Promise<void> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n // Per SSE, an ``event:`` line names the dispatch it precedes (the\n // server's feed_reset signal uses this). Cleared once consumed or at\n // the blank-line frame boundary.\n let pendingEventName: string | undefined;\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const rawLine of lines) {\n // Tolerate CRLF endings without changing the \\n-split behavior.\n const line = rawLine.endsWith('\\r') ? rawLine.slice(0, -1) : rawLine;\n\n // Blank line = SSE frame boundary; the pending event name only\n // applies within its own frame.\n if (line === '') {\n pendingEventName = undefined;\n continue;\n }\n\n // SSE comment frame (turn boundaries, keepalives) — ignore.\n if (line.startsWith(':')) continue;\n\n if (line.startsWith('event:')) {\n const nameValue = line.slice(6);\n pendingEventName = nameValue.startsWith(' ') ? nameValue.slice(1) : nameValue;\n continue;\n }\n\n if (line.startsWith('id:')) {\n const idValue = line.slice(3);\n // Per SSE, a single leading space after the colon is stripped.\n onId?.(idValue.startsWith(' ') ? idValue.slice(1) : idValue);\n continue;\n }\n\n if (line.startsWith('data: ')) {\n const data = line.slice(6);\n if (data === '[DONE]') {\n onEvent({ type: 'done' }, pendingEventName);\n pendingEventName = undefined;\n continue;\n }\n try {\n onEvent(JSON.parse(data) as AGUIEvent, pendingEventName);\n } catch {\n // Ignore parse errors for malformed events.\n }\n pendingEventName = undefined;\n }\n }\n }\n}\n\n/**\n * Resolve after ``ms`` unless ``signal`` aborts first. Returns true if the delay\n * completed, false if it was aborted — lets a reconnect loop exit cleanly.\n */\nfunction abortableDelay(ms: number, signal: AbortSignal): Promise<boolean> {\n return new Promise<boolean>((resolve) => {\n if (signal.aborted) {\n resolve(false);\n return;\n }\n const onAbort = (): void => {\n clearTimeout(timer);\n resolve(false);\n };\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve(true);\n }, ms);\n signal.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nexport interface AguiStreamOptions {\n autoApprove?: boolean;\n}\n\nexport interface AguiRequestBody {\n messages?: ChatMessage[];\n /** Concierge AGUI resume fields. */\n resumeValue?: string;\n resumeInterruptId?: string;\n /** Workspace-chat HITL resume (ChatCompletionRequest.resume shape:\n * { decisions: [{type: 'approve'|'edit'|'reject', ...}], interruptId }). */\n resume?: unknown;\n}\n\n/**\n * Helper to check if an event is a text content event\n */\nexport function isTextContentEvent(event: AGUIEvent): boolean {\n const type = event.type.toLowerCase();\n return type === 'text_message_content';\n}\n\n/**\n * Helper to check if an event is an error event\n */\nexport function isErrorEvent(event: AGUIEvent): boolean {\n const type = event.type.toLowerCase();\n return type === 'run_error';\n}\n\n/**\n * Helper to extract text delta from an event\n */\nexport function getTextDelta(event: AGUIEvent): string | null {\n if (isTextContentEvent(event) && event.delta) {\n return event.delta;\n }\n return null;\n}\n\n/**\n * Helper to extract error message from an event\n */\nexport function getErrorMessage(event: AGUIEvent): string | null {\n if (isErrorEvent(event)) {\n return event.message || event.code || 'Unknown error';\n }\n return null;\n}\n","import { GravityRailClient } from '@gravity-rail/sdk';\nimport {\n CredentialsManager,\n getEnvironmentConfig,\n resolveNonInteractiveAuth,\n type AuthResult,\n type EnvironmentConfig,\n} from '../cli-utils';\nimport { homedir } from 'os';\nimport { detectOutputFormat, type OutputFormat } from './output';\nimport { AuthRequiredError } from './errors';\nimport { registerOrgAuthHandler, type OrgAuthContext } from './org-auth';\nimport { createSandboxFetchFromEnv } from './sandbox-fetch';\n\n/** Build an authenticated API client with the CLI org-auth handler registered. */\nfunction makeApiClient(\n accessToken: string | undefined,\n apiUrl: string,\n fetchFn?: typeof fetch,\n orgAuthCtx?: OrgAuthContext\n): GravityRailClient {\n const resolvedFetch = fetchFn ?? createSandboxFetchFromEnv();\n const apiClient = new GravityRailClient(accessToken, apiUrl, resolvedFetch);\n registerOrgAuthHandler(apiClient, apiUrl, accessToken ?? '', orgAuthCtx);\n return apiClient;\n}\n\n/**\n * Org-auth context for a profile (login) command: enables the browser SSO\n * step-up and caches the captured session under the profile. API-key and\n * credential-broker contexts omit this — API keys are gate-exempt, and the\n * sandbox broker is non-interactive (no browser).\n */\nfunction interactiveOrgAuth(ctx: CommandContext): OrgAuthContext {\n return {\n credentialsManager: ctx.credentialsManager,\n env: ctx.env,\n profile: ctx.profile,\n frontendUrl: ctx.envConfig.frontendUrl,\n interactive: true,\n };\n}\n\n/**\n * Credential-broker context (code-interpreter sandbox): the scoped token is held\n * by the broker and absent from the env, so the CLI talks to the loopback broker\n * with NO auth header. Returns null when not in the sandbox (no broker URL) — the\n * standalone CLI then falls through to GRAVITY_RAIL_API_KEY / profile auth.\n */\n/**\n * The credential broker is ALWAYS a loopback listener inside the sandbox VM.\n * Requests sent to it carry no Authorization header (the broker adds it), so a\n * non-loopback value here would ship unauthenticated API traffic — including\n * request bodies — to an arbitrary host. uid-1000 code can set env vars, so\n * treat the URL as untrusted and accept only loopback. Anything else is ignored\n * (we fall through to normal auth) rather than trusted.\n */\nfunction isLoopbackBrokerUrl(rawUrl: string): boolean {\n try {\n const { hostname, protocol } = new URL(rawUrl);\n if (protocol !== 'http:' && protocol !== 'https:') return false;\n // URL() preserves brackets on IPv6 literals.\n const host = hostname.replace(/^\\[|\\]$/g, '');\n return host === '127.0.0.1' || host === '::1' || host === 'localhost';\n } catch {\n return false;\n }\n}\n\n/**\n * The sandbox's loopback broker URL, or null when not running in a sandbox.\n *\n * Single place the `GRAVITY_RAIL_BROKER_URL` loopback check lives, so every\n * caller — both authenticated commands and public commands —\n * applies the same validation.\n */\nexport function sandboxBrokerUrl(): string | null {\n const brokerUrl = process.env.GRAVITY_RAIL_BROKER_URL;\n if (!brokerUrl || !isLoopbackBrokerUrl(brokerUrl)) return null;\n return brokerUrl;\n}\n\nfunction tryBrokerContext(ctx: CommandContext): AuthenticatedContext | null {\n const brokerUrl = sandboxBrokerUrl();\n if (!brokerUrl) return null;\n const apiClient = makeApiClient(undefined, brokerUrl, createSandboxFetchFromEnv());\n return { ...ctx, accessToken: '', apiClient };\n}\n\nfunction contextWithToken(ctx: CommandContext, auth: AuthResult): AuthenticatedContext {\n const apiClient = makeApiClient(\n auth.accessToken,\n ctx.envConfig.apiUrl,\n undefined,\n auth.credentials ? interactiveOrgAuth(ctx) : undefined\n );\n return {\n ...ctx,\n accessToken: auth.accessToken,\n apiClient,\n profileWorkspace: auth.credentials?.workspaceUuid,\n };\n}\n\nexport interface GlobalOptions {\n env: string;\n /** Override API base URL (also: GRAVITY_RAIL_API_URL env var). */\n apiUrl?: string;\n outputFormat?: string;\n jq?: string;\n verbose?: boolean;\n allowWrite?: boolean;\n /** Named credential profile (`--profile` / GRAVITY_RAIL_PROFILE). */\n profile?: string;\n /** Directory to classify as a linked worktree. Defaults to `process.cwd()`. */\n startDir?: string;\n}\n\nexport interface PublicGlobalOptions {\n env?: string;\n apiUrl?: string;\n frontendUrl?: string;\n outputFormat?: string;\n jq?: string;\n verbose?: boolean;\n allowWrite?: boolean;\n /** Named credential profile (`--profile` / GRAVITY_RAIL_PROFILE). */\n profile?: string;\n /** Directory to classify as a linked worktree. Defaults to `process.cwd()`. */\n startDir?: string;\n}\n\nexport interface CommandContext {\n env: string;\n envConfig: EnvironmentConfig;\n outputFormat: OutputFormat;\n /** `--jq` filter, applied to JSON output. See `lib/jq.ts`. */\n jq?: string;\n verbose: boolean;\n allowWrite: boolean;\n credentialsManager: CredentialsManager;\n /** Resolved credential profile for this invocation. */\n profile: string;\n}\n\nexport interface AuthenticatedContext extends CommandContext {\n accessToken: string;\n apiClient: GravityRailClient;\n /** Default workspace UUID from the profile (dev workspace/member profiles). */\n profileWorkspace?: string;\n}\n\n/** Create a base command context (no auth required) */\nexport function createContext(opts: GlobalOptions): CommandContext {\n const envConfig = getEnvironmentConfig(opts.env, {\n apiUrl: opts.apiUrl,\n startDir: opts.startDir,\n });\n const credentialsManager = new CredentialsManager(homedir(), envConfig.apiUrl);\n const profile = credentialsManager.resolveProfileName(opts.profile, opts.env);\n return {\n env: opts.env,\n envConfig,\n outputFormat: detectOutputFormat(opts.outputFormat),\n jq: opts.jq,\n verbose: opts.verbose ?? false,\n allowWrite: opts.allowWrite ?? false,\n credentialsManager,\n profile,\n };\n}\n\n/**\n * Create an authenticated command context.\n * Order: GRAVITY_RAIL_API_KEY → named/current profile store. Never auto-triggers OAuth.\n *\n * Dev accounts that used to be selected with `--realm` are now named profiles\n * (import with `gr auth import-dev` after provisioning).\n */\nexport async function createAuthenticatedContext(\n opts: GlobalOptions\n): Promise<AuthenticatedContext> {\n // oxlint-disable-next-line @eslint-react/naming-convention-context-name -- CLI handler context, not React\n const ctx = createContext(opts);\n\n // Credential-broker mode takes precedence: token lives in the root daemon,\n // not the env, so route through the loopback broker with no auth header.\n const brokerCtx = tryBrokerContext(ctx);\n if (brokerCtx) return brokerCtx;\n\n const auth = await resolveNonInteractiveAuth({\n env: ctx.env,\n envConfig: ctx.envConfig,\n credentialsManager: ctx.credentialsManager,\n profile: ctx.profile,\n });\n if (auth) return contextWithToken(ctx, auth);\n\n if (ctx.profile !== 'default') {\n throw new AuthRequiredError(\n `No credentials for profile \"${ctx.profile}\" (${ctx.env}). ` +\n `Run: gr auth login --name ${ctx.profile} or gr auth import-dev`\n );\n }\n throw new AuthRequiredError(\n 'Not authenticated. Run `gr login`, `gr auth import-dev` (local dev), or set GRAVITY_RAIL_API_KEY.'\n );\n}\n\n/**\n * Narrow a handler context to `AuthenticatedContext`.\n *\n * Handler `ctx` is typed as `AuthenticatedContext | CommandContext` so that\n * `requiresAuth: false` handlers can also share the type. At runtime, every\n * handler that did not opt out of auth will receive an `AuthenticatedContext`,\n * but TypeScript cannot verify this — call this helper before accessing\n * `apiClient` / `accessToken`.\n *\n * Throws if called from a handler that did not declare `requiresAuth`.\n */\nexport function requireAuth(ctx: AuthenticatedContext | CommandContext): AuthenticatedContext {\n if (!('apiClient' in ctx)) {\n throw new Error('Command handler accessed apiClient without declaring requiresAuth');\n }\n return ctx;\n}\n\n/** Create a base command context for the public CLI (defaults to prod) */\nexport function createPublicContext(opts: PublicGlobalOptions): CommandContext {\n // INVARIANT — the public `gr` CLI defaults to PROD. Public API consumers have NO access to\n // our dev/staging environments; prod is the only API they can reach, so an unset env MUST\n // resolve to prod. Do NOT change this to 'dev'/'staging' for internal convenience or to\n // satisfy a ticket claiming the prod default is a bug (see #15819 — the bug was the --help\n // text, not this default). Internal devs select a non-prod env with an explicit `--env`.\n const env = opts.env ?? 'prod';\n const envConfig = getEnvironmentConfig(env, {\n apiUrl: opts.apiUrl,\n frontendUrl: opts.frontendUrl,\n startDir: opts.startDir,\n });\n const credentialsManager = new CredentialsManager(homedir(), envConfig.apiUrl);\n const profile = credentialsManager.resolveProfileName(opts.profile, env);\n return {\n env,\n envConfig,\n outputFormat: detectOutputFormat(opts.outputFormat),\n jq: opts.jq,\n verbose: opts.verbose ?? false,\n allowWrite: opts.allowWrite ?? false,\n credentialsManager,\n profile,\n };\n}\n\n/** Create an authenticated context for the public CLI. Tries env var, then cached token. */\nexport async function createPublicAuthenticatedContext(\n opts: PublicGlobalOptions\n): Promise<AuthenticatedContext> {\n const ctx = createPublicContext(opts);\n\n // Credential-broker mode takes precedence: the scoped token lives in the root\n // daemon, not the env, so route through the loopback broker with no auth header.\n // `gr.ts` (the `gr` entry point) uses THIS function, so the code-interpreter\n // sandbox reaches the API through here — without this check the sandbox CLI\n // throws AuthRequiredError because the broker deliberately strips\n // GRAVITY_RAIL_API_KEY from `.gr-env`. Returns null outside the sandbox, so\n // standalone/public CLI behavior is unchanged.\n const brokerCtx = tryBrokerContext(ctx);\n if (brokerCtx) return brokerCtx;\n\n const auth = await resolveNonInteractiveAuth({\n env: ctx.env,\n envConfig: ctx.envConfig,\n credentialsManager: ctx.credentialsManager,\n profile: ctx.profile,\n });\n if (auth) return contextWithToken(ctx, auth);\n\n throw new AuthRequiredError();\n}\n","import { spawnSync } from 'node:child_process';\nimport { CLIError } from './errors';\n\n/**\n * Apply a jq filter to CLI output, in-process.\n *\n * Why this exists rather than telling callers to pipe: `gr … -o json | jq …`\n * puts the burden of building a valid pipeline on the caller, and that is where\n * it breaks. A forensic pass over 90 days of Workspace Manager chats found\n * `jq: parse error` in 49 of 392 chats (PR #22929) — the second most common\n * failure signature in the whole corpus. The agent pipes a table-formatted\n * listing into jq, or pipes a command that errored and emitted nothing, and jq\n * chokes on input the agent never inspected.\n *\n * `--jq` removes the failure mode rather than documenting around it: the filter\n * runs against the JSON *we* just serialised, so the input is valid by\n * construction and `-o json` is implied. A bad filter now produces one clear\n * error about the filter, instead of a parse error about bytes the caller\n * cannot see.\n *\n * We shell out to the system `jq` deliberately. A pure-JS reimplementation\n * would be a new dependency and a second dialect to keep in sync with the one\n * people already know; the sandbox and every developer machine has `jq` on\n * PATH. When it is genuinely missing we say so and name the fallback, rather\n * than silently emitting unfiltered JSON that a script would then misread.\n */\nexport function applyJqFilter(json: string, filter: string): string {\n // No try/catch: spawnSync reports a missing or unspawnable binary through\n // `result.error`, it does not throw for those cases. A catch here would be\n // unreachable for exactly the failures it claimed to handle.\n const result = spawnSync('jq', ['-r', filter], {\n input: json,\n encoding: 'utf8',\n maxBuffer: 64 * 1024 * 1024,\n });\n\n if (result.error && (result.error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new CLIError(\n '--jq requires the `jq` binary on PATH, and it was not found. ' +\n 'Install jq, or omit --jq and filter the JSON yourself.'\n );\n }\n // A filter jq cannot COMPILE makes it print the syntax error and exit\n // without ever reading stdin, so our write lands on a closed pipe and\n // spawnSync reports EPIPE in `error` *alongside* jq's real exit status. It is\n // a race at any input size — whether the write or jq's exit gets there first\n // — which is why checking `error` before `status` replaced jq's diagnostic\n // with a pipe error only intermittently, and read as an unrelated flake.\n // EPIPE together with an exit status is therefore not a spawn failure; every\n // other `error` (ENOENT above, ENOBUFS from maxBuffer, a failed fork) is.\n const wroteToExitedJq =\n (result.error as NodeJS.ErrnoException | undefined)?.code === 'EPIPE' &&\n result.status !== null;\n if (result.error && !wroteToExitedJq) {\n throw new CLIError(`--jq could not run jq: ${result.error.message}`);\n }\n if (result.status !== 0) {\n // jq's own diagnostic is the useful part — it names the position in the\n // filter. Prefixing it keeps the caller from reading it as a gr error.\n const exited = result.signal\n ? `jq was killed by ${result.signal}`\n : `jq exited ${result.status}`;\n const detail = (result.stderr || '').trim() || exited;\n throw new CLIError(`--jq filter failed: ${detail}`);\n }\n\n return (result.stdout || '').replace(/\\n$/, '');\n}\n","import { sandboxBrokerUrl } from './context';\n\nexport class CLIError extends Error {\n constructor(\n message: string,\n public exitCode: number = 1\n ) {\n super(message);\n this.name = 'CLIError';\n }\n}\n\nexport class AuthRequiredError extends CLIError {\n constructor(message = 'Not authenticated. Run `gr login` or set GRAVITY_RAIL_API_KEY.') {\n super(message, 2);\n this.name = 'AuthRequiredError';\n }\n}\n\n/**\n * What a 401 tells the caller to do.\n *\n * - `login`: the CLI holds no usable credential of its own; log in or set a key.\n * - `session_credential`: a code-interpreter sandbox, where the credential\n * broker holds the session's token. Logging in or setting a key cannot change\n * what that token allows, so the hint must not suggest it (an agent that read\n * \"run gr login\" went looking for another `gr` to run instead).\n */\nexport type UnauthorizedHint = 'login' | 'session_credential';\n\nexport function unauthorizedHint(): UnauthorizedHint {\n return sandboxBrokerUrl() ? 'session_credential' : 'login';\n}\n\nconst UNAUTHORIZED_HINT_TEXT: Record<UnauthorizedHint, string> = {\n login: 'Run \"gr login\" to authenticate, or set GRAVITY_RAIL_API_KEY for non-interactive use.',\n session_credential:\n \"This session's credential does not allow this request. Logging in or setting an API key does not change that. Organization commands are outside a workspace session.\",\n};\n\nexport function handleError(err: unknown): never {\n if (err instanceof CLIError) {\n process.stderr.write(`Error: ${err.message}\\n`);\n process.exit(err.exitCode);\n }\n\n if (err instanceof Error) {\n process.stderr.write(`Error: ${err.message}\\n`);\n if ('errors' in err && Array.isArray((err as any).errors)) {\n for (const e of (err as any).errors) {\n process.stderr.write(` - ${e}\\n`);\n }\n }\n if ('statusCode' in err && (err as any).statusCode === 401) {\n // The server's reason was written above; the hint only says what to do next.\n process.stderr.write(`\\nHint: ${UNAUTHORIZED_HINT_TEXT[unauthorizedHint()]}\\n`);\n }\n process.exit(1);\n }\n\n process.stderr.write(`Error: ${String(err)}\\n`);\n process.exit(1);\n}\n","import type { ArgDef, ParsedArgs } from './types';\nimport { CLIError } from './errors';\n\n// ── Response shape detection ─────────────────────────────────────────\n\n/** Metadata extracted from a paginated API response */\nexport interface PaginationMeta {\n /** Total number of items across all pages (page-based only) */\n total?: number;\n /** Current page number (page-based only) */\n page?: number;\n /** Total pages (page-based only) */\n totalPages?: number;\n /** Whether more pages exist (cursor-based only) */\n hasMore?: boolean;\n /** Cursor for next page (cursor-based only) */\n nextCursor?: string;\n}\n\n/** Explicit pagination contract passed from commands to outputData */\nexport interface ListResult {\n items: unknown[];\n meta?: PaginationMeta;\n supportsAll?: boolean;\n}\n\n/** Type guard: is the value a ListResult (explicit contract)? */\nexport function isListResult(data: unknown): data is ListResult {\n if (!data || typeof data !== 'object' || Array.isArray(data)) return false;\n const obj = data as Record<string, unknown>;\n return (\n Array.isArray(obj.items) &&\n ('supportsAll' in obj ||\n ('meta' in obj && (obj.meta === undefined || typeof obj.meta === 'object')))\n );\n}\n\n/** Check if a response looks like a page-based paginated envelope.\n * Matches both `{ items, total, totalPages, page }` (standard) and\n * `{ items, total, page, pageSize }` (legacy — e.g. InvitationListResponse,\n * InquiryListResponse). This is a pure type guard with no side effects;\n * totalPages computation for legacy shapes happens in extractPaginationMeta. */\nexport function isPagePaginatedResponse(data: unknown): data is {\n items: unknown[];\n total: number;\n page: number;\n totalPages?: number;\n pageSize?: number;\n} {\n if (!data || typeof data !== 'object') return false;\n const obj = data as Record<string, unknown>;\n if (!Array.isArray(obj.items) || typeof obj.page !== 'number') return false;\n\n // Standard shape: has totalPages\n if (typeof obj.totalPages === 'number') return true;\n\n // Legacy shape: has total + pageSize but no totalPages\n if (typeof obj.total === 'number' && typeof obj.pageSize === 'number') return true;\n\n return false;\n}\n\n/** Check if a response looks like a cursor-based paginated envelope */\nexport function isCursorPaginatedResponse(data: unknown): data is {\n items: unknown[];\n hasMore: boolean;\n nextCursor?: string;\n} {\n if (!data || typeof data !== 'object') return false;\n const obj = data as Record<string, unknown>;\n return Array.isArray(obj.items) && typeof obj.hasMore === 'boolean';\n}\n\n/** Check if a response is any paginated envelope ({ items: [...], ... }) */\nexport function isPaginatedResponse(data: unknown): boolean {\n return isPagePaginatedResponse(data) || isCursorPaginatedResponse(data);\n}\n\n/** Extract pagination metadata from a response, or return undefined for non-paginated responses.\n * For legacy shapes without totalPages, computes it from total/pageSize. */\nexport function extractPaginationMeta(data: unknown): PaginationMeta | undefined {\n if (isPagePaginatedResponse(data)) {\n const totalPages =\n data.totalPages ?? (data.pageSize ? Math.ceil(data.total / data.pageSize) : undefined);\n return {\n total: data.total,\n page: data.page,\n totalPages,\n };\n }\n if (isCursorPaginatedResponse(data)) {\n return {\n hasMore: data.hasMore,\n nextCursor: data.nextCursor,\n };\n }\n return undefined;\n}\n\n// ── Warning formatting ───────────────────────────────────────────────\n\n/** Format a pagination warning for stderr. Returns undefined if no warning needed.\n * When `supportsAll` is false, the \"Use --all\" hint is omitted because the\n * command does not actually expose the --all flag. */\nexport function formatPaginationWarning(\n meta: PaginationMeta | undefined,\n supportsAll: boolean = true\n): string | undefined {\n if (!meta) return undefined;\n\n const allHint = supportsAll ? ' Use --all to fetch all pages.' : '';\n\n // Page-based: warn when there are multiple pages\n if (meta.totalPages !== undefined && meta.totalPages > 1) {\n const pageNum = meta.page ?? 1;\n return `Showing page ${pageNum} of ${meta.totalPages} (${meta.total} total items).${allHint}`;\n }\n\n // Cursor-based: warn when more pages exist\n if (meta.hasMore === true) {\n return `More results available.${allHint}`;\n }\n\n return undefined;\n}\n\n// ── Unwrapping ───────────────────────────────────────────────────────\n\n/** Unwrap items from a paginated response or return the data as-is if it's an array */\nexport function unwrapItems(data: unknown): unknown[] {\n if (Array.isArray(data)) return data;\n if (\n data &&\n typeof data === 'object' &&\n 'items' in data &&\n Array.isArray((data as Record<string, unknown>).items)\n ) {\n return (data as Record<string, unknown>).items as unknown[];\n }\n return [data];\n}\n\n// ── Arg definitions ──────────────────────────────────────────────────\n\n/** Default pagination args for list commands (page, page-size, all). No search. */\nexport const LIST_PAGINATION_ARGS: ArgDef[] = [\n { name: 'page', description: 'Page number' },\n { name: 'page-size', description: 'Page size' },\n { name: 'all', description: 'Fetch all pages and return combined results', isFlag: true },\n];\n\n// ── Arg-to-options helpers ───────────────────────────────────────────\n\n/** Convert parsed CLI args to API pagination options */\nexport function parsePaginationArgs(args: ParsedArgs): {\n page?: number;\n pageSize?: number;\n all?: boolean;\n} {\n const result: { page?: number; pageSize?: number; all?: boolean } = {};\n\n if (args.all === true) {\n result.all = true;\n }\n\n if (args.page !== undefined) {\n const num = Number(args.page);\n if (isNaN(num) || num < 1) throw new CLIError('--page must be a positive integer');\n result.page = num;\n }\n\n if (args['page-size'] !== undefined) {\n const num = Number(args['page-size']);\n if (isNaN(num) || num < 1) throw new CLIError('--page-size must be a positive integer');\n if (num > 100) throw new CLIError('--page-size must be at most 100 (API limit)');\n result.pageSize = num;\n }\n\n return result;\n}\n\n// ── fetchAll helpers ─────────────────────────────────────────────────\n\nconst MAX_PAGE_SIZE = 100;\nconst MAX_PAGES = 200; // Safety limit to prevent infinite loops\n\n/**\n * Fetch all pages from a page-based paginated endpoint.\n * The fetcher receives { page, pageSize } and should return the raw API response.\n * Throws CLIError if MAX_PAGES is reached without exhausting all pages.\n */\nexport async function fetchAllPages(\n fetcher: (opts: { page: number; pageSize: number }) => Promise<unknown>\n): Promise<unknown[]> {\n const allItems: unknown[] = [];\n let page = 1;\n\n while (page <= MAX_PAGES) {\n const result = await fetcher({ page, pageSize: MAX_PAGE_SIZE });\n const items = unwrapItems(result);\n allItems.push(...items);\n\n // Use server metadata for termination\n const meta = extractPaginationMeta(result);\n if (meta?.totalPages !== undefined) {\n if (page >= meta.totalPages) break;\n } else if (!isPagePaginatedResponse(result)) {\n // Raw array or no metadata — single fetch is enough\n if (items.length < MAX_PAGE_SIZE) break;\n }\n\n if (page === MAX_PAGES) {\n throw new CLIError(\n `Reached maximum page limit (${MAX_PAGES}). Results may be incomplete.`\n );\n }\n\n page++;\n }\n\n return allItems;\n}\n\n/**\n * Fetch all pages from a cursor-based paginated endpoint.\n * The fetcher receives { cursor? } and should return the raw API response.\n * Throws CLIError if MAX_PAGES is reached without exhausting all pages.\n */\nexport async function fetchAllCursorPages(\n fetcher: (opts: { cursor?: string }) => Promise<unknown>\n): Promise<unknown[]> {\n const allItems: unknown[] = [];\n let cursor: string | undefined;\n let pages = 0;\n\n while (pages < MAX_PAGES) {\n const result = await fetcher({ cursor });\n const items = unwrapItems(result);\n allItems.push(...items);\n pages++;\n\n if (isCursorPaginatedResponse(result) && result.hasMore && result.nextCursor) {\n cursor = result.nextCursor;\n } else {\n break;\n }\n\n if (pages === MAX_PAGES) {\n throw new CLIError(\n `Reached maximum page limit (${MAX_PAGES}). Results may be incomplete.`\n );\n }\n }\n\n return allItems;\n}\n\n// ── ListResult factory ──────────────────────────────────────────────\n\n/**\n * Wrap a raw API response into a ListResult with explicit pagination metadata.\n * Works with both page-based and cursor-based responses, as well as plain arrays.\n *\n * @param data - Raw API response (paginated envelope or plain array)\n * @param supportsAll - Whether the calling command exposes --all\n */\nexport function listResult(data: unknown, supportsAll: boolean = false): ListResult {\n return {\n items: unwrapItems(data),\n meta: extractPaginationMeta(data),\n supportsAll,\n };\n}\n","import { printTable } from '../cli-utils';\nimport { applyJqFilter } from './jq';\nimport {\n type PaginationMeta,\n isListResult,\n extractPaginationMeta,\n formatPaginationWarning,\n unwrapItems,\n} from './pagination';\n\nexport type OutputFormat = 'json' | 'jsonl' | 'table';\n\nexport interface OutputOptions {\n outputFormat: OutputFormat;\n /**\n * jq filter applied to the serialised JSON before it reaches stdout.\n *\n * Setting this implies JSON output regardless of `outputFormat`: a filter\n * over a rendered table is meaningless, and silently filtering nothing is\n * worse than ignoring the flag. See `lib/jq.ts` for why the filter lives\n * here rather than in a shell pipe.\n */\n jq?: string;\n}\n\nexport interface TableColumn<T> {\n header: string;\n getValue: (item: T) => string;\n maxWidth?: number;\n}\n\n/** Write JSON to stdout, applying `opts.jq` when one was requested. */\nfunction writeJson(value: unknown, opts: OutputOptions, pretty = true): void {\n const json = pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value);\n if (opts.jq) {\n const filtered = applyJqFilter(json, opts.jq);\n process.stdout.write(filtered === '' ? '\\n' : filtered + '\\n');\n return;\n }\n process.stdout.write(json + '\\n');\n}\n\n/** Detect default output format based on whether stdout is a TTY */\nexport function detectOutputFormat(explicit?: string): OutputFormat {\n if (explicit) return explicit as OutputFormat;\n return process.stdout.isTTY ? 'table' : 'json';\n}\n\n/**\n * Write a list of items to stdout in the requested format.\n *\n * Accepts:\n * - A `ListResult` (explicit contract with items, meta, supportsAll) — preferred.\n * - Raw arrays, paginated responses ({ items: [...] }), or any object — legacy.\n *\n * When a `ListResult` is passed, its explicit `meta` and `supportsAll` are used.\n * When raw data is passed, pagination metadata is auto-detected with\n * `supportsAll: false` as the safe default.\n *\n * The optional `paginationMeta` and `supportsAll` parameters are kept for\n * backward compatibility but are ignored when a `ListResult` is passed.\n */\nexport function outputData(\n data: unknown,\n opts: OutputOptions,\n columns?: TableColumn<any>[],\n paginationMeta?: PaginationMeta,\n supportsAll?: boolean\n): void {\n let items: unknown[];\n let meta: PaginationMeta | undefined;\n let allSupported: boolean;\n\n if (isListResult(data)) {\n // Explicit contract: use ListResult fields directly\n items = data.items;\n meta = data.meta;\n allSupported = data.supportsAll ?? false;\n } else {\n // Legacy path: auto-detect from raw data\n items = unwrapItems(data);\n meta = paginationMeta ?? extractPaginationMeta(data);\n allSupported = supportsAll ?? false;\n }\n\n const warning = formatPaginationWarning(meta, allSupported);\n if (warning) {\n process.stderr.write(warning + '\\n');\n }\n\n if (opts.jq) {\n writeJson(items, opts);\n return;\n }\n\n switch (opts.outputFormat) {\n case 'json':\n writeJson(items, opts);\n break;\n case 'jsonl':\n for (const item of items) {\n process.stdout.write(JSON.stringify(item) + '\\n');\n }\n break;\n case 'table':\n if (columns) {\n printTable(items, columns);\n } else {\n writeJson(items, opts);\n }\n break;\n }\n}\n\n/** Write a single object to stdout in the requested format */\nexport function outputSingle<T>(data: T, opts: OutputOptions, columns?: TableColumn<T>[]): void {\n if (opts.jq) {\n writeJson(data, opts);\n return;\n }\n\n switch (opts.outputFormat) {\n case 'json':\n writeJson(data, opts);\n break;\n case 'jsonl':\n process.stdout.write(JSON.stringify(data) + '\\n');\n break;\n case 'table':\n if (columns) {\n printTable([data], columns);\n } else {\n writeJson(data, opts);\n }\n break;\n }\n}\n\n/** Common column factory helpers for domain files.\n *\n * GR app-facing API wire is camelCase. First-party consumers (CLI, lambdas we\n * own) read that shape only — no snake_case dual-read \"bandaid\". When the API\n * flips a key, convert the consumer; do not carry both. (#19305)\n */\nexport const COL = {\n id: (): TableColumn<any> => ({ header: 'ID', getValue: (item) => String(item.id ?? '') }),\n uuid: (): TableColumn<any> => ({ header: 'UUID', getValue: (item) => item.uuid ?? '' }),\n name: (): TableColumn<any> => ({ header: 'NAME', getValue: (item) => item.name ?? '' }),\n status: (): TableColumn<any> => ({ header: 'STATUS', getValue: (item) => item.status ?? '' }),\n created: (): TableColumn<any> => ({\n header: 'CREATED',\n getValue: (item) => item.createdAt ?? '',\n }),\n updated: (): TableColumn<any> => ({\n header: 'UPDATED',\n getValue: (item) => item.updatedAt ?? '',\n }),\n description: (): TableColumn<any> => ({\n header: 'DESCRIPTION',\n getValue: (item) => item.description ?? '',\n }),\n enabled: (): TableColumn<any> => ({\n header: 'ENABLED',\n getValue: (item) => String(item.enabled ?? ''),\n }),\n};\n\n/**\n * Print a follow-on suggestion under the result, table output only.\n *\n * Suppressed for json/jsonl so machine consumers get parseable output — a hint\n * written to stdout would corrupt it.\n */\nexport function hint(opts: { outputFormat?: string }, lines: string[]): void {\n if ((opts.outputFormat ?? 'table') !== 'table') return;\n process.stdout.write('\\n' + lines.join('\\n') + '\\n');\n}\n\n/** Write a status/progress message to stderr (never pollutes stdout) */\nexport function stderr(msg: string): void {\n process.stderr.write(msg + '\\n');\n}\n\n/**\n * Wait until everything written to stdout has actually reached the OS.\n *\n * Call this before `process.exit()`. `process.exit` does not flush a pending\n * asynchronous write, and stdout **is** asynchronous whenever it is a pipe\n * (Node only makes it synchronous for files and TTYs), so a large piped payload\n * is silently cut at the pipe buffer — 8KB on Linux, 64KB elsewhere.\n *\n * `writableNeedDrain` is the wrong probe and was the bug: it only goes true\n * once the buffered amount exceeds `highWaterMark` (16KB by default). A 10KB\n * JSON document sits fully buffered with `needDrain === false`, so the guard\n * passed and `process.exit` discarded the tail. Observed as\n * `json.decoder.JSONDecodeError: Expecting ':' delimiter` at exactly char 8192\n * in a script reading `gr admin workspaces list -o json` through a pipe, while\n * the same command redirected to a file was complete and valid.\n *\n * The reliable signal is the write callback, which fires only after the data is\n * handed off. An empty write queues behind whatever is already pending, so its\n * callback is a barrier for all of it.\n */\nexport async function flushStdout(): Promise<void> {\n if (process.stdout.writableLength === 0) return;\n await new Promise<void>((resolve) => {\n process.stdout.write('', () => resolve());\n });\n}\n","/**\n * CLI handler for organization-level authentication challenges (GRA-6994/6995).\n *\n * When a workspace API call returns a 401 with WWW-Authenticate: Bearer realm=\"org\",\n * the SDK calls this handler. The CLI satisfies the challenge, in order:\n *\n * 1. Cached org session — a `gr_sess_` captured on a prior invocation and stored\n * under the profile. Replayed once as `X-Org-Session`; no browser. A rejected\n * candidate or a request for stronger authentication proceeds to fresh sign-in.\n * 2. Non-SSO direct join — `POST /o/{org}/join` with the account bearer token,\n * reading the org session from the response body's `orgSession` (orgs that\n * allow internal auth; the API sets no cookie for a bearer client). Result\n * is cached like (1).\n * 3. SSO browser step-up (loopback callback, RFC 8252) — open the org SSO URL in\n * the browser with a `return_to` pointing at the `/cli/org-auth` bridge page,\n * which redirects a single-use PKCE code back to a one-time `127.0.0.1`\n * listener the CLI runs. The CLI redeems the code over its authenticated API connection and caches the session like (1). Interactive\n * (profile) contexts only.\n * 4. Headless / non-interactive — throw a clear hint (use `gr login` or an API key).\n */\n\nimport { createServer } from 'http';\nimport { execFile } from 'child_process';\nimport { createHash, randomBytes } from 'crypto';\nimport type { AddressInfo } from 'net';\nimport type { GravityRailClient } from '@gravity-rail/sdk';\nimport type { OrgAuthInfo, OrgAuthSessionCandidate } from '@gravity-rail/sdk';\nimport type { CredentialsManager } from '../cli-utils';\nimport { stderr } from './output';\nimport { isOrgSessionCredential } from './org-session';\n\n/** A successful response that does not satisfy the sign-in contract. */\nclass OrgSignInResponseError extends Error {}\n\nconst ORG_AUTH_TIMEOUT_MS = 5 * 60 * 1000;\n\n/**\n * Cache captured SSO sessions conservatively under the server's 7-day org\n * session TTL (`ORG_SCOPED_SESSION_TTL_SECONDS`) so a cached session is\n * refreshed by a fresh step-up before it can 401 mid-command.\n */\nconst ORG_SESSION_CACHE_TTL_MS = 6.5 * 24 * 60 * 60 * 1000;\n\n/** Bridge page path on the frontend host that relays the org session to loopback. */\nconst CLI_ORG_AUTH_BRIDGE_PATH = '/cli/org-auth';\n\n/** Canonical UUID shape for the org id carried in the 401 challenge. */\nconst ORG_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/**\n * Context the org-auth handler needs to cache sessions and decide whether an\n * interactive browser step-up is permitted.\n */\nexport interface OrgAuthContext {\n /** Present for profile (login) contexts; absent for API-key / broker. */\n credentialsManager?: CredentialsManager;\n env: string;\n profile?: string;\n /** Configured frontend origin — the exact host the org SSO URL must live on. */\n frontendUrl?: string;\n /**\n * Whether a browser step-up may be launched. False for non-interactive\n * contexts (code-interpreter broker, CI) — those get the headless hint.\n */\n interactive: boolean;\n}\n\n/**\n * Attempt to satisfy an org auth challenge via the direct join endpoint.\n * Returns the org session credential on success, null when SSO is required.\n * Throws on unexpected network / server errors.\n */\nasync function tryDirectJoin(\n apiUrl: string,\n accessToken: string,\n orgAuthInfo: OrgAuthInfo\n): Promise<{ session: string; expiresAt?: string } | null> {\n const response = await fetch(`${apiUrl}/api/v2/o/${orgAuthInfo.orgUuid}/join`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${accessToken}`,\n },\n body: '{}',\n });\n\n if (response.status === 400) {\n // Org requires SSO — direct join is not permitted for this account\n return null;\n }\n\n if (!response.ok) {\n // Don't include the response body — the backend currently returns safe\n // JSON, but a future change could put PHI or other sensitive data there.\n // Status code is sufficient to disambiguate the failure mode.\n throw new Error(`Org join failed (HTTP ${response.status})`);\n }\n\n // The API sets no cookie for a bearer client: the org session comes back in\n // the body, and the CLI replays it as `X-Org-Session`.\n let body: { orgSession?: unknown; expiresAt?: unknown };\n try {\n body = (await response.json()) as { orgSession?: unknown; expiresAt?: unknown };\n } catch {\n throw new OrgSignInResponseError('Org join succeeded but returned an invalid response');\n }\n if (!body || typeof body !== 'object' || Array.isArray(body)) {\n throw new OrgSignInResponseError('Org join succeeded but returned an invalid response');\n }\n if (typeof body.orgSession !== 'string' || !body.orgSession) {\n throw new OrgSignInResponseError('Org join succeeded but returned no org session');\n }\n let expiresAt: string | undefined;\n if (body.expiresAt !== undefined) {\n if (typeof body.expiresAt !== 'string' || !Number.isFinite(Date.parse(body.expiresAt))) {\n throw new OrgSignInResponseError('Org join returned an invalid session expiry');\n }\n expiresAt = body.expiresAt;\n if (Date.parse(expiresAt) <= Date.now()) {\n throw new OrgSignInResponseError('Org join returned an expired session');\n }\n }\n return { session: body.orgSession, expiresAt };\n}\n\n/**\n * Validate that an auth URL is safe to hand to the OS URL opener.\n *\n * `open` / `xdg-open` / `cmd.exe start` will follow any URI scheme the OS\n * registers — including `file://`, `javascript:`, and custom app handlers —\n * so a compromised/MITMed server returning an attacker-controlled `authUrl`\n * could trigger arbitrary URI execution. Restrict to http(s) and require\n * the same parent domain as the configured API host (e.g. SSO login on\n * `app.gravityrail.com` is allowed when the API is `api.gravityrail.com`,\n * but `attacker.example` against `api.gravityrail.com` is rejected).\n *\n * \"Same parent domain\" is a last-2-labels match. This is a heuristic — it\n * does not consult the Public Suffix List, so `foo.co.uk` and `bar.co.uk`\n * would falsely match — but Gravity Rail's auth hosts do not live under\n * those ccTLDs. The auth host is always the configured frontend host\n * (backend `build_org_auth_url` uses `SYSTEM_CONFIG.frontend_url`), so we\n * match it EXACTLY against the known API + frontend hosts rather than any\n * subdomain heuristic — a last-2-labels match would admit\n * `evil.gravityrail.com`. Both `apiUrl` and `frontendUrl` are trust anchors\n * derived from the CLI's own env config, not from the server response.\n */\nfunction isAllowedAuthUrl(url: string, apiUrl: string, frontendUrl?: string): boolean {\n try {\n const parsed = new URL(url);\n if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') return false;\n const allowedHosts = [apiUrl, frontendUrl]\n .filter((u): u is string => Boolean(u))\n .map((u) => {\n try {\n return new URL(u).hostname;\n } catch {\n return undefined;\n }\n })\n .filter((h): h is string => Boolean(h));\n return allowedHosts.includes(parsed.hostname);\n } catch {\n return false;\n }\n}\n\n/** Open a URL in the system browser (cross-platform). */\nfunction openBrowser(url: string): void {\n let command: string;\n let args: string[];\n\n if (process.platform === 'darwin') {\n command = 'open';\n args = [url];\n } else if (process.platform === 'win32') {\n command = 'cmd.exe';\n args = ['/c', 'start', '', url];\n } else {\n command = 'xdg-open';\n args = [url];\n }\n\n execFile(command, args, (_err) => {\n // Failure is non-fatal — the URL is printed to stderr so the user can open it manually.\n });\n}\n\n/**\n * Non-interactive when there is no way to complete a browser step-up: an\n * explicit opt-out, or a Linux session with no display server. macOS/Windows\n * always have a windowing system available to `open`/`start`.\n */\nfunction isHeadless(): boolean {\n if (process.env.GRAVITY_RAIL_NO_BROWSER) return true;\n if (process.platform === 'linux') {\n return !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY;\n }\n return false;\n}\n\ninterface OrgSessionCapture {\n /** Resolves with the ephemeral bound loopback port once the server is listening. */\n ready: Promise<number>;\n /** Resolves with the code delivered by the browser navigation. */\n session: Promise<string>;\n close: () => void;\n}\n\n/** A loopback navigation listener. It accepts only a code with this flow's state and org. */\nexport function startOrgSessionCapture(\n expectedState: string,\n expectedOrgUuid: string,\n _allowedOrigin: string\n): OrgSessionCapture {\n let resolveSession!: (value: string) => void;\n let rejectSession!: (reason: Error) => void;\n const session = new Promise<string>((resolve, reject) => {\n resolveSession = resolve;\n rejectSession = reject;\n });\n\n const server = createServer((req, res) => {\n res.setHeader('Cache-Control', 'no-store');\n res.setHeader('Referrer-Policy', 'no-referrer');\n if (req.method !== 'GET') {\n res.writeHead(405);\n res.end();\n return;\n }\n const callback = new URL(req.url ?? '/', 'http://127.0.0.1');\n const code = callback.searchParams.get('code');\n if (\n callback.pathname !== '/' ||\n !code?.startsWith('gr_cli_org_') ||\n callback.searchParams.get('state') !== expectedState ||\n callback.searchParams.get('org_uuid') !== expectedOrgUuid\n ) {\n res.writeHead(400);\n res.end('Invalid sign-in callback');\n return;\n }\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('Return to the terminal to finish sign-in.');\n resolveSession(code);\n });\n\n let resolveReady!: (port: number) => void;\n let rejectReady!: (reason: Error) => void;\n const ready = new Promise<number>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n\n server.on('error', (err) => {\n rejectReady(err);\n rejectSession(err);\n });\n server.listen(0, '127.0.0.1', () => {\n // Inside the 'listening' callback address() is always the bound AddressInfo.\n resolveReady((server.address() as AddressInfo).port);\n });\n\n const timeout = setTimeout(() => {\n rejectSession(\n new Error(\n 'Organization authentication timed out.\\n' +\n 'Complete sign-in in the browser, then re-run the command.'\n )\n );\n }, ORG_AUTH_TIMEOUT_MS);\n timeout.unref();\n\n // Idempotent — the caller's finally and any test both call close(); a second\n // server.close() would otherwise error on an already-closed server.\n let closed = false;\n const close = (): void => {\n if (closed) return;\n closed = true;\n clearTimeout(timeout);\n server.close();\n };\n\n return { ready, session, close };\n}\n\n/** Build the browser URL: the org SSO auth URL with a return_to to the bridge. */\nexport function buildStepUpUrl(\n authUrl: string,\n orgUuid: string,\n port: number,\n state: string,\n challenge: string\n): string {\n const url = new URL(authUrl);\n // Encode the inner bridge query with URLSearchParams so org/port/state can't\n // break out of their params, then set the whole relative return_to (the\n // callback sanitizes it relative-only — open-redirect guard — and\n // URLSearchParams.set percent-encodes the outer value).\n const bridgeQuery = new URLSearchParams({ org: orgUuid, port: String(port), state, challenge });\n url.searchParams.set('return_to', `${CLI_ORG_AUTH_BRIDGE_PATH}?${bridgeQuery.toString()}`);\n return url.toString();\n}\n\n/** Randomised state nonce binding the browser flow to this CLI process. */\nfunction newStateNonce(): string {\n return randomBytes(16).toString('hex');\n}\n\n/**\n * Complete an SSO org challenge via the browser + loopback bridge.\n * Returns the captured `gr_sess_` org session.\n */\nasync function stepUpViaBrowser(\n orgAuthInfo: OrgAuthInfo,\n apiUrl: string,\n accessToken: string\n): Promise<string> {\n // Precondition: the caller has already validated authUrl via isAllowedAuthUrl.\n const state = newStateNonce();\n const verifier = randomBytes(32).toString('base64url');\n const challenge = createHash('sha256').update(verifier).digest('base64url');\n const allowedOrigin = new URL(orgAuthInfo.authUrl).origin;\n const capture = startOrgSessionCapture(state, orgAuthInfo.orgUuid, allowedOrigin);\n\n try {\n const port = await capture.ready;\n const stepUpUrl = buildStepUpUrl(\n orgAuthInfo.authUrl,\n orgAuthInfo.orgUuid,\n port,\n state,\n challenge\n );\n stderr(`\\nThis workspace requires organization SSO authentication.`);\n stderr(`Opening browser to complete sign-in...`);\n stderr(` ${stepUpUrl}\\n`);\n stderr(`If the browser does not open, visit the URL above manually.`);\n openBrowser(stepUpUrl);\n const code = await capture.session;\n const response = await fetch(`${apiUrl}/api/v2/auth/cli-org-handoff/redeem`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${accessToken}` },\n body: JSON.stringify({ orgUuid: orgAuthInfo.orgUuid, code, verifier }),\n });\n if (!response.ok)\n throw new Error(`Could not finish organization sign-in (${response.status}).`);\n let result: { orgSession?: unknown };\n try {\n result = (await response.json()) as { orgSession?: unknown };\n } catch {\n throw new OrgSignInResponseError('Invalid organization sign-in response.');\n }\n if (!result || !isOrgSessionCredential(result.orgSession)) {\n throw new OrgSignInResponseError('Invalid organization sign-in response.');\n }\n return result.orgSession;\n } finally {\n capture.close();\n }\n}\n\n/**\n * Register a CLI org-auth handler on the given client.\n *\n * See the module docstring for the resolution order (cache → non-SSO join →\n * SSO browser step-up → headless hint). Captured sessions are cached under the\n * profile (when a credentials manager is provided). The returned candidate lets\n * the SDK adopt it only if the original authentication context still owns the\n * request (Node.js has no document.cookie).\n */\nexport function registerOrgAuthHandler(\n apiClient: GravityRailClient,\n apiUrl: string,\n accessToken: string,\n orgAuthCtx?: OrgAuthContext\n): void {\n apiClient.setOrgAuthHandler(\n async (orgAuthInfo: OrgAuthInfo): Promise<OrgAuthSessionCandidate> => {\n const orgUuid = orgAuthInfo.orgUuid;\n // The org id is server-supplied (parsed from the challenge header). Reject\n // anything that is not a canonical UUID before it flows into a join URL\n // path or the bridge return_to query.\n if (!ORG_UUID_RE.test(orgUuid)) {\n throw new Error('Invalid organization id in auth challenge');\n }\n const cm = orgAuthCtx?.credentialsManager;\n\n // An asynchronous sign-in must not overwrite a newer cached login.\n const initialCachedSession =\n cm && orgAuthCtx\n ? cm.getOrgSession(orgAuthCtx.env, orgAuthCtx.profile, orgUuid)\n : undefined;\n\n // Return the newly issued candidate for conditional SDK adoption. Persist\n // it only while this flow still owns the profile's cache entry.\n const adopt = (session: string, expiresAt?: string): OrgAuthSessionCandidate => {\n // Validate before persistence; SDK adoption is a later boundary and\n // must not leave a malformed server response in the profile cache.\n if (!isOrgSessionCredential(session)) {\n throw new OrgSignInResponseError('Invalid organization sign-in response.');\n }\n if (\n cm &&\n orgAuthCtx &&\n expiresAt &&\n cm.getOrgSession(orgAuthCtx.env, orgAuthCtx.profile, orgUuid) ===\n initialCachedSession\n ) {\n cm.setOrgSession(orgAuthCtx.env, orgAuthCtx.profile, orgUuid, session, expiresAt);\n }\n return {\n session,\n orgUuid,\n source: 'new',\n onRejected: () => {\n if (cm && orgAuthCtx)\n cm.removeOrgSession(orgAuthCtx.env, orgAuthCtx.profile, orgUuid, session);\n },\n };\n };\n\n // 1. Try a cache candidate only before any rejection/stronger-context\n // challenge. The actual API request validates it against live policy.\n if (cm && orgAuthCtx && !orgAuthInfo.sessionRejected && !orgAuthInfo.acrValues?.length) {\n const cached = cm.getOrgSession(orgAuthCtx.env, orgAuthCtx.profile, orgUuid);\n if (cached) {\n return {\n session: cached,\n orgUuid,\n source: 'cache',\n onRejected: () => {\n cm.removeOrgSession(orgAuthCtx.env, orgAuthCtx.profile, orgUuid, cached);\n },\n };\n }\n }\n\n // 2. Non-SSO direct join.\n let orgSession: Awaited<ReturnType<typeof tryDirectJoin>> = null;\n try {\n orgSession = await tryDirectJoin(apiUrl, accessToken, orgAuthInfo);\n } catch (err) {\n if (err instanceof OrgSignInResponseError) throw err;\n const msg = err instanceof Error ? err.message : String(err);\n stderr(`Warning: org direct-join failed (${msg}); trying browser sign-in`);\n }\n if (orgSession !== null) {\n // A missing expiry permits this command, without inventing a\n // lifetime for a reusable cache entry. Contract failures are final.\n return adopt(orgSession.session, orgSession.expiresAt);\n }\n\n // 3./4. SSO org — browser step-up when interactive, else the headless hint.\n if (!orgAuthCtx?.interactive || isHeadless()) {\n throw new Error(\n 'This workspace’s organization requires SSO sign-in, which needs a browser.\\n' +\n 'Run an interactive `gr` command on a machine with a browser to sign in once ' +\n '(the session is then cached), or use an API key for non-interactive use:\\n' +\n ' export GRAVITY_RAIL_API_KEY=<key> (see: gr api-keys)'\n );\n }\n\n // Validate the auth URL against the exact configured API + frontend hosts\n // before opening it, so a hostile/MITM'd URL can't pivot the OS opener.\n if (!isAllowedAuthUrl(orgAuthInfo.authUrl, apiUrl, orgAuthCtx.frontendUrl)) {\n throw new Error(\n `Refusing to open organization auth URL: host does not match the configured API/frontend host. ` +\n `Re-run with the expected --api-url, or contact support.`\n );\n }\n\n const session = await stepUpViaBrowser(orgAuthInfo, apiUrl, accessToken);\n return adopt(session, new Date(Date.now() + ORG_SESSION_CACHE_TTL_MS).toISOString());\n }\n );\n}\n","/**\n * Sandbox adapter for Gravity Rail code-interpreter environments.\n *\n * This package only adapts sandbox-provided GRAVITY_RAIL_* environment values\n * to the official @gravity-rail/sdk surface. API methods and builder classes\n * live in the SDK.\n */\nimport {\n GravityRailClient,\n WorkspaceBuilder,\n runWorkspaceScript,\n type File as GravityRailFile,\n type GravityRailWorkspaceClient,\n type UploadFileData,\n} from '@gravity-rail/sdk';\nimport { readSandboxEnv, type SandboxEnv } from './env';\nimport { createSandboxFetch } from './sandbox-fetch';\n\nexport { readSandboxEnv } from './env';\nexport { createUnixBrokerFetch } from './unix-broker-fetch';\nexport type { SandboxEnv } from './env';\nexport { askUser } from './ask-user';\nexport type {\n AskAnswer,\n AskRejected,\n AskChoice,\n AskField,\n AskFieldType,\n AskSpec,\n AskSubmitted,\n AskUnavailable,\n} from './ask-user';\nexport {\n MAX_SAY_CHARS,\n SAY_FIELD,\n ask,\n clearHighlight,\n highlight,\n navigate,\n point,\n say,\n sayAskSpec,\n ui,\n} from './ui';\nexport type { HighlightOptions, SayOptions } from './ui';\nexport { Flow, FlowExit, runFlow } from './flow';\nexport type { FlowAskResult, FlowDefinition, FlowMeta, FlowRejection, FlowScope } from './flow';\nexport type { SandboxAuditHeaders } from './sandbox-fetch';\nexport {\n ELEVATION_MARKER_FILENAME,\n GrElevationRequired,\n createSandboxFetch,\n withAuditHeaders,\n withElevationInterceptor,\n} from './sandbox-fetch';\nexport type { SandboxFetchEnv } from './sandbox-fetch';\nexport {\n AgentBuilder,\n ApplyError,\n FormBuilder,\n GravityRailClient,\n JourneyBuilder,\n MemberFilterBuilder,\n MemberLabelBuilder,\n NotificationRuleBuilder,\n RoutineBuilder,\n TaskBuilder,\n WorkspaceBuilder,\n WorkflowBuilder,\n runWorkspaceScript,\n toSafeMemberImportPreview,\n toSafeMemberImportSummary,\n type GravityRailWorkspaceClient,\n} from '@gravity-rail/sdk';\n\nexport function createSdkClient(env: SandboxEnv = readSandboxEnv()): GravityRailClient {\n // Point the SDK at the loopback broker with NO auth header (undefined apiKey ⇒\n // BaseApiClient skips Authorization); the broker injects the real Bearer\n // token. No DNS pin — the broker is on 127.0.0.1, not the API host.\n return new GravityRailClient(\n undefined,\n env.brokerUrl,\n createSandboxFetch({\n chatId: env.chatId,\n sessionId: env.sessionId,\n toolCallId: env.toolCallId,\n })\n );\n}\n\nexport function createSandboxClient(\n env: SandboxEnv = readSandboxEnv()\n): GravityRailWorkspaceClient {\n if (!env.workspaceUuid) throw new Error('Workspace operations require a workspace Job');\n return createSdkClient(env).workspace(env.workspaceUuid);\n}\n\nexport function createWorkspaceBuilder(env: SandboxEnv = readSandboxEnv()): WorkspaceBuilder {\n return new WorkspaceBuilder(createSandboxClient(env));\n}\n\nexport function fileDownloadUrl(\n file: Pick<GravityRailFile, 'id' | 'filename'>,\n env: SandboxEnv = readSandboxEnv()\n): string {\n if (!env.workspaceUuid) throw new Error('Workspace files require a workspace Job');\n return `/api/v2/w/${env.workspaceUuid}/files/${file.id}/contents/${encodeURIComponent(file.filename)}`;\n}\n\n/** Call a platform operation under the current Job's immutable authorization. */\nexport async function requestJobTool(\n name: string,\n args: Record<string, unknown>,\n env: SandboxEnv = readSandboxEnv(),\n requestId: string = crypto.randomUUID()\n): Promise<unknown> {\n if (!env.jobUuid || !env.jobBrokerPath)\n throw new Error('This computer has no active Job broker');\n const response = await createSandboxFetch(env)(`${env.brokerUrl}${env.jobBrokerPath}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ requestId, name, args }),\n });\n if (!response.ok) throw new Error(`Job operation was refused (${response.status})`);\n return response.json();\n}\n\nexport async function saveToChat(\n filename: string,\n data: UploadFileData,\n mimeType = 'application/octet-stream',\n env: SandboxEnv = readSandboxEnv()\n): Promise<GravityRailFile> {\n if (env.chatFolderId === undefined) {\n throw new Error('Sandbox file delivery failed - GRAVITY_RAIL_CHAT_FOLDER_ID is not set');\n }\n\n return createSandboxClient(env).uploadFile({\n filename,\n data,\n mimeType,\n folderId: env.chatFolderId,\n overwrite: true,\n });\n}\n\nexport async function displayFile(\n filename: string,\n data: UploadFileData,\n mimeType = 'application/octet-stream',\n env: SandboxEnv = readSandboxEnv()\n): Promise<GravityRailFile> {\n const file = await saveToChat(filename, data, mimeType, env);\n const label = escapeMarkdownLabel(filename);\n const url = fileDownloadUrl(file, env);\n (globalThis as { console?: { log: (message: string) => void } }).console?.log(\n mimeType.startsWith('image/') ? `` : `[${label}](${url})`\n );\n return file;\n}\n\nexport function runScript(\n build: (workspace: WorkspaceBuilder) => void | Promise<void>,\n mode = 'plan',\n env: SandboxEnv = readSandboxEnv()\n): Promise<unknown> {\n return runWorkspaceScript(createSandboxClient(env), build, mode);\n}\n\nfunction escapeMarkdownLabel(value: string): string {\n return value.replace(/[\\\\[\\]]/g, '\\\\$&');\n}\n","/**\n * Sandbox environment: the GRAVITY_RAIL_* values the runtime injects.\n *\n * Split out of index.ts so modules that only need the env (askUser) do not\n * import the whole adapter surface — the cycle that would otherwise create is\n * silent under ESM and shows up as an undefined import at run time.\n */\nexport interface SandboxEnv {\n workspaceUuid?: string;\n jobUuid?: string;\n organizationId?: number;\n agentId?: number;\n jobBrokerPath?: string;\n /**\n * Loopback URL of the credential broker — the sandbox's ONLY route to the\n * API. The scoped token is never in the sandbox env: requests go here with NO\n * auth header and the root daemon injects `Authorization: Bearer <token>` and\n * forwards to the API. Always present.\n *\n * The real API origin is deliberately NOT exposed to sandbox code. Under\n * VPC-only egress a direct call to it cannot succeed (public DNS resolves the\n * internet-facing ALB, which the VM has no route to), so knowing the URL only\n * invites requests that hang until they time out.\n */\n brokerUrl: string;\n chatFolderId?: number;\n chatId?: number;\n /**\n * The acting Member — whoever's turn caused this script to run. Lets a script\n * partition its own state per member (`state/member-<id>.json`) and stamp who\n * wrote a record, without a round-trip to ask the API \"who am I\".\n *\n * OPTIONAL on purpose, even though the runtime always emits it: a script run\n * outside a member session (a bare `node script.ts` in a dev shell, a unit\n * test constructing an explicit env) has no acting member, and making this\n * required would turn those into a bootstrap throw. Branch on `undefined`\n * rather than defaulting to 0 — a wrong-but-present id silently mixes two\n * members' state files, which is worse than having none.\n *\n * Not an authorization input: the broker's scoped token is what the API\n * checks, and it is minted for this same member. Reading this value cannot\n * widen what a script may do.\n */\n memberId?: number;\n sessionId?: string;\n toolCallId?: string;\n}\n\ntype SandboxGlobal = typeof globalThis & {\n __GRAVITY_RAIL_SANDBOX_ENV__?: SandboxEnv;\n};\n\nfunction requiredEnv(name: string): string {\n const value = typeof process !== 'undefined' ? process.env[name] : undefined;\n if (!value) {\n throw new Error(`Sandbox bootstrap failed - missing env var: ${name}`);\n }\n return value;\n}\n\nfunction optionalInt(name: string): number | undefined {\n const raw = typeof process !== 'undefined' ? process.env[name] : undefined;\n if (!raw) return undefined;\n const parsed = Number(raw);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\nfunction readProcessEnv(): SandboxEnv {\n const workspaceUuid = process.env.GRAVITY_RAIL_WORKSPACE_UUID;\n const jobUuid = process.env.GRAVITY_RAIL_JOB_UUID;\n const organizationId = optionalInt('GRAVITY_RAIL_ORGANIZATION_ID');\n const agentId = optionalInt('GRAVITY_RAIL_AGENT_ID');\n if (!workspaceUuid && !(jobUuid && organizationId && agentId)) {\n requiredEnv('GRAVITY_RAIL_WORKSPACE_UUID');\n }\n return {\n workspaceUuid,\n jobUuid,\n organizationId,\n agentId,\n jobBrokerPath: process.env.GRAVITY_RAIL_JOB_BROKER_PATH,\n // The token is held by the broker, not the env; the broker URL is required.\n brokerUrl: requiredEnv('GRAVITY_RAIL_BROKER_URL'),\n chatFolderId: optionalInt('GRAVITY_RAIL_CHAT_FOLDER_ID'),\n chatId: optionalInt('GRAVITY_RAIL_CHAT_ID'),\n memberId: optionalInt('GRAVITY_RAIL_MEMBER_ID'),\n sessionId: typeof process !== 'undefined' ? process.env.GRAVITY_RAIL_SESSION_ID : undefined,\n toolCallId:\n typeof process !== 'undefined' ? process.env.GRAVITY_RAIL_TOOL_CALL_ID : undefined,\n };\n}\n\nexport function readSandboxEnv(explicit?: SandboxEnv): SandboxEnv {\n if (explicit) return explicit;\n const globalEnv = (globalThis as SandboxGlobal).__GRAVITY_RAIL_SANDBOX_ENV__;\n if (globalEnv) return globalEnv;\n return readProcessEnv();\n}\n","/**\n * Audit headers + scope-elevation interception for code-interpreter sandboxes.\n *\n * Sandbox code has exactly one outbound destination: the loopback credential\n * broker. There is no DNS pin here any more — the private-ALB pin only ever\n * existed because sandbox clients used to dial the API host directly, and they\n * no longer can (the API origin is not exposed to uid 1000 at all; the root\n * daemon holds it and applies the pin on the far side of the broker).\n */\n\nimport { writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { createUnixBrokerFetch } from './unix-broker-fetch';\n\n/**\n * Control marker filename the sandbox agent reads + deletes after each exec\n * (mirrors microvm/agent.py ELEVATION_MARKER_FILENAME). See GRA-6895.\n */\nexport const ELEVATION_MARKER_FILENAME = '.gr-elevation-request.json';\n\n/**\n * Thrown when a broker-relayed API call hits a scope-only 403 (GRA-6895).\n *\n * Before it is thrown, {@link writeElevationMarker} records the missing scope so\n * the sandbox agent surfaces an elevation request to `run_code`, which offers an\n * in-loop HITL scope elevation. Throwing stops the sandbox script; the marker is\n * what actually drives the elevation, so the outcome holds even if the caller\n * swallows this error.\n */\nexport class GrElevationRequired extends Error {\n readonly requiredScope: string;\n constructor(requiredScope: string, method: string, path: string) {\n super(\n `Gravity API ${method} ${path} failed (403): scope elevation required for '${requiredScope}'`\n );\n this.name = 'GrElevationRequired';\n this.requiredScope = requiredScope;\n }\n}\n\n/**\n * Record a scope-only 403 as the exec's elevation control marker.\n *\n * Last-wins: overwrites any prior marker in this exec. Written to\n * `GR_SANDBOX_ROOT` (the exec cwd), where the sandbox agent reads + deletes it.\n * Best-effort — a write failure must never mask the underlying 403.\n */\nfunction writeElevationMarker(scope: string, method: string, path: string): void {\n const root =\n (typeof process !== 'undefined' && process.env.GR_SANDBOX_ROOT) ||\n (typeof process !== 'undefined' ? process.cwd() : '.');\n try {\n // Path is the sandbox root (GR_SANDBOX_ROOT / cwd) joined to a FIXED\n // constant filename — no user input in either component, so no traversal.\n // oxlint-disable-next-line security/detect-non-literal-fs-filename -- root is the sandbox cwd, filename is a fixed constant\n writeFileSync(\n join(root, ELEVATION_MARKER_FILENAME),\n JSON.stringify({ scope, method, path }),\n 'utf8'\n );\n } catch {\n // best-effort — never mask the underlying 403\n }\n}\n\n/**\n * Wrap a fetch so a scope-only 403 (a 403 body carrying `required_scope`) writes\n * the elevation marker and throws {@link GrElevationRequired}. Any other 403 (or\n * a 403 without `required_scope`) is returned unchanged for the SDK's normal\n * error handling — purely additive on top of today's behavior.\n */\nexport function withElevationInterceptor(fetchFn: typeof fetch): typeof fetch {\n return async (input, init) => {\n const response = await fetchFn(input, init);\n if (response.status !== 403) return response;\n\n let requiredScope: string | undefined;\n try {\n const body: unknown = await response.clone().json();\n if (\n body !== null &&\n typeof body === 'object' &&\n typeof (body as { required_scope?: unknown }).required_scope === 'string' &&\n (body as { required_scope: string }).required_scope\n ) {\n requiredScope = (body as { required_scope: string }).required_scope;\n }\n } catch {\n // non-JSON / unreadable body — not a scope elevation; return as-is\n }\n if (!requiredScope) return response;\n\n const method = (init?.method ?? 'GET').toUpperCase();\n const rawPath =\n typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;\n // Store the URL PATH only (no scheme/host) so the HITL display matches the\n // Python client's resource path and isn't mangled by the backend's path\n // sanitizer (which strips ':' etc). Fall back to the raw string when it\n // isn't a parseable absolute URL (a relative path).\n let path = rawPath;\n try {\n path = new URL(rawPath).pathname;\n } catch {\n // relative / non-URL input — keep as-is\n }\n writeElevationMarker(requiredScope, method, path);\n throw new GrElevationRequired(requiredScope, method, path);\n };\n}\n\nexport interface SandboxAuditHeaders {\n chatId?: number;\n sessionId?: string;\n toolCallId?: string;\n}\n\ntype ToolCallGlobal = typeof globalThis & {\n __GRAVITY_RAIL_TOOL_CALL_ID__?: string;\n};\n\ntype WebRequest = Parameters<typeof fetch>[0];\ntype WebRequestInit = Parameters<typeof fetch>[1];\n\n/** Subset of sandbox env used when building fetch. */\nexport interface SandboxFetchEnv {\n chatId?: number;\n sessionId?: string;\n toolCallId?: string;\n}\n\nexport function withAuditHeaders(\n fetchFn: typeof fetch,\n headers: SandboxAuditHeaders\n): typeof fetch {\n const { chatId, sessionId, toolCallId } = headers;\n\n return async (input: WebRequest, init?: WebRequestInit): Promise<Response> => {\n const reqHeaders = new Headers(init?.headers);\n const dynamicToolCallId =\n (globalThis as ToolCallGlobal).__GRAVITY_RAIL_TOOL_CALL_ID__ ||\n (typeof process !== 'undefined' ? process.env.GRAVITY_RAIL_TOOL_CALL_ID : undefined);\n if (chatId !== undefined) {\n reqHeaders.set('X-GR-Chat-Id', String(chatId));\n }\n if (sessionId) {\n reqHeaders.set('X-GR-Session-Id', sessionId);\n }\n if (dynamicToolCallId || toolCallId) {\n reqHeaders.set('X-GR-Tool-Call-Id', dynamicToolCallId || toolCallId || '');\n }\n return fetchFn(input, { ...init, headers: reqHeaders });\n };\n}\n\n/** Build fetch for sandbox sessions (loopback broker + audit headers). */\nexport function createSandboxFetch(env: SandboxFetchEnv): typeof fetch {\n const socketPath =\n typeof process !== 'undefined' ? process.env.GRAVITY_RAIL_BROKER_SOCKET : undefined;\n return withElevationInterceptor(\n withAuditHeaders(socketPath ? createUnixBrokerFetch(socketPath) : fetch, {\n chatId: env.chatId,\n sessionId: env.sessionId,\n toolCallId: env.toolCallId,\n })\n );\n}\n","import { request as httpRequest } from 'node:http';\n\n/** HTTP over the one data socket exposed inside a Job's network namespace. */\nexport function createUnixBrokerFetch(socketPath: string): typeof fetch {\n return async (input, init) => {\n const request = new Request(input, init);\n const url = new URL(request.url);\n if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)) {\n throw new Error('The sandbox broker requires a loopback request');\n }\n const body = request.body ? Buffer.from(await request.arrayBuffer()) : undefined;\n return new Promise<Response>((resolve, reject) => {\n const connection = httpRequest(\n {\n socketPath,\n path: url.pathname + url.search,\n method: request.method,\n headers: Object.fromEntries(request.headers),\n },\n (response) => {\n const chunks: Buffer[] = [];\n let length = 0;\n response.on('data', (chunk: Buffer) => {\n length += chunk.length;\n if (length > 32 * 1024 * 1024) {\n connection.destroy(new Error('Sandbox response exceeds its size limit'));\n return;\n }\n chunks.push(chunk);\n });\n response.on('error', reject);\n response.on('end', () => {\n const headers = new Headers();\n for (const [name, value] of Object.entries(response.headers)) {\n if (Array.isArray(value)) value.forEach((item) => headers.append(name, item));\n else if (value !== undefined) headers.set(name, value);\n }\n const status = response.statusCode ?? 502;\n resolve(\n new Response([204, 205, 304].includes(status) ? null : Buffer.concat(chunks), {\n status,\n headers,\n })\n );\n });\n }\n );\n connection.on('error', reject);\n const abort = () => connection.destroy(new Error('Sandbox request was cancelled'));\n if (request.signal.aborted) abort();\n else request.signal.addEventListener('abort', abort, { once: true });\n connection.on('close', () => request.signal.removeEventListener('abort', abort));\n connection.end(body);\n });\n };\n}\n","/**\n * Script-raised prompts: let a skill script stop mid-run, put a form in front\n * of the operator, and continue with what they typed.\n *\n * The call blocks. The broker holds this request open, the backend parks the\n * script (blocked, never killed), and the worker renders the form and resolves\n * the hold with the answer — which arrives as this request's response body. To\n * the script it reads as one `await`.\n *\n * That is what makes procedural wizards possible: a script can branch on real\n * answers instead of guessing, and hand the model a summary of what the\n * operator chose when it finishes.\n */\nimport { createUnixBrokerFetch } from './unix-broker-fetch';\nimport { readSandboxEnv, type SandboxEnv } from './env';\n\n/** Control kinds a field can render as. */\nexport type AskFieldType = 'text' | 'longtext' | 'number' | 'select' | 'boolean';\n\nexport interface AskChoice {\n /** Machine value handed back to the script. */\n value: string;\n /** What the operator reads. Defaults to `value`. */\n label?: string;\n}\n\nexport interface AskField {\n /** Key this field's answer appears under in `values`. */\n name: string;\n /**\n * Operator-facing label. Defaults to `name`.\n *\n * Pass `''` for *no* label, which is different from passing nothing: a\n * narration beat's lone Continue button has the line above it as its\n * heading already, and falling back to the field name would draw\n * `continue` over it.\n */\n label?: string;\n type?: AskFieldType;\n /** Required for `select`; ignored otherwise. */\n choices?: AskChoice[];\n required?: boolean;\n placeholder?: string;\n /** Pre-filled value. */\n value?: string;\n /** Help text under the control. */\n help?: string;\n}\n\nexport interface AskSpec {\n /** Heading above the form. */\n title: string;\n /** One line of context under the title. */\n description?: string;\n fields: AskField[];\n /**\n * Label on the submit button. Ignored for a one-question form whose answers\n * are a short list — picking one IS the answer, so there is no button.\n */\n submitLabel?: string;\n /**\n * This ask is a narration beat: one line, one way to advance.\n *\n * Set by `ui.say`, never by hand. It travels to the client because a\n * surface may advance a beat hands-free — pressing the only button there\n * is does what the reader would have done — and must never do that to a\n * real question, where picking an option would be answering *for* them.\n * The client cannot safely infer the difference from the rendered form, so\n * the script states it.\n */\n narration?: boolean;\n}\n\n/** The operator filled the form in. */\nexport interface AskSubmitted {\n status: 'submitted';\n /** Field `name` → what they entered. Every declared field is present. */\n values: Record<string, string>;\n}\n\n/**\n * The operator declined the form. A wizard should stop, not retry.\n *\n * `reason` carries what they typed when they declined *in order to say\n * something*: the chat's \"Say something else…\" box, which answers the prompt\n * with prose instead of with the form. A plain dismissal (\"Skip\") has no\n * reason; the two are the same outcome because the operator did the same thing\n * either way, which is why there is no separate \"deflected\" status to forget to\n * handle.\n *\n * The script is NOT held open while that conversation happens: this answer\n * terminates the run. So print the reason before you return — whatever the\n * script writes on its way out is the only thing the model gets to act on.\n */\nexport interface AskRejected {\n status: 'rejected';\n /** Verbatim operator text. Absent — never empty — for a plain dismissal. */\n reason?: string;\n}\n\n/**\n * No prompt could be shown at all (no chat surface, or the backend cannot park\n * this exec). Distinct from `rejected`: nobody declined, nobody was asked.\n */\nexport interface AskUnavailable {\n status: 'unavailable';\n reason: string;\n}\n\nexport type AskAnswer = AskSubmitted | AskRejected | AskUnavailable;\n\n/** Path the broker serves the virtual ask endpoint on. */\nconst ASK_PATH = '/__gr_broker__/ask';\n\nfunction validate(spec: AskSpec): void {\n if (!spec || typeof spec.title !== 'string' || !spec.title.trim()) {\n throw new Error('askUser: a non-empty `title` is required');\n }\n if (!Array.isArray(spec.fields) || spec.fields.length === 0) {\n throw new Error('askUser: at least one field is required');\n }\n const seen = new Set<string>();\n for (const field of spec.fields) {\n if (!field?.name || typeof field.name !== 'string') {\n throw new Error('askUser: every field needs a string `name`');\n }\n if (seen.has(field.name)) {\n throw new Error(`askUser: duplicate field name '${field.name}'`);\n }\n seen.add(field.name);\n if (field.type === 'select' && !field.choices?.length) {\n throw new Error(`askUser: select field '${field.name}' needs \\`choices\\``);\n }\n }\n}\n\n/**\n * Ask the operator to fill in a form, and wait for the answer.\n *\n * ```ts\n * const answer = await askUser({\n * title: 'How should we follow up?',\n * fields: [\n * { name: 'channel', label: 'First channel', type: 'select',\n * choices: [{ value: 'sms' }, { value: 'voice' }] },\n * { name: 'days', label: 'Days between attempts', type: 'number', value: '1' },\n * ],\n * });\n * if (answer.status !== 'submitted') {\n * // Declined. `reason` is set only when they said why — and saying why is\n * // how they hand the question to the model, so print it and stop. Waiting\n * // for a follow-up here would wait forever: the run ends with this answer.\n * if (answer.status === 'rejected' && answer.reason) console.log(answer.reason);\n * return;\n * }\n * console.log(`Using ${answer.values.channel} every ${answer.values.days} days.`);\n * ```\n *\n * Always branch on `status`. A wizard that assumes `submitted` will read\n * `undefined` values when the operator declines.\n */\nexport async function askUser(\n spec: AskSpec,\n env: SandboxEnv = readSandboxEnv()\n): Promise<AskAnswer> {\n validate(spec);\n\n let response: Response;\n try {\n const socketPath =\n typeof process !== 'undefined' ? process.env.GRAVITY_RAIL_BROKER_SOCKET : undefined;\n const request = socketPath ? createUnixBrokerFetch(socketPath) : fetch;\n response = await request(`${env.brokerUrl}${ASK_PATH}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(spec),\n });\n } catch (error) {\n // Never throw for \"could not ask\" — a wizard should take its declined\n // path rather than die half-way through building something.\n return {\n status: 'unavailable',\n reason: error instanceof Error ? error.message : 'could not reach the prompt channel',\n };\n }\n\n let parsed: unknown;\n try {\n parsed = await response.json();\n } catch {\n return { status: 'unavailable', reason: `prompt channel returned ${response.status}` };\n }\n\n const answer = parsed as Partial<AskAnswer> | null;\n if (answer?.status === 'submitted') {\n const values = (answer as AskSubmitted).values ?? {};\n // Guarantee every declared field is present, so a script can destructure\n // without optional-chaining every read.\n const complete: Record<string, string> = {};\n for (const field of spec.fields) {\n complete[field.name] = String(values[field.name] ?? '');\n }\n return { status: 'submitted', values: complete };\n }\n if (answer?.status === 'rejected') {\n // Normalise a blank/absent/non-string reason to *no* reason. Carrying\n // `reason: ''` through would make every `if (answer.reason)` downstream\n // read a plain dismissal as \"they explained themselves\", and a script\n // would print an empty line at the model instead of nothing.\n const reason = (answer as AskRejected).reason;\n return typeof reason === 'string' && reason.trim()\n ? { status: 'rejected', reason }\n : { status: 'rejected' };\n }\n return {\n status: 'unavailable',\n reason:\n (answer as AskUnavailable | null)?.reason ?? `prompt channel returned ${response.status}`,\n };\n}\n","/**\n * The script's hands on the app: narrate, navigate, point, and ask.\n *\n * ## Every beat blocks; stage directions do not\n *\n * `say` and `ask` are the same verb. A tour line still needs a Next button —\n * the user has to finish reading before the guide moves on — so a line *is* a\n * question with one answer. Treating it as one buys two things that were\n * otherwise separate problems:\n *\n * - **Pacing.** The script advances when the user does, not on a timer the\n * script guessed. Nothing to add later; it falls out of blocking.\n * - **Ordering, by construction.** A non-blocking `say` had to be flushed\n * before the next call parked the exec, or three rapid lines would race\n * and the user would see only the last. If every line blocks, the second\n * cannot be sent until the first is answered, so there is no ordering\n * problem to solve.\n *\n * `navigate`, `highlight` and `clearHighlight` stay non-blocking. They are\n * stage directions rather than beats: nobody acknowledges a scene change, and\n * waiting for one would stall a script behind a lighting cue. They POST to an\n * ordinary workspace endpoint, which publishes on the chat's realtime channel\n * and returns. Because they travel the same forwardable `/api/` path as every\n * other call, they are authorised as the member, with no loopback bypass.\n *\n * So a beat reads:\n *\n * ```ts\n * await ui.navigate('app:page:workflows'); // stage direction\n * await ui.point('Workflows live here.', 'workflows.create-button'); // beat\n * ```\n *\n * and the spotlight is already up when the line appears, because `point`\n * publishes the highlight before it parks on the line.\n *\n * ## A stage direction never throws; a beat can end the script\n *\n * Losing an audience mid-way is not a reason to abandon a half-built\n * workspace, so `navigate`/`highlight` return a boolean nobody has to check.\n * A beat is different: the user can decline it, and that ends the run — see\n * `askUser` for the three outcomes and `Flow` for what a script should do\n * with them.\n */\nimport { askUser, type AskAnswer, type AskSpec } from './ask-user';\nimport { readSandboxEnv, type SandboxEnv } from './env';\nimport { createSandboxFetch } from './sandbox-fetch';\n\n/** Maximum characters in one `say`. Longer is a monologue — break it up. */\nexport const MAX_SAY_CHARS = 600;\n\n/**\n * Field name carrying a narration beat's acknowledgement.\n *\n * A beat is an ask with exactly one choice, so the value is never interesting —\n * what matters is that it came back at all. Exported so a script or a test can\n * read the answer back by name; nothing on the client reads it. What tells a\n * beat from a real question is `narration: true` on the spec, which the tool\n * turns into the payload's `guided` marker\n * (`lib/ai/tools/code_interpreter.py`) — see `sayAskSpec` below.\n */\nexport const SAY_FIELD = 'continue';\n\nexport interface HighlightOptions {\n /** Short caption shown against the highlighted element. */\n note?: string;\n}\n\nexport interface SayOptions {\n /**\n * Label on the button that advances the beat. Defaults to `Continue`.\n *\n * Worth setting when the line ends on a question the button answers\n * (\"Got it\", \"Show me\") — the default is right for ordinary narration and\n * wrong when the sentence has already asked something.\n */\n continueLabel?: string;\n}\n\ntype UiEvent =\n | { kind: 'navigate'; appUri: string }\n | { kind: 'highlight'; anchor: string; note?: string }\n | { kind: 'clear_highlight' };\n\n/**\n * Publish a batch of stage directions. Resolves true when the API accepted them.\n *\n * Never throws: a transport failure, a closed chat, or a workspace that has\n * moved on all mean \"nobody is watching\", and the caller's work is not made\n * better by an exception.\n */\nasync function publish(events: UiEvent[], env: SandboxEnv): Promise<boolean> {\n // No chat means no surface to drive — a script run from the CLI, or a\n // detached job. Not an error; there is simply nobody to talk to.\n if (!env.chatId) return false;\n // The audited fetch, not the global one: it carries the chat / session /\n // tool-call attribution headers the broker and API expect, so these calls\n // are traceable to the same exec as every other call the script makes.\n const sandboxFetch = createSandboxFetch({\n chatId: env.chatId,\n sessionId: env.sessionId,\n toolCallId: env.toolCallId,\n });\n try {\n const response = await sandboxFetch(\n `${env.brokerUrl}/api/v2/w/${env.workspaceUuid}/chats/${env.chatId}/ui-events`,\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ events }),\n }\n );\n return response.ok;\n } catch {\n return false;\n }\n}\n\n/**\n * Validate one beat's line.\n *\n * The message names the *beat*, not a function: four entry points build a\n * narration spec (`ui.say`, `ui.point`, `Flow.say`, `Flow.point`), and an error\n * reading `ui.say:` sent an author who wrote `flow.point` looking for a call\n * they had not made.\n */\nfunction requireText(text: string): string {\n const trimmed = (text ?? '').trim();\n if (!trimmed) throw new Error('beat text cannot be empty');\n if (trimmed.length > MAX_SAY_CHARS) {\n throw new Error(\n `beat text is ${trimmed.length} characters (max ${MAX_SAY_CHARS}). ` +\n 'Break it into steps the user can interrupt between.'\n );\n }\n return trimmed;\n}\n\n/**\n * The ask spec for one narration beat.\n *\n * `narration: true` is what lets a surface advance this hands-free. A beat has\n * one answer, so a timer that presses it is doing what the user would have\n * done; a real question has several, and a timer that picked one would be\n * answering *for* them. That difference has to be legible to the client, and\n * the shape of the markup is the wrong place to infer it from.\n *\n * The field carries an empty label deliberately: the line is already the\n * heading, and a label above a lone button would draw the question twice.\n */\nexport function sayAskSpec(text: string, options: SayOptions = {}): AskSpec {\n return {\n title: requireText(text),\n narration: true,\n fields: [\n {\n name: SAY_FIELD,\n label: '',\n type: 'select',\n choices: [{ value: 'continue', label: options.continueLabel ?? 'Continue' }],\n },\n ],\n };\n}\n\n/**\n * Say one thing, and wait for the user to take it in.\n *\n * ```ts\n * await ui.say(\"I'll set up your intake line first — it's the one that pays off today.\");\n * ```\n *\n * Resolves when they advance. A decline — Skip, or answering in prose — comes\n * back as `rejected`, and a script should stop on it rather than carrying on\n * talking. `Flow.say` does that for you.\n */\nexport async function say(\n text: string,\n options: SayOptions = {},\n env?: SandboxEnv\n): Promise<AskAnswer> {\n return ask(sayAskSpec(text, options), env);\n}\n\n/**\n * Take the user to a page, named by the same `app:page:` URI the Manager's\n * navigation tool uses. Unknown URIs are rejected by the API rather than\n * silently ignored, so a typo fails loudly in development.\n *\n * ```ts\n * await ui.navigate('app:page:workflows');\n * ```\n */\nexport async function navigate(\n appUri: string,\n env: SandboxEnv = readSandboxEnv()\n): Promise<boolean> {\n if (!appUri?.trim()) throw new Error('ui.navigate: appUri cannot be empty');\n return publish([{ kind: 'navigate', appUri: appUri.trim() }], env);\n}\n\n/**\n * Point at something on screen by its anchor id — never a CSS selector. Anchors\n * are declared by the components themselves and checked by a lint, so a\n * renamed class cannot silently break a tour in front of a customer.\n *\n * ```ts\n * await ui.highlight('workflows.create-button', { note: 'Start here.' });\n * ```\n */\nexport async function highlight(\n anchor: string,\n options: HighlightOptions = {},\n env: SandboxEnv = readSandboxEnv()\n): Promise<boolean> {\n if (!anchor?.trim()) throw new Error('ui.highlight: anchor cannot be empty');\n return publish([{ kind: 'highlight', anchor: anchor.trim(), note: options.note }], env);\n}\n\n/** Drop any active highlight. Clearing nothing is not an error. */\nexport async function clearHighlight(env: SandboxEnv = readSandboxEnv()): Promise<boolean> {\n return publish([{ kind: 'clear_highlight' }], env);\n}\n\n/**\n * Point at something and say what it is, as one beat.\n *\n * The highlight goes up *first* and does not block, so the spotlight is\n * already on the control when the line asking the user to look at it appears.\n * Doing it the other way round — narrating, then lighting up once they\n * advance — points at something they have already finished reading about.\n */\nexport async function point(\n text: string,\n anchor: string,\n options: HighlightOptions & SayOptions = {},\n env: SandboxEnv = readSandboxEnv()\n): Promise<AskAnswer> {\n if (!anchor?.trim()) throw new Error('ui.point: anchor cannot be empty');\n // Built before the highlight is published so an over-long line fails\n // without leaving a spotlight burned onto the page with no beat to explain\n // it.\n const spec = sayAskSpec(text, options);\n await publish([{ kind: 'highlight', anchor: anchor.trim(), note: options.note }], env);\n return ask(spec, env);\n}\n\n/**\n * Ask the operator to fill in a form, and wait for the answer.\n *\n * Re-exported here so one import covers the whole surface rather than\n * splitting it between a namespace and a free function.\n *\n * Always branch on `answer.status`; see `askUser` for why.\n */\nexport async function ask(spec: AskSpec, env?: SandboxEnv): Promise<AskAnswer> {\n return env ? askUser(spec, env) : askUser(spec);\n}\n\nexport const ui = { say, navigate, highlight, clearHighlight, point, ask } as const;\n","/**\n * Flows: parameterised, re-enterable scripts the manager can steer.\n *\n * A flow is an ordinary linear script — `for` loops, local variables, normal\n * control flow — that happens to keep its answers somewhere durable and knows\n * how to be started again. Onboarding is one. A tour is one. So is any workflow\n * app a customer builds. There is no separate \"kind\" of script for any of them:\n * the same shape, differing only in what its steps do and who its state belongs\n * to.\n *\n * ## The re-entry contract\n *\n * A user facing one of this flow's beats — a question, or just a line of\n * narration — can always decline it, optionally saying why (\"this isn't right,\n * I meant medical education, not school\"). That ends the script — it does NOT\n * sit parked while the user and the model talk. On the way out the runtime\n * prints an instruction telling the model how to start the flow again, and\n * where the answers live.\n *\n * A flow that runs to the END prints no such instruction — \"here is how to\n * continue\" after a completed tour reads as though it stopped half way. It\n * prints a completion report instead, which has a harder job: saying whether\n * this run did anything at all. A flow that skips every step it has already\n * done reaches the end instantly and is, from inside the body, indistinguishable\n * from a full run, so the report is the only thing that can tell a first\n * completion from a no-op — and it always offers the way back, because\n * \"complete\" is never the whole story for something a person can want again.\n *\n * The model can then do one of three things, and the state file is what makes\n * all three possible:\n *\n * 1. re-run unchanged — the user just wanted to ask something;\n * 2. edit the state file and re-run — the user corrected an answer;\n * 3. start a DIFFERENT flow, writing that flow's own state file — the user\n * wanted something else entirely.\n *\n * This is why state must be semantic. A program counter would let us resume but\n * not be revised; `vertical: 'school-education'` is a thing a model can read,\n * disagree with, and rewrite. The constraint is the feature.\n *\n * ## Re-running means re-running\n *\n * There is no magic resumption. Re-entry starts the script from the top with\n * the previous answers already in hand, and it is the script's job to skip what\n * its state says is done — `if (!flow.state.vertical) { ...ask... }`. That is\n * also why a flow must not rebuild what it already built: record a decision in\n * state immediately after acting on it, not at the end, or a rejection between\n * the two will redo the work on the next run.\n */\nimport { readSandboxEnv, type SandboxEnv } from './env';\nimport { sayAskSpec, ui, type HighlightOptions, type SayOptions } from './ui';\nimport type { AskSpec } from './ask-user';\n\n/** Who a flow's answers belong to. Fixed per script, never a runtime choice. */\nexport type FlowScope = 'member' | 'workspace';\n\n/**\n * Framework-owned half of the state file. The model edits `state`; everything\n * here is written by the runtime and should be left alone.\n */\nexport interface FlowMeta {\n flow: string;\n scope: FlowScope;\n /** ISO timestamp of the last write. */\n updatedAt: string;\n /** Member id that last wrote, when one was available. */\n updatedBy?: number;\n /**\n * Questions this user has declined, most recent last.\n *\n * Recorded so a re-entered flow can tell \"never asked\" from \"asked and\n * refused\". Without it the obvious loop appears: the user declines, the\n * model answers their question, the flow restarts and asks the identical\n * question, and they are exactly where they began.\n */\n rejections: FlowRejection[];\n /**\n * When this flow last ran all the way to the end, if it ever has.\n *\n * The difference between \"finished just now\" and \"finished last week and\n * did nothing this time\" is invisible from inside the body — a flow that\n * skips every step it has already done reaches the end instantly and looks\n * exactly like a successful run. Recording the timestamp is what lets the\n * runtime tell the model which of the two just happened.\n */\n completedAt?: string;\n}\n\nexport interface FlowRejection {\n /** The `title` of the ask that was declined. */\n question: string;\n /** What the user said, when they said anything. */\n reason?: string;\n at: string;\n}\n\ninterface FlowFile<S> {\n _meta: FlowMeta;\n state: S;\n}\n\nexport interface FlowDefinition<S extends object> {\n /**\n * The durable product this flow's initiative belongs to.\n *\n * Projects contain plans (ADR 2026-08-08-16): a Project is the lasting\n * identity, a Plan is one bounded initiative inside it. A flow is a plan, so\n * it needs both halves to know where it lives.\n */\n project: string;\n /** Plan slug. Names the state location, so keep it stable across edits. */\n name: string;\n /**\n * Whether these answers belong to one member or to the workspace.\n *\n * Get this wrong in either direction and it shows up late: workspace answers\n * in member scope get stranded when that person leaves, and member answers\n * in workspace scope mean two people resume into each other's session.\n */\n scope: FlowScope;\n /** Starting answers. Field names are the vocabulary the model revises. */\n initialState: S;\n /**\n * Where answers live. `'file'` is the default whenever state is declared.\n *\n * `'none'` suits a flow with nothing to remember — a short tour — and skips\n * the file entirely rather than leaving an empty one lying around.\n */\n storage?: 'file' | 'none';\n /** Overrides the conventional path. Rarely needed. */\n statePath?: string;\n /**\n * State keys that record how far this flow GOT, rather than what it learned\n * or built.\n *\n * Naming them is what makes a replay safe to hand out. Starting a finished\n * flow over means dropping its progress — but a state file also records\n * things that now EXIST in the workspace (`builtWorkflow`, a created\n * routine id), and dropping those tells the next run to build a second\n * copy. Deleting the whole file is therefore the obvious way to replay a\n * tour and the wrong one.\n *\n * Declare the progress fields and the runtime prints a ready-to-write state\n * that keeps everything else. Leave it undeclared and it prints the same\n * advice in prose, because it cannot know which half is which.\n */\n progressKeys?: readonly (keyof S & string)[];\n}\n\n/** Thrown when the user declines a question. `runFlow` catches it. */\nexport class FlowExit extends Error {\n constructor(\n readonly question: string,\n readonly reason?: string\n ) {\n super(`Flow stopped: ${question}`);\n this.name = 'FlowExit';\n }\n}\n\nexport type FlowAskResult =\n | { status: 'submitted'; values: Record<string, string> }\n | { status: 'rejected'; reason?: string }\n | { status: 'unavailable'; reason: string };\n\nfunction print(message = ''): void {\n process.stdout.write(`${message}\\n`);\n}\n\n/**\n * How much of the state file to print when a flow finishes.\n *\n * Printed at all because the alternative is worse: the model is handed a path,\n * and answering \"what did they pick?\" then costs a second exec to read a file\n * it was just told about. A thousand characters covers every flow we ship with\n * room to spare, and the path is still there when it does not.\n *\n * This is the operator's own answers going back to the model that is helping\n * them — the same audience that could already read the file, so printing it\n * discloses nothing the path did not. It is stdout, not a log; do not route it\n * to one.\n */\nconst MAX_STATE_PREVIEW_CHARS = 1000;\n\nfunction statePreview(state: unknown): string {\n const text = JSON.stringify(state, null, 2) ?? 'null';\n if (text.length <= MAX_STATE_PREVIEW_CHARS) return text;\n return (\n `${text.slice(0, MAX_STATE_PREVIEW_CHARS)}\\n` +\n `… truncated at ${MAX_STATE_PREVIEW_CHARS} characters — read the file for the rest.`\n );\n}\n\n/**\n * The reason a user gave for declining, when they gave one.\n *\n * Read structurally rather than by narrowing the union: a decline carries a\n * reason only when the user typed one, and a dismissal carries none at all.\n * Treating a missing or non-string value as \"no reason given\" keeps this\n * correct for both shapes without the flow layer caring which it got.\n */\nfunction declineReason(answer: object): string | undefined {\n const value = (answer as { reason?: unknown }).reason;\n return typeof value === 'string' && value.trim() ? value.trim() : undefined;\n}\n\n/**\n * Conventional state location.\n *\n * Member-scoped flows partition by member id *inside the shared tree* rather\n * than living in a member's home directory. Two members then never contend for\n * one file — which removes the need for locking entirely — while the workspace\n * keeps the answers when that person leaves.\n */\nfunction defaultStatePath<S extends object>(\n definition: FlowDefinition<S>,\n env: SandboxEnv\n): string {\n // Two levels, per the projects/plans model: the project is the durable\n // product, the plan is this bounded initiative. NOT the older flat\n // `/gr/workspace/plans/<slug>/` layout, which that model supersedes.\n const base = `/gr/workspace/projects/${definition.project}/plans/${definition.name}`;\n if (definition.scope === 'workspace') return `${base}/state.json`;\n // No member id (a CLI or detached run) still needs a stable path; `shared`\n // is honest about what it is rather than pretending to be someone.\n return `${base}/state/member-${env.memberId ?? 'shared'}.json`;\n}\n\n/**\n * The handle a flow body is given.\n *\n * Two audiences, and the split is why `flow-api.md` documents only half the\n * members below. A flow **author** uses `state`, `save`, `say`, `point`, `ask`,\n * `askOptional` and `wasRejected` — that is the whole documented surface. The\n * rest (`statePath`, `load`, `previouslyCompletedAt`, `thisRun`, `markComplete`,\n * `replayState`, `completionReport`, `reentryInstruction`) is what `runFlow`\n * calls around the body, public only because `runFlow` is a free function rather\n * than a method. Teaching them would offer an author a second way to do what\n * `runFlow` already does, which is how a flow ends up printing its own report\n * alongside the runtime's.\n */\nexport class Flow<S extends object> {\n /** The answers so far. Mutate freely; call `save()` when it matters. */\n state: S;\n\n private meta: FlowMeta;\n private readonly path: string | null;\n /**\n * When this flow had last been completed *as this run started*.\n *\n * Captured at load and never updated afterwards, because the whole question\n * it answers — \"did this run actually do anything?\" — stops being answerable\n * the moment `markComplete` stamps a new timestamp.\n */\n private completedBefore?: string;\n /**\n * What this run actually put in front of the person, as it happens.\n *\n * Counted because \"did anything happen?\" is the one question the printed\n * result could not answer, and it is the question that matters most. A flow\n * that skips every step it has already done finishes instantly and looks,\n * from the outside, exactly like a full run — so the model relayed \"your\n * tour is complete\" to someone who had just asked to be shown around and\n * had been shown nothing.\n */\n private readonly activity = { narrated: 0, asked: 0, answered: 0, declined: 0 };\n\n constructor(\n private readonly definition: FlowDefinition<S>,\n private readonly env: SandboxEnv\n ) {\n this.state = { ...definition.initialState };\n this.meta = {\n flow: `${definition.project}/${definition.name}`,\n scope: definition.scope,\n updatedAt: new Date().toISOString(),\n ...(env.memberId !== undefined ? { updatedBy: env.memberId } : {}),\n rejections: [],\n };\n this.path =\n definition.storage === 'none'\n ? null\n : (definition.statePath ?? defaultStatePath(definition, env));\n }\n\n /** Where this flow's answers live, or null when it stores none. */\n get statePath(): string | null {\n return this.path;\n }\n\n /**\n * Load previous answers, if any. Missing or unreadable state is not an\n * error — it means a first run, which is the common case.\n *\n * Warns (never refuses) when someone else wrote last. A hard lock would need\n * releasing on exit, and a process that dies in between leaves the flow\n * claimed forever with `--force` as the only way out — which trains everyone\n * to pass `--force`. A warning costs nothing and hands the decision to the\n * model, which can ask whether to continue that person's work or start over.\n */\n async load(): Promise<void> {\n if (!this.path) return;\n let parsed: FlowFile<S> | null = null;\n try {\n const { readFile } = await import('node:fs/promises');\n parsed = JSON.parse(await readFile(this.path, 'utf8')) as FlowFile<S>;\n } catch {\n return;\n }\n if (!parsed || typeof parsed !== 'object' || !parsed.state) return;\n\n this.state = { ...this.definition.initialState, ...parsed.state };\n if (parsed._meta) {\n this.completedBefore =\n typeof parsed._meta.completedAt === 'string' ? parsed._meta.completedAt : undefined;\n this.meta = {\n ...this.meta,\n rejections: Array.isArray(parsed._meta.rejections) ? parsed._meta.rejections : [],\n ...(this.completedBefore ? { completedAt: this.completedBefore } : {}),\n };\n const previous = parsed._meta.updatedBy;\n if (previous !== undefined && previous !== this.env.memberId) {\n print(\n `Note: these answers were last updated by member ${previous} at ` +\n `${parsed._meta.updatedAt}. Continuing from where they left off.`\n );\n }\n }\n }\n\n /**\n * Persist the answers.\n *\n * Call this immediately after acting on a decision, not at the end: a\n * rejection between the write and the record is what makes a re-entered\n * flow rebuild something it already built.\n */\n async save(): Promise<void> {\n if (!this.path) return;\n this.meta = {\n ...this.meta,\n updatedAt: new Date().toISOString(),\n ...(this.env.memberId !== undefined ? { updatedBy: this.env.memberId } : {}),\n };\n const payload: FlowFile<S> = { _meta: this.meta, state: this.state };\n try {\n const { mkdir, writeFile } = await import('node:fs/promises');\n // A path with no separator has no parent to create. `lastIndexOf`\n // returns -1 there, and slicing to -1 would drop the last character\n // and hand `mkdir` a *sibling* directory name — creating the wrong\n // directory and then writing beside it.\n const separator = this.path.lastIndexOf('/');\n if (separator > 0) await mkdir(this.path.slice(0, separator), { recursive: true });\n await writeFile(this.path, `${JSON.stringify(payload, null, 2)}\\n`, 'utf8');\n } catch (error) {\n // Never fatal. Losing the ability to resume is worse than losing this\n // run's progress, but neither is worth abandoning work already done.\n print(\n `Warning: could not save answers to ${this.path} ` +\n `(${error instanceof Error ? error.name : 'unknown error'}). ` +\n 'This run will finish; resuming later may start over.'\n );\n }\n }\n\n /**\n * Ask a question, and stop the flow if the user declines.\n *\n * The ergonomic default: a script reads as a straight line, and a rejection\n * unwinds to `runFlow` without every call site testing for it. Use\n * {@link askOptional} where declining should be handled rather than fatal.\n */\n async ask(spec: AskSpec): Promise<Record<string, string>> {\n const answer = await this.askOptional(spec);\n if (answer.status === 'submitted') return answer.values;\n throw new FlowExit(spec.title, answer.status === 'rejected' ? answer.reason : undefined);\n }\n\n /**\n * Say one line and wait for the user to take it in. Declining stops the flow.\n *\n * The narration counterpart of {@link ask}, and the one a tour is written\n * out of. Declining a *line* is the user saying \"not this, talk to me\" —\n * which is the same thing declining a question means, so it ends the run\n * the same way and the reason reaches the model through the same\n * re-entry instruction.\n */\n async say(text: string, options: SayOptions = {}): Promise<void> {\n await this.ask(sayAskSpec(text, options));\n }\n\n /**\n * Point at something and say what it is. Declining stops the flow.\n *\n * The highlight is published before the line parks, so the spotlight is up\n * while the user reads about it — see `ui.point`.\n */\n async point(text: string, anchor: string, options: HighlightOptions & SayOptions = {}) {\n const spec = sayAskSpec(text, options);\n await ui.highlight(anchor, options, this.env);\n await this.ask(spec);\n }\n\n /**\n * Ask a question and hand back what happened, including a decline.\n *\n * A rejection is still recorded in state, so a flow that carries on after\n * one does not re-ask the same thing on the next run.\n */\n async askOptional(spec: AskSpec): Promise<FlowAskResult> {\n // Forward this Flow's env: it was handed one for `memberId` and state\n // paths, and letting the prompt channel fall back to the ambient\n // `readSandboxEnv()` means the two can disagree about which chat is being\n // asked. Harmless in production, where both resolve the same, and exactly\n // the kind of split a test has to work around rather than exercise.\n // Counted here rather than at each call site: `say`, `point` and `ask`\n // all funnel through this one method, so this is the only place that\n // sees every beat exactly once.\n if (spec.narration) this.activity.narrated += 1;\n else this.activity.asked += 1;\n\n const answer = await ui.ask(spec, this.env);\n if (answer.status === 'submitted') {\n this.activity.answered += 1;\n return { status: 'submitted', values: answer.values };\n }\n if (answer.status === 'unavailable') {\n return { status: 'unavailable', reason: answer.reason };\n }\n const reason = declineReason(answer);\n this.activity.declined += 1;\n this.meta.rejections.push({\n question: spec.title,\n ...(reason ? { reason } : {}),\n at: new Date().toISOString(),\n });\n await this.save();\n return { status: 'rejected', ...(reason ? { reason } : {}) };\n }\n\n /** True when this exact question has already been declined. */\n wasRejected(question: string): boolean {\n return this.meta.rejections.some((entry) => entry.question === question);\n }\n\n /** When this flow was last completed before this run, if it ever was. */\n get previouslyCompletedAt(): string | undefined {\n return this.completedBefore;\n }\n\n /** What this run put in front of the person. Zero of everything is the tell. */\n get thisRun(): Readonly<{\n narrated: number;\n asked: number;\n answered: number;\n declined: number;\n }> {\n return this.activity;\n }\n\n /** One line naming what actually happened, in the plainest terms available. */\n private activityLine(): string {\n const { narrated, asked, answered, declined } = this.activity;\n if (narrated + asked === 0) {\n return 'This run put nothing in front of them — no narration, no questions.';\n }\n const parts: string[] = [];\n if (narrated) parts.push(`${narrated} line${narrated === 1 ? '' : 's'} narrated`);\n if (asked) parts.push(`${asked} question${asked === 1 ? '' : 's'} asked`);\n if (answered) parts.push(`${answered} answered`);\n if (declined) parts.push(`${declined} declined`);\n return `This run: ${parts.join(', ')}.`;\n }\n\n /** Record that the body reached the end. `runFlow` calls this. */\n markComplete(): void {\n this.meta = { ...this.meta, completedAt: new Date().toISOString() };\n }\n\n /**\n * The state to write in order to run this flow again for real.\n *\n * Progress dropped, everything else kept — see `progressKeys` for why the\n * distinction is the flow author's to make and why getting it wrong builds\n * a second copy of whatever the first run created.\n */\n replayState(): Partial<S> {\n const progress = new Set<string>(this.definition.progressKeys ?? []);\n const kept: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(this.state)) {\n if (!progress.has(key)) kept[key] = value;\n }\n return kept as Partial<S>;\n }\n\n /**\n * What the model reads when this flow reaches the end.\n *\n * It always offers the way back. \"Complete\" is never the whole story for a\n * flow a person can want again — a tour especially — and a report that only\n * says \"finished\" invites the model to tell someone who just asked to be\n * shown around that they have already seen it.\n */\n completionReport(scriptPath: string, resumeArgs: string[] = []): string {\n const command = [`node ${scriptPath}`, ...resumeArgs].join(' ');\n if (!this.path) {\n return `This flow keeps no saved answers, so running it again starts from the beginning:\\n ${command}`;\n }\n\n const progressKeys = this.definition.progressKeys ?? [];\n const lines = [this.activityLine(), '', `Their answers are in ${this.path}:`];\n lines.push(statePreview(this.state));\n lines.push('');\n\n // Both halves matter. A flow that asked nothing because it had nothing\n // left to ask is the bug this report exists for; a flow that asks nothing\n // *by design* — a build script with no audience — is ordinary, and\n // telling its author it \"exited immediately\" would be a lie.\n if (this.activity.narrated + this.activity.asked === 0 && this.completedBefore) {\n lines.push(\n 'It exited immediately because the state above already answers every ' +\n 'step. Running it again unchanged will do the same thing.'\n );\n } else {\n lines.push('Running it again as-is will skip everything the state above records.');\n }\n\n lines.push(`To replay, remove the relevant state and re-run: ${command}`);\n if (progressKeys.length) {\n lines.push(` • the whole flow — write: ${JSON.stringify({ state: this.replayState() })}`);\n lines.push(\n ` • one step — drop just that entry from ${progressKeys\n .map((key) => `\\`${key}\\``)\n .join(' / ')}, leaving the rest`\n );\n lines.push(\n 'Keep every other field. They name things that already exist, and ' +\n 'dropping them is what makes a replay build a second copy — which ' +\n 'is why deleting the whole file is the wrong way to start over.'\n );\n } else {\n lines.push(\n ' Drop the fields recording how far they got, and KEEP any that name ' +\n 'something already created — deleting the whole file is the obvious ' +\n 'way to replay a flow and the one that builds a second copy.'\n );\n }\n return lines.join('\\n');\n }\n\n /**\n * The instruction the model reads to start this flow again.\n *\n * Generated here rather than written by each script on purpose: a\n * hand-authored block goes stale the moment someone renames a parameter, and\n * every flow phrasing it differently means the model learns N patterns\n * instead of one.\n */\n reentryInstruction(scriptPath: string, exit?: FlowExit, resumeArgs: string[] = []): string {\n const lines: string[] = [];\n const command = [`node ${scriptPath}`, ...resumeArgs].join(' ');\n if (exit) {\n lines.push(\n exit.reason\n ? `The user declined \"${exit.question}\" and said: ${exit.reason}`\n : `The user declined \"${exit.question}\" without giving a reason.`\n );\n lines.push('');\n }\n lines.push(`To continue this flow, run: ${command}`);\n if (this.path) {\n lines.push(`Their answers so far are in ${this.path}`);\n lines.push(\n 'If any of those answers should change, edit that file first — the flow ' +\n 'picks up from whatever it says. Re-running WITHOUT changing anything ' +\n 'will ask the same question again.'\n );\n lines.push(\n 'If a different flow suits them better, start that one instead and write ' +\n 'ITS OWN state file rather than reusing this path — answers about the ' +\n 'workspace usually carry across; progress through this flow does not.'\n );\n } else {\n lines.push('This flow keeps no saved answers, so it starts from the beginning.');\n }\n return lines.join('\\n');\n }\n}\n\n/**\n * Run a flow: load answers, run the body, print the re-entry instruction.\n *\n * A decline unwinds out of `body` and is handled here — it is an ordinary\n * ending, not a failure, so the process exits 0. The instruction goes to stdout\n * because stdout is what the model reads back from an exec.\n */\nexport async function runFlow<S extends object>(\n definition: FlowDefinition<S>,\n body: (flow: Flow<S>) => Promise<void>,\n options: { scriptPath?: string; env?: SandboxEnv; resumeArgs?: string[] } = {}\n): Promise<void> {\n const env = options.env ?? readSandboxEnv();\n const scriptPath = options.scriptPath ?? process.argv[1] ?? `<${definition.name}>`;\n // Arguments the printed command must carry to resume faithfully. Not every\n // parameter belongs in state: a per-run choice like `--write` is a decision\n // about THIS invocation, and a re-entry instruction that silently drops it\n // tells the model to run a command that previews instead of building, then\n // reports \"nothing to do\". A flow declares what must survive; the runtime\n // prints it.\n const resumeArgs = options.resumeArgs ?? [];\n const flow = new Flow(definition, env);\n\n await flow.load();\n\n // Read before the body runs: reaching the end stamps a fresh timestamp, and\n // this is the only thing that can distinguish the two ways of getting there.\n const completedBefore = flow.previouslyCompletedAt;\n\n try {\n await body(flow);\n flow.markComplete();\n await flow.save();\n } catch (error) {\n if (!(error instanceof FlowExit)) throw error;\n await flow.save();\n print('');\n print(flow.reentryInstruction(scriptPath, error, resumeArgs));\n return;\n }\n\n // A finished flow does NOT print the *re-entry* instruction — \"here is how\n // to pick it up\" reads as though it stopped half way. What it prints\n // instead has to answer a question re-entry never had to: whether this run\n // did anything at all.\n //\n // A flow that skips every step it has already done reaches the end\n // instantly, and from the body that is indistinguishable from a full run.\n // Saying \"Finished\" either way is how someone who asked to be shown around\n // gets told they have already seen it — the script did nothing, said it was\n // complete, and the model faithfully passed that on.\n print('');\n if (completedBefore) {\n print(\n `Nothing to do: ${definition.project}/${definition.name} was already ` +\n `completed on ${completedBefore}, and this run changed nothing.`\n );\n } else {\n print(`Finished: ${definition.project}/${definition.name}.`);\n }\n print(flow.completionReport(scriptPath, resumeArgs));\n}\n","/**\n * Audit headers for API calls made from a code-interpreter sandbox.\n *\n * The private-ALB DNS pin that used to live here is gone: it was driven by\n * `GRAVITY_RAIL_API_IP`, which only the sandbox `.gr-env` ever set, and sandbox\n * clients no longer dial the API host at all — every call goes to the loopback\n * credential broker, and the root daemon applies the pin on the far side.\n */\n\nimport { createUnixBrokerFetch } from '@gravity-rail/sandbox';\nexport interface SandboxAuditHeaders {\n chatId?: number;\n sessionId?: string;\n toolCallId?: string;\n}\n\ntype ToolCallGlobal = typeof globalThis & {\n __GRAVITY_RAIL_TOOL_CALL_ID__?: string;\n};\n\ntype WebRequest = Parameters<typeof fetch>[0];\ntype WebRequestInit = Parameters<typeof fetch>[1];\n\nexport function withAuditHeaders(\n fetchFn: typeof fetch,\n headers: SandboxAuditHeaders\n): typeof fetch {\n const { chatId, sessionId, toolCallId } = headers;\n\n return async (input: WebRequest, init?: WebRequestInit): Promise<Response> => {\n const reqHeaders = new Headers(init?.headers);\n const dynamicToolCallId =\n (globalThis as ToolCallGlobal).__GRAVITY_RAIL_TOOL_CALL_ID__ ||\n (typeof process !== 'undefined' ? process.env.GRAVITY_RAIL_TOOL_CALL_ID : undefined);\n if (chatId !== undefined) {\n reqHeaders.set('X-GR-Chat-Id', String(chatId));\n }\n if (sessionId) {\n reqHeaders.set('X-GR-Session-Id', sessionId);\n }\n if (dynamicToolCallId || toolCallId) {\n reqHeaders.set('X-GR-Tool-Call-Id', dynamicToolCallId || toolCallId || '');\n }\n return fetchFn(input, { ...init, headers: reqHeaders });\n };\n}\n\n/**\n * Build fetch for CLI API calls, adding the sandbox correlation headers when\n * the GRAVITY_RAIL_* session vars are present.\n *\n * Outside a sandbox those vars are unset and this is plain `fetch` with a\n * pass-through header copy. Inside one, auth is added by the loopback broker,\n * never here.\n */\nexport function createSandboxFetchFromEnv(): typeof fetch {\n const env: Record<string, string | undefined> =\n typeof process !== 'undefined' ? process.env : {};\n const chatIdRaw = env.GRAVITY_RAIL_CHAT_ID;\n const chatId = chatIdRaw ? Number(chatIdRaw) : undefined;\n return withAuditHeaders(\n env.GRAVITY_RAIL_BROKER_SOCKET\n ? createUnixBrokerFetch(env.GRAVITY_RAIL_BROKER_SOCKET)\n : fetch,\n {\n chatId: chatId !== undefined && Number.isFinite(chatId) ? chatId : undefined,\n sessionId: env.GRAVITY_RAIL_SESSION_ID,\n toolCallId: env.GRAVITY_RAIL_TOOL_CALL_ID,\n }\n );\n}\n","/**\n * Where a hand-built API request goes, and with what credentials.\n *\n * Commands that call the SDK client (`requireAuth(ctx).apiClient`) already get\n * this right. A command that builds its own URL — raw `fetch`, the AG-UI\n * stream, a second SDK class — must take all three parts from here, because\n * the two environments differ in every one of them:\n *\n * | | standalone CLI | code-interpreter sandbox |\n * |---|---|---|\n * | base URL | the environment's API URL | the loopback credential broker |\n * | Authorization | `Bearer <token>` | none: the broker holds the token and adds it |\n * | fetch | global `fetch` | the broker fetch (unix socket when configured) |\n *\n * In the sandbox the context's `accessToken` is the empty string\n * (`tryBrokerContext`), so a request sent to the API URL with\n * `Bearer ${ctx.accessToken}` is a 401.\n */\nimport { sandboxBrokerUrl } from './context';\nimport { createSandboxFetchFromEnv } from './sandbox-fetch';\n\ninterface TransportContext {\n envConfig: { apiUrl: string };\n accessToken?: string;\n}\n\n/** The origin every `/api/v2/...` path is appended to. */\nexport function apiBaseUrl(ctx: TransportContext): string {\n return sandboxBrokerUrl() ?? ctx.envConfig.apiUrl;\n}\n\n/** The Authorization header to send: none through the broker, or with no token. */\nexport function apiAuthHeaders(accessToken: string | undefined): Record<string, string> {\n if (sandboxBrokerUrl() || !accessToken) return {};\n return { Authorization: `Bearer ${accessToken}` };\n}\n\n/** The token to hand a second SDK client: none in the sandbox, where the broker adds it. */\nexport function apiAccessToken(ctx: TransportContext): string | undefined {\n return sandboxBrokerUrl() ? undefined : ctx.accessToken || undefined;\n}\n\n/** The fetch to send it with. Resolved per call, so a test double on `global.fetch` is used. */\nexport const apiFetch: typeof fetch = (input, init) => createSandboxFetchFromEnv()(input, init);\n"],"mappings":";AAIA,SAAS,YAAY,cAAc,gBAAgB;AACnD,SAAS,aAAa,mBAAmB,YAAY;AACrD,SAAS,SAAS,MAAM,eAAe;AAehC,IAAM,eAAkD;AAAA,EAC5D,KAAK;AAAA,IACF,QAAQ;AAAA,IACR,aAAa;AAAA,EAChB;AAAA,EACA,MAAM;AAAA,IACH,QAAQ;AAAA,IACR,aAAa;AAAA,EAChB;AAAA,EACA,SAAS;AAAA,IACN,QAAQ;AAAA,IACR,aAAa;AAAA,EAChB;AACH;AAGO,IAAM,oBAAuC;AAAA,EACjD,QAAQ;AAAA,EACR,aAAa;AAChB;AAEO,IAAM,gBAAgB;AACtB,IAAM,gBAAgB;AACtB,IAAM,eAAe,oBAAoB,aAAa,GAAG,aAAa;AAE7E,IAAM,qBAAqB;AAC3B,IAAM,0BAA0B;AAChC,IAAM,wBAAwB;AAC9B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Sync","dirname","readFileSync","existsSync","join","resolve","join","resolve","existsSync","readFileSync","resolve","dirname","existsSync","mkdirSync","resolve","GravityRailClient","stderr","resolve","createServer","createHash","randomBytes","openBrowser","resolve","createServer","randomBytes","createHash","stderr","session","writeFileSync","join","GravityRailClient","WorkspaceBuilder","runWorkspaceScript","resolve","GravityRailClient","resolve"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli-utils/config.ts","../src/cli-utils/auth.ts","../package.json","../src/cli-utils/credentials-manager.ts","../src/lib/org-session.ts","../src/cli-utils/ui.ts","../src/cli-utils/agui.ts","../src/lib/context.ts","../src/lib/jq.ts","../src/lib/errors.ts","../src/lib/pagination.ts","../src/lib/output.ts","../src/lib/org-auth.ts","../../sandbox/src/index.ts","../../sandbox/src/env.ts","../../sandbox/src/sandbox-fetch.ts","../../sandbox/src/unix-broker-fetch.ts","../../sandbox/src/ask-user.ts","../../sandbox/src/ui.ts","../../sandbox/src/flow.ts","../src/lib/sandbox-fetch.ts","../src/lib/api-transport.ts"],"sourcesContent":["/**\n * CLI configuration for remote environments\n */\n\nimport { existsSync, readFileSync, statSync } from 'fs';\nimport { CORE_SCHEMA, defineSequenceTag, load } from 'js-yaml';\nimport { dirname, join, resolve } from 'path';\n\nexport interface EnvironmentConfig {\n apiUrl: string;\n frontendUrl: string;\n}\n\n/** Optional per-field URL overrides and the checkout to classify. */\nexport interface EnvironmentConfigOptions {\n apiUrl?: string;\n frontendUrl?: string;\n /** Directory to start the worktree walk from. Defaults to `process.cwd()`. */\n startDir?: string;\n}\n\nexport const ENVIRONMENTS: Record<string, EnvironmentConfig> = {\n dev: {\n apiUrl: 'https://api.gravityrail.test:5054',\n frontendUrl: 'https://app.gravityrail.test:3000',\n },\n prod: {\n apiUrl: 'https://api.gravityrail.com',\n frontendUrl: 'https://app.gravityrail.com',\n },\n staging: {\n apiUrl: 'https://api.gr-staging.com',\n frontendUrl: 'https://app.gr-staging.com',\n },\n};\n\n/** `--env dev` from a shell inside a dev-cloud pod: the pod's native services. */\nexport const DEV_CLOUD_POD_DEV: EnvironmentConfig = {\n apiUrl: 'http://127.0.0.1:5050',\n frontendUrl: 'http://127.0.0.1:3000',\n};\n\nexport const CALLBACK_PORT = 31337;\nexport const CALLBACK_PATH = '/oauth/callback';\nexport const REDIRECT_URI = `http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`;\n\nconst API_CONTAINER_PORT = 443;\nconst FRONTEND_CONTAINER_PORT = 3000;\nconst WORKTREE_SETUP_MARKER = 'worktree-setup.sh';\nconst OVERRIDE_FILENAME = 'docker-compose.override.yml';\nconst ENV_FILENAME = '.env';\n\n/**\n * Docker Compose `ports: !override` is an identity sequence tag. Register it\n * so generated worktree overrides load; do not implement merge/replace.\n */\nconst OVERRIDE_SEQUENCE_TAG = defineSequenceTag<unknown[]>('!override', {\n create: () => [],\n addItem: (carrier, item) => {\n // Must not return a value — js-yaml treats a truthy addItem return as a parse error.\n carrier.push(item);\n },\n identify: () => false,\n});\n\nconst COMPOSE_OVERRIDE_SCHEMA = CORE_SCHEMA.withTags(OVERRIDE_SEQUENCE_TAG);\n\nexport type CheckoutClassification =\n | { kind: 'non-worktree'; root?: string }\n | {\n kind: 'resolved-worktree';\n root: string;\n overridePath: string;\n apiPort: number;\n frontendPort: number;\n }\n | {\n kind: 'unresolved-worktree';\n root: string;\n overridePath: string;\n reason: string;\n };\n\nexport class WorktreeConfigError extends Error {\n constructor(\n message: string,\n readonly checkoutRoot: string,\n readonly overridePath: string\n ) {\n super(message);\n this.name = 'WorktreeConfigError';\n }\n}\n\n/** A plain JSON object: not null, not an array. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction parsePortToken(token: string | undefined): number | undefined {\n if (token === undefined || !/^\\d+$/.test(token)) return undefined;\n const value = Number(token);\n if (!Number.isInteger(value) || value <= 0 || value > 65535) return undefined;\n return value;\n}\n\n/**\n * Parse `published` and `target` from the right edge of a short-form mapping.\n * The optional bind-address prefix (including `${DOCKER_BIND_IP:-...}`) stays\n * opaque — it is never interpolated.\n */\nexport function parsePublishedTarget(\n mapping: string\n): { published: number; target: number } | undefined {\n const parts = mapping.split(':');\n if (parts.length < 2) return undefined;\n const target = parsePortToken(parts[parts.length - 1]);\n const published = parsePortToken(parts[parts.length - 2]);\n if (target === undefined || published === undefined) return undefined;\n return { published, target };\n}\n\nfunction publishedPortForTarget(ports: unknown, target: number): number | undefined {\n if (!Array.isArray(ports)) return undefined;\n for (const entry of ports) {\n if (typeof entry !== 'string') continue;\n const parsed = parsePublishedTarget(entry);\n if (parsed?.target === target) return parsed.published;\n }\n return undefined;\n}\n\nfunction servicePorts(services: Record<string, unknown>, name: string): unknown {\n const service = services[name];\n if (!isRecord(service)) return undefined;\n return service['ports'];\n}\n\nfunction findNearestGit(startDir: string): { root: string; gitIsFile: boolean } | undefined {\n let dir = resolve(startDir);\n while (true) {\n const gitPath = join(dir, '.git');\n if (existsSync(gitPath)) {\n try {\n const st = statSync(gitPath);\n return { root: dir, gitIsFile: st.isFile() };\n } catch {\n // Unreadable .git entry — keep walking.\n }\n }\n const parent = dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n}\n\n/**\n * A worktree provisioned for the native runtime (`gr.runtime=native`) has no\n * Compose override: `worktree-setup.sh` writes its ports into `.env` and marks\n * it `GR_PROVISIONED_RUNTIME=native`. Read only those three keys — the file\n * also carries secrets, which are never parsed or returned.\n */\nfunction nativeWorktreePorts(\n envPath: string\n): { envPath: string; ports: { apiPort: number; frontendPort: number } } | undefined {\n let content: string;\n try {\n content = readFileSync(envPath, 'utf-8');\n } catch {\n return undefined;\n }\n const wanted = new Set(['GR_PROVISIONED_RUNTIME', 'API_NGINX_PORT', 'FRONTEND_PORT']);\n const values = new Map<string, string>();\n for (const line of content.split(/\\r?\\n/)) {\n const match = /^\\s*([A-Z_][A-Z0-9_]*)=(.*)$/.exec(line);\n const key = match?.[1];\n const raw = match?.[2];\n if (key === undefined || raw === undefined || !wanted.has(key)) continue;\n values.set(key, raw.trim().replace(/^(['\"])(.*)\\1$/, '$2'));\n }\n if (values.get('GR_PROVISIONED_RUNTIME') !== 'native') return undefined;\n const apiPort = parsePortToken(values.get('API_NGINX_PORT'));\n const frontendPort = parsePortToken(values.get('FRONTEND_PORT'));\n if (apiPort === undefined || frontendPort === undefined) return undefined;\n return { envPath, ports: { apiPort, frontendPort } };\n}\n\nfunction unresolved(\n root: string,\n overridePath: string,\n reason: string\n): Extract<CheckoutClassification, { kind: 'unresolved-worktree' }> {\n return { kind: 'unresolved-worktree', root, overridePath, reason };\n}\n\nfunction loadComposeDocument(content: string): Record<string, unknown> | undefined {\n let loaded: unknown;\n try {\n loaded = load(content, { schema: COMPOSE_OVERRIDE_SCHEMA });\n } catch {\n return undefined;\n }\n return isRecord(loaded) ? loaded : undefined;\n}\n\n/**\n * Classify the checkout rooted at (or above) `startDir`.\n *\n * A linked worktree has a `.git` *file*. A primary checkout has a `.git`\n * directory. No repository is treated as non-worktree so packaged CLI\n * invocations keep environment defaults.\n */\nexport function classifyCheckout(startDir: string = process.cwd()): CheckoutClassification {\n const git = findNearestGit(startDir);\n if (!git || !git.gitIsFile) {\n return { kind: 'non-worktree', root: git?.root };\n }\n\n const overridePath = join(git.root, OVERRIDE_FILENAME);\n // git.root is the checkout found by walking up from cwd to `.git` (as for\n // overridePath above) and the filename is a constant: no caller-supplied path.\n // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal\n const envPath = join(git.root, ENV_FILENAME);\n if (!existsSync(overridePath)) {\n const native = nativeWorktreePorts(envPath);\n if (native) {\n return {\n kind: 'resolved-worktree',\n root: git.root,\n overridePath: native.envPath,\n ...native.ports,\n };\n }\n return unresolved(\n git.root,\n overridePath,\n `docker-compose.override.yml (generated by ${WORKTREE_SETUP_MARKER})`\n );\n }\n\n let content: string;\n try {\n content = readFileSync(overridePath, 'utf-8');\n } catch {\n return unresolved(git.root, overridePath, 'readable generated worktree override');\n }\n\n if (!content.includes(WORKTREE_SETUP_MARKER)) {\n return unresolved(\n git.root,\n overridePath,\n `generated ${WORKTREE_SETUP_MARKER} override marker`\n );\n }\n\n const document = loadComposeDocument(content);\n if (!document) {\n return unresolved(git.root, overridePath, 'valid generated worktree override YAML');\n }\n\n const services = document['services'];\n if (!isRecord(services)) {\n return unresolved(\n git.root,\n overridePath,\n `api-nginx published port for container ${API_CONTAINER_PORT}; frontend published port for container ${FRONTEND_CONTAINER_PORT}`\n );\n }\n\n const apiPort = publishedPortForTarget(servicePorts(services, 'api-nginx'), API_CONTAINER_PORT);\n const frontendPort = publishedPortForTarget(\n servicePorts(services, 'frontend'),\n FRONTEND_CONTAINER_PORT\n );\n const missing: string[] = [];\n if (apiPort === undefined) {\n missing.push(`api-nginx published port for container ${API_CONTAINER_PORT}`);\n }\n if (frontendPort === undefined) {\n missing.push(`frontend published port for container ${FRONTEND_CONTAINER_PORT}`);\n }\n if (apiPort === undefined || frontendPort === undefined) {\n return unresolved(git.root, overridePath, missing.join('; '));\n }\n\n return {\n kind: 'resolved-worktree',\n root: git.root,\n overridePath,\n apiPort,\n frontendPort,\n };\n}\n\nfunction worktreeFailClosed(\n checkout: Extract<CheckoutClassification, { kind: 'unresolved-worktree' }>,\n missingFields: string[]\n): never {\n throw new WorktreeConfigError(\n `Cannot resolve ${missingFields.join(' and ')} URL(s) for this linked worktree.\\n` +\n `Checkout: ${checkout.root}\\n` +\n `Override: ${checkout.overridePath}\\n` +\n `Missing: ${checkout.reason}\\n` +\n `Re-run scripts/worktree-setup.sh . from this checkout, or pass explicit ` +\n `--api-url and GRAVITY_RAIL_FRONTEND_URL (or both GRAVITY_RAIL_API_URL and ` +\n `GRAVITY_RAIL_FRONTEND_URL) so neither URL inherits the primary checkout.`,\n checkout.root,\n checkout.overridePath\n );\n}\n\nfunction worktreeDevUrls(apiPort: number, frontendPort: number): EnvironmentConfig {\n return {\n apiUrl: `https://api.gravityrail.test:${apiPort}`,\n frontendUrl: `https://app.gravityrail.test:${frontendPort}`,\n };\n}\n\nexport function getEnvironmentConfig(\n env: string,\n options: EnvironmentConfigOptions = {}\n): EnvironmentConfig {\n // Handle dev-cloud environments: --env dev-cloud:NAMESPACE\n if (env.startsWith('dev-cloud:')) {\n const namespace = env.slice('dev-cloud:'.length);\n if (!namespace) {\n throw new Error('dev-cloud environment requires a namespace: --env dev-cloud:NAMESPACE');\n }\n return {\n apiUrl:\n options.apiUrl ||\n process.env.GRAVITY_RAIL_API_URL ||\n `https://${namespace}-api.gravityrail-dev.com`,\n frontendUrl:\n options.frontendUrl ||\n process.env.GRAVITY_RAIL_FRONTEND_URL ||\n `https://${namespace}-app.gravityrail-dev.com`,\n };\n }\n\n const config = ENVIRONMENTS[env];\n if (!config) {\n throw new Error(\n `Invalid environment: ${env}. Use 'dev', 'staging', 'prod', or 'dev-cloud:NAMESPACE'.`\n );\n }\n\n const explicitApi = options.apiUrl || process.env.GRAVITY_RAIL_API_URL;\n const explicitFrontend = options.frontendUrl || process.env.GRAVITY_RAIL_FRONTEND_URL;\n\n if (env !== 'dev') {\n return {\n apiUrl: explicitApi || config.apiUrl,\n frontendUrl: explicitFrontend || config.frontendUrl,\n };\n }\n\n // Inside a dev-cloud pod (its chart sets ENVIRONMENT=dev-cloud) the stack\n // runs natively, with no gravityrail.test proxy: the API is on :5050 and the\n // frontend on :3000. `gr auth import-dev` there imports the pod's own\n // dev-realms.json into the dev store, so `--env dev` reaches that API.\n if (process.env.ENVIRONMENT === 'dev-cloud') {\n return {\n apiUrl: explicitApi || DEV_CLOUD_POD_DEV.apiUrl,\n frontendUrl: explicitFrontend || DEV_CLOUD_POD_DEV.frontendUrl,\n };\n }\n\n const checkout = classifyCheckout(options.startDir ?? process.cwd());\n\n if (checkout.kind === 'non-worktree') {\n return {\n apiUrl: explicitApi || config.apiUrl,\n frontendUrl: explicitFrontend || config.frontendUrl,\n };\n }\n\n if (checkout.kind === 'resolved-worktree') {\n const detected = worktreeDevUrls(checkout.apiPort, checkout.frontendPort);\n return {\n apiUrl: explicitApi || detected.apiUrl,\n frontendUrl: explicitFrontend || detected.frontendUrl,\n };\n }\n\n const missingFields: string[] = [];\n if (!explicitApi) missingFields.push('API');\n if (!explicitFrontend) missingFields.push('frontend');\n if (missingFields.length > 0) {\n worktreeFailClosed(checkout, missingFields);\n }\n return { apiUrl: explicitApi!, frontendUrl: explicitFrontend! };\n}\n","/**\n * CLI OAuth2 authentication utilities\n *\n * Provides OAuth2 with PKCE flow for CLI tools, including:\n * - Credential caching (per environment + named profile)\n * - Dynamic client registration\n * - Token refresh\n * - Browser-based authorization\n *\n * Credential persistence lives in `./credentials-manager` (multi-account profiles).\n */\n\nimport { createServer } from 'http';\nimport { createHash, randomBytes } from 'crypto';\nimport { exec } from 'child_process';\nimport { existsSync, mkdirSync } from 'fs';\nimport { dirname } from 'path';\nimport lockfile from 'proper-lockfile';\nimport pkg from '../../package.json';\nimport { EnvironmentConfig, CALLBACK_PORT, CALLBACK_PATH, REDIRECT_URI } from './config';\nimport { CredentialsManager, type CLICredentials } from './credentials-manager';\n\nexport {\n CredentialsManager,\n DEFAULT_PROFILE,\n type CLICredentials,\n type ProfileSummary,\n} from './credentials-manager';\n\nexport interface AuthResult {\n accessToken: string;\n credentials?: CLICredentials;\n}\n\nexport interface NonInteractiveAuthOptions {\n env: string;\n envConfig: EnvironmentConfig;\n credentialsManager: CredentialsManager;\n profile?: string;\n}\n\nconst ACCESS_TOKEN_EXPIRY_BUFFER_MS = 5 * 60 * 1000;\n\n/**\n * Sent on every token grant so reuse investigations can tell CLI releases\n * apart. Self-reported identification, not authentication.\n */\nconst TOKEN_REQUEST_USER_AGENT = `gravityrail-cli/${pkg.version}`;\n\n/** The one timeout on a refresh: the token POST, including reading its body. */\nconst REFRESH_REQUEST_TIMEOUT_MS = 15_000;\n\n/**\n * How long a refresh waits for another process's refresh of the same\n * credential file: 100, 200, 400 and 800 ms, then 1 s per retry — about 20.5 s\n * over 23 retries. That outlasts one whole refresh by the lock holder (bounded\n * by `REFRESH_REQUEST_TIMEOUT_MS`), so a waiter adopts the winner's result\n * instead of giving up. The library keeps a held lock fresh and reclaims one\n * abandoned by a crashed process, so its `stale`/`update` defaults are kept.\n */\nconst REFRESH_LOCK_RETRIES = { retries: 23, factor: 2, minTimeout: 100, maxTimeout: 1000 };\n\n// Refresh failures that are not a verdict on the stored token. Fixed strings\n// by design: never interpolate tokens, response bodies or transport errors.\nconst REFRESH_LOCK_FAILED =\n 'Could not lock the credential store to refresh the access token (another gr process may still be refreshing). Stored credentials were kept; retry the command.';\nconst REFRESH_REQUEST_FAILED =\n 'Token refresh did not complete (network error or timeout). Stored credentials were kept; retry the command.';\nconst REFRESH_FAILED =\n 'Token refresh failed. Stored credentials were kept; retry the command, and log in again if it keeps failing.';\nconst REFRESH_SUPERSEDED =\n 'Token refresh was rejected, but the stored credentials changed meanwhile and were kept. Retry the command.';\nconst REFRESH_BAD_RESPONSE =\n 'Token refresh returned an unusable response. Stored credentials were kept; retry the command.';\nconst REFRESH_SAVE_FAILED =\n 'Token refresh succeeded, but the new credentials could not be saved. Retry the command, and log in again if it keeps failing.';\n\nfunction stderr(msg: string): void {\n process.stderr.write(msg + '\\n');\n}\n\n/**\n * Parse an OAuth error response body, checking the JSON `error` field first,\n * falling back to text matching.\n */\nfunction isOAuthError(body: string, errorCode: string): boolean {\n try {\n const parsed = JSON.parse(body);\n if (parsed.error === errorCode) return true;\n } catch {\n // Not JSON — fall through to text match\n }\n return body.includes(errorCode);\n}\n\n/**\n * Validate and extract fields from an OAuth token response.\n * Throws on malformed responses per RFC 6749 §5.1.\n */\nfunction validateTokenResponse(tokenData: Record<string, unknown>): {\n accessToken: string;\n refreshToken?: string;\n expiresIn: number;\n} {\n if (!tokenData.access_token || typeof tokenData.access_token !== 'string') {\n throw new Error('Token response missing access_token');\n }\n\n if (tokenData.token_type && String(tokenData.token_type).toLowerCase() !== 'bearer') {\n throw new Error(`Unsupported token type: ${tokenData.token_type}`);\n }\n\n let expiresIn = 86400; // default 24h\n if (tokenData.expires_in != null) {\n const raw = Number(tokenData.expires_in);\n if (!Number.isFinite(raw) || raw < 60 || raw > 31536000) {\n stderr(' Warning: unusual expires_in value in the token response, using default');\n } else {\n expiresIn = raw;\n }\n }\n\n return {\n accessToken: tokenData.access_token,\n refreshToken:\n typeof tokenData.refresh_token === 'string' ? tokenData.refresh_token : undefined,\n expiresIn,\n };\n}\n\n/**\n * Generate PKCE code verifier and challenge\n */\nexport function generatePKCE(): { codeVerifier: string; codeChallenge: string } {\n const codeVerifier = randomBytes(64).toString('base64url').slice(0, 128);\n const codeChallenge = createHash('sha256').update(codeVerifier).digest('base64url');\n return { codeVerifier, codeChallenge };\n}\n\n/**\n * Open a URL in the default browser\n */\nexport function openBrowser(url: string): void {\n const platform = process.platform;\n let cmd: string;\n if (platform === 'darwin') {\n cmd = `open \"${url}\"`;\n } else if (platform === 'win32') {\n cmd = `start \"\" \"${url}\"`;\n } else {\n cmd = `xdg-open \"${url}\"`;\n }\n\n exec(cmd, (err) => {\n if (err) {\n stderr(' Could not open browser automatically.');\n }\n });\n}\n\n/**\n * Start a local HTTP server to receive the OAuth callback\n */\nexport function startCallbackServer(): Promise<{ code: string; state: string }> {\n return new Promise((resolve, reject) => {\n let authCode: string | null = null;\n let error: string | null = null;\n let receivedState: string | null = null;\n\n const server = createServer((req, res) => {\n const url = new URL(req.url!, `http://localhost:${CALLBACK_PORT}`);\n\n if (url.pathname !== CALLBACK_PATH) {\n res.writeHead(404);\n res.end('Not found');\n return;\n }\n\n if (url.searchParams.has('error')) {\n error = url.searchParams.get('error');\n const errorDesc = url.searchParams.get('error_description') || 'Unknown error';\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(`\n <html>\n <head><title>Authorization Failed</title></head>\n <body style=\"font-family: system-ui; text-align: center; padding: 50px;\">\n <h1 style=\"color: #dc2626;\">Authorization Failed</h1>\n <p>${errorDesc}</p>\n <p>You can close this window.</p>\n </body>\n </html>\n `);\n server.close();\n reject(new Error(`Authorization failed: ${error}`));\n } else if (url.searchParams.has('code')) {\n authCode = url.searchParams.get('code')!;\n receivedState = url.searchParams.get('state')!;\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(`\n <html>\n <head><title>Authorization Successful</title></head>\n <body style=\"font-family: system-ui; text-align: center; padding: 50px;\">\n <h1 style=\"color: #16a34a;\">Authorization Successful!</h1>\n <p>You can close this window and return to the terminal.</p>\n <script>setTimeout(() => window.close(), 2000);</script>\n </body>\n </html>\n `);\n server.close();\n resolve({ code: authCode, state: receivedState });\n } else {\n res.writeHead(400);\n res.end('Missing code parameter');\n }\n });\n\n server.listen(CALLBACK_PORT, 'localhost', () => {\n // Server started\n });\n\n // Timeout after 5 minutes (unref so it doesn't keep the process alive)\n const timeout = setTimeout(\n () => {\n if (!authCode && !error) {\n server.close();\n reject(new Error('Authorization timeout - no response received'));\n }\n },\n 5 * 60 * 1000\n );\n timeout.unref();\n });\n}\n\n/**\n * Vendor field in the RFC 8414 discovery document naming the server's pinned\n * first-party CLI client. Must match `FIRST_PARTY_CLIENT_METADATA_FIELD` in\n * `lib/routes/oauth/first_party.py`.\n */\nexport const FIRST_PARTY_CLIENT_METADATA_FIELD = 'gravityrail_first_party_cli_client_id';\n\n/**\n * Ask the server for its pinned first-party CLI client id, or null if it has none.\n *\n * Null is the dynamic-registration fallback trigger, and it has to cover two\n * different situations that the CLI cannot and need not tell apart: a server\n * deployed before the pinned client shipped, and a discovery request that\n * failed. Both mean \"we have no pinned identity to use here\", and DCR is the\n * correct answer to both — so every failure mode collapses to null rather than\n * throwing and taking down a login that would otherwise have worked.\n */\nexport async function fetchFirstPartyClientId(\n envConfig: EnvironmentConfig\n): Promise<string | null> {\n try {\n const response = await fetch(`${envConfig.apiUrl}/.well-known/oauth-authorization-server`, {\n headers: { Accept: 'application/json' },\n });\n if (!response.ok) return null;\n const metadata = (await response.json()) as Record<string, unknown>;\n const clientId = metadata[FIRST_PARTY_CLIENT_METADATA_FIELD];\n return typeof clientId === 'string' && clientId.length > 0 ? clientId : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Register a new OAuth client dynamically.\n *\n * Retained for servers that predate the pinned first-party client — older\n * self-hosted and dev deployments — not as the normal path. See\n * `resolveOAuthClient`.\n */\nasync function dynamicClientRegistration(\n envConfig: EnvironmentConfig,\n clientName: string = 'Gravity CLI'\n): Promise<{ client_id: string; client_secret: string }> {\n stderr(' Registering OAuth client...');\n\n const registrationUrl = `${envConfig.apiUrl}/api/v2/oauth/register`;\n\n const registrationData = {\n client_name: clientName,\n redirect_uris: [REDIRECT_URI],\n grant_types: ['authorization_code', 'refresh_token'],\n response_types: ['code'],\n token_endpoint_auth_method: 'client_secret_basic',\n scope: 'workspace:admin',\n };\n\n const response = await fetch(registrationUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(registrationData),\n });\n\n if (!response.ok) {\n throw new Error(`Client registration failed: ${response.status} - ${await response.text()}`);\n }\n\n return (await response.json()) as { client_id: string; client_secret: string };\n}\n\n/**\n * Build the client-authentication half of a token request.\n *\n * A confidential client (one we registered dynamically, which issued us a\n * secret) authenticates with HTTP Basic. The pinned first-party client has no\n * secret and identifies itself with a body `client_id` instead — RFC 6749\n * §2.3.1, and RFC 8252 §8.5 for why a CLI cannot hold one in the first place.\n * The server accepts either and reads the id from the header first.\n */\nfunction tokenRequestAuth(\n clientId: string,\n clientSecret?: string\n): { headers: Record<string, string>; params: Record<string, string> } {\n if (clientSecret) {\n const authHeader = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');\n return {\n headers: { Authorization: `Basic ${authHeader}` },\n params: {},\n };\n }\n return { headers: {}, params: { client_id: clientId } };\n}\n\n/**\n * Decide which OAuth client this login should use.\n *\n * The pinned first-party client wins whenever the server has one, including\n * for profiles that were created by an older CLI against the same server —\n * that is what retires per-login dynamic registration rather than merely\n * stopping new profiles from using it. Swapping is safe precisely here and\n * nowhere else: `performOAuthFlow` mints a fresh token pair anyway, so nothing\n * bound to the old client survives the call. Profiles that are never logged in\n * again keep refreshing against their old client untouched.\n *\n * `forceDynamicRegistration` is the retry path: the server has just answered\n * `invalid_client` for whichever client the branches below chose, so it must\n * skip **both** of the reuse branches, not only discovery. Skipping discovery\n * alone would fall through to the cached branch and hand back the very client\n * that was rejected — and when the rejected client *was* the cached one, that\n * is an identical second attempt. \"Register a fresh client\" is the only\n * response that can differ from the attempt that just failed.\n *\n * Exported so the three branches can be tested directly — `performOAuthFlow`\n * around it opens a browser and binds a loopback port, which no unit test\n * should have to stand up to assert which client was chosen.\n */\nexport async function resolveOAuthClient(\n envConfig: EnvironmentConfig,\n stored: CLICredentials | null,\n clientName: string = 'Gravity CLI',\n forceDynamicRegistration: boolean = false\n): Promise<{ clientId: string; clientSecret?: string }> {\n if (!forceDynamicRegistration) {\n const pinned = await fetchFirstPartyClientId(envConfig);\n if (pinned) {\n stderr(' Using the first-party CLI client');\n return { clientId: pinned };\n }\n\n // No pinned client on this server. Reuse whatever this profile\n // registered before, so an older environment does not accumulate a\n // client per login.\n if (stored?.clientId && stored.clientSecret) {\n stderr(' Using cached client credentials');\n return { clientId: stored.clientId, clientSecret: stored.clientSecret };\n }\n }\n\n const registration = await dynamicClientRegistration(envConfig, clientName);\n return { clientId: registration.client_id, clientSecret: registration.client_secret };\n}\n\nexport interface OAuthFlowOptions {\n env: string;\n envConfig: EnvironmentConfig;\n credentialsManager: CredentialsManager;\n clientName?: string;\n /** Named account profile to store tokens under (default: resolved current). */\n profile?: string;\n /**\n * Test seam: wait for the loopback callback. Defaults to the real server.\n *\n * The two side effects below are the reason this function had no direct\n * tests — one shells out to the system browser and the other binds a fixed\n * port, neither of which a unit test may do. Injecting them is what lets\n * the \"a failed login must not touch the stored profile\" invariant be\n * tested at all. Production never passes either.\n */\n startCallback?: () => Promise<{ code: string; state: string }>;\n /** Test seam: open the authorization URL. Defaults to the real browser. */\n openAuthUrl?: (url: string) => void;\n}\n\n/**\n * Perform the full OAuth2 browser-based flow with PKCE.\n *\n * This always opens the browser for authorization. It never returns a cached\n * token — that's the job of createAuthenticatedContext. The only thing reused\n * is the registered OAuth client ID (which is identity, not auth).\n *\n * **Nothing is written to the credential store until the token exchange has\n * succeeded.** A login can end at the consent screen the member cancels, at a\n * network failure, or at the five-minute callback timeout, and every one of\n * those must leave the profile exactly as it was — see the comment on the\n * single `save` below for what persisting early actually broke.\n */\nexport async function performOAuthFlow(options: OAuthFlowOptions): Promise<AuthResult> {\n const {\n env,\n envConfig,\n credentialsManager,\n clientName = 'Gravity CLI',\n profile,\n startCallback = startCallbackServer,\n openAuthUrl = openBrowser,\n } = options;\n const profileName = credentialsManager.resolveProfileName(profile, env);\n let hasRetried = false;\n let forceDynamicRegistration = false;\n\n while (true) {\n const stored = credentialsManager.load(env, profileName);\n const { clientId, clientSecret } = await resolveOAuthClient(\n envConfig,\n stored,\n clientName,\n forceDynamicRegistration\n );\n\n const { codeVerifier, codeChallenge } = generatePKCE();\n const state = randomBytes(32).toString('base64url');\n\n const authParams = new URLSearchParams({\n response_type: 'code',\n client_id: clientId,\n redirect_uri: REDIRECT_URI,\n scope: 'workspace:admin',\n state: state,\n code_challenge: codeChallenge,\n code_challenge_method: 'S256',\n });\n\n const authUrl = `${envConfig.apiUrl}/api/v2/oauth/authorize?${authParams}`;\n\n const callbackPromise = startCallback();\n\n stderr('\\n Opening browser for authorization...');\n stderr(` Profile: ${profileName}`);\n stderr(` If browser doesn't open, visit:\\n ${authUrl}\\n`);\n openAuthUrl(authUrl);\n\n stderr(' Waiting for authorization (timeout: 5 minutes)...');\n let code: string;\n let receivedState: string;\n try {\n ({ code, state: receivedState } = await callbackPromise);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (!hasRetried && isOAuthError(msg, 'invalid_client')) {\n stderr(' Client rejected by the server, re-registering...');\n hasRetried = true;\n // The rejected client was only ever held in memory, so there is\n // nothing on disk to clean up — `forceDynamicRegistration` alone\n // is what makes the next pass register a fresh one.\n forceDynamicRegistration = true;\n continue;\n }\n throw err;\n }\n\n if (receivedState !== state) {\n throw new Error('State mismatch - possible CSRF attack');\n }\n\n stderr(' Authorization code received!');\n stderr(' Exchanging code for tokens...');\n\n const tokenUrl = `${envConfig.apiUrl}/api/v2/oauth/token`;\n const auth = tokenRequestAuth(clientId, clientSecret);\n\n const tokenResponse = await fetch(tokenUrl, {\n method: 'POST',\n headers: {\n ...auth.headers,\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'User-Agent': TOKEN_REQUEST_USER_AGENT,\n },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n code: code,\n redirect_uri: REDIRECT_URI,\n code_verifier: codeVerifier,\n ...auth.params,\n }),\n });\n\n if (!tokenResponse.ok) {\n const body = await tokenResponse.text();\n if (!hasRetried && isOAuthError(body, 'invalid_client')) {\n stderr(' Client rejected by the server, re-registering...');\n hasRetried = true;\n forceDynamicRegistration = true;\n continue;\n }\n throw new Error(`Token exchange failed: ${tokenResponse.status} - ${body}`);\n }\n\n const tokenData = (await tokenResponse.json()) as Record<string, unknown>;\n const { accessToken, refreshToken, expiresIn } = validateTokenResponse(tokenData);\n\n // The one and only write, and it happens after the exchange has already\n // succeeded. Persisting the client identity before the browser step used\n // to leave a cancelled, failed or timed-out login with the NEW client id\n // sitting next to the OLD tokens — and the refresh grant looks a token\n // up by `refresh_token AND app_id` (`lib/routes/oauth/oauth_token.py`),\n // so that pairing matches no row and the next refresh is a guaranteed\n // `invalid_grant`. A member who simply closed the consent tab lost the\n // session they already had.\n //\n // A refresh token is only carried over when the client identity is\n // unchanged, for the same reason: one minted for the previous client is\n // not merely useless under the new one, it is actively harmful, because\n // the server answers it with `invalid_grant` and `refreshAccessToken`\n // clears the profile on that definitive rejection.\n // Dropping it degrades to \"log in again\", which is the honest outcome.\n //\n // `clientSecret` is written unconditionally, and when it is `undefined`\n // that is load-bearing rather than a no-op: the spread has just copied a\n // stale DCR secret out of `stored`, and this key overwrites it with\n // `undefined`, which `JSON.stringify` then omits entirely from the\n // persisted store. Both halves matter — in memory `tokenRequestAuth`\n // reads `undefined` and takes the body-`client_id` path, and on disk the\n // secret is gone rather than lying in wait for the next load. Dropping\n // this key \"because undefined does nothing\" would put the pinned public\n // client back on the Basic-auth path with a secret it does not have.\n //\n // Everything else on the profile (pinned workspace, cached org sessions)\n // is preserved — only the client identity and the tokens are decided\n // here, and org sessions are keyed to the account, not the client.\n const clientChanged = stored?.clientId !== clientId;\n const creds: CLICredentials = {\n ...(stored ?? {}),\n clientId,\n clientSecret,\n accessToken,\n refreshToken: refreshToken ?? (clientChanged ? undefined : stored?.refreshToken),\n expiresAt: new Date(Date.now() + expiresIn * 1000).toISOString(),\n };\n\n credentialsManager.save(env, creds, profileName);\n credentialsManager.setCurrentProfile(env, profileName);\n stderr(' Authentication successful!');\n\n return { accessToken, credentials: creds };\n }\n}\n\n/**\n * The `error` code of a JSON OAuth error body, or undefined when the body is\n * not one.\n *\n * Unlike `isOAuthError` there is no substring fallback: this decides whether a\n * profile is deleted, and only a structured server verdict may do that.\n */\nfunction parseOAuthErrorCode(body: string): string | undefined {\n try {\n const parsed: unknown = JSON.parse(body);\n if (parsed && typeof parsed === 'object') {\n const code = (parsed as { error?: unknown }).error;\n if (typeof code === 'string') return code;\n }\n } catch {\n // Not JSON — no verdict.\n }\n return undefined;\n}\n\n/**\n * Whether the stored access token has enough life left to run a command on.\n *\n * The same `ACCESS_TOKEN_EXPIRY_BUFFER_MS` horizon the resolver uses, so a\n * single process that entered the refresh with a few minutes left still\n * rotates instead of adopting a token that may expire mid-command. A waiter\n * still adopts the winner's successor without rotating it again: the server\n * mints access tokens for far longer than the buffer (24 h, `oauth_token.py`),\n * so a successor another process just stored always clears this check. A token\n * with no recorded expiry is usable, as everywhere else.\n */\nfunction isFreshEnough(creds: CLICredentials): boolean {\n return (\n !creds.expiresAt ||\n new Date(creds.expiresAt).getTime() > Date.now() + ACCESS_TOKEN_EXPIRY_BUFFER_MS\n );\n}\n\n/**\n * Take the cross-process refresh lock for one credential file.\n *\n * The target is the credential file's own path, so every refresh that shares\n * an environment (and API port) file serializes, whichever profile it is for.\n * The file need not exist: the library locks with a sibling `<path>.lock`\n * directory and `realpath: false` skips resolving the target.\n */\nasync function acquireRefreshLock(credentialsPath: string): Promise<() => Promise<void>> {\n try {\n const cacheDir = dirname(credentialsPath);\n if (!existsSync(cacheDir)) {\n mkdirSync(cacheDir, { recursive: true, mode: 0o700 });\n }\n return await lockfile.lock(credentialsPath, {\n realpath: false,\n retries: REFRESH_LOCK_RETRIES,\n // The library default throws from a timer, which would crash the\n // command. Losing the lock mid-refresh is worth a warning, not that.\n // The library has already dropped its in-process record of the lock\n // by the time this runs, so the `release()` in `refreshAccessToken`'s\n // `finally` is refused (ENOTACQUIRED) and can never remove a lock\n // another process has since taken.\n onCompromised: () => {\n stderr(\n ' Warning: lost the credential refresh lock; another gr process may refresh at the same time'\n );\n },\n });\n } catch {\n // Never fall back to an unlocked refresh: that is exactly the race this\n // lock exists to prevent.\n throw new Error(REFRESH_LOCK_FAILED);\n }\n}\n\n/**\n * Refresh the selected profile's access token, coordinating with other `gr`\n * processes on this machine (GitHub #29807).\n *\n * The server rotates refresh tokens and rejects a spent one as reuse, so two\n * processes presenting the same token race: one wins, the other gets\n * `invalid_grant`. Everything from reading the stored token to saving its\n * successor therefore runs under one lock on the credential file. A process\n * that waited re-reads the store and adopts what the winner saved instead of\n * presenting the spent token.\n *\n * `creds` is the caller's pre-lock snapshot and is deliberately not consulted:\n * every decision — whether a refresh is needed, which token to present, what\n * to save — is made from the profile read under the lock, because the snapshot\n * may already have been rotated away, logged out, or replaced by a login. The\n * parameter stays for the exported signature.\n *\n * Returns the profile's usable credentials, or null when the profile cannot\n * authenticate — including after a definitive rejection, which clears that\n * profile only. Any other failure (network, timeout, server error, malformed\n * response, a busy lock, a failed save) leaves the store untouched and throws a\n * plain Error whose message is fixed: no token, response body, or transport\n * detail ever reaches it.\n */\nexport async function refreshAccessToken(\n envConfig: EnvironmentConfig,\n _creds: CLICredentials,\n credentialsManager: CredentialsManager,\n env: string,\n profile?: string\n): Promise<CLICredentials | null> {\n // Resolved once, before waiting, so a `gr auth switch` in another process\n // cannot redirect this command to a different profile mid-refresh.\n const profileName = credentialsManager.resolveProfileName(profile, env);\n const release = await acquireRefreshLock(credentialsManager.getCredentialsFilePath(env));\n try {\n return await refreshUnderLock(envConfig, credentialsManager, env, profileName);\n } finally {\n // Rejects only when the lock was already lost (see `onCompromised`);\n // there is nothing left to release then.\n await release().catch(() => undefined);\n }\n}\n\nasync function refreshUnderLock(\n envConfig: EnvironmentConfig,\n credentialsManager: CredentialsManager,\n env: string,\n profileName: string\n): Promise<CLICredentials | null> {\n const stored = credentialsManager.load(env, profileName);\n\n // Another process may have refreshed while this one waited for the lock.\n if (stored?.accessToken && isFreshEnough(stored)) {\n return stored;\n }\n // A client secret is no longer part of the requirement: the pinned\n // first-party client is public and has none, and demanding one here would\n // silently strand every profile logged in with it — `context.ts` treats a\n // null return as \"re-login required\", so the CLI would open a browser on\n // every command instead of refreshing.\n if (!stored?.refreshToken || !stored.clientId) {\n stderr(' Cannot refresh: missing credentials (re-login required)');\n return null;\n }\n\n const presentedRefreshToken = stored.refreshToken;\n const auth = tokenRequestAuth(stored.clientId, stored.clientSecret);\n\n let response: Response;\n try {\n response = await fetch(`${envConfig.apiUrl}/api/v2/oauth/token`, {\n method: 'POST',\n headers: {\n ...auth.headers,\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'User-Agent': TOKEN_REQUEST_USER_AGENT,\n },\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: presentedRefreshToken,\n ...auth.params,\n }),\n // Bounds the request and the body reads below. Never retried: a\n // second POST of the same token is itself a reuse.\n //\n // Known residual: an abort only stops *this* side. If the server\n // commits the rotation after the deadline, the response carrying the\n // successor is lost and the stored token is spent; the next refresh\n // of it is a genuine invalid_grant and clears the profile. The client\n // cannot recover an unseen successor; the deadline is long enough\n // that this needs a token endpoint stalled for 15 s, not a slow one.\n signal: AbortSignal.timeout(REFRESH_REQUEST_TIMEOUT_MS),\n });\n } catch {\n throw new Error(REFRESH_REQUEST_FAILED);\n }\n\n if (!response.ok) {\n let body: string;\n try {\n body = await response.text();\n } catch {\n throw new Error(REFRESH_REQUEST_FAILED);\n }\n if (response.status === 400 && parseOAuthErrorCode(body) === 'invalid_grant') {\n // The verdict is about the token presented, not whatever the store\n // holds now. Clear only if that same token is still stored, so a\n // stale rejection can never delete a replacement saved meanwhile.\n const current = credentialsManager.load(env, profileName);\n if (!current) {\n stderr(' The server rejected the stored refresh token; re-login required');\n return null;\n }\n // Two local values from the user's own credential file; no remote\n // party can observe this comparison's timing. FP (CWE-208).\n // bearer:disable javascript_lang_observable_timing\n if (current.refreshToken === presentedRefreshToken) {\n credentialsManager.clear(env, profileName);\n stderr(' The server rejected the stored refresh token; re-login required');\n return null;\n }\n throw new Error(REFRESH_SUPERSEDED);\n }\n if (parseOAuthErrorCode(body) === 'invalid_client') {\n // The OAuth client this profile was issued under no longer exists\n // (`lib/routes/oauth/oauth_token.py` answers 401 invalid_client).\n // Nothing in the profile can authenticate again, so surface the\n // existing re-login path — but it is a verdict on the client, not\n // on the stored tokens, so leave the profile for `gr login` to\n // replace rather than deleting it here.\n stderr(\" The server no longer recognises this profile's OAuth client; re-login required\");\n return null;\n }\n throw new Error(REFRESH_FAILED);\n }\n\n let tokens: ReturnType<typeof validateTokenResponse>;\n try {\n tokens = validateTokenResponse((await response.json()) as Record<string, unknown>);\n } catch {\n throw new Error(REFRESH_BAD_RESPONSE);\n }\n\n // Merge into a fresh read so profile metadata (pinned workspace, cached\n // org sessions) written while the request was in flight survives. Login\n // and logout take no refresh lock, so the profile may also be gone or be\n // a different grant by now; the successor belongs to the grant that was\n // presented and must not be written over either.\n const latest = credentialsManager.load(env, profileName);\n if (!latest) {\n // Logged out while the request was in flight. The successor dies with\n // the grant it belongs to; resurrecting the profile would undo the logout.\n stderr(' Cannot refresh: missing credentials (re-login required)');\n return null;\n }\n // Two local values from the user's own credential file; no remote party\n // can observe this comparison's timing. FP (CWE-208).\n // bearer:disable javascript_lang_observable_timing\n if (latest.clientId !== stored.clientId || latest.refreshToken !== presentedRefreshToken) {\n // A login replaced the profile. Its tokens are a different grant (the\n // server keys them by refresh_token AND client), so writing this\n // successor over them would make the new login's next refresh an\n // invalid_grant. Use the login if it can authenticate; otherwise this\n // refresh has nothing valid to offer.\n if (latest.accessToken && isFreshEnough(latest)) {\n return latest;\n }\n throw new Error(REFRESH_SUPERSEDED);\n }\n\n const updated: CLICredentials = {\n ...latest,\n accessToken: tokens.accessToken,\n // A server may omit `refresh_token` when it does not rotate; the\n // presented token then stays valid.\n refreshToken: tokens.refreshToken ?? presentedRefreshToken,\n expiresAt: new Date(Date.now() + tokens.expiresIn * 1000).toISOString(),\n };\n try {\n credentialsManager.save(env, updated, profileName);\n } catch {\n throw new Error(REFRESH_SAVE_FAILED);\n }\n return updated;\n}\n\n/**\n * Resolve credentials that do not require a browser.\n *\n * Precedence: process API key, then the selected profile's valid access token,\n * then that profile's refresh token. A null result leaves the caller to decide\n * whether interactive OAuth is appropriate for its command.\n */\nexport async function resolveNonInteractiveAuth(\n options: NonInteractiveAuthOptions\n): Promise<AuthResult | null> {\n const { env, envConfig, credentialsManager, profile } = options;\n\n // Process env only — API keys are never persisted in the credential store.\n const apiKey = process.env.GRAVITY_RAIL_API_KEY;\n if (apiKey) {\n return { accessToken: apiKey };\n }\n\n const profileName = credentialsManager.resolveProfileName(profile, env);\n const credentials = credentialsManager.load(env, profileName);\n if (!credentials?.accessToken) return null;\n\n const notExpired =\n !credentials.expiresAt ||\n new Date(credentials.expiresAt) > new Date(Date.now() + ACCESS_TOKEN_EXPIRY_BUFFER_MS);\n if (notExpired) {\n return { accessToken: credentials.accessToken, credentials };\n }\n\n const refreshed = await refreshAccessToken(\n envConfig,\n credentials,\n credentialsManager,\n env,\n profileName\n );\n if (!refreshed?.accessToken) return null;\n\n return { accessToken: refreshed.accessToken, credentials: refreshed };\n}\n","{\n \"name\": \"@gravity-rail/cli\",\n \"version\": \"6.1.0\",\n \"description\": \"Gravity Rail CLI — manage workspaces from the command line\",\n \"type\": \"module\",\n \"bin\": {\n \"gr\": \"./dist/gr.js\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/lib.d.ts\",\n \"import\": \"./dist/lib.js\"\n },\n \"./lib\": {\n \"types\": \"./dist/lib.d.ts\",\n \"import\": \"./dist/lib.js\"\n },\n \"./cli-utils\": {\n \"types\": \"./dist/cli-utils.d.ts\",\n \"import\": \"./dist/cli-utils.js\"\n }\n },\n \"files\": [\n \"dist\"\n ],\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/Gravity-Rail/gravity-team.git\",\n \"directory\": \"packages/cli\"\n },\n \"homepage\": \"https://developer.gravityrail.com\",\n \"keywords\": [\n \"gravity-rail\",\n \"cli\",\n \"healthcare\",\n \"workspace\"\n ],\n \"engines\": {\n \"node\": \">=18\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"generate:skill-docs\": \"tsx scripts/generate-skill-docs.ts\",\n \"clean\": \"rm -rf dist\",\n \"typecheck\": \"bash ../../scripts/tsc-admitted.sh --noEmit\",\n \"test\": \"jest --forceExit\",\n \"test:ci\": \"jest --forceExit --passWithNoTests --coverage --coverageReporters=json-summary --coverageReporters=text-summary\"\n },\n \"dependencies\": {\n \"@gravity-rail/sdk\": \"workspace:^\",\n \"js-yaml\": \"^5.5.0\",\n \"libphonenumber-js\": \"^1.13.16\",\n \"proper-lockfile\": \"^4.1.2\"\n },\n \"devDependencies\": {\n \"@gravity-rail/sandbox\": \"workspace:*\",\n \"@types/jest\": \"^30.0.0\",\n \"@types/node\": \"^26.6.6\",\n \"@types/proper-lockfile\": \"^4.1.4\",\n \"jest\": \"^30.5.2\",\n \"ts-jest\": \"29.4.9\",\n \"tsup\": \"^9.0.0\",\n \"typescript\": \"^6.0.3\",\n \"typescript-native\": \"npm:typescript@7.0.2\",\n \"undici\": \"6.29.1\"\n }\n}\n","/**\n * CLI credential store with multi-account profile support.\n *\n * Store location: `~/.gr-cli/credentials-<env>.json` (mode 0600; dir mode 0700).\n * Format is versioned JSON with named profiles (aws-style). Flat single-credential\n * files from older CLI versions migrate to profile \"default\" on first read/write.\n *\n * Security notes (for operators / security review):\n * - Tokens and client secrets live only on the local filesystem under the user's home.\n * - Files are written mode 0600; the cache directory is created mode 0700.\n * - Profile and environment names are allowlist-validated with a\n * resolve()/relative() containment check so path traversal cannot escape `.gr-cli`.\n * - Callers must never log credential field values (accessToken, refreshToken, secrets).\n * - `GRAVITY_RAIL_API_KEY` is not persisted here; it remains process-env only and\n * overrides stored profiles for non-interactive automation.\n * - Dev profiles imported from `dev-realms.json` store bearer tokens only (no OAuth\n * client secret). They are local-dev conveniences and must never be committed.\n */\n\nimport {\n readFileSync,\n writeFileSync,\n existsSync,\n mkdirSync,\n chmodSync,\n unlinkSync,\n renameSync,\n} from 'fs';\nimport { join, resolve, relative, isAbsolute } from 'path';\nimport { isOrgSessionCredential } from '../lib/org-session';\n\nexport const DEFAULT_PROFILE = 'default';\n\n/** `URL.hostname` spellings of the local machine (IPv6 keeps its brackets). */\nconst LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '[::1]']);\n\n/**\n * Stored credentials for one named profile.\n *\n * OAuth logins have a clientId (+ optional refresh). `clientSecret` is present\n * only for a dynamically registered confidential client; profiles using the\n * pinned first-party public client have none, by design (GRA-7843).\n * Dev profiles imported from dev-realms.json are token-only (accessToken +\n * optional workspaceUuid) — no OAuth client registration.\n */\n/**\n * A cached org-scoped SSO session (`gr_sess_...`) obtained via browser step-up.\n * Replayed as the `X-Org-Session` header so subsequent invocations skip the\n * browser until the session expires (GRA-6995).\n */\nexport interface StoredOrgSession {\n session: string;\n /** ISO expiry; treated as a cache miss once passed. */\n expiresAt?: string;\n}\n\nexport interface CLICredentials {\n clientId?: string;\n clientSecret?: string;\n accessToken?: string;\n refreshToken?: string;\n expiresAt?: string;\n /** Default workspace UUID (workspace/member profiles from dev-realms). */\n workspaceUuid?: string;\n /**\n * Cached org-scoped SSO sessions keyed by organization UUID. Populated by the\n * org-auth step-up handler; independent of the account token's own expiry.\n */\n orgSessions?: Record<string, StoredOrgSession>;\n}\n\nexport interface ProfileSummary {\n name: string;\n current: boolean;\n hasAccessToken: boolean;\n /** ISO timestamp if known; never includes the token itself. */\n expiresAt?: string;\n /** Present when the profile pins a default workspace. */\n workspaceUuid?: string;\n}\n\ninterface CredentialStoreV2 {\n version: 2;\n currentProfile: string;\n profiles: Record<string, CLICredentials>;\n}\n\n/**\n * Manages CLI credentials storage (one file per environment, multi-profile).\n */\nexport class CredentialsManager {\n private cacheDir: string;\n private apiUrl?: string;\n\n constructor(rootDir: string, apiUrl?: string) {\n // `rootDir` is supplied only by CLI bootstrap (context.ts passes\n // os.homedir()) — the local user's own home directory, never remote or\n // request input — joined with the constant '.gr-cli'. FP (CWE-22).\n // bearer:disable javascript_lang_path_traversal\n // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal\n this.cacheDir = join(rootDir, '.gr-cli');\n this.apiUrl = apiUrl;\n }\n\n /**\n * Validate a profile name. Allows the legacy realm path form\n * `workspace/member` so `acme-demo/acme-admin` works as a profile name.\n * Rejects path traversal and absolute paths.\n */\n validateProfileName(profile: string): void {\n if (!profile) {\n throw new Error('Invalid profile name: (empty).');\n }\n if (profile.includes('..') || profile.startsWith('/') || profile.endsWith('/')) {\n throw new Error(\n `Invalid profile name: ${profile}. Do not use \"..\" or leading/trailing \"/\".`\n );\n }\n // Letters, digits, '_', '-', '.', and a single-level '/' for workspace/member.\n if (!/^[a-zA-Z0-9_.-]+(?:\\/[a-zA-Z0-9_.-]+)?$/.test(profile)) {\n throw new Error(\n `Invalid profile name: ${profile}. Use letters, digits, '_', '-', '.', ` +\n `or workspace/member form (one slash).`\n );\n }\n }\n\n /**\n * Resolve which profile to use for this invocation.\n * Precedence: explicit flag → GRAVITY_RAIL_PROFILE → stored current → \"default\".\n */\n resolveProfileName(explicit?: string | null, env?: string): string {\n if (explicit) {\n this.validateProfileName(explicit);\n return explicit;\n }\n const fromEnv = process.env.GRAVITY_RAIL_PROFILE;\n if (fromEnv) {\n this.validateProfileName(fromEnv);\n return fromEnv;\n }\n if (env) {\n return this.getCurrentProfile(env);\n }\n return DEFAULT_PROFILE;\n }\n\n getCurrentProfile(env: string): string {\n const parsed = this.readStore(env);\n if (!parsed) return DEFAULT_PROFILE;\n return parsed.store.currentProfile || DEFAULT_PROFILE;\n }\n\n setCurrentProfile(env: string, profile: string): void {\n this.validateProfileName(profile);\n const store = this.readStore(env)?.store ?? this.emptyStore(profile);\n if (!store.profiles[profile]) {\n throw new Error(\n `Profile \"${profile}\" has no stored credentials for ${env}. ` +\n `Run: gr auth login --name ${profile} (or gr auth import-dev for local tokens)`\n );\n }\n store.currentProfile = profile;\n this.writeStore(env, store);\n }\n\n listProfiles(env: string): ProfileSummary[] {\n const parsed = this.readStore(env);\n if (!parsed) return [];\n const store = parsed.store;\n const current = store.currentProfile || DEFAULT_PROFILE;\n return Object.keys(store.profiles)\n .sort()\n .map((name) => {\n const creds = store.profiles[name]!;\n return {\n name,\n current: name === current,\n hasAccessToken: Boolean(creds.accessToken || creds.refreshToken),\n expiresAt: creds.expiresAt,\n workspaceUuid: creds.workspaceUuid,\n };\n });\n }\n\n private getCredentialsPath(env: string): string {\n // `env` comes from --env and the dev-cloud:NAMESPACE branch accepts an\n // arbitrary namespace, so it could contain `..` or a path separator and\n // escape the cache directory. Validate against an allowlist first (real\n // env names are alphanumerics, `-`, `_`, `.`, and the dev-cloud `:`\n // separator). This rejects path separators outright — including the\n // `foo/bar` case that would otherwise resolve inside .gr-cli but fail\n // later with a cryptic ENOENT from the un-created subdirectory.\n if (!/^[a-zA-Z0-9_:.-]+$/.test(env)) {\n throw new Error(`Invalid environment name: ${env}`);\n }\n // Defense-in-depth: also contain the resolved path before any fs\n // operation, so a future change to buildCredentialsPath can't reintroduce\n // an escape even if the allowlist is loosened.\n const candidate = this.buildCredentialsPath(env);\n // `this.cacheDir` is rooted at os.homedir() (see constructor) — a constant\n // resolve of the user's own dir, no attacker input. FP (CWE-22).\n // bearer:disable javascript_lang_path_traversal\n const resolvedDir = resolve(this.cacheDir);\n // This resolve()/relative() pair IS the containment sanitizer — `env` was\n // already allowlist-validated above. Semgrep's taint tracker flags the\n // resolve() of the env-derived candidate without modelling the guard.\n // bearer:disable javascript_lang_path_traversal\n // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal\n const rel = relative(resolvedDir, resolve(candidate));\n if (rel.startsWith('..') || isAbsolute(rel)) {\n throw new Error(`Invalid environment name: ${env}`);\n }\n return candidate;\n }\n\n private buildCredentialsPath(env: string): string {\n // Isolate credential files by non-default API port so worktrees (shifted\n // ports + separate DBs) do not clobber each other's imported tokens.\n if (this.apiUrl) {\n try {\n const url = new URL(this.apiUrl);\n const port = url.port;\n if (port && port !== '80' && port !== '443') {\n // :5050 on loopback is the native API — a laptop's, and the one\n // inside a dev-cloud pod, whose `gr auth import-dev` writes the\n // unsuffixed store — so every loopback spelling shares it.\n const isCanonicalLocalDev =\n (LOOPBACK_HOSTNAMES.has(url.hostname) && port === '5050') ||\n (url.hostname.endsWith('gravityrail.test') && port === '5054');\n if (!isCanonicalLocalDev) {\n // `env` is allowlist-validated in getCredentialsPath before this\n // builder runs, cacheDir is homedir-rooted, and url.port is a\n // parsed URL port — no traversal component. FP (CWE-22).\n // bearer:disable javascript_lang_path_traversal\n // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal\n return join(this.cacheDir, `credentials-${env}-${port}.json`);\n }\n }\n } catch {\n // ignore invalid URLs\n }\n }\n // `env` is allowlist-validated in getCredentialsPath before this builder\n // runs and cacheDir is homedir-rooted — no traversal component. FP (CWE-22).\n // bearer:disable javascript_lang_path_traversal\n // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal\n return join(this.cacheDir, `credentials-${env}.json`);\n }\n\n private emptyStore(currentProfile = DEFAULT_PROFILE): CredentialStoreV2 {\n return { version: 2, currentProfile, profiles: {} };\n }\n\n private isCredentialShape(value: unknown): value is CLICredentials {\n if (!value || typeof value !== 'object') return false;\n const v = value as Record<string, unknown>;\n // Local JSON shape check only — typeof / field presence, not secret comparison.\n // FP (CWE-208): no secret values are compared; short-circuit cannot leak content.\n // A client id alone is a complete OAuth identity: the pinned first-party\n // client is public and has no secret (GRA-7843). Requiring `clientSecret`\n // here would make every such profile fail the shape check and be silently\n // dropped on read — losing the pinned id and the tokens stored beside it.\n // bearer:disable javascript_lang_observable_timing\n const hasOAuth = typeof v.clientId === 'string' && v.clientId.length > 0;\n // bearer:disable javascript_lang_observable_timing\n const hasToken = typeof v.accessToken === 'string' && v.accessToken.length > 0;\n return hasOAuth || hasToken;\n }\n\n /**\n * Read and normalize the on-disk store (migrating legacy formats in memory).\n * `wasLegacy` is true when the file was not already v2 so callers can rewrite once.\n */\n private readStore(env: string): { store: CredentialStoreV2; wasLegacy: boolean } | null {\n const credsPath = this.getCredentialsPath(env);\n if (!existsSync(credsPath)) {\n return null;\n }\n\n try {\n const raw = JSON.parse(readFileSync(credsPath, 'utf-8')) as Record<string, unknown>;\n\n // v2 multi-profile\n if (raw.version === 2 && raw.profiles && typeof raw.profiles === 'object') {\n const profiles: Record<string, CLICredentials> = {};\n for (const [name, value] of Object.entries(raw.profiles as Record<string, unknown>)) {\n if (this.isCredentialShape(value)) {\n profiles[name] = value;\n }\n }\n const current =\n typeof raw.currentProfile === 'string' && profiles[raw.currentProfile]\n ? raw.currentProfile\n : Object.keys(profiles)[0] || DEFAULT_PROFILE;\n return {\n store: { version: 2, currentProfile: current, profiles },\n wasLegacy: false,\n };\n }\n\n // Flat single-credential format (pre-multi-account)\n if (this.isCredentialShape(raw)) {\n return {\n store: {\n version: 2,\n currentProfile: DEFAULT_PROFILE,\n profiles: { [DEFAULT_PROFILE]: raw },\n },\n wasLegacy: true,\n };\n }\n\n // Old org-namespaced format { default: {...} }\n const legacyDefault = (raw as { default?: unknown }).default;\n if (this.isCredentialShape(legacyDefault)) {\n return {\n store: {\n version: 2,\n currentProfile: DEFAULT_PROFILE,\n profiles: { [DEFAULT_PROFILE]: legacyDefault },\n },\n wasLegacy: true,\n };\n }\n\n return null;\n } catch {\n return null;\n }\n }\n\n private ensureCacheDir(): void {\n if (!existsSync(this.cacheDir)) {\n mkdirSync(this.cacheDir, { recursive: true, mode: 0o700 });\n try {\n chmodSync(this.cacheDir, 0o700);\n } catch {\n // Ignore permission errors on Windows\n }\n }\n }\n\n private writeStore(env: string, store: CredentialStoreV2): void {\n this.ensureCacheDir();\n const credsPath = this.getCredentialsPath(env);\n // Atomic replace: write a sibling temp file, chmod, then rename into place.\n // POSIX rename is atomic, so a crash mid-write cannot leave a partial JSON\n // that would wipe every profile on the next parse failure.\n const tmpPath = `${credsPath}.tmp`;\n writeFileSync(tmpPath, JSON.stringify(store, null, 2) + '\\n', { mode: 0o600 });\n try {\n chmodSync(tmpPath, 0o600);\n } catch {\n // Ignore permission errors on Windows\n }\n renameSync(tmpPath, credsPath);\n try {\n chmodSync(credsPath, 0o600);\n } catch {\n // Ignore permission errors on Windows\n }\n }\n\n private filterExpired(creds: CLICredentials): CLICredentials | null {\n if (creds.expiresAt) {\n const expiresAt = new Date(creds.expiresAt);\n if (expiresAt <= new Date()) {\n if (creds.refreshToken) {\n return creds;\n }\n return null;\n }\n }\n return creds;\n }\n\n /**\n * Load credentials for an environment + profile.\n * When `profile` is omitted, uses the resolved current profile for `env`.\n */\n load(env: string, profile?: string): CLICredentials | null {\n const parsed = this.readStore(env);\n if (!parsed) return null;\n\n const { store, wasLegacy } = parsed;\n const name = profile ?? store.currentProfile ?? DEFAULT_PROFILE;\n if (profile) this.validateProfileName(profile);\n const creds = store.profiles[name];\n if (!creds) return null;\n\n // Persist migration from flat/org formats so subsequent multi-profile ops work.\n // wasLegacy comes from the single parse in readStore — no second file read.\n if (wasLegacy) {\n this.writeStore(env, store);\n }\n\n return this.filterExpired(creds);\n }\n\n /**\n * Save credentials for an environment + profile.\n * When `profile` is omitted, uses the current profile (or \"default\").\n * Sets currentProfile to the saved profile when the store was empty.\n */\n save(env: string, creds: CLICredentials, profile?: string): void {\n if (profile) this.validateProfileName(profile);\n const store = this.readStore(env)?.store ?? this.emptyStore();\n const name = profile ?? store.currentProfile ?? DEFAULT_PROFILE;\n if (profile) {\n // Explicit profile on save also becomes current when first created, or when\n // the caller is logging into a named account.\n store.profiles[name] = creds;\n if (!store.profiles[store.currentProfile] || Object.keys(store.profiles).length === 1) {\n store.currentProfile = name;\n }\n } else {\n store.profiles[name] = creds;\n if (!store.currentProfile) {\n store.currentProfile = name;\n }\n }\n this.writeStore(env, store);\n }\n\n /**\n * Bulk-save many profiles in one write (used by dev-realms import).\n * Does not change currentProfile unless the store was empty — then uses\n * `preferCurrent` if provided and present, else `superadmin`, else first.\n */\n saveMany(env: string, profiles: Record<string, CLICredentials>, preferCurrent?: string): number {\n const names = Object.keys(profiles);\n for (const name of names) {\n this.validateProfileName(name);\n }\n const store = this.readStore(env)?.store ?? this.emptyStore();\n const wasEmpty = Object.keys(store.profiles).length === 0;\n for (const [name, creds] of Object.entries(profiles)) {\n store.profiles[name] = creds;\n }\n if (wasEmpty) {\n if (preferCurrent && store.profiles[preferCurrent]) {\n store.currentProfile = preferCurrent;\n } else if (store.profiles.superadmin) {\n store.currentProfile = 'superadmin';\n } else {\n store.currentProfile = names.sort()[0] ?? DEFAULT_PROFILE;\n }\n }\n this.writeStore(env, store);\n return names.length;\n }\n\n /**\n * Clear one profile (default: current profile). Deletes the file when no profiles remain.\n * Pass a profile name to clear a specific account without touching others.\n */\n clear(env: string, profile?: string): void {\n const parsed = this.readStore(env);\n if (!parsed) return;\n const store = parsed.store;\n\n const name = profile ?? store.currentProfile ?? DEFAULT_PROFILE;\n if (profile) this.validateProfileName(profile);\n delete store.profiles[name];\n\n if (Object.keys(store.profiles).length === 0) {\n const credsPath = this.getCredentialsPath(env);\n if (existsSync(credsPath)) {\n try {\n unlinkSync(credsPath);\n } catch {\n // Ignore\n }\n }\n return;\n }\n\n if (store.currentProfile === name) {\n store.currentProfile = Object.keys(store.profiles).sort()[0]!;\n }\n this.writeStore(env, store);\n }\n\n /**\n * Read a cached org-scoped SSO session for an org, if present and unexpired.\n * Independent of the account token's expiry — a valid org session is reusable\n * even while the account token is being refreshed.\n */\n getOrgSession(env: string, profile: string | undefined, orgUuid: string): string | undefined {\n const parsed = this.readStore(env);\n if (!parsed) return undefined;\n const name = profile ?? parsed.store.currentProfile ?? DEFAULT_PROFILE;\n if (profile) this.validateProfileName(profile);\n const entry = parsed.store.profiles[name]?.orgSessions?.[orgUuid];\n if (!isOrgSessionCredential(entry?.session)) return undefined;\n if (entry.expiresAt && new Date(entry.expiresAt) <= new Date()) return undefined;\n return entry.session;\n }\n\n /**\n * Cache an org-scoped SSO session under an existing profile, keyed by org UUID.\n * No-op when the profile does not exist — org sessions only attach to a\n * logged-in account profile (never create a token-less profile row).\n */\n setOrgSession(\n env: string,\n profile: string | undefined,\n orgUuid: string,\n session: string,\n expiresAt?: string\n ): void {\n if (!isOrgSessionCredential(session)) {\n throw new Error('Invalid organization session. Sign in again.');\n }\n const parsed = this.readStore(env);\n if (!parsed) return;\n const store = parsed.store;\n const name = profile ?? store.currentProfile ?? DEFAULT_PROFILE;\n if (profile) this.validateProfileName(profile);\n const creds = store.profiles[name];\n if (!creds) return;\n creds.orgSessions = {\n ...(creds.orgSessions ?? {}),\n [orgUuid]: { session, ...(expiresAt ? { expiresAt } : {}) },\n };\n this.writeStore(env, store);\n }\n\n /** Remove the entry only when its currently stored token matches the rejected one. */\n removeOrgSession(\n env: string,\n profile: string | undefined,\n orgUuid: string,\n expectedSession: string\n ): void {\n const parsed = this.readStore(env);\n if (!parsed) return;\n const name = profile ?? parsed.store.currentProfile ?? DEFAULT_PROFILE;\n if (profile) this.validateProfileName(profile);\n const sessions = parsed.store.profiles[name]?.orgSessions;\n if (sessions?.[orgUuid]?.session !== expectedSession) return;\n delete sessions[orgUuid];\n this.writeStore(env, parsed.store);\n }\n\n getCacheDir(): string {\n return this.cacheDir;\n }\n\n /** Absolute path of the credentials file for `env` (for docs / `auth list`). */\n getCredentialsFilePath(env: string): string {\n return this.getCredentialsPath(env);\n }\n}\n","/** The opaque org credential accepted by the SDK's X-Org-Session transport. */\nexport function isOrgSessionCredential(value: unknown): value is string {\n return typeof value === 'string' && /^gr_sess_[A-Za-z0-9_-]+$/.test(value);\n}\n","/**\n * CLI terminal UI utilities\n *\n * Provides interactive terminal UI components for CLI tools\n */\n\nimport * as readline from 'readline';\n\nexport interface SelectOption<T> {\n item: T;\n label: string;\n detail?: string;\n}\n\nexport interface SelectFromListOptions<T> {\n title?: string;\n labelFn?: (item: T) => string;\n detailFn?: (item: T) => string | null;\n env?: string;\n emptyMessage?: string;\n allowNew?: boolean;\n newLabel?: string;\n}\n\nexport interface SelectResult<T> {\n item: T | null;\n isNew: boolean;\n}\n\nconst NEW_ITEM_MARKER = Symbol('NEW_ITEM');\n\n/**\n * Interactive list picker using arrow keys\n */\nexport async function selectFromList<T>(\n items: T[],\n options: SelectFromListOptions<T> = {}\n): Promise<SelectResult<T>> {\n const {\n title = 'Select an item',\n labelFn = (item: T) => String((item as any).name || (item as any).title || item),\n detailFn = null,\n env = null,\n emptyMessage = 'No items found.',\n allowNew = false,\n newLabel = 'Create new...',\n } = options;\n\n if ((!items || items.length === 0) && !allowNew) {\n console.log(`\\n ${emptyMessage}`);\n return { item: null, isNew: false };\n }\n\n // Prepend \"Create new\" option if allowed\n const displayItems: (T | typeof NEW_ITEM_MARKER)[] = allowNew\n ? [NEW_ITEM_MARKER, ...items]\n : items;\n\n return new Promise((resolve) => {\n let selectedIndex = allowNew ? 1 : 0;\n let filterText = '';\n\n const getFilteredItems = (): (T | typeof NEW_ITEM_MARKER)[] => {\n if (!filterText) return displayItems;\n const lower = filterText.toLowerCase();\n return displayItems.filter((item) => {\n if (item === NEW_ITEM_MARKER) return true;\n const label = labelFn(item);\n return label.toLowerCase().includes(lower);\n });\n };\n\n const render = (): void => {\n const filtered = getFilteredItems();\n\n // Clear screen and move cursor to top\n process.stdout.write('\\x1B[2J\\x1B[H');\n\n console.log('='.repeat(60));\n console.log(`${title} (↑/↓ to move, Enter to select, Esc to cancel)`);\n console.log('='.repeat(60));\n if (env) {\n console.log(`Environment: ${env}`);\n }\n console.log(`Filter: ${filterText}${filterText ? '' : '(type to filter)'}`);\n console.log('');\n\n if (filtered.length === 0) {\n console.log(` ${emptyMessage}`);\n console.log('');\n return;\n }\n\n // Show up to 15 items around the selected one\n const maxVisible = 15;\n let startIdx = Math.max(0, selectedIndex - Math.floor(maxVisible / 2));\n let endIdx = Math.min(filtered.length, startIdx + maxVisible);\n if (endIdx - startIdx < maxVisible && startIdx > 0) {\n startIdx = Math.max(0, endIdx - maxVisible);\n }\n\n if (startIdx > 0) {\n console.log(` ... ${startIdx} more above ...`);\n }\n\n for (let i = startIdx; i < endIdx; i++) {\n const item = filtered[i]!;\n const prefix = i === selectedIndex ? '> ' : ' ';\n\n let line: string;\n if (item === NEW_ITEM_MARKER) {\n line = `\\x1B[32m${newLabel}\\x1B[0m`; // Green color for \"Create new\"\n } else {\n const typedItem = item as T;\n line = labelFn(typedItem);\n if (detailFn) {\n const detail = detailFn(typedItem);\n if (detail) {\n line = `${line} \\x1B[90m${detail}\\x1B[0m`;\n }\n }\n }\n\n if (i === selectedIndex) {\n console.log(`\\x1B[7m${prefix}${line}\\x1B[0m`);\n } else {\n console.log(`${prefix}${line}`);\n }\n }\n\n if (endIdx < filtered.length) {\n console.log(` ... ${filtered.length - endIdx} more below ...`);\n }\n\n console.log('');\n console.log(` ${filtered.length} item(s)`);\n };\n\n // Set up raw mode for arrow key input\n readline.emitKeypressEvents(process.stdin);\n if (process.stdin.isTTY) {\n process.stdin.setRawMode(true);\n }\n\n render();\n\n const handleKeypress = (str: string | undefined, key: readline.Key): void => {\n const filtered = getFilteredItems();\n\n if (key.name === 'up') {\n selectedIndex = Math.max(0, selectedIndex - 1);\n render();\n } else if (key.name === 'down') {\n selectedIndex = Math.min(filtered.length - 1, selectedIndex + 1);\n render();\n } else if (key.name === 'return') {\n cleanup();\n if (filtered.length > 0 && selectedIndex < filtered.length) {\n const selected = filtered[selectedIndex]!;\n if (selected === NEW_ITEM_MARKER) {\n resolve({ item: null, isNew: true });\n } else {\n resolve({ item: selected as T, isNew: false });\n }\n } else {\n resolve({ item: null, isNew: false });\n }\n } else if (key.name === 'escape' || (key.ctrl && key.name === 'c')) {\n cleanup();\n resolve({ item: null, isNew: false });\n } else if (key.name === 'backspace') {\n filterText = filterText.slice(0, -1);\n selectedIndex = allowNew ? 0 : 0;\n render();\n } else if (str && str.length === 1 && !key.ctrl && !key.meta) {\n filterText += str;\n selectedIndex = allowNew ? 0 : 0;\n render();\n }\n };\n\n const cleanup = (): void => {\n process.stdin.removeListener('keypress', handleKeypress);\n if (process.stdin.isTTY) {\n process.stdin.setRawMode(false);\n }\n process.stdin.pause();\n process.stdout.write('\\x1B[2J\\x1B[H');\n };\n\n process.stdin.on('keypress', handleKeypress);\n process.stdin.resume();\n });\n}\n\n/**\n * Print a table of items\n */\nexport function printTable<T>(\n items: T[],\n columns: Array<{\n header: string;\n getValue: (item: T) => string;\n maxWidth?: number;\n }>,\n options: { title?: string; env?: string } = {}\n): void {\n if (!items || items.length === 0) {\n console.log('\\nNo items found.');\n return;\n }\n\n if (options.title) {\n console.log(`\\n=== ${options.title} ===`);\n }\n if (options.env) {\n console.log(`Environment: ${options.env}`);\n }\n console.log('');\n\n // Calculate column widths\n const widths = columns.map((col) => {\n const maxContent = Math.max(...items.map((item) => String(col.getValue(item) ?? '').length));\n const width = Math.max(col.header.length, maxContent);\n return col.maxWidth ? Math.min(width, col.maxWidth) : width;\n });\n\n // Print header\n const headerLine = columns.map((col, i) => col.header.padEnd(widths[i]!)).join(' ');\n console.log(headerLine);\n console.log(widths.map((w) => '-'.repeat(w)).join(' '));\n\n // Print rows\n for (const item of items) {\n const row = columns\n .map((col, i) => {\n const value = String(col.getValue(item) ?? '');\n const width = widths[i]!;\n return value.slice(0, width).padEnd(width);\n })\n .join(' ');\n console.log(row);\n }\n\n console.log('');\n console.log(`Total: ${items.length} item(s)`);\n}\n\n/**\n * Format a timestamp for display\n */\nexport function formatTimestamp(isoString: string | null | undefined): string {\n if (!isoString) return '';\n const date = new Date(isoString);\n const now = new Date();\n const diff = now.getTime() - date.getTime();\n\n if (diff < 60000) return 'just now';\n if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;\n if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;\n if (diff < 604800000) return `${Math.floor(diff / 86400000)}d ago`;\n\n return date.toLocaleDateString();\n}\n\n/**\n * Wrap text to a maximum width\n */\nexport function wrapText(text: string, width: number = 70): string[] {\n const words = text.split(' ');\n const lines: string[] = [];\n let currentLine = '';\n\n for (const word of words) {\n if (currentLine.length + word.length + 1 <= width) {\n currentLine += (currentLine ? ' ' : '') + word;\n } else {\n if (currentLine) lines.push(currentLine);\n currentLine = word;\n }\n }\n if (currentLine) lines.push(currentLine);\n return lines;\n}\n\n/**\n * Print a chat message with formatting\n */\nexport function printMessage(\n content: string,\n role: 'user' | 'assistant' | 'system',\n indent: string = ' '\n): void {\n const roleColors: Record<string, string> = {\n user: '\\x1B[34m', // Blue\n assistant: '\\x1B[32m', // Green\n system: '\\x1B[90m', // Gray\n };\n const resetColor = '\\x1B[0m';\n const color = roleColors[role] || resetColor;\n\n const label = role === 'user' ? 'You' : role === 'assistant' ? 'Assistant' : 'System';\n console.log(`${indent}${color}[${label}]${resetColor}`);\n\n const lines = content.split('\\n');\n for (const line of lines) {\n const wrapped = wrapText(line, 70);\n for (const wrappedLine of wrapped) {\n console.log(`${indent} ${wrappedLine}`);\n }\n }\n console.log('');\n}\n\n/**\n * Clear the terminal screen\n */\nexport function clearScreen(): void {\n process.stdout.write('\\x1B[2J\\x1B[H');\n}\n","/**\n * AG-UI Client for CLI chat interactions\n *\n * Implements the AG-UI (Agent-User Interaction) protocol for streaming\n * chat responses. See: https://docs.ag-ui.com/concepts/events\n */\n\nimport {\n isProposedMessageSettlementStatus,\n type ProposedMessageSettlementStatus,\n} from '@gravity-rail/sdk';\nimport { apiAuthHeaders, apiFetch } from '../lib/api-transport';\n\nimport type { ConciergeAppContextPayload } from '../lib/cli-client-context';\n\n/** How asking the server to send or discard a drafted message ended. */\nexport type ProposedMessageSettleResult =\n | { kind: 'settled'; status: ProposedMessageSettlementStatus; detail?: string | null }\n | { kind: 'refused'; status: number }\n | { kind: 'transport' };\n\n/**\n * AG-UI event types\n */\nexport type AGUIEventType =\n | 'RUN_STARTED'\n | 'RUN_FINISHED'\n | 'RUN_ERROR'\n | 'TEXT_MESSAGE_START'\n | 'TEXT_MESSAGE_CONTENT'\n | 'TEXT_MESSAGE_END'\n | 'TOOL_CALL_START'\n | 'TOOL_CALL_ARGS'\n | 'TOOL_CALL_END'\n | 'TOOL_CALL_RESULT'\n | 'STATE_SNAPSHOT'\n | 'STATE_DELTA'\n // Lowercase variants (some backends use these)\n | 'run_started'\n | 'run_finished'\n | 'run_error'\n | 'text_message_start'\n | 'text_message_content'\n | 'text_message_end'\n | 'tool_call_start'\n | 'tool_call_args'\n | 'tool_call_end'\n | 'tool_call_result'\n | 'state_snapshot'\n | 'state_delta'\n | 'done';\n\nexport interface AGUIEvent {\n type: AGUIEventType;\n messageId?: string;\n role?: string;\n delta?: string;\n content?: string;\n message?: string;\n code?: string;\n toolCallId?: string;\n toolCallName?: string;\n result?: any;\n snapshot?: any;\n operations?: any[];\n [key: string]: any;\n}\n\nexport interface ChatMessage {\n role: 'user' | 'assistant' | 'system';\n content: string;\n}\n\nexport interface AGUIClientOptions {\n baseUrl: string;\n workspaceUuid?: string;\n chatId?: number | string; // Numeric chat id (documented) or chat uuid (accepted)\n /** Full URL override — when provided, baseUrl/workspaceUuid/chatId are ignored for POST */\n endpointUrl?: string;\n accessToken: string;\n debug?: boolean;\n /** Model field sent in request body (default: 'manager'). Set to undefined to omit. */\n model?: string;\n /** Concierge / client context forwarded to the API (e.g. CLI surface hints). */\n appContext?: ConciergeAppContextPayload;\n}\n\n/**\n * AG-UI Client for streaming chat responses\n */\nexport class AGUIClient {\n private endpointUrl: string;\n private baseUrl: string;\n private workspaceUuid: string;\n private chatId: number | string;\n private accessToken: string;\n private debug: boolean;\n private model: string | undefined;\n private appContext: ConciergeAppContextPayload | undefined;\n\n constructor(options: AGUIClientOptions) {\n this.baseUrl = options.baseUrl;\n this.workspaceUuid = options.workspaceUuid ?? '';\n this.chatId = options.chatId ?? 0;\n if (!options.endpointUrl && (!options.workspaceUuid || options.chatId === undefined)) {\n throw new Error('AGUIClient requires workspaceUuid and chatId, or endpointUrl');\n }\n this.endpointUrl =\n options.endpointUrl ??\n `${options.baseUrl}/api/v2/w/${options.workspaceUuid}/web-chat/${options.chatId}/chat/agui`;\n this.accessToken = options.accessToken;\n this.debug = options.debug ?? false;\n this.model = 'model' in options ? options.model : 'manager';\n this.appContext = options.appContext;\n }\n\n private chatRouteUrl(suffix: string): string | null {\n // Numeric chatId: treat 0 / negative as \"no chat\" (<= 0 rather than a\n // falsy check so a deliberate sentinel of 0 doesn't mean \"valid chat\").\n // String chatId is a uuid; empty string means \"no chat\".\n const noChat = typeof this.chatId === 'number' ? this.chatId <= 0 : this.chatId.length === 0;\n if (!this.workspaceUuid || noChat) return null;\n return `${this.baseUrl}/api/v2/w/${this.workspaceUuid}/chats/${this.chatId}/${suffix}`;\n }\n\n /**\n * The operator's own live inline-connect link for this chat, or null when\n * none is live. The `inline_connect` prompt carries no URL on purpose (it is\n * a bearer, and the tool result is persisted and model-visible), so the\n * terminal fetches it here when the operator chooses to connect.\n */\n async fetchInlineConnectLink(\n appSlug: string\n ): Promise<{ connectUrl: string; expiresInMinutes: number } | null> {\n const url = this.chatRouteUrl(`inline-connect/${encodeURIComponent(appSlug)}/link`);\n if (!url) return null;\n try {\n const res = await apiFetch(url, { headers: apiAuthHeaders(this.accessToken) });\n if (!res.ok) return null;\n const body = (await res.json()) as { connectUrl?: unknown; expiresInMinutes?: unknown };\n if (typeof body.connectUrl !== 'string') return null;\n return {\n connectUrl: body.connectUrl,\n expiresInMinutes: typeof body.expiresInMinutes === 'number' ? body.expiresInMinutes : 0,\n };\n } catch {\n return null;\n }\n }\n\n /**\n * Send or discard a message the Manager proposed as a draft. The three\n * results are different things to tell the operator: `settled` carries how\n * it ended, `refused` is the server saying no (a 409 is a draft settled\n * elsewhere), and `transport` is not knowing — the draft is unchanged as\n * far as this client can tell.\n */\n async settleProposedMessage(\n promptId: string,\n decision: 'send' | 'discard'\n ): Promise<ProposedMessageSettleResult> {\n const url = this.chatRouteUrl(`proposed-messages/${encodeURIComponent(promptId)}/decision`);\n if (!url) return { kind: 'transport' };\n try {\n const res = await apiFetch(url, {\n method: 'POST',\n headers: {\n ...apiAuthHeaders(this.accessToken),\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ decision }),\n });\n if (!res.ok) return { kind: 'refused', status: res.status };\n const body = (await res.json()) as { status?: unknown; detail?: unknown };\n if (!isProposedMessageSettlementStatus(body.status)) return { kind: 'transport' };\n return {\n kind: 'settled',\n status: body.status,\n detail: typeof body.detail === 'string' ? body.detail : null,\n };\n } catch {\n return { kind: 'transport' };\n }\n }\n\n private inferenceStatusUrl(): string | null {\n // Numeric chatId: treat 0 / negative as \"no chat\" (<= 0 rather than a\n // falsy check so a deliberate sentinel of 0 doesn't mean \"valid chat\").\n // String chatId is a uuid; empty string means \"no chat\".\n const noChat = typeof this.chatId === 'number' ? this.chatId <= 0 : this.chatId.length === 0;\n if (!this.workspaceUuid || noChat) return null;\n return `${this.baseUrl}/api/v2/w/${this.workspaceUuid}/chats/${this.chatId}/inference/status`;\n }\n\n private async waitForInferenceInactive(maxWaitMs = 60_000): Promise<boolean> {\n const url = this.inferenceStatusUrl();\n if (!url) return false;\n const deadline = Date.now() + maxWaitMs;\n while (Date.now() < deadline) {\n try {\n const res = await apiFetch(url, {\n headers: apiAuthHeaders(this.accessToken),\n });\n if (res.ok) {\n const body = (await res.json()) as { active?: boolean };\n if (!body.active) return true;\n }\n } catch (err) {\n // Transient network errors (DNS blips, connection resets) shouldn't\n // crash the 409-retry loop. Log under --debug and keep polling\n // until the deadline; the caller will fall back to the original\n // 409 error if we can't confirm inactive in time.\n if (this.debug) {\n console.log(\n `[DEBUG] waitForInferenceInactive fetch failed: ${\n err instanceof Error ? err.message : String(err)\n }`\n );\n }\n }\n await new Promise((r) => setTimeout(r, 2000));\n }\n return false;\n }\n\n /**\n * Send messages and stream the response\n */\n async sendMessage(\n messages: ChatMessage[],\n onEvent: (event: AGUIEvent) => void,\n options?: AguiStreamOptions\n ): Promise<void> {\n return this.streamRequest({ messages }, onEvent, options);\n }\n\n /**\n * Stream an AG-UI request (initial messages or HITL resume).\n */\n async streamRequest(\n request: AguiRequestBody,\n onEvent: (event: AGUIEvent) => void,\n options?: AguiStreamOptions\n ): Promise<void> {\n const body = JSON.stringify({\n ...(this.model ? { model: this.model } : {}),\n messages: request.messages ?? [],\n ...(this.appContext ? { appContext: this.appContext } : {}),\n ...(request.resumeValue !== undefined ? { resumeValue: request.resumeValue } : {}),\n ...(request.resumeInterruptId ? { resumeInterruptId: request.resumeInterruptId } : {}),\n ...(request.resume !== undefined ? { resume: request.resume } : {}),\n ...(options?.autoApprove ? { context: { autoApprove: true } } : {}),\n });\n\n if (this.debug) {\n console.log(`\\n[DEBUG] POST ${this.endpointUrl}`);\n console.log(\n `[DEBUG] Body: ${request.resumeValue !== undefined ? 'resume' : `${(request.messages ?? []).length} message(s)`}`\n );\n }\n\n await this.postStream(body, onEvent, options);\n }\n\n private async postStream(\n body: string,\n onEvent: (event: AGUIEvent) => void,\n options?: AguiStreamOptions,\n conflictRetries = 0\n ): Promise<void> {\n const response = await apiFetch(this.endpointUrl, {\n method: 'POST',\n headers: {\n ...apiAuthHeaders(this.accessToken),\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream',\n },\n body,\n });\n\n if (this.debug) {\n console.log(`[DEBUG] Response status: ${response.status}`);\n }\n\n if (response.status === 409 && conflictRetries < 3) {\n const ready = await this.waitForInferenceInactive();\n if (ready) {\n await this.postStream(body, onEvent, options, conflictRetries + 1);\n return;\n }\n }\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => '');\n if (this.debug) {\n console.log(`[DEBUG] Error response: ${errorText}`);\n }\n throw new Error(\n `Chat request failed: ${response.status}${errorText ? `: ${errorText.slice(0, 200)}` : ''}`\n );\n }\n\n await parseSseStream(response.body!, onEvent);\n }\n\n /**\n * Subscribe to the chat's persistent AG-UI event feed and surface\n * server-initiated turns that arrive while we're idle between our own turns.\n *\n * The feed at ``/chats/{chatId}/events`` replays every AG-UI event for the\n * chat across all turns (assistant events plus user-message echoes). It never\n * self-terminates — it ends only on disconnect. On reconnect we send\n * ``Last-Event-ID`` so the server replays the gap. The loop reconnects with\n * capped exponential backoff and resolves quietly once ``signal`` aborts;\n * it never throws except when required args are missing (callers gate on\n * availability, so that path is a programming error).\n */\n async subscribeToFeed(opts: {\n onEvent: (event: AGUIEvent) => void;\n signal: AbortSignal;\n onDebug?: (msg: string) => void;\n }): Promise<void> {\n const { onEvent, signal, onDebug } = opts;\n\n // Guard even though callers gate on availability: the feed URL needs a\n // real workspace + chat. Mirror inferenceStatusUrl's \"no chat\" logic.\n const noChat = typeof this.chatId === 'number' ? this.chatId <= 0 : this.chatId.length === 0;\n if (!this.baseUrl || !this.workspaceUuid || noChat) {\n throw new Error('subscribeToFeed requires baseUrl, workspaceUuid, and a chatId');\n }\n const feedUrl = `${this.baseUrl}/api/v2/w/${this.workspaceUuid}/chats/${this.chatId}/events`;\n\n let lastEventId: string | undefined;\n let backoffMs = 1000;\n const maxBackoffMs = 15_000;\n // A connection that survived this long was healthy even if the chat\n // stayed silent the whole time — keepalive comment frames are\n // stripped by the parser, so they can never count as received data.\n const healthyConnectionMs = 30_000;\n\n while (!signal.aborted) {\n let receivedData = false;\n const connectedAt = Date.now();\n try {\n const headers: Record<string, string> = {\n ...apiAuthHeaders(this.accessToken),\n Accept: 'text/event-stream',\n };\n if (lastEventId !== undefined) headers['Last-Event-ID'] = lastEventId;\n\n const response = await apiFetch(feedUrl, { method: 'GET', headers, signal });\n if (!response.ok || !response.body) {\n throw new Error(`feed request failed: ${response.status}`);\n }\n onDebug?.(`feed connected${lastEventId ? ` (resume ${lastEventId})` : ''}`);\n\n await parseSseStream(\n response.body,\n (event, eventName) => {\n receivedData = true;\n // Retention lapsed — the server couldn't replay the gap.\n // Detected via the SSE ``event: feed_reset`` name (the\n // payload type is a belt-and-suspenders duplicate). For\n // v1 we just note it; some events may have been missed.\n if (\n eventName === 'feed_reset' ||\n (typeof event.type === 'string' && event.type.toUpperCase() === 'FEED_RESET')\n ) {\n onDebug?.('feed reset — server could not replay missed events');\n return;\n }\n onEvent(event);\n },\n (id) => {\n receivedData = true;\n lastEventId = id;\n }\n );\n // Stream ended (disconnect) — fall through to reconnect with backoff.\n } catch (err) {\n if (signal.aborted) return;\n onDebug?.(`feed error: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n if (signal.aborted) return;\n\n // Reset only on evidence of health (delivered frames, or a\n // long-lived idle connection); otherwise wait out the current\n // backoff and grow it for the NEXT attempt (1s, 2s, 4s … cap).\n // Healthy connections must never escalate — an earlier version\n // doubled unconditionally after the reset, so steady\n // reconnects crept toward the cap.\n const wasHealthy = receivedData || Date.now() - connectedAt >= healthyConnectionMs;\n if (wasHealthy) backoffMs = 1000;\n const completed = await abortableDelay(backoffMs, signal);\n if (!completed) return; // aborted while waiting\n if (!wasHealthy) backoffMs = Math.min(backoffMs * 2, maxBackoffMs);\n }\n }\n}\n\n/**\n * Parse a Server-Sent Events stream body into AG-UI events.\n *\n * Shared by ``AGUIClient.postStream`` (per-turn POST) and ``subscribeToFeed``\n * (persistent GET feed). Surfaces ``data:`` frames as parsed events, ``id:``\n * frames via ``onId`` (feed reconnect uses the last id as ``Last-Event-ID``),\n * and ignores SSE comment frames (``: turn-done``, keepalives). ``onId`` is\n * optional — the POST path has no use for entry ids.\n */\nexport async function parseSseStream(\n body: ReadableStream<Uint8Array>,\n onEvent: (event: AGUIEvent, eventName?: string) => void,\n onId?: (id: string) => void\n): Promise<void> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n // Per SSE, an ``event:`` line names the dispatch it precedes (the\n // server's feed_reset signal uses this). Cleared once consumed or at\n // the blank-line frame boundary.\n let pendingEventName: string | undefined;\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const rawLine of lines) {\n // Tolerate CRLF endings without changing the \\n-split behavior.\n const line = rawLine.endsWith('\\r') ? rawLine.slice(0, -1) : rawLine;\n\n // Blank line = SSE frame boundary; the pending event name only\n // applies within its own frame.\n if (line === '') {\n pendingEventName = undefined;\n continue;\n }\n\n // SSE comment frame (turn boundaries, keepalives) — ignore.\n if (line.startsWith(':')) continue;\n\n if (line.startsWith('event:')) {\n const nameValue = line.slice(6);\n pendingEventName = nameValue.startsWith(' ') ? nameValue.slice(1) : nameValue;\n continue;\n }\n\n if (line.startsWith('id:')) {\n const idValue = line.slice(3);\n // Per SSE, a single leading space after the colon is stripped.\n onId?.(idValue.startsWith(' ') ? idValue.slice(1) : idValue);\n continue;\n }\n\n if (line.startsWith('data: ')) {\n const data = line.slice(6);\n if (data === '[DONE]') {\n onEvent({ type: 'done' }, pendingEventName);\n pendingEventName = undefined;\n continue;\n }\n try {\n onEvent(JSON.parse(data) as AGUIEvent, pendingEventName);\n } catch {\n // Ignore parse errors for malformed events.\n }\n pendingEventName = undefined;\n }\n }\n }\n}\n\n/**\n * Resolve after ``ms`` unless ``signal`` aborts first. Returns true if the delay\n * completed, false if it was aborted — lets a reconnect loop exit cleanly.\n */\nfunction abortableDelay(ms: number, signal: AbortSignal): Promise<boolean> {\n return new Promise<boolean>((resolve) => {\n if (signal.aborted) {\n resolve(false);\n return;\n }\n const onAbort = (): void => {\n clearTimeout(timer);\n resolve(false);\n };\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve(true);\n }, ms);\n signal.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nexport interface AguiStreamOptions {\n autoApprove?: boolean;\n}\n\nexport interface AguiRequestBody {\n messages?: ChatMessage[];\n /** Concierge AGUI resume fields. */\n resumeValue?: string;\n resumeInterruptId?: string;\n /** Workspace-chat HITL resume (ChatCompletionRequest.resume shape:\n * { decisions: [{type: 'approve'|'edit'|'reject', ...}], interruptId }). */\n resume?: unknown;\n}\n\n/**\n * Helper to check if an event is a text content event\n */\nexport function isTextContentEvent(event: AGUIEvent): boolean {\n const type = event.type.toLowerCase();\n return type === 'text_message_content';\n}\n\n/**\n * Helper to check if an event is an error event\n */\nexport function isErrorEvent(event: AGUIEvent): boolean {\n const type = event.type.toLowerCase();\n return type === 'run_error';\n}\n\n/**\n * Helper to extract text delta from an event\n */\nexport function getTextDelta(event: AGUIEvent): string | null {\n if (isTextContentEvent(event) && event.delta) {\n return event.delta;\n }\n return null;\n}\n\n/**\n * Helper to extract error message from an event\n */\nexport function getErrorMessage(event: AGUIEvent): string | null {\n if (isErrorEvent(event)) {\n return event.message || event.code || 'Unknown error';\n }\n return null;\n}\n","import { GravityRailClient } from '@gravity-rail/sdk';\nimport {\n CredentialsManager,\n getEnvironmentConfig,\n resolveNonInteractiveAuth,\n type AuthResult,\n type EnvironmentConfig,\n} from '../cli-utils';\nimport { homedir } from 'os';\nimport { detectOutputFormat, type OutputFormat } from './output';\nimport { AuthRequiredError } from './errors';\nimport { registerOrgAuthHandler, type OrgAuthContext } from './org-auth';\nimport { createSandboxFetchFromEnv } from './sandbox-fetch';\n\n/** Build an authenticated API client with the CLI org-auth handler registered. */\nfunction makeApiClient(\n accessToken: string | undefined,\n apiUrl: string,\n fetchFn?: typeof fetch,\n orgAuthCtx?: OrgAuthContext\n): GravityRailClient {\n const resolvedFetch = fetchFn ?? createSandboxFetchFromEnv();\n const apiClient = new GravityRailClient(accessToken, apiUrl, resolvedFetch);\n registerOrgAuthHandler(apiClient, apiUrl, accessToken ?? '', orgAuthCtx);\n return apiClient;\n}\n\n/**\n * Org-auth context for a profile (login) command: enables the browser SSO\n * step-up and caches the captured session under the profile. API-key and\n * credential-broker contexts omit this — API keys are gate-exempt, and the\n * sandbox broker is non-interactive (no browser).\n */\nfunction interactiveOrgAuth(ctx: CommandContext): OrgAuthContext {\n return {\n credentialsManager: ctx.credentialsManager,\n env: ctx.env,\n profile: ctx.profile,\n frontendUrl: ctx.envConfig.frontendUrl,\n interactive: true,\n };\n}\n\n/**\n * Credential-broker context (code-interpreter sandbox): the scoped token is held\n * by the broker and absent from the env, so the CLI talks to the loopback broker\n * with NO auth header. Returns null when not in the sandbox (no broker URL) — the\n * standalone CLI then falls through to GRAVITY_RAIL_API_KEY / profile auth.\n */\n/**\n * The credential broker is ALWAYS a loopback listener inside the sandbox VM.\n * Requests sent to it carry no Authorization header (the broker adds it), so a\n * non-loopback value here would ship unauthenticated API traffic — including\n * request bodies — to an arbitrary host. uid-1000 code can set env vars, so\n * treat the URL as untrusted and accept only loopback. Anything else is ignored\n * (we fall through to normal auth) rather than trusted.\n */\nfunction isLoopbackBrokerUrl(rawUrl: string): boolean {\n try {\n const { hostname, protocol } = new URL(rawUrl);\n if (protocol !== 'http:' && protocol !== 'https:') return false;\n // URL() preserves brackets on IPv6 literals.\n const host = hostname.replace(/^\\[|\\]$/g, '');\n return host === '127.0.0.1' || host === '::1' || host === 'localhost';\n } catch {\n return false;\n }\n}\n\n/**\n * The sandbox's loopback broker URL, or null when not running in a sandbox.\n *\n * Single place the `GRAVITY_RAIL_BROKER_URL` loopback check lives, so every\n * caller — both authenticated commands and public commands —\n * applies the same validation.\n */\nexport function sandboxBrokerUrl(): string | null {\n const brokerUrl = process.env.GRAVITY_RAIL_BROKER_URL;\n if (!brokerUrl || !isLoopbackBrokerUrl(brokerUrl)) return null;\n return brokerUrl;\n}\n\nfunction tryBrokerContext(ctx: CommandContext): AuthenticatedContext | null {\n const brokerUrl = sandboxBrokerUrl();\n if (!brokerUrl) return null;\n const apiClient = makeApiClient(undefined, brokerUrl, createSandboxFetchFromEnv());\n return { ...ctx, accessToken: '', apiClient };\n}\n\nfunction contextWithToken(ctx: CommandContext, auth: AuthResult): AuthenticatedContext {\n const apiClient = makeApiClient(\n auth.accessToken,\n ctx.envConfig.apiUrl,\n undefined,\n auth.credentials ? interactiveOrgAuth(ctx) : undefined\n );\n return {\n ...ctx,\n accessToken: auth.accessToken,\n apiClient,\n profileWorkspace: auth.credentials?.workspaceUuid,\n };\n}\n\nexport interface GlobalOptions {\n env: string;\n /** Override API base URL (also: GRAVITY_RAIL_API_URL env var). */\n apiUrl?: string;\n outputFormat?: string;\n jq?: string;\n verbose?: boolean;\n allowWrite?: boolean;\n /** Named credential profile (`--profile` / GRAVITY_RAIL_PROFILE). */\n profile?: string;\n /** Directory to classify as a linked worktree. Defaults to `process.cwd()`. */\n startDir?: string;\n}\n\nexport interface PublicGlobalOptions {\n env?: string;\n apiUrl?: string;\n frontendUrl?: string;\n outputFormat?: string;\n jq?: string;\n verbose?: boolean;\n allowWrite?: boolean;\n /** Named credential profile (`--profile` / GRAVITY_RAIL_PROFILE). */\n profile?: string;\n /** Directory to classify as a linked worktree. Defaults to `process.cwd()`. */\n startDir?: string;\n}\n\nexport interface CommandContext {\n env: string;\n envConfig: EnvironmentConfig;\n outputFormat: OutputFormat;\n /** `--jq` filter, applied to JSON output. See `lib/jq.ts`. */\n jq?: string;\n verbose: boolean;\n allowWrite: boolean;\n credentialsManager: CredentialsManager;\n /** Resolved credential profile for this invocation. */\n profile: string;\n}\n\nexport interface AuthenticatedContext extends CommandContext {\n accessToken: string;\n apiClient: GravityRailClient;\n /** Default workspace UUID from the profile (dev workspace/member profiles). */\n profileWorkspace?: string;\n}\n\n/** Create a base command context (no auth required) */\nexport function createContext(opts: GlobalOptions): CommandContext {\n const envConfig = getEnvironmentConfig(opts.env, {\n apiUrl: opts.apiUrl,\n startDir: opts.startDir,\n });\n const credentialsManager = new CredentialsManager(homedir(), envConfig.apiUrl);\n const profile = credentialsManager.resolveProfileName(opts.profile, opts.env);\n return {\n env: opts.env,\n envConfig,\n outputFormat: detectOutputFormat(opts.outputFormat),\n jq: opts.jq,\n verbose: opts.verbose ?? false,\n allowWrite: opts.allowWrite ?? false,\n credentialsManager,\n profile,\n };\n}\n\n/**\n * Create an authenticated command context.\n * Order: GRAVITY_RAIL_API_KEY → named/current profile store. Never auto-triggers OAuth.\n *\n * Dev accounts that used to be selected with `--realm` are now named profiles\n * (import with `gr auth import-dev` after provisioning).\n */\nexport async function createAuthenticatedContext(\n opts: GlobalOptions\n): Promise<AuthenticatedContext> {\n // oxlint-disable-next-line @eslint-react/naming-convention-context-name -- CLI handler context, not React\n const ctx = createContext(opts);\n\n // Credential-broker mode takes precedence: token lives in the root daemon,\n // not the env, so route through the loopback broker with no auth header.\n const brokerCtx = tryBrokerContext(ctx);\n if (brokerCtx) return brokerCtx;\n\n const auth = await resolveNonInteractiveAuth({\n env: ctx.env,\n envConfig: ctx.envConfig,\n credentialsManager: ctx.credentialsManager,\n profile: ctx.profile,\n });\n if (auth) return contextWithToken(ctx, auth);\n\n if (ctx.profile !== 'default') {\n throw new AuthRequiredError(\n `No credentials for profile \"${ctx.profile}\" (${ctx.env}). ` +\n `Run: gr auth login --name ${ctx.profile} or gr auth import-dev`\n );\n }\n throw new AuthRequiredError(\n 'Not authenticated. Run `gr login`, `gr auth import-dev` (local dev), or set GRAVITY_RAIL_API_KEY.'\n );\n}\n\n/**\n * Narrow a handler context to `AuthenticatedContext`.\n *\n * Handler `ctx` is typed as `AuthenticatedContext | CommandContext` so that\n * `requiresAuth: false` handlers can also share the type. At runtime, every\n * handler that did not opt out of auth will receive an `AuthenticatedContext`,\n * but TypeScript cannot verify this — call this helper before accessing\n * `apiClient` / `accessToken`.\n *\n * Throws if called from a handler that did not declare `requiresAuth`.\n */\nexport function requireAuth(ctx: AuthenticatedContext | CommandContext): AuthenticatedContext {\n if (!('apiClient' in ctx)) {\n throw new Error('Command handler accessed apiClient without declaring requiresAuth');\n }\n return ctx;\n}\n\n/** Create a base command context for the public CLI (defaults to prod) */\nexport function createPublicContext(opts: PublicGlobalOptions): CommandContext {\n // INVARIANT — the public `gr` CLI defaults to PROD. Public API consumers have NO access to\n // our dev/staging environments; prod is the only API they can reach, so an unset env MUST\n // resolve to prod. Do NOT change this to 'dev'/'staging' for internal convenience or to\n // satisfy a ticket claiming the prod default is a bug (see #15819 — the bug was the --help\n // text, not this default). Internal devs select a non-prod env with an explicit `--env`.\n const env = opts.env ?? 'prod';\n const envConfig = getEnvironmentConfig(env, {\n apiUrl: opts.apiUrl,\n frontendUrl: opts.frontendUrl,\n startDir: opts.startDir,\n });\n const credentialsManager = new CredentialsManager(homedir(), envConfig.apiUrl);\n const profile = credentialsManager.resolveProfileName(opts.profile, env);\n return {\n env,\n envConfig,\n outputFormat: detectOutputFormat(opts.outputFormat),\n jq: opts.jq,\n verbose: opts.verbose ?? false,\n allowWrite: opts.allowWrite ?? false,\n credentialsManager,\n profile,\n };\n}\n\n/** Create an authenticated context for the public CLI. Tries env var, then cached token. */\nexport async function createPublicAuthenticatedContext(\n opts: PublicGlobalOptions\n): Promise<AuthenticatedContext> {\n const ctx = createPublicContext(opts);\n\n // Credential-broker mode takes precedence: the scoped token lives in the root\n // daemon, not the env, so route through the loopback broker with no auth header.\n // `gr.ts` (the `gr` entry point) uses THIS function, so the code-interpreter\n // sandbox reaches the API through here — without this check the sandbox CLI\n // throws AuthRequiredError because the broker deliberately strips\n // GRAVITY_RAIL_API_KEY from `.gr-env`. Returns null outside the sandbox, so\n // standalone/public CLI behavior is unchanged.\n const brokerCtx = tryBrokerContext(ctx);\n if (brokerCtx) return brokerCtx;\n\n const auth = await resolveNonInteractiveAuth({\n env: ctx.env,\n envConfig: ctx.envConfig,\n credentialsManager: ctx.credentialsManager,\n profile: ctx.profile,\n });\n if (auth) return contextWithToken(ctx, auth);\n\n throw new AuthRequiredError();\n}\n","import { spawnSync } from 'node:child_process';\nimport { CLIError } from './errors';\n\n/**\n * Apply a jq filter to CLI output, in-process.\n *\n * Why this exists rather than telling callers to pipe: `gr … -o json | jq …`\n * puts the burden of building a valid pipeline on the caller, and that is where\n * it breaks. A forensic pass over 90 days of Workspace Manager chats found\n * `jq: parse error` in 49 of 392 chats (PR #22929) — the second most common\n * failure signature in the whole corpus. The agent pipes a table-formatted\n * listing into jq, or pipes a command that errored and emitted nothing, and jq\n * chokes on input the agent never inspected.\n *\n * `--jq` removes the failure mode rather than documenting around it: the filter\n * runs against the JSON *we* just serialised, so the input is valid by\n * construction and `-o json` is implied. A bad filter now produces one clear\n * error about the filter, instead of a parse error about bytes the caller\n * cannot see.\n *\n * We shell out to the system `jq` deliberately. A pure-JS reimplementation\n * would be a new dependency and a second dialect to keep in sync with the one\n * people already know; the sandbox and every developer machine has `jq` on\n * PATH. When it is genuinely missing we say so and name the fallback, rather\n * than silently emitting unfiltered JSON that a script would then misread.\n */\nexport function applyJqFilter(json: string, filter: string): string {\n // No try/catch: spawnSync reports a missing or unspawnable binary through\n // `result.error`, it does not throw for those cases. A catch here would be\n // unreachable for exactly the failures it claimed to handle.\n const result = spawnSync('jq', ['-r', filter], {\n input: json,\n encoding: 'utf8',\n maxBuffer: 64 * 1024 * 1024,\n });\n\n if (result.error && (result.error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new CLIError(\n '--jq requires the `jq` binary on PATH, and it was not found. ' +\n 'Install jq, or omit --jq and filter the JSON yourself.'\n );\n }\n // A filter jq cannot COMPILE makes it print the syntax error and exit\n // without ever reading stdin, so our write lands on a closed pipe and\n // spawnSync reports EPIPE in `error` *alongside* jq's real exit status. It is\n // a race at any input size — whether the write or jq's exit gets there first\n // — which is why checking `error` before `status` replaced jq's diagnostic\n // with a pipe error only intermittently, and read as an unrelated flake.\n // EPIPE together with an exit status is therefore not a spawn failure; every\n // other `error` (ENOENT above, ENOBUFS from maxBuffer, a failed fork) is.\n const wroteToExitedJq =\n (result.error as NodeJS.ErrnoException | undefined)?.code === 'EPIPE' &&\n result.status !== null;\n if (result.error && !wroteToExitedJq) {\n throw new CLIError(`--jq could not run jq: ${result.error.message}`);\n }\n if (result.status !== 0) {\n // jq's own diagnostic is the useful part — it names the position in the\n // filter. Prefixing it keeps the caller from reading it as a gr error.\n const exited = result.signal\n ? `jq was killed by ${result.signal}`\n : `jq exited ${result.status}`;\n const detail = (result.stderr || '').trim() || exited;\n throw new CLIError(`--jq filter failed: ${detail}`);\n }\n\n return (result.stdout || '').replace(/\\n$/, '');\n}\n","import { sandboxBrokerUrl } from './context';\n\nexport class CLIError extends Error {\n constructor(\n message: string,\n public exitCode: number = 1\n ) {\n super(message);\n this.name = 'CLIError';\n }\n}\n\nexport class AuthRequiredError extends CLIError {\n constructor(message = 'Not authenticated. Run `gr login` or set GRAVITY_RAIL_API_KEY.') {\n super(message, 2);\n this.name = 'AuthRequiredError';\n }\n}\n\n/**\n * What a 401 tells the caller to do.\n *\n * - `login`: the CLI holds no usable credential of its own; log in or set a key.\n * - `session_credential`: a code-interpreter sandbox, where the credential\n * broker holds the session's token. Logging in or setting a key cannot change\n * what that token allows, so the hint must not suggest it (an agent that read\n * \"run gr login\" went looking for another `gr` to run instead).\n */\nexport type UnauthorizedHint = 'login' | 'session_credential';\n\nexport function unauthorizedHint(): UnauthorizedHint {\n return sandboxBrokerUrl() ? 'session_credential' : 'login';\n}\n\nconst UNAUTHORIZED_HINT_TEXT: Record<UnauthorizedHint, string> = {\n login: 'Run \"gr login\" to authenticate, or set GRAVITY_RAIL_API_KEY for non-interactive use.',\n session_credential:\n \"This session's credential does not allow this request. Logging in or setting an API key does not change that. Organization commands are outside a workspace session.\",\n};\n\nexport function handleError(err: unknown): never {\n if (err instanceof CLIError) {\n process.stderr.write(`Error: ${err.message}\\n`);\n process.exit(err.exitCode);\n }\n\n if (err instanceof Error) {\n process.stderr.write(`Error: ${err.message}\\n`);\n if ('errors' in err && Array.isArray((err as any).errors)) {\n for (const e of (err as any).errors) {\n process.stderr.write(` - ${e}\\n`);\n }\n }\n if ('statusCode' in err && (err as any).statusCode === 401) {\n // The server's reason was written above; the hint only says what to do next.\n process.stderr.write(`\\nHint: ${UNAUTHORIZED_HINT_TEXT[unauthorizedHint()]}\\n`);\n }\n process.exit(1);\n }\n\n process.stderr.write(`Error: ${String(err)}\\n`);\n process.exit(1);\n}\n","import type { ArgDef, ParsedArgs } from './types';\nimport { CLIError } from './errors';\n\n// ── Response shape detection ─────────────────────────────────────────\n\n/** Metadata extracted from a paginated API response */\nexport interface PaginationMeta {\n /** Total number of items across all pages (page-based only) */\n total?: number;\n /** Current page number (page-based only) */\n page?: number;\n /** Total pages (page-based only) */\n totalPages?: number;\n /** Whether more pages exist (cursor-based only) */\n hasMore?: boolean;\n /** Cursor for next page (cursor-based only) */\n nextCursor?: string;\n}\n\n/** Explicit pagination contract passed from commands to outputData */\nexport interface ListResult {\n items: unknown[];\n meta?: PaginationMeta;\n supportsAll?: boolean;\n}\n\n/** Type guard: is the value a ListResult (explicit contract)? */\nexport function isListResult(data: unknown): data is ListResult {\n if (!data || typeof data !== 'object' || Array.isArray(data)) return false;\n const obj = data as Record<string, unknown>;\n return (\n Array.isArray(obj.items) &&\n ('supportsAll' in obj ||\n ('meta' in obj && (obj.meta === undefined || typeof obj.meta === 'object')))\n );\n}\n\n/** Check if a response looks like a page-based paginated envelope.\n * Matches both `{ items, total, totalPages, page }` (standard) and\n * `{ items, total, page, pageSize }` (legacy — e.g. InvitationListResponse,\n * InquiryListResponse). This is a pure type guard with no side effects;\n * totalPages computation for legacy shapes happens in extractPaginationMeta. */\nexport function isPagePaginatedResponse(data: unknown): data is {\n items: unknown[];\n total: number;\n page: number;\n totalPages?: number;\n pageSize?: number;\n} {\n if (!data || typeof data !== 'object') return false;\n const obj = data as Record<string, unknown>;\n if (!Array.isArray(obj.items) || typeof obj.page !== 'number') return false;\n\n // Standard shape: has totalPages\n if (typeof obj.totalPages === 'number') return true;\n\n // Legacy shape: has total + pageSize but no totalPages\n if (typeof obj.total === 'number' && typeof obj.pageSize === 'number') return true;\n\n return false;\n}\n\n/** Check if a response looks like a cursor-based paginated envelope */\nexport function isCursorPaginatedResponse(data: unknown): data is {\n items: unknown[];\n hasMore: boolean;\n nextCursor?: string;\n} {\n if (!data || typeof data !== 'object') return false;\n const obj = data as Record<string, unknown>;\n return Array.isArray(obj.items) && typeof obj.hasMore === 'boolean';\n}\n\n/** Check if a response is any paginated envelope ({ items: [...], ... }) */\nexport function isPaginatedResponse(data: unknown): boolean {\n return isPagePaginatedResponse(data) || isCursorPaginatedResponse(data);\n}\n\n/** Extract pagination metadata from a response, or return undefined for non-paginated responses.\n * For legacy shapes without totalPages, computes it from total/pageSize. */\nexport function extractPaginationMeta(data: unknown): PaginationMeta | undefined {\n if (isPagePaginatedResponse(data)) {\n const totalPages =\n data.totalPages ?? (data.pageSize ? Math.ceil(data.total / data.pageSize) : undefined);\n return {\n total: data.total,\n page: data.page,\n totalPages,\n };\n }\n if (isCursorPaginatedResponse(data)) {\n return {\n hasMore: data.hasMore,\n nextCursor: data.nextCursor,\n };\n }\n return undefined;\n}\n\n// ── Warning formatting ───────────────────────────────────────────────\n\n/** Format a pagination warning for stderr. Returns undefined if no warning needed.\n * When `supportsAll` is false, the \"Use --all\" hint is omitted because the\n * command does not actually expose the --all flag. */\nexport function formatPaginationWarning(\n meta: PaginationMeta | undefined,\n supportsAll: boolean = true\n): string | undefined {\n if (!meta) return undefined;\n\n const allHint = supportsAll ? ' Use --all to fetch all pages.' : '';\n\n // Page-based: warn when there are multiple pages\n if (meta.totalPages !== undefined && meta.totalPages > 1) {\n const pageNum = meta.page ?? 1;\n return `Showing page ${pageNum} of ${meta.totalPages} (${meta.total} total items).${allHint}`;\n }\n\n // Cursor-based: warn when more pages exist\n if (meta.hasMore === true) {\n return `More results available.${allHint}`;\n }\n\n return undefined;\n}\n\n// ── Unwrapping ───────────────────────────────────────────────────────\n\n/** Unwrap items from a paginated response or return the data as-is if it's an array */\nexport function unwrapItems(data: unknown): unknown[] {\n if (Array.isArray(data)) return data;\n if (\n data &&\n typeof data === 'object' &&\n 'items' in data &&\n Array.isArray((data as Record<string, unknown>).items)\n ) {\n return (data as Record<string, unknown>).items as unknown[];\n }\n return [data];\n}\n\n// ── Arg definitions ──────────────────────────────────────────────────\n\n/** Default pagination args for list commands (page, page-size, all). No search. */\nexport const LIST_PAGINATION_ARGS: ArgDef[] = [\n { name: 'page', description: 'Page number' },\n { name: 'page-size', description: 'Page size' },\n { name: 'all', description: 'Fetch all pages and return combined results', isFlag: true },\n];\n\n// ── Arg-to-options helpers ───────────────────────────────────────────\n\n/** Convert parsed CLI args to API pagination options */\nexport function parsePaginationArgs(args: ParsedArgs): {\n page?: number;\n pageSize?: number;\n all?: boolean;\n} {\n const result: { page?: number; pageSize?: number; all?: boolean } = {};\n\n if (args.all === true) {\n result.all = true;\n }\n\n if (args.page !== undefined) {\n const num = Number(args.page);\n if (isNaN(num) || num < 1) throw new CLIError('--page must be a positive integer');\n result.page = num;\n }\n\n if (args['page-size'] !== undefined) {\n const num = Number(args['page-size']);\n if (isNaN(num) || num < 1) throw new CLIError('--page-size must be a positive integer');\n if (num > 100) throw new CLIError('--page-size must be at most 100 (API limit)');\n result.pageSize = num;\n }\n\n return result;\n}\n\n// ── fetchAll helpers ─────────────────────────────────────────────────\n\nconst MAX_PAGE_SIZE = 100;\nconst MAX_PAGES = 200; // Safety limit to prevent infinite loops\n\n/**\n * Fetch all pages from a page-based paginated endpoint.\n * The fetcher receives { page, pageSize } and should return the raw API response.\n * Throws CLIError if MAX_PAGES is reached without exhausting all pages.\n */\nexport async function fetchAllPages(\n fetcher: (opts: { page: number; pageSize: number }) => Promise<unknown>\n): Promise<unknown[]> {\n const allItems: unknown[] = [];\n let page = 1;\n\n while (page <= MAX_PAGES) {\n const result = await fetcher({ page, pageSize: MAX_PAGE_SIZE });\n const items = unwrapItems(result);\n allItems.push(...items);\n\n // Use server metadata for termination\n const meta = extractPaginationMeta(result);\n if (meta?.totalPages !== undefined) {\n if (page >= meta.totalPages) break;\n } else if (!isPagePaginatedResponse(result)) {\n // Raw array or no metadata — single fetch is enough\n if (items.length < MAX_PAGE_SIZE) break;\n }\n\n if (page === MAX_PAGES) {\n throw new CLIError(\n `Reached maximum page limit (${MAX_PAGES}). Results may be incomplete.`\n );\n }\n\n page++;\n }\n\n return allItems;\n}\n\n/**\n * Fetch all pages from a cursor-based paginated endpoint.\n * The fetcher receives { cursor? } and should return the raw API response.\n * Throws CLIError if MAX_PAGES is reached without exhausting all pages.\n */\nexport async function fetchAllCursorPages(\n fetcher: (opts: { cursor?: string }) => Promise<unknown>\n): Promise<unknown[]> {\n const allItems: unknown[] = [];\n let cursor: string | undefined;\n let pages = 0;\n\n while (pages < MAX_PAGES) {\n const result = await fetcher({ cursor });\n const items = unwrapItems(result);\n allItems.push(...items);\n pages++;\n\n if (isCursorPaginatedResponse(result) && result.hasMore && result.nextCursor) {\n cursor = result.nextCursor;\n } else {\n break;\n }\n\n if (pages === MAX_PAGES) {\n throw new CLIError(\n `Reached maximum page limit (${MAX_PAGES}). Results may be incomplete.`\n );\n }\n }\n\n return allItems;\n}\n\n// ── ListResult factory ──────────────────────────────────────────────\n\n/**\n * Wrap a raw API response into a ListResult with explicit pagination metadata.\n * Works with both page-based and cursor-based responses, as well as plain arrays.\n *\n * @param data - Raw API response (paginated envelope or plain array)\n * @param supportsAll - Whether the calling command exposes --all\n */\nexport function listResult(data: unknown, supportsAll: boolean = false): ListResult {\n return {\n items: unwrapItems(data),\n meta: extractPaginationMeta(data),\n supportsAll,\n };\n}\n","import { printTable } from '../cli-utils';\nimport { applyJqFilter } from './jq';\nimport {\n type PaginationMeta,\n isListResult,\n extractPaginationMeta,\n formatPaginationWarning,\n unwrapItems,\n} from './pagination';\n\nexport type OutputFormat = 'json' | 'jsonl' | 'table';\n\nexport interface OutputOptions {\n outputFormat: OutputFormat;\n /**\n * jq filter applied to the serialised JSON before it reaches stdout.\n *\n * Setting this implies JSON output regardless of `outputFormat`: a filter\n * over a rendered table is meaningless, and silently filtering nothing is\n * worse than ignoring the flag. See `lib/jq.ts` for why the filter lives\n * here rather than in a shell pipe.\n */\n jq?: string;\n}\n\nexport interface TableColumn<T> {\n header: string;\n getValue: (item: T) => string;\n maxWidth?: number;\n}\n\n/** Write JSON to stdout, applying `opts.jq` when one was requested. */\nfunction writeJson(value: unknown, opts: OutputOptions, pretty = true): void {\n const json = pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value);\n if (opts.jq) {\n const filtered = applyJqFilter(json, opts.jq);\n process.stdout.write(filtered === '' ? '\\n' : filtered + '\\n');\n return;\n }\n process.stdout.write(json + '\\n');\n}\n\n/** Detect default output format based on whether stdout is a TTY */\nexport function detectOutputFormat(explicit?: string): OutputFormat {\n if (explicit) return explicit as OutputFormat;\n return process.stdout.isTTY ? 'table' : 'json';\n}\n\n/**\n * Write a list of items to stdout in the requested format.\n *\n * Accepts:\n * - A `ListResult` (explicit contract with items, meta, supportsAll) — preferred.\n * - Raw arrays, paginated responses ({ items: [...] }), or any object — legacy.\n *\n * When a `ListResult` is passed, its explicit `meta` and `supportsAll` are used.\n * When raw data is passed, pagination metadata is auto-detected with\n * `supportsAll: false` as the safe default.\n *\n * The optional `paginationMeta` and `supportsAll` parameters are kept for\n * backward compatibility but are ignored when a `ListResult` is passed.\n */\nexport function outputData(\n data: unknown,\n opts: OutputOptions,\n columns?: TableColumn<any>[],\n paginationMeta?: PaginationMeta,\n supportsAll?: boolean\n): void {\n let items: unknown[];\n let meta: PaginationMeta | undefined;\n let allSupported: boolean;\n\n if (isListResult(data)) {\n // Explicit contract: use ListResult fields directly\n items = data.items;\n meta = data.meta;\n allSupported = data.supportsAll ?? false;\n } else {\n // Legacy path: auto-detect from raw data\n items = unwrapItems(data);\n meta = paginationMeta ?? extractPaginationMeta(data);\n allSupported = supportsAll ?? false;\n }\n\n const warning = formatPaginationWarning(meta, allSupported);\n if (warning) {\n process.stderr.write(warning + '\\n');\n }\n\n if (opts.jq) {\n writeJson(items, opts);\n return;\n }\n\n switch (opts.outputFormat) {\n case 'json':\n writeJson(items, opts);\n break;\n case 'jsonl':\n for (const item of items) {\n process.stdout.write(JSON.stringify(item) + '\\n');\n }\n break;\n case 'table':\n if (columns) {\n printTable(items, columns);\n } else {\n writeJson(items, opts);\n }\n break;\n }\n}\n\n/** Write a single object to stdout in the requested format */\nexport function outputSingle<T>(data: T, opts: OutputOptions, columns?: TableColumn<T>[]): void {\n if (opts.jq) {\n writeJson(data, opts);\n return;\n }\n\n switch (opts.outputFormat) {\n case 'json':\n writeJson(data, opts);\n break;\n case 'jsonl':\n process.stdout.write(JSON.stringify(data) + '\\n');\n break;\n case 'table':\n if (columns) {\n printTable([data], columns);\n } else {\n writeJson(data, opts);\n }\n break;\n }\n}\n\n/** Common column factory helpers for domain files.\n *\n * GR app-facing API wire is camelCase. First-party consumers (CLI, lambdas we\n * own) read that shape only — no snake_case dual-read \"bandaid\". When the API\n * flips a key, convert the consumer; do not carry both. (#19305)\n */\nexport const COL = {\n id: (): TableColumn<any> => ({ header: 'ID', getValue: (item) => String(item.id ?? '') }),\n uuid: (): TableColumn<any> => ({ header: 'UUID', getValue: (item) => item.uuid ?? '' }),\n name: (): TableColumn<any> => ({ header: 'NAME', getValue: (item) => item.name ?? '' }),\n status: (): TableColumn<any> => ({ header: 'STATUS', getValue: (item) => item.status ?? '' }),\n created: (): TableColumn<any> => ({\n header: 'CREATED',\n getValue: (item) => item.createdAt ?? '',\n }),\n updated: (): TableColumn<any> => ({\n header: 'UPDATED',\n getValue: (item) => item.updatedAt ?? '',\n }),\n description: (): TableColumn<any> => ({\n header: 'DESCRIPTION',\n getValue: (item) => item.description ?? '',\n }),\n enabled: (): TableColumn<any> => ({\n header: 'ENABLED',\n getValue: (item) => String(item.enabled ?? ''),\n }),\n};\n\n/**\n * Print a follow-on suggestion under the result, table output only.\n *\n * Suppressed for json/jsonl so machine consumers get parseable output — a hint\n * written to stdout would corrupt it.\n */\nexport function hint(opts: { outputFormat?: string }, lines: string[]): void {\n if ((opts.outputFormat ?? 'table') !== 'table') return;\n process.stdout.write('\\n' + lines.join('\\n') + '\\n');\n}\n\n/** Write a status/progress message to stderr (never pollutes stdout) */\nexport function stderr(msg: string): void {\n process.stderr.write(msg + '\\n');\n}\n\n/**\n * Wait until everything written to stdout has actually reached the OS.\n *\n * Call this before `process.exit()`. `process.exit` does not flush a pending\n * asynchronous write, and stdout **is** asynchronous whenever it is a pipe\n * (Node only makes it synchronous for files and TTYs), so a large piped payload\n * is silently cut at the pipe buffer — 8KB on Linux, 64KB elsewhere.\n *\n * `writableNeedDrain` is the wrong probe and was the bug: it only goes true\n * once the buffered amount exceeds `highWaterMark` (16KB by default). A 10KB\n * JSON document sits fully buffered with `needDrain === false`, so the guard\n * passed and `process.exit` discarded the tail. Observed as\n * `json.decoder.JSONDecodeError: Expecting ':' delimiter` at exactly char 8192\n * in a script reading `gr admin workspaces list -o json` through a pipe, while\n * the same command redirected to a file was complete and valid.\n *\n * The reliable signal is the write callback, which fires only after the data is\n * handed off. An empty write queues behind whatever is already pending, so its\n * callback is a barrier for all of it.\n */\nexport async function flushStdout(): Promise<void> {\n if (process.stdout.writableLength === 0) return;\n await new Promise<void>((resolve) => {\n process.stdout.write('', () => resolve());\n });\n}\n","/**\n * CLI handler for organization-level authentication challenges (GRA-6994/6995).\n *\n * When a workspace API call returns a 401 with WWW-Authenticate: Bearer realm=\"org\",\n * the SDK calls this handler. The CLI satisfies the challenge, in order:\n *\n * 1. Cached org session — a `gr_sess_` captured on a prior invocation and stored\n * under the profile. Replayed once as `X-Org-Session`; no browser. A rejected\n * candidate or a request for stronger authentication proceeds to fresh sign-in.\n * 2. Non-SSO direct join — `POST /o/{org}/join` with the account bearer token,\n * reading the org session from the response body's `orgSession` (orgs that\n * allow internal auth; the API sets no cookie for a bearer client). Result\n * is cached like (1).\n * 3. SSO browser step-up (loopback callback, RFC 8252) — open the org SSO URL in\n * the browser with a `return_to` pointing at the `/cli/org-auth` bridge page,\n * which redirects a single-use PKCE code back to a one-time `127.0.0.1`\n * listener the CLI runs. The CLI redeems the code over its authenticated API connection and caches the session like (1). Interactive\n * (profile) contexts only.\n * 4. Headless / non-interactive — throw a clear hint (use `gr login` or an API key).\n */\n\nimport { createServer } from 'http';\nimport { execFile } from 'child_process';\nimport { createHash, randomBytes } from 'crypto';\nimport type { AddressInfo } from 'net';\nimport type { GravityRailClient } from '@gravity-rail/sdk';\nimport type { OrgAuthInfo, OrgAuthSessionCandidate } from '@gravity-rail/sdk';\nimport type { CredentialsManager } from '../cli-utils';\nimport { stderr } from './output';\nimport { isOrgSessionCredential } from './org-session';\n\n/** A successful response that does not satisfy the sign-in contract. */\nclass OrgSignInResponseError extends Error {}\n\nconst ORG_AUTH_TIMEOUT_MS = 5 * 60 * 1000;\n\n/**\n * Cache captured SSO sessions conservatively under the server's 7-day org\n * session TTL (`ORG_SCOPED_SESSION_TTL_SECONDS`) so a cached session is\n * refreshed by a fresh step-up before it can 401 mid-command.\n */\nconst ORG_SESSION_CACHE_TTL_MS = 6.5 * 24 * 60 * 60 * 1000;\n\n/** Bridge page path on the frontend host that relays the org session to loopback. */\nconst CLI_ORG_AUTH_BRIDGE_PATH = '/cli/org-auth';\n\n/** Canonical UUID shape for the org id carried in the 401 challenge. */\nconst ORG_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/**\n * Context the org-auth handler needs to cache sessions and decide whether an\n * interactive browser step-up is permitted.\n */\nexport interface OrgAuthContext {\n /** Present for profile (login) contexts; absent for API-key / broker. */\n credentialsManager?: CredentialsManager;\n env: string;\n profile?: string;\n /** Configured frontend origin — the exact host the org SSO URL must live on. */\n frontendUrl?: string;\n /**\n * Whether a browser step-up may be launched. False for non-interactive\n * contexts (code-interpreter broker, CI) — those get the headless hint.\n */\n interactive: boolean;\n}\n\n/**\n * Attempt to satisfy an org auth challenge via the direct join endpoint.\n * Returns the org session credential on success, null when SSO is required.\n * Throws on unexpected network / server errors.\n */\nasync function tryDirectJoin(\n apiUrl: string,\n accessToken: string,\n orgAuthInfo: OrgAuthInfo\n): Promise<{ session: string; expiresAt?: string } | null> {\n const response = await fetch(`${apiUrl}/api/v2/o/${orgAuthInfo.orgUuid}/join`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${accessToken}`,\n },\n body: '{}',\n });\n\n if (response.status === 400) {\n // Org requires SSO — direct join is not permitted for this account\n return null;\n }\n\n if (!response.ok) {\n // Don't include the response body — the backend currently returns safe\n // JSON, but a future change could put PHI or other sensitive data there.\n // Status code is sufficient to disambiguate the failure mode.\n throw new Error(`Org join failed (HTTP ${response.status})`);\n }\n\n // The API sets no cookie for a bearer client: the org session comes back in\n // the body, and the CLI replays it as `X-Org-Session`.\n let body: { orgSession?: unknown; expiresAt?: unknown };\n try {\n body = (await response.json()) as { orgSession?: unknown; expiresAt?: unknown };\n } catch {\n throw new OrgSignInResponseError('Org join succeeded but returned an invalid response');\n }\n if (!body || typeof body !== 'object' || Array.isArray(body)) {\n throw new OrgSignInResponseError('Org join succeeded but returned an invalid response');\n }\n if (typeof body.orgSession !== 'string' || !body.orgSession) {\n throw new OrgSignInResponseError('Org join succeeded but returned no org session');\n }\n let expiresAt: string | undefined;\n if (body.expiresAt !== undefined) {\n if (typeof body.expiresAt !== 'string' || !Number.isFinite(Date.parse(body.expiresAt))) {\n throw new OrgSignInResponseError('Org join returned an invalid session expiry');\n }\n expiresAt = body.expiresAt;\n if (Date.parse(expiresAt) <= Date.now()) {\n throw new OrgSignInResponseError('Org join returned an expired session');\n }\n }\n return { session: body.orgSession, expiresAt };\n}\n\n/**\n * Validate that an auth URL is safe to hand to the OS URL opener.\n *\n * `open` / `xdg-open` / `cmd.exe start` will follow any URI scheme the OS\n * registers — including `file://`, `javascript:`, and custom app handlers —\n * so a compromised/MITMed server returning an attacker-controlled `authUrl`\n * could trigger arbitrary URI execution. Restrict to http(s) and require\n * the same parent domain as the configured API host (e.g. SSO login on\n * `app.gravityrail.com` is allowed when the API is `api.gravityrail.com`,\n * but `attacker.example` against `api.gravityrail.com` is rejected).\n *\n * \"Same parent domain\" is a last-2-labels match. This is a heuristic — it\n * does not consult the Public Suffix List, so `foo.co.uk` and `bar.co.uk`\n * would falsely match — but Gravity Rail's auth hosts do not live under\n * those ccTLDs. The auth host is always the configured frontend host\n * (backend `build_org_auth_url` uses `SYSTEM_CONFIG.frontend_url`), so we\n * match it EXACTLY against the known API + frontend hosts rather than any\n * subdomain heuristic — a last-2-labels match would admit\n * `evil.gravityrail.com`. Both `apiUrl` and `frontendUrl` are trust anchors\n * derived from the CLI's own env config, not from the server response.\n */\nfunction isAllowedAuthUrl(url: string, apiUrl: string, frontendUrl?: string): boolean {\n try {\n const parsed = new URL(url);\n if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') return false;\n const allowedHosts = [apiUrl, frontendUrl]\n .filter((u): u is string => Boolean(u))\n .map((u) => {\n try {\n return new URL(u).hostname;\n } catch {\n return undefined;\n }\n })\n .filter((h): h is string => Boolean(h));\n return allowedHosts.includes(parsed.hostname);\n } catch {\n return false;\n }\n}\n\n/** Open a URL in the system browser (cross-platform). */\nfunction openBrowser(url: string): void {\n let command: string;\n let args: string[];\n\n if (process.platform === 'darwin') {\n command = 'open';\n args = [url];\n } else if (process.platform === 'win32') {\n command = 'cmd.exe';\n args = ['/c', 'start', '', url];\n } else {\n command = 'xdg-open';\n args = [url];\n }\n\n execFile(command, args, (_err) => {\n // Failure is non-fatal — the URL is printed to stderr so the user can open it manually.\n });\n}\n\n/**\n * Non-interactive when there is no way to complete a browser step-up: an\n * explicit opt-out, or a Linux session with no display server. macOS/Windows\n * always have a windowing system available to `open`/`start`.\n */\nfunction isHeadless(): boolean {\n if (process.env.GRAVITY_RAIL_NO_BROWSER) return true;\n if (process.platform === 'linux') {\n return !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY;\n }\n return false;\n}\n\ninterface OrgSessionCapture {\n /** Resolves with the ephemeral bound loopback port once the server is listening. */\n ready: Promise<number>;\n /** Resolves with the code delivered by the browser navigation. */\n session: Promise<string>;\n close: () => void;\n}\n\n/** A loopback navigation listener. It accepts only a code with this flow's state and org. */\nexport function startOrgSessionCapture(\n expectedState: string,\n expectedOrgUuid: string,\n _allowedOrigin: string\n): OrgSessionCapture {\n let resolveSession!: (value: string) => void;\n let rejectSession!: (reason: Error) => void;\n const session = new Promise<string>((resolve, reject) => {\n resolveSession = resolve;\n rejectSession = reject;\n });\n\n const server = createServer((req, res) => {\n res.setHeader('Cache-Control', 'no-store');\n res.setHeader('Referrer-Policy', 'no-referrer');\n if (req.method !== 'GET') {\n res.writeHead(405);\n res.end();\n return;\n }\n const callback = new URL(req.url ?? '/', 'http://127.0.0.1');\n const code = callback.searchParams.get('code');\n if (\n callback.pathname !== '/' ||\n !code?.startsWith('gr_cli_org_') ||\n callback.searchParams.get('state') !== expectedState ||\n callback.searchParams.get('org_uuid') !== expectedOrgUuid\n ) {\n res.writeHead(400);\n res.end('Invalid sign-in callback');\n return;\n }\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('Return to the terminal to finish sign-in.');\n resolveSession(code);\n });\n\n let resolveReady!: (port: number) => void;\n let rejectReady!: (reason: Error) => void;\n const ready = new Promise<number>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n\n server.on('error', (err) => {\n rejectReady(err);\n rejectSession(err);\n });\n server.listen(0, '127.0.0.1', () => {\n // Inside the 'listening' callback address() is always the bound AddressInfo.\n resolveReady((server.address() as AddressInfo).port);\n });\n\n const timeout = setTimeout(() => {\n rejectSession(\n new Error(\n 'Organization authentication timed out.\\n' +\n 'Complete sign-in in the browser, then re-run the command.'\n )\n );\n }, ORG_AUTH_TIMEOUT_MS);\n timeout.unref();\n\n // Idempotent — the caller's finally and any test both call close(); a second\n // server.close() would otherwise error on an already-closed server.\n let closed = false;\n const close = (): void => {\n if (closed) return;\n closed = true;\n clearTimeout(timeout);\n server.close();\n };\n\n return { ready, session, close };\n}\n\n/** Build the browser URL: the org SSO auth URL with a return_to to the bridge. */\nexport function buildStepUpUrl(\n authUrl: string,\n orgUuid: string,\n port: number,\n state: string,\n challenge: string\n): string {\n const url = new URL(authUrl);\n // Encode the inner bridge query with URLSearchParams so org/port/state can't\n // break out of their params, then set the whole relative return_to (the\n // callback sanitizes it relative-only — open-redirect guard — and\n // URLSearchParams.set percent-encodes the outer value).\n const bridgeQuery = new URLSearchParams({ org: orgUuid, port: String(port), state, challenge });\n url.searchParams.set('return_to', `${CLI_ORG_AUTH_BRIDGE_PATH}?${bridgeQuery.toString()}`);\n return url.toString();\n}\n\n/** Randomised state nonce binding the browser flow to this CLI process. */\nfunction newStateNonce(): string {\n return randomBytes(16).toString('hex');\n}\n\n/**\n * Complete an SSO org challenge via the browser + loopback bridge.\n * Returns the captured `gr_sess_` org session.\n */\nasync function stepUpViaBrowser(\n orgAuthInfo: OrgAuthInfo,\n apiUrl: string,\n accessToken: string\n): Promise<string> {\n // Precondition: the caller has already validated authUrl via isAllowedAuthUrl.\n const state = newStateNonce();\n const verifier = randomBytes(32).toString('base64url');\n const challenge = createHash('sha256').update(verifier).digest('base64url');\n const allowedOrigin = new URL(orgAuthInfo.authUrl).origin;\n const capture = startOrgSessionCapture(state, orgAuthInfo.orgUuid, allowedOrigin);\n\n try {\n const port = await capture.ready;\n const stepUpUrl = buildStepUpUrl(\n orgAuthInfo.authUrl,\n orgAuthInfo.orgUuid,\n port,\n state,\n challenge\n );\n stderr(`\\nThis workspace requires organization SSO authentication.`);\n stderr(`Opening browser to complete sign-in...`);\n stderr(` ${stepUpUrl}\\n`);\n stderr(`If the browser does not open, visit the URL above manually.`);\n openBrowser(stepUpUrl);\n const code = await capture.session;\n const response = await fetch(`${apiUrl}/api/v2/auth/cli-org-handoff/redeem`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${accessToken}` },\n body: JSON.stringify({ orgUuid: orgAuthInfo.orgUuid, code, verifier }),\n });\n if (!response.ok)\n throw new Error(`Could not finish organization sign-in (${response.status}).`);\n let result: { orgSession?: unknown };\n try {\n result = (await response.json()) as { orgSession?: unknown };\n } catch {\n throw new OrgSignInResponseError('Invalid organization sign-in response.');\n }\n if (!result || !isOrgSessionCredential(result.orgSession)) {\n throw new OrgSignInResponseError('Invalid organization sign-in response.');\n }\n return result.orgSession;\n } finally {\n capture.close();\n }\n}\n\n/**\n * Register a CLI org-auth handler on the given client.\n *\n * See the module docstring for the resolution order (cache → non-SSO join →\n * SSO browser step-up → headless hint). Captured sessions are cached under the\n * profile (when a credentials manager is provided). The returned candidate lets\n * the SDK adopt it only if the original authentication context still owns the\n * request (Node.js has no document.cookie).\n */\nexport function registerOrgAuthHandler(\n apiClient: GravityRailClient,\n apiUrl: string,\n accessToken: string,\n orgAuthCtx?: OrgAuthContext\n): void {\n apiClient.setOrgAuthHandler(\n async (orgAuthInfo: OrgAuthInfo): Promise<OrgAuthSessionCandidate> => {\n const orgUuid = orgAuthInfo.orgUuid;\n // The org id is server-supplied (parsed from the challenge header). Reject\n // anything that is not a canonical UUID before it flows into a join URL\n // path or the bridge return_to query.\n if (!ORG_UUID_RE.test(orgUuid)) {\n throw new Error('Invalid organization id in auth challenge');\n }\n const cm = orgAuthCtx?.credentialsManager;\n\n // An asynchronous sign-in must not overwrite a newer cached login.\n const initialCachedSession =\n cm && orgAuthCtx\n ? cm.getOrgSession(orgAuthCtx.env, orgAuthCtx.profile, orgUuid)\n : undefined;\n\n // Return the newly issued candidate for conditional SDK adoption. Persist\n // it only while this flow still owns the profile's cache entry.\n const adopt = (session: string, expiresAt?: string): OrgAuthSessionCandidate => {\n // Validate before persistence; SDK adoption is a later boundary and\n // must not leave a malformed server response in the profile cache.\n if (!isOrgSessionCredential(session)) {\n throw new OrgSignInResponseError('Invalid organization sign-in response.');\n }\n if (\n cm &&\n orgAuthCtx &&\n expiresAt &&\n cm.getOrgSession(orgAuthCtx.env, orgAuthCtx.profile, orgUuid) ===\n initialCachedSession\n ) {\n cm.setOrgSession(orgAuthCtx.env, orgAuthCtx.profile, orgUuid, session, expiresAt);\n }\n return {\n session,\n orgUuid,\n source: 'new',\n onRejected: () => {\n if (cm && orgAuthCtx)\n cm.removeOrgSession(orgAuthCtx.env, orgAuthCtx.profile, orgUuid, session);\n },\n };\n };\n\n // 1. Try a cache candidate only before any rejection/stronger-context\n // challenge. The actual API request validates it against live policy.\n if (cm && orgAuthCtx && !orgAuthInfo.sessionRejected && !orgAuthInfo.acrValues?.length) {\n const cached = cm.getOrgSession(orgAuthCtx.env, orgAuthCtx.profile, orgUuid);\n if (cached) {\n return {\n session: cached,\n orgUuid,\n source: 'cache',\n onRejected: () => {\n cm.removeOrgSession(orgAuthCtx.env, orgAuthCtx.profile, orgUuid, cached);\n },\n };\n }\n }\n\n // 2. Non-SSO direct join.\n let orgSession: Awaited<ReturnType<typeof tryDirectJoin>> = null;\n try {\n orgSession = await tryDirectJoin(apiUrl, accessToken, orgAuthInfo);\n } catch (err) {\n if (err instanceof OrgSignInResponseError) throw err;\n const msg = err instanceof Error ? err.message : String(err);\n stderr(`Warning: org direct-join failed (${msg}); trying browser sign-in`);\n }\n if (orgSession !== null) {\n // A missing expiry permits this command, without inventing a\n // lifetime for a reusable cache entry. Contract failures are final.\n return adopt(orgSession.session, orgSession.expiresAt);\n }\n\n // 3./4. SSO org — browser step-up when interactive, else the headless hint.\n if (!orgAuthCtx?.interactive || isHeadless()) {\n throw new Error(\n 'This workspace’s organization requires SSO sign-in, which needs a browser.\\n' +\n 'Run an interactive `gr` command on a machine with a browser to sign in once ' +\n '(the session is then cached), or use an API key for non-interactive use:\\n' +\n ' export GRAVITY_RAIL_API_KEY=<key> (see: gr api-keys)'\n );\n }\n\n // Validate the auth URL against the exact configured API + frontend hosts\n // before opening it, so a hostile/MITM'd URL can't pivot the OS opener.\n if (!isAllowedAuthUrl(orgAuthInfo.authUrl, apiUrl, orgAuthCtx.frontendUrl)) {\n throw new Error(\n `Refusing to open organization auth URL: host does not match the configured API/frontend host. ` +\n `Re-run with the expected --api-url, or contact support.`\n );\n }\n\n const session = await stepUpViaBrowser(orgAuthInfo, apiUrl, accessToken);\n return adopt(session, new Date(Date.now() + ORG_SESSION_CACHE_TTL_MS).toISOString());\n }\n );\n}\n","/**\n * Sandbox adapter for Gravity Rail code-interpreter environments.\n *\n * This package only adapts sandbox-provided GRAVITY_RAIL_* environment values\n * to the official @gravity-rail/sdk surface. API methods and builder classes\n * live in the SDK.\n */\nimport {\n GravityRailClient,\n WorkspaceBuilder,\n runWorkspaceScript,\n type File as GravityRailFile,\n type GravityRailWorkspaceClient,\n type UploadFileData,\n} from '@gravity-rail/sdk';\nimport { readSandboxEnv, type SandboxEnv } from './env';\nimport { createSandboxFetch } from './sandbox-fetch';\n\nexport { readSandboxEnv } from './env';\nexport { createUnixBrokerFetch } from './unix-broker-fetch';\nexport type { SandboxEnv } from './env';\nexport { askUser } from './ask-user';\nexport type {\n AskAnswer,\n AskRejected,\n AskChoice,\n AskField,\n AskFieldType,\n AskSpec,\n AskSubmitted,\n AskUnavailable,\n} from './ask-user';\nexport {\n MAX_SAY_CHARS,\n SAY_FIELD,\n ask,\n clearHighlight,\n highlight,\n navigate,\n point,\n say,\n sayAskSpec,\n ui,\n} from './ui';\nexport type { HighlightOptions, SayOptions } from './ui';\nexport { Flow, FlowExit, runFlow } from './flow';\nexport type { FlowAskResult, FlowDefinition, FlowMeta, FlowRejection, FlowScope } from './flow';\nexport type { SandboxAuditHeaders } from './sandbox-fetch';\nexport {\n ELEVATION_MARKER_FILENAME,\n GrElevationRequired,\n createSandboxFetch,\n withAuditHeaders,\n withElevationInterceptor,\n} from './sandbox-fetch';\nexport type { SandboxFetchEnv } from './sandbox-fetch';\nexport {\n AgentBuilder,\n ApplyError,\n FormBuilder,\n GravityRailClient,\n JourneyBuilder,\n MemberFilterBuilder,\n MemberLabelBuilder,\n NotificationRuleBuilder,\n RoutineBuilder,\n TaskBuilder,\n WorkspaceBuilder,\n WorkflowBuilder,\n runWorkspaceScript,\n toSafeMemberImportPreview,\n toSafeMemberImportSummary,\n type GravityRailWorkspaceClient,\n} from '@gravity-rail/sdk';\n\nexport function createSdkClient(env: SandboxEnv = readSandboxEnv()): GravityRailClient {\n // Point the SDK at the loopback broker with NO auth header (undefined apiKey ⇒\n // BaseApiClient skips Authorization); the broker injects the real Bearer\n // token. No DNS pin — the broker is on 127.0.0.1, not the API host.\n return new GravityRailClient(\n undefined,\n env.brokerUrl,\n createSandboxFetch({\n chatId: env.chatId,\n sessionId: env.sessionId,\n toolCallId: env.toolCallId,\n })\n );\n}\n\nexport function createSandboxClient(\n env: SandboxEnv = readSandboxEnv()\n): GravityRailWorkspaceClient {\n if (!env.workspaceUuid) throw new Error('Workspace operations require a workspace Job');\n return createSdkClient(env).workspace(env.workspaceUuid);\n}\n\nexport function createWorkspaceBuilder(env: SandboxEnv = readSandboxEnv()): WorkspaceBuilder {\n return new WorkspaceBuilder(createSandboxClient(env));\n}\n\nexport function fileDownloadUrl(\n file: Pick<GravityRailFile, 'id' | 'filename'>,\n env: SandboxEnv = readSandboxEnv()\n): string {\n if (!env.workspaceUuid) throw new Error('Workspace files require a workspace Job');\n return `/api/v2/w/${env.workspaceUuid}/files/${file.id}/contents/${encodeURIComponent(file.filename)}`;\n}\n\n/** Call a platform operation under the current Job's immutable authorization. */\nexport async function requestJobTool(\n name: string,\n args: Record<string, unknown>,\n env: SandboxEnv = readSandboxEnv(),\n requestId: string = crypto.randomUUID()\n): Promise<unknown> {\n if (!env.jobUuid || !env.jobBrokerPath)\n throw new Error('This computer has no active Job broker');\n const response = await createSandboxFetch(env)(`${env.brokerUrl}${env.jobBrokerPath}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ requestId, name, args }),\n });\n if (!response.ok) throw new Error(`Job operation was refused (${response.status})`);\n return response.json();\n}\n\nexport async function saveToChat(\n filename: string,\n data: UploadFileData,\n mimeType = 'application/octet-stream',\n env: SandboxEnv = readSandboxEnv()\n): Promise<GravityRailFile> {\n if (env.chatFolderId === undefined) {\n throw new Error('Sandbox file delivery failed - GRAVITY_RAIL_CHAT_FOLDER_ID is not set');\n }\n\n return createSandboxClient(env).uploadFile({\n filename,\n data,\n mimeType,\n folderId: env.chatFolderId,\n overwrite: true,\n });\n}\n\nexport async function displayFile(\n filename: string,\n data: UploadFileData,\n mimeType = 'application/octet-stream',\n env: SandboxEnv = readSandboxEnv()\n): Promise<GravityRailFile> {\n const file = await saveToChat(filename, data, mimeType, env);\n const label = escapeMarkdownLabel(filename);\n const url = fileDownloadUrl(file, env);\n (globalThis as { console?: { log: (message: string) => void } }).console?.log(\n mimeType.startsWith('image/') ? `` : `[${label}](${url})`\n );\n return file;\n}\n\nexport function runScript(\n build: (workspace: WorkspaceBuilder) => void | Promise<void>,\n mode = 'plan',\n env: SandboxEnv = readSandboxEnv()\n): Promise<unknown> {\n return runWorkspaceScript(createSandboxClient(env), build, mode);\n}\n\nfunction escapeMarkdownLabel(value: string): string {\n return value.replace(/[\\\\[\\]]/g, '\\\\$&');\n}\n","/**\n * Sandbox environment: the GRAVITY_RAIL_* values the runtime injects.\n *\n * Split out of index.ts so modules that only need the env (askUser) do not\n * import the whole adapter surface — the cycle that would otherwise create is\n * silent under ESM and shows up as an undefined import at run time.\n */\nexport interface SandboxEnv {\n workspaceUuid?: string;\n jobUuid?: string;\n organizationId?: number;\n agentId?: number;\n jobBrokerPath?: string;\n /**\n * Loopback URL of the credential broker — the sandbox's ONLY route to the\n * API. The scoped token is never in the sandbox env: requests go here with NO\n * auth header and the root daemon injects `Authorization: Bearer <token>` and\n * forwards to the API. Always present.\n *\n * The real API origin is deliberately NOT exposed to sandbox code. Under\n * VPC-only egress a direct call to it cannot succeed (public DNS resolves the\n * internet-facing ALB, which the VM has no route to), so knowing the URL only\n * invites requests that hang until they time out.\n */\n brokerUrl: string;\n chatFolderId?: number;\n chatId?: number;\n /**\n * The acting Member — whoever's turn caused this script to run. Lets a script\n * partition its own state per member (`state/member-<id>.json`) and stamp who\n * wrote a record, without a round-trip to ask the API \"who am I\".\n *\n * OPTIONAL on purpose, even though the runtime always emits it: a script run\n * outside a member session (a bare `node script.ts` in a dev shell, a unit\n * test constructing an explicit env) has no acting member, and making this\n * required would turn those into a bootstrap throw. Branch on `undefined`\n * rather than defaulting to 0 — a wrong-but-present id silently mixes two\n * members' state files, which is worse than having none.\n *\n * Not an authorization input: the broker's scoped token is what the API\n * checks, and it is minted for this same member. Reading this value cannot\n * widen what a script may do.\n */\n memberId?: number;\n sessionId?: string;\n toolCallId?: string;\n}\n\ntype SandboxGlobal = typeof globalThis & {\n __GRAVITY_RAIL_SANDBOX_ENV__?: SandboxEnv;\n};\n\nfunction requiredEnv(name: string): string {\n const value = typeof process !== 'undefined' ? process.env[name] : undefined;\n if (!value) {\n throw new Error(`Sandbox bootstrap failed - missing env var: ${name}`);\n }\n return value;\n}\n\nfunction optionalInt(name: string): number | undefined {\n const raw = typeof process !== 'undefined' ? process.env[name] : undefined;\n if (!raw) return undefined;\n const parsed = Number(raw);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\nfunction readProcessEnv(): SandboxEnv {\n const workspaceUuid = process.env.GRAVITY_RAIL_WORKSPACE_UUID;\n const jobUuid = process.env.GRAVITY_RAIL_JOB_UUID;\n const organizationId = optionalInt('GRAVITY_RAIL_ORGANIZATION_ID');\n const agentId = optionalInt('GRAVITY_RAIL_AGENT_ID');\n if (!workspaceUuid && !(jobUuid && organizationId && agentId)) {\n requiredEnv('GRAVITY_RAIL_WORKSPACE_UUID');\n }\n return {\n workspaceUuid,\n jobUuid,\n organizationId,\n agentId,\n jobBrokerPath: process.env.GRAVITY_RAIL_JOB_BROKER_PATH,\n // The token is held by the broker, not the env; the broker URL is required.\n brokerUrl: requiredEnv('GRAVITY_RAIL_BROKER_URL'),\n chatFolderId: optionalInt('GRAVITY_RAIL_CHAT_FOLDER_ID'),\n chatId: optionalInt('GRAVITY_RAIL_CHAT_ID'),\n memberId: optionalInt('GRAVITY_RAIL_MEMBER_ID'),\n sessionId: typeof process !== 'undefined' ? process.env.GRAVITY_RAIL_SESSION_ID : undefined,\n toolCallId:\n typeof process !== 'undefined' ? process.env.GRAVITY_RAIL_TOOL_CALL_ID : undefined,\n };\n}\n\nexport function readSandboxEnv(explicit?: SandboxEnv): SandboxEnv {\n if (explicit) return explicit;\n const globalEnv = (globalThis as SandboxGlobal).__GRAVITY_RAIL_SANDBOX_ENV__;\n if (globalEnv) return globalEnv;\n return readProcessEnv();\n}\n","/**\n * Audit headers + scope-elevation interception for code-interpreter sandboxes.\n *\n * Sandbox code has exactly one outbound destination: the loopback credential\n * broker. There is no DNS pin here any more — the private-ALB pin only ever\n * existed because sandbox clients used to dial the API host directly, and they\n * no longer can (the API origin is not exposed to uid 1000 at all; the root\n * daemon holds it and applies the pin on the far side of the broker).\n */\n\nimport { writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { createUnixBrokerFetch } from './unix-broker-fetch';\n\n/**\n * Control marker filename the sandbox agent reads + deletes after each exec\n * (mirrors microvm/agent.py ELEVATION_MARKER_FILENAME). See GRA-6895.\n */\nexport const ELEVATION_MARKER_FILENAME = '.gr-elevation-request.json';\n\n/**\n * Thrown when a broker-relayed API call hits a scope-only 403 (GRA-6895).\n *\n * Before it is thrown, {@link writeElevationMarker} records the missing scope so\n * the sandbox agent surfaces an elevation request to `run_code`, which offers an\n * in-loop HITL scope elevation. Throwing stops the sandbox script; the marker is\n * what actually drives the elevation, so the outcome holds even if the caller\n * swallows this error.\n */\nexport class GrElevationRequired extends Error {\n readonly requiredScope: string;\n constructor(requiredScope: string, method: string, path: string) {\n super(\n `Gravity API ${method} ${path} failed (403): scope elevation required for '${requiredScope}'`\n );\n this.name = 'GrElevationRequired';\n this.requiredScope = requiredScope;\n }\n}\n\n/**\n * Record a scope-only 403 as the exec's elevation control marker.\n *\n * Last-wins: overwrites any prior marker in this exec. Written to\n * `GR_SANDBOX_ROOT` (the exec cwd), where the sandbox agent reads + deletes it.\n * Best-effort — a write failure must never mask the underlying 403.\n */\nfunction writeElevationMarker(scope: string, method: string, path: string): void {\n const root =\n (typeof process !== 'undefined' && process.env.GR_SANDBOX_ROOT) ||\n (typeof process !== 'undefined' ? process.cwd() : '.');\n try {\n // Path is the sandbox root (GR_SANDBOX_ROOT / cwd) joined to a FIXED\n // constant filename — no user input in either component, so no traversal.\n // oxlint-disable-next-line security/detect-non-literal-fs-filename -- root is the sandbox cwd, filename is a fixed constant\n writeFileSync(\n join(root, ELEVATION_MARKER_FILENAME),\n JSON.stringify({ scope, method, path }),\n 'utf8'\n );\n } catch {\n // best-effort — never mask the underlying 403\n }\n}\n\n/**\n * Wrap a fetch so a scope-only 403 (a 403 body carrying `required_scope`) writes\n * the elevation marker and throws {@link GrElevationRequired}. Any other 403 (or\n * a 403 without `required_scope`) is returned unchanged for the SDK's normal\n * error handling — purely additive on top of today's behavior.\n */\nexport function withElevationInterceptor(fetchFn: typeof fetch): typeof fetch {\n return async (input, init) => {\n const response = await fetchFn(input, init);\n if (response.status !== 403) return response;\n\n let requiredScope: string | undefined;\n try {\n const body: unknown = await response.clone().json();\n if (\n body !== null &&\n typeof body === 'object' &&\n typeof (body as { required_scope?: unknown }).required_scope === 'string' &&\n (body as { required_scope: string }).required_scope\n ) {\n requiredScope = (body as { required_scope: string }).required_scope;\n }\n } catch {\n // non-JSON / unreadable body — not a scope elevation; return as-is\n }\n if (!requiredScope) return response;\n\n const method = (init?.method ?? 'GET').toUpperCase();\n const rawPath =\n typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;\n // Store the URL PATH only (no scheme/host) so the HITL display matches the\n // Python client's resource path and isn't mangled by the backend's path\n // sanitizer (which strips ':' etc). Fall back to the raw string when it\n // isn't a parseable absolute URL (a relative path).\n let path = rawPath;\n try {\n path = new URL(rawPath).pathname;\n } catch {\n // relative / non-URL input — keep as-is\n }\n writeElevationMarker(requiredScope, method, path);\n throw new GrElevationRequired(requiredScope, method, path);\n };\n}\n\nexport interface SandboxAuditHeaders {\n chatId?: number;\n sessionId?: string;\n toolCallId?: string;\n}\n\ntype ToolCallGlobal = typeof globalThis & {\n __GRAVITY_RAIL_TOOL_CALL_ID__?: string;\n};\n\ntype WebRequest = Parameters<typeof fetch>[0];\ntype WebRequestInit = Parameters<typeof fetch>[1];\n\n/** Subset of sandbox env used when building fetch. */\nexport interface SandboxFetchEnv {\n chatId?: number;\n sessionId?: string;\n toolCallId?: string;\n}\n\nexport function withAuditHeaders(\n fetchFn: typeof fetch,\n headers: SandboxAuditHeaders\n): typeof fetch {\n const { chatId, sessionId, toolCallId } = headers;\n\n return async (input: WebRequest, init?: WebRequestInit): Promise<Response> => {\n const reqHeaders = new Headers(init?.headers);\n const dynamicToolCallId =\n (globalThis as ToolCallGlobal).__GRAVITY_RAIL_TOOL_CALL_ID__ ||\n (typeof process !== 'undefined' ? process.env.GRAVITY_RAIL_TOOL_CALL_ID : undefined);\n if (chatId !== undefined) {\n reqHeaders.set('X-GR-Chat-Id', String(chatId));\n }\n if (sessionId) {\n reqHeaders.set('X-GR-Session-Id', sessionId);\n }\n if (dynamicToolCallId || toolCallId) {\n reqHeaders.set('X-GR-Tool-Call-Id', dynamicToolCallId || toolCallId || '');\n }\n return fetchFn(input, { ...init, headers: reqHeaders });\n };\n}\n\n/** Build fetch for sandbox sessions (loopback broker + audit headers). */\nexport function createSandboxFetch(env: SandboxFetchEnv): typeof fetch {\n const socketPath =\n typeof process !== 'undefined' ? process.env.GRAVITY_RAIL_BROKER_SOCKET : undefined;\n return withElevationInterceptor(\n withAuditHeaders(socketPath ? createUnixBrokerFetch(socketPath) : fetch, {\n chatId: env.chatId,\n sessionId: env.sessionId,\n toolCallId: env.toolCallId,\n })\n );\n}\n","import { request as httpRequest } from 'node:http';\n\n/** HTTP over the one data socket exposed inside a Job's network namespace. */\nexport function createUnixBrokerFetch(socketPath: string): typeof fetch {\n return async (input, init) => {\n const request = new Request(input, init);\n const url = new URL(request.url);\n if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)) {\n throw new Error('The sandbox broker requires a loopback request');\n }\n const body = request.body ? Buffer.from(await request.arrayBuffer()) : undefined;\n return new Promise<Response>((resolve, reject) => {\n const connection = httpRequest(\n {\n socketPath,\n path: url.pathname + url.search,\n method: request.method,\n headers: Object.fromEntries(request.headers),\n },\n (response) => {\n const chunks: Buffer[] = [];\n let length = 0;\n response.on('data', (chunk: Buffer) => {\n length += chunk.length;\n if (length > 32 * 1024 * 1024) {\n connection.destroy(new Error('Sandbox response exceeds its size limit'));\n return;\n }\n chunks.push(chunk);\n });\n response.on('error', reject);\n response.on('end', () => {\n const headers = new Headers();\n for (const [name, value] of Object.entries(response.headers)) {\n if (Array.isArray(value)) value.forEach((item) => headers.append(name, item));\n else if (value !== undefined) headers.set(name, value);\n }\n const status = response.statusCode ?? 502;\n resolve(\n new Response([204, 205, 304].includes(status) ? null : Buffer.concat(chunks), {\n status,\n headers,\n })\n );\n });\n }\n );\n connection.on('error', reject);\n const abort = () => connection.destroy(new Error('Sandbox request was cancelled'));\n if (request.signal.aborted) abort();\n else request.signal.addEventListener('abort', abort, { once: true });\n connection.on('close', () => request.signal.removeEventListener('abort', abort));\n connection.end(body);\n });\n };\n}\n","/**\n * Script-raised prompts: let a skill script stop mid-run, put a form in front\n * of the operator, and continue with what they typed.\n *\n * The call blocks. The broker holds this request open, the backend parks the\n * script (blocked, never killed), and the worker renders the form and resolves\n * the hold with the answer — which arrives as this request's response body. To\n * the script it reads as one `await`.\n *\n * That is what makes procedural wizards possible: a script can branch on real\n * answers instead of guessing, and hand the model a summary of what the\n * operator chose when it finishes.\n */\nimport { createUnixBrokerFetch } from './unix-broker-fetch';\nimport { readSandboxEnv, type SandboxEnv } from './env';\n\n/** Control kinds a field can render as. */\nexport type AskFieldType = 'text' | 'longtext' | 'number' | 'select' | 'boolean';\n\nexport interface AskChoice {\n /** Machine value handed back to the script. */\n value: string;\n /** What the operator reads. Defaults to `value`. */\n label?: string;\n}\n\nexport interface AskField {\n /** Key this field's answer appears under in `values`. */\n name: string;\n /**\n * Operator-facing label. Defaults to `name`.\n *\n * Pass `''` for *no* label, which is different from passing nothing: a\n * narration beat's lone Continue button has the line above it as its\n * heading already, and falling back to the field name would draw\n * `continue` over it.\n */\n label?: string;\n type?: AskFieldType;\n /** Required for `select`; ignored otherwise. */\n choices?: AskChoice[];\n required?: boolean;\n placeholder?: string;\n /** Pre-filled value. */\n value?: string;\n /** Help text under the control. */\n help?: string;\n}\n\nexport interface AskSpec {\n /** Heading above the form. */\n title: string;\n /** One line of context under the title. */\n description?: string;\n fields: AskField[];\n /**\n * Label on the submit button. Ignored for a one-question form whose answers\n * are a short list — picking one IS the answer, so there is no button.\n */\n submitLabel?: string;\n /**\n * This ask is a narration beat: one line, one way to advance.\n *\n * Set by `ui.say`, never by hand. It travels to the client because a\n * surface may advance a beat hands-free — pressing the only button there\n * is does what the reader would have done — and must never do that to a\n * real question, where picking an option would be answering *for* them.\n * The client cannot safely infer the difference from the rendered form, so\n * the script states it.\n */\n narration?: boolean;\n}\n\n/** The operator filled the form in. */\nexport interface AskSubmitted {\n status: 'submitted';\n /** Field `name` → what they entered. Every declared field is present. */\n values: Record<string, string>;\n}\n\n/**\n * The operator declined the form. A wizard should stop, not retry.\n *\n * `reason` carries what they typed when they declined *in order to say\n * something*: the chat's \"Say something else…\" box, which answers the prompt\n * with prose instead of with the form. A plain dismissal (\"Skip\") has no\n * reason; the two are the same outcome because the operator did the same thing\n * either way, which is why there is no separate \"deflected\" status to forget to\n * handle.\n *\n * The script is NOT held open while that conversation happens: this answer\n * terminates the run. So print the reason before you return — whatever the\n * script writes on its way out is the only thing the model gets to act on.\n */\nexport interface AskRejected {\n status: 'rejected';\n /** Verbatim operator text. Absent — never empty — for a plain dismissal. */\n reason?: string;\n}\n\n/**\n * No prompt could be shown at all (no chat surface, or the backend cannot park\n * this exec). Distinct from `rejected`: nobody declined, nobody was asked.\n */\nexport interface AskUnavailable {\n status: 'unavailable';\n reason: string;\n}\n\nexport type AskAnswer = AskSubmitted | AskRejected | AskUnavailable;\n\n/** Path the broker serves the virtual ask endpoint on. */\nconst ASK_PATH = '/__gr_broker__/ask';\n\nfunction validate(spec: AskSpec): void {\n if (!spec || typeof spec.title !== 'string' || !spec.title.trim()) {\n throw new Error('askUser: a non-empty `title` is required');\n }\n if (!Array.isArray(spec.fields) || spec.fields.length === 0) {\n throw new Error('askUser: at least one field is required');\n }\n const seen = new Set<string>();\n for (const field of spec.fields) {\n if (!field?.name || typeof field.name !== 'string') {\n throw new Error('askUser: every field needs a string `name`');\n }\n if (seen.has(field.name)) {\n throw new Error(`askUser: duplicate field name '${field.name}'`);\n }\n seen.add(field.name);\n if (field.type === 'select' && !field.choices?.length) {\n throw new Error(`askUser: select field '${field.name}' needs \\`choices\\``);\n }\n }\n}\n\n/**\n * Ask the operator to fill in a form, and wait for the answer.\n *\n * ```ts\n * const answer = await askUser({\n * title: 'How should we follow up?',\n * fields: [\n * { name: 'channel', label: 'First channel', type: 'select',\n * choices: [{ value: 'sms' }, { value: 'voice' }] },\n * { name: 'days', label: 'Days between attempts', type: 'number', value: '1' },\n * ],\n * });\n * if (answer.status !== 'submitted') {\n * // Declined. `reason` is set only when they said why — and saying why is\n * // how they hand the question to the model, so print it and stop. Waiting\n * // for a follow-up here would wait forever: the run ends with this answer.\n * if (answer.status === 'rejected' && answer.reason) console.log(answer.reason);\n * return;\n * }\n * console.log(`Using ${answer.values.channel} every ${answer.values.days} days.`);\n * ```\n *\n * Always branch on `status`. A wizard that assumes `submitted` will read\n * `undefined` values when the operator declines.\n */\nexport async function askUser(\n spec: AskSpec,\n env: SandboxEnv = readSandboxEnv()\n): Promise<AskAnswer> {\n validate(spec);\n\n let response: Response;\n try {\n const socketPath =\n typeof process !== 'undefined' ? process.env.GRAVITY_RAIL_BROKER_SOCKET : undefined;\n const request = socketPath ? createUnixBrokerFetch(socketPath) : fetch;\n response = await request(`${env.brokerUrl}${ASK_PATH}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(spec),\n });\n } catch (error) {\n // Never throw for \"could not ask\" — a wizard should take its declined\n // path rather than die half-way through building something.\n return {\n status: 'unavailable',\n reason: error instanceof Error ? error.message : 'could not reach the prompt channel',\n };\n }\n\n let parsed: unknown;\n try {\n parsed = await response.json();\n } catch {\n return { status: 'unavailable', reason: `prompt channel returned ${response.status}` };\n }\n\n const answer = parsed as Partial<AskAnswer> | null;\n if (answer?.status === 'submitted') {\n const values = (answer as AskSubmitted).values ?? {};\n // Guarantee every declared field is present, so a script can destructure\n // without optional-chaining every read.\n const complete: Record<string, string> = {};\n for (const field of spec.fields) {\n complete[field.name] = String(values[field.name] ?? '');\n }\n return { status: 'submitted', values: complete };\n }\n if (answer?.status === 'rejected') {\n // Normalise a blank/absent/non-string reason to *no* reason. Carrying\n // `reason: ''` through would make every `if (answer.reason)` downstream\n // read a plain dismissal as \"they explained themselves\", and a script\n // would print an empty line at the model instead of nothing.\n const reason = (answer as AskRejected).reason;\n return typeof reason === 'string' && reason.trim()\n ? { status: 'rejected', reason }\n : { status: 'rejected' };\n }\n return {\n status: 'unavailable',\n reason:\n (answer as AskUnavailable | null)?.reason ?? `prompt channel returned ${response.status}`,\n };\n}\n","/**\n * The script's hands on the app: narrate, navigate, point, and ask.\n *\n * ## Every beat blocks; stage directions do not\n *\n * `say` and `ask` are the same verb. A tour line still needs a Next button —\n * the user has to finish reading before the guide moves on — so a line *is* a\n * question with one answer. Treating it as one buys two things that were\n * otherwise separate problems:\n *\n * - **Pacing.** The script advances when the user does, not on a timer the\n * script guessed. Nothing to add later; it falls out of blocking.\n * - **Ordering, by construction.** A non-blocking `say` had to be flushed\n * before the next call parked the exec, or three rapid lines would race\n * and the user would see only the last. If every line blocks, the second\n * cannot be sent until the first is answered, so there is no ordering\n * problem to solve.\n *\n * `navigate`, `highlight` and `clearHighlight` stay non-blocking. They are\n * stage directions rather than beats: nobody acknowledges a scene change, and\n * waiting for one would stall a script behind a lighting cue. They POST to an\n * ordinary workspace endpoint, which publishes on the chat's realtime channel\n * and returns. Because they travel the same forwardable `/api/` path as every\n * other call, they are authorised as the member, with no loopback bypass.\n *\n * So a beat reads:\n *\n * ```ts\n * await ui.navigate('app:page:workflows'); // stage direction\n * await ui.point('Workflows live here.', 'workflows.create-button'); // beat\n * ```\n *\n * and the spotlight is already up when the line appears, because `point`\n * publishes the highlight before it parks on the line.\n *\n * ## A stage direction never throws; a beat can end the script\n *\n * Losing an audience mid-way is not a reason to abandon a half-built\n * workspace, so `navigate`/`highlight` return a boolean nobody has to check.\n * A beat is different: the user can decline it, and that ends the run — see\n * `askUser` for the three outcomes and `Flow` for what a script should do\n * with them.\n */\nimport { askUser, type AskAnswer, type AskSpec } from './ask-user';\nimport { readSandboxEnv, type SandboxEnv } from './env';\nimport { createSandboxFetch } from './sandbox-fetch';\n\n/** Maximum characters in one `say`. Longer is a monologue — break it up. */\nexport const MAX_SAY_CHARS = 600;\n\n/**\n * Field name carrying a narration beat's acknowledgement.\n *\n * A beat is an ask with exactly one choice, so the value is never interesting —\n * what matters is that it came back at all. Exported so a script or a test can\n * read the answer back by name; nothing on the client reads it. What tells a\n * beat from a real question is `narration: true` on the spec, which the tool\n * turns into the payload's `guided` marker\n * (`lib/ai/tools/code_interpreter.py`) — see `sayAskSpec` below.\n */\nexport const SAY_FIELD = 'continue';\n\nexport interface HighlightOptions {\n /** Short caption shown against the highlighted element. */\n note?: string;\n}\n\nexport interface SayOptions {\n /**\n * Label on the button that advances the beat. Defaults to `Continue`.\n *\n * Worth setting when the line ends on a question the button answers\n * (\"Got it\", \"Show me\") — the default is right for ordinary narration and\n * wrong when the sentence has already asked something.\n */\n continueLabel?: string;\n}\n\ntype UiEvent =\n | { kind: 'navigate'; appUri: string }\n | { kind: 'highlight'; anchor: string; note?: string }\n | { kind: 'clear_highlight' };\n\n/**\n * Publish a batch of stage directions. Resolves true when the API accepted them.\n *\n * Never throws: a transport failure, a closed chat, or a workspace that has\n * moved on all mean \"nobody is watching\", and the caller's work is not made\n * better by an exception.\n */\nasync function publish(events: UiEvent[], env: SandboxEnv): Promise<boolean> {\n // No chat means no surface to drive — a script run from the CLI, or a\n // detached job. Not an error; there is simply nobody to talk to.\n if (!env.chatId) return false;\n // The audited fetch, not the global one: it carries the chat / session /\n // tool-call attribution headers the broker and API expect, so these calls\n // are traceable to the same exec as every other call the script makes.\n const sandboxFetch = createSandboxFetch({\n chatId: env.chatId,\n sessionId: env.sessionId,\n toolCallId: env.toolCallId,\n });\n try {\n const response = await sandboxFetch(\n `${env.brokerUrl}/api/v2/w/${env.workspaceUuid}/chats/${env.chatId}/ui-events`,\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ events }),\n }\n );\n return response.ok;\n } catch {\n return false;\n }\n}\n\n/**\n * Validate one beat's line.\n *\n * The message names the *beat*, not a function: four entry points build a\n * narration spec (`ui.say`, `ui.point`, `Flow.say`, `Flow.point`), and an error\n * reading `ui.say:` sent an author who wrote `flow.point` looking for a call\n * they had not made.\n */\nfunction requireText(text: string): string {\n const trimmed = (text ?? '').trim();\n if (!trimmed) throw new Error('beat text cannot be empty');\n if (trimmed.length > MAX_SAY_CHARS) {\n throw new Error(\n `beat text is ${trimmed.length} characters (max ${MAX_SAY_CHARS}). ` +\n 'Break it into steps the user can interrupt between.'\n );\n }\n return trimmed;\n}\n\n/**\n * The ask spec for one narration beat.\n *\n * `narration: true` is what lets a surface advance this hands-free. A beat has\n * one answer, so a timer that presses it is doing what the user would have\n * done; a real question has several, and a timer that picked one would be\n * answering *for* them. That difference has to be legible to the client, and\n * the shape of the markup is the wrong place to infer it from.\n *\n * The field carries an empty label deliberately: the line is already the\n * heading, and a label above a lone button would draw the question twice.\n */\nexport function sayAskSpec(text: string, options: SayOptions = {}): AskSpec {\n return {\n title: requireText(text),\n narration: true,\n fields: [\n {\n name: SAY_FIELD,\n label: '',\n type: 'select',\n choices: [{ value: 'continue', label: options.continueLabel ?? 'Continue' }],\n },\n ],\n };\n}\n\n/**\n * Say one thing, and wait for the user to take it in.\n *\n * ```ts\n * await ui.say(\"I'll set up your intake line first — it's the one that pays off today.\");\n * ```\n *\n * Resolves when they advance. A decline — Skip, or answering in prose — comes\n * back as `rejected`, and a script should stop on it rather than carrying on\n * talking. `Flow.say` does that for you.\n */\nexport async function say(\n text: string,\n options: SayOptions = {},\n env?: SandboxEnv\n): Promise<AskAnswer> {\n return ask(sayAskSpec(text, options), env);\n}\n\n/**\n * Take the user to a page, named by the same `app:page:` URI the Manager's\n * navigation tool uses. Unknown URIs are rejected by the API rather than\n * silently ignored, so a typo fails loudly in development.\n *\n * ```ts\n * await ui.navigate('app:page:workflows');\n * ```\n */\nexport async function navigate(\n appUri: string,\n env: SandboxEnv = readSandboxEnv()\n): Promise<boolean> {\n if (!appUri?.trim()) throw new Error('ui.navigate: appUri cannot be empty');\n return publish([{ kind: 'navigate', appUri: appUri.trim() }], env);\n}\n\n/**\n * Point at something on screen by its anchor id — never a CSS selector. Anchors\n * are declared by the components themselves and checked by a lint, so a\n * renamed class cannot silently break a tour in front of a customer.\n *\n * ```ts\n * await ui.highlight('workflows.create-button', { note: 'Start here.' });\n * ```\n */\nexport async function highlight(\n anchor: string,\n options: HighlightOptions = {},\n env: SandboxEnv = readSandboxEnv()\n): Promise<boolean> {\n if (!anchor?.trim()) throw new Error('ui.highlight: anchor cannot be empty');\n return publish([{ kind: 'highlight', anchor: anchor.trim(), note: options.note }], env);\n}\n\n/** Drop any active highlight. Clearing nothing is not an error. */\nexport async function clearHighlight(env: SandboxEnv = readSandboxEnv()): Promise<boolean> {\n return publish([{ kind: 'clear_highlight' }], env);\n}\n\n/**\n * Point at something and say what it is, as one beat.\n *\n * The highlight goes up *first* and does not block, so the spotlight is\n * already on the control when the line asking the user to look at it appears.\n * Doing it the other way round — narrating, then lighting up once they\n * advance — points at something they have already finished reading about.\n */\nexport async function point(\n text: string,\n anchor: string,\n options: HighlightOptions & SayOptions = {},\n env: SandboxEnv = readSandboxEnv()\n): Promise<AskAnswer> {\n if (!anchor?.trim()) throw new Error('ui.point: anchor cannot be empty');\n // Built before the highlight is published so an over-long line fails\n // without leaving a spotlight burned onto the page with no beat to explain\n // it.\n const spec = sayAskSpec(text, options);\n await publish([{ kind: 'highlight', anchor: anchor.trim(), note: options.note }], env);\n return ask(spec, env);\n}\n\n/**\n * Ask the operator to fill in a form, and wait for the answer.\n *\n * Re-exported here so one import covers the whole surface rather than\n * splitting it between a namespace and a free function.\n *\n * Always branch on `answer.status`; see `askUser` for why.\n */\nexport async function ask(spec: AskSpec, env?: SandboxEnv): Promise<AskAnswer> {\n return env ? askUser(spec, env) : askUser(spec);\n}\n\nexport const ui = { say, navigate, highlight, clearHighlight, point, ask } as const;\n","/**\n * Flows: parameterised, re-enterable scripts the manager can steer.\n *\n * A flow is an ordinary linear script — `for` loops, local variables, normal\n * control flow — that happens to keep its answers somewhere durable and knows\n * how to be started again. Onboarding is one. A tour is one. So is any workflow\n * app a customer builds. There is no separate \"kind\" of script for any of them:\n * the same shape, differing only in what its steps do and who its state belongs\n * to.\n *\n * ## The re-entry contract\n *\n * A user facing one of this flow's beats — a question, or just a line of\n * narration — can always decline it, optionally saying why (\"this isn't right,\n * I meant medical education, not school\"). That ends the script — it does NOT\n * sit parked while the user and the model talk. On the way out the runtime\n * prints an instruction telling the model how to start the flow again, and\n * where the answers live.\n *\n * A flow that runs to the END prints no such instruction — \"here is how to\n * continue\" after a completed tour reads as though it stopped half way. It\n * prints a completion report instead, which has a harder job: saying whether\n * this run did anything at all. A flow that skips every step it has already\n * done reaches the end instantly and is, from inside the body, indistinguishable\n * from a full run, so the report is the only thing that can tell a first\n * completion from a no-op — and it always offers the way back, because\n * \"complete\" is never the whole story for something a person can want again.\n *\n * The model can then do one of three things, and the state file is what makes\n * all three possible:\n *\n * 1. re-run unchanged — the user just wanted to ask something;\n * 2. edit the state file and re-run — the user corrected an answer;\n * 3. start a DIFFERENT flow, writing that flow's own state file — the user\n * wanted something else entirely.\n *\n * This is why state must be semantic. A program counter would let us resume but\n * not be revised; `vertical: 'school-education'` is a thing a model can read,\n * disagree with, and rewrite. The constraint is the feature.\n *\n * ## Re-running means re-running\n *\n * There is no magic resumption. Re-entry starts the script from the top with\n * the previous answers already in hand, and it is the script's job to skip what\n * its state says is done — `if (!flow.state.vertical) { ...ask... }`. That is\n * also why a flow must not rebuild what it already built: record a decision in\n * state immediately after acting on it, not at the end, or a rejection between\n * the two will redo the work on the next run.\n */\nimport { readSandboxEnv, type SandboxEnv } from './env';\nimport { sayAskSpec, ui, type HighlightOptions, type SayOptions } from './ui';\nimport type { AskSpec } from './ask-user';\n\n/** Who a flow's answers belong to. Fixed per script, never a runtime choice. */\nexport type FlowScope = 'member' | 'workspace';\n\n/**\n * Framework-owned half of the state file. The model edits `state`; everything\n * here is written by the runtime and should be left alone.\n */\nexport interface FlowMeta {\n flow: string;\n scope: FlowScope;\n /** ISO timestamp of the last write. */\n updatedAt: string;\n /** Member id that last wrote, when one was available. */\n updatedBy?: number;\n /**\n * Questions this user has declined, most recent last.\n *\n * Recorded so a re-entered flow can tell \"never asked\" from \"asked and\n * refused\". Without it the obvious loop appears: the user declines, the\n * model answers their question, the flow restarts and asks the identical\n * question, and they are exactly where they began.\n */\n rejections: FlowRejection[];\n /**\n * When this flow last ran all the way to the end, if it ever has.\n *\n * The difference between \"finished just now\" and \"finished last week and\n * did nothing this time\" is invisible from inside the body — a flow that\n * skips every step it has already done reaches the end instantly and looks\n * exactly like a successful run. Recording the timestamp is what lets the\n * runtime tell the model which of the two just happened.\n */\n completedAt?: string;\n}\n\nexport interface FlowRejection {\n /** The `title` of the ask that was declined. */\n question: string;\n /** What the user said, when they said anything. */\n reason?: string;\n at: string;\n}\n\ninterface FlowFile<S> {\n _meta: FlowMeta;\n state: S;\n}\n\nexport interface FlowDefinition<S extends object> {\n /**\n * The durable product this flow's initiative belongs to.\n *\n * Projects contain plans (ADR 2026-08-08-16): a Project is the lasting\n * identity, a Plan is one bounded initiative inside it. A flow is a plan, so\n * it needs both halves to know where it lives.\n */\n project: string;\n /** Plan slug. Names the state location, so keep it stable across edits. */\n name: string;\n /**\n * Whether these answers belong to one member or to the workspace.\n *\n * Get this wrong in either direction and it shows up late: workspace answers\n * in member scope get stranded when that person leaves, and member answers\n * in workspace scope mean two people resume into each other's session.\n */\n scope: FlowScope;\n /** Starting answers. Field names are the vocabulary the model revises. */\n initialState: S;\n /**\n * Where answers live. `'file'` is the default whenever state is declared.\n *\n * `'none'` suits a flow with nothing to remember — a short tour — and skips\n * the file entirely rather than leaving an empty one lying around.\n */\n storage?: 'file' | 'none';\n /** Overrides the conventional path. Rarely needed. */\n statePath?: string;\n /**\n * State keys that record how far this flow GOT, rather than what it learned\n * or built.\n *\n * Naming them is what makes a replay safe to hand out. Starting a finished\n * flow over means dropping its progress — but a state file also records\n * things that now EXIST in the workspace (`builtWorkflow`, a created\n * routine id), and dropping those tells the next run to build a second\n * copy. Deleting the whole file is therefore the obvious way to replay a\n * tour and the wrong one.\n *\n * Declare the progress fields and the runtime prints a ready-to-write state\n * that keeps everything else. Leave it undeclared and it prints the same\n * advice in prose, because it cannot know which half is which.\n */\n progressKeys?: readonly (keyof S & string)[];\n}\n\n/** Thrown when the user declines a question. `runFlow` catches it. */\nexport class FlowExit extends Error {\n constructor(\n readonly question: string,\n readonly reason?: string\n ) {\n super(`Flow stopped: ${question}`);\n this.name = 'FlowExit';\n }\n}\n\nexport type FlowAskResult =\n | { status: 'submitted'; values: Record<string, string> }\n | { status: 'rejected'; reason?: string }\n | { status: 'unavailable'; reason: string };\n\nfunction print(message = ''): void {\n process.stdout.write(`${message}\\n`);\n}\n\n/**\n * How much of the state file to print when a flow finishes.\n *\n * Printed at all because the alternative is worse: the model is handed a path,\n * and answering \"what did they pick?\" then costs a second exec to read a file\n * it was just told about. A thousand characters covers every flow we ship with\n * room to spare, and the path is still there when it does not.\n *\n * This is the operator's own answers going back to the model that is helping\n * them — the same audience that could already read the file, so printing it\n * discloses nothing the path did not. It is stdout, not a log; do not route it\n * to one.\n */\nconst MAX_STATE_PREVIEW_CHARS = 1000;\n\nfunction statePreview(state: unknown): string {\n const text = JSON.stringify(state, null, 2) ?? 'null';\n if (text.length <= MAX_STATE_PREVIEW_CHARS) return text;\n return (\n `${text.slice(0, MAX_STATE_PREVIEW_CHARS)}\\n` +\n `… truncated at ${MAX_STATE_PREVIEW_CHARS} characters — read the file for the rest.`\n );\n}\n\n/**\n * The reason a user gave for declining, when they gave one.\n *\n * Read structurally rather than by narrowing the union: a decline carries a\n * reason only when the user typed one, and a dismissal carries none at all.\n * Treating a missing or non-string value as \"no reason given\" keeps this\n * correct for both shapes without the flow layer caring which it got.\n */\nfunction declineReason(answer: object): string | undefined {\n const value = (answer as { reason?: unknown }).reason;\n return typeof value === 'string' && value.trim() ? value.trim() : undefined;\n}\n\n/**\n * Conventional state location.\n *\n * Member-scoped flows partition by member id *inside the shared tree* rather\n * than living in a member's home directory. Two members then never contend for\n * one file — which removes the need for locking entirely — while the workspace\n * keeps the answers when that person leaves.\n */\nfunction defaultStatePath<S extends object>(\n definition: FlowDefinition<S>,\n env: SandboxEnv\n): string {\n // Two levels, per the projects/plans model: the project is the durable\n // product, the plan is this bounded initiative. NOT the older flat\n // `/gr/workspace/plans/<slug>/` layout, which that model supersedes.\n const base = `/gr/workspace/projects/${definition.project}/plans/${definition.name}`;\n if (definition.scope === 'workspace') return `${base}/state.json`;\n // No member id (a CLI or detached run) still needs a stable path; `shared`\n // is honest about what it is rather than pretending to be someone.\n return `${base}/state/member-${env.memberId ?? 'shared'}.json`;\n}\n\n/**\n * The handle a flow body is given.\n *\n * Two audiences, and the split is why `flow-api.md` documents only half the\n * members below. A flow **author** uses `state`, `save`, `say`, `point`, `ask`,\n * `askOptional` and `wasRejected` — that is the whole documented surface. The\n * rest (`statePath`, `load`, `previouslyCompletedAt`, `thisRun`, `markComplete`,\n * `replayState`, `completionReport`, `reentryInstruction`) is what `runFlow`\n * calls around the body, public only because `runFlow` is a free function rather\n * than a method. Teaching them would offer an author a second way to do what\n * `runFlow` already does, which is how a flow ends up printing its own report\n * alongside the runtime's.\n */\nexport class Flow<S extends object> {\n /** The answers so far. Mutate freely; call `save()` when it matters. */\n state: S;\n\n private meta: FlowMeta;\n private readonly path: string | null;\n /**\n * When this flow had last been completed *as this run started*.\n *\n * Captured at load and never updated afterwards, because the whole question\n * it answers — \"did this run actually do anything?\" — stops being answerable\n * the moment `markComplete` stamps a new timestamp.\n */\n private completedBefore?: string;\n /**\n * What this run actually put in front of the person, as it happens.\n *\n * Counted because \"did anything happen?\" is the one question the printed\n * result could not answer, and it is the question that matters most. A flow\n * that skips every step it has already done finishes instantly and looks,\n * from the outside, exactly like a full run — so the model relayed \"your\n * tour is complete\" to someone who had just asked to be shown around and\n * had been shown nothing.\n */\n private readonly activity = { narrated: 0, asked: 0, answered: 0, declined: 0 };\n\n constructor(\n private readonly definition: FlowDefinition<S>,\n private readonly env: SandboxEnv\n ) {\n this.state = { ...definition.initialState };\n this.meta = {\n flow: `${definition.project}/${definition.name}`,\n scope: definition.scope,\n updatedAt: new Date().toISOString(),\n ...(env.memberId !== undefined ? { updatedBy: env.memberId } : {}),\n rejections: [],\n };\n this.path =\n definition.storage === 'none'\n ? null\n : (definition.statePath ?? defaultStatePath(definition, env));\n }\n\n /** Where this flow's answers live, or null when it stores none. */\n get statePath(): string | null {\n return this.path;\n }\n\n /**\n * Load previous answers, if any. Missing or unreadable state is not an\n * error — it means a first run, which is the common case.\n *\n * Warns (never refuses) when someone else wrote last. A hard lock would need\n * releasing on exit, and a process that dies in between leaves the flow\n * claimed forever with `--force` as the only way out — which trains everyone\n * to pass `--force`. A warning costs nothing and hands the decision to the\n * model, which can ask whether to continue that person's work or start over.\n */\n async load(): Promise<void> {\n if (!this.path) return;\n let parsed: FlowFile<S> | null = null;\n try {\n const { readFile } = await import('node:fs/promises');\n parsed = JSON.parse(await readFile(this.path, 'utf8')) as FlowFile<S>;\n } catch {\n return;\n }\n if (!parsed || typeof parsed !== 'object' || !parsed.state) return;\n\n this.state = { ...this.definition.initialState, ...parsed.state };\n if (parsed._meta) {\n this.completedBefore =\n typeof parsed._meta.completedAt === 'string' ? parsed._meta.completedAt : undefined;\n this.meta = {\n ...this.meta,\n rejections: Array.isArray(parsed._meta.rejections) ? parsed._meta.rejections : [],\n ...(this.completedBefore ? { completedAt: this.completedBefore } : {}),\n };\n const previous = parsed._meta.updatedBy;\n if (previous !== undefined && previous !== this.env.memberId) {\n print(\n `Note: these answers were last updated by member ${previous} at ` +\n `${parsed._meta.updatedAt}. Continuing from where they left off.`\n );\n }\n }\n }\n\n /**\n * Persist the answers.\n *\n * Call this immediately after acting on a decision, not at the end: a\n * rejection between the write and the record is what makes a re-entered\n * flow rebuild something it already built.\n */\n async save(): Promise<void> {\n if (!this.path) return;\n this.meta = {\n ...this.meta,\n updatedAt: new Date().toISOString(),\n ...(this.env.memberId !== undefined ? { updatedBy: this.env.memberId } : {}),\n };\n const payload: FlowFile<S> = { _meta: this.meta, state: this.state };\n try {\n const { mkdir, writeFile } = await import('node:fs/promises');\n // A path with no separator has no parent to create. `lastIndexOf`\n // returns -1 there, and slicing to -1 would drop the last character\n // and hand `mkdir` a *sibling* directory name — creating the wrong\n // directory and then writing beside it.\n const separator = this.path.lastIndexOf('/');\n if (separator > 0) await mkdir(this.path.slice(0, separator), { recursive: true });\n await writeFile(this.path, `${JSON.stringify(payload, null, 2)}\\n`, 'utf8');\n } catch (error) {\n // Never fatal. Losing the ability to resume is worse than losing this\n // run's progress, but neither is worth abandoning work already done.\n print(\n `Warning: could not save answers to ${this.path} ` +\n `(${error instanceof Error ? error.name : 'unknown error'}). ` +\n 'This run will finish; resuming later may start over.'\n );\n }\n }\n\n /**\n * Ask a question, and stop the flow if the user declines.\n *\n * The ergonomic default: a script reads as a straight line, and a rejection\n * unwinds to `runFlow` without every call site testing for it. Use\n * {@link askOptional} where declining should be handled rather than fatal.\n */\n async ask(spec: AskSpec): Promise<Record<string, string>> {\n const answer = await this.askOptional(spec);\n if (answer.status === 'submitted') return answer.values;\n throw new FlowExit(spec.title, answer.status === 'rejected' ? answer.reason : undefined);\n }\n\n /**\n * Say one line and wait for the user to take it in. Declining stops the flow.\n *\n * The narration counterpart of {@link ask}, and the one a tour is written\n * out of. Declining a *line* is the user saying \"not this, talk to me\" —\n * which is the same thing declining a question means, so it ends the run\n * the same way and the reason reaches the model through the same\n * re-entry instruction.\n */\n async say(text: string, options: SayOptions = {}): Promise<void> {\n await this.ask(sayAskSpec(text, options));\n }\n\n /**\n * Point at something and say what it is. Declining stops the flow.\n *\n * The highlight is published before the line parks, so the spotlight is up\n * while the user reads about it — see `ui.point`.\n */\n async point(text: string, anchor: string, options: HighlightOptions & SayOptions = {}) {\n const spec = sayAskSpec(text, options);\n await ui.highlight(anchor, options, this.env);\n await this.ask(spec);\n }\n\n /**\n * Ask a question and hand back what happened, including a decline.\n *\n * A rejection is still recorded in state, so a flow that carries on after\n * one does not re-ask the same thing on the next run.\n */\n async askOptional(spec: AskSpec): Promise<FlowAskResult> {\n // Forward this Flow's env: it was handed one for `memberId` and state\n // paths, and letting the prompt channel fall back to the ambient\n // `readSandboxEnv()` means the two can disagree about which chat is being\n // asked. Harmless in production, where both resolve the same, and exactly\n // the kind of split a test has to work around rather than exercise.\n // Counted here rather than at each call site: `say`, `point` and `ask`\n // all funnel through this one method, so this is the only place that\n // sees every beat exactly once.\n if (spec.narration) this.activity.narrated += 1;\n else this.activity.asked += 1;\n\n const answer = await ui.ask(spec, this.env);\n if (answer.status === 'submitted') {\n this.activity.answered += 1;\n return { status: 'submitted', values: answer.values };\n }\n if (answer.status === 'unavailable') {\n return { status: 'unavailable', reason: answer.reason };\n }\n const reason = declineReason(answer);\n this.activity.declined += 1;\n this.meta.rejections.push({\n question: spec.title,\n ...(reason ? { reason } : {}),\n at: new Date().toISOString(),\n });\n await this.save();\n return { status: 'rejected', ...(reason ? { reason } : {}) };\n }\n\n /** True when this exact question has already been declined. */\n wasRejected(question: string): boolean {\n return this.meta.rejections.some((entry) => entry.question === question);\n }\n\n /** When this flow was last completed before this run, if it ever was. */\n get previouslyCompletedAt(): string | undefined {\n return this.completedBefore;\n }\n\n /** What this run put in front of the person. Zero of everything is the tell. */\n get thisRun(): Readonly<{\n narrated: number;\n asked: number;\n answered: number;\n declined: number;\n }> {\n return this.activity;\n }\n\n /** One line naming what actually happened, in the plainest terms available. */\n private activityLine(): string {\n const { narrated, asked, answered, declined } = this.activity;\n if (narrated + asked === 0) {\n return 'This run put nothing in front of them — no narration, no questions.';\n }\n const parts: string[] = [];\n if (narrated) parts.push(`${narrated} line${narrated === 1 ? '' : 's'} narrated`);\n if (asked) parts.push(`${asked} question${asked === 1 ? '' : 's'} asked`);\n if (answered) parts.push(`${answered} answered`);\n if (declined) parts.push(`${declined} declined`);\n return `This run: ${parts.join(', ')}.`;\n }\n\n /** Record that the body reached the end. `runFlow` calls this. */\n markComplete(): void {\n this.meta = { ...this.meta, completedAt: new Date().toISOString() };\n }\n\n /**\n * The state to write in order to run this flow again for real.\n *\n * Progress dropped, everything else kept — see `progressKeys` for why the\n * distinction is the flow author's to make and why getting it wrong builds\n * a second copy of whatever the first run created.\n */\n replayState(): Partial<S> {\n const progress = new Set<string>(this.definition.progressKeys ?? []);\n const kept: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(this.state)) {\n if (!progress.has(key)) kept[key] = value;\n }\n return kept as Partial<S>;\n }\n\n /**\n * What the model reads when this flow reaches the end.\n *\n * It always offers the way back. \"Complete\" is never the whole story for a\n * flow a person can want again — a tour especially — and a report that only\n * says \"finished\" invites the model to tell someone who just asked to be\n * shown around that they have already seen it.\n */\n completionReport(scriptPath: string, resumeArgs: string[] = []): string {\n const command = [`node ${scriptPath}`, ...resumeArgs].join(' ');\n if (!this.path) {\n return `This flow keeps no saved answers, so running it again starts from the beginning:\\n ${command}`;\n }\n\n const progressKeys = this.definition.progressKeys ?? [];\n const lines = [this.activityLine(), '', `Their answers are in ${this.path}:`];\n lines.push(statePreview(this.state));\n lines.push('');\n\n // Both halves matter. A flow that asked nothing because it had nothing\n // left to ask is the bug this report exists for; a flow that asks nothing\n // *by design* — a build script with no audience — is ordinary, and\n // telling its author it \"exited immediately\" would be a lie.\n if (this.activity.narrated + this.activity.asked === 0 && this.completedBefore) {\n lines.push(\n 'It exited immediately because the state above already answers every ' +\n 'step. Running it again unchanged will do the same thing.'\n );\n } else {\n lines.push('Running it again as-is will skip everything the state above records.');\n }\n\n lines.push(`To replay, remove the relevant state and re-run: ${command}`);\n if (progressKeys.length) {\n lines.push(` • the whole flow — write: ${JSON.stringify({ state: this.replayState() })}`);\n lines.push(\n ` • one step — drop just that entry from ${progressKeys\n .map((key) => `\\`${key}\\``)\n .join(' / ')}, leaving the rest`\n );\n lines.push(\n 'Keep every other field. They name things that already exist, and ' +\n 'dropping them is what makes a replay build a second copy — which ' +\n 'is why deleting the whole file is the wrong way to start over.'\n );\n } else {\n lines.push(\n ' Drop the fields recording how far they got, and KEEP any that name ' +\n 'something already created — deleting the whole file is the obvious ' +\n 'way to replay a flow and the one that builds a second copy.'\n );\n }\n return lines.join('\\n');\n }\n\n /**\n * The instruction the model reads to start this flow again.\n *\n * Generated here rather than written by each script on purpose: a\n * hand-authored block goes stale the moment someone renames a parameter, and\n * every flow phrasing it differently means the model learns N patterns\n * instead of one.\n */\n reentryInstruction(scriptPath: string, exit?: FlowExit, resumeArgs: string[] = []): string {\n const lines: string[] = [];\n const command = [`node ${scriptPath}`, ...resumeArgs].join(' ');\n if (exit) {\n lines.push(\n exit.reason\n ? `The user declined \"${exit.question}\" and said: ${exit.reason}`\n : `The user declined \"${exit.question}\" without giving a reason.`\n );\n lines.push('');\n }\n lines.push(`To continue this flow, run: ${command}`);\n if (this.path) {\n lines.push(`Their answers so far are in ${this.path}`);\n lines.push(\n 'If any of those answers should change, edit that file first — the flow ' +\n 'picks up from whatever it says. Re-running WITHOUT changing anything ' +\n 'will ask the same question again.'\n );\n lines.push(\n 'If a different flow suits them better, start that one instead and write ' +\n 'ITS OWN state file rather than reusing this path — answers about the ' +\n 'workspace usually carry across; progress through this flow does not.'\n );\n } else {\n lines.push('This flow keeps no saved answers, so it starts from the beginning.');\n }\n return lines.join('\\n');\n }\n}\n\n/**\n * Run a flow: load answers, run the body, print the re-entry instruction.\n *\n * A decline unwinds out of `body` and is handled here — it is an ordinary\n * ending, not a failure, so the process exits 0. The instruction goes to stdout\n * because stdout is what the model reads back from an exec.\n */\nexport async function runFlow<S extends object>(\n definition: FlowDefinition<S>,\n body: (flow: Flow<S>) => Promise<void>,\n options: { scriptPath?: string; env?: SandboxEnv; resumeArgs?: string[] } = {}\n): Promise<void> {\n const env = options.env ?? readSandboxEnv();\n const scriptPath = options.scriptPath ?? process.argv[1] ?? `<${definition.name}>`;\n // Arguments the printed command must carry to resume faithfully. Not every\n // parameter belongs in state: a per-run choice like `--write` is a decision\n // about THIS invocation, and a re-entry instruction that silently drops it\n // tells the model to run a command that previews instead of building, then\n // reports \"nothing to do\". A flow declares what must survive; the runtime\n // prints it.\n const resumeArgs = options.resumeArgs ?? [];\n const flow = new Flow(definition, env);\n\n await flow.load();\n\n // Read before the body runs: reaching the end stamps a fresh timestamp, and\n // this is the only thing that can distinguish the two ways of getting there.\n const completedBefore = flow.previouslyCompletedAt;\n\n try {\n await body(flow);\n flow.markComplete();\n await flow.save();\n } catch (error) {\n if (!(error instanceof FlowExit)) throw error;\n await flow.save();\n print('');\n print(flow.reentryInstruction(scriptPath, error, resumeArgs));\n return;\n }\n\n // A finished flow does NOT print the *re-entry* instruction — \"here is how\n // to pick it up\" reads as though it stopped half way. What it prints\n // instead has to answer a question re-entry never had to: whether this run\n // did anything at all.\n //\n // A flow that skips every step it has already done reaches the end\n // instantly, and from the body that is indistinguishable from a full run.\n // Saying \"Finished\" either way is how someone who asked to be shown around\n // gets told they have already seen it — the script did nothing, said it was\n // complete, and the model faithfully passed that on.\n print('');\n if (completedBefore) {\n print(\n `Nothing to do: ${definition.project}/${definition.name} was already ` +\n `completed on ${completedBefore}, and this run changed nothing.`\n );\n } else {\n print(`Finished: ${definition.project}/${definition.name}.`);\n }\n print(flow.completionReport(scriptPath, resumeArgs));\n}\n","/**\n * Audit headers for API calls made from a code-interpreter sandbox.\n *\n * The private-ALB DNS pin that used to live here is gone: it was driven by\n * `GRAVITY_RAIL_API_IP`, which only the sandbox `.gr-env` ever set, and sandbox\n * clients no longer dial the API host at all — every call goes to the loopback\n * credential broker, and the root daemon applies the pin on the far side.\n */\n\nimport { createUnixBrokerFetch } from '@gravity-rail/sandbox';\nexport interface SandboxAuditHeaders {\n chatId?: number;\n sessionId?: string;\n toolCallId?: string;\n}\n\ntype ToolCallGlobal = typeof globalThis & {\n __GRAVITY_RAIL_TOOL_CALL_ID__?: string;\n};\n\ntype WebRequest = Parameters<typeof fetch>[0];\ntype WebRequestInit = Parameters<typeof fetch>[1];\n\nexport function withAuditHeaders(\n fetchFn: typeof fetch,\n headers: SandboxAuditHeaders\n): typeof fetch {\n const { chatId, sessionId, toolCallId } = headers;\n\n return async (input: WebRequest, init?: WebRequestInit): Promise<Response> => {\n const reqHeaders = new Headers(init?.headers);\n const dynamicToolCallId =\n (globalThis as ToolCallGlobal).__GRAVITY_RAIL_TOOL_CALL_ID__ ||\n (typeof process !== 'undefined' ? process.env.GRAVITY_RAIL_TOOL_CALL_ID : undefined);\n if (chatId !== undefined) {\n reqHeaders.set('X-GR-Chat-Id', String(chatId));\n }\n if (sessionId) {\n reqHeaders.set('X-GR-Session-Id', sessionId);\n }\n if (dynamicToolCallId || toolCallId) {\n reqHeaders.set('X-GR-Tool-Call-Id', dynamicToolCallId || toolCallId || '');\n }\n return fetchFn(input, { ...init, headers: reqHeaders });\n };\n}\n\n/**\n * Build fetch for CLI API calls, adding the sandbox correlation headers when\n * the GRAVITY_RAIL_* session vars are present.\n *\n * Outside a sandbox those vars are unset and this is plain `fetch` with a\n * pass-through header copy. Inside one, auth is added by the loopback broker,\n * never here.\n */\nexport function createSandboxFetchFromEnv(): typeof fetch {\n const env: Record<string, string | undefined> =\n typeof process !== 'undefined' ? process.env : {};\n const chatIdRaw = env.GRAVITY_RAIL_CHAT_ID;\n const chatId = chatIdRaw ? Number(chatIdRaw) : undefined;\n return withAuditHeaders(\n env.GRAVITY_RAIL_BROKER_SOCKET\n ? createUnixBrokerFetch(env.GRAVITY_RAIL_BROKER_SOCKET)\n : fetch,\n {\n chatId: chatId !== undefined && Number.isFinite(chatId) ? chatId : undefined,\n sessionId: env.GRAVITY_RAIL_SESSION_ID,\n toolCallId: env.GRAVITY_RAIL_TOOL_CALL_ID,\n }\n );\n}\n","/**\n * Where a hand-built API request goes, and with what credentials.\n *\n * Commands that call the SDK client (`requireAuth(ctx).apiClient`) already get\n * this right. A command that builds its own URL — raw `fetch`, the AG-UI\n * stream, a second SDK class — must take all three parts from here, because\n * the two environments differ in every one of them:\n *\n * | | standalone CLI | code-interpreter sandbox |\n * |---|---|---|\n * | base URL | the environment's API URL | the loopback credential broker |\n * | Authorization | `Bearer <token>` | none: the broker holds the token and adds it |\n * | fetch | global `fetch` | the broker fetch (unix socket when configured) |\n *\n * In the sandbox the context's `accessToken` is the empty string\n * (`tryBrokerContext`), so a request sent to the API URL with\n * `Bearer ${ctx.accessToken}` is a 401.\n */\nimport { sandboxBrokerUrl } from './context';\nimport { createSandboxFetchFromEnv } from './sandbox-fetch';\n\ninterface TransportContext {\n envConfig: { apiUrl: string };\n accessToken?: string;\n}\n\n/** The origin every `/api/v2/...` path is appended to. */\nexport function apiBaseUrl(ctx: TransportContext): string {\n return sandboxBrokerUrl() ?? ctx.envConfig.apiUrl;\n}\n\n/** The Authorization header to send: none through the broker, or with no token. */\nexport function apiAuthHeaders(accessToken: string | undefined): Record<string, string> {\n if (sandboxBrokerUrl() || !accessToken) return {};\n return { Authorization: `Bearer ${accessToken}` };\n}\n\n/** The token to hand a second SDK client: none in the sandbox, where the broker adds it. */\nexport function apiAccessToken(ctx: TransportContext): string | undefined {\n return sandboxBrokerUrl() ? undefined : ctx.accessToken || undefined;\n}\n\n/** The fetch to send it with. Resolved per call, so a test double on `global.fetch` is used. */\nexport const apiFetch: typeof fetch = (input, init) => createSandboxFetchFromEnv()(input, init);\n"],"mappings":";AAIA,SAAS,YAAY,cAAc,gBAAgB;AACnD,SAAS,aAAa,mBAAmB,YAAY;AACrD,SAAS,SAAS,MAAM,eAAe;AAehC,IAAM,eAAkD;AAAA,EAC5D,KAAK;AAAA,IACF,QAAQ;AAAA,IACR,aAAa;AAAA,EAChB;AAAA,EACA,MAAM;AAAA,IACH,QAAQ;AAAA,IACR,aAAa;AAAA,EAChB;AAAA,EACA,SAAS;AAAA,IACN,QAAQ;AAAA,IACR,aAAa;AAAA,EAChB;AACH;AAGO,IAAM,oBAAuC;AAAA,EACjD,QAAQ;AAAA,EACR,aAAa;AAChB;AAEO,IAAM,gBAAgB;AACtB,IAAM,gBAAgB;AACtB,IAAM,eAAe,oBAAoB,aAAa,GAAG,aAAa;AAE7E,IAAM,qBAAqB;AAC3B,IAAM,0BAA0B;AAChC,IAAM,wBAAwB;AAC9B,IAAM,oBAAoB;AAC1B,IAAM,eAAe;AAMrB,IAAM,wBAAwB,kBAA6B,aAAa;AAAA,EACrE,QAAQ,MAAM,CAAC;AAAA,EACf,SAAS,CAAC,SAAS,SAAS;AAEzB,YAAQ,KAAK,IAAI;AAAA,EACpB;AAAA,EACA,UAAU,MAAM;AACnB,CAAC;AAED,IAAM,0BAA0B,YAAY,SAAS,qBAAqB;AAkBnE,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC5C,YACG,SACS,cACA,cACV;AACC,UAAM,OAAO;AAHJ;AACA;AAGT,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AA,MACtB;AAAA,IACH;AAAA,EACH;AACH;AAMA,SAAS,eAAe,IAAY,QAAuC;AACxE,SAAO,IAAI,QAAiB,CAACC,aAAY;AACtC,QAAI,OAAO,SAAS;AACjB,MAAAA,SAAQ,KAAK;AACb;AAAA,IACH;AACA,UAAM,UAAU,MAAY;AACzB,mBAAa,KAAK;AAClB,MAAAA,SAAQ,KAAK;AAAA,IAChB;AACA,UAAM,QAAQ,WAAW,MAAM;AAC5B,aAAO,oBAAoB,SAAS,OAAO;AAC3C,MAAAA,SAAQ,IAAI;AAAA,IACf,GAAG,EAAE;AACL,WAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;AAAA,EAC3D,CAAC;AACJ;AAmBO,SAAS,mBAAmB,OAA2B;AAC3D,QAAM,OAAO,MAAM,KAAK,YAAY;AACpC,SAAO,SAAS;AACnB;AAKO,SAAS,aAAa,OAA2B;AACrD,QAAM,OAAO,MAAM,KAAK,YAAY;AACpC,SAAO,SAAS;AACnB;AAKO,SAAS,aAAa,OAAiC;AAC3D,MAAI,mBAAmB,KAAK,KAAK,MAAM,OAAO;AAC3C,WAAO,MAAM;AAAA,EAChB;AACA,SAAO;AACV;AAKO,SAAS,gBAAgB,OAAiC;AAC9D,MAAI,aAAa,KAAK,GAAG;AACtB,WAAO,MAAM,WAAW,MAAM,QAAQ;AAAA,EACzC;AACA,SAAO;AACV;","names":["existsSync","mkdirSync","dirname","readFileSync","existsSync","join","resolve","join","resolve","existsSync","readFileSync","resolve","dirname","existsSync","mkdirSync","resolve","GravityRailClient","stderr","resolve","createServer","createHash","randomBytes","openBrowser","resolve","createServer","randomBytes","createHash","stderr","session","writeFileSync","join","GravityRailClient","WorkspaceBuilder","runWorkspaceScript","resolve","GravityRailClient","resolve"]}
|