@opengeni/worker-bundle 0.23.4 → 0.24.2-canary.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.
Files changed (84) hide show
  1. package/dist/activities/agent-turn/admission.d.ts +17 -2
  2. package/dist/activities/agent-turn/claim.d.ts +1 -0
  3. package/dist/activities/agent-turn/codex.d.ts +2 -2
  4. package/dist/activities/agent-turn/list-models.d.ts +16 -0
  5. package/dist/activities/agent-turn/model-usage.d.ts +15 -1
  6. package/dist/activities/agent-turn/quiescence.d.ts +2 -0
  7. package/dist/activities/agent-turn/run.d.ts +9 -0
  8. package/dist/activities/agent-turn/sandbox-runtime.d.ts +15 -0
  9. package/dist/activities/agent-turn/session-title.d.ts +21 -0
  10. package/dist/activities/agent-turn/stream-attempt.d.ts +4 -0
  11. package/dist/activities/agent-turn/tool-environment.d.ts +2 -0
  12. package/dist/activities/agent-turn/tool-policy.d.ts +36 -5
  13. package/dist/activities/agent-turn/turn-context.d.ts +4 -1
  14. package/dist/activities/agent-turn.d.ts +1 -1
  15. package/dist/activities/automations.d.ts +1 -0
  16. package/dist/activities/capabilities.d.ts +3 -1
  17. package/dist/activities/context-compaction.d.ts +2 -0
  18. package/dist/activities/goals.d.ts +11 -0
  19. package/dist/activities/image-generation-references.d.ts +2 -1
  20. package/dist/activities/scheduled-tasks.d.ts +1 -0
  21. package/dist/activities/types.d.ts +8 -0
  22. package/dist/{activities-control-52W5IDWM.js → activities-control-ZWH7J4KZ.js} +297 -180
  23. package/dist/activities-control-ZWH7J4KZ.js.map +1 -0
  24. package/dist/activities-control.d.ts +2 -0
  25. package/dist/{activities-turn-A2G2KLSY.js → activities-turn-I4OPLQLS.js} +898 -333
  26. package/dist/activities-turn-I4OPLQLS.js.map +1 -0
  27. package/dist/activities.d.ts +2 -0
  28. package/dist/{chunk-GFNXVZVQ.js → chunk-65JEWP2Q.js} +107 -7
  29. package/dist/chunk-65JEWP2Q.js.map +1 -0
  30. package/dist/{chunk-GRFQTTSQ.js → chunk-GDCLDKSH.js} +7 -3
  31. package/dist/{chunk-GRFQTTSQ.js.map → chunk-GDCLDKSH.js.map} +1 -1
  32. package/dist/{chunk-IPVMCAW5.js → chunk-RQNH6CGR.js} +111 -62
  33. package/dist/chunk-RQNH6CGR.js.map +1 -0
  34. package/dist/index.d.ts +1 -0
  35. package/dist/index.js +43 -7
  36. package/dist/index.js.map +1 -1
  37. package/dist/observability-metrics.d.ts +34 -7
  38. package/dist/sandbox-reaper-timeout.d.ts +2 -2
  39. package/dist/sandbox-resume.d.ts +6 -1
  40. package/dist/workflow-bundle.js +26 -3
  41. package/dist/workflows/activities.d.ts +5 -0
  42. package/dist/workflows/automations.d.ts +5 -0
  43. package/package.json +17 -17
  44. package/src/activities/agent-run-admission.ts +7 -1
  45. package/src/activities/agent-turn/admission.ts +47 -6
  46. package/src/activities/agent-turn/claim.ts +33 -5
  47. package/src/activities/agent-turn/codex.ts +2 -2
  48. package/src/activities/agent-turn/compaction-prep.ts +8 -1
  49. package/src/activities/agent-turn/finalization.ts +31 -17
  50. package/src/activities/agent-turn/list-models.ts +101 -0
  51. package/src/activities/agent-turn/model-usage.ts +120 -45
  52. package/src/activities/agent-turn/quiescence.ts +11 -2
  53. package/src/activities/agent-turn/run.ts +80 -4
  54. package/src/activities/agent-turn/sandbox-runtime.ts +78 -81
  55. package/src/activities/agent-turn/session-title.ts +55 -2
  56. package/src/activities/agent-turn/stream-attempt.ts +266 -135
  57. package/src/activities/agent-turn/tool-environment.ts +102 -7
  58. package/src/activities/agent-turn/tool-policy.ts +58 -5
  59. package/src/activities/agent-turn/turn-context.ts +8 -2
  60. package/src/activities/agent-turn.ts +5 -1
  61. package/src/activities/api-integrations.ts +11 -1
  62. package/src/activities/automations.ts +122 -67
  63. package/src/activities/capabilities.ts +129 -2
  64. package/src/activities/context-compaction.ts +3 -0
  65. package/src/activities/goals.ts +108 -31
  66. package/src/activities/image-generation-references.ts +9 -9
  67. package/src/activities/mcp-credentials.ts +53 -0
  68. package/src/activities/rig-verification.ts +5 -3
  69. package/src/activities/scheduled-tasks.ts +217 -110
  70. package/src/activities/site-auth-maintenance.ts +12 -12
  71. package/src/activities/types.ts +6 -0
  72. package/src/activities.ts +1 -0
  73. package/src/activity-services.ts +4 -1
  74. package/src/github-rest-mcp.ts +2 -1
  75. package/src/index.ts +34 -4
  76. package/src/observability-metrics.ts +154 -14
  77. package/src/sandbox-reaper-timeout.ts +10 -4
  78. package/src/sandbox-resume.ts +58 -8
  79. package/src/workflows/activities.ts +15 -0
  80. package/src/workflows/automations.ts +21 -2
  81. package/dist/activities-control-52W5IDWM.js.map +0 -1
  82. package/dist/activities-turn-A2G2KLSY.js.map +0 -1
  83. package/dist/chunk-GFNXVZVQ.js.map +0 -1
  84. package/dist/chunk-IPVMCAW5.js.map +0 -1
