@sentry/junior 0.318.0 → 0.319.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 (92) hide show
  1. package/dist/{context-BKF_5zzI.js → adapter-8_S6Birm.js} +537 -537
  2. package/dist/{admin-UOHix_5P.js → admin-EsbUON1j.js} +1 -1
  3. package/dist/{agent-runner-DeYymwh2.js → agent-CtzMl32d.js} +18608 -5452
  4. package/dist/{agent-status-BA5x3Xtp.js → agent-status-Bq_AIpyp.js} +105 -1
  5. package/dist/{agent-update-delivery-DH8bx7jU.js → agent-update-delivery-pAvsbuGL.js} +4 -5
  6. package/dist/api/schema.d.ts +43 -23
  7. package/dist/api/schema.js +4 -4
  8. package/dist/api.js +70 -80
  9. package/dist/{app-DKAOuaoC.d.ts → app-tACXxJPI.d.ts} +4 -4
  10. package/dist/app.d.ts +2 -2
  11. package/dist/app.js +213 -91
  12. package/dist/{change-record-BzJgLsv7.d.ts → change-record-K-KsqNhT.d.ts} +9 -5
  13. package/dist/{channel-access-A0de5lRv.js → channel-access-DET5hzZM.js} +1 -1
  14. package/dist/{chat-core-engine-D3Wd7f5n.js → chat-core-engine-DpM3tMVi.js} +5 -5
  15. package/dist/cli/chat.d.ts +1 -1
  16. package/dist/cli/chat.js +23 -23
  17. package/dist/cli/check.js +5 -5
  18. package/dist/cli/main.js +2 -2
  19. package/dist/cli/plugins.d.ts +1 -1
  20. package/dist/cli/plugins.js +8 -8
  21. package/dist/cli/snapshot-create.js +5 -5
  22. package/dist/cli/upgrade.d.ts +1 -1
  23. package/dist/cli/upgrade.js +3 -4
  24. package/dist/{continue-in-slack-YxwMQVeR.js → continue-in-slack-CFzDyxkH.js} +3 -3
  25. package/dist/{conversation-feed-Cj7IuBtM.js → conversation-feed-DEUdD7mb.js} +2 -106
  26. package/dist/{conversation-privacy-Cr_dNW1p.js → conversation-privacy-C2vYK55O.js} +1 -1
  27. package/dist/{create-Btl1y1rq.js → create-Ta3SEIB5.js} +115 -5
  28. package/dist/{credential-sync-DTarZ63K.js → credential-sync-DyRqDmY4.js} +15 -18
  29. package/dist/{db-of6e3sGt.js → db-BCaNWl9p.js} +4579 -717
  30. package/dist/{deployment-C0qXa0FD.js → deployment-CfOew1Tm.js} +3 -3
  31. package/dist/{engine-context-C_QL_bMQ.js → engine-context-CiExoy1B.js} +144 -149
  32. package/dist/{html-9_pS9SjY.js → html-Bb2Si1bR.js} +6 -8
  33. package/dist/instrumentation.js +7 -23
  34. package/dist/list-wwDcROh9.js +5007 -0
  35. package/dist/{logging-BnOG0qz2.js → logging-BRPTXAdf.js} +8 -33
  36. package/dist/{mailbox-turn-Byrry9o1.js → markers-9QoqW5ov.js} +1675 -1255
  37. package/dist/nitro.d.ts +2 -2
  38. package/dist/nitro.js +6 -7
  39. package/dist/{oauth-callback-server-CjnnUr4o.js → oauth-callback-server-vhL9b-PZ.js} +2 -2
  40. package/dist/{oauth-relay-BvHFH0fV.js → oauth-relay-CH2v7WiB.js} +1 -1
  41. package/dist/{plugins-fBrz8PCV.d.ts → plugins-DhGXZjlu.d.ts} +1 -0
  42. package/dist/{profile-iHw1uu32.js → profile-D9LdwmZi.js} +16 -18
  43. package/dist/{prompt-DEkStuxG.js → prompt-3TqxEOtc.js} +1 -1
  44. package/dist/{reports-C1d9azyV.js → reports-K-tbtEyx.js} +2 -2
  45. package/dist/{resolve-DC6zBuDV.js → resolve-BBV2qf8A.js} +5 -5
  46. package/dist/{result-DxewDuXb.js → result-5IdGJP4M.js} +20 -9
  47. package/dist/{runner-99YxVN_r.js → runner-BK_joPlM.js} +7 -8
  48. package/dist/{sandbox-egress-signals-CgoX5CTI.js → sandbox-egress-signals-DXgWXXmm.js} +1 -1
  49. package/dist/{schema-BTojNBr5.js → schema-zWGG6VC1.js} +13 -7
  50. package/dist/{service-account-YDCPSByj.js → service-account-CateFyhw.js} +4 -5
  51. package/dist/{skills-CleC0Hze.js → skills-Ccjw8h2P.js} +9 -9
  52. package/dist/{slack-conversation-unfurl-BNQLC12R.js → slack-conversation-unfurl-ZC_TSpc4.js} +7 -7
  53. package/dist/storage-C9U7R5rM.js +273 -0
  54. package/dist/{system-prompt-table-Ci6Ck4gk.js → system-prompt-table-YBTHIFlP.js} +26 -84
  55. package/dist/topic-B2EWKKBT.js +6 -0
  56. package/dist/{package-discovery-DD9vencX.js → topics-DxuKurCX.js} +21 -1
  57. package/dist/{types-DCzTAA63.js → types-BNHkJrOP.js} +25 -11
  58. package/dist/{users-Cb9c1k9q.js → users-CCRAqYb_.js} +1 -1
  59. package/dist/{validation-BiUmWPhy.js → validation-BCUpJa8K.js} +4 -4
  60. package/dist/{version-VEXiEcZu.js → version-BNm0JYj3.js} +1 -1
  61. package/dist/version.js +1 -1
  62. package/dist/{worker-ChWYQdhm.js → worker-BhgpZ7_b.js} +4 -4
  63. package/migrations/20261127052408_space_name_nullable/migration.sql +5 -0
  64. package/migrations/20261127052408_space_name_nullable/snapshot.json +29 -0
  65. package/migrations/20261127060000_annotation_object_id_index/migration.sql +1 -0
  66. package/migrations/20261127060000_annotation_object_id_index/snapshot.json +69 -0
  67. package/migrations/20261127060001_annotation_subjects/migration.sql +78 -0
  68. package/migrations/20261127060001_annotation_subjects/snapshot.json +104 -0
  69. package/migrations/20261127060002_annotation_subject_index/migration.sql +1 -0
  70. package/migrations/20261127060002_annotation_subject_index/snapshot.json +70 -0
  71. package/migrations/20261127060003_annotation_title_url/migration.sql +84 -0
  72. package/migrations/20261127060003_annotation_title_url/snapshot.json +73 -0
  73. package/package.json +9 -7
  74. package/dist/auth-pause-state-f9hJM_zO.js +0 -113
  75. package/dist/catalog-runtime-BfdAnztW.js +0 -6
  76. package/dist/child-message-peFWLcCZ.js +0 -15
  77. package/dist/conversation-turn-Bru4w_FD.js +0 -1250
  78. package/dist/job-runner-B2XEvpif.js +0 -1505
  79. package/dist/lineage-nh4z9iQN.js +0 -36
  80. package/dist/list-HRP3TIRl.js +0 -12631
  81. package/dist/markers-CTTtJqYn.js +0 -342
  82. package/dist/message-BRUuLgrY.js +0 -153
  83. package/dist/model-input-CFC62mf-.js +0 -82
  84. package/dist/registry-Cl7Labpe.js +0 -3279
  85. package/dist/run-conversation-Cz2ubZK-.js +0 -337
  86. package/dist/sender-actors-77zTQbSG.js +0 -84
  87. package/dist/spawn-DuZfodPa.js +0 -45
  88. package/dist/task-runner-BJ9Up3bG.js +0 -1529
  89. package/dist/topic-CRYYBYp-.js +0 -7
  90. package/dist/topics-BoCkoPJJ.js +0 -21
  91. package/dist/turn-membership-VT7XZh-L.js +0 -856
  92. package/dist/turn-wake-C7HeLHAM.js +0 -151
