@opengeni/config 3.2.1 → 3.3.0-canary.37090756480001

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,5 +1,6 @@
1
1
  export { managedUserEmailAllowed } from "./managed-user-admission";
2
2
  import {
3
+ directModelConnectionSpec,
3
4
  BillingMode,
4
5
  CAPABILITY_DESCRIPTORS,
5
6
  agentConfigDeploymentLimitsFromAllowlist,
@@ -100,6 +101,13 @@ const EnvBoolean = z.preprocess((value) => {
100
101
  return value;
101
102
  }, z.boolean());
102
103
 
104
+ /** An absolute http(s) URL that is safe to render as a browser link. */
105
+ const PublicHttpUrl = z
106
+ .string()
107
+ .url()
108
+ .max(2_048)
109
+ .refine((value) => /^https?:\/\//iu.test(value), "must be an http(s) URL");
110
+
103
111
  /** Default pacing between consecutive no-input goal continuations. */
104
112
  export const DEFAULT_GOAL_IDLE_BACKOFF_MS: readonly number[] = [3_000, 30_000, 120_000, 300_000];
105
113
  export const DEFAULT_GOAL_IDLE_BACKOFF_MAX_MS = 600_000;
@@ -311,6 +319,15 @@ const SettingsSchema = z.object({
311
319
  .max(32)
312
320
  .regex(/^G-[A-Z0-9]+$/u)
313
321
  .optional(),
322
+ // Optional operator-owned legal documents linked from the signed-out console.
323
+ // Unset by default, so a self-hosted deployment never shows another operator's
324
+ // policies; the managed service points these at its own published pages.
325
+ legalPrivacyPolicyUrl: PublicHttpUrl.optional(),
326
+ legalTermsOfServiceUrl: PublicHttpUrl.optional(),
327
+ // Optional operator support address, shown as a "Contact support" mailto link
328
+ // on the signed-out page and in the Help menu. Unset by default for the same
329
+ // reason as the legal links.
330
+ supportEmail: z.string().trim().email().max(254).optional(),
314
331
  publicBaseUrl: z.string().url().optional(),
315
332
  // Product documentation the web console links from its Help menu. Absent
316
333
  // means the public OpenGeni docs; `none` hides the link for deployments that
@@ -1223,6 +1240,33 @@ const SettingsSchema = z.object({
1223
1240
  // getSettings caps the default at half a shorter configured Modal lifetime so
1224
1241
  // the entire reaper window always fits. Knob: OPENGENI_SANDBOX_IDLE_GRACE_MS.
1225
1242
  sandboxIdleGraceMs: z.coerce.number().int().positive().default(900_000),
1243
+ // Idle command containment. A legacy retained background command (a dev
1244
+ // server, a command whose output is still draining, a stopped command the
1245
+ // provider no longer answers for) keeps its box warm through a non-expiring
1246
+ // process holder, so the zero-holder drain never runs and the box would stay
1247
+ // up until the provider deadline kills it uncaptured. Once every session of
1248
+ // the sandbox group has been unused this long - no open turn or pending
1249
+ // request, no held wait_for_input, no other holder or writer, measured from
1250
+ // durable turn/holder/admission facts - the reaper checkpoints the workspace,
1251
+ // stops the box and settles those commands `lost` with reason
1252
+ // `idle_containment`. Default 30min: twice the default
1253
+ // idle grace, so a lease that is only waiting for a "glanced away" user is
1254
+ // never contained earlier than an idle lease would drain, and well inside
1255
+ // the 1h provider-deadline rotation lead, so an idle box is saved long before
1256
+ // the deadline path has to act. Set 0 to disable new idle enrollments without
1257
+ // disabling provider-deadline containment or cancelling an enrolled drain.
1258
+ // A positive window must exceed OPENGENI_SANDBOX_IDLE_GRACE_MS;
1259
+ // an explicit positive value must also stay below OPENGENI_SANDBOX_ROTATION_LEAD_MS,
1260
+ // and with an explicit OPENGENI_MODAL_IDLE_TIMEOUT_SECONDS the reaper period
1261
+ // plus this window plus the drain capture budget must fit before it.
1262
+ // getSettings derives the unset default between those two for short-lived
1263
+ // provider lifetimes. Knob: OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS.
1264
+ sandboxIdleCommandContainmentMs: z.coerce
1265
+ .number()
1266
+ .int()
1267
+ .nonnegative()
1268
+ .optional()
1269
+ .transform((value) => (value === 0 ? undefined : value)),
1226
1270
  // MID-SESSION /workspace snapshot cadence (sandbox-file-persistence). The
1227
1271
  // reaper's drain-persist only protects boxes the reaper itself kills; a box
1228
1272
  // that dies any other way (Modal's hard creation-time timeout on a session
@@ -2113,6 +2157,8 @@ export const RegistryProviderKind = z.enum([
2113
2157
  "vercel-gateway-managed",
2114
2158
  "vercel-gateway-workspace",
2115
2159
  "vercel-gateway-organization",
2160
+ "direct-openai-workspace",
2161
+ "direct-azure-workspace",
2116
2162
  "openrouter-workspace",
2117
2163
  "openrouter-organization",
2118
2164
  "anthropic-organization",
@@ -2465,7 +2511,11 @@ const CodexCatalogModelSchema = RegistryModelSchema.safeExtend({
2465
2511
  message: "Codex product id must match its upstream model slug",
2466
2512
  });
2467
2513
  }
2468
- });
2514
+ })
2515
+ .transform((model) => ({
2516
+ ...model,
2517
+ capabilities: reviewedCodexCatalogCapabilities(model.upstreamModelId, model.capabilities),
2518
+ }));
2469
2519
 
2470
2520
  export const ModelCatalogDocument = z
2471
2521
  .object({
@@ -2526,7 +2576,11 @@ export const ModelCatalogDocument = z
2526
2576
  });
2527
2577
  }
2528
2578
  document.registryProviders.forEach((provider, providerIndex) => {
2529
- if (RESERVED_MODEL_PROVIDER_IDS.has(provider.id)) {
2579
+ if (
2580
+ RESERVED_MODEL_PROVIDER_IDS.has(provider.id) ||
2581
+ provider.id.startsWith("workspace-openai-") ||
2582
+ provider.id.startsWith("workspace-azure-openai-")
2583
+ ) {
2530
2584
  context.addIssue({
2531
2585
  code: "custom",
2532
2586
  path: ["registryProviders", providerIndex, "id"],
@@ -3226,6 +3280,9 @@ function optionalEnvironmentValue(name: string, source: NodeJS.ProcessEnv): stri
3226
3280
  return value && value.trim().length > 0 ? value : undefined;
3227
3281
  }
3228
3282
 
3283
+ // getSettings runs per request in some processes; say this once per process.
3284
+ let idleCommandContainmentDisabledWarned = false;
3285
+
3229
3286
  export function getSettings(source: NodeJS.ProcessEnv = process.env): Settings {
3230
3287
  const optional = (name: string): string | undefined => optionalEnvironmentValue(name, source);
3231
3288
  const modelCatalogSource = optional("OPENGENI_MODEL_CATALOG_SOURCE");
@@ -3282,6 +3339,9 @@ export function getSettings(source: NodeJS.ProcessEnv = process.env): Settings {
3282
3339
  analyticsPosthogProjectKey: optional("OPENGENI_ANALYTICS_POSTHOG_PROJECT_KEY"),
3283
3340
  analyticsPosthogHost: optional("OPENGENI_ANALYTICS_POSTHOG_HOST"),
3284
3341
  analyticsGa4MeasurementId: optional("OPENGENI_ANALYTICS_GA4_MEASUREMENT_ID"),
3342
+ legalPrivacyPolicyUrl: optional("OPENGENI_LEGAL_PRIVACY_POLICY_URL"),
3343
+ legalTermsOfServiceUrl: optional("OPENGENI_LEGAL_TERMS_OF_SERVICE_URL"),
3344
+ supportEmail: optional("OPENGENI_SUPPORT_EMAIL"),
3285
3345
  publicBaseUrl: optional("OPENGENI_PUBLIC_BASE_URL"),
3286
3346
  documentationUrl: optional("OPENGENI_DOCUMENTATION_URL"),
3287
3347
  mcpOauthEnabled: optional("OPENGENI_MCP_OAUTH_ENABLED"),
@@ -3586,6 +3646,7 @@ export function getSettings(source: NodeJS.ProcessEnv = process.env): Settings {
3586
3646
  sandboxViewerHolderTtlMs: optional("OPENGENI_SANDBOX_VIEWER_HOLDER_TTL_MS"),
3587
3647
  sandboxInteractionHolderTtlMs: optional("OPENGENI_SANDBOX_INTERACTION_HOLDER_TTL_MS"),
3588
3648
  sandboxIdleGraceMs: optional("OPENGENI_SANDBOX_IDLE_GRACE_MS"),
3649
+ sandboxIdleCommandContainmentMs: optional("OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS"),
3589
3650
  sandboxSnapshotIntervalMs: optional("OPENGENI_SANDBOX_SNAPSHOT_INTERVAL_MS"),
3590
3651
  sandboxSnapshotTimeoutMs: optional("OPENGENI_SANDBOX_SNAPSHOT_TIMEOUT_MS"),
3591
3652
  sandboxDrainSnapshotTimeoutMs: optional("OPENGENI_SANDBOX_DRAIN_SNAPSHOT_TIMEOUT_MS"),
@@ -3717,6 +3778,40 @@ export function getSettings(source: NodeJS.ProcessEnv = process.env): Settings {
3717
3778
  : parsed.sandboxRotationLeadMs,
3718
3779
  mcpServers: ensureBuiltInMcpServers(parsed),
3719
3780
  };
3781
+ if (raw.sandboxIdleCommandContainmentMs === undefined) {
3782
+ // Strictly between the idle grace and the rotation lead whenever that
3783
+ // interval exists (short test/canary lifetimes), never above 30 minutes,
3784
+ // and early enough that an explicit Modal idle timeout cannot fire first.
3785
+ const modalIdleCeilingMs =
3786
+ settings.sandboxBackend === "modal" && settings.modalIdleTimeoutSeconds !== undefined
3787
+ ? settings.modalIdleTimeoutSeconds * 1000 -
3788
+ settings.sandboxLeaseReaperPeriodMs -
3789
+ sandboxArchiveCaptureTimeoutMs({
3790
+ sandboxSnapshotTimeoutMs: effectiveSandboxDrainSnapshotTimeoutMs(settings),
3791
+ }) -
3792
+ 1
3793
+ : Number.POSITIVE_INFINITY;
3794
+ const derived = Math.min(
3795
+ 1_800_000,
3796
+ Math.floor((settings.sandboxIdleGraceMs + settings.sandboxRotationLeadMs) / 2),
3797
+ modalIdleCeilingMs,
3798
+ );
3799
+ // A derived value never fails validation: with no room above the idle
3800
+ // grace, idle containment stays off and only the deadline rule applies.
3801
+ if (derived > settings.sandboxIdleGraceMs) {
3802
+ settings.sandboxIdleCommandContainmentMs = derived;
3803
+ } else {
3804
+ settings.sandboxIdleCommandContainmentMs = undefined;
3805
+ if (!idleCommandContainmentDisabledWarned) {
3806
+ idleCommandContainmentDisabledWarned = true;
3807
+ console.warn(
3808
+ "[config] idle command containment disabled: no window fits between " +
3809
+ `OPENGENI_SANDBOX_IDLE_GRACE_MS (${settings.sandboxIdleGraceMs}) and the Modal idle ` +
3810
+ "timeout / rotation lead ceiling; set OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS to override.",
3811
+ );
3812
+ }
3813
+ }
3814
+ }
3720
3815
  validateSettings(settings, source);
3721
3816
  return settings;
3722
3817
  }
@@ -4469,6 +4564,53 @@ function configuredRegistryProviders(settings: Settings): InternalRegistryProvid
4469
4564
  return injected;
4470
4565
  }
4471
4566
 
4567
+ /** Customer-owned OpenAI/Azure routes, bound to immutable connection identity. */
4568
+ export function withDirectModelProviders(
4569
+ settings: Settings,
4570
+ connections: readonly {
4571
+ id: string;
4572
+ version: number;
4573
+ subjectId: string | null;
4574
+ kind: string;
4575
+ status: string;
4576
+ providerDomain: string;
4577
+ metadata: Record<string, unknown>;
4578
+ apiKey?: string;
4579
+ }[],
4580
+ ): Settings {
4581
+ const providers = parseModelProvidersJson(settings.modelProvidersJson).filter(
4582
+ (provider) =>
4583
+ !provider.id.startsWith("workspace-openai-") &&
4584
+ !provider.id.startsWith("workspace-azure-openai-"),
4585
+ );
4586
+ for (const connection of connections) {
4587
+ const spec = directModelConnectionSpec(connection);
4588
+ if (!spec) continue;
4589
+ providers.push({
4590
+ kind: spec.provider === "openai" ? "direct-openai-workspace" : "direct-azure-workspace",
4591
+ id: spec.providerId,
4592
+ label: spec.provider === "openai" ? "Your OpenAI" : "Your Azure OpenAI",
4593
+ api: "responses",
4594
+ wireProfile: spec.provider === "openai" ? "openai" : "azure-openai",
4595
+ baseUrl: spec.baseUrl,
4596
+ ...(connection.apiKey ? { apiKey: connection.apiKey } : {}),
4597
+ models: [
4598
+ {
4599
+ id: spec.modelId,
4600
+ upstreamModelId: spec.model,
4601
+ label: spec.model,
4602
+ capabilities: legacyModelCapabilities(settings, {
4603
+ reasoningEffort: false,
4604
+ hostedWebSearch: false,
4605
+ }),
4606
+ toolOutputTruncationTokens: settings.modelToolOutputTruncationTokens,
4607
+ },
4608
+ ],
4609
+ });
4610
+ }
4611
+ return { ...settings, modelProvidersJson: JSON.stringify(providers) };
4612
+ }
4613
+
4472
4614
  /** Static catalog overlay; it contains no concrete workspace credential. */
4473
4615
  export function withWorkspaceGatewayCatalogProvider(
4474
4616
  settings: Settings,
@@ -4721,9 +4863,9 @@ function builtinLatencyModesForModel(modelId: string): Array<{
4721
4863
  }> {
4722
4864
  if (
4723
4865
  isBuiltinGpt56ModelId(modelId) ||
4724
- modelId.startsWith("gpt-6-") ||
4866
+ /^gpt-6(?:\.\d+)?-/u.test(modelId) ||
4725
4867
  modelId.startsWith("codex/gpt-5.6-") ||
4726
- modelId.startsWith("codex/gpt-6-")
4868
+ /^codex\/gpt-6(?:\.\d+)?-/u.test(modelId)
4727
4869
  ) {
4728
4870
  return [
4729
4871
  { id: "standard", upstream: "supported", runnable: true },
@@ -4738,6 +4880,31 @@ function builtinLatencyModesForModel(modelId: string): Array<{
4738
4880
  return [{ id: "standard", upstream: "unknown", runnable: true }];
4739
4881
  }
4740
4882
 
4883
+ function isReviewedGptVisionModel(slug: string): boolean {
4884
+ return slug.startsWith("gpt-5.6-") || /^gpt-6(?:\.\d+)?-/u.test(slug);
4885
+ }
4886
+
4887
+ /** Repair missing reviewed capabilities in live/stored Codex definitions.
4888
+ * Explicit latency restrictions and every unrelated catalog field remain authoritative.
4889
+ */
4890
+ function reviewedCodexCatalogCapabilities(
4891
+ slug: string,
4892
+ capabilities: ModelCapabilitiesV1,
4893
+ ): ModelCapabilitiesV1 {
4894
+ if (!/^gpt-6(?:\.\d+)?-/u.test(slug)) return capabilities;
4895
+ const fast = builtinLatencyModesForModel(`${CODEX_MODEL_ID_PREFIX}${slug}`).find(
4896
+ (mode) => mode.id === "fast",
4897
+ );
4898
+ return normalizeCapabilities({
4899
+ ...capabilities,
4900
+ inputModalities: [...new Set([...capabilities.inputModalities, "image" as const])],
4901
+ latencyModes:
4902
+ fast && !capabilities.latencyModes.some((mode) => mode.id === "fast")
4903
+ ? [...capabilities.latencyModes, fast]
4904
+ : capabilities.latencyModes,
4905
+ });
4906
+ }
4907
+
4741
4908
  function builtinPromptCachingForModel(
4742
4909
  modelId: string,
4743
4910
  ): NonNullable<ModelCapabilitiesV1["promptCaching"]> | undefined {
@@ -4831,9 +4998,22 @@ function assertLatencyModeRunnable(
4831
4998
  ): void {
4832
4999
  const runnable = runnableLatencyModesForModel(settings, modelId);
4833
5000
  if (!runnable.includes(latencyMode)) {
4834
- throw new Error(
4835
- `latency mode ${latencyMode} is not runnable for model ${modelId} (allowed: ${runnable.join(", ")})`,
5001
+ throw new UnsupportedLatencyModeError(modelId, latencyMode, runnable);
5002
+ }
5003
+ }
5004
+
5005
+ export class UnsupportedLatencyModeError extends Error {
5006
+ readonly code = "UNSUPPORTED_LATENCY_MODE";
5007
+
5008
+ constructor(
5009
+ readonly modelId: string,
5010
+ readonly latencyMode: LatencyMode,
5011
+ readonly allowedLatencyModes: readonly LatencyMode[],
5012
+ ) {
5013
+ super(
5014
+ `latency mode ${latencyMode} is not runnable for model ${modelId} (allowed: ${allowedLatencyModes.join(", ")})`,
4836
5015
  );
5016
+ this.name = "UnsupportedLatencyModeError";
4837
5017
  }
4838
5018
  }
4839
5019
 
@@ -4846,6 +5026,8 @@ function registryCredentialSource(provider: InternalRegistryProvider): Credentia
4846
5026
  case "xai-subscription":
4847
5027
  return { kind: "connected_subscription", provider: "xai" };
4848
5028
  case "vercel-gateway-workspace":
5029
+ case "direct-openai-workspace":
5030
+ case "direct-azure-workspace":
4849
5031
  case "openrouter-workspace":
4850
5032
  case "anthropic-workspace":
4851
5033
  case "claude-subscription-workspace":
@@ -4875,6 +5057,8 @@ function registryBilling(provider: InternalRegistryProvider): BillingAttribution
4875
5057
  case "xai-subscription":
4876
5058
  return { upstreamPayer: "connected_subscription", metering: "external" };
4877
5059
  case "vercel-gateway-workspace":
5060
+ case "direct-openai-workspace":
5061
+ case "direct-azure-workspace":
4878
5062
  case "openrouter-workspace":
4879
5063
  case "anthropic-workspace":
4880
5064
  case "claude-subscription-workspace":
@@ -5054,6 +5238,48 @@ function legacyCodexAstraImplicitCachingDefinitionVersionFor(
5054
5238
  return definitionVersionFor({ ...modelWithoutVersion, capabilities }, provider);
5055
5239
  }
5056
5240
 
5241
+ function matchesAdditiveCapabilityDefinitionVersion(
5242
+ model: ConfiguredModel,
5243
+ provider: ResolvedModelProvider,
5244
+ policy: TurnExecutionPolicyV1,
5245
+ ): boolean {
5246
+ const { definitionVersion: _definitionVersion, ...modelWithoutVersion } = model;
5247
+ const { latencyModes, inputModalities } = model.capabilities;
5248
+ // V1 has only three unique latency ids and three unique input modalities:
5249
+ // at most 4 * 7 subset digests retaining the frozen mode. Reconstruct an
5250
+ // exact historical declaration; never ignore the digest or alter existing
5251
+ // mode support, runnable state, billing multiplier, or request-tier routing.
5252
+ // Every other executable field remains in the digest. Do not compose this
5253
+ // with the pre-wire-profile or implicit-caching migration exceptions.
5254
+ for (let latencyMask = 1; latencyMask < 1 << latencyModes.length; latencyMask += 1) {
5255
+ const retainedModes = latencyModes.filter((_mode, index) => latencyMask & (1 << index));
5256
+ if (!retainedModes.some((mode) => mode.id === policy.latencyMode && mode.runnable)) {
5257
+ continue;
5258
+ }
5259
+ for (let inputMask = 1; inputMask < 1 << inputModalities.length; inputMask += 1) {
5260
+ const retainedInputs = inputModalities.filter((_modality, index) => inputMask & (1 << index));
5261
+ if (
5262
+ retainedModes.length === latencyModes.length &&
5263
+ retainedInputs.length === inputModalities.length
5264
+ ) {
5265
+ continue;
5266
+ }
5267
+ const capabilities = {
5268
+ ...model.capabilities,
5269
+ latencyModes: retainedModes,
5270
+ inputModalities: retainedInputs,
5271
+ };
5272
+ if (
5273
+ policy.definitionVersion ===
5274
+ definitionVersionFor({ ...modelWithoutVersion, capabilities }, provider)
5275
+ ) {
5276
+ return true;
5277
+ }
5278
+ }
5279
+ }
5280
+ return false;
5281
+ }
5282
+
5057
5283
  /**
5058
5284
  * The built-in provider's stable id: "openai" on the OpenAI platform, "azure"
5059
5285
  * on Azure. Exported because the workspace model-policy gate must attribute
@@ -5169,7 +5395,7 @@ export function withCodexCatalogProvider(settings: Settings): Settings {
5169
5395
  ...legacyModelCapabilities(settings, {
5170
5396
  reasoningEffort: true,
5171
5397
  hostedWebSearch: true,
5172
- vision: slug.startsWith("gpt-5.6-") || slug.startsWith("gpt-6-"),
5398
+ vision: isReviewedGptVisionModel(slug),
5173
5399
  }),
5174
5400
  ...(builtinPromptCachingForModel(`${CODEX_MODEL_ID_PREFIX}${slug}`)
5175
5401
  ? {
@@ -5436,7 +5662,7 @@ export function configuredModels(
5436
5662
  reasoningEffort: true,
5437
5663
  hostedWebSearch: settings.webSearchEnabled,
5438
5664
  hostedImageGeneration: builtinHostedImageGenerationForModel(settings, id),
5439
- vision: id.startsWith("gpt-5.6-") || id.startsWith("gpt-6-"),
5665
+ vision: isReviewedGptVisionModel(id),
5440
5666
  }),
5441
5667
  ...(builtinPromptCachingForModel(id)
5442
5668
  ? { promptCaching: builtinPromptCachingForModel(id)! }
@@ -5770,7 +5996,7 @@ export class TurnExecutionPolicyDefinitionMismatchError extends Error {
5770
5996
  /**
5771
5997
  * Parse-time validation lives in @opengeni/contracts; this verifier binds a
5772
5998
  * present snapshot to the current executable definition and exact turn row.
5773
- * Any deployment/provider drift fails before a provider or compaction call.
5999
+ * Non-additive executable drift fails before a provider or compaction call.
5774
6000
  */
5775
6001
  export function assertTurnExecutionPolicyMatchesConfigV1(
5776
6002
  settings: Settings,
@@ -5822,7 +6048,8 @@ export function assertTurnExecutionPolicyMatchesConfigV1(
5822
6048
  parsed.definitionVersion === resolved.model.definitionVersion ||
5823
6049
  parsed.definitionVersion === legacyImplicitOpenAiDefinitionVersion ||
5824
6050
  parsed.definitionVersion ===
5825
- legacyCodexAstraImplicitCachingDefinitionVersionFor(resolved.model, resolved.provider);
6051
+ legacyCodexAstraImplicitCachingDefinitionVersionFor(resolved.model, resolved.provider) ||
6052
+ matchesAdditiveCapabilityDefinitionVersion(resolved.model, resolved.provider, parsed);
5826
6053
  const identityMismatched =
5827
6054
  parsed.providerId !== resolved.provider.id ||
5828
6055
  parsed.upstreamModelId !== resolved.model.upstreamModelId ||
@@ -7610,6 +7837,26 @@ function validateSettings(settings: Settings, source: NodeJS.ProcessEnv = proces
7610
7837
  `leases after a default-backend rollout.`,
7611
7838
  );
7612
7839
  }
7840
+ const containmentMs = settings.sandboxIdleCommandContainmentMs;
7841
+ if (containmentMs !== undefined && !(containmentMs > settings.sandboxIdleGraceMs)) {
7842
+ throw new Error(
7843
+ `OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS (${containmentMs}) must exceed ` +
7844
+ `OPENGENI_SANDBOX_IDLE_GRACE_MS (${settings.sandboxIdleGraceMs}): a box kept warm only by ` +
7845
+ `retained commands must stay available at least as long as an idle box awaiting drain.`,
7846
+ );
7847
+ }
7848
+ if (
7849
+ containmentMs !== undefined &&
7850
+ optionalEnvironmentValue("OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS", source) !==
7851
+ undefined &&
7852
+ !(containmentMs < rotationLeadMs)
7853
+ ) {
7854
+ throw new Error(
7855
+ `OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS (${containmentMs}) must be strictly less than ` +
7856
+ `OPENGENI_SANDBOX_ROTATION_LEAD_MS (${rotationLeadMs}): an idle box must be checkpointed ` +
7857
+ `and stopped well before its provider deadline.`,
7858
+ );
7859
+ }
7613
7860
  if (settings.sandboxBackend === "modal") {
7614
7861
  const idleGraceMs = settings.sandboxIdleGraceMs;
7615
7862
  const lifecycle = effectiveSandboxLifecycle(settings, "modal");
@@ -7653,6 +7900,19 @@ function validateSettings(settings: Settings, source: NodeJS.ProcessEnv = proces
7653
7900
  `OPENGENI_SANDBOX_IDLE_GRACE_MS.`,
7654
7901
  );
7655
7902
  }
7903
+ if (
7904
+ settings.modalIdleTimeoutSeconds !== undefined &&
7905
+ containmentMs !== undefined &&
7906
+ !(reaperPeriod + containmentMs + drainCaptureTimeoutMs < idleTimeoutMs)
7907
+ ) {
7908
+ throw new Error(
7909
+ `OPENGENI_SANDBOX_LEASE_REAPER_PERIOD_MS + OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS + ` +
7910
+ `drain capture timeout (${reaperPeriod} + ${containmentMs} + ${drainCaptureTimeoutMs}) ` +
7911
+ `must be strictly less than OPENGENI_MODAL_IDLE_TIMEOUT_SECONDS*1000 (${idleTimeoutMs}): ` +
7912
+ `idle command containment must checkpoint a box before Modal's own idle reaper stops it. ` +
7913
+ `Lower OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS or raise the Modal idle timeout.`,
7914
+ );
7915
+ }
7656
7916
  }
7657
7917
  }
7658
7918
  // --- stream-token secret: required-when-desktop, but GRACEFULLY DEGRADE (stream-token availability contract) ---
@@ -7710,6 +7970,8 @@ export function validateModelCatalogSettings(
7710
7970
  provider.kind === "vercel-gateway-managed" ||
7711
7971
  provider.kind === "vercel-gateway-workspace" ||
7712
7972
  provider.kind === "vercel-gateway-organization" ||
7973
+ provider.kind === "direct-openai-workspace" ||
7974
+ provider.kind === "direct-azure-workspace" ||
7713
7975
  provider.kind === "openrouter-workspace" ||
7714
7976
  provider.kind === "openrouter-organization" ||
7715
7977
  provider.kind === "anthropic-organization" ||
@@ -8107,6 +8369,59 @@ function delay(ms: number): Promise<void> {
8107
8369
  /** Native Claude connections reuse the encrypted workspace and organization boundaries. */
8108
8370
  export const CLAUDE_CONNECTION_KINDS = ["anthropic", "claude_subscription"] as const;
8109
8371
  export type ClaudeConnectionKind = (typeof CLAUDE_CONNECTION_KINDS)[number];
8372
+ // Per-model native Messages controls. Unknown IDs never inherit adaptive
8373
+ // thinking merely because they share a provider with a supported model.
8374
+ const CLAUDE_NATIVE_MODEL_PROFILES: Readonly<
8375
+ Record<
8376
+ string,
8377
+ Readonly<{
8378
+ efforts: readonly ReasoningEffort[];
8379
+ defaultEffort: ReasoningEffort | null;
8380
+ contextWindowTokens: number;
8381
+ maxOutputTokens: number;
8382
+ }>
8383
+ >
8384
+ > = Object.fromEntries([
8385
+ ...[
8386
+ ["claude-opus-5-5", "medium"],
8387
+ ["claude-sonnet-5-5", "medium"],
8388
+ ["claude-opus-5", "high"],
8389
+ ["claude-sonnet-5", "high"],
8390
+ ["claude-opus-4-8", "high"],
8391
+ ["claude-opus-4-7", "xhigh"],
8392
+ ].map(([id, defaultEffort]) => [
8393
+ id,
8394
+ {
8395
+ efforts: ["low", "medium", "high", "xhigh", "max"],
8396
+ defaultEffort,
8397
+ contextWindowTokens: 1_000_000,
8398
+ maxOutputTokens: 128_000,
8399
+ },
8400
+ ]),
8401
+ ...["claude-opus-4-6", "claude-sonnet-4-6"].map((id) => [
8402
+ id,
8403
+ {
8404
+ efforts: ["low", "medium", "high", "max"],
8405
+ defaultEffort: "high",
8406
+ contextWindowTokens: 1_000_000,
8407
+ maxOutputTokens: 128_000,
8408
+ },
8409
+ ]),
8410
+ [
8411
+ "claude-haiku-4-5-20251001",
8412
+ {
8413
+ efforts: [],
8414
+ defaultEffort: null,
8415
+ contextWindowTokens: 200_000,
8416
+ maxOutputTokens: 64_000,
8417
+ },
8418
+ ],
8419
+ ]);
8420
+ export function claudeNativeModelProfile(upstreamModelId: string) {
8421
+ return Object.hasOwn(CLAUDE_NATIVE_MODEL_PROFILES, upstreamModelId)
8422
+ ? CLAUDE_NATIVE_MODEL_PROFILES[upstreamModelId]
8423
+ : undefined;
8424
+ }
8110
8425
  export function claudeProviderId(
8111
8426
  kind: ClaudeConnectionKind,
8112
8427
  scope: "workspace" | "organization" = "organization",
@@ -8148,19 +8463,21 @@ export function withClaudeConnectionCatalog(
8148
8463
  anthropic: {
8149
8464
  auth: kind === "anthropic" ? "api-key" : "oauth",
8150
8465
  cacheTtl: "5m",
8151
- maxOutputTokens: 32000,
8466
+ maxOutputTokens: 128000,
8152
8467
  streamIdleTimeoutMs: 600000,
8153
8468
  },
8154
8469
  models: connection.models.map((model) => {
8155
- // Only captured adaptive-thinking models are enabled by the managed catalog.
8156
- // Operators can explicitly declare other capabilities in a registry provider.
8157
- const adaptiveThinking = ["claude-opus-5-5", "claude-sonnet-5-5"].includes(
8158
- model.upstreamModelId,
8159
- );
8470
+ const profile = claudeNativeModelProfile(model.upstreamModelId);
8471
+ const adaptiveThinking = Boolean(profile?.efforts.length);
8472
+ const contextWindowTokens = profile?.contextWindowTokens ?? 200_000;
8473
+ const outputReserve = profile?.maxOutputTokens ?? 32_000;
8160
8474
  return {
8161
- contextWindowTokens: 200000,
8162
- effectiveContextWindowTokens: 168000,
8163
- autoCompactTokenLimit: 150000,
8475
+ contextWindowTokens,
8476
+ effectiveContextWindowTokens: contextWindowTokens - outputReserve,
8477
+ autoCompactTokenLimit:
8478
+ contextWindowTokens === 1_000_000
8479
+ ? 800_000
8480
+ : Math.min(150_000, contextWindowTokens - outputReserve - 18_000),
8164
8481
  id: id + "/" + model.upstreamModelId,
8165
8482
  upstreamModelId: model.upstreamModelId,
8166
8483
  label:
@@ -8182,8 +8499,8 @@ export function withClaudeConnectionCatalog(
8182
8499
  reasoning: {
8183
8500
  upstream: adaptiveThinking ? "supported" : "unknown",
8184
8501
  runnable: adaptiveThinking,
8185
- efforts: adaptiveThinking ? ["low", "medium", "high"] : [],
8186
- defaultEffort: adaptiveThinking ? "high" : null,
8502
+ efforts: [...(profile?.efforts ?? [])],
8503
+ defaultEffort: profile?.defaultEffort ?? null,
8187
8504
  required: false,
8188
8505
  },
8189
8506
  functionCalling: { upstream: "supported", runnable: true },
@@ -8239,3 +8556,5 @@ export function withClaudeConnectionCredential(
8239
8556
  }
8240
8557
  export * from "./claude-subscription-usage";
8241
8558
  export * from "./claude-subscription-oauth";
8559
+ export * from "./subscription-account-selection";
8560
+ export * from "./claude-subscription-capacity";
@@ -0,0 +1,36 @@
1
+ /** Stable account affinity shared by subscription providers. Candidate order is durable creation order. */
2
+ export function subscriptionAccountShardIndex(sessionId: string, candidateCount: number): number {
3
+ if (!Number.isSafeInteger(candidateCount) || candidateCount <= 0)
4
+ throw new Error("Subscription shard candidate count must be positive");
5
+ let hash = 0x811c9dc5;
6
+ for (let index = 0; index < sessionId.length; index += 1) {
7
+ hash ^= sessionId.charCodeAt(index);
8
+ hash = Math.imul(hash, 0x01000193);
9
+ }
10
+ return (hash >>> 0) % candidateCount;
11
+ }
12
+
13
+ /**
14
+ * Manual pins are binding even when unavailable. Policy homes remain sticky only
15
+ * while rotation is on; an exhausted home re-shards over the eligible survivors.
16
+ * Selection never changes the pool's active pointer.
17
+ */
18
+ export function selectSubscriptionAccount<T extends { id: string }>(input: {
19
+ sessionId: string;
20
+ eligible: readonly T[];
21
+ rotationEnabled: boolean;
22
+ activeCredentialId: string | null;
23
+ pinnedCredentialId: string | null;
24
+ pinSource: "manual" | "policy" | null;
25
+ }): T | null {
26
+ const pinned = input.eligible.find((account) => account.id === input.pinnedCredentialId);
27
+ if (input.pinnedCredentialId && input.pinSource !== "policy") return pinned ?? null;
28
+ if (!input.rotationEnabled)
29
+ return input.eligible.find((account) => account.id === input.activeCredentialId) ?? null;
30
+ return (
31
+ pinned ??
32
+ (input.eligible.length
33
+ ? input.eligible[subscriptionAccountShardIndex(input.sessionId, input.eligible.length)]!
34
+ : null)
35
+ );
36
+ }