@opengeni/db 0.28.9 → 0.31.1

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 (163) hide show
  1. package/dist/attached-browser-devices.d.ts +42 -0
  2. package/dist/attempt-tool-catalogs.d.ts +16 -0
  3. package/dist/browser-auth.d.ts +91 -0
  4. package/dist/browser-identities.d.ts +128 -0
  5. package/dist/browser-sessions.d.ts +272 -0
  6. package/dist/browser-state-artifacts.d.ts +17 -0
  7. package/dist/capability-components.d.ts +37 -0
  8. package/dist/capability-integrations.d.ts +192 -0
  9. package/dist/chunk-F5FT7BEZ.js +3535 -0
  10. package/dist/chunk-F5FT7BEZ.js.map +1 -0
  11. package/dist/chunk-ISI2TIUG.js +639 -0
  12. package/dist/chunk-ISI2TIUG.js.map +1 -0
  13. package/dist/chunk-MWDVXQOL.js +11639 -0
  14. package/dist/chunk-MWDVXQOL.js.map +1 -0
  15. package/dist/chunk-NBE6CHRI.js +955 -0
  16. package/dist/chunk-NBE6CHRI.js.map +1 -0
  17. package/dist/{chunk-VHBFHMPC.js → chunk-YHZXQ7HP.js} +754 -11
  18. package/dist/chunk-YHZXQ7HP.js.map +1 -0
  19. package/dist/codemode-operations.d.ts +117 -0
  20. package/dist/codex-token-resolver.d.ts +2 -2
  21. package/dist/company-profile-schema.d.ts +798 -0
  22. package/dist/company-profile.d.ts +268 -0
  23. package/dist/computer-sessions.d.ts +109 -0
  24. package/dist/connection-token-resolver.d.ts +9 -4
  25. package/dist/database.d.ts +52 -3
  26. package/dist/editable-artifact-durable-export.d.ts +153 -0
  27. package/dist/editable-artifact-durable-export.js +788 -0
  28. package/dist/editable-artifact-durable-export.js.map +1 -0
  29. package/dist/editable-artifact-materialization.d.ts +123 -0
  30. package/dist/editable-artifacts-schema.d.ts +4152 -0
  31. package/dist/editable-artifacts.d.ts +610 -0
  32. package/dist/editable-artifacts.js +26 -0
  33. package/dist/editable-artifacts.js.map +1 -0
  34. package/dist/generated-images.d.ts +139 -0
  35. package/dist/index.d.ts +698 -111
  36. package/dist/index.js +27573 -10322
  37. package/dist/index.js.map +1 -1
  38. package/dist/insights.d.ts +51 -4
  39. package/dist/integration-bindings.d.ts +70 -0
  40. package/dist/integration-features.d.ts +99 -0
  41. package/dist/interaction-revisions.d.ts +3 -0
  42. package/dist/interaction-schema.d.ts +5372 -0
  43. package/dist/knowledge-source-sync-schema.d.ts +1679 -0
  44. package/dist/knowledge-source-sync.d.ts +274 -0
  45. package/dist/memory-governance.d.ts +2 -2
  46. package/dist/memory-slack-delivery.d.ts +101 -0
  47. package/dist/new-session-drafts.d.ts +2 -2
  48. package/dist/pack-components.d.ts +76 -0
  49. package/dist/pack-installations.d.ts +86 -0
  50. package/dist/persistence-errors.d.ts +3 -3
  51. package/dist/plugin-packages.d.ts +126 -0
  52. package/dist/preference-registry.d.ts +1 -1
  53. package/dist/provision-roles.d.ts +9 -1
  54. package/dist/provision-roles.js +1 -1
  55. package/dist/runtime-posture.d.ts +18 -6
  56. package/dist/schema.d.ts +18342 -9099
  57. package/dist/schema.js +165 -1
  58. package/dist/scoped-knowledge.d.ts +97 -1
  59. package/dist/session-control.d.ts +4 -4
  60. package/dist/session-queue-commands.d.ts +19 -11
  61. package/dist/session-realtime-context.d.ts +2 -2
  62. package/dist/session-realtime-ledger.d.ts +4 -4
  63. package/dist/session-realtime-mirror.d.ts +2 -2
  64. package/dist/session-realtime-state.d.ts +1 -1
  65. package/dist/session-realtime-terminal.d.ts +1 -1
  66. package/dist/session-realtime.d.ts +7 -7
  67. package/dist/session-tool-call-settlement.d.ts +1 -1
  68. package/dist/slack-user-link-access.d.ts +54 -0
  69. package/dist/transcription-recordings.d.ts +2 -2
  70. package/dist/turn-initiator.d.ts +2 -2
  71. package/dist/video-generation.d.ts +216 -0
  72. package/dist/video-generation.js +66 -0
  73. package/dist/video-generation.js.map +1 -0
  74. package/dist/workspace-artifacts.d.ts +1 -1
  75. package/dist/workspace-instruction-policies.d.ts +1 -1
  76. package/dist/workspace-learning-policy-schema.d.ts +932 -0
  77. package/dist/workspace-learning-policy.d.ts +161 -0
  78. package/drizzle/0183_model_call_provider_cost_estimates.sql +39 -0
  79. package/drizzle/0184_sandbox_drain_teardown_fence.sql +682 -0
  80. package/drizzle/0185_temporal_schedule_cleanup_outbox.sql +168 -0
  81. package/drizzle/0186_sandbox_capture_provider_contract.sql +400 -0
  82. package/drizzle/0187_generated_image_artifacts.sql +173 -0
  83. package/drizzle/0188_image_generation_retention_failure.sql +25 -0
  84. package/drizzle/0189_retained_session_image_formats.sql +13 -0
  85. package/drizzle/0190_timeline_annotations.sql +31 -0
  86. package/drizzle/0191_editable_artifact_engine.sql +3853 -0
  87. package/drizzle/0192_editable_artifact_live_tickets.sql +338 -0
  88. package/drizzle/0193_editable_artifact_authorization.sql +190 -0
  89. package/drizzle/0194_editable_artifact_durable_exports.sql +160 -0
  90. package/drizzle/0195_editable_artifact_import_authorization.sql +203 -0
  91. package/drizzle/0196_rig_provider_images.sql +152 -0
  92. package/drizzle/0197_knowledge_source_sync_schedules.sql +523 -0
  93. package/drizzle/0198_memory_slack_publication_delivery.sql +393 -0
  94. package/drizzle/0199_workspace_learning_policy.sql +980 -0
  95. package/drizzle/0201_company_profile_authority.sql +849 -0
  96. package/drizzle/0202_document_index_checkpoints.sql +85 -0
  97. package/drizzle/0203_durable_video_generation.sql +353 -0
  98. package/drizzle/0204_video_generation_funding.sql +44 -0
  99. package/drizzle/0205_attempt_tool_catalogs.sql +230 -0
  100. package/drizzle/0206_browser_sessions.sql +646 -0
  101. package/drizzle/0207_browser_identities.sql +379 -0
  102. package/drizzle/0208_attached_browser_devices.sql +165 -0
  103. package/drizzle/0209_computer_sessions.sql +575 -0
  104. package/drizzle/0210_browser_auth_network_interventions.sql +441 -0
  105. package/drizzle/0211_editable_artifact_session_links.sql +58 -0
  106. package/drizzle/0212_slack_installation_bindings.sql +348 -0
  107. package/drizzle/0213_slack_user_link_access_requests.sql +177 -0
  108. package/drizzle/0214_session_activity_commit_gate.sql +262 -0
  109. package/drizzle/0215_capabilities_platform.sql +980 -0
  110. package/drizzle/0216_pack_component_ownership.sql +235 -0
  111. package/drizzle/0217_capability_definition_delete_authority.sql +32 -0
  112. package/package.json +18 -5
  113. package/src/attached-browser-devices.ts +371 -0
  114. package/src/attempt-tool-catalogs.ts +131 -0
  115. package/src/browser-auth.ts +1896 -0
  116. package/src/browser-identities.ts +1168 -0
  117. package/src/browser-sessions.ts +2005 -0
  118. package/src/browser-state-artifacts.ts +59 -0
  119. package/src/capability-components.ts +166 -0
  120. package/src/capability-integrations.ts +1663 -0
  121. package/src/codemode-operations.ts +674 -0
  122. package/src/company-profile-schema.ts +143 -0
  123. package/src/company-profile.ts +968 -0
  124. package/src/computer-sessions.ts +1130 -0
  125. package/src/connection-token-resolver.ts +270 -25
  126. package/src/database.ts +427 -23
  127. package/src/editable-artifact-durable-export.ts +1201 -0
  128. package/src/editable-artifact-materialization.ts +893 -0
  129. package/src/editable-artifacts-schema.ts +879 -0
  130. package/src/editable-artifacts.ts +5404 -0
  131. package/src/generated-images.ts +740 -0
  132. package/src/index.ts +5917 -1182
  133. package/src/insights.ts +160 -13
  134. package/src/integration-bindings.ts +455 -0
  135. package/src/integration-features.ts +859 -0
  136. package/src/interaction-revisions.ts +40 -0
  137. package/src/interaction-schema.ts +1303 -0
  138. package/src/knowledge-source-sync-schema.ts +192 -0
  139. package/src/knowledge-source-sync.ts +1922 -0
  140. package/src/memory-slack-delivery.ts +801 -0
  141. package/src/pack-components.ts +954 -0
  142. package/src/pack-installations.ts +929 -0
  143. package/src/persistence-errors.ts +4 -7
  144. package/src/plugin-packages.ts +1186 -0
  145. package/src/provision-roles.ts +302 -1
  146. package/src/runtime-posture-cli.ts +9 -0
  147. package/src/runtime-posture.ts +508 -5
  148. package/src/schema.ts +5117 -3119
  149. package/src/scoped-knowledge-schema.ts +1 -1
  150. package/src/scoped-knowledge.ts +655 -3
  151. package/src/session-control.ts +8 -5
  152. package/src/session-queue-commands.ts +187 -14
  153. package/src/session-realtime-context.ts +2 -2
  154. package/src/session-realtime-ledger.ts +3 -3
  155. package/src/session-realtime.ts +7 -7
  156. package/src/session-tool-call-settlement.ts +9 -0
  157. package/src/slack-user-link-access.ts +702 -0
  158. package/src/video-generation.ts +1452 -0
  159. package/src/workspace-learning-policy-schema.ts +139 -0
  160. package/src/workspace-learning-policy.ts +595 -0
  161. package/dist/chunk-P6CUHXQZ.js +0 -7248
  162. package/dist/chunk-P6CUHXQZ.js.map +0 -1
  163. package/dist/chunk-VHBFHMPC.js.map +0 -1