@@ -1,856 +0,0 @@
1
- import { R as getChatConfig } from "./context-BKF_5zzI.js";
2
- import { Os as SlackActionError, Rs as readPrivateSlackFile, bd as touchConversationDetail, hf as juniorConversations, mf as juniorMessageAttachments, pf as juniorAttachments, vd as conversationDetailTouch, zs as streamPrivateSlackFile } from "./db-of6e3sGt.js";
3
- import { G as mapBounded } from "./prompt-DEkStuxG.js";
4
- import * as z from "zod";
5
- import { and, asc, eq, inArray, isNotNull, isNull, lte, notExists, or, sql } from "drizzle-orm";
6
- import { createHash, randomUUID } from "node:crypto";
7
- import { AwsClient } from "aws4fetch";
8
- import { del, get, issueSignedToken, presignUrl, put } from "@vercel/blob";
9
- // src/chat/attachments/memory.ts
10
- /**
11
- * Store attachments in process memory, for tests.
12
- *
13
- * Objects are lost when the process stops, and each process has its own
14
- * copy. Do not use this provider for deployed apps.
15
- */
16
- function createMemoryAttachmentStorage() {
17
- const objects = /* @__PURE__ */ new Map();
18
- return {
19
- objects,
20
- provider: "memory",
21
- async put(input) {
22
- objects.set(input.key, Buffer.from(await new Response(input.body).arrayBuffer()));
23
- },
24
- async get(key, range) {
25
- const body = objects.get(key);
26
- if (!body) return null;
27
- const bytes = range ? body.subarray(range.start, range.end + 1) : body;
28
- return new ReadableStream({ start(controller) {
29
- controller.enqueue(new Uint8Array(bytes));
30
- controller.close();
31
- } });
32
- },
33
- async delete(keys) {
34
- for (const key of keys) objects.delete(key);
35
- }
36
- };
37
- }
38
- // src/chat/attachments/s3.ts
39
- const S3_DELETE_CONCURRENCY = 8;
40
- /**
41
- * Path-style object URL. Local S3 servers and AWS S3 both accept it.
42
- *
43
- * URL parsing removes `.` and `..` segments, also in `%2e` form. A key with
44
- * such a segment would address a different object, so reject it.
45
- */
46
- function objectUrl(config, key) {
47
- const endpoint = config.endpoint.replace(/\/+$/, "");
48
- const segments = key.split("/");
49
- if (segments.some((segment) => segment === "." || segment === "..")) throw new Error("S3 object keys cannot contain . or .. path segments");
50
- const path = segments.map(encodeURIComponent).join("/");
51
- return `${endpoint}/${encodeURIComponent(config.bucket)}/${path}`;
52
- }
53
- /**
54
- * Read a small S3 response body to the end so the connection is released.
55
- *
56
- * Error and empty bodies are small. `body.cancel()` can hang under the test
57
- * HTTP interceptor, so read the body instead.
58
- */
59
- async function drain(response) {
60
- await response.arrayBuffer();
61
- }
62
- /** Throw on a failed S3 response, and release the response body. */
63
- async function expectOk(response, operation) {
64
- await drain(response);
65
- if (!response.ok) throw new Error(`S3 ${operation} failed with status ${response.status}`);
66
- }
67
- /** Presigned URL lifetime in whole seconds, at least one. */
68
- function expiresInSeconds(expiresAtMs) {
69
- return String(Math.max(1, Math.ceil((expiresAtMs - Date.now()) / 1e3)));
70
- }
71
- /** Store private conversation attachments in an S3-compatible bucket. */
72
- function createS3AttachmentStorage(config) {
73
- const client = new AwsClient({
74
- accessKeyId: config.accessKeyId,
75
- region: config.region,
76
- secretAccessKey: config.secretAccessKey,
77
- service: "s3"
78
- });
79
- const writeClient = new AwsClient({
80
- accessKeyId: config.accessKeyId,
81
- region: config.region,
82
- retries: 0,
83
- secretAccessKey: config.secretAccessKey,
84
- service: "s3"
85
- });
86
- return {
87
- provider: "s3",
88
- async put(input) {
89
- await expectOk(await writeClient.fetch(objectUrl(config, input.key), {
90
- body: input.body,
91
- headers: {
92
- "content-length": String(input.bytes),
93
- "content-type": input.contentType,
94
- "x-amz-content-sha256": "UNSIGNED-PAYLOAD"
95
- },
96
- method: "PUT"
97
- }), "put");
98
- },
99
- async createUploadTarget(input) {
100
- const url = new URL(objectUrl(config, input.key));
101
- url.searchParams.set("X-Amz-Expires", expiresInSeconds(input.expiresAtMs));
102
- const browserHeaders = {
103
- "content-type": input.contentType,
104
- "if-none-match": "*"
105
- };
106
- return {
107
- headers: browserHeaders,
108
- method: "PUT",
109
- url: (await client.sign(url.toString(), {
110
- aws: {
111
- allHeaders: true,
112
- signQuery: true
113
- },
114
- headers: {
115
- ...browserHeaders,
116
- "content-length": String(input.bytes)
117
- },
118
- method: "PUT"
119
- })).url
120
- };
121
- },
122
- async createDownloadUrl(input) {
123
- const url = new URL(objectUrl(config, input.key));
124
- url.searchParams.set("X-Amz-Expires", expiresInSeconds(input.expiresAtMs));
125
- return (await client.sign(url.toString(), {
126
- aws: { signQuery: true },
127
- method: "GET"
128
- })).url;
129
- },
130
- async get(key, range) {
131
- const response = await client.fetch(objectUrl(config, key), range ? { headers: { range: rangeHeader(range) } } : void 0);
132
- if (response.status === 404) {
133
- await drain(response);
134
- return null;
135
- }
136
- if (!response.ok) await expectOk(response, "get");
137
- if (range && response.status !== 206) {
138
- await drain(response);
139
- throw new Error(`S3 get ignored the byte range with status ${response.status}`);
140
- }
141
- return response.body;
142
- },
143
- async delete(keys) {
144
- await mapBounded(keys, async (key) => {
145
- const response = await client.fetch(objectUrl(config, key), { method: "DELETE" });
146
- if (response.status === 404) {
147
- await drain(response);
148
- return;
149
- }
150
- await expectOk(response, "delete");
151
- }, S3_DELETE_CONCURRENCY);
152
- }
153
- };
154
- }
155
- // src/chat/attachments/vercel.ts
156
- const BLOB_API_VERSION = "12";
157
- const delegationPayloadSchema = z.object({ storeId: z.string().min(1) });
158
- /**
159
- * Read the store id from a delegation token, as the SDK does for its own
160
- * presigned requests. The token payload is base64url JSON before the dot.
161
- */
162
- function delegationStoreId(delegationToken) {
163
- const { storeId } = delegationPayloadSchema.parse(JSON.parse(Buffer.from(delegationToken.split(".")[0] ?? "", "base64url").toString()));
164
- return storeId.replace(/^store_/, "");
165
- }
166
- /** Store private conversation attachments in Vercel Blob. */
167
- function createVercelAttachmentStorage() {
168
- return {
169
- provider: "vercel-blob",
170
- async put(input) {
171
- await put(input.key, input.body, {
172
- access: "private",
173
- addRandomSuffix: false,
174
- allowOverwrite: true,
175
- contentType: input.contentType
176
- });
177
- },
178
- async createUploadTarget(input) {
179
- const limits = {
180
- allowedContentTypes: [input.contentType],
181
- maximumSizeInBytes: input.bytes,
182
- validUntil: input.expiresAtMs
183
- };
184
- const token = await issueSignedToken({
185
- ...limits,
186
- operations: ["put"],
187
- pathname: input.key
188
- });
189
- const { presignedUrl } = await presignUrl(token, {
190
- ...limits,
191
- access: "private",
192
- addRandomSuffix: false,
193
- allowOverwrite: false,
194
- operation: "put",
195
- pathname: input.key
196
- });
197
- return {
198
- headers: {
199
- "x-api-version": BLOB_API_VERSION,
200
- "x-content-type": input.contentType,
201
- "x-vercel-blob-access": "private",
202
- "x-vercel-blob-store-id": delegationStoreId(token.delegationToken)
203
- },
204
- method: "PUT",
205
- url: presignedUrl
206
- };
207
- },
208
- async createDownloadUrl(input) {
209
- const token = await issueSignedToken({
210
- operations: ["get"],
211
- pathname: input.key,
212
- validUntil: input.expiresAtMs
213
- });
214
- const { presignedUrl } = await presignUrl(token, {
215
- access: "private",
216
- operation: "get",
217
- pathname: input.key,
218
- useCache: false,
219
- validUntil: input.expiresAtMs
220
- });
221
- return presignedUrl;
222
- },
223
- async get(key, range) {
224
- const result = await get(key, {
225
- access: "private",
226
- useCache: false,
227
- ...range ? { headers: { range: rangeHeader(range) } } : void 0
228
- });
229
- if (result?.statusCode !== 200) return null;
230
- if (range && !result.headers.get("content-range")) {
231
- await result.stream.cancel();
232
- throw new Error("Vercel Blob get ignored the byte range");
233
- }
234
- return result.stream;
235
- },
236
- async delete(keys) {
237
- if (keys.length === 0) return;
238
- await del(keys);
239
- }
240
- };
241
- }
242
- // src/chat/attachments/storage.ts
243
- /** Stream bytes that are already in memory to `AttachmentStorage.put`. */
244
- function bufferBody(data) {
245
- return new ReadableStream({ start(controller) {
246
- controller.enqueue(data);
247
- controller.close();
248
- } });
249
- }
250
- /** Build the HTTP `Range` request header value for one byte range. */
251
- function rangeHeader(range) {
252
- return `bytes=${range.start}-${range.end}`;
253
- }
254
- /**
255
- * Return attachment storage for the configured provider.
256
- *
257
- * Callers do not choose a provider. Chat config decides it.
258
- */
259
- function getAttachmentStorage() {
260
- return createAttachmentStorage(getChatConfig().attachmentStorage);
261
- }
262
- /**
263
- * Create attachment storage for one provider config.
264
- *
265
- * Runtime code uses `getAttachmentStorage()`. Call this only to test a
266
- * provider adapter with its own config.
267
- */
268
- function createAttachmentStorage(config) {
269
- switch (config.provider) {
270
- case "vercel-blob": return createVercelAttachmentStorage();
271
- case "s3": return createS3AttachmentStorage(config.s3);
272
- case "memory": return createMemoryAttachmentStorage();
273
- default: throw new Error(`Unsupported attachment storage provider: ${String(config.provider)}`);
274
- }
275
- }
276
- // src/chat/attachments/source.ts
277
- /** The source deleted the file, or Junior can no longer read it. */
278
- var AttachmentSourceUnavailableError = class extends Error {
279
- constructor(message, options) {
280
- super(message, options);
281
- this.name = "AttachmentSourceUnavailableError";
282
- }
283
- };
284
- // src/chat/attachments/store.ts
285
- const DAY_MS = 864e5;
286
- const ATTACHMENT_GC_BATCH_LIMIT = 200;
287
- /** Time that Junior keeps attachment bytes after the file is stored. */
288
- const ATTACHMENT_RETENTION_MS = 30 * DAY_MS;
289
- /** Only `file` rows: a `url` row has no storage or file fields. */
290
- const isFileAttachment = eq(juniorAttachments.kind, "file");
291
- /**
292
- * The storage and file fields of a `file` row. Every `file` row has them, so
293
- * a missing one is a broken row.
294
- */
295
- function fileFields(row) {
296
- const { bytes, contentType, storageProvider, title } = row;
297
- if (bytes === null || contentType === null || storageProvider === null || title === null) throw new Error(`Attachment ${row.id} has no file fields`);
298
- return {
299
- bytes,
300
- contentType,
301
- filename: title,
302
- storageProvider
303
- };
304
- }
305
- function attachmentIdentity(file) {
306
- if ("data" in file) return file.source ?? { sha256: createHash("sha256").update(file.data).digest("hex") };
307
- return file.source;
308
- }
309
- /** Stable conversation-owned id for one file and its presentation metadata. */
310
- function attachmentId(args) {
311
- const identity = "sha256" in args.identity ? [
312
- args.conversationId,
313
- args.storageProvider,
314
- args.identity.sha256,
315
- args.filename,
316
- args.contentType
317
- ] : [
318
- args.conversationId,
319
- args.storageProvider,
320
- args.filename,
321
- args.contentType,
322
- args.identity.provider,
323
- args.identity.id
324
- ];
325
- return createHash("sha256").update(identity.join("\0")).digest("hex");
326
- }
327
- /**
328
- * Object key for one write attempt.
329
- *
330
- * Attachment ids are content-stable. Object keys are not: each put gets a fresh
331
- * key so a failed-write cleanup or GC delete cannot remove another writer's
332
- * durable blob.
333
- */
334
- function attachmentKey(args) {
335
- return `conversations/${args.conversationId}/attachments/${args.attachmentId}/${args.writeId}/${args.filename}`;
336
- }
337
- /** A source whose bytes do not match its declared size. A retry cannot fix it. */
338
- var AttachmentSizeError = class extends Error {
339
- constructor(bytes, expected, options) {
340
- super(`Attachment body does not match its declared ${expected} bytes (read ${bytes})`, options);
341
- this.name = "AttachmentSizeError";
342
- }
343
- };
344
- /** Tries for one object write, each with a freshly opened body. */
345
- const WRITE_ATTEMPTS = 3;
346
- async function bestEffortDelete(storage, key) {
347
- if (key === null) return;
348
- try {
349
- await storage.delete([key]);
350
- } catch {}
351
- }
352
- /**
353
- * Stream one file to a fresh key, and return its size and digest.
354
- *
355
- * The digest is taken while the bytes stream, so the body is never held
356
- * whole. A body that does not match its declared size is not kept.
357
- */
358
- async function writeAttachmentObject(args) {
359
- for (let attempt = 1;; attempt += 1) try {
360
- return await writeAttachmentObjectOnce(args);
361
- } catch (error) {
362
- if (error instanceof AttachmentSizeError || error instanceof AttachmentSourceUnavailableError || attempt >= WRITE_ATTEMPTS) {
363
- await bestEffortDelete(args.storage, args.key);
364
- throw error;
365
- }
366
- }
367
- }
368
- async function writeAttachmentObjectOnce(args) {
369
- const { file } = args;
370
- const expected = "data" in file ? file.data.byteLength : file.bytes;
371
- const source = "data" in file ? bufferBody(file.data) : await file.open();
372
- const hash = createHash("sha256");
373
- let bytes = 0;
374
- const body = source.pipeThrough(new TransformStream({ transform(chunk, controller) {
375
- bytes += chunk.byteLength;
376
- if (bytes > expected) throw new AttachmentSizeError(bytes, expected);
377
- hash.update(chunk);
378
- controller.enqueue(chunk);
379
- } }));
380
- try {
381
- await args.storage.put({
382
- body,
383
- bytes: expected,
384
- contentType: file.mimeType,
385
- key: args.key
386
- });
387
- } catch (error) {
388
- if (bytes > expected) throw new AttachmentSizeError(bytes, expected, { cause: error });
389
- throw error;
390
- }
391
- if (bytes !== expected) throw new AttachmentSizeError(bytes, expected);
392
- return {
393
- bytes,
394
- sha256: hash.digest("hex")
395
- };
396
- }
397
- async function isConversationPurged(db, conversationId) {
398
- const [row] = await db.db().select({ transcriptPurgedAt: juniorConversations.transcriptPurgedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId));
399
- return row?.transcriptPurgedAt != null;
400
- }
401
- function purgedConversationError(conversationId) {
402
- return /* @__PURE__ */ new Error(`Cannot store attachment for purged conversation ${conversationId}`);
403
- }
404
- async function assertConversationNotPurged(db, conversationId) {
405
- if (await isConversationPurged(db, conversationId)) throw purgedConversationError(conversationId);
406
- }
407
- /** Mark a just-written row for deletion and drop its unused object. */
408
- async function rejectPurgedAttachmentWrite(args) {
409
- const db = args.db.db();
410
- await db.with(conversationDetailTouch(db, [args.conversationId])).update(juniorAttachments).set({ deleteRequestedAt: args.now }).where(eq(juniorAttachments.id, args.id));
411
- await bestEffortDelete(args.storage, args.storageKey);
412
- throw purgedConversationError(args.conversationId);
413
- }
414
- /**
415
- * Return another writer's live row only when the conversation is still active.
416
- *
417
- * The caller already wrote a unique object for this attempt. Delete that unused
418
- * object either way. If the conversation is purged, do not report success for a
419
- * row that purge/GC is about to remove.
420
- */
421
- async function reuseLiveAttachment(args) {
422
- await bestEffortDelete(args.storage, args.storageKey);
423
- await assertConversationNotPurged(args.db, args.conversationId);
424
- return { id: args.id };
425
- }
426
- /**
427
- * Persist one conversation-owned file.
428
- *
429
- * Identity is stable under the conversation: it comes from the file's source
430
- * when it has one, and from its digest otherwise. Object storage is written
431
- * first under a unique key; the SQL row is created only after that write
432
- * succeeds. A row means the attachment is durable. Retries reuse an existing
433
- * live row. A purge-marked row is revived by writing a new object and pointing
434
- * the row at it, unless the conversation is still purged. If the SQL write
435
- * fails after object storage accepts the bytes, this path deletes that unique
436
- * object. A process crash between those steps can leave an unreferenced unique
437
- * object with no SQL row.
438
- */
439
- async function storeAttachment(args) {
440
- const now = new Date(args.nowMs ?? Date.now());
441
- const identity = attachmentIdentity(args.file);
442
- const source = args.file.source;
443
- const id = attachmentId({
444
- conversationId: args.conversationId,
445
- contentType: args.file.mimeType,
446
- filename: args.file.filename,
447
- identity,
448
- storageProvider: args.storage.provider
449
- });
450
- const [existing] = await args.db.db().select({
451
- contentType: juniorAttachments.contentType,
452
- conversationId: juniorAttachments.conversationId,
453
- deleteRequestedAt: juniorAttachments.deleteRequestedAt,
454
- filename: juniorAttachments.title,
455
- id: juniorAttachments.id,
456
- provider: juniorAttachments.provider,
457
- providerId: juniorAttachments.providerId,
458
- storageProvider: juniorAttachments.storageProvider,
459
- sha256: juniorAttachments.sha256,
460
- storageKey: juniorAttachments.storageKey
461
- }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
462
- if (existing) {
463
- if (existing.contentType !== args.file.mimeType || existing.conversationId !== args.conversationId || existing.filename !== args.file.filename || existing.provider !== (source?.provider ?? null) || existing.providerId !== (source?.id ?? null) || existing.storageProvider !== args.storage.provider || "sha256" in identity && existing.sha256 !== identity.sha256) throw new Error(`Attachment write conflicts with ${existing.id}`);
464
- if (existing.deleteRequestedAt === null) {
465
- await assertConversationNotPurged(args.db, args.conversationId);
466
- return { id: existing.id };
467
- }
468
- }
469
- await assertConversationNotPurged(args.db, args.conversationId);
470
- const { file } = args;
471
- let storageKey = null;
472
- let written;
473
- if ("deferred" in file) written = {
474
- bytes: file.bytes,
475
- sha256: null
476
- };
477
- else {
478
- storageKey = attachmentKey({
479
- attachmentId: id,
480
- conversationId: args.conversationId,
481
- filename: file.filename,
482
- writeId: randomUUID()
483
- });
484
- written = await writeAttachmentObject({
485
- file,
486
- key: storageKey,
487
- storage: args.storage
488
- });
489
- }
490
- if (existing?.deleteRequestedAt != null) {
491
- if (await isConversationPurged(args.db, args.conversationId)) {
492
- await bestEffortDelete(args.storage, storageKey);
493
- throw purgedConversationError(args.conversationId);
494
- }
495
- const oldStorageKey = existing.storageKey;
496
- if ((await args.db.db().with(conversationDetailTouch(args.db.db(), [args.conversationId])).update(juniorAttachments).set({
497
- ...written,
498
- deleteRequestedAt: null,
499
- storageKey
500
- }).where(and(eq(juniorAttachments.id, id), isNotNull(juniorAttachments.deleteRequestedAt))).returning({ id: juniorAttachments.id })).length > 0) {
501
- if (await isConversationPurged(args.db, args.conversationId)) await rejectPurgedAttachmentWrite({
502
- conversationId: args.conversationId,
503
- db: args.db,
504
- id,
505
- now,
506
- storage: args.storage,
507
- storageKey
508
- });
509
- if (oldStorageKey !== storageKey) await bestEffortDelete(args.storage, oldStorageKey);
510
- return { id };
511
- }
512
- const [afterRace] = await args.db.db().select({
513
- deleteRequestedAt: juniorAttachments.deleteRequestedAt,
514
- id: juniorAttachments.id,
515
- storageKey: juniorAttachments.storageKey
516
- }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
517
- if (afterRace?.deleteRequestedAt === null) return reuseLiveAttachment({
518
- conversationId: args.conversationId,
519
- db: args.db,
520
- id: afterRace.id,
521
- storage: args.storage,
522
- storageKey
523
- });
524
- }
525
- let inserted = [];
526
- try {
527
- inserted = await args.db.db().with(conversationDetailTouch(args.db.db(), [args.conversationId])).insert(juniorAttachments).values({
528
- id,
529
- conversationId: args.conversationId,
530
- storageProvider: args.storage.provider,
531
- storageKey,
532
- provider: source?.provider,
533
- providerId: source?.id,
534
- title: args.file.filename,
535
- contentType: args.file.mimeType,
536
- ...written,
537
- createdAt: now
538
- }).onConflictDoNothing({ target: juniorAttachments.id }).returning({ id: juniorAttachments.id });
539
- } catch (error) {
540
- await bestEffortDelete(args.storage, storageKey);
541
- throw error;
542
- }
543
- if (inserted.length > 0) {
544
- if (await isConversationPurged(args.db, args.conversationId)) await rejectPurgedAttachmentWrite({
545
- conversationId: args.conversationId,
546
- db: args.db,
547
- id,
548
- now,
549
- storage: args.storage,
550
- storageKey
551
- });
552
- return { id };
553
- }
554
- const [row] = await args.db.db().select({
555
- deleteRequestedAt: juniorAttachments.deleteRequestedAt,
556
- id: juniorAttachments.id,
557
- storageKey: juniorAttachments.storageKey
558
- }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
559
- if (!row) {
560
- await bestEffortDelete(args.storage, storageKey);
561
- throw new Error(`Attachment row missing after write for ${id}`);
562
- }
563
- if (row.deleteRequestedAt === null) return reuseLiveAttachment({
564
- conversationId: args.conversationId,
565
- db: args.db,
566
- id: row.id,
567
- storage: args.storage,
568
- storageKey
569
- });
570
- if (await isConversationPurged(args.db, args.conversationId)) {
571
- await bestEffortDelete(args.storage, storageKey);
572
- throw purgedConversationError(args.conversationId);
573
- }
574
- if ((await args.db.db().with(conversationDetailTouch(args.db.db(), [args.conversationId])).update(juniorAttachments).set({
575
- ...written,
576
- deleteRequestedAt: null,
577
- storageKey
578
- }).where(and(eq(juniorAttachments.id, id), isNotNull(juniorAttachments.deleteRequestedAt))).returning({ id: juniorAttachments.id })).length > 0) {
579
- if (await isConversationPurged(args.db, args.conversationId)) await rejectPurgedAttachmentWrite({
580
- conversationId: args.conversationId,
581
- db: args.db,
582
- id,
583
- now,
584
- storage: args.storage,
585
- storageKey
586
- });
587
- if (row.storageKey !== storageKey) await bestEffortDelete(args.storage, row.storageKey);
588
- return { id };
589
- }
590
- const [afterRace] = await args.db.db().select({
591
- deleteRequestedAt: juniorAttachments.deleteRequestedAt,
592
- id: juniorAttachments.id
593
- }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
594
- if (afterRace?.deleteRequestedAt === null) return reuseLiveAttachment({
595
- conversationId: args.conversationId,
596
- db: args.db,
597
- id: afterRace.id,
598
- storage: args.storage,
599
- storageKey
600
- });
601
- await bestEffortDelete(args.storage, storageKey);
602
- throw new Error(`Attachment ${id} disappeared while reviving`);
603
- }
604
- /**
605
- * Record an object that a browser already wrote, under the upload's id.
606
- *
607
- * The row takes over the object key. A retry with the same id keeps the
608
- * first row. The caller checked the object's size, type, and digest.
609
- */
610
- async function recordUploadedAttachment(args) {
611
- const { attachment } = args;
612
- const now = new Date(args.nowMs);
613
- await assertConversationNotPurged(args.db, attachment.conversationId);
614
- if ((await args.db.db().with(conversationDetailTouch(args.db.db(), [attachment.conversationId])).insert(juniorAttachments).values({
615
- bytes: attachment.bytes,
616
- contentType: attachment.contentType,
617
- conversationId: attachment.conversationId,
618
- createdAt: now,
619
- id: attachment.id,
620
- sha256: attachment.sha256,
621
- storageKey: attachment.storageKey,
622
- storageProvider: args.storage.provider,
623
- title: attachment.filename
624
- }).onConflictDoNothing({ target: juniorAttachments.id }).returning({ id: juniorAttachments.id })).length > 0 && await isConversationPurged(args.db, attachment.conversationId)) await rejectPurgedAttachmentWrite({
625
- conversationId: attachment.conversationId,
626
- db: args.db,
627
- id: attachment.id,
628
- now,
629
- storage: args.storage,
630
- storageKey: attachment.storageKey
631
- });
632
- }
633
- /**
634
- * Store a file that Junior recorded without its bytes, on its first read.
635
- *
636
- * The bytes stream from the source to a fresh key. The row then takes that
637
- * key only while it is still unstored, live, and in a conversation that is
638
- * not purged. Purge marks rows in the transaction that purges the
639
- * conversation, so this update cannot revive a purged row. When the update
640
- * misses, the new object is deleted: return the row that another writer
641
- * stored, or null when the row is no longer live.
642
- */
643
- async function storeDeferredAttachment(args) {
644
- const { attachment, storage } = args;
645
- const storageKey = attachmentKey({
646
- attachmentId: attachment.id,
647
- conversationId: attachment.conversationId,
648
- filename: attachment.filename,
649
- writeId: randomUUID()
650
- });
651
- const written = await writeAttachmentObject({
652
- file: {
653
- bytes: args.file.bytes,
654
- filename: attachment.filename,
655
- mimeType: attachment.contentType,
656
- open: args.file.open,
657
- source: attachment.source
658
- },
659
- key: storageKey,
660
- storage
661
- });
662
- const db = args.db.db();
663
- if ((await db.with(conversationDetailTouch(db, [attachment.conversationId])).update(juniorAttachments).set({
664
- ...written,
665
- storageKey
666
- }).where(and(eq(juniorAttachments.id, attachment.id), eq(juniorAttachments.conversationId, attachment.conversationId), eq(juniorAttachments.storageProvider, storage.provider), isNull(juniorAttachments.storageKey), isNull(juniorAttachments.deleteRequestedAt), notExists(db.select({ id: juniorConversations.conversationId }).from(juniorConversations).where(and(eq(juniorConversations.conversationId, attachment.conversationId), isNotNull(juniorConversations.transcriptPurgedAt)))))).returning({ id: juniorAttachments.id })).length > 0) return {
667
- ...attachment,
668
- bytes: written.bytes,
669
- storageKey
670
- };
671
- await bestEffortDelete(storage, storageKey);
672
- const current = await readLiveAttachment({
673
- attachmentId: attachment.id,
674
- conversationId: attachment.conversationId,
675
- db: args.db
676
- });
677
- return current?.storageKey ? {
678
- ...current,
679
- storageKey: current.storageKey
680
- } : null;
681
- }
682
- /** Load one live attachment owned by a conversation. */
683
- async function readLiveAttachment(args) {
684
- const [row] = await args.db.db().select({
685
- bytes: juniorAttachments.bytes,
686
- contentType: juniorAttachments.contentType,
687
- conversationId: juniorAttachments.conversationId,
688
- deleteRequestedAt: juniorAttachments.deleteRequestedAt,
689
- id: juniorAttachments.id,
690
- provider: juniorAttachments.provider,
691
- providerId: juniorAttachments.providerId,
692
- storageProvider: juniorAttachments.storageProvider,
693
- storageKey: juniorAttachments.storageKey,
694
- title: juniorAttachments.title
695
- }).from(juniorAttachments).where(and(eq(juniorAttachments.id, args.attachmentId), isFileAttachment, eq(juniorAttachments.conversationId, args.conversationId), isNull(juniorAttachments.deleteRequestedAt)));
696
- if (!row) return null;
697
- if (await isConversationPurged(args.db, args.conversationId)) return null;
698
- return {
699
- ...fileFields(row),
700
- conversationId: row.conversationId,
701
- id: row.id,
702
- source: row.provider && row.providerId ? {
703
- id: row.providerId,
704
- provider: row.provider
705
- } : null,
706
- storageKey: row.storageKey
707
- };
708
- }
709
- /** Persist many conversation-owned files. */
710
- async function storeAttachments(args) {
711
- return await mapBounded(args.files, (file) => storeAttachment({
712
- conversationId: args.conversationId,
713
- db: args.db,
714
- file: {
715
- data: file.data,
716
- filename: file.filename,
717
- mimeType: file.mimeType
718
- },
719
- ...args.nowMs !== void 0 ? { nowMs: args.nowMs } : void 0,
720
- storage: args.storage
721
- }));
722
- }
723
- /** Mark attachments unavailable when their conversation content is purged. */
724
- async function requestAttachmentDeletion(db, conversationIds, nowMs) {
725
- if (conversationIds.length === 0) return;
726
- await db.db().with(conversationDetailTouch(db.db(), conversationIds)).update(juniorAttachments).set({ deleteRequestedAt: new Date(nowMs) }).where(and(inArray(juniorAttachments.conversationId, conversationIds), isNull(juniorAttachments.deleteRequestedAt)));
727
- }
728
- /**
729
- * Delete purged attachments in one bounded batch.
730
- *
731
- * Eligible files are 30 days old, explicitly purge-marked, or owned by a
732
- * conversation whose transcript is already purged. A `url` row has no bytes,
733
- * so it lives as long as its message: it is eligible only when purge-marked
734
- * or purged. Delete object keys first, then remove rows that are still
735
- * eligible so a failed blob delete remains retryable.
736
- */
737
- async function collectAttachmentGarbage(args) {
738
- const expiresBefore = /* @__PURE__ */ new Date(args.nowMs - ATTACHMENT_RETENTION_MS);
739
- const purged = or(isNotNull(juniorAttachments.deleteRequestedAt), isNotNull(juniorConversations.transcriptPurgedAt));
740
- const eligible = or(lte(juniorAttachments.createdAt, expiresBefore), purged);
741
- const isUrl = eq(juniorAttachments.kind, "url");
742
- const rows = await args.db.db().select({
743
- id: juniorAttachments.id,
744
- storageKey: juniorAttachments.storageKey
745
- }).from(juniorAttachments).innerJoin(juniorConversations, eq(juniorAttachments.conversationId, juniorConversations.conversationId)).where(or(and(eq(juniorAttachments.storageProvider, args.storage.provider), eligible), and(isUrl, purged))).orderBy(asc(juniorAttachments.createdAt), asc(juniorAttachments.id)).limit(args.limit ?? ATTACHMENT_GC_BATCH_LIMIT);
746
- if (rows.length === 0) return { deleted: 0 };
747
- const keys = rows.flatMap((row) => row.storageKey ? [row.storageKey] : []);
748
- if (keys.length > 0) await args.storage.delete(keys);
749
- const stillEligible = await args.db.db().select({ id: juniorAttachments.id }).from(juniorAttachments).innerJoin(juniorConversations, eq(juniorAttachments.conversationId, juniorConversations.conversationId)).where(and(inArray(juniorAttachments.id, rows.map((row) => row.id)), or(and(isFileAttachment, eligible), and(isUrl, purged))));
750
- if (stillEligible.length === 0) return { deleted: 0 };
751
- const removed = await args.db.db().delete(juniorAttachments).where(inArray(juniorAttachments.id, stillEligible.map((row) => row.id))).returning({
752
- conversationId: juniorAttachments.conversationId,
753
- id: juniorAttachments.id,
754
- kind: juniorAttachments.kind
755
- });
756
- const urls = removed.filter((row) => row.kind === "url");
757
- if (urls.length > 0) await args.db.db().delete(juniorMessageAttachments).where(and(inArray(juniorMessageAttachments.conversationId, urls.map((row) => row.conversationId)), inArray(juniorMessageAttachments.attachmentId, urls.map((row) => row.id))));
758
- await touchConversationDetail(args.db.db(), removed.map((row) => row.conversationId));
759
- return { deleted: removed.length };
760
- }
761
- // src/chat/slack/attachments.ts
762
- /** Save the vision summary for a stored Slack attachment. */
763
- async function recordSlackAttachment(args) {
764
- const db = args.db.db();
765
- await db.with(conversationDetailTouch(db, [args.conversationId])).update(juniorAttachments).set({ visionSummary: args.visionSummary }).where(and(eq(juniorAttachments.id, args.attachmentId), eq(juniorAttachments.conversationId, args.conversationId), isNull(juniorAttachments.deleteRequestedAt)));
766
- }
767
- /** Read a saved vision summary for one live attachment. */
768
- async function readAttachmentVisionSummary(args) {
769
- const [row] = await args.db.db().select({ visionSummary: juniorAttachments.visionSummary }).from(juniorAttachments).where(and(eq(juniorAttachments.id, args.attachmentId), eq(juniorAttachments.conversationId, args.conversationId), isNull(juniorAttachments.deleteRequestedAt)));
770
- return row?.visionSummary;
771
- }
772
- /** Match live conversation attachments to Slack file ids. */
773
- async function matchSlackAttachments(args) {
774
- if (args.providerIds.length === 0) return [];
775
- return (await args.db.db().select({
776
- id: juniorAttachments.id,
777
- providerId: juniorAttachments.providerId,
778
- bytes: juniorAttachments.bytes,
779
- contentType: juniorAttachments.contentType,
780
- storageKey: juniorAttachments.storageKey,
781
- storageProvider: juniorAttachments.storageProvider,
782
- title: juniorAttachments.title
783
- }).from(juniorAttachments).where(and(eq(juniorAttachments.conversationId, args.conversationId), eq(juniorAttachments.provider, "slack"), inArray(juniorAttachments.providerId, args.providerIds), isNull(juniorAttachments.deleteRequestedAt)))).map((row) => {
784
- const { bytes, contentType, filename } = fileFields(row);
785
- const attachment = {
786
- bytes,
787
- contentType,
788
- filename,
789
- id: row.id,
790
- providerId: row.providerId
791
- };
792
- return row.storageKey === null ? {
793
- ...attachment,
794
- pending: true
795
- } : attachment;
796
- });
797
- }
798
- /**
799
- * Fingerprint the live Slack attachments that `matchSlackAttachments` can
800
- * return for a Conversation. It changes when one is recorded, stored, or
801
- * deleted, so a reader can tell that stored messages may now show other
802
- * files, or a file that is no longer pending.
803
- */
804
- function slackAttachmentsVersionQuery(db, conversationId) {
805
- return db.select({ version: sql`coalesce(md5(string_agg(concat(${juniorAttachments.id}, ':', ${juniorAttachments.storageKey} is null), ',' order by ${juniorAttachments.id})), '')` }).from(juniorAttachments).where(and(eq(juniorAttachments.conversationId, conversationId), eq(juniorAttachments.provider, "slack"), isNull(juniorAttachments.deleteRequestedAt)));
806
- }
807
- /** Read the Slack file identity retained by the Chat SDK. */
808
- function getSlackFileId(attachment) {
809
- const metadataId = attachment.fetchMetadata?.["fileId"];
810
- if (metadataId) return metadataId;
811
- return (attachment.url ?? attachment.fetchMetadata?.["url"] ?? "").match(/(?:^|[-/])(F[A-Z0-9]+)(?:[-/]|$)/)?.[1];
812
- }
813
- /**
814
- * Look up a Slack file that Junior recorded without storing it yet.
815
- *
816
- * Uses the installation token that the caller binds: the Slack turn, or the
817
- * dashboard route for the conversation's Slack team.
818
- */
819
- const readSlackAttachmentSource = async (source) => {
820
- const unavailable = (cause) => new AttachmentSourceUnavailableError("The Slack file was deleted, or this app can no longer access it.", { cause });
821
- if (source.provider !== "slack") throw unavailable();
822
- const file = await readPrivateSlackFile(source.id);
823
- if (!file) throw unavailable();
824
- return {
825
- bytes: file.bytes,
826
- open: async () => {
827
- try {
828
- return await streamPrivateSlackFile(file.url);
829
- } catch (error) {
830
- if (error instanceof SlackActionError && (error.code === "not_found" || error.statusCode === 403)) throw unavailable(error);
831
- throw error;
832
- }
833
- }
834
- };
835
- };
836
- // src/chat/task-execution/turn-membership.ts
837
- /** True when the committed message at `seq` belongs to the Turn. */
838
- function isTurnMessage(start, seq, message) {
839
- return seq > start.seq && message.role !== "system";
840
- }
841
- /**
842
- * The messages of a saved Turn with their provenance. Without a
843
- * `turn_started` event, nothing tells this Turn from earlier history, so it
844
- * has no messages.
845
- */
846
- function savedTurnMessages(record, start) {
847
- if (!start) return [];
848
- return record.piMessages.flatMap((message, index) => {
849
- const seq = record.piMessageSeqs[index];
850
- return seq !== void 0 && isTurnMessage(start, seq, message) ? [{
851
- message,
852
- provenance: record.piMessageProvenance[index] ?? { authority: "context" }
853
- }] : [];
854
- });
855
- }
856
- export { AttachmentSourceUnavailableError as _, readAttachmentVisionSummary as a, slackAttachmentsVersionQuery as c, readLiveAttachment as d, recordUploadedAttachment as f, storeDeferredAttachment as g, storeAttachments as h, matchSlackAttachments as i, collectAttachmentGarbage as l, storeAttachment as m, savedTurnMessages as n, readSlackAttachmentSource as o, requestAttachmentDeletion as p, getSlackFileId as r, recordSlackAttachment as s, isTurnMessage as t, isFileAttachment as u, bufferBody as v, getAttachmentStorage as y };