@opengeni/db 1.0.2 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/artifact-catalog.d.ts +12 -0
- package/dist/canonical-human-identities.js +3 -3
- package/dist/capability-reconciliation.js +2 -2
- package/dist/{chunk-KH3TYDGY.js → chunk-3GAR5UN3.js} +2 -2
- package/dist/{chunk-UEQQ2WWU.js → chunk-3TGYFFZR.js} +3 -26
- package/dist/chunk-3TGYFFZR.js.map +1 -0
- package/dist/{chunk-F3YMVRF4.js → chunk-6EIEGHPK.js} +4 -4
- package/dist/{chunk-OQZOGCLG.js → chunk-CONWNUSL.js} +2 -2
- package/dist/{chunk-7S53WLPI.js → chunk-CYP72JTQ.js} +11 -4
- package/dist/{chunk-7S53WLPI.js.map → chunk-CYP72JTQ.js.map} +1 -1
- package/dist/{chunk-LDTQGYD2.js → chunk-FWQNHNOU.js} +54 -2
- package/dist/chunk-FWQNHNOU.js.map +1 -0
- package/dist/{chunk-KEDWSSNP.js → chunk-GDN5TSZP.js} +2 -2
- package/dist/{chunk-PQGTWFRF.js → chunk-JICUP7ZR.js} +2 -2
- package/dist/{chunk-NLSG7GGA.js → chunk-JLVWBIEM.js} +3 -3
- package/dist/{chunk-Y77PVZZD.js → chunk-LXPFNG4L.js} +2 -2
- package/dist/{chunk-56MYWKQV.js → chunk-O2Y5E5M3.js} +68 -32
- package/dist/chunk-O2Y5E5M3.js.map +1 -0
- package/dist/{chunk-7POTLB24.js → chunk-QFJNEXFL.js} +2 -2
- package/dist/{chunk-MACELCXG.js → chunk-UCIMHNII.js} +101 -21
- package/dist/chunk-UCIMHNII.js.map +1 -0
- package/dist/{chunk-OMHBVHX7.js → chunk-VDPCIFKL.js} +5 -5
- package/dist/{chunk-N5QCKHYL.js → chunk-YOYILDLY.js} +87 -19
- package/dist/chunk-YOYILDLY.js.map +1 -0
- package/dist/connect-attempts.js +3 -3
- package/dist/credit-balances.d.ts +18 -0
- package/dist/credit-promotion-policy.d.ts +10 -0
- package/dist/editable-artifact-durable-export.js +2 -2
- package/dist/editable-artifacts.js +3 -3
- package/dist/index.d.ts +35 -10
- package/dist/index.js +2432 -2255
- package/dist/index.js.map +1 -1
- package/dist/managed-auth-session-sets.js +3 -3
- package/dist/managed-user-setup.d.ts +1 -0
- package/dist/mcp-operations.js +2 -2
- package/dist/organization-integration-policy.js +3 -3
- package/dist/organization-membership-lifecycle.d.ts +1 -0
- package/dist/persistence-errors.d.ts +9 -6
- package/dist/provision-roles.js +1 -1
- package/dist/retained-provider-commands.js +6 -6
- package/dist/runtime-posture.d.ts +7 -6
- package/dist/schema.d.ts +214 -2
- package/dist/schema.js +5 -1
- package/dist/session-background-commands.js +4 -4
- package/dist/session-command-output.js +5 -5
- package/dist/session-event-slices.js +3 -3
- package/dist/session-mcp-credential-rotation.js +5 -5
- package/dist/session-tenancy.d.ts +6 -1
- package/dist/session-tenancy.js +3 -5
- package/dist/video-generation.js +3 -3
- package/dist/workspace-tool-defaults.js +4 -4
- package/drizzle/0610_artifact_catalog_pins.sql +165 -0
- package/drizzle/0611_universal_session_tenancy_activation.sql +166 -0
- package/drizzle/0612_scheduled_model_unavailable_refusal.sql +21 -0
- package/drizzle/0613_model_scoped_promotional_credits.sql +238 -0
- package/drizzle/0614_quiescence_command_containment.sql +7 -0
- package/drizzle/0615_credit_promotion_policy_validation.sql +63 -0
- package/package.json +7 -7
- package/src/artifact-catalog.ts +31 -5
- package/src/credit-balances.ts +109 -0
- package/src/credit-promotion-policy.ts +12 -0
- package/src/database.ts +81 -42
- package/src/index.ts +295 -79
- package/src/managed-user-setup.ts +8 -0
- package/src/organization-membership-lifecycle.ts +8 -0
- package/src/persistence-errors.ts +17 -6
- package/src/provision-roles.ts +25 -0
- package/src/runtime-posture-cli.ts +0 -2
- package/src/runtime-posture.ts +86 -27
- package/src/schema.ts +57 -1
- package/src/session-tenancy.ts +9 -31
- package/src/video-generation.ts +2 -7
- package/dist/chunk-56MYWKQV.js.map +0 -1
- package/dist/chunk-LDTQGYD2.js.map +0 -1
- package/dist/chunk-MACELCXG.js.map +0 -1
- package/dist/chunk-N5QCKHYL.js.map +0 -1
- package/dist/chunk-UEQQ2WWU.js.map +0 -1
- /package/dist/{chunk-KH3TYDGY.js.map → chunk-3GAR5UN3.js.map} +0 -0
- /package/dist/{chunk-F3YMVRF4.js.map → chunk-6EIEGHPK.js.map} +0 -0
- /package/dist/{chunk-OQZOGCLG.js.map → chunk-CONWNUSL.js.map} +0 -0
- /package/dist/{chunk-KEDWSSNP.js.map → chunk-GDN5TSZP.js.map} +0 -0
- /package/dist/{chunk-PQGTWFRF.js.map → chunk-JICUP7ZR.js.map} +0 -0
- /package/dist/{chunk-NLSG7GGA.js.map → chunk-JLVWBIEM.js.map} +0 -0
- /package/dist/{chunk-Y77PVZZD.js.map → chunk-LXPFNG4L.js.map} +0 -0
- /package/dist/{chunk-7POTLB24.js.map → chunk-QFJNEXFL.js.map} +0 -0
- /package/dist/{chunk-OMHBVHX7.js.map → chunk-VDPCIFKL.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/video-generation.ts","../src/usage-allowances.ts","../src/credit-debit-attribution.ts","../src/credit-balances.ts"],"sourcesContent":["import {\n GENERATED_VIDEO_MAX_BYTES,\n GeneratedVideoReceipt,\n GROK_IMAGINE_VIDEO_1_5_MODEL_ID,\n SEEDANCE_2_5_MODEL_ID,\n VideoGenerationPolicy,\n VideoGenerationOperationSummary,\n retainedGeneratedVideoReferenceFromFile,\n type GeneratedVideoFacts,\n type MediaGenerationResult,\n type VideoGenerationFundingSource,\n type VideoGenerationPolicy as VideoGenerationPolicyValue,\n} from \"@opengeni/contracts\";\nimport { and, eq, inArray, sql } from \"drizzle-orm\";\nimport type { Database } from \"./database\";\nimport { rawRows, withRlsContext, withWorkspaceRls } from \"./database\";\nimport * as schema from \"./schema\";\nimport { checkWorkspaceAllowance } from \"./usage-allowances\";\nimport { creditDebitAttributionForTurn } from \"./credit-debit-attribution\";\nimport { getSpendableCreditBalance } from \"./credit-balances\";\n\nexport const ACTIVE_VIDEO_GENERATION_STATUSES = [\n \"preparing\",\n \"prepared\",\n \"accepted\",\n \"submission_uncertain\",\n \"provider_started\",\n \"retaining\",\n] as const;\n\nexport type VideoGenerationOperation = typeof schema.videoGenerationOperations.$inferSelect;\nexport type VideoGenerationReference = typeof schema.videoGenerationReferences.$inferSelect;\nexport type GeneratedVideoArtifact = typeof schema.generatedVideoArtifacts.$inferSelect;\n\nexport type VideoGenerationOperationWithReferences = VideoGenerationOperation & {\n references: VideoGenerationReference[];\n};\n\nexport class VideoGenerationConflictError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"VideoGenerationConflictError\";\n }\n}\n\nexport class VideoGenerationCapacityError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"VideoGenerationCapacityError\";\n }\n}\n\nexport class VideoGenerationCreditError extends Error {\n constructor(message = \"insufficient Opengeni credits\") {\n super(message);\n this.name = \"VideoGenerationCreditError\";\n }\n}\n\nexport async function getWorkspaceVideoGenerationPolicy(\n db: Database,\n workspaceId: string,\n): Promise<VideoGenerationPolicyValue> {\n return await withWorkspaceRls(db, workspaceId, async (scopedDb) => {\n const [row] = await scopedDb\n .select()\n .from(schema.workspaceVideoGenerationPolicies)\n .where(eq(schema.workspaceVideoGenerationPolicies.workspaceId, workspaceId))\n .limit(1);\n return policyFromRow(row);\n });\n}\n\nexport async function updateWorkspaceVideoGenerationPolicy(\n db: Database,\n input: {\n accountId: string;\n workspaceId: string;\n subjectId: string;\n expectedRevision: number;\n fundingSource: VideoGenerationFundingSource;\n enabledModelIds: string[];\n defaultModelId: string | null;\n },\n): Promise<VideoGenerationPolicyValue> {\n const requested = VideoGenerationPolicy.parse({\n schemaVersion: 1,\n revision: input.expectedRevision + 1,\n fundingSource: input.fundingSource,\n enabledModelIds: input.enabledModelIds,\n defaultModelId: input.defaultModelId,\n });\n assertSupportedModels(requested.enabledModelIds);\n return await withRlsContext(\n db,\n { accountId: input.accountId, workspaceId: input.workspaceId },\n async (scopedDb) =>\n await scopedDb.transaction(async (tx) => {\n const [workspace] = await tx\n .select({ id: schema.workspaces.id })\n .from(schema.workspaces)\n .where(\n and(\n eq(schema.workspaces.id, input.workspaceId),\n eq(schema.workspaces.accountId, input.accountId),\n ),\n )\n .for(\"update\")\n .limit(1);\n if (!workspace) throw new Error(\"Workspace not found\");\n const [current] = await tx\n .select()\n .from(schema.workspaceVideoGenerationPolicies)\n .where(eq(schema.workspaceVideoGenerationPolicies.workspaceId, input.workspaceId))\n .for(\"update\")\n .limit(1);\n const currentRevision = current?.revision ?? 0;\n if (currentRevision !== input.expectedRevision) {\n throw new VideoGenerationConflictError(\"Video generation policy changed\");\n }\n const now = new Date();\n const values = {\n workspaceId: input.workspaceId,\n accountId: input.accountId,\n revision: currentRevision + 1,\n fundingSource: requested.fundingSource,\n enabledModelIds: [...requested.enabledModelIds],\n defaultModelId: requested.defaultModelId,\n updatedBySubjectId: input.subjectId.slice(0, 1_024),\n updatedAt: now,\n };\n const [row] = current\n ? await tx\n .update(schema.workspaceVideoGenerationPolicies)\n .set(values)\n .where(eq(schema.workspaceVideoGenerationPolicies.workspaceId, input.workspaceId))\n .returning()\n : await tx.insert(schema.workspaceVideoGenerationPolicies).values(values).returning();\n if (!row) throw new Error(\"Video generation policy update was not persisted\");\n return policyFromRow(row);\n }),\n );\n}\n\nexport type AdmitVideoGenerationOperationInput = {\n id: string;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n toolCallId: string;\n admissionKey: string;\n requestDigest: string;\n promptDigest: string;\n requestEncrypted: string;\n modelId: string;\n sourceMode: string;\n capabilityRevision: string;\n policyRevision: number;\n fundingSource: VideoGenerationFundingSource;\n pricedCostMicros: number;\n connectionId: string | null;\n credentialVersion: number;\n credentialEncrypted: string;\n providerIdempotencyKey: string;\n expectedArtifactId: string;\n expectedFileId: string;\n reservedBytes?: number;\n workspaceQuotaBytes: number;\n maxConcurrentPerWorkspace: number;\n recoveryDeadlineAt: Date;\n references: Array<{\n ordinal: number;\n role: string;\n contentType: string;\n sizeBytes: number;\n sha256: string;\n stagingObjectKey: string;\n grantExpiresAt?: Date | null;\n cleanupAfter: Date;\n }>;\n};\n\nexport async function admitVideoGenerationOperation(\n db: Database,\n input: AdmitVideoGenerationOperationInput,\n): Promise<{ operation: VideoGenerationOperation; created: boolean }> {\n const reservedBytes = input.reservedBytes ?? GENERATED_VIDEO_MAX_BYTES;\n return await withRlsContext(\n db,\n { accountId: input.accountId, workspaceId: input.workspaceId },\n async (scopedDb) =>\n await scopedDb.transaction(async (tx) => {\n await tx.execute(\n sql`select pg_advisory_xact_lock(hashtextextended(${`video-generation:${input.admissionKey}`}, 0))`,\n );\n const [existing] = await tx\n .select()\n .from(schema.videoGenerationOperations)\n .where(\n and(\n eq(schema.videoGenerationOperations.workspaceId, input.workspaceId),\n eq(schema.videoGenerationOperations.admissionKey, input.admissionKey),\n ),\n )\n .limit(1);\n if (existing) {\n assertAdmissionMatches(existing, input);\n return { operation: existing, created: false };\n }\n const [policy] = await tx\n .select()\n .from(schema.workspaceVideoGenerationPolicies)\n .where(eq(schema.workspaceVideoGenerationPolicies.workspaceId, input.workspaceId))\n .for(\"update\")\n .limit(1);\n if (\n !policy ||\n policy.revision !== input.policyRevision ||\n policy.fundingSource !== input.fundingSource ||\n !policy.enabledModelIds.includes(input.modelId)\n ) {\n throw new VideoGenerationConflictError(\"Video generation capability changed\");\n }\n const active = await tx\n .select({ id: schema.videoGenerationOperations.id })\n .from(schema.videoGenerationOperations)\n .where(\n and(\n eq(schema.videoGenerationOperations.workspaceId, input.workspaceId),\n inArray(schema.videoGenerationOperations.status, [\n ...ACTIVE_VIDEO_GENERATION_STATUSES,\n ]),\n ),\n )\n .for(\"update\");\n if (active.length >= input.maxConcurrentPerWorkspace) {\n throw new VideoGenerationCapacityError(\"Workspace video generation limit reached\");\n }\n await tx\n .insert(schema.workspaceVideoGenerationQuotas)\n .values({\n workspaceId: input.workspaceId,\n accountId: input.accountId,\n })\n .onConflictDoNothing({\n target: schema.workspaceVideoGenerationQuotas.workspaceId,\n });\n const [quota] = await tx\n .select()\n .from(schema.workspaceVideoGenerationQuotas)\n .where(eq(schema.workspaceVideoGenerationQuotas.workspaceId, input.workspaceId))\n .for(\"update\")\n .limit(1);\n if (!quota) throw new Error(\"Video generation quota row disappeared\");\n if (quota.reservedBytes + quota.readyBytes + reservedBytes > input.workspaceQuotaBytes) {\n throw new VideoGenerationCapacityError(\"Workspace video storage quota reached\");\n }\n const [operation] = await tx\n .insert(schema.videoGenerationOperations)\n .values({\n id: input.id,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n attemptId: input.attemptId,\n toolCallId: input.toolCallId,\n admissionKey: input.admissionKey,\n requestDigest: input.requestDigest,\n promptDigest: input.promptDigest,\n requestEncrypted: input.requestEncrypted,\n modelId: input.modelId,\n sourceMode: input.sourceMode,\n capabilityRevision: input.capabilityRevision,\n fundingSource: input.fundingSource,\n pricedCostMicros: input.pricedCostMicros,\n creditState: input.pricedCostMicros > 0 ? \"debited\" : \"not_applicable\",\n connectionId: input.connectionId,\n credentialVersion: input.credentialVersion,\n credentialEncrypted: input.credentialEncrypted,\n providerIdempotencyKey: input.providerIdempotencyKey,\n expectedArtifactId: input.expectedArtifactId,\n expectedFileId: input.expectedFileId,\n reservedBytes,\n recoveryDeadlineAt: input.recoveryDeadlineAt,\n status: input.references.length === 0 ? \"prepared\" : \"preparing\",\n admissionOutputState: \"pending\",\n terminalUpdateState: \"ineligible\",\n })\n .returning();\n if (!operation) throw new Error(\"Video generation operation was not admitted\");\n if (input.pricedCostMicros > 0) {\n if (input.fundingSource !== \"opengeni_credits\" || input.connectionId !== null) {\n throw new Error(\"Only Opengeni-funded video operations may debit credits\");\n }\n await debitVideoGenerationCredits(tx, operation);\n }\n if (input.references.length > 0) {\n await tx.insert(schema.videoGenerationReferences).values(\n input.references.map((reference) => ({\n operationId: operation.id,\n workspaceId: input.workspaceId,\n accountId: input.accountId,\n grantExpiresAt: reference.grantExpiresAt ?? null,\n ...reference,\n })),\n );\n }\n await tx\n .update(schema.workspaceVideoGenerationQuotas)\n .set({\n reservedBytes: sql`${schema.workspaceVideoGenerationQuotas.reservedBytes} + ${reservedBytes}`,\n updatedAt: new Date(),\n })\n .where(eq(schema.workspaceVideoGenerationQuotas.workspaceId, input.workspaceId));\n return { operation, created: true };\n }),\n );\n}\n\n/** Persist a rotated provider token before it is used for another remote call. */\nexport async function rotateVideoGenerationCredential(\n db: Database,\n input: {\n accountId: string;\n workspaceId: string;\n operationId: string;\n requestDigest: string;\n expectedCredentialEncrypted: string;\n credentialEncrypted: string;\n },\n): Promise<VideoGenerationOperation> {\n const [row] = await db\n .update(schema.videoGenerationOperations)\n .set({\n credentialEncrypted: input.credentialEncrypted,\n updatedAt: new Date(),\n })\n .where(\n and(\n eq(schema.videoGenerationOperations.accountId, input.accountId),\n eq(schema.videoGenerationOperations.workspaceId, input.workspaceId),\n eq(schema.videoGenerationOperations.id, input.operationId),\n eq(schema.videoGenerationOperations.requestDigest, input.requestDigest),\n eq(schema.videoGenerationOperations.credentialEncrypted, input.expectedCredentialEncrypted),\n inArray(schema.videoGenerationOperations.status, [\n \"accepted\",\n \"submission_uncertain\",\n \"provider_started\",\n \"retaining\",\n ]),\n ),\n )\n .returning();\n if (!row) throw new VideoGenerationConflictError(\"Video provider credential changed\");\n return row;\n}\n\n/**\n * Seal a reference-bearing operation only after every immutable staging object\n * has been uploaded and independently verified by the worker. The source\n * sandbox path is intentionally not stored, so a failed preparation can only\n * be retried by the same logical tool call while its sandbox still exists.\n */\nexport async function markVideoGenerationPrepared(\n db: Database,\n input: OperationMutationInput,\n): Promise<VideoGenerationOperation> {\n return await mutateOperation(db, input, async (tx, operation) => {\n if (operation.status === \"prepared\") return operation;\n if (operation.status !== \"preparing\") throw invalidTransition(operation, \"prepared\");\n const references = await tx\n .select({\n stagingObjectKey: schema.videoGenerationReferences.stagingObjectKey,\n cleanedAt: schema.videoGenerationReferences.cleanedAt,\n })\n .from(schema.videoGenerationReferences)\n .where(eq(schema.videoGenerationReferences.operationId, operation.id));\n if (\n references.length === 0 ||\n references.some((reference) => !reference.stagingObjectKey || reference.cleanedAt)\n ) {\n throw new VideoGenerationConflictError(\"Video references are not sealed\");\n }\n const [updated] = await tx\n .update(schema.videoGenerationOperations)\n .set({ status: \"prepared\", updatedAt: new Date() })\n .where(eq(schema.videoGenerationOperations.id, operation.id))\n .returning();\n return requireRow(updated, \"seal video generation references\");\n });\n}\n\n/** Final authorization fence. Call only after the accepted function output is durable. */\nexport async function markVideoGenerationAccepted(\n db: Database,\n input: {\n accountId: string;\n workspaceId: string;\n operationId: string;\n requestDigest: string;\n },\n): Promise<VideoGenerationOperation> {\n return await mutateOperation(\n db,\n input,\n async (tx, operation) =>\n await markVideoGenerationAcceptedInTransaction(tx, {\n workspaceId: input.workspaceId,\n operation,\n }),\n );\n}\n\n/**\n * Transactional half of acceptance. The pending function result and this\n * transition must commit together: the provider reconciler never observes an\n * accepted operation whose model-visible `accepted` receipt was lost.\n */\nexport async function markVideoGenerationAcceptedInTransaction(\n tx: Database,\n input: {\n workspaceId: string;\n operation: VideoGenerationOperation;\n toolCallId?: string;\n },\n): Promise<VideoGenerationOperation> {\n const operation = input.operation;\n if (input.toolCallId !== undefined && operation.toolCallId !== input.toolCallId) {\n throw new VideoGenerationConflictError(\"Video generation tool-call identity changed\");\n }\n if (operation.admissionOutputState === \"recorded\") return operation;\n if (operation.status !== \"prepared\") {\n throw new VideoGenerationConflictError(\"Video generation is no longer awaiting acceptance\");\n }\n const [policy] = await tx\n .select()\n .from(schema.workspaceVideoGenerationPolicies)\n .where(eq(schema.workspaceVideoGenerationPolicies.workspaceId, input.workspaceId))\n .for(\"share\")\n .limit(1);\n const [connection] = operation.connectionId\n ? await tx\n .select({\n id: schema.connections.id,\n version: schema.connections.version,\n status: schema.connections.status,\n metadata: schema.connections.metadata,\n })\n .from(schema.connections)\n .where(\n and(\n eq(schema.connections.workspaceId, input.workspaceId),\n eq(schema.connections.id, operation.connectionId),\n ),\n )\n .for(\"share\")\n .limit(1)\n : [];\n const workspaceGatewayAuthorized =\n operation.fundingSource === \"workspace_gateway\" &&\n connection?.status === \"active\" &&\n connection.version === operation.credentialVersion &&\n connection.metadata.credentialRole === \"vercel_ai_gateway\";\n const managedAuthorized =\n operation.fundingSource === \"opengeni_credits\" &&\n operation.connectionId === null &&\n (operation.creditState === \"debited\" ||\n (operation.creditState === \"not_applicable\" && operation.pricedCostMicros === 0));\n const supergrokAuthorized =\n operation.fundingSource === \"supergrok_subscription\" &&\n operation.connectionId === null &&\n operation.credentialEncrypted !== null &&\n operation.pricedCostMicros === 0 &&\n operation.creditState === \"not_applicable\";\n if (\n !policy ||\n policy.fundingSource !== operation.fundingSource ||\n !policy.enabledModelIds.includes(operation.modelId) ||\n (!workspaceGatewayAuthorized && !managedAuthorized && !supergrokAuthorized)\n ) {\n throw new VideoGenerationConflictError(\"Video generation authorization changed\");\n }\n const now = new Date();\n const [updated] = await tx\n .update(schema.videoGenerationOperations)\n .set({\n status: \"accepted\",\n admissionOutputState: \"recorded\",\n terminalUpdateState: \"pending\",\n nextReconcileAt: now,\n updatedAt: now,\n })\n .where(eq(schema.videoGenerationOperations.id, operation.id))\n .returning();\n return requireRow(updated, \"record video generation acceptance\");\n}\n\nexport async function cancelVideoGenerationBeforeSubmit(\n db: Database,\n input: {\n accountId: string;\n workspaceId: string;\n operationId: string;\n requestDigest: string;\n reason: string;\n },\n): Promise<VideoGenerationOperation> {\n return await mutateOperation(db, input, async (tx, operation) => {\n if (operation.status === \"cancelled_before_submit\") return operation;\n if (!inPreSubmitState(operation.status) || operation.providerRequestSentAt) {\n throw new VideoGenerationConflictError(\n \"Video generation may already have reached the provider\",\n );\n }\n const now = new Date();\n await releaseReservedQuota(tx, operation, false);\n const creditState = await refundVideoGenerationCredits(tx, operation, now);\n const [updated] = await tx\n .update(schema.videoGenerationOperations)\n .set({\n status: \"cancelled_before_submit\",\n creditState,\n quotaState: \"released\",\n terminalAt: now,\n terminalUpdateState:\n operation.admissionOutputState === \"recorded\" ? \"pending\" : \"suppressed\",\n credentialEncrypted: null,\n requestEncrypted: null,\n boundedPublicReason: boundPublicReason(input.reason),\n updatedAt: now,\n })\n .where(eq(schema.videoGenerationOperations.id, operation.id))\n .returning();\n if (!updated) throw new Error(\"Video generation cancellation was not recorded\");\n return updated;\n });\n}\n\n/**\n * Turn-interruption half of pre-submit cancellation. It runs under the same\n * session/turn transaction that closes unresolved tool calls, so an accepted\n * receipt can never race a cancellation of its operation.\n */\nexport async function cancelUnacceptedVideoGenerationsForToolCallsInTransaction(\n tx: Database,\n input: {\n workspaceId: string;\n sessionId: string;\n turnId: string;\n toolCallIds: readonly string[];\n reason: string;\n now: Date;\n },\n): Promise<string[]> {\n const toolCallIds = [...new Set(input.toolCallIds)];\n if (toolCallIds.length === 0) return [];\n const operations = await tx\n .select()\n .from(schema.videoGenerationOperations)\n .where(\n and(\n eq(schema.videoGenerationOperations.workspaceId, input.workspaceId),\n eq(schema.videoGenerationOperations.sessionId, input.sessionId),\n eq(schema.videoGenerationOperations.turnId, input.turnId),\n inArray(schema.videoGenerationOperations.toolCallId, toolCallIds),\n eq(schema.videoGenerationOperations.admissionOutputState, \"pending\"),\n inArray(schema.videoGenerationOperations.status, [\"preparing\", \"prepared\"]),\n sql`${schema.videoGenerationOperations.providerRequestSentAt} is null`,\n ),\n )\n .orderBy(schema.videoGenerationOperations.id)\n .for(\"update\");\n const cancelled: string[] = [];\n for (const operation of operations) {\n await releaseReservedQuota(tx, operation, false);\n const creditState = await refundVideoGenerationCredits(tx, operation, input.now);\n const [updated] = await tx\n .update(schema.videoGenerationOperations)\n .set({\n status: \"cancelled_before_submit\",\n creditState,\n quotaState: \"released\",\n terminalAt: input.now,\n terminalUpdateState: \"suppressed\",\n nextReconcileAt: input.now,\n providerRequestEncrypted: null,\n providerRequestExpiresAt: null,\n credentialEncrypted: null,\n requestEncrypted: null,\n privateDataEraseAfter: input.now,\n boundedPublicReason: boundPublicReason(input.reason),\n reconcileLeaseOwner: null,\n reconcileLeaseExpiresAt: null,\n updatedAt: input.now,\n })\n .where(eq(schema.videoGenerationOperations.id, operation.id))\n .returning({ id: schema.videoGenerationOperations.id });\n if (!updated) throw new Error(\"Interrupted video generation was not cancelled\");\n await tx\n .update(schema.videoGenerationReferences)\n .set({ cleanupAfter: input.now })\n .where(eq(schema.videoGenerationReferences.operationId, operation.id));\n cancelled.push(updated.id);\n }\n return cancelled;\n}\n\nexport async function claimVideoGenerationOperations(\n db: Database,\n input: { owner: string; leaseSeconds: number; limit: number },\n): Promise<Array<{ operationId: string; accountId: string; workspaceId: string }>> {\n const rows = await rawRows<{\n operation_id: string;\n account_id: string;\n workspace_id: string;\n }>(\n db,\n sql`select * from opengeni_private.claim_video_generation_operations(\n ${input.owner}, ${input.leaseSeconds}, ${input.limit}\n )`,\n );\n return rows.map((row) => ({\n operationId: row.operation_id,\n accountId: row.account_id,\n workspaceId: row.workspace_id,\n }));\n}\n\nexport async function getVideoGenerationOperation(\n db: Database,\n workspaceId: string,\n operationId: string,\n): Promise<VideoGenerationOperationWithReferences | null> {\n return await withWorkspaceRls(db, workspaceId, async (scopedDb) => {\n const [operation] = await scopedDb\n .select()\n .from(schema.videoGenerationOperations)\n .where(\n and(\n eq(schema.videoGenerationOperations.workspaceId, workspaceId),\n eq(schema.videoGenerationOperations.id, operationId),\n ),\n )\n .limit(1);\n if (!operation) return null;\n const references = await scopedDb\n .select()\n .from(schema.videoGenerationReferences)\n .where(eq(schema.videoGenerationReferences.operationId, operationId))\n .orderBy(schema.videoGenerationReferences.ordinal);\n return { ...operation, references };\n });\n}\n\nexport async function markVideoGenerationSubmissionUncertain(\n db: Database,\n input: OperationMutationInput & { nextReconcileAt: Date; error: string },\n): Promise<VideoGenerationOperation> {\n return await mutateOperation(db, input, async (tx, operation) => {\n if (operation.status !== \"submission_uncertain\" || !operation.providerRequestEncrypted) {\n throw invalidTransition(operation, \"submission_uncertain\");\n }\n const now = new Date();\n const [updated] = await tx\n .update(schema.videoGenerationOperations)\n .set({\n status: \"submission_uncertain\",\n providerRequestSentAt: operation.providerRequestSentAt ?? now,\n nextReconcileAt: input.nextReconcileAt,\n lastError: boundPrivateError(input.error),\n reconcileLeaseOwner: null,\n reconcileLeaseExpiresAt: null,\n updatedAt: now,\n })\n .where(eq(schema.videoGenerationOperations.id, operation.id))\n .returning();\n return requireRow(updated, \"record uncertain video submission\");\n });\n}\n\n/**\n * Freeze the exact provider start body before issuing the request. If the\n * worker disappears after this transaction, recovery replays the same body\n * and idempotency key rather than reminting URLs or changing request bytes.\n */\nexport async function markVideoGenerationSubmissionIntent(\n db: Database,\n input: OperationMutationInput & {\n encryptedProviderRequest: string;\n providerRequestExpiresAt: Date;\n nextReconcileAt: Date;\n },\n): Promise<VideoGenerationOperation> {\n return await mutateOperation(db, input, async (tx, operation) => {\n if (operation.status === \"submission_uncertain\") {\n if (!operation.providerRequestEncrypted || !operation.providerRequestExpiresAt) {\n throw new VideoGenerationConflictError(\"Video provider request is incomplete\");\n }\n return operation;\n }\n if (operation.status !== \"accepted\") {\n throw invalidTransition(operation, \"submission_uncertain\");\n }\n const now = new Date();\n const [updated] = await tx\n .update(schema.videoGenerationOperations)\n .set({\n status: \"submission_uncertain\",\n providerRequestEncrypted: input.encryptedProviderRequest,\n providerRequestExpiresAt: input.providerRequestExpiresAt,\n nextReconcileAt: input.nextReconcileAt,\n lastError: null,\n reconcileLeaseOwner: null,\n reconcileLeaseExpiresAt: null,\n updatedAt: now,\n })\n .where(eq(schema.videoGenerationOperations.id, operation.id))\n .returning();\n await tx\n .update(schema.videoGenerationReferences)\n .set({\n grantExpiresAt: input.providerRequestExpiresAt,\n cleanupAfter: new Date(\n Math.max(\n operation.recoveryDeadlineAt.getTime(),\n input.providerRequestExpiresAt.getTime(),\n ),\n ),\n })\n .where(eq(schema.videoGenerationReferences.operationId, operation.id));\n return requireRow(updated, \"record video provider submission intent\");\n });\n}\n\nexport async function markVideoGenerationProviderStarted(\n db: Database,\n input: OperationMutationInput & {\n providerJobId: string;\n nextReconcileAt: Date;\n },\n): Promise<VideoGenerationOperation> {\n return await mutateOperation(db, input, async (tx, operation) => {\n if (\n operation.providerJobId === input.providerJobId &&\n operation.status === \"provider_started\"\n ) {\n return operation;\n }\n if (!inArrayValue(operation.status, [\"accepted\", \"submission_uncertain\"])) {\n throw invalidTransition(operation, \"provider_started\");\n }\n const now = new Date();\n const [updated] = await tx\n .update(schema.videoGenerationOperations)\n .set({\n status: \"provider_started\",\n providerJobId: input.providerJobId.slice(0, 1_024),\n providerRequestEncrypted: null,\n providerRequestExpiresAt: null,\n providerRequestSentAt: operation.providerRequestSentAt ?? now,\n providerStartedAt: operation.providerStartedAt ?? now,\n nextReconcileAt: input.nextReconcileAt,\n lastError: null,\n reconcileLeaseOwner: null,\n reconcileLeaseExpiresAt: null,\n updatedAt: now,\n })\n .where(eq(schema.videoGenerationOperations.id, operation.id))\n .returning();\n return requireRow(updated, \"record video provider job\");\n });\n}\n\nexport async function rescheduleVideoGenerationOperation(\n db: Database,\n input: OperationMutationInput & {\n owner?: string;\n nextReconcileAt: Date;\n error?: string;\n },\n): Promise<boolean> {\n return await withRlsContext(\n db,\n { accountId: input.accountId, workspaceId: input.workspaceId },\n async (scopedDb) => {\n const [updated] = await scopedDb\n .update(schema.videoGenerationOperations)\n .set({\n nextReconcileAt: input.nextReconcileAt,\n ...(input.error ? { lastError: boundPrivateError(input.error) } : {}),\n reconcileLeaseOwner: null,\n reconcileLeaseExpiresAt: null,\n updatedAt: new Date(),\n })\n .where(\n and(\n eq(schema.videoGenerationOperations.workspaceId, input.workspaceId),\n eq(schema.videoGenerationOperations.id, input.operationId),\n eq(schema.videoGenerationOperations.requestDigest, input.requestDigest),\n ...(input.owner\n ? [eq(schema.videoGenerationOperations.reconcileLeaseOwner, input.owner)]\n : []),\n ),\n )\n .returning({ id: schema.videoGenerationOperations.id });\n return updated !== undefined;\n },\n );\n}\n\nexport async function markVideoGenerationRetaining(\n db: Database,\n input: OperationMutationInput,\n): Promise<VideoGenerationOperation> {\n return await mutateOperation(db, input, async (tx, operation) => {\n if (operation.status === \"retaining\") return operation;\n if (operation.status !== \"provider_started\") throw invalidTransition(operation, \"retaining\");\n const [updated] = await tx\n .update(schema.videoGenerationOperations)\n .set({\n status: \"retaining\",\n nextReconcileAt: new Date(),\n reconcileLeaseOwner: null,\n reconcileLeaseExpiresAt: null,\n updatedAt: new Date(),\n })\n .where(eq(schema.videoGenerationOperations.id, operation.id))\n .returning();\n return requireRow(updated, \"begin video retention\");\n });\n}\n\nexport async function settleVideoGenerationFailure(\n db: Database,\n input: OperationMutationInput & {\n status: \"provider_failed\" | \"retention_failed\" | \"outcome_unknown\";\n publicReason: string;\n privateError?: string;\n },\n): Promise<VideoGenerationOperation> {\n return await mutateOperation(db, input, async (tx, operation) => {\n if (operation.status === input.status) return operation;\n const allowed =\n input.status === \"provider_failed\"\n ? [\"accepted\", \"submission_uncertain\", \"provider_started\"]\n : input.status === \"retention_failed\"\n ? [\"retaining\"]\n : [\"submission_uncertain\", \"provider_started\"];\n if (!inArrayValue(operation.status, allowed)) throw invalidTransition(operation, input.status);\n await releaseReservedQuota(tx, operation, false);\n const now = new Date();\n const creditState = await refundVideoGenerationCredits(tx, operation, now);\n const [updated] = await tx\n .update(schema.videoGenerationOperations)\n .set({\n status: input.status,\n creditState,\n quotaState: \"released\",\n terminalAt: now,\n nextReconcileAt: null,\n terminalUpdateState:\n operation.admissionOutputState === \"recorded\" ? \"pending\" : \"suppressed\",\n providerRequestEncrypted: null,\n providerRequestExpiresAt: null,\n credentialEncrypted: null,\n requestEncrypted: null,\n boundedPublicReason: boundPublicReason(input.publicReason),\n lastError: input.privateError ? boundPrivateError(input.privateError) : null,\n reconcileLeaseOwner: null,\n reconcileLeaseExpiresAt: null,\n privateDataEraseAfter: now,\n updatedAt: now,\n })\n .where(eq(schema.videoGenerationOperations.id, operation.id))\n .returning();\n return requireRow(updated, \"settle failed video generation\");\n });\n}\n\nexport type SettleVideoGenerationReadyInput = OperationMutationInput & {\n fileId: string;\n bucket: string;\n objectKey: string;\n sizeBytes: number;\n sha256: string;\n facts: GeneratedVideoFacts;\n};\n\nexport async function settleVideoGenerationReady(\n db: Database,\n input: SettleVideoGenerationReadyInput,\n): Promise<{\n operation: VideoGenerationOperation;\n artifact: GeneratedVideoArtifact;\n}> {\n return await withRlsContext(\n db,\n { accountId: input.accountId, workspaceId: input.workspaceId },\n async (scopedDb) =>\n await scopedDb.transaction(async (tx) => {\n const [operation] = await tx\n .select()\n .from(schema.videoGenerationOperations)\n .where(\n and(\n eq(schema.videoGenerationOperations.workspaceId, input.workspaceId),\n eq(schema.videoGenerationOperations.id, input.operationId),\n eq(schema.videoGenerationOperations.requestDigest, input.requestDigest),\n ),\n )\n .for(\"update\")\n .limit(1);\n if (!operation) throw new VideoGenerationConflictError(\"Video operation not found\");\n const [existingArtifact] = await tx\n .select()\n .from(schema.generatedVideoArtifacts)\n .where(eq(schema.generatedVideoArtifacts.operationId, operation.id))\n .limit(1);\n if (operation.status === \"completed\" && existingArtifact) {\n return { operation, artifact: existingArtifact };\n }\n if (operation.status !== \"retaining\") throw invalidTransition(operation, \"completed\");\n if (operation.expectedFileId !== input.fileId) {\n throw new VideoGenerationConflictError(\"Video File identity changed during settlement\");\n }\n if (operation.expectedArtifactId === operation.expectedFileId) {\n throw new Error(\"Video artifact and File identities must be distinct\");\n }\n // The durable provider operation owns this write, including when its\n // original session has since disappeared. Ordinary file reads stay scoped.\n await tx.execute(\n sql`SELECT set_config('opengeni.private_file_owner',${operation.privateFileOwnerSubjectId ?? \"\"},true)`,\n );\n const now = new Date();\n await tx.insert(schema.files).values({\n id: input.fileId,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n status: \"ready\",\n filename: `generated-video-${operation.expectedArtifactId}.mp4`,\n safeFilename: `generated-video-${operation.expectedArtifactId}.mp4`,\n contentType: \"video/mp4\",\n sizeBytes: input.sizeBytes,\n sha256: input.sha256,\n bucket: input.bucket,\n objectKey: input.objectKey,\n updatedAt: now,\n });\n const [artifact] = await tx\n .insert(schema.generatedVideoArtifacts)\n .values({\n id: operation.expectedArtifactId,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n primaryFileId: input.fileId,\n operationId: operation.id,\n sessionId: operation.sessionId,\n turnId: operation.turnId,\n attemptId: operation.attemptId,\n modelId: operation.modelId,\n sourceMode: operation.sourceMode,\n promptDigest: operation.promptDigest,\n contentType: \"video/mp4\",\n sizeBytes: input.sizeBytes,\n sha256: input.sha256,\n durationMillis: Math.round(input.facts.durationSeconds * 1_000),\n width: input.facts.width,\n height: input.facts.height,\n fpsMilli: Math.round(input.facts.fps * 1_000),\n videoCodec: input.facts.videoCodec,\n audioCodec: input.facts.audioCodec,\n hasAudio: input.facts.hasAudio,\n sandboxFilename: `generated-video-${operation.expectedArtifactId}.mp4`,\n readyAt: now,\n })\n .returning();\n if (!artifact) throw new Error(\"Generated video artifact was not persisted\");\n await tx\n .update(schema.workspaceVideoGenerationQuotas)\n .set({\n reservedBytes: sql`${schema.workspaceVideoGenerationQuotas.reservedBytes} - ${operation.reservedBytes}`,\n readyBytes: sql`${schema.workspaceVideoGenerationQuotas.readyBytes} + ${input.sizeBytes}`,\n updatedAt: now,\n })\n .where(eq(schema.workspaceVideoGenerationQuotas.workspaceId, input.workspaceId));\n const [updated] = await tx\n .update(schema.videoGenerationOperations)\n .set({\n status: \"completed\",\n quotaState: \"ready\",\n terminalAt: now,\n nextReconcileAt: null,\n terminalUpdateState:\n operation.admissionOutputState === \"recorded\" ? \"pending\" : \"suppressed\",\n providerRequestEncrypted: null,\n providerRequestExpiresAt: null,\n credentialEncrypted: null,\n requestEncrypted: null,\n boundedPublicReason: null,\n lastError: null,\n privateDataEraseAfter: now,\n reconcileLeaseOwner: null,\n reconcileLeaseExpiresAt: null,\n updatedAt: now,\n })\n .where(eq(schema.videoGenerationOperations.id, operation.id))\n .returning();\n return {\n operation: requireRow(updated, \"settle ready video generation\"),\n artifact,\n };\n }),\n );\n}\n\nexport async function getGeneratedVideoArtifact(\n db: Database,\n workspaceId: string,\n artifactId: string,\n): Promise<{\n artifact: GeneratedVideoArtifact;\n file: typeof schema.files.$inferSelect;\n} | null> {\n return await withWorkspaceRls(db, workspaceId, async (scopedDb) => {\n const [row] = await scopedDb\n .select({ artifact: schema.generatedVideoArtifacts, file: schema.files })\n .from(schema.generatedVideoArtifacts)\n .innerJoin(schema.files, eq(schema.files.id, schema.generatedVideoArtifacts.primaryFileId))\n .where(\n and(\n eq(schema.generatedVideoArtifacts.workspaceId, workspaceId),\n eq(schema.generatedVideoArtifacts.id, artifactId),\n ),\n )\n .limit(1);\n return row ?? null;\n });\n}\n\nexport async function listSessionGeneratedVideoArtifacts(\n db: Database,\n workspaceId: string,\n sessionId: string,\n): Promise<\n Array<{\n artifact: GeneratedVideoArtifact;\n file: typeof schema.files.$inferSelect;\n }>\n> {\n return await withWorkspaceRls(\n db,\n workspaceId,\n async (scopedDb) =>\n await scopedDb\n .select({\n artifact: schema.generatedVideoArtifacts,\n file: schema.files,\n })\n .from(schema.generatedVideoArtifacts)\n .innerJoin(schema.files, eq(schema.files.id, schema.generatedVideoArtifacts.primaryFileId))\n .where(\n and(\n eq(schema.generatedVideoArtifacts.workspaceId, workspaceId),\n eq(schema.generatedVideoArtifacts.sessionId, sessionId),\n sql`${schema.generatedVideoArtifacts.deletedAt} is null`,\n ),\n )\n .orderBy(schema.generatedVideoArtifacts.createdAt, schema.generatedVideoArtifacts.id),\n );\n}\n\n/**\n * Record one staging object as erased only after the object-store delete has\n * succeeded. Deleting first is safe because object deletion is idempotent; a\n * crash before this CAS simply repeats the same delete on recovery.\n */\nexport async function markVideoGenerationReferenceCleaned(\n db: Database,\n input: {\n accountId: string;\n workspaceId: string;\n operationId: string;\n ordinal: number;\n stagingObjectKey: string;\n },\n): Promise<boolean> {\n return await withRlsContext(\n db,\n { accountId: input.accountId, workspaceId: input.workspaceId },\n async (scopedDb) => {\n const [updated] = await scopedDb\n .update(schema.videoGenerationReferences)\n .set({\n stagingObjectKey: null,\n grantExpiresAt: null,\n cleanupAfter: null,\n cleanedAt: new Date(),\n })\n .where(\n and(\n eq(schema.videoGenerationReferences.workspaceId, input.workspaceId),\n eq(schema.videoGenerationReferences.operationId, input.operationId),\n eq(schema.videoGenerationReferences.ordinal, input.ordinal),\n eq(schema.videoGenerationReferences.stagingObjectKey, input.stagingObjectKey),\n ),\n )\n .returning({\n operationId: schema.videoGenerationReferences.operationId,\n });\n if (updated) return true;\n const [existing] = await scopedDb\n .select({ cleanedAt: schema.videoGenerationReferences.cleanedAt })\n .from(schema.videoGenerationReferences)\n .where(\n and(\n eq(schema.videoGenerationReferences.workspaceId, input.workspaceId),\n eq(schema.videoGenerationReferences.operationId, input.operationId),\n eq(schema.videoGenerationReferences.ordinal, input.ordinal),\n ),\n )\n .limit(1);\n return existing?.cleanedAt !== null && existing?.cleanedAt !== undefined;\n },\n );\n}\n\nexport async function markVideoGenerationTerminalUpdate(\n db: Database,\n input: {\n accountId: string;\n workspaceId: string;\n operationId: string;\n state: \"leased\" | \"delivered\" | \"suppressed\";\n updateId?: string;\n },\n): Promise<boolean> {\n return await withRlsContext(\n db,\n { accountId: input.accountId, workspaceId: input.workspaceId },\n async (scopedDb) => {\n return await markVideoGenerationTerminalUpdateInTransaction(scopedDb, input);\n },\n );\n}\n\nexport async function markVideoGenerationTerminalUpdateInTransaction(\n tx: Database,\n input: {\n workspaceId: string;\n operationId: string;\n state: \"leased\" | \"delivered\" | \"suppressed\";\n updateId?: string;\n },\n): Promise<boolean> {\n const allowed =\n input.state === \"leased\"\n ? [\"pending\", \"leased\"]\n : input.state === \"delivered\"\n ? [\"leased\"]\n : [\"pending\", \"leased\"];\n const [updated] = await tx\n .update(schema.videoGenerationOperations)\n .set({\n terminalUpdateState: input.state,\n terminalUpdateId: input.state === \"suppressed\" ? null : (input.updateId ?? null),\n updatedAt: new Date(),\n })\n .where(\n and(\n eq(schema.videoGenerationOperations.workspaceId, input.workspaceId),\n eq(schema.videoGenerationOperations.id, input.operationId),\n inArray(schema.videoGenerationOperations.terminalUpdateState, allowed),\n ...(input.state === \"delivered\" && input.updateId\n ? [eq(schema.videoGenerationOperations.terminalUpdateId, input.updateId)]\n : []),\n ),\n )\n .returning({ id: schema.videoGenerationOperations.id });\n return updated !== undefined;\n}\n\nexport function mediaGenerationResultForOperation(input: {\n operation: VideoGenerationOperation;\n readyReceipt?: Extract<MediaGenerationResult, { status: \"ready\" }>[\"receipt\"];\n}): MediaGenerationResult {\n if (input.operation.status === \"completed\" && input.readyReceipt) {\n return {\n type: \"media_generation_result\",\n schemaVersion: 1,\n status: \"ready\",\n operationId: input.operation.id,\n receipt: input.readyReceipt,\n };\n }\n const failureStatus = input.operation.status;\n if (\n !inArrayValue(failureStatus, [\n \"provider_failed\",\n \"retention_failed\",\n \"cancelled_before_submit\",\n \"outcome_unknown\",\n ])\n ) {\n throw new Error(\"Video generation operation is not terminal\");\n }\n return {\n type: \"media_generation_result\",\n schemaVersion: 1,\n status: failureStatus,\n operationId: input.operation.id,\n boundedPublicReason:\n input.operation.boundedPublicReason ?? \"Video generation did not complete.\",\n } as MediaGenerationResult;\n}\n\n/** Build the compact public/model terminal envelope from durable canonical rows. */\nexport async function mediaGenerationResultForStoredOperation(\n db: Database,\n operation: VideoGenerationOperation,\n): Promise<MediaGenerationResult> {\n if (operation.status !== \"completed\") {\n return mediaGenerationResultForOperation({ operation });\n }\n const retained = await getGeneratedVideoArtifact(\n db,\n operation.workspaceId,\n operation.expectedArtifactId,\n );\n if (!retained || retained.artifact.deletedAt) {\n throw new Error(\"Completed video generation lost its retained artifact\");\n }\n const artifact = retainedGeneratedVideoReferenceFromFile({\n id: retained.artifact.id,\n workspaceId: retained.artifact.workspaceId,\n status: retained.file.status,\n contentType: retained.file.contentType,\n sizeBytes: retained.file.sizeBytes,\n sha256: retained.file.sha256,\n updatedAt: retained.artifact.readyAt.toISOString(),\n width: retained.artifact.width,\n height: retained.artifact.height,\n });\n if (!artifact) throw new Error(\"Generated video receipt could not be constructed\");\n const receipt = GeneratedVideoReceipt.parse({\n type: \"generated_video\",\n schemaVersion: 1,\n operationId: operation.id,\n artifact,\n video: {\n durationSeconds: retained.artifact.durationMillis / 1_000,\n width: retained.artifact.width,\n height: retained.artifact.height,\n fps: retained.artifact.fpsMilli / 1_000,\n hasAudio: retained.artifact.hasAudio,\n videoCodec: retained.artifact.videoCodec,\n audioCodec: retained.artifact.audioCodec,\n },\n sandboxPath: `/workspace/generated-videos/${retained.artifact.sandboxFilename}`,\n });\n return mediaGenerationResultForOperation({\n operation,\n readyReceipt: receipt,\n });\n}\n\nexport async function getVideoGenerationOperationSummary(\n db: Database,\n workspaceId: string,\n operationId: string,\n): Promise<import(\"@opengeni/contracts\").VideoGenerationOperationSummary | null> {\n const operation = await getVideoGenerationOperation(db, workspaceId, operationId);\n if (!operation) return null;\n if (operation.privateFileOwnerSubjectId) {\n const [context] = await withWorkspaceRls(db, workspaceId, (tx) =>\n rawRows<{ owner: string | null }>(\n tx,\n sql`SELECT nullif(current_setting('opengeni.private_file_owner',true),'') AS owner`,\n ),\n );\n if (context?.owner !== operation.privateFileOwnerSubjectId) return null;\n }\n const terminal = inArrayValue(operation.status, [\n \"completed\",\n \"provider_failed\",\n \"cancelled_before_submit\",\n \"outcome_unknown\",\n \"retention_failed\",\n ])\n ? await mediaGenerationResultForStoredOperation(db, operation)\n : null;\n return VideoGenerationOperationSummary.parse({\n schemaVersion: 1,\n operationId: operation.id,\n modelId: operation.modelId,\n status: operation.status === \"submission_uncertain\" ? \"accepted\" : operation.status,\n createdAt: operation.createdAt.toISOString(),\n updatedAt: operation.updatedAt.toISOString(),\n terminal,\n });\n}\n\ntype OperationMutationInput = {\n accountId: string;\n workspaceId: string;\n operationId: string;\n requestDigest: string;\n};\n\nasync function mutateOperation<T>(\n db: Database,\n input: OperationMutationInput,\n mutate: (tx: Database, operation: VideoGenerationOperation) => Promise<T>,\n): Promise<T> {\n return await withRlsContext(\n db,\n { accountId: input.accountId, workspaceId: input.workspaceId },\n async (scopedDb) =>\n await scopedDb.transaction(async (txRaw) => {\n const tx = txRaw as unknown as Database;\n const [operation] = await tx\n .select()\n .from(schema.videoGenerationOperations)\n .where(\n and(\n eq(schema.videoGenerationOperations.workspaceId, input.workspaceId),\n eq(schema.videoGenerationOperations.id, input.operationId),\n eq(schema.videoGenerationOperations.requestDigest, input.requestDigest),\n ),\n )\n .for(\"update\")\n .limit(1);\n if (!operation) throw new VideoGenerationConflictError(\"Video operation not found\");\n return await mutate(tx, operation);\n }),\n );\n}\n\nasync function releaseReservedQuota(\n tx: Database,\n operation: VideoGenerationOperation,\n ready: boolean,\n): Promise<void> {\n if (operation.quotaState !== \"reserved\") return;\n await tx\n .update(schema.workspaceVideoGenerationQuotas)\n .set({\n reservedBytes: sql`${schema.workspaceVideoGenerationQuotas.reservedBytes} - ${operation.reservedBytes}`,\n ...(ready\n ? {\n readyBytes: sql`${schema.workspaceVideoGenerationQuotas.readyBytes} + ${operation.reservedBytes}`,\n }\n : {}),\n updatedAt: new Date(),\n })\n .where(eq(schema.workspaceVideoGenerationQuotas.workspaceId, operation.workspaceId));\n}\n\nasync function debitVideoGenerationCredits(\n tx: Database,\n operation: VideoGenerationOperation,\n): Promise<void> {\n if (operation.pricedCostMicros <= 0 || operation.fundingSource !== \"opengeni_credits\") {\n throw new Error(\"Managed video credit debit has an invalid funding binding\");\n }\n if (!operation.turnId) {\n throw new VideoGenerationCreditError(\"Paid video initiating turn is unavailable\");\n }\n // Model settlement locks the account before the ledger trigger's workspace\n // allowance fence. Preserve that order during prepaid media admission.\n await tx.execute(sql`select pg_advisory_xact_lock(hashtext(${operation.accountId}))`);\n const attribution = await creditDebitAttributionForTurn(tx, {\n accountId: operation.accountId,\n workspaceId: operation.workspaceId,\n turnId: operation.turnId,\n });\n const refusal = await checkWorkspaceAllowance(tx, {\n accountId: operation.accountId,\n workspaceId: operation.workspaceId,\n subjectId: attribution.kind === \"turn\" ? attribution.initiatingHumanSubjectId : null,\n });\n if (refusal) throw Object.assign(new VideoGenerationCreditError(refusal.message), refusal);\n const { balanceMicros } = await getSpendableCreditBalance(tx, operation.accountId);\n if (!Number.isSafeInteger(balanceMicros) || balanceMicros < operation.pricedCostMicros) {\n throw new VideoGenerationCreditError();\n }\n const now = new Date();\n const inserted = await tx\n .insert(schema.creditLedgerEntries)\n .values({\n accountId: operation.accountId,\n workspaceId: operation.workspaceId,\n type: \"video_generation_debit\",\n amountMicros: -operation.pricedCostMicros,\n sourceType: \"video_generation_operation\",\n sourceId: operation.id,\n idempotencyKey: `credit:video_generation_debit:${operation.id}`,\n metadata: {\n turnId: operation.turnId,\n modelId: operation.modelId,\n sourceMode: operation.sourceMode,\n pricedCostMicros: operation.pricedCostMicros,\n },\n occurredAt: now,\n })\n .onConflictDoNothing({ target: schema.creditLedgerEntries.idempotencyKey })\n .returning({ id: schema.creditLedgerEntries.id });\n if (inserted.length !== 1) {\n throw new VideoGenerationConflictError(\"Video generation credit debit already exists\");\n }\n await tx\n .insert(schema.usageEvents)\n .values({\n accountId: operation.accountId,\n workspaceId: operation.workspaceId,\n eventType: \"video_generation.cost\",\n quantity: operation.pricedCostMicros,\n unit: \"usd_micros\",\n sourceResourceType: \"video_generation_operation\",\n sourceResourceId: operation.id,\n sessionId: operation.sessionId,\n turnId: operation.turnId,\n turnAttemptId: operation.attemptId,\n idempotencyKey: `usage:video_generation.cost:${operation.id}`,\n occurredAt: now,\n })\n .onConflictDoNothing({ target: schema.usageEvents.idempotencyKey });\n}\n\nasync function refundVideoGenerationCredits(\n tx: Database,\n operation: VideoGenerationOperation,\n now: Date,\n): Promise<VideoGenerationOperation[\"creditState\"]> {\n if (operation.creditState !== \"debited\") return operation.creditState;\n if (operation.fundingSource !== \"opengeni_credits\" || operation.pricedCostMicros <= 0) {\n throw new Error(\"Video generation credit refund has an invalid funding binding\");\n }\n await tx.execute(sql`select pg_advisory_xact_lock(hashtext(${operation.accountId}))`);\n const inserted = await tx\n .insert(schema.creditLedgerEntries)\n .values({\n accountId: operation.accountId,\n workspaceId: operation.workspaceId,\n type: \"video_generation_refund\",\n amountMicros: operation.pricedCostMicros,\n sourceType: \"video_generation_operation\",\n sourceId: operation.id,\n idempotencyKey: `credit:video_generation_refund:${operation.id}`,\n metadata: {\n turnId: operation.turnId,\n modelId: operation.modelId,\n sourceMode: operation.sourceMode,\n pricedCostMicros: operation.pricedCostMicros,\n },\n occurredAt: now,\n })\n .onConflictDoNothing({ target: schema.creditLedgerEntries.idempotencyKey })\n .returning({ id: schema.creditLedgerEntries.id });\n if (inserted.length !== 1) {\n throw new VideoGenerationConflictError(\"Video generation credit refund already exists\");\n }\n await tx\n .insert(schema.usageEvents)\n .values({\n accountId: operation.accountId,\n workspaceId: operation.workspaceId,\n eventType: \"video_generation.refund\",\n quantity: operation.pricedCostMicros,\n unit: \"usd_micros\",\n sourceResourceType: \"video_generation_operation\",\n sourceResourceId: operation.id,\n sessionId: operation.sessionId,\n turnId: operation.turnId,\n turnAttemptId: operation.attemptId,\n idempotencyKey: `usage:video_generation.refund:${operation.id}`,\n occurredAt: now,\n })\n .onConflictDoNothing({ target: schema.usageEvents.idempotencyKey });\n return \"refunded\";\n}\n\nfunction policyFromRow(\n row: typeof schema.workspaceVideoGenerationPolicies.$inferSelect | undefined,\n): VideoGenerationPolicyValue {\n return VideoGenerationPolicy.parse(\n row\n ? {\n schemaVersion: 1,\n revision: row.revision,\n fundingSource: row.fundingSource,\n enabledModelIds: row.enabledModelIds,\n defaultModelId: row.defaultModelId,\n }\n : {\n schemaVersion: 1,\n revision: 0,\n fundingSource: \"workspace_gateway\",\n enabledModelIds: [],\n defaultModelId: null,\n },\n );\n}\n\nfunction assertSupportedModels(modelIds: readonly string[]): void {\n for (const modelId of modelIds) {\n if (modelId !== SEEDANCE_2_5_MODEL_ID && modelId !== GROK_IMAGINE_VIDEO_1_5_MODEL_ID) {\n throw new Error(`Unknown video generation model: ${modelId}`);\n }\n }\n}\n\nfunction assertAdmissionMatches(\n operation: VideoGenerationOperation,\n input: AdmitVideoGenerationOperationInput,\n): void {\n if (\n operation.requestDigest !== input.requestDigest ||\n operation.toolCallId !== input.toolCallId ||\n operation.sessionId !== input.sessionId ||\n operation.turnId !== input.turnId ||\n operation.fundingSource !== input.fundingSource ||\n operation.pricedCostMicros !== input.pricedCostMicros\n ) {\n throw new VideoGenerationConflictError(\n \"Video generation admission key was reused with different arguments\",\n );\n }\n}\n\nfunction inPreSubmitState(status: string): boolean {\n return inArrayValue(status, [\"preparing\", \"prepared\", \"accepted\"]);\n}\n\nfunction inArrayValue<T extends string>(value: string, candidates: readonly T[]): value is T {\n return (candidates as readonly string[]).includes(value);\n}\n\nfunction invalidTransition(operation: VideoGenerationOperation, target: string): Error {\n return new VideoGenerationConflictError(\n `Invalid video generation transition ${operation.status} -> ${target}`,\n );\n}\n\nfunction requireRow<T>(value: T | undefined, action: string): T {\n if (!value) throw new Error(`Failed to ${action}`);\n return value;\n}\n\nfunction boundPublicReason(value: string): string {\n const normalized = value.replace(/\\s+/gu, \" \").trim();\n return (normalized || \"Video generation did not complete.\").slice(0, 1_000);\n}\n\nfunction boundPrivateError(value: string): string {\n return value.replace(/\\s+/gu, \" \").trim().slice(0, 4_096);\n}\n","import { sql } from \"drizzle-orm\";\nimport { rawRows, setSubjectRlsContext, withRlsContext, type Database } from \"./database\";\nimport { currentCreditDebitAttribution } from \"./credit-debit-attribution\";\n\n/** All amounts are integer USD micros, never dollars or floating-point credits. */\nexport type MemberAllowanceRule = { share: number } | { credits: number } | null;\nexport type WorkspaceAllowanceConfig = {\n includedCredits: number;\n period: \"monthly\" | \"none\";\n anchorDay?: number;\n memberDefault?: \"none\" | \"equal_share\" | Exclude<MemberAllowanceRule, null>;\n thresholds?: { workspace?: number[]; member?: number[] };\n};\nexport type WorkspaceAllowance = WorkspaceAllowanceConfig & { version: number };\nexport type WorkspaceAllowanceState = { version: number; config: WorkspaceAllowance | null };\nexport type AllowanceStatus = \"ok\" | \"warning\" | \"exhausted\";\nexport type AllowanceUsage = {\n limit: number | null;\n used: number;\n remaining: number | null;\n fraction: number | null;\n status: AllowanceStatus;\n resetsAt: string | null;\n};\nexport type MemberAllowance = {\n subjectId: string;\n rule: MemberAllowanceRule;\n version: number;\n};\nexport type WorkspaceUsage = {\n period: { start: string | null; end: string | null };\n workspace: AllowanceUsage & { includedCredits: number; grantsRemaining: number };\n members: (AllowanceUsage &\n MemberAllowance & {\n externalIdentity: { source: string; externalId: string } | null;\n })[];\n nextCursor: string | null;\n};\nexport type AllowanceExhausted = {\n code: \"allowance_exhausted\";\n scope: \"workspace\" | \"member\";\n resetsAt: string | null;\n subjectId?: string;\n message: string;\n};\ntype Scope = { accountId: string; workspaceId: string };\ntype Actor = { actorSubjectId: string; actorType?: string | undefined };\n\nexport class UsageAllowanceVersionConflictError extends Error {\n constructor() {\n super(\"Usage allowance version conflict\");\n this.name = \"UsageAllowanceVersionConflictError\";\n }\n}\n\nfunction amount(value: number, name: string, positive = false): void {\n if (!Number.isSafeInteger(value) || value < (positive ? 1 : 0)) {\n throw new Error(\n `${name} must be ${positive ? \"a positive\" : \"a non-negative\"} safe integer in USD micros`,\n );\n }\n}\n\nexport function validateMemberAllowanceRule(rule: MemberAllowanceRule): void {\n if (rule === null) return;\n if (\"credits\" in rule) {\n if (Object.keys(rule).length !== 1)\n throw new Error(\"Member rule must have only credits or share\");\n amount(rule.credits, \"credits\");\n } else if (\"share\" in rule) {\n if (Object.keys(rule).length !== 1 || !Number.isFinite(rule.share) || rule.share < 0) {\n throw new Error(\"share must be a finite non-negative number\");\n }\n } else {\n throw new Error(\"Member rule must have credits or share\");\n }\n}\n\nexport function validateWorkspaceAllowanceConfig(config: WorkspaceAllowanceConfig): void {\n amount(config.includedCredits, \"includedCredits\");\n if (config.period !== \"monthly\" && config.period !== \"none\")\n throw new Error(\"Invalid allowance period\");\n if (\n config.anchorDay !== undefined &&\n (!Number.isInteger(config.anchorDay) || config.anchorDay < 1 || config.anchorDay > 31)\n ) {\n throw new Error(\"anchorDay must be an integer from 1 to 31\");\n }\n if (\n config.memberDefault !== undefined &&\n config.memberDefault !== \"none\" &&\n config.memberDefault !== \"equal_share\"\n ) {\n validateMemberAllowanceRule(config.memberDefault);\n }\n for (const list of [config.thresholds?.workspace, config.thresholds?.member]) {\n if (\n list !== undefined &&\n (list.length > 16 ||\n list.some((threshold) => !Number.isFinite(threshold) || threshold <= 0 || threshold > 1))\n ) {\n throw new Error(\n \"thresholds must contain at most 16 fractions greater than zero and at most one\",\n );\n }\n }\n}\n\nasync function command<T>(db: Database, input: Scope & Record<string, unknown>): Promise<T> {\n if (\n [\"set\", \"clear\", \"member\", \"grant\"].includes(String(input.action)) &&\n currentCreditDebitAttribution().kind === \"turn\"\n ) {\n // This context is installed by the authenticated request boundary, not\n // supplied in the allowance command. Agent attempts cannot substitute\n // human-looking actor labels to author allowance policy.\n throw new Error(\"Agent attempts cannot change usage allowances\");\n }\n try {\n const mutation = [\"set\", \"clear\", \"member\", \"grant\"].includes(String(input.action));\n return await withRlsContext(\n db,\n input,\n async (scoped) => {\n if (mutation) {\n // The organization lifecycle can hold this fence while waiting for\n // exclusive tenancy. Never acquire shared tenancy ahead of it.\n await scoped.execute(sql`select pg_advisory_xact_lock(\n hashtextextended(${`organization-membership:${input.accountId}`},0))`);\n await scoped.execute(sql`select pg_advisory_xact_lock_shared(\n hashtextextended(${`session-tenancy:${input.workspaceId}`},0))`);\n }\n if (typeof input.actorSubjectId === \"string\")\n await setSubjectRlsContext(scoped, input.actorSubjectId);\n const [row] = await rawRows<{ result: T }>(\n scoped,\n sql`select usage_allowance_command(${JSON.stringify(input)}::jsonb) as result`,\n );\n if (!row) throw new Error(\"Usage allowance command returned no result\");\n return row.result;\n },\n undefined,\n mutation ? \"none\" : \"shared\",\n );\n } catch (error) {\n const cause = error as { code?: string; cause?: { code?: string } };\n if ((cause.code ?? cause.cause?.code) === \"40001\")\n throw new UsageAllowanceVersionConflictError();\n throw error;\n }\n}\n\nfunction actor(input: Actor): Actor & { actorType: string } {\n return { actorSubjectId: input.actorSubjectId, actorType: input.actorType ?? \"subject\" };\n}\nfunction version(value: number): void {\n amount(value, \"expectedVersion\");\n}\n\nexport async function getWorkspaceAllowance(\n db: Database,\n input: Scope,\n): Promise<WorkspaceAllowance | null> {\n return await command(db, { ...input, action: \"get\" });\n}\n\n/** Includes the lifecycle revision even when no configuration exists. */\nexport async function getWorkspaceAllowanceState(\n db: Database,\n input: Scope,\n): Promise<WorkspaceAllowanceState> {\n return await command(db, { ...input, action: \"state\" });\n}\n\nexport async function setWorkspaceAllowance(\n db: Database,\n input: Scope & Actor & WorkspaceAllowanceConfig & { expectedVersion: number },\n): Promise<WorkspaceAllowance> {\n const { accountId, workspaceId, expectedVersion, actorSubjectId, actorType } = input;\n const config: WorkspaceAllowanceConfig = {\n includedCredits: input.includedCredits,\n period: input.period,\n ...(input.anchorDay === undefined ? {} : { anchorDay: input.anchorDay }),\n ...(input.memberDefault === undefined ? {} : { memberDefault: input.memberDefault }),\n ...(input.thresholds === undefined ? {} : { thresholds: input.thresholds }),\n };\n version(expectedVersion);\n validateWorkspaceAllowanceConfig(config);\n return await command(db, {\n accountId,\n workspaceId,\n expectedVersion,\n ...actor({ actorSubjectId, actorType }),\n action: \"set\",\n config,\n });\n}\n\nexport async function clearWorkspaceAllowance(\n db: Database,\n input: Scope & Actor & { expectedVersion: number; operationId?: string },\n): Promise<{ version: number }> {\n version(input.expectedVersion);\n if (input.expectedVersion === 0) throw new UsageAllowanceVersionConflictError();\n if (\n input.operationId !== undefined &&\n (!input.operationId.trim() || new TextEncoder().encode(input.operationId).length > 256)\n )\n throw new Error(\"operationId must be non-empty and at most 256 bytes\");\n return await command(db, { ...input, ...actor(input), action: \"clear\" });\n}\n\nexport async function grantWorkspaceCredits(\n db: Database,\n input: Scope & Actor & { operationId: string; credits: number; expiresAt?: string | null },\n): Promise<{ operationId: string; credits: number; remaining: number; expiresAt: string | null }> {\n amount(input.credits, \"credits\", true);\n if (!input.operationId.trim() || new TextEncoder().encode(input.operationId).length > 256) {\n throw new Error(\"operationId must be non-empty and at most 256 bytes\");\n }\n if (input.expiresAt != null && !Number.isFinite(Date.parse(input.expiresAt)))\n throw new Error(\"Invalid grant expiresAt\");\n return await command(db, {\n ...input,\n ...actor(input),\n expiresAt: input.expiresAt ?? null,\n action: \"grant\",\n });\n}\n\nexport async function setMemberAllowance(\n db: Database,\n input: Scope &\n Actor & { rule: MemberAllowanceRule; expectedVersion: number } & (\n | { subjectId: string; externalIdentity?: never }\n | { externalIdentity: { source: string; externalId: string }; subjectId?: never }\n ),\n): Promise<MemberAllowance> {\n version(input.expectedVersion);\n validateMemberAllowanceRule(input.rule);\n return await command(db, { ...input, ...actor(input), action: \"member\" });\n}\n\ntype RawUsage = {\n config: WorkspaceAllowanceConfig | null;\n period: WorkspaceUsage[\"period\"];\n used: number;\n includedUsed: number;\n grantsUsed: number;\n grantsRemaining: number;\n memberCount: number;\n members: (MemberAllowance & {\n used: number;\n externalIdentity: { source: string; externalId: string } | null;\n })[];\n};\n\nexport function allowanceUsage(\n limit: number | null,\n used: number,\n resetsAt: string | null,\n thresholds = [0.8, 1],\n): AllowanceUsage {\n const fraction = limit === null ? null : limit === 0 ? 1 : used / limit;\n const remaining = limit === null ? null : Math.max(0, limit - used);\n return {\n limit,\n used,\n remaining,\n fraction,\n status:\n remaining === 0\n ? \"exhausted\"\n : fraction !== null && thresholds.some((t) => fraction >= t)\n ? \"warning\"\n : \"ok\",\n resetsAt,\n };\n}\n\nexport async function getWorkspaceUsage(\n db: Database,\n input: Scope & {\n period?: \"current\" | string;\n limit?: number;\n cursor?: string | null;\n subjectId?: string;\n },\n): Promise<WorkspaceUsage> {\n if (\n input.period !== undefined &&\n input.period !== \"current\" &&\n !/^\\d{4}-(0[1-9]|1[0-2])$/.test(input.period)\n ) {\n throw new Error(\"period must be current or YYYY-MM\");\n }\n const pageSize = Math.min(500, Math.max(1, Math.trunc(input.limit ?? 100)));\n const raw = await command<RawUsage>(db, { ...input, limit: pageSize, action: \"usage\" });\n return projectUsage(raw, pageSize);\n}\n\nfunction projectUsage(raw: RawUsage, pageSize: number): WorkspaceUsage {\n const config = raw.config;\n const pool = config\n ? config.includedCredits + Number(raw.grantsUsed) + Number(raw.grantsRemaining)\n : null;\n const memberPool = config ? config.includedCredits + Number(raw.grantsRemaining) : null;\n const resetsAt = config ? raw.period.end : null;\n const members = raw.members.slice(0, pageSize).map((member) => {\n let rule = member.rule;\n if (rule === null) {\n const fallback = config?.memberDefault ?? \"none\";\n rule =\n fallback === \"none\"\n ? null\n : fallback === \"equal_share\"\n ? { share: raw.memberCount > 0 ? 1 / Number(raw.memberCount) : 0 }\n : fallback;\n }\n const limit =\n rule === null\n ? null\n : \"credits\" in rule\n ? rule.credits\n : memberPool === null\n ? null\n : Math.min(Number.MAX_SAFE_INTEGER, Math.floor(memberPool * rule.share));\n return {\n ...member,\n rule: member.rule,\n ...allowanceUsage(limit, Number(member.used), resetsAt, config?.thresholds?.member),\n };\n });\n return {\n period: config ? raw.period : { start: null, end: null },\n workspace: {\n ...allowanceUsage(pool, Number(raw.used), resetsAt, config?.thresholds?.workspace),\n includedCredits: config?.includedCredits ?? 0,\n grantsRemaining: Number(raw.grantsRemaining),\n },\n members,\n nextCursor: raw.members.length > pageSize ? members.at(-1)!.subjectId : null,\n };\n}\n\nexport async function checkWorkspaceAllowance(\n db: Database,\n input: Scope & { subjectId?: string | null },\n): Promise<AllowanceExhausted | null> {\n const raw = await command<RawUsage>(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n ...(input.subjectId ? { subjectId: input.subjectId } : {}),\n limit: 1,\n action: \"check\",\n });\n const usage = projectUsage(raw, 1);\n if (usage.workspace.status === \"exhausted\") {\n return {\n code: \"allowance_exhausted\",\n scope: \"workspace\",\n resetsAt: usage.workspace.resetsAt,\n message: \"The workspace usage allowance is exhausted.\",\n };\n }\n const member = input.subjectId\n ? usage.members.find((row) => row.subjectId === input.subjectId)\n : null;\n if (member?.status === \"exhausted\") {\n return {\n code: \"allowance_exhausted\",\n scope: \"member\",\n subjectId: member.subjectId,\n resetsAt: member.resetsAt,\n message: \"The member usage allowance is exhausted.\",\n };\n }\n return null;\n}\n\n/** Bounded periodic work, independent of reads/admission and webhook delivery. */\nexport async function maintainWorkspaceAllowances(\n db: Database,\n input: { limit?: number; memberLimit?: number } = {},\n): Promise<number> {\n const [row] = await rawRows<{ processed: number }>(\n db,\n sql`select maintain_usage_allowances(${input.limit ?? 20}::integer,${input.memberLimit ?? 100}::integer) as processed`,\n );\n return Number(row?.processed ?? 0);\n}\n","import { z } from \"zod\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { sql } from \"drizzle-orm\";\nimport { rawRows, withRlsContext, type Database } from \"./database\";\n\nconst creditDebitAttributionContext = new AsyncLocalStorage<CreditDebitAttribution>();\n\nexport function currentCreditDebitAttribution(): CreditDebitAttribution {\n return creditDebitAttributionContext.getStore() ?? { kind: \"unknown\" };\n}\n\n/** Scope trusted HTTP/MCP admission facts across nested sandbox calls. */\nexport function withCreditDebitAttribution<T>(\n attribution: CreditDebitAttribution,\n fn: () => Promise<T>,\n): Promise<T> {\n return creditDebitAttributionContext.run(\n Object.freeze(CreditDebitAttribution.parse(attribution)),\n fn,\n );\n}\n\n/** Read one immutable turn, rejecting a missing receipt rather than service. */\nexport async function creditDebitAttributionForTurn(\n db: Database,\n input: { accountId: string; workspaceId: string; turnId: string },\n): Promise<CreditDebitAttribution> {\n return withRlsContext(db, input, async (tx) => {\n const [turn] = await rawRows<{ initiatingHumanSubjectId: string | null }>(\n tx,\n sql`SELECT initiating_human_subject_id AS \"initiatingHumanSubjectId\"\n FROM session_turns WHERE account_id=${input.accountId}::uuid\n AND workspace_id=${input.workspaceId}::uuid AND id=${input.turnId}::uuid`,\n );\n if (!turn) throw new Error(\"Paid credit debit initiating turn is unavailable\");\n return CreditDebitAttribution.parse({\n kind: \"turn\",\n turnId: input.turnId,\n initiatingHumanSubjectId: turn.initiatingHumanSubjectId,\n });\n });\n}\n\n/**\n * Trusted admission facts, not an access grant. Unknown is deliberately\n * distinct from pure service: old jobs/leases cannot prove a human initiator.\n */\nexport const CreditDebitAttribution = z.discriminatedUnion(\"kind\", [\n z.object({\n kind: z.literal(\"turn\"),\n turnId: z.uuid(),\n initiatingHumanSubjectId: z.string().min(1).max(1024).nullable(),\n }),\n z.object({\n kind: z.literal(\"human\"),\n initiatingHumanSubjectId: z.string().min(1).max(1024),\n }),\n z.object({ kind: z.literal(\"service\") }),\n z.object({ kind: z.literal(\"unknown\") }),\n]);\nexport type CreditDebitAttribution = z.infer<typeof CreditDebitAttribution>;\n\nexport function creditDebitAttributionMetadata(\n attribution: CreditDebitAttribution,\n): Record<string, string> {\n switch (attribution.kind) {\n case \"turn\":\n return {\n turnId: attribution.turnId,\n ...(attribution.initiatingHumanSubjectId\n ? { initiatingHumanSubjectId: attribution.initiatingHumanSubjectId }\n : {}),\n };\n case \"human\":\n return { initiatingHumanSubjectId: attribution.initiatingHumanSubjectId };\n case \"service\":\n return {};\n case \"unknown\":\n throw new Error(\"Paid credit debit has no frozen initiating attribution\");\n }\n}\n","import type { BillingBalance, PromotionalCreditBalance } from \"@opengeni/contracts\";\nimport { sql } from \"drizzle-orm\";\nimport type { Database } from \"./database\";\nimport { rawRows, withAccountRls } from \"./database\";\nimport * as schema from \"./schema\";\n\n/** Read totals and grant remainders from one database snapshot. */\ntype CreditBalanceSnapshot = BillingBalance & { creditPolicyRevision?: number };\n\nexport async function getBillingBalance(\n db: Database,\n accountId: string,\n policyRevision?: number,\n): Promise<CreditBalanceSnapshot> {\n return await withAccountRls(db, accountId, async (tx) => {\n const [row] = await rawRows<{\n balance: string;\n grants: PromotionalCreditBalance[];\n revision: number;\n }>(\n tx,\n sql`\n with current_policy as (\n select revision, policy from opengeni_private.credit_promotion_policy_revisions\n where (${policyRevision ?? null}::bigint is null or revision <= ${policyRevision ?? null}::bigint)\n order by revision desc limit 1\n )\n select\n coalesce((select revision from current_policy), 0)::int as revision,\n (select coalesce(sum(amount_micros), 0)::text\n from ${schema.creditLedgerEntries} where account_id = ${accountId}) as balance,\n coalesce((select jsonb_agg(jsonb_build_object(\n 'grantId', g.id,\n 'label', coalesce(g.metadata->>'creditOfferLabel', 'Promotional credits'),\n 'eligibleModelIds', coalesce(\n (select coalesce(\n case when g.source_type = 'verified_signup_trial' then policy->'signupModelIds'\n else policy->'offers'->(g.metadata->>'creditOfferId')->'eligibleModelIds' end,\n policy->'defaultModelIds'\n ) from current_policy), to_jsonb(g.eligible_model_ids)),\n 'remainingMicros', g.amount_micros - coalesce(used.amount, 0)\n ) order by g.created_at, g.id)\n from ${schema.creditLedgerEntries} g\n left join (\n select grant_entry_id, sum(amount_micros) as amount\n from ${schema.creditDebitAllocations} where account_id = ${accountId}\n group by grant_entry_id\n ) used on used.grant_entry_id = g.id\n where g.account_id = ${accountId} and g.eligible_model_ids is not null\n and g.amount_micros > coalesce(used.amount, 0)\n ), '[]'::jsonb) as grants\n `,\n );\n const balanceMicros = Number(row?.balance ?? 0);\n const promotionalCredits = row?.grants ?? [];\n return {\n accountId,\n creditPolicyRevision: row?.revision ?? 0,\n balanceMicros,\n generalBalanceMicros:\n balanceMicros - promotionalCredits.reduce((sum, grant) => sum + grant.remainingMicros, 0),\n promotionalCredits,\n currency: \"usd\",\n updatedAt: new Date().toISOString(),\n };\n });\n}\n\n/** Missing model means a non-model resource, which can only use general credits. */\nexport function spendableCreditMicros(balance: BillingBalance, modelId?: string): number {\n return (\n Math.max(0, balance.generalBalanceMicros ?? balance.balanceMicros) +\n (balance.promotionalCredits ?? []).reduce(\n (sum, grant) =>\n sum + (modelId && grant.eligibleModelIds.includes(modelId) ? grant.remainingMicros : 0),\n 0,\n )\n );\n}\n\nexport async function getSpendableCreditBalance(\n db: Database,\n accountId: string,\n modelId?: string,\n policyRevision?: number,\n): Promise<CreditBalanceSnapshot> {\n const balance = await getBillingBalance(db, accountId, policyRevision);\n return { ...balance, balanceMicros: spendableCreditMicros(balance, modelId) };\n}\n\nexport function planCreditDebit(\n balance: BillingBalance,\n requestedMicros: number,\n modelId?: string,\n) {\n if (!Number.isSafeInteger(requestedMicros) || requestedMicros <= 0) {\n throw new Error(\"credit debit requires a positive, safe integer micro amount\");\n }\n const debitedMicros = Math.min(requestedMicros, spendableCreditMicros(balance, modelId));\n let remaining = debitedMicros;\n const allocations: { grantEntryId: string; amountMicros: number }[] = [];\n for (const grant of balance.promotionalCredits ?? []) {\n if (!remaining || !modelId || !grant.eligibleModelIds.includes(modelId)) continue;\n const amountMicros = Math.min(remaining, grant.remainingMicros);\n allocations.push({ grantEntryId: grant.grantId, amountMicros });\n remaining -= amountMicros;\n }\n return { debitedMicros, allocations };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAKK;AACP,SAAS,KAAK,IAAI,SAAS,OAAAA,YAAW;;;ACbtC,SAAS,OAAAC,YAAW;;;ACCpB,SAAS,yBAAyB;AAClC,SAAS,WAAW;AAGpB,IAAM,gCAAgC,IAAI,kBAA0C;AAE7E,SAAS,gCAAwD;AACtE,SAAO,8BAA8B,SAAS,KAAK,EAAE,MAAM,UAAU;AACvE;AAGO,SAAS,2BACd,aACA,IACY;AACZ,SAAO,8BAA8B;AAAA,IACnC,OAAO,OAAO,uBAAuB,MAAM,WAAW,CAAC;AAAA,IACvD;AAAA,EACF;AACF;AAGA,eAAsB,8BACpB,IACA,OACiC;AACjC,SAAO,eAAe,IAAI,OAAO,OAAO,OAAO;AAC7C,UAAM,CAAC,IAAI,IAAI,MAAM;AAAA,MACnB;AAAA,MACA;AAAA,8CACwC,MAAM,SAAS;AAAA,6BAChC,MAAM,WAA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qB,MAAM,kBACrC;AACA,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACF;AAEA,SAAS,iBAAiB,QAAyB;AACjD,SAAO,aAAa,QAAQ,CAAC,aAAa,YAAY,UAAU,CAAC;AACnE;AAEA,SAAS,aAA+B,OAAe,YAAsC;AAC3F,SAAQ,WAAiC,SAAS,KAAK;AACzD;AAEA,SAAS,kBAAkB,WAAqC,QAAuB;AACrF,SAAO,IAAI;AAAA,IACT,uCAAuC,UAAU,MAAM,OAAO,MAAM;AAAA,EACtE;AACF;AAEA,SAAS,WAAc,OAAsB,QAAmB;AAC9D,MAAI,CAAC,MAAO,OAAM,IAAI,MAAM,aAAa,MAAM,EAAE;AACjD,SAAO;AACT;AAEA,SAAS,kBAAkB,OAAuB;AAChD,QAAM,aAAa,MAAM,QAAQ,SAAS,GAAG,EAAE,KAAK;AACpD,UAAQ,cAAc,sCAAsC,MAAM,GAAG,GAAK;AAC5E;AAEA,SAAS,kBAAkB,OAAuB;AAChD,SAAO,MAAM,QAAQ,SAAS,GAAG,EAAE,KAAK,EAAE,MAAM,GAAG,IAAK;AAC1D;","names":["sql","sql","sql","sql","sql","sql"]}
|
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
import {
|
|
2
2
|
appendSessionCommandOutput
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-6EIEGHPK.js";
|
|
4
4
|
import {
|
|
5
5
|
lockSessionEventWriteRows
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-CYP72JTQ.js";
|
|
7
7
|
import {
|
|
8
8
|
withRlsContext,
|
|
9
9
|
withSessionActivityRlsContext
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-O2Y5E5M3.js";
|
|
11
11
|
import {
|
|
12
12
|
sandboxRetainedProcesses
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-FWQNHNOU.js";
|
|
14
14
|
|
|
15
15
|
// src/retained-provider-commands.ts
|
|
16
16
|
import { and, eq, sql } from "drizzle-orm";
|
|
@@ -299,4 +299,4 @@ export {
|
|
|
299
299
|
retainedProcessCancellationRequested,
|
|
300
300
|
requestRetainedProcessDeadlineCancellation
|
|
301
301
|
};
|
|
302
|
-
//# sourceMappingURL=chunk-
|
|
302
|
+
//# sourceMappingURL=chunk-VDPCIFKL.js.map
|
|
@@ -153,6 +153,12 @@ var SANDBOX_FILE_PUBLICATION_RUNTIME_ROUTINES = [
|
|
|
153
153
|
"list_sandbox_file_publications(uuid, uuid, jsonb)"
|
|
154
154
|
];
|
|
155
155
|
var SANDBOX_FILE_PUBLICATIONS_TABLE = "sandbox_file_publications";
|
|
156
|
+
var ARTIFACT_PIN_RUNTIME_ROUTINES = [
|
|
157
|
+
"update_artifact_pin(uuid, uuid, text, text, boolean)",
|
|
158
|
+
"list_artifact_pins(uuid, uuid)",
|
|
159
|
+
"list_sandbox_file_publications_pinned(uuid, uuid, jsonb)"
|
|
160
|
+
];
|
|
161
|
+
var ARTIFACT_PINS_TABLE = "artifact_catalog_pins";
|
|
156
162
|
var SCHEDULED_SLACK_BOT_MESSAGE_RUNTIME_ROUTINES = [
|
|
157
163
|
"prepare_scheduled_slack_bot_message(uuid, uuid, uuid, uuid, uuid, integer, text, text, text)",
|
|
158
164
|
"read_scheduled_slack_bot_message(uuid, uuid, uuid, uuid)"
|
|
@@ -811,10 +817,12 @@ var RUNTIME_TARGET_SCHEMA_FORBIDDEN_ROUTINES = [
|
|
|
811
817
|
SESSION_TENANCY_QUIESCENCE_ROUTINE,
|
|
812
818
|
TENANCY_BACKFILL_ACTIVATION_EVIDENCE_ROUTINE,
|
|
813
819
|
VERIFIED_SIGNUP_TRIAL_SWITCH_SETTER_ROUTINE,
|
|
820
|
+
"set_credit_promotion_policy(jsonb, text, text)",
|
|
814
821
|
MANAGED_AUTH_NEW_SIGNUPS_SWITCH_SETTER_ROUTINE,
|
|
815
822
|
...DOCUMENT_MIGRATION_AUDIT_INTERNAL_ROUTINES
|
|
816
823
|
];
|
|
817
824
|
var RUNTIME_TARGET_SCHEMA_INVOKER_ROUTINES = [
|
|
825
|
+
"set_credit_promotion_policy(jsonb, text, text)",
|
|
818
826
|
CLAUDE_SNAPSHOT_VALIDATOR_ROUTINE,
|
|
819
827
|
"usage_allowance_period(jsonb, timestamp with time zone)",
|
|
820
828
|
"validate_usage_allowance_config(jsonb)",
|
|
@@ -904,6 +912,7 @@ var FORCE_RLS_TABLES = [
|
|
|
904
912
|
"connections",
|
|
905
913
|
"connector_action_policies",
|
|
906
914
|
"connector_action_requests",
|
|
915
|
+
"credit_debit_allocations",
|
|
907
916
|
"credit_ledger_entries",
|
|
908
917
|
"device_enrollment_requests",
|
|
909
918
|
"document_authority_reclassifications",
|
|
@@ -1468,6 +1477,7 @@ var RUNTIME_READ_INSERT_TABLES = [
|
|
|
1468
1477
|
"browser_revision_components",
|
|
1469
1478
|
"browser_revisions",
|
|
1470
1479
|
"company_profile_revisions",
|
|
1480
|
+
"credit_debit_allocations",
|
|
1471
1481
|
"editable_artifact_blob_refs",
|
|
1472
1482
|
"editable_artifact_idempotency_receipts",
|
|
1473
1483
|
"editable_artifact_live_outbox",
|
|
@@ -1785,10 +1795,6 @@ async function inspectRuntimeDatabasePosture(db, options) {
|
|
|
1785
1795
|
replication: identity.rolreplication,
|
|
1786
1796
|
bypassRls: identity.rolbypassrls
|
|
1787
1797
|
};
|
|
1788
|
-
const activationRows = resultRows(
|
|
1789
|
-
await tx.execute(sql`select session_tenancy_any_product_activation() as activated`)
|
|
1790
|
-
);
|
|
1791
|
-
const sessionTenancyProductActivationPresent = activationRows[0]?.activated === true;
|
|
1792
1798
|
const variableSetCutoverRows = resultRows(
|
|
1793
1799
|
await tx.execute(sql`
|
|
1794
1800
|
select to_regprocedure(
|
|
@@ -1814,7 +1820,6 @@ async function inspectRuntimeDatabasePosture(db, options) {
|
|
|
1814
1820
|
privateTables: [],
|
|
1815
1821
|
targetRoutines: [],
|
|
1816
1822
|
privateRoutines: [],
|
|
1817
|
-
sessionTenancyProductActivationPresent,
|
|
1818
1823
|
sessionVariableSetAttachmentsCutoverPresent,
|
|
1819
1824
|
claudeSubscriptionPoolActivationPresent
|
|
1820
1825
|
};
|
|
@@ -1917,25 +1922,31 @@ async function inspectRuntimeDatabasePosture(db, options) {
|
|
|
1917
1922
|
c.relforcerowsecurity as rls_forced,
|
|
1918
1923
|
row_security_active(c.oid) as rls_active,
|
|
1919
1924
|
(select count(*)::int from pg_policy policy where policy.polrelid = c.oid) as policy_count,
|
|
1920
|
-
-- Column-only grants on
|
|
1921
|
-
--
|
|
1925
|
+
-- Column-only grants on capability tables are also unsafe; a pin
|
|
1926
|
+
-- table must remain EXECUTE-only even after column ACL drift.
|
|
1922
1927
|
(has_table_privilege(current_user, c.oid, 'SELECT') or
|
|
1923
|
-
((c.relname in ('modal_inventory_read_capabilities','usage_allowance_capabilities','session_import_batches') or
|
|
1928
|
+
((c.relname in ('modal_inventory_read_capabilities','usage_allowance_capabilities','session_import_batches', ${ARTIFACT_PINS_TABLE}) or
|
|
1924
1929
|
c.relname in (select jsonb_array_elements_text(${JSON.stringify(RUNTIME_ALLOWANCE_PRIVATE_TABLES)}::jsonb))) and
|
|
1925
1930
|
has_any_column_privilege(current_user, c.oid, 'SELECT'))) as can_select,
|
|
1926
1931
|
(has_table_privilege(current_user, c.oid, 'INSERT') or
|
|
1927
|
-
((c.relname in ('modal_inventory_read_capabilities','usage_allowance_capabilities','session_import_batches') or
|
|
1932
|
+
((c.relname in ('modal_inventory_read_capabilities','usage_allowance_capabilities','session_import_batches', ${ARTIFACT_PINS_TABLE}) or
|
|
1928
1933
|
c.relname in (select jsonb_array_elements_text(${JSON.stringify(RUNTIME_ALLOWANCE_PRIVATE_TABLES)}::jsonb))) and
|
|
1929
1934
|
has_any_column_privilege(current_user, c.oid, 'INSERT'))) as can_insert,
|
|
1930
1935
|
(has_table_privilege(current_user, c.oid, 'UPDATE') or
|
|
1931
|
-
((c.relname in ('modal_inventory_read_capabilities','usage_allowance_capabilities','session_import_batches') or
|
|
1936
|
+
((c.relname in ('modal_inventory_read_capabilities','usage_allowance_capabilities','session_import_batches', ${ARTIFACT_PINS_TABLE}) or
|
|
1932
1937
|
c.relname in (select jsonb_array_elements_text(${JSON.stringify(RUNTIME_ALLOWANCE_PRIVATE_TABLES)}::jsonb))) and
|
|
1933
1938
|
has_any_column_privilege(current_user, c.oid, 'UPDATE'))) as can_update,
|
|
1934
1939
|
has_table_privilege(current_user, c.oid, 'DELETE') as can_delete,
|
|
1935
1940
|
has_table_privilege(current_user, c.oid, 'TRUNCATE') as can_truncate,
|
|
1936
1941
|
(has_table_privilege(current_user, c.oid, 'REFERENCES') or
|
|
1937
1942
|
has_any_column_privilege(current_user, c.oid, 'REFERENCES')) as can_references,
|
|
1938
|
-
has_table_privilege(current_user, c.oid, 'TRIGGER') as can_trigger
|
|
1943
|
+
has_table_privilege(current_user, c.oid, 'TRIGGER') as can_trigger,
|
|
1944
|
+
CASE WHEN c.relname = ${ARTIFACT_PINS_TABLE} THEN ARRAY(
|
|
1945
|
+
SELECT DISTINCT acl.privilege_type FROM aclexplode(coalesce(c.relacl, acldefault('r', c.relowner))) acl
|
|
1946
|
+
WHERE acl.privilege_type NOT IN ('SELECT','INSERT','UPDATE','DELETE','TRUNCATE','REFERENCES','TRIGGER')
|
|
1947
|
+
AND CASE WHEN acl.grantee = 0 THEN true ELSE pg_has_role(current_user, acl.grantee, 'USAGE') END
|
|
1948
|
+
ORDER BY acl.privilege_type
|
|
1949
|
+
) ELSE ARRAY[]::text[] END AS extra_privileges
|
|
1939
1950
|
from pg_class c
|
|
1940
1951
|
join pg_namespace n on n.oid = c.relnamespace
|
|
1941
1952
|
where n.nspname = 'opengeni_private'
|
|
@@ -1949,6 +1960,7 @@ async function inspectRuntimeDatabasePosture(db, options) {
|
|
|
1949
1960
|
${SCOPED_COMPUTE_CAPABILITY_TABLE},
|
|
1950
1961
|
${CONNECTION_TENANCY_BACKFILL_CAPABILITY_TABLE},
|
|
1951
1962
|
${SANDBOX_FILE_PUBLICATIONS_TABLE},
|
|
1963
|
+
${ARTIFACT_PINS_TABLE},
|
|
1952
1964
|
${SCHEDULED_SLACK_BOT_MESSAGES_TABLE},
|
|
1953
1965
|
${ORGANIZATION_SIGNUP_USE_CASES_TABLE},
|
|
1954
1966
|
${SLACK_FILE_UPLOAD_OPERATIONS_TABLE},
|
|
@@ -1969,6 +1981,7 @@ async function inspectRuntimeDatabasePosture(db, options) {
|
|
|
1969
1981
|
'modal_inventory_read_capabilities',
|
|
1970
1982
|
${AUTOMATIC_SESSION_TITLE_FANOUT_OUTBOX_TABLE},
|
|
1971
1983
|
${VERIFIED_SIGNUP_TRIAL_SWITCH_TABLE},
|
|
1984
|
+
'credit_promotion_policy_revisions',
|
|
1972
1985
|
${MANAGED_AUTH_NEW_SIGNUPS_SWITCH_TABLE}
|
|
1973
1986
|
)
|
|
1974
1987
|
`)
|
|
@@ -1985,7 +1998,8 @@ async function inspectRuntimeDatabasePosture(db, options) {
|
|
|
1985
1998
|
delete: row.can_delete,
|
|
1986
1999
|
truncate: row.can_truncate,
|
|
1987
2000
|
references: row.can_references,
|
|
1988
|
-
trigger: row.can_trigger
|
|
2001
|
+
trigger: row.can_trigger,
|
|
2002
|
+
...row.extra_privileges?.length ? { extraPrivileges: row.extra_privileges } : {}
|
|
1989
2003
|
}));
|
|
1990
2004
|
const targetRoutines = resultRows(
|
|
1991
2005
|
await tx.execute(sql`
|
|
@@ -2059,7 +2073,6 @@ async function inspectRuntimeDatabasePosture(db, options) {
|
|
|
2059
2073
|
privateTables,
|
|
2060
2074
|
targetRoutines,
|
|
2061
2075
|
privateRoutines,
|
|
2062
|
-
sessionTenancyProductActivationPresent,
|
|
2063
2076
|
sessionVariableSetAttachmentsCutoverPresent,
|
|
2064
2077
|
claudeSubscriptionPoolActivationPresent
|
|
2065
2078
|
};
|
|
@@ -2086,11 +2099,6 @@ function evaluateRuntimeDatabasePosture(posture, options) {
|
|
|
2086
2099
|
if (!posture.sessionVariableSetAttachmentsCutoverPresent) {
|
|
2087
2100
|
violations.push("database is missing the 0352 session Variable Set attachment runtime receipt");
|
|
2088
2101
|
}
|
|
2089
|
-
if (posture.sessionTenancyProductActivationPresent && options.organizationTenancyCanonicalActivationEnabled !== true) {
|
|
2090
|
-
violations.push(
|
|
2091
|
-
"session-tenancy product activation is durable but OPENGENI_ORGANIZATION_TENANCY_CANONICAL_ACTIVATION_ENABLED is not true"
|
|
2092
|
-
);
|
|
2093
|
-
}
|
|
2094
2102
|
if (!identity.currentUser || !identity.sessionUser) {
|
|
2095
2103
|
violations.push("database identity is empty");
|
|
2096
2104
|
}
|
|
@@ -3408,6 +3416,17 @@ function evaluateRuntimeDatabasePosture(posture, options) {
|
|
|
3408
3416
|
if (posture.privateRoutines.length === 0) {
|
|
3409
3417
|
violations.push("opengeni_private has no helper routines");
|
|
3410
3418
|
}
|
|
3419
|
+
const creditPolicyTable = posture.privateTables.find(
|
|
3420
|
+
(table) => table.name === "credit_promotion_policy_revisions"
|
|
3421
|
+
);
|
|
3422
|
+
if (!creditPolicyTable) {
|
|
3423
|
+
violations.push("credit promotion policy table is missing");
|
|
3424
|
+
} else if (!creditPolicyTable.select) {
|
|
3425
|
+
violations.push("runtime role cannot read the credit promotion policy");
|
|
3426
|
+
}
|
|
3427
|
+
if (creditPolicyTable && (creditPolicyTable.owner === expectedRole || creditPolicyTable.insert || creditPolicyTable.update || creditPolicyTable.delete)) {
|
|
3428
|
+
violations.push("runtime role has forbidden write authority on the credit promotion policy");
|
|
3429
|
+
}
|
|
3411
3430
|
const trialSwitchTable = posture.privateTables.find(
|
|
3412
3431
|
(table) => table.name === VERIFIED_SIGNUP_TRIAL_SWITCH_TABLE
|
|
3413
3432
|
);
|
|
@@ -3504,6 +3523,29 @@ function evaluateRuntimeDatabasePosture(posture, options) {
|
|
|
3504
3523
|
}
|
|
3505
3524
|
}
|
|
3506
3525
|
}
|
|
3526
|
+
const pinTables = posture.privateTables.filter((table) => table.name === ARTIFACT_PINS_TABLE);
|
|
3527
|
+
if (pinTables.length !== 1) {
|
|
3528
|
+
if (!options.protectedTables)
|
|
3529
|
+
violations.push("artifact pin private relation is missing or ambiguous");
|
|
3530
|
+
} else {
|
|
3531
|
+
const table = pinTables[0];
|
|
3532
|
+
if (!table.rlsEnabled || !table.rlsForced || !table.rlsActive || (table.policyCount ?? 0) < 1)
|
|
3533
|
+
violations.push("artifact pin relation lacks active FORCE-RLS workspace isolation");
|
|
3534
|
+
if (table.select || table.insert || table.update || table.delete || table.truncate || table.references || table.trigger || table.extraPrivileges?.length || table.owner === expectedRole)
|
|
3535
|
+
violations.push("runtime role has forbidden direct artifact pin authority");
|
|
3536
|
+
if (tableByName.get("files")?.owner && table.owner !== tableByName.get("files").owner)
|
|
3537
|
+
violations.push("artifact pin owner does not match workspace authority");
|
|
3538
|
+
const quotedSchema = `"${targetSchema.replaceAll('"', '""')}"`;
|
|
3539
|
+
const searchPaths = /* @__PURE__ */ new Set([
|
|
3540
|
+
`search_path=pg_catalog, ${quotedSchema}, pg_temp`,
|
|
3541
|
+
`search_path=pg_catalog, ${/^[a-z_][a-z0-9_]*$/.test(targetSchema) ? targetSchema : quotedSchema}, pg_temp`
|
|
3542
|
+
]);
|
|
3543
|
+
for (const name of ARTIFACT_PIN_RUNTIME_ROUTINES) {
|
|
3544
|
+
const routines = posture.privateRoutines.filter((routine) => routine.name === name);
|
|
3545
|
+
if (routines.length !== 1 || !routines[0].execute || routines[0].publicExecute || !routines[0].securityDefiner || routines[0].owner !== table.owner || !routines[0].configuration?.some((configuration) => searchPaths.has(configuration)))
|
|
3546
|
+
violations.push(`artifact pin capability ${name} is missing or unsafe`);
|
|
3547
|
+
}
|
|
3548
|
+
}
|
|
3507
3549
|
const slackFileUploadTables = posture.privateTables.filter(
|
|
3508
3550
|
(table) => table.name === SLACK_FILE_UPLOAD_OPERATIONS_TABLE
|
|
3509
3551
|
);
|
|
@@ -5265,6 +5307,10 @@ BEGIN
|
|
|
5265
5307
|
END IF;
|
|
5266
5308
|
-- The trial-credit kill switch setter is operator-only (migration owner).
|
|
5267
5309
|
-- Reprovisioning repairs any accidental runtime or PUBLIC grant.
|
|
5310
|
+
IF to_regprocedure(format('%I.set_credit_promotion_policy(jsonb,text,text)', ${literal(schema)})) IS NOT NULL THEN
|
|
5311
|
+
EXECUTE format('REVOKE ALL ON FUNCTION %I.set_credit_promotion_policy(jsonb,text,text) FROM PUBLIC', ${literal(schema)});
|
|
5312
|
+
EXECUTE format('REVOKE ALL ON FUNCTION %I.set_credit_promotion_policy(jsonb,text,text) FROM %I', ${literal(schema)}, ${literal(role)});
|
|
5313
|
+
END IF;
|
|
5268
5314
|
IF to_regprocedure(
|
|
5269
5315
|
format('%I.set_verified_signup_trial_credits_enabled(boolean,text,text)', ${literal(schema)})
|
|
5270
5316
|
) IS NOT NULL THEN
|
|
@@ -5746,6 +5792,11 @@ BEGIN
|
|
|
5746
5792
|
REVOKE ALL (singleton, consent_enabled, release_evidence) ON TABLE opengeni_private.sandbox_recovery_rollout FROM PUBLIC;
|
|
5747
5793
|
EXECUTE format('GRANT SELECT ON TABLE opengeni_private.sandbox_recovery_rollout TO %I', ${literal(role)});
|
|
5748
5794
|
END IF;
|
|
5795
|
+
IF to_regclass('opengeni_private.credit_promotion_policy_revisions') IS NOT NULL THEN
|
|
5796
|
+
EXECUTE format('REVOKE ALL ON TABLE opengeni_private.credit_promotion_policy_revisions FROM %I', ${literal(role)});
|
|
5797
|
+
REVOKE ALL ON TABLE opengeni_private.credit_promotion_policy_revisions FROM PUBLIC;
|
|
5798
|
+
EXECUTE format('GRANT SELECT ON TABLE opengeni_private.credit_promotion_policy_revisions TO %I', ${literal(role)});
|
|
5799
|
+
END IF;
|
|
5749
5800
|
IF to_regclass('opengeni_private.verified_signup_trial_switch_revisions') IS NOT NULL THEN
|
|
5750
5801
|
-- Read-only for the operator gauge. Only the owner-only audited setter
|
|
5751
5802
|
-- appends revisions; runtime identities and PUBLIC never write them.
|
|
@@ -5799,6 +5850,22 @@ BEGIN
|
|
|
5799
5850
|
REVOKE ALL ON FUNCTION opengeni_private.record_sandbox_file_publication(uuid,uuid,uuid,uuid) FROM PUBLIC;
|
|
5800
5851
|
REVOKE ALL ON FUNCTION opengeni_private.list_sandbox_file_publications(uuid,uuid,jsonb) FROM PUBLIC;
|
|
5801
5852
|
END IF;
|
|
5853
|
+
IF to_regclass('opengeni_private.artifact_catalog_pins') IS NOT NULL THEN
|
|
5854
|
+
EXECUTE format('REVOKE ALL ON TABLE opengeni_private.artifact_catalog_pins FROM %I', ${literal(role)});
|
|
5855
|
+
-- Table revocation does not remove column ACLs. Reconcile every current
|
|
5856
|
+
-- column for both the runtime and PUBLIC, including future additions.
|
|
5857
|
+
EXECUTE format('REVOKE ALL (%s) ON TABLE opengeni_private.artifact_catalog_pins FROM %I',
|
|
5858
|
+
(SELECT string_agg(quote_ident(attname),',' ORDER BY attnum) FROM pg_attribute
|
|
5859
|
+
WHERE attrelid='opengeni_private.artifact_catalog_pins'::regclass AND attnum>0 AND NOT attisdropped),
|
|
5860
|
+
${literal(role)});
|
|
5861
|
+
REVOKE ALL ON TABLE opengeni_private.artifact_catalog_pins FROM PUBLIC;
|
|
5862
|
+
EXECUTE format('REVOKE ALL (%s) ON TABLE opengeni_private.artifact_catalog_pins FROM PUBLIC',
|
|
5863
|
+
(SELECT string_agg(quote_ident(attname),',' ORDER BY attnum) FROM pg_attribute
|
|
5864
|
+
WHERE attrelid='opengeni_private.artifact_catalog_pins'::regclass AND attnum>0 AND NOT attisdropped));
|
|
5865
|
+
REVOKE ALL ON FUNCTION opengeni_private.update_artifact_pin(uuid,uuid,text,text,boolean),
|
|
5866
|
+
opengeni_private.list_artifact_pins(uuid,uuid),
|
|
5867
|
+
opengeni_private.list_sandbox_file_publications_pinned(uuid,uuid,jsonb) FROM PUBLIC;
|
|
5868
|
+
END IF;
|
|
5802
5869
|
IF to_regclass('opengeni_private.slack_file_upload_operations') IS NOT NULL THEN
|
|
5803
5870
|
-- Ordinary RLS repositories own the upload CAS, not owner capabilities.
|
|
5804
5871
|
-- Never allow deletion/truncation to erase its durable completion fence.
|
|
@@ -6043,6 +6110,7 @@ if (import.meta.main) {
|
|
|
6043
6110
|
|
|
6044
6111
|
export {
|
|
6045
6112
|
SANDBOX_FILE_PUBLICATION_RUNTIME_ROUTINES,
|
|
6113
|
+
ARTIFACT_PIN_RUNTIME_ROUTINES,
|
|
6046
6114
|
SCHEDULED_SLACK_BOT_MESSAGE_RUNTIME_ROUTINES,
|
|
6047
6115
|
ORGANIZATION_SIGNUP_USE_CASE_RUNTIME_ROUTINES,
|
|
6048
6116
|
SLACK_FILE_UPLOAD_OPERATIONS_TABLE,
|
|
@@ -6072,4 +6140,4 @@ export {
|
|
|
6072
6140
|
runtimeDatabaseReadyCheck,
|
|
6073
6141
|
provisionRoles
|
|
6074
6142
|
};
|
|
6075
|
-
//# sourceMappingURL=chunk-
|
|
6143
|
+
//# sourceMappingURL=chunk-YOYILDLY.js.map
|