@@ -0,0 +1,1452 @@
1
+ import {
2
+ GENERATED_VIDEO_MAX_BYTES,
3
+ GeneratedVideoReceipt,
4
+ SEEDANCE_2_5_MODEL_ID,
5
+ VideoGenerationPolicy,
6
+ VideoGenerationOperationSummary,
7
+ retainedGeneratedVideoReferenceFromFile,
8
+ type GeneratedVideoFacts,
9
+ type MediaGenerationResult,
10
+ type VideoGenerationFundingSource,
11
+ type VideoGenerationPolicy as VideoGenerationPolicyValue,
12
+ } from "@opengeni/contracts";
13
+ import { and, eq, inArray, sql } from "drizzle-orm";
14
+ import type { Database } from "./database";
15
+ import { rawRows, withRlsContext, withWorkspaceRls } from "./database";
16
+ import * as schema from "./schema";
17
+
18
+ export const ACTIVE_VIDEO_GENERATION_STATUSES = [
19
+ "preparing",
20
+ "prepared",
21
+ "accepted",
22
+ "submission_uncertain",
23
+ "provider_started",
24
+ "retaining",
25
+ ] as const;
26
+
27
+ export type VideoGenerationOperation = typeof schema.videoGenerationOperations.$inferSelect;
28
+ export type VideoGenerationReference = typeof schema.videoGenerationReferences.$inferSelect;
29
+ export type GeneratedVideoArtifact = typeof schema.generatedVideoArtifacts.$inferSelect;
30
+
31
+ export type VideoGenerationOperationWithReferences = VideoGenerationOperation & {
32
+ references: VideoGenerationReference[];
33
+ };
34
+
35
+ export class VideoGenerationConflictError extends Error {
36
+ constructor(message: string) {
37
+ super(message);
38
+ this.name = "VideoGenerationConflictError";
39
+ }
40
+ }
41
+
42
+ export class VideoGenerationCapacityError extends Error {
43
+ constructor(message: string) {
44
+ super(message);
45
+ this.name = "VideoGenerationCapacityError";
46
+ }
47
+ }
48
+
49
+ export class VideoGenerationCreditError extends Error {
50
+ constructor(message = "insufficient OpenGeni credits") {
51
+ super(message);
52
+ this.name = "VideoGenerationCreditError";
53
+ }
54
+ }
55
+
56
+ export async function getWorkspaceVideoGenerationPolicy(
57
+ db: Database,
58
+ workspaceId: string,
59
+ ): Promise<VideoGenerationPolicyValue> {
60
+ return await withWorkspaceRls(db, workspaceId, async (scopedDb) => {
61
+ const [row] = await scopedDb
62
+ .select()
63
+ .from(schema.workspaceVideoGenerationPolicies)
64
+ .where(eq(schema.workspaceVideoGenerationPolicies.workspaceId, workspaceId))
65
+ .limit(1);
66
+ return policyFromRow(row);
67
+ });
68
+ }
69
+
70
+ export async function updateWorkspaceVideoGenerationPolicy(
71
+ db: Database,
72
+ input: {
73
+ accountId: string;
74
+ workspaceId: string;
75
+ subjectId: string;
76
+ expectedRevision: number;
77
+ fundingSource: VideoGenerationFundingSource;
78
+ enabledModelIds: string[];
79
+ defaultModelId: string | null;
80
+ },
81
+ ): Promise<VideoGenerationPolicyValue> {
82
+ const requested = VideoGenerationPolicy.parse({
83
+ schemaVersion: 1,
84
+ revision: input.expectedRevision + 1,
85
+ fundingSource: input.fundingSource,
86
+ enabledModelIds: input.enabledModelIds,
87
+ defaultModelId: input.defaultModelId,
88
+ });
89
+ assertSupportedModels(requested.enabledModelIds);
90
+ return await withRlsContext(
91
+ db,
92
+ { accountId: input.accountId, workspaceId: input.workspaceId },
93
+ async (scopedDb) =>
94
+ await scopedDb.transaction(async (tx) => {
95
+ const [workspace] = await tx
96
+ .select({ id: schema.workspaces.id })
97
+ .from(schema.workspaces)
98
+ .where(
99
+ and(
100
+ eq(schema.workspaces.id, input.workspaceId),
101
+ eq(schema.workspaces.accountId, input.accountId),
102
+ ),
103
+ )
104
+ .for("update")
105
+ .limit(1);
106
+ if (!workspace) throw new Error("Workspace not found");
107
+ const [current] = await tx
108
+ .select()
109
+ .from(schema.workspaceVideoGenerationPolicies)
110
+ .where(eq(schema.workspaceVideoGenerationPolicies.workspaceId, input.workspaceId))
111
+ .for("update")
112
+ .limit(1);
113
+ const currentRevision = current?.revision ?? 0;
114
+ if (currentRevision !== input.expectedRevision) {
115
+ throw new VideoGenerationConflictError("Video generation policy changed");
116
+ }
117
+ const now = new Date();
118
+ const values = {
119
+ workspaceId: input.workspaceId,
120
+ accountId: input.accountId,
121
+ revision: currentRevision + 1,
122
+ fundingSource: requested.fundingSource,
123
+ enabledModelIds: [...requested.enabledModelIds],
124
+ defaultModelId: requested.defaultModelId,
125
+ updatedBySubjectId: input.subjectId.slice(0, 1_024),
126
+ updatedAt: now,
127
+ };
128
+ const [row] = current
129
+ ? await tx
130
+ .update(schema.workspaceVideoGenerationPolicies)
131
+ .set(values)
132
+ .where(eq(schema.workspaceVideoGenerationPolicies.workspaceId, input.workspaceId))
133
+ .returning()
134
+ : await tx.insert(schema.workspaceVideoGenerationPolicies).values(values).returning();
135
+ if (!row) throw new Error("Video generation policy update was not persisted");
136
+ return policyFromRow(row);
137
+ }),
138
+ );
139
+ }
140
+
141
+ export type AdmitVideoGenerationOperationInput = {
142
+ id: string;
143
+ accountId: string;
144
+ workspaceId: string;
145
+ sessionId: string;
146
+ turnId: string;
147
+ attemptId: string;
148
+ toolCallId: string;
149
+ admissionKey: string;
150
+ requestDigest: string;
151
+ promptDigest: string;
152
+ requestEncrypted: string;
153
+ modelId: string;
154
+ sourceMode: string;
155
+ capabilityRevision: string;
156
+ policyRevision: number;
157
+ fundingSource: VideoGenerationFundingSource;
158
+ pricedCostMicros: number;
159
+ connectionId: string | null;
160
+ credentialVersion: number;
161
+ credentialEncrypted: string;
162
+ providerIdempotencyKey: string;
163
+ expectedArtifactId: string;
164
+ expectedFileId: string;
165
+ reservedBytes?: number;
166
+ workspaceQuotaBytes: number;
167
+ maxConcurrentPerWorkspace: number;
168
+ recoveryDeadlineAt: Date;
169
+ references: Array<{
170
+ ordinal: number;
171
+ role: string;
172
+ contentType: string;
173
+ sizeBytes: number;
174
+ sha256: string;
175
+ stagingObjectKey: string;
176
+ grantExpiresAt?: Date | null;
177
+ cleanupAfter: Date;
178
+ }>;
179
+ };
180
+
181
+ export async function admitVideoGenerationOperation(
182
+ db: Database,
183
+ input: AdmitVideoGenerationOperationInput,
184
+ ): Promise<{ operation: VideoGenerationOperation; created: boolean }> {
185
+ const reservedBytes = input.reservedBytes ?? GENERATED_VIDEO_MAX_BYTES;
186
+ return await withRlsContext(
187
+ db,
188
+ { accountId: input.accountId, workspaceId: input.workspaceId },
189
+ async (scopedDb) =>
190
+ await scopedDb.transaction(async (tx) => {
191
+ await tx.execute(
192
+ sql`select pg_advisory_xact_lock(hashtextextended(${`video-generation:${input.admissionKey}`}, 0))`,
193
+ );
194
+ const [existing] = await tx
195
+ .select()
196
+ .from(schema.videoGenerationOperations)
197
+ .where(
198
+ and(
199
+ eq(schema.videoGenerationOperations.workspaceId, input.workspaceId),
200
+ eq(schema.videoGenerationOperations.admissionKey, input.admissionKey),
201
+ ),
202
+ )
203
+ .limit(1);
204
+ if (existing) {
205
+ assertAdmissionMatches(existing, input);
206
+ return { operation: existing, created: false };
207
+ }
208
+ const [policy] = await tx
209
+ .select()
210
+ .from(schema.workspaceVideoGenerationPolicies)
211
+ .where(eq(schema.workspaceVideoGenerationPolicies.workspaceId, input.workspaceId))
212
+ .for("update")
213
+ .limit(1);
214
+ if (
215
+ !policy ||
216
+ policy.revision !== input.policyRevision ||
217
+ policy.fundingSource !== input.fundingSource ||
218
+ !policy.enabledModelIds.includes(input.modelId)
219
+ ) {
220
+ throw new VideoGenerationConflictError("Video generation capability changed");
221
+ }
222
+ const active = await tx
223
+ .select({ id: schema.videoGenerationOperations.id })
224
+ .from(schema.videoGenerationOperations)
225
+ .where(
226
+ and(
227
+ eq(schema.videoGenerationOperations.workspaceId, input.workspaceId),
228
+ inArray(schema.videoGenerationOperations.status, [
229
+ ...ACTIVE_VIDEO_GENERATION_STATUSES,
230
+ ]),
231
+ ),
232
+ )
233
+ .for("update");
234
+ if (active.length >= input.maxConcurrentPerWorkspace) {
235
+ throw new VideoGenerationCapacityError("Workspace video generation limit reached");
236
+ }
237
+ await tx
238
+ .insert(schema.workspaceVideoGenerationQuotas)
239
+ .values({ workspaceId: input.workspaceId, accountId: input.accountId })
240
+ .onConflictDoNothing({ target: schema.workspaceVideoGenerationQuotas.workspaceId });
241
+ const [quota] = await tx
242
+ .select()
243
+ .from(schema.workspaceVideoGenerationQuotas)
244
+ .where(eq(schema.workspaceVideoGenerationQuotas.workspaceId, input.workspaceId))
245
+ .for("update")
246
+ .limit(1);
247
+ if (!quota) throw new Error("Video generation quota row disappeared");
248
+ if (quota.reservedBytes + quota.readyBytes + reservedBytes > input.workspaceQuotaBytes) {
249
+ throw new VideoGenerationCapacityError("Workspace video storage quota reached");
250
+ }
251
+ const [operation] = await tx
252
+ .insert(schema.videoGenerationOperations)
253
+ .values({
254
+ id: input.id,
255
+ accountId: input.accountId,
256
+ workspaceId: input.workspaceId,
257
+ sessionId: input.sessionId,
258
+ turnId: input.turnId,
259
+ attemptId: input.attemptId,
260
+ toolCallId: input.toolCallId,
261
+ admissionKey: input.admissionKey,
262
+ requestDigest: input.requestDigest,
263
+ promptDigest: input.promptDigest,
264
+ requestEncrypted: input.requestEncrypted,
265
+ modelId: input.modelId,
266
+ sourceMode: input.sourceMode,
267
+ capabilityRevision: input.capabilityRevision,
268
+ fundingSource: input.fundingSource,
269
+ pricedCostMicros: input.pricedCostMicros,
270
+ creditState: input.pricedCostMicros > 0 ? "debited" : "not_applicable",
271
+ connectionId: input.connectionId,
272
+ credentialVersion: input.credentialVersion,
273
+ credentialEncrypted: input.credentialEncrypted,
274
+ providerIdempotencyKey: input.providerIdempotencyKey,
275
+ expectedArtifactId: input.expectedArtifactId,
276
+ expectedFileId: input.expectedFileId,
277
+ reservedBytes,
278
+ recoveryDeadlineAt: input.recoveryDeadlineAt,
279
+ status: input.references.length === 0 ? "prepared" : "preparing",
280
+ admissionOutputState: "pending",
281
+ terminalUpdateState: "ineligible",
282
+ })
283
+ .returning();
284
+ if (!operation) throw new Error("Video generation operation was not admitted");
285
+ if (input.pricedCostMicros > 0) {
286
+ if (input.fundingSource !== "opengeni_credits" || input.connectionId !== null) {
287
+ throw new Error("Only OpenGeni-funded video operations may debit credits");
288
+ }
289
+ await debitVideoGenerationCredits(tx, operation);
290
+ }
291
+ if (input.references.length > 0) {
292
+ await tx.insert(schema.videoGenerationReferences).values(
293
+ input.references.map((reference) => ({
294
+ operationId: operation.id,
295
+ workspaceId: input.workspaceId,
296
+ accountId: input.accountId,
297
+ grantExpiresAt: reference.grantExpiresAt ?? null,
298
+ ...reference,
299
+ })),
300
+ );
301
+ }
302
+ await tx
303
+ .update(schema.workspaceVideoGenerationQuotas)
304
+ .set({
305
+ reservedBytes: sql`${schema.workspaceVideoGenerationQuotas.reservedBytes} + ${reservedBytes}`,
306
+ updatedAt: new Date(),
307
+ })
308
+ .where(eq(schema.workspaceVideoGenerationQuotas.workspaceId, input.workspaceId));
309
+ return { operation, created: true };
310
+ }),
311
+ );
312
+ }
313
+
314
+ /**
315
+ * Seal a reference-bearing operation only after every immutable staging object
316
+ * has been uploaded and independently verified by the worker. The source
317
+ * sandbox path is intentionally not stored, so a failed preparation can only
318
+ * be retried by the same logical tool call while its sandbox still exists.
319
+ */
320
+ export async function markVideoGenerationPrepared(
321
+ db: Database,
322
+ input: OperationMutationInput,
323
+ ): Promise<VideoGenerationOperation> {
324
+ return await mutateOperation(db, input, async (tx, operation) => {
325
+ if (operation.status === "prepared") return operation;
326
+ if (operation.status !== "preparing") throw invalidTransition(operation, "prepared");
327
+ const references = await tx
328
+ .select({
329
+ stagingObjectKey: schema.videoGenerationReferences.stagingObjectKey,
330
+ cleanedAt: schema.videoGenerationReferences.cleanedAt,
331
+ })
332
+ .from(schema.videoGenerationReferences)
333
+ .where(eq(schema.videoGenerationReferences.operationId, operation.id));
334
+ if (
335
+ references.length === 0 ||
336
+ references.some((reference) => !reference.stagingObjectKey || reference.cleanedAt)
337
+ ) {
338
+ throw new VideoGenerationConflictError("Video references are not sealed");
339
+ }
340
+ const [updated] = await tx
341
+ .update(schema.videoGenerationOperations)
342
+ .set({ status: "prepared", updatedAt: new Date() })
343
+ .where(eq(schema.videoGenerationOperations.id, operation.id))
344
+ .returning();
345
+ return requireRow(updated, "seal video generation references");
346
+ });
347
+ }
348
+
349
+ /** Final authorization fence. Call only after the accepted function output is durable. */
350
+ export async function markVideoGenerationAccepted(
351
+ db: Database,
352
+ input: {
353
+ accountId: string;
354
+ workspaceId: string;
355
+ operationId: string;
356
+ requestDigest: string;
357
+ },
358
+ ): Promise<VideoGenerationOperation> {
359
+ return await mutateOperation(
360
+ db,
361
+ input,
362
+ async (tx, operation) =>
363
+ await markVideoGenerationAcceptedInTransaction(tx, {
364
+ workspaceId: input.workspaceId,
365
+ operation,
366
+ }),
367
+ );
368
+ }
369
+
370
+ /**
371
+ * Transactional half of acceptance. The pending function result and this
372
+ * transition must commit together: the provider reconciler never observes an
373
+ * accepted operation whose model-visible `accepted` receipt was lost.
374
+ */
375
+ export async function markVideoGenerationAcceptedInTransaction(
376
+ tx: Database,
377
+ input: {
378
+ workspaceId: string;
379
+ operation: VideoGenerationOperation;
380
+ toolCallId?: string;
381
+ },
382
+ ): Promise<VideoGenerationOperation> {
383
+ const operation = input.operation;
384
+ if (input.toolCallId !== undefined && operation.toolCallId !== input.toolCallId) {
385
+ throw new VideoGenerationConflictError("Video generation tool-call identity changed");
386
+ }
387
+ if (operation.admissionOutputState === "recorded") return operation;
388
+ if (operation.status !== "prepared") {
389
+ throw new VideoGenerationConflictError("Video generation is no longer awaiting acceptance");
390
+ }
391
+ const [policy] = await tx
392
+ .select()
393
+ .from(schema.workspaceVideoGenerationPolicies)
394
+ .where(eq(schema.workspaceVideoGenerationPolicies.workspaceId, input.workspaceId))
395
+ .for("share")
396
+ .limit(1);
397
+ const [connection] = operation.connectionId
398
+ ? await tx
399
+ .select({
400
+ id: schema.connections.id,
401
+ version: schema.connections.version,
402
+ status: schema.connections.status,
403
+ metadata: schema.connections.metadata,
404
+ })
405
+ .from(schema.connections)
406
+ .where(
407
+ and(
408
+ eq(schema.connections.workspaceId, input.workspaceId),
409
+ eq(schema.connections.id, operation.connectionId),
410
+ ),
411
+ )
412
+ .for("share")
413
+ .limit(1)
414
+ : [];
415
+ const workspaceGatewayAuthorized =
416
+ operation.fundingSource === "workspace_gateway" &&
417
+ connection?.status === "active" &&
418
+ connection.version === operation.credentialVersion &&
419
+ connection.metadata.credentialRole === "vercel_ai_gateway";
420
+ const managedAuthorized =
421
+ operation.fundingSource === "opengeni_credits" &&
422
+ operation.connectionId === null &&
423
+ (operation.creditState === "debited" ||
424
+ (operation.creditState === "not_applicable" && operation.pricedCostMicros === 0));
425
+ if (
426
+ !policy ||
427
+ policy.fundingSource !== operation.fundingSource ||
428
+ !policy.enabledModelIds.includes(operation.modelId) ||
429
+ (!workspaceGatewayAuthorized && !managedAuthorized)
430
+ ) {
431
+ throw new VideoGenerationConflictError("Video generation authorization changed");
432
+ }
433
+ const now = new Date();
434
+ const [updated] = await tx
435
+ .update(schema.videoGenerationOperations)
436
+ .set({
437
+ status: "accepted",
438
+ admissionOutputState: "recorded",
439
+ terminalUpdateState: "pending",
440
+ nextReconcileAt: now,
441
+ updatedAt: now,
442
+ })
443
+ .where(eq(schema.videoGenerationOperations.id, operation.id))
444
+ .returning();
445
+ return requireRow(updated, "record video generation acceptance");
446
+ }
447
+
448
+ export async function cancelVideoGenerationBeforeSubmit(
449
+ db: Database,
450
+ input: {
451
+ accountId: string;
452
+ workspaceId: string;
453
+ operationId: string;
454
+ requestDigest: string;
455
+ reason: string;
456
+ },
457
+ ): Promise<VideoGenerationOperation> {
458
+ return await mutateOperation(db, input, async (tx, operation) => {
459
+ if (operation.status === "cancelled_before_submit") return operation;
460
+ if (!inPreSubmitState(operation.status) || operation.providerRequestSentAt) {
461
+ throw new VideoGenerationConflictError(
462
+ "Video generation may already have reached the provider",
463
+ );
464
+ }
465
+ const now = new Date();
466
+ await releaseReservedQuota(tx, operation, false);
467
+ const creditState = await refundVideoGenerationCredits(tx, operation, now);
468
+ const [updated] = await tx
469
+ .update(schema.videoGenerationOperations)
470
+ .set({
471
+ status: "cancelled_before_submit",
472
+ creditState,
473
+ quotaState: "released",
474
+ terminalAt: now,
475
+ terminalUpdateState:
476
+ operation.admissionOutputState === "recorded" ? "pending" : "suppressed",
477
+ credentialEncrypted: null,
478
+ requestEncrypted: null,
479
+ boundedPublicReason: boundPublicReason(input.reason),
480
+ updatedAt: now,
481
+ })
482
+ .where(eq(schema.videoGenerationOperations.id, operation.id))
483
+ .returning();
484
+ if (!updated) throw new Error("Video generation cancellation was not recorded");
485
+ return updated;
486
+ });
487
+ }
488
+
489
+ /**
490
+ * Turn-interruption half of pre-submit cancellation. It runs under the same
491
+ * session/turn transaction that closes unresolved tool calls, so an accepted
492
+ * receipt can never race a cancellation of its operation.
493
+ */
494
+ export async function cancelUnacceptedVideoGenerationsForToolCallsInTransaction(
495
+ tx: Database,
496
+ input: {
497
+ workspaceId: string;
498
+ sessionId: string;
499
+ turnId: string;
500
+ toolCallIds: readonly string[];
501
+ reason: string;
502
+ now: Date;
503
+ },
504
+ ): Promise<string[]> {
505
+ const toolCallIds = [...new Set(input.toolCallIds)];
506
+ if (toolCallIds.length === 0) return [];
507
+ const operations = await tx
508
+ .select()
509
+ .from(schema.videoGenerationOperations)
510
+ .where(
511
+ and(
512
+ eq(schema.videoGenerationOperations.workspaceId, input.workspaceId),
513
+ eq(schema.videoGenerationOperations.sessionId, input.sessionId),
514
+ eq(schema.videoGenerationOperations.turnId, input.turnId),
515
+ inArray(schema.videoGenerationOperations.toolCallId, toolCallIds),
516
+ eq(schema.videoGenerationOperations.admissionOutputState, "pending"),
517
+ inArray(schema.videoGenerationOperations.status, ["preparing", "prepared"]),
518
+ sql`${schema.videoGenerationOperations.providerRequestSentAt} is null`,
519
+ ),
520
+ )
521
+ .orderBy(schema.videoGenerationOperations.id)
522
+ .for("update");
523
+ const cancelled: string[] = [];
524
+ for (const operation of operations) {
525
+ await releaseReservedQuota(tx, operation, false);
526
+ const creditState = await refundVideoGenerationCredits(tx, operation, input.now);
527
+ const [updated] = await tx
528
+ .update(schema.videoGenerationOperations)
529
+ .set({
530
+ status: "cancelled_before_submit",
531
+ creditState,
532
+ quotaState: "released",
533
+ terminalAt: input.now,
534
+ terminalUpdateState: "suppressed",
535
+ nextReconcileAt: input.now,
536
+ providerRequestEncrypted: null,
537
+ providerRequestExpiresAt: null,
538
+ credentialEncrypted: null,
539
+ requestEncrypted: null,
540
+ privateDataEraseAfter: input.now,
541
+ boundedPublicReason: boundPublicReason(input.reason),
542
+ reconcileLeaseOwner: null,
543
+ reconcileLeaseExpiresAt: null,
544
+ updatedAt: input.now,
545
+ })
546
+ .where(eq(schema.videoGenerationOperations.id, operation.id))
547
+ .returning({ id: schema.videoGenerationOperations.id });
548
+ if (!updated) throw new Error("Interrupted video generation was not cancelled");
549
+ await tx
550
+ .update(schema.videoGenerationReferences)
551
+ .set({ cleanupAfter: input.now })
552
+ .where(eq(schema.videoGenerationReferences.operationId, operation.id));
553
+ cancelled.push(updated.id);
554
+ }
555
+ return cancelled;
556
+ }
557
+
558
+ export async function claimVideoGenerationOperations(
559
+ db: Database,
560
+ input: { owner: string; leaseSeconds: number; limit: number },
561
+ ): Promise<Array<{ operationId: string; accountId: string; workspaceId: string }>> {
562
+ const rows = await rawRows<{
563
+ operation_id: string;
564
+ account_id: string;
565
+ workspace_id: string;
566
+ }>(
567
+ db,
568
+ sql`select * from opengeni_private.claim_video_generation_operations(
569
+ ${input.owner}, ${input.leaseSeconds}, ${input.limit}
570
+ )`,
571
+ );
572
+ return rows.map((row) => ({
573
+ operationId: row.operation_id,
574
+ accountId: row.account_id,
575
+ workspaceId: row.workspace_id,
576
+ }));
577
+ }
578
+
579
+ export async function getVideoGenerationOperation(
580
+ db: Database,
581
+ workspaceId: string,
582
+ operationId: string,
583
+ ): Promise<VideoGenerationOperationWithReferences | null> {
584
+ return await withWorkspaceRls(db, workspaceId, async (scopedDb) => {
585
+ const [operation] = await scopedDb
586
+ .select()
587
+ .from(schema.videoGenerationOperations)
588
+ .where(
589
+ and(
590
+ eq(schema.videoGenerationOperations.workspaceId, workspaceId),
591
+ eq(schema.videoGenerationOperations.id, operationId),
592
+ ),
593
+ )
594
+ .limit(1);
595
+ if (!operation) return null;
596
+ const references = await scopedDb
597
+ .select()
598
+ .from(schema.videoGenerationReferences)
599
+ .where(eq(schema.videoGenerationReferences.operationId, operationId))
600
+ .orderBy(schema.videoGenerationReferences.ordinal);
601
+ return { ...operation, references };
602
+ });
603
+ }
604
+
605
+ export async function markVideoGenerationSubmissionUncertain(
606
+ db: Database,
607
+ input: OperationMutationInput & { nextReconcileAt: Date; error: string },
608
+ ): Promise<VideoGenerationOperation> {
609
+ return await mutateOperation(db, input, async (tx, operation) => {
610
+ if (operation.status !== "submission_uncertain" || !operation.providerRequestEncrypted) {
611
+ throw invalidTransition(operation, "submission_uncertain");
612
+ }
613
+ const now = new Date();
614
+ const [updated] = await tx
615
+ .update(schema.videoGenerationOperations)
616
+ .set({
617
+ status: "submission_uncertain",
618
+ providerRequestSentAt: operation.providerRequestSentAt ?? now,
619
+ nextReconcileAt: input.nextReconcileAt,
620
+ lastError: boundPrivateError(input.error),
621
+ reconcileLeaseOwner: null,
622
+ reconcileLeaseExpiresAt: null,
623
+ updatedAt: now,
624
+ })
625
+ .where(eq(schema.videoGenerationOperations.id, operation.id))
626
+ .returning();
627
+ return requireRow(updated, "record uncertain video submission");
628
+ });
629
+ }
630
+
631
+ /**
632
+ * Freeze the exact provider start body before issuing the request. If the
633
+ * worker disappears after this transaction, recovery replays the same body
634
+ * and idempotency key rather than reminting URLs or changing request bytes.
635
+ */
636
+ export async function markVideoGenerationSubmissionIntent(
637
+ db: Database,
638
+ input: OperationMutationInput & {
639
+ encryptedProviderRequest: string;
640
+ providerRequestExpiresAt: Date;
641
+ nextReconcileAt: Date;
642
+ },
643
+ ): Promise<VideoGenerationOperation> {
644
+ return await mutateOperation(db, input, async (tx, operation) => {
645
+ if (operation.status === "submission_uncertain") {
646
+ if (!operation.providerRequestEncrypted || !operation.providerRequestExpiresAt) {
647
+ throw new VideoGenerationConflictError("Video provider request is incomplete");
648
+ }
649
+ return operation;
650
+ }
651
+ if (operation.status !== "accepted") {
652
+ throw invalidTransition(operation, "submission_uncertain");
653
+ }
654
+ const now = new Date();
655
+ const [updated] = await tx
656
+ .update(schema.videoGenerationOperations)
657
+ .set({
658
+ status: "submission_uncertain",
659
+ providerRequestEncrypted: input.encryptedProviderRequest,
660
+ providerRequestExpiresAt: input.providerRequestExpiresAt,
661
+ nextReconcileAt: input.nextReconcileAt,
662
+ lastError: null,
663
+ reconcileLeaseOwner: null,
664
+ reconcileLeaseExpiresAt: null,
665
+ updatedAt: now,
666
+ })
667
+ .where(eq(schema.videoGenerationOperations.id, operation.id))
668
+ .returning();
669
+ await tx
670
+ .update(schema.videoGenerationReferences)
671
+ .set({
672
+ grantExpiresAt: input.providerRequestExpiresAt,
673
+ cleanupAfter: new Date(
674
+ Math.max(
675
+ operation.recoveryDeadlineAt.getTime(),
676
+ input.providerRequestExpiresAt.getTime(),
677
+ ),
678
+ ),
679
+ })
680
+ .where(eq(schema.videoGenerationReferences.operationId, operation.id));
681
+ return requireRow(updated, "record video provider submission intent");
682
+ });
683
+ }
684
+
685
+ export async function markVideoGenerationProviderStarted(
686
+ db: Database,
687
+ input: OperationMutationInput & { providerJobId: string; nextReconcileAt: Date },
688
+ ): Promise<VideoGenerationOperation> {
689
+ return await mutateOperation(db, input, async (tx, operation) => {
690
+ if (
691
+ operation.providerJobId === input.providerJobId &&
692
+ operation.status === "provider_started"
693
+ ) {
694
+ return operation;
695
+ }
696
+ if (!inArrayValue(operation.status, ["accepted", "submission_uncertain"])) {
697
+ throw invalidTransition(operation, "provider_started");
698
+ }
699
+ const now = new Date();
700
+ const [updated] = await tx
701
+ .update(schema.videoGenerationOperations)
702
+ .set({
703
+ status: "provider_started",
704
+ providerJobId: input.providerJobId.slice(0, 1_024),
705
+ providerRequestEncrypted: null,
706
+ providerRequestExpiresAt: null,
707
+ providerRequestSentAt: operation.providerRequestSentAt ?? now,
708
+ providerStartedAt: operation.providerStartedAt ?? now,
709
+ nextReconcileAt: input.nextReconcileAt,
710
+ lastError: null,
711
+ reconcileLeaseOwner: null,
712
+ reconcileLeaseExpiresAt: null,
713
+ updatedAt: now,
714
+ })
715
+ .where(eq(schema.videoGenerationOperations.id, operation.id))
716
+ .returning();
717
+ return requireRow(updated, "record video provider job");
718
+ });
719
+ }
720
+
721
+ export async function rescheduleVideoGenerationOperation(
722
+ db: Database,
723
+ input: OperationMutationInput & { owner?: string; nextReconcileAt: Date; error?: string },
724
+ ): Promise<boolean> {
725
+ return await withRlsContext(
726
+ db,
727
+ { accountId: input.accountId, workspaceId: input.workspaceId },
728
+ async (scopedDb) => {
729
+ const [updated] = await scopedDb
730
+ .update(schema.videoGenerationOperations)
731
+ .set({
732
+ nextReconcileAt: input.nextReconcileAt,
733
+ ...(input.error ? { lastError: boundPrivateError(input.error) } : {}),
734
+ reconcileLeaseOwner: null,
735
+ reconcileLeaseExpiresAt: null,
736
+ updatedAt: new Date(),
737
+ })
738
+ .where(
739
+ and(
740
+ eq(schema.videoGenerationOperations.workspaceId, input.workspaceId),
741
+ eq(schema.videoGenerationOperations.id, input.operationId),
742
+ eq(schema.videoGenerationOperations.requestDigest, input.requestDigest),
743
+ ...(input.owner
744
+ ? [eq(schema.videoGenerationOperations.reconcileLeaseOwner, input.owner)]
745
+ : []),
746
+ ),
747
+ )
748
+ .returning({ id: schema.videoGenerationOperations.id });
749
+ return updated !== undefined;
750
+ },
751
+ );
752
+ }
753
+
754
+ export async function markVideoGenerationRetaining(
755
+ db: Database,
756
+ input: OperationMutationInput,
757
+ ): Promise<VideoGenerationOperation> {
758
+ return await mutateOperation(db, input, async (tx, operation) => {
759
+ if (operation.status === "retaining") return operation;
760
+ if (operation.status !== "provider_started") throw invalidTransition(operation, "retaining");
761
+ const [updated] = await tx
762
+ .update(schema.videoGenerationOperations)
763
+ .set({
764
+ status: "retaining",
765
+ nextReconcileAt: new Date(),
766
+ reconcileLeaseOwner: null,
767
+ reconcileLeaseExpiresAt: null,
768
+ updatedAt: new Date(),
769
+ })
770
+ .where(eq(schema.videoGenerationOperations.id, operation.id))
771
+ .returning();
772
+ return requireRow(updated, "begin video retention");
773
+ });
774
+ }
775
+
776
+ export async function settleVideoGenerationFailure(
777
+ db: Database,
778
+ input: OperationMutationInput & {
779
+ status: "provider_failed" | "retention_failed" | "outcome_unknown";
780
+ publicReason: string;
781
+ privateError?: string;
782
+ },
783
+ ): Promise<VideoGenerationOperation> {
784
+ return await mutateOperation(db, input, async (tx, operation) => {
785
+ if (operation.status === input.status) return operation;
786
+ const allowed =
787
+ input.status === "provider_failed"
788
+ ? ["accepted", "submission_uncertain", "provider_started"]
789
+ : input.status === "retention_failed"
790
+ ? ["retaining"]
791
+ : ["submission_uncertain", "provider_started"];
792
+ if (!inArrayValue(operation.status, allowed)) throw invalidTransition(operation, input.status);
793
+ await releaseReservedQuota(tx, operation, false);
794
+ const now = new Date();
795
+ const creditState = await refundVideoGenerationCredits(tx, operation, now);
796
+ const [updated] = await tx
797
+ .update(schema.videoGenerationOperations)
798
+ .set({
799
+ status: input.status,
800
+ creditState,
801
+ quotaState: "released",
802
+ terminalAt: now,
803
+ nextReconcileAt: null,
804
+ terminalUpdateState:
805
+ operation.admissionOutputState === "recorded" ? "pending" : "suppressed",
806
+ providerRequestEncrypted: null,
807
+ providerRequestExpiresAt: null,
808
+ credentialEncrypted: null,
809
+ requestEncrypted: null,
810
+ boundedPublicReason: boundPublicReason(input.publicReason),
811
+ lastError: input.privateError ? boundPrivateError(input.privateError) : null,
812
+ reconcileLeaseOwner: null,
813
+ reconcileLeaseExpiresAt: null,
814
+ privateDataEraseAfter: now,
815
+ updatedAt: now,
816
+ })
817
+ .where(eq(schema.videoGenerationOperations.id, operation.id))
818
+ .returning();
819
+ return requireRow(updated, "settle failed video generation");
820
+ });
821
+ }
822
+
823
+ export type SettleVideoGenerationReadyInput = OperationMutationInput & {
824
+ fileId: string;
825
+ bucket: string;
826
+ objectKey: string;
827
+ sizeBytes: number;
828
+ sha256: string;
829
+ facts: GeneratedVideoFacts;
830
+ };
831
+
832
+ export async function settleVideoGenerationReady(
833
+ db: Database,
834
+ input: SettleVideoGenerationReadyInput,
835
+ ): Promise<{ operation: VideoGenerationOperation; artifact: GeneratedVideoArtifact }> {
836
+ return await withRlsContext(
837
+ db,
838
+ { accountId: input.accountId, workspaceId: input.workspaceId },
839
+ async (scopedDb) =>
840
+ await scopedDb.transaction(async (tx) => {
841
+ const [operation] = await tx
842
+ .select()
843
+ .from(schema.videoGenerationOperations)
844
+ .where(
845
+ and(
846
+ eq(schema.videoGenerationOperations.workspaceId, input.workspaceId),
847
+ eq(schema.videoGenerationOperations.id, input.operationId),
848
+ eq(schema.videoGenerationOperations.requestDigest, input.requestDigest),
849
+ ),
850
+ )
851
+ .for("update")
852
+ .limit(1);
853
+ if (!operation) throw new VideoGenerationConflictError("Video operation not found");
854
+ const [existingArtifact] = await tx
855
+ .select()
856
+ .from(schema.generatedVideoArtifacts)
857
+ .where(eq(schema.generatedVideoArtifacts.operationId, operation.id))
858
+ .limit(1);
859
+ if (operation.status === "completed" && existingArtifact) {
860
+ return { operation, artifact: existingArtifact };
861
+ }
862
+ if (operation.status !== "retaining") throw invalidTransition(operation, "completed");
863
+ if (operation.expectedFileId !== input.fileId) {
864
+ throw new VideoGenerationConflictError("Video File identity changed during settlement");
865
+ }
866
+ if (operation.expectedArtifactId === operation.expectedFileId) {
867
+ throw new Error("Video artifact and File identities must be distinct");
868
+ }
869
+ const now = new Date();
870
+ await tx.insert(schema.files).values({
871
+ id: input.fileId,
872
+ accountId: input.accountId,
873
+ workspaceId: input.workspaceId,
874
+ status: "ready",
875
+ filename: `generated-video-${operation.expectedArtifactId}.mp4`,
876
+ safeFilename: `generated-video-${operation.expectedArtifactId}.mp4`,
877
+ contentType: "video/mp4",
878
+ sizeBytes: input.sizeBytes,
879
+ sha256: input.sha256,
880
+ bucket: input.bucket,
881
+ objectKey: input.objectKey,
882
+ updatedAt: now,
883
+ });
884
+ const [artifact] = await tx
885
+ .insert(schema.generatedVideoArtifacts)
886
+ .values({
887
+ id: operation.expectedArtifactId,
888
+ accountId: input.accountId,
889
+ workspaceId: input.workspaceId,
890
+ primaryFileId: input.fileId,
891
+ operationId: operation.id,
892
+ sessionId: operation.sessionId,
893
+ turnId: operation.turnId,
894
+ attemptId: operation.attemptId,
895
+ modelId: operation.modelId,
896
+ sourceMode: operation.sourceMode,
897
+ promptDigest: operation.promptDigest,
898
+ contentType: "video/mp4",
899
+ sizeBytes: input.sizeBytes,
900
+ sha256: input.sha256,
901
+ durationMillis: Math.round(input.facts.durationSeconds * 1_000),
902
+ width: input.facts.width,
903
+ height: input.facts.height,
904
+ fpsMilli: Math.round(input.facts.fps * 1_000),
905
+ videoCodec: input.facts.videoCodec,
906
+ audioCodec: input.facts.audioCodec,
907
+ hasAudio: input.facts.hasAudio,
908
+ sandboxFilename: `generated-video-${operation.expectedArtifactId}.mp4`,
909
+ readyAt: now,
910
+ })
911
+ .returning();
912
+ if (!artifact) throw new Error("Generated video artifact was not persisted");
913
+ await tx
914
+ .update(schema.workspaceVideoGenerationQuotas)
915
+ .set({
916
+ reservedBytes: sql`${schema.workspaceVideoGenerationQuotas.reservedBytes} - ${operation.reservedBytes}`,
917
+ readyBytes: sql`${schema.workspaceVideoGenerationQuotas.readyBytes} + ${input.sizeBytes}`,
918
+ updatedAt: now,
919
+ })
920
+ .where(eq(schema.workspaceVideoGenerationQuotas.workspaceId, input.workspaceId));
921
+ const [updated] = await tx
922
+ .update(schema.videoGenerationOperations)
923
+ .set({
924
+ status: "completed",
925
+ quotaState: "ready",
926
+ terminalAt: now,
927
+ nextReconcileAt: null,
928
+ terminalUpdateState:
929
+ operation.admissionOutputState === "recorded" ? "pending" : "suppressed",
930
+ providerRequestEncrypted: null,
931
+ providerRequestExpiresAt: null,
932
+ credentialEncrypted: null,
933
+ requestEncrypted: null,
934
+ privateDataEraseAfter: now,
935
+ reconcileLeaseOwner: null,
936
+ reconcileLeaseExpiresAt: null,
937
+ updatedAt: now,
938
+ })
939
+ .where(eq(schema.videoGenerationOperations.id, operation.id))
940
+ .returning();
941
+ return {
942
+ operation: requireRow(updated, "settle ready video generation"),
943
+ artifact,
944
+ };
945
+ }),
946
+ );
947
+ }
948
+
949
+ export async function getGeneratedVideoArtifact(
950
+ db: Database,
951
+ workspaceId: string,
952
+ artifactId: string,
953
+ ): Promise<{ artifact: GeneratedVideoArtifact; file: typeof schema.files.$inferSelect } | null> {
954
+ return await withWorkspaceRls(db, workspaceId, async (scopedDb) => {
955
+ const [row] = await scopedDb
956
+ .select({ artifact: schema.generatedVideoArtifacts, file: schema.files })
957
+ .from(schema.generatedVideoArtifacts)
958
+ .innerJoin(schema.files, eq(schema.files.id, schema.generatedVideoArtifacts.primaryFileId))
959
+ .where(
960
+ and(
961
+ eq(schema.generatedVideoArtifacts.workspaceId, workspaceId),
962
+ eq(schema.generatedVideoArtifacts.id, artifactId),
963
+ ),
964
+ )
965
+ .limit(1);
966
+ return row ?? null;
967
+ });
968
+ }
969
+
970
+ export async function listSessionGeneratedVideoArtifacts(
971
+ db: Database,
972
+ workspaceId: string,
973
+ sessionId: string,
974
+ ): Promise<Array<{ artifact: GeneratedVideoArtifact; file: typeof schema.files.$inferSelect }>> {
975
+ return await withWorkspaceRls(
976
+ db,
977
+ workspaceId,
978
+ async (scopedDb) =>
979
+ await scopedDb
980
+ .select({ artifact: schema.generatedVideoArtifacts, file: schema.files })
981
+ .from(schema.generatedVideoArtifacts)
982
+ .innerJoin(schema.files, eq(schema.files.id, schema.generatedVideoArtifacts.primaryFileId))
983
+ .where(
984
+ and(
985
+ eq(schema.generatedVideoArtifacts.workspaceId, workspaceId),
986
+ eq(schema.generatedVideoArtifacts.sessionId, sessionId),
987
+ sql`${schema.generatedVideoArtifacts.deletedAt} is null`,
988
+ ),
989
+ )
990
+ .orderBy(schema.generatedVideoArtifacts.createdAt, schema.generatedVideoArtifacts.id),
991
+ );
992
+ }
993
+
994
+ /**
995
+ * Record one staging object as erased only after the object-store delete has
996
+ * succeeded. Deleting first is safe because object deletion is idempotent; a
997
+ * crash before this CAS simply repeats the same delete on recovery.
998
+ */
999
+ export async function markVideoGenerationReferenceCleaned(
1000
+ db: Database,
1001
+ input: {
1002
+ accountId: string;
1003
+ workspaceId: string;
1004
+ operationId: string;
1005
+ ordinal: number;
1006
+ stagingObjectKey: string;
1007
+ },
1008
+ ): Promise<boolean> {
1009
+ return await withRlsContext(
1010
+ db,
1011
+ { accountId: input.accountId, workspaceId: input.workspaceId },
1012
+ async (scopedDb) => {
1013
+ const [updated] = await scopedDb
1014
+ .update(schema.videoGenerationReferences)
1015
+ .set({
1016
+ stagingObjectKey: null,
1017
+ grantExpiresAt: null,
1018
+ cleanupAfter: null,
1019
+ cleanedAt: new Date(),
1020
+ })
1021
+ .where(
1022
+ and(
1023
+ eq(schema.videoGenerationReferences.workspaceId, input.workspaceId),
1024
+ eq(schema.videoGenerationReferences.operationId, input.operationId),
1025
+ eq(schema.videoGenerationReferences.ordinal, input.ordinal),
1026
+ eq(schema.videoGenerationReferences.stagingObjectKey, input.stagingObjectKey),
1027
+ ),
1028
+ )
1029
+ .returning({ operationId: schema.videoGenerationReferences.operationId });
1030
+ if (updated) return true;
1031
+ const [existing] = await scopedDb
1032
+ .select({ cleanedAt: schema.videoGenerationReferences.cleanedAt })
1033
+ .from(schema.videoGenerationReferences)
1034
+ .where(
1035
+ and(
1036
+ eq(schema.videoGenerationReferences.workspaceId, input.workspaceId),
1037
+ eq(schema.videoGenerationReferences.operationId, input.operationId),
1038
+ eq(schema.videoGenerationReferences.ordinal, input.ordinal),
1039
+ ),
1040
+ )
1041
+ .limit(1);
1042
+ return existing?.cleanedAt !== null && existing?.cleanedAt !== undefined;
1043
+ },
1044
+ );
1045
+ }
1046
+
1047
+ export async function markVideoGenerationTerminalUpdate(
1048
+ db: Database,
1049
+ input: {
1050
+ accountId: string;
1051
+ workspaceId: string;
1052
+ operationId: string;
1053
+ state: "leased" | "delivered" | "suppressed";
1054
+ updateId?: string;
1055
+ },
1056
+ ): Promise<boolean> {
1057
+ return await withRlsContext(
1058
+ db,
1059
+ { accountId: input.accountId, workspaceId: input.workspaceId },
1060
+ async (scopedDb) => {
1061
+ return await markVideoGenerationTerminalUpdateInTransaction(scopedDb, input);
1062
+ },
1063
+ );
1064
+ }
1065
+
1066
+ export async function markVideoGenerationTerminalUpdateInTransaction(
1067
+ tx: Database,
1068
+ input: {
1069
+ workspaceId: string;
1070
+ operationId: string;
1071
+ state: "leased" | "delivered" | "suppressed";
1072
+ updateId?: string;
1073
+ },
1074
+ ): Promise<boolean> {
1075
+ const allowed =
1076
+ input.state === "leased"
1077
+ ? ["pending", "leased"]
1078
+ : input.state === "delivered"
1079
+ ? ["leased"]
1080
+ : ["pending", "leased"];
1081
+ const [updated] = await tx
1082
+ .update(schema.videoGenerationOperations)
1083
+ .set({
1084
+ terminalUpdateState: input.state,
1085
+ terminalUpdateId: input.state === "suppressed" ? null : (input.updateId ?? null),
1086
+ updatedAt: new Date(),
1087
+ })
1088
+ .where(
1089
+ and(
1090
+ eq(schema.videoGenerationOperations.workspaceId, input.workspaceId),
1091
+ eq(schema.videoGenerationOperations.id, input.operationId),
1092
+ inArray(schema.videoGenerationOperations.terminalUpdateState, allowed),
1093
+ ...(input.state === "delivered" && input.updateId
1094
+ ? [eq(schema.videoGenerationOperations.terminalUpdateId, input.updateId)]
1095
+ : []),
1096
+ ),
1097
+ )
1098
+ .returning({ id: schema.videoGenerationOperations.id });
1099
+ return updated !== undefined;
1100
+ }
1101
+
1102
+ export function mediaGenerationResultForOperation(input: {
1103
+ operation: VideoGenerationOperation;
1104
+ readyReceipt?: Extract<MediaGenerationResult, { status: "ready" }>["receipt"];
1105
+ }): MediaGenerationResult {
1106
+ if (input.operation.status === "completed" && input.readyReceipt) {
1107
+ return {
1108
+ type: "media_generation_result",
1109
+ schemaVersion: 1,
1110
+ status: "ready",
1111
+ operationId: input.operation.id,
1112
+ receipt: input.readyReceipt,
1113
+ };
1114
+ }
1115
+ const failureStatus = input.operation.status;
1116
+ if (
1117
+ !inArrayValue(failureStatus, [
1118
+ "provider_failed",
1119
+ "retention_failed",
1120
+ "cancelled_before_submit",
1121
+ "outcome_unknown",
1122
+ ])
1123
+ ) {
1124
+ throw new Error("Video generation operation is not terminal");
1125
+ }
1126
+ return {
1127
+ type: "media_generation_result",
1128
+ schemaVersion: 1,
1129
+ status: failureStatus,
1130
+ operationId: input.operation.id,
1131
+ boundedPublicReason:
1132
+ input.operation.boundedPublicReason ?? "Video generation did not complete.",
1133
+ } as MediaGenerationResult;
1134
+ }
1135
+
1136
+ /** Build the compact public/model terminal envelope from durable canonical rows. */
1137
+ export async function mediaGenerationResultForStoredOperation(
1138
+ db: Database,
1139
+ operation: VideoGenerationOperation,
1140
+ ): Promise<MediaGenerationResult> {
1141
+ if (operation.status !== "completed") {
1142
+ return mediaGenerationResultForOperation({ operation });
1143
+ }
1144
+ const retained = await getGeneratedVideoArtifact(
1145
+ db,
1146
+ operation.workspaceId,
1147
+ operation.expectedArtifactId,
1148
+ );
1149
+ if (!retained || retained.artifact.deletedAt) {
1150
+ throw new Error("Completed video generation lost its retained artifact");
1151
+ }
1152
+ const artifact = retainedGeneratedVideoReferenceFromFile({
1153
+ id: retained.artifact.id,
1154
+ workspaceId: retained.artifact.workspaceId,
1155
+ status: retained.file.status,
1156
+ contentType: retained.file.contentType,
1157
+ sizeBytes: retained.file.sizeBytes,
1158
+ sha256: retained.file.sha256,
1159
+ updatedAt: retained.artifact.readyAt.toISOString(),
1160
+ width: retained.artifact.width,
1161
+ height: retained.artifact.height,
1162
+ });
1163
+ if (!artifact) throw new Error("Generated video receipt could not be constructed");
1164
+ const receipt = GeneratedVideoReceipt.parse({
1165
+ type: "generated_video",
1166
+ schemaVersion: 1,
1167
+ operationId: operation.id,
1168
+ artifact,
1169
+ video: {
1170
+ durationSeconds: retained.artifact.durationMillis / 1_000,
1171
+ width: retained.artifact.width,
1172
+ height: retained.artifact.height,
1173
+ fps: retained.artifact.fpsMilli / 1_000,
1174
+ hasAudio: retained.artifact.hasAudio,
1175
+ videoCodec: retained.artifact.videoCodec,
1176
+ audioCodec: retained.artifact.audioCodec,
1177
+ },
1178
+ sandboxPath: `/workspace/generated-videos/${retained.artifact.sandboxFilename}`,
1179
+ });
1180
+ return mediaGenerationResultForOperation({ operation, readyReceipt: receipt });
1181
+ }
1182
+
1183
+ export async function getVideoGenerationOperationSummary(
1184
+ db: Database,
1185
+ workspaceId: string,
1186
+ operationId: string,
1187
+ ): Promise<import("@opengeni/contracts").VideoGenerationOperationSummary | null> {
1188
+ const operation = await getVideoGenerationOperation(db, workspaceId, operationId);
1189
+ if (!operation) return null;
1190
+ const terminal = inArrayValue(operation.status, [
1191
+ "completed",
1192
+ "provider_failed",
1193
+ "cancelled_before_submit",
1194
+ "outcome_unknown",
1195
+ "retention_failed",
1196
+ ])
1197
+ ? await mediaGenerationResultForStoredOperation(db, operation)
1198
+ : null;
1199
+ return VideoGenerationOperationSummary.parse({
1200
+ schemaVersion: 1,
1201
+ operationId: operation.id,
1202
+ modelId: operation.modelId,
1203
+ status: operation.status === "submission_uncertain" ? "accepted" : operation.status,
1204
+ createdAt: operation.createdAt.toISOString(),
1205
+ updatedAt: operation.updatedAt.toISOString(),
1206
+ terminal,
1207
+ });
1208
+ }
1209
+
1210
+ type OperationMutationInput = {
1211
+ accountId: string;
1212
+ workspaceId: string;
1213
+ operationId: string;
1214
+ requestDigest: string;
1215
+ };
1216
+
1217
+ async function mutateOperation<T>(
1218
+ db: Database,
1219
+ input: OperationMutationInput,
1220
+ mutate: (tx: Database, operation: VideoGenerationOperation) => Promise<T>,
1221
+ ): Promise<T> {
1222
+ return await withRlsContext(
1223
+ db,
1224
+ { accountId: input.accountId, workspaceId: input.workspaceId },
1225
+ async (scopedDb) =>
1226
+ await scopedDb.transaction(async (txRaw) => {
1227
+ const tx = txRaw as unknown as Database;
1228
+ const [operation] = await tx
1229
+ .select()
1230
+ .from(schema.videoGenerationOperations)
1231
+ .where(
1232
+ and(
1233
+ eq(schema.videoGenerationOperations.workspaceId, input.workspaceId),
1234
+ eq(schema.videoGenerationOperations.id, input.operationId),
1235
+ eq(schema.videoGenerationOperations.requestDigest, input.requestDigest),
1236
+ ),
1237
+ )
1238
+ .for("update")
1239
+ .limit(1);
1240
+ if (!operation) throw new VideoGenerationConflictError("Video operation not found");
1241
+ return await mutate(tx, operation);
1242
+ }),
1243
+ );
1244
+ }
1245
+
1246
+ async function releaseReservedQuota(
1247
+ tx: Database,
1248
+ operation: VideoGenerationOperation,
1249
+ ready: boolean,
1250
+ ): Promise<void> {
1251
+ if (operation.quotaState !== "reserved") return;
1252
+ await tx
1253
+ .update(schema.workspaceVideoGenerationQuotas)
1254
+ .set({
1255
+ reservedBytes: sql`${schema.workspaceVideoGenerationQuotas.reservedBytes} - ${operation.reservedBytes}`,
1256
+ ...(ready
1257
+ ? {
1258
+ readyBytes: sql`${schema.workspaceVideoGenerationQuotas.readyBytes} + ${operation.reservedBytes}`,
1259
+ }
1260
+ : {}),
1261
+ updatedAt: new Date(),
1262
+ })
1263
+ .where(eq(schema.workspaceVideoGenerationQuotas.workspaceId, operation.workspaceId));
1264
+ }
1265
+
1266
+ async function debitVideoGenerationCredits(
1267
+ tx: Database,
1268
+ operation: VideoGenerationOperation,
1269
+ ): Promise<void> {
1270
+ if (operation.pricedCostMicros <= 0 || operation.fundingSource !== "opengeni_credits") {
1271
+ throw new Error("Managed video credit debit has an invalid funding binding");
1272
+ }
1273
+ await tx.execute(sql`select pg_advisory_xact_lock(hashtext(${operation.accountId}))`);
1274
+ const [balanceRow] = await tx
1275
+ .select({
1276
+ balanceMicros: sql<number>`coalesce(sum(${schema.creditLedgerEntries.amountMicros}), 0)`,
1277
+ })
1278
+ .from(schema.creditLedgerEntries)
1279
+ .where(eq(schema.creditLedgerEntries.accountId, operation.accountId));
1280
+ const balanceMicros = Number(balanceRow?.balanceMicros ?? 0);
1281
+ if (!Number.isSafeInteger(balanceMicros) || balanceMicros < operation.pricedCostMicros) {
1282
+ throw new VideoGenerationCreditError();
1283
+ }
1284
+ const now = new Date();
1285
+ const inserted = await tx
1286
+ .insert(schema.creditLedgerEntries)
1287
+ .values({
1288
+ accountId: operation.accountId,
1289
+ workspaceId: operation.workspaceId,
1290
+ type: "video_generation_debit",
1291
+ amountMicros: -operation.pricedCostMicros,
1292
+ sourceType: "video_generation_operation",
1293
+ sourceId: operation.id,
1294
+ idempotencyKey: `credit:video_generation_debit:${operation.id}`,
1295
+ metadata: {
1296
+ modelId: operation.modelId,
1297
+ sourceMode: operation.sourceMode,
1298
+ pricedCostMicros: operation.pricedCostMicros,
1299
+ },
1300
+ occurredAt: now,
1301
+ })
1302
+ .onConflictDoNothing({ target: schema.creditLedgerEntries.idempotencyKey })
1303
+ .returning({ id: schema.creditLedgerEntries.id });
1304
+ if (inserted.length !== 1) {
1305
+ throw new VideoGenerationConflictError("Video generation credit debit already exists");
1306
+ }
1307
+ await tx
1308
+ .insert(schema.usageEvents)
1309
+ .values({
1310
+ accountId: operation.accountId,
1311
+ workspaceId: operation.workspaceId,
1312
+ eventType: "video_generation.cost",
1313
+ quantity: operation.pricedCostMicros,
1314
+ unit: "usd_micros",
1315
+ sourceResourceType: "video_generation_operation",
1316
+ sourceResourceId: operation.id,
1317
+ sessionId: operation.sessionId,
1318
+ turnId: operation.turnId,
1319
+ turnAttemptId: operation.attemptId,
1320
+ idempotencyKey: `usage:video_generation.cost:${operation.id}`,
1321
+ occurredAt: now,
1322
+ })
1323
+ .onConflictDoNothing({ target: schema.usageEvents.idempotencyKey });
1324
+ }
1325
+
1326
+ async function refundVideoGenerationCredits(
1327
+ tx: Database,
1328
+ operation: VideoGenerationOperation,
1329
+ now: Date,
1330
+ ): Promise<VideoGenerationOperation["creditState"]> {
1331
+ if (operation.creditState !== "debited") return operation.creditState;
1332
+ if (operation.fundingSource !== "opengeni_credits" || operation.pricedCostMicros <= 0) {
1333
+ throw new Error("Video generation credit refund has an invalid funding binding");
1334
+ }
1335
+ await tx.execute(sql`select pg_advisory_xact_lock(hashtext(${operation.accountId}))`);
1336
+ const inserted = await tx
1337
+ .insert(schema.creditLedgerEntries)
1338
+ .values({
1339
+ accountId: operation.accountId,
1340
+ workspaceId: operation.workspaceId,
1341
+ type: "video_generation_refund",
1342
+ amountMicros: operation.pricedCostMicros,
1343
+ sourceType: "video_generation_operation",
1344
+ sourceId: operation.id,
1345
+ idempotencyKey: `credit:video_generation_refund:${operation.id}`,
1346
+ metadata: {
1347
+ modelId: operation.modelId,
1348
+ sourceMode: operation.sourceMode,
1349
+ pricedCostMicros: operation.pricedCostMicros,
1350
+ },
1351
+ occurredAt: now,
1352
+ })
1353
+ .onConflictDoNothing({ target: schema.creditLedgerEntries.idempotencyKey })
1354
+ .returning({ id: schema.creditLedgerEntries.id });
1355
+ if (inserted.length !== 1) {
1356
+ throw new VideoGenerationConflictError("Video generation credit refund already exists");
1357
+ }
1358
+ await tx
1359
+ .insert(schema.usageEvents)
1360
+ .values({
1361
+ accountId: operation.accountId,
1362
+ workspaceId: operation.workspaceId,
1363
+ eventType: "video_generation.refund",
1364
+ quantity: operation.pricedCostMicros,
1365
+ unit: "usd_micros",
1366
+ sourceResourceType: "video_generation_operation",
1367
+ sourceResourceId: operation.id,
1368
+ sessionId: operation.sessionId,
1369
+ turnId: operation.turnId,
1370
+ turnAttemptId: operation.attemptId,
1371
+ idempotencyKey: `usage:video_generation.refund:${operation.id}`,
1372
+ occurredAt: now,
1373
+ })
1374
+ .onConflictDoNothing({ target: schema.usageEvents.idempotencyKey });
1375
+ return "refunded";
1376
+ }
1377
+
1378
+ function policyFromRow(
1379
+ row: typeof schema.workspaceVideoGenerationPolicies.$inferSelect | undefined,
1380
+ ): VideoGenerationPolicyValue {
1381
+ return VideoGenerationPolicy.parse(
1382
+ row
1383
+ ? {
1384
+ schemaVersion: 1,
1385
+ revision: row.revision,
1386
+ fundingSource: row.fundingSource,
1387
+ enabledModelIds: row.enabledModelIds,
1388
+ defaultModelId: row.defaultModelId,
1389
+ }
1390
+ : {
1391
+ schemaVersion: 1,
1392
+ revision: 0,
1393
+ fundingSource: "workspace_gateway",
1394
+ enabledModelIds: [],
1395
+ defaultModelId: null,
1396
+ },
1397
+ );
1398
+ }
1399
+
1400
+ function assertSupportedModels(modelIds: readonly string[]): void {
1401
+ for (const modelId of modelIds) {
1402
+ if (modelId !== SEEDANCE_2_5_MODEL_ID) {
1403
+ throw new Error(`Unknown video generation model: ${modelId}`);
1404
+ }
1405
+ }
1406
+ }
1407
+
1408
+ function assertAdmissionMatches(
1409
+ operation: VideoGenerationOperation,
1410
+ input: AdmitVideoGenerationOperationInput,
1411
+ ): void {
1412
+ if (
1413
+ operation.requestDigest !== input.requestDigest ||
1414
+ operation.toolCallId !== input.toolCallId ||
1415
+ operation.sessionId !== input.sessionId ||
1416
+ operation.turnId !== input.turnId ||
1417
+ operation.fundingSource !== input.fundingSource ||
1418
+ operation.pricedCostMicros !== input.pricedCostMicros
1419
+ ) {
1420
+ throw new VideoGenerationConflictError(
1421
+ "Video generation admission key was reused with different arguments",
1422
+ );
1423
+ }
1424
+ }
1425
+
1426
+ function inPreSubmitState(status: string): boolean {
1427
+ return inArrayValue(status, ["preparing", "prepared", "accepted"]);
1428
+ }
1429
+
1430
+ function inArrayValue<T extends string>(value: string, candidates: readonly T[]): value is T {
1431
+ return (candidates as readonly string[]).includes(value);
1432
+ }
1433
+
1434
+ function invalidTransition(operation: VideoGenerationOperation, target: string): Error {
1435
+ return new VideoGenerationConflictError(
1436
+ `Invalid video generation transition ${operation.status} -> ${target}`,
1437
+ );
1438
+ }
1439
+
1440
+ function requireRow<T>(value: T | undefined, action: string): T {
1441
+ if (!value) throw new Error(`Failed to ${action}`);
1442
+ return value;
1443
+ }
1444
+
1445
+ function boundPublicReason(value: string): string {
1446
+ const normalized = value.replace(/\s+/gu, " ").trim();
1447
+ return (normalized || "Video generation did not complete.").slice(0, 1_000);
1448
+ }
1449
+
1450
+ function boundPrivateError(value: string): string {
1451
+ return value.replace(/\s+/gu, " ").trim().slice(0, 4_096);
1452
+ }