@sentry/junior 0.313.0 → 0.314.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 (108) hide show
  1. package/dist/{adapter-CYAvJzZS.js → adapter-JARQvoLw.js} +1 -2
  2. package/dist/{adapter-context-CVsHoVSf.js → adapter-context-B4BrJZuS.js} +2 -2
  3. package/dist/{admin-Cyhb4TwZ.js → admin-BXGAySz0.js} +1 -1
  4. package/dist/{agent-runner-B5y9MsT-.js → agent-runner-qZU5TR8i.js} +797 -118
  5. package/dist/agent-update-cS7Z9mnG.js +26 -0
  6. package/dist/agent-update-delivery-CZ5M8RDa.js +85 -0
  7. package/dist/api/schema.d.ts +2 -2
  8. package/dist/api/schema.js +6 -6
  9. package/dist/api.d.ts +1 -1
  10. package/dist/api.js +334 -100
  11. package/dist/{app-DA8-hCMj.d.ts → app-D7tKnw9a.d.ts} +4 -21
  12. package/dist/app.d.ts +2 -2
  13. package/dist/app.js +80 -169
  14. package/dist/{background-compaction-queue-iZXadLV3.js → background-compaction-queue-C_uIBUvS.js} +6 -67
  15. package/dist/callback-C8SdXCwr.js +68 -0
  16. package/dist/{catalog-runtime-kkE3hvCX.js → catalog-runtime-BLKtnUL3.js} +1 -1
  17. package/dist/{channel-access-mt7K6dPh.js → channel-access-BOL29BG3.js} +6 -6
  18. package/dist/child-message--2G3Ft26.js +19 -0
  19. package/dist/cli/chat.js +18 -21
  20. package/dist/cli/check.js +4 -4
  21. package/dist/cli/main.js +2 -2
  22. package/dist/cli/plugins.js +5 -5
  23. package/dist/cli/snapshot-create.js +5 -5
  24. package/dist/cli/upgrade.d.ts +1 -1
  25. package/dist/cli/upgrade.js +23 -4
  26. package/dist/{config-CWbwKj0j.js → config-BIfHKNXN.js} +40 -35
  27. package/dist/{continue-in-slack-CxyFzdlF.js → continue-in-slack-fnmD2Ifb.js} +5 -7
  28. package/dist/{conversation-feed-BEXLD3Me.js → conversation-feed-DdFQuQDR.js} +1 -1
  29. package/dist/{logging-DNt-qOIO.js → conversation-privacy-DtZhI91r.js} +188 -2
  30. package/dist/{conversation-turn-B35eu0uz.js → conversation-turn-DScuDYmN.js} +418 -33
  31. package/dist/create-CrNt4Ewu.js +212 -0
  32. package/dist/{credential-sync-DWTOEQrm.js → credential-sync-CtqsGjj1.js} +14 -17
  33. package/dist/{credentialed-Dyv8b-lu.js → credentialed-dWRA3-oJ.js} +910 -426
  34. package/dist/{db-PwSRzWWn.js → db-BTmLKZrp.js} +2235 -38
  35. package/dist/{db-DYGcXYl3.d.ts → db-DcmzbA55.d.ts} +2 -2
  36. package/dist/{history-CYstOMKX.js → history-CneKY7_V.js} +19 -1
  37. package/dist/{html-DidUcRhI.js → html-B8rBt7F4.js} +5 -7
  38. package/dist/{install-2urLLXNt.js → install-OtFboxOM.js} +2 -2
  39. package/dist/instrumentation.js +2 -2
  40. package/dist/{lineage-BXplQAVH.js → lineage-EULJkGO1.js} +1 -2
  41. package/dist/{list-DyIyReSV.js → list-C5400AlJ.js} +235 -77
  42. package/dist/{turn-membership-DTR3SaKD.js → mailbox-turn-DL3Lvsm0.js} +4698 -587
  43. package/dist/markers-DUP8aBOp.js +323 -0
  44. package/dist/{media-B0pZJ0bG.js → media-FYM-Bl3H.js} +33 -8
  45. package/dist/{message-Z5YKC-Af.js → message-DuDelZFr.js} +16 -29
  46. package/dist/{model-input-BhPJYdSV.js → model-input-0osF3pBS.js} +3 -3
  47. package/dist/nitro.d.ts +2 -4
  48. package/dist/nitro.js +340 -13
  49. package/dist/{oauth-callback-server-ByvDdcdY.js → oauth-callback-server-DX2fQ7Nq.js} +2 -2
  50. package/dist/{oauth-relay-D-kK0yoN.js → oauth-relay-PwPMdZJv.js} +1 -1
  51. package/dist/{plugins-Bkk0XRo2.js → plugins-BXMdNdyA.js} +1 -1
  52. package/dist/{registry-POH4bZC4.js → registry-D6kS6xYH.js} +1402 -64
  53. package/dist/{resolve-CWtBNSKP.js → resolve-D8CPJcNK.js} +3 -3
  54. package/dist/result-D090hxr5.js +402 -0
  55. package/dist/{runner-CsZ_VRxp.js → runner-BU7fgrm-.js} +7 -8
  56. package/dist/{sandbox-egress-signals-FbCk1FkN.js → sandbox-egress-signals-BUmVrsoG.js} +1 -1
  57. package/dist/{schema-DojR2uCL.js → schema-7gW9vBpJ.js} +90 -9
  58. package/dist/{schema-DBf18QPS.d.ts → schema-BB6E0wyV.d.ts} +138 -5
  59. package/dist/{service-account-CDYb9hfX.js → service-account-plA-uzIB.js} +6 -5
  60. package/dist/{skills-B0jP4whm.js → skills-CIosT6bS.js} +3 -3
  61. package/dist/{slack-conversation-unfurl-D26t9kBC.js → slack-conversation-unfurl-CBgZqth6.js} +8 -10
  62. package/dist/{spawn-BjljgExZ.js → spawn-DRjdzh3R.js} +9 -17
  63. package/dist/{start-conversation-DbVujrwO.js → start-conversation-a4NXH4X9.js} +12 -15
  64. package/dist/{store-CjXrp-Up.js → store-BuhF1QDm.js} +2 -4
  65. package/dist/{task-queue-Cwlatjz3.js → task-queue-CrRjFzOh.js} +5 -16
  66. package/dist/{task-runner--Ke8KSMf.js → task-runner-C-pXsgHM.js} +104 -50
  67. package/dist/{thread-context-B8exINEe.js → thread-context-CDX4dSZd.js} +8 -9
  68. package/dist/turn-session-routing-CZTRU8IY.js +116 -0
  69. package/dist/turn-wake-Bzq1Efrm.js +154 -0
  70. package/dist/user-customization-B27StpVQ.js +9 -0
  71. package/dist/{validation-Ce0qbMlT.js → validation-bTq88sya.js} +1 -1
  72. package/dist/{vercel-queue-q4z8w5QO.js → vercel-queue-nL0Hq3hr.js} +32 -147
  73. package/dist/{version-DFh4n9nr.js → version-DGUa1dZK.js} +1 -1
  74. package/dist/version.js +1 -1
  75. package/dist/{warmup-D5hzqTcp.js → warmup-CCOuIwAS.js} +639 -137
  76. package/dist/{worker-CDg9Lbpg.js → worker-AkZg7Dg1.js} +5 -6
  77. package/migrations/0160_money_micro_usd_repair.sql +99 -0
  78. package/migrations/0161_agent_config_backfill.sql +34 -0
  79. package/migrations/0162_inbox_item_deliveries.sql +15 -0
  80. package/migrations/0163_pg_trgm.sql +2 -0
  81. package/migrations/0164_search_indexes.sql +4 -0
  82. package/migrations/0165_drop_legacy_archive_columns.sql +4 -0
  83. package/migrations/0166_memory_prefix_index.sql +1 -0
  84. package/migrations/0167_todo_search_indexes.sql +2 -0
  85. package/migrations/0168_todo_inbox_items.sql +4 -0
  86. package/migrations/0169_drop_code_urls.sql +2 -0
  87. package/migrations/meta/0160_snapshot.json +6515 -0
  88. package/migrations/meta/0161_snapshot.json +6278 -0
  89. package/migrations/meta/0162_snapshot.json +6404 -0
  90. package/migrations/meta/0163_snapshot.json +6404 -0
  91. package/migrations/meta/0164_snapshot.json +6466 -0
  92. package/migrations/meta/0165_snapshot.json +6466 -0
  93. package/migrations/meta/0166_snapshot.json +6494 -0
  94. package/migrations/meta/0167_snapshot.json +6525 -0
  95. package/migrations/meta/0168_snapshot.json +6525 -0
  96. package/migrations/meta/0169_snapshot.json +6513 -0
  97. package/migrations/meta/_journal.json +70 -0
  98. package/package.json +9 -18
  99. package/skills/design-automation-skill/SKILL.md +2 -3
  100. package/dist/actor-BsBdxDXQ.js +0 -208
  101. package/dist/conversation-privacy-BrMiDN61.js +0 -189
  102. package/dist/executor-CgWyWfYz.js +0 -1858
  103. package/dist/fan-out-Cod-yEHG.js +0 -10
  104. package/dist/ingest-B0AggUEC.js +0 -7931
  105. package/dist/request-deadline-BUiRYQYj.js +0 -24
  106. package/dist/service-account-o15pZWcJ.js +0 -931
  107. package/dist/state-BTawTCme.js +0 -161
  108. package/dist/statuses-BKwqCPhj.js +0 -69
