@opengeni/db 0.28.9 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (225) hide show
  1. package/dist/attached-browser-devices.d.ts +42 -0
  2. package/dist/attempt-tool-catalogs.d.ts +16 -0
  3. package/dist/browser-auth.d.ts +299 -0
  4. package/dist/browser-downloads.d.ts +51 -0
  5. package/dist/browser-identities.d.ts +137 -0
  6. package/dist/browser-sessions.d.ts +354 -0
  7. package/dist/browser-state-artifacts.d.ts +91 -0
  8. package/dist/canonical-human-identities.d.ts +48 -0
  9. package/dist/canonical-human-identities.js +28 -0
  10. package/dist/canonical-human-identities.js.map +1 -0
  11. package/dist/capability-components.d.ts +37 -0
  12. package/dist/capability-integrations.d.ts +194 -0
  13. package/dist/chunk-5KTIEDX7.js +13200 -0
  14. package/dist/chunk-5KTIEDX7.js.map +1 -0
  15. package/dist/chunk-CQZ4QSP5.js +995 -0
  16. package/dist/chunk-CQZ4QSP5.js.map +1 -0
  17. package/dist/chunk-F32YT7MP.js +117 -0
  18. package/dist/chunk-F32YT7MP.js.map +1 -0
  19. package/dist/chunk-JC5QPLUM.js +666 -0
  20. package/dist/chunk-JC5QPLUM.js.map +1 -0
  21. package/dist/chunk-P3RE4D2B.js +3535 -0
  22. package/dist/chunk-P3RE4D2B.js.map +1 -0
  23. package/dist/chunk-TAUTWOS5.js +259 -0
  24. package/dist/chunk-TAUTWOS5.js.map +1 -0
  25. package/dist/chunk-VKLB2ZGI.js +2389 -0
  26. package/dist/chunk-VKLB2ZGI.js.map +1 -0
  27. package/dist/codemode-operations.d.ts +117 -0
  28. package/dist/codex-token-resolver.d.ts +2 -2
  29. package/dist/company-profile-schema.d.ts +798 -0
  30. package/dist/company-profile.d.ts +268 -0
  31. package/dist/computer-sessions.d.ts +109 -0
  32. package/dist/connection-token-resolver.d.ts +9 -4
  33. package/dist/database.d.ts +57 -3
  34. package/dist/editable-artifact-durable-export.d.ts +153 -0
  35. package/dist/editable-artifact-durable-export.js +788 -0
  36. package/dist/editable-artifact-durable-export.js.map +1 -0
  37. package/dist/editable-artifact-materialization.d.ts +123 -0
  38. package/dist/editable-artifacts-schema.d.ts +4152 -0
  39. package/dist/editable-artifacts.d.ts +610 -0
  40. package/dist/editable-artifacts.js +26 -0
  41. package/dist/editable-artifacts.js.map +1 -0
  42. package/dist/generated-images.d.ts +139 -0
  43. package/dist/index.d.ts +1122 -126
  44. package/dist/index.js +42329 -18407
  45. package/dist/index.js.map +1 -1
  46. package/dist/insights.d.ts +73 -10
  47. package/dist/integration-bindings.d.ts +70 -0
  48. package/dist/integration-facets.d.ts +99 -0
  49. package/dist/interaction-revisions.d.ts +14 -0
  50. package/dist/interaction-schema.d.ts +6036 -0
  51. package/dist/knowledge-source-sync-schema.d.ts +1679 -0
  52. package/dist/knowledge-source-sync.d.ts +274 -0
  53. package/dist/memory-governance.d.ts +2 -2
  54. package/dist/memory-slack-delivery.d.ts +101 -0
  55. package/dist/new-session-drafts.d.ts +2 -2
  56. package/dist/pack-components.d.ts +76 -0
  57. package/dist/pack-installations.d.ts +86 -0
  58. package/dist/persistence-errors.d.ts +3 -3
  59. package/dist/plugin-packages.d.ts +126 -0
  60. package/dist/preference-registry.d.ts +1 -1
  61. package/dist/provision-roles.d.ts +9 -1
  62. package/dist/provision-roles.js +1 -1
  63. package/dist/runtime-posture.d.ts +19 -6
  64. package/dist/schema.d.ts +22654 -9359
  65. package/dist/schema.js +209 -3
  66. package/dist/scoped-knowledge.d.ts +97 -1
  67. package/dist/session-control.d.ts +33 -7
  68. package/dist/session-queue-commands.d.ts +19 -11
  69. package/dist/session-realtime-context.d.ts +2 -2
  70. package/dist/session-realtime-ledger.d.ts +4 -4
  71. package/dist/session-realtime-mirror.d.ts +2 -2
  72. package/dist/session-realtime-state.d.ts +1 -1
  73. package/dist/session-realtime-terminal.d.ts +1 -1
  74. package/dist/session-realtime.d.ts +7 -7
  75. package/dist/session-tenancy.d.ts +44 -0
  76. package/dist/session-tenancy.js +16 -0
  77. package/dist/session-tenancy.js.map +1 -0
  78. package/dist/session-tool-call-settlement.d.ts +1 -1
  79. package/dist/slack-task-policy-schema.d.ts +847 -0
  80. package/dist/slack-task-policy.d.ts +65 -0
  81. package/dist/slack-user-link-access.d.ts +54 -0
  82. package/dist/task-notes-schema.d.ts +924 -0
  83. package/dist/task-notes.d.ts +85 -0
  84. package/dist/transcription-recordings.d.ts +2 -2
  85. package/dist/turn-initiator.d.ts +2 -2
  86. package/dist/video-generation.d.ts +225 -0
  87. package/dist/video-generation.js +68 -0
  88. package/dist/video-generation.js.map +1 -0
  89. package/dist/workspace-artifacts.d.ts +1 -1
  90. package/dist/workspace-instruction-policies.d.ts +1 -1
  91. package/dist/workspace-learning-policy-schema.d.ts +932 -0
  92. package/dist/workspace-learning-policy.d.ts +161 -0
  93. package/dist/xai-subscription.d.ts +326 -0
  94. package/drizzle/0183_model_call_provider_cost_estimates.sql +39 -0
  95. package/drizzle/0184_sandbox_drain_teardown_fence.sql +682 -0
  96. package/drizzle/0185_temporal_schedule_cleanup_outbox.sql +168 -0
  97. package/drizzle/0186_sandbox_capture_provider_contract.sql +400 -0
  98. package/drizzle/0187_generated_image_artifacts.sql +173 -0
  99. package/drizzle/0188_image_generation_retention_failure.sql +25 -0
  100. package/drizzle/0189_retained_session_image_formats.sql +13 -0
  101. package/drizzle/0190_timeline_annotations.sql +31 -0
  102. package/drizzle/0191_editable_artifact_engine.sql +3853 -0
  103. package/drizzle/0192_editable_artifact_live_tickets.sql +338 -0
  104. package/drizzle/0193_editable_artifact_authorization.sql +190 -0
  105. package/drizzle/0194_editable_artifact_durable_exports.sql +160 -0
  106. package/drizzle/0195_editable_artifact_import_authorization.sql +203 -0
  107. package/drizzle/0196_rig_provider_images.sql +152 -0
  108. package/drizzle/0197_knowledge_source_sync_schedules.sql +523 -0
  109. package/drizzle/0198_memory_slack_publication_delivery.sql +393 -0
  110. package/drizzle/0199_workspace_learning_policy.sql +980 -0
  111. package/drizzle/0201_company_profile_authority.sql +849 -0
  112. package/drizzle/0202_document_index_checkpoints.sql +85 -0
  113. package/drizzle/0203_durable_video_generation.sql +353 -0
  114. package/drizzle/0204_video_generation_funding.sql +44 -0
  115. package/drizzle/0205_attempt_tool_catalogs.sql +230 -0
  116. package/drizzle/0206_browser_sessions.sql +646 -0
  117. package/drizzle/0207_browser_identities.sql +379 -0
  118. package/drizzle/0208_attached_browser_devices.sql +165 -0
  119. package/drizzle/0209_computer_sessions.sql +575 -0
  120. package/drizzle/0210_browser_auth_network_interventions.sql +441 -0
  121. package/drizzle/0211_editable_artifact_session_links.sql +58 -0
  122. package/drizzle/0212_browser_state_transfer_hardening.sql +560 -0
  123. package/drizzle/0212_slack_installation_bindings.sql +348 -0
  124. package/drizzle/0213_browser_interaction_authority.sql +67 -0
  125. package/drizzle/0213_slack_user_link_access_requests.sql +177 -0
  126. package/drizzle/0214_browser_download_saves.sql +34 -0
  127. package/drizzle/0214_session_activity_commit_gate.sql +262 -0
  128. package/drizzle/0215_browser_controller_host.sql +385 -0
  129. package/drizzle/0215_capabilities_platform.sql +980 -0
  130. package/drizzle/0216_browser_auth_health_evidence.sql +137 -0
  131. package/drizzle/0216_pack_component_ownership.sql +235 -0
  132. package/drizzle/0217_capability_definition_delete_authority.sql +32 -0
  133. package/drizzle/0217_external_browser_auth_operations.sql +22 -0
  134. package/drizzle/0218_organization_tenancy_foundation.sql +299 -0
  135. package/drizzle/0219_organization_tenancy_managed_human_provisioning.sql +317 -0
  136. package/drizzle/0219_site_auth_maintenance_sessions.sql +234 -0
  137. package/drizzle/0220_memory_slack_append_only_cascade.sql +38 -0
  138. package/drizzle/0220_session_channels.sql +54 -0
  139. package/drizzle/0221_sessions_channel_index.sql +5 -0
  140. package/drizzle/0222_session_visibility_authority_epochs.sql +158 -0
  141. package/drizzle/0222_sessions_channel_fk.sql +89 -0
  142. package/drizzle/0223_pending_tool_event_output.sql +55 -0
  143. package/drizzle/0223_sessions_channel_fk_validate.sql +118 -0
  144. package/drizzle/0224_slack_post_outcome_reconciliation.sql +123 -0
  145. package/drizzle/0225_session_visibility_fork_activation.sql +1363 -0
  146. package/drizzle/0226_personal_codex_authority_foundation.sql +365 -0
  147. package/drizzle/0227_slack_native_actions.sql +145 -0
  148. package/drizzle/0228_interaction_controller_data_plane.sql +14 -0
  149. package/drizzle/0228_slack_task_policy.sql +400 -0
  150. package/drizzle/0229_slack_inbox_file_fact.sql +10 -0
  151. package/drizzle/0230_user_scoped_variable_sets_rigs.sql +84 -0
  152. package/drizzle/0231_integration_definition_identity_cutover.sql +271 -0
  153. package/drizzle/0232_integration_facet_authority_cutover.sql +610 -0
  154. package/drizzle/0233_skill_and_integration_authority_cutover.sql +1162 -0
  155. package/drizzle/0234_xai_subscription_authority.sql +1139 -0
  156. package/drizzle/0235_canonical_human_login_bindings.sql +920 -0
  157. package/drizzle/0236_browser_identity_lifecycle.sql +39 -0
  158. package/drizzle/0236_session_visibility_slack_policy.sql +72 -0
  159. package/drizzle/0237_interaction_transition_reaper.sql +263 -0
  160. package/drizzle/0238_goal_persistence_policy.sql +471 -0
  161. package/drizzle/0238_supergrok_realtime_model.sql +29 -0
  162. package/drizzle/0239_supergrok_video_funding.sql +50 -0
  163. package/drizzle/0239_task_tree_notes.sql +990 -0
  164. package/package.json +26 -5
  165. package/src/attached-browser-devices.ts +371 -0
  166. package/src/attempt-tool-catalogs.ts +131 -0
  167. package/src/browser-auth.ts +4373 -0
  168. package/src/browser-downloads.ts +517 -0
  169. package/src/browser-identities.ts +1385 -0
  170. package/src/browser-sessions.ts +2294 -0
  171. package/src/browser-state-artifacts.ts +449 -0
  172. package/src/canonical-human-identities.ts +317 -0
  173. package/src/capability-components.ts +166 -0
  174. package/src/capability-integrations.ts +1571 -0
  175. package/src/codemode-operations.ts +674 -0
  176. package/src/company-profile-schema.ts +143 -0
  177. package/src/company-profile.ts +968 -0
  178. package/src/computer-sessions.ts +1130 -0
  179. package/src/connection-token-resolver.ts +270 -25
  180. package/src/database.ts +468 -24
  181. package/src/editable-artifact-durable-export.ts +1201 -0
  182. package/src/editable-artifact-materialization.ts +893 -0
  183. package/src/editable-artifacts-schema.ts +879 -0
  184. package/src/editable-artifacts.ts +5404 -0
  185. package/src/generated-images.ts +740 -0
  186. package/src/index.ts +9963 -1465
  187. package/src/insights.ts +251 -23
  188. package/src/integration-bindings.ts +455 -0
  189. package/src/integration-facets.ts +862 -0
  190. package/src/interaction-revisions.ts +70 -0
  191. package/src/interaction-schema.ts +1606 -0
  192. package/src/knowledge-source-sync-schema.ts +192 -0
  193. package/src/knowledge-source-sync.ts +1922 -0
  194. package/src/memory-slack-delivery.ts +801 -0
  195. package/src/pack-components.ts +954 -0
  196. package/src/pack-installations.ts +886 -0
  197. package/src/persistence-errors.ts +4 -7
  198. package/src/plugin-packages.ts +1186 -0
  199. package/src/provision-roles.ts +534 -1
  200. package/src/runtime-posture-cli.ts +9 -0
  201. package/src/runtime-posture.ts +721 -5
  202. package/src/schema.ts +6270 -3159
  203. package/src/scoped-knowledge-schema.ts +1 -1
  204. package/src/scoped-knowledge.ts +655 -3
  205. package/src/session-control.ts +130 -42
  206. package/src/session-queue-commands.ts +265 -15
  207. package/src/session-realtime-context.ts +2 -2
  208. package/src/session-realtime-ledger.ts +3 -3
  209. package/src/session-realtime.ts +7 -7
  210. package/src/session-tenancy.ts +188 -0
  211. package/src/session-tool-call-settlement.ts +18 -3
  212. package/src/slack-task-policy-schema.ts +130 -0
  213. package/src/slack-task-policy.ts +341 -0
  214. package/src/slack-user-link-access.ts +702 -0
  215. package/src/task-notes-schema.ts +135 -0
  216. package/src/task-notes.ts +178 -0
  217. package/src/video-generation.ts +1530 -0
  218. package/src/workspace-artifacts.ts +1 -1
  219. package/src/workspace-learning-policy-schema.ts +139 -0
  220. package/src/workspace-learning-policy.ts +595 -0
  221. package/src/xai-subscription.ts +1887 -0
  222. package/dist/chunk-P6CUHXQZ.js +0 -7248
  223. package/dist/chunk-P6CUHXQZ.js.map +0 -1
  224. package/dist/chunk-VHBFHMPC.js +0 -1219
  225. package/dist/chunk-VHBFHMPC.js.map +0 -1
