@sentry/junior 0.202.0 → 0.204.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 (174) hide show
  1. package/dist/agent-CMyTD4DD.js +17509 -0
  2. package/dist/agent-hooks-Bbcp9e33.js +4040 -0
  3. package/dist/agent-runner-DNb1A49M.js +678 -0
  4. package/dist/api/schema.d.ts +2728 -2639
  5. package/dist/api/schema.js +4 -169
  6. package/dist/api.d.ts +23 -17
  7. package/dist/api.js +3881 -5326
  8. package/dist/app-B1TOqBI8.d.ts +246 -0
  9. package/dist/app.d.ts +4 -520
  10. package/dist/app.js +9522 -11875
  11. package/dist/auth-pause-state-DosEalIG.js +168 -0
  12. package/dist/catalog-runtime-BReos-D4.js +7 -0
  13. package/dist/checkpoint-CNrPyRJN.js +2450 -0
  14. package/dist/cli/chat.d.ts +20 -0
  15. package/dist/cli/chat.js +229 -336
  16. package/dist/cli/check.d.ts +8 -0
  17. package/dist/cli/check.js +513 -806
  18. package/dist/cli/env.d.ts +13 -0
  19. package/dist/cli/env.js +63 -12
  20. package/dist/cli/init.d.ts +3 -0
  21. package/dist/cli/init.js +90 -159
  22. package/dist/cli/main.d.ts +6 -0
  23. package/dist/cli/main.js +43 -64
  24. package/dist/cli/plugins.d.ts +13 -0
  25. package/dist/cli/plugins.js +148 -227
  26. package/dist/cli/run.d.ts +16 -0
  27. package/dist/cli/run.js +52 -8
  28. package/dist/cli/snapshot-create.d.ts +4 -0
  29. package/dist/cli/snapshot-create.js +71 -125
  30. package/dist/cli/upgrade.d.ts +15 -0
  31. package/dist/cli/upgrade.js +232 -335
  32. package/dist/config-nGCW1OTG.js +941 -0
  33. package/dist/context-B45_WqVX.js +298 -0
  34. package/dist/conversation-privacy-B4voFRSm.js +182 -0
  35. package/dist/conversation-work-C6y3T5Hx.js +51 -0
  36. package/dist/credential-sync-kXr1hvO1.js +2660 -0
  37. package/dist/db-BeyXKJOI.d.ts +5 -0
  38. package/dist/destinations-BeBiJeEM.js +29 -0
  39. package/dist/execution-stats-DWfSihcH.js +373 -0
  40. package/dist/executor-DcMSlI5c.js +721 -0
  41. package/dist/experimental-CIXf7Uye.js +46 -0
  42. package/dist/history-ClE4toxe.d.ts +32 -0
  43. package/dist/history-CqTuSAdI.js +441 -0
  44. package/dist/instrumentation.d.ts +3 -3
  45. package/dist/instrumentation.js +130 -176
  46. package/dist/job-queue-Drn_LXlM.js +63 -0
  47. package/dist/logging-BzAk1S_s.js +1210 -0
  48. package/dist/model-profile-CZmVoGdX.js +49 -0
  49. package/dist/nitro.d.ts +31 -36
  50. package/dist/nitro.js +275 -456
  51. package/dist/oauth-callback-server-JiftokvA.js +130 -0
  52. package/dist/oauth-relay-CdCnu80W.js +62 -0
  53. package/dist/package-discovery-7a9YqLhE.js +455 -0
  54. package/dist/pending-auth-CWmSdZVg.js +185 -0
  55. package/dist/plugin-module-BKGOXca2.js +81 -0
  56. package/dist/plugins-BI9A1vKA.d.ts +95 -0
  57. package/dist/plugins-egKWjgue.js +99 -0
  58. package/dist/private-trace-result-BLvBjy_e.js +16 -0
  59. package/dist/profile-CrT5nXbw.js +861 -0
  60. package/dist/registry-DH1xUo2N.js +1419 -0
  61. package/dist/reporting-schema-DosTN__Q.js +105 -0
  62. package/dist/resolve-CZHnfxaS.js +546 -0
  63. package/dist/rolldown-runtime-B4FMCO8f.js +28 -0
  64. package/dist/runner-CZV2sC46.js +392 -0
  65. package/dist/sandbox-egress-signals-bHZfmhbd.js +46 -0
  66. package/dist/schema-Rn8-XEaN.js +1140 -0
  67. package/dist/sentry-CD3SdJl-.js +26 -0
  68. package/dist/skills-CIcDQSgM.js +316 -0
  69. package/dist/spawn-DdkUFRmq.js +29 -0
  70. package/dist/stats-DTUbAb88.js +2634 -0
  71. package/dist/store-C5qxF2ac.d.ts +208 -0
  72. package/dist/task-queue-CJIR4RF7.js +136 -0
  73. package/dist/task-runner-D-O3A-Cp.js +639 -0
  74. package/dist/thread-state-CRc9jTJS.js +431 -0
  75. package/dist/turn-execution-BkinIdJF.js +47 -0
  76. package/dist/turn-lifecycle-DQV19VTW.js +54 -0
  77. package/dist/usage-D3EbSO7w.js +296 -0
  78. package/dist/usage-schema-CKaDkH_j.js +20 -0
  79. package/dist/validation-C2CR-OX3.js +40 -0
  80. package/dist/vercel-queue-DIkVcfK4.js +167 -0
  81. package/dist/vercel.d.ts +6 -6
  82. package/dist/vercel.js +14 -6
  83. package/dist/version-CnXZ614E.d.ts +5 -0
  84. package/dist/version-DxcWdoKa.js +8 -0
  85. package/dist/version.d.ts +2 -4
  86. package/dist/version.js +2 -6
  87. package/dist/web-authorization-RMBxAR_t.js +76 -0
  88. package/dist/web-input-3EPfpf55.js +494 -0
  89. package/dist/work-fGofI7Op.js +509 -0
  90. package/dist/worker-CsOLq-mR.js +625 -0
  91. package/package.json +9 -9
  92. package/dist/agent-hooks-UXITLYOK.js +0 -51
  93. package/dist/catalog-runtime-BG3JLLK2.js +0 -14
  94. package/dist/chunk-2LYHWMR4.js +0 -46
  95. package/dist/chunk-2MK3QBGA.js +0 -321
  96. package/dist/chunk-3PGQSKJV.js +0 -692
  97. package/dist/chunk-3UI3WFTX.js +0 -519
  98. package/dist/chunk-3Y47VMHV.js +0 -6
  99. package/dist/chunk-4UO6FK4G.js +0 -64
  100. package/dist/chunk-5NOPO64K.js +0 -198
  101. package/dist/chunk-5PKWYPFT.js +0 -2943
  102. package/dist/chunk-63NKKFJL.js +0 -1228
  103. package/dist/chunk-6AYH6252.js +0 -787
  104. package/dist/chunk-6Y5B5PEX.js +0 -80
  105. package/dist/chunk-7DHZP5KJ.js +0 -333
  106. package/dist/chunk-7H2VZTWN.js +0 -103
  107. package/dist/chunk-7NL7T6VU.js +0 -406
  108. package/dist/chunk-A76OIMYN.js +0 -102
  109. package/dist/chunk-AWMS3SPP.js +0 -58
  110. package/dist/chunk-B3LY5RCL.js +0 -229
  111. package/dist/chunk-BD2KT3OB.js +0 -36
  112. package/dist/chunk-BXCX5QKA.js +0 -2086
  113. package/dist/chunk-C6VVF43U.js +0 -81
  114. package/dist/chunk-CEMMLV5L.js +0 -98
  115. package/dist/chunk-CM5HNV2W.js +0 -131
  116. package/dist/chunk-DA2KGZZI.js +0 -13
  117. package/dist/chunk-DBVY6HLX.js +0 -64
  118. package/dist/chunk-DIB4GX3G.js +0 -8
  119. package/dist/chunk-DKIJ2RP5.js +0 -68
  120. package/dist/chunk-DL2KLKVH.js +0 -931
  121. package/dist/chunk-DWPN6SCH.js +0 -172
  122. package/dist/chunk-ELWOYVOY.js +0 -206
  123. package/dist/chunk-EWT7H65X.js +0 -506
  124. package/dist/chunk-FA6POGLH.js +0 -70
  125. package/dist/chunk-HMREVIO2.js +0 -135
  126. package/dist/chunk-IIWUT4FO.js +0 -820
  127. package/dist/chunk-JAL3CH4G.js +0 -27
  128. package/dist/chunk-JSJQEWBJ.js +0 -3295
  129. package/dist/chunk-KHKKHDLD.js +0 -387
  130. package/dist/chunk-LA6R4A7Q.js +0 -706
  131. package/dist/chunk-LOOU2DUR.js +0 -20428
  132. package/dist/chunk-M6FHWXE3.js +0 -700
  133. package/dist/chunk-M76HMB7M.js +0 -1856
  134. package/dist/chunk-MAGNK5J4.js +0 -1520
  135. package/dist/chunk-MTM5IFCY.js +0 -1190
  136. package/dist/chunk-N7TMSOZH.js +0 -235
  137. package/dist/chunk-NHJU2ZAL.js +0 -56
  138. package/dist/chunk-NSXKRGRT.js +0 -717
  139. package/dist/chunk-OWMPFXJA.js +0 -1764
  140. package/dist/chunk-PDO5BLNM.js +0 -22
  141. package/dist/chunk-PEQXYSSE.js +0 -45
  142. package/dist/chunk-PW4P4JYF.js +0 -1135
  143. package/dist/chunk-QB54UQUS.js +0 -320
  144. package/dist/chunk-QP3OGJXF.js +0 -105
  145. package/dist/chunk-RC745GGZ.js +0 -122
  146. package/dist/chunk-REOIRYPR.js +0 -37
  147. package/dist/chunk-SCOZRLZ4.js +0 -164
  148. package/dist/chunk-TXJSXBV5.js +0 -1433
  149. package/dist/chunk-TXKUKMVO.js +0 -417
  150. package/dist/chunk-U2GPUYAL.js +0 -3656
  151. package/dist/chunk-UIE3R5XU.js +0 -17
  152. package/dist/chunk-UXPG6ZIN.js +0 -84
  153. package/dist/chunk-VFUK3X5B.js +0 -50
  154. package/dist/chunk-WQSHDTTI.js +0 -1163
  155. package/dist/chunk-X6GDDWQH.js +0 -60
  156. package/dist/chunk-Y2CM7HXH.js +0 -111
  157. package/dist/chunk-Y7X25LFY.js +0 -15
  158. package/dist/chunk-YDUR3ZYW.js +0 -10
  159. package/dist/conversation-work-VIOQ5ZF3.js +0 -54
  160. package/dist/db-3L2MCVRI.js +0 -26
  161. package/dist/discovery-DWVDM7UK.js +0 -44
  162. package/dist/experimental-P5FZM4CU.js +0 -12
  163. package/dist/oauth-callback-server-YVV6C6T2.js +0 -243
  164. package/dist/oauth-relay-5XPVRPYB.js +0 -8
  165. package/dist/plugins-YTYJMMJF.js +0 -14
  166. package/dist/runner-LQ7RETDP.js +0 -522
  167. package/dist/sandbox-egress-signals-FIL7EGPR.js +0 -73
  168. package/dist/sentry-MB3NL3IR.js +0 -42
  169. package/dist/skills-XRWYEDCD.js +0 -27
  170. package/dist/spawn-RC6SJUAI.js +0 -42
  171. package/dist/task-runner-7DY7ARYH.js +0 -36
  172. package/dist/validation-7MNQGCJA.js +0 -17
  173. package/dist/work-COALHUCG.js +0 -51
  174. package/dist/worker-6MURZIPD.js +0 -24
