@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
@@ -1,335 +0,0 @@
1
- import { a as getConversationStore } from "./db-DTxzH7u5.js";
2
- import { p as logException } from "./logging-FjclQsXu.js";
3
- import "./background-compaction-queue-CJDnWVOJ.js";
4
- import { At as getConversationWorkStates$1, Bt as recordConversationRetry$1, Dt as dropPendingMessages$1, Et as drainConversationMailbox$1, Ft as listActiveConversationIds$1, Gt as startConversationWork$1, Ht as releaseInboundMessage, It as markConversationWorkEnqueued$1, Jt as takeDeferredConversationMove, Kt as steerWebPendingMessages$1, Mt as hasRunnableConversationWork, Ot as getConversation$1, St as completeConversationWork$1, Ut as requestAnotherSlice$1, Vt as releaseConversationWork$1, Wt as requestConversationWork$1, _t as checkInConversationWork$1, bt as clearExpiredConversationLease$1, ft as ackMessages$1, gt as cancelHumanFacingPendingMessages$1, ht as beginConversationResume$1, kt as getConversationWorkState$1, mt as appendInboundMessage, pt as appendExclusiveInboundMessage, qt as stopConversationWork$1, vt as claimInboundMessage$1, wt as deadLetterAttempt$1, xt as completeConversationStop$1, yt as clearConsumedConversationWake$1, zt as recordAttemptFailure$1 } from "./projection-Cns7XwWa.js";
5
- // src/chat/task-execution/store.ts
6
- function metadataStore(options) {
7
- return options.conversationStore ?? getConversationStore();
8
- }
9
- function duplicateInboundNudgeIdempotencyKey(message, nowMs) {
10
- return `duplicate:${message.conversationId}:${message.inboundMessageId}:${nowMs}`;
11
- }
12
- function hasRecentEnqueueMarker(conversation, nowMs) {
13
- const lastEnqueuedAtMs = conversation.execution.lastEnqueuedAtMs;
14
- return typeof lastEnqueuedAtMs === "number" && lastEnqueuedAtMs + 6e4 > nowMs;
15
- }
16
- function now() {
17
- return Date.now();
18
- }
19
- async function recordExecutionMetadata(args) {
20
- const conversation = await getConversation$1({
21
- conversationId: args.conversationId,
22
- state: args.state
23
- });
24
- if (!conversation) return;
25
- await metadataStore(args).recordExecution({
26
- channelName: conversation.channelName,
27
- conversationId: conversation.conversationId,
28
- createdAtMs: conversation.createdAtMs,
29
- destination: conversation.destination,
30
- execution: {
31
- lastCheckpointAtMs: conversation.execution.lastCheckpointAtMs,
32
- lastEnqueuedAtMs: conversation.execution.lastEnqueuedAtMs,
33
- runId: conversation.execution.runId,
34
- status: conversation.execution.status,
35
- updatedAtMs: conversation.execution.updatedAtMs
36
- },
37
- lastActivityAtMs: conversation.lastActivityAtMs,
38
- metrics: null,
39
- actor: conversation.actor,
40
- source: conversation.source,
41
- title: conversation.title,
42
- updatedAtMs: conversation.updatedAtMs
43
- });
44
- }
45
- /** Return a persisted conversation record, if one exists. */
46
- async function getConversation(args) {
47
- return await getConversation$1(args);
48
- }
49
- /** Return a persisted conversation work record, if one exists. */
50
- async function getConversationWorkState(args) {
51
- return await getConversationWorkState$1(args);
52
- }
53
- /** Return the persisted work records of several Conversations in one read. */
54
- async function getConversationWorkStates(conversationIds) {
55
- return await getConversationWorkStates$1(conversationIds);
56
- }
57
- /** Count one failed conversation execution and persist its terminal retry state. */
58
- async function recordConversationRetry(args) {
59
- const result = await recordConversationRetry$1(args);
60
- await recordExecutionMetadata(args);
61
- return result;
62
- }
63
- /**
64
- * Ensure runnable conversation work has one accepted queue wake-up nudge.
65
- *
66
- * Ordinary wakes coalesce on a recent accepted marker. A caller can ignore the
67
- * marker without replacing an active lease. Replacement is only for consumed
68
- * or known-stale deliveries where another queue nudge must exist.
69
- */
70
- async function ensureConversationWake(args) {
71
- const nowMs = args.nowMs ?? now();
72
- const conversation = await getConversation$1({
73
- conversationId: args.conversationId,
74
- state: args.state
75
- });
76
- if (!conversation || !hasRunnableConversationWork(conversation)) return { status: "no_work" };
77
- if (args.replaceExistingWake !== true && conversation.execution.lease && conversation.execution.lease.expiresAtMs > nowMs) return { status: "lease_active" };
78
- if (args.ignoreEnqueueMarker !== true && args.replaceExistingWake !== true && hasRecentEnqueueMarker(conversation, nowMs)) return { status: "already_enqueued" };
79
- const queueResult = await args.queue.send({
80
- schemaVersion: 2,
81
- conversationId: args.conversationId
82
- }, {
83
- delayMs: args.delayMs,
84
- idempotencyKey: args.idempotencyKey
85
- });
86
- await markConversationWorkEnqueued({
87
- conversationId: args.conversationId,
88
- conversationStore: args.conversationStore,
89
- nowMs,
90
- state: args.state
91
- });
92
- return {
93
- status: "enqueued",
94
- queueMessageId: queueResult?.messageId
95
- };
96
- }
97
- /**
98
- * Record an inbound message id that skips the mailbox. When the claim is
99
- * saved but its metadata write fails, this releases the claim, so a
100
- * redelivery can claim it again.
101
- */
102
- async function claimInboundMessage(args) {
103
- const result = await claimInboundMessage$1(args);
104
- if (result.status === "claimed") try {
105
- await recordExecutionMetadata({
106
- conversationId: args.message.conversationId,
107
- conversationStore: args.conversationStore,
108
- state: args.state
109
- });
110
- } catch (error) {
111
- await releaseInboundMessage({
112
- message: args.message,
113
- state: args.state
114
- });
115
- throw error;
116
- }
117
- return result;
118
- }
119
- async function enqueueAfterAppend(args) {
120
- const nowMs = args.nowMs ?? now();
121
- const appendResult = args.appendResult;
122
- if (appendResult.status === "active") return appendResult;
123
- let idempotencyKey = args.message.inboundMessageId;
124
- if (appendResult.status === "duplicate") {
125
- const conversation = await getConversation$1({
126
- conversationId: args.message.conversationId,
127
- state: args.state
128
- });
129
- if (!conversation) return appendResult;
130
- if (hasRecentEnqueueMarker(conversation, nowMs)) {
131
- await recordExecutionMetadata({
132
- conversationId: args.message.conversationId,
133
- conversationStore: args.conversationStore,
134
- state: args.state
135
- });
136
- return appendResult;
137
- }
138
- if (!conversation.execution.pendingMessages.some((message) => message.inboundMessageId === args.message.inboundMessageId)) {
139
- await recordExecutionMetadata({
140
- conversationId: args.message.conversationId,
141
- conversationStore: args.conversationStore,
142
- state: args.state
143
- });
144
- return appendResult;
145
- }
146
- idempotencyKey = duplicateInboundNudgeIdempotencyKey(args.message, nowMs);
147
- }
148
- const wake = await ensureConversationWake({
149
- conversationId: args.message.conversationId,
150
- conversationStore: args.conversationStore,
151
- delayMs: args.queueDelayMs,
152
- idempotencyKey,
153
- ignoreEnqueueMarker: args.message.source === "event" ? void 0 : true,
154
- nowMs,
155
- queue: args.queue,
156
- replaceExistingWake: args.replaceExistingWake,
157
- state: args.state
158
- });
159
- if (wake.status !== "enqueued") await recordExecutionMetadata({
160
- conversationId: args.message.conversationId,
161
- conversationStore: args.conversationStore,
162
- state: args.state
163
- });
164
- return {
165
- ...appendResult,
166
- ...wake.status === "enqueued" ? { queueMessageId: wake.queueMessageId } : void 0
167
- };
168
- }
169
- /** Persist inbound work and ensure a worker wake-up. */
170
- async function appendAndEnqueueInboundMessage(args) {
171
- const nowMs = args.nowMs ?? now();
172
- const result = await enqueueAfterAppend({
173
- ...args,
174
- appendResult: await appendInboundMessage({
175
- message: args.message,
176
- nowMs,
177
- renderText: args.renderText,
178
- state: args.state
179
- }),
180
- nowMs
181
- });
182
- if (result.status === "active") throw new Error("Non-exclusive mailbox enqueue returned active");
183
- return result;
184
- }
185
- /** Persist exclusive inbound work and wake its worker when admitted. */
186
- async function appendAndEnqueueExclusiveInboundMessage(args) {
187
- const nowMs = args.nowMs ?? now();
188
- return await enqueueAfterAppend({
189
- ...args,
190
- appendResult: await appendExclusiveInboundMessage({
191
- message: args.message,
192
- nowMs,
193
- state: args.state
194
- }),
195
- nowMs
196
- });
197
- }
198
- /** Persist a stop request for the current Conversation run. */
199
- async function stopConversationWork(args) {
200
- const result = await stopConversationWork$1(args);
201
- if (result.status === "requested") {
202
- args.onStopSaved?.();
203
- await recordExecutionMetadata(args);
204
- }
205
- return result;
206
- }
207
- /** Finish an observed stop request under the current worker lease. */
208
- async function completeConversationStop(args) {
209
- const result = await completeConversationStop$1(args);
210
- if (result.status === "cleared") await recordExecutionMetadata(args);
211
- return result;
212
- }
213
- /** Clear an accepted wake marker after its delivery finds no runnable work. */
214
- async function clearConsumedConversationWake(args) {
215
- const result = await clearConsumedConversationWake$1(args);
216
- if (result) await recordExecutionMetadata(args);
217
- return result;
218
- }
219
- /** Mark a conversation runnable when there is no new mailbox message. */
220
- async function requestConversationWork(args) {
221
- const result = await requestConversationWork$1(args);
222
- await recordExecutionMetadata({
223
- conversationId: args.conversationId,
224
- conversationStore: args.conversationStore,
225
- state: args.state
226
- });
227
- return result;
228
- }
229
- /** Record that a wake-up nudge was accepted for the conversation. */
230
- async function markConversationWorkEnqueued(args) {
231
- await markConversationWorkEnqueued$1(args);
232
- await recordExecutionMetadata(args);
233
- }
234
- /** Try to acquire the durable execution lease for one conversation. */
235
- async function startConversationWork(args) {
236
- const result = await startConversationWork$1(args);
237
- await recordExecutionMetadata(args);
238
- return result;
239
- }
240
- /** Extend the durable execution lease when the worker checks in. */
241
- async function checkInConversationWork(args) {
242
- const result = await checkInConversationWork$1(args);
243
- if (result) await recordExecutionMetadata(args);
244
- return result;
245
- }
246
- /** Drain pending mailbox entries after the caller accepts responsibility. */
247
- async function drainConversationMailbox(args) {
248
- const result = await drainConversationMailbox$1(args);
249
- if (result.changed) await recordExecutionMetadata(args);
250
- return result.messages;
251
- }
252
- /** Acknowledge leased mailbox entries after the handler accepts responsibility. */
253
- async function ackMessages(args) {
254
- const result = await ackMessages$1(args);
255
- await recordExecutionMetadata(args);
256
- return result;
257
- }
258
- /** Cancel human-facing pending mailbox rows without requiring a worker lease. */
259
- async function cancelHumanFacingPendingMessages(args) {
260
- const result = await cancelHumanFacingPendingMessages$1(args);
261
- if (result.cancelledInboundMessageIds.length > 0) await recordExecutionMetadata(args);
262
- return result;
263
- }
264
- /** Drop pending mailbox rows by id without requiring a worker lease. */
265
- async function dropPendingMessages(args) {
266
- const dropped = await dropPendingMessages$1(args);
267
- if (dropped.length > 0) await recordExecutionMetadata(args);
268
- return dropped;
269
- }
270
- /** Mark one author's queued web messages as interrupts. */
271
- async function steerWebPendingMessages(args) {
272
- return await steerWebPendingMessages$1(args);
273
- }
274
- /** Mark the leased conversation as needing another queue-delivered slice. */
275
- async function requestAnotherSlice(args) {
276
- const result = await requestAnotherSlice$1(args);
277
- await recordExecutionMetadata(args);
278
- return result;
279
- }
280
- /** Begin a requested turn resume without releasing the current lease. */
281
- async function beginConversationResume(args) {
282
- const result = await beginConversationResume$1(args);
283
- if (result) await recordExecutionMetadata(args);
284
- return result;
285
- }
286
- /** Release the durable execution lease without changing completion state. */
287
- async function releaseConversationWork(args) {
288
- const result = await releaseConversationWork$1(args);
289
- await recordExecutionMetadata(args);
290
- return result;
291
- }
292
- /** Finish a leased conversation and report whether runnable work remains. */
293
- async function completeConversationWork(args) {
294
- const result = await completeConversationWork$1(args);
295
- await recordExecutionMetadata(args);
296
- if (result !== "lost_lease") await runDeferredMove(args);
297
- return result;
298
- }
299
- /**
300
- * Run the Slack "Continue here" click that waited for this Run to end. Its
301
- * failure is logged here, so it never fails the Run that already finished.
302
- */
303
- async function runDeferredMove(args) {
304
- const move = await takeDeferredConversationMove(args);
305
- if (move === void 0) return;
306
- try {
307
- const { continueDeferredSlackClick } = await import("./slack-conversation-unfurl-CogYrITA.js").then((n) => n.r);
308
- await continueDeferredSlackClick(move, args.getSlackAdapter);
309
- } catch (error) {
310
- logException(error, "slack.continue_here.deferred.failed", { "gen_ai.conversation.id": args.conversationId });
311
- }
312
- }
313
- /** Record one failed delivery attempt and dead-letter messages at their limit. */
314
- async function recordAttemptFailure(args) {
315
- const result = await recordAttemptFailure$1(args);
316
- if (result.status === "recorded") await recordExecutionMetadata(args);
317
- return result;
318
- }
319
- /** Record a terminal failure completion for a leased conversation. */
320
- async function deadLetterAttempt(args) {
321
- const result = await deadLetterAttempt$1(args);
322
- await recordExecutionMetadata(args);
323
- return result;
324
- }
325
- /** Recover an expired lease and persist the resulting retry state. */
326
- async function clearExpiredConversationLease(args) {
327
- const result = await clearExpiredConversationLease$1(args);
328
- await recordExecutionMetadata(args);
329
- return result;
330
- }
331
- /** List active conversation ids by oldest execution update first. */
332
- async function listActiveConversationIds(args = {}) {
333
- return await listActiveConversationIds$1(args);
334
- }
335
- export { requestAnotherSlice as C, stopConversationWork as D, steerWebPendingMessages as E, releaseConversationWork as S, startConversationWork as T, getConversationWorkState as _, cancelHumanFacingPendingMessages as a, recordAttemptFailure as b, clearConsumedConversationWake as c, completeConversationWork as d, deadLetterAttempt as f, getConversation as g, ensureConversationWake as h, beginConversationResume as i, clearExpiredConversationLease as l, dropPendingMessages as m, appendAndEnqueueExclusiveInboundMessage as n, checkInConversationWork as o, drainConversationMailbox as p, appendAndEnqueueInboundMessage as r, claimInboundMessage as s, ackMessages as t, completeConversationStop as u, getConversationWorkStates as v, requestConversationWork as w, recordConversationRetry as x, listActiveConversationIds as y };
@@ -1,294 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { Co as getDispatchRecord, Cr as isToolResultError, Da as createPluginLogger, Dr as stripRuntimeTurnContext, Ea as createPluginModelCostRecorder, Ln as getRegistrations, Oa as createPluginTurnEventReader, Tr as normalizeToolNameFromResult, b as hydrateConversationMessages, bl as createPluginCache, da as createPluginEmbedder, fa as createPluginModel, hi as createPluginState, ka as createPluginConversationEvents, mr as getPiMessageRole, st as getTurnRecord, wr as isToolResultMessage, yr as instructionTextForProjection } from "./projection-Cns7XwWa.js";
3
- import { Pt as readActorIdentity, a as getConversationStore, o as getDb } from "./db-DTxzH7u5.js";
4
- import { E as withSpan } from "./logging-FjclQsXu.js";
5
- import { a as getPersistedThreadState, c as coerceThreadConversationState, t as resolveConversationRouting } from "./turn-session-routing-Xh_2nSQe.js";
6
- import { v as parseSlackMessageTs } from "./actor-BsBdxDXQ.js";
7
- import { m as sameActorIdentity } from "./history-CYstOMKX.js";
8
- import { i as pluginTaskParamsSchema, r as pluginTaskId } from "./task-queue-C_zldF5J.js";
9
- import { i as getStateAdapter } from "./adapter-B1wujchl.js";
10
- import { t as mapBounded } from "./fan-out-Cod-yEHG.js";
11
- import * as z from "zod";
12
- import { pluginRunContextSchema } from "@sentry/junior-plugin-api";
13
- // src/chat/plugins/task-runner.ts
14
- /**
15
- * Plugin background-task orchestration.
16
- *
17
- * Core schedules tasks from completed sessions and exposes plugins only a
18
- * bounded run projection rather than live runtime internals or queue
19
- * payloads.
20
- */
21
- var task_runner_exports = /* @__PURE__ */ __exportAll({ processPluginTask: () => processPluginTask });
22
- const PLUGIN_MESSAGE_SEND_CONCURRENCY = 5;
23
- const PLUGIN_TASK_LOCK_TTL_MS = 3e5;
24
- const textPartSchema = z.object({
25
- type: z.literal("text"),
26
- text: z.string()
27
- });
28
- function textPart(value) {
29
- return textPartSchema.safeParse(value).data?.text;
30
- }
31
- function messageText(message) {
32
- const content = message.content;
33
- if (typeof content === "string") return sanitizeText(content);
34
- if (!Array.isArray(content)) return "";
35
- return sanitizeText(content.map(textPart).filter(Boolean).join("\n"));
36
- }
37
- function toolResultText(message) {
38
- const record = message;
39
- return sanitizeText([
40
- messageText(message),
41
- record["output"],
42
- record["result"],
43
- record["stdout"],
44
- record["stderr"],
45
- record["toolResult"]
46
- ].filter((value) => typeof value === "string" && value.length > 0).join("\n"));
47
- }
48
- function sanitizeText(text) {
49
- return text.replace(/<data_base64>[\s\S]*?<\/data_base64>/g, "<data_base64>[omitted]</data_base64>").replace(/data:image\/[a-z0-9.+-]+;base64,[a-z0-9+/=]+/gi, "[image data omitted]").replaceAll("\0", " ").trim();
50
- }
51
- /** Build the transcript provenance for a user message from its Pi provenance. */
52
- function messageProvenance(provenance) {
53
- return {
54
- authority: provenance.authority,
55
- ...provenance.actor ? { actor: provenance.actor } : void 0
56
- };
57
- }
58
- function runTranscriptEntry(message, provenance, runActor) {
59
- const role = getPiMessageRole(message);
60
- if (role === "user" || role === "assistant") {
61
- const text = role === "user" ? instructionTextForProjection(messageText(message)) : messageText(message);
62
- if (!text) return;
63
- if (role === "assistant") return {
64
- type: "message",
65
- role,
66
- text
67
- };
68
- return {
69
- type: "message",
70
- role,
71
- text,
72
- provenance: messageProvenance(provenance),
73
- isRunActor: sameActorIdentity(provenance.actor, runActor)
74
- };
75
- }
76
- if (!isToolResultMessage(message)) return;
77
- const toolName = normalizeToolNameFromResult(message);
78
- if (!toolName) return;
79
- const text = toolResultText(message);
80
- return {
81
- type: "toolResult",
82
- toolName,
83
- isError: isToolResultError(message),
84
- ...text ? { text } : void 0
85
- };
86
- }
87
- /**
88
- * Slice the current turn's Pi messages with their aligned provenance and strip
89
- * runtime turn context, keeping each surviving message paired with the exact
90
- * provenance recorded for it. Stripping can drop or rewrite messages, so the
91
- * pairing is applied per message rather than by post-strip index.
92
- */
93
- function turnMessagesWithProvenance(record) {
94
- const startIndex = record.turnStartMessageIndex ?? 0;
95
- const messages = record.piMessages.slice(startIndex);
96
- const provenance = record.piMessageProvenance.slice(startIndex);
97
- const paired = [];
98
- for (const [index, message] of messages.entries()) for (const stripped of stripRuntimeTurnContext([message])) paired.push({
99
- message: stripped,
100
- provenance: provenance[index] ?? { authority: "context" }
101
- });
102
- return paired;
103
- }
104
- /** Recover the Slack context author identity from a persisted thread message. */
105
- function slackContextAuthor(location, message) {
106
- const userId = message.author?.userId?.trim();
107
- if (!userId) return;
108
- return {
109
- platform: "slack",
110
- teamId: location.teamId,
111
- userId,
112
- ...message.author?.userName ? { userName: message.author.userName } : void 0,
113
- ...message.author?.fullName ? { fullName: message.author.fullName } : void 0
114
- };
115
- }
116
- function slackTimestampMs(value) {
117
- const timestamp = parseSlackMessageTs(value);
118
- if (!timestamp) return;
119
- const timestampMs = Number(timestamp) * 1e3;
120
- return Number.isFinite(timestampMs) ? timestampMs : void 0;
121
- }
122
- function conversationMessageTimestampMs(message) {
123
- if (message.meta?.slackTs !== void 0) return slackTimestampMs(message.meta.slackTs);
124
- return Number.isFinite(message.createdAtMs) ? message.createdAtMs : void 0;
125
- }
126
- function messageExistedAtRunCompletion(message, completedAtMs) {
127
- const messageTimestampMs = conversationMessageTimestampMs(message);
128
- return messageTimestampMs !== void 0 && messageTimestampMs <= completedAtMs;
129
- }
130
- /**
131
- * Project bounded public-thread context into the run transcript.
132
- *
133
- * Prior public Slack messages from the current Conversation are durable
134
- * evidence a completed run may have acted on, so passive consumers can cite
135
- * them. They are always context authority (never instruction), and private or
136
- * local Conversations add nothing here.
137
- */
138
- async function loadConversationContextTranscriptEntries(record, location, visibility, runActor) {
139
- if (location?.provider !== "slack" || visibility !== "public") return [];
140
- const state = await getPersistedThreadState(record.conversationId);
141
- const conversation = coerceThreadConversationState(state);
142
- await hydrateConversationMessages({
143
- conversation,
144
- conversationId: record.conversationId
145
- });
146
- const entries = [];
147
- for (const message of conversation.messages) {
148
- if (message.role !== "user") continue;
149
- if (!messageExistedAtRunCompletion(message, record.updatedAtMs)) continue;
150
- const text = sanitizeText(message.text);
151
- if (!text) continue;
152
- const author = slackContextAuthor(location, message);
153
- entries.push({
154
- type: "message",
155
- role: "user",
156
- text,
157
- provenance: {
158
- authority: "context",
159
- ...author ? { actor: author } : void 0
160
- },
161
- isRunActor: sameActorIdentity(author, runActor)
162
- });
163
- }
164
- return entries;
165
- }
166
- async function withPluginTaskLock(taskId, callback) {
167
- const state = getStateAdapter();
168
- await state.connect();
169
- const lock = await state.acquireLock(`plugin:task:${taskId}`, PLUGIN_TASK_LOCK_TTL_MS);
170
- if (!lock) throw new Error(`Could not acquire plugin task lock for ${taskId}`);
171
- try {
172
- return await callback();
173
- } finally {
174
- await state.releaseLock(lock);
175
- }
176
- }
177
- /** Load the bounded completed-run projection exposed to plugin tasks. */
178
- async function loadPluginRun(params) {
179
- const record = await getTurnRecord(params.conversationId, params.sessionId);
180
- if (!record) throw new Error("Completed plugin task session record is unavailable");
181
- if (record.state !== "completed") throw new Error("Completed plugin task session record is not completed");
182
- const conversationStore = getConversationStore();
183
- const routing = await resolveConversationRouting({
184
- conversationId: params.conversationId,
185
- conversationStore
186
- });
187
- if (!routing) throw new Error(`Conversation ${params.conversationId} is missing durable routing metadata`);
188
- const source = record.source ?? routing.source;
189
- if (!source) throw new Error("Completed plugin task session record is missing Source");
190
- const conversation = await conversationStore.get({ conversationId: params.conversationId });
191
- const runActor = record.actor ?? record.actors[0] ?? (record.dispatchId ? (await getDispatchRecord(record.dispatchId))?.actor : void 0);
192
- const actorUser = runActor ? (await readActorIdentity(runActor))?.user : void 0;
193
- const runEntries = turnMessagesWithProvenance(record).map(({ message, provenance }) => runTranscriptEntry(message, provenance, runActor)).filter((entry) => Boolean(entry));
194
- const runMessageTexts = new Set(runEntries.filter((entry) => entry.type === "message").map((entry) => entry.text));
195
- const contextEntries = (await loadConversationContextTranscriptEntries(record, conversation?.location, conversation?.visibility, runActor)).filter((entry) => entry.type !== "message" || !runMessageTexts.has(entry.text));
196
- return pluginRunContextSchema.parse({
197
- ...actorUser ? { actorUserId: actorUser.id } : void 0,
198
- completedAtMs: record.updatedAtMs,
199
- conversationId: record.conversationId,
200
- destination: routing.destination,
201
- ...routing.location ? { locationId: routing.location.id } : void 0,
202
- actors: record.actors,
203
- ...runActor ? { actor: runActor } : void 0,
204
- runId: record.turnId,
205
- source,
206
- transcript: [...contextEntries, ...runEntries]
207
- });
208
- }
209
- /** Build the plugin-facing context for one claimed task attempt. */
210
- function taskPluginContext(plugin, message, options = {}) {
211
- const pluginName = plugin.manifest.name;
212
- const sessionParams = pluginTaskParamsSchema.parse(message.params);
213
- const onCost = createPluginModelCostRecorder({
214
- conversationId: sessionParams.conversationId,
215
- pluginName,
216
- source: "task",
217
- turnId: sessionParams.sessionId
218
- });
219
- return {
220
- db: getDb(),
221
- embedder: createPluginEmbedder(pluginName, {
222
- onCost,
223
- signal: options.signal
224
- }),
225
- events: createPluginConversationEvents({
226
- conversationId: sessionParams.conversationId,
227
- operationId: pluginTaskId(message),
228
- plugin,
229
- turnId: sessionParams.sessionId
230
- }),
231
- id: pluginTaskId(message),
232
- log: createPluginLogger(pluginName),
233
- model: createPluginModel(pluginName, plugin.model, {
234
- onCost,
235
- signal: options.signal
236
- }),
237
- name: message.name,
238
- plugin: { name: pluginName },
239
- cache: createPluginCache(pluginName),
240
- run: { async load() {
241
- return await loadPluginRun(sessionParams);
242
- } },
243
- state: createPluginState(pluginName),
244
- turnEvents: createPluginTurnEventReader({
245
- conversationId: sessionParams.conversationId,
246
- plugin,
247
- turnId: sessionParams.sessionId
248
- })
249
- };
250
- }
251
- function findPluginTask(message) {
252
- const plugin = getRegistrations().find((candidate) => candidate.manifest.name === message.plugin);
253
- if (!plugin?.tasks || !Object.hasOwn(plugin.tasks, message.name)) return;
254
- return {
255
- plugin,
256
- task: plugin.tasks[message.name]
257
- };
258
- }
259
- /** Schedule all plugin tasks interested in a completed agent-run session. */
260
- async function scheduleSessionCompletedPluginTasks(params, send) {
261
- const coreParams = pluginTaskParamsSchema.parse(params);
262
- const taskRegistrations = getRegistrations().flatMap((plugin) => Object.keys(plugin.tasks ?? {}).map((name) => ({
263
- name,
264
- plugin
265
- })));
266
- if (taskRegistrations.length === 0) return;
267
- const record = await getTurnRecord(coreParams.conversationId, coreParams.sessionId);
268
- if (!record || record.state !== "completed") throw new Error("Completed plugin task session record is not ready");
269
- const messages = taskRegistrations.map(({ name, plugin }) => ({
270
- name,
271
- params: coreParams,
272
- plugin: plugin.manifest.name
273
- }));
274
- await mapBounded(messages, async (message) => {
275
- await send(message);
276
- }, PLUGIN_MESSAGE_SEND_CONCURRENCY);
277
- }
278
- /**
279
- * Execute one parsed plugin task request in a `plugin.task` span. The span
280
- * includes the lock wait, because both delay the work that runs the task.
281
- */
282
- async function processPluginTask(message, options = {}) {
283
- const params = pluginTaskParamsSchema.parse(message.params);
284
- await withSpan(`plugin.task ${message.plugin}.${message.name}`, "plugin.task", { conversationId: params.conversationId }, () => withPluginTaskLock(pluginTaskId(message), async () => {
285
- const resolved = findPluginTask(message);
286
- if (!resolved?.task) throw new Error(`Plugin task "${message.plugin}.${message.name}" is not registered`);
287
- await resolved.task.run(taskPluginContext(resolved.plugin, message, options));
288
- }), {
289
- "app.ai.turn.session_id": params.sessionId,
290
- "app.plugin.name": message.plugin,
291
- "app.plugin.task": message.name
292
- });
293
- }
294
- export { scheduleSessionCompletedPluginTasks as n, task_runner_exports as r, processPluginTask as t };