@opengeni/config 1.0.0-canary.6 → 1.0.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/dist/index.js CHANGED
@@ -1,13 +1,24 @@
1
+ // src/managed-user-admission.ts
2
+ function managedUserEmailAllowed(allowedUserEmails, email) {
3
+ return allowedUserEmails === void 0 || typeof email === "string" && allowedUserEmails.some((allowed2) => allowed2.toLowerCase() === email.trim().toLowerCase());
4
+ }
5
+
1
6
  // src/index.ts
7
+ import { isRetiredNativeAtlassianTool } from "@opengeni/contracts/atlassian-native-retirement";
2
8
  import {
9
+ directModelConnectionSpec,
3
10
  BillingMode,
4
11
  CAPABILITY_DESCRIPTORS,
12
+ agentConfigDeploymentLimitsFromAllowlist,
5
13
  DEFAULT_FIRST_PARTY_MCP_TOOLS,
14
+ DEFAULT_OPENGENI_DOCUMENTATION_URL,
15
+ currentAgentLearningToolSelection,
6
16
  Entitlements,
7
17
  EntitlementsMode,
8
18
  KnowledgeSourceSyncLimits,
9
19
  LatencyMode,
10
20
  MAX_NESTED_AGENT_DEPTH,
21
+ McpServerConnectionRef as PublicMcpServerConnectionRef,
11
22
  ProductAccessMode,
12
23
  ReasoningEffort,
13
24
  FIRST_PARTY_MCP_TOOL_NAMES,
@@ -42,7 +53,365 @@ import {
42
53
  } from "@opengeni/xai-subscription";
43
54
  import { XAI_SUBSCRIPTION_MODEL_ID_PREFIX as XAI_SUBSCRIPTION_MODEL_ID_PREFIX2 } from "@opengeni/xai-subscription";
44
55
  import { createHash } from "crypto";
56
+ import { isIP } from "net";
57
+ import { z as z2 } from "zod";
58
+
59
+ // src/claude-subscription-usage.ts
60
+ import {
61
+ ClaudeUsageWindowId
62
+ } from "@opengeni/contracts";
63
+ var prefixes = {
64
+ five_hour: ["5h"],
65
+ seven_day: ["7d"],
66
+ seven_day_opus: ["7d-opus"],
67
+ seven_day_sonnet: ["7d-sonnet"],
68
+ seven_day_overage_included: ["7d_oi", "7d-overage-included"],
69
+ overage: ["overage"]
70
+ };
71
+ function percent(value, scale) {
72
+ if (typeof value !== "number" && (typeof value !== "string" || !value.trim())) return null;
73
+ const number = Number(value) * scale;
74
+ return Number.isFinite(number) && number >= 0 ? number : null;
75
+ }
76
+ function epoch(value) {
77
+ if (!value || !/^\d+(?:\.\d+)?$/.test(value)) return null;
78
+ const time = Number(value) * 1e3;
79
+ return Number.isFinite(time) && time > 0 && time < 864e13 ? new Date(time).toISOString() : null;
80
+ }
81
+ function status(value) {
82
+ return value === "allowed" || value === "allowed_warning" || value === "rejected" ? value : null;
83
+ }
84
+ function latestReset(left, right, observedAt) {
85
+ return new Date(
86
+ Math.max(
87
+ left ? Date.parse(left) : Date.parse(observedAt) + 6e4,
88
+ right ? Date.parse(right) : Date.parse(observedAt) + 6e4
89
+ )
90
+ ).toISOString();
91
+ }
92
+ function evidenceKey(item) {
93
+ return JSON.stringify([
94
+ item.upstreamModelId,
95
+ item.upstreamModelId ? null : item.representativeClaim,
96
+ item.source === "provider"
97
+ ]);
98
+ }
99
+ function tiedRequest(left, right) {
100
+ const denied = left.status === "rejected" ? left : right.status === "rejected" ? right : null;
101
+ return {
102
+ ...denied ?? left,
103
+ resetsAt: denied ? latestReset(
104
+ left.status === "rejected" ? left.resetsAt : denied.resetsAt,
105
+ right.status === "rejected" ? right.resetsAt : denied.resetsAt,
106
+ left.observedAt
107
+ ) : null,
108
+ representativeClaim: left.representativeClaim === right.representativeClaim ? left.representativeClaim : null,
109
+ status: denied ? "rejected" : null,
110
+ overageStatus: null,
111
+ overageResetsAt: null
112
+ };
113
+ }
114
+ function parseClaudeUsageHeaders(headers, now = /* @__PURE__ */ new Date(), upstreamModelId) {
115
+ const observedAt = now.toISOString();
116
+ const claim = ClaudeUsageWindowId.safeParse(
117
+ headers.get("anthropic-ratelimit-unified-representative-claim")
118
+ );
119
+ const claimedStatus = status(headers.get("anthropic-ratelimit-unified-status"));
120
+ const claimedReset = epoch(headers.get("anthropic-ratelimit-unified-reset"));
121
+ const overageStatus = status(headers.get("anthropic-ratelimit-unified-overage-status"));
122
+ const overageResetsAt = epoch(headers.get("anthropic-ratelimit-unified-overage-reset"));
123
+ const windows = ClaudeUsageWindowId.options.flatMap((id) => {
124
+ const header = (suffix) => prefixes[id].map(
125
+ (prefix) => headers.get(`anthropic-ratelimit-unified-${prefix}-${suffix}`)
126
+ ).find((value) => value !== null) ?? null;
127
+ const representative = claim.success && claim.data === id;
128
+ const usedPercent = percent(header("utilization"), 100);
129
+ const resetsAt = epoch(header("reset")) ?? (representative ? claimedReset : null);
130
+ const windowStatus = status(header("status")) ?? (representative ? claimedStatus : null);
131
+ if (usedPercent === null && resetsAt === null && windowStatus === null) return [];
132
+ return [{ id, usedPercent, resetsAt, status: windowStatus, observedAt }];
133
+ });
134
+ return windows.length || claimedStatus || overageStatus ? {
135
+ windows,
136
+ observedAt,
137
+ source: "response_headers",
138
+ requestStatus: {
139
+ status: claimedStatus,
140
+ resetsAt: claimedReset,
141
+ representativeClaim: claim.success ? claim.data : null,
142
+ overageStatus,
143
+ overageResetsAt,
144
+ upstreamModelId: upstreamModelId ?? null,
145
+ observedAt
146
+ }
147
+ } : null;
148
+ }
149
+ function parseClaudeUsageResponse(value, now = /* @__PURE__ */ new Date()) {
150
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
151
+ const observedAt = now.toISOString();
152
+ const windows = ClaudeUsageWindowId.options.flatMap((id) => {
153
+ const window = value[id];
154
+ if (!window || typeof window !== "object" || Array.isArray(window)) return [];
155
+ const fields = window;
156
+ const usedPercent = percent(fields.utilization, 1);
157
+ const time = typeof fields.resets_at === "string" ? Date.parse(fields.resets_at) : NaN;
158
+ const resetsAt = Number.isFinite(time) ? new Date(time).toISOString() : null;
159
+ if (usedPercent === null && resetsAt === null) return [];
160
+ return [{ id, usedPercent, resetsAt, status: null, observedAt }];
161
+ });
162
+ return windows.length ? { windows, observedAt, source: "provider" } : null;
163
+ }
164
+ function emptyClaudeUsage(credentialVersion) {
165
+ return {
166
+ connected: credentialVersion !== null,
167
+ credentialVersion,
168
+ windows: [],
169
+ observedAt: null,
170
+ source: null,
171
+ refreshStatus: "not_checked",
172
+ refreshCheckedAt: null
173
+ };
174
+ }
175
+ function mergeClaudeUsage(current, observation) {
176
+ const windows = new Map(current.windows.map((window) => [window.id, window]));
177
+ for (const incomingWindow of observation.windows) {
178
+ const window = { ...incomingWindow, source: incomingWindow.source ?? observation.source };
179
+ const previous = windows.get(window.id);
180
+ if (!previous || previous.observedAt < window.observedAt) windows.set(window.id, window);
181
+ else if (previous.observedAt === window.observedAt && JSON.stringify(previous) !== JSON.stringify(window)) {
182
+ const rejected = previous.status === "rejected" || window.status === "rejected";
183
+ const full = (previous.usedPercent ?? 0) >= 100 || (window.usedPercent ?? 0) >= 100;
184
+ windows.set(window.id, {
185
+ ...previous,
186
+ usedPercent: previous.usedPercent === null ? window.usedPercent : window.usedPercent === null ? previous.usedPercent : Math.max(previous.usedPercent, window.usedPercent),
187
+ status: rejected ? "rejected" : previous.status === window.status ? previous.status : null,
188
+ resetsAt: rejected || full ? latestReset(previous.resetsAt, window.resetsAt, window.observedAt) : previous.resetsAt === window.resetsAt ? previous.resetsAt : null,
189
+ source: previous.source === "response_headers" || window.source === "response_headers" ? "response_headers" : "provider"
190
+ });
191
+ }
192
+ }
193
+ const incoming = observation.requestStatus;
194
+ const restrictions = new Map(
195
+ (current.requestRestrictions ?? []).map((item) => [evidenceKey(item), item])
196
+ );
197
+ for (const item of [
198
+ current.requestStatus?.status ? current.requestStatus : null,
199
+ ...observation.requestRestrictions ?? [],
200
+ incoming?.status ? incoming : null
201
+ ]) {
202
+ if (!item) continue;
203
+ const key = evidenceKey(item);
204
+ const previous = restrictions.get(key);
205
+ const sanitized = {
206
+ ...item,
207
+ overageStatus: null,
208
+ overageResetsAt: null
209
+ };
210
+ if (!previous || item.observedAt > previous.observedAt) restrictions.set(key, sanitized);
211
+ else if (item.observedAt === previous.observedAt && JSON.stringify(previous) !== JSON.stringify(sanitized))
212
+ restrictions.set(key, tiedRequest(previous, sanitized));
213
+ }
214
+ const directWindows = [
215
+ ...current.windows.filter(
216
+ (window) => window.source === "provider" || !window.source && current.source === "provider" && current.observedAt === window.observedAt
217
+ ),
218
+ ...observation.windows.filter((window) => (window.source ?? observation.source) === "provider")
219
+ ];
220
+ for (const window of directWindows) {
221
+ if (window.usedPercent === null || window.usedPercent >= 100) continue;
222
+ const proof = {
223
+ status: null,
224
+ resetsAt: null,
225
+ representativeClaim: window.id,
226
+ upstreamModelId: null,
227
+ overageStatus: null,
228
+ overageResetsAt: null,
229
+ observedAt: window.observedAt,
230
+ source: "provider"
231
+ };
232
+ const key = evidenceKey(proof);
233
+ if (!restrictions.has(key) || restrictions.get(key).observedAt < proof.observedAt)
234
+ restrictions.set(key, proof);
235
+ }
236
+ for (const [key, item] of restrictions) {
237
+ if (item.status !== "rejected") continue;
238
+ const proof = [...restrictions.values()].find(
239
+ (candidate) => candidate.source === "provider" && candidate.representativeClaim === item.representativeClaim && candidate.observedAt > item.observedAt && candidate.representativeClaim !== "overage" && candidate.representativeClaim !== "seven_day_overage_included"
240
+ );
241
+ if (proof)
242
+ restrictions.set(key, {
243
+ ...item,
244
+ status: null,
245
+ resetsAt: null,
246
+ observedAt: proof.observedAt
247
+ });
248
+ }
249
+ let requestRestrictions = [...restrictions.values()];
250
+ const evidenceTime = requestRestrictions.reduce(
251
+ (value, item) => item.observedAt > value ? item.observedAt : value,
252
+ observation.observedAt
253
+ );
254
+ const liveDenials = requestRestrictions.filter(
255
+ (item) => item.status === "rejected" && (item.resetsAt ? Date.parse(item.resetsAt) : Date.parse(item.observedAt) + 6e4) > Date.parse(evidenceTime)
256
+ );
257
+ if (requestRestrictions.length > 64 && liveDenials.length === 0) {
258
+ requestRestrictions = requestRestrictions.sort((left, right) => right.observedAt.localeCompare(left.observedAt)).slice(0, 64);
259
+ } else if (requestRestrictions.length > 64) {
260
+ const observedAt = evidenceTime;
261
+ const resetsAt = new Date(
262
+ Math.max(
263
+ ...liveDenials.map(
264
+ (item) => item.resetsAt ? Date.parse(item.resetsAt) : Date.parse(item.observedAt) + 6e4
265
+ ),
266
+ Date.parse(observedAt) + 6e4
267
+ )
268
+ ).toISOString();
269
+ requestRestrictions = [
270
+ {
271
+ status: "rejected",
272
+ resetsAt,
273
+ representativeClaim: null,
274
+ overageStatus: null,
275
+ overageResetsAt: null,
276
+ upstreamModelId: null,
277
+ observedAt
278
+ }
279
+ ];
280
+ }
281
+ const newest = !current.observedAt || current.observedAt < observation.observedAt;
282
+ const tied = current.observedAt === observation.observedAt;
283
+ let requestStatus = current.requestStatus ?? null;
284
+ if (newest) requestStatus = incoming ?? null;
285
+ else if (tied && JSON.stringify(requestStatus) !== JSON.stringify(incoming ?? null)) {
286
+ requestStatus = incoming && requestStatus && evidenceKey(incoming) === evidenceKey(requestStatus) ? tiedRequest(requestStatus, incoming) : null;
287
+ }
288
+ return {
289
+ ...current,
290
+ requestRestrictions,
291
+ requestStatus,
292
+ windows: ClaudeUsageWindowId.options.flatMap(
293
+ (id) => windows.has(id) ? [windows.get(id)] : []
294
+ ),
295
+ ...newest ? {
296
+ observedAt: observation.observedAt,
297
+ source: observation.source
298
+ // A newer direct or partial observation cannot retain an older paid
299
+ // fallback authorization. Window readings remain independently merged.
300
+ } : {}
301
+ };
302
+ }
303
+
304
+ // src/claude-subscription-oauth.ts
45
305
  import { z } from "zod";
306
+ var CLAUDE_OAUTH_CLIENT_ID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";
307
+ var CLAUDE_OAUTH_AUTHORIZE_URL = "https://claude.com/cai/oauth/authorize";
308
+ var CLAUDE_OAUTH_TOKEN_URL = "https://platform.claude.com/v1/oauth/token";
309
+ var CLAUDE_OAUTH_REDIRECT_URL = "https://platform.claude.com/oauth/code/callback";
310
+ var CLAUDE_OAUTH_SCOPES = ["user:inference", "user:profile"];
311
+ var ClaudeOAuthTokenResponse = z.object({
312
+ access_token: z.string().max(16384).regex(/^sk-ant-oat[0-9]+-\S+$/),
313
+ refresh_token: z.string().min(1).max(16384).optional(),
314
+ expires_in: z.number().int().positive().max(31536e3),
315
+ scope: z.string().min(1).max(8192)
316
+ }).passthrough();
317
+ function claudeAuthorizationUrl(input) {
318
+ const url = new URL(CLAUDE_OAUTH_AUTHORIZE_URL);
319
+ url.searchParams.set("code", "true");
320
+ url.searchParams.set("client_id", CLAUDE_OAUTH_CLIENT_ID);
321
+ url.searchParams.set("response_type", "code");
322
+ url.searchParams.set("redirect_uri", CLAUDE_OAUTH_REDIRECT_URL);
323
+ url.searchParams.set("scope", CLAUDE_OAUTH_SCOPES.join(" "));
324
+ url.searchParams.set("code_challenge", input.challenge);
325
+ url.searchParams.set("code_challenge_method", "S256");
326
+ url.searchParams.set("state", input.state);
327
+ return url.toString();
328
+ }
329
+
330
+ // src/subscription-account-selection.ts
331
+ function subscriptionAccountShardIndex(sessionId, candidateCount) {
332
+ if (!Number.isSafeInteger(candidateCount) || candidateCount <= 0)
333
+ throw new Error("Subscription shard candidate count must be positive");
334
+ let hash = 2166136261;
335
+ for (let index = 0; index < sessionId.length; index += 1) {
336
+ hash ^= sessionId.charCodeAt(index);
337
+ hash = Math.imul(hash, 16777619);
338
+ }
339
+ return (hash >>> 0) % candidateCount;
340
+ }
341
+ function selectSubscriptionAccount(input) {
342
+ const pinned = input.eligible.find((account) => account.id === input.pinnedCredentialId);
343
+ if (input.pinnedCredentialId && input.pinSource !== "policy") return pinned ?? null;
344
+ if (!input.rotationEnabled)
345
+ return input.eligible.find((account) => account.id === input.activeCredentialId) ?? null;
346
+ return pinned ?? (input.eligible.length ? input.eligible[subscriptionAccountShardIndex(input.sessionId, input.eligible.length)] : null);
347
+ }
348
+
349
+ // src/claude-subscription-capacity.ts
350
+ var UNKNOWN_RESET_RECHECK_MS = 6e4;
351
+ var allowed = (status2) => status2 === "allowed" || status2 === "allowed_warning";
352
+ function claudeSubscriptionCapacity(usage, upstreamModelId, now, options = {}) {
353
+ const available = { available: true, nextCheckAt: null, blockingWindows: [] };
354
+ if (!usage.connected || usage.refreshStatus === "reconnect")
355
+ return { ...available, available: false };
356
+ const relevant = (id) => {
357
+ if (id === "seven_day_opus") return /^claude-opus-/.test(upstreamModelId);
358
+ if (id === "seven_day_sonnet") return /^claude-sonnet-/.test(upstreamModelId);
359
+ return id === "five_hour" || id === "seven_day";
360
+ };
361
+ const applicable = usage.windows.filter((window) => relevant(window.id));
362
+ const relevantClaim = (id) => id === "seven_day_opus" || id === "seven_day_sonnet" ? relevant(id) : true;
363
+ const restrictions = (usage.requestRestrictions ?? []).filter(
364
+ (item) => item.status === "rejected" && (item.upstreamModelId === upstreamModelId || item.upstreamModelId === null && relevantClaim(item.representativeClaim)) && !applicable.some(
365
+ (window) => window.source === "provider" && window.usedPercent !== null && window.usedPercent < 100 && window.id === item.representativeClaim && window.observedAt > item.observedAt
366
+ ) && (item.resetsAt ? Date.parse(item.resetsAt) : Date.parse(item.observedAt) + UNKNOWN_RESET_RECHECK_MS) > now.getTime()
367
+ );
368
+ const blocking = applicable.filter((window) => {
369
+ if ((window.resetsAt ? Date.parse(window.resetsAt) : Date.parse(window.observedAt) + UNKNOWN_RESET_RECHECK_MS) <= now.getTime())
370
+ return false;
371
+ return window.status === "rejected" || window.status === null && (window.usedPercent ?? 0) >= 100;
372
+ });
373
+ const request = usage.requestStatus;
374
+ const exactModel = request?.upstreamModelId === upstreamModelId;
375
+ const relevantRequest = request && (exactModel || request.upstreamModelId === null && relevantClaim(request.representativeClaim));
376
+ const freshRequest = relevantRequest && applicable.every((window) => window.observedAt <= request.observedAt) && restrictions.every((item) => item.observedAt <= request.observedAt);
377
+ const planResetElapsed = request && (request.resetsAt ? Date.parse(request.resetsAt) : Date.parse(request.observedAt) + UNKNOWN_RESET_RECHECK_MS) <= now.getTime();
378
+ const exactAllowance = (usage.requestRestrictions ?? []).find(
379
+ (item) => item.upstreamModelId === upstreamModelId && allowed(item.status) && blocking.every((window) => window.observedAt < item.observedAt) && restrictions.every((restriction) => restriction.observedAt < item.observedAt)
380
+ );
381
+ if (exactAllowance) return available;
382
+ if (freshRequest && exactModel && allowed(request.status) && !planResetElapsed) return available;
383
+ const mayUseOverage = options.allowOverage !== false;
384
+ const overageResetElapsed = request?.overageResetsAt && Date.parse(request.overageResetsAt) <= now.getTime();
385
+ if (freshRequest && request.status === "rejected" && mayUseOverage && allowed(request.overageStatus) && !overageResetElapsed)
386
+ return available;
387
+ const rejectedRequest = freshRequest && request.status === "rejected" && !planResetElapsed;
388
+ if (blocking.length === 0 && !rejectedRequest && restrictions.length === 0) return available;
389
+ const resets = blocking.map(
390
+ (window) => window.resetsAt ? Date.parse(window.resetsAt) : Date.parse(window.observedAt) + UNKNOWN_RESET_RECHECK_MS
391
+ );
392
+ if (rejectedRequest)
393
+ resets.push(
394
+ request.resetsAt ? Date.parse(request.resetsAt) : Date.parse(request.observedAt) + UNKNOWN_RESET_RECHECK_MS
395
+ );
396
+ resets.push(
397
+ ...restrictions.map(
398
+ (item) => item.resetsAt ? Date.parse(item.resetsAt) : Date.parse(item.observedAt) + UNKNOWN_RESET_RECHECK_MS
399
+ )
400
+ );
401
+ let nextCheckAt = Math.max(...resets);
402
+ if (rejectedRequest && mayUseOverage && request.overageStatus === "rejected" && request.overageResetsAt) {
403
+ const overageReset = Date.parse(request.overageResetsAt);
404
+ if (overageReset <= now.getTime()) return available;
405
+ nextCheckAt = Math.min(nextCheckAt, overageReset);
406
+ }
407
+ return {
408
+ available: false,
409
+ nextCheckAt: new Date(nextCheckAt),
410
+ blockingWindows: blocking.map((window) => window.id)
411
+ };
412
+ }
413
+
414
+ // src/index.ts
46
415
  var envName = /^[A-Za-z_][A-Za-z0-9_]*$/;
47
416
  var registryId = /^[A-Za-z0-9_-]+$/;
48
417
  var DEFAULT_OPENROUTER_MODEL_ID = "openrouter/nvidia/nemotron-3-super-120b-a12b:free";
@@ -51,12 +420,13 @@ var DEFAULT_MODEL_COST_POLICY_JSON = JSON.stringify({
51
420
  });
52
421
  var SANDBOX_ARCHIVE_CAPTURE_MAX_TIMEOUT_MS = 60 * 6e4;
53
422
  var SANDBOX_ARCHIVE_CAPTURE_SETTLEMENT_GRACE_MS = 1e4;
423
+ var SANDBOX_DEADLINE_COMMAND_STOP_GRACE_MS = 12e4;
54
424
  var SANDBOX_SNAPSHOT_MAX_TIMEOUT_MS = SANDBOX_ARCHIVE_CAPTURE_MAX_TIMEOUT_MS - SANDBOX_ARCHIVE_CAPTURE_SETTLEMENT_GRACE_MS;
55
425
  var GOOGLE_DRIVE_PROVIDER_REQUEST_TIMEOUT_MAX_MS = 6e4;
56
426
  var GOOGLE_DRIVE_PROVIDER_RETRY_DELAY_MAX_MS = 6e4;
57
427
  var SANDBOX_LIFECYCLE_TRANSITION_MAX_WAIT_MS = 60 * 6e4;
58
428
  var SANDBOX_LIFECYCLE_RETRY_HANDOFF_GRACE_MS = 1e4;
59
- var EnvBoolean = z.preprocess((value) => {
429
+ var EnvBoolean = z2.preprocess((value) => {
60
430
  if (typeof value !== "string") {
61
431
  return value;
62
432
  }
@@ -68,10 +438,11 @@ var EnvBoolean = z.preprocess((value) => {
68
438
  return false;
69
439
  }
70
440
  return value;
71
- }, z.boolean());
441
+ }, z2.boolean());
442
+ var PublicHttpUrl = z2.string().url().max(2048).refine((value) => /^https?:\/\//iu.test(value), "must be an http(s) URL");
72
443
  var DEFAULT_GOAL_IDLE_BACKOFF_MS = [3e3, 3e4, 12e4, 3e5];
73
444
  var DEFAULT_GOAL_IDLE_BACKOFF_MAX_MS = 6e5;
74
- var EnvGoalIdleBackoffMs = z.preprocess((value) => {
445
+ var EnvGoalIdleBackoffMs = z2.preprocess((value) => {
75
446
  if (typeof value !== "string") return value;
76
447
  const source = value.trim();
77
448
  if (!source) return void 0;
@@ -79,8 +450,8 @@ var EnvGoalIdleBackoffMs = z.preprocess((value) => {
79
450
  const trimmed = entry.trim();
80
451
  return trimmed === "" ? Number.NaN : Number(trimmed);
81
452
  });
82
- }, z.array(z.number().int().nonnegative()).min(1, "OPENGENI_GOAL_IDLE_BACKOFF_MS must list at least one delay in milliseconds").readonly());
83
- var EnvFirstPartyMcpTools = z.preprocess(
453
+ }, z2.array(z2.number().int().nonnegative()).min(1, "OPENGENI_GOAL_IDLE_BACKOFF_MS must list at least one delay in milliseconds").readonly());
454
+ var EnvFirstPartyMcpTools = z2.preprocess(
84
455
  (value) => {
85
456
  if (typeof value !== "string") return value;
86
457
  const source = value.trim();
@@ -94,7 +465,7 @@ var EnvFirstPartyMcpTools = z.preprocess(
94
465
  }
95
466
  return source.split(",").map((entry) => entry.trim());
96
467
  },
97
- z.array(FirstPartyMcpToolName).superRefine((tools, context) => {
468
+ z2.array(FirstPartyMcpToolName).superRefine((tools, context) => {
98
469
  const seen = /* @__PURE__ */ new Set();
99
470
  for (const [index, tool] of tools.entries()) {
100
471
  if (seen.has(tool)) {
@@ -141,149 +512,140 @@ var sandboxPreparationProfiles = {
141
512
  };
142
513
  var AGENT_INSTRUCTIONS_CORE_PLACEHOLDER = "{{core}}";
143
514
  var DEFAULT_AGENT_INSTRUCTIONS = [
144
- "You are an OpenGeni workspace agent.",
145
- "Follow the user's task and any enabled pack or skill instructions for the current role.",
146
- "Work inside the sandbox workspace and use filesystem and shell tools when useful.",
515
+ "You are an OpenGeni workspace agent: a general assistant for questions, writing, research, analysis, and technical work.",
516
+ "Follow the user's task and the applicable Skill instructions for the current role.",
517
+ "When a task needs files or commands, work inside the sandbox workspace with the filesystem and shell tools.",
147
518
  "Repository resources are mounted under repos/<host>/<owner>/<repo> unless the session specifies another collision-free mount path.",
148
519
  "File resources are mounted under .opengeni/files/<file-id>/ unless the session specifies another mount path.",
149
520
  "Attached files are mounted read-only; copy them before modifying.",
150
- "Installed and selected Skills are indexed under .agents/ and may include role-specific guidance.",
151
- "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.",
152
- "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.",
153
- "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.",
154
- "Return concise, factual summaries with files changed, commands run, and remaining blockers.",
521
+ "Installed and selected Skills appear in the session Skill index; follow its reading instructions and any role-specific guidance.",
522
+ "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.",
523
+ "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.",
524
+ "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.",
525
+ "Answer questions directly and briefly; after making changes, say what changed, how you checked it, and anything still blocked.",
155
526
  AGENT_INSTRUCTIONS_CORE_PLACEHOLDER
156
527
  ].join(" ");
157
- var McpServerConnectionRefSchema = z.object({
158
- // Standalone ids are UUIDs; embedded hosts may use any stable opaque id.
159
- connectionId: z.string().min(1).optional(),
160
- provider: z.string().min(1).max(128).optional(),
161
- providerDomain: z.string().min(1),
162
- kind: z.enum(["oauth2", "api_key", "app_install", "delegated"]).optional(),
163
- scopes: z.array(z.string().min(1)).optional(),
164
- resource: z.string().min(1).optional(),
165
- selectedResources: z.array(
166
- z.object({
167
- id: z.string().min(1).max(512),
168
- kind: z.literal("repository")
169
- }).strict()
170
- ).min(1).max(256).superRefine((resources, context) => {
171
- const seen = /* @__PURE__ */ new Set();
172
- for (const [index, resource] of resources.entries()) {
173
- const key = `${resource.kind}\0${resource.id}`;
174
- if (seen.has(key)) {
175
- context.addIssue({
176
- code: "custom",
177
- message: "selectedResources must not contain duplicates",
178
- path: [index]
179
- });
180
- }
181
- seen.add(key);
528
+ var McpServerConnectionRefSchema = PublicMcpServerConnectionRef;
529
+ var McpOperationRecoverySchema = z2.record(
530
+ z2.string().min(1).max(512).regex(/^\S+$/u),
531
+ z2.object({ observerTool: z2.string().min(1).max(512).regex(/^\S+$/u) }).strict()
532
+ ).superRefine((bindings, context) => {
533
+ for (const [originalTool, binding] of Object.entries(bindings)) {
534
+ if (originalTool === binding.observerTool) {
535
+ context.addIssue({
536
+ code: "custom",
537
+ path: [originalTool, "observerTool"],
538
+ message: "MCP recovery observer must differ from the original tool"
539
+ });
182
540
  }
183
- }).optional(),
184
- authoritySource: z.literal("host").optional(),
185
- subjectScope: z.enum(["workspace", "subject"]).optional()
186
- }).strict().superRefine((reference, context) => {
187
- if (reference.authoritySource === "host" && !reference.connectionId) {
188
- context.addIssue({
189
- code: "custom",
190
- message: "host authority requires connectionId",
191
- path: ["connectionId"]
192
- });
193
- }
194
- if (!reference.selectedResources) return;
195
- if (!reference.connectionId) {
196
- context.addIssue({
197
- code: "custom",
198
- message: "selectedResources requires connectionId",
199
- path: ["connectionId"]
200
- });
201
- }
202
- if (!reference.provider) {
203
- context.addIssue({
204
- code: "custom",
205
- message: "selectedResources requires provider",
206
- path: ["provider"]
207
- });
208
541
  }
209
542
  });
210
- var DEFAULT_MODAL_IMAGE_REF = "opengenipublicneuacr.azurecr.io/opengeni-desktop@sha256:c3bd17b8841de1bff9bb2777aad422cf8c75de78e2c30f9ac81d0cd6810a1b78";
211
- var SettingsSchema = z.object({
212
- serviceName: z.string().default("opengeni"),
213
- environment: z.string().default("local"),
214
- deploymentRevision: z.string().default("dev"),
543
+ var DEFAULT_MODAL_IMAGE_REF = "opengenipublicneuacr.azurecr.io/opengeni-desktop@sha256:554d5b324a580071dd669e7c1190931e498eb1b397412a27c7de84a430ef393a";
544
+ var SettingsSchema = z2.object({
545
+ serviceName: z2.string().default("opengeni"),
546
+ environment: z2.string().default("local"),
547
+ deploymentRevision: z2.string().default("dev"),
215
548
  // The release-train version baked into official images (OPENGENI_SERVER_VERSION).
216
549
  // Absent on dev/source builds — consumers must treat it as optional.
217
- serverVersion: z.string().optional(),
218
- databaseUrl: z.string().default("postgres://opengeni:opengeni@127.0.0.1:5432/opengeni"),
550
+ serverVersion: z2.string().optional(),
551
+ databaseUrl: z2.string().default("postgres://opengeni:opengeni@127.0.0.1:5432/opengeni"),
552
+ // API application pool only. Managed auth owns its separate pool; readiness
553
+ // reuses the application handle. Keep the historical default for existing
554
+ // deployments and let operators budget this per process with replica counts.
555
+ apiDatabasePoolMax: z2.coerce.number().int().positive().default(32),
219
556
  // Step I (§7.8 runtime half). Dedicated Postgres schema for the EMBEDDED
220
557
  // topology. Default "" → standalone: no search_path scoping, server default
221
558
  // (`public`). When set (e.g. "opengeni"), the db handle + the managed-auth
222
559
  // pool send `search_path = "<dbSchema>","opengeni_private","public"` so every
223
560
  // query resolves into the dedicated schema with NO query rewrite (schema-isolation contract F1).
224
- dbSchema: z.string().default(""),
561
+ dbSchema: z2.string().default(""),
225
562
  // Step I (§7.7). RLS posture. "force" (default) = today's FORCE-RLS via the
226
563
  // non-owner `opengeni_app` role. "scoped" = the embedded owner-role path (the
227
564
  // GUC is still emitted defensively, so the query path is identical).
228
- rlsStrategy: z.enum(["force", "scoped"]).default("force"),
565
+ rlsStrategy: z2.enum(["force", "scoped"]).default("force"),
229
566
  // Exact PostgreSQL login identity required by the standalone FORCE-RLS
230
567
  // startup/readiness assertion. Embedded `scoped` hosts own their role model
231
568
  // and are deliberately not constrained to this name.
232
- runtimeDatabaseRole: z.string().min(1).default("opengeni_app"),
233
- natsUrl: z.string().default("nats://127.0.0.1:4222"),
234
- temporalHost: z.string().default("127.0.0.1:7233"),
235
- temporalNamespace: z.string().default("default"),
236
- temporalTaskQueue: z.string().default("opengeni-runs-ts"),
569
+ runtimeDatabaseRole: z2.string().min(1).default("opengeni_app"),
570
+ natsUrl: z2.string().default("nats://127.0.0.1:4222"),
571
+ temporalHost: z2.string().default("127.0.0.1:7233"),
572
+ temporalNamespace: z2.string().default("default"),
573
+ temporalTaskQueue: z2.string().default("opengeni-runs-ts"),
237
574
  temporalTlsEnabled: EnvBoolean.default(false),
238
- temporalApiKey: z.string().optional(),
239
- temporalTlsServerName: z.string().optional(),
240
- temporalTlsRootCaCertificateBase64: z.string().optional(),
241
- temporalTlsClientCertificateBase64: z.string().optional(),
242
- temporalTlsClientPrivateKeyBase64: z.string().optional(),
243
- startupDependencyRetryAttempts: z.coerce.number().int().positive().default(30),
244
- startupDependencyRetryInitialDelayMs: z.coerce.number().int().positive().default(1e3),
245
- startupDependencyRetryMaxDelayMs: z.coerce.number().int().positive().default(5e3),
246
- turnWorkerConcurrencyMode: z.enum(["fixed", "resource-based"]).default("fixed"),
247
- turnWorkerMaxConcurrentTurns: z.coerce.number().int().positive().max(2e3).default(16),
248
- turnWorkerTargetCpuUsage: z.coerce.number().positive().max(1).default(0.8),
249
- turnWorkerTargetMemoryUsage: z.coerce.number().positive().max(0.8).default(0.75),
575
+ temporalApiKey: z2.string().optional(),
576
+ temporalTlsServerName: z2.string().optional(),
577
+ temporalTlsRootCaCertificateBase64: z2.string().optional(),
578
+ temporalTlsClientCertificateBase64: z2.string().optional(),
579
+ temporalTlsClientPrivateKeyBase64: z2.string().optional(),
580
+ startupDependencyRetryAttempts: z2.coerce.number().int().positive().default(30),
581
+ startupDependencyRetryInitialDelayMs: z2.coerce.number().int().positive().default(1e3),
582
+ startupDependencyRetryMaxDelayMs: z2.coerce.number().int().positive().default(5e3),
583
+ turnWorkerConcurrencyMode: z2.enum(["fixed", "resource-based"]).default("fixed"),
584
+ turnWorkerMaxConcurrentTurns: z2.coerce.number().int().positive().max(2e3).default(16),
585
+ turnWorkerTargetCpuUsage: z2.coerce.number().positive().max(1).default(0.8),
586
+ turnWorkerTargetMemoryUsage: z2.coerce.number().positive().max(0.8).default(0.75),
250
587
  // Admission and emergency recovery are deliberately separate control loops.
251
588
  // The Temporal tuner stops polling at the lower target; only genuine danger
252
589
  // may invoke the disruptive graceful-drain fallback.
253
- turnWorkerEmergencyMemoryUsage: z.coerce.number().min(0.85).max(0.95).default(0.9),
254
- turnWorkerMemoryGuardIntervalMs: z.coerce.number().int().min(1e3).max(6e4).default(5e3),
255
- turnWorkerMemoryGuardSustainMs: z.coerce.number().int().min(5e3).max(3e5).default(3e4),
590
+ turnWorkerEmergencyMemoryUsage: z2.coerce.number().min(0.85).max(0.95).default(0.9),
591
+ turnWorkerMemoryGuardIntervalMs: z2.coerce.number().int().min(1e3).max(6e4).default(5e3),
592
+ turnWorkerMemoryGuardSustainMs: z2.coerce.number().int().min(5e3).max(3e5).default(3e4),
256
593
  observabilityStructuredLogs: EnvBoolean.default(false),
257
594
  observabilityMetricsEnabled: EnvBoolean.default(true),
258
- observabilityOtlpEndpoint: z.string().url().optional(),
259
- observabilityOtlpHeaders: z.string().default(""),
595
+ observabilityOtlpEndpoint: z2.string().url().optional(),
596
+ observabilityOtlpHeaders: z2.string().default(""),
597
+ observabilityDiagnosticsEndpoint: z2.string().url().optional(),
598
+ observabilityDiagnosticsHeaders: z2.string().default(""),
260
599
  analyticsEnabled: EnvBoolean.default(false),
261
600
  analyticsConsentRequired: EnvBoolean.default(true),
262
- analyticsReoClientId: z.string().max(128).regex(/^[A-Za-z0-9_-]+$/u).optional(),
263
- analyticsPosthogProjectKey: z.string().min(1).max(256).optional(),
264
- analyticsPosthogHost: z.string().url().max(2048).optional(),
265
- analyticsGa4MeasurementId: z.string().max(32).regex(/^G-[A-Z0-9]+$/u).optional(),
266
- publicBaseUrl: z.string().url().optional(),
601
+ analyticsReoClientId: z2.string().max(128).regex(/^[A-Za-z0-9_-]+$/u).optional(),
602
+ analyticsPosthogProjectKey: z2.string().min(1).max(256).optional(),
603
+ analyticsPosthogHost: z2.string().url().max(2048).optional(),
604
+ analyticsGa4MeasurementId: z2.string().max(32).regex(/^G-[A-Z0-9]+$/u).optional(),
605
+ // Optional operator-owned legal documents linked from the signed-out console.
606
+ // Unset by default, so a self-hosted deployment never shows another operator's
607
+ // policies; the managed service points these at its own published pages.
608
+ legalPrivacyPolicyUrl: PublicHttpUrl.optional(),
609
+ legalTermsOfServiceUrl: PublicHttpUrl.optional(),
610
+ // Optional operator support address, shown as a "Contact support" mailto link
611
+ // on the signed-out page and in the Help menu. Unset by default for the same
612
+ // reason as the legal links.
613
+ supportEmail: z2.string().trim().email().max(254).optional(),
614
+ publicBaseUrl: z2.string().url().optional(),
615
+ // Product documentation the web console links from its Help menu. Absent
616
+ // means the public OpenGeni docs; `none` hides the link for deployments that
617
+ // publish no documentation of their own.
618
+ documentationUrl: z2.preprocess(
619
+ (value) => typeof value === "string" ? value.trim().toLowerCase() === "none" ? null : value.trim() : value,
620
+ z2.url({ protocol: /^https?$/u, error: "must be an absolute http(s) URL or none" }).nullable().default(DEFAULT_OPENGENI_DOCUMENTATION_URL)
621
+ ),
267
622
  // Standards-based OAuth authorization server for external workspace MCP
268
623
  // clients. Opt-in because it creates a new public authentication surface.
269
624
  mcpOauthEnabled: EnvBoolean.default(false),
270
- // Forwarded client addresses are ignored by default. Operators may trust an
625
+ // Client source address for every API rate limit, abuse quota, and auth
626
+ // session record (Better Auth, MCP OAuth registration, enrollment, account
627
+ // setup, login transactions). Forwarded client addresses are ignored by
628
+ // default so a caller cannot choose its own bucket. Operators may trust an
271
629
  // exact number of proxy hops only when direct access to the API is blocked.
272
- mcpOauthTrustedProxyHops: z.coerce.number().int().min(0).max(16).default(0),
630
+ apiTrustedProxyHops: z2.coerce.number().int().min(0).max(16).default(0),
631
+ // Optional comma-separated CIDRs (or single addresses) of the proxy that
632
+ // connects to the API. When set, forwarded client addresses are honored
633
+ // only for requests whose transport peer is inside one of them.
634
+ apiTrustedProxyCidrs: z2.string().default(""),
273
635
  // Browser origin when the web app and API use separate origins in local
274
636
  // development. Production normally leaves this unset and uses publicBaseUrl.
275
- webBaseUrl: z.string().url().optional(),
637
+ webBaseUrl: z2.string().url().optional(),
276
638
  // Base URL for the bring-your-own-compute agent release assets the get.<domain>
277
639
  // install routes redirect to. Defaults to this repo's GitHub Releases. The route
278
640
  // appends `/download/agent-v<ver>/<asset>`.
279
- agentReleasesBaseUrl: z.string().url().default("https://github.com/Cloudgeni-ai/opengeni/releases"),
641
+ agentReleasesBaseUrl: z2.string().url().default("https://github.com/Cloudgeni-ai/opengeni/releases"),
280
642
  // Explicit operator-controlled promotion pointer for `/agent/latest/*`.
281
643
  // Versioned agent releases are immutable; changing this setting promotes or
282
644
  // rolls back the stable channel without moving or deleting a provider tag.
283
- agentStableVersion: z.string().regex(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u).default("0.1.16"),
645
+ agentStableVersion: z2.string().regex(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u).default("0.1.16"),
284
646
  // Optional independent beta-channel pointer. When unset, the beta update
285
647
  // manifest route is unavailable rather than silently serving stable.
286
- agentBetaVersion: z.string().regex(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u).optional(),
648
+ agentBetaVersion: z2.string().regex(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u).optional(),
287
649
  productAccessMode: ProductAccessMode.default("local"),
288
650
  // --- canonical organization-tenancy authority activation, default OFF ---
289
651
  // The named PRE-ACTIVATION opt-out for the organization-tenancy program. FALSE (the
@@ -306,11 +668,17 @@ var SettingsSchema = z.object({
306
668
  // variable out to disable it).
307
669
  organizationTenancyCanonicalActivationEnabled: EnvBoolean.default(false),
308
670
  billingMode: BillingMode.default("disabled"),
671
+ // Explicit launch gate for the one-time $10 verified self-service signup grant.
672
+ // A migration or deployment alone must not start issuing live credits.
673
+ verifiedSignupTrialCreditsEnabled: EnvBoolean.default(false),
309
674
  entitlementsMode: EntitlementsMode.default("none"),
310
675
  usageLimitsMode: UsageLimitsMode.default("none"),
311
- staticEntitlementsJson: z.string().default("{}"),
312
- staticUsageLimitsJson: z.string().default("{}"),
313
- delegationSecret: z.string().optional(),
676
+ // Gate new allowance policies until every API/worker in the fleet enforces
677
+ // them. Persisted-policy enforcement and recovery reads/clears stay active.
678
+ usageAllowancesEnabled: EnvBoolean.default(false),
679
+ staticEntitlementsJson: z2.string().default("{}"),
680
+ staticUsageLimitsJson: z2.string().default("{}"),
681
+ delegationSecret: z2.string().optional(),
314
682
  defaultFirstPartyMcpTools: EnvFirstPartyMcpTools,
315
683
  allowedFirstPartyMcpTools: EnvFirstPartyMcpTools,
316
684
  // sandbox workspace scoped stream-token HMAC secret (sandbox contract §C.3 / stream-token availability contract).
@@ -318,7 +686,7 @@ var SettingsSchema = z.object({
318
686
  // family, `ogs_` vs `ogd_` prefix). REQUIRED-WHEN-DESKTOP, but the absence of
319
687
  // BOTH while sandboxDesktopEnabled=true is a GRACEFUL DEGRADE (DesktopStream
320
688
  // transport:null + a loud boot warning), NOT a hard boot-fail (stream-token availability contract).
321
- streamTokenSecret: z.string().optional(),
689
+ streamTokenSecret: z2.string().optional(),
322
690
  // The desktop input plane (raw stream:control writes) is OFF in v1: even a
323
691
  // holder of stream:control gets 403 until this flips. Keeps stream:control a
324
692
  // declared-but-inert permission so later hardening is a flag flip.
@@ -341,47 +709,51 @@ var SettingsSchema = z.object({
341
709
  // Optional release-coherent bootstrap hint for custom rigs/connected machines
342
710
  // that do not carry the stock-image ogtool binary. Exact stable versions only:
343
711
  // the agent must never guess a tag or silently install `latest`.
344
- ogtoolPackageSpec: z.string().regex(/^@opengeni\/ogtool@(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u).optional(),
345
- environmentsEncryptionKey: z.string().optional(),
712
+ ogtoolPackageSpec: z2.string().regex(/^@opengeni\/ogtool@(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u).optional(),
713
+ environmentsEncryptionKey: z2.string().optional(),
346
714
  integrationsEnabled: EnvBoolean.default(false),
347
- integrationsStateSecret: z.string().optional(),
715
+ integrationsStateSecret: z2.string().optional(),
716
+ integrationsOauthShortStateEnabled: EnvBoolean.default(false),
348
717
  integrationsAllowPrivateNetworkTargets: EnvBoolean.default(false),
349
- integrationsOauthClientsJson: z.string().default("{}"),
350
- slackClientId: z.string().optional(),
351
- slackClientSecret: z.string().optional(),
352
- slackSigningSecret: z.string().optional(),
718
+ integrationsOauthClientsJson: z2.string().default("{}"),
719
+ gmailWatchTopicName: z2.string().regex(/^projects\/[^/]+\/topics\/[^/]+$/u).optional(),
720
+ slackClientId: z2.string().optional(),
721
+ slackClientSecret: z2.string().optional(),
722
+ slackSigningSecret: z2.string().optional(),
723
+ // Unlisted apps share Slack’s restricted history/replies quota across all tokens.
724
+ slackAccessMode: z2.enum(["limited", "full"]).default("limited"),
353
725
  slackBotDisplayName: OpenGeniSlackBotDisplayName.default("OpenGeni"),
354
- slackCommand: z.string().trim().regex(/^\/[a-z0-9_-]{1,31}$/u).default("/opengeni"),
355
- googleDriveClientId: z.string().optional(),
356
- googleDriveClientSecret: z.string().optional(),
357
- googleDriveSyncMaxItems: z.coerce.number().int().positive().max(1e4).default(500),
358
- googleDriveSyncMaxBytes: z.coerce.number().int().positive().max(5e9).default(5e8),
359
- googleDriveSyncMaxFileBytes: z.coerce.number().int().positive().max(5e9).default(1e8),
360
- googleDriveSyncMaxProviderRequests: z.coerce.number().int().positive().max(1e4).default(1e3),
361
- googleDriveSyncMaxElapsedSeconds: z.coerce.number().int().positive().max(3600).default(300),
362
- googleDriveSyncMaxFailureDetails: z.coerce.number().int().positive().max(100).default(25),
363
- googleDriveProviderRequestTimeoutMs: z.coerce.number().int().min(1e3).max(GOOGLE_DRIVE_PROVIDER_REQUEST_TIMEOUT_MAX_MS).default(3e4),
364
- googleDriveProviderRetryAttempts: z.coerce.number().int().min(1).max(5).default(3),
365
- googleDriveProviderRetryInitialDelayMs: z.coerce.number().int().positive().max(3e4).default(250),
366
- googleDriveProviderRetryMaxDelayMs: z.coerce.number().int().positive().max(GOOGLE_DRIVE_PROVIDER_RETRY_DELAY_MAX_MS).default(5e3),
367
- googleDriveProviderRetryBudgetMs: z.coerce.number().int().positive().max(12e4).default(15e3),
368
- fikenClientId: z.string().optional(),
369
- fikenClientSecret: z.string().optional(),
726
+ slackCommand: z2.string().trim().regex(/^\/[a-z0-9_-]{1,31}$/u).default("/opengeni"),
727
+ googleDriveClientId: z2.string().optional(),
728
+ googleDriveClientSecret: z2.string().optional(),
729
+ googleDriveSyncMaxItems: z2.coerce.number().int().positive().max(1e4).default(500),
730
+ googleDriveSyncMaxBytes: z2.coerce.number().int().positive().max(5e9).default(5e8),
731
+ googleDriveSyncMaxFileBytes: z2.coerce.number().int().positive().max(5e9).default(1e8),
732
+ googleDriveSyncMaxProviderRequests: z2.coerce.number().int().positive().max(1e4).default(1e3),
733
+ googleDriveSyncMaxElapsedSeconds: z2.coerce.number().int().positive().max(3600).default(300),
734
+ googleDriveSyncMaxFailureDetails: z2.coerce.number().int().positive().max(100).default(25),
735
+ googleDriveProviderRequestTimeoutMs: z2.coerce.number().int().min(1e3).max(GOOGLE_DRIVE_PROVIDER_REQUEST_TIMEOUT_MAX_MS).default(3e4),
736
+ googleDriveProviderRetryAttempts: z2.coerce.number().int().min(1).max(5).default(3),
737
+ googleDriveProviderRetryInitialDelayMs: z2.coerce.number().int().positive().max(3e4).default(250),
738
+ googleDriveProviderRetryMaxDelayMs: z2.coerce.number().int().positive().max(GOOGLE_DRIVE_PROVIDER_RETRY_DELAY_MAX_MS).default(5e3),
739
+ googleDriveProviderRetryBudgetMs: z2.coerce.number().int().positive().max(12e4).default(15e3),
740
+ fikenClientId: z2.string().optional(),
741
+ fikenClientSecret: z2.string().optional(),
370
742
  googleDriveWorkspaceEventsEnabled: EnvBoolean.optional(),
371
- atlassianClientId: z.string().optional(),
372
- atlassianClientSecret: z.string().optional(),
743
+ atlassianClientId: z2.string().optional(),
744
+ atlassianClientSecret: z2.string().optional(),
373
745
  // Undefined is meaningful: the migration boundary persists the product
374
746
  // default of 3 when no deployment override is supplied.
375
- maxNestedAgentDepth: z.coerce.number().int().nonnegative().max(MAX_NESTED_AGENT_DEPTH).optional(),
747
+ maxNestedAgentDepth: z2.coerce.number().int().nonnegative().max(MAX_NESTED_AGENT_DEPTH).optional(),
376
748
  // Operator OAuth apps for first-party social connectors, keyed by provider
377
749
  // id ("x", "reddit"): {"x":{"clientId":"...","clientSecret":"..."}}.
378
- socialOauthClientsJson: z.string().default("{}"),
750
+ socialOauthClientsJson: z2.string().default("{}"),
379
751
  // Session goal guard rails. Goals are designed for runs that legitimately
380
752
  // span days, so length is bounded by explicit completion/pause and budget
381
753
  // exhaustion, never by count. goalMaxAutoContinuations is therefore UNSET
382
754
  // by default (no cap); deployments may configure one, and it then acts as a
383
755
  // hard ceiling that per-goal overrides can only lower.
384
- goalMaxAutoContinuations: z.coerce.number().int().positive().optional(),
756
+ goalMaxAutoContinuations: z2.coerce.number().int().positive().optional(),
385
757
  // Idle backoff between CONSECUTIVE no-input goal continuations. This is
386
758
  // pacing, not a cap: the first continuation after a turn that consumed any
387
759
  // external input is immediate, the n-th consecutive no-input continuation
@@ -389,7 +761,7 @@ var SettingsSchema = z.object({
389
761
  // any new input (machine input, human/API prompt, Steer) wakes the session
390
762
  // immediately. The delay never exceeds goalIdleBackoffMaxMs.
391
763
  goalIdleBackoffMs: EnvGoalIdleBackoffMs.default(DEFAULT_GOAL_IDLE_BACKOFF_MS),
392
- goalIdleBackoffMaxMs: z.coerce.number().int().positive().default(DEFAULT_GOAL_IDLE_BACKOFF_MAX_MS),
764
+ goalIdleBackoffMaxMs: z2.coerce.number().int().positive().default(DEFAULT_GOAL_IDLE_BACKOFF_MAX_MS),
393
765
  // Child lifecycle notices: a child session's requires_action freeze, its
394
766
  // resolution, a direct Pause, a provider-capacity wait, and goal progress
395
767
  // become typed `session_system_updates` rows for the parent (in addition to
@@ -403,13 +775,6 @@ var SettingsSchema = z.object({
403
775
  // into @opengeni/db once at boot.
404
776
  // Env: OPENGENI_CHILD_LIFECYCLE_NOTICES_ENABLED.
405
777
  childLifecycleNoticesEnabled: EnvBoolean.default(false),
406
- // Explicit host-owned MCP connection authority is a rolling protocol
407
- // activation. Keep it off while any API, worker, or browser bundle predates
408
- // the authority discriminator; enable it only after the whole fleet runs an
409
- // image that understands host refs. Legacy markerless non-UUID refs remain a
410
- // separate compatibility lane for already-persisted embedding integrations.
411
- // Env: OPENGENI_HOST_MCP_AUTHORITY_SOURCE_ADMISSION_ENABLED.
412
- hostMcpAuthoritySourceAdmissionEnabled: EnvBoolean.default(false),
413
778
  // Per-channel and per-DM Slack workspace routing. Default ON. A channel does
414
779
  // not count a personal workspace as a candidate, so an organization with one
415
780
  // shared workspace resolves it as the sole candidate and never asks; the
@@ -424,17 +789,17 @@ var SettingsSchema = z.object({
424
789
  // session turn. Effectively unbounded by default for the same reason as
425
790
  // above; the graceful max-turns valve (idle + goal continuation, never a
426
791
  // session failure) remains as inert safety should a deployment set a cap.
427
- agentMaxModelCallsPerTurn: z.coerce.number().int().positive().default(1e6),
792
+ agentMaxModelCallsPerTurn: z2.coerce.number().int().positive().default(1e6),
428
793
  // Deployment fallback for models that do not declare their own window.
429
794
  // Built-in billed GPT-5.6 Sol/Terra/Luna pin Codex's 272k catalog instead.
430
795
  // OpenGeni always performs one durable, portable plaintext compaction
431
796
  // transition; there is no provider/server/off mode ladder.
432
- contextWindowTokens: z.coerce.number().int().positive().default(105e4),
797
+ contextWindowTokens: z2.coerce.number().int().positive().default(105e4),
433
798
  // Optional model-catalog effective input ceiling. Codex and billed GPT-5.6
434
799
  // models expose this as raw context_window * effective_context_window_percent;
435
800
  // when absent, retain the deployment-level window-minus-reserved-output
436
801
  // behavior.
437
- contextEffectiveWindowTokens: z.coerce.number().int().positive().optional(),
802
+ contextEffectiveWindowTokens: z2.coerce.number().int().positive().optional(),
438
803
  // Proactive compaction threshold as a ratio of the model context window.
439
804
  // Defaults to 90%: compact as late as possible — retained context beats early
440
805
  // headroom now that per-model windows are declared honestly (input-effective,
@@ -442,7 +807,7 @@ var SettingsSchema = z.object({
442
807
  // absorbs any overshoot as one retried call rather than a dead session.
443
808
  // Clamped to [0.3, 0.9] so deployments can tune the trigger without
444
809
  // accidentally disabling compaction.
445
- contextCompactionThresholdRatio: z.coerce.number().default(0.9).transform((value) => {
810
+ contextCompactionThresholdRatio: z2.coerce.number().default(0.9).transform((value) => {
446
811
  if (!Number.isFinite(value)) {
447
812
  return 0.9;
448
813
  }
@@ -450,118 +815,127 @@ var SettingsSchema = z.object({
450
815
  }),
451
816
  // Tokens reserved for model output; subtracted from the window to get the
452
817
  // usable input budget B = contextWindowTokens - contextReservedOutputTokens.
453
- contextReservedOutputTokens: z.coerce.number().int().nonnegative().default(128e3),
818
+ contextReservedOutputTokens: z2.coerce.number().int().nonnegative().default(128e3),
454
819
  // Model-catalog auto-compact limit. When present it is clamped to
455
820
  // 90% of the raw window, matching Codex core's auto_compact_token_limit().
456
- contextAutoCompactThresholdTokens: z.coerce.number().int().positive().optional(),
821
+ contextAutoCompactThresholdTokens: z2.coerce.number().int().positive().optional(),
457
822
  // Provider-neutral fallback for canonical model-facing tool-result text.
458
823
  // The current stable Codex catalog policy is 10k tokens; the truncator adds
459
824
  // Codex's 1.2x JSON serialization allowance when applying it.
460
- modelToolOutputTruncationTokens: z.coerce.number().int().positive().default(1e4),
825
+ modelToolOutputTruncationTokens: z2.coerce.number().int().positive().default(1e4),
461
826
  authRequired: EnvBoolean.default(false),
462
- accessKey: z.string().optional(),
827
+ accessKey: z2.string().optional(),
463
828
  authAllowHealth: EnvBoolean.default(true),
464
829
  authAllowMetrics: EnvBoolean.default(false),
465
- apiHost: z.string().default("0.0.0.0"),
466
- apiPort: z.coerce.number().int().positive().default(8e3),
467
- workerHttpPort: z.coerce.number().int().positive().default(8001),
830
+ apiHost: z2.string().default("0.0.0.0"),
831
+ apiPort: z2.coerce.number().int().positive().default(8e3),
832
+ // When set, GET /metrics is served only on this dedicated internal listener
833
+ // and never on the public API port that an ingress forwards to.
834
+ apiMetricsPort: z2.coerce.number().int().positive().optional(),
835
+ workerHttpPort: z2.coerce.number().int().positive().default(8001),
468
836
  // Worker-side first-party MCP traffic stays on the deployment's internal
469
837
  // network. OPENGENI_MCP_URL remains the sandbox/external route used by
470
838
  // Codemode and remote placements.
471
- opengeniMcpInternalUrl: z.string().url().optional(),
472
- opengeniMcpUrl: z.string().url().optional(),
839
+ opengeniMcpInternalUrl: z2.string().url().optional(),
840
+ opengeniMcpUrl: z2.string().url().optional(),
473
841
  // Origins allowed to send browser cookies cross-origin. Other origins may
474
842
  // call the public API with bearer credentials, but never receive credentialed
475
843
  // CORS responses.
476
- corsAllowOriginRegex: z.string().default(String.raw`^https?://(localhost|127\.0\.0\.1)(:\d+)?$`),
477
- openaiProvider: z.enum(["openai", "azure"]).default("openai"),
478
- openaiApiKey: z.string().optional(),
479
- openaiBaseUrl: z.string().optional(),
480
- openaiModel: z.string().default("gpt-5.6-sol"),
481
- openaiAllowedModels: z.string().default("gpt-5.6-sol,gpt-5.6-terra,gpt-5.6-luna"),
844
+ corsAllowOriginRegex: z2.string().default(String.raw`^https?://(localhost|127\.0\.0\.1)(:\d+)?$`),
845
+ // Local development only (`local` access mode in the `local` environment):
846
+ // extra exact browser origins, comma-separated, that may call the
847
+ // unauthenticated API besides this stack's own web origin. The local browser
848
+ // boundary ignores `corsAllowOriginRegex`.
849
+ localAllowedOrigins: z2.string().optional(),
850
+ openaiProvider: z2.enum(["openai", "azure"]).default("openai"),
851
+ openaiApiKey: z2.string().optional(),
852
+ openaiBaseUrl: z2.string().optional(),
853
+ openaiModel: z2.string().default("gpt-6-astra"),
854
+ openaiAllowedModels: z2.string().default("gpt-6-astra,gpt-6-sol,gpt-6-luna"),
482
855
  // OpenGeni-managed Vercel AI Gateway. When configured, the two reviewed
483
856
  // Gateway models below are added to the managed-credit catalog. Workspace
484
857
  // Gateway keys use the encrypted connection broker and never this secret.
485
- vercelAiGatewayApiKey: z.string().optional(),
858
+ vercelAiGatewayApiKey: z2.string().optional(),
486
859
  /** Image adapter route; native hosted providers ignore this model. */
487
- imageGenerationModel: z.string().trim().min(1).max(256).default("openai/gpt-image-2"),
860
+ imageGenerationModel: z2.string().trim().min(1).max(256).default("openai/gpt-image-2"),
488
861
  /** Durable video generation uses the workspace-owned Gateway credential. */
489
- videoGenerationPollIntervalMs: z.coerce.number().int().min(1e3).max(6e4).default(5e3),
490
- videoGenerationRecoveryDeadlineMs: z.coerce.number().int().min(6e4).max(24 * 60 * 6e4).default(2 * 60 * 6e4),
491
- videoGenerationReferenceUrlTtlSeconds: z.coerce.number().int().min(300).max(6 * 60 * 60).default(60 * 60),
492
- videoGenerationMaxConcurrentPerWorkspace: z.coerce.number().int().min(1).max(16).default(2),
493
- videoGenerationWorkspaceQuotaBytes: z.coerce.number().int().positive().max(Number.MAX_SAFE_INTEGER).default(20 * 1024 * 1024 * 1024),
494
- videoGenerationTempDirectory: z.string().trim().min(1).max(1024).default("/tmp/opengeni-video"),
495
- videoGenerationFfprobePath: z.string().trim().min(1).max(1024).default("ffprobe"),
862
+ videoGenerationPollIntervalMs: z2.coerce.number().int().min(1e3).max(6e4).default(5e3),
863
+ videoGenerationRecoveryDeadlineMs: z2.coerce.number().int().min(6e4).max(24 * 60 * 6e4).default(2 * 60 * 6e4),
864
+ videoGenerationReferenceUrlTtlSeconds: z2.coerce.number().int().min(300).max(6 * 60 * 60).default(60 * 60),
865
+ videoGenerationMaxConcurrentPerWorkspace: z2.coerce.number().int().min(1).max(16).default(2),
866
+ videoGenerationWorkspaceQuotaBytes: z2.coerce.number().int().positive().max(Number.MAX_SAFE_INTEGER).default(20 * 1024 * 1024 * 1024),
867
+ videoGenerationTempDirectory: z2.string().trim().min(1).max(1024).default("/tmp/opengeni-video"),
868
+ videoGenerationFfprobePath: z2.string().trim().min(1).max(1024).default("ffprobe"),
496
869
  // OpenGeni's customer price, not a claim about the provider's delayed cost report.
497
870
  // The durable operation freezes the exact resulting price before provider submit.
498
- videoGenerationCredit480pMicrosPerSecond: z.coerce.number().int().positive().max(1e7).default(155e3),
499
- videoGenerationCredit720pMicrosPerSecond: z.coerce.number().int().positive().max(1e7).default(35e4),
871
+ videoGenerationCredit480pMicrosPerSecond: z2.coerce.number().int().positive().max(1e7).default(155e3),
872
+ videoGenerationCredit720pMicrosPerSecond: z2.coerce.number().int().positive().max(1e7).default(35e4),
500
873
  // Native composer voice input (browser MediaRecorder → API transcription).
501
874
  // Provider credentials stay server-side; ClientConfig only projects availability
502
875
  // and hard ceilings. Selection happens once before audio is sent — never retry
503
876
  // the same clip across vendors after an upstream request may have started.
504
- voiceInputMaxDurationSeconds: z.coerce.number().int().positive().max(600).default(60),
505
- voiceInputMaxSizeBytes: z.coerce.number().int().positive().max(25 * 1024 * 1024).default(25 * 1024 * 1024),
877
+ voiceInputMaxDurationSeconds: z2.coerce.number().int().positive().max(600).default(60),
878
+ voiceInputMaxSizeBytes: z2.coerce.number().int().positive().max(25 * 1024 * 1024).default(25 * 1024 * 1024),
506
879
  // Durable long-form capture uploads bounded chunks to object storage, then
507
880
  // normalizes them into provider-safe segments. It is advertised only when
508
881
  // object storage and the configured ffmpeg executable are both available.
509
882
  voiceInputResumableEnabled: EnvBoolean.default(true),
510
- voiceInputResumableMaxDurationSeconds: z.coerce.number().int().positive().max(8 * 60 * 60).default(2 * 60 * 60),
511
- voiceInputResumableMaxSizeBytes: z.coerce.number().int().positive().max(512 * 1024 * 1024).default(512 * 1024 * 1024),
512
- voiceInputResumableMaxChunkSizeBytes: z.coerce.number().int().positive().max(25 * 1024 * 1024).default(8 * 1024 * 1024),
513
- voiceInputResumableRetentionSeconds: z.coerce.number().int().positive().max(7 * 24 * 60 * 60).default(24 * 60 * 60),
514
- voiceInputFfmpegPath: z.string().trim().min(1).max(1024).default("ffmpeg"),
883
+ voiceInputResumableMaxDurationSeconds: z2.coerce.number().int().positive().max(8 * 60 * 60).default(2 * 60 * 60),
884
+ voiceInputResumableMaxSizeBytes: z2.coerce.number().int().positive().max(512 * 1024 * 1024).default(512 * 1024 * 1024),
885
+ voiceInputResumableMaxChunkSizeBytes: z2.coerce.number().int().positive().max(25 * 1024 * 1024).default(8 * 1024 * 1024),
886
+ voiceInputResumableRetentionSeconds: z2.coerce.number().int().positive().max(7 * 24 * 60 * 60).default(24 * 60 * 60),
887
+ voiceInputFfmpegPath: z2.string().trim().min(1).max(1024).default("ffmpeg"),
515
888
  // Preferred provider order (comma-separated ids). First configured+ready wins.
516
889
  // Connected subscription STT is preferred by default; operators can put
517
890
  // openai/azure-openai first explicitly.
518
891
  // Supported: supergrok-subscription, codex-subscription, openai, azure-openai.
519
- voiceInputProviderOrder: z.string().default("supergrok-subscription,codex-subscription,openai,azure-openai"),
892
+ voiceInputProviderOrder: z2.string().default("supergrok-subscription,codex-subscription,openai,azure-openai"),
520
893
  // OpenAI public /v1/audio/transcriptions path. Reuses OPENGENI_OPENAI_API_KEY
521
894
  // when voiceInputOpenaiApiKey is unset. Default model is gpt-transcribe.
522
895
  voiceInputOpenaiEnabled: EnvBoolean.default(true),
523
- voiceInputOpenaiApiKey: z.string().optional(),
524
- voiceInputOpenaiBaseUrl: z.string().optional(),
525
- voiceInputOpenaiModel: z.string().default("gpt-transcribe"),
896
+ voiceInputOpenaiApiKey: z2.string().optional(),
897
+ voiceInputOpenaiBaseUrl: z2.string().optional(),
898
+ voiceInputOpenaiModel: z2.string().default("gpt-transcribe"),
526
899
  // Azure OpenAI deployment-scoped audio transcriptions. Reuses the turn-model
527
900
  // Azure endpoint/key/AD token when voice-specific overrides are unset.
528
901
  voiceInputAzureEnabled: EnvBoolean.default(true),
529
- voiceInputAzureEndpoint: z.string().optional(),
530
- voiceInputAzureDeployment: z.string().optional(),
531
- voiceInputAzureApiVersion: z.string().optional(),
532
- voiceInputAzureApiKey: z.string().optional(),
533
- voiceInputAzureAdToken: z.string().optional(),
902
+ voiceInputAzureEndpoint: z2.string().optional(),
903
+ voiceInputAzureDeployment: z2.string().optional(),
904
+ voiceInputAzureApiVersion: z2.string().optional(),
905
+ voiceInputAzureApiKey: z2.string().optional(),
906
+ voiceInputAzureAdToken: z2.string().optional(),
534
907
  // Legacy opt-in for undocumented ChatGPT /backend-api/transcribe. When
535
908
  // OPENGENI_CODEX_SUBSCRIPTION_ENABLED is true, Codex STT is included without
536
909
  // this flag. Set false and omit codex-subscription from PROVIDER_ORDER to
537
910
  // keep subscription model routing while disabling Codex voice input.
538
911
  voiceInputCodexExperimentalEnabled: EnvBoolean.default(false),
539
- modelPricingJson: z.string().default("{}"),
912
+ modelPricingJson: z2.string().default("{}"),
540
913
  // Supported-model membership source. Database mode is resolved by the async
541
914
  // core overlay; getSettings remains synchronous and env-only.
542
- modelCatalogSource: z.enum(["code", "database"]).default("code"),
915
+ modelCatalogSource: z2.enum(["code", "database"]).default("code"),
543
916
  // Deployment-owned workspace-facing price policy. This is deliberately
544
917
  // separate from catalog membership and upstream credential ownership.
545
918
  // Shape: { "product/model-id": "free" | "credits" }.
546
- modelCostPolicyJson: z.string().default("{}"),
919
+ modelCostPolicyJson: z2.string().default("{}"),
547
920
  // Optional per-product agent guidance. Database mode replaces this with the
548
921
  // singleton document's validated modelNotes map.
549
- modelNotesJson: z.string().default("{}"),
922
+ modelNotesJson: z2.string().default("{}"),
550
923
  // Managed OpenRouter credential. The curated model table is injected in
551
924
  // code/catalog-document resolution and never read from host provider JSON.
552
- openrouterApiKey: z.string().optional(),
925
+ openrouterApiKey: z2.string().optional(),
553
926
  // Internal, secret-free catalog overlays populated only by
554
927
  // applyModelCatalogDocument. They intentionally have no OPENGENI_* env
555
928
  // binding so database mode cannot be bypassed with a second source.
556
- resolvedGatewayModelsJson: z.string().optional(),
557
- resolvedOpenRouterModelsJson: z.string().optional(),
929
+ resolvedGatewayModelsJson: z2.string().optional(),
930
+ resolvedOpenRouterModelsJson: z2.string().optional(),
931
+ resolvedCodexModelsJson: z2.string().optional(),
558
932
  // Extra (non-built-in) model providers, declared by the host as a JSON
559
933
  // provider registry. Each entry carries its own base URL, API key, wire API
560
934
  // ("responses" | "chat") and the models it exposes. The models a client may
561
935
  // use are the UNION of the built-in provider's allowed models and every
562
936
  // registry provider's models. validateSettings parses this at boot so a
563
937
  // malformed registry / unresolvable key / id collision fails fast.
564
- modelProvidersJson: z.string().default("[]"),
938
+ modelProvidersJson: z2.string().default("[]"),
565
939
  // Codex (ChatGPT) subscription: when enabled, a per-workspace connected
566
940
  // subscription is injected as a synthetic "codex-subscription" registry
567
941
  // provider whose models route through the ChatGPT backend (@opengeni/codex).
@@ -571,15 +945,17 @@ var SettingsSchema = z.object({
571
945
  // account pool and a distinct rail from the existing xai/* API-key provider.
572
946
  supergrokSubscriptionEnabled: EnvBoolean.default(false),
573
947
  // OPENGENI_SUPERGROK_SUBSCRIPTION_ENABLED
948
+ claudeSubscriptionEnabled: EnvBoolean.default(false),
949
+ // OPENGENI_CLAUDE_SUBSCRIPTION_ENABLED
574
950
  // Maximum silence between complete, valid SuperGrok SSE data events. This is
575
951
  // not a request/run duration cap; every valid event resets the timer.
576
- supergrokResponseStreamIdleTimeoutMs: z.coerce.number().int().positive().max(24 * 60 * 6e4).default(XAI_RESPONSE_STREAM_IDLE_TIMEOUT_MS),
952
+ supergrokResponseStreamIdleTimeoutMs: z2.coerce.number().int().positive().max(24 * 60 * 6e4).default(XAI_RESPONSE_STREAM_IDLE_TIMEOUT_MS),
577
953
  // Expose the connected apps attached to a Codex subscription through the
578
954
  // synthetic codex_apps MCP server. Independent from subscription routing so
579
955
  // operators can use Codex models without exposing ChatGPT connectors.
580
956
  codexConnectedAppsEnabled: EnvBoolean.default(false),
581
957
  // OPENGENI_CODEX_CONNECTED_APPS_ENABLED
582
- codexProductSku: z.string().optional(),
958
+ codexProductSku: z2.string().optional(),
583
959
  // OPENGENI_CODEX_PRODUCT_SKU (X-OpenAI-Product-Sku, apps only)
584
960
  // Progressive MCP disclosure (Codex-CLI-style tool_search): on a codex turn,
585
961
  // flag non-eager selected MCP tools `defer_loading:true` (dropping their
@@ -603,10 +979,23 @@ var SettingsSchema = z.object({
603
979
  // Multi-account P3 (auto-rotation): an account is "near exhaustion" — ineligible to be
604
980
  // rotated TO — when EITHER usage window (5h/weekly) is at/over this percent. Default 90 to
605
981
  // match the UI danger flip (UsageBar danger at pct >= 90). OPENGENI_CODEX_ROTATION_NEAR_EXHAUSTION_PCT.
606
- codexRotationNearExhaustionPct: z.coerce.number().int().min(1).max(100).default(90),
982
+ codexRotationNearExhaustionPct: z2.coerce.number().int().min(1).max(100).default(90),
983
+ reasoningConfigurationUpdatesEnabled: EnvBoolean.default(false),
607
984
  openaiReasoningEffort: ReasoningEffort.default("low"),
608
- openaiAllowedReasoningEfforts: z.string().default("low,medium,high,xhigh,max"),
609
- openaiResponsesTransport: z.enum(["http", "websocket"]).default("http"),
985
+ openaiAllowedReasoningEfforts: z2.string().default("low,medium,high,xhigh,max"),
986
+ // Default for new chats and scheduled tasks when the workspace has an
987
+ // OpenGeni credit balance, no saved workspace default, and no usable
988
+ // connected subscription, and the deployment default is not already a
989
+ // credits-billed model. Selected only when this model is selectable in the
990
+ // workspace catalog; otherwise the first selectable credits model is used.
991
+ // OPENGENI_CREDITS_DEFAULT_MODEL / OPENGENI_CREDITS_DEFAULT_REASONING_EFFORT.
992
+ creditsDefaultModel: z2.string().trim().min(1).max(256).refine((value) => !/[\u000A\u000D|]/u.test(value), {
993
+ message: "credits default model must not contain newlines or the | field separator"
994
+ }).default("gpt-6-luna"),
995
+ // Preferred effort for the credits default. Clamped to the highest effort
996
+ // the selected model supports at or below this value.
997
+ creditsDefaultReasoningEffort: ReasoningEffort.default("xhigh"),
998
+ openaiResponsesTransport: z2.enum(["http", "websocket"]).default("http"),
610
999
  // Provider-assigned item ids (rs_/msg_/fc_…) in Responses API input are
611
1000
  // resolved against the provider's server-side response store. That store is
612
1001
  // not durable enough to anchor long runs on: a response that streamed fine
@@ -615,7 +1004,7 @@ var SettingsSchema = z.object({
615
1004
  // every model-call input so requests are self-contained — conversation
616
1005
  // truth already lives client-side in session_history_items. "preserve"
617
1006
  // keeps the SDK's pass-through behavior.
618
- openaiProviderItemIds: z.enum(["strip", "preserve"]).default("strip"),
1007
+ openaiProviderItemIds: z2.enum(["strip", "preserve"]).default("strip"),
619
1008
  // With ids stripped the provider cannot resolve prior reasoning server-side,
620
1009
  // so request reasoning.encrypted_content and send it back with each call:
621
1010
  // reasoning continuity without depending on provider-side storage.
@@ -623,7 +1012,7 @@ var SettingsSchema = z.object({
623
1012
  // Model-call retry budget for transient provider failures (429s and friends).
624
1013
  // The openai client default of 2 retries is too small for sustained TPM
625
1014
  // backpressure during long autonomous runs.
626
- openaiMaxRetries: z.coerce.number().int().nonnegative().default(5),
1015
+ openaiMaxRetries: z2.coerce.number().int().nonnegative().default(5),
627
1016
  // Native hosted web search. The live Azure Responses path executes the
628
1017
  // hosted web_search tool, so this is provider-unconditional: ON by default
629
1018
  // on every provider, exposed only so operators can disable it. When true,
@@ -631,6 +1020,19 @@ var SettingsSchema = z.object({
631
1020
  // merged with the MCP-server tools (getAllTools = [...mcpTools, ...tools])
632
1021
  // and the sandbox capability tools, never replacing them.
633
1022
  webSearchEnabled: EnvBoolean.default(true),
1023
+ // Jev (TypeSafe's fast judge model) for worker-side agent tools. Without a
1024
+ // usable key every Jev-backed feature is off. The key stays on the server
1025
+ // (API and worker) and never reaches a sandbox or Connected Machine.
1026
+ jevApiKey: z2.string().optional(),
1027
+ jevBaseUrl: z2.string().url().default("https://api.typesafe.ai"),
1028
+ jevModel: z2.string().trim().min(1).max(128).default("jev-latest"),
1029
+ jevRequestTimeoutMs: z2.coerce.number().int().positive().max(12e4).default(1e4),
1030
+ // Jev-backed `code_search` agent tool. `off` never offers it, `opt_in` offers
1031
+ // it only where workspace settings enable it, `default_on` offers it
1032
+ // everywhere except workspaces that disable it, and `experiment` gives it to
1033
+ // a fixed half of sessions in workspaces without their own setting, for
1034
+ // comparison. It also needs jevApiKey.
1035
+ codeSearchMode: z2.enum(["off", "opt_in", "default_on", "experiment"]).default("off"),
634
1036
  // Deployment-default agent persona template (the white-label surface). The
635
1037
  // runtime resolves the effective template per turn as
636
1038
  // per-session-override > per-workspace override > this default, substitutes
@@ -638,38 +1040,40 @@ var SettingsSchema = z.object({
638
1040
  // it when the template omits the marker), and uses the result as the agent's
639
1041
  // instructions. Defaulting to DEFAULT_AGENT_INSTRUCTIONS keeps the composed
640
1042
  // default pinned by runtime tests.
641
- agentInstructionsTemplate: z.string().default(DEFAULT_AGENT_INSTRUCTIONS),
642
- azureOpenaiBaseUrl: z.string().optional(),
643
- azureOpenaiEndpoint: z.string().optional(),
644
- azureOpenaiDeployment: z.string().optional(),
645
- azureOpenaiApiVersion: z.string().optional(),
646
- azureOpenaiApiKey: z.string().optional(),
647
- azureOpenaiAdToken: z.string().optional(),
1043
+ agentInstructionsTemplate: z2.string().default(DEFAULT_AGENT_INSTRUCTIONS),
1044
+ azureOpenaiBaseUrl: z2.string().optional(),
1045
+ azureOpenaiEndpoint: z2.string().optional(),
1046
+ azureOpenaiDeployment: z2.string().optional(),
1047
+ azureOpenaiApiVersion: z2.string().optional(),
1048
+ azureOpenaiApiKey: z2.string().optional(),
1049
+ azureOpenaiAdToken: z2.string().optional(),
648
1050
  disableOpenaiTracing: EnvBoolean.default(false),
649
1051
  sandboxBackend: SandboxBackend.default("docker"),
650
- dockerImage: z.string().default("opengeni-sandbox:local"),
1052
+ dockerImage: z2.string().default("opengeni-sandbox:local"),
651
1053
  // Explicit deployment contract: the configured base sandbox image contains
652
1054
  // the verified, self-contained native artifact runtime at its fixed image
653
1055
  // paths. Disabled by default so arbitrary/custom provider images never make
654
1056
  // document/spreadsheet/presentation skills appear when their runtime is
655
- // absent. Per-pack/per-rig image overrides fail closed in the worker even
656
1057
  // when this base-image contract is enabled.
657
1058
  sandboxArtifactRuntimeEnabled: EnvBoolean.default(false),
658
- dockerExposedPorts: z.string().default(""),
659
- dockerNetwork: z.string().optional(),
1059
+ dockerExposedPorts: z2.string().default(""),
1060
+ dockerNetwork: z2.string().optional(),
660
1061
  // When the worker itself runs in a container and talks to a host Docker daemon,
661
1062
  // this directory must be bind-mounted at the exact same absolute path on both
662
1063
  // sides. The Agents SDK materializes the workspace here before bind-mounting it
663
1064
  // into the sandbox container.
664
- dockerWorkspaceBaseDir: z.string().min(1).optional(),
665
- modalAppName: z.string().default("opengeni-sandbox"),
666
- modalImageRef: z.string().optional(),
1065
+ dockerWorkspaceBaseDir: z2.string().min(1).optional(),
1066
+ modalAppName: z2.string().default("opengeni-sandbox"),
1067
+ modalImageRef: z2.string().optional(),
1068
+ // Activate only after descriptor-aware readers, DB fences and the exact
1069
+ // native image have passed the supervised-command rollout canary.
1070
+ modalCommandSupervisionEnabled: EnvBoolean.default(false),
667
1071
  // Provider-native immutable Modal image ID for the exact logical
668
1072
  // `modalImageRef`. When set, the runtime uses ModalImageSelector.fromId and
669
1073
  // never asks Modal to parse or import the registry ref. The logical ref is
670
1074
  // still persisted on the sandbox lease for provenance and conflict fencing;
671
1075
  // the Modal session envelope persists the actual image ID.
672
- modalImageId: z.string().min(4).max(128).regex(/^im-[A-Za-z0-9]+$/).optional(),
1076
+ modalImageId: z2.string().min(4).max(128).regex(/^im-[A-Za-z0-9]+$/).optional(),
673
1077
  // Name of a Modal Secret (containing REGISTRY_USERNAME + REGISTRY_PASSWORD) used
674
1078
  // to authenticate the pull of `modalImageRef` from a PRIVATE registry. When UNSET
675
1079
  // (the default), the sandbox image is pulled UNAUTHENTICATED — i.e. it must be a
@@ -678,7 +1082,7 @@ var SettingsSchema = z.object({
678
1082
  // run a private image (e.g. a cloud-hosted ACR/ECR/GCR digest): the runtime resolves
679
1083
  // the named Secret and builds the image via `fromRegistry(tag, secret)` before the
680
1084
  // first sandbox is created. Knob: OPENGENI_MODAL_IMAGE_REGISTRY_SECRET.
681
- modalImageRegistrySecret: z.string().optional(),
1085
+ modalImageRegistrySecret: z2.string().optional(),
682
1086
  // Modal's hard sandbox lifetime (timeoutMs = this * 1000), counted from box
683
1087
  // creation. A resume-by-id does NOT reset that provider clock. It is the
684
1088
  // BACKSTOP that reclaims a box if the reaper/worker is down, NOT the warm-window
@@ -689,17 +1093,17 @@ var SettingsSchema = z.object({
689
1093
  // deadline-aware snapshot/rematerialization transition. The transition—not a
690
1094
  // larger timeout—is what lets a session outlive one finite provider box.
691
1095
  // Knob: OPENGENI_MODAL_TIMEOUT_SECONDS.
692
- modalTimeoutSeconds: z.coerce.number().int().positive().max(86400).default(86400),
1096
+ modalTimeoutSeconds: z2.coerce.number().int().positive().max(86400).default(86400),
693
1097
  // Optional provider reservations for every new Modal sandbox. CPU is measured
694
1098
  // in physical cores and may be fractional; memory is measured in MiB. Leave
695
1099
  // both unset to preserve Modal's provider defaults. The Agents adapter stores
696
1100
  // the resolved values in its session state so snapshot replacement and exact
697
1101
  // resume cannot silently change the reservation.
698
- modalSandboxCpu: z.coerce.number().positive().optional(),
699
- modalSandboxMemoryMiB: z.coerce.number().int().positive().optional(),
700
- modalTokenId: z.string().optional(),
701
- modalTokenSecret: z.string().optional(),
702
- modalEnvironment: z.string().optional(),
1102
+ modalSandboxCpu: z2.coerce.number().positive().optional(),
1103
+ modalSandboxMemoryMiB: z2.coerce.number().int().positive().optional(),
1104
+ modalTokenId: z2.string().optional(),
1105
+ modalTokenSecret: z2.string().optional(),
1106
+ modalEnvironment: z2.string().optional(),
703
1107
  // modal gap-fill: idleTimeoutMs + workspacePersistence were unmapped (module 03 §4.1).
704
1108
  //
705
1109
  // CRITICAL (sandbox-file-persistence): when this is UNSET the Modal SDK sends
@@ -717,7 +1121,7 @@ var SettingsSchema = z.object({
717
1121
  // explicitly (OPENGENI_MODAL_IDLE_TIMEOUT_SECONDS) only to deliberately idle-reap
718
1122
  // SOONER than the hard lifetime; the boot invariant forbids a value that would
719
1123
  // reap before reaperPeriod + idleGrace elapses.
720
- modalIdleTimeoutSeconds: z.coerce.number().int().positive().optional(),
1124
+ modalIdleTimeoutSeconds: z2.coerce.number().int().positive().optional(),
721
1125
  // /workspace FILE PERSISTENCE across warm/cold cycles. Directory snapshots
722
1126
  // preserve only the durable user workspace, so provider recovery does not
723
1127
  // restore an entire machine image or replace the selected rig/base image.
@@ -726,16 +1130,14 @@ var SettingsSchema = z.object({
726
1130
  // Modal creations only.
727
1131
  // `snapshot_filesystem` remains available for explicit compatibility and
728
1132
  // immutable rig-image materialization. `tar` is the portable fallback.
729
- modalWorkspacePersistence: z.enum(["tar", "snapshot_filesystem", "snapshot_directory"]).default("snapshot_directory"),
1133
+ modalWorkspacePersistence: z2.enum(["tar", "snapshot_filesystem", "snapshot_directory"]).default("snapshot_directory"),
730
1134
  // Shared desktop toggle: this module reads it for the 6080 port-merge; the
731
1135
  // owner module (P4.x) acts on it to launch the display stack.
732
1136
  sandboxDesktopEnabled: EnvBoolean.default(false),
733
- // Human take-control toggle: when ON (default) the negotiated DesktopStream
734
- // cell advertises mode "interactive" — the noVNC viewer can drive mouse+keyboard
735
- // into :0 (x11vnc runs without -viewonly). Turn it OFF for a genuinely read-only
736
- // deployment: the cell reports mode "read-only" and the client disables the
737
- // "Take control" affordance. This gates the HUMAN viewer plane; agent
738
- // interaction is authorized through managed ComputerSession tools.
1137
+ // Human sandbox input policy. Canonical ComputerSession attachments reflect
1138
+ // it and /actions enforces it independently of the client. The legacy
1139
+ // DesktopStream adapter also reports read-only when disabled. Agent tools
1140
+ // retain their separate session-control authority.
739
1141
  sandboxDesktopInteractive: EnvBoolean.default(true),
740
1142
  // REAL PTY terminal toggle (P5.t): gates the ttyd pty-ws plane (7681) the API
741
1143
  // mints over the SAME tunnel as the desktop. Defaults ON — the interactive
@@ -747,13 +1149,13 @@ var SettingsSchema = z.object({
747
1149
  // The desktop framebuffer geometry the pixel plane advertises + launches the
748
1150
  // display stack with (P4.2). v1 has no live RANDR resize; a change is a full
749
1151
  // down→up restart. Defaults match the proven spike geometry (1280x800).
750
- streamResolutionWidth: z.coerce.number().int().positive().default(1280),
751
- streamResolutionHeight: z.coerce.number().int().positive().default(800),
1152
+ streamResolutionWidth: z2.coerce.number().int().positive().default(1280),
1153
+ streamResolutionHeight: z2.coerce.number().int().positive().default(800),
752
1154
  // Recording loop: ffmpeg x11grab of :0 → mp4/webm → @opengeni/storage.
753
1155
  // recordingMaxBytes caps the in-memory finalize buffer (≤ storage single-PUT);
754
1156
  // recordingMaxSeconds is the ffmpeg -t hard ceiling (bounds a multi-day turn).
755
1157
  recordingEnabled: EnvBoolean.default(true),
756
- recordingDefaultCodec: z.enum(["h264-mp4", "vp9-webm"]).default("h264-mp4"),
1158
+ recordingDefaultCodec: z2.enum(["h264-mp4", "vp9-webm"]).default("h264-mp4"),
757
1159
  // Workbench v2 turn-end workspace capture. When on, the turn
758
1160
  // activity probes the box's changed files off the live box at turn end and
759
1161
  // persists a capture revision (blobs in @opengeni/storage) so the workbench
@@ -761,85 +1163,86 @@ var SettingsSchema = z.object({
761
1163
  // fully behind this flag: off ⇒ capture is skipped and reads fall back to the
762
1164
  // live/wake path (status-quo behavior). Default on; explicit per environment.
763
1165
  workspaceCaptureEnabled: EnvBoolean.default(true),
764
- recordingFramerate: z.coerce.number().int().positive().default(15),
765
- recordingMaxSeconds: z.coerce.number().int().positive().default(600),
766
- recordingMaxBytes: z.coerce.number().int().positive().default(268435456),
1166
+ recordingFramerate: z2.coerce.number().int().positive().default(15),
1167
+ recordingMaxSeconds: z2.coerce.number().int().positive().default(600),
1168
+ recordingMaxBytes: z2.coerce.number().int().positive().default(268435456),
767
1169
  // 256 MB
768
1170
  // --- daytona ---
769
- daytonaApiKey: z.string().optional(),
770
- daytonaApiUrl: z.string().url().optional(),
771
- daytonaTarget: z.string().optional(),
772
- daytonaImage: z.string().optional(),
773
- daytonaSnapshotName: z.string().optional(),
774
- daytonaAutoStopInterval: z.coerce.number().int().nonnegative().optional(),
1171
+ daytonaApiKey: z2.string().optional(),
1172
+ daytonaApiUrl: z2.string().url().optional(),
1173
+ daytonaTarget: z2.string().optional(),
1174
+ daytonaImage: z2.string().optional(),
1175
+ daytonaSnapshotName: z2.string().optional(),
1176
+ daytonaAutoStopInterval: z2.coerce.number().int().nonnegative().optional(),
775
1177
  // 0 disables idle-kill
776
- daytonaTimeoutSeconds: z.coerce.number().int().positive().optional(),
777
- daytonaExposedPortUrlTtlSeconds: z.coerce.number().int().positive().optional(),
1178
+ daytonaTimeoutSeconds: z2.coerce.number().int().positive().optional(),
1179
+ daytonaExposedPortUrlTtlSeconds: z2.coerce.number().int().positive().optional(),
778
1180
  // --- runloop ---
779
- runloopApiKey: z.string().optional(),
780
- runloopBaseUrl: z.string().url().optional(),
781
- runloopBlueprintName: z.string().optional(),
782
- runloopBlueprintId: z.string().optional(),
1181
+ runloopApiKey: z2.string().optional(),
1182
+ runloopBaseUrl: z2.string().url().optional(),
1183
+ runloopBlueprintName: z2.string().optional(),
1184
+ runloopBlueprintId: z2.string().optional(),
783
1185
  runloopTunnel: EnvBoolean.default(true),
784
- runloopKeepAliveSeconds: z.coerce.number().int().positive().optional(),
1186
+ runloopKeepAliveSeconds: z2.coerce.number().int().positive().optional(),
785
1187
  // --- e2b (SDK reads E2B_API_KEY from env; mirrored for validation + forwarding) ---
786
- e2bApiKey: z.string().optional(),
787
- e2bTemplate: z.string().optional(),
788
- e2bTimeoutSeconds: z.coerce.number().int().positive().optional(),
789
- e2bTimeoutAction: z.enum(["pause", "kill"]).optional(),
1188
+ e2bApiKey: z2.string().optional(),
1189
+ e2bTemplate: z2.string().optional(),
1190
+ e2bTimeoutSeconds: z2.coerce.number().int().positive().optional(),
1191
+ e2bTimeoutAction: z2.enum(["pause", "kill"]).optional(),
790
1192
  e2bAllowInternetAccess: EnvBoolean.optional(),
791
1193
  e2bAutoResume: EnvBoolean.optional(),
792
- e2bWorkspacePersistence: z.enum(["tar", "snapshot"]).optional(),
1194
+ e2bWorkspacePersistence: z2.enum(["tar", "snapshot"]).optional(),
793
1195
  // --- blaxel ---
794
- blaxelApiKey: z.string().optional(),
795
- blaxelImage: z.string().optional(),
796
- blaxelRegion: z.string().optional(),
1196
+ blaxelApiKey: z2.string().optional(),
1197
+ blaxelImage: z2.string().optional(),
1198
+ blaxelRegion: z2.string().optional(),
797
1199
  blaxelExposedPortPublic: EnvBoolean.optional(),
798
1200
  // public vs bl_preview_token
799
- blaxelExposedPortUrlTtlSeconds: z.coerce.number().int().positive().optional(),
800
- blaxelMemoryMb: z.coerce.number().int().positive().optional(),
801
- blaxelTtl: z.string().optional(),
1201
+ blaxelExposedPortUrlTtlSeconds: z2.coerce.number().int().positive().optional(),
1202
+ blaxelMemoryMb: z2.coerce.number().int().positive().optional(),
1203
+ blaxelTtl: z2.string().optional(),
802
1204
  // --- cloudflare (headless) ---
803
- cloudflareWorkerUrl: z.string().url().optional(),
804
- cloudflareApiKey: z.string().optional(),
1205
+ cloudflareWorkerUrl: z2.string().url().optional(),
1206
+ cloudflareApiKey: z2.string().optional(),
1207
+ experimentalBrowserContextPoolEnabled: EnvBoolean.default(false),
805
1208
  // --- remote browser placements ---
806
1209
  // Provider credentials are injected only into the placement-resident
807
1210
  // browserd launch. They never enter session contracts, journals, or sandboxes.
808
- browserbaseApiKey: z.string().min(1).max(8192).optional(),
809
- kernelApiKey: z.string().min(1).max(8192).optional(),
810
- kernelEndpoint: z.string().url().optional(),
811
- kernelBrowserTimeoutSeconds: z.coerce.number().int().positive().max(86400).default(3600),
1211
+ browserbaseApiKey: z2.string().min(1).max(8192).optional(),
1212
+ kernelApiKey: z2.string().min(1).max(8192).optional(),
1213
+ kernelEndpoint: z2.string().url().optional(),
1214
+ kernelBrowserTimeoutSeconds: z2.coerce.number().int().positive().max(86400).default(3600),
812
1215
  kernelBrowserStealth: EnvBoolean.default(false),
813
1216
  // --- vercel (headless) ---
814
- vercelToken: z.string().optional(),
815
- vercelProjectId: z.string().optional(),
816
- vercelTeamId: z.string().optional(),
817
- vercelRuntime: z.string().optional(),
1217
+ vercelToken: z2.string().optional(),
1218
+ vercelProjectId: z2.string().optional(),
1219
+ vercelTeamId: z2.string().optional(),
1220
+ vercelRuntime: z2.string().optional(),
818
1221
  // --- OpenSandbox (optional Kubernetes-native provisioned sandbox) ---
819
- openSandboxBaseUrl: z.string().url().optional(),
820
- openSandboxApiKey: z.string().min(1).optional(),
1222
+ openSandboxBaseUrl: z2.string().url().optional(),
1223
+ openSandboxApiKey: z2.string().min(1).optional(),
821
1224
  // Release and preview profiles must provide an immutable OCI digest. The
822
1225
  // adapter refuses tag-only references when this backend is active.
823
- openSandboxImage: z.string().min(1).optional(),
1226
+ openSandboxImage: z2.string().min(1).optional(),
824
1227
  // Renewable provider TTL is a leak/backstop clock, not OpenGeni's idle
825
1228
  // policy. The pinned server accepts a one-minute minimum; ordinary
826
1229
  // deployments default to one hour.
827
- openSandboxTtlSeconds: z.coerce.number().int().min(60).max(86400).default(3600),
1230
+ openSandboxTtlSeconds: z2.coerce.number().int().min(60).max(86400).default(3600),
828
1231
  openSandboxUseServerProxy: EnvBoolean.default(true),
829
1232
  // Channel B (browserd / noVNC / ttyd) uses OSEP-0011 signed URI-mode ingress.
830
1233
  // Exec/files stay on the private lifecycle server-proxy regardless of this flag.
831
1234
  openSandboxSignedEndpoints: EnvBoolean.default(false),
832
- openSandboxSignedEndpointTtlSeconds: z.coerce.number().int().min(60).max(3600).default(600),
833
- openSandboxChannelBPublicBaseUrl: z.string().url().optional(),
1235
+ openSandboxSignedEndpointTtlSeconds: z2.coerce.number().int().min(60).max(3600).default(600),
1236
+ openSandboxChannelBPublicBaseUrl: z2.string().url().optional(),
834
1237
  // Emergency hatch only: force JPEG/RFB through the API frame-proxy even when
835
1238
  // signed endpoints are on (M2 subprotocol failure). Unset means OpenSandbox
836
1239
  // uses the frame-proxy unless signed endpoints are on.
837
1240
  openSandboxInteractionFrameProxy: EnvBoolean.optional(),
838
- openSandboxPoolRef: z.string().regex(/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/).optional(),
1241
+ openSandboxPoolRef: z2.string().regex(/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/).optional(),
839
1242
  // Optional same-cluster, read-only observability projection. The application
840
1243
  // chart sets this only on the control worker and mounts a dedicated projected
841
1244
  // service-account token; non-Kubernetes and remote-provider deployments omit it.
842
- openSandboxKubernetesInventoryNamespace: z.string().min(1).max(63).regex(/^[a-z0-9](?:[-a-z0-9]*[a-z0-9])?$/).optional(),
1245
+ openSandboxKubernetesInventoryNamespace: z2.string().min(1).max(63).regex(/^[a-z0-9](?:[-a-z0-9]*[a-z0-9])?$/).optional(),
843
1246
  // --- sandbox ownership inversion (P1.2 rollout flag, default OFF) ---
844
1247
  // The keystone flag for the stateless resume-by-id model. When FALSE the
845
1248
  // agent-turn path is BYTE-FOR-BYTE today's build-and-discard behavior (no
@@ -893,13 +1296,13 @@ var SettingsSchema = z.object({
893
1296
  // when ABSENT and sandboxSelfhostedEnabled is on, the poll route reports the
894
1297
  // credential plane disabled (graceful degrade, mirrors streamTokenSecret). NEVER
895
1298
  // logged. Lives in the opengeni-runtime secret (Helm-clobbered configmap avoided).
896
- enrollmentSigningSecret: z.string().optional(),
1299
+ enrollmentSigningSecret: z2.string().optional(),
897
1300
  // Connect-info the EnrollmentCredentials hand the agent: the NATS server URL(s)
898
1301
  // the agent dials for the control plane, and the relay edge base URL for streams.
899
1302
  // The per-workspace NATS Account creds binding is infra-deferred (M4/relay
900
1303
  // milestone) — the poll returns these endpoints + a placeholder creds field.
901
- selfhostedNatsUrl: z.string().optional(),
902
- selfhostedRelayUrl: z.string().optional(),
1304
+ selfhostedNatsUrl: z2.string().optional(),
1305
+ selfhostedRelayUrl: z2.string().optional(),
903
1306
  // The HMAC secret the control plane signs the agent's relay PRODUCER token with
904
1307
  // (the `ogr_` envelope threaded into EnrollmentCredentials.relayToken; M8b/design
905
1308
  // §10.5). The relay verifies the producer token with the SAME secret. Optional:
@@ -907,10 +1310,10 @@ var SettingsSchema = z.object({
907
1310
  // plane is simply unavailable until configured). Falls back to streamTokenSecret /
908
1311
  // delegationSecret (same HMAC family) so a deployment with a stream-token secret
909
1312
  // needs no second one. NEVER logged. Lives in the opengeni-runtime secret.
910
- selfhostedRelayTokenSecret: z.string().optional(),
1313
+ selfhostedRelayTokenSecret: z2.string().optional(),
911
1314
  // The minisign PUBLIC key the agent pins for self-update verification (handed to
912
1315
  // the agent in EnrollmentCredentials; the SECRET key lives only in CI).
913
- agentUpdatePublicKey: z.string().optional(),
1316
+ agentUpdatePublicKey: z2.string().optional(),
914
1317
  // --- NATS auth-callout tenancy boundary (bring-your-own-compute M-AUTH; design
915
1318
  // §10.1 NATS Accounts per workspace + §17 the isolation smoke) -------------
916
1319
  // nats-server is configured with AUTH CALLOUT: an external agent connects
@@ -927,24 +1330,24 @@ var SettingsSchema = z.object({
927
1330
  // The callout account SIGNING SEED (`SA...`). Both the user JWT and the
928
1331
  // authorization-response JWT are signed by this account key; its public key
929
1332
  // (`A...`) is the `auth_callout.issuer` in the server config. NEVER logged.
930
- selfhostedNatsCalloutAccountSeed: z.string().optional(),
1333
+ selfhostedNatsCalloutAccountSeed: z2.string().optional(),
931
1334
  // The TARGET ACCOUNT NAME the minted user is placed into (the server-config-mode
932
1335
  // `auth_callout.account`, e.g. "APP"). The responder writes it as the minted user
933
1336
  // JWT `aud` so nats-server binds the agent to this account — the SAME account the
934
1337
  // privileged control plane connects into, so exact process request/reply
935
1338
  // routes. Optional; resolveNatsCalloutConfig defaults it to "APP".
936
- selfhostedNatsCalloutAccountName: z.string().optional(),
1339
+ selfhostedNatsCalloutAccountName: z2.string().optional(),
937
1340
  // The callout RESPONDER's own NATS login (one of the `auth_callout.auth_users`
938
1341
  // in the AUTH account) — the responder connects with this to subscribe
939
1342
  // $SYS.REQ.USER.AUTH. Username/password.
940
- selfhostedNatsCalloutUser: z.string().optional(),
941
- selfhostedNatsCalloutPassword: z.string().optional(),
1343
+ selfhostedNatsCalloutUser: z2.string().optional(),
1344
+ selfhostedNatsCalloutPassword: z2.string().optional(),
942
1345
  // The PRIVILEGED control-plane login (api/worker): a static account user that may
943
1346
  // request exact process RPC subjects + receive their inbox replies. The event bus + the
944
1347
  // selfhosted control RPC ride THIS connection. Username/password; when unset the
945
1348
  // bus connects anonymously (local dev / a NATS with no auth_callout).
946
- selfhostedNatsControlUser: z.string().optional(),
947
- selfhostedNatsControlPassword: z.string().optional(),
1349
+ selfhostedNatsControlUser: z2.string().optional(),
1350
+ selfhostedNatsControlPassword: z2.string().optional(),
948
1351
  // --- selfhosted (Connected Machine) control/exec op deadlines ---------------
949
1352
  // CONTROL ops (ping / fs / git / desktop / pty) keep a short request timeout so
950
1353
  // liveness failures surface promptly. EXEC duration is a different concern: by
@@ -954,8 +1357,8 @@ var SettingsSchema = z.object({
954
1357
  // process deadline by setting a positive value; 0 never schedules a process kill.
955
1358
  // Knobs: OPENGENI_SANDBOX_SELFHOSTED_EXEC_TIMEOUT_MS (default 0 = none) and
956
1359
  // OPENGENI_SANDBOX_SELFHOSTED_CONTROL_TIMEOUT_MS (default 30s).
957
- sandboxSelfhostedExecTimeoutMs: z.coerce.number().int().nonnegative().default(0),
958
- sandboxSelfhostedControlTimeoutMs: z.coerce.number().int().positive().default(3e4),
1360
+ sandboxSelfhostedExecTimeoutMs: z2.coerce.number().int().nonnegative().default(0),
1361
+ sandboxSelfhostedControlTimeoutMs: z2.coerce.number().int().positive().default(3e4),
959
1362
  // --- sandbox lease cadences (cadence invariant validated at boot below) ---
960
1363
  // reaperPeriod < viewerHolderTTL, and reaperPeriod + idleGrace < the EFFECTIVE
961
1364
  // box idle timeout (effectiveModalIdleTimeoutSeconds, which defaults to the hard
@@ -963,12 +1366,12 @@ var SettingsSchema = z.object({
963
1366
  // idle timeout — which we pin high enough (via the idle-timeout default) that
964
1367
  // OpenGeni's reaper, not Modal's idle-reap, governs teardown so /workspace is
965
1368
  // snapshotted before the box dies (sandbox-file-persistence).
966
- sandboxLeaseReaperPeriodMs: z.coerce.number().int().positive().default(3e4),
967
- sandboxViewerHolderTtlMs: z.coerce.number().int().positive().default(9e4),
1369
+ sandboxLeaseReaperPeriodMs: z2.coerce.number().int().positive().default(3e4),
1370
+ sandboxViewerHolderTtlMs: z2.coerce.number().int().positive().default(9e4),
968
1371
  // A BrowserSession controller refreshes its durable resource and exact
969
1372
  // interaction lease holder together. This longer crash horizon tolerates API
970
1373
  // replacement while still releasing a placement whose controller died.
971
- sandboxInteractionHolderTtlMs: z.coerce.number().int().positive().default(18e4),
1374
+ sandboxInteractionHolderTtlMs: z2.coerce.number().int().positive().default(18e4),
972
1375
  // The DRAIN grace: how long a refcount-0 (draining) lease stays WARM before the
973
1376
  // reaper resume-by-ids the box and terminates it. This is the cost-vs-snappiness
974
1377
  // dial — when the user navigates away the box keeps refcount 0, but it survives
@@ -978,7 +1381,29 @@ var SettingsSchema = z.object({
978
1381
  // fresh EMPTY box; lower it to trade warm cost for a snappier reclaim.
979
1382
  // getSettings caps the default at half a shorter configured Modal lifetime so
980
1383
  // the entire reaper window always fits. Knob: OPENGENI_SANDBOX_IDLE_GRACE_MS.
981
- sandboxIdleGraceMs: z.coerce.number().int().positive().default(9e5),
1384
+ sandboxIdleGraceMs: z2.coerce.number().int().positive().default(9e5),
1385
+ // Idle command containment. A legacy retained background command (a dev
1386
+ // server, a command whose output is still draining, a stopped command the
1387
+ // provider no longer answers for) keeps its box warm through a non-expiring
1388
+ // process holder, so the zero-holder drain never runs and the box would stay
1389
+ // up until the provider deadline kills it uncaptured. Once every session of
1390
+ // the sandbox group has been unused this long - no open turn or pending
1391
+ // request, no held wait_for_input, no other holder or writer, measured from
1392
+ // durable turn/holder/admission facts - the reaper checkpoints the workspace,
1393
+ // stops the box and settles those commands `lost` with reason
1394
+ // `idle_containment`. Default 30min: twice the default
1395
+ // idle grace, so a lease that is only waiting for a "glanced away" user is
1396
+ // never contained earlier than an idle lease would drain, and well inside
1397
+ // the 1h provider-deadline rotation lead, so an idle box is saved long before
1398
+ // the deadline path has to act. Set 0 to disable new idle enrollments without
1399
+ // disabling provider-deadline containment or cancelling an enrolled drain.
1400
+ // A positive window must exceed OPENGENI_SANDBOX_IDLE_GRACE_MS;
1401
+ // an explicit positive value must also stay below OPENGENI_SANDBOX_ROTATION_LEAD_MS,
1402
+ // and with an explicit OPENGENI_MODAL_IDLE_TIMEOUT_SECONDS the reaper period
1403
+ // plus this window plus the drain capture budget must fit before it.
1404
+ // getSettings derives the unset default between those two for short-lived
1405
+ // provider lifetimes. Knob: OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS.
1406
+ sandboxIdleCommandContainmentMs: z2.coerce.number().int().nonnegative().optional().transform((value) => value === 0 ? void 0 : value),
982
1407
  // MID-SESSION /workspace snapshot cadence (sandbox-file-persistence). The
983
1408
  // reaper's drain-persist only protects boxes the reaper itself kills; a box
984
1409
  // that dies any other way (Modal's hard creation-time timeout on a session
@@ -988,20 +1413,20 @@ var SettingsSchema = z.object({
988
1413
  // one (same epoch-fenced fold-onto-lease seam as the drain), bounding the
989
1414
  // worst-case loss of ANY unclean box death to this window. 0 disables.
990
1415
  // Knob: OPENGENI_SANDBOX_SNAPSHOT_INTERVAL_MS. Default 15min.
991
- sandboxSnapshotIntervalMs: z.coerce.number().int().min(0).default(9e5),
1416
+ sandboxSnapshotIntervalMs: z2.coerce.number().int().min(0).default(9e5),
992
1417
  // Maximum time a best-effort /workspace snapshot capture may hold turn/reaper
993
1418
  // cleanup. A hung provider snapshot must never pin a lease holder, block
994
1419
  // graceful shutdown, or become permission to GC an older archive. Timeout is
995
1420
  // treated exactly like a failed best-effort snapshot. Knob:
996
1421
  // OPENGENI_SANDBOX_SNAPSHOT_TIMEOUT_MS. Default 60s.
997
- sandboxSnapshotTimeoutMs: z.coerce.number().int().positive().max(SANDBOX_SNAPSHOT_MAX_TIMEOUT_MS).default(6e4),
1422
+ sandboxSnapshotTimeoutMs: z2.coerce.number().int().positive().max(SANDBOX_SNAPSHOT_MAX_TIMEOUT_MS).default(6e4),
998
1423
  // A zero-holder drain may need substantially longer than a best-effort
999
1424
  // mid-turn/turn-end snapshot for a very large workspace. Keep that provider
1000
1425
  // budget independent so increasing drain recovery headroom cannot pin an
1001
1426
  // ordinary turn finalizer for the same duration. Unset preserves the legacy
1002
1427
  // single-budget behavior. Knob:
1003
1428
  // OPENGENI_SANDBOX_DRAIN_SNAPSHOT_TIMEOUT_MS.
1004
- sandboxDrainSnapshotTimeoutMs: z.coerce.number().int().positive().max(SANDBOX_SNAPSHOT_MAX_TIMEOUT_MS).optional(),
1429
+ sandboxDrainSnapshotTimeoutMs: z2.coerce.number().int().positive().max(SANDBOX_SNAPSHOT_MAX_TIMEOUT_MS).optional(),
1005
1430
  // Begin a controlled snapshot/quiesce/drain/rematerialize transition this far
1006
1431
  // ahead of a finite provider deadline. Modal's 24h creation clock cannot be
1007
1432
  // extended; the logical sandbox outlives it by moving to one successor box.
@@ -1010,22 +1435,22 @@ var SettingsSchema = z.object({
1010
1435
  // an extra coupled environment override. An explicit value may be larger when
1011
1436
  // an operator deliberately wants more rotation headroom; the boot invariant
1012
1437
  // still requires it to remain below the provider lifetime.
1013
- sandboxRotationLeadMs: z.coerce.number().int().positive().default(36e5),
1438
+ sandboxRotationLeadMs: z2.coerce.number().int().positive().default(36e5),
1014
1439
  // Bound provider-deadline rotation admission independently of execution.
1015
1440
  // Every admitted box receives its own durable drain child; the control worker
1016
1441
  // limits provider I/O to 32 concurrent activities. Matching that bound avoids
1017
1442
  // both the old one-box-per-tick deadline backlog and an unbounded provider/API
1018
1443
  // burst. Operators may tune this for a differently-sized worker pool.
1019
- sandboxRotationBatchSize: z.coerce.number().int().positive().max(500).default(32),
1444
+ sandboxRotationBatchSize: z2.coerce.number().int().positive().max(500).default(32),
1020
1445
  // expires_at refresh window for a held lease (>> the turn 10s heartbeat so a
1021
1446
  // single missed heartbeat never TTL-reaps a live turn). The warming TTL is the
1022
1447
  // window a cold->warming spawner has to commit warm before a reaper resets it.
1023
- sandboxLeaseTtlMs: z.coerce.number().int().positive().default(9e4),
1024
- sandboxLeaseWarmingTtlMs: z.coerce.number().int().positive().default(12e4),
1448
+ sandboxLeaseTtlMs: z2.coerce.number().int().positive().default(9e4),
1449
+ sandboxLeaseWarmingTtlMs: z2.coerce.number().int().positive().default(12e4),
1025
1450
  // Overall user-facing budget for warming a sandbox lease. Unlike the lease TTL
1026
1451
  // (a liveness/reaper cadence), this bounds how long one turn waits for capacity
1027
1452
  // or provider creation before surfacing a clear turn.failed error.
1028
- sandboxWarmingTimeoutMs: z.coerce.number().int().positive().default(6e5),
1453
+ sandboxWarmingTimeoutMs: z2.coerce.number().int().positive().default(6e5),
1029
1454
  // Request-scoped workspace control-prefix budget: how long one HTTP-originated
1030
1455
  // session/workspace mutation (Send, Steer, Pause/Resume/Cancel, queue
1031
1456
  // move/edit/delete, composer draft, settings narrowing, quiescent tree
@@ -1034,114 +1459,132 @@ var SettingsSchema = z.object({
1034
1459
  // settlement and claims never use it. The API installs the validated value
1035
1460
  // into @opengeni/db once at app construction; nothing reads the env per
1036
1461
  // request. Env: OPENGENI_WORKSPACE_CONTROL_LOCK_TIMEOUT_MS. Default 20 s.
1037
- workspaceControlLockTimeoutMs: z.coerce.number({
1462
+ workspaceControlLockTimeoutMs: z2.coerce.number({
1038
1463
  message: "OPENGENI_WORKSPACE_CONTROL_LOCK_TIMEOUT_MS must be a positive integer (ms)"
1039
1464
  }).int("OPENGENI_WORKSPACE_CONTROL_LOCK_TIMEOUT_MS must be a positive integer (ms)").positive("OPENGENI_WORKSPACE_CONTROL_LOCK_TIMEOUT_MS must be a positive integer (ms)").default(2e4),
1040
1465
  // Rig setup-script budget (M3): the wall-clock timeout the rig-setup lifecycle
1041
1466
  // hook runs its script under, distinct from the 120s per-command lifecycle
1042
1467
  // default (a rig may compile/install heavy tooling on first cold create).
1043
1468
  // Env: OPENGENI_RIG_SETUP_TIMEOUT_MS. Default 10min.
1044
- rigSetupTimeoutMs: z.coerce.number().int().positive().default(6e5),
1469
+ rigSetupTimeoutMs: z2.coerce.number().int().positive().default(6e5),
1045
1470
  // --- sandbox warm-time billing (P2.1) ---
1046
1471
  // Per-backend warm rate (usd_micros/sec), like modelPricingJson: an empty {}
1047
1472
  // means warm-cost is not debited (warm-seconds are still metered for audit).
1048
1473
  // Shape: { "modal": 5, "runloop": 4, ... }. Backends absent here meter
1049
1474
  // warm-seconds but accrue NO warm_cost / debit (rate 0).
1050
- sandboxWarmRateMicrosPerSecondJson: z.string().default("{}"),
1475
+ sandboxWarmRateMicrosPerSecondJson: z2.string().default("{}"),
1476
+ sandboxWarmBillingMode: z2.enum(["usage_only", "shadow", "credits"]).default("usage_only"),
1051
1477
  // Per-workspace warm cap (cumulative warm-seconds since the start of the UTC
1052
1478
  // month, summed over sandbox.warm_seconds). 0 = unbounded. A workspace over the
1053
1479
  // cap force-drains its VIEWER-ONLY boxes (guarded AND turn_holders=0 — a paying
1054
1480
  // turn is never killed); the reaper then stop()s at refcount 0.
1055
- sandboxMaxWarmSecondsPerWorkspace: z.coerce.number().int().nonnegative().default(0),
1056
- sandboxPreparationProfiles: z.string().default("none"),
1057
- sandboxEnvAllowlist: z.string().default(""),
1058
- objectStorageEndpoint: z.string().url().optional(),
1059
- objectStorageInternalEndpoint: z.string().url().optional(),
1060
- objectStorageSandboxEndpoint: z.string().url().optional(),
1061
- objectStorageBackend: z.enum(["s3-compatible", "aws-s3", "azure-blob", "gcs"]).default("s3-compatible"),
1062
- objectStorageBucket: z.string().min(1).default("opengeni-files"),
1063
- objectStorageRegion: z.string().min(1).default("us-east-1"),
1064
- objectStorageS3Provider: z.string().min(1).default("Minio"),
1065
- objectStorageAccessKeyId: z.string().optional(),
1066
- objectStorageSecretAccessKey: z.string().optional(),
1481
+ sandboxMaxWarmSecondsPerWorkspace: z2.coerce.number().int().nonnegative().default(0),
1482
+ sandboxPreparationProfiles: z2.string().default("none"),
1483
+ sandboxEnvAllowlist: z2.string().default(""),
1484
+ // Comma-separated image references a workspace may select as its default
1485
+ // sandbox image. Empty keeps every workspace on the deployment image.
1486
+ sandboxImageAllowlist: z2.string().default(""),
1487
+ objectStorageEndpoint: z2.string().url().optional(),
1488
+ objectStorageInternalEndpoint: z2.string().url().optional(),
1489
+ objectStorageSandboxEndpoint: z2.string().url().optional(),
1490
+ objectStorageBackend: z2.enum(["s3-compatible", "aws-s3", "azure-blob", "gcs"]).default("s3-compatible"),
1491
+ objectStorageBucket: z2.string().min(1).default("opengeni-files"),
1492
+ objectStorageRegion: z2.string().min(1).default("us-east-1"),
1493
+ objectStorageS3Provider: z2.string().min(1).default("Minio"),
1494
+ objectStorageAccessKeyId: z2.string().optional(),
1495
+ objectStorageSecretAccessKey: z2.string().optional(),
1067
1496
  objectStorageForcePathStyle: EnvBoolean.default(true),
1068
- objectStorageAzureConnectionString: z.string().optional(),
1069
- objectStorageAzureAccountName: z.string().optional(),
1070
- objectStorageAzureAccountKey: z.string().optional(),
1071
- objectStorageAzureEndpoint: z.string().url().optional(),
1072
- objectStorageGcsProjectId: z.string().optional(),
1073
- objectStorageGcsCredentialsJson: z.string().optional(),
1074
- objectStorageGcsKeyFilename: z.string().optional(),
1075
- objectStorageGcsApiEndpoint: z.string().url().optional(),
1076
- documentParser: z.string().min(1).default("liteparse"),
1077
- documentChunkSize: z.coerce.number().int().positive().default(1200),
1078
- documentChunkOverlap: z.coerce.number().int().nonnegative().default(160),
1079
- documentEmbeddingProvider: z.enum(["openai", "deterministic"]).default("openai"),
1080
- documentEmbeddingModel: z.string().min(1).default("text-embedding-3-large"),
1081
- documentEmbeddingDimensions: z.coerce.number().int().positive().default(3072),
1082
- documentEmbeddingApiKey: z.string().optional(),
1083
- documentEmbeddingBaseUrl: z.string().url().optional(),
1084
- documentCurationProvider: z.enum(["openai", "heuristic", "none"]).default("openai"),
1085
- documentCurationModel: z.string().min(1).default("gpt-4o-mini"),
1086
- documentCurationApiKey: z.string().optional(),
1087
- documentCurationBaseUrl: z.string().url().optional(),
1088
- gitAuthorName: z.string().optional(),
1089
- gitAuthorEmail: z.string().optional(),
1090
- gitCommitterName: z.string().optional(),
1091
- gitCommitterEmail: z.string().optional(),
1092
- githubAppManifestBaseUrl: z.string().optional(),
1093
- githubAppManifestStateSecret: z.string().optional(),
1094
- githubAppId: z.string().optional(),
1095
- githubClientId: z.string().optional(),
1096
- githubClientSecret: z.string().optional(),
1497
+ objectStorageAzureConnectionString: z2.string().optional(),
1498
+ objectStorageAzureAccountName: z2.string().optional(),
1499
+ objectStorageAzureAccountKey: z2.string().optional(),
1500
+ objectStorageAzureEndpoint: z2.string().url().optional(),
1501
+ objectStorageGcsProjectId: z2.string().optional(),
1502
+ objectStorageGcsCredentialsJson: z2.string().optional(),
1503
+ objectStorageGcsKeyFilename: z2.string().optional(),
1504
+ objectStorageGcsApiEndpoint: z2.string().url().optional(),
1505
+ documentParser: z2.string().min(1).default("liteparse"),
1506
+ documentChunkSize: z2.coerce.number().int().positive().default(1200),
1507
+ documentChunkOverlap: z2.coerce.number().int().nonnegative().default(160),
1508
+ documentEmbeddingProvider: z2.enum(["openai", "deterministic"]).default("openai"),
1509
+ documentEmbeddingModel: z2.string().min(1).default("text-embedding-3-large"),
1510
+ documentEmbeddingDimensions: z2.coerce.number().int().positive().default(3072),
1511
+ documentEmbeddingApiKey: z2.string().optional(),
1512
+ documentEmbeddingBaseUrl: z2.string().url().optional(),
1513
+ documentEmbeddingBillingMode: z2.enum(["usage_only", "shadow", "credits"]).default("usage_only"),
1514
+ // Explicit commercial cutover. Existing queued revisions remain unpriced;
1515
+ // only jobs created at or after this instant may enter the paid rail.
1516
+ documentEmbeddingCreditsActivatedAt: z2.iso.datetime().optional(),
1517
+ // Customer tariff for the exact UTF-8 bytes sent to the embedder. Zero leaves
1518
+ // the paid mode unavailable; no commercial rate is selected by this PR.
1519
+ documentEmbeddingRateMicrosPerMillionBytes: z2.coerce.number().int().nonnegative().default(0),
1520
+ documentCurationProvider: z2.enum(["openai", "heuristic", "none"]).default("openai"),
1521
+ documentCurationModel: z2.string().min(1).default("gpt-4o-mini"),
1522
+ documentCurationApiKey: z2.string().optional(),
1523
+ documentCurationBaseUrl: z2.string().url().optional(),
1524
+ gitAuthorName: z2.string().optional(),
1525
+ gitAuthorEmail: z2.string().optional(),
1526
+ gitCommitterName: z2.string().optional(),
1527
+ gitCommitterEmail: z2.string().optional(),
1528
+ githubAppManifestBaseUrl: z2.string().optional(),
1529
+ githubAppManifestStateSecret: z2.string().optional(),
1530
+ githubAppId: z2.string().optional(),
1531
+ githubClientId: z2.string().optional(),
1532
+ githubClientSecret: z2.string().optional(),
1097
1533
  /** Default-off rollout for the in-process GitHub repository API tool surface. */
1098
1534
  githubRestMcpEnabled: EnvBoolean.default(false),
1099
1535
  githubPersonalOauthEnabled: EnvBoolean.default(false),
1100
- githubPersonalOauthClientId: z.string().optional(),
1101
- githubPersonalOauthClientSecret: z.string().optional(),
1102
- githubAppSlug: z.string().optional(),
1103
- githubWebhookSecret: z.string().optional(),
1104
- githubAppPrivateKey: z.string().optional(),
1105
- prReviewGithubAppId: z.string().optional(),
1106
- prReviewGithubClientId: z.string().optional(),
1107
- prReviewGithubClientSecret: z.string().optional(),
1108
- prReviewGithubAppSlug: z.string().optional(),
1109
- prReviewGithubWebhookSecret: z.string().optional(),
1110
- prReviewGithubAppPrivateKey: z.string().optional(),
1111
- betterAuthSecret: z.string().optional(),
1112
- betterAuthAllowedHosts: z.string().default(""),
1113
- betterAuthCookieDomain: z.string().optional(),
1114
- betterAuthTrustedOrigins: z.string().default(""),
1115
- managedAuthGoogleClientId: z.string().optional(),
1116
- managedAuthGoogleClientSecret: z.string().optional(),
1117
- managedAuthGithubClientId: z.string().optional(),
1118
- managedAuthGithubClientSecret: z.string().optional(),
1536
+ githubPersonalOauthClientId: z2.string().optional(),
1537
+ githubPersonalOauthClientSecret: z2.string().optional(),
1538
+ githubAppSlug: z2.string().optional(),
1539
+ githubWebhookSecret: z2.string().optional(),
1540
+ githubAppPrivateKey: z2.string().optional(),
1541
+ prReviewGithubAppId: z2.string().optional(),
1542
+ prReviewGithubClientId: z2.string().optional(),
1543
+ prReviewGithubClientSecret: z2.string().optional(),
1544
+ prReviewGithubAppSlug: z2.string().optional(),
1545
+ prReviewGithubWebhookSecret: z2.string().optional(),
1546
+ prReviewGithubAppPrivateKey: z2.string().optional(),
1547
+ betterAuthSecret: z2.string().optional(),
1548
+ betterAuthAllowedHosts: z2.string().default(""),
1549
+ betterAuthCookieDomain: z2.string().optional(),
1550
+ betterAuthTrustedOrigins: z2.string().default(""),
1551
+ managedAuthGoogleClientId: z2.string().optional(),
1552
+ managedAuthGoogleClientSecret: z2.string().optional(),
1553
+ managedAuthGithubClientId: z2.string().optional(),
1554
+ managedAuthGithubClientSecret: z2.string().optional(),
1119
1555
  // Rolling browser login-slot compatibility. Repository/deployment default is
1120
1556
  // deliberately legacy; changing to broker is an operator-authorized rollout.
1121
- managedAuthSessionSetMode: z.enum(["legacy", "dual", "broker"]).default("legacy"),
1557
+ allowedUserEmails: z2.array(z2.email().transform((email) => email.toLowerCase())).min(1).optional(),
1558
+ managedAuthSessionSetMode: z2.enum(["legacy", "dual", "broker"]).default("legacy"),
1559
+ // Deployment ceiling for new managed accounts. When false, managed auth
1560
+ // refuses every new Better Auth account (email/password sign-up and implicit
1561
+ // Google/GitHub sign-up) while existing sign-in, sessions, password reset,
1562
+ // email verification, and invitation-bound account setup keep working. Read
1563
+ // at startup; the 0585 runtime switch pauses sign-ups without a restart.
1564
+ managedAuthNewSignupsEnabled: EnvBoolean.default(true),
1122
1565
  // Query transport is an explicit second-stage rollout. A pre-compatibility
1123
1566
  // web image understands only fragment bearers, so API replicas must keep
1124
1567
  // generating fragment links until the compatible web fleet has converged.
1125
- organizationUserSetupEmailTokenTransport: z.enum(["fragment", "query"]).default("fragment"),
1568
+ organizationUserSetupEmailTokenTransport: z2.enum(["fragment", "query"]).default("fragment"),
1126
1569
  // Query-bearing setup links may appear in controller/edge error logs even
1127
1570
  // when access logs and request tracing are disabled. This explicit operator
1128
1571
  // confirmation keeps query transport fail closed until that separate sink is
1129
1572
  // proven sanitized.
1130
1573
  organizationUserSetupQueryEdgeSanitizationConfirmed: EnvBoolean.default(false),
1131
- resendApiKey: z.string().optional(),
1132
- emailFrom: z.string().default("OpenGeni <auth@mail.opengeni.ai>"),
1133
- stripeSecretKey: z.string().optional(),
1134
- stripePublishableKey: z.string().optional(),
1135
- stripeWebhookSecret: z.string().optional(),
1136
- stripeCreditsProductId: z.string().optional(),
1137
- mcpServers: z.array(
1138
- z.object({
1139
- id: z.string().min(1).regex(registryId),
1140
- name: z.string().min(1).optional(),
1141
- url: z.string().url(),
1142
- allowedTools: z.array(z.string().min(1)).optional(),
1143
- timeoutMs: z.number().int().positive().optional(),
1144
- cacheToolsList: z.boolean().default(false),
1574
+ resendApiKey: z2.string().optional(),
1575
+ emailFrom: z2.string().default("OpenGeni <auth@mail.opengeni.ai>"),
1576
+ stripeSecretKey: z2.string().optional(),
1577
+ stripePublishableKey: z2.string().optional(),
1578
+ stripeWebhookSecret: z2.string().optional(),
1579
+ stripeCreditsProductId: z2.string().optional(),
1580
+ mcpServers: z2.array(
1581
+ z2.object({
1582
+ id: z2.string().min(1).regex(registryId),
1583
+ name: z2.string().min(1).optional(),
1584
+ url: z2.string().url(),
1585
+ allowedTools: z2.array(z2.string().min(1)).optional(),
1586
+ timeoutMs: z2.number().int().positive().optional(),
1587
+ cacheToolsList: z2.boolean().default(false),
1145
1588
  /** Runtime approval policy, overlaid from an attempt-frozen session snapshot. */
1146
1589
  requireApproval: SessionMcpApprovalPolicy.optional(),
1147
1590
  /**
@@ -1150,11 +1593,109 @@ var SettingsSchema = z.object({
1150
1593
  * encrypted capability-installation credentials; do not put secrets in
1151
1594
  * OPENGENI_MCP_SERVERS.
1152
1595
  */
1153
- headers: z.record(z.string(), z.string()).optional(),
1154
- connectionRef: McpServerConnectionRefSchema.optional()
1596
+ headers: z2.record(z2.string(), z2.string()).optional(),
1597
+ connectionRef: McpServerConnectionRefSchema.optional(),
1598
+ operationRecovery: McpOperationRecoverySchema.optional()
1155
1599
  })
1156
1600
  ).default([])
1157
1601
  });
1602
+ var ArtifactServiceSettingsSchema = SettingsSchema.pick({
1603
+ serviceName: true,
1604
+ environment: true,
1605
+ deploymentRevision: true,
1606
+ dbSchema: true,
1607
+ rlsStrategy: true,
1608
+ observabilityStructuredLogs: true,
1609
+ observabilityMetricsEnabled: true,
1610
+ observabilityOtlpEndpoint: true,
1611
+ observabilityOtlpHeaders: true
1612
+ });
1613
+ var ArtifactOutboxSettingsSchema = ArtifactServiceSettingsSchema.extend({
1614
+ natsUrl: SettingsSchema.shape.natsUrl,
1615
+ selfhostedNatsControlUser: SettingsSchema.shape.selfhostedNatsControlUser,
1616
+ selfhostedNatsControlPassword: SettingsSchema.shape.selfhostedNatsControlPassword
1617
+ });
1618
+ var ObjectStorageSettingsSchema = SettingsSchema.pick({
1619
+ objectStorageBackend: true,
1620
+ objectStorageEndpoint: true,
1621
+ objectStorageInternalEndpoint: true,
1622
+ objectStorageSandboxEndpoint: true,
1623
+ objectStorageBucket: true,
1624
+ objectStorageRegion: true,
1625
+ objectStorageAccessKeyId: true,
1626
+ objectStorageSecretAccessKey: true,
1627
+ objectStorageForcePathStyle: true,
1628
+ objectStorageAzureConnectionString: true,
1629
+ objectStorageAzureAccountName: true,
1630
+ objectStorageAzureAccountKey: true,
1631
+ objectStorageAzureEndpoint: true,
1632
+ objectStorageGcsProjectId: true,
1633
+ objectStorageGcsCredentialsJson: true,
1634
+ objectStorageGcsKeyFilename: true,
1635
+ objectStorageGcsApiEndpoint: true
1636
+ });
1637
+ var ArtifactMaterializerSettingsSchema = ArtifactServiceSettingsSchema.extend(
1638
+ ObjectStorageSettingsSchema.shape
1639
+ );
1640
+ function artifactServiceEnvironment(source) {
1641
+ const optional = (name) => optionalEnvironmentValue(name, source);
1642
+ return {
1643
+ serviceName: optional("OPENGENI_SERVICE_NAME"),
1644
+ environment: optional("OPENGENI_ENVIRONMENT"),
1645
+ deploymentRevision: optional("OPENGENI_DEPLOYMENT_REVISION") ?? optional("SOURCE_VERSION") ?? optional("GITHUB_SHA"),
1646
+ dbSchema: optional("OPENGENI_DB_SCHEMA"),
1647
+ rlsStrategy: optional("OPENGENI_RLS_STRATEGY"),
1648
+ observabilityStructuredLogs: optional("OPENGENI_OBSERVABILITY_STRUCTURED_LOGS"),
1649
+ observabilityMetricsEnabled: optional("OPENGENI_OBSERVABILITY_METRICS_ENABLED"),
1650
+ observabilityOtlpEndpoint: optional("OPENGENI_OTEL_EXPORTER_OTLP_ENDPOINT") ?? optional("OTEL_EXPORTER_OTLP_ENDPOINT"),
1651
+ observabilityOtlpHeaders: optional("OPENGENI_OTEL_EXPORTER_OTLP_HEADERS") ?? optional("OTEL_EXPORTER_OTLP_HEADERS")
1652
+ };
1653
+ }
1654
+ function getArtifactOutboxSettings(source = process.env) {
1655
+ const settings = ArtifactOutboxSettingsSchema.parse({
1656
+ ...artifactServiceEnvironment(source),
1657
+ natsUrl: optionalEnvironmentValue("OPENGENI_NATS_URL", source),
1658
+ selfhostedNatsControlUser: optionalEnvironmentValue(
1659
+ "OPENGENI_SELFHOSTED_NATS_CONTROL_USER",
1660
+ source
1661
+ ),
1662
+ selfhostedNatsControlPassword: optionalEnvironmentValue(
1663
+ "OPENGENI_SELFHOSTED_NATS_CONTROL_PASSWORD",
1664
+ source
1665
+ )
1666
+ });
1667
+ dbSearchPath(settings);
1668
+ if (Boolean(settings.selfhostedNatsControlUser) !== Boolean(settings.selfhostedNatsControlPassword)) {
1669
+ throw new Error("Artifact outbox NATS control user and password must be configured together");
1670
+ }
1671
+ return settings;
1672
+ }
1673
+ function getArtifactMaterializerSettings(source = process.env) {
1674
+ const optional = (name) => optionalEnvironmentValue(name, source);
1675
+ const settings = ArtifactMaterializerSettingsSchema.parse({
1676
+ ...artifactServiceEnvironment(source),
1677
+ objectStorageEndpoint: optional("OPENGENI_OBJECT_STORAGE_ENDPOINT"),
1678
+ objectStorageInternalEndpoint: optional("OPENGENI_OBJECT_STORAGE_INTERNAL_ENDPOINT"),
1679
+ objectStorageSandboxEndpoint: optional("OPENGENI_OBJECT_STORAGE_SANDBOX_ENDPOINT"),
1680
+ objectStorageBackend: optional("OPENGENI_OBJECT_STORAGE_BACKEND"),
1681
+ objectStorageBucket: optional("OPENGENI_OBJECT_STORAGE_BUCKET"),
1682
+ objectStorageRegion: optional("OPENGENI_OBJECT_STORAGE_REGION"),
1683
+ objectStorageAccessKeyId: optional("OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID"),
1684
+ objectStorageSecretAccessKey: optional("OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY"),
1685
+ objectStorageForcePathStyle: optional("OPENGENI_OBJECT_STORAGE_FORCE_PATH_STYLE"),
1686
+ objectStorageAzureConnectionString: optional("OPENGENI_OBJECT_STORAGE_AZURE_CONNECTION_STRING"),
1687
+ objectStorageAzureAccountName: optional("OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_NAME"),
1688
+ objectStorageAzureAccountKey: optional("OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_KEY"),
1689
+ objectStorageAzureEndpoint: optional("OPENGENI_OBJECT_STORAGE_AZURE_ENDPOINT"),
1690
+ objectStorageGcsProjectId: optional("OPENGENI_OBJECT_STORAGE_GCS_PROJECT_ID"),
1691
+ objectStorageGcsCredentialsJson: optional("OPENGENI_OBJECT_STORAGE_GCS_CREDENTIALS_JSON"),
1692
+ objectStorageGcsKeyFilename: optional("OPENGENI_OBJECT_STORAGE_GCS_KEY_FILENAME"),
1693
+ objectStorageGcsApiEndpoint: optional("OPENGENI_OBJECT_STORAGE_GCS_API_ENDPOINT")
1694
+ });
1695
+ dbSearchPath(settings);
1696
+ validateObjectStorageSettings(settings);
1697
+ return settings;
1698
+ }
1158
1699
  function configuredGoogleDriveSyncLimits(settings) {
1159
1700
  return KnowledgeSourceSyncLimits.parse({
1160
1701
  maxItems: settings.googleDriveSyncMaxItems,
@@ -1195,6 +1736,24 @@ function personalGitHubOAuthCallbackUrl(publicBaseUrl) {
1195
1736
  const origin = canonicalPublicOrigin(publicBaseUrl);
1196
1737
  return origin ? `${origin}/v1/integrations/github-personal/oauth/callback` : null;
1197
1738
  }
1739
+ function usableDeploymentSecret(value) {
1740
+ return isUsableVoiceInputSecret(value) ? value : void 0;
1741
+ }
1742
+ function usableJevApiKey(settings) {
1743
+ return usableDeploymentSecret(settings.jevApiKey);
1744
+ }
1745
+ function agentConfigDeploymentPolicy(settings) {
1746
+ return agentConfigDeploymentLimitsFromAllowlist(
1747
+ resolveFirstPartyMcpToolPolicy(settings).allowed,
1748
+ settings.webSearchEnabled ? {} : { webSearch: "web search is turned off on this server" }
1749
+ );
1750
+ }
1751
+ function codeSearchDeploymentPolicy(settings) {
1752
+ const available = settings.codeSearchMode !== "off" && usableJevApiKey(settings) !== void 0;
1753
+ if (!available) return { available: false, workspaceDefault: "off" };
1754
+ const workspaceDefault = settings.codeSearchMode === "default_on" ? "on" : settings.codeSearchMode === "experiment" ? "split" : "off";
1755
+ return { available, workspaceDefault };
1756
+ }
1198
1757
  function isUsableVoiceInputSecret(value) {
1199
1758
  if (value == null) return false;
1200
1759
  const trimmed = value.trim();
@@ -1279,18 +1838,18 @@ function voiceInputDeploymentConfigured(settings) {
1279
1838
  (provider) => provider.kind !== "codex-subscription" && provider.kind !== "supergrok-subscription"
1280
1839
  );
1281
1840
  }
1282
- var ModelPricingSchema = z.object({
1283
- inputMicrosPerMillionTokens: z.number().int().nonnegative(),
1284
- cachedInputMicrosPerMillionTokens: z.number().int().nonnegative().optional(),
1285
- cacheWriteMicrosPerMillionTokens: z.number().int().nonnegative().optional(),
1286
- outputMicrosPerMillionTokens: z.number().int().nonnegative(),
1287
- marginBps: z.number().int().min(0).max(1e5).optional()
1841
+ var ModelPricingSchema = z2.object({
1842
+ inputMicrosPerMillionTokens: z2.number().int().nonnegative(),
1843
+ cachedInputMicrosPerMillionTokens: z2.number().int().nonnegative().optional(),
1844
+ cacheWriteMicrosPerMillionTokens: z2.number().int().nonnegative().optional(),
1845
+ outputMicrosPerMillionTokens: z2.number().int().nonnegative(),
1846
+ marginBps: z2.number().int().min(0).max(1e5).optional()
1288
1847
  });
1289
- var ModelPricingScheduleSchema = z.object({
1848
+ var ModelPricingScheduleSchema = z2.object({
1290
1849
  default: ModelPricingSchema,
1291
- inputTokenTiers: z.array(
1292
- z.object({
1293
- minimumInputTokens: z.number().int().nonnegative(),
1850
+ inputTokenTiers: z2.array(
1851
+ z2.object({
1852
+ minimumInputTokens: z2.number().int().nonnegative(),
1294
1853
  pricing: ModelPricingSchema
1295
1854
  })
1296
1855
  ).optional()
@@ -1307,10 +1866,10 @@ var ModelPricingScheduleSchema = z.object({
1307
1866
  previous = tier.minimumInputTokens;
1308
1867
  }
1309
1868
  });
1310
- var CapabilitySupportV1 = z.enum(["supported", "unsupported", "unknown"]);
1311
- var CapabilityStateV1Schema = z.object({
1869
+ var CapabilitySupportV1 = z2.enum(["supported", "unsupported", "unknown"]);
1870
+ var CapabilityStateV1Schema = z2.object({
1312
1871
  upstream: CapabilitySupportV1,
1313
- runnable: z.boolean()
1872
+ runnable: z2.boolean()
1314
1873
  }).superRefine((state, ctx) => {
1315
1874
  if (state.upstream === "unsupported" && state.runnable) {
1316
1875
  ctx.addIssue({
@@ -1320,17 +1879,17 @@ var CapabilityStateV1Schema = z.object({
1320
1879
  });
1321
1880
  }
1322
1881
  });
1323
- var ModelModalityV1 = z.enum(["text", "image", "audio"]);
1324
- var ModelLatencyModeV1 = z.enum(["standard", "priority", "fast"]);
1325
- var ModelCapabilitiesV1Schema = z.object({
1882
+ var ModelModalityV1 = z2.enum(["text", "image", "audio"]);
1883
+ var ModelLatencyModeV1 = z2.enum(["standard", "priority", "fast"]);
1884
+ var ModelCapabilitiesV1Schema = z2.object({
1326
1885
  reasoning: CapabilityStateV1Schema.extend({
1327
- efforts: z.array(ReasoningEffort),
1886
+ efforts: z2.array(ReasoningEffort),
1328
1887
  defaultEffort: ReasoningEffort.nullable(),
1329
- required: z.boolean()
1888
+ required: z2.boolean()
1330
1889
  }),
1331
1890
  functionCalling: CapabilityStateV1Schema,
1332
1891
  structuredOutput: CapabilityStateV1Schema,
1333
- hostedTools: z.object({
1892
+ hostedTools: z2.object({
1334
1893
  webSearch: CapabilityStateV1Schema,
1335
1894
  xSearch: CapabilityStateV1Schema,
1336
1895
  codeExecution: CapabilityStateV1Schema,
@@ -1339,24 +1898,24 @@ var ModelCapabilitiesV1Schema = z.object({
1339
1898
  runnable: false
1340
1899
  })
1341
1900
  }),
1342
- inputModalities: z.array(ModelModalityV1).min(1),
1901
+ inputModalities: z2.array(ModelModalityV1).min(1),
1343
1902
  /** Exact MIME types accepted as typed `input_file`; `text/*` is allowed. */
1344
- inputFileMediaTypes: z.array(z.string()).default([]),
1345
- outputModalities: z.array(ModelModalityV1).min(1),
1346
- transports: z.object({
1903
+ inputFileMediaTypes: z2.array(z2.string()).default([]),
1904
+ outputModalities: z2.array(ModelModalityV1).min(1),
1905
+ transports: z2.object({
1347
1906
  sse: CapabilityStateV1Schema,
1348
1907
  responsesWebSocket: CapabilityStateV1Schema,
1349
1908
  realtimeAudio: CapabilityStateV1Schema
1350
1909
  }),
1351
1910
  promptCaching: CapabilityStateV1Schema.extend({
1352
- mode: z.enum(["implicit", "automatic", "none"])
1911
+ mode: z2.enum(["implicit", "automatic", "none"])
1353
1912
  }).optional(),
1354
- latencyModes: z.array(
1355
- z.object({
1913
+ latencyModes: z2.array(
1914
+ z2.object({
1356
1915
  id: ModelLatencyModeV1,
1357
1916
  upstream: CapabilitySupportV1,
1358
- runnable: z.boolean(),
1359
- billingMultiplierBps: z.number().int().positive().optional()
1917
+ runnable: z2.boolean(),
1918
+ billingMultiplierBps: z2.number().int().positive().optional()
1360
1919
  })
1361
1920
  ).min(1)
1362
1921
  }).superRefine((capabilities, ctx) => {
@@ -1410,9 +1969,9 @@ var ModelCapabilitiesV1Schema = z.object({
1410
1969
  }
1411
1970
  }
1412
1971
  });
1413
- var ModelProviderApi = z.enum(["responses", "chat"]);
1414
- var ModelProviderWireProfile = z.enum(["openai", "azure-openai"]);
1415
- var RegistryProviderKind = z.enum([
1972
+ var ModelProviderApi = z2.enum(["responses", "chat", "anthropic-messages"]);
1973
+ var ModelProviderWireProfile = z2.enum(["openai", "azure-openai"]);
1974
+ var RegistryProviderKind = z2.enum([
1416
1975
  "api-key",
1417
1976
  "anonymous",
1418
1977
  "codex-subscription",
@@ -1420,36 +1979,42 @@ var RegistryProviderKind = z.enum([
1420
1979
  "vercel-gateway-managed",
1421
1980
  "vercel-gateway-workspace",
1422
1981
  "vercel-gateway-organization",
1982
+ "direct-openai-workspace",
1983
+ "direct-azure-workspace",
1423
1984
  "openrouter-workspace",
1424
- "openrouter-organization"
1985
+ "openrouter-organization",
1986
+ "anthropic-organization",
1987
+ "claude-subscription-organization",
1988
+ "anthropic-workspace",
1989
+ "claude-subscription-workspace"
1425
1990
  ]);
1426
- var RegistryModelSchema = z.object({
1427
- id: z.string().min(1),
1991
+ var RegistryModelSchema = z2.object({
1992
+ id: z2.string().min(1),
1428
1993
  // canonical OpenGeni product id
1429
- upstreamModelId: z.string().min(1).optional(),
1994
+ upstreamModelId: z2.string().min(1).optional(),
1430
1995
  // exact provider slug; defaults to id
1431
- aliases: z.array(z.string().min(1)).optional(),
1996
+ aliases: z2.array(z2.string().min(1)).optional(),
1432
1997
  // accepted input only; never sent upstream
1433
- label: z.string().min(1).optional(),
1998
+ label: z2.string().min(1).optional(),
1434
1999
  // display name; defaults to id
1435
- shortLabel: z.string().min(1).max(64).optional(),
2000
+ shortLabel: z2.string().min(1).max(64).optional(),
1436
2001
  // compact UI label; optional
1437
- contextWindowTokens: z.number().int().positive().optional(),
1438
- effectiveContextWindowTokens: z.number().int().positive().optional(),
1439
- autoCompactTokenLimit: z.number().int().positive().optional(),
2002
+ contextWindowTokens: z2.number().int().positive().optional(),
2003
+ effectiveContextWindowTokens: z2.number().int().positive().optional(),
2004
+ autoCompactTokenLimit: z2.number().int().positive().optional(),
1440
2005
  // Canonical model-facing function/tool-result policy. The runtime applies
1441
2006
  // the same 1.2x serialization allowance as Codex when materializing output.
1442
- toolOutputTruncationTokens: z.number().int().positive().optional(),
1443
- reasoningEffort: z.boolean().optional(),
2007
+ toolOutputTruncationTokens: z2.number().int().positive().optional(),
2008
+ reasoningEffort: z2.boolean().optional(),
1444
2009
  // legacy compatibility input/projection
1445
- hostedWebSearch: z.boolean().optional(),
2010
+ hostedWebSearch: z2.boolean().optional(),
1446
2011
  // legacy compatibility input/projection
1447
2012
  capabilities: ModelCapabilitiesV1Schema.optional(),
1448
- pricing: z.union([ModelPricingSchema, ModelPricingScheduleSchema]).optional(),
2013
+ pricing: z2.union([ModelPricingSchema, ModelPricingScheduleSchema]).optional(),
1449
2014
  // Reserved normalized contracts are derived by OpenGeni in V1. Generic
1450
2015
  // registry JSON must not opt itself into workspace BYOK or reattribute cost.
1451
- credentialSource: z.never().optional(),
1452
- billing: z.never().optional()
2016
+ credentialSource: z2.never().optional(),
2017
+ billing: z2.never().optional()
1453
2018
  }).superRefine((model, ctx) => {
1454
2019
  if (model.capabilities && model.reasoningEffort !== void 0 && model.reasoningEffort !== model.capabilities.reasoning.runnable) {
1455
2020
  ctx.addIssue({
@@ -1466,27 +2031,54 @@ var RegistryModelSchema = z.object({
1466
2031
  });
1467
2032
  }
1468
2033
  });
1469
- var RegistryProviderSchema = z.object({
2034
+ var ClaudeSubscriptionIdentity = z2.object({
2035
+ accountUuid: z2.union([z2.string().uuid(), z2.literal("")]),
2036
+ deviceId: z2.string().regex(/^[a-f0-9]{64}$/)
2037
+ }).strict();
2038
+ var ClaudeSubscriptionCredential = z2.object({
2039
+ version: z2.literal(1),
2040
+ token: z2.string().regex(/^sk-ant-oat[0-9]+-\S+$/),
2041
+ identity: ClaudeSubscriptionIdentity,
2042
+ oauth: z2.object({
2043
+ refreshToken: z2.string().min(1).max(16384),
2044
+ expiresAt: z2.string().datetime(),
2045
+ scopes: z2.array(z2.string().min(1).max(256)).min(1).max(32)
2046
+ }).strict().optional()
2047
+ }).strict();
2048
+ var AnthropicProviderOptions = z2.object({
2049
+ identity: ClaudeSubscriptionIdentity.optional(),
2050
+ // Native connection provenance only; never included in Anthropic request bodies.
2051
+ credentialBinding: z2.object({
2052
+ connectionId: z2.string().uuid(),
2053
+ credentialVersion: z2.number().int().positive()
2054
+ }).strict().optional(),
2055
+ auth: z2.enum(["api-key", "oauth"]).default("api-key"),
2056
+ cacheTtl: z2.enum(["5m", "1h", "off"]).default("5m"),
2057
+ maxOutputTokens: z2.number().int().positive().default(32e3),
2058
+ streamIdleTimeoutMs: z2.number().int().positive().default(6e5)
2059
+ });
2060
+ var RegistryProviderSchema = z2.object({
1470
2061
  kind: RegistryProviderKind.default("api-key"),
1471
- id: z.string().min(1).regex(registryId),
2062
+ id: z2.string().min(1).regex(registryId),
1472
2063
  // stable provider id, e.g. "fireworks"
1473
- label: z.string().min(1).optional(),
2064
+ label: z2.string().min(1).optional(),
1474
2065
  api: ModelProviderApi.default("chat"),
2066
+ anthropic: AnthropicProviderOptions.optional(),
1475
2067
  wireProfile: ModelProviderWireProfile.default("openai"),
1476
- baseUrl: z.string().url(),
1477
- apiKey: z.string().optional(),
2068
+ baseUrl: z2.string().url(),
2069
+ apiKey: z2.string().optional(),
1478
2070
  // inline key (pragmatic) ...
1479
- apiKeyEnv: z.string().optional(),
2071
+ apiKeyEnv: z2.string().optional(),
1480
2072
  // ... OR name of the env var holding the key (preferred)
1481
- defaultQuery: z.record(z.string(), z.string()).optional(),
1482
- defaultHeaders: z.record(z.string(), z.string()).optional(),
1483
- publicDefaultQueryNames: z.array(z.string().min(1)).optional(),
1484
- publicDefaultHeaderNames: z.array(z.string().min(1)).optional(),
2073
+ defaultQuery: z2.record(z2.string(), z2.string()).optional(),
2074
+ defaultHeaders: z2.record(z2.string(), z2.string()).optional(),
2075
+ publicDefaultQueryNames: z2.array(z2.string().min(1)).optional(),
2076
+ publicDefaultHeaderNames: z2.array(z2.string().min(1)).optional(),
1485
2077
  // V1 derives these from provider kind. Workspace BYOK is deliberately not a
1486
2078
  // registry switch and requires a separately reviewed encrypted broker.
1487
- credentialSource: z.never().optional(),
1488
- billing: z.never().optional(),
1489
- models: z.array(RegistryModelSchema).min(1)
2079
+ credentialSource: z2.never().optional(),
2080
+ billing: z2.never().optional(),
2081
+ models: z2.array(RegistryModelSchema).min(1)
1490
2082
  }).superRefine((provider, ctx) => {
1491
2083
  if (provider.kind !== "anonymous") {
1492
2084
  return;
@@ -1556,17 +2148,21 @@ var RESERVED_MODEL_PROVIDER_IDS = /* @__PURE__ */ new Set([
1556
2148
  ORGANIZATION_GATEWAY_PROVIDER_ID,
1557
2149
  OPENROUTER_PROVIDER_ID,
1558
2150
  WORKSPACE_OPENROUTER_PROVIDER_ID,
1559
- ORGANIZATION_OPENROUTER_PROVIDER_ID
2151
+ ORGANIZATION_OPENROUTER_PROVIDER_ID,
2152
+ "organization-anthropic",
2153
+ "organization-claude-subscription",
2154
+ "workspace-anthropic",
2155
+ "workspace-claude-subscription"
1560
2156
  ]);
1561
- var ModelCostClass = z.enum(["free", "credits"]);
1562
- var ConfiguredModelCostClass = z.enum([
2157
+ var ModelCostClass = z2.enum(["free", "credits"]);
2158
+ var ConfiguredModelCostClass = z2.enum([
1563
2159
  "free",
1564
2160
  "credits",
1565
2161
  "subscription",
1566
2162
  "workspace",
1567
2163
  "organization"
1568
2164
  ]);
1569
- var ModelNote = z.string().max(500).refine((value) => !/[\r\n|]/u.test(value), {
2165
+ var ModelNote = z2.string().max(500).refine((value) => !/[\r\n|]/u.test(value), {
1570
2166
  message: "model notes must not contain newlines or the | field separator"
1571
2167
  });
1572
2168
  function parseModelCostPolicyJson(raw) {
@@ -1579,7 +2175,7 @@ function parseModelCostPolicyJson(raw) {
1579
2175
  { cause: error }
1580
2176
  );
1581
2177
  }
1582
- return z.record(z.string().min(1), ModelCostClass).parse(parsed);
2178
+ return z2.record(z2.string().min(1), ModelCostClass).parse(parsed);
1583
2179
  }
1584
2180
  function parseModelNotesJson(raw) {
1585
2181
  let parsed;
@@ -1591,45 +2187,45 @@ function parseModelNotesJson(raw) {
1591
2187
  { cause: error }
1592
2188
  );
1593
2189
  }
1594
- return z.record(z.string().min(1), ModelNote).parse(parsed);
2190
+ return z2.record(z2.string().min(1), ModelNote).parse(parsed);
1595
2191
  }
1596
2192
  function configuredModelNotes(settings) {
1597
2193
  return parseModelNotesJson(settings.modelNotesJson);
1598
2194
  }
1599
- var GatewayCatalogModel = z.object({
1600
- productId: z.string().min(1),
1601
- workspaceProductId: z.string().min(1).startsWith(WORKSPACE_GATEWAY_MODEL_ID_PREFIX),
1602
- upstreamModelId: z.string().min(1),
1603
- label: z.string().min(1),
1604
- shortLabel: z.string().min(1).max(64).optional(),
1605
- providers: z.array(z.string().min(1)).min(1),
1606
- implicitCaching: z.boolean().default(false),
1607
- vision: z.boolean().default(false),
1608
- inputFileMediaTypes: z.array(z.string().min(1)).default([]),
1609
- contextWindowTokens: z.number().int().positive().default(1e6),
1610
- effectiveContextWindowTokens: z.number().int().positive().default(9e5),
1611
- autoCompactTokenLimit: z.number().int().positive().default(85e4),
1612
- pricing: z.union([ModelPricingSchema, ModelPricingScheduleSchema]).optional(),
1613
- credentialSource: z.never().optional(),
1614
- billing: z.never().optional(),
1615
- apiKey: z.never().optional()
2195
+ var GatewayCatalogModel = z2.object({
2196
+ productId: z2.string().min(1),
2197
+ workspaceProductId: z2.string().min(1).startsWith(WORKSPACE_GATEWAY_MODEL_ID_PREFIX),
2198
+ upstreamModelId: z2.string().min(1),
2199
+ label: z2.string().min(1),
2200
+ shortLabel: z2.string().min(1).max(64).optional(),
2201
+ providers: z2.array(z2.string().min(1)).min(1),
2202
+ implicitCaching: z2.boolean().default(false),
2203
+ vision: z2.boolean().default(false),
2204
+ inputFileMediaTypes: z2.array(z2.string().min(1)).default([]),
2205
+ contextWindowTokens: z2.number().int().positive().default(1e6),
2206
+ effectiveContextWindowTokens: z2.number().int().positive().default(9e5),
2207
+ autoCompactTokenLimit: z2.number().int().positive().default(85e4),
2208
+ pricing: z2.union([ModelPricingSchema, ModelPricingScheduleSchema]).optional(),
2209
+ credentialSource: z2.never().optional(),
2210
+ billing: z2.never().optional(),
2211
+ apiKey: z2.never().optional()
1616
2212
  }).strict();
1617
- var OpenRouterCatalogModel = z.object({
1618
- upstreamModelId: z.string().min(1).endsWith(":free"),
1619
- label: z.string().min(1),
1620
- shortLabel: z.string().min(1).max(64).optional(),
1621
- aliases: z.array(z.string().min(1)).default([]),
2213
+ var OpenRouterCatalogModel = z2.object({
2214
+ upstreamModelId: z2.string().min(1).endsWith(":free"),
2215
+ label: z2.string().min(1),
2216
+ shortLabel: z2.string().min(1).max(64).optional(),
2217
+ aliases: z2.array(z2.string().min(1)).default([]),
1622
2218
  capabilities: ModelCapabilitiesV1Schema,
1623
- contextWindowTokens: z.number().int().positive().optional(),
1624
- effectiveContextWindowTokens: z.number().int().positive().optional(),
1625
- autoCompactTokenLimit: z.number().int().positive().optional(),
1626
- toolOutputTruncationTokens: z.number().int().positive().optional(),
1627
- credentialSource: z.never().optional(),
1628
- billing: z.never().optional(),
1629
- pricing: z.never().optional(),
1630
- apiKey: z.never().optional()
2219
+ contextWindowTokens: z2.number().int().positive().optional(),
2220
+ effectiveContextWindowTokens: z2.number().int().positive().optional(),
2221
+ autoCompactTokenLimit: z2.number().int().positive().optional(),
2222
+ toolOutputTruncationTokens: z2.number().int().positive().optional(),
2223
+ credentialSource: z2.never().optional(),
2224
+ billing: z2.never().optional(),
2225
+ pricing: z2.never().optional(),
2226
+ apiKey: z2.never().optional()
1631
2227
  }).strict();
1632
- var DeploymentRegistryBaseUrl = z.string().url().superRefine((value, context) => {
2228
+ var DeploymentRegistryBaseUrl = z2.string().url().superRefine((value, context) => {
1633
2229
  const url = new URL(value);
1634
2230
  if (url.username || url.password) {
1635
2231
  context.addIssue({
@@ -1650,40 +2246,66 @@ var DeploymentRegistryBaseUrl = z.string().url().superRefine((value, context) =>
1650
2246
  });
1651
2247
  }
1652
2248
  });
1653
- var DeploymentRegistryProviderKind = z.enum(["api-key", "anonymous"]);
2249
+ var DeploymentRegistryProviderKind = z2.enum(["api-key", "anonymous"]);
1654
2250
  var DeploymentRegistryModelSchema = RegistryModelSchema.safeExtend({
1655
- pricing: z.never().optional()
2251
+ pricing: z2.never().optional()
1656
2252
  }).strict();
1657
2253
  var DeploymentRegistryProviderSchema = RegistryProviderSchema.safeExtend({
1658
2254
  kind: DeploymentRegistryProviderKind.default("api-key"),
1659
2255
  baseUrl: DeploymentRegistryBaseUrl,
1660
- models: z.array(DeploymentRegistryModelSchema).min(1),
1661
- apiKey: z.never().optional(),
1662
- apiKeyEnv: z.never().optional(),
1663
- defaultHeaders: z.never().optional(),
1664
- defaultQuery: z.never().optional(),
1665
- publicDefaultHeaderNames: z.never().optional(),
1666
- publicDefaultQueryNames: z.never().optional()
2256
+ models: z2.array(DeploymentRegistryModelSchema).min(1),
2257
+ apiKey: z2.never().optional(),
2258
+ apiKeyEnv: z2.never().optional(),
2259
+ defaultHeaders: z2.never().optional(),
2260
+ defaultQuery: z2.never().optional(),
2261
+ publicDefaultHeaderNames: z2.never().optional(),
2262
+ publicDefaultQueryNames: z2.never().optional()
1667
2263
  }).strict();
1668
2264
  var DeploymentGatewayCatalogModelSchema = GatewayCatalogModel.safeExtend({
1669
- pricing: z.never().optional()
2265
+ pricing: z2.never().optional()
1670
2266
  }).strict();
1671
- var ModelCatalogDocument = z.object({
1672
- schemaVersion: z.literal(1),
2267
+ var CodexCatalogModelSchema = RegistryModelSchema.safeExtend({
2268
+ retired: z2.boolean().optional(),
2269
+ id: z2.string().regex(/^codex\/[a-zA-Z0-9][a-zA-Z0-9._-]*$/),
2270
+ upstreamModelId: z2.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/),
2271
+ capabilities: ModelCapabilitiesV1Schema,
2272
+ pricing: z2.never().optional()
2273
+ }).strict().superRefine((model, context) => {
2274
+ if (model.id !== `${CODEX_MODEL_ID_PREFIX}${model.upstreamModelId}`) {
2275
+ context.addIssue({
2276
+ code: "custom",
2277
+ path: ["id"],
2278
+ message: "Codex product id must match its upstream model slug"
2279
+ });
2280
+ }
2281
+ }).transform((model) => ({
2282
+ ...model,
2283
+ capabilities: reviewedCodexCatalogCapabilities(model.upstreamModelId, model.capabilities)
2284
+ }));
2285
+ var ModelCatalogDocument = z2.object({
2286
+ schemaVersion: z2.literal(1),
1673
2287
  /** Canonical deployment default. Omission preserves the V1 first-built-in
1674
2288
  * fallback for existing documents; operators should set this explicitly
1675
2289
  * when cutting over a registry or connected-subscription default. */
1676
- defaultModel: z.string().min(1).optional(),
1677
- builtInModels: z.array(z.string().min(1)).min(1),
1678
- registryProviders: z.array(DeploymentRegistryProviderSchema).default([]),
1679
- gatewayModels: z.array(DeploymentGatewayCatalogModelSchema).default([]),
1680
- openrouterModels: z.array(OpenRouterCatalogModel).default([]),
1681
- modelNotes: z.record(z.string().min(1), ModelNote).default({}),
1682
- billing: z.never().optional(),
1683
- enabled: z.never().optional(),
1684
- apiKey: z.never().optional(),
1685
- bands: z.never().optional()
2290
+ defaultModel: z2.string().min(1).optional(),
2291
+ builtInModels: z2.array(z2.string().min(1)),
2292
+ registryProviders: z2.array(DeploymentRegistryProviderSchema).default([]),
2293
+ codexModels: z2.array(CodexCatalogModelSchema).optional(),
2294
+ gatewayModels: z2.array(DeploymentGatewayCatalogModelSchema).default([]),
2295
+ openrouterModels: z2.array(OpenRouterCatalogModel).default([]),
2296
+ modelNotes: z2.record(z2.string().min(1), ModelNote).default({}),
2297
+ billing: z2.never().optional(),
2298
+ enabled: z2.never().optional(),
2299
+ apiKey: z2.never().optional(),
2300
+ bands: z2.never().optional()
1686
2301
  }).strict().superRefine((document, context) => {
2302
+ if (document.builtInModels.length === 0 && !document.defaultModel) {
2303
+ context.addIssue({
2304
+ code: "custom",
2305
+ path: ["defaultModel"],
2306
+ message: "catalogs without built-in models require an explicit default model"
2307
+ });
2308
+ }
1687
2309
  const productIds = /* @__PURE__ */ new Set();
1688
2310
  const providerIds = /* @__PURE__ */ new Set();
1689
2311
  const gatewayUpstreamIds = /* @__PURE__ */ new Set();
@@ -1705,8 +2327,16 @@ var ModelCatalogDocument = z.object({
1705
2327
  productIds.add(id);
1706
2328
  };
1707
2329
  document.builtInModels.forEach((id, index) => add(id, ["builtInModels", index]));
2330
+ document.codexModels?.forEach((model, index) => add(model.id, ["codexModels", index, "id"]));
2331
+ if (document.codexModels?.some((model) => model.retired && model.id === document.defaultModel)) {
2332
+ context.addIssue({
2333
+ code: "custom",
2334
+ path: ["defaultModel"],
2335
+ message: "a retired model cannot be the deployment default"
2336
+ });
2337
+ }
1708
2338
  document.registryProviders.forEach((provider, providerIndex) => {
1709
- if (RESERVED_MODEL_PROVIDER_IDS.has(provider.id)) {
2339
+ if (RESERVED_MODEL_PROVIDER_IDS.has(provider.id) || provider.id.startsWith("workspace-openai-") || provider.id.startsWith("workspace-azure-openai-")) {
1710
2340
  context.addIssue({
1711
2341
  code: "custom",
1712
2342
  path: ["registryProviders", providerIndex, "id"],
@@ -1751,7 +2381,7 @@ var ModelCatalogDocument = z.object({
1751
2381
  message: "catalog default model must not contain newlines or the | field separator"
1752
2382
  });
1753
2383
  }
1754
- if (document.defaultModel && !productIds.has(document.defaultModel) && !document.defaultModel.startsWith(CODEX_MODEL_ID_PREFIX) && !document.defaultModel.startsWith(XAI_SUBSCRIPTION_MODEL_ID_PREFIX)) {
2384
+ if (document.defaultModel && !productIds.has(document.defaultModel) && !(document.codexModels === void 0 && document.defaultModel.startsWith(CODEX_MODEL_ID_PREFIX)) && !document.defaultModel.startsWith(XAI_SUBSCRIPTION_MODEL_ID_PREFIX)) {
1755
2385
  context.addIssue({
1756
2386
  code: "custom",
1757
2387
  path: ["defaultModel"],
@@ -1821,15 +2451,19 @@ function applyModelCatalogDocument(settings, rawDocument) {
1821
2451
  ),
1822
2452
  resolvedGatewayModelsJson: JSON.stringify(document.gatewayModels),
1823
2453
  resolvedOpenRouterModelsJson: JSON.stringify(document.openrouterModels),
2454
+ resolvedCodexModelsJson: document.codexModels === void 0 ? void 0 : JSON.stringify(document.codexModels),
1824
2455
  modelNotesJson: JSON.stringify(document.modelNotes)
1825
2456
  };
1826
2457
  return resolved;
1827
2458
  }
1828
- var IntegrationOAuthClientConfigSchema = z.object({
1829
- clientId: z.string().min(1),
1830
- clientSecret: z.string().min(1).optional(),
1831
- tokenEndpointAuthMethod: z.enum(["none", "client_secret_post", "client_secret_basic"]).default("none")
2459
+ var IntegrationOAuthClientConfigSchema = z2.object({
2460
+ clientId: z2.string().min(1),
2461
+ clientSecret: z2.string().min(1).optional(),
2462
+ tokenEndpointAuthMethod: z2.enum(["none", "client_secret_post", "client_secret_basic"]).default("none")
1832
2463
  });
2464
+ function isManagedOpenRouterFreeRoute(route) {
2465
+ return route.provider.kind === "openrouter-managed" && route.configured.upstreamModelId.endsWith(":free");
2466
+ }
1833
2467
  var VERCEL_AI_GATEWAY_BASE_URL = "https://ai-gateway.vercel.sh/v1";
1834
2468
  var VERCEL_AI_GATEWAY_AI_SDK_BASE_URL = "https://ai-gateway.vercel.sh/v4/ai";
1835
2469
  var VERCEL_AI_GATEWAY_CONNECTION_DOMAIN = "ai-gateway.vercel.sh";
@@ -1903,12 +2537,10 @@ var OPENGENI_OPENROUTER_MODELS = [
1903
2537
  capabilities: {
1904
2538
  reasoning: {
1905
2539
  upstream: "supported",
1906
- // OpenRouter advertises the reasoning controls, but the catalogue does
1907
- // not publish this model's accepted effort vocabulary. Preserve that
1908
- // upstream fact without exposing an unverified runnable selector.
1909
- runnable: false,
1910
- efforts: [],
1911
- defaultEffort: null,
2540
+ // OpenRouter /api/v1/models advertises low and medium for this route.
2541
+ runnable: true,
2542
+ efforts: ["low", "medium"],
2543
+ defaultEffort: "medium",
1912
2544
  required: false
1913
2545
  },
1914
2546
  functionCalling: { upstream: "supported", runnable: true },
@@ -1958,7 +2590,7 @@ function configuredGatewayCatalogModels(settings) {
1958
2590
  if (settings.resolvedGatewayModelsJson === void 0) {
1959
2591
  return defaultGatewayCatalogModels();
1960
2592
  }
1961
- return z.array(GatewayCatalogModel).parse(JSON.parse(settings.resolvedGatewayModelsJson));
2593
+ return z2.array(GatewayCatalogModel).parse(JSON.parse(settings.resolvedGatewayModelsJson));
1962
2594
  }
1963
2595
  function configuredGatewayUpstreamModelIds(settings) {
1964
2596
  return configuredGatewayCatalogModels(settings).map((model) => model.upstreamModelId);
@@ -1977,7 +2609,7 @@ function configuredOpenRouterCatalogModels(settings) {
1977
2609
  if (settings.resolvedOpenRouterModelsJson === void 0) {
1978
2610
  return [...OPENGENI_OPENROUTER_MODELS];
1979
2611
  }
1980
- return z.array(OpenRouterCatalogModel).parse(JSON.parse(settings.resolvedOpenRouterModelsJson));
2612
+ return z2.array(OpenRouterCatalogModel).parse(JSON.parse(settings.resolvedOpenRouterModelsJson));
1981
2613
  }
1982
2614
  function configuredOpenRouterUpstreamModelIds(settings) {
1983
2615
  return configuredOpenRouterCatalogModels(settings).map((model) => model.upstreamModelId);
@@ -1995,6 +2627,73 @@ function configuredOpenRouterOrganizationProductModelIds(settings) {
1995
2627
  return [];
1996
2628
  }
1997
2629
  var defaultModelPricing = {
2630
+ "gpt-6-astra": {
2631
+ default: {
2632
+ // OpenAI list price: $10 / $1 cached / $12.50 cache write / $50 output.
2633
+ inputMicrosPerMillionTokens: 1e7,
2634
+ cachedInputMicrosPerMillionTokens: 1e6,
2635
+ cacheWriteMicrosPerMillionTokens: 125e5,
2636
+ outputMicrosPerMillionTokens: 5e7,
2637
+ marginBps: 500
2638
+ },
2639
+ inputTokenTiers: [
2640
+ {
2641
+ // Prompts with more than 272K input tokens use 2x input and 1.5x output.
2642
+ minimumInputTokens: 272001,
2643
+ pricing: {
2644
+ inputMicrosPerMillionTokens: 2e7,
2645
+ cachedInputMicrosPerMillionTokens: 2e6,
2646
+ cacheWriteMicrosPerMillionTokens: 25e6,
2647
+ outputMicrosPerMillionTokens: 75e6,
2648
+ marginBps: 500
2649
+ }
2650
+ }
2651
+ ]
2652
+ },
2653
+ "gpt-6-sol": {
2654
+ default: {
2655
+ // OpenAI list price: $2 / $0.20 cached / $2.50 cache write / $10 output.
2656
+ inputMicrosPerMillionTokens: 2e6,
2657
+ cachedInputMicrosPerMillionTokens: 2e5,
2658
+ cacheWriteMicrosPerMillionTokens: 25e5,
2659
+ outputMicrosPerMillionTokens: 1e7,
2660
+ marginBps: 500
2661
+ },
2662
+ inputTokenTiers: [
2663
+ {
2664
+ minimumInputTokens: 272001,
2665
+ pricing: {
2666
+ inputMicrosPerMillionTokens: 4e6,
2667
+ cachedInputMicrosPerMillionTokens: 4e5,
2668
+ cacheWriteMicrosPerMillionTokens: 5e6,
2669
+ outputMicrosPerMillionTokens: 15e6,
2670
+ marginBps: 500
2671
+ }
2672
+ }
2673
+ ]
2674
+ },
2675
+ "gpt-6-luna": {
2676
+ default: {
2677
+ // OpenAI list price: $0.10 / $0.01 cached / $0.125 cache write / $0.50 output.
2678
+ inputMicrosPerMillionTokens: 1e5,
2679
+ cachedInputMicrosPerMillionTokens: 1e4,
2680
+ cacheWriteMicrosPerMillionTokens: 125e3,
2681
+ outputMicrosPerMillionTokens: 5e5,
2682
+ marginBps: 500
2683
+ },
2684
+ inputTokenTiers: [
2685
+ {
2686
+ minimumInputTokens: 272001,
2687
+ pricing: {
2688
+ inputMicrosPerMillionTokens: 2e5,
2689
+ cachedInputMicrosPerMillionTokens: 2e4,
2690
+ cacheWriteMicrosPerMillionTokens: 25e4,
2691
+ outputMicrosPerMillionTokens: 75e4,
2692
+ marginBps: 500
2693
+ }
2694
+ }
2695
+ ]
2696
+ },
1998
2697
  "gpt-5.6-sol": {
1999
2698
  default: {
2000
2699
  // Promotional OpenAI pricing, guaranteed through at least 2026-11-21.
@@ -2094,6 +2793,103 @@ var defaultModelPricing = {
2094
2793
  }
2095
2794
  }
2096
2795
  };
2796
+ var reviewedModelListPricing = {
2797
+ // Reviewed 2026-10-03 against https://developers.openai.com/api/docs/pricing
2798
+ // and https://ai-gateway.vercel.sh/v1/models. GPT-6.1 Sol's cache-read rate
2799
+ // is 5% of input, not GPT-6 Sol's 10%. The long-context boundary is >272K.
2800
+ "gpt-6.1-sol": {
2801
+ default: {
2802
+ inputMicrosPerMillionTokens: 2e6,
2803
+ cachedInputMicrosPerMillionTokens: 1e5,
2804
+ cacheWriteMicrosPerMillionTokens: 25e5,
2805
+ outputMicrosPerMillionTokens: 1e7,
2806
+ marginBps: 500
2807
+ },
2808
+ inputTokenTiers: [
2809
+ {
2810
+ minimumInputTokens: 272001,
2811
+ pricing: {
2812
+ inputMicrosPerMillionTokens: 4e6,
2813
+ cachedInputMicrosPerMillionTokens: 2e5,
2814
+ cacheWriteMicrosPerMillionTokens: 5e6,
2815
+ outputMicrosPerMillionTokens: 15e6,
2816
+ marginBps: 500
2817
+ }
2818
+ }
2819
+ ]
2820
+ },
2821
+ // xAI Standard API list rates, reviewed 2026-10-03:
2822
+ // https://docs.x.ai/developers/models/grok-4.5 (and grok-4.6 / grok-4.7).
2823
+ // Preserve the native API's established >=200K boundary. Gateway's separately
2824
+ // configured >200K schedule is not interchangeable with this native schedule.
2825
+ // xAI's automatic caching has no separate cache-write surcharge.
2826
+ ...Object.fromEntries(
2827
+ [
2828
+ ["grok-4.5", 3e5],
2829
+ ["grok-4.6", 5e5],
2830
+ ["grok-4.7", 5e5]
2831
+ ].map(([model, cachedInput]) => [
2832
+ model,
2833
+ {
2834
+ default: {
2835
+ inputMicrosPerMillionTokens: 2e6,
2836
+ cachedInputMicrosPerMillionTokens: cachedInput,
2837
+ outputMicrosPerMillionTokens: 6e6,
2838
+ marginBps: 500
2839
+ },
2840
+ inputTokenTiers: [
2841
+ {
2842
+ minimumInputTokens: 2e5,
2843
+ pricing: {
2844
+ inputMicrosPerMillionTokens: 4e6,
2845
+ cachedInputMicrosPerMillionTokens: cachedInput * 2,
2846
+ outputMicrosPerMillionTokens: 12e6,
2847
+ marginBps: 500
2848
+ }
2849
+ }
2850
+ ]
2851
+ }
2852
+ ])
2853
+ ),
2854
+ // Every reviewed native Claude profile. Standard/global prices include
2855
+ // 5-minute cache writes; 1-hour native routes are projected separately.
2856
+ // https://platform.claude.com/docs/en/about-claude/pricing (2026-10-03).
2857
+ // Opus 5.5 cache reads are 5%, unlike the older models' 10%; none of these
2858
+ // models has a long-context premium.
2859
+ ...Object.fromEntries(
2860
+ [
2861
+ ["claude-opus-5-5", 4e6, 2e5, 5e6, 2e7],
2862
+ ["claude-sonnet-5-5", 2e6, 2e5, 25e5, 1e7],
2863
+ ["claude-opus-5", 5e6, 5e5, 625e4, 25e6],
2864
+ ["claude-sonnet-5", 2e6, 2e5, 25e5, 1e7],
2865
+ ["claude-opus-4-8", 5e6, 5e5, 625e4, 25e6],
2866
+ ["claude-opus-4-7", 5e6, 5e5, 625e4, 25e6],
2867
+ ["claude-opus-4-6", 5e6, 5e5, 625e4, 25e6],
2868
+ ["claude-sonnet-4-6", 3e6, 3e5, 375e4, 15e6],
2869
+ ["claude-haiku-4-5-20251001", 1e6, 1e5, 125e4, 5e6]
2870
+ ].map(([model, input, cachedInput, cacheWrite, output]) => [
2871
+ model,
2872
+ {
2873
+ default: {
2874
+ inputMicrosPerMillionTokens: input,
2875
+ cachedInputMicrosPerMillionTokens: cachedInput,
2876
+ cacheWriteMicrosPerMillionTokens: cacheWrite,
2877
+ outputMicrosPerMillionTokens: output,
2878
+ marginBps: 500
2879
+ }
2880
+ }
2881
+ ])
2882
+ )
2883
+ };
2884
+ var reviewedFreeOpenRouterListPricing = {
2885
+ default: {
2886
+ inputMicrosPerMillionTokens: 0,
2887
+ cachedInputMicrosPerMillionTokens: 0,
2888
+ cacheWriteMicrosPerMillionTokens: 0,
2889
+ outputMicrosPerMillionTokens: 0,
2890
+ marginBps: 500
2891
+ }
2892
+ };
2097
2893
  var SANDBOX_REQUIRED_ENV = {
2098
2894
  // docker/local/none need no credentials (local dev container / in-process / off).
2099
2895
  docker: [],
@@ -2153,6 +2949,7 @@ function optionalEnvironmentValue(name, source) {
2153
2949
  const value = source[name];
2154
2950
  return value && value.trim().length > 0 ? value : void 0;
2155
2951
  }
2952
+ var idleCommandContainmentDisabledWarned = false;
2156
2953
  function getSettings(source = process.env) {
2157
2954
  const optional = (name) => optionalEnvironmentValue(name, source);
2158
2955
  const modelCatalogSource = optional("OPENGENI_MODEL_CATALOG_SOURCE");
@@ -2163,6 +2960,7 @@ function getSettings(source = process.env) {
2163
2960
  deploymentRevision: optional("OPENGENI_DEPLOYMENT_REVISION") ?? optional("SOURCE_VERSION") ?? optional("GITHUB_SHA"),
2164
2961
  serverVersion: optional("OPENGENI_SERVER_VERSION"),
2165
2962
  databaseUrl: optional("OPENGENI_DATABASE_URL"),
2963
+ apiDatabasePoolMax: optional("OPENGENI_API_DATABASE_POOL_MAX"),
2166
2964
  dbSchema: optional("OPENGENI_DB_SCHEMA"),
2167
2965
  rlsStrategy: optional("OPENGENI_RLS_STRATEGY"),
2168
2966
  runtimeDatabaseRole: optional("OPENGENI_RUNTIME_DATABASE_ROLE"),
@@ -2194,15 +2992,22 @@ function getSettings(source = process.env) {
2194
2992
  observabilityMetricsEnabled: optional("OPENGENI_OBSERVABILITY_METRICS_ENABLED"),
2195
2993
  observabilityOtlpEndpoint: optional("OPENGENI_OTEL_EXPORTER_OTLP_ENDPOINT") ?? optional("OTEL_EXPORTER_OTLP_ENDPOINT"),
2196
2994
  observabilityOtlpHeaders: optional("OPENGENI_OTEL_EXPORTER_OTLP_HEADERS") ?? optional("OTEL_EXPORTER_OTLP_HEADERS"),
2995
+ observabilityDiagnosticsEndpoint: optional("OPENGENI_OBSERVABILITY_DIAGNOSTICS_ENDPOINT"),
2996
+ observabilityDiagnosticsHeaders: optional("OPENGENI_OBSERVABILITY_DIAGNOSTICS_HEADERS"),
2197
2997
  analyticsEnabled: optional("OPENGENI_ANALYTICS_ENABLED"),
2198
2998
  analyticsConsentRequired: optional("OPENGENI_ANALYTICS_CONSENT_REQUIRED"),
2199
2999
  analyticsReoClientId: optional("OPENGENI_ANALYTICS_REO_CLIENT_ID"),
2200
3000
  analyticsPosthogProjectKey: optional("OPENGENI_ANALYTICS_POSTHOG_PROJECT_KEY"),
2201
3001
  analyticsPosthogHost: optional("OPENGENI_ANALYTICS_POSTHOG_HOST"),
2202
3002
  analyticsGa4MeasurementId: optional("OPENGENI_ANALYTICS_GA4_MEASUREMENT_ID"),
3003
+ legalPrivacyPolicyUrl: optional("OPENGENI_LEGAL_PRIVACY_POLICY_URL"),
3004
+ legalTermsOfServiceUrl: optional("OPENGENI_LEGAL_TERMS_OF_SERVICE_URL"),
3005
+ supportEmail: optional("OPENGENI_SUPPORT_EMAIL"),
2203
3006
  publicBaseUrl: optional("OPENGENI_PUBLIC_BASE_URL"),
3007
+ documentationUrl: optional("OPENGENI_DOCUMENTATION_URL"),
2204
3008
  mcpOauthEnabled: optional("OPENGENI_MCP_OAUTH_ENABLED"),
2205
- mcpOauthTrustedProxyHops: optional("OPENGENI_MCP_OAUTH_TRUSTED_PROXY_HOPS"),
3009
+ apiTrustedProxyHops: optional("OPENGENI_API_TRUSTED_PROXY_HOPS"),
3010
+ apiTrustedProxyCidrs: optional("OPENGENI_API_TRUSTED_PROXY_CIDRS"),
2206
3011
  webBaseUrl: optional("OPENGENI_WEB_BASE_URL"),
2207
3012
  agentReleasesBaseUrl: optional("OPENGENI_AGENT_RELEASES_BASE_URL"),
2208
3013
  agentStableVersion: optional("OPENGENI_AGENT_STABLE_VERSION"),
@@ -2212,8 +3017,10 @@ function getSettings(source = process.env) {
2212
3017
  "OPENGENI_ORGANIZATION_TENANCY_CANONICAL_ACTIVATION_ENABLED"
2213
3018
  ),
2214
3019
  billingMode: optional("OPENGENI_BILLING_MODE"),
3020
+ verifiedSignupTrialCreditsEnabled: optional("OPENGENI_VERIFIED_SIGNUP_TRIAL_CREDITS_ENABLED"),
2215
3021
  entitlementsMode: optional("OPENGENI_ENTITLEMENTS_MODE"),
2216
3022
  usageLimitsMode: optional("OPENGENI_USAGE_LIMITS_MODE"),
3023
+ usageAllowancesEnabled: optional("OPENGENI_USAGE_ALLOWANCES_ENABLED"),
2217
3024
  staticEntitlementsJson: optional("OPENGENI_STATIC_ENTITLEMENTS_JSON"),
2218
3025
  staticUsageLimitsJson: optional("OPENGENI_STATIC_USAGE_LIMITS_JSON"),
2219
3026
  delegationSecret: optional("OPENGENI_DELEGATION_SECRET"),
@@ -2233,13 +3040,16 @@ function getSettings(source = process.env) {
2233
3040
  environmentsEncryptionKey: optional("OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY"),
2234
3041
  integrationsEnabled: optional("OPENGENI_INTEGRATIONS_ENABLED"),
2235
3042
  integrationsStateSecret: optional("OPENGENI_INTEGRATIONS_STATE_SECRET"),
3043
+ integrationsOauthShortStateEnabled: optional("OPENGENI_INTEGRATIONS_OAUTH_SHORT_STATE_ENABLED"),
2236
3044
  integrationsAllowPrivateNetworkTargets: optional(
2237
3045
  "OPENGENI_INTEGRATIONS_ALLOW_PRIVATE_NETWORK_TARGETS"
2238
3046
  ),
2239
3047
  integrationsOauthClientsJson: optional("OPENGENI_INTEGRATIONS_OAUTH_CLIENTS_JSON"),
3048
+ gmailWatchTopicName: optional("OPENGENI_GMAIL_WATCH_TOPIC_NAME"),
2240
3049
  slackClientId: optional("OPENGENI_SLACK_CLIENT_ID"),
2241
3050
  slackClientSecret: optional("OPENGENI_SLACK_CLIENT_SECRET"),
2242
3051
  slackSigningSecret: optional("OPENGENI_SLACK_SIGNING_SECRET"),
3052
+ slackAccessMode: optional("OPENGENI_SLACK_ACCESS_MODE"),
2243
3053
  slackBotDisplayName: optional("OPENGENI_SLACK_BOT_DISPLAY_NAME"),
2244
3054
  slackCommand: optional("OPENGENI_SLACK_COMMAND"),
2245
3055
  googleDriveClientId: optional("OPENGENI_GOOGLE_DRIVE_CLIENT_ID"),
@@ -2274,9 +3084,6 @@ function getSettings(source = process.env) {
2274
3084
  goalIdleBackoffMs: optional("OPENGENI_GOAL_IDLE_BACKOFF_MS"),
2275
3085
  goalIdleBackoffMaxMs: optional("OPENGENI_GOAL_IDLE_BACKOFF_MAX_MS"),
2276
3086
  childLifecycleNoticesEnabled: optional("OPENGENI_CHILD_LIFECYCLE_NOTICES_ENABLED"),
2277
- hostMcpAuthoritySourceAdmissionEnabled: optional(
2278
- "OPENGENI_HOST_MCP_AUTHORITY_SOURCE_ADMISSION_ENABLED"
2279
- ),
2280
3087
  slackWorkspaceRoutingEnabled: optional("OPENGENI_SLACK_WORKSPACE_ROUTING_ENABLED"),
2281
3088
  agentMaxModelCallsPerTurn: optional("OPENGENI_AGENT_MAX_MODEL_CALLS_PER_TURN"),
2282
3089
  contextWindowTokens: optional("OPENGENI_CONTEXT_WINDOW_TOKENS"),
@@ -2291,10 +3098,12 @@ function getSettings(source = process.env) {
2291
3098
  authAllowMetrics: optional("OPENGENI_AUTH_ALLOW_METRICS"),
2292
3099
  apiHost: optional("OPENGENI_API_HOST"),
2293
3100
  apiPort: optional("OPENGENI_API_PORT"),
3101
+ apiMetricsPort: optional("OPENGENI_API_METRICS_PORT"),
2294
3102
  workerHttpPort: optional("OPENGENI_WORKER_HTTP_PORT"),
2295
3103
  opengeniMcpInternalUrl: optional("OPENGENI_MCP_INTERNAL_URL"),
2296
3104
  opengeniMcpUrl: optional("OPENGENI_MCP_URL"),
2297
3105
  corsAllowOriginRegex: optional("OPENGENI_CORS_ALLOW_ORIGIN_REGEX"),
3106
+ localAllowedOrigins: optional("OPENGENI_LOCAL_ALLOWED_ORIGINS"),
2298
3107
  openaiProvider: optional("OPENGENI_OPENAI_PROVIDER"),
2299
3108
  openaiApiKey: optional("OPENGENI_OPENAI_API_KEY") ?? optional("OPENAI_API_KEY"),
2300
3109
  openaiBaseUrl: optional("OPENGENI_OPENAI_BASE_URL") ?? optional("OPENAI_BASE_URL"),
@@ -2353,6 +3162,7 @@ function getSettings(source = process.env) {
2353
3162
  modelProvidersJson: optional("OPENGENI_MODEL_PROVIDERS_JSON"),
2354
3163
  codexSubscriptionEnabled: optional("OPENGENI_CODEX_SUBSCRIPTION_ENABLED"),
2355
3164
  supergrokSubscriptionEnabled: optional("OPENGENI_SUPERGROK_SUBSCRIPTION_ENABLED"),
3165
+ claudeSubscriptionEnabled: optional("OPENGENI_CLAUDE_SUBSCRIPTION_ENABLED"),
2356
3166
  supergrokResponseStreamIdleTimeoutMs: optional(
2357
3167
  "OPENGENI_SUPERGROK_RESPONSE_STREAM_IDLE_TIMEOUT_MS"
2358
3168
  ),
@@ -2361,13 +3171,23 @@ function getSettings(source = process.env) {
2361
3171
  lazyToolSearchEnabled: optional("OPENGENI_LAZY_TOOL_SEARCH_ENABLED"),
2362
3172
  codexFleetPolicyShadowEnabled: optional("OPENGENI_CODEX_FLEET_POLICY_SHADOW_ENABLED"),
2363
3173
  codexProductSku: optional("OPENGENI_CODEX_PRODUCT_SKU"),
3174
+ reasoningConfigurationUpdatesEnabled: optional(
3175
+ "OPENGENI_REASONING_CONFIGURATION_UPDATES_ENABLED"
3176
+ ),
2364
3177
  openaiReasoningEffort: optional("OPENGENI_OPENAI_REASONING_EFFORT"),
2365
3178
  openaiAllowedReasoningEfforts: optional("OPENGENI_OPENAI_ALLOWED_REASONING_EFFORTS"),
3179
+ creditsDefaultModel: optional("OPENGENI_CREDITS_DEFAULT_MODEL"),
3180
+ creditsDefaultReasoningEffort: optional("OPENGENI_CREDITS_DEFAULT_REASONING_EFFORT"),
2366
3181
  openaiResponsesTransport: optional("OPENGENI_OPENAI_RESPONSES_TRANSPORT"),
2367
3182
  openaiProviderItemIds: optional("OPENGENI_OPENAI_PROVIDER_ITEM_IDS"),
2368
3183
  openaiReasoningEncryptedContent: optional("OPENGENI_OPENAI_REASONING_ENCRYPTED_CONTENT"),
2369
3184
  openaiMaxRetries: optional("OPENGENI_OPENAI_MAX_RETRIES"),
2370
3185
  webSearchEnabled: optional("OPENGENI_WEB_SEARCH_ENABLED"),
3186
+ jevApiKey: optional("OPENGENI_JEV_API_KEY"),
3187
+ jevBaseUrl: optional("OPENGENI_JEV_BASE_URL"),
3188
+ jevModel: optional("OPENGENI_JEV_MODEL"),
3189
+ jevRequestTimeoutMs: optional("OPENGENI_JEV_REQUEST_TIMEOUT_MS"),
3190
+ codeSearchMode: optional("OPENGENI_CODE_SEARCH_MODE"),
2371
3191
  agentInstructionsTemplate: optional("OPENGENI_AGENT_INSTRUCTIONS_TEMPLATE"),
2372
3192
  azureOpenaiBaseUrl: optional("OPENGENI_AZURE_OPENAI_BASE_URL"),
2373
3193
  azureOpenaiEndpoint: optional("OPENGENI_AZURE_OPENAI_ENDPOINT"),
@@ -2384,6 +3204,7 @@ function getSettings(source = process.env) {
2384
3204
  dockerWorkspaceBaseDir: optional("OPENGENI_DOCKER_WORKSPACE_BASE_DIR"),
2385
3205
  modalAppName: optional("OPENGENI_MODAL_APP_NAME"),
2386
3206
  modalImageRef: optional("OPENGENI_MODAL_IMAGE_REF") ?? DEFAULT_MODAL_IMAGE_REF,
3207
+ modalCommandSupervisionEnabled: optional("OPENGENI_MODAL_COMMAND_SUPERVISION_ENABLED"),
2387
3208
  modalImageId: optional("OPENGENI_MODAL_IMAGE_ID"),
2388
3209
  modalImageRegistrySecret: optional("OPENGENI_MODAL_IMAGE_REGISTRY_SECRET"),
2389
3210
  modalTimeoutSeconds: optional("OPENGENI_MODAL_TIMEOUT_SECONDS"),
@@ -2435,6 +3256,9 @@ function getSettings(source = process.env) {
2435
3256
  blaxelTtl: optional("OPENGENI_BLAXEL_TTL"),
2436
3257
  cloudflareWorkerUrl: optional("OPENGENI_CLOUDFLARE_WORKER_URL"),
2437
3258
  cloudflareApiKey: optional("OPENGENI_CLOUDFLARE_API_KEY"),
3259
+ experimentalBrowserContextPoolEnabled: optional(
3260
+ "OPENGENI_EXPERIMENTAL_BROWSER_CONTEXT_POOL_ENABLED"
3261
+ ),
2438
3262
  browserbaseApiKey: optional("OPENGENI_BROWSERBASE_API_KEY"),
2439
3263
  kernelApiKey: optional("OPENGENI_KERNEL_API_KEY"),
2440
3264
  kernelEndpoint: optional("OPENGENI_KERNEL_ENDPOINT"),
@@ -2483,6 +3307,7 @@ function getSettings(source = process.env) {
2483
3307
  sandboxViewerHolderTtlMs: optional("OPENGENI_SANDBOX_VIEWER_HOLDER_TTL_MS"),
2484
3308
  sandboxInteractionHolderTtlMs: optional("OPENGENI_SANDBOX_INTERACTION_HOLDER_TTL_MS"),
2485
3309
  sandboxIdleGraceMs: optional("OPENGENI_SANDBOX_IDLE_GRACE_MS"),
3310
+ sandboxIdleCommandContainmentMs: optional("OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS"),
2486
3311
  sandboxSnapshotIntervalMs: optional("OPENGENI_SANDBOX_SNAPSHOT_INTERVAL_MS"),
2487
3312
  sandboxSnapshotTimeoutMs: optional("OPENGENI_SANDBOX_SNAPSHOT_TIMEOUT_MS"),
2488
3313
  sandboxDrainSnapshotTimeoutMs: optional("OPENGENI_SANDBOX_DRAIN_SNAPSHOT_TIMEOUT_MS"),
@@ -2496,9 +3321,11 @@ function getSettings(source = process.env) {
2496
3321
  sandboxWarmRateMicrosPerSecondJson: optional(
2497
3322
  "OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON"
2498
3323
  ),
3324
+ sandboxWarmBillingMode: optional("OPENGENI_SANDBOX_WARM_BILLING_MODE"),
2499
3325
  sandboxMaxWarmSecondsPerWorkspace: optional("OPENGENI_SANDBOX_MAX_WARM_SECONDS_PER_WORKSPACE"),
2500
3326
  sandboxPreparationProfiles: optional("OPENGENI_SANDBOX_PREPARATION_PROFILES"),
2501
3327
  sandboxEnvAllowlist: optional("OPENGENI_SANDBOX_ENV_ALLOWLIST"),
3328
+ sandboxImageAllowlist: optional("OPENGENI_SANDBOX_IMAGE_ALLOWLIST"),
2502
3329
  objectStorageEndpoint: optional("OPENGENI_OBJECT_STORAGE_ENDPOINT"),
2503
3330
  objectStorageInternalEndpoint: optional("OPENGENI_OBJECT_STORAGE_INTERNAL_ENDPOINT"),
2504
3331
  objectStorageSandboxEndpoint: optional("OPENGENI_OBJECT_STORAGE_SANDBOX_ENDPOINT"),
@@ -2525,6 +3352,13 @@ function getSettings(source = process.env) {
2525
3352
  documentEmbeddingDimensions: optional("OPENGENI_DOCUMENT_EMBEDDING_DIMENSIONS"),
2526
3353
  documentEmbeddingApiKey: optional("OPENGENI_DOCUMENT_EMBEDDING_API_KEY"),
2527
3354
  documentEmbeddingBaseUrl: optional("OPENGENI_DOCUMENT_EMBEDDING_BASE_URL"),
3355
+ documentEmbeddingBillingMode: optional("OPENGENI_DOCUMENT_EMBEDDING_BILLING_MODE"),
3356
+ documentEmbeddingCreditsActivatedAt: optional(
3357
+ "OPENGENI_DOCUMENT_EMBEDDING_CREDITS_ACTIVATED_AT"
3358
+ ),
3359
+ documentEmbeddingRateMicrosPerMillionBytes: optional(
3360
+ "OPENGENI_DOCUMENT_EMBEDDING_RATE_MICROS_PER_MILLION_BYTES"
3361
+ ),
2528
3362
  documentCurationProvider: optional("OPENGENI_DOCUMENT_CURATION_PROVIDER"),
2529
3363
  documentCurationModel: optional("OPENGENI_DOCUMENT_CURATION_MODEL"),
2530
3364
  documentCurationApiKey: optional("OPENGENI_DOCUMENT_CURATION_API_KEY"),
@@ -2559,7 +3393,9 @@ function getSettings(source = process.env) {
2559
3393
  managedAuthGoogleClientSecret: optional("OPENGENI_MANAGED_AUTH_GOOGLE_CLIENT_SECRET"),
2560
3394
  managedAuthGithubClientId: optional("OPENGENI_MANAGED_AUTH_GITHUB_CLIENT_ID"),
2561
3395
  managedAuthGithubClientSecret: optional("OPENGENI_MANAGED_AUTH_GITHUB_CLIENT_SECRET"),
3396
+ allowedUserEmails: source.OPENGENI_ALLOWED_USER_EMAILS === void 0 ? void 0 : source.OPENGENI_ALLOWED_USER_EMAILS.split(",").map((email) => email.trim()),
2562
3397
  managedAuthSessionSetMode: optional("OPENGENI_MANAGED_AUTH_SESSION_SET_MODE"),
3398
+ managedAuthNewSignupsEnabled: optional("OPENGENI_MANAGED_AUTH_NEW_SIGNUPS_ENABLED"),
2563
3399
  organizationUserSetupEmailTokenTransport: optional(
2564
3400
  "OPENGENI_ORGANIZATION_USER_SETUP_EMAIL_TOKEN_TRANSPORT"
2565
3401
  ),
@@ -2578,9 +3414,41 @@ function getSettings(source = process.env) {
2578
3414
  const settings = {
2579
3415
  ...parsed,
2580
3416
  sandboxIdleGraceMs: raw.sandboxIdleGraceMs === void 0 && parsed.sandboxBackend === "modal" ? Math.min(9e5, Math.floor(parsed.modalTimeoutSeconds * 1e3 / 2)) : parsed.sandboxIdleGraceMs,
2581
- sandboxRotationLeadMs: raw.sandboxRotationLeadMs === void 0 && parsed.sandboxBackend === "modal" ? Math.min(36e5, Math.floor(parsed.modalTimeoutSeconds * 1e3 / 2)) : parsed.sandboxRotationLeadMs,
3417
+ sandboxRotationLeadMs: raw.sandboxRotationLeadMs === void 0 && parsed.sandboxBackend === "modal" ? Math.min(
3418
+ 36e5,
3419
+ Math.max(
3420
+ Math.floor(parsed.modalTimeoutSeconds * 1e3 / 2),
3421
+ SANDBOX_DEADLINE_COMMAND_STOP_GRACE_MS + sandboxArchiveCaptureTimeoutMs({
3422
+ sandboxSnapshotTimeoutMs: Math.max(
3423
+ parsed.sandboxSnapshotTimeoutMs,
3424
+ parsed.sandboxDrainSnapshotTimeoutMs ?? parsed.sandboxSnapshotTimeoutMs
3425
+ )
3426
+ }) + 2 * parsed.sandboxLeaseReaperPeriodMs + 1
3427
+ )
3428
+ ) : parsed.sandboxRotationLeadMs,
2582
3429
  mcpServers: ensureBuiltInMcpServers(parsed)
2583
3430
  };
3431
+ if (raw.sandboxIdleCommandContainmentMs === void 0) {
3432
+ const modalIdleCeilingMs = settings.sandboxBackend === "modal" && settings.modalIdleTimeoutSeconds !== void 0 ? settings.modalIdleTimeoutSeconds * 1e3 - settings.sandboxLeaseReaperPeriodMs - sandboxArchiveCaptureTimeoutMs({
3433
+ sandboxSnapshotTimeoutMs: effectiveSandboxDrainSnapshotTimeoutMs(settings)
3434
+ }) - 1 : Number.POSITIVE_INFINITY;
3435
+ const derived = Math.min(
3436
+ 18e5,
3437
+ Math.floor((settings.sandboxIdleGraceMs + settings.sandboxRotationLeadMs) / 2),
3438
+ modalIdleCeilingMs
3439
+ );
3440
+ if (derived > settings.sandboxIdleGraceMs) {
3441
+ settings.sandboxIdleCommandContainmentMs = derived;
3442
+ } else {
3443
+ settings.sandboxIdleCommandContainmentMs = void 0;
3444
+ if (!idleCommandContainmentDisabledWarned) {
3445
+ idleCommandContainmentDisabledWarned = true;
3446
+ console.warn(
3447
+ `[config] idle command containment disabled: no window fits between OPENGENI_SANDBOX_IDLE_GRACE_MS (${settings.sandboxIdleGraceMs}) and the Modal idle timeout / rotation lead ceiling; set OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS to override.`
3448
+ );
3449
+ }
3450
+ }
3451
+ }
2584
3452
  validateSettings(settings, source);
2585
3453
  return settings;
2586
3454
  }
@@ -2595,20 +3463,24 @@ function resolveFirstPartyDelegationSecret(settings) {
2595
3463
  return settings.productAccessMode === "local" && (settings.environment === "local" || settings.environment === "test") ? LOCAL_FIRST_PARTY_DELEGATION_SECRET : void 0;
2596
3464
  }
2597
3465
  function resolveFirstPartyMcpToolPolicy(settings) {
2598
- const allowed = settings.allowedFirstPartyMcpTools ?? [...FIRST_PARTY_MCP_TOOL_NAMES];
2599
- const allowedSet = new Set(allowed);
2600
- const defaults = settings.defaultFirstPartyMcpTools ?? [...DEFAULT_FIRST_PARTY_MCP_TOOLS];
3466
+ const allowed2 = currentAgentLearningToolSelection(
3467
+ settings.allowedFirstPartyMcpTools ?? [...FIRST_PARTY_MCP_TOOL_NAMES]
3468
+ ).filter((tool) => !isRetiredNativeAtlassianTool(tool));
3469
+ const allowedSet = new Set(allowed2);
3470
+ const defaults = currentAgentLearningToolSelection(
3471
+ settings.defaultFirstPartyMcpTools ?? [...DEFAULT_FIRST_PARTY_MCP_TOOLS]
3472
+ );
2601
3473
  return {
2602
3474
  default: defaults.filter((tool) => allowedSet.has(tool)),
2603
- allowed: [...allowed]
3475
+ allowed: [...allowed2]
2604
3476
  };
2605
3477
  }
2606
3478
  function allowedFirstPartyMcpToolsForSession(settings, selected) {
2607
3479
  const policy = resolveFirstPartyMcpToolPolicy(settings);
2608
- const allowed = new Set(policy.allowed);
2609
- const tools = new Set(selected ?? policy.default);
3480
+ const allowed2 = new Set(policy.allowed);
3481
+ const tools = new Set(currentAgentLearningToolSelection(selected ?? policy.default));
2610
3482
  if (tools.has("goal_pause")) tools.add("goal_resume");
2611
- return [...tools].filter((tool) => allowed.has(tool));
3483
+ return [...tools].filter((tool) => allowed2.has(tool));
2612
3484
  }
2613
3485
  function effectiveModalIdleTimeoutSeconds(settings) {
2614
3486
  return settings.modalIdleTimeoutSeconds ?? settings.modalTimeoutSeconds;
@@ -3089,7 +3961,9 @@ function openRouterRegistryProvider(settings, input) {
3089
3961
  }
3090
3962
  function configuredRegistryProviders(settings) {
3091
3963
  const providers = parseModelProvidersJson(settings.modelProvidersJson);
3092
- const injected = [...providers];
3964
+ const injected = providers.filter(
3965
+ (provider) => settings.claudeSubscriptionEnabled || !(provider.api === "anthropic-messages" && provider.anthropic?.auth === "oauth")
3966
+ );
3093
3967
  if (settings.vercelAiGatewayApiKey && configuredGatewayCatalogModels(settings).length > 0) {
3094
3968
  injected.push(
3095
3969
  gatewayRegistryProvider(settings, {
@@ -3105,6 +3979,37 @@ function configuredRegistryProviders(settings) {
3105
3979
  if (openrouter) injected.push(openrouter);
3106
3980
  return injected;
3107
3981
  }
3982
+ function withDirectModelProviders(settings, connections) {
3983
+ const providers = parseModelProvidersJson(settings.modelProvidersJson).filter(
3984
+ (provider) => !provider.id.startsWith("workspace-openai-") && !provider.id.startsWith("workspace-azure-openai-")
3985
+ );
3986
+ for (const connection of connections) {
3987
+ const spec = directModelConnectionSpec(connection);
3988
+ if (!spec) continue;
3989
+ providers.push({
3990
+ kind: spec.provider === "openai" ? "direct-openai-workspace" : "direct-azure-workspace",
3991
+ id: spec.providerId,
3992
+ label: spec.provider === "openai" ? "Your OpenAI" : "Your Azure OpenAI",
3993
+ api: "responses",
3994
+ wireProfile: spec.provider === "openai" ? "openai" : "azure-openai",
3995
+ baseUrl: spec.baseUrl,
3996
+ ...connection.apiKey ? { apiKey: connection.apiKey } : {},
3997
+ models: [
3998
+ {
3999
+ id: spec.modelId,
4000
+ upstreamModelId: spec.model,
4001
+ label: spec.model,
4002
+ capabilities: legacyModelCapabilities(settings, {
4003
+ reasoningEffort: false,
4004
+ hostedWebSearch: false
4005
+ }),
4006
+ toolOutputTruncationTokens: settings.modelToolOutputTruncationTokens
4007
+ }
4008
+ ]
4009
+ });
4010
+ }
4011
+ return { ...settings, modelProvidersJson: JSON.stringify(providers) };
4012
+ }
3108
4013
  function withWorkspaceGatewayCatalogProvider(settings, customModels = []) {
3109
4014
  const providers = parseModelProvidersJson(settings.modelProvidersJson);
3110
4015
  const withoutWorkspace = providers.filter(
@@ -3217,8 +4122,8 @@ function productLabelForModelId(modelId) {
3217
4122
  function productShortLabelForModelId(modelId) {
3218
4123
  const slug = modelId.startsWith(CODEX_MODEL_ID_PREFIX) ? modelId.slice(CODEX_MODEL_ID_PREFIX.length) : modelId;
3219
4124
  switch (slug) {
3220
- case "grok-4.6":
3221
- return "4.6";
4125
+ case "grok-4.7":
4126
+ return "4.7";
3222
4127
  case "gpt-5.6-sol":
3223
4128
  return "5.6 Sol";
3224
4129
  case "gpt-5.6-terra":
@@ -3227,6 +4132,10 @@ function productShortLabelForModelId(modelId) {
3227
4132
  return "5.6 Luna";
3228
4133
  case "gpt-6-astra":
3229
4134
  return "6 Astra";
4135
+ case "gpt-6-sol":
4136
+ return "6 Sol";
4137
+ case "gpt-6-luna":
4138
+ return "6 Luna";
3230
4139
  default:
3231
4140
  return null;
3232
4141
  }
@@ -3246,7 +4155,7 @@ function builtinContextLimitsForModel(settings, modelId) {
3246
4155
  return { contextWindowTokens: settings.contextWindowTokens };
3247
4156
  }
3248
4157
  function builtinLatencyModesForModel(modelId) {
3249
- if (isBuiltinGpt56ModelId(modelId) || modelId.startsWith("codex/gpt-5.6-") || modelId === "codex/gpt-6-astra") {
4158
+ if (isBuiltinGpt56ModelId(modelId) || /^gpt-6(?:\.\d+)?-/u.test(modelId) || modelId.startsWith("codex/gpt-5.6-") || /^codex\/gpt-6(?:\.\d+)?-/u.test(modelId)) {
3250
4159
  return [
3251
4160
  { id: "standard", upstream: "supported", runnable: true },
3252
4161
  {
@@ -3259,12 +4168,26 @@ function builtinLatencyModesForModel(modelId) {
3259
4168
  }
3260
4169
  return [{ id: "standard", upstream: "unknown", runnable: true }];
3261
4170
  }
4171
+ function isReviewedGptVisionModel(slug) {
4172
+ return slug.startsWith("gpt-5.6-") || /^gpt-6(?:\.\d+)?-/u.test(slug);
4173
+ }
4174
+ function reviewedCodexCatalogCapabilities(slug, capabilities) {
4175
+ if (!/^gpt-6(?:\.\d+)?-/u.test(slug)) return capabilities;
4176
+ const fast = builtinLatencyModesForModel(`${CODEX_MODEL_ID_PREFIX}${slug}`).find(
4177
+ (mode) => mode.id === "fast"
4178
+ );
4179
+ return normalizeCapabilities({
4180
+ ...capabilities,
4181
+ inputModalities: [.../* @__PURE__ */ new Set([...capabilities.inputModalities, "image"])],
4182
+ latencyModes: fast && !capabilities.latencyModes.some((mode) => mode.id === "fast") ? [...capabilities.latencyModes, fast] : capabilities.latencyModes
4183
+ });
4184
+ }
3262
4185
  function builtinPromptCachingForModel(modelId) {
3263
4186
  const slug = modelId.startsWith(CODEX_MODEL_ID_PREFIX) ? modelId.slice(CODEX_MODEL_ID_PREFIX.length) : modelId;
3264
- return slug.startsWith("gpt-5.6-") ? { upstream: "supported", runnable: true, mode: "implicit" } : void 0;
4187
+ return slug.startsWith("gpt-5.6-") || slug.startsWith("gpt-6-") ? { upstream: "supported", runnable: true, mode: "implicit" } : void 0;
3265
4188
  }
3266
4189
  function builtinHostedImageGenerationForModel(settings, modelId) {
3267
- return settings.openaiProvider === "openai" && isDirectOpenAiApiBaseUrl(settings.openaiBaseUrl) && isBuiltinGpt56ModelId(modelId);
4190
+ return settings.openaiProvider === "openai" && isDirectOpenAiApiBaseUrl(settings.openaiBaseUrl) && (isBuiltinGpt56ModelId(modelId) || modelId.startsWith("gpt-6-"));
3268
4191
  }
3269
4192
  function isDirectOpenAiApiBaseUrl(baseUrl) {
3270
4193
  if (baseUrl === void 0) return true;
@@ -3303,11 +4226,21 @@ function runnableLatencyModesForModel(settings, modelId) {
3303
4226
  function assertLatencyModeRunnable(settings, modelId, latencyMode) {
3304
4227
  const runnable = runnableLatencyModesForModel(settings, modelId);
3305
4228
  if (!runnable.includes(latencyMode)) {
3306
- throw new Error(
3307
- `latency mode ${latencyMode} is not runnable for model ${modelId} (allowed: ${runnable.join(", ")})`
3308
- );
4229
+ throw new UnsupportedLatencyModeError(modelId, latencyMode, runnable);
3309
4230
  }
3310
4231
  }
4232
+ var UnsupportedLatencyModeError = class extends Error {
4233
+ constructor(modelId, latencyMode, allowedLatencyModes) {
4234
+ super(
4235
+ `latency mode ${latencyMode} is not runnable for model ${modelId} (allowed: ${allowedLatencyModes.join(", ")})`
4236
+ );
4237
+ this.modelId = modelId;
4238
+ this.latencyMode = latencyMode;
4239
+ this.allowedLatencyModes = allowedLatencyModes;
4240
+ this.name = "UnsupportedLatencyModeError";
4241
+ }
4242
+ code = "UNSUPPORTED_LATENCY_MODE";
4243
+ };
3311
4244
  function registryCredentialSource(provider) {
3312
4245
  switch (provider.kind) {
3313
4246
  case "anonymous":
@@ -3316,10 +4249,17 @@ function registryCredentialSource(provider) {
3316
4249
  return { kind: "connected_subscription", provider: "codex" };
3317
4250
  case "xai-subscription":
3318
4251
  return { kind: "connected_subscription", provider: "xai" };
4252
+ case "claude-subscription-workspace":
4253
+ case "claude-subscription-organization":
4254
+ return { kind: "connected_subscription", provider: "claude" };
3319
4255
  case "vercel-gateway-workspace":
4256
+ case "direct-openai-workspace":
4257
+ case "direct-azure-workspace":
3320
4258
  case "openrouter-workspace":
4259
+ case "anthropic-workspace":
3321
4260
  return { kind: "workspace_connection", mechanism: "api_key" };
3322
4261
  case "vercel-gateway-organization":
4262
+ case "anthropic-organization":
3323
4263
  case "openrouter-organization":
3324
4264
  return { kind: "organization_connection", mechanism: "api_key" };
3325
4265
  case "api-key":
@@ -3339,11 +4279,17 @@ function registryBilling(provider) {
3339
4279
  return { upstreamPayer: "deployment", metering: "external" };
3340
4280
  case "codex-subscription":
3341
4281
  case "xai-subscription":
4282
+ case "claude-subscription-workspace":
4283
+ case "claude-subscription-organization":
3342
4284
  return { upstreamPayer: "connected_subscription", metering: "external" };
3343
4285
  case "vercel-gateway-workspace":
4286
+ case "direct-openai-workspace":
4287
+ case "direct-azure-workspace":
3344
4288
  case "openrouter-workspace":
4289
+ case "anthropic-workspace":
3345
4290
  return { upstreamPayer: "workspace", metering: "external" };
3346
4291
  case "vercel-gateway-organization":
4292
+ case "anthropic-organization":
3347
4293
  case "openrouter-organization":
3348
4294
  return { upstreamPayer: "organization", metering: "external" };
3349
4295
  case "api-key":
@@ -3374,6 +4320,9 @@ function staticRequestMetadataForDigest(provider) {
3374
4320
  const publicHeaders = new Set(provider.publicDefaultHeaderNames ?? []);
3375
4321
  const publicQuery = new Set(provider.publicDefaultQueryNames ?? []);
3376
4322
  return {
4323
+ ...provider.anthropic ? {
4324
+ anthropic: (({ identity: _identity, credentialBinding: _binding, ...options }) => options)(provider.anthropic)
4325
+ } : {},
3377
4326
  headers: Object.entries(provider.defaultHeaders ?? {}).sort(([left], [right]) => left.localeCompare(right)).map(
3378
4327
  ([name, value]) => publicHeaders.has(name) ? { name, classification: "public", value } : { name, classification: "secret" }
3379
4328
  ),
@@ -3415,7 +4364,8 @@ function definitionVersionFor(model, provider, options = {}) {
3415
4364
  ...includeWireProfile ? { wireProfile: provider.wireProfile } : {},
3416
4365
  baseUrl: provider.baseUrl ?? null,
3417
4366
  defaultHeaders: requestMetadata.headers,
3418
- defaultQuery: requestMetadata.query
4367
+ defaultQuery: requestMetadata.query,
4368
+ ...requestMetadata.anthropic ? { anthropic: requestMetadata.anthropic } : {}
3419
4369
  },
3420
4370
  credentialSource: model.credentialSource,
3421
4371
  billing: model.billing,
@@ -3437,11 +4387,44 @@ function legacyImplicitOpenAiDefinitionVersionFor(model, provider) {
3437
4387
  includeWireProfile: false
3438
4388
  });
3439
4389
  }
3440
- function builtinProviderId(settings) {
3441
- return settings.openaiProvider === "azure" ? "azure" : "openai";
4390
+ function legacyCodexAstraImplicitCachingDefinitionVersionFor(model, provider) {
4391
+ if (model.id !== "codex/gpt-6-astra" || model.upstreamModelId !== "gpt-6-astra" || provider.id !== CODEX_PROVIDER_ID || provider.kind !== "codex-subscription" || provider.api !== "responses" || provider.wireProfile !== "openai" || canonicalJson(model.capabilities.promptCaching) !== canonicalJson({ upstream: "supported", runnable: true, mode: "implicit" })) {
4392
+ return null;
4393
+ }
4394
+ const { definitionVersion: _definitionVersion, ...modelWithoutVersion } = model;
4395
+ const { promptCaching: _promptCaching, ...capabilities } = model.capabilities;
4396
+ return definitionVersionFor({ ...modelWithoutVersion, capabilities }, provider);
3442
4397
  }
3443
- function builtinProviderLabel(settings) {
3444
- return settings.openaiProvider === "azure" ? "Azure OpenAI" : "OpenAI";
4398
+ function matchesAdditiveCapabilityDefinitionVersion(model, provider, policy) {
4399
+ const { definitionVersion: _definitionVersion, ...modelWithoutVersion } = model;
4400
+ const { latencyModes, inputModalities } = model.capabilities;
4401
+ for (let latencyMask = 1; latencyMask < 1 << latencyModes.length; latencyMask += 1) {
4402
+ const retainedModes = latencyModes.filter((_mode, index) => latencyMask & 1 << index);
4403
+ if (!retainedModes.some((mode) => mode.id === policy.latencyMode && mode.runnable)) {
4404
+ continue;
4405
+ }
4406
+ for (let inputMask = 1; inputMask < 1 << inputModalities.length; inputMask += 1) {
4407
+ const retainedInputs = inputModalities.filter((_modality, index) => inputMask & 1 << index);
4408
+ if (retainedModes.length === latencyModes.length && retainedInputs.length === inputModalities.length) {
4409
+ continue;
4410
+ }
4411
+ const capabilities = {
4412
+ ...model.capabilities,
4413
+ latencyModes: retainedModes,
4414
+ inputModalities: retainedInputs
4415
+ };
4416
+ if (policy.definitionVersion === definitionVersionFor({ ...modelWithoutVersion, capabilities }, provider)) {
4417
+ return true;
4418
+ }
4419
+ }
4420
+ }
4421
+ return false;
4422
+ }
4423
+ function builtinProviderId(settings) {
4424
+ return settings.openaiProvider === "azure" ? "azure" : "openai";
4425
+ }
4426
+ function builtinProviderLabel(settings) {
4427
+ return settings.openaiProvider === "azure" ? "Azure OpenAI" : "OpenAI";
3445
4428
  }
3446
4429
  function configuredProviders(settings, source = process.env) {
3447
4430
  const credentialSource = builtinCredentialSource(settings);
@@ -3458,10 +4441,10 @@ function configuredProviders(settings, source = process.env) {
3458
4441
  if (settings.openaiProvider === "azure") {
3459
4442
  const baseUrl = settings.azureOpenaiBaseUrl ?? settings.azureOpenaiEndpoint;
3460
4443
  builtin.baseUrl = baseUrl ? normalizeRegistryBaseUrl(baseUrl, builtin.id) : void 0;
3461
- builtin.apiKey = settings.azureOpenaiApiKey ?? settings.azureOpenaiAdToken;
4444
+ builtin.apiKey = usableDeploymentSecret(settings.azureOpenaiApiKey) ?? settings.azureOpenaiAdToken;
3462
4445
  } else {
3463
4446
  builtin.baseUrl = settings.openaiBaseUrl ? normalizeRegistryBaseUrl(settings.openaiBaseUrl, builtin.id) : void 0;
3464
- builtin.apiKey = settings.openaiApiKey;
4447
+ builtin.apiKey = usableDeploymentSecret(settings.openaiApiKey);
3465
4448
  }
3466
4449
  const registry = configuredRegistryProviders(settings).map(
3467
4450
  (provider) => ({
@@ -3469,6 +4452,7 @@ function configuredProviders(settings, source = process.env) {
3469
4452
  label: provider.label ?? provider.id,
3470
4453
  kind: provider.kind,
3471
4454
  api: provider.api,
4455
+ anthropic: provider.anthropic,
3472
4456
  wireProfile: provider.wireProfile,
3473
4457
  builtin: false,
3474
4458
  baseUrl: provider.baseUrl,
@@ -3483,11 +4467,17 @@ function configuredProviders(settings, source = process.env) {
3483
4467
  );
3484
4468
  return [builtin, ...registry];
3485
4469
  }
4470
+ function codexUpstreamModelSlugs(settings) {
4471
+ if (settings.resolvedCodexModelsJson === void 0) return [...CODEX_FALLBACK_MODEL_SLUGS];
4472
+ return z2.array(CodexCatalogModelSchema).parse(JSON.parse(settings.resolvedCodexModelsJson)).filter((model) => !model.retired).map((model) => model.upstreamModelId);
4473
+ }
3486
4474
  function withCodexCatalogProvider(settings) {
3487
4475
  const providers = parseModelProvidersJson(settings.modelProvidersJson);
3488
4476
  if (providers.some((provider2) => provider2.id === CODEX_PROVIDER_ID)) {
3489
4477
  return settings;
3490
4478
  }
4479
+ const catalogModels = settings.resolvedCodexModelsJson === void 0 ? void 0 : z2.array(CodexCatalogModelSchema).parse(JSON.parse(settings.resolvedCodexModelsJson)).filter((model) => !model.retired).map(({ retired: _retired, ...model }) => model);
4480
+ if (catalogModels?.length === 0) return settings;
3491
4481
  const provider = {
3492
4482
  kind: "codex-subscription",
3493
4483
  id: CODEX_PROVIDER_ID,
@@ -3495,12 +4485,12 @@ function withCodexCatalogProvider(settings) {
3495
4485
  api: "responses",
3496
4486
  wireProfile: "openai",
3497
4487
  baseUrl: CODEX_PROVIDER_BASE_URL,
3498
- models: CODEX_FALLBACK_MODEL_SLUGS.map((slug) => {
4488
+ models: catalogModels ?? CODEX_FALLBACK_MODEL_SLUGS.map((slug) => {
3499
4489
  const capabilities = {
3500
4490
  ...legacyModelCapabilities(settings, {
3501
4491
  reasoningEffort: true,
3502
4492
  hostedWebSearch: true,
3503
- vision: slug.startsWith("gpt-5.6-") || slug === "gpt-6-astra"
4493
+ vision: isReviewedGptVisionModel(slug)
3504
4494
  }),
3505
4495
  ...builtinPromptCachingForModel(`${CODEX_MODEL_ID_PREFIX}${slug}`) ? {
3506
4496
  promptCaching: builtinPromptCachingForModel(`${CODEX_MODEL_ID_PREFIX}${slug}`)
@@ -3683,7 +4673,7 @@ function configuredModels(settings, source = process.env) {
3683
4673
  reasoningEffort: true,
3684
4674
  hostedWebSearch: settings.webSearchEnabled,
3685
4675
  hostedImageGeneration: builtinHostedImageGenerationForModel(settings, id),
3686
- vision: id.startsWith("gpt-5.6-")
4676
+ vision: isReviewedGptVisionModel(id)
3687
4677
  }),
3688
4678
  ...builtinPromptCachingForModel(id) ? { promptCaching: builtinPromptCachingForModel(id) } : {},
3689
4679
  latencyModes: builtinLatencyModesForModel(id)
@@ -3762,7 +4752,57 @@ function canonicalizeConfiguredModelId(settings, modelId) {
3762
4752
  return models.find((model) => model.aliases.includes(modelId))?.id ?? modelId;
3763
4753
  }
3764
4754
  function configuredAllowedModels(settings) {
3765
- return configuredModels(settings).map((model) => model.id);
4755
+ return configuredModels(settings).filter((model) => isModelAvailableForNewSelection(settings, model.id)).map((model) => model.id);
4756
+ }
4757
+ function isModelAvailableForNewSelection(settings, modelId) {
4758
+ if (!modelId.startsWith(CODEX_MODEL_ID_PREFIX) || settings.resolvedCodexModelsJson === void 0)
4759
+ return true;
4760
+ const models = z2.array(CodexCatalogModelSchema).parse(JSON.parse(settings.resolvedCodexModelsJson));
4761
+ return models.some((model) => model.id === modelId && !model.retired);
4762
+ }
4763
+ function settingsForAcceptedSubscriptionTurn(settings, policy, expected) {
4764
+ const parsed = TurnExecutionPolicyV1.parse(policy);
4765
+ if (!parsed.productModelId.startsWith(CODEX_MODEL_ID_PREFIX)) return settings;
4766
+ if (!settings.codexSubscriptionEnabled) throw new Error("Codex subscription is disabled");
4767
+ const models = settings.resolvedCodexModelsJson === void 0 ? [] : z2.array(CodexCatalogModelSchema).parse(JSON.parse(settings.resolvedCodexModelsJson));
4768
+ const retained = models.find((model2) => model2.id === parsed.productModelId && model2.retired);
4769
+ if (!retained) {
4770
+ assertTurnExecutionPolicyMatchesConfigV1(settings, parsed, expected);
4771
+ return settings;
4772
+ }
4773
+ const { retired: _retired, ...model } = retained;
4774
+ const withoutCodex = {
4775
+ ...settings,
4776
+ modelProvidersJson: JSON.stringify(
4777
+ parseModelProvidersJson(settings.modelProvidersJson).filter(
4778
+ (provider) => provider.id !== CODEX_PROVIDER_ID
4779
+ )
4780
+ )
4781
+ };
4782
+ const providerSettings = withCodexCatalogProvider({
4783
+ ...withoutCodex,
4784
+ resolvedCodexModelsJson: JSON.stringify([model])
4785
+ });
4786
+ const retainedProvider = parseModelProvidersJson(providerSettings.modelProvidersJson).find(
4787
+ (provider) => provider.id === CODEX_PROVIDER_ID
4788
+ );
4789
+ const providers = parseModelProvidersJson(settings.modelProvidersJson);
4790
+ const current = providers.find((provider) => provider.id === CODEX_PROVIDER_ID);
4791
+ const restored = {
4792
+ ...settings,
4793
+ modelProvidersJson: JSON.stringify([
4794
+ ...providers.filter((provider) => provider.id !== CODEX_PROVIDER_ID),
4795
+ {
4796
+ ...retainedProvider,
4797
+ models: [
4798
+ ...(current?.models ?? []).filter((candidate) => candidate.id !== model.id),
4799
+ model
4800
+ ]
4801
+ }
4802
+ ])
4803
+ };
4804
+ assertTurnExecutionPolicyMatchesConfigV1(restored, parsed, expected);
4805
+ return restored;
3766
4806
  }
3767
4807
  function resolveModelProvider(settings, modelId) {
3768
4808
  const canonicalModelId = canonicalizeConfiguredModelId(settings, modelId);
@@ -3815,6 +4855,9 @@ function resolveModelProviderForTurn(settings, modelId) {
3815
4855
  function resolveTurnExecutionPolicyV1(settings, input) {
3816
4856
  const catalogSettings = settingsForTurnExecutionPolicy(settings, input.modelId);
3817
4857
  const productModelId = canonicalizeConfiguredModelId(catalogSettings, input.modelId);
4858
+ if (!isModelAvailableForNewSelection(catalogSettings, productModelId)) {
4859
+ throw new Error("Turn execution policy model is retired from new selection");
4860
+ }
3818
4861
  const resolved = resolveModelProvider(catalogSettings, productModelId);
3819
4862
  if (!resolved) {
3820
4863
  throw new Error("Turn execution policy model is not present in the configured catalog");
@@ -3842,6 +4885,13 @@ function resolveTurnExecutionPolicyV1(settings, input) {
3842
4885
  definitionVersion: resolved.model.definitionVersion
3843
4886
  });
3844
4887
  }
4888
+ var TurnExecutionPolicyDefinitionMismatchError = class extends Error {
4889
+ code = "turn_execution_policy_definition_mismatch";
4890
+ constructor() {
4891
+ super("Turn execution policy does not match the current provider definition");
4892
+ this.name = "TurnExecutionPolicyDefinitionMismatchError";
4893
+ }
4894
+ };
3845
4895
  function assertTurnExecutionPolicyMatchesConfigV1(settings, policy, expected) {
3846
4896
  const parsed = TurnExecutionPolicyV1.parse(policy);
3847
4897
  const catalogSettings = settingsForTurnExecutionPolicy(settings, parsed.productModelId);
@@ -3860,15 +4910,33 @@ function assertTurnExecutionPolicyMatchesConfigV1(settings, policy, expected) {
3860
4910
  if (!resolved) {
3861
4911
  throw new Error("Turn execution policy model is no longer configured");
3862
4912
  }
4913
+ const legacyClaudeScope = resolved.provider.kind === "claude-subscription-workspace" ? "workspace" : resolved.provider.kind === "claude-subscription-organization" ? "organization" : null;
4914
+ const legacyClaudeAccountingMatches = legacyClaudeScope !== null && parsed.providerId === resolved.provider.id && parsed.upstreamModelId === resolved.model.upstreamModelId && parsed.wireApi === resolved.model.api && canonicalJson(parsed.credentialSource) === canonicalJson({
4915
+ kind: `${legacyClaudeScope}_connection`,
4916
+ mechanism: "api_key"
4917
+ }) && canonicalJson(parsed.billing) === canonicalJson({
4918
+ upstreamPayer: legacyClaudeScope,
4919
+ metering: "external"
4920
+ }) && parsed.definitionVersion === definitionVersionFor(
4921
+ {
4922
+ ...resolved.model,
4923
+ credentialSource: parsed.credentialSource,
4924
+ billing: parsed.billing
4925
+ },
4926
+ resolved.provider
4927
+ );
3863
4928
  const legacyImplicitOpenAiDefinitionVersion = legacyImplicitOpenAiDefinitionVersionFor(
3864
4929
  resolved.model,
3865
4930
  resolved.provider
3866
4931
  );
3867
- const definitionVersionMatches = parsed.definitionVersion === resolved.model.definitionVersion || parsed.definitionVersion === legacyImplicitOpenAiDefinitionVersion;
3868
- const mismatched = parsed.providerId !== resolved.provider.id || parsed.upstreamModelId !== resolved.model.upstreamModelId || parsed.wireApi !== resolved.model.api || !definitionVersionMatches || canonicalJson(parsed.credentialSource) !== canonicalJson(resolved.model.credentialSource) || canonicalJson(parsed.billing) !== canonicalJson(resolved.model.billing);
3869
- if (mismatched) {
4932
+ const definitionVersionMatches = parsed.definitionVersion === resolved.model.definitionVersion || parsed.definitionVersion === legacyImplicitOpenAiDefinitionVersion || parsed.definitionVersion === legacyCodexAstraImplicitCachingDefinitionVersionFor(resolved.model, resolved.provider) || matchesAdditiveCapabilityDefinitionVersion(resolved.model, resolved.provider, parsed);
4933
+ const identityMismatched = parsed.providerId !== resolved.provider.id || parsed.upstreamModelId !== resolved.model.upstreamModelId || parsed.wireApi !== resolved.model.api || canonicalJson(parsed.credentialSource) !== canonicalJson(resolved.model.credentialSource) || canonicalJson(parsed.billing) !== canonicalJson(resolved.model.billing);
4934
+ if (identityMismatched && !legacyClaudeAccountingMatches) {
3870
4935
  throw new Error("Turn execution policy does not match the current provider definition");
3871
4936
  }
4937
+ if (!definitionVersionMatches && !legacyClaudeAccountingMatches) {
4938
+ throw new TurnExecutionPolicyDefinitionMismatchError();
4939
+ }
3872
4940
  return { policy: parsed, provider: resolved.provider, model: resolved.model };
3873
4941
  }
3874
4942
  function configuredModelPricingSchedules(settings) {
@@ -3898,6 +4966,103 @@ function configuredModelPricingSchedules(settings) {
3898
4966
  ...configured
3899
4967
  };
3900
4968
  }
4969
+ function configuredModelListPricingSchedules(settings) {
4970
+ const prices = configuredModelPricingSchedules(settings);
4971
+ const configured = Object.fromEntries(
4972
+ Object.entries(parseModelPricingJson(settings.modelPricingJson)).map(([model, pricing]) => [
4973
+ model,
4974
+ normalizeModelPricingSchedule(pricing)
4975
+ ])
4976
+ );
4977
+ if (settings.openaiProvider === "openai" && isDirectOpenAiApiBaseUrl(settings.openaiBaseUrl ?? "https://api.openai.com/v1")) {
4978
+ for (const model of configuredModels(settings)) {
4979
+ if (model.providerId !== builtinProviderId(settings) || !model.upstreamModelId.startsWith("gpt-") || prices[model.id] !== void 0)
4980
+ continue;
4981
+ const reviewed = reviewedModelListPricing[model.upstreamModelId];
4982
+ if (reviewed) prices[model.id] = reviewed;
4983
+ }
4984
+ }
4985
+ for (const provider of configuredRegistryProviders(settings)) {
4986
+ for (const model of provider.models) {
4987
+ if (prices[model.id] !== void 0) continue;
4988
+ const reviewed = reviewedProviderModelPricing(settings, provider, model, configured);
4989
+ if (reviewed) prices[model.id] = reviewed;
4990
+ }
4991
+ }
4992
+ return prices;
4993
+ }
4994
+ function reviewedProviderModelPricing(settings, provider, model, configured) {
4995
+ const upstream = model.upstreamModelId ?? model.id;
4996
+ let priceId;
4997
+ let nativeClaude = false;
4998
+ switch (provider.kind) {
4999
+ case "anonymous":
5000
+ if (provider.baseUrl.replace(/\/$/u, "") === OPENROUTER_BASE_URL && upstream === DEFAULT_OPENROUTER_MODEL_ID.slice(OPENROUTER_MODEL_ID_PREFIX.length)) {
5001
+ priceId = DEFAULT_OPENROUTER_MODEL_ID;
5002
+ }
5003
+ break;
5004
+ case "codex-subscription":
5005
+ if (upstream.startsWith("gpt-")) priceId = upstream;
5006
+ break;
5007
+ case "xai-subscription":
5008
+ if (upstream.startsWith("grok-")) priceId = upstream;
5009
+ break;
5010
+ case "anthropic-workspace":
5011
+ case "anthropic-organization":
5012
+ case "claude-subscription-workspace":
5013
+ case "claude-subscription-organization":
5014
+ if (claudeNativeModelProfile(upstream)) {
5015
+ priceId = upstream;
5016
+ nativeClaude = true;
5017
+ }
5018
+ break;
5019
+ case "direct-openai-workspace":
5020
+ if (isDirectOpenAiApiBaseUrl(provider.baseUrl) && upstream.startsWith("gpt-")) {
5021
+ priceId = upstream;
5022
+ }
5023
+ break;
5024
+ case "vercel-gateway-managed":
5025
+ case "vercel-gateway-workspace":
5026
+ case "vercel-gateway-organization":
5027
+ priceId = configuredGatewayCatalogModels(settings).find(
5028
+ (candidate) => candidate.upstreamModelId === upstream && Object.values(OPENGENI_GATEWAY_MODELS).some(
5029
+ (reviewed) => reviewed.upstreamModelId === candidate.upstreamModelId
5030
+ )
5031
+ )?.productId;
5032
+ break;
5033
+ case "openrouter-workspace":
5034
+ case "openrouter-organization":
5035
+ case "openrouter-managed":
5036
+ if (upstream === DEFAULT_OPENROUTER_MODEL_ID.slice(OPENROUTER_MODEL_ID_PREFIX.length)) {
5037
+ priceId = DEFAULT_OPENROUTER_MODEL_ID;
5038
+ }
5039
+ break;
5040
+ case "api-key":
5041
+ if (isDirectOpenAiApiBaseUrl(provider.baseUrl) && upstream.startsWith("gpt-")) {
5042
+ priceId = upstream;
5043
+ } else if (provider.baseUrl.replace(/\/$/u, "") === "https://api.x.ai/v1") {
5044
+ if (upstream.startsWith("grok-")) priceId = upstream;
5045
+ } else if (provider.api === "anthropic-messages" && provider.baseUrl.replace(/\/$/u, "") === "https://api.anthropic.com/v1" && claudeNativeModelProfile(upstream)) {
5046
+ priceId = upstream;
5047
+ nativeClaude = true;
5048
+ }
5049
+ break;
5050
+ default:
5051
+ return void 0;
5052
+ }
5053
+ if (!priceId) return void 0;
5054
+ if (configured[priceId]) return configured[priceId];
5055
+ const schedule = reviewedModelListPricing[priceId] ?? defaultModelPricing[priceId] ?? (priceId === DEFAULT_OPENROUTER_MODEL_ID ? reviewedFreeOpenRouterListPricing : void 0);
5056
+ if (!schedule) return void 0;
5057
+ if (!nativeClaude || provider.anthropic?.cacheTtl !== "1h") return schedule;
5058
+ return {
5059
+ ...schedule,
5060
+ default: {
5061
+ ...schedule.default,
5062
+ cacheWriteMicrosPerMillionTokens: schedule.default.inputMicrosPerMillionTokens * 2
5063
+ }
5064
+ };
5065
+ }
3901
5066
  function configuredModelPricing(settings) {
3902
5067
  return Object.fromEntries(
3903
5068
  Object.entries(configuredModelPricingSchedules(settings)).map(([model, schedule]) => [
@@ -3963,6 +5128,216 @@ function calculateModelUsageCostMicros(settings, model, usage, options) {
3963
5128
  }
3964
5129
  function calculateModelUsageCostBreakdown(settings, model, usage, options) {
3965
5130
  const schedule = configuredModelPricingSchedules(settings)[model];
5131
+ return calculateUsageCostBreakdown(settings, model, usage, schedule, options);
5132
+ }
5133
+ function calculateModelListUsageCostBreakdown(settings, model, usage, options) {
5134
+ const schedule = configuredModelListPricingSchedules(settings)[model];
5135
+ return calculateUsageCostBreakdown(settings, model, usage, schedule, options);
5136
+ }
5137
+ function calculateModelListUsageCostSnapshot(settings, model, usage, options) {
5138
+ const schedule = configuredModelListPricingSchedules(settings)[model];
5139
+ const fallback = calculateUsageCostBreakdown(settings, model, usage, schedule, options);
5140
+ const unknown = { ...fallback, listByClassMicros: null, listByClassApprox: false };
5141
+ if (!schedule || !options?.priceContextKnown) return unknown;
5142
+ const entries = usage.requestUsageEntries?.length ? usage.requestUsageEntries : [usage];
5143
+ const classes = {
5144
+ uncachedInput: 0,
5145
+ cacheRead: 0,
5146
+ cacheWrite: 0,
5147
+ output: 0
5148
+ };
5149
+ const rawCostByPricing = /* @__PURE__ */ new Map();
5150
+ const native = nativeClaudeListWriteContext(settings, model);
5151
+ for (const entry of entries) {
5152
+ if (!knownTokenCounter(entry.inputTokens) || !knownTokenCounter(entry.outputTokens))
5153
+ return unknown;
5154
+ const cached = knownDetailTokenCounter(entry, [
5155
+ "cached_tokens",
5156
+ "cachedInputTokens",
5157
+ "cached_input_tokens"
5158
+ ]);
5159
+ const writes = knownDetailTokenCounter(entry, ["cache_write_tokens", "cacheWriteTokens"], true);
5160
+ if (cached === void 0 || writes === void 0 || cached + writes > entry.inputTokens)
5161
+ return unknown;
5162
+ const pricing = selectModelPricing(schedule, entry.inputTokens);
5163
+ if (cached > 0 && pricing.cachedInputMicrosPerMillionTokens === void 0) return unknown;
5164
+ if (writes > 0 && pricing.cacheWriteMicrosPerMillionTokens === void 0) return unknown;
5165
+ const costs = {
5166
+ uncachedInput: Math.ceil(
5167
+ (entry.inputTokens - cached - writes) * pricing.inputMicrosPerMillionTokens / 1e6
5168
+ ),
5169
+ cacheRead: Math.ceil(cached * (pricing.cachedInputMicrosPerMillionTokens ?? 0) / 1e6),
5170
+ cacheWrite: Math.ceil(writes * (pricing.cacheWriteMicrosPerMillionTokens ?? 0) / 1e6),
5171
+ output: Math.ceil(entry.outputTokens * pricing.outputMicrosPerMillionTokens / 1e6)
5172
+ };
5173
+ if (native && writes > 0) {
5174
+ const fiveMinute = knownDetailTokenCounter(entry, ["cache_write_tokens_5m"]);
5175
+ const oneHour = knownDetailTokenCounter(entry, ["cache_write_tokens_1h"]);
5176
+ if (fiveMinute === void 0 || oneHour === void 0 || fiveMinute + oneHour !== writes)
5177
+ return unknown;
5178
+ if (native.publishedRates) {
5179
+ costs.cacheWrite = Math.ceil(fiveMinute * native.publishedRates.fiveMinute / 1e6) + Math.ceil(oneHour * native.publishedRates.oneHour / 1e6);
5180
+ } else if (!(native.declaredTtl === "5m" && oneHour === 0 || native.declaredTtl === "1h" && fiveMinute === 0)) {
5181
+ return unknown;
5182
+ }
5183
+ }
5184
+ const raw = sumListCostClasses(costs);
5185
+ rawCostByPricing.set(pricing, (rawCostByPricing.get(pricing) ?? 0) + raw);
5186
+ for (const key of MODEL_LIST_COST_CLASS_KEYS) classes[key] += costs[key];
5187
+ }
5188
+ let providerCostMicros = sumListCostClasses(classes);
5189
+ let creditCostMicros = 0;
5190
+ for (const [pricing, raw] of rawCostByPricing) {
5191
+ creditCostMicros += Math.ceil(raw * (1e4 + (pricing.marginBps ?? 0)) / 1e4);
5192
+ }
5193
+ let listByClassApprox = false;
5194
+ const latencyMode = options.latencyMode ?? "standard";
5195
+ if (latencyMode !== "standard") {
5196
+ const catalogSettings = settingsForTurnExecutionPolicy(settings, model);
5197
+ const resolved = resolveModelProvider(
5198
+ catalogSettings,
5199
+ canonicalizeConfiguredModelId(catalogSettings, model)
5200
+ );
5201
+ const multiplier = resolved?.model.capabilities.latencyModes.find(
5202
+ (mode) => mode.id === latencyMode && mode.runnable
5203
+ )?.billingMultiplierBps;
5204
+ if (multiplier === void 0 || multiplier <= 0) return unknown;
5205
+ providerCostMicros = Math.ceil(providerCostMicros * multiplier / 1e4);
5206
+ creditCostMicros = Math.ceil(creditCostMicros * multiplier / 1e4);
5207
+ const scaled = allocateLatencyListCostClasses(classes, multiplier, providerCostMicros);
5208
+ if (!scaled) return unknown;
5209
+ Object.assign(classes, scaled.classes);
5210
+ listByClassApprox = scaled.approximate;
5211
+ }
5212
+ if (![providerCostMicros, creditCostMicros, ...Object.values(classes)].every(knownTokenCounter))
5213
+ return unknown;
5214
+ return { providerCostMicros, creditCostMicros, listByClassMicros: classes, listByClassApprox };
5215
+ }
5216
+ function allocateRecordedModelListCostByClass(settings, model, usage, recordedProviderCostMicros) {
5217
+ const unknown = {
5218
+ listByClassMicros: null,
5219
+ listByClassApprox: false
5220
+ };
5221
+ if (!knownTokenCounter(recordedProviderCostMicros)) return unknown;
5222
+ const schedule = configuredModelListPricingSchedules(settings)[model];
5223
+ if (!schedule) return unknown;
5224
+ const weights = { uncachedInput: 0n, cacheRead: 0n, cacheWrite: 0n, output: 0n };
5225
+ const entries = usage.requestUsageEntries?.length ? usage.requestUsageEntries : [usage];
5226
+ for (const entry of entries) {
5227
+ if (!knownTokenCounter(entry.inputTokens) || !knownTokenCounter(entry.outputTokens))
5228
+ return unknown;
5229
+ const cached = knownDetailTokenCounter(entry, [
5230
+ "cached_tokens",
5231
+ "cachedInputTokens",
5232
+ "cached_input_tokens"
5233
+ ]);
5234
+ const writes = knownDetailTokenCounter(entry, ["cache_write_tokens", "cacheWriteTokens"], true);
5235
+ if (cached === void 0 || writes === void 0 || cached + writes > entry.inputTokens)
5236
+ return unknown;
5237
+ const pricing = selectModelPricing(schedule, entry.inputTokens);
5238
+ const counters = {
5239
+ uncachedInput: entry.inputTokens - cached - writes,
5240
+ cacheRead: cached,
5241
+ cacheWrite: writes,
5242
+ output: entry.outputTokens
5243
+ };
5244
+ const rates = {
5245
+ uncachedInput: pricing.inputMicrosPerMillionTokens,
5246
+ cacheRead: pricing.cachedInputMicrosPerMillionTokens,
5247
+ cacheWrite: pricing.cacheWriteMicrosPerMillionTokens,
5248
+ output: pricing.outputMicrosPerMillionTokens
5249
+ };
5250
+ for (const key of MODEL_LIST_COST_CLASS_KEYS) {
5251
+ if (counters[key] === 0) continue;
5252
+ const rate = rates[key];
5253
+ if (!knownTokenCounter(rate)) return unknown;
5254
+ weights[key] += BigInt(counters[key]) * BigInt(rate);
5255
+ }
5256
+ }
5257
+ const classes = allocateRecordedListCostWeights(weights, recordedProviderCostMicros);
5258
+ return classes ? { listByClassMicros: classes, listByClassApprox: true } : unknown;
5259
+ }
5260
+ var MODEL_LIST_COST_CLASS_KEYS = ["uncachedInput", "cacheRead", "cacheWrite", "output"];
5261
+ function sumListCostClasses(costs) {
5262
+ return MODEL_LIST_COST_CLASS_KEYS.reduce((total, key) => total + costs[key], 0);
5263
+ }
5264
+ function allocateRecordedListCostWeights(weights, target) {
5265
+ const denominator = MODEL_LIST_COST_CLASS_KEYS.reduce((total, key) => total + weights[key], 0n);
5266
+ if (denominator === 0n) {
5267
+ return target === 0 ? { uncachedInput: 0, cacheRead: 0, cacheWrite: 0, output: 0 } : void 0;
5268
+ }
5269
+ const rows = MODEL_LIST_COST_CLASS_KEYS.map((key, index) => {
5270
+ const numerator = BigInt(target) * weights[key];
5271
+ return { key, index, value: numerator / denominator, remainder: numerator % denominator };
5272
+ });
5273
+ const remaining = BigInt(target) - rows.reduce((total, row) => total + row.value, 0n);
5274
+ const ranked = [...rows].sort(
5275
+ (a, b) => a.remainder === b.remainder ? a.index - b.index : a.remainder > b.remainder ? -1 : 1
5276
+ );
5277
+ for (let index = 0; index < Number(remaining); index++) ranked[index].value += 1n;
5278
+ return Object.fromEntries(
5279
+ rows.map((row) => [row.key, Number(row.value)])
5280
+ );
5281
+ }
5282
+ function knownTokenCounter(value) {
5283
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
5284
+ }
5285
+ function knownDetailTokenCounter(entry, keys, firstOnly = false) {
5286
+ const details = Array.isArray(entry.inputTokensDetails) ? entry.inputTokensDetails : entry.inputTokensDetails ? [entry.inputTokensDetails] : [];
5287
+ if (details.length === 0) return void 0;
5288
+ let total = 0;
5289
+ for (const detail of details) {
5290
+ const present = keys.filter((key) => detail[key] !== void 0);
5291
+ if (present.length === 0) return void 0;
5292
+ for (const key of firstOnly ? present.slice(0, 1) : present) {
5293
+ if (!knownTokenCounter(detail[key])) return void 0;
5294
+ total += detail[key];
5295
+ }
5296
+ }
5297
+ return knownTokenCounter(total) ? total : void 0;
5298
+ }
5299
+ function nativeClaudeListWriteContext(settings, modelId) {
5300
+ for (const provider of configuredRegistryProviders(settings)) {
5301
+ const model = provider.models.find((candidate) => candidate.id === modelId);
5302
+ if (!model || provider.api !== "anthropic-messages") continue;
5303
+ const result = { declaredTtl: provider.anthropic?.cacheTtl };
5304
+ const upstream = model.upstreamModelId ?? model.id;
5305
+ const overrides = parseModelPricingJson(settings.modelPricingJson);
5306
+ const official = provider.kind === "anthropic-workspace" || provider.kind === "anthropic-organization" || provider.kind === "claude-subscription-workspace" || provider.kind === "claude-subscription-organization" || provider.kind === "api-key" && provider.baseUrl.replace(/\/$/u, "") === "https://api.anthropic.com/v1";
5307
+ const published = reviewedModelListPricing[upstream]?.default;
5308
+ if (!official || !claudeNativeModelProfile(upstream) || !published?.cacheWriteMicrosPerMillionTokens || model.pricing || overrides[modelId] !== void 0 || overrides[upstream] !== void 0)
5309
+ return result;
5310
+ return {
5311
+ ...result,
5312
+ publishedRates: {
5313
+ fiveMinute: published.cacheWriteMicrosPerMillionTokens,
5314
+ oneHour: published.inputMicrosPerMillionTokens * 2
5315
+ }
5316
+ };
5317
+ }
5318
+ return void 0;
5319
+ }
5320
+ function allocateLatencyListCostClasses(classes, multiplier, target) {
5321
+ if (!knownTokenCounter(multiplier) || !knownTokenCounter(target) || !Object.values(classes).every(knownTokenCounter))
5322
+ return void 0;
5323
+ const rows = MODEL_LIST_COST_CLASS_KEYS.map((key, index) => {
5324
+ const numerator = BigInt(classes[key]) * BigInt(multiplier);
5325
+ return { key, index, value: Number(numerator / 10000n), remainder: numerator % 10000n };
5326
+ });
5327
+ const remaining = target - rows.reduce((total, row) => total + row.value, 0);
5328
+ if (remaining < 0 || remaining > rows.length) return void 0;
5329
+ const ranked = [...rows].sort(
5330
+ (a, b) => a.remainder === b.remainder ? a.index - b.index : a.remainder > b.remainder ? -1 : 1
5331
+ );
5332
+ for (let index = 0; index < remaining; index++) ranked[index].value += 1;
5333
+ return {
5334
+ classes: Object.fromEntries(
5335
+ rows.map((row) => [row.key, row.value])
5336
+ ),
5337
+ approximate: rows.some((row) => row.remainder !== 0n)
5338
+ };
5339
+ }
5340
+ function calculateUsageCostBreakdown(settings, model, usage, schedule, options) {
3966
5341
  if (!schedule) {
3967
5342
  throw new Error(`Missing model pricing for ${model}`);
3968
5343
  }
@@ -4221,7 +5596,7 @@ async function retryStartupDependency(label, operation, options = {}) {
4221
5596
  try {
4222
5597
  return await operation();
4223
5598
  } catch (error) {
4224
- if (attempt >= attempts) {
5599
+ if (attempt >= attempts || options.shouldRetry?.(error) === false) {
4225
5600
  throw error;
4226
5601
  }
4227
5602
  const delayMs = Math.min(maxDelayMs, initialDelayMs * 2 ** (attempt - 1));
@@ -4311,7 +5686,7 @@ function parseModelPricingJson(raw) {
4311
5686
  if (!model.trim()) {
4312
5687
  throw new Error("OPENGENI_MODEL_PRICING_JSON contains an empty model name");
4313
5688
  }
4314
- out[model] = z.union([ModelPricingSchema, ModelPricingScheduleSchema]).parse(value);
5689
+ out[model] = z2.union([ModelPricingSchema, ModelPricingScheduleSchema]).parse(value);
4315
5690
  }
4316
5691
  return out;
4317
5692
  }
@@ -4421,9 +5796,9 @@ function parseIntegrationsOauthClientsJson(raw) {
4421
5796
  }
4422
5797
  return out;
4423
5798
  }
4424
- var SocialOAuthClientConfigSchema = z.object({
4425
- clientId: z.string().min(1),
4426
- clientSecret: z.string().min(1).optional()
5799
+ var SocialOAuthClientConfigSchema = z2.object({
5800
+ clientId: z2.string().min(1),
5801
+ clientSecret: z2.string().min(1).optional()
4427
5802
  });
4428
5803
  var SOCIAL_OAUTH_PROVIDER_IDS = ["x", "reddit"];
4429
5804
  function parseSocialOauthClientsJson(raw) {
@@ -4560,20 +5935,9 @@ function ensureBuiltInMcpServers(settings) {
4560
5935
  ...hasDocs ? [] : [
4561
5936
  {
4562
5937
  id: "docs",
4563
- name: "Document Search",
5938
+ name: "Knowledge",
4564
5939
  url: firstPartyDocsMcpUrl,
4565
- allowedTools: [
4566
- "search_documents",
4567
- "fetch_document_chunk",
4568
- "list_document_bases",
4569
- "list_indexed_documents",
4570
- "knowledge_search",
4571
- "knowledge_get",
4572
- "knowledge_browse",
4573
- "knowledge_fetch",
4574
- "memory_search",
4575
- "memory_propose"
4576
- ],
5940
+ allowedTools: ["knowledge_search", "knowledge_get", "knowledge_browse"],
4577
5941
  cacheToolsList: false
4578
5942
  }
4579
5943
  ],
@@ -4632,8 +5996,61 @@ function isDigestPinnedModalDesktopImage(settings) {
4632
5996
  if (settings.modalImageId) return true;
4633
5997
  return typeof settings.modalImageRef === "string" && MODAL_DESKTOP_IMAGE_DIGEST_REF.test(settings.modalImageRef);
4634
5998
  }
5999
+ function trustedProxyCidrEntries(raw) {
6000
+ const entries = [];
6001
+ for (const entry of raw.split(",")) {
6002
+ const value = entry.trim();
6003
+ if (!value) continue;
6004
+ const slash = value.indexOf("/");
6005
+ const address = slash < 0 ? value : value.slice(0, slash);
6006
+ const version = isIP(address);
6007
+ const family = version === 4 ? "ipv4" : version === 6 ? "ipv6" : null;
6008
+ const maxPrefix = family === "ipv4" ? 32 : 128;
6009
+ const prefixText = slash < 0 ? String(maxPrefix) : value.slice(slash + 1);
6010
+ const prefix = /^\d{1,3}$/u.test(prefixText) ? Number(prefixText) : Number.NaN;
6011
+ if (!family || !Number.isInteger(prefix) || prefix < 0 || prefix > maxPrefix) {
6012
+ throw new Error(
6013
+ `OPENGENI_API_TRUSTED_PROXY_CIDRS entry "${value.slice(0, 64)}" is not an IP address or CIDR range`
6014
+ );
6015
+ }
6016
+ entries.push({ address, prefix, family });
6017
+ }
6018
+ return entries;
6019
+ }
6020
+ function localAllowedOriginEntries(raw) {
6021
+ const origins = [];
6022
+ for (const entry of (raw ?? "").split(",")) {
6023
+ const value = entry.trim();
6024
+ if (!value) continue;
6025
+ let url = null;
6026
+ try {
6027
+ url = new URL(value);
6028
+ } catch {
6029
+ url = null;
6030
+ }
6031
+ if (!url || url.protocol !== "http:" && url.protocol !== "https:" || url.username || url.password || url.hostname.includes("*") || url.pathname !== "/" || url.search || url.hash || value.endsWith("?") || value.endsWith("#")) {
6032
+ throw new Error(
6033
+ `OPENGENI_LOCAL_ALLOWED_ORIGINS entry "${value.slice(0, 64)}" is not an exact http(s) origin such as http://127.0.0.1:5173`
6034
+ );
6035
+ }
6036
+ origins.push(url.origin);
6037
+ }
6038
+ return origins;
6039
+ }
6040
+ var LOCAL_SANDBOX_API_ROUTES = [
6041
+ // Codemode calls, journal reads, catalog, and the Site/SDK proxy.
6042
+ /^\/v1\/workspaces\/[^/]+\/codemode(?:\/|$)/u,
6043
+ // First-party MCP, including its /docs and /files servers.
6044
+ /^\/v1\/workspaces\/[^/]+\/mcp(?:\/|$)/u,
6045
+ // The personal GitHub HTTPS smart-Git broker.
6046
+ /^\/v1\/git\/personal\/[A-Za-z0-9_-]{43}\/(?:info\/refs|git-upload-pack|git-receive-pack)$/u
6047
+ ];
6048
+ function localSandboxApiRouteAllowed(pathname) {
6049
+ return LOCAL_SANDBOX_API_ROUTES.some((route) => route.test(pathname));
6050
+ }
4635
6051
  function validateSettings(settings, source = process.env) {
4636
6052
  temporalConnectionOptions(settings);
6053
+ localAllowedOriginEntries(settings.localAllowedOrigins);
4637
6054
  if (settings.organizationUserSetupEmailTokenTransport === "query" && !settings.organizationUserSetupQueryEdgeSanitizationConfirmed) {
4638
6055
  throw new Error(
4639
6056
  "OPENGENI_ORGANIZATION_USER_SETUP_QUERY_EDGE_SANITIZATION_CONFIRMED=true is required when OPENGENI_ORGANIZATION_USER_SETUP_EMAIL_TOKEN_TRANSPORT=query"
@@ -4716,6 +6133,18 @@ function validateSettings(settings, source = process.env) {
4716
6133
  );
4717
6134
  }
4718
6135
  }
6136
+ const retiredTrustedProxyHops = source.OPENGENI_MCP_OAUTH_TRUSTED_PROXY_HOPS?.trim();
6137
+ if (retiredTrustedProxyHops && retiredTrustedProxyHops !== "0") {
6138
+ throw new Error(
6139
+ "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"
6140
+ );
6141
+ }
6142
+ const trustedProxyCidrs = trustedProxyCidrEntries(settings.apiTrustedProxyCidrs);
6143
+ if (trustedProxyCidrs.length > 0 && settings.apiTrustedProxyHops === 0) {
6144
+ throw new Error(
6145
+ "OPENGENI_API_TRUSTED_PROXY_CIDRS requires OPENGENI_API_TRUSTED_PROXY_HOPS greater than 0"
6146
+ );
6147
+ }
4719
6148
  if (settings.mcpOauthEnabled) {
4720
6149
  if (settings.productAccessMode === "configured") {
4721
6150
  throw new Error(
@@ -4976,60 +6405,7 @@ function validateSettings(settings, source = process.env) {
4976
6405
  );
4977
6406
  }
4978
6407
  }
4979
- if (settings.objectStorageBackend === "s3-compatible" || settings.objectStorageBackend === "aws-s3") {
4980
- if (Boolean(settings.objectStorageAccessKeyId) !== Boolean(settings.objectStorageSecretAccessKey)) {
4981
- throw new Error(
4982
- "OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID and OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY must both be set or both omitted"
4983
- );
4984
- }
4985
- if (settings.objectStorageBackend === "s3-compatible" && (settings.objectStorageEndpoint || settings.objectStorageInternalEndpoint || settings.objectStorageSandboxEndpoint) && (!settings.objectStorageAccessKeyId || !settings.objectStorageSecretAccessKey)) {
4986
- throw new Error(
4987
- "S3-compatible object storage endpoints require OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID and OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY"
4988
- );
4989
- }
4990
- if (settings.objectStorageAzureConnectionString || settings.objectStorageAzureAccountName || settings.objectStorageAzureAccountKey || settings.objectStorageAzureEndpoint) {
4991
- throw new Error(
4992
- "S3 object storage uses OPENGENI_OBJECT_STORAGE_* S3 settings, not OPENGENI_OBJECT_STORAGE_AZURE_* settings"
4993
- );
4994
- }
4995
- if (settings.objectStorageGcsProjectId || settings.objectStorageGcsCredentialsJson || settings.objectStorageGcsKeyFilename || settings.objectStorageGcsApiEndpoint) {
4996
- throw new Error(
4997
- "S3 object storage uses OPENGENI_OBJECT_STORAGE_* S3 settings, not OPENGENI_OBJECT_STORAGE_GCS_* settings"
4998
- );
4999
- }
5000
- } else if (settings.objectStorageBackend === "azure-blob") {
5001
- if (settings.objectStorageEndpoint || settings.objectStorageInternalEndpoint || settings.objectStorageSandboxEndpoint || settings.objectStorageAccessKeyId || settings.objectStorageSecretAccessKey) {
5002
- throw new Error(
5003
- "Azure Blob storage uses OPENGENI_OBJECT_STORAGE_AZURE_* settings, not S3-compatible object storage settings"
5004
- );
5005
- }
5006
- if (settings.objectStorageGcsProjectId || settings.objectStorageGcsCredentialsJson || settings.objectStorageGcsKeyFilename || settings.objectStorageGcsApiEndpoint) {
5007
- throw new Error(
5008
- "Azure Blob storage uses OPENGENI_OBJECT_STORAGE_AZURE_* settings, not OPENGENI_OBJECT_STORAGE_GCS_* settings"
5009
- );
5010
- }
5011
- const hasConnectionString = Boolean(settings.objectStorageAzureConnectionString);
5012
- const hasSharedKey = Boolean(settings.objectStorageAzureAccountName) && Boolean(settings.objectStorageAzureAccountKey);
5013
- if (!hasConnectionString && !hasSharedKey) {
5014
- throw new Error(
5015
- "Azure Blob storage requires OPENGENI_OBJECT_STORAGE_AZURE_CONNECTION_STRING or OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_NAME plus OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_KEY"
5016
- );
5017
- }
5018
- } else {
5019
- if (settings.objectStorageEndpoint || settings.objectStorageInternalEndpoint || settings.objectStorageSandboxEndpoint || settings.objectStorageAccessKeyId || settings.objectStorageSecretAccessKey) {
5020
- throw new Error(
5021
- "GCS object storage uses OPENGENI_OBJECT_STORAGE_GCS_* settings, not S3-compatible object storage settings"
5022
- );
5023
- }
5024
- if (settings.objectStorageAzureConnectionString || settings.objectStorageAzureAccountName || settings.objectStorageAzureAccountKey || settings.objectStorageAzureEndpoint) {
5025
- throw new Error(
5026
- "GCS object storage uses OPENGENI_OBJECT_STORAGE_GCS_* settings, not OPENGENI_OBJECT_STORAGE_AZURE_* settings"
5027
- );
5028
- }
5029
- if (settings.objectStorageGcsCredentialsJson) {
5030
- parseGcsCredentialsJson(settings.objectStorageGcsCredentialsJson);
5031
- }
5032
- }
6408
+ validateObjectStorageSettings(settings);
5033
6409
  if (settings.documentChunkOverlap >= settings.documentChunkSize) {
5034
6410
  throw new Error(
5035
6411
  "OPENGENI_DOCUMENT_CHUNK_OVERLAP must be smaller than OPENGENI_DOCUMENT_CHUNK_SIZE"
@@ -5038,7 +6414,22 @@ function validateSettings(settings, source = process.env) {
5038
6414
  parseExposedPorts(settings.dockerExposedPorts);
5039
6415
  sandboxEnvironmentVariableNames(settings);
5040
6416
  sandboxLifecycleHookIds(settings);
5041
- parseSandboxWarmRateJson(settings.sandboxWarmRateMicrosPerSecondJson);
6417
+ const warmRates = parseSandboxWarmRateJson(settings.sandboxWarmRateMicrosPerSecondJson);
6418
+ if (settings.sandboxWarmBillingMode === "credits" && Object.values(warmRates).some((rate) => !Number.isSafeInteger(rate))) {
6419
+ throw new Error(
6420
+ "OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON paid rates must be safe integers"
6421
+ );
6422
+ }
6423
+ if (settings.documentEmbeddingBillingMode === "credits" && settings.documentEmbeddingProvider === "openai" && settings.documentEmbeddingRateMicrosPerMillionBytes <= 0) {
6424
+ throw new Error(
6425
+ "OPENGENI_DOCUMENT_EMBEDDING_RATE_MICROS_PER_MILLION_BYTES must be positive when paid OpenAI embedding billing is enabled"
6426
+ );
6427
+ }
6428
+ if (settings.documentEmbeddingBillingMode === "credits" && settings.documentEmbeddingProvider === "openai" && !settings.documentEmbeddingCreditsActivatedAt) {
6429
+ throw new Error(
6430
+ "OPENGENI_DOCUMENT_EMBEDDING_CREDITS_ACTIVATED_AT is required for paid OpenAI embeddings"
6431
+ );
6432
+ }
5042
6433
  if (settings.sandboxBackend === "opensandbox") {
5043
6434
  if (!/@sha256:[0-9a-f]{64}$/i.test(settings.openSandboxImage ?? "")) {
5044
6435
  throw new Error(
@@ -5057,9 +6448,9 @@ function validateSettings(settings, source = process.env) {
5057
6448
  throw new Error(`OPENGENI_MCP_SERVERS contains duplicate id ${server.id}`);
5058
6449
  }
5059
6450
  serverIds.add(server.id);
5060
- if (server.connectionRef?.authoritySource === "host" && !settings.hostMcpAuthoritySourceAdmissionEnabled) {
6451
+ if (server.connectionRef?.authoritySource === "host") {
5061
6452
  throw new Error(
5062
- "OPENGENI_MCP_SERVERS host-owned connection refs require OPENGENI_HOST_MCP_AUTHORITY_SOURCE_ADMISSION_ENABLED=true after the whole API/worker fleet is upgraded"
6453
+ "OPENGENI_MCP_SERVERS host-owned connection refs are no longer supported; select ordinary native connections"
5063
6454
  );
5064
6455
  }
5065
6456
  }
@@ -5097,9 +6488,21 @@ function validateSettings(settings, source = process.env) {
5097
6488
  ordinaryCaptureTimeoutMs,
5098
6489
  drainCaptureTimeoutMs
5099
6490
  );
5100
- if (!(rotationLeadMs > providerDeadlineCaptureTimeoutMs + reaperPeriod)) {
6491
+ const requiredRotationLeadMs = SANDBOX_DEADLINE_COMMAND_STOP_GRACE_MS + providerDeadlineCaptureTimeoutMs + 2 * reaperPeriod;
6492
+ if (!(rotationLeadMs > requiredRotationLeadMs)) {
6493
+ throw new Error(
6494
+ `OPENGENI_SANDBOX_ROTATION_LEAD_MS (${rotationLeadMs}) must exceed the legacy command stop grace, largest durable snapshot or drain capture timeout, and two reaper periods (${requiredRotationLeadMs}), including for persisted Modal leases after a default-backend rollout.`
6495
+ );
6496
+ }
6497
+ const containmentMs = settings.sandboxIdleCommandContainmentMs;
6498
+ if (containmentMs !== void 0 && !(containmentMs > settings.sandboxIdleGraceMs)) {
5101
6499
  throw new Error(
5102
- `OPENGENI_SANDBOX_ROTATION_LEAD_MS (${rotationLeadMs}) must exceed the largest durable snapshot or drain capture timeout plus one reaper period (${providerDeadlineCaptureTimeoutMs + reaperPeriod}), including for persisted Modal leases after a default-backend rollout.`
6500
+ `OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS (${containmentMs}) must exceed OPENGENI_SANDBOX_IDLE_GRACE_MS (${settings.sandboxIdleGraceMs}): a box kept warm only by retained commands must stay available at least as long as an idle box awaiting drain.`
6501
+ );
6502
+ }
6503
+ if (containmentMs !== void 0 && optionalEnvironmentValue("OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS", source) !== void 0 && !(containmentMs < rotationLeadMs)) {
6504
+ throw new Error(
6505
+ `OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS (${containmentMs}) must be strictly less than OPENGENI_SANDBOX_ROTATION_LEAD_MS (${rotationLeadMs}): an idle box must be checkpointed and stopped well before its provider deadline.`
5103
6506
  );
5104
6507
  }
5105
6508
  if (settings.sandboxBackend === "modal") {
@@ -5132,6 +6535,11 @@ function validateSettings(settings, source = process.env) {
5132
6535
  `OPENGENI_SANDBOX_LEASE_REAPER_PERIOD_MS + OPENGENI_SANDBOX_IDLE_GRACE_MS (${reaperPeriod} + ${idleGraceMs} = ${reaperPeriod + idleGraceMs}) must be strictly less than the effective box idle timeout (${idleTimeoutMs}): a drained box must SURVIVE its full warm window so the reaper can resume + snapshot /workspace + terminate it on the sweep AFTER the drain grace elapses \u2014 Modal's idle-reap must NOT fire first (or /workspace is lost). Raise OPENGENI_MODAL_IDLE_TIMEOUT_SECONDS (defaults to OPENGENI_MODAL_TIMEOUT_SECONDS) or lower OPENGENI_SANDBOX_IDLE_GRACE_MS.`
5133
6536
  );
5134
6537
  }
6538
+ if (settings.modalIdleTimeoutSeconds !== void 0 && containmentMs !== void 0 && !(reaperPeriod + containmentMs + drainCaptureTimeoutMs < idleTimeoutMs)) {
6539
+ throw new Error(
6540
+ `OPENGENI_SANDBOX_LEASE_REAPER_PERIOD_MS + OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS + drain capture timeout (${reaperPeriod} + ${containmentMs} + ${drainCaptureTimeoutMs}) must be strictly less than OPENGENI_MODAL_IDLE_TIMEOUT_SECONDS*1000 (${idleTimeoutMs}): idle command containment must checkpoint a box before Modal's own idle reaper stops it. Lower OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS or raise the Modal idle timeout.`
6541
+ );
6542
+ }
5135
6543
  }
5136
6544
  }
5137
6545
  if (settings.sandboxDesktopEnabled && settings.sandboxBackend === "modal" && !["local", "test"].includes(settings.environment)) {
@@ -5159,7 +6567,7 @@ function validateModelCatalogSettings(settings, source = process.env) {
5159
6567
  const builtinId = builtinProviderId(settings);
5160
6568
  const providerIds = /* @__PURE__ */ new Set();
5161
6569
  for (const provider of registryProviders) {
5162
- if (provider.kind === "vercel-gateway-managed" || provider.kind === "vercel-gateway-workspace" || provider.kind === "vercel-gateway-organization" || provider.kind === "openrouter-workspace" || provider.kind === "openrouter-organization" || provider.kind === "xai-subscription") {
6570
+ if (provider.kind === "vercel-gateway-managed" || provider.kind === "vercel-gateway-workspace" || provider.kind === "vercel-gateway-organization" || provider.kind === "direct-openai-workspace" || provider.kind === "direct-azure-workspace" || provider.kind === "openrouter-workspace" || provider.kind === "openrouter-organization" || provider.kind === "anthropic-organization" || provider.kind === "anthropic-workspace" || provider.kind === "claude-subscription-workspace" || provider.kind === "claude-subscription-organization" || provider.kind === "xai-subscription") {
5163
6571
  throw new Error(
5164
6572
  `OPENGENI_MODEL_PROVIDERS_JSON provider kind ${provider.kind} is reserved for a reviewed OpenGeni credential broker`
5165
6573
  );
@@ -5201,10 +6609,25 @@ function validateModelCatalogSettings(settings, source = process.env) {
5201
6609
  `The default model ${settings.openaiModel} is not executable in the resolved model catalog`
5202
6610
  );
5203
6611
  }
6612
+ const explicitCreditsDefault = source.OPENGENI_CREDITS_DEFAULT_MODEL?.trim();
6613
+ if (explicitCreditsDefault && settings.modelCatalogSource === "code" && settings.billingMode === "stripe") {
6614
+ const creditsDefaultId = canonicalizeConfiguredModelId(settings, settings.creditsDefaultModel);
6615
+ const creditsDefault = models.find((model) => model.id === creditsDefaultId);
6616
+ if (creditsDefault?.cost !== "credits") {
6617
+ throw new Error(
6618
+ `OPENGENI_CREDITS_DEFAULT_MODEL ${settings.creditsDefaultModel} is not a credits-billed model in the resolved model catalog`
6619
+ );
6620
+ }
6621
+ }
5204
6622
  const deploymentProductIds = new Set(
5205
6623
  models.filter((model) => model.credentialSource.kind === "deployment").map((model) => model.id)
5206
6624
  );
5207
6625
  const noteProductIds = new Set(models.map((model) => model.id));
6626
+ if (settings.resolvedCodexModelsJson !== void 0) {
6627
+ for (const model of z2.array(CodexCatalogModelSchema).parse(JSON.parse(settings.resolvedCodexModelsJson))) {
6628
+ noteProductIds.add(model.id);
6629
+ }
6630
+ }
5208
6631
  for (const model of configuredGatewayCatalogModels(settings)) {
5209
6632
  deploymentProductIds.add(model.productId);
5210
6633
  noteProductIds.add(model.productId);
@@ -5282,6 +6705,62 @@ function resolveNatsCalloutConfig(settings) {
5282
6705
  }
5283
6706
  return { accountSeed, accountName, user, password };
5284
6707
  }
6708
+ function validateObjectStorageSettings(settings) {
6709
+ if (settings.objectStorageBackend === "s3-compatible" || settings.objectStorageBackend === "aws-s3") {
6710
+ if (Boolean(settings.objectStorageAccessKeyId) !== Boolean(settings.objectStorageSecretAccessKey)) {
6711
+ throw new Error(
6712
+ "OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID and OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY must both be set or both omitted"
6713
+ );
6714
+ }
6715
+ if (settings.objectStorageBackend === "s3-compatible" && (settings.objectStorageEndpoint || settings.objectStorageInternalEndpoint || settings.objectStorageSandboxEndpoint) && (!settings.objectStorageAccessKeyId || !settings.objectStorageSecretAccessKey)) {
6716
+ throw new Error(
6717
+ "S3-compatible object storage endpoints require OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID and OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY"
6718
+ );
6719
+ }
6720
+ if (settings.objectStorageAzureConnectionString || settings.objectStorageAzureAccountName || settings.objectStorageAzureAccountKey || settings.objectStorageAzureEndpoint) {
6721
+ throw new Error(
6722
+ "S3 object storage uses OPENGENI_OBJECT_STORAGE_* S3 settings, not OPENGENI_OBJECT_STORAGE_AZURE_* settings"
6723
+ );
6724
+ }
6725
+ if (settings.objectStorageGcsProjectId || settings.objectStorageGcsCredentialsJson || settings.objectStorageGcsKeyFilename || settings.objectStorageGcsApiEndpoint) {
6726
+ throw new Error(
6727
+ "S3 object storage uses OPENGENI_OBJECT_STORAGE_* S3 settings, not OPENGENI_OBJECT_STORAGE_GCS_* settings"
6728
+ );
6729
+ }
6730
+ } else if (settings.objectStorageBackend === "azure-blob") {
6731
+ if (settings.objectStorageEndpoint || settings.objectStorageInternalEndpoint || settings.objectStorageSandboxEndpoint || settings.objectStorageAccessKeyId || settings.objectStorageSecretAccessKey) {
6732
+ throw new Error(
6733
+ "Azure Blob storage uses OPENGENI_OBJECT_STORAGE_AZURE_* settings, not S3-compatible object storage settings"
6734
+ );
6735
+ }
6736
+ if (settings.objectStorageGcsProjectId || settings.objectStorageGcsCredentialsJson || settings.objectStorageGcsKeyFilename || settings.objectStorageGcsApiEndpoint) {
6737
+ throw new Error(
6738
+ "Azure Blob storage uses OPENGENI_OBJECT_STORAGE_AZURE_* settings, not OPENGENI_OBJECT_STORAGE_GCS_* settings"
6739
+ );
6740
+ }
6741
+ const hasConnectionString = Boolean(settings.objectStorageAzureConnectionString);
6742
+ const hasSharedKey = Boolean(settings.objectStorageAzureAccountName) && Boolean(settings.objectStorageAzureAccountKey);
6743
+ if (!hasConnectionString && !hasSharedKey) {
6744
+ throw new Error(
6745
+ "Azure Blob storage requires OPENGENI_OBJECT_STORAGE_AZURE_CONNECTION_STRING or OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_NAME plus OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_KEY"
6746
+ );
6747
+ }
6748
+ } else {
6749
+ if (settings.objectStorageEndpoint || settings.objectStorageInternalEndpoint || settings.objectStorageSandboxEndpoint || settings.objectStorageAccessKeyId || settings.objectStorageSecretAccessKey) {
6750
+ throw new Error(
6751
+ "GCS object storage uses OPENGENI_OBJECT_STORAGE_GCS_* settings, not S3-compatible object storage settings"
6752
+ );
6753
+ }
6754
+ if (settings.objectStorageAzureConnectionString || settings.objectStorageAzureAccountName || settings.objectStorageAzureAccountKey || settings.objectStorageAzureEndpoint) {
6755
+ throw new Error(
6756
+ "GCS object storage uses OPENGENI_OBJECT_STORAGE_GCS_* settings, not OPENGENI_OBJECT_STORAGE_AZURE_* settings"
6757
+ );
6758
+ }
6759
+ if (settings.objectStorageGcsCredentialsJson) {
6760
+ parseGcsCredentialsJson(settings.objectStorageGcsCredentialsJson);
6761
+ }
6762
+ }
6763
+ }
5285
6764
  function resolveNatsControlPlaneAuth(settings) {
5286
6765
  const user = settings.selfhostedNatsControlUser?.trim();
5287
6766
  const password = settings.selfhostedNatsControlPassword?.trim();
@@ -5293,6 +6772,9 @@ function resolveNatsControlPlaneAuth(settings) {
5293
6772
  function splitCsv(raw) {
5294
6773
  return raw.split(",").map((value) => value.trim()).filter(Boolean);
5295
6774
  }
6775
+ function sandboxImageAllowlist(settings) {
6776
+ return [...new Set(splitCsv(settings.sandboxImageAllowlist ?? ""))];
6777
+ }
5296
6778
  function uniqueEnvNames(raw, fieldName) {
5297
6779
  const seen = /* @__PURE__ */ new Set();
5298
6780
  const out = [];
@@ -5323,12 +6805,153 @@ function parseGcsCredentialsJson(raw) {
5323
6805
  function delay(ms) {
5324
6806
  return new Promise((resolve) => setTimeout(resolve, ms));
5325
6807
  }
6808
+ var CLAUDE_CONNECTION_KINDS = ["anthropic", "claude_subscription"];
6809
+ var CLAUDE_NATIVE_MODEL_PROFILES = Object.fromEntries([
6810
+ ...[
6811
+ ["claude-opus-5-5", "medium"],
6812
+ ["claude-sonnet-5-5", "medium"],
6813
+ ["claude-opus-5", "high"],
6814
+ ["claude-sonnet-5", "high"],
6815
+ ["claude-opus-4-8", "high"],
6816
+ ["claude-opus-4-7", "xhigh"]
6817
+ ].map(([id, defaultEffort]) => [
6818
+ id,
6819
+ {
6820
+ efforts: ["low", "medium", "high", "xhigh", "max"],
6821
+ defaultEffort,
6822
+ contextWindowTokens: 1e6,
6823
+ maxOutputTokens: 128e3
6824
+ }
6825
+ ]),
6826
+ ...["claude-opus-4-6", "claude-sonnet-4-6"].map((id) => [
6827
+ id,
6828
+ {
6829
+ efforts: ["low", "medium", "high", "max"],
6830
+ defaultEffort: "high",
6831
+ contextWindowTokens: 1e6,
6832
+ maxOutputTokens: 128e3
6833
+ }
6834
+ ]),
6835
+ [
6836
+ "claude-haiku-4-5-20251001",
6837
+ {
6838
+ efforts: [],
6839
+ defaultEffort: null,
6840
+ contextWindowTokens: 2e5,
6841
+ maxOutputTokens: 64e3
6842
+ }
6843
+ ]
6844
+ ]);
6845
+ function claudeNativeModelProfile(upstreamModelId) {
6846
+ return Object.hasOwn(CLAUDE_NATIVE_MODEL_PROFILES, upstreamModelId) ? CLAUDE_NATIVE_MODEL_PROFILES[upstreamModelId] : void 0;
6847
+ }
6848
+ function claudeProviderId(kind, scope = "organization") {
6849
+ return `${scope}-${kind === "anthropic" ? "anthropic" : "claude-subscription"}`;
6850
+ }
6851
+ function withClaudeConnectionCatalog(settings, connections, scope = "organization") {
6852
+ let providers = parseModelProvidersJson(settings.modelProvidersJson);
6853
+ for (const kind of CLAUDE_CONNECTION_KINDS) {
6854
+ if (kind === "claude_subscription" && !settings.claudeSubscriptionEnabled) {
6855
+ providers = providers.filter((provider) => provider.id !== claudeProviderId(kind, scope));
6856
+ continue;
6857
+ }
6858
+ const connection = connections[kind];
6859
+ if (!connection) continue;
6860
+ const id = claudeProviderId(kind, scope);
6861
+ providers = providers.filter((provider) => provider.id !== id);
6862
+ if (!connection.models.length) continue;
6863
+ providers.push({
6864
+ id,
6865
+ label: kind === "anthropic" ? "Anthropic API" : "Claude subscription",
6866
+ kind: kind === "anthropic" ? `anthropic-${scope}` : `claude-subscription-${scope}`,
6867
+ api: "anthropic-messages",
6868
+ wireProfile: "openai",
6869
+ baseUrl: "https://api.anthropic.com/v1",
6870
+ anthropic: {
6871
+ auth: kind === "anthropic" ? "api-key" : "oauth",
6872
+ cacheTtl: "5m",
6873
+ maxOutputTokens: 128e3,
6874
+ streamIdleTimeoutMs: 6e5
6875
+ },
6876
+ models: connection.models.map((model) => {
6877
+ const profile = claudeNativeModelProfile(model.upstreamModelId);
6878
+ const adaptiveThinking = Boolean(profile?.efforts.length);
6879
+ const contextWindowTokens = profile?.contextWindowTokens ?? 2e5;
6880
+ const outputReserve = profile?.maxOutputTokens ?? 32e3;
6881
+ return {
6882
+ contextWindowTokens,
6883
+ effectiveContextWindowTokens: contextWindowTokens - outputReserve,
6884
+ autoCompactTokenLimit: contextWindowTokens === 1e6 ? 8e5 : Math.min(15e4, contextWindowTokens - outputReserve - 18e3),
6885
+ id: id + "/" + model.upstreamModelId,
6886
+ upstreamModelId: model.upstreamModelId,
6887
+ label: model.label ?? (model.upstreamModelId === "claude-opus-5-5" ? "Claude Opus 5.5" : model.upstreamModelId === "claude-sonnet-5-5" ? "Claude Sonnet 5.5" : model.upstreamModelId),
6888
+ reasoningEffort: adaptiveThinking,
6889
+ hostedWebSearch: false,
6890
+ capabilities: {
6891
+ ...legacyModelCapabilities(settings, {
6892
+ reasoningEffort: adaptiveThinking,
6893
+ hostedWebSearch: false,
6894
+ vision: true
6895
+ }),
6896
+ inputFileMediaTypes: [],
6897
+ reasoning: {
6898
+ upstream: adaptiveThinking ? "supported" : "unknown",
6899
+ runnable: adaptiveThinking,
6900
+ efforts: [...profile?.efforts ?? []],
6901
+ defaultEffort: profile?.defaultEffort ?? null,
6902
+ required: false
6903
+ },
6904
+ functionCalling: { upstream: "supported", runnable: true },
6905
+ promptCaching: { upstream: "supported", runnable: true, mode: "automatic" }
6906
+ }
6907
+ };
6908
+ })
6909
+ });
6910
+ }
6911
+ return { ...settings, modelProvidersJson: JSON.stringify(providers) };
6912
+ }
6913
+ function withClaudeConnectionCredential(settings, kind, credential, scope = "organization", credentialBinding) {
6914
+ if (kind === "claude_subscription" && !settings.claudeSubscriptionEnabled)
6915
+ throw new Error("Claude subscriptions are not enabled on this deployment");
6916
+ if (!credential.trim()) throw new Error("Claude credential is empty");
6917
+ const bundle = kind === "claude_subscription" && credential.trim().startsWith("{") ? ClaudeSubscriptionCredential.parse(JSON.parse(credential)) : null;
6918
+ return {
6919
+ ...settings,
6920
+ modelProvidersJson: JSON.stringify(
6921
+ parseModelProvidersJson(settings.modelProvidersJson).map(
6922
+ (provider) => provider.id === claudeProviderId(kind, scope) ? {
6923
+ ...provider,
6924
+ apiKey: bundle?.token ?? credential,
6925
+ ...kind === "claude_subscription" && provider.anthropic ? {
6926
+ anthropic: {
6927
+ ...provider.anthropic,
6928
+ identity: bundle?.identity,
6929
+ credentialBinding: credentialBinding ? {
6930
+ connectionId: credentialBinding.connectionId,
6931
+ credentialVersion: credentialBinding.credentialVersion
6932
+ } : void 0
6933
+ }
6934
+ } : {}
6935
+ } : provider
6936
+ )
6937
+ )
6938
+ };
6939
+ }
5326
6940
  export {
5327
6941
  AGENT_INSTRUCTIONS_CORE_PLACEHOLDER,
5328
6942
  AI_GATEWAY_REALTIME_MODELS,
6943
+ CLAUDE_CONNECTION_KINDS,
6944
+ CLAUDE_OAUTH_AUTHORIZE_URL,
6945
+ CLAUDE_OAUTH_CLIENT_ID,
6946
+ CLAUDE_OAUTH_REDIRECT_URL,
6947
+ CLAUDE_OAUTH_SCOPES,
6948
+ CLAUDE_OAUTH_TOKEN_URL,
5329
6949
  CODEX_REALTIME_MODEL_ID,
5330
6950
  CapabilityStateV1Schema,
5331
6951
  CapabilitySupportV1,
6952
+ ClaudeOAuthTokenResponse,
6953
+ ClaudeSubscriptionCredential,
6954
+ ClaudeSubscriptionIdentity,
5332
6955
  ConfiguredModelCostClass,
5333
6956
  DEFAULT_AGENT_INSTRUCTIONS,
5334
6957
  DEFAULT_GOAL_IDLE_BACKOFF_MAX_MS,
@@ -5340,6 +6963,7 @@ export {
5340
6963
  GOOGLE_DRIVE_PROVIDER_RETRY_DELAY_MAX_MS,
5341
6964
  GatewayCatalogModel,
5342
6965
  IntegrationOAuthClientConfigSchema,
6966
+ McpOperationRecoverySchema,
5343
6967
  McpServerConnectionRefSchema,
5344
6968
  ModelCapabilitiesV1Schema,
5345
6969
  ModelCatalogDocument,
@@ -5361,12 +6985,15 @@ export {
5361
6985
  RegistryProviderKind,
5362
6986
  SANDBOX_ARCHIVE_CAPTURE_MAX_TIMEOUT_MS,
5363
6987
  SANDBOX_ARCHIVE_CAPTURE_SETTLEMENT_GRACE_MS,
6988
+ SANDBOX_DEADLINE_COMMAND_STOP_GRACE_MS,
5364
6989
  SANDBOX_LIFECYCLE_RETRY_HANDOFF_GRACE_MS,
5365
6990
  SANDBOX_LIFECYCLE_TRANSITION_MAX_WAIT_MS,
5366
6991
  SANDBOX_REQUIRED_ENV,
5367
6992
  SANDBOX_SNAPSHOT_MAX_TIMEOUT_MS,
5368
6993
  SUPERGROK_REALTIME_MODEL_ID,
5369
6994
  SocialOAuthClientConfigSchema,
6995
+ TurnExecutionPolicyDefinitionMismatchError,
6996
+ UnsupportedLatencyModeError,
5370
6997
  VERCEL_AI_GATEWAY_AI_SDK_BASE_URL,
5371
6998
  VERCEL_AI_GATEWAY_BASE_URL,
5372
6999
  VERCEL_AI_GATEWAY_CONNECTION_DOMAIN,
@@ -5379,6 +7006,8 @@ export {
5379
7006
  WORKSPACE_OPENROUTER_PROVIDER_ID,
5380
7007
  WORKSPACE_REALTIME_MODEL_ID_PREFIX,
5381
7008
  XAI_SUBSCRIPTION_MODEL_ID_PREFIX2 as XAI_SUBSCRIPTION_MODEL_ID_PREFIX,
7009
+ agentConfigDeploymentPolicy,
7010
+ allocateRecordedModelListCostByClass,
5382
7011
  allowedFirstPartyMcpToolsForSession,
5383
7012
  applyGitAuthPointerEnvironment,
5384
7013
  applyModelCatalogDocument,
@@ -5387,12 +7016,20 @@ export {
5387
7016
  calculateGatewayReportedCostBreakdown,
5388
7017
  calculateGatewayReportedCostMicros,
5389
7018
  calculateGatewayReportedProviderCostMicros,
7019
+ calculateModelListUsageCostBreakdown,
7020
+ calculateModelListUsageCostSnapshot,
5390
7021
  calculateModelUsageCostBreakdown,
5391
7022
  calculateModelUsageCostMicros,
5392
7023
  calculateVideoGenerationCreditCostMicros,
5393
7024
  canonicalPublicOrigin,
5394
7025
  canonicalizeConfiguredModelId,
7026
+ claudeAuthorizationUrl,
7027
+ claudeNativeModelProfile,
7028
+ claudeProviderId,
7029
+ claudeSubscriptionCapacity,
7030
+ codeSearchDeploymentPolicy,
5395
7031
  codemodeWorkspaceUrl,
7032
+ codexUpstreamModelSlugs,
5396
7033
  collectGitIdentityEnvironment,
5397
7034
  collectSandboxEnvironment,
5398
7035
  configuredAllowedModels,
@@ -5403,6 +7040,7 @@ export {
5403
7040
  configuredGatewayWorkspaceProductModelIds,
5404
7041
  configuredGoogleDriveSyncLimits,
5405
7042
  configuredModelInputIdentities,
7043
+ configuredModelListPricingSchedules,
5406
7044
  configuredModelNotes,
5407
7045
  configuredModelPricing,
5408
7046
  configuredModelPricingSchedules,
@@ -5418,20 +7056,31 @@ export {
5418
7056
  effectiveModalIdleTimeoutSeconds,
5419
7057
  effectiveSandboxDrainSnapshotTimeoutMs,
5420
7058
  effectiveSandboxLifecycle,
7059
+ emptyClaudeUsage,
5421
7060
  environmentsEncryptionKeyBytes,
5422
7061
  firstPartyMcpBaseUrl,
5423
7062
  firstPartyMcpInternalBaseUrl,
5424
7063
  firstPartyMcpInternalWorkspaceUrl,
5425
7064
  firstPartyMcpWorkspaceUrl,
5426
7065
  gatewayRequestPolicyForUpstreamModel,
7066
+ getArtifactMaterializerSettings,
7067
+ getArtifactOutboxSettings,
5427
7068
  getSettings,
5428
7069
  googleDriveOAuthCallbackUrl,
5429
7070
  googleDriveProviderRetryOptions,
5430
7071
  hasGitCredentialRepositorySelection,
5431
7072
  hasGitHubRepositorySelection,
5432
7073
  isDirectOpenAiApiBaseUrl,
7074
+ isManagedOpenRouterFreeRoute,
7075
+ isModelAvailableForNewSelection,
5433
7076
  isUsableVoiceInputSecret,
7077
+ localAllowedOriginEntries,
7078
+ localSandboxApiRouteAllowed,
7079
+ managedUserEmailAllowed,
7080
+ mergeClaudeUsage,
5434
7081
  modelCostClassForConfiguredModel,
7082
+ parseClaudeUsageHeaders,
7083
+ parseClaudeUsageResponse,
5435
7084
  parseExposedPorts,
5436
7085
  parseIntegrationsOauthClientsJson,
5437
7086
  parseMcpServers,
@@ -5464,23 +7113,33 @@ export {
5464
7113
  resolveVoiceInputProviderRegistry,
5465
7114
  responseSatisfiesLatencyMode,
5466
7115
  retryStartupDependency,
7116
+ reviewedModelListPricing,
5467
7117
  runnableLatencyModesForModel,
5468
7118
  sandboxArchiveCaptureTimeoutMs,
5469
7119
  sandboxEnvironmentVariableNames,
7120
+ sandboxImageAllowlist,
5470
7121
  sandboxLifecycleHookIds,
5471
7122
  sandboxLifecycleTransitionWaitMs,
5472
7123
  sandboxPreparationProfiles,
5473
7124
  sandboxWarmRateMicrosPerSecond,
5474
7125
  selectModelPricing,
7126
+ selectSubscriptionAccount,
5475
7127
  serviceTierForLatencyMode,
7128
+ settingsForAcceptedSubscriptionTurn,
5476
7129
  settingsWithResolvedModelContext,
5477
7130
  stableSandboxEnvironmentForRun,
5478
7131
  startupRetryOptions,
5479
7132
  streamTokenDegraded,
7133
+ subscriptionAccountShardIndex,
5480
7134
  temporalConnectionOptions,
7135
+ trustedProxyCidrEntries,
7136
+ usableJevApiKey,
5481
7137
  validateModelCatalogSettings,
5482
7138
  voiceInputDeploymentConfigured,
7139
+ withClaudeConnectionCatalog,
7140
+ withClaudeConnectionCredential,
5483
7141
  withCodexCatalogProvider,
7142
+ withDirectModelProviders,
5484
7143
  withOrganizationGatewayCatalogProvider,
5485
7144
  withOrganizationGatewayCredential,
5486
7145
  withOrganizationOpenRouterCatalogProvider,