@@ -0,0 +1,666 @@
1
+ import {
2
+ LOSSLESS_CONTENT_WRITER_APPLICATION_NAME,
3
+ schema_exports,
4
+ sessions,
5
+ workspaceSessionActivityRevisions,
6
+ workspaces
7
+ } from "./chunk-5KTIEDX7.js";
8
+
9
+ // src/persistence-errors.ts
10
+ var SQLSTATE_KEYS = ["sqlState", "sqlstate", "code"];
11
+ var NESTED_ERROR_KEYS = ["cause", "original", "driverError", "error", "errors"];
12
+ var DATABASE_ERROR_NAMES = /* @__PURE__ */ new Set(["DatabaseError", "DrizzleQueryError", "PostgresError"]);
13
+ var DATABASE_DIAGNOSTIC_KEYS = [
14
+ "severity",
15
+ "schema_name",
16
+ "table_name",
17
+ "column_name",
18
+ "data_type_name",
19
+ "constraint_name",
20
+ "routine"
21
+ ];
22
+ var SAFE_FACT_KEYS = [
23
+ ["severity", "severity"],
24
+ ["schema_name", "schema"],
25
+ ["schema", "schema"],
26
+ ["table_name", "table"],
27
+ ["table", "table"],
28
+ ["column_name", "column"],
29
+ ["column", "column"],
30
+ ["data_type_name", "dataType"],
31
+ ["dataType", "dataType"],
32
+ ["constraint_name", "constraint"],
33
+ ["constraint", "constraint"],
34
+ ["routine", "routine"]
35
+ ];
36
+ function isRecord(value) {
37
+ return Boolean(value && typeof value === "object");
38
+ }
39
+ function safeFact(value) {
40
+ if (typeof value !== "string" || value.length === 0) return void 0;
41
+ return value;
42
+ }
43
+ function nestedPostgresSqlState(error) {
44
+ const queue = [error];
45
+ const seen = /* @__PURE__ */ new Set();
46
+ let fallback = null;
47
+ while (queue.length > 0 && seen.size < 64) {
48
+ const current = queue.shift();
49
+ if (!isRecord(current) || seen.has(current)) continue;
50
+ seen.add(current);
51
+ for (const key of SQLSTATE_KEYS) {
52
+ const value = current[key];
53
+ if (typeof value !== "string" || !/^[0-9A-Z]{5}$/i.test(value)) continue;
54
+ const normalized = value.toUpperCase();
55
+ if (normalized === "40P01" || normalized === "40001") return normalized;
56
+ fallback ??= normalized;
57
+ }
58
+ for (const key of NESTED_ERROR_KEYS) {
59
+ const nested = current[key];
60
+ if (Array.isArray(nested)) queue.push(...nested);
61
+ else if (nested !== void 0) queue.push(nested);
62
+ }
63
+ }
64
+ return fallback;
65
+ }
66
+ function databaseFailureCode(sqlState) {
67
+ if (sqlState === "40P01") return "db_deadlock";
68
+ if (sqlState === "40001") return "db_serialization_failure";
69
+ return "db_failure";
70
+ }
71
+ function isRetryablePersistenceSqlState(sqlState) {
72
+ return sqlState === "40P01" || sqlState === "40001";
73
+ }
74
+ function isDatabasePersistenceFailure(error) {
75
+ if (nestedPostgresSqlState(error) !== null) return true;
76
+ const queue = [error];
77
+ const seen = /* @__PURE__ */ new Set();
78
+ while (queue.length > 0 && seen.size < 64) {
79
+ const current = queue.shift();
80
+ if (!isRecord(current) || seen.has(current)) continue;
81
+ seen.add(current);
82
+ if (typeof current.name === "string" && DATABASE_ERROR_NAMES.has(current.name)) {
83
+ return true;
84
+ }
85
+ if (typeof current.query === "string" && (Object.hasOwn(current, "params") || Object.hasOwn(current, "parameters"))) {
86
+ return true;
87
+ }
88
+ if (DATABASE_DIAGNOSTIC_KEYS.some((key) => Object.hasOwn(current, key))) {
89
+ return true;
90
+ }
91
+ for (const key of NESTED_ERROR_KEYS) {
92
+ const nested = current[key];
93
+ if (Array.isArray(nested)) queue.push(...nested);
94
+ else if (nested !== void 0) queue.push(nested);
95
+ }
96
+ }
97
+ return false;
98
+ }
99
+ function safeDatabaseErrorFacts(error) {
100
+ const queue = [error];
101
+ const seen = /* @__PURE__ */ new Set();
102
+ const facts = {};
103
+ while (queue.length > 0 && seen.size < 64) {
104
+ const current = queue.shift();
105
+ if (!isRecord(current) || seen.has(current)) continue;
106
+ seen.add(current);
107
+ for (const [source, destination] of SAFE_FACT_KEYS) {
108
+ if (facts[destination] !== void 0) continue;
109
+ const value = safeFact(current[source]);
110
+ if (value !== void 0) facts[destination] = value;
111
+ }
112
+ for (const key of NESTED_ERROR_KEYS) {
113
+ const nested = current[key];
114
+ if (Array.isArray(nested)) queue.push(...nested);
115
+ else if (nested !== void 0) queue.push(nested);
116
+ }
117
+ }
118
+ return facts;
119
+ }
120
+ var SessionEventPersistenceError = class extends Error {
121
+ constructor(details, cause) {
122
+ const label = details.code === "db_deadlock" ? "Database deadlock" : details.code === "db_serialization_failure" ? "Database serialization failure" : "Database failure";
123
+ const operation = `${label} while persisting ${details.eventTypes.join(", ") || "session events"}`;
124
+ super(operation, cause === void 0 ? void 0 : { cause });
125
+ this.details = details;
126
+ }
127
+ name = "SessionEventPersistenceError";
128
+ get code() {
129
+ return this.details.code;
130
+ }
131
+ };
132
+ function isSessionEventPersistenceError(error) {
133
+ return error instanceof SessionEventPersistenceError;
134
+ }
135
+ async function runIdempotentPersistenceTransaction(options, transaction) {
136
+ const maxAttempts = options.maxAttempts ?? 3;
137
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
138
+ throw new Error("Persistence maxAttempts must be a positive integer");
139
+ }
140
+ const correlationId = options.correlationId ?? crypto.randomUUID();
141
+ const eventTypes = [...new Set(options.eventTypes ?? [])].sort();
142
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
143
+ try {
144
+ return await transaction(attempt);
145
+ } catch (error) {
146
+ const sqlState = nestedPostgresSqlState(error);
147
+ const retryable = isRetryablePersistenceSqlState(sqlState);
148
+ if (retryable && attempt < maxAttempts) {
149
+ await options.onRetry?.({
150
+ attempt,
151
+ sqlState
152
+ });
153
+ continue;
154
+ }
155
+ if (!isDatabasePersistenceFailure(error)) throw error;
156
+ throw new SessionEventPersistenceError(
157
+ {
158
+ code: databaseFailureCode(sqlState),
159
+ sqlState,
160
+ stage: options.stage,
161
+ eventTypes,
162
+ correlationId,
163
+ attempts: attempt,
164
+ retryOutcome: retryable ? "exhausted" : "not_retryable",
165
+ database: safeDatabaseErrorFacts(error)
166
+ },
167
+ error
168
+ );
169
+ }
170
+ }
171
+ throw new Error("Unreachable persistence retry state");
172
+ }
173
+
174
+ // src/database.ts
175
+ import { AsyncLocalStorage } from "async_hooks";
176
+ import { eq, sql } from "drizzle-orm";
177
+ import { drizzle } from "drizzle-orm/postgres-js";
178
+ import postgres from "postgres";
179
+ var sessionRlsActorContext = new AsyncLocalStorage();
180
+ async function withSessionRlsActorContext(actor, fn) {
181
+ if (!actor.subjectId.trim()) {
182
+ throw new Error("withSessionRlsActorContext: a non-empty subjectId is required");
183
+ }
184
+ if (actor.initiatingHumanSubjectId !== void 0 && actor.initiatingHumanSubjectId !== null && !actor.initiatingHumanSubjectId.trim()) {
185
+ throw new Error(
186
+ "withSessionRlsActorContext: initiatingHumanSubjectId must be null or non-empty"
187
+ );
188
+ }
189
+ return await sessionRlsActorContext.run(actor, fn);
190
+ }
191
+ var dbBindings = /* @__PURE__ */ new WeakMap();
192
+ function rlsStrategyFor(db) {
193
+ return dbBindings.get(db)?.rlsStrategy ?? "force";
194
+ }
195
+ async function rawRows(executor, query) {
196
+ const result = await executor.execute(query);
197
+ if (Array.isArray(result)) {
198
+ return result;
199
+ }
200
+ const rows = result.rows;
201
+ if (Array.isArray(rows)) {
202
+ return rows;
203
+ }
204
+ throw new Error("Unsupported database execute() result shape");
205
+ }
206
+ var SandboxProviderReadLockUnavailableError = class extends Error {
207
+ constructor() {
208
+ super("Sandbox provider reads are temporarily busy. Retry the request.");
209
+ this.name = "SandboxProviderReadLockUnavailableError";
210
+ }
211
+ };
212
+ var SANDBOX_PROVIDER_READ_LOCK_WAIT_MS = 15e3;
213
+ var SANDBOX_PROVIDER_READ_LOCK_POLL_MAX_MS = 200;
214
+ function sandboxProviderReadLockKey(identity) {
215
+ return [
216
+ "sandbox-provider-read",
217
+ identity.workspaceId,
218
+ identity.sandboxGroupId,
219
+ identity.leaseEpoch,
220
+ identity.instanceId
221
+ ].join(":");
222
+ }
223
+ async function waitForSandboxProviderReadLockPoll(delayMs, signal) {
224
+ if (signal?.aborted) {
225
+ throw signal.reason ?? new DOMException("The operation was aborted", "AbortError");
226
+ }
227
+ await new Promise((resolve, reject) => {
228
+ let settled = false;
229
+ let timer;
230
+ const cleanup = () => signal?.removeEventListener("abort", abort);
231
+ const finish = () => {
232
+ if (settled) return;
233
+ settled = true;
234
+ cleanup();
235
+ resolve();
236
+ };
237
+ const abort = () => {
238
+ if (settled) return;
239
+ settled = true;
240
+ clearTimeout(timer);
241
+ cleanup();
242
+ reject(signal?.reason ?? new DOMException("The operation was aborted", "AbortError"));
243
+ };
244
+ timer = setTimeout(finish, delayMs);
245
+ signal?.addEventListener("abort", abort, { once: true });
246
+ if (signal?.aborted) abort();
247
+ });
248
+ }
249
+ async function withSandboxProviderReadLock(db, identity, signal, fn) {
250
+ const key = sandboxProviderReadLockKey(identity);
251
+ const deadline = Date.now() + SANDBOX_PROVIDER_READ_LOCK_WAIT_MS;
252
+ return await db.transaction(async (lockedDb) => {
253
+ let pollMs = 20;
254
+ while (true) {
255
+ if (signal?.aborted) {
256
+ throw signal.reason ?? new DOMException("The operation was aborted", "AbortError");
257
+ }
258
+ const [row] = await rawRows(
259
+ lockedDb,
260
+ sql`select pg_try_advisory_xact_lock(hashtextextended(${key}, 0)) as acquired`
261
+ );
262
+ if (row?.acquired === true) return await fn();
263
+ const remainingMs = deadline - Date.now();
264
+ if (remainingMs <= 0) throw new SandboxProviderReadLockUnavailableError();
265
+ await waitForSandboxProviderReadLockPoll(Math.min(pollMs, remainingMs), signal);
266
+ pollMs = Math.min(pollMs * 2, SANDBOX_PROVIDER_READ_LOCK_POLL_MAX_MS);
267
+ }
268
+ });
269
+ }
270
+ function createDb(databaseUrl, options = {}) {
271
+ const client = postgres(databaseUrl, {
272
+ max: options.max ?? 10,
273
+ prepare: false,
274
+ idle_timeout: 30,
275
+ max_lifetime: 1800,
276
+ // `connection` carries per-session Postgres STARTUP parameters. `application_name`
277
+ // (always) aids server-side diagnostics; `search_path` (embedded only) is the
278
+ // supported, query-param-free way to scope a connection to a dedicated schema —
279
+ // postgres-js IGNORES a URL `?search_path=`. Unset searchPath → omit it so the
280
+ // server default (`public`) is unchanged for standalone.
281
+ connection: {
282
+ application_name: LOSSLESS_CONTENT_WRITER_APPLICATION_NAME,
283
+ ...options.searchPath ? { search_path: options.searchPath } : {},
284
+ ...options.isolationLevel ? { default_transaction_isolation: options.isolationLevel } : {}
285
+ }
286
+ });
287
+ const db = drizzle(client, { schema: schema_exports });
288
+ dbBindings.set(db, {
289
+ rlsStrategy: options.rlsStrategy ?? "force",
290
+ ...options.userLookup ? { userLookup: options.userLookup } : {}
291
+ });
292
+ return {
293
+ db,
294
+ close: async () => {
295
+ await client.end();
296
+ }
297
+ };
298
+ }
299
+ function registerDbBinding(db, binding) {
300
+ dbBindings.set(db, {
301
+ rlsStrategy: binding.rlsStrategy ?? "force",
302
+ ...binding.userLookup ? { userLookup: binding.userLookup } : {}
303
+ });
304
+ }
305
+ async function setRlsContext(db, context) {
306
+ if (typeof context.accountId !== "string" || context.accountId.trim() === "") {
307
+ throw new Error("setRlsContext: a non-empty accountId is required to establish an RLS context");
308
+ }
309
+ await db.execute(sql`select set_config('opengeni.account_id', ${context.accountId}, true)`);
310
+ await db.execute(
311
+ sql`select set_config('opengeni.workspace_id', ${context.workspaceId ?? ""}, true)`
312
+ );
313
+ await db.execute(sql`select set_config('opengeni.lossless_content_writer', '1', true)`);
314
+ await db.execute(sql`select
315
+ set_config('opengeni.sandbox_recovery_protocol_v2', '1', true),
316
+ set_config('opengeni.pending_tool_event_output_v1', '1', true)`);
317
+ const sessionActor = sessionRlsActorContext.getStore();
318
+ if (sessionActor) {
319
+ await setSubjectRlsContext(db, sessionActor.subjectId);
320
+ await db.execute(
321
+ sql`select set_config(
322
+ 'opengeni.initiating_human_subject_id',
323
+ ${sessionActor.initiatingHumanSubjectId ?? ""},
324
+ true
325
+ )`
326
+ );
327
+ }
328
+ }
329
+ async function readRlsContextSettings(db) {
330
+ const [settings] = await rawRows(
331
+ db,
332
+ sql`select
333
+ current_setting('opengeni.account_id', true) as account_id,
334
+ current_setting('opengeni.workspace_id', true) as workspace_id`
335
+ );
336
+ return {
337
+ accountId: settings?.account_id ?? "",
338
+ workspaceId: settings?.workspace_id ?? ""
339
+ };
340
+ }
341
+ async function assertRlsContextApplied(db, context) {
342
+ const applied = await readRlsContextSettings(db);
343
+ const expectedWorkspaceId = context.workspaceId ?? "";
344
+ if (applied.accountId !== context.accountId) {
345
+ throw new Error(
346
+ `RLS context not applied on the active backend: expected account ${context.accountId}, got "${applied.accountId}"`
347
+ );
348
+ }
349
+ if (applied.workspaceId !== expectedWorkspaceId) {
350
+ throw new Error(
351
+ `RLS context not applied on the active backend: expected workspace "${expectedWorkspaceId}", got "${applied.workspaceId}"`
352
+ );
353
+ }
354
+ }
355
+ async function restoreRlsContextSettings(db, settings) {
356
+ const [restored] = await rawRows(
357
+ db,
358
+ sql`select
359
+ set_config('opengeni.account_id', ${settings.accountId}, true) as account_id,
360
+ set_config('opengeni.workspace_id', ${settings.workspaceId}, true) as workspace_id`
361
+ );
362
+ if (restored?.account_id !== settings.accountId || restored.workspace_id !== settings.workspaceId) {
363
+ throw new Error("RLS context could not be restored after a nested scope");
364
+ }
365
+ }
366
+ async function withRlsContext(db, context, fn, transactionConfig) {
367
+ const restoreParentScope = isTransactionHandle(db);
368
+ return await db.transaction(async (tx) => {
369
+ const scoped = tx;
370
+ const parentScope = restoreParentScope ? await readRlsContextSettings(scoped) : null;
371
+ await setRlsContext(scoped, context);
372
+ await assertRlsContextApplied(scoped, context);
373
+ const value = await fn(scoped);
374
+ if (parentScope) await restoreRlsContextSettings(scoped, parentScope);
375
+ return value;
376
+ }, transactionConfig);
377
+ }
378
+ async function withDatabaseStatementTimeout(db, timeoutMs, fn) {
379
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
380
+ throw new Error("withDatabaseStatementTimeout requires a positive timeout");
381
+ }
382
+ const boundedTimeoutMs = Math.max(1, Math.floor(timeoutMs));
383
+ return await db.transaction(async (tx) => {
384
+ const scoped = tx;
385
+ await scoped.execute(
386
+ sql`select set_config('statement_timeout', ${`${boundedTimeoutMs}ms`}, true)`
387
+ );
388
+ return await fn(scoped);
389
+ });
390
+ }
391
+ async function rlsContextForWorkspace(db, workspaceId) {
392
+ const [row] = await db.select({ accountId: workspaces.accountId }).from(workspaces).where(eq(workspaces.id, workspaceId)).limit(1);
393
+ if (!row) {
394
+ throw new Error(`Workspace not found: ${workspaceId}`);
395
+ }
396
+ return { accountId: row.accountId, workspaceId };
397
+ }
398
+ async function withWorkspaceRls(db, workspaceId, fn, transactionConfig) {
399
+ return await withRlsContext(
400
+ db,
401
+ await rlsContextForWorkspace(db, workspaceId),
402
+ fn,
403
+ transactionConfig
404
+ );
405
+ }
406
+ function isTransactionHandle(db) {
407
+ return typeof db.rollback === "function";
408
+ }
409
+ async function assertSessionActivityGateEntry(db) {
410
+ if (!isTransactionHandle(db)) return;
411
+ const [gate] = await rawRows(
412
+ db,
413
+ sql`
414
+ select nullif(
415
+ current_setting('opengeni.session_activity_gate_state', true),
416
+ ''
417
+ ) as state
418
+ `
419
+ );
420
+ if (gate?.state === null || gate === void 0) {
421
+ throw new Error("Session activity commit gate must start at the outer transaction boundary");
422
+ }
423
+ }
424
+ async function beginSessionActivityGate(db, workspaceId) {
425
+ const [gate] = await rawRows(
426
+ db,
427
+ sql`
428
+ with current_gate as materialized (
429
+ select
430
+ nullif(current_setting('opengeni.session_activity_gate_state', true), '') as prior_state,
431
+ nullif(current_setting('opengeni.session_activity_gate_workspace_id', true), '') as prior_workspace_id
432
+ )
433
+ select
434
+ prior_state,
435
+ prior_workspace_id,
436
+ case
437
+ when prior_state is null
438
+ then set_config('opengeni.session_activity_gate_state', 'open', true)
439
+ else prior_state
440
+ end as effective_state,
441
+ case
442
+ when prior_state is null
443
+ then set_config('opengeni.session_activity_gate_workspace_id', ${workspaceId}, true)
444
+ else prior_workspace_id
445
+ end as effective_workspace_id
446
+ from current_gate
447
+ `
448
+ );
449
+ if (!gate) {
450
+ throw new Error("Session activity commit gate could not be opened");
451
+ }
452
+ if (gate.prior_state === null) {
453
+ return { db, owner: true };
454
+ }
455
+ if (gate.prior_state === "open" && gate.prior_workspace_id === workspaceId) {
456
+ return { db, owner: false };
457
+ }
458
+ throw new Error("Session activity commit gate is already owned by another transaction scope");
459
+ }
460
+ async function finalizeSessionActivityGate(db, workspaceId) {
461
+ await db.execute(
462
+ sql`select set_config('opengeni.session_activity_gate_state', 'preparing', true)`
463
+ );
464
+ await db.execute(sql`set constraints all immediate`);
465
+ await db.execute(
466
+ sql`set constraints sessions_activity_insert_commit_guard, sessions_activity_update_commit_guard deferred`
467
+ );
468
+ const [result] = await rawRows(
469
+ db,
470
+ sql`
471
+ with gate as materialized (
472
+ select set_config('opengeni.session_activity_gate_state', 'finalizing', true) as state
473
+ ),
474
+ pending as materialized (
475
+ select ${sessions.id}
476
+ from ${sessions}
477
+ cross join gate
478
+ where ${sessions.workspaceId} = ${workspaceId}
479
+ and ${sessions.activityRevisionPendingXid}
480
+ = pg_current_xact_id()::text::bigint
481
+ ),
482
+ advanced as (
483
+ update ${workspaceSessionActivityRevisions} as counter
484
+ set revision = counter.revision + 1
485
+ where counter.workspace_id = ${workspaceId}
486
+ and exists (select 1 from pending)
487
+ returning counter.revision
488
+ ),
489
+ stamped as (
490
+ update ${sessions} as session
491
+ set
492
+ activity_revision = advanced.revision,
493
+ activity_revision_pending_xid = null
494
+ from advanced
495
+ where session.workspace_id = ${workspaceId}
496
+ and session.activity_revision_pending_xid
497
+ = pg_current_xact_id()::text::bigint
498
+ returning session.id
499
+ ),
500
+ stats as materialized (
501
+ select
502
+ exists (select 1 from pending) as had_pending,
503
+ (select count(*)::integer from pending) as pending_count,
504
+ (select revision::text from advanced) as revision,
505
+ (select count(*)::integer from stamped) as stamped_count
506
+ ),
507
+ finalized as materialized (
508
+ select
509
+ had_pending,
510
+ pending_count,
511
+ revision,
512
+ stamped_count,
513
+ set_config('opengeni.session_activity_gate_state', 'finalized', true) as state
514
+ from stats
515
+ )
516
+ select had_pending, pending_count, revision, stamped_count
517
+ from finalized
518
+ `
519
+ );
520
+ if (!result) {
521
+ throw new Error("Session activity commit gate did not return a finalization result");
522
+ }
523
+ if (result.had_pending && result.revision === null) {
524
+ throw new Error("Workspace session activity counter is unavailable");
525
+ }
526
+ if (result.stamped_count !== result.pending_count) {
527
+ throw new Error("Session activity commit gate did not stamp every pending row");
528
+ }
529
+ await db.execute(
530
+ sql`set constraints sessions_activity_insert_commit_guard, sessions_activity_update_commit_guard immediate`
531
+ );
532
+ }
533
+ async function withSessionActivityRlsContext(db, context, fn, transactionConfig) {
534
+ await assertSessionActivityGateEntry(db);
535
+ return await withRlsContext(
536
+ db,
537
+ context,
538
+ async (scopedDb) => {
539
+ const gate = await beginSessionActivityGate(scopedDb, context.workspaceId);
540
+ const value = await fn(gate.db);
541
+ await assertRlsContextApplied(gate.db, context);
542
+ if (gate.owner) {
543
+ await finalizeSessionActivityGate(gate.db, context.workspaceId);
544
+ }
545
+ return value;
546
+ },
547
+ transactionConfig
548
+ );
549
+ }
550
+ async function withWorkspaceSessionActivityRls(db, workspaceId, fn, transactionConfig) {
551
+ return await withSessionActivityRlsContext(
552
+ db,
553
+ { ...await rlsContextForWorkspace(db, workspaceId), workspaceId },
554
+ fn,
555
+ transactionConfig
556
+ );
557
+ }
558
+ async function withSessionActivitySavepoint(db, fn) {
559
+ return await db.transaction(async (tx) => await fn(tx));
560
+ }
561
+ async function retrySessionActivityRls(db, workspaceId, options, fn) {
562
+ return await runIdempotentPersistenceTransaction(options, async () => {
563
+ return await withWorkspaceSessionActivityRls(db, workspaceId, fn);
564
+ });
565
+ }
566
+ async function retryWorkspacePersistence(db, workspaceId, options, fn) {
567
+ return await runIdempotentPersistenceTransaction(options, async () => {
568
+ return await withWorkspaceRls(db, workspaceId, fn);
569
+ });
570
+ }
571
+ async function retryRlsPersistence(db, context, options, fn) {
572
+ return await runIdempotentPersistenceTransaction(options, async () => {
573
+ return await withRlsContext(db, context, fn);
574
+ });
575
+ }
576
+ async function withWorkspaceSubjectRls(db, workspaceId, subjectId, fn, transactionConfig) {
577
+ if (!subjectId.trim()) {
578
+ throw new Error("withWorkspaceSubjectRls: a non-empty subjectId is required");
579
+ }
580
+ const context = await rlsContextForWorkspace(db, workspaceId);
581
+ return await withRlsContext(
582
+ db,
583
+ context,
584
+ async (scopedDb) => {
585
+ await setSubjectRlsContext(scopedDb, subjectId);
586
+ return await fn(scopedDb);
587
+ },
588
+ transactionConfig
589
+ );
590
+ }
591
+ async function withWorkspaceSubjectSessionActivityRls(db, workspaceId, subjectId, fn, transactionConfig) {
592
+ if (!subjectId.trim()) {
593
+ throw new Error("withWorkspaceSubjectSessionActivityRls: a non-empty subjectId is required");
594
+ }
595
+ const context = await rlsContextForWorkspace(db, workspaceId);
596
+ return await withSessionActivityRlsContext(
597
+ db,
598
+ { ...context, workspaceId },
599
+ async (scopedDb) => {
600
+ await setSubjectRlsContext(scopedDb, subjectId);
601
+ return await fn(scopedDb);
602
+ },
603
+ transactionConfig
604
+ );
605
+ }
606
+ async function setSubjectRlsContext(db, subjectId) {
607
+ if (!subjectId.trim()) {
608
+ throw new Error("setSubjectRlsContext: a non-empty subjectId is required");
609
+ }
610
+ await db.execute(sql`select set_config('opengeni.subject_id', ${subjectId}, true)`);
611
+ const applied = await db.execute(
612
+ sql`select current_setting('opengeni.subject_id', true) as subject_id`
613
+ );
614
+ if ((applied[0]?.subject_id ?? "") !== subjectId) {
615
+ throw new Error("Authenticated subject RLS context was not applied on the active backend");
616
+ }
617
+ }
618
+ async function withWorkspaceUsageLock(db, workspaceId, fn) {
619
+ const context = await rlsContextForWorkspace(db, workspaceId);
620
+ return await withRlsContext(db, context, async (scopedDb) => {
621
+ await scopedDb.execute(sql`select pg_advisory_xact_lock(hashtext(${`usage:${workspaceId}`}))`);
622
+ return await fn(scopedDb);
623
+ });
624
+ }
625
+ async function withAccountRls(db, accountId, fn) {
626
+ return await withRlsContext(db, { accountId, workspaceId: null }, fn);
627
+ }
628
+ function dbBindingFor(db) {
629
+ return dbBindings.get(db);
630
+ }
631
+
632
+ export {
633
+ nestedPostgresSqlState,
634
+ databaseFailureCode,
635
+ isRetryablePersistenceSqlState,
636
+ isDatabasePersistenceFailure,
637
+ safeDatabaseErrorFacts,
638
+ SessionEventPersistenceError,
639
+ isSessionEventPersistenceError,
640
+ runIdempotentPersistenceTransaction,
641
+ withSessionRlsActorContext,
642
+ rlsStrategyFor,
643
+ rawRows,
644
+ SandboxProviderReadLockUnavailableError,
645
+ withSandboxProviderReadLock,
646
+ createDb,
647
+ registerDbBinding,
648
+ setRlsContext,
649
+ withRlsContext,
650
+ withDatabaseStatementTimeout,
651
+ rlsContextForWorkspace,
652
+ withWorkspaceRls,
653
+ withSessionActivityRlsContext,
654
+ withWorkspaceSessionActivityRls,
655
+ withSessionActivitySavepoint,
656
+ retrySessionActivityRls,
657
+ retryWorkspacePersistence,
658
+ retryRlsPersistence,
659
+ withWorkspaceSubjectRls,
660
+ withWorkspaceSubjectSessionActivityRls,
661
+ setSubjectRlsContext,
662
+ withWorkspaceUsageLock,
663
+ withAccountRls,
664
+ dbBindingFor
665
+ };
666
+ //# sourceMappingURL=chunk-JC5QPLUM.js.map