@opengeni/config 1.1.0-canary.0 → 1.1.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,183 +512,153 @@ 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
521
  "Installed and selected Skills appear in the session Skill index; follow its reading instructions and any 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.",
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
- hostBinding: z.object({ bindingId: z.string().uuid(), generation: z.number().int().positive().safe() }).strict().optional(),
186
- subjectScope: z.enum(["workspace", "subject"]).optional()
187
- }).strict().superRefine((reference, context) => {
188
- if (reference.authoritySource === "host" && !reference.connectionId) {
189
- context.addIssue({
190
- code: "custom",
191
- message: "host authority requires connectionId",
192
- path: ["connectionId"]
193
- });
194
- }
195
- if (reference.hostBinding && reference.authoritySource !== "host")
196
- context.addIssue({
197
- code: "custom",
198
- path: ["hostBinding"],
199
- message: "Durable binding requires host authority"
200
- });
201
- if (!reference.selectedResources) return;
202
- if (!reference.connectionId) {
203
- context.addIssue({
204
- code: "custom",
205
- message: "selectedResources requires connectionId",
206
- path: ["connectionId"]
207
- });
208
- }
209
- if (!reference.provider) {
210
- context.addIssue({
211
- code: "custom",
212
- message: "selectedResources requires provider",
213
- path: ["provider"]
214
- });
215
541
  }
216
542
  });
217
- var DEFAULT_MODAL_IMAGE_REF = "opengenipublicneuacr.azurecr.io/opengeni-desktop@sha256:c3bd17b8841de1bff9bb2777aad422cf8c75de78e2c30f9ac81d0cd6810a1b78";
218
- var SettingsSchema = z.object({
219
- serviceName: z.string().default("opengeni"),
220
- environment: z.string().default("local"),
221
- 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"),
222
548
  // The release-train version baked into official images (OPENGENI_SERVER_VERSION).
223
549
  // Absent on dev/source builds — consumers must treat it as optional.
224
- serverVersion: z.string().optional(),
225
- 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),
226
556
  // Step I (§7.8 runtime half). Dedicated Postgres schema for the EMBEDDED
227
557
  // topology. Default "" → standalone: no search_path scoping, server default
228
558
  // (`public`). When set (e.g. "opengeni"), the db handle + the managed-auth
229
559
  // pool send `search_path = "<dbSchema>","opengeni_private","public"` so every
230
560
  // query resolves into the dedicated schema with NO query rewrite (schema-isolation contract F1).
231
- dbSchema: z.string().default(""),
561
+ dbSchema: z2.string().default(""),
232
562
  // Step I (§7.7). RLS posture. "force" (default) = today's FORCE-RLS via the
233
563
  // non-owner `opengeni_app` role. "scoped" = the embedded owner-role path (the
234
564
  // GUC is still emitted defensively, so the query path is identical).
235
- rlsStrategy: z.enum(["force", "scoped"]).default("force"),
565
+ rlsStrategy: z2.enum(["force", "scoped"]).default("force"),
236
566
  // Exact PostgreSQL login identity required by the standalone FORCE-RLS
237
567
  // startup/readiness assertion. Embedded `scoped` hosts own their role model
238
568
  // and are deliberately not constrained to this name.
239
- runtimeDatabaseRole: z.string().min(1).default("opengeni_app"),
240
- natsUrl: z.string().default("nats://127.0.0.1:4222"),
241
- temporalHost: z.string().default("127.0.0.1:7233"),
242
- temporalNamespace: z.string().default("default"),
243
- 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"),
244
574
  temporalTlsEnabled: EnvBoolean.default(false),
245
- temporalApiKey: z.string().optional(),
246
- temporalTlsServerName: z.string().optional(),
247
- temporalTlsRootCaCertificateBase64: z.string().optional(),
248
- temporalTlsClientCertificateBase64: z.string().optional(),
249
- temporalTlsClientPrivateKeyBase64: z.string().optional(),
250
- startupDependencyRetryAttempts: z.coerce.number().int().positive().default(30),
251
- startupDependencyRetryInitialDelayMs: z.coerce.number().int().positive().default(1e3),
252
- startupDependencyRetryMaxDelayMs: z.coerce.number().int().positive().default(5e3),
253
- turnWorkerConcurrencyMode: z.enum(["fixed", "resource-based"]).default("fixed"),
254
- turnWorkerMaxConcurrentTurns: z.coerce.number().int().positive().max(2e3).default(16),
255
- turnWorkerTargetCpuUsage: z.coerce.number().positive().max(1).default(0.8),
256
- 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),
257
587
  // Admission and emergency recovery are deliberately separate control loops.
258
588
  // The Temporal tuner stops polling at the lower target; only genuine danger
259
589
  // may invoke the disruptive graceful-drain fallback.
260
- turnWorkerEmergencyMemoryUsage: z.coerce.number().min(0.85).max(0.95).default(0.9),
261
- turnWorkerMemoryGuardIntervalMs: z.coerce.number().int().min(1e3).max(6e4).default(5e3),
262
- 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),
263
593
  observabilityStructuredLogs: EnvBoolean.default(false),
264
594
  observabilityMetricsEnabled: EnvBoolean.default(true),
265
- observabilityOtlpEndpoint: z.string().url().optional(),
266
- 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(""),
267
599
  analyticsEnabled: EnvBoolean.default(false),
268
600
  analyticsConsentRequired: EnvBoolean.default(true),
269
- analyticsReoClientId: z.string().max(128).regex(/^[A-Za-z0-9_-]+$/u).optional(),
270
- analyticsPosthogProjectKey: z.string().min(1).max(256).optional(),
271
- analyticsPosthogHost: z.string().url().max(2048).optional(),
272
- analyticsGa4MeasurementId: z.string().max(32).regex(/^G-[A-Z0-9]+$/u).optional(),
273
- 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
+ ),
274
622
  // Standards-based OAuth authorization server for external workspace MCP
275
623
  // clients. Opt-in because it creates a new public authentication surface.
276
624
  mcpOauthEnabled: EnvBoolean.default(false),
277
- // 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
278
629
  // exact number of proxy hops only when direct access to the API is blocked.
279
- 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(""),
280
635
  // Browser origin when the web app and API use separate origins in local
281
636
  // development. Production normally leaves this unset and uses publicBaseUrl.
282
- webBaseUrl: z.string().url().optional(),
637
+ webBaseUrl: z2.string().url().optional(),
283
638
  // Base URL for the bring-your-own-compute agent release assets the get.<domain>
284
639
  // install routes redirect to. Defaults to this repo's GitHub Releases. The route
285
640
  // appends `/download/agent-v<ver>/<asset>`.
286
- 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"),
287
642
  // Explicit operator-controlled promotion pointer for `/agent/latest/*`.
288
643
  // Versioned agent releases are immutable; changing this setting promotes or
289
644
  // rolls back the stable channel without moving or deleting a provider tag.
290
- 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"),
291
646
  // Optional independent beta-channel pointer. When unset, the beta update
292
647
  // manifest route is unavailable rather than silently serving stable.
293
- 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(),
294
649
  productAccessMode: ProductAccessMode.default("local"),
295
- // --- canonical organization-tenancy authority activation, default OFF ---
296
- // The named PRE-ACTIVATION opt-out for the organization-tenancy program. FALSE (the
297
- // default, and the value an operator leaves in place to decline or defer) means
298
- // this deployment stays on the reversible legacy workspace-owned lane: no phase-F
299
- // subsystem may switch its access decision to organization/membership authority
300
- // ids. TRUE is an operator's explicit statement that the activation preconditions
301
- // in docs/organization-tenancy.md have been proven for this deployment and that
302
- // the one-way boundary is accepted.
303
- //
304
- // This is NOT a kill switch and NOT a rollback: once an activation migration has
305
- // committed, setting it back to false does not restore the legacy authority - only
306
- // forward recovery is available. It also grants and revokes nothing by itself;
307
- // every individual authorization decision keeps its own fences.
308
- //
309
- // No runtime path reads it yet: canonical activation (phase F) is unshipped, so
310
- // the flag exists to reserve the name, pin the safe default, and give every future
311
- // activation slice one gate to consult. EnvBoolean (NOT z.coerce.boolean(), which
312
- // coerces "false" -> true and would activate the moment an operator wrote the
313
- // variable out to disable it).
314
- organizationTenancyCanonicalActivationEnabled: EnvBoolean.default(false),
315
650
  billingMode: BillingMode.default("disabled"),
651
+ // Explicit launch gate for the one-time $10 verified self-service signup grant.
652
+ // A migration or deployment alone must not start issuing live credits.
653
+ verifiedSignupTrialCreditsEnabled: EnvBoolean.default(false),
316
654
  entitlementsMode: EntitlementsMode.default("none"),
317
655
  usageLimitsMode: UsageLimitsMode.default("none"),
318
- staticEntitlementsJson: z.string().default("{}"),
319
- staticUsageLimitsJson: z.string().default("{}"),
320
- delegationSecret: z.string().optional(),
656
+ // Gate new allowance policies until every API/worker in the fleet enforces
657
+ // them. Persisted-policy enforcement and recovery reads/clears stay active.
658
+ usageAllowancesEnabled: EnvBoolean.default(false),
659
+ staticEntitlementsJson: z2.string().default("{}"),
660
+ staticUsageLimitsJson: z2.string().default("{}"),
661
+ delegationSecret: z2.string().optional(),
321
662
  defaultFirstPartyMcpTools: EnvFirstPartyMcpTools,
322
663
  allowedFirstPartyMcpTools: EnvFirstPartyMcpTools,
323
664
  // sandbox workspace scoped stream-token HMAC secret (sandbox contract §C.3 / stream-token availability contract).
