@opengeni/config 1.2.2 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -1,7 +1,20 @@
1
+ export { managedUserEmailAllowed } from "./managed-user-admission";
2
+ import { EnvCreditPromotionPolicy } from "./credit-promotions";
3
+ export {
4
+ CreditPromotionPolicy,
5
+ signupCreditModelIds,
6
+ promotionalCreditScope,
7
+ } from "./credit-promotions";
8
+ import { isRetiredNativeAtlassianTool } from "@opengeni/contracts/atlassian-native-retirement";
9
+ import { modelLogoUrl } from "@opengeni/contracts/model-display";
1
10
  import {
11
+ directModelConnectionSpec,
2
12
  BillingMode,
3
13
  CAPABILITY_DESCRIPTORS,
14
+ agentConfigDeploymentLimitsFromAllowlist,
15
+ type AgentConfigDeploymentLimits,
4
16
  DEFAULT_FIRST_PARTY_MCP_TOOLS,
17
+ DEFAULT_OPENGENI_DOCUMENTATION_URL,
5
18
  currentAgentLearningToolSelection,
6
19
  Entitlements,
7
20
  EntitlementsMode,
@@ -26,6 +39,7 @@ import {
26
39
  type VideoGenerationResolution,
27
40
  type FirstPartyMcpToolName as FirstPartyMcpToolNameType,
28
41
  } from "@opengeni/contracts";
42
+ import type { CodeSearchDeploymentPolicy } from "@opengeni/contracts/code-search";
29
43
  import { CODEX_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS } from "@opengeni/codex";
30
44
  import {
31
45
  CODEX_FALLBACK_MODEL_SLUGS,
@@ -48,6 +62,7 @@ import {
48
62
  } from "@opengeni/xai-subscription";
49
63
  export { XAI_SUBSCRIPTION_MODEL_ID_PREFIX } from "@opengeni/xai-subscription";
50
64
  import { createHash } from "node:crypto";
65
+ import { isIP } from "node:net";
51
66
  import { z } from "zod";
52
67
 
53
68
  const envName = /^[A-Za-z_][A-Za-z0-9_]*$/;
@@ -63,6 +78,9 @@ export const DEFAULT_MODEL_COST_POLICY_JSON = JSON.stringify({
63
78
  // a configured request timeout may never consume the entire durable claim.
64
79
  export const SANDBOX_ARCHIVE_CAPTURE_MAX_TIMEOUT_MS = 60 * 60_000;
65
80
  export const SANDBOX_ARCHIVE_CAPTURE_SETTLEMENT_GRACE_MS = 10_000;
81
+ // Deadline rotation gives retained legacy commands a bounded stop window
82
+ // before capturing the still-running sandbox's current files.
83
+ export const SANDBOX_DEADLINE_COMMAND_STOP_GRACE_MS = 120_000;
66
84
  export const SANDBOX_SNAPSHOT_MAX_TIMEOUT_MS =
67
85
  SANDBOX_ARCHIVE_CAPTURE_MAX_TIMEOUT_MS - SANDBOX_ARCHIVE_CAPTURE_SETTLEMENT_GRACE_MS;
68
86
  export const GOOGLE_DRIVE_PROVIDER_REQUEST_TIMEOUT_MAX_MS = 60_000;
@@ -91,6 +109,13 @@ const EnvBoolean = z.preprocess((value) => {
91
109
  return value;
92
110
  }, z.boolean());
93
111
 
112
+ /** An absolute http(s) URL that is safe to render as a browser link. */
113
+ const PublicHttpUrl = z
114
+ .string()
115
+ .url()
116
+ .max(2_048)
117
+ .refine((value) => /^https?:\/\//iu.test(value), "must be an http(s) URL");
118
+
94
119
  /** Default pacing between consecutive no-input goal continuations. */
95
120
  export const DEFAULT_GOAL_IDLE_BACKOFF_MS: readonly number[] = [3_000, 30_000, 120_000, 300_000];
96
121
  export const DEFAULT_GOAL_IDLE_BACKOFF_MAX_MS = 600_000;
@@ -181,8 +206,9 @@ export const AGENT_INSTRUCTIONS_CORE_PLACEHOLDER = "{{core}}";
181
206
 
182
207
  /**
183
208
  * Default per-workspace agent persona template. This is the BRAND + tool-usage
184
- * opinion (the white-labellable surface): the "You are an OpenGeni workspace
185
- * agent." identity line, the framing/opinion lines, and the mount-path facts.
209
+ * opinion (the white-labellable surface): the general-assistant identity line,
210
+ * the framing/opinion lines, and the mount-path facts. Domain-specific tooling
211
+ * guidance (for example Terraform or Checkov) belongs in opt-in Skills.
186
212
  *
187
213
  * The CORE that MUST survive any override — the goal-loop ownership line (which
188
214
  * names the opengeni__goal_* tools) and the dynamic workspace-environment block
@@ -196,17 +222,17 @@ export const AGENT_INSTRUCTIONS_CORE_PLACEHOLDER = "{{core}}";
196
222
  * intentionally.
197
223
  */
198
224
  export const DEFAULT_AGENT_INSTRUCTIONS = [
199
- "You are an OpenGeni workspace agent.",
200
- "Follow the user's task and any enabled pack or skill instructions for the current role.",
201
- "Work inside the sandbox workspace and use filesystem and shell tools when useful.",
225
+ "You are an OpenGeni workspace agent: a general assistant for questions, writing, research, analysis, and technical work.",
226
+ "Follow the user's task and the applicable Skill instructions for the current role.",
227
+ "When a task needs files or commands, work inside the sandbox workspace with the filesystem and shell tools.",
202
228
  "Repository resources are mounted under repos/<host>/<owner>/<repo> unless the session specifies another collision-free mount path.",
203
229
  "File resources are mounted under .opengeni/files/<file-id>/ unless the session specifies another mount path.",
204
230
  "Attached files are mounted read-only; copy them before modifying.",
205
231
  "Installed and selected Skills appear in the session Skill index; follow its reading instructions and any role-specific guidance.",
206
- "Use Checkov, Terraform, Azure CLI, git provider CLIs, and repository tools when relevant; gh, glab, and az repos are pre-authenticated when the host brokers matching git credentials.",
207
- "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.",
208
- "Treat code-changing work as GitOps work: create a focused branch/commit/PR when git provider credentials are available; otherwise report exact commands and blockers.",
209
- "Return concise, factual summaries with files changed, commands run, and remaining blockers.",
232
+ "Provider CLIs such as gh, glab, and az may be pre-authenticated by the host through brokered git credentials or a sandbox preparation profile; try them before asking for credentials.",
233
+ "When the Git repository you change has a remote and git provider credentials are available, work on a focused branch and open a pull request.",
234
+ "Otherwise leave changes in the working tree and do not create or mention branches, commits, or pull requests unless the user asks; if the repository has a remote, say the changes are not pushed, and if the user asks for something you cannot make, say what blocks it.",
235
+ "Answer questions directly and briefly; after making changes, say what changed, how you checked it, and anything still blocked.",
210
236
  AGENT_INSTRUCTIONS_CORE_PLACEHOLDER,
211
237
  ].join(" ");
212
238
 
@@ -234,7 +260,7 @@ export const McpOperationRecoverySchema = z
234
260
 
235
261
  /** Public, digest-pinned desktop image used by Modal unless the operator overrides it. */
236
262
  export const DEFAULT_MODAL_IMAGE_REF =
237
- "opengenipublicneuacr.azurecr.io/opengeni-desktop@sha256:c3bd17b8841de1bff9bb2777aad422cf8c75de78e2c30f9ac81d0cd6810a1b78";
263
+ "opengenipublicneuacr.azurecr.io/opengeni-desktop@sha256:554d5b324a580071dd669e7c1190931e498eb1b397412a27c7de84a430ef393a";
238
264
 
239
265
  const SettingsSchema = z.object({
240
266
  serviceName: z.string().default("opengeni"),
@@ -244,6 +270,10 @@ const SettingsSchema = z.object({
244
270
  // Absent on dev/source builds — consumers must treat it as optional.
245
271
  serverVersion: z.string().optional(),
246
272
  databaseUrl: z.string().default("postgres://opengeni:opengeni@127.0.0.1:5432/opengeni"),
273
+ // API application pool only. Managed auth owns its separate pool; readiness
274
+ // reuses the application handle. Keep the historical default for existing
275
+ // deployments and let operators budget this per process with replica counts.
276
+ apiDatabasePoolMax: z.coerce.number().int().positive().default(32),
247
277
  // Step I (§7.8 runtime half). Dedicated Postgres schema for the EMBEDDED
248
278
  // topology. Default "" → standalone: no search_path scoping, server default
249
279
  // (`public`). When set (e.g. "opengeni"), the db handle + the managed-auth
@@ -285,6 +315,8 @@ const SettingsSchema = z.object({
285
315
  observabilityMetricsEnabled: EnvBoolean.default(true),
286
316
  observabilityOtlpEndpoint: z.string().url().optional(),
287
317
  observabilityOtlpHeaders: z.string().default(""),
318
+ observabilityDiagnosticsEndpoint: z.string().url().optional(),
319
+ observabilityDiagnosticsHeaders: z.string().default(""),
288
320
  analyticsEnabled: EnvBoolean.default(false),
289
321
  analyticsConsentRequired: EnvBoolean.default(true),
290
322
  analyticsReoClientId: z
@@ -299,13 +331,44 @@ const SettingsSchema = z.object({
299
331
  .max(32)
300
332
  .regex(/^G-[A-Z0-9]+$/u)
301
333
  .optional(),
334
+ // Optional operator-owned legal documents linked from the signed-out console.
335
+ // Unset by default, so a self-hosted deployment never shows another operator's
336
+ // policies; the managed service points these at its own published pages.
337
+ legalPrivacyPolicyUrl: PublicHttpUrl.optional(),
338
+ legalTermsOfServiceUrl: PublicHttpUrl.optional(),
339
+ // Optional operator support address, shown as a "Contact support" mailto link
340
+ // on the signed-out page and in the Help menu. Unset by default for the same
341
+ // reason as the legal links.
342
+ supportEmail: z.string().trim().email().max(254).optional(),
302
343
  publicBaseUrl: z.string().url().optional(),
344
+ // Product documentation the web console links from its Help menu. Absent
345
+ // means the public OpenGeni docs; `none` hides the link for deployments that
346
+ // publish no documentation of their own.
347
+ documentationUrl: z.preprocess(
348
+ (value) =>
349
+ typeof value === "string"
350
+ ? value.trim().toLowerCase() === "none"
351
+ ? null
352
+ : value.trim()
353
+ : value,
354
+ z
355
+ .url({ protocol: /^https?$/u, error: "must be an absolute http(s) URL or none" })
356
+ .nullable()
357
+ .default(DEFAULT_OPENGENI_DOCUMENTATION_URL),
358
+ ),
303
359
  // Standards-based OAuth authorization server for external workspace MCP
304
360
  // clients. Opt-in because it creates a new public authentication surface.
305
361
  mcpOauthEnabled: EnvBoolean.default(false),
306
- // Forwarded client addresses are ignored by default. Operators may trust an
362
+ // Client source address for every API rate limit, abuse quota, and auth
363
+ // session record (Better Auth, MCP OAuth registration, enrollment, account
364
+ // setup, login transactions). Forwarded client addresses are ignored by
365
+ // default so a caller cannot choose its own bucket. Operators may trust an
307
366
  // exact number of proxy hops only when direct access to the API is blocked.
308
- mcpOauthTrustedProxyHops: z.coerce.number().int().min(0).max(16).default(0),
367
+ apiTrustedProxyHops: z.coerce.number().int().min(0).max(16).default(0),
368
+ // Optional comma-separated CIDRs (or single addresses) of the proxy that
369
+ // connects to the API. When set, forwarded client addresses are honored
370
+ // only for requests whose transport peer is inside one of them.
371
+ apiTrustedProxyCidrs: z.string().default(""),
309
372
  // Browser origin when the web app and API use separate origins in local
310
373
  // development. Production normally leaves this unset and uses publicBaseUrl.
311
374
  webBaseUrl: z.string().url().optional(),
@@ -330,29 +393,16 @@ const SettingsSchema = z.object({
330
393
  .regex(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u)
331
394
  .optional(),
332
395
  productAccessMode: ProductAccessMode.default("local"),
333
- // --- canonical organization-tenancy authority activation, default OFF ---
334
- // The named PRE-ACTIVATION opt-out for the organization-tenancy program. FALSE (the
335
- // default, and the value an operator leaves in place to decline or defer) means
336
- // this deployment stays on the reversible legacy workspace-owned lane: no phase-F
337
- // subsystem may switch its access decision to organization/membership authority
338
- // ids. TRUE is an operator's explicit statement that the activation preconditions
339
- // in docs/organization-tenancy.md have been proven for this deployment and that
340
- // the one-way boundary is accepted.
341
- //
342
- // This is NOT a kill switch and NOT a rollback: once an activation migration has
343
- // committed, setting it back to false does not restore the legacy authority - only
344
- // forward recovery is available. It also grants and revokes nothing by itself;
345
- // every individual authorization decision keeps its own fences.
346
- //
347
- // No runtime path reads it yet: canonical activation (phase F) is unshipped, so
348
- // the flag exists to reserve the name, pin the safe default, and give every future
349
- // activation slice one gate to consult. EnvBoolean (NOT z.coerce.boolean(), which
350
- // coerces "false" -> true and would activate the moment an operator wrote the
351
- // variable out to disable it).
352
- organizationTenancyCanonicalActivationEnabled: EnvBoolean.default(false),
353
396
  billingMode: BillingMode.default("disabled"),
397
+ // Explicit launch gate for the one-time $10 verified self-service signup grant.
398
+ // A migration or deployment alone must not start issuing live credits.
399
+ verifiedSignupTrialCreditsEnabled: EnvBoolean.default(false),
400
+ creditPromotionPolicy: EnvCreditPromotionPolicy,
354
401
  entitlementsMode: EntitlementsMode.default("none"),
355
402
  usageLimitsMode: UsageLimitsMode.default("none"),
403
+ // Gate new allowance policies until every API/worker in the fleet enforces
404
+ // them. Persisted-policy enforcement and recovery reads/clears stay active.
405
+ usageAllowancesEnabled: EnvBoolean.default(false),
356
406
  staticEntitlementsJson: z.string().default("{}"),
357
407
  staticUsageLimitsJson: z.string().default("{}"),
358
408
  delegationSecret: z.string().optional(),
@@ -393,11 +443,18 @@ const SettingsSchema = z.object({
393
443
  environmentsEncryptionKey: z.string().optional(),
394
444
  integrationsEnabled: EnvBoolean.default(false),
395
445
  integrationsStateSecret: z.string().optional(),
446
+ integrationsOauthShortStateEnabled: EnvBoolean.default(false),
396
447
  integrationsAllowPrivateNetworkTargets: EnvBoolean.default(false),
397
448
  integrationsOauthClientsJson: z.string().default("{}"),
449
+ gmailWatchTopicName: z
450
+ .string()
451
+ .regex(/^projects\/[^/]+\/topics\/[^/]+$/u)
452
+ .optional(),
398
453
  slackClientId: z.string().optional(),
399
454
  slackClientSecret: z.string().optional(),
400
455
  slackSigningSecret: z.string().optional(),
456
+ // Unlisted apps share Slack’s restricted history/replies quota across all tokens.
457
+ slackAccessMode: z.enum(["limited", "full"]).default("limited"),
401
458
  slackBotDisplayName: OpenGeniSlackBotDisplayName.default("OpenGeni"),
402
459
  slackCommand: z
403
460
  .string()
@@ -484,16 +541,6 @@ const SettingsSchema = z.object({
484
541
  // into @opengeni/db once at boot.
485
542
  // Env: OPENGENI_CHILD_LIFECYCLE_NOTICES_ENABLED.
486
543
  childLifecycleNoticesEnabled: EnvBoolean.default(false),
487
- // Explicit host-owned MCP connection authority is a rolling protocol
488
- // activation. Keep it off while any API, worker, or browser bundle predates
489
- // the authority discriminator; enable it only after the whole fleet runs an
490
- // image that understands host refs. Legacy markerless non-UUID refs remain a
491
- // separate compatibility lane for already-persisted embedding integrations.
492
- // Env: OPENGENI_HOST_MCP_AUTHORITY_SOURCE_ADMISSION_ENABLED.
493
- hostMcpAuthoritySourceAdmissionEnabled: EnvBoolean.default(false),
494
- // Server-owned per-organization remote MCP resolver configuration. Optional;
495
- // inline credentials and native provider OAuth do not require this service.
496
- hostMcpCredentialResolversJson: z.string().optional(),
497
544
  // Per-channel and per-DM Slack workspace routing. Default ON. A channel does
498
545
  // not count a personal workspace as a candidate, so an organization with one
499
546
  // shared workspace resolves it as the sole candidate and never asks; the
@@ -551,6 +598,9 @@ const SettingsSchema = z.object({
551
598
  authAllowMetrics: EnvBoolean.default(false),
552
599
  apiHost: z.string().default("0.0.0.0"),
553
600
  apiPort: z.coerce.number().int().positive().default(8000),
601
+ // When set, GET /metrics is served only on this dedicated internal listener
602
+ // and never on the public API port that an ingress forwards to.
603
+ apiMetricsPort: z.coerce.number().int().positive().optional(),
554
604
  workerHttpPort: z.coerce.number().int().positive().default(8001),
555
605
  // Worker-side first-party MCP traffic stays on the deployment's internal
556
606
  // network. OPENGENI_MCP_URL remains the sandbox/external route used by
@@ -561,11 +611,16 @@ const SettingsSchema = z.object({
561
611
  // call the public API with bearer credentials, but never receive credentialed
562
612
  // CORS responses.
563
613
  corsAllowOriginRegex: z.string().default(String.raw`^https?://(localhost|127\.0\.0\.1)(:\d+)?$`),
614
+ // Local development only (`local` access mode in the `local` environment):
615
+ // extra exact browser origins, comma-separated, that may call the
616
+ // unauthenticated API besides this stack's own web origin. The local browser
617
+ // boundary ignores `corsAllowOriginRegex`.
618
+ localAllowedOrigins: z.string().optional(),
564
619
  openaiProvider: z.enum(["openai", "azure"]).default("openai"),
565
620
  openaiApiKey: z.string().optional(),
566
621
  openaiBaseUrl: z.string().optional(),
567
- openaiModel: z.string().default("gpt-5.6-sol"),
568
- openaiAllowedModels: z.string().default("gpt-5.6-sol,gpt-5.6-terra,gpt-5.6-luna"),
622
+ openaiModel: z.string().default("gpt-6-astra"),
623
+ openaiAllowedModels: z.string().default("gpt-6-astra,gpt-6-sol,gpt-6-luna"),
569
624
  // OpenGeni-managed Vercel AI Gateway. When configured, the two reviewed
570
625
  // Gateway models below are added to the managed-credit catalog. Workspace
571
626
  // Gateway keys use the encrypted connection broker and never this secret.
@@ -694,6 +749,7 @@ const SettingsSchema = z.object({
694
749
  // binding so database mode cannot be bypassed with a second source.
695
750
  resolvedGatewayModelsJson: z.string().optional(),
696
751
  resolvedOpenRouterModelsJson: z.string().optional(),
752
+ resolvedCodexModelsJson: z.string().optional(),
697
753
  // Extra (non-built-in) model providers, declared by the host as a JSON
698
754
  // provider registry. Each entry carries its own base URL, API key, wire API
699
755
  // ("responses" | "chat") and the models it exposes. The models a client may
@@ -708,6 +764,7 @@ const SettingsSchema = z.object({
708
764
  // SuperGrok/xAI connected subscription. This is a workspace-scoped OAuth
709
765
  // account pool and a distinct rail from the existing xai/* API-key provider.
710
766
  supergrokSubscriptionEnabled: EnvBoolean.default(false), // OPENGENI_SUPERGROK_SUBSCRIPTION_ENABLED
767
+ claudeSubscriptionEnabled: EnvBoolean.default(false), // OPENGENI_CLAUDE_SUBSCRIPTION_ENABLED
711
768
  // Maximum silence between complete, valid SuperGrok SSE data events. This is
712
769
  // not a request/run duration cap; every valid event resets the timer.
713
770
  supergrokResponseStreamIdleTimeoutMs: z.coerce
@@ -744,8 +801,27 @@ const SettingsSchema = z.object({
744
801
  // rotated TO — when EITHER usage window (5h/weekly) is at/over this percent. Default 90 to
745
802
  // match the UI danger flip (UsageBar danger at pct >= 90). OPENGENI_CODEX_ROTATION_NEAR_EXHAUSTION_PCT.
746
803
  codexRotationNearExhaustionPct: z.coerce.number().int().min(1).max(100).default(90),
804
+ reasoningConfigurationUpdatesEnabled: EnvBoolean.default(false),
747
805
  openaiReasoningEffort: ReasoningEffort.default("low"),
748
806
  openaiAllowedReasoningEfforts: z.string().default("low,medium,high,xhigh,max"),
807
+ // Default for new chats and scheduled tasks when the workspace has an
808
+ // OpenGeni credit balance, no saved workspace default, and no usable
809
+ // connected subscription, and the deployment default is not already a
810
+ // credits-billed model. Selected only when this model is selectable in the
811
+ // workspace catalog; otherwise the first selectable credits model is used.
812
+ // OPENGENI_CREDITS_DEFAULT_MODEL / OPENGENI_CREDITS_DEFAULT_REASONING_EFFORT.
813
+ creditsDefaultModel: z
814
+ .string()
815
+ .trim()
816
+ .min(1)
817
+ .max(256)
818
+ .refine((value) => !/[\u000A\u000D|]/u.test(value), {
819
+ message: "credits default model must not contain newlines or the | field separator",
820
+ })
821
+ .default("gpt-6-luna"),
822
+ // Preferred effort for the credits default. Clamped to the highest effort
823
+ // the selected model supports at or below this value.
824
+ creditsDefaultReasoningEffort: ReasoningEffort.default("xhigh"),
749
825
  openaiResponsesTransport: z.enum(["http", "websocket"]).default("http"),
750
826
  // Provider-assigned item ids (rs_/msg_/fc_…) in Responses API input are
751
827
  // resolved against the provider's server-side response store. That store is
@@ -771,6 +847,19 @@ const SettingsSchema = z.object({
771
847
  // merged with the MCP-server tools (getAllTools = [...mcpTools, ...tools])
772
848
  // and the sandbox capability tools, never replacing them.
773
849
  webSearchEnabled: EnvBoolean.default(true),
850
+ // Jev (TypeSafe's fast judge model) for worker-side agent tools. Without a
851
+ // usable key every Jev-backed feature is off. The key stays on the server
852
+ // (API and worker) and never reaches a sandbox or Connected Machine.
853
+ jevApiKey: z.string().optional(),
854
+ jevBaseUrl: z.string().url().default("https://api.typesafe.ai"),
855
+ jevModel: z.string().trim().min(1).max(128).default("jev-latest"),
856
+ jevRequestTimeoutMs: z.coerce.number().int().positive().max(120_000).default(10_000),
857
+ // Jev-backed `code_search` agent tool. `off` never offers it, `opt_in` offers
858
+ // it only where workspace settings enable it, `default_on` offers it
859
+ // everywhere except workspaces that disable it, and `experiment` gives it to
860
+ // a fixed half of sessions in workspaces without their own setting, for
861
+ // comparison. It also needs jevApiKey.
862
+ codeSearchMode: z.enum(["off", "opt_in", "default_on", "experiment"]).default("off"),
774
863
  // Deployment-default agent persona template (the white-label surface). The
775
864
  // runtime resolves the effective template per turn as
776
865
  // per-session-override > per-workspace override > this default, substitutes
@@ -792,7 +881,7 @@ const SettingsSchema = z.object({
792
881
  // the verified, self-contained native artifact runtime at its fixed image
793
882
  // paths. Disabled by default so arbitrary/custom provider images never make
794
883
  // document/spreadsheet/presentation skills appear when their runtime is
795
- // absent. Per-pack/per-rig image overrides fail closed in the worker even
884
+
796
885
  // when this base-image contract is enabled.
797
886
  sandboxArtifactRuntimeEnabled: EnvBoolean.default(false),
798
887
  dockerExposedPorts: z.string().default(""),
@@ -804,6 +893,9 @@ const SettingsSchema = z.object({
804
893
  dockerWorkspaceBaseDir: z.string().min(1).optional(),
805
894
  modalAppName: z.string().default("opengeni-sandbox"),
806
895
  modalImageRef: z.string().optional(),
896
+ // Activate only after descriptor-aware readers, DB fences and the exact
897
+ // native image have passed the supervised-command rollout canary.
898
+ modalCommandSupervisionEnabled: EnvBoolean.default(false),
807
899
  // Provider-native immutable Modal image ID for the exact logical
808
900
  // `modalImageRef`. When set, the runtime uses ModalImageSelector.fromId and
809
901
  // never asks Modal to parse or import the registry ref. The logical ref is
@@ -881,12 +973,10 @@ const SettingsSchema = z.object({
881
973
  // Shared desktop toggle: this module reads it for the 6080 port-merge; the
882
974
  // owner module (P4.x) acts on it to launch the display stack.
883
975
  sandboxDesktopEnabled: EnvBoolean.default(false),
884
- // Human take-control toggle: when ON (default) the negotiated DesktopStream
885
- // cell advertises mode "interactive" — the noVNC viewer can drive mouse+keyboard
886
- // into :0 (x11vnc runs without -viewonly). Turn it OFF for a genuinely read-only
887
- // deployment: the cell reports mode "read-only" and the client disables the
888
- // "Take control" affordance. This gates the HUMAN viewer plane; agent
889
- // interaction is authorized through managed ComputerSession tools.
976
+ // Human sandbox input policy. Canonical ComputerSession attachments reflect
977
+ // it and /actions enforces it independently of the client. The legacy
978
+ // DesktopStream adapter also reports read-only when disabled. Agent tools
979
+ // retain their separate session-control authority.
890
980
  sandboxDesktopInteractive: EnvBoolean.default(true),
891
981
  // REAL PTY terminal toggle (P5.t): gates the ttyd pty-ws plane (7681) the API
892
982
  // mints over the SAME tunnel as the desktop. Defaults ON — the interactive
@@ -950,6 +1040,7 @@ const SettingsSchema = z.object({
950
1040
  // --- cloudflare (headless) ---
951
1041
  cloudflareWorkerUrl: z.string().url().optional(),
952
1042
  cloudflareApiKey: z.string().optional(),
1043
+ experimentalBrowserContextPoolEnabled: EnvBoolean.default(false),
953
1044
  // --- remote browser placements ---
954
1045
  // Provider credentials are injected only into the placement-resident
955
1046
  // browserd launch. They never enter session contracts, journals, or sandboxes.
@@ -1135,6 +1226,33 @@ const SettingsSchema = z.object({
1135
1226
  // getSettings caps the default at half a shorter configured Modal lifetime so
1136
1227
  // the entire reaper window always fits. Knob: OPENGENI_SANDBOX_IDLE_GRACE_MS.
1137
1228
  sandboxIdleGraceMs: z.coerce.number().int().positive().default(900_000),
1229
+ // Idle command containment. A legacy retained background command (a dev
1230
+ // server, a command whose output is still draining, a stopped command the
1231
+ // provider no longer answers for) keeps its box warm through a non-expiring
1232
+ // process holder, so the zero-holder drain never runs and the box would stay
1233
+ // up until the provider deadline kills it uncaptured. Once every session of
1234
+ // the sandbox group has been unused this long - no open turn or pending
1235
+ // request, no held wait_for_input, no other holder or writer, measured from
1236
+ // durable turn/holder/admission facts - the reaper checkpoints the workspace,
1237
+ // stops the box and settles those commands `lost` with reason
1238
+ // `idle_containment`. Default 30min: twice the default
1239
+ // idle grace, so a lease that is only waiting for a "glanced away" user is
1240
+ // never contained earlier than an idle lease would drain, and well inside
1241
+ // the 1h provider-deadline rotation lead, so an idle box is saved long before
1242
+ // the deadline path has to act. Set 0 to disable new idle enrollments without
1243
+ // disabling provider-deadline containment or cancelling an enrolled drain.
1244
+ // A positive window must exceed OPENGENI_SANDBOX_IDLE_GRACE_MS;
1245
+ // an explicit positive value must also stay below OPENGENI_SANDBOX_ROTATION_LEAD_MS,
1246
+ // and with an explicit OPENGENI_MODAL_IDLE_TIMEOUT_SECONDS the reaper period
1247
+ // plus this window plus the drain capture budget must fit before it.
1248
+ // getSettings derives the unset default between those two for short-lived
1249
+ // provider lifetimes. Knob: OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS.
1250
+ sandboxIdleCommandContainmentMs: z.coerce
1251
+ .number()
1252
+ .int()
1253
+ .nonnegative()
1254
+ .optional()
1255
+ .transform((value) => (value === 0 ? undefined : value)),
1138
1256
  // MID-SESSION /workspace snapshot cadence (sandbox-file-persistence). The
1139
1257
  // reaper's drain-persist only protects boxes the reaper itself kills; a box
1140
1258
  // that dies any other way (Modal's hard creation-time timeout on a session
@@ -1218,6 +1336,7 @@ const SettingsSchema = z.object({
1218
1336
  // Shape: { "modal": 5, "runloop": 4, ... }. Backends absent here meter
1219
1337
  // warm-seconds but accrue NO warm_cost / debit (rate 0).
1220
1338
  sandboxWarmRateMicrosPerSecondJson: z.string().default("{}"),
1339
+ sandboxWarmBillingMode: z.enum(["usage_only", "shadow", "credits"]).default("usage_only"),
1221
1340
  // Per-workspace warm cap (cumulative warm-seconds since the start of the UTC
1222
1341
  // month, summed over sandbox.warm_seconds). 0 = unbounded. A workspace over the
1223
1342
  // cap force-drains its VIEWER-ONLY boxes (guarded AND turn_holders=0 — a paying
@@ -1225,6 +1344,9 @@ const SettingsSchema = z.object({
1225
1344
  sandboxMaxWarmSecondsPerWorkspace: z.coerce.number().int().nonnegative().default(0),
1226
1345
  sandboxPreparationProfiles: z.string().default("none"),
1227
1346
  sandboxEnvAllowlist: z.string().default(""),
1347
+ // Comma-separated image references a workspace may select as its default
1348
+ // sandbox image. Empty keeps every workspace on the deployment image.
1349
+ sandboxImageAllowlist: z.string().default(""),
1228
1350
  objectStorageEndpoint: z.string().url().optional(),
1229
1351
  objectStorageInternalEndpoint: z.string().url().optional(),
1230
1352
  objectStorageSandboxEndpoint: z.string().url().optional(),
@@ -1253,6 +1375,13 @@ const SettingsSchema = z.object({
1253
1375
  documentEmbeddingDimensions: z.coerce.number().int().positive().default(3072),
1254
1376
  documentEmbeddingApiKey: z.string().optional(),
1255
1377
  documentEmbeddingBaseUrl: z.string().url().optional(),
1378
+ documentEmbeddingBillingMode: z.enum(["usage_only", "shadow", "credits"]).default("usage_only"),
1379
+ // Explicit commercial cutover. Existing queued revisions remain unpriced;
1380
+ // only jobs created at or after this instant may enter the paid rail.
1381
+ documentEmbeddingCreditsActivatedAt: z.iso.datetime().optional(),
1382
+ // Customer tariff for the exact UTF-8 bytes sent to the embedder. Zero leaves
1383
+ // the paid mode unavailable; no commercial rate is selected by this PR.
1384
+ documentEmbeddingRateMicrosPerMillionBytes: z.coerce.number().int().nonnegative().default(0),
1256
1385
  documentCurationProvider: z.enum(["openai", "heuristic", "none"]).default("openai"),
1257
1386
  documentCurationModel: z.string().min(1).default("gpt-4o-mini"),
1258
1387
  documentCurationApiKey: z.string().optional(),
@@ -1290,7 +1419,17 @@ const SettingsSchema = z.object({
1290
1419
  managedAuthGithubClientSecret: z.string().optional(),
1291
1420
  // Rolling browser login-slot compatibility. Repository/deployment default is
1292
1421
  // deliberately legacy; changing to broker is an operator-authorized rollout.
1422
+ allowedUserEmails: z
1423
+ .array(z.email().transform((email) => email.toLowerCase()))
1424
+ .min(1)
1425
+ .optional(),
1293
1426
  managedAuthSessionSetMode: z.enum(["legacy", "dual", "broker"]).default("legacy"),
1427
+ // Deployment ceiling for new managed accounts. When false, managed auth
1428
+ // refuses every new Better Auth account (email/password sign-up and implicit
1429
+ // Google/GitHub sign-up) while existing sign-in, sessions, password reset,
1430
+ // email verification, and invitation-bound account setup keep working. Read
1431
+ // at startup; the 0585 runtime switch pauses sign-ups without a restart.
1432
+ managedAuthNewSignupsEnabled: EnvBoolean.default(true),
1294
1433
  // Query transport is an explicit second-stage rollout. A pre-compatibility
1295
1434
  // web image understands only fragment bearers, so API replicas must keep
1296
1435
  // generating fragment links until the compatible web fleet has converged.
@@ -1332,6 +1471,124 @@ const SettingsSchema = z.object({
1332
1471
  });
1333
1472
 
1334
1473
  export type Settings = z.infer<typeof SettingsSchema>;
1474
+
1475
+ // Independently supervised artifact services are not API/agent runtimes. Parse
1476
+ // only their actual capabilities, using the same field schemas as getSettings.
1477
+ const ArtifactServiceSettingsSchema = SettingsSchema.pick({
1478
+ serviceName: true,
1479
+ environment: true,
1480
+ deploymentRevision: true,
1481
+ dbSchema: true,
1482
+ rlsStrategy: true,
1483
+ observabilityStructuredLogs: true,
1484
+ observabilityMetricsEnabled: true,
1485
+ observabilityOtlpEndpoint: true,
1486
+ observabilityOtlpHeaders: true,
1487
+ });
1488
+ const ArtifactOutboxSettingsSchema = ArtifactServiceSettingsSchema.extend({
1489
+ natsUrl: SettingsSchema.shape.natsUrl,
1490
+ selfhostedNatsControlUser: SettingsSchema.shape.selfhostedNatsControlUser,
1491
+ selfhostedNatsControlPassword: SettingsSchema.shape.selfhostedNatsControlPassword,
1492
+ });
1493
+ const ObjectStorageSettingsSchema = SettingsSchema.pick({
1494
+ objectStorageBackend: true,
1495
+ objectStorageEndpoint: true,
1496
+ objectStorageInternalEndpoint: true,
1497
+ objectStorageSandboxEndpoint: true,
1498
+ objectStorageBucket: true,
1499
+ objectStorageRegion: true,
1500
+ objectStorageAccessKeyId: true,
1501
+ objectStorageSecretAccessKey: true,
1502
+ objectStorageForcePathStyle: true,
1503
+ objectStorageAzureConnectionString: true,
1504
+ objectStorageAzureAccountName: true,
1505
+ objectStorageAzureAccountKey: true,
1506
+ objectStorageAzureEndpoint: true,
1507
+ objectStorageGcsProjectId: true,
1508
+ objectStorageGcsCredentialsJson: true,
1509
+ objectStorageGcsKeyFilename: true,
1510
+ objectStorageGcsApiEndpoint: true,
1511
+ });
1512
+ const ArtifactMaterializerSettingsSchema = ArtifactServiceSettingsSchema.extend(
1513
+ ObjectStorageSettingsSchema.shape,
1514
+ );
1515
+ export type ArtifactOutboxSettings = z.infer<typeof ArtifactOutboxSettingsSchema>;
1516
+ export type ObjectStorageSettings = z.infer<typeof ObjectStorageSettingsSchema>;
1517
+ export type ArtifactMaterializerSettings = z.infer<typeof ArtifactMaterializerSettingsSchema>;
1518
+
1519
+ function artifactServiceEnvironment(source: NodeJS.ProcessEnv) {
1520
+ const optional = (name: string) => optionalEnvironmentValue(name, source);
1521
+ return {
1522
+ serviceName: optional("OPENGENI_SERVICE_NAME"),
1523
+ environment: optional("OPENGENI_ENVIRONMENT"),
1524
+ deploymentRevision:
1525
+ optional("OPENGENI_DEPLOYMENT_REVISION") ??
1526
+ optional("SOURCE_VERSION") ??
1527
+ optional("GITHUB_SHA"),
1528
+ dbSchema: optional("OPENGENI_DB_SCHEMA"),
1529
+ rlsStrategy: optional("OPENGENI_RLS_STRATEGY"),
1530
+ observabilityStructuredLogs: optional("OPENGENI_OBSERVABILITY_STRUCTURED_LOGS"),
1531
+ observabilityMetricsEnabled: optional("OPENGENI_OBSERVABILITY_METRICS_ENABLED"),
1532
+ observabilityOtlpEndpoint:
1533
+ optional("OPENGENI_OTEL_EXPORTER_OTLP_ENDPOINT") ?? optional("OTEL_EXPORTER_OTLP_ENDPOINT"),
1534
+ observabilityOtlpHeaders:
1535
+ optional("OPENGENI_OTEL_EXPORTER_OTLP_HEADERS") ?? optional("OTEL_EXPORTER_OTLP_HEADERS"),
1536
+ };
1537
+ }
1538
+
1539
+ export function getArtifactOutboxSettings(
1540
+ source: NodeJS.ProcessEnv = process.env,
1541
+ ): ArtifactOutboxSettings {
1542
+ const settings = ArtifactOutboxSettingsSchema.parse({
1543
+ ...artifactServiceEnvironment(source),
1544
+ natsUrl: optionalEnvironmentValue("OPENGENI_NATS_URL", source),
1545
+ selfhostedNatsControlUser: optionalEnvironmentValue(
1546
+ "OPENGENI_SELFHOSTED_NATS_CONTROL_USER",
1547
+ source,
1548
+ ),
1549
+ selfhostedNatsControlPassword: optionalEnvironmentValue(
1550
+ "OPENGENI_SELFHOSTED_NATS_CONTROL_PASSWORD",
1551
+ source,
1552
+ ),
1553
+ });
1554
+ dbSearchPath(settings);
1555
+ if (
1556
+ Boolean(settings.selfhostedNatsControlUser) !== Boolean(settings.selfhostedNatsControlPassword)
1557
+ ) {
1558
+ throw new Error("Artifact outbox NATS control user and password must be configured together");
1559
+ }
1560
+ return settings;
1561
+ }
1562
+
1563
+ export function getArtifactMaterializerSettings(
1564
+ source: NodeJS.ProcessEnv = process.env,
1565
+ ): ArtifactMaterializerSettings {
1566
+ const optional = (name: string) => optionalEnvironmentValue(name, source);
1567
+ const settings = ArtifactMaterializerSettingsSchema.parse({
1568
+ ...artifactServiceEnvironment(source),
1569
+ objectStorageEndpoint: optional("OPENGENI_OBJECT_STORAGE_ENDPOINT"),
1570
+ objectStorageInternalEndpoint: optional("OPENGENI_OBJECT_STORAGE_INTERNAL_ENDPOINT"),
1571
+ objectStorageSandboxEndpoint: optional("OPENGENI_OBJECT_STORAGE_SANDBOX_ENDPOINT"),
1572
+ objectStorageBackend: optional("OPENGENI_OBJECT_STORAGE_BACKEND"),
1573
+ objectStorageBucket: optional("OPENGENI_OBJECT_STORAGE_BUCKET"),
1574
+ objectStorageRegion: optional("OPENGENI_OBJECT_STORAGE_REGION"),
1575
+ objectStorageAccessKeyId: optional("OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID"),
1576
+ objectStorageSecretAccessKey: optional("OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY"),
1577
+ objectStorageForcePathStyle: optional("OPENGENI_OBJECT_STORAGE_FORCE_PATH_STYLE"),
1578
+ objectStorageAzureConnectionString: optional("OPENGENI_OBJECT_STORAGE_AZURE_CONNECTION_STRING"),
1579
+ objectStorageAzureAccountName: optional("OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_NAME"),
1580
+ objectStorageAzureAccountKey: optional("OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_KEY"),
1581
+ objectStorageAzureEndpoint: optional("OPENGENI_OBJECT_STORAGE_AZURE_ENDPOINT"),
1582
+ objectStorageGcsProjectId: optional("OPENGENI_OBJECT_STORAGE_GCS_PROJECT_ID"),
1583
+ objectStorageGcsCredentialsJson: optional("OPENGENI_OBJECT_STORAGE_GCS_CREDENTIALS_JSON"),
1584
+ objectStorageGcsKeyFilename: optional("OPENGENI_OBJECT_STORAGE_GCS_KEY_FILENAME"),
1585
+ objectStorageGcsApiEndpoint: optional("OPENGENI_OBJECT_STORAGE_GCS_API_ENDPOINT"),
1586
+ });
1587
+ dbSearchPath(settings);
1588
+ validateObjectStorageSettings(settings);
1589
+ return settings;
1590
+ }
1591
+
1335
1592
  export type McpServerConfig = Settings["mcpServers"][number];
1336
1593
 
1337
1594
  export type GoogleDriveProviderRetryOptions = {
@@ -1439,6 +1696,48 @@ export type VoiceInputProviderConfig =
1439
1696
  experimental: true;
1440
1697
  };
1441
1698
 
1699
+ function usableDeploymentSecret(value: string | null | undefined): string | undefined {
1700
+ return isUsableVoiceInputSecret(value) ? value : undefined;
1701
+ }
1702
+
1703
+ /** The deployment's Jev key, or undefined when it is missing or a placeholder. */
1704
+ export function usableJevApiKey(settings: Pick<Settings, "jevApiKey">): string | undefined {
1705
+ return usableDeploymentSecret(settings.jevApiKey);
1706
+ }
1707
+
1708
+ /** Deployment half of agent configuration: hard capability limits. */
1709
+ export function agentConfigDeploymentPolicy(
1710
+ settings: Pick<
1711
+ Settings,
1712
+ "webSearchEnabled" | "defaultFirstPartyMcpTools" | "allowedFirstPartyMcpTools"
1713
+ >,
1714
+ ): AgentConfigDeploymentLimits {
1715
+ return agentConfigDeploymentLimitsFromAllowlist(
1716
+ resolveFirstPartyMcpToolPolicy(settings).allowed,
1717
+ settings.webSearchEnabled ? {} : { webSearch: "web search is turned off on this server" },
1718
+ );
1719
+ }
1720
+
1721
+ /**
1722
+ * Deployment half of the `code_search` decision. `available` is false when
1723
+ * the mode is off or no usable Jev key is configured; workspaces then cannot
1724
+ * turn it on. `workspaceDefault` applies to workspaces without their own
1725
+ * setting.
1726
+ */
1727
+ export function codeSearchDeploymentPolicy(
1728
+ settings: Pick<Settings, "codeSearchMode" | "jevApiKey">,
1729
+ ): CodeSearchDeploymentPolicy {
1730
+ const available = settings.codeSearchMode !== "off" && usableJevApiKey(settings) !== undefined;
1731
+ if (!available) return { available: false, workspaceDefault: "off" };
1732
+ const workspaceDefault =
1733
+ settings.codeSearchMode === "default_on"
1734
+ ? "on"
1735
+ : settings.codeSearchMode === "experiment"
1736
+ ? "split"
1737
+ : "off";
1738
+ return { available, workspaceDefault };
1739
+ }
1740
+
1442
1741
  /**
1443
1742
  * Reject empty / template secrets so `.env.example` placeholders like
1444
1743
  * `your-key` cannot advertise voice input as available and then 401 upstream.
@@ -1630,6 +1929,27 @@ export type ModelUsageCostBreakdown = {
1630
1929
  creditCostMicros: number;
1631
1930
  };
1632
1931
 
1932
+ export type ModelListCostClassesMicros = {
1933
+ uncachedInput: number;
1934
+ cacheRead: number;
1935
+ cacheWrite: number;
1936
+ output: number;
1937
+ };
1938
+
1939
+ export type ModelListUsageCostSnapshot = ModelUsageCostBreakdown & {
1940
+ /** Captured upstream list costs, summing to providerCostMicros, never debits. */
1941
+ listByClassMicros: ModelListCostClassesMicros | null;
1942
+ /** True only when a returned class split includes latency rounding allocation. */
1943
+ listByClassApprox: boolean;
1944
+ };
1945
+
1946
+ export type ModelRecordedListCostAllocation = {
1947
+ /** Approximate attribution of a stored upstream total, never a new price. */
1948
+ listByClassMicros: ModelListCostClassesMicros | null;
1949
+ /** True for every eligible historical allocation, including known zero. */
1950
+ listByClassApprox: boolean;
1951
+ };
1952
+
1633
1953
  export type StaticUsageLimitsConfig = StaticUsageLimits;
1634
1954
  export type EntitlementsConfig = Entitlements;
1635
1955
 
@@ -1800,7 +2120,7 @@ export type ModelExecutionLimitsV1 = {
1800
2120
 
1801
2121
  export type CredentialSourceV1 =
1802
2122
  | { kind: "deployment"; mechanism: "api_key" | "azure_ad_bearer" | "none" }
1803
- | { kind: "connected_subscription"; provider: "codex" | "xai" }
2123
+ | { kind: "connected_subscription"; provider: "codex" | "xai" | "claude" }
1804
2124
  | { kind: "workspace_connection"; mechanism: "api_key" }
1805
2125
  | { kind: "organization_connection"; mechanism: "api_key" };
1806
2126
 
@@ -1816,7 +2136,7 @@ export type BillingAttributionV1 = {
1816
2136
  * wired as "chat" because its beta Responses endpoint echoes input back and
1817
2137
  * silently no-ops hosted tools (see docs/model-providers.md).
1818
2138
  */
1819
- export const ModelProviderApi = z.enum(["responses", "chat"]);
2139
+ export const ModelProviderApi = z.enum(["responses", "chat", "anthropic-messages"]);
1820
2140
  export type ModelProviderApi = z.infer<typeof ModelProviderApi>;
1821
2141
 
1822
2142
  /**
@@ -1841,12 +2161,25 @@ export const RegistryProviderKind = z.enum([
1841
2161
  "vercel-gateway-managed",
1842
2162
  "vercel-gateway-workspace",
1843
2163
  "vercel-gateway-organization",
2164
+ "direct-openai-workspace",
2165
+ "direct-azure-workspace",
1844
2166
  "openrouter-workspace",
1845
2167
  "openrouter-organization",
2168
+ "anthropic-organization",
2169
+ "claude-subscription-organization",
2170
+ "anthropic-workspace",
2171
+ "claude-subscription-workspace",
1846
2172
  ]);
1847
2173
  export type RegistryProviderKind = z.infer<typeof RegistryProviderKind>;
1848
2174
 
1849
2175
  /** A single model exposed by a registry provider. */
2176
+ const ModelLogoUrlSchema = z
2177
+ .string()
2178
+ .refine(
2179
+ (value) => modelLogoUrl({ id: "", logoUrl: value }) !== null,
2180
+ "model logoUrl must be an HTTPS URL without embedded credentials, at most 2048 characters",
2181
+ );
2182
+
1850
2183
  const RegistryModelSchema = z
1851
2184
  .object({
1852
2185
  id: z.string().min(1), // canonical OpenGeni product id
@@ -1854,6 +2187,7 @@ const RegistryModelSchema = z
1854
2187
  aliases: z.array(z.string().min(1)).optional(), // accepted input only; never sent upstream
1855
2188
  label: z.string().min(1).optional(), // display name; defaults to id
1856
2189
  shortLabel: z.string().min(1).max(64).optional(), // compact UI label; optional
2190
+ logoUrl: ModelLogoUrlSchema.optional(),
1857
2191
  contextWindowTokens: z.number().int().positive().optional(),
1858
2192
  effectiveContextWindowTokens: z.number().int().positive().optional(),
1859
2193
  autoCompactTokenLimit: z.number().int().positive().optional(),
@@ -1896,12 +2230,51 @@ const RegistryModelSchema = z
1896
2230
  });
1897
2231
 
1898
2232
  /** A non-built-in provider declared by the host via OPENGENI_MODEL_PROVIDERS_JSON. */
2233
+ export const ClaudeSubscriptionIdentity = z
2234
+ .object({
2235
+ accountUuid: z.union([z.string().uuid(), z.literal("")]),
2236
+ deviceId: z.string().regex(/^[a-f0-9]{64}$/),
2237
+ })
2238
+ .strict();
2239
+ export type ClaudeSubscriptionIdentity = z.infer<typeof ClaudeSubscriptionIdentity>;
2240
+ export const ClaudeSubscriptionCredential = z
2241
+ .object({
2242
+ version: z.literal(1),
2243
+ token: z.string().regex(/^sk-ant-oat[0-9]+-\S+$/),
2244
+ identity: ClaudeSubscriptionIdentity,
2245
+ oauth: z
2246
+ .object({
2247
+ refreshToken: z.string().min(1).max(16384),
2248
+ expiresAt: z.string().datetime(),
2249
+ scopes: z.array(z.string().min(1).max(256)).min(1).max(32),
2250
+ })
2251
+ .strict()
2252
+ .optional(),
2253
+ })
2254
+ .strict();
2255
+ const AnthropicProviderOptions = z.object({
2256
+ identity: ClaudeSubscriptionIdentity.optional(),
2257
+ // Native connection provenance only; never included in Anthropic request bodies.
2258
+ credentialBinding: z
2259
+ .object({
2260
+ connectionId: z.string().uuid(),
2261
+ credentialVersion: z.number().int().positive(),
2262
+ })
2263
+ .strict()
2264
+ .optional(),
2265
+ auth: z.enum(["api-key", "oauth"]).default("api-key"),
2266
+ cacheTtl: z.enum(["5m", "1h", "off"]).default("5m"),
2267
+ maxOutputTokens: z.number().int().positive().default(32000),
2268
+ streamIdleTimeoutMs: z.number().int().positive().default(600000),
2269
+ });
2270
+
1899
2271
  const RegistryProviderSchema = z
1900
2272
  .object({
1901
2273
  kind: RegistryProviderKind.default("api-key"),
1902
2274
  id: z.string().min(1).regex(registryId), // stable provider id, e.g. "fireworks"
1903
2275
  label: z.string().min(1).optional(),
1904
2276
  api: ModelProviderApi.default("chat"),
2277
+ anthropic: AnthropicProviderOptions.optional(),
1905
2278
  wireProfile: ModelProviderWireProfile.default("openai"),
1906
2279
  baseUrl: z.string().url(),
1907
2280
  apiKey: z.string().optional(), // inline key (pragmatic) ...
@@ -1989,6 +2362,10 @@ const RESERVED_MODEL_PROVIDER_IDS = new Set<string>([
1989
2362
  OPENROUTER_PROVIDER_ID,
1990
2363
  WORKSPACE_OPENROUTER_PROVIDER_ID,
1991
2364
  ORGANIZATION_OPENROUTER_PROVIDER_ID,
2365
+ "organization-anthropic",
2366
+ "organization-claude-subscription",
2367
+ "workspace-anthropic",
2368
+ "workspace-claude-subscription",
1992
2369
  ]);
1993
2370
 
1994
2371
  export const ModelCostClass = z.enum(["free", "credits"]);
@@ -2049,6 +2426,7 @@ export const GatewayCatalogModel = z
2049
2426
  upstreamModelId: z.string().min(1),
2050
2427
  label: z.string().min(1),
2051
2428
  shortLabel: z.string().min(1).max(64).optional(),
2429
+ logoUrl: ModelLogoUrlSchema.optional(),
2052
2430
  providers: z.array(z.string().min(1)).min(1),
2053
2431
  implicitCaching: z.boolean().default(false),
2054
2432
  vision: z.boolean().default(false),
@@ -2069,6 +2447,7 @@ export const OpenRouterCatalogModel = z
2069
2447
  upstreamModelId: z.string().min(1).endsWith(":free"),
2070
2448
  label: z.string().min(1),
2071
2449
  shortLabel: z.string().min(1).max(64).optional(),
2450
+ logoUrl: ModelLogoUrlSchema.optional(),
2072
2451
  aliases: z.array(z.string().min(1)).default([]),
2073
2452
  capabilities: ModelCapabilitiesV1Schema,
2074
2453
  contextWindowTokens: z.number().int().positive().optional(),
@@ -2130,6 +2509,28 @@ const DeploymentGatewayCatalogModelSchema = GatewayCatalogModel.safeExtend({
2130
2509
  pricing: z.never().optional(),
2131
2510
  }).strict();
2132
2511
 
2512
+ const CodexCatalogModelSchema = RegistryModelSchema.safeExtend({
2513
+ retired: z.boolean().optional(),
2514
+ id: z.string().regex(/^codex\/[a-zA-Z0-9][a-zA-Z0-9._-]*$/),
2515
+ upstreamModelId: z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/),
2516
+ capabilities: ModelCapabilitiesV1Schema,
2517
+ pricing: z.never().optional(),
2518
+ })
2519
+ .strict()
2520
+ .superRefine((model, context) => {
2521
+ if (model.id !== `${CODEX_MODEL_ID_PREFIX}${model.upstreamModelId}`) {
2522
+ context.addIssue({
2523
+ code: "custom",
2524
+ path: ["id"],
2525
+ message: "Codex product id must match its upstream model slug",
2526
+ });
2527
+ }
2528
+ })
2529
+ .transform((model) => ({
2530
+ ...model,
2531
+ capabilities: reviewedCodexCatalogCapabilities(model.upstreamModelId, model.capabilities),
2532
+ }));
2533
+
2133
2534
  export const ModelCatalogDocument = z
2134
2535
  .object({
2135
2536
  schemaVersion: z.literal(1),
@@ -2137,8 +2538,9 @@ export const ModelCatalogDocument = z
2137
2538
  * fallback for existing documents; operators should set this explicitly
2138
2539
  * when cutting over a registry or connected-subscription default. */
2139
2540
  defaultModel: z.string().min(1).optional(),
2140
- builtInModels: z.array(z.string().min(1)).min(1),
2541
+ builtInModels: z.array(z.string().min(1)),
2141
2542
  registryProviders: z.array(DeploymentRegistryProviderSchema).default([]),
2543
+ codexModels: z.array(CodexCatalogModelSchema).optional(),
2142
2544
  gatewayModels: z.array(DeploymentGatewayCatalogModelSchema).default([]),
2143
2545
  openrouterModels: z.array(OpenRouterCatalogModel).default([]),
2144
2546
  modelNotes: z.record(z.string().min(1), ModelNote).default({}),
@@ -2149,6 +2551,13 @@ export const ModelCatalogDocument = z
2149
2551
  })
2150
2552
  .strict()
2151
2553
  .superRefine((document, context) => {
2554
+ if (document.builtInModels.length === 0 && !document.defaultModel) {
2555
+ context.addIssue({
2556
+ code: "custom",
2557
+ path: ["defaultModel"],
2558
+ message: "catalogs without built-in models require an explicit default model",
2559
+ });
2560
+ }
2152
2561
  const productIds = new Set<string>();
2153
2562
  const providerIds = new Set<string>();
2154
2563
  const gatewayUpstreamIds = new Set<string>();
@@ -2170,8 +2579,22 @@ export const ModelCatalogDocument = z
2170
2579
  productIds.add(id);
2171
2580
  };
2172
2581
  document.builtInModels.forEach((id, index) => add(id, ["builtInModels", index]));
2582
+ document.codexModels?.forEach((model, index) => add(model.id, ["codexModels", index, "id"]));
2583
+ if (
2584
+ document.codexModels?.some((model) => model.retired && model.id === document.defaultModel)
2585
+ ) {
2586
+ context.addIssue({
2587
+ code: "custom",
2588
+ path: ["defaultModel"],
2589
+ message: "a retired model cannot be the deployment default",
2590
+ });
2591
+ }
2173
2592
  document.registryProviders.forEach((provider, providerIndex) => {
2174
- if (RESERVED_MODEL_PROVIDER_IDS.has(provider.id)) {
2593
+ if (
2594
+ RESERVED_MODEL_PROVIDER_IDS.has(provider.id) ||
2595
+ provider.id.startsWith("workspace-openai-") ||
2596
+ provider.id.startsWith("workspace-azure-openai-")
2597
+ ) {
2175
2598
  context.addIssue({
2176
2599
  code: "custom",
2177
2600
  path: ["registryProviders", providerIndex, "id"],
@@ -2219,7 +2642,10 @@ export const ModelCatalogDocument = z
2219
2642
  if (
2220
2643
  document.defaultModel &&
2221
2644
  !productIds.has(document.defaultModel) &&
2222
- !document.defaultModel.startsWith(CODEX_MODEL_ID_PREFIX) &&
2645
+ !(
2646
+ document.codexModels === undefined &&
2647
+ document.defaultModel.startsWith(CODEX_MODEL_ID_PREFIX)
2648
+ ) &&
2223
2649
  !document.defaultModel.startsWith(XAI_SUBSCRIPTION_MODEL_ID_PREFIX)
2224
2650
  ) {
2225
2651
  context.addIssue({
@@ -2304,6 +2730,8 @@ export function applyModelCatalogDocument(settings: Settings, rawDocument: unkno
2304
2730
  ),
2305
2731
  resolvedGatewayModelsJson: JSON.stringify(document.gatewayModels),
2306
2732
  resolvedOpenRouterModelsJson: JSON.stringify(document.openrouterModels),
2733
+ resolvedCodexModelsJson:
2734
+ document.codexModels === undefined ? undefined : JSON.stringify(document.codexModels),
2307
2735
  modelNotesJson: JSON.stringify(document.modelNotes),
2308
2736
  };
2309
2737
  return resolved;
@@ -2326,6 +2754,7 @@ export type IntegrationOAuthClientConfig = z.infer<typeof IntegrationOAuthClient
2326
2754
  * replacement.
2327
2755
  */
2328
2756
  export interface ResolvedModelProvider {
2757
+ anthropic?: z.infer<typeof AnthropicProviderOptions> | undefined;
2329
2758
  id: string; // "openai" | "azure" | registry id
2330
2759
  label: string;
2331
2760
  kind: RegistryProviderKind | "openrouter-managed";
@@ -2354,6 +2783,8 @@ export interface ConfiguredModel {
2354
2783
  label: string;
2355
2784
  /** Optional curated compact label for dense UI (e.g. mobile composer). */
2356
2785
  shortLabel?: string | undefined;
2786
+ /** Optional HTTPS maker logo; display metadata does not change execution identity. */
2787
+ logoUrl?: string | undefined;
2357
2788
  providerId: string;
2358
2789
  providerLabel: string;
2359
2790
  api: ModelProviderApi;
@@ -2381,6 +2812,26 @@ export interface ConfiguredModel {
2381
2812
  hostedWebSearch: boolean;
2382
2813
  }
2383
2814
 
2815
+ /**
2816
+ * Whether a resolved route is the deployment-funded OpenRouter free tier: the
2817
+ * managed OpenRouter provider, which sends every workspace's requests with the
2818
+ * deployment's one OpenRouter key, serving an upstream `:free` variant (the
2819
+ * curated catalog admits nothing else). OpenRouter limits free-variant
2820
+ * requests per account per minute and per day, so each request on this route
2821
+ * spends quota that every turn on the deployment shares. A workspace or
2822
+ * organization OpenRouter connection uses its own account and is not this
2823
+ * route.
2824
+ */
2825
+ export function isManagedOpenRouterFreeRoute(route: {
2826
+ provider: Pick<ResolvedModelProvider, "kind">;
2827
+ configured: Pick<ConfiguredModel, "upstreamModelId">;
2828
+ }): boolean {
2829
+ return (
2830
+ route.provider.kind === "openrouter-managed" &&
2831
+ route.configured.upstreamModelId.endsWith(":free")
2832
+ );
2833
+ }
2834
+
2384
2835
  export const VERCEL_AI_GATEWAY_BASE_URL = "https://ai-gateway.vercel.sh/v1" as const;
2385
2836
  export const VERCEL_AI_GATEWAY_AI_SDK_BASE_URL = "https://ai-gateway.vercel.sh/v4/ai" as const;
2386
2837
  export const VERCEL_AI_GATEWAY_CONNECTION_DOMAIN = "ai-gateway.vercel.sh" as const;
@@ -2587,6 +3038,73 @@ export function configuredOpenRouterOrganizationProductModelIds(settings: Settin
2587
3038
  * llm-prices.com as a ground-truth canary; it does not generate this table.
2588
3039
  */
2589
3040
  export const defaultModelPricing: Record<string, ModelPricingScheduleV1> = {
3041
+ "gpt-6-astra": {
3042
+ default: {
3043
+ // OpenAI list price: $10 / $1 cached / $12.50 cache write / $50 output.
3044
+ inputMicrosPerMillionTokens: 10_000_000,
3045
+ cachedInputMicrosPerMillionTokens: 1_000_000,
3046
+ cacheWriteMicrosPerMillionTokens: 12_500_000,
3047
+ outputMicrosPerMillionTokens: 50_000_000,
3048
+ marginBps: 500,
3049
+ },
3050
+ inputTokenTiers: [
3051
+ {
3052
+ // Prompts with more than 272K input tokens use 2x input and 1.5x output.
3053
+ minimumInputTokens: 272_001,
3054
+ pricing: {
3055
+ inputMicrosPerMillionTokens: 20_000_000,
3056
+ cachedInputMicrosPerMillionTokens: 2_000_000,
3057
+ cacheWriteMicrosPerMillionTokens: 25_000_000,
3058
+ outputMicrosPerMillionTokens: 75_000_000,
3059
+ marginBps: 500,
3060
+ },
3061
+ },
3062
+ ],
3063
+ },
3064
+ "gpt-6-sol": {
3065
+ default: {
3066
+ // OpenAI list price: $2 / $0.20 cached / $2.50 cache write / $10 output.
3067
+ inputMicrosPerMillionTokens: 2_000_000,
3068
+ cachedInputMicrosPerMillionTokens: 200_000,
3069
+ cacheWriteMicrosPerMillionTokens: 2_500_000,
3070
+ outputMicrosPerMillionTokens: 10_000_000,
3071
+ marginBps: 500,
3072
+ },
3073
+ inputTokenTiers: [
3074
+ {
3075
+ minimumInputTokens: 272_001,
3076
+ pricing: {
3077
+ inputMicrosPerMillionTokens: 4_000_000,
3078
+ cachedInputMicrosPerMillionTokens: 400_000,
3079
+ cacheWriteMicrosPerMillionTokens: 5_000_000,
3080
+ outputMicrosPerMillionTokens: 15_000_000,
3081
+ marginBps: 500,
3082
+ },
3083
+ },
3084
+ ],
3085
+ },
3086
+ "gpt-6-luna": {
3087
+ default: {
3088
+ // OpenAI list price: $0.10 / $0.01 cached / $0.125 cache write / $0.50 output.
3089
+ inputMicrosPerMillionTokens: 100_000,
3090
+ cachedInputMicrosPerMillionTokens: 10_000,
3091
+ cacheWriteMicrosPerMillionTokens: 125_000,
3092
+ outputMicrosPerMillionTokens: 500_000,
3093
+ marginBps: 500,
3094
+ },
3095
+ inputTokenTiers: [
3096
+ {
3097
+ minimumInputTokens: 272_001,
3098
+ pricing: {
3099
+ inputMicrosPerMillionTokens: 200_000,
3100
+ cachedInputMicrosPerMillionTokens: 20_000,
3101
+ cacheWriteMicrosPerMillionTokens: 250_000,
3102
+ outputMicrosPerMillionTokens: 750_000,
3103
+ marginBps: 500,
3104
+ },
3105
+ },
3106
+ ],
3107
+ },
2590
3108
  "gpt-5.6-sol": {
2591
3109
  default: {
2592
3110
  // Promotional OpenAI pricing, guaranteed through at least 2026-11-21.
@@ -2687,6 +3205,113 @@ export const defaultModelPricing: Record<string, ModelPricingScheduleV1> = {
2687
3205
  },
2688
3206
  };
2689
3207
 
3208
+ /** Reviewed comparison rates only; never debit or execution-definition defaults. */
3209
+ export const reviewedModelListPricing: Record<string, ModelPricingScheduleV1> = {
3210
+ // Reviewed 2026-10-03 against https://developers.openai.com/api/docs/pricing
3211
+ // and https://ai-gateway.vercel.sh/v1/models. GPT-6.1 Sol's cache-read rate
3212
+ // is 5% of input, not GPT-6 Sol's 10%. The long-context boundary is >272K.
3213
+ "gpt-6.1-sol": {
3214
+ default: {
3215
+ inputMicrosPerMillionTokens: 2_000_000,
3216
+ cachedInputMicrosPerMillionTokens: 100_000,
3217
+ cacheWriteMicrosPerMillionTokens: 2_500_000,
3218
+ outputMicrosPerMillionTokens: 10_000_000,
3219
+ marginBps: 500,
3220
+ },
3221
+ inputTokenTiers: [
3222
+ {
3223
+ minimumInputTokens: 272_001,
3224
+ pricing: {
3225
+ inputMicrosPerMillionTokens: 4_000_000,
3226
+ cachedInputMicrosPerMillionTokens: 200_000,
3227
+ cacheWriteMicrosPerMillionTokens: 5_000_000,
3228
+ outputMicrosPerMillionTokens: 15_000_000,
3229
+ marginBps: 500,
3230
+ },
3231
+ },
3232
+ ],
3233
+ },
3234
+ // xAI Standard API list rates, reviewed 2026-10-03:
3235
+ // https://docs.x.ai/developers/models/grok-4.5 (and grok-4.6 / grok-4.7).
3236
+ // Preserve the native API's established >=200K boundary. Gateway's separately
3237
+ // configured >200K schedule is not interchangeable with this native schedule.
3238
+ // xAI's automatic caching has no separate cache-write surcharge.
3239
+ ...Object.fromEntries(
3240
+ (
3241
+ [
3242
+ ["grok-4.5", 300_000],
3243
+ ["grok-4.6", 500_000],
3244
+ ["grok-4.7", 500_000],
3245
+ ] as const
3246
+ ).map(([model, cachedInput]) => [
3247
+ model,
3248
+ {
3249
+ default: {
3250
+ inputMicrosPerMillionTokens: 2_000_000,
3251
+ cachedInputMicrosPerMillionTokens: cachedInput,
3252
+ outputMicrosPerMillionTokens: 6_000_000,
3253
+ marginBps: 500,
3254
+ },
3255
+ inputTokenTiers: [
3256
+ {
3257
+ minimumInputTokens: 200_000,
3258
+ pricing: {
3259
+ inputMicrosPerMillionTokens: 4_000_000,
3260
+ cachedInputMicrosPerMillionTokens: cachedInput * 2,
3261
+ outputMicrosPerMillionTokens: 12_000_000,
3262
+ marginBps: 500,
3263
+ },
3264
+ },
3265
+ ],
3266
+ },
3267
+ ]),
3268
+ ),
3269
+ // Every reviewed native Claude profile. Standard/global prices include
3270
+ // 5-minute cache writes; 1-hour native routes are projected separately.
3271
+ // https://platform.claude.com/docs/en/about-claude/pricing (2026-10-03).
3272
+ // Opus 5.5 cache reads are 5%, unlike the older models' 10%; none of these
3273
+ // models has a long-context premium.
3274
+ ...Object.fromEntries(
3275
+ (
3276
+ [
3277
+ ["claude-opus-5-5", 4_000_000, 200_000, 5_000_000, 20_000_000],
3278
+ ["claude-sonnet-5-5", 2_000_000, 200_000, 2_500_000, 10_000_000],
3279
+ ["claude-opus-5", 5_000_000, 500_000, 6_250_000, 25_000_000],
3280
+ ["claude-sonnet-5", 2_000_000, 200_000, 2_500_000, 10_000_000],
3281
+ ["claude-opus-4-8", 5_000_000, 500_000, 6_250_000, 25_000_000],
3282
+ ["claude-opus-4-7", 5_000_000, 500_000, 6_250_000, 25_000_000],
3283
+ ["claude-opus-4-6", 5_000_000, 500_000, 6_250_000, 25_000_000],
3284
+ ["claude-sonnet-4-6", 3_000_000, 300_000, 3_750_000, 15_000_000],
3285
+ ["claude-haiku-4-5-20251001", 1_000_000, 100_000, 1_250_000, 5_000_000],
3286
+ ] as const
3287
+ ).map(([model, input, cachedInput, cacheWrite, output]) => [
3288
+ model,
3289
+ {
3290
+ default: {
3291
+ inputMicrosPerMillionTokens: input,
3292
+ cachedInputMicrosPerMillionTokens: cachedInput,
3293
+ cacheWriteMicrosPerMillionTokens: cacheWrite,
3294
+ outputMicrosPerMillionTokens: output,
3295
+ marginBps: 500,
3296
+ },
3297
+ },
3298
+ ]),
3299
+ ),
3300
+ };
3301
+
3302
+ // Explicitly priced free variant, not an unknown rate. List-only metadata
3303
+ // preserves previously accepted free-route execution definitions.
3304
+ // https://openrouter.ai/api/v1/models, verified 2026-10-03.
3305
+ const reviewedFreeOpenRouterListPricing: ModelPricingScheduleV1 = {
3306
+ default: {
3307
+ inputMicrosPerMillionTokens: 0,
3308
+ cachedInputMicrosPerMillionTokens: 0,
3309
+ cacheWriteMicrosPerMillionTokens: 0,
3310
+ outputMicrosPerMillionTokens: 0,
3311
+ marginBps: 500,
3312
+ },
3313
+ };
3314
+
2690
3315
  // --- backend-gated required-credential table (the single source of truth) ---
2691
3316
  // Each sandbox backend declares ONLY its own required credentials: a deployment
2692
3317
  // configured for `sandboxBackend=modal` must carry the Modal token, but a
@@ -2778,6 +3403,9 @@ function optionalEnvironmentValue(name: string, source: NodeJS.ProcessEnv): stri
2778
3403
  return value && value.trim().length > 0 ? value : undefined;
2779
3404
  }
2780
3405
 
3406
+ // getSettings runs per request in some processes; say this once per process.
3407
+ let idleCommandContainmentDisabledWarned = false;
3408
+
2781
3409
  export function getSettings(source: NodeJS.ProcessEnv = process.env): Settings {
2782
3410
  const optional = (name: string): string | undefined => optionalEnvironmentValue(name, source);
2783
3411
  const modelCatalogSource = optional("OPENGENI_MODEL_CATALOG_SOURCE");
@@ -2793,6 +3421,7 @@ export function getSettings(source: NodeJS.ProcessEnv = process.env): Settings {
2793
3421
  optional("GITHUB_SHA"),
2794
3422
  serverVersion: optional("OPENGENI_SERVER_VERSION"),
2795
3423
  databaseUrl: optional("OPENGENI_DATABASE_URL"),
3424
+ apiDatabasePoolMax: optional("OPENGENI_API_DATABASE_POOL_MAX"),
2796
3425
  dbSchema: optional("OPENGENI_DB_SCHEMA"),
2797
3426
  rlsStrategy: optional("OPENGENI_RLS_STRATEGY"),
2798
3427
  runtimeDatabaseRole: optional("OPENGENI_RUNTIME_DATABASE_ROLE"),
@@ -2826,26 +3455,33 @@ export function getSettings(source: NodeJS.ProcessEnv = process.env): Settings {
2826
3455
  optional("OPENGENI_OTEL_EXPORTER_OTLP_ENDPOINT") ?? optional("OTEL_EXPORTER_OTLP_ENDPOINT"),
2827
3456
  observabilityOtlpHeaders:
2828
3457
  optional("OPENGENI_OTEL_EXPORTER_OTLP_HEADERS") ?? optional("OTEL_EXPORTER_OTLP_HEADERS"),
3458
+ observabilityDiagnosticsEndpoint: optional("OPENGENI_OBSERVABILITY_DIAGNOSTICS_ENDPOINT"),
3459
+ observabilityDiagnosticsHeaders: optional("OPENGENI_OBSERVABILITY_DIAGNOSTICS_HEADERS"),
2829
3460
  analyticsEnabled: optional("OPENGENI_ANALYTICS_ENABLED"),
2830
3461
  analyticsConsentRequired: optional("OPENGENI_ANALYTICS_CONSENT_REQUIRED"),
2831
3462
  analyticsReoClientId: optional("OPENGENI_ANALYTICS_REO_CLIENT_ID"),
2832
3463
  analyticsPosthogProjectKey: optional("OPENGENI_ANALYTICS_POSTHOG_PROJECT_KEY"),
2833
3464
  analyticsPosthogHost: optional("OPENGENI_ANALYTICS_POSTHOG_HOST"),
2834
3465
  analyticsGa4MeasurementId: optional("OPENGENI_ANALYTICS_GA4_MEASUREMENT_ID"),
3466
+ legalPrivacyPolicyUrl: optional("OPENGENI_LEGAL_PRIVACY_POLICY_URL"),
3467
+ legalTermsOfServiceUrl: optional("OPENGENI_LEGAL_TERMS_OF_SERVICE_URL"),
3468
+ supportEmail: optional("OPENGENI_SUPPORT_EMAIL"),
2835
3469
  publicBaseUrl: optional("OPENGENI_PUBLIC_BASE_URL"),
3470
+ documentationUrl: optional("OPENGENI_DOCUMENTATION_URL"),
2836
3471
  mcpOauthEnabled: optional("OPENGENI_MCP_OAUTH_ENABLED"),
2837
- mcpOauthTrustedProxyHops: optional("OPENGENI_MCP_OAUTH_TRUSTED_PROXY_HOPS"),
3472
+ apiTrustedProxyHops: optional("OPENGENI_API_TRUSTED_PROXY_HOPS"),
3473
+ apiTrustedProxyCidrs: optional("OPENGENI_API_TRUSTED_PROXY_CIDRS"),
2838
3474
  webBaseUrl: optional("OPENGENI_WEB_BASE_URL"),
2839
3475
  agentReleasesBaseUrl: optional("OPENGENI_AGENT_RELEASES_BASE_URL"),
2840
3476
  agentStableVersion: optional("OPENGENI_AGENT_STABLE_VERSION"),
2841
3477
  agentBetaVersion: optional("OPENGENI_AGENT_BETA_VERSION"),
2842
3478
  productAccessMode: optional("OPENGENI_PRODUCT_ACCESS_MODE"),
2843
- organizationTenancyCanonicalActivationEnabled: optional(
2844
- "OPENGENI_ORGANIZATION_TENANCY_CANONICAL_ACTIVATION_ENABLED",
2845
- ),
2846
3479
  billingMode: optional("OPENGENI_BILLING_MODE"),
3480
+ verifiedSignupTrialCreditsEnabled: optional("OPENGENI_VERIFIED_SIGNUP_TRIAL_CREDITS_ENABLED"),
3481
+ creditPromotionPolicy: optional("OPENGENI_CREDIT_PROMOTION_POLICY_JSON"),
2847
3482
  entitlementsMode: optional("OPENGENI_ENTITLEMENTS_MODE"),
2848
3483
  usageLimitsMode: optional("OPENGENI_USAGE_LIMITS_MODE"),
3484
+ usageAllowancesEnabled: optional("OPENGENI_USAGE_ALLOWANCES_ENABLED"),
2849
3485
  staticEntitlementsJson: optional("OPENGENI_STATIC_ENTITLEMENTS_JSON"),
2850
3486
  staticUsageLimitsJson: optional("OPENGENI_STATIC_USAGE_LIMITS_JSON"),
2851
3487
  delegationSecret: optional("OPENGENI_DELEGATION_SECRET"),
@@ -2865,13 +3501,16 @@ export function getSettings(source: NodeJS.ProcessEnv = process.env): Settings {
2865
3501
  environmentsEncryptionKey: optional("OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY"),
2866
3502
  integrationsEnabled: optional("OPENGENI_INTEGRATIONS_ENABLED"),
2867
3503
  integrationsStateSecret: optional("OPENGENI_INTEGRATIONS_STATE_SECRET"),
3504
+ integrationsOauthShortStateEnabled: optional("OPENGENI_INTEGRATIONS_OAUTH_SHORT_STATE_ENABLED"),
2868
3505
  integrationsAllowPrivateNetworkTargets: optional(
2869
3506
  "OPENGENI_INTEGRATIONS_ALLOW_PRIVATE_NETWORK_TARGETS",
2870
3507
  ),
2871
3508
  integrationsOauthClientsJson: optional("OPENGENI_INTEGRATIONS_OAUTH_CLIENTS_JSON"),
3509
+ gmailWatchTopicName: optional("OPENGENI_GMAIL_WATCH_TOPIC_NAME"),
2872
3510
  slackClientId: optional("OPENGENI_SLACK_CLIENT_ID"),
2873
3511
  slackClientSecret: optional("OPENGENI_SLACK_CLIENT_SECRET"),
2874
3512
  slackSigningSecret: optional("OPENGENI_SLACK_SIGNING_SECRET"),
3513
+ slackAccessMode: optional("OPENGENI_SLACK_ACCESS_MODE"),
2875
3514
  slackBotDisplayName: optional("OPENGENI_SLACK_BOT_DISPLAY_NAME"),
2876
3515
  slackCommand: optional("OPENGENI_SLACK_COMMAND"),
2877
3516
  googleDriveClientId: optional("OPENGENI_GOOGLE_DRIVE_CLIENT_ID"),
@@ -2906,10 +3545,6 @@ export function getSettings(source: NodeJS.ProcessEnv = process.env): Settings {
2906
3545
  goalIdleBackoffMs: optional("OPENGENI_GOAL_IDLE_BACKOFF_MS"),
2907
3546
  goalIdleBackoffMaxMs: optional("OPENGENI_GOAL_IDLE_BACKOFF_MAX_MS"),
2908
3547
  childLifecycleNoticesEnabled: optional("OPENGENI_CHILD_LIFECYCLE_NOTICES_ENABLED"),
2909
- hostMcpAuthoritySourceAdmissionEnabled: optional(
2910
- "OPENGENI_HOST_MCP_AUTHORITY_SOURCE_ADMISSION_ENABLED",
2911
- ),
2912
- hostMcpCredentialResolversJson: optional("OPENGENI_HOST_MCP_CREDENTIAL_RESOLVERS_JSON"),
2913
3548
  slackWorkspaceRoutingEnabled: optional("OPENGENI_SLACK_WORKSPACE_ROUTING_ENABLED"),
2914
3549
  agentMaxModelCallsPerTurn: optional("OPENGENI_AGENT_MAX_MODEL_CALLS_PER_TURN"),
2915
3550
  contextWindowTokens: optional("OPENGENI_CONTEXT_WINDOW_TOKENS"),
@@ -2924,10 +3559,12 @@ export function getSettings(source: NodeJS.ProcessEnv = process.env): Settings {
2924
3559
  authAllowMetrics: optional("OPENGENI_AUTH_ALLOW_METRICS"),
2925
3560
  apiHost: optional("OPENGENI_API_HOST"),
2926
3561
  apiPort: optional("OPENGENI_API_PORT"),
3562
+ apiMetricsPort: optional("OPENGENI_API_METRICS_PORT"),
2927
3563
  workerHttpPort: optional("OPENGENI_WORKER_HTTP_PORT"),
2928
3564
  opengeniMcpInternalUrl: optional("OPENGENI_MCP_INTERNAL_URL"),
2929
3565
  opengeniMcpUrl: optional("OPENGENI_MCP_URL"),
2930
3566
  corsAllowOriginRegex: optional("OPENGENI_CORS_ALLOW_ORIGIN_REGEX"),
3567
+ localAllowedOrigins: optional("OPENGENI_LOCAL_ALLOWED_ORIGINS"),
2931
3568
  openaiProvider: optional("OPENGENI_OPENAI_PROVIDER"),
2932
3569
  openaiApiKey: optional("OPENGENI_OPENAI_API_KEY") ?? optional("OPENAI_API_KEY"),
2933
3570
  openaiBaseUrl: optional("OPENGENI_OPENAI_BASE_URL") ?? optional("OPENAI_BASE_URL"),
@@ -2986,6 +3623,7 @@ export function getSettings(source: NodeJS.ProcessEnv = process.env): Settings {
2986
3623
  modelProvidersJson: optional("OPENGENI_MODEL_PROVIDERS_JSON"),
2987
3624
  codexSubscriptionEnabled: optional("OPENGENI_CODEX_SUBSCRIPTION_ENABLED"),
2988
3625
  supergrokSubscriptionEnabled: optional("OPENGENI_SUPERGROK_SUBSCRIPTION_ENABLED"),
3626
+ claudeSubscriptionEnabled: optional("OPENGENI_CLAUDE_SUBSCRIPTION_ENABLED"),
2989
3627
  supergrokResponseStreamIdleTimeoutMs: optional(
2990
3628
  "OPENGENI_SUPERGROK_RESPONSE_STREAM_IDLE_TIMEOUT_MS",
2991
3629
  ),
@@ -2994,13 +3632,23 @@ export function getSettings(source: NodeJS.ProcessEnv = process.env): Settings {
2994
3632
  lazyToolSearchEnabled: optional("OPENGENI_LAZY_TOOL_SEARCH_ENABLED"),
2995
3633
  codexFleetPolicyShadowEnabled: optional("OPENGENI_CODEX_FLEET_POLICY_SHADOW_ENABLED"),
2996
3634
  codexProductSku: optional("OPENGENI_CODEX_PRODUCT_SKU"),
3635
+ reasoningConfigurationUpdatesEnabled: optional(
3636
+ "OPENGENI_REASONING_CONFIGURATION_UPDATES_ENABLED",
3637
+ ),
2997
3638
  openaiReasoningEffort: optional("OPENGENI_OPENAI_REASONING_EFFORT"),
2998
3639
  openaiAllowedReasoningEfforts: optional("OPENGENI_OPENAI_ALLOWED_REASONING_EFFORTS"),
3640
+ creditsDefaultModel: optional("OPENGENI_CREDITS_DEFAULT_MODEL"),
3641
+ creditsDefaultReasoningEffort: optional("OPENGENI_CREDITS_DEFAULT_REASONING_EFFORT"),
2999
3642
  openaiResponsesTransport: optional("OPENGENI_OPENAI_RESPONSES_TRANSPORT"),
3000
3643
  openaiProviderItemIds: optional("OPENGENI_OPENAI_PROVIDER_ITEM_IDS"),
3001
3644
  openaiReasoningEncryptedContent: optional("OPENGENI_OPENAI_REASONING_ENCRYPTED_CONTENT"),
3002
3645
  openaiMaxRetries: optional("OPENGENI_OPENAI_MAX_RETRIES"),
3003
3646
  webSearchEnabled: optional("OPENGENI_WEB_SEARCH_ENABLED"),
3647
+ jevApiKey: optional("OPENGENI_JEV_API_KEY"),
3648
+ jevBaseUrl: optional("OPENGENI_JEV_BASE_URL"),
3649
+ jevModel: optional("OPENGENI_JEV_MODEL"),
3650
+ jevRequestTimeoutMs: optional("OPENGENI_JEV_REQUEST_TIMEOUT_MS"),
3651
+ codeSearchMode: optional("OPENGENI_CODE_SEARCH_MODE"),
3004
3652
  agentInstructionsTemplate: optional("OPENGENI_AGENT_INSTRUCTIONS_TEMPLATE"),
3005
3653
  azureOpenaiBaseUrl: optional("OPENGENI_AZURE_OPENAI_BASE_URL"),
3006
3654
  azureOpenaiEndpoint: optional("OPENGENI_AZURE_OPENAI_ENDPOINT"),
@@ -3017,6 +3665,7 @@ export function getSettings(source: NodeJS.ProcessEnv = process.env): Settings {
3017
3665
  dockerWorkspaceBaseDir: optional("OPENGENI_DOCKER_WORKSPACE_BASE_DIR"),
3018
3666
  modalAppName: optional("OPENGENI_MODAL_APP_NAME"),
3019
3667
  modalImageRef: optional("OPENGENI_MODAL_IMAGE_REF") ?? DEFAULT_MODAL_IMAGE_REF,
3668
+ modalCommandSupervisionEnabled: optional("OPENGENI_MODAL_COMMAND_SUPERVISION_ENABLED"),
3020
3669
  modalImageId: optional("OPENGENI_MODAL_IMAGE_ID"),
3021
3670
  modalImageRegistrySecret: optional("OPENGENI_MODAL_IMAGE_REGISTRY_SECRET"),
3022
3671
  modalTimeoutSeconds: optional("OPENGENI_MODAL_TIMEOUT_SECONDS"),
@@ -3068,6 +3717,9 @@ export function getSettings(source: NodeJS.ProcessEnv = process.env): Settings {
3068
3717
  blaxelTtl: optional("OPENGENI_BLAXEL_TTL"),
3069
3718
  cloudflareWorkerUrl: optional("OPENGENI_CLOUDFLARE_WORKER_URL"),
3070
3719
  cloudflareApiKey: optional("OPENGENI_CLOUDFLARE_API_KEY"),
3720
+ experimentalBrowserContextPoolEnabled: optional(
3721
+ "OPENGENI_EXPERIMENTAL_BROWSER_CONTEXT_POOL_ENABLED",
3722
+ ),
3071
3723
  browserbaseApiKey: optional("OPENGENI_BROWSERBASE_API_KEY"),
3072
3724
  kernelApiKey: optional("OPENGENI_KERNEL_API_KEY"),
3073
3725
  kernelEndpoint: optional("OPENGENI_KERNEL_ENDPOINT"),
@@ -3116,6 +3768,7 @@ export function getSettings(source: NodeJS.ProcessEnv = process.env): Settings {
3116
3768
  sandboxViewerHolderTtlMs: optional("OPENGENI_SANDBOX_VIEWER_HOLDER_TTL_MS"),
3117
3769
  sandboxInteractionHolderTtlMs: optional("OPENGENI_SANDBOX_INTERACTION_HOLDER_TTL_MS"),
3118
3770
  sandboxIdleGraceMs: optional("OPENGENI_SANDBOX_IDLE_GRACE_MS"),
3771
+ sandboxIdleCommandContainmentMs: optional("OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS"),
3119
3772
  sandboxSnapshotIntervalMs: optional("OPENGENI_SANDBOX_SNAPSHOT_INTERVAL_MS"),
3120
3773
  sandboxSnapshotTimeoutMs: optional("OPENGENI_SANDBOX_SNAPSHOT_TIMEOUT_MS"),
3121
3774
  sandboxDrainSnapshotTimeoutMs: optional("OPENGENI_SANDBOX_DRAIN_SNAPSHOT_TIMEOUT_MS"),
@@ -3129,9 +3782,11 @@ export function getSettings(source: NodeJS.ProcessEnv = process.env): Settings {
3129
3782
  sandboxWarmRateMicrosPerSecondJson: optional(
3130
3783
  "OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON",
3131
3784
  ),
3785
+ sandboxWarmBillingMode: optional("OPENGENI_SANDBOX_WARM_BILLING_MODE"),
3132
3786
  sandboxMaxWarmSecondsPerWorkspace: optional("OPENGENI_SANDBOX_MAX_WARM_SECONDS_PER_WORKSPACE"),
3133
3787
  sandboxPreparationProfiles: optional("OPENGENI_SANDBOX_PREPARATION_PROFILES"),
3134
3788
  sandboxEnvAllowlist: optional("OPENGENI_SANDBOX_ENV_ALLOWLIST"),
3789
+ sandboxImageAllowlist: optional("OPENGENI_SANDBOX_IMAGE_ALLOWLIST"),
3135
3790
  objectStorageEndpoint: optional("OPENGENI_OBJECT_STORAGE_ENDPOINT"),
3136
3791
  objectStorageInternalEndpoint: optional("OPENGENI_OBJECT_STORAGE_INTERNAL_ENDPOINT"),
3137
3792
  objectStorageSandboxEndpoint: optional("OPENGENI_OBJECT_STORAGE_SANDBOX_ENDPOINT"),
@@ -3158,6 +3813,13 @@ export function getSettings(source: NodeJS.ProcessEnv = process.env): Settings {
3158
3813
  documentEmbeddingDimensions: optional("OPENGENI_DOCUMENT_EMBEDDING_DIMENSIONS"),
3159
3814
  documentEmbeddingApiKey: optional("OPENGENI_DOCUMENT_EMBEDDING_API_KEY"),
3160
3815
  documentEmbeddingBaseUrl: optional("OPENGENI_DOCUMENT_EMBEDDING_BASE_URL"),
3816
+ documentEmbeddingBillingMode: optional("OPENGENI_DOCUMENT_EMBEDDING_BILLING_MODE"),
3817
+ documentEmbeddingCreditsActivatedAt: optional(
3818
+ "OPENGENI_DOCUMENT_EMBEDDING_CREDITS_ACTIVATED_AT",
3819
+ ),
3820
+ documentEmbeddingRateMicrosPerMillionBytes: optional(
3821
+ "OPENGENI_DOCUMENT_EMBEDDING_RATE_MICROS_PER_MILLION_BYTES",
3822
+ ),
3161
3823
  documentCurationProvider: optional("OPENGENI_DOCUMENT_CURATION_PROVIDER"),
3162
3824
  documentCurationModel: optional("OPENGENI_DOCUMENT_CURATION_MODEL"),
3163
3825
  documentCurationApiKey: optional("OPENGENI_DOCUMENT_CURATION_API_KEY"),
@@ -3192,7 +3854,12 @@ export function getSettings(source: NodeJS.ProcessEnv = process.env): Settings {
3192
3854
  managedAuthGoogleClientSecret: optional("OPENGENI_MANAGED_AUTH_GOOGLE_CLIENT_SECRET"),
3193
3855
  managedAuthGithubClientId: optional("OPENGENI_MANAGED_AUTH_GITHUB_CLIENT_ID"),
3194
3856
  managedAuthGithubClientSecret: optional("OPENGENI_MANAGED_AUTH_GITHUB_CLIENT_SECRET"),
3857
+ allowedUserEmails:
3858
+ source.OPENGENI_ALLOWED_USER_EMAILS === undefined
3859
+ ? undefined
3860
+ : source.OPENGENI_ALLOWED_USER_EMAILS.split(",").map((email) => email.trim()),
3195
3861
  managedAuthSessionSetMode: optional("OPENGENI_MANAGED_AUTH_SESSION_SET_MODE"),
3862
+ managedAuthNewSignupsEnabled: optional("OPENGENI_MANAGED_AUTH_NEW_SIGNUPS_ENABLED"),
3196
3863
  organizationUserSetupEmailTokenTransport: optional(
3197
3864
  "OPENGENI_ORGANIZATION_USER_SETUP_EMAIL_TOKEN_TRANSPORT",
3198
3865
  ),
@@ -3216,14 +3883,80 @@ export function getSettings(source: NodeJS.ProcessEnv = process.env): Settings {
3216
3883
  : parsed.sandboxIdleGraceMs,
3217
3884
  sandboxRotationLeadMs:
3218
3885
  raw.sandboxRotationLeadMs === undefined && parsed.sandboxBackend === "modal"
3219
- ? Math.min(3_600_000, Math.floor((parsed.modalTimeoutSeconds * 1000) / 2))
3886
+ ? Math.min(
3887
+ 3_600_000,
3888
+ Math.max(
3889
+ Math.floor((parsed.modalTimeoutSeconds * 1000) / 2),
3890
+ SANDBOX_DEADLINE_COMMAND_STOP_GRACE_MS +
3891
+ sandboxArchiveCaptureTimeoutMs({
3892
+ sandboxSnapshotTimeoutMs: Math.max(
3893
+ parsed.sandboxSnapshotTimeoutMs,
3894
+ parsed.sandboxDrainSnapshotTimeoutMs ?? parsed.sandboxSnapshotTimeoutMs,
3895
+ ),
3896
+ }) +
3897
+ 2 * parsed.sandboxLeaseReaperPeriodMs +
3898
+ 1,
3899
+ ),
3900
+ )
3220
3901
  : parsed.sandboxRotationLeadMs,
3221
3902
  mcpServers: ensureBuiltInMcpServers(parsed),
3222
3903
  };
3904
+ if (raw.sandboxIdleCommandContainmentMs === undefined) {
3905
+ // Strictly between the idle grace and the rotation lead whenever that
3906
+ // interval exists (short test/canary lifetimes), never above 30 minutes,
3907
+ // and early enough that an explicit Modal idle timeout cannot fire first.
3908
+ const modalIdleCeilingMs =
3909
+ settings.sandboxBackend === "modal" && settings.modalIdleTimeoutSeconds !== undefined
3910
+ ? settings.modalIdleTimeoutSeconds * 1000 -
3911
+ settings.sandboxLeaseReaperPeriodMs -
3912
+ sandboxArchiveCaptureTimeoutMs({
3913
+ sandboxSnapshotTimeoutMs: effectiveSandboxDrainSnapshotTimeoutMs(settings),
3914
+ }) -
3915
+ 1
3916
+ : Number.POSITIVE_INFINITY;
3917
+ const derived = Math.min(
3918
+ 1_800_000,
3919
+ Math.floor((settings.sandboxIdleGraceMs + settings.sandboxRotationLeadMs) / 2),
3920
+ modalIdleCeilingMs,
3921
+ );
3922
+ // A derived value never fails validation: with no room above the idle
3923
+ // grace, idle containment stays off and only the deadline rule applies.
3924
+ if (derived > settings.sandboxIdleGraceMs) {
3925
+ settings.sandboxIdleCommandContainmentMs = derived;
3926
+ } else {
3927
+ settings.sandboxIdleCommandContainmentMs = undefined;
3928
+ if (!idleCommandContainmentDisabledWarned) {
3929
+ idleCommandContainmentDisabledWarned = true;
3930
+ console.warn(
3931
+ "[config] idle command containment disabled: no window fits between " +
3932
+ `OPENGENI_SANDBOX_IDLE_GRACE_MS (${settings.sandboxIdleGraceMs}) and the Modal idle ` +
3933
+ "timeout / rotation lead ceiling; set OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS to override.",
3934
+ );
3935
+ }
3936
+ }
3937
+ }
3938
+ warnRetiredOrganizationTenancyActivationSwitch(source);
3223
3939
  validateSettings(settings, source);
3224
3940
  return settings;
3225
3941
  }
3226
3942
 
3943
+ let retiredOrganizationTenancyActivationSwitchWarned = false;
3944
+
3945
+ /**
3946
+ * Session-tenancy activation is universal since migration 0611, so the former
3947
+ * deployment switch is accepted and ignored. Deployments that still set it keep
3948
+ * booting; the one-time warning tells the operator to delete it.
3949
+ */
3950
+ function warnRetiredOrganizationTenancyActivationSwitch(source: NodeJS.ProcessEnv): void {
3951
+ if (retiredOrganizationTenancyActivationSwitchWarned) return;
3952
+ if (source.OPENGENI_ORGANIZATION_TENANCY_CANONICAL_ACTIVATION_ENABLED === undefined) return;
3953
+ retiredOrganizationTenancyActivationSwitchWarned = true;
3954
+ console.warn(
3955
+ "[config] OPENGENI_ORGANIZATION_TENANCY_CANONICAL_ACTIVATION_ENABLED is retired and ignored: " +
3956
+ "every organization is session-tenancy activated (migration 0611). Remove it from the deployment.",
3957
+ );
3958
+ }
3959
+
3227
3960
  const LOCAL_FIRST_PARTY_DELEGATION_SECRET = "opengeni-local-first-party-delegation-secret-v1";
3228
3961
 
3229
3962
  /**
@@ -3256,7 +3989,7 @@ export function resolveFirstPartyMcpToolPolicy(
3256
3989
  ): FirstPartyMcpToolPolicy {
3257
3990
  const allowed = currentAgentLearningToolSelection(
3258
3991
  settings.allowedFirstPartyMcpTools ?? [...FIRST_PARTY_MCP_TOOL_NAMES],
3259
- );
3992
+ ).filter((tool) => !isRetiredNativeAtlassianTool(tool));
3260
3993
  const allowedSet = new Set(allowed);
3261
3994
  const defaults = currentAgentLearningToolSelection(
3262
3995
  settings.defaultFirstPartyMcpTools ?? [...DEFAULT_FIRST_PARTY_MCP_TOOLS],
@@ -3789,6 +4522,7 @@ function gatewayRegistryProvider(
3789
4522
  upstreamModelId: model.upstreamModelId,
3790
4523
  label: model.label,
3791
4524
  ...(model.shortLabel ? { shortLabel: model.shortLabel } : {}),
4525
+ ...(model.logoUrl ? { logoUrl: model.logoUrl } : {}),
3792
4526
  capabilities: gatewayModelCapabilities(settings, {
3793
4527
  implicitCaching: model.implicitCaching,
3794
4528
  vision: model.vision,
@@ -3894,6 +4628,7 @@ function openRouterRegistryProvider(
3894
4628
  aliases,
3895
4629
  label: model.label,
3896
4630
  ...(model.shortLabel ? { shortLabel: model.shortLabel } : {}),
4631
+ ...(model.logoUrl ? { logoUrl: model.logoUrl } : {}),
3897
4632
  capabilities: model.capabilities,
3898
4633
  ...(model.contextWindowTokens === undefined
3899
4634
  ? {}
@@ -3949,7 +4684,11 @@ function openRouterRegistryProvider(
3949
4684
 
3950
4685
  function configuredRegistryProviders(settings: Settings): InternalRegistryProvider[] {
3951
4686
  const providers = parseModelProvidersJson(settings.modelProvidersJson);
3952
- const injected: InternalRegistryProvider[] = [...providers];
4687
+ const injected: InternalRegistryProvider[] = providers.filter(
4688
+ (provider) =>
4689
+ settings.claudeSubscriptionEnabled ||
4690
+ !(provider.api === "anthropic-messages" && provider.anthropic?.auth === "oauth"),
4691
+ );
3953
4692
  if (settings.vercelAiGatewayApiKey && configuredGatewayCatalogModels(settings).length > 0) {
3954
4693
  injected.push(
3955
4694
  gatewayRegistryProvider(settings, {
@@ -3968,6 +4707,53 @@ function configuredRegistryProviders(settings: Settings): InternalRegistryProvid
3968
4707
  return injected;
3969
4708
  }
3970
4709
 
4710
+ /** Customer-owned OpenAI/Azure routes, bound to immutable connection identity. */
4711
+ export function withDirectModelProviders(
4712
+ settings: Settings,
4713
+ connections: readonly {
4714
+ id: string;
4715
+ version: number;
4716
+ subjectId: string | null;
4717
+ kind: string;
4718
+ status: string;
4719
+ providerDomain: string;
4720
+ metadata: Record<string, unknown>;
4721
+ apiKey?: string;
4722
+ }[],
4723
+ ): Settings {
4724
+ const providers = parseModelProvidersJson(settings.modelProvidersJson).filter(
4725
+ (provider) =>
4726
+ !provider.id.startsWith("workspace-openai-") &&
4727
+ !provider.id.startsWith("workspace-azure-openai-"),
4728
+ );
4729
+ for (const connection of connections) {
4730
+ const spec = directModelConnectionSpec(connection);
4731
+ if (!spec) continue;
4732
+ providers.push({
4733
+ kind: spec.provider === "openai" ? "direct-openai-workspace" : "direct-azure-workspace",
4734
+ id: spec.providerId,
4735
+ label: spec.provider === "openai" ? "Your OpenAI" : "Your Azure OpenAI",
4736
+ api: "responses",
4737
+ wireProfile: spec.provider === "openai" ? "openai" : "azure-openai",
4738
+ baseUrl: spec.baseUrl,
4739
+ ...(connection.apiKey ? { apiKey: connection.apiKey } : {}),
4740
+ models: [
4741
+ {
4742
+ id: spec.modelId,
4743
+ upstreamModelId: spec.model,
4744
+ label: spec.model,
4745
+ capabilities: legacyModelCapabilities(settings, {
4746
+ reasoningEffort: false,
4747
+ hostedWebSearch: false,
4748
+ }),
4749
+ toolOutputTruncationTokens: settings.modelToolOutputTruncationTokens,
4750
+ },
4751
+ ],
4752
+ });
4753
+ }
4754
+ return { ...settings, modelProvidersJson: JSON.stringify(providers) };
4755
+ }
4756
+
3971
4757
  /** Static catalog overlay; it contains no concrete workspace credential. */
3972
4758
  export function withWorkspaceGatewayCatalogProvider(
3973
4759
  settings: Settings,
@@ -4058,7 +4844,10 @@ export function withWorkspaceOpenRouterCredential(
4058
4844
  /** Secret-free organization Vercel AI Gateway catalog overlay. */
4059
4845
  export function withOrganizationGatewayCatalogProvider(
4060
4846
  settings: Settings,
4061
- customModels: readonly { upstreamModelId: string; label?: string | null }[] = [],
4847
+ customModels: readonly {
4848
+ upstreamModelId: string;
4849
+ label?: string | null;
4850
+ }[] = [],
4062
4851
  ): Settings {
4063
4852
  if (customModels.length === 0) return settings;
4064
4853
  const providers = parseModelProvidersJson(settings.modelProvidersJson).filter(
@@ -4074,7 +4863,10 @@ export function withOrganizationGatewayCatalogProvider(
4074
4863
  export function withOrganizationGatewayCredential(
4075
4864
  settings: Settings,
4076
4865
  apiKey: string,
4077
- customModels: readonly { upstreamModelId: string; label?: string | null }[] = [],
4866
+ customModels: readonly {
4867
+ upstreamModelId: string;
4868
+ label?: string | null;
4869
+ }[] = [],
4078
4870
  ): Settings {
4079
4871
  if (!apiKey.trim()) throw new Error("organization AI Gateway credential is empty");
4080
4872
  const catalog = withOrganizationGatewayCatalogProvider(settings, customModels);
@@ -4087,7 +4879,10 @@ export function withOrganizationGatewayCredential(
4087
4879
  /** Secret-free organization OpenRouter catalog overlay. */
4088
4880
  export function withOrganizationOpenRouterCatalogProvider(
4089
4881
  settings: Settings,
4090
- customModels: readonly { upstreamModelId: string; label?: string | null }[] = [],
4882
+ customModels: readonly {
4883
+ upstreamModelId: string;
4884
+ label?: string | null;
4885
+ }[] = [],
4091
4886
  ): Settings {
4092
4887
  const providers = parseModelProvidersJson(settings.modelProvidersJson).filter(
4093
4888
  (provider) => provider.id !== ORGANIZATION_OPENROUTER_PROVIDER_ID,
@@ -4104,7 +4899,10 @@ export function withOrganizationOpenRouterCatalogProvider(
4104
4899
  export function withOrganizationOpenRouterCredential(
4105
4900
  settings: Settings,
4106
4901
  apiKey: string,
4107
- customModels: readonly { upstreamModelId: string; label?: string | null }[] = [],
4902
+ customModels: readonly {
4903
+ upstreamModelId: string;
4904
+ label?: string | null;
4905
+ }[] = [],
4108
4906
  ): Settings {
4109
4907
  if (!apiKey.trim()) throw new Error("organization OpenRouter credential is empty");
4110
4908
  const catalog = withOrganizationOpenRouterCatalogProvider(settings, customModels);
@@ -4157,8 +4955,8 @@ export function productShortLabelForModelId(modelId: string): string | null {
4157
4955
  ? modelId.slice(CODEX_MODEL_ID_PREFIX.length)
4158
4956
  : modelId;
4159
4957
  switch (slug) {
4160
- case "grok-4.6":
4161
- return "4.6";
4958
+ case "grok-4.7":
4959
+ return "4.7";
4162
4960
  case "gpt-5.6-sol":
4163
4961
  return "5.6 Sol";
4164
4962
  case "gpt-5.6-terra":
@@ -4167,6 +4965,10 @@ export function productShortLabelForModelId(modelId: string): string | null {
4167
4965
  return "5.6 Luna";
4168
4966
  case "gpt-6-astra":
4169
4967
  return "6 Astra";
4968
+ case "gpt-6-sol":
4969
+ return "6 Sol";
4970
+ case "gpt-6-luna":
4971
+ return "6 Luna";
4170
4972
  default:
4171
4973
  return null;
4172
4974
  }
@@ -4204,8 +5006,9 @@ function builtinLatencyModesForModel(modelId: string): Array<{
4204
5006
  }> {
4205
5007
  if (
4206
5008
  isBuiltinGpt56ModelId(modelId) ||
5009
+ /^gpt-6(?:\.\d+)?-/u.test(modelId) ||
4207
5010
  modelId.startsWith("codex/gpt-5.6-") ||
4208
- modelId === "codex/gpt-6-astra"
5011
+ /^codex\/gpt-6(?:\.\d+)?-/u.test(modelId)
4209
5012
  ) {
4210
5013
  return [
4211
5014
  { id: "standard", upstream: "supported", runnable: true },
@@ -4220,13 +5023,38 @@ function builtinLatencyModesForModel(modelId: string): Array<{
4220
5023
  return [{ id: "standard", upstream: "unknown", runnable: true }];
4221
5024
  }
4222
5025
 
5026
+ function isReviewedGptVisionModel(slug: string): boolean {
5027
+ return slug.startsWith("gpt-5.6-") || /^gpt-6(?:\.\d+)?-/u.test(slug);
5028
+ }
5029
+
5030
+ /** Repair missing reviewed capabilities in live/stored Codex definitions.
5031
+ * Explicit latency restrictions and every unrelated catalog field remain authoritative.
5032
+ */
5033
+ function reviewedCodexCatalogCapabilities(
5034
+ slug: string,
5035
+ capabilities: ModelCapabilitiesV1,
5036
+ ): ModelCapabilitiesV1 {
5037
+ if (!/^gpt-6(?:\.\d+)?-/u.test(slug)) return capabilities;
5038
+ const fast = builtinLatencyModesForModel(`${CODEX_MODEL_ID_PREFIX}${slug}`).find(
5039
+ (mode) => mode.id === "fast",
5040
+ );
5041
+ return normalizeCapabilities({
5042
+ ...capabilities,
5043
+ inputModalities: [...new Set([...capabilities.inputModalities, "image" as const])],
5044
+ latencyModes:
5045
+ fast && !capabilities.latencyModes.some((mode) => mode.id === "fast")
5046
+ ? [...capabilities.latencyModes, fast]
5047
+ : capabilities.latencyModes,
5048
+ });
5049
+ }
5050
+
4223
5051
  function builtinPromptCachingForModel(
4224
5052
  modelId: string,
4225
5053
  ): NonNullable<ModelCapabilitiesV1["promptCaching"]> | undefined {
4226
5054
  const slug = modelId.startsWith(CODEX_MODEL_ID_PREFIX)
4227
5055
  ? modelId.slice(CODEX_MODEL_ID_PREFIX.length)
4228
5056
  : modelId;
4229
- return slug.startsWith("gpt-5.6-")
5057
+ return slug.startsWith("gpt-5.6-") || slug.startsWith("gpt-6-")
4230
5058
  ? { upstream: "supported", runnable: true, mode: "implicit" }
4231
5059
  : undefined;
4232
5060
  }
@@ -4236,7 +5064,7 @@ function builtinHostedImageGenerationForModel(settings: Settings, modelId: strin
4236
5064
  return (
4237
5065
  settings.openaiProvider === "openai" &&
4238
5066
  isDirectOpenAiApiBaseUrl(settings.openaiBaseUrl) &&
4239
- isBuiltinGpt56ModelId(modelId)
5067
+ (isBuiltinGpt56ModelId(modelId) || modelId.startsWith("gpt-6-"))
4240
5068
  );
4241
5069
  }
4242
5070
 
@@ -4313,9 +5141,22 @@ function assertLatencyModeRunnable(
4313
5141
  ): void {
4314
5142
  const runnable = runnableLatencyModesForModel(settings, modelId);
4315
5143
  if (!runnable.includes(latencyMode)) {
4316
- throw new Error(
4317
- `latency mode ${latencyMode} is not runnable for model ${modelId} (allowed: ${runnable.join(", ")})`,
5144
+ throw new UnsupportedLatencyModeError(modelId, latencyMode, runnable);
5145
+ }
5146
+ }
5147
+
5148
+ export class UnsupportedLatencyModeError extends Error {
5149
+ readonly code = "UNSUPPORTED_LATENCY_MODE";
5150
+
5151
+ constructor(
5152
+ readonly modelId: string,
5153
+ readonly latencyMode: LatencyMode,
5154
+ readonly allowedLatencyModes: readonly LatencyMode[],
5155
+ ) {
5156
+ super(
5157
+ `latency mode ${latencyMode} is not runnable for model ${modelId} (allowed: ${allowedLatencyModes.join(", ")})`,
4318
5158
  );
5159
+ this.name = "UnsupportedLatencyModeError";
4319
5160
  }
4320
5161
  }
4321
5162
 
@@ -4327,10 +5168,17 @@ function registryCredentialSource(provider: InternalRegistryProvider): Credentia
4327
5168
  return { kind: "connected_subscription", provider: "codex" };
4328
5169
  case "xai-subscription":
4329
5170
  return { kind: "connected_subscription", provider: "xai" };
5171
+ case "claude-subscription-workspace":
5172
+ case "claude-subscription-organization":
5173
+ return { kind: "connected_subscription", provider: "claude" };
4330
5174
  case "vercel-gateway-workspace":
5175
+ case "direct-openai-workspace":
5176
+ case "direct-azure-workspace":
4331
5177
  case "openrouter-workspace":
5178
+ case "anthropic-workspace":
4332
5179
  return { kind: "workspace_connection", mechanism: "api_key" };
4333
5180
  case "vercel-gateway-organization":
5181
+ case "anthropic-organization":
4334
5182
  case "openrouter-organization":
4335
5183
  return { kind: "organization_connection", mechanism: "api_key" };
4336
5184
  case "api-key":
@@ -4351,11 +5199,17 @@ function registryBilling(provider: InternalRegistryProvider): BillingAttribution
4351
5199
  return { upstreamPayer: "deployment", metering: "external" };
4352
5200
  case "codex-subscription":
4353
5201
  case "xai-subscription":
5202
+ case "claude-subscription-workspace":
5203
+ case "claude-subscription-organization":
4354
5204
  return { upstreamPayer: "connected_subscription", metering: "external" };
4355
5205
  case "vercel-gateway-workspace":
5206
+ case "direct-openai-workspace":
5207
+ case "direct-azure-workspace":
4356
5208
  case "openrouter-workspace":
5209
+ case "anthropic-workspace":
4357
5210
  return { upstreamPayer: "workspace", metering: "external" };
4358
5211
  case "vercel-gateway-organization":
5212
+ case "anthropic-organization":
4359
5213
  case "openrouter-organization":
4360
5214
  return { upstreamPayer: "organization", metering: "external" };
4361
5215
  case "api-key":
@@ -4394,6 +5248,7 @@ function builtinCredentialSource(settings: Settings): CredentialSourceV1 {
4394
5248
  }
4395
5249
 
4396
5250
  function staticRequestMetadataForDigest(provider: ResolvedModelProvider): {
5251
+ anthropic?: ResolvedModelProvider["anthropic"];
4397
5252
  headers: Array<{
4398
5253
  name: string;
4399
5254
  classification: "public" | "secret";
@@ -4408,6 +5263,12 @@ function staticRequestMetadataForDigest(provider: ResolvedModelProvider): {
4408
5263
  const publicHeaders = new Set(provider.publicDefaultHeaderNames ?? []);
4409
5264
  const publicQuery = new Set(provider.publicDefaultQueryNames ?? []);
4410
5265
  return {
5266
+ ...(provider.anthropic
5267
+ ? {
5268
+ anthropic: (({ identity: _identity, credentialBinding: _binding, ...options }) =>
5269
+ options)(provider.anthropic),
5270
+ }
5271
+ : {}),
4411
5272
  headers: Object.entries(provider.defaultHeaders ?? {})
4412
5273
  .sort(([left], [right]) => left.localeCompare(right))
4413
5274
  .map(([name, value]) =>
@@ -4464,6 +5325,7 @@ function definitionVersionFor(
4464
5325
  baseUrl: provider.baseUrl ?? null,
4465
5326
  defaultHeaders: requestMetadata.headers,
4466
5327
  defaultQuery: requestMetadata.query,
5328
+ ...(requestMetadata.anthropic ? { anthropic: requestMetadata.anthropic } : {}),
4467
5329
  },
4468
5330
  credentialSource: model.credentialSource,
4469
5331
  billing: model.billing,
@@ -4493,6 +5355,75 @@ function legacyImplicitOpenAiDefinitionVersionFor(
4493
5355
  });
4494
5356
  }
4495
5357
 
5358
+ function legacyCodexAstraImplicitCachingDefinitionVersionFor(
5359
+ model: ConfiguredModel,
5360
+ provider: ResolvedModelProvider,
5361
+ ): string | null {
5362
+ // The GPT-6 rollout only made the already-implicit Codex cache discoverable.
5363
+ // Bound this compatibility to that product/transport and exact declaration;
5364
+ // never normalize explicit caching, another capability, or another model.
5365
+ if (
5366
+ model.id !== "codex/gpt-6-astra" ||
5367
+ model.upstreamModelId !== "gpt-6-astra" ||
5368
+ provider.id !== CODEX_PROVIDER_ID ||
5369
+ provider.kind !== "codex-subscription" ||
5370
+ provider.api !== "responses" ||
5371
+ provider.wireProfile !== "openai" ||
5372
+ canonicalJson(model.capabilities.promptCaching) !==
5373
+ canonicalJson({ upstream: "supported", runnable: true, mode: "implicit" })
5374
+ ) {
5375
+ return null;
5376
+ }
5377
+ const { definitionVersion: _definitionVersion, ...modelWithoutVersion } = model;
5378
+ const { promptCaching: _promptCaching, ...capabilities } = model.capabilities;
5379
+ // Recompute, rather than allowlisting an incident hash: all other current
5380
+ // fields must still reproduce the accepted digest. Do not compose this with
5381
+ // the older wire-profile compatibility or rewrite the accepted policy.
5382
+ return definitionVersionFor({ ...modelWithoutVersion, capabilities }, provider);
5383
+ }
5384
+
5385
+ function matchesAdditiveCapabilityDefinitionVersion(
5386
+ model: ConfiguredModel,
5387
+ provider: ResolvedModelProvider,
5388
+ policy: TurnExecutionPolicyV1,
5389
+ ): boolean {
5390
+ const { definitionVersion: _definitionVersion, ...modelWithoutVersion } = model;
5391
+ const { latencyModes, inputModalities } = model.capabilities;
5392
+ // V1 has only three unique latency ids and three unique input modalities:
5393
+ // at most 4 * 7 subset digests retaining the frozen mode. Reconstruct an
5394
+ // exact historical declaration; never ignore the digest or alter existing
5395
+ // mode support, runnable state, billing multiplier, or request-tier routing.
5396
+ // Every other executable field remains in the digest. Do not compose this
5397
+ // with the pre-wire-profile or implicit-caching migration exceptions.
5398
+ for (let latencyMask = 1; latencyMask < 1 << latencyModes.length; latencyMask += 1) {
5399
+ const retainedModes = latencyModes.filter((_mode, index) => latencyMask & (1 << index));
5400
+ if (!retainedModes.some((mode) => mode.id === policy.latencyMode && mode.runnable)) {
5401
+ continue;
5402
+ }
5403
+ for (let inputMask = 1; inputMask < 1 << inputModalities.length; inputMask += 1) {
5404
+ const retainedInputs = inputModalities.filter((_modality, index) => inputMask & (1 << index));
5405
+ if (
5406
+ retainedModes.length === latencyModes.length &&
5407
+ retainedInputs.length === inputModalities.length
5408
+ ) {
5409
+ continue;
5410
+ }
5411
+ const capabilities = {
5412
+ ...model.capabilities,
5413
+ latencyModes: retainedModes,
5414
+ inputModalities: retainedInputs,
5415
+ };
5416
+ if (
5417
+ policy.definitionVersion ===
5418
+ definitionVersionFor({ ...modelWithoutVersion, capabilities }, provider)
5419
+ ) {
5420
+ return true;
5421
+ }
5422
+ }
5423
+ }
5424
+ return false;
5425
+ }
5426
+
4496
5427
  /**
4497
5428
  * The built-in provider's stable id: "openai" on the OpenAI platform, "azure"
4498
5429
  * on Azure. Exported because the workspace model-policy gate must attribute
@@ -4534,12 +5465,13 @@ export function configuredProviders(
4534
5465
  if (settings.openaiProvider === "azure") {
4535
5466
  const baseUrl = settings.azureOpenaiBaseUrl ?? settings.azureOpenaiEndpoint;
4536
5467
  builtin.baseUrl = baseUrl ? normalizeRegistryBaseUrl(baseUrl, builtin.id) : undefined;
4537
- builtin.apiKey = settings.azureOpenaiApiKey ?? settings.azureOpenaiAdToken;
5468
+ builtin.apiKey =
5469
+ usableDeploymentSecret(settings.azureOpenaiApiKey) ?? settings.azureOpenaiAdToken;
4538
5470
  } else {
4539
5471
  builtin.baseUrl = settings.openaiBaseUrl
4540
5472
  ? normalizeRegistryBaseUrl(settings.openaiBaseUrl, builtin.id)
4541
5473
  : undefined;
4542
- builtin.apiKey = settings.openaiApiKey;
5474
+ builtin.apiKey = usableDeploymentSecret(settings.openaiApiKey);
4543
5475
  }
4544
5476
  const registry = configuredRegistryProviders(settings).map(
4545
5477
  (provider): ResolvedModelProvider => ({
@@ -4547,6 +5479,7 @@ export function configuredProviders(
4547
5479
  label: provider.label ?? provider.id,
4548
5480
  kind: provider.kind,
4549
5481
  api: provider.api,
5482
+ anthropic: provider.anthropic,
4550
5483
  wireProfile: provider.wireProfile,
4551
5484
  builtin: false,
4552
5485
  baseUrl: provider.baseUrl,
@@ -4568,11 +5501,30 @@ export function configuredProviders(
4568
5501
  * select, lease, refresh, or expose a concrete credential; those runtime
4569
5502
  * operations remain owned by the credential allocator.
4570
5503
  */
5504
+ /** Exact upstream slugs of the active Codex catalog (or the built-in fallback list). */
5505
+ export function codexUpstreamModelSlugs(settings: Settings): string[] {
5506
+ if (settings.resolvedCodexModelsJson === undefined) return [...CODEX_FALLBACK_MODEL_SLUGS];
5507
+ return z
5508
+ .array(CodexCatalogModelSchema)
5509
+ .parse(JSON.parse(settings.resolvedCodexModelsJson))
5510
+ .filter((model) => !model.retired)
5511
+ .map((model) => model.upstreamModelId);
5512
+ }
5513
+
4571
5514
  export function withCodexCatalogProvider(settings: Settings): Settings {
4572
5515
  const providers = parseModelProvidersJson(settings.modelProvidersJson);
4573
5516
  if (providers.some((provider) => provider.id === CODEX_PROVIDER_ID)) {
4574
5517
  return settings;
4575
5518
  }
5519
+ const catalogModels =
5520
+ settings.resolvedCodexModelsJson === undefined
5521
+ ? undefined
5522
+ : z
5523
+ .array(CodexCatalogModelSchema)
5524
+ .parse(JSON.parse(settings.resolvedCodexModelsJson))
5525
+ .filter((model) => !model.retired)
5526
+ .map(({ retired: _retired, ...model }) => model);
5527
+ if (catalogModels?.length === 0) return settings;
4576
5528
  const provider: RegistryProvider = {
4577
5529
  kind: "codex-subscription",
4578
5530
  id: CODEX_PROVIDER_ID,
@@ -4580,40 +5532,42 @@ export function withCodexCatalogProvider(settings: Settings): Settings {
4580
5532
  api: "responses",
4581
5533
  wireProfile: "openai",
4582
5534
  baseUrl: CODEX_PROVIDER_BASE_URL,
4583
- models: CODEX_FALLBACK_MODEL_SLUGS.map((slug) => {
4584
- const capabilities = {
4585
- ...legacyModelCapabilities(settings, {
5535
+ models:
5536
+ catalogModels ??
5537
+ CODEX_FALLBACK_MODEL_SLUGS.map((slug) => {
5538
+ const capabilities = {
5539
+ ...legacyModelCapabilities(settings, {
5540
+ reasoningEffort: true,
5541
+ hostedWebSearch: true,
5542
+ vision: isReviewedGptVisionModel(slug),
5543
+ }),
5544
+ ...(builtinPromptCachingForModel(`${CODEX_MODEL_ID_PREFIX}${slug}`)
5545
+ ? {
5546
+ promptCaching: builtinPromptCachingForModel(`${CODEX_MODEL_ID_PREFIX}${slug}`)!,
5547
+ }
5548
+ : {}),
5549
+ latencyModes: builtinLatencyModesForModel(`${CODEX_MODEL_ID_PREFIX}${slug}`),
5550
+ };
5551
+ return {
5552
+ id: `${CODEX_MODEL_ID_PREFIX}${slug}`,
5553
+ upstreamModelId: slug,
5554
+ label: productLabelForModelId(slug),
5555
+ ...(productShortLabelForModelId(slug)
5556
+ ? { shortLabel: productShortLabelForModelId(slug)! }
5557
+ : {}),
4586
5558
  reasoningEffort: true,
5559
+ // The ChatGPT/Codex Responses backend accepts the native web_search
5560
+ // hosted tool (unlike hosted apply_patch/computer transports). Declaring
5561
+ // this here makes provider resolution truthful; the worker still applies
5562
+ // the durable session/turn policy gate before attaching it.
4587
5563
  hostedWebSearch: true,
4588
- vision: slug.startsWith("gpt-5.6-") || slug === "gpt-6-astra",
4589
- }),
4590
- ...(builtinPromptCachingForModel(`${CODEX_MODEL_ID_PREFIX}${slug}`)
4591
- ? {
4592
- promptCaching: builtinPromptCachingForModel(`${CODEX_MODEL_ID_PREFIX}${slug}`)!,
4593
- }
4594
- : {}),
4595
- latencyModes: builtinLatencyModesForModel(`${CODEX_MODEL_ID_PREFIX}${slug}`),
4596
- };
4597
- return {
4598
- id: `${CODEX_MODEL_ID_PREFIX}${slug}`,
4599
- upstreamModelId: slug,
4600
- label: productLabelForModelId(slug),
4601
- ...(productShortLabelForModelId(slug)
4602
- ? { shortLabel: productShortLabelForModelId(slug)! }
4603
- : {}),
4604
- reasoningEffort: true,
4605
- // The ChatGPT/Codex Responses backend accepts the native web_search
4606
- // hosted tool (unlike hosted apply_patch/computer transports). Declaring
4607
- // this here makes provider resolution truthful; the worker still applies
4608
- // the durable session/turn policy gate before attaching it.
4609
- hostedWebSearch: true,
4610
- capabilities,
4611
- contextWindowTokens: CODEX_MODEL_CONTEXT_WINDOW_TOKENS,
4612
- effectiveContextWindowTokens: CODEX_MODEL_EFFECTIVE_CONTEXT_WINDOW_TOKENS,
4613
- autoCompactTokenLimit: CODEX_MODEL_AUTO_COMPACT_TOKEN_LIMIT,
4614
- toolOutputTruncationTokens: CODEX_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS,
4615
- };
4616
- }),
5564
+ capabilities,
5565
+ contextWindowTokens: CODEX_MODEL_CONTEXT_WINDOW_TOKENS,
5566
+ effectiveContextWindowTokens: CODEX_MODEL_EFFECTIVE_CONTEXT_WINDOW_TOKENS,
5567
+ autoCompactTokenLimit: CODEX_MODEL_AUTO_COMPACT_TOKEN_LIMIT,
5568
+ toolOutputTruncationTokens: CODEX_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS,
5569
+ };
5570
+ }),
4617
5571
  };
4618
5572
  return {
4619
5573
  ...settings,
@@ -4852,7 +5806,7 @@ export function configuredModels(
4852
5806
  reasoningEffort: true,
4853
5807
  hostedWebSearch: settings.webSearchEnabled,
4854
5808
  hostedImageGeneration: builtinHostedImageGenerationForModel(settings, id),
4855
- vision: id.startsWith("gpt-5.6-"),
5809
+ vision: isReviewedGptVisionModel(id),
4856
5810
  }),
4857
5811
  ...(builtinPromptCachingForModel(id)
4858
5812
  ? { promptCaching: builtinPromptCachingForModel(id)! }
@@ -4900,6 +5854,7 @@ export function configuredModels(
4900
5854
  id: model.id,
4901
5855
  aliases: [...(model.aliases ?? [])],
4902
5856
  label: model.label ?? productLabelForModelId(model.id),
5857
+ ...(model.logoUrl ? { logoUrl: model.logoUrl } : {}),
4903
5858
  ...(model.shortLabel
4904
5859
  ? { shortLabel: model.shortLabel }
4905
5860
  : productShortLabelForModelId(model.id)
@@ -4963,7 +5918,78 @@ export function canonicalizeConfiguredModelId(settings: Settings, modelId: strin
4963
5918
  * openai allow-list, then registry ids.
4964
5919
  */
4965
5920
  export function configuredAllowedModels(settings: Settings): string[] {
4966
- return configuredModels(settings).map((model) => model.id);
5921
+ return configuredModels(settings)
5922
+ .filter((model) => isModelAvailableForNewSelection(settings, model.id))
5923
+ .map((model) => model.id);
5924
+ }
5925
+
5926
+ /** Retirement is selection metadata, never provider authority or executable identity. */
5927
+ export function isModelAvailableForNewSelection(settings: Settings, modelId: string): boolean {
5928
+ if (!modelId.startsWith(CODEX_MODEL_ID_PREFIX) || settings.resolvedCodexModelsJson === undefined)
5929
+ return true;
5930
+ const models = z
5931
+ .array(CodexCatalogModelSchema)
5932
+ .parse(JSON.parse(settings.resolvedCodexModelsJson));
5933
+ return models.some((model) => model.id === modelId && !model.retired);
5934
+ }
5935
+
5936
+ /** Called only with the durable policy installed for a claimed accepted attempt. */
5937
+ export function settingsForAcceptedSubscriptionTurn(
5938
+ settings: Settings,
5939
+ policy: TurnExecutionPolicyV1,
5940
+ expected: {
5941
+ modelId: string;
5942
+ reasoningEffort: Settings["openaiReasoningEffort"];
5943
+ latencyMode?: LatencyMode;
5944
+ },
5945
+ ): Settings {
5946
+ const parsed = TurnExecutionPolicyV1.parse(policy);
5947
+ if (!parsed.productModelId.startsWith(CODEX_MODEL_ID_PREFIX)) return settings;
5948
+ if (!settings.codexSubscriptionEnabled) throw new Error("Codex subscription is disabled");
5949
+ const models =
5950
+ settings.resolvedCodexModelsJson === undefined
5951
+ ? []
5952
+ : z.array(CodexCatalogModelSchema).parse(JSON.parse(settings.resolvedCodexModelsJson));
5953
+ const retained = models.find((model) => model.id === parsed.productModelId && model.retired);
5954
+ if (!retained) {
5955
+ assertTurnExecutionPolicyMatchesConfigV1(settings, parsed, expected);
5956
+ return settings;
5957
+ }
5958
+ const { retired: _retired, ...model } = retained;
5959
+ // Use the existing fixed broker transport. Only this exact definition is added;
5960
+ // selection metadata remains retired in the original catalog JSON.
5961
+ const withoutCodex = {
5962
+ ...settings,
5963
+ modelProvidersJson: JSON.stringify(
5964
+ parseModelProvidersJson(settings.modelProvidersJson).filter(
5965
+ (provider) => provider.id !== CODEX_PROVIDER_ID,
5966
+ ),
5967
+ ),
5968
+ };
5969
+ const providerSettings = withCodexCatalogProvider({
5970
+ ...withoutCodex,
5971
+ resolvedCodexModelsJson: JSON.stringify([model]),
5972
+ });
5973
+ const retainedProvider = parseModelProvidersJson(providerSettings.modelProvidersJson).find(
5974
+ (provider) => provider.id === CODEX_PROVIDER_ID,
5975
+ )!;
5976
+ const providers = parseModelProvidersJson(settings.modelProvidersJson);
5977
+ const current = providers.find((provider) => provider.id === CODEX_PROVIDER_ID);
5978
+ const restored = {
5979
+ ...settings,
5980
+ modelProvidersJson: JSON.stringify([
5981
+ ...providers.filter((provider) => provider.id !== CODEX_PROVIDER_ID),
5982
+ {
5983
+ ...retainedProvider,
5984
+ models: [
5985
+ ...(current?.models ?? []).filter((candidate) => candidate.id !== model.id),
5986
+ model,
5987
+ ],
5988
+ },
5989
+ ]),
5990
+ };
5991
+ assertTurnExecutionPolicyMatchesConfigV1(restored, parsed, expected);
5992
+ return restored;
4967
5993
  }
4968
5994
 
4969
5995
  /**
@@ -5057,6 +6083,18 @@ export function resolveModelProviderForTurn(
5057
6083
  );
5058
6084
  }
5059
6085
 
6086
+ /**
6087
+ * The requested model cannot start new work: it is retired from new selection
6088
+ * or absent from the configured catalog. Callers that own a durable refusal
6089
+ * (for example a scheduled occurrence) record it instead of failing blindly.
6090
+ */
6091
+ export class TurnExecutionPolicyModelUnavailableError extends Error {
6092
+ constructor(message: string) {
6093
+ super(message);
6094
+ this.name = "TurnExecutionPolicyModelUnavailableError";
6095
+ }
6096
+ }
6097
+
5060
6098
  /**
5061
6099
  * Build a trusted, secret-safe execution policy from the normalized catalog.
5062
6100
  * The Codex overlay here contains static product/provider identity only; it
@@ -5068,9 +6106,16 @@ export function resolveTurnExecutionPolicyV1(
5068
6106
  ): TurnExecutionPolicyV1 {
5069
6107
  const catalogSettings = settingsForTurnExecutionPolicy(settings, input.modelId);
5070
6108
  const productModelId = canonicalizeConfiguredModelId(catalogSettings, input.modelId);
6109
+ if (!isModelAvailableForNewSelection(catalogSettings, productModelId)) {
6110
+ throw new TurnExecutionPolicyModelUnavailableError(
6111
+ "Turn execution policy model is retired from new selection",
6112
+ );
6113
+ }
5071
6114
  const resolved = resolveModelProvider(catalogSettings, productModelId);
5072
6115
  if (!resolved) {
5073
- throw new Error("Turn execution policy model is not present in the configured catalog");
6116
+ throw new TurnExecutionPolicyModelUnavailableError(
6117
+ "Turn execution policy model is not present in the configured catalog",
6118
+ );
5074
6119
  }
5075
6120
  if (
5076
6121
  input.requestedModelId !== null &&
@@ -5099,10 +6144,20 @@ export function resolveTurnExecutionPolicyV1(
5099
6144
  });
5100
6145
  }
5101
6146
 
6147
+ /** Explicit accepted execution identity matches, but its definition digest differs. */
6148
+ export class TurnExecutionPolicyDefinitionMismatchError extends Error {
6149
+ readonly code = "turn_execution_policy_definition_mismatch";
6150
+
6151
+ constructor() {
6152
+ super("Turn execution policy does not match the current provider definition");
6153
+ this.name = "TurnExecutionPolicyDefinitionMismatchError";
6154
+ }
6155
+ }
6156
+
5102
6157
  /**
5103
6158
  * Parse-time validation lives in @opengeni/contracts; this verifier binds a
5104
6159
  * present snapshot to the current executable definition and exact turn row.
5105
- * Any deployment/provider drift fails before a provider or compaction call.
6160
+ * Non-additive executable drift fails before a provider or compaction call.
5106
6161
  */
5107
6162
  export function assertTurnExecutionPolicyMatchesConfigV1(
5108
6163
  settings: Settings,
@@ -5142,6 +6197,39 @@ export function assertTurnExecutionPolicyMatchesConfigV1(
5142
6197
  if (!resolved) {
5143
6198
  throw new Error("Turn execution policy model is no longer configured");
5144
6199
  }
6200
+ // The individual-account cutover corrects subscription accounting labels.
6201
+ // Preserve an already accepted legacy policy only if its complete original
6202
+ // executable digest matches; this exception cannot compose with other drift.
6203
+ const legacyClaudeScope =
6204
+ resolved.provider.kind === "claude-subscription-workspace"
6205
+ ? "workspace"
6206
+ : resolved.provider.kind === "claude-subscription-organization"
6207
+ ? "organization"
6208
+ : null;
6209
+ const legacyClaudeAccountingMatches =
6210
+ legacyClaudeScope !== null &&
6211
+ parsed.providerId === resolved.provider.id &&
6212
+ parsed.upstreamModelId === resolved.model.upstreamModelId &&
6213
+ parsed.wireApi === resolved.model.api &&
6214
+ canonicalJson(parsed.credentialSource) ===
6215
+ canonicalJson({
6216
+ kind: `${legacyClaudeScope}_connection`,
6217
+ mechanism: "api_key",
6218
+ }) &&
6219
+ canonicalJson(parsed.billing) ===
6220
+ canonicalJson({
6221
+ upstreamPayer: legacyClaudeScope,
6222
+ metering: "external",
6223
+ }) &&
6224
+ parsed.definitionVersion ===
6225
+ definitionVersionFor(
6226
+ {
6227
+ ...resolved.model,
6228
+ credentialSource: parsed.credentialSource,
6229
+ billing: parsed.billing,
6230
+ },
6231
+ resolved.provider,
6232
+ );
5145
6233
  // wireProfile was added to the definition digest after policies already
5146
6234
  // existed in durable in-flight turns. An omitted profile meant exactly
5147
6235
  // "openai", so accept that one legacy digest only; Azure and every other
@@ -5152,17 +6240,24 @@ export function assertTurnExecutionPolicyMatchesConfigV1(
5152
6240
  );
5153
6241
  const definitionVersionMatches =
5154
6242
  parsed.definitionVersion === resolved.model.definitionVersion ||
5155
- parsed.definitionVersion === legacyImplicitOpenAiDefinitionVersion;
5156
- const mismatched =
6243
+ parsed.definitionVersion === legacyImplicitOpenAiDefinitionVersion ||
6244
+ parsed.definitionVersion ===
6245
+ legacyCodexAstraImplicitCachingDefinitionVersionFor(resolved.model, resolved.provider) ||
6246
+ matchesAdditiveCapabilityDefinitionVersion(resolved.model, resolved.provider, parsed);
6247
+ const identityMismatched =
5157
6248
  parsed.providerId !== resolved.provider.id ||
5158
6249
  parsed.upstreamModelId !== resolved.model.upstreamModelId ||
5159
6250
  parsed.wireApi !== resolved.model.api ||
5160
- !definitionVersionMatches ||
5161
6251
  canonicalJson(parsed.credentialSource) !== canonicalJson(resolved.model.credentialSource) ||
5162
6252
  canonicalJson(parsed.billing) !== canonicalJson(resolved.model.billing);
5163
- if (mismatched) {
6253
+ // Identity/source changes must never enter a rollout-retry classification,
6254
+ // even when their definition digest also differs.
6255
+ if (identityMismatched && !legacyClaudeAccountingMatches) {
5164
6256
  throw new Error("Turn execution policy does not match the current provider definition");
5165
6257
  }
6258
+ if (!definitionVersionMatches && !legacyClaudeAccountingMatches) {
6259
+ throw new TurnExecutionPolicyDefinitionMismatchError();
6260
+ }
5166
6261
  return { policy: parsed, provider: resolved.provider, model: resolved.model };
5167
6262
  }
5168
6263
 
@@ -5202,6 +6297,154 @@ export function configuredModelPricingSchedules(
5202
6297
  };
5203
6298
  }
5204
6299
 
6300
+ /**
6301
+ * Insights list-price metadata, including reviewed namespaced provider routes.
6302
+ * Kept separate from debit/catalog pricing: adding a comparison must not change
6303
+ * an accepted turn's frozen execution-definition hash or payer classification.
6304
+ * Inline registry and explicit product-ID prices always win over projections.
6305
+ */
6306
+ export function configuredModelListPricingSchedules(
6307
+ settings: Settings,
6308
+ ): Record<string, ModelPricingScheduleV1> {
6309
+ const prices = configuredModelPricingSchedules(settings);
6310
+ const configured = Object.fromEntries(
6311
+ Object.entries(parseModelPricingJson(settings.modelPricingJson)).map(([model, pricing]) => [
6312
+ model,
6313
+ normalizeModelPricingSchedule(pricing),
6314
+ ]),
6315
+ );
6316
+ // Bare new IDs need the actual configured public OpenAI route, not merely a
6317
+ // familiar model name. Azure/custom endpoints do not inherit these API rates.
6318
+ if (
6319
+ settings.openaiProvider === "openai" &&
6320
+ isDirectOpenAiApiBaseUrl(settings.openaiBaseUrl ?? "https://api.openai.com/v1")
6321
+ ) {
6322
+ for (const model of configuredModels(settings)) {
6323
+ if (
6324
+ model.providerId !== builtinProviderId(settings) ||
6325
+ !model.upstreamModelId.startsWith("gpt-") ||
6326
+ prices[model.id] !== undefined
6327
+ )
6328
+ continue;
6329
+ const reviewed = reviewedModelListPricing[model.upstreamModelId];
6330
+ if (reviewed) prices[model.id] = reviewed;
6331
+ }
6332
+ }
6333
+ for (const provider of configuredRegistryProviders(settings)) {
6334
+ for (const model of provider.models) {
6335
+ if (prices[model.id] !== undefined) continue;
6336
+ const reviewed = reviewedProviderModelPricing(settings, provider, model, configured);
6337
+ if (reviewed) prices[model.id] = reviewed;
6338
+ }
6339
+ }
6340
+ return prices;
6341
+ }
6342
+
6343
+ /**
6344
+ * A reviewed upstream list rate may also describe a namespaced product route.
6345
+ * Never infer a rate by stripping arbitrary prefixes, matching labels, or
6346
+ * treating every OpenAI-compatible endpoint as the original provider.
6347
+ * This is pricing metadata only: credential selection and payer/metering are
6348
+ * still derived exclusively from the accepted execution policy.
6349
+ */
6350
+ function reviewedProviderModelPricing(
6351
+ settings: Settings,
6352
+ provider: InternalRegistryProvider,
6353
+ model: RegistryProvider["models"][number],
6354
+ configured: Record<string, ModelPricingScheduleV1>,
6355
+ ): ModelPricingScheduleV1 | undefined {
6356
+ const upstream = model.upstreamModelId ?? model.id;
6357
+ let priceId: string | undefined;
6358
+ let nativeClaude = false;
6359
+ switch (provider.kind) {
6360
+ case "anonymous":
6361
+ if (
6362
+ provider.baseUrl.replace(/\/$/u, "") === OPENROUTER_BASE_URL &&
6363
+ upstream === DEFAULT_OPENROUTER_MODEL_ID.slice(OPENROUTER_MODEL_ID_PREFIX.length)
6364
+ ) {
6365
+ priceId = DEFAULT_OPENROUTER_MODEL_ID;
6366
+ }
6367
+ break;
6368
+ case "codex-subscription":
6369
+ if (upstream.startsWith("gpt-")) priceId = upstream;
6370
+ break;
6371
+ case "xai-subscription":
6372
+ if (upstream.startsWith("grok-")) priceId = upstream;
6373
+ break;
6374
+ case "anthropic-workspace":
6375
+ case "anthropic-organization":
6376
+ case "claude-subscription-workspace":
6377
+ case "claude-subscription-organization":
6378
+ if (claudeNativeModelProfile(upstream)) {
6379
+ priceId = upstream;
6380
+ nativeClaude = true;
6381
+ }
6382
+ break;
6383
+ case "direct-openai-workspace":
6384
+ if (isDirectOpenAiApiBaseUrl(provider.baseUrl) && upstream.startsWith("gpt-")) {
6385
+ priceId = upstream;
6386
+ }
6387
+ break;
6388
+ case "vercel-gateway-managed":
6389
+ case "vercel-gateway-workspace":
6390
+ case "vercel-gateway-organization":
6391
+ // Only curated, provider-pinned routes use the conservative fallback.
6392
+ // Arbitrary Gateway custom models still require exact reported cost or
6393
+ // an explicit operator rate, even if their slugs resemble a known model.
6394
+ priceId = configuredGatewayCatalogModels(settings).find(
6395
+ (candidate) =>
6396
+ candidate.upstreamModelId === upstream &&
6397
+ Object.values(OPENGENI_GATEWAY_MODELS).some(
6398
+ (reviewed) => reviewed.upstreamModelId === candidate.upstreamModelId,
6399
+ ),
6400
+ )?.productId;
6401
+ break;
6402
+ case "openrouter-workspace":
6403
+ case "openrouter-organization":
6404
+ case "openrouter-managed":
6405
+ if (upstream === DEFAULT_OPENROUTER_MODEL_ID.slice(OPENROUTER_MODEL_ID_PREFIX.length)) {
6406
+ priceId = DEFAULT_OPENROUTER_MODEL_ID;
6407
+ }
6408
+ break;
6409
+ case "api-key":
6410
+ // Explicit deployments of the official APIs may use their own product
6411
+ // IDs. Custom gateways/proxies and Azure SKUs do not inherit API rates.
6412
+ if (isDirectOpenAiApiBaseUrl(provider.baseUrl) && upstream.startsWith("gpt-")) {
6413
+ priceId = upstream;
6414
+ } else if (provider.baseUrl.replace(/\/$/u, "") === "https://api.x.ai/v1") {
6415
+ if (upstream.startsWith("grok-")) priceId = upstream;
6416
+ } else if (
6417
+ provider.api === "anthropic-messages" &&
6418
+ provider.baseUrl.replace(/\/$/u, "") === "https://api.anthropic.com/v1" &&
6419
+ claudeNativeModelProfile(upstream)
6420
+ ) {
6421
+ priceId = upstream;
6422
+ nativeClaude = true;
6423
+ }
6424
+ break;
6425
+ default:
6426
+ return undefined;
6427
+ }
6428
+ if (!priceId) return undefined;
6429
+ // Explicit upstream overrides retain the existing Codex comparison behavior;
6430
+ // a product-ID override or inline registry rate still has higher precedence.
6431
+ if (configured[priceId]) return configured[priceId];
6432
+ const schedule =
6433
+ reviewedModelListPricing[priceId] ??
6434
+ defaultModelPricing[priceId] ??
6435
+ (priceId === DEFAULT_OPENROUTER_MODEL_ID ? reviewedFreeOpenRouterListPricing : undefined);
6436
+ if (!schedule) return undefined;
6437
+ if (!nativeClaude || provider.anthropic?.cacheTtl !== "1h") return schedule;
6438
+ // Anthropic's 1-hour cache writes are 2x base input, rather than 5m's 1.25x.
6439
+ return {
6440
+ ...schedule,
6441
+ default: {
6442
+ ...schedule.default,
6443
+ cacheWriteMicrosPerMillionTokens: schedule.default.inputMicrosPerMillionTokens * 2,
6444
+ },
6445
+ };
6446
+ }
6447
+
5205
6448
  /** Legacy flat projection: returns the default/below-threshold price. */
5206
6449
  export function configuredModelPricing(settings: Settings): Record<string, ModelPricing> {
5207
6450
  return Object.fromEntries(
@@ -5318,77 +6561,385 @@ export function calculateModelUsageCostBreakdown(
5318
6561
  options?: { latencyMode?: LatencyMode },
5319
6562
  ): ModelUsageCostBreakdown {
5320
6563
  const schedule = configuredModelPricingSchedules(settings)[model];
5321
- if (!schedule) {
5322
- throw new Error(`Missing model pricing for ${model}`);
5323
- }
5324
- const entries =
5325
- usage.requestUsageEntries && usage.requestUsageEntries.length > 0
5326
- ? usage.requestUsageEntries
5327
- : [usage];
6564
+ return calculateUsageCostBreakdown(settings, model, usage, schedule, options);
6565
+ }
6566
+
6567
+ /** Provider-list/equivalent-credit comparison only; never debit authority. */
6568
+ export function calculateModelListUsageCostBreakdown(
6569
+ settings: Settings,
6570
+ model: string,
6571
+ usage: ModelUsageInput,
6572
+ options?: { latencyMode?: LatencyMode },
6573
+ ): ModelUsageCostBreakdown {
6574
+ const schedule = configuredModelListPricingSchedules(settings)[model];
6575
+ return calculateUsageCostBreakdown(settings, model, usage, schedule, options);
6576
+ }
6577
+
6578
+ /**
6579
+ * Forward-only list comparison snapshot for the model-call fact writer.
6580
+ * Callers must establish request price provenance (including geography/service
6581
+ * tier) and retain per-request counters. Unknown counters/TTL/modifiers yield
6582
+ * no class split, not invented zeros. Historical facts must not use this helper.
6583
+ * Native Claude details preserve cache_write_tokens_5m and cache_write_tokens_1h.
6584
+ */
6585
+ export function calculateModelListUsageCostSnapshot(
6586
+ settings: Settings,
6587
+ model: string,
6588
+ usage: ModelUsageInput,
6589
+ options?: { latencyMode?: LatencyMode; priceContextKnown?: boolean },
6590
+ ): ModelListUsageCostSnapshot {
6591
+ const schedule = configuredModelListPricingSchedules(settings)[model];
6592
+ const fallback = calculateUsageCostBreakdown(settings, model, usage, schedule, options);
6593
+ const unknown = { ...fallback, listByClassMicros: null, listByClassApprox: false };
6594
+ if (!schedule || !options?.priceContextKnown) return unknown;
6595
+ const entries = usage.requestUsageEntries?.length ? usage.requestUsageEntries : [usage];
6596
+ const classes: ModelListCostClassesMicros = {
6597
+ uncachedInput: 0,
6598
+ cacheRead: 0,
6599
+ cacheWrite: 0,
6600
+ output: 0,
6601
+ };
5328
6602
  const rawCostByPricing = new Map<ModelPricing, number>();
6603
+ const native = nativeClaudeListWriteContext(settings, model);
5329
6604
  for (const entry of entries) {
5330
- const pricing = selectModelPricing(schedule, positiveInt(entry.inputTokens));
5331
- rawCostByPricing.set(
5332
- pricing,
5333
- (rawCostByPricing.get(pricing) ?? 0) + calculateEntryCostMicros(pricing, entry),
5334
- );
6605
+ if (!knownTokenCounter(entry.inputTokens) || !knownTokenCounter(entry.outputTokens))
6606
+ return unknown;
6607
+ const cached = knownDetailTokenCounter(entry, [
6608
+ "cached_tokens",
6609
+ "cachedInputTokens",
6610
+ "cached_input_tokens",
6611
+ ]);
6612
+ const writes = knownDetailTokenCounter(entry, ["cache_write_tokens", "cacheWriteTokens"], true);
6613
+ if (cached === undefined || writes === undefined || cached + writes > entry.inputTokens)
6614
+ return unknown;
6615
+ const pricing = selectModelPricing(schedule, entry.inputTokens);
6616
+ if (cached > 0 && pricing.cachedInputMicrosPerMillionTokens === undefined) return unknown;
6617
+ if (writes > 0 && pricing.cacheWriteMicrosPerMillionTokens === undefined) return unknown;
6618
+ const costs: ModelListCostClassesMicros = {
6619
+ uncachedInput: Math.ceil(
6620
+ ((entry.inputTokens - cached - writes) * pricing.inputMicrosPerMillionTokens) / 1_000_000,
6621
+ ),
6622
+ cacheRead: Math.ceil((cached * (pricing.cachedInputMicrosPerMillionTokens ?? 0)) / 1_000_000),
6623
+ cacheWrite: Math.ceil((writes * (pricing.cacheWriteMicrosPerMillionTokens ?? 0)) / 1_000_000),
6624
+ output: Math.ceil((entry.outputTokens * pricing.outputMicrosPerMillionTokens) / 1_000_000),
6625
+ };
6626
+ if (native && writes > 0) {
6627
+ const fiveMinute = knownDetailTokenCounter(entry, ["cache_write_tokens_5m"]);
6628
+ const oneHour = knownDetailTokenCounter(entry, ["cache_write_tokens_1h"]);
6629
+ if (fiveMinute === undefined || oneHour === undefined || fiveMinute + oneHour !== writes)
6630
+ return unknown;
6631
+ if (native.publishedRates) {
6632
+ costs.cacheWrite =
6633
+ Math.ceil((fiveMinute * native.publishedRates.fiveMinute) / 1_000_000) +
6634
+ Math.ceil((oneHour * native.publishedRates.oneHour) / 1_000_000);
6635
+ } else if (
6636
+ !(
6637
+ (native.declaredTtl === "5m" && oneHour === 0) ||
6638
+ (native.declaredTtl === "1h" && fiveMinute === 0)
6639
+ )
6640
+ ) {
6641
+ // A single explicit override cannot establish two different TTL prices.
6642
+ return unknown;
6643
+ }
6644
+ }
6645
+ const raw = sumListCostClasses(costs);
6646
+ rawCostByPricing.set(pricing, (rawCostByPricing.get(pricing) ?? 0) + raw);
6647
+ for (const key of MODEL_LIST_COST_CLASS_KEYS) classes[key] += costs[key];
5335
6648
  }
5336
- let providerCostMicros = 0;
6649
+ let providerCostMicros = sumListCostClasses(classes);
5337
6650
  let creditCostMicros = 0;
5338
- for (const [pricing, rawCost] of rawCostByPricing) {
5339
- const marginBps = pricing.marginBps ?? 0;
5340
- providerCostMicros += rawCost;
5341
- creditCostMicros += Math.ceil((rawCost * (10_000 + marginBps)) / 10_000);
6651
+ for (const [pricing, raw] of rawCostByPricing) {
6652
+ creditCostMicros += Math.ceil((raw * (10_000 + (pricing.marginBps ?? 0))) / 10_000);
5342
6653
  }
5343
- const latencyMode = options?.latencyMode ?? "standard";
6654
+ let listByClassApprox = false;
6655
+ const latencyMode = options.latencyMode ?? "standard";
5344
6656
  if (latencyMode !== "standard") {
5345
6657
  const catalogSettings = settingsForTurnExecutionPolicy(settings, model);
5346
6658
  const resolved = resolveModelProvider(
5347
6659
  catalogSettings,
5348
6660
  canonicalizeConfiguredModelId(catalogSettings, model),
5349
6661
  );
5350
- const multiplierBps = resolved?.model.capabilities.latencyModes.find(
6662
+ const multiplier = resolved?.model.capabilities.latencyModes.find(
5351
6663
  (mode) => mode.id === latencyMode && mode.runnable,
5352
6664
  )?.billingMultiplierBps;
5353
- if (multiplierBps && multiplierBps > 0) {
5354
- providerCostMicros = Math.ceil((providerCostMicros * multiplierBps) / 10_000);
5355
- creditCostMicros = Math.ceil((creditCostMicros * multiplierBps) / 10_000);
5356
- }
6665
+ if (multiplier === undefined || multiplier <= 0) return unknown;
6666
+ providerCostMicros = Math.ceil((providerCostMicros * multiplier) / 10_000);
6667
+ creditCostMicros = Math.ceil((creditCostMicros * multiplier) / 10_000);
6668
+ const scaled = allocateLatencyListCostClasses(classes, multiplier, providerCostMicros);
6669
+ if (!scaled) return unknown;
6670
+ Object.assign(classes, scaled.classes);
6671
+ listByClassApprox = scaled.approximate;
5357
6672
  }
5358
- return { providerCostMicros, creditCostMicros };
6673
+ if (![providerCostMicros, creditCostMicros, ...Object.values(classes)].every(knownTokenCounter))
6674
+ return unknown;
6675
+ return { providerCostMicros, creditCostMicros, listByClassMicros: classes, listByClassApprox };
5359
6676
  }
5360
6677
 
5361
6678
  /**
5362
- * Convert AI Gateway's exact USD inference cost to OpenGeni credit micros and
5363
- * apply the configured model margin. Decimal arithmetic is integer-only so a
5364
- * sub-micro provider charge cannot be lost to floating-point rounding.
6679
+ * Approximate class attribution of a previously recorded upstream list total.
6680
+ * Current reviewed rates are weights only: this never recomputes that total,
6681
+ * credits, or charges. Missing class counters/rates remain unknown. Historical
6682
+ * cache writes use the schedule's single TTL rate, not an exact TTL assertion.
6683
+ * Reasoning is already included in outputTokens and is never added again.
5365
6684
  */
5366
- export function calculateGatewayReportedCostMicros(
6685
+ export function allocateRecordedModelListCostByClass(
5367
6686
  settings: Settings,
5368
6687
  model: string,
5369
- inferenceCostUsd: string,
5370
- options?: { inputTokens?: number },
5371
- ): number {
5372
- return calculateGatewayReportedCostBreakdown(settings, model, inferenceCostUsd, options)
5373
- .creditCostMicros;
6688
+ usage: ModelUsageInput,
6689
+ recordedProviderCostMicros: number | null | undefined,
6690
+ ): ModelRecordedListCostAllocation {
6691
+ const unknown: ModelRecordedListCostAllocation = {
6692
+ listByClassMicros: null,
6693
+ listByClassApprox: false,
6694
+ };
6695
+ if (!knownTokenCounter(recordedProviderCostMicros)) return unknown;
6696
+ const schedule = configuredModelListPricingSchedules(settings)[model];
6697
+ if (!schedule) return unknown;
6698
+ const weights = { uncachedInput: 0n, cacheRead: 0n, cacheWrite: 0n, output: 0n };
6699
+ const entries = usage.requestUsageEntries?.length ? usage.requestUsageEntries : [usage];
6700
+ for (const entry of entries) {
6701
+ if (!knownTokenCounter(entry.inputTokens) || !knownTokenCounter(entry.outputTokens))
6702
+ return unknown;
6703
+ const cached = knownDetailTokenCounter(entry, [
6704
+ "cached_tokens",
6705
+ "cachedInputTokens",
6706
+ "cached_input_tokens",
6707
+ ]);
6708
+ const writes = knownDetailTokenCounter(entry, ["cache_write_tokens", "cacheWriteTokens"], true);
6709
+ if (cached === undefined || writes === undefined || cached + writes > entry.inputTokens)
6710
+ return unknown;
6711
+ const pricing = selectModelPricing(schedule, entry.inputTokens);
6712
+ const counters = {
6713
+ uncachedInput: entry.inputTokens - cached - writes,
6714
+ cacheRead: cached,
6715
+ cacheWrite: writes,
6716
+ output: entry.outputTokens,
6717
+ };
6718
+ const rates = {
6719
+ uncachedInput: pricing.inputMicrosPerMillionTokens,
6720
+ cacheRead: pricing.cachedInputMicrosPerMillionTokens,
6721
+ cacheWrite: pricing.cacheWriteMicrosPerMillionTokens,
6722
+ output: pricing.outputMicrosPerMillionTokens,
6723
+ };
6724
+ for (const key of MODEL_LIST_COST_CLASS_KEYS) {
6725
+ if (counters[key] === 0) continue;
6726
+ const rate = rates[key];
6727
+ if (!knownTokenCounter(rate)) return unknown;
6728
+ // Do not round or convert weights to Number: both can distort ratios.
6729
+ weights[key] += BigInt(counters[key]) * BigInt(rate);
6730
+ }
6731
+ }
6732
+ const classes = allocateRecordedListCostWeights(weights, recordedProviderCostMicros);
6733
+ return classes ? { listByClassMicros: classes, listByClassApprox: true } : unknown;
5374
6734
  }
5375
6735
 
5376
- type GatewayReportedCostDecimal = {
5377
- providerNumerator: bigint;
5378
- decimalScale: bigint;
5379
- providerCostMicros: number;
5380
- };
6736
+ const MODEL_LIST_COST_CLASS_KEYS = ["uncachedInput", "cacheRead", "cacheWrite", "output"] as const;
5381
6737
 
5382
- function parseGatewayReportedCostDecimal(inferenceCostUsd: string): GatewayReportedCostDecimal {
5383
- const match = /^(0|[1-9]\d*)(?:\.(\d{1,18}))?$/.exec(inferenceCostUsd);
5384
- if (!match) {
5385
- throw new Error("Invalid AI Gateway inference cost");
6738
+ function sumListCostClasses(costs: ModelListCostClassesMicros): number {
6739
+ return MODEL_LIST_COST_CLASS_KEYS.reduce((total, key) => total + costs[key], 0);
6740
+ }
6741
+
6742
+ /** Integer-only largest remainder, preserving the supplied historical total. */
6743
+ function allocateRecordedListCostWeights(
6744
+ weights: Record<(typeof MODEL_LIST_COST_CLASS_KEYS)[number], bigint>,
6745
+ target: number,
6746
+ ): ModelListCostClassesMicros | undefined {
6747
+ const denominator = MODEL_LIST_COST_CLASS_KEYS.reduce((total, key) => total + weights[key], 0n);
6748
+ if (denominator === 0n) {
6749
+ return target === 0 ? { uncachedInput: 0, cacheRead: 0, cacheWrite: 0, output: 0 } : undefined;
5386
6750
  }
5387
- const fraction = match[2] ?? "";
5388
- const decimalDigits = BigInt(`${match[1]}${fraction}`);
5389
- const decimalScale = 10n ** BigInt(fraction.length);
5390
- const providerNumerator = decimalDigits * 1_000_000n;
5391
- const providerCostMicros = (providerNumerator + decimalScale - 1n) / decimalScale;
6751
+ const rows = MODEL_LIST_COST_CLASS_KEYS.map((key, index) => {
6752
+ const numerator = BigInt(target) * weights[key];
6753
+ return { key, index, value: numerator / denominator, remainder: numerator % denominator };
6754
+ });
6755
+ const remaining = BigInt(target) - rows.reduce((total, row) => total + row.value, 0n);
6756
+ const ranked = [...rows].sort((a, b) =>
6757
+ a.remainder === b.remainder ? a.index - b.index : a.remainder > b.remainder ? -1 : 1,
6758
+ );
6759
+ for (let index = 0; index < Number(remaining); index++) ranked[index]!.value += 1n;
6760
+ return Object.fromEntries(
6761
+ rows.map((row) => [row.key, Number(row.value)]),
6762
+ ) as ModelListCostClassesMicros;
6763
+ }
6764
+
6765
+ function knownTokenCounter(value: unknown): value is number {
6766
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
6767
+ }
6768
+
6769
+ function knownDetailTokenCounter(
6770
+ entry: ModelUsageInput,
6771
+ keys: readonly string[],
6772
+ firstOnly = false,
6773
+ ): number | undefined {
6774
+ const details = Array.isArray(entry.inputTokensDetails)
6775
+ ? entry.inputTokensDetails
6776
+ : entry.inputTokensDetails
6777
+ ? [entry.inputTokensDetails]
6778
+ : [];
6779
+ if (details.length === 0) return undefined;
6780
+ let total = 0;
6781
+ for (const detail of details) {
6782
+ const present = keys.filter((key) => detail[key] !== undefined);
6783
+ if (present.length === 0) return undefined;
6784
+ for (const key of firstOnly ? present.slice(0, 1) : present) {
6785
+ if (!knownTokenCounter(detail[key])) return undefined;
6786
+ total += detail[key]!;
6787
+ }
6788
+ }
6789
+ return knownTokenCounter(total) ? total : undefined;
6790
+ }
6791
+
6792
+ function nativeClaudeListWriteContext(
6793
+ settings: Settings,
6794
+ modelId: string,
6795
+ ):
6796
+ | {
6797
+ declaredTtl: "off" | "5m" | "1h" | undefined;
6798
+ publishedRates?: { fiveMinute: number; oneHour: number };
6799
+ }
6800
+ | undefined {
6801
+ for (const provider of configuredRegistryProviders(settings)) {
6802
+ const model = provider.models.find((candidate) => candidate.id === modelId);
6803
+ if (!model || provider.api !== "anthropic-messages") continue;
6804
+ const result = { declaredTtl: provider.anthropic?.cacheTtl };
6805
+ const upstream = model.upstreamModelId ?? model.id;
6806
+ const overrides = parseModelPricingJson(settings.modelPricingJson);
6807
+ const official =
6808
+ provider.kind === "anthropic-workspace" ||
6809
+ provider.kind === "anthropic-organization" ||
6810
+ provider.kind === "claude-subscription-workspace" ||
6811
+ provider.kind === "claude-subscription-organization" ||
6812
+ (provider.kind === "api-key" &&
6813
+ provider.baseUrl.replace(/\/$/u, "") === "https://api.anthropic.com/v1");
6814
+ const published = reviewedModelListPricing[upstream]?.default;
6815
+ if (
6816
+ !official ||
6817
+ !claudeNativeModelProfile(upstream) ||
6818
+ !published?.cacheWriteMicrosPerMillionTokens ||
6819
+ model.pricing ||
6820
+ overrides[modelId] !== undefined ||
6821
+ overrides[upstream] !== undefined
6822
+ )
6823
+ return result;
6824
+ return {
6825
+ ...result,
6826
+ publishedRates: {
6827
+ fiveMinute: published.cacheWriteMicrosPerMillionTokens,
6828
+ oneHour: published.inputMicrosPerMillionTokens * 2,
6829
+ },
6830
+ };
6831
+ }
6832
+ return undefined;
6833
+ }
6834
+
6835
+ /** Deterministic largest-remainder allocation; disclose any fractional scaling. */
6836
+ function allocateLatencyListCostClasses(
6837
+ classes: ModelListCostClassesMicros,
6838
+ multiplier: number,
6839
+ target: number,
6840
+ ): { classes: ModelListCostClassesMicros; approximate: boolean } | undefined {
6841
+ if (
6842
+ !knownTokenCounter(multiplier) ||
6843
+ !knownTokenCounter(target) ||
6844
+ !Object.values(classes).every(knownTokenCounter)
6845
+ )
6846
+ return undefined;
6847
+ const rows = MODEL_LIST_COST_CLASS_KEYS.map((key, index) => {
6848
+ const numerator = BigInt(classes[key]) * BigInt(multiplier);
6849
+ return { key, index, value: Number(numerator / 10_000n), remainder: numerator % 10_000n };
6850
+ });
6851
+ const remaining = target - rows.reduce((total, row) => total + row.value, 0);
6852
+ if (remaining < 0 || remaining > rows.length) return undefined;
6853
+ const ranked = [...rows].sort((a, b) =>
6854
+ a.remainder === b.remainder ? a.index - b.index : a.remainder > b.remainder ? -1 : 1,
6855
+ );
6856
+ for (let index = 0; index < remaining; index++) ranked[index]!.value += 1;
6857
+ return {
6858
+ classes: Object.fromEntries(
6859
+ rows.map((row) => [row.key, row.value]),
6860
+ ) as ModelListCostClassesMicros,
6861
+ approximate: rows.some((row) => row.remainder !== 0n),
6862
+ };
6863
+ }
6864
+
6865
+ function calculateUsageCostBreakdown(
6866
+ settings: Settings,
6867
+ model: string,
6868
+ usage: ModelUsageInput,
6869
+ schedule: ModelPricingScheduleV1 | undefined,
6870
+ options?: { latencyMode?: LatencyMode },
6871
+ ): ModelUsageCostBreakdown {
6872
+ if (!schedule) {
6873
+ throw new Error(`Missing model pricing for ${model}`);
6874
+ }
6875
+ const entries =
6876
+ usage.requestUsageEntries && usage.requestUsageEntries.length > 0
6877
+ ? usage.requestUsageEntries
6878
+ : [usage];
6879
+ const rawCostByPricing = new Map<ModelPricing, number>();
6880
+ for (const entry of entries) {
6881
+ const pricing = selectModelPricing(schedule, positiveInt(entry.inputTokens));
6882
+ rawCostByPricing.set(
6883
+ pricing,
6884
+ (rawCostByPricing.get(pricing) ?? 0) + calculateEntryCostMicros(pricing, entry),
6885
+ );
6886
+ }
6887
+ let providerCostMicros = 0;
6888
+ let creditCostMicros = 0;
6889
+ for (const [pricing, rawCost] of rawCostByPricing) {
6890
+ const marginBps = pricing.marginBps ?? 0;
6891
+ providerCostMicros += rawCost;
6892
+ creditCostMicros += Math.ceil((rawCost * (10_000 + marginBps)) / 10_000);
6893
+ }
6894
+ const latencyMode = options?.latencyMode ?? "standard";
6895
+ if (latencyMode !== "standard") {
6896
+ const catalogSettings = settingsForTurnExecutionPolicy(settings, model);
6897
+ const resolved = resolveModelProvider(
6898
+ catalogSettings,
6899
+ canonicalizeConfiguredModelId(catalogSettings, model),
6900
+ );
6901
+ const multiplierBps = resolved?.model.capabilities.latencyModes.find(
6902
+ (mode) => mode.id === latencyMode && mode.runnable,
6903
+ )?.billingMultiplierBps;
6904
+ if (multiplierBps && multiplierBps > 0) {
6905
+ providerCostMicros = Math.ceil((providerCostMicros * multiplierBps) / 10_000);
6906
+ creditCostMicros = Math.ceil((creditCostMicros * multiplierBps) / 10_000);
6907
+ }
6908
+ }
6909
+ return { providerCostMicros, creditCostMicros };
6910
+ }
6911
+
6912
+ /**
6913
+ * Convert AI Gateway's exact USD inference cost to OpenGeni credit micros and
6914
+ * apply the configured model margin. Decimal arithmetic is integer-only so a
6915
+ * sub-micro provider charge cannot be lost to floating-point rounding.
6916
+ */
6917
+ export function calculateGatewayReportedCostMicros(
6918
+ settings: Settings,
6919
+ model: string,
6920
+ inferenceCostUsd: string,
6921
+ options?: { inputTokens?: number },
6922
+ ): number {
6923
+ return calculateGatewayReportedCostBreakdown(settings, model, inferenceCostUsd, options)
6924
+ .creditCostMicros;
6925
+ }
6926
+
6927
+ type GatewayReportedCostDecimal = {
6928
+ providerNumerator: bigint;
6929
+ decimalScale: bigint;
6930
+ providerCostMicros: number;
6931
+ };
6932
+
6933
+ function parseGatewayReportedCostDecimal(inferenceCostUsd: string): GatewayReportedCostDecimal {
6934
+ const match = /^(0|[1-9]\d*)(?:\.(\d{1,18}))?$/.exec(inferenceCostUsd);
6935
+ if (!match) {
6936
+ throw new Error("Invalid AI Gateway inference cost");
6937
+ }
6938
+ const fraction = match[2] ?? "";
6939
+ const decimalDigits = BigInt(`${match[1]}${fraction}`);
6940
+ const decimalScale = 10n ** BigInt(fraction.length);
6941
+ const providerNumerator = decimalDigits * 1_000_000n;
6942
+ const providerCostMicros = (providerNumerator + decimalScale - 1n) / decimalScale;
5392
6943
  if (providerCostMicros > BigInt(Number.MAX_SAFE_INTEGER)) {
5393
6944
  throw new Error("AI Gateway inference cost exceeds the supported billing range");
5394
6945
  }
@@ -5764,6 +7315,7 @@ export function applyGitAuthPointerEnvironment(
5764
7315
  }
5765
7316
 
5766
7317
  export type StartupRetryOptions = {
7318
+ shouldRetry?: (error: unknown) => boolean;
5767
7319
  attempts?: number;
5768
7320
  initialDelayMs?: number;
5769
7321
  maxDelayMs?: number;
@@ -5778,7 +7330,7 @@ export type StartupRetryOptions = {
5778
7330
 
5779
7331
  export function startupRetryOptions(
5780
7332
  settings: Settings,
5781
- ): Required<Omit<StartupRetryOptions, "onRetry">> {
7333
+ ): Required<Omit<StartupRetryOptions, "onRetry" | "shouldRetry">> {
5782
7334
  return {
5783
7335
  attempts: settings.startupDependencyRetryAttempts,
5784
7336
  initialDelayMs: settings.startupDependencyRetryInitialDelayMs,
@@ -5798,7 +7350,7 @@ export async function retryStartupDependency<T>(
5798
7350
  try {
5799
7351
  return await operation();
5800
7352
  } catch (error) {
5801
- if (attempt >= attempts) {
7353
+ if (attempt >= attempts || options.shouldRetry?.(error) === false) {
5802
7354
  throw error;
5803
7355
  }
5804
7356
  const delayMs = Math.min(maxDelayMs, initialDelayMs * 2 ** (attempt - 1));
@@ -6310,8 +7862,99 @@ function isDigestPinnedModalDesktopImage(settings: Settings): boolean {
6310
7862
  );
6311
7863
  }
6312
7864
 
7865
+ export type TrustedProxyCidr = {
7866
+ address: string;
7867
+ prefix: number;
7868
+ family: "ipv4" | "ipv6";
7869
+ };
7870
+
7871
+ /**
7872
+ * Parse `OPENGENI_API_TRUSTED_PROXY_CIDRS`: comma-separated IPv4/IPv6 CIDRs or
7873
+ * single addresses. Throws on any malformed entry so a typo can never widen or
7874
+ * silently disable the trusted proxy set.
7875
+ */
7876
+ export function trustedProxyCidrEntries(raw: string): TrustedProxyCidr[] {
7877
+ const entries: TrustedProxyCidr[] = [];
7878
+ for (const entry of raw.split(",")) {
7879
+ const value = entry.trim();
7880
+ if (!value) continue;
7881
+ const slash = value.indexOf("/");
7882
+ const address = slash < 0 ? value : value.slice(0, slash);
7883
+ const version = isIP(address);
7884
+ const family = version === 4 ? "ipv4" : version === 6 ? "ipv6" : null;
7885
+ const maxPrefix = family === "ipv4" ? 32 : 128;
7886
+ const prefixText = slash < 0 ? String(maxPrefix) : value.slice(slash + 1);
7887
+ const prefix = /^\d{1,3}$/u.test(prefixText) ? Number(prefixText) : Number.NaN;
7888
+ if (!family || !Number.isInteger(prefix) || prefix < 0 || prefix > maxPrefix) {
7889
+ throw new Error(
7890
+ `OPENGENI_API_TRUSTED_PROXY_CIDRS entry "${value.slice(0, 64)}" is not an IP address or CIDR range`,
7891
+ );
7892
+ }
7893
+ entries.push({ address, prefix, family });
7894
+ }
7895
+ return entries;
7896
+ }
7897
+
7898
+ /**
7899
+ * Parse `OPENGENI_LOCAL_ALLOWED_ORIGINS`: comma-separated exact browser origins
7900
+ * (`http(s)://host[:port]`, no path, query, credentials, or wildcard). Throws on
7901
+ * any malformed entry so a typo can never widen or silently disable the local
7902
+ * browser boundary.
7903
+ */
7904
+ export function localAllowedOriginEntries(raw: string | undefined): string[] {
7905
+ const origins: string[] = [];
7906
+ for (const entry of (raw ?? "").split(",")) {
7907
+ const value = entry.trim();
7908
+ if (!value) continue;
7909
+ let url: URL | null = null;
7910
+ try {
7911
+ url = new URL(value);
7912
+ } catch {
7913
+ url = null;
7914
+ }
7915
+ if (
7916
+ !url ||
7917
+ (url.protocol !== "http:" && url.protocol !== "https:") ||
7918
+ url.username ||
7919
+ url.password ||
7920
+ url.hostname.includes("*") ||
7921
+ url.pathname !== "/" ||
7922
+ url.search ||
7923
+ url.hash ||
7924
+ value.endsWith("?") ||
7925
+ value.endsWith("#")
7926
+ ) {
7927
+ throw new Error(
7928
+ `OPENGENI_LOCAL_ALLOWED_ORIGINS entry "${value.slice(0, 64)}" is not an exact http(s) origin such as http://127.0.0.1:5173`,
7929
+ );
7930
+ }
7931
+ origins.push(url.origin);
7932
+ }
7933
+ return origins;
7934
+ }
7935
+
7936
+ const LOCAL_SANDBOX_API_ROUTES: readonly RegExp[] = [
7937
+ // Codemode calls, journal reads, catalog, and the Site/SDK proxy.
7938
+ /^\/v1\/workspaces\/[^/]+\/codemode(?:\/|$)/u,
7939
+ // First-party MCP, including its /docs and /files servers.
7940
+ /^\/v1\/workspaces\/[^/]+\/mcp(?:\/|$)/u,
7941
+ // The personal GitHub HTTPS smart-Git broker.
7942
+ /^\/v1\/git\/personal\/[A-Za-z0-9_-]{43}\/(?:info\/refs|git-upload-pack|git-receive-pack)$/u,
7943
+ ];
7944
+
7945
+ /**
7946
+ * Local development only: whether a normalized API path is one a sandbox calls
7947
+ * (Codemode, first-party MCP, and the personal Git broker). The Linux Docker
7948
+ * sandbox route relays only these, and the local API serves only these on the
7949
+ * addresses that only sandboxes use (see `apps/api/src/http/local-browser-boundary.ts`).
7950
+ */
7951
+ export function localSandboxApiRouteAllowed(pathname: string): boolean {
7952
+ return LOCAL_SANDBOX_API_ROUTES.some((route) => route.test(pathname));
7953
+ }
7954
+
6313
7955
  function validateSettings(settings: Settings, source: NodeJS.ProcessEnv = process.env): void {
6314
7956
  temporalConnectionOptions(settings);
7957
+ localAllowedOriginEntries(settings.localAllowedOrigins);
6315
7958
  if (
6316
7959
  settings.organizationUserSetupEmailTokenTransport === "query" &&
6317
7960
  !settings.organizationUserSetupQueryEdgeSanitizationConfirmed
@@ -6405,6 +8048,21 @@ function validateSettings(settings: Settings, source: NodeJS.ProcessEnv = proces
6405
8048
  );
6406
8049
  }
6407
8050
  }
8051
+ // The retired MCP-only name must never be ignored silently: a deployment
8052
+ // that trusted forwarded addresses would fall back to the transport peer.
8053
+ // "0" (the old .env.example value) means the same as the new default.
8054
+ const retiredTrustedProxyHops = source.OPENGENI_MCP_OAUTH_TRUSTED_PROXY_HOPS?.trim();
8055
+ if (retiredTrustedProxyHops && retiredTrustedProxyHops !== "0") {
8056
+ throw new Error(
8057
+ "OPENGENI_MCP_OAUTH_TRUSTED_PROXY_HOPS was renamed to OPENGENI_API_TRUSTED_PROXY_HOPS, which now sets the client address for every API rate limit and auth session; rename the variable",
8058
+ );
8059
+ }
8060
+ const trustedProxyCidrs = trustedProxyCidrEntries(settings.apiTrustedProxyCidrs);
8061
+ if (trustedProxyCidrs.length > 0 && settings.apiTrustedProxyHops === 0) {
8062
+ throw new Error(
8063
+ "OPENGENI_API_TRUSTED_PROXY_CIDRS requires OPENGENI_API_TRUSTED_PROXY_HOPS greater than 0",
8064
+ );
8065
+ }
6408
8066
  if (settings.mcpOauthEnabled) {
6409
8067
  if (settings.productAccessMode === "configured") {
6410
8068
  throw new Error(
@@ -6705,105 +8363,7 @@ function validateSettings(settings: Settings, source: NodeJS.ProcessEnv = proces
6705
8363
  );
6706
8364
  }
6707
8365
  }
6708
- if (
6709
- settings.objectStorageBackend === "s3-compatible" ||
6710
- settings.objectStorageBackend === "aws-s3"
6711
- ) {
6712
- if (
6713
- Boolean(settings.objectStorageAccessKeyId) !== Boolean(settings.objectStorageSecretAccessKey)
6714
- ) {
6715
- throw new Error(
6716
- "OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID and OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY must both be set or both omitted",
6717
- );
6718
- }
6719
- if (
6720
- settings.objectStorageBackend === "s3-compatible" &&
6721
- (settings.objectStorageEndpoint ||
6722
- settings.objectStorageInternalEndpoint ||
6723
- settings.objectStorageSandboxEndpoint) &&
6724
- (!settings.objectStorageAccessKeyId || !settings.objectStorageSecretAccessKey)
6725
- ) {
6726
- throw new Error(
6727
- "S3-compatible object storage endpoints require OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID and OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY",
6728
- );
6729
- }
6730
- if (
6731
- settings.objectStorageAzureConnectionString ||
6732
- settings.objectStorageAzureAccountName ||
6733
- settings.objectStorageAzureAccountKey ||
6734
- settings.objectStorageAzureEndpoint
6735
- ) {
6736
- throw new Error(
6737
- "S3 object storage uses OPENGENI_OBJECT_STORAGE_* S3 settings, not OPENGENI_OBJECT_STORAGE_AZURE_* settings",
6738
- );
6739
- }
6740
- if (
6741
- settings.objectStorageGcsProjectId ||
6742
- settings.objectStorageGcsCredentialsJson ||
6743
- settings.objectStorageGcsKeyFilename ||
6744
- settings.objectStorageGcsApiEndpoint
6745
- ) {
6746
- throw new Error(
6747
- "S3 object storage uses OPENGENI_OBJECT_STORAGE_* S3 settings, not OPENGENI_OBJECT_STORAGE_GCS_* settings",
6748
- );
6749
- }
6750
- } else if (settings.objectStorageBackend === "azure-blob") {
6751
- if (
6752
- settings.objectStorageEndpoint ||
6753
- settings.objectStorageInternalEndpoint ||
6754
- settings.objectStorageSandboxEndpoint ||
6755
- settings.objectStorageAccessKeyId ||
6756
- settings.objectStorageSecretAccessKey
6757
- ) {
6758
- throw new Error(
6759
- "Azure Blob storage uses OPENGENI_OBJECT_STORAGE_AZURE_* settings, not S3-compatible object storage settings",
6760
- );
6761
- }
6762
- if (
6763
- settings.objectStorageGcsProjectId ||
6764
- settings.objectStorageGcsCredentialsJson ||
6765
- settings.objectStorageGcsKeyFilename ||
6766
- settings.objectStorageGcsApiEndpoint
6767
- ) {
6768
- throw new Error(
6769
- "Azure Blob storage uses OPENGENI_OBJECT_STORAGE_AZURE_* settings, not OPENGENI_OBJECT_STORAGE_GCS_* settings",
6770
- );
6771
- }
6772
- const hasConnectionString = Boolean(settings.objectStorageAzureConnectionString);
6773
- const hasSharedKey =
6774
- Boolean(settings.objectStorageAzureAccountName) &&
6775
- Boolean(settings.objectStorageAzureAccountKey);
6776
- if (!hasConnectionString && !hasSharedKey) {
6777
- throw new Error(
6778
- "Azure Blob storage requires OPENGENI_OBJECT_STORAGE_AZURE_CONNECTION_STRING or OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_NAME plus OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_KEY",
6779
- );
6780
- }
6781
- } else {
6782
- if (
6783
- settings.objectStorageEndpoint ||
6784
- settings.objectStorageInternalEndpoint ||
6785
- settings.objectStorageSandboxEndpoint ||
6786
- settings.objectStorageAccessKeyId ||
6787
- settings.objectStorageSecretAccessKey
6788
- ) {
6789
- throw new Error(
6790
- "GCS object storage uses OPENGENI_OBJECT_STORAGE_GCS_* settings, not S3-compatible object storage settings",
6791
- );
6792
- }
6793
- if (
6794
- settings.objectStorageAzureConnectionString ||
6795
- settings.objectStorageAzureAccountName ||
6796
- settings.objectStorageAzureAccountKey ||
6797
- settings.objectStorageAzureEndpoint
6798
- ) {
6799
- throw new Error(
6800
- "GCS object storage uses OPENGENI_OBJECT_STORAGE_GCS_* settings, not OPENGENI_OBJECT_STORAGE_AZURE_* settings",
6801
- );
6802
- }
6803
- if (settings.objectStorageGcsCredentialsJson) {
6804
- parseGcsCredentialsJson(settings.objectStorageGcsCredentialsJson);
6805
- }
6806
- }
8366
+ validateObjectStorageSettings(settings);
6807
8367
  if (settings.documentChunkOverlap >= settings.documentChunkSize) {
6808
8368
  throw new Error(
6809
8369
  "OPENGENI_DOCUMENT_CHUNK_OVERLAP must be smaller than OPENGENI_DOCUMENT_CHUNK_SIZE",
@@ -6813,7 +8373,36 @@ function validateSettings(settings: Settings, source: NodeJS.ProcessEnv = proces
6813
8373
  sandboxEnvironmentVariableNames(settings);
6814
8374
  sandboxLifecycleHookIds(settings);
6815
8375
  // Fail fast on a malformed warm-rate table (P2.1).
6816
- parseSandboxWarmRateJson(settings.sandboxWarmRateMicrosPerSecondJson);
8376
+ const warmRates = parseSandboxWarmRateJson(settings.sandboxWarmRateMicrosPerSecondJson);
8377
+ // The meter rounds each settled interval to whole USD micros. Fractional
8378
+ // micros/second would make the total depend on heartbeat frequency; only
8379
+ // integer rates have interval-independent settlement at the same elapsed time.
8380
+ if (
8381
+ settings.sandboxWarmBillingMode === "credits" &&
8382
+ Object.values(warmRates).some((rate) => !Number.isSafeInteger(rate))
8383
+ ) {
8384
+ throw new Error(
8385
+ "OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON paid rates must be safe integers",
8386
+ );
8387
+ }
8388
+ if (
8389
+ settings.documentEmbeddingBillingMode === "credits" &&
8390
+ settings.documentEmbeddingProvider === "openai" &&
8391
+ settings.documentEmbeddingRateMicrosPerMillionBytes <= 0
8392
+ ) {
8393
+ throw new Error(
8394
+ "OPENGENI_DOCUMENT_EMBEDDING_RATE_MICROS_PER_MILLION_BYTES must be positive when paid OpenAI embedding billing is enabled",
8395
+ );
8396
+ }
8397
+ if (
8398
+ settings.documentEmbeddingBillingMode === "credits" &&
8399
+ settings.documentEmbeddingProvider === "openai" &&
8400
+ !settings.documentEmbeddingCreditsActivatedAt
8401
+ ) {
8402
+ throw new Error(
8403
+ "OPENGENI_DOCUMENT_EMBEDDING_CREDITS_ACTIVATED_AT is required for paid OpenAI embeddings",
8404
+ );
8405
+ }
6817
8406
  if (settings.sandboxBackend === "opensandbox") {
6818
8407
  if (!/@sha256:[0-9a-f]{64}$/i.test(settings.openSandboxImage ?? "")) {
6819
8408
  throw new Error(
@@ -6832,12 +8421,9 @@ function validateSettings(settings: Settings, source: NodeJS.ProcessEnv = proces
6832
8421
  throw new Error(`OPENGENI_MCP_SERVERS contains duplicate id ${server.id}`);
6833
8422
  }
6834
8423
  serverIds.add(server.id);
6835
- if (
6836
- server.connectionRef?.authoritySource === "host" &&
6837
- !settings.hostMcpAuthoritySourceAdmissionEnabled
6838
- ) {
8424
+ if (server.connectionRef?.authoritySource === "host") {
6839
8425
  throw new Error(
6840
- "OPENGENI_MCP_SERVERS host-owned connection refs require OPENGENI_HOST_MCP_AUTHORITY_SOURCE_ADMISSION_ENABLED=true after the whole API/worker fleet is upgraded",
8426
+ "OPENGENI_MCP_SERVERS host-owned connection refs are no longer supported; select ordinary native connections",
6841
8427
  );
6842
8428
  }
6843
8429
  }
@@ -6891,14 +8477,36 @@ function validateSettings(settings: Settings, source: NodeJS.ProcessEnv = proces
6891
8477
  ordinaryCaptureTimeoutMs,
6892
8478
  drainCaptureTimeoutMs,
6893
8479
  );
6894
- if (!(rotationLeadMs > providerDeadlineCaptureTimeoutMs + reaperPeriod)) {
8480
+ const requiredRotationLeadMs =
8481
+ SANDBOX_DEADLINE_COMMAND_STOP_GRACE_MS + providerDeadlineCaptureTimeoutMs + 2 * reaperPeriod;
8482
+ if (!(rotationLeadMs > requiredRotationLeadMs)) {
6895
8483
  throw new Error(
6896
8484
  `OPENGENI_SANDBOX_ROTATION_LEAD_MS (${rotationLeadMs}) must exceed the ` +
6897
- `largest durable snapshot or drain capture timeout plus one reaper period ` +
6898
- `(${providerDeadlineCaptureTimeoutMs + reaperPeriod}), including for persisted Modal ` +
8485
+ `legacy command stop grace, largest durable snapshot or drain capture timeout, and two reaper periods ` +
8486
+ `(${requiredRotationLeadMs}), including for persisted Modal ` +
6899
8487
  `leases after a default-backend rollout.`,
6900
8488
  );
6901
8489
  }
8490
+ const containmentMs = settings.sandboxIdleCommandContainmentMs;
8491
+ if (containmentMs !== undefined && !(containmentMs > settings.sandboxIdleGraceMs)) {
8492
+ throw new Error(
8493
+ `OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS (${containmentMs}) must exceed ` +
8494
+ `OPENGENI_SANDBOX_IDLE_GRACE_MS (${settings.sandboxIdleGraceMs}): a box kept warm only by ` +
8495
+ `retained commands must stay available at least as long as an idle box awaiting drain.`,
8496
+ );
8497
+ }
8498
+ if (
8499
+ containmentMs !== undefined &&
8500
+ optionalEnvironmentValue("OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS", source) !==
8501
+ undefined &&
8502
+ !(containmentMs < rotationLeadMs)
8503
+ ) {
8504
+ throw new Error(
8505
+ `OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS (${containmentMs}) must be strictly less than ` +
8506
+ `OPENGENI_SANDBOX_ROTATION_LEAD_MS (${rotationLeadMs}): an idle box must be checkpointed ` +
8507
+ `and stopped well before its provider deadline.`,
8508
+ );
8509
+ }
6902
8510
  if (settings.sandboxBackend === "modal") {
6903
8511
  const idleGraceMs = settings.sandboxIdleGraceMs;
6904
8512
  const lifecycle = effectiveSandboxLifecycle(settings, "modal");
@@ -6942,6 +8550,19 @@ function validateSettings(settings: Settings, source: NodeJS.ProcessEnv = proces
6942
8550
  `OPENGENI_SANDBOX_IDLE_GRACE_MS.`,
6943
8551
  );
6944
8552
  }
8553
+ if (
8554
+ settings.modalIdleTimeoutSeconds !== undefined &&
8555
+ containmentMs !== undefined &&
8556
+ !(reaperPeriod + containmentMs + drainCaptureTimeoutMs < idleTimeoutMs)
8557
+ ) {
8558
+ throw new Error(
8559
+ `OPENGENI_SANDBOX_LEASE_REAPER_PERIOD_MS + OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS + ` +
8560
+ `drain capture timeout (${reaperPeriod} + ${containmentMs} + ${drainCaptureTimeoutMs}) ` +
8561
+ `must be strictly less than OPENGENI_MODAL_IDLE_TIMEOUT_SECONDS*1000 (${idleTimeoutMs}): ` +
8562
+ `idle command containment must checkpoint a box before Modal's own idle reaper stops it. ` +
8563
+ `Lower OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS or raise the Modal idle timeout.`,
8564
+ );
8565
+ }
6945
8566
  }
6946
8567
  }
6947
8568
  // --- stream-token secret: required-when-desktop, but GRACEFULLY DEGRADE (stream-token availability contract) ---
@@ -6999,8 +8620,14 @@ export function validateModelCatalogSettings(
6999
8620
  provider.kind === "vercel-gateway-managed" ||
7000
8621
  provider.kind === "vercel-gateway-workspace" ||
7001
8622
  provider.kind === "vercel-gateway-organization" ||
8623
+ provider.kind === "direct-openai-workspace" ||
8624
+ provider.kind === "direct-azure-workspace" ||
7002
8625
  provider.kind === "openrouter-workspace" ||
7003
8626
  provider.kind === "openrouter-organization" ||
8627
+ provider.kind === "anthropic-organization" ||
8628
+ provider.kind === "anthropic-workspace" ||
8629
+ provider.kind === "claude-subscription-workspace" ||
8630
+ provider.kind === "claude-subscription-organization" ||
7004
8631
  provider.kind === "xai-subscription"
7005
8632
  ) {
7006
8633
  throw new Error(
@@ -7038,6 +8665,19 @@ export function validateModelCatalogSettings(
7038
8665
  // validated even when managed billing is disabled.
7039
8666
  const models = configuredModels(settings, source);
7040
8667
  const defaultCatalogSettings = settingsForTurnExecutionPolicy(settings, settings.openaiModel);
8668
+ const policy = settings.creditPromotionPolicy;
8669
+ const promotionalModelIds = new Set([
8670
+ ...(policy.defaultModelIds ?? []),
8671
+ ...(policy.signupModelIds ?? []),
8672
+ ...Object.values(policy.offers).flatMap((offer) => offer.eligibleModelIds ?? []),
8673
+ ]);
8674
+ for (const modelId of promotionalModelIds) {
8675
+ if (!models.some((model) => model.id === modelId && model.cost === "credits")) {
8676
+ throw new Error(
8677
+ `Promotional credit model ${modelId} must be a canonical credits-billed model in the catalog`,
8678
+ );
8679
+ }
8680
+ }
7041
8681
  const defaultCatalogModels =
7042
8682
  defaultCatalogSettings === settings ? models : configuredModels(defaultCatalogSettings, source);
7043
8683
  if (models.length === 0 && defaultCatalogModels.length === 0) {
@@ -7052,11 +8692,39 @@ export function validateModelCatalogSettings(
7052
8692
  `The default model ${settings.openaiModel} is not executable in the resolved model catalog`,
7053
8693
  );
7054
8694
  }
8695
+ // An operator-set credits default must name a credits-billed model in the
8696
+ // env catalog; a typo would otherwise fall back silently to the first
8697
+ // selectable credits model. Only an explicit value in code catalog mode is
8698
+ // checked: the built-in gpt-6-luna may be absent from a custom catalog, and
8699
+ // a database catalog is edited independently of this env value, so both keep
8700
+ // the documented fallback (docs/model-providers.md) instead of failing
8701
+ // every catalog read.
8702
+ const explicitCreditsDefault = source.OPENGENI_CREDITS_DEFAULT_MODEL?.trim();
8703
+ if (
8704
+ explicitCreditsDefault &&
8705
+ settings.modelCatalogSource === "code" &&
8706
+ settings.billingMode === "stripe"
8707
+ ) {
8708
+ const creditsDefaultId = canonicalizeConfiguredModelId(settings, settings.creditsDefaultModel);
8709
+ const creditsDefault = models.find((model) => model.id === creditsDefaultId);
8710
+ if (creditsDefault?.cost !== "credits") {
8711
+ throw new Error(
8712
+ `OPENGENI_CREDITS_DEFAULT_MODEL ${settings.creditsDefaultModel} is not a credits-billed model in the resolved model catalog`,
8713
+ );
8714
+ }
8715
+ }
7055
8716
 
7056
8717
  const deploymentProductIds = new Set(
7057
8718
  models.filter((model) => model.credentialSource.kind === "deployment").map((model) => model.id),
7058
8719
  );
7059
8720
  const noteProductIds = new Set(models.map((model) => model.id));
8721
+ if (settings.resolvedCodexModelsJson !== undefined) {
8722
+ for (const model of z
8723
+ .array(CodexCatalogModelSchema)
8724
+ .parse(JSON.parse(settings.resolvedCodexModelsJson))) {
8725
+ noteProductIds.add(model.id);
8726
+ }
8727
+ }
7060
8728
  for (const model of configuredGatewayCatalogModels(settings)) {
7061
8729
  deploymentProductIds.add(model.productId);
7062
8730
  noteProductIds.add(model.productId);
@@ -7191,6 +8859,108 @@ export function resolveNatsCalloutConfig(settings: Settings): NatsCalloutConfig
7191
8859
  return { accountSeed, accountName, user, password };
7192
8860
  }
7193
8861
 
8862
+ function validateObjectStorageSettings(settings: ObjectStorageSettings): void {
8863
+ if (
8864
+ settings.objectStorageBackend === "s3-compatible" ||
8865
+ settings.objectStorageBackend === "aws-s3"
8866
+ ) {
8867
+ if (
8868
+ Boolean(settings.objectStorageAccessKeyId) !== Boolean(settings.objectStorageSecretAccessKey)
8869
+ ) {
8870
+ throw new Error(
8871
+ "OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID and OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY must both be set or both omitted",
8872
+ );
8873
+ }
8874
+ if (
8875
+ settings.objectStorageBackend === "s3-compatible" &&
8876
+ (settings.objectStorageEndpoint ||
8877
+ settings.objectStorageInternalEndpoint ||
8878
+ settings.objectStorageSandboxEndpoint) &&
8879
+ (!settings.objectStorageAccessKeyId || !settings.objectStorageSecretAccessKey)
8880
+ ) {
8881
+ throw new Error(
8882
+ "S3-compatible object storage endpoints require OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID and OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY",
8883
+ );
8884
+ }
8885
+ if (
8886
+ settings.objectStorageAzureConnectionString ||
8887
+ settings.objectStorageAzureAccountName ||
8888
+ settings.objectStorageAzureAccountKey ||
8889
+ settings.objectStorageAzureEndpoint
8890
+ ) {
8891
+ throw new Error(
8892
+ "S3 object storage uses OPENGENI_OBJECT_STORAGE_* S3 settings, not OPENGENI_OBJECT_STORAGE_AZURE_* settings",
8893
+ );
8894
+ }
8895
+ if (
8896
+ settings.objectStorageGcsProjectId ||
8897
+ settings.objectStorageGcsCredentialsJson ||
8898
+ settings.objectStorageGcsKeyFilename ||
8899
+ settings.objectStorageGcsApiEndpoint
8900
+ ) {
8901
+ throw new Error(
8902
+ "S3 object storage uses OPENGENI_OBJECT_STORAGE_* S3 settings, not OPENGENI_OBJECT_STORAGE_GCS_* settings",
8903
+ );
8904
+ }
8905
+ } else if (settings.objectStorageBackend === "azure-blob") {
8906
+ if (
8907
+ settings.objectStorageEndpoint ||
8908
+ settings.objectStorageInternalEndpoint ||
8909
+ settings.objectStorageSandboxEndpoint ||
8910
+ settings.objectStorageAccessKeyId ||
8911
+ settings.objectStorageSecretAccessKey
8912
+ ) {
8913
+ throw new Error(
8914
+ "Azure Blob storage uses OPENGENI_OBJECT_STORAGE_AZURE_* settings, not S3-compatible object storage settings",
8915
+ );
8916
+ }
8917
+ if (
8918
+ settings.objectStorageGcsProjectId ||
8919
+ settings.objectStorageGcsCredentialsJson ||
8920
+ settings.objectStorageGcsKeyFilename ||
8921
+ settings.objectStorageGcsApiEndpoint
8922
+ ) {
8923
+ throw new Error(
8924
+ "Azure Blob storage uses OPENGENI_OBJECT_STORAGE_AZURE_* settings, not OPENGENI_OBJECT_STORAGE_GCS_* settings",
8925
+ );
8926
+ }
8927
+ const hasConnectionString = Boolean(settings.objectStorageAzureConnectionString);
8928
+ const hasSharedKey =
8929
+ Boolean(settings.objectStorageAzureAccountName) &&
8930
+ Boolean(settings.objectStorageAzureAccountKey);
8931
+ if (!hasConnectionString && !hasSharedKey) {
8932
+ throw new Error(
8933
+ "Azure Blob storage requires OPENGENI_OBJECT_STORAGE_AZURE_CONNECTION_STRING or OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_NAME plus OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_KEY",
8934
+ );
8935
+ }
8936
+ } else {
8937
+ if (
8938
+ settings.objectStorageEndpoint ||
8939
+ settings.objectStorageInternalEndpoint ||
8940
+ settings.objectStorageSandboxEndpoint ||
8941
+ settings.objectStorageAccessKeyId ||
8942
+ settings.objectStorageSecretAccessKey
8943
+ ) {
8944
+ throw new Error(
8945
+ "GCS object storage uses OPENGENI_OBJECT_STORAGE_GCS_* settings, not S3-compatible object storage settings",
8946
+ );
8947
+ }
8948
+ if (
8949
+ settings.objectStorageAzureConnectionString ||
8950
+ settings.objectStorageAzureAccountName ||
8951
+ settings.objectStorageAzureAccountKey ||
8952
+ settings.objectStorageAzureEndpoint
8953
+ ) {
8954
+ throw new Error(
8955
+ "GCS object storage uses OPENGENI_OBJECT_STORAGE_GCS_* settings, not OPENGENI_OBJECT_STORAGE_AZURE_* settings",
8956
+ );
8957
+ }
8958
+ if (settings.objectStorageGcsCredentialsJson) {
8959
+ parseGcsCredentialsJson(settings.objectStorageGcsCredentialsJson);
8960
+ }
8961
+ }
8962
+ }
8963
+
7194
8964
  /**
7195
8965
  * The PRIVILEGED control-plane NATS login (api/worker). Present only when BOTH a
7196
8966
  * user and password are set; otherwise null and the bus connects anonymously (local
@@ -7202,7 +8972,9 @@ export interface NatsControlPlaneAuth {
7202
8972
  password: string;
7203
8973
  }
7204
8974
 
7205
- export function resolveNatsControlPlaneAuth(settings: Settings): NatsControlPlaneAuth | null {
8975
+ export function resolveNatsControlPlaneAuth(
8976
+ settings: Pick<Settings, "selfhostedNatsControlUser" | "selfhostedNatsControlPassword">,
8977
+ ): NatsControlPlaneAuth | null {
7206
8978
  const user = settings.selfhostedNatsControlUser?.trim();
7207
8979
  const password = settings.selfhostedNatsControlPassword?.trim();
7208
8980
  if (!user || !password) {
@@ -7218,6 +8990,11 @@ function splitCsv(raw: string): string[] {
7218
8990
  .filter(Boolean);
7219
8991
  }
7220
8992
 
8993
+ /** Image references a workspace may select as its default sandbox image. */
8994
+ export function sandboxImageAllowlist(settings: Pick<Settings, "sandboxImageAllowlist">): string[] {
8995
+ return [...new Set(splitCsv(settings.sandboxImageAllowlist ?? ""))];
8996
+ }
8997
+
7221
8998
  function uniqueEnvNames(raw: string[], fieldName: string): string[] {
7222
8999
  const seen = new Set<string>();
7223
9000
  const out: string[] = [];
@@ -7251,3 +9028,196 @@ function parseGcsCredentialsJson(raw: string): unknown {
7251
9028
  function delay(ms: number): Promise<void> {
7252
9029
  return new Promise((resolve) => setTimeout(resolve, ms));
7253
9030
  }
9031
+
9032
+ /** Native Claude connections reuse the encrypted workspace and organization boundaries. */
9033
+ export const CLAUDE_CONNECTION_KINDS = ["anthropic", "claude_subscription"] as const;
9034
+ export type ClaudeConnectionKind = (typeof CLAUDE_CONNECTION_KINDS)[number];
9035
+ // Per-model native Messages controls. Unknown IDs never inherit adaptive
9036
+ // thinking merely because they share a provider with a supported model.
9037
+ const CLAUDE_NATIVE_MODEL_PROFILES: Readonly<
9038
+ Record<
9039
+ string,
9040
+ Readonly<{
9041
+ efforts: readonly ReasoningEffort[];
9042
+ defaultEffort: ReasoningEffort | null;
9043
+ contextWindowTokens: number;
9044
+ maxOutputTokens: number;
9045
+ }>
9046
+ >
9047
+ > = Object.fromEntries([
9048
+ ...[
9049
+ ["claude-opus-5-5", "medium"],
9050
+ ["claude-sonnet-5-5", "medium"],
9051
+ ["claude-opus-5", "high"],
9052
+ ["claude-sonnet-5", "high"],
9053
+ ["claude-opus-4-8", "high"],
9054
+ ["claude-opus-4-7", "xhigh"],
9055
+ ].map(([id, defaultEffort]) => [
9056
+ id,
9057
+ {
9058
+ efforts: ["low", "medium", "high", "xhigh", "max"],
9059
+ defaultEffort,
9060
+ contextWindowTokens: 1_000_000,
9061
+ maxOutputTokens: 128_000,
9062
+ },
9063
+ ]),
9064
+ ...["claude-opus-4-6", "claude-sonnet-4-6"].map((id) => [
9065
+ id,
9066
+ {
9067
+ efforts: ["low", "medium", "high", "max"],
9068
+ defaultEffort: "high",
9069
+ contextWindowTokens: 1_000_000,
9070
+ maxOutputTokens: 128_000,
9071
+ },
9072
+ ]),
9073
+ [
9074
+ "claude-haiku-4-5-20251001",
9075
+ {
9076
+ efforts: [],
9077
+ defaultEffort: null,
9078
+ contextWindowTokens: 200_000,
9079
+ maxOutputTokens: 64_000,
9080
+ },
9081
+ ],
9082
+ ]);
9083
+ export function claudeNativeModelProfile(upstreamModelId: string) {
9084
+ return Object.hasOwn(CLAUDE_NATIVE_MODEL_PROFILES, upstreamModelId)
9085
+ ? CLAUDE_NATIVE_MODEL_PROFILES[upstreamModelId]
9086
+ : undefined;
9087
+ }
9088
+ export function claudeProviderId(
9089
+ kind: ClaudeConnectionKind,
9090
+ scope: "workspace" | "organization" = "organization",
9091
+ ): string {
9092
+ return `${scope}-${kind === "anthropic" ? "anthropic" : "claude-subscription"}`;
9093
+ }
9094
+ export type ClaudeConnectionCatalog = Partial<
9095
+ Record<
9096
+ ClaudeConnectionKind,
9097
+ {
9098
+ active?: boolean;
9099
+ models: readonly { upstreamModelId: string; label?: string | null }[];
9100
+ }
9101
+ >
9102
+ >;
9103
+ export function withClaudeConnectionCatalog(
9104
+ settings: Settings,
9105
+ connections: ClaudeConnectionCatalog,
9106
+ scope: "workspace" | "organization" = "organization",
9107
+ ): Settings {
9108
+ let providers = parseModelProvidersJson(settings.modelProvidersJson);
9109
+ for (const kind of CLAUDE_CONNECTION_KINDS) {
9110
+ if (kind === "claude_subscription" && !settings.claudeSubscriptionEnabled) {
9111
+ providers = providers.filter((provider) => provider.id !== claudeProviderId(kind, scope));
9112
+ continue;
9113
+ }
9114
+ const connection = connections[kind];
9115
+ if (!connection) continue;
9116
+ const id = claudeProviderId(kind, scope);
9117
+ providers = providers.filter((provider) => provider.id !== id);
9118
+ if (!connection.models.length) continue;
9119
+ providers.push({
9120
+ id,
9121
+ label: kind === "anthropic" ? "Anthropic API" : "Claude subscription",
9122
+ kind: kind === "anthropic" ? `anthropic-${scope}` : `claude-subscription-${scope}`,
9123
+ api: "anthropic-messages",
9124
+ wireProfile: "openai",
9125
+ baseUrl: "https://api.anthropic.com/v1",
9126
+ anthropic: {
9127
+ auth: kind === "anthropic" ? "api-key" : "oauth",
9128
+ cacheTtl: "5m",
9129
+ maxOutputTokens: 128000,
9130
+ streamIdleTimeoutMs: 600000,
9131
+ },
9132
+ models: connection.models.map((model) => {
9133
+ const profile = claudeNativeModelProfile(model.upstreamModelId);
9134
+ const adaptiveThinking = Boolean(profile?.efforts.length);
9135
+ const contextWindowTokens = profile?.contextWindowTokens ?? 200_000;
9136
+ const outputReserve = profile?.maxOutputTokens ?? 32_000;
9137
+ return {
9138
+ contextWindowTokens,
9139
+ effectiveContextWindowTokens: contextWindowTokens - outputReserve,
9140
+ autoCompactTokenLimit:
9141
+ contextWindowTokens === 1_000_000
9142
+ ? 800_000
9143
+ : Math.min(150_000, contextWindowTokens - outputReserve - 18_000),
9144
+ id: id + "/" + model.upstreamModelId,
9145
+ upstreamModelId: model.upstreamModelId,
9146
+ label:
9147
+ model.label ??
9148
+ (model.upstreamModelId === "claude-opus-5-5"
9149
+ ? "Claude Opus 5.5"
9150
+ : model.upstreamModelId === "claude-sonnet-5-5"
9151
+ ? "Claude Sonnet 5.5"
9152
+ : model.upstreamModelId),
9153
+ reasoningEffort: adaptiveThinking,
9154
+ hostedWebSearch: false,
9155
+ capabilities: {
9156
+ ...legacyModelCapabilities(settings, {
9157
+ reasoningEffort: adaptiveThinking,
9158
+ hostedWebSearch: false,
9159
+ vision: true,
9160
+ }),
9161
+ inputFileMediaTypes: [],
9162
+ reasoning: {
9163
+ upstream: adaptiveThinking ? "supported" : "unknown",
9164
+ runnable: adaptiveThinking,
9165
+ efforts: [...(profile?.efforts ?? [])],
9166
+ defaultEffort: profile?.defaultEffort ?? null,
9167
+ required: false,
9168
+ },
9169
+ functionCalling: { upstream: "supported", runnable: true },
9170
+ promptCaching: { upstream: "supported", runnable: true, mode: "automatic" },
9171
+ },
9172
+ };
9173
+ }),
9174
+ });
9175
+ }
9176
+ return { ...settings, modelProvidersJson: JSON.stringify(providers) };
9177
+ }
9178
+ export function withClaudeConnectionCredential(
9179
+ settings: Settings,
9180
+ kind: ClaudeConnectionKind,
9181
+ credential: string,
9182
+ scope: "workspace" | "organization" = "organization",
9183
+ credentialBinding?: { connectionId: string; credentialVersion: number },
9184
+ ): Settings {
9185
+ if (kind === "claude_subscription" && !settings.claudeSubscriptionEnabled)
9186
+ throw new Error("Claude subscriptions are not enabled on this deployment");
9187
+ if (!credential.trim()) throw new Error("Claude credential is empty");
9188
+ const bundle =
9189
+ kind === "claude_subscription" && credential.trim().startsWith("{")
9190
+ ? ClaudeSubscriptionCredential.parse(JSON.parse(credential))
9191
+ : null;
9192
+ return {
9193
+ ...settings,
9194
+ modelProvidersJson: JSON.stringify(
9195
+ parseModelProvidersJson(settings.modelProvidersJson).map((provider) =>
9196
+ provider.id === claudeProviderId(kind, scope)
9197
+ ? {
9198
+ ...provider,
9199
+ apiKey: bundle?.token ?? credential,
9200
+ ...(kind === "claude_subscription" && provider.anthropic
9201
+ ? {
9202
+ anthropic: {
9203
+ ...provider.anthropic,
9204
+ identity: bundle?.identity,
9205
+ credentialBinding: credentialBinding
9206
+ ? {
9207
+ connectionId: credentialBinding.connectionId,
9208
+ credentialVersion: credentialBinding.credentialVersion,
9209
+ }
9210
+ : undefined,
9211
+ },
9212
+ }
9213
+ : {}),
9214
+ }
9215
+ : provider,
9216
+ ),
9217
+ ),
9218
+ };
9219
+ }
9220
+ export * from "./claude-subscription-usage";
9221
+ export * from "./claude-subscription-oauth";
9222
+ export * from "./subscription-account-selection";
9223
+ export * from "./claude-subscription-capacity";