@@ -1,17 +1,35 @@
1
1
  import {
2
2
  environmentsEncryptionKeyBytes,
3
3
  type Settings,
4
+ WORKSPACE_GATEWAY_MODEL_ID_PREFIX,
5
+ WORKSPACE_OPENROUTER_MODEL_ID_PREFIX,
4
6
  withCodexCatalogProvider,
5
7
  withWorkspaceGatewayCatalogProvider,
6
8
  withWorkspaceGatewayCredential,
9
+ withWorkspaceOpenRouterCatalogProvider,
10
+ withWorkspaceOpenRouterCredential,
11
+ withOrganizationGatewayCatalogProvider,
12
+ withOrganizationGatewayCredential,
13
+ withOrganizationOpenRouterCatalogProvider,
14
+ withOrganizationOpenRouterCredential,
15
+ ORGANIZATION_GATEWAY_MODEL_ID_PREFIX,
16
+ ORGANIZATION_OPENROUTER_MODEL_ID_PREFIX,
7
17
  withXaiSubscriptionCatalogProvider,
8
18
  } from "@opengeni/config";
9
19
  import { settingsWithEnabledCapabilityMcpServers } from "@opengeni/core";
10
20
  import {
21
+ getWorkspaceGatewayCustomModelForExecution,
22
+ getWorkspaceOpenRouterCustomModelForExecution,
11
23
  listSessionMcpServerMetadata,
12
24
  listSessionMcpServersForRun,
25
+ listWorkspaceGatewayCustomModels,
26
+ listWorkspaceOpenRouterCustomModels,
13
27
  workspaceCodexSubscriptionActive,
14
28
  loadWorkspaceVercelAiGatewayApiKey,
29
+ loadWorkspaceOpenRouterApiKey,
30
+ listOrganizationModelProviderCustomModelsForWorkspace,
31
+ getOrganizationModelProviderCustomModelForExecution,
32
+ loadOrganizationModelProviderApiKey,
15
33
  type Database,
16
34
  type SessionMcpServerForRun,
17
35
  } from "@opengeni/db";
