@sentry/junior 0.311.0 → 0.312.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 (118) hide show
  1. package/dist/{adapter-context-G2M0y6rP.js → adapter-context-BRjEWRy1.js} +2 -2
  2. package/dist/{adapter-B1wujchl.js → adapter-iIq7ihf7.js} +1 -1
  3. package/dist/{admin-DCiBhUT1.js → admin-DhInw5K9.js} +1 -1
  4. package/dist/{agent-runner-BVHPUIc8.js → agent-runner-C9iDurwX.js} +3423 -3477
  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 +289 -306
  9. package/dist/{app-Cw5Vy6H6.d.ts → app-DRFrC8Mw.d.ts} +2 -9
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +338 -604
  12. package/dist/{background-compaction-queue-CJDnWVOJ.js → background-compaction-queue-DrKi7w3d.js} +10 -85
  13. package/dist/callback-mFlTUWWx.js +75 -0
  14. package/dist/{catalog-runtime-DMY3VV-D.js → catalog-runtime-D7xapBAX.js} +1 -1
  15. package/dist/channel-access-CJGfNTdn.js +221 -0
  16. package/dist/child-message-DcsritGf.js +179 -0
  17. package/dist/cli/chat.js +18 -19
  18. package/dist/cli/check.js +3 -3
  19. package/dist/cli/init.js +0 -1
  20. package/dist/cli/main.js +3 -7
  21. package/dist/cli/plugins.js +4 -4
  22. package/dist/cli/run.d.ts +1 -2
  23. package/dist/cli/run.js +1 -2
  24. package/dist/cli/snapshot-create.js +5 -5
  25. package/dist/cli/upgrade.d.ts +1 -1
  26. package/dist/cli/upgrade.js +3 -3
  27. package/dist/{config-BrXDQefC.js → config-kXB2Y5tl.js} +59 -27
  28. package/dist/{continue-in-slack-DNXSC9So.js → continue-in-slack-O6pV5004.js} +7 -8
  29. package/dist/{conversation-feed-DkinDu5o.js → conversation-feed-uNOv_x68.js} +74 -20
  30. package/dist/{conversation-privacy-DxttrKb9.js → conversation-privacy-L4ja1_W6.js} +1 -1
  31. package/dist/{conversation-turn-DWw7Xhdr.js → conversation-turn-CeLbHqdw.js} +31 -27
  32. package/dist/{credential-sync-Bk8wGb8Y.js → credential-sync-I8VBGk05.js} +16 -15
  33. package/dist/{projection-Cns7XwWa.js → credentialed-Cb6E2phL.js} +16308 -20732
  34. package/dist/{db-7ETESH44.d.ts → db-BbC5stfa.d.ts} +11 -6
  35. package/dist/{db-DTxzH7u5.js → db-LAyyX8tk.js} +174 -91
  36. package/dist/{executor-DqTiYj9S.js → executor-SCub-fAq.js} +117 -97
  37. package/dist/{html-B9Sl4Axb.js → html-BCZ3Xtb_.js} +6 -6
  38. package/dist/ingest-BDf3D50j.js +3836 -0
  39. package/dist/{install-Sg4ePfLl.js → install-DCFJFkC0.js} +2 -2
  40. package/dist/instrumentation.js +3 -3
  41. package/dist/{lineage-BHAMpNKr.js → lineage-B_m-4TJw.js} +2 -2
  42. package/dist/{stop-CYsfc0Ed.js → list-CN2QA2R9.js} +663 -442
  43. package/dist/{logging-FjclQsXu.js → logging-dQ9ZRGQ8.js} +1 -1
  44. package/dist/{schedule-BLJ476XQ.js → media-CYm1QD8T.js} +1055 -11
  45. package/dist/{message-CJ7_RL50.js → message-DSXGj1hM.js} +19 -26
  46. package/dist/{model-input-CMLh4Cwq.js → model-input--TrP9hYV.js} +3 -3
  47. package/dist/nitro.d.ts +1 -1
  48. package/dist/nitro.js +4 -3
  49. package/dist/{oauth-callback-server-RVcbiDjL.js → oauth-callback-server-DHCZC6B4.js} +2 -2
  50. package/dist/{oauth-relay-Bu9kkaQu.js → oauth-relay-pPMGnDZt.js} +1 -1
  51. package/dist/{registry-BPwuOP2O.js → registry-CZOzddwu.js} +1 -1
  52. package/dist/{resolve-BK29bBry.js → resolve-cKOQ14Dh.js} +3 -3
  53. package/dist/result-DcvEOe1r.js +574 -0
  54. package/dist/result-event-type-BdIJuZxg.js +48 -0
  55. package/dist/{runner-BcAE-cJm.js → runner-DBfUW44l.js} +14 -16
  56. package/dist/{sandbox-egress-signals-C-q0go5b.js → sandbox-egress-signals-BVF_xAm1.js} +1 -1
  57. package/dist/{schema-DYcJeV7d.d.ts → schema-BEHKxr4I.d.ts} +166 -242
  58. package/dist/{schema-BLgSZXcL.js → schema-Bk9Nm2E8.js} +106 -121
  59. package/dist/{service-account-iJoCtkHR.js → service-account-CVYsFjty.js} +3 -3
  60. package/dist/{service-account-gN0zqf0S.js → service-account-Ts4ulcrV.js} +5 -5
  61. package/dist/{skills-BoZ80epJ.js → skills-VTnhAJWm.js} +2 -2
  62. package/dist/{slack-conversation-unfurl-CogYrITA.js → slack-conversation-unfurl-fuLnF1jE.js} +9 -9
  63. package/dist/{spawn-Dk92r7mX.js → spawn-vxAarlX5.js} +6 -5
  64. package/dist/start-conversation-CEn2KH1A.js +941 -0
  65. package/dist/{state-DH3Cmgp3.js → state-C1P3_Ywk.js} +4 -4
  66. package/dist/statuses-_cRJHXK7.js +150 -0
  67. package/dist/store-DFZaN-Ix.js +492 -0
  68. package/dist/task-queue-Cx4Lmjyk.js +90 -0
  69. package/dist/task-runner-CbTwFA6k.js +1432 -0
  70. package/dist/{thread-context-BW2BsQbH.js → thread-context-BkAZDTX2.js} +7 -7
  71. package/dist/thread-state-DhPndWi1.js +5625 -0
  72. package/dist/{validation-DrJd0nnq.js → validation-nIzMtAVJ.js} +1 -1
  73. package/dist/{task-queue-C_zldF5J.js → vercel-queue-hW90XzbG.js} +93 -172
  74. package/dist/{version-CNKZ8owc.js → version-Brbtz4Qf.js} +1 -1
  75. package/dist/version.js +1 -1
  76. package/dist/{warmup-BWdHew2H.js → warmup-BDA5myRK.js} +6463 -12290
  77. package/dist/web-message-id-C6P83ans.js +10 -0
  78. package/dist/{worker-t9qpu_Zx.js → worker-D63RcaVD.js} +20 -7
  79. package/migrations/0143_todos.sql +14 -0
  80. package/migrations/0144_inbox_items.sql +32 -0
  81. package/migrations/0145_todo_changed_by_agent.sql +1 -0
  82. package/migrations/0146_inbox_item_subject_title_parts.sql +1 -0
  83. package/migrations/0147_inbox_snooze_wake_reason.sql +1 -0
  84. package/migrations/0148_authorization_request_index.sql +1 -0
  85. package/migrations/0149_conversation_metadata.sql +10 -0
  86. package/migrations/0150_conversation_metadata_fill.sql +39 -0
  87. package/migrations/0151_conversation_search_index.sql +1 -0
  88. package/migrations/0152_inbox_item_legacy_automation_keys.sql +21 -0
  89. package/migrations/0153_artifact_expiry.sql +1 -0
  90. package/migrations/0154_artifact_permanent_sha_index.sql +1 -0
  91. package/migrations/0155_artifact_drop_public_sha_index.sql +3 -0
  92. package/migrations/0156_conversation_kind_lead.sql +6 -0
  93. package/migrations/0157_conversation_lead_actor_index.sql +1 -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/_journal.json +106 -1
  110. package/package.json +6 -6
  111. package/skills/design-automation-skill/SKILL.md +108 -0
  112. package/dist/briefs-BDjnug6Y.js +0 -395
  113. package/dist/conversation-ca__NDQW.js +0 -1063
  114. package/dist/prompt-CDqcsDYC.js +0 -910
  115. package/dist/store-DmmMIrQi.js +0 -335
  116. package/dist/task-runner-C7oCJQIx.js +0 -294
  117. package/dist/turn-session-routing-Xh_2nSQe.js +0 -261
  118. package/dist/web-message-id-Ch5dPq-a.js +0 -306
