@opengeni/config 0.2.4 → 0.2.5
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 +2 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/index.ts +6 -0
package/dist/index.d.ts
CHANGED
|
@@ -35,6 +35,7 @@ declare const SettingsSchema: z.ZodObject<{
|
|
|
35
35
|
serviceName: z.ZodDefault<z.ZodString>;
|
|
36
36
|
environment: z.ZodDefault<z.ZodString>;
|
|
37
37
|
deploymentRevision: z.ZodDefault<z.ZodString>;
|
|
38
|
+
serverVersion: z.ZodOptional<z.ZodString>;
|
|
38
39
|
databaseUrl: z.ZodDefault<z.ZodString>;
|
|
39
40
|
dbSchema: z.ZodDefault<z.ZodString>;
|
|
40
41
|
rlsStrategy: z.ZodDefault<z.ZodEnum<{
|
|
@@ -105,6 +106,7 @@ declare const SettingsSchema: z.ZodObject<{
|
|
|
105
106
|
authAllowMetrics: z.ZodDefault<z.ZodPreprocess<z.ZodBoolean>>;
|
|
106
107
|
apiHost: z.ZodDefault<z.ZodString>;
|
|
107
108
|
apiPort: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
|
|
109
|
+
workerHttpPort: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
|
|
108
110
|
opengeniMcpUrl: z.ZodOptional<z.ZodString>;
|
|
109
111
|
corsAllowOriginRegex: z.ZodDefault<z.ZodString>;
|
|
110
112
|
openaiProvider: z.ZodDefault<z.ZodEnum<{
|
package/dist/index.js
CHANGED
|
@@ -77,6 +77,9 @@ var SettingsSchema = z.object({
|
|
|
77
77
|
serviceName: z.string().default("opengeni"),
|
|
78
78
|
environment: z.string().default("local"),
|
|
79
79
|
deploymentRevision: z.string().default("dev"),
|
|
80
|
+
// The release-train version baked into official images (OPENGENI_SERVER_VERSION).
|
|
81
|
+
// Absent on dev/source builds — consumers must treat it as optional.
|
|
82
|
+
serverVersion: z.string().optional(),
|
|
80
83
|
databaseUrl: z.string().default("postgres://opengeni:opengeni@127.0.0.1:5432/opengeni"),
|
|
81
84
|
// Step I (§7.8 runtime half). Dedicated Postgres schema for the EMBEDDED
|
|
82
85
|
// topology. Default "" → standalone: no search_path scoping, server default
|
|
@@ -180,6 +183,7 @@ var SettingsSchema = z.object({
|
|
|
180
183
|
authAllowMetrics: EnvBoolean.default(false),
|
|
181
184
|
apiHost: z.string().default("0.0.0.0"),
|
|
182
185
|
apiPort: z.coerce.number().int().positive().default(8e3),
|
|
186
|
+
workerHttpPort: z.coerce.number().int().positive().default(8001),
|
|
183
187
|
opengeniMcpUrl: z.string().url().optional(),
|
|
184
188
|
corsAllowOriginRegex: z.string().default(String.raw`^https?://(localhost|127\.0\.0\.1)(:\d+)?$`),
|
|
185
189
|
openaiProvider: z.enum(["openai", "azure"]).default("openai"),
|
|
@@ -719,6 +723,7 @@ function getSettings() {
|
|
|
719
723
|
serviceName: optional("OPENGENI_SERVICE_NAME"),
|
|
720
724
|
environment: optional("OPENGENI_ENVIRONMENT"),
|
|
721
725
|
deploymentRevision: optional("OPENGENI_DEPLOYMENT_REVISION") ?? optional("SOURCE_VERSION") ?? optional("GITHUB_SHA"),
|
|
726
|
+
serverVersion: optional("OPENGENI_SERVER_VERSION"),
|
|
722
727
|
databaseUrl: optional("OPENGENI_DATABASE_URL"),
|
|
723
728
|
dbSchema: optional("OPENGENI_DB_SCHEMA"),
|
|
724
729
|
rlsStrategy: optional("OPENGENI_RLS_STRATEGY"),
|
|
@@ -763,6 +768,7 @@ function getSettings() {
|
|
|
763
768
|
authAllowMetrics: optional("OPENGENI_AUTH_ALLOW_METRICS"),
|
|
764
769
|
apiHost: optional("OPENGENI_API_HOST"),
|
|
765
770
|
apiPort: optional("OPENGENI_API_PORT"),
|
|
771
|
+
workerHttpPort: optional("OPENGENI_WORKER_HTTP_PORT"),
|
|
766
772
|
opengeniMcpUrl: optional("OPENGENI_MCP_URL"),
|
|
767
773
|
corsAllowOriginRegex: optional("OPENGENI_CORS_ALLOW_ORIGIN_REGEX"),
|
|
768
774
|
openaiProvider: optional("OPENGENI_OPENAI_PROVIDER"),
|
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 ProductAccessMode,\n ReasoningEffort,\n SandboxBackend,\n StaticUsageLimits,\n UsageLimitsMode,\n} from \"@opengeni/contracts\";\nimport { CODEX_MODEL_ID_PREFIX } from \"@opengeni/codex/constants\";\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-IDENTICAL to the historical\n * hardcoded preamble. The template below is exactly the historical lines 1–11\n * joined by \" \", followed by \" \" + the placeholder. Changing a single\n * character here changes that default; a runtime test pins it.\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/<owner>/<repo>.\",\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, GitHub CLI, and repository tools when relevant.\",\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 GitHub 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\nconst SettingsSchema = z.object({\n serviceName: z.string().default(\"opengeni\"),\n environment: z.string().default(\"local\"),\n deploymentRevision: z.string().default(\"dev\"),\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 (SPIKE-1 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 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>` (or `/latest/download/<asset>`).\n agentReleasesBaseUrl: z.string().url().default(\"https://github.com/Cloudgeni-ai/opengeni/releases\"),\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-surfacing scoped stream-token HMAC secret (master-spine §C.3 / I8).\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 (I8/OD-8).\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 environmentsEncryptionKey: z.string().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 // Where turn-input conversation history comes from (issue #35):\n // \"items\" (default) = the session_history_items table (SDK-native,\n // version-stable conversation truth); \"run_state\" = the legacy serialized\n // RunState blob. Items and the sandbox envelope are dual-written\n // unconditionally; this flag governs the read path only, so flipping back to\n // \"run_state\" remains a safe rollback at any time.\n sessionHistorySource: z.enum([\"run_state\", \"items\"]).default(\"items\"),\n // Provider-aware conversation context management (long-lived sessions\n // otherwise grow unbounded until they overflow the model context window and\n // hard-fail every turn). Resolution (see resolveContextCompactionMode):\n // \"auto\" (default) -> \"server\" when openaiProvider === \"openai\" (the\n // OpenAI platform Responses API honors server-side context_management),\n // else \"client\" (Azure rejects context_management with a 400, so we run\n // our own client-side compaction).\n // \"server\" / \"client\" -> force that path regardless of provider.\n // \"off\" -> neither path (legacy unbounded growth; escape hatch only).\n contextCompactionMode: z.enum([\"auto\", \"server\", \"client\", \"off\"]).default(\"auto\"),\n // The model's real context window in tokens. gpt-5.5's true window is\n // 1,050,000; it is absent from the SDK's hardcoded compaction window map (it\n // knows only up to gpt-5.4), so the SDK's DynamicCompactionPolicy would fall\n // back to a wrong 240k. We pass an explicit StaticCompactionPolicy threshold\n // derived from these settings on the server path, and use the same numbers to\n // budget the client path.\n contextWindowTokens: z.coerce.number().int().positive().default(1_050_000),\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 // Server path only: explicit compact_threshold (tokens) handed to the SDK's\n // StaticCompactionPolicy. Defaults to floor(B * contextCompactSoftFraction)\n // when unset.\n contextServerCompactThresholdTokens: z.coerce.number().int().positive().optional(),\n // Server path/back-compat knobs. The client compaction path ignores these:\n // it uses Codex-parity 0.9 * (window - reserved output - 20k summary buffer).\n contextCompactSoftFraction: z.coerce.number().positive().max(1).default(0.70),\n contextCompactHardFraction: z.coerce.number().positive().max(1).default(0.85),\n // Deprecated for the client path; parsed for env/back-compat only.\n contextKeepRecentTokens: z.coerce.number().int().positive().default(32_000),\n // Parsed for back-compat. Client compaction uses the fixed 20k Codex summary\n // buffer as its generated-summary output ceiling.\n contextSummaryMaxTokens: z.coerce.number().int().positive().default(20_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 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.5\"),\n openaiAllowedModels: z.string().default(\"gpt-5.5,gpt-5.4,gpt-5.4-mini\"),\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 // 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 byte-identical to the historical hardcoded preamble.\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 // 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 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 // --- 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 (dossier §17/§25.1).\n sandboxSelfhostedEnabled: 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/dossier\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; dossier\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 // --- 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 // 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 // --- 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.enum([\"s3-compatible\", \"aws-s3\", \"azure-blob\", \"gcs\"]).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.array(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 /**\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 })).default([]),\n});\n\nexport type Settings = z.infer<typeof SettingsSchema>;\nexport type McpServerConfig = Settings[\"mcpServers\"][number];\nexport type ModelPricing = {\n inputMicrosPerMillionTokens: number;\n cachedInputMicrosPerMillionTokens?: number | undefined;\n outputMicrosPerMillionTokens: number;\n marginBps?: number | 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\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.object({\n id: z.string().min(1), // model id sent to the provider, e.g. \"accounts/fireworks/models/glm-5p2\"\n label: z.string().min(1).optional(), // display name; defaults to id\n contextWindowTokens: z.number().int().positive().optional(),\n reasoningEffort: z.boolean().optional(), // model accepts a reasoning-effort control\n hostedWebSearch: z.boolean().optional(), // provider executes the hosted web_search tool for this model\n pricing: ModelPricingSchema.optional(),\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 models: z.array(RegistryModelSchema).min(1),\n});\nexport type RegistryProvider = z.infer<typeof RegistryProviderSchema>;\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. compactionMode\n * is \"server\" only for the built-in OpenAI platform provider (its Responses API\n * honors server-side context_management) and \"client\" for everything else.\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 compactionMode: ContextCompactionMode; // \"server\" only for built-in OpenAI; \"client\" otherwise\n}\n\n/** A single exposed model + the provider that serves it. */\nexport interface ConfiguredModel {\n id: string;\n label: string;\n providerId: string;\n providerLabel: string;\n api: ModelProviderApi;\n contextWindowTokens?: number | undefined;\n reasoningEffort: boolean;\n hostedWebSearch: boolean;\n}\n\nexport const defaultModelPricing: Record<string, ModelPricing> = {\n \"gpt-5.5\": {\n inputMicrosPerMillionTokens: 5_000_000,\n cachedInputMicrosPerMillionTokens: 500_000,\n outputMicrosPerMillionTokens: 30_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<z.infer<typeof SandboxBackend>, readonly SandboxRequiredEnv[]> = {\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: [\n { field: \"daytonaApiKey\", env: \"OPENGENI_DAYTONA_API_KEY\" },\n ],\n runloop: [\n { field: \"runloopApiKey\", env: \"OPENGENI_RUNLOOP_API_KEY\" },\n ],\n e2b: [\n { field: \"e2bApiKey\", env: \"OPENGENI_E2B_API_KEY\" },\n ],\n blaxel: [\n { field: \"blaxelApiKey\", env: \"OPENGENI_BLAXEL_API_KEY\" },\n ],\n cloudflare: [\n { field: \"cloudflareWorkerUrl\", env: \"OPENGENI_CLOUDFLARE_WORKER_URL\" },\n ],\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: optional(\"OPENGENI_DEPLOYMENT_REVISION\") ?? optional(\"SOURCE_VERSION\") ?? optional(\"GITHUB_SHA\"),\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 startupDependencyRetryAttempts: optional(\"OPENGENI_STARTUP_DEPENDENCY_RETRY_ATTEMPTS\"),\n startupDependencyRetryInitialDelayMs: optional(\"OPENGENI_STARTUP_DEPENDENCY_RETRY_INITIAL_DELAY_MS\"),\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: optional(\"OPENGENI_OTEL_EXPORTER_OTLP_ENDPOINT\") ?? optional(\"OTEL_EXPORTER_OTLP_ENDPOINT\"),\n observabilityOtlpHeaders: 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 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 environmentsEncryptionKey: optional(\"OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY\"),\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 sessionHistorySource: optional(\"OPENGENI_SESSION_HISTORY_SOURCE\"),\n contextCompactionMode: optional(\"OPENGENI_CONTEXT_COMPACTION_MODE\"),\n contextWindowTokens: optional(\"OPENGENI_CONTEXT_WINDOW_TOKENS\"),\n contextReservedOutputTokens: optional(\"OPENGENI_CONTEXT_RESERVED_OUTPUT_TOKENS\"),\n contextServerCompactThresholdTokens: optional(\"OPENGENI_CONTEXT_SERVER_COMPACT_THRESHOLD_TOKENS\"),\n contextCompactSoftFraction: optional(\"OPENGENI_CONTEXT_COMPACT_SOFT_FRACTION\"),\n contextCompactHardFraction: optional(\"OPENGENI_CONTEXT_COMPACT_HARD_FRACTION\"),\n contextKeepRecentTokens: optional(\"OPENGENI_CONTEXT_KEEP_RECENT_TOKENS\"),\n contextSummaryMaxTokens: optional(\"OPENGENI_CONTEXT_SUMMARY_MAX_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 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 codexProductSku: optional(\"OPENGENI_CODEX_PRODUCT_SKU\"),\n codexRotationNearExhaustionPct: optional(\"OPENGENI_CODEX_ROTATION_NEAR_EXHAUSTION_PCT\"),\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 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 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 sandboxSelfhostedEnabled: optional(\"OPENGENI_SANDBOX_SELFHOSTED_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 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 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 sandboxWarmRateMicrosPerSecondJson: optional(\"OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON\"),\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(settings: Settings, source: NodeJS.ProcessEnv = process.env): 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\n/** The built-in provider's stable id: \"openai\" on the OpenAI platform, \"azure\" on Azure. */\nfunction 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\", compactionMode from\n * resolveContextCompactionMode), then each registry provider in declaration\n * order (compactionMode \"client\"). 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 builtin: ResolvedModelProvider = {\n id: builtinProviderId(settings),\n label: builtinProviderLabel(settings),\n kind: \"api-key\",\n api: \"responses\",\n builtin: true,\n compactionMode: resolveContextCompactionMode(settings),\n };\n if (settings.openaiProvider === \"azure\") {\n builtin.baseUrl = settings.azureOpenaiBaseUrl ?? settings.azureOpenaiEndpoint;\n builtin.apiKey = settings.azureOpenaiApiKey ?? settings.azureOpenaiAdToken;\n } else {\n builtin.baseUrl = settings.openaiBaseUrl;\n builtin.apiKey = settings.openaiApiKey;\n }\n const registry = parseModelProvidersJson(settings.modelProvidersJson).map((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 compactionMode: \"client\",\n }));\n return [builtin, ...registry];\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 // 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.5\") 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 registryOwnedIds = new Set(\n parseModelProvidersJson(settings.modelProvidersJson).flatMap((provider) => provider.models.map((model) => model.id)),\n );\n const isRegistryNamespaced = (id: string): boolean =>\n id.startsWith(CODEX_MODEL_ID_PREFIX) || (id.includes(\"/\") && registryOwnedIds.has(id));\n const out: ConfiguredModel[] = uniqueValues([settings.openaiModel, ...splitCsv(settings.openaiAllowedModels)])\n .filter((id) => !isRegistryNamespaced(id))\n .map((id) => ({\n id,\n label: id,\n providerId: builtinId,\n providerLabel: builtinLabel,\n api: \"responses\" as const,\n contextWindowTokens: settings.contextWindowTokens,\n reasoningEffort: true,\n hostedWebSearch: settings.webSearchEnabled,\n }));\n for (const provider of parseModelProvidersJson(settings.modelProvidersJson)) {\n const providerLabel = provider.label ?? provider.id;\n for (const model of provider.models) {\n out.push({\n id: model.id,\n label: model.label ?? model.id,\n providerId: provider.id,\n providerLabel,\n api: provider.api,\n ...(model.contextWindowTokens === undefined ? {} : { contextWindowTokens: model.contextWindowTokens }),\n reasoningEffort: model.reasoningEffort ?? false,\n hostedWebSearch: model.hostedWebSearch ?? false,\n });\n }\n }\n const seen = new Set<string>();\n return out.filter((model) => {\n if (seen.has(model.id)) {\n return false;\n }\n seen.add(model.id);\n return true;\n });\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 model = configuredModels(settings).find((candidate) => candidate.id === modelId);\n if (!model) {\n return undefined;\n }\n const provider = configuredProviders(settings).find((candidate) => candidate.id === model.providerId);\n if (!provider) {\n return undefined;\n }\n return { provider, model };\n}\n\n/**\n * Effective per-model pricing. Merge order (later wins):\n * defaultModelPricing → registry model `pricing` entries (keyed by model id)\n * → parseModelPricingJson(settings.modelPricingJson) (explicit JSON wins).\n */\nexport function configuredModelPricing(settings: Settings): Record<string, ModelPricing> {\n const registry: Record<string, ModelPricing> = {};\n for (const provider of parseModelProvidersJson(settings.modelProvidersJson)) {\n for (const model of provider.models) {\n if (model.pricing) {\n registry[model.id] = model.pricing;\n }\n }\n }\n const configured = parseModelPricingJson(settings.modelPricingJson);\n return {\n ...defaultModelPricing,\n ...registry,\n ...configured,\n };\n}\n\n/**\n * Resolved conversation-context compaction path for a run.\n * - \"server\": let the OpenAI platform Responses API compact server-side (the\n * SDK emits context_management; we pass the correct gpt-5.5 threshold).\n * - \"client\": run OpenGeni's own client-side compaction (Azure and any other\n * backend that rejects/ignores context_management).\n * - \"off\": neither (legacy unbounded growth; escape hatch).\n *\n * \"auto\" maps to \"server\" on the OpenAI platform provider and \"client\"\n * otherwise — Azure's Responses API returns 400 unsupported_parameter for\n * context_management, so it must never take the server path.\n */\nexport type ContextCompactionMode = \"server\" | \"client\" | \"off\";\n\nexport function resolveContextCompactionMode(settings: Pick<Settings, \"contextCompactionMode\" | \"openaiProvider\">): ContextCompactionMode {\n switch (settings.contextCompactionMode) {\n case \"server\":\n return \"server\";\n case \"client\":\n return \"client\";\n case \"off\":\n return \"off\";\n case \"auto\":\n default:\n return settings.openaiProvider === \"openai\" ? \"server\" : \"client\";\n }\n}\n\n/** Usable input-token budget B = window - reserved output. */\nexport function contextInputBudgetTokens(settings: Pick<Settings, \"contextWindowTokens\" | \"contextReservedOutputTokens\">): number {\n return Math.max(0, settings.contextWindowTokens - settings.contextReservedOutputTokens);\n}\n\n/**\n * Server-path compact_threshold (tokens) handed to the SDK's\n * StaticCompactionPolicy: the explicit override when set, else\n * floor(B * softFraction). This is what sidesteps the SDK's wrong 240k\n * fallback for gpt-5.5 (which is absent from its hardcoded window map).\n */\nexport function contextServerCompactThreshold(settings: Pick<Settings, \"contextWindowTokens\" | \"contextReservedOutputTokens\" | \"contextServerCompactThresholdTokens\" | \"contextCompactSoftFraction\">): number {\n if (settings.contextServerCompactThresholdTokens) {\n return settings.contextServerCompactThresholdTokens;\n }\n return Math.floor(contextInputBudgetTokens(settings) * settings.contextCompactSoftFraction);\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(settings: Settings, model: string, usage: ModelUsageInput): number {\n const pricing = configuredModelPricing(settings)[model];\n if (!pricing) {\n throw new Error(`Missing model pricing for ${model}`);\n }\n const entries = usage.requestUsageEntries && usage.requestUsageEntries.length > 0 ? usage.requestUsageEntries : [usage];\n const rawCost = entries.reduce((sum, entry) => sum + calculateEntryCostMicros(pricing, entry), 0);\n const marginBps = pricing.marginBps ?? 0;\n return Math.ceil(rawCost * (10_000 + marginBps) / 10_000);\n}\n\nexport function configuredAllowedReasoningEfforts(settings: Settings): Array<z.infer<typeof ReasoningEffort>> {\n return uniqueValues([settings.openaiReasoningEffort, ...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(\"OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY must be base64 for exactly 32 bytes (generate with: openssl rand -base64 32)\");\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 SPIKE-1 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(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((entry): entry is [string, string] => typeof entry[1] === \"string\" && entry[1].trim().length > 0));\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 GitHub App installation token\n * VALUE that `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) the token VALUE never rides the manifest at all — it is seeded to a\n * FILE inside the box (agent-managed, refreshable mid-turn via the `github_token`\n * MCP tool) and git auth flows through GIT_ASKPASS -> that file. What IS stable and\n * lives here is the token FILE PATH (`OPENGENI_GIT_TOKEN_FILE`): a constant derived\n * from HOME, so it appears IDENTICALLY on BOTH the turn AND every attach manifest\n * (the SDK's per-turn provided-session env delta stays empty even as the token\n * rotates). The attach surfaces have only the `Session` (no repo resources) and so\n * never seed a token, but the file-path pointer is harmless (an unwritten file\n * simply yields no auth); the BLOCKING attach-vs-turn error this helper fixes is\n * for the common (no-repo) and workspace-environment-attached cases.\n */\nexport function stableSandboxEnvironmentForRun(\n settings: Settings,\n workspaceEnvironment: Record<string, 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 token FILE PATH. A constant derived from the\n // resolved HOME (falling back to the descriptor workspaceRoot), so it is\n // parity-safe — it joins the shared base and therefore appears IDENTICALLY on\n // BOTH the worker-turn manifest AND every API-direct attach manifest, keeping\n // the SDK's provided-session env delta empty. Only the PATH is stable; the token\n // VALUE lives exclusively in the file (agent-managed, refreshable mid-turn), never\n // the manifest env.\n environment.OPENGENI_GIT_TOKEN_FILE ??= `${environment.HOME ?? descriptor.workspaceRoot}/.opengeni/git-token`;\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(resources: ReadonlyArray<{ kind: string; githubInstallationId?: unknown; githubRepositoryId?: unknown }>): 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((resource) => resource.kind === \"repository\" && positive(resource.githubInstallationId) && positive(resource.githubRepositoryId));\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(settings: Settings): 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) => value.toLowerCase());\n if (profiles.includes(\"none\")) {\n if (profiles.length > 1) {\n throw new Error(\"OPENGENI_SANDBOX_PREPARATION_PROFILES cannot combine none with other profiles\");\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}`);\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}`);\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(`OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON must be valid JSON: ${message}`);\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(\"OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON must be a JSON object keyed by backend name\");\n }\n const out: Record<string, number> = {};\n for (const [backend, value] of Object.entries(parsed)) {\n if (!backend.trim()) {\n throw new Error(\"OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON contains an empty backend name\");\n }\n const rate = typeof value === \"number\" ? value : Number(value);\n if (!Number.isFinite(rate) || rate < 0) {\n throw new Error(`OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON rate for ${backend} must be a non-negative number`);\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 }\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(`OPENGENI_MODEL_PROVIDERS_JSON provider[${index}] is invalid: ${result.error.message}`);\n }\n return result.data;\n });\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 }\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 }\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 = pricing.cachedInputMicrosPerMillionTokens ?? pricing.inputMicrosPerMillionTokens;\n return 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\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 += 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 id: \"files\",\n name: \"Files\",\n url: firstPartyMcpUrl,\n allowedTools: [\"files_get_download_url\"],\n cacheToolsList: true,\n }]),\n ...(hasDocs ? [] : [{\n id: \"docs\",\n name: \"Document Search\",\n url: firstPartyDocsMcpUrl,\n allowedTools: [\"search_documents\", \"fetch_document_chunk\", \"list_document_bases\"],\n cacheToolsList: false,\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 settings.opengeniMcpUrl ?? `http://127.0.0.1:${settings.apiPort}/v1/workspaces/{workspaceId}/mcp`;\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 if (settings.productAccessMode === \"managed\") {\n if (!settings.publicBaseUrl) {\n throw new Error(\"OPENGENI_PUBLIC_BASE_URL is required when OPENGENI_PRODUCT_ACCESS_MODE=managed\");\n }\n if (!settings.betterAuthSecret) {\n throw new Error(\"OPENGENI_BETTER_AUTH_SECRET is required when OPENGENI_PRODUCT_ACCESS_MODE=managed\");\n }\n if (!settings.delegationSecret) {\n throw new Error(\"OPENGENI_DELEGATION_SECRET is required when OPENGENI_PRODUCT_ACCESS_MODE=managed\");\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(\"OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY is required for managed mode outside local/test\");\n }\n }\n environmentsEncryptionKeyBytes(settings);\n if (\n settings.productAccessMode === \"configured\"\n && ![\"local\", \"test\"].includes(settings.environment)\n && !settings.delegationSecret\n && !settings.authRequired\n ) {\n throw new Error(\"OPENGENI_PRODUCT_ACCESS_MODE=configured requires OPENGENI_DELEGATION_SECRET or OPENGENI_AUTH_REQUIRED=true outside local/test\");\n }\n if (settings.billingMode === \"stripe\") {\n if (!settings.stripeSecretKey || !settings.stripeWebhookSecret) {\n throw new Error(\"OPENGENI_STRIPE_SECRET_KEY and OPENGENI_STRIPE_WEBHOOK_SECRET are required when OPENGENI_BILLING_MODE=stripe\");\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(`Missing model pricing for managed billing model(s): ${missing.join(\", \")}. Set OPENGENI_MODEL_PRICING_JSON.`);\n }\n }\n if (settings.usageLimitsMode === \"static\") {\n const limits = configuredStaticUsageLimits(settings);\n if (Object.keys(limits).length === 0) {\n throw new Error(\"OPENGENI_STATIC_USAGE_LIMITS_JSON must define at least one cap when OPENGENI_USAGE_LIMITS_MODE=static\");\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(\"OPENGENI_STATIC_ENTITLEMENTS_JSON must define at least one feature when OPENGENI_ENTITLEMENTS_MODE=static\");\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(\"Azure OpenAI requires OPENGENI_AZURE_OPENAI_BASE_URL or OPENGENI_AZURE_OPENAI_ENDPOINT\");\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(\"OPENGENI_MODAL_TOKEN_ID and OPENGENI_MODAL_TOKEN_SECRET must both be set or both omitted\");\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 (value === undefined || value === null || (typeof value === \"string\" && value.trim().length === 0)) {\n throw new Error(`${required.env} is required when OPENGENI_SANDBOX_BACKEND=${settings.sandboxBackend}`);\n }\n }\n if (settings.objectStorageBackend === \"s3-compatible\" || settings.objectStorageBackend === \"aws-s3\") {\n if (Boolean(settings.objectStorageAccessKeyId) !== Boolean(settings.objectStorageSecretAccessKey)) {\n throw new Error(\"OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID and OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY must both be set or both omitted\");\n }\n if (settings.objectStorageBackend === \"s3-compatible\" && (settings.objectStorageEndpoint || settings.objectStorageSandboxEndpoint) && (!settings.objectStorageAccessKeyId || !settings.objectStorageSecretAccessKey)) {\n throw new Error(\"S3-compatible object storage endpoints require OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID and OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY\");\n }\n if (settings.objectStorageAzureConnectionString || settings.objectStorageAzureAccountName || settings.objectStorageAzureAccountKey || settings.objectStorageAzureEndpoint) {\n throw new Error(\"S3 object storage uses OPENGENI_OBJECT_STORAGE_* S3 settings, not OPENGENI_OBJECT_STORAGE_AZURE_* settings\");\n }\n if (settings.objectStorageGcsProjectId || settings.objectStorageGcsCredentialsJson || settings.objectStorageGcsKeyFilename || settings.objectStorageGcsApiEndpoint) {\n throw new Error(\"S3 object storage uses OPENGENI_OBJECT_STORAGE_* S3 settings, not OPENGENI_OBJECT_STORAGE_GCS_* settings\");\n }\n } else if (settings.objectStorageBackend === \"azure-blob\") {\n if (settings.objectStorageEndpoint || settings.objectStorageSandboxEndpoint || settings.objectStorageAccessKeyId || settings.objectStorageSecretAccessKey) {\n throw new Error(\"Azure Blob storage uses OPENGENI_OBJECT_STORAGE_AZURE_* settings, not S3-compatible object storage settings\");\n }\n if (settings.objectStorageGcsProjectId || settings.objectStorageGcsCredentialsJson || settings.objectStorageGcsKeyFilename || settings.objectStorageGcsApiEndpoint) {\n throw new Error(\"Azure Blob storage uses OPENGENI_OBJECT_STORAGE_AZURE_* settings, not OPENGENI_OBJECT_STORAGE_GCS_* settings\");\n }\n const hasConnectionString = Boolean(settings.objectStorageAzureConnectionString);\n const hasSharedKey = Boolean(settings.objectStorageAzureAccountName) && Boolean(settings.objectStorageAzureAccountKey);\n if (!hasConnectionString && !hasSharedKey) {\n throw new Error(\"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 } else {\n if (settings.objectStorageEndpoint || settings.objectStorageSandboxEndpoint || settings.objectStorageAccessKeyId || settings.objectStorageSecretAccessKey) {\n throw new Error(\"GCS object storage uses OPENGENI_OBJECT_STORAGE_GCS_* settings, not S3-compatible object storage settings\");\n }\n if (settings.objectStorageAzureConnectionString || settings.objectStorageAzureAccountName || settings.objectStorageAzureAccountKey || settings.objectStorageAzureEndpoint) {\n throw new Error(\"GCS object storage uses OPENGENI_OBJECT_STORAGE_GCS_* settings, not OPENGENI_OBJECT_STORAGE_AZURE_* settings\");\n }\n if (settings.objectStorageGcsCredentialsJson) {\n parseGcsCredentialsJson(settings.objectStorageGcsCredentialsJson);\n }\n }\n if (settings.documentChunkOverlap >= settings.documentChunkSize) {\n throw new Error(\"OPENGENI_DOCUMENT_CHUNK_OVERLAP must be smaller than OPENGENI_DOCUMENT_CHUNK_SIZE\");\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 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 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 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 // --- stream-token secret: required-when-desktop, but GRACEFULLY DEGRADE (I8) ---\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(`OPENGENI_MODEL_PROVIDERS_JSON provider id ${provider.id} collides with the built-in provider id`);\n }\n if (providerIds.has(provider.id)) {\n throw new Error(`OPENGENI_MODEL_PROVIDERS_JSON contains duplicate provider id ${provider.id}`);\n }\n providerIds.add(provider.id);\n if (!resolveProviderApiKey(provider)) {\n throw new Error(`OPENGENI_MODEL_PROVIDERS_JSON provider ${provider.id} requires a resolvable API key (set apiKey or apiKeyEnv)`);\n }\n }\n}\n\n/**\n * Resolve the secret used to sign/verify scoped stream tokens (master-spine\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 (I8/OD-8). 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/dossier §10.2). 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/dossier §10.5). 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.split(\",\").map((value) => value.trim()).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 }\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,OACK;AACP,SAAS,6BAA6B;AACtC,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;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA,OAAO,CAAC;AAAA,EACV;AACF;AAUO,IAAM,sCAAsC;AAkB5C,IAAM,6BAA6B;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;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;AACvC,SAAO,IAAI,MAAM,GAAG,EAAE,IAAI,CAAC,UAAU,MAAM,KAAK,CAAC,EAAE,OAAO,OAAO;AACnE;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,EAAE;AAAA,EAC/F;AACF;AAEA,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import {\n BillingMode,\n CAPABILITY_DESCRIPTORS,\n Entitlements,\n EntitlementsMode,\n ProductAccessMode,\n ReasoningEffort,\n SandboxBackend,\n StaticUsageLimits,\n UsageLimitsMode,\n} from \"@opengeni/contracts\";\nimport { CODEX_MODEL_ID_PREFIX } from \"@opengeni/codex/constants\";\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-IDENTICAL to the historical\n * hardcoded preamble. The template below is exactly the historical lines 1–11\n * joined by \" \", followed by \" \" + the placeholder. Changing a single\n * character here changes that default; a runtime test pins it.\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/<owner>/<repo>.\",\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, GitHub CLI, and repository tools when relevant.\",\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 GitHub 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\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 (SPIKE-1 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 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>` (or `/latest/download/<asset>`).\n agentReleasesBaseUrl: z.string().url().default(\"https://github.com/Cloudgeni-ai/opengeni/releases\"),\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-surfacing scoped stream-token HMAC secret (master-spine §C.3 / I8).\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 (I8/OD-8).\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 environmentsEncryptionKey: z.string().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 // Where turn-input conversation history comes from (issue #35):\n // \"items\" (default) = the session_history_items table (SDK-native,\n // version-stable conversation truth); \"run_state\" = the legacy serialized\n // RunState blob. Items and the sandbox envelope are dual-written\n // unconditionally; this flag governs the read path only, so flipping back to\n // \"run_state\" remains a safe rollback at any time.\n sessionHistorySource: z.enum([\"run_state\", \"items\"]).default(\"items\"),\n // Provider-aware conversation context management (long-lived sessions\n // otherwise grow unbounded until they overflow the model context window and\n // hard-fail every turn). Resolution (see resolveContextCompactionMode):\n // \"auto\" (default) -> \"server\" when openaiProvider === \"openai\" (the\n // OpenAI platform Responses API honors server-side context_management),\n // else \"client\" (Azure rejects context_management with a 400, so we run\n // our own client-side compaction).\n // \"server\" / \"client\" -> force that path regardless of provider.\n // \"off\" -> neither path (legacy unbounded growth; escape hatch only).\n contextCompactionMode: z.enum([\"auto\", \"server\", \"client\", \"off\"]).default(\"auto\"),\n // The model's real context window in tokens. gpt-5.5's true window is\n // 1,050,000; it is absent from the SDK's hardcoded compaction window map (it\n // knows only up to gpt-5.4), so the SDK's DynamicCompactionPolicy would fall\n // back to a wrong 240k. We pass an explicit StaticCompactionPolicy threshold\n // derived from these settings on the server path, and use the same numbers to\n // budget the client path.\n contextWindowTokens: z.coerce.number().int().positive().default(1_050_000),\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 // Server path only: explicit compact_threshold (tokens) handed to the SDK's\n // StaticCompactionPolicy. Defaults to floor(B * contextCompactSoftFraction)\n // when unset.\n contextServerCompactThresholdTokens: z.coerce.number().int().positive().optional(),\n // Server path/back-compat knobs. The client compaction path ignores these:\n // it uses Codex-parity 0.9 * (window - reserved output - 20k summary buffer).\n contextCompactSoftFraction: z.coerce.number().positive().max(1).default(0.70),\n contextCompactHardFraction: z.coerce.number().positive().max(1).default(0.85),\n // Deprecated for the client path; parsed for env/back-compat only.\n contextKeepRecentTokens: z.coerce.number().int().positive().default(32_000),\n // Parsed for back-compat. Client compaction uses the fixed 20k Codex summary\n // buffer as its generated-summary output ceiling.\n contextSummaryMaxTokens: z.coerce.number().int().positive().default(20_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.5\"),\n openaiAllowedModels: z.string().default(\"gpt-5.5,gpt-5.4,gpt-5.4-mini\"),\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 // 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 byte-identical to the historical hardcoded preamble.\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 // 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 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 // --- 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 (dossier §17/§25.1).\n sandboxSelfhostedEnabled: 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/dossier\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; dossier\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 // --- 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 // 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 // --- 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.enum([\"s3-compatible\", \"aws-s3\", \"azure-blob\", \"gcs\"]).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.array(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 /**\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 })).default([]),\n});\n\nexport type Settings = z.infer<typeof SettingsSchema>;\nexport type McpServerConfig = Settings[\"mcpServers\"][number];\nexport type ModelPricing = {\n inputMicrosPerMillionTokens: number;\n cachedInputMicrosPerMillionTokens?: number | undefined;\n outputMicrosPerMillionTokens: number;\n marginBps?: number | 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\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.object({\n id: z.string().min(1), // model id sent to the provider, e.g. \"accounts/fireworks/models/glm-5p2\"\n label: z.string().min(1).optional(), // display name; defaults to id\n contextWindowTokens: z.number().int().positive().optional(),\n reasoningEffort: z.boolean().optional(), // model accepts a reasoning-effort control\n hostedWebSearch: z.boolean().optional(), // provider executes the hosted web_search tool for this model\n pricing: ModelPricingSchema.optional(),\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 models: z.array(RegistryModelSchema).min(1),\n});\nexport type RegistryProvider = z.infer<typeof RegistryProviderSchema>;\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. compactionMode\n * is \"server\" only for the built-in OpenAI platform provider (its Responses API\n * honors server-side context_management) and \"client\" for everything else.\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 compactionMode: ContextCompactionMode; // \"server\" only for built-in OpenAI; \"client\" otherwise\n}\n\n/** A single exposed model + the provider that serves it. */\nexport interface ConfiguredModel {\n id: string;\n label: string;\n providerId: string;\n providerLabel: string;\n api: ModelProviderApi;\n contextWindowTokens?: number | undefined;\n reasoningEffort: boolean;\n hostedWebSearch: boolean;\n}\n\nexport const defaultModelPricing: Record<string, ModelPricing> = {\n \"gpt-5.5\": {\n inputMicrosPerMillionTokens: 5_000_000,\n cachedInputMicrosPerMillionTokens: 500_000,\n outputMicrosPerMillionTokens: 30_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<z.infer<typeof SandboxBackend>, readonly SandboxRequiredEnv[]> = {\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: [\n { field: \"daytonaApiKey\", env: \"OPENGENI_DAYTONA_API_KEY\" },\n ],\n runloop: [\n { field: \"runloopApiKey\", env: \"OPENGENI_RUNLOOP_API_KEY\" },\n ],\n e2b: [\n { field: \"e2bApiKey\", env: \"OPENGENI_E2B_API_KEY\" },\n ],\n blaxel: [\n { field: \"blaxelApiKey\", env: \"OPENGENI_BLAXEL_API_KEY\" },\n ],\n cloudflare: [\n { field: \"cloudflareWorkerUrl\", env: \"OPENGENI_CLOUDFLARE_WORKER_URL\" },\n ],\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: optional(\"OPENGENI_DEPLOYMENT_REVISION\") ?? optional(\"SOURCE_VERSION\") ?? 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 startupDependencyRetryAttempts: optional(\"OPENGENI_STARTUP_DEPENDENCY_RETRY_ATTEMPTS\"),\n startupDependencyRetryInitialDelayMs: optional(\"OPENGENI_STARTUP_DEPENDENCY_RETRY_INITIAL_DELAY_MS\"),\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: optional(\"OPENGENI_OTEL_EXPORTER_OTLP_ENDPOINT\") ?? optional(\"OTEL_EXPORTER_OTLP_ENDPOINT\"),\n observabilityOtlpHeaders: 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 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 environmentsEncryptionKey: optional(\"OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY\"),\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 sessionHistorySource: optional(\"OPENGENI_SESSION_HISTORY_SOURCE\"),\n contextCompactionMode: optional(\"OPENGENI_CONTEXT_COMPACTION_MODE\"),\n contextWindowTokens: optional(\"OPENGENI_CONTEXT_WINDOW_TOKENS\"),\n contextReservedOutputTokens: optional(\"OPENGENI_CONTEXT_RESERVED_OUTPUT_TOKENS\"),\n contextServerCompactThresholdTokens: optional(\"OPENGENI_CONTEXT_SERVER_COMPACT_THRESHOLD_TOKENS\"),\n contextCompactSoftFraction: optional(\"OPENGENI_CONTEXT_COMPACT_SOFT_FRACTION\"),\n contextCompactHardFraction: optional(\"OPENGENI_CONTEXT_COMPACT_HARD_FRACTION\"),\n contextKeepRecentTokens: optional(\"OPENGENI_CONTEXT_KEEP_RECENT_TOKENS\"),\n contextSummaryMaxTokens: optional(\"OPENGENI_CONTEXT_SUMMARY_MAX_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 codexProductSku: optional(\"OPENGENI_CODEX_PRODUCT_SKU\"),\n codexRotationNearExhaustionPct: optional(\"OPENGENI_CODEX_ROTATION_NEAR_EXHAUSTION_PCT\"),\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 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 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 sandboxSelfhostedEnabled: optional(\"OPENGENI_SANDBOX_SELFHOSTED_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 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 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 sandboxWarmRateMicrosPerSecondJson: optional(\"OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON\"),\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(settings: Settings, source: NodeJS.ProcessEnv = process.env): 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\n/** The built-in provider's stable id: \"openai\" on the OpenAI platform, \"azure\" on Azure. */\nfunction 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\", compactionMode from\n * resolveContextCompactionMode), then each registry provider in declaration\n * order (compactionMode \"client\"). 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 builtin: ResolvedModelProvider = {\n id: builtinProviderId(settings),\n label: builtinProviderLabel(settings),\n kind: \"api-key\",\n api: \"responses\",\n builtin: true,\n compactionMode: resolveContextCompactionMode(settings),\n };\n if (settings.openaiProvider === \"azure\") {\n builtin.baseUrl = settings.azureOpenaiBaseUrl ?? settings.azureOpenaiEndpoint;\n builtin.apiKey = settings.azureOpenaiApiKey ?? settings.azureOpenaiAdToken;\n } else {\n builtin.baseUrl = settings.openaiBaseUrl;\n builtin.apiKey = settings.openaiApiKey;\n }\n const registry = parseModelProvidersJson(settings.modelProvidersJson).map((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 compactionMode: \"client\",\n }));\n return [builtin, ...registry];\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 // 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.5\") 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 registryOwnedIds = new Set(\n parseModelProvidersJson(settings.modelProvidersJson).flatMap((provider) => provider.models.map((model) => model.id)),\n );\n const isRegistryNamespaced = (id: string): boolean =>\n id.startsWith(CODEX_MODEL_ID_PREFIX) || (id.includes(\"/\") && registryOwnedIds.has(id));\n const out: ConfiguredModel[] = uniqueValues([settings.openaiModel, ...splitCsv(settings.openaiAllowedModels)])\n .filter((id) => !isRegistryNamespaced(id))\n .map((id) => ({\n id,\n label: id,\n providerId: builtinId,\n providerLabel: builtinLabel,\n api: \"responses\" as const,\n contextWindowTokens: settings.contextWindowTokens,\n reasoningEffort: true,\n hostedWebSearch: settings.webSearchEnabled,\n }));\n for (const provider of parseModelProvidersJson(settings.modelProvidersJson)) {\n const providerLabel = provider.label ?? provider.id;\n for (const model of provider.models) {\n out.push({\n id: model.id,\n label: model.label ?? model.id,\n providerId: provider.id,\n providerLabel,\n api: provider.api,\n ...(model.contextWindowTokens === undefined ? {} : { contextWindowTokens: model.contextWindowTokens }),\n reasoningEffort: model.reasoningEffort ?? false,\n hostedWebSearch: model.hostedWebSearch ?? false,\n });\n }\n }\n const seen = new Set<string>();\n return out.filter((model) => {\n if (seen.has(model.id)) {\n return false;\n }\n seen.add(model.id);\n return true;\n });\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 model = configuredModels(settings).find((candidate) => candidate.id === modelId);\n if (!model) {\n return undefined;\n }\n const provider = configuredProviders(settings).find((candidate) => candidate.id === model.providerId);\n if (!provider) {\n return undefined;\n }\n return { provider, model };\n}\n\n/**\n * Effective per-model pricing. Merge order (later wins):\n * defaultModelPricing → registry model `pricing` entries (keyed by model id)\n * → parseModelPricingJson(settings.modelPricingJson) (explicit JSON wins).\n */\nexport function configuredModelPricing(settings: Settings): Record<string, ModelPricing> {\n const registry: Record<string, ModelPricing> = {};\n for (const provider of parseModelProvidersJson(settings.modelProvidersJson)) {\n for (const model of provider.models) {\n if (model.pricing) {\n registry[model.id] = model.pricing;\n }\n }\n }\n const configured = parseModelPricingJson(settings.modelPricingJson);\n return {\n ...defaultModelPricing,\n ...registry,\n ...configured,\n };\n}\n\n/**\n * Resolved conversation-context compaction path for a run.\n * - \"server\": let the OpenAI platform Responses API compact server-side (the\n * SDK emits context_management; we pass the correct gpt-5.5 threshold).\n * - \"client\": run OpenGeni's own client-side compaction (Azure and any other\n * backend that rejects/ignores context_management).\n * - \"off\": neither (legacy unbounded growth; escape hatch).\n *\n * \"auto\" maps to \"server\" on the OpenAI platform provider and \"client\"\n * otherwise — Azure's Responses API returns 400 unsupported_parameter for\n * context_management, so it must never take the server path.\n */\nexport type ContextCompactionMode = \"server\" | \"client\" | \"off\";\n\nexport function resolveContextCompactionMode(settings: Pick<Settings, \"contextCompactionMode\" | \"openaiProvider\">): ContextCompactionMode {\n switch (settings.contextCompactionMode) {\n case \"server\":\n return \"server\";\n case \"client\":\n return \"client\";\n case \"off\":\n return \"off\";\n case \"auto\":\n default:\n return settings.openaiProvider === \"openai\" ? \"server\" : \"client\";\n }\n}\n\n/** Usable input-token budget B = window - reserved output. */\nexport function contextInputBudgetTokens(settings: Pick<Settings, \"contextWindowTokens\" | \"contextReservedOutputTokens\">): number {\n return Math.max(0, settings.contextWindowTokens - settings.contextReservedOutputTokens);\n}\n\n/**\n * Server-path compact_threshold (tokens) handed to the SDK's\n * StaticCompactionPolicy: the explicit override when set, else\n * floor(B * softFraction). This is what sidesteps the SDK's wrong 240k\n * fallback for gpt-5.5 (which is absent from its hardcoded window map).\n */\nexport function contextServerCompactThreshold(settings: Pick<Settings, \"contextWindowTokens\" | \"contextReservedOutputTokens\" | \"contextServerCompactThresholdTokens\" | \"contextCompactSoftFraction\">): number {\n if (settings.contextServerCompactThresholdTokens) {\n return settings.contextServerCompactThresholdTokens;\n }\n return Math.floor(contextInputBudgetTokens(settings) * settings.contextCompactSoftFraction);\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(settings: Settings, model: string, usage: ModelUsageInput): number {\n const pricing = configuredModelPricing(settings)[model];\n if (!pricing) {\n throw new Error(`Missing model pricing for ${model}`);\n }\n const entries = usage.requestUsageEntries && usage.requestUsageEntries.length > 0 ? usage.requestUsageEntries : [usage];\n const rawCost = entries.reduce((sum, entry) => sum + calculateEntryCostMicros(pricing, entry), 0);\n const marginBps = pricing.marginBps ?? 0;\n return Math.ceil(rawCost * (10_000 + marginBps) / 10_000);\n}\n\nexport function configuredAllowedReasoningEfforts(settings: Settings): Array<z.infer<typeof ReasoningEffort>> {\n return uniqueValues([settings.openaiReasoningEffort, ...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(\"OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY must be base64 for exactly 32 bytes (generate with: openssl rand -base64 32)\");\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 SPIKE-1 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(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((entry): entry is [string, string] => typeof entry[1] === \"string\" && entry[1].trim().length > 0));\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 GitHub App installation token\n * VALUE that `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) the token VALUE never rides the manifest at all — it is seeded to a\n * FILE inside the box (agent-managed, refreshable mid-turn via the `github_token`\n * MCP tool) and git auth flows through GIT_ASKPASS -> that file. What IS stable and\n * lives here is the token FILE PATH (`OPENGENI_GIT_TOKEN_FILE`): a constant derived\n * from HOME, so it appears IDENTICALLY on BOTH the turn AND every attach manifest\n * (the SDK's per-turn provided-session env delta stays empty even as the token\n * rotates). The attach surfaces have only the `Session` (no repo resources) and so\n * never seed a token, but the file-path pointer is harmless (an unwritten file\n * simply yields no auth); the BLOCKING attach-vs-turn error this helper fixes is\n * for the common (no-repo) and workspace-environment-attached cases.\n */\nexport function stableSandboxEnvironmentForRun(\n settings: Settings,\n workspaceEnvironment: Record<string, 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 token FILE PATH. A constant derived from the\n // resolved HOME (falling back to the descriptor workspaceRoot), so it is\n // parity-safe — it joins the shared base and therefore appears IDENTICALLY on\n // BOTH the worker-turn manifest AND every API-direct attach manifest, keeping\n // the SDK's provided-session env delta empty. Only the PATH is stable; the token\n // VALUE lives exclusively in the file (agent-managed, refreshable mid-turn), never\n // the manifest env.\n environment.OPENGENI_GIT_TOKEN_FILE ??= `${environment.HOME ?? descriptor.workspaceRoot}/.opengeni/git-token`;\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(resources: ReadonlyArray<{ kind: string; githubInstallationId?: unknown; githubRepositoryId?: unknown }>): 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((resource) => resource.kind === \"repository\" && positive(resource.githubInstallationId) && positive(resource.githubRepositoryId));\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(settings: Settings): 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) => value.toLowerCase());\n if (profiles.includes(\"none\")) {\n if (profiles.length > 1) {\n throw new Error(\"OPENGENI_SANDBOX_PREPARATION_PROFILES cannot combine none with other profiles\");\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}`);\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}`);\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(`OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON must be valid JSON: ${message}`);\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(\"OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON must be a JSON object keyed by backend name\");\n }\n const out: Record<string, number> = {};\n for (const [backend, value] of Object.entries(parsed)) {\n if (!backend.trim()) {\n throw new Error(\"OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON contains an empty backend name\");\n }\n const rate = typeof value === \"number\" ? value : Number(value);\n if (!Number.isFinite(rate) || rate < 0) {\n throw new Error(`OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON rate for ${backend} must be a non-negative number`);\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 }\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(`OPENGENI_MODEL_PROVIDERS_JSON provider[${index}] is invalid: ${result.error.message}`);\n }\n return result.data;\n });\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 }\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 }\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 = pricing.cachedInputMicrosPerMillionTokens ?? pricing.inputMicrosPerMillionTokens;\n return 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\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 += 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 id: \"files\",\n name: \"Files\",\n url: firstPartyMcpUrl,\n allowedTools: [\"files_get_download_url\"],\n cacheToolsList: true,\n }]),\n ...(hasDocs ? [] : [{\n id: \"docs\",\n name: \"Document Search\",\n url: firstPartyDocsMcpUrl,\n allowedTools: [\"search_documents\", \"fetch_document_chunk\", \"list_document_bases\"],\n cacheToolsList: false,\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 settings.opengeniMcpUrl ?? `http://127.0.0.1:${settings.apiPort}/v1/workspaces/{workspaceId}/mcp`;\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 if (settings.productAccessMode === \"managed\") {\n if (!settings.publicBaseUrl) {\n throw new Error(\"OPENGENI_PUBLIC_BASE_URL is required when OPENGENI_PRODUCT_ACCESS_MODE=managed\");\n }\n if (!settings.betterAuthSecret) {\n throw new Error(\"OPENGENI_BETTER_AUTH_SECRET is required when OPENGENI_PRODUCT_ACCESS_MODE=managed\");\n }\n if (!settings.delegationSecret) {\n throw new Error(\"OPENGENI_DELEGATION_SECRET is required when OPENGENI_PRODUCT_ACCESS_MODE=managed\");\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(\"OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY is required for managed mode outside local/test\");\n }\n }\n environmentsEncryptionKeyBytes(settings);\n if (\n settings.productAccessMode === \"configured\"\n && ![\"local\", \"test\"].includes(settings.environment)\n && !settings.delegationSecret\n && !settings.authRequired\n ) {\n throw new Error(\"OPENGENI_PRODUCT_ACCESS_MODE=configured requires OPENGENI_DELEGATION_SECRET or OPENGENI_AUTH_REQUIRED=true outside local/test\");\n }\n if (settings.billingMode === \"stripe\") {\n if (!settings.stripeSecretKey || !settings.stripeWebhookSecret) {\n throw new Error(\"OPENGENI_STRIPE_SECRET_KEY and OPENGENI_STRIPE_WEBHOOK_SECRET are required when OPENGENI_BILLING_MODE=stripe\");\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(`Missing model pricing for managed billing model(s): ${missing.join(\", \")}. Set OPENGENI_MODEL_PRICING_JSON.`);\n }\n }\n if (settings.usageLimitsMode === \"static\") {\n const limits = configuredStaticUsageLimits(settings);\n if (Object.keys(limits).length === 0) {\n throw new Error(\"OPENGENI_STATIC_USAGE_LIMITS_JSON must define at least one cap when OPENGENI_USAGE_LIMITS_MODE=static\");\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(\"OPENGENI_STATIC_ENTITLEMENTS_JSON must define at least one feature when OPENGENI_ENTITLEMENTS_MODE=static\");\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(\"Azure OpenAI requires OPENGENI_AZURE_OPENAI_BASE_URL or OPENGENI_AZURE_OPENAI_ENDPOINT\");\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(\"OPENGENI_MODAL_TOKEN_ID and OPENGENI_MODAL_TOKEN_SECRET must both be set or both omitted\");\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 (value === undefined || value === null || (typeof value === \"string\" && value.trim().length === 0)) {\n throw new Error(`${required.env} is required when OPENGENI_SANDBOX_BACKEND=${settings.sandboxBackend}`);\n }\n }\n if (settings.objectStorageBackend === \"s3-compatible\" || settings.objectStorageBackend === \"aws-s3\") {\n if (Boolean(settings.objectStorageAccessKeyId) !== Boolean(settings.objectStorageSecretAccessKey)) {\n throw new Error(\"OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID and OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY must both be set or both omitted\");\n }\n if (settings.objectStorageBackend === \"s3-compatible\" && (settings.objectStorageEndpoint || settings.objectStorageSandboxEndpoint) && (!settings.objectStorageAccessKeyId || !settings.objectStorageSecretAccessKey)) {\n throw new Error(\"S3-compatible object storage endpoints require OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID and OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY\");\n }\n if (settings.objectStorageAzureConnectionString || settings.objectStorageAzureAccountName || settings.objectStorageAzureAccountKey || settings.objectStorageAzureEndpoint) {\n throw new Error(\"S3 object storage uses OPENGENI_OBJECT_STORAGE_* S3 settings, not OPENGENI_OBJECT_STORAGE_AZURE_* settings\");\n }\n if (settings.objectStorageGcsProjectId || settings.objectStorageGcsCredentialsJson || settings.objectStorageGcsKeyFilename || settings.objectStorageGcsApiEndpoint) {\n throw new Error(\"S3 object storage uses OPENGENI_OBJECT_STORAGE_* S3 settings, not OPENGENI_OBJECT_STORAGE_GCS_* settings\");\n }\n } else if (settings.objectStorageBackend === \"azure-blob\") {\n if (settings.objectStorageEndpoint || settings.objectStorageSandboxEndpoint || settings.objectStorageAccessKeyId || settings.objectStorageSecretAccessKey) {\n throw new Error(\"Azure Blob storage uses OPENGENI_OBJECT_STORAGE_AZURE_* settings, not S3-compatible object storage settings\");\n }\n if (settings.objectStorageGcsProjectId || settings.objectStorageGcsCredentialsJson || settings.objectStorageGcsKeyFilename || settings.objectStorageGcsApiEndpoint) {\n throw new Error(\"Azure Blob storage uses OPENGENI_OBJECT_STORAGE_AZURE_* settings, not OPENGENI_OBJECT_STORAGE_GCS_* settings\");\n }\n const hasConnectionString = Boolean(settings.objectStorageAzureConnectionString);\n const hasSharedKey = Boolean(settings.objectStorageAzureAccountName) && Boolean(settings.objectStorageAzureAccountKey);\n if (!hasConnectionString && !hasSharedKey) {\n throw new Error(\"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 } else {\n if (settings.objectStorageEndpoint || settings.objectStorageSandboxEndpoint || settings.objectStorageAccessKeyId || settings.objectStorageSecretAccessKey) {\n throw new Error(\"GCS object storage uses OPENGENI_OBJECT_STORAGE_GCS_* settings, not S3-compatible object storage settings\");\n }\n if (settings.objectStorageAzureConnectionString || settings.objectStorageAzureAccountName || settings.objectStorageAzureAccountKey || settings.objectStorageAzureEndpoint) {\n throw new Error(\"GCS object storage uses OPENGENI_OBJECT_STORAGE_GCS_* settings, not OPENGENI_OBJECT_STORAGE_AZURE_* settings\");\n }\n if (settings.objectStorageGcsCredentialsJson) {\n parseGcsCredentialsJson(settings.objectStorageGcsCredentialsJson);\n }\n }\n if (settings.documentChunkOverlap >= settings.documentChunkSize) {\n throw new Error(\"OPENGENI_DOCUMENT_CHUNK_OVERLAP must be smaller than OPENGENI_DOCUMENT_CHUNK_SIZE\");\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 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 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 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 // --- stream-token secret: required-when-desktop, but GRACEFULLY DEGRADE (I8) ---\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(`OPENGENI_MODEL_PROVIDERS_JSON provider id ${provider.id} collides with the built-in provider id`);\n }\n if (providerIds.has(provider.id)) {\n throw new Error(`OPENGENI_MODEL_PROVIDERS_JSON contains duplicate provider id ${provider.id}`);\n }\n providerIds.add(provider.id);\n if (!resolveProviderApiKey(provider)) {\n throw new Error(`OPENGENI_MODEL_PROVIDERS_JSON provider ${provider.id} requires a resolvable API key (set apiKey or apiKeyEnv)`);\n }\n }\n}\n\n/**\n * Resolve the secret used to sign/verify scoped stream tokens (master-spine\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 (I8/OD-8). 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/dossier §10.2). 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/dossier §10.5). 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.split(\",\").map((value) => value.trim()).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 }\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,OACK;AACP,SAAS,6BAA6B;AACtC,SAAS,SAAS;AAElB,IAAM,UAAU;AAChB,IAAM,aAAa;AACnB,IAAM,aAAa,EAAE,WAAW,CAAC,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,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,EAAE;AAAA,EAC/F;AACF;AAEA,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@opengeni/config",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.5",
|
|
4
4
|
"description": "OpenGeni runtime configuration: settings resolution, deployment knobs, and config validation shared across the server packages.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
},
|
|
37
37
|
"dependencies": {
|
|
38
38
|
"@opengeni/codex": "^0.2.1",
|
|
39
|
-
"@opengeni/contracts": "^0.
|
|
39
|
+
"@opengeni/contracts": "^0.7.0",
|
|
40
40
|
"zod": "^4.2.1"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
package/src/index.ts
CHANGED
|
@@ -105,6 +105,9 @@ const SettingsSchema = z.object({
|
|
|
105
105
|
serviceName: z.string().default("opengeni"),
|
|
106
106
|
environment: z.string().default("local"),
|
|
107
107
|
deploymentRevision: z.string().default("dev"),
|
|
108
|
+
// The release-train version baked into official images (OPENGENI_SERVER_VERSION).
|
|
109
|
+
// Absent on dev/source builds — consumers must treat it as optional.
|
|
110
|
+
serverVersion: z.string().optional(),
|
|
108
111
|
databaseUrl: z.string().default("postgres://opengeni:opengeni@127.0.0.1:5432/opengeni"),
|
|
109
112
|
// Step I (§7.8 runtime half). Dedicated Postgres schema for the EMBEDDED
|
|
110
113
|
// topology. Default "" → standalone: no search_path scoping, server default
|
|
@@ -208,6 +211,7 @@ const SettingsSchema = z.object({
|
|
|
208
211
|
authAllowMetrics: EnvBoolean.default(false),
|
|
209
212
|
apiHost: z.string().default("0.0.0.0"),
|
|
210
213
|
apiPort: z.coerce.number().int().positive().default(8000),
|
|
214
|
+
workerHttpPort: z.coerce.number().int().positive().default(8001),
|
|
211
215
|
opengeniMcpUrl: z.string().url().optional(),
|
|
212
216
|
corsAllowOriginRegex: z.string().default(String.raw`^https?://(localhost|127\.0\.0\.1)(:\d+)?$`),
|
|
213
217
|
openaiProvider: z.enum(["openai", "azure"]).default("openai"),
|
|
@@ -834,6 +838,7 @@ export function getSettings(): Settings {
|
|
|
834
838
|
serviceName: optional("OPENGENI_SERVICE_NAME"),
|
|
835
839
|
environment: optional("OPENGENI_ENVIRONMENT"),
|
|
836
840
|
deploymentRevision: optional("OPENGENI_DEPLOYMENT_REVISION") ?? optional("SOURCE_VERSION") ?? optional("GITHUB_SHA"),
|
|
841
|
+
serverVersion: optional("OPENGENI_SERVER_VERSION"),
|
|
837
842
|
databaseUrl: optional("OPENGENI_DATABASE_URL"),
|
|
838
843
|
dbSchema: optional("OPENGENI_DB_SCHEMA"),
|
|
839
844
|
rlsStrategy: optional("OPENGENI_RLS_STRATEGY"),
|
|
@@ -878,6 +883,7 @@ export function getSettings(): Settings {
|
|
|
878
883
|
authAllowMetrics: optional("OPENGENI_AUTH_ALLOW_METRICS"),
|
|
879
884
|
apiHost: optional("OPENGENI_API_HOST"),
|
|
880
885
|
apiPort: optional("OPENGENI_API_PORT"),
|
|
886
|
+
workerHttpPort: optional("OPENGENI_WORKER_HTTP_PORT"),
|
|
881
887
|
opengeniMcpUrl: optional("OPENGENI_MCP_URL"),
|
|
882
888
|
corsAllowOriginRegex: optional("OPENGENI_CORS_ALLOW_ORIGIN_REGEX"),
|
|
883
889
|
openaiProvider: optional("OPENGENI_OPENAI_PROVIDER"),
|