@@ -1,1135 +0,0 @@
1
- import {
2
- juniorDestinations,
3
- timestamptz
4
- } from "./chunk-VFUK3X5B.js";
5
- import {
6
- DEFAULT_SQL_STATEMENT_TIMEOUT_MS
7
- } from "./chunk-63NKKFJL.js";
8
-
9
- // src/db/neon.ts
10
- import { AsyncLocalStorage } from "async_hooks";
11
- import {
12
- Pool
13
- } from "@neondatabase/serverless";
14
- import { drizzle } from "drizzle-orm/neon-serverless";
15
- import { migrate } from "drizzle-orm/neon-serverless/migrator";
16
-
17
- // src/db/schema/artifacts.ts
18
- import {
19
- boolean,
20
- index,
21
- integer,
22
- pgTable,
23
- text,
24
- uniqueIndex
25
- } from "drizzle-orm/pg-core";
26
- var juniorArtifacts = pgTable(
27
- "junior_artifacts",
28
- {
29
- /** Public identity used in `/public/artifacts/<id>.<ext>`. */
30
- id: text("id").primaryKey(),
31
- conversationId: text("conversation_id").notNull(),
32
- sha256: text("sha256").notNull(),
33
- ext: text("ext").notNull(),
34
- storageKey: text("storage_key").notNull(),
35
- contentType: text("content_type").notNull(),
36
- bytes: integer("bytes").notNull(),
37
- public: boolean("public").notNull(),
38
- createdAt: timestamptz("created_at").notNull(),
39
- /** Set when the artifact should stop being served publicly. */
40
- deleteRequestedAt: timestamptz("delete_requested_at")
41
- },
42
- (table) => [
43
- uniqueIndex("junior_artifacts_conversation_sha_uidx").on(
44
- table.conversationId,
45
- table.sha256
46
- ),
47
- index("junior_artifacts_gc_idx").on(
48
- table.deleteRequestedAt,
49
- table.createdAt
50
- ),
51
- index("junior_artifacts_conversation_idx").on(table.conversationId)
52
- ]
53
- );
54
-
55
- // src/db/schema/attachments.ts
56
- import { index as index4, integer as integer3, pgTable as pgTable5, text as text5 } from "drizzle-orm/pg-core";
57
-
58
- // src/db/schema/conversations.ts
59
- import { getTableColumns, sql as sql2 } from "drizzle-orm";
60
- import {
61
- index as index3,
62
- integer as integer2,
63
- jsonb as jsonb2,
64
- pgTable as pgTable4,
65
- text as text4
66
- } from "drizzle-orm/pg-core";
67
-
68
- // src/db/schema/identities.ts
69
- import { sql } from "drizzle-orm";
70
- import {
71
- boolean as boolean2,
72
- index as index2,
73
- jsonb,
74
- pgTable as pgTable3,
75
- text as text3,
76
- uniqueIndex as uniqueIndex3
77
- } from "drizzle-orm/pg-core";
78
-
79
- // src/db/schema/users.ts
80
- import { text as text2, pgTable as pgTable2, uniqueIndex as uniqueIndex2 } from "drizzle-orm/pg-core";
81
- var juniorUsers = pgTable2(
82
- "junior_users",
83
- {
84
- id: text2("id").primaryKey(),
85
- primaryEmail: text2("primary_email").notNull(),
86
- primaryEmailNormalized: text2("primary_email_normalized").notNull(),
87
- displayName: text2("display_name"),
88
- createdAt: timestamptz("created_at").notNull(),
89
- updatedAt: timestamptz("updated_at").notNull()
90
- },
91
- (table) => [
92
- uniqueIndex2("junior_users_primary_email_normalized_uidx").on(
93
- table.primaryEmailNormalized
94
- )
95
- ]
96
- );
97
-
98
- // src/db/schema/identities.ts
99
- var juniorIdentities = pgTable3(
100
- "junior_identities",
101
- {
102
- id: text3("id").primaryKey(),
103
- kind: text3("kind").$type().notNull(),
104
- provider: text3("provider").notNull(),
105
- providerTenantId: text3("provider_tenant_id").notNull().default(""),
106
- providerSubjectId: text3("provider_subject_id").notNull(),
107
- displayName: text3("display_name"),
108
- handle: text3("handle"),
109
- email: text3("email"),
110
- avatarUrl: text3("avatar_url"),
111
- metadata: jsonb("metadata_json"),
112
- createdAt: timestamptz("created_at").notNull(),
113
- updatedAt: timestamptz("updated_at").notNull(),
114
- userId: text3("user_id").references(() => juniorUsers.id),
115
- emailNormalized: text3("email_normalized"),
116
- emailVerified: boolean2("email_verified").notNull().default(false)
117
- },
118
- (table) => [
119
- uniqueIndex3("junior_identities_provider_subject_uidx").on(
120
- table.provider,
121
- table.providerTenantId,
122
- table.providerSubjectId
123
- ),
124
- index2("junior_identities_user_idx").on(table.userId),
125
- index2("junior_identities_verified_email_idx").on(table.emailNormalized).where(
126
- sql`${table.emailVerified} = true AND ${table.emailNormalized} IS NOT NULL`
127
- ),
128
- index2("junior_identities_kind_provider_idx").on(table.kind, table.provider)
129
- ]
130
- );
131
-
132
- // src/db/schema/conversations.ts
133
- var juniorConversations = pgTable4(
134
- "junior_conversations",
135
- {
136
- conversationId: text4("conversation_id").primaryKey(),
137
- schemaVersion: integer2("schema_version").notNull().default(1),
138
- source: text4("source").$type(),
139
- /** Structured session Source locator; set-once on the conversation root. */
140
- // TODO(dcramer): Remove source_json after resume reads the saved Turn Source
141
- // and all provider context readers use Conversation Location.
142
- sessionSource: jsonb2("source_json").$type(),
143
- originType: text4("origin_type"),
144
- originId: text4("origin_id"),
145
- originRunId: text4("origin_run_id"),
146
- /** Complete Location associated with this Conversation. */
147
- location: jsonb2("location_json").$type(),
148
- // TODO(dcramer): Rename destination_id to location_id after all deployed
149
- // readers and writers use the singular Conversation Location contract.
150
- destinationId: text4("destination_id").references(
151
- () => juniorDestinations.id
152
- ),
153
- // TODO(dcramer): Drop destination_json after every row uses location_id and
154
- // no supported worker writes the legacy JSON value.
155
- destination: jsonb2("destination_json").$type(),
156
- actorIdentityId: text4("actor_identity_id").references(
157
- () => juniorIdentities.id
158
- ),
159
- creatorIdentityId: text4("creator_identity_id").references(
160
- () => juniorIdentities.id
161
- ),
162
- credentialSubjectIdentityId: text4(
163
- "credential_subject_identity_id"
164
- ).references(() => juniorIdentities.id),
165
- actor: jsonb2("actor_json").$type(),
166
- channelName: text4("channel_name"),
167
- title: text4("title"),
168
- createdAt: timestamptz("created_at").notNull(),
169
- lastActivityAt: timestamptz("last_activity_at").notNull(),
170
- updatedAt: timestamptz("updated_at").notNull(),
171
- executionUpdatedAt: timestamptz("execution_updated_at"),
172
- executionStatus: text4("execution_status").$type().notNull(),
173
- runId: text4("run_id"),
174
- lastCheckpointAt: timestamptz("last_checkpoint_at"),
175
- lastEnqueuedAt: timestamptz("last_enqueued_at"),
176
- // Subagent runs are child conversations; top-level listings filter
177
- // parent_conversation_id IS NULL. Historical advisor children use this too.
178
- parentConversationId: text4("parent_conversation_id").references(
179
- () => juniorConversations.conversationId
180
- ),
181
- // Roots reference themselves; descendants reference the root whose actor
182
- // and destination own their privacy boundary.
183
- rootConversationId: text4("root_conversation_id").references(
184
- () => juniorConversations.conversationId
185
- ),
186
- transcriptPurgedAt: timestamptz("transcript_purged_at"),
187
- durationMs: integer2("duration_ms").notNull().default(0),
188
- usage: jsonb2("usage_json").$type(),
189
- executionDurationMs: integer2("execution_duration_ms").notNull().default(0),
190
- executionUsage: jsonb2("execution_usage_json").$type(),
191
- metricRunId: text4("metric_run_id"),
192
- // Keep the legacy column in the schema. Runtime code must not read or write it.
193
- legacyArchivedAt: timestamptz("archived_at")
194
- },
195
- (table) => [
196
- index3("junior_conversations_last_activity_idx").on(
197
- table.lastActivityAt.desc(),
198
- table.conversationId
199
- ),
200
- index3("junior_conversations_active_idx").using(
201
- "btree",
202
- sql2`coalesce(${table.executionUpdatedAt}, ${table.updatedAt})`,
203
- table.conversationId
204
- ).where(sql2`${table.executionStatus} <> 'idle'`),
205
- index3("junior_conversations_destination_activity_idx").on(
206
- table.destinationId,
207
- table.lastActivityAt.desc()
208
- ),
209
- index3("junior_conversations_actor_activity_idx").on(
210
- table.actorIdentityId,
211
- table.lastActivityAt.desc()
212
- ),
213
- index3("junior_conversations_origin_idx").on(
214
- table.originType,
215
- table.originId,
216
- table.lastActivityAt.desc()
217
- ),
218
- index3("junior_conversations_parent_idx").on(table.parentConversationId),
219
- index3("junior_conversations_root_idx").on(table.rootConversationId)
220
- ]
221
- );
222
- function conversationReadColumns() {
223
- const { legacyArchivedAt, ...columns } = getTableColumns(juniorConversations);
224
- void legacyArchivedAt;
225
- return columns;
226
- }
227
-
228
- // src/db/schema/attachments.ts
229
- var juniorAttachments = pgTable5(
230
- "junior_attachments",
231
- {
232
- id: text5("id").primaryKey(),
233
- conversationId: text5("conversation_id").notNull().references(() => juniorConversations.conversationId, {
234
- onDelete: "cascade"
235
- }),
236
- /** Service that stores the file bytes. */
237
- storageProvider: text5("storage_provider").notNull(),
238
- storageKey: text5("storage_key").notNull(),
239
- /** Provider that supplied the file. */
240
- provider: text5("provider"),
241
- /** File id assigned by the source provider. */
242
- providerId: text5("provider_id"),
243
- filename: text5("filename").notNull(),
244
- contentType: text5("content_type").notNull(),
245
- bytes: integer3("bytes").notNull(),
246
- sha256: text5("sha256").notNull(),
247
- visionSummary: text5("vision_summary"),
248
- createdAt: timestamptz("created_at").notNull(),
249
- /** Set when conversation purge marks the attachment unavailable. */
250
- deleteRequestedAt: timestamptz("delete_requested_at")
251
- },
252
- (table) => [
253
- index4("junior_attachments_conversation_idx").on(table.conversationId),
254
- index4("junior_attachments_provider_idx").on(
255
- table.conversationId,
256
- table.provider,
257
- table.providerId
258
- ),
259
- index4("junior_attachments_gc_idx").on(
260
- table.storageProvider,
261
- table.deleteRequestedAt,
262
- table.createdAt
263
- )
264
- ]
265
- );
266
-
267
- // src/db/schema/code.ts
268
- import { sql as sql3 } from "drizzle-orm";
269
- import {
270
- index as index5,
271
- integer as integer4,
272
- pgTable as pgTable6,
273
- text as text6,
274
- uniqueIndex as uniqueIndex4,
275
- uuid
276
- } from "drizzle-orm/pg-core";
277
- var juniorCodeRepositories = pgTable6(
278
- "junior_code_repositories",
279
- {
280
- id: uuid("id").primaryKey(),
281
- name: text6("name").notNull(),
282
- provider: text6("provider").notNull(),
283
- providerId: text6("provider_id").notNull(),
284
- url: text6("url"),
285
- updatedAt: timestamptz("updated_at").notNull()
286
- },
287
- (table) => [
288
- uniqueIndex4("junior_code_repositories_provider_id_idx").on(
289
- table.provider,
290
- table.providerId
291
- )
292
- ]
293
- );
294
- var juniorCodeChanges = pgTable6(
295
- "junior_code_changes",
296
- {
297
- id: uuid("id").primaryKey(),
298
- closedAt: timestamptz("closed_at"),
299
- conversationIds: text6("conversation_ids").array().notNull().default(sql3`ARRAY[]::text[]`),
300
- mergedAt: timestamptz("merged_at"),
301
- number: integer4("number").notNull(),
302
- openedAt: timestamptz("opened_at").notNull(),
303
- provider: text6("provider").notNull(),
304
- providerId: text6("provider_id").notNull(),
305
- repositoryId: uuid("repository_id").notNull().references(() => juniorCodeRepositories.id, { onDelete: "cascade" }),
306
- state: text6("state").$type().notNull(),
307
- title: text6("title"),
308
- updatedAt: timestamptz("updated_at").notNull(),
309
- url: text6("url")
310
- },
311
- (table) => [
312
- uniqueIndex4("junior_code_changes_provider_id_idx").on(
313
- table.provider,
314
- table.providerId
315
- ),
316
- index5("junior_code_changes_opened_at_idx").on(table.openedAt),
317
- index5("junior_code_changes_merged_at_idx").on(table.mergedAt),
318
- index5("junior_code_changes_closed_at_idx").on(table.closedAt),
319
- index5("junior_code_changes_open_idx").on(table.id).where(sql3`${table.state} = 'open'`)
320
- ]
321
- );
322
-
323
- // src/db/schema/conversation-annotations.ts
324
- import {
325
- foreignKey,
326
- jsonb as jsonb3,
327
- pgTable as pgTable7,
328
- primaryKey,
329
- text as text7
330
- } from "drizzle-orm/pg-core";
331
- var juniorConversationAnnotations = pgTable7(
332
- "junior_conversation_annotations",
333
- {
334
- conversationId: text7("conversation_id").notNull(),
335
- plugin: text7("plugin").notNull(),
336
- kind: text7("kind").notNull(),
337
- key: text7("key").notNull(),
338
- annotation: jsonb3("annotation_json").$type().notNull(),
339
- createdAt: timestamptz("created_at").notNull(),
340
- updatedAt: timestamptz("updated_at").notNull()
341
- },
342
- (table) => [
343
- primaryKey({
344
- name: "junior_conversation_annotations_pk",
345
- columns: [table.conversationId, table.plugin, table.kind, table.key]
346
- }),
347
- foreignKey({
348
- name: "junior_conversation_annotations_conversation_id_fk",
349
- columns: [table.conversationId],
350
- foreignColumns: [juniorConversations.conversationId]
351
- }).onDelete("cascade")
352
- ]
353
- );
354
-
355
- // src/db/schema/api-tokens.ts
356
- import { index as index6, pgTable as pgTable8, text as text8, uniqueIndex as uniqueIndex5 } from "drizzle-orm/pg-core";
357
- var juniorApiTokens = pgTable8(
358
- "junior_api_tokens",
359
- {
360
- id: text8("id").primaryKey(),
361
- ownerEmailNormalized: text8("owner_email_normalized").notNull(),
362
- name: text8("name").notNull(),
363
- tokenHash: text8("token_hash").notNull(),
364
- tokenSuffix: text8("token_suffix").notNull(),
365
- createdAt: timestamptz("created_at").notNull(),
366
- expiresAt: timestamptz("expires_at").notNull(),
367
- lastUsedAt: timestamptz("last_used_at"),
368
- revokedAt: timestamptz("revoked_at")
369
- },
370
- (table) => [
371
- uniqueIndex5("junior_api_tokens_token_hash_uidx").on(table.tokenHash),
372
- index6("junior_api_tokens_owner_email_idx").on(table.ownerEmailNormalized)
373
- ]
374
- );
375
-
376
- // src/db/schema/conversation-events.ts
377
- import {
378
- foreignKey as foreignKey2,
379
- index as index7,
380
- integer as integer5,
381
- jsonb as jsonb4,
382
- pgTable as pgTable9,
383
- primaryKey as primaryKey2,
384
- text as text9,
385
- uniqueIndex as uniqueIndex6
386
- } from "drizzle-orm/pg-core";
387
- import { sql as sql4 } from "drizzle-orm";
388
- var juniorConversationEvents = pgTable9(
389
- "junior_conversation_events",
390
- {
391
- conversationId: text9("conversation_id").notNull(),
392
- seq: integer5("seq").notNull(),
393
- historyVersion: integer5("history_version").notNull(),
394
- schemaVersion: integer5("schema_version").default(1).notNull(),
395
- idempotencyKey: text9("idempotency_key"),
396
- type: text9("type").notNull(),
397
- payload: jsonb4("payload").$type().notNull(),
398
- actorIdentityId: text9("actor_identity_id").references(
399
- () => juniorIdentities.id
400
- ),
401
- createdAt: timestamptz("created_at").notNull()
402
- },
403
- (table) => [
404
- primaryKey2({
405
- name: "junior_conversation_events_conversation_id_seq_pk",
406
- columns: [table.conversationId, table.seq]
407
- }),
408
- foreignKey2({
409
- name: "junior_conversation_events_conversation_id_junior_conversations_conversation_id_fk",
410
- columns: [table.conversationId],
411
- foreignColumns: [juniorConversations.conversationId]
412
- }),
413
- index7("junior_conversation_events_history_version_idx").on(
414
- table.conversationId,
415
- table.historyVersion,
416
- table.seq
417
- ),
418
- index7("junior_conversation_events_type_idx").on(
419
- table.conversationId,
420
- table.type,
421
- table.seq
422
- ),
423
- index7("junior_conversation_events_actor_identity_idx").on(
424
- table.actorIdentityId,
425
- table.conversationId,
426
- table.seq
427
- ),
428
- index7("junior_conversation_events_message_search_idx").using("gin", sql4`to_tsvector('english', ${table.payload}->>'text')`).where(sql4`${table.type} = 'message'`),
429
- uniqueIndex6("junior_conversation_events_idempotency_idx").on(
430
- table.conversationId,
431
- table.idempotencyKey
432
- )
433
- ]
434
- );
435
-
436
- // src/db/schema/conversation-bindings.ts
437
- import { index as index8, pgTable as pgTable10, primaryKey as primaryKey3, text as text10 } from "drizzle-orm/pg-core";
438
- var juniorConversationBindings = pgTable10(
439
- "junior_conversation_bindings",
440
- {
441
- conversationId: text10("conversation_id").notNull().references(() => juniorConversations.conversationId),
442
- provider: text10("provider").notNull(),
443
- providerTenantId: text10("provider_tenant_id").notNull().default(""),
444
- // TODO(dcramer): Rename provider_destination_id with the Location SQL
445
- // migration. It identifies the provider place that contains the thread.
446
- providerDestinationId: text10("provider_destination_id").notNull(),
447
- providerConversationId: text10("provider_conversation_id").notNull(),
448
- createdAt: timestamptz("created_at").notNull()
449
- },
450
- (table) => [
451
- primaryKey3({
452
- name: "junior_conversation_bindings_provider_conversation_pk",
453
- columns: [
454
- table.provider,
455
- table.providerTenantId,
456
- table.providerDestinationId,
457
- table.providerConversationId
458
- ]
459
- }),
460
- index8("junior_conversation_bindings_conversation_idx").on(
461
- table.conversationId
462
- )
463
- ]
464
- );
465
-
466
- // src/db/schema/conversation-participants.ts
467
- import { index as index9, pgTable as pgTable11, primaryKey as primaryKey4, text as text11 } from "drizzle-orm/pg-core";
468
- var juniorConversationParticipants = pgTable11(
469
- "junior_conversation_participants",
470
- {
471
- userId: text11("user_id").notNull().references(() => juniorUsers.id),
472
- rootConversationId: text11("root_conversation_id").notNull().references(() => juniorConversations.conversationId),
473
- lastMessageAt: timestamptz("last_message_at").notNull(),
474
- archivedAt: timestamptz("archived_at")
475
- },
476
- (table) => [
477
- primaryKey4({
478
- name: "junior_conversation_participants_user_root_pk",
479
- columns: [table.userId, table.rootConversationId]
480
- }),
481
- index9("junior_conversation_participants_user_activity_idx").on(
482
- table.userId,
483
- table.lastMessageAt.desc()
484
- ),
485
- index9("junior_conversation_participants_root_idx").on(
486
- table.rootConversationId
487
- )
488
- ]
489
- );
490
-
491
- // src/db/schema/agent-invocations.ts
492
- import {
493
- index as index10,
494
- jsonb as jsonb5,
495
- pgTable as pgTable12,
496
- primaryKey as primaryKey5,
497
- text as text12,
498
- uniqueIndex as uniqueIndex7
499
- } from "drizzle-orm/pg-core";
500
- var AGENT_INVOCATION_MAILBOX_STATUSES = [
501
- "pending",
502
- "appended"
503
- ];
504
- var juniorAgentBindings = pgTable12(
505
- "junior_agent_bindings",
506
- {
507
- parentConversationId: text12("parent_conversation_id").notNull().references(() => juniorConversations.conversationId),
508
- name: text12("name").notNull(),
509
- childConversationId: text12("child_conversation_id").notNull().references(() => juniorConversations.conversationId)
510
- },
511
- (table) => [
512
- primaryKey5({
513
- columns: [table.parentConversationId, table.name]
514
- }),
515
- uniqueIndex7("junior_agent_bindings_child_idx").on(
516
- table.childConversationId
517
- )
518
- ]
519
- );
520
- var juniorAgentInvocations = pgTable12(
521
- "junior_agent_invocations",
522
- {
523
- invocationId: text12("invocation_id").primaryKey(),
524
- parentConversationId: text12("parent_conversation_id").notNull().references(() => juniorConversations.conversationId),
525
- childConversationId: text12("child_conversation_id").notNull().references(() => juniorConversations.conversationId),
526
- agentName: text12("agent_name"),
527
- input: text12("input").notNull(),
528
- actor: jsonb5("actor_json").$type().notNull(),
529
- credentialContext: jsonb5(
530
- "credential_context_json"
531
- ).$type(),
532
- source: jsonb5("source_json").$type().notNull(),
533
- destination: jsonb5("destination_json").$type().notNull(),
534
- // TODO(dcramer): Remove destinationVisibility after all deployed Agent
535
- // invocation readers ignore the destination_visibility SQL column.
536
- destinationVisibility: text12(
537
- "destination_visibility"
538
- ).$type(),
539
- reasoningLevel: text12("reasoning_level").$type(),
540
- status: text12("status").$type().notNull(),
541
- mailboxStatus: text12("mailbox_status").$type().notNull(),
542
- result: text12("result"),
543
- errorMessage: text12("error_message"),
544
- createdAt: timestamptz("created_at").notNull(),
545
- updatedAt: timestamptz("updated_at").notNull(),
546
- terminalAt: timestamptz("terminal_at")
547
- },
548
- (table) => [
549
- index10("junior_agent_invocations_child_idx").on(table.childConversationId),
550
- index10("junior_agent_invocations_mailbox_idx").on(
551
- table.mailboxStatus,
552
- table.createdAt
553
- )
554
- ]
555
- );
556
-
557
- // src/db/schema/location-configurations.ts
558
- import { pgTable as pgTable13, primaryKey as primaryKey6, text as text13 } from "drizzle-orm/pg-core";
559
- var juniorLocationConfigurations = pgTable13(
560
- "junior_location_configurations",
561
- {
562
- locationId: text13("location_id").notNull().references(() => juniorDestinations.id, { onDelete: "cascade" }),
563
- key: text13("key").notNull(),
564
- value: text13("value").notNull(),
565
- updatedAt: timestamptz("updated_at").notNull(),
566
- updatedBy: text13("updated_by"),
567
- source: text13("source"),
568
- expiresAt: text13("expires_at")
569
- },
570
- (table) => [primaryKey6({ columns: [table.locationId, table.key] })]
571
- );
572
-
573
- // src/db/schema/event-tasks.ts
574
- import { sql as sql5 } from "drizzle-orm";
575
- import { bigint, index as index11, jsonb as jsonb6, pgTable as pgTable14, text as text14 } from "drizzle-orm/pg-core";
576
- var juniorEventTasks = pgTable14(
577
- "junior_event_tasks",
578
- {
579
- id: text14("id").primaryKey(),
580
- teamId: text14("team_id").notNull(),
581
- namespace: text14("namespace").notNull(),
582
- identifier: text14("identifier").notNull(),
583
- createdAtMs: bigint("created_at_ms", { mode: "number" }).notNull(),
584
- /** Retained row status. Deleted tasks keep history but stop matching. */
585
- status: text14("status").$type().notNull().default("active"),
586
- /** Short display title generated from the task instruction. */
587
- title: text14("title"),
588
- task: jsonb6("task_json").$type().notNull()
589
- },
590
- (table) => [
591
- index11("junior_event_tasks_team_idx").on(table.teamId, table.createdAtMs, table.id).where(sql5`${table.status} <> 'deleted'`),
592
- index11("junior_event_tasks_match_idx").on(table.namespace, table.identifier, table.createdAtMs, table.id).where(sql5`${table.status} <> 'deleted'`)
593
- ]
594
- );
595
-
596
- // src/db/schema/stats.ts
597
- import { date, integer as integer6, pgTable as pgTable15, primaryKey as primaryKey7, text as text15 } from "drizzle-orm/pg-core";
598
- var juniorStats = pgTable15(
599
- "junior_stats",
600
- {
601
- date: date("date", { mode: "string" }).notNull(),
602
- namespace: text15("namespace").notNull(),
603
- metric: text15("metric").notNull(),
604
- name: text15("name").notNull(),
605
- count: integer6("count").notNull().default(0)
606
- },
607
- (table) => [
608
- primaryKey7({
609
- name: "junior_stats_date_namespace_metric_name_pk",
610
- columns: [table.date, table.namespace, table.metric, table.name]
611
- })
612
- ]
613
- );
614
-
615
- // src/db/schema/task-executions.ts
616
- import { sql as sql6 } from "drizzle-orm";
617
- import {
618
- bigint as bigint2,
619
- check,
620
- foreignKey as foreignKey3,
621
- index as index12,
622
- pgTable as pgTable16,
623
- primaryKey as primaryKey8,
624
- text as text16
625
- } from "drizzle-orm/pg-core";
626
- var juniorTaskExecutions = pgTable16(
627
- "junior_task_executions",
628
- {
629
- executionId: text16("execution_id").notNull(),
630
- kind: text16("kind").notNull(),
631
- namespace: text16("namespace").notNull(),
632
- taskId: text16("task_id").notNull(),
633
- conversationId: text16("conversation_id"),
634
- executedAtMs: bigint2("executed_at_ms", { mode: "number" }).notNull(),
635
- status: text16("status").$type().notNull()
636
- },
637
- (table) => [
638
- check(
639
- "junior_task_executions_kind_check",
640
- sql6`${table.kind} in ('scheduled', 'event')`
641
- ),
642
- check(
643
- "junior_task_executions_status_check",
644
- sql6`${table.status} in ('blocked', 'completed', 'failed')`
645
- ),
646
- primaryKey8({
647
- name: "junior_task_executions_kind_namespace_execution_id_pk",
648
- columns: [table.kind, table.namespace, table.executionId]
649
- }),
650
- foreignKey3({
651
- name: "junior_task_executions_conversation_id_junior_conversations_conversation_id_fk",
652
- columns: [table.conversationId],
653
- foreignColumns: [juniorConversations.conversationId]
654
- }),
655
- index12("junior_task_executions_task_time_idx").on(
656
- table.kind,
657
- table.namespace,
658
- table.taskId,
659
- table.executedAtMs
660
- ),
661
- index12("junior_task_executions_time_kind_idx").on(
662
- table.executedAtMs,
663
- table.kind
664
- ),
665
- index12("junior_task_executions_conversation_time_idx").on(
666
- table.conversationId,
667
- table.executedAtMs
668
- )
669
- ]
670
- );
671
-
672
- // src/db/schema/scheduled-tasks.ts
673
- import { sql as sql7 } from "drizzle-orm";
674
- import { bigint as bigint3, index as index13, jsonb as jsonb7, pgTable as pgTable17, text as text17 } from "drizzle-orm/pg-core";
675
- var juniorSchedulerTasks = pgTable17(
676
- "junior_scheduler_tasks",
677
- {
678
- id: text17("id").primaryKey(),
679
- teamId: text17("team_id").notNull(),
680
- // TODO(dcramer): Remove after v0.127.x runtimes are unsupported and no
681
- // supported runtime writes this column.
682
- creatorSlackUserId: text17("creator_slack_user_id"),
683
- creatorIdentityId: text17("creator_identity_id"),
684
- status: text17("status").notNull(),
685
- nextRunAtMs: bigint3("next_run_at_ms", { mode: "number" }),
686
- runNowAtMs: bigint3("run_now_at_ms", { mode: "number" }),
687
- createdAtMs: bigint3("created_at_ms", { mode: "number" }).notNull(),
688
- /** Short display title generated from the task instruction. */
689
- title: text17("title"),
690
- record: jsonb7("record").$type().notNull()
691
- },
692
- (table) => [
693
- // TODO(dcramer): Remove after no supported runtime reads or writes the
694
- // legacy creatorSlackUserId column.
695
- index13("junior_scheduler_tasks_creator_idx").on(table.teamId, table.creatorSlackUserId, table.createdAtMs, table.id).where(sql7`${table.status} <> 'deleted'`),
696
- index13("junior_scheduler_tasks_creator_identity_idx").on(table.creatorIdentityId, table.createdAtMs, table.id).where(
697
- sql7`${table.status} <> 'deleted' AND ${table.creatorIdentityId} IS NOT NULL`
698
- ),
699
- index13("junior_scheduler_tasks_team_status_idx").on(table.teamId, table.createdAtMs, table.id).where(sql7`${table.status} <> 'deleted'`),
700
- index13("junior_scheduler_tasks_run_now_due_idx").on(table.runNowAtMs, table.createdAtMs, table.id).where(
701
- sql7`${table.status} = 'active' AND ${table.runNowAtMs} IS NOT NULL`
702
- ),
703
- index13("junior_scheduler_tasks_next_run_due_idx").on(table.nextRunAtMs, table.createdAtMs, table.id).where(
704
- sql7`${table.status} = 'active' AND ${table.nextRunAtMs} IS NOT NULL`
705
- )
706
- ]
707
- );
708
- var juniorSchedulerRuns = pgTable17(
709
- "junior_scheduler_runs",
710
- {
711
- id: text17("id").primaryKey(),
712
- taskId: text17("task_id").notNull(),
713
- status: text17("status").notNull(),
714
- scheduledForMs: bigint3("scheduled_for_ms", { mode: "number" }).notNull(),
715
- record: jsonb7("record").$type().notNull()
716
- },
717
- (table) => [
718
- index13("junior_scheduler_runs_task_status_idx").on(
719
- table.taskId,
720
- table.status,
721
- table.scheduledForMs
722
- ),
723
- index13("junior_scheduler_runs_status_idx").on(
724
- table.status,
725
- table.scheduledForMs
726
- )
727
- ]
728
- );
729
-
730
- // src/db/schema/snapshots.ts
731
- import { sql as sql8 } from "drizzle-orm";
732
- import {
733
- bigint as bigint4,
734
- check as check2,
735
- index as index14,
736
- integer as integer7,
737
- pgTable as pgTable19,
738
- text as text19,
739
- uniqueIndex as uniqueIndex9
740
- } from "drizzle-orm/pg-core";
741
-
742
- // src/db/schema/workspaces.ts
743
- import { pgTable as pgTable18, primaryKey as primaryKey9, text as text18, uniqueIndex as uniqueIndex8 } from "drizzle-orm/pg-core";
744
- var juniorWorkspaces = pgTable18(
745
- "junior_workspaces",
746
- {
747
- id: text18("id").primaryKey(),
748
- name: text18("name").notNull(),
749
- setupScript: text18("setup_script").notNull().default(""),
750
- createdAt: timestamptz("created_at").notNull(),
751
- updatedAt: timestamptz("updated_at").notNull()
752
- },
753
- (table) => [uniqueIndex8("junior_workspaces_name_idx").on(table.name)]
754
- );
755
- var juniorWorkspaceRepos = pgTable18(
756
- "junior_workspace_repos",
757
- {
758
- workspaceId: text18("workspace_id").notNull().references(() => juniorWorkspaces.id, { onDelete: "cascade" }),
759
- provider: text18("provider").notNull(),
760
- repo: text18("repo").notNull()
761
- },
762
- (table) => [
763
- primaryKey9({ columns: [table.workspaceId, table.provider, table.repo] })
764
- ]
765
- );
766
-
767
- // src/db/schema/snapshots.ts
768
- var juniorSnapshots = pgTable19(
769
- "junior_snapshots",
770
- {
771
- id: text19("id").primaryKey(),
772
- workspaceId: text19("workspace_id").notNull().references(() => juniorWorkspaces.id, { onDelete: "cascade" }),
773
- profileHash: text19("profile_hash").notNull(),
774
- status: text19("status").$type().notNull(),
775
- // Ready artifact facts.
776
- snapshotId: text19("snapshot_id"),
777
- buildDurationMs: integer7("build_duration_ms"),
778
- // Provider snapshot size when the capture response includes it.
779
- sizeBytes: bigint4("size_bytes", { mode: "number" }),
780
- generatedAt: timestamptz("generated_at"),
781
- // Builder references for check-in and snapshot-owner cleanup.
782
- buildStartedAt: timestamptz("build_started_at"),
783
- buildPhase: text19("build_phase").$type(),
784
- buildSandboxName: text19("build_sandbox_name"),
785
- buildCommandId: text19("build_command_id"),
786
- buildError: text19("build_error"),
787
- createdAt: timestamptz("created_at").notNull(),
788
- updatedAt: timestamptz("updated_at").notNull()
789
- },
790
- (table) => [
791
- check2(
792
- "junior_snapshots_status_check",
793
- sql8`${table.status} in ('building', 'failed', 'ready')`
794
- ),
795
- check2(
796
- "junior_snapshots_build_phase_check",
797
- sql8`${table.buildPhase} is null or ${table.buildPhase} in ('created', 'dependencies_installed', 'repositories_prepared')`
798
- ),
799
- check2(
800
- "junior_snapshots_ready_fields_check",
801
- sql8`${table.status} <> 'ready' or (${table.snapshotId} is not null and ${table.buildDurationMs} is not null and ${table.generatedAt} is not null)`
802
- ),
803
- check2(
804
- "junior_snapshots_build_fields_check",
805
- sql8`${table.status} = 'ready' or (${table.buildStartedAt} is not null and ${table.buildPhase} is not null)`
806
- ),
807
- check2(
808
- "junior_snapshots_build_duration_check",
809
- sql8`${table.buildDurationMs} is null or ${table.buildDurationMs} >= 0`
810
- ),
811
- check2(
812
- "junior_snapshots_size_bytes_check",
813
- sql8`${table.sizeBytes} is null or ${table.sizeBytes} >= 0`
814
- ),
815
- // Provider snapshot ids are unique. Nulls stay allowed for in-flight rows.
816
- uniqueIndex9("junior_snapshots_snapshot_id_uidx").on(table.snapshotId),
817
- index14("junior_snapshots_workspace_idx").on(table.workspaceId),
818
- index14("junior_snapshots_workspace_profile_status_idx").on(
819
- table.workspaceId,
820
- table.profileHash,
821
- table.status
822
- ),
823
- uniqueIndex9("junior_snapshots_active_build_uidx").on(table.workspaceId, table.profileHash).where(sql8`${table.status} = 'building'`),
824
- index14("junior_snapshots_workspace_status_idx").on(
825
- table.workspaceId,
826
- table.status
827
- )
828
- ]
829
- );
830
-
831
- // src/db/schema.ts
832
- var juniorSqlSchema = {
833
- juniorArtifacts,
834
- juniorAttachments,
835
- juniorCodeChanges,
836
- juniorCodeRepositories,
837
- juniorConversationAnnotations,
838
- juniorApiTokens,
839
- juniorAgentBindings,
840
- juniorAgentInvocations,
841
- juniorConversationEvents,
842
- juniorConversationBindings,
843
- juniorConversationParticipants,
844
- juniorConversations,
845
- juniorLocationConfigurations,
846
- juniorDestinations,
847
- juniorEventTasks,
848
- juniorIdentities,
849
- juniorSnapshots,
850
- juniorStats,
851
- juniorTaskExecutions,
852
- juniorSchedulerRuns,
853
- juniorSchedulerTasks,
854
- juniorUsers,
855
- juniorWorkspaceRepos,
856
- juniorWorkspaces
857
- };
858
-
859
- // src/db/neon.ts
860
- var NeonExecutor = class {
861
- constructor(pool) {
862
- this.pool = pool;
863
- }
864
- pool;
865
- transactionClient = new AsyncLocalStorage();
866
- savepointId = 0;
867
- db() {
868
- return drizzle(this.queryClient(), {
869
- schema: juniorSqlSchema
870
- });
871
- }
872
- async execute(statement, params = []) {
873
- await this.queryClient().query(statement, [...params]);
874
- }
875
- async query(statement, params = []) {
876
- const result = await this.queryClient().query(statement, [
877
- ...params
878
- ]);
879
- return result.rows;
880
- }
881
- async migrate(config) {
882
- await migrate(
883
- drizzle(this.queryClient(), { schema: juniorSqlSchema }),
884
- config
885
- );
886
- }
887
- async transaction(callback) {
888
- const existingClient = this.transactionClient.getStore();
889
- if (existingClient) {
890
- const savepoint = `junior_savepoint_${++this.savepointId}`;
891
- await existingClient.query(`SAVEPOINT ${savepoint}`);
892
- try {
893
- const result = await callback();
894
- await existingClient.query(`RELEASE SAVEPOINT ${savepoint}`);
895
- return result;
896
- } catch (error) {
897
- await existingClient.query(`ROLLBACK TO SAVEPOINT ${savepoint}`);
898
- await existingClient.query(`RELEASE SAVEPOINT ${savepoint}`);
899
- throw error;
900
- }
901
- }
902
- const client = await this.pool.connect();
903
- try {
904
- await client.query("BEGIN");
905
- const result = await this.transactionClient.run(client, callback);
906
- await client.query("COMMIT");
907
- return result;
908
- } catch (error) {
909
- await client.query("ROLLBACK");
910
- throw error;
911
- } finally {
912
- client.release();
913
- }
914
- }
915
- async withLock(lockName, callback) {
916
- if (!lockName) {
917
- throw new Error("SQL lock name is required");
918
- }
919
- const existingClient = this.transactionClient.getStore();
920
- if (existingClient) {
921
- await existingClient.query("SELECT pg_advisory_xact_lock(hashtext($1))", [
922
- lockName
923
- ]);
924
- return await callback();
925
- }
926
- const client = await this.pool.connect();
927
- try {
928
- await client.query("BEGIN");
929
- return await this.transactionClient.run(client, async () => {
930
- try {
931
- await client.query("SELECT pg_advisory_xact_lock(hashtext($1))", [
932
- lockName
933
- ]);
934
- const result = await callback();
935
- await client.query("COMMIT");
936
- return result;
937
- } catch (error) {
938
- await client.query("ROLLBACK");
939
- throw error;
940
- }
941
- });
942
- } finally {
943
- client.release();
944
- }
945
- }
946
- async withMigrationLock(migrationTable, callback) {
947
- const client = await this.pool.connect();
948
- const lockName = `junior:migrate:${migrationTable}`;
949
- try {
950
- await client.query("SELECT pg_advisory_lock(hashtext($1))", [lockName]);
951
- return await callback();
952
- } finally {
953
- client.release(true);
954
- }
955
- }
956
- async close() {
957
- await this.pool.end();
958
- }
959
- queryClient() {
960
- return this.transactionClient.getStore() ?? this.pool;
961
- }
962
- };
963
- function createNeonJuniorSqlExecutor(args) {
964
- return new NeonExecutor(
965
- new Pool({
966
- connectionString: args.connectionString,
967
- max: 3,
968
- statement_timeout: args.statementTimeoutMs
969
- })
970
- );
971
- }
972
-
973
- // src/db/postgres.ts
974
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
975
- import pg from "pg";
976
- import { drizzle as drizzle2 } from "drizzle-orm/node-postgres";
977
- import { migrate as migrate2 } from "drizzle-orm/node-postgres/migrator";
978
- var { Pool: Pool2 } = pg;
979
- var PostgresExecutor = class {
980
- constructor(pool) {
981
- this.pool = pool;
982
- }
983
- pool;
984
- transactionClient = new AsyncLocalStorage2();
985
- savepointId = 0;
986
- db() {
987
- return drizzle2(this.queryClient(), {
988
- schema: juniorSqlSchema
989
- });
990
- }
991
- async execute(statement, params = []) {
992
- await this.queryClient().query(statement, [...params]);
993
- }
994
- async query(statement, params = []) {
995
- const result = await this.queryClient().query(statement, [
996
- ...params
997
- ]);
998
- return result.rows;
999
- }
1000
- async migrate(config) {
1001
- await migrate2(
1002
- drizzle2(this.queryClient(), { schema: juniorSqlSchema }),
1003
- config
1004
- );
1005
- }
1006
- async transaction(callback) {
1007
- const existingClient = this.transactionClient.getStore();
1008
- if (existingClient) {
1009
- const savepoint = `junior_savepoint_${++this.savepointId}`;
1010
- await existingClient.query(`SAVEPOINT ${savepoint}`);
1011
- try {
1012
- const result = await callback();
1013
- await existingClient.query(`RELEASE SAVEPOINT ${savepoint}`);
1014
- return result;
1015
- } catch (error) {
1016
- await existingClient.query(`ROLLBACK TO SAVEPOINT ${savepoint}`);
1017
- await existingClient.query(`RELEASE SAVEPOINT ${savepoint}`);
1018
- throw error;
1019
- }
1020
- }
1021
- const client = await this.pool.connect();
1022
- try {
1023
- await client.query("BEGIN");
1024
- const result = await this.transactionClient.run(client, callback);
1025
- await client.query("COMMIT");
1026
- return result;
1027
- } catch (error) {
1028
- await client.query("ROLLBACK");
1029
- throw error;
1030
- } finally {
1031
- client.release();
1032
- }
1033
- }
1034
- async withLock(lockName, callback) {
1035
- if (!lockName) {
1036
- throw new Error("SQL lock name is required");
1037
- }
1038
- const existingClient = this.transactionClient.getStore();
1039
- if (existingClient) {
1040
- await existingClient.query("SELECT pg_advisory_xact_lock(hashtext($1))", [
1041
- lockName
1042
- ]);
1043
- return await callback();
1044
- }
1045
- const client = await this.pool.connect();
1046
- try {
1047
- await client.query("BEGIN");
1048
- return await this.transactionClient.run(client, async () => {
1049
- try {
1050
- await client.query("SELECT pg_advisory_xact_lock(hashtext($1))", [
1051
- lockName
1052
- ]);
1053
- const result = await callback();
1054
- await client.query("COMMIT");
1055
- return result;
1056
- } catch (error) {
1057
- await client.query("ROLLBACK");
1058
- throw error;
1059
- }
1060
- });
1061
- } finally {
1062
- client.release();
1063
- }
1064
- }
1065
- async withMigrationLock(migrationTable, callback) {
1066
- const client = await this.pool.connect();
1067
- const lockName = `junior:migrate:${migrationTable}`;
1068
- try {
1069
- await client.query("SELECT pg_advisory_lock(hashtext($1))", [lockName]);
1070
- return await callback();
1071
- } finally {
1072
- client.release(true);
1073
- }
1074
- }
1075
- async close() {
1076
- await this.pool.end();
1077
- }
1078
- queryClient() {
1079
- return this.transactionClient.getStore() ?? this.pool;
1080
- }
1081
- };
1082
- function createPostgresJuniorSqlExecutor(args) {
1083
- return new PostgresExecutor(
1084
- new Pool2({
1085
- application_name: args.applicationName,
1086
- connectionString: args.connectionString,
1087
- max: 3,
1088
- statement_timeout: args.statementTimeoutMs
1089
- })
1090
- );
1091
- }
1092
-
1093
- // src/db/executor.ts
1094
- function createJuniorSqlExecutor(args) {
1095
- const statementTimeoutMs = args.statementTimeoutMs ?? DEFAULT_SQL_STATEMENT_TIMEOUT_MS;
1096
- if (args.driver === "postgres") {
1097
- return createPostgresJuniorSqlExecutor({
1098
- connectionString: args.connectionString,
1099
- statementTimeoutMs
1100
- });
1101
- }
1102
- return createNeonJuniorSqlExecutor({
1103
- connectionString: args.connectionString,
1104
- statementTimeoutMs
1105
- });
1106
- }
1107
-
1108
- export {
1109
- juniorArtifacts,
1110
- juniorUsers,
1111
- juniorIdentities,
1112
- juniorConversations,
1113
- conversationReadColumns,
1114
- juniorAttachments,
1115
- juniorCodeRepositories,
1116
- juniorCodeChanges,
1117
- juniorConversationAnnotations,
1118
- juniorApiTokens,
1119
- juniorConversationEvents,
1120
- juniorConversationBindings,
1121
- juniorConversationParticipants,
1122
- AGENT_INVOCATION_MAILBOX_STATUSES,
1123
- juniorAgentBindings,
1124
- juniorAgentInvocations,
1125
- juniorLocationConfigurations,
1126
- juniorEventTasks,
1127
- juniorStats,
1128
- juniorTaskExecutions,
1129
- juniorSchedulerTasks,
1130
- juniorSchedulerRuns,
1131
- juniorWorkspaces,
1132
- juniorWorkspaceRepos,
1133
- juniorSnapshots,
1134
- createJuniorSqlExecutor
1135
- };