@opengeni/worker-bundle 0.20.1 → 0.22.0-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 (189) hide show
  1. package/dist/activities/agent-turn/admission.d.ts +52 -0
  2. package/dist/activities/agent-turn/agent-build.d.ts +89 -0
  3. package/dist/activities/agent-turn/claim.d.ts +67 -0
  4. package/dist/activities/agent-turn/codex-capacity.d.ts +40 -0
  5. package/dist/activities/agent-turn/codex.d.ts +32 -0
  6. package/dist/activities/agent-turn/compaction-prep.d.ts +88 -0
  7. package/dist/activities/agent-turn/credential-leases.d.ts +56 -0
  8. package/dist/activities/agent-turn/errors.d.ts +253 -0
  9. package/dist/activities/agent-turn/failure-settlement.d.ts +33 -0
  10. package/dist/activities/agent-turn/file-resources.d.ts +37 -0
  11. package/dist/activities/agent-turn/finalization.d.ts +42 -0
  12. package/dist/activities/agent-turn/github-repository-bindings.d.ts +105 -0
  13. package/dist/activities/agent-turn/governance-model.d.ts +66 -0
  14. package/dist/activities/agent-turn/history-sink.d.ts +52 -0
  15. package/dist/activities/agent-turn/history.d.ts +63 -0
  16. package/dist/activities/agent-turn/media-artifacts.d.ts +145 -0
  17. package/dist/activities/agent-turn/model-usage.d.ts +218 -0
  18. package/dist/activities/agent-turn/quiescence.d.ts +135 -0
  19. package/dist/activities/agent-turn/run-credentials.d.ts +84 -0
  20. package/dist/activities/agent-turn/run.d.ts +3 -0
  21. package/dist/activities/agent-turn/sandbox-establish.d.ts +93 -0
  22. package/dist/activities/agent-turn/sandbox-provision.d.ts +89 -0
  23. package/dist/activities/agent-turn/sandbox-route.d.ts +151 -0
  24. package/dist/activities/agent-turn/sandbox-runtime.d.ts +44 -0
  25. package/dist/activities/agent-turn/stream-attempt.d.ts +107 -0
  26. package/dist/activities/agent-turn/tool-environment.d.ts +142 -0
  27. package/dist/activities/agent-turn/tool-policy.d.ts +127 -0
  28. package/dist/activities/agent-turn/tool-result-spill.d.ts +59 -0
  29. package/dist/activities/agent-turn/turn-context.d.ts +144 -0
  30. package/dist/activities/agent-turn/xai-capacity.d.ts +2 -0
  31. package/dist/activities/agent-turn.d.ts +12 -954
  32. package/dist/activities/automations.d.ts +16 -0
  33. package/dist/activities/common.d.ts +1 -1
  34. package/dist/activities/connector-attachments.d.ts +13 -0
  35. package/dist/activities/documents.d.ts +1 -0
  36. package/dist/activities/environment.d.ts +26 -15
  37. package/dist/activities/generated-images.d.ts +1 -1
  38. package/dist/activities/git-credential-renewal.d.ts +3 -1
  39. package/dist/activities/goals.d.ts +4 -1
  40. package/dist/activities/google-drive-provider.d.ts +29 -0
  41. package/dist/activities/google-drive-publication.d.ts +66 -0
  42. package/dist/activities/image-generation-references.d.ts +2 -0
  43. package/dist/activities/incident-telemetry-authority.d.ts +52 -0
  44. package/dist/activities/incident-telemetry-preflight.d.ts +71 -0
  45. package/dist/activities/knowledge-source-sync-driver.d.ts +21 -0
  46. package/dist/activities/knowledge-source-sync.d.ts +33 -1
  47. package/dist/activities/mcp-credentials.d.ts +9 -3
  48. package/dist/activities/open-suffix-resume.d.ts +77 -0
  49. package/dist/activities/packs.d.ts +3 -11
  50. package/dist/activities/parent-wake.d.ts +19 -0
  51. package/dist/activities/retained-screenshot-reaper.d.ts +1 -1
  52. package/dist/activities/retained-screenshots.d.ts +1 -1
  53. package/dist/activities/rig-verification.d.ts +1 -1
  54. package/dist/activities/run-input.d.ts +16 -7
  55. package/dist/activities/sandbox-images.d.ts +1 -14
  56. package/dist/activities/sandbox-lease.d.ts +21 -3
  57. package/dist/activities/scheduled-tasks.d.ts +47 -0
  58. package/dist/activities/types.d.ts +23 -2
  59. package/dist/activities/video-media-validation.d.ts +1 -1
  60. package/dist/activities/video-output-retention.d.ts +1 -2
  61. package/dist/activities/xai-auth.d.ts +3 -0
  62. package/dist/{activities-control-SMKF2OBE.js → activities-control-DKG22ONJ.js} +2946 -549
  63. package/dist/activities-control-DKG22ONJ.js.map +1 -0
  64. package/dist/activities-control.d.ts +6 -2
  65. package/dist/activities-turn-4IMC3MAA.js +21326 -0
  66. package/dist/activities-turn-4IMC3MAA.js.map +1 -0
  67. package/dist/activities.d.ts +7 -3
  68. package/dist/artifact-materializer-entry.js +41 -22
  69. package/dist/artifact-materializer-entry.js.map +1 -1
  70. package/dist/{chunk-N5TJIFCE.js → chunk-CE7TPKBS.js} +468 -1
  71. package/dist/chunk-CE7TPKBS.js.map +1 -0
  72. package/dist/chunk-CNYGVRKF.js +4698 -0
  73. package/dist/chunk-CNYGVRKF.js.map +1 -0
  74. package/dist/connection-provider-use.d.ts +18 -0
  75. package/dist/editable-artifact-materializer.d.ts +4 -3
  76. package/dist/github-rest-mcp.d.ts +26 -0
  77. package/dist/index.d.ts +10 -2
  78. package/dist/index.js +58 -14
  79. package/dist/index.js.map +1 -1
  80. package/dist/knowledge-source-sync-activity-policy.d.ts +2 -0
  81. package/dist/model-context-contributions.d.ts +8 -4
  82. package/dist/observability-metrics.d.ts +63 -4
  83. package/dist/opensandbox-kubernetes-inventory.d.ts +21 -0
  84. package/dist/personal-github-git-credentials.d.ts +9 -0
  85. package/dist/pr-review-credentials.d.ts +6 -0
  86. package/dist/sandbox-archive-storage.d.ts +45 -0
  87. package/dist/sandbox-resume.d.ts +65 -6
  88. package/dist/sandbox-routing.d.ts +38 -2
  89. package/dist/scheduled-alert-occurrence.d.ts +33 -0
  90. package/dist/workflow-bundle.js +87 -28
  91. package/dist/workflows/activities.d.ts +1 -0
  92. package/dist/workflows/automations.d.ts +6 -0
  93. package/dist/workflows/document-index.d.ts +1 -0
  94. package/dist/workflows.d.ts +1 -0
  95. package/package.json +17 -17
  96. package/src/activities/agent-turn/admission.ts +292 -0
  97. package/src/activities/agent-turn/agent-build.ts +802 -0
  98. package/src/activities/agent-turn/claim.ts +590 -0
  99. package/src/activities/agent-turn/codex-capacity.ts +720 -0
  100. package/src/activities/agent-turn/codex.ts +94 -0
  101. package/src/activities/agent-turn/compaction-prep.ts +722 -0
  102. package/src/activities/agent-turn/credential-leases.ts +240 -0
  103. package/src/activities/agent-turn/errors.ts +1068 -0
  104. package/src/activities/agent-turn/failure-settlement.ts +1436 -0
  105. package/src/activities/agent-turn/file-resources.ts +227 -0
  106. package/src/activities/agent-turn/finalization.ts +754 -0
  107. package/src/activities/agent-turn/github-repository-bindings.ts +300 -0
  108. package/src/activities/agent-turn/governance-model.ts +465 -0
  109. package/src/activities/agent-turn/history-sink.ts +139 -0
  110. package/src/activities/agent-turn/history.ts +200 -0
  111. package/src/activities/agent-turn/media-artifacts.ts +359 -0
  112. package/src/activities/agent-turn/model-usage.ts +823 -0
  113. package/src/activities/agent-turn/quiescence.ts +353 -0
  114. package/src/activities/agent-turn/run-credentials.ts +761 -0
  115. package/src/activities/agent-turn/run.ts +1530 -0
  116. package/src/activities/agent-turn/sandbox-establish.ts +1207 -0
  117. package/src/activities/agent-turn/sandbox-provision.ts +569 -0
  118. package/src/activities/agent-turn/sandbox-route.ts +358 -0
  119. package/src/activities/agent-turn/sandbox-runtime.ts +731 -0
  120. package/src/activities/agent-turn/stream-attempt.ts +1670 -0
  121. package/src/activities/agent-turn/tool-environment.ts +729 -0
  122. package/src/activities/agent-turn/tool-policy.ts +216 -0
  123. package/src/activities/agent-turn/tool-result-spill.ts +265 -0
  124. package/src/activities/agent-turn/turn-context.ts +281 -0
  125. package/src/activities/agent-turn/xai-capacity.ts +229 -0
  126. package/src/activities/agent-turn.ts +12 -12575
  127. package/src/activities/api-integrations.ts +3 -0
  128. package/src/activities/automations.ts +214 -0
  129. package/src/activities/codemode-dispatcher.ts +12 -1
  130. package/src/activities/common.ts +1 -5
  131. package/src/activities/connector-attachments.ts +168 -0
  132. package/src/activities/context-compaction.ts +18 -0
  133. package/src/activities/documents.ts +6 -4
  134. package/src/activities/environment.ts +151 -55
  135. package/src/activities/generated-images.ts +26 -11
  136. package/src/activities/git-credential-renewal.ts +13 -3
  137. package/src/activities/goals.ts +85 -19
  138. package/src/activities/google-drive-provider.ts +178 -0
  139. package/src/activities/google-drive-publication.ts +938 -0
  140. package/src/activities/image-generation-references.ts +11 -2
  141. package/src/activities/incident-telemetry-authority.ts +327 -0
  142. package/src/activities/incident-telemetry-preflight.ts +317 -0
  143. package/src/activities/knowledge-source-sync-driver.ts +23 -0
  144. package/src/activities/knowledge-source-sync.ts +556 -40
  145. package/src/activities/mcp-credentials.ts +191 -17
  146. package/src/activities/open-suffix-resume.ts +422 -0
  147. package/src/activities/packs.ts +12 -60
  148. package/src/activities/parent-wake.ts +64 -14
  149. package/src/activities/retained-screenshot-reaper.ts +6 -3
  150. package/src/activities/retained-screenshots.ts +15 -47
  151. package/src/activities/rig-verification.ts +1 -1
  152. package/src/activities/run-input.ts +128 -136
  153. package/src/activities/sandbox-images.ts +7 -166
  154. package/src/activities/sandbox-lease.ts +406 -15
  155. package/src/activities/scheduled-tasks.ts +2103 -411
  156. package/src/activities/session-state.ts +10 -2
  157. package/src/activities/types.ts +32 -2
  158. package/src/activities/video-media-validation.ts +3 -3
  159. package/src/activities/video-output-retention.ts +2 -57
  160. package/src/activities/xai-auth.ts +8 -0
  161. package/src/activities-control.ts +2 -0
  162. package/src/activities.ts +3 -0
  163. package/src/activity-services.ts +13 -4
  164. package/src/connection-provider-use.ts +36 -0
  165. package/src/editable-artifact-materializer-subprocess.ts +25 -14
  166. package/src/editable-artifact-materializer.ts +29 -18
  167. package/src/github-rest-mcp.ts +713 -0
  168. package/src/http.ts +16 -6
  169. package/src/index.ts +40 -5
  170. package/src/knowledge-source-sync-activity-policy.ts +2 -0
  171. package/src/model-context-contributions.ts +33 -10
  172. package/src/observability-metrics.ts +357 -0
  173. package/src/opensandbox-kubernetes-inventory.ts +292 -0
  174. package/src/personal-github-git-credentials.ts +331 -0
  175. package/src/pr-review-credentials.ts +163 -0
  176. package/src/sandbox-archive-storage.ts +159 -0
  177. package/src/sandbox-resume.ts +449 -63
  178. package/src/sandbox-routing.ts +314 -16
  179. package/src/scheduled-alert-occurrence.ts +176 -0
  180. package/src/workflows/activities.ts +18 -2
  181. package/src/workflows/automations.ts +11 -0
  182. package/src/workflows/session.ts +13 -3
  183. package/src/workflows.ts +1 -0
  184. package/dist/activities-control-SMKF2OBE.js.map +0 -1
  185. package/dist/activities-turn-IDS3WEHA.js +0 -16532
  186. package/dist/activities-turn-IDS3WEHA.js.map +0 -1
  187. package/dist/chunk-N5TJIFCE.js.map +0 -1
  188. package/dist/chunk-P6Z2SLAA.js +0 -3092
  189. package/dist/chunk-P6Z2SLAA.js.map +0 -1