@@ -0,0 +1,941 @@
1
+ import { Ar as getDispatchConversationId, Eo as SlackActionError, Fo as readPrivateSlackFile, Lo as streamPrivateSlackFile, Nr as getDispatchRecord, io as conversationWatch, wi as getDashboardConversationLink } from "./credentialed-Cb6E2phL.js";
2
+ import { ht as bufferBody } from "./config-kXB2Y5tl.js";
3
+ import { t as mapBounded } from "./fan-out-Cod-yEHG.js";
4
+ import { o as getActiveTraceContext } from "./logging-dQ9ZRGQ8.js";
5
+ import "./actor-BsBdxDXQ.js";
6
+ import { $t as resolveActorIdentityId, A as isTopLevelKind, Fn as conversationDetailTouch, Vn as sameDestination, a as getConversationStore, fn as ToolInputError, nt as conversationKindSql, o as getDb, s as getSqlExecutor } from "./db-LAyyX8tk.js";
7
+ import { B as juniorAttachments, C as juniorConversationParticipants, H as juniorConversations, K as juniorUsers, M as juniorConversationEvents, U as juniorIdentities, n as isPostgresErrorCode, z as juniorAttachmentUploads } from "./executor-SCub-fAq.js";
8
+ import { d as contextProvenance } from "./history-CYstOMKX.js";
9
+ import { L as buildDeterministicTurnId, W as openConversationProjection, c as appendAndEnqueueExclusiveInboundMessage, l as appendAndEnqueueInboundMessage, z as commitMessages } from "./thread-state-DhPndWi1.js";
10
+ import { i as isVisionImageMediaType, r as detectImageMediaType } from "./media-CYm1QD8T.js";
11
+ import { t as getVercelConversationWorkQueue } from "./vercel-queue-hW90XzbG.js";
12
+ import { a as recordUploadedAttachment, i as readLiveAttachment, n as fileFields, u as AttachmentSourceUnavailableError } from "./store-DFZaN-Ix.js";
13
+ import { t as webMessageId } from "./web-message-id-C6P83ans.js";
14
+ import * as z from "zod";
15
+ import { createHash, randomUUID } from "node:crypto";
16
+ import { createWebSource, localDestinationSchema, subscribableResourceSchema } from "@sentry/junior-plugin-api";
17
+ import { and, asc, eq, gt, inArray, isNull, lte, sql } from "drizzle-orm";
18
+ import { alias } from "drizzle-orm/pg-core";
19
+ // src/chat/tool-support/structured-result.ts
20
+ const juniorToolContinuationSchema = z.object({
21
+ arguments: z.record(z.string(), z.unknown()),
22
+ reason: z.string().min(1).optional()
23
+ }).strict();
24
+ const juniorToolBoundContinuationSchema = juniorToolContinuationSchema.extend({ tool_name: z.string().min(1) });
25
+ /** Shared optional fields for canonical Junior tool outputs. */
26
+ const juniorToolOutputSchema = z.object({
27
+ target: z.string().min(1).optional(),
28
+ truncated: z.boolean().optional(),
29
+ /** True when this attempt did not finish before its time budget. */
30
+ timed_out: z.boolean().optional(),
31
+ continuation: juniorToolContinuationSchema.optional()
32
+ }).passthrough();
33
+ function sortJsonValue(value) {
34
+ if (Array.isArray(value)) return value.map(sortJsonValue);
35
+ if (!value || typeof value !== "object") return value;
36
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => [key, sortJsonValue(item)]));
37
+ }
38
+ const continuationDetailsSchema = z.looseObject({ continuation: z.looseObject({}) });
39
+ /** Bind continuation metadata to the exposed runtime tool name. */
40
+ function injectContinuationToolName(details, toolName) {
41
+ const parsed = continuationDetailsSchema.safeParse(details);
42
+ if (!parsed.success) return details;
43
+ return {
44
+ ...parsed.data,
45
+ continuation: juniorToolBoundContinuationSchema.parse({
46
+ ...parsed.data.continuation,
47
+ tool_name: toolName
48
+ })
49
+ };
50
+ }
51
+ function makeStructuredToolOutput(details, options = {}) {
52
+ return {
53
+ content: [{
54
+ type: "text",
55
+ text: JSON.stringify(sortJsonValue(details))
56
+ }, ...options.content ?? []],
57
+ details
58
+ };
59
+ }
60
+ // src/chat/tool-support/zod-tool.ts
61
+ function isContentOnlyToolResult(value) {
62
+ return value !== null && typeof value === "object" && Array.isArray(value.content) && !("details" in value);
63
+ }
64
+ function isStructuredToolResultEnvelope(value) {
65
+ return value !== null && typeof value === "object" && Array.isArray(value.content) && "details" in value;
66
+ }
67
+ function parseToolContent(content) {
68
+ 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.");
69
+ return content;
70
+ }
71
+ function formatZodPath(path) {
72
+ return path.length > 0 ? path.map(String).join(".") : "root";
73
+ }
74
+ function formatToolInputError(error) {
75
+ return `Invalid tool arguments: ${error.issues.slice(0, 5).map((issue) => `${formatZodPath(issue.path)}: ${issue.message}`).join("; ") || "input did not match schema"}`;
76
+ }
77
+ /** Parse tool input with its Zod schema, as a model-repairable error on failure. */
78
+ function parseToolInput(schema, args) {
79
+ const result = schema.safeParse(args);
80
+ if (!result.success) throw new ToolInputError(formatToolInputError(result.error), { cause: result.error });
81
+ return result.data;
82
+ }
83
+ /** Declare the static definition of a Zod tool once, for the registry and its factory. */
84
+ function zodToolDefinition(definition) {
85
+ return definition;
86
+ }
87
+ function zodTool(definition) {
88
+ const { inputSchema, outputSchema, prepareArguments, execute, ...toolDef } = definition;
89
+ let modelInputSchema;
90
+ try {
91
+ modelInputSchema = z.toJSONSchema(inputSchema);
92
+ } catch (error) {
93
+ throw new TypeError("zodTool() inputSchema must be representable as JSON Schema.", { cause: error });
94
+ }
95
+ let modelOutputSchema;
96
+ if (outputSchema) try {
97
+ modelOutputSchema = z.toJSONSchema(outputSchema);
98
+ } catch (error) {
99
+ throw new TypeError("zodTool() outputSchema must be representable as JSON Schema.", { cause: error });
100
+ }
101
+ return {
102
+ ...toolDef,
103
+ inputSchema: modelInputSchema,
104
+ ...modelOutputSchema ? { outputSchema: modelOutputSchema } : void 0,
105
+ prepareArguments(args) {
106
+ return parseToolInput(inputSchema, prepareArguments ? prepareArguments(args) : args);
107
+ },
108
+ ...execute ? { async execute(input, options) {
109
+ const result = await execute(input, options);
110
+ if (!outputSchema) {
111
+ if (isContentOnlyToolResult(result)) return result;
112
+ throw new TypeError("zodTool() content-only tools must return { content } without details.");
113
+ }
114
+ if (isStructuredToolResultEnvelope(result)) return {
115
+ content: parseToolContent(result.content),
116
+ details: outputSchema.parse(result.details)
117
+ };
118
+ return outputSchema.parse(result);
119
+ } } : void 0
120
+ };
121
+ }
122
+ // src/chat/slack/attachments.ts
123
+ /** Save the vision summary for a stored Slack attachment. */
124
+ async function recordSlackAttachment(args) {
125
+ const db = args.db.db();
126
+ await db.with(conversationDetailTouch(db, [args.conversationId])).update(juniorAttachments).set({ visionSummary: args.visionSummary }).where(and(eq(juniorAttachments.id, args.attachmentId), eq(juniorAttachments.conversationId, args.conversationId), isNull(juniorAttachments.deleteRequestedAt)));
127
+ }
128
+ /** Read a saved vision summary for one live attachment. */
129
+ async function readAttachmentVisionSummary(args) {
130
+ const [row] = await args.db.db().select({ visionSummary: juniorAttachments.visionSummary }).from(juniorAttachments).where(and(eq(juniorAttachments.id, args.attachmentId), eq(juniorAttachments.conversationId, args.conversationId), isNull(juniorAttachments.deleteRequestedAt)));
131
+ return row?.visionSummary;
132
+ }
133
+ /** Match live conversation attachments to Slack file ids. */
134
+ async function matchSlackAttachments(args) {
135
+ if (args.providerIds.length === 0) return [];
136
+ return (await args.db.db().select({
137
+ id: juniorAttachments.id,
138
+ providerId: juniorAttachments.providerId,
139
+ bytes: juniorAttachments.bytes,
140
+ contentType: juniorAttachments.contentType,
141
+ storageKey: juniorAttachments.storageKey,
142
+ storageProvider: juniorAttachments.storageProvider,
143
+ title: juniorAttachments.title
144
+ }).from(juniorAttachments).where(and(eq(juniorAttachments.conversationId, args.conversationId), eq(juniorAttachments.provider, "slack"), inArray(juniorAttachments.providerId, args.providerIds), isNull(juniorAttachments.deleteRequestedAt)))).map((row) => {
145
+ const { bytes, contentType, filename } = fileFields(row);
146
+ const attachment = {
147
+ bytes,
148
+ contentType,
149
+ filename,
150
+ id: row.id,
151
+ providerId: row.providerId
152
+ };
153
+ return row.storageKey === null ? {
154
+ ...attachment,
155
+ pending: true
156
+ } : attachment;
157
+ });
158
+ }
159
+ /**
160
+ * Fingerprint the live Slack attachments that `matchSlackAttachments` can
161
+ * return for a Conversation. It changes when one is recorded, stored, or
162
+ * deleted, so a reader can tell that stored messages may now show other
163
+ * files, or a file that is no longer pending.
164
+ */
165
+ function slackAttachmentsVersionQuery(db, conversationId) {
166
+ return db.select({ version: sql`coalesce(md5(string_agg(concat(${juniorAttachments.id}, ':', ${juniorAttachments.storageKey} is null), ',' order by ${juniorAttachments.id})), '')` }).from(juniorAttachments).where(and(eq(juniorAttachments.conversationId, conversationId), eq(juniorAttachments.provider, "slack"), isNull(juniorAttachments.deleteRequestedAt)));
167
+ }
168
+ /** Read the Slack file identity retained by the Chat SDK. */
169
+ function getSlackFileId(attachment) {
170
+ const metadataId = attachment.fetchMetadata?.["fileId"];
171
+ if (metadataId) return metadataId;
172
+ return (attachment.url ?? attachment.fetchMetadata?.["url"] ?? "").match(/(?:^|[-/])(F[A-Z0-9]+)(?:[-/]|$)/)?.[1];
173
+ }
174
+ /**
175
+ * Look up a Slack file that Junior recorded without storing it yet.
176
+ *
177
+ * Uses the installation token that the caller binds: the Slack turn, or the
178
+ * dashboard route for the conversation's Slack team.
179
+ */
180
+ const readSlackAttachmentSource = async (source) => {
181
+ const unavailable = (cause) => new AttachmentSourceUnavailableError("The Slack file was deleted, or this app can no longer access it.", { cause });
182
+ if (source.provider !== "slack") throw unavailable();
183
+ const file = await readPrivateSlackFile(source.id);
184
+ if (!file) throw unavailable();
185
+ return {
186
+ bytes: file.bytes,
187
+ open: async () => {
188
+ try {
189
+ return await streamPrivateSlackFile(file.url);
190
+ } catch (error) {
191
+ if (error instanceof SlackActionError && (error.code === "not_found" || error.statusCode === 403)) throw unavailable(error);
192
+ throw error;
193
+ }
194
+ }
195
+ };
196
+ };
197
+ // src/chat/agent-invocations/fork-history.ts
198
+ /** Instructions that a fork child reads with its first task. */
199
+ const FORK_INSTRUCTIONS = "You are a fork of your parent agent. The messages before your first parent task are copied from the parent's conversation so you have its context. They are not your job: your job is the parent task below. Sandbox files, approvals, and credentials of the parent were not copied, and your sandbox is separate. Verify files in your own sandbox before you use them.";
200
+ /**
201
+ * Cut parent history for a fork: everything before the parent's message that
202
+ * started the fork, through the last point where every tool call has its
203
+ * result. A model request with an unanswered tool call fails, and the parent
204
+ * can commit its history in the middle of a tool round.
205
+ */
206
+ function forkHistoryFrom(messages, parentToolCallId) {
207
+ const spawnIndex = parentToolCallId ? messages.findIndex((message) => message.role === "assistant" && message.content.some((part) => part.type === "toolCall" && part.id === parentToolCallId)) : -1;
208
+ const before = spawnIndex >= 0 ? messages.slice(0, spawnIndex) : messages;
209
+ const pending = /* @__PURE__ */ new Set();
210
+ let end = 0;
211
+ for (const [index, message] of before.entries()) {
212
+ if (message.role === "assistant") {
213
+ for (const part of message.content) if (part.type === "toolCall") pending.add(part.id);
214
+ } else if (message.role === "toolResult") pending.delete(message.toolCallId);
215
+ if (pending.size === 0) end = index + 1;
216
+ }
217
+ return before.slice(0, end);
218
+ }
219
+ /**
220
+ * Load the start history of a fork child from its parent Conversation.
221
+ */
222
+ async function loadForkHistory(invocation) {
223
+ return forkHistoryFrom((await openConversationProjection({ conversationId: invocation.parentConversationId })).messages, invocation.parentToolCallId);
224
+ }
225
+ async function hasTurnStarted(conversationId) {
226
+ const [row] = await getSqlExecutor().db().select({ seq: juniorConversationEvents.seq }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "turn_started"))).limit(1);
227
+ return row !== void 0;
228
+ }
229
+ /**
230
+ * Commit the start history of a fork child before its first Turn starts, so
231
+ * the history is below the Turn start. A child that already has agent
232
+ * history, such as on a retry, commits nothing. A child whose Turn already
233
+ * started commits nothing too: the history would be Turn messages, and a
234
+ * parent `reply` in it would read as the Turn's answer. Only a worker that
235
+ * committed fork history after the Turn start leaves such a child.
236
+ */
237
+ async function commitForkHistory(args) {
238
+ if ((await openConversationProjection({ conversationId: args.childConversationId })).messages.length > 0 || await hasTurnStarted(args.childConversationId)) return;
239
+ const messages = await loadForkHistory(args);
240
+ if (messages.length === 0) return;
241
+ await commitMessages({
242
+ conversationId: args.childConversationId,
243
+ messages,
244
+ provenance: messages.map(() => contextProvenance)
245
+ });
246
+ }
247
+ /** True for agent history that a fork child inherited from its parent. */
248
+ function isInheritedForkHistory(event, firstEvent) {
249
+ return firstEvent !== void 0 && event.seq > firstEvent.seq && event.createdAtMs < firstEvent.createdAtMs && (event.data.type === "assistant_message" || event.data.type === "tool_result");
250
+ }
251
+ const firstRow = alias(juniorConversationEvents, "first_event");
252
+ /**
253
+ * SQL filter for event rows that a fork child did not inherit from its
254
+ * parent. Usage reports use it, so inherited model calls count only in the
255
+ * parent. It reads only a lower seq, the Conversation's first event, so a
256
+ * counted row never changes whether it counts.
257
+ */
258
+ function notInheritedByForkChild() {
259
+ return sql`not coalesce(${juniorConversationEvents.createdAt} < (
260
+ select ${firstRow.createdAt}
261
+ from ${juniorConversationEvents} as ${sql.identifier("first_event")}
262
+ where ${firstRow.conversationId} = ${juniorConversationEvents.conversationId}
263
+ and ${firstRow.seq} < ${juniorConversationEvents.seq}
264
+ order by ${firstRow.seq}
265
+ limit 1
266
+ ), false)`;
267
+ }
268
+ // src/chat/services/turn-session-routing.ts
269
+ async function loadConversationChain(conversationId, conversationStore) {
270
+ const chain = [];
271
+ const seen = /* @__PURE__ */ new Set();
272
+ let cursor = conversationId;
273
+ while (cursor && !seen.has(cursor)) {
274
+ seen.add(cursor);
275
+ const conversation = await conversationStore.get({ conversationId: cursor });
276
+ if (!conversation) break;
277
+ chain.push(conversation);
278
+ cursor = conversation.parentConversationId;
279
+ }
280
+ return chain;
281
+ }
282
+ /**
283
+ * Normalize a stored Slack session source against the conversation destination.
284
+ *
285
+ * Does not create channel or thread values from the conversation id.
286
+ */
287
+ function slackSourceForDestination(args) {
288
+ if (args.source?.kind !== "slack" || args.source.channelId !== args.destination.channelId) return;
289
+ const threadTs = args.source.threadTs?.trim();
290
+ return {
291
+ kind: "slack",
292
+ visibility: args.source.visibility ?? "public",
293
+ teamId: args.source.teamId?.trim() || args.destination.teamId,
294
+ channelId: args.source.channelId,
295
+ ...threadTs ? { threadTs } : void 0
296
+ };
297
+ }
298
+ /**
299
+ * Resolve the Conversation Location, Destination, and session Source.
300
+ *
301
+ * Reads parent Conversations when this Conversation has no Destination.
302
+ */
303
+ async function resolveConversationRouting(args) {
304
+ const conversationStore = args.conversationStore ?? (await import("./db-LAyyX8tk.js").then((n) => n.n)).getConversationStore();
305
+ const chain = await loadConversationChain(args.conversationId, conversationStore);
306
+ let destination;
307
+ let source;
308
+ let location;
309
+ for (const conversation of chain) {
310
+ destination ??= conversation.destination;
311
+ source ??= conversation.sessionSource;
312
+ location ??= conversation.location;
313
+ if (destination && source) break;
314
+ }
315
+ if (!destination) return;
316
+ if (destination.platform === "slack") {
317
+ const slackSource = slackSourceForDestination({
318
+ destination,
319
+ source
320
+ });
321
+ return {
322
+ destination,
323
+ ...location ? { location } : void 0,
324
+ ...slackSource ? { source: slackSource } : void 0
325
+ };
326
+ }
327
+ return {
328
+ destination,
329
+ ...location ? { location } : void 0,
330
+ ...source ? { source } : void 0
331
+ };
332
+ }
333
+ /** Require the Conversation Destination and Source from SQL. */
334
+ async function resolveTurnSessionRouting(args) {
335
+ const routing = await resolveConversationRouting(args);
336
+ if (!routing?.destination || !routing.source) throw new Error(`Conversation ${args.conversationId} is missing durable routing metadata`);
337
+ return {
338
+ destination: routing.destination,
339
+ ...routing.location ? { location: routing.location } : void 0,
340
+ source: routing.source
341
+ };
342
+ }
343
+ /**
344
+ * Require the Destination and Source to resume a Turn.
345
+ *
346
+ * A dispatch Conversation stores the dispatch Source, which has no session
347
+ * Source. Its dispatch record owns the Destination and Source.
348
+ */
349
+ async function resolveTurnResumeRouting(args) {
350
+ if (!args.dispatchId) return await resolveTurnSessionRouting(args);
351
+ const dispatch = await getDispatchRecord(args.dispatchId);
352
+ if (!dispatch) throw new Error(`Dispatch record is missing for ${args.dispatchId}`);
353
+ const dispatchConversationId = getDispatchConversationId(dispatch);
354
+ if (dispatchConversationId !== args.conversationId) throw new Error(`Dispatch ${dispatch.id} belongs to ${dispatchConversationId}, not ${args.conversationId}`);
355
+ const location = (await resolveConversationRouting(args))?.location;
356
+ return {
357
+ destination: dispatch.destination,
358
+ ...location ? { location } : void 0,
359
+ source: dispatch.source
360
+ };
361
+ }
362
+ // src/chat/task-execution/turn-membership.ts
363
+ /** True when the committed message at `seq` belongs to the Turn. */
364
+ function isTurnMessage(start, seq, message) {
365
+ return seq > start.seq && message.role !== "system";
366
+ }
367
+ /**
368
+ * The messages of a saved Turn with their provenance. Without a
369
+ * `turn_started` event, nothing tells this Turn from earlier history, so it
370
+ * has no messages.
371
+ */
372
+ function savedTurnMessages(record, start) {
373
+ if (!start) return [];
374
+ return record.piMessages.flatMap((message, index) => {
375
+ const seq = record.piMessageSeqs[index];
376
+ return seq !== void 0 && isTurnMessage(start, seq, message) ? [{
377
+ message,
378
+ provenance: record.piMessageProvenance[index] ?? { authority: "context" }
379
+ }] : [];
380
+ });
381
+ }
382
+ // src/chat/attachments/uploads.ts
383
+ const MINUTE_MS = 6e4;
384
+ /** Time that a browser has to write the bytes after it asks to upload. */
385
+ const UPLOAD_TARGET_TTL_MS = 15 * MINUTE_MS;
386
+ /** Time that a written upload can still join a Message. */
387
+ const UPLOAD_SEND_WINDOW_MS = 60 * MINUTE_MS;
388
+ /**
389
+ * Age at which cleanup deletes an upload that no Message used. It is much
390
+ * longer than the send window, so cleanup cannot race a send.
391
+ */
392
+ const UPLOAD_RETENTION_MS = 1440 * MINUTE_MS;
393
+ const UPLOAD_GC_BATCH_LIMIT = 200;
394
+ /** Leading bytes that image type detection reads. */
395
+ const SIGNATURE_BYTES = 16;
396
+ /** A Message refers to an upload that it cannot use. */
397
+ var AttachmentUploadError = class extends Error {
398
+ constructor(message) {
399
+ super(message);
400
+ this.name = "AttachmentUploadError";
401
+ }
402
+ };
403
+ /**
404
+ * Reserve one object key for a browser upload.
405
+ *
406
+ * Returns no target when the provider cannot sign browser writes. The caller
407
+ * then takes the bytes with `writeAttachmentUpload`.
408
+ */
409
+ async function createAttachmentUpload(args) {
410
+ const nowMs = args.nowMs ?? Date.now();
411
+ const id = randomUUID();
412
+ const storageKey = `conversations/${args.scope.conversationId}/uploads/${id}`;
413
+ await args.db.db().insert(juniorAttachmentUploads).values({
414
+ ...args.scope,
415
+ bytes: args.file.bytes,
416
+ contentType: args.file.contentType,
417
+ createdAt: new Date(nowMs),
418
+ filename: args.file.filename,
419
+ id,
420
+ storageKey,
421
+ storageProvider: args.storage.provider
422
+ });
423
+ const target = await args.storage.createUploadTarget?.({
424
+ bytes: args.file.bytes,
425
+ contentType: args.file.contentType,
426
+ expiresAtMs: nowMs + UPLOAD_TARGET_TTL_MS,
427
+ key: storageKey
428
+ });
429
+ return target ? {
430
+ id,
431
+ target
432
+ } : { id };
433
+ }
434
+ async function readUploadRows(args) {
435
+ 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))));
436
+ }
437
+ /** Write upload bytes through the API, for providers without browser writes. */
438
+ async function writeAttachmentUpload(args) {
439
+ const nowMs = args.nowMs ?? Date.now();
440
+ 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))));
441
+ if (!row) throw new AttachmentUploadError("Upload not found.");
442
+ if (await readLiveAttachment({
443
+ attachmentId: row.id,
444
+ conversationId: row.conversationId,
445
+ db: args.db
446
+ })) throw new AttachmentUploadError("Upload was already sent.");
447
+ if (args.body.byteLength !== row.bytes) throw new AttachmentUploadError("Upload size does not match the file.");
448
+ await args.storage.put({
449
+ body: bufferBody(args.body),
450
+ bytes: row.bytes,
451
+ contentType: row.contentType,
452
+ key: row.storageKey
453
+ });
454
+ }
455
+ /** Read a whole object once for its size, digest, and leading bytes. */
456
+ async function inspectObject(body, maxBytes) {
457
+ const hash = createHash("sha256");
458
+ const head = [];
459
+ let headBytes = 0;
460
+ let bytes = 0;
461
+ const reader = body.getReader();
462
+ for (;;) {
463
+ const { done, value } = await reader.read();
464
+ if (done) break;
465
+ bytes += value.byteLength;
466
+ if (bytes > maxBytes) {
467
+ await reader.cancel();
468
+ return;
469
+ }
470
+ hash.update(value);
471
+ if (headBytes < SIGNATURE_BYTES) {
472
+ head.push(Buffer.from(value.subarray(0, SIGNATURE_BYTES - headBytes)));
473
+ headBytes += head.at(-1).byteLength;
474
+ }
475
+ }
476
+ return {
477
+ bytes,
478
+ head: Buffer.concat(head),
479
+ sha256: hash.digest("hex")
480
+ };
481
+ }
482
+ /**
483
+ * Pick the type to store from the file signature, not only the browser's
484
+ * guess from the file name. Models reject an image whose bytes do not match
485
+ * its type, so a file that only claims to be an image is stored as bytes.
486
+ */
487
+ function storedContentType(declared, head) {
488
+ const detected = detectImageMediaType(head);
489
+ if (detected) return detected;
490
+ return isVisionImageMediaType(declared) ? "application/octet-stream" : declared;
491
+ }
492
+ /**
493
+ * Check the uploads of one Message before the Message is accepted.
494
+ *
495
+ * Each upload must belong to the scope and be written in full at its
496
+ * declared size. Throws `AttachmentUploadError` for any upload that the
497
+ * Message cannot use.
498
+ */
499
+ async function verifyAttachmentUploads(args) {
500
+ if (args.uploadIds.length === 0) return [];
501
+ if (new Set(args.uploadIds).size !== args.uploadIds.length) throw new AttachmentUploadError("Attach each file once.");
502
+ const rows = await readUploadRows({
503
+ db: args.db,
504
+ nowMs: args.nowMs ?? Date.now(),
505
+ scope: args.scope,
506
+ storageProvider: args.storage.provider,
507
+ uploadIds: args.uploadIds
508
+ });
509
+ const byId = new Map(rows.map((row) => [row.id, row]));
510
+ return await Promise.all(args.uploadIds.map(async (uploadId) => {
511
+ const row = byId.get(uploadId);
512
+ if (!row) throw new AttachmentUploadError("Upload expired. Attach the file again.");
513
+ const recorded = await readLiveAttachment({
514
+ attachmentId: row.id,
515
+ conversationId: row.conversationId,
516
+ db: args.db
517
+ });
518
+ if (recorded) return {
519
+ attachment: {
520
+ bytes: recorded.bytes,
521
+ contentType: recorded.contentType,
522
+ filename: recorded.filename,
523
+ id: recorded.id
524
+ },
525
+ recorded: true
526
+ };
527
+ const body = await args.storage.get(row.storageKey);
528
+ const object = body ? await inspectObject(body, row.bytes) : void 0;
529
+ if (!object || object.bytes !== row.bytes) throw new AttachmentUploadError(`Upload of ${row.filename} is not complete. Attach it again.`);
530
+ return {
531
+ attachment: {
532
+ bytes: row.bytes,
533
+ contentType: storedContentType(row.contentType, object.head),
534
+ filename: row.filename,
535
+ id: row.id
536
+ },
537
+ recorded: false,
538
+ sha256: object.sha256,
539
+ storageKey: row.storageKey
540
+ };
541
+ }));
542
+ }
543
+ /** Record checked uploads as attachments of their Conversation. */
544
+ async function recordAttachmentUploads(args) {
545
+ await mapBounded(args.uploads.filter((upload) => !upload.recorded), (upload) => recordUploadedAttachment({
546
+ attachment: {
547
+ ...upload.attachment,
548
+ conversationId: args.conversationId,
549
+ sha256: upload.sha256,
550
+ storageKey: upload.storageKey
551
+ },
552
+ db: args.db,
553
+ nowMs: args.nowMs ?? Date.now(),
554
+ storage: args.storage
555
+ }));
556
+ return args.uploads.map((upload) => upload.attachment);
557
+ }
558
+ /**
559
+ * Delete old upload rows in one bounded batch.
560
+ *
561
+ * An upload that a Message recorded keeps its object: the attachment row owns
562
+ * it now. Other objects are deleted first, so a failed delete stays
563
+ * retryable.
564
+ */
565
+ async function collectAttachmentUploadGarbage(args) {
566
+ const rows = await args.db.db().select({
567
+ id: juniorAttachmentUploads.id,
568
+ recordedId: juniorAttachments.id,
569
+ storageKey: juniorAttachmentUploads.storageKey
570
+ }).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);
571
+ if (rows.length === 0) return { deleted: 0 };
572
+ const unusedKeys = rows.filter((row) => row.recordedId === null).map((row) => row.storageKey);
573
+ await args.storage.delete(unusedKeys);
574
+ return { deleted: (await args.db.db().delete(juniorAttachmentUploads).where(inArray(juniorAttachmentUploads.id, rows.map((row) => row.id))).returning({ id: juniorAttachmentUploads.id })).length };
575
+ }
576
+ // src/chat/conversations/destination.ts
577
+ function requireLocalDestination(conversationId) {
578
+ const parsed = localDestinationSchema.safeParse({
579
+ platform: "local",
580
+ conversationId
581
+ });
582
+ if (!parsed.success) throw new Error(`Invalid local conversation id: ${conversationId}`);
583
+ return parsed.data;
584
+ }
585
+ /**
586
+ * Keep a stored Destination, or create the temporary local Destination.
587
+ *
588
+ * TODO(dcramer): Delete this module after Conversation and AgentRun use
589
+ * Location, and web and event Turns no longer need a local
590
+ * Destination.
591
+ */
592
+ function resolveConversationDestination(args) {
593
+ return args.existing ?? requireLocalDestination(args.conversationId);
594
+ }
595
+ // src/chat/conversations/web-input.ts
596
+ function normalizeEmail(email) {
597
+ return email.trim().toLowerCase();
598
+ }
599
+ function stableHex(...parts) {
600
+ return createHash("sha256").update(parts.join("\0")).digest("hex").slice(0, 24);
601
+ }
602
+ /**
603
+ * Build a durable Conversation id for one web Actor and create key.
604
+ *
605
+ * Retries with the same key must address the same Conversation before the
606
+ * mailbox Message id is derived.
607
+ */
608
+ function createConversationId(args) {
609
+ return `local:web:${stableHex(normalizeEmail(args.actorEmail), args.idempotencyKey)}`;
610
+ }
611
+ /** Return the stable Turn id for one mailbox Message. */
612
+ function conversationTurnIdForMessage(messageId) {
613
+ return buildDeterministicTurnId(messageId);
614
+ }
615
+ /**
616
+ * Store the dashboard participant in the current Conversation actor field.
617
+ *
618
+ * TODO(dcramer): Remove this StoredSlackActor conversion after Conversation
619
+ * actor storage accepts web Actors directly.
620
+ */
621
+ function storedActorFromWeb(actor) {
622
+ return {
623
+ ...actor.email ? { email: normalizeEmail(actor.email) } : void 0,
624
+ ...actor.fullName ? { fullName: actor.fullName } : void 0
625
+ };
626
+ }
627
+ /**
628
+ * Return whether a person can add a web Message to an existing
629
+ * Conversation: a dashboard Conversation, a Slack thread, or a Thread.
630
+ */
631
+ function acceptsWebMessages(conversation) {
632
+ if (!isTopLevelKind(conversation.kind)) return conversation.kind === "thread";
633
+ const { conversationId, destination } = conversation;
634
+ if (destination?.platform === "slack") return true;
635
+ return destination?.platform === "local" && conversationId.startsWith("local:web:");
636
+ }
637
+ /**
638
+ * Build the web Actor for one signed-in User. Junior is the web provider,
639
+ * so the provider-scoped Actor id is the User id.
640
+ */
641
+ function webActorFromUser(user, profile) {
642
+ return {
643
+ platform: "web",
644
+ userId: user.id,
645
+ email: normalizeEmail(user.email),
646
+ ...user.displayName ? { fullName: user.displayName } : void 0,
647
+ ...profile?.userName ? { userName: profile.userName } : void 0
648
+ };
649
+ }
650
+ /** Build one web mailbox entry. */
651
+ function buildWebInboundMessage(args) {
652
+ const text = args.message.trim();
653
+ if (!text && !args.attachments?.length) throw new Error("Web Message must not be empty");
654
+ if (!args.actor.email) throw new Error("Web Actor requires a verified email");
655
+ const nowMs = args.nowMs ?? Date.now();
656
+ const traceContext = getActiveTraceContext();
657
+ return {
658
+ conversationId: args.conversationId,
659
+ createdAtMs: args.createdAtMs ?? nowMs,
660
+ delivery: args.delivery ?? "defer",
661
+ ...args.destination ? { destination: args.destination } : void 0,
662
+ inboundMessageId: args.messageId,
663
+ input: {
664
+ authorId: args.actor.userId,
665
+ ...args.authorIdentityId ? { authorIdentityId: args.authorIdentityId } : void 0,
666
+ text,
667
+ ...args.attachments?.length ? { attachments: args.attachments } : void 0,
668
+ ...args.reviewItemChange ? { reviewItemChange: args.reviewItemChange } : void 0,
669
+ metadata: {
670
+ authorEmail: normalizeEmail(args.actor.email),
671
+ ...args.actor.fullName && { authorFullName: args.actor.fullName },
672
+ authorUserId: args.actor.userId,
673
+ ...args.actor.userName && { authorUserName: args.actor.userName },
674
+ kind: "api_turn",
675
+ messageId: args.messageId
676
+ }
677
+ },
678
+ receivedAtMs: nowMs,
679
+ source: "web",
680
+ ...traceContext ? { traceContext } : void 0
681
+ };
682
+ }
683
+ /**
684
+ * Record web activity and create a Conversation root when needed. Returns the
685
+ * Destination for the Message's work. A child's work keeps none, so its
686
+ * workers read the Conversation.
687
+ */
688
+ async function recordWebConversationActivity(args) {
689
+ const store = args.conversationStore ?? getConversationStore();
690
+ const existing = await store.get({ conversationId: args.conversationId });
691
+ const destination = resolveConversationDestination({
692
+ conversationId: args.conversationId,
693
+ existing: existing?.destination
694
+ });
695
+ const isNewRoot = !existing;
696
+ const visibility = args.rootVisibility === "private" ? "private" : "public";
697
+ const source = isNewRoot ? createWebSource(args.conversationId, visibility) : void 0;
698
+ await store.recordActivity({
699
+ conversationId: args.conversationId,
700
+ ...existing?.destination ? void 0 : { destination },
701
+ nowMs: args.nowMs,
702
+ actor: storedActorFromWeb(args.actor),
703
+ ...isNewRoot ? { source: "web" } : void 0,
704
+ ...source ? { sessionSource: source } : void 0,
705
+ ...isNewRoot && args.rootTitle ? { title: args.rootTitle } : void 0,
706
+ ...isNewRoot ? { visibility } : void 0,
707
+ ...isNewRoot && args.rootKind ? { kind: args.rootKind } : void 0
708
+ });
709
+ return existing && !isTopLevelKind(existing.kind) ? void 0 : destination;
710
+ }
711
+ /** Create a Conversation from web input and enqueue its first Message. */
712
+ async function createAndEnqueueConversation(input, options) {
713
+ if (!input.actor.email) throw new Error("Web Actor requires a verified email");
714
+ const conversationId = createConversationId({
715
+ actorEmail: input.actor.email,
716
+ idempotencyKey: input.idempotencyKey
717
+ });
718
+ return await appendAndEnqueueWebMessage({
719
+ actor: input.actor,
720
+ conversationId,
721
+ idempotencyKey: input.idempotencyKey,
722
+ message: input.message,
723
+ uploads: input.uploads,
724
+ ...input.title ? { rootTitle: input.title } : void 0,
725
+ rootVisibility: input.visibility === "private" ? "private" : "public"
726
+ }, options);
727
+ }
728
+ async function appendAndEnqueueWebMessage(input, options) {
729
+ const text = input.message.trim();
730
+ if (!text && !input.uploads?.length) throw new Error("Web Message must not be empty");
731
+ if (!input.actor.email) throw new Error("Web Actor requires a verified email");
732
+ const nowMs = options.nowMs ?? Date.now();
733
+ const messageId = await webMessageId({
734
+ conversationId: input.conversationId,
735
+ idempotencyKey: input.idempotencyKey
736
+ });
737
+ const destination = await recordWebConversationActivity({
738
+ actor: input.actor,
739
+ conversationId: input.conversationId,
740
+ conversationStore: options.conversationStore,
741
+ nowMs,
742
+ ...input.rootTitle && { rootTitle: input.rootTitle },
743
+ ...input.rootVisibility && { rootVisibility: input.rootVisibility }
744
+ });
745
+ let attachments = [];
746
+ if (input.uploads?.length) {
747
+ if (!options.attachmentStorage) throw new Error("Attachment storage is unavailable.");
748
+ attachments = await recordAttachmentUploads({
749
+ conversationId: input.conversationId,
750
+ db: getSqlExecutor(),
751
+ nowMs,
752
+ storage: options.attachmentStorage,
753
+ uploads: input.uploads
754
+ });
755
+ }
756
+ const enqueue = options.exclusive ? appendAndEnqueueExclusiveInboundMessage : appendAndEnqueueInboundMessage;
757
+ const authorIdentityId = await resolveActorIdentityId(getSqlExecutor(), input.actor);
758
+ const enqueueTo = (destination) => enqueue({
759
+ message: buildWebInboundMessage({
760
+ actor: input.actor,
761
+ authorIdentityId,
762
+ conversationId: input.conversationId,
763
+ delivery: input.delivery,
764
+ destination,
765
+ message: text,
766
+ attachments,
767
+ messageId,
768
+ nowMs,
769
+ ...input.reviewItemChange && { reviewItemChange: input.reviewItemChange }
770
+ }),
771
+ conversationStore: options.conversationStore,
772
+ nowMs,
773
+ queue: options.queue,
774
+ state: options.state
775
+ });
776
+ let result;
777
+ try {
778
+ result = await enqueueTo(destination);
779
+ } catch (error) {
780
+ if (!destination) throw error;
781
+ const stored = await (options.conversationStore ?? getConversationStore()).get({ conversationId: input.conversationId });
782
+ const current = resolveConversationDestination({
783
+ conversationId: input.conversationId,
784
+ existing: stored?.destination
785
+ });
786
+ if (sameDestination(current, destination)) throw error;
787
+ result = await enqueueTo(current);
788
+ }
789
+ const status = result.status === "appended" ? "accepted" : result.status;
790
+ return {
791
+ conversationId: input.conversationId,
792
+ messageId,
793
+ status
794
+ };
795
+ }
796
+ // src/chat/lead/conversation.ts
797
+ /**
798
+ * The Lead of one person: their private Conversation that finds, starts, and
799
+ * steers their other Conversations. Only web creates a Lead, so its root
800
+ * Actor is the web Identity of its User, and a unique index keeps one Lead
801
+ * for each Identity.
802
+ */
803
+ const UNIQUE_VIOLATION = "23505";
804
+ const LEAD_TITLE = "Lead";
805
+ async function findLead(identityId) {
806
+ const [row] = await getDb().select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(eq(juniorConversations.kind, "lead"), eq(juniorConversations.actorIdentityId, identityId))).limit(1);
807
+ return row ? await getConversationStore().get({ conversationId: row.conversationId }) : void 0;
808
+ }
809
+ /** Return the Lead of one User, and create it on first use. */
810
+ async function getLeadConversation(user) {
811
+ const actor = webActorFromUser(user);
812
+ const identityId = await resolveActorIdentityId(getSqlExecutor(), actor);
813
+ if (!identityId) throw new Error("A Lead needs a web Identity");
814
+ const existing = await findLead(identityId);
815
+ if (existing) return existing;
816
+ try {
817
+ await recordWebConversationActivity({
818
+ actor,
819
+ conversationId: `local:web:${randomUUID()}`,
820
+ nowMs: Date.now(),
821
+ rootKind: "lead",
822
+ rootTitle: LEAD_TITLE,
823
+ rootVisibility: "private"
824
+ });
825
+ } catch (error) {
826
+ if (!isPostgresErrorCode(error, UNIQUE_VIOLATION)) throw error;
827
+ }
828
+ const created = await findLead(identityId);
829
+ if (!created) throw new Error("The Lead was not saved");
830
+ return created;
831
+ }
832
+ /**
833
+ * Return the User of a Lead: the person whose Conversations it steers.
834
+ * Returns nothing for a Conversation that is not a Lead.
835
+ */
836
+ async function readLeadUser(conversationId) {
837
+ const [row] = await getDb().select({
838
+ displayName: juniorUsers.displayName,
839
+ email: juniorUsers.primaryEmail,
840
+ id: juniorUsers.id
841
+ }).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(eq(juniorConversations.conversationId, conversationId), eq(juniorConversations.kind, "lead"))).limit(1);
842
+ return row ? {
843
+ id: row.id,
844
+ email: row.email,
845
+ ...row.displayName ? { displayName: row.displayName } : void 0
846
+ } : void 0;
847
+ }
848
+ /**
849
+ * Return whether the person of a Lead is a Participant of one root
850
+ * Conversation. False when the sender is not a Lead, or when the target is
851
+ * not a root, such as an Automation run.
852
+ */
853
+ async function leadPersonParticipates(args) {
854
+ const target = alias(juniorConversations, "target");
855
+ const [row] = await getDb().select({ one: sql`1` }).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).innerJoin(juniorConversationParticipants, and(eq(juniorConversationParticipants.userId, juniorIdentities.userId), eq(juniorConversationParticipants.rootConversationId, args.rootConversationId))).innerJoin(target, and(eq(target.conversationId, args.rootConversationId), eq(conversationKindSql(target), "root"))).where(and(eq(juniorConversations.conversationId, args.leadConversationId), eq(juniorConversations.kind, "lead"))).limit(1);
856
+ return row !== void 0;
857
+ }
858
+ // src/chat/lead/start-conversation.ts
859
+ /**
860
+ * Start one Conversation from a Lead. The new Conversation is a public web
861
+ * root of the Lead's person and runs as that person, like any root. The
862
+ * Lead's task is its first Message. The start is not reviewed. Action
863
+ * review judges the new root's own tool calls, as it does a child agent's.
864
+ */
865
+ /**
866
+ * Create the Conversation and enqueue the task as its first Message. Repeat
867
+ * calls with the same `messageKey` are safe.
868
+ */
869
+ async function startLeadConversation(args) {
870
+ const user = await readLeadUser(args.leadConversationId);
871
+ if (!user) throw new Error("Only a Lead can start a Conversation");
872
+ const idempotencyKey = `lead:${args.leadConversationId}:${args.messageKey}`;
873
+ const conversationId = createConversationId({
874
+ actorEmail: user.email,
875
+ idempotencyKey
876
+ });
877
+ await appendAndEnqueueWebMessage({
878
+ actor: webActorFromUser(user),
879
+ conversationId,
880
+ idempotencyKey,
881
+ message: args.task,
882
+ rootTitle: args.title,
883
+ rootVisibility: "public"
884
+ }, {
885
+ nowMs: Date.now(),
886
+ queue: args.queue
887
+ });
888
+ return { conversationId };
889
+ }
890
+ // src/chat/tools/start-conversation.ts
891
+ /** Static definition of `startConversation`, which only a Lead lists. */
892
+ const startConversationToolDefinition = zodToolDefinition({
893
+ description: [
894
+ "Start a new conversation that does one piece of the person's work. It is a public conversation of the person, and it starts at once.",
895
+ "Your task is its first message, and it runs as the person, so write the task as the person's request.",
896
+ "Use messageAgent instead for work that a conversation already does."
897
+ ].join(" "),
898
+ exposure: "modelOnly",
899
+ approvalMode: "auto",
900
+ annotations: {
901
+ destructiveHint: false,
902
+ idempotentHint: true,
903
+ openWorldHint: false,
904
+ readOnlyHint: false
905
+ },
906
+ inputSchema: z.object({
907
+ task: z.string().trim().min(1).describe("Self-contained brief for a peer who has not seen this conversation: the goal, the targets, the facts you know, the constraints, and what done means."),
908
+ title: z.string().trim().min(1).max(60).describe("Short display title of the new conversation.")
909
+ }).strict(),
910
+ outputSchema: juniorToolOutputSchema.extend({
911
+ conversation_id: z.string().min(1).describe("ID of the new conversation. Pass it to messageAgent to steer it."),
912
+ dashboard_url: z.string().url().optional().describe("Dashboard link of the new conversation."),
913
+ subscribable: subscribableResourceSchema.describe("Watch it with watchEvents only when the person asks to hear back.")
914
+ })
915
+ });
916
+ /** Create the tool that starts a Conversation from a Lead Turn. */
917
+ function createStartConversationTool(context) {
918
+ return zodTool({
919
+ ...startConversationToolDefinition,
920
+ execute: async (input, options) => {
921
+ if (!options.toolCallId || !context.turnId) throw new ToolInputError("startConversation requires an active Turn and tool call ID");
922
+ const { conversationId } = await startLeadConversation({
923
+ leadConversationId: context.conversationId,
924
+ messageKey: `${context.turnId}:${options.toolCallId}`,
925
+ queue: context.conversationWorkQueue ?? getVercelConversationWorkQueue(),
926
+ task: input.task,
927
+ title: input.title
928
+ });
929
+ const dashboardUrl = getDashboardConversationLink(conversationId);
930
+ return {
931
+ conversation_id: conversationId,
932
+ ...dashboardUrl ? { dashboard_url: dashboardUrl } : void 0,
933
+ subscribable: conversationWatch({
934
+ conversationId,
935
+ title: input.title
936
+ })
937
+ };
938
+ }
939
+ });
940
+ }
941
+ export { readSlackAttachmentSource as A, FORK_INSTRUCTIONS as C, getSlackFileId as D, notInheritedByForkChild as E, zodToolDefinition as F, injectContinuationToolName as I, juniorToolOutputSchema as L, slackAttachmentsVersionQuery as M, parseToolInput as N, matchSlackAttachments as O, zodTool as P, makeStructuredToolOutput as R, resolveTurnResumeRouting as S, isInheritedForkHistory as T, verifyAttachmentUploads as _, readLeadUser as a, savedTurnMessages as b, conversationTurnIdForMessage as c, recordWebConversationActivity as d, webActorFromUser as f, createAttachmentUpload as g, collectAttachmentUploadGarbage as h, leadPersonParticipates as i, recordSlackAttachment as j, readAttachmentVisionSummary as k, createAndEnqueueConversation as l, AttachmentUploadError as m, startConversationToolDefinition as n, acceptsWebMessages as o, resolveConversationDestination as p, getLeadConversation as r, appendAndEnqueueWebMessage as s, createStartConversationTool as t, createConversationId as u, writeAttachmentUpload as v, commitForkHistory as w, resolveConversationRouting as x, isTurnMessage as y };