@sentry/junior 0.311.0 → 0.313.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 (120) hide show
  1. package/dist/{adapter-B1wujchl.js → adapter-CYAvJzZS.js} +1 -1
  2. package/dist/{adapter-context-G2M0y6rP.js → adapter-context-CVsHoVSf.js} +2 -2
  3. package/dist/{admin-DCiBhUT1.js → admin-Cyhb4TwZ.js} +1 -1
  4. package/dist/{agent-runner-BVHPUIc8.js → agent-runner-B5y9MsT-.js} +3487 -3493
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +6 -6
  7. package/dist/api.d.ts +2 -2
  8. package/dist/api.js +294 -311
  9. package/dist/{app-Cw5Vy6H6.d.ts → app-DA8-hCMj.d.ts} +2 -9
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +336 -604
  12. package/dist/{background-compaction-queue-CJDnWVOJ.js → background-compaction-queue-iZXadLV3.js} +60 -85
  13. package/dist/{catalog-runtime-DMY3VV-D.js → catalog-runtime-kkE3hvCX.js} +1 -1
  14. package/dist/channel-access-mt7K6dPh.js +221 -0
  15. package/dist/cli/chat.js +18 -19
  16. package/dist/cli/check.js +3 -3
  17. package/dist/cli/init.js +0 -1
  18. package/dist/cli/main.js +3 -7
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/run.d.ts +1 -2
  21. package/dist/cli/run.js +1 -2
  22. package/dist/cli/snapshot-create.js +5 -5
  23. package/dist/cli/upgrade.d.ts +1 -1
  24. package/dist/cli/upgrade.js +3 -3
  25. package/dist/{config-BrXDQefC.js → config-CWbwKj0j.js} +59 -27
  26. package/dist/{continue-in-slack-DNXSC9So.js → continue-in-slack-CxyFzdlF.js} +7 -8
  27. package/dist/{conversation-feed-DkinDu5o.js → conversation-feed-BEXLD3Me.js} +86 -21
  28. package/dist/{conversation-privacy-DxttrKb9.js → conversation-privacy-BrMiDN61.js} +1 -1
  29. package/dist/{conversation-turn-DWw7Xhdr.js → conversation-turn-B35eu0uz.js} +78 -56
  30. package/dist/{credential-sync-Bk8wGb8Y.js → credential-sync-DWTOEQrm.js} +15 -15
  31. package/dist/{projection-Cns7XwWa.js → credentialed-Dyv8b-lu.js} +16306 -20732
  32. package/dist/{db-7ETESH44.d.ts → db-DYGcXYl3.d.ts} +11 -6
  33. package/dist/{db-DTxzH7u5.js → db-PwSRzWWn.js} +181 -100
  34. package/dist/{executor-DqTiYj9S.js → executor-CgWyWfYz.js} +117 -99
  35. package/dist/{html-B9Sl4Axb.js → html-DidUcRhI.js} +6 -6
  36. package/dist/ingest-B0AggUEC.js +7931 -0
  37. package/dist/{install-Sg4ePfLl.js → install-2urLLXNt.js} +2 -2
  38. package/dist/instrumentation.js +3 -3
  39. package/dist/{lineage-BHAMpNKr.js → lineage-BXplQAVH.js} +2 -2
  40. package/dist/{stop-CYsfc0Ed.js → list-DyIyReSV.js} +709 -475
  41. package/dist/{logging-FjclQsXu.js → logging-DNt-qOIO.js} +1 -1
  42. package/dist/{schedule-BLJ476XQ.js → media-B0pZJ0bG.js} +1058 -11
  43. package/dist/{message-CJ7_RL50.js → message-Z5YKC-Af.js} +35 -28
  44. package/dist/{model-input-CMLh4Cwq.js → model-input-BhPJYdSV.js} +3 -3
  45. package/dist/nitro.d.ts +1 -1
  46. package/dist/nitro.js +4 -3
  47. package/dist/{oauth-callback-server-RVcbiDjL.js → oauth-callback-server-ByvDdcdY.js} +2 -2
  48. package/dist/{oauth-relay-Bu9kkaQu.js → oauth-relay-D-kK0yoN.js} +1 -1
  49. package/dist/{registry-BPwuOP2O.js → registry-POH4bZC4.js} +1 -1
  50. package/dist/reporting-window-C4dbzDiR.js +124 -0
  51. package/dist/request-deadline-BUiRYQYj.js +24 -0
  52. package/dist/{resolve-BK29bBry.js → resolve-CWtBNSKP.js} +3 -3
  53. package/dist/{runner-BcAE-cJm.js → runner-CsZ_VRxp.js} +14 -16
  54. package/dist/{sandbox-egress-signals-C-q0go5b.js → sandbox-egress-signals-FbCk1FkN.js} +1 -1
  55. package/dist/{schema-DYcJeV7d.d.ts → schema-DBf18QPS.d.ts} +2773 -3630
  56. package/dist/{schema-BLgSZXcL.js → schema-DojR2uCL.js} +106 -121
  57. package/dist/{service-account-iJoCtkHR.js → service-account-CDYb9hfX.js} +3 -3
  58. package/dist/{service-account-gN0zqf0S.js → service-account-o15pZWcJ.js} +5 -5
  59. package/dist/{skills-BoZ80epJ.js → skills-B0jP4whm.js} +2 -2
  60. package/dist/{slack-conversation-unfurl-CogYrITA.js → slack-conversation-unfurl-D26t9kBC.js} +9 -9
  61. package/dist/{spawn-Dk92r7mX.js → spawn-BjljgExZ.js} +14 -32
  62. package/dist/start-conversation-DbVujrwO.js +755 -0
  63. package/dist/{state-DH3Cmgp3.js → state-BTawTCme.js} +4 -4
  64. package/dist/statuses-BKwqCPhj.js +69 -0
  65. package/dist/store-CjXrp-Up.js +492 -0
  66. package/dist/task-queue-Cwlatjz3.js +90 -0
  67. package/dist/task-runner--Ke8KSMf.js +1432 -0
  68. package/dist/{thread-context-BW2BsQbH.js → thread-context-B8exINEe.js} +6 -7
  69. package/dist/turn-membership-DTR3SaKD.js +5859 -0
  70. package/dist/{validation-DrJd0nnq.js → validation-Ce0qbMlT.js} +1 -1
  71. package/dist/{task-queue-C_zldF5J.js → vercel-queue-q4z8w5QO.js} +93 -172
  72. package/dist/{version-CNKZ8owc.js → version-DFh4n9nr.js} +1 -1
  73. package/dist/version.js +1 -1
  74. package/dist/{warmup-BWdHew2H.js → warmup-D5hzqTcp.js} +4853 -13605
  75. package/dist/web-message-id-C6P83ans.js +10 -0
  76. package/dist/{worker-t9qpu_Zx.js → worker-CDg9Lbpg.js} +20 -7
  77. package/migrations/0143_todos.sql +14 -0
  78. package/migrations/0144_inbox_items.sql +32 -0
  79. package/migrations/0145_todo_changed_by_agent.sql +1 -0
  80. package/migrations/0146_inbox_item_subject_title_parts.sql +1 -0
  81. package/migrations/0147_inbox_snooze_wake_reason.sql +1 -0
  82. package/migrations/0148_authorization_request_index.sql +1 -0
  83. package/migrations/0149_conversation_metadata.sql +10 -0
  84. package/migrations/0150_conversation_metadata_fill.sql +39 -0
  85. package/migrations/0151_conversation_search_index.sql +1 -0
  86. package/migrations/0152_inbox_item_legacy_automation_keys.sql +21 -0
  87. package/migrations/0153_artifact_expiry.sql +1 -0
  88. package/migrations/0154_artifact_permanent_sha_index.sql +1 -0
  89. package/migrations/0155_artifact_drop_public_sha_index.sql +3 -0
  90. package/migrations/0156_conversation_kind_lead.sql +6 -0
  91. package/migrations/0157_conversation_lead_actor_index.sql +1 -0
  92. package/migrations/0158_keep_legacy_archive_columns.sql +5 -0
  93. package/migrations/0159_conversation_embeddings_fk_validate.sql +5 -0
  94. package/migrations/meta/0143_snapshot.json +6434 -0
  95. package/migrations/meta/0144_snapshot.json +6434 -0
  96. package/migrations/meta/0145_snapshot.json +6440 -0
  97. package/migrations/meta/0146_snapshot.json +6446 -0
  98. package/migrations/meta/0147_snapshot.json +6452 -0
  99. package/migrations/meta/0148_snapshot.json +6474 -0
  100. package/migrations/meta/0149_snapshot.json +6490 -0
  101. package/migrations/meta/0150_snapshot.json +6490 -0
  102. package/migrations/meta/0151_snapshot.json +6505 -0
  103. package/migrations/meta/0152_snapshot.json +6505 -0
  104. package/migrations/meta/0153_snapshot.json +6511 -0
  105. package/migrations/meta/0154_snapshot.json +6533 -0
  106. package/migrations/meta/0155_snapshot.json +6511 -0
  107. package/migrations/meta/0156_snapshot.json +6511 -0
  108. package/migrations/meta/0157_snapshot.json +6527 -0
  109. package/migrations/meta/0158_snapshot.json +6515 -0
  110. package/migrations/meta/0159_snapshot.json +6515 -0
  111. package/migrations/meta/_journal.json +120 -1
  112. package/package.json +6 -6
  113. package/skills/design-automation-skill/SKILL.md +108 -0
  114. package/dist/briefs-BDjnug6Y.js +0 -395
  115. package/dist/conversation-ca__NDQW.js +0 -1063
  116. package/dist/prompt-CDqcsDYC.js +0 -910
  117. package/dist/store-DmmMIrQi.js +0 -335
  118. package/dist/task-runner-C7oCJQIx.js +0 -294
  119. package/dist/turn-session-routing-Xh_2nSQe.js +0 -261
  120. package/dist/web-message-id-Ch5dPq-a.js +0 -306
