@sentry/junior 0.315.0 → 0.317.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 (139) hide show
  1. package/dist/{admin-5jUYY46p.js → admin-CAugg87B.js} +1 -1
  2. package/dist/{agent-runner-C7GNLRB6.js → agent-runner-AjrEV6Qe.js} +13532 -12811
  3. package/dist/{reporting-window-C4dbzDiR.js → agent-status-BA5x3Xtp.js} +33 -1
  4. package/dist/{agent-update-delivery-BNEYQsAf.js → agent-update-delivery-B_YIZcgf.js} +10 -37
  5. package/dist/api/schema.d.ts +609 -104
  6. package/dist/api/schema.js +6 -6
  7. package/dist/api.js +373 -469
  8. package/dist/{app-D_bAXRDe.d.ts → app-MoNAsVV5.d.ts} +52 -28
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +177 -132
  11. package/dist/catalog-runtime-DfSpJZdY.js +6 -0
  12. package/dist/{change-record-Bqsa5ZXE.d.ts → change-record-BzJgLsv7.d.ts} +60 -1
  13. package/dist/{adapter-context-BlSGE44V.js → channel-access-j-YAVYK4.js} +2 -42
  14. package/dist/{chat-core-engine-CxkwRpn9.js → chat-core-engine-aH85nEHv.js} +4 -3
  15. package/dist/{child-message--2G3Ft26.js → child-message-DHjQLEd1.js} +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.js +5 -4
  20. package/dist/cli/snapshot-create.js +5 -2
  21. package/dist/cli/upgrade.js +27 -5
  22. package/dist/config-CHQ8X251.js +2422 -0
  23. package/dist/{continue-in-slack-BGKjIdFp.js → continue-in-slack-D-FZ8Fin.js} +2 -3
  24. package/dist/{conversation-feed-Sl8lKKmR.js → conversation-feed--9S0_PXL.js} +9 -4
  25. package/dist/{proxy-path-Dc-0jXGi.js → conversation-privacy-B1uXn5sf.js} +2 -16
  26. package/dist/{conversation-turn-BoLK9i6g.js → conversation-turn-BUE_7xaN.js} +102 -172
  27. package/dist/{create-BOycVH9h.js → create-DoDIYgtZ.js} +12 -10
  28. package/dist/{credential-sync-Mn4OdkEh.js → credential-sync-BJOqGnjV.js} +17 -12
  29. package/dist/{db-DXTOYRzR.js → db-BFmyYZtJ.js} +20276 -27398
  30. package/dist/{deployment-CG3TchWh.js → deployment-DXq9ZLU4.js} +17 -15
  31. package/dist/{engine-context-dyWlfNdD.js → engine-context-CgQ7mlHt.js} +264 -50
  32. package/dist/{html-CfXEwl_h.js → html-B3VKTGbJ.js} +6 -2
  33. package/dist/instrumentation.js +15 -7
  34. package/dist/{job-runner-CySgpi9v.js → job-runner-A1lCkybD.js} +397 -22
  35. package/dist/{lineage-tRTOcrsL.js → lineage-Bktb0UcV.js} +1 -1
  36. package/dist/{list-DXBz8SYL.js → list-Bxvg5wXf.js} +260 -698
  37. package/dist/{logging-czs0nqLC.js → logging--smS7XRK.js} +2 -2
  38. package/dist/{mailbox-turn-79Nv1JXv.js → mailbox-turn-uSXhUFc9.js} +648 -2957
  39. package/dist/{message-BTox2Cmb.js → message-BNenhsmB.js} +12 -22
  40. package/dist/{model-input-IRGa98V7.js → model-input-BReSnwHp.js} +3 -3
  41. package/dist/nitro.d.ts +1 -1
  42. package/dist/nitro.js +20 -6
  43. package/dist/{oauth-callback-server-NXK7AlBp.js → oauth-callback-server-CE4soEIY.js} +2 -2
  44. package/dist/{oauth-relay-6NBPSpFE.js → oauth-relay-C36gX1gH.js} +2 -2
  45. package/dist/{package-discovery-BI6T_RkD.js → package-discovery-DD9vencX.js} +1 -50
  46. package/dist/{parent-result-Dg6P6roR.js → parent-result-Ck1rFYRQ.js} +93 -106
  47. package/dist/{plugins-BXMdNdyA.js → plugins-D_Ru4CWc.js} +1 -1
  48. package/dist/profile-BQ-iBDsZ.js +4657 -0
  49. package/dist/{transcript-BHhJVY0P.js → prompt-Dv7gkpD6.js} +97 -103
  50. package/dist/proxy-path-BHYoKZdq.js +15 -0
  51. package/dist/registry-iXMT5Jmh.js +3279 -0
  52. package/dist/reports-WKHfGTsU.js +195 -0
  53. package/dist/{resolve-BUFkmxkT.js → resolve-tony4ibz.js} +9 -29
  54. package/dist/{result-DfATzX77.js → result-Bta_dlWa.js} +42 -117
  55. package/dist/run-conversation-DL6ru7iW.js +336 -0
  56. package/dist/{runner-CmKP3inb.js → runner-BstDRbD9.js} +7 -7
  57. package/dist/{sandbox-egress-signals-DYo5BsM7.js → sandbox-egress-signals-oSJMJOnn.js} +1 -1
  58. package/dist/{schema-DrBMdPmv.js → schema-DfqrHACA.js} +67 -84
  59. package/dist/sender-actors-CPglLd5R.js +83 -0
  60. package/dist/{service-account-CxTX7nnR.js → service-account-CTV_jaNu.js} +3 -1
  61. package/dist/{skills-BlHUDj7k.js → skills-BCEU41zM.js} +4 -4
  62. package/dist/{slack-conversation-unfurl-Dhe3lB1U.js → slack-conversation-unfurl-DxVmhbGP.js} +7 -6
  63. package/dist/{spawn-CfvlFdfz.js → spawn-frczVPIr.js} +11 -8
  64. package/dist/{system-prompt-table-CDCYVwqN.js → system-prompt-table-CiXy0eNR.js} +91 -70
  65. package/dist/{task-runner-DcdQJd9e.js → task-runner-C9Yc2_ae.js} +35 -49
  66. package/dist/{thread-context-DF5uDcWN.js → thread-context-CqZDKErp.js} +6 -6
  67. package/dist/topics-SRN7IVX-.js +24 -0
  68. package/dist/turn-membership-CENFf3kI.js +856 -0
  69. package/dist/{turn-wake-um5Ubd4m.js → turn-wake-BhloiI2h.js} +4 -5
  70. package/dist/{media-Cr9pGkzr.js → types-C4iC-IMC.js} +819 -777
  71. package/dist/user-customization-CvfuY9Eo.js +93 -0
  72. package/dist/users-ByG5RCEJ.js +181 -0
  73. package/dist/{validation-CJyuOPD2.js → validation-8gjfR91V.js} +1 -1
  74. package/dist/{version-Bhe7RPIe.js → version-BeZhWWBE.js} +1 -1
  75. package/dist/version.js +1 -1
  76. package/dist/{worker-D8PRgUqr.js → worker-BqMQQNRk.js} +5 -4
  77. package/migrations/20261125171254_conversation_visibility/migration.sql +4 -0
  78. package/migrations/20261125171254_conversation_visibility/snapshot.json +67 -0
  79. package/migrations/20261125171257_conversation_visibility_backfill/migration.sql +25 -0
  80. package/migrations/20261125171257_conversation_visibility_backfill/snapshot.json +9 -0
  81. package/migrations/20261125213232_drop_versions_notify/migration.sql +19 -0
  82. package/migrations/20261125213232_drop_versions_notify/snapshot.json +9 -0
  83. package/migrations/20261125225138_conversation_kind_root_thread/migration.sql +23 -0
  84. package/migrations/20261125225138_conversation_kind_root_thread/snapshot.json +55 -0
  85. package/migrations/20261125225142_conversation_kind_root_thread_backfill/migration.sql +7 -0
  86. package/migrations/20261125225142_conversation_kind_root_thread_backfill/snapshot.json +9 -0
  87. package/migrations/20261126000151_conversation_event_message_role_seq_index/migration.sql +1 -0
  88. package/migrations/20261126000151_conversation_event_message_role_seq_index/snapshot.json +69 -0
  89. package/migrations/20261126012917_merge_leaves/migration.sql +2 -0
  90. package/migrations/20261126012917_merge_leaves/snapshot.json +12 -0
  91. package/migrations/20261126025226_drop_agent_invocations/migration.sql +6 -0
  92. package/migrations/20261126025226_drop_agent_invocations/snapshot.json +9 -0
  93. package/migrations/20261126033000_space_conversations_lead_children/migration.sql +155 -0
  94. package/migrations/20261126033000_space_conversations_lead_children/snapshot.json +9 -0
  95. package/migrations/20261126144620_drop_user_message_time_index/migration.sql +1 -0
  96. package/migrations/20261126144620_drop_user_message_time_index/snapshot.json +38 -0
  97. package/migrations/20261126153100_inbox_item_subjects/migration.sql +140 -0
  98. package/migrations/20261126153100_inbox_item_subjects/snapshot.json +9 -0
  99. package/migrations/20261126153103_inbox_item_subjects_not_null/migration.sql +12 -0
  100. package/migrations/20261126153103_inbox_item_subjects_not_null/snapshot.json +9 -0
  101. package/migrations/20261126153105_inbox_item_subject_indexes/migration.sql +1 -0
  102. package/migrations/20261126153105_inbox_item_subject_indexes/snapshot.json +9 -0
  103. package/migrations/20261126153108_automation_run_conversation_index/migration.sql +1 -0
  104. package/migrations/20261126153108_automation_run_conversation_index/snapshot.json +9 -0
  105. package/migrations/20261126153159_inbox_item_subjects_schema/migration.sql +4 -0
  106. package/migrations/20261126153159_inbox_item_subjects_schema/snapshot.json +437 -0
  107. package/migrations/20261126153259_inbox_questions/migration.sql +76 -0
  108. package/migrations/20261126153259_inbox_questions/snapshot.json +9 -0
  109. package/migrations/20261126153301_inbox_questions_valid/migration.sql +3 -0
  110. package/migrations/20261126153301_inbox_questions_valid/snapshot.json +9 -0
  111. package/migrations/20261126153343_inbox_questions_schema/migration.sql +5 -0
  112. package/migrations/20261126153343_inbox_questions_schema/snapshot.json +407 -0
  113. package/migrations/20261126154025_inbox_item_owners/migration.sql +74 -0
  114. package/migrations/20261126154025_inbox_item_owners/snapshot.json +9 -0
  115. package/migrations/20261126154048_inbox_item_open_subject_key_index/migration.sql +1 -0
  116. package/migrations/20261126154048_inbox_item_open_subject_key_index/snapshot.json +9 -0
  117. package/migrations/20261126154051_drop_inbox_item_owner_indexes/migration.sql +7 -0
  118. package/migrations/20261126154051_drop_inbox_item_owner_indexes/snapshot.json +9 -0
  119. package/migrations/20261126154121_inbox_item_owners_schema/migration.sql +8 -0
  120. package/migrations/20261126154121_inbox_item_owners_schema/snapshot.json +311 -0
  121. package/migrations/20261126175601_conversation_event_turn/migration.sql +5 -0
  122. package/migrations/20261126175601_conversation_event_turn/snapshot.json +103 -0
  123. package/migrations/20261126175614_conversation_event_turn_index/migration.sql +1 -0
  124. package/migrations/20261126175614_conversation_event_turn_index/snapshot.json +62 -0
  125. package/migrations/20261126230028_merge_leaves/migration.sql +2 -0
  126. package/migrations/20261126230028_merge_leaves/snapshot.json +12 -0
  127. package/migrations/20261126231932_space_lead_holds_name/migration.sql +46 -0
  128. package/migrations/20261126231932_space_lead_holds_name/snapshot.json +58 -0
  129. package/migrations/20261127001022_merge_leaves/migration.sql +2 -0
  130. package/migrations/20261127001022_merge_leaves/snapshot.json +12 -0
  131. package/package.json +5 -5
  132. package/skills/jr-rpc/SKILL.md +3 -5
  133. package/dist/direct-url-BYgYfuIy.js +0 -22
  134. package/dist/markers-CE0HMXWT.js +0 -67
  135. package/dist/people-Cegp1Iwq.js +0 -81
  136. package/dist/start-conversation-Uh8Sk1EF.js +0 -162
  137. package/dist/turn-session-routing-GtetHsdO.js +0 -1309
  138. package/dist/user-customization-B27StpVQ.js +0 -9
  139. package/dist/web-message-id-C6P83ans.js +0 -10
