@opengeni/db 0.28.1 → 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.
- package/dist/attached-browser-devices.d.ts +42 -0
- package/dist/attempt-tool-catalogs.d.ts +16 -0
- package/dist/browser-auth.d.ts +91 -0
- package/dist/browser-identities.d.ts +128 -0
- package/dist/browser-sessions.d.ts +272 -0
- package/dist/browser-state-artifacts.d.ts +17 -0
- package/dist/capability-components.d.ts +37 -0
- package/dist/capability-integrations.d.ts +192 -0
- package/dist/chunk-F5FT7BEZ.js +3535 -0
- package/dist/chunk-F5FT7BEZ.js.map +1 -0
- package/dist/chunk-ISI2TIUG.js +639 -0
- package/dist/chunk-ISI2TIUG.js.map +1 -0
- package/dist/chunk-MWDVXQOL.js +11639 -0
- package/dist/chunk-MWDVXQOL.js.map +1 -0
- package/dist/chunk-NBE6CHRI.js +955 -0
- package/dist/chunk-NBE6CHRI.js.map +1 -0
- package/dist/{chunk-DBS5HPEW.js → chunk-YHZXQ7HP.js} +760 -11
- package/dist/chunk-YHZXQ7HP.js.map +1 -0
- package/dist/codemode-operations.d.ts +117 -0
- package/dist/codex-token-resolver.d.ts +2 -2
- package/dist/company-profile-schema.d.ts +798 -0
- package/dist/company-profile.d.ts +268 -0
- package/dist/computer-sessions.d.ts +109 -0
- package/dist/connection-token-resolver.d.ts +9 -4
- package/dist/database.d.ts +52 -3
- package/dist/editable-artifact-durable-export.d.ts +153 -0
- package/dist/editable-artifact-durable-export.js +788 -0
- package/dist/editable-artifact-durable-export.js.map +1 -0
- package/dist/editable-artifact-materialization.d.ts +123 -0
- package/dist/editable-artifacts-schema.d.ts +4152 -0
- package/dist/editable-artifacts.d.ts +610 -0
- package/dist/editable-artifacts.js +26 -0
- package/dist/editable-artifacts.js.map +1 -0
- package/dist/environment-crypto.d.ts +8 -4
- package/dist/generated-images.d.ts +139 -0
- package/dist/index.d.ts +958 -126
- package/dist/index.js +31204 -12172
- package/dist/index.js.map +1 -1
- package/dist/insights.d.ts +51 -4
- package/dist/integration-bindings.d.ts +70 -0
- package/dist/integration-features.d.ts +99 -0
- package/dist/interaction-revisions.d.ts +3 -0
- package/dist/interaction-schema.d.ts +5372 -0
- package/dist/knowledge-source-sync-schema.d.ts +1679 -0
- package/dist/knowledge-source-sync.d.ts +274 -0
- package/dist/lossless-columns.d.ts +58 -0
- package/dist/lossless-json.d.ts +39 -0
- package/dist/memory-domain.d.ts +3 -6
- package/dist/memory-governance.d.ts +2 -2
- package/dist/memory-slack-delivery.d.ts +101 -0
- package/dist/new-session-drafts.d.ts +2 -2
- package/dist/pack-components.d.ts +76 -0
- package/dist/pack-installations.d.ts +86 -0
- package/dist/persistence-errors.d.ts +7 -14
- package/dist/plugin-packages.d.ts +126 -0
- package/dist/preference-registry.d.ts +1 -1
- package/dist/provision-roles.d.ts +9 -1
- package/dist/provision-roles.js +1 -1
- package/dist/runtime-posture.d.ts +18 -6
- package/dist/schema.d.ts +19122 -8731
- package/dist/schema.js +173 -1
- package/dist/scoped-knowledge.d.ts +97 -1
- package/dist/session-control.d.ts +4 -4
- package/dist/session-queue-commands.d.ts +19 -11
- package/dist/session-realtime-context.d.ts +2 -2
- package/dist/session-realtime-ledger.d.ts +4 -4
- package/dist/session-realtime-mirror.d.ts +2 -2
- package/dist/session-realtime-state.d.ts +1 -1
- package/dist/session-realtime-terminal.d.ts +8 -1
- package/dist/session-realtime.d.ts +7 -7
- package/dist/session-tool-call-settlement.d.ts +1 -1
- package/dist/slack-user-link-access.d.ts +54 -0
- package/dist/transcription-recordings-schema.d.ts +44 -6
- package/dist/transcription-recordings.d.ts +3 -3
- package/dist/turn-initiator.d.ts +2 -2
- package/dist/video-generation.d.ts +216 -0
- package/dist/video-generation.js +66 -0
- package/dist/video-generation.js.map +1 -0
- package/dist/workspace-artifacts.d.ts +1 -1
- package/dist/workspace-instruction-policies.d.ts +1 -1
- package/dist/workspace-learning-policy-schema.d.ts +932 -0
- package/dist/workspace-learning-policy.d.ts +161 -0
- package/drizzle/0065_enrollment_credential_generation.sql +10 -0
- package/drizzle/0140_retained_screenshot_artifacts.sql +192 -0
- package/drizzle/0176_lossless_canonical_json.sql +975 -0
- package/drizzle/0177_session_events_workspace_turn_type_index.sql +5 -0
- package/drizzle/0178_permissioned_secret_reads.sql +14 -0
- package/drizzle/0179_slack_private_shortcut_delivery_gate.sql +85 -0
- package/drizzle/0180_retained_screenshot_lifecycle_fences.sql +273 -0
- package/drizzle/0181_connected_machine_removal.sql +52 -0
- package/drizzle/0182_connected_machine_remove_session_default.sql +77 -0
- package/drizzle/0183_model_call_provider_cost_estimates.sql +39 -0
- package/drizzle/0184_sandbox_drain_teardown_fence.sql +682 -0
- package/drizzle/0185_temporal_schedule_cleanup_outbox.sql +168 -0
- package/drizzle/0186_sandbox_capture_provider_contract.sql +400 -0
- package/drizzle/0187_generated_image_artifacts.sql +173 -0
- package/drizzle/0188_image_generation_retention_failure.sql +25 -0
- package/drizzle/0189_retained_session_image_formats.sql +13 -0
- package/drizzle/0190_timeline_annotations.sql +31 -0
- package/drizzle/0191_editable_artifact_engine.sql +3853 -0
- package/drizzle/0192_editable_artifact_live_tickets.sql +338 -0
- package/drizzle/0193_editable_artifact_authorization.sql +190 -0
- package/drizzle/0194_editable_artifact_durable_exports.sql +160 -0
- package/drizzle/0195_editable_artifact_import_authorization.sql +203 -0
- package/drizzle/0196_rig_provider_images.sql +152 -0
- package/drizzle/0197_knowledge_source_sync_schedules.sql +523 -0
- package/drizzle/0198_memory_slack_publication_delivery.sql +393 -0
- package/drizzle/0199_workspace_learning_policy.sql +980 -0
- package/drizzle/0201_company_profile_authority.sql +849 -0
- package/drizzle/0202_document_index_checkpoints.sql +85 -0
- package/drizzle/0203_durable_video_generation.sql +353 -0
- package/drizzle/0204_video_generation_funding.sql +44 -0
- package/drizzle/0205_attempt_tool_catalogs.sql +230 -0
- package/drizzle/0206_browser_sessions.sql +646 -0
- package/drizzle/0207_browser_identities.sql +379 -0
- package/drizzle/0208_attached_browser_devices.sql +165 -0
- package/drizzle/0209_computer_sessions.sql +575 -0
- package/drizzle/0210_browser_auth_network_interventions.sql +441 -0
- package/drizzle/0211_editable_artifact_session_links.sql +58 -0
- package/drizzle/0212_slack_installation_bindings.sql +348 -0
- package/drizzle/0213_slack_user_link_access_requests.sql +177 -0
- package/drizzle/0214_session_activity_commit_gate.sql +262 -0
- package/drizzle/0215_capabilities_platform.sql +980 -0
- package/drizzle/0216_pack_component_ownership.sql +235 -0
- package/drizzle/0217_capability_definition_delete_authority.sql +32 -0
- package/package.json +18 -5
- package/src/attached-browser-devices.ts +371 -0
- package/src/attempt-tool-catalogs.ts +131 -0
- package/src/browser-auth.ts +1896 -0
- package/src/browser-identities.ts +1168 -0
- package/src/browser-sessions.ts +2005 -0
- package/src/browser-state-artifacts.ts +59 -0
- package/src/capability-components.ts +166 -0
- package/src/capability-integrations.ts +1663 -0
- package/src/codemode-operations.ts +674 -0
- package/src/company-profile-schema.ts +143 -0
- package/src/company-profile.ts +968 -0
- package/src/computer-sessions.ts +1130 -0
- package/src/connection-token-resolver.ts +270 -25
- package/src/database.ts +434 -24
- package/src/editable-artifact-durable-export.ts +1201 -0
- package/src/editable-artifact-materialization.ts +893 -0
- package/src/editable-artifacts-schema.ts +879 -0
- package/src/editable-artifacts.ts +5404 -0
- package/src/environment-crypto.ts +22 -9
- package/src/generated-images.ts +740 -0
- package/src/index.ts +10117 -2730
- package/src/insights.ts +160 -13
- package/src/integration-bindings.ts +455 -0
- package/src/integration-features.ts +859 -0
- package/src/interaction-revisions.ts +40 -0
- package/src/interaction-schema.ts +1303 -0
- package/src/knowledge-source-sync-schema.ts +192 -0
- package/src/knowledge-source-sync.ts +1922 -0
- package/src/lossless-columns.ts +35 -0
- package/src/lossless-json.ts +322 -0
- package/src/memory-domain.ts +5 -44
- package/src/memory-slack-delivery.ts +801 -0
- package/src/pack-components.ts +954 -0
- package/src/pack-installations.ts +929 -0
- package/src/persistence-errors.ts +26 -34
- package/src/plugin-packages.ts +1186 -0
- package/src/provision-roles.ts +302 -1
- package/src/runtime-posture-cli.ts +9 -0
- package/src/runtime-posture.ts +514 -5
- package/src/schema.ts +5177 -2957
- package/src/scoped-knowledge-schema.ts +1 -1
- package/src/scoped-knowledge.ts +655 -3
- package/src/session-control.ts +133 -81
- package/src/session-queue-commands.ts +511 -247
- package/src/session-realtime-context.ts +20 -7
- package/src/session-realtime-ledger.ts +32 -10
- package/src/session-realtime-mirror.ts +4 -2
- package/src/session-realtime-terminal.ts +89 -21
- package/src/session-realtime.ts +10 -9
- package/src/session-tool-call-settlement.ts +38 -15
- package/src/slack-user-link-access.ts +702 -0
- package/src/transcription-recordings-schema.ts +5 -2
- package/src/transcription-recordings.ts +70 -40
- package/src/video-generation.ts +1452 -0
- package/src/workspace-learning-policy-schema.ts +139 -0
- package/src/workspace-learning-policy.ts +595 -0
- package/dist/chunk-DBS5HPEW.js.map +0 -1
- package/dist/chunk-HT5T62CC.js +0 -6803
- package/dist/chunk-HT5T62CC.js.map +0 -1
- package/dist/event-payload-sanitizer.d.ts +0 -32
- package/src/event-payload-sanitizer.ts +0 -377
|
@@ -0,0 +1,955 @@
|
|
|
1
|
+
import {
|
|
2
|
+
rawRows,
|
|
3
|
+
withRlsContext,
|
|
4
|
+
withWorkspaceRls
|
|
5
|
+
} from "./chunk-ISI2TIUG.js";
|
|
6
|
+
import {
|
|
7
|
+
connections,
|
|
8
|
+
creditLedgerEntries,
|
|
9
|
+
files,
|
|
10
|
+
generatedVideoArtifacts,
|
|
11
|
+
usageEvents,
|
|
12
|
+
videoGenerationOperations,
|
|
13
|
+
videoGenerationReferences,
|
|
14
|
+
workspaceVideoGenerationPolicies,
|
|
15
|
+
workspaceVideoGenerationQuotas,
|
|
16
|
+
workspaces
|
|
17
|
+
} from "./chunk-MWDVXQOL.js";
|
|
18
|
+
|
|
19
|
+
// src/video-generation.ts
|
|
20
|
+
import {
|
|
21
|
+
GENERATED_VIDEO_MAX_BYTES,
|
|
22
|
+
GeneratedVideoReceipt,
|
|
23
|
+
SEEDANCE_2_5_MODEL_ID,
|
|
24
|
+
VideoGenerationPolicy,
|
|
25
|
+
VideoGenerationOperationSummary,
|
|
26
|
+
retainedGeneratedVideoReferenceFromFile
|
|
27
|
+
} from "@opengeni/contracts";
|
|
28
|
+
import { and, eq, inArray, sql } from "drizzle-orm";
|
|
29
|
+
var ACTIVE_VIDEO_GENERATION_STATUSES = [
|
|
30
|
+
"preparing",
|
|
31
|
+
"prepared",
|
|
32
|
+
"accepted",
|
|
33
|
+
"submission_uncertain",
|
|
34
|
+
"provider_started",
|
|
35
|
+
"retaining"
|
|
36
|
+
];
|
|
37
|
+
var VideoGenerationConflictError = class extends Error {
|
|
38
|
+
constructor(message) {
|
|
39
|
+
super(message);
|
|
40
|
+
this.name = "VideoGenerationConflictError";
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
var VideoGenerationCapacityError = class extends Error {
|
|
44
|
+
constructor(message) {
|
|
45
|
+
super(message);
|
|
46
|
+
this.name = "VideoGenerationCapacityError";
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
var VideoGenerationCreditError = class extends Error {
|
|
50
|
+
constructor(message = "insufficient OpenGeni credits") {
|
|
51
|
+
super(message);
|
|
52
|
+
this.name = "VideoGenerationCreditError";
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
async function getWorkspaceVideoGenerationPolicy(db, workspaceId) {
|
|
56
|
+
return await withWorkspaceRls(db, workspaceId, async (scopedDb) => {
|
|
57
|
+
const [row] = await scopedDb.select().from(workspaceVideoGenerationPolicies).where(eq(workspaceVideoGenerationPolicies.workspaceId, workspaceId)).limit(1);
|
|
58
|
+
return policyFromRow(row);
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
async function updateWorkspaceVideoGenerationPolicy(db, input) {
|
|
62
|
+
const requested = VideoGenerationPolicy.parse({
|
|
63
|
+
schemaVersion: 1,
|
|
64
|
+
revision: input.expectedRevision + 1,
|
|
65
|
+
fundingSource: input.fundingSource,
|
|
66
|
+
enabledModelIds: input.enabledModelIds,
|
|
67
|
+
defaultModelId: input.defaultModelId
|
|
68
|
+
});
|
|
69
|
+
assertSupportedModels(requested.enabledModelIds);
|
|
70
|
+
return await withRlsContext(
|
|
71
|
+
db,
|
|
72
|
+
{ accountId: input.accountId, workspaceId: input.workspaceId },
|
|
73
|
+
async (scopedDb) => await scopedDb.transaction(async (tx) => {
|
|
74
|
+
const [workspace] = await tx.select({ id: workspaces.id }).from(workspaces).where(
|
|
75
|
+
and(
|
|
76
|
+
eq(workspaces.id, input.workspaceId),
|
|
77
|
+
eq(workspaces.accountId, input.accountId)
|
|
78
|
+
)
|
|
79
|
+
).for("update").limit(1);
|
|
80
|
+
if (!workspace) throw new Error("Workspace not found");
|
|
81
|
+
const [current] = await tx.select().from(workspaceVideoGenerationPolicies).where(eq(workspaceVideoGenerationPolicies.workspaceId, input.workspaceId)).for("update").limit(1);
|
|
82
|
+
const currentRevision = current?.revision ?? 0;
|
|
83
|
+
if (currentRevision !== input.expectedRevision) {
|
|
84
|
+
throw new VideoGenerationConflictError("Video generation policy changed");
|
|
85
|
+
}
|
|
86
|
+
const now = /* @__PURE__ */ new Date();
|
|
87
|
+
const values = {
|
|
88
|
+
workspaceId: input.workspaceId,
|
|
89
|
+
accountId: input.accountId,
|
|
90
|
+
revision: currentRevision + 1,
|
|
91
|
+
fundingSource: requested.fundingSource,
|
|
92
|
+
enabledModelIds: [...requested.enabledModelIds],
|
|
93
|
+
defaultModelId: requested.defaultModelId,
|
|
94
|
+
updatedBySubjectId: input.subjectId.slice(0, 1024),
|
|
95
|
+
updatedAt: now
|
|
96
|
+
};
|
|
97
|
+
const [row] = current ? await tx.update(workspaceVideoGenerationPolicies).set(values).where(eq(workspaceVideoGenerationPolicies.workspaceId, input.workspaceId)).returning() : await tx.insert(workspaceVideoGenerationPolicies).values(values).returning();
|
|
98
|
+
if (!row) throw new Error("Video generation policy update was not persisted");
|
|
99
|
+
return policyFromRow(row);
|
|
100
|
+
})
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
async function admitVideoGenerationOperation(db, input) {
|
|
104
|
+
const reservedBytes = input.reservedBytes ?? GENERATED_VIDEO_MAX_BYTES;
|
|
105
|
+
return await withRlsContext(
|
|
106
|
+
db,
|
|
107
|
+
{ accountId: input.accountId, workspaceId: input.workspaceId },
|
|
108
|
+
async (scopedDb) => await scopedDb.transaction(async (tx) => {
|
|
109
|
+
await tx.execute(
|
|
110
|
+
sql`select pg_advisory_xact_lock(hashtextextended(${`video-generation:${input.admissionKey}`}, 0))`
|
|
111
|
+
);
|
|
112
|
+
const [existing] = await tx.select().from(videoGenerationOperations).where(
|
|
113
|
+
and(
|
|
114
|
+
eq(videoGenerationOperations.workspaceId, input.workspaceId),
|
|
115
|
+
eq(videoGenerationOperations.admissionKey, input.admissionKey)
|
|
116
|
+
)
|
|
117
|
+
).limit(1);
|
|
118
|
+
if (existing) {
|
|
119
|
+
assertAdmissionMatches(existing, input);
|
|
120
|
+
return { operation: existing, created: false };
|
|
121
|
+
}
|
|
122
|
+
const [policy] = await tx.select().from(workspaceVideoGenerationPolicies).where(eq(workspaceVideoGenerationPolicies.workspaceId, input.workspaceId)).for("update").limit(1);
|
|
123
|
+
if (!policy || policy.revision !== input.policyRevision || policy.fundingSource !== input.fundingSource || !policy.enabledModelIds.includes(input.modelId)) {
|
|
124
|
+
throw new VideoGenerationConflictError("Video generation capability changed");
|
|
125
|
+
}
|
|
126
|
+
const active = await tx.select({ id: videoGenerationOperations.id }).from(videoGenerationOperations).where(
|
|
127
|
+
and(
|
|
128
|
+
eq(videoGenerationOperations.workspaceId, input.workspaceId),
|
|
129
|
+
inArray(videoGenerationOperations.status, [
|
|
130
|
+
...ACTIVE_VIDEO_GENERATION_STATUSES
|
|
131
|
+
])
|
|
132
|
+
)
|
|
133
|
+
).for("update");
|
|
134
|
+
if (active.length >= input.maxConcurrentPerWorkspace) {
|
|
135
|
+
throw new VideoGenerationCapacityError("Workspace video generation limit reached");
|
|
136
|
+
}
|
|
137
|
+
await tx.insert(workspaceVideoGenerationQuotas).values({ workspaceId: input.workspaceId, accountId: input.accountId }).onConflictDoNothing({ target: workspaceVideoGenerationQuotas.workspaceId });
|
|
138
|
+
const [quota] = await tx.select().from(workspaceVideoGenerationQuotas).where(eq(workspaceVideoGenerationQuotas.workspaceId, input.workspaceId)).for("update").limit(1);
|
|
139
|
+
if (!quota) throw new Error("Video generation quota row disappeared");
|
|
140
|
+
if (quota.reservedBytes + quota.readyBytes + reservedBytes > input.workspaceQuotaBytes) {
|
|
141
|
+
throw new VideoGenerationCapacityError("Workspace video storage quota reached");
|
|
142
|
+
}
|
|
143
|
+
const [operation] = await tx.insert(videoGenerationOperations).values({
|
|
144
|
+
id: input.id,
|
|
145
|
+
accountId: input.accountId,
|
|
146
|
+
workspaceId: input.workspaceId,
|
|
147
|
+
sessionId: input.sessionId,
|
|
148
|
+
turnId: input.turnId,
|
|
149
|
+
attemptId: input.attemptId,
|
|
150
|
+
toolCallId: input.toolCallId,
|
|
151
|
+
admissionKey: input.admissionKey,
|
|
152
|
+
requestDigest: input.requestDigest,
|
|
153
|
+
promptDigest: input.promptDigest,
|
|
154
|
+
requestEncrypted: input.requestEncrypted,
|
|
155
|
+
modelId: input.modelId,
|
|
156
|
+
sourceMode: input.sourceMode,
|
|
157
|
+
capabilityRevision: input.capabilityRevision,
|
|
158
|
+
fundingSource: input.fundingSource,
|
|
159
|
+
pricedCostMicros: input.pricedCostMicros,
|
|
160
|
+
creditState: input.pricedCostMicros > 0 ? "debited" : "not_applicable",
|
|
161
|
+
connectionId: input.connectionId,
|
|
162
|
+
credentialVersion: input.credentialVersion,
|
|
163
|
+
credentialEncrypted: input.credentialEncrypted,
|
|
164
|
+
providerIdempotencyKey: input.providerIdempotencyKey,
|
|
165
|
+
expectedArtifactId: input.expectedArtifactId,
|
|
166
|
+
expectedFileId: input.expectedFileId,
|
|
167
|
+
reservedBytes,
|
|
168
|
+
recoveryDeadlineAt: input.recoveryDeadlineAt,
|
|
169
|
+
status: input.references.length === 0 ? "prepared" : "preparing",
|
|
170
|
+
admissionOutputState: "pending",
|
|
171
|
+
terminalUpdateState: "ineligible"
|
|
172
|
+
}).returning();
|
|
173
|
+
if (!operation) throw new Error("Video generation operation was not admitted");
|
|
174
|
+
if (input.pricedCostMicros > 0) {
|
|
175
|
+
if (input.fundingSource !== "opengeni_credits" || input.connectionId !== null) {
|
|
176
|
+
throw new Error("Only OpenGeni-funded video operations may debit credits");
|
|
177
|
+
}
|
|
178
|
+
await debitVideoGenerationCredits(tx, operation);
|
|
179
|
+
}
|
|
180
|
+
if (input.references.length > 0) {
|
|
181
|
+
await tx.insert(videoGenerationReferences).values(
|
|
182
|
+
input.references.map((reference) => ({
|
|
183
|
+
operationId: operation.id,
|
|
184
|
+
workspaceId: input.workspaceId,
|
|
185
|
+
accountId: input.accountId,
|
|
186
|
+
grantExpiresAt: reference.grantExpiresAt ?? null,
|
|
187
|
+
...reference
|
|
188
|
+
}))
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
await tx.update(workspaceVideoGenerationQuotas).set({
|
|
192
|
+
reservedBytes: sql`${workspaceVideoGenerationQuotas.reservedBytes} + ${reservedBytes}`,
|
|
193
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
194
|
+
}).where(eq(workspaceVideoGenerationQuotas.workspaceId, input.workspaceId));
|
|
195
|
+
return { operation, created: true };
|
|
196
|
+
})
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
async function markVideoGenerationPrepared(db, input) {
|
|
200
|
+
return await mutateOperation(db, input, async (tx, operation) => {
|
|
201
|
+
if (operation.status === "prepared") return operation;
|
|
202
|
+
if (operation.status !== "preparing") throw invalidTransition(operation, "prepared");
|
|
203
|
+
const references = await tx.select({
|
|
204
|
+
stagingObjectKey: videoGenerationReferences.stagingObjectKey,
|
|
205
|
+
cleanedAt: videoGenerationReferences.cleanedAt
|
|
206
|
+
}).from(videoGenerationReferences).where(eq(videoGenerationReferences.operationId, operation.id));
|
|
207
|
+
if (references.length === 0 || references.some((reference) => !reference.stagingObjectKey || reference.cleanedAt)) {
|
|
208
|
+
throw new VideoGenerationConflictError("Video references are not sealed");
|
|
209
|
+
}
|
|
210
|
+
const [updated] = await tx.update(videoGenerationOperations).set({ status: "prepared", updatedAt: /* @__PURE__ */ new Date() }).where(eq(videoGenerationOperations.id, operation.id)).returning();
|
|
211
|
+
return requireRow(updated, "seal video generation references");
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
async function markVideoGenerationAccepted(db, input) {
|
|
215
|
+
return await mutateOperation(
|
|
216
|
+
db,
|
|
217
|
+
input,
|
|
218
|
+
async (tx, operation) => await markVideoGenerationAcceptedInTransaction(tx, {
|
|
219
|
+
workspaceId: input.workspaceId,
|
|
220
|
+
operation
|
|
221
|
+
})
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
async function markVideoGenerationAcceptedInTransaction(tx, input) {
|
|
225
|
+
const operation = input.operation;
|
|
226
|
+
if (input.toolCallId !== void 0 && operation.toolCallId !== input.toolCallId) {
|
|
227
|
+
throw new VideoGenerationConflictError("Video generation tool-call identity changed");
|
|
228
|
+
}
|
|
229
|
+
if (operation.admissionOutputState === "recorded") return operation;
|
|
230
|
+
if (operation.status !== "prepared") {
|
|
231
|
+
throw new VideoGenerationConflictError("Video generation is no longer awaiting acceptance");
|
|
232
|
+
}
|
|
233
|
+
const [policy] = await tx.select().from(workspaceVideoGenerationPolicies).where(eq(workspaceVideoGenerationPolicies.workspaceId, input.workspaceId)).for("share").limit(1);
|
|
234
|
+
const [connection] = operation.connectionId ? await tx.select({
|
|
235
|
+
id: connections.id,
|
|
236
|
+
version: connections.version,
|
|
237
|
+
status: connections.status,
|
|
238
|
+
metadata: connections.metadata
|
|
239
|
+
}).from(connections).where(
|
|
240
|
+
and(
|
|
241
|
+
eq(connections.workspaceId, input.workspaceId),
|
|
242
|
+
eq(connections.id, operation.connectionId)
|
|
243
|
+
)
|
|
244
|
+
).for("share").limit(1) : [];
|
|
245
|
+
const workspaceGatewayAuthorized = operation.fundingSource === "workspace_gateway" && connection?.status === "active" && connection.version === operation.credentialVersion && connection.metadata.credentialRole === "vercel_ai_gateway";
|
|
246
|
+
const managedAuthorized = operation.fundingSource === "opengeni_credits" && operation.connectionId === null && (operation.creditState === "debited" || operation.creditState === "not_applicable" && operation.pricedCostMicros === 0);
|
|
247
|
+
if (!policy || policy.fundingSource !== operation.fundingSource || !policy.enabledModelIds.includes(operation.modelId) || !workspaceGatewayAuthorized && !managedAuthorized) {
|
|
248
|
+
throw new VideoGenerationConflictError("Video generation authorization changed");
|
|
249
|
+
}
|
|
250
|
+
const now = /* @__PURE__ */ new Date();
|
|
251
|
+
const [updated] = await tx.update(videoGenerationOperations).set({
|
|
252
|
+
status: "accepted",
|
|
253
|
+
admissionOutputState: "recorded",
|
|
254
|
+
terminalUpdateState: "pending",
|
|
255
|
+
nextReconcileAt: now,
|
|
256
|
+
updatedAt: now
|
|
257
|
+
}).where(eq(videoGenerationOperations.id, operation.id)).returning();
|
|
258
|
+
return requireRow(updated, "record video generation acceptance");
|
|
259
|
+
}
|
|
260
|
+
async function cancelVideoGenerationBeforeSubmit(db, input) {
|
|
261
|
+
return await mutateOperation(db, input, async (tx, operation) => {
|
|
262
|
+
if (operation.status === "cancelled_before_submit") return operation;
|
|
263
|
+
if (!inPreSubmitState(operation.status) || operation.providerRequestSentAt) {
|
|
264
|
+
throw new VideoGenerationConflictError(
|
|
265
|
+
"Video generation may already have reached the provider"
|
|
266
|
+
);
|
|
267
|
+
}
|
|
268
|
+
const now = /* @__PURE__ */ new Date();
|
|
269
|
+
await releaseReservedQuota(tx, operation, false);
|
|
270
|
+
const creditState = await refundVideoGenerationCredits(tx, operation, now);
|
|
271
|
+
const [updated] = await tx.update(videoGenerationOperations).set({
|
|
272
|
+
status: "cancelled_before_submit",
|
|
273
|
+
creditState,
|
|
274
|
+
quotaState: "released",
|
|
275
|
+
terminalAt: now,
|
|
276
|
+
terminalUpdateState: operation.admissionOutputState === "recorded" ? "pending" : "suppressed",
|
|
277
|
+
credentialEncrypted: null,
|
|
278
|
+
requestEncrypted: null,
|
|
279
|
+
boundedPublicReason: boundPublicReason(input.reason),
|
|
280
|
+
updatedAt: now
|
|
281
|
+
}).where(eq(videoGenerationOperations.id, operation.id)).returning();
|
|
282
|
+
if (!updated) throw new Error("Video generation cancellation was not recorded");
|
|
283
|
+
return updated;
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
async function cancelUnacceptedVideoGenerationsForToolCallsInTransaction(tx, input) {
|
|
287
|
+
const toolCallIds = [...new Set(input.toolCallIds)];
|
|
288
|
+
if (toolCallIds.length === 0) return [];
|
|
289
|
+
const operations = await tx.select().from(videoGenerationOperations).where(
|
|
290
|
+
and(
|
|
291
|
+
eq(videoGenerationOperations.workspaceId, input.workspaceId),
|
|
292
|
+
eq(videoGenerationOperations.sessionId, input.sessionId),
|
|
293
|
+
eq(videoGenerationOperations.turnId, input.turnId),
|
|
294
|
+
inArray(videoGenerationOperations.toolCallId, toolCallIds),
|
|
295
|
+
eq(videoGenerationOperations.admissionOutputState, "pending"),
|
|
296
|
+
inArray(videoGenerationOperations.status, ["preparing", "prepared"]),
|
|
297
|
+
sql`${videoGenerationOperations.providerRequestSentAt} is null`
|
|
298
|
+
)
|
|
299
|
+
).orderBy(videoGenerationOperations.id).for("update");
|
|
300
|
+
const cancelled = [];
|
|
301
|
+
for (const operation of operations) {
|
|
302
|
+
await releaseReservedQuota(tx, operation, false);
|
|
303
|
+
const creditState = await refundVideoGenerationCredits(tx, operation, input.now);
|
|
304
|
+
const [updated] = await tx.update(videoGenerationOperations).set({
|
|
305
|
+
status: "cancelled_before_submit",
|
|
306
|
+
creditState,
|
|
307
|
+
quotaState: "released",
|
|
308
|
+
terminalAt: input.now,
|
|
309
|
+
terminalUpdateState: "suppressed",
|
|
310
|
+
nextReconcileAt: input.now,
|
|
311
|
+
providerRequestEncrypted: null,
|
|
312
|
+
providerRequestExpiresAt: null,
|
|
313
|
+
credentialEncrypted: null,
|
|
314
|
+
requestEncrypted: null,
|
|
315
|
+
privateDataEraseAfter: input.now,
|
|
316
|
+
boundedPublicReason: boundPublicReason(input.reason),
|
|
317
|
+
reconcileLeaseOwner: null,
|
|
318
|
+
reconcileLeaseExpiresAt: null,
|
|
319
|
+
updatedAt: input.now
|
|
320
|
+
}).where(eq(videoGenerationOperations.id, operation.id)).returning({ id: videoGenerationOperations.id });
|
|
321
|
+
if (!updated) throw new Error("Interrupted video generation was not cancelled");
|
|
322
|
+
await tx.update(videoGenerationReferences).set({ cleanupAfter: input.now }).where(eq(videoGenerationReferences.operationId, operation.id));
|
|
323
|
+
cancelled.push(updated.id);
|
|
324
|
+
}
|
|
325
|
+
return cancelled;
|
|
326
|
+
}
|
|
327
|
+
async function claimVideoGenerationOperations(db, input) {
|
|
328
|
+
const rows = await rawRows(
|
|
329
|
+
db,
|
|
330
|
+
sql`select * from opengeni_private.claim_video_generation_operations(
|
|
331
|
+
${input.owner}, ${input.leaseSeconds}, ${input.limit}
|
|
332
|
+
)`
|
|
333
|
+
);
|
|
334
|
+
return rows.map((row) => ({
|
|
335
|
+
operationId: row.operation_id,
|
|
336
|
+
accountId: row.account_id,
|
|
337
|
+
workspaceId: row.workspace_id
|
|
338
|
+
}));
|
|
339
|
+
}
|
|
340
|
+
async function getVideoGenerationOperation(db, workspaceId, operationId) {
|
|
341
|
+
return await withWorkspaceRls(db, workspaceId, async (scopedDb) => {
|
|
342
|
+
const [operation] = await scopedDb.select().from(videoGenerationOperations).where(
|
|
343
|
+
and(
|
|
344
|
+
eq(videoGenerationOperations.workspaceId, workspaceId),
|
|
345
|
+
eq(videoGenerationOperations.id, operationId)
|
|
346
|
+
)
|
|
347
|
+
).limit(1);
|
|
348
|
+
if (!operation) return null;
|
|
349
|
+
const references = await scopedDb.select().from(videoGenerationReferences).where(eq(videoGenerationReferences.operationId, operationId)).orderBy(videoGenerationReferences.ordinal);
|
|
350
|
+
return { ...operation, references };
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
async function markVideoGenerationSubmissionUncertain(db, input) {
|
|
354
|
+
return await mutateOperation(db, input, async (tx, operation) => {
|
|
355
|
+
if (operation.status !== "submission_uncertain" || !operation.providerRequestEncrypted) {
|
|
356
|
+
throw invalidTransition(operation, "submission_uncertain");
|
|
357
|
+
}
|
|
358
|
+
const now = /* @__PURE__ */ new Date();
|
|
359
|
+
const [updated] = await tx.update(videoGenerationOperations).set({
|
|
360
|
+
status: "submission_uncertain",
|
|
361
|
+
providerRequestSentAt: operation.providerRequestSentAt ?? now,
|
|
362
|
+
nextReconcileAt: input.nextReconcileAt,
|
|
363
|
+
lastError: boundPrivateError(input.error),
|
|
364
|
+
reconcileLeaseOwner: null,
|
|
365
|
+
reconcileLeaseExpiresAt: null,
|
|
366
|
+
updatedAt: now
|
|
367
|
+
}).where(eq(videoGenerationOperations.id, operation.id)).returning();
|
|
368
|
+
return requireRow(updated, "record uncertain video submission");
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
async function markVideoGenerationSubmissionIntent(db, input) {
|
|
372
|
+
return await mutateOperation(db, input, async (tx, operation) => {
|
|
373
|
+
if (operation.status === "submission_uncertain") {
|
|
374
|
+
if (!operation.providerRequestEncrypted || !operation.providerRequestExpiresAt) {
|
|
375
|
+
throw new VideoGenerationConflictError("Video provider request is incomplete");
|
|
376
|
+
}
|
|
377
|
+
return operation;
|
|
378
|
+
}
|
|
379
|
+
if (operation.status !== "accepted") {
|
|
380
|
+
throw invalidTransition(operation, "submission_uncertain");
|
|
381
|
+
}
|
|
382
|
+
const now = /* @__PURE__ */ new Date();
|
|
383
|
+
const [updated] = await tx.update(videoGenerationOperations).set({
|
|
384
|
+
status: "submission_uncertain",
|
|
385
|
+
providerRequestEncrypted: input.encryptedProviderRequest,
|
|
386
|
+
providerRequestExpiresAt: input.providerRequestExpiresAt,
|
|
387
|
+
nextReconcileAt: input.nextReconcileAt,
|
|
388
|
+
lastError: null,
|
|
389
|
+
reconcileLeaseOwner: null,
|
|
390
|
+
reconcileLeaseExpiresAt: null,
|
|
391
|
+
updatedAt: now
|
|
392
|
+
}).where(eq(videoGenerationOperations.id, operation.id)).returning();
|
|
393
|
+
await tx.update(videoGenerationReferences).set({
|
|
394
|
+
grantExpiresAt: input.providerRequestExpiresAt,
|
|
395
|
+
cleanupAfter: new Date(
|
|
396
|
+
Math.max(
|
|
397
|
+
operation.recoveryDeadlineAt.getTime(),
|
|
398
|
+
input.providerRequestExpiresAt.getTime()
|
|
399
|
+
)
|
|
400
|
+
)
|
|
401
|
+
}).where(eq(videoGenerationReferences.operationId, operation.id));
|
|
402
|
+
return requireRow(updated, "record video provider submission intent");
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
async function markVideoGenerationProviderStarted(db, input) {
|
|
406
|
+
return await mutateOperation(db, input, async (tx, operation) => {
|
|
407
|
+
if (operation.providerJobId === input.providerJobId && operation.status === "provider_started") {
|
|
408
|
+
return operation;
|
|
409
|
+
}
|
|
410
|
+
if (!inArrayValue(operation.status, ["accepted", "submission_uncertain"])) {
|
|
411
|
+
throw invalidTransition(operation, "provider_started");
|
|
412
|
+
}
|
|
413
|
+
const now = /* @__PURE__ */ new Date();
|
|
414
|
+
const [updated] = await tx.update(videoGenerationOperations).set({
|
|
415
|
+
status: "provider_started",
|
|
416
|
+
providerJobId: input.providerJobId.slice(0, 1024),
|
|
417
|
+
providerRequestEncrypted: null,
|
|
418
|
+
providerRequestExpiresAt: null,
|
|
419
|
+
providerRequestSentAt: operation.providerRequestSentAt ?? now,
|
|
420
|
+
providerStartedAt: operation.providerStartedAt ?? now,
|
|
421
|
+
nextReconcileAt: input.nextReconcileAt,
|
|
422
|
+
lastError: null,
|
|
423
|
+
reconcileLeaseOwner: null,
|
|
424
|
+
reconcileLeaseExpiresAt: null,
|
|
425
|
+
updatedAt: now
|
|
426
|
+
}).where(eq(videoGenerationOperations.id, operation.id)).returning();
|
|
427
|
+
return requireRow(updated, "record video provider job");
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
async function rescheduleVideoGenerationOperation(db, input) {
|
|
431
|
+
return await withRlsContext(
|
|
432
|
+
db,
|
|
433
|
+
{ accountId: input.accountId, workspaceId: input.workspaceId },
|
|
434
|
+
async (scopedDb) => {
|
|
435
|
+
const [updated] = await scopedDb.update(videoGenerationOperations).set({
|
|
436
|
+
nextReconcileAt: input.nextReconcileAt,
|
|
437
|
+
...input.error ? { lastError: boundPrivateError(input.error) } : {},
|
|
438
|
+
reconcileLeaseOwner: null,
|
|
439
|
+
reconcileLeaseExpiresAt: null,
|
|
440
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
441
|
+
}).where(
|
|
442
|
+
and(
|
|
443
|
+
eq(videoGenerationOperations.workspaceId, input.workspaceId),
|
|
444
|
+
eq(videoGenerationOperations.id, input.operationId),
|
|
445
|
+
eq(videoGenerationOperations.requestDigest, input.requestDigest),
|
|
446
|
+
...input.owner ? [eq(videoGenerationOperations.reconcileLeaseOwner, input.owner)] : []
|
|
447
|
+
)
|
|
448
|
+
).returning({ id: videoGenerationOperations.id });
|
|
449
|
+
return updated !== void 0;
|
|
450
|
+
}
|
|
451
|
+
);
|
|
452
|
+
}
|
|
453
|
+
async function markVideoGenerationRetaining(db, input) {
|
|
454
|
+
return await mutateOperation(db, input, async (tx, operation) => {
|
|
455
|
+
if (operation.status === "retaining") return operation;
|
|
456
|
+
if (operation.status !== "provider_started") throw invalidTransition(operation, "retaining");
|
|
457
|
+
const [updated] = await tx.update(videoGenerationOperations).set({
|
|
458
|
+
status: "retaining",
|
|
459
|
+
nextReconcileAt: /* @__PURE__ */ new Date(),
|
|
460
|
+
reconcileLeaseOwner: null,
|
|
461
|
+
reconcileLeaseExpiresAt: null,
|
|
462
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
463
|
+
}).where(eq(videoGenerationOperations.id, operation.id)).returning();
|
|
464
|
+
return requireRow(updated, "begin video retention");
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
async function settleVideoGenerationFailure(db, input) {
|
|
468
|
+
return await mutateOperation(db, input, async (tx, operation) => {
|
|
469
|
+
if (operation.status === input.status) return operation;
|
|
470
|
+
const allowed = input.status === "provider_failed" ? ["accepted", "submission_uncertain", "provider_started"] : input.status === "retention_failed" ? ["retaining"] : ["submission_uncertain", "provider_started"];
|
|
471
|
+
if (!inArrayValue(operation.status, allowed)) throw invalidTransition(operation, input.status);
|
|
472
|
+
await releaseReservedQuota(tx, operation, false);
|
|
473
|
+
const now = /* @__PURE__ */ new Date();
|
|
474
|
+
const creditState = await refundVideoGenerationCredits(tx, operation, now);
|
|
475
|
+
const [updated] = await tx.update(videoGenerationOperations).set({
|
|
476
|
+
status: input.status,
|
|
477
|
+
creditState,
|
|
478
|
+
quotaState: "released",
|
|
479
|
+
terminalAt: now,
|
|
480
|
+
nextReconcileAt: null,
|
|
481
|
+
terminalUpdateState: operation.admissionOutputState === "recorded" ? "pending" : "suppressed",
|
|
482
|
+
providerRequestEncrypted: null,
|
|
483
|
+
providerRequestExpiresAt: null,
|
|
484
|
+
credentialEncrypted: null,
|
|
485
|
+
requestEncrypted: null,
|
|
486
|
+
boundedPublicReason: boundPublicReason(input.publicReason),
|
|
487
|
+
lastError: input.privateError ? boundPrivateError(input.privateError) : null,
|
|
488
|
+
reconcileLeaseOwner: null,
|
|
489
|
+
reconcileLeaseExpiresAt: null,
|
|
490
|
+
privateDataEraseAfter: now,
|
|
491
|
+
updatedAt: now
|
|
492
|
+
}).where(eq(videoGenerationOperations.id, operation.id)).returning();
|
|
493
|
+
return requireRow(updated, "settle failed video generation");
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
async function settleVideoGenerationReady(db, input) {
|
|
497
|
+
return await withRlsContext(
|
|
498
|
+
db,
|
|
499
|
+
{ accountId: input.accountId, workspaceId: input.workspaceId },
|
|
500
|
+
async (scopedDb) => await scopedDb.transaction(async (tx) => {
|
|
501
|
+
const [operation] = await tx.select().from(videoGenerationOperations).where(
|
|
502
|
+
and(
|
|
503
|
+
eq(videoGenerationOperations.workspaceId, input.workspaceId),
|
|
504
|
+
eq(videoGenerationOperations.id, input.operationId),
|
|
505
|
+
eq(videoGenerationOperations.requestDigest, input.requestDigest)
|
|
506
|
+
)
|
|
507
|
+
).for("update").limit(1);
|
|
508
|
+
if (!operation) throw new VideoGenerationConflictError("Video operation not found");
|
|
509
|
+
const [existingArtifact] = await tx.select().from(generatedVideoArtifacts).where(eq(generatedVideoArtifacts.operationId, operation.id)).limit(1);
|
|
510
|
+
if (operation.status === "completed" && existingArtifact) {
|
|
511
|
+
return { operation, artifact: existingArtifact };
|
|
512
|
+
}
|
|
513
|
+
if (operation.status !== "retaining") throw invalidTransition(operation, "completed");
|
|
514
|
+
if (operation.expectedFileId !== input.fileId) {
|
|
515
|
+
throw new VideoGenerationConflictError("Video File identity changed during settlement");
|
|
516
|
+
}
|
|
517
|
+
if (operation.expectedArtifactId === operation.expectedFileId) {
|
|
518
|
+
throw new Error("Video artifact and File identities must be distinct");
|
|
519
|
+
}
|
|
520
|
+
const now = /* @__PURE__ */ new Date();
|
|
521
|
+
await tx.insert(files).values({
|
|
522
|
+
id: input.fileId,
|
|
523
|
+
accountId: input.accountId,
|
|
524
|
+
workspaceId: input.workspaceId,
|
|
525
|
+
status: "ready",
|
|
526
|
+
filename: `generated-video-${operation.expectedArtifactId}.mp4`,
|
|
527
|
+
safeFilename: `generated-video-${operation.expectedArtifactId}.mp4`,
|
|
528
|
+
contentType: "video/mp4",
|
|
529
|
+
sizeBytes: input.sizeBytes,
|
|
530
|
+
sha256: input.sha256,
|
|
531
|
+
bucket: input.bucket,
|
|
532
|
+
objectKey: input.objectKey,
|
|
533
|
+
updatedAt: now
|
|
534
|
+
});
|
|
535
|
+
const [artifact] = await tx.insert(generatedVideoArtifacts).values({
|
|
536
|
+
id: operation.expectedArtifactId,
|
|
537
|
+
accountId: input.accountId,
|
|
538
|
+
workspaceId: input.workspaceId,
|
|
539
|
+
primaryFileId: input.fileId,
|
|
540
|
+
operationId: operation.id,
|
|
541
|
+
sessionId: operation.sessionId,
|
|
542
|
+
turnId: operation.turnId,
|
|
543
|
+
attemptId: operation.attemptId,
|
|
544
|
+
modelId: operation.modelId,
|
|
545
|
+
sourceMode: operation.sourceMode,
|
|
546
|
+
promptDigest: operation.promptDigest,
|
|
547
|
+
contentType: "video/mp4",
|
|
548
|
+
sizeBytes: input.sizeBytes,
|
|
549
|
+
sha256: input.sha256,
|
|
550
|
+
durationMillis: Math.round(input.facts.durationSeconds * 1e3),
|
|
551
|
+
width: input.facts.width,
|
|
552
|
+
height: input.facts.height,
|
|
553
|
+
fpsMilli: Math.round(input.facts.fps * 1e3),
|
|
554
|
+
videoCodec: input.facts.videoCodec,
|
|
555
|
+
audioCodec: input.facts.audioCodec,
|
|
556
|
+
hasAudio: input.facts.hasAudio,
|
|
557
|
+
sandboxFilename: `generated-video-${operation.expectedArtifactId}.mp4`,
|
|
558
|
+
readyAt: now
|
|
559
|
+
}).returning();
|
|
560
|
+
if (!artifact) throw new Error("Generated video artifact was not persisted");
|
|
561
|
+
await tx.update(workspaceVideoGenerationQuotas).set({
|
|
562
|
+
reservedBytes: sql`${workspaceVideoGenerationQuotas.reservedBytes} - ${operation.reservedBytes}`,
|
|
563
|
+
readyBytes: sql`${workspaceVideoGenerationQuotas.readyBytes} + ${input.sizeBytes}`,
|
|
564
|
+
updatedAt: now
|
|
565
|
+
}).where(eq(workspaceVideoGenerationQuotas.workspaceId, input.workspaceId));
|
|
566
|
+
const [updated] = await tx.update(videoGenerationOperations).set({
|
|
567
|
+
status: "completed",
|
|
568
|
+
quotaState: "ready",
|
|
569
|
+
terminalAt: now,
|
|
570
|
+
nextReconcileAt: null,
|
|
571
|
+
terminalUpdateState: operation.admissionOutputState === "recorded" ? "pending" : "suppressed",
|
|
572
|
+
providerRequestEncrypted: null,
|
|
573
|
+
providerRequestExpiresAt: null,
|
|
574
|
+
credentialEncrypted: null,
|
|
575
|
+
requestEncrypted: null,
|
|
576
|
+
privateDataEraseAfter: now,
|
|
577
|
+
reconcileLeaseOwner: null,
|
|
578
|
+
reconcileLeaseExpiresAt: null,
|
|
579
|
+
updatedAt: now
|
|
580
|
+
}).where(eq(videoGenerationOperations.id, operation.id)).returning();
|
|
581
|
+
return {
|
|
582
|
+
operation: requireRow(updated, "settle ready video generation"),
|
|
583
|
+
artifact
|
|
584
|
+
};
|
|
585
|
+
})
|
|
586
|
+
);
|
|
587
|
+
}
|
|
588
|
+
async function getGeneratedVideoArtifact(db, workspaceId, artifactId) {
|
|
589
|
+
return await withWorkspaceRls(db, workspaceId, async (scopedDb) => {
|
|
590
|
+
const [row] = await scopedDb.select({ artifact: generatedVideoArtifacts, file: files }).from(generatedVideoArtifacts).innerJoin(files, eq(files.id, generatedVideoArtifacts.primaryFileId)).where(
|
|
591
|
+
and(
|
|
592
|
+
eq(generatedVideoArtifacts.workspaceId, workspaceId),
|
|
593
|
+
eq(generatedVideoArtifacts.id, artifactId)
|
|
594
|
+
)
|
|
595
|
+
).limit(1);
|
|
596
|
+
return row ?? null;
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
async function listSessionGeneratedVideoArtifacts(db, workspaceId, sessionId) {
|
|
600
|
+
return await withWorkspaceRls(
|
|
601
|
+
db,
|
|
602
|
+
workspaceId,
|
|
603
|
+
async (scopedDb) => await scopedDb.select({ artifact: generatedVideoArtifacts, file: files }).from(generatedVideoArtifacts).innerJoin(files, eq(files.id, generatedVideoArtifacts.primaryFileId)).where(
|
|
604
|
+
and(
|
|
605
|
+
eq(generatedVideoArtifacts.workspaceId, workspaceId),
|
|
606
|
+
eq(generatedVideoArtifacts.sessionId, sessionId),
|
|
607
|
+
sql`${generatedVideoArtifacts.deletedAt} is null`
|
|
608
|
+
)
|
|
609
|
+
).orderBy(generatedVideoArtifacts.createdAt, generatedVideoArtifacts.id)
|
|
610
|
+
);
|
|
611
|
+
}
|
|
612
|
+
async function markVideoGenerationReferenceCleaned(db, input) {
|
|
613
|
+
return await withRlsContext(
|
|
614
|
+
db,
|
|
615
|
+
{ accountId: input.accountId, workspaceId: input.workspaceId },
|
|
616
|
+
async (scopedDb) => {
|
|
617
|
+
const [updated] = await scopedDb.update(videoGenerationReferences).set({
|
|
618
|
+
stagingObjectKey: null,
|
|
619
|
+
grantExpiresAt: null,
|
|
620
|
+
cleanupAfter: null,
|
|
621
|
+
cleanedAt: /* @__PURE__ */ new Date()
|
|
622
|
+
}).where(
|
|
623
|
+
and(
|
|
624
|
+
eq(videoGenerationReferences.workspaceId, input.workspaceId),
|
|
625
|
+
eq(videoGenerationReferences.operationId, input.operationId),
|
|
626
|
+
eq(videoGenerationReferences.ordinal, input.ordinal),
|
|
627
|
+
eq(videoGenerationReferences.stagingObjectKey, input.stagingObjectKey)
|
|
628
|
+
)
|
|
629
|
+
).returning({ operationId: videoGenerationReferences.operationId });
|
|
630
|
+
if (updated) return true;
|
|
631
|
+
const [existing] = await scopedDb.select({ cleanedAt: videoGenerationReferences.cleanedAt }).from(videoGenerationReferences).where(
|
|
632
|
+
and(
|
|
633
|
+
eq(videoGenerationReferences.workspaceId, input.workspaceId),
|
|
634
|
+
eq(videoGenerationReferences.operationId, input.operationId),
|
|
635
|
+
eq(videoGenerationReferences.ordinal, input.ordinal)
|
|
636
|
+
)
|
|
637
|
+
).limit(1);
|
|
638
|
+
return existing?.cleanedAt !== null && existing?.cleanedAt !== void 0;
|
|
639
|
+
}
|
|
640
|
+
);
|
|
641
|
+
}
|
|
642
|
+
async function markVideoGenerationTerminalUpdate(db, input) {
|
|
643
|
+
return await withRlsContext(
|
|
644
|
+
db,
|
|
645
|
+
{ accountId: input.accountId, workspaceId: input.workspaceId },
|
|
646
|
+
async (scopedDb) => {
|
|
647
|
+
return await markVideoGenerationTerminalUpdateInTransaction(scopedDb, input);
|
|
648
|
+
}
|
|
649
|
+
);
|
|
650
|
+
}
|
|
651
|
+
async function markVideoGenerationTerminalUpdateInTransaction(tx, input) {
|
|
652
|
+
const allowed = input.state === "leased" ? ["pending", "leased"] : input.state === "delivered" ? ["leased"] : ["pending", "leased"];
|
|
653
|
+
const [updated] = await tx.update(videoGenerationOperations).set({
|
|
654
|
+
terminalUpdateState: input.state,
|
|
655
|
+
terminalUpdateId: input.state === "suppressed" ? null : input.updateId ?? null,
|
|
656
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
657
|
+
}).where(
|
|
658
|
+
and(
|
|
659
|
+
eq(videoGenerationOperations.workspaceId, input.workspaceId),
|
|
660
|
+
eq(videoGenerationOperations.id, input.operationId),
|
|
661
|
+
inArray(videoGenerationOperations.terminalUpdateState, allowed),
|
|
662
|
+
...input.state === "delivered" && input.updateId ? [eq(videoGenerationOperations.terminalUpdateId, input.updateId)] : []
|
|
663
|
+
)
|
|
664
|
+
).returning({ id: videoGenerationOperations.id });
|
|
665
|
+
return updated !== void 0;
|
|
666
|
+
}
|
|
667
|
+
function mediaGenerationResultForOperation(input) {
|
|
668
|
+
if (input.operation.status === "completed" && input.readyReceipt) {
|
|
669
|
+
return {
|
|
670
|
+
type: "media_generation_result",
|
|
671
|
+
schemaVersion: 1,
|
|
672
|
+
status: "ready",
|
|
673
|
+
operationId: input.operation.id,
|
|
674
|
+
receipt: input.readyReceipt
|
|
675
|
+
};
|
|
676
|
+
}
|
|
677
|
+
const failureStatus = input.operation.status;
|
|
678
|
+
if (!inArrayValue(failureStatus, [
|
|
679
|
+
"provider_failed",
|
|
680
|
+
"retention_failed",
|
|
681
|
+
"cancelled_before_submit",
|
|
682
|
+
"outcome_unknown"
|
|
683
|
+
])) {
|
|
684
|
+
throw new Error("Video generation operation is not terminal");
|
|
685
|
+
}
|
|
686
|
+
return {
|
|
687
|
+
type: "media_generation_result",
|
|
688
|
+
schemaVersion: 1,
|
|
689
|
+
status: failureStatus,
|
|
690
|
+
operationId: input.operation.id,
|
|
691
|
+
boundedPublicReason: input.operation.boundedPublicReason ?? "Video generation did not complete."
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
async function mediaGenerationResultForStoredOperation(db, operation) {
|
|
695
|
+
if (operation.status !== "completed") {
|
|
696
|
+
return mediaGenerationResultForOperation({ operation });
|
|
697
|
+
}
|
|
698
|
+
const retained = await getGeneratedVideoArtifact(
|
|
699
|
+
db,
|
|
700
|
+
operation.workspaceId,
|
|
701
|
+
operation.expectedArtifactId
|
|
702
|
+
);
|
|
703
|
+
if (!retained || retained.artifact.deletedAt) {
|
|
704
|
+
throw new Error("Completed video generation lost its retained artifact");
|
|
705
|
+
}
|
|
706
|
+
const artifact = retainedGeneratedVideoReferenceFromFile({
|
|
707
|
+
id: retained.artifact.id,
|
|
708
|
+
workspaceId: retained.artifact.workspaceId,
|
|
709
|
+
status: retained.file.status,
|
|
710
|
+
contentType: retained.file.contentType,
|
|
711
|
+
sizeBytes: retained.file.sizeBytes,
|
|
712
|
+
sha256: retained.file.sha256,
|
|
713
|
+
updatedAt: retained.artifact.readyAt.toISOString(),
|
|
714
|
+
width: retained.artifact.width,
|
|
715
|
+
height: retained.artifact.height
|
|
716
|
+
});
|
|
717
|
+
if (!artifact) throw new Error("Generated video receipt could not be constructed");
|
|
718
|
+
const receipt = GeneratedVideoReceipt.parse({
|
|
719
|
+
type: "generated_video",
|
|
720
|
+
schemaVersion: 1,
|
|
721
|
+
operationId: operation.id,
|
|
722
|
+
artifact,
|
|
723
|
+
video: {
|
|
724
|
+
durationSeconds: retained.artifact.durationMillis / 1e3,
|
|
725
|
+
width: retained.artifact.width,
|
|
726
|
+
height: retained.artifact.height,
|
|
727
|
+
fps: retained.artifact.fpsMilli / 1e3,
|
|
728
|
+
hasAudio: retained.artifact.hasAudio,
|
|
729
|
+
videoCodec: retained.artifact.videoCodec,
|
|
730
|
+
audioCodec: retained.artifact.audioCodec
|
|
731
|
+
},
|
|
732
|
+
sandboxPath: `/workspace/generated-videos/${retained.artifact.sandboxFilename}`
|
|
733
|
+
});
|
|
734
|
+
return mediaGenerationResultForOperation({ operation, readyReceipt: receipt });
|
|
735
|
+
}
|
|
736
|
+
async function getVideoGenerationOperationSummary(db, workspaceId, operationId) {
|
|
737
|
+
const operation = await getVideoGenerationOperation(db, workspaceId, operationId);
|
|
738
|
+
if (!operation) return null;
|
|
739
|
+
const terminal = inArrayValue(operation.status, [
|
|
740
|
+
"completed",
|
|
741
|
+
"provider_failed",
|
|
742
|
+
"cancelled_before_submit",
|
|
743
|
+
"outcome_unknown",
|
|
744
|
+
"retention_failed"
|
|
745
|
+
]) ? await mediaGenerationResultForStoredOperation(db, operation) : null;
|
|
746
|
+
return VideoGenerationOperationSummary.parse({
|
|
747
|
+
schemaVersion: 1,
|
|
748
|
+
operationId: operation.id,
|
|
749
|
+
modelId: operation.modelId,
|
|
750
|
+
status: operation.status === "submission_uncertain" ? "accepted" : operation.status,
|
|
751
|
+
createdAt: operation.createdAt.toISOString(),
|
|
752
|
+
updatedAt: operation.updatedAt.toISOString(),
|
|
753
|
+
terminal
|
|
754
|
+
});
|
|
755
|
+
}
|
|
756
|
+
async function mutateOperation(db, input, mutate) {
|
|
757
|
+
return await withRlsContext(
|
|
758
|
+
db,
|
|
759
|
+
{ accountId: input.accountId, workspaceId: input.workspaceId },
|
|
760
|
+
async (scopedDb) => await scopedDb.transaction(async (txRaw) => {
|
|
761
|
+
const tx = txRaw;
|
|
762
|
+
const [operation] = await tx.select().from(videoGenerationOperations).where(
|
|
763
|
+
and(
|
|
764
|
+
eq(videoGenerationOperations.workspaceId, input.workspaceId),
|
|
765
|
+
eq(videoGenerationOperations.id, input.operationId),
|
|
766
|
+
eq(videoGenerationOperations.requestDigest, input.requestDigest)
|
|
767
|
+
)
|
|
768
|
+
).for("update").limit(1);
|
|
769
|
+
if (!operation) throw new VideoGenerationConflictError("Video operation not found");
|
|
770
|
+
return await mutate(tx, operation);
|
|
771
|
+
})
|
|
772
|
+
);
|
|
773
|
+
}
|
|
774
|
+
async function releaseReservedQuota(tx, operation, ready) {
|
|
775
|
+
if (operation.quotaState !== "reserved") return;
|
|
776
|
+
await tx.update(workspaceVideoGenerationQuotas).set({
|
|
777
|
+
reservedBytes: sql`${workspaceVideoGenerationQuotas.reservedBytes} - ${operation.reservedBytes}`,
|
|
778
|
+
...ready ? {
|
|
779
|
+
readyBytes: sql`${workspaceVideoGenerationQuotas.readyBytes} + ${operation.reservedBytes}`
|
|
780
|
+
} : {},
|
|
781
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
782
|
+
}).where(eq(workspaceVideoGenerationQuotas.workspaceId, operation.workspaceId));
|
|
783
|
+
}
|
|
784
|
+
async function debitVideoGenerationCredits(tx, operation) {
|
|
785
|
+
if (operation.pricedCostMicros <= 0 || operation.fundingSource !== "opengeni_credits") {
|
|
786
|
+
throw new Error("Managed video credit debit has an invalid funding binding");
|
|
787
|
+
}
|
|
788
|
+
await tx.execute(sql`select pg_advisory_xact_lock(hashtext(${operation.accountId}))`);
|
|
789
|
+
const [balanceRow] = await tx.select({
|
|
790
|
+
balanceMicros: sql`coalesce(sum(${creditLedgerEntries.amountMicros}), 0)`
|
|
791
|
+
}).from(creditLedgerEntries).where(eq(creditLedgerEntries.accountId, operation.accountId));
|
|
792
|
+
const balanceMicros = Number(balanceRow?.balanceMicros ?? 0);
|
|
793
|
+
if (!Number.isSafeInteger(balanceMicros) || balanceMicros < operation.pricedCostMicros) {
|
|
794
|
+
throw new VideoGenerationCreditError();
|
|
795
|
+
}
|
|
796
|
+
const now = /* @__PURE__ */ new Date();
|
|
797
|
+
const inserted = await tx.insert(creditLedgerEntries).values({
|
|
798
|
+
accountId: operation.accountId,
|
|
799
|
+
workspaceId: operation.workspaceId,
|
|
800
|
+
type: "video_generation_debit",
|
|
801
|
+
amountMicros: -operation.pricedCostMicros,
|
|
802
|
+
sourceType: "video_generation_operation",
|
|
803
|
+
sourceId: operation.id,
|
|
804
|
+
idempotencyKey: `credit:video_generation_debit:${operation.id}`,
|
|
805
|
+
metadata: {
|
|
806
|
+
modelId: operation.modelId,
|
|
807
|
+
sourceMode: operation.sourceMode,
|
|
808
|
+
pricedCostMicros: operation.pricedCostMicros
|
|
809
|
+
},
|
|
810
|
+
occurredAt: now
|
|
811
|
+
}).onConflictDoNothing({ target: creditLedgerEntries.idempotencyKey }).returning({ id: creditLedgerEntries.id });
|
|
812
|
+
if (inserted.length !== 1) {
|
|
813
|
+
throw new VideoGenerationConflictError("Video generation credit debit already exists");
|
|
814
|
+
}
|
|
815
|
+
await tx.insert(usageEvents).values({
|
|
816
|
+
accountId: operation.accountId,
|
|
817
|
+
workspaceId: operation.workspaceId,
|
|
818
|
+
eventType: "video_generation.cost",
|
|
819
|
+
quantity: operation.pricedCostMicros,
|
|
820
|
+
unit: "usd_micros",
|
|
821
|
+
sourceResourceType: "video_generation_operation",
|
|
822
|
+
sourceResourceId: operation.id,
|
|
823
|
+
sessionId: operation.sessionId,
|
|
824
|
+
turnId: operation.turnId,
|
|
825
|
+
turnAttemptId: operation.attemptId,
|
|
826
|
+
idempotencyKey: `usage:video_generation.cost:${operation.id}`,
|
|
827
|
+
occurredAt: now
|
|
828
|
+
}).onConflictDoNothing({ target: usageEvents.idempotencyKey });
|
|
829
|
+
}
|
|
830
|
+
async function refundVideoGenerationCredits(tx, operation, now) {
|
|
831
|
+
if (operation.creditState !== "debited") return operation.creditState;
|
|
832
|
+
if (operation.fundingSource !== "opengeni_credits" || operation.pricedCostMicros <= 0) {
|
|
833
|
+
throw new Error("Video generation credit refund has an invalid funding binding");
|
|
834
|
+
}
|
|
835
|
+
await tx.execute(sql`select pg_advisory_xact_lock(hashtext(${operation.accountId}))`);
|
|
836
|
+
const inserted = await tx.insert(creditLedgerEntries).values({
|
|
837
|
+
accountId: operation.accountId,
|
|
838
|
+
workspaceId: operation.workspaceId,
|
|
839
|
+
type: "video_generation_refund",
|
|
840
|
+
amountMicros: operation.pricedCostMicros,
|
|
841
|
+
sourceType: "video_generation_operation",
|
|
842
|
+
sourceId: operation.id,
|
|
843
|
+
idempotencyKey: `credit:video_generation_refund:${operation.id}`,
|
|
844
|
+
metadata: {
|
|
845
|
+
modelId: operation.modelId,
|
|
846
|
+
sourceMode: operation.sourceMode,
|
|
847
|
+
pricedCostMicros: operation.pricedCostMicros
|
|
848
|
+
},
|
|
849
|
+
occurredAt: now
|
|
850
|
+
}).onConflictDoNothing({ target: creditLedgerEntries.idempotencyKey }).returning({ id: creditLedgerEntries.id });
|
|
851
|
+
if (inserted.length !== 1) {
|
|
852
|
+
throw new VideoGenerationConflictError("Video generation credit refund already exists");
|
|
853
|
+
}
|
|
854
|
+
await tx.insert(usageEvents).values({
|
|
855
|
+
accountId: operation.accountId,
|
|
856
|
+
workspaceId: operation.workspaceId,
|
|
857
|
+
eventType: "video_generation.refund",
|
|
858
|
+
quantity: operation.pricedCostMicros,
|
|
859
|
+
unit: "usd_micros",
|
|
860
|
+
sourceResourceType: "video_generation_operation",
|
|
861
|
+
sourceResourceId: operation.id,
|
|
862
|
+
sessionId: operation.sessionId,
|
|
863
|
+
turnId: operation.turnId,
|
|
864
|
+
turnAttemptId: operation.attemptId,
|
|
865
|
+
idempotencyKey: `usage:video_generation.refund:${operation.id}`,
|
|
866
|
+
occurredAt: now
|
|
867
|
+
}).onConflictDoNothing({ target: usageEvents.idempotencyKey });
|
|
868
|
+
return "refunded";
|
|
869
|
+
}
|
|
870
|
+
function policyFromRow(row) {
|
|
871
|
+
return VideoGenerationPolicy.parse(
|
|
872
|
+
row ? {
|
|
873
|
+
schemaVersion: 1,
|
|
874
|
+
revision: row.revision,
|
|
875
|
+
fundingSource: row.fundingSource,
|
|
876
|
+
enabledModelIds: row.enabledModelIds,
|
|
877
|
+
defaultModelId: row.defaultModelId
|
|
878
|
+
} : {
|
|
879
|
+
schemaVersion: 1,
|
|
880
|
+
revision: 0,
|
|
881
|
+
fundingSource: "workspace_gateway",
|
|
882
|
+
enabledModelIds: [],
|
|
883
|
+
defaultModelId: null
|
|
884
|
+
}
|
|
885
|
+
);
|
|
886
|
+
}
|
|
887
|
+
function assertSupportedModels(modelIds) {
|
|
888
|
+
for (const modelId of modelIds) {
|
|
889
|
+
if (modelId !== SEEDANCE_2_5_MODEL_ID) {
|
|
890
|
+
throw new Error(`Unknown video generation model: ${modelId}`);
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
function assertAdmissionMatches(operation, input) {
|
|
895
|
+
if (operation.requestDigest !== input.requestDigest || operation.toolCallId !== input.toolCallId || operation.sessionId !== input.sessionId || operation.turnId !== input.turnId || operation.fundingSource !== input.fundingSource || operation.pricedCostMicros !== input.pricedCostMicros) {
|
|
896
|
+
throw new VideoGenerationConflictError(
|
|
897
|
+
"Video generation admission key was reused with different arguments"
|
|
898
|
+
);
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
function inPreSubmitState(status) {
|
|
902
|
+
return inArrayValue(status, ["preparing", "prepared", "accepted"]);
|
|
903
|
+
}
|
|
904
|
+
function inArrayValue(value, candidates) {
|
|
905
|
+
return candidates.includes(value);
|
|
906
|
+
}
|
|
907
|
+
function invalidTransition(operation, target) {
|
|
908
|
+
return new VideoGenerationConflictError(
|
|
909
|
+
`Invalid video generation transition ${operation.status} -> ${target}`
|
|
910
|
+
);
|
|
911
|
+
}
|
|
912
|
+
function requireRow(value, action) {
|
|
913
|
+
if (!value) throw new Error(`Failed to ${action}`);
|
|
914
|
+
return value;
|
|
915
|
+
}
|
|
916
|
+
function boundPublicReason(value) {
|
|
917
|
+
const normalized = value.replace(/\s+/gu, " ").trim();
|
|
918
|
+
return (normalized || "Video generation did not complete.").slice(0, 1e3);
|
|
919
|
+
}
|
|
920
|
+
function boundPrivateError(value) {
|
|
921
|
+
return value.replace(/\s+/gu, " ").trim().slice(0, 4096);
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
export {
|
|
925
|
+
ACTIVE_VIDEO_GENERATION_STATUSES,
|
|
926
|
+
VideoGenerationConflictError,
|
|
927
|
+
VideoGenerationCapacityError,
|
|
928
|
+
VideoGenerationCreditError,
|
|
929
|
+
getWorkspaceVideoGenerationPolicy,
|
|
930
|
+
updateWorkspaceVideoGenerationPolicy,
|
|
931
|
+
admitVideoGenerationOperation,
|
|
932
|
+
markVideoGenerationPrepared,
|
|
933
|
+
markVideoGenerationAccepted,
|
|
934
|
+
markVideoGenerationAcceptedInTransaction,
|
|
935
|
+
cancelVideoGenerationBeforeSubmit,
|
|
936
|
+
cancelUnacceptedVideoGenerationsForToolCallsInTransaction,
|
|
937
|
+
claimVideoGenerationOperations,
|
|
938
|
+
getVideoGenerationOperation,
|
|
939
|
+
markVideoGenerationSubmissionUncertain,
|
|
940
|
+
markVideoGenerationSubmissionIntent,
|
|
941
|
+
markVideoGenerationProviderStarted,
|
|
942
|
+
rescheduleVideoGenerationOperation,
|
|
943
|
+
markVideoGenerationRetaining,
|
|
944
|
+
settleVideoGenerationFailure,
|
|
945
|
+
settleVideoGenerationReady,
|
|
946
|
+
getGeneratedVideoArtifact,
|
|
947
|
+
listSessionGeneratedVideoArtifacts,
|
|
948
|
+
markVideoGenerationReferenceCleaned,
|
|
949
|
+
markVideoGenerationTerminalUpdate,
|
|
950
|
+
markVideoGenerationTerminalUpdateInTransaction,
|
|
951
|
+
mediaGenerationResultForOperation,
|
|
952
|
+
mediaGenerationResultForStoredOperation,
|
|
953
|
+
getVideoGenerationOperationSummary
|
|
954
|
+
};
|
|
955
|
+
//# sourceMappingURL=chunk-NBE6CHRI.js.map
|