@@ -1,1858 +0,0 @@
1
- import { h as logWarn, p as logException } from "./logging-DNt-qOIO.js";
2
- import { _ as withScope } from "./sentry-CPbZjomA.js";
3
- import "./config-CWbwKj0j.js";
4
- import * as z from "zod";
5
- import { AsyncLocalStorage } from "node:async_hooks";
6
- import { actorSchema, sourceSchema } from "@sentry/junior-plugin-api";
7
- import { sql } from "drizzle-orm";
8
- import { bigint, boolean, check, customType, date, doublePrecision, foreignKey, index, integer, jsonb, pgSequence, pgTable, primaryKey, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
9
- import { Pool as Pool$1, neon } from "@neondatabase/serverless";
10
- import { drizzle } from "drizzle-orm/neon-serverless";
11
- import { Agent } from "undici";
12
- import { readMigrationFiles } from "drizzle-orm/migrator";
13
- import pg from "pg";
14
- import { drizzle as drizzle$1 } from "drizzle-orm/node-postgres";
15
- // src/db/schema/timestamps.ts
16
- const timestamptz = (name) => timestamp(name, { withTimezone: true });
17
- // src/db/schema/artifacts.ts
18
- /** Durable metadata for conversation-owned artifacts. */
19
- const juniorArtifacts = pgTable("junior_artifacts", {
20
- /** Row identity. A public row serves at `/public/artifacts/<id>.<ext>`. */
21
- id: text("id").primaryKey(),
22
- conversationId: text("conversation_id").notNull(),
23
- sha256: text("sha256").notNull(),
24
- ext: text("ext").notNull(),
25
- storageKey: text("storage_key").notNull(),
26
- contentType: text("content_type").notNull(),
27
- bytes: integer("bytes").notNull(),
28
- /**
29
- * Path under the Sandbox `artifacts/` directory for a live file. Null for
30
- * a public frozen copy, such as a published image.
31
- */
32
- path: text("path"),
33
- visibility: text("visibility").$type().notNull().default("conversation"),
34
- createdAt: timestamptz("created_at").notNull(),
35
- /** Set when the artifact is unpublished or its live file is deleted. */
36
- deleteRequestedAt: timestamptz("delete_requested_at"),
37
- /** When a public artifact stops serving. Null serves until unpublished. */
38
- expiresAt: timestamptz("expires_at")
39
- }, (table) => [
40
- check("junior_artifacts_visibility_check", sql`${table.visibility} in ('conversation', 'internal', 'public')`),
41
- check("junior_artifacts_path_visibility_check", sql`(${table.path} is null) = (${table.visibility} = 'public')`),
42
- uniqueIndex("junior_artifacts_conversation_path_uidx").on(table.conversationId, table.path),
43
- uniqueIndex("junior_artifacts_permanent_sha_uidx").on(table.conversationId, table.sha256).where(sql`${table.visibility} = 'public' and ${table.expiresAt} is null`),
44
- index("junior_artifacts_gc_idx").on(table.deleteRequestedAt, table.createdAt),
45
- index("junior_artifacts_conversation_idx").on(table.conversationId)
46
- ]);
47
- // src/db/embeddings.ts
48
- /**
49
- * Shared parts of the derived embedding indexes. Each owner keeps its own
50
- * table, so a foreign key still deletes a vector with its source row. These
51
- * helpers keep the column types, the distance SQL, the batch checks, and the
52
- * backfill loop the same in every table.
53
- */
54
- function pgvectorColumn(dataType) {
55
- return customType({
56
- dataType() {
57
- return dataType;
58
- },
59
- toDriver(value) {
60
- return JSON.stringify(value);
61
- },
62
- fromDriver(value) {
63
- return value.slice(1, -1).split(",").map(Number);
64
- }
65
- });
66
- }
67
- /**
68
- * pgvector `vector` column without a fixed size, so a new embedding model
69
- * needs no migration. Each table records the size of each row in its own
70
- * column.
71
- */
72
- const embeddingVector = pgvectorColumn("vector");
73
- /**
74
- * Half-precision `embeddingVector`: 2 bytes per value instead of 4, for
75
- * tables that hold many vectors.
76
- */
77
- const embeddingHalfvec = pgvectorColumn("halfvec");
78
- const embeddingResultSchema = z.object({
79
- costUsd: z.number().finite().nonnegative().optional(),
80
- dimensions: z.number().int().positive(),
81
- model: z.string().min(1),
82
- provider: z.string().min(1),
83
- vectors: z.array(z.array(z.number().finite()))
84
- }).strict();
85
- /**
86
- * Validate an embedder result: one vector per text, all of the reported
87
- * size. With `dimensions`, the size must be one that the table accepts. With
88
- * `expected`, the result must come from that provider and model, because a
89
- * backfill that finds rows by model would see a row of another model as
90
- * missing on every run.
91
- */
92
- function parseEmbeddingBatch(raw, args) {
93
- const result = embeddingResultSchema.parse(raw);
94
- if (args.dimensions && !args.dimensions.includes(result.dimensions)) throw new Error("Unsupported embedding vector size.");
95
- if (result.vectors.length !== args.textCount) throw new Error("Embedding provider returned an unexpected vector count.");
96
- if (result.vectors.some((vector) => vector.length !== result.dimensions)) throw new Error("Embedding provider returned an unexpected vector size.");
97
- if (args.expected && (result.provider !== args.expected.provider || result.model !== args.expected.model)) throw new Error(`Embedding provider used model ${result.provider}/${result.model}, not ${args.expected.provider}/${args.expected.model}.`);
98
- return {
99
- dimensions: result.dimensions,
100
- model: result.model,
101
- provider: result.provider,
102
- vectors: result.vectors
103
- };
104
- }
105
- /** Embed one text with the embedder's model and return its vector. */
106
- async function embedText(embedder, input) {
107
- const batch = parseEmbeddingBatch(await embedder.embedTexts({
108
- inputType: input.inputType,
109
- texts: [input.text]
110
- }), {
111
- expected: embedder,
112
- textCount: 1
113
- });
114
- return {
115
- model: batch.model,
116
- provider: batch.provider,
117
- vector: batch.vectors[0]
118
- };
119
- }
120
- function vectorSize(query) {
121
- if (query.length === 0) throw new Error("Embedding vector is empty.");
122
- return sql.raw(String(query.length));
123
- }
124
- /**
125
- * Cosine distance from a stored vector to a query vector. Both sides are cast
126
- * to the query size, the form that an HNSW expression index on that size
127
- * matches. The cast fails on a stored vector of another size, so filter on the
128
- * size first, as the index predicate does, or use `guardedCosineDistance`.
129
- * A caller with another copy of drizzle-orm embeds the result in its own
130
- * `sql` template to get its own `SQL` type.
131
- */
132
- function cosineDistance(args) {
133
- const size = vectorSize(args.query);
134
- const type = sql.raw(args.type);
135
- return sql`(${args.column}::${type}(${size})) <=> ${JSON.stringify(args.query)}::${type}(${size})`;
136
- }
137
- /**
138
- * `cosineDistance`, or null for a stored vector of another size. Postgres
139
- * does not promise to check a WHERE term before it computes an ORDER BY or
140
- * SELECT expression, and pgvector fails on vectors of two sizes. CASE fixes
141
- * the order.
142
- */
143
- function guardedCosineDistance(args) {
144
- return sql`CASE WHEN ${args.dimensions} = ${vectorSize(args.query)} THEN ${cosineDistance(args)} END`;
145
- }
146
- /**
147
- * Embed items that have no current vector, one batch at a time, and store
148
- * each batch before the next starts. `listMissing` returns the next items in
149
- * the caller's order, after the last item of the previous page, so each run
150
- * ends even when a write leaves an item missing. Text that trims to nothing
151
- * is skipped, because the embedder rejects it. A provider failure stops the
152
- * run and keeps the batches stored before it, so a later run continues.
153
- */
154
- async function refreshEmbeddings(args) {
155
- const now = args.now ?? Date.now;
156
- let after;
157
- let embedded = 0;
158
- for (;;) {
159
- const remaining = (args.maxItems ?? 1e400) - embedded;
160
- if (remaining <= 0 || args.deadlineMs !== void 0 && now() >= args.deadlineMs) return {
161
- done: false,
162
- embedded
163
- };
164
- const page = await args.listMissing({
165
- after,
166
- limit: Math.min(args.batchSize, remaining)
167
- });
168
- after = page.at(-1);
169
- if (!after) return {
170
- done: true,
171
- embedded
172
- };
173
- const items = page.filter((item) => item.text.trim() !== "");
174
- if (items.length === 0) continue;
175
- const batch = parseEmbeddingBatch(await args.embedder.embedTexts({
176
- inputType: "document",
177
- texts: items.map((item) => item.text)
178
- }), {
179
- ...args.dimensions ? { dimensions: args.dimensions } : void 0,
180
- expected: args.embedder,
181
- textCount: items.length
182
- });
183
- await args.write(items.map((item, index) => ({
184
- item,
185
- vector: batch.vectors[index]
186
- })), batch);
187
- embedded += items.length;
188
- }
189
- }
190
- // src/db/schema/tsvector.ts
191
- /** Postgres full-text lexemes. Queries read them only through SQL. */
192
- const tsvector = customType({ dataType() {
193
- return "tsvector";
194
- } });
195
- // src/chat/memory/types.ts
196
- const MEMORY_KINDS = [
197
- "preference",
198
- "procedure",
199
- "knowledge"
200
- ];
201
- const MEMORY_SCOPES = ["private", "public"];
202
- const MEMORY_SUBJECT_TYPES = [
203
- "user",
204
- "conversation",
205
- "general"
206
- ];
207
- const MEMORY_SOURCE_PLATFORMS = [
208
- "slack",
209
- "local",
210
- "web"
211
- ];
212
- const MEMORY_EMBEDDING_METRICS = ["cosine"];
213
- /** Things that can happen to a stored memory and feed future recall weights. */
214
- /** `contradicted` and `superseded` record why a memory was retired. */
215
- const MEMORY_SIGNALS = [
216
- "duplicate",
217
- "contradicted",
218
- "superseded"
219
- ];
220
- /**
221
- * Vector sizes the embeddings table can store, so one table can hold vectors
222
- * from an old and a new model while a model change is in progress. Only 1024
223
- * has an HNSW index.
224
- */
225
- const MEMORY_EMBEDDING_DIMENSIONS = [1024, 1536];
226
- const nonEmptyStringSchema = z.string().min(1);
227
- /** Host data used to set memory access, subject, and source. */
228
- const memoryRuntimeContextSchema = z.object({
229
- conversationId: nonEmptyStringSchema.optional(),
230
- locationId: nonEmptyStringSchema.optional(),
231
- actor: actorSchema.optional(),
232
- source: sourceSchema,
233
- /** User linked to the active Actor. */
234
- userId: nonEmptyStringSchema.optional()
235
- }).strict();
236
- // src/db/schema/memory.ts
237
- const juniorMemoryMemories = pgTable("junior_memory_memories", {
238
- id: text("id").primaryKey(),
239
- scope: text("scope", { enum: MEMORY_SCOPES }).notNull(),
240
- scopeKey: text("scope_key").notNull(),
241
- kind: text("type", { enum: MEMORY_KINDS }).notNull(),
242
- subjectType: text("subject_type", { enum: MEMORY_SUBJECT_TYPES }).notNull(),
243
- subjectKey: text("subject_key"),
244
- content: text("content").notNull(),
245
- searchVector: tsvector("search_vector").generatedAlwaysAs(sql`to_tsvector('english', "content")`),
246
- sourcePlatform: text("source_platform", { enum: MEMORY_SOURCE_PLATFORMS }).notNull(),
247
- sourceKey: text("source_key").notNull(),
248
- /** Location where Junior learned the memory, when known. */
249
- locationId: text("location_id"),
250
- /** Conversation where Junior learned the memory, when known. */
251
- conversationId: text("conversation_id"),
252
- idempotencyKey: text("idempotency_key"),
253
- observedAtMs: bigint("observed_at_ms", { mode: "number" }).notNull(),
254
- createdAtMs: bigint("created_at_ms", { mode: "number" }).notNull(),
255
- expiresAtMs: bigint("expires_at_ms", { mode: "number" }),
256
- supersededAtMs: bigint("superseded_at_ms", { mode: "number" }),
257
- supersededById: text("superseded_by_id"),
258
- archivedAtMs: bigint("archived_at_ms", { mode: "number" }),
259
- archiveReason: text("archive_reason")
260
- }, (table) => [
261
- index("junior_memory_memories_visible_idx").on(table.scope, table.scopeKey, table.createdAtMs.desc(), table.id).where(sql`${table.archivedAtMs} IS NULL AND ${table.supersededAtMs} IS NULL AND ${table.supersededById} IS NULL`),
262
- index("junior_memory_memories_expiration_idx").on(table.expiresAtMs).where(sql`${table.archivedAtMs} IS NULL AND ${table.expiresAtMs} IS NOT NULL`),
263
- index("junior_memory_memories_search_idx").using("gin", table.scope, table.scopeKey, table.searchVector).where(sql`${table.archivedAtMs} IS NULL AND ${table.supersededAtMs} IS NULL AND ${table.supersededById} IS NULL`),
264
- uniqueIndex("junior_memory_memories_idempotency_idx").on(table.scope, table.scopeKey, table.idempotencyKey).where(sql`${table.idempotencyKey} IS NOT NULL AND ${table.archivedAtMs} IS NULL AND ${table.supersededAtMs} IS NULL AND ${table.supersededById} IS NULL`),
265
- index("junior_memory_memories_archived_idempotency_idx").on(table.scope, table.scopeKey, table.idempotencyKey).where(sql`${table.idempotencyKey} IS NOT NULL AND ${table.archivedAtMs} IS NOT NULL AND ${table.archiveReason} <> 'expired'`),
266
- check("junior_memory_memories_scope_check", sql`${table.scope} IN ('private', 'public')`),
267
- check("junior_memory_memories_kind_check", sql`${table.kind} IN (
268
- 'preference',
269
- 'procedure',
270
- 'knowledge'
271
- )`),
272
- check("junior_memory_memories_subject_type_check", sql`${table.subjectType} IN ('user', 'conversation', 'general')`),
273
- check("junior_memory_memories_subject_key_check", sql`(${table.subjectType} = 'general' AND ${table.subjectKey} IS NULL) OR (${table.subjectType} IN ('user', 'conversation') AND ${table.subjectKey} IS NOT NULL AND length(${table.subjectKey}) > 0)`),
274
- check("junior_memory_memories_source_platform_check", sql`${table.sourcePlatform} IN ('slack', 'local', 'web')`)
275
- ]);
276
- const juniorMemoryEmbeddings = pgTable("junior_memory_embeddings", {
277
- memoryId: text("memory_id").notNull().references(() => juniorMemoryMemories.id, { onDelete: "cascade" }),
278
- provider: text("provider").notNull(),
279
- model: text("model").notNull(),
280
- dimensions: integer("dimensions").notNull(),
281
- metric: text("metric", { enum: MEMORY_EMBEDDING_METRICS }).notNull(),
282
- contentHash: text("content_hash").notNull(),
283
- embedding: embeddingVector("embedding").notNull(),
284
- createdAtMs: bigint("created_at_ms", { mode: "number" }).notNull()
285
- }, (table) => [
286
- primaryKey({ columns: [
287
- table.memoryId,
288
- table.provider,
289
- table.model
290
- ] }),
291
- index("junior_memory_embeddings_model_idx").on(table.provider, table.model, table.dimensions, table.metric),
292
- index("junior_memory_embeddings_embedding_1024_hnsw_idx").using("hnsw", sql`(${table.embedding}::vector(1024)) vector_cosine_ops`).with({
293
- m: 16,
294
- ef_construction: 64
295
- }).where(sql`${table.dimensions} = 1024`),
296
- check("junior_memory_embeddings_metric_check", sql`${table.metric} IN ('cosine')`),
297
- check("junior_memory_embeddings_dimensions_check", sql`${table.dimensions} IN (${sql.raw(MEMORY_EMBEDDING_DIMENSIONS.join(", "))}) AND vector_dims(${table.embedding}) = ${table.dimensions}`)
298
- ]);
299
- /**
300
- * Thin log of signals about stored memories, such as a capture that resolved
301
- * to an existing memory. Callers count recent rows to weigh memories.
302
- */
303
- const juniorMemorySignals = pgTable("junior_memory_signals", {
304
- memoryId: text("memory_id").notNull().references(() => juniorMemoryMemories.id, { onDelete: "cascade" }),
305
- signal: text("signal", { enum: MEMORY_SIGNALS }).notNull(),
306
- idempotencyKey: text("idempotency_key").notNull(),
307
- /** Conversation where Junior saw the signal, when known. */
308
- conversationId: text("conversation_id"),
309
- observedAtMs: bigint("observed_at_ms", { mode: "number" }).notNull()
310
- }, (table) => [
311
- primaryKey({ columns: [
312
- table.memoryId,
313
- table.signal,
314
- table.idempotencyKey
315
- ] }),
316
- index("junior_memory_signals_observed_idx").on(table.memoryId, table.signal, table.observedAtMs),
317
- check("junior_memory_signals_signal_check", sql`${table.signal} IN ('duplicate', 'contradicted', 'superseded')`)
318
- ]);
319
- // src/db/schema/destinations.ts
320
- const juniorDestinations = pgTable("junior_destinations", {
321
- id: text("id").primaryKey(),
322
- provider: text("provider").notNull(),
323
- providerTenantId: text("provider_tenant_id").notNull().default(""),
324
- providerDestinationId: text("provider_destination_id").notNull(),
325
- kind: text("kind").$type().notNull(),
326
- parentDestinationId: text("parent_destination_id"),
327
- displayName: text("display_name"),
328
- visibility: text("visibility").$type().notNull().default("unknown"),
329
- metadata: jsonb("metadata_json"),
330
- createdAt: timestamptz("created_at").notNull(),
331
- updatedAt: timestamptz("updated_at").notNull()
332
- }, (table) => [uniqueIndex("junior_destinations_provider_destination_uidx").on(table.provider, table.providerTenantId, table.providerDestinationId), index("junior_destinations_provider_kind_idx").on(table.provider, table.kind)]);
333
- const juniorUsers = pgTable("junior_users", {
334
- id: text("id").primaryKey(),
335
- primaryEmail: text("primary_email").notNull(),
336
- primaryEmailNormalized: text("primary_email_normalized").notNull(),
337
- displayName: text("display_name"),
338
- timezone: text("timezone"),
339
- /** Text the user saved to change how Junior replies to them. */
340
- customization: text("customization"),
341
- /** Push notification hours. Null means the default schedule. */
342
- notificationSchedule: jsonb("notification_schedule").$type(),
343
- /** Junior-wide admin role. Only the `junior admin` CLI changes it. */
344
- isAdmin: boolean("is_admin").notNull().default(false),
345
- /** Auto-archive this user's conversations when their work is done. */
346
- autoArchiveDefault: boolean("auto_archive_default").notNull().default(false),
347
- /** Hours done work and the conversation stay quiet before auto-archive. */
348
- autoArchiveGraceHours: integer("auto_archive_grace_hours").notNull().default(24),
349
- /**
350
- * Small per-user choices, such as an experiment opt-in, that can come
351
- * and go without a migration. `api/user-settings.ts` owns the keys.
352
- */
353
- preferences: jsonb("preferences").$type().notNull().default({}),
354
- createdAt: timestamptz("created_at").notNull(),
355
- updatedAt: timestamptz("updated_at").notNull()
356
- }, (table) => [uniqueIndex("junior_users_primary_email_normalized_uidx").on(table.primaryEmailNormalized)]);
357
- // src/db/schema/identities.ts
358
- /** Words of a Slack person's name and handle, for prefix search. */
359
- function slackPersonSearchDocument(table) {
360
- return sql`to_tsvector('simple', coalesce(${table.displayName}, '') || ' ' || coalesce(${table.handle}, ''))`;
361
- }
362
- /**
363
- * Slack people. Literal values, so a prepared query with this predicate
364
- * can use the partial index.
365
- */
366
- function slackPersonPredicate(table) {
367
- return sql`${table.provider} = 'slack' AND ${table.kind} = 'user'`;
368
- }
369
- const juniorIdentities = pgTable("junior_identities", {
370
- id: text("id").primaryKey(),
371
- kind: text("kind").$type().notNull(),
372
- provider: text("provider").notNull(),
373
- providerTenantId: text("provider_tenant_id").notNull().default(""),
374
- providerSubjectId: text("provider_subject_id").notNull(),
375
- displayName: text("display_name"),
376
- handle: text("handle"),
377
- email: text("email"),
378
- avatarUrl: text("avatar_url"),
379
- metadata: jsonb("metadata_json"),
380
- createdAt: timestamptz("created_at").notNull(),
381
- updatedAt: timestamptz("updated_at").notNull(),
382
- userId: text("user_id").references(() => juniorUsers.id),
383
- emailNormalized: text("email_normalized"),
384
- emailVerified: boolean("email_verified").notNull().default(false),
385
- signedInAt: timestamptz("signed_in_at")
386
- }, (table) => [
387
- uniqueIndex("junior_identities_provider_subject_uidx").on(table.provider, table.providerTenantId, table.providerSubjectId),
388
- index("junior_identities_user_idx").on(table.userId),
389
- index("junior_identities_verified_email_idx").on(table.emailNormalized).where(sql`${table.emailVerified} = true AND ${table.emailNormalized} IS NOT NULL`),
390
- index("junior_identities_kind_provider_idx").on(table.kind, table.provider),
391
- index("junior_identities_slack_person_search_idx").using("gin", slackPersonSearchDocument(table)).where(slackPersonPredicate(table))
392
- ]);
393
- // src/db/schema/conversations.ts
394
- const juniorConversations = pgTable("junior_conversations", {
395
- conversationId: text("conversation_id").primaryKey(),
396
- schemaVersion: integer("schema_version").notNull().default(1),
397
- source: text("source").$type(),
398
- /** Structured session Source locator; set-once on the conversation root. */
399
- sessionSource: jsonb("source_json").$type(),
400
- /** Complete Location associated with this Conversation. */
401
- location: jsonb("location_json").$type(),
402
- destinationId: text("destination_id").references(() => juniorDestinations.id),
403
- destination: jsonb("destination_json").$type(),
404
- actorIdentityId: text("actor_identity_id").references(() => juniorIdentities.id),
405
- creatorIdentityId: text("creator_identity_id").references(() => juniorIdentities.id),
406
- credentialSubjectIdentityId: text("credential_subject_identity_id").references(() => juniorIdentities.id),
407
- actor: jsonb("actor_json").$type(),
408
- channelName: text("channel_name"),
409
- title: text("title"),
410
- summary: text("summary"),
411
- metadataThroughSeq: integer("metadata_through_seq"),
412
- createdAt: timestamptz("created_at").notNull(),
413
- lastActivityAt: timestamptz("last_activity_at").notNull(),
414
- /**
415
- * The newest Message that a reader would notice (`refreshLastMessageAt`).
416
- * Null until the Conversation has one.
417
- */
418
- lastMessageAt: timestamptz("last_message_at"),
419
- updatedAt: timestamptz("updated_at").notNull(),
420
- executionUpdatedAt: timestamptz("execution_updated_at"),
421
- executionStatus: text("execution_status").$type().notNull(),
422
- runId: text("run_id"),
423
- lastCheckpointAt: timestamptz("last_checkpoint_at"),
424
- lastEnqueuedAt: timestamptz("last_enqueued_at"),
425
- parentConversationId: text("parent_conversation_id").references(() => juniorConversations.conversationId),
426
- kind: text("kind").$type(),
427
- agentConfig: jsonb("agent_config_json").$type(),
428
- archivedAt: timestamptz("archived_at"),
429
- forkedFromConversationId: text("forked_from_conversation_id").references(() => juniorConversations.conversationId, { onDelete: "set null" }),
430
- quickQuestionAt: timestamptz("quick_question_at"),
431
- rootConversationId: text("root_conversation_id").references(() => juniorConversations.conversationId),
432
- transcriptPurgedAt: timestamptz("transcript_purged_at"),
433
- /**
434
- * Set while the Conversation is stopped. Its Watch Events are then saved
435
- * as Messages that start no Turn. A person's later input, or new work
436
- * from its parent, clears it.
437
- */
438
- stoppedAt: timestamptz("stopped_at"),
439
- /**
440
- * Set while a root's Event Turn replies stay out of its Location. Junior
441
- * still stores them. A person's next mention in the Location clears it.
442
- */
443
- deliveryPausedAt: timestamptz("delivery_paused_at"),
444
- durationMs: integer("duration_ms").notNull().default(0),
445
- usage: jsonb("usage_json").$type(),
446
- executionDurationMs: integer("execution_duration_ms").notNull().default(0),
447
- executionUsage: jsonb("execution_usage_json").$type(),
448
- metricRunId: text("metric_run_id"),
449
- detailVersion: integer("detail_version").notNull().default(0)
450
- }, (table) => [
451
- check("junior_conversations_kind_check", sql`${table.kind} in ('root', 'automation', 'lead', 'thread', 'task')`),
452
- check("junior_conversations_kind_parent_check", sql`${table.kind} is null or ((${table.kind} in ('root', 'automation', 'lead')) = (${table.parentConversationId} is null))`),
453
- index("junior_conversations_last_activity_idx").on(table.lastActivityAt.desc(), table.conversationId),
454
- index("junior_conversations_active_idx").using("btree", sql`coalesce(${table.executionUpdatedAt}, ${table.updatedAt})`, table.conversationId).where(sql`${table.executionStatus} <> 'idle'`),
455
- index("junior_conversations_destination_activity_idx").on(table.destinationId, table.lastActivityAt.desc()),
456
- index("junior_conversations_actor_activity_idx").on(table.actorIdentityId, table.lastActivityAt.desc()),
457
- index("junior_conversations_parent_idx").on(table.parentConversationId),
458
- index("junior_conversations_forked_from_idx").on(table.forkedFromConversationId),
459
- index("junior_conversations_root_idx").on(table.rootConversationId),
460
- uniqueIndex("junior_conversations_lead_actor_idx").on(table.actorIdentityId).where(sql`${table.kind} = 'lead'`),
461
- index("junior_conversations_search_idx").using("gin", sql`to_tsvector('english', coalesce(${table.title}, '') || ' ' || coalesce(${table.summary}, ''))`)
462
- ]);
463
- // src/db/schema/attachments.ts
464
- /**
465
- * What a Message carries: a stored file (`file`) or a web link that its text
466
- * names (`url`). Rows are owned by one Conversation, and a repeat of the same
467
- * thing in that Conversation reuses its row.
468
- */
469
- const juniorAttachments = pgTable("junior_attachments", {
470
- id: text("id").primaryKey(),
471
- /** `file` or `url`. Only `file` rows have storage and file fields. */
472
- kind: text("kind").notNull().default("file"),
473
- conversationId: text("conversation_id").notNull().references(() => juniorConversations.conversationId, { onDelete: "cascade" }),
474
- /** Service that stores the file bytes. */
475
- storageProvider: text("storage_provider"),
476
- /**
477
- * Object key of the stored bytes. Null for a file that Junior records
478
- * without storing, such as a large Slack file.
479
- */
480
- storageKey: text("storage_key"),
481
- /** Provider that supplied the file. */
482
- provider: text("provider"),
483
- /** File id assigned by the source provider. */
484
- providerId: text("provider_id"),
485
- /**
486
- * File name of a file. The column keeps its old name until no worker
487
- * that reads `filename` runs.
488
- */
489
- title: text("filename"),
490
- contentType: text("content_type"),
491
- bytes: integer("bytes"),
492
- /** Web link of a `url` row, as its message text wrote it. */
493
- url: text("url"),
494
- /** Digest of the stored bytes. Null when `storage_key` is null. */
495
- sha256: text("sha256"),
496
- visionSummary: text("vision_summary"),
497
- createdAt: timestamptz("created_at").notNull(),
498
- /** Set when conversation purge marks the attachment unavailable. */
499
- deleteRequestedAt: timestamptz("delete_requested_at")
500
- }, (table) => [
501
- index("junior_attachments_conversation_idx").on(table.conversationId),
502
- index("junior_attachments_provider_idx").on(table.conversationId, table.provider, table.providerId),
503
- index("junior_attachments_gc_idx").on(table.storageProvider, table.deleteRequestedAt, table.createdAt),
504
- uniqueIndex("junior_attachments_conversation_url_idx").on(table.conversationId, table.url).where(sql`${table.url} IS NOT NULL`)
505
- ]);
506
- /**
507
- * Where each stored message event uses an Attachment. `seq` is the seq of the
508
- * first save of its message, as in the transcript. `position` is the 1-based
509
- * order of a link in the message text, and null for an Attachment that is not
510
- * in the text. No foreign keys, so creating the table locks no existing
511
- * table.
512
- */
513
- const juniorMessageAttachments = pgTable("junior_message_attachments", {
514
- conversationId: text("conversation_id").notNull(),
515
- seq: integer("seq").notNull(),
516
- attachmentId: text("attachment_id").notNull(),
517
- position: integer("position")
518
- }, (table) => [primaryKey({
519
- name: "junior_message_attachments_pk",
520
- columns: [
521
- table.conversationId,
522
- table.seq,
523
- table.attachmentId
524
- ]
525
- })]);
526
- /**
527
- * Browser uploads that wait for a web Message.
528
- *
529
- * A row binds one object key to the viewer, Conversation, and Message
530
- * idempotency key that asked for it. A Message turns the upload into a
531
- * `junior_attachments` row with the same id. Cleanup deletes the object of an
532
- * upload that no Message used.
533
- */
534
- const juniorAttachmentUploads = pgTable("junior_attachment_uploads", {
535
- id: text("id").primaryKey(),
536
- /** No foreign key: a new Conversation has no row until its first send. */
537
- conversationId: text("conversation_id").notNull(),
538
- userId: text("user_id").notNull(),
539
- idempotencyKey: text("idempotency_key").notNull(),
540
- storageProvider: text("storage_provider").notNull(),
541
- storageKey: text("storage_key").notNull(),
542
- filename: text("filename").notNull(),
543
- contentType: text("content_type").notNull(),
544
- /** Size that the browser declared and the upload target allows. */
545
- bytes: integer("bytes").notNull(),
546
- createdAt: timestamptz("created_at").notNull()
547
- }, (table) => [index("junior_attachment_uploads_gc_idx").on(table.storageProvider, table.createdAt)]);
548
- // src/db/schema/code.ts
549
- /**
550
- * Words of a repository name, for prefix search. `owner/repo` is one token
551
- * to the text parser, so the slash becomes a space.
552
- */
553
- function codeRepositorySearchDocument(table) {
554
- return sql`to_tsvector('simple', translate(${table.name}, '/', ' '))`;
555
- }
556
- /** The number and the title words of a code change, for prefix search. */
557
- function codeChangeSearchDocument(table) {
558
- return sql`to_tsvector('simple', ${table.number}::text || ' ' || coalesce(${table.title}, ''))`;
559
- }
560
- /** Repository known to Junior through an installed code plugin. */
561
- const juniorCodeRepositories = pgTable("junior_code_repositories", {
562
- id: uuid("id").primaryKey(),
563
- name: text("name").notNull(),
564
- provider: text("provider").notNull(),
565
- providerId: text("provider_id").notNull(),
566
- url: text("url"),
567
- updatedAt: timestamptz("updated_at").notNull()
568
- }, (table) => [uniqueIndex("junior_code_repositories_provider_id_idx").on(table.provider, table.providerId), index("junior_code_repositories_search_idx").using("gin", codeRepositorySearchDocument(table))]);
569
- /** Latest known state for one code change created by Junior. */
570
- const juniorCodeChanges = pgTable("junior_code_changes", {
571
- id: uuid("id").primaryKey(),
572
- additions: integer("additions"),
573
- changedFiles: integer("changed_files"),
574
- closedAt: timestamptz("closed_at"),
575
- conversationIds: text("conversation_ids").array().notNull().default(sql`ARRAY[]::text[]`),
576
- deletions: integer("deletions"),
577
- draft: boolean("draft").notNull().default(false),
578
- /** Latest push, review, or comment by a person, from the code plugin. */
579
- lastActivityAt: timestamptz("last_activity_at"),
580
- mergedAt: timestamptz("merged_at"),
581
- number: integer("number").notNull(),
582
- openedAt: timestamptz("opened_at").notNull(),
583
- provider: text("provider").notNull(),
584
- providerId: text("provider_id").notNull(),
585
- repositoryId: uuid("repository_id").notNull().references(() => juniorCodeRepositories.id, { onDelete: "cascade" }),
586
- state: text("state").$type().notNull(),
587
- title: text("title"),
588
- updatedAt: timestamptz("updated_at").notNull(),
589
- url: text("url")
590
- }, (table) => [
591
- uniqueIndex("junior_code_changes_provider_id_idx").on(table.provider, table.providerId),
592
- index("junior_code_changes_opened_at_idx").on(table.openedAt),
593
- index("junior_code_changes_merged_at_idx").on(table.mergedAt),
594
- index("junior_code_changes_closed_at_idx").on(table.closedAt),
595
- index("junior_code_changes_repository_state_idx").on(table.repositoryId, table.state, table.updatedAt.desc()),
596
- index("junior_code_changes_search_idx").using("gin", codeChangeSearchDocument(table)),
597
- index("junior_code_changes_open_idx").on(table.id).where(sql`${table.state} = 'open'`)
598
- ]);
599
- // src/db/schema/conversation-annotations.ts
600
- const juniorConversationAnnotations = pgTable("junior_conversation_annotations", {
601
- conversationId: text("conversation_id").notNull(),
602
- plugin: text("plugin").notNull(),
603
- kind: text("kind").notNull(),
604
- key: text("key").notNull(),
605
- annotation: jsonb("annotation_json").$type().notNull(),
606
- createdAt: timestamptz("created_at").notNull(),
607
- updatedAt: timestamptz("updated_at").notNull()
608
- }, (table) => [primaryKey({
609
- name: "junior_conversation_annotations_pk",
610
- columns: [
611
- table.conversationId,
612
- table.plugin,
613
- table.kind,
614
- table.key
615
- ]
616
- }), foreignKey({
617
- name: "junior_conversation_annotations_conversation_id_fk",
618
- columns: [table.conversationId],
619
- foreignColumns: [juniorConversations.conversationId]
620
- }).onDelete("cascade")]);
621
- // src/db/schema/api-tokens.ts
622
- const juniorApiTokens = pgTable("junior_api_tokens", {
623
- id: text("id").primaryKey(),
624
- ownerEmailNormalized: text("owner_email_normalized").notNull(),
625
- name: text("name").notNull(),
626
- tokenHash: text("token_hash").notNull(),
627
- tokenSuffix: text("token_suffix").notNull(),
628
- createdAt: timestamptz("created_at").notNull(),
629
- expiresAt: timestamptz("expires_at").notNull(),
630
- lastUsedAt: timestamptz("last_used_at"),
631
- revokedAt: timestamptz("revoked_at")
632
- }, (table) => [uniqueIndex("junior_api_tokens_token_hash_uidx").on(table.tokenHash), index("junior_api_tokens_owner_email_idx").on(table.ownerEmailNormalized)]);
633
- // src/db/schema/conversation-events.ts
634
- /**
635
- * Match a user_message payload that a person sent as an instruction from a
636
- * chat surface. `junior_conversation_events_user_message_time_idx` has this
637
- * predicate, so a query with it can use the index and skip other events.
638
- */
639
- function isUserInstruction(payload) {
640
- return sql`(${payload}->'provenance'->>'authority') = 'instruction' and (${payload}->'provenance'->'actor'->>'platform') in ('slack', 'local', 'web')`;
641
- }
642
- /**
643
- * Append-only canonical conversation history. `history_version` partitions
644
- * model-history replacements, while `(conversation_id, seq)` is the stable
645
- * event identity and lease-fencing tripwire.
646
- *
647
- * `actor_identity_id` is the first-class author identity for human-authored
648
- * events. Message payloads may still carry display author fields in `meta`.
649
- */
650
- const juniorConversationEvents = pgTable("junior_conversation_events", {
651
- conversationId: text("conversation_id").notNull(),
652
- seq: integer("seq").notNull(),
653
- historyVersion: integer("history_version").notNull(),
654
- schemaVersion: integer("schema_version").default(1).notNull(),
655
- idempotencyKey: text("idempotency_key"),
656
- type: text("type").notNull(),
657
- payload: jsonb("payload").$type().notNull(),
658
- actorIdentityId: text("actor_identity_id").references(() => juniorIdentities.id),
659
- createdAt: timestamptz("created_at").notNull()
660
- }, (table) => [
661
- primaryKey({
662
- name: "junior_conversation_events_conversation_id_seq_pk",
663
- columns: [table.conversationId, table.seq]
664
- }),
665
- foreignKey({
666
- name: "junior_conversation_events_conversation_id_junior_conversations_conversation_id_fk",
667
- columns: [table.conversationId],
668
- foreignColumns: [juniorConversations.conversationId]
669
- }),
670
- index("junior_conversation_events_history_version_idx").on(table.conversationId, table.historyVersion, table.seq),
671
- index("junior_conversation_events_type_idx").on(table.conversationId, table.type, table.seq),
672
- index("junior_conversation_events_plugin_report_idx").on(sql`(${table.payload}->>'namespace')`, sql`(${table.payload}->>'name')`, table.createdAt).where(sql`${table.type} = 'structured_event'`),
673
- index("junior_conversation_events_guardian_review_time_idx").on(table.createdAt).where(sql`${table.type} = 'guardian_action_reviewed'`),
674
- index("junior_conversation_events_authorization_request_idx").on(table.conversationId, table.createdAt).where(sql`${table.type} = 'authorization_requested'`),
675
- index("junior_conversation_events_plugin_conversation_idx").on(table.conversationId, sql`(${table.payload}->>'namespace')`, sql`(${table.payload}->>'name')`, table.seq).where(sql`${table.type} = 'structured_event'`),
676
- index("junior_conversation_events_actor_identity_idx").on(table.actorIdentityId, table.conversationId, table.seq),
677
- index("junior_conversation_events_author_idx").on(table.conversationId, table.actorIdentityId, table.seq).where(sql`${table.actorIdentityId} is not null`),
678
- index("junior_conversation_events_message_role_idx").on(table.conversationId, sql`(${table.payload}->>'role')`, table.createdAt, table.seq).where(sql`${table.type} = 'message'`),
679
- index("junior_conversation_events_user_message_time_idx").on(table.conversationId, table.createdAt, table.seq).where(sql`${table.type} = 'user_message' and ${isUserInstruction(table.payload)}`),
680
- index("junior_conversation_events_message_search_idx").using("gin", sql`to_tsvector('english', ${table.payload}->>'text')`).where(sql`${table.type} = 'message'`),
681
- uniqueIndex("junior_conversation_events_idempotency_idx").on(table.conversationId, table.idempotencyKey)
682
- ]);
683
- // src/db/schema/conversation-metrics.ts
684
- const CONVERSATION_METRICS = [
685
- "duration_ms",
686
- "total_tokens",
687
- "input_tokens",
688
- "output_tokens",
689
- "cached_input_tokens",
690
- "cache_creation_tokens",
691
- "reasoning_tokens",
692
- "cost_micro_usd"
693
- ];
694
- /**
695
- * One metric value for one Conversation Run. A Run is one Turn, so People
696
- * spend reads the Identity of the Turn Actor from these rows.
697
- */
698
- const juniorConversationMetrics = pgTable("junior_conversation_metrics", {
699
- conversationId: text("conversation_id").notNull(),
700
- runId: text("run_id").notNull(),
701
- metric: text("metric").$type().notNull(),
702
- actorIdentityId: text("actor_identity_id").references(() => juniorIdentities.id),
703
- value: doublePrecision("value").notNull(),
704
- occurredAt: timestamptz("occurred_at").notNull(),
705
- updatedAt: timestamptz("updated_at").notNull()
706
- }, (table) => [
707
- primaryKey({
708
- name: "junior_conversation_metrics_conversation_id_run_id_metric_pk",
709
- columns: [
710
- table.conversationId,
711
- table.runId,
712
- table.metric
713
- ]
714
- }),
715
- foreignKey({
716
- name: "junior_conversation_metrics_conversation_id_junior_conversations_conversation_id_fk",
717
- columns: [table.conversationId],
718
- foreignColumns: [juniorConversations.conversationId]
719
- }),
720
- index("junior_conversation_metrics_actor_identity_occurred_at_idx").on(table.actorIdentityId, table.occurredAt),
721
- index("junior_conversation_metrics_occurred_at_metric_idx").on(table.occurredAt, table.metric),
722
- index("junior_conversation_metrics_turn_metric_occurred_at_idx").on(table.metric, table.occurredAt, table.actorIdentityId, table.conversationId, table.value).where(sql`${table.metric} IN ('duration_ms', 'total_tokens', 'cost_micro_usd')`)
723
- ]);
724
- // src/db/schema/conversation-embeddings.ts
725
- /**
726
- * One embedding per Conversation, for semantic search. Its text is the
727
- * Conversation metadata. A derived index: the next metadata update replaces
728
- * the row.
729
- */
730
- const juniorConversationEmbeddings = pgTable("junior_conversation_embeddings", {
731
- conversationId: text("conversation_id").primaryKey(),
732
- legacyBriefVersion: integer("brief_version"),
733
- /** The `metadata_through_seq` of the embedded Conversation metadata. */
734
- throughSeq: integer("through_seq"),
735
- provider: text("provider").notNull(),
736
- model: text("model").notNull(),
737
- dimensions: integer("dimensions").notNull(),
738
- embedding: embeddingVector("embedding").notNull(),
739
- createdAt: timestamptz("created_at").defaultNow().notNull()
740
- }, (table) => [foreignKey({
741
- name: "junior_conversation_embeddings_conversation_fk",
742
- columns: [table.conversationId],
743
- foreignColumns: [juniorConversations.conversationId]
744
- }).onDelete("cascade"), check("junior_conversation_embeddings_dimensions_check", sql`vector_dims(${table.embedding}) = ${table.dimensions}`)]);
745
- // src/db/schema/conversation-event-embeddings.ts
746
- /**
747
- * One embedding per searchable Conversation event, for semantic search of the
748
- * history of one Conversation. A derived index: a purge that deletes the
749
- * event deletes its row, and a new embedding model replaces the row.
750
- */
751
- const juniorConversationEventEmbeddings = pgTable("junior_conversation_event_embeddings", {
752
- conversationId: text("conversation_id").notNull(),
753
- seq: integer("seq").notNull(),
754
- provider: text("provider").notNull(),
755
- model: text("model").notNull(),
756
- dimensions: integer("dimensions").notNull(),
757
- embedding: embeddingHalfvec("embedding").notNull(),
758
- createdAt: timestamptz("created_at").defaultNow().notNull()
759
- }, (table) => [
760
- primaryKey({
761
- name: "junior_conversation_event_embeddings_pk",
762
- columns: [table.conversationId, table.seq]
763
- }),
764
- foreignKey({
765
- name: "junior_conversation_event_embeddings_event_fk",
766
- columns: [table.conversationId, table.seq],
767
- foreignColumns: [juniorConversationEvents.conversationId, juniorConversationEvents.seq]
768
- }).onDelete("cascade"),
769
- check("junior_conversation_event_embeddings_dimensions_check", sql`vector_dims(${table.embedding}) = ${table.dimensions}`)
770
- ]);
771
- // src/db/schema/conversation-event-lexemes.ts
772
- /**
773
- * Stored full-text lexemes of one searchable Conversation event, for keyword
774
- * search of the history of one Conversation. A derived index: a purge that
775
- * deletes the event deletes its row. Events are immutable, so a row never
776
- * changes.
777
- */
778
- const juniorConversationEventLexemes = pgTable("junior_conversation_event_lexemes", {
779
- conversationId: text("conversation_id").notNull(),
780
- seq: integer("seq").notNull(),
781
- lexemes: tsvector("lexemes").notNull(),
782
- createdAt: timestamptz("created_at").defaultNow().notNull()
783
- }, (table) => [
784
- primaryKey({
785
- name: "junior_conversation_event_lexemes_pk",
786
- columns: [table.conversationId, table.seq]
787
- }),
788
- foreignKey({
789
- name: "junior_conversation_event_lexemes_event_fk",
790
- columns: [table.conversationId, table.seq],
791
- foreignColumns: [juniorConversationEvents.conversationId, juniorConversationEvents.seq]
792
- }).onDelete("cascade"),
793
- index("junior_conversation_event_lexemes_lexemes_idx").using("gin", table.lexemes)
794
- ]);
795
- // src/db/schema/conversation-briefs.ts
796
- /**
797
- * Legacy Brief versions. Conversation metadata replaced Briefs; only purge
798
- * still deletes rows here.
799
- * TODO(dcramer): Drop this table after the metadata backfill ships.
800
- */
801
- const juniorConversationBriefs = pgTable("junior_conversation_briefs", {
802
- conversationId: text("conversation_id").notNull(),
803
- version: integer("version").notNull(),
804
- turnId: text("turn_id").notNull(),
805
- throughSeq: integer("through_seq").notNull(),
806
- content: jsonb("content").notNull(),
807
- outcomeStatus: text("outcome_status"),
808
- searchText: text("search_text").notNull(),
809
- modelId: text("model_id").notNull(),
810
- costMicroUsd: bigint("cost_micro_usd", { mode: "number" }),
811
- legacyCostUsd: doublePrecision("cost_usd"),
812
- createdAt: timestamptz("created_at").defaultNow().notNull()
813
- }, (table) => [
814
- primaryKey({
815
- name: "junior_conversation_briefs_conversation_id_version_pk",
816
- columns: [table.conversationId, table.version]
817
- }),
818
- foreignKey({
819
- name: "junior_conversation_briefs_conversation_id_junior_conversations_conversation_id_fk",
820
- columns: [table.conversationId],
821
- foreignColumns: [juniorConversations.conversationId]
822
- }).onDelete("cascade"),
823
- uniqueIndex("junior_conversation_briefs_conversation_turn_idx").on(table.conversationId, table.turnId),
824
- index("junior_conversation_briefs_conversation_version_idx").on(table.conversationId, table.version.desc()),
825
- index("junior_conversation_briefs_created_at_idx").on(table.createdAt, table.conversationId),
826
- index("junior_conversation_briefs_search_idx").using("gin", sql`to_tsvector('english', ${table.searchText})`)
827
- ]);
828
- // src/db/schema/conversation-bindings.ts
829
- /** Provider conversation coordinates bound to Junior's opaque durable conversation id. */
830
- const juniorConversationBindings = pgTable("junior_conversation_bindings", {
831
- conversationId: text("conversation_id").notNull().references(() => juniorConversations.conversationId),
832
- provider: text("provider").notNull(),
833
- providerTenantId: text("provider_tenant_id").notNull().default(""),
834
- providerDestinationId: text("provider_destination_id").notNull(),
835
- providerConversationId: text("provider_conversation_id").notNull(),
836
- createdAt: timestamptz("created_at").notNull()
837
- }, (table) => [primaryKey({
838
- name: "junior_conversation_bindings_provider_conversation_pk",
839
- columns: [
840
- table.provider,
841
- table.providerTenantId,
842
- table.providerDestinationId,
843
- table.providerConversationId
844
- ]
845
- }), index("junior_conversation_bindings_conversation_idx").on(table.conversationId)]);
846
- // src/db/schema/conversation-participants.ts
847
- /**
848
- * One Participant: a linked user on one root conversation. Rows come from
849
- * Turn Actors: the root Actor and the authors of Turn input messages, and
850
- * the root Actor again when their Identity gets its User later. Thread
851
- * context authors do not get a row. Access and feeds read only these rows.
852
- * An unsubscribed row keeps access but leaves the active feed.
853
- */
854
- const juniorConversationParticipants = pgTable("junior_conversation_participants", {
855
- userId: text("user_id").notNull().references(() => juniorUsers.id),
856
- rootConversationId: text("root_conversation_id").notNull().references(() => juniorConversations.conversationId),
857
- lastMessageAt: timestamptz("last_message_at").notNull(),
858
- pinnedAt: timestamptz("pinned_at"),
859
- /**
860
- * The viewer's place for this pin in the Pinned section, from a drag
861
- * reorder. Null until the first reorder, and cleared on unpin and
862
- * re-pin. Null pins sort first, by activity.
863
- */
864
- pinPosition: integer("pin_position"),
865
- /**
866
- * Per-conversation auto-archive choice for this user. Null uses the
867
- * user's `autoArchiveDefault`.
868
- */
869
- autoArchive: boolean("auto_archive"),
870
- /**
871
- * Set when this user left the conversation. It stays out of their
872
- * active feed until they mention Junior in it again, subscribe, or pin
873
- * it. The row keeps its access, so it is not deleted.
874
- */
875
- unsubscribedAt: timestamptz("unsubscribed_at")
876
- }, (table) => [
877
- primaryKey({
878
- name: "junior_conversation_participants_user_root_pk",
879
- columns: [table.userId, table.rootConversationId]
880
- }),
881
- index("junior_conversation_participants_user_activity_idx").on(table.userId, table.lastMessageAt.desc()),
882
- index("junior_conversation_participants_root_idx").on(table.rootConversationId),
883
- index("junior_conversation_participants_auto_archive_idx").on(table.userId).where(sql`${table.autoArchive}`),
884
- index("junior_conversation_participants_unsubscribed_idx").on(table.userId, table.rootConversationId).where(sql`${table.unsubscribedAt} is not null`)
885
- ]);
886
- // src/db/schema/conversation-read-positions.ts
887
- /**
888
- * How far one signed-in user has read one Conversation transcript.
889
- *
890
- * `last_read_seq` is the event sequence of the last transcript row the user
891
- * saw. It only moves forward, so clients on several devices can write in any
892
- * order.
893
- */
894
- const juniorConversationReadPositions = pgTable("junior_conversation_read_positions", {
895
- userId: text("user_id").notNull().references(() => juniorUsers.id),
896
- conversationId: text("conversation_id").notNull().references(() => juniorConversations.conversationId),
897
- lastReadSeq: integer("last_read_seq").notNull(),
898
- updatedAt: timestamptz("updated_at").notNull()
899
- }, (table) => [primaryKey({
900
- name: "junior_conversation_read_positions_user_conversation_pk",
901
- columns: [table.userId, table.conversationId]
902
- })]);
903
- // src/db/schema/agent-invocations.ts
904
- const juniorAgentBindings = pgTable("junior_agent_bindings", {
905
- parentConversationId: text("parent_conversation_id").notNull().references(() => juniorConversations.conversationId),
906
- name: text("name").notNull(),
907
- childConversationId: text("child_conversation_id").notNull().references(() => juniorConversations.conversationId)
908
- }, (table) => [primaryKey({ columns: [table.parentConversationId, table.name] }), uniqueIndex("junior_agent_bindings_child_idx").on(table.childConversationId)]);
909
- const juniorAgentInvocations = pgTable("junior_agent_invocations", {
910
- invocationId: text("invocation_id").primaryKey(),
911
- parentConversationId: text("parent_conversation_id").notNull().references(() => juniorConversations.conversationId),
912
- childConversationId: text("child_conversation_id").notNull().references(() => juniorConversations.conversationId),
913
- agentName: text("agent_name"),
914
- input: text("input").notNull(),
915
- title: text("title"),
916
- actor: jsonb("actor_json").$type().notNull(),
917
- credentialContext: jsonb("credential_context_json").$type(),
918
- source: jsonb("source_json").$type().notNull(),
919
- destination: jsonb("destination_json").$type().notNull(),
920
- destinationVisibility: text("destination_visibility").$type(),
921
- agentType: text("agent_type").$type(),
922
- fork: boolean("fork").notNull().default(false),
923
- reasoningLevel: text("reasoning_level").$type(),
924
- parentToolCallId: text("parent_tool_call_id"),
925
- status: text("status").$type().notNull(),
926
- mailboxStatus: text("mailbox_status").$type().notNull(),
927
- parentMailboxStatus: text("parent_mailbox_status").$type(),
928
- result: text("result"),
929
- errorMessage: text("error_message"),
930
- createdAt: timestamptz("created_at").notNull(),
931
- updatedAt: timestamptz("updated_at").notNull(),
932
- terminalAt: timestamptz("terminal_at")
933
- }, (table) => [
934
- index("junior_agent_invocations_child_idx").on(table.childConversationId),
935
- index("junior_agent_invocations_mailbox_idx").on(table.mailboxStatus, table.createdAt),
936
- index("junior_agent_invocations_parent_mailbox_idx").on(table.parentMailboxStatus, table.terminalAt)
937
- ]);
938
- // src/db/schema/location-configurations.ts
939
- /** Durable user configuration entries scoped to provider Locations. */
940
- const juniorLocationConfigurations = pgTable("junior_location_configurations", {
941
- locationId: text("location_id").notNull().references(() => juniorDestinations.id, { onDelete: "cascade" }),
942
- key: text("key").notNull(),
943
- value: text("value").notNull(),
944
- updatedAt: timestamptz("updated_at").notNull(),
945
- updatedBy: text("updated_by"),
946
- source: text("source"),
947
- expiresAt: text("expires_at")
948
- }, (table) => [primaryKey({ columns: [table.locationId, table.key] })]);
949
- // src/db/schema/automation-versions.ts
950
- /** One saved Automation definition. Lifecycle and scheduler state are not versioned. */
951
- const juniorAutomationVersions = pgTable("junior_automation_versions", {
952
- automationId: text("automation_id").notNull(),
953
- /** Starts at 1 and increases by 1 for each saved definition change. */
954
- version: integer("version").notNull(),
955
- createdAtMs: bigint("created_at_ms", { mode: "number" }).notNull(),
956
- /** Slack principal that saved this definition. Null when unknown. */
957
- editedBy: jsonb("edited_by"),
958
- definition: jsonb("definition").notNull()
959
- }, (table) => [primaryKey({
960
- name: "junior_automation_versions_pk",
961
- columns: [table.automationId, table.version]
962
- }), foreignKey({
963
- name: "junior_automation_versions_automation_id_fk",
964
- columns: [table.automationId],
965
- foreignColumns: [juniorAutomations.id]
966
- }).onDelete("cascade")]);
967
- // src/db/schema/automation-runs.ts
968
- /**
969
- * One dispatch of an Automation, from claim or dispatch to its outcome. A
970
- * Scheduled automation run id is `<automation id>:<scheduled time>`. An event
971
- * automation run id is its dispatch id. Automation code sets
972
- * `conversation_id` when it dispatches the run. A run that was skipped, or
973
- * that failed before dispatch, has no Conversation.
974
- *
975
- * `automation_version` is the Automation version that the run dispatched. It
976
- * shows which instruction ran and who saved it after the definition changes.
977
- * It is null before dispatch, and when no saved version matched.
978
- */
979
- const juniorAutomationRuns = pgTable("junior_automation_runs", {
980
- id: text("id").primaryKey(),
981
- automationId: text("automation_id").notNull().references(() => juniorAutomations.id, { onDelete: "cascade" }),
982
- conversationId: text("conversation_id").unique().references(() => juniorConversations.conversationId),
983
- status: text("status").$type().notNull(),
984
- automationVersion: integer("automation_version"),
985
- scheduledForMs: bigint("scheduled_for_ms", { mode: "number" }),
986
- attempt: integer("attempt"),
987
- claimedAtMs: bigint("claimed_at_ms", { mode: "number" }),
988
- dispatchId: text("dispatch_id"),
989
- startedAtMs: bigint("started_at_ms", { mode: "number" }),
990
- completedAtMs: bigint("completed_at_ms", { mode: "number" }),
991
- errorMessage: text("error_message"),
992
- resultMessageTs: text("result_message_ts"),
993
- costMicroUsd: bigint("cost_micro_usd", { mode: "number" })
994
- }, (table) => [
995
- foreignKey({
996
- name: "junior_automation_runs_automation_version_fk",
997
- columns: [table.automationId, table.automationVersion],
998
- foreignColumns: [juniorAutomationVersions.automationId, juniorAutomationVersions.version]
999
- }),
1000
- check("junior_automation_runs_status_check", sql`${table.status} in ('pending', 'running', 'completed', 'failed', 'blocked', 'skipped')`),
1001
- index("junior_automation_runs_automation_idx").on(table.automationId, table.completedAtMs),
1002
- index("junior_automation_runs_completed_idx").on(table.completedAtMs),
1003
- index("junior_automation_runs_incomplete_idx").on(table.automationId, table.scheduledForMs).where(sql`${table.status} in ('pending', 'running')`)
1004
- ]);
1005
- // src/db/schema/automations.ts
1006
- /**
1007
- * One row per Automation of either kind. `record` holds the fields that have
1008
- * no column. Each write also copies the nested fields that queries filter or
1009
- * search on into columns: `team_id`, `channel_id`, `creator_slack_user_id`,
1010
- * the task `instruction` or `skill`, and the event trigger `namespace` and
1011
- * `identifier`. Exactly one of `instruction` and `skill` is set, by the task
1012
- * kind. A skill's context is only in `record`. An event trigger with no
1013
- * identifier runs for every resource of its namespace, so its `identifier` is
1014
- * null. The match index finds those rows with `identifier is null`.
1015
- */
1016
- const juniorAutomations = pgTable("junior_automations", {
1017
- id: text("id").primaryKey(),
1018
- kind: text("kind").$type().notNull(),
1019
- teamId: text("team_id").notNull(),
1020
- channelId: text("channel_id").notNull(),
1021
- creatorSlackUserId: text("creator_slack_user_id").notNull(),
1022
- /** Junior identity that created the Automation. It decides ownership. */
1023
- creatorIdentityId: text("creator_identity_id").notNull().references(() => juniorIdentities.id),
1024
- status: text("status").$type().notNull(),
1025
- /** Why a run blocked this Automation, until its creator resumes it. */
1026
- statusReason: text("status_reason"),
1027
- title: text("title"),
1028
- /** The instruction of an instruction task. Null for a skill task. */
1029
- instruction: text("instruction"),
1030
- /** The skill of a skill task. Null for an instruction task. */
1031
- skill: text("skill"),
1032
- createdAtMs: bigint("created_at_ms", { mode: "number" }).notNull(),
1033
- nextRunAtMs: bigint("next_run_at_ms", { mode: "number" }),
1034
- runNowAtMs: bigint("run_now_at_ms", { mode: "number" }),
1035
- /**
1036
- * The latest run with an outcome. The list reads its end time and status
1037
- * to order by activity and to find failed last runs.
1038
- * `refreshAutomationLastRun` sets it after each run write. A purged run
1039
- * clears it.
1040
- */
1041
- lastRunId: text("last_run_id").references(() => juniorAutomationRuns.id, { onDelete: "set null" }),
1042
- /**
1043
- * When core last saw this Automation recover after a person dismissed
1044
- * its alert. A dismissed alert hides the Automation's alerts until then.
1045
- */
1046
- alertRecoveredAtMs: bigint("alert_recovered_at_ms", { mode: "number" }),
1047
- namespace: text("namespace"),
1048
- identifier: text("identifier"),
1049
- record: jsonb("record").$type().notNull()
1050
- }, (table) => [
1051
- check("junior_automations_kind_check", sql`${table.kind} in ('scheduled', 'event')`),
1052
- check("junior_automations_status_check", sql`${table.status} in ('active', 'blocked', 'paused', 'completed', 'deleted')`),
1053
- check("junior_automations_task_check", sql`(${table.instruction} is null) <> (${table.skill} is null)`),
1054
- check("junior_automations_record_check", sql`jsonb_typeof(${table.record}) = 'object'`),
1055
- check("junior_automations_trigger_check", sql`(${table.kind} = 'scheduled' and ${table.namespace} is null and ${table.identifier} is null) or (${table.kind} = 'event' and ${table.namespace} is not null and ${table.nextRunAtMs} is null and ${table.runNowAtMs} is null and ${table.status} <> 'completed')`),
1056
- index("junior_automations_team_idx").on(table.teamId, table.createdAtMs, table.id).where(sql`${table.status} <> 'deleted'`),
1057
- index("junior_automations_creator_identity_idx").on(table.creatorIdentityId, table.createdAtMs, table.id),
1058
- index("junior_automations_creator_slack_idx").on(table.teamId, table.creatorSlackUserId).where(sql`${table.status} <> 'deleted'`),
1059
- index("junior_automations_last_run_idx").on(table.lastRunId),
1060
- index("junior_automations_run_now_due_idx").on(table.runNowAtMs, table.createdAtMs, table.id).where(sql`${table.status} = 'active' AND ${table.runNowAtMs} IS NOT NULL`),
1061
- index("junior_automations_next_run_due_idx").on(table.nextRunAtMs, table.createdAtMs, table.id).where(sql`${table.status} = 'active' AND ${table.nextRunAtMs} IS NOT NULL`),
1062
- index("junior_automations_skill_idx").on(table.skill, table.createdAtMs, table.id).where(sql`${table.status} <> 'deleted' AND ${table.skill} IS NOT NULL`),
1063
- index("junior_automations_match_idx").on(table.namespace, table.identifier, table.createdAtMs, table.id).where(sql`${table.status} <> 'deleted'`)
1064
- ]);
1065
- // src/db/schema/inbox-items.ts
1066
- /**
1067
- * One Inbox item: something that needs a person. An action item stores its
1068
- * `request`, and
1069
- * its `answer` after an assignee submits it. `closed_at` is set for `done`
1070
- * and `dismissed`. `closed_by_user_id` is null when an agent closed it.
1071
- * `owner_kind` and `owner_id` name its owner. The owner kind decides how the
1072
- * item gets its visibility and tenant, and where the Inbox stacks it. The id
1073
- * has no foreign key, because it can name a row of more than one table.
1074
- */
1075
- const juniorInboxItems = pgTable("junior_inbox_items", {
1076
- id: text("id").primaryKey(),
1077
- kind: text("kind").$type().notNull(),
1078
- status: text("status").$type().notNull(),
1079
- /**
1080
- * `private` when the Conversation that added it is not public. A private
1081
- * item stays private and links only to that Conversation.
1082
- */
1083
- visibility: text("visibility").$type().notNull(),
1084
- title: text("title").notNull(),
1085
- body: text("body").notNull(),
1086
- request: jsonb("request").$type(),
1087
- answer: jsonb("answer").$type(),
1088
- assignedToEveryone: boolean("assigned_to_everyone").notNull().default(false),
1089
- dedupeKey: text("dedupe_key").notNull(),
1090
- subjectId: text("subject_id"),
1091
- subjectTitle: text("subject_title"),
1092
- subjectUrl: text("subject_url"),
1093
- /** The parsed subject title of a code change (`InboxItemSubjectTitleParts`). */
1094
- subjectTitleParts: jsonb("subject_title_parts").$type(),
1095
- ownerKind: text("owner_kind").$type().notNull().default("conversation"),
1096
- ownerId: text("owner_id").notNull(),
1097
- /**
1098
- * Turn of the agent that added the item, or that last added it again with
1099
- * its dedupe key. Null for a plugin item, which has no Turn.
1100
- */
1101
- addedByTurnId: text("added_by_turn_id"),
1102
- /**
1103
- * Provider tenant, such as a Slack workspace, of the Conversation that
1104
- * added the item. A public item is visible only inside it.
1105
- */
1106
- provider: text("provider"),
1107
- providerTenantId: text("provider_tenant_id"),
1108
- automationId: text("automation_id").references(() => juniorAutomations.id, { onDelete: "set null" }),
1109
- closedAt: timestamptz("closed_at"),
1110
- closedByUserId: text("closed_by_user_id").references(() => juniorUsers.id, { onDelete: "set null" }),
1111
- closeReason: text("close_reason"),
1112
- createdAt: timestamptz("created_at").notNull(),
1113
- updatedAt: timestamptz("updated_at").notNull()
1114
- }, (table) => [
1115
- check("junior_inbox_items_kind_check", sql`(${table.kind} = 'notice' and ${table.request} is null and ${table.answer} is null) or (${table.kind} = 'action' and (${table.request} is not null or ((${table.dedupeKey} like 'plugin:%' or ${table.dedupeKey} like 'automation:%') and ${table.answer} is null)))`),
1116
- check("junior_inbox_items_owner_check", sql`(${table.ownerKind} = 'conversation' and ${table.dedupeKey} not like 'automation:%') or (${table.ownerKind} = 'automation' and ${table.dedupeKey} like 'automation:%')`),
1117
- check("junior_inbox_items_status_check", sql`(${table.status} = 'open' and ${table.closedAt} is null) or (${table.status} in ('done', 'dismissed') and ${table.closedAt} is not null)`),
1118
- check("junior_inbox_items_tenant_check", sql`(${table.provider} is null) = (${table.providerTenantId} is null)`),
1119
- check("junior_inbox_items_visibility_check", sql`${table.visibility} = 'public' or not ${table.assignedToEveryone}`),
1120
- uniqueIndex("junior_inbox_items_open_dedupe_uidx").on(sql`coalesce(${table.provider}, '')`, sql`coalesce(${table.providerTenantId}, '')`, table.dedupeKey).where(sql`${table.status} = 'open'`),
1121
- index("junior_inbox_items_status_idx").on(table.status, table.updatedAt, table.id),
1122
- index("junior_inbox_items_subject_idx").on(table.subjectId, table.status),
1123
- index("junior_inbox_items_owner_idx").on(table.ownerKind, table.ownerId),
1124
- index("junior_inbox_items_open_action_owner_idx").on(table.ownerId).where(sql`${table.status} = 'open' and ${table.kind} = 'action'`),
1125
- index("junior_inbox_items_automation_idx").on(table.automationId, table.status),
1126
- index("junior_inbox_items_answered_idx").on(table.ownerId, table.closedByUserId, table.closedAt).where(sql`${table.answer} is not null`)
1127
- ]);
1128
- /** The assigned Users of an Inbox item. Everyone is a flag on the item. */
1129
- const juniorInboxItemAssignees = pgTable("junior_inbox_item_assignees", {
1130
- itemId: text("item_id").notNull().references(() => juniorInboxItems.id, { onDelete: "cascade" }),
1131
- userId: text("user_id").notNull().references(() => juniorUsers.id, { onDelete: "cascade" })
1132
- }, (table) => [primaryKey({ columns: [table.itemId, table.userId] }), index("junior_inbox_item_assignees_user_idx").on(table.userId)]);
1133
- /** The Conversations linked to an Inbox item. */
1134
- const juniorInboxItemConversations = pgTable("junior_inbox_item_conversations", {
1135
- itemId: text("item_id").notNull().references(() => juniorInboxItems.id, { onDelete: "cascade" }),
1136
- conversationId: text("conversation_id").notNull().references(() => juniorConversations.conversationId, { onDelete: "cascade" })
1137
- }, (table) => [primaryKey({ columns: [table.itemId, table.conversationId] }), index("junior_inbox_item_conversations_conversation_idx").on(table.conversationId)]);
1138
- /**
1139
- * The Slack message that shows an Inbox item in one linked Slack thread.
1140
- * Junior updates it in place after each change.
1141
- */
1142
- const juniorInboxItemSlackCards = pgTable("junior_inbox_item_slack_cards", {
1143
- itemId: text("item_id").notNull().references(() => juniorInboxItems.id, { onDelete: "cascade" }),
1144
- conversationId: text("conversation_id").notNull().references(() => juniorConversations.conversationId, { onDelete: "cascade" }),
1145
- teamId: text("team_id").notNull(),
1146
- channelId: text("channel_id").notNull(),
1147
- messageTs: text("message_ts").notNull()
1148
- }, (table) => [primaryKey({ columns: [table.itemId, table.conversationId] })]);
1149
- // src/db/schema/inbox-snoozes.ts
1150
- /**
1151
- * One person's snooze of one Inbox item. A `snoozed` row hides the item
1152
- * from that person's Inbox until one of its triggers fires. `woken` and
1153
- * `cancelled` are final. The item's own status says whether it resolved.
1154
- * A trigger that wakes it records why in `wake_reason`, which only that
1155
- * person sees, until they open or act on the item.
1156
- */
1157
- const juniorInboxSnoozes = pgTable("junior_inbox_snoozes", {
1158
- id: text("id").primaryKey(),
1159
- userId: text("user_id").notNull().references(() => juniorUsers.id, { onDelete: "cascade" }),
1160
- inboxItemId: text("inbox_item_id").notNull().references(() => juniorInboxItems.id, { onDelete: "cascade" }),
1161
- state: text("state").$type().notNull(),
1162
- wakeReason: jsonb("wake_reason").$type(),
1163
- createdAt: timestamptz("created_at").notNull()
1164
- }, (table) => [
1165
- check("junior_inbox_snoozes_state_check", sql`${table.state} in ('snoozed', 'woken', 'cancelled')`),
1166
- uniqueIndex("junior_inbox_snoozes_snoozed_uidx").on(table.userId, table.inboxItemId).where(sql`${table.state} = 'snoozed'`),
1167
- index("junior_inbox_snoozes_settled_idx").on(table.createdAt).where(sql`${table.state} <> 'snoozed'`),
1168
- index("junior_inbox_snoozes_inbox_item_idx").on(table.inboxItemId)
1169
- ]);
1170
- /**
1171
- * An Event that ends a snooze. `wake` brings the item back; `resolve`
1172
- * dismisses the item and cancels the snooze. A snooze's triggers join with
1173
- * OR: the first to fire wins, and the snooze ignores the rest. Time is a
1174
- * `timer.fired` Event like any other.
1175
- */
1176
- const juniorInboxSnoozeTriggers = pgTable("junior_inbox_snooze_triggers", {
1177
- snoozeId: text("snooze_id").notNull().references(() => juniorInboxSnoozes.id, { onDelete: "cascade" }),
1178
- outcome: text("outcome").$type().notNull(),
1179
- namespace: text("namespace").notNull(),
1180
- identifier: text("identifier").notNull(),
1181
- eventType: text("event_type").notNull(),
1182
- match: jsonb("match").$type()
1183
- }, (table) => [
1184
- check("junior_inbox_snooze_triggers_outcome_check", sql`${table.outcome} in ('wake', 'resolve')`),
1185
- index("junior_inbox_snooze_triggers_event_idx").on(table.namespace, table.identifier, table.eventType),
1186
- index("junior_inbox_snooze_triggers_snooze_idx").on(table.snoozeId)
1187
- ]);
1188
- // src/db/schema/stats.ts
1189
- /**
1190
- * Daily named counters used by Junior and loaded plugins.
1191
- * TODO: store hour keys when dashboard 24h workspace usage needs hourly bars.
1192
- * `date` is a Postgres date column, so counters stay day-bucketed today.
1193
- */
1194
- const juniorStats = pgTable("junior_stats", {
1195
- date: date("date", { mode: "string" }).notNull(),
1196
- namespace: text("namespace").notNull(),
1197
- metric: text("metric").notNull(),
1198
- name: text("name").notNull(),
1199
- count: bigint("value", { mode: "number" }).notNull().default(0),
1200
- legacyCount: integer("count").notNull().default(0)
1201
- }, (table) => [primaryKey({
1202
- name: "junior_stats_date_namespace_metric_name_pk",
1203
- columns: [
1204
- table.date,
1205
- table.namespace,
1206
- table.metric,
1207
- table.name
1208
- ]
1209
- })]);
1210
- // src/db/schema/todos.ts
1211
- /**
1212
- * Gives each To-do its id and each change its version. One sequence serves
1213
- * every Conversation, so history that a fork copies from its parent never
1214
- * shows a version that the fork's own To-dos reuse.
1215
- */
1216
- const juniorTodoVersionSeq = pgSequence("junior_todo_version_seq");
1217
- /**
1218
- * One To-do: work that a Conversation has not finished. At most one
1219
- * assignee: a Conversation (the list's own agent or one of its child agents)
1220
- * or a User. A To-do without one belongs to the list's own agent.
1221
- * `changed_by_user_id` is set when a person made the latest change.
1222
- * `changed_by_conversation_id` is set when the assignee child agent closed
1223
- * it, or core closed it on that child's result. Both are null when the
1224
- * list's own agent made the latest change. Both User keys block deleting the User, as
1225
- * Conversation participants do: setting them null would turn a person's
1226
- * To-do into the agent's and hide an unseen change from `<todo-delta>`.
1227
- */
1228
- const juniorTodos = pgTable("junior_todos", {
1229
- conversationId: text("conversation_id").notNull(),
1230
- id: bigint("id", { mode: "number" }).notNull(),
1231
- title: text("title").notNull(),
1232
- notes: text("notes"),
1233
- status: text("status").$type().notNull(),
1234
- assigneeConversationId: text("assignee_conversation_id"),
1235
- assigneeUserId: text("assignee_user_id").references(() => juniorUsers.id),
1236
- version: bigint("version", { mode: "number" }).notNull(),
1237
- changedByUserId: text("changed_by_user_id").references(() => juniorUsers.id),
1238
- changedByConversationId: text("changed_by_conversation_id"),
1239
- createdAt: timestamptz("created_at").notNull(),
1240
- updatedAt: timestamptz("updated_at").notNull()
1241
- }, (table) => [
1242
- primaryKey({
1243
- name: "junior_todos_pk",
1244
- columns: [table.conversationId, table.id]
1245
- }),
1246
- foreignKey({
1247
- name: "junior_todos_conversation_id_fk",
1248
- columns: [table.conversationId],
1249
- foreignColumns: [juniorConversations.conversationId]
1250
- }).onDelete("cascade"),
1251
- check("junior_todos_status_check", sql`${table.status} in ('open', 'in_progress', 'done', 'dropped')`),
1252
- check("junior_todos_assignee_check", sql`${table.assigneeConversationId} is null or ${table.assigneeUserId} is null`)
1253
- ]);
1254
- // src/db/schema/push-subscriptions.ts
1255
- /**
1256
- * One browser Web Push subscription for one user. A user can have one row for
1257
- * each browser or installed dashboard app. The push service owns the endpoint.
1258
- */
1259
- const juniorPushSubscriptions = pgTable("junior_push_subscriptions", {
1260
- id: text("id").primaryKey(),
1261
- userId: text("user_id").notNull().references(() => juniorUsers.id, { onDelete: "cascade" }),
1262
- endpoint: text("endpoint").notNull(),
1263
- p256dh: text("p256dh").notNull(),
1264
- auth: text("auth").notNull(),
1265
- createdAt: timestamptz("created_at").notNull(),
1266
- updatedAt: timestamptz("updated_at").notNull()
1267
- }, (table) => [uniqueIndex("junior_push_subscriptions_endpoint_uidx").on(table.endpoint), index("junior_push_subscriptions_user_idx").on(table.userId)]);
1268
- // src/db/schema/workspaces.ts
1269
- /** Named recipe used to prepare a reusable Sandbox. */
1270
- const juniorWorkspaces = pgTable("junior_workspaces", {
1271
- id: text("id").primaryKey(),
1272
- name: text("name").notNull(),
1273
- setupScript: text("setup_script").notNull().default(""),
1274
- vcpus: integer("vcpus"),
1275
- createdAt: timestamptz("created_at").notNull(),
1276
- updatedAt: timestamptz("updated_at").notNull()
1277
- }, (table) => [uniqueIndex("junior_workspaces_name_idx").on(table.name)]);
1278
- /** Repository included in one Workspace recipe. */
1279
- const juniorWorkspaceRepos = pgTable("junior_workspace_repos", {
1280
- workspaceId: text("workspace_id").notNull().references(() => juniorWorkspaces.id, { onDelete: "cascade" }),
1281
- provider: text("provider").notNull(),
1282
- repo: text("repo").notNull()
1283
- }, (table) => [primaryKey({ columns: [
1284
- table.workspaceId,
1285
- table.provider,
1286
- table.repo
1287
- ] })]);
1288
- // src/db/schema/snapshots.ts
1289
- /**
1290
- * Sandbox snapshot build and ready artifact for one Workspace recipe.
1291
- * A ready row keeps its builder owner until the snapshot is discarded.
1292
- */
1293
- const juniorSnapshots = pgTable("junior_snapshots", {
1294
- id: text("id").primaryKey(),
1295
- workspaceId: text("workspace_id").notNull().references(() => juniorWorkspaces.id, { onDelete: "cascade" }),
1296
- profileHash: text("profile_hash").notNull(),
1297
- status: text("status").$type().notNull(),
1298
- snapshotId: text("snapshot_id"),
1299
- buildDurationMs: integer("build_duration_ms"),
1300
- sizeBytes: bigint("size_bytes", { mode: "number" }),
1301
- generatedAt: timestamptz("generated_at"),
1302
- buildStartedAt: timestamptz("build_started_at"),
1303
- buildPhase: text("build_phase").$type(),
1304
- buildSandboxName: text("build_sandbox_name"),
1305
- buildCommandId: text("build_command_id"),
1306
- buildError: text("build_error"),
1307
- createdAt: timestamptz("created_at").notNull(),
1308
- updatedAt: timestamptz("updated_at").notNull()
1309
- }, (table) => [
1310
- check("junior_snapshots_status_check", sql`${table.status} in ('building', 'failed', 'ready')`),
1311
- check("junior_snapshots_build_phase_check", sql`${table.buildPhase} is null or ${table.buildPhase} in ('created', 'dependencies_installed', 'repositories_prepared')`),
1312
- check("junior_snapshots_ready_fields_check", sql`${table.status} <> 'ready' or (${table.snapshotId} is not null and ${table.buildDurationMs} is not null and ${table.generatedAt} is not null)`),
1313
- check("junior_snapshots_build_fields_check", sql`${table.status} = 'ready' or (${table.buildStartedAt} is not null and ${table.buildPhase} is not null)`),
1314
- check("junior_snapshots_build_duration_check", sql`${table.buildDurationMs} is null or ${table.buildDurationMs} >= 0`),
1315
- check("junior_snapshots_size_bytes_check", sql`${table.sizeBytes} is null or ${table.sizeBytes} >= 0`),
1316
- uniqueIndex("junior_snapshots_snapshot_id_uidx").on(table.snapshotId),
1317
- index("junior_snapshots_workspace_idx").on(table.workspaceId),
1318
- index("junior_snapshots_workspace_profile_status_idx").on(table.workspaceId, table.profileHash, table.status),
1319
- uniqueIndex("junior_snapshots_active_build_uidx").on(table.workspaceId, table.profileHash).where(sql`${table.status} = 'building'`),
1320
- index("junior_snapshots_workspace_status_idx").on(table.workspaceId, table.status)
1321
- ]);
1322
- // src/db/schema.ts
1323
- const juniorSqlSchema = {
1324
- juniorArtifacts,
1325
- juniorAttachmentUploads,
1326
- juniorAttachments,
1327
- juniorMessageAttachments,
1328
- juniorCodeChanges,
1329
- juniorCodeRepositories,
1330
- juniorConversationAnnotations,
1331
- juniorApiTokens,
1332
- juniorAgentBindings,
1333
- juniorAgentInvocations,
1334
- juniorConversationEvents,
1335
- juniorConversationMetrics,
1336
- juniorConversationEmbeddings,
1337
- juniorConversationEventEmbeddings,
1338
- juniorConversationEventLexemes,
1339
- juniorConversationBriefs,
1340
- juniorConversationBindings,
1341
- juniorConversationParticipants,
1342
- juniorConversationReadPositions,
1343
- juniorConversations,
1344
- juniorLocationConfigurations,
1345
- juniorMemoryEmbeddings,
1346
- juniorMemoryMemories,
1347
- juniorMemorySignals,
1348
- juniorDestinations,
1349
- juniorIdentities,
1350
- juniorInboxSnoozes,
1351
- juniorInboxSnoozeTriggers,
1352
- juniorInboxItemAssignees,
1353
- juniorInboxItemConversations,
1354
- juniorInboxItemSlackCards,
1355
- juniorInboxItems,
1356
- juniorTodos,
1357
- juniorPushSubscriptions,
1358
- juniorSnapshots,
1359
- juniorStats,
1360
- juniorAutomationRuns,
1361
- juniorAutomationVersions,
1362
- juniorAutomations,
1363
- juniorUsers,
1364
- juniorWorkspaceRepos,
1365
- juniorWorkspaces
1366
- };
1367
- // src/db/info-messages.ts
1368
- /**
1369
- * Send Postgres `INFO` messages from every pool connection to `onInfo`.
1370
- * A migration uses `RAISE INFO` to report its result to the operator.
1371
- * Postgres always sends `INFO` to the client. Its own messages, such as
1372
- * "already exists, skipping", are `NOTICE`, so they stay out.
1373
- */
1374
- function forwardInfoMessages(pool, onInfo) {
1375
- pool.on("connect", (client) => {
1376
- client.on("notice", (notice) => {
1377
- if (notice.severity === "INFO" && notice.message) onInfo(notice.message);
1378
- });
1379
- });
1380
- }
1381
- // src/db/postgres-error.ts
1382
- const MAX_CAUSE_DEPTH = 5;
1383
- /**
1384
- * Return whether a PostgreSQL failure, or an error that it wraps as `cause`,
1385
- * has the requested SQLSTATE.
1386
- */
1387
- function isPostgresErrorCode(error, code) {
1388
- let current = error;
1389
- for (let depth = 0; depth < MAX_CAUSE_DEPTH && typeof current === "object" && current !== null; depth += 1) {
1390
- if ("code" in current && current.code === code) return true;
1391
- current = "cause" in current ? current.cause : void 0;
1392
- }
1393
- return false;
1394
- }
1395
- // src/db/migrate.ts
1396
- const LOCK_TIMEOUT_MS = 5e3;
1397
- const LOCK_ATTEMPTS = 5;
1398
- const LOCK_RETRY_DELAY_MS = 5e3;
1399
- const LOCK_NOT_AVAILABLE = "55P03";
1400
- const MIGRATION_LOCK_POLL_MS = 1e3;
1401
- const CONCURRENT_STATEMENT = /^(?:CREATE (?:UNIQUE )?INDEX|DROP INDEX|REINDEX)\b[^;]*\bCONCURRENTLY\b/i;
1402
- const CONCURRENT_INDEX = /^CREATE (?:UNIQUE )?INDEX CONCURRENTLY IF NOT EXISTS "([a-z0-9_]+)" /i;
1403
- /** Statement text without its leading comment lines. */
1404
- function sqlOf(statement) {
1405
- return statement.split("\n").filter((line) => !line.trim().startsWith("--")).join("\n").trim();
1406
- }
1407
- /**
1408
- * Index builds of a migration that only builds indexes concurrently, or
1409
- * undefined for a migration that runs in a transaction.
1410
- */
1411
- function concurrentIndexes(tag, statements) {
1412
- const sql = statements.map(sqlOf).filter(Boolean);
1413
- if (!sql.some((statement) => CONCURRENT_STATEMENT.test(statement))) return;
1414
- return sql.map((statement) => {
1415
- const name = CONCURRENT_INDEX.exec(statement)?.[1];
1416
- if (!name) throw new Error(`Migration ${tag}: a migration that uses CONCURRENTLY must contain only CREATE [UNIQUE] INDEX CONCURRENTLY IF NOT EXISTS "name" statements.`);
1417
- return {
1418
- name,
1419
- statement
1420
- };
1421
- });
1422
- }
1423
- /**
1424
- * Wait for the migration lock by polling `pg_try_advisory_lock`. A session
1425
- * blocked in `pg_advisory_lock` holds a snapshot, and `CREATE INDEX
1426
- * CONCURRENTLY` waits for every older snapshot, so a second migrator that
1427
- * blocked there would deadlock with the build of the first.
1428
- */
1429
- async function waitForMigrationLock(tryLock) {
1430
- while (!await tryLock()) await new Promise((resolve) => setTimeout(resolve, MIGRATION_LOCK_POLL_MS));
1431
- }
1432
- async function retryOnLockTimeout(tag, apply) {
1433
- for (let attempt = 1;; attempt += 1) try {
1434
- await apply();
1435
- return;
1436
- } catch (error) {
1437
- if (attempt >= LOCK_ATTEMPTS || !isPostgresErrorCode(error, LOCK_NOT_AVAILABLE)) throw error;
1438
- logWarn("db.migration.lock_timeout", {
1439
- "app.db.migration.tag": tag,
1440
- "app.db.migration.attempt": attempt
1441
- });
1442
- await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_DELAY_MS));
1443
- }
1444
- }
1445
- /**
1446
- * Apply pending Drizzle migrations, each in its own transaction.
1447
- *
1448
- * Drizzle's `migrate()` runs every pending migration in one transaction
1449
- * (drizzle-orm#3249), so locks from earlier migrations stay held while later
1450
- * migrations wait for theirs. That can deadlock with live traffic. This keeps
1451
- * Drizzle's journal table and skip rule, so existing databases are unaffected.
1452
- * A migration that waits too long for a lock rolls back and runs again. A
1453
- * migration that only builds indexes concurrently runs outside a transaction.
1454
- */
1455
- async function applyMigrations(executor, config) {
1456
- const schema = config.migrationsSchema ?? "drizzle";
1457
- const table = `"${schema}"."${config.migrationsTable ?? "__drizzle_migrations"}"`;
1458
- await executor.execute(`CREATE SCHEMA IF NOT EXISTS "${schema}"`);
1459
- await executor.execute(`CREATE TABLE IF NOT EXISTS ${table} (id SERIAL PRIMARY KEY, hash text NOT NULL, created_at bigint)`);
1460
- const [last] = await executor.query(`SELECT created_at::text AS "createdAt" FROM ${table} ORDER BY created_at DESC LIMIT 1`);
1461
- const appliedAt = Number(last?.createdAt ?? 0);
1462
- for (const migration of readMigrationFiles(config)) {
1463
- if (migration.folderMillis <= appliedAt) continue;
1464
- const tag = String(migration.folderMillis);
1465
- const recordApplied = () => executor.execute(`INSERT INTO ${table} (hash, created_at) VALUES ($1, $2)`, [migration.hash, migration.folderMillis]);
1466
- const indexes = concurrentIndexes(tag, migration.sql);
1467
- if (indexes) {
1468
- for (const { name, statement } of indexes) {
1469
- const [state] = await executor.query(`SELECT indisvalid AND indisready AS usable FROM pg_index WHERE indexrelid = to_regclass($1)`, [name]);
1470
- if (state && !state.usable) await executor.execute(`DROP INDEX CONCURRENTLY IF EXISTS "${name}"`);
1471
- await executor.execute(statement);
1472
- }
1473
- await recordApplied();
1474
- continue;
1475
- }
1476
- await retryOnLockTimeout(tag, async () => {
1477
- await executor.transaction(async () => {
1478
- await executor.execute(`SET LOCAL lock_timeout = ${LOCK_TIMEOUT_MS}`);
1479
- for (const statement of migration.sql) await executor.execute(statement);
1480
- await recordApplied();
1481
- });
1482
- });
1483
- }
1484
- }
1485
- // src/db/neon.ts
1486
- const POOL_MAX = 10;
1487
- function toWebSocketError(error, failure) {
1488
- if (error instanceof Error) return error;
1489
- const event = error ?? {};
1490
- const cause = event.error instanceof Error ? event.error : void 0;
1491
- const reason = typeof event.message === "string" && event.message || cause?.message || cause && `${cause.name} (no message)` || typeof event.type === "string" && event.type || String(error);
1492
- return new Error(`WebSocket ${failure}: ${reason}`, event.error === void 0 ? void 0 : { cause: event.error });
1493
- }
1494
- function warnWebSocketFailure(name, error, failure) {
1495
- const reported = toWebSocketError(error, failure);
1496
- logWarn(name, {
1497
- "app.db.driver": "neon",
1498
- "error.type": reported.name,
1499
- "exception.message": reported.message
1500
- });
1501
- }
1502
- /**
1503
- * Sends a pool query over Neon's SQL-over-HTTP endpoint when no idle
1504
- * WebSocket client is free.
1505
- *
1506
- * pg-pool reuses the newest idle client, so light polling keeps one or two
1507
- * clients warm and the rest idle out. A parallel read batch then opens about
1508
- * eight WebSockets, each with a new Postgres session. An HTTP query reuses the
1509
- * proxy's cached backend connection, so the batch skips that handshake. The
1510
- * warm path stays on WebSocket. `connect()` and transactions are unchanged.
1511
- */
1512
- var OverflowPool = class extends Pool$1 {
1513
- pendingAcquires = 0;
1514
- webSocketOnly = new AsyncLocalStorage();
1515
- sql;
1516
- dispatcher;
1517
- statementTimeoutMs;
1518
- constructor(args) {
1519
- super({
1520
- connectionString: args.connectionString,
1521
- max: POOL_MAX,
1522
- idleTimeoutMillis: 3e5,
1523
- min: 1,
1524
- statement_timeout: args.statementTimeoutMs
1525
- });
1526
- this.sql = neon(args.connectionString, { fullResults: true });
1527
- this.dispatcher = args.dispatcher;
1528
- this.statementTimeoutMs = args.statementTimeoutMs;
1529
- this.on("remove", () => this.reconnectWhenEmpty());
1530
- }
1531
- query(input, values, callback) {
1532
- const query = typeof input === "string" ? { text: input } : input;
1533
- if (callback !== void 0 || typeof values === "function" || typeof query?.text !== "string" || "submit" in query) return super.query(input, values, callback);
1534
- const params = values ?? query.values ?? [];
1535
- if (this.webSocketOnly.getStore() || this.idleCount > this.pendingAcquires || this.totalCount === 0) return this.queryWebSocket(query, params);
1536
- this.growInBackground();
1537
- return this.queryHttp(query, params);
1538
- }
1539
- growInBackground() {
1540
- setImmediate(() => {
1541
- if (this.ending || this.idleCount > 0 || this.totalCount >= POOL_MAX) return;
1542
- this.openClient();
1543
- });
1544
- }
1545
- reconnectWhenEmpty() {
1546
- setImmediate(() => {
1547
- if (this.ending || this.totalCount > 0) return;
1548
- this.openClient();
1549
- });
1550
- }
1551
- openClient() {
1552
- this.connect((error, client) => {
1553
- if (client) {
1554
- client.release();
1555
- return;
1556
- }
1557
- warnWebSocketFailure("db.pool.client.connect_failed", error, "connect failed");
1558
- });
1559
- }
1560
- /** Keep every pool query in `callback` on WebSocket. */
1561
- async onWebSocket(callback) {
1562
- return await this.webSocketOnly.run(true, callback);
1563
- }
1564
- async queryWebSocket(query, params) {
1565
- const client = await this.acquire();
1566
- try {
1567
- const result = await client.query({
1568
- ...query,
1569
- values: params
1570
- });
1571
- client.release();
1572
- return result;
1573
- } catch (error) {
1574
- client.release(error);
1575
- throw error;
1576
- }
1577
- }
1578
- acquire() {
1579
- this.pendingAcquires++;
1580
- return new Promise((resolve, reject) => {
1581
- this.connect((error, client) => {
1582
- this.pendingAcquires--;
1583
- if (client) resolve(client);
1584
- else reject(error ?? /* @__PURE__ */ new Error("pg pool returned no client"));
1585
- });
1586
- });
1587
- }
1588
- async queryHttp(query, params) {
1589
- const fetchOptions = { dispatcher: this.dispatcher };
1590
- if (this.statementTimeoutMs) fetchOptions.signal = AbortSignal.timeout(this.statementTimeoutMs);
1591
- return await withScope(async (scope) => {
1592
- scope.setAttributes({ "app.db.transport": "http" });
1593
- return await this.sql.query(query.text, params, {
1594
- arrayMode: query.rowMode === "array",
1595
- fullResults: true,
1596
- types: query.types ?? this.options.types,
1597
- fetchOptions
1598
- });
1599
- });
1600
- }
1601
- };
1602
- var NeonExecutor = class {
1603
- transactionClient = new AsyncLocalStorage();
1604
- savepointId = 0;
1605
- isolatedQueryId = 0;
1606
- pool;
1607
- dispatcher;
1608
- constructor(pool, dispatcher) {
1609
- this.pool = pool;
1610
- this.dispatcher = dispatcher;
1611
- }
1612
- db() {
1613
- return drizzle(this.queryClient(), { schema: juniorSqlSchema });
1614
- }
1615
- async execute(statement, params = []) {
1616
- await this.queryClient().query(statement, [...params]);
1617
- }
1618
- async query(statement, params = []) {
1619
- return (await this.queryClient().query(statement, [...params])).rows;
1620
- }
1621
- async queryIsolated(statement, params = []) {
1622
- const client = await this.pool.connect();
1623
- try {
1624
- return (await client.query({
1625
- name: `junior_isolated_${++this.isolatedQueryId}`,
1626
- text: statement,
1627
- values: [...params]
1628
- })).rows;
1629
- } finally {
1630
- client.release(true);
1631
- }
1632
- }
1633
- async migrate(config) {
1634
- await applyMigrations(this, config);
1635
- }
1636
- async transaction(callback) {
1637
- const existingClient = this.transactionClient.getStore();
1638
- if (existingClient) {
1639
- const savepoint = `junior_savepoint_${++this.savepointId}`;
1640
- await existingClient.query(`SAVEPOINT ${savepoint}`);
1641
- try {
1642
- const result = await callback();
1643
- await existingClient.query(`RELEASE SAVEPOINT ${savepoint}`);
1644
- return result;
1645
- } catch (error) {
1646
- await existingClient.query(`ROLLBACK TO SAVEPOINT ${savepoint}`);
1647
- await existingClient.query(`RELEASE SAVEPOINT ${savepoint}`);
1648
- throw error;
1649
- }
1650
- }
1651
- const client = await this.pool.connect();
1652
- try {
1653
- await client.query("BEGIN");
1654
- const result = await this.transactionClient.run(client, callback);
1655
- await client.query("COMMIT");
1656
- return result;
1657
- } catch (error) {
1658
- await client.query("ROLLBACK");
1659
- throw error;
1660
- } finally {
1661
- client.release();
1662
- }
1663
- }
1664
- async withLock(lockName, callback) {
1665
- if (!lockName) throw new Error("SQL lock name is required");
1666
- const existingClient = this.transactionClient.getStore();
1667
- if (existingClient) {
1668
- await existingClient.query("SELECT pg_advisory_xact_lock(hashtext($1))", [lockName]);
1669
- return await callback();
1670
- }
1671
- const client = await this.pool.connect();
1672
- try {
1673
- await client.query("BEGIN");
1674
- return await this.transactionClient.run(client, async () => {
1675
- try {
1676
- await client.query("SELECT pg_advisory_xact_lock(hashtext($1))", [lockName]);
1677
- const result = await callback();
1678
- await client.query("COMMIT");
1679
- return result;
1680
- } catch (error) {
1681
- await client.query("ROLLBACK");
1682
- throw error;
1683
- }
1684
- });
1685
- } finally {
1686
- client.release();
1687
- }
1688
- }
1689
- async withMigrationLock(migrationTable, callback) {
1690
- const client = await this.pool.connect();
1691
- const lockName = `junior:migrate:${migrationTable}`;
1692
- try {
1693
- await waitForMigrationLock(async () => {
1694
- return (await client.query("SELECT pg_try_advisory_lock(hashtext($1)) AS locked", [lockName])).rows[0]?.locked === true;
1695
- });
1696
- return await this.pool.onWebSocket(callback);
1697
- } finally {
1698
- client.release(true);
1699
- }
1700
- }
1701
- async close() {
1702
- await this.pool.end();
1703
- await this.dispatcher.close();
1704
- }
1705
- queryClient() {
1706
- return this.transactionClient.getStore() ?? this.pool;
1707
- }
1708
- };
1709
- /** Create the shared Neon-backed Junior SQL executor. */
1710
- function createNeonJuniorSqlExecutor(args) {
1711
- const { onInfo, ...poolArgs } = args;
1712
- const dispatcher = new Agent({ allowH2: true });
1713
- const pool = new OverflowPool({
1714
- ...poolArgs,
1715
- dispatcher
1716
- });
1717
- pool.on("error", (error) => {
1718
- warnWebSocketFailure("db.pool.client.failed", error, "idle client failed");
1719
- });
1720
- if (onInfo) forwardInfoMessages(pool, onInfo);
1721
- return new NeonExecutor(pool, dispatcher);
1722
- }
1723
- // src/db/postgres.ts
1724
- const { Pool } = pg;
1725
- var PostgresExecutor = class {
1726
- transactionClient = new AsyncLocalStorage();
1727
- savepointId = 0;
1728
- isolatedQueryId = 0;
1729
- pool;
1730
- constructor(pool) {
1731
- this.pool = pool;
1732
- }
1733
- db() {
1734
- return drizzle$1(this.queryClient(), { schema: juniorSqlSchema });
1735
- }
1736
- async execute(statement, params = []) {
1737
- await this.queryClient().query(statement, [...params]);
1738
- }
1739
- async query(statement, params = []) {
1740
- return (await this.queryClient().query(statement, [...params])).rows;
1741
- }
1742
- async queryIsolated(statement, params = []) {
1743
- const client = await this.pool.connect();
1744
- try {
1745
- return (await client.query({
1746
- name: `junior_isolated_${++this.isolatedQueryId}`,
1747
- text: statement,
1748
- values: [...params]
1749
- })).rows;
1750
- } finally {
1751
- client.release(true);
1752
- }
1753
- }
1754
- async migrate(config) {
1755
- await applyMigrations(this, config);
1756
- }
1757
- async transaction(callback) {
1758
- const existingClient = this.transactionClient.getStore();
1759
- if (existingClient) {
1760
- const savepoint = `junior_savepoint_${++this.savepointId}`;
1761
- await existingClient.query(`SAVEPOINT ${savepoint}`);
1762
- try {
1763
- const result = await callback();
1764
- await existingClient.query(`RELEASE SAVEPOINT ${savepoint}`);
1765
- return result;
1766
- } catch (error) {
1767
- await existingClient.query(`ROLLBACK TO SAVEPOINT ${savepoint}`);
1768
- await existingClient.query(`RELEASE SAVEPOINT ${savepoint}`);
1769
- throw error;
1770
- }
1771
- }
1772
- const client = await this.pool.connect();
1773
- try {
1774
- await client.query("BEGIN");
1775
- const result = await this.transactionClient.run(client, callback);
1776
- await client.query("COMMIT");
1777
- return result;
1778
- } catch (error) {
1779
- await client.query("ROLLBACK");
1780
- throw error;
1781
- } finally {
1782
- client.release();
1783
- }
1784
- }
1785
- async withLock(lockName, callback) {
1786
- if (!lockName) throw new Error("SQL lock name is required");
1787
- const existingClient = this.transactionClient.getStore();
1788
- if (existingClient) {
1789
- await existingClient.query("SELECT pg_advisory_xact_lock(hashtext($1))", [lockName]);
1790
- return await callback();
1791
- }
1792
- const client = await this.pool.connect();
1793
- try {
1794
- await client.query("BEGIN");
1795
- return await this.transactionClient.run(client, async () => {
1796
- try {
1797
- await client.query("SELECT pg_advisory_xact_lock(hashtext($1))", [lockName]);
1798
- const result = await callback();
1799
- await client.query("COMMIT");
1800
- return result;
1801
- } catch (error) {
1802
- await client.query("ROLLBACK");
1803
- throw error;
1804
- }
1805
- });
1806
- } finally {
1807
- client.release();
1808
- }
1809
- }
1810
- async withMigrationLock(migrationTable, callback) {
1811
- const client = await this.pool.connect();
1812
- const lockName = `junior:migrate:${migrationTable}`;
1813
- try {
1814
- await waitForMigrationLock(async () => {
1815
- return (await client.query("SELECT pg_try_advisory_lock(hashtext($1)) AS locked", [lockName])).rows[0]?.locked === true;
1816
- });
1817
- return await callback();
1818
- } finally {
1819
- client.release(true);
1820
- }
1821
- }
1822
- async close() {
1823
- await this.pool.end();
1824
- }
1825
- queryClient() {
1826
- return this.transactionClient.getStore() ?? this.pool;
1827
- }
1828
- };
1829
- /** Create the shared Node Postgres-backed Junior SQL executor. */
1830
- function createPostgresJuniorSqlExecutor(args) {
1831
- const pool = new Pool({
1832
- application_name: args.applicationName,
1833
- connectionString: args.connectionString,
1834
- max: 3,
1835
- statement_timeout: args.statementTimeoutMs
1836
- });
1837
- pool.on("error", (error) => {
1838
- logException(error, "db.pool.client.failed", { "app.db.driver": "postgres" });
1839
- });
1840
- if (args.onInfo) forwardInfoMessages(pool, args.onInfo);
1841
- return new PostgresExecutor(pool);
1842
- }
1843
- // src/db/executor.ts
1844
- /** Create the SQL executor appropriate for the configured database URL. */
1845
- function createJuniorSqlExecutor(args) {
1846
- const statementTimeoutMs = args.statementTimeoutMs ?? 3e4;
1847
- if (args.driver === "postgres") return createPostgresJuniorSqlExecutor({
1848
- connectionString: args.connectionString,
1849
- onInfo: args.onInfo,
1850
- statementTimeoutMs
1851
- });
1852
- return createNeonJuniorSqlExecutor({
1853
- connectionString: args.connectionString,
1854
- onInfo: args.onInfo,
1855
- statementTimeoutMs
1856
- });
1857
- }
1858
- export { MEMORY_SCOPES as $, juniorConversationMetrics as A, juniorAttachments as B, juniorConversationParticipants as C, juniorConversationEventEmbeddings as D, juniorConversationEventLexemes as E, codeChangeSearchDocument as F, slackPersonSearchDocument as G, juniorConversations as H, codeRepositorySearchDocument as I, juniorMemoryEmbeddings as J, juniorUsers as K, juniorCodeChanges as L, juniorConversationEvents as M, juniorApiTokens as N, juniorConversationEmbeddings as O, juniorConversationAnnotations as P, MEMORY_KINDS as Q, juniorCodeRepositories as R, juniorConversationReadPositions as S, juniorConversationBriefs as T, juniorIdentities as U, juniorMessageAttachments as V, slackPersonPredicate as W, juniorMemorySignals as X, juniorMemoryMemories as Y, MEMORY_EMBEDDING_DIMENSIONS as Z, juniorAutomationRuns as _, juniorWorkspaces as a, guardedCosineDistance as at, juniorAgentBindings as b, juniorTodos as c, juniorArtifacts as ct, juniorInboxSnoozes as d, MEMORY_SOURCE_PLATFORMS as et, juniorInboxItemAssignees as f, juniorAutomations as g, juniorInboxItems as h, juniorWorkspaceRepos as i, embedText as it, isUserInstruction as j, CONVERSATION_METRICS as k, juniorStats as l, juniorInboxItemSlackCards as m, isPostgresErrorCode as n, memoryRuntimeContextSchema as nt, juniorPushSubscriptions as o, parseEmbeddingBatch as ot, juniorInboxItemConversations as p, juniorDestinations as q, juniorSnapshots as r, cosineDistance as rt, juniorTodoVersionSeq as s, refreshEmbeddings as st, createJuniorSqlExecutor as t, MEMORY_SUBJECT_TYPES as tt, juniorInboxSnoozeTriggers as u, juniorAutomationVersions as v, juniorConversationBindings as w, juniorAgentInvocations as x, juniorLocationConfigurations as y, juniorAttachmentUploads as z };