@opengeni/config 0.7.1 → 0.7.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +17 -0
- package/dist/index.js +38 -5
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/index.ts +37 -5
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import {\n BillingMode,\n CAPABILITY_DESCRIPTORS,\n Entitlements,\n EntitlementsMode,\n MAX_NESTED_AGENT_DEPTH,\n ProductAccessMode,\n ReasoningEffort,\n SandboxBackend,\n SessionMcpApprovalPolicy,\n StaticUsageLimits,\n TurnExecutionPolicyV1,\n UsageLimitsMode,\n type TurnExecutionModelSourceV1,\n type TurnExecutionReasoningSourceV1,\n} from \"@opengeni/contracts\";\nimport { CODEX_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS } from \"@opengeni/codex\";\nimport {\n CODEX_FALLBACK_MODEL_SLUGS,\n CODEX_MODEL_AUTO_COMPACT_TOKEN_LIMIT,\n CODEX_MODEL_CONTEXT_WINDOW_TOKENS,\n CODEX_MODEL_EFFECTIVE_CONTEXT_WINDOW_TOKENS,\n CODEX_MODEL_ID_PREFIX,\n CODEX_PROVIDER_BASE_URL,\n CODEX_PROVIDER_ID,\n} from \"@opengeni/codex/constants\";\nimport { createHash } from \"node:crypto\";\nimport { z } from \"zod\";\n\nconst envName = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst registryId = /^[A-Za-z0-9_-]+$/;\nconst EnvBoolean = z.preprocess((value) => {\n if (typeof value !== \"string\") {\n return value;\n }\n const normalized = value.trim().toLowerCase();\n if ([\"true\", \"1\", \"yes\", \"y\", \"on\"].includes(normalized)) {\n return true;\n }\n if ([\"false\", \"0\", \"no\", \"n\", \"off\"].includes(normalized)) {\n return false;\n }\n return value;\n}, z.boolean());\n\nexport const sandboxPreparationProfiles: Record<string, { env: string[]; hooks: string[] }> = {\n none: {\n env: [],\n hooks: [],\n },\n azure: {\n env: [\n \"ARM_CLIENT_ID\",\n \"ARM_CLIENT_SECRET\",\n \"ARM_TENANT_ID\",\n \"ARM_SUBSCRIPTION_ID\",\n \"AZURE_CLIENT_ID\",\n \"AZURE_CLIENT_SECRET\",\n \"AZURE_TENANT_ID\",\n \"AZURE_SUBSCRIPTION_ID\",\n \"AZURE_AUTHORITY_HOST\",\n ],\n hooks: [\"azure-cli-login\"],\n },\n github: {\n env: [\n \"GH_TOKEN\",\n \"GITHUB_TOKEN\",\n \"GIT_AUTHOR_NAME\",\n \"GIT_AUTHOR_EMAIL\",\n \"GIT_COMMITTER_NAME\",\n \"GIT_COMMITTER_EMAIL\",\n ],\n hooks: [],\n },\n};\n\n/**\n * Placeholder token inside an agent-instructions persona template. The runtime\n * substitutes the non-bypassable CORE (goal-loop ownership + the dynamic\n * workspace-environment block) at this marker. A template that omits the\n * marker still gets the CORE appended after it (a non-bypassable fail-safe),\n * so a white-labelled persona can never drop the goal-loop contract or the\n * environment metadata the agent depends on.\n */\nexport const AGENT_INSTRUCTIONS_CORE_PLACEHOLDER = \"{{core}}\";\n\n/**\n * Default per-workspace agent persona template. This is the BRAND + tool-usage\n * opinion (the white-labellable surface): the \"You are an OpenGeni workspace\n * agent.\" identity line, the framing/opinion lines, and the mount-path facts.\n *\n * The CORE that MUST survive any override — the goal-loop ownership line (which\n * names the opengeni__goal_* tools) and the dynamic workspace-environment block\n * — is injected at AGENT_INSTRUCTIONS_CORE_PLACEHOLDER by the runtime, never\n * baked into this overridable string.\n *\n * INVARIANT: with no per-workspace override and an empty environment, the\n * runtime's composed instructions are byte-for-byte pinned by a runtime test.\n * The template below is joined by \" \", followed by \" \" + the placeholder.\n * Changing a single character here changes that default; update the pin\n * intentionally.\n */\nexport const DEFAULT_AGENT_INSTRUCTIONS = [\n \"You are an OpenGeni workspace agent.\",\n \"Follow the user's task and any enabled pack or skill instructions for the current role.\",\n \"Work inside the sandbox workspace and use filesystem and shell tools when useful.\",\n \"Repository resources are mounted under repos/<host>/<owner>/<repo> unless the session specifies another collision-free mount path.\",\n \"File resources are mounted under files/<file-id>/ unless the session specifies another mount path.\",\n \"Attached files are mounted read-only; copy them before modifying.\",\n \"Bundled skills are under .agents/ and can include infrastructure, marketing, or other role-specific guidance.\",\n \"Use Checkov, Terraform, Azure CLI, git provider CLIs, and repository tools when relevant; gh, glab, and az repos are pre-authenticated when the host brokers matching git credentials.\",\n \"When the Azure sandbox preparation profile is enabled and service-principal variables are present, the sandbox is pre-authenticated with normal Azure CLI before work starts.\",\n \"Treat code-changing work as GitOps work: create a focused branch/commit/PR when git provider credentials are available; otherwise report exact commands and blockers.\",\n \"Return concise, factual summaries with files changed, commands run, and remaining blockers.\",\n AGENT_INSTRUCTIONS_CORE_PLACEHOLDER,\n].join(\" \");\n\nexport const McpServerConnectionRefSchema = z\n .object({\n // Standalone ids are UUIDs; embedded hosts may use any stable opaque id.\n connectionId: z.string().min(1).optional(),\n provider: z.string().min(1).max(128).optional(),\n providerDomain: z.string().min(1),\n kind: z.enum([\"oauth2\", \"api_key\", \"app_install\", \"delegated\"]).optional(),\n scopes: z.array(z.string().min(1)).optional(),\n resource: z.string().min(1).optional(),\n selectedResources: z\n .array(\n z\n .object({\n id: z.string().min(1).max(512),\n kind: z.literal(\"repository\"),\n })\n .strict(),\n )\n .min(1)\n .max(256)\n .superRefine((resources, context) => {\n const seen = new Set<string>();\n for (const [index, resource] of resources.entries()) {\n const key = `${resource.kind}\\0${resource.id}`;\n if (seen.has(key)) {\n context.addIssue({\n code: \"custom\",\n message: \"selectedResources must not contain duplicates\",\n path: [index],\n });\n }\n seen.add(key);\n }\n })\n .optional(),\n subjectScope: z.enum([\"workspace\", \"subject\"]).optional(),\n })\n .strict()\n .superRefine((reference, context) => {\n if (!reference.selectedResources) return;\n if (!reference.connectionId) {\n context.addIssue({\n code: \"custom\",\n message: \"selectedResources requires connectionId\",\n path: [\"connectionId\"],\n });\n }\n if (!reference.provider) {\n context.addIssue({\n code: \"custom\",\n message: \"selectedResources requires provider\",\n path: [\"provider\"],\n });\n }\n });\nexport type McpServerConnectionRef = z.infer<typeof McpServerConnectionRefSchema>;\n\nconst SettingsSchema = z.object({\n serviceName: z.string().default(\"opengeni\"),\n environment: z.string().default(\"local\"),\n deploymentRevision: z.string().default(\"dev\"),\n // The release-train version baked into official images (OPENGENI_SERVER_VERSION).\n // Absent on dev/source builds — consumers must treat it as optional.\n serverVersion: z.string().optional(),\n databaseUrl: z.string().default(\"postgres://opengeni:opengeni@127.0.0.1:5432/opengeni\"),\n // Step I (§7.8 runtime half). Dedicated Postgres schema for the EMBEDDED\n // topology. Default \"\" → standalone: no search_path scoping, server default\n // (`public`). When set (e.g. \"opengeni\"), the db handle + the managed-auth\n // pool send `search_path = \"<dbSchema>\",\"opengeni_private\",\"public\"` so every\n // query resolves into the dedicated schema with NO query rewrite (schema-isolation contract F1).\n dbSchema: z.string().default(\"\"),\n // Step I (§7.7). RLS posture. \"force\" (default) = today's FORCE-RLS via the\n // non-owner `opengeni_app` role. \"scoped\" = the embedded owner-role path (the\n // GUC is still emitted defensively, so the query path is identical).\n rlsStrategy: z.enum([\"force\", \"scoped\"]).default(\"force\"),\n natsUrl: z.string().default(\"nats://127.0.0.1:4222\"),\n temporalHost: z.string().default(\"127.0.0.1:7233\"),\n temporalNamespace: z.string().default(\"default\"),\n temporalTaskQueue: z.string().default(\"opengeni-runs-ts\"),\n temporalTlsEnabled: EnvBoolean.default(false),\n temporalApiKey: z.string().optional(),\n temporalTlsServerName: z.string().optional(),\n temporalTlsRootCaCertificateBase64: z.string().optional(),\n temporalTlsClientCertificateBase64: z.string().optional(),\n temporalTlsClientPrivateKeyBase64: z.string().optional(),\n startupDependencyRetryAttempts: z.coerce.number().int().positive().default(30),\n startupDependencyRetryInitialDelayMs: z.coerce.number().int().positive().default(1000),\n startupDependencyRetryMaxDelayMs: z.coerce.number().int().positive().default(5000),\n observabilityStructuredLogs: EnvBoolean.default(false),\n observabilityMetricsEnabled: EnvBoolean.default(true),\n observabilityOtlpEndpoint: z.string().url().optional(),\n observabilityOtlpHeaders: z.string().default(\"\"),\n publicBaseUrl: z.string().url().optional(),\n // Base URL for the bring-your-own-compute agent release assets the get.<domain>\n // install routes redirect to. Defaults to this repo's GitHub Releases. The route\n // appends `/download/agent-v<ver>/<asset>`.\n agentReleasesBaseUrl: z\n .string()\n .url()\n .default(\"https://github.com/Cloudgeni-ai/opengeni/releases\"),\n // Explicit operator-controlled promotion pointer for `/agent/latest/*`.\n // Versioned agent releases are immutable; changing this setting promotes or\n // rolls back the stable channel without moving or deleting a provider tag.\n agentStableVersion: z\n .string()\n .regex(/^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)$/u)\n .default(\"0.1.8\"),\n productAccessMode: ProductAccessMode.default(\"local\"),\n billingMode: BillingMode.default(\"disabled\"),\n entitlementsMode: EntitlementsMode.default(\"none\"),\n usageLimitsMode: UsageLimitsMode.default(\"none\"),\n staticEntitlementsJson: z.string().default(\"{}\"),\n staticUsageLimitsJson: z.string().default(\"{}\"),\n delegationSecret: z.string().optional(),\n // sandbox workspace scoped stream-token HMAC secret (sandbox contract §C.3 / stream-token availability contract).\n // When unset, the API falls back to `delegationSecret` (the same HMAC envelope\n // family, `ogs_` vs `ogd_` prefix). REQUIRED-WHEN-DESKTOP, but the absence of\n // BOTH while sandboxDesktopEnabled=true is a GRACEFUL DEGRADE (DesktopStream\n // transport:null + a loud boot warning), NOT a hard boot-fail (stream-token availability contract).\n streamTokenSecret: z.string().optional(),\n // The desktop input plane (raw stream:control writes) is OFF in v1: even a\n // holder of stream:control gets 403 until this flips. Keeps stream:control a\n // declared-but-inert permission so later hardening is a flag flip.\n streamControlEnabled: EnvBoolean.default(false),\n // Existing-session explicit tool replacement is gated until every API and\n // worker instance understands durable tools_provided provenance.\n sessionTurnToolReplacementEnabled: EnvBoolean.default(false),\n toolspaceEnabled: EnvBoolean.default(false),\n toolspaceMaxCallsPerTurn: z.coerce.number().int().positive().default(200),\n // Optional release-coherent bootstrap hint for custom rigs/connected machines\n // that do not carry the stock-image ogtool binary. Exact stable versions only:\n // the agent must never guess a tag or silently install `latest`.\n ogtoolPackageSpec: z\n .string()\n .regex(/^@opengeni\\/ogtool@(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)$/u)\n .optional(),\n environmentsEncryptionKey: z.string().optional(),\n integrationsEnabled: EnvBoolean.default(false),\n integrationsStateSecret: z.string().optional(),\n integrationsAllowPrivateNetworkTargets: EnvBoolean.default(false),\n integrationsOauthClientsJson: z.string().default(\"{}\"),\n // Undefined is meaningful: the migration boundary persists the product\n // default of 3 when no deployment override is supplied.\n maxNestedAgentDepth: z.coerce.number().int().nonnegative().max(MAX_NESTED_AGENT_DEPTH).optional(),\n // Session goal guard rails. Goals are designed for runs that legitimately\n // span days, so length is bounded by pathology detection (no-progress\n // streaks, budget exhaustion), never by count. goalMaxAutoContinuations is\n // therefore UNSET by default (no cap); deployments may configure one, and\n // it then acts as a hard ceiling that per-goal overrides can only lower.\n goalMaxAutoContinuations: z.coerce.number().int().positive().optional(),\n goalNoProgressLimit: z.coerce.number().int().positive().default(3),\n // Per-segment ceiling on agent loop turns (model calls) within a single\n // session turn. Effectively unbounded by default for the same reason as\n // above; the graceful max-turns valve (idle + goal continuation, never a\n // session failure) remains as inert safety should a deployment set a cap.\n agentMaxModelCallsPerTurn: z.coerce.number().int().positive().default(1_000_000),\n // The model family's real context window in tokens. OpenGeni always performs\n // one durable, portable plaintext compaction transition; there is no\n // provider/server/off mode ladder.\n contextWindowTokens: z.coerce.number().int().positive().default(1_050_000),\n // Optional model-catalog effective input ceiling. Codex models expose this as\n // raw context_window * effective_context_window_percent; when absent, retain\n // the deployment-level window-minus-reserved-output behavior.\n contextEffectiveWindowTokens: z.coerce.number().int().positive().optional(),\n // Proactive compaction threshold as a ratio of the model context window.\n // Defaults to 90%: compact as late as possible — retained context beats early\n // headroom now that per-model windows are declared honestly (input-effective,\n // empirically measured), and the fail-closed reactive compact-on-reject path\n // absorbs any overshoot as one retried call rather than a dead session.\n // Clamped to [0.3, 0.9] so deployments can tune the trigger without\n // accidentally disabling compaction.\n contextCompactionThresholdRatio: z.coerce\n .number()\n .default(0.9)\n .transform((value) => {\n if (!Number.isFinite(value)) {\n return 0.9;\n }\n return Math.min(0.9, Math.max(0.3, value));\n }),\n // Tokens reserved for model output; subtracted from the window to get the\n // usable input budget B = contextWindowTokens - contextReservedOutputTokens.\n contextReservedOutputTokens: z.coerce.number().int().nonnegative().default(128_000),\n // Model-catalog auto-compact limit. When present it is clamped to\n // 90% of the raw window, matching Codex core's auto_compact_token_limit().\n contextAutoCompactThresholdTokens: z.coerce.number().int().positive().optional(),\n // Provider-neutral fallback for canonical model-facing tool-result text.\n // The current stable Codex catalog policy is 10k tokens; the truncator adds\n // Codex's 1.2x JSON serialization allowance when applying it.\n modelToolOutputTruncationTokens: z.coerce.number().int().positive().default(10_000),\n authRequired: EnvBoolean.default(false),\n accessKey: z.string().optional(),\n authAllowHealth: EnvBoolean.default(true),\n authAllowMetrics: EnvBoolean.default(false),\n apiHost: z.string().default(\"0.0.0.0\"),\n apiPort: z.coerce.number().int().positive().default(8000),\n workerHttpPort: z.coerce.number().int().positive().default(8001),\n opengeniMcpUrl: z.string().url().optional(),\n corsAllowOriginRegex: z.string().default(String.raw`^https?://(localhost|127\\.0\\.0\\.1)(:\\d+)?$`),\n openaiProvider: z.enum([\"openai\", \"azure\"]).default(\"openai\"),\n openaiApiKey: z.string().optional(),\n openaiBaseUrl: z.string().optional(),\n openaiModel: z.string().default(\"gpt-5.6-sol\"),\n openaiAllowedModels: z.string().default(\"gpt-5.6-sol,gpt-5.6-terra,gpt-5.6-luna\"),\n modelPricingJson: z.string().default(\"{}\"),\n // Extra (non-built-in) model providers, declared by the host as a JSON\n // provider registry. Each entry carries its own base URL, API key, wire API\n // (\"responses\" | \"chat\") and the models it exposes. The models a client may\n // use are the UNION of the built-in provider's allowed models and every\n // registry provider's models. validateSettings parses this at boot so a\n // malformed registry / unresolvable key / id collision fails fast.\n modelProvidersJson: z.string().default(\"[]\"),\n // Codex (ChatGPT) subscription: when enabled, a per-workspace connected\n // subscription is injected as a synthetic \"codex-subscription\" registry\n // provider whose models route through the ChatGPT backend (@opengeni/codex).\n codexSubscriptionEnabled: EnvBoolean.default(false), // OPENGENI_CODEX_SUBSCRIPTION_ENABLED\n codexProductSku: z.string().optional(), // OPENGENI_CODEX_PRODUCT_SKU (X-OpenAI-Product-Sku, apps only)\n // Progressive connector disclosure (Codex-CLI-style tool_search): on a codex\n // turn, flag the ~217 codex_apps connector tools `defer_loading:true` (dropping\n // their schemas from model context) and add one client-executed tool_search\n // tool that BM25-discloses only the matching connectors. Default OFF — a codex\n // turn is byte-for-byte unchanged until enabled. OPENGENI_CODEX_TOOL_SEARCH_ENABLED\n codexToolSearchEnabled: EnvBoolean.default(false),\n // credential allocator atomic, workspace-local credential allocation. Default OFF is a\n // deliberate rolling-deploy fence: migrate + roll every worker first, then\n // enable. Turning it off restores the legacy sticky selector without a schema\n // rollback; the additive lease table/cursor columns become inert.\n codexCredentialLeasingEnabled: EnvBoolean.default(false),\n // Decision-observability fence. When enabled, the worker emits one\n // bounded, metadata-only adaptive-policy replay record alongside the unchanged\n // sticky-sharded decision. It never changes placement/admission/failover.\n codexFleetPolicyShadowEnabled: EnvBoolean.default(false),\n // Multi-account P3 (auto-rotation): an account is \"near exhaustion\" — ineligible to be\n // rotated TO — when EITHER usage window (5h/weekly) is at/over this percent. Default 90 to\n // match the UI danger flip (UsageBar danger at pct >= 90). OPENGENI_CODEX_ROTATION_NEAR_EXHAUSTION_PCT.\n codexRotationNearExhaustionPct: z.coerce.number().int().min(1).max(100).default(90),\n openaiReasoningEffort: ReasoningEffort.default(\"low\"),\n openaiAllowedReasoningEfforts: z.string().default(\"low,medium,high,xhigh\"),\n openaiResponsesTransport: z.enum([\"http\", \"websocket\"]).default(\"http\"),\n // Provider-assigned item ids (rs_/msg_/fc_…) in Responses API input are\n // resolved against the provider's server-side response store. That store is\n // not durable enough to anchor long runs on: a response that streamed fine\n // can be missing from the store on the very next model call, which then\n // fails with 400 \"Item with id ... not found\". \"strip\" removes the ids from\n // every model-call input so requests are self-contained — conversation\n // truth already lives client-side in session_history_items. \"preserve\"\n // keeps the SDK's pass-through behavior.\n openaiProviderItemIds: z.enum([\"strip\", \"preserve\"]).default(\"strip\"),\n // With ids stripped the provider cannot resolve prior reasoning server-side,\n // so request reasoning.encrypted_content and send it back with each call:\n // reasoning continuity without depending on provider-side storage.\n openaiReasoningEncryptedContent: EnvBoolean.default(true),\n // Model-call retry budget for transient provider failures (429s and friends).\n // The openai client default of 2 retries is too small for sustained TPM\n // backpressure during long autonomous runs.\n openaiMaxRetries: z.coerce.number().int().nonnegative().default(5),\n // Native hosted web search. The live Azure Responses path executes the\n // hosted web_search tool, so this is provider-unconditional: ON by default\n // on every provider, exposed only so operators can disable it. When true,\n // buildOpenGeniAgent attaches webSearchTool() to the agent's tools — it is\n // merged with the MCP-server tools (getAllTools = [...mcpTools, ...tools])\n // and the sandbox capability tools, never replacing them.\n webSearchEnabled: EnvBoolean.default(true),\n // Deployment-default agent persona template (the white-label surface). The\n // runtime resolves the effective template per turn as\n // per-session-override > per-workspace override > this default, substitutes\n // the non-bypassable CORE at AGENT_INSTRUCTIONS_CORE_PLACEHOLDER (or appends\n // it when the template omits the marker), and uses the result as the agent's\n // instructions. Defaulting to DEFAULT_AGENT_INSTRUCTIONS keeps the composed\n // default pinned by runtime tests.\n agentInstructionsTemplate: z.string().default(DEFAULT_AGENT_INSTRUCTIONS),\n azureOpenaiBaseUrl: z.string().optional(),\n azureOpenaiEndpoint: z.string().optional(),\n azureOpenaiDeployment: z.string().optional(),\n azureOpenaiApiVersion: z.string().optional(),\n azureOpenaiApiKey: z.string().optional(),\n azureOpenaiAdToken: z.string().optional(),\n disableOpenaiTracing: EnvBoolean.default(false),\n sandboxBackend: SandboxBackend.default(\"docker\"),\n dockerImage: z.string().default(\"opengeni-sandbox:local\"),\n dockerExposedPorts: z.string().default(\"\"),\n dockerNetwork: z.string().optional(),\n modalAppName: z.string().default(\"opengeni-sandbox\"),\n modalImageRef: z.string().optional(),\n // Name of a Modal Secret (containing REGISTRY_USERNAME + REGISTRY_PASSWORD) used\n // to authenticate the pull of `modalImageRef` from a PRIVATE registry. When UNSET\n // (the default), the sandbox image is pulled UNAUTHENTICATED — i.e. it must be a\n // PUBLIC registry tag, which is the only shape the Agents-extension Modal backend\n // supports out of the box (`Image.fromRegistry(tag)` with no secret). Set this to\n // run a private image (e.g. a cloud-hosted ACR/ECR/GCR digest): the runtime resolves\n // the named Secret and builds the image via `fromRegistry(tag, secret)` before the\n // first sandbox is created. Knob: OPENGENI_MODAL_IMAGE_REGISTRY_SECRET.\n modalImageRegistrySecret: z.string().optional(),\n // Modal's hard sandbox lifetime (timeoutMs = this * 1000), counted from each\n // create/resume — it is the BACKSTOP that reclaims a box if the reaper/worker is\n // down, NOT the warm-window controller (that's sandboxIdleGraceMs). It must\n // comfortably exceed reaperPeriod + idleGrace so the reaper terminates a\n // genuinely-idle box FIRST; the boot invariant below enforces that. Default 1h\n // (was 900s/15min): the 15-min drain grace counts from the user's LAST release,\n // but Modal's clock starts at the preceding turn's resume — so a 15-min grace on\n // top of a 900s lifetime would let Modal kill the box mid-warm-window. 3600s\n // leaves ~45min of headroom for the active turn before the warm window opens.\n // Knob: OPENGENI_MODAL_TIMEOUT_SECONDS.\n modalTimeoutSeconds: z.coerce.number().int().positive().default(3600),\n modalTokenId: z.string().optional(),\n modalTokenSecret: z.string().optional(),\n modalEnvironment: z.string().optional(),\n // modal gap-fill: idleTimeoutMs + workspacePersistence were unmapped (module 03 §4.1).\n //\n // CRITICAL (sandbox-file-persistence): when this is UNSET the Modal SDK sends\n // idleTimeoutSecs=undefined, so Modal applies its OWN short server-default idle\n // timeout (~minutes) — and a box between turns sits with NO active connection,\n // so that idle clock runs and Modal idle-reaps the box LONG before OpenGeni's\n // own reaper waits out sandboxIdleGraceMs (15min) to resume+persist+terminate\n // it. The observed failure: every drain logs \"drainable box already gone\n // (NotFound on resume)\", persistWorkspace() never fires, /workspace is lost.\n // Modal's idle-reap is a SECOND reaper racing OpenGeni's — and it wins. The fix:\n // OpenGeni OWNS box lifecycle via its reaper + the hard modalTimeoutSeconds\n // backstop, so the Modal idle-reap must NOT fire first. We default the effective\n // idle timeout to the hard lifetime (effectiveModalIdleTimeoutSeconds), making\n // the box survive its full warm window so the reaper can snapshot it. Set this\n // explicitly (OPENGENI_MODAL_IDLE_TIMEOUT_SECONDS) only to deliberately idle-reap\n // SOONER than the hard lifetime; the boot invariant forbids a value that would\n // reap before reaperPeriod + idleGrace elapses.\n modalIdleTimeoutSeconds: z.coerce.number().int().positive().optional(),\n // /workspace FILE PERSISTENCE across warm/cold cycles. Defaults to\n // `snapshot_filesystem` so EVERY box is created persistence-capable: the reaper\n // snapshots the live box before it terminates a drained group, and a later\n // cold-restore hydrates a fresh box from that snapshot (sandbox-file-persistence).\n // `snapshot_filesystem` requires the manifest declare NO ephemeralPersistencePaths\n // (buildManifest never sets entry.ephemeral, so it never downgrades to tar). Set\n // OPENGENI_MODAL_WORKSPACE_PERSISTENCE=tar to opt back out (no native snapshot;\n // the reaper persists a tar archive — same store+hydrate plumbing, slower).\n modalWorkspacePersistence: z\n .enum([\"tar\", \"snapshot_filesystem\", \"snapshot_directory\"])\n .default(\"snapshot_filesystem\"),\n // Snapshot GC backstop (sandbox-file-persistence): the reaper keeps ONE latest\n // filesystem snapshot per lease (delete-prior-on-supersede + delete-on-teardown).\n // This is the TTL retention floor for the periodic orphan sweep — a snapshot\n // whose lease is cold and older than this is best-effort deleted so a crashed\n // persist-then-no-restore never leaks a Modal image. 0 disables the TTL sweep\n // (delete-on-supersede/teardown still run). Default 7 days.\n modalSnapshotRetentionSeconds: z.coerce.number().int().nonnegative().default(604_800),\n // Shared desktop toggle: this module reads it for the 6080 port-merge; the\n // owner module (P4.x) acts on it to launch the display stack.\n sandboxDesktopEnabled: EnvBoolean.default(false),\n // Human take-control toggle: when ON (default) the negotiated DesktopStream\n // cell advertises mode \"interactive\" — the noVNC viewer can drive mouse+keyboard\n // into :0 (x11vnc runs without -viewonly). Turn it OFF for a genuinely read-only\n // deployment: the cell reports mode \"read-only\" and the client disables the\n // \"Take control\" affordance. Independent of computerUseReadOnly (the AGENT\n // driver); this gates the HUMAN viewer plane.\n sandboxDesktopInteractive: EnvBoolean.default(true),\n // REAL PTY terminal toggle (P5.t): gates the ttyd pty-ws plane (7681) the API\n // mints over the SAME tunnel as the desktop. Defaults ON — the interactive\n // terminal is a baseline structured-service surface (unlike the heavier desktop\n // pixel plane); a deployment can turn it off to fall back to the read-only\n // sse-events command firehose. The 7681 port-merge tracks sandboxDesktopEnabled\n // (a desktop-capable image is the one that bakes ttyd).\n sandboxTerminalEnabled: EnvBoolean.default(true),\n // The desktop framebuffer geometry the pixel plane advertises + launches the\n // display stack with (P4.2). v1 has no live RANDR resize; a change is a full\n // down→up restart. Defaults match the proven spike geometry (1280x800).\n streamResolutionWidth: z.coerce.number().int().positive().default(1280),\n streamResolutionHeight: z.coerce.number().int().positive().default(800),\n // P4.3 computer-use: the agent drives the SAME :0 humans watch (xdotool/XTEST +\n // scrot). Gated by sandboxDesktopEnabled + a desktop-capable backend in\n // buildAgentCapabilities; computerUseReadOnly:false is the agent-driver default\n // (it must click/type — the human viewer plane is the read-only one).\n computerUseEnabled: EnvBoolean.default(true),\n computerUseReadOnly: EnvBoolean.default(false),\n // P4.3 recording loop: ffmpeg x11grab of :0 → mp4/webm → @opengeni/storage.\n // recordingMaxBytes caps the in-memory finalize buffer (≤ storage single-PUT);\n // recordingMaxSeconds is the ffmpeg -t hard ceiling (bounds a multi-day turn).\n recordingEnabled: EnvBoolean.default(true),\n recordingDefaultCodec: z.enum([\"h264-mp4\", \"vp9-webm\"]).default(\"h264-mp4\"),\n // Workbench v2 turn-end workspace capture. When on, the turn\n // activity probes the box's changed files off the live box at turn end and\n // persists a capture revision (blobs in @opengeni/storage) so the workbench\n // paints cold/offline sessions with zero machine round-trips. Best-effort and\n // fully behind this flag: off ⇒ capture is skipped and reads fall back to the\n // live/wake path (status-quo behavior). Default on; explicit per environment.\n workspaceCaptureEnabled: EnvBoolean.default(true),\n recordingFramerate: z.coerce.number().int().positive().default(15),\n recordingMaxSeconds: z.coerce.number().int().positive().default(600),\n recordingMaxBytes: z.coerce.number().int().positive().default(268_435_456), // 256 MB\n // --- daytona ---\n daytonaApiKey: z.string().optional(),\n daytonaApiUrl: z.string().url().optional(),\n daytonaTarget: z.string().optional(),\n daytonaImage: z.string().optional(),\n daytonaSnapshotName: z.string().optional(),\n daytonaAutoStopInterval: z.coerce.number().int().nonnegative().optional(), // 0 disables idle-kill\n daytonaTimeoutSeconds: z.coerce.number().int().positive().optional(),\n daytonaExposedPortUrlTtlSeconds: z.coerce.number().int().positive().optional(),\n // --- runloop ---\n runloopApiKey: z.string().optional(),\n runloopBaseUrl: z.string().url().optional(),\n runloopBlueprintName: z.string().optional(),\n runloopBlueprintId: z.string().optional(),\n runloopTunnel: EnvBoolean.default(true),\n runloopKeepAliveSeconds: z.coerce.number().int().positive().optional(),\n // --- e2b (SDK reads E2B_API_KEY from env; mirrored for validation + forwarding) ---\n e2bApiKey: z.string().optional(),\n e2bTemplate: z.string().optional(),\n e2bTimeoutSeconds: z.coerce.number().int().positive().optional(),\n e2bTimeoutAction: z.enum([\"pause\", \"kill\"]).optional(),\n e2bAllowInternetAccess: EnvBoolean.optional(),\n e2bAutoResume: EnvBoolean.optional(),\n e2bWorkspacePersistence: z.enum([\"tar\", \"snapshot\"]).optional(),\n // --- blaxel ---\n blaxelApiKey: z.string().optional(),\n blaxelImage: z.string().optional(),\n blaxelRegion: z.string().optional(),\n blaxelExposedPortPublic: EnvBoolean.optional(), // public vs bl_preview_token\n blaxelExposedPortUrlTtlSeconds: z.coerce.number().int().positive().optional(),\n blaxelMemoryMb: z.coerce.number().int().positive().optional(),\n blaxelTtl: z.string().optional(),\n // --- cloudflare (headless) ---\n cloudflareWorkerUrl: z.string().url().optional(),\n cloudflareApiKey: z.string().optional(),\n // --- vercel (headless) ---\n vercelToken: z.string().optional(),\n vercelProjectId: z.string().optional(),\n vercelTeamId: z.string().optional(),\n vercelRuntime: z.string().optional(),\n // --- sandbox ownership inversion (P1.2 rollout flag, default OFF) ---\n // The keystone flag for the stateless resume-by-id model. When FALSE the\n // agent-turn path is BYTE-FOR-BYTE today's build-and-discard behavior (no\n // lease acquire, no resume-by-id, no non-owned injection). When TRUE the turn\n // activity acquires the group lease, resumes the one box by id from the lease\n // envelope, injects it as a NON-OWNED RunConfig session (the SDK never reaps\n // it — the proven keystone), and releases the holder in finally. Uses\n // EnvBoolean (NOT z.coerce.boolean(), which would coerce \"false\" -> true and\n // turn the flag ON the moment anyone set the env var to disable it).\n sandboxOwnershipEnabled: EnvBoolean.default(false),\n // --- standalone rig-verifier ownership rollout flag, default OFF ---\n // Rig verification creates a throwaway provider sandbox outside the normal\n // session-turn path. When enabled, that sandbox must first acquire the same\n // durable lease lifecycle used by session boxes so the global orphan sweep\n // recognizes its exact provider instance. Keep this separate from the general\n // sandboxOwnershipEnabled rollout: every reaper worker must understand verifier\n // leases before dispatch is enabled. When false the verifier fails closed before\n // provider create; it never falls back to the legacy unowned path.\n rigVerificationLeaseOwnershipEnabled: EnvBoolean.default(false),\n // --- lazy sandbox provisioning rollout flag, default OFF ---\n // Only effective when sandboxOwnershipEnabled is ALSO on (lazy provisioning is a\n // property of the owned path — the SDK never creates/resumes an injected session,\n // so we control when the box is established). When TRUE, a turn does NOT provision\n // its box at turn start: the lease acquire + resume-by-id + hooks + downloads +\n // heartbeat + recording are deferred to an in-process single-flight provisioner\n // that runs the FIRST time a sandbox op is dispatched (via the routing proxy's\n // resolveActiveBackend). A turn whose model never calls a sandbox-backed tool ends\n // with NO lease row and ZERO warm-seconds. When FALSE (or ownership off) the turn\n // provisions eagerly exactly as today — byte-for-byte. EnvBoolean (NOT\n // z.coerce.boolean(), which coerces \"false\" -> true and would turn the flag ON the\n // moment anyone set the env var to disable it).\n sandboxLazyProvisionEnabled: EnvBoolean.default(false),\n // --- bring-your-own-compute (selfhosted 11th backend) rollout flag, default OFF ---\n // The keystone flag for the whole selfhosted feature (the enrollment device-flow,\n // the NATS control plane, the relay stream tier). When FALSE the enrollment routes\n // 404 (invisible — the surface does not exist for this deployment) and the\n // selfhosted backend is inert; boot is unaffected. EnvBoolean (NOT\n // z.coerce.boolean(), which coerces \"false\" -> true). Flipped per-environment via\n // the deploy-staging IaC secret/configmap pattern.\n sandboxSelfhostedEnabled: EnvBoolean.default(false),\n // Gates the op-stream (streaming exec) transport to Connected Machines. The\n // runner must ALSO advertise Capabilities.op_stream; default off, and legacy\n // request/reply exec is the permanent fallback. EnvBoolean (NOT\n // z.coerce.boolean(), which coerces \"false\" -> true).\n agentOpStreamEnabled: EnvBoolean.default(false),\n // The HMAC secret the control plane signs the enrollment bearer credential with\n // (the `oge_` envelope the agent presents back to the control plane). Optional:\n // when ABSENT and sandboxSelfhostedEnabled is on, the poll route reports the\n // credential plane disabled (graceful degrade, mirrors streamTokenSecret). NEVER\n // logged. Lives in the opengeni-runtime secret (Helm-clobbered configmap avoided).\n enrollmentSigningSecret: z.string().optional(),\n // Connect-info the EnrollmentCredentials hand the agent: the NATS server URL(s)\n // the agent dials for the control plane, and the relay edge base URL for streams.\n // The per-workspace NATS Account creds binding is infra-deferred (M4/relay\n // milestone) — the poll returns these endpoints + a placeholder creds field.\n selfhostedNatsUrl: z.string().optional(),\n selfhostedRelayUrl: z.string().optional(),\n // The HMAC secret the control plane signs the agent's relay PRODUCER token with\n // (the `ogr_` envelope threaded into EnrollmentCredentials.relayToken; M8b/design\n // §10.5). The relay verifies the producer token with the SAME secret. Optional:\n // when ABSENT the poll returns an empty relayToken (graceful degrade — the stream\n // plane is simply unavailable until configured). Falls back to streamTokenSecret /\n // delegationSecret (same HMAC family) so a deployment with a stream-token secret\n // needs no second one. NEVER logged. Lives in the opengeni-runtime secret.\n selfhostedRelayTokenSecret: z.string().optional(),\n // The minisign PUBLIC key the agent pins for self-update verification (handed to\n // the agent in EnrollmentCredentials; the SECRET key lives only in CI).\n agentUpdatePublicKey: z.string().optional(),\n // --- NATS auth-callout tenancy boundary (bring-your-own-compute M-AUTH; design\n // §10.1 NATS Accounts per workspace + §17 the isolation smoke) -------------\n // nats-server is configured with AUTH CALLOUT: an external agent connects\n // presenting its `oge_` enrollment bearer as the connect auth-token; the server\n // issues an authorization request on $SYS.REQ.USER.AUTH to our responder, which\n // validates the bearer and returns a SIGNED NATS user JWT scoped to pub/sub ONLY\n // `agent.<ws>.>` (+ `_INBOX.>`). That per-subject scope IS the per-workspace\n // isolation. These are deployment-level secrets in the opengeni-runtime secret\n // (Helm-clobbered configmap avoided), all OPTIONAL: when the callout plane is not\n // configured the responder simply does not start (selfhosted agents cannot\n // connect — graceful, never a boot-fail).\n //\n // The callout account SIGNING SEED (`SA...`). Both the user JWT and the\n // authorization-response JWT are signed by this account key; its public key\n // (`A...`) is the `auth_callout.issuer` in the server config. NEVER logged.\n selfhostedNatsCalloutAccountSeed: z.string().optional(),\n // The TARGET ACCOUNT NAME the minted user is placed into (the server-config-mode\n // `auth_callout.account`, e.g. \"APP\"). The responder writes it as the minted user\n // JWT `aud` so nats-server binds the agent to this account — the SAME account the\n // privileged control plane connects into, so `agent.<ws>.<id>.rpc` request/reply\n // routes. Optional; resolveNatsCalloutConfig defaults it to \"APP\".\n selfhostedNatsCalloutAccountName: z.string().optional(),\n // The callout RESPONDER's own NATS login (one of the `auth_callout.auth_users`\n // in the AUTH account) — the responder connects with this to subscribe\n // $SYS.REQ.USER.AUTH. Username/password.\n selfhostedNatsCalloutUser: z.string().optional(),\n selfhostedNatsCalloutPassword: z.string().optional(),\n // The PRIVILEGED control-plane login (api/worker): a static account user that may\n // request `agent.*.rpc` + receive its inbox replies. The event bus + the\n // selfhosted control RPC ride THIS connection. Username/password; when unset the\n // bus connects anonymously (local dev / a NATS with no auth_callout).\n selfhostedNatsControlUser: z.string().optional(),\n selfhostedNatsControlPassword: z.string().optional(),\n // --- selfhosted (Connected Machine) control/exec op deadlines ---------------\n // The control plane splits its op deadline in two. CONTROL ops (ping / fs / git /\n // desktop / pty) must stay responsive so a machine's liveness is never masked by a\n // slow op, so they use the short control timeout. EXEC gets its OWN, larger budget:\n // a real command (compile, test run, dependency install) routinely outlives the\n // control timeout, and before the split a long command was killed at the ~30s\n // control wall. The agent kills the exec child at this deadline; the wire waits\n // slightly longer (SELFHOSTED_EXEC_REPLY_GRACE_MS) for the typed timed-out reply.\n //\n // The exec default is a DELIBERATELY MODEST 2min (not 5): the agent-side admission\n // pool is (until a later agent release) a FLAT 8 permits with no per-class split,\n // so 8 slow execs holding a permit for 5 minutes would blanket-DRAIN every fs/git\n // op — shipping the amplifier before the class-aware-admission fix. 2min still\n // clears the large majority of the observed >30s exec tail; genuinely long jobs run\n // in the background (see the exec-deadline hint) or raise the knob per deployment.\n // Knobs: OPENGENI_SANDBOX_SELFHOSTED_EXEC_TIMEOUT_MS (default 2min) and\n // OPENGENI_SANDBOX_SELFHOSTED_CONTROL_TIMEOUT_MS (default 30s).\n sandboxSelfhostedExecTimeoutMs: z.coerce.number().int().positive().default(120_000),\n sandboxSelfhostedControlTimeoutMs: z.coerce.number().int().positive().default(30_000),\n // --- sandbox lease cadences (cadence invariant validated at boot below) ---\n // reaperPeriod < viewerHolderTTL, and reaperPeriod + idleGrace < the EFFECTIVE\n // box idle timeout (effectiveModalIdleTimeoutSeconds, which defaults to the hard\n // modalTimeoutSeconds). No keep-alive loop: between turns the box survives on its\n // idle timeout — which we pin high enough (via the idle-timeout default) that\n // OpenGeni's reaper, not Modal's idle-reap, governs teardown so /workspace is\n // snapshotted before the box dies (sandbox-file-persistence).\n sandboxLeaseReaperPeriodMs: z.coerce.number().int().positive().default(30_000),\n sandboxViewerHolderTtlMs: z.coerce.number().int().positive().default(90_000),\n // The DRAIN grace: how long a refcount-0 (draining) lease stays WARM before the\n // reaper resume-by-ids the box and terminates it. This is the cost-vs-snappiness\n // dial — when the user navigates away the box keeps refcount 0, but it survives\n // this whole window so a \"glanced away then came back\" re-arms the SAME warm box\n // (acquireLease re-arms draining->warm; the reaper's BEFORE-terminate re-read\n // skips a re-armed box). Default 15min so a brief detour never cold-creates a\n // fresh EMPTY box; lower it to trade warm cost for a snappier reclaim. Knob:\n // OPENGENI_SANDBOX_IDLE_GRACE_MS.\n sandboxIdleGraceMs: z.coerce.number().int().positive().default(900_000),\n // MID-SESSION /workspace snapshot cadence (sandbox-file-persistence). The\n // reaper's drain-persist only protects boxes the reaper itself kills; a box\n // that dies any other way (Modal's hard creation-time timeout on a session\n // busy past it, provider OOM/infra death) loses everything since the last\n // clean drain. While a turn holds the box, the turn heartbeat and turn-end\n // both take a snapshot when at least this interval has passed since the last\n // one (same epoch-fenced fold-onto-lease seam as the drain), bounding the\n // worst-case loss of ANY unclean box death to this window. 0 disables.\n // Knob: OPENGENI_SANDBOX_SNAPSHOT_INTERVAL_MS. Default 15min.\n sandboxSnapshotIntervalMs: z.coerce.number().int().min(0).default(900_000),\n // Maximum time a best-effort /workspace snapshot capture may hold turn/reaper\n // cleanup. A hung provider snapshot must never pin a lease holder, block\n // graceful shutdown, or become permission to GC an older archive. Timeout is\n // treated exactly like a failed best-effort snapshot. Knob:\n // OPENGENI_SANDBOX_SNAPSHOT_TIMEOUT_MS. Default 60s.\n sandboxSnapshotTimeoutMs: z.coerce.number().int().positive().default(60_000),\n // expires_at refresh window for a held lease (>> the turn 10s heartbeat so a\n // single missed heartbeat never TTL-reaps a live turn). The warming TTL is the\n // window a cold->warming spawner has to commit warm before a reaper resets it.\n sandboxLeaseTtlMs: z.coerce.number().int().positive().default(90_000),\n sandboxLeaseWarmingTtlMs: z.coerce.number().int().positive().default(120_000),\n // Overall user-facing budget for warming a sandbox lease. Unlike the lease TTL\n // (a liveness/reaper cadence), this bounds how long one turn waits for capacity\n // or provider creation before surfacing a clear turn.failed error.\n sandboxWarmingTimeoutMs: z.coerce.number().int().positive().default(600_000),\n // Rig setup-script budget (M3): the wall-clock timeout the rig-setup lifecycle\n // hook runs its script under, distinct from the 120s per-command lifecycle\n // default (a rig may compile/install heavy tooling on first cold create).\n // Env: OPENGENI_RIG_SETUP_TIMEOUT_MS. Default 10min.\n rigSetupTimeoutMs: z.coerce.number().int().positive().default(600_000),\n // --- sandbox warm-time billing (P2.1) ---\n // Per-backend warm rate (usd_micros/sec), like modelPricingJson: an empty {}\n // means warm-cost is not debited (warm-seconds are still metered for audit).\n // Shape: { \"modal\": 5, \"runloop\": 4, ... }. Backends absent here meter\n // warm-seconds but accrue NO warm_cost / debit (rate 0).\n sandboxWarmRateMicrosPerSecondJson: z.string().default(\"{}\"),\n // Per-workspace warm cap (cumulative warm-seconds since the start of the UTC\n // month, summed over sandbox.warm_seconds). 0 = unbounded. A workspace over the\n // cap force-drains its VIEWER-ONLY boxes (guarded AND turn_holders=0 — a paying\n // turn is never killed); the reaper then stop()s at refcount 0.\n sandboxMaxWarmSecondsPerWorkspace: z.coerce.number().int().nonnegative().default(0),\n sandboxPreparationProfiles: z.string().default(\"none\"),\n sandboxEnvAllowlist: z.string().default(\"\"),\n objectStorageEndpoint: z.string().url().optional(),\n objectStorageSandboxEndpoint: z.string().url().optional(),\n objectStorageBackend: z\n .enum([\"s3-compatible\", \"aws-s3\", \"azure-blob\", \"gcs\"])\n .default(\"s3-compatible\"),\n objectStorageBucket: z.string().min(1).default(\"opengeni-files\"),\n objectStorageRegion: z.string().min(1).default(\"us-east-1\"),\n objectStorageS3Provider: z.string().min(1).default(\"Minio\"),\n objectStorageAccessKeyId: z.string().optional(),\n objectStorageSecretAccessKey: z.string().optional(),\n objectStorageForcePathStyle: EnvBoolean.default(true),\n objectStorageAzureConnectionString: z.string().optional(),\n objectStorageAzureAccountName: z.string().optional(),\n objectStorageAzureAccountKey: z.string().optional(),\n objectStorageAzureEndpoint: z.string().url().optional(),\n objectStorageGcsProjectId: z.string().optional(),\n objectStorageGcsCredentialsJson: z.string().optional(),\n objectStorageGcsKeyFilename: z.string().optional(),\n objectStorageGcsApiEndpoint: z.string().url().optional(),\n documentParser: z.string().min(1).default(\"liteparse\"),\n documentChunkSize: z.coerce.number().int().positive().default(1200),\n documentChunkOverlap: z.coerce.number().int().nonnegative().default(160),\n documentEmbeddingProvider: z.enum([\"openai\", \"deterministic\"]).default(\"openai\"),\n documentEmbeddingModel: z.string().min(1).default(\"text-embedding-3-large\"),\n documentEmbeddingDimensions: z.coerce.number().int().positive().default(3072),\n documentEmbeddingApiKey: z.string().optional(),\n documentEmbeddingBaseUrl: z.string().url().optional(),\n gitAuthorName: z.string().optional(),\n gitAuthorEmail: z.string().optional(),\n gitCommitterName: z.string().optional(),\n gitCommitterEmail: z.string().optional(),\n githubAppManifestBaseUrl: z.string().optional(),\n githubAppManifestStateSecret: z.string().optional(),\n githubAppId: z.string().optional(),\n githubClientId: z.string().optional(),\n githubClientSecret: z.string().optional(),\n githubAppSlug: z.string().optional(),\n githubWebhookSecret: z.string().optional(),\n githubAppPrivateKey: z.string().optional(),\n betterAuthSecret: z.string().optional(),\n betterAuthAllowedHosts: z.string().default(\"\"),\n betterAuthCookieDomain: z.string().optional(),\n betterAuthTrustedOrigins: z.string().default(\"\"),\n resendApiKey: z.string().optional(),\n emailFrom: z.string().default(\"OpenGeni <auth@mail.opengeni.ai>\"),\n stripeSecretKey: z.string().optional(),\n stripePublishableKey: z.string().optional(),\n stripeWebhookSecret: z.string().optional(),\n stripeCreditsProductId: z.string().optional(),\n mcpServers: z\n .array(\n z.object({\n id: z.string().min(1).regex(registryId),\n name: z.string().min(1).optional(),\n url: z.string().url(),\n allowedTools: z.array(z.string().min(1)).optional(),\n timeoutMs: z.number().int().positive().optional(),\n cacheToolsList: z.boolean().default(false),\n /** Runtime approval policy, overlaid from an attempt-frozen session snapshot. */\n requireApproval: SessionMcpApprovalPolicy.optional(),\n /**\n * Extra request headers sent to this MCP server (credential injection\n * for workspace-enabled capability MCPs). Populated at runtime from\n * encrypted capability-installation credentials; do not put secrets in\n * OPENGENI_MCP_SERVERS.\n */\n headers: z.record(z.string(), z.string()).optional(),\n connectionRef: McpServerConnectionRefSchema.optional(),\n }),\n )\n .default([]),\n});\n\nexport type Settings = z.infer<typeof SettingsSchema>;\nexport type McpServerConfig = Settings[\"mcpServers\"][number];\nexport type TemporalTlsConnectionConfig = {\n serverNameOverride?: string;\n serverRootCACertificate?: Uint8Array;\n clientCertPair?: {\n crt: Uint8Array;\n key: Uint8Array;\n };\n};\nexport type TemporalConnectionOptions = {\n address: string;\n tls?: true | TemporalTlsConnectionConfig;\n apiKey?: string;\n};\nexport type ModelPricing = {\n inputMicrosPerMillionTokens: number;\n cachedInputMicrosPerMillionTokens?: number | undefined;\n outputMicrosPerMillionTokens: number;\n marginBps?: number | undefined;\n};\nexport type ModelPricingScheduleV1 = {\n default: ModelPricing;\n inputTokenTiers?:\n | Array<{\n minimumInputTokens: number;\n pricing: ModelPricing;\n }>\n | undefined;\n};\nexport type ModelUsageInput = {\n inputTokens?: number | undefined;\n outputTokens?: number | undefined;\n totalTokens?: number | undefined;\n inputTokensDetails?: Record<string, number> | Array<Record<string, number>> | undefined;\n requestUsageEntries?: ModelUsageInput[] | undefined;\n};\n\nexport type StaticUsageLimitsConfig = StaticUsageLimits;\nexport type EntitlementsConfig = Entitlements;\n\nconst ModelPricingSchema = z.object({\n inputMicrosPerMillionTokens: z.number().int().nonnegative(),\n cachedInputMicrosPerMillionTokens: z.number().int().nonnegative().optional(),\n outputMicrosPerMillionTokens: z.number().int().nonnegative(),\n marginBps: z.number().int().min(0).max(100_000).optional(),\n});\n\nconst ModelPricingScheduleSchema = z\n .object({\n default: ModelPricingSchema,\n inputTokenTiers: z\n .array(\n z.object({\n minimumInputTokens: z.number().int().nonnegative(),\n pricing: ModelPricingSchema,\n }),\n )\n .optional(),\n })\n .superRefine((schedule, ctx) => {\n let previous = -1;\n for (const [index, tier] of (schedule.inputTokenTiers ?? []).entries()) {\n if (tier.minimumInputTokens <= previous) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"inputTokenTiers\", index, \"minimumInputTokens\"],\n message: \"input-token tier thresholds must be strictly increasing\",\n });\n }\n previous = tier.minimumInputTokens;\n }\n });\n\nexport const CapabilitySupportV1 = z.enum([\"supported\", \"unsupported\", \"unknown\"]);\nexport type CapabilitySupportV1 = z.infer<typeof CapabilitySupportV1>;\n\nexport const CapabilityStateV1Schema = z\n .object({\n upstream: CapabilitySupportV1,\n runnable: z.boolean(),\n })\n .superRefine((state, ctx) => {\n if (state.upstream === \"unsupported\" && state.runnable) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"runnable\"],\n message: \"an upstream-unsupported capability cannot be runnable\",\n });\n }\n });\nexport type CapabilityStateV1 = z.infer<typeof CapabilityStateV1Schema>;\n\nconst ModelModalityV1 = z.enum([\"text\", \"image\", \"audio\"]);\nconst ModelLatencyModeV1 = z.enum([\"standard\", \"priority\", \"fast\"]);\n\nexport const ModelCapabilitiesV1Schema = z\n .object({\n reasoning: CapabilityStateV1Schema.extend({\n efforts: z.array(ReasoningEffort),\n defaultEffort: ReasoningEffort.nullable(),\n required: z.boolean(),\n }),\n functionCalling: CapabilityStateV1Schema,\n structuredOutput: CapabilityStateV1Schema,\n hostedTools: z.object({\n webSearch: CapabilityStateV1Schema,\n xSearch: CapabilityStateV1Schema,\n codeExecution: CapabilityStateV1Schema,\n }),\n inputModalities: z.array(ModelModalityV1).min(1),\n outputModalities: z.array(ModelModalityV1).min(1),\n transports: z.object({\n sse: CapabilityStateV1Schema,\n responsesWebSocket: CapabilityStateV1Schema,\n realtimeAudio: CapabilityStateV1Schema,\n }),\n latencyModes: z\n .array(\n z.object({\n id: ModelLatencyModeV1,\n upstream: CapabilitySupportV1,\n runnable: z.boolean(),\n billingMultiplierBps: z.number().int().positive().optional(),\n }),\n )\n .min(1),\n })\n .superRefine((capabilities, ctx) => {\n const efforts = new Set(capabilities.reasoning.efforts);\n if (efforts.size !== capabilities.reasoning.efforts.length) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"reasoning\", \"efforts\"],\n message: \"reasoning efforts must be unique\",\n });\n }\n if (\n capabilities.reasoning.defaultEffort !== null &&\n !efforts.has(capabilities.reasoning.defaultEffort)\n ) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"reasoning\", \"defaultEffort\"],\n message: \"the default reasoning effort must be one of the supported efforts\",\n });\n }\n if (capabilities.reasoning.runnable && capabilities.reasoning.efforts.length === 0) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"reasoning\", \"efforts\"],\n message: \"a runnable reasoning capability must declare at least one effort\",\n });\n }\n for (const field of [\"inputModalities\", \"outputModalities\"] as const) {\n if (new Set(capabilities[field]).size !== capabilities[field].length) {\n ctx.addIssue({\n code: \"custom\",\n path: [field],\n message: `${field} must be unique`,\n });\n }\n }\n const latencyIds = new Set<string>();\n for (const [index, mode] of capabilities.latencyModes.entries()) {\n if (latencyIds.has(mode.id)) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"latencyModes\", index, \"id\"],\n message: \"latency mode ids must be unique\",\n });\n }\n latencyIds.add(mode.id);\n if (mode.upstream === \"unsupported\" && mode.runnable) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"latencyModes\", index, \"runnable\"],\n message: \"an upstream-unsupported latency mode cannot be runnable\",\n });\n }\n }\n });\nexport type ModelCapabilitiesV1 = z.infer<typeof ModelCapabilitiesV1Schema>;\n\nexport type ModelDeploymentV1 = {\n upstreamModelId: string;\n wireApi: ModelProviderApi;\n};\n\nexport type ModelExecutionLimitsV1 = {\n contextWindowTokens: number | null;\n effectiveContextWindowTokens: number | null;\n autoCompactTokenLimit: number | null;\n toolOutputTruncationTokens: number | null;\n};\n\nexport type CredentialSourceV1 =\n | { kind: \"deployment\"; mechanism: \"api_key\" | \"azure_ad_bearer\" }\n | { kind: \"connected_subscription\"; provider: \"codex\" }\n | { kind: \"workspace_connection\"; mechanism: \"api_key\" };\n\nexport type BillingAttributionV1 = {\n upstreamPayer: \"deployment\" | \"workspace\" | \"connected_subscription\";\n metering: \"opengeni_credits\" | \"external\";\n};\n\n/**\n * Wire API a provider speaks. The built-in OpenAI/Azure provider always uses\n * \"responses\" (the OpenAI Responses API). Extra registry providers default to\n * \"chat\" (the broadly compatible /v1/chat/completions surface); Fireworks is\n * wired as \"chat\" because its beta Responses endpoint echoes input back and\n * silently no-ops hosted tools (see docs/model-providers.md).\n */\nexport const ModelProviderApi = z.enum([\"responses\", \"chat\"]);\nexport type ModelProviderApi = z.infer<typeof ModelProviderApi>;\n\n/**\n * Registry provider kind. \"api-key\" providers carry their own static key/headers;\n * \"codex-subscription\" providers authenticate per-request with a ChatGPT/Codex\n * subscription token resolved at call time (no static key) — see @opengeni/codex.\n */\nexport const RegistryProviderKind = z.enum([\"api-key\", \"codex-subscription\"]);\nexport type RegistryProviderKind = z.infer<typeof RegistryProviderKind>;\n\n/** A single model exposed by a registry provider. */\nconst RegistryModelSchema = z\n .object({\n id: z.string().min(1), // canonical OpenGeni product id\n upstreamModelId: z.string().min(1).optional(), // exact provider slug; defaults to id\n aliases: z.array(z.string().min(1)).optional(), // accepted input only; never sent upstream\n label: z.string().min(1).optional(), // display name; defaults to id\n contextWindowTokens: z.number().int().positive().optional(),\n effectiveContextWindowTokens: z.number().int().positive().optional(),\n autoCompactTokenLimit: z.number().int().positive().optional(),\n // Canonical model-facing function/tool-result policy. The runtime applies\n // the same 1.2x serialization allowance as Codex when materializing output.\n toolOutputTruncationTokens: z.number().int().positive().optional(),\n reasoningEffort: z.boolean().optional(), // legacy compatibility input/projection\n hostedWebSearch: z.boolean().optional(), // legacy compatibility input/projection\n capabilities: ModelCapabilitiesV1Schema.optional(),\n pricing: z.union([ModelPricingSchema, ModelPricingScheduleSchema]).optional(),\n // Reserved normalized contracts are derived by OpenGeni in V1. Generic\n // registry JSON must not opt itself into workspace BYOK or reattribute cost.\n credentialSource: z.never().optional(),\n billing: z.never().optional(),\n })\n .superRefine((model, ctx) => {\n if (\n model.capabilities &&\n model.reasoningEffort !== undefined &&\n model.reasoningEffort !== model.capabilities.reasoning.runnable\n ) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"reasoningEffort\"],\n message: \"legacy reasoningEffort must agree with capabilities.reasoning.runnable\",\n });\n }\n if (\n model.capabilities &&\n model.hostedWebSearch !== undefined &&\n model.hostedWebSearch !== model.capabilities.hostedTools.webSearch.runnable\n ) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"hostedWebSearch\"],\n message:\n \"legacy hostedWebSearch must agree with capabilities.hostedTools.webSearch.runnable\",\n });\n }\n });\n\n/** A non-built-in provider declared by the host via OPENGENI_MODEL_PROVIDERS_JSON. */\nconst RegistryProviderSchema = z.object({\n kind: RegistryProviderKind.default(\"api-key\"), // \"codex-subscription\" => per-request token, no static key\n id: z.string().min(1).regex(registryId), // stable provider id, e.g. \"fireworks\"\n label: z.string().min(1).optional(),\n api: ModelProviderApi.default(\"chat\"),\n baseUrl: z.string().url(),\n apiKey: z.string().optional(), // inline key (pragmatic) ...\n apiKeyEnv: z.string().optional(), // ... OR name of the env var holding the key (preferred)\n defaultQuery: z.record(z.string(), z.string()).optional(),\n defaultHeaders: z.record(z.string(), z.string()).optional(),\n publicDefaultQueryNames: z.array(z.string().min(1)).optional(),\n publicDefaultHeaderNames: z.array(z.string().min(1)).optional(),\n // V1 derives these from provider kind. Workspace BYOK is deliberately not a\n // registry switch and requires a separately reviewed encrypted broker.\n credentialSource: z.never().optional(),\n billing: z.never().optional(),\n models: z.array(RegistryModelSchema).min(1),\n});\nexport type RegistryProvider = z.infer<typeof RegistryProviderSchema>;\n\nexport const IntegrationOAuthClientConfigSchema = z.object({\n clientId: z.string().min(1),\n clientSecret: z.string().min(1).optional(),\n tokenEndpointAuthMethod: z\n .enum([\"none\", \"client_secret_post\", \"client_secret_basic\"])\n .default(\"none\"),\n});\nexport type IntegrationOAuthClientConfig = z.infer<typeof IntegrationOAuthClientConfigSchema>;\n\n/**\n * Runtime-resolved provider (built-in or registry), client-construction-ready.\n * The built-in OpenAI/Azure provider is always present and always \"responses\";\n * registry providers carry their own base URL / key / wire API. Compaction is\n * not a provider capability: all providers use the same durable plaintext\n * replacement.\n */\nexport interface ResolvedModelProvider {\n id: string; // \"openai\" | \"azure\" | registry id\n label: string;\n kind: RegistryProviderKind; // \"api-key\" (built-ins + most registry) | \"codex-subscription\"\n api: ModelProviderApi;\n builtin: boolean;\n baseUrl?: string | undefined;\n apiKey?: string | undefined;\n defaultQuery?: Record<string, string> | undefined;\n defaultHeaders?: Record<string, string> | undefined;\n publicDefaultQueryNames?: string[] | undefined;\n publicDefaultHeaderNames?: string[] | undefined;\n credentialSource: CredentialSourceV1;\n billing: BillingAttributionV1;\n}\n\n/** A single exposed model + the provider that serves it. */\nexport interface ConfiguredModel {\n schemaVersion: 1;\n id: string;\n aliases: string[];\n label: string;\n providerId: string;\n providerLabel: string;\n api: ModelProviderApi;\n upstreamModelId: string;\n deployment: ModelDeploymentV1;\n executionLimits: ModelExecutionLimitsV1;\n credentialSource: CredentialSourceV1;\n billing: BillingAttributionV1;\n capabilities: ModelCapabilitiesV1;\n pricing?: ModelPricingScheduleV1 | undefined;\n definitionVersion: string;\n contextWindowTokens?: number | undefined;\n effectiveContextWindowTokens?: number | undefined;\n autoCompactTokenLimit?: number | undefined;\n toolOutputTruncationTokens?: number | undefined;\n reasoningEffort: boolean;\n hostedWebSearch: boolean;\n}\n\nexport const defaultModelPricing: Record<string, ModelPricing> = {\n \"gpt-5.6-sol\": {\n inputMicrosPerMillionTokens: 5_000_000,\n cachedInputMicrosPerMillionTokens: 500_000,\n outputMicrosPerMillionTokens: 30_000_000,\n marginBps: 2_500,\n },\n \"gpt-5.6-terra\": {\n inputMicrosPerMillionTokens: 2_500_000,\n cachedInputMicrosPerMillionTokens: 250_000,\n outputMicrosPerMillionTokens: 15_000_000,\n marginBps: 2_500,\n },\n \"gpt-5.6-luna\": {\n inputMicrosPerMillionTokens: 1_000_000,\n cachedInputMicrosPerMillionTokens: 100_000,\n outputMicrosPerMillionTokens: 6_000_000,\n marginBps: 2_500,\n },\n \"gpt-5.4\": {\n inputMicrosPerMillionTokens: 2_500_000,\n cachedInputMicrosPerMillionTokens: 250_000,\n outputMicrosPerMillionTokens: 15_000_000,\n marginBps: 2_500,\n },\n \"gpt-5.4-mini\": {\n inputMicrosPerMillionTokens: 750_000,\n cachedInputMicrosPerMillionTokens: 75_000,\n outputMicrosPerMillionTokens: 4_500_000,\n marginBps: 2_500,\n },\n \"gpt-5.2\": {\n inputMicrosPerMillionTokens: 1_750_000,\n cachedInputMicrosPerMillionTokens: 175_000,\n outputMicrosPerMillionTokens: 14_000_000,\n marginBps: 2_500,\n },\n \"gpt-5.2-chat-latest\": {\n inputMicrosPerMillionTokens: 1_750_000,\n cachedInputMicrosPerMillionTokens: 175_000,\n outputMicrosPerMillionTokens: 14_000_000,\n marginBps: 2_500,\n },\n \"gpt-5.2-codex\": {\n inputMicrosPerMillionTokens: 1_750_000,\n cachedInputMicrosPerMillionTokens: 175_000,\n outputMicrosPerMillionTokens: 14_000_000,\n marginBps: 2_500,\n },\n \"gpt-5.1\": {\n inputMicrosPerMillionTokens: 1_250_000,\n cachedInputMicrosPerMillionTokens: 125_000,\n outputMicrosPerMillionTokens: 10_000_000,\n marginBps: 2_500,\n },\n \"gpt-5\": {\n inputMicrosPerMillionTokens: 1_250_000,\n cachedInputMicrosPerMillionTokens: 125_000,\n outputMicrosPerMillionTokens: 10_000_000,\n marginBps: 2_500,\n },\n \"gpt-5-mini\": {\n inputMicrosPerMillionTokens: 250_000,\n cachedInputMicrosPerMillionTokens: 25_000,\n outputMicrosPerMillionTokens: 2_000_000,\n marginBps: 2_500,\n },\n \"gpt-5-nano\": {\n inputMicrosPerMillionTokens: 50_000,\n cachedInputMicrosPerMillionTokens: 5_000,\n outputMicrosPerMillionTokens: 400_000,\n marginBps: 2_500,\n },\n // Fireworks AI / GLM 5.2 — the first shipped non-OpenAI registry model. A\n // built-in default pricing entry makes managed billing work out of the box\n // for hosts that expose this model via OPENGENI_MODEL_PROVIDERS_JSON without\n // also setting OPENGENI_MODEL_PRICING_JSON.\n \"accounts/fireworks/models/glm-5p2\": {\n inputMicrosPerMillionTokens: 1_400_000,\n cachedInputMicrosPerMillionTokens: 260_000,\n outputMicrosPerMillionTokens: 4_400_000,\n marginBps: 2_500,\n },\n};\n\n// --- backend-gated required-credential table (the single source of truth) ---\n// Each sandbox backend declares ONLY its own required credentials: a deployment\n// configured for `sandboxBackend=modal` must carry the Modal token, but a\n// daytona/e2b/local/none deployment must NOT be forced to set Modal creds (and\n// vice versa). validateSettings() iterates this table for the *active* backend\n// only — so the cred a backend doesn't use is never a boot blocker — and the\n// deployment package mirrors the same table to drive its env-render + the\n// required-env manifest (one table, two consumers).\n//\n// `field` is the parsed Settings key (boot validation reads the typed value);\n// `env` is the OPENGENI_* variable name (deployment renders/requires it). The\n// modal token is a both-or-neither pair handled by an extra refine in\n// validateSettings — this table holds the hard \"must be present when active\"\n// requirements.\nexport type SandboxRequiredEnv = {\n field: keyof Settings;\n env: string;\n};\n\nexport const SANDBOX_REQUIRED_ENV: Record<\n z.infer<typeof SandboxBackend>,\n readonly SandboxRequiredEnv[]\n> = {\n // docker/local/none need no credentials (local dev container / in-process / off).\n docker: [],\n local: [],\n none: [],\n modal: [\n { field: \"modalAppName\", env: \"OPENGENI_MODAL_APP_NAME\" },\n { field: \"modalTokenId\", env: \"OPENGENI_MODAL_TOKEN_ID\" },\n { field: \"modalTokenSecret\", env: \"OPENGENI_MODAL_TOKEN_SECRET\" },\n ],\n daytona: [{ field: \"daytonaApiKey\", env: \"OPENGENI_DAYTONA_API_KEY\" }],\n runloop: [{ field: \"runloopApiKey\", env: \"OPENGENI_RUNLOOP_API_KEY\" }],\n e2b: [{ field: \"e2bApiKey\", env: \"OPENGENI_E2B_API_KEY\" }],\n blaxel: [{ field: \"blaxelApiKey\", env: \"OPENGENI_BLAXEL_API_KEY\" }],\n cloudflare: [{ field: \"cloudflareWorkerUrl\", env: \"OPENGENI_CLOUDFLARE_WORKER_URL\" }],\n vercel: [\n { field: \"vercelToken\", env: \"OPENGENI_VERCEL_TOKEN\" },\n { field: \"vercelProjectId\", env: \"OPENGENI_VERCEL_PROJECT_ID\" },\n ],\n // selfhosted needs NO per-box credentials: it is the user's own machine reached\n // over the agent's own enrollment. The enrollment-signing + relay-token secrets\n // are deployment-level (a single runtime secret, not per-active-backend creds),\n // wired in the connectivity/enrollment milestones (M4/M5), not here.\n selfhosted: [],\n};\n\n/** The required OPENGENI_* env var names for a backend (for the deployment manifest). */\nexport function requiredSandboxEnvForBackend(backend: z.infer<typeof SandboxBackend>): string[] {\n return (SANDBOX_REQUIRED_ENV[backend] ?? []).map((entry) => entry.env);\n}\n\nfunction optional(name: string): string | undefined {\n const value = process.env[name];\n return value && value.trim().length > 0 ? value : undefined;\n}\n\nexport function getSettings(): Settings {\n const raw = {\n serviceName: optional(\"OPENGENI_SERVICE_NAME\"),\n environment: optional(\"OPENGENI_ENVIRONMENT\"),\n deploymentRevision:\n optional(\"OPENGENI_DEPLOYMENT_REVISION\") ??\n optional(\"SOURCE_VERSION\") ??\n optional(\"GITHUB_SHA\"),\n serverVersion: optional(\"OPENGENI_SERVER_VERSION\"),\n databaseUrl: optional(\"OPENGENI_DATABASE_URL\"),\n dbSchema: optional(\"OPENGENI_DB_SCHEMA\"),\n rlsStrategy: optional(\"OPENGENI_RLS_STRATEGY\"),\n natsUrl: optional(\"OPENGENI_NATS_URL\"),\n temporalHost: optional(\"OPENGENI_TEMPORAL_HOST\"),\n temporalNamespace: optional(\"OPENGENI_TEMPORAL_NAMESPACE\"),\n temporalTaskQueue: optional(\"OPENGENI_TEMPORAL_TASK_QUEUE\"),\n temporalTlsEnabled: optional(\"OPENGENI_TEMPORAL_TLS_ENABLED\"),\n temporalApiKey: optional(\"OPENGENI_TEMPORAL_API_KEY\"),\n temporalTlsServerName: optional(\"OPENGENI_TEMPORAL_TLS_SERVER_NAME\"),\n temporalTlsRootCaCertificateBase64: optional(\n \"OPENGENI_TEMPORAL_TLS_ROOT_CA_CERTIFICATE_BASE64\",\n ),\n temporalTlsClientCertificateBase64: optional(\"OPENGENI_TEMPORAL_TLS_CLIENT_CERTIFICATE_BASE64\"),\n temporalTlsClientPrivateKeyBase64: optional(\"OPENGENI_TEMPORAL_TLS_CLIENT_PRIVATE_KEY_BASE64\"),\n startupDependencyRetryAttempts: optional(\"OPENGENI_STARTUP_DEPENDENCY_RETRY_ATTEMPTS\"),\n startupDependencyRetryInitialDelayMs: optional(\n \"OPENGENI_STARTUP_DEPENDENCY_RETRY_INITIAL_DELAY_MS\",\n ),\n startupDependencyRetryMaxDelayMs: optional(\"OPENGENI_STARTUP_DEPENDENCY_RETRY_MAX_DELAY_MS\"),\n observabilityStructuredLogs: optional(\"OPENGENI_OBSERVABILITY_STRUCTURED_LOGS\"),\n observabilityMetricsEnabled: optional(\"OPENGENI_OBSERVABILITY_METRICS_ENABLED\"),\n observabilityOtlpEndpoint:\n optional(\"OPENGENI_OTEL_EXPORTER_OTLP_ENDPOINT\") ?? optional(\"OTEL_EXPORTER_OTLP_ENDPOINT\"),\n observabilityOtlpHeaders:\n optional(\"OPENGENI_OTEL_EXPORTER_OTLP_HEADERS\") ?? optional(\"OTEL_EXPORTER_OTLP_HEADERS\"),\n publicBaseUrl: optional(\"OPENGENI_PUBLIC_BASE_URL\"),\n agentReleasesBaseUrl: optional(\"OPENGENI_AGENT_RELEASES_BASE_URL\"),\n agentStableVersion: optional(\"OPENGENI_AGENT_STABLE_VERSION\"),\n productAccessMode: optional(\"OPENGENI_PRODUCT_ACCESS_MODE\"),\n billingMode: optional(\"OPENGENI_BILLING_MODE\"),\n entitlementsMode: optional(\"OPENGENI_ENTITLEMENTS_MODE\"),\n usageLimitsMode: optional(\"OPENGENI_USAGE_LIMITS_MODE\"),\n staticEntitlementsJson: optional(\"OPENGENI_STATIC_ENTITLEMENTS_JSON\"),\n staticUsageLimitsJson: optional(\"OPENGENI_STATIC_USAGE_LIMITS_JSON\"),\n delegationSecret: optional(\"OPENGENI_DELEGATION_SECRET\"),\n streamTokenSecret: optional(\"OPENGENI_STREAM_TOKEN_SECRET\"),\n streamControlEnabled: optional(\"OPENGENI_STREAM_CONTROL_ENABLED\"),\n sessionTurnToolReplacementEnabled: optional(\"OPENGENI_SESSION_TURN_TOOL_REPLACEMENT_ENABLED\"),\n toolspaceEnabled: optional(\"OPENGENI_TOOLSPACE_ENABLED\"),\n toolspaceMaxCallsPerTurn: optional(\"OPENGENI_TOOLSPACE_MAX_CALLS_PER_TURN\"),\n ogtoolPackageSpec: optional(\"OPENGENI_OGTOOL_PACKAGE_SPEC\"),\n environmentsEncryptionKey: optional(\"OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY\"),\n integrationsEnabled: optional(\"OPENGENI_INTEGRATIONS_ENABLED\"),\n integrationsStateSecret: optional(\"OPENGENI_INTEGRATIONS_STATE_SECRET\"),\n integrationsAllowPrivateNetworkTargets: optional(\n \"OPENGENI_INTEGRATIONS_ALLOW_PRIVATE_NETWORK_TARGETS\",\n ),\n integrationsOauthClientsJson: optional(\"OPENGENI_INTEGRATIONS_OAUTH_CLIENTS_JSON\"),\n maxNestedAgentDepth: optional(\"OPENGENI_MAX_NESTED_AGENT_DEPTH\"),\n goalMaxAutoContinuations: optional(\"OPENGENI_GOAL_MAX_AUTO_CONTINUATIONS\"),\n goalNoProgressLimit: optional(\"OPENGENI_GOAL_NO_PROGRESS_LIMIT\"),\n agentMaxModelCallsPerTurn: optional(\"OPENGENI_AGENT_MAX_MODEL_CALLS_PER_TURN\"),\n contextWindowTokens: optional(\"OPENGENI_CONTEXT_WINDOW_TOKENS\"),\n contextEffectiveWindowTokens: optional(\"OPENGENI_CONTEXT_EFFECTIVE_WINDOW_TOKENS\"),\n contextCompactionThresholdRatio: optional(\"OPENGENI_COMPACTION_THRESHOLD_RATIO\"),\n contextReservedOutputTokens: optional(\"OPENGENI_CONTEXT_RESERVED_OUTPUT_TOKENS\"),\n contextAutoCompactThresholdTokens: optional(\"OPENGENI_CONTEXT_AUTO_COMPACT_THRESHOLD_TOKENS\"),\n modelToolOutputTruncationTokens: optional(\"OPENGENI_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS\"),\n authRequired: optional(\"OPENGENI_AUTH_REQUIRED\"),\n accessKey: optional(\"OPENGENI_ACCESS_KEY\"),\n authAllowHealth: optional(\"OPENGENI_AUTH_ALLOW_HEALTH\"),\n authAllowMetrics: optional(\"OPENGENI_AUTH_ALLOW_METRICS\"),\n apiHost: optional(\"OPENGENI_API_HOST\"),\n apiPort: optional(\"OPENGENI_API_PORT\"),\n workerHttpPort: optional(\"OPENGENI_WORKER_HTTP_PORT\"),\n opengeniMcpUrl: optional(\"OPENGENI_MCP_URL\"),\n corsAllowOriginRegex: optional(\"OPENGENI_CORS_ALLOW_ORIGIN_REGEX\"),\n openaiProvider: optional(\"OPENGENI_OPENAI_PROVIDER\"),\n openaiApiKey: optional(\"OPENGENI_OPENAI_API_KEY\") ?? optional(\"OPENAI_API_KEY\"),\n openaiBaseUrl: optional(\"OPENGENI_OPENAI_BASE_URL\") ?? optional(\"OPENAI_BASE_URL\"),\n openaiModel: optional(\"OPENGENI_OPENAI_MODEL\"),\n openaiAllowedModels: optional(\"OPENGENI_OPENAI_ALLOWED_MODELS\"),\n modelPricingJson: optional(\"OPENGENI_MODEL_PRICING_JSON\"),\n modelProvidersJson: optional(\"OPENGENI_MODEL_PROVIDERS_JSON\"),\n codexSubscriptionEnabled: optional(\"OPENGENI_CODEX_SUBSCRIPTION_ENABLED\"),\n codexToolSearchEnabled: optional(\"OPENGENI_CODEX_TOOL_SEARCH_ENABLED\"),\n codexCredentialLeasingEnabled: optional(\"OPENGENI_CODEX_CREDENTIAL_LEASING_ENABLED\"),\n codexFleetPolicyShadowEnabled: optional(\"OPENGENI_CODEX_FLEET_POLICY_SHADOW_ENABLED\"),\n codexProductSku: optional(\"OPENGENI_CODEX_PRODUCT_SKU\"),\n openaiReasoningEffort: optional(\"OPENGENI_OPENAI_REASONING_EFFORT\"),\n openaiAllowedReasoningEfforts: optional(\"OPENGENI_OPENAI_ALLOWED_REASONING_EFFORTS\"),\n openaiResponsesTransport: optional(\"OPENGENI_OPENAI_RESPONSES_TRANSPORT\"),\n openaiProviderItemIds: optional(\"OPENGENI_OPENAI_PROVIDER_ITEM_IDS\"),\n openaiReasoningEncryptedContent: optional(\"OPENGENI_OPENAI_REASONING_ENCRYPTED_CONTENT\"),\n openaiMaxRetries: optional(\"OPENGENI_OPENAI_MAX_RETRIES\"),\n webSearchEnabled: optional(\"OPENGENI_WEB_SEARCH_ENABLED\"),\n agentInstructionsTemplate: optional(\"OPENGENI_AGENT_INSTRUCTIONS_TEMPLATE\"),\n azureOpenaiBaseUrl: optional(\"OPENGENI_AZURE_OPENAI_BASE_URL\"),\n azureOpenaiEndpoint: optional(\"OPENGENI_AZURE_OPENAI_ENDPOINT\"),\n azureOpenaiDeployment: optional(\"OPENGENI_AZURE_OPENAI_DEPLOYMENT\"),\n azureOpenaiApiVersion: optional(\"OPENGENI_AZURE_OPENAI_API_VERSION\"),\n azureOpenaiApiKey: optional(\"OPENGENI_AZURE_OPENAI_API_KEY\"),\n azureOpenaiAdToken: optional(\"OPENGENI_AZURE_OPENAI_AD_TOKEN\"),\n disableOpenaiTracing: optional(\"OPENGENI_DISABLE_OPENAI_TRACING\"),\n sandboxBackend: optional(\"OPENGENI_SANDBOX_BACKEND\"),\n dockerImage: optional(\"OPENGENI_DOCKER_IMAGE\"),\n dockerExposedPorts: optional(\"OPENGENI_DOCKER_EXPOSED_PORTS\"),\n dockerNetwork: optional(\"OPENGENI_DOCKER_NETWORK\"),\n modalAppName: optional(\"OPENGENI_MODAL_APP_NAME\"),\n modalImageRef: optional(\"OPENGENI_MODAL_IMAGE_REF\"),\n modalImageRegistrySecret: optional(\"OPENGENI_MODAL_IMAGE_REGISTRY_SECRET\"),\n modalTimeoutSeconds: optional(\"OPENGENI_MODAL_TIMEOUT_SECONDS\"),\n modalTokenId: optional(\"OPENGENI_MODAL_TOKEN_ID\"),\n modalTokenSecret: optional(\"OPENGENI_MODAL_TOKEN_SECRET\"),\n modalEnvironment: optional(\"OPENGENI_MODAL_ENVIRONMENT\"),\n modalIdleTimeoutSeconds: optional(\"OPENGENI_MODAL_IDLE_TIMEOUT_SECONDS\"),\n modalWorkspacePersistence: optional(\"OPENGENI_MODAL_WORKSPACE_PERSISTENCE\"),\n modalSnapshotRetentionSeconds: optional(\"OPENGENI_MODAL_SNAPSHOT_RETENTION_SECONDS\"),\n sandboxDesktopEnabled: optional(\"OPENGENI_SANDBOX_DESKTOP_ENABLED\"),\n sandboxDesktopInteractive: optional(\"OPENGENI_SANDBOX_DESKTOP_INTERACTIVE\"),\n sandboxTerminalEnabled: optional(\"OPENGENI_SANDBOX_TERMINAL_ENABLED\"),\n streamResolutionWidth: optional(\"OPENGENI_STREAM_RESOLUTION_WIDTH\"),\n streamResolutionHeight: optional(\"OPENGENI_STREAM_RESOLUTION_HEIGHT\"),\n computerUseEnabled: optional(\"OPENGENI_COMPUTER_USE_ENABLED\"),\n computerUseReadOnly: optional(\"OPENGENI_COMPUTER_USE_READONLY\"),\n recordingEnabled: optional(\"OPENGENI_RECORDING_ENABLED\"),\n workspaceCaptureEnabled: optional(\"OPENGENI_WORKSPACE_CAPTURE\"),\n recordingDefaultCodec: optional(\"OPENGENI_RECORDING_DEFAULT_CODEC\"),\n recordingFramerate: optional(\"OPENGENI_RECORDING_FRAMERATE\"),\n recordingMaxSeconds: optional(\"OPENGENI_RECORDING_MAX_SECONDS\"),\n recordingMaxBytes: optional(\"OPENGENI_RECORDING_MAX_BYTES\"),\n daytonaApiKey: optional(\"OPENGENI_DAYTONA_API_KEY\"),\n daytonaApiUrl: optional(\"OPENGENI_DAYTONA_API_URL\"),\n daytonaTarget: optional(\"OPENGENI_DAYTONA_TARGET\"),\n daytonaImage: optional(\"OPENGENI_DAYTONA_IMAGE\"),\n daytonaSnapshotName: optional(\"OPENGENI_DAYTONA_SNAPSHOT_NAME\"),\n daytonaAutoStopInterval: optional(\"OPENGENI_DAYTONA_AUTO_STOP_INTERVAL\"),\n daytonaTimeoutSeconds: optional(\"OPENGENI_DAYTONA_TIMEOUT_SECONDS\"),\n daytonaExposedPortUrlTtlSeconds: optional(\"OPENGENI_DAYTONA_EXPOSED_PORT_URL_TTL_SECONDS\"),\n runloopApiKey: optional(\"OPENGENI_RUNLOOP_API_KEY\"),\n runloopBaseUrl: optional(\"OPENGENI_RUNLOOP_BASE_URL\"),\n runloopBlueprintName: optional(\"OPENGENI_RUNLOOP_BLUEPRINT_NAME\"),\n runloopBlueprintId: optional(\"OPENGENI_RUNLOOP_BLUEPRINT_ID\"),\n runloopTunnel: optional(\"OPENGENI_RUNLOOP_TUNNEL\"),\n runloopKeepAliveSeconds: optional(\"OPENGENI_RUNLOOP_KEEP_ALIVE_SECONDS\"),\n e2bApiKey: optional(\"OPENGENI_E2B_API_KEY\"),\n e2bTemplate: optional(\"OPENGENI_E2B_TEMPLATE\"),\n e2bTimeoutSeconds: optional(\"OPENGENI_E2B_TIMEOUT_SECONDS\"),\n e2bTimeoutAction: optional(\"OPENGENI_E2B_TIMEOUT_ACTION\"),\n e2bAllowInternetAccess: optional(\"OPENGENI_E2B_ALLOW_INTERNET_ACCESS\"),\n e2bAutoResume: optional(\"OPENGENI_E2B_AUTO_RESUME\"),\n e2bWorkspacePersistence: optional(\"OPENGENI_E2B_WORKSPACE_PERSISTENCE\"),\n blaxelApiKey: optional(\"OPENGENI_BLAXEL_API_KEY\"),\n blaxelImage: optional(\"OPENGENI_BLAXEL_IMAGE\"),\n blaxelRegion: optional(\"OPENGENI_BLAXEL_REGION\"),\n blaxelExposedPortPublic: optional(\"OPENGENI_BLAXEL_EXPOSED_PORT_PUBLIC\"),\n blaxelExposedPortUrlTtlSeconds: optional(\"OPENGENI_BLAXEL_EXPOSED_PORT_URL_TTL_SECONDS\"),\n blaxelMemoryMb: optional(\"OPENGENI_BLAXEL_MEMORY_MB\"),\n blaxelTtl: optional(\"OPENGENI_BLAXEL_TTL\"),\n cloudflareWorkerUrl: optional(\"OPENGENI_CLOUDFLARE_WORKER_URL\"),\n cloudflareApiKey: optional(\"OPENGENI_CLOUDFLARE_API_KEY\"),\n vercelToken: optional(\"OPENGENI_VERCEL_TOKEN\"),\n vercelProjectId: optional(\"OPENGENI_VERCEL_PROJECT_ID\"),\n vercelTeamId: optional(\"OPENGENI_VERCEL_TEAM_ID\"),\n vercelRuntime: optional(\"OPENGENI_VERCEL_RUNTIME\"),\n sandboxOwnershipEnabled: optional(\"OPENGENI_SANDBOX_OWNERSHIP_ENABLED\"),\n rigVerificationLeaseOwnershipEnabled: optional(\n \"OPENGENI_RIG_VERIFICATION_LEASE_OWNERSHIP_ENABLED\",\n ),\n sandboxLazyProvisionEnabled: optional(\"OPENGENI_SANDBOX_LAZY_PROVISION\"),\n sandboxSelfhostedEnabled: optional(\"OPENGENI_SANDBOX_SELFHOSTED_ENABLED\"),\n agentOpStreamEnabled: optional(\"OPENGENI_AGENT_OP_STREAM_ENABLED\"),\n enrollmentSigningSecret: optional(\"OPENGENI_ENROLLMENT_SIGNING_SECRET\"),\n selfhostedNatsUrl: optional(\"OPENGENI_SELFHOSTED_NATS_URL\"),\n selfhostedRelayUrl: optional(\"OPENGENI_SELFHOSTED_RELAY_URL\"),\n selfhostedRelayTokenSecret: optional(\"OPENGENI_SELFHOSTED_RELAY_TOKEN_SECRET\"),\n agentUpdatePublicKey: optional(\"OPENGENI_AGENT_UPDATE_PUBLIC_KEY\"),\n selfhostedNatsCalloutAccountSeed: optional(\"OPENGENI_SELFHOSTED_NATS_CALLOUT_ACCOUNT_SEED\"),\n selfhostedNatsCalloutAccountName: optional(\"OPENGENI_SELFHOSTED_NATS_CALLOUT_ACCOUNT_NAME\"),\n selfhostedNatsCalloutUser: optional(\"OPENGENI_SELFHOSTED_NATS_CALLOUT_USER\"),\n selfhostedNatsCalloutPassword: optional(\"OPENGENI_SELFHOSTED_NATS_CALLOUT_PASSWORD\"),\n selfhostedNatsControlUser: optional(\"OPENGENI_SELFHOSTED_NATS_CONTROL_USER\"),\n selfhostedNatsControlPassword: optional(\"OPENGENI_SELFHOSTED_NATS_CONTROL_PASSWORD\"),\n sandboxSelfhostedExecTimeoutMs: optional(\"OPENGENI_SANDBOX_SELFHOSTED_EXEC_TIMEOUT_MS\"),\n sandboxSelfhostedControlTimeoutMs: optional(\"OPENGENI_SANDBOX_SELFHOSTED_CONTROL_TIMEOUT_MS\"),\n sandboxLeaseReaperPeriodMs: optional(\"OPENGENI_SANDBOX_LEASE_REAPER_PERIOD_MS\"),\n sandboxViewerHolderTtlMs: optional(\"OPENGENI_SANDBOX_VIEWER_HOLDER_TTL_MS\"),\n sandboxIdleGraceMs: optional(\"OPENGENI_SANDBOX_IDLE_GRACE_MS\"),\n sandboxSnapshotIntervalMs: optional(\"OPENGENI_SANDBOX_SNAPSHOT_INTERVAL_MS\"),\n sandboxSnapshotTimeoutMs: optional(\"OPENGENI_SANDBOX_SNAPSHOT_TIMEOUT_MS\"),\n sandboxLeaseTtlMs: optional(\"OPENGENI_SANDBOX_LEASE_TTL_MS\"),\n sandboxLeaseWarmingTtlMs: optional(\"OPENGENI_SANDBOX_LEASE_WARMING_TTL_MS\"),\n sandboxWarmingTimeoutMs: optional(\"OPENGENI_SANDBOX_WARMING_TIMEOUT_MS\"),\n rigSetupTimeoutMs: optional(\"OPENGENI_RIG_SETUP_TIMEOUT_MS\"),\n sandboxWarmRateMicrosPerSecondJson: optional(\n \"OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON\",\n ),\n sandboxMaxWarmSecondsPerWorkspace: optional(\"OPENGENI_SANDBOX_MAX_WARM_SECONDS_PER_WORKSPACE\"),\n sandboxPreparationProfiles: optional(\"OPENGENI_SANDBOX_PREPARATION_PROFILES\"),\n sandboxEnvAllowlist: optional(\"OPENGENI_SANDBOX_ENV_ALLOWLIST\"),\n objectStorageEndpoint: optional(\"OPENGENI_OBJECT_STORAGE_ENDPOINT\"),\n objectStorageSandboxEndpoint: optional(\"OPENGENI_OBJECT_STORAGE_SANDBOX_ENDPOINT\"),\n objectStorageBackend: optional(\"OPENGENI_OBJECT_STORAGE_BACKEND\"),\n objectStorageBucket: optional(\"OPENGENI_OBJECT_STORAGE_BUCKET\"),\n objectStorageRegion: optional(\"OPENGENI_OBJECT_STORAGE_REGION\"),\n objectStorageS3Provider: optional(\"OPENGENI_OBJECT_STORAGE_S3_PROVIDER\"),\n objectStorageAccessKeyId: optional(\"OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID\"),\n objectStorageSecretAccessKey: optional(\"OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY\"),\n objectStorageForcePathStyle: optional(\"OPENGENI_OBJECT_STORAGE_FORCE_PATH_STYLE\"),\n objectStorageAzureConnectionString: optional(\"OPENGENI_OBJECT_STORAGE_AZURE_CONNECTION_STRING\"),\n objectStorageAzureAccountName: optional(\"OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_NAME\"),\n objectStorageAzureAccountKey: optional(\"OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_KEY\"),\n objectStorageAzureEndpoint: optional(\"OPENGENI_OBJECT_STORAGE_AZURE_ENDPOINT\"),\n objectStorageGcsProjectId: optional(\"OPENGENI_OBJECT_STORAGE_GCS_PROJECT_ID\"),\n objectStorageGcsCredentialsJson: optional(\"OPENGENI_OBJECT_STORAGE_GCS_CREDENTIALS_JSON\"),\n objectStorageGcsKeyFilename: optional(\"OPENGENI_OBJECT_STORAGE_GCS_KEY_FILENAME\"),\n objectStorageGcsApiEndpoint: optional(\"OPENGENI_OBJECT_STORAGE_GCS_API_ENDPOINT\"),\n documentParser: optional(\"OPENGENI_DOCUMENT_PARSER\"),\n documentChunkSize: optional(\"OPENGENI_DOCUMENT_CHUNK_SIZE\"),\n documentChunkOverlap: optional(\"OPENGENI_DOCUMENT_CHUNK_OVERLAP\"),\n documentEmbeddingProvider: optional(\"OPENGENI_DOCUMENT_EMBEDDING_PROVIDER\"),\n documentEmbeddingModel: optional(\"OPENGENI_DOCUMENT_EMBEDDING_MODEL\"),\n documentEmbeddingDimensions: optional(\"OPENGENI_DOCUMENT_EMBEDDING_DIMENSIONS\"),\n documentEmbeddingApiKey: optional(\"OPENGENI_DOCUMENT_EMBEDDING_API_KEY\"),\n documentEmbeddingBaseUrl: optional(\"OPENGENI_DOCUMENT_EMBEDDING_BASE_URL\"),\n gitAuthorName: optional(\"OPENGENI_GIT_AUTHOR_NAME\"),\n gitAuthorEmail: optional(\"OPENGENI_GIT_AUTHOR_EMAIL\"),\n gitCommitterName: optional(\"OPENGENI_GIT_COMMITTER_NAME\"),\n gitCommitterEmail: optional(\"OPENGENI_GIT_COMMITTER_EMAIL\"),\n githubAppManifestBaseUrl: optional(\"OPENGENI_GITHUB_APP_MANIFEST_BASE_URL\"),\n githubAppManifestStateSecret: optional(\"OPENGENI_GITHUB_APP_MANIFEST_STATE_SECRET\"),\n githubAppId: optional(\"OPENGENI_GITHUB_APP_ID\"),\n githubClientId: optional(\"OPENGENI_GITHUB_CLIENT_ID\"),\n githubClientSecret: optional(\"OPENGENI_GITHUB_CLIENT_SECRET\"),\n githubAppSlug: optional(\"OPENGENI_GITHUB_APP_SLUG\"),\n githubWebhookSecret: optional(\"OPENGENI_GITHUB_WEBHOOK_SECRET\"),\n githubAppPrivateKey: optional(\"OPENGENI_GITHUB_APP_PRIVATE_KEY\"),\n betterAuthSecret: optional(\"OPENGENI_BETTER_AUTH_SECRET\"),\n betterAuthAllowedHosts: optional(\"OPENGENI_BETTER_AUTH_ALLOWED_HOSTS\"),\n betterAuthCookieDomain: optional(\"OPENGENI_BETTER_AUTH_COOKIE_DOMAIN\"),\n betterAuthTrustedOrigins: optional(\"OPENGENI_BETTER_AUTH_TRUSTED_ORIGINS\"),\n resendApiKey: optional(\"OPENGENI_RESEND_API_KEY\"),\n emailFrom: optional(\"OPENGENI_EMAIL_FROM\"),\n stripeSecretKey: optional(\"OPENGENI_STRIPE_SECRET_KEY\"),\n stripePublishableKey: optional(\"OPENGENI_STRIPE_PUBLISHABLE_KEY\"),\n stripeWebhookSecret: optional(\"OPENGENI_STRIPE_WEBHOOK_SECRET\"),\n stripeCreditsProductId: optional(\"OPENGENI_STRIPE_CREDITS_PRODUCT_ID\"),\n mcpServers: parseMcpServers(optional(\"OPENGENI_MCP_SERVERS\")),\n };\n const parsed = SettingsSchema.parse(raw);\n const settings = {\n ...parsed,\n mcpServers: ensureBuiltInMcpServers(parsed),\n };\n validateSettings(settings);\n return settings;\n}\n\n/**\n * The Modal sandbox idle timeout (seconds) the provider actually passes as\n * idleTimeoutMs (sandbox-file-persistence). When the operator did not pin\n * OPENGENI_MODAL_IDLE_TIMEOUT_SECONDS we DEFAULT it to the hard lifetime\n * (modalTimeoutSeconds): OpenGeni's reaper owns box lifecycle, so Modal's\n * built-in idle-reap (which would otherwise fire on its short server default and\n * kill the box BEFORE the reaper can snapshot /workspace) is pushed out to the\n * hard backstop. An explicit smaller value is honoured (the boot invariant keeps\n * it above reaperPeriod + idleGrace so a drained box still survives long enough\n * to be persisted).\n */\nexport function effectiveModalIdleTimeoutSeconds(settings: Settings): number {\n return settings.modalIdleTimeoutSeconds ?? settings.modalTimeoutSeconds;\n}\n\nexport function collectSandboxEnvironment(\n settings: Settings,\n source: NodeJS.ProcessEnv = process.env,\n): Record<string, string> {\n const out: Record<string, string> = {};\n for (const name of sandboxEnvironmentVariableNames(settings)) {\n const value = source[name];\n if (value) {\n out[name] = value;\n }\n }\n return out;\n}\n\n/**\n * Resolved API key for a registry provider: the inline `apiKey` when present,\n * else the value of the env var named by `apiKeyEnv`. The preferred form is\n * `apiKeyEnv` (the secret stays out of OPENGENI_MODEL_PROVIDERS_JSON). Reads\n * from `source` (defaults to process.env) so callers can resolve against an\n * explicit environment in tests.\n */\nexport function resolveProviderApiKey(\n provider: Pick<RegistryProvider, \"apiKey\" | \"apiKeyEnv\">,\n source: NodeJS.ProcessEnv = process.env,\n): string | undefined {\n if (provider.apiKey) {\n return provider.apiKey;\n }\n if (provider.apiKeyEnv) {\n const value = source[provider.apiKeyEnv];\n return value && value.trim().length > 0 ? value : undefined;\n }\n return undefined;\n}\n\nconst HTTP_FIELD_NAME = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\nconst CREDENTIAL_LIKE_NAME_PARTS = new Set([\n \"apikey\",\n \"auth\",\n \"authorization\",\n \"bearer\",\n \"credential\",\n \"cookie\",\n \"key\",\n \"password\",\n \"secret\",\n \"session\",\n \"signature\",\n \"token\",\n]);\nconst REASONING_EFFORT_ORDER = new Map(\n ReasoningEffort.options.map((effort, index) => [effort, index]),\n);\nconst MODALITY_ORDER = new Map([\"text\", \"image\", \"audio\"].map((value, index) => [value, index]));\nconst LATENCY_MODE_ORDER = new Map(\n [\"standard\", \"priority\", \"fast\"].map((value, index) => [value, index]),\n);\n\nfunction normalizeRegistryBaseUrl(value: string, providerId: string): string {\n const url = new URL(value);\n if (url.username || url.password) {\n throw new Error(`provider ${providerId} baseUrl must not contain userinfo`);\n }\n if (url.search) {\n throw new Error(\n `provider ${providerId} baseUrl must not contain a query; move query entries to defaultQuery`,\n );\n }\n if (url.hash) {\n throw new Error(`provider ${providerId} baseUrl must not contain a fragment`);\n }\n return url.toString();\n}\n\nfunction isCredentialLikeMetadataName(name: string): boolean {\n return name\n .toLowerCase()\n .split(/[-_.]/u)\n .some((part) => CREDENTIAL_LIKE_NAME_PARTS.has(part));\n}\n\nfunction normalizeHeaderMap(\n providerId: string,\n headers: Record<string, string> | undefined,\n): Record<string, string> | undefined {\n if (!headers) {\n return undefined;\n }\n const normalized: Record<string, string> = {};\n const rawByNormalized = new Map<string, string>();\n for (const [rawName, value] of Object.entries(headers)) {\n if (!HTTP_FIELD_NAME.test(rawName)) {\n throw new Error(\n `provider ${providerId} defaultHeaders contains invalid HTTP field name ${JSON.stringify(rawName)}`,\n );\n }\n const name = rawName.toLowerCase();\n const previous = rawByNormalized.get(name);\n if (previous !== undefined) {\n throw new Error(\n `provider ${providerId} defaultHeaders names ${JSON.stringify(previous)} and ${JSON.stringify(rawName)} collide after lowercase normalization`,\n );\n }\n if (name === \"authorization\") {\n throw new Error(\n `provider ${providerId} defaultHeaders must not override SDK-managed Authorization`,\n );\n }\n rawByNormalized.set(name, rawName);\n normalized[name] = value;\n }\n return normalized;\n}\n\nfunction normalizePublicHeaderNames(\n providerId: string,\n names: string[] | undefined,\n headers: Record<string, string> | undefined,\n): string[] | undefined {\n if (!names) {\n return undefined;\n }\n const normalized: string[] = [];\n const seen = new Set<string>();\n for (const rawName of names) {\n if (!HTTP_FIELD_NAME.test(rawName)) {\n throw new Error(\n `provider ${providerId} publicDefaultHeaderNames contains invalid HTTP field name ${JSON.stringify(rawName)}`,\n );\n }\n const name = rawName.toLowerCase();\n if (seen.has(name)) {\n throw new Error(\n `provider ${providerId} publicDefaultHeaderNames contains duplicate normalized name ${JSON.stringify(name)}`,\n );\n }\n if (!(name in (headers ?? {}))) {\n throw new Error(\n `provider ${providerId} publicDefaultHeaderNames declares absent defaultHeaders entry ${JSON.stringify(name)}`,\n );\n }\n if (isCredentialLikeMetadataName(name)) {\n throw new Error(\n `provider ${providerId} publicDefaultHeaderNames cannot classify credential-like name ${JSON.stringify(name)} as public`,\n );\n }\n seen.add(name);\n normalized.push(name);\n }\n return normalized;\n}\n\nfunction normalizeQueryMap(\n providerId: string,\n query: Record<string, string> | undefined,\n): Record<string, string> | undefined {\n if (!query) {\n return undefined;\n }\n for (const name of Object.keys(query)) {\n if (!name) {\n throw new Error(`provider ${providerId} defaultQuery contains an empty name`);\n }\n }\n return { ...query };\n}\n\nfunction normalizePublicQueryNames(\n providerId: string,\n names: string[] | undefined,\n query: Record<string, string> | undefined,\n): string[] | undefined {\n if (!names) {\n return undefined;\n }\n const seen = new Set<string>();\n for (const name of names) {\n if (seen.has(name)) {\n throw new Error(\n `provider ${providerId} publicDefaultQueryNames contains duplicate name ${JSON.stringify(name)}`,\n );\n }\n if (!(name in (query ?? {}))) {\n throw new Error(\n `provider ${providerId} publicDefaultQueryNames declares absent defaultQuery entry ${JSON.stringify(name)}`,\n );\n }\n if (isCredentialLikeMetadataName(name)) {\n throw new Error(\n `provider ${providerId} publicDefaultQueryNames cannot classify credential-like name ${JSON.stringify(name)} as public`,\n );\n }\n seen.add(name);\n }\n return [...names];\n}\n\nfunction normalizeRegistryProvider(provider: RegistryProvider): RegistryProvider {\n const defaultHeaders = normalizeHeaderMap(provider.id, provider.defaultHeaders);\n const defaultQuery = normalizeQueryMap(provider.id, provider.defaultQuery);\n return {\n ...provider,\n baseUrl: normalizeRegistryBaseUrl(provider.baseUrl, provider.id),\n ...(defaultHeaders === undefined ? {} : { defaultHeaders }),\n ...(defaultQuery === undefined ? {} : { defaultQuery }),\n ...(provider.publicDefaultHeaderNames === undefined\n ? {}\n : {\n publicDefaultHeaderNames: normalizePublicHeaderNames(\n provider.id,\n provider.publicDefaultHeaderNames,\n defaultHeaders,\n ),\n }),\n ...(provider.publicDefaultQueryNames === undefined\n ? {}\n : {\n publicDefaultQueryNames: normalizePublicQueryNames(\n provider.id,\n provider.publicDefaultQueryNames,\n defaultQuery,\n ),\n }),\n };\n}\n\nfunction normalizeModelPricingSchedule(\n pricing: ModelPricing | ModelPricingScheduleV1,\n): ModelPricingScheduleV1 {\n return \"default\" in pricing ? pricing : { default: pricing };\n}\n\nfunction normalizeCapabilities(capabilities: ModelCapabilitiesV1): ModelCapabilitiesV1 {\n const parsed = ModelCapabilitiesV1Schema.parse(capabilities);\n return {\n ...parsed,\n reasoning: {\n ...parsed.reasoning,\n efforts: [...parsed.reasoning.efforts].sort(\n (left, right) =>\n (REASONING_EFFORT_ORDER.get(left) ?? 0) - (REASONING_EFFORT_ORDER.get(right) ?? 0),\n ),\n },\n inputModalities: [...parsed.inputModalities].sort(\n (left, right) => (MODALITY_ORDER.get(left) ?? 0) - (MODALITY_ORDER.get(right) ?? 0),\n ),\n outputModalities: [...parsed.outputModalities].sort(\n (left, right) => (MODALITY_ORDER.get(left) ?? 0) - (MODALITY_ORDER.get(right) ?? 0),\n ),\n latencyModes: [...parsed.latencyModes].sort(\n (left, right) =>\n (LATENCY_MODE_ORDER.get(left.id) ?? 0) - (LATENCY_MODE_ORDER.get(right.id) ?? 0),\n ),\n };\n}\n\nfunction legacyModelCapabilities(\n settings: Settings,\n input: { reasoningEffort: boolean; hostedWebSearch: boolean },\n): ModelCapabilitiesV1 {\n const reasoningEfforts = input.reasoningEffort ? configuredAllowedReasoningEfforts(settings) : [];\n return normalizeCapabilities({\n reasoning: {\n upstream: input.reasoningEffort ? \"supported\" : \"unknown\",\n runnable: input.reasoningEffort,\n efforts: reasoningEfforts,\n defaultEffort: input.reasoningEffort ? settings.openaiReasoningEffort : null,\n required: false,\n },\n functionCalling: { upstream: \"unknown\", runnable: true },\n structuredOutput: { upstream: \"unknown\", runnable: false },\n hostedTools: {\n webSearch: {\n upstream: input.hostedWebSearch ? \"supported\" : \"unknown\",\n runnable: input.hostedWebSearch,\n },\n xSearch: { upstream: \"unknown\", runnable: false },\n codeExecution: { upstream: \"unknown\", runnable: false },\n },\n inputModalities: [\"text\"],\n outputModalities: [\"text\"],\n transports: {\n sse: { upstream: \"unknown\", runnable: true },\n responsesWebSocket: { upstream: \"unknown\", runnable: false },\n realtimeAudio: { upstream: \"unknown\", runnable: false },\n },\n latencyModes: [{ id: \"standard\", upstream: \"unknown\", runnable: true }],\n });\n}\n\nfunction registryCredentialSource(provider: RegistryProvider): CredentialSourceV1 {\n return provider.kind === \"codex-subscription\"\n ? { kind: \"connected_subscription\", provider: \"codex\" }\n : { kind: \"deployment\", mechanism: \"api_key\" };\n}\n\nfunction registryBilling(provider: RegistryProvider): BillingAttributionV1 {\n return provider.kind === \"codex-subscription\"\n ? { upstreamPayer: \"connected_subscription\", metering: \"external\" }\n : { upstreamPayer: \"deployment\", metering: \"opengeni_credits\" };\n}\n\nfunction builtinCredentialSource(settings: Settings): CredentialSourceV1 {\n if (settings.openaiProvider === \"azure\" && !settings.azureOpenaiApiKey) {\n return { kind: \"deployment\", mechanism: \"azure_ad_bearer\" };\n }\n return { kind: \"deployment\", mechanism: \"api_key\" };\n}\n\nfunction staticRequestMetadataForDigest(provider: ResolvedModelProvider): {\n headers: Array<{ name: string; classification: \"public\" | \"secret\"; value?: string }>;\n query: Array<{ name: string; classification: \"public\" | \"secret\"; value?: string }>;\n} {\n const publicHeaders = new Set(provider.publicDefaultHeaderNames ?? []);\n const publicQuery = new Set(provider.publicDefaultQueryNames ?? []);\n return {\n headers: Object.entries(provider.defaultHeaders ?? {})\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([name, value]) =>\n publicHeaders.has(name)\n ? { name, classification: \"public\" as const, value }\n : { name, classification: \"secret\" as const },\n ),\n query: Object.entries(provider.defaultQuery ?? {})\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([name, value]) =>\n publicQuery.has(name)\n ? { name, classification: \"public\" as const, value }\n : { name, classification: \"secret\" as const },\n ),\n };\n}\n\nfunction canonicalJson(value: unknown): string {\n const normalize = (input: unknown): unknown => {\n if (Array.isArray(input)) {\n return input.map((entry) => normalize(entry));\n }\n if (input && typeof input === \"object\") {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(input).sort()) {\n const child = (input as Record<string, unknown>)[key];\n if (child !== undefined) {\n out[key] = normalize(child);\n }\n }\n return out;\n }\n return input;\n };\n return JSON.stringify(normalize(value));\n}\n\nfunction definitionVersionFor(\n model: Omit<ConfiguredModel, \"definitionVersion\">,\n provider: ResolvedModelProvider,\n): string {\n const requestMetadata = staticRequestMetadataForDigest(provider);\n const digestInput = canonicalJson({\n schemaVersion: model.schemaVersion,\n id: model.id,\n providerId: model.providerId,\n deployment: model.deployment,\n provider: {\n adapterKind: provider.kind,\n wireApi: provider.api,\n baseUrl: provider.baseUrl ?? null,\n defaultHeaders: requestMetadata.headers,\n defaultQuery: requestMetadata.query,\n },\n credentialSource: model.credentialSource,\n billing: model.billing,\n executionLimits: model.executionLimits,\n capabilities: model.capabilities,\n pricing: model.pricing ?? null,\n });\n return `sha256:${createHash(\"sha256\")\n .update(\"opengeni:model-definition:v1\\n\", \"utf8\")\n .update(digestInput, \"utf8\")\n .digest(\"hex\")}`;\n}\n\n/**\n * The built-in provider's stable id: \"openai\" on the OpenAI platform, \"azure\"\n * on Azure. Exported because the workspace model-policy gate must attribute\n * the legacy resolveTurnModel-null fallback (which routes to this built-in\n * client) to the SAME identity the router uses — otherwise a policy blocking\n * the built-in could be bypassed through the null-resolution path.\n */\nexport function builtinProviderId(settings: Pick<Settings, \"openaiProvider\">): string {\n return settings.openaiProvider === \"azure\" ? \"azure\" : \"openai\";\n}\n\nfunction builtinProviderLabel(settings: Pick<Settings, \"openaiProvider\">): string {\n return settings.openaiProvider === \"azure\" ? \"Azure OpenAI\" : \"OpenAI\";\n}\n\n/**\n * Every provider a client may route to: the built-in OpenAI/Azure provider\n * first (id \"openai\"/\"azure\", always \"responses\"), then each registry provider\n * in declaration order. Client-construction inputs are filled from\n * the existing flat openai/azure settings for the built-in, and from the\n * registry entry for the rest. Registry ids may not collide with the built-in\n * id — validateSettings rejects that at boot.\n */\nexport function configuredProviders(settings: Settings): ResolvedModelProvider[] {\n const credentialSource = builtinCredentialSource(settings);\n const builtin: ResolvedModelProvider = {\n id: builtinProviderId(settings),\n label: builtinProviderLabel(settings),\n kind: \"api-key\",\n api: \"responses\",\n builtin: true,\n credentialSource,\n billing: { upstreamPayer: \"deployment\", metering: \"opengeni_credits\" },\n };\n if (settings.openaiProvider === \"azure\") {\n const baseUrl = settings.azureOpenaiBaseUrl ?? settings.azureOpenaiEndpoint;\n builtin.baseUrl = baseUrl ? normalizeRegistryBaseUrl(baseUrl, builtin.id) : undefined;\n builtin.apiKey = settings.azureOpenaiApiKey ?? settings.azureOpenaiAdToken;\n } else {\n builtin.baseUrl = settings.openaiBaseUrl\n ? normalizeRegistryBaseUrl(settings.openaiBaseUrl, builtin.id)\n : undefined;\n builtin.apiKey = settings.openaiApiKey;\n }\n const registry = parseModelProvidersJson(settings.modelProvidersJson).map(\n (provider): ResolvedModelProvider => ({\n id: provider.id,\n label: provider.label ?? provider.id,\n kind: provider.kind,\n api: provider.api,\n builtin: false,\n baseUrl: provider.baseUrl,\n apiKey: resolveProviderApiKey(provider),\n defaultQuery: provider.defaultQuery,\n defaultHeaders: provider.defaultHeaders,\n publicDefaultQueryNames: provider.publicDefaultQueryNames,\n publicDefaultHeaderNames: provider.publicDefaultHeaderNames,\n credentialSource: registryCredentialSource(provider),\n billing: registryBilling(provider),\n }),\n );\n return [builtin, ...registry];\n}\n\n/**\n * Pure catalog overlay for a workspace whose existing Codex connection seam\n * reports ready. This describes product/provider identity only; it does not\n * select, lease, refresh, or expose a concrete credential; those runtime\n * operations remain owned by the credential allocator.\n */\nexport function withCodexCatalogProvider(settings: Settings): Settings {\n const providers = parseModelProvidersJson(settings.modelProvidersJson);\n if (providers.some((provider) => provider.id === CODEX_PROVIDER_ID)) {\n return settings;\n }\n const provider: RegistryProvider = {\n kind: \"codex-subscription\",\n id: CODEX_PROVIDER_ID,\n label: \"Codex (ChatGPT subscription)\",\n api: \"responses\",\n baseUrl: CODEX_PROVIDER_BASE_URL,\n models: CODEX_FALLBACK_MODEL_SLUGS.map((slug) => ({\n id: `${CODEX_MODEL_ID_PREFIX}${slug}`,\n upstreamModelId: slug,\n label: slug,\n reasoningEffort: true,\n contextWindowTokens: CODEX_MODEL_CONTEXT_WINDOW_TOKENS,\n effectiveContextWindowTokens: CODEX_MODEL_EFFECTIVE_CONTEXT_WINDOW_TOKENS,\n autoCompactTokenLimit: CODEX_MODEL_AUTO_COMPACT_TOKEN_LIMIT,\n toolOutputTruncationTokens: CODEX_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS,\n })),\n };\n return { ...settings, modelProvidersJson: JSON.stringify([...providers, provider]) };\n}\n\n/**\n * The provider identity a model id resolves to, for workspace model-policy\n * evaluation — MUST agree with the real router (resolveTurnModel /\n * MultiProviderModelProvider) on every case:\n * - `codex/<slug>` → the codex-subscription provider id, ALWAYS. With no\n * active subscription the router fails loud (CodexSubscriptionUnavailableError),\n * never the built-in — so attributing by prefix is exact even against BASE\n * settings where the overlay provider is not injected.\n * - a configured model id → its configuredModels providerId (registry or built-in).\n * - anything else → the built-in id: an unknown id is the legacy\n * resolveTurnModel-null fallback, which the built-in OpenAI/Azure client\n * serves. A policy blocking the built-in must block this path too.\n */\nexport function policyProviderIdForModel(settings: Settings, modelId: string): string {\n const canonicalModelId = canonicalizeConfiguredModelId(settings, modelId);\n if (canonicalModelId.startsWith(CODEX_MODEL_ID_PREFIX)) {\n return CODEX_PROVIDER_ID;\n }\n const configured = configuredModels(settings).find((model) => model.id === canonicalModelId);\n return configured?.providerId ?? builtinProviderId(settings);\n}\n\nfunction resolvedExecutionLimits(\n settings: Settings,\n model: {\n contextWindowTokens?: number | undefined;\n effectiveContextWindowTokens?: number | undefined;\n autoCompactTokenLimit?: number | undefined;\n toolOutputTruncationTokens?: number | undefined;\n },\n): ModelExecutionLimitsV1 {\n return {\n contextWindowTokens: model.contextWindowTokens ?? settings.contextWindowTokens,\n effectiveContextWindowTokens:\n model.effectiveContextWindowTokens ?? settings.contextEffectiveWindowTokens ?? null,\n autoCompactTokenLimit:\n model.autoCompactTokenLimit ?? settings.contextAutoCompactThresholdTokens ?? null,\n toolOutputTruncationTokens:\n model.toolOutputTruncationTokens ?? settings.modelToolOutputTruncationTokens ?? null,\n };\n}\n\nfunction finalizeConfiguredModel(\n settings: Settings,\n provider: ResolvedModelProvider,\n input: Omit<ConfiguredModel, \"schemaVersion\" | \"definitionVersion\" | \"executionLimits\">,\n): ConfiguredModel {\n const modelWithoutVersion: Omit<ConfiguredModel, \"definitionVersion\"> = {\n schemaVersion: 1,\n ...input,\n executionLimits: resolvedExecutionLimits(settings, input),\n };\n return {\n ...modelWithoutVersion,\n definitionVersion: definitionVersionFor(modelWithoutVersion, provider),\n };\n}\n\nfunction assertUniqueModelIdentities(models: ConfiguredModel[]): void {\n const canonicalOwners = new Map<string, string>();\n for (const model of models) {\n const previous = canonicalOwners.get(model.id);\n if (previous !== undefined) {\n throw new Error(\n `OPENGENI_MODEL_PROVIDERS_JSON model id ${JSON.stringify(model.id)} is declared by both ${previous} and ${model.providerId}`,\n );\n }\n canonicalOwners.set(model.id, model.providerId);\n }\n\n const acceptedInputs = new Map(canonicalOwners);\n for (const model of models) {\n const ownAliases = new Set<string>();\n for (const alias of model.aliases) {\n if (ownAliases.has(alias)) {\n throw new Error(\n `OPENGENI_MODEL_PROVIDERS_JSON model ${JSON.stringify(model.id)} contains duplicate alias ${JSON.stringify(alias)}`,\n );\n }\n ownAliases.add(alias);\n const previous = acceptedInputs.get(alias);\n if (previous !== undefined) {\n throw new Error(\n `OPENGENI_MODEL_PROVIDERS_JSON alias ${JSON.stringify(alias)} for model ${JSON.stringify(model.id)} collides with model/provider ${previous}`,\n );\n }\n acceptedInputs.set(alias, model.id);\n }\n }\n}\n\n/**\n * Every model a client may use, the built-in provider's models first\n * (configuredAllowedModels-from-openai, mapped to \"responses\" with\n * hostedWebSearch/contextWindow/reasoningEffort from the flat settings), then\n * each registry provider's models (label→id, hostedWebSearch/reasoningEffort\n * default false). De-duplicated by id (first wins) so the default model stays\n * first and the built-in allow-list takes precedence over registry entries.\n */\nexport function configuredModels(settings: Settings): ConfiguredModel[] {\n const builtinId = builtinProviderId(settings);\n const builtinLabel = builtinProviderLabel(settings);\n const providers = configuredProviders(settings);\n const providerById = new Map(providers.map((provider) => [provider.id, provider]));\n const pricingSchedules = configuredModelPricingSchedules(settings);\n // The built-in (OpenAI/Azure) provider must NEVER claim a registry-namespaced\n // model id. The worker overwrites settings.openaiModel with the turn's model\n // (apps/worker agent-turn runSettings) — including a `codex/<slug>` id, or a\n // registry id like \"accounts/fireworks/models/glm-5p2\" — so without this\n // filter the built-in allow-list would emit a `{ id, providerId: <azure> }`\n // entry that, by the first-wins de-dup below, shadows the real registry /\n // codex-subscription provider and ships the id to Azure as a deployment name\n // (opaque DeploymentNotFound 404). A `<provider>/<model>`-namespaced id (it\n // contains \"/\") that a registry actually owns is never a valid Azure/OpenAI\n // deployment name, and a `codex/`-prefixed id never is either — exclude both\n // from the built-in list. A BARE id a registry merely redeclares (e.g.\n // \"gpt-5.6-sol\") is left in place so the built-in still wins it via the first-wins\n // de-dup below (preserving the documented built-in-precedence contract). When\n // a codex/ id has NO codex provider injected (no active subscription) it then\n // resolves to nothing and getModel fails loud with\n // CodexSubscriptionUnavailableError instead of mis-routing to Azure.\n const parsedRegistry = parseModelProvidersJson(settings.modelProvidersJson);\n const registryOwnedIds = new Set(\n parsedRegistry.flatMap((provider) => provider.models.map((model) => model.id)),\n );\n const registryAliases = new Set(\n parsedRegistry.flatMap((provider) => provider.models.flatMap((model) => model.aliases ?? [])),\n );\n const isRegistryNamespaced = (id: string): boolean =>\n id.startsWith(CODEX_MODEL_ID_PREFIX) ||\n registryAliases.has(id) ||\n (id.includes(\"/\") && registryOwnedIds.has(id));\n const builtinProvider = providerById.get(builtinId);\n if (!builtinProvider) {\n throw new Error(`Built-in model provider ${builtinId} is not configured`);\n }\n const out: ConfiguredModel[] = uniqueValues([\n settings.openaiModel,\n ...splitCsv(settings.openaiAllowedModels),\n ])\n .filter((id) => !isRegistryNamespaced(id))\n .map((id) => {\n const capabilities = legacyModelCapabilities(settings, {\n reasoningEffort: true,\n hostedWebSearch: settings.webSearchEnabled,\n });\n return finalizeConfiguredModel(settings, builtinProvider, {\n id,\n aliases: [],\n label: id,\n providerId: builtinId,\n providerLabel: builtinLabel,\n api: \"responses\" as const,\n upstreamModelId: id,\n deployment: { upstreamModelId: id, wireApi: \"responses\" },\n credentialSource: builtinProvider.credentialSource,\n billing: builtinProvider.billing,\n capabilities,\n ...(pricingSchedules[id] === undefined ? {} : { pricing: pricingSchedules[id] }),\n contextWindowTokens: settings.contextWindowTokens,\n toolOutputTruncationTokens: settings.modelToolOutputTruncationTokens,\n reasoningEffort: capabilities.reasoning.runnable,\n hostedWebSearch: capabilities.hostedTools.webSearch.runnable,\n });\n });\n for (const provider of parsedRegistry) {\n const providerLabel = provider.label ?? provider.id;\n const resolvedProvider = providerById.get(provider.id);\n if (!resolvedProvider) {\n throw new Error(`Registry model provider ${provider.id} is not configured`);\n }\n for (const model of provider.models) {\n const capabilities = model.capabilities\n ? normalizeCapabilities(model.capabilities)\n : legacyModelCapabilities(settings, {\n reasoningEffort: model.reasoningEffort ?? false,\n hostedWebSearch: model.hostedWebSearch ?? false,\n });\n const upstreamModelId = model.upstreamModelId ?? model.id;\n out.push(\n finalizeConfiguredModel(settings, resolvedProvider, {\n id: model.id,\n aliases: [...(model.aliases ?? [])],\n label: model.label ?? model.id,\n providerId: provider.id,\n providerLabel,\n api: provider.api,\n upstreamModelId,\n deployment: { upstreamModelId, wireApi: provider.api },\n credentialSource: resolvedProvider.credentialSource,\n billing: resolvedProvider.billing,\n capabilities,\n ...(pricingSchedules[model.id] === undefined\n ? {}\n : { pricing: pricingSchedules[model.id] }),\n ...(model.contextWindowTokens === undefined\n ? {}\n : { contextWindowTokens: model.contextWindowTokens }),\n ...(model.effectiveContextWindowTokens === undefined\n ? {}\n : { effectiveContextWindowTokens: model.effectiveContextWindowTokens }),\n ...(model.autoCompactTokenLimit === undefined\n ? {}\n : { autoCompactTokenLimit: model.autoCompactTokenLimit }),\n ...(model.toolOutputTruncationTokens === undefined\n ? {}\n : { toolOutputTruncationTokens: model.toolOutputTruncationTokens }),\n reasoningEffort: capabilities.reasoning.runnable,\n hostedWebSearch: capabilities.hostedTools.webSearch.runnable,\n }),\n );\n }\n }\n assertUniqueModelIdentities(out);\n return out;\n}\n\n/** Resolve a known canonical id or alias. Unknown strings are returned unchanged. */\nexport function canonicalizeConfiguredModelId(settings: Settings, modelId: string): string {\n const models = configuredModels(settings);\n const canonical = models.find((model) => model.id === modelId);\n if (canonical) {\n return canonical.id;\n }\n return models.find((model) => model.aliases.includes(modelId))?.id ?? modelId;\n}\n\n/**\n * Allowed model ids in selection order. Reimplemented on top of\n * configuredModels so it is the union of the built-in allow-list and every\n * registry provider's ids, de-duplicated. INVARIANT (existing callers + tests\n * depend on it): settings.openaiModel is always first, then the rest of the\n * openai allow-list, then registry ids.\n */\nexport function configuredAllowedModels(settings: Settings): string[] {\n return configuredModels(settings).map((model) => model.id);\n}\n\n/**\n * Resolve a model string to the provider that serves it and its configured\n * shape. Returns undefined when the id is not exposed (built-in allow-list nor\n * any registry provider), so the runtime can fall back to the legacy global\n * client path.\n */\nexport function resolveModelProvider(\n settings: Settings,\n modelId: string,\n): { provider: ResolvedModelProvider; model: ConfiguredModel } | undefined {\n const canonicalModelId = canonicalizeConfiguredModelId(settings, modelId);\n const model = configuredModels(settings).find((candidate) => candidate.id === canonicalModelId);\n if (!model) {\n return undefined;\n }\n const provider = configuredProviders(settings).find(\n (candidate) => candidate.id === model.providerId,\n );\n if (!provider) {\n return undefined;\n }\n return { provider, model };\n}\n\nexport type ResolveTurnExecutionPolicyV1Input = {\n /** Effective persisted turn model. Aliases are accepted and canonicalized. */\n modelId: string;\n /** Exact caller-supplied input before canonicalization, only for explicit switches. */\n requestedModelId: string | null;\n modelSource: TurnExecutionModelSourceV1;\n reasoningEffort: Settings[\"openaiReasoningEffort\"];\n reasoningSource: TurnExecutionReasoningSourceV1;\n};\n\nfunction settingsForTurnExecutionPolicy(settings: Settings, modelId: string): Settings {\n return settings.codexSubscriptionEnabled && modelId.startsWith(CODEX_MODEL_ID_PREFIX)\n ? withCodexCatalogProvider(settings)\n : settings;\n}\n\n/**\n * Build a trusted, secret-safe execution policy from the normalized catalog.\n * The Codex overlay here contains static product/provider identity only; it\n * neither proves readiness nor chooses, decrypts, leases, or exposes an account.\n */\nexport function resolveTurnExecutionPolicyV1(\n settings: Settings,\n input: ResolveTurnExecutionPolicyV1Input,\n): TurnExecutionPolicyV1 {\n const catalogSettings = settingsForTurnExecutionPolicy(settings, input.modelId);\n const productModelId = canonicalizeConfiguredModelId(catalogSettings, input.modelId);\n const resolved = resolveModelProvider(catalogSettings, productModelId);\n if (!resolved) {\n throw new Error(\"Turn execution policy model is not present in the configured catalog\");\n }\n if (\n input.requestedModelId !== null &&\n canonicalizeConfiguredModelId(catalogSettings, input.requestedModelId) !== productModelId\n ) {\n throw new Error(\"Turn execution policy requested model does not canonicalize to its product\");\n }\n return TurnExecutionPolicyV1.parse({\n schemaVersion: 1,\n productModelId,\n requestedModelId: input.requestedModelId,\n modelSource: input.modelSource,\n reasoningEffort: input.reasoningEffort,\n reasoningSource: input.reasoningSource,\n providerId: resolved.provider.id,\n upstreamModelId: resolved.model.upstreamModelId,\n wireApi: resolved.model.api,\n credentialSource: resolved.model.credentialSource,\n billing: resolved.model.billing,\n definitionVersion: resolved.model.definitionVersion,\n });\n}\n\n/**\n * Parse-time validation lives in @opengeni/contracts; this verifier binds a\n * present snapshot to the current executable definition and exact turn row.\n * Any deployment/provider drift fails before a provider or compaction call.\n */\nexport function assertTurnExecutionPolicyMatchesConfigV1(\n settings: Settings,\n policy: TurnExecutionPolicyV1,\n expected: {\n modelId: string;\n reasoningEffort: Settings[\"openaiReasoningEffort\"];\n },\n): {\n policy: TurnExecutionPolicyV1;\n provider: ResolvedModelProvider;\n model: ConfiguredModel;\n} {\n const parsed = TurnExecutionPolicyV1.parse(policy);\n const catalogSettings = settingsForTurnExecutionPolicy(settings, parsed.productModelId);\n const canonicalExpectedModel = canonicalizeConfiguredModelId(catalogSettings, expected.modelId);\n if (\n parsed.productModelId !== canonicalExpectedModel ||\n parsed.reasoningEffort !== expected.reasoningEffort\n ) {\n throw new Error(\"Turn execution policy does not match the accepted turn model/reasoning\");\n }\n if (\n parsed.requestedModelId !== null &&\n canonicalizeConfiguredModelId(catalogSettings, parsed.requestedModelId) !==\n parsed.productModelId\n ) {\n throw new Error(\"Turn execution policy requested model does not match its product model\");\n }\n const resolved = resolveModelProvider(catalogSettings, parsed.productModelId);\n if (!resolved) {\n throw new Error(\"Turn execution policy model is no longer configured\");\n }\n const mismatched =\n parsed.providerId !== resolved.provider.id ||\n parsed.upstreamModelId !== resolved.model.upstreamModelId ||\n parsed.wireApi !== resolved.model.api ||\n parsed.definitionVersion !== resolved.model.definitionVersion ||\n canonicalJson(parsed.credentialSource) !== canonicalJson(resolved.model.credentialSource) ||\n canonicalJson(parsed.billing) !== canonicalJson(resolved.model.billing);\n if (mismatched) {\n throw new Error(\"Turn execution policy does not match the current provider definition\");\n }\n return { policy: parsed, provider: resolved.provider, model: resolved.model };\n}\n\n/**\n * Effective per-model pricing schedules. Merge order (later wins): built-in\n * flat defaults → registry model flat/scheduled pricing → explicit legacy flat\n * OPENGENI_MODEL_PRICING_JSON. The explicit legacy map intentionally replaces\n * a registry schedule with one flat default so its historical precedence stays\n * exact.\n */\nexport function configuredModelPricingSchedules(\n settings: Settings,\n): Record<string, ModelPricingScheduleV1> {\n const defaults = Object.fromEntries(\n Object.entries(defaultModelPricing).map(([model, pricing]) => [model, { default: pricing }]),\n );\n const registry: Record<string, ModelPricingScheduleV1> = {};\n for (const provider of parseModelProvidersJson(settings.modelProvidersJson)) {\n for (const model of provider.models) {\n if (model.pricing) {\n registry[model.id] = normalizeModelPricingSchedule(model.pricing);\n }\n }\n }\n const configured = Object.fromEntries(\n Object.entries(parseModelPricingJson(settings.modelPricingJson)).map(([model, pricing]) => [\n model,\n { default: pricing },\n ]),\n );\n return {\n ...defaults,\n ...registry,\n ...configured,\n };\n}\n\n/** Legacy flat projection: returns the default/below-threshold price. */\nexport function configuredModelPricing(settings: Settings): Record<string, ModelPricing> {\n return Object.fromEntries(\n Object.entries(configuredModelPricingSchedules(settings)).map(([model, schedule]) => [\n model,\n schedule.default,\n ]),\n );\n}\n\n/** Select the per-provider-request price at an exact input-token threshold. */\nexport function selectModelPricing(\n schedule: ModelPricingScheduleV1,\n inputTokens: number,\n): ModelPricing {\n const normalizedInputTokens = Math.max(0, Math.floor(inputTokens));\n let selected = schedule.default;\n for (const tier of schedule.inputTokenTiers ?? []) {\n if (normalizedInputTokens < tier.minimumInputTokens) {\n break;\n }\n selected = tier.pricing;\n }\n return selected;\n}\n\n/**\n * Usable input-token budget: an explicit model-catalog effective window when\n * available, otherwise the deployment window minus its output reserve.\n */\nexport function contextInputBudgetTokens(\n settings: Pick<\n Settings,\n \"contextWindowTokens\" | \"contextEffectiveWindowTokens\" | \"contextReservedOutputTokens\"\n >,\n): number {\n if (settings.contextEffectiveWindowTokens !== undefined) {\n return Math.min(settings.contextWindowTokens, settings.contextEffectiveWindowTokens);\n }\n return Math.max(0, settings.contextWindowTokens - settings.contextReservedOutputTokens);\n}\n\n/**\n * Apply the resolved provider/model's context policy to one turn. Registry\n * metadata is authoritative when present; deployment defaults remain the\n * fallback for models that do not declare their own limits.\n */\nexport function settingsWithResolvedModelContext(\n settings: Settings,\n model: Pick<\n ConfiguredModel,\n | \"contextWindowTokens\"\n | \"effectiveContextWindowTokens\"\n | \"autoCompactTokenLimit\"\n | \"toolOutputTruncationTokens\"\n >,\n): Settings {\n const contextWindowTokens = model.contextWindowTokens ?? settings.contextWindowTokens;\n return {\n ...settings,\n contextWindowTokens,\n ...(model.effectiveContextWindowTokens === undefined\n ? {}\n : {\n contextEffectiveWindowTokens: Math.min(\n contextWindowTokens,\n model.effectiveContextWindowTokens,\n ),\n }),\n ...(model.autoCompactTokenLimit === undefined\n ? {}\n : { contextAutoCompactThresholdTokens: model.autoCompactTokenLimit }),\n ...(model.toolOutputTruncationTokens === undefined\n ? {}\n : { modelToolOutputTruncationTokens: model.toolOutputTruncationTokens }),\n };\n}\n\nexport function configuredStaticUsageLimits(settings: Settings): StaticUsageLimitsConfig {\n return parseStaticUsageLimitsJson(settings.staticUsageLimitsJson);\n}\n\nexport function configuredEntitlements(settings: Settings): EntitlementsConfig {\n if (settings.entitlementsMode === \"none\") {\n return {};\n }\n const configured = parseStaticEntitlementsJson(settings.staticEntitlementsJson);\n if (settings.entitlementsMode === \"static\") {\n return configured;\n }\n return {\n \"managed.auth.email_password\": true,\n \"managed.billing.prepaid_credits\": settings.billingMode === \"stripe\",\n \"managed.api_keys\": true,\n \"managed.workspaces\": true,\n \"managed.github_app\": Boolean(settings.githubAppId && settings.githubAppPrivateKey),\n ...configured,\n };\n}\n\nexport function calculateModelUsageCostMicros(\n settings: Settings,\n model: string,\n usage: ModelUsageInput,\n): number {\n const schedule = configuredModelPricingSchedules(settings)[model];\n if (!schedule) {\n throw new Error(`Missing model pricing for ${model}`);\n }\n const entries =\n usage.requestUsageEntries && usage.requestUsageEntries.length > 0\n ? usage.requestUsageEntries\n : [usage];\n const rawCostByPricing = new Map<ModelPricing, number>();\n for (const entry of entries) {\n const pricing = selectModelPricing(schedule, positiveInt(entry.inputTokens));\n rawCostByPricing.set(\n pricing,\n (rawCostByPricing.get(pricing) ?? 0) + calculateEntryCostMicros(pricing, entry),\n );\n }\n let total = 0;\n for (const [pricing, rawCost] of rawCostByPricing) {\n const marginBps = pricing.marginBps ?? 0;\n total += Math.ceil((rawCost * (10_000 + marginBps)) / 10_000);\n }\n return total;\n}\n\nexport function configuredAllowedReasoningEfforts(\n settings: Settings,\n): Array<z.infer<typeof ReasoningEffort>> {\n return uniqueValues([\n settings.openaiReasoningEffort,\n ...splitCsv(settings.openaiAllowedReasoningEfforts),\n ]).map((value) => ReasoningEffort.parse(value));\n}\n\n/**\n * Decodes OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY (base64, exactly 32 bytes) for\n * AES-256-GCM workspace environment value encryption. Returns null when unset.\n * Throws naming only the env var, never echoing its value.\n */\nexport function environmentsEncryptionKeyBytes(settings: Settings): Uint8Array | null {\n if (!settings.environmentsEncryptionKey) {\n return null;\n }\n const decoded = Buffer.from(settings.environmentsEncryptionKey, \"base64\");\n if (decoded.length !== 32) {\n throw new Error(\n \"OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY must be base64 for exactly 32 bytes (generate with: openssl rand -base64 32)\",\n );\n }\n return new Uint8Array(decoded);\n}\n\n/**\n * Build one structurally compatible connection policy for both\n * `@temporalio/client` and `@temporalio/worker`. An API key or any custom TLS\n * material enables TLS automatically; the explicit flag covers server-auth TLS\n * without credentials. Secret values are never included in validation errors.\n */\nexport function temporalConnectionOptions(settings: Settings): TemporalConnectionOptions {\n const apiKey = settings.temporalApiKey?.trim() || undefined;\n const serverNameOverride = settings.temporalTlsServerName?.trim() || undefined;\n const rootCa = decodeTemporalTlsMaterial(\n settings.temporalTlsRootCaCertificateBase64,\n \"OPENGENI_TEMPORAL_TLS_ROOT_CA_CERTIFICATE_BASE64\",\n );\n const clientCertificate = decodeTemporalTlsMaterial(\n settings.temporalTlsClientCertificateBase64,\n \"OPENGENI_TEMPORAL_TLS_CLIENT_CERTIFICATE_BASE64\",\n );\n const clientPrivateKey = decodeTemporalTlsMaterial(\n settings.temporalTlsClientPrivateKeyBase64,\n \"OPENGENI_TEMPORAL_TLS_CLIENT_PRIVATE_KEY_BASE64\",\n );\n\n if (Boolean(clientCertificate) !== Boolean(clientPrivateKey)) {\n throw new Error(\n \"OPENGENI_TEMPORAL_TLS_CLIENT_CERTIFICATE_BASE64 and \" +\n \"OPENGENI_TEMPORAL_TLS_CLIENT_PRIVATE_KEY_BASE64 must both be set or both omitted\",\n );\n }\n\n const tls: TemporalTlsConnectionConfig = {};\n if (serverNameOverride) {\n tls.serverNameOverride = serverNameOverride;\n }\n if (rootCa) {\n tls.serverRootCACertificate = rootCa;\n }\n if (clientCertificate && clientPrivateKey) {\n tls.clientCertPair = { crt: clientCertificate, key: clientPrivateKey };\n }\n const hasCustomTls = Object.keys(tls).length > 0;\n const tlsEnabled = settings.temporalTlsEnabled || Boolean(apiKey) || hasCustomTls;\n\n return {\n address: settings.temporalHost,\n ...(tlsEnabled ? { tls: hasCustomTls ? tls : true } : {}),\n ...(apiKey ? { apiKey } : {}),\n };\n}\n\nfunction decodeTemporalTlsMaterial(\n value: string | undefined,\n settingName: string,\n): Uint8Array | undefined {\n // RFC 2045 base64 commonly arrives wrapped at 76 columns. Kubernetes\n // stringData and external secret stores preserve those line breaks, so\n // normalize whitespace before applying the strict alphabet/canonical check.\n const encoded = value?.replace(/\\s/g, \"\");\n if (!encoded) {\n return undefined;\n }\n if (!/^[A-Za-z0-9+/]+={0,2}$/.test(encoded) || encoded.length % 4 === 1) {\n throw new Error(`${settingName} must contain valid base64`);\n }\n const decoded = Buffer.from(encoded, \"base64\");\n const canonical = decoded.toString(\"base64\").replace(/=+$/, \"\");\n if (decoded.length === 0 || canonical !== encoded.replace(/=+$/, \"\")) {\n throw new Error(`${settingName} must contain valid base64`);\n }\n return new Uint8Array(decoded);\n}\n\n/**\n * The connection `search_path` for OpenGeni's db handles + the managed-auth pool\n * (Step I, §7.8 runtime half). Returns `undefined` when `dbSchema` is unset\n * (standalone) so no `search_path` startup parameter is sent and the server\n * default (`public`) applies — byte-for-byte today's behavior. When `dbSchema`\n * is set (embedded), returns `\"<schema>,opengeni_private,public\"` — `public`\n * stays LAST so `gen_random_uuid()` (pgcrypto) and the `vector` type still\n * resolve (the schema-isolation contract live footgun). `opengeni_private` is on the path so the\n * RLS GUC-reader helpers resolve when referenced unqualified.\n */\nexport function dbSearchPath(settings: Pick<Settings, \"dbSchema\">): string | undefined {\n const schema = settings.dbSchema?.trim();\n if (!schema) {\n return undefined;\n }\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(schema)) {\n throw new Error(`OPENGENI_DB_SCHEMA is not a valid Postgres identifier: ${schema}`);\n }\n return `${schema},opengeni_private,public`;\n}\n\nexport function collectGitIdentityEnvironment(settings: Settings): Record<string, string> {\n return Object.fromEntries(\n Object.entries({\n GIT_AUTHOR_NAME: settings.gitAuthorName,\n GIT_AUTHOR_EMAIL: settings.gitAuthorEmail,\n GIT_COMMITTER_NAME: settings.gitCommitterName ?? settings.gitAuthorName,\n GIT_COMMITTER_EMAIL: settings.gitCommitterEmail ?? settings.gitAuthorEmail,\n }).filter(\n (entry): entry is [string, string] =>\n typeof entry[1] === \"string\" && entry[1].trim().length > 0,\n ),\n );\n}\n\nconst DEFAULT_SANDBOX_PATH = \"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\";\n\nfunction prependPathEntry(pathValue: string | undefined, entry: string): string {\n const parts = (pathValue ?? DEFAULT_SANDBOX_PATH).split(\":\").filter(Boolean);\n return [entry, ...parts.filter((part) => part !== entry)].join(\":\");\n}\n\n/**\n * The STABLE run-scoped sandbox environment: the subset of a run's box-manifest\n * environment that is IDENTICAL whether the box is first warmed by the worker\n * TURN or by an API-direct ATTACH (viewer / Channel-A / desktop / terminal). It\n * is the layered base every cold box must be created with so a later turn's\n * agent-manifest apply finds an EMPTY environment delta in the SDK's\n * `validateNoEnvironmentDelta` (which throws \"Live sandbox sessions cannot change\n * manifest environment variables\" on ANY key the agent declares that the box's\n * manifest lacks or carries a different value for).\n *\n * Precedence (lowest → highest): deployment allowlist (`collectSandboxEnvironment`)\n * < git identity (`collectGitIdentityEnvironment`) < the session's attached\n * workspace environment < the backend-aware HOME default. Reserved-name validation\n * at write time keeps workspace values from colliding with platform entries.\n *\n * DELIBERATELY EXCLUDES the per-run, ROTATING git provider token VALUES that\n * `sandboxEnvironmentForRun` mints when a repository resource is\n * attached: that token is minted FRESH per call, so it is not a stable, attach-\n * reproducible value and must not be part of the shared base. Under the token-\n * broker (B1) token VALUES never ride the manifest at all — they are seeded to\n * FILES inside the box and git/provider CLI auth reads those files. What IS stable\n * and lives here for provisioned boxes are the token directory / GitHub alias\n * FILE PATH and wrapper PATH entries: constants derived from HOME, so they\n * appear IDENTICALLY on BOTH the turn AND every attach manifest (the SDK's\n * per-turn provided-session env delta stays empty even as tokens rotate). These\n * helper pointers are deliberately not added for selfhosted/local/none because\n * the platform never mints or seeds git provider tokens there. The attach\n * surfaces have only the `Session` (no repo resources) and so never seed a token,\n * but unwritten files simply yield no auth; the BLOCKING attach-vs-turn error\n * this helper fixes is for the common (no-repo) and workspace-environment-attached\n * provisioned-box cases.\n */\nexport function stableSandboxEnvironmentForRun(\n settings: Settings,\n workspaceEnvironment: Record<string, string> = {},\n options: { workspaceId?: string } = {},\n): Record<string, string> {\n const environment: Record<string, string> = {\n ...collectSandboxEnvironment(settings),\n ...collectGitIdentityEnvironment(settings),\n ...workspaceEnvironment,\n };\n // Backend-aware HOME: a provisioned box (docker + every cloud provider) runs the\n // agent under the descriptor's workspaceRoot. `local` runs in-process as the host\n // unix user (keep its real $HOME); `none` has no box.\n const descriptor = CAPABILITY_DESCRIPTORS[settings.sandboxBackend];\n if (settings.sandboxBackend !== \"none\" && settings.sandboxBackend !== \"local\") {\n environment.HOME ??= descriptor.workspaceRoot;\n }\n // TOKEN-BROKER (B1): the STABLE credential FILE PATHS and CLI wrapper PATH for\n // provisioned boxes only. Constants derived from the resolved HOME (falling\n // back to the descriptor workspaceRoot), so they are parity-safe — they join\n // the shared base and therefore appear IDENTICALLY on BOTH the worker-turn\n // manifest AND every API-direct attach manifest. Only PATHS are stable; token\n // VALUES live exclusively in files that runtime seeds off-manifest.\n const provisionedGitHelperBackend =\n settings.sandboxBackend !== \"none\" &&\n settings.sandboxBackend !== \"local\" &&\n settings.sandboxBackend !== \"selfhosted\";\n if (provisionedGitHelperBackend) {\n const home = environment.HOME ?? descriptor.workspaceRoot;\n environment.OPENGENI_GIT_CREDENTIALS_DIR ??= `${home}/.opengeni/git-credentials`;\n environment.OPENGENI_GIT_TOKEN_FILE ??= `${home}/.opengeni/git-token`;\n environment.OPENGENI_GIT_CLI_WRAPPER_DIR ??= `${home}/.opengeni/bin`;\n environment.PATH = prependPathEntry(environment.PATH, environment.OPENGENI_GIT_CLI_WRAPPER_DIR);\n }\n if (settings.toolspaceEnabled) {\n environment.OPENGENI_TOOLSPACE_TOKEN_FILE ??= `${environment.HOME ?? descriptor.workspaceRoot}/.opengeni/toolspace-token`;\n if (settings.ogtoolPackageSpec) {\n environment.OPENGENI_OGTOOL_PACKAGE_SPEC ??= settings.ogtoolPackageSpec;\n }\n if (options.workspaceId) {\n environment.OPENGENI_TOOLSPACE_URL ??= firstPartyMcpWorkspaceUrl(\n settings,\n options.workspaceId,\n );\n }\n }\n return environment;\n}\n\n/**\n * Whether a resource set carries a GitHub-App-connected repository (installation\n * + repository ids present) — the SAME predicate the worker turn uses to decide\n * whether it declares the stable git-auth pointers. Attach surfaces call this so\n * an attach-warmed cold box carries the IDENTICAL manifest env a later repo turn\n * declares (env parity — see applyGitAuthPointerEnvironment).\n */\nexport function hasGitHubRepositorySelection(\n resources: ReadonlyArray<{\n kind: string;\n provider?: unknown;\n installationId?: unknown;\n repositoryId?: unknown;\n githubInstallationId?: unknown;\n githubRepositoryId?: unknown;\n }>,\n): boolean {\n const positive = (value: unknown): boolean =>\n (typeof value === \"number\" && Number.isInteger(value) && value > 0) ||\n (typeof value === \"string\" && /^\\d+$/.test(value) && Number(value) > 0);\n return resources.some(\n (resource) =>\n resource.kind === \"repository\" &&\n ((positive(resource.githubInstallationId) && positive(resource.githubRepositoryId)) ||\n (resource.provider === \"github\" &&\n positive(resource.installationId) &&\n positive(resource.repositoryId))),\n );\n}\n\nexport function hasGitCredentialRepositorySelection(\n resources: ReadonlyArray<{\n kind: string;\n provider?: unknown;\n githubInstallationId?: unknown;\n githubRepositoryId?: unknown;\n }>,\n): boolean {\n return resources.some(\n (resource) =>\n resource.kind === \"repository\" &&\n (resource.provider === \"github\" ||\n resource.provider === \"gitlab\" ||\n resource.provider === \"azure_devops\" ||\n hasGitHubRepositorySelection([resource])),\n );\n}\n\n/**\n * TOKEN-BROKER (B1) parity: the STABLE git-auth POINTER environment a\n * repo-attached run declares — GIT_ASKPASS (a fixed path under HOME; the script\n * itself is provisioned at box setup), GIT_TERMINAL_PROMPT, and the GitHub-App\n * bot identity fallbacks. NO rotating value rides here (the token lives in the\n * file behind the askpass), so the layer is attach-reproducible and MUST be\n * applied identically by the worker turn (sandboxEnvironmentForRun) AND every\n * API-direct attach surface that can cold-create the box (viewer attach,\n * channel-A ops). A box cold-created WITHOUT this layer kills the next repo\n * turn: the turn's manifest declares these keys, the box's env lacks them, and\n * the SDK's provided-session guard throws \"Live sandbox sessions cannot change\n * manifest environment variables\" (observed live: an open session page's viewer\n * attach won the cold-create race and the first turn died).\n *\n * Mutates and returns `environment`. Identity fallbacks preserve values already\n * present (the deployment git-identity allowlist wins over the bot identity).\n */\nexport function applyGitAuthPointerEnvironment(\n environment: Record<string, string>,\n identity: { name: string; email: string } | null,\n): Record<string, string> {\n environment.GIT_ASKPASS = `${environment.HOME ?? \"/workspace\"}/.opengeni/askpass`;\n environment.GIT_TERMINAL_PROMPT = \"0\";\n if (identity) {\n environment.GIT_AUTHOR_NAME = environment.GIT_AUTHOR_NAME || identity.name;\n environment.GIT_AUTHOR_EMAIL = environment.GIT_AUTHOR_EMAIL || identity.email;\n environment.GIT_COMMITTER_NAME = environment.GIT_COMMITTER_NAME || identity.name;\n environment.GIT_COMMITTER_EMAIL = environment.GIT_COMMITTER_EMAIL || identity.email;\n }\n return environment;\n}\n\nexport type StartupRetryOptions = {\n attempts?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n onRetry?: (event: {\n label: string;\n attempt: number;\n attempts: number;\n delayMs: number;\n error: unknown;\n }) => void;\n};\n\nexport function startupRetryOptions(\n settings: Settings,\n): Required<Omit<StartupRetryOptions, \"onRetry\">> {\n return {\n attempts: settings.startupDependencyRetryAttempts,\n initialDelayMs: settings.startupDependencyRetryInitialDelayMs,\n maxDelayMs: settings.startupDependencyRetryMaxDelayMs,\n };\n}\n\nexport async function retryStartupDependency<T>(\n label: string,\n operation: () => Promise<T>,\n options: StartupRetryOptions = {},\n): Promise<T> {\n const attempts = Math.max(1, Math.floor(options.attempts ?? 30));\n const initialDelayMs = Math.max(0, Math.floor(options.initialDelayMs ?? 1000));\n const maxDelayMs = Math.max(initialDelayMs, Math.floor(options.maxDelayMs ?? 5000));\n for (let attempt = 1; attempt <= attempts; attempt += 1) {\n try {\n return await operation();\n } catch (error) {\n if (attempt >= attempts) {\n throw error;\n }\n const delayMs = Math.min(maxDelayMs, initialDelayMs * 2 ** (attempt - 1));\n options.onRetry?.({ label, attempt, attempts, delayMs, error });\n await delay(delayMs);\n }\n }\n throw new Error(`unreachable startup retry state for ${label}`);\n}\n\nexport function sandboxEnvironmentVariableNames(settings: Settings): string[] {\n const profiles = sandboxPreparationProfileNames(settings);\n const names: string[] = [];\n for (const profile of profiles) {\n names.push(...sandboxPreparationProfiles[profile]!.env);\n }\n names.push(...splitCsv(settings.sandboxEnvAllowlist));\n return uniqueEnvNames(names, \"sandbox env\");\n}\n\nexport function sandboxLifecycleHookIds(settings: Settings): string[] {\n const ids: string[] = [];\n for (const profile of sandboxPreparationProfileNames(settings)) {\n ids.push(...sandboxPreparationProfiles[profile]!.hooks);\n }\n return uniqueValues(ids);\n}\n\nfunction sandboxPreparationProfileNames(settings: Settings): string[] {\n const profiles = splitCsv(settings.sandboxPreparationProfiles).map((value) =>\n value.toLowerCase(),\n );\n if (profiles.includes(\"none\")) {\n if (profiles.length > 1) {\n throw new Error(\n \"OPENGENI_SANDBOX_PREPARATION_PROFILES cannot combine none with other profiles\",\n );\n }\n return [\"none\"];\n }\n for (const profile of profiles) {\n if (!sandboxPreparationProfiles[profile]) {\n throw new Error(`Unknown sandbox preparation profile ${profile}`);\n }\n }\n return profiles;\n}\n\nexport function parseExposedPorts(raw: string): number[] {\n return splitCsv(raw).map((value) => {\n const port = Number(value);\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(\"OPENGENI_DOCKER_EXPOSED_PORTS must contain TCP port numbers\");\n }\n return port;\n });\n}\n\nexport function parseMcpServers(raw: string | undefined): unknown[] | undefined {\n if (!raw) {\n return undefined;\n }\n try {\n const parsed = JSON.parse(raw);\n if (!Array.isArray(parsed)) {\n throw new Error(\"value must be a JSON array\");\n }\n return parsed;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`OPENGENI_MCP_SERVERS must be a JSON array: ${message}`, { cause: error });\n }\n}\n\nexport function parseModelPricingJson(raw: string): Record<string, ModelPricing> {\n if (!raw.trim() || raw.trim() === \"{}\") {\n return {};\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`OPENGENI_MODEL_PRICING_JSON must be valid JSON: ${message}`, { cause: error });\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(\"OPENGENI_MODEL_PRICING_JSON must be a JSON object keyed by model name\");\n }\n const out: Record<string, ModelPricing> = {};\n for (const [model, value] of Object.entries(parsed)) {\n if (!model.trim()) {\n throw new Error(\"OPENGENI_MODEL_PRICING_JSON contains an empty model name\");\n }\n out[model] = ModelPricingSchema.parse(value);\n }\n return out;\n}\n\n// --- sandbox warm-rate table (P2.1) ---\n// Per-backend usd_micros/sec, parsed from sandboxWarmRateMicrosPerSecondJson the\n// same way model pricing is. An empty {} (the default) means no warm-cost is\n// debited — warm-seconds are still metered for audit, just at rate 0.\nexport function parseSandboxWarmRateJson(raw: string): Record<string, number> {\n if (!raw.trim() || raw.trim() === \"{}\") {\n return {};\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(\n `OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON must be valid JSON: ${message}`,\n { cause: error },\n );\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(\n \"OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON must be a JSON object keyed by backend name\",\n );\n }\n const out: Record<string, number> = {};\n for (const [backend, value] of Object.entries(parsed)) {\n if (!backend.trim()) {\n throw new Error(\n \"OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON contains an empty backend name\",\n );\n }\n const rate = typeof value === \"number\" ? value : Number(value);\n if (!Number.isFinite(rate) || rate < 0) {\n throw new Error(\n `OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON rate for ${backend} must be a non-negative number`,\n );\n }\n out[backend] = rate;\n }\n return out;\n}\n\n// Resolve the warm rate (usd_micros/sec) for a backend; 0 when the backend has no\n// configured rate (the box is metered in seconds but not cost-debited).\nexport function sandboxWarmRateMicrosPerSecond(settings: Settings, backend: string): number {\n const table = parseSandboxWarmRateJson(settings.sandboxWarmRateMicrosPerSecondJson);\n return table[backend] ?? 0;\n}\n\n/**\n * Parse + validate the extra-provider registry JSON. `[]` (or empty/whitespace)\n * yields an empty list. Surfaces JSON and zod errors prefixed with the env-var\n * name so a malformed registry fails fast at boot (validateSettings calls this).\n */\nexport function parseModelProvidersJson(raw: string): RegistryProvider[] {\n if (!raw.trim() || raw.trim() === \"[]\") {\n return [];\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`OPENGENI_MODEL_PROVIDERS_JSON must be valid JSON: ${message}`, {\n cause: error,\n });\n }\n if (!Array.isArray(parsed)) {\n throw new Error(\"OPENGENI_MODEL_PROVIDERS_JSON must be a JSON array of providers\");\n }\n return parsed.map((entry, index) => {\n const result = RegistryProviderSchema.safeParse(entry);\n if (!result.success) {\n throw new Error(\n `OPENGENI_MODEL_PROVIDERS_JSON provider[${index}] is invalid: ${result.error.message}`,\n );\n }\n try {\n return normalizeRegistryProvider(result.data);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`OPENGENI_MODEL_PROVIDERS_JSON provider[${index}] is invalid: ${message}`, {\n cause: error,\n });\n }\n });\n}\n\nexport function parseIntegrationsOauthClientsJson(\n raw: string | undefined,\n): Record<string, IntegrationOAuthClientConfig> {\n if (!raw?.trim() || raw.trim() === \"{}\") {\n return {};\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`OPENGENI_INTEGRATIONS_OAUTH_CLIENTS_JSON must be valid JSON: ${message}`, {\n cause: error,\n });\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(\n \"OPENGENI_INTEGRATIONS_OAUTH_CLIENTS_JSON must be a JSON object keyed by authorization-server issuer or URL\",\n );\n }\n const out: Record<string, IntegrationOAuthClientConfig> = {};\n for (const [key, value] of Object.entries(parsed)) {\n if (!key.trim()) {\n throw new Error(\"OPENGENI_INTEGRATIONS_OAUTH_CLIENTS_JSON contains an empty issuer key\");\n }\n const result = IntegrationOAuthClientConfigSchema.safeParse(value);\n if (!result.success) {\n throw new Error(\n `OPENGENI_INTEGRATIONS_OAUTH_CLIENTS_JSON client for ${key} is invalid: ${result.error.message}`,\n );\n }\n out[key] = result.data;\n }\n return out;\n}\n\nexport function parseStaticUsageLimitsJson(raw: string): StaticUsageLimitsConfig {\n if (!raw.trim() || raw.trim() === \"{}\") {\n return {};\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`OPENGENI_STATIC_USAGE_LIMITS_JSON must be valid JSON: ${message}`, {\n cause: error,\n });\n }\n return StaticUsageLimits.parse(parsed);\n}\n\nexport function parseStaticEntitlementsJson(raw: string): EntitlementsConfig {\n if (!raw.trim() || raw.trim() === \"{}\") {\n return {};\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`OPENGENI_STATIC_ENTITLEMENTS_JSON must be valid JSON: ${message}`, {\n cause: error,\n });\n }\n return Entitlements.parse(parsed);\n}\n\nfunction calculateEntryCostMicros(pricing: ModelPricing, entry: ModelUsageInput): number {\n const inputTokens = positiveInt(entry.inputTokens);\n const outputTokens = positiveInt(entry.outputTokens);\n const cachedTokens = Math.min(inputTokens, cachedInputTokens(entry));\n const uncachedInputTokens = Math.max(0, inputTokens - cachedTokens);\n const cachedInputRate =\n pricing.cachedInputMicrosPerMillionTokens ?? pricing.inputMicrosPerMillionTokens;\n return (\n Math.ceil((uncachedInputTokens * pricing.inputMicrosPerMillionTokens) / 1_000_000) +\n Math.ceil((cachedTokens * cachedInputRate) / 1_000_000) +\n Math.ceil((outputTokens * pricing.outputMicrosPerMillionTokens) / 1_000_000)\n );\n}\n\nfunction cachedInputTokens(entry: ModelUsageInput): number {\n const details = Array.isArray(entry.inputTokensDetails)\n ? entry.inputTokensDetails\n : entry.inputTokensDetails\n ? [entry.inputTokensDetails]\n : [];\n let total = 0;\n for (const detail of details) {\n total +=\n positiveInt(detail.cached_tokens) +\n positiveInt(detail.cachedInputTokens) +\n positiveInt(detail.cached_input_tokens);\n }\n return total;\n}\n\nfunction positiveInt(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;\n}\n\nfunction ensureBuiltInMcpServers(settings: Settings): Settings[\"mcpServers\"] {\n const existing = settings.mcpServers.filter((server) => server.id !== \"opengeni\");\n const firstPartyMcpUrl = firstPartyMcpServerUrl(settings);\n const firstPartyDocsMcpUrl = firstPartyDocumentsMcpServerUrl(firstPartyMcpUrl);\n const hasFiles = existing.some((server) => server.id === \"files\");\n const hasDocs = existing.some((server) => server.id === \"docs\");\n return [\n {\n id: \"opengeni\",\n name: \"OpenGeni\",\n url: firstPartyMcpUrl,\n // The opengeni server's tools/list response is permission-scoped: it\n // varies by the calling session's delegated grant (e.g. a manager\n // session sees sessions_*/environment_* tools that a worker session\n // does not). The OpenAI Agents SDK caches tools/list in a process-global\n // map keyed only by the MCP server name, which is identical for every\n // session in the worker process. Caching here would let the first\n // session to warm the cache dictate what every later session sees,\n // regardless of permissions. tools/list is a cheap per-turn call, so we\n // never cache it. (The files server pins allowedTools to a single\n // permission-invariant tool and docs is already uncached, so both stay\n // safe to cache / leave as-is.)\n cacheToolsList: false,\n },\n ...(hasFiles\n ? []\n : [\n {\n id: \"files\",\n name: \"Files\",\n url: firstPartyMcpUrl,\n allowedTools: [\"files_get_download_url\"],\n cacheToolsList: true,\n },\n ]),\n ...(hasDocs\n ? []\n : [\n {\n id: \"docs\",\n name: \"Document Search\",\n url: firstPartyDocsMcpUrl,\n allowedTools: [\n \"search_documents\",\n \"fetch_document_chunk\",\n \"list_document_bases\",\n \"knowledge_search\",\n \"knowledge_fetch\",\n \"memory_search\",\n \"memory_propose\",\n ],\n cacheToolsList: false,\n },\n ]),\n ...existing,\n ];\n}\n\n/**\n * The base URL of OpenGeni's own first-party MCP endpoint, as a `{workspaceId}`\n * template — the SINGLE source of truth for the `opengeniMcpUrl`-or-loopback\n * decision. Every site that needs the first-party MCP base (config's tool\n * registry here, and the worker-side `firstPartyMcpServerUrlForRun` /\n * `firstPartyMcpUrls` in @opengeni/runtime) MUST route through this so the\n * default lives in exactly one place.\n *\n * BINDING CONTRACT (`opengeniMcpUrl`):\n * - STANDALONE (unset): falls back to the loopback default\n * `http://127.0.0.1:${apiPort}/v1/workspaces/{workspaceId}/mcp` — the worker\n * and API are in/next to the same host:port, so loopback resolves the\n * workspace-scoped MCP. Byte-for-byte today's behavior.\n * - EMBEDDED / MOUNTED (must set): when OpenGeni's API is mounted as a host\n * sub-app under a prefix (e.g. `https://host/og/v1/...`), the loopback\n * default is WRONG — the worker runs in the host process and `127.0.0.1:\n * ${apiPort}` is not where the mounted, sandbox-routable MCP lives. The host\n * MUST set `OPENGENI_MCP_URL` to the externally/sandbox-routable base (a\n * `{workspaceId}` template, or a concrete base that gets re-scoped). This is\n * the one binding a mounted embed cannot leave unset.\n */\nexport function firstPartyMcpBaseUrl(settings: Settings): string {\n return (\n settings.opengeniMcpUrl ??\n `http://127.0.0.1:${settings.apiPort}/v1/workspaces/{workspaceId}/mcp`\n );\n}\n\nexport function firstPartyMcpWorkspaceUrl(settings: Settings, workspaceId: string): string {\n const raw = firstPartyMcpBaseUrl(settings);\n if (raw.includes(\"{workspaceId}\")) {\n return raw.replaceAll(\"{workspaceId}\", workspaceId);\n }\n const url = new URL(raw);\n url.pathname = `/v1/workspaces/${workspaceId}/mcp`;\n url.search = \"\";\n url.hash = \"\";\n return url.toString();\n}\n\nfunction firstPartyMcpServerUrl(settings: Settings): string {\n return firstPartyMcpBaseUrl(settings);\n}\n\nfunction firstPartyDocumentsMcpServerUrl(mcpUrl: string): string {\n return `${mcpUrl.replace(/\\/+$/, \"\")}/docs`;\n}\n\nfunction validateSettings(settings: Settings): void {\n temporalConnectionOptions(settings);\n if (settings.toolspaceEnabled && !settings.delegationSecret) {\n throw new Error(\"OPENGENI_DELEGATION_SECRET is required when OPENGENI_TOOLSPACE_ENABLED=true\");\n }\n if (settings.productAccessMode === \"managed\") {\n if (!settings.publicBaseUrl) {\n throw new Error(\n \"OPENGENI_PUBLIC_BASE_URL is required when OPENGENI_PRODUCT_ACCESS_MODE=managed\",\n );\n }\n if (!settings.betterAuthSecret) {\n throw new Error(\n \"OPENGENI_BETTER_AUTH_SECRET is required when OPENGENI_PRODUCT_ACCESS_MODE=managed\",\n );\n }\n if (!settings.delegationSecret) {\n throw new Error(\n \"OPENGENI_DELEGATION_SECRET is required when OPENGENI_PRODUCT_ACCESS_MODE=managed\",\n );\n }\n if (![\"local\", \"test\"].includes(settings.environment) && !settings.resendApiKey) {\n throw new Error(\"OPENGENI_RESEND_API_KEY is required for managed mode outside local/test\");\n }\n if (![\"local\", \"test\"].includes(settings.environment) && !settings.environmentsEncryptionKey) {\n throw new Error(\n \"OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY is required for managed mode outside local/test\",\n );\n }\n }\n environmentsEncryptionKeyBytes(settings);\n if (settings.integrationsEnabled) {\n if (settings.productAccessMode === \"managed\" && !settings.publicBaseUrl) {\n throw new Error(\n \"OPENGENI_PUBLIC_BASE_URL is required when OPENGENI_INTEGRATIONS_ENABLED=true and OPENGENI_PRODUCT_ACCESS_MODE=managed\",\n );\n }\n if (\n settings.publicBaseUrl &&\n !settings.publicBaseUrl.startsWith(\"https://\") &&\n ![\"local\", \"test\"].includes(settings.environment)\n ) {\n throw new Error(\n \"OPENGENI_PUBLIC_BASE_URL must use https when OPENGENI_INTEGRATIONS_ENABLED=true outside local/test\",\n );\n }\n if (!settings.integrationsStateSecret && ![\"local\", \"test\"].includes(settings.environment)) {\n throw new Error(\n \"OPENGENI_INTEGRATIONS_STATE_SECRET is required when OPENGENI_INTEGRATIONS_ENABLED=true outside local/test\",\n );\n }\n }\n parseIntegrationsOauthClientsJson(settings.integrationsOauthClientsJson);\n if (\n settings.productAccessMode === \"configured\" &&\n ![\"local\", \"test\"].includes(settings.environment) &&\n !settings.delegationSecret &&\n !settings.authRequired\n ) {\n throw new Error(\n \"OPENGENI_PRODUCT_ACCESS_MODE=configured requires OPENGENI_DELEGATION_SECRET or OPENGENI_AUTH_REQUIRED=true outside local/test\",\n );\n }\n if (settings.billingMode === \"stripe\") {\n if (!settings.stripeSecretKey || !settings.stripeWebhookSecret) {\n throw new Error(\n \"OPENGENI_STRIPE_SECRET_KEY and OPENGENI_STRIPE_WEBHOOK_SECRET are required when OPENGENI_BILLING_MODE=stripe\",\n );\n }\n }\n if (settings.productAccessMode !== \"managed\" && settings.billingMode === \"stripe\") {\n throw new Error(\"OPENGENI_BILLING_MODE=stripe requires OPENGENI_PRODUCT_ACCESS_MODE=managed\");\n }\n if (settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\") {\n const pricing = configuredModelPricing(settings);\n const missing = configuredAllowedModels(settings).filter((model) => !pricing[model]);\n if (missing.length > 0) {\n throw new Error(\n `Missing model pricing for managed billing model(s): ${missing.join(\", \")}. Set OPENGENI_MODEL_PRICING_JSON.`,\n );\n }\n }\n if (settings.usageLimitsMode === \"static\") {\n const limits = configuredStaticUsageLimits(settings);\n if (Object.keys(limits).length === 0) {\n throw new Error(\n \"OPENGENI_STATIC_USAGE_LIMITS_JSON must define at least one cap when OPENGENI_USAGE_LIMITS_MODE=static\",\n );\n }\n } else {\n parseStaticUsageLimitsJson(settings.staticUsageLimitsJson);\n }\n if (settings.entitlementsMode === \"static\") {\n const entitlements = parseStaticEntitlementsJson(settings.staticEntitlementsJson);\n if (Object.keys(entitlements).length === 0) {\n throw new Error(\n \"OPENGENI_STATIC_ENTITLEMENTS_JSON must define at least one feature when OPENGENI_ENTITLEMENTS_MODE=static\",\n );\n }\n } else {\n parseStaticEntitlementsJson(settings.staticEntitlementsJson);\n }\n if (settings.authRequired && !settings.accessKey) {\n throw new Error(\"OPENGENI_ACCESS_KEY is required when OPENGENI_AUTH_REQUIRED=true\");\n }\n if (settings.openaiProvider === \"azure\") {\n if (!settings.azureOpenaiBaseUrl && !settings.azureOpenaiEndpoint) {\n throw new Error(\n \"Azure OpenAI requires OPENGENI_AZURE_OPENAI_BASE_URL or OPENGENI_AZURE_OPENAI_ENDPOINT\",\n );\n }\n if (!settings.azureOpenaiBaseUrl && !settings.azureOpenaiDeployment) {\n throw new Error(\"Azure OpenAI endpoint mode requires OPENGENI_AZURE_OPENAI_DEPLOYMENT\");\n }\n if (!settings.azureOpenaiBaseUrl && !settings.azureOpenaiApiVersion) {\n throw new Error(\"Azure OpenAI endpoint mode requires OPENGENI_AZURE_OPENAI_API_VERSION\");\n }\n if (!settings.azureOpenaiApiKey && !settings.azureOpenaiAdToken) {\n throw new Error(\"Azure OpenAI requires an API key or AD token\");\n }\n }\n // The Modal token is a both-or-neither pair regardless of the active backend\n // (a half-configured token is always a misconfiguration). This is orthogonal\n // to the backend-gated required-cred sweep below.\n if (Boolean(settings.modalTokenId) !== Boolean(settings.modalTokenSecret)) {\n throw new Error(\n \"OPENGENI_MODAL_TOKEN_ID and OPENGENI_MODAL_TOKEN_SECRET must both be set or both omitted\",\n );\n }\n // Backend-gated required credentials: only the *active* backend's creds are\n // required. A modal deployment must carry the Modal token; a daytona/e2b/none\n // deployment must NOT be forced to (and is not). Drives off the single\n // SANDBOX_REQUIRED_ENV table that the deployment package also mirrors.\n for (const required of SANDBOX_REQUIRED_ENV[settings.sandboxBackend] ?? []) {\n const value = settings[required.field];\n if (\n value === undefined ||\n value === null ||\n (typeof value === \"string\" && value.trim().length === 0)\n ) {\n throw new Error(\n `${required.env} is required when OPENGENI_SANDBOX_BACKEND=${settings.sandboxBackend}`,\n );\n }\n }\n if (\n settings.objectStorageBackend === \"s3-compatible\" ||\n settings.objectStorageBackend === \"aws-s3\"\n ) {\n if (\n Boolean(settings.objectStorageAccessKeyId) !== Boolean(settings.objectStorageSecretAccessKey)\n ) {\n throw new Error(\n \"OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID and OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY must both be set or both omitted\",\n );\n }\n if (\n settings.objectStorageBackend === \"s3-compatible\" &&\n (settings.objectStorageEndpoint || settings.objectStorageSandboxEndpoint) &&\n (!settings.objectStorageAccessKeyId || !settings.objectStorageSecretAccessKey)\n ) {\n throw new Error(\n \"S3-compatible object storage endpoints require OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID and OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY\",\n );\n }\n if (\n settings.objectStorageAzureConnectionString ||\n settings.objectStorageAzureAccountName ||\n settings.objectStorageAzureAccountKey ||\n settings.objectStorageAzureEndpoint\n ) {\n throw new Error(\n \"S3 object storage uses OPENGENI_OBJECT_STORAGE_* S3 settings, not OPENGENI_OBJECT_STORAGE_AZURE_* settings\",\n );\n }\n if (\n settings.objectStorageGcsProjectId ||\n settings.objectStorageGcsCredentialsJson ||\n settings.objectStorageGcsKeyFilename ||\n settings.objectStorageGcsApiEndpoint\n ) {\n throw new Error(\n \"S3 object storage uses OPENGENI_OBJECT_STORAGE_* S3 settings, not OPENGENI_OBJECT_STORAGE_GCS_* settings\",\n );\n }\n } else if (settings.objectStorageBackend === \"azure-blob\") {\n if (\n settings.objectStorageEndpoint ||\n settings.objectStorageSandboxEndpoint ||\n settings.objectStorageAccessKeyId ||\n settings.objectStorageSecretAccessKey\n ) {\n throw new Error(\n \"Azure Blob storage uses OPENGENI_OBJECT_STORAGE_AZURE_* settings, not S3-compatible object storage settings\",\n );\n }\n if (\n settings.objectStorageGcsProjectId ||\n settings.objectStorageGcsCredentialsJson ||\n settings.objectStorageGcsKeyFilename ||\n settings.objectStorageGcsApiEndpoint\n ) {\n throw new Error(\n \"Azure Blob storage uses OPENGENI_OBJECT_STORAGE_AZURE_* settings, not OPENGENI_OBJECT_STORAGE_GCS_* settings\",\n );\n }\n const hasConnectionString = Boolean(settings.objectStorageAzureConnectionString);\n const hasSharedKey =\n Boolean(settings.objectStorageAzureAccountName) &&\n Boolean(settings.objectStorageAzureAccountKey);\n if (!hasConnectionString && !hasSharedKey) {\n throw new Error(\n \"Azure Blob storage requires OPENGENI_OBJECT_STORAGE_AZURE_CONNECTION_STRING or OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_NAME plus OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_KEY\",\n );\n }\n } else {\n if (\n settings.objectStorageEndpoint ||\n settings.objectStorageSandboxEndpoint ||\n settings.objectStorageAccessKeyId ||\n settings.objectStorageSecretAccessKey\n ) {\n throw new Error(\n \"GCS object storage uses OPENGENI_OBJECT_STORAGE_GCS_* settings, not S3-compatible object storage settings\",\n );\n }\n if (\n settings.objectStorageAzureConnectionString ||\n settings.objectStorageAzureAccountName ||\n settings.objectStorageAzureAccountKey ||\n settings.objectStorageAzureEndpoint\n ) {\n throw new Error(\n \"GCS object storage uses OPENGENI_OBJECT_STORAGE_GCS_* settings, not OPENGENI_OBJECT_STORAGE_AZURE_* settings\",\n );\n }\n if (settings.objectStorageGcsCredentialsJson) {\n parseGcsCredentialsJson(settings.objectStorageGcsCredentialsJson);\n }\n }\n if (settings.documentChunkOverlap >= settings.documentChunkSize) {\n throw new Error(\n \"OPENGENI_DOCUMENT_CHUNK_OVERLAP must be smaller than OPENGENI_DOCUMENT_CHUNK_SIZE\",\n );\n }\n parseExposedPorts(settings.dockerExposedPorts);\n sandboxEnvironmentVariableNames(settings);\n sandboxLifecycleHookIds(settings);\n // Fail fast on a malformed warm-rate table (P2.1).\n parseSandboxWarmRateJson(settings.sandboxWarmRateMicrosPerSecondJson);\n const serverIds = new Set<string>();\n for (const server of settings.mcpServers) {\n if (serverIds.has(server.id)) {\n throw new Error(`OPENGENI_MCP_SERVERS contains duplicate id ${server.id}`);\n }\n serverIds.add(server.id);\n }\n // --- sandbox lease cadence invariant (fail fast at boot) ---\n // reaperPeriod (30s) < viewerHolderTTL (90s), and reaperPeriod + idleGrace must\n // be strictly less than the provider lifetime (modalTimeoutSeconds*1000):\n // - the reaper must run more often than the TTL it polices; and\n // - the reaper must terminate a genuinely-idle box (after the full drain grace,\n // observed on the NEXT sweep) BEFORE the provider's hard lifetime reclaims it\n // out from under us — the provider lifetime is the backstop, not the\n // warm-window controller. idleGrace counts from the user's last release;\n // the provider clock counts from the preceding resume, so we leave the\n // active-turn headroom in modalTimeoutSeconds (default 3600s).\n {\n const reaperPeriod = settings.sandboxLeaseReaperPeriodMs;\n const viewerTtl = settings.sandboxViewerHolderTtlMs;\n const idleGraceMs = settings.sandboxIdleGraceMs;\n const providerLifetimeMs = settings.modalTimeoutSeconds * 1000;\n // The EFFECTIVE box lifetime when it sits idle between turns is the Modal IDLE\n // timeout, NOT the hard lifetime (sandbox-file-persistence): a box with no\n // active connection is idle-reaped at idleTimeout. effectiveModalIdleTimeout\n // defaults to the hard lifetime (so the idle-reap never beats the OpenGeni\n // reaper), but an operator can pin it shorter — the invariants below bind the\n // reaper cadence + drain grace to the idle timeout (the REAL ceiling), so a\n // drained box always survives long enough for the reaper to snapshot it.\n const idleTimeoutMs = effectiveModalIdleTimeoutSeconds(settings) * 1000;\n if (!(reaperPeriod < viewerTtl)) {\n throw new Error(\n `OPENGENI_SANDBOX_LEASE_REAPER_PERIOD_MS (${reaperPeriod}) must be strictly less than ` +\n `OPENGENI_SANDBOX_VIEWER_HOLDER_TTL_MS (${viewerTtl}): the reaper must run more often ` +\n `than the TTL it polices, or stale viewer holders outlive a full reaper period.`,\n );\n }\n if (!(idleTimeoutMs <= providerLifetimeMs)) {\n throw new Error(\n `OPENGENI_MODAL_IDLE_TIMEOUT_SECONDS*1000 (${idleTimeoutMs}) must not exceed the hard provider ` +\n `lifetime (OPENGENI_MODAL_TIMEOUT_SECONDS*1000 = ${providerLifetimeMs}): the idle timeout is a ` +\n `floor under the hard lifetime, not above it.`,\n );\n }\n if (!(viewerTtl < idleTimeoutMs)) {\n throw new Error(\n `OPENGENI_SANDBOX_VIEWER_HOLDER_TTL_MS (${viewerTtl}) must be strictly less than the effective box ` +\n `idle timeout (${idleTimeoutMs}): a viewer holder must be reapable before the box idles out from ` +\n `under it (the provider idle-timeout is the backstop).`,\n );\n }\n if (!(reaperPeriod + idleGraceMs < idleTimeoutMs)) {\n throw new Error(\n `OPENGENI_SANDBOX_LEASE_REAPER_PERIOD_MS + OPENGENI_SANDBOX_IDLE_GRACE_MS ` +\n `(${reaperPeriod} + ${idleGraceMs} = ${reaperPeriod + idleGraceMs}) must be strictly less than the ` +\n `effective box idle timeout (${idleTimeoutMs}): a drained box must SURVIVE its full warm window so ` +\n `the reaper can resume + snapshot /workspace + terminate it on the sweep AFTER the drain grace ` +\n `elapses — Modal's idle-reap must NOT fire first (or /workspace is lost). Raise ` +\n `OPENGENI_MODAL_IDLE_TIMEOUT_SECONDS (defaults to OPENGENI_MODAL_TIMEOUT_SECONDS) or lower ` +\n `OPENGENI_SANDBOX_IDLE_GRACE_MS.`,\n );\n }\n }\n // --- stream-token secret: required-when-desktop, but GRACEFULLY DEGRADE (stream-token availability contract) ---\n // The desktop pixel plane needs an HMAC secret to mint scoped stream tokens.\n // It is REQUIRED when desktop is enabled — but per OD-8 a missing secret is NOT\n // a hard boot-fail: we emit a LOUD warning and the deployment ships with\n // DesktopStream.transport:null (resolveStreamTokenSecret returns undefined ->\n // negotiateCapabilities degrades the desktop cell). This keeps a desktop-\n // configured deployment bootable (headless + Channel-A still work) instead of\n // crashing the whole API on a missing secret.\n if (settings.sandboxDesktopEnabled && resolveStreamTokenSecret(settings) === undefined) {\n console.warn(\n \"[opengeni] OPENGENI_SANDBOX_DESKTOP_ENABLED=true but neither OPENGENI_STREAM_TOKEN_SECRET nor \" +\n \"OPENGENI_DELEGATION_SECRET is set: the desktop pixel plane will GRACEFULLY DEGRADE \" +\n \"(DesktopStream.transport=null — no scoped stream tokens can be minted). Set \" +\n \"OPENGENI_STREAM_TOKEN_SECRET to enable the live desktop stream.\",\n );\n }\n // Model provider registry: parse it here so JSON/zod errors surface at boot,\n // reject a registry id colliding with the built-in provider id (it would\n // shadow the built-in in configuredProviders), reject duplicate registry\n // ids, and require a resolvable API key for every registry provider (a\n // provider with no usable key can never serve a turn). Registry models flow\n // through configuredAllowedModels, so the managed-billing pricing check above\n // already covers them.\n const registryProviders = parseModelProvidersJson(settings.modelProvidersJson);\n const builtinId = builtinProviderId(settings);\n const providerIds = new Set<string>();\n for (const provider of registryProviders) {\n if (provider.id === builtinId) {\n throw new Error(\n `OPENGENI_MODEL_PROVIDERS_JSON provider id ${provider.id} collides with the built-in provider id`,\n );\n }\n if (providerIds.has(provider.id)) {\n throw new Error(\n `OPENGENI_MODEL_PROVIDERS_JSON contains duplicate provider id ${provider.id}`,\n );\n }\n providerIds.add(provider.id);\n if (!resolveProviderApiKey(provider)) {\n throw new Error(\n `OPENGENI_MODEL_PROVIDERS_JSON provider ${provider.id} requires a resolvable API key (set apiKey or apiKeyEnv)`,\n );\n }\n }\n // Materialize the normalized catalog at boot so canonical product ids,\n // aliases, definition digests, and capability/pricing normalization are\n // validated even when managed billing is disabled.\n configuredModels(settings);\n}\n\n/**\n * Resolve the secret used to sign/verify scoped stream tokens (sandbox contract\n * §C.3). Falls back to `delegationSecret` (the same HMAC envelope family —\n * `ogs_` vs `ogd_` prefix) so a deployment that already carries a delegation\n * secret does not need a second one. Returns undefined when neither is set,\n * which drives the graceful-degrade (DesktopStream.transport:null).\n */\nexport function resolveStreamTokenSecret(settings: Settings): string | undefined {\n const explicit = settings.streamTokenSecret?.trim();\n if (explicit) {\n return explicit;\n }\n const delegation = settings.delegationSecret?.trim();\n return delegation ? delegation : undefined;\n}\n\n/**\n * True iff the desktop pixel plane must GRACEFULLY DEGRADE because desktop is\n * enabled but no stream-token secret is resolvable (stream-token availability contract). When true,\n * negotiateCapabilities forces DesktopStream.transport:null.\n */\nexport function streamTokenDegraded(settings: Settings): boolean {\n return settings.sandboxDesktopEnabled && resolveStreamTokenSecret(settings) === undefined;\n}\n\n/**\n * Resolve the secret the control plane signs the enrollment bearer credential\n * with (the `oge_` envelope the agent presents back — M5). Falls\n * back to `delegationSecret` (the same HMAC envelope family) so a deployment that\n * already carries a delegation secret needs no second one. Returns undefined when\n * neither is set; when selfhosted is enabled but this is undefined, the poll route\n * reports the credential plane disabled (graceful degrade, never a 500). NEVER log\n * the returned value.\n */\nexport function resolveEnrollmentSigningSecret(settings: Settings): string | undefined {\n const explicit = settings.enrollmentSigningSecret?.trim();\n if (explicit) {\n return explicit;\n }\n const delegation = settings.delegationSecret?.trim();\n return delegation ? delegation : undefined;\n}\n\n/**\n * Resolve the HMAC secret the control plane signs the agent's relay PRODUCER token\n * with (the `ogr_` envelope; M8b). The RELAY verifies the producer\n * token with the SAME secret (injected into the relay via env). Prefers an explicit\n * `selfhostedRelayTokenSecret`, then the `streamTokenSecret` (the relay already\n * needs that one to verify the viewer's `ogs_` token, so a single secret can back\n * both planes), then `delegationSecret` (same HMAC family). Returns undefined when\n * none is set — the enrollment poll then returns an empty relayToken (graceful\n * degrade; the stream plane is unavailable until configured). NEVER log the value.\n */\nexport function resolveRelayTokenSecret(settings: Settings): string | undefined {\n const explicit = settings.selfhostedRelayTokenSecret?.trim();\n if (explicit) {\n return explicit;\n }\n const stream = settings.streamTokenSecret?.trim();\n if (stream) {\n return stream;\n }\n const delegation = settings.delegationSecret?.trim();\n return delegation ? delegation : undefined;\n}\n\n/**\n * The resolved NATS auth-callout responder config (M-AUTH). Present only when the\n * callout plane is FULLY configured: the account signing seed + the responder's own\n * login. When any piece is missing this returns null and the responder does not\n * start (selfhosted agents cannot connect — a graceful disabled state, never a boot\n * crash). The returned `accountSeed` is a secret; NEVER log it.\n */\nexport interface NatsCalloutConfig {\n /** The callout account SIGNING seed (`SA...`) — signs the user + response JWTs. */\n accountSeed: string;\n /** The target account NAME the user is placed into (the response `aud`). */\n accountName: string;\n /** The responder's NATS login (an `auth_callout.auth_users` user). */\n user: string;\n password: string;\n}\n\nexport function resolveNatsCalloutConfig(settings: Settings): NatsCalloutConfig | null {\n const accountSeed = settings.selfhostedNatsCalloutAccountSeed?.trim();\n const accountName = settings.selfhostedNatsCalloutAccountName?.trim() || \"APP\";\n const user = settings.selfhostedNatsCalloutUser?.trim();\n const password = settings.selfhostedNatsCalloutPassword?.trim();\n if (!accountSeed || !user || !password) {\n return null;\n }\n return { accountSeed, accountName, user, password };\n}\n\n/**\n * The PRIVILEGED control-plane NATS login (api/worker). Present only when BOTH a\n * user and password are set; otherwise null and the bus connects anonymously (local\n * dev / a NATS without auth_callout). When the callout plane is on, this is the\n * static account user permitted to request `agent.*.rpc`.\n */\nexport interface NatsControlPlaneAuth {\n user: string;\n password: string;\n}\n\nexport function resolveNatsControlPlaneAuth(settings: Settings): NatsControlPlaneAuth | null {\n const user = settings.selfhostedNatsControlUser?.trim();\n const password = settings.selfhostedNatsControlPassword?.trim();\n if (!user || !password) {\n return null;\n }\n return { user, password };\n}\n\nfunction splitCsv(raw: string): string[] {\n return raw\n .split(\",\")\n .map((value) => value.trim())\n .filter(Boolean);\n}\n\nfunction uniqueEnvNames(raw: string[], fieldName: string): string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const name of raw) {\n if (!envName.test(name)) {\n throw new Error(`${fieldName} contains invalid variable name ${name}`);\n }\n if (!seen.has(name)) {\n seen.add(name);\n out.push(name);\n }\n }\n return out;\n}\n\nfunction uniqueValues(raw: string[]): string[] {\n return [...new Set(raw.filter(Boolean))];\n}\n\nfunction parseGcsCredentialsJson(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`OPENGENI_OBJECT_STORAGE_GCS_CREDENTIALS_JSON must be valid JSON: ${message}`, {\n cause: error,\n });\n }\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,iDAAiD;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,kBAAkB;AAC3B,SAAS,SAAS;AAElB,IAAM,UAAU;AAChB,IAAM,aAAa;AACnB,IAAM,aAAa,EAAE,WAAW,CAAC,UAAU;AACzC,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO;AAAA,EACT;AACA,QAAM,aAAa,MAAM,KAAK,EAAE,YAAY;AAC5C,MAAI,CAAC,QAAQ,KAAK,OAAO,KAAK,IAAI,EAAE,SAAS,UAAU,GAAG;AACxD,WAAO;AAAA,EACT;AACA,MAAI,CAAC,SAAS,KAAK,MAAM,KAAK,KAAK,EAAE,SAAS,UAAU,GAAG;AACzD,WAAO;AAAA,EACT;AACA,SAAO;AACT,GAAG,EAAE,QAAQ,CAAC;AAEP,IAAM,6BAAiF;AAAA,EAC5F,MAAM;AAAA,IACJ,KAAK,CAAC;AAAA,IACN,OAAO,CAAC;AAAA,EACV;AAAA,EACA,OAAO;AAAA,IACL,KAAK;AAAA,MACH;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA,OAAO,CAAC,iBAAiB;AAAA,EAC3B;AAAA,EACA,QAAQ;AAAA,IACN,KAAK;AAAA,MACH;AAAA,MACA;AAAA,MACA;AAAA,MACA;AA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;AACpD;AAaO,SAAS,4BAA4B,UAAiD;AAC3F,QAAM,OAAO,SAAS,2BAA2B,KAAK;AACtD,QAAM,WAAW,SAAS,+BAA+B,KAAK;AAC9D,MAAI,CAAC,QAAQ,CAAC,UAAU;AACtB,WAAO;AAAA,EACT;AACA,SAAO,EAAE,MAAM,SAAS;AAC1B;AAEA,SAAS,SAAS,KAAuB;AACvC,SAAO,IACJ,MAAM,GAAG,EACT,IAAI,CAAC,UAAU,MAAM,KAAK,CAAC,EAC3B,OAAO,OAAO;AACnB;AAEA,SAAS,eAAe,KAAe,WAA6B;AAClE,QAAM,OAAO,oBAAI,IAAY;AAC7B,QAAM,MAAgB,CAAC;AACvB,aAAW,QAAQ,KAAK;AACtB,QAAI,CAAC,QAAQ,KAAK,IAAI,GAAG;AACvB,YAAM,IAAI,MAAM,GAAG,SAAS,mCAAmC,IAAI,EAAE;AAAA,IACvE;AACA,QAAI,CAAC,KAAK,IAAI,IAAI,GAAG;AACnB,WAAK,IAAI,IAAI;AACb,UAAI,KAAK,IAAI;AAAA,IACf;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,aAAa,KAAyB;AAC7C,SAAO,CAAC,GAAG,IAAI,IAAI,IAAI,OAAO,OAAO,CAAC,CAAC;AACzC;AAEA,SAAS,wBAAwB,KAAsB;AACrD,MAAI;AACF,WAAO,KAAK,MAAM,GAAG;AAAA,EACvB,SAAS,OAAO;AACd,UAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,UAAM,IAAI,MAAM,oEAAoE,OAAO,IAAI;AAAA,MAC7F,OAAO;AAAA,IACT,CAAC;AAAA,EACH;AACF;AAEA,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;","names":["provider"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import {\n BillingMode,\n CAPABILITY_DESCRIPTORS,\n Entitlements,\n EntitlementsMode,\n MAX_NESTED_AGENT_DEPTH,\n ProductAccessMode,\n ReasoningEffort,\n SandboxBackend,\n SessionMcpApprovalPolicy,\n StaticUsageLimits,\n TurnExecutionPolicyV1,\n UsageLimitsMode,\n type TurnExecutionModelSourceV1,\n type TurnExecutionReasoningSourceV1,\n} from \"@opengeni/contracts\";\nimport { CODEX_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS } from \"@opengeni/codex\";\nimport {\n CODEX_FALLBACK_MODEL_SLUGS,\n CODEX_MODEL_AUTO_COMPACT_TOKEN_LIMIT,\n CODEX_MODEL_CONTEXT_WINDOW_TOKENS,\n CODEX_MODEL_EFFECTIVE_CONTEXT_WINDOW_TOKENS,\n CODEX_MODEL_ID_PREFIX,\n CODEX_PROVIDER_BASE_URL,\n CODEX_PROVIDER_ID,\n} from \"@opengeni/codex/constants\";\nimport { createHash } from \"node:crypto\";\nimport { z } from \"zod\";\n\nconst envName = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst registryId = /^[A-Za-z0-9_-]+$/;\nconst EnvBoolean = z.preprocess((value) => {\n if (typeof value !== \"string\") {\n return value;\n }\n const normalized = value.trim().toLowerCase();\n if ([\"true\", \"1\", \"yes\", \"y\", \"on\"].includes(normalized)) {\n return true;\n }\n if ([\"false\", \"0\", \"no\", \"n\", \"off\"].includes(normalized)) {\n return false;\n }\n return value;\n}, z.boolean());\n\nexport const sandboxPreparationProfiles: Record<string, { env: string[]; hooks: string[] }> = {\n none: {\n env: [],\n hooks: [],\n },\n azure: {\n env: [\n \"ARM_CLIENT_ID\",\n \"ARM_CLIENT_SECRET\",\n \"ARM_TENANT_ID\",\n \"ARM_SUBSCRIPTION_ID\",\n \"AZURE_CLIENT_ID\",\n \"AZURE_CLIENT_SECRET\",\n \"AZURE_TENANT_ID\",\n \"AZURE_SUBSCRIPTION_ID\",\n \"AZURE_AUTHORITY_HOST\",\n ],\n hooks: [\"azure-cli-login\"],\n },\n github: {\n env: [\n \"GH_TOKEN\",\n \"GITHUB_TOKEN\",\n \"GIT_AUTHOR_NAME\",\n \"GIT_AUTHOR_EMAIL\",\n \"GIT_COMMITTER_NAME\",\n \"GIT_COMMITTER_EMAIL\",\n ],\n hooks: [],\n },\n};\n\n/**\n * Placeholder token inside an agent-instructions persona template. The runtime\n * substitutes the non-bypassable CORE (goal-loop ownership + the dynamic\n * workspace-environment block) at this marker. A template that omits the\n * marker still gets the CORE appended after it (a non-bypassable fail-safe),\n * so a white-labelled persona can never drop the goal-loop contract or the\n * environment metadata the agent depends on.\n */\nexport const AGENT_INSTRUCTIONS_CORE_PLACEHOLDER = \"{{core}}\";\n\n/**\n * Default per-workspace agent persona template. This is the BRAND + tool-usage\n * opinion (the white-labellable surface): the \"You are an OpenGeni workspace\n * agent.\" identity line, the framing/opinion lines, and the mount-path facts.\n *\n * The CORE that MUST survive any override — the goal-loop ownership line (which\n * names the opengeni__goal_* tools) and the dynamic workspace-environment block\n * — is injected at AGENT_INSTRUCTIONS_CORE_PLACEHOLDER by the runtime, never\n * baked into this overridable string.\n *\n * INVARIANT: with no per-workspace override and an empty environment, the\n * runtime's composed instructions are byte-for-byte pinned by a runtime test.\n * The template below is joined by \" \", followed by \" \" + the placeholder.\n * Changing a single character here changes that default; update the pin\n * intentionally.\n */\nexport const DEFAULT_AGENT_INSTRUCTIONS = [\n \"You are an OpenGeni workspace agent.\",\n \"Follow the user's task and any enabled pack or skill instructions for the current role.\",\n \"Work inside the sandbox workspace and use filesystem and shell tools when useful.\",\n \"Repository resources are mounted under repos/<host>/<owner>/<repo> unless the session specifies another collision-free mount path.\",\n \"File resources are mounted under files/<file-id>/ unless the session specifies another mount path.\",\n \"Attached files are mounted read-only; copy them before modifying.\",\n \"Bundled skills are under .agents/ and can include infrastructure, marketing, or other role-specific guidance.\",\n \"Use Checkov, Terraform, Azure CLI, git provider CLIs, and repository tools when relevant; gh, glab, and az repos are pre-authenticated when the host brokers matching git credentials.\",\n \"When the Azure sandbox preparation profile is enabled and service-principal variables are present, the sandbox is pre-authenticated with normal Azure CLI before work starts.\",\n \"Treat code-changing work as GitOps work: create a focused branch/commit/PR when git provider credentials are available; otherwise report exact commands and blockers.\",\n \"Return concise, factual summaries with files changed, commands run, and remaining blockers.\",\n AGENT_INSTRUCTIONS_CORE_PLACEHOLDER,\n].join(\" \");\n\nexport const McpServerConnectionRefSchema = z\n .object({\n // Standalone ids are UUIDs; embedded hosts may use any stable opaque id.\n connectionId: z.string().min(1).optional(),\n provider: z.string().min(1).max(128).optional(),\n providerDomain: z.string().min(1),\n kind: z.enum([\"oauth2\", \"api_key\", \"app_install\", \"delegated\"]).optional(),\n scopes: z.array(z.string().min(1)).optional(),\n resource: z.string().min(1).optional(),\n selectedResources: z\n .array(\n z\n .object({\n id: z.string().min(1).max(512),\n kind: z.literal(\"repository\"),\n })\n .strict(),\n )\n .min(1)\n .max(256)\n .superRefine((resources, context) => {\n const seen = new Set<string>();\n for (const [index, resource] of resources.entries()) {\n const key = `${resource.kind}\\0${resource.id}`;\n if (seen.has(key)) {\n context.addIssue({\n code: \"custom\",\n message: \"selectedResources must not contain duplicates\",\n path: [index],\n });\n }\n seen.add(key);\n }\n })\n .optional(),\n subjectScope: z.enum([\"workspace\", \"subject\"]).optional(),\n })\n .strict()\n .superRefine((reference, context) => {\n if (!reference.selectedResources) return;\n if (!reference.connectionId) {\n context.addIssue({\n code: \"custom\",\n message: \"selectedResources requires connectionId\",\n path: [\"connectionId\"],\n });\n }\n if (!reference.provider) {\n context.addIssue({\n code: \"custom\",\n message: \"selectedResources requires provider\",\n path: [\"provider\"],\n });\n }\n });\nexport type McpServerConnectionRef = z.infer<typeof McpServerConnectionRefSchema>;\n\nconst SettingsSchema = z.object({\n serviceName: z.string().default(\"opengeni\"),\n environment: z.string().default(\"local\"),\n deploymentRevision: z.string().default(\"dev\"),\n // The release-train version baked into official images (OPENGENI_SERVER_VERSION).\n // Absent on dev/source builds — consumers must treat it as optional.\n serverVersion: z.string().optional(),\n databaseUrl: z.string().default(\"postgres://opengeni:opengeni@127.0.0.1:5432/opengeni\"),\n // Step I (§7.8 runtime half). Dedicated Postgres schema for the EMBEDDED\n // topology. Default \"\" → standalone: no search_path scoping, server default\n // (`public`). When set (e.g. \"opengeni\"), the db handle + the managed-auth\n // pool send `search_path = \"<dbSchema>\",\"opengeni_private\",\"public\"` so every\n // query resolves into the dedicated schema with NO query rewrite (schema-isolation contract F1).\n dbSchema: z.string().default(\"\"),\n // Step I (§7.7). RLS posture. \"force\" (default) = today's FORCE-RLS via the\n // non-owner `opengeni_app` role. \"scoped\" = the embedded owner-role path (the\n // GUC is still emitted defensively, so the query path is identical).\n rlsStrategy: z.enum([\"force\", \"scoped\"]).default(\"force\"),\n // Exact PostgreSQL login identity required by the standalone FORCE-RLS\n // startup/readiness assertion. Embedded `scoped` hosts own their role model\n // and are deliberately not constrained to this name.\n runtimeDatabaseRole: z.string().min(1).default(\"opengeni_app\"),\n natsUrl: z.string().default(\"nats://127.0.0.1:4222\"),\n temporalHost: z.string().default(\"127.0.0.1:7233\"),\n temporalNamespace: z.string().default(\"default\"),\n temporalTaskQueue: z.string().default(\"opengeni-runs-ts\"),\n temporalTlsEnabled: EnvBoolean.default(false),\n temporalApiKey: z.string().optional(),\n temporalTlsServerName: z.string().optional(),\n temporalTlsRootCaCertificateBase64: z.string().optional(),\n temporalTlsClientCertificateBase64: z.string().optional(),\n temporalTlsClientPrivateKeyBase64: z.string().optional(),\n startupDependencyRetryAttempts: z.coerce.number().int().positive().default(30),\n startupDependencyRetryInitialDelayMs: z.coerce.number().int().positive().default(1000),\n startupDependencyRetryMaxDelayMs: z.coerce.number().int().positive().default(5000),\n turnWorkerConcurrencyMode: z.enum([\"fixed\", \"resource-based\"]).default(\"fixed\"),\n turnWorkerMaxConcurrentTurns: z.coerce.number().int().positive().max(2_000).default(16),\n turnWorkerTargetCpuUsage: z.coerce.number().positive().max(1).default(0.8),\n turnWorkerTargetMemoryUsage: z.coerce.number().positive().max(0.8).default(0.75),\n observabilityStructuredLogs: EnvBoolean.default(false),\n observabilityMetricsEnabled: EnvBoolean.default(true),\n observabilityOtlpEndpoint: z.string().url().optional(),\n observabilityOtlpHeaders: z.string().default(\"\"),\n publicBaseUrl: z.string().url().optional(),\n // Base URL for the bring-your-own-compute agent release assets the get.<domain>\n // install routes redirect to. Defaults to this repo's GitHub Releases. The route\n // appends `/download/agent-v<ver>/<asset>`.\n agentReleasesBaseUrl: z\n .string()\n .url()\n .default(\"https://github.com/Cloudgeni-ai/opengeni/releases\"),\n // Explicit operator-controlled promotion pointer for `/agent/latest/*`.\n // Versioned agent releases are immutable; changing this setting promotes or\n // rolls back the stable channel without moving or deleting a provider tag.\n agentStableVersion: z\n .string()\n .regex(/^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)$/u)\n .default(\"0.1.8\"),\n productAccessMode: ProductAccessMode.default(\"local\"),\n billingMode: BillingMode.default(\"disabled\"),\n entitlementsMode: EntitlementsMode.default(\"none\"),\n usageLimitsMode: UsageLimitsMode.default(\"none\"),\n staticEntitlementsJson: z.string().default(\"{}\"),\n staticUsageLimitsJson: z.string().default(\"{}\"),\n delegationSecret: z.string().optional(),\n // sandbox workspace scoped stream-token HMAC secret (sandbox contract §C.3 / stream-token availability contract).\n // When unset, the API falls back to `delegationSecret` (the same HMAC envelope\n // family, `ogs_` vs `ogd_` prefix). REQUIRED-WHEN-DESKTOP, but the absence of\n // BOTH while sandboxDesktopEnabled=true is a GRACEFUL DEGRADE (DesktopStream\n // transport:null + a loud boot warning), NOT a hard boot-fail (stream-token availability contract).\n streamTokenSecret: z.string().optional(),\n // The desktop input plane (raw stream:control writes) is OFF in v1: even a\n // holder of stream:control gets 403 until this flips. Keeps stream:control a\n // declared-but-inert permission so later hardening is a flag flip.\n streamControlEnabled: EnvBoolean.default(false),\n // Existing-session explicit tool replacement is gated until every API and\n // worker instance understands durable tools_provided provenance.\n sessionTurnToolReplacementEnabled: EnvBoolean.default(false),\n toolspaceEnabled: EnvBoolean.default(false),\n toolspaceMaxCallsPerTurn: z.coerce.number().int().positive().default(200),\n // Optional release-coherent bootstrap hint for custom rigs/connected machines\n // that do not carry the stock-image ogtool binary. Exact stable versions only:\n // the agent must never guess a tag or silently install `latest`.\n ogtoolPackageSpec: z\n .string()\n .regex(/^@opengeni\\/ogtool@(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)$/u)\n .optional(),\n environmentsEncryptionKey: z.string().optional(),\n integrationsEnabled: EnvBoolean.default(false),\n integrationsStateSecret: z.string().optional(),\n integrationsAllowPrivateNetworkTargets: EnvBoolean.default(false),\n integrationsOauthClientsJson: z.string().default(\"{}\"),\n // Undefined is meaningful: the migration boundary persists the product\n // default of 3 when no deployment override is supplied.\n maxNestedAgentDepth: z.coerce.number().int().nonnegative().max(MAX_NESTED_AGENT_DEPTH).optional(),\n // Session goal guard rails. Goals are designed for runs that legitimately\n // span days, so length is bounded by pathology detection (no-progress\n // streaks, budget exhaustion), never by count. goalMaxAutoContinuations is\n // therefore UNSET by default (no cap); deployments may configure one, and\n // it then acts as a hard ceiling that per-goal overrides can only lower.\n goalMaxAutoContinuations: z.coerce.number().int().positive().optional(),\n goalNoProgressLimit: z.coerce.number().int().positive().default(3),\n // Per-segment ceiling on agent loop turns (model calls) within a single\n // session turn. Effectively unbounded by default for the same reason as\n // above; the graceful max-turns valve (idle + goal continuation, never a\n // session failure) remains as inert safety should a deployment set a cap.\n agentMaxModelCallsPerTurn: z.coerce.number().int().positive().default(1_000_000),\n // The model family's real context window in tokens. OpenGeni always performs\n // one durable, portable plaintext compaction transition; there is no\n // provider/server/off mode ladder.\n contextWindowTokens: z.coerce.number().int().positive().default(1_050_000),\n // Optional model-catalog effective input ceiling. Codex models expose this as\n // raw context_window * effective_context_window_percent; when absent, retain\n // the deployment-level window-minus-reserved-output behavior.\n contextEffectiveWindowTokens: z.coerce.number().int().positive().optional(),\n // Proactive compaction threshold as a ratio of the model context window.\n // Defaults to 90%: compact as late as possible — retained context beats early\n // headroom now that per-model windows are declared honestly (input-effective,\n // empirically measured), and the fail-closed reactive compact-on-reject path\n // absorbs any overshoot as one retried call rather than a dead session.\n // Clamped to [0.3, 0.9] so deployments can tune the trigger without\n // accidentally disabling compaction.\n contextCompactionThresholdRatio: z.coerce\n .number()\n .default(0.9)\n .transform((value) => {\n if (!Number.isFinite(value)) {\n return 0.9;\n }\n return Math.min(0.9, Math.max(0.3, value));\n }),\n // Tokens reserved for model output; subtracted from the window to get the\n // usable input budget B = contextWindowTokens - contextReservedOutputTokens.\n contextReservedOutputTokens: z.coerce.number().int().nonnegative().default(128_000),\n // Model-catalog auto-compact limit. When present it is clamped to\n // 90% of the raw window, matching Codex core's auto_compact_token_limit().\n contextAutoCompactThresholdTokens: z.coerce.number().int().positive().optional(),\n // Provider-neutral fallback for canonical model-facing tool-result text.\n // The current stable Codex catalog policy is 10k tokens; the truncator adds\n // Codex's 1.2x JSON serialization allowance when applying it.\n modelToolOutputTruncationTokens: z.coerce.number().int().positive().default(10_000),\n authRequired: EnvBoolean.default(false),\n accessKey: z.string().optional(),\n authAllowHealth: EnvBoolean.default(true),\n authAllowMetrics: EnvBoolean.default(false),\n apiHost: z.string().default(\"0.0.0.0\"),\n apiPort: z.coerce.number().int().positive().default(8000),\n workerHttpPort: z.coerce.number().int().positive().default(8001),\n opengeniMcpUrl: z.string().url().optional(),\n corsAllowOriginRegex: z.string().default(String.raw`^https?://(localhost|127\\.0\\.0\\.1)(:\\d+)?$`),\n openaiProvider: z.enum([\"openai\", \"azure\"]).default(\"openai\"),\n openaiApiKey: z.string().optional(),\n openaiBaseUrl: z.string().optional(),\n openaiModel: z.string().default(\"gpt-5.6-sol\"),\n openaiAllowedModels: z.string().default(\"gpt-5.6-sol,gpt-5.6-terra,gpt-5.6-luna\"),\n modelPricingJson: z.string().default(\"{}\"),\n // Extra (non-built-in) model providers, declared by the host as a JSON\n // provider registry. Each entry carries its own base URL, API key, wire API\n // (\"responses\" | \"chat\") and the models it exposes. The models a client may\n // use are the UNION of the built-in provider's allowed models and every\n // registry provider's models. validateSettings parses this at boot so a\n // malformed registry / unresolvable key / id collision fails fast.\n modelProvidersJson: z.string().default(\"[]\"),\n // Codex (ChatGPT) subscription: when enabled, a per-workspace connected\n // subscription is injected as a synthetic \"codex-subscription\" registry\n // provider whose models route through the ChatGPT backend (@opengeni/codex).\n codexSubscriptionEnabled: EnvBoolean.default(false), // OPENGENI_CODEX_SUBSCRIPTION_ENABLED\n // Expose the connected apps attached to a Codex subscription through the\n // synthetic codex_apps MCP server. Independent from subscription routing so\n // operators can use Codex models without exposing ChatGPT connectors.\n codexConnectedAppsEnabled: EnvBoolean.default(false), // OPENGENI_CODEX_CONNECTED_APPS_ENABLED\n codexProductSku: z.string().optional(), // OPENGENI_CODEX_PRODUCT_SKU (X-OpenAI-Product-Sku, apps only)\n // Progressive MCP disclosure (Codex-CLI-style tool_search): on a codex turn,\n // flag non-mandatory selected MCP tools `defer_loading:true` (dropping their\n // schemas from model context) and add one client-executed tool_search tool\n // that BM25-discloses bounded matches. The mandatory OpenGeni tools stay\n // eager. Default OFF — a codex turn is byte-for-byte unchanged until enabled.\n // OPENGENI_CODEX_TOOL_SEARCH_ENABLED\n codexToolSearchEnabled: EnvBoolean.default(false),\n // credential allocator atomic, workspace-local credential allocation. Default OFF is a\n // deliberate rolling-deploy fence: migrate + roll every worker first, then\n // enable. Turning it off restores the legacy sticky selector without a schema\n // rollback; the additive lease table/cursor columns become inert.\n codexCredentialLeasingEnabled: EnvBoolean.default(false),\n // Decision-observability fence. When enabled, the worker emits one\n // bounded, metadata-only adaptive-policy replay record alongside the unchanged\n // sticky-sharded decision. It never changes placement/admission/failover.\n codexFleetPolicyShadowEnabled: EnvBoolean.default(false),\n // Multi-account P3 (auto-rotation): an account is \"near exhaustion\" — ineligible to be\n // rotated TO — when EITHER usage window (5h/weekly) is at/over this percent. Default 90 to\n // match the UI danger flip (UsageBar danger at pct >= 90). OPENGENI_CODEX_ROTATION_NEAR_EXHAUSTION_PCT.\n codexRotationNearExhaustionPct: z.coerce.number().int().min(1).max(100).default(90),\n openaiReasoningEffort: ReasoningEffort.default(\"low\"),\n openaiAllowedReasoningEfforts: z.string().default(\"low,medium,high,xhigh\"),\n openaiResponsesTransport: z.enum([\"http\", \"websocket\"]).default(\"http\"),\n // Provider-assigned item ids (rs_/msg_/fc_…) in Responses API input are\n // resolved against the provider's server-side response store. That store is\n // not durable enough to anchor long runs on: a response that streamed fine\n // can be missing from the store on the very next model call, which then\n // fails with 400 \"Item with id ... not found\". \"strip\" removes the ids from\n // every model-call input so requests are self-contained — conversation\n // truth already lives client-side in session_history_items. \"preserve\"\n // keeps the SDK's pass-through behavior.\n openaiProviderItemIds: z.enum([\"strip\", \"preserve\"]).default(\"strip\"),\n // With ids stripped the provider cannot resolve prior reasoning server-side,\n // so request reasoning.encrypted_content and send it back with each call:\n // reasoning continuity without depending on provider-side storage.\n openaiReasoningEncryptedContent: EnvBoolean.default(true),\n // Model-call retry budget for transient provider failures (429s and friends).\n // The openai client default of 2 retries is too small for sustained TPM\n // backpressure during long autonomous runs.\n openaiMaxRetries: z.coerce.number().int().nonnegative().default(5),\n // Native hosted web search. The live Azure Responses path executes the\n // hosted web_search tool, so this is provider-unconditional: ON by default\n // on every provider, exposed only so operators can disable it. When true,\n // buildOpenGeniAgent attaches webSearchTool() to the agent's tools — it is\n // merged with the MCP-server tools (getAllTools = [...mcpTools, ...tools])\n // and the sandbox capability tools, never replacing them.\n webSearchEnabled: EnvBoolean.default(true),\n // Deployment-default agent persona template (the white-label surface). The\n // runtime resolves the effective template per turn as\n // per-session-override > per-workspace override > this default, substitutes\n // the non-bypassable CORE at AGENT_INSTRUCTIONS_CORE_PLACEHOLDER (or appends\n // it when the template omits the marker), and uses the result as the agent's\n // instructions. Defaulting to DEFAULT_AGENT_INSTRUCTIONS keeps the composed\n // default pinned by runtime tests.\n agentInstructionsTemplate: z.string().default(DEFAULT_AGENT_INSTRUCTIONS),\n azureOpenaiBaseUrl: z.string().optional(),\n azureOpenaiEndpoint: z.string().optional(),\n azureOpenaiDeployment: z.string().optional(),\n azureOpenaiApiVersion: z.string().optional(),\n azureOpenaiApiKey: z.string().optional(),\n azureOpenaiAdToken: z.string().optional(),\n disableOpenaiTracing: EnvBoolean.default(false),\n sandboxBackend: SandboxBackend.default(\"docker\"),\n dockerImage: z.string().default(\"opengeni-sandbox:local\"),\n dockerExposedPorts: z.string().default(\"\"),\n dockerNetwork: z.string().optional(),\n modalAppName: z.string().default(\"opengeni-sandbox\"),\n modalImageRef: z.string().optional(),\n // Name of a Modal Secret (containing REGISTRY_USERNAME + REGISTRY_PASSWORD) used\n // to authenticate the pull of `modalImageRef` from a PRIVATE registry. When UNSET\n // (the default), the sandbox image is pulled UNAUTHENTICATED — i.e. it must be a\n // PUBLIC registry tag, which is the only shape the Agents-extension Modal backend\n // supports out of the box (`Image.fromRegistry(tag)` with no secret). Set this to\n // run a private image (e.g. a cloud-hosted ACR/ECR/GCR digest): the runtime resolves\n // the named Secret and builds the image via `fromRegistry(tag, secret)` before the\n // first sandbox is created. Knob: OPENGENI_MODAL_IMAGE_REGISTRY_SECRET.\n modalImageRegistrySecret: z.string().optional(),\n // Modal's hard sandbox lifetime (timeoutMs = this * 1000), counted from each\n // create/resume — it is the BACKSTOP that reclaims a box if the reaper/worker is\n // down, NOT the warm-window controller (that's sandboxIdleGraceMs). It must\n // comfortably exceed reaperPeriod + idleGrace so the reaper terminates a\n // genuinely-idle box FIRST; the boot invariant below enforces that. Default 1h\n // (was 900s/15min): the 15-min drain grace counts from the user's LAST release,\n // but Modal's clock starts at the preceding turn's resume — so a 15-min grace on\n // top of a 900s lifetime would let Modal kill the box mid-warm-window. 3600s\n // leaves ~45min of headroom for the active turn before the warm window opens.\n // Knob: OPENGENI_MODAL_TIMEOUT_SECONDS.\n modalTimeoutSeconds: z.coerce.number().int().positive().default(3600),\n modalTokenId: z.string().optional(),\n modalTokenSecret: z.string().optional(),\n modalEnvironment: z.string().optional(),\n // modal gap-fill: idleTimeoutMs + workspacePersistence were unmapped (module 03 §4.1).\n //\n // CRITICAL (sandbox-file-persistence): when this is UNSET the Modal SDK sends\n // idleTimeoutSecs=undefined, so Modal applies its OWN short server-default idle\n // timeout (~minutes) — and a box between turns sits with NO active connection,\n // so that idle clock runs and Modal idle-reaps the box LONG before OpenGeni's\n // own reaper waits out sandboxIdleGraceMs (15min) to resume+persist+terminate\n // it. The observed failure: every drain logs \"drainable box already gone\n // (NotFound on resume)\", persistWorkspace() never fires, /workspace is lost.\n // Modal's idle-reap is a SECOND reaper racing OpenGeni's — and it wins. The fix:\n // OpenGeni OWNS box lifecycle via its reaper + the hard modalTimeoutSeconds\n // backstop, so the Modal idle-reap must NOT fire first. We default the effective\n // idle timeout to the hard lifetime (effectiveModalIdleTimeoutSeconds), making\n // the box survive its full warm window so the reaper can snapshot it. Set this\n // explicitly (OPENGENI_MODAL_IDLE_TIMEOUT_SECONDS) only to deliberately idle-reap\n // SOONER than the hard lifetime; the boot invariant forbids a value that would\n // reap before reaperPeriod + idleGrace elapses.\n modalIdleTimeoutSeconds: z.coerce.number().int().positive().optional(),\n // /workspace FILE PERSISTENCE across warm/cold cycles. Defaults to\n // `snapshot_filesystem` so EVERY box is created persistence-capable: the reaper\n // snapshots the live box before it terminates a drained group, and a later\n // cold-restore hydrates a fresh box from that snapshot (sandbox-file-persistence).\n // `snapshot_filesystem` requires the manifest declare NO ephemeralPersistencePaths\n // (buildManifest never sets entry.ephemeral, so it never downgrades to tar). Set\n // OPENGENI_MODAL_WORKSPACE_PERSISTENCE=tar to opt back out (no native snapshot;\n // the reaper persists a tar archive — same store+hydrate plumbing, slower).\n modalWorkspacePersistence: z\n .enum([\"tar\", \"snapshot_filesystem\", \"snapshot_directory\"])\n .default(\"snapshot_filesystem\"),\n // Snapshot GC backstop (sandbox-file-persistence): the reaper keeps ONE latest\n // filesystem snapshot per lease (delete-prior-on-supersede + delete-on-teardown).\n // This is the TTL retention floor for the periodic orphan sweep — a snapshot\n // whose lease is cold and older than this is best-effort deleted so a crashed\n // persist-then-no-restore never leaks a Modal image. 0 disables the TTL sweep\n // (delete-on-supersede/teardown still run). Default 7 days.\n modalSnapshotRetentionSeconds: z.coerce.number().int().nonnegative().default(604_800),\n // Shared desktop toggle: this module reads it for the 6080 port-merge; the\n // owner module (P4.x) acts on it to launch the display stack.\n sandboxDesktopEnabled: EnvBoolean.default(false),\n // Human take-control toggle: when ON (default) the negotiated DesktopStream\n // cell advertises mode \"interactive\" — the noVNC viewer can drive mouse+keyboard\n // into :0 (x11vnc runs without -viewonly). Turn it OFF for a genuinely read-only\n // deployment: the cell reports mode \"read-only\" and the client disables the\n // \"Take control\" affordance. Independent of computerUseReadOnly (the AGENT\n // driver); this gates the HUMAN viewer plane.\n sandboxDesktopInteractive: EnvBoolean.default(true),\n // REAL PTY terminal toggle (P5.t): gates the ttyd pty-ws plane (7681) the API\n // mints over the SAME tunnel as the desktop. Defaults ON — the interactive\n // terminal is a baseline structured-service surface (unlike the heavier desktop\n // pixel plane); a deployment can turn it off to fall back to the read-only\n // sse-events command firehose. The 7681 port-merge tracks sandboxDesktopEnabled\n // (a desktop-capable image is the one that bakes ttyd).\n sandboxTerminalEnabled: EnvBoolean.default(true),\n // The desktop framebuffer geometry the pixel plane advertises + launches the\n // display stack with (P4.2). v1 has no live RANDR resize; a change is a full\n // down→up restart. Defaults match the proven spike geometry (1280x800).\n streamResolutionWidth: z.coerce.number().int().positive().default(1280),\n streamResolutionHeight: z.coerce.number().int().positive().default(800),\n // P4.3 computer-use: the agent drives the SAME :0 humans watch (xdotool/XTEST +\n // scrot). Gated by sandboxDesktopEnabled + a desktop-capable backend in\n // buildAgentCapabilities; computerUseReadOnly:false is the agent-driver default\n // (it must click/type — the human viewer plane is the read-only one).\n computerUseEnabled: EnvBoolean.default(true),\n computerUseReadOnly: EnvBoolean.default(false),\n // P4.3 recording loop: ffmpeg x11grab of :0 → mp4/webm → @opengeni/storage.\n // recordingMaxBytes caps the in-memory finalize buffer (≤ storage single-PUT);\n // recordingMaxSeconds is the ffmpeg -t hard ceiling (bounds a multi-day turn).\n recordingEnabled: EnvBoolean.default(true),\n recordingDefaultCodec: z.enum([\"h264-mp4\", \"vp9-webm\"]).default(\"h264-mp4\"),\n // Workbench v2 turn-end workspace capture. When on, the turn\n // activity probes the box's changed files off the live box at turn end and\n // persists a capture revision (blobs in @opengeni/storage) so the workbench\n // paints cold/offline sessions with zero machine round-trips. Best-effort and\n // fully behind this flag: off ⇒ capture is skipped and reads fall back to the\n // live/wake path (status-quo behavior). Default on; explicit per environment.\n workspaceCaptureEnabled: EnvBoolean.default(true),\n recordingFramerate: z.coerce.number().int().positive().default(15),\n recordingMaxSeconds: z.coerce.number().int().positive().default(600),\n recordingMaxBytes: z.coerce.number().int().positive().default(268_435_456), // 256 MB\n // --- daytona ---\n daytonaApiKey: z.string().optional(),\n daytonaApiUrl: z.string().url().optional(),\n daytonaTarget: z.string().optional(),\n daytonaImage: z.string().optional(),\n daytonaSnapshotName: z.string().optional(),\n daytonaAutoStopInterval: z.coerce.number().int().nonnegative().optional(), // 0 disables idle-kill\n daytonaTimeoutSeconds: z.coerce.number().int().positive().optional(),\n daytonaExposedPortUrlTtlSeconds: z.coerce.number().int().positive().optional(),\n // --- runloop ---\n runloopApiKey: z.string().optional(),\n runloopBaseUrl: z.string().url().optional(),\n runloopBlueprintName: z.string().optional(),\n runloopBlueprintId: z.string().optional(),\n runloopTunnel: EnvBoolean.default(true),\n runloopKeepAliveSeconds: z.coerce.number().int().positive().optional(),\n // --- e2b (SDK reads E2B_API_KEY from env; mirrored for validation + forwarding) ---\n e2bApiKey: z.string().optional(),\n e2bTemplate: z.string().optional(),\n e2bTimeoutSeconds: z.coerce.number().int().positive().optional(),\n e2bTimeoutAction: z.enum([\"pause\", \"kill\"]).optional(),\n e2bAllowInternetAccess: EnvBoolean.optional(),\n e2bAutoResume: EnvBoolean.optional(),\n e2bWorkspacePersistence: z.enum([\"tar\", \"snapshot\"]).optional(),\n // --- blaxel ---\n blaxelApiKey: z.string().optional(),\n blaxelImage: z.string().optional(),\n blaxelRegion: z.string().optional(),\n blaxelExposedPortPublic: EnvBoolean.optional(), // public vs bl_preview_token\n blaxelExposedPortUrlTtlSeconds: z.coerce.number().int().positive().optional(),\n blaxelMemoryMb: z.coerce.number().int().positive().optional(),\n blaxelTtl: z.string().optional(),\n // --- cloudflare (headless) ---\n cloudflareWorkerUrl: z.string().url().optional(),\n cloudflareApiKey: z.string().optional(),\n // --- vercel (headless) ---\n vercelToken: z.string().optional(),\n vercelProjectId: z.string().optional(),\n vercelTeamId: z.string().optional(),\n vercelRuntime: z.string().optional(),\n // --- sandbox ownership inversion (P1.2 rollout flag, default OFF) ---\n // The keystone flag for the stateless resume-by-id model. When FALSE the\n // agent-turn path is BYTE-FOR-BYTE today's build-and-discard behavior (no\n // lease acquire, no resume-by-id, no non-owned injection). When TRUE the turn\n // activity acquires the group lease, resumes the one box by id from the lease\n // envelope, injects it as a NON-OWNED RunConfig session (the SDK never reaps\n // it — the proven keystone), and releases the holder in finally. Uses\n // EnvBoolean (NOT z.coerce.boolean(), which would coerce \"false\" -> true and\n // turn the flag ON the moment anyone set the env var to disable it).\n sandboxOwnershipEnabled: EnvBoolean.default(false),\n // --- standalone rig-verifier ownership rollout flag, default OFF ---\n // Rig verification creates a throwaway provider sandbox outside the normal\n // session-turn path. When enabled, that sandbox must first acquire the same\n // durable lease lifecycle used by session boxes so the global orphan sweep\n // recognizes its exact provider instance. Keep this separate from the general\n // sandboxOwnershipEnabled rollout: every reaper worker must understand verifier\n // leases before dispatch is enabled. When false the verifier fails closed before\n // provider create; it never falls back to the legacy unowned path.\n rigVerificationLeaseOwnershipEnabled: EnvBoolean.default(false),\n // --- lazy sandbox provisioning rollout flag, default OFF ---\n // Only effective when sandboxOwnershipEnabled is ALSO on (lazy provisioning is a\n // property of the owned path — the SDK never creates/resumes an injected session,\n // so we control when the box is established). When TRUE, a turn does NOT provision\n // its box at turn start: the lease acquire + resume-by-id + hooks + downloads +\n // heartbeat + recording are deferred to an in-process single-flight provisioner\n // that runs the FIRST time a sandbox op is dispatched (via the routing proxy's\n // resolveActiveBackend). A turn whose model never calls a sandbox-backed tool ends\n // with NO lease row and ZERO warm-seconds. When FALSE (or ownership off) the turn\n // provisions eagerly exactly as today — byte-for-byte. EnvBoolean (NOT\n // z.coerce.boolean(), which coerces \"false\" -> true and would turn the flag ON the\n // moment anyone set the env var to disable it).\n sandboxLazyProvisionEnabled: EnvBoolean.default(false),\n // --- bring-your-own-compute (selfhosted 11th backend) rollout flag, default OFF ---\n // The keystone flag for the whole selfhosted feature (the enrollment device-flow,\n // the NATS control plane, the relay stream tier). When FALSE the enrollment routes\n // 404 (invisible — the surface does not exist for this deployment) and the\n // selfhosted backend is inert; boot is unaffected. EnvBoolean (NOT\n // z.coerce.boolean(), which coerces \"false\" -> true). Flipped per-environment via\n // the deploy-staging IaC secret/configmap pattern.\n sandboxSelfhostedEnabled: EnvBoolean.default(false),\n // Gates the op-stream (streaming exec) transport to Connected Machines. The\n // runner must ALSO advertise Capabilities.op_stream; default off, and legacy\n // request/reply exec is the permanent fallback. EnvBoolean (NOT\n // z.coerce.boolean(), which coerces \"false\" -> true).\n agentOpStreamEnabled: EnvBoolean.default(false),\n // The HMAC secret the control plane signs the enrollment bearer credential with\n // (the `oge_` envelope the agent presents back to the control plane). Optional:\n // when ABSENT and sandboxSelfhostedEnabled is on, the poll route reports the\n // credential plane disabled (graceful degrade, mirrors streamTokenSecret). NEVER\n // logged. Lives in the opengeni-runtime secret (Helm-clobbered configmap avoided).\n enrollmentSigningSecret: z.string().optional(),\n // Connect-info the EnrollmentCredentials hand the agent: the NATS server URL(s)\n // the agent dials for the control plane, and the relay edge base URL for streams.\n // The per-workspace NATS Account creds binding is infra-deferred (M4/relay\n // milestone) — the poll returns these endpoints + a placeholder creds field.\n selfhostedNatsUrl: z.string().optional(),\n selfhostedRelayUrl: z.string().optional(),\n // The HMAC secret the control plane signs the agent's relay PRODUCER token with\n // (the `ogr_` envelope threaded into EnrollmentCredentials.relayToken; M8b/design\n // §10.5). The relay verifies the producer token with the SAME secret. Optional:\n // when ABSENT the poll returns an empty relayToken (graceful degrade — the stream\n // plane is simply unavailable until configured). Falls back to streamTokenSecret /\n // delegationSecret (same HMAC family) so a deployment with a stream-token secret\n // needs no second one. NEVER logged. Lives in the opengeni-runtime secret.\n selfhostedRelayTokenSecret: z.string().optional(),\n // The minisign PUBLIC key the agent pins for self-update verification (handed to\n // the agent in EnrollmentCredentials; the SECRET key lives only in CI).\n agentUpdatePublicKey: z.string().optional(),\n // --- NATS auth-callout tenancy boundary (bring-your-own-compute M-AUTH; design\n // §10.1 NATS Accounts per workspace + §17 the isolation smoke) -------------\n // nats-server is configured with AUTH CALLOUT: an external agent connects\n // presenting its `oge_` enrollment bearer as the connect auth-token; the server\n // issues an authorization request on $SYS.REQ.USER.AUTH to our responder, which\n // validates the bearer and returns a SIGNED NATS user JWT scoped to pub/sub ONLY\n // `agent.<ws>.>` (+ `_INBOX.>`). That per-subject scope IS the per-workspace\n // isolation. These are deployment-level secrets in the opengeni-runtime secret\n // (Helm-clobbered configmap avoided), all OPTIONAL: when the callout plane is not\n // configured the responder simply does not start (selfhosted agents cannot\n // connect — graceful, never a boot-fail).\n //\n // The callout account SIGNING SEED (`SA...`). Both the user JWT and the\n // authorization-response JWT are signed by this account key; its public key\n // (`A...`) is the `auth_callout.issuer` in the server config. NEVER logged.\n selfhostedNatsCalloutAccountSeed: z.string().optional(),\n // The TARGET ACCOUNT NAME the minted user is placed into (the server-config-mode\n // `auth_callout.account`, e.g. \"APP\"). The responder writes it as the minted user\n // JWT `aud` so nats-server binds the agent to this account — the SAME account the\n // privileged control plane connects into, so `agent.<ws>.<id>.rpc` request/reply\n // routes. Optional; resolveNatsCalloutConfig defaults it to \"APP\".\n selfhostedNatsCalloutAccountName: z.string().optional(),\n // The callout RESPONDER's own NATS login (one of the `auth_callout.auth_users`\n // in the AUTH account) — the responder connects with this to subscribe\n // $SYS.REQ.USER.AUTH. Username/password.\n selfhostedNatsCalloutUser: z.string().optional(),\n selfhostedNatsCalloutPassword: z.string().optional(),\n // The PRIVILEGED control-plane login (api/worker): a static account user that may\n // request `agent.*.rpc` + receive its inbox replies. The event bus + the\n // selfhosted control RPC ride THIS connection. Username/password; when unset the\n // bus connects anonymously (local dev / a NATS with no auth_callout).\n selfhostedNatsControlUser: z.string().optional(),\n selfhostedNatsControlPassword: z.string().optional(),\n // --- selfhosted (Connected Machine) control/exec op deadlines ---------------\n // The control plane splits its op deadline in two. CONTROL ops (ping / fs / git /\n // desktop / pty) must stay responsive so a machine's liveness is never masked by a\n // slow op, so they use the short control timeout. EXEC gets its OWN, larger budget:\n // a real command (compile, test run, dependency install) routinely outlives the\n // control timeout, and before the split a long command was killed at the ~30s\n // control wall. The agent kills the exec child at this deadline; the wire waits\n // slightly longer (SELFHOSTED_EXEC_REPLY_GRACE_MS) for the typed timed-out reply.\n //\n // The exec default is a DELIBERATELY MODEST 2min (not 5): the agent-side admission\n // pool is (until a later agent release) a FLAT 8 permits with no per-class split,\n // so 8 slow execs holding a permit for 5 minutes would blanket-DRAIN every fs/git\n // op — shipping the amplifier before the class-aware-admission fix. 2min still\n // clears the large majority of the observed >30s exec tail; genuinely long jobs run\n // in the background (see the exec-deadline hint) or raise the knob per deployment.\n // Knobs: OPENGENI_SANDBOX_SELFHOSTED_EXEC_TIMEOUT_MS (default 2min) and\n // OPENGENI_SANDBOX_SELFHOSTED_CONTROL_TIMEOUT_MS (default 30s).\n sandboxSelfhostedExecTimeoutMs: z.coerce.number().int().positive().default(120_000),\n sandboxSelfhostedControlTimeoutMs: z.coerce.number().int().positive().default(30_000),\n // --- sandbox lease cadences (cadence invariant validated at boot below) ---\n // reaperPeriod < viewerHolderTTL, and reaperPeriod + idleGrace < the EFFECTIVE\n // box idle timeout (effectiveModalIdleTimeoutSeconds, which defaults to the hard\n // modalTimeoutSeconds). No keep-alive loop: between turns the box survives on its\n // idle timeout — which we pin high enough (via the idle-timeout default) that\n // OpenGeni's reaper, not Modal's idle-reap, governs teardown so /workspace is\n // snapshotted before the box dies (sandbox-file-persistence).\n sandboxLeaseReaperPeriodMs: z.coerce.number().int().positive().default(30_000),\n sandboxViewerHolderTtlMs: z.coerce.number().int().positive().default(90_000),\n // The DRAIN grace: how long a refcount-0 (draining) lease stays WARM before the\n // reaper resume-by-ids the box and terminates it. This is the cost-vs-snappiness\n // dial — when the user navigates away the box keeps refcount 0, but it survives\n // this whole window so a \"glanced away then came back\" re-arms the SAME warm box\n // (acquireLease re-arms draining->warm; the reaper's BEFORE-terminate re-read\n // skips a re-armed box). Default 15min so a brief detour never cold-creates a\n // fresh EMPTY box; lower it to trade warm cost for a snappier reclaim. Knob:\n // OPENGENI_SANDBOX_IDLE_GRACE_MS.\n sandboxIdleGraceMs: z.coerce.number().int().positive().default(900_000),\n // MID-SESSION /workspace snapshot cadence (sandbox-file-persistence). The\n // reaper's drain-persist only protects boxes the reaper itself kills; a box\n // that dies any other way (Modal's hard creation-time timeout on a session\n // busy past it, provider OOM/infra death) loses everything since the last\n // clean drain. While a turn holds the box, the turn heartbeat and turn-end\n // both take a snapshot when at least this interval has passed since the last\n // one (same epoch-fenced fold-onto-lease seam as the drain), bounding the\n // worst-case loss of ANY unclean box death to this window. 0 disables.\n // Knob: OPENGENI_SANDBOX_SNAPSHOT_INTERVAL_MS. Default 15min.\n sandboxSnapshotIntervalMs: z.coerce.number().int().min(0).default(900_000),\n // Maximum time a best-effort /workspace snapshot capture may hold turn/reaper\n // cleanup. A hung provider snapshot must never pin a lease holder, block\n // graceful shutdown, or become permission to GC an older archive. Timeout is\n // treated exactly like a failed best-effort snapshot. Knob:\n // OPENGENI_SANDBOX_SNAPSHOT_TIMEOUT_MS. Default 60s.\n sandboxSnapshotTimeoutMs: z.coerce.number().int().positive().default(60_000),\n // expires_at refresh window for a held lease (>> the turn 10s heartbeat so a\n // single missed heartbeat never TTL-reaps a live turn). The warming TTL is the\n // window a cold->warming spawner has to commit warm before a reaper resets it.\n sandboxLeaseTtlMs: z.coerce.number().int().positive().default(90_000),\n sandboxLeaseWarmingTtlMs: z.coerce.number().int().positive().default(120_000),\n // Overall user-facing budget for warming a sandbox lease. Unlike the lease TTL\n // (a liveness/reaper cadence), this bounds how long one turn waits for capacity\n // or provider creation before surfacing a clear turn.failed error.\n sandboxWarmingTimeoutMs: z.coerce.number().int().positive().default(600_000),\n // Rig setup-script budget (M3): the wall-clock timeout the rig-setup lifecycle\n // hook runs its script under, distinct from the 120s per-command lifecycle\n // default (a rig may compile/install heavy tooling on first cold create).\n // Env: OPENGENI_RIG_SETUP_TIMEOUT_MS. Default 10min.\n rigSetupTimeoutMs: z.coerce.number().int().positive().default(600_000),\n // --- sandbox warm-time billing (P2.1) ---\n // Per-backend warm rate (usd_micros/sec), like modelPricingJson: an empty {}\n // means warm-cost is not debited (warm-seconds are still metered for audit).\n // Shape: { \"modal\": 5, \"runloop\": 4, ... }. Backends absent here meter\n // warm-seconds but accrue NO warm_cost / debit (rate 0).\n sandboxWarmRateMicrosPerSecondJson: z.string().default(\"{}\"),\n // Per-workspace warm cap (cumulative warm-seconds since the start of the UTC\n // month, summed over sandbox.warm_seconds). 0 = unbounded. A workspace over the\n // cap force-drains its VIEWER-ONLY boxes (guarded AND turn_holders=0 — a paying\n // turn is never killed); the reaper then stop()s at refcount 0.\n sandboxMaxWarmSecondsPerWorkspace: z.coerce.number().int().nonnegative().default(0),\n sandboxPreparationProfiles: z.string().default(\"none\"),\n sandboxEnvAllowlist: z.string().default(\"\"),\n objectStorageEndpoint: z.string().url().optional(),\n objectStorageSandboxEndpoint: z.string().url().optional(),\n objectStorageBackend: z\n .enum([\"s3-compatible\", \"aws-s3\", \"azure-blob\", \"gcs\"])\n .default(\"s3-compatible\"),\n objectStorageBucket: z.string().min(1).default(\"opengeni-files\"),\n objectStorageRegion: z.string().min(1).default(\"us-east-1\"),\n objectStorageS3Provider: z.string().min(1).default(\"Minio\"),\n objectStorageAccessKeyId: z.string().optional(),\n objectStorageSecretAccessKey: z.string().optional(),\n objectStorageForcePathStyle: EnvBoolean.default(true),\n objectStorageAzureConnectionString: z.string().optional(),\n objectStorageAzureAccountName: z.string().optional(),\n objectStorageAzureAccountKey: z.string().optional(),\n objectStorageAzureEndpoint: z.string().url().optional(),\n objectStorageGcsProjectId: z.string().optional(),\n objectStorageGcsCredentialsJson: z.string().optional(),\n objectStorageGcsKeyFilename: z.string().optional(),\n objectStorageGcsApiEndpoint: z.string().url().optional(),\n documentParser: z.string().min(1).default(\"liteparse\"),\n documentChunkSize: z.coerce.number().int().positive().default(1200),\n documentChunkOverlap: z.coerce.number().int().nonnegative().default(160),\n documentEmbeddingProvider: z.enum([\"openai\", \"deterministic\"]).default(\"openai\"),\n documentEmbeddingModel: z.string().min(1).default(\"text-embedding-3-large\"),\n documentEmbeddingDimensions: z.coerce.number().int().positive().default(3072),\n documentEmbeddingApiKey: z.string().optional(),\n documentEmbeddingBaseUrl: z.string().url().optional(),\n documentCurationProvider: z.enum([\"openai\", \"heuristic\", \"none\"]).default(\"openai\"),\n documentCurationModel: z.string().min(1).default(\"gpt-4o-mini\"),\n documentCurationApiKey: z.string().optional(),\n documentCurationBaseUrl: z.string().url().optional(),\n gitAuthorName: z.string().optional(),\n gitAuthorEmail: z.string().optional(),\n gitCommitterName: z.string().optional(),\n gitCommitterEmail: z.string().optional(),\n githubAppManifestBaseUrl: z.string().optional(),\n githubAppManifestStateSecret: z.string().optional(),\n githubAppId: z.string().optional(),\n githubClientId: z.string().optional(),\n githubClientSecret: z.string().optional(),\n githubAppSlug: z.string().optional(),\n githubWebhookSecret: z.string().optional(),\n githubAppPrivateKey: z.string().optional(),\n betterAuthSecret: z.string().optional(),\n betterAuthAllowedHosts: z.string().default(\"\"),\n betterAuthCookieDomain: z.string().optional(),\n betterAuthTrustedOrigins: z.string().default(\"\"),\n resendApiKey: z.string().optional(),\n emailFrom: z.string().default(\"OpenGeni <auth@mail.opengeni.ai>\"),\n stripeSecretKey: z.string().optional(),\n stripePublishableKey: z.string().optional(),\n stripeWebhookSecret: z.string().optional(),\n stripeCreditsProductId: z.string().optional(),\n mcpServers: z\n .array(\n z.object({\n id: z.string().min(1).regex(registryId),\n name: z.string().min(1).optional(),\n url: z.string().url(),\n allowedTools: z.array(z.string().min(1)).optional(),\n timeoutMs: z.number().int().positive().optional(),\n cacheToolsList: z.boolean().default(false),\n /** Runtime approval policy, overlaid from an attempt-frozen session snapshot. */\n requireApproval: SessionMcpApprovalPolicy.optional(),\n /**\n * Extra request headers sent to this MCP server (credential injection\n * for workspace-enabled capability MCPs). Populated at runtime from\n * encrypted capability-installation credentials; do not put secrets in\n * OPENGENI_MCP_SERVERS.\n */\n headers: z.record(z.string(), z.string()).optional(),\n connectionRef: McpServerConnectionRefSchema.optional(),\n }),\n )\n .default([]),\n});\n\nexport type Settings = z.infer<typeof SettingsSchema>;\nexport type McpServerConfig = Settings[\"mcpServers\"][number];\nexport type TemporalTlsConnectionConfig = {\n serverNameOverride?: string;\n serverRootCACertificate?: Uint8Array;\n clientCertPair?: {\n crt: Uint8Array;\n key: Uint8Array;\n };\n};\nexport type TemporalConnectionOptions = {\n address: string;\n tls?: true | TemporalTlsConnectionConfig;\n apiKey?: string;\n};\nexport type ModelPricing = {\n inputMicrosPerMillionTokens: number;\n cachedInputMicrosPerMillionTokens?: number | undefined;\n outputMicrosPerMillionTokens: number;\n marginBps?: number | undefined;\n};\nexport type ModelPricingScheduleV1 = {\n default: ModelPricing;\n inputTokenTiers?:\n | Array<{\n minimumInputTokens: number;\n pricing: ModelPricing;\n }>\n | undefined;\n};\nexport type ModelUsageInput = {\n inputTokens?: number | undefined;\n outputTokens?: number | undefined;\n totalTokens?: number | undefined;\n inputTokensDetails?: Record<string, number> | Array<Record<string, number>> | undefined;\n requestUsageEntries?: ModelUsageInput[] | undefined;\n};\n\nexport type StaticUsageLimitsConfig = StaticUsageLimits;\nexport type EntitlementsConfig = Entitlements;\n\nconst ModelPricingSchema = z.object({\n inputMicrosPerMillionTokens: z.number().int().nonnegative(),\n cachedInputMicrosPerMillionTokens: z.number().int().nonnegative().optional(),\n outputMicrosPerMillionTokens: z.number().int().nonnegative(),\n marginBps: z.number().int().min(0).max(100_000).optional(),\n});\n\nconst ModelPricingScheduleSchema = z\n .object({\n default: ModelPricingSchema,\n inputTokenTiers: z\n .array(\n z.object({\n minimumInputTokens: z.number().int().nonnegative(),\n pricing: ModelPricingSchema,\n }),\n )\n .optional(),\n })\n .superRefine((schedule, ctx) => {\n let previous = -1;\n for (const [index, tier] of (schedule.inputTokenTiers ?? []).entries()) {\n if (tier.minimumInputTokens <= previous) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"inputTokenTiers\", index, \"minimumInputTokens\"],\n message: \"input-token tier thresholds must be strictly increasing\",\n });\n }\n previous = tier.minimumInputTokens;\n }\n });\n\nexport const CapabilitySupportV1 = z.enum([\"supported\", \"unsupported\", \"unknown\"]);\nexport type CapabilitySupportV1 = z.infer<typeof CapabilitySupportV1>;\n\nexport const CapabilityStateV1Schema = z\n .object({\n upstream: CapabilitySupportV1,\n runnable: z.boolean(),\n })\n .superRefine((state, ctx) => {\n if (state.upstream === \"unsupported\" && state.runnable) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"runnable\"],\n message: \"an upstream-unsupported capability cannot be runnable\",\n });\n }\n });\nexport type CapabilityStateV1 = z.infer<typeof CapabilityStateV1Schema>;\n\nconst ModelModalityV1 = z.enum([\"text\", \"image\", \"audio\"]);\nconst ModelLatencyModeV1 = z.enum([\"standard\", \"priority\", \"fast\"]);\n\nexport const ModelCapabilitiesV1Schema = z\n .object({\n reasoning: CapabilityStateV1Schema.extend({\n efforts: z.array(ReasoningEffort),\n defaultEffort: ReasoningEffort.nullable(),\n required: z.boolean(),\n }),\n functionCalling: CapabilityStateV1Schema,\n structuredOutput: CapabilityStateV1Schema,\n hostedTools: z.object({\n webSearch: CapabilityStateV1Schema,\n xSearch: CapabilityStateV1Schema,\n codeExecution: CapabilityStateV1Schema,\n }),\n inputModalities: z.array(ModelModalityV1).min(1),\n outputModalities: z.array(ModelModalityV1).min(1),\n transports: z.object({\n sse: CapabilityStateV1Schema,\n responsesWebSocket: CapabilityStateV1Schema,\n realtimeAudio: CapabilityStateV1Schema,\n }),\n latencyModes: z\n .array(\n z.object({\n id: ModelLatencyModeV1,\n upstream: CapabilitySupportV1,\n runnable: z.boolean(),\n billingMultiplierBps: z.number().int().positive().optional(),\n }),\n )\n .min(1),\n })\n .superRefine((capabilities, ctx) => {\n const efforts = new Set(capabilities.reasoning.efforts);\n if (efforts.size !== capabilities.reasoning.efforts.length) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"reasoning\", \"efforts\"],\n message: \"reasoning efforts must be unique\",\n });\n }\n if (\n capabilities.reasoning.defaultEffort !== null &&\n !efforts.has(capabilities.reasoning.defaultEffort)\n ) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"reasoning\", \"defaultEffort\"],\n message: \"the default reasoning effort must be one of the supported efforts\",\n });\n }\n if (capabilities.reasoning.runnable && capabilities.reasoning.efforts.length === 0) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"reasoning\", \"efforts\"],\n message: \"a runnable reasoning capability must declare at least one effort\",\n });\n }\n for (const field of [\"inputModalities\", \"outputModalities\"] as const) {\n if (new Set(capabilities[field]).size !== capabilities[field].length) {\n ctx.addIssue({\n code: \"custom\",\n path: [field],\n message: `${field} must be unique`,\n });\n }\n }\n const latencyIds = new Set<string>();\n for (const [index, mode] of capabilities.latencyModes.entries()) {\n if (latencyIds.has(mode.id)) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"latencyModes\", index, \"id\"],\n message: \"latency mode ids must be unique\",\n });\n }\n latencyIds.add(mode.id);\n if (mode.upstream === \"unsupported\" && mode.runnable) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"latencyModes\", index, \"runnable\"],\n message: \"an upstream-unsupported latency mode cannot be runnable\",\n });\n }\n }\n });\nexport type ModelCapabilitiesV1 = z.infer<typeof ModelCapabilitiesV1Schema>;\n\nexport type ModelDeploymentV1 = {\n upstreamModelId: string;\n wireApi: ModelProviderApi;\n};\n\nexport type ModelExecutionLimitsV1 = {\n contextWindowTokens: number | null;\n effectiveContextWindowTokens: number | null;\n autoCompactTokenLimit: number | null;\n toolOutputTruncationTokens: number | null;\n};\n\nexport type CredentialSourceV1 =\n | { kind: \"deployment\"; mechanism: \"api_key\" | \"azure_ad_bearer\" }\n | { kind: \"connected_subscription\"; provider: \"codex\" }\n | { kind: \"workspace_connection\"; mechanism: \"api_key\" };\n\nexport type BillingAttributionV1 = {\n upstreamPayer: \"deployment\" | \"workspace\" | \"connected_subscription\";\n metering: \"opengeni_credits\" | \"external\";\n};\n\n/**\n * Wire API a provider speaks. The built-in OpenAI/Azure provider always uses\n * \"responses\" (the OpenAI Responses API). Extra registry providers default to\n * \"chat\" (the broadly compatible /v1/chat/completions surface); Fireworks is\n * wired as \"chat\" because its beta Responses endpoint echoes input back and\n * silently no-ops hosted tools (see docs/model-providers.md).\n */\nexport const ModelProviderApi = z.enum([\"responses\", \"chat\"]);\nexport type ModelProviderApi = z.infer<typeof ModelProviderApi>;\n\n/**\n * Registry provider kind. \"api-key\" providers carry their own static key/headers;\n * \"codex-subscription\" providers authenticate per-request with a ChatGPT/Codex\n * subscription token resolved at call time (no static key) — see @opengeni/codex.\n */\nexport const RegistryProviderKind = z.enum([\"api-key\", \"codex-subscription\"]);\nexport type RegistryProviderKind = z.infer<typeof RegistryProviderKind>;\n\n/** A single model exposed by a registry provider. */\nconst RegistryModelSchema = z\n .object({\n id: z.string().min(1), // canonical OpenGeni product id\n upstreamModelId: z.string().min(1).optional(), // exact provider slug; defaults to id\n aliases: z.array(z.string().min(1)).optional(), // accepted input only; never sent upstream\n label: z.string().min(1).optional(), // display name; defaults to id\n contextWindowTokens: z.number().int().positive().optional(),\n effectiveContextWindowTokens: z.number().int().positive().optional(),\n autoCompactTokenLimit: z.number().int().positive().optional(),\n // Canonical model-facing function/tool-result policy. The runtime applies\n // the same 1.2x serialization allowance as Codex when materializing output.\n toolOutputTruncationTokens: z.number().int().positive().optional(),\n reasoningEffort: z.boolean().optional(), // legacy compatibility input/projection\n hostedWebSearch: z.boolean().optional(), // legacy compatibility input/projection\n capabilities: ModelCapabilitiesV1Schema.optional(),\n pricing: z.union([ModelPricingSchema, ModelPricingScheduleSchema]).optional(),\n // Reserved normalized contracts are derived by OpenGeni in V1. Generic\n // registry JSON must not opt itself into workspace BYOK or reattribute cost.\n credentialSource: z.never().optional(),\n billing: z.never().optional(),\n })\n .superRefine((model, ctx) => {\n if (\n model.capabilities &&\n model.reasoningEffort !== undefined &&\n model.reasoningEffort !== model.capabilities.reasoning.runnable\n ) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"reasoningEffort\"],\n message: \"legacy reasoningEffort must agree with capabilities.reasoning.runnable\",\n });\n }\n if (\n model.capabilities &&\n model.hostedWebSearch !== undefined &&\n model.hostedWebSearch !== model.capabilities.hostedTools.webSearch.runnable\n ) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"hostedWebSearch\"],\n message:\n \"legacy hostedWebSearch must agree with capabilities.hostedTools.webSearch.runnable\",\n });\n }\n });\n\n/** A non-built-in provider declared by the host via OPENGENI_MODEL_PROVIDERS_JSON. */\nconst RegistryProviderSchema = z.object({\n kind: RegistryProviderKind.default(\"api-key\"), // \"codex-subscription\" => per-request token, no static key\n id: z.string().min(1).regex(registryId), // stable provider id, e.g. \"fireworks\"\n label: z.string().min(1).optional(),\n api: ModelProviderApi.default(\"chat\"),\n baseUrl: z.string().url(),\n apiKey: z.string().optional(), // inline key (pragmatic) ...\n apiKeyEnv: z.string().optional(), // ... OR name of the env var holding the key (preferred)\n defaultQuery: z.record(z.string(), z.string()).optional(),\n defaultHeaders: z.record(z.string(), z.string()).optional(),\n publicDefaultQueryNames: z.array(z.string().min(1)).optional(),\n publicDefaultHeaderNames: z.array(z.string().min(1)).optional(),\n // V1 derives these from provider kind. Workspace BYOK is deliberately not a\n // registry switch and requires a separately reviewed encrypted broker.\n credentialSource: z.never().optional(),\n billing: z.never().optional(),\n models: z.array(RegistryModelSchema).min(1),\n});\nexport type RegistryProvider = z.infer<typeof RegistryProviderSchema>;\n\nexport const IntegrationOAuthClientConfigSchema = z.object({\n clientId: z.string().min(1),\n clientSecret: z.string().min(1).optional(),\n tokenEndpointAuthMethod: z\n .enum([\"none\", \"client_secret_post\", \"client_secret_basic\"])\n .default(\"none\"),\n});\nexport type IntegrationOAuthClientConfig = z.infer<typeof IntegrationOAuthClientConfigSchema>;\n\n/**\n * Runtime-resolved provider (built-in or registry), client-construction-ready.\n * The built-in OpenAI/Azure provider is always present and always \"responses\";\n * registry providers carry their own base URL / key / wire API. Compaction is\n * not a provider capability: all providers use the same durable plaintext\n * replacement.\n */\nexport interface ResolvedModelProvider {\n id: string; // \"openai\" | \"azure\" | registry id\n label: string;\n kind: RegistryProviderKind; // \"api-key\" (built-ins + most registry) | \"codex-subscription\"\n api: ModelProviderApi;\n builtin: boolean;\n baseUrl?: string | undefined;\n apiKey?: string | undefined;\n defaultQuery?: Record<string, string> | undefined;\n defaultHeaders?: Record<string, string> | undefined;\n publicDefaultQueryNames?: string[] | undefined;\n publicDefaultHeaderNames?: string[] | undefined;\n credentialSource: CredentialSourceV1;\n billing: BillingAttributionV1;\n}\n\n/** A single exposed model + the provider that serves it. */\nexport interface ConfiguredModel {\n schemaVersion: 1;\n id: string;\n aliases: string[];\n label: string;\n providerId: string;\n providerLabel: string;\n api: ModelProviderApi;\n upstreamModelId: string;\n deployment: ModelDeploymentV1;\n executionLimits: ModelExecutionLimitsV1;\n credentialSource: CredentialSourceV1;\n billing: BillingAttributionV1;\n capabilities: ModelCapabilitiesV1;\n pricing?: ModelPricingScheduleV1 | undefined;\n definitionVersion: string;\n contextWindowTokens?: number | undefined;\n effectiveContextWindowTokens?: number | undefined;\n autoCompactTokenLimit?: number | undefined;\n toolOutputTruncationTokens?: number | undefined;\n reasoningEffort: boolean;\n hostedWebSearch: boolean;\n}\n\nexport const defaultModelPricing: Record<string, ModelPricing> = {\n \"gpt-5.6-sol\": {\n inputMicrosPerMillionTokens: 5_000_000,\n cachedInputMicrosPerMillionTokens: 500_000,\n outputMicrosPerMillionTokens: 30_000_000,\n marginBps: 2_500,\n },\n \"gpt-5.6-terra\": {\n inputMicrosPerMillionTokens: 2_500_000,\n cachedInputMicrosPerMillionTokens: 250_000,\n outputMicrosPerMillionTokens: 15_000_000,\n marginBps: 2_500,\n },\n \"gpt-5.6-luna\": {\n inputMicrosPerMillionTokens: 1_000_000,\n cachedInputMicrosPerMillionTokens: 100_000,\n outputMicrosPerMillionTokens: 6_000_000,\n marginBps: 2_500,\n },\n \"gpt-5.4\": {\n inputMicrosPerMillionTokens: 2_500_000,\n cachedInputMicrosPerMillionTokens: 250_000,\n outputMicrosPerMillionTokens: 15_000_000,\n marginBps: 2_500,\n },\n \"gpt-5.4-mini\": {\n inputMicrosPerMillionTokens: 750_000,\n cachedInputMicrosPerMillionTokens: 75_000,\n outputMicrosPerMillionTokens: 4_500_000,\n marginBps: 2_500,\n },\n \"gpt-5.2\": {\n inputMicrosPerMillionTokens: 1_750_000,\n cachedInputMicrosPerMillionTokens: 175_000,\n outputMicrosPerMillionTokens: 14_000_000,\n marginBps: 2_500,\n },\n \"gpt-5.2-chat-latest\": {\n inputMicrosPerMillionTokens: 1_750_000,\n cachedInputMicrosPerMillionTokens: 175_000,\n outputMicrosPerMillionTokens: 14_000_000,\n marginBps: 2_500,\n },\n \"gpt-5.2-codex\": {\n inputMicrosPerMillionTokens: 1_750_000,\n cachedInputMicrosPerMillionTokens: 175_000,\n outputMicrosPerMillionTokens: 14_000_000,\n marginBps: 2_500,\n },\n \"gpt-5.1\": {\n inputMicrosPerMillionTokens: 1_250_000,\n cachedInputMicrosPerMillionTokens: 125_000,\n outputMicrosPerMillionTokens: 10_000_000,\n marginBps: 2_500,\n },\n \"gpt-5\": {\n inputMicrosPerMillionTokens: 1_250_000,\n cachedInputMicrosPerMillionTokens: 125_000,\n outputMicrosPerMillionTokens: 10_000_000,\n marginBps: 2_500,\n },\n \"gpt-5-mini\": {\n inputMicrosPerMillionTokens: 250_000,\n cachedInputMicrosPerMillionTokens: 25_000,\n outputMicrosPerMillionTokens: 2_000_000,\n marginBps: 2_500,\n },\n \"gpt-5-nano\": {\n inputMicrosPerMillionTokens: 50_000,\n cachedInputMicrosPerMillionTokens: 5_000,\n outputMicrosPerMillionTokens: 400_000,\n marginBps: 2_500,\n },\n // Fireworks AI / GLM 5.2 — the first shipped non-OpenAI registry model. A\n // built-in default pricing entry makes managed billing work out of the box\n // for hosts that expose this model via OPENGENI_MODEL_PROVIDERS_JSON without\n // also setting OPENGENI_MODEL_PRICING_JSON.\n \"accounts/fireworks/models/glm-5p2\": {\n inputMicrosPerMillionTokens: 1_400_000,\n cachedInputMicrosPerMillionTokens: 260_000,\n outputMicrosPerMillionTokens: 4_400_000,\n marginBps: 2_500,\n },\n};\n\n// --- backend-gated required-credential table (the single source of truth) ---\n// Each sandbox backend declares ONLY its own required credentials: a deployment\n// configured for `sandboxBackend=modal` must carry the Modal token, but a\n// daytona/e2b/local/none deployment must NOT be forced to set Modal creds (and\n// vice versa). validateSettings() iterates this table for the *active* backend\n// only — so the cred a backend doesn't use is never a boot blocker — and the\n// deployment package mirrors the same table to drive its env-render + the\n// required-env manifest (one table, two consumers).\n//\n// `field` is the parsed Settings key (boot validation reads the typed value);\n// `env` is the OPENGENI_* variable name (deployment renders/requires it). The\n// modal token is a both-or-neither pair handled by an extra refine in\n// validateSettings — this table holds the hard \"must be present when active\"\n// requirements.\nexport type SandboxRequiredEnv = {\n field: keyof Settings;\n env: string;\n};\n\nexport const SANDBOX_REQUIRED_ENV: Record<\n z.infer<typeof SandboxBackend>,\n readonly SandboxRequiredEnv[]\n> = {\n // docker/local/none need no credentials (local dev container / in-process / off).\n docker: [],\n local: [],\n none: [],\n modal: [\n { field: \"modalAppName\", env: \"OPENGENI_MODAL_APP_NAME\" },\n { field: \"modalTokenId\", env: \"OPENGENI_MODAL_TOKEN_ID\" },\n { field: \"modalTokenSecret\", env: \"OPENGENI_MODAL_TOKEN_SECRET\" },\n ],\n daytona: [{ field: \"daytonaApiKey\", env: \"OPENGENI_DAYTONA_API_KEY\" }],\n runloop: [{ field: \"runloopApiKey\", env: \"OPENGENI_RUNLOOP_API_KEY\" }],\n e2b: [{ field: \"e2bApiKey\", env: \"OPENGENI_E2B_API_KEY\" }],\n blaxel: [{ field: \"blaxelApiKey\", env: \"OPENGENI_BLAXEL_API_KEY\" }],\n cloudflare: [{ field: \"cloudflareWorkerUrl\", env: \"OPENGENI_CLOUDFLARE_WORKER_URL\" }],\n vercel: [\n { field: \"vercelToken\", env: \"OPENGENI_VERCEL_TOKEN\" },\n { field: \"vercelProjectId\", env: \"OPENGENI_VERCEL_PROJECT_ID\" },\n ],\n // selfhosted needs NO per-box credentials: it is the user's own machine reached\n // over the agent's own enrollment. The enrollment-signing + relay-token secrets\n // are deployment-level (a single runtime secret, not per-active-backend creds),\n // wired in the connectivity/enrollment milestones (M4/M5), not here.\n selfhosted: [],\n};\n\n/** The required OPENGENI_* env var names for a backend (for the deployment manifest). */\nexport function requiredSandboxEnvForBackend(backend: z.infer<typeof SandboxBackend>): string[] {\n return (SANDBOX_REQUIRED_ENV[backend] ?? []).map((entry) => entry.env);\n}\n\nfunction optional(name: string): string | undefined {\n const value = process.env[name];\n return value && value.trim().length > 0 ? value : undefined;\n}\n\nexport function getSettings(): Settings {\n const raw = {\n serviceName: optional(\"OPENGENI_SERVICE_NAME\"),\n environment: optional(\"OPENGENI_ENVIRONMENT\"),\n deploymentRevision:\n optional(\"OPENGENI_DEPLOYMENT_REVISION\") ??\n optional(\"SOURCE_VERSION\") ??\n optional(\"GITHUB_SHA\"),\n serverVersion: optional(\"OPENGENI_SERVER_VERSION\"),\n databaseUrl: optional(\"OPENGENI_DATABASE_URL\"),\n dbSchema: optional(\"OPENGENI_DB_SCHEMA\"),\n rlsStrategy: optional(\"OPENGENI_RLS_STRATEGY\"),\n runtimeDatabaseRole: optional(\"OPENGENI_RUNTIME_DATABASE_ROLE\"),\n natsUrl: optional(\"OPENGENI_NATS_URL\"),\n temporalHost: optional(\"OPENGENI_TEMPORAL_HOST\"),\n temporalNamespace: optional(\"OPENGENI_TEMPORAL_NAMESPACE\"),\n temporalTaskQueue: optional(\"OPENGENI_TEMPORAL_TASK_QUEUE\"),\n temporalTlsEnabled: optional(\"OPENGENI_TEMPORAL_TLS_ENABLED\"),\n temporalApiKey: optional(\"OPENGENI_TEMPORAL_API_KEY\"),\n temporalTlsServerName: optional(\"OPENGENI_TEMPORAL_TLS_SERVER_NAME\"),\n temporalTlsRootCaCertificateBase64: optional(\n \"OPENGENI_TEMPORAL_TLS_ROOT_CA_CERTIFICATE_BASE64\",\n ),\n temporalTlsClientCertificateBase64: optional(\"OPENGENI_TEMPORAL_TLS_CLIENT_CERTIFICATE_BASE64\"),\n temporalTlsClientPrivateKeyBase64: optional(\"OPENGENI_TEMPORAL_TLS_CLIENT_PRIVATE_KEY_BASE64\"),\n startupDependencyRetryAttempts: optional(\"OPENGENI_STARTUP_DEPENDENCY_RETRY_ATTEMPTS\"),\n startupDependencyRetryInitialDelayMs: optional(\n \"OPENGENI_STARTUP_DEPENDENCY_RETRY_INITIAL_DELAY_MS\",\n ),\n startupDependencyRetryMaxDelayMs: optional(\"OPENGENI_STARTUP_DEPENDENCY_RETRY_MAX_DELAY_MS\"),\n turnWorkerConcurrencyMode: optional(\"OPENGENI_TURN_WORKER_CONCURRENCY_MODE\"),\n turnWorkerMaxConcurrentTurns: optional(\"OPENGENI_TURN_WORKER_MAX_CONCURRENT_TURNS\"),\n turnWorkerTargetCpuUsage: optional(\"OPENGENI_TURN_WORKER_TARGET_CPU_USAGE\"),\n turnWorkerTargetMemoryUsage: optional(\"OPENGENI_TURN_WORKER_TARGET_MEMORY_USAGE\"),\n observabilityStructuredLogs: optional(\"OPENGENI_OBSERVABILITY_STRUCTURED_LOGS\"),\n observabilityMetricsEnabled: optional(\"OPENGENI_OBSERVABILITY_METRICS_ENABLED\"),\n observabilityOtlpEndpoint:\n optional(\"OPENGENI_OTEL_EXPORTER_OTLP_ENDPOINT\") ?? optional(\"OTEL_EXPORTER_OTLP_ENDPOINT\"),\n observabilityOtlpHeaders:\n optional(\"OPENGENI_OTEL_EXPORTER_OTLP_HEADERS\") ?? optional(\"OTEL_EXPORTER_OTLP_HEADERS\"),\n publicBaseUrl: optional(\"OPENGENI_PUBLIC_BASE_URL\"),\n agentReleasesBaseUrl: optional(\"OPENGENI_AGENT_RELEASES_BASE_URL\"),\n agentStableVersion: optional(\"OPENGENI_AGENT_STABLE_VERSION\"),\n productAccessMode: optional(\"OPENGENI_PRODUCT_ACCESS_MODE\"),\n billingMode: optional(\"OPENGENI_BILLING_MODE\"),\n entitlementsMode: optional(\"OPENGENI_ENTITLEMENTS_MODE\"),\n usageLimitsMode: optional(\"OPENGENI_USAGE_LIMITS_MODE\"),\n staticEntitlementsJson: optional(\"OPENGENI_STATIC_ENTITLEMENTS_JSON\"),\n staticUsageLimitsJson: optional(\"OPENGENI_STATIC_USAGE_LIMITS_JSON\"),\n delegationSecret: optional(\"OPENGENI_DELEGATION_SECRET\"),\n streamTokenSecret: optional(\"OPENGENI_STREAM_TOKEN_SECRET\"),\n streamControlEnabled: optional(\"OPENGENI_STREAM_CONTROL_ENABLED\"),\n sessionTurnToolReplacementEnabled: optional(\"OPENGENI_SESSION_TURN_TOOL_REPLACEMENT_ENABLED\"),\n toolspaceEnabled: optional(\"OPENGENI_TOOLSPACE_ENABLED\"),\n toolspaceMaxCallsPerTurn: optional(\"OPENGENI_TOOLSPACE_MAX_CALLS_PER_TURN\"),\n ogtoolPackageSpec: optional(\"OPENGENI_OGTOOL_PACKAGE_SPEC\"),\n environmentsEncryptionKey: optional(\"OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY\"),\n integrationsEnabled: optional(\"OPENGENI_INTEGRATIONS_ENABLED\"),\n integrationsStateSecret: optional(\"OPENGENI_INTEGRATIONS_STATE_SECRET\"),\n integrationsAllowPrivateNetworkTargets: optional(\n \"OPENGENI_INTEGRATIONS_ALLOW_PRIVATE_NETWORK_TARGETS\",\n ),\n integrationsOauthClientsJson: optional(\"OPENGENI_INTEGRATIONS_OAUTH_CLIENTS_JSON\"),\n maxNestedAgentDepth: optional(\"OPENGENI_MAX_NESTED_AGENT_DEPTH\"),\n goalMaxAutoContinuations: optional(\"OPENGENI_GOAL_MAX_AUTO_CONTINUATIONS\"),\n goalNoProgressLimit: optional(\"OPENGENI_GOAL_NO_PROGRESS_LIMIT\"),\n agentMaxModelCallsPerTurn: optional(\"OPENGENI_AGENT_MAX_MODEL_CALLS_PER_TURN\"),\n contextWindowTokens: optional(\"OPENGENI_CONTEXT_WINDOW_TOKENS\"),\n contextEffectiveWindowTokens: optional(\"OPENGENI_CONTEXT_EFFECTIVE_WINDOW_TOKENS\"),\n contextCompactionThresholdRatio: optional(\"OPENGENI_COMPACTION_THRESHOLD_RATIO\"),\n contextReservedOutputTokens: optional(\"OPENGENI_CONTEXT_RESERVED_OUTPUT_TOKENS\"),\n contextAutoCompactThresholdTokens: optional(\"OPENGENI_CONTEXT_AUTO_COMPACT_THRESHOLD_TOKENS\"),\n modelToolOutputTruncationTokens: optional(\"OPENGENI_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS\"),\n authRequired: optional(\"OPENGENI_AUTH_REQUIRED\"),\n accessKey: optional(\"OPENGENI_ACCESS_KEY\"),\n authAllowHealth: optional(\"OPENGENI_AUTH_ALLOW_HEALTH\"),\n authAllowMetrics: optional(\"OPENGENI_AUTH_ALLOW_METRICS\"),\n apiHost: optional(\"OPENGENI_API_HOST\"),\n apiPort: optional(\"OPENGENI_API_PORT\"),\n workerHttpPort: optional(\"OPENGENI_WORKER_HTTP_PORT\"),\n opengeniMcpUrl: optional(\"OPENGENI_MCP_URL\"),\n corsAllowOriginRegex: optional(\"OPENGENI_CORS_ALLOW_ORIGIN_REGEX\"),\n openaiProvider: optional(\"OPENGENI_OPENAI_PROVIDER\"),\n openaiApiKey: optional(\"OPENGENI_OPENAI_API_KEY\") ?? optional(\"OPENAI_API_KEY\"),\n openaiBaseUrl: optional(\"OPENGENI_OPENAI_BASE_URL\") ?? optional(\"OPENAI_BASE_URL\"),\n openaiModel: optional(\"OPENGENI_OPENAI_MODEL\"),\n openaiAllowedModels: optional(\"OPENGENI_OPENAI_ALLOWED_MODELS\"),\n modelPricingJson: optional(\"OPENGENI_MODEL_PRICING_JSON\"),\n modelProvidersJson: optional(\"OPENGENI_MODEL_PROVIDERS_JSON\"),\n codexSubscriptionEnabled: optional(\"OPENGENI_CODEX_SUBSCRIPTION_ENABLED\"),\n codexConnectedAppsEnabled: optional(\"OPENGENI_CODEX_CONNECTED_APPS_ENABLED\"),\n codexToolSearchEnabled: optional(\"OPENGENI_CODEX_TOOL_SEARCH_ENABLED\"),\n codexCredentialLeasingEnabled: optional(\"OPENGENI_CODEX_CREDENTIAL_LEASING_ENABLED\"),\n codexFleetPolicyShadowEnabled: optional(\"OPENGENI_CODEX_FLEET_POLICY_SHADOW_ENABLED\"),\n codexProductSku: optional(\"OPENGENI_CODEX_PRODUCT_SKU\"),\n openaiReasoningEffort: optional(\"OPENGENI_OPENAI_REASONING_EFFORT\"),\n openaiAllowedReasoningEfforts: optional(\"OPENGENI_OPENAI_ALLOWED_REASONING_EFFORTS\"),\n openaiResponsesTransport: optional(\"OPENGENI_OPENAI_RESPONSES_TRANSPORT\"),\n openaiProviderItemIds: optional(\"OPENGENI_OPENAI_PROVIDER_ITEM_IDS\"),\n openaiReasoningEncryptedContent: optional(\"OPENGENI_OPENAI_REASONING_ENCRYPTED_CONTENT\"),\n openaiMaxRetries: optional(\"OPENGENI_OPENAI_MAX_RETRIES\"),\n webSearchEnabled: optional(\"OPENGENI_WEB_SEARCH_ENABLED\"),\n agentInstructionsTemplate: optional(\"OPENGENI_AGENT_INSTRUCTIONS_TEMPLATE\"),\n azureOpenaiBaseUrl: optional(\"OPENGENI_AZURE_OPENAI_BASE_URL\"),\n azureOpenaiEndpoint: optional(\"OPENGENI_AZURE_OPENAI_ENDPOINT\"),\n azureOpenaiDeployment: optional(\"OPENGENI_AZURE_OPENAI_DEPLOYMENT\"),\n azureOpenaiApiVersion: optional(\"OPENGENI_AZURE_OPENAI_API_VERSION\"),\n azureOpenaiApiKey: optional(\"OPENGENI_AZURE_OPENAI_API_KEY\"),\n azureOpenaiAdToken: optional(\"OPENGENI_AZURE_OPENAI_AD_TOKEN\"),\n disableOpenaiTracing: optional(\"OPENGENI_DISABLE_OPENAI_TRACING\"),\n sandboxBackend: optional(\"OPENGENI_SANDBOX_BACKEND\"),\n dockerImage: optional(\"OPENGENI_DOCKER_IMAGE\"),\n dockerExposedPorts: optional(\"OPENGENI_DOCKER_EXPOSED_PORTS\"),\n dockerNetwork: optional(\"OPENGENI_DOCKER_NETWORK\"),\n modalAppName: optional(\"OPENGENI_MODAL_APP_NAME\"),\n modalImageRef: optional(\"OPENGENI_MODAL_IMAGE_REF\"),\n modalImageRegistrySecret: optional(\"OPENGENI_MODAL_IMAGE_REGISTRY_SECRET\"),\n modalTimeoutSeconds: optional(\"OPENGENI_MODAL_TIMEOUT_SECONDS\"),\n modalTokenId: optional(\"OPENGENI_MODAL_TOKEN_ID\"),\n modalTokenSecret: optional(\"OPENGENI_MODAL_TOKEN_SECRET\"),\n modalEnvironment: optional(\"OPENGENI_MODAL_ENVIRONMENT\"),\n modalIdleTimeoutSeconds: optional(\"OPENGENI_MODAL_IDLE_TIMEOUT_SECONDS\"),\n modalWorkspacePersistence: optional(\"OPENGENI_MODAL_WORKSPACE_PERSISTENCE\"),\n modalSnapshotRetentionSeconds: optional(\"OPENGENI_MODAL_SNAPSHOT_RETENTION_SECONDS\"),\n sandboxDesktopEnabled: optional(\"OPENGENI_SANDBOX_DESKTOP_ENABLED\"),\n sandboxDesktopInteractive: optional(\"OPENGENI_SANDBOX_DESKTOP_INTERACTIVE\"),\n sandboxTerminalEnabled: optional(\"OPENGENI_SANDBOX_TERMINAL_ENABLED\"),\n streamResolutionWidth: optional(\"OPENGENI_STREAM_RESOLUTION_WIDTH\"),\n streamResolutionHeight: optional(\"OPENGENI_STREAM_RESOLUTION_HEIGHT\"),\n computerUseEnabled: optional(\"OPENGENI_COMPUTER_USE_ENABLED\"),\n computerUseReadOnly: optional(\"OPENGENI_COMPUTER_USE_READONLY\"),\n recordingEnabled: optional(\"OPENGENI_RECORDING_ENABLED\"),\n workspaceCaptureEnabled: optional(\"OPENGENI_WORKSPACE_CAPTURE\"),\n recordingDefaultCodec: optional(\"OPENGENI_RECORDING_DEFAULT_CODEC\"),\n recordingFramerate: optional(\"OPENGENI_RECORDING_FRAMERATE\"),\n recordingMaxSeconds: optional(\"OPENGENI_RECORDING_MAX_SECONDS\"),\n recordingMaxBytes: optional(\"OPENGENI_RECORDING_MAX_BYTES\"),\n daytonaApiKey: optional(\"OPENGENI_DAYTONA_API_KEY\"),\n daytonaApiUrl: optional(\"OPENGENI_DAYTONA_API_URL\"),\n daytonaTarget: optional(\"OPENGENI_DAYTONA_TARGET\"),\n daytonaImage: optional(\"OPENGENI_DAYTONA_IMAGE\"),\n daytonaSnapshotName: optional(\"OPENGENI_DAYTONA_SNAPSHOT_NAME\"),\n daytonaAutoStopInterval: optional(\"OPENGENI_DAYTONA_AUTO_STOP_INTERVAL\"),\n daytonaTimeoutSeconds: optional(\"OPENGENI_DAYTONA_TIMEOUT_SECONDS\"),\n daytonaExposedPortUrlTtlSeconds: optional(\"OPENGENI_DAYTONA_EXPOSED_PORT_URL_TTL_SECONDS\"),\n runloopApiKey: optional(\"OPENGENI_RUNLOOP_API_KEY\"),\n runloopBaseUrl: optional(\"OPENGENI_RUNLOOP_BASE_URL\"),\n runloopBlueprintName: optional(\"OPENGENI_RUNLOOP_BLUEPRINT_NAME\"),\n runloopBlueprintId: optional(\"OPENGENI_RUNLOOP_BLUEPRINT_ID\"),\n runloopTunnel: optional(\"OPENGENI_RUNLOOP_TUNNEL\"),\n runloopKeepAliveSeconds: optional(\"OPENGENI_RUNLOOP_KEEP_ALIVE_SECONDS\"),\n e2bApiKey: optional(\"OPENGENI_E2B_API_KEY\"),\n e2bTemplate: optional(\"OPENGENI_E2B_TEMPLATE\"),\n e2bTimeoutSeconds: optional(\"OPENGENI_E2B_TIMEOUT_SECONDS\"),\n e2bTimeoutAction: optional(\"OPENGENI_E2B_TIMEOUT_ACTION\"),\n e2bAllowInternetAccess: optional(\"OPENGENI_E2B_ALLOW_INTERNET_ACCESS\"),\n e2bAutoResume: optional(\"OPENGENI_E2B_AUTO_RESUME\"),\n e2bWorkspacePersistence: optional(\"OPENGENI_E2B_WORKSPACE_PERSISTENCE\"),\n blaxelApiKey: optional(\"OPENGENI_BLAXEL_API_KEY\"),\n blaxelImage: optional(\"OPENGENI_BLAXEL_IMAGE\"),\n blaxelRegion: optional(\"OPENGENI_BLAXEL_REGION\"),\n blaxelExposedPortPublic: optional(\"OPENGENI_BLAXEL_EXPOSED_PORT_PUBLIC\"),\n blaxelExposedPortUrlTtlSeconds: optional(\"OPENGENI_BLAXEL_EXPOSED_PORT_URL_TTL_SECONDS\"),\n blaxelMemoryMb: optional(\"OPENGENI_BLAXEL_MEMORY_MB\"),\n blaxelTtl: optional(\"OPENGENI_BLAXEL_TTL\"),\n cloudflareWorkerUrl: optional(\"OPENGENI_CLOUDFLARE_WORKER_URL\"),\n cloudflareApiKey: optional(\"OPENGENI_CLOUDFLARE_API_KEY\"),\n vercelToken: optional(\"OPENGENI_VERCEL_TOKEN\"),\n vercelProjectId: optional(\"OPENGENI_VERCEL_PROJECT_ID\"),\n vercelTeamId: optional(\"OPENGENI_VERCEL_TEAM_ID\"),\n vercelRuntime: optional(\"OPENGENI_VERCEL_RUNTIME\"),\n sandboxOwnershipEnabled: optional(\"OPENGENI_SANDBOX_OWNERSHIP_ENABLED\"),\n rigVerificationLeaseOwnershipEnabled: optional(\n \"OPENGENI_RIG_VERIFICATION_LEASE_OWNERSHIP_ENABLED\",\n ),\n sandboxLazyProvisionEnabled: optional(\"OPENGENI_SANDBOX_LAZY_PROVISION\"),\n sandboxSelfhostedEnabled: optional(\"OPENGENI_SANDBOX_SELFHOSTED_ENABLED\"),\n agentOpStreamEnabled: optional(\"OPENGENI_AGENT_OP_STREAM_ENABLED\"),\n enrollmentSigningSecret: optional(\"OPENGENI_ENROLLMENT_SIGNING_SECRET\"),\n selfhostedNatsUrl: optional(\"OPENGENI_SELFHOSTED_NATS_URL\"),\n selfhostedRelayUrl: optional(\"OPENGENI_SELFHOSTED_RELAY_URL\"),\n selfhostedRelayTokenSecret: optional(\"OPENGENI_SELFHOSTED_RELAY_TOKEN_SECRET\"),\n agentUpdatePublicKey: optional(\"OPENGENI_AGENT_UPDATE_PUBLIC_KEY\"),\n selfhostedNatsCalloutAccountSeed: optional(\"OPENGENI_SELFHOSTED_NATS_CALLOUT_ACCOUNT_SEED\"),\n selfhostedNatsCalloutAccountName: optional(\"OPENGENI_SELFHOSTED_NATS_CALLOUT_ACCOUNT_NAME\"),\n selfhostedNatsCalloutUser: optional(\"OPENGENI_SELFHOSTED_NATS_CALLOUT_USER\"),\n selfhostedNatsCalloutPassword: optional(\"OPENGENI_SELFHOSTED_NATS_CALLOUT_PASSWORD\"),\n selfhostedNatsControlUser: optional(\"OPENGENI_SELFHOSTED_NATS_CONTROL_USER\"),\n selfhostedNatsControlPassword: optional(\"OPENGENI_SELFHOSTED_NATS_CONTROL_PASSWORD\"),\n sandboxSelfhostedExecTimeoutMs: optional(\"OPENGENI_SANDBOX_SELFHOSTED_EXEC_TIMEOUT_MS\"),\n sandboxSelfhostedControlTimeoutMs: optional(\"OPENGENI_SANDBOX_SELFHOSTED_CONTROL_TIMEOUT_MS\"),\n sandboxLeaseReaperPeriodMs: optional(\"OPENGENI_SANDBOX_LEASE_REAPER_PERIOD_MS\"),\n sandboxViewerHolderTtlMs: optional(\"OPENGENI_SANDBOX_VIEWER_HOLDER_TTL_MS\"),\n sandboxIdleGraceMs: optional(\"OPENGENI_SANDBOX_IDLE_GRACE_MS\"),\n sandboxSnapshotIntervalMs: optional(\"OPENGENI_SANDBOX_SNAPSHOT_INTERVAL_MS\"),\n sandboxSnapshotTimeoutMs: optional(\"OPENGENI_SANDBOX_SNAPSHOT_TIMEOUT_MS\"),\n sandboxLeaseTtlMs: optional(\"OPENGENI_SANDBOX_LEASE_TTL_MS\"),\n sandboxLeaseWarmingTtlMs: optional(\"OPENGENI_SANDBOX_LEASE_WARMING_TTL_MS\"),\n sandboxWarmingTimeoutMs: optional(\"OPENGENI_SANDBOX_WARMING_TIMEOUT_MS\"),\n rigSetupTimeoutMs: optional(\"OPENGENI_RIG_SETUP_TIMEOUT_MS\"),\n sandboxWarmRateMicrosPerSecondJson: optional(\n \"OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON\",\n ),\n sandboxMaxWarmSecondsPerWorkspace: optional(\"OPENGENI_SANDBOX_MAX_WARM_SECONDS_PER_WORKSPACE\"),\n sandboxPreparationProfiles: optional(\"OPENGENI_SANDBOX_PREPARATION_PROFILES\"),\n sandboxEnvAllowlist: optional(\"OPENGENI_SANDBOX_ENV_ALLOWLIST\"),\n objectStorageEndpoint: optional(\"OPENGENI_OBJECT_STORAGE_ENDPOINT\"),\n objectStorageSandboxEndpoint: optional(\"OPENGENI_OBJECT_STORAGE_SANDBOX_ENDPOINT\"),\n objectStorageBackend: optional(\"OPENGENI_OBJECT_STORAGE_BACKEND\"),\n objectStorageBucket: optional(\"OPENGENI_OBJECT_STORAGE_BUCKET\"),\n objectStorageRegion: optional(\"OPENGENI_OBJECT_STORAGE_REGION\"),\n objectStorageS3Provider: optional(\"OPENGENI_OBJECT_STORAGE_S3_PROVIDER\"),\n objectStorageAccessKeyId: optional(\"OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID\"),\n objectStorageSecretAccessKey: optional(\"OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY\"),\n objectStorageForcePathStyle: optional(\"OPENGENI_OBJECT_STORAGE_FORCE_PATH_STYLE\"),\n objectStorageAzureConnectionString: optional(\"OPENGENI_OBJECT_STORAGE_AZURE_CONNECTION_STRING\"),\n objectStorageAzureAccountName: optional(\"OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_NAME\"),\n objectStorageAzureAccountKey: optional(\"OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_KEY\"),\n objectStorageAzureEndpoint: optional(\"OPENGENI_OBJECT_STORAGE_AZURE_ENDPOINT\"),\n objectStorageGcsProjectId: optional(\"OPENGENI_OBJECT_STORAGE_GCS_PROJECT_ID\"),\n objectStorageGcsCredentialsJson: optional(\"OPENGENI_OBJECT_STORAGE_GCS_CREDENTIALS_JSON\"),\n objectStorageGcsKeyFilename: optional(\"OPENGENI_OBJECT_STORAGE_GCS_KEY_FILENAME\"),\n objectStorageGcsApiEndpoint: optional(\"OPENGENI_OBJECT_STORAGE_GCS_API_ENDPOINT\"),\n documentParser: optional(\"OPENGENI_DOCUMENT_PARSER\"),\n documentChunkSize: optional(\"OPENGENI_DOCUMENT_CHUNK_SIZE\"),\n documentChunkOverlap: optional(\"OPENGENI_DOCUMENT_CHUNK_OVERLAP\"),\n documentEmbeddingProvider: optional(\"OPENGENI_DOCUMENT_EMBEDDING_PROVIDER\"),\n documentEmbeddingModel: optional(\"OPENGENI_DOCUMENT_EMBEDDING_MODEL\"),\n documentEmbeddingDimensions: optional(\"OPENGENI_DOCUMENT_EMBEDDING_DIMENSIONS\"),\n documentEmbeddingApiKey: optional(\"OPENGENI_DOCUMENT_EMBEDDING_API_KEY\"),\n documentEmbeddingBaseUrl: optional(\"OPENGENI_DOCUMENT_EMBEDDING_BASE_URL\"),\n documentCurationProvider: optional(\"OPENGENI_DOCUMENT_CURATION_PROVIDER\"),\n documentCurationModel: optional(\"OPENGENI_DOCUMENT_CURATION_MODEL\"),\n documentCurationApiKey: optional(\"OPENGENI_DOCUMENT_CURATION_API_KEY\"),\n documentCurationBaseUrl: optional(\"OPENGENI_DOCUMENT_CURATION_BASE_URL\"),\n gitAuthorName: optional(\"OPENGENI_GIT_AUTHOR_NAME\"),\n gitAuthorEmail: optional(\"OPENGENI_GIT_AUTHOR_EMAIL\"),\n gitCommitterName: optional(\"OPENGENI_GIT_COMMITTER_NAME\"),\n gitCommitterEmail: optional(\"OPENGENI_GIT_COMMITTER_EMAIL\"),\n githubAppManifestBaseUrl: optional(\"OPENGENI_GITHUB_APP_MANIFEST_BASE_URL\"),\n githubAppManifestStateSecret: optional(\"OPENGENI_GITHUB_APP_MANIFEST_STATE_SECRET\"),\n githubAppId: optional(\"OPENGENI_GITHUB_APP_ID\"),\n githubClientId: optional(\"OPENGENI_GITHUB_CLIENT_ID\"),\n githubClientSecret: optional(\"OPENGENI_GITHUB_CLIENT_SECRET\"),\n githubAppSlug: optional(\"OPENGENI_GITHUB_APP_SLUG\"),\n githubWebhookSecret: optional(\"OPENGENI_GITHUB_WEBHOOK_SECRET\"),\n githubAppPrivateKey: optional(\"OPENGENI_GITHUB_APP_PRIVATE_KEY\"),\n betterAuthSecret: optional(\"OPENGENI_BETTER_AUTH_SECRET\"),\n betterAuthAllowedHosts: optional(\"OPENGENI_BETTER_AUTH_ALLOWED_HOSTS\"),\n betterAuthCookieDomain: optional(\"OPENGENI_BETTER_AUTH_COOKIE_DOMAIN\"),\n betterAuthTrustedOrigins: optional(\"OPENGENI_BETTER_AUTH_TRUSTED_ORIGINS\"),\n resendApiKey: optional(\"OPENGENI_RESEND_API_KEY\"),\n emailFrom: optional(\"OPENGENI_EMAIL_FROM\"),\n stripeSecretKey: optional(\"OPENGENI_STRIPE_SECRET_KEY\"),\n stripePublishableKey: optional(\"OPENGENI_STRIPE_PUBLISHABLE_KEY\"),\n stripeWebhookSecret: optional(\"OPENGENI_STRIPE_WEBHOOK_SECRET\"),\n stripeCreditsProductId: optional(\"OPENGENI_STRIPE_CREDITS_PRODUCT_ID\"),\n mcpServers: parseMcpServers(optional(\"OPENGENI_MCP_SERVERS\")),\n };\n const parsed = SettingsSchema.parse(raw);\n const settings = {\n ...parsed,\n mcpServers: ensureBuiltInMcpServers(parsed),\n };\n validateSettings(settings);\n return settings;\n}\n\n/**\n * The Modal sandbox idle timeout (seconds) the provider actually passes as\n * idleTimeoutMs (sandbox-file-persistence). When the operator did not pin\n * OPENGENI_MODAL_IDLE_TIMEOUT_SECONDS we DEFAULT it to the hard lifetime\n * (modalTimeoutSeconds): OpenGeni's reaper owns box lifecycle, so Modal's\n * built-in idle-reap (which would otherwise fire on its short server default and\n * kill the box BEFORE the reaper can snapshot /workspace) is pushed out to the\n * hard backstop. An explicit smaller value is honoured (the boot invariant keeps\n * it above reaperPeriod + idleGrace so a drained box still survives long enough\n * to be persisted).\n */\nexport function effectiveModalIdleTimeoutSeconds(settings: Settings): number {\n return settings.modalIdleTimeoutSeconds ?? settings.modalTimeoutSeconds;\n}\n\nexport function collectSandboxEnvironment(\n settings: Settings,\n source: NodeJS.ProcessEnv = process.env,\n): Record<string, string> {\n const out: Record<string, string> = {};\n for (const name of sandboxEnvironmentVariableNames(settings)) {\n const value = source[name];\n if (value) {\n out[name] = value;\n }\n }\n return out;\n}\n\n/**\n * Resolved API key for a registry provider: the inline `apiKey` when present,\n * else the value of the env var named by `apiKeyEnv`. The preferred form is\n * `apiKeyEnv` (the secret stays out of OPENGENI_MODEL_PROVIDERS_JSON). Reads\n * from `source` (defaults to process.env) so callers can resolve against an\n * explicit environment in tests.\n */\nexport function resolveProviderApiKey(\n provider: Pick<RegistryProvider, \"apiKey\" | \"apiKeyEnv\">,\n source: NodeJS.ProcessEnv = process.env,\n): string | undefined {\n if (provider.apiKey) {\n return provider.apiKey;\n }\n if (provider.apiKeyEnv) {\n const value = source[provider.apiKeyEnv];\n return value && value.trim().length > 0 ? value : undefined;\n }\n return undefined;\n}\n\nconst HTTP_FIELD_NAME = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\nconst CREDENTIAL_LIKE_NAME_PARTS = new Set([\n \"apikey\",\n \"auth\",\n \"authorization\",\n \"bearer\",\n \"credential\",\n \"cookie\",\n \"key\",\n \"password\",\n \"secret\",\n \"session\",\n \"signature\",\n \"token\",\n]);\nconst REASONING_EFFORT_ORDER = new Map(\n ReasoningEffort.options.map((effort, index) => [effort, index]),\n);\nconst MODALITY_ORDER = new Map([\"text\", \"image\", \"audio\"].map((value, index) => [value, index]));\nconst LATENCY_MODE_ORDER = new Map(\n [\"standard\", \"priority\", \"fast\"].map((value, index) => [value, index]),\n);\n\nfunction normalizeRegistryBaseUrl(value: string, providerId: string): string {\n const url = new URL(value);\n if (url.username || url.password) {\n throw new Error(`provider ${providerId} baseUrl must not contain userinfo`);\n }\n if (url.search) {\n throw new Error(\n `provider ${providerId} baseUrl must not contain a query; move query entries to defaultQuery`,\n );\n }\n if (url.hash) {\n throw new Error(`provider ${providerId} baseUrl must not contain a fragment`);\n }\n return url.toString();\n}\n\nfunction isCredentialLikeMetadataName(name: string): boolean {\n return name\n .toLowerCase()\n .split(/[-_.]/u)\n .some((part) => CREDENTIAL_LIKE_NAME_PARTS.has(part));\n}\n\nfunction normalizeHeaderMap(\n providerId: string,\n headers: Record<string, string> | undefined,\n): Record<string, string> | undefined {\n if (!headers) {\n return undefined;\n }\n const normalized: Record<string, string> = {};\n const rawByNormalized = new Map<string, string>();\n for (const [rawName, value] of Object.entries(headers)) {\n if (!HTTP_FIELD_NAME.test(rawName)) {\n throw new Error(\n `provider ${providerId} defaultHeaders contains invalid HTTP field name ${JSON.stringify(rawName)}`,\n );\n }\n const name = rawName.toLowerCase();\n const previous = rawByNormalized.get(name);\n if (previous !== undefined) {\n throw new Error(\n `provider ${providerId} defaultHeaders names ${JSON.stringify(previous)} and ${JSON.stringify(rawName)} collide after lowercase normalization`,\n );\n }\n if (name === \"authorization\") {\n throw new Error(\n `provider ${providerId} defaultHeaders must not override SDK-managed Authorization`,\n );\n }\n rawByNormalized.set(name, rawName);\n normalized[name] = value;\n }\n return normalized;\n}\n\nfunction normalizePublicHeaderNames(\n providerId: string,\n names: string[] | undefined,\n headers: Record<string, string> | undefined,\n): string[] | undefined {\n if (!names) {\n return undefined;\n }\n const normalized: string[] = [];\n const seen = new Set<string>();\n for (const rawName of names) {\n if (!HTTP_FIELD_NAME.test(rawName)) {\n throw new Error(\n `provider ${providerId} publicDefaultHeaderNames contains invalid HTTP field name ${JSON.stringify(rawName)}`,\n );\n }\n const name = rawName.toLowerCase();\n if (seen.has(name)) {\n throw new Error(\n `provider ${providerId} publicDefaultHeaderNames contains duplicate normalized name ${JSON.stringify(name)}`,\n );\n }\n if (!(name in (headers ?? {}))) {\n throw new Error(\n `provider ${providerId} publicDefaultHeaderNames declares absent defaultHeaders entry ${JSON.stringify(name)}`,\n );\n }\n if (isCredentialLikeMetadataName(name)) {\n throw new Error(\n `provider ${providerId} publicDefaultHeaderNames cannot classify credential-like name ${JSON.stringify(name)} as public`,\n );\n }\n seen.add(name);\n normalized.push(name);\n }\n return normalized;\n}\n\nfunction normalizeQueryMap(\n providerId: string,\n query: Record<string, string> | undefined,\n): Record<string, string> | undefined {\n if (!query) {\n return undefined;\n }\n for (const name of Object.keys(query)) {\n if (!name) {\n throw new Error(`provider ${providerId} defaultQuery contains an empty name`);\n }\n }\n return { ...query };\n}\n\nfunction normalizePublicQueryNames(\n providerId: string,\n names: string[] | undefined,\n query: Record<string, string> | undefined,\n): string[] | undefined {\n if (!names) {\n return undefined;\n }\n const seen = new Set<string>();\n for (const name of names) {\n if (seen.has(name)) {\n throw new Error(\n `provider ${providerId} publicDefaultQueryNames contains duplicate name ${JSON.stringify(name)}`,\n );\n }\n if (!(name in (query ?? {}))) {\n throw new Error(\n `provider ${providerId} publicDefaultQueryNames declares absent defaultQuery entry ${JSON.stringify(name)}`,\n );\n }\n if (isCredentialLikeMetadataName(name)) {\n throw new Error(\n `provider ${providerId} publicDefaultQueryNames cannot classify credential-like name ${JSON.stringify(name)} as public`,\n );\n }\n seen.add(name);\n }\n return [...names];\n}\n\nfunction normalizeRegistryProvider(provider: RegistryProvider): RegistryProvider {\n const defaultHeaders = normalizeHeaderMap(provider.id, provider.defaultHeaders);\n const defaultQuery = normalizeQueryMap(provider.id, provider.defaultQuery);\n return {\n ...provider,\n baseUrl: normalizeRegistryBaseUrl(provider.baseUrl, provider.id),\n ...(defaultHeaders === undefined ? {} : { defaultHeaders }),\n ...(defaultQuery === undefined ? {} : { defaultQuery }),\n ...(provider.publicDefaultHeaderNames === undefined\n ? {}\n : {\n publicDefaultHeaderNames: normalizePublicHeaderNames(\n provider.id,\n provider.publicDefaultHeaderNames,\n defaultHeaders,\n ),\n }),\n ...(provider.publicDefaultQueryNames === undefined\n ? {}\n : {\n publicDefaultQueryNames: normalizePublicQueryNames(\n provider.id,\n provider.publicDefaultQueryNames,\n defaultQuery,\n ),\n }),\n };\n}\n\nfunction normalizeModelPricingSchedule(\n pricing: ModelPricing | ModelPricingScheduleV1,\n): ModelPricingScheduleV1 {\n return \"default\" in pricing ? pricing : { default: pricing };\n}\n\nfunction normalizeCapabilities(capabilities: ModelCapabilitiesV1): ModelCapabilitiesV1 {\n const parsed = ModelCapabilitiesV1Schema.parse(capabilities);\n return {\n ...parsed,\n reasoning: {\n ...parsed.reasoning,\n efforts: [...parsed.reasoning.efforts].sort(\n (left, right) =>\n (REASONING_EFFORT_ORDER.get(left) ?? 0) - (REASONING_EFFORT_ORDER.get(right) ?? 0),\n ),\n },\n inputModalities: [...parsed.inputModalities].sort(\n (left, right) => (MODALITY_ORDER.get(left) ?? 0) - (MODALITY_ORDER.get(right) ?? 0),\n ),\n outputModalities: [...parsed.outputModalities].sort(\n (left, right) => (MODALITY_ORDER.get(left) ?? 0) - (MODALITY_ORDER.get(right) ?? 0),\n ),\n latencyModes: [...parsed.latencyModes].sort(\n (left, right) =>\n (LATENCY_MODE_ORDER.get(left.id) ?? 0) - (LATENCY_MODE_ORDER.get(right.id) ?? 0),\n ),\n };\n}\n\nfunction legacyModelCapabilities(\n settings: Settings,\n input: { reasoningEffort: boolean; hostedWebSearch: boolean },\n): ModelCapabilitiesV1 {\n const reasoningEfforts = input.reasoningEffort ? configuredAllowedReasoningEfforts(settings) : [];\n return normalizeCapabilities({\n reasoning: {\n upstream: input.reasoningEffort ? \"supported\" : \"unknown\",\n runnable: input.reasoningEffort,\n efforts: reasoningEfforts,\n defaultEffort: input.reasoningEffort ? settings.openaiReasoningEffort : null,\n required: false,\n },\n functionCalling: { upstream: \"unknown\", runnable: true },\n structuredOutput: { upstream: \"unknown\", runnable: false },\n hostedTools: {\n webSearch: {\n upstream: input.hostedWebSearch ? \"supported\" : \"unknown\",\n runnable: input.hostedWebSearch,\n },\n xSearch: { upstream: \"unknown\", runnable: false },\n codeExecution: { upstream: \"unknown\", runnable: false },\n },\n inputModalities: [\"text\"],\n outputModalities: [\"text\"],\n transports: {\n sse: { upstream: \"unknown\", runnable: true },\n responsesWebSocket: { upstream: \"unknown\", runnable: false },\n realtimeAudio: { upstream: \"unknown\", runnable: false },\n },\n latencyModes: [{ id: \"standard\", upstream: \"unknown\", runnable: true }],\n });\n}\n\nfunction registryCredentialSource(provider: RegistryProvider): CredentialSourceV1 {\n return provider.kind === \"codex-subscription\"\n ? { kind: \"connected_subscription\", provider: \"codex\" }\n : { kind: \"deployment\", mechanism: \"api_key\" };\n}\n\nfunction registryBilling(provider: RegistryProvider): BillingAttributionV1 {\n return provider.kind === \"codex-subscription\"\n ? { upstreamPayer: \"connected_subscription\", metering: \"external\" }\n : { upstreamPayer: \"deployment\", metering: \"opengeni_credits\" };\n}\n\nfunction builtinCredentialSource(settings: Settings): CredentialSourceV1 {\n if (settings.openaiProvider === \"azure\" && !settings.azureOpenaiApiKey) {\n return { kind: \"deployment\", mechanism: \"azure_ad_bearer\" };\n }\n return { kind: \"deployment\", mechanism: \"api_key\" };\n}\n\nfunction staticRequestMetadataForDigest(provider: ResolvedModelProvider): {\n headers: Array<{ name: string; classification: \"public\" | \"secret\"; value?: string }>;\n query: Array<{ name: string; classification: \"public\" | \"secret\"; value?: string }>;\n} {\n const publicHeaders = new Set(provider.publicDefaultHeaderNames ?? []);\n const publicQuery = new Set(provider.publicDefaultQueryNames ?? []);\n return {\n headers: Object.entries(provider.defaultHeaders ?? {})\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([name, value]) =>\n publicHeaders.has(name)\n ? { name, classification: \"public\" as const, value }\n : { name, classification: \"secret\" as const },\n ),\n query: Object.entries(provider.defaultQuery ?? {})\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([name, value]) =>\n publicQuery.has(name)\n ? { name, classification: \"public\" as const, value }\n : { name, classification: \"secret\" as const },\n ),\n };\n}\n\nfunction canonicalJson(value: unknown): string {\n const normalize = (input: unknown): unknown => {\n if (Array.isArray(input)) {\n return input.map((entry) => normalize(entry));\n }\n if (input && typeof input === \"object\") {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(input).sort()) {\n const child = (input as Record<string, unknown>)[key];\n if (child !== undefined) {\n out[key] = normalize(child);\n }\n }\n return out;\n }\n return input;\n };\n return JSON.stringify(normalize(value));\n}\n\nfunction definitionVersionFor(\n model: Omit<ConfiguredModel, \"definitionVersion\">,\n provider: ResolvedModelProvider,\n): string {\n const requestMetadata = staticRequestMetadataForDigest(provider);\n const digestInput = canonicalJson({\n schemaVersion: model.schemaVersion,\n id: model.id,\n providerId: model.providerId,\n deployment: model.deployment,\n provider: {\n adapterKind: provider.kind,\n wireApi: provider.api,\n baseUrl: provider.baseUrl ?? null,\n defaultHeaders: requestMetadata.headers,\n defaultQuery: requestMetadata.query,\n },\n credentialSource: model.credentialSource,\n billing: model.billing,\n executionLimits: model.executionLimits,\n capabilities: model.capabilities,\n pricing: model.pricing ?? null,\n });\n return `sha256:${createHash(\"sha256\")\n .update(\"opengeni:model-definition:v1\\n\", \"utf8\")\n .update(digestInput, \"utf8\")\n .digest(\"hex\")}`;\n}\n\n/**\n * The built-in provider's stable id: \"openai\" on the OpenAI platform, \"azure\"\n * on Azure. Exported because the workspace model-policy gate must attribute\n * the legacy resolveTurnModel-null fallback (which routes to this built-in\n * client) to the SAME identity the router uses — otherwise a policy blocking\n * the built-in could be bypassed through the null-resolution path.\n */\nexport function builtinProviderId(settings: Pick<Settings, \"openaiProvider\">): string {\n return settings.openaiProvider === \"azure\" ? \"azure\" : \"openai\";\n}\n\nfunction builtinProviderLabel(settings: Pick<Settings, \"openaiProvider\">): string {\n return settings.openaiProvider === \"azure\" ? \"Azure OpenAI\" : \"OpenAI\";\n}\n\n/**\n * Every provider a client may route to: the built-in OpenAI/Azure provider\n * first (id \"openai\"/\"azure\", always \"responses\"), then each registry provider\n * in declaration order. Client-construction inputs are filled from\n * the existing flat openai/azure settings for the built-in, and from the\n * registry entry for the rest. Registry ids may not collide with the built-in\n * id — validateSettings rejects that at boot.\n */\nexport function configuredProviders(settings: Settings): ResolvedModelProvider[] {\n const credentialSource = builtinCredentialSource(settings);\n const builtin: ResolvedModelProvider = {\n id: builtinProviderId(settings),\n label: builtinProviderLabel(settings),\n kind: \"api-key\",\n api: \"responses\",\n builtin: true,\n credentialSource,\n billing: { upstreamPayer: \"deployment\", metering: \"opengeni_credits\" },\n };\n if (settings.openaiProvider === \"azure\") {\n const baseUrl = settings.azureOpenaiBaseUrl ?? settings.azureOpenaiEndpoint;\n builtin.baseUrl = baseUrl ? normalizeRegistryBaseUrl(baseUrl, builtin.id) : undefined;\n builtin.apiKey = settings.azureOpenaiApiKey ?? settings.azureOpenaiAdToken;\n } else {\n builtin.baseUrl = settings.openaiBaseUrl\n ? normalizeRegistryBaseUrl(settings.openaiBaseUrl, builtin.id)\n : undefined;\n builtin.apiKey = settings.openaiApiKey;\n }\n const registry = parseModelProvidersJson(settings.modelProvidersJson).map(\n (provider): ResolvedModelProvider => ({\n id: provider.id,\n label: provider.label ?? provider.id,\n kind: provider.kind,\n api: provider.api,\n builtin: false,\n baseUrl: provider.baseUrl,\n apiKey: resolveProviderApiKey(provider),\n defaultQuery: provider.defaultQuery,\n defaultHeaders: provider.defaultHeaders,\n publicDefaultQueryNames: provider.publicDefaultQueryNames,\n publicDefaultHeaderNames: provider.publicDefaultHeaderNames,\n credentialSource: registryCredentialSource(provider),\n billing: registryBilling(provider),\n }),\n );\n return [builtin, ...registry];\n}\n\n/**\n * Pure catalog overlay for a workspace whose existing Codex connection seam\n * reports ready. This describes product/provider identity only; it does not\n * select, lease, refresh, or expose a concrete credential; those runtime\n * operations remain owned by the credential allocator.\n */\nexport function withCodexCatalogProvider(settings: Settings): Settings {\n const providers = parseModelProvidersJson(settings.modelProvidersJson);\n if (providers.some((provider) => provider.id === CODEX_PROVIDER_ID)) {\n return settings;\n }\n const provider: RegistryProvider = {\n kind: \"codex-subscription\",\n id: CODEX_PROVIDER_ID,\n label: \"Codex (ChatGPT subscription)\",\n api: \"responses\",\n baseUrl: CODEX_PROVIDER_BASE_URL,\n models: CODEX_FALLBACK_MODEL_SLUGS.map((slug) => ({\n id: `${CODEX_MODEL_ID_PREFIX}${slug}`,\n upstreamModelId: slug,\n label: slug,\n reasoningEffort: true,\n // The ChatGPT/Codex Responses backend accepts the native web_search\n // hosted tool (unlike hosted apply_patch/computer transports). Declaring\n // this here makes provider resolution truthful; the worker still applies\n // the durable session/turn policy gate before attaching it.\n hostedWebSearch: true,\n contextWindowTokens: CODEX_MODEL_CONTEXT_WINDOW_TOKENS,\n effectiveContextWindowTokens: CODEX_MODEL_EFFECTIVE_CONTEXT_WINDOW_TOKENS,\n autoCompactTokenLimit: CODEX_MODEL_AUTO_COMPACT_TOKEN_LIMIT,\n toolOutputTruncationTokens: CODEX_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS,\n })),\n };\n return { ...settings, modelProvidersJson: JSON.stringify([...providers, provider]) };\n}\n\n/**\n * The provider identity a model id resolves to, for workspace model-policy\n * evaluation — MUST agree with the real router (resolveTurnModel /\n * MultiProviderModelProvider) on every case:\n * - `codex/<slug>` → the codex-subscription provider id, ALWAYS. With no\n * active subscription the router fails loud (CodexSubscriptionUnavailableError),\n * never the built-in — so attributing by prefix is exact even against BASE\n * settings where the overlay provider is not injected.\n * - a configured model id → its configuredModels providerId (registry or built-in).\n * - anything else → the built-in id: an unknown id is the legacy\n * resolveTurnModel-null fallback, which the built-in OpenAI/Azure client\n * serves. A policy blocking the built-in must block this path too.\n */\nexport function policyProviderIdForModel(settings: Settings, modelId: string): string {\n const canonicalModelId = canonicalizeConfiguredModelId(settings, modelId);\n if (canonicalModelId.startsWith(CODEX_MODEL_ID_PREFIX)) {\n return CODEX_PROVIDER_ID;\n }\n const configured = configuredModels(settings).find((model) => model.id === canonicalModelId);\n return configured?.providerId ?? builtinProviderId(settings);\n}\n\nfunction resolvedExecutionLimits(\n settings: Settings,\n model: {\n contextWindowTokens?: number | undefined;\n effectiveContextWindowTokens?: number | undefined;\n autoCompactTokenLimit?: number | undefined;\n toolOutputTruncationTokens?: number | undefined;\n },\n): ModelExecutionLimitsV1 {\n return {\n contextWindowTokens: model.contextWindowTokens ?? settings.contextWindowTokens,\n effectiveContextWindowTokens:\n model.effectiveContextWindowTokens ?? settings.contextEffectiveWindowTokens ?? null,\n autoCompactTokenLimit:\n model.autoCompactTokenLimit ?? settings.contextAutoCompactThresholdTokens ?? null,\n toolOutputTruncationTokens:\n model.toolOutputTruncationTokens ?? settings.modelToolOutputTruncationTokens ?? null,\n };\n}\n\nfunction finalizeConfiguredModel(\n settings: Settings,\n provider: ResolvedModelProvider,\n input: Omit<ConfiguredModel, \"schemaVersion\" | \"definitionVersion\" | \"executionLimits\">,\n): ConfiguredModel {\n const modelWithoutVersion: Omit<ConfiguredModel, \"definitionVersion\"> = {\n schemaVersion: 1,\n ...input,\n executionLimits: resolvedExecutionLimits(settings, input),\n };\n return {\n ...modelWithoutVersion,\n definitionVersion: definitionVersionFor(modelWithoutVersion, provider),\n };\n}\n\nfunction assertUniqueModelIdentities(models: ConfiguredModel[]): void {\n const canonicalOwners = new Map<string, string>();\n for (const model of models) {\n const previous = canonicalOwners.get(model.id);\n if (previous !== undefined) {\n throw new Error(\n `OPENGENI_MODEL_PROVIDERS_JSON model id ${JSON.stringify(model.id)} is declared by both ${previous} and ${model.providerId}`,\n );\n }\n canonicalOwners.set(model.id, model.providerId);\n }\n\n const acceptedInputs = new Map(canonicalOwners);\n for (const model of models) {\n const ownAliases = new Set<string>();\n for (const alias of model.aliases) {\n if (ownAliases.has(alias)) {\n throw new Error(\n `OPENGENI_MODEL_PROVIDERS_JSON model ${JSON.stringify(model.id)} contains duplicate alias ${JSON.stringify(alias)}`,\n );\n }\n ownAliases.add(alias);\n const previous = acceptedInputs.get(alias);\n if (previous !== undefined) {\n throw new Error(\n `OPENGENI_MODEL_PROVIDERS_JSON alias ${JSON.stringify(alias)} for model ${JSON.stringify(model.id)} collides with model/provider ${previous}`,\n );\n }\n acceptedInputs.set(alias, model.id);\n }\n }\n}\n\n/**\n * Every model a client may use, the built-in provider's models first\n * (configuredAllowedModels-from-openai, mapped to \"responses\" with\n * hostedWebSearch/contextWindow/reasoningEffort from the flat settings), then\n * each registry provider's models (label→id, hostedWebSearch/reasoningEffort\n * default false). De-duplicated by id (first wins) so the default model stays\n * first and the built-in allow-list takes precedence over registry entries.\n */\nexport function configuredModels(settings: Settings): ConfiguredModel[] {\n const builtinId = builtinProviderId(settings);\n const builtinLabel = builtinProviderLabel(settings);\n const providers = configuredProviders(settings);\n const providerById = new Map(providers.map((provider) => [provider.id, provider]));\n const pricingSchedules = configuredModelPricingSchedules(settings);\n // The built-in (OpenAI/Azure) provider must NEVER claim a registry-namespaced\n // model id. The worker overwrites settings.openaiModel with the turn's model\n // (apps/worker agent-turn runSettings) — including a `codex/<slug>` id, or a\n // registry id like \"accounts/fireworks/models/glm-5p2\" — so without this\n // filter the built-in allow-list would emit a `{ id, providerId: <azure> }`\n // entry that, by the first-wins de-dup below, shadows the real registry /\n // codex-subscription provider and ships the id to Azure as a deployment name\n // (opaque DeploymentNotFound 404). A `<provider>/<model>`-namespaced id (it\n // contains \"/\") that a registry actually owns is never a valid Azure/OpenAI\n // deployment name, and a `codex/`-prefixed id never is either — exclude both\n // from the built-in list. A BARE id a registry merely redeclares (e.g.\n // \"gpt-5.6-sol\") is left in place so the built-in still wins it via the first-wins\n // de-dup below (preserving the documented built-in-precedence contract). When\n // a codex/ id has NO codex provider injected (no active subscription) it then\n // resolves to nothing and getModel fails loud with\n // CodexSubscriptionUnavailableError instead of mis-routing to Azure.\n const parsedRegistry = parseModelProvidersJson(settings.modelProvidersJson);\n const registryOwnedIds = new Set(\n parsedRegistry.flatMap((provider) => provider.models.map((model) => model.id)),\n );\n const registryAliases = new Set(\n parsedRegistry.flatMap((provider) => provider.models.flatMap((model) => model.aliases ?? [])),\n );\n const isRegistryNamespaced = (id: string): boolean =>\n id.startsWith(CODEX_MODEL_ID_PREFIX) ||\n registryAliases.has(id) ||\n (id.includes(\"/\") && registryOwnedIds.has(id));\n const builtinProvider = providerById.get(builtinId);\n if (!builtinProvider) {\n throw new Error(`Built-in model provider ${builtinId} is not configured`);\n }\n const out: ConfiguredModel[] = uniqueValues([\n settings.openaiModel,\n ...splitCsv(settings.openaiAllowedModels),\n ])\n .filter((id) => !isRegistryNamespaced(id))\n .map((id) => {\n const capabilities = legacyModelCapabilities(settings, {\n reasoningEffort: true,\n hostedWebSearch: settings.webSearchEnabled,\n });\n return finalizeConfiguredModel(settings, builtinProvider, {\n id,\n aliases: [],\n label: id,\n providerId: builtinId,\n providerLabel: builtinLabel,\n api: \"responses\" as const,\n upstreamModelId: id,\n deployment: { upstreamModelId: id, wireApi: \"responses\" },\n credentialSource: builtinProvider.credentialSource,\n billing: builtinProvider.billing,\n capabilities,\n ...(pricingSchedules[id] === undefined ? {} : { pricing: pricingSchedules[id] }),\n contextWindowTokens: settings.contextWindowTokens,\n toolOutputTruncationTokens: settings.modelToolOutputTruncationTokens,\n reasoningEffort: capabilities.reasoning.runnable,\n hostedWebSearch: capabilities.hostedTools.webSearch.runnable,\n });\n });\n for (const provider of parsedRegistry) {\n const providerLabel = provider.label ?? provider.id;\n const resolvedProvider = providerById.get(provider.id);\n if (!resolvedProvider) {\n throw new Error(`Registry model provider ${provider.id} is not configured`);\n }\n for (const model of provider.models) {\n const capabilities = model.capabilities\n ? normalizeCapabilities(model.capabilities)\n : legacyModelCapabilities(settings, {\n reasoningEffort: model.reasoningEffort ?? false,\n hostedWebSearch: model.hostedWebSearch ?? false,\n });\n const upstreamModelId = model.upstreamModelId ?? model.id;\n out.push(\n finalizeConfiguredModel(settings, resolvedProvider, {\n id: model.id,\n aliases: [...(model.aliases ?? [])],\n label: model.label ?? model.id,\n providerId: provider.id,\n providerLabel,\n api: provider.api,\n upstreamModelId,\n deployment: { upstreamModelId, wireApi: provider.api },\n credentialSource: resolvedProvider.credentialSource,\n billing: resolvedProvider.billing,\n capabilities,\n ...(pricingSchedules[model.id] === undefined\n ? {}\n : { pricing: pricingSchedules[model.id] }),\n ...(model.contextWindowTokens === undefined\n ? {}\n : { contextWindowTokens: model.contextWindowTokens }),\n ...(model.effectiveContextWindowTokens === undefined\n ? {}\n : { effectiveContextWindowTokens: model.effectiveContextWindowTokens }),\n ...(model.autoCompactTokenLimit === undefined\n ? {}\n : { autoCompactTokenLimit: model.autoCompactTokenLimit }),\n ...(model.toolOutputTruncationTokens === undefined\n ? {}\n : { toolOutputTruncationTokens: model.toolOutputTruncationTokens }),\n reasoningEffort: capabilities.reasoning.runnable,\n hostedWebSearch: capabilities.hostedTools.webSearch.runnable,\n }),\n );\n }\n }\n assertUniqueModelIdentities(out);\n return out;\n}\n\n/** Resolve a known canonical id or alias. Unknown strings are returned unchanged. */\nexport function canonicalizeConfiguredModelId(settings: Settings, modelId: string): string {\n const models = configuredModels(settings);\n const canonical = models.find((model) => model.id === modelId);\n if (canonical) {\n return canonical.id;\n }\n return models.find((model) => model.aliases.includes(modelId))?.id ?? modelId;\n}\n\n/**\n * Allowed model ids in selection order. Reimplemented on top of\n * configuredModels so it is the union of the built-in allow-list and every\n * registry provider's ids, de-duplicated. INVARIANT (existing callers + tests\n * depend on it): settings.openaiModel is always first, then the rest of the\n * openai allow-list, then registry ids.\n */\nexport function configuredAllowedModels(settings: Settings): string[] {\n return configuredModels(settings).map((model) => model.id);\n}\n\n/**\n * Resolve a model string to the provider that serves it and its configured\n * shape. Returns undefined when the id is not exposed (built-in allow-list nor\n * any registry provider), so the runtime can fall back to the legacy global\n * client path.\n */\nexport function resolveModelProvider(\n settings: Settings,\n modelId: string,\n): { provider: ResolvedModelProvider; model: ConfiguredModel } | undefined {\n const canonicalModelId = canonicalizeConfiguredModelId(settings, modelId);\n const model = configuredModels(settings).find((candidate) => candidate.id === canonicalModelId);\n if (!model) {\n return undefined;\n }\n const provider = configuredProviders(settings).find(\n (candidate) => candidate.id === model.providerId,\n );\n if (!provider) {\n return undefined;\n }\n return { provider, model };\n}\n\nexport type ResolveTurnExecutionPolicyV1Input = {\n /** Effective persisted turn model. Aliases are accepted and canonicalized. */\n modelId: string;\n /** Exact caller-supplied input before canonicalization, only for explicit switches. */\n requestedModelId: string | null;\n modelSource: TurnExecutionModelSourceV1;\n reasoningEffort: Settings[\"openaiReasoningEffort\"];\n reasoningSource: TurnExecutionReasoningSourceV1;\n};\n\nfunction settingsForTurnExecutionPolicy(settings: Settings, modelId: string): Settings {\n return settings.codexSubscriptionEnabled && modelId.startsWith(CODEX_MODEL_ID_PREFIX)\n ? withCodexCatalogProvider(settings)\n : settings;\n}\n\n/**\n * Build a trusted, secret-safe execution policy from the normalized catalog.\n * The Codex overlay here contains static product/provider identity only; it\n * neither proves readiness nor chooses, decrypts, leases, or exposes an account.\n */\nexport function resolveTurnExecutionPolicyV1(\n settings: Settings,\n input: ResolveTurnExecutionPolicyV1Input,\n): TurnExecutionPolicyV1 {\n const catalogSettings = settingsForTurnExecutionPolicy(settings, input.modelId);\n const productModelId = canonicalizeConfiguredModelId(catalogSettings, input.modelId);\n const resolved = resolveModelProvider(catalogSettings, productModelId);\n if (!resolved) {\n throw new Error(\"Turn execution policy model is not present in the configured catalog\");\n }\n if (\n input.requestedModelId !== null &&\n canonicalizeConfiguredModelId(catalogSettings, input.requestedModelId) !== productModelId\n ) {\n throw new Error(\"Turn execution policy requested model does not canonicalize to its product\");\n }\n return TurnExecutionPolicyV1.parse({\n schemaVersion: 1,\n productModelId,\n requestedModelId: input.requestedModelId,\n modelSource: input.modelSource,\n reasoningEffort: input.reasoningEffort,\n reasoningSource: input.reasoningSource,\n providerId: resolved.provider.id,\n upstreamModelId: resolved.model.upstreamModelId,\n wireApi: resolved.model.api,\n credentialSource: resolved.model.credentialSource,\n billing: resolved.model.billing,\n definitionVersion: resolved.model.definitionVersion,\n });\n}\n\n/**\n * Parse-time validation lives in @opengeni/contracts; this verifier binds a\n * present snapshot to the current executable definition and exact turn row.\n * Any deployment/provider drift fails before a provider or compaction call.\n */\nexport function assertTurnExecutionPolicyMatchesConfigV1(\n settings: Settings,\n policy: TurnExecutionPolicyV1,\n expected: {\n modelId: string;\n reasoningEffort: Settings[\"openaiReasoningEffort\"];\n },\n): {\n policy: TurnExecutionPolicyV1;\n provider: ResolvedModelProvider;\n model: ConfiguredModel;\n} {\n const parsed = TurnExecutionPolicyV1.parse(policy);\n const catalogSettings = settingsForTurnExecutionPolicy(settings, parsed.productModelId);\n const canonicalExpectedModel = canonicalizeConfiguredModelId(catalogSettings, expected.modelId);\n if (\n parsed.productModelId !== canonicalExpectedModel ||\n parsed.reasoningEffort !== expected.reasoningEffort\n ) {\n throw new Error(\"Turn execution policy does not match the accepted turn model/reasoning\");\n }\n if (\n parsed.requestedModelId !== null &&\n canonicalizeConfiguredModelId(catalogSettings, parsed.requestedModelId) !==\n parsed.productModelId\n ) {\n throw new Error(\"Turn execution policy requested model does not match its product model\");\n }\n const resolved = resolveModelProvider(catalogSettings, parsed.productModelId);\n if (!resolved) {\n throw new Error(\"Turn execution policy model is no longer configured\");\n }\n const mismatched =\n parsed.providerId !== resolved.provider.id ||\n parsed.upstreamModelId !== resolved.model.upstreamModelId ||\n parsed.wireApi !== resolved.model.api ||\n parsed.definitionVersion !== resolved.model.definitionVersion ||\n canonicalJson(parsed.credentialSource) !== canonicalJson(resolved.model.credentialSource) ||\n canonicalJson(parsed.billing) !== canonicalJson(resolved.model.billing);\n if (mismatched) {\n throw new Error(\"Turn execution policy does not match the current provider definition\");\n }\n return { policy: parsed, provider: resolved.provider, model: resolved.model };\n}\n\n/**\n * Effective per-model pricing schedules. Merge order (later wins): built-in\n * flat defaults → registry model flat/scheduled pricing → explicit legacy flat\n * OPENGENI_MODEL_PRICING_JSON. The explicit legacy map intentionally replaces\n * a registry schedule with one flat default so its historical precedence stays\n * exact.\n */\nexport function configuredModelPricingSchedules(\n settings: Settings,\n): Record<string, ModelPricingScheduleV1> {\n const defaults = Object.fromEntries(\n Object.entries(defaultModelPricing).map(([model, pricing]) => [model, { default: pricing }]),\n );\n const registry: Record<string, ModelPricingScheduleV1> = {};\n for (const provider of parseModelProvidersJson(settings.modelProvidersJson)) {\n for (const model of provider.models) {\n if (model.pricing) {\n registry[model.id] = normalizeModelPricingSchedule(model.pricing);\n }\n }\n }\n const configured = Object.fromEntries(\n Object.entries(parseModelPricingJson(settings.modelPricingJson)).map(([model, pricing]) => [\n model,\n { default: pricing },\n ]),\n );\n return {\n ...defaults,\n ...registry,\n ...configured,\n };\n}\n\n/** Legacy flat projection: returns the default/below-threshold price. */\nexport function configuredModelPricing(settings: Settings): Record<string, ModelPricing> {\n return Object.fromEntries(\n Object.entries(configuredModelPricingSchedules(settings)).map(([model, schedule]) => [\n model,\n schedule.default,\n ]),\n );\n}\n\n/** Select the per-provider-request price at an exact input-token threshold. */\nexport function selectModelPricing(\n schedule: ModelPricingScheduleV1,\n inputTokens: number,\n): ModelPricing {\n const normalizedInputTokens = Math.max(0, Math.floor(inputTokens));\n let selected = schedule.default;\n for (const tier of schedule.inputTokenTiers ?? []) {\n if (normalizedInputTokens < tier.minimumInputTokens) {\n break;\n }\n selected = tier.pricing;\n }\n return selected;\n}\n\n/**\n * Usable input-token budget: an explicit model-catalog effective window when\n * available, otherwise the deployment window minus its output reserve.\n */\nexport function contextInputBudgetTokens(\n settings: Pick<\n Settings,\n \"contextWindowTokens\" | \"contextEffectiveWindowTokens\" | \"contextReservedOutputTokens\"\n >,\n): number {\n if (settings.contextEffectiveWindowTokens !== undefined) {\n return Math.min(settings.contextWindowTokens, settings.contextEffectiveWindowTokens);\n }\n return Math.max(0, settings.contextWindowTokens - settings.contextReservedOutputTokens);\n}\n\n/**\n * Apply the resolved provider/model's context policy to one turn. Registry\n * metadata is authoritative when present; deployment defaults remain the\n * fallback for models that do not declare their own limits.\n */\nexport function settingsWithResolvedModelContext(\n settings: Settings,\n model: Pick<\n ConfiguredModel,\n | \"contextWindowTokens\"\n | \"effectiveContextWindowTokens\"\n | \"autoCompactTokenLimit\"\n | \"toolOutputTruncationTokens\"\n >,\n): Settings {\n const contextWindowTokens = model.contextWindowTokens ?? settings.contextWindowTokens;\n return {\n ...settings,\n contextWindowTokens,\n ...(model.effectiveContextWindowTokens === undefined\n ? {}\n : {\n contextEffectiveWindowTokens: Math.min(\n contextWindowTokens,\n model.effectiveContextWindowTokens,\n ),\n }),\n ...(model.autoCompactTokenLimit === undefined\n ? {}\n : { contextAutoCompactThresholdTokens: model.autoCompactTokenLimit }),\n ...(model.toolOutputTruncationTokens === undefined\n ? {}\n : { modelToolOutputTruncationTokens: model.toolOutputTruncationTokens }),\n };\n}\n\nexport function configuredStaticUsageLimits(settings: Settings): StaticUsageLimitsConfig {\n return parseStaticUsageLimitsJson(settings.staticUsageLimitsJson);\n}\n\nexport function configuredEntitlements(settings: Settings): EntitlementsConfig {\n if (settings.entitlementsMode === \"none\") {\n return {};\n }\n const configured = parseStaticEntitlementsJson(settings.staticEntitlementsJson);\n if (settings.entitlementsMode === \"static\") {\n return configured;\n }\n return {\n \"managed.auth.email_password\": true,\n \"managed.billing.prepaid_credits\": settings.billingMode === \"stripe\",\n \"managed.api_keys\": true,\n \"managed.workspaces\": true,\n \"managed.github_app\": Boolean(settings.githubAppId && settings.githubAppPrivateKey),\n ...configured,\n };\n}\n\nexport function calculateModelUsageCostMicros(\n settings: Settings,\n model: string,\n usage: ModelUsageInput,\n): number {\n const schedule = configuredModelPricingSchedules(settings)[model];\n if (!schedule) {\n throw new Error(`Missing model pricing for ${model}`);\n }\n const entries =\n usage.requestUsageEntries && usage.requestUsageEntries.length > 0\n ? usage.requestUsageEntries\n : [usage];\n const rawCostByPricing = new Map<ModelPricing, number>();\n for (const entry of entries) {\n const pricing = selectModelPricing(schedule, positiveInt(entry.inputTokens));\n rawCostByPricing.set(\n pricing,\n (rawCostByPricing.get(pricing) ?? 0) + calculateEntryCostMicros(pricing, entry),\n );\n }\n let total = 0;\n for (const [pricing, rawCost] of rawCostByPricing) {\n const marginBps = pricing.marginBps ?? 0;\n total += Math.ceil((rawCost * (10_000 + marginBps)) / 10_000);\n }\n return total;\n}\n\nexport function configuredAllowedReasoningEfforts(\n settings: Settings,\n): Array<z.infer<typeof ReasoningEffort>> {\n return uniqueValues([\n settings.openaiReasoningEffort,\n ...splitCsv(settings.openaiAllowedReasoningEfforts),\n ]).map((value) => ReasoningEffort.parse(value));\n}\n\n/**\n * Decodes OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY (base64, exactly 32 bytes) for\n * AES-256-GCM workspace environment value encryption. Returns null when unset.\n * Throws naming only the env var, never echoing its value.\n */\nexport function environmentsEncryptionKeyBytes(settings: Settings): Uint8Array | null {\n if (!settings.environmentsEncryptionKey) {\n return null;\n }\n const decoded = Buffer.from(settings.environmentsEncryptionKey, \"base64\");\n if (decoded.length !== 32) {\n throw new Error(\n \"OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY must be base64 for exactly 32 bytes (generate with: openssl rand -base64 32)\",\n );\n }\n return new Uint8Array(decoded);\n}\n\n/**\n * Build one structurally compatible connection policy for both\n * `@temporalio/client` and `@temporalio/worker`. An API key or any custom TLS\n * material enables TLS automatically; the explicit flag covers server-auth TLS\n * without credentials. Secret values are never included in validation errors.\n */\nexport function temporalConnectionOptions(settings: Settings): TemporalConnectionOptions {\n const apiKey = settings.temporalApiKey?.trim() || undefined;\n const serverNameOverride = settings.temporalTlsServerName?.trim() || undefined;\n const rootCa = decodeTemporalTlsMaterial(\n settings.temporalTlsRootCaCertificateBase64,\n \"OPENGENI_TEMPORAL_TLS_ROOT_CA_CERTIFICATE_BASE64\",\n );\n const clientCertificate = decodeTemporalTlsMaterial(\n settings.temporalTlsClientCertificateBase64,\n \"OPENGENI_TEMPORAL_TLS_CLIENT_CERTIFICATE_BASE64\",\n );\n const clientPrivateKey = decodeTemporalTlsMaterial(\n settings.temporalTlsClientPrivateKeyBase64,\n \"OPENGENI_TEMPORAL_TLS_CLIENT_PRIVATE_KEY_BASE64\",\n );\n\n if (Boolean(clientCertificate) !== Boolean(clientPrivateKey)) {\n throw new Error(\n \"OPENGENI_TEMPORAL_TLS_CLIENT_CERTIFICATE_BASE64 and \" +\n \"OPENGENI_TEMPORAL_TLS_CLIENT_PRIVATE_KEY_BASE64 must both be set or both omitted\",\n );\n }\n\n const tls: TemporalTlsConnectionConfig = {};\n if (serverNameOverride) {\n tls.serverNameOverride = serverNameOverride;\n }\n if (rootCa) {\n tls.serverRootCACertificate = rootCa;\n }\n if (clientCertificate && clientPrivateKey) {\n tls.clientCertPair = { crt: clientCertificate, key: clientPrivateKey };\n }\n const hasCustomTls = Object.keys(tls).length > 0;\n const tlsEnabled = settings.temporalTlsEnabled || Boolean(apiKey) || hasCustomTls;\n\n return {\n address: settings.temporalHost,\n ...(tlsEnabled ? { tls: hasCustomTls ? tls : true } : {}),\n ...(apiKey ? { apiKey } : {}),\n };\n}\n\nfunction decodeTemporalTlsMaterial(\n value: string | undefined,\n settingName: string,\n): Uint8Array | undefined {\n // RFC 2045 base64 commonly arrives wrapped at 76 columns. Kubernetes\n // stringData and external secret stores preserve those line breaks, so\n // normalize whitespace before applying the strict alphabet/canonical check.\n const encoded = value?.replace(/\\s/g, \"\");\n if (!encoded) {\n return undefined;\n }\n if (!/^[A-Za-z0-9+/]+={0,2}$/.test(encoded) || encoded.length % 4 === 1) {\n throw new Error(`${settingName} must contain valid base64`);\n }\n const decoded = Buffer.from(encoded, \"base64\");\n const canonical = decoded.toString(\"base64\").replace(/=+$/, \"\");\n if (decoded.length === 0 || canonical !== encoded.replace(/=+$/, \"\")) {\n throw new Error(`${settingName} must contain valid base64`);\n }\n return new Uint8Array(decoded);\n}\n\n/**\n * The connection `search_path` for OpenGeni's db handles + the managed-auth pool\n * (Step I, §7.8 runtime half). Returns `undefined` when `dbSchema` is unset\n * (standalone) so no `search_path` startup parameter is sent and the server\n * default (`public`) applies — byte-for-byte today's behavior. When `dbSchema`\n * is set (embedded), returns `\"<schema>,opengeni_private,public\"` — `public`\n * stays LAST so `gen_random_uuid()` (pgcrypto) and the `vector` type still\n * resolve (the schema-isolation contract live footgun). `opengeni_private` is on the path so the\n * RLS GUC-reader helpers resolve when referenced unqualified.\n */\nexport function dbSearchPath(settings: Pick<Settings, \"dbSchema\">): string | undefined {\n const schema = settings.dbSchema?.trim();\n if (!schema) {\n return undefined;\n }\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(schema)) {\n throw new Error(`OPENGENI_DB_SCHEMA is not a valid Postgres identifier: ${schema}`);\n }\n return `${schema},opengeni_private,public`;\n}\n\nexport function collectGitIdentityEnvironment(settings: Settings): Record<string, string> {\n return Object.fromEntries(\n Object.entries({\n GIT_AUTHOR_NAME: settings.gitAuthorName,\n GIT_AUTHOR_EMAIL: settings.gitAuthorEmail,\n GIT_COMMITTER_NAME: settings.gitCommitterName ?? settings.gitAuthorName,\n GIT_COMMITTER_EMAIL: settings.gitCommitterEmail ?? settings.gitAuthorEmail,\n }).filter(\n (entry): entry is [string, string] =>\n typeof entry[1] === \"string\" && entry[1].trim().length > 0,\n ),\n );\n}\n\nconst DEFAULT_SANDBOX_PATH = \"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\";\n\nfunction prependPathEntry(pathValue: string | undefined, entry: string): string {\n const parts = (pathValue ?? DEFAULT_SANDBOX_PATH).split(\":\").filter(Boolean);\n return [entry, ...parts.filter((part) => part !== entry)].join(\":\");\n}\n\n/**\n * The STABLE run-scoped sandbox environment: the subset of a run's box-manifest\n * environment that is IDENTICAL whether the box is first warmed by the worker\n * TURN or by an API-direct ATTACH (viewer / Channel-A / desktop / terminal). It\n * is the layered base every cold box must be created with so a later turn's\n * agent-manifest apply finds an EMPTY environment delta in the SDK's\n * `validateNoEnvironmentDelta` (which throws \"Live sandbox sessions cannot change\n * manifest environment variables\" on ANY key the agent declares that the box's\n * manifest lacks or carries a different value for).\n *\n * Precedence (lowest → highest): deployment allowlist (`collectSandboxEnvironment`)\n * < git identity (`collectGitIdentityEnvironment`) < the session's attached\n * workspace environment < the backend-aware HOME default. Reserved-name validation\n * at write time keeps workspace values from colliding with platform entries.\n *\n * DELIBERATELY EXCLUDES the per-run, ROTATING git provider token VALUES that\n * `sandboxEnvironmentForRun` mints when a repository resource is\n * attached: that token is minted FRESH per call, so it is not a stable, attach-\n * reproducible value and must not be part of the shared base. Under the token-\n * broker (B1) token VALUES never ride the manifest at all — they are seeded to\n * FILES inside the box and git/provider CLI auth reads those files. What IS stable\n * and lives here for provisioned boxes are the token directory / GitHub alias\n * FILE PATH and wrapper PATH entries: constants derived from HOME, so they\n * appear IDENTICALLY on BOTH the turn AND every attach manifest (the SDK's\n * per-turn provided-session env delta stays empty even as tokens rotate). These\n * helper pointers are deliberately not added for selfhosted/local/none because\n * the platform never mints or seeds git provider tokens there. The attach\n * surfaces have only the `Session` (no repo resources) and so never seed a token,\n * but unwritten files simply yield no auth; the BLOCKING attach-vs-turn error\n * this helper fixes is for the common (no-repo) and workspace-environment-attached\n * provisioned-box cases.\n */\nexport function stableSandboxEnvironmentForRun(\n settings: Settings,\n workspaceEnvironment: Record<string, string> = {},\n options: { workspaceId?: string } = {},\n): Record<string, string> {\n const environment: Record<string, string> = {\n ...collectSandboxEnvironment(settings),\n ...collectGitIdentityEnvironment(settings),\n ...workspaceEnvironment,\n };\n // Backend-aware HOME: a provisioned box (docker + every cloud provider) runs the\n // agent under the descriptor's workspaceRoot. `local` runs in-process as the host\n // unix user (keep its real $HOME); `none` has no box.\n const descriptor = CAPABILITY_DESCRIPTORS[settings.sandboxBackend];\n if (settings.sandboxBackend !== \"none\" && settings.sandboxBackend !== \"local\") {\n environment.HOME ??= descriptor.workspaceRoot;\n }\n // TOKEN-BROKER (B1): the STABLE credential FILE PATHS and CLI wrapper PATH for\n // provisioned boxes only. Constants derived from the resolved HOME (falling\n // back to the descriptor workspaceRoot), so they are parity-safe — they join\n // the shared base and therefore appear IDENTICALLY on BOTH the worker-turn\n // manifest AND every API-direct attach manifest. Only PATHS are stable; token\n // VALUES live exclusively in files that runtime seeds off-manifest.\n const provisionedGitHelperBackend =\n settings.sandboxBackend !== \"none\" &&\n settings.sandboxBackend !== \"local\" &&\n settings.sandboxBackend !== \"selfhosted\";\n if (provisionedGitHelperBackend) {\n const home = environment.HOME ?? descriptor.workspaceRoot;\n environment.OPENGENI_GIT_CREDENTIALS_DIR ??= `${home}/.opengeni/git-credentials`;\n environment.OPENGENI_GIT_TOKEN_FILE ??= `${home}/.opengeni/git-token`;\n environment.OPENGENI_GIT_CLI_WRAPPER_DIR ??= `${home}/.opengeni/bin`;\n environment.PATH = prependPathEntry(environment.PATH, environment.OPENGENI_GIT_CLI_WRAPPER_DIR);\n }\n if (settings.toolspaceEnabled) {\n environment.OPENGENI_TOOLSPACE_TOKEN_FILE ??= `${environment.HOME ?? descriptor.workspaceRoot}/.opengeni/toolspace-token`;\n if (settings.ogtoolPackageSpec) {\n environment.OPENGENI_OGTOOL_PACKAGE_SPEC ??= settings.ogtoolPackageSpec;\n }\n if (options.workspaceId) {\n environment.OPENGENI_TOOLSPACE_URL ??= firstPartyMcpWorkspaceUrl(\n settings,\n options.workspaceId,\n );\n }\n }\n return environment;\n}\n\n/**\n * Whether a resource set carries a GitHub-App-connected repository (installation\n * + repository ids present) — the SAME predicate the worker turn uses to decide\n * whether it declares the stable git-auth pointers. Attach surfaces call this so\n * an attach-warmed cold box carries the IDENTICAL manifest env a later repo turn\n * declares (env parity — see applyGitAuthPointerEnvironment).\n */\nexport function hasGitHubRepositorySelection(\n resources: ReadonlyArray<{\n kind: string;\n provider?: unknown;\n installationId?: unknown;\n repositoryId?: unknown;\n githubInstallationId?: unknown;\n githubRepositoryId?: unknown;\n }>,\n): boolean {\n const positive = (value: unknown): boolean =>\n (typeof value === \"number\" && Number.isInteger(value) && value > 0) ||\n (typeof value === \"string\" && /^\\d+$/.test(value) && Number(value) > 0);\n return resources.some(\n (resource) =>\n resource.kind === \"repository\" &&\n ((positive(resource.githubInstallationId) && positive(resource.githubRepositoryId)) ||\n (resource.provider === \"github\" &&\n positive(resource.installationId) &&\n positive(resource.repositoryId))),\n );\n}\n\nexport function hasGitCredentialRepositorySelection(\n resources: ReadonlyArray<{\n kind: string;\n provider?: unknown;\n githubInstallationId?: unknown;\n githubRepositoryId?: unknown;\n }>,\n): boolean {\n return resources.some(\n (resource) =>\n resource.kind === \"repository\" &&\n (resource.provider === \"github\" ||\n resource.provider === \"gitlab\" ||\n resource.provider === \"azure_devops\" ||\n hasGitHubRepositorySelection([resource])),\n );\n}\n\n/**\n * TOKEN-BROKER (B1) parity: the STABLE git-auth POINTER environment a\n * repo-attached run declares — GIT_ASKPASS (a fixed path under HOME; the script\n * itself is provisioned at box setup), GIT_TERMINAL_PROMPT, and the GitHub-App\n * bot identity fallbacks. NO rotating value rides here (the token lives in the\n * file behind the askpass), so the layer is attach-reproducible and MUST be\n * applied identically by the worker turn (sandboxEnvironmentForRun) AND every\n * API-direct attach surface that can cold-create the box (viewer attach,\n * channel-A ops). A box cold-created WITHOUT this layer kills the next repo\n * turn: the turn's manifest declares these keys, the box's env lacks them, and\n * the SDK's provided-session guard throws \"Live sandbox sessions cannot change\n * manifest environment variables\" (observed live: an open session page's viewer\n * attach won the cold-create race and the first turn died).\n *\n * Mutates and returns `environment`. Identity fallbacks preserve values already\n * present (the deployment git-identity allowlist wins over the bot identity).\n */\nexport function applyGitAuthPointerEnvironment(\n environment: Record<string, string>,\n identity: { name: string; email: string } | null,\n): Record<string, string> {\n environment.GIT_ASKPASS = `${environment.HOME ?? \"/workspace\"}/.opengeni/askpass`;\n environment.GIT_TERMINAL_PROMPT = \"0\";\n if (identity) {\n environment.GIT_AUTHOR_NAME = environment.GIT_AUTHOR_NAME || identity.name;\n environment.GIT_AUTHOR_EMAIL = environment.GIT_AUTHOR_EMAIL || identity.email;\n environment.GIT_COMMITTER_NAME = environment.GIT_COMMITTER_NAME || identity.name;\n environment.GIT_COMMITTER_EMAIL = environment.GIT_COMMITTER_EMAIL || identity.email;\n }\n return environment;\n}\n\nexport type StartupRetryOptions = {\n attempts?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n onRetry?: (event: {\n label: string;\n attempt: number;\n attempts: number;\n delayMs: number;\n error: unknown;\n }) => void;\n};\n\nexport function startupRetryOptions(\n settings: Settings,\n): Required<Omit<StartupRetryOptions, \"onRetry\">> {\n return {\n attempts: settings.startupDependencyRetryAttempts,\n initialDelayMs: settings.startupDependencyRetryInitialDelayMs,\n maxDelayMs: settings.startupDependencyRetryMaxDelayMs,\n };\n}\n\nexport async function retryStartupDependency<T>(\n label: string,\n operation: () => Promise<T>,\n options: StartupRetryOptions = {},\n): Promise<T> {\n const attempts = Math.max(1, Math.floor(options.attempts ?? 30));\n const initialDelayMs = Math.max(0, Math.floor(options.initialDelayMs ?? 1000));\n const maxDelayMs = Math.max(initialDelayMs, Math.floor(options.maxDelayMs ?? 5000));\n for (let attempt = 1; attempt <= attempts; attempt += 1) {\n try {\n return await operation();\n } catch (error) {\n if (attempt >= attempts) {\n throw error;\n }\n const delayMs = Math.min(maxDelayMs, initialDelayMs * 2 ** (attempt - 1));\n options.onRetry?.({ label, attempt, attempts, delayMs, error });\n await delay(delayMs);\n }\n }\n throw new Error(`unreachable startup retry state for ${label}`);\n}\n\nexport function sandboxEnvironmentVariableNames(settings: Settings): string[] {\n const profiles = sandboxPreparationProfileNames(settings);\n const names: string[] = [];\n for (const profile of profiles) {\n names.push(...sandboxPreparationProfiles[profile]!.env);\n }\n names.push(...splitCsv(settings.sandboxEnvAllowlist));\n return uniqueEnvNames(names, \"sandbox env\");\n}\n\nexport function sandboxLifecycleHookIds(settings: Settings): string[] {\n const ids: string[] = [];\n for (const profile of sandboxPreparationProfileNames(settings)) {\n ids.push(...sandboxPreparationProfiles[profile]!.hooks);\n }\n return uniqueValues(ids);\n}\n\nfunction sandboxPreparationProfileNames(settings: Settings): string[] {\n const profiles = splitCsv(settings.sandboxPreparationProfiles).map((value) =>\n value.toLowerCase(),\n );\n if (profiles.includes(\"none\")) {\n if (profiles.length > 1) {\n throw new Error(\n \"OPENGENI_SANDBOX_PREPARATION_PROFILES cannot combine none with other profiles\",\n );\n }\n return [\"none\"];\n }\n for (const profile of profiles) {\n if (!sandboxPreparationProfiles[profile]) {\n throw new Error(`Unknown sandbox preparation profile ${profile}`);\n }\n }\n return profiles;\n}\n\nexport function parseExposedPorts(raw: string): number[] {\n return splitCsv(raw).map((value) => {\n const port = Number(value);\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(\"OPENGENI_DOCKER_EXPOSED_PORTS must contain TCP port numbers\");\n }\n return port;\n });\n}\n\nexport function parseMcpServers(raw: string | undefined): unknown[] | undefined {\n if (!raw) {\n return undefined;\n }\n try {\n const parsed = JSON.parse(raw);\n if (!Array.isArray(parsed)) {\n throw new Error(\"value must be a JSON array\");\n }\n return parsed;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`OPENGENI_MCP_SERVERS must be a JSON array: ${message}`, { cause: error });\n }\n}\n\nexport function parseModelPricingJson(raw: string): Record<string, ModelPricing> {\n if (!raw.trim() || raw.trim() === \"{}\") {\n return {};\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`OPENGENI_MODEL_PRICING_JSON must be valid JSON: ${message}`, { cause: error });\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(\"OPENGENI_MODEL_PRICING_JSON must be a JSON object keyed by model name\");\n }\n const out: Record<string, ModelPricing> = {};\n for (const [model, value] of Object.entries(parsed)) {\n if (!model.trim()) {\n throw new Error(\"OPENGENI_MODEL_PRICING_JSON contains an empty model name\");\n }\n out[model] = ModelPricingSchema.parse(value);\n }\n return out;\n}\n\n// --- sandbox warm-rate table (P2.1) ---\n// Per-backend usd_micros/sec, parsed from sandboxWarmRateMicrosPerSecondJson the\n// same way model pricing is. An empty {} (the default) means no warm-cost is\n// debited — warm-seconds are still metered for audit, just at rate 0.\nexport function parseSandboxWarmRateJson(raw: string): Record<string, number> {\n if (!raw.trim() || raw.trim() === \"{}\") {\n return {};\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(\n `OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON must be valid JSON: ${message}`,\n { cause: error },\n );\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(\n \"OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON must be a JSON object keyed by backend name\",\n );\n }\n const out: Record<string, number> = {};\n for (const [backend, value] of Object.entries(parsed)) {\n if (!backend.trim()) {\n throw new Error(\n \"OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON contains an empty backend name\",\n );\n }\n const rate = typeof value === \"number\" ? value : Number(value);\n if (!Number.isFinite(rate) || rate < 0) {\n throw new Error(\n `OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON rate for ${backend} must be a non-negative number`,\n );\n }\n out[backend] = rate;\n }\n return out;\n}\n\n// Resolve the warm rate (usd_micros/sec) for a backend; 0 when the backend has no\n// configured rate (the box is metered in seconds but not cost-debited).\nexport function sandboxWarmRateMicrosPerSecond(settings: Settings, backend: string): number {\n const table = parseSandboxWarmRateJson(settings.sandboxWarmRateMicrosPerSecondJson);\n return table[backend] ?? 0;\n}\n\n/**\n * Parse + validate the extra-provider registry JSON. `[]` (or empty/whitespace)\n * yields an empty list. Surfaces JSON and zod errors prefixed with the env-var\n * name so a malformed registry fails fast at boot (validateSettings calls this).\n */\nexport function parseModelProvidersJson(raw: string): RegistryProvider[] {\n if (!raw.trim() || raw.trim() === \"[]\") {\n return [];\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`OPENGENI_MODEL_PROVIDERS_JSON must be valid JSON: ${message}`, {\n cause: error,\n });\n }\n if (!Array.isArray(parsed)) {\n throw new Error(\"OPENGENI_MODEL_PROVIDERS_JSON must be a JSON array of providers\");\n }\n return parsed.map((entry, index) => {\n const result = RegistryProviderSchema.safeParse(entry);\n if (!result.success) {\n throw new Error(\n `OPENGENI_MODEL_PROVIDERS_JSON provider[${index}] is invalid: ${result.error.message}`,\n );\n }\n try {\n return normalizeRegistryProvider(result.data);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`OPENGENI_MODEL_PROVIDERS_JSON provider[${index}] is invalid: ${message}`, {\n cause: error,\n });\n }\n });\n}\n\nexport function parseIntegrationsOauthClientsJson(\n raw: string | undefined,\n): Record<string, IntegrationOAuthClientConfig> {\n if (!raw?.trim() || raw.trim() === \"{}\") {\n return {};\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`OPENGENI_INTEGRATIONS_OAUTH_CLIENTS_JSON must be valid JSON: ${message}`, {\n cause: error,\n });\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(\n \"OPENGENI_INTEGRATIONS_OAUTH_CLIENTS_JSON must be a JSON object keyed by authorization-server issuer or URL\",\n );\n }\n const out: Record<string, IntegrationOAuthClientConfig> = {};\n for (const [key, value] of Object.entries(parsed)) {\n if (!key.trim()) {\n throw new Error(\"OPENGENI_INTEGRATIONS_OAUTH_CLIENTS_JSON contains an empty issuer key\");\n }\n const result = IntegrationOAuthClientConfigSchema.safeParse(value);\n if (!result.success) {\n throw new Error(\n `OPENGENI_INTEGRATIONS_OAUTH_CLIENTS_JSON client for ${key} is invalid: ${result.error.message}`,\n );\n }\n out[key] = result.data;\n }\n return out;\n}\n\nexport function parseStaticUsageLimitsJson(raw: string): StaticUsageLimitsConfig {\n if (!raw.trim() || raw.trim() === \"{}\") {\n return {};\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`OPENGENI_STATIC_USAGE_LIMITS_JSON must be valid JSON: ${message}`, {\n cause: error,\n });\n }\n return StaticUsageLimits.parse(parsed);\n}\n\nexport function parseStaticEntitlementsJson(raw: string): EntitlementsConfig {\n if (!raw.trim() || raw.trim() === \"{}\") {\n return {};\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`OPENGENI_STATIC_ENTITLEMENTS_JSON must be valid JSON: ${message}`, {\n cause: error,\n });\n }\n return Entitlements.parse(parsed);\n}\n\nfunction calculateEntryCostMicros(pricing: ModelPricing, entry: ModelUsageInput): number {\n const inputTokens = positiveInt(entry.inputTokens);\n const outputTokens = positiveInt(entry.outputTokens);\n const cachedTokens = Math.min(inputTokens, cachedInputTokens(entry));\n const uncachedInputTokens = Math.max(0, inputTokens - cachedTokens);\n const cachedInputRate =\n pricing.cachedInputMicrosPerMillionTokens ?? pricing.inputMicrosPerMillionTokens;\n return (\n Math.ceil((uncachedInputTokens * pricing.inputMicrosPerMillionTokens) / 1_000_000) +\n Math.ceil((cachedTokens * cachedInputRate) / 1_000_000) +\n Math.ceil((outputTokens * pricing.outputMicrosPerMillionTokens) / 1_000_000)\n );\n}\n\nfunction cachedInputTokens(entry: ModelUsageInput): number {\n const details = Array.isArray(entry.inputTokensDetails)\n ? entry.inputTokensDetails\n : entry.inputTokensDetails\n ? [entry.inputTokensDetails]\n : [];\n let total = 0;\n for (const detail of details) {\n total +=\n positiveInt(detail.cached_tokens) +\n positiveInt(detail.cachedInputTokens) +\n positiveInt(detail.cached_input_tokens);\n }\n return total;\n}\n\nfunction positiveInt(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;\n}\n\nfunction ensureBuiltInMcpServers(settings: Settings): Settings[\"mcpServers\"] {\n const existing = settings.mcpServers.filter((server) => server.id !== \"opengeni\");\n const firstPartyMcpUrl = firstPartyMcpServerUrl(settings);\n const firstPartyDocsMcpUrl = firstPartyDocumentsMcpServerUrl(firstPartyMcpUrl);\n const hasFiles = existing.some((server) => server.id === \"files\");\n const hasDocs = existing.some((server) => server.id === \"docs\");\n return [\n {\n id: \"opengeni\",\n name: \"OpenGeni\",\n url: firstPartyMcpUrl,\n // The opengeni server's tools/list response is permission-scoped: it\n // varies by the calling session's delegated grant (e.g. a manager\n // session sees sessions_*/environment_* tools that a worker session\n // does not). The OpenAI Agents SDK caches tools/list in a process-global\n // map keyed only by the MCP server name, which is identical for every\n // session in the worker process. Caching here would let the first\n // session to warm the cache dictate what every later session sees,\n // regardless of permissions. tools/list is a cheap per-turn call, so we\n // never cache it. (The files server pins allowedTools to a single\n // permission-invariant tool and docs is already uncached, so both stay\n // safe to cache / leave as-is.)\n cacheToolsList: false,\n },\n ...(hasFiles\n ? []\n : [\n {\n id: \"files\",\n name: \"Files\",\n url: firstPartyMcpUrl,\n allowedTools: [\"files_get_download_url\"],\n cacheToolsList: true,\n },\n ]),\n ...(hasDocs\n ? []\n : [\n {\n id: \"docs\",\n name: \"Document Search\",\n url: firstPartyDocsMcpUrl,\n allowedTools: [\n \"search_documents\",\n \"fetch_document_chunk\",\n \"list_document_bases\",\n \"knowledge_search\",\n \"knowledge_fetch\",\n \"memory_search\",\n \"memory_propose\",\n ],\n cacheToolsList: false,\n },\n ]),\n ...existing,\n ];\n}\n\n/**\n * The base URL of OpenGeni's own first-party MCP endpoint, as a `{workspaceId}`\n * template — the SINGLE source of truth for the `opengeniMcpUrl`-or-loopback\n * decision. Every site that needs the first-party MCP base (config's tool\n * registry here, and the worker-side `firstPartyMcpServerUrlForRun` /\n * `firstPartyMcpUrls` in @opengeni/runtime) MUST route through this so the\n * default lives in exactly one place.\n *\n * BINDING CONTRACT (`opengeniMcpUrl`):\n * - STANDALONE (unset): falls back to the loopback default\n * `http://127.0.0.1:${apiPort}/v1/workspaces/{workspaceId}/mcp` — the worker\n * and API are in/next to the same host:port, so loopback resolves the\n * workspace-scoped MCP. Byte-for-byte today's behavior.\n * - EMBEDDED / MOUNTED (must set): when OpenGeni's API is mounted as a host\n * sub-app under a prefix (e.g. `https://host/og/v1/...`), the loopback\n * default is WRONG — the worker runs in the host process and `127.0.0.1:\n * ${apiPort}` is not where the mounted, sandbox-routable MCP lives. The host\n * MUST set `OPENGENI_MCP_URL` to the externally/sandbox-routable base (a\n * `{workspaceId}` template, or a concrete base that gets re-scoped). This is\n * the one binding a mounted embed cannot leave unset.\n */\nexport function firstPartyMcpBaseUrl(settings: Settings): string {\n return (\n settings.opengeniMcpUrl ??\n `http://127.0.0.1:${settings.apiPort}/v1/workspaces/{workspaceId}/mcp`\n );\n}\n\nexport function firstPartyMcpWorkspaceUrl(settings: Settings, workspaceId: string): string {\n const raw = firstPartyMcpBaseUrl(settings);\n if (raw.includes(\"{workspaceId}\")) {\n return raw.replaceAll(\"{workspaceId}\", workspaceId);\n }\n const url = new URL(raw);\n url.pathname = `/v1/workspaces/${workspaceId}/mcp`;\n url.search = \"\";\n url.hash = \"\";\n return url.toString();\n}\n\nfunction firstPartyMcpServerUrl(settings: Settings): string {\n return firstPartyMcpBaseUrl(settings);\n}\n\nfunction firstPartyDocumentsMcpServerUrl(mcpUrl: string): string {\n return `${mcpUrl.replace(/\\/+$/, \"\")}/docs`;\n}\n\nfunction validateSettings(settings: Settings): void {\n temporalConnectionOptions(settings);\n if (settings.toolspaceEnabled && !settings.delegationSecret) {\n throw new Error(\"OPENGENI_DELEGATION_SECRET is required when OPENGENI_TOOLSPACE_ENABLED=true\");\n }\n if (settings.productAccessMode === \"managed\") {\n if (!settings.publicBaseUrl) {\n throw new Error(\n \"OPENGENI_PUBLIC_BASE_URL is required when OPENGENI_PRODUCT_ACCESS_MODE=managed\",\n );\n }\n if (!settings.betterAuthSecret) {\n throw new Error(\n \"OPENGENI_BETTER_AUTH_SECRET is required when OPENGENI_PRODUCT_ACCESS_MODE=managed\",\n );\n }\n if (!settings.delegationSecret) {\n throw new Error(\n \"OPENGENI_DELEGATION_SECRET is required when OPENGENI_PRODUCT_ACCESS_MODE=managed\",\n );\n }\n if (![\"local\", \"test\"].includes(settings.environment) && !settings.resendApiKey) {\n throw new Error(\"OPENGENI_RESEND_API_KEY is required for managed mode outside local/test\");\n }\n if (![\"local\", \"test\"].includes(settings.environment) && !settings.environmentsEncryptionKey) {\n throw new Error(\n \"OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY is required for managed mode outside local/test\",\n );\n }\n }\n environmentsEncryptionKeyBytes(settings);\n if (settings.integrationsEnabled) {\n if (settings.productAccessMode === \"managed\" && !settings.publicBaseUrl) {\n throw new Error(\n \"OPENGENI_PUBLIC_BASE_URL is required when OPENGENI_INTEGRATIONS_ENABLED=true and OPENGENI_PRODUCT_ACCESS_MODE=managed\",\n );\n }\n if (\n settings.publicBaseUrl &&\n !settings.publicBaseUrl.startsWith(\"https://\") &&\n ![\"local\", \"test\"].includes(settings.environment)\n ) {\n throw new Error(\n \"OPENGENI_PUBLIC_BASE_URL must use https when OPENGENI_INTEGRATIONS_ENABLED=true outside local/test\",\n );\n }\n if (!settings.integrationsStateSecret && ![\"local\", \"test\"].includes(settings.environment)) {\n throw new Error(\n \"OPENGENI_INTEGRATIONS_STATE_SECRET is required when OPENGENI_INTEGRATIONS_ENABLED=true outside local/test\",\n );\n }\n }\n parseIntegrationsOauthClientsJson(settings.integrationsOauthClientsJson);\n if (\n settings.productAccessMode === \"configured\" &&\n ![\"local\", \"test\"].includes(settings.environment) &&\n !settings.delegationSecret &&\n !settings.authRequired\n ) {\n throw new Error(\n \"OPENGENI_PRODUCT_ACCESS_MODE=configured requires OPENGENI_DELEGATION_SECRET or OPENGENI_AUTH_REQUIRED=true outside local/test\",\n );\n }\n if (settings.billingMode === \"stripe\") {\n if (!settings.stripeSecretKey || !settings.stripeWebhookSecret) {\n throw new Error(\n \"OPENGENI_STRIPE_SECRET_KEY and OPENGENI_STRIPE_WEBHOOK_SECRET are required when OPENGENI_BILLING_MODE=stripe\",\n );\n }\n }\n if (settings.productAccessMode !== \"managed\" && settings.billingMode === \"stripe\") {\n throw new Error(\"OPENGENI_BILLING_MODE=stripe requires OPENGENI_PRODUCT_ACCESS_MODE=managed\");\n }\n if (settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\") {\n const pricing = configuredModelPricing(settings);\n const missing = configuredAllowedModels(settings).filter((model) => !pricing[model]);\n if (missing.length > 0) {\n throw new Error(\n `Missing model pricing for managed billing model(s): ${missing.join(\", \")}. Set OPENGENI_MODEL_PRICING_JSON.`,\n );\n }\n }\n if (settings.usageLimitsMode === \"static\") {\n const limits = configuredStaticUsageLimits(settings);\n if (Object.keys(limits).length === 0) {\n throw new Error(\n \"OPENGENI_STATIC_USAGE_LIMITS_JSON must define at least one cap when OPENGENI_USAGE_LIMITS_MODE=static\",\n );\n }\n } else {\n parseStaticUsageLimitsJson(settings.staticUsageLimitsJson);\n }\n if (settings.entitlementsMode === \"static\") {\n const entitlements = parseStaticEntitlementsJson(settings.staticEntitlementsJson);\n if (Object.keys(entitlements).length === 0) {\n throw new Error(\n \"OPENGENI_STATIC_ENTITLEMENTS_JSON must define at least one feature when OPENGENI_ENTITLEMENTS_MODE=static\",\n );\n }\n } else {\n parseStaticEntitlementsJson(settings.staticEntitlementsJson);\n }\n if (settings.authRequired && !settings.accessKey) {\n throw new Error(\"OPENGENI_ACCESS_KEY is required when OPENGENI_AUTH_REQUIRED=true\");\n }\n if (settings.openaiProvider === \"azure\") {\n if (!settings.azureOpenaiBaseUrl && !settings.azureOpenaiEndpoint) {\n throw new Error(\n \"Azure OpenAI requires OPENGENI_AZURE_OPENAI_BASE_URL or OPENGENI_AZURE_OPENAI_ENDPOINT\",\n );\n }\n if (!settings.azureOpenaiBaseUrl && !settings.azureOpenaiDeployment) {\n throw new Error(\"Azure OpenAI endpoint mode requires OPENGENI_AZURE_OPENAI_DEPLOYMENT\");\n }\n if (!settings.azureOpenaiBaseUrl && !settings.azureOpenaiApiVersion) {\n throw new Error(\"Azure OpenAI endpoint mode requires OPENGENI_AZURE_OPENAI_API_VERSION\");\n }\n if (!settings.azureOpenaiApiKey && !settings.azureOpenaiAdToken) {\n throw new Error(\"Azure OpenAI requires an API key or AD token\");\n }\n }\n // The Modal token is a both-or-neither pair regardless of the active backend\n // (a half-configured token is always a misconfiguration). This is orthogonal\n // to the backend-gated required-cred sweep below.\n if (Boolean(settings.modalTokenId) !== Boolean(settings.modalTokenSecret)) {\n throw new Error(\n \"OPENGENI_MODAL_TOKEN_ID and OPENGENI_MODAL_TOKEN_SECRET must both be set or both omitted\",\n );\n }\n // Backend-gated required credentials: only the *active* backend's creds are\n // required. A modal deployment must carry the Modal token; a daytona/e2b/none\n // deployment must NOT be forced to (and is not). Drives off the single\n // SANDBOX_REQUIRED_ENV table that the deployment package also mirrors.\n for (const required of SANDBOX_REQUIRED_ENV[settings.sandboxBackend] ?? []) {\n const value = settings[required.field];\n if (\n value === undefined ||\n value === null ||\n (typeof value === \"string\" && value.trim().length === 0)\n ) {\n throw new Error(\n `${required.env} is required when OPENGENI_SANDBOX_BACKEND=${settings.sandboxBackend}`,\n );\n }\n }\n if (\n settings.objectStorageBackend === \"s3-compatible\" ||\n settings.objectStorageBackend === \"aws-s3\"\n ) {\n if (\n Boolean(settings.objectStorageAccessKeyId) !== Boolean(settings.objectStorageSecretAccessKey)\n ) {\n throw new Error(\n \"OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID and OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY must both be set or both omitted\",\n );\n }\n if (\n settings.objectStorageBackend === \"s3-compatible\" &&\n (settings.objectStorageEndpoint || settings.objectStorageSandboxEndpoint) &&\n (!settings.objectStorageAccessKeyId || !settings.objectStorageSecretAccessKey)\n ) {\n throw new Error(\n \"S3-compatible object storage endpoints require OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID and OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY\",\n );\n }\n if (\n settings.objectStorageAzureConnectionString ||\n settings.objectStorageAzureAccountName ||\n settings.objectStorageAzureAccountKey ||\n settings.objectStorageAzureEndpoint\n ) {\n throw new Error(\n \"S3 object storage uses OPENGENI_OBJECT_STORAGE_* S3 settings, not OPENGENI_OBJECT_STORAGE_AZURE_* settings\",\n );\n }\n if (\n settings.objectStorageGcsProjectId ||\n settings.objectStorageGcsCredentialsJson ||\n settings.objectStorageGcsKeyFilename ||\n settings.objectStorageGcsApiEndpoint\n ) {\n throw new Error(\n \"S3 object storage uses OPENGENI_OBJECT_STORAGE_* S3 settings, not OPENGENI_OBJECT_STORAGE_GCS_* settings\",\n );\n }\n } else if (settings.objectStorageBackend === \"azure-blob\") {\n if (\n settings.objectStorageEndpoint ||\n settings.objectStorageSandboxEndpoint ||\n settings.objectStorageAccessKeyId ||\n settings.objectStorageSecretAccessKey\n ) {\n throw new Error(\n \"Azure Blob storage uses OPENGENI_OBJECT_STORAGE_AZURE_* settings, not S3-compatible object storage settings\",\n );\n }\n if (\n settings.objectStorageGcsProjectId ||\n settings.objectStorageGcsCredentialsJson ||\n settings.objectStorageGcsKeyFilename ||\n settings.objectStorageGcsApiEndpoint\n ) {\n throw new Error(\n \"Azure Blob storage uses OPENGENI_OBJECT_STORAGE_AZURE_* settings, not OPENGENI_OBJECT_STORAGE_GCS_* settings\",\n );\n }\n const hasConnectionString = Boolean(settings.objectStorageAzureConnectionString);\n const hasSharedKey =\n Boolean(settings.objectStorageAzureAccountName) &&\n Boolean(settings.objectStorageAzureAccountKey);\n if (!hasConnectionString && !hasSharedKey) {\n throw new Error(\n \"Azure Blob storage requires OPENGENI_OBJECT_STORAGE_AZURE_CONNECTION_STRING or OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_NAME plus OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_KEY\",\n );\n }\n } else {\n if (\n settings.objectStorageEndpoint ||\n settings.objectStorageSandboxEndpoint ||\n settings.objectStorageAccessKeyId ||\n settings.objectStorageSecretAccessKey\n ) {\n throw new Error(\n \"GCS object storage uses OPENGENI_OBJECT_STORAGE_GCS_* settings, not S3-compatible object storage settings\",\n );\n }\n if (\n settings.objectStorageAzureConnectionString ||\n settings.objectStorageAzureAccountName ||\n settings.objectStorageAzureAccountKey ||\n settings.objectStorageAzureEndpoint\n ) {\n throw new Error(\n \"GCS object storage uses OPENGENI_OBJECT_STORAGE_GCS_* settings, not OPENGENI_OBJECT_STORAGE_AZURE_* settings\",\n );\n }\n if (settings.objectStorageGcsCredentialsJson) {\n parseGcsCredentialsJson(settings.objectStorageGcsCredentialsJson);\n }\n }\n if (settings.documentChunkOverlap >= settings.documentChunkSize) {\n throw new Error(\n \"OPENGENI_DOCUMENT_CHUNK_OVERLAP must be smaller than OPENGENI_DOCUMENT_CHUNK_SIZE\",\n );\n }\n parseExposedPorts(settings.dockerExposedPorts);\n sandboxEnvironmentVariableNames(settings);\n sandboxLifecycleHookIds(settings);\n // Fail fast on a malformed warm-rate table (P2.1).\n parseSandboxWarmRateJson(settings.sandboxWarmRateMicrosPerSecondJson);\n const serverIds = new Set<string>();\n for (const server of settings.mcpServers) {\n if (serverIds.has(server.id)) {\n throw new Error(`OPENGENI_MCP_SERVERS contains duplicate id ${server.id}`);\n }\n serverIds.add(server.id);\n }\n // --- sandbox lease cadence invariant (fail fast at boot) ---\n // reaperPeriod (30s) < viewerHolderTTL (90s), and reaperPeriod + idleGrace must\n // be strictly less than the provider lifetime (modalTimeoutSeconds*1000):\n // - the reaper must run more often than the TTL it polices; and\n // - the reaper must terminate a genuinely-idle box (after the full drain grace,\n // observed on the NEXT sweep) BEFORE the provider's hard lifetime reclaims it\n // out from under us — the provider lifetime is the backstop, not the\n // warm-window controller. idleGrace counts from the user's last release;\n // the provider clock counts from the preceding resume, so we leave the\n // active-turn headroom in modalTimeoutSeconds (default 3600s).\n {\n const reaperPeriod = settings.sandboxLeaseReaperPeriodMs;\n const viewerTtl = settings.sandboxViewerHolderTtlMs;\n const idleGraceMs = settings.sandboxIdleGraceMs;\n const providerLifetimeMs = settings.modalTimeoutSeconds * 1000;\n // The EFFECTIVE box lifetime when it sits idle between turns is the Modal IDLE\n // timeout, NOT the hard lifetime (sandbox-file-persistence): a box with no\n // active connection is idle-reaped at idleTimeout. effectiveModalIdleTimeout\n // defaults to the hard lifetime (so the idle-reap never beats the OpenGeni\n // reaper), but an operator can pin it shorter — the invariants below bind the\n // reaper cadence + drain grace to the idle timeout (the REAL ceiling), so a\n // drained box always survives long enough for the reaper to snapshot it.\n const idleTimeoutMs = effectiveModalIdleTimeoutSeconds(settings) * 1000;\n if (!(reaperPeriod < viewerTtl)) {\n throw new Error(\n `OPENGENI_SANDBOX_LEASE_REAPER_PERIOD_MS (${reaperPeriod}) must be strictly less than ` +\n `OPENGENI_SANDBOX_VIEWER_HOLDER_TTL_MS (${viewerTtl}): the reaper must run more often ` +\n `than the TTL it polices, or stale viewer holders outlive a full reaper period.`,\n );\n }\n if (!(idleTimeoutMs <= providerLifetimeMs)) {\n throw new Error(\n `OPENGENI_MODAL_IDLE_TIMEOUT_SECONDS*1000 (${idleTimeoutMs}) must not exceed the hard provider ` +\n `lifetime (OPENGENI_MODAL_TIMEOUT_SECONDS*1000 = ${providerLifetimeMs}): the idle timeout is a ` +\n `floor under the hard lifetime, not above it.`,\n );\n }\n if (!(viewerTtl < idleTimeoutMs)) {\n throw new Error(\n `OPENGENI_SANDBOX_VIEWER_HOLDER_TTL_MS (${viewerTtl}) must be strictly less than the effective box ` +\n `idle timeout (${idleTimeoutMs}): a viewer holder must be reapable before the box idles out from ` +\n `under it (the provider idle-timeout is the backstop).`,\n );\n }\n if (!(reaperPeriod + idleGraceMs < idleTimeoutMs)) {\n throw new Error(\n `OPENGENI_SANDBOX_LEASE_REAPER_PERIOD_MS + OPENGENI_SANDBOX_IDLE_GRACE_MS ` +\n `(${reaperPeriod} + ${idleGraceMs} = ${reaperPeriod + idleGraceMs}) must be strictly less than the ` +\n `effective box idle timeout (${idleTimeoutMs}): a drained box must SURVIVE its full warm window so ` +\n `the reaper can resume + snapshot /workspace + terminate it on the sweep AFTER the drain grace ` +\n `elapses — Modal's idle-reap must NOT fire first (or /workspace is lost). Raise ` +\n `OPENGENI_MODAL_IDLE_TIMEOUT_SECONDS (defaults to OPENGENI_MODAL_TIMEOUT_SECONDS) or lower ` +\n `OPENGENI_SANDBOX_IDLE_GRACE_MS.`,\n );\n }\n }\n // --- stream-token secret: required-when-desktop, but GRACEFULLY DEGRADE (stream-token availability contract) ---\n // The desktop pixel plane needs an HMAC secret to mint scoped stream tokens.\n // It is REQUIRED when desktop is enabled — but per OD-8 a missing secret is NOT\n // a hard boot-fail: we emit a LOUD warning and the deployment ships with\n // DesktopStream.transport:null (resolveStreamTokenSecret returns undefined ->\n // negotiateCapabilities degrades the desktop cell). This keeps a desktop-\n // configured deployment bootable (headless + Channel-A still work) instead of\n // crashing the whole API on a missing secret.\n if (settings.sandboxDesktopEnabled && resolveStreamTokenSecret(settings) === undefined) {\n console.warn(\n \"[opengeni] OPENGENI_SANDBOX_DESKTOP_ENABLED=true but neither OPENGENI_STREAM_TOKEN_SECRET nor \" +\n \"OPENGENI_DELEGATION_SECRET is set: the desktop pixel plane will GRACEFULLY DEGRADE \" +\n \"(DesktopStream.transport=null — no scoped stream tokens can be minted). Set \" +\n \"OPENGENI_STREAM_TOKEN_SECRET to enable the live desktop stream.\",\n );\n }\n // Model provider registry: parse it here so JSON/zod errors surface at boot,\n // reject a registry id colliding with the built-in provider id (it would\n // shadow the built-in in configuredProviders), reject duplicate registry\n // ids, and require a resolvable API key for every registry provider (a\n // provider with no usable key can never serve a turn). Registry models flow\n // through configuredAllowedModels, so the managed-billing pricing check above\n // already covers them.\n const registryProviders = parseModelProvidersJson(settings.modelProvidersJson);\n const builtinId = builtinProviderId(settings);\n const providerIds = new Set<string>();\n for (const provider of registryProviders) {\n if (provider.id === builtinId) {\n throw new Error(\n `OPENGENI_MODEL_PROVIDERS_JSON provider id ${provider.id} collides with the built-in provider id`,\n );\n }\n if (providerIds.has(provider.id)) {\n throw new Error(\n `OPENGENI_MODEL_PROVIDERS_JSON contains duplicate provider id ${provider.id}`,\n );\n }\n providerIds.add(provider.id);\n if (!resolveProviderApiKey(provider)) {\n throw new Error(\n `OPENGENI_MODEL_PROVIDERS_JSON provider ${provider.id} requires a resolvable API key (set apiKey or apiKeyEnv)`,\n );\n }\n }\n // Materialize the normalized catalog at boot so canonical product ids,\n // aliases, definition digests, and capability/pricing normalization are\n // validated even when managed billing is disabled.\n configuredModels(settings);\n}\n\n/**\n * Resolve the secret used to sign/verify scoped stream tokens (sandbox contract\n * §C.3). Falls back to `delegationSecret` (the same HMAC envelope family —\n * `ogs_` vs `ogd_` prefix) so a deployment that already carries a delegation\n * secret does not need a second one. Returns undefined when neither is set,\n * which drives the graceful-degrade (DesktopStream.transport:null).\n */\nexport function resolveStreamTokenSecret(settings: Settings): string | undefined {\n const explicit = settings.streamTokenSecret?.trim();\n if (explicit) {\n return explicit;\n }\n const delegation = settings.delegationSecret?.trim();\n return delegation ? delegation : undefined;\n}\n\n/**\n * True iff the desktop pixel plane must GRACEFULLY DEGRADE because desktop is\n * enabled but no stream-token secret is resolvable (stream-token availability contract). When true,\n * negotiateCapabilities forces DesktopStream.transport:null.\n */\nexport function streamTokenDegraded(settings: Settings): boolean {\n return settings.sandboxDesktopEnabled && resolveStreamTokenSecret(settings) === undefined;\n}\n\n/**\n * Resolve the secret the control plane signs the enrollment bearer credential\n * with (the `oge_` envelope the agent presents back — M5). Falls\n * back to `delegationSecret` (the same HMAC envelope family) so a deployment that\n * already carries a delegation secret needs no second one. Returns undefined when\n * neither is set; when selfhosted is enabled but this is undefined, the poll route\n * reports the credential plane disabled (graceful degrade, never a 500). NEVER log\n * the returned value.\n */\nexport function resolveEnrollmentSigningSecret(settings: Settings): string | undefined {\n const explicit = settings.enrollmentSigningSecret?.trim();\n if (explicit) {\n return explicit;\n }\n const delegation = settings.delegationSecret?.trim();\n return delegation ? delegation : undefined;\n}\n\n/**\n * Resolve the HMAC secret the control plane signs the agent's relay PRODUCER token\n * with (the `ogr_` envelope; M8b). The RELAY verifies the producer\n * token with the SAME secret (injected into the relay via env). Prefers an explicit\n * `selfhostedRelayTokenSecret`, then the `streamTokenSecret` (the relay already\n * needs that one to verify the viewer's `ogs_` token, so a single secret can back\n * both planes), then `delegationSecret` (same HMAC family). Returns undefined when\n * none is set — the enrollment poll then returns an empty relayToken (graceful\n * degrade; the stream plane is unavailable until configured). NEVER log the value.\n */\nexport function resolveRelayTokenSecret(settings: Settings): string | undefined {\n const explicit = settings.selfhostedRelayTokenSecret?.trim();\n if (explicit) {\n return explicit;\n }\n const stream = settings.streamTokenSecret?.trim();\n if (stream) {\n return stream;\n }\n const delegation = settings.delegationSecret?.trim();\n return delegation ? delegation : undefined;\n}\n\n/**\n * The resolved NATS auth-callout responder config (M-AUTH). Present only when the\n * callout plane is FULLY configured: the account signing seed + the responder's own\n * login. When any piece is missing this returns null and the responder does not\n * start (selfhosted agents cannot connect — a graceful disabled state, never a boot\n * crash). The returned `accountSeed` is a secret; NEVER log it.\n */\nexport interface NatsCalloutConfig {\n /** The callout account SIGNING seed (`SA...`) — signs the user + response JWTs. */\n accountSeed: string;\n /** The target account NAME the user is placed into (the response `aud`). */\n accountName: string;\n /** The responder's NATS login (an `auth_callout.auth_users` user). */\n user: string;\n password: string;\n}\n\nexport function resolveNatsCalloutConfig(settings: Settings): NatsCalloutConfig | null {\n const accountSeed = settings.selfhostedNatsCalloutAccountSeed?.trim();\n const accountName = settings.selfhostedNatsCalloutAccountName?.trim() || \"APP\";\n const user = settings.selfhostedNatsCalloutUser?.trim();\n const password = settings.selfhostedNatsCalloutPassword?.trim();\n if (!accountSeed || !user || !password) {\n return null;\n }\n return { accountSeed, accountName, user, password };\n}\n\n/**\n * The PRIVILEGED control-plane NATS login (api/worker). Present only when BOTH a\n * user and password are set; otherwise null and the bus connects anonymously (local\n * dev / a NATS without auth_callout). When the callout plane is on, this is the\n * static account user permitted to request `agent.*.rpc`.\n */\nexport interface NatsControlPlaneAuth {\n user: string;\n password: string;\n}\n\nexport function resolveNatsControlPlaneAuth(settings: Settings): NatsControlPlaneAuth | null {\n const user = settings.selfhostedNatsControlUser?.trim();\n const password = settings.selfhostedNatsControlPassword?.trim();\n if (!user || !password) {\n return null;\n }\n return { user, password };\n}\n\nfunction splitCsv(raw: string): string[] {\n return raw\n .split(\",\")\n .map((value) => value.trim())\n .filter(Boolean);\n}\n\nfunction uniqueEnvNames(raw: string[], fieldName: string): string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const name of raw) {\n if (!envName.test(name)) {\n throw new Error(`${fieldName} contains invalid variable name ${name}`);\n }\n if (!seen.has(name)) {\n seen.add(name);\n out.push(name);\n }\n }\n return out;\n}\n\nfunction uniqueValues(raw: string[]): string[] {\n return [...new Set(raw.filter(Boolean))];\n}\n\nfunction parseGcsCredentialsJson(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`OPENGENI_OBJECT_STORAGE_GCS_CREDENTIALS_JSON must be valid JSON: ${message}`, {\n cause: error,\n });\n }\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"],"mappings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