@@ -1,1309 +0,0 @@
1
- import { Cp as bufferBody, Cu as juniorSpaces, Du as juniorUsers, Gt as isTopLevel, Ia as getDispatchConversationId, Kt as messagesNeedSpaceMembership, Su as juniorSpaceMembers, _c as touchConversationDetail, _u as juniorAttachmentUploads, a as getDb, bu as juniorConversations, dl as resolveActorIdentityId, gc as nextDetailVersion, hc as conversationDetailTouch, i as getConversationStore, o as getSqlExecutor, qd as ToolInputError, sl as readUserAvatarUrls, vf as sameDestination, vu as juniorAttachments, yu as juniorMessageAttachments, za as getDispatchRecord, zn as isPostgresErrorCode } from "./db-DXTOYRzR.js";
2
- import { G as mapBounded } from "./transcript-BHhJVY0P.js";
3
- import { o as getActiveTraceContext } from "./logging-czs0nqLC.js";
4
- import { i as isVisionImageMediaType, r as detectImageMediaType } from "./media-Cr9pGkzr.js";
5
- import { Mn as buildDeterministicTurnId, Xt as appendAndEnqueueInboundMessage, Yt as appendAndEnqueueExclusiveInboundMessage } from "./mailbox-turn-79Nv1JXv.js";
6
- import { t as webMessageId } from "./web-message-id-C6P83ans.js";
7
- import * as z from "zod";
8
- import { createHash, randomUUID } from "node:crypto";
9
- import { createWebSource, localDestinationSchema } from "@sentry/junior-plugin-api";
10
- import { and, asc, count, eq, exists, gt, inArray, isNotNull, isNull, lte, notExists, or, sql } from "drizzle-orm";
11
- // src/chat/tool-support/structured-result.ts
12
- const juniorToolContinuationSchema = z.object({
13
- arguments: z.record(z.string(), z.unknown()),
14
- reason: z.string().min(1).optional()
15
- }).strict();
16
- const juniorToolBoundContinuationSchema = juniorToolContinuationSchema.extend({ tool_name: z.string().min(1) });
17
- /** Shared optional fields for canonical Junior tool outputs. */
18
- const juniorToolOutputSchema = z.object({
19
- target: z.string().min(1).optional(),
20
- truncated: z.boolean().optional(),
21
- /** True when this attempt did not finish before its time budget. */
22
- timed_out: z.boolean().optional(),
23
- continuation: juniorToolContinuationSchema.optional()
24
- }).passthrough();
25
- function sortJsonValue(value) {
26
- if (Array.isArray(value)) return value.map(sortJsonValue);
27
- if (!value || typeof value !== "object") return value;
28
- return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => [key, sortJsonValue(item)]));
29
- }
30
- const continuationDetailsSchema = z.looseObject({ continuation: z.looseObject({}) });
31
- /** Bind continuation metadata to the exposed runtime tool name. */
32
- function injectContinuationToolName(details, toolName) {
33
- const parsed = continuationDetailsSchema.safeParse(details);
34
- if (!parsed.success) return details;
35
- return {
36
- ...parsed.data,
37
- continuation: juniorToolBoundContinuationSchema.parse({
38
- ...parsed.data.continuation,
39
- tool_name: toolName
40
- })
41
- };
42
- }
43
- function makeStructuredToolOutput(details, options = {}) {
44
- return {
45
- content: [{
46
- type: "text",
47
- text: JSON.stringify(sortJsonValue(details))
48
- }, ...options.content ?? []],
49
- details
50
- };
51
- }
52
- // src/chat/tool-support/zod-tool.ts
53
- function isContentOnlyToolResult(value) {
54
- return value !== null && typeof value === "object" && Array.isArray(value.content) && !("details" in value);
55
- }
56
- function isStructuredToolResultEnvelope(value) {
57
- return value !== null && typeof value === "object" && Array.isArray(value.content) && "details" in value;
58
- }
59
- function parseToolContent(content) {
60
- for (const item of content) if (!item || typeof item !== "object" || (item.type === "text" ? typeof item.text !== "string" : item.type === "image" ? typeof item.data !== "string" || typeof item.mimeType !== "string" : true)) throw new TypeError("zodTool() content must contain valid text or image items.");
61
- return content;
62
- }
63
- function formatZodPath(path) {
64
- return path.length > 0 ? path.map(String).join(".") : "root";
65
- }
66
- function formatToolInputError(error) {
67
- return `Invalid tool arguments: ${error.issues.slice(0, 5).map((issue) => `${formatZodPath(issue.path)}: ${issue.message}`).join("; ") || "input did not match schema"}`;
68
- }
69
- /** Parse tool input with its Zod schema, as a model-repairable error on failure. */
70
- function parseToolInput(schema, args) {
71
- const result = schema.safeParse(args);
72
- if (!result.success) throw new ToolInputError(formatToolInputError(result.error), { cause: result.error });
73
- return result.data;
74
- }
75
- /** Declare the static definition of a Zod tool once, for the registry and its factory. */
76
- function zodToolDefinition(definition) {
77
- return definition;
78
- }
79
- function zodTool(definition) {
80
- const { inputSchema, outputSchema, prepareArguments, execute, ...toolDef } = definition;
81
- let modelInputSchema;
82
- try {
83
- modelInputSchema = z.toJSONSchema(inputSchema);
84
- } catch (error) {
85
- throw new TypeError("zodTool() inputSchema must be representable as JSON Schema.", { cause: error });
86
- }
87
- let modelOutputSchema;
88
- if (outputSchema) try {
89
- modelOutputSchema = z.toJSONSchema(outputSchema);
90
- } catch (error) {
91
- throw new TypeError("zodTool() outputSchema must be representable as JSON Schema.", { cause: error });
92
- }
93
- return {
94
- ...toolDef,
95
- inputSchema: modelInputSchema,
96
- ...modelOutputSchema ? { outputSchema: modelOutputSchema } : void 0,
97
- prepareArguments(args) {
98
- return parseToolInput(inputSchema, prepareArguments ? prepareArguments(args) : args);
99
- },
100
- ...execute ? { async execute(input, options) {
101
- const result = await execute(input, options);
102
- if (!outputSchema) {
103
- if (isContentOnlyToolResult(result)) return result;
104
- throw new TypeError("zodTool() content-only tools must return { content } without details.");
105
- }
106
- if (isStructuredToolResultEnvelope(result)) return {
107
- content: parseToolContent(result.content),
108
- details: outputSchema.parse(result.details)
109
- };
110
- return outputSchema.parse(result);
111
- } } : void 0
112
- };
113
- }
114
- // src/chat/attachments/source.ts
115
- /** The source deleted the file, or Junior can no longer read it. */
116
- var AttachmentSourceUnavailableError = class extends Error {
117
- constructor(message, options) {
118
- super(message, options);
119
- this.name = "AttachmentSourceUnavailableError";
120
- }
121
- };
122
- // src/chat/attachments/store.ts
123
- const DAY_MS = 864e5;
124
- const ATTACHMENT_GC_BATCH_LIMIT = 200;
125
- /** Time that Junior keeps attachment bytes after the file is stored. */
126
- const ATTACHMENT_RETENTION_MS = 30 * DAY_MS;
127
- /** Only `file` rows: a `url` row has no storage or file fields. */
128
- const isFileAttachment = eq(juniorAttachments.kind, "file");
129
- /**
130
- * The storage and file fields of a `file` row. Every `file` row has them, so
131
- * a missing one is a broken row.
132
- */
133
- function fileFields(row) {
134
- const { bytes, contentType, storageProvider, title } = row;
135
- if (bytes === null || contentType === null || storageProvider === null || title === null) throw new Error(`Attachment ${row.id} has no file fields`);
136
- return {
137
- bytes,
138
- contentType,
139
- filename: title,
140
- storageProvider
141
- };
142
- }
143
- function attachmentIdentity(file) {
144
- if ("data" in file) return file.source ?? { sha256: createHash("sha256").update(file.data).digest("hex") };
145
- return file.source;
146
- }
147
- /** Stable conversation-owned id for one file and its presentation metadata. */
148
- function attachmentId(args) {
149
- const identity = "sha256" in args.identity ? [
150
- args.conversationId,
151
- args.storageProvider,
152
- args.identity.sha256,
153
- args.filename,
154
- args.contentType
155
- ] : [
156
- args.conversationId,
157
- args.storageProvider,
158
- args.filename,
159
- args.contentType,
160
- args.identity.provider,
161
- args.identity.id
162
- ];
163
- return createHash("sha256").update(identity.join("\0")).digest("hex");
164
- }
165
- /**
166
- * Object key for one write attempt.
167
- *
168
- * Attachment ids are content-stable. Object keys are not: each put gets a fresh
169
- * key so a failed-write cleanup or GC delete cannot remove another writer's
170
- * durable blob.
171
- */
172
- function attachmentKey(args) {
173
- return `conversations/${args.conversationId}/attachments/${args.attachmentId}/${args.writeId}/${args.filename}`;
174
- }
175
- /** A source whose bytes do not match its declared size. A retry cannot fix it. */
176
- var AttachmentSizeError = class extends Error {
177
- constructor(bytes, expected, options) {
178
- super(`Attachment body does not match its declared ${expected} bytes (read ${bytes})`, options);
179
- this.name = "AttachmentSizeError";
180
- }
181
- };
182
- /** Tries for one object write, each with a freshly opened body. */
183
- const WRITE_ATTEMPTS = 3;
184
- async function bestEffortDelete(storage, key) {
185
- if (key === null) return;
186
- try {
187
- await storage.delete([key]);
188
- } catch {}
189
- }
190
- /**
191
- * Stream one file to a fresh key, and return its size and digest.
192
- *
193
- * The digest is taken while the bytes stream, so the body is never held
194
- * whole. A body that does not match its declared size is not kept.
195
- */
196
- async function writeAttachmentObject(args) {
197
- for (let attempt = 1;; attempt += 1) try {
198
- return await writeAttachmentObjectOnce(args);
199
- } catch (error) {
200
- if (error instanceof AttachmentSizeError || error instanceof AttachmentSourceUnavailableError || attempt >= WRITE_ATTEMPTS) {
201
- await bestEffortDelete(args.storage, args.key);
202
- throw error;
203
- }
204
- }
205
- }
206
- async function writeAttachmentObjectOnce(args) {
207
- const { file } = args;
208
- const expected = "data" in file ? file.data.byteLength : file.bytes;
209
- const source = "data" in file ? bufferBody(file.data) : await file.open();
210
- const hash = createHash("sha256");
211
- let bytes = 0;
212
- const body = source.pipeThrough(new TransformStream({ transform(chunk, controller) {
213
- bytes += chunk.byteLength;
214
- if (bytes > expected) throw new AttachmentSizeError(bytes, expected);
215
- hash.update(chunk);
216
- controller.enqueue(chunk);
217
- } }));
218
- try {
219
- await args.storage.put({
220
- body,
221
- bytes: expected,
222
- contentType: file.mimeType,
223
- key: args.key
224
- });
225
- } catch (error) {
226
- if (bytes > expected) throw new AttachmentSizeError(bytes, expected, { cause: error });
227
- throw error;
228
- }
229
- if (bytes !== expected) throw new AttachmentSizeError(bytes, expected);
230
- return {
231
- bytes,
232
- sha256: hash.digest("hex")
233
- };
234
- }
235
- async function isConversationPurged(db, conversationId) {
236
- const [row] = await db.db().select({ transcriptPurgedAt: juniorConversations.transcriptPurgedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId));
237
- return row?.transcriptPurgedAt != null;
238
- }
239
- function purgedConversationError(conversationId) {
240
- return /* @__PURE__ */ new Error(`Cannot store attachment for purged conversation ${conversationId}`);
241
- }
242
- async function assertConversationNotPurged(db, conversationId) {
243
- if (await isConversationPurged(db, conversationId)) throw purgedConversationError(conversationId);
244
- }
245
- /** Mark a just-written row for deletion and drop its unused object. */
246
- async function rejectPurgedAttachmentWrite(args) {
247
- const db = args.db.db();
248
- await db.with(conversationDetailTouch(db, [args.conversationId])).update(juniorAttachments).set({ deleteRequestedAt: args.now }).where(eq(juniorAttachments.id, args.id));
249
- await bestEffortDelete(args.storage, args.storageKey);
250
- throw purgedConversationError(args.conversationId);
251
- }
252
- /**
253
- * Return another writer's live row only when the conversation is still active.
254
- *
255
- * The caller already wrote a unique object for this attempt. Delete that unused
256
- * object either way. If the conversation is purged, do not report success for a
257
- * row that purge/GC is about to remove.
258
- */
259
- async function reuseLiveAttachment(args) {
260
- await bestEffortDelete(args.storage, args.storageKey);
261
- await assertConversationNotPurged(args.db, args.conversationId);
262
- return { id: args.id };
263
- }
264
- /**
265
- * Persist one conversation-owned file.
266
- *
267
- * Identity is stable under the conversation: it comes from the file's source
268
- * when it has one, and from its digest otherwise. Object storage is written
269
- * first under a unique key; the SQL row is created only after that write
270
- * succeeds. A row means the attachment is durable. Retries reuse an existing
271
- * live row. A purge-marked row is revived by writing a new object and pointing
272
- * the row at it, unless the conversation is still purged. If the SQL write
273
- * fails after object storage accepts the bytes, this path deletes that unique
274
- * object. A process crash between those steps can leave an unreferenced unique
275
- * object with no SQL row.
276
- */
277
- async function storeAttachment(args) {
278
- const now = new Date(args.nowMs ?? Date.now());
279
- const identity = attachmentIdentity(args.file);
280
- const source = args.file.source;
281
- const id = attachmentId({
282
- conversationId: args.conversationId,
283
- contentType: args.file.mimeType,
284
- filename: args.file.filename,
285
- identity,
286
- storageProvider: args.storage.provider
287
- });
288
- const [existing] = await args.db.db().select({
289
- contentType: juniorAttachments.contentType,
290
- conversationId: juniorAttachments.conversationId,
291
- deleteRequestedAt: juniorAttachments.deleteRequestedAt,
292
- filename: juniorAttachments.title,
293
- id: juniorAttachments.id,
294
- provider: juniorAttachments.provider,
295
- providerId: juniorAttachments.providerId,
296
- storageProvider: juniorAttachments.storageProvider,
297
- sha256: juniorAttachments.sha256,
298
- storageKey: juniorAttachments.storageKey
299
- }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
300
- if (existing) {
301
- 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}`);
302
- if (existing.deleteRequestedAt === null) {
303
- await assertConversationNotPurged(args.db, args.conversationId);
304
- return { id: existing.id };
305
- }
306
- }
307
- await assertConversationNotPurged(args.db, args.conversationId);
308
- const { file } = args;
309
- let storageKey = null;
310
- let written;
311
- if ("deferred" in file) written = {
312
- bytes: file.bytes,
313
- sha256: null
314
- };
315
- else {
316
- storageKey = attachmentKey({
317
- attachmentId: id,
318
- conversationId: args.conversationId,
319
- filename: file.filename,
320
- writeId: randomUUID()
321
- });
322
- written = await writeAttachmentObject({
323
- file,
324
- key: storageKey,
325
- storage: args.storage
326
- });
327
- }
328
- if (existing?.deleteRequestedAt != null) {
329
- if (await isConversationPurged(args.db, args.conversationId)) {
330
- await bestEffortDelete(args.storage, storageKey);
331
- throw purgedConversationError(args.conversationId);
332
- }
333
- const oldStorageKey = existing.storageKey;
334
- if ((await args.db.db().with(conversationDetailTouch(args.db.db(), [args.conversationId])).update(juniorAttachments).set({
335
- ...written,
336
- deleteRequestedAt: null,
337
- storageKey
338
- }).where(and(eq(juniorAttachments.id, id), isNotNull(juniorAttachments.deleteRequestedAt))).returning({ id: juniorAttachments.id })).length > 0) {
339
- if (await isConversationPurged(args.db, args.conversationId)) await rejectPurgedAttachmentWrite({
340
- conversationId: args.conversationId,
341
- db: args.db,
342
- id,
343
- now,
344
- storage: args.storage,
345
- storageKey
346
- });
347
- if (oldStorageKey !== storageKey) await bestEffortDelete(args.storage, oldStorageKey);
348
- return { id };
349
- }
350
- const [afterRace] = await args.db.db().select({
351
- deleteRequestedAt: juniorAttachments.deleteRequestedAt,
352
- id: juniorAttachments.id,
353
- storageKey: juniorAttachments.storageKey
354
- }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
355
- if (afterRace?.deleteRequestedAt === null) return reuseLiveAttachment({
356
- conversationId: args.conversationId,
357
- db: args.db,
358
- id: afterRace.id,
359
- storage: args.storage,
360
- storageKey
361
- });
362
- }
363
- let inserted = [];
364
- try {
365
- inserted = await args.db.db().with(conversationDetailTouch(args.db.db(), [args.conversationId])).insert(juniorAttachments).values({
366
- id,
367
- conversationId: args.conversationId,
368
- storageProvider: args.storage.provider,
369
- storageKey,
370
- provider: source?.provider,
371
- providerId: source?.id,
372
- title: args.file.filename,
373
- contentType: args.file.mimeType,
374
- ...written,
375
- createdAt: now
376
- }).onConflictDoNothing({ target: juniorAttachments.id }).returning({ id: juniorAttachments.id });
377
- } catch (error) {
378
- await bestEffortDelete(args.storage, storageKey);
379
- throw error;
380
- }
381
- if (inserted.length > 0) {
382
- if (await isConversationPurged(args.db, args.conversationId)) await rejectPurgedAttachmentWrite({
383
- conversationId: args.conversationId,
384
- db: args.db,
385
- id,
386
- now,
387
- storage: args.storage,
388
- storageKey
389
- });
390
- return { id };
391
- }
392
- const [row] = await args.db.db().select({
393
- deleteRequestedAt: juniorAttachments.deleteRequestedAt,
394
- id: juniorAttachments.id,
395
- storageKey: juniorAttachments.storageKey
396
- }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
397
- if (!row) {
398
- await bestEffortDelete(args.storage, storageKey);
399
- throw new Error(`Attachment row missing after write for ${id}`);
400
- }
401
- if (row.deleteRequestedAt === null) return reuseLiveAttachment({
402
- conversationId: args.conversationId,
403
- db: args.db,
404
- id: row.id,
405
- storage: args.storage,
406
- storageKey
407
- });
408
- if (await isConversationPurged(args.db, args.conversationId)) {
409
- await bestEffortDelete(args.storage, storageKey);
410
- throw purgedConversationError(args.conversationId);
411
- }
412
- if ((await args.db.db().with(conversationDetailTouch(args.db.db(), [args.conversationId])).update(juniorAttachments).set({
413
- ...written,
414
- deleteRequestedAt: null,
415
- storageKey
416
- }).where(and(eq(juniorAttachments.id, id), isNotNull(juniorAttachments.deleteRequestedAt))).returning({ id: juniorAttachments.id })).length > 0) {
417
- if (await isConversationPurged(args.db, args.conversationId)) await rejectPurgedAttachmentWrite({
418
- conversationId: args.conversationId,
419
- db: args.db,
420
- id,
421
- now,
422
- storage: args.storage,
423
- storageKey
424
- });
425
- if (row.storageKey !== storageKey) await bestEffortDelete(args.storage, row.storageKey);
426
- return { id };
427
- }
428
- const [afterRace] = await args.db.db().select({
429
- deleteRequestedAt: juniorAttachments.deleteRequestedAt,
430
- id: juniorAttachments.id
431
- }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
432
- if (afterRace?.deleteRequestedAt === null) return reuseLiveAttachment({
433
- conversationId: args.conversationId,
434
- db: args.db,
435
- id: afterRace.id,
436
- storage: args.storage,
437
- storageKey
438
- });
439
- await bestEffortDelete(args.storage, storageKey);
440
- throw new Error(`Attachment ${id} disappeared while reviving`);
441
- }
442
- /**
443
- * Record an object that a browser already wrote, under the upload's id.
444
- *
445
- * The row takes over the object key. A retry with the same id keeps the
446
- * first row. The caller checked the object's size, type, and digest.
447
- */
448
- async function recordUploadedAttachment(args) {
449
- const { attachment } = args;
450
- const now = new Date(args.nowMs);
451
- await assertConversationNotPurged(args.db, attachment.conversationId);
452
- if ((await args.db.db().with(conversationDetailTouch(args.db.db(), [attachment.conversationId])).insert(juniorAttachments).values({
453
- bytes: attachment.bytes,
454
- contentType: attachment.contentType,
455
- conversationId: attachment.conversationId,
456
- createdAt: now,
457
- id: attachment.id,
458
- sha256: attachment.sha256,
459
- storageKey: attachment.storageKey,
460
- storageProvider: args.storage.provider,
461
- title: attachment.filename
462
- }).onConflictDoNothing({ target: juniorAttachments.id }).returning({ id: juniorAttachments.id })).length > 0 && await isConversationPurged(args.db, attachment.conversationId)) await rejectPurgedAttachmentWrite({
463
- conversationId: attachment.conversationId,
464
- db: args.db,
465
- id: attachment.id,
466
- now,
467
- storage: args.storage,
468
- storageKey: attachment.storageKey
469
- });
470
- }
471
- /**
472
- * Store a file that Junior recorded without its bytes, on its first read.
473
- *
474
- * The bytes stream from the source to a fresh key. The row then takes that
475
- * key only while it is still unstored, live, and in a conversation that is
476
- * not purged. Purge marks rows in the transaction that purges the
477
- * conversation, so this update cannot revive a purged row. When the update
478
- * misses, the new object is deleted: return the row that another writer
479
- * stored, or null when the row is no longer live.
480
- */
481
- async function storeDeferredAttachment(args) {
482
- const { attachment, storage } = args;
483
- const storageKey = attachmentKey({
484
- attachmentId: attachment.id,
485
- conversationId: attachment.conversationId,
486
- filename: attachment.filename,
487
- writeId: randomUUID()
488
- });
489
- const written = await writeAttachmentObject({
490
- file: {
491
- bytes: args.file.bytes,
492
- filename: attachment.filename,
493
- mimeType: attachment.contentType,
494
- open: args.file.open,
495
- source: attachment.source
496
- },
497
- key: storageKey,
498
- storage
499
- });
500
- const db = args.db.db();
501
- if ((await db.with(conversationDetailTouch(db, [attachment.conversationId])).update(juniorAttachments).set({
502
- ...written,
503
- storageKey
504
- }).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 {
505
- ...attachment,
506
- bytes: written.bytes,
507
- storageKey
508
- };
509
- await bestEffortDelete(storage, storageKey);
510
- const current = await readLiveAttachment({
511
- attachmentId: attachment.id,
512
- conversationId: attachment.conversationId,
513
- db: args.db
514
- });
515
- return current?.storageKey ? {
516
- ...current,
517
- storageKey: current.storageKey
518
- } : null;
519
- }
520
- /** Load one live attachment owned by a conversation. */
521
- async function readLiveAttachment(args) {
522
- const [row] = await args.db.db().select({
523
- bytes: juniorAttachments.bytes,
524
- contentType: juniorAttachments.contentType,
525
- conversationId: juniorAttachments.conversationId,
526
- deleteRequestedAt: juniorAttachments.deleteRequestedAt,
527
- id: juniorAttachments.id,
528
- provider: juniorAttachments.provider,
529
- providerId: juniorAttachments.providerId,
530
- storageProvider: juniorAttachments.storageProvider,
531
- storageKey: juniorAttachments.storageKey,
532
- title: juniorAttachments.title
533
- }).from(juniorAttachments).where(and(eq(juniorAttachments.id, args.attachmentId), isFileAttachment, eq(juniorAttachments.conversationId, args.conversationId), isNull(juniorAttachments.deleteRequestedAt)));
534
- if (!row) return null;
535
- if (await isConversationPurged(args.db, args.conversationId)) return null;
536
- return {
537
- ...fileFields(row),
538
- conversationId: row.conversationId,
539
- id: row.id,
540
- source: row.provider && row.providerId ? {
541
- id: row.providerId,
542
- provider: row.provider
543
- } : null,
544
- storageKey: row.storageKey
545
- };
546
- }
547
- /** Persist many conversation-owned files. */
548
- async function storeAttachments(args) {
549
- return await mapBounded(args.files, (file) => storeAttachment({
550
- conversationId: args.conversationId,
551
- db: args.db,
552
- file: {
553
- data: file.data,
554
- filename: file.filename,
555
- mimeType: file.mimeType
556
- },
557
- ...args.nowMs !== void 0 ? { nowMs: args.nowMs } : void 0,
558
- storage: args.storage
559
- }));
560
- }
561
- /** Mark attachments unavailable when their conversation content is purged. */
562
- async function requestAttachmentDeletion(db, conversationIds, nowMs) {
563
- if (conversationIds.length === 0) return;
564
- await db.db().with(conversationDetailTouch(db.db(), conversationIds)).update(juniorAttachments).set({ deleteRequestedAt: new Date(nowMs) }).where(and(inArray(juniorAttachments.conversationId, conversationIds), isNull(juniorAttachments.deleteRequestedAt)));
565
- }
566
- /**
567
- * Delete purged attachments in one bounded batch.
568
- *
569
- * Eligible files are 30 days old, explicitly purge-marked, or owned by a
570
- * conversation whose transcript is already purged. A `url` row has no bytes,
571
- * so it lives as long as its message: it is eligible only when purge-marked
572
- * or purged. Delete object keys first, then remove rows that are still
573
- * eligible so a failed blob delete remains retryable.
574
- */
575
- async function collectAttachmentGarbage(args) {
576
- const expiresBefore = /* @__PURE__ */ new Date(args.nowMs - ATTACHMENT_RETENTION_MS);
577
- const purged = or(isNotNull(juniorAttachments.deleteRequestedAt), isNotNull(juniorConversations.transcriptPurgedAt));
578
- const eligible = or(lte(juniorAttachments.createdAt, expiresBefore), purged);
579
- const isUrl = eq(juniorAttachments.kind, "url");
580
- const rows = await args.db.db().select({
581
- id: juniorAttachments.id,
582
- storageKey: juniorAttachments.storageKey
583
- }).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);
584
- if (rows.length === 0) return { deleted: 0 };
585
- const keys = rows.flatMap((row) => row.storageKey ? [row.storageKey] : []);
586
- if (keys.length > 0) await args.storage.delete(keys);
587
- 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))));
588
- if (stillEligible.length === 0) return { deleted: 0 };
589
- const removed = await args.db.db().delete(juniorAttachments).where(inArray(juniorAttachments.id, stillEligible.map((row) => row.id))).returning({
590
- conversationId: juniorAttachments.conversationId,
591
- id: juniorAttachments.id,
592
- kind: juniorAttachments.kind
593
- });
594
- const urls = removed.filter((row) => row.kind === "url");
595
- 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))));
596
- await touchConversationDetail(args.db.db(), removed.map((row) => row.conversationId));
597
- return { deleted: removed.length };
598
- }
599
- // src/chat/spaces/store.ts
600
- /**
601
- * Spaces and their members (`design/spaces.md`). Any signed-in person can
602
- * read a public Space. Only members read a private Space, and only members
603
- * change a Space.
604
- */
605
- function memberCountSql() {
606
- return getDb().select({ value: count() }).from(juniorSpaceMembers).where(eq(juniorSpaceMembers.spaceId, juniorSpaces.id));
607
- }
608
- function viewerMembership(viewerUserId) {
609
- return getDb().select({ one: juniorSpaceMembers.userId }).from(juniorSpaceMembers).where(and(eq(juniorSpaceMembers.spaceId, juniorSpaces.id), eq(juniorSpaceMembers.userId, viewerUserId)));
610
- }
611
- async function selectSpaces(viewerUserId, where) {
612
- return await getDb().select({
613
- id: juniorSpaces.id,
614
- name: juniorSpaces.name,
615
- description: juniorSpaces.description,
616
- visibility: juniorSpaces.visibility,
617
- createdAt: juniorSpaces.createdAt,
618
- updatedAt: juniorSpaces.updatedAt,
619
- archivedAt: juniorSpaces.archivedAt,
620
- memberCount: sql`(${memberCountSql()})`.mapWith(Number),
621
- viewerIsMember: sql`${exists(viewerMembership(viewerUserId))}`.mapWith(Boolean)
622
- }).from(juniorSpaces).where(and(where, or(eq(juniorSpaces.visibility, "public"), exists(viewerMembership(viewerUserId))))).orderBy(asc(juniorSpaces.name), asc(juniorSpaces.id));
623
- }
624
- /** Return the Spaces that match the filter, by name. */
625
- async function listSpaces(viewerUserId, filter) {
626
- return await selectSpaces(viewerUserId, and(filter.archived ? isNotNull(juniorSpaces.archivedAt) : isNull(juniorSpaces.archivedAt), filter.membership === "member" ? exists(viewerMembership(viewerUserId)) : void 0));
627
- }
628
- /** Return one Space, or nothing when it does not exist. */
629
- async function readSpace(viewerUserId, spaceId) {
630
- const [space] = await selectSpaces(viewerUserId, eq(juniorSpaces.id, spaceId));
631
- return space;
632
- }
633
- /** Create a Space. Its creator is its first member. */
634
- async function createSpace(args) {
635
- const executor = getSqlExecutor();
636
- const id = randomUUID();
637
- const now = /* @__PURE__ */ new Date();
638
- await executor.transaction(async () => {
639
- const db = executor.db();
640
- await db.insert(juniorSpaces).values({
641
- id,
642
- name: args.name,
643
- description: args.description,
644
- visibility: args.visibility,
645
- createdByUserId: args.creatorUserId,
646
- createdAt: now,
647
- updatedAt: now
648
- });
649
- await db.insert(juniorSpaceMembers).values({
650
- spaceId: id,
651
- userId: args.creatorUserId,
652
- joinedAt: now
653
- });
654
- });
655
- const space = await readSpace(args.creatorUserId, id);
656
- if (!space) throw new Error("The Space was not saved");
657
- return space;
658
- }
659
- /**
660
- * Change the name or description of a Space. Its visibility is set when it
661
- * is created and never changes.
662
- */
663
- async function updateSpace(spaceId, changes) {
664
- const { name } = changes;
665
- await getDb().transaction(async (tx) => {
666
- await tx.update(juniorSpaces).set({
667
- ...name !== void 0 ? { name } : void 0,
668
- ...changes.description !== void 0 ? { description: changes.description } : void 0,
669
- updatedAt: /* @__PURE__ */ new Date()
670
- }).where(eq(juniorSpaces.id, spaceId));
671
- if (name === void 0) return;
672
- await tx.update(juniorConversations).set({
673
- title: name,
674
- detailVersion: nextDetailVersion
675
- }).where(and(eq(juniorConversations.kind, "lead"), eq(juniorConversations.spaceId, spaceId)));
676
- });
677
- }
678
- /** Add one person to a Space. Joining twice keeps the first join. */
679
- async function joinSpace(spaceId, userId) {
680
- await getDb().insert(juniorSpaceMembers).values({
681
- spaceId,
682
- userId,
683
- joinedAt: /* @__PURE__ */ new Date()
684
- }).onConflictDoNothing();
685
- }
686
- /**
687
- * Remove one person from a Space. Returns "last_member", and changes
688
- * nothing, when they are the last member of a private Space: nobody could
689
- * read or restore a private Space with no members.
690
- */
691
- async function leaveSpace(spaceId, userId) {
692
- const executor = getSqlExecutor();
693
- return await executor.transaction(async () => {
694
- const db = executor.db();
695
- const [space] = await db.select({ visibility: juniorSpaces.visibility }).from(juniorSpaces).where(eq(juniorSpaces.id, spaceId)).for("update");
696
- const member = and(eq(juniorSpaceMembers.spaceId, spaceId), eq(juniorSpaceMembers.userId, userId));
697
- if (space?.visibility === "private") {
698
- const members = await db.select({ userId: juniorSpaceMembers.userId }).from(juniorSpaceMembers).where(eq(juniorSpaceMembers.spaceId, spaceId)).limit(2);
699
- if (members.length === 1 && members[0].userId === userId) return "last_member";
700
- }
701
- await db.delete(juniorSpaceMembers).where(member);
702
- });
703
- }
704
- /** Return the members of a Space, earliest join first. */
705
- async function listSpaceMembers(spaceId) {
706
- const db = getDb();
707
- const rows = await db.select({
708
- userId: juniorSpaceMembers.userId,
709
- email: juniorUsers.primaryEmail,
710
- displayName: juniorUsers.displayName,
711
- joinedAt: juniorSpaceMembers.joinedAt
712
- }).from(juniorSpaceMembers).innerJoin(juniorUsers, eq(juniorUsers.id, juniorSpaceMembers.userId)).where(eq(juniorSpaceMembers.spaceId, spaceId)).orderBy(asc(juniorSpaceMembers.joinedAt), asc(juniorSpaceMembers.userId));
713
- const avatars = await readUserAvatarUrls(db, rows.map((row) => row.userId));
714
- return rows.map((row) => ({
715
- ...row,
716
- avatarUrl: avatars.get(row.userId) ?? null
717
- }));
718
- }
719
- // src/chat/attachments/uploads.ts
720
- const MINUTE_MS = 6e4;
721
- /** Time that a browser has to write the bytes after it asks to upload. */
722
- const UPLOAD_TARGET_TTL_MS = 15 * MINUTE_MS;
723
- /** Time that a written upload can still join a Message. */
724
- const UPLOAD_SEND_WINDOW_MS = 60 * MINUTE_MS;
725
- /**
726
- * Age at which cleanup deletes an upload that no Message used. It is much
727
- * longer than the send window, so cleanup cannot race a send.
728
- */
729
- const UPLOAD_RETENTION_MS = 1440 * MINUTE_MS;
730
- const UPLOAD_GC_BATCH_LIMIT = 200;
731
- /** Leading bytes that image type detection reads. */
732
- const SIGNATURE_BYTES = 16;
733
- /** A Message refers to an upload that it cannot use. */
734
- var AttachmentUploadError = class extends Error {
735
- constructor(message) {
736
- super(message);
737
- this.name = "AttachmentUploadError";
738
- }
739
- };
740
- /**
741
- * Reserve one object key for a browser upload.
742
- *
743
- * Returns no target when the provider cannot sign browser writes. The caller
744
- * then takes the bytes with `writeAttachmentUpload`.
745
- */
746
- async function createAttachmentUpload(args) {
747
- const nowMs = args.nowMs ?? Date.now();
748
- const id = randomUUID();
749
- const storageKey = `conversations/${args.scope.conversationId}/uploads/${id}`;
750
- await args.db.db().insert(juniorAttachmentUploads).values({
751
- ...args.scope,
752
- bytes: args.file.bytes,
753
- contentType: args.file.contentType,
754
- createdAt: new Date(nowMs),
755
- filename: args.file.filename,
756
- id,
757
- storageKey,
758
- storageProvider: args.storage.provider
759
- });
760
- const target = await args.storage.createUploadTarget?.({
761
- bytes: args.file.bytes,
762
- contentType: args.file.contentType,
763
- expiresAtMs: nowMs + UPLOAD_TARGET_TTL_MS,
764
- key: storageKey
765
- });
766
- return target ? {
767
- id,
768
- target
769
- } : { id };
770
- }
771
- async function readUploadRows(args) {
772
- return await args.db.db().select().from(juniorAttachmentUploads).where(and(inArray(juniorAttachmentUploads.id, [...args.uploadIds]), eq(juniorAttachmentUploads.conversationId, args.scope.conversationId), eq(juniorAttachmentUploads.idempotencyKey, args.scope.idempotencyKey), eq(juniorAttachmentUploads.userId, args.scope.userId), eq(juniorAttachmentUploads.storageProvider, args.storageProvider), gt(juniorAttachmentUploads.createdAt, /* @__PURE__ */ new Date(args.nowMs - UPLOAD_SEND_WINDOW_MS))));
773
- }
774
- /** Write upload bytes through the API, for providers without browser writes. */
775
- async function writeAttachmentUpload(args) {
776
- const nowMs = args.nowMs ?? Date.now();
777
- const [row] = await args.db.db().select().from(juniorAttachmentUploads).where(and(eq(juniorAttachmentUploads.id, args.uploadId), eq(juniorAttachmentUploads.userId, args.userId), eq(juniorAttachmentUploads.storageProvider, args.storage.provider), gt(juniorAttachmentUploads.createdAt, /* @__PURE__ */ new Date(nowMs - UPLOAD_TARGET_TTL_MS))));
778
- if (!row) throw new AttachmentUploadError("Upload not found.");
779
- if (await readLiveAttachment({
780
- attachmentId: row.id,
781
- conversationId: row.conversationId,
782
- db: args.db
783
- })) throw new AttachmentUploadError("Upload was already sent.");
784
- if (args.body.byteLength !== row.bytes) throw new AttachmentUploadError("Upload size does not match the file.");
785
- await args.storage.put({
786
- body: bufferBody(args.body),
787
- bytes: row.bytes,
788
- contentType: row.contentType,
789
- key: row.storageKey
790
- });
791
- }
792
- /** Read a whole object once for its size, digest, and leading bytes. */
793
- async function inspectObject(body, maxBytes) {
794
- const hash = createHash("sha256");
795
- const head = [];
796
- let headBytes = 0;
797
- let bytes = 0;
798
- const reader = body.getReader();
799
- for (;;) {
800
- const { done, value } = await reader.read();
801
- if (done) break;
802
- bytes += value.byteLength;
803
- if (bytes > maxBytes) {
804
- await reader.cancel();
805
- return;
806
- }
807
- hash.update(value);
808
- if (headBytes < SIGNATURE_BYTES) {
809
- head.push(Buffer.from(value.subarray(0, SIGNATURE_BYTES - headBytes)));
810
- headBytes += head.at(-1).byteLength;
811
- }
812
- }
813
- return {
814
- bytes,
815
- head: Buffer.concat(head),
816
- sha256: hash.digest("hex")
817
- };
818
- }
819
- /**
820
- * Pick the type to store from the file signature, not only the browser's
821
- * guess from the file name. Models reject an image whose bytes do not match
822
- * its type, so a file that only claims to be an image is stored as bytes.
823
- */
824
- function storedContentType(declared, head) {
825
- const detected = detectImageMediaType(head);
826
- if (detected) return detected;
827
- return isVisionImageMediaType(declared) ? "application/octet-stream" : declared;
828
- }
829
- /**
830
- * Check the uploads of one Message before the Message is accepted.
831
- *
832
- * Each upload must belong to the scope and be written in full at its
833
- * declared size. Throws `AttachmentUploadError` for any upload that the
834
- * Message cannot use.
835
- */
836
- async function verifyAttachmentUploads(args) {
837
- if (args.uploadIds.length === 0) return [];
838
- if (new Set(args.uploadIds).size !== args.uploadIds.length) throw new AttachmentUploadError("Attach each file once.");
839
- const rows = await readUploadRows({
840
- db: args.db,
841
- nowMs: args.nowMs ?? Date.now(),
842
- scope: args.scope,
843
- storageProvider: args.storage.provider,
844
- uploadIds: args.uploadIds
845
- });
846
- const byId = new Map(rows.map((row) => [row.id, row]));
847
- return await Promise.all(args.uploadIds.map(async (uploadId) => {
848
- const row = byId.get(uploadId);
849
- if (!row) throw new AttachmentUploadError("Upload expired. Attach the file again.");
850
- const recorded = await readLiveAttachment({
851
- attachmentId: row.id,
852
- conversationId: row.conversationId,
853
- db: args.db
854
- });
855
- if (recorded) return {
856
- attachment: {
857
- bytes: recorded.bytes,
858
- contentType: recorded.contentType,
859
- filename: recorded.filename,
860
- id: recorded.id
861
- },
862
- recorded: true
863
- };
864
- const body = await args.storage.get(row.storageKey);
865
- const object = body ? await inspectObject(body, row.bytes) : void 0;
866
- if (!object || object.bytes !== row.bytes) throw new AttachmentUploadError(`Upload of ${row.filename} is not complete. Attach it again.`);
867
- return {
868
- attachment: {
869
- bytes: row.bytes,
870
- contentType: storedContentType(row.contentType, object.head),
871
- filename: row.filename,
872
- id: row.id
873
- },
874
- recorded: false,
875
- sha256: object.sha256,
876
- storageKey: row.storageKey
877
- };
878
- }));
879
- }
880
- /** Record checked uploads as attachments of their Conversation. */
881
- async function recordAttachmentUploads(args) {
882
- await mapBounded(args.uploads.filter((upload) => !upload.recorded), (upload) => recordUploadedAttachment({
883
- attachment: {
884
- ...upload.attachment,
885
- conversationId: args.conversationId,
886
- sha256: upload.sha256,
887
- storageKey: upload.storageKey
888
- },
889
- db: args.db,
890
- nowMs: args.nowMs ?? Date.now(),
891
- storage: args.storage
892
- }));
893
- return args.uploads.map((upload) => upload.attachment);
894
- }
895
- /**
896
- * Delete old upload rows in one bounded batch.
897
- *
898
- * An upload that a Message recorded keeps its object: the attachment row owns
899
- * it now. Other objects are deleted first, so a failed delete stays
900
- * retryable.
901
- */
902
- async function collectAttachmentUploadGarbage(args) {
903
- const rows = await args.db.db().select({
904
- id: juniorAttachmentUploads.id,
905
- recordedId: juniorAttachments.id,
906
- storageKey: juniorAttachmentUploads.storageKey
907
- }).from(juniorAttachmentUploads).leftJoin(juniorAttachments, eq(juniorAttachments.id, juniorAttachmentUploads.id)).where(and(eq(juniorAttachmentUploads.storageProvider, args.storage.provider), lte(juniorAttachmentUploads.createdAt, /* @__PURE__ */ new Date(args.nowMs - UPLOAD_RETENTION_MS)))).orderBy(asc(juniorAttachmentUploads.createdAt)).limit(UPLOAD_GC_BATCH_LIMIT);
908
- if (rows.length === 0) return { deleted: 0 };
909
- const unusedKeys = rows.filter((row) => row.recordedId === null).map((row) => row.storageKey);
910
- await args.storage.delete(unusedKeys);
911
- return { deleted: (await args.db.db().delete(juniorAttachmentUploads).where(inArray(juniorAttachmentUploads.id, rows.map((row) => row.id))).returning({ id: juniorAttachmentUploads.id })).length };
912
- }
913
- // src/chat/conversations/destination.ts
914
- function requireLocalDestination(conversationId) {
915
- const parsed = localDestinationSchema.safeParse({
916
- platform: "local",
917
- conversationId
918
- });
919
- if (!parsed.success) throw new Error(`Invalid local conversation id: ${conversationId}`);
920
- return parsed.data;
921
- }
922
- /**
923
- * Keep a stored Destination, or create the temporary local Destination.
924
- *
925
- * TODO(dcramer): Delete this module after Conversation and AgentRun use
926
- * Location, and web and event Turns no longer need a local
927
- * Destination.
928
- */
929
- function resolveConversationDestination(args) {
930
- return args.existing ?? requireLocalDestination(args.conversationId);
931
- }
932
- // src/chat/conversations/web-input.ts
933
- function normalizeEmail(email) {
934
- return email.trim().toLowerCase();
935
- }
936
- function stableHex(...parts) {
937
- return createHash("sha256").update(parts.join("\0")).digest("hex").slice(0, 24);
938
- }
939
- /**
940
- * Build a durable Conversation id for one web Actor and create key.
941
- *
942
- * Retries with the same key must address the same Conversation before the
943
- * mailbox Message id is derived.
944
- */
945
- function createConversationId(args) {
946
- return `local:web:${stableHex(normalizeEmail(args.actorEmail), args.idempotencyKey)}`;
947
- }
948
- /** Return the stable Turn id for one mailbox Message. */
949
- function conversationTurnIdForMessage(messageId) {
950
- return buildDeterministicTurnId(messageId);
951
- }
952
- /**
953
- * Store the dashboard participant in the current Conversation actor field.
954
- *
955
- * TODO(dcramer): Remove this StoredSlackActor conversion after Conversation
956
- * actor storage accepts web Actors directly.
957
- */
958
- function storedActorFromWeb(actor) {
959
- return {
960
- ...actor.email ? { email: normalizeEmail(actor.email) } : void 0,
961
- ...actor.fullName ? { fullName: actor.fullName } : void 0
962
- };
963
- }
964
- /**
965
- * Return whether a person can add a web Message to an existing
966
- * Conversation: a dashboard Conversation, a Slack thread, or a Thread.
967
- */
968
- function acceptsWebMessages(conversation) {
969
- if (!isTopLevel(conversation)) return conversation.kind === "thread";
970
- const { conversationId, destination } = conversation;
971
- if (destination?.platform === "slack") return true;
972
- return destination?.platform === "local" && conversationId.startsWith("local:web:");
973
- }
974
- /**
975
- * Build the web Actor for one signed-in User. Junior is the web provider,
976
- * so the provider-scoped Actor id is the User id.
977
- */
978
- function webActorFromUser(user, profile) {
979
- return {
980
- platform: "web",
981
- userId: user.id,
982
- email: normalizeEmail(user.email),
983
- ...user.displayName ? { fullName: user.displayName } : void 0,
984
- ...profile?.userName ? { userName: profile.userName } : void 0
985
- };
986
- }
987
- /** Build one web mailbox entry. */
988
- function buildWebInboundMessage(args) {
989
- const text = args.message.trim();
990
- if (!text && !args.attachments?.length) throw new Error("Web Message must not be empty");
991
- if (!args.actor.email) throw new Error("Web Actor requires a verified email");
992
- const nowMs = args.nowMs ?? Date.now();
993
- const traceContext = getActiveTraceContext();
994
- return {
995
- conversationId: args.conversationId,
996
- createdAtMs: args.createdAtMs ?? nowMs,
997
- delivery: args.delivery ?? "defer",
998
- ...args.destination ? { destination: args.destination } : void 0,
999
- inboundMessageId: args.messageId,
1000
- input: {
1001
- authorId: args.actor.userId,
1002
- ...args.authorIdentityId ? { authorIdentityId: args.authorIdentityId } : void 0,
1003
- text,
1004
- ...args.attachments?.length ? { attachments: args.attachments } : void 0,
1005
- ...args.reviewItemChange ? { reviewItemChange: args.reviewItemChange } : void 0,
1006
- metadata: {
1007
- authorEmail: normalizeEmail(args.actor.email),
1008
- ...args.actor.fullName && { authorFullName: args.actor.fullName },
1009
- authorUserId: args.actor.userId,
1010
- ...args.actor.userName && { authorUserName: args.actor.userName },
1011
- kind: "api_turn",
1012
- messageId: args.messageId
1013
- }
1014
- },
1015
- receivedAtMs: nowMs,
1016
- source: "web",
1017
- ...traceContext ? { traceContext } : void 0
1018
- };
1019
- }
1020
- /**
1021
- * Record web activity and create a Conversation root when needed. Returns the
1022
- * Destination for the Message's work. A child's work keeps none, so its
1023
- * workers read the Conversation.
1024
- */
1025
- async function recordWebConversationActivity(args) {
1026
- const store = args.conversationStore ?? getConversationStore();
1027
- const existing = await store.get({ conversationId: args.conversationId });
1028
- const destination = resolveConversationDestination({
1029
- conversationId: args.conversationId,
1030
- existing: existing?.destination
1031
- });
1032
- const isNewRoot = !existing;
1033
- const visibility = args.rootVisibility === "private" ? "private" : "public";
1034
- const source = isNewRoot ? createWebSource(args.conversationId, visibility) : void 0;
1035
- await store.recordActivity({
1036
- conversationId: args.conversationId,
1037
- ...existing?.destination ? void 0 : { destination },
1038
- nowMs: args.nowMs,
1039
- actor: storedActorFromWeb(args.actor),
1040
- ...isNewRoot ? { source: "web" } : void 0,
1041
- ...source ? { sessionSource: source } : void 0,
1042
- ...isNewRoot && args.rootTitle ? { title: args.rootTitle } : void 0,
1043
- ...isNewRoot ? { visibility } : void 0,
1044
- ...isNewRoot && args.rootKind ? { kind: args.rootKind } : void 0,
1045
- ...isNewRoot && args.rootSpaceId ? { spaceId: args.rootSpaceId } : void 0
1046
- });
1047
- return existing && !isTopLevel(existing) ? void 0 : destination;
1048
- }
1049
- /** Create a Conversation from web input and enqueue its first Message. */
1050
- async function createAndEnqueueConversation(input, options) {
1051
- if (!input.actor.email) throw new Error("Web Actor requires a verified email");
1052
- const conversationId = createConversationId({
1053
- actorEmail: input.actor.email,
1054
- idempotencyKey: input.idempotencyKey
1055
- });
1056
- return await appendAndEnqueueWebMessage({
1057
- actor: input.actor,
1058
- conversationId,
1059
- idempotencyKey: input.idempotencyKey,
1060
- message: input.message,
1061
- uploads: input.uploads,
1062
- ...input.title ? { rootTitle: input.title } : void 0,
1063
- rootVisibility: input.visibility === "private" ? "private" : "public",
1064
- ...input.spaceId ? { rootSpaceId: input.spaceId } : void 0
1065
- }, options);
1066
- }
1067
- async function appendAndEnqueueWebMessage(input, options) {
1068
- const text = input.message.trim();
1069
- if (!text && !input.uploads?.length) throw new Error("Web Message must not be empty");
1070
- if (!input.actor.email) throw new Error("Web Actor requires a verified email");
1071
- const nowMs = options.nowMs ?? Date.now();
1072
- const messageId = await webMessageId({
1073
- conversationId: input.conversationId,
1074
- idempotencyKey: input.idempotencyKey
1075
- });
1076
- const destination = await recordWebConversationActivity({
1077
- actor: input.actor,
1078
- conversationId: input.conversationId,
1079
- conversationStore: options.conversationStore,
1080
- nowMs,
1081
- ...input.rootTitle && { rootTitle: input.rootTitle },
1082
- ...input.rootVisibility && { rootVisibility: input.rootVisibility },
1083
- ...input.rootSpaceId && { rootSpaceId: input.rootSpaceId }
1084
- });
1085
- let attachments = [];
1086
- if (input.uploads?.length) {
1087
- if (!options.attachmentStorage) throw new Error("Attachment storage is unavailable.");
1088
- attachments = await recordAttachmentUploads({
1089
- conversationId: input.conversationId,
1090
- db: getSqlExecutor(),
1091
- nowMs,
1092
- storage: options.attachmentStorage,
1093
- uploads: input.uploads
1094
- });
1095
- }
1096
- const enqueue = options.exclusive ? appendAndEnqueueExclusiveInboundMessage : appendAndEnqueueInboundMessage;
1097
- const authorIdentityId = await resolveActorIdentityId(getSqlExecutor(), input.actor);
1098
- const enqueueTo = (destination) => enqueue({
1099
- message: buildWebInboundMessage({
1100
- actor: input.actor,
1101
- authorIdentityId,
1102
- conversationId: input.conversationId,
1103
- delivery: input.delivery,
1104
- destination,
1105
- message: text,
1106
- attachments,
1107
- messageId,
1108
- nowMs,
1109
- ...input.reviewItemChange && { reviewItemChange: input.reviewItemChange }
1110
- }),
1111
- conversationStore: options.conversationStore,
1112
- nowMs,
1113
- queue: options.queue,
1114
- state: options.state
1115
- });
1116
- let result;
1117
- try {
1118
- result = await enqueueTo(destination);
1119
- } catch (error) {
1120
- if (!destination) throw error;
1121
- const stored = await (options.conversationStore ?? getConversationStore()).get({ conversationId: input.conversationId });
1122
- const current = resolveConversationDestination({
1123
- conversationId: input.conversationId,
1124
- existing: stored?.destination
1125
- });
1126
- if (sameDestination(current, destination)) throw error;
1127
- result = await enqueueTo(current);
1128
- }
1129
- const status = result.status === "appended" ? "accepted" : result.status;
1130
- return {
1131
- conversationId: input.conversationId,
1132
- messageId,
1133
- status
1134
- };
1135
- }
1136
- // src/chat/lead/conversation.ts
1137
- /**
1138
- * The Lead of one Space: the Space's top-level Conversation that finds,
1139
- * starts, and steers the Space's other Conversations. It has the Space's
1140
- * visibility. Its members talk to it, and a unique index keeps one Lead for
1141
- * each Space. Its title is the Space's name.
1142
- */
1143
- const UNIQUE_VIOLATION = "23505";
1144
- /** Return the Lead of a Space, if it has one. */
1145
- async function readSpaceLead(spaceId) {
1146
- const [row] = await getDb().select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(eq(juniorConversations.kind, "lead"), eq(juniorConversations.spaceId, spaceId))).limit(1);
1147
- return row ? await getConversationStore().get({ conversationId: row.conversationId }) : void 0;
1148
- }
1149
- /**
1150
- * Return the Lead of a Space, and create it on first use. The member who
1151
- * creates it is its first Actor. It has the Space's visibility and its own
1152
- * Destination, so it reads other Conversations by the usual rules.
1153
- */
1154
- async function getSpaceLead(args) {
1155
- const existing = await readSpaceLead(args.space.id);
1156
- if (existing) return existing;
1157
- try {
1158
- await recordWebConversationActivity({
1159
- actor: webActorFromUser(args.member),
1160
- conversationId: `local:web:${randomUUID()}`,
1161
- nowMs: Date.now(),
1162
- rootKind: "lead",
1163
- rootSpaceId: args.space.id,
1164
- rootTitle: args.space.name,
1165
- rootVisibility: args.space.visibility
1166
- });
1167
- } catch (error) {
1168
- if (!isPostgresErrorCode(error, UNIQUE_VIOLATION)) throw error;
1169
- }
1170
- const created = await readSpaceLead(args.space.id);
1171
- if (!created) throw new Error("The Lead was not saved");
1172
- return created;
1173
- }
1174
- /**
1175
- * Return the id and visibility of a Lead's Space. Returns nothing for a
1176
- * Conversation that is not a Lead.
1177
- */
1178
- async function readLeadSpace(conversationId) {
1179
- const [row] = await getDb().select({
1180
- id: juniorSpaces.id,
1181
- visibility: juniorSpaces.visibility
1182
- }).from(juniorConversations).innerJoin(juniorSpaces, eq(juniorSpaces.id, juniorConversations.spaceId)).where(and(eq(juniorConversations.conversationId, conversationId), eq(juniorConversations.kind, "lead"))).limit(1);
1183
- return row;
1184
- }
1185
- /**
1186
- * Return whether a person may send a Message to a Conversation now, as far
1187
- * as its Space decides: only members of a Space that is not archived message
1188
- * its Lead. Every other Conversation leaves the decision to its access rules.
1189
- */
1190
- async function spaceTakesMessagesFrom(conversation, userId) {
1191
- if (!messagesNeedSpaceMembership(conversation.kind) || !conversation.spaceId) return true;
1192
- const space = await readSpace(userId, conversation.spaceId);
1193
- return Boolean(space?.viewerIsMember && !space.archivedAt);
1194
- }
1195
- // src/chat/task-execution/turn-membership.ts
1196
- /** True when the committed message at `seq` belongs to the Turn. */
1197
- function isTurnMessage(start, seq, message) {
1198
- return seq > start.seq && message.role !== "system";
1199
- }
1200
- /**
1201
- * The messages of a saved Turn with their provenance. Without a
1202
- * `turn_started` event, nothing tells this Turn from earlier history, so it
1203
- * has no messages.
1204
- */
1205
- function savedTurnMessages(record, start) {
1206
- if (!start) return [];
1207
- return record.piMessages.flatMap((message, index) => {
1208
- const seq = record.piMessageSeqs[index];
1209
- return seq !== void 0 && isTurnMessage(start, seq, message) ? [{
1210
- message,
1211
- provenance: record.piMessageProvenance[index] ?? { authority: "context" }
1212
- }] : [];
1213
- });
1214
- }
1215
- // src/chat/services/turn-session-routing.ts
1216
- async function loadConversationChain(conversationId, conversationStore) {
1217
- const chain = [];
1218
- const seen = /* @__PURE__ */ new Set();
1219
- let cursor = conversationId;
1220
- while (cursor && !seen.has(cursor)) {
1221
- seen.add(cursor);
1222
- const conversation = await conversationStore.get({ conversationId: cursor });
1223
- if (!conversation) break;
1224
- chain.push(conversation);
1225
- cursor = conversation.parentConversationId;
1226
- }
1227
- return chain;
1228
- }
1229
- /**
1230
- * Normalize a stored Slack session source against the conversation destination.
1231
- *
1232
- * Does not create channel or thread values from the conversation id.
1233
- */
1234
- function slackSourceForDestination(args) {
1235
- if (args.source?.kind !== "slack" || args.source.channelId !== args.destination.channelId) return;
1236
- const threadTs = args.source.threadTs?.trim();
1237
- return {
1238
- kind: "slack",
1239
- visibility: args.source.visibility ?? "public",
1240
- teamId: args.source.teamId?.trim() || args.destination.teamId,
1241
- channelId: args.source.channelId,
1242
- ...threadTs ? { threadTs } : void 0
1243
- };
1244
- }
1245
- /**
1246
- * Resolve the Conversation Location, Destination, and session Source.
1247
- *
1248
- * Reads parent Conversations when this Conversation has no Destination.
1249
- */
1250
- async function resolveConversationRouting(args) {
1251
- const conversationStore = args.conversationStore ?? (await import("./db-DXTOYRzR.js").then((n) => n.t)).getConversationStore();
1252
- const chain = await loadConversationChain(args.conversationId, conversationStore);
1253
- let destination;
1254
- let source;
1255
- let location;
1256
- for (const conversation of chain) {
1257
- destination ??= conversation.destination;
1258
- source ??= conversation.sessionSource;
1259
- location ??= conversation.location;
1260
- if (destination && source) break;
1261
- }
1262
- if (!destination) return;
1263
- if (destination.platform === "slack") {
1264
- const slackSource = slackSourceForDestination({
1265
- destination,
1266
- source
1267
- });
1268
- return {
1269
- destination,
1270
- ...location ? { location } : void 0,
1271
- ...slackSource ? { source: slackSource } : void 0
1272
- };
1273
- }
1274
- return {
1275
- destination,
1276
- ...location ? { location } : void 0,
1277
- ...source ? { source } : void 0
1278
- };
1279
- }
1280
- /** Require the Conversation Destination and Source from SQL. */
1281
- async function resolveTurnSessionRouting(args) {
1282
- const routing = await resolveConversationRouting(args);
1283
- if (!routing?.destination || !routing.source) throw new Error(`Conversation ${args.conversationId} is missing durable routing metadata`);
1284
- return {
1285
- destination: routing.destination,
1286
- ...routing.location ? { location: routing.location } : void 0,
1287
- source: routing.source
1288
- };
1289
- }
1290
- /**
1291
- * Require the Destination and Source to resume a Turn.
1292
- *
1293
- * A dispatch Conversation stores the dispatch Source, which has no session
1294
- * Source. Its dispatch record owns the Destination and Source.
1295
- */
1296
- async function resolveTurnResumeRouting(args) {
1297
- if (!args.dispatchId) return await resolveTurnSessionRouting(args);
1298
- const dispatch = await getDispatchRecord(args.dispatchId);
1299
- if (!dispatch) throw new Error(`Dispatch record is missing for ${args.dispatchId}`);
1300
- const dispatchConversationId = getDispatchConversationId(dispatch);
1301
- if (dispatchConversationId !== args.conversationId) throw new Error(`Dispatch ${dispatch.id} belongs to ${dispatchConversationId}, not ${args.conversationId}`);
1302
- const location = (await resolveConversationRouting(args))?.location;
1303
- return {
1304
- destination: dispatch.destination,
1305
- ...location ? { location } : void 0,
1306
- source: dispatch.source
1307
- };
1308
- }
1309
- export { fileFields as A, zodToolDefinition as B, joinSpace as C, readSpace as D, listSpaces as E, storeAttachments as F, juniorToolOutputSchema as H, storeDeferredAttachment as I, AttachmentSourceUnavailableError as L, readLiveAttachment as M, requestAttachmentDeletion as N, updateSpace as O, storeAttachment as P, parseToolInput as R, createSpace as S, listSpaceMembers as T, makeStructuredToolOutput as U, injectContinuationToolName as V, AttachmentUploadError as _, getSpaceLead as a, verifyAttachmentUploads as b, spaceTakesMessagesFrom as c, conversationTurnIdForMessage as d, createAndEnqueueConversation as f, resolveConversationDestination as g, webActorFromUser as h, savedTurnMessages as i, isFileAttachment as j, collectAttachmentGarbage as k, acceptsWebMessages as l, recordWebConversationActivity as m, resolveTurnResumeRouting as n, readLeadSpace as o, createConversationId as p, isTurnMessage as r, readSpaceLead as s, resolveConversationRouting as t, appendAndEnqueueWebMessage as u, collectAttachmentUploadGarbage as v, leaveSpace as w, writeAttachmentUpload as x, createAttachmentUpload as y, zodTool as z };