@@ -126,10 +144,119 @@ export function withXaiSubscriptionProvider(settings: Settings): Settings {
126
144
 
127
145
  export async function settingsWithWorkspaceGatewayCredential(
128
146
  db: Database,
147
+ accountId: string,
129
148
  workspaceId: string,
130
149
  settings: Settings,
150
+ retainedProductModelId?: string | null,
131
151
  ): Promise<Settings> {
132
- const catalogSettings = withWorkspaceGatewayCatalogProvider(settings);
152
+ const activeCustomModels = await listWorkspaceGatewayCustomModels(db, { accountId, workspaceId });
153
+ const retainedUpstreamModelId = retainedProductModelId?.startsWith(
154
+ WORKSPACE_GATEWAY_MODEL_ID_PREFIX,
155
+ )
156
+ ? retainedProductModelId.slice(WORKSPACE_GATEWAY_MODEL_ID_PREFIX.length)
157
+ : null;
158
+ const retainedCustomModel = retainedUpstreamModelId
159
+ ? await getWorkspaceGatewayCustomModelForExecution(db, {
160
+ accountId,
161
+ workspaceId,
162
+ upstreamModelId: retainedUpstreamModelId,
163
+ })
164
+ : null;
165
+ const customModels =
166
+ retainedCustomModel &&
167
+ !activeCustomModels.some(
168
+ (model) => model.upstreamModelId === retainedCustomModel.upstreamModelId,
169
+ )
170
+ ? [...activeCustomModels, retainedCustomModel]
171
+ : activeCustomModels;
172
+ const catalogSettings = withWorkspaceGatewayCatalogProvider(settings, customModels);
133
173
  const apiKey = await loadWorkspaceVercelAiGatewayApiKey(db, settings, workspaceId);
134
- return apiKey ? withWorkspaceGatewayCredential(catalogSettings, apiKey) : catalogSettings;
174
+ return apiKey
175
+ ? withWorkspaceGatewayCredential(catalogSettings, apiKey, customModels)
176
+ : catalogSettings;
177
+ }
178
+
179
+ export async function settingsWithWorkspaceOpenRouterCredential(
180
+ db: Database,
181
+ accountId: string,
182
+ workspaceId: string,
183
+ settings: Settings,
184
+ retainedProductModelId?: string | null,
185
+ ): Promise<Settings> {
186
+ const activeCustomModels = await listWorkspaceOpenRouterCustomModels(db, {
187
+ accountId,
188
+ workspaceId,
189
+ });
190
+ const retainedUpstreamModelId = retainedProductModelId?.startsWith(
191
+ WORKSPACE_OPENROUTER_MODEL_ID_PREFIX,
192
+ )
193
+ ? retainedProductModelId.slice(WORKSPACE_OPENROUTER_MODEL_ID_PREFIX.length)
194
+ : null;
195
+ const retainedCustomModel = retainedUpstreamModelId
196
+ ? await getWorkspaceOpenRouterCustomModelForExecution(db, {
197
+ accountId,
198
+ workspaceId,
199
+ upstreamModelId: retainedUpstreamModelId,
200
+ })
201
+ : null;
202
+ const customModels =
203
+ retainedCustomModel &&
204
+ !activeCustomModels.some(
205
+ (model) => model.upstreamModelId === retainedCustomModel.upstreamModelId,
206
+ )
207
+ ? [...activeCustomModels, retainedCustomModel]
208
+ : activeCustomModels;
209
+ const catalogSettings = withWorkspaceOpenRouterCatalogProvider(settings, customModels);
210
+ const apiKey = await loadWorkspaceOpenRouterApiKey(db, settings, workspaceId);
211
+ return apiKey
212
+ ? withWorkspaceOpenRouterCredential(catalogSettings, apiKey, customModels)
213
+ : catalogSettings;
214
+ }
215
+
216
+ export async function settingsWithOrganizationProviderCredentials(
217
+ db: Database,
218
+ accountId: string,
219
+ workspaceId: string,
220
+ settings: Settings,
221
+ retainedProductModelId?: string | null,
222
+ ): Promise<Settings> {
223
+ const buildModels = async (providerKind: "vercel_gateway" | "openrouter", prefix: string) => {
224
+ const active = await listOrganizationModelProviderCustomModelsForWorkspace(db, {
225
+ accountId,
226
+ workspaceId,
227
+ providerKind,
228
+ });
229
+ const upstreamModelId = retainedProductModelId?.startsWith(prefix)
230
+ ? retainedProductModelId.slice(prefix.length)
231
+ : null;
232
+ const retained = upstreamModelId
233
+ ? await getOrganizationModelProviderCustomModelForExecution(db, {
234
+ accountId,
235
+ workspaceId,
236
+ providerKind,
237
+ upstreamModelId,
238
+ })
239
+ : null;
240
+ return retained && !active.some((model) => model.id === retained.id)
241
+ ? [...active, retained]
242
+ : active;
243
+ };
244
+ const gatewayModels = await buildModels("vercel_gateway", ORGANIZATION_GATEWAY_MODEL_ID_PREFIX);
245
+ const openRouterModels = await buildModels("openrouter", ORGANIZATION_OPENROUTER_MODEL_ID_PREFIX);
246
+ const gatewayKey = await loadOrganizationModelProviderApiKey(db, settings, {
247
+ accountId,
248
+ workspaceId,
249
+ providerKind: "vercel_gateway",
250
+ });
251
+ const gatewaySettings = gatewayKey
252
+ ? withOrganizationGatewayCredential(settings, gatewayKey, gatewayModels)
253
+ : withOrganizationGatewayCatalogProvider(settings, gatewayModels);
254
+ const openRouterKey = await loadOrganizationModelProviderApiKey(db, settings, {
255
+ accountId,
256
+ workspaceId,
257
+ providerKind: "openrouter",
258
+ });
259
+ return openRouterKey
260
+ ? withOrganizationOpenRouterCredential(gatewaySettings, openRouterKey, openRouterModels)
261
+ : withOrganizationOpenRouterCatalogProvider(gatewaySettings, openRouterModels);
135
262
  }
@@ -99,6 +99,8 @@ export async function maybeCompactContext(
99
99
  * append again — the event is already durable.
100
100
  */
101
101
  publishLiveEvents?: (events: SessionEvent[]) => Promise<void>;
102
+ /** Observe the durable start immediately after its attempt-fenced commit. */
103
+ onCompactionStarted?: (trigger: "auto" | "operator" | "proactive" | "overflow") => void;
102
104
  /** Materialize retained screenshot receipts only in the attempt-local model view. */
103
105
  materializeHistory?: (items: CompactionItem[]) => Promise<CompactionItem[]>;
104
106
  /** Turn-scoped attachment/modality view; canonical persisted rows stay untouched. */
@@ -208,6 +210,7 @@ export async function maybeCompactContext(
208
210
  `turn attempt was fenced while recording context compaction start: ${started.reason}`,
209
211
  );
210
212
  }
213
+ options.onCompactionStarted?.(trigger);
211
214
  await options.publishLiveEvents?.(started.events);
212
215
 
213
216
  if (useRemoteV2) {
@@ -2,6 +2,12 @@ import {
2
2
  allowedFirstPartyMcpToolsForSession,
3
3
  configuredStaticUsageLimits,
4
4
  policyProviderIdForModel,
5
+ resolveModelProvider,
6
+ resolveTurnExecutionPolicyV1,
7
+ withCodexCatalogProvider,
8
+ withXaiSubscriptionCatalogProvider,
9
+ WORKSPACE_GATEWAY_MODEL_ID_PREFIX,
10
+ WORKSPACE_OPENROUTER_MODEL_ID_PREFIX,
5
11
  type Settings,
6
12
  } from "@opengeni/config";
7
13
  import {
@@ -28,6 +34,11 @@ import type {
28
34
  MaybeContinueGoalInput,
29
35
  MaybeContinueGoalResult,
30
36
  } from "./types";
37
+ import {
38
+ modelFundingForAdmission,
39
+ resolveCatalogSettings,
40
+ resolveWorkspaceCatalogSettings,
41
+ } from "@opengeni/core";
31
42
 
32
43
  export function createGoalActivities(services: () => Promise<ControlActivityServices>) {
33
44
  async function enqueueGoalRetryWake(input: MaybeContinueGoalInput): Promise<void> {
@@ -47,12 +58,15 @@ export function createGoalActivities(services: () => Promise<ControlActivityServ
47
58
  async function maybeContinueGoal(
48
59
  input: MaybeContinueGoalInput,
49
60
  ): Promise<MaybeContinueGoalResult> {
50
- const { settings, db, bus } = await services();
61
+ const service = await services();
62
+ const { db, bus } = service;
63
+ const catalogSourceSettings = service.catalogSourceSettings ?? service.settings;
51
64
  // Cheap pre-read: the common goal-less session skips the budget queries.
52
65
  const existingGoal = await getSessionGoal(db, input.workspaceId, input.sessionId);
53
66
  if (!existingGoal || existingGoal.status !== "active") {
54
67
  return { action: "none" };
55
68
  }
69
+ let settings = (await resolveCatalogSettings(db, catalogSourceSettings)).settings;
56
70
  // Loaded before the budget check so the codex-billed predicate and the
57
71
  // synthesized turn use the SAME effective policy. An explicit per-turn
58
72
  // model can differ from the persisted session default; follow-up goal work
@@ -66,34 +80,34 @@ export function createGoalActivities(services: () => Promise<ControlActivityServ
66
80
  input.workspaceId,
67
81
  input.sessionId,
68
82
  );
69
- let continuationModel = latestStartedTurn?.model ?? session.model;
83
+ const inheritedContinuationModel = latestStartedTurn?.model ?? session.model;
84
+ let continuationModel = inheritedContinuationModel;
70
85
  const continuationReasoningEffort =
71
86
  latestStartedTurn?.reasoningEffort ?? session.reasoningEffort;
72
87
  const continuationLatencyMode = latestStartedTurn?.latencyMode ?? session.latencyMode;
73
- // Workspace model policy: a continuation inherits the last STARTED turn's
74
- // model, so a single policy-violating turn would otherwise re-arm itself on
75
- // every continuation (exactly how one bare-model turn kept a goal loop on
76
- // the paid built-in provider all night). If the inherited model is blocked
77
- // but the session's own default is allowed, recover to the default; if
78
- // both are blocked, pause the goal visibly (the budget-pause channel, with
79
- // a truthful rationale) instead of synthesizing a turn the worker's hard
80
- // gate would fail over and over.
81
- let modelPolicyBlocked: string | null = null;
82
88
  const workspaceModelPolicy = await getWorkspaceModelPolicy(db, input.workspaceId);
83
- if (workspaceModelPolicy) {
84
- const policyBlocks = (modelId: string): boolean =>
85
- !evaluateWorkspaceModelPolicy(workspaceModelPolicy, {
86
- providerId: policyProviderIdForModel(settings, modelId),
87
- modelId,
88
- }).allowed;
89
- if (policyBlocks(continuationModel)) {
90
- if (continuationModel !== session.model && !policyBlocks(session.model)) {
91
- continuationModel = session.model;
92
- } else {
93
- modelPolicyBlocked = `workspace model policy blocks model "${continuationModel}"; pick an allowed model or change the workspace model policy`;
94
- }
95
- }
89
+ if (
90
+ inheritedContinuationModel.startsWith(WORKSPACE_GATEWAY_MODEL_ID_PREFIX) ||
91
+ inheritedContinuationModel.startsWith(WORKSPACE_OPENROUTER_MODEL_ID_PREFIX) ||
92
+ session.model.startsWith(WORKSPACE_GATEWAY_MODEL_ID_PREFIX) ||
93
+ session.model.startsWith(WORKSPACE_OPENROUTER_MODEL_ID_PREFIX)
94
+ ) {
95
+ settings = (
96
+ await resolveWorkspaceCatalogSettings(db, catalogSourceSettings, {
97
+ accountId: input.accountId,
98
+ workspaceId: input.workspaceId,
99
+ retainedProductModelIds: [inheritedContinuationModel, session.model],
100
+ })
101
+ ).settings;
96
102
  }
103
+ const modelDecision = goalContinuationModelDecision({
104
+ settings,
105
+ workspaceModelPolicy,
106
+ inheritedModel: inheritedContinuationModel,
107
+ sessionModel: session.model,
108
+ });
109
+ continuationModel = modelDecision.model;
110
+ let modelPolicyBlocked = modelDecision.blocked;
97
111
  // remote_v2 sessions may only continue on Codex models — refuse synthesis
98
112
  // that would leave the portable/non-Codex path (and mixed history shapes).
99
113
  if (
@@ -112,6 +126,11 @@ export function createGoalActivities(services: () => Promise<ControlActivityServ
112
126
  workspaceId: input.workspaceId,
113
127
  model: continuationModel,
114
128
  });
129
+ const fundedWithoutCredits = goalContinuationFundedWithoutCredits(
130
+ settings,
131
+ continuationModel,
132
+ isCodexRun,
133
+ );
115
134
  // Budget exhaustion pauses the goal visibly instead of failing the
116
135
  // session. Computed up front and applied inside the locked decision so a
117
136
  // limits pause never consumes continuation budget.
@@ -120,8 +139,17 @@ export function createGoalActivities(services: () => Promise<ControlActivityServ
120
139
  db,
121
140
  input.accountId,
122
141
  input.workspaceId,
123
- isCodexRun,
142
+ fundedWithoutCredits,
124
143
  );
144
+ const turnExecutionPolicy = resolveTurnExecutionPolicyV1(settings, {
145
+ modelId: continuationModel,
146
+ requestedModelId: null,
147
+ modelSource: "continuation",
148
+ reasoningEffort: continuationReasoningEffort,
149
+ reasoningSource: "continuation",
150
+ latencyMode: continuationLatencyMode,
151
+ latencyModeSource: "continuation",
152
+ });
125
153
  const decision = await materializeGoalContinuation(db, {
126
154
  accountId: input.accountId,
127
155
  workspaceId: input.workspaceId,
@@ -142,6 +170,7 @@ export function createGoalActivities(services: () => Promise<ControlActivityServ
142
170
  model: continuationModel,
143
171
  reasoningEffort: continuationReasoningEffort,
144
172
  latencyMode: continuationLatencyMode,
173
+ turnExecutionPolicy,
145
174
  tools: withFirstPartyTools(settings, session.tools),
146
175
  sandboxBackend: session.sandboxBackend,
147
176
  },
@@ -174,6 +203,53 @@ export function createGoalActivities(services: () => Promise<ControlActivityServ
174
203
  };
175
204
  }
176
205
 
206
+ export function goalContinuationModelDecision(input: {
207
+ settings: Settings;
208
+ workspaceModelPolicy: Awaited<ReturnType<typeof getWorkspaceModelPolicy>>;
209
+ inheritedModel: string;
210
+ sessionModel: string;
211
+ }): { model: string; blocked: string | null } {
212
+ const catalogSettings = input.settings.supergrokSubscriptionEnabled
213
+ ? withXaiSubscriptionCatalogProvider(
214
+ input.settings.codexSubscriptionEnabled
215
+ ? withCodexCatalogProvider(input.settings)
216
+ : input.settings,
217
+ )
218
+ : input.settings.codexSubscriptionEnabled
219
+ ? withCodexCatalogProvider(input.settings)
220
+ : input.settings;
221
+ const policyBlocks = (modelId: string): boolean =>
222
+ input.workspaceModelPolicy !== null &&
223
+ !evaluateWorkspaceModelPolicy(input.workspaceModelPolicy, {
224
+ providerId: policyProviderIdForModel(catalogSettings, modelId),
225
+ modelId,
226
+ }).allowed;
227
+ const candidates = [...new Set([input.inheritedModel, input.sessionModel])];
228
+ for (const model of candidates) {
229
+ if (resolveModelProvider(catalogSettings, model) && !policyBlocks(model)) {
230
+ return { model, blocked: null };
231
+ }
232
+ }
233
+ if (!resolveModelProvider(catalogSettings, input.inheritedModel)) {
234
+ return {
235
+ model: input.inheritedModel,
236
+ blocked: `model "${input.inheritedModel}" is no longer in the deployment or workspace catalog; choose an available model before resuming the goal`,
237
+ };
238
+ }
239
+ return {
240
+ model: input.inheritedModel,
241
+ blocked: `workspace model policy blocks model "${input.inheritedModel}"; pick an allowed model or change the workspace model policy`,
242
+ };
243
+ }
244
+
245
+ export function goalContinuationFundedWithoutCredits(
246
+ settings: Settings,
247
+ model: string,
248
+ codexBilled: boolean,
249
+ ): boolean {
250
+ return modelFundingForAdmission(settings, model, codexBilled).fundedWithoutCredits;
251
+ }
252
+
177
253
  export function goalContinuationPrompt(
178
254
  _goal: SessionGoal,
179
255
  _autoContinuation: number,
@@ -185,6 +261,7 @@ export function goalContinuationPrompt(
185
261
  "Waiting on child sessions or external events:",
186
262
  "- When the next progress depends on child sessions you spawned or on an external event, do not sleep, loop, or poll sessions_list/session_get/session_events to wait for it.",
187
263
  "- Re-check sessions_list or session_get once; if the work is still in flight, call opengeni__goal_wait with a concrete reason and a deadline (untilSeconds), then end your turn immediately. You will be woken by a child result, a message, a human prompt, or at the deadline, and this goal stays active.",
264
+ "- If the immediately preceding user-facing update already reported this same unchanged wait, do not restate it or produce another equivalent final answer. Call opengeni__goal_wait and end the turn. Report only material new state or a newly discovered blocker.",
188
265
  "- A hold is for child/external progress only. If you are blocked on a human decision, use opengeni__goal_pause under the blocked audit below instead.",
189
266
  "",
190
267
  ]
@@ -269,13 +346,13 @@ async function goalRunBudgetBlocked(
269
346
  db: Database,
270
347
  accountId: string,
271
348
  workspaceId: string,
272
- isCodexRun: boolean,
349
+ fundedWithoutCredits: boolean,
273
350
  ): Promise<string | null> {
274
- // Codex-billed continuations are paid by the user's ChatGPT/Codex plan: skip
275
- // the credit-balance gate and the monthly model-cost cap. The agent-run COUNT
276
- // cap below is a volume quota (not a credit/cost gate) and is intentionally kept.
351
+ // Free, subscription, and workspace-funded continuations skip OpenGeni's
352
+ // credit-balance gate and monthly model-cost cap. The agent-run COUNT cap
353
+ // below is a volume quota (not a credit/cost gate) and remains enforced.
277
354
  if (
278
- !isCodexRun &&
355
+ !fundedWithoutCredits &&
279
356
  (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")
280
357
  ) {
281
358
  const balance = await getBillingBalance(db, accountId);
@@ -285,7 +362,7 @@ async function goalRunBudgetBlocked(
285
362
  }
286
363
  if (settings.usageLimitsMode === "static" || settings.usageLimitsMode === "managed") {
287
364
  const limits = configuredStaticUsageLimits(settings);
288
- if (!isCodexRun && limits.maxMonthlyCostMicrosPerAccount) {
365
+ if (!fundedWithoutCredits && limits.maxMonthlyCostMicrosPerAccount) {
289
366
  const used = await sumUsageQuantity(db, {
290
367
  accountId,
291
368
  eventType: "model.cost",
@@ -200,20 +200,20 @@ async function referenceBytes(
200
200
  );
201
201
  }
202
202
  return {
203
- bytes: await readStoredFile(input.objectStorage, file),
203
+ bytes: await readStoredImageReferenceFile(input.objectStorage, file),
204
204
  file,
205
205
  };
206
206
  }
207
207
 
208
- async function readStoredFile(objectStorage: ObjectStorage, file: FileAsset): Promise<Uint8Array> {
209
- const bytes = await objectStorage.getFileRange(file, {
210
- start: 0,
211
- end: file.sizeBytes - 1,
212
- });
213
- if (!bytes) {
208
+ export async function readStoredImageReferenceFile(
209
+ objectStorage: Pick<ObjectStorage, "getFileBytes">,
210
+ file: FileAsset,
211
+ ): Promise<Uint8Array> {
212
+ const bytes = await objectStorage.getFileBytes(file);
213
+ if (bytes.byteLength !== file.sizeBytes) {
214
214
  throw new ImageGenerationReferenceError(
215
- "reference_unavailable",
216
- "The durable image reference bytes are unavailable.",
215
+ "reference_integrity_mismatch",
216
+ "The durable image reference bytes do not match their file metadata.",
217
217
  );
218
218
  }
219
219
  return bytes;
@@ -12,6 +12,9 @@ import {
12
12
  } from "@opengeni/db";
13
13
  import { recordTenancyCompatibilityLaneUse, type Observability } from "@opengeni/observability";
14
14
 
15
+ const OPENGENI_CONNECTION_ID_PATTERN =
16
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
17
+
15
18
  export function connectionTokenResolverForTurn(input: {
16
19
  db: Database;
17
20
  settings: Settings;
@@ -44,6 +47,56 @@ export function connectionTokenResolverForTurn(input: {
44
47
  })
45
48
  : buildConnectionTokenResolver(input.db, input.settings);
46
49
  return async (request) => {
50
+ // Host-owned refs carry explicit provenance because their opaque ids may
51
+ // themselves be valid UUIDs. They never enter OpenGeni's native connection
52
+ // authority or PostgreSQL UUID lookup; the bound host authorizes the exact
53
+ // immutable turn context on every credential request.
54
+ if (request.connectionRef.authoritySource === "host") {
55
+ if (hostResolver) return await baseResolver(request);
56
+ return {
57
+ status: "auth_needed",
58
+ reason: "unsupported_auth",
59
+ providerDomain: request.connectionRef.providerDomain,
60
+ authoritySource: "host",
61
+ ...(request.connectionRef.provider ? { provider: request.connectionRef.provider } : {}),
62
+ ...(request.connectionRef.connectionId
63
+ ? { connectionId: request.connectionRef.connectionId }
64
+ : {}),
65
+ ...(request.connectionRef.scopes ? { scopes: request.connectionRef.scopes } : {}),
66
+ ...(request.connectionRef.resource ? { resource: request.connectionRef.resource } : {}),
67
+ ...(request.connectionRef.selectedResources
68
+ ? { selectedResources: request.connectionRef.selectedResources }
69
+ : {}),
70
+ };
71
+ }
72
+ // Before explicit provenance existed, the public embedding contract let a
73
+ // bound host use any non-UUID opaque id. Preserve those frozen/stored refs
74
+ // during upgrades while keeping every UUID-shaped omission on OpenGeni's
75
+ // native accepted-use authority. New host refs must carry authoritySource
76
+ // so UUID-shaped host ids are unambiguous.
77
+ if (
78
+ hostResolver &&
79
+ request.connectionRef.connectionId &&
80
+ !OPENGENI_CONNECTION_ID_PATTERN.test(request.connectionRef.connectionId)
81
+ ) {
82
+ try {
83
+ return await baseResolver(request);
84
+ } catch {
85
+ return {
86
+ status: "auth_needed",
87
+ reason: "refresh_failed",
88
+ providerDomain: request.connectionRef.providerDomain,
89
+ authoritySource: "host",
90
+ ...(request.connectionRef.provider ? { provider: request.connectionRef.provider } : {}),
91
+ connectionId: request.connectionRef.connectionId,
92
+ ...(request.connectionRef.scopes ? { scopes: request.connectionRef.scopes } : {}),
93
+ ...(request.connectionRef.resource ? { resource: request.connectionRef.resource } : {}),
94
+ ...(request.connectionRef.selectedResources
95
+ ? { selectedResources: request.connectionRef.selectedResources }
96
+ : {}),
97
+ };
98
+ }
99
+ }
47
100
  const acceptedDelegation = input.turn.personalConnectionDelegations.find(
48
101
  (delegation) =>
49
102
  (delegation.connectionType === undefined ||
@@ -115,11 +115,13 @@ export function rigPlatformChecksForSettings(
115
115
  'test -x "$__og_browser_engine"',
116
116
  '__og_browser_token="$(mktemp)"',
117
117
  "trap 'opengeni-browserd-down >/dev/null 2>&1 || true; rm -f \"$__og_browser_token\"' EXIT",
118
- "printf '%s\\n' 'rig-platform-check' > \"$__og_browser_token\"",
118
+ "__og_browser_token_value=\"$(od -An -N32 -tx1 /dev/urandom | tr -d '[:space:]')\"",
119
+ 'test "${#__og_browser_token_value}" -eq 64',
120
+ 'printf \'%s\\n\' "$__og_browser_token_value" > "$__og_browser_token"',
119
121
  'chmod 0600 "$__og_browser_token"',
120
122
  'OPENGENI_BROWSERD_ADMIN_TOKEN_FILE="$__og_browser_token" OPENGENI_BROWSERD_PORT=7682 OPENGENI_BROWSERD_ALLOWED_ORIGINS= opengeni-browserd-up',
121
123
  "curl --noproxy '*' -fsS http://127.0.0.1:7682/healthz >/dev/null",
122
- "curl --noproxy '*' -fsS -H 'Authorization: Bearer rig-platform-check' http://127.0.0.1:7682/v1/browser-sessions >/dev/null",
124
+ "curl --noproxy '*' -fsS -H \"Authorization: Bearer $__og_browser_token_value\" http://127.0.0.1:7682/v1/browser-sessions >/dev/null",
123
125
  ].join("\n"),
124
126
  },
125
127
  ];
@@ -148,7 +150,7 @@ export function rigPlatformChecksForSettings(
148
150
  "test -x /usr/local/bin/opengeni-desktop-down",
149
151
  "command -v Xvfb >/dev/null",
150
152
  "command -v x11vnc >/dev/null",
151
- "command -v websockify >/dev/null",
153
+ "test -x /opt/noVNC/utils/novnc_proxy",
152
154
  "command -v scrot >/dev/null",
153
155
  "command -v xdotool >/dev/null",
154
156
  '__og_desktop_home="$(mktemp -d)"',