@@ -0,0 +1,465 @@
1
+ import {
2
+ materializeRigVersionForAttempt,
3
+ getWorkspaceModelPolicy,
4
+ getWorkspace,
5
+ resolveCompanyBrainContextSelection,
6
+ getGeneratedVideoArtifact,
7
+ listSessionSystemUpdatesForTurn,
8
+ getOrCreateCompanyProfileSnapshot,
9
+ getOrCreatePreferenceRegistrySnapshot,
10
+ getOrCreateWorkspaceInstructionPolicySnapshot,
11
+ PreferenceRegistryInitiatorError,
12
+ resolveSessionAttemptPersonalResources,
13
+ } from "@opengeni/db";
14
+ import {
15
+ projectHistoryForProvider,
16
+ restoreGenericDispatchHistoryItems,
17
+ projectModelInputForCapabilities,
18
+ hasActiveWorkspaceInstructionPolicy,
19
+ renderWorkspaceGovernanceContext,
20
+ type OpenGeniRuntime,
21
+ } from "@opengeni/runtime";
22
+ import { settingsWithResolvedModelContext, type Settings } from "@opengeni/config";
23
+ import { settingsWithSessionMcpServersForRun } from "../capabilities";
24
+ import { resolveRigProviderImageForRun } from "@opengeni/core";
25
+ import {
26
+ resolveWorkspacePackRuntime,
27
+ resolveWorkspaceInstalledSkillRuntime,
28
+ settingsWithPackSandboxImage,
29
+ settingsWithRigImage,
30
+ } from "../packs";
31
+ import { createModelHistoryAttachmentProjector } from "../run-input";
32
+ import type {
33
+ TurnActivityServices as ActivityServices,
34
+ RunAgentTurnInput,
35
+ RunAgentTurnResult,
36
+ } from "../types";
37
+ import {
38
+ buildCompanyBrainContributionReceipt,
39
+ summarizeCompanyBrainContributions,
40
+ } from "../../model-context-contributions";
41
+ import {
42
+ collectGeneratedImageReceipts,
43
+ projectGeneratedImageHistoryForModel,
44
+ } from "../generated-images";
45
+ import { createTurnMediaArtifacts } from "./media-artifacts";
46
+ import { retryWhileMissing } from "@opengeni/storage";
47
+ import { WorkspaceModelPolicyBlockedError } from "@opengeni/runtime";
48
+ import {
49
+ evaluateWorkspaceModelPolicy,
50
+ resolveWorkspaceAgentHumanInputEnabled,
51
+ type MediaGenerationResult,
52
+ } from "@opengeni/contracts";
53
+
54
+ import { assertWorkspaceHumanInputAllowed } from "./admission";
55
+ import {
56
+ lazyToolTransportForTurn,
57
+ openAiHostedImageProviderBindingForTurn,
58
+ modelAttachmentInputPolicyForTurn,
59
+ } from "./tool-policy";
60
+
61
+ import type { ClaimTurnOk } from "./claim";
62
+ import type { EventingState, WorkspaceRefState } from "./turn-context";
63
+
64
+ export type GovernanceModelDeps = {
65
+ input: RunAgentTurnInput;
66
+ db: ActivityServices["db"];
67
+ runtime: ActivityServices["runtime"];
68
+ objectStorage: ActivityServices["objectStorage"];
69
+ eventing: EventingState;
70
+ workspaceRefs: WorkspaceRefState;
71
+ media: ReturnType<typeof createTurnMediaArtifacts>;
72
+ turn: ClaimTurnOk["turn"];
73
+ session: ClaimTurnOk["session"];
74
+ capabilitySettings: ClaimTurnOk["capabilitySettings"];
75
+ fileAuthoritySubjectId: ClaimTurnOk["fileAuthoritySubjectId"];
76
+ humanInputResume: ClaimTurnOk["humanInputResume"];
77
+ turnExecutionPolicy: ClaimTurnOk["turnExecutionPolicy"];
78
+ requiredGeneratedVideoFiles: Array<{
79
+ operationId: string;
80
+ artifactId: string;
81
+ fileId: string;
82
+ objectKey: string;
83
+ sizeBytes: number;
84
+ sha256: string;
85
+ filename: string;
86
+ }>;
87
+ };
88
+
89
+ export type GovernanceModelOk = {
90
+ runtimePreparationStartedAt: number;
91
+ packRuntime: Awaited<ReturnType<typeof resolveWorkspacePackRuntime>>;
92
+ installedSkillRuntime: Awaited<ReturnType<typeof resolveWorkspaceInstalledSkillRuntime>>;
93
+ rigVersion:
94
+ | NonNullable<Awaited<ReturnType<typeof materializeRigVersionForAttempt>>>["version"]
95
+ | null;
96
+ rigName: string | null;
97
+ agentHumanInputEnabled: boolean;
98
+ workspaceAgentInstructions: string | null | undefined;
99
+ workspaceGovernance: ReturnType<typeof renderWorkspaceGovernanceContext>;
100
+ structuredWorkspacePolicyActive: boolean;
101
+ workspaceMemory: string | null | undefined;
102
+ buildCompanyBrainContributionReceiptFor: (
103
+ skillActivations: Parameters<
104
+ typeof buildCompanyBrainContributionReceipt
105
+ >[0]["skillActivations"],
106
+ ) => ReturnType<typeof buildCompanyBrainContributionReceipt>;
107
+ logicalSandboxSettings: Settings;
108
+ verifiedRigProviderImageId: string | undefined;
109
+ runSettings: Settings;
110
+ resolvedModel: ReturnType<OpenGeniRuntime["resolveTurnModel"]>;
111
+ providerApi:
112
+ | NonNullable<ReturnType<OpenGeniRuntime["resolveTurnModel"]>>["provider"]["api"]
113
+ | "responses";
114
+ nativeImageProviderBinding: ReturnType<typeof openAiHostedImageProviderBindingForTurn>;
115
+ lazyToolTransport: ReturnType<typeof lazyToolTransportForTurn>;
116
+ modelInputPolicy: ReturnType<typeof modelAttachmentInputPolicyForTurn>;
117
+ supportsImageInput: boolean;
118
+ modelHistoryProjector: (
119
+ items: Array<Record<string, unknown>>,
120
+ projectionOptions?: Parameters<ReturnType<typeof createModelHistoryAttachmentProjector>>[1],
121
+ ) => Promise<Array<Record<string, unknown>>>;
122
+ generatedImageHistoryProjector: (
123
+ items: Array<Record<string, unknown>>,
124
+ ) => Promise<Array<Record<string, unknown>>>;
125
+ compactionModelHistoryProjector: (
126
+ items: Array<Record<string, unknown>>,
127
+ ) => Promise<Array<Record<string, unknown>>>;
128
+ };
129
+
130
+ export type GovernanceModelOutcome = { exit: RunAgentTurnResult } | { ok: GovernanceModelOk };
131
+
132
+ export async function prepareGovernanceAndModel(
133
+ deps: GovernanceModelDeps,
134
+ ): Promise<GovernanceModelOutcome> {
135
+ const {
136
+ input,
137
+ db,
138
+ runtime,
139
+ objectStorage,
140
+ eventing,
141
+ workspaceRefs,
142
+ media,
143
+ turn,
144
+ session,
145
+ capabilitySettings,
146
+ fileAuthoritySubjectId,
147
+ humanInputResume,
148
+ turnExecutionPolicy,
149
+ requiredGeneratedVideoFiles,
150
+ } = deps;
151
+
152
+ const runtimePreparationStartedAt = performance.now();
153
+
154
+ // Personal Rig/Variable Set authority is revalidated immediately before
155
+ // any direct resource read. The database function is a zero-row no-op for
156
+ // sessions with no personal resources, preserving the legacy workspace path.
157
+ await resolveSessionAttemptPersonalResources(db, {
158
+ accountId: input.accountId,
159
+ workspaceId: input.workspaceId,
160
+ subjectId: fileAuthoritySubjectId,
161
+ attemptId: input.attemptId,
162
+ });
163
+
164
+ const governanceClaims = {
165
+ accountId: input.accountId,
166
+ workspaceId: input.workspaceId,
167
+ sessionId: input.sessionId,
168
+ turnId: turn.id,
169
+ attemptId: input.attemptId,
170
+ executionGeneration: turn.executionGeneration,
171
+ };
172
+ // Independent workspace reads after the personal-resource fence. Pack,
173
+ // installed skills, frozen rig, governance snapshots, and model policy do
174
+ // not depend on each other. Company-brain selection still waits on the
175
+ // snapshots below so its receipt stays exact.
176
+ const [
177
+ packRuntime,
178
+ installedSkillRuntime,
179
+ rigMaterialization,
180
+ [workspace, companyProfileSnapshot, instructionPolicySnapshot, preferenceSnapshot],
181
+ workspaceModelPolicy,
182
+ ] = await Promise.all([
183
+ resolveWorkspacePackRuntime(db, input.workspaceId),
184
+ resolveWorkspaceInstalledSkillRuntime(db, input.workspaceId),
185
+ session.rigId && session.rigVersionId
186
+ ? (async () =>
187
+ await materializeRigVersionForAttempt(db, {
188
+ accountId: input.accountId,
189
+ workspaceId: input.workspaceId,
190
+ subjectId: fileAuthoritySubjectId,
191
+ sessionId: input.sessionId,
192
+ turnId: turn.id,
193
+ attemptId: input.attemptId,
194
+ executionGeneration: turn.executionGeneration,
195
+ }))()
196
+ : Promise.resolve(null),
197
+ Promise.all([
198
+ getWorkspace(db, input.workspaceId),
199
+ getOrCreateCompanyProfileSnapshot(db, governanceClaims),
200
+ getOrCreateWorkspaceInstructionPolicySnapshot(db, governanceClaims),
201
+ getOrCreatePreferenceRegistrySnapshot(db, governanceClaims).catch((error) => {
202
+ if (error instanceof PreferenceRegistryInitiatorError) return null;
203
+ throw error;
204
+ }),
205
+ ]),
206
+ getWorkspaceModelPolicy(db, input.workspaceId),
207
+ ]);
208
+ const rigVersion = rigMaterialization?.version ?? null;
209
+ // Rig display name for the doctrine block + setup events/errors (only on a
210
+ // rig-bound turn; null-safe fallback keeps the turn alive if the rig row is
211
+ // gone). Loaded once here alongside the version.
212
+ const rigName = rigVersion ? (rigMaterialization?.rigName ?? "rig") : null;
213
+ // Telemetry: stamp the frozen rig binding (empty for a rig-less turn).
214
+ workspaceRefs.rigId = session.rigId ?? "";
215
+ workspaceRefs.rigVersionId = session.rigVersionId ?? "";
216
+ if (!workspace) throw new Error(`Workspace not found: ${input.workspaceId}`);
217
+ const agentHumanInputEnabled = resolveWorkspaceAgentHumanInputEnabled(workspace.settings);
218
+ const contextSelection = await resolveCompanyBrainContextSelection(db, governanceClaims);
219
+ const workspaceAgentInstructions = contextSelection.legacyWorkspaceInstructions;
220
+ const memoryPromptMode = contextSelection.receipt.memoryPromptMode;
221
+ assertWorkspaceHumanInputAllowed(agentHumanInputEnabled, "resume", humanInputResume !== null);
222
+ const companyProfileIncluded = contextSelection.receipt.companyProfileIncluded;
223
+ const workspaceGovernance = renderWorkspaceGovernanceContext(
224
+ {
225
+ companyProfile: companyProfileSnapshot,
226
+ instructionPolicy: instructionPolicySnapshot,
227
+ preferences: preferenceSnapshot,
228
+ },
229
+ {
230
+ includeCompanyProfile: companyProfileIncluded,
231
+ },
232
+ );
233
+ const structuredWorkspacePolicyActive =
234
+ hasActiveWorkspaceInstructionPolicy(instructionPolicySnapshot);
235
+ const workspaceMemory = contextSelection.workspaceMemory;
236
+ const buildCompanyBrainContributionReceiptFor = (
237
+ skillActivations: Parameters<
238
+ typeof buildCompanyBrainContributionReceipt
239
+ >[0]["skillActivations"],
240
+ ) =>
241
+ buildCompanyBrainContributionReceipt({
242
+ contextSelectionReceiptId: contextSelection.receipt.id,
243
+ attemptId: input.attemptId,
244
+ turnId: turn.id,
245
+ nestedAgentDepth: session.nestedAgentDepth,
246
+ memoryPromptMode,
247
+ instructionPolicy: instructionPolicySnapshot,
248
+ workspaceAgentInstructions,
249
+ preferences: preferenceSnapshot,
250
+ companyProfile: companyProfileSnapshot,
251
+ companyProfileIncluded,
252
+ workspaceMemory,
253
+ skillActivations,
254
+ });
255
+ try {
256
+ // Portable operator compaction runs before tool/skill preparation, so its
257
+ // exact Company Brain prefix contains governance and standing memory but
258
+ // no runtime skill catalog. Later compaction paths replace this summary
259
+ // after the complete skill activation set is resolved.
260
+ eventing.companyBrainContextContributions = summarizeCompanyBrainContributions(
261
+ buildCompanyBrainContributionReceiptFor([]),
262
+ );
263
+ } catch {
264
+ // Contribution telemetry must never change model execution semantics.
265
+ }
266
+ const logicalSandboxSettings = settingsWithRigImage(
267
+ settingsWithPackSandboxImage(
268
+ capabilitySettings,
269
+ packRuntime.sandboxImage,
270
+ packRuntime.sandboxProviderImages,
271
+ ),
272
+ rigVersion?.image ?? null,
273
+ );
274
+ const providerImageSelection = await resolveRigProviderImageForRun(
275
+ logicalSandboxSettings,
276
+ rigVersion,
277
+ turn.sandboxBackend,
278
+ );
279
+ const providerImageSettings = providerImageSelection.settings;
280
+ const verifiedRigProviderImageId =
281
+ providerImageSelection.reason === "selected"
282
+ ? (providerImageSelection.imageId ?? undefined)
283
+ : undefined;
284
+ const baseRunSettings = {
285
+ // IMAGE PRECEDENCE: rig > pre-V2 Pack compatibility > deployment.
286
+ // resolveWorkspacePackRuntime returns no image for V2 Pack rows, so
287
+ // settingsWithRigImage runs outermost over only the intentionally
288
+ // retained legacy fallback. A matching verified provider-native ID is
289
+ // then applied only to fresh creation without changing the logical
290
+ // lease image.
291
+ ...providerImageSettings,
292
+ openaiModel: turn.model,
293
+ openaiReasoningEffort: turn.reasoningEffort,
294
+ sandboxBackend: turn.sandboxBackend,
295
+ };
296
+ const runSettings = await settingsWithSessionMcpServersForRun(
297
+ db,
298
+ input.workspaceId,
299
+ input.sessionId,
300
+ input.attemptId,
301
+ baseRunSettings,
302
+ );
303
+
304
+ // Multi-provider per-turn routing → the provider gating (compaction mode,
305
+ // hosted web search, encrypted reasoning, context window) the agent and
306
+ // compaction summarizer must use; null falls back to the legacy global
307
+ // client. Resolve against `capabilitySettings` (whose openaiModel is the
308
+ // deployment default), NOT `runSettings`: runSettings.openaiModel is the
309
+ // turn's model, so for a turn ON a registry model the built-in provider
310
+ // would otherwise claim that id (configuredModels builds the built-in's
311
+ // models from openaiModel) and shadow the registry entry — resolving the
312
+ // turn to the built-in (Azure) gating while the global model router routes
313
+ // the name to its registry provider. That mismatch attaches web_search to
314
+ // a chat-only Fireworks model. Resolving against the default-model settings
315
+ // keeps gating consistent with the router. Cost accounting covers registry
316
+ // models via configuredModelPricing.
317
+ const resolvedModel = runtime.resolveTurnModel(
318
+ capabilitySettings,
319
+ turnExecutionPolicy.productModelId,
320
+ );
321
+ const providerApi = resolvedModel?.provider.api ?? "responses";
322
+ const nativeImageProviderBinding =
323
+ providerApi === "responses"
324
+ ? openAiHostedImageProviderBindingForTurn(capabilitySettings, resolvedModel)
325
+ : null;
326
+ const lazyToolTransport = lazyToolTransportForTurn(resolvedModel);
327
+ const modelInputPolicy = modelAttachmentInputPolicyForTurn(resolvedModel);
328
+ // Use the proven wire capability, not the catalogue modality alone. Chat
329
+ // providers may advertise vision, but OpenGeni intentionally has no typed
330
+ // image transport for that wire yet; exposing view_image there would turn
331
+ // pixels into a multi-megabyte text/base64 function result.
332
+ const supportsImageInput = modelInputPolicy.supportsImageInput;
333
+ media.modelCanReceiveRetainedSessionImages = supportsImageInput;
334
+ const attachmentProjector = createModelHistoryAttachmentProjector(
335
+ modelInputPolicy,
336
+ objectStorage
337
+ ? async (file) => {
338
+ const object = await retryWhileMissing(async () =>
339
+ objectStorage.getObjectBytes(file.objectKey),
340
+ );
341
+ if (!object) throw new Error("attachment object is missing");
342
+ return object.bytes;
343
+ }
344
+ : undefined,
345
+ );
346
+ const modelHistoryProjector = async (
347
+ items: Array<Record<string, unknown>>,
348
+ projectionOptions?: Parameters<typeof attachmentProjector>[1],
349
+ ) =>
350
+ projectModelInputForCapabilities(
351
+ await attachmentProjector(items, projectionOptions),
352
+ modelInputPolicy,
353
+ );
354
+ const generatedImageHistoryProjector = async (
355
+ items: Array<Record<string, unknown>>,
356
+ ): Promise<Array<Record<string, unknown>>> => {
357
+ collectGeneratedImageReceipts(items, media.generatedImageReceiptsByProviderItemId);
358
+ return projectGeneratedImageHistoryForModel(items);
359
+ };
360
+ const compactionModelHistoryProjector = async (items: Array<Record<string, unknown>>) =>
361
+ await modelHistoryProjector(
362
+ projectHistoryForProvider(
363
+ await generatedImageHistoryProjector(restoreGenericDispatchHistoryItems(items)),
364
+ providerApi,
365
+ ),
366
+ );
367
+ // Bind the provider/model catalog's context policy to every model-facing
368
+ // path for this turn. In particular, Codex subscription turns must not
369
+ // inherit the deployment's OpenAI/Azure mode or 1.05M context defaults:
370
+ // raw window, effective ceiling, and auto-compact limit are distinct live
371
+ // catalog values and must reach pre-turn compaction, history guards, and
372
+ // every model call together.
373
+ eventing.modelRunSettings = resolvedModel
374
+ ? settingsWithResolvedModelContext(runSettings, resolvedModel.configured)
375
+ : runSettings;
376
+ // WORKSPACE MODEL POLICY — the authoritative hard gate. Runs immediately
377
+ // after resolution and BEFORE any model call (the compaction summarizer
378
+ // and the main run both come later in this scope), so a blocked
379
+ // provider/model can never be reached through ANY stamp path: explicit
380
+ // turn model, inherited session default, goal-continuation inheritance,
381
+ // or the legacy null-resolution fallback. The frozen execution policy is
382
+ // the attribution source even if an injected test runtime returns no
383
+ // concrete resolved model. Fail-loud, never a silent remap.
384
+ {
385
+ if (workspaceModelPolicy) {
386
+ const verdict = evaluateWorkspaceModelPolicy(workspaceModelPolicy, {
387
+ providerId: turnExecutionPolicy.providerId,
388
+ modelId: turnExecutionPolicy.productModelId,
389
+ });
390
+ if (!verdict.allowed) {
391
+ throw new WorkspaceModelPolicyBlockedError(
392
+ turnExecutionPolicy.productModelId,
393
+ turnExecutionPolicy.providerId,
394
+ verdict.reason,
395
+ );
396
+ }
397
+ }
398
+ }
399
+ // A recovered asynchronous video completion is model-visible only after
400
+ // its durable File is present at the exact sandbox path carried by the
401
+ // receipt. Resolve and verify the claimed update before sandbox policy is
402
+ // chosen so this turn cannot remain lazy and expose an absent path.
403
+ for (const update of await listSessionSystemUpdatesForTurn(
404
+ db,
405
+ input.workspaceId,
406
+ input.sessionId,
407
+ turn.id,
408
+ )) {
409
+ const payload = update.payload as MediaGenerationResult;
410
+ if (payload.type !== "media_generation_result" || payload.status !== "ready") continue;
411
+ const retained = await getGeneratedVideoArtifact(
412
+ db,
413
+ input.workspaceId,
414
+ payload.receipt.artifact.artifactId,
415
+ );
416
+ if (
417
+ !retained ||
418
+ retained.artifact.deletedAt ||
419
+ retained.file.status !== "ready" ||
420
+ retained.file.contentType !== "video/mp4" ||
421
+ retained.file.sizeBytes !== payload.receipt.artifact.originalBytes ||
422
+ retained.file.sha256 !== payload.receipt.artifact.sha256 ||
423
+ retained.artifact.sandboxFilename !== `generated-video-${retained.artifact.id}.mp4`
424
+ ) {
425
+ throw new Error("Generated video completion does not match its retained File");
426
+ }
427
+ requiredGeneratedVideoFiles.push({
428
+ operationId: payload.operationId,
429
+ artifactId: retained.artifact.id,
430
+ fileId: retained.file.id,
431
+ objectKey: retained.file.objectKey,
432
+ sizeBytes: retained.file.sizeBytes,
433
+ sha256: retained.file.sha256,
434
+ filename: retained.artifact.sandboxFilename,
435
+ });
436
+ }
437
+
438
+ return {
439
+ ok: {
440
+ runtimePreparationStartedAt,
441
+ packRuntime,
442
+ installedSkillRuntime,
443
+ rigVersion,
444
+ rigName,
445
+ agentHumanInputEnabled,
446
+ workspaceAgentInstructions,
447
+ workspaceGovernance,
448
+ structuredWorkspacePolicyActive,
449
+ workspaceMemory,
450
+ buildCompanyBrainContributionReceiptFor,
451
+ logicalSandboxSettings,
452
+ verifiedRigProviderImageId,
453
+ runSettings,
454
+ resolvedModel,
455
+ providerApi,
456
+ nativeImageProviderBinding,
457
+ lazyToolTransport,
458
+ modelInputPolicy,
459
+ supportsImageInput,
460
+ modelHistoryProjector,
461
+ generatedImageHistoryProjector,
462
+ compactionModelHistoryProjector,
463
+ },
464
+ };
465
+ }
@@ -0,0 +1,139 @@
1
+ import { appendSessionHistoryItems, upsertSandboxSessionEnvelope } from "@opengeni/db";
2
+ import { sandboxStateEntryFromRunState, type OpenGeniRuntime } from "@opengeni/runtime";
3
+ import type { Settings } from "@opengeni/config";
4
+ import { TurnAttemptFencedError } from "../turn-attempt-fenced";
5
+ import type { SharedActivityServices } from "../types";
6
+ import { compactGeneratedImageHistory } from "../generated-images";
7
+ import { compactRetainedScreenshotHistory } from "../retained-screenshots";
8
+ import type { turnInput } from "../run-input";
9
+ import { safeErrorDiagnostic } from "./errors";
10
+ import { historyRowsToAppend, isModelOrToolProgressHistoryItem } from "./history";
11
+ import { runMandatoryHistoryPersistenceStep } from "./quiescence";
12
+ import type { TurnMediaArtifacts } from "./media-artifacts";
13
+
14
+ export type TurnHistorySinkDeps = {
15
+ db: SharedActivityServices["db"];
16
+ accountId: string;
17
+ workspaceId: string;
18
+ sessionId: string;
19
+ attemptId: string;
20
+ media: TurnMediaArtifacts;
21
+ getTurnId: () => string | undefined;
22
+ getStream: () => Awaited<ReturnType<OpenGeniRuntime["runStream"]>> | undefined;
23
+ getModelRunSettings: () => Settings;
24
+ getExecutionGeneration: () => number;
25
+ };
26
+
27
+ /**
28
+ * Dual-write of conversation truth (issue #35): completed items are reconciled
29
+ * into session_history_items after every model response and at every turn-end
30
+ * path (idempotent on position), and the sandbox recovery envelope is upserted
31
+ * alongside. Best-effort by design: persistence problems must never fail the
32
+ * run.
33
+ *
34
+ * Orphaned-tool-output guard: `stream.state.history` is NOT a plain
35
+ * append-only array — it is a computed getter
36
+ * (`getTurnInput(originalInput, generatedItems)`) that runs the SDK's
37
+ * `dropOrphanToolCalls` on every access, so a `function_call` with no settling
38
+ * result yet is transiently ABSENT from history and a later reconcile sees a
39
+ * DIFFERENT, shorter/reordered list. A blind length watermark with
40
+ * onConflictDoNothing-on-position then freezes the first shape of a position
41
+ * and can persist a `function_call_result` at a tail position while its
42
+ * `function_call` was pruned away in an earlier slice and never written — the
43
+ * orphan that bricks the session. We defend against it at the stream boundary
44
+ * with the turn-scoped pending-tool ledger. A partial parallel batch records
45
+ * raw results but does not call this reconciler. Once every registered call has
46
+ * a result, the SDK history is stable and this scalar append watermark is valid
47
+ * again. The sanitizer remains the final call/result pairing guard for every
48
+ * other reconcile.
49
+ */
50
+ export class TurnHistorySink {
51
+ persistedHistoryCount = 0;
52
+ nextHistoryPosition = 0;
53
+ providerArtifactCandidates: Awaited<ReturnType<typeof turnInput>>["providerArtifactCandidates"] =
54
+ {
55
+ knownHistoryItemIds: [],
56
+ historyItemIds: [],
57
+ };
58
+
59
+ constructor(private readonly deps: TurnHistorySinkDeps) {}
60
+
61
+ reconcileConversationTruth = async (
62
+ options: { skipInputOnlyRows?: boolean; requireDurable?: boolean } = {},
63
+ ) => {
64
+ const { media } = this.deps;
65
+ const stream = this.deps.getStream();
66
+ const turnId = this.deps.getTurnId();
67
+ if (!stream || !turnId) {
68
+ return;
69
+ }
70
+ const durableTurnId = turnId;
71
+ try {
72
+ const rawHistory = (stream.state as { history?: unknown[] }).history;
73
+ if (Array.isArray(rawHistory)) {
74
+ const typedHistory = rawHistory as Array<Record<string, unknown>>;
75
+ await media.retainNativeGeneratedImagesFromHistory(typedHistory);
76
+ const durableHistory = compactGeneratedImageHistory(
77
+ compactRetainedScreenshotHistory(typedHistory, media.retainedScreenshotReceiptsByCallId),
78
+ media.generatedImageReceiptsByProviderItemId,
79
+ );
80
+ const { rows, nextWatermark, nextPosition } = historyRowsToAppend(
81
+ durableHistory,
82
+ this.persistedHistoryCount,
83
+ this.nextHistoryPosition,
84
+ this.deps.getModelRunSettings().modelToolOutputTruncationTokens,
85
+ );
86
+ const hasModelOrToolProgress = rows.some((row) =>
87
+ isModelOrToolProgressHistoryItem(row.item),
88
+ );
89
+ const shouldAppendRows =
90
+ rows.length > 0 && (!options.skipInputOnlyRows || hasModelOrToolProgress);
91
+ if (shouldAppendRows) {
92
+ await runMandatoryHistoryPersistenceStep("history_append", async () => {
93
+ const appended = await appendSessionHistoryItems(this.deps.db, {
94
+ accountId: this.deps.accountId,
95
+ workspaceId: this.deps.workspaceId,
96
+ sessionId: this.deps.sessionId,
97
+ turnId: durableTurnId,
98
+ expectedExecutionGeneration: this.deps.getExecutionGeneration(),
99
+ expectedAttemptId: this.deps.attemptId,
100
+ modelToolOutputTruncationTokens:
101
+ this.deps.getModelRunSettings().modelToolOutputTruncationTokens,
102
+ items: rows,
103
+ });
104
+ if (!appended) {
105
+ throw new TurnAttemptFencedError(
106
+ "turn execution generation was fenced while saving conversation history",
107
+ );
108
+ }
109
+ });
110
+ }
111
+ if (shouldAppendRows || !options.skipInputOnlyRows) {
112
+ this.persistedHistoryCount = nextWatermark;
113
+ this.nextHistoryPosition = nextPosition;
114
+ }
115
+ }
116
+ const envelope = sandboxStateEntryFromRunState(stream.state);
117
+ if (envelope) {
118
+ await runMandatoryHistoryPersistenceStep("sandbox_envelope", () =>
119
+ upsertSandboxSessionEnvelope(this.deps.db, {
120
+ accountId: this.deps.accountId,
121
+ workspaceId: this.deps.workspaceId,
122
+ sessionId: this.deps.sessionId,
123
+ envelope,
124
+ }),
125
+ );
126
+ }
127
+ } catch (persistError) {
128
+ console.error(
129
+ "session history dual-write failed (run unaffected)",
130
+ safeErrorDiagnostic(persistError),
131
+ );
132
+ if (options.requireDurable) throw persistError;
133
+ }
134
+ };
135
+ }
136
+
137
+ export function createTurnHistorySink(deps: TurnHistorySinkDeps): TurnHistorySink {
138
+ return new TurnHistorySink(deps);
139
+ }