@@ -325,7 +666,7 @@ var SettingsSchema = z.object({
325
666
  // family, `ogs_` vs `ogd_` prefix). REQUIRED-WHEN-DESKTOP, but the absence of
326
667
  // BOTH while sandboxDesktopEnabled=true is a GRACEFUL DEGRADE (DesktopStream
327
668
  // transport:null + a loud boot warning), NOT a hard boot-fail (stream-token availability contract).
328
- streamTokenSecret: z.string().optional(),
669
+ streamTokenSecret: z2.string().optional(),
329
670
  // The desktop input plane (raw stream:control writes) is OFF in v1: even a
330
671
  // holder of stream:control gets 403 until this flips. Keeps stream:control a
331
672
  // declared-but-inert permission so later hardening is a flag flip.
@@ -348,47 +689,51 @@ var SettingsSchema = z.object({
348
689
  // Optional release-coherent bootstrap hint for custom rigs/connected machines
349
690
  // that do not carry the stock-image ogtool binary. Exact stable versions only:
350
691
  // the agent must never guess a tag or silently install `latest`.
351
- ogtoolPackageSpec: z.string().regex(/^@opengeni\/ogtool@(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u).optional(),
352
- environmentsEncryptionKey: z.string().optional(),
692
+ ogtoolPackageSpec: z2.string().regex(/^@opengeni\/ogtool@(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u).optional(),
693
+ environmentsEncryptionKey: z2.string().optional(),
353
694
  integrationsEnabled: EnvBoolean.default(false),
354
- integrationsStateSecret: z.string().optional(),
695
+ integrationsStateSecret: z2.string().optional(),
696
+ integrationsOauthShortStateEnabled: EnvBoolean.default(false),
355
697
  integrationsAllowPrivateNetworkTargets: EnvBoolean.default(false),
356
- integrationsOauthClientsJson: z.string().default("{}"),
357
- slackClientId: z.string().optional(),
358
- slackClientSecret: z.string().optional(),
359
- slackSigningSecret: z.string().optional(),
698
+ integrationsOauthClientsJson: z2.string().default("{}"),
699
+ gmailWatchTopicName: z2.string().regex(/^projects\/[^/]+\/topics\/[^/]+$/u).optional(),
700
+ slackClientId: z2.string().optional(),
701
+ slackClientSecret: z2.string().optional(),
702
+ slackSigningSecret: z2.string().optional(),
703
+ // Unlisted apps share Slack’s restricted history/replies quota across all tokens.
704
+ slackAccessMode: z2.enum(["limited", "full"]).default("limited"),
360
705
  slackBotDisplayName: OpenGeniSlackBotDisplayName.default("OpenGeni"),
361
- slackCommand: z.string().trim().regex(/^\/[a-z0-9_-]{1,31}$/u).default("/opengeni"),
362
- googleDriveClientId: z.string().optional(),
363
- googleDriveClientSecret: z.string().optional(),
364
- googleDriveSyncMaxItems: z.coerce.number().int().positive().max(1e4).default(500),
365
- googleDriveSyncMaxBytes: z.coerce.number().int().positive().max(5e9).default(5e8),
366
- googleDriveSyncMaxFileBytes: z.coerce.number().int().positive().max(5e9).default(1e8),
367
- googleDriveSyncMaxProviderRequests: z.coerce.number().int().positive().max(1e4).default(1e3),
368
- googleDriveSyncMaxElapsedSeconds: z.coerce.number().int().positive().max(3600).default(300),
369
- googleDriveSyncMaxFailureDetails: z.coerce.number().int().positive().max(100).default(25),
370
- googleDriveProviderRequestTimeoutMs: z.coerce.number().int().min(1e3).max(GOOGLE_DRIVE_PROVIDER_REQUEST_TIMEOUT_MAX_MS).default(3e4),
371
- googleDriveProviderRetryAttempts: z.coerce.number().int().min(1).max(5).default(3),
372
- googleDriveProviderRetryInitialDelayMs: z.coerce.number().int().positive().max(3e4).default(250),
373
- googleDriveProviderRetryMaxDelayMs: z.coerce.number().int().positive().max(GOOGLE_DRIVE_PROVIDER_RETRY_DELAY_MAX_MS).default(5e3),
374
- googleDriveProviderRetryBudgetMs: z.coerce.number().int().positive().max(12e4).default(15e3),
375
- fikenClientId: z.string().optional(),
376
- fikenClientSecret: z.string().optional(),
706
+ slackCommand: z2.string().trim().regex(/^\/[a-z0-9_-]{1,31}$/u).default("/opengeni"),
707
+ googleDriveClientId: z2.string().optional(),
708
+ googleDriveClientSecret: z2.string().optional(),
709
+ googleDriveSyncMaxItems: z2.coerce.number().int().positive().max(1e4).default(500),
710
+ googleDriveSyncMaxBytes: z2.coerce.number().int().positive().max(5e9).default(5e8),
711
+ googleDriveSyncMaxFileBytes: z2.coerce.number().int().positive().max(5e9).default(1e8),
712
+ googleDriveSyncMaxProviderRequests: z2.coerce.number().int().positive().max(1e4).default(1e3),
713
+ googleDriveSyncMaxElapsedSeconds: z2.coerce.number().int().positive().max(3600).default(300),
714
+ googleDriveSyncMaxFailureDetails: z2.coerce.number().int().positive().max(100).default(25),
715
+ googleDriveProviderRequestTimeoutMs: z2.coerce.number().int().min(1e3).max(GOOGLE_DRIVE_PROVIDER_REQUEST_TIMEOUT_MAX_MS).default(3e4),
716
+ googleDriveProviderRetryAttempts: z2.coerce.number().int().min(1).max(5).default(3),
717
+ googleDriveProviderRetryInitialDelayMs: z2.coerce.number().int().positive().max(3e4).default(250),
718
+ googleDriveProviderRetryMaxDelayMs: z2.coerce.number().int().positive().max(GOOGLE_DRIVE_PROVIDER_RETRY_DELAY_MAX_MS).default(5e3),
719
+ googleDriveProviderRetryBudgetMs: z2.coerce.number().int().positive().max(12e4).default(15e3),
720
+ fikenClientId: z2.string().optional(),
721
+ fikenClientSecret: z2.string().optional(),
377
722
  googleDriveWorkspaceEventsEnabled: EnvBoolean.optional(),
378
- atlassianClientId: z.string().optional(),
379
- atlassianClientSecret: z.string().optional(),
723
+ atlassianClientId: z2.string().optional(),
724
+ atlassianClientSecret: z2.string().optional(),
380
725
  // Undefined is meaningful: the migration boundary persists the product
381
726
  // default of 3 when no deployment override is supplied.
382
- maxNestedAgentDepth: z.coerce.number().int().nonnegative().max(MAX_NESTED_AGENT_DEPTH).optional(),
727
+ maxNestedAgentDepth: z2.coerce.number().int().nonnegative().max(MAX_NESTED_AGENT_DEPTH).optional(),
383
728
  // Operator OAuth apps for first-party social connectors, keyed by provider
384
729
  // id ("x", "reddit"): {"x":{"clientId":"...","clientSecret":"..."}}.
385
- socialOauthClientsJson: z.string().default("{}"),
730
+ socialOauthClientsJson: z2.string().default("{}"),
386
731
  // Session goal guard rails. Goals are designed for runs that legitimately
387
732
  // span days, so length is bounded by explicit completion/pause and budget
388
733
  // exhaustion, never by count. goalMaxAutoContinuations is therefore UNSET
389
734
  // by default (no cap); deployments may configure one, and it then acts as a
390
735
  // hard ceiling that per-goal overrides can only lower.
391
- goalMaxAutoContinuations: z.coerce.number().int().positive().optional(),
736
+ goalMaxAutoContinuations: z2.coerce.number().int().positive().optional(),
392
737
  // Idle backoff between CONSECUTIVE no-input goal continuations. This is
393
738
  // pacing, not a cap: the first continuation after a turn that consumed any
394
739
  // external input is immediate, the n-th consecutive no-input continuation
@@ -396,7 +741,7 @@ var SettingsSchema = z.object({
396
741
  // any new input (machine input, human/API prompt, Steer) wakes the session
397
742
  // immediately. The delay never exceeds goalIdleBackoffMaxMs.
398
743
  goalIdleBackoffMs: EnvGoalIdleBackoffMs.default(DEFAULT_GOAL_IDLE_BACKOFF_MS),
399
- goalIdleBackoffMaxMs: z.coerce.number().int().positive().default(DEFAULT_GOAL_IDLE_BACKOFF_MAX_MS),
744
+ goalIdleBackoffMaxMs: z2.coerce.number().int().positive().default(DEFAULT_GOAL_IDLE_BACKOFF_MAX_MS),
400
745
  // Child lifecycle notices: a child session's requires_action freeze, its
401
746
  // resolution, a direct Pause, a provider-capacity wait, and goal progress
402
747
  // become typed `session_system_updates` rows for the parent (in addition to
@@ -410,16 +755,6 @@ var SettingsSchema = z.object({
410
755
  // into @opengeni/db once at boot.
411
756
  // Env: OPENGENI_CHILD_LIFECYCLE_NOTICES_ENABLED.
412
757
  childLifecycleNoticesEnabled: EnvBoolean.default(false),
413
- // Explicit host-owned MCP connection authority is a rolling protocol
414
- // activation. Keep it off while any API, worker, or browser bundle predates
415
- // the authority discriminator; enable it only after the whole fleet runs an
416
- // image that understands host refs. Legacy markerless non-UUID refs remain a
417
- // separate compatibility lane for already-persisted embedding integrations.
418
- // Env: OPENGENI_HOST_MCP_AUTHORITY_SOURCE_ADMISSION_ENABLED.
419
- hostMcpAuthoritySourceAdmissionEnabled: EnvBoolean.default(false),
420
- // Server-owned per-organization remote MCP resolver configuration. Optional;
421
- // inline credentials and native provider OAuth do not require this service.
422
- hostMcpCredentialResolversJson: z.string().optional(),
423
758
  // Per-channel and per-DM Slack workspace routing. Default ON. A channel does
424
759
  // not count a personal workspace as a candidate, so an organization with one
425
760
  // shared workspace resolves it as the sole candidate and never asks; the
@@ -434,17 +769,17 @@ var SettingsSchema = z.object({
434
769
  // session turn. Effectively unbounded by default for the same reason as
435
770
  // above; the graceful max-turns valve (idle + goal continuation, never a
436
771
  // session failure) remains as inert safety should a deployment set a cap.
437
- agentMaxModelCallsPerTurn: z.coerce.number().int().positive().default(1e6),
772
+ agentMaxModelCallsPerTurn: z2.coerce.number().int().positive().default(1e6),
438
773
  // Deployment fallback for models that do not declare their own window.
439
774
  // Built-in billed GPT-5.6 Sol/Terra/Luna pin Codex's 272k catalog instead.
440
775
  // OpenGeni always performs one durable, portable plaintext compaction
441
776
  // transition; there is no provider/server/off mode ladder.
442
- contextWindowTokens: z.coerce.number().int().positive().default(105e4),
777
+ contextWindowTokens: z2.coerce.number().int().positive().default(105e4),
443
778
  // Optional model-catalog effective input ceiling. Codex and billed GPT-5.6
444
779
  // models expose this as raw context_window * effective_context_window_percent;
445
780
  // when absent, retain the deployment-level window-minus-reserved-output
446
781
  // behavior.
447
- contextEffectiveWindowTokens: z.coerce.number().int().positive().optional(),
782
+ contextEffectiveWindowTokens: z2.coerce.number().int().positive().optional(),
448
783
  // Proactive compaction threshold as a ratio of the model context window.
449
784
  // Defaults to 90%: compact as late as possible — retained context beats early
450
785
  // headroom now that per-model windows are declared honestly (input-effective,
@@ -452,7 +787,7 @@ var SettingsSchema = z.object({
452
787
  // absorbs any overshoot as one retried call rather than a dead session.
453
788
  // Clamped to [0.3, 0.9] so deployments can tune the trigger without
454
789
  // accidentally disabling compaction.
455
- contextCompactionThresholdRatio: z.coerce.number().default(0.9).transform((value) => {
790
+ contextCompactionThresholdRatio: z2.coerce.number().default(0.9).transform((value) => {
456
791
  if (!Number.isFinite(value)) {
457
792
  return 0.9;
458
793
  }
@@ -460,118 +795,127 @@ var SettingsSchema = z.object({
460
795
  }),
461
796
  // Tokens reserved for model output; subtracted from the window to get the
462
797
  // usable input budget B = contextWindowTokens - contextReservedOutputTokens.
463
- contextReservedOutputTokens: z.coerce.number().int().nonnegative().default(128e3),
798
+ contextReservedOutputTokens: z2.coerce.number().int().nonnegative().default(128e3),
464
799
  // Model-catalog auto-compact limit. When present it is clamped to
465
800
  // 90% of the raw window, matching Codex core's auto_compact_token_limit().
466
- contextAutoCompactThresholdTokens: z.coerce.number().int().positive().optional(),
801
+ contextAutoCompactThresholdTokens: z2.coerce.number().int().positive().optional(),
467
802
  // Provider-neutral fallback for canonical model-facing tool-result text.
468
803
  // The current stable Codex catalog policy is 10k tokens; the truncator adds
469
804
  // Codex's 1.2x JSON serialization allowance when applying it.
470
- modelToolOutputTruncationTokens: z.coerce.number().int().positive().default(1e4),
805
+ modelToolOutputTruncationTokens: z2.coerce.number().int().positive().default(1e4),
471
806
  authRequired: EnvBoolean.default(false),
472
- accessKey: z.string().optional(),
807
+ accessKey: z2.string().optional(),
473
808
  authAllowHealth: EnvBoolean.default(true),
474
809
  authAllowMetrics: EnvBoolean.default(false),
475
- apiHost: z.string().default("0.0.0.0"),
476
- apiPort: z.coerce.number().int().positive().default(8e3),
477
- workerHttpPort: z.coerce.number().int().positive().default(8001),
810
+ apiHost: z2.string().default("0.0.0.0"),
811
+ apiPort: z2.coerce.number().int().positive().default(8e3),
812
+ // When set, GET /metrics is served only on this dedicated internal listener
813
+ // and never on the public API port that an ingress forwards to.
814
+ apiMetricsPort: z2.coerce.number().int().positive().optional(),
815
+ workerHttpPort: z2.coerce.number().int().positive().default(8001),
478
816
  // Worker-side first-party MCP traffic stays on the deployment's internal
479
817
  // network. OPENGENI_MCP_URL remains the sandbox/external route used by
480
818
  // Codemode and remote placements.
481
- opengeniMcpInternalUrl: z.string().url().optional(),
482
- opengeniMcpUrl: z.string().url().optional(),
819
+ opengeniMcpInternalUrl: z2.string().url().optional(),
820
+ opengeniMcpUrl: z2.string().url().optional(),
483
821
  // Origins allowed to send browser cookies cross-origin. Other origins may
484
822
  // call the public API with bearer credentials, but never receive credentialed
485
823
  // CORS responses.
486
- corsAllowOriginRegex: z.string().default(String.raw`^https?://(localhost|127\.0\.0\.1)(:\d+)?$`),
487
- openaiProvider: z.enum(["openai", "azure"]).default("openai"),
488
- openaiApiKey: z.string().optional(),
489
- openaiBaseUrl: z.string().optional(),
490
- openaiModel: z.string().default("gpt-5.6-sol"),
491
- openaiAllowedModels: z.string().default("gpt-5.6-sol,gpt-5.6-terra,gpt-5.6-luna"),
824
+ corsAllowOriginRegex: z2.string().default(String.raw`^https?://(localhost|127\.0\.0\.1)(:\d+)?$`),
825
+ // Local development only (`local` access mode in the `local` environment):
826
+ // extra exact browser origins, comma-separated, that may call the
827
+ // unauthenticated API besides this stack's own web origin. The local browser
828
+ // boundary ignores `corsAllowOriginRegex`.
829
+ localAllowedOrigins: z2.string().optional(),
830
+ openaiProvider: z2.enum(["openai", "azure"]).default("openai"),
831
+ openaiApiKey: z2.string().optional(),
832
+ openaiBaseUrl: z2.string().optional(),
833
+ openaiModel: z2.string().default("gpt-6-astra"),
834
+ openaiAllowedModels: z2.string().default("gpt-6-astra,gpt-6-sol,gpt-6-luna"),
492
835
  // OpenGeni-managed Vercel AI Gateway. When configured, the two reviewed
493
836
  // Gateway models below are added to the managed-credit catalog. Workspace
494
837
  // Gateway keys use the encrypted connection broker and never this secret.
495
- vercelAiGatewayApiKey: z.string().optional(),
838
+ vercelAiGatewayApiKey: z2.string().optional(),
496
839
  /** Image adapter route; native hosted providers ignore this model. */
497
- imageGenerationModel: z.string().trim().min(1).max(256).default("openai/gpt-image-2"),
840
+ imageGenerationModel: z2.string().trim().min(1).max(256).default("openai/gpt-image-2"),
498
841
  /** Durable video generation uses the workspace-owned Gateway credential. */
499
- videoGenerationPollIntervalMs: z.coerce.number().int().min(1e3).max(6e4).default(5e3),
500
- videoGenerationRecoveryDeadlineMs: z.coerce.number().int().min(6e4).max(24 * 60 * 6e4).default(2 * 60 * 6e4),
501
- videoGenerationReferenceUrlTtlSeconds: z.coerce.number().int().min(300).max(6 * 60 * 60).default(60 * 60),
502
- videoGenerationMaxConcurrentPerWorkspace: z.coerce.number().int().min(1).max(16).default(2),
503
- videoGenerationWorkspaceQuotaBytes: z.coerce.number().int().positive().max(Number.MAX_SAFE_INTEGER).default(20 * 1024 * 1024 * 1024),
504
- videoGenerationTempDirectory: z.string().trim().min(1).max(1024).default("/tmp/opengeni-video"),
505
- videoGenerationFfprobePath: z.string().trim().min(1).max(1024).default("ffprobe"),
842
+ videoGenerationPollIntervalMs: z2.coerce.number().int().min(1e3).max(6e4).default(5e3),
843
+ videoGenerationRecoveryDeadlineMs: z2.coerce.number().int().min(6e4).max(24 * 60 * 6e4).default(2 * 60 * 6e4),
844
+ videoGenerationReferenceUrlTtlSeconds: z2.coerce.number().int().min(300).max(6 * 60 * 60).default(60 * 60),
845
+ videoGenerationMaxConcurrentPerWorkspace: z2.coerce.number().int().min(1).max(16).default(2),
846
+ videoGenerationWorkspaceQuotaBytes: z2.coerce.number().int().positive().max(Number.MAX_SAFE_INTEGER).default(20 * 1024 * 1024 * 1024),
847
+ videoGenerationTempDirectory: z2.string().trim().min(1).max(1024).default("/tmp/opengeni-video"),
848
+ videoGenerationFfprobePath: z2.string().trim().min(1).max(1024).default("ffprobe"),
506
849
  // OpenGeni's customer price, not a claim about the provider's delayed cost report.
507
850
  // The durable operation freezes the exact resulting price before provider submit.
508
- videoGenerationCredit480pMicrosPerSecond: z.coerce.number().int().positive().max(1e7).default(155e3),
509
- videoGenerationCredit720pMicrosPerSecond: z.coerce.number().int().positive().max(1e7).default(35e4),
851
+ videoGenerationCredit480pMicrosPerSecond: z2.coerce.number().int().positive().max(1e7).default(155e3),
852
+ videoGenerationCredit720pMicrosPerSecond: z2.coerce.number().int().positive().max(1e7).default(35e4),
510
853
  // Native composer voice input (browser MediaRecorder → API transcription).
511
854
  // Provider credentials stay server-side; ClientConfig only projects availability
512
855
  // and hard ceilings. Selection happens once before audio is sent — never retry
513
856
  // the same clip across vendors after an upstream request may have started.
514
- voiceInputMaxDurationSeconds: z.coerce.number().int().positive().max(600).default(60),
515
- voiceInputMaxSizeBytes: z.coerce.number().int().positive().max(25 * 1024 * 1024).default(25 * 1024 * 1024),
857
+ voiceInputMaxDurationSeconds: z2.coerce.number().int().positive().max(600).default(60),
858
+ voiceInputMaxSizeBytes: z2.coerce.number().int().positive().max(25 * 1024 * 1024).default(25 * 1024 * 1024),
516
859
  // Durable long-form capture uploads bounded chunks to object storage, then
517
860
  // normalizes them into provider-safe segments. It is advertised only when
518
861
  // object storage and the configured ffmpeg executable are both available.
519
862
  voiceInputResumableEnabled: EnvBoolean.default(true),
520
- voiceInputResumableMaxDurationSeconds: z.coerce.number().int().positive().max(8 * 60 * 60).default(2 * 60 * 60),
521
- voiceInputResumableMaxSizeBytes: z.coerce.number().int().positive().max(512 * 1024 * 1024).default(512 * 1024 * 1024),
522
- voiceInputResumableMaxChunkSizeBytes: z.coerce.number().int().positive().max(25 * 1024 * 1024).default(8 * 1024 * 1024),
523
- voiceInputResumableRetentionSeconds: z.coerce.number().int().positive().max(7 * 24 * 60 * 60).default(24 * 60 * 60),
524
- voiceInputFfmpegPath: z.string().trim().min(1).max(1024).default("ffmpeg"),
863
+ voiceInputResumableMaxDurationSeconds: z2.coerce.number().int().positive().max(8 * 60 * 60).default(2 * 60 * 60),
864
+ voiceInputResumableMaxSizeBytes: z2.coerce.number().int().positive().max(512 * 1024 * 1024).default(512 * 1024 * 1024),
865
+ voiceInputResumableMaxChunkSizeBytes: z2.coerce.number().int().positive().max(25 * 1024 * 1024).default(8 * 1024 * 1024),
866
+ voiceInputResumableRetentionSeconds: z2.coerce.number().int().positive().max(7 * 24 * 60 * 60).default(24 * 60 * 60),
867
+ voiceInputFfmpegPath: z2.string().trim().min(1).max(1024).default("ffmpeg"),
525
868
  // Preferred provider order (comma-separated ids). First configured+ready wins.
526
869
  // Connected subscription STT is preferred by default; operators can put
527
870
  // openai/azure-openai first explicitly.
528
871
  // Supported: supergrok-subscription, codex-subscription, openai, azure-openai.
529
- voiceInputProviderOrder: z.string().default("supergrok-subscription,codex-subscription,openai,azure-openai"),
872
+ voiceInputProviderOrder: z2.string().default("supergrok-subscription,codex-subscription,openai,azure-openai"),
530
873
  // OpenAI public /v1/audio/transcriptions path. Reuses OPENGENI_OPENAI_API_KEY
531
874
  // when voiceInputOpenaiApiKey is unset. Default model is gpt-transcribe.
532
875
  voiceInputOpenaiEnabled: EnvBoolean.default(true),
533
- voiceInputOpenaiApiKey: z.string().optional(),
534
- voiceInputOpenaiBaseUrl: z.string().optional(),
535
- voiceInputOpenaiModel: z.string().default("gpt-transcribe"),
876
+ voiceInputOpenaiApiKey: z2.string().optional(),
877
+ voiceInputOpenaiBaseUrl: z2.string().optional(),
878
+ voiceInputOpenaiModel: z2.string().default("gpt-transcribe"),
536
879
  // Azure OpenAI deployment-scoped audio transcriptions. Reuses the turn-model
537
880
  // Azure endpoint/key/AD token when voice-specific overrides are unset.
538
881
  voiceInputAzureEnabled: EnvBoolean.default(true),
539
- voiceInputAzureEndpoint: z.string().optional(),
540
- voiceInputAzureDeployment: z.string().optional(),
541
- voiceInputAzureApiVersion: z.string().optional(),
542
- voiceInputAzureApiKey: z.string().optional(),
543
- voiceInputAzureAdToken: z.string().optional(),
882
+ voiceInputAzureEndpoint: z2.string().optional(),
883
+ voiceInputAzureDeployment: z2.string().optional(),
884
+ voiceInputAzureApiVersion: z2.string().optional(),
885
+ voiceInputAzureApiKey: z2.string().optional(),
886
+ voiceInputAzureAdToken: z2.string().optional(),
544
887
  // Legacy opt-in for undocumented ChatGPT /backend-api/transcribe. When
545
888
  // OPENGENI_CODEX_SUBSCRIPTION_ENABLED is true, Codex STT is included without
546
889
  // this flag. Set false and omit codex-subscription from PROVIDER_ORDER to
547
890
  // keep subscription model routing while disabling Codex voice input.
548
891
  voiceInputCodexExperimentalEnabled: EnvBoolean.default(false),
549
- modelPricingJson: z.string().default("{}"),
892
+ modelPricingJson: z2.string().default("{}"),
550
893
  // Supported-model membership source. Database mode is resolved by the async
551
894
  // core overlay; getSettings remains synchronous and env-only.
552
- modelCatalogSource: z.enum(["code", "database"]).default("code"),
895
+ modelCatalogSource: z2.enum(["code", "database"]).default("code"),
553
896
  // Deployment-owned workspace-facing price policy. This is deliberately
554
897
  // separate from catalog membership and upstream credential ownership.
555
898
  // Shape: { "product/model-id": "free" | "credits" }.
556
- modelCostPolicyJson: z.string().default("{}"),
899
+ modelCostPolicyJson: z2.string().default("{}"),
557
900
  // Optional per-product agent guidance. Database mode replaces this with the
558
901
  // singleton document's validated modelNotes map.
559
- modelNotesJson: z.string().default("{}"),
902
+ modelNotesJson: z2.string().default("{}"),
560
903
  // Managed OpenRouter credential. The curated model table is injected in
561
904
  // code/catalog-document resolution and never read from host provider JSON.
562
- openrouterApiKey: z.string().optional(),
905
+ openrouterApiKey: z2.string().optional(),
563
906
  // Internal, secret-free catalog overlays populated only by
564
907
  // applyModelCatalogDocument. They intentionally have no OPENGENI_* env
565
908
  // binding so database mode cannot be bypassed with a second source.
566
- resolvedGatewayModelsJson: z.string().optional(),
567
- resolvedOpenRouterModelsJson: z.string().optional(),
909
+ resolvedGatewayModelsJson: z2.string().optional(),
910
+ resolvedOpenRouterModelsJson: z2.string().optional(),
911
+ resolvedCodexModelsJson: z2.string().optional(),
568
912
  // Extra (non-built-in) model providers, declared by the host as a JSON
569
913
  // provider registry. Each entry carries its own base URL, API key, wire API
570
914
  // ("responses" | "chat") and the models it exposes. The models a client may
571
915
  // use are the UNION of the built-in provider's allowed models and every
572
916
  // registry provider's models. validateSettings parses this at boot so a
573
917
  // malformed registry / unresolvable key / id collision fails fast.
574
- modelProvidersJson: z.string().default("[]"),
918
+ modelProvidersJson: z2.string().default("[]"),
575
919
  // Codex (ChatGPT) subscription: when enabled, a per-workspace connected
576
920
  // subscription is injected as a synthetic "codex-subscription" registry
577
921
  // provider whose models route through the ChatGPT backend (@opengeni/codex).
@@ -581,15 +925,17 @@ var SettingsSchema = z.object({
581
925
  // account pool and a distinct rail from the existing xai/* API-key provider.
582
926
  supergrokSubscriptionEnabled: EnvBoolean.default(false),
583
927
  // OPENGENI_SUPERGROK_SUBSCRIPTION_ENABLED
928
+ claudeSubscriptionEnabled: EnvBoolean.default(false),
929
+ // OPENGENI_CLAUDE_SUBSCRIPTION_ENABLED
584
930
  // Maximum silence between complete, valid SuperGrok SSE data events. This is
585
931
  // not a request/run duration cap; every valid event resets the timer.
586
- supergrokResponseStreamIdleTimeoutMs: z.coerce.number().int().positive().max(24 * 60 * 6e4).default(XAI_RESPONSE_STREAM_IDLE_TIMEOUT_MS),
932
+ supergrokResponseStreamIdleTimeoutMs: z2.coerce.number().int().positive().max(24 * 60 * 6e4).default(XAI_RESPONSE_STREAM_IDLE_TIMEOUT_MS),
587
933
  // Expose the connected apps attached to a Codex subscription through the
588
934
  // synthetic codex_apps MCP server. Independent from subscription routing so
589
935
  // operators can use Codex models without exposing ChatGPT connectors.
590
936
  codexConnectedAppsEnabled: EnvBoolean.default(false),
591
937
  // OPENGENI_CODEX_CONNECTED_APPS_ENABLED
592
- codexProductSku: z.string().optional(),
938
+ codexProductSku: z2.string().optional(),
593
939
  // OPENGENI_CODEX_PRODUCT_SKU (X-OpenAI-Product-Sku, apps only)
594
940
  // Progressive MCP disclosure (Codex-CLI-style tool_search): on a codex turn,
595
941
  // flag non-eager selected MCP tools `defer_loading:true` (dropping their
@@ -613,10 +959,23 @@ var SettingsSchema = z.object({
613
959
  // Multi-account P3 (auto-rotation): an account is "near exhaustion" — ineligible to be
614
960
  // rotated TO — when EITHER usage window (5h/weekly) is at/over this percent. Default 90 to
615
961
  // match the UI danger flip (UsageBar danger at pct >= 90). OPENGENI_CODEX_ROTATION_NEAR_EXHAUSTION_PCT.
616
- codexRotationNearExhaustionPct: z.coerce.number().int().min(1).max(100).default(90),
962
+ codexRotationNearExhaustionPct: z2.coerce.number().int().min(1).max(100).default(90),
963
+ reasoningConfigurationUpdatesEnabled: EnvBoolean.default(false),
617
964
  openaiReasoningEffort: ReasoningEffort.default("low"),
618
- openaiAllowedReasoningEfforts: z.string().default("low,medium,high,xhigh,max"),
619
- openaiResponsesTransport: z.enum(["http", "websocket"]).default("http"),
965
+ openaiAllowedReasoningEfforts: z2.string().default("low,medium,high,xhigh,max"),
966
+ // Default for new chats and scheduled tasks when the workspace has an
967
+ // OpenGeni credit balance, no saved workspace default, and no usable
968
+ // connected subscription, and the deployment default is not already a
969
+ // credits-billed model. Selected only when this model is selectable in the
970
+ // workspace catalog; otherwise the first selectable credits model is used.
971
+ // OPENGENI_CREDITS_DEFAULT_MODEL / OPENGENI_CREDITS_DEFAULT_REASONING_EFFORT.
972
+ creditsDefaultModel: z2.string().trim().min(1).max(256).refine((value) => !/[\u000A\u000D|]/u.test(value), {
973
+ message: "credits default model must not contain newlines or the | field separator"
974
+ }).default("gpt-6-luna"),
975
+ // Preferred effort for the credits default. Clamped to the highest effort
976
+ // the selected model supports at or below this value.
977
+ creditsDefaultReasoningEffort: ReasoningEffort.default("xhigh"),
978
+ openaiResponsesTransport: z2.enum(["http", "websocket"]).default("http"),
620
979
  // Provider-assigned item ids (rs_/msg_/fc_…) in Responses API input are
621
980
  // resolved against the provider's server-side response store. That store is
622
981
  // not durable enough to anchor long runs on: a response that streamed fine
@@ -625,7 +984,7 @@ var SettingsSchema = z.object({
625
984
  // every model-call input so requests are self-contained — conversation
626
985
  // truth already lives client-side in session_history_items. "preserve"
627
986
  // keeps the SDK's pass-through behavior.
628
- openaiProviderItemIds: z.enum(["strip", "preserve"]).default("strip"),
987
+ openaiProviderItemIds: z2.enum(["strip", "preserve"]).default("strip"),
629
988
  // With ids stripped the provider cannot resolve prior reasoning server-side,
630
989
  // so request reasoning.encrypted_content and send it back with each call:
631
990
  // reasoning continuity without depending on provider-side storage.
@@ -633,7 +992,7 @@ var SettingsSchema = z.object({
633
992
  // Model-call retry budget for transient provider failures (429s and friends).
634
993
  // The openai client default of 2 retries is too small for sustained TPM
635
994
  // backpressure during long autonomous runs.
636
- openaiMaxRetries: z.coerce.number().int().nonnegative().default(5),
995
+ openaiMaxRetries: z2.coerce.number().int().nonnegative().default(5),
637
996
  // Native hosted web search. The live Azure Responses path executes the
638
997
  // hosted web_search tool, so this is provider-unconditional: ON by default
639
998
  // on every provider, exposed only so operators can disable it. When true,
@@ -641,6 +1000,19 @@ var SettingsSchema = z.object({
641
1000
  // merged with the MCP-server tools (getAllTools = [...mcpTools, ...tools])
642
1001
  // and the sandbox capability tools, never replacing them.
643
1002
  webSearchEnabled: EnvBoolean.default(true),
1003
+ // Jev (TypeSafe's fast judge model) for worker-side agent tools. Without a
1004
+ // usable key every Jev-backed feature is off. The key stays on the server
1005
+ // (API and worker) and never reaches a sandbox or Connected Machine.
1006
+ jevApiKey: z2.string().optional(),
1007
+ jevBaseUrl: z2.string().url().default("https://api.typesafe.ai"),
1008
+ jevModel: z2.string().trim().min(1).max(128).default("jev-latest"),
1009
+ jevRequestTimeoutMs: z2.coerce.number().int().positive().max(12e4).default(1e4),
1010
+ // Jev-backed `code_search` agent tool. `off` never offers it, `opt_in` offers
1011
+ // it only where workspace settings enable it, `default_on` offers it
1012
+ // everywhere except workspaces that disable it, and `experiment` gives it to
1013
+ // a fixed half of sessions in workspaces without their own setting, for
1014
+ // comparison. It also needs jevApiKey.
1015
+ codeSearchMode: z2.enum(["off", "opt_in", "default_on", "experiment"]).default("off"),
644
1016
  // Deployment-default agent persona template (the white-label surface). The
645
1017
  // runtime resolves the effective template per turn as
646
1018
  // per-session-override > per-workspace override > this default, substitutes
@@ -648,38 +1020,40 @@ var SettingsSchema = z.object({
648
1020
  // it when the template omits the marker), and uses the result as the agent's
649
1021
  // instructions. Defaulting to DEFAULT_AGENT_INSTRUCTIONS keeps the composed
650
1022
  // default pinned by runtime tests.
651
- agentInstructionsTemplate: z.string().default(DEFAULT_AGENT_INSTRUCTIONS),
652
- azureOpenaiBaseUrl: z.string().optional(),
653
- azureOpenaiEndpoint: z.string().optional(),
654
- azureOpenaiDeployment: z.string().optional(),
655
- azureOpenaiApiVersion: z.string().optional(),
656
- azureOpenaiApiKey: z.string().optional(),
657
- azureOpenaiAdToken: z.string().optional(),
1023
+ agentInstructionsTemplate: z2.string().default(DEFAULT_AGENT_INSTRUCTIONS),
1024
+ azureOpenaiBaseUrl: z2.string().optional(),
1025
+ azureOpenaiEndpoint: z2.string().optional(),
1026
+ azureOpenaiDeployment: z2.string().optional(),
1027
+ azureOpenaiApiVersion: z2.string().optional(),
1028
+ azureOpenaiApiKey: z2.string().optional(),
1029
+ azureOpenaiAdToken: z2.string().optional(),
658
1030
  disableOpenaiTracing: EnvBoolean.default(false),
659
1031
  sandboxBackend: SandboxBackend.default("docker"),
660
- dockerImage: z.string().default("opengeni-sandbox:local"),
1032
+ dockerImage: z2.string().default("opengeni-sandbox:local"),
661
1033
  // Explicit deployment contract: the configured base sandbox image contains
662
1034
  // the verified, self-contained native artifact runtime at its fixed image
663
1035
  // paths. Disabled by default so arbitrary/custom provider images never make
664
1036
  // document/spreadsheet/presentation skills appear when their runtime is
665
- // absent. Per-pack/per-rig image overrides fail closed in the worker even
666
1037
  // when this base-image contract is enabled.
667
1038
  sandboxArtifactRuntimeEnabled: EnvBoolean.default(false),
668
- dockerExposedPorts: z.string().default(""),
669
- dockerNetwork: z.string().optional(),
1039
+ dockerExposedPorts: z2.string().default(""),
1040
+ dockerNetwork: z2.string().optional(),
670
1041
  // When the worker itself runs in a container and talks to a host Docker daemon,
671
1042
  // this directory must be bind-mounted at the exact same absolute path on both
672
1043
  // sides. The Agents SDK materializes the workspace here before bind-mounting it
673
1044
  // into the sandbox container.
674
- dockerWorkspaceBaseDir: z.string().min(1).optional(),
675
- modalAppName: z.string().default("opengeni-sandbox"),
676
- modalImageRef: z.string().optional(),
1045
+ dockerWorkspaceBaseDir: z2.string().min(1).optional(),
1046
+ modalAppName: z2.string().default("opengeni-sandbox"),
1047
+ modalImageRef: z2.string().optional(),
1048
+ // Activate only after descriptor-aware readers, DB fences and the exact
1049
+ // native image have passed the supervised-command rollout canary.
1050
+ modalCommandSupervisionEnabled: EnvBoolean.default(false),
677
1051
  // Provider-native immutable Modal image ID for the exact logical
678
1052
  // `modalImageRef`. When set, the runtime uses ModalImageSelector.fromId and
679
1053
  // never asks Modal to parse or import the registry ref. The logical ref is
680
1054
  // still persisted on the sandbox lease for provenance and conflict fencing;
681
1055
  // the Modal session envelope persists the actual image ID.
682
- modalImageId: z.string().min(4).max(128).regex(/^im-[A-Za-z0-9]+$/).optional(),
1056
+ modalImageId: z2.string().min(4).max(128).regex(/^im-[A-Za-z0-9]+$/).optional(),
683
1057
  // Name of a Modal Secret (containing REGISTRY_USERNAME + REGISTRY_PASSWORD) used
684
1058
  // to authenticate the pull of `modalImageRef` from a PRIVATE registry. When UNSET
685
1059
  // (the default), the sandbox image is pulled UNAUTHENTICATED — i.e. it must be a
@@ -688,7 +1062,7 @@ var SettingsSchema = z.object({
688
1062
  // run a private image (e.g. a cloud-hosted ACR/ECR/GCR digest): the runtime resolves
689
1063
  // the named Secret and builds the image via `fromRegistry(tag, secret)` before the
690
1064
  // first sandbox is created. Knob: OPENGENI_MODAL_IMAGE_REGISTRY_SECRET.
691
- modalImageRegistrySecret: z.string().optional(),
1065
+ modalImageRegistrySecret: z2.string().optional(),
692
1066
  // Modal's hard sandbox lifetime (timeoutMs = this * 1000), counted from box
693
1067
  // creation. A resume-by-id does NOT reset that provider clock. It is the
694
1068
  // BACKSTOP that reclaims a box if the reaper/worker is down, NOT the warm-window
@@ -699,17 +1073,17 @@ var SettingsSchema = z.object({
699
1073
  // deadline-aware snapshot/rematerialization transition. The transition—not a
700
1074
  // larger timeout—is what lets a session outlive one finite provider box.
701
1075
  // Knob: OPENGENI_MODAL_TIMEOUT_SECONDS.
702
- modalTimeoutSeconds: z.coerce.number().int().positive().max(86400).default(86400),
1076
+ modalTimeoutSeconds: z2.coerce.number().int().positive().max(86400).default(86400),
703
1077
  // Optional provider reservations for every new Modal sandbox. CPU is measured
704
1078
  // in physical cores and may be fractional; memory is measured in MiB. Leave
705
1079
  // both unset to preserve Modal's provider defaults. The Agents adapter stores
706
1080
  // the resolved values in its session state so snapshot replacement and exact
707
1081
  // resume cannot silently change the reservation.
708
- modalSandboxCpu: z.coerce.number().positive().optional(),
709
- modalSandboxMemoryMiB: z.coerce.number().int().positive().optional(),
710
- modalTokenId: z.string().optional(),
711
- modalTokenSecret: z.string().optional(),
712
- modalEnvironment: z.string().optional(),
1082
+ modalSandboxCpu: z2.coerce.number().positive().optional(),
1083
+ modalSandboxMemoryMiB: z2.coerce.number().int().positive().optional(),
1084
+ modalTokenId: z2.string().optional(),
1085
+ modalTokenSecret: z2.string().optional(),
1086
+ modalEnvironment: z2.string().optional(),
713
1087
  // modal gap-fill: idleTimeoutMs + workspacePersistence were unmapped (module 03 §4.1).
714
1088
  //
715
1089
  // CRITICAL (sandbox-file-persistence): when this is UNSET the Modal SDK sends
@@ -727,7 +1101,7 @@ var SettingsSchema = z.object({
727
1101
  // explicitly (OPENGENI_MODAL_IDLE_TIMEOUT_SECONDS) only to deliberately idle-reap
728
1102
  // SOONER than the hard lifetime; the boot invariant forbids a value that would
729
1103
  // reap before reaperPeriod + idleGrace elapses.
730
- modalIdleTimeoutSeconds: z.coerce.number().int().positive().optional(),
1104
+ modalIdleTimeoutSeconds: z2.coerce.number().int().positive().optional(),
731
1105
  // /workspace FILE PERSISTENCE across warm/cold cycles. Directory snapshots
732
1106
  // preserve only the durable user workspace, so provider recovery does not
733
1107
  // restore an entire machine image or replace the selected rig/base image.
@@ -736,16 +1110,14 @@ var SettingsSchema = z.object({
736
1110
  // Modal creations only.
737
1111
  // `snapshot_filesystem` remains available for explicit compatibility and
738
1112
  // immutable rig-image materialization. `tar` is the portable fallback.
739
- modalWorkspacePersistence: z.enum(["tar", "snapshot_filesystem", "snapshot_directory"]).default("snapshot_directory"),
1113
+ modalWorkspacePersistence: z2.enum(["tar", "snapshot_filesystem", "snapshot_directory"]).default("snapshot_directory"),
740
1114
  // Shared desktop toggle: this module reads it for the 6080 port-merge; the
741
1115
  // owner module (P4.x) acts on it to launch the display stack.
742
1116
  sandboxDesktopEnabled: EnvBoolean.default(false),
743
- // Human take-control toggle: when ON (default) the negotiated DesktopStream
744
- // cell advertises mode "interactive" — the noVNC viewer can drive mouse+keyboard
745
- // into :0 (x11vnc runs without -viewonly). Turn it OFF for a genuinely read-only
746
- // deployment: the cell reports mode "read-only" and the client disables the
747
- // "Take control" affordance. This gates the HUMAN viewer plane; agent
748
- // interaction is authorized through managed ComputerSession tools.
1117
+ // Human sandbox input policy. Canonical ComputerSession attachments reflect
1118
+ // it and /actions enforces it independently of the client. The legacy
1119
+ // DesktopStream adapter also reports read-only when disabled. Agent tools
1120
+ // retain their separate session-control authority.
749
1121
  sandboxDesktopInteractive: EnvBoolean.default(true),
750
1122
  // REAL PTY terminal toggle (P5.t): gates the ttyd pty-ws plane (7681) the API
751
1123
  // mints over the SAME tunnel as the desktop. Defaults ON — the interactive
@@ -757,13 +1129,13 @@ var SettingsSchema = z.object({
757
1129
  // The desktop framebuffer geometry the pixel plane advertises + launches the
758
1130
  // display stack with (P4.2). v1 has no live RANDR resize; a change is a full
759
1131
  // down→up restart. Defaults match the proven spike geometry (1280x800).
760
- streamResolutionWidth: z.coerce.number().int().positive().default(1280),
761
- streamResolutionHeight: z.coerce.number().int().positive().default(800),
1132
+ streamResolutionWidth: z2.coerce.number().int().positive().default(1280),
1133
+ streamResolutionHeight: z2.coerce.number().int().positive().default(800),
762
1134
  // Recording loop: ffmpeg x11grab of :0 → mp4/webm → @opengeni/storage.
763
1135
  // recordingMaxBytes caps the in-memory finalize buffer (≤ storage single-PUT);
764
1136
  // recordingMaxSeconds is the ffmpeg -t hard ceiling (bounds a multi-day turn).
765
1137
  recordingEnabled: EnvBoolean.default(true),
766
- recordingDefaultCodec: z.enum(["h264-mp4", "vp9-webm"]).default("h264-mp4"),
1138
+ recordingDefaultCodec: z2.enum(["h264-mp4", "vp9-webm"]).default("h264-mp4"),
767
1139
  // Workbench v2 turn-end workspace capture. When on, the turn
768
1140
  // activity probes the box's changed files off the live box at turn end and
769
1141
  // persists a capture revision (blobs in @opengeni/storage) so the workbench
@@ -771,85 +1143,86 @@ var SettingsSchema = z.object({
771
1143
  // fully behind this flag: off ⇒ capture is skipped and reads fall back to the
772
1144
  // live/wake path (status-quo behavior). Default on; explicit per environment.
773
1145
  workspaceCaptureEnabled: EnvBoolean.default(true),
774
- recordingFramerate: z.coerce.number().int().positive().default(15),
775
- recordingMaxSeconds: z.coerce.number().int().positive().default(600),
776
- recordingMaxBytes: z.coerce.number().int().positive().default(268435456),
1146
+ recordingFramerate: z2.coerce.number().int().positive().default(15),
1147
+ recordingMaxSeconds: z2.coerce.number().int().positive().default(600),
1148
+ recordingMaxBytes: z2.coerce.number().int().positive().default(268435456),
777
1149
  // 256 MB
778
1150
  // --- daytona ---
779
- daytonaApiKey: z.string().optional(),
780
- daytonaApiUrl: z.string().url().optional(),
781
- daytonaTarget: z.string().optional(),
782
- daytonaImage: z.string().optional(),
783
- daytonaSnapshotName: z.string().optional(),
784
- daytonaAutoStopInterval: z.coerce.number().int().nonnegative().optional(),
1151
+ daytonaApiKey: z2.string().optional(),
1152
+ daytonaApiUrl: z2.string().url().optional(),
1153
+ daytonaTarget: z2.string().optional(),
1154
+ daytonaImage: z2.string().optional(),
1155
+ daytonaSnapshotName: z2.string().optional(),
1156
+ daytonaAutoStopInterval: z2.coerce.number().int().nonnegative().optional(),
785
1157
  // 0 disables idle-kill
786
- daytonaTimeoutSeconds: z.coerce.number().int().positive().optional(),
787
- daytonaExposedPortUrlTtlSeconds: z.coerce.number().int().positive().optional(),
1158
+ daytonaTimeoutSeconds: z2.coerce.number().int().positive().optional(),
1159
+ daytonaExposedPortUrlTtlSeconds: z2.coerce.number().int().positive().optional(),
788
1160
  // --- runloop ---
789
- runloopApiKey: z.string().optional(),
790
- runloopBaseUrl: z.string().url().optional(),
791
- runloopBlueprintName: z.string().optional(),
792
- runloopBlueprintId: z.string().optional(),
1161
+ runloopApiKey: z2.string().optional(),
1162
+ runloopBaseUrl: z2.string().url().optional(),
1163
+ runloopBlueprintName: z2.string().optional(),
1164
+ runloopBlueprintId: z2.string().optional(),
793
1165
  runloopTunnel: EnvBoolean.default(true),
794
- runloopKeepAliveSeconds: z.coerce.number().int().positive().optional(),
1166
+ runloopKeepAliveSeconds: z2.coerce.number().int().positive().optional(),
795
1167
  // --- e2b (SDK reads E2B_API_KEY from env; mirrored for validation + forwarding) ---
796
- e2bApiKey: z.string().optional(),
797
- e2bTemplate: z.string().optional(),
798
- e2bTimeoutSeconds: z.coerce.number().int().positive().optional(),
799
- e2bTimeoutAction: z.enum(["pause", "kill"]).optional(),
1168
+ e2bApiKey: z2.string().optional(),
1169
+ e2bTemplate: z2.string().optional(),
1170
+ e2bTimeoutSeconds: z2.coerce.number().int().positive().optional(),
1171
+ e2bTimeoutAction: z2.enum(["pause", "kill"]).optional(),
800
1172
  e2bAllowInternetAccess: EnvBoolean.optional(),
801
1173
  e2bAutoResume: EnvBoolean.optional(),
802
- e2bWorkspacePersistence: z.enum(["tar", "snapshot"]).optional(),
1174
+ e2bWorkspacePersistence: z2.enum(["tar", "snapshot"]).optional(),
803
1175
  // --- blaxel ---
804
- blaxelApiKey: z.string().optional(),
805
- blaxelImage: z.string().optional(),
806
- blaxelRegion: z.string().optional(),
1176
+ blaxelApiKey: z2.string().optional(),
1177
+ blaxelImage: z2.string().optional(),
1178
+ blaxelRegion: z2.string().optional(),
807
1179
  blaxelExposedPortPublic: EnvBoolean.optional(),
808
1180
  // public vs bl_preview_token
809
- blaxelExposedPortUrlTtlSeconds: z.coerce.number().int().positive().optional(),
810
- blaxelMemoryMb: z.coerce.number().int().positive().optional(),
811
- blaxelTtl: z.string().optional(),
1181
+ blaxelExposedPortUrlTtlSeconds: z2.coerce.number().int().positive().optional(),
1182
+ blaxelMemoryMb: z2.coerce.number().int().positive().optional(),
1183
+ blaxelTtl: z2.string().optional(),
812
1184
  // --- cloudflare (headless) ---
813
- cloudflareWorkerUrl: z.string().url().optional(),
814
- cloudflareApiKey: z.string().optional(),
1185
+ cloudflareWorkerUrl: z2.string().url().optional(),
1186
+ cloudflareApiKey: z2.string().optional(),
1187
+ experimentalBrowserContextPoolEnabled: EnvBoolean.default(false),
815
1188
  // --- remote browser placements ---
816
1189
  // Provider credentials are injected only into the placement-resident
817
1190
  // browserd launch. They never enter session contracts, journals, or sandboxes.
818
- browserbaseApiKey: z.string().min(1).max(8192).optional(),
819
- kernelApiKey: z.string().min(1).max(8192).optional(),
820
- kernelEndpoint: z.string().url().optional(),
821
- kernelBrowserTimeoutSeconds: z.coerce.number().int().positive().max(86400).default(3600),
1191
+ browserbaseApiKey: z2.string().min(1).max(8192).optional(),
1192
+ kernelApiKey: z2.string().min(1).max(8192).optional(),
1193
+ kernelEndpoint: z2.string().url().optional(),
1194
+ kernelBrowserTimeoutSeconds: z2.coerce.number().int().positive().max(86400).default(3600),
822
1195
  kernelBrowserStealth: EnvBoolean.default(false),
823
1196
  // --- vercel (headless) ---
824
- vercelToken: z.string().optional(),
825
- vercelProjectId: z.string().optional(),
826
- vercelTeamId: z.string().optional(),
827
- vercelRuntime: z.string().optional(),
1197
+ vercelToken: z2.string().optional(),
1198
+ vercelProjectId: z2.string().optional(),
1199
+ vercelTeamId: z2.string().optional(),
1200
+ vercelRuntime: z2.string().optional(),
828
1201
  // --- OpenSandbox (optional Kubernetes-native provisioned sandbox) ---
829
- openSandboxBaseUrl: z.string().url().optional(),
830
- openSandboxApiKey: z.string().min(1).optional(),
1202
+ openSandboxBaseUrl: z2.string().url().optional(),
1203
+ openSandboxApiKey: z2.string().min(1).optional(),
831
1204
  // Release and preview profiles must provide an immutable OCI digest. The
832
1205
  // adapter refuses tag-only references when this backend is active.
833
- openSandboxImage: z.string().min(1).optional(),
1206
+ openSandboxImage: z2.string().min(1).optional(),
834
1207
  // Renewable provider TTL is a leak/backstop clock, not OpenGeni's idle
835
1208
  // policy. The pinned server accepts a one-minute minimum; ordinary
836
1209
  // deployments default to one hour.
837
- openSandboxTtlSeconds: z.coerce.number().int().min(60).max(86400).default(3600),
1210
+ openSandboxTtlSeconds: z2.coerce.number().int().min(60).max(86400).default(3600),
838
1211
  openSandboxUseServerProxy: EnvBoolean.default(true),
839
1212
  // Channel B (browserd / noVNC / ttyd) uses OSEP-0011 signed URI-mode ingress.
840
1213
  // Exec/files stay on the private lifecycle server-proxy regardless of this flag.
841
1214
  openSandboxSignedEndpoints: EnvBoolean.default(false),
842
- openSandboxSignedEndpointTtlSeconds: z.coerce.number().int().min(60).max(3600).default(600),
843
- openSandboxChannelBPublicBaseUrl: z.string().url().optional(),
1215
+ openSandboxSignedEndpointTtlSeconds: z2.coerce.number().int().min(60).max(3600).default(600),
1216
+ openSandboxChannelBPublicBaseUrl: z2.string().url().optional(),
844
1217
  // Emergency hatch only: force JPEG/RFB through the API frame-proxy even when
845
1218
  // signed endpoints are on (M2 subprotocol failure). Unset means OpenSandbox
846
1219
  // uses the frame-proxy unless signed endpoints are on.
847
1220
  openSandboxInteractionFrameProxy: EnvBoolean.optional(),
848
- openSandboxPoolRef: z.string().regex(/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/).optional(),
1221
+ openSandboxPoolRef: z2.string().regex(/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/).optional(),
849
1222
  // Optional same-cluster, read-only observability projection. The application
850
1223
  // chart sets this only on the control worker and mounts a dedicated projected
851
1224
  // service-account token; non-Kubernetes and remote-provider deployments omit it.
852
- openSandboxKubernetesInventoryNamespace: z.string().min(1).max(63).regex(/^[a-z0-9](?:[-a-z0-9]*[a-z0-9])?$/).optional(),
1225
+ openSandboxKubernetesInventoryNamespace: z2.string().min(1).max(63).regex(/^[a-z0-9](?:[-a-z0-9]*[a-z0-9])?$/).optional(),
853
1226
  // --- sandbox ownership inversion (P1.2 rollout flag, default OFF) ---
854
1227
  // The keystone flag for the stateless resume-by-id model. When FALSE the
855
1228
  // agent-turn path is BYTE-FOR-BYTE today's build-and-discard behavior (no
@@ -903,13 +1276,13 @@ var SettingsSchema = z.object({
903
1276
  // when ABSENT and sandboxSelfhostedEnabled is on, the poll route reports the
904
1277
  // credential plane disabled (graceful degrade, mirrors streamTokenSecret). NEVER
905
1278
  // logged. Lives in the opengeni-runtime secret (Helm-clobbered configmap avoided).
906
- enrollmentSigningSecret: z.string().optional(),
1279
+ enrollmentSigningSecret: z2.string().optional(),
907
1280
  // Connect-info the EnrollmentCredentials hand the agent: the NATS server URL(s)
908
1281
  // the agent dials for the control plane, and the relay edge base URL for streams.
909
1282
  // The per-workspace NATS Account creds binding is infra-deferred (M4/relay
910
1283
  // milestone) — the poll returns these endpoints + a placeholder creds field.
911
- selfhostedNatsUrl: z.string().optional(),
912
- selfhostedRelayUrl: z.string().optional(),
1284
+ selfhostedNatsUrl: z2.string().optional(),
1285
+ selfhostedRelayUrl: z2.string().optional(),
913
1286
  // The HMAC secret the control plane signs the agent's relay PRODUCER token with
914
1287
  // (the `ogr_` envelope threaded into EnrollmentCredentials.relayToken; M8b/design
915
1288
  // §10.5). The relay verifies the producer token with the SAME secret. Optional:
@@ -917,10 +1290,10 @@ var SettingsSchema = z.object({
917
1290
  // plane is simply unavailable until configured). Falls back to streamTokenSecret /
918
1291
  // delegationSecret (same HMAC family) so a deployment with a stream-token secret
919
1292
  // needs no second one. NEVER logged. Lives in the opengeni-runtime secret.
920
- selfhostedRelayTokenSecret: z.string().optional(),
1293
+ selfhostedRelayTokenSecret: z2.string().optional(),
921
1294
  // The minisign PUBLIC key the agent pins for self-update verification (handed to
922
1295
  // the agent in EnrollmentCredentials; the SECRET key lives only in CI).
923
- agentUpdatePublicKey: z.string().optional(),
1296
+ agentUpdatePublicKey: z2.string().optional(),
924
1297
  // --- NATS auth-callout tenancy boundary (bring-your-own-compute M-AUTH; design
925
1298
  // §10.1 NATS Accounts per workspace + §17 the isolation smoke) -------------
926
1299
  // nats-server is configured with AUTH CALLOUT: an external agent connects
@@ -937,24 +1310,24 @@ var SettingsSchema = z.object({
937
1310
  // The callout account SIGNING SEED (`SA...`). Both the user JWT and the
938
1311
  // authorization-response JWT are signed by this account key; its public key
939
1312
  // (`A...`) is the `auth_callout.issuer` in the server config. NEVER logged.
940
- selfhostedNatsCalloutAccountSeed: z.string().optional(),
1313
+ selfhostedNatsCalloutAccountSeed: z2.string().optional(),
941
1314
  // The TARGET ACCOUNT NAME the minted user is placed into (the server-config-mode
942
1315
  // `auth_callout.account`, e.g. "APP"). The responder writes it as the minted user
943
1316
  // JWT `aud` so nats-server binds the agent to this account — the SAME account the
944
1317
  // privileged control plane connects into, so exact process request/reply
945
1318
  // routes. Optional; resolveNatsCalloutConfig defaults it to "APP".
946
- selfhostedNatsCalloutAccountName: z.string().optional(),
1319
+ selfhostedNatsCalloutAccountName: z2.string().optional(),
947
1320
  // The callout RESPONDER's own NATS login (one of the `auth_callout.auth_users`
948
1321
  // in the AUTH account) — the responder connects with this to subscribe
949
1322
  // $SYS.REQ.USER.AUTH. Username/password.
950
- selfhostedNatsCalloutUser: z.string().optional(),
951
- selfhostedNatsCalloutPassword: z.string().optional(),
1323
+ selfhostedNatsCalloutUser: z2.string().optional(),
1324
+ selfhostedNatsCalloutPassword: z2.string().optional(),
952
1325
  // The PRIVILEGED control-plane login (api/worker): a static account user that may
953
1326
  // request exact process RPC subjects + receive their inbox replies. The event bus + the
954
1327
  // selfhosted control RPC ride THIS connection. Username/password; when unset the
955
1328
  // bus connects anonymously (local dev / a NATS with no auth_callout).
956
- selfhostedNatsControlUser: z.string().optional(),
957
- selfhostedNatsControlPassword: z.string().optional(),
1329
+ selfhostedNatsControlUser: z2.string().optional(),
1330
+ selfhostedNatsControlPassword: z2.string().optional(),
958
1331
  // --- selfhosted (Connected Machine) control/exec op deadlines ---------------
959
1332
  // CONTROL ops (ping / fs / git / desktop / pty) keep a short request timeout so
960
1333
  // liveness failures surface promptly. EXEC duration is a different concern: by
@@ -964,8 +1337,8 @@ var SettingsSchema = z.object({
964
1337
  // process deadline by setting a positive value; 0 never schedules a process kill.
965
1338
  // Knobs: OPENGENI_SANDBOX_SELFHOSTED_EXEC_TIMEOUT_MS (default 0 = none) and
966
1339
  // OPENGENI_SANDBOX_SELFHOSTED_CONTROL_TIMEOUT_MS (default 30s).
967
- sandboxSelfhostedExecTimeoutMs: z.coerce.number().int().nonnegative().default(0),
968
- sandboxSelfhostedControlTimeoutMs: z.coerce.number().int().positive().default(3e4),
1340
+ sandboxSelfhostedExecTimeoutMs: z2.coerce.number().int().nonnegative().default(0),
1341
+ sandboxSelfhostedControlTimeoutMs: z2.coerce.number().int().positive().default(3e4),
969
1342
  // --- sandbox lease cadences (cadence invariant validated at boot below) ---
970
1343
  // reaperPeriod < viewerHolderTTL, and reaperPeriod + idleGrace < the EFFECTIVE
971
1344
  // box idle timeout (effectiveModalIdleTimeoutSeconds, which defaults to the hard
@@ -973,12 +1346,12 @@ var SettingsSchema = z.object({
973
1346
  // idle timeout — which we pin high enough (via the idle-timeout default) that
974
1347
  // OpenGeni's reaper, not Modal's idle-reap, governs teardown so /workspace is
975
1348
  // snapshotted before the box dies (sandbox-file-persistence).
976
- sandboxLeaseReaperPeriodMs: z.coerce.number().int().positive().default(3e4),
977
- sandboxViewerHolderTtlMs: z.coerce.number().int().positive().default(9e4),
1349
+ sandboxLeaseReaperPeriodMs: z2.coerce.number().int().positive().default(3e4),
1350
+ sandboxViewerHolderTtlMs: z2.coerce.number().int().positive().default(9e4),
978
1351
  // A BrowserSession controller refreshes its durable resource and exact
979
1352
  // interaction lease holder together. This longer crash horizon tolerates API
980
1353
  // replacement while still releasing a placement whose controller died.
981
- sandboxInteractionHolderTtlMs: z.coerce.number().int().positive().default(18e4),
1354
+ sandboxInteractionHolderTtlMs: z2.coerce.number().int().positive().default(18e4),
982
1355
  // The DRAIN grace: how long a refcount-0 (draining) lease stays WARM before the
983
1356
  // reaper resume-by-ids the box and terminates it. This is the cost-vs-snappiness
984
1357
  // dial — when the user navigates away the box keeps refcount 0, but it survives
@@ -988,7 +1361,29 @@ var SettingsSchema = z.object({
988
1361
  // fresh EMPTY box; lower it to trade warm cost for a snappier reclaim.
989
1362
  // getSettings caps the default at half a shorter configured Modal lifetime so
990
1363
  // the entire reaper window always fits. Knob: OPENGENI_SANDBOX_IDLE_GRACE_MS.
991
- sandboxIdleGraceMs: z.coerce.number().int().positive().default(9e5),
1364
+ sandboxIdleGraceMs: z2.coerce.number().int().positive().default(9e5),
1365
+ // Idle command containment. A legacy retained background command (a dev
1366
+ // server, a command whose output is still draining, a stopped command the
1367
+ // provider no longer answers for) keeps its box warm through a non-expiring
1368
+ // process holder, so the zero-holder drain never runs and the box would stay
1369
+ // up until the provider deadline kills it uncaptured. Once every session of
1370
+ // the sandbox group has been unused this long - no open turn or pending
1371
+ // request, no held wait_for_input, no other holder or writer, measured from
1372
+ // durable turn/holder/admission facts - the reaper checkpoints the workspace,
1373
+ // stops the box and settles those commands `lost` with reason
1374
+ // `idle_containment`. Default 30min: twice the default
1375
+ // idle grace, so a lease that is only waiting for a "glanced away" user is
1376
+ // never contained earlier than an idle lease would drain, and well inside
1377
+ // the 1h provider-deadline rotation lead, so an idle box is saved long before
1378
+ // the deadline path has to act. Set 0 to disable new idle enrollments without
1379
+ // disabling provider-deadline containment or cancelling an enrolled drain.
1380
+ // A positive window must exceed OPENGENI_SANDBOX_IDLE_GRACE_MS;
1381
+ // an explicit positive value must also stay below OPENGENI_SANDBOX_ROTATION_LEAD_MS,
1382
+ // and with an explicit OPENGENI_MODAL_IDLE_TIMEOUT_SECONDS the reaper period
1383
+ // plus this window plus the drain capture budget must fit before it.
1384
+ // getSettings derives the unset default between those two for short-lived
1385
+ // provider lifetimes. Knob: OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS.
1386
+ sandboxIdleCommandContainmentMs: z2.coerce.number().int().nonnegative().optional().transform((value) => value === 0 ? void 0 : value),
992
1387
  // MID-SESSION /workspace snapshot cadence (sandbox-file-persistence). The
993
1388
  // reaper's drain-persist only protects boxes the reaper itself kills; a box
994
1389
  // that dies any other way (Modal's hard creation-time timeout on a session
@@ -998,20 +1393,20 @@ var SettingsSchema = z.object({
998
1393
  // one (same epoch-fenced fold-onto-lease seam as the drain), bounding the
999
1394
  // worst-case loss of ANY unclean box death to this window. 0 disables.
1000
1395
  // Knob: OPENGENI_SANDBOX_SNAPSHOT_INTERVAL_MS. Default 15min.
1001
- sandboxSnapshotIntervalMs: z.coerce.number().int().min(0).default(9e5),
1396
+ sandboxSnapshotIntervalMs: z2.coerce.number().int().min(0).default(9e5),
1002
1397
  // Maximum time a best-effort /workspace snapshot capture may hold turn/reaper
1003
1398
  // cleanup. A hung provider snapshot must never pin a lease holder, block
1004
1399
  // graceful shutdown, or become permission to GC an older archive. Timeout is
1005
1400
  // treated exactly like a failed best-effort snapshot. Knob:
1006
1401
  // OPENGENI_SANDBOX_SNAPSHOT_TIMEOUT_MS. Default 60s.
1007
- sandboxSnapshotTimeoutMs: z.coerce.number().int().positive().max(SANDBOX_SNAPSHOT_MAX_TIMEOUT_MS).default(6e4),
1402
+ sandboxSnapshotTimeoutMs: z2.coerce.number().int().positive().max(SANDBOX_SNAPSHOT_MAX_TIMEOUT_MS).default(6e4),
1008
1403
  // A zero-holder drain may need substantially longer than a best-effort
1009
1404
  // mid-turn/turn-end snapshot for a very large workspace. Keep that provider
1010
1405
  // budget independent so increasing drain recovery headroom cannot pin an
1011
1406
  // ordinary turn finalizer for the same duration. Unset preserves the legacy
1012
1407
  // single-budget behavior. Knob:
1013
1408
  // OPENGENI_SANDBOX_DRAIN_SNAPSHOT_TIMEOUT_MS.
1014
- sandboxDrainSnapshotTimeoutMs: z.coerce.number().int().positive().max(SANDBOX_SNAPSHOT_MAX_TIMEOUT_MS).optional(),
1409
+ sandboxDrainSnapshotTimeoutMs: z2.coerce.number().int().positive().max(SANDBOX_SNAPSHOT_MAX_TIMEOUT_MS).optional(),
1015
1410
  // Begin a controlled snapshot/quiesce/drain/rematerialize transition this far
1016
1411
  // ahead of a finite provider deadline. Modal's 24h creation clock cannot be
1017
1412
  // extended; the logical sandbox outlives it by moving to one successor box.
@@ -1020,22 +1415,22 @@ var SettingsSchema = z.object({
1020
1415
  // an extra coupled environment override. An explicit value may be larger when
1021
1416
  // an operator deliberately wants more rotation headroom; the boot invariant
1022
1417
  // still requires it to remain below the provider lifetime.
1023
- sandboxRotationLeadMs: z.coerce.number().int().positive().default(36e5),
1418
+ sandboxRotationLeadMs: z2.coerce.number().int().positive().default(36e5),
1024
1419
  // Bound provider-deadline rotation admission independently of execution.
1025
1420
  // Every admitted box receives its own durable drain child; the control worker
1026
1421
  // limits provider I/O to 32 concurrent activities. Matching that bound avoids
1027
1422
  // both the old one-box-per-tick deadline backlog and an unbounded provider/API
1028
1423
  // burst. Operators may tune this for a differently-sized worker pool.
1029
- sandboxRotationBatchSize: z.coerce.number().int().positive().max(500).default(32),
1424
+ sandboxRotationBatchSize: z2.coerce.number().int().positive().max(500).default(32),
1030
1425
  // expires_at refresh window for a held lease (>> the turn 10s heartbeat so a
1031
1426
  // single missed heartbeat never TTL-reaps a live turn). The warming TTL is the
1032
1427
  // window a cold->warming spawner has to commit warm before a reaper resets it.
1033
- sandboxLeaseTtlMs: z.coerce.number().int().positive().default(9e4),
1034
- sandboxLeaseWarmingTtlMs: z.coerce.number().int().positive().default(12e4),
1428
+ sandboxLeaseTtlMs: z2.coerce.number().int().positive().default(9e4),
1429
+ sandboxLeaseWarmingTtlMs: z2.coerce.number().int().positive().default(12e4),
1035
1430
  // Overall user-facing budget for warming a sandbox lease. Unlike the lease TTL
1036
1431
  // (a liveness/reaper cadence), this bounds how long one turn waits for capacity
1037
1432
  // or provider creation before surfacing a clear turn.failed error.
1038
- sandboxWarmingTimeoutMs: z.coerce.number().int().positive().default(6e5),
1433
+ sandboxWarmingTimeoutMs: z2.coerce.number().int().positive().default(6e5),
1039
1434
  // Request-scoped workspace control-prefix budget: how long one HTTP-originated
1040
1435
  // session/workspace mutation (Send, Steer, Pause/Resume/Cancel, queue
1041
1436
  // move/edit/delete, composer draft, settings narrowing, quiescent tree
@@ -1044,114 +1439,132 @@ var SettingsSchema = z.object({
1044
1439
  // settlement and claims never use it. The API installs the validated value
1045
1440
  // into @opengeni/db once at app construction; nothing reads the env per
1046
1441
  // request. Env: OPENGENI_WORKSPACE_CONTROL_LOCK_TIMEOUT_MS. Default 20 s.
1047
- workspaceControlLockTimeoutMs: z.coerce.number({
1442
+ workspaceControlLockTimeoutMs: z2.coerce.number({
1048
1443
  message: "OPENGENI_WORKSPACE_CONTROL_LOCK_TIMEOUT_MS must be a positive integer (ms)"
1049
1444
  }).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),
1050
1445
  // Rig setup-script budget (M3): the wall-clock timeout the rig-setup lifecycle
1051
1446
  // hook runs its script under, distinct from the 120s per-command lifecycle
1052
1447
  // default (a rig may compile/install heavy tooling on first cold create).
1053
1448
  // Env: OPENGENI_RIG_SETUP_TIMEOUT_MS. Default 10min.
1054
- rigSetupTimeoutMs: z.coerce.number().int().positive().default(6e5),
1449
+ rigSetupTimeoutMs: z2.coerce.number().int().positive().default(6e5),
1055
1450
  // --- sandbox warm-time billing (P2.1) ---
1056
1451
  // Per-backend warm rate (usd_micros/sec), like modelPricingJson: an empty {}
1057
1452
  // means warm-cost is not debited (warm-seconds are still metered for audit).
1058
1453
  // Shape: { "modal": 5, "runloop": 4, ... }. Backends absent here meter
1059
1454
  // warm-seconds but accrue NO warm_cost / debit (rate 0).
1060
- sandboxWarmRateMicrosPerSecondJson: z.string().default("{}"),
1455
+ sandboxWarmRateMicrosPerSecondJson: z2.string().default("{}"),
1456
+ sandboxWarmBillingMode: z2.enum(["usage_only", "shadow", "credits"]).default("usage_only"),
1061
1457
  // Per-workspace warm cap (cumulative warm-seconds since the start of the UTC
1062
1458
  // month, summed over sandbox.warm_seconds). 0 = unbounded. A workspace over the
1063
1459
  // cap force-drains its VIEWER-ONLY boxes (guarded AND turn_holders=0 — a paying
1064
1460
  // turn is never killed); the reaper then stop()s at refcount 0.
1065
- sandboxMaxWarmSecondsPerWorkspace: z.coerce.number().int().nonnegative().default(0),
1066
- sandboxPreparationProfiles: z.string().default("none"),
1067
- sandboxEnvAllowlist: z.string().default(""),
1068
- objectStorageEndpoint: z.string().url().optional(),
1069
- objectStorageInternalEndpoint: z.string().url().optional(),
1070
- objectStorageSandboxEndpoint: z.string().url().optional(),
1071
- objectStorageBackend: z.enum(["s3-compatible", "aws-s3", "azure-blob", "gcs"]).default("s3-compatible"),
1072
- objectStorageBucket: z.string().min(1).default("opengeni-files"),
1073
- objectStorageRegion: z.string().min(1).default("us-east-1"),
1074
- objectStorageS3Provider: z.string().min(1).default("Minio"),
1075
- objectStorageAccessKeyId: z.string().optional(),
1076
- objectStorageSecretAccessKey: z.string().optional(),
1461
+ sandboxMaxWarmSecondsPerWorkspace: z2.coerce.number().int().nonnegative().default(0),
1462
+ sandboxPreparationProfiles: z2.string().default("none"),
1463
+ sandboxEnvAllowlist: z2.string().default(""),
1464
+ // Comma-separated image references a workspace may select as its default
1465
+ // sandbox image. Empty keeps every workspace on the deployment image.
1466
+ sandboxImageAllowlist: z2.string().default(""),
1467
+ objectStorageEndpoint: z2.string().url().optional(),
1468
+ objectStorageInternalEndpoint: z2.string().url().optional(),
1469
+ objectStorageSandboxEndpoint: z2.string().url().optional(),
1470
+ objectStorageBackend: z2.enum(["s3-compatible", "aws-s3", "azure-blob", "gcs"]).default("s3-compatible"),
1471
+ objectStorageBucket: z2.string().min(1).default("opengeni-files"),
1472
+ objectStorageRegion: z2.string().min(1).default("us-east-1"),
1473
+ objectStorageS3Provider: z2.string().min(1).default("Minio"),
1474
+ objectStorageAccessKeyId: z2.string().optional(),
1475
+ objectStorageSecretAccessKey: z2.string().optional(),
1077
1476
  objectStorageForcePathStyle: EnvBoolean.default(true),
1078
- objectStorageAzureConnectionString: z.string().optional(),
1079
- objectStorageAzureAccountName: z.string().optional(),
1080
- objectStorageAzureAccountKey: z.string().optional(),
1081
- objectStorageAzureEndpoint: z.string().url().optional(),
1082
- objectStorageGcsProjectId: z.string().optional(),
1083
- objectStorageGcsCredentialsJson: z.string().optional(),
1084
- objectStorageGcsKeyFilename: z.string().optional(),
1085
- objectStorageGcsApiEndpoint: z.string().url().optional(),
1086
- documentParser: z.string().min(1).default("liteparse"),
1087
- documentChunkSize: z.coerce.number().int().positive().default(1200),
1088
- documentChunkOverlap: z.coerce.number().int().nonnegative().default(160),
1089
- documentEmbeddingProvider: z.enum(["openai", "deterministic"]).default("openai"),
1090
- documentEmbeddingModel: z.string().min(1).default("text-embedding-3-large"),
1091
- documentEmbeddingDimensions: z.coerce.number().int().positive().default(3072),
1092
- documentEmbeddingApiKey: z.string().optional(),
1093
- documentEmbeddingBaseUrl: z.string().url().optional(),
1094
- documentCurationProvider: z.enum(["openai", "heuristic", "none"]).default("openai"),
1095
- documentCurationModel: z.string().min(1).default("gpt-4o-mini"),
1096
- documentCurationApiKey: z.string().optional(),
1097
- documentCurationBaseUrl: z.string().url().optional(),
1098
- gitAuthorName: z.string().optional(),
1099
- gitAuthorEmail: z.string().optional(),
1100
- gitCommitterName: z.string().optional(),
1101
- gitCommitterEmail: z.string().optional(),
1102
- githubAppManifestBaseUrl: z.string().optional(),
1103
- githubAppManifestStateSecret: z.string().optional(),
1104
- githubAppId: z.string().optional(),
1105
- githubClientId: z.string().optional(),
1106
- githubClientSecret: z.string().optional(),
1477
+ objectStorageAzureConnectionString: z2.string().optional(),
1478
+ objectStorageAzureAccountName: z2.string().optional(),
1479
+ objectStorageAzureAccountKey: z2.string().optional(),
1480
+ objectStorageAzureEndpoint: z2.string().url().optional(),
1481
+ objectStorageGcsProjectId: z2.string().optional(),
1482
+ objectStorageGcsCredentialsJson: z2.string().optional(),
1483
+ objectStorageGcsKeyFilename: z2.string().optional(),
1484
+ objectStorageGcsApiEndpoint: z2.string().url().optional(),
1485
+ documentParser: z2.string().min(1).default("liteparse"),
1486
+ documentChunkSize: z2.coerce.number().int().positive().default(1200),
1487
+ documentChunkOverlap: z2.coerce.number().int().nonnegative().default(160),
1488
+ documentEmbeddingProvider: z2.enum(["openai", "deterministic"]).default("openai"),
1489
+ documentEmbeddingModel: z2.string().min(1).default("text-embedding-3-large"),
1490
+ documentEmbeddingDimensions: z2.coerce.number().int().positive().default(3072),
1491
+ documentEmbeddingApiKey: z2.string().optional(),
1492
+ documentEmbeddingBaseUrl: z2.string().url().optional(),
1493
+ documentEmbeddingBillingMode: z2.enum(["usage_only", "shadow", "credits"]).default("usage_only"),
1494
+ // Explicit commercial cutover. Existing queued revisions remain unpriced;
1495
+ // only jobs created at or after this instant may enter the paid rail.
1496
+ documentEmbeddingCreditsActivatedAt: z2.iso.datetime().optional(),
1497
+ // Customer tariff for the exact UTF-8 bytes sent to the embedder. Zero leaves
1498
+ // the paid mode unavailable; no commercial rate is selected by this PR.
1499
+ documentEmbeddingRateMicrosPerMillionBytes: z2.coerce.number().int().nonnegative().default(0),
1500
+ documentCurationProvider: z2.enum(["openai", "heuristic", "none"]).default("openai"),
1501
+ documentCurationModel: z2.string().min(1).default("gpt-4o-mini"),
1502
+ documentCurationApiKey: z2.string().optional(),
1503
+ documentCurationBaseUrl: z2.string().url().optional(),
1504
+ gitAuthorName: z2.string().optional(),
1505
+ gitAuthorEmail: z2.string().optional(),
1506
+ gitCommitterName: z2.string().optional(),
1507
+ gitCommitterEmail: z2.string().optional(),
1508
+ githubAppManifestBaseUrl: z2.string().optional(),
1509
+ githubAppManifestStateSecret: z2.string().optional(),
1510
+ githubAppId: z2.string().optional(),
1511
+ githubClientId: z2.string().optional(),
1512
+ githubClientSecret: z2.string().optional(),
1107
1513
  /** Default-off rollout for the in-process GitHub repository API tool surface. */
1108
1514
  githubRestMcpEnabled: EnvBoolean.default(false),
1109
1515
  githubPersonalOauthEnabled: EnvBoolean.default(false),
1110
- githubPersonalOauthClientId: z.string().optional(),
1111
- githubPersonalOauthClientSecret: z.string().optional(),
1112
- githubAppSlug: z.string().optional(),
1113
- githubWebhookSecret: z.string().optional(),
1114
- githubAppPrivateKey: z.string().optional(),
1115
- prReviewGithubAppId: z.string().optional(),
1116
- prReviewGithubClientId: z.string().optional(),
1117
- prReviewGithubClientSecret: z.string().optional(),
1118
- prReviewGithubAppSlug: z.string().optional(),
1119
- prReviewGithubWebhookSecret: z.string().optional(),
1120
- prReviewGithubAppPrivateKey: z.string().optional(),
1121
- betterAuthSecret: z.string().optional(),
1122
- betterAuthAllowedHosts: z.string().default(""),
1123
- betterAuthCookieDomain: z.string().optional(),
1124
- betterAuthTrustedOrigins: z.string().default(""),
1125
- managedAuthGoogleClientId: z.string().optional(),
1126
- managedAuthGoogleClientSecret: z.string().optional(),
1127
- managedAuthGithubClientId: z.string().optional(),
1128
- managedAuthGithubClientSecret: z.string().optional(),
1516
+ githubPersonalOauthClientId: z2.string().optional(),
1517
+ githubPersonalOauthClientSecret: z2.string().optional(),
1518
+ githubAppSlug: z2.string().optional(),
1519
+ githubWebhookSecret: z2.string().optional(),
1520
+ githubAppPrivateKey: z2.string().optional(),
1521
+ prReviewGithubAppId: z2.string().optional(),
1522
+ prReviewGithubClientId: z2.string().optional(),
1523
+ prReviewGithubClientSecret: z2.string().optional(),
1524
+ prReviewGithubAppSlug: z2.string().optional(),
1525
+ prReviewGithubWebhookSecret: z2.string().optional(),
1526
+ prReviewGithubAppPrivateKey: z2.string().optional(),
1527
+ betterAuthSecret: z2.string().optional(),
1528
+ betterAuthAllowedHosts: z2.string().default(""),
1529
+ betterAuthCookieDomain: z2.string().optional(),
1530
+ betterAuthTrustedOrigins: z2.string().default(""),
1531
+ managedAuthGoogleClientId: z2.string().optional(),
1532
+ managedAuthGoogleClientSecret: z2.string().optional(),
1533
+ managedAuthGithubClientId: z2.string().optional(),
1534
+ managedAuthGithubClientSecret: z2.string().optional(),
1129
1535
  // Rolling browser login-slot compatibility. Repository/deployment default is
1130
1536
  // deliberately legacy; changing to broker is an operator-authorized rollout.
1131
- managedAuthSessionSetMode: z.enum(["legacy", "dual", "broker"]).default("legacy"),
1537
+ allowedUserEmails: z2.array(z2.email().transform((email) => email.toLowerCase())).min(1).optional(),
1538
+ managedAuthSessionSetMode: z2.enum(["legacy", "dual", "broker"]).default("legacy"),
1539
+ // Deployment ceiling for new managed accounts. When false, managed auth
1540
+ // refuses every new Better Auth account (email/password sign-up and implicit
1541
+ // Google/GitHub sign-up) while existing sign-in, sessions, password reset,
1542
+ // email verification, and invitation-bound account setup keep working. Read
1543
+ // at startup; the 0585 runtime switch pauses sign-ups without a restart.
1544
+ managedAuthNewSignupsEnabled: EnvBoolean.default(true),
1132
1545
  // Query transport is an explicit second-stage rollout. A pre-compatibility
1133
1546
  // web image understands only fragment bearers, so API replicas must keep
1134
1547
  // generating fragment links until the compatible web fleet has converged.
1135
- organizationUserSetupEmailTokenTransport: z.enum(["fragment", "query"]).default("fragment"),
1548
+ organizationUserSetupEmailTokenTransport: z2.enum(["fragment", "query"]).default("fragment"),
1136
1549
  // Query-bearing setup links may appear in controller/edge error logs even
1137
1550
  // when access logs and request tracing are disabled. This explicit operator
1138
1551
  // confirmation keeps query transport fail closed until that separate sink is
1139
1552
  // proven sanitized.
1140
1553
  organizationUserSetupQueryEdgeSanitizationConfirmed: EnvBoolean.default(false),
1141
- resendApiKey: z.string().optional(),
1142
- emailFrom: z.string().default("OpenGeni <auth@mail.opengeni.ai>"),
1143
- stripeSecretKey: z.string().optional(),
1144
- stripePublishableKey: z.string().optional(),
1145
- stripeWebhookSecret: z.string().optional(),
1146
- stripeCreditsProductId: z.string().optional(),
1147
- mcpServers: z.array(
1148
- z.object({
1149
- id: z.string().min(1).regex(registryId),
1150
- name: z.string().min(1).optional(),
1151
- url: z.string().url(),
1152
- allowedTools: z.array(z.string().min(1)).optional(),
1153
- timeoutMs: z.number().int().positive().optional(),
1154
- cacheToolsList: z.boolean().default(false),
1554
+ resendApiKey: z2.string().optional(),
1555
+ emailFrom: z2.string().default("OpenGeni <auth@mail.opengeni.ai>"),
1556
+ stripeSecretKey: z2.string().optional(),
1557
+ stripePublishableKey: z2.string().optional(),
1558
+ stripeWebhookSecret: z2.string().optional(),
1559
+ stripeCreditsProductId: z2.string().optional(),
1560
+ mcpServers: z2.array(
1561
+ z2.object({
1562
+ id: z2.string().min(1).regex(registryId),
1563
+ name: z2.string().min(1).optional(),
1564
+ url: z2.string().url(),
1565
+ allowedTools: z2.array(z2.string().min(1)).optional(),
1566
+ timeoutMs: z2.number().int().positive().optional(),
1567
+ cacheToolsList: z2.boolean().default(false),
1155
1568
  /** Runtime approval policy, overlaid from an attempt-frozen session snapshot. */
1156
1569
  requireApproval: SessionMcpApprovalPolicy.optional(),
1157
1570
  /**
@@ -1160,11 +1573,109 @@ var SettingsSchema = z.object({
1160
1573
  * encrypted capability-installation credentials; do not put secrets in
1161
1574
  * OPENGENI_MCP_SERVERS.
1162
1575
  */
1163
- headers: z.record(z.string(), z.string()).optional(),
1164
- connectionRef: McpServerConnectionRefSchema.optional()
1576
+ headers: z2.record(z2.string(), z2.string()).optional(),
1577
+ connectionRef: McpServerConnectionRefSchema.optional(),
1578
+ operationRecovery: McpOperationRecoverySchema.optional()
1165
1579
  })
1166
1580
  ).default([])
1167
1581
  });
1582
+ var ArtifactServiceSettingsSchema = SettingsSchema.pick({
1583
+ serviceName: true,
1584
+ environment: true,
1585
+ deploymentRevision: true,
1586
+ dbSchema: true,
1587
+ rlsStrategy: true,
1588
+ observabilityStructuredLogs: true,
1589
+ observabilityMetricsEnabled: true,
1590
+ observabilityOtlpEndpoint: true,
1591
+ observabilityOtlpHeaders: true
1592
+ });
1593
+ var ArtifactOutboxSettingsSchema = ArtifactServiceSettingsSchema.extend({
1594
+ natsUrl: SettingsSchema.shape.natsUrl,
1595
+ selfhostedNatsControlUser: SettingsSchema.shape.selfhostedNatsControlUser,
1596
+ selfhostedNatsControlPassword: SettingsSchema.shape.selfhostedNatsControlPassword
1597
+ });
1598
+ var ObjectStorageSettingsSchema = SettingsSchema.pick({
1599
+ objectStorageBackend: true,
1600
+ objectStorageEndpoint: true,
1601
+ objectStorageInternalEndpoint: true,
1602
+ objectStorageSandboxEndpoint: true,
1603
+ objectStorageBucket: true,
1604
+ objectStorageRegion: true,
1605
+ objectStorageAccessKeyId: true,
1606
+ objectStorageSecretAccessKey: true,
1607
+ objectStorageForcePathStyle: true,
1608
+ objectStorageAzureConnectionString: true,
1609
+ objectStorageAzureAccountName: true,
1610
+ objectStorageAzureAccountKey: true,
1611
+ objectStorageAzureEndpoint: true,
1612
+ objectStorageGcsProjectId: true,
1613
+ objectStorageGcsCredentialsJson: true,
1614
+ objectStorageGcsKeyFilename: true,
1615
+ objectStorageGcsApiEndpoint: true
1616
+ });
1617
+ var ArtifactMaterializerSettingsSchema = ArtifactServiceSettingsSchema.extend(
1618
+ ObjectStorageSettingsSchema.shape
1619
+ );
1620
+ function artifactServiceEnvironment(source) {
1621
+ const optional = (name) => optionalEnvironmentValue(name, source);
1622
+ return {
1623
+ serviceName: optional("OPENGENI_SERVICE_NAME"),
1624
+ environment: optional("OPENGENI_ENVIRONMENT"),
1625
+ deploymentRevision: optional("OPENGENI_DEPLOYMENT_REVISION") ?? optional("SOURCE_VERSION") ?? optional("GITHUB_SHA"),
1626
+ dbSchema: optional("OPENGENI_DB_SCHEMA"),
1627
+ rlsStrategy: optional("OPENGENI_RLS_STRATEGY"),
1628
+ observabilityStructuredLogs: optional("OPENGENI_OBSERVABILITY_STRUCTURED_LOGS"),
1629
+ observabilityMetricsEnabled: optional("OPENGENI_OBSERVABILITY_METRICS_ENABLED"),
1630
+ observabilityOtlpEndpoint: optional("OPENGENI_OTEL_EXPORTER_OTLP_ENDPOINT") ?? optional("OTEL_EXPORTER_OTLP_ENDPOINT"),
1631
+ observabilityOtlpHeaders: optional("OPENGENI_OTEL_EXPORTER_OTLP_HEADERS") ?? optional("OTEL_EXPORTER_OTLP_HEADERS")
1632
+ };
1633
+ }
1634
+ function getArtifactOutboxSettings(source = process.env) {
1635
+ const settings = ArtifactOutboxSettingsSchema.parse({
1636
+ ...artifactServiceEnvironment(source),
1637
+ natsUrl: optionalEnvironmentValue("OPENGENI_NATS_URL", source),
1638
+ selfhostedNatsControlUser: optionalEnvironmentValue(
1639
+ "OPENGENI_SELFHOSTED_NATS_CONTROL_USER",
1640
+ source
1641
+ ),
1642
+ selfhostedNatsControlPassword: optionalEnvironmentValue(
1643
+ "OPENGENI_SELFHOSTED_NATS_CONTROL_PASSWORD",
1644
+ source
1645
+ )
1646
+ });
1647
+ dbSearchPath(settings);
1648
+ if (Boolean(settings.selfhostedNatsControlUser) !== Boolean(settings.selfhostedNatsControlPassword)) {
1649
+ throw new Error("Artifact outbox NATS control user and password must be configured together");
1650
+ }
1651
+ return settings;
1652
+ }
1653
+ function getArtifactMaterializerSettings(source = process.env) {
1654
+ const optional = (name) => optionalEnvironmentValue(name, source);
1655
+ const settings = ArtifactMaterializerSettingsSchema.parse({
1656
+ ...artifactServiceEnvironment(source),
1657
+ objectStorageEndpoint: optional("OPENGENI_OBJECT_STORAGE_ENDPOINT"),
1658
+ objectStorageInternalEndpoint: optional("OPENGENI_OBJECT_STORAGE_INTERNAL_ENDPOINT"),
1659
+ objectStorageSandboxEndpoint: optional("OPENGENI_OBJECT_STORAGE_SANDBOX_ENDPOINT"),
1660
+ objectStorageBackend: optional("OPENGENI_OBJECT_STORAGE_BACKEND"),
1661
+ objectStorageBucket: optional("OPENGENI_OBJECT_STORAGE_BUCKET"),
1662
+ objectStorageRegion: optional("OPENGENI_OBJECT_STORAGE_REGION"),
1663
+ objectStorageAccessKeyId: optional("OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID"),
1664
+ objectStorageSecretAccessKey: optional("OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY"),
1665
+ objectStorageForcePathStyle: optional("OPENGENI_OBJECT_STORAGE_FORCE_PATH_STYLE"),
1666
+ objectStorageAzureConnectionString: optional("OPENGENI_OBJECT_STORAGE_AZURE_CONNECTION_STRING"),
1667
+ objectStorageAzureAccountName: optional("OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_NAME"),
1668
+ objectStorageAzureAccountKey: optional("OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_KEY"),
1669
+ objectStorageAzureEndpoint: optional("OPENGENI_OBJECT_STORAGE_AZURE_ENDPOINT"),
1670
+ objectStorageGcsProjectId: optional("OPENGENI_OBJECT_STORAGE_GCS_PROJECT_ID"),
1671
+ objectStorageGcsCredentialsJson: optional("OPENGENI_OBJECT_STORAGE_GCS_CREDENTIALS_JSON"),
1672
+ objectStorageGcsKeyFilename: optional("OPENGENI_OBJECT_STORAGE_GCS_KEY_FILENAME"),
1673
+ objectStorageGcsApiEndpoint: optional("OPENGENI_OBJECT_STORAGE_GCS_API_ENDPOINT")
1674
+ });
1675
+ dbSearchPath(settings);
1676
+ validateObjectStorageSettings(settings);
1677
+ return settings;
1678
+ }
1168
1679
  function configuredGoogleDriveSyncLimits(settings) {
1169
1680
  return KnowledgeSourceSyncLimits.parse({
1170
1681
  maxItems: settings.googleDriveSyncMaxItems,
@@ -1205,6 +1716,24 @@ function personalGitHubOAuthCallbackUrl(publicBaseUrl) {
1205
1716
  const origin = canonicalPublicOrigin(publicBaseUrl);
1206
1717
  return origin ? `${origin}/v1/integrations/github-personal/oauth/callback` : null;
1207
1718
  }
1719
+ function usableDeploymentSecret(value) {
1720
+ return isUsableVoiceInputSecret(value) ? value : void 0;
1721
+ }
1722
+ function usableJevApiKey(settings) {
1723
+ return usableDeploymentSecret(settings.jevApiKey);
1724
+ }
1725
+ function agentConfigDeploymentPolicy(settings) {
1726
+ return agentConfigDeploymentLimitsFromAllowlist(
1727
+ resolveFirstPartyMcpToolPolicy(settings).allowed,
1728
+ settings.webSearchEnabled ? {} : { webSearch: "web search is turned off on this server" }
1729
+ );
1730
+ }
1731
+ function codeSearchDeploymentPolicy(settings) {
1732
+ const available = settings.codeSearchMode !== "off" && usableJevApiKey(settings) !== void 0;
1733
+ if (!available) return { available: false, workspaceDefault: "off" };
1734
+ const workspaceDefault = settings.codeSearchMode === "default_on" ? "on" : settings.codeSearchMode === "experiment" ? "split" : "off";
1735
+ return { available, workspaceDefault };
1736
+ }
1208
1737
  function isUsableVoiceInputSecret(value) {
1209
1738
  if (value == null) return false;
1210
1739
  const trimmed = value.trim();
@@ -1289,18 +1818,18 @@ function voiceInputDeploymentConfigured(settings) {
1289
1818
  (provider) => provider.kind !== "codex-subscription" && provider.kind !== "supergrok-subscription"
1290
1819
  );
1291
1820
  }
1292
- var ModelPricingSchema = z.object({
1293
- inputMicrosPerMillionTokens: z.number().int().nonnegative(),
1294
- cachedInputMicrosPerMillionTokens: z.number().int().nonnegative().optional(),
1295
- cacheWriteMicrosPerMillionTokens: z.number().int().nonnegative().optional(),
1296
- outputMicrosPerMillionTokens: z.number().int().nonnegative(),
1297
- marginBps: z.number().int().min(0).max(1e5).optional()
1821
+ var ModelPricingSchema = z2.object({
1822
+ inputMicrosPerMillionTokens: z2.number().int().nonnegative(),
1823
+ cachedInputMicrosPerMillionTokens: z2.number().int().nonnegative().optional(),
1824
+ cacheWriteMicrosPerMillionTokens: z2.number().int().nonnegative().optional(),
1825
+ outputMicrosPerMillionTokens: z2.number().int().nonnegative(),
1826
+ marginBps: z2.number().int().min(0).max(1e5).optional()
1298
1827
  });
1299
- var ModelPricingScheduleSchema = z.object({
1828
+ var ModelPricingScheduleSchema = z2.object({
1300
1829
  default: ModelPricingSchema,
1301
- inputTokenTiers: z.array(
1302
- z.object({
1303
- minimumInputTokens: z.number().int().nonnegative(),
1830
+ inputTokenTiers: z2.array(
1831
+ z2.object({
1832
+ minimumInputTokens: z2.number().int().nonnegative(),
1304
1833
  pricing: ModelPricingSchema
1305
1834
  })
1306
1835
  ).optional()
@@ -1317,10 +1846,10 @@ var ModelPricingScheduleSchema = z.object({
1317
1846
  previous = tier.minimumInputTokens;
1318
1847
  }
1319
1848
  });
1320
- var CapabilitySupportV1 = z.enum(["supported", "unsupported", "unknown"]);
1321
- var CapabilityStateV1Schema = z.object({
1849
+ var CapabilitySupportV1 = z2.enum(["supported", "unsupported", "unknown"]);
1850
+ var CapabilityStateV1Schema = z2.object({
1322
1851
  upstream: CapabilitySupportV1,
1323
- runnable: z.boolean()
1852
+ runnable: z2.boolean()
1324
1853
  }).superRefine((state, ctx) => {
1325
1854
  if (state.upstream === "unsupported" && state.runnable) {
1326
1855
  ctx.addIssue({
@@ -1330,17 +1859,17 @@ var CapabilityStateV1Schema = z.object({
1330
1859
  });
1331
1860
  }
1332
1861
  });
1333
- var ModelModalityV1 = z.enum(["text", "image", "audio"]);
1334
- var ModelLatencyModeV1 = z.enum(["standard", "priority", "fast"]);
1335
- var ModelCapabilitiesV1Schema = z.object({
1862
+ var ModelModalityV1 = z2.enum(["text", "image", "audio"]);
1863
+ var ModelLatencyModeV1 = z2.enum(["standard", "priority", "fast"]);
1864
+ var ModelCapabilitiesV1Schema = z2.object({
1336
1865
  reasoning: CapabilityStateV1Schema.extend({
1337
- efforts: z.array(ReasoningEffort),
1866
+ efforts: z2.array(ReasoningEffort),
1338
1867
  defaultEffort: ReasoningEffort.nullable(),
1339
- required: z.boolean()
1868
+ required: z2.boolean()
1340
1869
  }),
1341
1870
  functionCalling: CapabilityStateV1Schema,
1342
1871
  structuredOutput: CapabilityStateV1Schema,
1343
- hostedTools: z.object({
1872
+ hostedTools: z2.object({
1344
1873
  webSearch: CapabilityStateV1Schema,
1345
1874
  xSearch: CapabilityStateV1Schema,
1346
1875
  codeExecution: CapabilityStateV1Schema,
@@ -1349,24 +1878,24 @@ var ModelCapabilitiesV1Schema = z.object({
1349
1878
  runnable: false
1350
1879
  })
1351
1880
  }),
1352
- inputModalities: z.array(ModelModalityV1).min(1),
1881
+ inputModalities: z2.array(ModelModalityV1).min(1),
1353
1882
  /** Exact MIME types accepted as typed `input_file`; `text/*` is allowed. */
1354
- inputFileMediaTypes: z.array(z.string()).default([]),
1355
- outputModalities: z.array(ModelModalityV1).min(1),
1356
- transports: z.object({
1883
+ inputFileMediaTypes: z2.array(z2.string()).default([]),
1884
+ outputModalities: z2.array(ModelModalityV1).min(1),
1885
+ transports: z2.object({
1357
1886
  sse: CapabilityStateV1Schema,
1358
1887
  responsesWebSocket: CapabilityStateV1Schema,
1359
1888
  realtimeAudio: CapabilityStateV1Schema
1360
1889
  }),
1361
1890
  promptCaching: CapabilityStateV1Schema.extend({
1362
- mode: z.enum(["implicit", "automatic", "none"])
1891
+ mode: z2.enum(["implicit", "automatic", "none"])
1363
1892
  }).optional(),
1364
- latencyModes: z.array(
1365
- z.object({
1893
+ latencyModes: z2.array(
1894
+ z2.object({
1366
1895
  id: ModelLatencyModeV1,
1367
1896
  upstream: CapabilitySupportV1,
1368
- runnable: z.boolean(),
1369
- billingMultiplierBps: z.number().int().positive().optional()
1897
+ runnable: z2.boolean(),
1898
+ billingMultiplierBps: z2.number().int().positive().optional()
1370
1899
  })
1371
1900
  ).min(1)
1372
1901
  }).superRefine((capabilities, ctx) => {
@@ -1420,9 +1949,9 @@ var ModelCapabilitiesV1Schema = z.object({
1420
1949
  }
1421
1950
  }
1422
1951
  });
1423
- var ModelProviderApi = z.enum(["responses", "chat"]);
1424
- var ModelProviderWireProfile = z.enum(["openai", "azure-openai"]);
1425
- var RegistryProviderKind = z.enum([
1952
+ var ModelProviderApi = z2.enum(["responses", "chat", "anthropic-messages"]);
1953
+ var ModelProviderWireProfile = z2.enum(["openai", "azure-openai"]);
1954
+ var RegistryProviderKind = z2.enum([
1426
1955
  "api-key",
1427
1956
  "anonymous",
1428
1957
  "codex-subscription",
@@ -1430,36 +1959,42 @@ var RegistryProviderKind = z.enum([
1430
1959
  "vercel-gateway-managed",
1431
1960
  "vercel-gateway-workspace",
1432
1961
  "vercel-gateway-organization",
1962
+ "direct-openai-workspace",
1963
+ "direct-azure-workspace",
1433
1964
  "openrouter-workspace",
1434
- "openrouter-organization"
1965
+ "openrouter-organization",
1966
+ "anthropic-organization",
1967
+ "claude-subscription-organization",
1968
+ "anthropic-workspace",
1969
+ "claude-subscription-workspace"
1435
1970
  ]);
1436
- var RegistryModelSchema = z.object({
1437
- id: z.string().min(1),
1971
+ var RegistryModelSchema = z2.object({
1972
+ id: z2.string().min(1),
1438
1973
  // canonical OpenGeni product id
1439
- upstreamModelId: z.string().min(1).optional(),
1974
+ upstreamModelId: z2.string().min(1).optional(),
1440
1975
  // exact provider slug; defaults to id
1441
- aliases: z.array(z.string().min(1)).optional(),
1976
+ aliases: z2.array(z2.string().min(1)).optional(),
1442
1977
  // accepted input only; never sent upstream
1443
- label: z.string().min(1).optional(),
1978
+ label: z2.string().min(1).optional(),
1444
1979
  // display name; defaults to id
1445
- shortLabel: z.string().min(1).max(64).optional(),
1980
+ shortLabel: z2.string().min(1).max(64).optional(),
1446
1981
  // compact UI label; optional
1447
- contextWindowTokens: z.number().int().positive().optional(),
1448
- effectiveContextWindowTokens: z.number().int().positive().optional(),
1449
- autoCompactTokenLimit: z.number().int().positive().optional(),
1982
+ contextWindowTokens: z2.number().int().positive().optional(),
1983
+ effectiveContextWindowTokens: z2.number().int().positive().optional(),
1984
+ autoCompactTokenLimit: z2.number().int().positive().optional(),
1450
1985
  // Canonical model-facing function/tool-result policy. The runtime applies
1451
1986
  // the same 1.2x serialization allowance as Codex when materializing output.
1452
- toolOutputTruncationTokens: z.number().int().positive().optional(),
1453
- reasoningEffort: z.boolean().optional(),
1987
+ toolOutputTruncationTokens: z2.number().int().positive().optional(),
1988
+ reasoningEffort: z2.boolean().optional(),
1454
1989
  // legacy compatibility input/projection
1455
- hostedWebSearch: z.boolean().optional(),
1990
+ hostedWebSearch: z2.boolean().optional(),
1456
1991
  // legacy compatibility input/projection
1457
1992
  capabilities: ModelCapabilitiesV1Schema.optional(),
1458
- pricing: z.union([ModelPricingSchema, ModelPricingScheduleSchema]).optional(),
1993
+ pricing: z2.union([ModelPricingSchema, ModelPricingScheduleSchema]).optional(),
1459
1994
  // Reserved normalized contracts are derived by OpenGeni in V1. Generic
1460
1995
  // registry JSON must not opt itself into workspace BYOK or reattribute cost.
1461
- credentialSource: z.never().optional(),
1462
- billing: z.never().optional()
1996
+ credentialSource: z2.never().optional(),
1997
+ billing: z2.never().optional()
1463
1998
  }).superRefine((model, ctx) => {
1464
1999
  if (model.capabilities && model.reasoningEffort !== void 0 && model.reasoningEffort !== model.capabilities.reasoning.runnable) {
1465
2000
  ctx.addIssue({
@@ -1476,27 +2011,54 @@ var RegistryModelSchema = z.object({
1476
2011
  });
1477
2012
  }
1478
2013
  });
1479
- var RegistryProviderSchema = z.object({
2014
+ var ClaudeSubscriptionIdentity = z2.object({
2015
+ accountUuid: z2.union([z2.string().uuid(), z2.literal("")]),
2016
+ deviceId: z2.string().regex(/^[a-f0-9]{64}$/)
2017
+ }).strict();
2018
+ var ClaudeSubscriptionCredential = z2.object({
2019
+ version: z2.literal(1),
2020
+ token: z2.string().regex(/^sk-ant-oat[0-9]+-\S+$/),
2021
+ identity: ClaudeSubscriptionIdentity,
2022
+ oauth: z2.object({
2023
+ refreshToken: z2.string().min(1).max(16384),
2024
+ expiresAt: z2.string().datetime(),
2025
+ scopes: z2.array(z2.string().min(1).max(256)).min(1).max(32)
2026
+ }).strict().optional()
2027
+ }).strict();
2028
+ var AnthropicProviderOptions = z2.object({
2029
+ identity: ClaudeSubscriptionIdentity.optional(),
2030
+ // Native connection provenance only; never included in Anthropic request bodies.
2031
+ credentialBinding: z2.object({
2032
+ connectionId: z2.string().uuid(),
2033
+ credentialVersion: z2.number().int().positive()
2034
+ }).strict().optional(),
2035
+ auth: z2.enum(["api-key", "oauth"]).default("api-key"),
2036
+ cacheTtl: z2.enum(["5m", "1h", "off"]).default("5m"),
2037
+ maxOutputTokens: z2.number().int().positive().default(32e3),
2038
+ streamIdleTimeoutMs: z2.number().int().positive().default(6e5)
2039
+ });
2040
+ var RegistryProviderSchema = z2.object({
1480
2041
  kind: RegistryProviderKind.default("api-key"),
1481
- id: z.string().min(1).regex(registryId),
2042
+ id: z2.string().min(1).regex(registryId),
1482
2043
  // stable provider id, e.g. "fireworks"
1483
- label: z.string().min(1).optional(),
2044
+ label: z2.string().min(1).optional(),
1484
2045
  api: ModelProviderApi.default("chat"),
2046
+ anthropic: AnthropicProviderOptions.optional(),
1485
2047
  wireProfile: ModelProviderWireProfile.default("openai"),
1486
- baseUrl: z.string().url(),
1487
- apiKey: z.string().optional(),
2048
+ baseUrl: z2.string().url(),
2049
+ apiKey: z2.string().optional(),
1488
2050
  // inline key (pragmatic) ...
1489
- apiKeyEnv: z.string().optional(),
2051
+ apiKeyEnv: z2.string().optional(),
1490
2052
  // ... OR name of the env var holding the key (preferred)
1491
- defaultQuery: z.record(z.string(), z.string()).optional(),
1492
- defaultHeaders: z.record(z.string(), z.string()).optional(),
1493
- publicDefaultQueryNames: z.array(z.string().min(1)).optional(),
1494
- publicDefaultHeaderNames: z.array(z.string().min(1)).optional(),
2053
+ defaultQuery: z2.record(z2.string(), z2.string()).optional(),
2054
+ defaultHeaders: z2.record(z2.string(), z2.string()).optional(),
2055
+ publicDefaultQueryNames: z2.array(z2.string().min(1)).optional(),
2056
+ publicDefaultHeaderNames: z2.array(z2.string().min(1)).optional(),
1495
2057
  // V1 derives these from provider kind. Workspace BYOK is deliberately not a
1496
2058
  // registry switch and requires a separately reviewed encrypted broker.
1497
- credentialSource: z.never().optional(),
1498
- billing: z.never().optional(),
1499
- models: z.array(RegistryModelSchema).min(1)
2059
+ credentialSource: z2.never().optional(),
2060
+ billing: z2.never().optional(),
2061
+ models: z2.array(RegistryModelSchema).min(1)
1500
2062
  }).superRefine((provider, ctx) => {
1501
2063
  if (provider.kind !== "anonymous") {
1502
2064
  return;
@@ -1566,17 +2128,21 @@ var RESERVED_MODEL_PROVIDER_IDS = /* @__PURE__ */ new Set([
1566
2128
  ORGANIZATION_GATEWAY_PROVIDER_ID,
1567
2129
  OPENROUTER_PROVIDER_ID,
1568
2130
  WORKSPACE_OPENROUTER_PROVIDER_ID,
1569
- ORGANIZATION_OPENROUTER_PROVIDER_ID
2131
+ ORGANIZATION_OPENROUTER_PROVIDER_ID,
2132
+ "organization-anthropic",
2133
+ "organization-claude-subscription",
2134
+ "workspace-anthropic",
2135
+ "workspace-claude-subscription"
1570
2136
  ]);
1571
- var ModelCostClass = z.enum(["free", "credits"]);
1572
- var ConfiguredModelCostClass = z.enum([
2137
+ var ModelCostClass = z2.enum(["free", "credits"]);
2138
+ var ConfiguredModelCostClass = z2.enum([
1573
2139
  "free",
1574
2140
  "credits",
1575
2141
  "subscription",
1576
2142
  "workspace",
1577
2143
  "organization"
1578
2144
  ]);
1579
- var ModelNote = z.string().max(500).refine((value) => !/[\r\n|]/u.test(value), {
2145
+ var ModelNote = z2.string().max(500).refine((value) => !/[\r\n|]/u.test(value), {
1580
2146
  message: "model notes must not contain newlines or the | field separator"
1581
2147
  });
1582
2148
  function parseModelCostPolicyJson(raw) {
@@ -1589,7 +2155,7 @@ function parseModelCostPolicyJson(raw) {
1589
2155
  { cause: error }
1590
2156
  );
1591
2157
  }
1592
- return z.record(z.string().min(1), ModelCostClass).parse(parsed);
2158
+ return z2.record(z2.string().min(1), ModelCostClass).parse(parsed);
1593
2159
  }
1594
2160
  function parseModelNotesJson(raw) {
1595
2161
  let parsed;
@@ -1601,45 +2167,45 @@ function parseModelNotesJson(raw) {
1601
2167
  { cause: error }
1602
2168
  );
1603
2169
  }
1604
- return z.record(z.string().min(1), ModelNote).parse(parsed);
2170
+ return z2.record(z2.string().min(1), ModelNote).parse(parsed);
1605
2171
  }
1606
2172
  function configuredModelNotes(settings) {
1607
2173
  return parseModelNotesJson(settings.modelNotesJson);
1608
2174
  }
1609
- var GatewayCatalogModel = z.object({
1610
- productId: z.string().min(1),
1611
- workspaceProductId: z.string().min(1).startsWith(WORKSPACE_GATEWAY_MODEL_ID_PREFIX),
1612
- upstreamModelId: z.string().min(1),
1613
- label: z.string().min(1),
1614
- shortLabel: z.string().min(1).max(64).optional(),
1615
- providers: z.array(z.string().min(1)).min(1),
1616
- implicitCaching: z.boolean().default(false),
1617
- vision: z.boolean().default(false),
1618
- inputFileMediaTypes: z.array(z.string().min(1)).default([]),
1619
- contextWindowTokens: z.number().int().positive().default(1e6),
1620
- effectiveContextWindowTokens: z.number().int().positive().default(9e5),
1621
- autoCompactTokenLimit: z.number().int().positive().default(85e4),
1622
- pricing: z.union([ModelPricingSchema, ModelPricingScheduleSchema]).optional(),
1623
- credentialSource: z.never().optional(),
1624
- billing: z.never().optional(),
1625
- apiKey: z.never().optional()
2175
+ var GatewayCatalogModel = z2.object({
2176
+ productId: z2.string().min(1),
2177
+ workspaceProductId: z2.string().min(1).startsWith(WORKSPACE_GATEWAY_MODEL_ID_PREFIX),
2178
+ upstreamModelId: z2.string().min(1),
2179
+ label: z2.string().min(1),
2180
+ shortLabel: z2.string().min(1).max(64).optional(),
2181
+ providers: z2.array(z2.string().min(1)).min(1),
2182
+ implicitCaching: z2.boolean().default(false),
2183
+ vision: z2.boolean().default(false),
2184
+ inputFileMediaTypes: z2.array(z2.string().min(1)).default([]),
2185
+ contextWindowTokens: z2.number().int().positive().default(1e6),
2186
+ effectiveContextWindowTokens: z2.number().int().positive().default(9e5),
2187
+ autoCompactTokenLimit: z2.number().int().positive().default(85e4),
2188
+ pricing: z2.union([ModelPricingSchema, ModelPricingScheduleSchema]).optional(),
2189
+ credentialSource: z2.never().optional(),
2190
+ billing: z2.never().optional(),
2191
+ apiKey: z2.never().optional()
1626
2192
  }).strict();
1627
- var OpenRouterCatalogModel = z.object({
1628
- upstreamModelId: z.string().min(1).endsWith(":free"),
1629
- label: z.string().min(1),
1630
- shortLabel: z.string().min(1).max(64).optional(),
1631
- aliases: z.array(z.string().min(1)).default([]),
2193
+ var OpenRouterCatalogModel = z2.object({
2194
+ upstreamModelId: z2.string().min(1).endsWith(":free"),
2195
+ label: z2.string().min(1),
2196
+ shortLabel: z2.string().min(1).max(64).optional(),
2197
+ aliases: z2.array(z2.string().min(1)).default([]),
1632
2198
  capabilities: ModelCapabilitiesV1Schema,
1633
- contextWindowTokens: z.number().int().positive().optional(),
1634
- effectiveContextWindowTokens: z.number().int().positive().optional(),
1635
- autoCompactTokenLimit: z.number().int().positive().optional(),
1636
- toolOutputTruncationTokens: z.number().int().positive().optional(),
1637
- credentialSource: z.never().optional(),
1638
- billing: z.never().optional(),
1639
- pricing: z.never().optional(),
1640
- apiKey: z.never().optional()
2199
+ contextWindowTokens: z2.number().int().positive().optional(),
2200
+ effectiveContextWindowTokens: z2.number().int().positive().optional(),
2201
+ autoCompactTokenLimit: z2.number().int().positive().optional(),
2202
+ toolOutputTruncationTokens: z2.number().int().positive().optional(),
2203
+ credentialSource: z2.never().optional(),
2204
+ billing: z2.never().optional(),
2205
+ pricing: z2.never().optional(),
2206
+ apiKey: z2.never().optional()
1641
2207
  }).strict();
1642
- var DeploymentRegistryBaseUrl = z.string().url().superRefine((value, context) => {
2208
+ var DeploymentRegistryBaseUrl = z2.string().url().superRefine((value, context) => {
1643
2209
  const url = new URL(value);
1644
2210
  if (url.username || url.password) {
1645
2211
  context.addIssue({
@@ -1660,40 +2226,66 @@ var DeploymentRegistryBaseUrl = z.string().url().superRefine((value, context) =>
1660
2226
  });
1661
2227
  }
1662
2228
  });
1663
- var DeploymentRegistryProviderKind = z.enum(["api-key", "anonymous"]);
2229
+ var DeploymentRegistryProviderKind = z2.enum(["api-key", "anonymous"]);
1664
2230
  var DeploymentRegistryModelSchema = RegistryModelSchema.safeExtend({
1665
- pricing: z.never().optional()
2231
+ pricing: z2.never().optional()
1666
2232
  }).strict();
1667
2233
  var DeploymentRegistryProviderSchema = RegistryProviderSchema.safeExtend({
1668
2234
  kind: DeploymentRegistryProviderKind.default("api-key"),
1669
2235
  baseUrl: DeploymentRegistryBaseUrl,
1670
- models: z.array(DeploymentRegistryModelSchema).min(1),
1671
- apiKey: z.never().optional(),
1672
- apiKeyEnv: z.never().optional(),
1673
- defaultHeaders: z.never().optional(),
1674
- defaultQuery: z.never().optional(),
1675
- publicDefaultHeaderNames: z.never().optional(),
1676
- publicDefaultQueryNames: z.never().optional()
2236
+ models: z2.array(DeploymentRegistryModelSchema).min(1),
2237
+ apiKey: z2.never().optional(),
2238
+ apiKeyEnv: z2.never().optional(),
2239
+ defaultHeaders: z2.never().optional(),
2240
+ defaultQuery: z2.never().optional(),
2241
+ publicDefaultHeaderNames: z2.never().optional(),
2242
+ publicDefaultQueryNames: z2.never().optional()
1677
2243
  }).strict();
1678
2244
  var DeploymentGatewayCatalogModelSchema = GatewayCatalogModel.safeExtend({
1679
- pricing: z.never().optional()
2245
+ pricing: z2.never().optional()
1680
2246
  }).strict();
1681
- var ModelCatalogDocument = z.object({
1682
- schemaVersion: z.literal(1),
2247
+ var CodexCatalogModelSchema = RegistryModelSchema.safeExtend({
2248
+ retired: z2.boolean().optional(),
2249
+ id: z2.string().regex(/^codex\/[a-zA-Z0-9][a-zA-Z0-9._-]*$/),
2250
+ upstreamModelId: z2.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/),
2251
+ capabilities: ModelCapabilitiesV1Schema,
2252
+ pricing: z2.never().optional()
2253
+ }).strict().superRefine((model, context) => {
2254
+ if (model.id !== `${CODEX_MODEL_ID_PREFIX}${model.upstreamModelId}`) {
2255
+ context.addIssue({
2256
+ code: "custom",
2257
+ path: ["id"],
2258
+ message: "Codex product id must match its upstream model slug"
2259
+ });
2260
+ }
2261
+ }).transform((model) => ({
2262
+ ...model,
2263
+ capabilities: reviewedCodexCatalogCapabilities(model.upstreamModelId, model.capabilities)
2264
+ }));
2265
+ var ModelCatalogDocument = z2.object({
2266
+ schemaVersion: z2.literal(1),
1683
2267
  /** Canonical deployment default. Omission preserves the V1 first-built-in
1684
2268
  * fallback for existing documents; operators should set this explicitly
1685
2269
  * when cutting over a registry or connected-subscription default. */
1686
- defaultModel: z.string().min(1).optional(),
1687
- builtInModels: z.array(z.string().min(1)).min(1),
1688
- registryProviders: z.array(DeploymentRegistryProviderSchema).default([]),
1689
- gatewayModels: z.array(DeploymentGatewayCatalogModelSchema).default([]),
1690
- openrouterModels: z.array(OpenRouterCatalogModel).default([]),
1691
- modelNotes: z.record(z.string().min(1), ModelNote).default({}),
1692
- billing: z.never().optional(),
1693
- enabled: z.never().optional(),
1694
- apiKey: z.never().optional(),
1695
- bands: z.never().optional()
2270
+ defaultModel: z2.string().min(1).optional(),
2271
+ builtInModels: z2.array(z2.string().min(1)),
2272
+ registryProviders: z2.array(DeploymentRegistryProviderSchema).default([]),
2273
+ codexModels: z2.array(CodexCatalogModelSchema).optional(),
2274
+ gatewayModels: z2.array(DeploymentGatewayCatalogModelSchema).default([]),
2275
+ openrouterModels: z2.array(OpenRouterCatalogModel).default([]),
2276
+ modelNotes: z2.record(z2.string().min(1), ModelNote).default({}),
2277
+ billing: z2.never().optional(),
2278
+ enabled: z2.never().optional(),
2279
+ apiKey: z2.never().optional(),
2280
+ bands: z2.never().optional()
1696
2281
  }).strict().superRefine((document, context) => {
2282
+ if (document.builtInModels.length === 0 && !document.defaultModel) {
2283
+ context.addIssue({
2284
+ code: "custom",
2285
+ path: ["defaultModel"],
2286
+ message: "catalogs without built-in models require an explicit default model"
2287
+ });
2288
+ }
1697
2289
  const productIds = /* @__PURE__ */ new Set();
1698
2290
  const providerIds = /* @__PURE__ */ new Set();
1699
2291
  const gatewayUpstreamIds = /* @__PURE__ */ new Set();
@@ -1715,8 +2307,16 @@ var ModelCatalogDocument = z.object({
1715
2307
  productIds.add(id);
1716
2308
  };
1717
2309
  document.builtInModels.forEach((id, index) => add(id, ["builtInModels", index]));
2310
+ document.codexModels?.forEach((model, index) => add(model.id, ["codexModels", index, "id"]));
2311
+ if (document.codexModels?.some((model) => model.retired && model.id === document.defaultModel)) {
2312
+ context.addIssue({
2313
+ code: "custom",
2314
+ path: ["defaultModel"],
2315
+ message: "a retired model cannot be the deployment default"
2316
+ });
2317
+ }
1718
2318
  document.registryProviders.forEach((provider, providerIndex) => {
1719
- if (RESERVED_MODEL_PROVIDER_IDS.has(provider.id)) {
2319
+ if (RESERVED_MODEL_PROVIDER_IDS.has(provider.id) || provider.id.startsWith("workspace-openai-") || provider.id.startsWith("workspace-azure-openai-")) {
1720
2320
  context.addIssue({
1721
2321
  code: "custom",
1722
2322
  path: ["registryProviders", providerIndex, "id"],
@@ -1761,7 +2361,7 @@ var ModelCatalogDocument = z.object({
1761
2361
  message: "catalog default model must not contain newlines or the | field separator"
1762
2362
  });
1763
2363
  }
1764
- if (document.defaultModel && !productIds.has(document.defaultModel) && !document.defaultModel.startsWith(CODEX_MODEL_ID_PREFIX) && !document.defaultModel.startsWith(XAI_SUBSCRIPTION_MODEL_ID_PREFIX)) {
2364
+ 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)) {
1765
2365
  context.addIssue({
1766
2366
  code: "custom",
1767
2367
  path: ["defaultModel"],
@@ -1831,15 +2431,19 @@ function applyModelCatalogDocument(settings, rawDocument) {
1831
2431
  ),
1832
2432
  resolvedGatewayModelsJson: JSON.stringify(document.gatewayModels),
1833
2433
  resolvedOpenRouterModelsJson: JSON.stringify(document.openrouterModels),
2434
+ resolvedCodexModelsJson: document.codexModels === void 0 ? void 0 : JSON.stringify(document.codexModels),
1834
2435
  modelNotesJson: JSON.stringify(document.modelNotes)
1835
2436
  };
1836
2437
  return resolved;
1837
2438
  }
1838
- var IntegrationOAuthClientConfigSchema = z.object({
1839
- clientId: z.string().min(1),
1840
- clientSecret: z.string().min(1).optional(),
1841
- tokenEndpointAuthMethod: z.enum(["none", "client_secret_post", "client_secret_basic"]).default("none")
2439
+ var IntegrationOAuthClientConfigSchema = z2.object({
2440
+ clientId: z2.string().min(1),
2441
+ clientSecret: z2.string().min(1).optional(),
2442
+ tokenEndpointAuthMethod: z2.enum(["none", "client_secret_post", "client_secret_basic"]).default("none")
1842
2443
  });
2444
+ function isManagedOpenRouterFreeRoute(route) {
2445
+ return route.provider.kind === "openrouter-managed" && route.configured.upstreamModelId.endsWith(":free");
2446
+ }
1843
2447
  var VERCEL_AI_GATEWAY_BASE_URL = "https://ai-gateway.vercel.sh/v1";
1844
2448
  var VERCEL_AI_GATEWAY_AI_SDK_BASE_URL = "https://ai-gateway.vercel.sh/v4/ai";
1845
2449
  var VERCEL_AI_GATEWAY_CONNECTION_DOMAIN = "ai-gateway.vercel.sh";
@@ -1966,7 +2570,7 @@ function configuredGatewayCatalogModels(settings) {
1966
2570
  if (settings.resolvedGatewayModelsJson === void 0) {
1967
2571
  return defaultGatewayCatalogModels();
1968
2572
  }
1969
- return z.array(GatewayCatalogModel).parse(JSON.parse(settings.resolvedGatewayModelsJson));
2573
+ return z2.array(GatewayCatalogModel).parse(JSON.parse(settings.resolvedGatewayModelsJson));
1970
2574
  }
1971
2575
  function configuredGatewayUpstreamModelIds(settings) {
1972
2576
  return configuredGatewayCatalogModels(settings).map((model) => model.upstreamModelId);
@@ -1985,7 +2589,7 @@ function configuredOpenRouterCatalogModels(settings) {
1985
2589
  if (settings.resolvedOpenRouterModelsJson === void 0) {
1986
2590
  return [...OPENGENI_OPENROUTER_MODELS];
1987
2591
  }
1988
- return z.array(OpenRouterCatalogModel).parse(JSON.parse(settings.resolvedOpenRouterModelsJson));
2592
+ return z2.array(OpenRouterCatalogModel).parse(JSON.parse(settings.resolvedOpenRouterModelsJson));
1989
2593
  }
1990
2594
  function configuredOpenRouterUpstreamModelIds(settings) {
1991
2595
  return configuredOpenRouterCatalogModels(settings).map((model) => model.upstreamModelId);
@@ -2003,6 +2607,73 @@ function configuredOpenRouterOrganizationProductModelIds(settings) {
2003
2607
  return [];
2004
2608
  }
2005
2609
  var defaultModelPricing = {
2610
+ "gpt-6-astra": {
2611
+ default: {
2612
+ // OpenAI list price: $10 / $1 cached / $12.50 cache write / $50 output.
2613
+ inputMicrosPerMillionTokens: 1e7,
2614
+ cachedInputMicrosPerMillionTokens: 1e6,
2615
+ cacheWriteMicrosPerMillionTokens: 125e5,
2616
+ outputMicrosPerMillionTokens: 5e7,
2617
+ marginBps: 500
2618
+ },
2619
+ inputTokenTiers: [
2620
+ {
2621
+ // Prompts with more than 272K input tokens use 2x input and 1.5x output.
2622
+ minimumInputTokens: 272001,
2623
+ pricing: {
2624
+ inputMicrosPerMillionTokens: 2e7,
2625
+ cachedInputMicrosPerMillionTokens: 2e6,
2626
+ cacheWriteMicrosPerMillionTokens: 25e6,
2627
+ outputMicrosPerMillionTokens: 75e6,
2628
+ marginBps: 500
2629
+ }
2630
+ }
2631
+ ]
2632
+ },
2633
+ "gpt-6-sol": {
2634
+ default: {
2635
+ // OpenAI list price: $2 / $0.20 cached / $2.50 cache write / $10 output.
2636
+ inputMicrosPerMillionTokens: 2e6,
2637
+ cachedInputMicrosPerMillionTokens: 2e5,
2638
+ cacheWriteMicrosPerMillionTokens: 25e5,
2639
+ outputMicrosPerMillionTokens: 1e7,
2640
+ marginBps: 500
2641
+ },
2642
+ inputTokenTiers: [
2643
+ {
2644
+ minimumInputTokens: 272001,
2645
+ pricing: {
2646
+ inputMicrosPerMillionTokens: 4e6,
2647
+ cachedInputMicrosPerMillionTokens: 4e5,
2648
+ cacheWriteMicrosPerMillionTokens: 5e6,
2649
+ outputMicrosPerMillionTokens: 15e6,
2650
+ marginBps: 500
2651
+ }
2652
+ }
2653
+ ]
2654
+ },
2655
+ "gpt-6-luna": {
2656
+ default: {
2657
+ // OpenAI list price: $0.10 / $0.01 cached / $0.125 cache write / $0.50 output.
2658
+ inputMicrosPerMillionTokens: 1e5,
2659
+ cachedInputMicrosPerMillionTokens: 1e4,
2660
+ cacheWriteMicrosPerMillionTokens: 125e3,
2661
+ outputMicrosPerMillionTokens: 5e5,
2662
+ marginBps: 500
2663
+ },
2664
+ inputTokenTiers: [
2665
+ {
2666
+ minimumInputTokens: 272001,
2667
+ pricing: {
2668
+ inputMicrosPerMillionTokens: 2e5,
2669
+ cachedInputMicrosPerMillionTokens: 2e4,
2670
+ cacheWriteMicrosPerMillionTokens: 25e4,
2671
+ outputMicrosPerMillionTokens: 75e4,
2672
+ marginBps: 500
2673
+ }
2674
+ }
2675
+ ]
2676
+ },
2006
2677
  "gpt-5.6-sol": {
2007
2678
  default: {
2008
2679
  // Promotional OpenAI pricing, guaranteed through at least 2026-11-21.
@@ -2102,6 +2773,103 @@ var defaultModelPricing = {
2102
2773
  }
2103
2774
  }
2104
2775
  };
2776
+ var reviewedModelListPricing = {
2777
+ // Reviewed 2026-10-03 against https://developers.openai.com/api/docs/pricing
2778
+ // and https://ai-gateway.vercel.sh/v1/models. GPT-6.1 Sol's cache-read rate
2779
+ // is 5% of input, not GPT-6 Sol's 10%. The long-context boundary is >272K.
2780
+ "gpt-6.1-sol": {
2781
+ default: {
2782
+ inputMicrosPerMillionTokens: 2e6,
2783
+ cachedInputMicrosPerMillionTokens: 1e5,
2784
+ cacheWriteMicrosPerMillionTokens: 25e5,
2785
+ outputMicrosPerMillionTokens: 1e7,
2786
+ marginBps: 500
2787
+ },
2788
+ inputTokenTiers: [
2789
+ {
2790
+ minimumInputTokens: 272001,
2791
+ pricing: {
2792
+ inputMicrosPerMillionTokens: 4e6,
2793
+ cachedInputMicrosPerMillionTokens: 2e5,
2794
+ cacheWriteMicrosPerMillionTokens: 5e6,
2795
+ outputMicrosPerMillionTokens: 15e6,
2796
+ marginBps: 500
2797
+ }
2798
+ }
2799
+ ]
2800
+ },
2801
+ // xAI Standard API list rates, reviewed 2026-10-03:
2802
+ // https://docs.x.ai/developers/models/grok-4.5 (and grok-4.6 / grok-4.7).
2803
+ // Preserve the native API's established >=200K boundary. Gateway's separately
2804
+ // configured >200K schedule is not interchangeable with this native schedule.
2805
+ // xAI's automatic caching has no separate cache-write surcharge.
2806
+ ...Object.fromEntries(
2807
+ [
2808
+ ["grok-4.5", 3e5],
2809
+ ["grok-4.6", 5e5],
2810
+ ["grok-4.7", 5e5]
2811
+ ].map(([model, cachedInput]) => [
2812
+ model,
2813
+ {
2814
+ default: {
2815
+ inputMicrosPerMillionTokens: 2e6,
2816
+ cachedInputMicrosPerMillionTokens: cachedInput,
2817
+ outputMicrosPerMillionTokens: 6e6,
2818
+ marginBps: 500
2819
+ },
2820
+ inputTokenTiers: [
2821
+ {
2822
+ minimumInputTokens: 2e5,
2823
+ pricing: {
2824
+ inputMicrosPerMillionTokens: 4e6,
2825
+ cachedInputMicrosPerMillionTokens: cachedInput * 2,
2826
+ outputMicrosPerMillionTokens: 12e6,
2827
+ marginBps: 500
2828
+ }
2829
+ }
2830
+ ]
2831
+ }
2832
+ ])
2833
+ ),
2834
+ // Every reviewed native Claude profile. Standard/global prices include
2835
+ // 5-minute cache writes; 1-hour native routes are projected separately.
2836
+ // https://platform.claude.com/docs/en/about-claude/pricing (2026-10-03).
2837
+ // Opus 5.5 cache reads are 5%, unlike the older models' 10%; none of these
2838
+ // models has a long-context premium.
2839
+ ...Object.fromEntries(
2840
+ [
2841
+ ["claude-opus-5-5", 4e6, 2e5, 5e6, 2e7],
2842
+ ["claude-sonnet-5-5", 2e6, 2e5, 25e5, 1e7],
2843
+ ["claude-opus-5", 5e6, 5e5, 625e4, 25e6],
2844
+ ["claude-sonnet-5", 2e6, 2e5, 25e5, 1e7],
2845
+ ["claude-opus-4-8", 5e6, 5e5, 625e4, 25e6],
2846
+ ["claude-opus-4-7", 5e6, 5e5, 625e4, 25e6],
2847
+ ["claude-opus-4-6", 5e6, 5e5, 625e4, 25e6],
2848
+ ["claude-sonnet-4-6", 3e6, 3e5, 375e4, 15e6],
2849
+ ["claude-haiku-4-5-20251001", 1e6, 1e5, 125e4, 5e6]
2850
+ ].map(([model, input, cachedInput, cacheWrite, output]) => [
2851
+ model,
2852
+ {
2853
+ default: {
2854
+ inputMicrosPerMillionTokens: input,
2855
+ cachedInputMicrosPerMillionTokens: cachedInput,
2856
+ cacheWriteMicrosPerMillionTokens: cacheWrite,
2857
+ outputMicrosPerMillionTokens: output,
2858
+ marginBps: 500
2859
+ }
2860
+ }
2861
+ ])
2862
+ )
2863
+ };
2864
+ var reviewedFreeOpenRouterListPricing = {
2865
+ default: {
2866
+ inputMicrosPerMillionTokens: 0,
2867
+ cachedInputMicrosPerMillionTokens: 0,
2868
+ cacheWriteMicrosPerMillionTokens: 0,
2869
+ outputMicrosPerMillionTokens: 0,
2870
+ marginBps: 500
2871
+ }
2872
+ };
2105
2873
  var SANDBOX_REQUIRED_ENV = {
2106
2874
  // docker/local/none need no credentials (local dev container / in-process / off).
2107
2875
  docker: [],
@@ -2161,6 +2929,7 @@ function optionalEnvironmentValue(name, source) {
2161
2929
  const value = source[name];
2162
2930
  return value && value.trim().length > 0 ? value : void 0;
2163
2931
  }
2932
+ var idleCommandContainmentDisabledWarned = false;
2164
2933
  function getSettings(source = process.env) {
2165
2934
  const optional = (name) => optionalEnvironmentValue(name, source);
2166
2935
  const modelCatalogSource = optional("OPENGENI_MODEL_CATALOG_SOURCE");
@@ -2171,6 +2940,7 @@ function getSettings(source = process.env) {
2171
2940
  deploymentRevision: optional("OPENGENI_DEPLOYMENT_REVISION") ?? optional("SOURCE_VERSION") ?? optional("GITHUB_SHA"),
2172
2941
  serverVersion: optional("OPENGENI_SERVER_VERSION"),
2173
2942
  databaseUrl: optional("OPENGENI_DATABASE_URL"),
2943
+ apiDatabasePoolMax: optional("OPENGENI_API_DATABASE_POOL_MAX"),
2174
2944
  dbSchema: optional("OPENGENI_DB_SCHEMA"),
2175
2945
  rlsStrategy: optional("OPENGENI_RLS_STRATEGY"),
2176
2946
  runtimeDatabaseRole: optional("OPENGENI_RUNTIME_DATABASE_ROLE"),
@@ -2202,26 +2972,32 @@ function getSettings(source = process.env) {
2202
2972
  observabilityMetricsEnabled: optional("OPENGENI_OBSERVABILITY_METRICS_ENABLED"),
2203
2973
  observabilityOtlpEndpoint: optional("OPENGENI_OTEL_EXPORTER_OTLP_ENDPOINT") ?? optional("OTEL_EXPORTER_OTLP_ENDPOINT"),
2204
2974
  observabilityOtlpHeaders: optional("OPENGENI_OTEL_EXPORTER_OTLP_HEADERS") ?? optional("OTEL_EXPORTER_OTLP_HEADERS"),
2975
+ observabilityDiagnosticsEndpoint: optional("OPENGENI_OBSERVABILITY_DIAGNOSTICS_ENDPOINT"),
2976
+ observabilityDiagnosticsHeaders: optional("OPENGENI_OBSERVABILITY_DIAGNOSTICS_HEADERS"),
2205
2977
  analyticsEnabled: optional("OPENGENI_ANALYTICS_ENABLED"),
2206
2978
  analyticsConsentRequired: optional("OPENGENI_ANALYTICS_CONSENT_REQUIRED"),
2207
2979
  analyticsReoClientId: optional("OPENGENI_ANALYTICS_REO_CLIENT_ID"),
2208
2980
  analyticsPosthogProjectKey: optional("OPENGENI_ANALYTICS_POSTHOG_PROJECT_KEY"),
2209
2981
  analyticsPosthogHost: optional("OPENGENI_ANALYTICS_POSTHOG_HOST"),
2210
2982
  analyticsGa4MeasurementId: optional("OPENGENI_ANALYTICS_GA4_MEASUREMENT_ID"),
2983
+ legalPrivacyPolicyUrl: optional("OPENGENI_LEGAL_PRIVACY_POLICY_URL"),
2984
+ legalTermsOfServiceUrl: optional("OPENGENI_LEGAL_TERMS_OF_SERVICE_URL"),
2985
+ supportEmail: optional("OPENGENI_SUPPORT_EMAIL"),
2211
2986
  publicBaseUrl: optional("OPENGENI_PUBLIC_BASE_URL"),
2987
+ documentationUrl: optional("OPENGENI_DOCUMENTATION_URL"),
2212
2988
  mcpOauthEnabled: optional("OPENGENI_MCP_OAUTH_ENABLED"),
2213
- mcpOauthTrustedProxyHops: optional("OPENGENI_MCP_OAUTH_TRUSTED_PROXY_HOPS"),
2989
+ apiTrustedProxyHops: optional("OPENGENI_API_TRUSTED_PROXY_HOPS"),
2990
+ apiTrustedProxyCidrs: optional("OPENGENI_API_TRUSTED_PROXY_CIDRS"),
2214
2991
  webBaseUrl: optional("OPENGENI_WEB_BASE_URL"),
2215
2992
  agentReleasesBaseUrl: optional("OPENGENI_AGENT_RELEASES_BASE_URL"),
2216
2993
  agentStableVersion: optional("OPENGENI_AGENT_STABLE_VERSION"),
2217
2994
  agentBetaVersion: optional("OPENGENI_AGENT_BETA_VERSION"),
2218
2995
  productAccessMode: optional("OPENGENI_PRODUCT_ACCESS_MODE"),
2219
- organizationTenancyCanonicalActivationEnabled: optional(
2220
- "OPENGENI_ORGANIZATION_TENANCY_CANONICAL_ACTIVATION_ENABLED"
2221
- ),
2222
2996
  billingMode: optional("OPENGENI_BILLING_MODE"),
2997
+ verifiedSignupTrialCreditsEnabled: optional("OPENGENI_VERIFIED_SIGNUP_TRIAL_CREDITS_ENABLED"),
2223
2998
  entitlementsMode: optional("OPENGENI_ENTITLEMENTS_MODE"),
2224
2999
  usageLimitsMode: optional("OPENGENI_USAGE_LIMITS_MODE"),
3000
+ usageAllowancesEnabled: optional("OPENGENI_USAGE_ALLOWANCES_ENABLED"),
2225
3001
  staticEntitlementsJson: optional("OPENGENI_STATIC_ENTITLEMENTS_JSON"),
2226
3002
  staticUsageLimitsJson: optional("OPENGENI_STATIC_USAGE_LIMITS_JSON"),
2227
3003
  delegationSecret: optional("OPENGENI_DELEGATION_SECRET"),
@@ -2241,13 +3017,16 @@ function getSettings(source = process.env) {
2241
3017
  environmentsEncryptionKey: optional("OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY"),
2242
3018
  integrationsEnabled: optional("OPENGENI_INTEGRATIONS_ENABLED"),
2243
3019
  integrationsStateSecret: optional("OPENGENI_INTEGRATIONS_STATE_SECRET"),
3020
+ integrationsOauthShortStateEnabled: optional("OPENGENI_INTEGRATIONS_OAUTH_SHORT_STATE_ENABLED"),
2244
3021
  integrationsAllowPrivateNetworkTargets: optional(
2245
3022
  "OPENGENI_INTEGRATIONS_ALLOW_PRIVATE_NETWORK_TARGETS"
2246
3023
  ),
2247
3024
  integrationsOauthClientsJson: optional("OPENGENI_INTEGRATIONS_OAUTH_CLIENTS_JSON"),
3025
+ gmailWatchTopicName: optional("OPENGENI_GMAIL_WATCH_TOPIC_NAME"),
2248
3026
  slackClientId: optional("OPENGENI_SLACK_CLIENT_ID"),
2249
3027
  slackClientSecret: optional("OPENGENI_SLACK_CLIENT_SECRET"),
2250
3028
  slackSigningSecret: optional("OPENGENI_SLACK_SIGNING_SECRET"),
3029
+ slackAccessMode: optional("OPENGENI_SLACK_ACCESS_MODE"),
2251
3030
  slackBotDisplayName: optional("OPENGENI_SLACK_BOT_DISPLAY_NAME"),
2252
3031
  slackCommand: optional("OPENGENI_SLACK_COMMAND"),
2253
3032
  googleDriveClientId: optional("OPENGENI_GOOGLE_DRIVE_CLIENT_ID"),
@@ -2282,10 +3061,6 @@ function getSettings(source = process.env) {
2282
3061
  goalIdleBackoffMs: optional("OPENGENI_GOAL_IDLE_BACKOFF_MS"),
2283
3062
  goalIdleBackoffMaxMs: optional("OPENGENI_GOAL_IDLE_BACKOFF_MAX_MS"),
2284
3063
  childLifecycleNoticesEnabled: optional("OPENGENI_CHILD_LIFECYCLE_NOTICES_ENABLED"),
2285
- hostMcpAuthoritySourceAdmissionEnabled: optional(
2286
- "OPENGENI_HOST_MCP_AUTHORITY_SOURCE_ADMISSION_ENABLED"
2287
- ),
2288
- hostMcpCredentialResolversJson: optional("OPENGENI_HOST_MCP_CREDENTIAL_RESOLVERS_JSON"),
2289
3064
  slackWorkspaceRoutingEnabled: optional("OPENGENI_SLACK_WORKSPACE_ROUTING_ENABLED"),
2290
3065
  agentMaxModelCallsPerTurn: optional("OPENGENI_AGENT_MAX_MODEL_CALLS_PER_TURN"),
2291
3066
  contextWindowTokens: optional("OPENGENI_CONTEXT_WINDOW_TOKENS"),
@@ -2300,10 +3075,12 @@ function getSettings(source = process.env) {
2300
3075
  authAllowMetrics: optional("OPENGENI_AUTH_ALLOW_METRICS"),
2301
3076
  apiHost: optional("OPENGENI_API_HOST"),
2302
3077
  apiPort: optional("OPENGENI_API_PORT"),
3078
+ apiMetricsPort: optional("OPENGENI_API_METRICS_PORT"),
2303
3079
  workerHttpPort: optional("OPENGENI_WORKER_HTTP_PORT"),
2304
3080
  opengeniMcpInternalUrl: optional("OPENGENI_MCP_INTERNAL_URL"),
2305
3081
  opengeniMcpUrl: optional("OPENGENI_MCP_URL"),
2306
3082
  corsAllowOriginRegex: optional("OPENGENI_CORS_ALLOW_ORIGIN_REGEX"),
3083
+ localAllowedOrigins: optional("OPENGENI_LOCAL_ALLOWED_ORIGINS"),
2307
3084
  openaiProvider: optional("OPENGENI_OPENAI_PROVIDER"),
2308
3085
  openaiApiKey: optional("OPENGENI_OPENAI_API_KEY") ?? optional("OPENAI_API_KEY"),
2309
3086
  openaiBaseUrl: optional("OPENGENI_OPENAI_BASE_URL") ?? optional("OPENAI_BASE_URL"),
@@ -2362,6 +3139,7 @@ function getSettings(source = process.env) {
2362
3139
  modelProvidersJson: optional("OPENGENI_MODEL_PROVIDERS_JSON"),
2363
3140
  codexSubscriptionEnabled: optional("OPENGENI_CODEX_SUBSCRIPTION_ENABLED"),
2364
3141
  supergrokSubscriptionEnabled: optional("OPENGENI_SUPERGROK_SUBSCRIPTION_ENABLED"),
3142
+ claudeSubscriptionEnabled: optional("OPENGENI_CLAUDE_SUBSCRIPTION_ENABLED"),
2365
3143
  supergrokResponseStreamIdleTimeoutMs: optional(
2366
3144
  "OPENGENI_SUPERGROK_RESPONSE_STREAM_IDLE_TIMEOUT_MS"
2367
3145
  ),
@@ -2370,13 +3148,23 @@ function getSettings(source = process.env) {
2370
3148
  lazyToolSearchEnabled: optional("OPENGENI_LAZY_TOOL_SEARCH_ENABLED"),
2371
3149
  codexFleetPolicyShadowEnabled: optional("OPENGENI_CODEX_FLEET_POLICY_SHADOW_ENABLED"),
2372
3150
  codexProductSku: optional("OPENGENI_CODEX_PRODUCT_SKU"),
3151
+ reasoningConfigurationUpdatesEnabled: optional(
3152
+ "OPENGENI_REASONING_CONFIGURATION_UPDATES_ENABLED"
3153
+ ),
2373
3154
  openaiReasoningEffort: optional("OPENGENI_OPENAI_REASONING_EFFORT"),
2374
3155
  openaiAllowedReasoningEfforts: optional("OPENGENI_OPENAI_ALLOWED_REASONING_EFFORTS"),
3156
+ creditsDefaultModel: optional("OPENGENI_CREDITS_DEFAULT_MODEL"),
3157
+ creditsDefaultReasoningEffort: optional("OPENGENI_CREDITS_DEFAULT_REASONING_EFFORT"),
2375
3158
  openaiResponsesTransport: optional("OPENGENI_OPENAI_RESPONSES_TRANSPORT"),
2376
3159
  openaiProviderItemIds: optional("OPENGENI_OPENAI_PROVIDER_ITEM_IDS"),
2377
3160
  openaiReasoningEncryptedContent: optional("OPENGENI_OPENAI_REASONING_ENCRYPTED_CONTENT"),
2378
3161
  openaiMaxRetries: optional("OPENGENI_OPENAI_MAX_RETRIES"),
2379
3162
  webSearchEnabled: optional("OPENGENI_WEB_SEARCH_ENABLED"),
3163
+ jevApiKey: optional("OPENGENI_JEV_API_KEY"),
3164
+ jevBaseUrl: optional("OPENGENI_JEV_BASE_URL"),
3165
+ jevModel: optional("OPENGENI_JEV_MODEL"),
3166
+ jevRequestTimeoutMs: optional("OPENGENI_JEV_REQUEST_TIMEOUT_MS"),
3167
+ codeSearchMode: optional("OPENGENI_CODE_SEARCH_MODE"),
2380
3168
  agentInstructionsTemplate: optional("OPENGENI_AGENT_INSTRUCTIONS_TEMPLATE"),
2381
3169
  azureOpenaiBaseUrl: optional("OPENGENI_AZURE_OPENAI_BASE_URL"),
2382
3170
  azureOpenaiEndpoint: optional("OPENGENI_AZURE_OPENAI_ENDPOINT"),
@@ -2393,6 +3181,7 @@ function getSettings(source = process.env) {
2393
3181
  dockerWorkspaceBaseDir: optional("OPENGENI_DOCKER_WORKSPACE_BASE_DIR"),
2394
3182
  modalAppName: optional("OPENGENI_MODAL_APP_NAME"),
2395
3183
  modalImageRef: optional("OPENGENI_MODAL_IMAGE_REF") ?? DEFAULT_MODAL_IMAGE_REF,
3184
+ modalCommandSupervisionEnabled: optional("OPENGENI_MODAL_COMMAND_SUPERVISION_ENABLED"),
2396
3185
  modalImageId: optional("OPENGENI_MODAL_IMAGE_ID"),
2397
3186
  modalImageRegistrySecret: optional("OPENGENI_MODAL_IMAGE_REGISTRY_SECRET"),
2398
3187
  modalTimeoutSeconds: optional("OPENGENI_MODAL_TIMEOUT_SECONDS"),
@@ -2444,6 +3233,9 @@ function getSettings(source = process.env) {
2444
3233
  blaxelTtl: optional("OPENGENI_BLAXEL_TTL"),
2445
3234
  cloudflareWorkerUrl: optional("OPENGENI_CLOUDFLARE_WORKER_URL"),
2446
3235
  cloudflareApiKey: optional("OPENGENI_CLOUDFLARE_API_KEY"),
3236
+ experimentalBrowserContextPoolEnabled: optional(
3237
+ "OPENGENI_EXPERIMENTAL_BROWSER_CONTEXT_POOL_ENABLED"
3238
+ ),
2447
3239
  browserbaseApiKey: optional("OPENGENI_BROWSERBASE_API_KEY"),
2448
3240
  kernelApiKey: optional("OPENGENI_KERNEL_API_KEY"),
2449
3241
  kernelEndpoint: optional("OPENGENI_KERNEL_ENDPOINT"),
@@ -2492,6 +3284,7 @@ function getSettings(source = process.env) {
2492
3284
  sandboxViewerHolderTtlMs: optional("OPENGENI_SANDBOX_VIEWER_HOLDER_TTL_MS"),
2493
3285
  sandboxInteractionHolderTtlMs: optional("OPENGENI_SANDBOX_INTERACTION_HOLDER_TTL_MS"),
2494
3286
  sandboxIdleGraceMs: optional("OPENGENI_SANDBOX_IDLE_GRACE_MS"),
3287
+ sandboxIdleCommandContainmentMs: optional("OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS"),
2495
3288
  sandboxSnapshotIntervalMs: optional("OPENGENI_SANDBOX_SNAPSHOT_INTERVAL_MS"),
2496
3289
  sandboxSnapshotTimeoutMs: optional("OPENGENI_SANDBOX_SNAPSHOT_TIMEOUT_MS"),
2497
3290
  sandboxDrainSnapshotTimeoutMs: optional("OPENGENI_SANDBOX_DRAIN_SNAPSHOT_TIMEOUT_MS"),
@@ -2505,9 +3298,11 @@ function getSettings(source = process.env) {
2505
3298
  sandboxWarmRateMicrosPerSecondJson: optional(
2506
3299
  "OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON"
2507
3300
  ),
3301
+ sandboxWarmBillingMode: optional("OPENGENI_SANDBOX_WARM_BILLING_MODE"),
2508
3302
  sandboxMaxWarmSecondsPerWorkspace: optional("OPENGENI_SANDBOX_MAX_WARM_SECONDS_PER_WORKSPACE"),
2509
3303
  sandboxPreparationProfiles: optional("OPENGENI_SANDBOX_PREPARATION_PROFILES"),
2510
3304
  sandboxEnvAllowlist: optional("OPENGENI_SANDBOX_ENV_ALLOWLIST"),
3305
+ sandboxImageAllowlist: optional("OPENGENI_SANDBOX_IMAGE_ALLOWLIST"),
2511
3306
  objectStorageEndpoint: optional("OPENGENI_OBJECT_STORAGE_ENDPOINT"),
2512
3307
  objectStorageInternalEndpoint: optional("OPENGENI_OBJECT_STORAGE_INTERNAL_ENDPOINT"),
2513
3308
  objectStorageSandboxEndpoint: optional("OPENGENI_OBJECT_STORAGE_SANDBOX_ENDPOINT"),
@@ -2534,6 +3329,13 @@ function getSettings(source = process.env) {
2534
3329
  documentEmbeddingDimensions: optional("OPENGENI_DOCUMENT_EMBEDDING_DIMENSIONS"),
2535
3330
  documentEmbeddingApiKey: optional("OPENGENI_DOCUMENT_EMBEDDING_API_KEY"),
2536
3331
  documentEmbeddingBaseUrl: optional("OPENGENI_DOCUMENT_EMBEDDING_BASE_URL"),
3332
+ documentEmbeddingBillingMode: optional("OPENGENI_DOCUMENT_EMBEDDING_BILLING_MODE"),
3333
+ documentEmbeddingCreditsActivatedAt: optional(
3334
+ "OPENGENI_DOCUMENT_EMBEDDING_CREDITS_ACTIVATED_AT"
3335
+ ),
3336
+ documentEmbeddingRateMicrosPerMillionBytes: optional(
3337
+ "OPENGENI_DOCUMENT_EMBEDDING_RATE_MICROS_PER_MILLION_BYTES"
3338
+ ),
2537
3339
  documentCurationProvider: optional("OPENGENI_DOCUMENT_CURATION_PROVIDER"),
2538
3340
  documentCurationModel: optional("OPENGENI_DOCUMENT_CURATION_MODEL"),
2539
3341
  documentCurationApiKey: optional("OPENGENI_DOCUMENT_CURATION_API_KEY"),
@@ -2568,7 +3370,9 @@ function getSettings(source = process.env) {
2568
3370
  managedAuthGoogleClientSecret: optional("OPENGENI_MANAGED_AUTH_GOOGLE_CLIENT_SECRET"),
2569
3371
  managedAuthGithubClientId: optional("OPENGENI_MANAGED_AUTH_GITHUB_CLIENT_ID"),
2570
3372
  managedAuthGithubClientSecret: optional("OPENGENI_MANAGED_AUTH_GITHUB_CLIENT_SECRET"),
3373
+ allowedUserEmails: source.OPENGENI_ALLOWED_USER_EMAILS === void 0 ? void 0 : source.OPENGENI_ALLOWED_USER_EMAILS.split(",").map((email) => email.trim()),
2571
3374
  managedAuthSessionSetMode: optional("OPENGENI_MANAGED_AUTH_SESSION_SET_MODE"),
3375
+ managedAuthNewSignupsEnabled: optional("OPENGENI_MANAGED_AUTH_NEW_SIGNUPS_ENABLED"),
2572
3376
  organizationUserSetupEmailTokenTransport: optional(
2573
3377
  "OPENGENI_ORGANIZATION_USER_SETUP_EMAIL_TOKEN_TRANSPORT"
2574
3378
  ),
@@ -2587,12 +3391,54 @@ function getSettings(source = process.env) {
2587
3391
  const settings = {
2588
3392
  ...parsed,
2589
3393
  sandboxIdleGraceMs: raw.sandboxIdleGraceMs === void 0 && parsed.sandboxBackend === "modal" ? Math.min(9e5, Math.floor(parsed.modalTimeoutSeconds * 1e3 / 2)) : parsed.sandboxIdleGraceMs,
2590
- sandboxRotationLeadMs: raw.sandboxRotationLeadMs === void 0 && parsed.sandboxBackend === "modal" ? Math.min(36e5, Math.floor(parsed.modalTimeoutSeconds * 1e3 / 2)) : parsed.sandboxRotationLeadMs,
3394
+ sandboxRotationLeadMs: raw.sandboxRotationLeadMs === void 0 && parsed.sandboxBackend === "modal" ? Math.min(
3395
+ 36e5,
3396
+ Math.max(
3397
+ Math.floor(parsed.modalTimeoutSeconds * 1e3 / 2),
3398
+ SANDBOX_DEADLINE_COMMAND_STOP_GRACE_MS + sandboxArchiveCaptureTimeoutMs({
3399
+ sandboxSnapshotTimeoutMs: Math.max(
3400
+ parsed.sandboxSnapshotTimeoutMs,
3401
+ parsed.sandboxDrainSnapshotTimeoutMs ?? parsed.sandboxSnapshotTimeoutMs
3402
+ )
3403
+ }) + 2 * parsed.sandboxLeaseReaperPeriodMs + 1
3404
+ )
3405
+ ) : parsed.sandboxRotationLeadMs,
2591
3406
  mcpServers: ensureBuiltInMcpServers(parsed)
2592
3407
  };
3408
+ if (raw.sandboxIdleCommandContainmentMs === void 0) {
3409
+ const modalIdleCeilingMs = settings.sandboxBackend === "modal" && settings.modalIdleTimeoutSeconds !== void 0 ? settings.modalIdleTimeoutSeconds * 1e3 - settings.sandboxLeaseReaperPeriodMs - sandboxArchiveCaptureTimeoutMs({
3410
+ sandboxSnapshotTimeoutMs: effectiveSandboxDrainSnapshotTimeoutMs(settings)
3411
+ }) - 1 : Number.POSITIVE_INFINITY;
3412
+ const derived = Math.min(
3413
+ 18e5,
3414
+ Math.floor((settings.sandboxIdleGraceMs + settings.sandboxRotationLeadMs) / 2),
3415
+ modalIdleCeilingMs
3416
+ );
3417
+ if (derived > settings.sandboxIdleGraceMs) {
3418
+ settings.sandboxIdleCommandContainmentMs = derived;
3419
+ } else {
3420
+ settings.sandboxIdleCommandContainmentMs = void 0;
3421
+ if (!idleCommandContainmentDisabledWarned) {
3422
+ idleCommandContainmentDisabledWarned = true;
3423
+ console.warn(
3424
+ `[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.`
3425
+ );
3426
+ }
3427
+ }
3428
+ }
3429
+ warnRetiredOrganizationTenancyActivationSwitch(source);
2593
3430
  validateSettings(settings, source);
2594
3431
  return settings;
2595
3432
  }
3433
+ var retiredOrganizationTenancyActivationSwitchWarned = false;
3434
+ function warnRetiredOrganizationTenancyActivationSwitch(source) {
3435
+ if (retiredOrganizationTenancyActivationSwitchWarned) return;
3436
+ if (source.OPENGENI_ORGANIZATION_TENANCY_CANONICAL_ACTIVATION_ENABLED === void 0) return;
3437
+ retiredOrganizationTenancyActivationSwitchWarned = true;
3438
+ console.warn(
3439
+ "[config] OPENGENI_ORGANIZATION_TENANCY_CANONICAL_ACTIVATION_ENABLED is retired and ignored: every organization is session-tenancy activated (migration 0611). Remove it from the deployment."
3440
+ );
3441
+ }
2596
3442
  var LOCAL_FIRST_PARTY_DELEGATION_SECRET = "opengeni-local-first-party-delegation-secret-v1";
2597
3443
  function resolveFirstPartyDelegationSecret(settings) {
2598
3444
  const explicit = settings.delegationSecret?.trim();
@@ -2604,20 +3450,24 @@ function resolveFirstPartyDelegationSecret(settings) {
2604
3450
  return settings.productAccessMode === "local" && (settings.environment === "local" || settings.environment === "test") ? LOCAL_FIRST_PARTY_DELEGATION_SECRET : void 0;
2605
3451
  }
2606
3452
  function resolveFirstPartyMcpToolPolicy(settings) {
2607
- const allowed = settings.allowedFirstPartyMcpTools ?? [...FIRST_PARTY_MCP_TOOL_NAMES];
2608
- const allowedSet = new Set(allowed);
2609
- const defaults = settings.defaultFirstPartyMcpTools ?? [...DEFAULT_FIRST_PARTY_MCP_TOOLS];
3453
+ const allowed2 = currentAgentLearningToolSelection(
3454
+ settings.allowedFirstPartyMcpTools ?? [...FIRST_PARTY_MCP_TOOL_NAMES]
3455
+ ).filter((tool) => !isRetiredNativeAtlassianTool(tool));
3456
+ const allowedSet = new Set(allowed2);
3457
+ const defaults = currentAgentLearningToolSelection(
3458
+ settings.defaultFirstPartyMcpTools ?? [...DEFAULT_FIRST_PARTY_MCP_TOOLS]
3459
+ );
2610
3460
  return {
2611
3461
  default: defaults.filter((tool) => allowedSet.has(tool)),
2612
- allowed: [...allowed]
3462
+ allowed: [...allowed2]
2613
3463
  };
2614
3464
  }
2615
3465
  function allowedFirstPartyMcpToolsForSession(settings, selected) {
2616
3466
  const policy = resolveFirstPartyMcpToolPolicy(settings);
2617
- const allowed = new Set(policy.allowed);
2618
- const tools = new Set(selected ?? policy.default);
3467
+ const allowed2 = new Set(policy.allowed);
3468
+ const tools = new Set(currentAgentLearningToolSelection(selected ?? policy.default));
2619
3469
  if (tools.has("goal_pause")) tools.add("goal_resume");
2620
- return [...tools].filter((tool) => allowed.has(tool));
3470
+ return [...tools].filter((tool) => allowed2.has(tool));
2621
3471
  }
2622
3472
  function effectiveModalIdleTimeoutSeconds(settings) {
2623
3473
  return settings.modalIdleTimeoutSeconds ?? settings.modalTimeoutSeconds;
@@ -3098,7 +3948,9 @@ function openRouterRegistryProvider(settings, input) {
3098
3948
  }
3099
3949
  function configuredRegistryProviders(settings) {
3100
3950
  const providers = parseModelProvidersJson(settings.modelProvidersJson);
3101
- const injected = [...providers];
3951
+ const injected = providers.filter(
3952
+ (provider) => settings.claudeSubscriptionEnabled || !(provider.api === "anthropic-messages" && provider.anthropic?.auth === "oauth")
3953
+ );
3102
3954
  if (settings.vercelAiGatewayApiKey && configuredGatewayCatalogModels(settings).length > 0) {
3103
3955
  injected.push(
3104
3956
  gatewayRegistryProvider(settings, {
@@ -3114,6 +3966,37 @@ function configuredRegistryProviders(settings) {
3114
3966
  if (openrouter) injected.push(openrouter);
3115
3967
  return injected;
3116
3968
  }
3969
+ function withDirectModelProviders(settings, connections) {
3970
+ const providers = parseModelProvidersJson(settings.modelProvidersJson).filter(
3971
+ (provider) => !provider.id.startsWith("workspace-openai-") && !provider.id.startsWith("workspace-azure-openai-")
3972
+ );
3973
+ for (const connection of connections) {
3974
+ const spec = directModelConnectionSpec(connection);
3975
+ if (!spec) continue;
3976
+ providers.push({
3977
+ kind: spec.provider === "openai" ? "direct-openai-workspace" : "direct-azure-workspace",
3978
+ id: spec.providerId,
3979
+ label: spec.provider === "openai" ? "Your OpenAI" : "Your Azure OpenAI",
3980
+ api: "responses",
3981
+ wireProfile: spec.provider === "openai" ? "openai" : "azure-openai",
3982
+ baseUrl: spec.baseUrl,
3983
+ ...connection.apiKey ? { apiKey: connection.apiKey } : {},
3984
+ models: [
3985
+ {
3986
+ id: spec.modelId,
3987
+ upstreamModelId: spec.model,
3988
+ label: spec.model,
3989
+ capabilities: legacyModelCapabilities(settings, {
3990
+ reasoningEffort: false,
3991
+ hostedWebSearch: false
3992
+ }),
3993
+ toolOutputTruncationTokens: settings.modelToolOutputTruncationTokens
3994
+ }
3995
+ ]
3996
+ });
3997
+ }
3998
+ return { ...settings, modelProvidersJson: JSON.stringify(providers) };
3999
+ }
3117
4000
  function withWorkspaceGatewayCatalogProvider(settings, customModels = []) {
3118
4001
  const providers = parseModelProvidersJson(settings.modelProvidersJson);
3119
4002
  const withoutWorkspace = providers.filter(
@@ -3226,8 +4109,8 @@ function productLabelForModelId(modelId) {
3226
4109
  function productShortLabelForModelId(modelId) {
3227
4110
  const slug = modelId.startsWith(CODEX_MODEL_ID_PREFIX) ? modelId.slice(CODEX_MODEL_ID_PREFIX.length) : modelId;
3228
4111
  switch (slug) {
3229
- case "grok-4.6":
3230
- return "4.6";
4112
+ case "grok-4.7":
4113
+ return "4.7";
3231
4114
  case "gpt-5.6-sol":
3232
4115
  return "5.6 Sol";
3233
4116
  case "gpt-5.6-terra":
@@ -3236,6 +4119,10 @@ function productShortLabelForModelId(modelId) {
3236
4119
  return "5.6 Luna";
3237
4120
  case "gpt-6-astra":
3238
4121
  return "6 Astra";
4122
+ case "gpt-6-sol":
4123
+ return "6 Sol";
4124
+ case "gpt-6-luna":
4125
+ return "6 Luna";
3239
4126
  default:
3240
4127
  return null;
3241
4128
  }
@@ -3255,7 +4142,7 @@ function builtinContextLimitsForModel(settings, modelId) {
3255
4142
  return { contextWindowTokens: settings.contextWindowTokens };
3256
4143
  }
3257
4144
  function builtinLatencyModesForModel(modelId) {
3258
- if (isBuiltinGpt56ModelId(modelId) || modelId.startsWith("codex/gpt-5.6-") || modelId === "codex/gpt-6-astra") {
4145
+ if (isBuiltinGpt56ModelId(modelId) || /^gpt-6(?:\.\d+)?-/u.test(modelId) || modelId.startsWith("codex/gpt-5.6-") || /^codex\/gpt-6(?:\.\d+)?-/u.test(modelId)) {
3259
4146
  return [
3260
4147
  { id: "standard", upstream: "supported", runnable: true },
3261
4148
  {
@@ -3268,12 +4155,26 @@ function builtinLatencyModesForModel(modelId) {
3268
4155
  }
3269
4156
  return [{ id: "standard", upstream: "unknown", runnable: true }];
3270
4157
  }
4158
+ function isReviewedGptVisionModel(slug) {
4159
+ return slug.startsWith("gpt-5.6-") || /^gpt-6(?:\.\d+)?-/u.test(slug);
4160
+ }
4161
+ function reviewedCodexCatalogCapabilities(slug, capabilities) {
4162
+ if (!/^gpt-6(?:\.\d+)?-/u.test(slug)) return capabilities;
4163
+ const fast = builtinLatencyModesForModel(`${CODEX_MODEL_ID_PREFIX}${slug}`).find(
4164
+ (mode) => mode.id === "fast"
4165
+ );
4166
+ return normalizeCapabilities({
4167
+ ...capabilities,
4168
+ inputModalities: [.../* @__PURE__ */ new Set([...capabilities.inputModalities, "image"])],
4169
+ latencyModes: fast && !capabilities.latencyModes.some((mode) => mode.id === "fast") ? [...capabilities.latencyModes, fast] : capabilities.latencyModes
4170
+ });
4171
+ }
3271
4172
  function builtinPromptCachingForModel(modelId) {
3272
4173
  const slug = modelId.startsWith(CODEX_MODEL_ID_PREFIX) ? modelId.slice(CODEX_MODEL_ID_PREFIX.length) : modelId;
3273
- return slug.startsWith("gpt-5.6-") ? { upstream: "supported", runnable: true, mode: "implicit" } : void 0;
4174
+ return slug.startsWith("gpt-5.6-") || slug.startsWith("gpt-6-") ? { upstream: "supported", runnable: true, mode: "implicit" } : void 0;
3274
4175
  }
3275
4176
  function builtinHostedImageGenerationForModel(settings, modelId) {
3276
- return settings.openaiProvider === "openai" && isDirectOpenAiApiBaseUrl(settings.openaiBaseUrl) && isBuiltinGpt56ModelId(modelId);
4177
+ return settings.openaiProvider === "openai" && isDirectOpenAiApiBaseUrl(settings.openaiBaseUrl) && (isBuiltinGpt56ModelId(modelId) || modelId.startsWith("gpt-6-"));
3277
4178
  }
3278
4179
  function isDirectOpenAiApiBaseUrl(baseUrl) {
3279
4180
  if (baseUrl === void 0) return true;
@@ -3312,11 +4213,21 @@ function runnableLatencyModesForModel(settings, modelId) {
3312
4213
  function assertLatencyModeRunnable(settings, modelId, latencyMode) {
3313
4214
  const runnable = runnableLatencyModesForModel(settings, modelId);
3314
4215
  if (!runnable.includes(latencyMode)) {
3315
- throw new Error(
3316
- `latency mode ${latencyMode} is not runnable for model ${modelId} (allowed: ${runnable.join(", ")})`
3317
- );
4216
+ throw new UnsupportedLatencyModeError(modelId, latencyMode, runnable);
3318
4217
  }
3319
4218
  }
4219
+ var UnsupportedLatencyModeError = class extends Error {
4220
+ constructor(modelId, latencyMode, allowedLatencyModes) {
4221
+ super(
4222
+ `latency mode ${latencyMode} is not runnable for model ${modelId} (allowed: ${allowedLatencyModes.join(", ")})`
4223
+ );
4224
+ this.modelId = modelId;
4225
+ this.latencyMode = latencyMode;
4226
+ this.allowedLatencyModes = allowedLatencyModes;
4227
+ this.name = "UnsupportedLatencyModeError";
4228
+ }
4229
+ code = "UNSUPPORTED_LATENCY_MODE";
4230
+ };
3320
4231
  function registryCredentialSource(provider) {
3321
4232
  switch (provider.kind) {
3322
4233
  case "anonymous":
@@ -3325,10 +4236,17 @@ function registryCredentialSource(provider) {
3325
4236
  return { kind: "connected_subscription", provider: "codex" };
3326
4237
  case "xai-subscription":
3327
4238
  return { kind: "connected_subscription", provider: "xai" };
4239
+ case "claude-subscription-workspace":
4240
+ case "claude-subscription-organization":
4241
+ return { kind: "connected_subscription", provider: "claude" };
3328
4242
  case "vercel-gateway-workspace":
4243
+ case "direct-openai-workspace":
4244
+ case "direct-azure-workspace":
3329
4245
  case "openrouter-workspace":
4246
+ case "anthropic-workspace":
3330
4247
  return { kind: "workspace_connection", mechanism: "api_key" };
3331
4248
  case "vercel-gateway-organization":
4249
+ case "anthropic-organization":
3332
4250
  case "openrouter-organization":
3333
4251
  return { kind: "organization_connection", mechanism: "api_key" };
3334
4252
  case "api-key":
@@ -3348,11 +4266,17 @@ function registryBilling(provider) {
3348
4266
  return { upstreamPayer: "deployment", metering: "external" };
3349
4267
  case "codex-subscription":
3350
4268
  case "xai-subscription":
4269
+ case "claude-subscription-workspace":
4270
+ case "claude-subscription-organization":
3351
4271
  return { upstreamPayer: "connected_subscription", metering: "external" };
3352
4272
  case "vercel-gateway-workspace":
4273
+ case "direct-openai-workspace":
4274
+ case "direct-azure-workspace":
3353
4275
  case "openrouter-workspace":
4276
+ case "anthropic-workspace":
3354
4277
  return { upstreamPayer: "workspace", metering: "external" };
3355
4278
  case "vercel-gateway-organization":
4279
+ case "anthropic-organization":
3356
4280
  case "openrouter-organization":
3357
4281
  return { upstreamPayer: "organization", metering: "external" };
3358
4282
  case "api-key":
@@ -3383,6 +4307,9 @@ function staticRequestMetadataForDigest(provider) {
3383
4307
  const publicHeaders = new Set(provider.publicDefaultHeaderNames ?? []);
3384
4308
  const publicQuery = new Set(provider.publicDefaultQueryNames ?? []);
3385
4309
  return {
4310
+ ...provider.anthropic ? {
4311
+ anthropic: (({ identity: _identity, credentialBinding: _binding, ...options }) => options)(provider.anthropic)
4312
+ } : {},
3386
4313
  headers: Object.entries(provider.defaultHeaders ?? {}).sort(([left], [right]) => left.localeCompare(right)).map(
3387
4314
  ([name, value]) => publicHeaders.has(name) ? { name, classification: "public", value } : { name, classification: "secret" }
3388
4315
  ),
@@ -3424,7 +4351,8 @@ function definitionVersionFor(model, provider, options = {}) {
3424
4351
  ...includeWireProfile ? { wireProfile: provider.wireProfile } : {},
3425
4352
  baseUrl: provider.baseUrl ?? null,
3426
4353
  defaultHeaders: requestMetadata.headers,
3427
- defaultQuery: requestMetadata.query
4354
+ defaultQuery: requestMetadata.query,
4355
+ ...requestMetadata.anthropic ? { anthropic: requestMetadata.anthropic } : {}
3428
4356
  },
3429
4357
  credentialSource: model.credentialSource,
3430
4358
  billing: model.billing,
@@ -3446,6 +4374,39 @@ function legacyImplicitOpenAiDefinitionVersionFor(model, provider) {
3446
4374
  includeWireProfile: false
3447
4375
  });
3448
4376
  }
4377
+ function legacyCodexAstraImplicitCachingDefinitionVersionFor(model, provider) {
4378
+ 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" })) {
4379
+ return null;
4380
+ }
4381
+ const { definitionVersion: _definitionVersion, ...modelWithoutVersion } = model;
4382
+ const { promptCaching: _promptCaching, ...capabilities } = model.capabilities;
4383
+ return definitionVersionFor({ ...modelWithoutVersion, capabilities }, provider);
4384
+ }
4385
+ function matchesAdditiveCapabilityDefinitionVersion(model, provider, policy) {
4386
+ const { definitionVersion: _definitionVersion, ...modelWithoutVersion } = model;
4387
+ const { latencyModes, inputModalities } = model.capabilities;
4388
+ for (let latencyMask = 1; latencyMask < 1 << latencyModes.length; latencyMask += 1) {
4389
+ const retainedModes = latencyModes.filter((_mode, index) => latencyMask & 1 << index);
4390
+ if (!retainedModes.some((mode) => mode.id === policy.latencyMode && mode.runnable)) {
4391
+ continue;
4392
+ }
4393
+ for (let inputMask = 1; inputMask < 1 << inputModalities.length; inputMask += 1) {
4394
+ const retainedInputs = inputModalities.filter((_modality, index) => inputMask & 1 << index);
4395
+ if (retainedModes.length === latencyModes.length && retainedInputs.length === inputModalities.length) {
4396
+ continue;
4397
+ }
4398
+ const capabilities = {
4399
+ ...model.capabilities,
4400
+ latencyModes: retainedModes,
4401
+ inputModalities: retainedInputs
4402
+ };
4403
+ if (policy.definitionVersion === definitionVersionFor({ ...modelWithoutVersion, capabilities }, provider)) {
4404
+ return true;
4405
+ }
4406
+ }
4407
+ }
4408
+ return false;
4409
+ }
3449
4410
  function builtinProviderId(settings) {
3450
4411
  return settings.openaiProvider === "azure" ? "azure" : "openai";
3451
4412
  }
@@ -3467,10 +4428,10 @@ function configuredProviders(settings, source = process.env) {
3467
4428
  if (settings.openaiProvider === "azure") {
3468
4429
  const baseUrl = settings.azureOpenaiBaseUrl ?? settings.azureOpenaiEndpoint;
3469
4430
  builtin.baseUrl = baseUrl ? normalizeRegistryBaseUrl(baseUrl, builtin.id) : void 0;
3470
- builtin.apiKey = settings.azureOpenaiApiKey ?? settings.azureOpenaiAdToken;
4431
+ builtin.apiKey = usableDeploymentSecret(settings.azureOpenaiApiKey) ?? settings.azureOpenaiAdToken;
3471
4432
  } else {
3472
4433
  builtin.baseUrl = settings.openaiBaseUrl ? normalizeRegistryBaseUrl(settings.openaiBaseUrl, builtin.id) : void 0;
3473
- builtin.apiKey = settings.openaiApiKey;
4434
+ builtin.apiKey = usableDeploymentSecret(settings.openaiApiKey);
3474
4435
  }
3475
4436
  const registry = configuredRegistryProviders(settings).map(
3476
4437
  (provider) => ({
@@ -3478,6 +4439,7 @@ function configuredProviders(settings, source = process.env) {
3478
4439
  label: provider.label ?? provider.id,
3479
4440
  kind: provider.kind,
3480
4441
  api: provider.api,
4442
+ anthropic: provider.anthropic,
3481
4443
  wireProfile: provider.wireProfile,
3482
4444
  builtin: false,
3483
4445
  baseUrl: provider.baseUrl,
@@ -3492,11 +4454,17 @@ function configuredProviders(settings, source = process.env) {
3492
4454
  );
3493
4455
  return [builtin, ...registry];
3494
4456
  }
4457
+ function codexUpstreamModelSlugs(settings) {
4458
+ if (settings.resolvedCodexModelsJson === void 0) return [...CODEX_FALLBACK_MODEL_SLUGS];
4459
+ return z2.array(CodexCatalogModelSchema).parse(JSON.parse(settings.resolvedCodexModelsJson)).filter((model) => !model.retired).map((model) => model.upstreamModelId);
4460
+ }
3495
4461
  function withCodexCatalogProvider(settings) {
3496
4462
  const providers = parseModelProvidersJson(settings.modelProvidersJson);
3497
4463
  if (providers.some((provider2) => provider2.id === CODEX_PROVIDER_ID)) {
3498
4464
  return settings;
3499
4465
  }
4466
+ 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);
4467
+ if (catalogModels?.length === 0) return settings;
3500
4468
  const provider = {
3501
4469
  kind: "codex-subscription",
3502
4470
  id: CODEX_PROVIDER_ID,
@@ -3504,12 +4472,12 @@ function withCodexCatalogProvider(settings) {
3504
4472
  api: "responses",
3505
4473
  wireProfile: "openai",
3506
4474
  baseUrl: CODEX_PROVIDER_BASE_URL,
3507
- models: CODEX_FALLBACK_MODEL_SLUGS.map((slug) => {
4475
+ models: catalogModels ?? CODEX_FALLBACK_MODEL_SLUGS.map((slug) => {
3508
4476
  const capabilities = {
3509
4477
  ...legacyModelCapabilities(settings, {
3510
4478
  reasoningEffort: true,
3511
4479
  hostedWebSearch: true,
3512
- vision: slug.startsWith("gpt-5.6-") || slug === "gpt-6-astra"
4480
+ vision: isReviewedGptVisionModel(slug)
3513
4481
  }),
3514
4482
  ...builtinPromptCachingForModel(`${CODEX_MODEL_ID_PREFIX}${slug}`) ? {
3515
4483
  promptCaching: builtinPromptCachingForModel(`${CODEX_MODEL_ID_PREFIX}${slug}`)
@@ -3692,7 +4660,7 @@ function configuredModels(settings, source = process.env) {
3692
4660
  reasoningEffort: true,
3693
4661
  hostedWebSearch: settings.webSearchEnabled,
3694
4662
  hostedImageGeneration: builtinHostedImageGenerationForModel(settings, id),
3695
- vision: id.startsWith("gpt-5.6-")
4663
+ vision: isReviewedGptVisionModel(id)
3696
4664
  }),
3697
4665
  ...builtinPromptCachingForModel(id) ? { promptCaching: builtinPromptCachingForModel(id) } : {},
3698
4666
  latencyModes: builtinLatencyModesForModel(id)
@@ -3771,7 +4739,57 @@ function canonicalizeConfiguredModelId(settings, modelId) {
3771
4739
  return models.find((model) => model.aliases.includes(modelId))?.id ?? modelId;
3772
4740
  }
3773
4741
  function configuredAllowedModels(settings) {
3774
- return configuredModels(settings).map((model) => model.id);
4742
+ return configuredModels(settings).filter((model) => isModelAvailableForNewSelection(settings, model.id)).map((model) => model.id);
4743
+ }
4744
+ function isModelAvailableForNewSelection(settings, modelId) {
4745
+ if (!modelId.startsWith(CODEX_MODEL_ID_PREFIX) || settings.resolvedCodexModelsJson === void 0)
4746
+ return true;
4747
+ const models = z2.array(CodexCatalogModelSchema).parse(JSON.parse(settings.resolvedCodexModelsJson));
4748
+ return models.some((model) => model.id === modelId && !model.retired);
4749
+ }
4750
+ function settingsForAcceptedSubscriptionTurn(settings, policy, expected) {
4751
+ const parsed = TurnExecutionPolicyV1.parse(policy);
4752
+ if (!parsed.productModelId.startsWith(CODEX_MODEL_ID_PREFIX)) return settings;
4753
+ if (!settings.codexSubscriptionEnabled) throw new Error("Codex subscription is disabled");
4754
+ const models = settings.resolvedCodexModelsJson === void 0 ? [] : z2.array(CodexCatalogModelSchema).parse(JSON.parse(settings.resolvedCodexModelsJson));
4755
+ const retained = models.find((model2) => model2.id === parsed.productModelId && model2.retired);
4756
+ if (!retained) {
4757
+ assertTurnExecutionPolicyMatchesConfigV1(settings, parsed, expected);
4758
+ return settings;
4759
+ }
4760
+ const { retired: _retired, ...model } = retained;
4761
+ const withoutCodex = {
4762
+ ...settings,
4763
+ modelProvidersJson: JSON.stringify(
4764
+ parseModelProvidersJson(settings.modelProvidersJson).filter(
4765
+ (provider) => provider.id !== CODEX_PROVIDER_ID
4766
+ )
4767
+ )
4768
+ };
4769
+ const providerSettings = withCodexCatalogProvider({
4770
+ ...withoutCodex,
4771
+ resolvedCodexModelsJson: JSON.stringify([model])
4772
+ });
4773
+ const retainedProvider = parseModelProvidersJson(providerSettings.modelProvidersJson).find(
4774
+ (provider) => provider.id === CODEX_PROVIDER_ID
4775
+ );
4776
+ const providers = parseModelProvidersJson(settings.modelProvidersJson);
4777
+ const current = providers.find((provider) => provider.id === CODEX_PROVIDER_ID);
4778
+ const restored = {
4779
+ ...settings,
4780
+ modelProvidersJson: JSON.stringify([
4781
+ ...providers.filter((provider) => provider.id !== CODEX_PROVIDER_ID),
4782
+ {
4783
+ ...retainedProvider,
4784
+ models: [
4785
+ ...(current?.models ?? []).filter((candidate) => candidate.id !== model.id),
4786
+ model
4787
+ ]
4788
+ }
4789
+ ])
4790
+ };
4791
+ assertTurnExecutionPolicyMatchesConfigV1(restored, parsed, expected);
4792
+ return restored;
3775
4793
  }
3776
4794
  function resolveModelProvider(settings, modelId) {
3777
4795
  const canonicalModelId = canonicalizeConfiguredModelId(settings, modelId);
@@ -3821,12 +4839,25 @@ function resolveModelProviderForTurn(settings, modelId) {
3821
4839
  canonicalizeConfiguredModelId(catalogSettings, modelId)
3822
4840
  );
3823
4841
  }
4842
+ var TurnExecutionPolicyModelUnavailableError = class extends Error {
4843
+ constructor(message) {
4844
+ super(message);
4845
+ this.name = "TurnExecutionPolicyModelUnavailableError";
4846
+ }
4847
+ };
3824
4848
  function resolveTurnExecutionPolicyV1(settings, input) {
3825
4849
  const catalogSettings = settingsForTurnExecutionPolicy(settings, input.modelId);
3826
4850
  const productModelId = canonicalizeConfiguredModelId(catalogSettings, input.modelId);
4851
+ if (!isModelAvailableForNewSelection(catalogSettings, productModelId)) {
4852
+ throw new TurnExecutionPolicyModelUnavailableError(
4853
+ "Turn execution policy model is retired from new selection"
4854
+ );
4855
+ }
3827
4856
  const resolved = resolveModelProvider(catalogSettings, productModelId);
3828
4857
  if (!resolved) {
3829
- throw new Error("Turn execution policy model is not present in the configured catalog");
4858
+ throw new TurnExecutionPolicyModelUnavailableError(
4859
+ "Turn execution policy model is not present in the configured catalog"
4860
+ );
3830
4861
  }
3831
4862
  if (input.requestedModelId !== null && canonicalizeConfiguredModelId(catalogSettings, input.requestedModelId) !== productModelId) {
3832
4863
  throw new Error("Turn execution policy requested model does not canonicalize to its product");
@@ -3851,6 +4882,13 @@ function resolveTurnExecutionPolicyV1(settings, input) {
3851
4882
  definitionVersion: resolved.model.definitionVersion
3852
4883
  });
3853
4884
  }
4885
+ var TurnExecutionPolicyDefinitionMismatchError = class extends Error {
4886
+ code = "turn_execution_policy_definition_mismatch";
4887
+ constructor() {
4888
+ super("Turn execution policy does not match the current provider definition");
4889
+ this.name = "TurnExecutionPolicyDefinitionMismatchError";
4890
+ }
4891
+ };
3854
4892
  function assertTurnExecutionPolicyMatchesConfigV1(settings, policy, expected) {
3855
4893
  const parsed = TurnExecutionPolicyV1.parse(policy);
3856
4894
  const catalogSettings = settingsForTurnExecutionPolicy(settings, parsed.productModelId);
@@ -3869,15 +4907,33 @@ function assertTurnExecutionPolicyMatchesConfigV1(settings, policy, expected) {
3869
4907
  if (!resolved) {
3870
4908
  throw new Error("Turn execution policy model is no longer configured");
3871
4909
  }
4910
+ const legacyClaudeScope = resolved.provider.kind === "claude-subscription-workspace" ? "workspace" : resolved.provider.kind === "claude-subscription-organization" ? "organization" : null;
4911
+ const legacyClaudeAccountingMatches = legacyClaudeScope !== null && parsed.providerId === resolved.provider.id && parsed.upstreamModelId === resolved.model.upstreamModelId && parsed.wireApi === resolved.model.api && canonicalJson(parsed.credentialSource) === canonicalJson({
4912
+ kind: `${legacyClaudeScope}_connection`,
4913
+ mechanism: "api_key"
4914
+ }) && canonicalJson(parsed.billing) === canonicalJson({
4915
+ upstreamPayer: legacyClaudeScope,
4916
+ metering: "external"
4917
+ }) && parsed.definitionVersion === definitionVersionFor(
4918
+ {
4919
+ ...resolved.model,
4920
+ credentialSource: parsed.credentialSource,
4921
+ billing: parsed.billing
4922
+ },
4923
+ resolved.provider
4924
+ );
3872
4925
  const legacyImplicitOpenAiDefinitionVersion = legacyImplicitOpenAiDefinitionVersionFor(
3873
4926
  resolved.model,
3874
4927
  resolved.provider
3875
4928
  );
3876
- const definitionVersionMatches = parsed.definitionVersion === resolved.model.definitionVersion || parsed.definitionVersion === legacyImplicitOpenAiDefinitionVersion;
3877
- 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);
3878
- if (mismatched) {
4929
+ const definitionVersionMatches = parsed.definitionVersion === resolved.model.definitionVersion || parsed.definitionVersion === legacyImplicitOpenAiDefinitionVersion || parsed.definitionVersion === legacyCodexAstraImplicitCachingDefinitionVersionFor(resolved.model, resolved.provider) || matchesAdditiveCapabilityDefinitionVersion(resolved.model, resolved.provider, parsed);
4930
+ 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);
4931
+ if (identityMismatched && !legacyClaudeAccountingMatches) {
3879
4932
  throw new Error("Turn execution policy does not match the current provider definition");
3880
4933
  }
4934
+ if (!definitionVersionMatches && !legacyClaudeAccountingMatches) {
4935
+ throw new TurnExecutionPolicyDefinitionMismatchError();
4936
+ }
3881
4937
  return { policy: parsed, provider: resolved.provider, model: resolved.model };
3882
4938
  }
3883
4939
  function configuredModelPricingSchedules(settings) {
@@ -3907,6 +4963,103 @@ function configuredModelPricingSchedules(settings) {
3907
4963
  ...configured
3908
4964
  };
3909
4965
  }
4966
+ function configuredModelListPricingSchedules(settings) {
4967
+ const prices = configuredModelPricingSchedules(settings);
4968
+ const configured = Object.fromEntries(
4969
+ Object.entries(parseModelPricingJson(settings.modelPricingJson)).map(([model, pricing]) => [
4970
+ model,
4971
+ normalizeModelPricingSchedule(pricing)
4972
+ ])
4973
+ );
4974
+ if (settings.openaiProvider === "openai" && isDirectOpenAiApiBaseUrl(settings.openaiBaseUrl ?? "https://api.openai.com/v1")) {
4975
+ for (const model of configuredModels(settings)) {
4976
+ if (model.providerId !== builtinProviderId(settings) || !model.upstreamModelId.startsWith("gpt-") || prices[model.id] !== void 0)
4977
+ continue;
4978
+ const reviewed = reviewedModelListPricing[model.upstreamModelId];
4979
+ if (reviewed) prices[model.id] = reviewed;
4980
+ }
4981
+ }
4982
+ for (const provider of configuredRegistryProviders(settings)) {
4983
+ for (const model of provider.models) {
4984
+ if (prices[model.id] !== void 0) continue;
4985
+ const reviewed = reviewedProviderModelPricing(settings, provider, model, configured);
4986
+ if (reviewed) prices[model.id] = reviewed;
4987
+ }
4988
+ }
4989
+ return prices;
4990
+ }
4991
+ function reviewedProviderModelPricing(settings, provider, model, configured) {
4992
+ const upstream = model.upstreamModelId ?? model.id;
4993
+ let priceId;
4994
+ let nativeClaude = false;
4995
+ switch (provider.kind) {
4996
+ case "anonymous":
4997
+ if (provider.baseUrl.replace(/\/$/u, "") === OPENROUTER_BASE_URL && upstream === DEFAULT_OPENROUTER_MODEL_ID.slice(OPENROUTER_MODEL_ID_PREFIX.length)) {
4998
+ priceId = DEFAULT_OPENROUTER_MODEL_ID;
4999
+ }
5000
+ break;
5001
+ case "codex-subscription":
5002
+ if (upstream.startsWith("gpt-")) priceId = upstream;
5003
+ break;
5004
+ case "xai-subscription":
5005
+ if (upstream.startsWith("grok-")) priceId = upstream;
5006
+ break;
5007
+ case "anthropic-workspace":
5008
+ case "anthropic-organization":
5009
+ case "claude-subscription-workspace":
5010
+ case "claude-subscription-organization":
5011
+ if (claudeNativeModelProfile(upstream)) {
5012
+ priceId = upstream;
5013
+ nativeClaude = true;
5014
+ }
5015
+ break;
5016
+ case "direct-openai-workspace":
5017
+ if (isDirectOpenAiApiBaseUrl(provider.baseUrl) && upstream.startsWith("gpt-")) {
5018
+ priceId = upstream;
5019
+ }
5020
+ break;
5021
+ case "vercel-gateway-managed":
5022
+ case "vercel-gateway-workspace":
5023
+ case "vercel-gateway-organization":
5024
+ priceId = configuredGatewayCatalogModels(settings).find(
5025
+ (candidate) => candidate.upstreamModelId === upstream && Object.values(OPENGENI_GATEWAY_MODELS).some(
5026
+ (reviewed) => reviewed.upstreamModelId === candidate.upstreamModelId
5027
+ )
5028
+ )?.productId;
5029
+ break;
5030
+ case "openrouter-workspace":
5031
+ case "openrouter-organization":
5032
+ case "openrouter-managed":
5033
+ if (upstream === DEFAULT_OPENROUTER_MODEL_ID.slice(OPENROUTER_MODEL_ID_PREFIX.length)) {
5034
+ priceId = DEFAULT_OPENROUTER_MODEL_ID;
5035
+ }
5036
+ break;
5037
+ case "api-key":
5038
+ if (isDirectOpenAiApiBaseUrl(provider.baseUrl) && upstream.startsWith("gpt-")) {
5039
+ priceId = upstream;
5040
+ } else if (provider.baseUrl.replace(/\/$/u, "") === "https://api.x.ai/v1") {
5041
+ if (upstream.startsWith("grok-")) priceId = upstream;
5042
+ } else if (provider.api === "anthropic-messages" && provider.baseUrl.replace(/\/$/u, "") === "https://api.anthropic.com/v1" && claudeNativeModelProfile(upstream)) {
5043
+ priceId = upstream;
5044
+ nativeClaude = true;
5045
+ }
5046
+ break;
5047
+ default:
5048
+ return void 0;
5049
+ }
5050
+ if (!priceId) return void 0;
5051
+ if (configured[priceId]) return configured[priceId];
5052
+ const schedule = reviewedModelListPricing[priceId] ?? defaultModelPricing[priceId] ?? (priceId === DEFAULT_OPENROUTER_MODEL_ID ? reviewedFreeOpenRouterListPricing : void 0);
5053
+ if (!schedule) return void 0;
5054
+ if (!nativeClaude || provider.anthropic?.cacheTtl !== "1h") return schedule;
5055
+ return {
5056
+ ...schedule,
5057
+ default: {
5058
+ ...schedule.default,
5059
+ cacheWriteMicrosPerMillionTokens: schedule.default.inputMicrosPerMillionTokens * 2
5060
+ }
5061
+ };
5062
+ }
3910
5063
  function configuredModelPricing(settings) {
3911
5064
  return Object.fromEntries(
3912
5065
  Object.entries(configuredModelPricingSchedules(settings)).map(([model, schedule]) => [
@@ -3972,6 +5125,216 @@ function calculateModelUsageCostMicros(settings, model, usage, options) {
3972
5125
  }
3973
5126
  function calculateModelUsageCostBreakdown(settings, model, usage, options) {
3974
5127
  const schedule = configuredModelPricingSchedules(settings)[model];
5128
+ return calculateUsageCostBreakdown(settings, model, usage, schedule, options);
5129
+ }
5130
+ function calculateModelListUsageCostBreakdown(settings, model, usage, options) {
5131
+ const schedule = configuredModelListPricingSchedules(settings)[model];
5132
+ return calculateUsageCostBreakdown(settings, model, usage, schedule, options);
5133
+ }
5134
+ function calculateModelListUsageCostSnapshot(settings, model, usage, options) {
5135
+ const schedule = configuredModelListPricingSchedules(settings)[model];
5136
+ const fallback = calculateUsageCostBreakdown(settings, model, usage, schedule, options);
5137
+ const unknown = { ...fallback, listByClassMicros: null, listByClassApprox: false };
5138
+ if (!schedule || !options?.priceContextKnown) return unknown;
5139
+ const entries = usage.requestUsageEntries?.length ? usage.requestUsageEntries : [usage];
5140
+ const classes = {
5141
+ uncachedInput: 0,
5142
+ cacheRead: 0,
5143
+ cacheWrite: 0,
5144
+ output: 0
5145
+ };
5146
+ const rawCostByPricing = /* @__PURE__ */ new Map();
5147
+ const native = nativeClaudeListWriteContext(settings, model);
5148
+ for (const entry of entries) {
5149
+ if (!knownTokenCounter(entry.inputTokens) || !knownTokenCounter(entry.outputTokens))
5150
+ return unknown;
5151
+ const cached = knownDetailTokenCounter(entry, [
5152
+ "cached_tokens",
5153
+ "cachedInputTokens",
5154
+ "cached_input_tokens"
5155
+ ]);
5156
+ const writes = knownDetailTokenCounter(entry, ["cache_write_tokens", "cacheWriteTokens"], true);
5157
+ if (cached === void 0 || writes === void 0 || cached + writes > entry.inputTokens)
5158
+ return unknown;
5159
+ const pricing = selectModelPricing(schedule, entry.inputTokens);
5160
+ if (cached > 0 && pricing.cachedInputMicrosPerMillionTokens === void 0) return unknown;
5161
+ if (writes > 0 && pricing.cacheWriteMicrosPerMillionTokens === void 0) return unknown;
5162
+ const costs = {
5163
+ uncachedInput: Math.ceil(
5164
+ (entry.inputTokens - cached - writes) * pricing.inputMicrosPerMillionTokens / 1e6
5165
+ ),
5166
+ cacheRead: Math.ceil(cached * (pricing.cachedInputMicrosPerMillionTokens ?? 0) / 1e6),
5167
+ cacheWrite: Math.ceil(writes * (pricing.cacheWriteMicrosPerMillionTokens ?? 0) / 1e6),
5168
+ output: Math.ceil(entry.outputTokens * pricing.outputMicrosPerMillionTokens / 1e6)
5169
+ };
5170
+ if (native && writes > 0) {
5171
+ const fiveMinute = knownDetailTokenCounter(entry, ["cache_write_tokens_5m"]);
5172
+ const oneHour = knownDetailTokenCounter(entry, ["cache_write_tokens_1h"]);
5173
+ if (fiveMinute === void 0 || oneHour === void 0 || fiveMinute + oneHour !== writes)
5174
+ return unknown;
5175
+ if (native.publishedRates) {
5176
+ costs.cacheWrite = Math.ceil(fiveMinute * native.publishedRates.fiveMinute / 1e6) + Math.ceil(oneHour * native.publishedRates.oneHour / 1e6);
5177
+ } else if (!(native.declaredTtl === "5m" && oneHour === 0 || native.declaredTtl === "1h" && fiveMinute === 0)) {
5178
+ return unknown;
5179
+ }
5180
+ }
5181
+ const raw = sumListCostClasses(costs);
5182
+ rawCostByPricing.set(pricing, (rawCostByPricing.get(pricing) ?? 0) + raw);
5183
+ for (const key of MODEL_LIST_COST_CLASS_KEYS) classes[key] += costs[key];
5184
+ }
5185
+ let providerCostMicros = sumListCostClasses(classes);
5186
+ let creditCostMicros = 0;
5187
+ for (const [pricing, raw] of rawCostByPricing) {
5188
+ creditCostMicros += Math.ceil(raw * (1e4 + (pricing.marginBps ?? 0)) / 1e4);
5189
+ }
5190
+ let listByClassApprox = false;
5191
+ const latencyMode = options.latencyMode ?? "standard";
5192
+ if (latencyMode !== "standard") {
5193
+ const catalogSettings = settingsForTurnExecutionPolicy(settings, model);
5194
+ const resolved = resolveModelProvider(
5195
+ catalogSettings,
5196
+ canonicalizeConfiguredModelId(catalogSettings, model)
5197
+ );
5198
+ const multiplier = resolved?.model.capabilities.latencyModes.find(
5199
+ (mode) => mode.id === latencyMode && mode.runnable
5200
+ )?.billingMultiplierBps;
5201
+ if (multiplier === void 0 || multiplier <= 0) return unknown;
5202
+ providerCostMicros = Math.ceil(providerCostMicros * multiplier / 1e4);
5203
+ creditCostMicros = Math.ceil(creditCostMicros * multiplier / 1e4);
5204
+ const scaled = allocateLatencyListCostClasses(classes, multiplier, providerCostMicros);
5205
+ if (!scaled) return unknown;
5206
+ Object.assign(classes, scaled.classes);
5207
+ listByClassApprox = scaled.approximate;
5208
+ }
5209
+ if (![providerCostMicros, creditCostMicros, ...Object.values(classes)].every(knownTokenCounter))
5210
+ return unknown;
5211
+ return { providerCostMicros, creditCostMicros, listByClassMicros: classes, listByClassApprox };
5212
+ }
5213
+ function allocateRecordedModelListCostByClass(settings, model, usage, recordedProviderCostMicros) {
5214
+ const unknown = {
5215
+ listByClassMicros: null,
5216
+ listByClassApprox: false
5217
+ };
5218
+ if (!knownTokenCounter(recordedProviderCostMicros)) return unknown;
5219
+ const schedule = configuredModelListPricingSchedules(settings)[model];
5220
+ if (!schedule) return unknown;
5221
+ const weights = { uncachedInput: 0n, cacheRead: 0n, cacheWrite: 0n, output: 0n };
5222
+ const entries = usage.requestUsageEntries?.length ? usage.requestUsageEntries : [usage];
5223
+ for (const entry of entries) {
5224
+ if (!knownTokenCounter(entry.inputTokens) || !knownTokenCounter(entry.outputTokens))
5225
+ return unknown;
5226
+ const cached = knownDetailTokenCounter(entry, [
5227
+ "cached_tokens",
5228
+ "cachedInputTokens",
5229
+ "cached_input_tokens"
5230
+ ]);
5231
+ const writes = knownDetailTokenCounter(entry, ["cache_write_tokens", "cacheWriteTokens"], true);
5232
+ if (cached === void 0 || writes === void 0 || cached + writes > entry.inputTokens)
5233
+ return unknown;
5234
+ const pricing = selectModelPricing(schedule, entry.inputTokens);
5235
+ const counters = {
5236
+ uncachedInput: entry.inputTokens - cached - writes,
5237
+ cacheRead: cached,
5238
+ cacheWrite: writes,
5239
+ output: entry.outputTokens
5240
+ };
5241
+ const rates = {
5242
+ uncachedInput: pricing.inputMicrosPerMillionTokens,
5243
+ cacheRead: pricing.cachedInputMicrosPerMillionTokens,
5244
+ cacheWrite: pricing.cacheWriteMicrosPerMillionTokens,
5245
+ output: pricing.outputMicrosPerMillionTokens
5246
+ };
5247
+ for (const key of MODEL_LIST_COST_CLASS_KEYS) {
5248
+ if (counters[key] === 0) continue;
5249
+ const rate = rates[key];
5250
+ if (!knownTokenCounter(rate)) return unknown;
5251
+ weights[key] += BigInt(counters[key]) * BigInt(rate);
5252
+ }
5253
+ }
5254
+ const classes = allocateRecordedListCostWeights(weights, recordedProviderCostMicros);
5255
+ return classes ? { listByClassMicros: classes, listByClassApprox: true } : unknown;
5256
+ }
5257
+ var MODEL_LIST_COST_CLASS_KEYS = ["uncachedInput", "cacheRead", "cacheWrite", "output"];
5258
+ function sumListCostClasses(costs) {
5259
+ return MODEL_LIST_COST_CLASS_KEYS.reduce((total, key) => total + costs[key], 0);
5260
+ }
5261
+ function allocateRecordedListCostWeights(weights, target) {
5262
+ const denominator = MODEL_LIST_COST_CLASS_KEYS.reduce((total, key) => total + weights[key], 0n);
5263
+ if (denominator === 0n) {
5264
+ return target === 0 ? { uncachedInput: 0, cacheRead: 0, cacheWrite: 0, output: 0 } : void 0;
5265
+ }
5266
+ const rows = MODEL_LIST_COST_CLASS_KEYS.map((key, index) => {
5267
+ const numerator = BigInt(target) * weights[key];
5268
+ return { key, index, value: numerator / denominator, remainder: numerator % denominator };
5269
+ });
5270
+ const remaining = BigInt(target) - rows.reduce((total, row) => total + row.value, 0n);
5271
+ const ranked = [...rows].sort(
5272
+ (a, b) => a.remainder === b.remainder ? a.index - b.index : a.remainder > b.remainder ? -1 : 1
5273
+ );
5274
+ for (let index = 0; index < Number(remaining); index++) ranked[index].value += 1n;
5275
+ return Object.fromEntries(
5276
+ rows.map((row) => [row.key, Number(row.value)])
5277
+ );
5278
+ }
5279
+ function knownTokenCounter(value) {
5280
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
5281
+ }
5282
+ function knownDetailTokenCounter(entry, keys, firstOnly = false) {
5283
+ const details = Array.isArray(entry.inputTokensDetails) ? entry.inputTokensDetails : entry.inputTokensDetails ? [entry.inputTokensDetails] : [];
5284
+ if (details.length === 0) return void 0;
5285
+ let total = 0;
5286
+ for (const detail of details) {
5287
+ const present = keys.filter((key) => detail[key] !== void 0);
5288
+ if (present.length === 0) return void 0;
5289
+ for (const key of firstOnly ? present.slice(0, 1) : present) {
5290
+ if (!knownTokenCounter(detail[key])) return void 0;
5291
+ total += detail[key];
5292
+ }
5293
+ }
5294
+ return knownTokenCounter(total) ? total : void 0;
5295
+ }
5296
+ function nativeClaudeListWriteContext(settings, modelId) {
5297
+ for (const provider of configuredRegistryProviders(settings)) {
5298
+ const model = provider.models.find((candidate) => candidate.id === modelId);
5299
+ if (!model || provider.api !== "anthropic-messages") continue;
5300
+ const result = { declaredTtl: provider.anthropic?.cacheTtl };
5301
+ const upstream = model.upstreamModelId ?? model.id;
5302
+ const overrides = parseModelPricingJson(settings.modelPricingJson);
5303
+ 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";
5304
+ const published = reviewedModelListPricing[upstream]?.default;
5305
+ if (!official || !claudeNativeModelProfile(upstream) || !published?.cacheWriteMicrosPerMillionTokens || model.pricing || overrides[modelId] !== void 0 || overrides[upstream] !== void 0)
5306
+ return result;
5307
+ return {
5308
+ ...result,
5309
+ publishedRates: {
5310
+ fiveMinute: published.cacheWriteMicrosPerMillionTokens,
5311
+ oneHour: published.inputMicrosPerMillionTokens * 2
5312
+ }
5313
+ };
5314
+ }
5315
+ return void 0;
5316
+ }
5317
+ function allocateLatencyListCostClasses(classes, multiplier, target) {
5318
+ if (!knownTokenCounter(multiplier) || !knownTokenCounter(target) || !Object.values(classes).every(knownTokenCounter))
5319
+ return void 0;
5320
+ const rows = MODEL_LIST_COST_CLASS_KEYS.map((key, index) => {
5321
+ const numerator = BigInt(classes[key]) * BigInt(multiplier);
5322
+ return { key, index, value: Number(numerator / 10000n), remainder: numerator % 10000n };
5323
+ });
5324
+ const remaining = target - rows.reduce((total, row) => total + row.value, 0);
5325
+ if (remaining < 0 || remaining > rows.length) return void 0;
5326
+ const ranked = [...rows].sort(
5327
+ (a, b) => a.remainder === b.remainder ? a.index - b.index : a.remainder > b.remainder ? -1 : 1
5328
+ );
5329
+ for (let index = 0; index < remaining; index++) ranked[index].value += 1;
5330
+ return {
5331
+ classes: Object.fromEntries(
5332
+ rows.map((row) => [row.key, row.value])
5333
+ ),
5334
+ approximate: rows.some((row) => row.remainder !== 0n)
5335
+ };
5336
+ }
5337
+ function calculateUsageCostBreakdown(settings, model, usage, schedule, options) {
3975
5338
  if (!schedule) {
3976
5339
  throw new Error(`Missing model pricing for ${model}`);
3977
5340
  }
@@ -4230,7 +5593,7 @@ async function retryStartupDependency(label, operation, options = {}) {
4230
5593
  try {
4231
5594
  return await operation();
4232
5595
  } catch (error) {
4233
- if (attempt >= attempts) {
5596
+ if (attempt >= attempts || options.shouldRetry?.(error) === false) {
4234
5597
  throw error;
4235
5598
  }
4236
5599
  const delayMs = Math.min(maxDelayMs, initialDelayMs * 2 ** (attempt - 1));
@@ -4320,7 +5683,7 @@ function parseModelPricingJson(raw) {
4320
5683
  if (!model.trim()) {
4321
5684
  throw new Error("OPENGENI_MODEL_PRICING_JSON contains an empty model name");
4322
5685
  }
4323
- out[model] = z.union([ModelPricingSchema, ModelPricingScheduleSchema]).parse(value);
5686
+ out[model] = z2.union([ModelPricingSchema, ModelPricingScheduleSchema]).parse(value);
4324
5687
  }
4325
5688
  return out;
4326
5689
  }
@@ -4430,9 +5793,9 @@ function parseIntegrationsOauthClientsJson(raw) {
4430
5793
  }
4431
5794
  return out;
4432
5795
  }
4433
- var SocialOAuthClientConfigSchema = z.object({
4434
- clientId: z.string().min(1),
4435
- clientSecret: z.string().min(1).optional()
5796
+ var SocialOAuthClientConfigSchema = z2.object({
5797
+ clientId: z2.string().min(1),
5798
+ clientSecret: z2.string().min(1).optional()
4436
5799
  });
4437
5800
  var SOCIAL_OAUTH_PROVIDER_IDS = ["x", "reddit"];
4438
5801
  function parseSocialOauthClientsJson(raw) {
@@ -4569,20 +5932,9 @@ function ensureBuiltInMcpServers(settings) {
4569
5932
  ...hasDocs ? [] : [
4570
5933
  {
4571
5934
  id: "docs",
4572
- name: "Document Search",
5935
+ name: "Knowledge",
4573
5936
  url: firstPartyDocsMcpUrl,
4574
- allowedTools: [
4575
- "search_documents",
4576
- "fetch_document_chunk",
4577
- "list_document_bases",
4578
- "list_indexed_documents",
4579
- "knowledge_search",
4580
- "knowledge_get",
4581
- "knowledge_browse",
4582
- "knowledge_fetch",
4583
- "memory_search",
4584
- "memory_propose"
4585
- ],
5937
+ allowedTools: ["knowledge_search", "knowledge_get", "knowledge_browse"],
4586
5938
  cacheToolsList: false
4587
5939
  }
4588
5940
  ],
@@ -4641,8 +5993,61 @@ function isDigestPinnedModalDesktopImage(settings) {
4641
5993
  if (settings.modalImageId) return true;
4642
5994
  return typeof settings.modalImageRef === "string" && MODAL_DESKTOP_IMAGE_DIGEST_REF.test(settings.modalImageRef);
4643
5995
  }
5996
+ function trustedProxyCidrEntries(raw) {
5997
+ const entries = [];
5998
+ for (const entry of raw.split(",")) {
5999
+ const value = entry.trim();
6000
+ if (!value) continue;
6001
+ const slash = value.indexOf("/");
6002
+ const address = slash < 0 ? value : value.slice(0, slash);
6003
+ const version = isIP(address);
6004
+ const family = version === 4 ? "ipv4" : version === 6 ? "ipv6" : null;
6005
+ const maxPrefix = family === "ipv4" ? 32 : 128;
6006
+ const prefixText = slash < 0 ? String(maxPrefix) : value.slice(slash + 1);
6007
+ const prefix = /^\d{1,3}$/u.test(prefixText) ? Number(prefixText) : Number.NaN;
6008
+ if (!family || !Number.isInteger(prefix) || prefix < 0 || prefix > maxPrefix) {
6009
+ throw new Error(
6010
+ `OPENGENI_API_TRUSTED_PROXY_CIDRS entry "${value.slice(0, 64)}" is not an IP address or CIDR range`
6011
+ );
6012
+ }
6013
+ entries.push({ address, prefix, family });
6014
+ }
6015
+ return entries;
6016
+ }
6017
+ function localAllowedOriginEntries(raw) {
6018
+ const origins = [];
6019
+ for (const entry of (raw ?? "").split(",")) {
6020
+ const value = entry.trim();
6021
+ if (!value) continue;
6022
+ let url = null;
6023
+ try {
6024
+ url = new URL(value);
6025
+ } catch {
6026
+ url = null;
6027
+ }
6028
+ 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("#")) {
6029
+ throw new Error(
6030
+ `OPENGENI_LOCAL_ALLOWED_ORIGINS entry "${value.slice(0, 64)}" is not an exact http(s) origin such as http://127.0.0.1:5173`
6031
+ );
6032
+ }
6033
+ origins.push(url.origin);
6034
+ }
6035
+ return origins;
6036
+ }
6037
+ var LOCAL_SANDBOX_API_ROUTES = [
6038
+ // Codemode calls, journal reads, catalog, and the Site/SDK proxy.
6039
+ /^\/v1\/workspaces\/[^/]+\/codemode(?:\/|$)/u,
6040
+ // First-party MCP, including its /docs and /files servers.
6041
+ /^\/v1\/workspaces\/[^/]+\/mcp(?:\/|$)/u,
6042
+ // The personal GitHub HTTPS smart-Git broker.
6043
+ /^\/v1\/git\/personal\/[A-Za-z0-9_-]{43}\/(?:info\/refs|git-upload-pack|git-receive-pack)$/u
6044
+ ];
6045
+ function localSandboxApiRouteAllowed(pathname) {
6046
+ return LOCAL_SANDBOX_API_ROUTES.some((route) => route.test(pathname));
6047
+ }
4644
6048
  function validateSettings(settings, source = process.env) {
4645
6049
  temporalConnectionOptions(settings);
6050
+ localAllowedOriginEntries(settings.localAllowedOrigins);
4646
6051
  if (settings.organizationUserSetupEmailTokenTransport === "query" && !settings.organizationUserSetupQueryEdgeSanitizationConfirmed) {
4647
6052
  throw new Error(
4648
6053
  "OPENGENI_ORGANIZATION_USER_SETUP_QUERY_EDGE_SANITIZATION_CONFIRMED=true is required when OPENGENI_ORGANIZATION_USER_SETUP_EMAIL_TOKEN_TRANSPORT=query"
@@ -4725,6 +6130,18 @@ function validateSettings(settings, source = process.env) {
4725
6130
  );
4726
6131
  }
4727
6132
  }
6133
+ const retiredTrustedProxyHops = source.OPENGENI_MCP_OAUTH_TRUSTED_PROXY_HOPS?.trim();
6134
+ if (retiredTrustedProxyHops && retiredTrustedProxyHops !== "0") {
6135
+ throw new Error(
6136
+ "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"
6137
+ );
6138
+ }
6139
+ const trustedProxyCidrs = trustedProxyCidrEntries(settings.apiTrustedProxyCidrs);
6140
+ if (trustedProxyCidrs.length > 0 && settings.apiTrustedProxyHops === 0) {
6141
+ throw new Error(
6142
+ "OPENGENI_API_TRUSTED_PROXY_CIDRS requires OPENGENI_API_TRUSTED_PROXY_HOPS greater than 0"
6143
+ );
6144
+ }
4728
6145
  if (settings.mcpOauthEnabled) {
4729
6146
  if (settings.productAccessMode === "configured") {
4730
6147
  throw new Error(
@@ -4985,60 +6402,7 @@ function validateSettings(settings, source = process.env) {
4985
6402
  );
4986
6403
  }
4987
6404
  }
4988
- if (settings.objectStorageBackend === "s3-compatible" || settings.objectStorageBackend === "aws-s3") {
4989
- if (Boolean(settings.objectStorageAccessKeyId) !== Boolean(settings.objectStorageSecretAccessKey)) {
4990
- throw new Error(
4991
- "OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID and OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY must both be set or both omitted"
4992
- );
4993
- }
4994
- if (settings.objectStorageBackend === "s3-compatible" && (settings.objectStorageEndpoint || settings.objectStorageInternalEndpoint || settings.objectStorageSandboxEndpoint) && (!settings.objectStorageAccessKeyId || !settings.objectStorageSecretAccessKey)) {
4995
- throw new Error(
4996
- "S3-compatible object storage endpoints require OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID and OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY"
4997
- );
4998
- }
4999
- if (settings.objectStorageAzureConnectionString || settings.objectStorageAzureAccountName || settings.objectStorageAzureAccountKey || settings.objectStorageAzureEndpoint) {
5000
- throw new Error(
5001
- "S3 object storage uses OPENGENI_OBJECT_STORAGE_* S3 settings, not OPENGENI_OBJECT_STORAGE_AZURE_* settings"
5002
- );
5003
- }
5004
- if (settings.objectStorageGcsProjectId || settings.objectStorageGcsCredentialsJson || settings.objectStorageGcsKeyFilename || settings.objectStorageGcsApiEndpoint) {
5005
- throw new Error(
5006
- "S3 object storage uses OPENGENI_OBJECT_STORAGE_* S3 settings, not OPENGENI_OBJECT_STORAGE_GCS_* settings"
5007
- );
5008
- }
5009
- } else if (settings.objectStorageBackend === "azure-blob") {
5010
- if (settings.objectStorageEndpoint || settings.objectStorageInternalEndpoint || settings.objectStorageSandboxEndpoint || settings.objectStorageAccessKeyId || settings.objectStorageSecretAccessKey) {
5011
- throw new Error(
5012
- "Azure Blob storage uses OPENGENI_OBJECT_STORAGE_AZURE_* settings, not S3-compatible object storage settings"
5013
- );
5014
- }
5015
- if (settings.objectStorageGcsProjectId || settings.objectStorageGcsCredentialsJson || settings.objectStorageGcsKeyFilename || settings.objectStorageGcsApiEndpoint) {
5016
- throw new Error(
5017
- "Azure Blob storage uses OPENGENI_OBJECT_STORAGE_AZURE_* settings, not OPENGENI_OBJECT_STORAGE_GCS_* settings"
5018
- );
5019
- }
5020
- const hasConnectionString = Boolean(settings.objectStorageAzureConnectionString);
5021
- const hasSharedKey = Boolean(settings.objectStorageAzureAccountName) && Boolean(settings.objectStorageAzureAccountKey);
5022
- if (!hasConnectionString && !hasSharedKey) {
5023
- throw new Error(
5024
- "Azure Blob storage requires OPENGENI_OBJECT_STORAGE_AZURE_CONNECTION_STRING or OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_NAME plus OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_KEY"
5025
- );
5026
- }
5027
- } else {
5028
- if (settings.objectStorageEndpoint || settings.objectStorageInternalEndpoint || settings.objectStorageSandboxEndpoint || settings.objectStorageAccessKeyId || settings.objectStorageSecretAccessKey) {
5029
- throw new Error(
5030
- "GCS object storage uses OPENGENI_OBJECT_STORAGE_GCS_* settings, not S3-compatible object storage settings"
5031
- );
5032
- }
5033
- if (settings.objectStorageAzureConnectionString || settings.objectStorageAzureAccountName || settings.objectStorageAzureAccountKey || settings.objectStorageAzureEndpoint) {
5034
- throw new Error(
5035
- "GCS object storage uses OPENGENI_OBJECT_STORAGE_GCS_* settings, not OPENGENI_OBJECT_STORAGE_AZURE_* settings"
5036
- );
5037
- }
5038
- if (settings.objectStorageGcsCredentialsJson) {
5039
- parseGcsCredentialsJson(settings.objectStorageGcsCredentialsJson);
5040
- }
5041
- }
6405
+ validateObjectStorageSettings(settings);
5042
6406
  if (settings.documentChunkOverlap >= settings.documentChunkSize) {
5043
6407
  throw new Error(
5044
6408
  "OPENGENI_DOCUMENT_CHUNK_OVERLAP must be smaller than OPENGENI_DOCUMENT_CHUNK_SIZE"
@@ -5047,7 +6411,22 @@ function validateSettings(settings, source = process.env) {
5047
6411
  parseExposedPorts(settings.dockerExposedPorts);
5048
6412
  sandboxEnvironmentVariableNames(settings);
5049
6413
  sandboxLifecycleHookIds(settings);
5050
- parseSandboxWarmRateJson(settings.sandboxWarmRateMicrosPerSecondJson);
6414
+ const warmRates = parseSandboxWarmRateJson(settings.sandboxWarmRateMicrosPerSecondJson);
6415
+ if (settings.sandboxWarmBillingMode === "credits" && Object.values(warmRates).some((rate) => !Number.isSafeInteger(rate))) {
6416
+ throw new Error(
6417
+ "OPENGENI_SANDBOX_WARM_RATE_MICROS_PER_SECOND_JSON paid rates must be safe integers"
6418
+ );
6419
+ }
6420
+ if (settings.documentEmbeddingBillingMode === "credits" && settings.documentEmbeddingProvider === "openai" && settings.documentEmbeddingRateMicrosPerMillionBytes <= 0) {
6421
+ throw new Error(
6422
+ "OPENGENI_DOCUMENT_EMBEDDING_RATE_MICROS_PER_MILLION_BYTES must be positive when paid OpenAI embedding billing is enabled"
6423
+ );
6424
+ }
6425
+ if (settings.documentEmbeddingBillingMode === "credits" && settings.documentEmbeddingProvider === "openai" && !settings.documentEmbeddingCreditsActivatedAt) {
6426
+ throw new Error(
6427
+ "OPENGENI_DOCUMENT_EMBEDDING_CREDITS_ACTIVATED_AT is required for paid OpenAI embeddings"
6428
+ );
6429
+ }
5051
6430
  if (settings.sandboxBackend === "opensandbox") {
5052
6431
  if (!/@sha256:[0-9a-f]{64}$/i.test(settings.openSandboxImage ?? "")) {
5053
6432
  throw new Error(
@@ -5066,9 +6445,9 @@ function validateSettings(settings, source = process.env) {
5066
6445
  throw new Error(`OPENGENI_MCP_SERVERS contains duplicate id ${server.id}`);
5067
6446
  }
5068
6447
  serverIds.add(server.id);
5069
- if (server.connectionRef?.authoritySource === "host" && !settings.hostMcpAuthoritySourceAdmissionEnabled) {
6448
+ if (server.connectionRef?.authoritySource === "host") {
5070
6449
  throw new Error(
5071
- "OPENGENI_MCP_SERVERS host-owned connection refs require OPENGENI_HOST_MCP_AUTHORITY_SOURCE_ADMISSION_ENABLED=true after the whole API/worker fleet is upgraded"
6450
+ "OPENGENI_MCP_SERVERS host-owned connection refs are no longer supported; select ordinary native connections"
5072
6451
  );
5073
6452
  }
5074
6453
  }
@@ -5106,9 +6485,21 @@ function validateSettings(settings, source = process.env) {
5106
6485
  ordinaryCaptureTimeoutMs,
5107
6486
  drainCaptureTimeoutMs
5108
6487
  );
5109
- if (!(rotationLeadMs > providerDeadlineCaptureTimeoutMs + reaperPeriod)) {
6488
+ const requiredRotationLeadMs = SANDBOX_DEADLINE_COMMAND_STOP_GRACE_MS + providerDeadlineCaptureTimeoutMs + 2 * reaperPeriod;
6489
+ if (!(rotationLeadMs > requiredRotationLeadMs)) {
6490
+ throw new Error(
6491
+ `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.`
6492
+ );
6493
+ }
6494
+ const containmentMs = settings.sandboxIdleCommandContainmentMs;
6495
+ if (containmentMs !== void 0 && !(containmentMs > settings.sandboxIdleGraceMs)) {
6496
+ throw new Error(
6497
+ `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.`
6498
+ );
6499
+ }
6500
+ if (containmentMs !== void 0 && optionalEnvironmentValue("OPENGENI_SANDBOX_IDLE_COMMAND_CONTAINMENT_MS", source) !== void 0 && !(containmentMs < rotationLeadMs)) {
5110
6501
  throw new Error(
5111
- `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.`
6502
+ `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.`
5112
6503
  );
5113
6504
  }
5114
6505
  if (settings.sandboxBackend === "modal") {
@@ -5141,6 +6532,11 @@ function validateSettings(settings, source = process.env) {
5141
6532
  `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.`
5142
6533
  );
5143
6534
  }
6535
+ if (settings.modalIdleTimeoutSeconds !== void 0 && containmentMs !== void 0 && !(reaperPeriod + containmentMs + drainCaptureTimeoutMs < idleTimeoutMs)) {
6536
+ throw new Error(
6537
+ `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.`
6538
+ );
6539
+ }
5144
6540
  }
5145
6541
  }
5146
6542
  if (settings.sandboxDesktopEnabled && settings.sandboxBackend === "modal" && !["local", "test"].includes(settings.environment)) {
@@ -5168,7 +6564,7 @@ function validateModelCatalogSettings(settings, source = process.env) {
5168
6564
  const builtinId = builtinProviderId(settings);
5169
6565
  const providerIds = /* @__PURE__ */ new Set();
5170
6566
  for (const provider of registryProviders) {
5171
- 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") {
6567
+ 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") {
5172
6568
  throw new Error(
5173
6569
  `OPENGENI_MODEL_PROVIDERS_JSON provider kind ${provider.kind} is reserved for a reviewed OpenGeni credential broker`
5174
6570
  );
@@ -5210,10 +6606,25 @@ function validateModelCatalogSettings(settings, source = process.env) {
5210
6606
  `The default model ${settings.openaiModel} is not executable in the resolved model catalog`
5211
6607
  );
5212
6608
  }
6609
+ const explicitCreditsDefault = source.OPENGENI_CREDITS_DEFAULT_MODEL?.trim();
6610
+ if (explicitCreditsDefault && settings.modelCatalogSource === "code" && settings.billingMode === "stripe") {
6611
+ const creditsDefaultId = canonicalizeConfiguredModelId(settings, settings.creditsDefaultModel);
6612
+ const creditsDefault = models.find((model) => model.id === creditsDefaultId);
6613
+ if (creditsDefault?.cost !== "credits") {
6614
+ throw new Error(
6615
+ `OPENGENI_CREDITS_DEFAULT_MODEL ${settings.creditsDefaultModel} is not a credits-billed model in the resolved model catalog`
6616
+ );
6617
+ }
6618
+ }
5213
6619
  const deploymentProductIds = new Set(
5214
6620
  models.filter((model) => model.credentialSource.kind === "deployment").map((model) => model.id)
5215
6621
  );
5216
6622
  const noteProductIds = new Set(models.map((model) => model.id));
6623
+ if (settings.resolvedCodexModelsJson !== void 0) {
6624
+ for (const model of z2.array(CodexCatalogModelSchema).parse(JSON.parse(settings.resolvedCodexModelsJson))) {
6625
+ noteProductIds.add(model.id);
6626
+ }
6627
+ }
5217
6628
  for (const model of configuredGatewayCatalogModels(settings)) {
5218
6629
  deploymentProductIds.add(model.productId);
5219
6630
  noteProductIds.add(model.productId);
@@ -5291,6 +6702,62 @@ function resolveNatsCalloutConfig(settings) {
5291
6702
  }
5292
6703
  return { accountSeed, accountName, user, password };
5293
6704
  }
6705
+ function validateObjectStorageSettings(settings) {
6706
+ if (settings.objectStorageBackend === "s3-compatible" || settings.objectStorageBackend === "aws-s3") {
6707
+ if (Boolean(settings.objectStorageAccessKeyId) !== Boolean(settings.objectStorageSecretAccessKey)) {
6708
+ throw new Error(
6709
+ "OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID and OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY must both be set or both omitted"
6710
+ );
6711
+ }
6712
+ if (settings.objectStorageBackend === "s3-compatible" && (settings.objectStorageEndpoint || settings.objectStorageInternalEndpoint || settings.objectStorageSandboxEndpoint) && (!settings.objectStorageAccessKeyId || !settings.objectStorageSecretAccessKey)) {
6713
+ throw new Error(
6714
+ "S3-compatible object storage endpoints require OPENGENI_OBJECT_STORAGE_ACCESS_KEY_ID and OPENGENI_OBJECT_STORAGE_SECRET_ACCESS_KEY"
6715
+ );
6716
+ }
6717
+ if (settings.objectStorageAzureConnectionString || settings.objectStorageAzureAccountName || settings.objectStorageAzureAccountKey || settings.objectStorageAzureEndpoint) {
6718
+ throw new Error(
6719
+ "S3 object storage uses OPENGENI_OBJECT_STORAGE_* S3 settings, not OPENGENI_OBJECT_STORAGE_AZURE_* settings"
6720
+ );
6721
+ }
6722
+ if (settings.objectStorageGcsProjectId || settings.objectStorageGcsCredentialsJson || settings.objectStorageGcsKeyFilename || settings.objectStorageGcsApiEndpoint) {
6723
+ throw new Error(
6724
+ "S3 object storage uses OPENGENI_OBJECT_STORAGE_* S3 settings, not OPENGENI_OBJECT_STORAGE_GCS_* settings"
6725
+ );
6726
+ }
6727
+ } else if (settings.objectStorageBackend === "azure-blob") {
6728
+ if (settings.objectStorageEndpoint || settings.objectStorageInternalEndpoint || settings.objectStorageSandboxEndpoint || settings.objectStorageAccessKeyId || settings.objectStorageSecretAccessKey) {
6729
+ throw new Error(
6730
+ "Azure Blob storage uses OPENGENI_OBJECT_STORAGE_AZURE_* settings, not S3-compatible object storage settings"
6731
+ );
6732
+ }
6733
+ if (settings.objectStorageGcsProjectId || settings.objectStorageGcsCredentialsJson || settings.objectStorageGcsKeyFilename || settings.objectStorageGcsApiEndpoint) {
6734
+ throw new Error(
6735
+ "Azure Blob storage uses OPENGENI_OBJECT_STORAGE_AZURE_* settings, not OPENGENI_OBJECT_STORAGE_GCS_* settings"
6736
+ );
6737
+ }
6738
+ const hasConnectionString = Boolean(settings.objectStorageAzureConnectionString);
6739
+ const hasSharedKey = Boolean(settings.objectStorageAzureAccountName) && Boolean(settings.objectStorageAzureAccountKey);
6740
+ if (!hasConnectionString && !hasSharedKey) {
6741
+ throw new Error(
6742
+ "Azure Blob storage requires OPENGENI_OBJECT_STORAGE_AZURE_CONNECTION_STRING or OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_NAME plus OPENGENI_OBJECT_STORAGE_AZURE_ACCOUNT_KEY"
6743
+ );
6744
+ }
6745
+ } else {
6746
+ if (settings.objectStorageEndpoint || settings.objectStorageInternalEndpoint || settings.objectStorageSandboxEndpoint || settings.objectStorageAccessKeyId || settings.objectStorageSecretAccessKey) {
6747
+ throw new Error(
6748
+ "GCS object storage uses OPENGENI_OBJECT_STORAGE_GCS_* settings, not S3-compatible object storage settings"
6749
+ );
6750
+ }
6751
+ if (settings.objectStorageAzureConnectionString || settings.objectStorageAzureAccountName || settings.objectStorageAzureAccountKey || settings.objectStorageAzureEndpoint) {
6752
+ throw new Error(
6753
+ "GCS object storage uses OPENGENI_OBJECT_STORAGE_GCS_* settings, not OPENGENI_OBJECT_STORAGE_AZURE_* settings"
6754
+ );
6755
+ }
6756
+ if (settings.objectStorageGcsCredentialsJson) {
6757
+ parseGcsCredentialsJson(settings.objectStorageGcsCredentialsJson);
6758
+ }
6759
+ }
6760
+ }
5294
6761
  function resolveNatsControlPlaneAuth(settings) {
5295
6762
  const user = settings.selfhostedNatsControlUser?.trim();
5296
6763
  const password = settings.selfhostedNatsControlPassword?.trim();
@@ -5302,6 +6769,9 @@ function resolveNatsControlPlaneAuth(settings) {
5302
6769
  function splitCsv(raw) {
5303
6770
  return raw.split(",").map((value) => value.trim()).filter(Boolean);
5304
6771
  }
6772
+ function sandboxImageAllowlist(settings) {
6773
+ return [...new Set(splitCsv(settings.sandboxImageAllowlist ?? ""))];
6774
+ }
5305
6775
  function uniqueEnvNames(raw, fieldName) {
5306
6776
  const seen = /* @__PURE__ */ new Set();
5307
6777
  const out = [];
@@ -5332,12 +6802,153 @@ function parseGcsCredentialsJson(raw) {
5332
6802
  function delay(ms) {
5333
6803
  return new Promise((resolve) => setTimeout(resolve, ms));
5334
6804
  }
6805
+ var CLAUDE_CONNECTION_KINDS = ["anthropic", "claude_subscription"];
6806
+ var CLAUDE_NATIVE_MODEL_PROFILES = Object.fromEntries([
6807
+ ...[
6808
+ ["claude-opus-5-5", "medium"],
6809
+ ["claude-sonnet-5-5", "medium"],
6810
+ ["claude-opus-5", "high"],
6811
+ ["claude-sonnet-5", "high"],
6812
+ ["claude-opus-4-8", "high"],
6813
+ ["claude-opus-4-7", "xhigh"]
6814
+ ].map(([id, defaultEffort]) => [
6815
+ id,
6816
+ {
6817
+ efforts: ["low", "medium", "high", "xhigh", "max"],
6818
+ defaultEffort,
6819
+ contextWindowTokens: 1e6,
6820
+ maxOutputTokens: 128e3
6821
+ }
6822
+ ]),
6823
+ ...["claude-opus-4-6", "claude-sonnet-4-6"].map((id) => [
6824
+ id,
6825
+ {
6826
+ efforts: ["low", "medium", "high", "max"],
6827
+ defaultEffort: "high",
6828
+ contextWindowTokens: 1e6,
6829
+ maxOutputTokens: 128e3
6830
+ }
6831
+ ]),
6832
+ [
6833
+ "claude-haiku-4-5-20251001",
6834
+ {
6835
+ efforts: [],
6836
+ defaultEffort: null,
6837
+ contextWindowTokens: 2e5,
6838
+ maxOutputTokens: 64e3
6839
+ }
6840
+ ]
6841
+ ]);
6842
+ function claudeNativeModelProfile(upstreamModelId) {
6843
+ return Object.hasOwn(CLAUDE_NATIVE_MODEL_PROFILES, upstreamModelId) ? CLAUDE_NATIVE_MODEL_PROFILES[upstreamModelId] : void 0;
6844
+ }
6845
+ function claudeProviderId(kind, scope = "organization") {
6846
+ return `${scope}-${kind === "anthropic" ? "anthropic" : "claude-subscription"}`;
6847
+ }
6848
+ function withClaudeConnectionCatalog(settings, connections, scope = "organization") {
6849
+ let providers = parseModelProvidersJson(settings.modelProvidersJson);
6850
+ for (const kind of CLAUDE_CONNECTION_KINDS) {
6851
+ if (kind === "claude_subscription" && !settings.claudeSubscriptionEnabled) {
6852
+ providers = providers.filter((provider) => provider.id !== claudeProviderId(kind, scope));
6853
+ continue;
6854
+ }
6855
+ const connection = connections[kind];
6856
+ if (!connection) continue;
6857
+ const id = claudeProviderId(kind, scope);
6858
+ providers = providers.filter((provider) => provider.id !== id);
6859
+ if (!connection.models.length) continue;
6860
+ providers.push({
6861
+ id,
6862
+ label: kind === "anthropic" ? "Anthropic API" : "Claude subscription",
6863
+ kind: kind === "anthropic" ? `anthropic-${scope}` : `claude-subscription-${scope}`,
6864
+ api: "anthropic-messages",
6865
+ wireProfile: "openai",
6866
+ baseUrl: "https://api.anthropic.com/v1",
6867
+ anthropic: {
6868
+ auth: kind === "anthropic" ? "api-key" : "oauth",
6869
+ cacheTtl: "5m",
6870
+ maxOutputTokens: 128e3,
6871
+ streamIdleTimeoutMs: 6e5
6872
+ },
6873
+ models: connection.models.map((model) => {
6874
+ const profile = claudeNativeModelProfile(model.upstreamModelId);
6875
+ const adaptiveThinking = Boolean(profile?.efforts.length);
6876
+ const contextWindowTokens = profile?.contextWindowTokens ?? 2e5;
6877
+ const outputReserve = profile?.maxOutputTokens ?? 32e3;
6878
+ return {
6879
+ contextWindowTokens,
6880
+ effectiveContextWindowTokens: contextWindowTokens - outputReserve,
6881
+ autoCompactTokenLimit: contextWindowTokens === 1e6 ? 8e5 : Math.min(15e4, contextWindowTokens - outputReserve - 18e3),
6882
+ id: id + "/" + model.upstreamModelId,
6883
+ upstreamModelId: model.upstreamModelId,
6884
+ 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),
6885
+ reasoningEffort: adaptiveThinking,
6886
+ hostedWebSearch: false,
6887
+ capabilities: {
6888
+ ...legacyModelCapabilities(settings, {
6889
+ reasoningEffort: adaptiveThinking,
6890
+ hostedWebSearch: false,
6891
+ vision: true
6892
+ }),
6893
+ inputFileMediaTypes: [],
6894
+ reasoning: {
6895
+ upstream: adaptiveThinking ? "supported" : "unknown",
6896
+ runnable: adaptiveThinking,
6897
+ efforts: [...profile?.efforts ?? []],
6898
+ defaultEffort: profile?.defaultEffort ?? null,
6899
+ required: false
6900
+ },
6901
+ functionCalling: { upstream: "supported", runnable: true },
6902
+ promptCaching: { upstream: "supported", runnable: true, mode: "automatic" }
6903
+ }
6904
+ };
6905
+ })
6906
+ });
6907
+ }
6908
+ return { ...settings, modelProvidersJson: JSON.stringify(providers) };
6909
+ }
6910
+ function withClaudeConnectionCredential(settings, kind, credential, scope = "organization", credentialBinding) {
6911
+ if (kind === "claude_subscription" && !settings.claudeSubscriptionEnabled)
6912
+ throw new Error("Claude subscriptions are not enabled on this deployment");
6913
+ if (!credential.trim()) throw new Error("Claude credential is empty");
6914
+ const bundle = kind === "claude_subscription" && credential.trim().startsWith("{") ? ClaudeSubscriptionCredential.parse(JSON.parse(credential)) : null;
6915
+ return {
6916
+ ...settings,
6917
+ modelProvidersJson: JSON.stringify(
6918
+ parseModelProvidersJson(settings.modelProvidersJson).map(
6919
+ (provider) => provider.id === claudeProviderId(kind, scope) ? {
6920
+ ...provider,
6921
+ apiKey: bundle?.token ?? credential,
6922
+ ...kind === "claude_subscription" && provider.anthropic ? {
6923
+ anthropic: {
6924
+ ...provider.anthropic,
6925
+ identity: bundle?.identity,
6926
+ credentialBinding: credentialBinding ? {
6927
+ connectionId: credentialBinding.connectionId,
6928
+ credentialVersion: credentialBinding.credentialVersion
6929
+ } : void 0
6930
+ }
6931
+ } : {}
6932
+ } : provider
6933
+ )
6934
+ )
6935
+ };
6936
+ }
5335
6937
  export {
5336
6938
  AGENT_INSTRUCTIONS_CORE_PLACEHOLDER,
5337
6939
  AI_GATEWAY_REALTIME_MODELS,
6940
+ CLAUDE_CONNECTION_KINDS,
6941
+ CLAUDE_OAUTH_AUTHORIZE_URL,
6942
+ CLAUDE_OAUTH_CLIENT_ID,
6943
+ CLAUDE_OAUTH_REDIRECT_URL,
6944
+ CLAUDE_OAUTH_SCOPES,
6945
+ CLAUDE_OAUTH_TOKEN_URL,
5338
6946
  CODEX_REALTIME_MODEL_ID,
5339
6947
  CapabilityStateV1Schema,
5340
6948
  CapabilitySupportV1,
6949
+ ClaudeOAuthTokenResponse,
6950
+ ClaudeSubscriptionCredential,
6951
+ ClaudeSubscriptionIdentity,
5341
6952
  ConfiguredModelCostClass,
5342
6953
  DEFAULT_AGENT_INSTRUCTIONS,
5343
6954
  DEFAULT_GOAL_IDLE_BACKOFF_MAX_MS,
@@ -5349,6 +6960,7 @@ export {
5349
6960
  GOOGLE_DRIVE_PROVIDER_RETRY_DELAY_MAX_MS,
5350
6961
  GatewayCatalogModel,
5351
6962
  IntegrationOAuthClientConfigSchema,
6963
+ McpOperationRecoverySchema,
5352
6964
  McpServerConnectionRefSchema,
5353
6965
  ModelCapabilitiesV1Schema,
5354
6966
  ModelCatalogDocument,
@@ -5370,12 +6982,16 @@ export {
5370
6982
  RegistryProviderKind,
5371
6983
  SANDBOX_ARCHIVE_CAPTURE_MAX_TIMEOUT_MS,
5372
6984
  SANDBOX_ARCHIVE_CAPTURE_SETTLEMENT_GRACE_MS,
6985
+ SANDBOX_DEADLINE_COMMAND_STOP_GRACE_MS,
5373
6986
  SANDBOX_LIFECYCLE_RETRY_HANDOFF_GRACE_MS,
5374
6987
  SANDBOX_LIFECYCLE_TRANSITION_MAX_WAIT_MS,
5375
6988
  SANDBOX_REQUIRED_ENV,
5376
6989
  SANDBOX_SNAPSHOT_MAX_TIMEOUT_MS,
5377
6990
  SUPERGROK_REALTIME_MODEL_ID,
5378
6991
  SocialOAuthClientConfigSchema,
6992
+ TurnExecutionPolicyDefinitionMismatchError,
6993
+ TurnExecutionPolicyModelUnavailableError,
6994
+ UnsupportedLatencyModeError,
5379
6995
  VERCEL_AI_GATEWAY_AI_SDK_BASE_URL,
5380
6996
  VERCEL_AI_GATEWAY_BASE_URL,
5381
6997
  VERCEL_AI_GATEWAY_CONNECTION_DOMAIN,
@@ -5388,6 +7004,8 @@ export {
5388
7004
  WORKSPACE_OPENROUTER_PROVIDER_ID,
5389
7005
  WORKSPACE_REALTIME_MODEL_ID_PREFIX,
5390
7006
  XAI_SUBSCRIPTION_MODEL_ID_PREFIX2 as XAI_SUBSCRIPTION_MODEL_ID_PREFIX,
7007
+ agentConfigDeploymentPolicy,
7008
+ allocateRecordedModelListCostByClass,
5391
7009
  allowedFirstPartyMcpToolsForSession,
5392
7010
  applyGitAuthPointerEnvironment,
5393
7011
  applyModelCatalogDocument,
@@ -5396,12 +7014,20 @@ export {
5396
7014
  calculateGatewayReportedCostBreakdown,
5397
7015
  calculateGatewayReportedCostMicros,
5398
7016
  calculateGatewayReportedProviderCostMicros,
7017
+ calculateModelListUsageCostBreakdown,
7018
+ calculateModelListUsageCostSnapshot,
5399
7019
  calculateModelUsageCostBreakdown,
5400
7020
  calculateModelUsageCostMicros,
5401
7021
  calculateVideoGenerationCreditCostMicros,
5402
7022
  canonicalPublicOrigin,
5403
7023
  canonicalizeConfiguredModelId,
7024
+ claudeAuthorizationUrl,
7025
+ claudeNativeModelProfile,
7026
+ claudeProviderId,
7027
+ claudeSubscriptionCapacity,
7028
+ codeSearchDeploymentPolicy,
5404
7029
  codemodeWorkspaceUrl,
7030
+ codexUpstreamModelSlugs,
5405
7031
  collectGitIdentityEnvironment,
5406
7032
  collectSandboxEnvironment,
5407
7033
  configuredAllowedModels,
@@ -5412,6 +7038,7 @@ export {
5412
7038
  configuredGatewayWorkspaceProductModelIds,
5413
7039
  configuredGoogleDriveSyncLimits,
5414
7040
  configuredModelInputIdentities,
7041
+ configuredModelListPricingSchedules,
5415
7042
  configuredModelNotes,
5416
7043
  configuredModelPricing,
5417
7044
  configuredModelPricingSchedules,
@@ -5427,20 +7054,31 @@ export {
5427
7054
  effectiveModalIdleTimeoutSeconds,
5428
7055
  effectiveSandboxDrainSnapshotTimeoutMs,
5429
7056
  effectiveSandboxLifecycle,
7057
+ emptyClaudeUsage,
5430
7058
  environmentsEncryptionKeyBytes,
5431
7059
  firstPartyMcpBaseUrl,
5432
7060
  firstPartyMcpInternalBaseUrl,
5433
7061
  firstPartyMcpInternalWorkspaceUrl,
5434
7062
  firstPartyMcpWorkspaceUrl,
5435
7063
  gatewayRequestPolicyForUpstreamModel,
7064
+ getArtifactMaterializerSettings,
7065
+ getArtifactOutboxSettings,
5436
7066
  getSettings,
5437
7067
  googleDriveOAuthCallbackUrl,
5438
7068
  googleDriveProviderRetryOptions,
5439
7069
  hasGitCredentialRepositorySelection,
5440
7070
  hasGitHubRepositorySelection,
5441
7071
  isDirectOpenAiApiBaseUrl,
7072
+ isManagedOpenRouterFreeRoute,
7073
+ isModelAvailableForNewSelection,
5442
7074
  isUsableVoiceInputSecret,
7075
+ localAllowedOriginEntries,
7076
+ localSandboxApiRouteAllowed,
7077
+ managedUserEmailAllowed,
7078
+ mergeClaudeUsage,
5443
7079
  modelCostClassForConfiguredModel,
7080
+ parseClaudeUsageHeaders,
7081
+ parseClaudeUsageResponse,
5444
7082
  parseExposedPorts,
5445
7083
  parseIntegrationsOauthClientsJson,
5446
7084
  parseMcpServers,
@@ -5473,23 +7111,33 @@ export {
5473
7111
  resolveVoiceInputProviderRegistry,
5474
7112
  responseSatisfiesLatencyMode,
5475
7113
  retryStartupDependency,
7114
+ reviewedModelListPricing,
5476
7115
  runnableLatencyModesForModel,
5477
7116
  sandboxArchiveCaptureTimeoutMs,
5478
7117
  sandboxEnvironmentVariableNames,
7118
+ sandboxImageAllowlist,
5479
7119
  sandboxLifecycleHookIds,
5480
7120
  sandboxLifecycleTransitionWaitMs,
5481
7121
  sandboxPreparationProfiles,
5482
7122
  sandboxWarmRateMicrosPerSecond,
5483
7123
  selectModelPricing,
7124
+ selectSubscriptionAccount,
5484
7125
  serviceTierForLatencyMode,
7126
+ settingsForAcceptedSubscriptionTurn,
5485
7127
  settingsWithResolvedModelContext,
5486
7128
  stableSandboxEnvironmentForRun,
5487
7129
  startupRetryOptions,
5488
7130
  streamTokenDegraded,
7131
+ subscriptionAccountShardIndex,
5489
7132
  temporalConnectionOptions,
7133
+ trustedProxyCidrEntries,
7134
+ usableJevApiKey,
5490
7135
  validateModelCatalogSettings,
5491
7136
  voiceInputDeploymentConfigured,
7137
+ withClaudeConnectionCatalog,
7138
+ withClaudeConnectionCredential,
5492
7139
  withCodexCatalogProvider,
7140
+ withDirectModelProviders,
5493
7141
  withOrganizationGatewayCatalogProvider,
5494
7142
  withOrganizationGatewayCredential,
5495
7143
  withOrganizationOpenRouterCatalogProvider,