@@ -1,7 +1,7 @@
1
- import { i as getChatConfig } from "./config-BrXDQefC.js";
2
- import { h as logWarn } from "./logging-FjclQsXu.js";
3
- import { o as getDb } from "./db-DTxzH7u5.js";
4
- import { K as juniorUsers } from "./executor-DqTiYj9S.js";
1
+ import { r as getChatConfig } from "./config-CWbwKj0j.js";
2
+ import { h as logWarn } from "./logging-DNt-qOIO.js";
3
+ import { o as getDb } from "./db-PwSRzWWn.js";
4
+ import { K as juniorUsers } from "./executor-CgWyWfYz.js";
5
5
  import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
6
6
  import { eq } from "drizzle-orm";
7
7
  // src/chat/conversations/legacy-web-actor-id.ts
@@ -0,0 +1,69 @@
1
+ import * as z from "zod";
2
+ // src/chat/todos/types.ts
3
+ /** Statuses of a To-do. `done` and `dropped` close it. */
4
+ const TODO_STATUSES = [
5
+ "open",
6
+ "in_progress",
7
+ "done",
8
+ "dropped"
9
+ ];
10
+ /** Statuses of a To-do that is still work to do. */
11
+ const OPEN_TODO_STATUSES = ["open", "in_progress"];
12
+ /** Whether a To-do with this status is still work to do. */
13
+ function isOpenTodoStatus(status) {
14
+ return status === "open" || status === "in_progress";
15
+ }
16
+ /** Model-facing tool that changes the To-dos. */
17
+ const UPDATE_TODOS_TOOL_NAME = "updateTodos";
18
+ /** Assignee text for the list's own agent, in tool results and blocks. */
19
+ const SELF_TODO_ASSIGNEE = "self";
20
+ // src/api/schema/user-customization.ts
21
+ /** Longest customization text one user can save. */
22
+ const USER_CUSTOMIZATION_MAX_CHARS = 1e3;
23
+ /** Saved customization text. An empty string means none. */
24
+ const userCustomizationTextSchema = z.string().trim().max(USER_CUSTOMIZATION_MAX_CHARS);
25
+ /** Request and response body for the viewer's customization. */
26
+ const userCustomizationSchema = z.object({ customization: userCustomizationTextSchema }).strict();
27
+ // src/chat/agent-invocations/result-event-type.ts
28
+ /** Event namespace of the messages between a parent and its child agents. */
29
+ const AGENT_INVOCATION_EVENT_NAMESPACE = "junior";
30
+ const AGENT_INVOCATION_RESULT_EVENT_TYPE_PREFIX = "agent_invocation.";
31
+ /** Build the Event type of the parent message for one agent invocation result. */
32
+ function agentInvocationResultEventType(status) {
33
+ return `${AGENT_INVOCATION_RESULT_EVENT_TYPE_PREFIX}${status}`;
34
+ }
35
+ /** True when an Event type names an agent invocation result. */
36
+ function isAgentInvocationResultEventType(eventType) {
37
+ return eventType.startsWith(AGENT_INVOCATION_RESULT_EVENT_TYPE_PREFIX);
38
+ }
39
+ /** Event type of the `reply` that ends a child agent's Turn. */
40
+ const AGENT_REPLY_EVENT_TYPE = "agent.reply";
41
+ /** Event type of a message that a child agent sends to its parent. */
42
+ const AGENT_MESSAGE_EVENT_TYPE = "agent.message";
43
+ // src/chat/agent-invocations/statuses.ts
44
+ const AGENT_INVOCATION_STATUSES = [
45
+ "pending",
46
+ "running",
47
+ "paused",
48
+ "blocked",
49
+ "completed",
50
+ "failed",
51
+ "stopped"
52
+ ];
53
+ const AGENT_INVOCATION_MAILBOX_STATUSES = ["pending", "appended"];
54
+ /**
55
+ * Parent mailbox append state. Only terminal invocations have a value.
56
+ * `replaced` means the child still had open work, so a later agent invocation
57
+ * on the same child sends the result instead. `skipped` means a stop ended
58
+ * the work, so the result is never used. `steered` means the agent invocation
59
+ * that was running read the input as a steering message, so its result covers
60
+ * this one.
61
+ */
62
+ const AGENT_INVOCATION_PARENT_MAILBOX_STATUSES = [
63
+ "pending",
64
+ "appended",
65
+ "replaced",
66
+ "skipped",
67
+ "steered"
68
+ ];
69
+ export { AGENT_MESSAGE_EVENT_TYPE as a, isAgentInvocationResultEventType as c, userCustomizationTextSchema as d, OPEN_TODO_STATUSES as f, isOpenTodoStatus as g, UPDATE_TODOS_TOOL_NAME as h, AGENT_INVOCATION_EVENT_NAMESPACE as i, USER_CUSTOMIZATION_MAX_CHARS as l, TODO_STATUSES as m, AGENT_INVOCATION_PARENT_MAILBOX_STATUSES as n, AGENT_REPLY_EVENT_TYPE as o, SELF_TODO_ASSIGNEE as p, AGENT_INVOCATION_STATUSES as r, agentInvocationResultEventType as s, AGENT_INVOCATION_MAILBOX_STATUSES as t, userCustomizationSchema as u };
@@ -0,0 +1,492 @@
1
+ import { B as juniorAttachments, H as juniorConversations, V as juniorMessageAttachments } from "./executor-CgWyWfYz.js";
2
+ import { In as touchConversationDetail, Pn as conversationDetailTouch } from "./db-PwSRzWWn.js";
3
+ import { t as mapBounded } from "./fan-out-Cod-yEHG.js";
4
+ import { ht as bufferBody } from "./config-CWbwKj0j.js";
5
+ import { createHash, randomUUID } from "node:crypto";
6
+ import { and, asc, eq, inArray, isNotNull, isNull, lte, notExists, or } from "drizzle-orm";
7
+ // src/chat/attachments/source.ts
8
+ /** The source deleted the file, or Junior can no longer read it. */
9
+ var AttachmentSourceUnavailableError = class extends Error {
10
+ constructor(message, options) {
11
+ super(message, options);
12
+ this.name = "AttachmentSourceUnavailableError";
13
+ }
14
+ };
15
+ // src/chat/attachments/store.ts
16
+ const DAY_MS = 864e5;
17
+ const ATTACHMENT_GC_BATCH_LIMIT = 200;
18
+ /** Time that Junior keeps attachment bytes after the file is stored. */
19
+ const ATTACHMENT_RETENTION_MS = 30 * DAY_MS;
20
+ /** Only `file` rows: a `url` row has no storage or file fields. */
21
+ const isFileAttachment = eq(juniorAttachments.kind, "file");
22
+ /**
23
+ * The storage and file fields of a `file` row. Every `file` row has them, so
24
+ * a missing one is a broken row.
25
+ */
26
+ function fileFields(row) {
27
+ const { bytes, contentType, storageProvider, title } = row;
28
+ if (bytes === null || contentType === null || storageProvider === null || title === null) throw new Error(`Attachment ${row.id} has no file fields`);
29
+ return {
30
+ bytes,
31
+ contentType,
32
+ filename: title,
33
+ storageProvider
34
+ };
35
+ }
36
+ function attachmentIdentity(file) {
37
+ if ("data" in file) return file.source ?? { sha256: createHash("sha256").update(file.data).digest("hex") };
38
+ return file.source;
39
+ }
40
+ /** Stable conversation-owned id for one file and its presentation metadata. */
41
+ function attachmentId(args) {
42
+ const identity = "sha256" in args.identity ? [
43
+ args.conversationId,
44
+ args.storageProvider,
45
+ args.identity.sha256,
46
+ args.filename,
47
+ args.contentType
48
+ ] : [
49
+ args.conversationId,
50
+ args.storageProvider,
51
+ args.filename,
52
+ args.contentType,
53
+ args.identity.provider,
54
+ args.identity.id
55
+ ];
56
+ return createHash("sha256").update(identity.join("\0")).digest("hex");
57
+ }
58
+ /**
59
+ * Object key for one write attempt.
60
+ *
61
+ * Attachment ids are content-stable. Object keys are not: each put gets a fresh
62
+ * key so a failed-write cleanup or GC delete cannot remove another writer's
63
+ * durable blob.
64
+ */
65
+ function attachmentKey(args) {
66
+ return `conversations/${args.conversationId}/attachments/${args.attachmentId}/${args.writeId}/${args.filename}`;
67
+ }
68
+ /** A source whose bytes do not match its declared size. A retry cannot fix it. */
69
+ var AttachmentSizeError = class extends Error {
70
+ constructor(bytes, expected, options) {
71
+ super(`Attachment body does not match its declared ${expected} bytes (read ${bytes})`, options);
72
+ this.name = "AttachmentSizeError";
73
+ }
74
+ };
75
+ /** Tries for one object write, each with a freshly opened body. */
76
+ const WRITE_ATTEMPTS = 3;
77
+ async function bestEffortDelete(storage, key) {
78
+ if (key === null) return;
79
+ try {
80
+ await storage.delete([key]);
81
+ } catch {}
82
+ }
83
+ /**
84
+ * Stream one file to a fresh key, and return its size and digest.
85
+ *
86
+ * The digest is taken while the bytes stream, so the body is never held
87
+ * whole. A body that does not match its declared size is not kept.
88
+ */
89
+ async function writeAttachmentObject(args) {
90
+ for (let attempt = 1;; attempt += 1) try {
91
+ return await writeAttachmentObjectOnce(args);
92
+ } catch (error) {
93
+ if (error instanceof AttachmentSizeError || error instanceof AttachmentSourceUnavailableError || attempt >= WRITE_ATTEMPTS) {
94
+ await bestEffortDelete(args.storage, args.key);
95
+ throw error;
96
+ }
97
+ }
98
+ }
99
+ async function writeAttachmentObjectOnce(args) {
100
+ const { file } = args;
101
+ const expected = "data" in file ? file.data.byteLength : file.bytes;
102
+ const source = "data" in file ? bufferBody(file.data) : await file.open();
103
+ const hash = createHash("sha256");
104
+ let bytes = 0;
105
+ const body = source.pipeThrough(new TransformStream({ transform(chunk, controller) {
106
+ bytes += chunk.byteLength;
107
+ if (bytes > expected) throw new AttachmentSizeError(bytes, expected);
108
+ hash.update(chunk);
109
+ controller.enqueue(chunk);
110
+ } }));
111
+ try {
112
+ await args.storage.put({
113
+ body,
114
+ bytes: expected,
115
+ contentType: file.mimeType,
116
+ key: args.key
117
+ });
118
+ } catch (error) {
119
+ if (bytes > expected) throw new AttachmentSizeError(bytes, expected, { cause: error });
120
+ throw error;
121
+ }
122
+ if (bytes !== expected) throw new AttachmentSizeError(bytes, expected);
123
+ return {
124
+ bytes,
125
+ sha256: hash.digest("hex")
126
+ };
127
+ }
128
+ async function isConversationPurged(db, conversationId) {
129
+ const [row] = await db.db().select({ transcriptPurgedAt: juniorConversations.transcriptPurgedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId));
130
+ return row?.transcriptPurgedAt != null;
131
+ }
132
+ function purgedConversationError(conversationId) {
133
+ return /* @__PURE__ */ new Error(`Cannot store attachment for purged conversation ${conversationId}`);
134
+ }
135
+ async function assertConversationNotPurged(db, conversationId) {
136
+ if (await isConversationPurged(db, conversationId)) throw purgedConversationError(conversationId);
137
+ }
138
+ /** Mark a just-written row for deletion and drop its unused object. */
139
+ async function rejectPurgedAttachmentWrite(args) {
140
+ const db = args.db.db();
141
+ await db.with(conversationDetailTouch(db, [args.conversationId])).update(juniorAttachments).set({ deleteRequestedAt: args.now }).where(eq(juniorAttachments.id, args.id));
142
+ await bestEffortDelete(args.storage, args.storageKey);
143
+ throw purgedConversationError(args.conversationId);
144
+ }
145
+ /**
146
+ * Return another writer's live row only when the conversation is still active.
147
+ *
148
+ * The caller already wrote a unique object for this attempt. Delete that unused
149
+ * object either way. If the conversation is purged, do not report success for a
150
+ * row that purge/GC is about to remove.
151
+ */
152
+ async function reuseLiveAttachment(args) {
153
+ await bestEffortDelete(args.storage, args.storageKey);
154
+ await assertConversationNotPurged(args.db, args.conversationId);
155
+ return { id: args.id };
156
+ }
157
+ /**
158
+ * Persist one conversation-owned file.
159
+ *
160
+ * Identity is stable under the conversation: it comes from the file's source
161
+ * when it has one, and from its digest otherwise. Object storage is written
162
+ * first under a unique key; the SQL row is created only after that write
163
+ * succeeds. A row means the attachment is durable. Retries reuse an existing
164
+ * live row. A purge-marked row is revived by writing a new object and pointing
165
+ * the row at it, unless the conversation is still purged. If the SQL write
166
+ * fails after object storage accepts the bytes, this path deletes that unique
167
+ * object. A process crash between those steps can leave an unreferenced unique
168
+ * object with no SQL row.
169
+ */
170
+ async function storeAttachment(args) {
171
+ const now = new Date(args.nowMs ?? Date.now());
172
+ const identity = attachmentIdentity(args.file);
173
+ const source = args.file.source;
174
+ const id = attachmentId({
175
+ conversationId: args.conversationId,
176
+ contentType: args.file.mimeType,
177
+ filename: args.file.filename,
178
+ identity,
179
+ storageProvider: args.storage.provider
180
+ });
181
+ const [existing] = await args.db.db().select({
182
+ contentType: juniorAttachments.contentType,
183
+ conversationId: juniorAttachments.conversationId,
184
+ deleteRequestedAt: juniorAttachments.deleteRequestedAt,
185
+ filename: juniorAttachments.title,
186
+ id: juniorAttachments.id,
187
+ provider: juniorAttachments.provider,
188
+ providerId: juniorAttachments.providerId,
189
+ storageProvider: juniorAttachments.storageProvider,
190
+ sha256: juniorAttachments.sha256,
191
+ storageKey: juniorAttachments.storageKey
192
+ }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
193
+ if (existing) {
194
+ 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}`);
195
+ if (existing.deleteRequestedAt === null) {
196
+ await assertConversationNotPurged(args.db, args.conversationId);
197
+ return { id: existing.id };
198
+ }
199
+ }
200
+ await assertConversationNotPurged(args.db, args.conversationId);
201
+ const { file } = args;
202
+ let storageKey = null;
203
+ let written;
204
+ if ("deferred" in file) written = {
205
+ bytes: file.bytes,
206
+ sha256: null
207
+ };
208
+ else {
209
+ storageKey = attachmentKey({
210
+ attachmentId: id,
211
+ conversationId: args.conversationId,
212
+ filename: file.filename,
213
+ writeId: randomUUID()
214
+ });
215
+ written = await writeAttachmentObject({
216
+ file,
217
+ key: storageKey,
218
+ storage: args.storage
219
+ });
220
+ }
221
+ if (existing?.deleteRequestedAt != null) {
222
+ if (await isConversationPurged(args.db, args.conversationId)) {
223
+ await bestEffortDelete(args.storage, storageKey);
224
+ throw purgedConversationError(args.conversationId);
225
+ }
226
+ const oldStorageKey = existing.storageKey;
227
+ if ((await args.db.db().with(conversationDetailTouch(args.db.db(), [args.conversationId])).update(juniorAttachments).set({
228
+ ...written,
229
+ deleteRequestedAt: null,
230
+ storageKey
231
+ }).where(and(eq(juniorAttachments.id, id), isNotNull(juniorAttachments.deleteRequestedAt))).returning({ id: juniorAttachments.id })).length > 0) {
232
+ if (await isConversationPurged(args.db, args.conversationId)) await rejectPurgedAttachmentWrite({
233
+ conversationId: args.conversationId,
234
+ db: args.db,
235
+ id,
236
+ now,
237
+ storage: args.storage,
238
+ storageKey
239
+ });
240
+ if (oldStorageKey !== storageKey) await bestEffortDelete(args.storage, oldStorageKey);
241
+ return { id };
242
+ }
243
+ const [afterRace] = await args.db.db().select({
244
+ deleteRequestedAt: juniorAttachments.deleteRequestedAt,
245
+ id: juniorAttachments.id,
246
+ storageKey: juniorAttachments.storageKey
247
+ }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
248
+ if (afterRace?.deleteRequestedAt === null) return reuseLiveAttachment({
249
+ conversationId: args.conversationId,
250
+ db: args.db,
251
+ id: afterRace.id,
252
+ storage: args.storage,
253
+ storageKey
254
+ });
255
+ }
256
+ let inserted = [];
257
+ try {
258
+ inserted = await args.db.db().with(conversationDetailTouch(args.db.db(), [args.conversationId])).insert(juniorAttachments).values({
259
+ id,
260
+ conversationId: args.conversationId,
261
+ storageProvider: args.storage.provider,
262
+ storageKey,
263
+ provider: source?.provider,
264
+ providerId: source?.id,
265
+ title: args.file.filename,
266
+ contentType: args.file.mimeType,
267
+ ...written,
268
+ createdAt: now
269
+ }).onConflictDoNothing({ target: juniorAttachments.id }).returning({ id: juniorAttachments.id });
270
+ } catch (error) {
271
+ await bestEffortDelete(args.storage, storageKey);
272
+ throw error;
273
+ }
274
+ if (inserted.length > 0) {
275
+ if (await isConversationPurged(args.db, args.conversationId)) await rejectPurgedAttachmentWrite({
276
+ conversationId: args.conversationId,
277
+ db: args.db,
278
+ id,
279
+ now,
280
+ storage: args.storage,
281
+ storageKey
282
+ });
283
+ return { id };
284
+ }
285
+ const [row] = await args.db.db().select({
286
+ deleteRequestedAt: juniorAttachments.deleteRequestedAt,
287
+ id: juniorAttachments.id,
288
+ storageKey: juniorAttachments.storageKey
289
+ }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
290
+ if (!row) {
291
+ await bestEffortDelete(args.storage, storageKey);
292
+ throw new Error(`Attachment row missing after write for ${id}`);
293
+ }
294
+ if (row.deleteRequestedAt === null) return reuseLiveAttachment({
295
+ conversationId: args.conversationId,
296
+ db: args.db,
297
+ id: row.id,
298
+ storage: args.storage,
299
+ storageKey
300
+ });
301
+ if (await isConversationPurged(args.db, args.conversationId)) {
302
+ await bestEffortDelete(args.storage, storageKey);
303
+ throw purgedConversationError(args.conversationId);
304
+ }
305
+ if ((await args.db.db().with(conversationDetailTouch(args.db.db(), [args.conversationId])).update(juniorAttachments).set({
306
+ ...written,
307
+ deleteRequestedAt: null,
308
+ storageKey
309
+ }).where(and(eq(juniorAttachments.id, id), isNotNull(juniorAttachments.deleteRequestedAt))).returning({ id: juniorAttachments.id })).length > 0) {
310
+ if (await isConversationPurged(args.db, args.conversationId)) await rejectPurgedAttachmentWrite({
311
+ conversationId: args.conversationId,
312
+ db: args.db,
313
+ id,
314
+ now,
315
+ storage: args.storage,
316
+ storageKey
317
+ });
318
+ if (row.storageKey !== storageKey) await bestEffortDelete(args.storage, row.storageKey);
319
+ return { id };
320
+ }
321
+ const [afterRace] = await args.db.db().select({
322
+ deleteRequestedAt: juniorAttachments.deleteRequestedAt,
323
+ id: juniorAttachments.id
324
+ }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
325
+ if (afterRace?.deleteRequestedAt === null) return reuseLiveAttachment({
326
+ conversationId: args.conversationId,
327
+ db: args.db,
328
+ id: afterRace.id,
329
+ storage: args.storage,
330
+ storageKey
331
+ });
332
+ await bestEffortDelete(args.storage, storageKey);
333
+ throw new Error(`Attachment ${id} disappeared while reviving`);
334
+ }
335
+ /**
336
+ * Record an object that a browser already wrote, under the upload's id.
337
+ *
338
+ * The row takes over the object key. A retry with the same id keeps the
339
+ * first row. The caller checked the object's size, type, and digest.
340
+ */
341
+ async function recordUploadedAttachment(args) {
342
+ const { attachment } = args;
343
+ const now = new Date(args.nowMs);
344
+ await assertConversationNotPurged(args.db, attachment.conversationId);
345
+ if ((await args.db.db().with(conversationDetailTouch(args.db.db(), [attachment.conversationId])).insert(juniorAttachments).values({
346
+ bytes: attachment.bytes,
347
+ contentType: attachment.contentType,
348
+ conversationId: attachment.conversationId,
349
+ createdAt: now,
350
+ id: attachment.id,
351
+ sha256: attachment.sha256,
352
+ storageKey: attachment.storageKey,
353
+ storageProvider: args.storage.provider,
354
+ title: attachment.filename
355
+ }).onConflictDoNothing({ target: juniorAttachments.id }).returning({ id: juniorAttachments.id })).length > 0 && await isConversationPurged(args.db, attachment.conversationId)) await rejectPurgedAttachmentWrite({
356
+ conversationId: attachment.conversationId,
357
+ db: args.db,
358
+ id: attachment.id,
359
+ now,
360
+ storage: args.storage,
361
+ storageKey: attachment.storageKey
362
+ });
363
+ }
364
+ /**
365
+ * Store a file that Junior recorded without its bytes, on its first read.
366
+ *
367
+ * The bytes stream from the source to a fresh key. The row then takes that
368
+ * key only while it is still unstored, live, and in a conversation that is
369
+ * not purged. Purge marks rows in the transaction that purges the
370
+ * conversation, so this update cannot revive a purged row. When the update
371
+ * misses, the new object is deleted: return the row that another writer
372
+ * stored, or null when the row is no longer live.
373
+ */
374
+ async function storeDeferredAttachment(args) {
375
+ const { attachment, storage } = args;
376
+ const storageKey = attachmentKey({
377
+ attachmentId: attachment.id,
378
+ conversationId: attachment.conversationId,
379
+ filename: attachment.filename,
380
+ writeId: randomUUID()
381
+ });
382
+ const written = await writeAttachmentObject({
383
+ file: {
384
+ bytes: args.file.bytes,
385
+ filename: attachment.filename,
386
+ mimeType: attachment.contentType,
387
+ open: args.file.open,
388
+ source: attachment.source
389
+ },
390
+ key: storageKey,
391
+ storage
392
+ });
393
+ const db = args.db.db();
394
+ if ((await db.with(conversationDetailTouch(db, [attachment.conversationId])).update(juniorAttachments).set({
395
+ ...written,
396
+ storageKey
397
+ }).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 {
398
+ ...attachment,
399
+ bytes: written.bytes,
400
+ storageKey
401
+ };
402
+ await bestEffortDelete(storage, storageKey);
403
+ const current = await readLiveAttachment({
404
+ attachmentId: attachment.id,
405
+ conversationId: attachment.conversationId,
406
+ db: args.db
407
+ });
408
+ return current?.storageKey ? {
409
+ ...current,
410
+ storageKey: current.storageKey
411
+ } : null;
412
+ }
413
+ /** Load one live attachment owned by a conversation. */
414
+ async function readLiveAttachment(args) {
415
+ const [row] = await args.db.db().select({
416
+ bytes: juniorAttachments.bytes,
417
+ contentType: juniorAttachments.contentType,
418
+ conversationId: juniorAttachments.conversationId,
419
+ deleteRequestedAt: juniorAttachments.deleteRequestedAt,
420
+ id: juniorAttachments.id,
421
+ provider: juniorAttachments.provider,
422
+ providerId: juniorAttachments.providerId,
423
+ storageProvider: juniorAttachments.storageProvider,
424
+ storageKey: juniorAttachments.storageKey,
425
+ title: juniorAttachments.title
426
+ }).from(juniorAttachments).where(and(eq(juniorAttachments.id, args.attachmentId), isFileAttachment, eq(juniorAttachments.conversationId, args.conversationId), isNull(juniorAttachments.deleteRequestedAt)));
427
+ if (!row) return null;
428
+ if (await isConversationPurged(args.db, args.conversationId)) return null;
429
+ return {
430
+ ...fileFields(row),
431
+ conversationId: row.conversationId,
432
+ id: row.id,
433
+ source: row.provider && row.providerId ? {
434
+ id: row.providerId,
435
+ provider: row.provider
436
+ } : null,
437
+ storageKey: row.storageKey
438
+ };
439
+ }
440
+ /** Persist many conversation-owned files. */
441
+ async function storeAttachments(args) {
442
+ return await mapBounded(args.files, (file) => storeAttachment({
443
+ conversationId: args.conversationId,
444
+ db: args.db,
445
+ file: {
446
+ data: file.data,
447
+ filename: file.filename,
448
+ mimeType: file.mimeType
449
+ },
450
+ ...args.nowMs !== void 0 ? { nowMs: args.nowMs } : void 0,
451
+ storage: args.storage
452
+ }));
453
+ }
454
+ /** Mark attachments unavailable when their conversation content is purged. */
455
+ async function requestAttachmentDeletion(db, conversationIds, nowMs) {
456
+ if (conversationIds.length === 0) return;
457
+ await db.db().with(conversationDetailTouch(db.db(), conversationIds)).update(juniorAttachments).set({ deleteRequestedAt: new Date(nowMs) }).where(and(inArray(juniorAttachments.conversationId, conversationIds), isNull(juniorAttachments.deleteRequestedAt)));
458
+ }
459
+ /**
460
+ * Delete purged attachments in one bounded batch.
461
+ *
462
+ * Eligible files are 30 days old, explicitly purge-marked, or owned by a
463
+ * conversation whose transcript is already purged. A `url` row has no bytes,
464
+ * so it lives as long as its message: it is eligible only when purge-marked
465
+ * or purged. Delete object keys first, then remove rows that are still
466
+ * eligible so a failed blob delete remains retryable.
467
+ */
468
+ async function collectAttachmentGarbage(args) {
469
+ const expiresBefore = /* @__PURE__ */ new Date(args.nowMs - ATTACHMENT_RETENTION_MS);
470
+ const purged = or(isNotNull(juniorAttachments.deleteRequestedAt), isNotNull(juniorConversations.transcriptPurgedAt));
471
+ const eligible = or(lte(juniorAttachments.createdAt, expiresBefore), purged);
472
+ const isUrl = eq(juniorAttachments.kind, "url");
473
+ const rows = await args.db.db().select({
474
+ id: juniorAttachments.id,
475
+ storageKey: juniorAttachments.storageKey
476
+ }).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);
477
+ if (rows.length === 0) return { deleted: 0 };
478
+ const keys = rows.flatMap((row) => row.storageKey ? [row.storageKey] : []);
479
+ if (keys.length > 0) await args.storage.delete(keys);
480
+ 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))));
481
+ if (stillEligible.length === 0) return { deleted: 0 };
482
+ const removed = await args.db.db().delete(juniorAttachments).where(inArray(juniorAttachments.id, stillEligible.map((row) => row.id))).returning({
483
+ conversationId: juniorAttachments.conversationId,
484
+ id: juniorAttachments.id,
485
+ kind: juniorAttachments.kind
486
+ });
487
+ const urls = removed.filter((row) => row.kind === "url");
488
+ 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))));
489
+ await touchConversationDetail(args.db.db(), removed.map((row) => row.conversationId));
490
+ return { deleted: removed.length };
491
+ }
492
+ export { recordUploadedAttachment as a, storeAttachments as c, readLiveAttachment as i, storeDeferredAttachment as l, fileFields as n, requestAttachmentDeletion as o, isFileAttachment as r, storeAttachment as s, collectAttachmentGarbage as t, AttachmentSourceUnavailableError as u };
@@ -0,0 +1,90 @@
1
+ import { h as logWarn } from "./logging-DNt-qOIO.js";
2
+ import { u as queueCallback } from "./background-compaction-queue-iZXadLV3.js";
3
+ import { c as QUEUE_SIGNATURE_MAX_AGE_MS, d as getQueueProvider, l as signQueueMessage, u as verifyQueueMessage } from "./vercel-queue-q4z8w5QO.js";
4
+ import * as z from "zod";
5
+ import { createHash } from "node:crypto";
6
+ // src/chat/plugins/task-queue.ts
7
+ /**
8
+ * Delivery for plugin-registered tasks.
9
+ *
10
+ * Plugins register named tasks. This module owns the shared signed message,
11
+ * send path, and HTTP/local callback. Core keeps one topic and one runner.
12
+ */
13
+ /** Deploy topic name. Keep stable for Vercel queue wiring. */
14
+ const PLUGIN_TASK_QUEUE_TOPIC = "junior_plugin_tasks";
15
+ const PLUGIN_TASK_DEV_CONSUMER_GROUP = "junior_plugin_tasks_dev";
16
+ const PLUGIN_TASK_MAX_DELIVERIES = 5;
17
+ const PLUGIN_TASK_SIGN_CONTEXT = "junior.plugin_task_queue.v1";
18
+ const PLUGIN_TASK_SIGN_VERSION = "v1";
19
+ const pluginTaskParamsSchema = z.object({
20
+ conversationId: z.string().min(1),
21
+ sessionId: z.string().min(1)
22
+ }).strict();
23
+ const pluginTaskSign = {
24
+ context: PLUGIN_TASK_SIGN_CONTEXT,
25
+ schema: z.object({
26
+ name: z.string().min(1),
27
+ params: pluginTaskParamsSchema,
28
+ plugin: z.string().min(1)
29
+ }).strict(),
30
+ signatureVersion: PLUGIN_TASK_SIGN_VERSION,
31
+ parts: (message) => [
32
+ message.plugin,
33
+ message.name,
34
+ message.params.conversationId,
35
+ message.params.sessionId
36
+ ]
37
+ };
38
+ /** Build the stable id used for delivery dedupe and tracing. */
39
+ function pluginTaskId(args) {
40
+ return `plugin-task_${createHash("sha256").update(args.plugin).update("\0").update(args.name).update("\0").update(args.params.conversationId).update("\0").update(args.params.sessionId).digest("hex").slice(0, 32)}`;
41
+ }
42
+ /** Sign a plugin task message for tests and local checks. */
43
+ function signPluginTaskQueueMessage(message, nowMs = Date.now()) {
44
+ return signQueueMessage(pluginTaskSign, message, nowMs);
45
+ }
46
+ function verifyPluginTaskQueueMessage(value, nowMs = Date.now()) {
47
+ return verifyQueueMessage(pluginTaskSign, value, nowMs);
48
+ }
49
+ function logPluginTaskQueueMessageRejected(reason, metadata) {
50
+ logWarn("plugin.task.queue_message.rejected", {
51
+ "app.queue.consumer_group": metadata.consumerGroup,
52
+ "app.queue.delivery_count": metadata.deliveryCount,
53
+ "app.queue.message_id": metadata.messageId,
54
+ "app.queue.reject_reason": reason,
55
+ "app.queue.topic_name": metadata.topicName
56
+ });
57
+ }
58
+ function pluginTaskCallback() {
59
+ return queueCallback({
60
+ consumerGroup: PLUGIN_TASK_DEV_CONSUMER_GROUP,
61
+ maxDeliveries: PLUGIN_TASK_MAX_DELIVERIES,
62
+ onRejected: logPluginTaskQueueMessageRejected,
63
+ run: async (message) => {
64
+ const { processPluginTask } = await import("./task-runner--Ke8KSMf.js").then((n) => n.r);
65
+ await processPluginTask(message);
66
+ },
67
+ topic: PLUGIN_TASK_QUEUE_TOPIC,
68
+ verify: verifyPluginTaskQueueMessage
69
+ });
70
+ }
71
+ /** Send one plugin task through the shared signed delivery path. */
72
+ async function sendVercelPluginTask(message) {
73
+ await getQueueProvider().send(PLUGIN_TASK_QUEUE_TOPIC, signPluginTaskQueueMessage(message), {
74
+ idempotencyKey: pluginTaskId(message),
75
+ retentionSeconds: QUEUE_SIGNATURE_MAX_AGE_MS / 1e3
76
+ });
77
+ }
78
+ /** Create the HTTP callback for plugin tasks. */
79
+ function createVercelPluginTaskCallback() {
80
+ return pluginTaskCallback().create();
81
+ }
82
+ /** Return the queue consumer for plugin tasks, for a pulling queue worker. */
83
+ function pluginTaskQueueConsumer() {
84
+ return pluginTaskCallback().consumer;
85
+ }
86
+ /** Register the local-dev consumer for plugin tasks. */
87
+ function registerVercelPluginTaskDevConsumer() {
88
+ return pluginTaskCallback().registerDev();
89
+ }
90
+ export { pluginTaskQueueConsumer as a, pluginTaskParamsSchema as i, createVercelPluginTaskCallback as n, registerVercelPluginTaskDevConsumer as o, pluginTaskId as r, sendVercelPluginTask as s, PLUGIN_TASK_QUEUE_TOPIC as t };