@odla-ai/cli 0.11.2 → 0.12.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/README.md +6 -1
- package/dist/bin.cjs +566 -332
- package/dist/bin.cjs.map +1 -1
- package/dist/bin.js +3 -2
- package/dist/bin.js.map +1 -1
- package/dist/{chunk-DC4MIB4X.js → chunk-Y4HWUEFF.js} +488 -256
- package/dist/chunk-Y4HWUEFF.js.map +1 -0
- package/dist/index.cjs +569 -335
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +50 -51
- package/dist/index.d.ts +50 -51
- package/dist/index.js +5 -5
- package/package.json +1 -1
- package/skills/odla/SKILL.md +18 -10
- package/skills/odla/references/build.md +17 -14
- package/skills/odla/references/sdks.md +29 -17
- package/skills/odla-migrate/SKILL.md +8 -6
- package/skills/odla-migrate/references/phase-2b-calendar.md +130 -42
- package/skills/odla-migrate/references/secrets-map.md +3 -0
- package/skills/odla-migrate/references/troubleshooting.md +16 -5
- package/dist/chunk-DC4MIB4X.js.map +0 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../../../node_modules/tsup/assets/cjs_shims.js","../src/admin-ai.ts","../src/token.ts","../src/open.ts","../src/local.ts","../src/secret-input.ts","../src/admin-ai-auth.ts","../src/admin-ai-audit.ts","../src/admin-ai-policy.ts","../src/admin-ai-usage.ts","../src/argv.ts","../src/admin-command.ts","../src/capabilities.ts","../src/config.ts","../src/calendar-errors.ts","../src/redact.ts","../src/calendar-http.ts","../src/calendar-poll.ts","../src/calendar.ts","../src/doctor-checks.ts","../src/wrangler.ts","../src/doctor.ts","../src/help.ts","../src/harness-options.ts","../src/init.ts","../src/provision.ts","../src/provision-credentials.ts","../src/secrets.ts","../src/secrets-set.ts","../src/security-command-context.ts","../src/security-command-output.ts","../src/security-run-command.ts","../src/security.ts","../src/security-hosted-github.ts","../src/security-hosted-request.ts","../src/security-hosted-intent.ts","../src/security-hosted-jobs.ts","../src/security-command.ts","../src/skill.ts","../src/skill-adapters.ts","../src/smoke.ts","../src/cli.ts"],"sourcesContent":["export { runCli } from \"./cli\";\nexport type { CliDependencies } from \"./cli\";\nexport { adminAi, getScopedPlatformToken, SYSTEM_AI_PURPOSES } from \"./admin-ai\";\nexport type { AdminAiOptions, ScopedPlatformTokenOptions, SystemAiPurpose } from \"./admin-ai\";\nexport { CAPABILITIES, printCapabilities } from \"./capabilities\";\nexport { calendarCalendars, calendarConnect, calendarDisconnect, calendarResync, calendarStatus } from \"./calendar\";\nexport type { CalendarLifecycleOptions } from \"./calendar\";\nexport { GOOGLE_CALENDAR_READ_SCOPE, calendarBookingPageUrl, calendarServiceConfig } from \"./config\";\nexport type { AvailableGoogleCalendar, CalendarConnectionState, CalendarStatus } from \"./calendar-http\";\nexport { doctor } from \"./doctor\";\nexport { initProject } from \"./init\";\nexport { provision } from \"./provision\";\nexport { redactSecrets } from \"./redact\";\nexport { secretsPush } from \"./secrets\";\nexport type { SecretsPushOptions } from \"./secrets\";\nexport { secretsSet, secretsSetClerkKey } from \"./secrets-set\";\nexport type { SecretsSetOptions } from \"./secrets-set\";\nexport { runHostedSecurity } from \"./security\";\nexport type { HostedSecurityProfile, HostedSecurityResult, HostedSecurityTokenRequest, RunHostedSecurityOptions } from \"./security\";\nexport {\n connectGitHubSecuritySource,\n disconnectGitHubSecuritySource,\n followHostedSecurityJob,\n getHostedSecurityJob,\n getHostedSecurityIntent,\n getHostedSecurityPlan,\n getHostedSecurityReport,\n inferGitHubRepository,\n isTerminalHostedSecurityStatus,\n listGitHubSecuritySources,\n listHostedSecurityJobs,\n repositoryFromGitRemote,\n startHostedSecurityJob,\n} from \"./security-hosted\";\nexport type {\n ConnectGitHubSecuritySourceOptions,\n DisconnectGitHubSecuritySourceOptions,\n FollowHostedSecurityJobOptions,\n GetHostedSecurityJobOptions,\n GetHostedSecurityIntentOptions,\n GitHubConnectionAttempt,\n GitHubConnectionStatus,\n GitHubSecuritySource,\n HostedSecurityCounts,\n HostedSecurityCoverage,\n HostedSecurityJob,\n HostedSecurityJobStatus,\n HostedSecurityIntent,\n HostedSecurityIntentResponse,\n HostedSecurityPlan,\n HostedSecurityPlanRoute,\n HostedSecurityReport,\n HostedSecurityReportFinding,\n HostedSecurityRoute,\n ListGitHubSecuritySourcesOptions,\n ListHostedSecurityJobsOptions,\n StartHostedSecurityJobOptions,\n} from \"./security-hosted\";\nexport { AGENT_HARNESSES, installSkill } from \"./skill\";\nexport type { AgentHarness, AgentHarnessSelector, HarnessInstallResult, SkillInstallOptions, SkillInstallResult } from \"./skill\";\nexport { smoke } from \"./smoke\";\nexport type {\n CalendarConfig,\n CalendarServiceConfig,\n GoogleCalendarConfig,\n GoogleCalendarMatchConfig,\n OdlaProjectConfig,\n LoadedProjectConfig,\n LocalCredentials,\n ProvisionOptions,\n ProvisionPlan,\n SmokeOptions,\n} from \"./types\";\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","import process from \"node:process\";\nimport { platformAudience } from \"./token\";\nimport { secretInputValue } from \"./secret-input\";\nimport { resolveAdminPlatformToken, type ScopedPlatformScope } from \"./admin-ai-auth\";\nimport { adminAiAuditQuery, readAdminAiAudit } from \"./admin-ai-audit\";\nimport { requireSystemAiPurpose } from \"./admin-ai-policy\";\nimport { adminAiUsageQuery, readAdminAiUsage } from \"./admin-ai-usage\";\nexport { getScopedPlatformToken } from \"./admin-ai-auth\";\nexport type { ScopedPlatformTokenOptions } from \"./admin-ai-auth\";\nexport { SYSTEM_AI_PURPOSES } from \"./admin-ai-policy\";\nexport type { SystemAiPurpose } from \"./admin-ai-policy\";\n\n/** Inputs for one System AI policy/catalog read, policy update,\n * credential-status read, write-only credential transfer, or metadata-only\n * usage or admin-audit read. Provider values may come only from a named environment variable\n * or stdin. */\nexport interface AdminAiOptions {\n action: \"show\" | \"models\" | \"set\" | \"credentials\" | \"credential-set\" | \"usage\" | \"audit\";\n purpose?: string;\n provider?: string;\n model?: string;\n enabled?: boolean;\n maxInputBytes?: number;\n maxOutputTokens?: number;\n maxCallsPerRun?: number;\n platform?: string;\n token?: string;\n /** Existing odla account email used only when a fresh handshake is required. */\n email?: string;\n json?: boolean;\n open?: boolean;\n fetch?: typeof fetch;\n stdout?: Pick<typeof console, \"log\">;\n openApprovalUrl?: (url: string) => Promise<void>;\n credentialProvider?: string;\n fromEnv?: string;\n stdin?: boolean;\n readStdin?: () => Promise<string>;\n discoveryProvider?: string;\n discoveryModel?: string;\n validationProvider?: string;\n validationModel?: string;\n /** Optional metadata-only usage filters. */\n appId?: string;\n env?: string;\n runId?: string;\n limit?: number;\n /** Separate short-lived admin-token cache; never reuses the app developer-token file. */\n tokenFile?: string;\n}\n\n/** Read or update platform-funded AI routing and inspect attributed usage.\n * Authentication is a short-lived,\n * explicitly scoped device grant; ordinary app developer tokens never become\n * platform admins. Credential writes accept values only from a named env var\n * or stdin, transfer them once, and never place them in argv, output, or the\n * scoped-token cache. */\nexport async function adminAi(options: AdminAiOptions): Promise<void> {\n const platform = platformAudience(options.platform ?? process.env.ODLA_PLATFORM ?? \"https://odla.ai\");\n const doFetch = options.fetch ?? fetch;\n const out = options.stdout ?? console;\n const usageQuery = options.action === \"usage\" ? adminAiUsageQuery(options) : undefined;\n const auditQuery = options.action === \"audit\" ? adminAiAuditQuery(options) : undefined;\n const scope: ScopedPlatformScope = options.action === \"set\"\n ? \"platform:ai:policy:write\"\n : options.action === \"credential-set\"\n ? \"platform:ai:credential:write\"\n : options.action === \"credentials\"\n ? \"platform:ai:credential:read\"\n : options.action === \"usage\"\n ? \"platform:ai:usage:read\"\n : options.action === \"audit\"\n ? \"platform:ai:audit:read\"\n : \"platform:ai:policy:read\";\n const token = await resolveAdminPlatformToken({\n platform,\n scope,\n token: options.token,\n email: options.email,\n open: options.open,\n fetch: doFetch,\n stdout: out,\n openApprovalUrl: options.openApprovalUrl,\n tokenFile: options.tokenFile,\n });\n const headers = { authorization: `Bearer ${token}`, \"content-type\": \"application/json\" };\n\n if (options.action === \"usage\") {\n await readAdminAiUsage({ platform, query: usageQuery ?? \"\", headers, json: options.json, fetch: doFetch, stdout: out });\n return;\n }\n\n if (options.action === \"audit\") {\n await readAdminAiAudit({ platform, query: auditQuery ?? \"\", headers, json: options.json, fetch: doFetch, stdout: out });\n return;\n }\n\n if (options.action === \"credentials\") {\n const res = await doFetch(`${platform}/registry/platform/ai-credentials`, { headers });\n const body = await responseBody(res);\n if (!res.ok) throw new Error(apiError(\"read platform AI credential status\", res.status, body));\n const credentials = isRecord(body) && isRecord(body.credentials) ? body.credentials : body;\n if (options.json) out.log(JSON.stringify({ credentials }, null, 2));\n else for (const [provider, status] of Object.entries(isRecord(credentials) ? credentials : {})) {\n const label = isRecord(status) && status.set === true\n ? status.readable === true ? \"vault readable\" : \"stored; vault unreadable\"\n : \"not set\";\n out.log(`${provider}\\t${label}`);\n }\n return;\n }\n\n if (options.action === \"credential-set\") {\n const provider = requireProvider(options.credentialProvider);\n const value = await secretInputValue(options);\n const res = await doFetch(`${platform}/registry/platform/ai-credentials/${encodeURIComponent(provider)}`, {\n method: \"PUT\",\n headers,\n body: JSON.stringify({ value }),\n });\n const body = await responseBody(res);\n if (!res.ok) throw new Error(apiError(`store ${provider} platform credential`, res.status, body));\n out.log(`stored ${provider} platform credential (write-only; value was not returned)`);\n return;\n }\n\n if (options.action === \"show\" || options.action === \"models\") {\n const res = await doFetch(`${platform}/registry/platform/ai-policies`, { headers });\n const body = await responseBody(res);\n if (!res.ok) throw new Error(apiError(\"read platform AI policies\", res.status, body));\n if (options.action === \"models\") {\n const models = catalogModels(body).filter((model) => !options.provider || model.provider === options.provider);\n if (!models.length) throw new Error(options.provider ? `no System AI models found for provider ${options.provider}` : \"platform returned no System AI models\");\n if (options.json) out.log(JSON.stringify({ models }, null, 2));\n else for (const model of models) out.log(`${model.provider}\\t${model.id}`);\n return;\n }\n const policies = policyArray(body);\n if (options.json) {\n out.log(JSON.stringify({ policies, models: catalogModels(body) }, null, 2));\n return;\n }\n out.log(\"purpose\\tenabled\\tprovider\\tmodel\\tmax calls\\tmax input bytes\\tmax output tokens\");\n for (const policy of policies) {\n out.log([\n policy.purpose,\n String(policy.enabled),\n policy.provider,\n policy.model,\n String(policy.maxCallsPerRun ?? \"\"),\n String(policy.maxInputBytes ?? \"\"),\n String(policy.maxOutputTokens ?? \"\"),\n ].join(\"\\t\"));\n }\n return;\n }\n\n if (options.purpose === \"security\") {\n const currentResponse = await doFetch(`${platform}/registry/platform/ai-policies`, { headers });\n const currentBody = await responseBody(currentResponse);\n if (!currentResponse.ok) throw new Error(apiError(\"read current security AI policies\", currentResponse.status, currentBody));\n const policies = policyArray(currentBody);\n const discovery = policies.find((policy) => policy.purpose === \"security.discovery\");\n const validation = policies.find((policy) => policy.purpose === \"security.validation\");\n if (!discovery || !validation || !Number.isSafeInteger(discovery.version) || !Number.isSafeInteger(validation.version)) {\n throw new Error(\"platform returned invalid security AI policy revisions\");\n }\n const shared = {\n ...(options.enabled === undefined ? {} : { enabled: options.enabled }),\n ...(options.maxInputBytes === undefined ? {} : { maxInputBytes: options.maxInputBytes }),\n ...(options.maxOutputTokens === undefined ? {} : { maxOutputTokens: options.maxOutputTokens }),\n ...(options.maxCallsPerRun === undefined ? {} : { maxCallsPerRun: options.maxCallsPerRun }),\n };\n const discoveryUpdate = {\n ...shared,\n ...(options.discoveryProvider?.trim() ? { provider: options.discoveryProvider.trim() } : {}),\n ...(options.discoveryModel?.trim() ? { model: options.discoveryModel.trim() } : {}),\n };\n const validationUpdate = {\n ...shared,\n ...(options.validationProvider?.trim() ? { provider: options.validationProvider.trim() } : {}),\n ...(options.validationModel?.trim() ? { model: options.validationModel.trim() } : {}),\n };\n if (!Object.keys(discoveryUpdate).length && !Object.keys(validationUpdate).length) {\n throw new Error(\"security set requires a route, enabled state, or budget change\");\n }\n const res = await doFetch(`${platform}/registry/platform/ai-policies/security`, {\n method: \"PUT\",\n headers,\n body: JSON.stringify({\n expectedVersions: { discovery: discovery.version, validation: validation.version },\n discovery: discoveryUpdate,\n validation: validationUpdate,\n }),\n });\n const response = await responseBody(res);\n if (!res.ok) throw new Error(apiError(\"update security review routes\", res.status, response));\n out.log(options.json ? JSON.stringify(response, null, 2) : \"updated security review discovery and independent validation routes atomically\");\n return;\n }\n\n const purpose = requireSystemAiPurpose(options.purpose);\n const body = {\n ...(options.provider?.trim() ? { provider: options.provider.trim() } : {}),\n ...(options.model?.trim() ? { model: options.model.trim() } : {}),\n ...(options.enabled === undefined ? {} : { enabled: options.enabled }),\n ...(options.maxInputBytes === undefined ? {} : { maxInputBytes: options.maxInputBytes }),\n ...(options.maxOutputTokens === undefined ? {} : { maxOutputTokens: options.maxOutputTokens }),\n ...(options.maxCallsPerRun === undefined ? {} : { maxCallsPerRun: options.maxCallsPerRun }),\n };\n if (!Object.keys(body).length) throw new Error(\"set requires a provider, model, enabled state, or budget change\");\n const res = await doFetch(`${platform}/registry/platform/ai-policies/${encodeURIComponent(purpose)}`, {\n method: \"PUT\",\n headers,\n body: JSON.stringify(body),\n });\n const response = await responseBody(res);\n if (!res.ok) throw new Error(apiError(`update ${purpose}`, res.status, response));\n const policy: Record<string, unknown> = isRecord(response) && isRecord(response.policy)\n ? response.policy\n : isRecord(response) ? response : {};\n out.log(options.json ? JSON.stringify({ policy }, null, 2) : `updated ${purpose}: ${String(policy.provider ?? \"unchanged\")}/${String(policy.model ?? \"unchanged\")}`);\n}\n\nfunction requireProvider(value: string | undefined): \"anthropic\" | \"openai\" | \"google\" {\n if (value !== \"anthropic\" && value !== \"openai\" && value !== \"google\") {\n throw new Error(\"provider must be one of: anthropic, openai, google\");\n }\n return value;\n}\n\nfunction policyArray(body: unknown): Array<Record<string, unknown>> {\n if (isRecord(body) && Array.isArray(body.policies)) return body.policies.filter(isRecord);\n if (isRecord(body) && isRecord(body.policies)) return Object.values(body.policies).filter(isRecord);\n throw new Error(\"platform returned an invalid AI policy response\");\n}\n\nfunction catalogModels(body: unknown): Array<{ id: string; provider: string }> {\n if (!isRecord(body) || !isRecord(body.catalog) || !Array.isArray(body.catalog.models)) {\n throw new Error(\"platform returned an invalid System AI model catalog\");\n }\n return body.catalog.models.filter((value): value is { id: string; provider: string } =>\n isRecord(value) && typeof value.id === \"string\" && typeof value.provider === \"string\");\n}\n\nasync function responseBody(res: Response): Promise<unknown> {\n const text = await res.text();\n if (!text) return {};\n try { return JSON.parse(text) as unknown; } catch { return { message: text.slice(0, 300) }; }\n}\n\nfunction apiError(action: string, status: number, body: unknown): string {\n const error = isRecord(body) && isRecord(body.error) ? body.error : undefined;\n const message = error && typeof error.message === \"string\" ? error.message : isRecord(body) && typeof body.message === \"string\" ? body.message : \"request failed\";\n return `${action} failed (${status}): ${message}`;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n","import { requestToken } from \"@odla-ai/db\";\nimport process from \"node:process\";\nimport type { LoadedProjectConfig, ProvisionOptions } from \"./types\";\nimport { openUrl } from \"./open\";\nimport { displayPath, readJsonFile, writePrivateJson } from \"./local\";\n\ntype FetchLike = typeof fetch;\n\n/** Resolve the explicit, audience-bound environment, cached, or freshly\n * human-approved developer credential for a project operation. A new\n * handshake requires `options.email` or `ODLA_USER_EMAIL`; neither is used\n * when a still-valid token is supplied or cached. */\nexport async function getDeveloperToken(\n cfg: LoadedProjectConfig,\n options: ProvisionOptions,\n doFetch: FetchLike,\n out: Pick<typeof console, \"log\" | \"error\">,\n): Promise<string> {\n if (options.token) return options.token;\n const audience = platformAudience(cfg.platformUrl);\n if (process.env.ODLA_DEV_TOKEN) {\n const declared = process.env.ODLA_DEV_TOKEN_AUDIENCE;\n if (declared) {\n if (platformAudience(declared) !== audience) throw new Error(\"ODLA_DEV_TOKEN_AUDIENCE does not match the configured platform\");\n } else if (audience !== \"https://odla.ai\") {\n throw new Error(\"ODLA_DEV_TOKEN_AUDIENCE is required for a non-default platform\");\n }\n return process.env.ODLA_DEV_TOKEN;\n }\n\n const cached = readJsonFile<{ token?: string; expiresAt?: number; platform?: string; email?: string }>(cfg.local.tokenFile);\n if (cached?.token && cached.platform === audience && (cached.expiresAt ?? 0) > Date.now() + 60_000) {\n out.log(`auth: using cached developer token (${displayPath(cfg.local.tokenFile, cfg.rootDir)})`);\n return cached.token;\n }\n\n const browser = approvalBrowser(options);\n const email = handshakeEmail(options.email, cached?.platform === audience ? cached.email : undefined);\n const { token, expiresAt } = await requestToken({\n endpoint: cfg.platformUrl,\n email,\n label: `${cfg.app.id} provisioner`,\n fetch: doFetch,\n onCode: async ({ userCode, expiresIn, verificationUriComplete }) => {\n const approvalUrl = verificationUriComplete ?? handshakeUrl(cfg.platformUrl, userCode);\n out.log(\"\");\n out.log(`Review, then approve code ${userCode} at ${approvalUrl} within ${Math.floor(expiresIn / 60)}m.`);\n if (browser.open) {\n try {\n await (options.openApprovalUrl ?? openUrl)(approvalUrl);\n out.log(`auth: opened browser for approval${browser.mode === \"auto\" ? \" (auto)\" : \"\"}`);\n } catch (err) {\n out.log(`auth: could not open browser (${err instanceof Error ? err.message : String(err)})`);\n }\n } else if (browser.reason) {\n out.log(`auth: browser launch skipped (${browser.reason})`);\n }\n out.log(\"\");\n },\n });\n writePrivateJson(cfg.local.tokenFile, { platform: audience, email, token, expiresAt });\n out.log(`auth: developer token cached (${displayPath(cfg.local.tokenFile, cfg.rootDir)})`);\n return token;\n}\n\n/** Resolve the non-secret account identifier for a fresh handshake: explicit\n * `--email`, then `ODLA_USER_EMAIL`, then the same-audience private cache.\n * Existing tokens bypass this entirely. Agents must never request a password\n * or Clerk token. */\nexport function handshakeEmail(value?: string, cached?: string): string {\n const email = (value ?? process.env.ODLA_USER_EMAIL ?? cached ?? \"\").trim().toLowerCase();\n if (email.length > 254 || !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email)) {\n throw new Error(\"a fresh odla handshake requires --email <account> or ODLA_USER_EMAIL\");\n }\n return email;\n}\n\n/** Host facts consulted when deciding whether a browser can be shown. */\nexport interface BrowserHost {\n platform?: NodeJS.Platform;\n env?: Record<string, string | undefined>;\n}\n\n/** Decide whether to open the signed-in Studio review URL. The gate asks\n * whether this machine can show the user's signed-in browser — not whether\n * stdin is a TTY — so scripted and agent-driven runs still pop the approval\n * page for the human at the keyboard. Launch is skipped only in CI, over SSH,\n * or on a display-less host; `--open` and `--no-open` always win. */\nexport function approvalBrowser(\n options: Pick<ProvisionOptions, \"open\">,\n host: BrowserHost = {},\n): { open: boolean; mode?: \"auto\" | \"forced\"; reason?: string } {\n if (options.open === true) return { open: true, mode: \"forced\" };\n if (options.open === false) return { open: false, reason: \"disabled by --no-open\" };\n const env = host.env ?? process.env;\n if (env.CI) return { open: false, reason: \"CI environment\" };\n if (env.SSH_CONNECTION || env.SSH_TTY) return { open: false, reason: \"SSH session; pass --open to force\" };\n const platform = host.platform ?? process.platform;\n if (platform !== \"darwin\" && platform !== \"win32\" && !env.DISPLAY && !env.WAYLAND_DISPLAY) {\n return { open: false, reason: \"no graphical display; pass --open to force\" };\n }\n return { open: true, mode: \"auto\" };\n}\n\n/** Construct the fallback Studio URL for servers predating verification URIs. */\nexport function handshakeUrl(platformUrl: string, userCode: string): string {\n const url = new URL(\"/studio\", platformUrl);\n url.searchParams.set(\"code\", userCode);\n return url.toString();\n}\n\n/** Canonical credential audience: one HTTPS origin (HTTP only on loopback). */\nexport function platformAudience(value: string): string {\n let url: URL;\n try { url = new URL(value); } catch { throw new Error(\"platform must be an absolute URL\"); }\n const local = url.hostname === \"localhost\" || url.hostname === \"127.0.0.1\" || url.hostname === \"[::1]\";\n if (url.protocol !== \"https:\" && !(local && url.protocol === \"http:\")) {\n throw new Error(\"platform credentials require HTTPS except for loopback development\");\n }\n if (url.username || url.password || url.search || url.hash) {\n throw new Error(\"platform URL must not contain credentials, query, or fragment\");\n }\n return url.origin;\n}\n","import { spawn } from \"node:child_process\";\nimport process from \"node:process\";\n\nexport interface OpenUrlOptions {\n platform?: NodeJS.Platform;\n spawnImpl?: typeof spawn;\n}\n\nexport async function openUrl(url: string, options: OpenUrlOptions = {}): Promise<void> {\n const command = openerFor(options.platform ?? process.platform);\n const doSpawn = options.spawnImpl ?? spawn;\n await new Promise<void>((resolve, reject) => {\n const child = doSpawn(command.cmd, [...command.args, url], {\n stdio: \"ignore\",\n detached: true,\n });\n child.once(\"error\", reject);\n child.once(\"spawn\", () => {\n child.unref();\n resolve();\n });\n });\n}\n\nexport function openerFor(platform: NodeJS.Platform): { cmd: string; args: string[] } {\n if (platform === \"darwin\") return { cmd: \"open\", args: [] };\n if (platform === \"win32\") return { cmd: \"cmd\", args: [\"/c\", \"start\", \"\"] };\n return { cmd: \"xdg-open\", args: [] };\n}\n","import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, relative, resolve } from \"node:path\";\nimport type { LoadedProjectConfig, LocalCredentials } from \"./types\";\n\nconst GITIGNORE_LINES = [\".odla/*.local.json\", \".odla/dev-token.json\", \".dev.vars\"];\n\nexport function readJsonFile<T>(path: string): T | null {\n try {\n return JSON.parse(readFileSync(path, \"utf8\")) as T;\n } catch {\n return null;\n }\n}\n\nexport function writePrivateJson(path: string, value: unknown): void {\n writePrivateText(path, `${JSON.stringify(value, null, 2)}\\n`);\n}\n\nexport function readCredentials(path: string): LocalCredentials | null {\n if (!existsSync(path)) return null;\n let value: unknown;\n try {\n value = JSON.parse(readFileSync(path, \"utf8\"));\n } catch {\n throw new Error(`credentials file ${path} is not valid JSON; fix or remove it before provisioning`);\n }\n if (!value || typeof value !== \"object\" || typeof (value as LocalCredentials).appId !== \"string\" ||\n !(value as LocalCredentials).envs || typeof (value as LocalCredentials).envs !== \"object\") {\n throw new Error(`credentials file ${path} has an invalid shape; fix or remove it before provisioning`);\n }\n return value as LocalCredentials;\n}\n\nexport function mergeCredential(\n current: LocalCredentials | null,\n update: { appId: string; platformUrl: string; dbEndpoint: string; env: string; tenantId: string; dbKey?: string; o11yToken?: string },\n): LocalCredentials {\n const next: LocalCredentials = current ?? {\n appId: update.appId,\n platformUrl: update.platformUrl,\n dbEndpoint: update.dbEndpoint,\n updatedAt: new Date(0).toISOString(),\n envs: {},\n };\n next.appId = update.appId;\n next.platformUrl = update.platformUrl;\n next.dbEndpoint = update.dbEndpoint;\n next.updatedAt = new Date().toISOString();\n next.envs[update.env] = {\n ...(next.envs[update.env] ?? {}),\n tenantId: update.tenantId,\n ...(update.dbKey ? { dbKey: update.dbKey } : {}),\n ...(update.o11yToken ? { o11yToken: update.o11yToken } : {}),\n };\n return next;\n}\n\nexport function ensureGitignore(rootDir: string, localPaths: string[] = []): void {\n const path = resolve(rootDir, \".gitignore\");\n const existing = existsSync(path) ? readFileSync(path, \"utf8\") : \"\";\n const configured = localPaths.map((localPath) => gitignoreEntry(rootDir, localPath)).filter((line): line is string => !!line);\n const wanted = [...new Set([...GITIGNORE_LINES, ...configured])];\n const missing = wanted.filter((line) => !existing.split(/\\r?\\n/).includes(line));\n if (missing.length === 0) return;\n const prefix = existing && !existing.endsWith(\"\\n\") ? \"\\n\" : \"\";\n writeFileSync(path, `${existing}${prefix}${missing.join(\"\\n\")}\\n`);\n}\n\nexport interface O11yDevVars {\n endpoint: string;\n service: string;\n version?: string;\n}\n\nexport function o11yDevVars(cfg: LoadedProjectConfig): O11yDevVars | undefined {\n if (!cfg.services.includes(\"o11y\")) return undefined;\n return {\n endpoint: cfg.o11y?.endpoint ?? \"https://o11y.odla.ai\",\n service: cfg.o11y?.service ?? cfg.app.id,\n ...(cfg.o11y?.version ? { version: cfg.o11y.version } : {}),\n };\n}\n\nexport function resolveWriteDevVarsTarget(cfg: LoadedProjectConfig, requested: string | boolean | undefined): string | null {\n if (!requested) return null;\n if (requested === true) return cfg.local.devVarsFile;\n return resolve(dirname(cfg.configPath), requested);\n}\n\nexport function writeDevVars(path: string, credentials: LocalCredentials, env: string, o11y?: O11yDevVars): void {\n const entry = credentials.envs[env];\n if (!entry) throw new Error(`no credentials for env \"${env}\" in ${path}`);\n const lines = [`ODLA_PLATFORM=\"${credentials.platformUrl}\"`];\n if (entry.dbKey) lines.push(`ODLA_ENDPOINT=\"${credentials.dbEndpoint}\"`);\n lines.push(`ODLA_APP_ID=\"${credentials.appId}\"`, `ODLA_ENV=\"${env}\"`, `ODLA_TENANT=\"${entry.tenantId}\"`);\n if (entry.dbKey) lines.push(`ODLA_API_KEY=\"${entry.dbKey}\"`);\n if (o11y) {\n lines.push(`ODLA_O11Y_ENDPOINT=\"${o11y.endpoint}\"`, `ODLA_O11Y_SERVICE=\"${o11y.service}\"`);\n if (o11y.version) lines.push(`ODLA_O11Y_VERSION=\"${o11y.version}\"`);\n // The ingest token is a secret; .dev.vars is gitignored (holds ODLA_API_KEY too).\n if (entry.o11yToken) lines.push(`ODLA_O11Y_TOKEN=\"${entry.o11yToken}\"`);\n }\n const existing = existsSync(path) ? readFileSync(path, \"utf8\") : \"\";\n const retained = existing.split(/\\r?\\n/).filter((line) => !isManagedDevVar(line));\n while (retained.at(-1) === \"\") retained.pop();\n const prefix = retained.length ? `${retained.join(\"\\n\")}\\n\\n` : \"\";\n writePrivateText(path, `${prefix}${lines.join(\"\\n\")}\\n`);\n}\n\nconst MANAGED_DEV_VARS = new Set([\n \"ODLA_PLATFORM\", \"ODLA_ENDPOINT\", \"ODLA_APP_ID\", \"ODLA_ENV\", \"ODLA_TENANT\", \"ODLA_API_KEY\",\n \"ODLA_O11Y_ENDPOINT\", \"ODLA_O11Y_SERVICE\", \"ODLA_O11Y_VERSION\", \"ODLA_O11Y_TOKEN\",\n]);\n\nfunction isManagedDevVar(line: string): boolean {\n const match = line.match(/^\\s*(?:export\\s+)?([A-Z][A-Z0-9_]*)\\s*=/);\n return !!match?.[1] && MANAGED_DEV_VARS.has(match[1]);\n}\n\nfunction writePrivateText(path: string, text: string): void {\n mkdirSync(dirname(path), { recursive: true });\n const temporary = `${path}.tmp-${process.pid}-${Date.now()}`;\n writeFileSync(temporary, text, { mode: 0o600 });\n chmodSync(temporary, 0o600);\n renameSync(temporary, path);\n}\n\nexport function gitignoreEntry(rootDir: string, path: string): string | null {\n const rel = relative(resolve(rootDir), resolve(path));\n if (!rel || rel === \"..\" || rel.startsWith(`..${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`) || isAbsolute(rel)) return null;\n return rel.replaceAll(\"\\\\\", \"/\");\n}\n\nexport function displayPath(path: string, rootDir = process.cwd()): string {\n const rel = relative(rootDir, path);\n return rel && !rel.startsWith(\"..\") ? rel : path;\n}\n","import process from \"node:process\";\n\n/**\n * Secret ingestion shared by every write-only CLI transfer (`admin ai\n * credential set`, `secrets set`, `secrets set-clerk-key`): values may come\n * only from a named environment variable or stdin — never argv — so they\n * cannot land in shell history, process listings, or an agent's transcript.\n */\nexport interface SecretInputOptions {\n /** Environment variable holding the value. Mutually exclusive with `stdin`. */\n fromEnv?: string;\n /** Read the value from stdin. Mutually exclusive with `fromEnv`. */\n stdin?: boolean;\n /** Test/embedding override for the stdin reader. */\n readStdin?: () => Promise<string>;\n}\n\nconst MAX_BYTES = 64 * 1024;\n\n/**\n * Resolve the secret value from exactly one of `--from-env`/`--stdin`,\n * stripping one trailing newline and rejecting empty or >64 KiB values.\n * `kind` names the value in error messages (e.g. \"credential\", \"secret\").\n */\nexport async function secretInputValue(options: SecretInputOptions, kind = \"credential\"): Promise<string> {\n if (options.fromEnv && options.stdin) throw new Error(\"choose exactly one of --from-env or --stdin\");\n let value: string | undefined;\n if (options.fromEnv) value = process.env[options.fromEnv];\n else if (options.stdin) value = await (options.readStdin ?? (() => readSecretStream(kind)))();\n else throw new Error(`${kind} input required: use --from-env <NAME> or --stdin; values are never accepted as arguments`);\n value = value?.replace(/[\\r\\n]+$/, \"\");\n if (!value) throw new Error(options.fromEnv ? `environment variable ${options.fromEnv} is empty or unset` : `stdin ${kind} is empty`);\n if (new TextEncoder().encode(value).byteLength > MAX_BYTES) throw new Error(`${kind} exceeds 64 KiB`);\n return value;\n}\n\n/** @internal Default stdin reader; `stream` is injectable only for tests. */\nexport async function readSecretStream(kind: string, stream: AsyncIterable<unknown> = process.stdin): Promise<string> {\n let value = \"\";\n for await (const chunk of stream) {\n value += String(chunk);\n if (value.length > MAX_BYTES) throw new Error(`${kind} exceeds 64 KiB`);\n }\n return value;\n}\n","import { existsSync } from \"node:fs\";\nimport process from \"node:process\";\nimport { requestToken } from \"@odla-ai/db\";\nimport { ensureGitignore, readJsonFile, writePrivateJson } from \"./local\";\nimport { openUrl } from \"./open\";\nimport { approvalBrowser, handshakeEmail, handshakeUrl, platformAudience } from \"./token\";\n\n/** One exact platform scope obtainable through the admin device flow. */\nexport type ScopedPlatformScope =\n | \"platform:ai:policy:read\"\n | \"platform:ai:policy:write\"\n | \"platform:ai:credential:read\"\n | \"platform:ai:credential:write\"\n | \"platform:ai:usage:read\"\n | \"platform:ai:audit:read\"\n | \"platform:security:self\";\n\n/** Inputs for obtaining one short-lived, exact-scope platform device grant. */\nexport interface ScopedPlatformTokenOptions {\n platform: string;\n scope: ScopedPlatformScope;\n /** Existing odla account email used only when a fresh handshake is required. */\n email?: string;\n open?: boolean;\n fetch?: typeof fetch;\n stdout?: Pick<typeof console, \"log\">;\n openApprovalUrl?: (url: string) => Promise<void>;\n tokenFile?: string;\n}\n\ninterface AdminPlatformTokenOptions extends ScopedPlatformTokenOptions {\n token?: string;\n}\n\n/** Obtain/cache one exact platform scope without granting ambient admin. */\nexport async function getScopedPlatformToken(options: ScopedPlatformTokenOptions): Promise<string> {\n return resolveAdminPlatformToken(options);\n}\n\n/** Resolve an explicit, audience-bound env, cached, or newly approved token. */\nexport async function resolveAdminPlatformToken(options: AdminPlatformTokenOptions): Promise<string> {\n const audience = platformAudience(options.platform);\n if (options.token) return options.token;\n const fromEnv = process.env.ODLA_ADMIN_TOKEN;\n if (fromEnv) return audienceBoundEnvToken(fromEnv, audience);\n return scopedToken(\n audience,\n options.scope,\n options,\n options.fetch ?? fetch,\n options.stdout ?? console,\n );\n}\n\nfunction audienceBoundEnvToken(token: string, platform: string): string {\n const audience = platformAudience(platform);\n const declared = process.env.ODLA_ADMIN_TOKEN_AUDIENCE;\n if (declared) {\n if (platformAudience(declared) !== audience) throw new Error(\"ODLA_ADMIN_TOKEN_AUDIENCE does not match the configured platform\");\n } else if (audience !== \"https://odla.ai\") {\n throw new Error(\"ODLA_ADMIN_TOKEN_AUDIENCE is required for a non-default platform\");\n }\n return token;\n}\n\nasync function scopedToken(\n platform: string,\n scope: string,\n options: ScopedPlatformTokenOptions,\n doFetch: typeof fetch,\n out: Pick<typeof console, \"log\">,\n): Promise<string> {\n const audience = platformAudience(platform);\n const tokenFile = options.tokenFile ?? `${process.cwd()}/.odla/admin-token.local.json`;\n const cache = readJsonFile<{ platform?: string; email?: string; tokens?: Record<string, { token?: string; expiresAt?: number }> }>(tokenFile);\n const cached = cache?.platform === audience ? cache.tokens?.[scope] : undefined;\n if (cached?.token && (cached.expiresAt ?? 0) > Date.now() + 60_000) {\n out.log(`auth: using cached ${scope} grant (${tokenFile})`);\n return cached.token;\n }\n const email = handshakeEmail(options.email, cache?.platform === audience ? cache.email : undefined);\n const { token, expiresAt } = await requestToken({\n endpoint: audience,\n email,\n label: `odla CLI admin AI (${scope})`,\n scopes: [scope],\n fetch: doFetch,\n onCode: async ({ userCode, expiresIn, verificationUriComplete }) => {\n const approvalUrl = verificationUriComplete ?? handshakeUrl(audience, userCode);\n out.log(`Review, then approve scoped request ${userCode} at ${approvalUrl} within ${Math.floor(expiresIn / 60)}m.`);\n if (approvalBrowser({ open: options.open }).open) {\n await (options.openApprovalUrl ?? openUrl)(approvalUrl).catch(() => undefined);\n }\n },\n });\n const tokens = cache?.platform === audience ? { ...(cache.tokens ?? {}) } : {};\n tokens[scope] = { token, expiresAt };\n if (existsSync(`${process.cwd()}/.git`)) ensureGitignore(process.cwd(), [tokenFile]);\n writePrivateJson(tokenFile, { platform: audience, email, tokens });\n out.log(`auth: cached ${scope} grant (${tokenFile}; mode 0600)`);\n return token;\n}\n","/** Optional limit for the metadata-only System AI administration trail. */\nexport interface AdminAiAuditFilters {\n limit?: number;\n}\n\ninterface AdminAiAuditRequest {\n platform: string;\n query: string;\n headers: Record<string, string>;\n json?: boolean;\n fetch: typeof fetch;\n stdout: Pick<typeof console, \"log\">;\n}\n\n/** Validate the audit limit and build its query before authentication. */\nexport function adminAiAuditQuery(filters: AdminAiAuditFilters): string {\n if (filters.limit === undefined) return \"\";\n if (!Number.isSafeInteger(filters.limit) || filters.limit < 1 || filters.limit > 200) {\n throw new Error(\"audit limit must be an integer from 1 to 200\");\n }\n return `?limit=${filters.limit}`;\n}\n\n/** Read and render immutable, metadata-only System AI admin changes. */\nexport async function readAdminAiAudit(request: AdminAiAuditRequest): Promise<void> {\n const response = await request.fetch(`${request.platform}/registry/platform/ai-audit${request.query}`, {\n headers: request.headers,\n });\n const body = await responseBody(response);\n if (!response.ok) throw new Error(apiError(response.status, body));\n if (request.json) {\n request.stdout.log(JSON.stringify(body, null, 2));\n return;\n }\n const events = isRecord(body) && Array.isArray(body.events) ? body.events.filter(isRecord) : [];\n request.stdout.log(\"when\\tchange\\ttarget\\tbefore -> after\\tactor\");\n for (const event of events) {\n const before = isRecord(event.oldPolicy) ? event.oldPolicy : undefined;\n const after = isRecord(event.newPolicy) ? event.newPolicy : undefined;\n const route = before && after\n ? `${String(before.provider)}/${String(before.model)}@v${String(before.version)} -> ${String(after.provider)}/${String(after.model)}@v${String(after.version)}`\n : \"value not retained\";\n request.stdout.log([\n timestamp(event.createdAt), String(event.changeKind ?? \"\"),\n String(event.purpose ?? event.provider ?? \"\"), route,\n `${String(event.actorType ?? \"\")}:${String(event.actorId ?? \"\")}`,\n ].join(\"\\t\"));\n }\n}\n\nasync function responseBody(response: Response): Promise<unknown> {\n const text = await response.text();\n if (!text) return {};\n try { return JSON.parse(text) as unknown; } catch { return { message: text.slice(0, 300) }; }\n}\n\nfunction apiError(status: number, body: unknown): string {\n const error = isRecord(body) && isRecord(body.error) ? body.error : undefined;\n const message = error && typeof error.message === \"string\"\n ? error.message\n : isRecord(body) && typeof body.message === \"string\" ? body.message : \"request failed\";\n return `read System AI admin changes failed (${status}): ${message}`;\n}\n\nfunction timestamp(value: unknown): string {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return String(value ?? \"\");\n const date = new Date(value);\n return Number.isFinite(date.valueOf()) ? date.toISOString() : \"\";\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n","/** Hosted platform purposes whose provider, model, and budgets an admin may route. */\nexport const SYSTEM_AI_PURPOSES = [\"o11y.triage\", \"security.discovery\", \"security.validation\"] as const;\n\n/** One catalog-validated, platform-funded System AI purpose. */\nexport type SystemAiPurpose = (typeof SYSTEM_AI_PURPOSES)[number];\n\n/** Validate a CLI purpose before any network mutation. */\nexport function requireSystemAiPurpose(value: string | undefined): SystemAiPurpose {\n if (!SYSTEM_AI_PURPOSES.includes(value as SystemAiPurpose)) {\n throw new Error(`purpose must be one of: ${SYSTEM_AI_PURPOSES.join(\", \")}`);\n }\n return value as SystemAiPurpose;\n}\n","/** Optional metadata-only filters for attributed platform AI usage. */\nexport interface AdminAiUsageFilters {\n appId?: string;\n env?: string;\n runId?: string;\n limit?: number;\n}\n\ninterface AdminAiUsageRequest {\n platform: string;\n query: string;\n headers: Record<string, string>;\n json?: boolean;\n fetch: typeof fetch;\n stdout: Pick<typeof console, \"log\">;\n}\n\n/** Validate usage filters and build the platform query before authentication. */\nexport function adminAiUsageQuery(filters: AdminAiUsageFilters): string {\n const params = new URLSearchParams();\n if (filters.appId?.trim()) params.set(\"appId\", filters.appId.trim());\n if (filters.env?.trim()) params.set(\"env\", filters.env.trim());\n if (filters.runId?.trim()) params.set(\"runId\", filters.runId.trim());\n if (filters.limit !== undefined) params.set(\"limit\", String(usageLimit(filters.limit)));\n const query = params.toString();\n return query ? `?${query}` : \"\";\n}\n\n/** Read and render metadata-only, app-attributed platform AI usage. */\nexport async function readAdminAiUsage(request: AdminAiUsageRequest): Promise<void> {\n const res = await request.fetch(`${request.platform}/registry/platform/ai-usage${request.query}`, {\n headers: request.headers,\n });\n const body = await responseBody(res);\n if (!res.ok) throw new Error(apiError(\"read platform AI usage\", res.status, body));\n if (request.json) request.stdout.log(JSON.stringify(body, null, 2));\n else printUsage(body, request.stdout);\n}\n\nfunction usageLimit(value: number): number {\n if (!Number.isSafeInteger(value) || value < 1 || value > 500) {\n throw new Error(\"usage limit must be an integer from 1 to 500\");\n }\n return value;\n}\n\nfunction printUsage(body: unknown, out: Pick<typeof console, \"log\">): void {\n const aggregates = isRecord(body) && isRecord(body.aggregates) && Array.isArray(body.aggregates.byStatus)\n ? body.aggregates.byStatus.filter(isRecord)\n : [];\n out.log(`All retained hosted-security status totals (up to ${String(isRecord(body) ? body.retentionDays ?? 90 : 90)} days; o11y triage excluded)\\nstatus\\tcalls\\tinput tokens\\toutput tokens\\tcost\\tunpriced calls`);\n for (const row of aggregates) {\n out.log([\n String(row.status ?? \"\"), String(row.calls ?? \"\"), String(row.input_tokens ?? \"\"),\n String(row.output_tokens ?? \"\"), formatMicrousd(row.cost_microusd), String(row.unpriced_calls ?? \"\"),\n ].join(\"\\t\"));\n }\n const events = isRecord(body) && Array.isArray(body.events) ? body.events.filter(isRecord) : [];\n out.log(`Latest ${String(isRecord(body) ? body.eventLimit ?? events.length : events.length)} hosted-security events\\nwhen\\tapp/env\\trun\\tactor\\tpurpose/role\\troute / policy\\ttokens\\tcost\\tstatus`);\n for (const event of events) {\n const input = numeric(event.input_tokens);\n const output = numeric(event.output_tokens);\n const priced = event.priced === true || event.priced === 1;\n out.log([\n timestamp(event.created_at), `${String(event.app_id ?? \"\")}/${String(event.env ?? \"\")}`,\n String(event.run_id ?? \"\"), `${String(event.actor_type ?? \"\")}:${String(event.actor_id ?? \"\")}`,\n `${String(event.purpose ?? \"\")}/${String(event.role ?? \"\")}`,\n `${String(event.provider ?? \"\")}/${String(event.model ?? \"\")}@v${String(event.policy_version ?? \"unknown\")}`, String(input + output),\n priced ? formatMicrousd(event.cost_microusd) : \"unpriced\",\n `${String(event.status ?? \"\")}${event.error_code ? `:${String(event.error_code)}` : \"\"}`,\n ].join(\"\\t\"));\n }\n}\n\nfunction numeric(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n\nfunction formatMicrousd(value: unknown): string {\n return typeof value === \"number\" && Number.isFinite(value) ? `$${(value / 1_000_000).toFixed(6)}` : \"unpriced\";\n}\n\nfunction timestamp(value: unknown): string {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return String(value ?? \"\");\n const date = new Date(value);\n return Number.isFinite(date.valueOf()) ? date.toISOString() : \"\";\n}\n\nasync function responseBody(res: Response): Promise<unknown> {\n const text = await res.text();\n if (!text) return {};\n try { return JSON.parse(text) as unknown; } catch { return { message: text.slice(0, 300) }; }\n}\n\nfunction apiError(action: string, status: number, body: unknown): string {\n const error = isRecord(body) && isRecord(body.error) ? body.error : undefined;\n const message = error && typeof error.message === \"string\" ? error.message : isRecord(body) && typeof body.message === \"string\" ? body.message : \"request failed\";\n return `${action} failed (${status}): ${message}`;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n","export type OptionValue = string | boolean | string[];\n\nexport interface ParsedArgv {\n positionals: string[];\n options: Record<string, OptionValue>;\n}\n\n/** Parse the small, dependency-free option grammar shared by every CLI command. */\nexport function parseArgv(argv: string[]): ParsedArgv {\n const positionals: string[] = [];\n const options: Record<string, OptionValue> = {};\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i]!;\n if (!arg.startsWith(\"--\")) {\n positionals.push(arg);\n continue;\n }\n const eq = arg.indexOf(\"=\");\n const rawName = arg.slice(2, eq === -1 ? undefined : eq);\n if (!rawName) continue;\n if (rawName.startsWith(\"no-\")) {\n options[rawName.slice(3)] = false;\n continue;\n }\n if (eq !== -1) {\n addOption(options, rawName, arg.slice(eq + 1));\n continue;\n }\n const value = argv[i + 1];\n if (value !== undefined && !value.startsWith(\"--\")) {\n i++;\n addOption(options, rawName, value);\n } else {\n addOption(options, rawName, true);\n }\n }\n return { positionals, options };\n}\n\nexport function assertArgs(parsed: ParsedArgv, allowedOptions: string[], maxPositionals: number): void {\n const allowed = new Set(allowedOptions);\n for (const name of Object.keys(parsed.options)) {\n if (!allowed.has(name)) throw new Error(`unknown option \"--${name}\"; run \"odla-ai help\" for supported options`);\n }\n if (parsed.positionals.length > maxPositionals) {\n throw new Error(`unexpected argument \"${parsed.positionals[maxPositionals]}\"; run \"odla-ai help\"`);\n }\n}\n\nexport function requiredString(value: OptionValue | undefined, name: string): string {\n const result = stringOpt(value);\n if (!result) throw new Error(`${name} is required`);\n return result;\n}\n\nexport function stringOpt(value: OptionValue | undefined): string | undefined {\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) return value[value.length - 1];\n return undefined;\n}\n\nexport function listOpt(value: OptionValue | undefined): string[] | undefined {\n if (value === undefined || typeof value === \"boolean\") return undefined;\n const values = Array.isArray(value) ? value : [value];\n return values.flatMap((item) => item.split(\",\")).map((item) => item.trim()).filter(Boolean);\n}\n\nexport function boolOpt(value: OptionValue | undefined): boolean | undefined {\n if (typeof value === \"boolean\") return value;\n if (typeof value === \"string\" && (value === \"true\" || value === \"false\")) return value === \"true\";\n if (value === undefined) return undefined;\n throw new Error(\"boolean option must be true or false\");\n}\n\nexport function numberOpt(value: OptionValue | undefined, flag: string): number | undefined {\n if (value === undefined) return undefined;\n const raw = stringOpt(value);\n const parsed = raw === undefined ? Number.NaN : Number(raw);\n if (!Number.isSafeInteger(parsed) || parsed < 1) throw new Error(`${flag} requires a positive integer`);\n return parsed;\n}\n\nfunction addOption(options: Record<string, OptionValue>, name: string, value: string | boolean): void {\n const current = options[name];\n if (current === undefined) options[name] = value;\n else if (Array.isArray(current)) current.push(String(value));\n else options[name] = [String(current), String(value)];\n}\n","import { adminAi } from \"./admin-ai\";\nimport {\n assertArgs,\n boolOpt,\n numberOpt,\n stringOpt,\n type ParsedArgv,\n} from \"./argv\";\n\nexport async function adminCommand(parsed: ParsedArgv): Promise<void> {\n const area = parsed.positionals[1];\n const action = parsed.positionals[2];\n const credentialSet = action === \"credential\" && parsed.positionals[3] === \"set\";\n const credentials = action === \"credentials\";\n const models = action === \"models\";\n const usage = action === \"usage\";\n const audit = action === \"audit\";\n if (area !== \"ai\" || (action !== \"show\" && action !== \"set\"\n && !credentialSet && !credentials && !models && !usage && !audit)) {\n throw new Error('unknown admin command. Try \"odla-ai admin ai show\".');\n }\n assertArgs(parsed, [\n \"platform\", \"json\", \"open\", \"email\", \"provider\", \"model\", \"enabled\",\n \"max-input-bytes\", \"max-output-tokens\", \"max-calls-per-run\", \"from-env\", \"stdin\",\n \"discovery-provider\", \"discovery-model\", \"validation-provider\", \"validation-model\",\n \"app-id\", \"env\", \"run-id\", \"limit\",\n ], credentialSet ? 5 : action === \"set\" ? 4 : 3);\n await adminAi({\n action: credentialSet\n ? \"credential-set\"\n : credentials ? \"credentials\"\n : models ? \"models\"\n : usage ? \"usage\"\n : audit ? \"audit\"\n : action as \"show\" | \"set\",\n purpose: action === \"set\" ? parsed.positionals[3] : undefined,\n provider: stringOpt(parsed.options.provider),\n model: stringOpt(parsed.options.model),\n enabled: boolOpt(parsed.options.enabled),\n maxInputBytes: numberOpt(parsed.options[\"max-input-bytes\"], \"--max-input-bytes\"),\n maxOutputTokens: numberOpt(parsed.options[\"max-output-tokens\"], \"--max-output-tokens\"),\n maxCallsPerRun: numberOpt(parsed.options[\"max-calls-per-run\"], \"--max-calls-per-run\"),\n platform: stringOpt(parsed.options.platform),\n email: stringOpt(parsed.options.email),\n json: parsed.options.json === true,\n open: parsed.options.open === false\n ? false\n : parsed.options.open === true ? true : undefined,\n credentialProvider: credentialSet ? parsed.positionals[4] : undefined,\n fromEnv: stringOpt(parsed.options[\"from-env\"]),\n stdin: parsed.options.stdin === true,\n discoveryProvider: stringOpt(parsed.options[\"discovery-provider\"]),\n discoveryModel: stringOpt(parsed.options[\"discovery-model\"]),\n validationProvider: stringOpt(parsed.options[\"validation-provider\"]),\n validationModel: stringOpt(parsed.options[\"validation-model\"]),\n appId: stringOpt(parsed.options[\"app-id\"]),\n env: stringOpt(parsed.options.env),\n runId: stringOpt(parsed.options[\"run-id\"]),\n limit: numberOpt(parsed.options.limit, \"--limit\"),\n });\n}\n","/** Stable, machine-readable division of work between the CLI, coding agent,\n * human operator, and Studio. Printed by `odla-ai capabilities --json`. */\nexport const CAPABILITIES = {\n cli: [\n \"start an email-bound device request without accepting a password or user session token\",\n \"register the app and enable configured services per environment\",\n \"issue, persist, and explicitly rotate configured service credentials\",\n \"write local Worker values and push deployed Worker secrets through Wrangler stdin\",\n \"store tenant-vault secrets (including the Clerk webhook secret and reserved Clerk secret key) write-only from stdin or an env var\",\n \"push db schema/rules and configure platform AI, auth, and deployment links\",\n \"apply read-only Google calendar mirror and public booking-page config, then drive state-bound consent, status, discovery, resync, and disconnect flows\",\n \"validate config offline and smoke-test a provisioned db environment\",\n \"run app-attributed hosted security discovery and independent validation without provider keys\",\n \"connect/revoke source-read-only GitHub sources and drive commit-pinned hosted security jobs without PATs or provider keys\",\n \"let admins manage system AI policy and credentials, inspect attributed usage, and read immutable admin changes through separate short-lived capability-only approvals\",\n ],\n agent: [\n \"install and import the selected odla SDKs\",\n \"wrap the Worker with withObservability and choose useful telemetry\",\n \"make application-specific schema, rules, auth, UI, and migration decisions\",\n \"wire @odla-ai/calendar into trusted Worker code and keep the app admin key out of browsers\",\n ],\n human: [\n \"provide the existing odla account email, then sign in and explicitly review/approve the exact device code\",\n \"review mirrored calendar/attendee disclosure and complete the server-issued Google consent flow\",\n \"consent to production changes with --yes\",\n \"request destructive credential rotation explicitly\",\n \"review application semantics, security findings, releases, and merges\",\n \"approve redacted-source disclosure before hosted security reasoning\",\n \"approve GitHub App repository access separately from redacted-snippet disclosure\",\n ],\n studio: [\n \"view telemetry and environment state\",\n \"let signed-in users inventory/revoke their own agent grants and admins audit/global-revoke them\",\n \"review calendar connection, granted read scope, selected calendars, and sync health without exposing provider tokens\",\n \"perform manual credential recovery when the CLI's local shown-once copy is unavailable\",\n \"configure system AI purposes and view app/environment/run-attributed usage\",\n \"connect/revoke GitHub security sources and inspect ref-to-SHA jobs, routes, retention, coverage, and normalized reports\",\n ],\n} as const;\n\ntype Output = Pick<typeof console, \"log\">;\n\n/** Print the stable responsibility boundary for humans or agent tooling. */\nexport function printCapabilities(json = false, out: Output = console): void {\n if (json) {\n out.log(JSON.stringify(CAPABILITIES, null, 2));\n return;\n }\n out.log(\"odla-ai responsibility boundary\\n\");\n printGroup(out, \"CLI automates\", CAPABILITIES.cli);\n printGroup(out, \"Coding agent changes source\", CAPABILITIES.agent);\n printGroup(out, \"Human checkpoints\", CAPABILITIES.human);\n printGroup(out, \"Studio\", CAPABILITIES.studio);\n}\n\nfunction printGroup(out: Output, heading: string, items: readonly string[]): void {\n out.log(`${heading}:`);\n for (const item of items) out.log(` - ${item}`);\n out.log(\"\");\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { AppRules, CalendarServiceConfig, LoadedProjectConfig, OdlaProjectConfig, ProvisionPlan } from \"./types\";\n\nconst DEFAULT_PLATFORM = \"https://odla.ai\";\n// Safe-by-default: production must be opted into explicitly in odla.config.\nconst DEFAULT_ENVS = [\"dev\"];\nconst DEFAULT_SERVICES = [\"db\", \"ai\"];\n/** The only Google OAuth scope the platform ever requests: read-only calendar events. */\nexport const GOOGLE_CALENDAR_READ_SCOPE = \"https://www.googleapis.com/auth/calendar.events.readonly\";\n\nexport async function loadProjectConfig(configPath = \"odla.config.mjs\"): Promise<LoadedProjectConfig> {\n const resolved = resolve(configPath);\n if (!existsSync(resolved)) {\n throw new Error(`config not found: ${configPath}. Run \"odla-ai init\" first or pass --config.`);\n }\n\n const raw = await loadConfigModule(resolved);\n const rootDir = dirname(resolved);\n validateRawConfig(raw, resolved);\n\n const platformUrl = trimSlash(process.env.ODLA_PLATFORM_URL || raw.platformUrl || DEFAULT_PLATFORM);\n const dbEndpoint = trimSlash(process.env.ODLA_DB_ENDPOINT || raw.dbEndpoint || platformUrl);\n const envs = unique(raw.envs?.length ? raw.envs : DEFAULT_ENVS);\n const services = unique(raw.services?.length ? raw.services : DEFAULT_SERVICES);\n validateCalendarConfig(raw, envs, services, resolved);\n const local = {\n tokenFile: resolve(rootDir, raw.local?.tokenFile ?? \".odla/dev-token.json\"),\n credentialsFile: resolve(rootDir, raw.local?.credentialsFile ?? \".odla/credentials.local.json\"),\n devVarsFile: resolve(rootDir, raw.local?.devVarsFile ?? \".dev.vars\"),\n gitignore: raw.local?.gitignore ?? true,\n };\n\n return {\n ...raw,\n configPath: resolved,\n rootDir,\n platformUrl,\n dbEndpoint,\n envs,\n services,\n local,\n };\n}\n\nexport async function resolveDataExport<T>(\n cfg: LoadedProjectConfig,\n value: unknown,\n names: string[],\n): Promise<T | undefined> {\n if (value === undefined || value === null || value === false) return undefined;\n if (typeof value !== \"string\") return value as T;\n\n const target = isAbsolute(value) ? value : resolve(cfg.rootDir, value);\n if (target.endsWith(\".json\")) {\n return JSON.parse(readFileSync(target, \"utf8\")) as T;\n }\n const mod = (await import(pathToFileURL(target).href)) as Record<string, unknown>;\n for (const name of names) {\n if (mod[name] !== undefined) return mod[name] as T;\n }\n if (mod.default !== undefined) return mod.default as T;\n throw new Error(`${value} did not export ${names.join(\", \")} or default`);\n}\n\nexport function buildPlan(cfg: LoadedProjectConfig): ProvisionPlan {\n return {\n appId: cfg.app.id,\n appName: cfg.app.name,\n platformUrl: cfg.platformUrl,\n dbEndpoint: cfg.dbEndpoint,\n envs: cfg.envs,\n services: cfg.services,\n hasSchema: !!cfg.db?.schema,\n hasRules: !!cfg.db?.rules || (!!cfg.db?.schema && cfg.db.defaultRules !== false),\n aiProvider: cfg.ai?.provider,\n };\n}\n\n/** Resolve the checked-in calendar block into one controller-safe env payload. */\nexport function calendarServiceConfig(cfg: LoadedProjectConfig, env: string): CalendarServiceConfig {\n if (!cfg.services.includes(\"calendar\")) throw new Error('calendar service is not enabled in config services');\n if (!cfg.envs.includes(env)) throw new Error(`calendar env \"${env}\" is not declared in config envs`);\n const google = cfg.calendar?.google;\n if (!google) throw new Error(\"calendar.google is required when the calendar service is enabled\");\n return {\n provider: \"google\",\n access: \"read\",\n calendars: unique(google.calendars[env]!.map((id) => id.trim())),\n match: {\n organizerSelf: google.match?.organizerSelf ?? true,\n requireAttendees: google.match?.requireAttendees ?? true,\n ...(google.match?.summaryPrefix !== undefined ? { summaryPrefix: google.match.summaryPrefix.trim() } : {}),\n },\n attendeePolicy: google.attendeePolicy ?? \"full\",\n };\n}\n\n/** Public Appointment Schedule URL to apply separately from connector config. */\nexport function calendarBookingPageUrl(cfg: LoadedProjectConfig, env: string): string | null | undefined {\n const value = cfg.calendar?.google.bookingPageUrl?.[env];\n if (value === undefined || value === null) return value;\n return new URL(value).toString();\n}\n\nexport function rulesFromSchema(schema: unknown): AppRules {\n const entities = serializedEntities(schema);\n return Object.fromEntries(\n entities.map((name) => [name, { view: \"false\", create: \"false\", update: \"false\", delete: \"false\" }]),\n );\n}\n\nexport function serializedEntities(schema: unknown): string[] {\n if (!schema || typeof schema !== \"object\") return [];\n const entities = (schema as { entities?: unknown }).entities;\n if (!entities || typeof entities !== \"object\" || Array.isArray(entities)) return [];\n return Object.keys(entities);\n}\n\nexport function envValue(value: string | undefined): string | undefined {\n if (!value) return undefined;\n if (value.startsWith(\"$\")) return process.env[value.slice(1)];\n return value;\n}\n\nfunction validateRawConfig(raw: unknown, path: string): asserts raw is OdlaProjectConfig {\n if (!raw || typeof raw !== \"object\") throw new Error(`${path} must export an object`);\n const cfg = raw as OdlaProjectConfig;\n if (!cfg.app || typeof cfg.app !== \"object\") throw new Error(`${path}: missing app object`);\n if (!validId(cfg.app.id)) throw new Error(`${path}: app.id must be lowercase letters, numbers, and hyphens`);\n if (!cfg.app.name || typeof cfg.app.name !== \"string\") throw new Error(`${path}: app.name is required`);\n if (cfg.envs !== undefined && (!Array.isArray(cfg.envs) || cfg.envs.some((env) => typeof env !== \"string\"))) {\n throw new Error(`${path}: envs must be an array of names`);\n }\n if (cfg.envs?.some((env) => !validId(env))) throw new Error(`${path}: env names must be lowercase letters, numbers, and hyphens`);\n if (cfg.services !== undefined && (!Array.isArray(cfg.services) || cfg.services.some((service) => typeof service !== \"string\" || !service.trim()))) {\n throw new Error(`${path}: services must be an array of non-empty names`);\n }\n}\n\nfunction validateCalendarConfig(cfg: OdlaProjectConfig, envs: string[], services: string[], path: string): void {\n const enabled = services.includes(\"calendar\");\n if (!cfg.calendar) {\n if (enabled) throw new Error(`${path}: calendar.google is required when services includes \"calendar\"`);\n return;\n }\n if (!isRecord(cfg.calendar)) throw new Error(`${path}: calendar must be an object`);\n assertOnly(cfg.calendar, [\"google\"], `${path}: calendar`);\n if (!isRecord(cfg.calendar.google)) throw new Error(`${path}: calendar.google must be an object`);\n const google = cfg.calendar.google;\n assertOnly(google, [\"calendars\", \"bookingPageUrl\", \"match\", \"attendeePolicy\"], `${path}: calendar.google`);\n if (!isRecord(google.calendars)) throw new Error(`${path}: calendar.google.calendars must map env names to calendar ids`);\n const unknownEnv = Object.keys(google.calendars).find((env) => !envs.includes(env));\n if (unknownEnv) throw new Error(`${path}: calendar.google.calendars.${unknownEnv} is not in config envs`);\n for (const env of envs) {\n const ids = google.calendars[env];\n if (!Array.isArray(ids) || ids.length === 0) {\n throw new Error(`${path}: calendar.google.calendars.${env} must be a non-empty array`);\n }\n if (ids.length > 10) {\n throw new Error(`${path}: calendar.google.calendars.${env} must contain at most 10 calendar ids`);\n }\n if (ids.some((id) => !safeText(id, 1_024))) {\n throw new Error(`${path}: calendar.google.calendars.${env} contains an invalid calendar id`);\n }\n }\n if (google.bookingPageUrl !== undefined) {\n if (!isRecord(google.bookingPageUrl)) throw new Error(`${path}: calendar.google.bookingPageUrl must map env names to HTTPS URLs or null`);\n const unknownBookingEnv = Object.keys(google.bookingPageUrl).find((env) => !envs.includes(env));\n if (unknownBookingEnv) throw new Error(`${path}: calendar.google.bookingPageUrl.${unknownBookingEnv} is not in config envs`);\n for (const [env, value] of Object.entries(google.bookingPageUrl)) {\n if (value !== null && !safeHttpsUrl(value)) {\n throw new Error(`${path}: calendar.google.bookingPageUrl.${env} must be an HTTPS URL without credentials or fragment`);\n }\n }\n }\n if (google.attendeePolicy !== undefined && google.attendeePolicy !== \"full\" && google.attendeePolicy !== \"hashed\") {\n throw new Error(`${path}: calendar.google.attendeePolicy must be \"full\" or \"hashed\"`);\n }\n if (google.match !== undefined) {\n if (!isRecord(google.match)) throw new Error(`${path}: calendar.google.match must be an object`);\n assertOnly(google.match, [\"summaryPrefix\", \"organizerSelf\", \"requireAttendees\"], `${path}: calendar.google.match`);\n if (google.match.summaryPrefix !== undefined && !safeText(google.match.summaryPrefix, 256)) {\n throw new Error(`${path}: calendar.google.match.summaryPrefix must be 1-256 printable characters`);\n }\n for (const name of [\"organizerSelf\", \"requireAttendees\"] as const) {\n if (google.match[name] !== undefined && typeof google.match[name] !== \"boolean\") {\n throw new Error(`${path}: calendar.google.match.${name} must be boolean`);\n }\n }\n }\n if (enabled && !services.includes(\"db\")) throw new Error(`${path}: calendar service requires the db service`);\n}\n\nfunction assertOnly(value: Record<string, unknown>, allowed: string[], label: string): void {\n const extra = Object.keys(value).find((key) => !allowed.includes(key));\n if (extra) throw new Error(`${label}.${extra} is not supported`);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction safeText(value: unknown, max: number): value is string {\n return typeof value === \"string\" && value.trim().length > 0 && value.length <= max && !/[\\u0000-\\u001f\\u007f]/.test(value);\n}\n\nfunction safeHttpsUrl(value: unknown): value is string {\n if (typeof value !== \"string\" || value.length > 2_048) return false;\n try {\n const url = new URL(value);\n return url.protocol === \"https:\" && !url.username && !url.password && !url.hash;\n } catch {\n return false;\n }\n}\n\nfunction validId(value: unknown): value is string {\n return typeof value === \"string\" && /^[a-z0-9][a-z0-9-]*$/.test(value);\n}\n\nasync function loadConfigModule(path: string): Promise<OdlaProjectConfig> {\n if (path.endsWith(\".json\")) return JSON.parse(readFileSync(path, \"utf8\")) as OdlaProjectConfig;\n const mod = (await import(`${pathToFileURL(path).href}?t=${Date.now()}`)) as {\n default?: OdlaProjectConfig | (() => OdlaProjectConfig | Promise<OdlaProjectConfig>);\n config?: OdlaProjectConfig;\n };\n const value = mod.default ?? mod.config;\n if (typeof value === \"function\") return await value();\n return value as OdlaProjectConfig;\n}\n\nfunction trimSlash(value: string): string {\n return value.replace(/\\/+$/, \"\");\n}\n\nfunction unique(values: string[]): string[] {\n return [...new Set(values.filter(Boolean))];\n}\n","const PLATFORM_NOT_READY_CODES = new Set([\n \"calendar_google_oauth_not_configured\",\n \"calendar_token_vault_not_configured\",\n \"calendar_db_ingress_not_configured\",\n]);\n\n/**\n * Calendar registry request that completed with a non-2xx response. Preserves\n * the HTTP status and the platform's machine-readable `error.code` so callers\n * can branch on the code instead of parsing the redacted message.\n */\nexport class CalendarRequestError extends Error {\n /** HTTP status returned by the registry. */\n readonly status: number;\n /** Machine-readable `error.code` from the response body, when present. */\n readonly code?: string;\n\n constructor(message: string, status: number, code?: string) {\n super(message);\n this.name = \"CalendarRequestError\";\n this.status = status;\n if (code !== undefined) this.code = code;\n }\n}\n\n/**\n * True when the error is the platform reporting that its own calendar\n * connector is not yet configured (Google OAuth client, token vault, or DB\n * ingress). Only a platform operator can fix these, so provision reports them\n * as a resumable warning instead of aborting. Matches on the error code, not\n * the HTTP status — the code is the contract.\n */\nexport function isCalendarPlatformNotReady(error: unknown): error is CalendarRequestError & { code: string } {\n return error instanceof CalendarRequestError && error.code !== undefined && PLATFORM_NOT_READY_CODES.has(error.code);\n}\n","/**\n * Secret redaction shared by every command's output path and by doctor's\n * \"does this value look like a secret\" checks. Clerk publishable keys\n * (pk_test_/pk_live_) are public by design and are deliberately not matched.\n */\nconst REPLACEMENTS: Array<[RegExp, string]> = [\n [/odla_(sk|dev)_[A-Za-z0-9._-]+/g, \"odla_$1_[redacted]\"],\n [/\\bsk_(live|test)_[A-Za-z0-9]+/g, \"sk_$1_[redacted]\"],\n [/\\bsk-[A-Za-z0-9._-]+/g, \"sk-[redacted]\"],\n [/\\bwhsec_[A-Za-z0-9+/=]+/g, \"whsec_[redacted]\"],\n [/\\bo11y_[A-Za-z0-9]+/g, \"o11y_[redacted]\"],\n [/\\b(ghp|gho|github_pat)_[A-Za-z0-9_]+/g, \"$1_[redacted]\"],\n [/\\bAKIA[A-Z0-9]{12,}/g, \"AKIA[redacted]\"],\n];\n\n/**\n * Return `value` with every secret-shaped substring replaced by a `[redacted]`\n * placeholder that keeps the identifying prefix (e.g. `sk_live_[redacted]`).\n * Matches odla db keys (`odla_sk_`/`odla_dev_`), Clerk secret keys\n * (`sk_live_`/`sk_test_`), OpenAI keys (`sk-`), webhook signing secrets\n * (`whsec_`), o11y tokens (`o11y_`), GitHub tokens (`ghp_`/`gho_`/`github_pat_`),\n * and AWS access-key ids (`AKIA…`). Clerk publishable keys (`pk_test_`/\n * `pk_live_`) are public by design and intentionally left untouched. Used to\n * sanitize anything the CLI echoes (notably network error bodies) before it\n * reaches stdout/stderr. Non-matching input is returned unchanged.\n */\nexport function redactSecrets(value: string): string {\n let result = value;\n for (const [pattern, replacement] of REPLACEMENTS) result = result.replace(pattern, replacement);\n return result;\n}\n\n/** True when a value matches any known secret shape (used for detection, never display). */\nexport function looksSecret(value: string): boolean {\n return redactSecrets(value) !== value || value.includes(\"-----BEGIN\");\n}\n","import { CalendarRequestError } from \"./calendar-errors\";\nimport { redactSecrets } from \"./redact\";\nimport { platformAudience } from \"./token\";\n\nexport const CALENDAR_STATES = [\n \"not_connected\", \"authorizing\", \"needs_sync\", \"initial_sync\", \"healthy\", \"degraded\", \"disconnected\", \"failed\",\n] as const;\n/** Connection lifecycle reported by the registry; mirrors the platform's calendar states. */\nexport type CalendarConnectionState = (typeof CALENDAR_STATES)[number];\n\n/** Owner-visible, secret-free calendar connection and sync health. */\nexport interface CalendarStatus {\n env: string;\n enabled: boolean;\n /** True when the platform has provider credentials for this connection. */\n connected: boolean;\n provider: \"google\" | null;\n status: CalendarConnectionState;\n access?: \"read\";\n calendars: string[];\n attendeePolicy?: \"full\" | \"hashed\";\n /** True once a booking projection may have established the DB privacy policy. */\n attendeePolicyLocked?: boolean;\n bookingPageUrl?: string | null;\n grantedScopes: string[];\n attemptId?: string;\n lastSuccessfulSyncAt?: number;\n lastFullSyncAt?: number;\n watchExpiresAt?: number;\n bookingCount?: number;\n error?: { code?: string; message?: string };\n}\n\nexport interface CalendarHttpContext {\n platform: string;\n appId: string;\n env: string;\n token: string;\n fetch?: typeof fetch;\n}\n\nexport interface CalendarConnectionAttempt {\n attemptId: string;\n consentUrl: string;\n expiresAt: number;\n}\n\n/** One Google calendar the connected identity may select for mirroring. */\nexport interface AvailableGoogleCalendar {\n id: string;\n summary?: string;\n primary?: boolean;\n selected?: boolean;\n accessRole?: \"freeBusyReader\" | \"reader\" | \"writer\" | \"owner\";\n}\n\nexport async function readCalendarStatus(ctx: CalendarHttpContext): Promise<CalendarStatus> {\n return parseCalendarStatus(await calendarJson(ctx, \"\", {}), ctx.env);\n}\n\nexport async function discoverGoogleCalendars(ctx: CalendarHttpContext): Promise<AvailableGoogleCalendar[]> {\n const raw = await calendarJson(ctx, \"/calendars\", {});\n const value = record(raw);\n if (!value || !Array.isArray(value.calendars)) throw new Error(\"calendar discovery returned an invalid response\");\n return value.calendars.map((item, index) => {\n const calendar = record(item);\n const id = textField(calendar?.id, 1_024);\n if (!calendar || !id) throw new Error(`calendar discovery returned an invalid calendar at index ${index}`);\n const role = calendar.accessRole;\n if (role !== undefined && role !== \"freeBusyReader\" && role !== \"reader\" && role !== \"writer\" && role !== \"owner\") {\n throw new Error(`calendar discovery returned an invalid access role at index ${index}`);\n }\n return {\n id,\n ...optionalText(\"summary\", calendar.summary, 500),\n ...(typeof calendar.primary === \"boolean\" ? { primary: calendar.primary } : {}),\n ...(typeof calendar.selected === \"boolean\" ? { selected: calendar.selected } : {}),\n ...(typeof role === \"string\" ? { accessRole: role } : {}),\n };\n });\n}\n\nexport async function applyCalendarSettings(ctx: CalendarHttpContext, bookingPageUrl: string | null): Promise<CalendarStatus> {\n return parseCalendarStatus(await calendarJson(ctx, \"\", { method: \"PUT\", body: JSON.stringify({ bookingPageUrl }) }), ctx.env);\n}\n\nexport async function startCalendarConnection(ctx: CalendarHttpContext): Promise<CalendarConnectionAttempt> {\n const raw = await calendarJson(ctx, \"/google/connect\", { method: \"POST\", body: \"{}\" });\n const value = wrapped(raw, \"attempt\");\n const attemptId = textField(value.attemptId, 180);\n const consentUrl = textField(value.consentUrl, 4_096);\n const expiresAt = timestamp(value.expiresAt);\n if (!attemptId || !consentUrl || expiresAt === undefined) throw new Error(\"calendar connect returned an invalid attempt\");\n return { attemptId, consentUrl, expiresAt };\n}\n\nexport async function pollCalendarConnection(ctx: CalendarHttpContext, attemptId: string): Promise<CalendarStatus> {\n return parseCalendarStatus(\n await calendarJson(ctx, `/google/connect/${encodeURIComponent(identifier(attemptId, \"attemptId\"))}`, {}),\n ctx.env,\n );\n}\n\nexport async function requestCalendarResync(ctx: CalendarHttpContext): Promise<CalendarStatus> {\n return parseCalendarStatus(await calendarJson(ctx, \"/resync\", { method: \"POST\", body: \"{}\" }), ctx.env);\n}\n\nexport async function requestCalendarDisconnect(ctx: CalendarHttpContext): Promise<CalendarStatus> {\n return parseCalendarStatus(\n await calendarJson(ctx, \"/disconnect\", { method: \"POST\", body: JSON.stringify({ purge: false }) }),\n ctx.env,\n );\n}\n\nexport function parseCalendarStatus(raw: unknown, env: string): CalendarStatus {\n const outer = wrapped(raw, \"calendar\");\n const value = record(outer.attempt) ?? record(outer.status) ?? outer;\n const connection = record(value.connection) ?? {};\n const sync = record(value.sync) ?? record(connection.sync) ?? {};\n const config = record(value.config) ?? record(outer.config) ?? {};\n const googleConfig = record(config.google) ?? config;\n const watches = record(value.watches) ?? {};\n const stateValue = calendarState(value.status ?? value.state ?? connection.status ?? connection.state);\n if (!stateValue) {\n throw new Error(\"calendar status returned an invalid connection state\");\n }\n const providerValue = value.provider ?? connection.provider ?? config.provider ?? (config.google ? \"google\" : undefined);\n if (providerValue !== undefined && providerValue !== null && providerValue !== \"google\") {\n throw new Error(\"calendar status returned an unsupported provider\");\n }\n const accessValue = value.access ?? connection.access ?? config.access ?? googleConfig.access;\n if (accessValue !== undefined && accessValue !== \"read\") throw new Error(\"calendar status returned unsupported access\");\n const policyValue = value.attendeePolicy ?? config.attendeePolicy ?? googleConfig.attendeePolicy;\n if (policyValue !== undefined && policyValue !== \"full\" && policyValue !== \"hashed\") {\n throw new Error(\"calendar status returned an invalid attendee policy\");\n }\n const errorValue = record(value.error) ?? record(connection.error);\n const errorCode = textField(value.lastErrorCode, 128);\n const bookingPageValue = Object.hasOwn(value, \"bookingPageUrl\")\n ? value.bookingPageUrl\n : Object.hasOwn(config, \"bookingPageUrl\") ? config.bookingPageUrl : googleConfig.bookingPageUrl;\n return {\n env,\n enabled: typeof value.enabled === \"boolean\" ? value.enabled : true,\n connected: typeof (value.connected ?? connection.connected) === \"boolean\"\n ? Boolean(value.connected ?? connection.connected)\n : [\"needs_sync\", \"initial_sync\", \"healthy\", \"degraded\"].includes(stateValue),\n provider: providerValue === \"google\" ? \"google\" : null,\n status: stateValue,\n ...(accessValue === \"read\" ? { access: \"read\" as const } : {}),\n calendars: calendarIds(value.configuredCalendars ?? value.calendars ?? config.calendars ?? googleConfig.calendars),\n ...(policyValue === \"full\" || policyValue === \"hashed\" ? { attendeePolicy: policyValue } : {}),\n ...(typeof value.attendeePolicyLocked === \"boolean\"\n ? { attendeePolicyLocked: value.attendeePolicyLocked } : {}),\n ...optionalNullableUrl(\"bookingPageUrl\", bookingPageValue),\n grantedScopes: stringList(value.grantedScopes ?? connection.grantedScopes ?? connection.scopes),\n ...optionalText(\"attemptId\", value.attemptId ?? connection.attemptId, 180),\n ...optionalNumber(\"lastSuccessfulSyncAt\", value.lastSuccessfulSyncAt ?? sync.lastSuccessfulSyncAt),\n ...optionalNumber(\"lastFullSyncAt\", value.lastFullSyncAt ?? sync.lastFullSyncAt),\n ...optionalNumber(\"watchExpiresAt\", value.watchExpiresAt ?? sync.watchExpiresAt ?? watches.nextExpirationAt),\n ...optionalInteger(\"bookingCount\", value.bookingCount ?? sync.bookingCount),\n ...(errorValue || errorCode ? { error: {\n ...(textField(errorValue?.code, 128) ? { code: textField(errorValue?.code, 128) } : {}),\n ...(textField(errorValue?.message, 500) ? { message: textField(errorValue?.message, 500) } : {}),\n ...(!errorValue && errorCode ? { code: errorCode } : {}),\n } } : {}),\n };\n}\n\nfunction calendarState(value: unknown): CalendarConnectionState | null {\n if (typeof value !== \"string\") return null;\n if ((CALENDAR_STATES as readonly string[]).includes(value)) return value as CalendarConnectionState;\n const legacy: Record<string, CalendarConnectionState> = {\n disabled: \"not_connected\",\n disconnected: \"disconnected\",\n connecting: \"authorizing\",\n syncing: \"initial_sync\",\n ready: \"healthy\",\n error: \"failed\",\n };\n return legacy[value] ?? null;\n}\n\nasync function calendarJson(ctx: CalendarHttpContext, suffix: string, init: RequestInit): Promise<unknown> {\n const platform = platformAudience(ctx.platform);\n const appId = identifier(ctx.appId, \"appId\");\n const env = identifier(ctx.env, \"env\");\n const url = new URL(`/registry/apps/${encodeURIComponent(appId)}/calendar${suffix}`, platform);\n url.searchParams.set(\"env\", env);\n const token = credential(ctx.token);\n let response: Response;\n try {\n response = await (ctx.fetch ?? fetch)(url, {\n ...init,\n redirect: \"error\",\n credentials: \"omit\",\n headers: { authorization: `Bearer ${token}`, \"content-type\": \"application/json\", ...init.headers },\n });\n } catch (error) {\n throw new Error(`calendar request failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n const body = await response.json().catch(() => ({})) as { error?: { code?: unknown; message?: unknown } };\n if (!response.ok) {\n const code = textField(body.error?.code, 128);\n const message = textField(body.error?.message, 500);\n const detail = `${code ? ` ${code}` : \"\"}${message ? `: ${message}` : \"\"}`;\n throw new CalendarRequestError(redactSecrets(`calendar request failed (${response.status})${detail}`), response.status, code);\n }\n return body;\n}\n\nfunction wrapped(raw: unknown, key: string): Record<string, unknown> {\n const outer = record(raw);\n if (!outer) throw new Error(\"calendar returned an invalid response\");\n return record(outer[key]) ?? outer;\n}\n\nfunction record(value: unknown): Record<string, unknown> | null {\n return value !== null && typeof value === \"object\" && !Array.isArray(value) ? value as Record<string, unknown> : null;\n}\n\nfunction textField(value: unknown, max: number): string | undefined {\n return typeof value === \"string\" && value.length > 0 && value.length <= max && !/[\\u0000-\\u001f\\u007f]/.test(value) ? value : undefined;\n}\n\nfunction stringList(value: unknown): string[] {\n return Array.isArray(value) ? [...new Set(value.filter((item): item is string => !!textField(item, 4_096)))] : [];\n}\n\nfunction calendarIds(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return [...new Set(value.flatMap((item) => {\n if (typeof item === \"string\") return textField(item, 4_096) ? [item] : [];\n const calendar = record(item);\n const id = textField(calendar?.id, 4_096);\n return id && calendar?.selected !== false ? [id] : [];\n }))];\n}\n\nfunction timestamp(value: unknown): number | undefined {\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) return value;\n if (typeof value === \"string\") {\n const parsed = Date.parse(value);\n if (Number.isFinite(parsed)) return parsed;\n }\n return undefined;\n}\n\nfunction optionalText<K extends string>(key: K, value: unknown, max: number): { [P in K]?: string } {\n const parsed = textField(value, max);\n return parsed ? { [key]: parsed } as { [P in K]?: string } : {};\n}\n\nfunction optionalNumber<K extends string>(key: K, value: unknown): { [P in K]?: number } {\n const parsed = timestamp(value);\n return parsed === undefined ? {} : { [key]: parsed } as { [P in K]?: number };\n}\n\nfunction optionalInteger<K extends string>(key: K, value: unknown): { [P in K]?: number } {\n return Number.isSafeInteger(value) && (value as number) >= 0 ? { [key]: value } as { [P in K]?: number } : {};\n}\n\nfunction optionalNullableUrl<K extends string>(key: K, value: unknown): { [P in K]?: string | null } {\n if (value === null) return { [key]: null } as { [P in K]?: string | null };\n const parsed = textField(value, 4_096);\n return parsed ? { [key]: parsed } as { [P in K]?: string | null } : {};\n}\n\nfunction identifier(value: string, name: string): string {\n if (typeof value !== \"string\" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,179}$/.test(value)) throw new Error(`${name} is invalid`);\n return value;\n}\n\nfunction credential(value: string): string {\n if (typeof value !== \"string\" || value.length < 8 || value.length > 8_192 || /\\s|[\\u0000-\\u001f\\u007f]/.test(value)) {\n throw new Error(\"calendar requires an odla developer token\");\n }\n return value;\n}\n","/** Abort-aware delay shared by new-attempt and existing-sync polling. */\nexport async function waitForCalendarPoll(milliseconds: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) throw signal.reason ?? new Error(\"calendar connection aborted\");\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(resolve, milliseconds);\n signal?.addEventListener(\"abort\", () => {\n clearTimeout(timer);\n reject(signal.reason ?? new Error(\"calendar connection aborted\"));\n }, { once: true });\n });\n}\n","import { calendarBookingPageUrl, calendarServiceConfig, loadProjectConfig } from \"./config\";\nimport {\n applyCalendarSettings,\n discoverGoogleCalendars,\n pollCalendarConnection,\n readCalendarStatus,\n requestCalendarDisconnect,\n requestCalendarResync,\n startCalendarConnection,\n} from \"./calendar-http\";\nimport type { CalendarHttpContext, CalendarStatus } from \"./calendar-http\";\nimport type { AvailableGoogleCalendar } from \"./calendar-http\";\nimport { waitForCalendarPoll } from \"./calendar-poll\";\nimport { openUrl } from \"./open\";\nimport { approvalBrowser, getDeveloperToken, platformAudience } from \"./token\";\n\n/** Shared inputs for the calendar lifecycle commands (status, connect,\n * calendars, resync, disconnect): the project config path and env, plus\n * injectable token, output, browser, clock, and polling hooks so agents and\n * tests can drive the flow deterministically. */\nexport interface CalendarLifecycleOptions {\n /** Path to the checked-in odla project config. */ configPath: string;\n /** Configured environment; defaults to dev when present. */ env?: string;\n /** Existing developer-token override. */ token?: string;\n /** Existing odla account email used only for a fresh handshake. */ email?: string;\n open?: boolean; yes?: boolean; json?: boolean;\n fetch?: typeof fetch; stdout?: Pick<typeof console, \"log\" | \"error\">;\n openConsentUrl?: (url: string) => Promise<void>;\n wait?: (milliseconds: number, signal?: AbortSignal) => Promise<void>;\n pollTimeoutMs?: number; now?: () => number; signal?: AbortSignal;\n}\n\n/** Read the owner-visible Google connection and mirror health for one env. */\nexport async function calendarStatus(options: CalendarLifecycleOptions): Promise<CalendarStatus> {\n const { ctx, out } = await lifecycleContext(options);\n const status = await readCalendarStatus(ctx);\n printStatus(status, options.json === true, out);\n return status;\n}\n\n/** List calendars visible to the connected Google identity for config authoring. */\nexport async function calendarCalendars(options: CalendarLifecycleOptions): Promise<AvailableGoogleCalendar[]> {\n const { ctx, out } = await lifecycleContext(options);\n const calendars = await discoverGoogleCalendars(ctx);\n if (options.json) out.log(JSON.stringify({ env: ctx.env, calendars }, null, 2));\n else if (calendars.length === 0) out.log(`${ctx.env}: no Google calendars available`);\n else for (const calendar of calendars) {\n out.log(`${calendar.selected ? \"✓\" : calendar.primary ? \"*\" : \" \"} ${calendar.id}${calendar.summary ? ` — ${calendar.summary}` : \"\"}${calendar.accessRole ? ` (${calendar.accessRole})` : \"\"}`);\n }\n return calendars;\n}\n\n/** Apply the public booking page setting, then complete Google consent + initial sync. */\nexport async function calendarConnect(options: CalendarLifecycleOptions): Promise<CalendarStatus> {\n const { cfg, ctx, out } = await lifecycleContext(options);\n productionConsent(ctx.env, options.yes, \"connect calendar\");\n const page = calendarBookingPageUrl(cfg, ctx.env);\n const applied = page === undefined ? await readCalendarStatus(ctx) : await applyCalendarSettings(ctx, page);\n const connectOptions = connectionOptions(options, out);\n return await continueConnectedCalendar(ctx, applied, connectOptions, false)\n ?? connectWithContext(ctx, connectOptions);\n}\n\n/** Provision applies public embed/link configuration through the owner route. */\nexport async function applyCalendarBookingPage(\n ctx: CalendarHttpContext,\n bookingPageUrl: string | null | undefined,\n out: Pick<typeof console, \"log\">,\n): Promise<CalendarStatus | null> {\n if (bookingPageUrl === undefined) return null;\n const status = await applyCalendarSettings(ctx, bookingPageUrl);\n out.log(`${ctx.env}: calendar booking page ${bookingPageUrl ? \"set\" : \"cleared\"}`);\n return status;\n}\n\n/** Ask the hosted connector for an immediate incremental/full recovery sync. */\nexport async function calendarResync(options: CalendarLifecycleOptions): Promise<CalendarStatus> {\n const { ctx, out } = await lifecycleContext(options);\n productionConsent(ctx.env, options.yes, \"resync calendar\");\n const status = await requestCalendarResync(ctx);\n out.log(`${ctx.env}: calendar resync requested (${status.status})`);\n return status;\n}\n\n/** Stop watches and delete this connection's encrypted platform token/cursors\n * without purging the mirror or revoking the shared Google project grant. */\nexport async function calendarDisconnect(options: CalendarLifecycleOptions): Promise<CalendarStatus> {\n if (!options.yes) throw new Error('calendar disconnect requires --yes');\n const { ctx, out } = await lifecycleContext(options);\n const status = await requestCalendarDisconnect(ctx);\n out.log(`${ctx.env}: calendar disconnected; retained mirror rows may now be stale`);\n return status;\n}\n\n/** Provision's idempotent connection phase after service enablement/config apply. */\nexport async function ensureCalendarConnected(\n ctx: CalendarHttpContext,\n options: Omit<CalendarLifecycleOptions, \"configPath\" | \"env\" | \"token\" | \"fetch\">,\n): Promise<CalendarStatus> {\n const out = options.stdout ?? console;\n const current = await readCalendarStatus(ctx);\n const connectOptions = connectionOptions(options, out);\n return await continueConnectedCalendar(ctx, current, connectOptions, true)\n ?? connectWithContext(ctx, connectOptions);\n}\n\nasync function lifecycleContext(options: CalendarLifecycleOptions): Promise<{\n cfg: Awaited<ReturnType<typeof loadProjectConfig>>;\n ctx: CalendarHttpContext;\n out: Pick<typeof console, \"log\" | \"error\">;\n}> {\n const cfg = await loadProjectConfig(options.configPath);\n if (!cfg.services.includes(\"calendar\")) throw new Error('calendar service is not enabled in config services');\n const env = options.env ?? (cfg.envs.includes(\"dev\") ? \"dev\" : cfg.envs[0]);\n if (!env || !cfg.envs.includes(env)) throw new Error(`env \"${env ?? \"\"}\" is not declared in ${options.configPath}`);\n // Resolving this also asserts that the authored Google block covers the env.\n calendarServiceConfig(cfg, env);\n const out = options.stdout ?? console;\n const doFetch = options.fetch ?? fetch;\n const token = await getDeveloperToken(\n cfg,\n {\n configPath: cfg.configPath,\n token: options.token,\n email: options.email,\n open: options.open,\n openApprovalUrl: options.openConsentUrl,\n },\n doFetch,\n out,\n );\n return { cfg, ctx: { platform: cfg.platformUrl, appId: cfg.app.id, env, token, fetch: doFetch }, out };\n}\n\nfunction connectionOptions(\n options: Pick<CalendarLifecycleOptions, \"open\" | \"openConsentUrl\" | \"wait\" | \"pollTimeoutMs\" | \"now\" | \"signal\">,\n out: Pick<typeof console, \"log\" | \"error\">,\n): ConnectContextOptions {\n const browser = approvalBrowser({ open: options.open });\n return {\n out,\n open: browser.open,\n openConsentUrl: options.openConsentUrl,\n wait: options.wait,\n pollTimeoutMs: options.pollTimeoutMs,\n now: options.now,\n signal: options.signal,\n };\n}\n\ninterface ConnectContextOptions {\n out: Pick<typeof console, \"log\" | \"error\">;\n open: boolean;\n openConsentUrl?: (url: string) => Promise<void>;\n wait?: (milliseconds: number, signal?: AbortSignal) => Promise<void>;\n pollTimeoutMs?: number;\n now?: () => number;\n signal?: AbortSignal;\n}\n\n/** Continue an installed provider connection without accidentally replacing\n * it. `needs_sync` means config is confirmed/staged but no current mirror has\n * completed; it needs a resync, not another Google OAuth grant. */\nasync function continueConnectedCalendar(\n ctx: CalendarHttpContext,\n current: CalendarStatus,\n options: ConnectContextOptions,\n reuseDegraded: boolean,\n): Promise<CalendarStatus | null> {\n if (current.status === \"healthy\" || (reuseDegraded && current.status === \"degraded\")) {\n options.out.log(`${ctx.env}: calendar ${reuseDegraded ? \"connected\" : \"already connected\"} (${current.status})`);\n return current;\n }\n // Explicit `calendar connect` is the repair path for a degraded grant;\n // idempotent provision keeps serving the last successful mirror.\n if (current.status === \"degraded\") return null;\n if (current.status === \"needs_sync\") {\n if (!current.connected) return null;\n options.out.log(`${ctx.env}: calendar configuration needs sync`);\n const synced = await requestCalendarResync(ctx);\n options.out.log(`${ctx.env}: calendar ${synced.status.replaceAll(\"_\", \" \")}`);\n return synced;\n }\n if (current.status === \"failed\" && current.connected) {\n const reason = current.error?.message ?? current.error?.code;\n throw new Error(`calendar connection failed${reason ? `: ${reason}` : \"\"}; inspect status and resync or reconnect explicitly`);\n }\n const waitingForExisting = current.status === \"authorizing\"\n || (current.status === \"initial_sync\" && current.connected);\n if (!waitingForExisting) return null;\n\n const now = options.now ?? Date.now;\n const deadline = now() + pollTimeout(options.pollTimeoutMs);\n const wait = options.wait ?? waitForCalendarPoll;\n let prior = \"\";\n while (now() < deadline) {\n if (options.signal?.aborted) throw options.signal.reason ?? new Error(\"calendar connection aborted\");\n const status = await readCalendarStatus(ctx);\n if (status.status !== prior) {\n options.out.log(`${ctx.env}: calendar ${status.status.replaceAll(\"_\", \" \")}`);\n prior = status.status;\n }\n if (status.status === \"healthy\" || (reuseDegraded && status.status === \"degraded\")) return status;\n if (status.status === \"degraded\") return null;\n if (status.status === \"needs_sync\") return requestCalendarResync(ctx);\n if (status.status === \"failed\" && status.connected) {\n const reason = status.error?.message ?? status.error?.code;\n throw new Error(`calendar connection failed${reason ? `: ${reason}` : \"\"}; inspect status and resync or reconnect explicitly`);\n }\n if (status.status !== \"authorizing\" && (status.status !== \"initial_sync\" || !status.connected)) return null;\n await wait(Math.min(2_000, Math.max(0, deadline - now())), options.signal);\n }\n throw new Error('Existing Google Calendar authorization or initial sync timed out; run \"odla-ai calendar status\" and retry');\n}\n\nasync function connectWithContext(ctx: CalendarHttpContext, options: ConnectContextOptions): Promise<CalendarStatus> {\n const attempt = await startCalendarConnection(ctx);\n const consentUrl = trustedCalendarConsentUrl(ctx.platform, attempt.consentUrl);\n options.out.log(`${ctx.env}: Google Calendar consent: ${consentUrl}`);\n if (options.open) {\n await (options.openConsentUrl ?? openUrl)(consentUrl);\n options.out.log(`${ctx.env}: opened Google Calendar consent in your browser`);\n }\n const now = options.now ?? Date.now;\n const timeout = pollTimeout(options.pollTimeoutMs);\n const deadline = Math.min(attempt.expiresAt, now() + timeout);\n const wait = options.wait ?? waitForCalendarPoll;\n let prior = \"\";\n while (now() < deadline) {\n if (options.signal?.aborted) throw options.signal.reason ?? new Error(\"calendar connection aborted\");\n const status = await pollCalendarConnection(ctx, attempt.attemptId);\n if (status.status !== prior) {\n options.out.log(`${ctx.env}: calendar ${status.status.replaceAll(\"_\", \" \")}`);\n prior = status.status;\n }\n if (status.status === \"healthy\" || status.status === \"degraded\") return status;\n if (status.status === \"failed\" || status.status === \"disconnected\" || status.status === \"not_connected\") {\n const reason = status.error?.message ?? status.error?.code;\n throw new Error(`calendar connection ${status.status}${reason ? `: ${reason}` : \"\"}`);\n }\n await wait(Math.min(2_000, Math.max(0, deadline - now())), options.signal);\n }\n throw new Error('Google Calendar consent or initial sync timed out; run \"odla-ai calendar status\" and retry connect');\n}\n\nexport function trustedCalendarConsentUrl(platform: string, value: string): string {\n const origin = platformAudience(platform);\n let url: URL;\n try { url = value.startsWith(\"/\") ? new URL(value, origin) : new URL(value); } catch { throw new Error(\"odla.ai returned an invalid calendar consent URL\"); }\n const platformPage = url.origin === origin;\n const googlePage = url.origin === \"https://accounts.google.com\" && url.pathname === \"/o/oauth2/v2/auth\";\n if ((!platformPage && !googlePage) || url.username || url.password || url.hash) {\n throw new Error(\"odla.ai returned an untrusted calendar consent URL\");\n }\n return url.toString();\n}\n\nfunction pollTimeout(value = 10 * 60_000): number {\n if (!Number.isSafeInteger(value) || value < 1_000 || value > 60 * 60_000) throw new Error(\"calendar poll timeout must be 1000-3600000ms\");\n return value;\n}\n\nexport { waitForCalendarPoll } from \"./calendar-poll\";\n\nfunction productionConsent(env: string, yes: boolean | undefined, action: string): void {\n if ((env === \"prod\" || env === \"production\") && !yes) throw new Error(`refusing to ${action} for \"${env}\" without --yes`);\n}\n\nfunction printStatus(status: CalendarStatus, json: boolean, out: Pick<typeof console, \"log\">): void {\n if (json) {\n out.log(JSON.stringify(status, null, 2));\n return;\n }\n out.log(`calendar: ${status.provider ?? \"none\"}/${status.status} (${status.env})`);\n out.log(` access: ${status.access ?? \"not granted\"}`);\n out.log(` calendars: ${status.calendars.length ? status.calendars.join(\", \") : \"none\"}`);\n if (status.attendeePolicy) {\n out.log(` attendee policy: ${status.attendeePolicy}${status.attendeePolicyLocked ? \" (locked)\" : \"\"}`);\n }\n if (status.bookingPageUrl !== undefined) out.log(` booking page: ${status.bookingPageUrl ?? \"not configured\"}`);\n out.log(` last sync: ${status.lastSuccessfulSyncAt === undefined ? \"never\" : new Date(status.lastSuccessfulSyncAt).toISOString()}`);\n if (status.bookingCount !== undefined) out.log(` bookings: ${status.bookingCount}`);\n if (status.error?.code || status.error?.message) out.log(` error: ${status.error.code ?? \"error\"}${status.error.message ? ` — ${status.error.message}` : \"\"}`);\n}\n","import { execFileSync } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { looksSecret } from \"./redact\";\nimport { gitignoreEntry } from \"./local\";\nimport { findWranglerConfig, readWranglerConfig } from \"./wrangler\";\nimport type { AppRules } from \"./types\";\n\n/**\n * Rules lint: a literal \"true\" grants the action to every client. `view` may\n * be deliberate for public content — allowlist those namespaces via\n * `db.publicRead`; writes are never safely \"true\".\n */\nexport function lintRules(rules: AppRules | undefined, entities: string[], publicRead: string[]): string[] {\n const warnings: string[] = [];\n if (!rules) return warnings;\n for (const [ns, actions] of Object.entries(rules)) {\n for (const [action, expr] of Object.entries(actions)) {\n if (typeof expr !== \"string\" || expr.trim() !== \"true\") continue;\n if (action === \"view\" && publicRead.includes(ns)) continue;\n warnings.push(\n action === \"view\"\n ? `rules.${ns}.view is \"true\" — public read; add \"${ns}\" to db.publicRead if intended`\n : `rules.${ns}.${action} is \"true\" — any client can ${action} ${ns} rows`,\n );\n }\n }\n for (const entity of entities) {\n if (!(entity in rules)) warnings.push(`schema entity \"${entity}\" has no rules entry (all client access denied)`);\n }\n return warnings;\n}\n\nexport type ExecLike = (cmd: string, args: string[], cwd: string) => string;\n\nconst defaultExec: ExecLike = (cmd, args, cwd) => execFileSync(cmd, args, { cwd, encoding: \"utf8\", stdio: [\"ignore\", \"pipe\", \"ignore\"] });\n\n/** Credential files that must never be committed. Silent when git is absent. */\nexport function trackedSecretFiles(rootDir: string, exec: ExecLike = defaultExec, localPaths: string[] = []): string[] {\n let output: string;\n try {\n const custom = localPaths\n .map((path) => gitignoreEntry(rootDir, path))\n .filter((path): path is string => !!path);\n output = exec(\"git\", [\"ls-files\", \"--\", \".dev.vars\", \".odla\", ...custom], rootDir);\n } catch {\n return [];\n }\n return output\n .split(/\\r?\\n/)\n .filter(Boolean)\n .map((path) => `${path} is tracked by git — run \"git rm --cached ${path}\" and commit; it belongs in .gitignore`);\n}\n\n/** Wrangler config sanity: the assets-dir footgun, secret-looking vars. */\nexport function wranglerWarnings(rootDir: string): string[] {\n const configPath = findWranglerConfig(rootDir);\n if (!configPath) return [];\n const config = readWranglerConfig(configPath);\n if (!config) return [];\n\n const warnings: string[] = [];\n const blocks: Array<{ label: string; block: Record<string, unknown> }> = [{ label: \"\", block: config }];\n const envs = config.env;\n if (envs && typeof envs === \"object\") {\n for (const [name, block] of Object.entries(envs as Record<string, unknown>)) {\n if (block && typeof block === \"object\") blocks.push({ label: `env.${name}.`, block: block as Record<string, unknown> });\n }\n }\n\n for (const { label, block } of blocks) {\n const assets = block.assets as { directory?: string } | undefined;\n if (assets?.directory) {\n const dir = resolve(rootDir, assets.directory);\n if (dir === resolve(rootDir)) {\n warnings.push(`${label}assets.directory is the project root — point it at a dedicated build dir (wrangler dev fails with \"spawn EBADF\")`);\n } else if (existsSync(join(dir, \"node_modules\"))) {\n warnings.push(`${label}assets.directory contains node_modules — wrangler dev's watcher will exhaust file descriptors`);\n }\n }\n const vars = block.vars;\n if (vars && typeof vars === \"object\") {\n for (const [name, value] of Object.entries(vars as Record<string, unknown>)) {\n if (name === \"ODLA_API_KEY\" || name === \"ODLA_O11Y_TOKEN\" || (typeof value === \"string\" && looksSecret(value))) {\n warnings.push(`wrangler ${label}vars.${name} looks like a secret — use \"odla-ai secrets push\" / wrangler secret put, never vars`);\n }\n }\n }\n }\n\n const pkg = readPackageJson(rootDir);\n if (pkg && typeof pkg.scripts === \"object\" && pkg.scripts && \"deploy\" in (pkg.scripts as Record<string, unknown>)) {\n warnings.push(`package.json has a script named \"deploy\" — CI may auto-deploy it; rename to deploy:app`);\n }\n return warnings;\n}\n\n/** Offline checks for the source/config work that provisioning cannot infer\n * safely. The CLI owns control-plane enablement and secret delivery; these\n * warnings keep the remaining application edits visible instead of letting a\n * successfully provisioned but uninstrumented Worker look complete. */\nexport function o11yProjectWarnings(rootDir: string): string[] {\n const warnings: string[] = [];\n const pkg = readPackageJson(rootDir);\n const dependencies = pkg?.dependencies as Record<string, unknown> | undefined;\n const devDependencies = pkg?.devDependencies as Record<string, unknown> | undefined;\n if (!dependencies?.[\"@odla-ai/o11y\"]) {\n warnings.push(\n devDependencies?.[\"@odla-ai/o11y\"]\n ? \"@odla-ai/o11y is a devDependency — move it to dependencies so the Worker can import it\"\n : 'Worker instrumentation is missing @odla-ai/o11y — install it and wrap the handler with \"withObservability\"',\n );\n }\n\n const configPath = findWranglerConfig(rootDir);\n const config = configPath ? readWranglerConfig(configPath) : null;\n if (!configPath || !config) {\n warnings.push(\"cannot verify o11y Worker instrumentation — add a parseable wrangler.jsonc/json config\");\n return warnings;\n }\n\n const main = typeof config.main === \"string\" ? resolve(rootDir, config.main) : null;\n if (!main || !existsSync(main)) {\n warnings.push(\"cannot verify o11y Worker instrumentation — wrangler main is missing or unreadable\");\n } else {\n let source = \"\";\n try {\n source = readFileSync(main, \"utf8\");\n } catch {\n // The warning below is intentionally the same for an unreadable source.\n }\n if (!/\\bwithObservability\\b/.test(source)) {\n warnings.push(`wrangler entrypoint ${config.main as string} does not reference withObservability`);\n }\n }\n\n const flags = Array.isArray(config.compatibility_flags) ? config.compatibility_flags : [];\n if (!flags.includes(\"nodejs_compat\")) {\n warnings.push('wrangler compatibility_flags is missing \"nodejs_compat\" required by @odla-ai/o11y');\n }\n return warnings;\n}\n\n/** Source-side calendar SDK check. OAuth and sync health remain platform-owned. */\nexport function calendarProjectWarnings(rootDir: string): string[] {\n const pkg = readPackageJson(rootDir);\n const dependencies = pkg?.dependencies as Record<string, unknown> | undefined;\n const devDependencies = pkg?.devDependencies as Record<string, unknown> | undefined;\n if (dependencies?.[\"@odla-ai/calendar\"]) return [];\n return [\n devDependencies?.[\"@odla-ai/calendar\"]\n ? \"@odla-ai/calendar is a devDependency — move it to dependencies so trusted Worker code can import it\"\n : \"calendar service is enabled but @odla-ai/calendar is not installed in dependencies\",\n ];\n}\n\nfunction readPackageJson(rootDir: string): Record<string, unknown> | null {\n try {\n return JSON.parse(readFileSync(join(rootDir, \"package.json\"), \"utf8\")) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n","import { spawn } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport interface RunResult {\n code: number;\n stdout: string;\n stderr: string;\n}\n\n/** Subprocess seam: injectable in tests, `defaultRunner` in production. */\nexport type CommandRunner = (cmd: string, args: string[], opts?: { input?: string; cwd?: string }) => Promise<RunResult>;\n\nexport const defaultRunner: CommandRunner = (cmd, args, opts) =>\n new Promise((resolvePromise, reject) => {\n const child = spawn(cmd, args, { cwd: opts?.cwd, stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n let stdout = \"\";\n let stderr = \"\";\n child.stdout.on(\"data\", (chunk: Buffer) => (stdout += chunk.toString()));\n child.stderr.on(\"data\", (chunk: Buffer) => (stderr += chunk.toString()));\n child.on(\"error\", reject);\n child.on(\"close\", (code) => resolvePromise({ code: code ?? 1, stdout, stderr }));\n child.stdin.end(opts?.input ?? \"\");\n });\n\nconst WRANGLER_CONFIG_FILES = [\"wrangler.jsonc\", \"wrangler.json\", \"wrangler.toml\"];\n\nexport function findWranglerConfig(rootDir: string): string | null {\n for (const name of WRANGLER_CONFIG_FILES) {\n const path = join(rootDir, name);\n if (existsSync(path)) return path;\n }\n return null;\n}\n\n/** Parses wrangler.json/jsonc. Returns null for .toml (unparsed) or invalid JSON. */\nexport function readWranglerConfig(path: string): Record<string, unknown> | null {\n if (path.endsWith(\".toml\")) return null;\n try {\n return JSON.parse(stripJsonComments(readFileSync(path, \"utf8\"))) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\n/** Removes // and both-slash block comments without touching string contents. */\nexport function stripJsonComments(text: string): string {\n let result = \"\";\n let inString = false;\n for (let i = 0; i < text.length; i++) {\n const ch = text[i]!;\n if (inString) {\n result += ch;\n if (ch === \"\\\\\") {\n result += text[i + 1] ?? \"\";\n i++;\n } else if (ch === '\"') {\n inString = false;\n }\n continue;\n }\n if (ch === '\"') {\n inString = true;\n result += ch;\n continue;\n }\n if (ch === \"/\" && text[i + 1] === \"/\") {\n while (i < text.length && text[i] !== \"\\n\") i++;\n result += \"\\n\";\n continue;\n }\n if (ch === \"/\" && text[i + 1] === \"*\") {\n i += 2;\n while (i < text.length && !(text[i] === \"*\" && text[i + 1] === \"/\")) i++;\n i++;\n continue;\n }\n result += ch;\n }\n return result;\n}\n\nexport async function wranglerLoggedIn(run: CommandRunner, cwd: string): Promise<boolean> {\n try {\n const result = await run(\"npx\", [\"wrangler\", \"whoami\"], { cwd });\n return result.code === 0 && !/not authenticated/i.test(`${result.stdout}${result.stderr}`);\n } catch {\n return false;\n }\n}\n\n/** Pipes the value via stdin — it never appears on argv or in process listings. */\nexport function wranglerPutSecret(\n run: CommandRunner,\n opts: { name: string; value: string; env?: string; cwd: string },\n): Promise<RunResult> {\n const args = [\"wrangler\", \"secret\", \"put\", opts.name, ...(opts.env ? [\"--env\", opts.env] : [])];\n return run(\"npx\", args, { input: opts.value, cwd: opts.cwd });\n}\n","import { buildPlan, calendarBookingPageUrl, calendarServiceConfig, loadProjectConfig, resolveDataExport, rulesFromSchema, serializedEntities } from \"./config\";\nimport { calendarProjectWarnings, lintRules, o11yProjectWarnings, trackedSecretFiles, wranglerWarnings } from \"./doctor-checks\";\nimport { readCredentials } from \"./local\";\nimport type { AppRules } from \"./types\";\n\nexport interface DoctorOptions {\n configPath: string;\n stdout?: Pick<typeof console, \"log\" | \"error\">;\n}\n\n/**\n * Validate and summarize an odla project config entirely offline — no network\n * calls and no file writes. Loads `configPath`, builds the provision plan, and\n * resolves the schema and rules (synthesizing deny-all rules from the schema\n * when `db.rules` is omitted and `db.defaultRules` isn't `false`), then prints a\n * summary line for the app, envs, services, schema entity count, rules namespace\n * count, and AI provider.\n *\n * It then collects warnings for the mistakes provision can't fix silently: a\n * schema with no entities, a rules namespace with no matching entity, the `ai`\n * service enabled without an `ai.provider`, `auth.clerk` entries that reference\n * an unset env var (`$FOO`), an `ai.keyEnv` that isn't set (provider key upload\n * will be skipped), and — when `o11y` is enabled — any env whose local\n * credentials lack an ingest token. It also folds in the shared rule linter,\n * git-tracked secret-shaped files, and wrangler config warnings. Prints `ok`\n * when clean, otherwise the warning list. Purely advisory: never throws on\n * warnings and never mutates anything.\n *\n * @param options.configPath Path to the `odla.config.mjs` to inspect.\n * @param options.stdout Optional console-like sink (defaults to `console`).\n */\nexport async function doctor(options: DoctorOptions): Promise<void> {\n const out = options.stdout ?? console;\n const cfg = await loadProjectConfig(options.configPath);\n const plan = buildPlan(cfg);\n const hasDb = cfg.services.includes(\"db\");\n const schema = hasDb ? await resolveDataExport<unknown>(cfg, cfg.db?.schema, [\"schema\", \"SCHEMA\"]) : undefined;\n const configuredRules = hasDb\n ? await resolveDataExport<AppRules>(cfg, cfg.db?.rules, [\"rules\", \"RULES\"])\n : undefined;\n const rules = configuredRules ?? (schema && cfg.db?.defaultRules !== false ? rulesFromSchema(schema) : undefined);\n const entities = serializedEntities(schema);\n\n out.log(`config: ${cfg.configPath}`);\n out.log(`app: ${plan.appName} (${plan.appId})`);\n out.log(`envs: ${plan.envs.join(\", \")}`);\n out.log(`svc: ${plan.services.join(\", \")}`);\n out.log(`schema: ${schema ? `${entities.length} entities` : \"none\"}`);\n out.log(`rules: ${rules ? `${Object.keys(rules).length} namespaces` : \"none\"}`);\n out.log(`ai: ${cfg.services.includes(\"ai\") ? (cfg.ai?.provider ?? \"not configured\") : \"not enabled\"}`);\n if (cfg.services.includes(\"calendar\")) {\n const calendar = cfg.envs.map((env) => `${env}:${calendarServiceConfig(cfg, env).calendars.length}`).join(\", \");\n out.log(`calendar: google/read-only (${calendar}; attendee ${cfg.calendar?.google.attendeePolicy ?? \"full\"})`);\n const pages = cfg.envs.map((env) => `${env}:${calendarBookingPageUrl(cfg, env) ?? \"none\"}`).join(\", \");\n out.log(`booking pages: ${pages}`);\n } else {\n out.log(\"calendar: not enabled\");\n }\n\n const warnings: string[] = [];\n if (schema && entities.length === 0) warnings.push(\"schema has no entities\");\n if (rules) {\n for (const ns of Object.keys(rules)) {\n if (entities.length > 0 && !entities.includes(ns)) warnings.push(`rules include \"${ns}\" but schema has no matching entity`);\n }\n }\n if (cfg.services.includes(\"ai\") && !cfg.ai?.provider) warnings.push(\"ai service is enabled but ai.provider is not set\");\n if (cfg.auth?.clerk) {\n for (const [env, value] of Object.entries(cfg.auth.clerk)) {\n if (typeof value === \"string\" && value.startsWith(\"$\") && !process.env[value.slice(1)]) {\n warnings.push(`auth.clerk.${env} references unset env var ${value}`);\n }\n }\n }\n if (cfg.services.includes(\"ai\") && cfg.ai?.keyEnv && !process.env[cfg.ai.keyEnv]) {\n warnings.push(`${cfg.ai.keyEnv} is not set; provision will skip provider key storage`);\n }\n if (cfg.services.includes(\"o11y\")) {\n // o11y enabled but no ingest token = telemetry silently rejected. Provision mints one.\n const credentials = readCredentials(cfg.local.credentialsFile);\n for (const env of cfg.envs) {\n if (!credentials?.envs[env]?.o11yToken) {\n warnings.push(`o11y is enabled but env \"${env}\" has no ingest token — run \"odla-ai provision\" to mint one`);\n }\n }\n warnings.push(...o11yProjectWarnings(cfg.rootDir));\n }\n if (cfg.services.includes(\"calendar\")) warnings.push(...calendarProjectWarnings(cfg.rootDir));\n else if (cfg.calendar) warnings.push('calendar config is present but \"calendar\" is not in services');\n warnings.push(...lintRules(rules, entities, cfg.db?.publicRead ?? []));\n warnings.push(...trackedSecretFiles(cfg.rootDir, undefined, [\n cfg.local.tokenFile,\n cfg.local.credentialsFile,\n cfg.local.devVarsFile,\n ]));\n warnings.push(...wranglerWarnings(cfg.rootDir));\n\n if (warnings.length) {\n out.log(\"\");\n out.log(\"warnings:\");\n for (const warning of warnings) out.log(` - ${warning}`);\n } else {\n out.log(\"ok\");\n }\n}\n","import { readFileSync } from \"node:fs\";\n\nexport function cliVersion(): string {\n const pkg = JSON.parse(readFileSync(new URL(\"../package.json\", import.meta.url), \"utf8\")) as { version?: string };\n return pkg.version ?? \"unknown\";\n}\n\nexport function printHelp(): void {\n console.log(`odla-ai\n\nUsage:\n odla-ai setup [--dir <project>] [--agent <name>] [--global] [--force]\n odla-ai init --app-id <id> --name <name> [--services db,ai,o11y,calendar] [--env dev --env prod]\n odla-ai doctor [--config odla.config.mjs]\n odla-ai calendar status [--env dev] [--email <odla-account>] [--json]\n odla-ai calendar calendars [--env dev] [--email <odla-account>] [--json]\n odla-ai calendar connect [--env dev] [--email <odla-account>] [--no-open] [--yes]\n odla-ai calendar resync [--env dev] [--email <odla-account>] [--yes]\n odla-ai calendar disconnect [--env dev] [--email <odla-account>] --yes\n odla-ai capabilities [--json]\n odla-ai admin ai show [--platform https://odla.ai] [--email <odla-account>] [--json]\n odla-ai admin ai models [--provider <id>] [--json]\n odla-ai admin ai set <purpose> [--provider <id>] [--model <id>] [--enabled|--no-enabled]\n odla-ai admin ai set security --discovery-provider <id> --discovery-model <id>\n --validation-provider <id> --validation-model <id> [--enabled|--no-enabled]\n odla-ai admin ai credentials [--json]\n odla-ai admin ai credential set <provider> (--from-env <NAME>|--stdin)\n odla-ai admin ai usage [--app-id <id>] [--env <env>] [--run-id <id>] [--limit <1-500>] [--json]\n odla-ai admin ai audit [--limit <1-200>] [--json]\n odla-ai security github connect [--repo owner/name] [--env dev] [--email <odla-account>] [--no-open]\n odla-ai security github disconnect --source <id> [--env dev] [--yes]\n odla-ai security plan [--env dev] [--json]\n odla-ai security sources [--env dev] [--json]\n odla-ai security run --source <id> --plan-digest <sha256:...> --ack-redacted-source [--ref <branch|tag|sha>] [--env dev] [--no-follow]\n odla-ai security status <job-id> [--follow] [--json]\n odla-ai security report <job-id> [--json]\n odla-ai security run [target] --ack-redacted-source [--env dev] [--profile odla] [--fail-on high]\n odla-ai security run [target] --self --ack-redacted-source\n odla-ai provision [--config odla.config.mjs] [--email <odla-account>] [--dry-run] [--push-secrets] [--rotate-o11y-token] [--write-dev-vars[=path]] [--yes]\n odla-ai smoke [--config odla.config.mjs] [--env dev] [--email <odla-account>] [--no-open]\n odla-ai skill install [--dir <project>] [--agent <name>] [--global] [--force]\n odla-ai secrets push --env <env> [--config odla.config.mjs] [--dry-run] [--yes]\n odla-ai secrets set <name> --env <env> (--from-env <NAME>|--stdin) [--email <odla-account>] [--config odla.config.mjs] [--yes]\n odla-ai secrets set-clerk-key --env <env> (--from-env <NAME>|--stdin) [--email <odla-account>] [--config odla.config.mjs] [--yes]\n odla-ai version\n\nCommands:\n setup Install offline odla runbooks for common coding-agent harnesses.\n init Create a generic odla.config.mjs plus starter schema/rules files.\n doctor Validate and summarize the project config without network calls.\n calendar Inspect, connect, resync, or disconnect a read-only Google mirror.\n capabilities Show what the CLI automates vs agent edits and human checkpoints.\n admin Manage platform-funded AI routing/credentials/usage with narrow device grants.\n security Connect GitHub sources and run commit-pinned hosted reviews, or scan a local snapshot.\n provision Register services, configure them, persist credentials, optionally push secrets.\n smoke Verify local credentials, public-config, live schema, and db aggregate.\n skill Same installer; --agent accepts all, claude, codex, cursor,\n copilot, gemini, or agents (repeatable or comma-separated).\n secrets Push configured db/o11y secrets into the Worker via wrangler\n stdin; set stores a tenant-vault secret and set-clerk-key the\n reserved Clerk secret key, write-only from stdin or an env var.\n version Print the CLI version.\n\nSafety:\n New projects target dev only. Add prod explicitly to odla.config.mjs and pass\n --yes to provision it; use --dry-run first to inspect the resolved plan.\n Provision caches the approved developer token and service credentials under\n .odla/ with mode 0600, and init adds those paths to .gitignore. Secret push\n preflights Wrangler before any shown-once issuance or destructive rotation.\n Provision opens the approval page in your browser automatically whenever the\n machine can show one, including agent-driven runs; only CI, SSH, and\n display-less hosts skip it. Use --open to force or --no-open to suppress.\n A fresh device handshake requires --email <odla-account> or ODLA_USER_EMAIL.\n The email is a non-secret identity hint: never provide a password or session\n token. The matching account must already exist, be signed in, explicitly\n review the exact code, and finish any current request before claiming another.\n Calendar setup has a second human checkpoint: odla issues a state-bound Google consent URL;\n OAuth codes and refresh tokens never enter the CLI, repo, chat, or app.\n GitHub security uses source-read-only access plus optional metadata-only Checks write: the CLI never asks\n for a PAT or provider key. GitHub read access is separate from the explicit\n --ack-redacted-source consent and the exact --plan-digest printed by security\n plan are required before bounded snippets reach System AI.\n Run security plan first to inspect the admin-selected providers, models,\n per-route bounds, credential readiness, retention, no-execution boundary,\n and digest that binds consent to that exact plan.\n`);\n}\n","import type { ParsedArgv } from \"./argv\";\nimport type { AgentHarnessSelector } from \"./skill\";\n\nexport function harnessList(parsed: ParsedArgv): AgentHarnessSelector[] {\n const selected = [\n ...harnessOption(parsed.options.agent, \"--agent\"),\n ...harnessOption(parsed.options.harness, \"--harness\"),\n ];\n return (selected.length ? selected : [\"all\"]) as AgentHarnessSelector[];\n}\n\nfunction harnessOption(\n value: string | boolean | string[] | undefined,\n flag: string,\n): string[] {\n if (value === undefined) return [];\n if (typeof value === \"boolean\") throw new Error(`${flag} requires a harness name`);\n const raw = Array.isArray(value) ? value : [value];\n const parts = raw.flatMap((item) => item.split(\",\"));\n if (parts.some((item) => !item.trim())) {\n throw new Error(`${flag} requires a harness name`);\n }\n return parts.map((item) => item.trim());\n}\n","import { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport { ensureGitignore } from \"./local\";\n\nexport interface InitOptions {\n rootDir?: string;\n configPath?: string;\n appId: string;\n name: string;\n envs?: string[];\n services?: string[];\n aiProvider?: string;\n force?: boolean;\n stdout?: Pick<typeof console, \"log\" | \"error\">;\n}\n\n/**\n * Scaffold a new odla project into `rootDir` (default: cwd). Writes an\n * `odla.config.mjs` (default name, overridable via `configPath`) plus starter\n * `src/odla/schema.mjs` (a single `notes` entity) and `src/odla/rules.mjs`\n * (deny-all), and creates the `src/odla` and `.odla` directories. Also runs\n * `ensureGitignore` so the local token/credentials paths are ignored.\n *\n * Fully local and synchronous — no network calls. The config file is only\n * written when it doesn't already exist unless `force` is set (otherwise it\n * throws); the schema/rules files are written only when missing (never\n * overwritten, even with `force`). `appId` must match `^[a-z0-9][a-z0-9-]*$` or\n * it throws. Defaults: `envs` → `[\"dev\"]`, `services` → `[\"db\",\"ai\"]`,\n * `aiProvider` → `\"anthropic\"` (which also picks the `keyEnv`, e.g.\n * `ANTHROPIC_API_KEY`/`OPENAI_API_KEY`/`GOOGLE_API_KEY`).\n *\n * @param options.appId Slug for the app (lowercase alphanumerics and hyphens).\n * @param options.name Human-readable app name embedded in the config.\n * @param options.rootDir Project root (defaults to `process.cwd()`).\n * @param options.configPath Config filename relative to root (default `odla.config.mjs`).\n * @param options.envs Environment names (default `[\"dev\"]`; production is an explicit opt-in).\n * @param options.services Enabled services (default `[\"db\",\"ai\"]`).\n * @param options.aiProvider AI provider slug (default `\"anthropic\"`).\n * @param options.force Overwrite an existing config file instead of throwing.\n * @param options.stdout Optional console-like sink (defaults to `console`).\n */\nexport function initProject(options: InitOptions): void {\n const out = options.stdout ?? console;\n const rootDir = resolve(options.rootDir ?? process.cwd());\n const configPath = resolve(rootDir, options.configPath ?? \"odla.config.mjs\");\n if (existsSync(configPath) && !options.force) {\n throw new Error(`${configPath} already exists. Pass --force to overwrite.`);\n }\n if (!/^[a-z0-9][a-z0-9-]*$/.test(options.appId)) {\n throw new Error(\"--app-id must be lowercase letters, numbers, and hyphens\");\n }\n // Production is an explicit opt-in. This prevents an unattended `init` +\n // `provision` flow from mutating the live environment by default.\n const envs = options.envs?.length ? options.envs : [\"dev\"];\n const services = options.services?.length ? options.services : [\"db\", \"ai\"];\n if (services.includes(\"calendar\") && !services.includes(\"db\")) throw new Error(\"--services calendar requires db\");\n const aiProvider = options.aiProvider ?? \"anthropic\";\n\n mkdirSync(dirname(configPath), { recursive: true });\n mkdirSync(resolve(rootDir, \"src/odla\"), { recursive: true });\n mkdirSync(resolve(rootDir, \".odla\"), { recursive: true });\n\n writeFileSync(configPath, configTemplate({ appId: options.appId, name: options.name, envs, services, aiProvider }));\n writeIfMissing(resolve(rootDir, \"src/odla/schema.mjs\"), schemaTemplate());\n writeIfMissing(resolve(rootDir, \"src/odla/rules.mjs\"), rulesTemplate());\n ensureGitignore(rootDir);\n\n out.log(`created ${relativeDisplay(configPath, rootDir)}`);\n out.log(\"created src/odla/schema.mjs and src/odla/rules.mjs\");\n out.log(\"updated .gitignore for local odla credentials\");\n}\n\nfunction writeIfMissing(path: string, text: string): void {\n if (existsSync(path)) return;\n writeFileSync(path, text);\n}\n\nfunction configTemplate(input: { appId: string; name: string; envs: string[]; services: string[]; aiProvider: string }): string {\n const calendar = input.services.includes(\"calendar\")\n ? ` calendar: {\n google: {\n calendars: ${JSON.stringify(Object.fromEntries(input.envs.map((env) => [env, [\"primary\"]])))},\n bookingPageUrl: ${JSON.stringify(Object.fromEntries(input.envs.map((env) => [env, null])))},\n match: { organizerSelf: true, requireAttendees: true },\n attendeePolicy: \"full\",\n // Read-only in this release. Google consent happens in Studio during provision.\n },\n },\n`\n : \"\";\n return `export default {\n platformUrl: process.env.ODLA_PLATFORM_URL ?? \"https://odla.ai\",\n dbEndpoint: process.env.ODLA_ENDPOINT ?? process.env.ODLA_DB_ENDPOINT ?? \"https://db.odla.ai\",\n app: {\n id: \"${input.appId}\",\n name: \"${input.name.replace(/\"/g, '\\\\\"')}\",\n },\n envs: ${JSON.stringify(input.envs)},\n services: ${JSON.stringify(input.services)},\n db: {\n schema: \"./src/odla/schema.mjs\",\n rules: \"./src/odla/rules.mjs\",\n // When rules is omitted, the CLI generates deny-all rules from schema.\n defaultRules: \"deny\",\n },\n ai: {\n provider: process.env.ODLA_AI_PROVIDER ?? \"${input.aiProvider}\",\n // Optional: set this env var while running provision to store the provider\n // key in the platform vault for each tenant.\n keyEnv: \"${defaultKeyEnv(input.aiProvider)}\",\n },\n${calendar}\n auth: {\n clerk: {\n // dev: \"$CLERK_PUBLISHABLE_KEY\",\n // prod: \"$CLERK_PUBLISHABLE_KEY\",\n },\n },\n // Add \"o11y\" to services to enable observability; provision then mints the\n // ingest token and scaffolds the ODLA_O11Y_* vars into .dev.vars.\n // o11y: {\n // service: \"${input.appId}\", // defaults to the app id\n // // endpoint: \"https://o11y.odla.ai\",\n // },\n links: {\n // dev: \"https://dev.example.com\",\n // prod: \"https://example.com\",\n },\n local: {\n tokenFile: \".odla/dev-token.json\",\n credentialsFile: \".odla/credentials.local.json\",\n devVarsFile: \".dev.vars\",\n },\n};\n`;\n}\n\nfunction schemaTemplate(): string {\n return `// Replace this starter schema with your app's odla-db schema.\n// Knowledge-graph projects can export @odla-ai/kg's toSerializedSchema(ontology).\nexport const schema = {\n entities: {\n notes: {\n attrs: {\n id: { type: \"string\", unique: true, indexed: true, optional: false },\n text: { type: \"string\", unique: false, indexed: false, optional: false },\n createdAt: { type: \"number\", unique: false, indexed: true, optional: false },\n },\n },\n },\n links: {},\n};\n`;\n}\n\nfunction rulesTemplate(): string {\n return `// odla-db is default-deny. The starter keeps runtime data backend-only.\nexport const rules = {\n notes: {\n view: \"false\",\n create: \"false\",\n update: \"false\",\n delete: \"false\",\n },\n};\n`;\n}\n\nfunction defaultKeyEnv(provider: string): string {\n if (provider === \"openai\") return \"OPENAI_API_KEY\";\n if (provider === \"google\") return \"GOOGLE_API_KEY\";\n return \"ANTHROPIC_API_KEY\";\n}\n\nfunction relativeDisplay(path: string, rootDir: string): string {\n return path.startsWith(rootDir) ? path.slice(rootDir.length + 1) : path;\n}\n","import { createAppsClient, tenantIdFor } from \"@odla-ai/apps\";\nimport { DEFAULT_SECRET_NAMES, putSecret } from \"@odla-ai/ai\";\nimport process from \"node:process\";\nimport type { AppRules, LoadedProjectConfig, ProvisionOptions } from \"./types\";\nimport { buildPlan, calendarBookingPageUrl, calendarServiceConfig, envValue, GOOGLE_CALENDAR_READ_SCOPE, loadProjectConfig, resolveDataExport, rulesFromSchema } from \"./config\";\nimport { applyCalendarBookingPage, ensureCalendarConnected } from \"./calendar\";\nimport { isCalendarPlatformNotReady } from \"./calendar-errors\";\nimport { getDeveloperToken } from \"./token\";\nimport {\n displayPath, ensureGitignore, gitignoreEntry, o11yDevVars, readCredentials, resolveWriteDevVarsTarget, writeDevVars,\n} from \"./local\";\nimport { provisionEnvCredentials } from \"./provision-credentials\";\nimport { redactSecrets } from \"./redact\";\nimport { preflightSecretsPush, secretsPushAfterPreflight } from \"./secrets\";\n\ntype FetchLike = typeof fetch;\n\n/**\n * Provision an app end-to-end from its config — the primary deploy path, and\n * (apart from key rotation) idempotent, so re-running is safe. Obtains a\n * developer token, creates the registry app when absent, enables each service\n * per env (AI also gets `setAi` with the configured provider/model), configures\n * Clerk auth and links, then per env mints or reuses credentials only for the\n * configured services, pushes the schema with the db key and the\n * rules with the developer token, and stores the provider key in the tenant\n * vault when `ai.keyEnv` is set and present. Writes the credentials file\n * (mode 0600, gitignored) and, when requested, `.dev.vars`. Google Calendar\n * consent runs last, per env; when the platform connector itself is not yet\n * configured (`calendar_*_not_configured`), provision prints a resume hint\n * (`odla-ai calendar connect`) instead of aborting.\n *\n * The developer token comes from (in order) `options.token`, `$ODLA_DEV_TOKEN`,\n * the cached `.odla` token, or a fresh email-bound device handshake — which\n * prints a user code for the same signed-in account to review and auto-opens\n * the browser whenever this machine can show one — including scripted and\n * agent-driven runs; only CI, SSH, and display-less hosts skip it\n * (`open: true`/`false` forces/suppresses it). Network error bodies pass through\n * `redactSecrets` before display.\n *\n * @param options.dryRun Print the resolved plan and return before any network call/write.\n * @param options.rotateKeys Rotate db keys and o11y tokens.\n * @param options.rotateO11yToken Rotate only the o11y token.\n * @param options.email Existing odla account email for a fresh handshake;\n * this is an identity hint, never a password or session credential.\n * @param options.pushSecrets Preflight Wrangler, then push each env's configured\n * Worker secrets immediately after credential provisioning.\n * @param options.writeDevVars `true`/a path writes `.dev.vars`; `writeCredentials: false` skips the creds file.\n * @param options.yes Required for a non-dry-run plan containing `prod` or\n * `production`; callers must show and review `dryRun` output first.\n * @throws When a production plan is executed without `yes`, configuration is\n * invalid, authorization fails, or a provisioning operation fails.\n */\nexport async function provision(options: ProvisionOptions): Promise<void> {\n const out = options.stdout ?? console;\n const cfg = await loadProjectConfig(options.configPath);\n const plan = buildPlan(cfg);\n const hasDb = cfg.services.includes(\"db\");\n const hasO11y = cfg.services.includes(\"o11y\");\n\n if (options.rotateO11yToken && !hasO11y) {\n throw new Error(\"--rotate-o11y-token requires the o11y service in odla.config.mjs\");\n }\n if (options.pushSecrets && options.writeCredentials === false) {\n throw new Error(\"--push-secrets cannot be combined with --no-write-credentials\");\n }\n\n out.log(`odla-ai: ${plan.appName} (${plan.appId})`);\n out.log(` platform: ${plan.platformUrl}`);\n out.log(` db: ${plan.dbEndpoint}`);\n out.log(` envs: ${plan.envs.join(\", \")}`);\n out.log(` services: ${plan.services.join(\", \")}`);\n\n const productionEnvs = plan.envs.filter((env) => env === \"prod\" || env === \"production\");\n if (!options.dryRun && productionEnvs.length > 0 && !options.yes) {\n throw new Error(\n `refusing to provision production env ${productionEnvs.join(\", \")} without --yes; run --dry-run first`,\n );\n }\n\n const schema = hasDb ? await resolveDataExport<unknown>(cfg, cfg.db?.schema, [\"schema\", \"SCHEMA\"]) : undefined;\n const configuredRules = hasDb ? await resolveDataExport<AppRules>(cfg, cfg.db?.rules, [\"rules\", \"RULES\"]) : undefined;\n const rules = configuredRules ?? (schema && cfg.db?.defaultRules !== false ? rulesFromSchema(schema) : undefined);\n\n if (options.dryRun) {\n out.log(\"dry run: no network calls or file writes\");\n out.log(` schema: ${schema ? \"yes\" : \"no\"}`);\n out.log(` rules: ${rules ? Object.keys(rules).length : 0} namespaces`);\n out.log(` ai: ${cfg.services.includes(\"ai\") ? (cfg.ai?.provider ?? \"not configured\") : \"not enabled\"}`);\n if (cfg.services.includes(\"calendar\")) {\n for (const env of cfg.envs) {\n const calendar = calendarServiceConfig(cfg, env);\n out.log(` calendar.${env}: google/read, ${calendar.calendars.join(\", \")} (${calendar.attendeePolicy}; ${GOOGLE_CALENDAR_READ_SCOPE})`);\n const bookingPage = calendarBookingPageUrl(cfg, env);\n out.log(` calendar.${env}.bookingPageUrl: ${bookingPage === undefined ? \"unchanged\" : bookingPage ?? \"clear\"}`);\n }\n }\n out.log(` secrets: ${options.pushSecrets ? \"push configured Worker secrets\" : \"local only\"}`);\n return;\n }\n\n let credentials = readCredentials(cfg.local.credentialsFile);\n if (credentials && credentials.appId !== cfg.app.id) {\n throw new Error(\n `credentials at ${displayPath(cfg.local.credentialsFile, cfg.rootDir)} are for \"${credentials.appId}\", not \"${cfg.app.id}\"`,\n );\n }\n const rotatesO11y = !!(options.rotateKeys || options.rotateO11yToken);\n const missingO11y = cfg.envs.some((env) => !credentials?.envs[env]?.o11yToken);\n const missingDb = cfg.envs.some((env) => !credentials?.envs[env]?.dbKey);\n const losesShownOnceCredential = (hasDb && (!!options.rotateKeys || missingDb)) || (hasO11y && (rotatesO11y || missingO11y));\n if (options.writeCredentials === false && losesShownOnceCredential) {\n throw new Error(\"credential issuance/rotation requires the private credentials file; remove --no-write-credentials\");\n }\n const devVarsTarget = resolveWriteDevVarsTarget(cfg, options.writeDevVars);\n if (cfg.local.gitignore) {\n ensureGitignore(cfg.rootDir, [cfg.local.tokenFile, cfg.local.credentialsFile, ...(devVarsTarget ? [devVarsTarget] : [])]);\n }\n if (options.pushSecrets) {\n await preflightSecretsPush({ configPath: cfg.configPath, runner: options.secretRunner });\n out.log(\"secrets: Wrangler config and login preflight passed\");\n }\n\n const doFetch = options.fetch ?? fetch;\n const token = await getDeveloperToken(cfg, options, doFetch, out);\n const apps = createAppsClient({ endpoint: cfg.platformUrl, token, fetcher: { fetch: doFetch } });\n\n const existing = await readRegistryApp(cfg, token, doFetch);\n if (existing) {\n out.log(`app: ${cfg.app.id} already exists`);\n } else {\n await apps.createApp({ name: cfg.app.name, appId: cfg.app.id });\n out.log(`app: created ${cfg.app.id}`);\n }\n\n const serviceOrder = [...cfg.services].sort((a, b) => serviceRank(a) - serviceRank(b));\n for (const env of cfg.envs) {\n for (const service of serviceOrder) {\n if (service === \"ai\") {\n if (cfg.ai?.provider) {\n await apps.setAi(cfg.app.id, env, { provider: cfg.ai.provider, ...(cfg.ai.model ? { model: cfg.ai.model } : {}) });\n out.log(`${env}: ai configured (${cfg.ai.provider}${cfg.ai.model ? `/${cfg.ai.model}` : \"\"})`);\n } else {\n await apps.setService(cfg.app.id, \"ai\", true, { env });\n out.log(`${env}: ai enabled`);\n }\n } else {\n const config = service === \"calendar\" ? calendarServiceConfig(cfg, env) : undefined;\n await apps.setService(cfg.app.id, service, true, { env, ...(config ? { config } : {}) });\n out.log(`${env}: ${service} enabled`);\n }\n }\n\n const authConfig = normalizeClerkConfig(cfg.auth?.clerk?.[env]);\n if (authConfig?.publishableKey) {\n await apps.setAuth(cfg.app.id, env, authConfig);\n out.log(`${env}: auth configured (clerk ${authConfig.mode ?? \"client\"})`);\n }\n\n const link = cfg.links?.[env];\n if (link !== undefined) {\n await apps.setLink(cfg.app.id, env, link ?? null);\n out.log(`${env}: link ${link ? \"set\" : \"cleared\"}`);\n }\n\n if (cfg.services.includes(\"calendar\")) {\n const calendarCtx = { platform: cfg.platformUrl, appId: cfg.app.id, env, token, fetch: doFetch };\n await applyCalendarBookingPage(calendarCtx, calendarBookingPageUrl(cfg, env), out);\n }\n }\n\n for (const env of cfg.envs) {\n const tenantId = tenantIdFor(cfg.app.id, env);\n credentials = await provisionEnvCredentials({\n cfg,\n env,\n developerToken: token,\n credentials,\n rotateDb: !!options.rotateKeys,\n rotateO11y: rotatesO11y,\n write: options.writeCredentials !== false,\n fetch: doFetch,\n stdout: out,\n });\n const dbKey = credentials.envs[env]?.dbKey;\n\n if (options.pushSecrets) {\n try {\n await secretsPushAfterPreflight({\n configPath: cfg.configPath,\n env,\n yes: options.yes,\n runner: options.secretRunner,\n stdout: out,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const consent = env === \"prod\" || env === \"production\" ? \" --yes\" : \"\";\n throw new Error(\n `${message}\\n${env}: credentials are already saved; retry ` +\n `\"odla-ai secrets push --env ${env}${consent}\" without issuing or rotating again`,\n { cause: error },\n );\n }\n }\n\n if (schema && dbKey) {\n await postJson(doFetch, `${cfg.dbEndpoint}/app/${encodeURIComponent(tenantId)}/schema`, dbKey, { schema });\n out.log(`${env}: schema pushed`);\n }\n if (rules) {\n await postJson(doFetch, `${cfg.dbEndpoint}/app/${encodeURIComponent(tenantId)}/admin/rules`, token, rules);\n out.log(`${env}: rules pushed (${Object.keys(rules).length} namespaces)`);\n }\n\n if (cfg.services.includes(\"ai\") && cfg.ai?.provider && cfg.ai.keyEnv) {\n const key = process.env[cfg.ai.keyEnv];\n if (key) {\n const secretName = cfg.ai.secretName ?? defaultSecretName(cfg.ai.provider);\n await putSecret({ endpoint: cfg.dbEndpoint, token, fetch: doFetch }, tenantId, secretName, key);\n out.log(`${env}: ${cfg.ai.provider} key stored in vault (${secretName})`);\n } else {\n out.log(`${env}: ${cfg.ai.keyEnv} not set; skipped provider key storage`);\n }\n }\n\n }\n\n if (options.writeCredentials !== false && credentials) {\n const ignored = cfg.local.gitignore && gitignoreEntry(cfg.rootDir, cfg.local.credentialsFile);\n out.log(`credentials: wrote ${displayPath(cfg.local.credentialsFile, cfg.rootDir)} (0600${ignored ? \", gitignored\" : \"\"})`);\n }\n\n if (devVarsTarget && credentials) {\n const env = cfg.envs.includes(\"dev\") ? \"dev\" : (cfg.envs[0] ?? \"prod\");\n writeDevVars(devVarsTarget, credentials, env, o11yDevVars(cfg));\n out.log(`dev vars: wrote ${displayPath(devVarsTarget, cfg.rootDir)} for ${env}`);\n }\n\n // Google consent runs last: the only human checkpoint never blocks\n // credentials, schema, rules, or local artifacts.\n if (cfg.services.includes(\"calendar\")) {\n for (const env of cfg.envs) {\n try {\n await ensureCalendarConnected(\n { platform: cfg.platformUrl, appId: cfg.app.id, env, token, fetch: doFetch },\n {\n open: options.open,\n openConsentUrl: options.openApprovalUrl,\n wait: options.calendarPollWait,\n pollTimeoutMs: options.calendarPollTimeoutMs,\n stdout: out,\n },\n );\n } catch (error) {\n if (!isCalendarPlatformNotReady(error)) throw error;\n out.log(`${env}: calendar consent skipped (${error.code}); resume with \"odla-ai calendar connect --env ${env}\" once the platform is configured`);\n }\n }\n }\n}\n\nfunction serviceRank(service: string): number {\n if (service === \"db\") return 0;\n if (service === \"calendar\") return 2;\n return 1;\n}\n\nasync function readRegistryApp(cfg: LoadedProjectConfig, token: string, doFetch: FetchLike): Promise<unknown | null> {\n const res = await doFetch(`${cfg.platformUrl}/registry/apps/${encodeURIComponent(cfg.app.id)}`, {\n headers: { authorization: `Bearer ${token}` },\n });\n if (res.status === 404) return null;\n if (!res.ok) return null;\n const json = (await res.json()) as { app?: unknown };\n return json.app ?? null;\n}\n\nasync function postJson(doFetch: FetchLike, url: string, bearer: string, body: unknown): Promise<void> {\n const res = await doFetch(url, {\n method: \"POST\",\n headers: { authorization: `Bearer ${bearer}`, \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n if (!res.ok) throw new Error(`${new URL(url).pathname} failed: ${res.status} ${await safeText(res)}`);\n}\n\nfunction normalizeClerkConfig(value: unknown): { publishableKey: string; audience?: string; mode?: \"client\" | \"full\" } | null {\n if (!value) return null;\n if (typeof value === \"string\") {\n const publishableKey = envValue(value);\n return publishableKey ? { publishableKey } : null;\n }\n if (typeof value !== \"object\") return null;\n const cfg = value as { publishableKey?: string; audience?: string; mode?: \"client\" | \"full\" };\n const publishableKey = envValue(cfg.publishableKey);\n return publishableKey ? { publishableKey, ...(cfg.audience ? { audience: cfg.audience } : {}), ...(cfg.mode ? { mode: cfg.mode } : {}) } : null;\n}\n\nfunction defaultSecretName(provider: string): string {\n const names = DEFAULT_SECRET_NAMES as Record<string, string>;\n return names[provider] ?? `${provider}_api_key`;\n}\n\nasync function safeText(res: Response): Promise<string> {\n try {\n return redactSecrets((await res.text()).slice(0, 500));\n } catch {\n return \"\";\n }\n}\n","import { tenantIdFor } from \"@odla-ai/apps\";\nimport type { LoadedProjectConfig, LocalCredentials } from \"./types\";\nimport { mergeCredential, writePrivateJson } from \"./local\";\nimport { redactSecrets } from \"./redact\";\n\ntype FetchLike = typeof fetch;\n\ninterface ProvisionEnvCredentialsOptions {\n cfg: LoadedProjectConfig;\n env: string;\n developerToken: string;\n credentials: LocalCredentials | null;\n rotateDb: boolean;\n rotateO11y: boolean;\n write: boolean;\n fetch: FetchLike;\n stdout: Pick<typeof console, \"log\">;\n}\n\n/** Mint/reuse only the credentials required by configured services. */\nexport async function provisionEnvCredentials(opts: ProvisionEnvCredentialsOptions): Promise<LocalCredentials> {\n const tenantId = tenantIdFor(opts.cfg.app.id, opts.env);\n const prior = opts.credentials?.envs[opts.env];\n let credentials = opts.credentials;\n let dbKey = opts.cfg.services.includes(\"db\") && !opts.rotateDb ? prior?.dbKey : undefined;\n let o11yToken = opts.cfg.services.includes(\"o11y\") && !opts.rotateO11y ? prior?.o11yToken : undefined;\n\n if (opts.cfg.services.includes(\"db\")) {\n if (dbKey) {\n opts.stdout.log(`${opts.env}: reusing local db key for ${tenantId}`);\n } else {\n dbKey = await mintDbKey(opts, tenantId);\n credentials = save(opts, credentials, tenantId, { dbKey });\n opts.stdout.log(`${opts.env}: minted db key for ${tenantId}`);\n }\n }\n\n if (opts.cfg.services.includes(\"o11y\")) {\n if (o11yToken) {\n opts.stdout.log(`${opts.env}: reusing local o11y ingest token`);\n } else {\n o11yToken = await issueO11yToken(opts);\n credentials = save(opts, credentials, tenantId, { ...(dbKey ? { dbKey } : {}), o11yToken });\n opts.stdout.log(`${opts.env}: ${opts.rotateO11y ? \"rotated\" : \"issued\"} o11y ingest token`);\n }\n }\n\n return save(opts, credentials, tenantId, {\n ...(dbKey ? { dbKey } : {}),\n ...(o11yToken ? { o11yToken } : {}),\n });\n}\n\nfunction save(\n opts: ProvisionEnvCredentialsOptions,\n current: LocalCredentials | null,\n tenantId: string,\n values: { dbKey?: string; o11yToken?: string },\n): LocalCredentials {\n const next = mergeCredential(current, {\n appId: opts.cfg.app.id,\n platformUrl: opts.cfg.platformUrl,\n dbEndpoint: opts.cfg.dbEndpoint,\n env: opts.env,\n tenantId,\n ...values,\n });\n if (opts.write) writePrivateJson(opts.cfg.local.credentialsFile, next);\n return next;\n}\n\nasync function mintDbKey(opts: ProvisionEnvCredentialsOptions, tenantId: string): Promise<string> {\n const headers = { authorization: `Bearer ${opts.developerToken}`, \"content-type\": \"application/json\" };\n let res = await opts.fetch(`${opts.cfg.dbEndpoint}/admin/apps/${encodeURIComponent(tenantId)}/keys`, {\n method: \"POST\",\n headers,\n body: \"{}\",\n });\n if (res.status === 404) {\n const created = await opts.fetch(`${opts.cfg.dbEndpoint}/admin/apps`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n name: opts.env === \"prod\" ? opts.cfg.app.name : `${opts.cfg.app.name} (${opts.env})`,\n appId: tenantId,\n }),\n });\n if (!created.ok) throw new Error(`db app create (${tenantId}) failed: ${created.status} ${await safeText(created)}`);\n res = await opts.fetch(`${opts.cfg.dbEndpoint}/admin/apps/${encodeURIComponent(tenantId)}/keys`, {\n method: \"POST\",\n headers,\n body: \"{}\",\n });\n }\n if (!res.ok) throw new Error(`db key mint (${tenantId}) failed: ${res.status} ${await safeText(res)}`);\n const body = (await res.json()) as { key?: string };\n if (!body.key) throw new Error(`db key mint (${tenantId}) returned no key`);\n return body.key;\n}\n\nasync function issueO11yToken(opts: ProvisionEnvCredentialsOptions): Promise<string> {\n const suffix = opts.rotateO11y ? \"/rotate\" : \"\";\n const res = await opts.fetch(\n `${opts.cfg.platformUrl}/o11y/${encodeURIComponent(opts.cfg.app.id)}/token${suffix}?env=${encodeURIComponent(opts.env)}`,\n { method: \"POST\", headers: { authorization: `Bearer ${opts.developerToken}` } },\n );\n if (res.status === 409 && !opts.rotateO11y) {\n throw new Error(\n `o11y token already exists for env \"${opts.env}\", but its shown-once value is not in the local credentials file; ` +\n `run \"odla-ai provision --rotate-o11y-token --push-secrets\" to replace it explicitly`,\n );\n }\n if (!res.ok) throw new Error(`o11y token ${opts.rotateO11y ? \"rotation\" : \"issue\"} (${opts.env}) failed: ${res.status} ${await safeText(res)}`);\n const body = (await res.json()) as { token?: string };\n if (!body.token) throw new Error(`o11y token ${opts.rotateO11y ? \"rotation\" : \"issue\"} (${opts.env}) returned no token`);\n return body.token;\n}\n\nasync function safeText(res: Response): Promise<string> {\n try {\n return redactSecrets((await res.text()).slice(0, 500));\n } catch {\n return \"\";\n }\n}\n","import { loadProjectConfig } from \"./config\";\nimport { displayPath, readCredentials } from \"./local\";\nimport { redactSecrets } from \"./redact\";\nimport type { LoadedProjectConfig } from \"./types\";\nimport { defaultRunner, findWranglerConfig, wranglerLoggedIn, wranglerPutSecret } from \"./wrangler\";\nimport type { CommandRunner } from \"./wrangler\";\n\n/** Moves locally stored configured service credentials to one Wrangler environment over stdin. */\nexport interface SecretsPushOptions {\n configPath: string;\n env: string;\n dryRun?: boolean;\n /** Required to push to a prod-named env; the visible consent token in agent transcripts. */\n yes?: boolean;\n runner?: CommandRunner;\n stdout?: Pick<typeof console, \"log\" | \"error\">;\n}\n\nexport interface SecretsPreflightOptions {\n configPath: string;\n runner?: CommandRunner;\n}\n\nconst PROD_ENV_NAMES = new Set([\"prod\", \"production\"]);\n\n/**\n * Moves the env's configured db and/or o11y credentials from the private local\n * credentials file into the Worker, piping values over stdin so they never\n * appear on argv, in output, or in the conversation transcript.\n */\nexport async function secretsPush(options: SecretsPushOptions): Promise<void> {\n await secretsPushImpl(options, true);\n}\n\n/** @internal Push after the caller has completed `preflightSecretsPush`. */\nexport async function secretsPushAfterPreflight(options: SecretsPushOptions): Promise<void> {\n await secretsPushImpl(options, false);\n}\n\nasync function secretsPushImpl(options: SecretsPushOptions, preflight: boolean): Promise<void> {\n const out = options.stdout ?? console;\n const cfg = await loadProjectConfig(options.configPath);\n const env = options.env;\n\n if (!cfg.envs.includes(env)) {\n throw new Error(`env \"${env}\" is not in config envs (${cfg.envs.join(\", \")})`);\n }\n if (PROD_ENV_NAMES.has(env) && !options.yes) {\n throw new Error(`refusing to push a secret to \"${env}\" without --yes`);\n }\n\n const credentialsPath = displayPath(cfg.local.credentialsFile, cfg.rootDir);\n const credentials = readCredentials(cfg.local.credentialsFile);\n if (!credentials) throw new Error(`no credentials at ${credentialsPath} — run \"odla-ai provision\" first`);\n if (credentials.appId !== cfg.app.id) {\n throw new Error(`credentials at ${credentialsPath} are for \"${credentials.appId}\", not \"${cfg.app.id}\"`);\n }\n const entry = credentials.envs[env];\n if (!entry) throw new Error(`no credentials for env \"${env}\" in ${credentialsPath} — run \"odla-ai provision\" first`);\n\n const secrets: Array<{ name: string; value: string }> = [];\n if (cfg.services.includes(\"o11y\")) {\n if (!entry.o11yToken) throw new Error(`no o11y token for env \"${env}\" in ${credentialsPath} — run \"odla-ai provision\" first`);\n secrets.push({ name: \"ODLA_O11Y_TOKEN\", value: entry.o11yToken });\n }\n if (cfg.services.includes(\"db\")) {\n if (!entry.dbKey) throw new Error(`no db key for env \"${env}\" in ${credentialsPath} — run \"odla-ai provision\" first`);\n secrets.push({ name: \"ODLA_API_KEY\", value: entry.dbKey });\n }\n if (secrets.length === 0) {\n out.log(`${env}: no configured Worker secrets to push`);\n return;\n }\n\n // Convention from the reference apps: the top-level wrangler config is prod;\n // every other env is a named `env.<name>` block.\n const wranglerEnv = PROD_ENV_NAMES.has(env) ? undefined : env;\n const target = wranglerEnv ? `wrangler env \"${wranglerEnv}\"` : \"the top-level (prod) wrangler env\";\n\n if (options.dryRun) {\n assertWranglerConfig(cfg);\n for (const s of secrets) out.log(`dry run: would push ${s.name} (${redactSecrets(s.value)}) to ${target}`);\n return;\n }\n\n const run = options.runner ?? defaultRunner;\n if (preflight) await preflightLoadedConfig(cfg, run);\n\n for (const s of secrets) {\n const result = await wranglerPutSecret(run, { name: s.name, value: s.value, env: wranglerEnv, cwd: cfg.rootDir });\n if (result.code !== 0) {\n throw new Error(`wrangler secret put ${s.name} failed (exit ${result.code}): ${redactSecrets(`${result.stderr || result.stdout}`.trim())}`);\n }\n out.log(`${s.name} pushed to ${target} (value read from ${credentialsPath}, never echoed)`);\n }\n}\n\n/** Check Wrangler config and login before provisioning issues or rotates secrets. */\nexport async function preflightSecretsPush(options: SecretsPreflightOptions): Promise<void> {\n const cfg = await loadProjectConfig(options.configPath);\n if (!cfg.services.some((service) => service === \"db\" || service === \"o11y\")) return;\n await preflightLoadedConfig(cfg, options.runner ?? defaultRunner);\n}\n\nasync function preflightLoadedConfig(cfg: LoadedProjectConfig, run: CommandRunner): Promise<void> {\n assertWranglerConfig(cfg);\n if (!(await wranglerLoggedIn(run, cfg.rootDir))) {\n throw new Error(`wrangler is not logged in — run \"wrangler login\" (a browser step for the human)`);\n }\n}\n\nfunction assertWranglerConfig(cfg: LoadedProjectConfig): void {\n if (!findWranglerConfig(cfg.rootDir)) {\n throw new Error(`no wrangler config found in ${cfg.rootDir} (wrangler.jsonc, wrangler.json, or wrangler.toml)`);\n }\n}\n","import { putSecret } from \"@odla-ai/ai\";\nimport { tenantIdFor } from \"@odla-ai/apps\";\nimport { loadProjectConfig } from \"./config\";\nimport { redactSecrets } from \"./redact\";\nimport { secretInputValue } from \"./secret-input\";\nimport { getDeveloperToken } from \"./token\";\nimport type { LoadedProjectConfig } from \"./types\";\n\n/**\n * Inputs for one write-only tenant-vault transfer (`secrets set` /\n * `secrets set-clerk-key`). Values may come only from a named environment\n * variable or stdin, so a producer command can be piped straight into the\n * vault without the secret ever being displayed or stored on disk.\n */\nexport interface SecretsSetOptions {\n configPath: string;\n env: string;\n /** Vault secret name (`secrets set` only; `$`-prefixed names are reserved). */\n name?: string;\n fromEnv?: string;\n stdin?: boolean;\n /** Explicit consent for a prod-named env (and for sk_live_ into a non-prod env). */\n yes?: boolean;\n /** Developer token override; defaults to $ODLA_DEV_TOKEN, the cached token, or a device handshake. */\n token?: string;\n /** Existing odla account email used only when a fresh handshake is required. */\n email?: string;\n open?: boolean;\n openApprovalUrl?: (url: string) => Promise<void>;\n fetch?: typeof fetch;\n readStdin?: () => Promise<string>;\n stdout?: Pick<typeof console, \"log\" | \"error\">;\n}\n\nconst PROD_ENV_NAMES = new Set([\"prod\", \"production\"]);\n\n/**\n * Store one named secret in the env's tenant vault (the same write-only slot\n * Studio's Secrets panel fills), e.g. `clerk_webhook_secret` for synced auth.\n * The value is encrypted at rest and can be read back only by that tenant's\n * app API key — never by this CLI, Studio, or the developer token.\n */\nexport async function secretsSet(options: SecretsSetOptions): Promise<void> {\n const name = (options.name ?? \"\").trim();\n if (!name) throw new Error('secret name is required, e.g. \"odla-ai secrets set clerk_webhook_secret --env dev --stdin\"');\n if (name.startsWith(\"$\")) {\n throw new Error('\"$\"-prefixed vault names are platform-reserved; for the Clerk secret key use \"odla-ai secrets set-clerk-key\"');\n }\n const { cfg, tenantId, value, doFetch, out } = await resolveVaultWrite(options);\n const token = await getDeveloperToken(cfg, options, doFetch, out);\n try {\n await putSecret({ endpoint: cfg.dbEndpoint, token, fetch: doFetch }, tenantId, name, value);\n } catch (err) {\n throw new Error(scrubValue(err instanceof Error ? err.message : String(err), value));\n }\n out.log(`${name} stored in the ${tenantId} vault (write-only; the value was never echoed and cannot be read back here)`);\n}\n\n/**\n * Store the app's Clerk secret key under the reserved `$clerk_secret` slot so\n * odla-db can resolve the app's users (invites, member lookups). Reserved\n * secrets are never readable by app keys; the dedicated endpoint is the only\n * way to set one. Guards against instance/env mismatches: an sk_test_ key\n * never belongs in a prod-named env, and an sk_live_ key entering a non-prod\n * env requires `--yes` (live users would sync into a non-prod tenant).\n */\nexport async function secretsSetClerkKey(options: SecretsSetOptions): Promise<void> {\n const { cfg, tenantId, value, doFetch, out } = await resolveVaultWrite(options);\n if (!value.startsWith(\"sk_\")) throw new Error(\"the Clerk secret key must start with sk_ (sk_test_… or sk_live_…)\");\n if (value.startsWith(\"sk_test_\") && PROD_ENV_NAMES.has(options.env)) {\n throw new Error(`refusing to store an sk_test_ Clerk key for \"${options.env}\" — use the production instance's sk_live_ key`);\n }\n if (value.startsWith(\"sk_live_\") && !PROD_ENV_NAMES.has(options.env) && !options.yes) {\n throw new Error(`refusing to store an sk_live_ Clerk key for \"${options.env}\" without --yes (live users would sync into a non-prod tenant)`);\n }\n const token = await getDeveloperToken(cfg, options, doFetch, out);\n const res = await doFetch(`${cfg.dbEndpoint}/admin/apps/${encodeURIComponent(tenantId)}/clerk-secret`, {\n method: \"POST\",\n headers: { authorization: `Bearer ${token}`, \"content-type\": \"application/json\" },\n body: JSON.stringify({ value }),\n });\n if (!res.ok) {\n const text = scrubValue((await res.text().catch(() => \"\")).slice(0, 300), value);\n throw new Error(`store Clerk secret key failed (${res.status}): ${text || \"request failed\"}`);\n }\n out.log(`Clerk secret key stored for ${tenantId} ($clerk_secret, reserved + write-only; the value was never echoed)`);\n}\n\n/** No error text may carry the transferred value, even when a misbehaving\n * endpoint echoes it back in a shape the pattern redactor doesn't know. */\nfunction scrubValue(text: string, value: string): string {\n return redactSecrets(text).split(value).join(\"[value redacted]\");\n}\n\ninterface VaultWrite {\n cfg: LoadedProjectConfig;\n tenantId: string;\n value: string;\n doFetch: typeof fetch;\n out: Pick<typeof console, \"log\" | \"error\">;\n}\n\n/** Shared preamble: config, env + prod consent, value ingestion. Every value\n * check runs before the caller acquires a token, so a bad invocation fails\n * fast instead of sending the user through a device handshake first. */\nasync function resolveVaultWrite(options: SecretsSetOptions): Promise<VaultWrite> {\n const out = options.stdout ?? console;\n const doFetch = options.fetch ?? fetch;\n const cfg = await loadProjectConfig(options.configPath);\n if (!cfg.envs.includes(options.env)) {\n throw new Error(`env \"${options.env}\" is not in config envs (${cfg.envs.join(\", \")})`);\n }\n if (PROD_ENV_NAMES.has(options.env) && !options.yes) {\n throw new Error(`refusing to store a secret for \"${options.env}\" without --yes`);\n }\n const value = await secretInputValue(options, \"secret\");\n return { cfg, tenantId: tenantIdFor(cfg.app.id, options.env), value, doFetch, out };\n}\n","import { createInterface } from \"node:readline/promises\";\nimport { stringOpt, type ParsedArgv } from \"./argv\";\nimport { loadProjectConfig } from \"./config\";\nimport type { CliDependencies } from \"./cli\";\nimport type { HostedSecurityProfile } from \"./security\";\nimport { getDeveloperToken, platformAudience } from \"./token\";\n\nexport interface HostedSecurityContext {\n platform: string;\n token: string;\n appId: string;\n env: string;\n fetch: typeof fetch;\n stdout: Pick<typeof console, \"log\" | \"error\">;\n}\n\nexport async function hostedSecurityContext(\n parsed: ParsedArgv,\n dependencies: CliDependencies,\n): Promise<HostedSecurityContext> {\n const configPath = stringOpt(parsed.options.config) ?? \"odla.config.mjs\";\n const cfg = await loadProjectConfig(configPath);\n const env = stringOpt(parsed.options.env) ?? (cfg.envs.includes(\"dev\") ? \"dev\" : cfg.envs[0]);\n if (!env || !cfg.envs.includes(env)) {\n throw new Error(`env \"${env ?? \"\"}\" is not declared in ${configPath}`);\n }\n const platform = platformAudience(stringOpt(parsed.options.platform) ?? cfg.platformUrl);\n if (platformAudience(cfg.platformUrl) !== platform) {\n throw new Error(\"--platform cannot reuse a project developer token from another platform; update odla.config.mjs and authenticate there\");\n }\n const doFetch = dependencies.fetch ?? fetch;\n const stdout = dependencies.stdout ?? console;\n const open = parsed.options.open === false\n ? false\n : parsed.options.open === true ? true : undefined;\n const token = await getDeveloperToken(\n cfg,\n { configPath, email: stringOpt(parsed.options.email), open, openApprovalUrl: dependencies.openUrl },\n doFetch,\n stdout,\n );\n return { platform, token, appId: cfg.app.id, env, fetch: doFetch, stdout };\n}\n\nexport async function interactiveConfirmation(\n message: string,\n dependencies: CliDependencies,\n): Promise<boolean> {\n if (dependencies.confirm) return dependencies.confirm(message);\n if (!process.stdin.isTTY || !process.stdout.isTTY) return false;\n const prompt = createInterface({ input: process.stdin, output: process.stdout });\n try {\n const answer = await prompt.question(`${message} [y/N] `);\n return /^y(?:es)?$/i.test(answer.trim());\n } finally {\n prompt.close();\n }\n}\n\nexport function requiredSecurityPositional(\n parsed: ParsedArgv,\n index: number,\n label: string,\n): string {\n const value = parsed.positionals[index];\n if (!value) throw new Error(`${label} is required`);\n return value;\n}\n\nexport function securityProfile(\n value: string | undefined,\n): HostedSecurityProfile | undefined {\n if (value === undefined) return undefined;\n if (value === \"odla\" || value === \"cloudflare-app\" || value === \"generic\") return value;\n throw new Error(\"--profile must be odla, cloudflare-app, or generic\");\n}\n","import { stringOpt, type ParsedArgv } from \"./argv\";\nimport type {\n HostedSecurityJob,\n HostedSecurityIntent,\n HostedSecurityPlan,\n HostedSecurityReport,\n HostedSecurityRoute,\n} from \"./security-hosted\";\n\nexport function printHostedSecurityPlan(\n out: Pick<typeof console, \"log\">,\n plan: HostedSecurityPlan,\n appId: string,\n): void {\n out.log(`Hosted security plan for ${appId}/${plan.env}: ${plan.ready ? \"ready\" : \"not ready\"}`);\n out.log(` plan digest: ${plan.planDigest}`);\n out.log(` consent/report/redaction: ${plan.consentContract} · ${plan.reportProjection} · ${plan.redactionContract}`);\n out.log(` prompt bundle: ${plan.promptBundle}`);\n printHostedSecurityPlanRoute(out, \"discovery\", plan.routes.discovery);\n printHostedSecurityPlanRoute(out, \"validation\", plan.routes.validation);\n out.log(` independent validation: ${plan.independent ? \"yes\" : \"no\"}`);\n out.log(\" source disclosure: bounded best-effort credential-pattern-redacted snippets may be sent through odla.ai to the selected providers\");\n out.log(` retained report: model-derived prose and repository-relative paths for up to ${plan.reportRetentionDays} days; treat it as sensitive`);\n out.log(\" target execution: disabled\");\n out.log(` to approve this exact plan, run security run --source <id> --plan-digest ${plan.planDigest} --ack-redacted-source`);\n}\n\nexport function printHostedSecurityIntent(\n out: Pick<typeof console, \"log\">,\n intent: HostedSecurityIntent,\n): void {\n out.log(`Hosted security execution intent for ${intent.appId}/${intent.env}:`);\n out.log(` execution digest: ${intent.executionDigest}`);\n out.log(` contract: ${intent.executionContract}`);\n out.log(` source: ${intent.repository} (${intent.sourceId})`);\n out.log(` ref: ${intent.requestedRef ?? `default branch (${intent.defaultBranch})`}`);\n out.log(` profile: ${intent.profile}`);\n out.log(` disclosure: ${intent.sourceDisclosure} · plan ${intent.planDigest}`);\n}\n\nexport function assertHostedSecurityPlanReady(plan: HostedSecurityPlan): void {\n const reasons: string[] = [];\n for (const [label, route] of Object.entries(plan.routes)) {\n if (!route.enabled) reasons.push(`${label} is disabled`);\n if (!route.credentialReady) reasons.push(`${label} provider credential is unavailable`);\n }\n if (!plan.independent) reasons.push(\"discovery and validation are not independently routed\");\n if (plan.ready && reasons.length === 0) return;\n if (!plan.ready && reasons.length === 0) reasons.push(\"the platform marked the plan unavailable\");\n throw new Error(`hosted security is not ready${reasons.length ? `: ${reasons.join(\"; \")}` : \"\"}. Ask a platform admin to update System AI security policy or credentials`);\n}\n\nexport function printHostedJob(\n out: Pick<typeof console, \"log\">,\n job: HostedSecurityJob,\n platform: string,\n appId: string,\n): void {\n out.log(`security job ${job.jobId}: ${job.status}`);\n out.log(` source: ${job.repository} ${job.requestedRef ?? \"default\"} -> ${job.commitSha ?? \"resolving\"}`);\n if (job.routes) {\n out.log(` discovery: ${routeLabel(job.routes.discovery)}`);\n out.log(` validation: ${routeLabel(job.routes.validation)}`);\n } else {\n out.log(\" routes: platform System AI policy (assigned when analysis starts)\");\n }\n out.log(` disclosure: ${job.sourceDisclosure} snippets · metadata retained up to ${job.retentionDays} days`);\n out.log(` consent: plan ${job.planDigest} · execution ${job.executionDigest} (${job.executionContract})`);\n if (job.coverageStatus || job.coverage) printHostedCoverage(out, job);\n if (job.counts) {\n out.log(` findings: confirmed=${job.counts.confirmed} needs_reproduction=${job.counts.needsReproduction} candidates=${job.counts.candidates}`);\n }\n if (job.errorCode) out.log(` failure: ${job.errorCode}`);\n const url = new URL(\"/studio\", platform);\n url.searchParams.set(\"app\", appId);\n url.searchParams.set(\"env\", job.env);\n url.searchParams.set(\"tab\", \"security\");\n url.searchParams.set(\"job\", job.jobId);\n out.log(` Studio: ${url.toString()}`);\n}\n\nexport function printHostedReport(\n out: Pick<typeof console, \"log\">,\n report: HostedSecurityReport,\n): void {\n out.log(`security report ${report.jobId}: ${report.repository}@${report.revision}`);\n out.log(` coverage: ${report.coverageStatus} cells=${report.metrics.coverageCells} shallow=${report.metrics.shallowCells} blocked=${report.metrics.blockedCells} unscheduled=${report.metrics.unscheduledCells} budget_exhausted=${report.metrics.budgetExhaustedCells}`);\n out.log(` findings: confirmed=${report.metrics.confirmed} needs_reproduction=${report.metrics.needsReproduction} candidates=${report.metrics.candidates} rejected=${report.metrics.rejected}`);\n out.log(` discovery: ${report.provenance.discovery?.provider ?? \"unknown\"}/${report.provenance.discovery?.model ?? \"unknown\"}`);\n out.log(` validation: ${report.provenance.validation?.provider ?? \"unknown\"}/${report.provenance.validation?.model ?? \"unknown\"} independent=${String(report.provenance.independentValidation)}`);\n for (const finding of report.findings) {\n const location = finding.locations[0];\n out.log(` [${finding.severity}] ${finding.title}${location ? ` (${location.path}:${location.line})` : \"\"} · ${finding.disposition}`);\n }\n for (const limitation of report.limitations) out.log(` limitation: ${limitation}`);\n}\n\nexport function enforceHostedReportGate(\n report: HostedSecurityReport,\n parsed: ParsedArgv,\n out: Pick<typeof console, \"log\">,\n emitSuccess: boolean,\n): void {\n const failOn = hostedSeverity(stringOpt(parsed.options[\"fail-on\"]) ?? \"high\", \"--fail-on\");\n const candidateValue = parsed.options[\"fail-on-candidates\"];\n const failOnCandidates = candidateValue === false\n ? undefined\n : hostedSeverity(stringOpt(candidateValue) ?? \"critical\", \"--fail-on-candidates\");\n const atOrAbove = (severity: HostedSecurityReport[\"findings\"][number][\"severity\"], threshold: string) =>\n HOSTED_SEVERITIES.indexOf(severity) >= HOSTED_SEVERITIES.indexOf(threshold as typeof severity);\n const confirmed = report.findings.filter((finding) =>\n finding.disposition === \"confirmed\" && atOrAbove(finding.severity, failOn));\n const leads = failOnCandidates\n ? report.findings.filter((finding) =>\n finding.disposition !== \"confirmed\" && atOrAbove(finding.severity, failOnCandidates))\n : [];\n // Stricter than the local gate on purpose: a hosted run always schedules AI coverage, so any\n // status other than \"complete\" — including \"not_run\" — means it silently did not happen, and this\n // reads coverageStatus off the wire. Fail closed. The local gate deliberately lets \"not_run\" pass\n // (see enforceLocalGate) because a credential-free passive scan legitimately produces it.\n const incomplete = report.coverageStatus !== \"complete\"\n && parsed.options[\"allow-incomplete\"] !== true;\n if (confirmed.length || leads.length || incomplete) {\n throw new Error(`hosted security gate failed: ${confirmed.length} confirmed >= ${failOn}; ${leads.length} leads >= ${failOnCandidates ?? \"disabled\"}${incomplete ? `; coverage ${report.coverageStatus}` : \"\"}`);\n }\n if (emitSuccess) {\n out.log(`security gate passed: 0 confirmed >= ${failOn}; 0 leads >= ${failOnCandidates ?? \"disabled\"}; coverage ${report.coverageStatus}. This is not proof that the application is secure.`);\n }\n}\n\nfunction printHostedSecurityPlanRoute(\n out: Pick<typeof console, \"log\">,\n label: string,\n route: HostedSecurityPlan[\"routes\"][\"discovery\"],\n): void {\n const readiness = route.enabled && route.credentialReady ? \"ready\" : [\n route.enabled ? undefined : \"disabled\",\n route.credentialReady ? undefined : \"credential unavailable\",\n ].filter(Boolean).join(\", \");\n out.log(` ${label}: ${route.provider}/${route.model} · policy v${route.policyVersion} · ${readiness}`);\n out.log(` bounds: ${route.maxCallsPerRun} calls/run · ${route.maxInputBytes} input bytes/call · ${route.maxOutputTokens} output tokens/call`);\n}\n\nfunction printHostedCoverage(out: Pick<typeof console, \"log\">, job: HostedSecurityJob): void {\n const coverage = job.coverage;\n out.log(` coverage: ${job.coverageStatus ?? \"pending\"}${coverage?.completeCells !== undefined ? ` ${coverage.completeCells}/${coverage.totalCells ?? \"?\"}` : \"\"}${coverage?.shallowCells ? ` shallow=${coverage.shallowCells}` : \"\"}${coverage?.blockedCells ? ` blocked=${coverage.blockedCells}` : \"\"}${coverage?.unscheduledCells ? ` unscheduled=${coverage.unscheduledCells}` : \"\"}${coverage?.budgetExhaustedCells ? ` budget_exhausted=${coverage.budgetExhaustedCells}` : \"\"}`);\n}\n\nfunction routeLabel(route: HostedSecurityRoute): string {\n return `${route.provider}/${route.model}${route.policyVersion ? ` policy v${route.policyVersion}` : \"\"}`;\n}\n\nconst HOSTED_SEVERITIES = [\"informational\", \"low\", \"medium\", \"high\", \"critical\"] as const;\n\nfunction hostedSeverity(value: string, flag: string): typeof HOSTED_SEVERITIES[number] {\n if (HOSTED_SEVERITIES.includes(value as typeof HOSTED_SEVERITIES[number])) {\n return value as typeof HOSTED_SEVERITIES[number];\n }\n throw new Error(`${flag} must be informational, low, medium, high, or critical`);\n}\n","import { findingsAtOrAbove, type Severity } from \"@odla-ai/security\";\nimport { getScopedPlatformToken } from \"./admin-ai\";\nimport {\n assertArgs,\n numberOpt,\n requiredString,\n stringOpt,\n type ParsedArgv,\n} from \"./argv\";\nimport { loadProjectConfig } from \"./config\";\nimport type { CliDependencies } from \"./cli\";\nimport { hostedSecurityContext, securityProfile } from \"./security-command-context\";\nimport {\n assertHostedSecurityPlanReady,\n enforceHostedReportGate,\n printHostedJob,\n printHostedReport,\n printHostedSecurityIntent,\n printHostedSecurityPlan,\n} from \"./security-command-output\";\nimport { runHostedSecurity } from \"./security\";\nimport {\n followHostedSecurityJob,\n getHostedSecurityIntent,\n getHostedSecurityPlan,\n getHostedSecurityReport,\n startHostedSecurityJob,\n} from \"./security-hosted\";\nimport { getDeveloperToken, platformAudience } from \"./token\";\n\nexport async function runSourceSecurityCommand(\n parsed: ParsedArgv,\n dependencies: CliDependencies,\n sourceId: string,\n): Promise<void> {\n assertArgs(parsed, [\n \"config\", \"env\", \"profile\", \"platform\", \"source\", \"ref\", \"follow\", \"email\", \"open\", \"json\",\n \"ack-redacted-source\", \"plan-digest\", \"fail-on\", \"fail-on-candidates\", \"allow-incomplete\",\n ], 2);\n const follow = parsed.options.follow !== false;\n if (!follow && (parsed.options[\"fail-on\"] !== undefined\n || parsed.options[\"fail-on-candidates\"] !== undefined\n || parsed.options[\"allow-incomplete\"] !== undefined)) {\n throw new Error(\"hosted security gate options require following the job; remove --no-follow\");\n }\n const acknowledgedDigest = requiredString(parsed.options[\"plan-digest\"], \"--plan-digest\");\n const context = await hostedSecurityContext(parsed, dependencies);\n const plan = await getHostedSecurityPlan(context);\n if (parsed.options.json !== true) printHostedSecurityPlan(context.stdout, plan, context.appId);\n assertHostedSecurityPlanReady(plan);\n if (acknowledgedDigest !== plan.planDigest) {\n throw new Error(`--plan-digest does not match the current hosted security plan (${plan.planDigest}); review and explicitly acknowledge the current digest`);\n }\n const requestedRef = stringOpt(parsed.options.ref);\n const requestedProfile = securityProfile(stringOpt(parsed.options.profile));\n const preview = await getHostedSecurityIntent({\n ...context,\n sourceId,\n ref: requestedRef,\n profile: requestedProfile,\n });\n if (parsed.options.json !== true) printHostedSecurityIntent(context.stdout, preview.intent);\n if (preview.plan.planDigest !== plan.planDigest || preview.intent.planDigest !== plan.planDigest) {\n throw new Error(`hosted security plan changed while previewing execution (${preview.plan.planDigest}); review and explicitly acknowledge the current plan digest`);\n }\n const job = await startHostedSecurityJob({\n ...context,\n sourceId,\n ref: requestedRef,\n profile: requestedProfile,\n clientRequestId: crypto.randomUUID(),\n sourceDisclosureAck: parsed.options[\"ack-redacted-source\"] === true ? \"redacted\" : undefined,\n expectedPlanDigest: plan.planDigest,\n expectedExecutionDigest: preview.intent.executionDigest,\n expectedPolicyVersions: {\n discovery: plan.routes.discovery.policyVersion,\n validation: plan.routes.validation.policyVersion,\n },\n });\n const result = follow\n ? await followHostedSecurityJob({\n ...context,\n jobId: job.jobId,\n wait: dependencies.pollWait,\n onUpdate: parsed.options.json === true\n ? undefined\n : (value) => printHostedJob(context.stdout, value, context.platform, context.appId),\n })\n : job;\n if (!follow) {\n if (parsed.options.json === true) {\n context.stdout.log(JSON.stringify({ plan, intent: preview.intent, job: result }, null, 2));\n } else {\n printHostedJob(context.stdout, result, context.platform, context.appId);\n }\n return;\n }\n if (result.status !== \"completed\") {\n if (parsed.options.json === true) {\n context.stdout.log(JSON.stringify({ plan, intent: preview.intent, job: result }, null, 2));\n }\n throw new Error(`hosted security job ${result.jobId} ended ${result.status}${result.errorCode ? `: ${result.errorCode}` : \"\"}`);\n }\n const report = await getHostedSecurityReport({ ...context, jobId: result.jobId });\n if (parsed.options.json === true) {\n context.stdout.log(JSON.stringify({ plan, intent: preview.intent, job: result, report }, null, 2));\n } else {\n printHostedReport(context.stdout, report);\n }\n enforceHostedReportGate(report, parsed, context.stdout, parsed.options.json !== true);\n}\n\nexport async function runLocalSecurityCommand(\n parsed: ParsedArgv,\n dependencies: CliDependencies,\n): Promise<void> {\n if (parsed.options.source === true) {\n throw new Error(\"--source requires a source id; run security sources first\");\n }\n assertArgs(parsed, [\n \"config\", \"env\", \"out\", \"profile\", \"max-hunt-tasks\", \"run-id\", \"platform\",\n \"self\", \"ack-redacted-source\", \"email\", \"open\", \"fail-on\", \"fail-on-candidates\", \"allow-incomplete\",\n ], 3);\n const configPath = stringOpt(parsed.options.config) ?? \"odla.config.mjs\";\n const selfAudit = parsed.options.self === true;\n const open = parsed.options.open === false\n ? false\n : parsed.options.open === true ? true : undefined;\n const platform = stringOpt(parsed.options.platform);\n const doFetch = dependencies.fetch ?? fetch;\n const out = dependencies.stdout ?? console;\n const result = await runHostedSecurity({\n configPath,\n selfAudit,\n target: parsed.positionals[2],\n out: stringOpt(parsed.options.out),\n env: stringOpt(parsed.options.env),\n profile: securityProfile(stringOpt(parsed.options.profile)),\n maxHuntTasks: numberOpt(parsed.options[\"max-hunt-tasks\"], \"--max-hunt-tasks\"),\n runId: stringOpt(parsed.options[\"run-id\"]),\n platform,\n sourceDisclosureAck: parsed.options[\"ack-redacted-source\"] === true ? \"redacted\" : undefined,\n fetch: doFetch,\n stdout: out,\n getToken: async (request) => {\n if (request.scope === \"platform:security:self\") {\n return getScopedPlatformToken({\n platform: request.platform,\n scope: request.scope,\n email: stringOpt(parsed.options.email),\n open,\n fetch: doFetch,\n stdout: out,\n openApprovalUrl: dependencies.openUrl,\n });\n }\n const cfg = await loadProjectConfig(configPath);\n if (platformAudience(cfg.platformUrl) !== platformAudience(request.platform)) {\n throw new Error(\"--platform cannot reuse a project developer token from another platform; update odla.config.mjs and authenticate there\");\n }\n return getDeveloperToken(\n cfg,\n { configPath, email: stringOpt(parsed.options.email), open, openApprovalUrl: dependencies.openUrl },\n doFetch,\n out,\n );\n },\n });\n enforceLocalGate(result.report, parsed);\n}\n\nfunction enforceLocalGate(\n report: Parameters<typeof findingsAtOrAbove>[0],\n parsed: ParsedArgv,\n): void {\n const failOn = severityOpt(stringOpt(parsed.options[\"fail-on\"]) ?? \"high\", \"--fail-on\");\n const candidateValue = parsed.options[\"fail-on-candidates\"];\n const failOnCandidates = candidateValue === false\n ? undefined\n : severityOpt(stringOpt(candidateValue) ?? \"critical\", \"--fail-on-candidates\");\n const confirmed = findingsAtOrAbove(report, failOn);\n const leads = failOnCandidates\n ? findingsAtOrAbove(report, failOnCandidates, true)\n .filter((finding) => finding.disposition !== \"confirmed\")\n : [];\n // \"not_run\" must pass: a credential-free passive scan has no discovery reasoner, so coverage.ts\n // reports not_run, and README advertises exactly that CI recipe without --allow-incomplete.\n // Gating it here would break every deterministic-only run. The no-false-assurance job belongs to\n // the reporter, which prints that zero AI coverage cells is not evidence of complete coverage.\n // The hosted gate is stricter (see enforceHostedReportGate) because there AI always runs.\n const incomplete = report.coverageStatus === \"incomplete\"\n && parsed.options[\"allow-incomplete\"] !== true;\n if (confirmed.length || leads.length || incomplete) {\n throw new Error(`hosted security gate failed: ${confirmed.length} confirmed >= ${failOn}; ${leads.length} leads >= ${failOnCandidates ?? \"disabled\"}${incomplete ? \"; coverage incomplete\" : \"\"}`);\n }\n}\n\nfunction severityOpt(value: string, flag: string): Severity {\n if ([\"informational\", \"low\", \"medium\", \"high\", \"critical\"].includes(value)) {\n return value as Severity;\n }\n throw new Error(`${flag} must be informational, low, medium, high, or critical`);\n}\n","import { isAbsolute, relative, resolve, sep } from \"node:path\";\nimport {\n cloudflareAppProfile,\n createPlatformSecurityReasoners,\n createSecurityHarness,\n genericProfile,\n odlaProfile,\n securityFingerprint,\n type PlatformSecurityRun,\n type SecurityProfile,\n type SecurityReport,\n type SecurityRoleCallBudgetUsage,\n} from \"@odla-ai/security\";\nimport { FileRunStore, snapshotDirectory, writeSecurityArtifacts } from \"@odla-ai/security/node\";\nimport { loadProjectConfig } from \"./config\";\n\n/** Built-in security coverage profile selected for a hosted reasoning run. */\nexport type HostedSecurityProfile = \"odla\" | \"cloudflare-app\" | \"generic\";\n\n/** Exact attribution and authorization need supplied to a lazy token callback. */\nexport interface HostedSecurityTokenRequest {\n platform: string;\n appId: string;\n env: string;\n selfAudit: boolean;\n /** Self-audit asks the caller for an explicitly scoped platform credential. */\n /** Ordinary app runs use owner authority and therefore request no platform scope. */\n scope: \"platform:security:self\" | null;\n}\n\n/** Local snapshot/orchestration controls for an app-attributed hosted security\n * run. The platform supplies model routes and provider credentials. */\nexport interface RunHostedSecurityOptions {\n /** Project config; loaded for customer-app runs and ignored for self-audit. */\n configPath?: string;\n /** Scan odla itself under the protected odla-ai/prod identity. */\n selfAudit?: boolean;\n /** Repository directory to snapshot. Defaults to the config root or cwd for self-audit. */\n target?: string;\n /** Private artifact directory. Defaults to `<target>/.odla/security/hosted`. */\n out?: string;\n /** Customer environment. Must be declared in config. Self-audit always uses prod. */\n env?: string;\n profile?: HostedSecurityProfile;\n maxHuntTasks?: number;\n /** Exact acknowledgement required before any source capture or network call. */\n sourceDisclosureAck?: \"redacted\";\n /** Optional client correlation id; the platform returns the authoritative run id. */\n runId?: string;\n /** Platform override. Customer runs otherwise use config.platformUrl. */\n platform?: string;\n /** Injected app credential; for self-audit this must be explicitly scoped by the caller. */\n token?: string;\n /** Lazy token acquisition. Receives the exact app/env and required scope. */\n getToken?: (request: HostedSecurityTokenRequest) => string | Promise<string>;\n fetch?: typeof fetch;\n signal?: AbortSignal;\n stdout?: Pick<typeof console, \"log\" | \"error\">;\n}\n\n/** Completed local report, public platform run metadata, and private artifact path. */\nexport interface HostedSecurityResult {\n report: SecurityReport;\n run: Readonly<PlatformSecurityRun>;\n output: string;\n}\n\n/**\n * Run the hosted, redacted-source security harness for an odla app or odla's\n * protected self-audit identity. Provider/model selection and provider secrets\n * remain platform-owned; this function accepts only an app/scoped bearer and\n * the opaque role grants remain inside @odla-ai/security's reasoner closures.\n */\nexport async function runHostedSecurity(options: RunHostedSecurityOptions): Promise<HostedSecurityResult> {\n if (options.sourceDisclosureAck !== \"redacted\") {\n throw new Error(\"Hosted security requires sourceDisclosureAck=redacted before repository source may leave this process\");\n }\n\n const selfAudit = options.selfAudit === true;\n const cfg = selfAudit ? undefined : await loadProjectConfig(options.configPath ?? \"odla.config.mjs\");\n const appId = selfAudit ? \"odla-ai\" : cfg!.app.id;\n const env = selfAudit ? \"prod\" : selectEnv(options.env, cfg!.envs, cfg!.configPath, cfg!.rootDir);\n const platform = options.platform ?? cfg?.platformUrl ?? \"https://odla.ai\";\n const target = resolve(options.target ?? cfg?.rootDir ?? \".\");\n const output = resolve(options.out ?? resolve(target, \".odla/security/hosted\"));\n const outputRelative = relative(target, output).split(sep).join(\"/\");\n if (!outputRelative) throw new Error(\"Hosted security output cannot be the repository root\");\n // This is the desired first-pass ceiling. The hosted reasoner's immutable\n // call budget automatically reserves recon, caps hunts, then funds retries.\n const profile = profileFor(options.profile ?? \"odla\", options.maxHuntTasks ?? 12);\n\n const tokenRequest: HostedSecurityTokenRequest = {\n platform,\n appId,\n env,\n selfAudit,\n scope: selfAudit ? \"platform:security:self\" : null,\n };\n const token = await injectedToken(options, tokenRequest);\n const snapshot = await snapshotDirectory(target, {\n exclude: !outputRelative.startsWith(\"../\") && !isAbsolute(outputRelative) ? [outputRelative] : [],\n });\n const hosted = await createPlatformSecurityReasoners({\n platform,\n token,\n appId,\n env,\n repository: snapshot.repository,\n revision: snapshot.revision,\n snapshotDigest: snapshot.digest,\n sourceDisclosure: \"redacted\",\n clientRunId: options.runId ?? crypto.randomUUID(),\n ...(selfAudit ? { selfAudit: { enabled: true as const, subject: \"service:odla-security-self-audit\" } } : {}),\n fetch: options.fetch,\n signal: options.signal,\n });\n const harness = createSecurityHarness({\n profile,\n store: new FileRunStore(resolve(output, \"state\")),\n discoveryReasoner: hosted.discoveryReasoner,\n validationReasoner: hosted.validationReasoner,\n policy: {\n modelSourceDisclosure: \"redacted\",\n active: false,\n allowNetwork: false,\n },\n });\n const report = await harness.run(snapshot, { runId: hosted.run.runId, signal: options.signal });\n await writeSecurityArtifacts(output, report);\n const reportDigest = await securityFingerprint(report);\n await hosted.complete({\n reportDigest,\n coverageStatus: report.coverageStatus,\n confirmed: report.metrics.confirmed,\n candidates: report.metrics.candidates,\n }, { signal: options.signal });\n printSummary(options.stdout ?? console, appId, env, hosted.run, report, output);\n return Object.freeze({ report, run: hosted.run, output });\n}\n\nfunction selectEnv(requested: string | undefined, declared: string[], configPath: string, rootDir: string): string {\n const env = requested ?? (declared.includes(\"dev\") ? \"dev\" : declared[0]);\n if (!env || !declared.includes(env)) {\n const shown = relative(rootDir, configPath) || configPath;\n throw new Error(`env \"${env ?? \"\"}\" is not declared in ${shown}`);\n }\n return env;\n}\n\nasync function injectedToken(options: RunHostedSecurityOptions, request: HostedSecurityTokenRequest): Promise<string> {\n const value = options.token ?? await options.getToken?.(Object.freeze({ ...request }));\n if (typeof value !== \"string\" || value.length < 8 || value.length > 8_192 || /\\s|[\\u0000-\\u001f\\u007f]/.test(value)) {\n throw new Error(\n request.selfAudit\n ? \"Self-audit requires an injected, scoped platform security token\"\n : \"Hosted security requires an injected app developer token or getToken callback\",\n );\n }\n return value;\n}\n\nfunction profileFor(name: HostedSecurityProfile, maxHuntTasks: number | undefined): SecurityProfile {\n const profile = name === \"odla\"\n ? odlaProfile()\n : name === \"cloudflare-app\"\n ? cloudflareAppProfile()\n : name === \"generic\"\n ? genericProfile()\n : undefined;\n if (!profile) throw new Error(`unknown security profile \"${String(name)}\"`);\n if (maxHuntTasks === undefined) return profile;\n if (!Number.isSafeInteger(maxHuntTasks) || maxHuntTasks < 1) throw new Error(\"maxHuntTasks must be a positive integer\");\n return { ...profile, maxHuntTasks };\n}\n\nfunction printSummary(\n out: Pick<typeof console, \"log\" | \"error\">,\n appId: string,\n env: string,\n run: Readonly<PlatformSecurityRun>,\n report: SecurityReport,\n output: string,\n): void {\n const complete = report.coverage.filter((cell) => cell.state === \"complete\").length;\n out.log(`security: ${appId}/${env} run=${run.runId} profile=${run.profileVersion}`);\n out.log(` discovery: ${run.discovery.identity.provider}/${run.discovery.identity.model}`);\n out.log(` validation: ${run.validation.identity.provider}/${run.validation.identity.model}`);\n out.log(` coverage: ${report.coverageStatus} ${complete}/${report.coverage.length} blocked=${report.metrics.blockedCells} shallow=${report.metrics.shallowCells} unscheduled=${report.metrics.unscheduledCells} budget_exhausted=${report.metrics.budgetExhaustedCells}`);\n if (report.callBudget) out.log(` calls: discovery=${formatBudget(report.callBudget.discovery)} validation=${formatBudget(report.callBudget.validation)}`);\n out.log(` findings: confirmed=${report.metrics.confirmed} needs_reproduction=${report.metrics.needsReproduction} candidates=${report.metrics.candidates}`);\n out.log(` report: ${resolve(output, \"REPORT.md\")}`);\n}\n\nfunction formatBudget(usage: SecurityRoleCallBudgetUsage | undefined): string {\n return usage ? `${usage.usedCalls}/${usage.maxCalls} skipped=${usage.skippedCalls}` : \"caller-managed\";\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { openUrl } from \"./open\";\nimport {\n githubRepositoryName,\n hostedIdentifier,\n hostedPollInterval,\n hostedPollTimeout,\n requestHostedSecurityJson,\n trustedGitHubInstallUrl,\n waitForHostedPoll,\n} from \"./security-hosted-request\";\nimport type {\n ConnectGitHubSecuritySourceOptions,\n DisconnectGitHubSecuritySourceOptions,\n GitHubConnectionAttempt,\n GitHubConnectionStatus,\n GitHubSecuritySource,\n ListGitHubSecuritySourcesOptions,\n} from \"./security-hosted-types\";\n\n/** Begin GitHub App installation, launch its server-issued GitHub URL, and\n * poll the exact attempt until the callback has connected a source. */\nexport async function connectGitHubSecuritySource(\n options: ConnectGitHubSecuritySourceOptions,\n): Promise<GitHubConnectionStatus> {\n const out = options.stdout ?? console;\n const repository = githubRepositoryName(options.repository);\n const attempt = await requestHostedSecurityJson<GitHubConnectionAttempt>(\n options,\n \"/registry/github/connect\",\n {\n method: \"POST\",\n body: JSON.stringify({\n appId: hostedIdentifier(options.appId, \"appId\"),\n env: hostedIdentifier(options.env, \"env\"),\n repository,\n }),\n },\n \"start GitHub connection\",\n );\n const serverExpiry = Date.parse(attempt?.expiresAt ?? \"\");\n if (!attempt?.attemptId || !attempt.installUrl || !Number.isFinite(serverExpiry)) {\n throw new Error(\"odla.ai returned an invalid GitHub connection attempt\");\n }\n const installUrl = trustedGitHubInstallUrl(attempt.installUrl);\n out.log(`GitHub approval: ${installUrl}`);\n if (options.open !== false) {\n await (options.openInstallUrl ?? openUrl)(installUrl);\n out.log(\"github: opened installation approval in your browser\");\n }\n const interval = hostedPollInterval(options.pollIntervalMs);\n const now = options.now ?? Date.now;\n const deadline = Math.min(serverExpiry, now() + hostedPollTimeout(options.pollTimeoutMs));\n const wait = options.wait ?? waitForHostedPoll;\n while (true) {\n const state = await requestHostedSecurityJson<GitHubConnectionStatus>(\n options,\n `/registry/github/connect/${encodeURIComponent(attempt.attemptId)}`,\n {},\n \"check GitHub connection\",\n );\n if (state.status !== \"pending\") {\n if (state.status === \"connected\") return state;\n throw new Error(`GitHub connection ${state.status}${state.failureCode ? `: ${state.failureCode}` : \"\"}`);\n }\n if (now() >= deadline) throw new Error(\"GitHub connection approval timed out\");\n await wait(Math.min(interval, Math.max(0, deadline - now())), options.signal);\n }\n}\n\n/** List repository sources the current app owner connected for one environment. */\nexport async function listGitHubSecuritySources(\n options: ListGitHubSecuritySourcesOptions,\n): Promise<GitHubSecuritySource[]> {\n const appId = hostedIdentifier(options.appId, \"appId\");\n const env = hostedIdentifier(options.env, \"env\");\n const body = await requestHostedSecurityJson<{ sources: GitHubSecuritySource[] }>(\n options,\n `/registry/apps/${encodeURIComponent(appId)}/github/sources?env=${encodeURIComponent(env)}`,\n {},\n \"list GitHub security sources\",\n );\n return Array.isArray(body.sources) ? body.sources : [];\n}\n\n/** Revoke odla's use of one saved source without requiring a GitHub-side App\n * uninstall. The server marks the source deleted and rejects new jobs. */\nexport async function disconnectGitHubSecuritySource(\n options: DisconnectGitHubSecuritySourceOptions,\n): Promise<void> {\n const appId = hostedIdentifier(options.appId, \"appId\");\n const sourceId = hostedIdentifier(options.sourceId, \"sourceId\");\n await requestHostedSecurityJson<{ ok: true }>(\n options,\n `/registry/apps/${encodeURIComponent(appId)}/github/sources/${encodeURIComponent(sourceId)}`,\n { method: \"DELETE\" },\n \"disconnect GitHub security source\",\n );\n}\n\n/** Parse an HTTPS, ssh://, or git@github.com origin without retaining embedded\n * credentials. Only github.com owner/name remotes are accepted. */\nexport function repositoryFromGitRemote(remoteInput: string): string {\n const remote = remoteInput.trim();\n const scp = /^git@github\\.com:([^/\\s]+)\\/([^/\\s]+?)\\/?$/.exec(remote);\n if (scp) return githubRepositoryName(`${scp[1]}/${scp[2]!.replace(/\\.git$/, \"\")}`);\n let url: URL;\n try {\n url = new URL(remote);\n } catch {\n throw new Error(\"origin must be a github.com HTTPS or SSH repository URL\");\n }\n if (url.hostname !== \"github.com\" || (url.protocol !== \"https:\" && url.protocol !== \"ssh:\")) {\n throw new Error(\"origin must be a github.com HTTPS or SSH repository URL\");\n }\n if (url.password || (url.protocol === \"https:\" && url.username) || url.search || url.hash) {\n throw new Error(\"credential-bearing GitHub origin URLs are not accepted\");\n }\n const parts = url.pathname.replace(/^\\/+|\\/+$/g, \"\").split(\"/\");\n if (parts.length !== 2) {\n throw new Error(\"origin must identify one GitHub owner/name repository\");\n }\n return githubRepositoryName(`${parts[0]}/${parts[1]!.replace(/\\.git$/, \"\")}`);\n}\n\n/** Read the current repository's origin without invoking a shell. */\nexport async function inferGitHubRepository(\n cwd = process.cwd(),\n readOrigin: (cwd: string) => Promise<string> = defaultReadOrigin,\n): Promise<string> {\n let remote: string;\n try {\n remote = await readOrigin(cwd);\n } catch {\n throw new Error(\"Could not read git origin; pass --repo owner/name\");\n }\n return repositoryFromGitRemote(remote);\n}\n\nasync function defaultReadOrigin(cwd: string): Promise<string> {\n const result = await promisify(execFile)(\n \"git\",\n [\"remote\", \"get-url\", \"origin\"],\n { cwd, encoding: \"utf8\" },\n );\n return result.stdout;\n}\n","import { platformAudience } from \"./token\";\nimport type {\n HostedSecurityPlan,\n HostedSecurityPlanRoute,\n HostedSecurityRequestOptions,\n} from \"./security-hosted-types\";\n\nexport async function requestHostedSecurityJson<T>(\n options: HostedSecurityRequestOptions,\n path: string,\n init: RequestInit,\n action: string,\n): Promise<T> {\n const platform = platformAudience(options.platform);\n const token = hostedSecurityCredential(options.token);\n const requestInit = {\n ...init,\n redirect: \"error\",\n credentials: \"omit\",\n cache: \"no-store\",\n signal: options.signal,\n headers: {\n authorization: `Bearer ${token}`,\n \"content-type\": \"application/json\",\n ...init.headers,\n },\n } as RequestInit;\n const response = await (options.fetch ?? fetch)(new URL(path, platform), requestInit);\n const body = await response.json().catch(() => ({})) as T & {\n error?: { code?: string; message?: string };\n };\n if (!response.ok) {\n const code = optionalHostedText(body.error?.code, \"error code\", 128);\n const message = optionalHostedText(body.error?.message, \"error message\", 300);\n throw new Error(`${action} failed (${response.status})${code ? ` ${code}` : \"\"}${message ? `: ${message}` : \"\"}`);\n }\n return body;\n}\n\nexport function hostedIdentifier(value: string, name: string): string {\n const result = optionalHostedText(value, name, 180);\n if (!result || !/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(result)) {\n throw new Error(`${name} is invalid`);\n }\n return result;\n}\n\nexport function positivePolicyVersion(value: unknown, name: string): number {\n if (!Number.isSafeInteger(value) || (value as number) < 1) {\n throw new Error(`${name} is invalid`);\n }\n return value as number;\n}\n\nexport function optionalHostedText(\n value: unknown,\n name: string,\n maxLength: number,\n): string | undefined {\n if (value === undefined || value === null || value === \"\") return undefined;\n if (typeof value !== \"string\" || value.length > maxLength || /[\\u0000-\\u001f\\u007f]/.test(value)) {\n throw new Error(`${name} is invalid`);\n }\n return value;\n}\n\nexport function githubRepositoryName(value: string): string {\n if (typeof value !== \"string\" || value.length > 201) {\n throw new Error(\"repository must be owner/name\");\n }\n const parts = value.split(\"/\");\n const owner = parts[0] ?? \"\";\n const name = (parts[1] ?? \"\").replace(/\\.git$/i, \"\");\n if (parts.length !== 2\n || !/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,98}[A-Za-z0-9])?$/.test(owner)\n || !/^[A-Za-z0-9_.-]{1,100}$/.test(name)\n || name === \".\" || name === \"..\") {\n throw new Error(\"repository must be owner/name\");\n }\n return `${owner}/${name}`;\n}\n\nexport function trustedGitHubInstallUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new Error(\"odla.ai returned an invalid GitHub installation URL\");\n }\n if (url.protocol !== \"https:\" || url.hostname !== \"github.com\" || url.username || url.password) {\n throw new Error(\"odla.ai returned an untrusted GitHub installation URL\");\n }\n return url.toString();\n}\n\nexport function hostedPollInterval(value = 2_000): number {\n if (!Number.isSafeInteger(value) || value < 100 || value > 30_000) {\n throw new Error(\"poll interval must be 100-30000ms\");\n }\n return value;\n}\n\nexport function hostedPollTimeout(value = 10 * 60_000): number {\n if (!Number.isSafeInteger(value) || value < 1_000 || value > 60 * 60_000) {\n throw new Error(\"poll timeout must be 1000-3600000ms\");\n }\n return value;\n}\n\nexport async function waitForHostedPoll(\n milliseconds: number,\n signal?: AbortSignal,\n): Promise<void> {\n if (signal?.aborted) throw signal.reason ?? new DOMException(\"aborted\", \"AbortError\");\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(resolve, milliseconds);\n signal?.addEventListener(\"abort\", () => {\n clearTimeout(timer);\n reject(signal.reason ?? new DOMException(\"aborted\", \"AbortError\"));\n }, { once: true });\n });\n}\n\nexport function isValidHostedSecurityPlan(\n value: HostedSecurityPlan,\n env: string,\n): boolean {\n if (!value || value.env !== env || !/^sha256:[a-f0-9]{64}$/.test(value.planDigest)\n || value.consentContract !== \"odla.hosted-security-consent.v1\"\n || value.reportProjection !== \"odla.hosted-security-report.v1\"\n || value.redactionContract !== \"odla.best-effort-credential-pattern-redaction.v1\"\n || typeof value.promptBundle !== \"string\" || value.promptBundle.length < 1 || value.promptBundle.length > 100\n || typeof value.ready !== \"boolean\"\n || typeof value.independent !== \"boolean\" || value.sourceDisclosure !== \"redacted\"\n || value.targetExecution !== false || !Number.isSafeInteger(value.reportRetentionDays)\n || value.reportRetentionDays < 1) return false;\n const validRoute = (\n route: HostedSecurityPlanRoute | undefined,\n purpose: HostedSecurityPlanRoute[\"purpose\"],\n ) => !!route\n && route.purpose === purpose\n && typeof route.enabled === \"boolean\"\n && typeof route.credentialReady === \"boolean\"\n && typeof route.provider === \"string\" && route.provider.length > 0 && route.provider.length <= 100\n && typeof route.model === \"string\" && route.model.length > 0 && route.model.length <= 200\n && Number.isSafeInteger(route.policyVersion) && route.policyVersion >= 1\n && Number.isSafeInteger(route.maxCallsPerRun) && route.maxCallsPerRun >= 1\n && Number.isSafeInteger(route.maxInputBytes) && route.maxInputBytes >= 1\n && Number.isSafeInteger(route.maxOutputTokens) && route.maxOutputTokens >= 1;\n return validRoute(value.routes?.discovery, \"security.discovery\")\n && validRoute(value.routes?.validation, \"security.validation\");\n}\n\nfunction hostedSecurityCredential(value: string): string {\n if (typeof value !== \"string\" || value.length < 8 || value.length > 8_192\n || /\\s|[\\u0000-\\u001f\\u007f]/.test(value)) {\n throw new Error(\"Hosted security requires an injected odla developer token\");\n }\n return value;\n}\n","import {\n hostedIdentifier,\n isValidHostedSecurityPlan,\n optionalHostedText,\n requestHostedSecurityJson,\n} from \"./security-hosted-request\";\nimport type {\n GetHostedSecurityIntentOptions,\n HostedSecurityIntent,\n HostedSecurityIntentResponse,\n} from \"./security-hosted-types\";\n\n/** Fetch the atomic processing-plan and source/ref/profile execution preview. */\nexport async function getHostedSecurityIntent(\n options: GetHostedSecurityIntentOptions,\n): Promise<HostedSecurityIntentResponse> {\n const appId = hostedIdentifier(options.appId, \"appId\");\n const env = hostedIdentifier(options.env, \"env\");\n const sourceId = hostedIdentifier(options.sourceId, \"sourceId\");\n const ref = optionalHostedText(options.ref, \"ref\", 255);\n const query = new URLSearchParams({ env, sourceId });\n if (ref) query.set(\"ref\", ref);\n if (options.profile) query.set(\"profile\", options.profile);\n const response = await requestHostedSecurityJson<HostedSecurityIntentResponse>(\n options,\n `/registry/apps/${encodeURIComponent(appId)}/security/intent?${query.toString()}`,\n {},\n \"read hosted security execution intent\",\n );\n if (!isValidHostedSecurityPlan(response.plan, env)\n || !isValidIntent(response.intent, { appId, env, sourceId })) {\n throw new Error(\"odla.ai returned an invalid hosted security execution intent\");\n }\n if (response.intent.planDigest !== response.plan.planDigest) {\n throw new Error(\"odla.ai returned a hosted security intent for a different processing plan\");\n }\n return response;\n}\n\nfunction isValidIntent(\n value: HostedSecurityIntent | undefined,\n expected: { appId: string; env: string; sourceId: string },\n): value is HostedSecurityIntent {\n return !!value\n && value.executionContract === \"odla.hosted-security-execution-consent.v1\"\n && /^sha256:[a-f0-9]{64}$/.test(value.executionDigest)\n && /^sha256:[a-f0-9]{64}$/.test(value.planDigest)\n && value.appId === expected.appId && value.env === expected.env && value.sourceId === expected.sourceId\n && typeof value.repository === \"string\" && value.repository.length > 2 && value.repository.length <= 201\n && typeof value.defaultBranch === \"string\" && value.defaultBranch.length > 0 && value.defaultBranch.length <= 255\n && typeof value.requestedRef === \"string\" && value.requestedRef.length > 0\n && value.requestedRef.length <= 255 && !/[\\u0000-\\u001f\\u007f]/.test(value.requestedRef)\n && [\"odla\", \"cloudflare-app\", \"generic\"].includes(value.profile)\n && value.sourceDisclosure === \"redacted\";\n}\n","import {\n hostedIdentifier,\n hostedPollInterval,\n hostedPollTimeout,\n isValidHostedSecurityPlan,\n optionalHostedText,\n positivePolicyVersion,\n requestHostedSecurityJson,\n waitForHostedPoll,\n} from \"./security-hosted-request\";\nimport type {\n FollowHostedSecurityJobOptions,\n GetHostedSecurityJobOptions,\n HostedSecurityJob,\n HostedSecurityJobStatus,\n HostedSecurityPlan,\n HostedSecurityReport,\n ListGitHubSecuritySourcesOptions,\n ListHostedSecurityJobsOptions,\n StartHostedSecurityJobOptions,\n} from \"./security-hosted-types\";\n\n/** Read the admin-selected routes, budgets, readiness, disclosure boundary,\n * and digest that must be acknowledged when a hosted review is enqueued. */\nexport async function getHostedSecurityPlan(\n options: ListGitHubSecuritySourcesOptions,\n): Promise<HostedSecurityPlan> {\n const appId = hostedIdentifier(options.appId, \"appId\");\n const env = hostedIdentifier(options.env, \"env\");\n const plan = await requestHostedSecurityJson<HostedSecurityPlan>(\n options,\n `/registry/apps/${encodeURIComponent(appId)}/security/plan?env=${encodeURIComponent(env)}`,\n {},\n \"read hosted security disclosure plan\",\n );\n if (!isValidHostedSecurityPlan(plan, env)) {\n throw new Error(\"odla.ai returned an invalid hosted security disclosure plan\");\n }\n return plan;\n}\n\n/** Enqueue a commit-pinned server-side review. The server resolves sourceId to\n * its saved GitHub App installation; clients cannot choose an installation or\n * pass a PAT. */\nexport async function startHostedSecurityJob(\n options: StartHostedSecurityJobOptions,\n): Promise<HostedSecurityJob> {\n if (options.sourceDisclosureAck !== \"redacted\") {\n throw new Error(\"Hosted GitHub security requires sourceDisclosureAck=redacted; repository access alone is not disclosure consent\");\n }\n const appId = hostedIdentifier(options.appId, \"appId\");\n const env = hostedIdentifier(options.env, \"env\");\n const sourceId = hostedIdentifier(options.sourceId, \"sourceId\");\n const ref = optionalHostedText(options.ref, \"ref\", 255);\n const expectedPlanDigest = securityPlanDigest(options.expectedPlanDigest);\n const expectedExecutionDigest = securityExecutionDigest(options.expectedExecutionDigest);\n const expectedPolicyVersions = {\n discovery: positivePolicyVersion(\n options.expectedPolicyVersions?.discovery,\n \"expected discovery policy version\",\n ),\n validation: positivePolicyVersion(\n options.expectedPolicyVersions?.validation,\n \"expected validation policy version\",\n ),\n };\n let body: { job: HostedSecurityJob };\n try {\n body = await requestHostedSecurityJson<{ job: HostedSecurityJob }>(\n options,\n `/registry/apps/${encodeURIComponent(appId)}/security/jobs`,\n {\n method: \"POST\",\n body: JSON.stringify({\n env,\n sourceId,\n ...(ref ? { ref } : {}),\n ...(options.profile ? { profile: options.profile } : {}),\n ...(options.clientRequestId\n ? { clientRequestId: hostedIdentifier(options.clientRequestId, \"clientRequestId\") }\n : {}),\n sourceDisclosure: \"redacted\",\n expectedPlanDigest,\n expectedExecutionDigest,\n expectedPolicyVersions,\n }),\n },\n \"start hosted security job\",\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (/\\b(?:plan_conflict|policy_conflict|intent_conflict|security_ai_not_ready)\\b/.test(message)) {\n throw new Error(\"Hosted security plan or execution intent changed or became unavailable after review; fetch a fresh intent and explicitly acknowledge its digest before enqueueing again\", { cause: error });\n }\n throw error;\n }\n if (!body.job?.jobId) {\n throw new Error(\"odla.ai returned an invalid hosted security job\");\n }\n return body.job;\n}\n\n/** Read one bounded hosted job status without an archive or explicit source excerpt. */\nexport async function getHostedSecurityJob(\n options: GetHostedSecurityJobOptions,\n): Promise<HostedSecurityJob> {\n const body = await requestHostedSecurityJson<{ job: HostedSecurityJob }>(\n options,\n hostedJobPath(options.appId, options.jobId),\n {},\n \"read hosted security job\",\n );\n if (!body.job?.jobId) throw new Error(\"odla.ai returned an invalid hosted security job\");\n return body.job;\n}\n\n/** List bounded, newest-first job metadata for an app environment. */\nexport async function listHostedSecurityJobs(\n options: ListHostedSecurityJobsOptions,\n): Promise<HostedSecurityJob[]> {\n const appId = hostedIdentifier(options.appId, \"appId\");\n const env = hostedIdentifier(options.env, \"env\");\n const body = await requestHostedSecurityJson<{ jobs: HostedSecurityJob[] }>(\n options,\n `/registry/apps/${encodeURIComponent(appId)}/security/jobs?env=${encodeURIComponent(env)}`,\n {},\n \"list hosted security jobs\",\n );\n return Array.isArray(body.jobs) ? body.jobs : [];\n}\n\n/** Poll one exact job until it reaches a terminal state. */\nexport async function followHostedSecurityJob(\n options: FollowHostedSecurityJobOptions,\n): Promise<HostedSecurityJob> {\n const interval = hostedPollInterval(options.pollIntervalMs);\n const now = options.now ?? Date.now;\n const deadline = now() + hostedPollTimeout(options.pollTimeoutMs ?? 60 * 60_000);\n const wait = options.wait ?? waitForHostedPoll;\n let prior = \"\";\n while (true) {\n const job = await getHostedSecurityJob(options);\n const fingerprint = `${job.status}:${job.updatedAt}`;\n if (fingerprint !== prior) options.onUpdate?.(Object.freeze({ ...job }));\n prior = fingerprint;\n if (isTerminalHostedSecurityStatus(job.status)) return job;\n if (now() >= deadline) {\n throw new Error(`Hosted security job ${job.jobId} did not finish before the polling deadline`);\n }\n await wait(Math.min(interval, Math.max(0, deadline - now())), options.signal);\n }\n}\n\n/** Fetch the bounded normalized report projection for a completed hosted job. */\nexport async function getHostedSecurityReport(\n options: GetHostedSecurityJobOptions,\n): Promise<HostedSecurityReport> {\n return requestHostedSecurityJson<HostedSecurityReport>(\n options,\n `${hostedJobPath(options.appId, options.jobId)}/report`,\n {},\n \"read hosted security report\",\n );\n}\n\n/** Return whether a hosted job status can no longer transition. */\nexport function isTerminalHostedSecurityStatus(\n status: HostedSecurityJobStatus,\n): boolean {\n return status === \"completed\" || status === \"failed\" || status === \"cancelled\";\n}\n\nfunction hostedJobPath(appIdInput: string, jobIdInput: string): string {\n const appId = hostedIdentifier(appIdInput, \"appId\");\n const jobId = hostedIdentifier(jobIdInput, \"jobId\");\n return `/registry/apps/${encodeURIComponent(appId)}/security/jobs/${encodeURIComponent(jobId)}`;\n}\n\nfunction securityPlanDigest(value: string): `sha256:${string}` {\n if (!/^sha256:[a-f0-9]{64}$/.test(value)) {\n throw new Error(\"expected plan digest must be a sha256 digest from security plan\");\n }\n return value as `sha256:${string}`;\n}\n\nfunction securityExecutionDigest(value: string): `sha256:${string}` {\n if (!/^sha256:[a-f0-9]{64}$/.test(value)) {\n throw new Error(\"expected execution digest must be a sha256 digest from security intent\");\n }\n return value as `sha256:${string}`;\n}\n","import {\n assertArgs,\n requiredString,\n stringOpt,\n type ParsedArgv,\n} from \"./argv\";\nimport type { CliDependencies } from \"./cli\";\nimport {\n hostedSecurityContext,\n interactiveConfirmation,\n requiredSecurityPositional,\n} from \"./security-command-context\";\nimport {\n printHostedJob,\n printHostedReport,\n printHostedSecurityPlan,\n} from \"./security-command-output\";\nimport {\n runLocalSecurityCommand,\n runSourceSecurityCommand,\n} from \"./security-run-command\";\nimport {\n connectGitHubSecuritySource,\n disconnectGitHubSecuritySource,\n followHostedSecurityJob,\n getHostedSecurityJob,\n getHostedSecurityPlan,\n getHostedSecurityReport,\n inferGitHubRepository,\n listGitHubSecuritySources,\n} from \"./security-hosted\";\nimport { openUrl } from \"./open\";\n\nexport async function securityCommand(\n parsed: ParsedArgv,\n dependencies: CliDependencies,\n): Promise<void> {\n const sub = parsed.positionals[1];\n if (sub === \"github\") {\n await githubSecurityCommand(parsed, dependencies);\n return;\n }\n if (sub === \"plan\") {\n assertArgs(parsed, [\"config\", \"env\", \"platform\", \"email\", \"open\", \"json\"], 2);\n const context = await hostedSecurityContext(parsed, dependencies);\n const plan = await getHostedSecurityPlan(context);\n if (parsed.options.json === true) context.stdout.log(JSON.stringify(plan, null, 2));\n else printHostedSecurityPlan(context.stdout, plan, context.appId);\n return;\n }\n if (sub === \"sources\") {\n await listSecuritySources(parsed, dependencies);\n return;\n }\n if (sub === \"status\") {\n await securityStatus(parsed, dependencies);\n return;\n }\n if (sub === \"report\") {\n assertArgs(parsed, [\"config\", \"env\", \"platform\", \"email\", \"open\", \"json\"], 3);\n const jobId = requiredSecurityPositional(parsed, 2, \"job id\");\n const context = await hostedSecurityContext(parsed, dependencies);\n const report = await getHostedSecurityReport({ ...context, jobId });\n if (parsed.options.json === true) context.stdout.log(JSON.stringify(report, null, 2));\n else printHostedReport(context.stdout, report);\n return;\n }\n if (sub !== \"run\") {\n throw new Error('unknown security command. Try \"odla-ai security plan\", \"security sources\", or \"security run\".');\n }\n const sourceId = stringOpt(parsed.options.source);\n if (sourceId) await runSourceSecurityCommand(parsed, dependencies, sourceId);\n else await runLocalSecurityCommand(parsed, dependencies);\n}\n\nasync function githubSecurityCommand(\n parsed: ParsedArgv,\n dependencies: CliDependencies,\n): Promise<void> {\n const action = parsed.positionals[2];\n if (action === \"disconnect\") {\n assertArgs(parsed, [\"config\", \"env\", \"platform\", \"source\", \"email\", \"open\", \"yes\"], 3);\n const context = await hostedSecurityContext(parsed, dependencies);\n const sourceId = requiredString(parsed.options.source, \"--source\");\n const confirmed = parsed.options.yes === true || await interactiveConfirmation(\n `Disconnect GitHub security source ${sourceId} from ${context.appId}/${context.env}?`,\n dependencies,\n );\n if (!confirmed) {\n throw new Error(\"GitHub source disconnect cancelled; pass --yes in a non-interactive shell\");\n }\n await disconnectGitHubSecuritySource({ ...context, sourceId });\n context.stdout.log(`github: disconnected ${sourceId} from ${context.appId}/${context.env}`);\n return;\n }\n if (action !== \"connect\") {\n throw new Error('unknown security github command. Try \"odla-ai security github connect\".');\n }\n assertArgs(parsed, [\"config\", \"env\", \"platform\", \"repo\", \"email\", \"open\"], 3);\n const context = await hostedSecurityContext(parsed, dependencies);\n const repository = stringOpt(parsed.options.repo)\n ?? await inferGitHubRepository(process.cwd(), dependencies.readGitOrigin);\n const connection = await connectGitHubSecuritySource({\n ...context,\n repository,\n open: parsed.options.open !== false,\n openInstallUrl: dependencies.openUrl ?? openUrl,\n wait: dependencies.pollWait,\n stdout: context.stdout,\n });\n context.stdout.log(`github: connected ${connection.repository ?? repository} (${connection.sourceId ?? \"source pending\"})`);\n context.stdout.log(\"github: odla.ai stores the installation; no PAT or GitHub token is written locally\");\n}\n\nasync function listSecuritySources(\n parsed: ParsedArgv,\n dependencies: CliDependencies,\n): Promise<void> {\n assertArgs(parsed, [\"config\", \"env\", \"platform\", \"email\", \"open\", \"json\"], 2);\n const context = await hostedSecurityContext(parsed, dependencies);\n const [plan, sources] = await Promise.all([\n getHostedSecurityPlan(context),\n listGitHubSecuritySources(context),\n ]);\n if (parsed.options.json === true) {\n context.stdout.log(JSON.stringify({ plan, sources }, null, 2));\n return;\n }\n printHostedSecurityPlan(context.stdout, plan, context.appId);\n if (!sources.length) {\n context.stdout.log(`No GitHub security sources connected for ${context.appId}/${context.env}.`);\n return;\n }\n context.stdout.log(`GitHub security sources for ${context.appId}/${context.env}\\nsource\\trepository\\tdefault ref\\tstatus`);\n for (const source of sources) {\n context.stdout.log(`${source.sourceId}\\t${source.repository}\\t${source.defaultBranch}\\t${source.status}`);\n }\n}\n\nasync function securityStatus(\n parsed: ParsedArgv,\n dependencies: CliDependencies,\n): Promise<void> {\n assertArgs(parsed, [\"config\", \"env\", \"platform\", \"email\", \"open\", \"json\", \"follow\"], 3);\n const jobId = requiredSecurityPositional(parsed, 2, \"job id\");\n const context = await hostedSecurityContext(parsed, dependencies);\n const job = parsed.options.follow === true\n ? await followHostedSecurityJob({\n ...context,\n jobId,\n wait: dependencies.pollWait,\n onUpdate: parsed.options.json === true\n ? undefined\n : (value) => printHostedJob(context.stdout, value, context.platform, context.appId),\n })\n : await getHostedSecurityJob({ ...context, jobId });\n if (parsed.options.json === true) context.stdout.log(JSON.stringify(job, null, 2));\n else if (parsed.options.follow !== true) {\n printHostedJob(context.stdout, job, context.platform, context.appId);\n }\n}\n","import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { claudeAdapter, CURSOR_RULE, PROJECT_INSTRUCTIONS } from \"./skill-adapters\";\n\n/** Agent harnesses with a first-class local adapter. */\nexport const AGENT_HARNESSES = [\"claude\", \"codex\", \"cursor\", \"copilot\", \"gemini\", \"agents\"] as const;\n\n/** A supported coding-agent harness. `agents` is the portable `AGENTS.md` adapter. */\nexport type AgentHarness = (typeof AGENT_HARNESSES)[number];\n\n/** A harness name accepted by setup; `all` expands to every project-local adapter. */\nexport type AgentHarnessSelector = AgentHarness | \"all\";\n\n/** Controls project-local or global installation of the bundled agent runbooks. */\nexport interface SkillInstallOptions {\n /** Project directory receiving the shared runbooks and harness adapters. Defaults to cwd. */\n dir?: string;\n /** Install user-wide Claude and/or Codex skills instead of project adapters. */\n global?: boolean;\n /** Harnesses to install. The programmatic compatibility default is `claude`; the CLI passes `all`. */\n harnesses?: AgentHarnessSelector[];\n /** Overwrite locally modified odla-managed files or managed instruction sections. */\n force?: boolean;\n /** Test/embedding override for the home directory. */\n homeDir?: string;\n /** Test/embedding override for `$CODEX_HOME`. */\n codexHomeDir?: string;\n /** Test/embedding override for the bundled skills directory. */\n sourceDir?: string;\n stdout?: Pick<typeof console, \"log\" | \"error\">;\n}\n\n/** One harness adapter and the directories or files through which it discovers odla. */\nexport interface HarnessInstallResult {\n harness: AgentHarness;\n targets: string[];\n}\n\n/** Files written or left unchanged by an idempotent agent-runbook installation. */\nexport interface SkillInstallResult {\n /** Primary native skill directory, retained for compatibility with earlier callers. */\n targetDir: string;\n /** Files changed directly under `targetDir`, relative to that directory. */\n written: string[];\n /** Files already current directly under `targetDir`, relative to that directory. */\n unchanged: string[];\n /** Absolute paths of every changed shared-runbook or adapter file. */\n writtenPaths: string[];\n /** Absolute paths of every already-current shared-runbook or adapter file. */\n unchangedPaths: string[];\n harnesses: HarnessInstallResult[];\n}\n\ninterface PlannedFile {\n target: string;\n content: string;\n boundary: string;\n managedMerge?: boolean;\n}\n\n/**\n * Installs one shared offline runbook tree plus thin native adapters for the\n * selected coding-agent harnesses. Project installs use `.agents/skills/` as\n * the canonical bundle; Claude Code, Cursor, Copilot, Gemini, and generic\n * `AGENTS.md` adapters point to it. Global installs support the native Claude\n * and Codex skill roots only.\n *\n * Installation is idempotent and planned before any write: an odla-managed\n * file changed by the user aborts the whole operation unless `force` is set.\n * Existing `AGENTS.md`, `GEMINI.md`, and Copilot instructions are preserved;\n * only the bounded odla-managed section is appended or replaced.\n */\nexport function installSkill(options: SkillInstallOptions = {}): SkillInstallResult {\n const out = options.stdout ?? console;\n const sourceDir = options.sourceDir ?? fileURLToPath(new URL(\"../skills\", import.meta.url));\n const files = listFiles(sourceDir);\n if (files.length === 0) throw new Error(`no bundled skills found at ${sourceDir}`);\n\n const harnesses = normalizeHarnesses(options.harnesses, options.global === true);\n const root = resolve(options.dir ?? process.cwd());\n const home = resolve(options.homeDir ?? homedir());\n const plans = new Map<string, PlannedFile>();\n const targets = new Map<AgentHarness, Set<string>>();\n\n const rememberTarget = (harness: AgentHarness, target: string): void => {\n const current = targets.get(harness) ?? new Set<string>();\n current.add(target);\n targets.set(harness, current);\n };\n const plan = (target: string, content: string, managedMerge = false, boundary = root): void => {\n const existing = plans.get(target);\n if (existing && existing.content !== content) throw new Error(`internal agent setup conflict for ${target}`);\n plans.set(target, { target, content, boundary, managedMerge });\n };\n const planSkillTree = (targetDir: string, boundary = root): void => {\n for (const rel of files) plan(join(targetDir, rel), readFileSync(join(sourceDir, rel), \"utf8\"), false, boundary);\n };\n\n let targetDir: string;\n if (options.global) {\n const claudeRoot = join(home, \".claude\", \"skills\");\n const codexRoot = resolve(options.codexHomeDir ?? process.env.CODEX_HOME ?? join(home, \".codex\"), \"skills\");\n targetDir = harnesses[0] === \"codex\" ? codexRoot : claudeRoot;\n for (const harness of harnesses) {\n const skillRoot = harness === \"claude\" ? claudeRoot : codexRoot;\n planSkillTree(skillRoot, harness === \"claude\" ? home : dirname(dirname(codexRoot)));\n rememberTarget(harness, skillRoot);\n }\n } else {\n const sharedRoot = join(root, \".agents\", \"skills\");\n planSkillTree(sharedRoot);\n\n const claudeRoot = join(root, \".claude\", \"skills\");\n targetDir = harnesses.includes(\"claude\") ? claudeRoot : sharedRoot;\n for (const harness of harnesses) rememberTarget(harness, sharedRoot);\n\n if (harnesses.includes(\"claude\")) {\n for (const skill of skillNames(files)) {\n const canonical = readFileSync(join(sourceDir, skill, \"SKILL.md\"), \"utf8\");\n plan(join(claudeRoot, skill, \"SKILL.md\"), claudeAdapter(skill, canonical));\n }\n rememberTarget(\"claude\", claudeRoot);\n }\n if (harnesses.includes(\"cursor\")) {\n const cursorRule = join(root, \".cursor\", \"rules\", \"odla.mdc\");\n plan(cursorRule, CURSOR_RULE);\n rememberTarget(\"cursor\", cursorRule);\n }\n if (harnesses.includes(\"agents\")) {\n const agentsFile = join(root, \"AGENTS.md\");\n plan(agentsFile, managedFileContent(agentsFile, PROJECT_INSTRUCTIONS, options.force === true, root), true);\n rememberTarget(\"agents\", agentsFile);\n }\n if (harnesses.includes(\"copilot\")) {\n const copilotFile = join(root, \".github\", \"copilot-instructions.md\");\n plan(copilotFile, managedFileContent(copilotFile, PROJECT_INSTRUCTIONS, options.force === true, root), true);\n rememberTarget(\"copilot\", copilotFile);\n }\n if (harnesses.includes(\"gemini\")) {\n const geminiFile = join(root, \"GEMINI.md\");\n plan(geminiFile, managedFileContent(geminiFile, PROJECT_INSTRUCTIONS, options.force === true, root), true);\n rememberTarget(\"gemini\", geminiFile);\n }\n }\n\n const writtenPaths = new Set<string>();\n const unchangedPaths = new Set<string>();\n const conflicts: string[] = [];\n for (const file of plans.values()) {\n const symlink = symlinkedComponent(file.boundary, file.target);\n if (symlink) {\n conflicts.push(`${file.target} (redirected by symbolic link ${symlink})`);\n continue;\n }\n if (!existsSync(file.target)) {\n writtenPaths.add(file.target);\n continue;\n }\n const current = readFileSync(file.target, \"utf8\");\n if (current === file.content) {\n unchangedPaths.add(file.target);\n } else if (file.managedMerge || options.force) {\n writtenPaths.add(file.target);\n unchangedPaths.delete(file.target);\n } else {\n conflicts.push(file.target);\n }\n }\n\n if (conflicts.length > 0) {\n throw new Error(\n `agent setup files modified locally (re-run with --force to replace only odla-managed content):\\n${conflicts.map((f) => ` - ${f}`).join(\"\\n\")}`,\n );\n }\n\n for (const file of plans.values()) {\n if (!existsSync(file.target) || readFileSync(file.target, \"utf8\") !== file.content) {\n mkdirSync(dirname(file.target), { recursive: true });\n writeFileSync(file.target, file.content);\n }\n }\n\n const skills = skillNames(files);\n const installations = harnesses.map((harness) => ({ harness, targets: [...(targets.get(harness) ?? [])] }));\n out.log(`agent harnesses: ${harnesses.join(\", \")}`);\n out.log(`offline skills: ${skills.join(\", \")}`);\n for (const installation of installations) out.log(`${installation.harness}: ${installation.targets.join(\", \")}`);\n out.log(`installed ${writtenPaths.size} managed file(s)${unchangedPaths.size ? ` (${unchangedPaths.size} unchanged)` : \"\"}`);\n return {\n targetDir,\n written: pathsUnder(targetDir, writtenPaths),\n unchanged: pathsUnder(targetDir, unchangedPaths),\n writtenPaths: [...writtenPaths].sort(),\n unchangedPaths: [...unchangedPaths].sort(),\n harnesses: installations,\n };\n}\n\nfunction pathsUnder(root: string, paths: Set<string>): string[] {\n return [...paths]\n .map((path) => relative(root, path))\n .filter((path) => path !== \"..\" && !path.startsWith(`..${sep}`) && !isAbsolute(path))\n .sort();\n}\n\nfunction normalizeHarnesses(values: AgentHarnessSelector[] | undefined, global: boolean): AgentHarness[] {\n const requested: string[] = values?.length ? values : [\"claude\"];\n const allowed = new Set<string>([...AGENT_HARNESSES, \"all\"]);\n for (const harness of requested) {\n if (!allowed.has(harness)) {\n throw new Error(`unknown agent harness \"${harness}\"; choose all, ${AGENT_HARNESSES.join(\", \")}`);\n }\n }\n const expanded: AgentHarness[] = requested.includes(\"all\")\n ? global ? [\"claude\", \"codex\"] : [...AGENT_HARNESSES]\n : [...new Set(requested)] as AgentHarness[];\n if (global) {\n const unsupported = expanded.filter((harness) => harness !== \"claude\" && harness !== \"codex\");\n if (unsupported.length) {\n throw new Error(`--global supports claude and codex only; ${unsupported.join(\", \")} require a project-local adapter`);\n }\n }\n return expanded;\n}\n\nfunction managedFileContent(path: string, block: string, force: boolean, boundary: string): string {\n const symlink = symlinkedComponent(boundary, path);\n if (symlink) throw new Error(`refusing to manage ${path}: symbolic link component ${symlink}`);\n if (!existsSync(path)) return `${block}\\n`;\n const current = readFileSync(path, \"utf8\");\n const start = \"<!-- odla-ai agent setup:start -->\";\n const end = \"<!-- odla-ai agent setup:end -->\";\n const startAt = current.indexOf(start);\n const endAt = current.indexOf(end);\n if ((startAt === -1) !== (endAt === -1) || (startAt !== -1 && endAt < startAt)) {\n throw new Error(`malformed odla-managed section in ${path}`);\n }\n if (startAt === -1) {\n const separator = current.length === 0 || current.endsWith(\"\\n\\n\") ? \"\" : current.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n return `${current}${separator}${block}\\n`;\n }\n const afterEnd = endAt + end.length;\n const existing = current.slice(startAt, afterEnd);\n if (existing !== block && !force) {\n throw new Error(`odla-managed section modified locally in ${path}; re-run with --force to replace that section`);\n }\n return `${current.slice(0, startAt)}${block}${current.slice(afterEnd)}`;\n}\n\nfunction symlinkedComponent(boundary: string, target: string): string | undefined {\n const rel = relative(boundary, target);\n if (rel === \"..\" || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {\n throw new Error(`agent setup target escapes its install root: ${target}`);\n }\n let current = boundary;\n for (const part of rel.split(sep).filter(Boolean)) {\n current = join(current, part);\n try {\n if (lstatSync(current).isSymbolicLink()) return current;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n }\n }\n return undefined;\n}\n\nfunction skillNames(files: string[]): string[] {\n return [...new Set(files.filter((file) => /(^|[\\\\/])SKILL\\.md$/.test(file)).map((file) => file.split(/[\\\\/]/)[0]!))].sort();\n}\n\nfunction listFiles(dir: string): string[] {\n if (!existsSync(dir)) return [];\n const results: string[] = [];\n const walk = (current: string): void => {\n for (const entry of readdirSync(current, { withFileTypes: true })) {\n const path = join(current, entry.name);\n if (entry.isDirectory()) walk(path);\n else results.push(relative(dir, path));\n }\n };\n walk(dir);\n return results.sort();\n}\n","/** Shared instruction block inserted into harness-native project files. */\nexport const PROJECT_INSTRUCTIONS = `<!-- odla-ai agent setup:start -->\n## odla agent workflow\n\nFor work that creates an odla app or adds odla services, read and follow\n\\`.agents/skills/odla/SKILL.md\\`. It dispatches an existing static site to\n\\`.agents/skills/odla-migrate/SKILL.md\\`. For production telemetry triage, use\n\\`.agents/skills/odla-o11y-debug/SKILL.md\\`.\n\nThe complete runbooks and their references are installed in this repository.\nDo not fetch online odla documentation as setup context. Network access is only\nneeded when a runbook deliberately calls the odla service, npm, Cloudflare, or\nanother configured provider.\n<!-- odla-ai agent setup:end -->`;\n\n/** Cursor's native rule wrapper around the shared project instructions. */\nexport const CURSOR_RULE = `---\ndescription: Build, migrate, provision, secure, or debug an odla app using the locally installed odla runbooks\nglobs:\nalwaysApply: false\n---\n\n${PROJECT_INSTRUCTIONS}\n`;\n\n/** Build a thin Claude skill that delegates to the canonical offline bundle. */\nexport function claudeAdapter(skill: string, canonical: string): string {\n const match = canonical.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---/);\n if (!match) throw new Error(`bundled skill ${skill} has no YAML frontmatter`);\n const lines = match[1]!.split(/\\r?\\n/);\n const frontmatter: string[] = [];\n let keepIndented = false;\n for (const line of lines) {\n if (line.startsWith(\"name:\") || line.startsWith(\"description:\")) {\n frontmatter.push(line);\n keepIndented = line.startsWith(\"description:\");\n } else if (keepIndented && /^\\s+/.test(line)) {\n frontmatter.push(line);\n } else {\n keepIndented = false;\n }\n }\n return `---\n${frontmatter.join(\"\\n\")}\n---\n\n# ${skill} (odla adapter)\n\nRead \\`../../../.agents/skills/${skill}/SKILL.md\\` completely and follow it. That\ncanonical local skill owns every reference path and contains the full offline\nrunbook. Do not substitute a remote documentation page for the installed copy.\n`;\n}\n","import { calendarServiceConfig, GOOGLE_CALENDAR_READ_SCOPE, loadProjectConfig, resolveDataExport, serializedEntities } from \"./config\";\nimport { readCalendarStatus } from \"./calendar-http\";\nimport { displayPath, readCredentials } from \"./local\";\nimport { getDeveloperToken } from \"./token\";\nimport type { SmokeOptions } from \"./types\";\n\ntype FetchLike = typeof fetch;\n\n/**\n * Verify a live, already-provisioned environment end-to-end. Resolves the target\n * env (`options.env`, else `dev`, else the first declared env) and requires it to\n * be declared in the config. Reads the local credentials file and checks that it\n * belongs to this app and holds a `tenantId` + `dbKey` for the env — otherwise it\n * throws pointing the user at `odla-ai provision --write-dev-vars`.\n *\n * It then makes real network calls: fetches the registry public-config (and, when\n * `ai.provider` is configured, asserts the live provider matches), fetches the\n * live db schema with the db key and asserts every entity from the local schema\n * is present, and runs a `count` aggregate against the first entity to confirm\n * the db answers queries. Progress lines are printed and it ends with `ok`.\n * Read-only — it writes nothing and throws on the first mismatch or failed\n * request.\n *\n * @param options.configPath Path to the `odla.config.mjs`.\n * @param options.env Env to check (default `dev`, else the first declared env).\n * @param options.fetch Injectable `fetch` (for tests/embedding).\n * @param options.stdout Optional console-like sink (defaults to `console`).\n */\nexport async function smoke(options: SmokeOptions): Promise<void> {\n const out = options.stdout ?? console;\n const cfg = await loadProjectConfig(options.configPath);\n const env = options.env ?? (cfg.envs.includes(\"dev\") ? \"dev\" : (cfg.envs[0] ?? \"prod\"));\n if (!cfg.envs.includes(env)) throw new Error(`env \"${env}\" is not declared in ${displayPath(cfg.configPath, cfg.rootDir)}`);\n\n const credentials = readCredentials(cfg.local.credentialsFile);\n if (!credentials) {\n throw new Error(`local credentials missing: ${displayPath(cfg.local.credentialsFile, cfg.rootDir)}. Run \"odla-ai provision --write-dev-vars\".`);\n }\n if (credentials.appId !== cfg.app.id) {\n throw new Error(`local credentials are for app \"${credentials.appId}\", but config app is \"${cfg.app.id}\"`);\n }\n\n const entry = credentials.envs[env];\n if (!entry?.tenantId || !entry.dbKey) {\n throw new Error(`local credentials have no db key for env \"${env}\". Run \"odla-ai provision --write-dev-vars\".`);\n }\n\n const doFetch = options.fetch ?? fetch;\n out.log(`smoke: ${cfg.app.id}/${env}`);\n out.log(` tenant: ${entry.tenantId}`);\n\n const publicConfig = await getJson(doFetch, publicConfigUrl(cfg.platformUrl, cfg.app.id, env), undefined);\n out.log(` public-config: ok`);\n\n if (cfg.ai?.provider) {\n const provider = ((publicConfig as { ai?: { provider?: unknown } | null }).ai?.provider ?? null) as string | null;\n if (provider !== cfg.ai.provider) {\n throw new Error(`ai provider mismatch: expected \"${cfg.ai.provider}\", public-config has \"${provider ?? \"none\"}\"`);\n }\n out.log(` ai: ${provider}`);\n }\n\n if (cfg.services.includes(\"calendar\")) {\n const token = await getDeveloperToken(\n cfg,\n {\n configPath: cfg.configPath,\n token: options.token,\n email: options.email,\n open: options.open,\n openApprovalUrl: options.openApprovalUrl,\n },\n doFetch,\n out,\n );\n const status = await readCalendarStatus({ platform: cfg.platformUrl, appId: cfg.app.id, env, token, fetch: doFetch });\n assertCalendarHealthy(status, calendarServiceConfig(cfg, env));\n out.log(` calendar: ${status.status}, last sync ${new Date(status.lastSuccessfulSyncAt!).toISOString()}`);\n }\n\n const expectedSchema = await resolveDataExport<unknown>(cfg, cfg.db?.schema, [\"schema\", \"SCHEMA\"]);\n const expectedEntities = serializedEntities(expectedSchema);\n const liveSchemaPayload = await getJson(doFetch, `${cfg.dbEndpoint}/app/${encodeURIComponent(entry.tenantId)}/schema`, entry.dbKey);\n const liveSchema = (liveSchemaPayload as { schema?: unknown }).schema ?? liveSchemaPayload;\n const liveEntities = serializedEntities(liveSchema);\n if (expectedEntities.length) {\n const missing = expectedEntities.filter((entity) => !liveEntities.includes(entity));\n if (missing.length) throw new Error(`live schema is missing expected entities: ${missing.join(\", \")}`);\n }\n out.log(` schema: ${liveEntities.length} entities`);\n\n const aggregateEntity = expectedEntities[0] ?? liveEntities[0];\n if (aggregateEntity) {\n const aggregate = await postJson(doFetch, `${cfg.dbEndpoint}/app/${encodeURIComponent(entry.tenantId)}/aggregate`, entry.dbKey, {\n ns: aggregateEntity,\n aggregate: { count: true },\n });\n const count = (aggregate as { aggregate?: { count?: unknown } }).aggregate?.count;\n out.log(` aggregate: ${aggregateEntity}.count=${String(count ?? \"ok\")}`);\n } else {\n out.log(` aggregate: skipped (schema has no entities)`);\n }\n if (cfg.services.includes(\"calendar\")) {\n const bookings = await postJson(doFetch, `${cfg.dbEndpoint}/app/${encodeURIComponent(entry.tenantId)}/aggregate`, entry.dbKey, {\n ns: \"$bookings\",\n aggregate: { count: true },\n });\n const count = (bookings as { aggregate?: { count?: unknown } }).aggregate?.count;\n out.log(` bookings: ${String(count ?? \"ok\")}`);\n }\n out.log(\"ok\");\n}\n\nfunction assertCalendarHealthy(\n status: Awaited<ReturnType<typeof readCalendarStatus>>,\n expected: ReturnType<typeof calendarServiceConfig>,\n): void {\n if (!status.enabled || status.provider !== \"google\") throw new Error(\"calendar is not enabled with the Google provider\");\n if (status.status !== \"healthy\") {\n throw new Error(`calendar connection is ${status.status}${status.error?.message ? `: ${status.error.message}` : \"\"}`);\n }\n if (status.access !== \"read\") throw new Error(\"calendar connection is not read-only\");\n const hasReadScope = status.grantedScopes.some((scope) => scope === GOOGLE_CALENDAR_READ_SCOPE || scope === \"calendar.events.readonly\");\n if (!hasReadScope) throw new Error(\"calendar connection is missing calendar.events.readonly consent\");\n const missing = expected.calendars.filter((id) => !status.calendars.includes(id));\n if (missing.length) throw new Error(`calendar connection is missing configured calendars: ${missing.join(\", \")}`);\n if (status.lastSuccessfulSyncAt === undefined) throw new Error(\"calendar has never completed a sync\");\n if (Date.now() - status.lastSuccessfulSyncAt > 30 * 60_000) throw new Error(\"calendar sync is more than 30 minutes stale\");\n if (status.watchExpiresAt !== undefined && status.watchExpiresAt <= Date.now()) throw new Error(\"calendar watch channel is expired\");\n}\n\nasync function getJson(doFetch: FetchLike, url: string, bearer: string | undefined): Promise<unknown> {\n const res = await doFetch(url, {\n headers: bearer ? { authorization: `Bearer ${bearer}` } : undefined,\n });\n if (!res.ok) throw new Error(`${new URL(url).pathname} returned ${res.status}: ${await safeText(res)}`);\n return res.json();\n}\n\nasync function postJson(doFetch: FetchLike, url: string, bearer: string, body: unknown): Promise<unknown> {\n const res = await doFetch(url, {\n method: \"POST\",\n headers: { authorization: `Bearer ${bearer}`, \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n if (!res.ok) throw new Error(`${new URL(url).pathname} returned ${res.status}: ${await safeText(res)}`);\n return res.json();\n}\n\nfunction publicConfigUrl(platformUrl: string, appId: string, env: string): string {\n const url = new URL(`/registry/apps/${encodeURIComponent(appId)}/public-config`, platformUrl);\n url.searchParams.set(\"env\", env);\n return url.toString();\n}\n\nasync function safeText(res: Response): Promise<string> {\n try {\n return (await res.text()).slice(0, 500);\n } catch {\n return \"\";\n }\n}\n","import { adminCommand } from \"./admin-command\";\nimport {\n assertArgs,\n listOpt,\n parseArgv,\n requiredString,\n stringOpt,\n} from \"./argv\";\nimport { printCapabilities } from \"./capabilities\";\nimport { calendarCalendars, calendarConnect, calendarDisconnect, calendarResync, calendarStatus } from \"./calendar\";\nimport { doctor } from \"./doctor\";\nimport { cliVersion, printHelp } from \"./help\";\nimport { harnessList } from \"./harness-options\";\nimport { initProject } from \"./init\";\nimport { provision } from \"./provision\";\nimport { secretsPush } from \"./secrets\";\nimport { secretsSet, secretsSetClerkKey } from \"./secrets-set\";\nimport { securityCommand } from \"./security-command\";\nimport { installSkill } from \"./skill\";\nimport { smoke } from \"./smoke\";\nimport type { ProvisionOptions } from \"./types\";\n\n/** Injectable side-effect boundaries used to run and test the command dispatcher. */\nexport interface CliDependencies {\n fetch?: typeof fetch;\n openUrl?: (url: string) => Promise<void>;\n pollWait?: (milliseconds: number, signal?: AbortSignal) => Promise<void>;\n readGitOrigin?: (cwd: string) => Promise<string>;\n confirm?: (message: string) => Promise<boolean>;\n stdout?: Pick<typeof console, \"log\" | \"error\">;\n}\n\n/**\n * Parse CLI arguments and dispatch the matching odla command.\n *\n * The dispatcher covers project setup, platform AI administration, hosted and\n * local security, provisioning, smoke checks, skill installation, and secret\n * pushes. It rejects unknown commands, unsupported options, extra positionals,\n * missing values, and errors returned by the selected command.\n *\n * @param argv Argument vector without the node/script prefix.\n * @param dependencies Optional side-effect overrides for embedding and tests.\n */\nexport async function runCli(\n argv = process.argv.slice(2),\n dependencies: CliDependencies = {},\n): Promise<void> {\n const parsed = parseArgv(argv);\n const command = parsed.positionals[0] ?? \"help\";\n if (command === \"version\" || command === \"-v\" || parsed.options.version === true) {\n assertArgs(parsed, [\"version\"], 1);\n console.log(cliVersion());\n return;\n }\n if (command === \"help\" || command === \"--help\" || command === \"-h\") {\n assertArgs(parsed, [\"help\"], 1);\n printHelp();\n return;\n }\n if (command === \"init\") {\n assertArgs(parsed, [\n \"app-id\", \"name\", \"config\", \"env\", \"services\", \"ai-provider\", \"force\",\n ], 1);\n initProject({\n appId: requiredString(parsed.options[\"app-id\"], \"--app-id\"),\n name: requiredString(parsed.options.name, \"--name\"),\n configPath: stringOpt(parsed.options.config),\n envs: listOpt(parsed.options.env),\n services: listOpt(parsed.options.services),\n aiProvider: stringOpt(parsed.options[\"ai-provider\"]),\n force: parsed.options.force === true,\n });\n return;\n }\n if (command === \"doctor\") {\n assertArgs(parsed, [\"config\"], 1);\n await doctor({ configPath: stringOpt(parsed.options.config) ?? \"odla.config.mjs\" });\n return;\n }\n if (command === \"calendar\") {\n await calendarCommand(parsed, dependencies);\n return;\n }\n if (command === \"capabilities\") {\n assertArgs(parsed, [\"json\"], 1);\n printCapabilities(parsed.options.json === true);\n return;\n }\n if (command === \"admin\") {\n await adminCommand(parsed);\n return;\n }\n if (command === \"security\") {\n await securityCommand(parsed, dependencies);\n return;\n }\n if (command === \"provision\") {\n await provisionCommand(parsed, dependencies);\n return;\n }\n if (command === \"smoke\") {\n assertArgs(parsed, [\"config\", \"env\", \"token\", \"email\", \"open\"], 1);\n await smoke({\n configPath: stringOpt(parsed.options.config) ?? \"odla.config.mjs\",\n env: stringOpt(parsed.options.env),\n token: stringOpt(parsed.options.token),\n email: stringOpt(parsed.options.email),\n open: parsed.options.open === false ? false : parsed.options.open === true ? true : undefined,\n openApprovalUrl: dependencies.openUrl,\n fetch: dependencies.fetch,\n stdout: dependencies.stdout,\n });\n return;\n }\n if (command === \"setup\") {\n assertArgs(parsed, [\"dir\", \"global\", \"force\", \"agent\", \"harness\"], 1);\n installSkill({\n dir: stringOpt(parsed.options.dir),\n global: parsed.options.global === true,\n harnesses: harnessList(parsed),\n force: parsed.options.force === true,\n });\n console.log(\n \"\\nOffline runbooks installed. Open this repo in your coding agent and ask it to set up odla.\\n\" +\n \"Its native adapter finds the local `odla` skill, chooses build or migration, and drives the CLI.\",\n );\n return;\n }\n if (command === \"skill\") {\n const sub = parsed.positionals[1];\n if (sub !== \"install\") {\n throw new Error(`unknown skill subcommand \"${sub ?? \"\"}\". Try \"odla-ai skill install\".`);\n }\n assertArgs(parsed, [\"dir\", \"global\", \"force\", \"agent\", \"harness\"], 2);\n installSkill({\n dir: stringOpt(parsed.options.dir),\n global: parsed.options.global === true,\n harnesses: harnessList(parsed),\n force: parsed.options.force === true,\n });\n return;\n }\n if (command === \"secrets\") {\n const sub = parsed.positionals[1];\n if (sub === \"set\" || sub === \"set-clerk-key\") {\n assertArgs(parsed, [\"config\", \"env\", \"from-env\", \"stdin\", \"token\", \"email\", \"yes\"], sub === \"set\" ? 3 : 2);\n const options = {\n configPath: stringOpt(parsed.options.config) ?? \"odla.config.mjs\",\n name: parsed.positionals[2],\n env: requiredString(parsed.options.env, \"--env\"),\n fromEnv: stringOpt(parsed.options[\"from-env\"]),\n stdin: parsed.options.stdin === true,\n token: stringOpt(parsed.options.token),\n email: stringOpt(parsed.options.email),\n yes: parsed.options.yes === true,\n fetch: dependencies.fetch,\n stdout: dependencies.stdout,\n };\n await (sub === \"set\" ? secretsSet(options) : secretsSetClerkKey(options));\n return;\n }\n if (sub !== \"push\") {\n throw new Error(\n `unknown secrets subcommand \"${sub ?? \"\"}\". Try \"odla-ai secrets push --env dev\", ` +\n `\"odla-ai secrets set <name> --env dev --stdin\", or \"odla-ai secrets set-clerk-key --env dev --stdin\".`,\n );\n }\n assertArgs(parsed, [\"config\", \"env\", \"dry-run\", \"yes\"], 2);\n await secretsPush({\n configPath: stringOpt(parsed.options.config) ?? \"odla.config.mjs\",\n env: requiredString(parsed.options.env, \"--env\"),\n dryRun: parsed.options[\"dry-run\"] === true,\n yes: parsed.options.yes === true,\n });\n return;\n }\n throw new Error(`unknown command \"${command}\". Run \"odla-ai help\".`);\n}\n\nasync function provisionCommand(\n parsed: ReturnType<typeof parseArgv>,\n dependencies: CliDependencies,\n): Promise<void> {\n assertArgs(parsed, [\n \"config\", \"dry-run\", \"rotate-keys\", \"rotate-o11y-token\", \"push-secrets\",\n \"write-credentials\", \"write-dev-vars\", \"token\", \"email\", \"open\", \"yes\",\n ], 1);\n const writeDevVars = parsed.options[\"write-dev-vars\"];\n const options: ProvisionOptions = {\n configPath: stringOpt(parsed.options.config) ?? \"odla.config.mjs\",\n dryRun: parsed.options[\"dry-run\"] === true,\n rotateKeys: parsed.options[\"rotate-keys\"] === true,\n rotateO11yToken: parsed.options[\"rotate-o11y-token\"] === true,\n pushSecrets: parsed.options[\"push-secrets\"] === true,\n writeCredentials: parsed.options[\"write-credentials\"] !== false,\n writeDevVars: typeof writeDevVars === \"string\" ? writeDevVars : writeDevVars === true,\n token: stringOpt(parsed.options.token),\n email: stringOpt(parsed.options.email),\n open: parsed.options.open === false\n ? false\n : parsed.options.open === true ? true : undefined,\n yes: parsed.options.yes === true,\n fetch: dependencies.fetch,\n openApprovalUrl: dependencies.openUrl,\n stdout: dependencies.stdout,\n };\n await provision(options);\n}\n\nasync function calendarCommand(parsed: ReturnType<typeof parseArgv>, dependencies: CliDependencies): Promise<void> {\n const sub = parsed.positionals[1];\n if (sub !== \"status\" && sub !== \"calendars\" && sub !== \"connect\" && sub !== \"resync\" && sub !== \"disconnect\") {\n throw new Error(`unknown calendar subcommand \"${sub ?? \"\"}\". Try \"odla-ai calendar status --env dev\".`);\n }\n assertArgs(parsed, [\"config\", \"env\", \"json\", \"token\", \"email\", \"open\", \"yes\"], 2);\n if (sub !== \"status\" && sub !== \"calendars\" && parsed.options.json !== undefined) throw new Error(`--json is supported only by calendar status/calendars`);\n if ((sub === \"status\" || sub === \"calendars\") && parsed.options.yes !== undefined) throw new Error(`--yes is not used by \"calendar ${sub}\"`);\n const options = {\n configPath: stringOpt(parsed.options.config) ?? \"odla.config.mjs\",\n env: stringOpt(parsed.options.env),\n token: stringOpt(parsed.options.token),\n email: stringOpt(parsed.options.email),\n open: parsed.options.open === false ? false : parsed.options.open === true ? true : undefined,\n yes: parsed.options.yes === true,\n json: parsed.options.json === true,\n fetch: dependencies.fetch,\n stdout: dependencies.stdout,\n openConsentUrl: dependencies.openUrl,\n };\n if (sub === \"status\") await calendarStatus(options);\n else if (sub === \"calendars\") await calendarCalendars(options);\n else if (sub === \"connect\") await calendarConnect(options);\n else if (sub === \"resync\") await calendarResync(options);\n else await calendarDisconnect(options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKA,IAAM,mBAAmB,MACvB,OAAO,aAAa,cAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,OAC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,QAAQ,OAAW,OAAM,IAAI,MAAM,kCAAkC,GAAG,GAAG;AAC3I,QAAM,UAAU;AAAA,IACd,YAAY,UAAU,OAAO,QAAQ,MAAM,KAAK;AAAA,IAChD,KAAK,UAAU,OAAO,QAAQ,GAAG;AAAA,IACjC,OAAO,UAAU,OAAO,QAAQ,KAAK;AAAA,IACrC,OAAO,UAAU,OAAO,QAAQ,KAAK;AAAA,IACrC,MAAM,OAAO,QAAQ,SAAS,QAAQ,QAAQ,OAAO,QAAQ,SAAS,OAAO,OAAO;AAAA,IACpF,KAAK,OAAO,QAAQ,QAAQ;AAAA,IAC5B,MAAM,OAAO,QAAQ,SAAS;AAAA,IAC9B,OAAO,aAAa;AAAA,IACpB,QAAQ,aAAa;AAAA,IACrB,gBAAgB,aAAa;AAAA,EAC/B;AACA,MAAI,QAAQ,SAAU,OAAM,eAAe,OAAO;AAAA,WACzC,QAAQ,YAAa,OAAM,kBAAkB,OAAO;AAAA,WACpD,QAAQ,UAAW,OAAM,gBAAgB,OAAO;AAAA,WAChD,QAAQ,SAAU,OAAM,eAAe,OAAO;AAAA,MAClD,OAAM,mBAAmB,OAAO;AACvC;","names":["import_node_process","import_node_process","process","resolve","process","import_node_process","process","import_node_fs","import_node_process","import_db","process","responseBody","apiError","isRecord","timestamp","process","res","body","responseBody","apiError","isRecord","policy","response","import_node_fs","import_node_path","isRecord","timestamp","resolve","import_node_child_process","import_node_fs","import_node_path","import_node_child_process","import_node_fs","import_node_path","import_node_fs","import_node_fs","import_node_path","import_apps","import_node_process","safeText","process","safeText","publishableKey","import_ai","import_apps","PROD_ENV_NAMES","import_security","import_node_path","import_node_child_process","resolve","context","import_node_fs","import_node_path","import_node_url","targetDir","postJson","safeText","writeDevVars"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../../../node_modules/tsup/assets/cjs_shims.js","../src/admin-ai.ts","../src/token.ts","../src/handshake-state.ts","../src/local.ts","../src/open.ts","../src/secret-input.ts","../src/admin-ai-auth.ts","../src/admin-ai-audit.ts","../src/admin-ai-policy.ts","../src/admin-ai-usage.ts","../src/argv.ts","../src/admin-command.ts","../src/app-export.ts","../src/config.ts","../src/app-lifecycle.ts","../src/capabilities.ts","../src/calendar-errors.ts","../src/redact.ts","../src/calendar-http.ts","../src/calendar-poll.ts","../src/calendar.ts","../src/doctor-checks.ts","../src/wrangler.ts","../src/doctor.ts","../src/help.ts","../src/harness-options.ts","../src/init.ts","../src/provision.ts","../src/provision-credentials.ts","../src/secrets.ts","../src/secrets-set.ts","../src/security-command-context.ts","../src/security-command-output.ts","../src/security-run-command.ts","../src/security.ts","../src/security-hosted-github.ts","../src/security-hosted-request.ts","../src/security-hosted-intent.ts","../src/security-hosted-jobs.ts","../src/security-command.ts","../src/skill.ts","../src/skill-adapters.ts","../src/smoke.ts","../src/cli.ts"],"sourcesContent":["export { exitCodeFor, runCli } from \"./cli\";\nexport type { CliDependencies } from \"./cli\";\nexport { adminAi, getScopedPlatformToken, SYSTEM_AI_PURPOSES } from \"./admin-ai\";\nexport type { AdminAiOptions, ScopedPlatformTokenOptions, SystemAiPurpose } from \"./admin-ai\";\nexport { CAPABILITIES, printCapabilities } from \"./capabilities\";\nexport { calendarCalendars, calendarConnect, calendarDisconnect, calendarStatus } from \"./calendar\";\nexport type { CalendarLifecycleOptions } from \"./calendar\";\nexport { GOOGLE_CALENDAR_EVENTS_SCOPE, calendarBookingPageUrl, calendarServiceConfig } from \"./config\";\nexport type { AvailableGoogleCalendar, CalendarConnectionState, CalendarStatus } from \"./calendar-http\";\nexport { doctor } from \"./doctor\";\nexport { initProject } from \"./init\";\nexport { provision } from \"./provision\";\nexport { redactSecrets } from \"./redact\";\nexport { secretsPush } from \"./secrets\";\nexport type { SecretsPushOptions } from \"./secrets\";\nexport { secretsSet, secretsSetClerkKey } from \"./secrets-set\";\nexport type { SecretsSetOptions } from \"./secrets-set\";\nexport { runHostedSecurity } from \"./security\";\nexport type { HostedSecurityProfile, HostedSecurityResult, HostedSecurityTokenRequest, RunHostedSecurityOptions } from \"./security\";\nexport {\n connectGitHubSecuritySource,\n disconnectGitHubSecuritySource,\n followHostedSecurityJob,\n getHostedSecurityJob,\n getHostedSecurityIntent,\n getHostedSecurityPlan,\n getHostedSecurityReport,\n inferGitHubRepository,\n isTerminalHostedSecurityStatus,\n listGitHubSecuritySources,\n listHostedSecurityJobs,\n repositoryFromGitRemote,\n startHostedSecurityJob,\n} from \"./security-hosted\";\nexport type {\n ConnectGitHubSecuritySourceOptions,\n DisconnectGitHubSecuritySourceOptions,\n FollowHostedSecurityJobOptions,\n GetHostedSecurityJobOptions,\n GetHostedSecurityIntentOptions,\n GitHubConnectionAttempt,\n GitHubConnectionStatus,\n GitHubSecuritySource,\n HostedSecurityCounts,\n HostedSecurityCoverage,\n HostedSecurityJob,\n HostedSecurityJobStatus,\n HostedSecurityIntent,\n HostedSecurityIntentResponse,\n HostedSecurityPlan,\n HostedSecurityPlanRoute,\n HostedSecurityReport,\n HostedSecurityReportFinding,\n HostedSecurityRoute,\n ListGitHubSecuritySourcesOptions,\n ListHostedSecurityJobsOptions,\n StartHostedSecurityJobOptions,\n} from \"./security-hosted\";\nexport { AGENT_HARNESSES, installSkill } from \"./skill\";\nexport type { AgentHarness, AgentHarnessSelector, HarnessInstallResult, SkillInstallOptions, SkillInstallResult } from \"./skill\";\nexport { smoke } from \"./smoke\";\nexport type {\n CalendarConfig,\n CalendarServiceConfig,\n GoogleCalendarConfig,\n OdlaProjectConfig,\n LoadedProjectConfig,\n LocalCredentials,\n ProvisionOptions,\n ProvisionPlan,\n SmokeOptions,\n} from \"./types\";\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","import process from \"node:process\";\nimport { platformAudience } from \"./token\";\nimport { secretInputValue } from \"./secret-input\";\nimport { resolveAdminPlatformToken, type ScopedPlatformScope } from \"./admin-ai-auth\";\nimport { adminAiAuditQuery, readAdminAiAudit } from \"./admin-ai-audit\";\nimport { requireSystemAiPurpose } from \"./admin-ai-policy\";\nimport { adminAiUsageQuery, readAdminAiUsage } from \"./admin-ai-usage\";\nexport { getScopedPlatformToken } from \"./admin-ai-auth\";\nexport type { ScopedPlatformTokenOptions } from \"./admin-ai-auth\";\nexport { SYSTEM_AI_PURPOSES } from \"./admin-ai-policy\";\nexport type { SystemAiPurpose } from \"./admin-ai-policy\";\n\n/** Inputs for one System AI policy/catalog read, policy update,\n * credential-status read, write-only credential transfer, or metadata-only\n * usage or admin-audit read. Provider values may come only from a named environment variable\n * or stdin. */\nexport interface AdminAiOptions {\n action: \"show\" | \"models\" | \"set\" | \"credentials\" | \"credential-set\" | \"usage\" | \"audit\";\n purpose?: string;\n provider?: string;\n model?: string;\n enabled?: boolean;\n maxInputBytes?: number;\n maxOutputTokens?: number;\n maxCallsPerRun?: number;\n platform?: string;\n token?: string;\n /** Existing odla account email used only when a fresh handshake is required. */\n email?: string;\n json?: boolean;\n open?: boolean;\n fetch?: typeof fetch;\n stdout?: Pick<typeof console, \"log\">;\n openApprovalUrl?: (url: string) => Promise<void>;\n credentialProvider?: string;\n fromEnv?: string;\n stdin?: boolean;\n readStdin?: () => Promise<string>;\n discoveryProvider?: string;\n discoveryModel?: string;\n validationProvider?: string;\n validationModel?: string;\n /** Optional metadata-only usage filters. */\n appId?: string;\n env?: string;\n runId?: string;\n limit?: number;\n /** Separate short-lived admin-token cache; never reuses the app developer-token file. */\n tokenFile?: string;\n}\n\n/** Read or update platform-funded AI routing and inspect attributed usage.\n * Authentication is a short-lived,\n * explicitly scoped device grant; ordinary app developer tokens never become\n * platform admins. Credential writes accept values only from a named env var\n * or stdin, transfer them once, and never place them in argv, output, or the\n * scoped-token cache. */\nexport async function adminAi(options: AdminAiOptions): Promise<void> {\n const platform = platformAudience(options.platform ?? process.env.ODLA_PLATFORM ?? \"https://odla.ai\");\n const doFetch = options.fetch ?? fetch;\n const out = options.stdout ?? console;\n const usageQuery = options.action === \"usage\" ? adminAiUsageQuery(options) : undefined;\n const auditQuery = options.action === \"audit\" ? adminAiAuditQuery(options) : undefined;\n const scope: ScopedPlatformScope = options.action === \"set\"\n ? \"platform:ai:policy:write\"\n : options.action === \"credential-set\"\n ? \"platform:ai:credential:write\"\n : options.action === \"credentials\"\n ? \"platform:ai:credential:read\"\n : options.action === \"usage\"\n ? \"platform:ai:usage:read\"\n : options.action === \"audit\"\n ? \"platform:ai:audit:read\"\n : \"platform:ai:policy:read\";\n const token = await resolveAdminPlatformToken({\n platform,\n scope,\n token: options.token,\n email: options.email,\n open: options.open,\n fetch: doFetch,\n stdout: out,\n openApprovalUrl: options.openApprovalUrl,\n tokenFile: options.tokenFile,\n });\n const headers = { authorization: `Bearer ${token}`, \"content-type\": \"application/json\" };\n\n if (options.action === \"usage\") {\n await readAdminAiUsage({ platform, query: usageQuery ?? \"\", headers, json: options.json, fetch: doFetch, stdout: out });\n return;\n }\n\n if (options.action === \"audit\") {\n await readAdminAiAudit({ platform, query: auditQuery ?? \"\", headers, json: options.json, fetch: doFetch, stdout: out });\n return;\n }\n\n if (options.action === \"credentials\") {\n const res = await doFetch(`${platform}/registry/platform/ai-credentials`, { headers });\n const body = await responseBody(res);\n if (!res.ok) throw new Error(apiError(\"read platform AI credential status\", res.status, body));\n const credentials = isRecord(body) && isRecord(body.credentials) ? body.credentials : body;\n if (options.json) out.log(JSON.stringify({ credentials }, null, 2));\n else for (const [provider, status] of Object.entries(isRecord(credentials) ? credentials : {})) {\n const label = isRecord(status) && status.set === true\n ? status.readable === true ? \"vault readable\" : \"stored; vault unreadable\"\n : \"not set\";\n out.log(`${provider}\\t${label}`);\n }\n return;\n }\n\n if (options.action === \"credential-set\") {\n const provider = requireProvider(options.credentialProvider);\n const value = await secretInputValue(options);\n const res = await doFetch(`${platform}/registry/platform/ai-credentials/${encodeURIComponent(provider)}`, {\n method: \"PUT\",\n headers,\n body: JSON.stringify({ value }),\n });\n const body = await responseBody(res);\n if (!res.ok) throw new Error(apiError(`store ${provider} platform credential`, res.status, body));\n out.log(`stored ${provider} platform credential (write-only; value was not returned)`);\n return;\n }\n\n if (options.action === \"show\" || options.action === \"models\") {\n const res = await doFetch(`${platform}/registry/platform/ai-policies`, { headers });\n const body = await responseBody(res);\n if (!res.ok) throw new Error(apiError(\"read platform AI policies\", res.status, body));\n if (options.action === \"models\") {\n const models = catalogModels(body).filter((model) => !options.provider || model.provider === options.provider);\n if (!models.length) throw new Error(options.provider ? `no System AI models found for provider ${options.provider}` : \"platform returned no System AI models\");\n if (options.json) out.log(JSON.stringify({ models }, null, 2));\n else for (const model of models) out.log(`${model.provider}\\t${model.id}`);\n return;\n }\n const policies = policyArray(body);\n if (options.json) {\n out.log(JSON.stringify({ policies, models: catalogModels(body) }, null, 2));\n return;\n }\n out.log(\"purpose\\tenabled\\tprovider\\tmodel\\tmax calls\\tmax input bytes\\tmax output tokens\");\n for (const policy of policies) {\n out.log([\n policy.purpose,\n String(policy.enabled),\n policy.provider,\n policy.model,\n String(policy.maxCallsPerRun ?? \"\"),\n String(policy.maxInputBytes ?? \"\"),\n String(policy.maxOutputTokens ?? \"\"),\n ].join(\"\\t\"));\n }\n return;\n }\n\n if (options.purpose === \"security\") {\n const currentResponse = await doFetch(`${platform}/registry/platform/ai-policies`, { headers });\n const currentBody = await responseBody(currentResponse);\n if (!currentResponse.ok) throw new Error(apiError(\"read current security AI policies\", currentResponse.status, currentBody));\n const policies = policyArray(currentBody);\n const discovery = policies.find((policy) => policy.purpose === \"security.discovery\");\n const validation = policies.find((policy) => policy.purpose === \"security.validation\");\n if (!discovery || !validation || !Number.isSafeInteger(discovery.version) || !Number.isSafeInteger(validation.version)) {\n throw new Error(\"platform returned invalid security AI policy revisions\");\n }\n const shared = {\n ...(options.enabled === undefined ? {} : { enabled: options.enabled }),\n ...(options.maxInputBytes === undefined ? {} : { maxInputBytes: options.maxInputBytes }),\n ...(options.maxOutputTokens === undefined ? {} : { maxOutputTokens: options.maxOutputTokens }),\n ...(options.maxCallsPerRun === undefined ? {} : { maxCallsPerRun: options.maxCallsPerRun }),\n };\n const discoveryUpdate = {\n ...shared,\n ...(options.discoveryProvider?.trim() ? { provider: options.discoveryProvider.trim() } : {}),\n ...(options.discoveryModel?.trim() ? { model: options.discoveryModel.trim() } : {}),\n };\n const validationUpdate = {\n ...shared,\n ...(options.validationProvider?.trim() ? { provider: options.validationProvider.trim() } : {}),\n ...(options.validationModel?.trim() ? { model: options.validationModel.trim() } : {}),\n };\n if (!Object.keys(discoveryUpdate).length && !Object.keys(validationUpdate).length) {\n throw new Error(\"security set requires a route, enabled state, or budget change\");\n }\n const res = await doFetch(`${platform}/registry/platform/ai-policies/security`, {\n method: \"PUT\",\n headers,\n body: JSON.stringify({\n expectedVersions: { discovery: discovery.version, validation: validation.version },\n discovery: discoveryUpdate,\n validation: validationUpdate,\n }),\n });\n const response = await responseBody(res);\n if (!res.ok) throw new Error(apiError(\"update security review routes\", res.status, response));\n out.log(options.json ? JSON.stringify(response, null, 2) : \"updated security review discovery and independent validation routes atomically\");\n return;\n }\n\n const purpose = requireSystemAiPurpose(options.purpose);\n const body = {\n ...(options.provider?.trim() ? { provider: options.provider.trim() } : {}),\n ...(options.model?.trim() ? { model: options.model.trim() } : {}),\n ...(options.enabled === undefined ? {} : { enabled: options.enabled }),\n ...(options.maxInputBytes === undefined ? {} : { maxInputBytes: options.maxInputBytes }),\n ...(options.maxOutputTokens === undefined ? {} : { maxOutputTokens: options.maxOutputTokens }),\n ...(options.maxCallsPerRun === undefined ? {} : { maxCallsPerRun: options.maxCallsPerRun }),\n };\n if (!Object.keys(body).length) throw new Error(\"set requires a provider, model, enabled state, or budget change\");\n const res = await doFetch(`${platform}/registry/platform/ai-policies/${encodeURIComponent(purpose)}`, {\n method: \"PUT\",\n headers,\n body: JSON.stringify(body),\n });\n const response = await responseBody(res);\n if (!res.ok) throw new Error(apiError(`update ${purpose}`, res.status, response));\n const policy: Record<string, unknown> = isRecord(response) && isRecord(response.policy)\n ? response.policy\n : isRecord(response) ? response : {};\n out.log(options.json ? JSON.stringify({ policy }, null, 2) : `updated ${purpose}: ${String(policy.provider ?? \"unchanged\")}/${String(policy.model ?? \"unchanged\")}`);\n}\n\nfunction requireProvider(value: string | undefined): \"anthropic\" | \"openai\" | \"google\" {\n if (value !== \"anthropic\" && value !== \"openai\" && value !== \"google\") {\n throw new Error(\"provider must be one of: anthropic, openai, google\");\n }\n return value;\n}\n\nfunction policyArray(body: unknown): Array<Record<string, unknown>> {\n if (isRecord(body) && Array.isArray(body.policies)) return body.policies.filter(isRecord);\n if (isRecord(body) && isRecord(body.policies)) return Object.values(body.policies).filter(isRecord);\n throw new Error(\"platform returned an invalid AI policy response\");\n}\n\nfunction catalogModels(body: unknown): Array<{ id: string; provider: string }> {\n if (!isRecord(body) || !isRecord(body.catalog) || !Array.isArray(body.catalog.models)) {\n throw new Error(\"platform returned an invalid System AI model catalog\");\n }\n return body.catalog.models.filter((value): value is { id: string; provider: string } =>\n isRecord(value) && typeof value.id === \"string\" && typeof value.provider === \"string\");\n}\n\nasync function responseBody(res: Response): Promise<unknown> {\n const text = await res.text();\n if (!text) return {};\n try { return JSON.parse(text) as unknown; } catch { return { message: text.slice(0, 300) }; }\n}\n\nfunction apiError(action: string, status: number, body: unknown): string {\n const error = isRecord(body) && isRecord(body.error) ? body.error : undefined;\n const message = error && typeof error.message === \"string\" ? error.message : isRecord(body) && typeof body.message === \"string\" ? body.message : \"request failed\";\n return `${action} failed (${status}): ${message}`;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n","import { collectToken, OdlaError, requestToken } from \"@odla-ai/db\";\nimport type { DeviceToken } from \"@odla-ai/db\";\nimport process from \"node:process\";\nimport type { LoadedProjectConfig, ProvisionOptions } from \"./types\";\nimport {\n approvalHint,\n approvalReminder,\n clearPendingHandshake,\n handshakeFile,\n handshakeWaitMs,\n readPendingHandshake,\n writePendingHandshake,\n type PendingHandshake,\n} from \"./handshake-state\";\nimport { openUrl } from \"./open\";\nimport { displayPath, readJsonFile, writePrivateJson } from \"./local\";\n\ntype FetchLike = typeof fetch;\n\n/** Resolve the explicit, audience-bound environment, cached, or freshly\n * human-approved developer credential for a project operation. A new\n * handshake requires `options.email` or `ODLA_USER_EMAIL`; neither is used\n * when a still-valid token is supplied or cached. */\nexport async function getDeveloperToken(\n cfg: LoadedProjectConfig,\n options: ProvisionOptions,\n doFetch: FetchLike,\n out: Pick<typeof console, \"log\" | \"error\">,\n): Promise<string> {\n if (options.token) return options.token;\n const audience = platformAudience(cfg.platformUrl);\n if (process.env.ODLA_DEV_TOKEN) {\n const declared = process.env.ODLA_DEV_TOKEN_AUDIENCE;\n if (declared) {\n if (platformAudience(declared) !== audience) throw new Error(\"ODLA_DEV_TOKEN_AUDIENCE does not match the configured platform\");\n } else if (audience !== \"https://odla.ai\") {\n throw new Error(\"ODLA_DEV_TOKEN_AUDIENCE is required for a non-default platform\");\n }\n return process.env.ODLA_DEV_TOKEN;\n }\n\n const cached = readJsonFile<{ token?: string; expiresAt?: number; platform?: string; email?: string }>(cfg.local.tokenFile);\n if (cached?.token && cached.platform === audience && (cached.expiresAt ?? 0) > Date.now() + 60_000) {\n out.log(`auth: using cached developer token (${displayPath(cfg.local.tokenFile, cfg.rootDir)})`);\n return cached.token;\n }\n\n const ctx: HandshakeContext = {\n cfg,\n options,\n doFetch,\n out,\n audience,\n browser: approvalBrowser(options),\n email: handshakeEmail(options.email, cached?.platform === audience ? cached.email : undefined),\n pendingFile: handshakeFile(cfg),\n };\n const waitMs = handshakeWaitMs(options.wait);\n const { token, expiresAt } = (await resumePendingHandshake(ctx, waitMs)) ?? (await freshHandshake(ctx, waitMs));\n clearPendingHandshake(ctx.pendingFile);\n writePrivateJson(cfg.local.tokenFile, { platform: audience, email: ctx.email, token, expiresAt });\n out.log(`auth: developer token cached (${displayPath(cfg.local.tokenFile, cfg.rootDir)})`);\n return token;\n}\n\ninterface HandshakeContext {\n cfg: LoadedProjectConfig;\n options: ProvisionOptions;\n doFetch: FetchLike;\n out: Pick<typeof console, \"log\" | \"error\">;\n audience: string;\n browser: ReturnType<typeof approvalBrowser>;\n email: string;\n pendingFile: string;\n}\n\n/** Collect a persisted still-claimable handshake instead of minting a new\n * code; returns null when there is none (or it lapsed) so a fresh one starts. */\nasync function resumePendingHandshake(ctx: HandshakeContext, waitMs: number | undefined): Promise<DeviceToken | null> {\n const pending = readPendingHandshake(ctx.pendingFile, ctx.audience, ctx.email);\n if (!pending) return null;\n ctx.out.log(\"\");\n ctx.out.log(`auth: resuming pending handshake — ${approvalHint(pending)}`);\n await launchApproval(ctx, pending.approvalUrl);\n ctx.out.log(\"\");\n const stopReminder = approvalReminder(ctx.out, pending);\n try {\n return await collectToken({\n endpoint: ctx.cfg.platformUrl,\n deviceCode: pending.deviceCode,\n expiresAt: pending.expiresAt,\n interval: pending.interval,\n waitMs,\n fetch: ctx.doFetch,\n });\n } catch (err) {\n const code = err instanceof OdlaError ? err.code : undefined;\n if (code === \"handshake_pending\") throw stillPending(pending, ctx.email);\n if (code === \"handshake_expired\" || code === \"handshake_timeout\") {\n clearPendingHandshake(ctx.pendingFile);\n ctx.out.log(\"auth: pending handshake lapsed unapproved; starting a fresh one\");\n return null;\n }\n if (code === \"handshake_denied\") clearPendingHandshake(ctx.pendingFile);\n throw err;\n } finally {\n stopReminder();\n }\n}\n\nasync function freshHandshake(ctx: HandshakeContext, waitMs: number | undefined): Promise<DeviceToken> {\n let started: PendingHandshake | undefined;\n let stopReminder: (() => void) | undefined;\n try {\n return await requestToken({\n endpoint: ctx.cfg.platformUrl,\n email: ctx.email,\n label: `${ctx.cfg.app.id} provisioner`,\n fetch: ctx.doFetch,\n waitMs,\n onCode: async ({ userCode, deviceCode, expiresIn, interval, verificationUriComplete }) => {\n const approvalUrl = verificationUriComplete ?? handshakeUrl(ctx.cfg.platformUrl, userCode);\n started = {\n platform: ctx.audience,\n email: ctx.email,\n userCode,\n deviceCode,\n approvalUrl,\n interval,\n expiresAt: Date.now() + expiresIn * 1000,\n };\n writePendingHandshake(ctx.pendingFile, started);\n ctx.out.log(\"\");\n ctx.out.log(`Review, then ${approvalHint(started)}.`);\n await launchApproval(ctx, approvalUrl);\n ctx.out.log(\"\");\n stopReminder = approvalReminder(ctx.out, started);\n },\n });\n } catch (err) {\n const code = err instanceof OdlaError ? err.code : undefined;\n if (code === \"handshake_pending\" && started) throw stillPending(started, ctx.email);\n if (code === \"handshake_denied\" || code === \"handshake_expired\" || code === \"handshake_timeout\") {\n clearPendingHandshake(ctx.pendingFile);\n }\n throw err;\n } finally {\n stopReminder?.();\n }\n}\n\n/** Launching a browser is best-effort and unverifiable: a sandboxed shell can\n * accept the spawn yet show nothing, so the printed URL stays the source of\n * truth and every outcome message points back at it. */\nasync function launchApproval(ctx: HandshakeContext, approvalUrl: string): Promise<void> {\n if (ctx.browser.open) {\n try {\n await (ctx.options.openApprovalUrl ?? openUrl)(approvalUrl);\n ctx.out.log(`auth: asked the OS to open a browser${ctx.browser.mode === \"auto\" ? \" (auto)\" : \"\"} — if no tab appeared, use the URL above`);\n } catch (err) {\n ctx.out.log(`auth: could not open browser (${err instanceof Error ? err.message : String(err)})`);\n }\n } else if (ctx.browser.reason) {\n ctx.out.log(`auth: browser launch skipped (${ctx.browser.reason}) — show the human the URL above`);\n }\n}\n\n/** The wait cap elapsed with the handshake still approvable. The pending file\n * survives, so rerunning the same command resumes and collects. */\nfunction stillPending(pending: PendingHandshake, email: string): OdlaError {\n return new OdlaError(\n \"handshake_pending\",\n `handshake still pending — ask ${email} to ${approvalHint(pending)}, then re-run this command; it resumes the same handshake and collects the token`,\n { retryable: true },\n );\n}\n\n/** Resolve the non-secret account identifier for a fresh handshake: explicit\n * `--email`, then `ODLA_USER_EMAIL`, then the same-audience private cache.\n * Existing tokens bypass this entirely. Agents must never request a password\n * or Clerk token. */\nexport function handshakeEmail(value?: string, cached?: string): string {\n const email = (value ?? process.env.ODLA_USER_EMAIL ?? cached ?? \"\").trim().toLowerCase();\n if (email.length > 254 || !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email)) {\n throw new Error(\"a fresh odla handshake requires --email <account> or ODLA_USER_EMAIL\");\n }\n return email;\n}\n\n/** Host facts consulted when deciding whether a browser can be shown. */\nexport interface BrowserHost {\n platform?: NodeJS.Platform;\n env?: Record<string, string | undefined>;\n}\n\n/** Decide whether to open the signed-in Studio review URL. The gate asks\n * whether this machine can show the user's signed-in browser — not whether\n * stdin is a TTY — so scripted and agent-driven runs still pop the approval\n * page for the human at the keyboard. Launch is skipped only in CI, over SSH,\n * or on a display-less host; `--open` and `--no-open` always win. */\nexport function approvalBrowser(\n options: Pick<ProvisionOptions, \"open\">,\n host: BrowserHost = {},\n): { open: boolean; mode?: \"auto\" | \"forced\"; reason?: string } {\n if (options.open === true) return { open: true, mode: \"forced\" };\n if (options.open === false) return { open: false, reason: \"disabled by --no-open\" };\n const env = host.env ?? process.env;\n // Test runners must never reach the human's real browser (or load the\n // production Studio handshake page): a fixture-driven flow that forgets to\n // inject an opener would otherwise spawn real tabs on the developer's\n // machine. Unlike agent shells — which deliberately DO auto-open — test\n // environments are identifiable and always suppressed.\n if (env.VITEST || env.NODE_ENV === \"test\") return { open: false, reason: \"test environment\" };\n if (env.CI) return { open: false, reason: \"CI environment\" };\n if (env.SSH_CONNECTION || env.SSH_TTY) return { open: false, reason: \"SSH session; pass --open to force\" };\n const platform = host.platform ?? process.platform;\n if (platform !== \"darwin\" && platform !== \"win32\" && !env.DISPLAY && !env.WAYLAND_DISPLAY) {\n return { open: false, reason: \"no graphical display; pass --open to force\" };\n }\n return { open: true, mode: \"auto\" };\n}\n\n/** Construct the fallback Studio URL for servers predating verification URIs. */\nexport function handshakeUrl(platformUrl: string, userCode: string): string {\n const url = new URL(\"/studio\", platformUrl);\n url.searchParams.set(\"code\", userCode);\n return url.toString();\n}\n\n/** Canonical credential audience: one HTTPS origin (HTTP only on loopback). */\nexport function platformAudience(value: string): string {\n let url: URL;\n try { url = new URL(value); } catch { throw new Error(\"platform must be an absolute URL\"); }\n const local = url.hostname === \"localhost\" || url.hostname === \"127.0.0.1\" || url.hostname === \"[::1]\";\n if (url.protocol !== \"https:\" && !(local && url.protocol === \"http:\")) {\n throw new Error(\"platform credentials require HTTPS except for loopback development\");\n }\n if (url.username || url.password || url.search || url.hash) {\n throw new Error(\"platform URL must not contain credentials, query, or fragment\");\n }\n return url.origin;\n}\n","import { rmSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport process from \"node:process\";\nimport { readJsonFile, writePrivateJson } from \"./local\";\nimport type { LoadedProjectConfig } from \"./types\";\n\n/** One pending device handshake, persisted (mode 0600) the moment it starts so\n * a killed CLI — agent tool shells time out long before a human approves — can\n * resume collecting instead of losing the approval. */\nexport interface PendingHandshake {\n /** Canonical platform audience the handshake was started against. */\n platform: string;\n email: string;\n userCode: string;\n /** Opaque poll credential; private like the cached token, never displayed. */\n deviceCode: string;\n approvalUrl: string;\n /** Seconds between polls, as announced by the server at start. */\n interval: number;\n /** Epoch milliseconds when the handshake lapses server-side. */\n expiresAt: number;\n}\n\n/** The pending-handshake file lives beside the token cache; the default\n * `.odla/handshake.local.json` is covered by the managed gitignore rules. */\nexport function handshakeFile(cfg: Pick<LoadedProjectConfig, \"local\">): string {\n return join(dirname(cfg.local.tokenFile), \"handshake.local.json\");\n}\n\n/** Don't resume a handshake about to lapse mid-poll; start fresh instead. */\nconst RESUME_MARGIN_MS = 5_000;\n\n/** Read a still-claimable pending handshake for this audience and account. */\nexport function readPendingHandshake(path: string, platform: string, email: string): PendingHandshake | null {\n const pending = readJsonFile<Partial<PendingHandshake>>(path);\n if (!pending || pending.platform !== platform || pending.email !== email) return null;\n if (typeof pending.userCode !== \"string\" || typeof pending.deviceCode !== \"string\" || typeof pending.approvalUrl !== \"string\") return null;\n if (typeof pending.expiresAt !== \"number\" || pending.expiresAt <= Date.now() + RESUME_MARGIN_MS) return null;\n return { interval: 3, ...pending } as PendingHandshake;\n}\n\nexport function writePendingHandshake(path: string, pending: PendingHandshake): void {\n writePrivateJson(path, pending);\n}\n\nexport function clearPendingHandshake(path: string): void {\n rmSync(path, { force: true });\n}\n\n/** Whole minutes (at least 1) before the handshake lapses, for messages. */\nexport function minutesLeft(expiresAt: number): number {\n return Math.max(1, Math.round((expiresAt - Date.now()) / 60_000));\n}\n\n/** One-line pointer to the approval page; every wait message ends with it. */\nexport function approvalHint(pending: Pick<PendingHandshake, \"userCode\" | \"approvalUrl\" | \"expiresAt\">): string {\n return `approve code ${pending.userCode} at ${pending.approvalUrl} (${minutesLeft(pending.expiresAt)}m left)`;\n}\n\n/** Reprint the approval pointer while polling so even a shell that kills the\n * process mid-wait ends its captured output with the URL the human needs.\n * Returns a stop function; the timer never holds the process open. */\nexport function approvalReminder(\n out: Pick<typeof console, \"log\">,\n pending: Pick<PendingHandshake, \"userCode\" | \"approvalUrl\" | \"expiresAt\">,\n periodMs = 30_000,\n): () => void {\n const timer = setInterval(() => out.log(`auth: still waiting — ${approvalHint(pending)}`), periodMs);\n (timer as unknown as { unref?: () => void }).unref?.();\n return () => clearInterval(timer);\n}\n\n/** Resolve the approval wait cap: an explicit `--wait` always wins; an\n * interactive terminal waits out the handshake's own expiry; every other\n * shell (agent tools, pipes, CI) is capped at 90 seconds — those shells kill\n * long-running commands, and the persisted pending handshake makes the rerun\n * resume instantly instead of minting a new code. */\nexport function handshakeWaitMs(\n waitSeconds: number | undefined,\n interactive: boolean = process.stdout.isTTY === true,\n): number | undefined {\n if (waitSeconds !== undefined) return waitSeconds * 1000;\n return interactive ? undefined : 90_000;\n}\n","import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, relative, resolve } from \"node:path\";\nimport type { LoadedProjectConfig, LocalCredentials } from \"./types\";\n\nconst GITIGNORE_LINES = [\".odla/*.local.json\", \".odla/dev-token.json\", \".dev.vars\"];\n\nexport function readJsonFile<T>(path: string): T | null {\n try {\n return JSON.parse(readFileSync(path, \"utf8\")) as T;\n } catch {\n return null;\n }\n}\n\nexport function writePrivateJson(path: string, value: unknown): void {\n writePrivateText(path, `${JSON.stringify(value, null, 2)}\\n`);\n}\n\nexport function readCredentials(path: string): LocalCredentials | null {\n if (!existsSync(path)) return null;\n let value: unknown;\n try {\n value = JSON.parse(readFileSync(path, \"utf8\"));\n } catch {\n throw new Error(`credentials file ${path} is not valid JSON; fix or remove it before provisioning`);\n }\n if (!value || typeof value !== \"object\" || typeof (value as LocalCredentials).appId !== \"string\" ||\n !(value as LocalCredentials).envs || typeof (value as LocalCredentials).envs !== \"object\") {\n throw new Error(`credentials file ${path} has an invalid shape; fix or remove it before provisioning`);\n }\n return value as LocalCredentials;\n}\n\nexport function mergeCredential(\n current: LocalCredentials | null,\n update: { appId: string; platformUrl: string; dbEndpoint: string; env: string; tenantId: string; dbKey?: string; o11yToken?: string },\n): LocalCredentials {\n const next: LocalCredentials = current ?? {\n appId: update.appId,\n platformUrl: update.platformUrl,\n dbEndpoint: update.dbEndpoint,\n updatedAt: new Date(0).toISOString(),\n envs: {},\n };\n next.appId = update.appId;\n next.platformUrl = update.platformUrl;\n next.dbEndpoint = update.dbEndpoint;\n next.updatedAt = new Date().toISOString();\n next.envs[update.env] = {\n ...(next.envs[update.env] ?? {}),\n tenantId: update.tenantId,\n ...(update.dbKey ? { dbKey: update.dbKey } : {}),\n ...(update.o11yToken ? { o11yToken: update.o11yToken } : {}),\n };\n return next;\n}\n\nexport function ensureGitignore(rootDir: string, localPaths: string[] = []): void {\n const path = resolve(rootDir, \".gitignore\");\n const existing = existsSync(path) ? readFileSync(path, \"utf8\") : \"\";\n const configured = localPaths.map((localPath) => gitignoreEntry(rootDir, localPath)).filter((line): line is string => !!line);\n const wanted = [...new Set([...GITIGNORE_LINES, ...configured])];\n const missing = wanted.filter((line) => !existing.split(/\\r?\\n/).includes(line));\n if (missing.length === 0) return;\n const prefix = existing && !existing.endsWith(\"\\n\") ? \"\\n\" : \"\";\n writeFileSync(path, `${existing}${prefix}${missing.join(\"\\n\")}\\n`);\n}\n\nexport interface O11yDevVars {\n endpoint: string;\n service: string;\n version?: string;\n}\n\nexport function o11yDevVars(cfg: LoadedProjectConfig): O11yDevVars | undefined {\n if (!cfg.services.includes(\"o11y\")) return undefined;\n return {\n endpoint: cfg.o11y?.endpoint ?? \"https://o11y.odla.ai\",\n service: cfg.o11y?.service ?? cfg.app.id,\n ...(cfg.o11y?.version ? { version: cfg.o11y.version } : {}),\n };\n}\n\nexport function resolveWriteDevVarsTarget(cfg: LoadedProjectConfig, requested: string | boolean | undefined): string | null {\n if (!requested) return null;\n if (requested === true) return cfg.local.devVarsFile;\n return resolve(dirname(cfg.configPath), requested);\n}\n\nexport function writeDevVars(path: string, credentials: LocalCredentials, env: string, o11y?: O11yDevVars): void {\n const entry = credentials.envs[env];\n if (!entry) throw new Error(`no credentials for env \"${env}\" in ${path}`);\n const lines = [`ODLA_PLATFORM=\"${credentials.platformUrl}\"`];\n if (entry.dbKey) lines.push(`ODLA_ENDPOINT=\"${credentials.dbEndpoint}\"`);\n lines.push(`ODLA_APP_ID=\"${credentials.appId}\"`, `ODLA_ENV=\"${env}\"`, `ODLA_TENANT=\"${entry.tenantId}\"`);\n if (entry.dbKey) lines.push(`ODLA_API_KEY=\"${entry.dbKey}\"`);\n if (o11y) {\n lines.push(`ODLA_O11Y_ENDPOINT=\"${o11y.endpoint}\"`, `ODLA_O11Y_SERVICE=\"${o11y.service}\"`);\n if (o11y.version) lines.push(`ODLA_O11Y_VERSION=\"${o11y.version}\"`);\n // The ingest token is a secret; .dev.vars is gitignored (holds ODLA_API_KEY too).\n if (entry.o11yToken) lines.push(`ODLA_O11Y_TOKEN=\"${entry.o11yToken}\"`);\n }\n const existing = existsSync(path) ? readFileSync(path, \"utf8\") : \"\";\n const retained = existing.split(/\\r?\\n/).filter((line) => !isManagedDevVar(line));\n while (retained.at(-1) === \"\") retained.pop();\n const prefix = retained.length ? `${retained.join(\"\\n\")}\\n\\n` : \"\";\n writePrivateText(path, `${prefix}${lines.join(\"\\n\")}\\n`);\n}\n\nconst MANAGED_DEV_VARS = new Set([\n \"ODLA_PLATFORM\", \"ODLA_ENDPOINT\", \"ODLA_APP_ID\", \"ODLA_ENV\", \"ODLA_TENANT\", \"ODLA_API_KEY\",\n \"ODLA_O11Y_ENDPOINT\", \"ODLA_O11Y_SERVICE\", \"ODLA_O11Y_VERSION\", \"ODLA_O11Y_TOKEN\",\n]);\n\nfunction isManagedDevVar(line: string): boolean {\n const match = line.match(/^\\s*(?:export\\s+)?([A-Z][A-Z0-9_]*)\\s*=/);\n return !!match?.[1] && MANAGED_DEV_VARS.has(match[1]);\n}\n\nfunction writePrivateText(path: string, text: string): void {\n mkdirSync(dirname(path), { recursive: true });\n const temporary = `${path}.tmp-${process.pid}-${Date.now()}`;\n writeFileSync(temporary, text, { mode: 0o600 });\n chmodSync(temporary, 0o600);\n renameSync(temporary, path);\n}\n\nexport function gitignoreEntry(rootDir: string, path: string): string | null {\n const rel = relative(resolve(rootDir), resolve(path));\n if (!rel || rel === \"..\" || rel.startsWith(`..${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`) || isAbsolute(rel)) return null;\n return rel.replaceAll(\"\\\\\", \"/\");\n}\n\nexport function displayPath(path: string, rootDir = process.cwd()): string {\n const rel = relative(rootDir, path);\n return rel && !rel.startsWith(\"..\") ? rel : path;\n}\n","import { spawn } from \"node:child_process\";\nimport process from \"node:process\";\n\nexport interface OpenUrlOptions {\n platform?: NodeJS.Platform;\n spawnImpl?: typeof spawn;\n}\n\nexport async function openUrl(url: string, options: OpenUrlOptions = {}): Promise<void> {\n const command = openerFor(options.platform ?? process.platform);\n const doSpawn = options.spawnImpl ?? spawn;\n await new Promise<void>((resolve, reject) => {\n const child = doSpawn(command.cmd, [...command.args, url], {\n stdio: \"ignore\",\n detached: true,\n });\n child.once(\"error\", reject);\n child.once(\"spawn\", () => {\n child.unref();\n resolve();\n });\n });\n}\n\nexport function openerFor(platform: NodeJS.Platform): { cmd: string; args: string[] } {\n if (platform === \"darwin\") return { cmd: \"open\", args: [] };\n if (platform === \"win32\") return { cmd: \"cmd\", args: [\"/c\", \"start\", \"\"] };\n return { cmd: \"xdg-open\", args: [] };\n}\n","import process from \"node:process\";\n\n/**\n * Secret ingestion shared by every write-only CLI transfer (`admin ai\n * credential set`, `secrets set`, `secrets set-clerk-key`): values may come\n * only from a named environment variable or stdin — never argv — so they\n * cannot land in shell history, process listings, or an agent's transcript.\n */\nexport interface SecretInputOptions {\n /** Environment variable holding the value. Mutually exclusive with `stdin`. */\n fromEnv?: string;\n /** Read the value from stdin. Mutually exclusive with `fromEnv`. */\n stdin?: boolean;\n /** Test/embedding override for the stdin reader. */\n readStdin?: () => Promise<string>;\n}\n\nconst MAX_BYTES = 64 * 1024;\n\n/**\n * Resolve the secret value from exactly one of `--from-env`/`--stdin`,\n * stripping one trailing newline and rejecting empty or >64 KiB values.\n * `kind` names the value in error messages (e.g. \"credential\", \"secret\").\n */\nexport async function secretInputValue(options: SecretInputOptions, kind = \"credential\"): Promise<string> {\n if (options.fromEnv && options.stdin) throw new Error(\"choose exactly one of --from-env or --stdin\");\n let value: string | undefined;\n if (options.fromEnv) value = process.env[options.fromEnv];\n else if (options.stdin) value = await (options.readStdin ?? (() => readSecretStream(kind)))();\n else throw new Error(`${kind} input required: use --from-env <NAME> or --stdin; values are never accepted as arguments`);\n value = value?.replace(/[\\r\\n]+$/, \"\");\n if (!value) throw new Error(options.fromEnv ? `environment variable ${options.fromEnv} is empty or unset` : `stdin ${kind} is empty`);\n if (new TextEncoder().encode(value).byteLength > MAX_BYTES) throw new Error(`${kind} exceeds 64 KiB`);\n return value;\n}\n\n/** @internal Default stdin reader; `stream` is injectable only for tests. */\nexport async function readSecretStream(kind: string, stream: AsyncIterable<unknown> = process.stdin): Promise<string> {\n let value = \"\";\n for await (const chunk of stream) {\n value += String(chunk);\n if (value.length > MAX_BYTES) throw new Error(`${kind} exceeds 64 KiB`);\n }\n return value;\n}\n","import { existsSync } from \"node:fs\";\nimport process from \"node:process\";\nimport { requestToken } from \"@odla-ai/db\";\nimport { ensureGitignore, readJsonFile, writePrivateJson } from \"./local\";\nimport { openUrl } from \"./open\";\nimport { approvalBrowser, handshakeEmail, handshakeUrl, platformAudience } from \"./token\";\n\n/** One exact platform scope obtainable through the admin device flow. */\nexport type ScopedPlatformScope =\n | \"platform:ai:policy:read\"\n | \"platform:ai:policy:write\"\n | \"platform:ai:credential:read\"\n | \"platform:ai:credential:write\"\n | \"platform:ai:usage:read\"\n | \"platform:ai:audit:read\"\n | \"platform:security:self\";\n\n/** Inputs for obtaining one short-lived, exact-scope platform device grant. */\nexport interface ScopedPlatformTokenOptions {\n platform: string;\n scope: ScopedPlatformScope;\n /** Existing odla account email used only when a fresh handshake is required. */\n email?: string;\n open?: boolean;\n fetch?: typeof fetch;\n stdout?: Pick<typeof console, \"log\">;\n openApprovalUrl?: (url: string) => Promise<void>;\n tokenFile?: string;\n}\n\ninterface AdminPlatformTokenOptions extends ScopedPlatformTokenOptions {\n token?: string;\n}\n\n/** Obtain/cache one exact platform scope without granting ambient admin. */\nexport async function getScopedPlatformToken(options: ScopedPlatformTokenOptions): Promise<string> {\n return resolveAdminPlatformToken(options);\n}\n\n/** Resolve an explicit, audience-bound env, cached, or newly approved token. */\nexport async function resolveAdminPlatformToken(options: AdminPlatformTokenOptions): Promise<string> {\n const audience = platformAudience(options.platform);\n if (options.token) return options.token;\n const fromEnv = process.env.ODLA_ADMIN_TOKEN;\n if (fromEnv) return audienceBoundEnvToken(fromEnv, audience);\n return scopedToken(\n audience,\n options.scope,\n options,\n options.fetch ?? fetch,\n options.stdout ?? console,\n );\n}\n\nfunction audienceBoundEnvToken(token: string, platform: string): string {\n const audience = platformAudience(platform);\n const declared = process.env.ODLA_ADMIN_TOKEN_AUDIENCE;\n if (declared) {\n if (platformAudience(declared) !== audience) throw new Error(\"ODLA_ADMIN_TOKEN_AUDIENCE does not match the configured platform\");\n } else if (audience !== \"https://odla.ai\") {\n throw new Error(\"ODLA_ADMIN_TOKEN_AUDIENCE is required for a non-default platform\");\n }\n return token;\n}\n\nasync function scopedToken(\n platform: string,\n scope: string,\n options: ScopedPlatformTokenOptions,\n doFetch: typeof fetch,\n out: Pick<typeof console, \"log\">,\n): Promise<string> {\n const audience = platformAudience(platform);\n const tokenFile = options.tokenFile ?? `${process.cwd()}/.odla/admin-token.local.json`;\n const cache = readJsonFile<{ platform?: string; email?: string; tokens?: Record<string, { token?: string; expiresAt?: number }> }>(tokenFile);\n const cached = cache?.platform === audience ? cache.tokens?.[scope] : undefined;\n if (cached?.token && (cached.expiresAt ?? 0) > Date.now() + 60_000) {\n out.log(`auth: using cached ${scope} grant (${tokenFile})`);\n return cached.token;\n }\n const email = handshakeEmail(options.email, cache?.platform === audience ? cache.email : undefined);\n const { token, expiresAt } = await requestToken({\n endpoint: audience,\n email,\n label: `odla CLI admin AI (${scope})`,\n scopes: [scope],\n fetch: doFetch,\n onCode: async ({ userCode, expiresIn, verificationUriComplete }) => {\n const approvalUrl = verificationUriComplete ?? handshakeUrl(audience, userCode);\n out.log(`Review, then approve scoped request ${userCode} at ${approvalUrl} within ${Math.floor(expiresIn / 60)}m.`);\n if (approvalBrowser({ open: options.open }).open) {\n await (options.openApprovalUrl ?? openUrl)(approvalUrl).catch(() => undefined);\n }\n },\n });\n const tokens = cache?.platform === audience ? { ...(cache.tokens ?? {}) } : {};\n tokens[scope] = { token, expiresAt };\n if (existsSync(`${process.cwd()}/.git`)) ensureGitignore(process.cwd(), [tokenFile]);\n writePrivateJson(tokenFile, { platform: audience, email, tokens });\n out.log(`auth: cached ${scope} grant (${tokenFile}; mode 0600)`);\n return token;\n}\n","/** Optional limit for the metadata-only System AI administration trail. */\nexport interface AdminAiAuditFilters {\n limit?: number;\n}\n\ninterface AdminAiAuditRequest {\n platform: string;\n query: string;\n headers: Record<string, string>;\n json?: boolean;\n fetch: typeof fetch;\n stdout: Pick<typeof console, \"log\">;\n}\n\n/** Validate the audit limit and build its query before authentication. */\nexport function adminAiAuditQuery(filters: AdminAiAuditFilters): string {\n if (filters.limit === undefined) return \"\";\n if (!Number.isSafeInteger(filters.limit) || filters.limit < 1 || filters.limit > 200) {\n throw new Error(\"audit limit must be an integer from 1 to 200\");\n }\n return `?limit=${filters.limit}`;\n}\n\n/** Read and render immutable, metadata-only System AI admin changes. */\nexport async function readAdminAiAudit(request: AdminAiAuditRequest): Promise<void> {\n const response = await request.fetch(`${request.platform}/registry/platform/ai-audit${request.query}`, {\n headers: request.headers,\n });\n const body = await responseBody(response);\n if (!response.ok) throw new Error(apiError(response.status, body));\n if (request.json) {\n request.stdout.log(JSON.stringify(body, null, 2));\n return;\n }\n const events = isRecord(body) && Array.isArray(body.events) ? body.events.filter(isRecord) : [];\n request.stdout.log(\"when\\tchange\\ttarget\\tbefore -> after\\tactor\");\n for (const event of events) {\n const before = isRecord(event.oldPolicy) ? event.oldPolicy : undefined;\n const after = isRecord(event.newPolicy) ? event.newPolicy : undefined;\n const route = before && after\n ? `${String(before.provider)}/${String(before.model)}@v${String(before.version)} -> ${String(after.provider)}/${String(after.model)}@v${String(after.version)}`\n : \"value not retained\";\n request.stdout.log([\n timestamp(event.createdAt), String(event.changeKind ?? \"\"),\n String(event.purpose ?? event.provider ?? \"\"), route,\n `${String(event.actorType ?? \"\")}:${String(event.actorId ?? \"\")}`,\n ].join(\"\\t\"));\n }\n}\n\nasync function responseBody(response: Response): Promise<unknown> {\n const text = await response.text();\n if (!text) return {};\n try { return JSON.parse(text) as unknown; } catch { return { message: text.slice(0, 300) }; }\n}\n\nfunction apiError(status: number, body: unknown): string {\n const error = isRecord(body) && isRecord(body.error) ? body.error : undefined;\n const message = error && typeof error.message === \"string\"\n ? error.message\n : isRecord(body) && typeof body.message === \"string\" ? body.message : \"request failed\";\n return `read System AI admin changes failed (${status}): ${message}`;\n}\n\nfunction timestamp(value: unknown): string {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return String(value ?? \"\");\n const date = new Date(value);\n return Number.isFinite(date.valueOf()) ? date.toISOString() : \"\";\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n","/** Hosted platform purposes whose provider, model, and budgets an admin may route. */\nexport const SYSTEM_AI_PURPOSES = [\"o11y.triage\", \"security.discovery\", \"security.validation\"] as const;\n\n/** One catalog-validated, platform-funded System AI purpose. */\nexport type SystemAiPurpose = (typeof SYSTEM_AI_PURPOSES)[number];\n\n/** Validate a CLI purpose before any network mutation. */\nexport function requireSystemAiPurpose(value: string | undefined): SystemAiPurpose {\n if (!SYSTEM_AI_PURPOSES.includes(value as SystemAiPurpose)) {\n throw new Error(`purpose must be one of: ${SYSTEM_AI_PURPOSES.join(\", \")}`);\n }\n return value as SystemAiPurpose;\n}\n","/** Optional metadata-only filters for attributed platform AI usage. */\nexport interface AdminAiUsageFilters {\n appId?: string;\n env?: string;\n runId?: string;\n limit?: number;\n}\n\ninterface AdminAiUsageRequest {\n platform: string;\n query: string;\n headers: Record<string, string>;\n json?: boolean;\n fetch: typeof fetch;\n stdout: Pick<typeof console, \"log\">;\n}\n\n/** Validate usage filters and build the platform query before authentication. */\nexport function adminAiUsageQuery(filters: AdminAiUsageFilters): string {\n const params = new URLSearchParams();\n if (filters.appId?.trim()) params.set(\"appId\", filters.appId.trim());\n if (filters.env?.trim()) params.set(\"env\", filters.env.trim());\n if (filters.runId?.trim()) params.set(\"runId\", filters.runId.trim());\n if (filters.limit !== undefined) params.set(\"limit\", String(usageLimit(filters.limit)));\n const query = params.toString();\n return query ? `?${query}` : \"\";\n}\n\n/** Read and render metadata-only, app-attributed platform AI usage. */\nexport async function readAdminAiUsage(request: AdminAiUsageRequest): Promise<void> {\n const res = await request.fetch(`${request.platform}/registry/platform/ai-usage${request.query}`, {\n headers: request.headers,\n });\n const body = await responseBody(res);\n if (!res.ok) throw new Error(apiError(\"read platform AI usage\", res.status, body));\n if (request.json) request.stdout.log(JSON.stringify(body, null, 2));\n else printUsage(body, request.stdout);\n}\n\nfunction usageLimit(value: number): number {\n if (!Number.isSafeInteger(value) || value < 1 || value > 500) {\n throw new Error(\"usage limit must be an integer from 1 to 500\");\n }\n return value;\n}\n\nfunction printUsage(body: unknown, out: Pick<typeof console, \"log\">): void {\n const aggregates = isRecord(body) && isRecord(body.aggregates) && Array.isArray(body.aggregates.byStatus)\n ? body.aggregates.byStatus.filter(isRecord)\n : [];\n out.log(`All retained hosted-security status totals (up to ${String(isRecord(body) ? body.retentionDays ?? 90 : 90)} days; o11y triage excluded)\\nstatus\\tcalls\\tinput tokens\\toutput tokens\\tcost\\tunpriced calls`);\n for (const row of aggregates) {\n out.log([\n String(row.status ?? \"\"), String(row.calls ?? \"\"), String(row.input_tokens ?? \"\"),\n String(row.output_tokens ?? \"\"), formatMicrousd(row.cost_microusd), String(row.unpriced_calls ?? \"\"),\n ].join(\"\\t\"));\n }\n const events = isRecord(body) && Array.isArray(body.events) ? body.events.filter(isRecord) : [];\n out.log(`Latest ${String(isRecord(body) ? body.eventLimit ?? events.length : events.length)} hosted-security events\\nwhen\\tapp/env\\trun\\tactor\\tpurpose/role\\troute / policy\\ttokens\\tcost\\tstatus`);\n for (const event of events) {\n const input = numeric(event.input_tokens);\n const output = numeric(event.output_tokens);\n const priced = event.priced === true || event.priced === 1;\n out.log([\n timestamp(event.created_at), `${String(event.app_id ?? \"\")}/${String(event.env ?? \"\")}`,\n String(event.run_id ?? \"\"), `${String(event.actor_type ?? \"\")}:${String(event.actor_id ?? \"\")}`,\n `${String(event.purpose ?? \"\")}/${String(event.role ?? \"\")}`,\n `${String(event.provider ?? \"\")}/${String(event.model ?? \"\")}@v${String(event.policy_version ?? \"unknown\")}`, String(input + output),\n priced ? formatMicrousd(event.cost_microusd) : \"unpriced\",\n `${String(event.status ?? \"\")}${event.error_code ? `:${String(event.error_code)}` : \"\"}`,\n ].join(\"\\t\"));\n }\n}\n\nfunction numeric(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n\nfunction formatMicrousd(value: unknown): string {\n return typeof value === \"number\" && Number.isFinite(value) ? `$${(value / 1_000_000).toFixed(6)}` : \"unpriced\";\n}\n\nfunction timestamp(value: unknown): string {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return String(value ?? \"\");\n const date = new Date(value);\n return Number.isFinite(date.valueOf()) ? date.toISOString() : \"\";\n}\n\nasync function responseBody(res: Response): Promise<unknown> {\n const text = await res.text();\n if (!text) return {};\n try { return JSON.parse(text) as unknown; } catch { return { message: text.slice(0, 300) }; }\n}\n\nfunction apiError(action: string, status: number, body: unknown): string {\n const error = isRecord(body) && isRecord(body.error) ? body.error : undefined;\n const message = error && typeof error.message === \"string\" ? error.message : isRecord(body) && typeof body.message === \"string\" ? body.message : \"request failed\";\n return `${action} failed (${status}): ${message}`;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n","export type OptionValue = string | boolean | string[];\n\nexport interface ParsedArgv {\n positionals: string[];\n options: Record<string, OptionValue>;\n}\n\n/** Parse the small, dependency-free option grammar shared by every CLI command. */\nexport function parseArgv(argv: string[]): ParsedArgv {\n const positionals: string[] = [];\n const options: Record<string, OptionValue> = {};\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i]!;\n if (!arg.startsWith(\"--\")) {\n positionals.push(arg);\n continue;\n }\n const eq = arg.indexOf(\"=\");\n const rawName = arg.slice(2, eq === -1 ? undefined : eq);\n if (!rawName) continue;\n if (rawName.startsWith(\"no-\")) {\n options[rawName.slice(3)] = false;\n continue;\n }\n if (eq !== -1) {\n addOption(options, rawName, arg.slice(eq + 1));\n continue;\n }\n const value = argv[i + 1];\n if (value !== undefined && !value.startsWith(\"--\")) {\n i++;\n addOption(options, rawName, value);\n } else {\n addOption(options, rawName, true);\n }\n }\n return { positionals, options };\n}\n\nexport function assertArgs(parsed: ParsedArgv, allowedOptions: string[], maxPositionals: number): void {\n const allowed = new Set(allowedOptions);\n for (const name of Object.keys(parsed.options)) {\n if (!allowed.has(name)) throw new Error(`unknown option \"--${name}\"; run \"odla-ai help\" for supported options`);\n }\n if (parsed.positionals.length > maxPositionals) {\n throw new Error(`unexpected argument \"${parsed.positionals[maxPositionals]}\"; run \"odla-ai help\"`);\n }\n}\n\nexport function requiredString(value: OptionValue | undefined, name: string): string {\n const result = stringOpt(value);\n if (!result) throw new Error(`${name} is required`);\n return result;\n}\n\nexport function stringOpt(value: OptionValue | undefined): string | undefined {\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) return value[value.length - 1];\n return undefined;\n}\n\nexport function listOpt(value: OptionValue | undefined): string[] | undefined {\n if (value === undefined || typeof value === \"boolean\") return undefined;\n const values = Array.isArray(value) ? value : [value];\n return values.flatMap((item) => item.split(\",\")).map((item) => item.trim()).filter(Boolean);\n}\n\nexport function boolOpt(value: OptionValue | undefined): boolean | undefined {\n if (typeof value === \"boolean\") return value;\n if (typeof value === \"string\" && (value === \"true\" || value === \"false\")) return value === \"true\";\n if (value === undefined) return undefined;\n throw new Error(\"boolean option must be true or false\");\n}\n\nexport function numberOpt(value: OptionValue | undefined, flag: string): number | undefined {\n if (value === undefined) return undefined;\n const raw = stringOpt(value);\n const parsed = raw === undefined ? Number.NaN : Number(raw);\n if (!Number.isSafeInteger(parsed) || parsed < 1) throw new Error(`${flag} requires a positive integer`);\n return parsed;\n}\n\nfunction addOption(options: Record<string, OptionValue>, name: string, value: string | boolean): void {\n const current = options[name];\n if (current === undefined) options[name] = value;\n else if (Array.isArray(current)) current.push(String(value));\n else options[name] = [String(current), String(value)];\n}\n","import { adminAi } from \"./admin-ai\";\nimport {\n assertArgs,\n boolOpt,\n numberOpt,\n stringOpt,\n type ParsedArgv,\n} from \"./argv\";\n\nexport async function adminCommand(parsed: ParsedArgv): Promise<void> {\n const area = parsed.positionals[1];\n const action = parsed.positionals[2];\n const credentialSet = action === \"credential\" && parsed.positionals[3] === \"set\";\n const credentials = action === \"credentials\";\n const models = action === \"models\";\n const usage = action === \"usage\";\n const audit = action === \"audit\";\n if (area !== \"ai\" || (action !== \"show\" && action !== \"set\"\n && !credentialSet && !credentials && !models && !usage && !audit)) {\n throw new Error('unknown admin command. Try \"odla-ai admin ai show\".');\n }\n assertArgs(parsed, [\n \"platform\", \"json\", \"open\", \"email\", \"provider\", \"model\", \"enabled\",\n \"max-input-bytes\", \"max-output-tokens\", \"max-calls-per-run\", \"from-env\", \"stdin\",\n \"discovery-provider\", \"discovery-model\", \"validation-provider\", \"validation-model\",\n \"app-id\", \"env\", \"run-id\", \"limit\",\n ], credentialSet ? 5 : action === \"set\" ? 4 : 3);\n await adminAi({\n action: credentialSet\n ? \"credential-set\"\n : credentials ? \"credentials\"\n : models ? \"models\"\n : usage ? \"usage\"\n : audit ? \"audit\"\n : action as \"show\" | \"set\",\n purpose: action === \"set\" ? parsed.positionals[3] : undefined,\n provider: stringOpt(parsed.options.provider),\n model: stringOpt(parsed.options.model),\n enabled: boolOpt(parsed.options.enabled),\n maxInputBytes: numberOpt(parsed.options[\"max-input-bytes\"], \"--max-input-bytes\"),\n maxOutputTokens: numberOpt(parsed.options[\"max-output-tokens\"], \"--max-output-tokens\"),\n maxCallsPerRun: numberOpt(parsed.options[\"max-calls-per-run\"], \"--max-calls-per-run\"),\n platform: stringOpt(parsed.options.platform),\n email: stringOpt(parsed.options.email),\n json: parsed.options.json === true,\n open: parsed.options.open === false\n ? false\n : parsed.options.open === true ? true : undefined,\n credentialProvider: credentialSet ? parsed.positionals[4] : undefined,\n fromEnv: stringOpt(parsed.options[\"from-env\"]),\n stdin: parsed.options.stdin === true,\n discoveryProvider: stringOpt(parsed.options[\"discovery-provider\"]),\n discoveryModel: stringOpt(parsed.options[\"discovery-model\"]),\n validationProvider: stringOpt(parsed.options[\"validation-provider\"]),\n validationModel: stringOpt(parsed.options[\"validation-model\"]),\n appId: stringOpt(parsed.options[\"app-id\"]),\n env: stringOpt(parsed.options.env),\n runId: stringOpt(parsed.options[\"run-id\"]),\n limit: numberOpt(parsed.options.limit, \"--limit\"),\n });\n}\n","// `odla-ai app export` — download a portable snapshot of the configured app's\n// database (gzipped JSONL: schema registry, config, every row). The data-\n// portability half of the backup system: any developer credential that owns\n// the app can pull its data out at any time.\nimport { createWriteStream } from \"node:fs\";\nimport { Readable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport { loadProjectConfig } from \"./config\";\nimport { getDeveloperToken } from \"./token\";\n\nexport interface AppExportOptions {\n configPath: string;\n env?: string;\n token?: string;\n email?: string;\n /** Take a fresh snapshot first instead of downloading the newest existing one. */\n fresh?: boolean;\n /** Output path; defaults to `{tenant}-{date}-tx{n}.jsonl.gz` in cwd. */\n out?: string;\n json?: boolean;\n fetch?: typeof fetch;\n stdout?: Pick<typeof console, \"log\" | \"error\">;\n}\n\ninterface BackupRow {\n id: string;\n key: string;\n kind: string;\n max_tx: number;\n bytes: number;\n sha256: string;\n created_at: number;\n}\n\nexport async function appExport(options: AppExportOptions): Promise<{ file: string; backup: BackupRow }> {\n const cfg = await loadProjectConfig(options.configPath);\n const out = options.stdout ?? console;\n const doFetch = options.fetch ?? fetch;\n const env = options.env ?? (cfg.envs.includes(\"dev\") ? \"dev\" : cfg.envs[0]);\n if (!env || !cfg.envs.includes(env)) throw new Error(`env \"${env ?? \"\"}\" is not declared in ${options.configPath}`);\n const tenant = env === \"prod\" ? cfg.app.id : `${cfg.app.id}--${env}`;\n const token = await getDeveloperToken(\n cfg,\n { configPath: cfg.configPath, token: options.token, email: options.email, open: false },\n doFetch,\n out,\n );\n const auth = { authorization: `Bearer ${token}` };\n const base = `${cfg.dbEndpoint}/admin/apps/${encodeURIComponent(tenant)}`;\n\n if (options.fresh) {\n const res = await doFetch(`${base}/export`, { method: \"POST\", headers: auth });\n const body = (await res.json().catch(() => ({}))) as { error?: { code?: string; message?: string } };\n if (!res.ok) throw new Error(`export failed${body.error?.code ? ` (${body.error.code})` : \"\"}: ${body.error?.message ?? res.status}`);\n }\n\n const list = await doFetch(`${base}/backups`, { headers: auth });\n if (!list.ok) throw new Error(`couldn't list backups (${list.status})`);\n const { backups } = (await list.json()) as { backups: BackupRow[] };\n const newest = backups[0];\n if (!newest) {\n throw new Error(\n `${tenant} has no backups yet — run \\`odla-ai app export --fresh\\` to take one now (nightly snapshots appear after the first day with writes)`,\n );\n }\n\n const download = await doFetch(`${base}/backups/${newest.id}/download`, { headers: auth });\n if (!download.ok || !download.body) throw new Error(`download failed (${download.status})`);\n const file = options.out ?? `${tenant}-${new Date(newest.created_at).toISOString().slice(0, 10)}-tx${newest.max_tx}.jsonl.gz`;\n await pipeline(Readable.fromWeb(download.body as never), createWriteStream(file));\n\n if (options.json) out.log(JSON.stringify({ file, backup: newest }, null, 2));\n else {\n out.log(`${tenant}: wrote ${file} (${newest.bytes} bytes, ${newest.kind} snapshot at tx ${newest.max_tx})`);\n out.log(`sha256 ${download.headers.get(\"x-odla-sha256\") ?? newest.sha256}`);\n }\n return { file, backup: newest };\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { AppRules, CalendarServiceConfig, LoadedProjectConfig, OdlaProjectConfig, ProvisionPlan } from \"./types\";\n\nconst DEFAULT_PLATFORM = \"https://odla.ai\";\n// Safe-by-default: production must be opted into explicitly in odla.config.\nconst DEFAULT_ENVS = [\"dev\"];\nconst DEFAULT_SERVICES = [\"db\", \"ai\"];\n/** The Google OAuth scope that authorizes booking writes (events read/write). */\nexport const GOOGLE_CALENDAR_EVENTS_SCOPE = \"https://www.googleapis.com/auth/calendar.events\";\n\nexport async function loadProjectConfig(configPath = \"odla.config.mjs\"): Promise<LoadedProjectConfig> {\n const resolved = resolve(configPath);\n if (!existsSync(resolved)) {\n throw new Error(`config not found: ${configPath}. Run \"odla-ai init\" first or pass --config.`);\n }\n\n const raw = await loadConfigModule(resolved);\n const rootDir = dirname(resolved);\n validateRawConfig(raw, resolved);\n\n const platformUrl = trimSlash(process.env.ODLA_PLATFORM_URL || raw.platformUrl || DEFAULT_PLATFORM);\n const dbEndpoint = trimSlash(process.env.ODLA_DB_ENDPOINT || raw.dbEndpoint || platformUrl);\n const envs = unique(raw.envs?.length ? raw.envs : DEFAULT_ENVS);\n const services = unique(raw.services?.length ? raw.services : DEFAULT_SERVICES);\n validateCalendarConfig(raw, envs, services, resolved);\n const local = {\n tokenFile: resolve(rootDir, raw.local?.tokenFile ?? \".odla/dev-token.json\"),\n credentialsFile: resolve(rootDir, raw.local?.credentialsFile ?? \".odla/credentials.local.json\"),\n devVarsFile: resolve(rootDir, raw.local?.devVarsFile ?? \".dev.vars\"),\n gitignore: raw.local?.gitignore ?? true,\n };\n\n return {\n ...raw,\n configPath: resolved,\n rootDir,\n platformUrl,\n dbEndpoint,\n envs,\n services,\n local,\n };\n}\n\nexport async function resolveDataExport<T>(\n cfg: LoadedProjectConfig,\n value: unknown,\n names: string[],\n): Promise<T | undefined> {\n if (value === undefined || value === null || value === false) return undefined;\n if (typeof value !== \"string\") return value as T;\n\n const target = isAbsolute(value) ? value : resolve(cfg.rootDir, value);\n if (target.endsWith(\".json\")) {\n return JSON.parse(readFileSync(target, \"utf8\")) as T;\n }\n const mod = (await import(pathToFileURL(target).href)) as Record<string, unknown>;\n for (const name of names) {\n if (mod[name] !== undefined) return mod[name] as T;\n }\n if (mod.default !== undefined) return mod.default as T;\n throw new Error(`${value} did not export ${names.join(\", \")} or default`);\n}\n\nexport function buildPlan(cfg: LoadedProjectConfig): ProvisionPlan {\n return {\n appId: cfg.app.id,\n appName: cfg.app.name,\n platformUrl: cfg.platformUrl,\n dbEndpoint: cfg.dbEndpoint,\n envs: cfg.envs,\n services: cfg.services,\n hasSchema: !!cfg.db?.schema,\n hasRules: !!cfg.db?.rules || (!!cfg.db?.schema && cfg.db.defaultRules !== false),\n aiProvider: cfg.ai?.provider,\n };\n}\n\n/** Resolve the checked-in calendar block into one controller-safe env payload. */\nexport function calendarServiceConfig(cfg: LoadedProjectConfig, env: string): CalendarServiceConfig {\n if (!cfg.services.includes(\"calendar\")) throw new Error('calendar service is not enabled in config services');\n if (!cfg.envs.includes(env)) throw new Error(`calendar env \"${env}\" is not declared in config envs`);\n const google = cfg.calendar?.google;\n if (!google) throw new Error(\"calendar.google is required when the calendar service is enabled\");\n const availability = unique(\n (google.availabilityCalendars?.[env] ?? google.calendars?.[env])!.map((id) => id.trim()),\n );\n return {\n provider: \"google\",\n access: \"book\",\n bookingCalendarId: google.bookingCalendar?.[env]?.trim() ?? availability[0]!,\n availabilityCalendars: availability,\n };\n}\n\n/** Public Appointment Schedule URL to apply separately from connector config. */\nexport function calendarBookingPageUrl(cfg: LoadedProjectConfig, env: string): string | null | undefined {\n const value = cfg.calendar?.google.bookingPageUrl?.[env];\n if (value === undefined || value === null) return value;\n return new URL(value).toString();\n}\n\nexport function rulesFromSchema(schema: unknown): AppRules {\n const entities = serializedEntities(schema);\n return Object.fromEntries(\n entities.map((name) => [name, { view: \"false\", create: \"false\", update: \"false\", delete: \"false\" }]),\n );\n}\n\nexport function serializedEntities(schema: unknown): string[] {\n if (!schema || typeof schema !== \"object\") return [];\n const entities = (schema as { entities?: unknown }).entities;\n if (!entities || typeof entities !== \"object\" || Array.isArray(entities)) return [];\n return Object.keys(entities);\n}\n\nexport function envValue(value: string | undefined): string | undefined {\n if (!value) return undefined;\n if (value.startsWith(\"$\")) return process.env[value.slice(1)];\n return value;\n}\n\nfunction validateRawConfig(raw: unknown, path: string): asserts raw is OdlaProjectConfig {\n if (!raw || typeof raw !== \"object\") throw new Error(`${path} must export an object`);\n const cfg = raw as OdlaProjectConfig;\n if (!cfg.app || typeof cfg.app !== \"object\") throw new Error(`${path}: missing app object`);\n if (!validId(cfg.app.id)) throw new Error(`${path}: app.id must be lowercase letters, numbers, and hyphens`);\n if (!cfg.app.name || typeof cfg.app.name !== \"string\") throw new Error(`${path}: app.name is required`);\n if (cfg.envs !== undefined && (!Array.isArray(cfg.envs) || cfg.envs.some((env) => typeof env !== \"string\"))) {\n throw new Error(`${path}: envs must be an array of names`);\n }\n if (cfg.envs?.some((env) => !validId(env))) throw new Error(`${path}: env names must be lowercase letters, numbers, and hyphens`);\n if (cfg.services !== undefined && (!Array.isArray(cfg.services) || cfg.services.some((service) => typeof service !== \"string\" || !service.trim()))) {\n throw new Error(`${path}: services must be an array of non-empty names`);\n }\n}\n\nfunction validateCalendarConfig(cfg: OdlaProjectConfig, envs: string[], services: string[], path: string): void {\n const enabled = services.includes(\"calendar\");\n if (!cfg.calendar) {\n if (enabled) throw new Error(`${path}: calendar.google is required when services includes \"calendar\"`);\n return;\n }\n if (!isRecord(cfg.calendar)) throw new Error(`${path}: calendar must be an object`);\n assertOnly(cfg.calendar, [\"google\"], `${path}: calendar`);\n if (!isRecord(cfg.calendar.google)) throw new Error(`${path}: calendar.google must be an object`);\n const google = cfg.calendar.google;\n assertOnly(\n google,\n [\"availabilityCalendars\", \"calendars\", \"bookingCalendar\", \"bookingPageUrl\"],\n `${path}: calendar.google`,\n );\n // `calendars` is the retired read-mirror spelling of availabilityCalendars;\n // exactly one of the two must be authored.\n const availabilityKey = google.availabilityCalendars !== undefined ? \"availabilityCalendars\"\n : google.calendars !== undefined ? \"calendars\" : null;\n if (!availabilityKey || (google.availabilityCalendars !== undefined && google.calendars !== undefined)) {\n throw new Error(`${path}: calendar.google requires exactly one of availabilityCalendars or calendars (legacy)`);\n }\n const availability = google[availabilityKey];\n if (!isRecord(availability)) throw new Error(`${path}: calendar.google.${availabilityKey} must map env names to calendar ids`);\n const unknownEnv = Object.keys(availability).find((env) => !envs.includes(env));\n if (unknownEnv) throw new Error(`${path}: calendar.google.${availabilityKey}.${unknownEnv} is not in config envs`);\n for (const env of envs) {\n const ids = availability[env];\n if (!Array.isArray(ids) || ids.length === 0) {\n throw new Error(`${path}: calendar.google.${availabilityKey}.${env} must be a non-empty array`);\n }\n if (ids.length > 10) {\n throw new Error(`${path}: calendar.google.${availabilityKey}.${env} must contain at most 10 calendar ids`);\n }\n if (ids.some((id) => !safeText(id, 1_024))) {\n throw new Error(`${path}: calendar.google.${availabilityKey}.${env} contains an invalid calendar id`);\n }\n }\n if (google.bookingCalendar !== undefined) {\n if (!isRecord(google.bookingCalendar)) throw new Error(`${path}: calendar.google.bookingCalendar must map env names to one calendar id`);\n const unknownBookingEnv = Object.keys(google.bookingCalendar).find((env) => !envs.includes(env));\n if (unknownBookingEnv) throw new Error(`${path}: calendar.google.bookingCalendar.${unknownBookingEnv} is not in config envs`);\n for (const [env, value] of Object.entries(google.bookingCalendar)) {\n if (!safeText(value, 1_024)) {\n throw new Error(`${path}: calendar.google.bookingCalendar.${env} must be a calendar id`);\n }\n }\n }\n if (google.bookingPageUrl !== undefined) {\n if (!isRecord(google.bookingPageUrl)) throw new Error(`${path}: calendar.google.bookingPageUrl must map env names to HTTPS URLs or null`);\n const unknownBookingEnv = Object.keys(google.bookingPageUrl).find((env) => !envs.includes(env));\n if (unknownBookingEnv) throw new Error(`${path}: calendar.google.bookingPageUrl.${unknownBookingEnv} is not in config envs`);\n for (const [env, value] of Object.entries(google.bookingPageUrl)) {\n if (value !== null && !safeHttpsUrl(value)) {\n throw new Error(`${path}: calendar.google.bookingPageUrl.${env} must be an HTTPS URL without credentials or fragment`);\n }\n }\n }\n if (enabled && !services.includes(\"db\")) throw new Error(`${path}: calendar service requires the db service`);\n}\n\nfunction assertOnly(value: Record<string, unknown>, allowed: string[], label: string): void {\n const extra = Object.keys(value).find((key) => !allowed.includes(key));\n if (extra) throw new Error(`${label}.${extra} is not supported`);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction safeText(value: unknown, max: number): value is string {\n return typeof value === \"string\" && value.trim().length > 0 && value.length <= max && !/[\\u0000-\\u001f\\u007f]/.test(value);\n}\n\nfunction safeHttpsUrl(value: unknown): value is string {\n if (typeof value !== \"string\" || value.length > 2_048) return false;\n try {\n const url = new URL(value);\n return url.protocol === \"https:\" && !url.username && !url.password && !url.hash;\n } catch {\n return false;\n }\n}\n\nfunction validId(value: unknown): value is string {\n return typeof value === \"string\" && /^[a-z0-9][a-z0-9-]*$/.test(value);\n}\n\nasync function loadConfigModule(path: string): Promise<OdlaProjectConfig> {\n if (path.endsWith(\".json\")) return JSON.parse(readFileSync(path, \"utf8\")) as OdlaProjectConfig;\n const mod = (await import(`${pathToFileURL(path).href}?t=${Date.now()}`)) as {\n default?: OdlaProjectConfig | (() => OdlaProjectConfig | Promise<OdlaProjectConfig>);\n config?: OdlaProjectConfig;\n };\n const value = mod.default ?? mod.config;\n if (typeof value === \"function\") return await value();\n return value as OdlaProjectConfig;\n}\n\nfunction trimSlash(value: string): string {\n return value.replace(/\\/+$/, \"\");\n}\n\nfunction unique(values: string[]): string[] {\n return [...new Set(values.filter(Boolean))];\n}\n","// `odla-ai app archive|restore` — the CLI half of the platform's archive\n// lifecycle. Archive suspends every environment's data plane (keys refused,\n// requests rejected) while retaining ALL data; restore reverses it exactly.\n// There is deliberately NO purge subcommand and the server refuses machine +\n// developer credentials for purge anyway: permanent deletion is a signed-in\n// human's Studio action only.\nimport { appExport } from \"./app-export\";\nimport { assertArgs, stringOpt, type ParsedArgv } from \"./argv\";\nimport { loadProjectConfig } from \"./config\";\nimport { getDeveloperToken } from \"./token\";\n\nexport interface AppLifecycleOptions {\n configPath: string;\n token?: string;\n email?: string;\n yes?: boolean;\n json?: boolean;\n fetch?: typeof fetch;\n stdout?: Pick<typeof console, \"log\" | \"error\">;\n}\n\ninterface LifecycleResponse {\n ok?: boolean;\n app?: { appId: string; archivedAt: number | null };\n operation?: { state: string };\n error?: { code?: string; message?: string };\n}\n\nasync function lifecycleCall(action: \"archive\" | \"restore\", options: AppLifecycleOptions): Promise<LifecycleResponse> {\n const cfg = await loadProjectConfig(options.configPath);\n const out = options.stdout ?? console;\n const doFetch = options.fetch ?? fetch;\n const token = await getDeveloperToken(\n cfg,\n { configPath: cfg.configPath, token: options.token, email: options.email, open: false },\n doFetch,\n out,\n );\n const res = await doFetch(`${cfg.platformUrl}/registry/apps/${encodeURIComponent(cfg.app.id)}/${action}`, {\n method: \"POST\",\n headers: { authorization: `Bearer ${token}`, \"content-type\": \"application/json\" },\n });\n const body = (await res.json().catch(() => ({}))) as LifecycleResponse;\n if (!res.ok || !body.ok) {\n throw new Error(`${action} failed${body.error?.code ? ` (${body.error.code})` : \"\"}: ${body.error?.message ?? `registry returned ${res.status}`}`);\n }\n return body;\n}\n\n/** Archive the configured app. Refuses to run without --yes: this takes every\n * environment's data plane down at once (all data retained, restorable). */\nexport async function appArchive(options: AppLifecycleOptions): Promise<void> {\n if (options.yes !== true) {\n throw new Error(\n \"app archive suspends EVERY environment: API keys stop working and all services refuse requests until restored. \" +\n \"All data is retained. Pass --yes to proceed.\",\n );\n }\n const out = options.stdout ?? console;\n const body = await lifecycleCall(\"archive\", options);\n if (options.json) out.log(JSON.stringify(body, null, 2));\n else if (body.operation?.state === \"noop\") out.log(`${body.app?.appId}: already archived`);\n else out.log(`${body.app?.appId}: archived — data retained; run \\`odla-ai app restore\\` (or use Studio) to bring it back`);\n}\n\n/** Restore (un-archive) the configured app. Idempotent — safe to re-run. */\nexport async function appRestore(options: AppLifecycleOptions): Promise<void> {\n const out = options.stdout ?? console;\n const body = await lifecycleCall(\"restore\", options);\n if (options.json) out.log(JSON.stringify(body, null, 2));\n else if (body.operation?.state === \"noop\") out.log(`${body.app?.appId}: already active`);\n else out.log(`${body.app?.appId}: restored — every service's data plane is live again`);\n}\n\n/** Dispatch `odla-ai app <archive|restore|export>` from the parsed argv. */\nexport async function appCommand(\n parsed: ParsedArgv,\n dependencies: { fetch?: typeof fetch; stdout?: Pick<typeof console, \"log\" | \"error\"> } = {},\n): Promise<void> {\n const sub = parsed.positionals[1];\n if (sub === \"export\") {\n assertArgs(parsed, [\"config\", \"env\", \"token\", \"email\", \"fresh\", \"out\", \"json\"], 2);\n await appExport({\n configPath: stringOpt(parsed.options.config) ?? \"odla.config.mjs\",\n env: stringOpt(parsed.options.env),\n token: stringOpt(parsed.options.token),\n email: stringOpt(parsed.options.email),\n fresh: parsed.options.fresh === true,\n out: stringOpt(parsed.options.out),\n json: parsed.options.json === true,\n fetch: dependencies.fetch,\n stdout: dependencies.stdout,\n });\n return;\n }\n if (sub !== \"archive\" && sub !== \"restore\") {\n throw new Error(\n `unknown app subcommand \"${sub ?? \"\"}\". Try \"odla-ai app archive --yes\", \"odla-ai app restore\", or \"odla-ai app export\". ` +\n \"(Permanent deletion has no CLI: it requires a signed-in owner in Studio.)\",\n );\n }\n assertArgs(parsed, [\"config\", \"token\", \"email\", \"yes\", \"json\"], 2);\n const options: AppLifecycleOptions = {\n configPath: stringOpt(parsed.options.config) ?? \"odla.config.mjs\",\n token: stringOpt(parsed.options.token),\n email: stringOpt(parsed.options.email),\n yes: parsed.options.yes === true,\n json: parsed.options.json === true,\n fetch: dependencies.fetch,\n stdout: dependencies.stdout,\n };\n if (sub === \"archive\") await appArchive(options);\n else await appRestore(options);\n}\n","/** Stable, machine-readable division of work between the CLI, coding agent,\n * human operator, and Studio. Printed by `odla-ai capabilities --json`. */\nexport const CAPABILITIES = {\n cli: [\n \"start an email-bound device request without accepting a password or user session token\",\n \"register the app and enable configured services per environment\",\n \"issue, persist, and explicitly rotate configured service credentials\",\n \"write local Worker values and push deployed Worker secrets through Wrangler stdin\",\n \"store tenant-vault secrets (including the Clerk webhook secret and reserved Clerk secret key) write-only from stdin or an env var\",\n \"push db schema/rules and configure platform AI, auth, and deployment links\",\n \"apply Google Calendar booking config, then drive state-bound consent, status, discovery, and disconnect flows (bookings run live through the platform proxy)\",\n \"validate config offline and smoke-test a provisioned db environment\",\n \"run app-attributed hosted security discovery and independent validation without provider keys\",\n \"connect/revoke source-read-only GitHub sources and drive commit-pinned hosted security jobs without PATs or provider keys\",\n \"let admins manage system AI policy and credentials, inspect attributed usage, and read immutable admin changes through separate short-lived capability-only approvals\",\n ],\n agent: [\n \"install and import the selected odla SDKs\",\n \"wrap the Worker with withObservability and choose useful telemetry\",\n \"make application-specific schema, rules, auth, UI, and migration decisions\",\n \"wire @odla-ai/calendar into trusted Worker code and keep the app admin key out of browsers\",\n ],\n human: [\n \"provide the existing odla account email, then sign in and explicitly review/approve the exact device code\",\n \"review mirrored calendar/attendee disclosure and complete the server-issued Google consent flow\",\n \"consent to production changes with --yes\",\n \"request destructive credential rotation explicitly\",\n \"review application semantics, security findings, releases, and merges\",\n \"approve redacted-source disclosure before hosted security reasoning\",\n \"approve GitHub App repository access separately from redacted-snippet disclosure\",\n ],\n studio: [\n \"view telemetry and environment state\",\n \"let signed-in users inventory/revoke their own agent grants and admins audit/global-revoke them\",\n \"review calendar connection, granted read scope, selected calendars, and sync health without exposing provider tokens\",\n \"perform manual credential recovery when the CLI's local shown-once copy is unavailable\",\n \"configure system AI purposes and view app/environment/run-attributed usage\",\n \"connect/revoke GitHub security sources and inspect ref-to-SHA jobs, routes, retention, coverage, and normalized reports\",\n ],\n} as const;\n\ntype Output = Pick<typeof console, \"log\">;\n\n/** Print the stable responsibility boundary for humans or agent tooling. */\nexport function printCapabilities(json = false, out: Output = console): void {\n if (json) {\n out.log(JSON.stringify(CAPABILITIES, null, 2));\n return;\n }\n out.log(\"odla-ai responsibility boundary\\n\");\n printGroup(out, \"CLI automates\", CAPABILITIES.cli);\n printGroup(out, \"Coding agent changes source\", CAPABILITIES.agent);\n printGroup(out, \"Human checkpoints\", CAPABILITIES.human);\n printGroup(out, \"Studio\", CAPABILITIES.studio);\n}\n\nfunction printGroup(out: Output, heading: string, items: readonly string[]): void {\n out.log(`${heading}:`);\n for (const item of items) out.log(` - ${item}`);\n out.log(\"\");\n}\n","const PLATFORM_NOT_READY_CODES = new Set([\n \"calendar_google_oauth_not_configured\",\n \"calendar_token_vault_not_configured\",\n // Current spelling (booking-era key verifier) plus the retired mirror-era\n // ingress code, so the CLI stays resumable against either platform version.\n \"calendar_db_verifier_not_configured\",\n \"calendar_db_ingress_not_configured\",\n]);\n\n/**\n * Calendar registry request that completed with a non-2xx response. Preserves\n * the HTTP status and the platform's machine-readable `error.code` so callers\n * can branch on the code instead of parsing the redacted message.\n */\nexport class CalendarRequestError extends Error {\n /** HTTP status returned by the registry. */\n readonly status: number;\n /** Machine-readable `error.code` from the response body, when present. */\n readonly code?: string;\n\n constructor(message: string, status: number, code?: string) {\n super(message);\n this.name = \"CalendarRequestError\";\n this.status = status;\n if (code !== undefined) this.code = code;\n }\n}\n\n/**\n * True when the error is the platform reporting that its own calendar\n * connector is not yet configured (Google OAuth client, token vault, or DB\n * ingress). Only a platform operator can fix these, so provision reports them\n * as a resumable warning instead of aborting. Matches on the error code, not\n * the HTTP status — the code is the contract.\n */\nexport function isCalendarPlatformNotReady(error: unknown): error is CalendarRequestError & { code: string } {\n return error instanceof CalendarRequestError && error.code !== undefined && PLATFORM_NOT_READY_CODES.has(error.code);\n}\n","/**\n * Secret redaction shared by every command's output path and by doctor's\n * \"does this value look like a secret\" checks. Clerk publishable keys\n * (pk_test_/pk_live_) are public by design and are deliberately not matched.\n */\nconst REPLACEMENTS: Array<[RegExp, string]> = [\n [/odla_(sk|dev)_[A-Za-z0-9._-]+/g, \"odla_$1_[redacted]\"],\n [/\\bsk_(live|test)_[A-Za-z0-9]+/g, \"sk_$1_[redacted]\"],\n [/\\bsk-[A-Za-z0-9._-]+/g, \"sk-[redacted]\"],\n [/\\bwhsec_[A-Za-z0-9+/=]+/g, \"whsec_[redacted]\"],\n [/\\bo11y_[A-Za-z0-9]+/g, \"o11y_[redacted]\"],\n [/\\b(ghp|gho|github_pat)_[A-Za-z0-9_]+/g, \"$1_[redacted]\"],\n [/\\bAKIA[A-Z0-9]{12,}/g, \"AKIA[redacted]\"],\n];\n\n/**\n * Return `value` with every secret-shaped substring replaced by a `[redacted]`\n * placeholder that keeps the identifying prefix (e.g. `sk_live_[redacted]`).\n * Matches odla db keys (`odla_sk_`/`odla_dev_`), Clerk secret keys\n * (`sk_live_`/`sk_test_`), OpenAI keys (`sk-`), webhook signing secrets\n * (`whsec_`), o11y tokens (`o11y_`), GitHub tokens (`ghp_`/`gho_`/`github_pat_`),\n * and AWS access-key ids (`AKIA…`). Clerk publishable keys (`pk_test_`/\n * `pk_live_`) are public by design and intentionally left untouched. Used to\n * sanitize anything the CLI echoes (notably network error bodies) before it\n * reaches stdout/stderr. Non-matching input is returned unchanged.\n */\nexport function redactSecrets(value: string): string {\n let result = value;\n for (const [pattern, replacement] of REPLACEMENTS) result = result.replace(pattern, replacement);\n return result;\n}\n\n/** True when a value matches any known secret shape (used for detection, never display). */\nexport function looksSecret(value: string): boolean {\n return redactSecrets(value) !== value || value.includes(\"-----BEGIN\");\n}\n","import { CalendarRequestError } from \"./calendar-errors\";\nimport { redactSecrets } from \"./redact\";\nimport { platformAudience } from \"./token\";\n\nexport const CALENDAR_STATES = [\n \"not_connected\", \"authorizing\", \"healthy\", \"degraded\", \"disconnected\", \"failed\",\n] as const;\n/** Connection lifecycle reported by the registry; mirrors the platform's\n * calendar states. `degraded` means connected but re-consent is required. */\nexport type CalendarConnectionState = (typeof CALENDAR_STATES)[number];\n\n/** Owner-visible, secret-free calendar connection health. */\nexport interface CalendarStatus {\n env: string;\n enabled: boolean;\n /** True when the platform has provider credentials for this connection. */\n connected: boolean;\n /** True when the grant covers booking writes; false means reconnect. */\n writable: boolean;\n provider: \"google\" | null;\n status: CalendarConnectionState;\n access?: \"book\";\n /** Calendar that receives created bookings. */\n bookingCalendarId?: string;\n /** Calendars consulted for FreeBusy availability. */\n calendars: string[];\n bookingPageUrl?: string | null;\n grantedScopes: string[];\n attemptId?: string;\n error?: { code?: string; message?: string };\n}\n\nexport interface CalendarHttpContext {\n platform: string;\n appId: string;\n env: string;\n token: string;\n fetch?: typeof fetch;\n}\n\nexport interface CalendarConnectionAttempt {\n attemptId: string;\n consentUrl: string;\n expiresAt: number;\n}\n\n/** One Google calendar the connected identity may select for mirroring. */\nexport interface AvailableGoogleCalendar {\n id: string;\n summary?: string;\n primary?: boolean;\n selected?: boolean;\n accessRole?: \"freeBusyReader\" | \"reader\" | \"writer\" | \"owner\";\n}\n\nexport async function readCalendarStatus(ctx: CalendarHttpContext): Promise<CalendarStatus> {\n return parseCalendarStatus(await calendarJson(ctx, \"\", {}), ctx.env);\n}\n\nexport async function discoverGoogleCalendars(ctx: CalendarHttpContext): Promise<AvailableGoogleCalendar[]> {\n const raw = await calendarJson(ctx, \"/calendars\", {});\n const value = record(raw);\n if (!value || !Array.isArray(value.calendars)) throw new Error(\"calendar discovery returned an invalid response\");\n return value.calendars.map((item, index) => {\n const calendar = record(item);\n const id = textField(calendar?.id, 1_024);\n if (!calendar || !id) throw new Error(`calendar discovery returned an invalid calendar at index ${index}`);\n const role = calendar.accessRole;\n if (role !== undefined && role !== \"freeBusyReader\" && role !== \"reader\" && role !== \"writer\" && role !== \"owner\") {\n throw new Error(`calendar discovery returned an invalid access role at index ${index}`);\n }\n return {\n id,\n ...optionalText(\"summary\", calendar.summary, 500),\n ...(typeof calendar.primary === \"boolean\" ? { primary: calendar.primary } : {}),\n ...(typeof calendar.selected === \"boolean\" ? { selected: calendar.selected } : {}),\n ...(typeof role === \"string\" ? { accessRole: role } : {}),\n };\n });\n}\n\nexport async function applyCalendarSettings(ctx: CalendarHttpContext, bookingPageUrl: string | null): Promise<CalendarStatus> {\n return parseCalendarStatus(await calendarJson(ctx, \"\", { method: \"PUT\", body: JSON.stringify({ bookingPageUrl }) }), ctx.env);\n}\n\nexport async function startCalendarConnection(ctx: CalendarHttpContext): Promise<CalendarConnectionAttempt> {\n const raw = await calendarJson(ctx, \"/google/connect\", { method: \"POST\", body: \"{}\" });\n const value = wrapped(raw, \"attempt\");\n const attemptId = textField(value.attemptId, 180);\n const consentUrl = textField(value.consentUrl, 4_096);\n const expiresAt = timestamp(value.expiresAt);\n if (!attemptId || !consentUrl || expiresAt === undefined) throw new Error(\"calendar connect returned an invalid attempt\");\n return { attemptId, consentUrl, expiresAt };\n}\n\nexport async function pollCalendarConnection(ctx: CalendarHttpContext, attemptId: string): Promise<CalendarStatus> {\n return parseCalendarStatus(\n await calendarJson(ctx, `/google/connect/${encodeURIComponent(identifier(attemptId, \"attemptId\"))}`, {}),\n ctx.env,\n );\n}\n\nexport async function requestCalendarDisconnect(ctx: CalendarHttpContext): Promise<CalendarStatus> {\n return parseCalendarStatus(\n await calendarJson(ctx, \"/disconnect\", { method: \"POST\", body: JSON.stringify({ purge: false }) }),\n ctx.env,\n );\n}\n\nexport function parseCalendarStatus(raw: unknown, env: string): CalendarStatus {\n const outer = wrapped(raw, \"calendar\");\n const value = record(outer.attempt) ?? record(outer.status) ?? outer;\n const connection = record(value.connection) ?? {};\n const config = record(value.config) ?? record(outer.config) ?? {};\n const googleConfig = record(config.google) ?? config;\n const stateValue = calendarState(value.status ?? value.state ?? connection.status ?? connection.state);\n if (!stateValue) {\n throw new Error(\"calendar status returned an invalid connection state\");\n }\n const providerValue = value.provider ?? connection.provider ?? config.provider ?? (config.google ? \"google\" : undefined);\n if (providerValue !== undefined && providerValue !== null && providerValue !== \"google\") {\n throw new Error(\"calendar status returned an unsupported provider\");\n }\n const accessValue = value.access ?? connection.access ?? config.access ?? googleConfig.access;\n // \"read\" is the retired mirror's spelling; the live registry reports \"book\".\n if (accessValue !== undefined && accessValue !== \"book\" && accessValue !== \"read\") {\n throw new Error(\"calendar status returned unsupported access\");\n }\n const errorValue = record(value.error) ?? record(connection.error);\n const errorCode = textField(value.lastErrorCode, 128);\n const bookingPageValue = Object.hasOwn(value, \"bookingPageUrl\")\n ? value.bookingPageUrl\n : Object.hasOwn(config, \"bookingPageUrl\") ? config.bookingPageUrl : googleConfig.bookingPageUrl;\n const connected = typeof (value.connected ?? connection.connected) === \"boolean\"\n ? Boolean(value.connected ?? connection.connected)\n : [\"healthy\", \"degraded\"].includes(stateValue);\n const bookingCalendarId = textField(value.bookingCalendarId ?? config.bookingCalendarId, 1_024);\n return {\n env,\n enabled: typeof value.enabled === \"boolean\" ? value.enabled : true,\n connected,\n writable: typeof value.writable === \"boolean\" ? value.writable : stateValue === \"healthy\",\n provider: providerValue === \"google\" ? \"google\" : null,\n status: stateValue,\n ...(accessValue !== undefined ? { access: \"book\" as const } : {}),\n ...(bookingCalendarId ? { bookingCalendarId } : {}),\n calendars: calendarIds(\n value.availabilityCalendars ?? config.availabilityCalendars\n ?? value.configuredCalendars ?? value.calendars ?? config.calendars ?? googleConfig.calendars,\n ),\n ...optionalNullableUrl(\"bookingPageUrl\", bookingPageValue),\n grantedScopes: stringList(value.grantedScopes ?? connection.grantedScopes ?? connection.scopes),\n ...optionalText(\"attemptId\", value.attemptId ?? connection.attemptId, 180),\n ...(errorValue || errorCode ? { error: {\n ...(textField(errorValue?.code, 128) ? { code: textField(errorValue?.code, 128) } : {}),\n ...(textField(errorValue?.message, 500) ? { message: textField(errorValue?.message, 500) } : {}),\n ...(!errorValue && errorCode ? { code: errorCode } : {}),\n } } : {}),\n };\n}\n\nfunction calendarState(value: unknown): CalendarConnectionState | null {\n if (typeof value !== \"string\") return null;\n if ((CALENDAR_STATES as readonly string[]).includes(value)) return value as CalendarConnectionState;\n const legacy: Record<string, CalendarConnectionState> = {\n disabled: \"not_connected\",\n disconnected: \"disconnected\",\n connecting: \"authorizing\",\n syncing: \"healthy\",\n needs_sync: \"healthy\",\n initial_sync: \"healthy\",\n ready: \"healthy\",\n error: \"failed\",\n };\n return legacy[value] ?? null;\n}\n\nasync function calendarJson(ctx: CalendarHttpContext, suffix: string, init: RequestInit): Promise<unknown> {\n const platform = platformAudience(ctx.platform);\n const appId = identifier(ctx.appId, \"appId\");\n const env = identifier(ctx.env, \"env\");\n const url = new URL(`/registry/apps/${encodeURIComponent(appId)}/calendar${suffix}`, platform);\n url.searchParams.set(\"env\", env);\n const token = credential(ctx.token);\n let response: Response;\n try {\n response = await (ctx.fetch ?? fetch)(url, {\n ...init,\n redirect: \"error\",\n credentials: \"omit\",\n headers: { authorization: `Bearer ${token}`, \"content-type\": \"application/json\", ...init.headers },\n });\n } catch (error) {\n throw new Error(`calendar request failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n const body = await response.json().catch(() => ({})) as { error?: { code?: unknown; message?: unknown } };\n if (!response.ok) {\n const code = textField(body.error?.code, 128);\n const message = textField(body.error?.message, 500);\n const detail = `${code ? ` ${code}` : \"\"}${message ? `: ${message}` : \"\"}`;\n throw new CalendarRequestError(redactSecrets(`calendar request failed (${response.status})${detail}`), response.status, code);\n }\n return body;\n}\n\nfunction wrapped(raw: unknown, key: string): Record<string, unknown> {\n const outer = record(raw);\n if (!outer) throw new Error(\"calendar returned an invalid response\");\n return record(outer[key]) ?? outer;\n}\n\nfunction record(value: unknown): Record<string, unknown> | null {\n return value !== null && typeof value === \"object\" && !Array.isArray(value) ? value as Record<string, unknown> : null;\n}\n\nfunction textField(value: unknown, max: number): string | undefined {\n return typeof value === \"string\" && value.length > 0 && value.length <= max && !/[\\u0000-\\u001f\\u007f]/.test(value) ? value : undefined;\n}\n\nfunction stringList(value: unknown): string[] {\n return Array.isArray(value) ? [...new Set(value.filter((item): item is string => !!textField(item, 4_096)))] : [];\n}\n\nfunction calendarIds(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return [...new Set(value.flatMap((item) => {\n if (typeof item === \"string\") return textField(item, 4_096) ? [item] : [];\n const calendar = record(item);\n const id = textField(calendar?.id, 4_096);\n return id && calendar?.selected !== false ? [id] : [];\n }))];\n}\n\nfunction timestamp(value: unknown): number | undefined {\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) return value;\n if (typeof value === \"string\") {\n const parsed = Date.parse(value);\n if (Number.isFinite(parsed)) return parsed;\n }\n return undefined;\n}\n\nfunction optionalText<K extends string>(key: K, value: unknown, max: number): { [P in K]?: string } {\n const parsed = textField(value, max);\n return parsed ? { [key]: parsed } as { [P in K]?: string } : {};\n}\n\n\n\nfunction optionalNullableUrl<K extends string>(key: K, value: unknown): { [P in K]?: string | null } {\n if (value === null) return { [key]: null } as { [P in K]?: string | null };\n const parsed = textField(value, 4_096);\n return parsed ? { [key]: parsed } as { [P in K]?: string | null } : {};\n}\n\nfunction identifier(value: string, name: string): string {\n if (typeof value !== \"string\" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,179}$/.test(value)) throw new Error(`${name} is invalid`);\n return value;\n}\n\nfunction credential(value: string): string {\n if (typeof value !== \"string\" || value.length < 8 || value.length > 8_192 || /\\s|[\\u0000-\\u001f\\u007f]/.test(value)) {\n throw new Error(\"calendar requires an odla developer token\");\n }\n return value;\n}\n","/** Abort-aware delay shared by new-attempt and existing-sync polling. */\nexport async function waitForCalendarPoll(milliseconds: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) throw signal.reason ?? new Error(\"calendar connection aborted\");\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(resolve, milliseconds);\n signal?.addEventListener(\"abort\", () => {\n clearTimeout(timer);\n reject(signal.reason ?? new Error(\"calendar connection aborted\"));\n }, { once: true });\n });\n}\n","import { calendarBookingPageUrl, calendarServiceConfig, loadProjectConfig } from \"./config\";\nimport {\n applyCalendarSettings,\n discoverGoogleCalendars,\n pollCalendarConnection,\n readCalendarStatus,\n requestCalendarDisconnect,\n startCalendarConnection,\n} from \"./calendar-http\";\nimport type { CalendarHttpContext, CalendarStatus } from \"./calendar-http\";\nimport type { AvailableGoogleCalendar } from \"./calendar-http\";\nimport { waitForCalendarPoll } from \"./calendar-poll\";\nimport { openUrl } from \"./open\";\nimport { approvalBrowser, getDeveloperToken, platformAudience } from \"./token\";\n\n/** Shared inputs for the calendar lifecycle commands (status, connect,\n * calendars, disconnect): the project config path and env, plus injectable\n * token, output, browser, clock, and polling hooks so agents and tests can\n * drive the flow deterministically. */\nexport interface CalendarLifecycleOptions {\n /** Path to the checked-in odla project config. */ configPath: string;\n /** Configured environment; defaults to dev when present. */ env?: string;\n /** Existing developer-token override. */ token?: string;\n /** Existing odla account email used only for a fresh handshake. */ email?: string;\n open?: boolean; yes?: boolean; json?: boolean;\n fetch?: typeof fetch; stdout?: Pick<typeof console, \"log\" | \"error\">;\n openConsentUrl?: (url: string) => Promise<void>;\n wait?: (milliseconds: number, signal?: AbortSignal) => Promise<void>;\n pollTimeoutMs?: number; now?: () => number; signal?: AbortSignal;\n}\n\n/** Read the owner-visible Google connection and booking health for one env. */\nexport async function calendarStatus(options: CalendarLifecycleOptions): Promise<CalendarStatus> {\n const { ctx, out } = await lifecycleContext(options);\n const status = await readCalendarStatus(ctx);\n printStatus(status, options.json === true, out);\n return status;\n}\n\n/** List calendars visible to the connected Google identity for config authoring. */\nexport async function calendarCalendars(options: CalendarLifecycleOptions): Promise<AvailableGoogleCalendar[]> {\n const { ctx, out } = await lifecycleContext(options);\n const calendars = await discoverGoogleCalendars(ctx);\n if (options.json) out.log(JSON.stringify({ env: ctx.env, calendars }, null, 2));\n else if (calendars.length === 0) out.log(`${ctx.env}: no Google calendars available`);\n else for (const calendar of calendars) {\n out.log(`${calendar.selected ? \"✓\" : calendar.primary ? \"*\" : \" \"} ${calendar.id}${calendar.summary ? ` — ${calendar.summary}` : \"\"}${calendar.accessRole ? ` (${calendar.accessRole})` : \"\"}`);\n }\n return calendars;\n}\n\n/** Apply the optional booking-page setting, then complete Google consent.\n * A connection whose grant predates booking scopes (`degraded`) re-runs\n * consent so the platform can create events and read FreeBusy. */\nexport async function calendarConnect(options: CalendarLifecycleOptions): Promise<CalendarStatus> {\n const { cfg, ctx, out } = await lifecycleContext(options);\n productionConsent(ctx.env, options.yes, \"connect calendar\");\n const page = calendarBookingPageUrl(cfg, ctx.env);\n const applied = page === undefined ? await readCalendarStatus(ctx) : await applyCalendarSettings(ctx, page);\n const connectOptions = connectionOptions(options, out);\n return await continueConnectedCalendar(ctx, applied, connectOptions)\n ?? connectWithContext(ctx, connectOptions);\n}\n\n/** Provision applies public embed/link configuration through the owner route. */\nexport async function applyCalendarBookingPage(\n ctx: CalendarHttpContext,\n bookingPageUrl: string | null | undefined,\n out: Pick<typeof console, \"log\">,\n): Promise<CalendarStatus | null> {\n if (bookingPageUrl === undefined) return null;\n const status = await applyCalendarSettings(ctx, bookingPageUrl);\n out.log(`${ctx.env}: calendar booking page ${bookingPageUrl ? \"set\" : \"cleared\"}`);\n return status;\n}\n\n/** Delete this connection's encrypted platform tokens. No calendar data is\n * stored anywhere, so there is nothing else to clean up; the shared Google\n * project grant is not revoked. */\nexport async function calendarDisconnect(options: CalendarLifecycleOptions): Promise<CalendarStatus> {\n if (!options.yes) throw new Error('calendar disconnect requires --yes');\n const { ctx, out } = await lifecycleContext(options);\n const status = await requestCalendarDisconnect(ctx);\n out.log(`${ctx.env}: calendar disconnected; no calendar data was stored`);\n return status;\n}\n\n/** Provision's idempotent connection phase after service enablement/config apply. */\nexport async function ensureCalendarConnected(\n ctx: CalendarHttpContext,\n options: Omit<CalendarLifecycleOptions, \"configPath\" | \"env\" | \"token\" | \"fetch\">,\n): Promise<CalendarStatus> {\n const out = options.stdout ?? console;\n const current = await readCalendarStatus(ctx);\n const connectOptions = connectionOptions(options, out);\n return await continueConnectedCalendar(ctx, current, connectOptions)\n ?? connectWithContext(ctx, connectOptions);\n}\n\nasync function lifecycleContext(options: CalendarLifecycleOptions): Promise<{\n cfg: Awaited<ReturnType<typeof loadProjectConfig>>;\n ctx: CalendarHttpContext;\n out: Pick<typeof console, \"log\" | \"error\">;\n}> {\n const cfg = await loadProjectConfig(options.configPath);\n if (!cfg.services.includes(\"calendar\")) throw new Error('calendar service is not enabled in config services');\n const env = options.env ?? (cfg.envs.includes(\"dev\") ? \"dev\" : cfg.envs[0]);\n if (!env || !cfg.envs.includes(env)) throw new Error(`env \"${env ?? \"\"}\" is not declared in ${options.configPath}`);\n // Resolving this also asserts that the authored Google block covers the env.\n calendarServiceConfig(cfg, env);\n const out = options.stdout ?? console;\n const doFetch = options.fetch ?? fetch;\n const token = await getDeveloperToken(\n cfg,\n {\n configPath: cfg.configPath,\n token: options.token,\n email: options.email,\n open: options.open,\n openApprovalUrl: options.openConsentUrl,\n },\n doFetch,\n out,\n );\n return { cfg, ctx: { platform: cfg.platformUrl, appId: cfg.app.id, env, token, fetch: doFetch }, out };\n}\n\nfunction connectionOptions(\n options: Pick<CalendarLifecycleOptions, \"open\" | \"openConsentUrl\" | \"wait\" | \"pollTimeoutMs\" | \"now\" | \"signal\">,\n out: Pick<typeof console, \"log\" | \"error\">,\n): ConnectContextOptions {\n const browser = approvalBrowser({ open: options.open });\n return {\n out,\n open: browser.open,\n openConsentUrl: options.openConsentUrl,\n wait: options.wait,\n pollTimeoutMs: options.pollTimeoutMs,\n now: options.now,\n signal: options.signal,\n };\n}\n\ninterface ConnectContextOptions {\n out: Pick<typeof console, \"log\" | \"error\">;\n open: boolean;\n openConsentUrl?: (url: string) => Promise<void>;\n wait?: (milliseconds: number, signal?: AbortSignal) => Promise<void>;\n pollTimeoutMs?: number;\n now?: () => number;\n signal?: AbortSignal;\n}\n\n/** Reuse an installed, writable connection; anything else falls through to a\n * fresh Google consent. `degraded` (connected but not writable — a grant from\n * the retired read-only era) always re-consents: the booking proxy cannot act\n * until the owner grants the events + freebusy scopes. */\nasync function continueConnectedCalendar(\n ctx: CalendarHttpContext,\n current: CalendarStatus,\n options: ConnectContextOptions,\n): Promise<CalendarStatus | null> {\n if (current.status === \"healthy\") {\n options.out.log(`${ctx.env}: calendar already connected (healthy)`);\n return current;\n }\n if (current.status === \"degraded\") {\n options.out.log(`${ctx.env}: calendar grant predates booking scopes — Google re-consent required`);\n return null;\n }\n if (current.status === \"failed\" && current.connected) {\n const reason = current.error?.message ?? current.error?.code;\n throw new Error(`calendar connection failed${reason ? `: ${reason}` : \"\"}; inspect status and reconnect explicitly`);\n }\n if (current.status !== \"authorizing\") return null;\n\n // Another operator's consent is mid-flight; follow it instead of racing it.\n const now = options.now ?? Date.now;\n const deadline = now() + pollTimeout(options.pollTimeoutMs);\n const wait = options.wait ?? waitForCalendarPoll;\n let prior = \"\";\n while (now() < deadline) {\n if (options.signal?.aborted) throw options.signal.reason ?? new Error(\"calendar connection aborted\");\n const status = await readCalendarStatus(ctx);\n if (status.status !== prior) {\n options.out.log(`${ctx.env}: calendar ${status.status.replaceAll(\"_\", \" \")}`);\n prior = status.status;\n }\n if (status.status === \"healthy\") return status;\n if (status.status === \"degraded\") return null;\n if (status.status === \"failed\" && status.connected) {\n const reason = status.error?.message ?? status.error?.code;\n throw new Error(`calendar connection failed${reason ? `: ${reason}` : \"\"}; inspect status and reconnect explicitly`);\n }\n if (status.status !== \"authorizing\") return null;\n await wait(Math.min(2_000, Math.max(0, deadline - now())), options.signal);\n }\n throw new Error('Existing Google Calendar authorization timed out; run \"odla-ai calendar status\" and retry');\n}\n\nasync function connectWithContext(ctx: CalendarHttpContext, options: ConnectContextOptions): Promise<CalendarStatus> {\n const attempt = await startCalendarConnection(ctx);\n const consentUrl = trustedCalendarConsentUrl(ctx.platform, attempt.consentUrl);\n options.out.log(`${ctx.env}: Google Calendar consent: ${consentUrl}`);\n if (options.open) {\n await (options.openConsentUrl ?? openUrl)(consentUrl);\n options.out.log(`${ctx.env}: opened Google Calendar consent in your browser`);\n }\n const now = options.now ?? Date.now;\n const timeout = pollTimeout(options.pollTimeoutMs);\n const deadline = Math.min(attempt.expiresAt, now() + timeout);\n const wait = options.wait ?? waitForCalendarPoll;\n let prior = \"\";\n while (now() < deadline) {\n if (options.signal?.aborted) throw options.signal.reason ?? new Error(\"calendar connection aborted\");\n const status = await pollCalendarConnection(ctx, attempt.attemptId);\n if (status.status !== prior) {\n options.out.log(`${ctx.env}: calendar ${status.status.replaceAll(\"_\", \" \")}`);\n prior = status.status;\n }\n if (status.status === \"healthy\") return status;\n if (status.status === \"degraded\") {\n throw new Error(\"calendar connected without booking scopes; re-run connect and grant calendar access\");\n }\n if (status.status === \"failed\" || status.status === \"disconnected\" || status.status === \"not_connected\") {\n const reason = status.error?.message ?? status.error?.code;\n throw new Error(`calendar connection ${status.status}${reason ? `: ${reason}` : \"\"}`);\n }\n await wait(Math.min(2_000, Math.max(0, deadline - now())), options.signal);\n }\n throw new Error('Google Calendar consent timed out; run \"odla-ai calendar status\" and retry connect');\n}\n\nexport function trustedCalendarConsentUrl(platform: string, value: string): string {\n const origin = platformAudience(platform);\n let url: URL;\n try { url = value.startsWith(\"/\") ? new URL(value, origin) : new URL(value); } catch { throw new Error(\"odla.ai returned an invalid calendar consent URL\"); }\n const platformPage = url.origin === origin;\n const googlePage = url.origin === \"https://accounts.google.com\" && url.pathname === \"/o/oauth2/v2/auth\";\n if ((!platformPage && !googlePage) || url.username || url.password || url.hash) {\n throw new Error(\"odla.ai returned an untrusted calendar consent URL\");\n }\n return url.toString();\n}\n\nfunction pollTimeout(value = 10 * 60_000): number {\n if (!Number.isSafeInteger(value) || value < 1_000 || value > 60 * 60_000) throw new Error(\"calendar poll timeout must be 1000-3600000ms\");\n return value;\n}\n\nexport { waitForCalendarPoll } from \"./calendar-poll\";\n\nfunction productionConsent(env: string, yes: boolean | undefined, action: string): void {\n if ((env === \"prod\" || env === \"production\") && !yes) throw new Error(`refusing to ${action} for \"${env}\" without --yes`);\n}\n\nfunction printStatus(status: CalendarStatus, json: boolean, out: Pick<typeof console, \"log\">): void {\n if (json) {\n out.log(JSON.stringify(status, null, 2));\n return;\n }\n out.log(`calendar: ${status.provider ?? \"none\"}/${status.status} (${status.env})`);\n out.log(` bookable: ${status.writable ? \"yes\" : status.connected ? \"no — reconnect to grant booking scopes\" : \"no — not connected\"}`);\n if (status.bookingCalendarId) out.log(` booking calendar: ${status.bookingCalendarId}`);\n out.log(` availability calendars: ${status.calendars.length ? status.calendars.join(\", \") : \"none\"}`);\n if (status.bookingPageUrl !== undefined) out.log(` booking page: ${status.bookingPageUrl ?? \"not configured\"}`);\n if (status.error?.code || status.error?.message) out.log(` error: ${status.error.code ?? \"error\"}${status.error.message ? ` — ${status.error.message}` : \"\"}`);\n}\n","import { execFileSync } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { looksSecret } from \"./redact\";\nimport { gitignoreEntry } from \"./local\";\nimport { findWranglerConfig, readWranglerConfig } from \"./wrangler\";\nimport type { AppRules } from \"./types\";\n\n/**\n * Rules lint: a literal \"true\" grants the action to every client. `view` may\n * be deliberate for public content — allowlist those namespaces via\n * `db.publicRead`; writes are never safely \"true\".\n */\nexport function lintRules(rules: AppRules | undefined, entities: string[], publicRead: string[]): string[] {\n const warnings: string[] = [];\n if (!rules) return warnings;\n for (const [ns, actions] of Object.entries(rules)) {\n for (const [action, expr] of Object.entries(actions)) {\n if (typeof expr !== \"string\" || expr.trim() !== \"true\") continue;\n if (action === \"view\" && publicRead.includes(ns)) continue;\n warnings.push(\n action === \"view\"\n ? `rules.${ns}.view is \"true\" — public read; add \"${ns}\" to db.publicRead if intended`\n : `rules.${ns}.${action} is \"true\" — any client can ${action} ${ns} rows`,\n );\n }\n }\n for (const entity of entities) {\n if (!(entity in rules)) warnings.push(`schema entity \"${entity}\" has no rules entry (all client access denied)`);\n }\n return warnings;\n}\n\nexport type ExecLike = (cmd: string, args: string[], cwd: string) => string;\n\nconst defaultExec: ExecLike = (cmd, args, cwd) => execFileSync(cmd, args, { cwd, encoding: \"utf8\", stdio: [\"ignore\", \"pipe\", \"ignore\"] });\n\n/** Credential files that must never be committed. Silent when git is absent. */\nexport function trackedSecretFiles(rootDir: string, exec: ExecLike = defaultExec, localPaths: string[] = []): string[] {\n let output: string;\n try {\n const custom = localPaths\n .map((path) => gitignoreEntry(rootDir, path))\n .filter((path): path is string => !!path);\n output = exec(\"git\", [\"ls-files\", \"--\", \".dev.vars\", \".odla\", ...custom], rootDir);\n } catch {\n return [];\n }\n return output\n .split(/\\r?\\n/)\n .filter(Boolean)\n .map((path) => `${path} is tracked by git — run \"git rm --cached ${path}\" and commit; it belongs in .gitignore`);\n}\n\n/** Wrangler config sanity: the assets-dir footgun, secret-looking vars. */\nexport function wranglerWarnings(rootDir: string): string[] {\n const configPath = findWranglerConfig(rootDir);\n if (!configPath) return [];\n const config = readWranglerConfig(configPath);\n if (!config) return [];\n\n const warnings: string[] = [];\n const blocks: Array<{ label: string; block: Record<string, unknown> }> = [{ label: \"\", block: config }];\n const envs = config.env;\n if (envs && typeof envs === \"object\") {\n for (const [name, block] of Object.entries(envs as Record<string, unknown>)) {\n if (block && typeof block === \"object\") blocks.push({ label: `env.${name}.`, block: block as Record<string, unknown> });\n }\n }\n\n for (const { label, block } of blocks) {\n const assets = block.assets as { directory?: string } | undefined;\n if (assets?.directory) {\n const dir = resolve(rootDir, assets.directory);\n if (dir === resolve(rootDir)) {\n warnings.push(`${label}assets.directory is the project root — point it at a dedicated build dir (wrangler dev fails with \"spawn EBADF\")`);\n } else if (existsSync(join(dir, \"node_modules\"))) {\n warnings.push(`${label}assets.directory contains node_modules — wrangler dev's watcher will exhaust file descriptors`);\n }\n }\n const vars = block.vars;\n if (vars && typeof vars === \"object\") {\n for (const [name, value] of Object.entries(vars as Record<string, unknown>)) {\n if (name === \"ODLA_API_KEY\" || name === \"ODLA_O11Y_TOKEN\" || (typeof value === \"string\" && looksSecret(value))) {\n warnings.push(`wrangler ${label}vars.${name} looks like a secret — use \"odla-ai secrets push\" / wrangler secret put, never vars`);\n }\n }\n }\n }\n\n const pkg = readPackageJson(rootDir);\n if (pkg && typeof pkg.scripts === \"object\" && pkg.scripts && \"deploy\" in (pkg.scripts as Record<string, unknown>)) {\n warnings.push(`package.json has a script named \"deploy\" — CI may auto-deploy it; rename to deploy:app`);\n }\n return warnings;\n}\n\n/** Offline checks for the source/config work that provisioning cannot infer\n * safely. The CLI owns control-plane enablement and secret delivery; these\n * warnings keep the remaining application edits visible instead of letting a\n * successfully provisioned but uninstrumented Worker look complete. */\nexport function o11yProjectWarnings(rootDir: string): string[] {\n const warnings: string[] = [];\n const pkg = readPackageJson(rootDir);\n const dependencies = pkg?.dependencies as Record<string, unknown> | undefined;\n const devDependencies = pkg?.devDependencies as Record<string, unknown> | undefined;\n if (!dependencies?.[\"@odla-ai/o11y\"]) {\n warnings.push(\n devDependencies?.[\"@odla-ai/o11y\"]\n ? \"@odla-ai/o11y is a devDependency — move it to dependencies so the Worker can import it\"\n : 'Worker instrumentation is missing @odla-ai/o11y — install it and wrap the handler with \"withObservability\"',\n );\n }\n\n const configPath = findWranglerConfig(rootDir);\n const config = configPath ? readWranglerConfig(configPath) : null;\n if (!configPath || !config) {\n warnings.push(\"cannot verify o11y Worker instrumentation — add a parseable wrangler.jsonc/json config\");\n return warnings;\n }\n\n const main = typeof config.main === \"string\" ? resolve(rootDir, config.main) : null;\n if (!main || !existsSync(main)) {\n warnings.push(\"cannot verify o11y Worker instrumentation — wrangler main is missing or unreadable\");\n } else {\n let source = \"\";\n try {\n source = readFileSync(main, \"utf8\");\n } catch {\n // The warning below is intentionally the same for an unreadable source.\n }\n if (!/\\bwithObservability\\b/.test(source)) {\n warnings.push(`wrangler entrypoint ${config.main as string} does not reference withObservability`);\n }\n }\n\n const flags = Array.isArray(config.compatibility_flags) ? config.compatibility_flags : [];\n if (!flags.includes(\"nodejs_compat\")) {\n warnings.push('wrangler compatibility_flags is missing \"nodejs_compat\" required by @odla-ai/o11y');\n }\n return warnings;\n}\n\n/** Source-side calendar SDK check. OAuth and sync health remain platform-owned. */\nexport function calendarProjectWarnings(rootDir: string): string[] {\n const pkg = readPackageJson(rootDir);\n const dependencies = pkg?.dependencies as Record<string, unknown> | undefined;\n const devDependencies = pkg?.devDependencies as Record<string, unknown> | undefined;\n if (dependencies?.[\"@odla-ai/calendar\"]) return [];\n return [\n devDependencies?.[\"@odla-ai/calendar\"]\n ? \"@odla-ai/calendar is a devDependency — move it to dependencies so trusted Worker code can import it\"\n : \"calendar service is enabled but @odla-ai/calendar is not installed in dependencies\",\n ];\n}\n\nfunction readPackageJson(rootDir: string): Record<string, unknown> | null {\n try {\n return JSON.parse(readFileSync(join(rootDir, \"package.json\"), \"utf8\")) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n","import { spawn } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport interface RunResult {\n code: number;\n stdout: string;\n stderr: string;\n}\n\n/** Subprocess seam: injectable in tests, `defaultRunner` in production. */\nexport type CommandRunner = (cmd: string, args: string[], opts?: { input?: string; cwd?: string }) => Promise<RunResult>;\n\nexport const defaultRunner: CommandRunner = (cmd, args, opts) =>\n new Promise((resolvePromise, reject) => {\n const child = spawn(cmd, args, { cwd: opts?.cwd, stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n let stdout = \"\";\n let stderr = \"\";\n child.stdout.on(\"data\", (chunk: Buffer) => (stdout += chunk.toString()));\n child.stderr.on(\"data\", (chunk: Buffer) => (stderr += chunk.toString()));\n child.on(\"error\", reject);\n child.on(\"close\", (code) => resolvePromise({ code: code ?? 1, stdout, stderr }));\n child.stdin.end(opts?.input ?? \"\");\n });\n\nconst WRANGLER_CONFIG_FILES = [\"wrangler.jsonc\", \"wrangler.json\", \"wrangler.toml\"];\n\nexport function findWranglerConfig(rootDir: string): string | null {\n for (const name of WRANGLER_CONFIG_FILES) {\n const path = join(rootDir, name);\n if (existsSync(path)) return path;\n }\n return null;\n}\n\n/** Parses wrangler.json/jsonc. Returns null for .toml (unparsed) or invalid JSON. */\nexport function readWranglerConfig(path: string): Record<string, unknown> | null {\n if (path.endsWith(\".toml\")) return null;\n try {\n return JSON.parse(stripJsonComments(readFileSync(path, \"utf8\"))) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\n/** Removes // and both-slash block comments without touching string contents. */\nexport function stripJsonComments(text: string): string {\n let result = \"\";\n let inString = false;\n for (let i = 0; i < text.length; i++) {\n const ch = text[i]!;\n if (inString) {\n result += ch;\n if (ch === \"\\\\\") {\n result += text[i + 1] ?? \"\";\n i++;\n } else if (ch === '\"') {\n inString = false;\n }\n continue;\n }\n if (ch === '\"') {\n inString = true;\n result += ch;\n continue;\n }\n if (ch === \"/\" && text[i + 1] === \"/\") {\n while (i < text.length && text[i] !== \"\\n\") i++;\n result += \"\\n\";\n continue;\n }\n if (ch === \"/\" && text[i + 1] === \"*\") {\n i += 2;\n while (i < text.length && !(text[i] === \"*\" && text[i + 1] === \"/\")) i++;\n i++;\n continue;\n }\n result += ch;\n }\n return result;\n}\n\nexport async function wranglerLoggedIn(run: CommandRunner, cwd: string): Promise<boolean> {\n try {\n const result = await run(\"npx\", [\"wrangler\", \"whoami\"], { cwd });\n return result.code === 0 && !/not authenticated/i.test(`${result.stdout}${result.stderr}`);\n } catch {\n return false;\n }\n}\n\n/** Pipes the value via stdin — it never appears on argv or in process listings. */\nexport function wranglerPutSecret(\n run: CommandRunner,\n opts: { name: string; value: string; env?: string; cwd: string },\n): Promise<RunResult> {\n const args = [\"wrangler\", \"secret\", \"put\", opts.name, ...(opts.env ? [\"--env\", opts.env] : [])];\n return run(\"npx\", args, { input: opts.value, cwd: opts.cwd });\n}\n","import { buildPlan, calendarBookingPageUrl, calendarServiceConfig, loadProjectConfig, resolveDataExport, rulesFromSchema, serializedEntities } from \"./config\";\nimport { calendarProjectWarnings, lintRules, o11yProjectWarnings, trackedSecretFiles, wranglerWarnings } from \"./doctor-checks\";\nimport { readCredentials } from \"./local\";\nimport type { AppRules } from \"./types\";\n\nexport interface DoctorOptions {\n configPath: string;\n stdout?: Pick<typeof console, \"log\" | \"error\">;\n}\n\n/**\n * Validate and summarize an odla project config entirely offline — no network\n * calls and no file writes. Loads `configPath`, builds the provision plan, and\n * resolves the schema and rules (synthesizing deny-all rules from the schema\n * when `db.rules` is omitted and `db.defaultRules` isn't `false`), then prints a\n * summary line for the app, envs, services, schema entity count, rules namespace\n * count, and AI provider.\n *\n * It then collects warnings for the mistakes provision can't fix silently: a\n * schema with no entities, a rules namespace with no matching entity, the `ai`\n * service enabled without an `ai.provider`, `auth.clerk` entries that reference\n * an unset env var (`$FOO`), an `ai.keyEnv` that isn't set (provider key upload\n * will be skipped), and — when `o11y` is enabled — any env whose local\n * credentials lack an ingest token. It also folds in the shared rule linter,\n * git-tracked secret-shaped files, and wrangler config warnings. Prints `ok`\n * when clean, otherwise the warning list. Purely advisory: never throws on\n * warnings and never mutates anything.\n *\n * @param options.configPath Path to the `odla.config.mjs` to inspect.\n * @param options.stdout Optional console-like sink (defaults to `console`).\n */\nexport async function doctor(options: DoctorOptions): Promise<void> {\n const out = options.stdout ?? console;\n const cfg = await loadProjectConfig(options.configPath);\n const plan = buildPlan(cfg);\n const hasDb = cfg.services.includes(\"db\");\n const schema = hasDb ? await resolveDataExport<unknown>(cfg, cfg.db?.schema, [\"schema\", \"SCHEMA\"]) : undefined;\n const configuredRules = hasDb\n ? await resolveDataExport<AppRules>(cfg, cfg.db?.rules, [\"rules\", \"RULES\"])\n : undefined;\n const rules = configuredRules ?? (schema && cfg.db?.defaultRules !== false ? rulesFromSchema(schema) : undefined);\n const entities = serializedEntities(schema);\n\n out.log(`config: ${cfg.configPath}`);\n out.log(`app: ${plan.appName} (${plan.appId})`);\n out.log(`envs: ${plan.envs.join(\", \")}`);\n out.log(`svc: ${plan.services.join(\", \")}`);\n out.log(`schema: ${schema ? `${entities.length} entities` : \"none\"}`);\n out.log(`rules: ${rules ? `${Object.keys(rules).length} namespaces` : \"none\"}`);\n out.log(`ai: ${cfg.services.includes(\"ai\") ? (cfg.ai?.provider ?? \"not configured\") : \"not enabled\"}`);\n if (cfg.services.includes(\"calendar\")) {\n const calendar = cfg.envs\n .map((env) => {\n const resolved = calendarServiceConfig(cfg, env);\n return `${env}:${resolved.bookingCalendarId}+${resolved.availabilityCalendars.length}`;\n })\n .join(\", \");\n out.log(`calendar: google/booking (${calendar})`);\n const pages = cfg.envs.map((env) => `${env}:${calendarBookingPageUrl(cfg, env) ?? \"none\"}`).join(\", \");\n out.log(`booking pages: ${pages}`);\n } else {\n out.log(\"calendar: not enabled\");\n }\n\n const warnings: string[] = [];\n if (schema && entities.length === 0) warnings.push(\"schema has no entities\");\n if (rules) {\n for (const ns of Object.keys(rules)) {\n if (entities.length > 0 && !entities.includes(ns)) warnings.push(`rules include \"${ns}\" but schema has no matching entity`);\n }\n }\n if (cfg.services.includes(\"ai\") && !cfg.ai?.provider) warnings.push(\"ai service is enabled but ai.provider is not set\");\n if (cfg.auth?.clerk) {\n for (const [env, value] of Object.entries(cfg.auth.clerk)) {\n if (typeof value === \"string\" && value.startsWith(\"$\") && !process.env[value.slice(1)]) {\n warnings.push(`auth.clerk.${env} references unset env var ${value}`);\n }\n }\n }\n if (cfg.services.includes(\"ai\") && cfg.ai?.keyEnv && !process.env[cfg.ai.keyEnv]) {\n warnings.push(`${cfg.ai.keyEnv} is not set; provision will skip provider key storage`);\n }\n if (cfg.services.includes(\"o11y\")) {\n // o11y enabled but no ingest token = telemetry silently rejected. Provision mints one.\n const credentials = readCredentials(cfg.local.credentialsFile);\n for (const env of cfg.envs) {\n if (!credentials?.envs[env]?.o11yToken) {\n warnings.push(`o11y is enabled but env \"${env}\" has no ingest token — run \"odla-ai provision\" to mint one`);\n }\n }\n warnings.push(...o11yProjectWarnings(cfg.rootDir));\n }\n if (cfg.services.includes(\"calendar\")) warnings.push(...calendarProjectWarnings(cfg.rootDir));\n else if (cfg.calendar) warnings.push('calendar config is present but \"calendar\" is not in services');\n warnings.push(...lintRules(rules, entities, cfg.db?.publicRead ?? []));\n warnings.push(...trackedSecretFiles(cfg.rootDir, undefined, [\n cfg.local.tokenFile,\n cfg.local.credentialsFile,\n cfg.local.devVarsFile,\n ]));\n warnings.push(...wranglerWarnings(cfg.rootDir));\n\n if (warnings.length) {\n out.log(\"\");\n out.log(\"warnings:\");\n for (const warning of warnings) out.log(` - ${warning}`);\n } else {\n out.log(\"ok\");\n }\n}\n","import { readFileSync } from \"node:fs\";\n\nexport function cliVersion(): string {\n const pkg = JSON.parse(readFileSync(new URL(\"../package.json\", import.meta.url), \"utf8\")) as { version?: string };\n return pkg.version ?? \"unknown\";\n}\n\nexport function printHelp(): void {\n console.log(`odla-ai\n\nUsage:\n odla-ai setup [--dir <project>] [--agent <name>] [--global] [--force]\n odla-ai init --app-id <id> --name <name> [--services db,ai,o11y,calendar] [--env dev --env prod]\n odla-ai doctor [--config odla.config.mjs]\n odla-ai calendar status [--env dev] [--email <odla-account>] [--json]\n odla-ai calendar calendars [--env dev] [--email <odla-account>] [--json]\n odla-ai calendar connect [--env dev] [--email <odla-account>] [--no-open] [--yes]\n odla-ai calendar disconnect [--env dev] [--email <odla-account>] --yes\n odla-ai app archive [--config odla.config.mjs] [--email <odla-account>] [--json] --yes\n odla-ai app restore [--config odla.config.mjs] [--email <odla-account>] [--json]\n odla-ai app export [--env dev] [--fresh] [--out <file>] [--email <odla-account>] [--json]\n odla-ai capabilities [--json]\n odla-ai admin ai show [--platform https://odla.ai] [--email <odla-account>] [--json]\n odla-ai admin ai models [--provider <id>] [--json]\n odla-ai admin ai set <purpose> [--provider <id>] [--model <id>] [--enabled|--no-enabled]\n odla-ai admin ai set security --discovery-provider <id> --discovery-model <id>\n --validation-provider <id> --validation-model <id> [--enabled|--no-enabled]\n odla-ai admin ai credentials [--json]\n odla-ai admin ai credential set <provider> (--from-env <NAME>|--stdin)\n odla-ai admin ai usage [--app-id <id>] [--env <env>] [--run-id <id>] [--limit <1-500>] [--json]\n odla-ai admin ai audit [--limit <1-200>] [--json]\n odla-ai security github connect [--repo owner/name] [--env dev] [--email <odla-account>] [--no-open]\n odla-ai security github disconnect --source <id> [--env dev] [--yes]\n odla-ai security plan [--env dev] [--json]\n odla-ai security sources [--env dev] [--json]\n odla-ai security run --source <id> --plan-digest <sha256:...> --ack-redacted-source [--ref <branch|tag|sha>] [--env dev] [--no-follow]\n odla-ai security status <job-id> [--follow] [--json]\n odla-ai security report <job-id> [--json]\n odla-ai security run [target] --ack-redacted-source [--env dev] [--profile odla] [--fail-on high]\n odla-ai security run [target] --self --ack-redacted-source\n odla-ai provision [--config odla.config.mjs] [--email <odla-account>] [--wait <seconds>] [--dry-run] [--push-secrets] [--rotate-o11y-token] [--write-dev-vars[=path]] [--yes]\n odla-ai smoke [--config odla.config.mjs] [--env dev] [--email <odla-account>] [--no-open]\n odla-ai skill install [--dir <project>] [--agent <name>] [--global] [--force]\n odla-ai secrets push --env <env> [--config odla.config.mjs] [--dry-run] [--yes]\n odla-ai secrets set <name> --env <env> (--from-env <NAME>|--stdin) [--email <odla-account>] [--config odla.config.mjs] [--yes]\n odla-ai secrets set-clerk-key --env <env> (--from-env <NAME>|--stdin) [--email <odla-account>] [--config odla.config.mjs] [--yes]\n odla-ai version\n\nCommands:\n setup Install offline odla runbooks for common coding-agent harnesses.\n init Create a generic odla.config.mjs plus starter schema/rules files.\n doctor Validate and summarize the project config without network calls.\n calendar Inspect, connect, or disconnect the live Google booking connection.\n app Archive (suspend, data retained), restore, or export the app.\n Archiving takes every environment's data plane down until restored;\n permanent deletion has NO CLI — it requires a signed-in owner in\n Studio, and no machine or agent credential can purge. \"app export\"\n downloads a portable gzipped-JSONL snapshot of one environment's\n database (--fresh takes a new snapshot first) — your data is\n always yours to take.\n capabilities Show what the CLI automates vs agent edits and human checkpoints.\n admin Manage platform-funded AI routing/credentials/usage with narrow device grants.\n security Connect GitHub sources and run commit-pinned hosted reviews, or scan a local snapshot.\n provision Register services, configure them, persist credentials, optionally push secrets.\n smoke Verify local credentials, public-config, live schema, and db aggregate.\n skill Same installer; --agent accepts all, claude, codex, cursor,\n copilot, gemini, or agents (repeatable or comma-separated).\n secrets Push configured db/o11y secrets into the Worker via wrangler\n stdin; set stores a tenant-vault secret and set-clerk-key the\n reserved Clerk secret key, write-only from stdin or an env var.\n version Print the CLI version.\n\nSafety:\n New projects target dev only. Add prod explicitly to odla.config.mjs and pass\n --yes to provision it; use --dry-run first to inspect the resolved plan.\n Provision caches the approved developer token and service credentials under\n .odla/ with mode 0600, and init adds those paths to .gitignore. Secret push\n preflights Wrangler before any shown-once issuance or destructive rotation.\n Provision opens the approval page in your browser automatically whenever the\n machine can show one, including agent-driven runs; only CI, SSH, and\n display-less hosts skip it. Use --open to force or --no-open to suppress.\n Browser launch is best-effort: the printed approval URL is authoritative and\n agents must relay it to the human verbatim. A started handshake is persisted\n under .odla/, so a command killed mid-wait loses nothing — rerunning resumes\n the same code. Outside an interactive terminal the wait is capped (90s by\n default, --wait <seconds> to change); a still-pending handshake then exits\n with code 75: relay the URL, wait for approval, and re-run to collect.\n A fresh device handshake requires --email <odla-account> or ODLA_USER_EMAIL.\n The email is a non-secret identity hint: never provide a password or session\n token. The matching account must already exist, be signed in, explicitly\n review the exact code, and finish any current request before claiming another.\n Calendar setup has a second human checkpoint: odla issues a state-bound Google consent URL;\n OAuth codes and refresh tokens never enter the CLI, repo, chat, or app.\n GitHub security uses source-read-only access plus optional metadata-only Checks write: the CLI never asks\n for a PAT or provider key. GitHub read access is separate from the explicit\n --ack-redacted-source consent and the exact --plan-digest printed by security\n plan are required before bounded snippets reach System AI.\n Run security plan first to inspect the admin-selected providers, models,\n per-route bounds, credential readiness, retention, no-execution boundary,\n and digest that binds consent to that exact plan.\n`);\n}\n","import type { ParsedArgv } from \"./argv\";\nimport type { AgentHarnessSelector } from \"./skill\";\n\nexport function harnessList(parsed: ParsedArgv): AgentHarnessSelector[] {\n const selected = [\n ...harnessOption(parsed.options.agent, \"--agent\"),\n ...harnessOption(parsed.options.harness, \"--harness\"),\n ];\n return (selected.length ? selected : [\"all\"]) as AgentHarnessSelector[];\n}\n\nfunction harnessOption(\n value: string | boolean | string[] | undefined,\n flag: string,\n): string[] {\n if (value === undefined) return [];\n if (typeof value === \"boolean\") throw new Error(`${flag} requires a harness name`);\n const raw = Array.isArray(value) ? value : [value];\n const parts = raw.flatMap((item) => item.split(\",\"));\n if (parts.some((item) => !item.trim())) {\n throw new Error(`${flag} requires a harness name`);\n }\n return parts.map((item) => item.trim());\n}\n","import { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport { ensureGitignore } from \"./local\";\n\nexport interface InitOptions {\n rootDir?: string;\n configPath?: string;\n appId: string;\n name: string;\n envs?: string[];\n services?: string[];\n aiProvider?: string;\n force?: boolean;\n stdout?: Pick<typeof console, \"log\" | \"error\">;\n}\n\n/**\n * Scaffold a new odla project into `rootDir` (default: cwd). Writes an\n * `odla.config.mjs` (default name, overridable via `configPath`) plus starter\n * `src/odla/schema.mjs` (a single `notes` entity) and `src/odla/rules.mjs`\n * (deny-all), and creates the `src/odla` and `.odla` directories. Also runs\n * `ensureGitignore` so the local token/credentials paths are ignored.\n *\n * Fully local and synchronous — no network calls. The config file is only\n * written when it doesn't already exist unless `force` is set (otherwise it\n * throws); the schema/rules files are written only when missing (never\n * overwritten, even with `force`). `appId` must match `^[a-z0-9][a-z0-9-]*$` or\n * it throws. Defaults: `envs` → `[\"dev\"]`, `services` → `[\"db\",\"ai\"]`,\n * `aiProvider` → `\"anthropic\"` (which also picks the `keyEnv`, e.g.\n * `ANTHROPIC_API_KEY`/`OPENAI_API_KEY`/`GOOGLE_API_KEY`).\n *\n * @param options.appId Slug for the app (lowercase alphanumerics and hyphens).\n * @param options.name Human-readable app name embedded in the config.\n * @param options.rootDir Project root (defaults to `process.cwd()`).\n * @param options.configPath Config filename relative to root (default `odla.config.mjs`).\n * @param options.envs Environment names (default `[\"dev\"]`; production is an explicit opt-in).\n * @param options.services Enabled services (default `[\"db\",\"ai\"]`).\n * @param options.aiProvider AI provider slug (default `\"anthropic\"`).\n * @param options.force Overwrite an existing config file instead of throwing.\n * @param options.stdout Optional console-like sink (defaults to `console`).\n */\nexport function initProject(options: InitOptions): void {\n const out = options.stdout ?? console;\n const rootDir = resolve(options.rootDir ?? process.cwd());\n const configPath = resolve(rootDir, options.configPath ?? \"odla.config.mjs\");\n if (existsSync(configPath) && !options.force) {\n throw new Error(`${configPath} already exists. Pass --force to overwrite.`);\n }\n if (!/^[a-z0-9][a-z0-9-]*$/.test(options.appId)) {\n throw new Error(\"--app-id must be lowercase letters, numbers, and hyphens\");\n }\n // Production is an explicit opt-in. This prevents an unattended `init` +\n // `provision` flow from mutating the live environment by default.\n const envs = options.envs?.length ? options.envs : [\"dev\"];\n const services = options.services?.length ? options.services : [\"db\", \"ai\"];\n if (services.includes(\"calendar\") && !services.includes(\"db\")) throw new Error(\"--services calendar requires db\");\n const aiProvider = options.aiProvider ?? \"anthropic\";\n\n mkdirSync(dirname(configPath), { recursive: true });\n mkdirSync(resolve(rootDir, \"src/odla\"), { recursive: true });\n mkdirSync(resolve(rootDir, \".odla\"), { recursive: true });\n\n writeFileSync(configPath, configTemplate({ appId: options.appId, name: options.name, envs, services, aiProvider }));\n writeIfMissing(resolve(rootDir, \"src/odla/schema.mjs\"), schemaTemplate());\n writeIfMissing(resolve(rootDir, \"src/odla/rules.mjs\"), rulesTemplate());\n ensureGitignore(rootDir);\n\n out.log(`created ${relativeDisplay(configPath, rootDir)}`);\n out.log(\"created src/odla/schema.mjs and src/odla/rules.mjs\");\n out.log(\"updated .gitignore for local odla credentials\");\n}\n\nfunction writeIfMissing(path: string, text: string): void {\n if (existsSync(path)) return;\n writeFileSync(path, text);\n}\n\nfunction configTemplate(input: { appId: string; name: string; envs: string[]; services: string[]; aiProvider: string }): string {\n const calendar = input.services.includes(\"calendar\")\n ? ` calendar: {\n google: {\n // Calendars consulted for availability; bookings land on bookingCalendar\n // (defaults to the first availability calendar). Google consent happens\n // in the browser during provision; bookings write live through odla.ai.\n availabilityCalendars: ${JSON.stringify(Object.fromEntries(input.envs.map((env) => [env, [\"primary\"]])))},\n bookingPageUrl: ${JSON.stringify(Object.fromEntries(input.envs.map((env) => [env, null])))},\n },\n },\n`\n : \"\";\n return `export default {\n platformUrl: process.env.ODLA_PLATFORM_URL ?? \"https://odla.ai\",\n dbEndpoint: process.env.ODLA_ENDPOINT ?? process.env.ODLA_DB_ENDPOINT ?? \"https://db.odla.ai\",\n app: {\n id: \"${input.appId}\",\n name: \"${input.name.replace(/\"/g, '\\\\\"')}\",\n },\n envs: ${JSON.stringify(input.envs)},\n services: ${JSON.stringify(input.services)},\n db: {\n schema: \"./src/odla/schema.mjs\",\n rules: \"./src/odla/rules.mjs\",\n // When rules is omitted, the CLI generates deny-all rules from schema.\n defaultRules: \"deny\",\n },\n ai: {\n provider: process.env.ODLA_AI_PROVIDER ?? \"${input.aiProvider}\",\n // Optional: set this env var while running provision to store the provider\n // key in the platform vault for each tenant.\n keyEnv: \"${defaultKeyEnv(input.aiProvider)}\",\n },\n${calendar}\n auth: {\n clerk: {\n // dev: \"$CLERK_PUBLISHABLE_KEY\",\n // prod: \"$CLERK_PUBLISHABLE_KEY\",\n },\n },\n // Add \"o11y\" to services to enable observability; provision then mints the\n // ingest token and scaffolds the ODLA_O11Y_* vars into .dev.vars.\n // o11y: {\n // service: \"${input.appId}\", // defaults to the app id\n // // endpoint: \"https://o11y.odla.ai\",\n // },\n links: {\n // dev: \"https://dev.example.com\",\n // prod: \"https://example.com\",\n },\n local: {\n tokenFile: \".odla/dev-token.json\",\n credentialsFile: \".odla/credentials.local.json\",\n devVarsFile: \".dev.vars\",\n },\n};\n`;\n}\n\nfunction schemaTemplate(): string {\n return `// Replace this starter schema with your app's odla-db schema.\n// Knowledge-graph projects can export @odla-ai/kg's toSerializedSchema(ontology).\nexport const schema = {\n entities: {\n notes: {\n attrs: {\n id: { type: \"string\", unique: true, indexed: true, optional: false },\n text: { type: \"string\", unique: false, indexed: false, optional: false },\n createdAt: { type: \"number\", unique: false, indexed: true, optional: false },\n },\n },\n },\n links: {},\n};\n`;\n}\n\nfunction rulesTemplate(): string {\n return `// odla-db is default-deny. The starter keeps runtime data backend-only.\nexport const rules = {\n notes: {\n view: \"false\",\n create: \"false\",\n update: \"false\",\n delete: \"false\",\n },\n};\n`;\n}\n\nfunction defaultKeyEnv(provider: string): string {\n if (provider === \"openai\") return \"OPENAI_API_KEY\";\n if (provider === \"google\") return \"GOOGLE_API_KEY\";\n return \"ANTHROPIC_API_KEY\";\n}\n\nfunction relativeDisplay(path: string, rootDir: string): string {\n return path.startsWith(rootDir) ? path.slice(rootDir.length + 1) : path;\n}\n","import { createAppsClient, tenantIdFor } from \"@odla-ai/apps\";\nimport { DEFAULT_SECRET_NAMES, putSecret } from \"@odla-ai/ai\";\nimport process from \"node:process\";\nimport type { AppRules, LoadedProjectConfig, ProvisionOptions } from \"./types\";\nimport { buildPlan, calendarBookingPageUrl, calendarServiceConfig, envValue, GOOGLE_CALENDAR_EVENTS_SCOPE, loadProjectConfig, resolveDataExport, rulesFromSchema } from \"./config\";\nimport { applyCalendarBookingPage, ensureCalendarConnected } from \"./calendar\";\nimport { isCalendarPlatformNotReady } from \"./calendar-errors\";\nimport { handshakeFile } from \"./handshake-state\";\nimport { getDeveloperToken } from \"./token\";\nimport {\n displayPath, ensureGitignore, gitignoreEntry, o11yDevVars, readCredentials, resolveWriteDevVarsTarget, writeDevVars,\n} from \"./local\";\nimport { provisionEnvCredentials } from \"./provision-credentials\";\nimport { redactSecrets } from \"./redact\";\nimport { preflightSecretsPush, secretsPushAfterPreflight } from \"./secrets\";\n\ntype FetchLike = typeof fetch;\n\n/**\n * Provision an app end-to-end from its config — the primary deploy path, and\n * (apart from key rotation) idempotent, so re-running is safe. Obtains a\n * developer token, creates the registry app when absent, enables each service\n * per env (AI also gets `setAi` with the configured provider/model), configures\n * Clerk auth and links, then per env mints or reuses credentials only for the\n * configured services, pushes the schema with the db key and the\n * rules with the developer token, and stores the provider key in the tenant\n * vault when `ai.keyEnv` is set and present. Writes the credentials file\n * (mode 0600, gitignored) and, when requested, `.dev.vars`. Google Calendar\n * consent runs last, per env; when the platform connector itself is not yet\n * configured (`calendar_*_not_configured`), provision prints a resume hint\n * (`odla-ai calendar connect`) instead of aborting.\n *\n * The developer token comes from (in order) `options.token`, `$ODLA_DEV_TOKEN`,\n * the cached `.odla` token, or a fresh email-bound device handshake — which\n * prints a user code for the same signed-in account to review and auto-opens\n * the browser whenever this machine can show one — including scripted and\n * agent-driven runs; only CI, SSH, and display-less hosts skip it\n * (`open: true`/`false` forces/suppresses it). Network error bodies pass through\n * `redactSecrets` before display.\n *\n * @param options.dryRun Print the resolved plan and return before any network call/write.\n * @param options.rotateKeys Rotate db keys and o11y tokens.\n * @param options.rotateO11yToken Rotate only the o11y token.\n * @param options.email Existing odla account email for a fresh handshake;\n * this is an identity hint, never a password or session credential.\n * @param options.pushSecrets Preflight Wrangler, then push each env's configured\n * Worker secrets immediately after credential provisioning.\n * @param options.writeDevVars `true`/a path writes `.dev.vars`; `writeCredentials: false` skips the creds file.\n * @param options.yes Required for a non-dry-run plan containing `prod` or\n * `production`; callers must show and review `dryRun` output first.\n * @throws When a production plan is executed without `yes`, configuration is\n * invalid, authorization fails, or a provisioning operation fails.\n */\nexport async function provision(options: ProvisionOptions): Promise<void> {\n const out = options.stdout ?? console;\n const cfg = await loadProjectConfig(options.configPath);\n const plan = buildPlan(cfg);\n const hasDb = cfg.services.includes(\"db\");\n const hasO11y = cfg.services.includes(\"o11y\");\n\n if (options.rotateO11yToken && !hasO11y) {\n throw new Error(\"--rotate-o11y-token requires the o11y service in odla.config.mjs\");\n }\n if (options.pushSecrets && options.writeCredentials === false) {\n throw new Error(\"--push-secrets cannot be combined with --no-write-credentials\");\n }\n\n out.log(`odla-ai: ${plan.appName} (${plan.appId})`);\n out.log(` platform: ${plan.platformUrl}`);\n out.log(` db: ${plan.dbEndpoint}`);\n out.log(` envs: ${plan.envs.join(\", \")}`);\n out.log(` services: ${plan.services.join(\", \")}`);\n\n const productionEnvs = plan.envs.filter((env) => env === \"prod\" || env === \"production\");\n if (!options.dryRun && productionEnvs.length > 0 && !options.yes) {\n throw new Error(\n `refusing to provision production env ${productionEnvs.join(\", \")} without --yes; run --dry-run first`,\n );\n }\n\n const schema = hasDb ? await resolveDataExport<unknown>(cfg, cfg.db?.schema, [\"schema\", \"SCHEMA\"]) : undefined;\n const configuredRules = hasDb ? await resolveDataExport<AppRules>(cfg, cfg.db?.rules, [\"rules\", \"RULES\"]) : undefined;\n const rules = configuredRules ?? (schema && cfg.db?.defaultRules !== false ? rulesFromSchema(schema) : undefined);\n\n if (options.dryRun) {\n out.log(\"dry run: no network calls or file writes\");\n out.log(` schema: ${schema ? \"yes\" : \"no\"}`);\n out.log(` rules: ${rules ? Object.keys(rules).length : 0} namespaces`);\n out.log(` ai: ${cfg.services.includes(\"ai\") ? (cfg.ai?.provider ?? \"not configured\") : \"not enabled\"}`);\n if (cfg.services.includes(\"calendar\")) {\n for (const env of cfg.envs) {\n const calendar = calendarServiceConfig(cfg, env);\n out.log(` calendar.${env}: google/book → ${calendar.bookingCalendarId}; availability ${calendar.availabilityCalendars.join(\", \")} (${GOOGLE_CALENDAR_EVENTS_SCOPE})`);\n const bookingPage = calendarBookingPageUrl(cfg, env);\n out.log(` calendar.${env}.bookingPageUrl: ${bookingPage === undefined ? \"unchanged\" : bookingPage ?? \"clear\"}`);\n }\n }\n out.log(` secrets: ${options.pushSecrets ? \"push configured Worker secrets\" : \"local only\"}`);\n return;\n }\n\n let credentials = readCredentials(cfg.local.credentialsFile);\n if (credentials && credentials.appId !== cfg.app.id) {\n throw new Error(\n `credentials at ${displayPath(cfg.local.credentialsFile, cfg.rootDir)} are for \"${credentials.appId}\", not \"${cfg.app.id}\"`,\n );\n }\n const rotatesO11y = !!(options.rotateKeys || options.rotateO11yToken);\n const missingO11y = cfg.envs.some((env) => !credentials?.envs[env]?.o11yToken);\n const missingDb = cfg.envs.some((env) => !credentials?.envs[env]?.dbKey);\n const losesShownOnceCredential = (hasDb && (!!options.rotateKeys || missingDb)) || (hasO11y && (rotatesO11y || missingO11y));\n if (options.writeCredentials === false && losesShownOnceCredential) {\n throw new Error(\"credential issuance/rotation requires the private credentials file; remove --no-write-credentials\");\n }\n const devVarsTarget = resolveWriteDevVarsTarget(cfg, options.writeDevVars);\n if (cfg.local.gitignore) {\n ensureGitignore(cfg.rootDir, [cfg.local.tokenFile, handshakeFile(cfg), cfg.local.credentialsFile, ...(devVarsTarget ? [devVarsTarget] : [])]);\n }\n if (options.pushSecrets) {\n await preflightSecretsPush({ configPath: cfg.configPath, runner: options.secretRunner });\n out.log(\"secrets: Wrangler config and login preflight passed\");\n }\n\n const doFetch = options.fetch ?? fetch;\n const token = await getDeveloperToken(cfg, options, doFetch, out);\n const apps = createAppsClient({ endpoint: cfg.platformUrl, token, fetcher: { fetch: doFetch } });\n\n const existing = await readRegistryApp(cfg, token, doFetch);\n if (existing) {\n out.log(`app: ${cfg.app.id} already exists`);\n } else {\n await apps.createApp({ name: cfg.app.name, appId: cfg.app.id });\n out.log(`app: created ${cfg.app.id}`);\n }\n\n const serviceOrder = [...cfg.services].sort((a, b) => serviceRank(a) - serviceRank(b));\n for (const env of cfg.envs) {\n for (const service of serviceOrder) {\n if (service === \"ai\") {\n if (cfg.ai?.provider) {\n await apps.setAi(cfg.app.id, env, { provider: cfg.ai.provider, ...(cfg.ai.model ? { model: cfg.ai.model } : {}) });\n out.log(`${env}: ai configured (${cfg.ai.provider}${cfg.ai.model ? `/${cfg.ai.model}` : \"\"})`);\n } else {\n await apps.setService(cfg.app.id, \"ai\", true, { env });\n out.log(`${env}: ai enabled`);\n }\n } else {\n const config = service === \"calendar\" ? calendarServiceConfig(cfg, env) : undefined;\n await apps.setService(cfg.app.id, service, true, { env, ...(config ? { config } : {}) });\n out.log(`${env}: ${service} enabled`);\n }\n }\n\n const authConfig = normalizeClerkConfig(cfg.auth?.clerk?.[env]);\n if (authConfig?.publishableKey) {\n await apps.setAuth(cfg.app.id, env, authConfig);\n out.log(`${env}: auth configured (clerk ${authConfig.mode ?? \"client\"})`);\n }\n\n const link = cfg.links?.[env];\n if (link !== undefined) {\n await apps.setLink(cfg.app.id, env, link ?? null);\n out.log(`${env}: link ${link ? \"set\" : \"cleared\"}`);\n }\n\n if (cfg.services.includes(\"calendar\")) {\n const calendarCtx = { platform: cfg.platformUrl, appId: cfg.app.id, env, token, fetch: doFetch };\n await applyCalendarBookingPage(calendarCtx, calendarBookingPageUrl(cfg, env), out);\n }\n }\n\n for (const env of cfg.envs) {\n const tenantId = tenantIdFor(cfg.app.id, env);\n credentials = await provisionEnvCredentials({\n cfg,\n env,\n developerToken: token,\n credentials,\n rotateDb: !!options.rotateKeys,\n rotateO11y: rotatesO11y,\n write: options.writeCredentials !== false,\n fetch: doFetch,\n stdout: out,\n });\n const dbKey = credentials.envs[env]?.dbKey;\n\n if (options.pushSecrets) {\n try {\n await secretsPushAfterPreflight({\n configPath: cfg.configPath,\n env,\n yes: options.yes,\n runner: options.secretRunner,\n stdout: out,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const consent = env === \"prod\" || env === \"production\" ? \" --yes\" : \"\";\n throw new Error(\n `${message}\\n${env}: credentials are already saved; retry ` +\n `\"odla-ai secrets push --env ${env}${consent}\" without issuing or rotating again`,\n { cause: error },\n );\n }\n }\n\n if (schema && dbKey) {\n await postJson(doFetch, `${cfg.dbEndpoint}/app/${encodeURIComponent(tenantId)}/schema`, dbKey, { schema });\n out.log(`${env}: schema pushed`);\n }\n if (rules) {\n await postJson(doFetch, `${cfg.dbEndpoint}/app/${encodeURIComponent(tenantId)}/admin/rules`, token, rules);\n out.log(`${env}: rules pushed (${Object.keys(rules).length} namespaces)`);\n }\n\n if (cfg.services.includes(\"ai\") && cfg.ai?.provider && cfg.ai.keyEnv) {\n const key = process.env[cfg.ai.keyEnv];\n if (key) {\n const secretName = cfg.ai.secretName ?? defaultSecretName(cfg.ai.provider);\n await putSecret({ endpoint: cfg.dbEndpoint, token, fetch: doFetch }, tenantId, secretName, key);\n out.log(`${env}: ${cfg.ai.provider} key stored in vault (${secretName})`);\n } else {\n out.log(`${env}: ${cfg.ai.keyEnv} not set; skipped provider key storage`);\n }\n }\n\n }\n\n if (options.writeCredentials !== false && credentials) {\n const ignored = cfg.local.gitignore && gitignoreEntry(cfg.rootDir, cfg.local.credentialsFile);\n out.log(`credentials: wrote ${displayPath(cfg.local.credentialsFile, cfg.rootDir)} (0600${ignored ? \", gitignored\" : \"\"})`);\n }\n\n if (devVarsTarget && credentials) {\n const env = cfg.envs.includes(\"dev\") ? \"dev\" : (cfg.envs[0] ?? \"prod\");\n writeDevVars(devVarsTarget, credentials, env, o11yDevVars(cfg));\n out.log(`dev vars: wrote ${displayPath(devVarsTarget, cfg.rootDir)} for ${env}`);\n }\n\n // Google consent runs last: the only human checkpoint never blocks\n // credentials, schema, rules, or local artifacts.\n if (cfg.services.includes(\"calendar\")) {\n for (const env of cfg.envs) {\n try {\n await ensureCalendarConnected(\n { platform: cfg.platformUrl, appId: cfg.app.id, env, token, fetch: doFetch },\n {\n open: options.open,\n openConsentUrl: options.openApprovalUrl,\n wait: options.calendarPollWait,\n pollTimeoutMs: options.calendarPollTimeoutMs,\n stdout: out,\n },\n );\n } catch (error) {\n if (!isCalendarPlatformNotReady(error)) throw error;\n out.log(`${env}: calendar consent skipped (${error.code}); resume with \"odla-ai calendar connect --env ${env}\" once the platform is configured`);\n }\n }\n }\n}\n\nfunction serviceRank(service: string): number {\n if (service === \"db\") return 0;\n if (service === \"calendar\") return 2;\n return 1;\n}\n\nasync function readRegistryApp(cfg: LoadedProjectConfig, token: string, doFetch: FetchLike): Promise<unknown | null> {\n const res = await doFetch(`${cfg.platformUrl}/registry/apps/${encodeURIComponent(cfg.app.id)}`, {\n headers: { authorization: `Bearer ${token}` },\n });\n if (res.status === 404) return null;\n if (!res.ok) return null;\n const json = (await res.json()) as { app?: unknown };\n return json.app ?? null;\n}\n\nasync function postJson(doFetch: FetchLike, url: string, bearer: string, body: unknown): Promise<void> {\n const res = await doFetch(url, {\n method: \"POST\",\n headers: { authorization: `Bearer ${bearer}`, \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n if (!res.ok) throw new Error(`${new URL(url).pathname} failed: ${res.status} ${await safeText(res)}`);\n}\n\nfunction normalizeClerkConfig(value: unknown): { publishableKey: string; audience?: string; mode?: \"client\" | \"full\" } | null {\n if (!value) return null;\n if (typeof value === \"string\") {\n const publishableKey = envValue(value);\n return publishableKey ? { publishableKey } : null;\n }\n if (typeof value !== \"object\") return null;\n const cfg = value as { publishableKey?: string; audience?: string; mode?: \"client\" | \"full\" };\n const publishableKey = envValue(cfg.publishableKey);\n return publishableKey ? { publishableKey, ...(cfg.audience ? { audience: cfg.audience } : {}), ...(cfg.mode ? { mode: cfg.mode } : {}) } : null;\n}\n\nfunction defaultSecretName(provider: string): string {\n const names = DEFAULT_SECRET_NAMES as Record<string, string>;\n return names[provider] ?? `${provider}_api_key`;\n}\n\nasync function safeText(res: Response): Promise<string> {\n try {\n return redactSecrets((await res.text()).slice(0, 500));\n } catch {\n return \"\";\n }\n}\n","import { tenantIdFor } from \"@odla-ai/apps\";\nimport type { LoadedProjectConfig, LocalCredentials } from \"./types\";\nimport { mergeCredential, writePrivateJson } from \"./local\";\nimport { redactSecrets } from \"./redact\";\n\ntype FetchLike = typeof fetch;\n\ninterface ProvisionEnvCredentialsOptions {\n cfg: LoadedProjectConfig;\n env: string;\n developerToken: string;\n credentials: LocalCredentials | null;\n rotateDb: boolean;\n rotateO11y: boolean;\n write: boolean;\n fetch: FetchLike;\n stdout: Pick<typeof console, \"log\">;\n}\n\n/** Mint/reuse only the credentials required by configured services. */\nexport async function provisionEnvCredentials(opts: ProvisionEnvCredentialsOptions): Promise<LocalCredentials> {\n const tenantId = tenantIdFor(opts.cfg.app.id, opts.env);\n const prior = opts.credentials?.envs[opts.env];\n let credentials = opts.credentials;\n let dbKey = opts.cfg.services.includes(\"db\") && !opts.rotateDb ? prior?.dbKey : undefined;\n let o11yToken = opts.cfg.services.includes(\"o11y\") && !opts.rotateO11y ? prior?.o11yToken : undefined;\n\n if (opts.cfg.services.includes(\"db\")) {\n if (dbKey) {\n opts.stdout.log(`${opts.env}: reusing local db key for ${tenantId}`);\n } else {\n dbKey = await mintDbKey(opts, tenantId);\n credentials = save(opts, credentials, tenantId, { dbKey });\n opts.stdout.log(`${opts.env}: minted db key for ${tenantId}`);\n }\n }\n\n if (opts.cfg.services.includes(\"o11y\")) {\n if (o11yToken) {\n opts.stdout.log(`${opts.env}: reusing local o11y ingest token`);\n } else {\n o11yToken = await issueO11yToken(opts);\n credentials = save(opts, credentials, tenantId, { ...(dbKey ? { dbKey } : {}), o11yToken });\n opts.stdout.log(`${opts.env}: ${opts.rotateO11y ? \"rotated\" : \"issued\"} o11y ingest token`);\n }\n }\n\n return save(opts, credentials, tenantId, {\n ...(dbKey ? { dbKey } : {}),\n ...(o11yToken ? { o11yToken } : {}),\n });\n}\n\nfunction save(\n opts: ProvisionEnvCredentialsOptions,\n current: LocalCredentials | null,\n tenantId: string,\n values: { dbKey?: string; o11yToken?: string },\n): LocalCredentials {\n const next = mergeCredential(current, {\n appId: opts.cfg.app.id,\n platformUrl: opts.cfg.platformUrl,\n dbEndpoint: opts.cfg.dbEndpoint,\n env: opts.env,\n tenantId,\n ...values,\n });\n if (opts.write) writePrivateJson(opts.cfg.local.credentialsFile, next);\n return next;\n}\n\nasync function mintDbKey(opts: ProvisionEnvCredentialsOptions, tenantId: string): Promise<string> {\n const headers = { authorization: `Bearer ${opts.developerToken}`, \"content-type\": \"application/json\" };\n let res = await opts.fetch(`${opts.cfg.dbEndpoint}/admin/apps/${encodeURIComponent(tenantId)}/keys`, {\n method: \"POST\",\n headers,\n body: \"{}\",\n });\n if (res.status === 404) {\n const created = await opts.fetch(`${opts.cfg.dbEndpoint}/admin/apps`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n name: opts.env === \"prod\" ? opts.cfg.app.name : `${opts.cfg.app.name} (${opts.env})`,\n appId: tenantId,\n }),\n });\n if (!created.ok) throw new Error(`db app create (${tenantId}) failed: ${created.status} ${await safeText(created)}`);\n res = await opts.fetch(`${opts.cfg.dbEndpoint}/admin/apps/${encodeURIComponent(tenantId)}/keys`, {\n method: \"POST\",\n headers,\n body: \"{}\",\n });\n }\n if (!res.ok) throw new Error(`db key mint (${tenantId}) failed: ${res.status} ${await safeText(res)}`);\n const body = (await res.json()) as { key?: string };\n if (!body.key) throw new Error(`db key mint (${tenantId}) returned no key`);\n return body.key;\n}\n\nasync function issueO11yToken(opts: ProvisionEnvCredentialsOptions): Promise<string> {\n const suffix = opts.rotateO11y ? \"/rotate\" : \"\";\n const res = await opts.fetch(\n `${opts.cfg.platformUrl}/o11y/${encodeURIComponent(opts.cfg.app.id)}/token${suffix}?env=${encodeURIComponent(opts.env)}`,\n { method: \"POST\", headers: { authorization: `Bearer ${opts.developerToken}` } },\n );\n if (res.status === 409 && !opts.rotateO11y) {\n throw new Error(\n `o11y token already exists for env \"${opts.env}\", but its shown-once value is not in the local credentials file; ` +\n `run \"odla-ai provision --rotate-o11y-token --push-secrets\" to replace it explicitly`,\n );\n }\n if (!res.ok) throw new Error(`o11y token ${opts.rotateO11y ? \"rotation\" : \"issue\"} (${opts.env}) failed: ${res.status} ${await safeText(res)}`);\n const body = (await res.json()) as { token?: string };\n if (!body.token) throw new Error(`o11y token ${opts.rotateO11y ? \"rotation\" : \"issue\"} (${opts.env}) returned no token`);\n return body.token;\n}\n\nasync function safeText(res: Response): Promise<string> {\n try {\n return redactSecrets((await res.text()).slice(0, 500));\n } catch {\n return \"\";\n }\n}\n","import { loadProjectConfig } from \"./config\";\nimport { displayPath, readCredentials } from \"./local\";\nimport { redactSecrets } from \"./redact\";\nimport type { LoadedProjectConfig } from \"./types\";\nimport { defaultRunner, findWranglerConfig, wranglerLoggedIn, wranglerPutSecret } from \"./wrangler\";\nimport type { CommandRunner } from \"./wrangler\";\n\n/** Moves locally stored configured service credentials to one Wrangler environment over stdin. */\nexport interface SecretsPushOptions {\n configPath: string;\n env: string;\n dryRun?: boolean;\n /** Required to push to a prod-named env; the visible consent token in agent transcripts. */\n yes?: boolean;\n runner?: CommandRunner;\n stdout?: Pick<typeof console, \"log\" | \"error\">;\n}\n\nexport interface SecretsPreflightOptions {\n configPath: string;\n runner?: CommandRunner;\n}\n\nconst PROD_ENV_NAMES = new Set([\"prod\", \"production\"]);\n\n/**\n * Moves the env's configured db and/or o11y credentials from the private local\n * credentials file into the Worker, piping values over stdin so they never\n * appear on argv, in output, or in the conversation transcript.\n */\nexport async function secretsPush(options: SecretsPushOptions): Promise<void> {\n await secretsPushImpl(options, true);\n}\n\n/** @internal Push after the caller has completed `preflightSecretsPush`. */\nexport async function secretsPushAfterPreflight(options: SecretsPushOptions): Promise<void> {\n await secretsPushImpl(options, false);\n}\n\nasync function secretsPushImpl(options: SecretsPushOptions, preflight: boolean): Promise<void> {\n const out = options.stdout ?? console;\n const cfg = await loadProjectConfig(options.configPath);\n const env = options.env;\n\n if (!cfg.envs.includes(env)) {\n throw new Error(`env \"${env}\" is not in config envs (${cfg.envs.join(\", \")})`);\n }\n if (PROD_ENV_NAMES.has(env) && !options.yes) {\n throw new Error(`refusing to push a secret to \"${env}\" without --yes`);\n }\n\n const credentialsPath = displayPath(cfg.local.credentialsFile, cfg.rootDir);\n const credentials = readCredentials(cfg.local.credentialsFile);\n if (!credentials) throw new Error(`no credentials at ${credentialsPath} — run \"odla-ai provision\" first`);\n if (credentials.appId !== cfg.app.id) {\n throw new Error(`credentials at ${credentialsPath} are for \"${credentials.appId}\", not \"${cfg.app.id}\"`);\n }\n const entry = credentials.envs[env];\n if (!entry) throw new Error(`no credentials for env \"${env}\" in ${credentialsPath} — run \"odla-ai provision\" first`);\n\n const secrets: Array<{ name: string; value: string }> = [];\n if (cfg.services.includes(\"o11y\")) {\n if (!entry.o11yToken) throw new Error(`no o11y token for env \"${env}\" in ${credentialsPath} — run \"odla-ai provision\" first`);\n secrets.push({ name: \"ODLA_O11Y_TOKEN\", value: entry.o11yToken });\n }\n if (cfg.services.includes(\"db\")) {\n if (!entry.dbKey) throw new Error(`no db key for env \"${env}\" in ${credentialsPath} — run \"odla-ai provision\" first`);\n secrets.push({ name: \"ODLA_API_KEY\", value: entry.dbKey });\n }\n if (secrets.length === 0) {\n out.log(`${env}: no configured Worker secrets to push`);\n return;\n }\n\n // Convention from the reference apps: the top-level wrangler config is prod;\n // every other env is a named `env.<name>` block.\n const wranglerEnv = PROD_ENV_NAMES.has(env) ? undefined : env;\n const target = wranglerEnv ? `wrangler env \"${wranglerEnv}\"` : \"the top-level (prod) wrangler env\";\n\n if (options.dryRun) {\n assertWranglerConfig(cfg);\n for (const s of secrets) out.log(`dry run: would push ${s.name} (${redactSecrets(s.value)}) to ${target}`);\n return;\n }\n\n const run = options.runner ?? defaultRunner;\n if (preflight) await preflightLoadedConfig(cfg, run);\n\n for (const s of secrets) {\n const result = await wranglerPutSecret(run, { name: s.name, value: s.value, env: wranglerEnv, cwd: cfg.rootDir });\n if (result.code !== 0) {\n throw new Error(`wrangler secret put ${s.name} failed (exit ${result.code}): ${redactSecrets(`${result.stderr || result.stdout}`.trim())}`);\n }\n out.log(`${s.name} pushed to ${target} (value read from ${credentialsPath}, never echoed)`);\n }\n}\n\n/** Check Wrangler config and login before provisioning issues or rotates secrets. */\nexport async function preflightSecretsPush(options: SecretsPreflightOptions): Promise<void> {\n const cfg = await loadProjectConfig(options.configPath);\n if (!cfg.services.some((service) => service === \"db\" || service === \"o11y\")) return;\n await preflightLoadedConfig(cfg, options.runner ?? defaultRunner);\n}\n\nasync function preflightLoadedConfig(cfg: LoadedProjectConfig, run: CommandRunner): Promise<void> {\n assertWranglerConfig(cfg);\n if (!(await wranglerLoggedIn(run, cfg.rootDir))) {\n throw new Error(`wrangler is not logged in — run \"wrangler login\" (a browser step for the human)`);\n }\n}\n\nfunction assertWranglerConfig(cfg: LoadedProjectConfig): void {\n if (!findWranglerConfig(cfg.rootDir)) {\n throw new Error(`no wrangler config found in ${cfg.rootDir} (wrangler.jsonc, wrangler.json, or wrangler.toml)`);\n }\n}\n","import { putSecret } from \"@odla-ai/ai\";\nimport { tenantIdFor } from \"@odla-ai/apps\";\nimport { loadProjectConfig } from \"./config\";\nimport { redactSecrets } from \"./redact\";\nimport { secretInputValue } from \"./secret-input\";\nimport { getDeveloperToken } from \"./token\";\nimport type { LoadedProjectConfig } from \"./types\";\n\n/**\n * Inputs for one write-only tenant-vault transfer (`secrets set` /\n * `secrets set-clerk-key`). Values may come only from a named environment\n * variable or stdin, so a producer command can be piped straight into the\n * vault without the secret ever being displayed or stored on disk.\n */\nexport interface SecretsSetOptions {\n configPath: string;\n env: string;\n /** Vault secret name (`secrets set` only; `$`-prefixed names are reserved). */\n name?: string;\n fromEnv?: string;\n stdin?: boolean;\n /** Explicit consent for a prod-named env (and for sk_live_ into a non-prod env). */\n yes?: boolean;\n /** Developer token override; defaults to $ODLA_DEV_TOKEN, the cached token, or a device handshake. */\n token?: string;\n /** Existing odla account email used only when a fresh handshake is required. */\n email?: string;\n open?: boolean;\n openApprovalUrl?: (url: string) => Promise<void>;\n fetch?: typeof fetch;\n readStdin?: () => Promise<string>;\n stdout?: Pick<typeof console, \"log\" | \"error\">;\n}\n\nconst PROD_ENV_NAMES = new Set([\"prod\", \"production\"]);\n\n/**\n * Store one named secret in the env's tenant vault (the same write-only slot\n * Studio's Secrets panel fills), e.g. `clerk_webhook_secret` for synced auth.\n * The value is encrypted at rest and can be read back only by that tenant's\n * app API key — never by this CLI, Studio, or the developer token.\n */\nexport async function secretsSet(options: SecretsSetOptions): Promise<void> {\n const name = (options.name ?? \"\").trim();\n if (!name) throw new Error('secret name is required, e.g. \"odla-ai secrets set clerk_webhook_secret --env dev --stdin\"');\n if (name.startsWith(\"$\")) {\n throw new Error('\"$\"-prefixed vault names are platform-reserved; for the Clerk secret key use \"odla-ai secrets set-clerk-key\"');\n }\n const { cfg, tenantId, value, doFetch, out } = await resolveVaultWrite(options);\n const token = await getDeveloperToken(cfg, options, doFetch, out);\n try {\n await putSecret({ endpoint: cfg.dbEndpoint, token, fetch: doFetch }, tenantId, name, value);\n } catch (err) {\n throw new Error(scrubValue(err instanceof Error ? err.message : String(err), value));\n }\n out.log(`${name} stored in the ${tenantId} vault (write-only; the value was never echoed and cannot be read back here)`);\n}\n\n/**\n * Store the app's Clerk secret key under the reserved `$clerk_secret` slot so\n * odla-db can resolve the app's users (invites, member lookups). Reserved\n * secrets are never readable by app keys; the dedicated endpoint is the only\n * way to set one. Guards against instance/env mismatches: an sk_test_ key\n * never belongs in a prod-named env, and an sk_live_ key entering a non-prod\n * env requires `--yes` (live users would sync into a non-prod tenant).\n */\nexport async function secretsSetClerkKey(options: SecretsSetOptions): Promise<void> {\n const { cfg, tenantId, value, doFetch, out } = await resolveVaultWrite(options);\n if (!value.startsWith(\"sk_\")) throw new Error(\"the Clerk secret key must start with sk_ (sk_test_… or sk_live_…)\");\n if (value.startsWith(\"sk_test_\") && PROD_ENV_NAMES.has(options.env)) {\n throw new Error(`refusing to store an sk_test_ Clerk key for \"${options.env}\" — use the production instance's sk_live_ key`);\n }\n if (value.startsWith(\"sk_live_\") && !PROD_ENV_NAMES.has(options.env) && !options.yes) {\n throw new Error(`refusing to store an sk_live_ Clerk key for \"${options.env}\" without --yes (live users would sync into a non-prod tenant)`);\n }\n const token = await getDeveloperToken(cfg, options, doFetch, out);\n const res = await doFetch(`${cfg.dbEndpoint}/admin/apps/${encodeURIComponent(tenantId)}/clerk-secret`, {\n method: \"POST\",\n headers: { authorization: `Bearer ${token}`, \"content-type\": \"application/json\" },\n body: JSON.stringify({ value }),\n });\n if (!res.ok) {\n const text = scrubValue((await res.text().catch(() => \"\")).slice(0, 300), value);\n throw new Error(`store Clerk secret key failed (${res.status}): ${text || \"request failed\"}`);\n }\n out.log(`Clerk secret key stored for ${tenantId} ($clerk_secret, reserved + write-only; the value was never echoed)`);\n}\n\n/** No error text may carry the transferred value, even when a misbehaving\n * endpoint echoes it back in a shape the pattern redactor doesn't know. */\nfunction scrubValue(text: string, value: string): string {\n return redactSecrets(text).split(value).join(\"[value redacted]\");\n}\n\ninterface VaultWrite {\n cfg: LoadedProjectConfig;\n tenantId: string;\n value: string;\n doFetch: typeof fetch;\n out: Pick<typeof console, \"log\" | \"error\">;\n}\n\n/** Shared preamble: config, env + prod consent, value ingestion. Every value\n * check runs before the caller acquires a token, so a bad invocation fails\n * fast instead of sending the user through a device handshake first. */\nasync function resolveVaultWrite(options: SecretsSetOptions): Promise<VaultWrite> {\n const out = options.stdout ?? console;\n const doFetch = options.fetch ?? fetch;\n const cfg = await loadProjectConfig(options.configPath);\n if (!cfg.envs.includes(options.env)) {\n throw new Error(`env \"${options.env}\" is not in config envs (${cfg.envs.join(\", \")})`);\n }\n if (PROD_ENV_NAMES.has(options.env) && !options.yes) {\n throw new Error(`refusing to store a secret for \"${options.env}\" without --yes`);\n }\n const value = await secretInputValue(options, \"secret\");\n return { cfg, tenantId: tenantIdFor(cfg.app.id, options.env), value, doFetch, out };\n}\n","import { createInterface } from \"node:readline/promises\";\nimport { stringOpt, type ParsedArgv } from \"./argv\";\nimport { loadProjectConfig } from \"./config\";\nimport type { CliDependencies } from \"./cli\";\nimport type { HostedSecurityProfile } from \"./security\";\nimport { getDeveloperToken, platformAudience } from \"./token\";\n\nexport interface HostedSecurityContext {\n platform: string;\n token: string;\n appId: string;\n env: string;\n fetch: typeof fetch;\n stdout: Pick<typeof console, \"log\" | \"error\">;\n}\n\nexport async function hostedSecurityContext(\n parsed: ParsedArgv,\n dependencies: CliDependencies,\n): Promise<HostedSecurityContext> {\n const configPath = stringOpt(parsed.options.config) ?? \"odla.config.mjs\";\n const cfg = await loadProjectConfig(configPath);\n const env = stringOpt(parsed.options.env) ?? (cfg.envs.includes(\"dev\") ? \"dev\" : cfg.envs[0]);\n if (!env || !cfg.envs.includes(env)) {\n throw new Error(`env \"${env ?? \"\"}\" is not declared in ${configPath}`);\n }\n const platform = platformAudience(stringOpt(parsed.options.platform) ?? cfg.platformUrl);\n if (platformAudience(cfg.platformUrl) !== platform) {\n throw new Error(\"--platform cannot reuse a project developer token from another platform; update odla.config.mjs and authenticate there\");\n }\n const doFetch = dependencies.fetch ?? fetch;\n const stdout = dependencies.stdout ?? console;\n const open = parsed.options.open === false\n ? false\n : parsed.options.open === true ? true : undefined;\n const token = await getDeveloperToken(\n cfg,\n { configPath, email: stringOpt(parsed.options.email), open, openApprovalUrl: dependencies.openUrl },\n doFetch,\n stdout,\n );\n return { platform, token, appId: cfg.app.id, env, fetch: doFetch, stdout };\n}\n\nexport async function interactiveConfirmation(\n message: string,\n dependencies: CliDependencies,\n): Promise<boolean> {\n if (dependencies.confirm) return dependencies.confirm(message);\n if (!process.stdin.isTTY || !process.stdout.isTTY) return false;\n const prompt = createInterface({ input: process.stdin, output: process.stdout });\n try {\n const answer = await prompt.question(`${message} [y/N] `);\n return /^y(?:es)?$/i.test(answer.trim());\n } finally {\n prompt.close();\n }\n}\n\nexport function requiredSecurityPositional(\n parsed: ParsedArgv,\n index: number,\n label: string,\n): string {\n const value = parsed.positionals[index];\n if (!value) throw new Error(`${label} is required`);\n return value;\n}\n\nexport function securityProfile(\n value: string | undefined,\n): HostedSecurityProfile | undefined {\n if (value === undefined) return undefined;\n if (value === \"odla\" || value === \"cloudflare-app\" || value === \"generic\") return value;\n throw new Error(\"--profile must be odla, cloudflare-app, or generic\");\n}\n","import { stringOpt, type ParsedArgv } from \"./argv\";\nimport type {\n HostedSecurityJob,\n HostedSecurityIntent,\n HostedSecurityPlan,\n HostedSecurityReport,\n HostedSecurityRoute,\n} from \"./security-hosted\";\n\nexport function printHostedSecurityPlan(\n out: Pick<typeof console, \"log\">,\n plan: HostedSecurityPlan,\n appId: string,\n): void {\n out.log(`Hosted security plan for ${appId}/${plan.env}: ${plan.ready ? \"ready\" : \"not ready\"}`);\n out.log(` plan digest: ${plan.planDigest}`);\n out.log(` consent/report/redaction: ${plan.consentContract} · ${plan.reportProjection} · ${plan.redactionContract}`);\n out.log(` prompt bundle: ${plan.promptBundle}`);\n printHostedSecurityPlanRoute(out, \"discovery\", plan.routes.discovery);\n printHostedSecurityPlanRoute(out, \"validation\", plan.routes.validation);\n out.log(` independent validation: ${plan.independent ? \"yes\" : \"no\"}`);\n out.log(\" source disclosure: bounded best-effort credential-pattern-redacted snippets may be sent through odla.ai to the selected providers\");\n out.log(` retained report: model-derived prose and repository-relative paths for up to ${plan.reportRetentionDays} days; treat it as sensitive`);\n out.log(\" target execution: disabled\");\n out.log(` to approve this exact plan, run security run --source <id> --plan-digest ${plan.planDigest} --ack-redacted-source`);\n}\n\nexport function printHostedSecurityIntent(\n out: Pick<typeof console, \"log\">,\n intent: HostedSecurityIntent,\n): void {\n out.log(`Hosted security execution intent for ${intent.appId}/${intent.env}:`);\n out.log(` execution digest: ${intent.executionDigest}`);\n out.log(` contract: ${intent.executionContract}`);\n out.log(` source: ${intent.repository} (${intent.sourceId})`);\n out.log(` ref: ${intent.requestedRef ?? `default branch (${intent.defaultBranch})`}`);\n out.log(` profile: ${intent.profile}`);\n out.log(` disclosure: ${intent.sourceDisclosure} · plan ${intent.planDigest}`);\n}\n\nexport function assertHostedSecurityPlanReady(plan: HostedSecurityPlan): void {\n const reasons: string[] = [];\n for (const [label, route] of Object.entries(plan.routes)) {\n if (!route.enabled) reasons.push(`${label} is disabled`);\n if (!route.credentialReady) reasons.push(`${label} provider credential is unavailable`);\n }\n if (!plan.independent) reasons.push(\"discovery and validation are not independently routed\");\n if (plan.ready && reasons.length === 0) return;\n if (!plan.ready && reasons.length === 0) reasons.push(\"the platform marked the plan unavailable\");\n throw new Error(`hosted security is not ready${reasons.length ? `: ${reasons.join(\"; \")}` : \"\"}. Ask a platform admin to update System AI security policy or credentials`);\n}\n\nexport function printHostedJob(\n out: Pick<typeof console, \"log\">,\n job: HostedSecurityJob,\n platform: string,\n appId: string,\n): void {\n out.log(`security job ${job.jobId}: ${job.status}`);\n out.log(` source: ${job.repository} ${job.requestedRef ?? \"default\"} -> ${job.commitSha ?? \"resolving\"}`);\n if (job.routes) {\n out.log(` discovery: ${routeLabel(job.routes.discovery)}`);\n out.log(` validation: ${routeLabel(job.routes.validation)}`);\n } else {\n out.log(\" routes: platform System AI policy (assigned when analysis starts)\");\n }\n out.log(` disclosure: ${job.sourceDisclosure} snippets · metadata retained up to ${job.retentionDays} days`);\n out.log(` consent: plan ${job.planDigest} · execution ${job.executionDigest} (${job.executionContract})`);\n if (job.coverageStatus || job.coverage) printHostedCoverage(out, job);\n if (job.counts) {\n out.log(` findings: confirmed=${job.counts.confirmed} needs_reproduction=${job.counts.needsReproduction} candidates=${job.counts.candidates}`);\n }\n if (job.errorCode) out.log(` failure: ${job.errorCode}`);\n const url = new URL(\"/studio\", platform);\n url.searchParams.set(\"app\", appId);\n url.searchParams.set(\"env\", job.env);\n url.searchParams.set(\"tab\", \"security\");\n url.searchParams.set(\"job\", job.jobId);\n out.log(` Studio: ${url.toString()}`);\n}\n\nexport function printHostedReport(\n out: Pick<typeof console, \"log\">,\n report: HostedSecurityReport,\n): void {\n out.log(`security report ${report.jobId}: ${report.repository}@${report.revision}`);\n out.log(` coverage: ${report.coverageStatus} cells=${report.metrics.coverageCells} shallow=${report.metrics.shallowCells} blocked=${report.metrics.blockedCells} unscheduled=${report.metrics.unscheduledCells} budget_exhausted=${report.metrics.budgetExhaustedCells}`);\n out.log(` findings: confirmed=${report.metrics.confirmed} needs_reproduction=${report.metrics.needsReproduction} candidates=${report.metrics.candidates} rejected=${report.metrics.rejected}`);\n out.log(` discovery: ${report.provenance.discovery?.provider ?? \"unknown\"}/${report.provenance.discovery?.model ?? \"unknown\"}`);\n out.log(` validation: ${report.provenance.validation?.provider ?? \"unknown\"}/${report.provenance.validation?.model ?? \"unknown\"} independent=${String(report.provenance.independentValidation)}`);\n for (const finding of report.findings) {\n const location = finding.locations[0];\n out.log(` [${finding.severity}] ${finding.title}${location ? ` (${location.path}:${location.line})` : \"\"} · ${finding.disposition}`);\n }\n for (const limitation of report.limitations) out.log(` limitation: ${limitation}`);\n}\n\nexport function enforceHostedReportGate(\n report: HostedSecurityReport,\n parsed: ParsedArgv,\n out: Pick<typeof console, \"log\">,\n emitSuccess: boolean,\n): void {\n const failOn = hostedSeverity(stringOpt(parsed.options[\"fail-on\"]) ?? \"high\", \"--fail-on\");\n const candidateValue = parsed.options[\"fail-on-candidates\"];\n const failOnCandidates = candidateValue === false\n ? undefined\n : hostedSeverity(stringOpt(candidateValue) ?? \"critical\", \"--fail-on-candidates\");\n const atOrAbove = (severity: HostedSecurityReport[\"findings\"][number][\"severity\"], threshold: string) =>\n HOSTED_SEVERITIES.indexOf(severity) >= HOSTED_SEVERITIES.indexOf(threshold as typeof severity);\n const confirmed = report.findings.filter((finding) =>\n finding.disposition === \"confirmed\" && atOrAbove(finding.severity, failOn));\n const leads = failOnCandidates\n ? report.findings.filter((finding) =>\n finding.disposition !== \"confirmed\" && atOrAbove(finding.severity, failOnCandidates))\n : [];\n // Stricter than the local gate on purpose: a hosted run always schedules AI coverage, so any\n // status other than \"complete\" — including \"not_run\" — means it silently did not happen, and this\n // reads coverageStatus off the wire. Fail closed. The local gate deliberately lets \"not_run\" pass\n // (see enforceLocalGate) because a credential-free passive scan legitimately produces it.\n const incomplete = report.coverageStatus !== \"complete\"\n && parsed.options[\"allow-incomplete\"] !== true;\n if (confirmed.length || leads.length || incomplete) {\n throw new Error(`hosted security gate failed: ${confirmed.length} confirmed >= ${failOn}; ${leads.length} leads >= ${failOnCandidates ?? \"disabled\"}${incomplete ? `; coverage ${report.coverageStatus}` : \"\"}`);\n }\n if (emitSuccess) {\n out.log(`security gate passed: 0 confirmed >= ${failOn}; 0 leads >= ${failOnCandidates ?? \"disabled\"}; coverage ${report.coverageStatus}. This is not proof that the application is secure.`);\n }\n}\n\nfunction printHostedSecurityPlanRoute(\n out: Pick<typeof console, \"log\">,\n label: string,\n route: HostedSecurityPlan[\"routes\"][\"discovery\"],\n): void {\n const readiness = route.enabled && route.credentialReady ? \"ready\" : [\n route.enabled ? undefined : \"disabled\",\n route.credentialReady ? undefined : \"credential unavailable\",\n ].filter(Boolean).join(\", \");\n out.log(` ${label}: ${route.provider}/${route.model} · policy v${route.policyVersion} · ${readiness}`);\n out.log(` bounds: ${route.maxCallsPerRun} calls/run · ${route.maxInputBytes} input bytes/call · ${route.maxOutputTokens} output tokens/call`);\n}\n\nfunction printHostedCoverage(out: Pick<typeof console, \"log\">, job: HostedSecurityJob): void {\n const coverage = job.coverage;\n out.log(` coverage: ${job.coverageStatus ?? \"pending\"}${coverage?.completeCells !== undefined ? ` ${coverage.completeCells}/${coverage.totalCells ?? \"?\"}` : \"\"}${coverage?.shallowCells ? ` shallow=${coverage.shallowCells}` : \"\"}${coverage?.blockedCells ? ` blocked=${coverage.blockedCells}` : \"\"}${coverage?.unscheduledCells ? ` unscheduled=${coverage.unscheduledCells}` : \"\"}${coverage?.budgetExhaustedCells ? ` budget_exhausted=${coverage.budgetExhaustedCells}` : \"\"}`);\n}\n\nfunction routeLabel(route: HostedSecurityRoute): string {\n return `${route.provider}/${route.model}${route.policyVersion ? ` policy v${route.policyVersion}` : \"\"}`;\n}\n\nconst HOSTED_SEVERITIES = [\"informational\", \"low\", \"medium\", \"high\", \"critical\"] as const;\n\nfunction hostedSeverity(value: string, flag: string): typeof HOSTED_SEVERITIES[number] {\n if (HOSTED_SEVERITIES.includes(value as typeof HOSTED_SEVERITIES[number])) {\n return value as typeof HOSTED_SEVERITIES[number];\n }\n throw new Error(`${flag} must be informational, low, medium, high, or critical`);\n}\n","import { findingsAtOrAbove, type Severity } from \"@odla-ai/security\";\nimport { getScopedPlatformToken } from \"./admin-ai\";\nimport {\n assertArgs,\n numberOpt,\n requiredString,\n stringOpt,\n type ParsedArgv,\n} from \"./argv\";\nimport { loadProjectConfig } from \"./config\";\nimport type { CliDependencies } from \"./cli\";\nimport { hostedSecurityContext, securityProfile } from \"./security-command-context\";\nimport {\n assertHostedSecurityPlanReady,\n enforceHostedReportGate,\n printHostedJob,\n printHostedReport,\n printHostedSecurityIntent,\n printHostedSecurityPlan,\n} from \"./security-command-output\";\nimport { runHostedSecurity } from \"./security\";\nimport {\n followHostedSecurityJob,\n getHostedSecurityIntent,\n getHostedSecurityPlan,\n getHostedSecurityReport,\n startHostedSecurityJob,\n} from \"./security-hosted\";\nimport { getDeveloperToken, platformAudience } from \"./token\";\n\nexport async function runSourceSecurityCommand(\n parsed: ParsedArgv,\n dependencies: CliDependencies,\n sourceId: string,\n): Promise<void> {\n assertArgs(parsed, [\n \"config\", \"env\", \"profile\", \"platform\", \"source\", \"ref\", \"follow\", \"email\", \"open\", \"json\",\n \"ack-redacted-source\", \"plan-digest\", \"fail-on\", \"fail-on-candidates\", \"allow-incomplete\",\n ], 2);\n const follow = parsed.options.follow !== false;\n if (!follow && (parsed.options[\"fail-on\"] !== undefined\n || parsed.options[\"fail-on-candidates\"] !== undefined\n || parsed.options[\"allow-incomplete\"] !== undefined)) {\n throw new Error(\"hosted security gate options require following the job; remove --no-follow\");\n }\n const acknowledgedDigest = requiredString(parsed.options[\"plan-digest\"], \"--plan-digest\");\n const context = await hostedSecurityContext(parsed, dependencies);\n const plan = await getHostedSecurityPlan(context);\n if (parsed.options.json !== true) printHostedSecurityPlan(context.stdout, plan, context.appId);\n assertHostedSecurityPlanReady(plan);\n if (acknowledgedDigest !== plan.planDigest) {\n throw new Error(`--plan-digest does not match the current hosted security plan (${plan.planDigest}); review and explicitly acknowledge the current digest`);\n }\n const requestedRef = stringOpt(parsed.options.ref);\n const requestedProfile = securityProfile(stringOpt(parsed.options.profile));\n const preview = await getHostedSecurityIntent({\n ...context,\n sourceId,\n ref: requestedRef,\n profile: requestedProfile,\n });\n if (parsed.options.json !== true) printHostedSecurityIntent(context.stdout, preview.intent);\n if (preview.plan.planDigest !== plan.planDigest || preview.intent.planDigest !== plan.planDigest) {\n throw new Error(`hosted security plan changed while previewing execution (${preview.plan.planDigest}); review and explicitly acknowledge the current plan digest`);\n }\n const job = await startHostedSecurityJob({\n ...context,\n sourceId,\n ref: requestedRef,\n profile: requestedProfile,\n clientRequestId: crypto.randomUUID(),\n sourceDisclosureAck: parsed.options[\"ack-redacted-source\"] === true ? \"redacted\" : undefined,\n expectedPlanDigest: plan.planDigest,\n expectedExecutionDigest: preview.intent.executionDigest,\n expectedPolicyVersions: {\n discovery: plan.routes.discovery.policyVersion,\n validation: plan.routes.validation.policyVersion,\n },\n });\n const result = follow\n ? await followHostedSecurityJob({\n ...context,\n jobId: job.jobId,\n wait: dependencies.pollWait,\n onUpdate: parsed.options.json === true\n ? undefined\n : (value) => printHostedJob(context.stdout, value, context.platform, context.appId),\n })\n : job;\n if (!follow) {\n if (parsed.options.json === true) {\n context.stdout.log(JSON.stringify({ plan, intent: preview.intent, job: result }, null, 2));\n } else {\n printHostedJob(context.stdout, result, context.platform, context.appId);\n }\n return;\n }\n if (result.status !== \"completed\") {\n if (parsed.options.json === true) {\n context.stdout.log(JSON.stringify({ plan, intent: preview.intent, job: result }, null, 2));\n }\n throw new Error(`hosted security job ${result.jobId} ended ${result.status}${result.errorCode ? `: ${result.errorCode}` : \"\"}`);\n }\n const report = await getHostedSecurityReport({ ...context, jobId: result.jobId });\n if (parsed.options.json === true) {\n context.stdout.log(JSON.stringify({ plan, intent: preview.intent, job: result, report }, null, 2));\n } else {\n printHostedReport(context.stdout, report);\n }\n enforceHostedReportGate(report, parsed, context.stdout, parsed.options.json !== true);\n}\n\nexport async function runLocalSecurityCommand(\n parsed: ParsedArgv,\n dependencies: CliDependencies,\n): Promise<void> {\n if (parsed.options.source === true) {\n throw new Error(\"--source requires a source id; run security sources first\");\n }\n assertArgs(parsed, [\n \"config\", \"env\", \"out\", \"profile\", \"max-hunt-tasks\", \"run-id\", \"platform\",\n \"self\", \"ack-redacted-source\", \"email\", \"open\", \"fail-on\", \"fail-on-candidates\", \"allow-incomplete\",\n ], 3);\n const configPath = stringOpt(parsed.options.config) ?? \"odla.config.mjs\";\n const selfAudit = parsed.options.self === true;\n const open = parsed.options.open === false\n ? false\n : parsed.options.open === true ? true : undefined;\n const platform = stringOpt(parsed.options.platform);\n const doFetch = dependencies.fetch ?? fetch;\n const out = dependencies.stdout ?? console;\n const result = await runHostedSecurity({\n configPath,\n selfAudit,\n target: parsed.positionals[2],\n out: stringOpt(parsed.options.out),\n env: stringOpt(parsed.options.env),\n profile: securityProfile(stringOpt(parsed.options.profile)),\n maxHuntTasks: numberOpt(parsed.options[\"max-hunt-tasks\"], \"--max-hunt-tasks\"),\n runId: stringOpt(parsed.options[\"run-id\"]),\n platform,\n sourceDisclosureAck: parsed.options[\"ack-redacted-source\"] === true ? \"redacted\" : undefined,\n fetch: doFetch,\n stdout: out,\n getToken: async (request) => {\n if (request.scope === \"platform:security:self\") {\n return getScopedPlatformToken({\n platform: request.platform,\n scope: request.scope,\n email: stringOpt(parsed.options.email),\n open,\n fetch: doFetch,\n stdout: out,\n openApprovalUrl: dependencies.openUrl,\n });\n }\n const cfg = await loadProjectConfig(configPath);\n if (platformAudience(cfg.platformUrl) !== platformAudience(request.platform)) {\n throw new Error(\"--platform cannot reuse a project developer token from another platform; update odla.config.mjs and authenticate there\");\n }\n return getDeveloperToken(\n cfg,\n { configPath, email: stringOpt(parsed.options.email), open, openApprovalUrl: dependencies.openUrl },\n doFetch,\n out,\n );\n },\n });\n enforceLocalGate(result.report, parsed);\n}\n\nfunction enforceLocalGate(\n report: Parameters<typeof findingsAtOrAbove>[0],\n parsed: ParsedArgv,\n): void {\n const failOn = severityOpt(stringOpt(parsed.options[\"fail-on\"]) ?? \"high\", \"--fail-on\");\n const candidateValue = parsed.options[\"fail-on-candidates\"];\n const failOnCandidates = candidateValue === false\n ? undefined\n : severityOpt(stringOpt(candidateValue) ?? \"critical\", \"--fail-on-candidates\");\n const confirmed = findingsAtOrAbove(report, failOn);\n const leads = failOnCandidates\n ? findingsAtOrAbove(report, failOnCandidates, true)\n .filter((finding) => finding.disposition !== \"confirmed\")\n : [];\n // \"not_run\" must pass: a credential-free passive scan has no discovery reasoner, so coverage.ts\n // reports not_run, and README advertises exactly that CI recipe without --allow-incomplete.\n // Gating it here would break every deterministic-only run. The no-false-assurance job belongs to\n // the reporter, which prints that zero AI coverage cells is not evidence of complete coverage.\n // The hosted gate is stricter (see enforceHostedReportGate) because there AI always runs.\n const incomplete = report.coverageStatus === \"incomplete\"\n && parsed.options[\"allow-incomplete\"] !== true;\n if (confirmed.length || leads.length || incomplete) {\n throw new Error(`hosted security gate failed: ${confirmed.length} confirmed >= ${failOn}; ${leads.length} leads >= ${failOnCandidates ?? \"disabled\"}${incomplete ? \"; coverage incomplete\" : \"\"}`);\n }\n}\n\nfunction severityOpt(value: string, flag: string): Severity {\n if ([\"informational\", \"low\", \"medium\", \"high\", \"critical\"].includes(value)) {\n return value as Severity;\n }\n throw new Error(`${flag} must be informational, low, medium, high, or critical`);\n}\n","import { isAbsolute, relative, resolve, sep } from \"node:path\";\nimport {\n cloudflareAppProfile,\n createPlatformSecurityReasoners,\n createSecurityHarness,\n genericProfile,\n odlaProfile,\n securityFingerprint,\n type PlatformSecurityRun,\n type SecurityProfile,\n type SecurityReport,\n type SecurityRoleCallBudgetUsage,\n} from \"@odla-ai/security\";\nimport { FileRunStore, snapshotDirectory, writeSecurityArtifacts } from \"@odla-ai/security/node\";\nimport { loadProjectConfig } from \"./config\";\n\n/** Built-in security coverage profile selected for a hosted reasoning run. */\nexport type HostedSecurityProfile = \"odla\" | \"cloudflare-app\" | \"generic\";\n\n/** Exact attribution and authorization need supplied to a lazy token callback. */\nexport interface HostedSecurityTokenRequest {\n platform: string;\n appId: string;\n env: string;\n selfAudit: boolean;\n /** Self-audit asks the caller for an explicitly scoped platform credential. */\n /** Ordinary app runs use owner authority and therefore request no platform scope. */\n scope: \"platform:security:self\" | null;\n}\n\n/** Local snapshot/orchestration controls for an app-attributed hosted security\n * run. The platform supplies model routes and provider credentials. */\nexport interface RunHostedSecurityOptions {\n /** Project config; loaded for customer-app runs and ignored for self-audit. */\n configPath?: string;\n /** Scan odla itself under the protected odla-ai/prod identity. */\n selfAudit?: boolean;\n /** Repository directory to snapshot. Defaults to the config root or cwd for self-audit. */\n target?: string;\n /** Private artifact directory. Defaults to `<target>/.odla/security/hosted`. */\n out?: string;\n /** Customer environment. Must be declared in config. Self-audit always uses prod. */\n env?: string;\n profile?: HostedSecurityProfile;\n maxHuntTasks?: number;\n /** Exact acknowledgement required before any source capture or network call. */\n sourceDisclosureAck?: \"redacted\";\n /** Optional client correlation id; the platform returns the authoritative run id. */\n runId?: string;\n /** Platform override. Customer runs otherwise use config.platformUrl. */\n platform?: string;\n /** Injected app credential; for self-audit this must be explicitly scoped by the caller. */\n token?: string;\n /** Lazy token acquisition. Receives the exact app/env and required scope. */\n getToken?: (request: HostedSecurityTokenRequest) => string | Promise<string>;\n fetch?: typeof fetch;\n signal?: AbortSignal;\n stdout?: Pick<typeof console, \"log\" | \"error\">;\n}\n\n/** Completed local report, public platform run metadata, and private artifact path. */\nexport interface HostedSecurityResult {\n report: SecurityReport;\n run: Readonly<PlatformSecurityRun>;\n output: string;\n}\n\n/**\n * Run the hosted, redacted-source security harness for an odla app or odla's\n * protected self-audit identity. Provider/model selection and provider secrets\n * remain platform-owned; this function accepts only an app/scoped bearer and\n * the opaque role grants remain inside @odla-ai/security's reasoner closures.\n */\nexport async function runHostedSecurity(options: RunHostedSecurityOptions): Promise<HostedSecurityResult> {\n if (options.sourceDisclosureAck !== \"redacted\") {\n throw new Error(\"Hosted security requires sourceDisclosureAck=redacted before repository source may leave this process\");\n }\n\n const selfAudit = options.selfAudit === true;\n const cfg = selfAudit ? undefined : await loadProjectConfig(options.configPath ?? \"odla.config.mjs\");\n const appId = selfAudit ? \"odla-ai\" : cfg!.app.id;\n const env = selfAudit ? \"prod\" : selectEnv(options.env, cfg!.envs, cfg!.configPath, cfg!.rootDir);\n const platform = options.platform ?? cfg?.platformUrl ?? \"https://odla.ai\";\n const target = resolve(options.target ?? cfg?.rootDir ?? \".\");\n const output = resolve(options.out ?? resolve(target, \".odla/security/hosted\"));\n const outputRelative = relative(target, output).split(sep).join(\"/\");\n if (!outputRelative) throw new Error(\"Hosted security output cannot be the repository root\");\n // This is the desired first-pass ceiling. The hosted reasoner's immutable\n // call budget automatically reserves recon, caps hunts, then funds retries.\n const profile = profileFor(options.profile ?? \"odla\", options.maxHuntTasks ?? 12);\n\n const tokenRequest: HostedSecurityTokenRequest = {\n platform,\n appId,\n env,\n selfAudit,\n scope: selfAudit ? \"platform:security:self\" : null,\n };\n const token = await injectedToken(options, tokenRequest);\n const snapshot = await snapshotDirectory(target, {\n exclude: !outputRelative.startsWith(\"../\") && !isAbsolute(outputRelative) ? [outputRelative] : [],\n });\n const hosted = await createPlatformSecurityReasoners({\n platform,\n token,\n appId,\n env,\n repository: snapshot.repository,\n revision: snapshot.revision,\n snapshotDigest: snapshot.digest,\n sourceDisclosure: \"redacted\",\n clientRunId: options.runId ?? crypto.randomUUID(),\n ...(selfAudit ? { selfAudit: { enabled: true as const, subject: \"service:odla-security-self-audit\" } } : {}),\n fetch: options.fetch,\n signal: options.signal,\n });\n const harness = createSecurityHarness({\n profile,\n store: new FileRunStore(resolve(output, \"state\")),\n discoveryReasoner: hosted.discoveryReasoner,\n validationReasoner: hosted.validationReasoner,\n policy: {\n modelSourceDisclosure: \"redacted\",\n active: false,\n allowNetwork: false,\n },\n });\n const report = await harness.run(snapshot, { runId: hosted.run.runId, signal: options.signal });\n await writeSecurityArtifacts(output, report);\n const reportDigest = await securityFingerprint(report);\n await hosted.complete({\n reportDigest,\n coverageStatus: report.coverageStatus,\n confirmed: report.metrics.confirmed,\n candidates: report.metrics.candidates,\n }, { signal: options.signal });\n printSummary(options.stdout ?? console, appId, env, hosted.run, report, output);\n return Object.freeze({ report, run: hosted.run, output });\n}\n\nfunction selectEnv(requested: string | undefined, declared: string[], configPath: string, rootDir: string): string {\n const env = requested ?? (declared.includes(\"dev\") ? \"dev\" : declared[0]);\n if (!env || !declared.includes(env)) {\n const shown = relative(rootDir, configPath) || configPath;\n throw new Error(`env \"${env ?? \"\"}\" is not declared in ${shown}`);\n }\n return env;\n}\n\nasync function injectedToken(options: RunHostedSecurityOptions, request: HostedSecurityTokenRequest): Promise<string> {\n const value = options.token ?? await options.getToken?.(Object.freeze({ ...request }));\n if (typeof value !== \"string\" || value.length < 8 || value.length > 8_192 || /\\s|[\\u0000-\\u001f\\u007f]/.test(value)) {\n throw new Error(\n request.selfAudit\n ? \"Self-audit requires an injected, scoped platform security token\"\n : \"Hosted security requires an injected app developer token or getToken callback\",\n );\n }\n return value;\n}\n\nfunction profileFor(name: HostedSecurityProfile, maxHuntTasks: number | undefined): SecurityProfile {\n const profile = name === \"odla\"\n ? odlaProfile()\n : name === \"cloudflare-app\"\n ? cloudflareAppProfile()\n : name === \"generic\"\n ? genericProfile()\n : undefined;\n if (!profile) throw new Error(`unknown security profile \"${String(name)}\"`);\n if (maxHuntTasks === undefined) return profile;\n if (!Number.isSafeInteger(maxHuntTasks) || maxHuntTasks < 1) throw new Error(\"maxHuntTasks must be a positive integer\");\n return { ...profile, maxHuntTasks };\n}\n\nfunction printSummary(\n out: Pick<typeof console, \"log\" | \"error\">,\n appId: string,\n env: string,\n run: Readonly<PlatformSecurityRun>,\n report: SecurityReport,\n output: string,\n): void {\n const complete = report.coverage.filter((cell) => cell.state === \"complete\").length;\n out.log(`security: ${appId}/${env} run=${run.runId} profile=${run.profileVersion}`);\n out.log(` discovery: ${run.discovery.identity.provider}/${run.discovery.identity.model}`);\n out.log(` validation: ${run.validation.identity.provider}/${run.validation.identity.model}`);\n out.log(` coverage: ${report.coverageStatus} ${complete}/${report.coverage.length} blocked=${report.metrics.blockedCells} shallow=${report.metrics.shallowCells} unscheduled=${report.metrics.unscheduledCells} budget_exhausted=${report.metrics.budgetExhaustedCells}`);\n if (report.callBudget) out.log(` calls: discovery=${formatBudget(report.callBudget.discovery)} validation=${formatBudget(report.callBudget.validation)}`);\n out.log(` findings: confirmed=${report.metrics.confirmed} needs_reproduction=${report.metrics.needsReproduction} candidates=${report.metrics.candidates}`);\n out.log(` report: ${resolve(output, \"REPORT.md\")}`);\n}\n\nfunction formatBudget(usage: SecurityRoleCallBudgetUsage | undefined): string {\n return usage ? `${usage.usedCalls}/${usage.maxCalls} skipped=${usage.skippedCalls}` : \"caller-managed\";\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { openUrl } from \"./open\";\nimport {\n githubRepositoryName,\n hostedIdentifier,\n hostedPollInterval,\n hostedPollTimeout,\n requestHostedSecurityJson,\n trustedGitHubInstallUrl,\n waitForHostedPoll,\n} from \"./security-hosted-request\";\nimport type {\n ConnectGitHubSecuritySourceOptions,\n DisconnectGitHubSecuritySourceOptions,\n GitHubConnectionAttempt,\n GitHubConnectionStatus,\n GitHubSecuritySource,\n ListGitHubSecuritySourcesOptions,\n} from \"./security-hosted-types\";\n\n/** Begin GitHub App installation, launch its server-issued GitHub URL, and\n * poll the exact attempt until the callback has connected a source. */\nexport async function connectGitHubSecuritySource(\n options: ConnectGitHubSecuritySourceOptions,\n): Promise<GitHubConnectionStatus> {\n const out = options.stdout ?? console;\n const repository = githubRepositoryName(options.repository);\n const attempt = await requestHostedSecurityJson<GitHubConnectionAttempt>(\n options,\n \"/registry/github/connect\",\n {\n method: \"POST\",\n body: JSON.stringify({\n appId: hostedIdentifier(options.appId, \"appId\"),\n env: hostedIdentifier(options.env, \"env\"),\n repository,\n }),\n },\n \"start GitHub connection\",\n );\n const serverExpiry = Date.parse(attempt?.expiresAt ?? \"\");\n if (!attempt?.attemptId || !attempt.installUrl || !Number.isFinite(serverExpiry)) {\n throw new Error(\"odla.ai returned an invalid GitHub connection attempt\");\n }\n const installUrl = trustedGitHubInstallUrl(attempt.installUrl);\n out.log(`GitHub approval: ${installUrl}`);\n if (options.open !== false) {\n await (options.openInstallUrl ?? openUrl)(installUrl);\n out.log(\"github: opened installation approval in your browser\");\n }\n const interval = hostedPollInterval(options.pollIntervalMs);\n const now = options.now ?? Date.now;\n const deadline = Math.min(serverExpiry, now() + hostedPollTimeout(options.pollTimeoutMs));\n const wait = options.wait ?? waitForHostedPoll;\n while (true) {\n const state = await requestHostedSecurityJson<GitHubConnectionStatus>(\n options,\n `/registry/github/connect/${encodeURIComponent(attempt.attemptId)}`,\n {},\n \"check GitHub connection\",\n );\n if (state.status !== \"pending\") {\n if (state.status === \"connected\") return state;\n throw new Error(`GitHub connection ${state.status}${state.failureCode ? `: ${state.failureCode}` : \"\"}`);\n }\n if (now() >= deadline) throw new Error(\"GitHub connection approval timed out\");\n await wait(Math.min(interval, Math.max(0, deadline - now())), options.signal);\n }\n}\n\n/** List repository sources the current app owner connected for one environment. */\nexport async function listGitHubSecuritySources(\n options: ListGitHubSecuritySourcesOptions,\n): Promise<GitHubSecuritySource[]> {\n const appId = hostedIdentifier(options.appId, \"appId\");\n const env = hostedIdentifier(options.env, \"env\");\n const body = await requestHostedSecurityJson<{ sources: GitHubSecuritySource[] }>(\n options,\n `/registry/apps/${encodeURIComponent(appId)}/github/sources?env=${encodeURIComponent(env)}`,\n {},\n \"list GitHub security sources\",\n );\n return Array.isArray(body.sources) ? body.sources : [];\n}\n\n/** Revoke odla's use of one saved source without requiring a GitHub-side App\n * uninstall. The server marks the source deleted and rejects new jobs. */\nexport async function disconnectGitHubSecuritySource(\n options: DisconnectGitHubSecuritySourceOptions,\n): Promise<void> {\n const appId = hostedIdentifier(options.appId, \"appId\");\n const sourceId = hostedIdentifier(options.sourceId, \"sourceId\");\n await requestHostedSecurityJson<{ ok: true }>(\n options,\n `/registry/apps/${encodeURIComponent(appId)}/github/sources/${encodeURIComponent(sourceId)}`,\n { method: \"DELETE\" },\n \"disconnect GitHub security source\",\n );\n}\n\n/** Parse an HTTPS, ssh://, or git@github.com origin without retaining embedded\n * credentials. Only github.com owner/name remotes are accepted. */\nexport function repositoryFromGitRemote(remoteInput: string): string {\n const remote = remoteInput.trim();\n const scp = /^git@github\\.com:([^/\\s]+)\\/([^/\\s]+?)\\/?$/.exec(remote);\n if (scp) return githubRepositoryName(`${scp[1]}/${scp[2]!.replace(/\\.git$/, \"\")}`);\n let url: URL;\n try {\n url = new URL(remote);\n } catch {\n throw new Error(\"origin must be a github.com HTTPS or SSH repository URL\");\n }\n if (url.hostname !== \"github.com\" || (url.protocol !== \"https:\" && url.protocol !== \"ssh:\")) {\n throw new Error(\"origin must be a github.com HTTPS or SSH repository URL\");\n }\n if (url.password || (url.protocol === \"https:\" && url.username) || url.search || url.hash) {\n throw new Error(\"credential-bearing GitHub origin URLs are not accepted\");\n }\n const parts = url.pathname.replace(/^\\/+|\\/+$/g, \"\").split(\"/\");\n if (parts.length !== 2) {\n throw new Error(\"origin must identify one GitHub owner/name repository\");\n }\n return githubRepositoryName(`${parts[0]}/${parts[1]!.replace(/\\.git$/, \"\")}`);\n}\n\n/** Read the current repository's origin without invoking a shell. */\nexport async function inferGitHubRepository(\n cwd = process.cwd(),\n readOrigin: (cwd: string) => Promise<string> = defaultReadOrigin,\n): Promise<string> {\n let remote: string;\n try {\n remote = await readOrigin(cwd);\n } catch {\n throw new Error(\"Could not read git origin; pass --repo owner/name\");\n }\n return repositoryFromGitRemote(remote);\n}\n\nasync function defaultReadOrigin(cwd: string): Promise<string> {\n const result = await promisify(execFile)(\n \"git\",\n [\"remote\", \"get-url\", \"origin\"],\n { cwd, encoding: \"utf8\" },\n );\n return result.stdout;\n}\n","import { platformAudience } from \"./token\";\nimport type {\n HostedSecurityPlan,\n HostedSecurityPlanRoute,\n HostedSecurityRequestOptions,\n} from \"./security-hosted-types\";\n\nexport async function requestHostedSecurityJson<T>(\n options: HostedSecurityRequestOptions,\n path: string,\n init: RequestInit,\n action: string,\n): Promise<T> {\n const platform = platformAudience(options.platform);\n const token = hostedSecurityCredential(options.token);\n const requestInit = {\n ...init,\n redirect: \"error\",\n credentials: \"omit\",\n cache: \"no-store\",\n signal: options.signal,\n headers: {\n authorization: `Bearer ${token}`,\n \"content-type\": \"application/json\",\n ...init.headers,\n },\n } as RequestInit;\n const response = await (options.fetch ?? fetch)(new URL(path, platform), requestInit);\n const body = await response.json().catch(() => ({})) as T & {\n error?: { code?: string; message?: string };\n };\n if (!response.ok) {\n const code = optionalHostedText(body.error?.code, \"error code\", 128);\n const message = optionalHostedText(body.error?.message, \"error message\", 300);\n throw new Error(`${action} failed (${response.status})${code ? ` ${code}` : \"\"}${message ? `: ${message}` : \"\"}`);\n }\n return body;\n}\n\nexport function hostedIdentifier(value: string, name: string): string {\n const result = optionalHostedText(value, name, 180);\n if (!result || !/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(result)) {\n throw new Error(`${name} is invalid`);\n }\n return result;\n}\n\nexport function positivePolicyVersion(value: unknown, name: string): number {\n if (!Number.isSafeInteger(value) || (value as number) < 1) {\n throw new Error(`${name} is invalid`);\n }\n return value as number;\n}\n\nexport function optionalHostedText(\n value: unknown,\n name: string,\n maxLength: number,\n): string | undefined {\n if (value === undefined || value === null || value === \"\") return undefined;\n if (typeof value !== \"string\" || value.length > maxLength || /[\\u0000-\\u001f\\u007f]/.test(value)) {\n throw new Error(`${name} is invalid`);\n }\n return value;\n}\n\nexport function githubRepositoryName(value: string): string {\n if (typeof value !== \"string\" || value.length > 201) {\n throw new Error(\"repository must be owner/name\");\n }\n const parts = value.split(\"/\");\n const owner = parts[0] ?? \"\";\n const name = (parts[1] ?? \"\").replace(/\\.git$/i, \"\");\n if (parts.length !== 2\n || !/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,98}[A-Za-z0-9])?$/.test(owner)\n || !/^[A-Za-z0-9_.-]{1,100}$/.test(name)\n || name === \".\" || name === \"..\") {\n throw new Error(\"repository must be owner/name\");\n }\n return `${owner}/${name}`;\n}\n\nexport function trustedGitHubInstallUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new Error(\"odla.ai returned an invalid GitHub installation URL\");\n }\n if (url.protocol !== \"https:\" || url.hostname !== \"github.com\" || url.username || url.password) {\n throw new Error(\"odla.ai returned an untrusted GitHub installation URL\");\n }\n return url.toString();\n}\n\nexport function hostedPollInterval(value = 2_000): number {\n if (!Number.isSafeInteger(value) || value < 100 || value > 30_000) {\n throw new Error(\"poll interval must be 100-30000ms\");\n }\n return value;\n}\n\nexport function hostedPollTimeout(value = 10 * 60_000): number {\n if (!Number.isSafeInteger(value) || value < 1_000 || value > 60 * 60_000) {\n throw new Error(\"poll timeout must be 1000-3600000ms\");\n }\n return value;\n}\n\nexport async function waitForHostedPoll(\n milliseconds: number,\n signal?: AbortSignal,\n): Promise<void> {\n if (signal?.aborted) throw signal.reason ?? new DOMException(\"aborted\", \"AbortError\");\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(resolve, milliseconds);\n signal?.addEventListener(\"abort\", () => {\n clearTimeout(timer);\n reject(signal.reason ?? new DOMException(\"aborted\", \"AbortError\"));\n }, { once: true });\n });\n}\n\nexport function isValidHostedSecurityPlan(\n value: HostedSecurityPlan,\n env: string,\n): boolean {\n if (!value || value.env !== env || !/^sha256:[a-f0-9]{64}$/.test(value.planDigest)\n || value.consentContract !== \"odla.hosted-security-consent.v1\"\n || value.reportProjection !== \"odla.hosted-security-report.v1\"\n || value.redactionContract !== \"odla.best-effort-credential-pattern-redaction.v1\"\n || typeof value.promptBundle !== \"string\" || value.promptBundle.length < 1 || value.promptBundle.length > 100\n || typeof value.ready !== \"boolean\"\n || typeof value.independent !== \"boolean\" || value.sourceDisclosure !== \"redacted\"\n || value.targetExecution !== false || !Number.isSafeInteger(value.reportRetentionDays)\n || value.reportRetentionDays < 1) return false;\n const validRoute = (\n route: HostedSecurityPlanRoute | undefined,\n purpose: HostedSecurityPlanRoute[\"purpose\"],\n ) => !!route\n && route.purpose === purpose\n && typeof route.enabled === \"boolean\"\n && typeof route.credentialReady === \"boolean\"\n && typeof route.provider === \"string\" && route.provider.length > 0 && route.provider.length <= 100\n && typeof route.model === \"string\" && route.model.length > 0 && route.model.length <= 200\n && Number.isSafeInteger(route.policyVersion) && route.policyVersion >= 1\n && Number.isSafeInteger(route.maxCallsPerRun) && route.maxCallsPerRun >= 1\n && Number.isSafeInteger(route.maxInputBytes) && route.maxInputBytes >= 1\n && Number.isSafeInteger(route.maxOutputTokens) && route.maxOutputTokens >= 1;\n return validRoute(value.routes?.discovery, \"security.discovery\")\n && validRoute(value.routes?.validation, \"security.validation\");\n}\n\nfunction hostedSecurityCredential(value: string): string {\n if (typeof value !== \"string\" || value.length < 8 || value.length > 8_192\n || /\\s|[\\u0000-\\u001f\\u007f]/.test(value)) {\n throw new Error(\"Hosted security requires an injected odla developer token\");\n }\n return value;\n}\n","import {\n hostedIdentifier,\n isValidHostedSecurityPlan,\n optionalHostedText,\n requestHostedSecurityJson,\n} from \"./security-hosted-request\";\nimport type {\n GetHostedSecurityIntentOptions,\n HostedSecurityIntent,\n HostedSecurityIntentResponse,\n} from \"./security-hosted-types\";\n\n/** Fetch the atomic processing-plan and source/ref/profile execution preview. */\nexport async function getHostedSecurityIntent(\n options: GetHostedSecurityIntentOptions,\n): Promise<HostedSecurityIntentResponse> {\n const appId = hostedIdentifier(options.appId, \"appId\");\n const env = hostedIdentifier(options.env, \"env\");\n const sourceId = hostedIdentifier(options.sourceId, \"sourceId\");\n const ref = optionalHostedText(options.ref, \"ref\", 255);\n const query = new URLSearchParams({ env, sourceId });\n if (ref) query.set(\"ref\", ref);\n if (options.profile) query.set(\"profile\", options.profile);\n const response = await requestHostedSecurityJson<HostedSecurityIntentResponse>(\n options,\n `/registry/apps/${encodeURIComponent(appId)}/security/intent?${query.toString()}`,\n {},\n \"read hosted security execution intent\",\n );\n if (!isValidHostedSecurityPlan(response.plan, env)\n || !isValidIntent(response.intent, { appId, env, sourceId })) {\n throw new Error(\"odla.ai returned an invalid hosted security execution intent\");\n }\n if (response.intent.planDigest !== response.plan.planDigest) {\n throw new Error(\"odla.ai returned a hosted security intent for a different processing plan\");\n }\n return response;\n}\n\nfunction isValidIntent(\n value: HostedSecurityIntent | undefined,\n expected: { appId: string; env: string; sourceId: string },\n): value is HostedSecurityIntent {\n return !!value\n && value.executionContract === \"odla.hosted-security-execution-consent.v1\"\n && /^sha256:[a-f0-9]{64}$/.test(value.executionDigest)\n && /^sha256:[a-f0-9]{64}$/.test(value.planDigest)\n && value.appId === expected.appId && value.env === expected.env && value.sourceId === expected.sourceId\n && typeof value.repository === \"string\" && value.repository.length > 2 && value.repository.length <= 201\n && typeof value.defaultBranch === \"string\" && value.defaultBranch.length > 0 && value.defaultBranch.length <= 255\n && typeof value.requestedRef === \"string\" && value.requestedRef.length > 0\n && value.requestedRef.length <= 255 && !/[\\u0000-\\u001f\\u007f]/.test(value.requestedRef)\n && [\"odla\", \"cloudflare-app\", \"generic\"].includes(value.profile)\n && value.sourceDisclosure === \"redacted\";\n}\n","import {\n hostedIdentifier,\n hostedPollInterval,\n hostedPollTimeout,\n isValidHostedSecurityPlan,\n optionalHostedText,\n positivePolicyVersion,\n requestHostedSecurityJson,\n waitForHostedPoll,\n} from \"./security-hosted-request\";\nimport type {\n FollowHostedSecurityJobOptions,\n GetHostedSecurityJobOptions,\n HostedSecurityJob,\n HostedSecurityJobStatus,\n HostedSecurityPlan,\n HostedSecurityReport,\n ListGitHubSecuritySourcesOptions,\n ListHostedSecurityJobsOptions,\n StartHostedSecurityJobOptions,\n} from \"./security-hosted-types\";\n\n/** Read the admin-selected routes, budgets, readiness, disclosure boundary,\n * and digest that must be acknowledged when a hosted review is enqueued. */\nexport async function getHostedSecurityPlan(\n options: ListGitHubSecuritySourcesOptions,\n): Promise<HostedSecurityPlan> {\n const appId = hostedIdentifier(options.appId, \"appId\");\n const env = hostedIdentifier(options.env, \"env\");\n const plan = await requestHostedSecurityJson<HostedSecurityPlan>(\n options,\n `/registry/apps/${encodeURIComponent(appId)}/security/plan?env=${encodeURIComponent(env)}`,\n {},\n \"read hosted security disclosure plan\",\n );\n if (!isValidHostedSecurityPlan(plan, env)) {\n throw new Error(\"odla.ai returned an invalid hosted security disclosure plan\");\n }\n return plan;\n}\n\n/** Enqueue a commit-pinned server-side review. The server resolves sourceId to\n * its saved GitHub App installation; clients cannot choose an installation or\n * pass a PAT. */\nexport async function startHostedSecurityJob(\n options: StartHostedSecurityJobOptions,\n): Promise<HostedSecurityJob> {\n if (options.sourceDisclosureAck !== \"redacted\") {\n throw new Error(\"Hosted GitHub security requires sourceDisclosureAck=redacted; repository access alone is not disclosure consent\");\n }\n const appId = hostedIdentifier(options.appId, \"appId\");\n const env = hostedIdentifier(options.env, \"env\");\n const sourceId = hostedIdentifier(options.sourceId, \"sourceId\");\n const ref = optionalHostedText(options.ref, \"ref\", 255);\n const expectedPlanDigest = securityPlanDigest(options.expectedPlanDigest);\n const expectedExecutionDigest = securityExecutionDigest(options.expectedExecutionDigest);\n const expectedPolicyVersions = {\n discovery: positivePolicyVersion(\n options.expectedPolicyVersions?.discovery,\n \"expected discovery policy version\",\n ),\n validation: positivePolicyVersion(\n options.expectedPolicyVersions?.validation,\n \"expected validation policy version\",\n ),\n };\n let body: { job: HostedSecurityJob };\n try {\n body = await requestHostedSecurityJson<{ job: HostedSecurityJob }>(\n options,\n `/registry/apps/${encodeURIComponent(appId)}/security/jobs`,\n {\n method: \"POST\",\n body: JSON.stringify({\n env,\n sourceId,\n ...(ref ? { ref } : {}),\n ...(options.profile ? { profile: options.profile } : {}),\n ...(options.clientRequestId\n ? { clientRequestId: hostedIdentifier(options.clientRequestId, \"clientRequestId\") }\n : {}),\n sourceDisclosure: \"redacted\",\n expectedPlanDigest,\n expectedExecutionDigest,\n expectedPolicyVersions,\n }),\n },\n \"start hosted security job\",\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (/\\b(?:plan_conflict|policy_conflict|intent_conflict|security_ai_not_ready)\\b/.test(message)) {\n throw new Error(\"Hosted security plan or execution intent changed or became unavailable after review; fetch a fresh intent and explicitly acknowledge its digest before enqueueing again\", { cause: error });\n }\n throw error;\n }\n if (!body.job?.jobId) {\n throw new Error(\"odla.ai returned an invalid hosted security job\");\n }\n return body.job;\n}\n\n/** Read one bounded hosted job status without an archive or explicit source excerpt. */\nexport async function getHostedSecurityJob(\n options: GetHostedSecurityJobOptions,\n): Promise<HostedSecurityJob> {\n const body = await requestHostedSecurityJson<{ job: HostedSecurityJob }>(\n options,\n hostedJobPath(options.appId, options.jobId),\n {},\n \"read hosted security job\",\n );\n if (!body.job?.jobId) throw new Error(\"odla.ai returned an invalid hosted security job\");\n return body.job;\n}\n\n/** List bounded, newest-first job metadata for an app environment. */\nexport async function listHostedSecurityJobs(\n options: ListHostedSecurityJobsOptions,\n): Promise<HostedSecurityJob[]> {\n const appId = hostedIdentifier(options.appId, \"appId\");\n const env = hostedIdentifier(options.env, \"env\");\n const body = await requestHostedSecurityJson<{ jobs: HostedSecurityJob[] }>(\n options,\n `/registry/apps/${encodeURIComponent(appId)}/security/jobs?env=${encodeURIComponent(env)}`,\n {},\n \"list hosted security jobs\",\n );\n return Array.isArray(body.jobs) ? body.jobs : [];\n}\n\n/** Poll one exact job until it reaches a terminal state. */\nexport async function followHostedSecurityJob(\n options: FollowHostedSecurityJobOptions,\n): Promise<HostedSecurityJob> {\n const interval = hostedPollInterval(options.pollIntervalMs);\n const now = options.now ?? Date.now;\n const deadline = now() + hostedPollTimeout(options.pollTimeoutMs ?? 60 * 60_000);\n const wait = options.wait ?? waitForHostedPoll;\n let prior = \"\";\n while (true) {\n const job = await getHostedSecurityJob(options);\n const fingerprint = `${job.status}:${job.updatedAt}`;\n if (fingerprint !== prior) options.onUpdate?.(Object.freeze({ ...job }));\n prior = fingerprint;\n if (isTerminalHostedSecurityStatus(job.status)) return job;\n if (now() >= deadline) {\n throw new Error(`Hosted security job ${job.jobId} did not finish before the polling deadline`);\n }\n await wait(Math.min(interval, Math.max(0, deadline - now())), options.signal);\n }\n}\n\n/** Fetch the bounded normalized report projection for a completed hosted job. */\nexport async function getHostedSecurityReport(\n options: GetHostedSecurityJobOptions,\n): Promise<HostedSecurityReport> {\n return requestHostedSecurityJson<HostedSecurityReport>(\n options,\n `${hostedJobPath(options.appId, options.jobId)}/report`,\n {},\n \"read hosted security report\",\n );\n}\n\n/** Return whether a hosted job status can no longer transition. */\nexport function isTerminalHostedSecurityStatus(\n status: HostedSecurityJobStatus,\n): boolean {\n return status === \"completed\" || status === \"failed\" || status === \"cancelled\";\n}\n\nfunction hostedJobPath(appIdInput: string, jobIdInput: string): string {\n const appId = hostedIdentifier(appIdInput, \"appId\");\n const jobId = hostedIdentifier(jobIdInput, \"jobId\");\n return `/registry/apps/${encodeURIComponent(appId)}/security/jobs/${encodeURIComponent(jobId)}`;\n}\n\nfunction securityPlanDigest(value: string): `sha256:${string}` {\n if (!/^sha256:[a-f0-9]{64}$/.test(value)) {\n throw new Error(\"expected plan digest must be a sha256 digest from security plan\");\n }\n return value as `sha256:${string}`;\n}\n\nfunction securityExecutionDigest(value: string): `sha256:${string}` {\n if (!/^sha256:[a-f0-9]{64}$/.test(value)) {\n throw new Error(\"expected execution digest must be a sha256 digest from security intent\");\n }\n return value as `sha256:${string}`;\n}\n","import {\n assertArgs,\n requiredString,\n stringOpt,\n type ParsedArgv,\n} from \"./argv\";\nimport type { CliDependencies } from \"./cli\";\nimport {\n hostedSecurityContext,\n interactiveConfirmation,\n requiredSecurityPositional,\n} from \"./security-command-context\";\nimport {\n printHostedJob,\n printHostedReport,\n printHostedSecurityPlan,\n} from \"./security-command-output\";\nimport {\n runLocalSecurityCommand,\n runSourceSecurityCommand,\n} from \"./security-run-command\";\nimport {\n connectGitHubSecuritySource,\n disconnectGitHubSecuritySource,\n followHostedSecurityJob,\n getHostedSecurityJob,\n getHostedSecurityPlan,\n getHostedSecurityReport,\n inferGitHubRepository,\n listGitHubSecuritySources,\n} from \"./security-hosted\";\nimport { openUrl } from \"./open\";\n\nexport async function securityCommand(\n parsed: ParsedArgv,\n dependencies: CliDependencies,\n): Promise<void> {\n const sub = parsed.positionals[1];\n if (sub === \"github\") {\n await githubSecurityCommand(parsed, dependencies);\n return;\n }\n if (sub === \"plan\") {\n assertArgs(parsed, [\"config\", \"env\", \"platform\", \"email\", \"open\", \"json\"], 2);\n const context = await hostedSecurityContext(parsed, dependencies);\n const plan = await getHostedSecurityPlan(context);\n if (parsed.options.json === true) context.stdout.log(JSON.stringify(plan, null, 2));\n else printHostedSecurityPlan(context.stdout, plan, context.appId);\n return;\n }\n if (sub === \"sources\") {\n await listSecuritySources(parsed, dependencies);\n return;\n }\n if (sub === \"status\") {\n await securityStatus(parsed, dependencies);\n return;\n }\n if (sub === \"report\") {\n assertArgs(parsed, [\"config\", \"env\", \"platform\", \"email\", \"open\", \"json\"], 3);\n const jobId = requiredSecurityPositional(parsed, 2, \"job id\");\n const context = await hostedSecurityContext(parsed, dependencies);\n const report = await getHostedSecurityReport({ ...context, jobId });\n if (parsed.options.json === true) context.stdout.log(JSON.stringify(report, null, 2));\n else printHostedReport(context.stdout, report);\n return;\n }\n if (sub !== \"run\") {\n throw new Error('unknown security command. Try \"odla-ai security plan\", \"security sources\", or \"security run\".');\n }\n const sourceId = stringOpt(parsed.options.source);\n if (sourceId) await runSourceSecurityCommand(parsed, dependencies, sourceId);\n else await runLocalSecurityCommand(parsed, dependencies);\n}\n\nasync function githubSecurityCommand(\n parsed: ParsedArgv,\n dependencies: CliDependencies,\n): Promise<void> {\n const action = parsed.positionals[2];\n if (action === \"disconnect\") {\n assertArgs(parsed, [\"config\", \"env\", \"platform\", \"source\", \"email\", \"open\", \"yes\"], 3);\n const context = await hostedSecurityContext(parsed, dependencies);\n const sourceId = requiredString(parsed.options.source, \"--source\");\n const confirmed = parsed.options.yes === true || await interactiveConfirmation(\n `Disconnect GitHub security source ${sourceId} from ${context.appId}/${context.env}?`,\n dependencies,\n );\n if (!confirmed) {\n throw new Error(\"GitHub source disconnect cancelled; pass --yes in a non-interactive shell\");\n }\n await disconnectGitHubSecuritySource({ ...context, sourceId });\n context.stdout.log(`github: disconnected ${sourceId} from ${context.appId}/${context.env}`);\n return;\n }\n if (action !== \"connect\") {\n throw new Error('unknown security github command. Try \"odla-ai security github connect\".');\n }\n assertArgs(parsed, [\"config\", \"env\", \"platform\", \"repo\", \"email\", \"open\"], 3);\n const context = await hostedSecurityContext(parsed, dependencies);\n const repository = stringOpt(parsed.options.repo)\n ?? await inferGitHubRepository(process.cwd(), dependencies.readGitOrigin);\n const connection = await connectGitHubSecuritySource({\n ...context,\n repository,\n open: parsed.options.open !== false,\n openInstallUrl: dependencies.openUrl ?? openUrl,\n wait: dependencies.pollWait,\n stdout: context.stdout,\n });\n context.stdout.log(`github: connected ${connection.repository ?? repository} (${connection.sourceId ?? \"source pending\"})`);\n context.stdout.log(\"github: odla.ai stores the installation; no PAT or GitHub token is written locally\");\n}\n\nasync function listSecuritySources(\n parsed: ParsedArgv,\n dependencies: CliDependencies,\n): Promise<void> {\n assertArgs(parsed, [\"config\", \"env\", \"platform\", \"email\", \"open\", \"json\"], 2);\n const context = await hostedSecurityContext(parsed, dependencies);\n const [plan, sources] = await Promise.all([\n getHostedSecurityPlan(context),\n listGitHubSecuritySources(context),\n ]);\n if (parsed.options.json === true) {\n context.stdout.log(JSON.stringify({ plan, sources }, null, 2));\n return;\n }\n printHostedSecurityPlan(context.stdout, plan, context.appId);\n if (!sources.length) {\n context.stdout.log(`No GitHub security sources connected for ${context.appId}/${context.env}.`);\n return;\n }\n context.stdout.log(`GitHub security sources for ${context.appId}/${context.env}\\nsource\\trepository\\tdefault ref\\tstatus`);\n for (const source of sources) {\n context.stdout.log(`${source.sourceId}\\t${source.repository}\\t${source.defaultBranch}\\t${source.status}`);\n }\n}\n\nasync function securityStatus(\n parsed: ParsedArgv,\n dependencies: CliDependencies,\n): Promise<void> {\n assertArgs(parsed, [\"config\", \"env\", \"platform\", \"email\", \"open\", \"json\", \"follow\"], 3);\n const jobId = requiredSecurityPositional(parsed, 2, \"job id\");\n const context = await hostedSecurityContext(parsed, dependencies);\n const job = parsed.options.follow === true\n ? await followHostedSecurityJob({\n ...context,\n jobId,\n wait: dependencies.pollWait,\n onUpdate: parsed.options.json === true\n ? undefined\n : (value) => printHostedJob(context.stdout, value, context.platform, context.appId),\n })\n : await getHostedSecurityJob({ ...context, jobId });\n if (parsed.options.json === true) context.stdout.log(JSON.stringify(job, null, 2));\n else if (parsed.options.follow !== true) {\n printHostedJob(context.stdout, job, context.platform, context.appId);\n }\n}\n","import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { claudeAdapter, CURSOR_RULE, PROJECT_INSTRUCTIONS } from \"./skill-adapters\";\n\n/** Agent harnesses with a first-class local adapter. */\nexport const AGENT_HARNESSES = [\"claude\", \"codex\", \"cursor\", \"copilot\", \"gemini\", \"agents\"] as const;\n\n/** A supported coding-agent harness. `agents` is the portable `AGENTS.md` adapter. */\nexport type AgentHarness = (typeof AGENT_HARNESSES)[number];\n\n/** A harness name accepted by setup; `all` expands to every project-local adapter. */\nexport type AgentHarnessSelector = AgentHarness | \"all\";\n\n/** Controls project-local or global installation of the bundled agent runbooks. */\nexport interface SkillInstallOptions {\n /** Project directory receiving the shared runbooks and harness adapters. Defaults to cwd. */\n dir?: string;\n /** Install user-wide Claude and/or Codex skills instead of project adapters. */\n global?: boolean;\n /** Harnesses to install. The programmatic compatibility default is `claude`; the CLI passes `all`. */\n harnesses?: AgentHarnessSelector[];\n /** Overwrite locally modified odla-managed files or managed instruction sections. */\n force?: boolean;\n /** Test/embedding override for the home directory. */\n homeDir?: string;\n /** Test/embedding override for `$CODEX_HOME`. */\n codexHomeDir?: string;\n /** Test/embedding override for the bundled skills directory. */\n sourceDir?: string;\n stdout?: Pick<typeof console, \"log\" | \"error\">;\n}\n\n/** One harness adapter and the directories or files through which it discovers odla. */\nexport interface HarnessInstallResult {\n harness: AgentHarness;\n targets: string[];\n}\n\n/** Files written or left unchanged by an idempotent agent-runbook installation. */\nexport interface SkillInstallResult {\n /** Primary native skill directory, retained for compatibility with earlier callers. */\n targetDir: string;\n /** Files changed directly under `targetDir`, relative to that directory. */\n written: string[];\n /** Files already current directly under `targetDir`, relative to that directory. */\n unchanged: string[];\n /** Absolute paths of every changed shared-runbook or adapter file. */\n writtenPaths: string[];\n /** Absolute paths of every already-current shared-runbook or adapter file. */\n unchangedPaths: string[];\n harnesses: HarnessInstallResult[];\n}\n\ninterface PlannedFile {\n target: string;\n content: string;\n boundary: string;\n managedMerge?: boolean;\n}\n\n/**\n * Installs one shared offline runbook tree plus thin native adapters for the\n * selected coding-agent harnesses. Project installs use `.agents/skills/` as\n * the canonical bundle; Claude Code, Cursor, Copilot, Gemini, and generic\n * `AGENTS.md` adapters point to it. Global installs support the native Claude\n * and Codex skill roots only.\n *\n * Installation is idempotent and planned before any write: an odla-managed\n * file changed by the user aborts the whole operation unless `force` is set.\n * Existing `AGENTS.md`, `GEMINI.md`, and Copilot instructions are preserved;\n * only the bounded odla-managed section is appended or replaced.\n */\nexport function installSkill(options: SkillInstallOptions = {}): SkillInstallResult {\n const out = options.stdout ?? console;\n const sourceDir = options.sourceDir ?? fileURLToPath(new URL(\"../skills\", import.meta.url));\n const files = listFiles(sourceDir);\n if (files.length === 0) throw new Error(`no bundled skills found at ${sourceDir}`);\n\n const harnesses = normalizeHarnesses(options.harnesses, options.global === true);\n const root = resolve(options.dir ?? process.cwd());\n const home = resolve(options.homeDir ?? homedir());\n const plans = new Map<string, PlannedFile>();\n const targets = new Map<AgentHarness, Set<string>>();\n\n const rememberTarget = (harness: AgentHarness, target: string): void => {\n const current = targets.get(harness) ?? new Set<string>();\n current.add(target);\n targets.set(harness, current);\n };\n const plan = (target: string, content: string, managedMerge = false, boundary = root): void => {\n const existing = plans.get(target);\n if (existing && existing.content !== content) throw new Error(`internal agent setup conflict for ${target}`);\n plans.set(target, { target, content, boundary, managedMerge });\n };\n const planSkillTree = (targetDir: string, boundary = root): void => {\n for (const rel of files) plan(join(targetDir, rel), readFileSync(join(sourceDir, rel), \"utf8\"), false, boundary);\n };\n\n let targetDir: string;\n if (options.global) {\n const claudeRoot = join(home, \".claude\", \"skills\");\n const codexRoot = resolve(options.codexHomeDir ?? process.env.CODEX_HOME ?? join(home, \".codex\"), \"skills\");\n targetDir = harnesses[0] === \"codex\" ? codexRoot : claudeRoot;\n for (const harness of harnesses) {\n const skillRoot = harness === \"claude\" ? claudeRoot : codexRoot;\n planSkillTree(skillRoot, harness === \"claude\" ? home : dirname(dirname(codexRoot)));\n rememberTarget(harness, skillRoot);\n }\n } else {\n const sharedRoot = join(root, \".agents\", \"skills\");\n planSkillTree(sharedRoot);\n\n const claudeRoot = join(root, \".claude\", \"skills\");\n targetDir = harnesses.includes(\"claude\") ? claudeRoot : sharedRoot;\n for (const harness of harnesses) rememberTarget(harness, sharedRoot);\n\n if (harnesses.includes(\"claude\")) {\n for (const skill of skillNames(files)) {\n const canonical = readFileSync(join(sourceDir, skill, \"SKILL.md\"), \"utf8\");\n plan(join(claudeRoot, skill, \"SKILL.md\"), claudeAdapter(skill, canonical));\n }\n rememberTarget(\"claude\", claudeRoot);\n }\n if (harnesses.includes(\"cursor\")) {\n const cursorRule = join(root, \".cursor\", \"rules\", \"odla.mdc\");\n plan(cursorRule, CURSOR_RULE);\n rememberTarget(\"cursor\", cursorRule);\n }\n if (harnesses.includes(\"agents\")) {\n const agentsFile = join(root, \"AGENTS.md\");\n plan(agentsFile, managedFileContent(agentsFile, PROJECT_INSTRUCTIONS, options.force === true, root), true);\n rememberTarget(\"agents\", agentsFile);\n }\n if (harnesses.includes(\"copilot\")) {\n const copilotFile = join(root, \".github\", \"copilot-instructions.md\");\n plan(copilotFile, managedFileContent(copilotFile, PROJECT_INSTRUCTIONS, options.force === true, root), true);\n rememberTarget(\"copilot\", copilotFile);\n }\n if (harnesses.includes(\"gemini\")) {\n const geminiFile = join(root, \"GEMINI.md\");\n plan(geminiFile, managedFileContent(geminiFile, PROJECT_INSTRUCTIONS, options.force === true, root), true);\n rememberTarget(\"gemini\", geminiFile);\n }\n }\n\n const writtenPaths = new Set<string>();\n const unchangedPaths = new Set<string>();\n const conflicts: string[] = [];\n for (const file of plans.values()) {\n const symlink = symlinkedComponent(file.boundary, file.target);\n if (symlink) {\n conflicts.push(`${file.target} (redirected by symbolic link ${symlink})`);\n continue;\n }\n if (!existsSync(file.target)) {\n writtenPaths.add(file.target);\n continue;\n }\n const current = readFileSync(file.target, \"utf8\");\n if (current === file.content) {\n unchangedPaths.add(file.target);\n } else if (file.managedMerge || options.force) {\n writtenPaths.add(file.target);\n unchangedPaths.delete(file.target);\n } else {\n conflicts.push(file.target);\n }\n }\n\n if (conflicts.length > 0) {\n throw new Error(\n `agent setup files modified locally (re-run with --force to replace only odla-managed content):\\n${conflicts.map((f) => ` - ${f}`).join(\"\\n\")}`,\n );\n }\n\n for (const file of plans.values()) {\n if (!existsSync(file.target) || readFileSync(file.target, \"utf8\") !== file.content) {\n mkdirSync(dirname(file.target), { recursive: true });\n writeFileSync(file.target, file.content);\n }\n }\n\n const skills = skillNames(files);\n const installations = harnesses.map((harness) => ({ harness, targets: [...(targets.get(harness) ?? [])] }));\n out.log(`agent harnesses: ${harnesses.join(\", \")}`);\n out.log(`offline skills: ${skills.join(\", \")}`);\n for (const installation of installations) out.log(`${installation.harness}: ${installation.targets.join(\", \")}`);\n out.log(`installed ${writtenPaths.size} managed file(s)${unchangedPaths.size ? ` (${unchangedPaths.size} unchanged)` : \"\"}`);\n return {\n targetDir,\n written: pathsUnder(targetDir, writtenPaths),\n unchanged: pathsUnder(targetDir, unchangedPaths),\n writtenPaths: [...writtenPaths].sort(),\n unchangedPaths: [...unchangedPaths].sort(),\n harnesses: installations,\n };\n}\n\nfunction pathsUnder(root: string, paths: Set<string>): string[] {\n return [...paths]\n .map((path) => relative(root, path))\n .filter((path) => path !== \"..\" && !path.startsWith(`..${sep}`) && !isAbsolute(path))\n .sort();\n}\n\nfunction normalizeHarnesses(values: AgentHarnessSelector[] | undefined, global: boolean): AgentHarness[] {\n const requested: string[] = values?.length ? values : [\"claude\"];\n const allowed = new Set<string>([...AGENT_HARNESSES, \"all\"]);\n for (const harness of requested) {\n if (!allowed.has(harness)) {\n throw new Error(`unknown agent harness \"${harness}\"; choose all, ${AGENT_HARNESSES.join(\", \")}`);\n }\n }\n const expanded: AgentHarness[] = requested.includes(\"all\")\n ? global ? [\"claude\", \"codex\"] : [...AGENT_HARNESSES]\n : [...new Set(requested)] as AgentHarness[];\n if (global) {\n const unsupported = expanded.filter((harness) => harness !== \"claude\" && harness !== \"codex\");\n if (unsupported.length) {\n throw new Error(`--global supports claude and codex only; ${unsupported.join(\", \")} require a project-local adapter`);\n }\n }\n return expanded;\n}\n\nfunction managedFileContent(path: string, block: string, force: boolean, boundary: string): string {\n const symlink = symlinkedComponent(boundary, path);\n if (symlink) throw new Error(`refusing to manage ${path}: symbolic link component ${symlink}`);\n if (!existsSync(path)) return `${block}\\n`;\n const current = readFileSync(path, \"utf8\");\n const start = \"<!-- odla-ai agent setup:start -->\";\n const end = \"<!-- odla-ai agent setup:end -->\";\n const startAt = current.indexOf(start);\n const endAt = current.indexOf(end);\n if ((startAt === -1) !== (endAt === -1) || (startAt !== -1 && endAt < startAt)) {\n throw new Error(`malformed odla-managed section in ${path}`);\n }\n if (startAt === -1) {\n const separator = current.length === 0 || current.endsWith(\"\\n\\n\") ? \"\" : current.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n return `${current}${separator}${block}\\n`;\n }\n const afterEnd = endAt + end.length;\n const existing = current.slice(startAt, afterEnd);\n if (existing !== block && !force) {\n throw new Error(`odla-managed section modified locally in ${path}; re-run with --force to replace that section`);\n }\n return `${current.slice(0, startAt)}${block}${current.slice(afterEnd)}`;\n}\n\nfunction symlinkedComponent(boundary: string, target: string): string | undefined {\n const rel = relative(boundary, target);\n if (rel === \"..\" || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {\n throw new Error(`agent setup target escapes its install root: ${target}`);\n }\n let current = boundary;\n for (const part of rel.split(sep).filter(Boolean)) {\n current = join(current, part);\n try {\n if (lstatSync(current).isSymbolicLink()) return current;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n }\n }\n return undefined;\n}\n\nfunction skillNames(files: string[]): string[] {\n return [...new Set(files.filter((file) => /(^|[\\\\/])SKILL\\.md$/.test(file)).map((file) => file.split(/[\\\\/]/)[0]!))].sort();\n}\n\nfunction listFiles(dir: string): string[] {\n if (!existsSync(dir)) return [];\n const results: string[] = [];\n const walk = (current: string): void => {\n for (const entry of readdirSync(current, { withFileTypes: true })) {\n const path = join(current, entry.name);\n if (entry.isDirectory()) walk(path);\n else results.push(relative(dir, path));\n }\n };\n walk(dir);\n return results.sort();\n}\n","/** Shared instruction block inserted into harness-native project files. */\nexport const PROJECT_INSTRUCTIONS = `<!-- odla-ai agent setup:start -->\n## odla agent workflow\n\nFor work that creates an odla app or adds odla services, read and follow\n\\`.agents/skills/odla/SKILL.md\\`. It dispatches an existing static site to\n\\`.agents/skills/odla-migrate/SKILL.md\\`. For production telemetry triage, use\n\\`.agents/skills/odla-o11y-debug/SKILL.md\\`.\n\nThe complete runbooks and their references are installed in this repository.\nDo not fetch online odla documentation as setup context. Network access is only\nneeded when a runbook deliberately calls the odla service, npm, Cloudflare, or\nanother configured provider.\n<!-- odla-ai agent setup:end -->`;\n\n/** Cursor's native rule wrapper around the shared project instructions. */\nexport const CURSOR_RULE = `---\ndescription: Build, migrate, provision, secure, or debug an odla app using the locally installed odla runbooks\nglobs:\nalwaysApply: false\n---\n\n${PROJECT_INSTRUCTIONS}\n`;\n\n/** Build a thin Claude skill that delegates to the canonical offline bundle. */\nexport function claudeAdapter(skill: string, canonical: string): string {\n const match = canonical.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---/);\n if (!match) throw new Error(`bundled skill ${skill} has no YAML frontmatter`);\n const lines = match[1]!.split(/\\r?\\n/);\n const frontmatter: string[] = [];\n let keepIndented = false;\n for (const line of lines) {\n if (line.startsWith(\"name:\") || line.startsWith(\"description:\")) {\n frontmatter.push(line);\n keepIndented = line.startsWith(\"description:\");\n } else if (keepIndented && /^\\s+/.test(line)) {\n frontmatter.push(line);\n } else {\n keepIndented = false;\n }\n }\n return `---\n${frontmatter.join(\"\\n\")}\n---\n\n# ${skill} (odla adapter)\n\nRead \\`../../../.agents/skills/${skill}/SKILL.md\\` completely and follow it. That\ncanonical local skill owns every reference path and contains the full offline\nrunbook. Do not substitute a remote documentation page for the installed copy.\n`;\n}\n","import { calendarServiceConfig, GOOGLE_CALENDAR_EVENTS_SCOPE, loadProjectConfig, resolveDataExport, serializedEntities } from \"./config\";\nimport { readCalendarStatus } from \"./calendar-http\";\nimport { displayPath, readCredentials } from \"./local\";\nimport { getDeveloperToken } from \"./token\";\nimport type { SmokeOptions } from \"./types\";\n\ntype FetchLike = typeof fetch;\n\n/**\n * Verify a live, already-provisioned environment end-to-end. Resolves the target\n * env (`options.env`, else `dev`, else the first declared env) and requires it to\n * be declared in the config. Reads the local credentials file and checks that it\n * belongs to this app and holds a `tenantId` + `dbKey` for the env — otherwise it\n * throws pointing the user at `odla-ai provision --write-dev-vars`.\n *\n * It then makes real network calls: fetches the registry public-config (and, when\n * `ai.provider` is configured, asserts the live provider matches), fetches the\n * live db schema with the db key and asserts every entity from the local schema\n * is present, and runs a `count` aggregate against the first entity to confirm\n * the db answers queries. Progress lines are printed and it ends with `ok`.\n * Read-only — it writes nothing and throws on the first mismatch or failed\n * request.\n *\n * @param options.configPath Path to the `odla.config.mjs`.\n * @param options.env Env to check (default `dev`, else the first declared env).\n * @param options.fetch Injectable `fetch` (for tests/embedding).\n * @param options.stdout Optional console-like sink (defaults to `console`).\n */\nexport async function smoke(options: SmokeOptions): Promise<void> {\n const out = options.stdout ?? console;\n const cfg = await loadProjectConfig(options.configPath);\n const env = options.env ?? (cfg.envs.includes(\"dev\") ? \"dev\" : (cfg.envs[0] ?? \"prod\"));\n if (!cfg.envs.includes(env)) throw new Error(`env \"${env}\" is not declared in ${displayPath(cfg.configPath, cfg.rootDir)}`);\n\n const credentials = readCredentials(cfg.local.credentialsFile);\n if (!credentials) {\n throw new Error(`local credentials missing: ${displayPath(cfg.local.credentialsFile, cfg.rootDir)}. Run \"odla-ai provision --write-dev-vars\".`);\n }\n if (credentials.appId !== cfg.app.id) {\n throw new Error(`local credentials are for app \"${credentials.appId}\", but config app is \"${cfg.app.id}\"`);\n }\n\n const entry = credentials.envs[env];\n if (!entry?.tenantId || !entry.dbKey) {\n throw new Error(`local credentials have no db key for env \"${env}\". Run \"odla-ai provision --write-dev-vars\".`);\n }\n\n const doFetch = options.fetch ?? fetch;\n out.log(`smoke: ${cfg.app.id}/${env}`);\n out.log(` tenant: ${entry.tenantId}`);\n\n const publicConfig = await getJson(doFetch, publicConfigUrl(cfg.platformUrl, cfg.app.id, env), undefined);\n out.log(` public-config: ok`);\n\n if (cfg.ai?.provider) {\n const provider = ((publicConfig as { ai?: { provider?: unknown } | null }).ai?.provider ?? null) as string | null;\n if (provider !== cfg.ai.provider) {\n throw new Error(`ai provider mismatch: expected \"${cfg.ai.provider}\", public-config has \"${provider ?? \"none\"}\"`);\n }\n out.log(` ai: ${provider}`);\n }\n\n if (cfg.services.includes(\"calendar\")) {\n const token = await getDeveloperToken(\n cfg,\n {\n configPath: cfg.configPath,\n token: options.token,\n email: options.email,\n open: options.open,\n openApprovalUrl: options.openApprovalUrl,\n },\n doFetch,\n out,\n );\n const status = await readCalendarStatus({ platform: cfg.platformUrl, appId: cfg.app.id, env, token, fetch: doFetch });\n assertCalendarHealthy(status, calendarServiceConfig(cfg, env));\n out.log(` calendar: ${status.status}, bookable (booking → ${status.bookingCalendarId ?? \"primary\"})`);\n }\n\n const expectedSchema = await resolveDataExport<unknown>(cfg, cfg.db?.schema, [\"schema\", \"SCHEMA\"]);\n const expectedEntities = serializedEntities(expectedSchema);\n const liveSchemaPayload = await getJson(doFetch, `${cfg.dbEndpoint}/app/${encodeURIComponent(entry.tenantId)}/schema`, entry.dbKey);\n const liveSchema = (liveSchemaPayload as { schema?: unknown }).schema ?? liveSchemaPayload;\n const liveEntities = serializedEntities(liveSchema);\n if (expectedEntities.length) {\n const missing = expectedEntities.filter((entity) => !liveEntities.includes(entity));\n if (missing.length) throw new Error(`live schema is missing expected entities: ${missing.join(\", \")}`);\n }\n out.log(` schema: ${liveEntities.length} entities`);\n\n const aggregateEntity = expectedEntities[0] ?? liveEntities[0];\n if (aggregateEntity) {\n const aggregate = await postJson(doFetch, `${cfg.dbEndpoint}/app/${encodeURIComponent(entry.tenantId)}/aggregate`, entry.dbKey, {\n ns: aggregateEntity,\n aggregate: { count: true },\n });\n const count = (aggregate as { aggregate?: { count?: unknown } }).aggregate?.count;\n out.log(` aggregate: ${aggregateEntity}.count=${String(count ?? \"ok\")}`);\n } else {\n out.log(` aggregate: skipped (schema has no entities)`);\n }\n // Live-booking calendar keeps no mirror in odla-db — connection health\n // (checked above) is the whole calendar smoke.\n out.log(\"ok\");\n}\n\nfunction assertCalendarHealthy(\n status: Awaited<ReturnType<typeof readCalendarStatus>>,\n expected: ReturnType<typeof calendarServiceConfig>,\n): void {\n if (!status.enabled || status.provider !== \"google\") throw new Error(\"calendar is not enabled with the Google provider\");\n if (status.status !== \"healthy\") {\n throw new Error(`calendar connection is ${status.status}${status.error?.message ? `: ${status.error.message}` : \"\"}`);\n }\n if (!status.writable) throw new Error('calendar grant does not cover booking writes; run \"odla-ai calendar connect\" to re-consent');\n const hasEventsScope = status.grantedScopes.some((scope) => scope === GOOGLE_CALENDAR_EVENTS_SCOPE);\n if (!hasEventsScope) throw new Error(\"calendar connection is missing calendar.events consent\");\n const missing = expected.availabilityCalendars.filter((id) => !status.calendars.includes(id));\n if (missing.length) throw new Error(`calendar connection is missing configured calendars: ${missing.join(\", \")}`);\n}\n\nasync function getJson(doFetch: FetchLike, url: string, bearer: string | undefined): Promise<unknown> {\n const res = await doFetch(url, {\n headers: bearer ? { authorization: `Bearer ${bearer}` } : undefined,\n });\n if (!res.ok) throw new Error(`${new URL(url).pathname} returned ${res.status}: ${await safeText(res)}`);\n return res.json();\n}\n\nasync function postJson(doFetch: FetchLike, url: string, bearer: string, body: unknown): Promise<unknown> {\n const res = await doFetch(url, {\n method: \"POST\",\n headers: { authorization: `Bearer ${bearer}`, \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n if (!res.ok) throw new Error(`${new URL(url).pathname} returned ${res.status}: ${await safeText(res)}`);\n return res.json();\n}\n\nfunction publicConfigUrl(platformUrl: string, appId: string, env: string): string {\n const url = new URL(`/registry/apps/${encodeURIComponent(appId)}/public-config`, platformUrl);\n url.searchParams.set(\"env\", env);\n return url.toString();\n}\n\nasync function safeText(res: Response): Promise<string> {\n try {\n return (await res.text()).slice(0, 500);\n } catch {\n return \"\";\n }\n}\n","import { adminCommand } from \"./admin-command\";\nimport { appCommand } from \"./app-lifecycle\";\nimport {\n assertArgs,\n listOpt,\n numberOpt,\n parseArgv,\n requiredString,\n stringOpt,\n} from \"./argv\";\nimport { printCapabilities } from \"./capabilities\";\nimport { calendarCalendars, calendarConnect, calendarDisconnect, calendarStatus } from \"./calendar\";\nimport { doctor } from \"./doctor\";\nimport { cliVersion, printHelp } from \"./help\";\nimport { harnessList } from \"./harness-options\";\nimport { initProject } from \"./init\";\nimport { provision } from \"./provision\";\nimport { secretsPush } from \"./secrets\";\nimport { secretsSet, secretsSetClerkKey } from \"./secrets-set\";\nimport { securityCommand } from \"./security-command\";\nimport { installSkill } from \"./skill\";\nimport { smoke } from \"./smoke\";\nimport type { ProvisionOptions } from \"./types\";\n\n/** Map a CLI failure to its process exit code: 75 (EX_TEMPFAIL) marks a\n * handshake that is still awaiting human approval — the pending state is\n * persisted and rerunning the same command resumes it — everything else is 1. */\nexport function exitCodeFor(err: unknown): number {\n return (err as { code?: unknown } | null)?.code === \"handshake_pending\" ? 75 : 1;\n}\n\n/** Injectable side-effect boundaries used to run and test the command dispatcher. */\nexport interface CliDependencies {\n fetch?: typeof fetch;\n openUrl?: (url: string) => Promise<void>;\n pollWait?: (milliseconds: number, signal?: AbortSignal) => Promise<void>;\n readGitOrigin?: (cwd: string) => Promise<string>;\n confirm?: (message: string) => Promise<boolean>;\n stdout?: Pick<typeof console, \"log\" | \"error\">;\n}\n\n/**\n * Parse CLI arguments and dispatch the matching odla command.\n *\n * The dispatcher covers project setup, platform AI administration, hosted and\n * local security, provisioning, smoke checks, skill installation, and secret\n * pushes. It rejects unknown commands, unsupported options, extra positionals,\n * missing values, and errors returned by the selected command.\n *\n * @param argv Argument vector without the node/script prefix.\n * @param dependencies Optional side-effect overrides for embedding and tests.\n */\nexport async function runCli(\n argv = process.argv.slice(2),\n dependencies: CliDependencies = {},\n): Promise<void> {\n const parsed = parseArgv(argv);\n const command = parsed.positionals[0] ?? \"help\";\n if (command === \"version\" || command === \"-v\" || parsed.options.version === true) {\n assertArgs(parsed, [\"version\"], 1);\n console.log(cliVersion());\n return;\n }\n if (command === \"help\" || command === \"--help\" || command === \"-h\") {\n assertArgs(parsed, [\"help\"], 1);\n printHelp();\n return;\n }\n if (command === \"init\") {\n assertArgs(parsed, [\n \"app-id\", \"name\", \"config\", \"env\", \"services\", \"ai-provider\", \"force\",\n ], 1);\n initProject({\n appId: requiredString(parsed.options[\"app-id\"], \"--app-id\"),\n name: requiredString(parsed.options.name, \"--name\"),\n configPath: stringOpt(parsed.options.config),\n envs: listOpt(parsed.options.env),\n services: listOpt(parsed.options.services),\n aiProvider: stringOpt(parsed.options[\"ai-provider\"]),\n force: parsed.options.force === true,\n });\n return;\n }\n if (command === \"doctor\") {\n assertArgs(parsed, [\"config\"], 1);\n await doctor({ configPath: stringOpt(parsed.options.config) ?? \"odla.config.mjs\" });\n return;\n }\n if (command === \"calendar\") {\n await calendarCommand(parsed, dependencies);\n return;\n }\n if (command === \"capabilities\") {\n assertArgs(parsed, [\"json\"], 1);\n printCapabilities(parsed.options.json === true);\n return;\n }\n if (command === \"admin\") {\n await adminCommand(parsed);\n return;\n }\n if (command === \"app\") {\n await appCommand(parsed, dependencies);\n return;\n }\n if (command === \"security\") {\n await securityCommand(parsed, dependencies);\n return;\n }\n if (command === \"provision\") {\n await provisionCommand(parsed, dependencies);\n return;\n }\n if (command === \"smoke\") {\n assertArgs(parsed, [\"config\", \"env\", \"token\", \"email\", \"open\"], 1);\n await smoke({\n configPath: stringOpt(parsed.options.config) ?? \"odla.config.mjs\",\n env: stringOpt(parsed.options.env),\n token: stringOpt(parsed.options.token),\n email: stringOpt(parsed.options.email),\n open: parsed.options.open === false ? false : parsed.options.open === true ? true : undefined,\n openApprovalUrl: dependencies.openUrl,\n fetch: dependencies.fetch,\n stdout: dependencies.stdout,\n });\n return;\n }\n if (command === \"setup\") {\n assertArgs(parsed, [\"dir\", \"global\", \"force\", \"agent\", \"harness\"], 1);\n installSkill({\n dir: stringOpt(parsed.options.dir),\n global: parsed.options.global === true,\n harnesses: harnessList(parsed),\n force: parsed.options.force === true,\n });\n console.log(\n \"\\nOffline runbooks installed. Open this repo in your coding agent and ask it to set up odla.\\n\" +\n \"Its native adapter finds the local `odla` skill, chooses build or migration, and drives the CLI.\",\n );\n return;\n }\n if (command === \"skill\") {\n const sub = parsed.positionals[1];\n if (sub !== \"install\") {\n throw new Error(`unknown skill subcommand \"${sub ?? \"\"}\". Try \"odla-ai skill install\".`);\n }\n assertArgs(parsed, [\"dir\", \"global\", \"force\", \"agent\", \"harness\"], 2);\n installSkill({\n dir: stringOpt(parsed.options.dir),\n global: parsed.options.global === true,\n harnesses: harnessList(parsed),\n force: parsed.options.force === true,\n });\n return;\n }\n if (command === \"secrets\") {\n const sub = parsed.positionals[1];\n if (sub === \"set\" || sub === \"set-clerk-key\") {\n assertArgs(parsed, [\"config\", \"env\", \"from-env\", \"stdin\", \"token\", \"email\", \"yes\"], sub === \"set\" ? 3 : 2);\n const options = {\n configPath: stringOpt(parsed.options.config) ?? \"odla.config.mjs\",\n name: parsed.positionals[2],\n env: requiredString(parsed.options.env, \"--env\"),\n fromEnv: stringOpt(parsed.options[\"from-env\"]),\n stdin: parsed.options.stdin === true,\n token: stringOpt(parsed.options.token),\n email: stringOpt(parsed.options.email),\n yes: parsed.options.yes === true,\n fetch: dependencies.fetch,\n stdout: dependencies.stdout,\n };\n await (sub === \"set\" ? secretsSet(options) : secretsSetClerkKey(options));\n return;\n }\n if (sub !== \"push\") {\n throw new Error(\n `unknown secrets subcommand \"${sub ?? \"\"}\". Try \"odla-ai secrets push --env dev\", ` +\n `\"odla-ai secrets set <name> --env dev --stdin\", or \"odla-ai secrets set-clerk-key --env dev --stdin\".`,\n );\n }\n assertArgs(parsed, [\"config\", \"env\", \"dry-run\", \"yes\"], 2);\n await secretsPush({\n configPath: stringOpt(parsed.options.config) ?? \"odla.config.mjs\",\n env: requiredString(parsed.options.env, \"--env\"),\n dryRun: parsed.options[\"dry-run\"] === true,\n yes: parsed.options.yes === true,\n });\n return;\n }\n throw new Error(`unknown command \"${command}\". Run \"odla-ai help\".`);\n}\n\nasync function provisionCommand(\n parsed: ReturnType<typeof parseArgv>,\n dependencies: CliDependencies,\n): Promise<void> {\n assertArgs(parsed, [\n \"config\", \"dry-run\", \"rotate-keys\", \"rotate-o11y-token\", \"push-secrets\",\n \"write-credentials\", \"write-dev-vars\", \"token\", \"email\", \"open\", \"wait\", \"yes\",\n ], 1);\n const writeDevVars = parsed.options[\"write-dev-vars\"];\n const options: ProvisionOptions = {\n configPath: stringOpt(parsed.options.config) ?? \"odla.config.mjs\",\n dryRun: parsed.options[\"dry-run\"] === true,\n rotateKeys: parsed.options[\"rotate-keys\"] === true,\n rotateO11yToken: parsed.options[\"rotate-o11y-token\"] === true,\n pushSecrets: parsed.options[\"push-secrets\"] === true,\n writeCredentials: parsed.options[\"write-credentials\"] !== false,\n writeDevVars: typeof writeDevVars === \"string\" ? writeDevVars : writeDevVars === true,\n token: stringOpt(parsed.options.token),\n email: stringOpt(parsed.options.email),\n open: parsed.options.open === false\n ? false\n : parsed.options.open === true ? true : undefined,\n wait: numberOpt(parsed.options.wait, \"--wait\"),\n yes: parsed.options.yes === true,\n fetch: dependencies.fetch,\n openApprovalUrl: dependencies.openUrl,\n stdout: dependencies.stdout,\n };\n await provision(options);\n}\n\nasync function calendarCommand(parsed: ReturnType<typeof parseArgv>, dependencies: CliDependencies): Promise<void> {\n const sub = parsed.positionals[1];\n if (sub !== \"status\" && sub !== \"calendars\" && sub !== \"connect\" && sub !== \"disconnect\") {\n throw new Error(`unknown calendar subcommand \"${sub ?? \"\"}\". Try \"odla-ai calendar status --env dev\".`);\n }\n assertArgs(parsed, [\"config\", \"env\", \"json\", \"token\", \"email\", \"open\", \"yes\"], 2);\n if (sub !== \"status\" && sub !== \"calendars\" && parsed.options.json !== undefined) throw new Error(`--json is supported only by calendar status/calendars`);\n if ((sub === \"status\" || sub === \"calendars\") && parsed.options.yes !== undefined) throw new Error(`--yes is not used by \"calendar ${sub}\"`);\n const options = {\n configPath: stringOpt(parsed.options.config) ?? \"odla.config.mjs\",\n env: stringOpt(parsed.options.env),\n token: stringOpt(parsed.options.token),\n email: stringOpt(parsed.options.email),\n open: parsed.options.open === false ? false : parsed.options.open === true ? true : undefined,\n yes: parsed.options.yes === true,\n json: parsed.options.json === true,\n fetch: dependencies.fetch,\n stdout: dependencies.stdout,\n openConsentUrl: dependencies.openUrl,\n };\n if (sub === \"status\") await calendarStatus(options);\n else if (sub === \"calendars\") await calendarCalendars(options);\n else if (sub === \"connect\") await calendarConnect(options);\n else await calendarDisconnect(options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKA,IAAM,mBAAmB,MACvB,OAAO,aAAa,cAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,OAC7B,SAAS,iBAAiB,SAAS,cAAc,QAAQ,YAAY,MAAM,WAC1E,SAAS,cAAc,MACvB,IAAI,IAAI,WAAW,SAAS,OAAO,EAAE;AAEtC,IAAM,gBAAgC,iCAAiB;;;ACZ9D,IAAAA,uBAAoB;;;ACApB,gBAAsD;AAEtD,IAAAC,uBAAoB;;;ACFpB,IAAAC,k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,GAAG;AAAA,IACjC,OAAO,UAAU,OAAO,QAAQ,KAAK;AAAA,IACrC,OAAO,UAAU,OAAO,QAAQ,KAAK;AAAA,IACrC,MAAM,OAAO,QAAQ,SAAS,QAAQ,QAAQ,OAAO,QAAQ,SAAS,OAAO,OAAO;AAAA,IACpF,KAAK,OAAO,QAAQ,QAAQ;AAAA,IAC5B,MAAM,OAAO,QAAQ,SAAS;AAAA,IAC9B,OAAO,aAAa;AAAA,IACpB,QAAQ,aAAa;AAAA,IACrB,gBAAgB,aAAa;AAAA,EAC/B;AACA,MAAI,QAAQ,SAAU,OAAM,eAAe,OAAO;AAAA,WACzC,QAAQ,YAAa,OAAM,kBAAkB,OAAO;AAAA,WACpD,QAAQ,UAAW,OAAM,gBAAgB,OAAO;AAAA,MACpD,OAAM,mBAAmB,OAAO;AACvC;","names":["import_node_process","import_node_process","import_node_fs","import_node_path","process","import_node_process","process","resolve","process","import_node_process","process","import_node_fs","import_node_process","import_db","process","responseBody","apiError","isRecord","timestamp","process","res","body","responseBody","apiError","isRecord","policy","response","import_node_fs","import_node_fs","import_node_path","isRecord","timestamp","resolve","import_node_child_process","import_node_fs","import_node_path","import_node_child_process","import_node_fs","import_node_path","import_node_fs","import_node_fs","import_node_path","import_apps","import_node_process","safeText","process","safeText","publishableKey","import_ai","import_apps","PROD_ENV_NAMES","import_promises","import_security","import_node_path","import_node_child_process","resolve","context","import_node_fs","import_node_path","import_node_url","targetDir","postJson","safeText","writeDevVars"]}
|