@sentry/junior 0.305.0 → 0.307.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 (98) hide show
  1. package/dist/{adapter-context-BpvbUki8.js → adapter-context-B69WPn6b.js} +2 -2
  2. package/dist/{admin-CoDt35ny.js → admin-nCJXMgkp.js} +2 -2
  3. package/dist/{agent-runner-C5d6rY5g.js → agent-runner-DdFcxAxG.js} +463 -303
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +7 -8
  6. package/dist/api.d.ts +19 -4
  7. package/dist/api.js +437 -310
  8. package/dist/{app-Cs157Zc5.d.ts → app-EZur8cVC.d.ts} +12 -3
  9. package/dist/app.d.ts +2 -2
  10. package/dist/app.js +532 -439
  11. package/dist/background-compaction-queue-BhEe4UfU.js +231 -0
  12. package/dist/{briefs-BRdznF7c.js → briefs-Dl9lxi7J.js} +3 -3
  13. package/dist/{catalog-runtime-J52Tej47.js → catalog-runtime-OXrv2Ewn.js} +1 -1
  14. package/dist/cli/chat.d.ts +1 -1
  15. package/dist/cli/chat.js +17 -16
  16. package/dist/cli/check.js +58 -48
  17. package/dist/cli/main.js +3 -3
  18. package/dist/cli/plugins.d.ts +1 -1
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +5 -5
  21. package/dist/cli/upgrade.d.ts +2 -2
  22. package/dist/cli/upgrade.js +3 -8
  23. package/dist/{config-CBZp0udd.js → config-362yMSIz.js} +183 -49
  24. package/dist/{connections-BYmuJ6Vm.js → connections-BJv3EjmB.js} +10 -8
  25. package/dist/{continue-in-slack-Cvot6S38.js → continue-in-slack-CFEevC7z.js} +5 -5
  26. package/dist/{conversation-BOqdRtUx.js → conversation--f85g4zL.js} +132 -132
  27. package/dist/{conversation-feed-CgpgP7yi.js → conversation-feed-BNs9KiqC.js} +1 -1
  28. package/dist/{conversation-privacy-D2pOzBNl.js → conversation-privacy-Tjj5P2W6.js} +1 -1
  29. package/dist/{conversation-turn-CI8WDpnK.js → conversation-turn-DU0_WDAr.js} +26 -72
  30. package/dist/{credential-sync-COqnZ1Dx.js → credential-sync-D6aFARKE.js} +28 -27
  31. package/dist/{db-DU84dCVu.js → db-Bcbd9zQc.js} +226 -18
  32. package/dist/{db-zbN5ZV_o.d.ts → db-C41UgdBj.d.ts} +1 -1
  33. package/dist/{executor-CFyrgOu1.js → executor-DBMBrpNV.js} +137 -33
  34. package/dist/{history-m2-ceTTX.js → history-N7IVbUom.js} +5 -1
  35. package/dist/{install-CQ76CfRw.js → install-CgoAbzfF.js} +2 -2
  36. package/dist/instrumentation.js +2 -2
  37. package/dist/{lineage-DLd2UxVP.js → lineage-CsZDmz3e.js} +2 -2
  38. package/dist/{logging-BPNTQVFu.js → logging-CHCuQ5iz.js} +1 -1
  39. package/dist/{message-BWJLeQ5e.js → message-B8vCbZZB.js} +8 -8
  40. package/dist/{model-input-DoM9Ht-d.js → model-input-Xluiy-1W.js} +3 -3
  41. package/dist/nitro.d.ts +2 -2
  42. package/dist/nitro.js +3 -4
  43. package/dist/{oauth-callback-server-DeHbnAQl.js → oauth-callback-server-BUuNvfvu.js} +2 -2
  44. package/dist/{oauth-relay-DAmfVmJu.js → oauth-relay-DGAZzg9m.js} +1 -1
  45. package/dist/{plugins-B_0Cr0MO.d.ts → plugins-fBrz8PCV.d.ts} +2 -0
  46. package/dist/{projection-CcFBVFUo.js → projection-xPpvqexa.js} +13423 -11432
  47. package/dist/{prompt-C5LREK2p.js → prompt-D8u4jFs_.js} +15 -7
  48. package/dist/{registry-BjZZqKqi.js → registry-D20hG3r6.js} +19 -9
  49. package/dist/{resolve-CeJgXuH1.js → resolve-BhCySRCW.js} +3 -3
  50. package/dist/{result-icDrueyB.js → result-DddO63S9.js} +13 -11
  51. package/dist/{runner-nVfMkMMB.js → runner-DQR9vYce.js} +13 -15
  52. package/dist/{sandbox-egress-signals-H9vQ5qRf.js → sandbox-egress-signals-DFlNUOnK.js} +1 -1
  53. package/dist/{automation-CuA3yEcD.js → schedule-BG1tEbRF.js} +380 -8
  54. package/dist/{schema-CKcu-IK6.d.ts → schema-CRXcj4fj.d.ts} +420 -143
  55. package/dist/{schema-Bx0Mlo32.js → schema-D4jdesIu.js} +62 -8
  56. package/dist/{service-account-DU5865XA.js → service-account-Bv5QwrEq.js} +8 -6
  57. package/dist/{service-account-Dw06p3zm.js → service-account-CNfycv0z.js} +3 -3
  58. package/dist/{session-stop-uotLtp4g.js → session-stop-BDdwyZaa.js} +878 -171
  59. package/dist/{skills-Bex1EaO5.js → skills-63i1Bcv1.js} +32 -28
  60. package/dist/{slack-conversation-unfurl-EPG3riWF.js → slack-conversation-unfurl-DtpBUlUu.js} +10 -9
  61. package/dist/{spawn-CoD3vDuS.js → spawn-mwimEY9_.js} +6 -6
  62. package/dist/{state-nCR4Muhn.js → state-BBn9L6gC.js} +4 -4
  63. package/dist/{stop-BFVd0P0m.js → stop-Da-Ug7tg.js} +172 -239
  64. package/dist/{store-Ca6G962n.js → store-CdWg2r2L.js} +5 -5
  65. package/dist/{background-compaction-queue-BTqMIfTA.js → task-queue-BcjAYWyB.js} +164 -180
  66. package/dist/{task-runner-xsOPIxCZ.js → task-runner-CoXmMlsW.js} +13 -11
  67. package/dist/{thread-context-BOvZhsKK.js → thread-context-ZPGqOjW7.js} +8 -91
  68. package/dist/turn-session-routing-DFYak28Q.js +263 -0
  69. package/dist/{turn-user-message-BrhuyYrH.js → turn-user-message-B1S8nOnG.js} +3 -3
  70. package/dist/users-DDbENg-I.js +181 -0
  71. package/dist/{validation-BnY9K5WB.js → validation-fl21ps-k.js} +1 -1
  72. package/dist/{version-qROlRQGF.js → version-DCdMMx_0.js} +1 -1
  73. package/dist/version.js +1 -1
  74. package/dist/{viewer-CxUiOraX.js → viewer-DN_xzVKj.js} +3 -3
  75. package/dist/{warmup--Gkz7iB-.js → warmup-CxhEhm71.js} +842 -532
  76. package/dist/{web-message-id-lNodcCOI.js → web-message-id-BT8Mg8LL.js} +16 -1
  77. package/dist/{worker-DJ8d9fmD.js → worker-Btb1SB5h.js} +8 -7
  78. package/migrations/0114_plan_items.sql +22 -0
  79. package/migrations/0115_automation_creator_slack_index.sql +1 -0
  80. package/migrations/0116_conversation_event_search.sql +25 -0
  81. package/migrations/0117_automation_last_run.sql +46 -0
  82. package/migrations/0118_automation_last_run_index.sql +1 -0
  83. package/migrations/0119_money_micro_usd.sql +29 -0
  84. package/migrations/0120_conversation_cost_micro_usd.sql +8 -0
  85. package/migrations/meta/0114_snapshot.json +5203 -0
  86. package/migrations/meta/0115_snapshot.json +5225 -0
  87. package/migrations/meta/0116_snapshot.json +5388 -0
  88. package/migrations/meta/0117_snapshot.json +5413 -0
  89. package/migrations/meta/0118_snapshot.json +5428 -0
  90. package/migrations/meta/0119_snapshot.json +5441 -0
  91. package/migrations/meta/0120_snapshot.json +5441 -0
  92. package/migrations/meta/_journal.json +49 -0
  93. package/package.json +10 -9
  94. package/dist/queue-B2AAL3ym.js +0 -115
  95. package/dist/schedule-cP0AACm1.js +0 -344
  96. package/dist/secrets-DHaJ5TTn.js +0 -18
  97. package/dist/task-queue-BLPZU6kC.js +0 -89
  98. package/dist/turn-session-routing-2bW2qfeb.js +0 -1792
@@ -1,7 +1,7 @@
1
- import { a as getConversationStore } from "./db-DU84dCVu.js";
2
- import { p as logException } from "./logging-BPNTQVFu.js";
3
- import "./background-compaction-queue-BTqMIfTA.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-CcFBVFUo.js";
1
+ import { a as getConversationStore } from "./db-Bcbd9zQc.js";
2
+ import { p as logException } from "./logging-CHCuQ5iz.js";
3
+ import "./background-compaction-queue-BhEe4UfU.js";
4
+ import { At as hasRunnableConversationWork, Bt as releaseInboundMessage, Dt as getConversationWorkState$1, Et as getConversation$1, Gt as stopConversationWork$1, Ht as requestConversationWork$1, Kt as takeDeferredConversationMove, Lt as recordAttemptFailure$1, Nt as listActiveConversationIds$1, Ot as getConversationWorkStates$1, Pt as markConversationWorkEnqueued$1, Rt as recordConversationRetry$1, St as deadLetterAttempt$1, Tt as dropPendingMessages$1, Ut as startConversationWork$1, Vt as requestAnotherSlice$1, Wt as steerWebPendingMessages$1, _t as clearConsumedConversationWake$1, bt as completeConversationWork$1, dt as appendExclusiveInboundMessage, ft as appendInboundMessage, gt as claimInboundMessage$1, ht as checkInConversationWork$1, mt as cancelHumanFacingPendingMessages$1, pt as beginConversationResume$1, ut as ackMessages$1, vt as clearExpiredConversationLease$1, wt as drainConversationMailbox$1, yt as completeConversationStop$1, zt as releaseConversationWork$1 } from "./projection-xPpvqexa.js";
5
5
  // src/chat/task-execution/store.ts
6
6
  function metadataStore(options) {
7
7
  return options.conversationStore ?? getConversationStore();
@@ -304,7 +304,7 @@ async function runDeferredMove(args) {
304
304
  const move = await takeDeferredConversationMove(args);
305
305
  if (move === void 0) return;
306
306
  try {
307
- const { continueDeferredSlackClick } = await import("./slack-conversation-unfurl-EPG3riWF.js").then((n) => n.r);
307
+ const { continueDeferredSlackClick } = await import("./slack-conversation-unfurl-DtpBUlUu.js").then((n) => n.r);
308
308
  await continueDeferredSlackClick(move, args.getSlackAdapter);
309
309
  } catch (error) {
310
310
  logException(error, "slack.continue_here.deferred.failed", { "gen_ai.conversation.id": args.conversationId });
@@ -1,54 +1,9 @@
1
- import { i as getChatConfig } from "./config-CBZp0udd.js";
2
- import { E as withSpan, m as logInfo, p as logException } from "./logging-BPNTQVFu.js";
3
- import { t as readJuniorSecret } from "./secrets-DHaJ5TTn.js";
1
+ import { h as logWarn, m as logInfo, p as logException } from "./logging-CHCuQ5iz.js";
2
+ import { i as getChatConfig } from "./config-362yMSIz.js";
4
3
  import * as z from "zod";
5
4
  import { AsyncLocalStorage } from "node:async_hooks";
6
5
  import { createHash, createHmac, timingSafeEqual } from "node:crypto";
7
6
  import { QueueClient, handleCallback, registerDevConsumer } from "@vercel/queue";
8
- /** Validate the v2 conversation work hint sent through Vercel Queue. */
9
- const conversationQueueMessageSchema = z.object({
10
- schemaVersion: z.literal(2),
11
- conversationId: z.string().trim().min(1)
12
- }).strict();
13
- var ConversationQueueMessageRejectedError = class extends Error {
14
- conversationId;
15
- reason;
16
- constructor(reason, message, options = {}) {
17
- super(message);
18
- this.name = "ConversationQueueMessageRejectedError";
19
- this.reason = reason;
20
- this.conversationId = options.conversationId;
21
- }
22
- };
23
- /** Return whether an error means the queue message was permanently rejected. */
24
- function isConversationQueueMessageRejectedError(error) {
25
- return error instanceof ConversationQueueMessageRejectedError;
26
- }
27
- /** Build the idempotency key of a wake that one worker event sends. */
28
- function nudgeIdempotencyKey(reason, conversationId, nowMs) {
29
- return `${reason}:${conversationId}:${nowMs}`;
30
- }
31
- // src/chat/runtime/request-deadline.ts
32
- const requestDeadlineStorage = new AsyncLocalStorage();
33
- function createTurnRequestDeadline(startedAtMs) {
34
- return {
35
- startedAtMs,
36
- deadlineAtMs: startedAtMs + Math.max(1, getChatConfig().functionMaxDurationSeconds * 1e3 - 2e4)
37
- };
38
- }
39
- /** Return the host request deadline inherited by the current async turn. */
40
- function getTurnRequestDeadline() {
41
- return requestDeadlineStorage.getStore();
42
- }
43
- /** Run work with one host request deadline shared by nested queued turns. */
44
- function runWithTurnRequestDeadline(callback, startedAtMs = Date.now()) {
45
- if (requestDeadlineStorage.getStore()) return callback();
46
- return runWithNewTurnRequestDeadline(callback, startedAtMs);
47
- }
48
- /** Run work that a new host request owns, even inside another request. */
49
- function runWithNewTurnRequestDeadline(callback, startedAtMs = Date.now()) {
50
- return requestDeadlineStorage.run(createTurnRequestDeadline(startedAtMs), callback);
51
- }
52
7
  // src/chat/queue/bullmq.ts
53
8
  const MAX_ATTEMPTS = 50;
54
9
  const MAX_BACKOFF_MS = 3e4;
@@ -212,6 +167,94 @@ const vercelQueueProvider = {
212
167
  function getQueueProvider() {
213
168
  return getChatConfig().queue.provider === "bullmq" ? bullmqQueueProvider : vercelQueueProvider;
214
169
  }
170
+ // src/chat/runtime/request-deadline.ts
171
+ const requestDeadlineStorage = new AsyncLocalStorage();
172
+ function createTurnRequestDeadline(startedAtMs) {
173
+ return {
174
+ startedAtMs,
175
+ deadlineAtMs: startedAtMs + Math.max(1, getChatConfig().functionMaxDurationSeconds * 1e3 - 2e4)
176
+ };
177
+ }
178
+ /** Return the host request deadline inherited by the current async turn. */
179
+ function getTurnRequestDeadline() {
180
+ return requestDeadlineStorage.getStore();
181
+ }
182
+ /** Run work under the current host request deadline, or start one. */
183
+ function runWithTurnRequestDeadline(callback, startedAtMs = Date.now()) {
184
+ if (requestDeadlineStorage.getStore()) return callback();
185
+ return runWithNewTurnRequestDeadline(callback, startedAtMs);
186
+ }
187
+ /** Run work that a new host request owns, even inside another request. */
188
+ function runWithNewTurnRequestDeadline(callback, startedAtMs = Date.now()) {
189
+ return requestDeadlineStorage.run(createTurnRequestDeadline(startedAtMs), callback);
190
+ }
191
+ // src/chat/queue/callback.ts
192
+ /** Shared queue callback wiring for signed messages. */
193
+ /** Build the HTTP callback and local-dev consumer for one signed queue. */
194
+ function queueCallback(options) {
195
+ const consume = async (message, metadata) => {
196
+ if (options.skip?.(metadata)) return;
197
+ try {
198
+ await runWithTurnRequestDeadline(() => options.run(message, metadata));
199
+ } catch (error) {
200
+ const reason = options.permanentError?.(error);
201
+ if (!reason) throw error;
202
+ options.onRejected(reason, metadata, error);
203
+ }
204
+ };
205
+ const handler = async (value, metadata) => {
206
+ if (options.skip?.(metadata)) return;
207
+ const checked = options.verify(value);
208
+ if (checked.status === "rejected") {
209
+ options.onRejected(checked.reason, metadata);
210
+ return;
211
+ }
212
+ if (checked.status === "unavailable") throw new Error(`Queue message verification unavailable: ${checked.reason}`);
213
+ await runWithNewTurnRequestDeadline(() => consume(checked.message, metadata));
214
+ };
215
+ const retry = (error, metadata) => {
216
+ const reason = options.permanentError?.(error);
217
+ if (reason) {
218
+ options.onRejected(reason, metadata, error);
219
+ return { acknowledge: true };
220
+ }
221
+ if (options.maxDeliveries !== null && metadata.deliveryCount >= options.maxDeliveries) return { acknowledge: true };
222
+ };
223
+ const consumer = {
224
+ consumerGroup: options.consumerGroup,
225
+ handler,
226
+ retry,
227
+ topic: options.topic,
228
+ visibilityTimeoutSeconds: options.visibilityTimeoutSeconds
229
+ };
230
+ return {
231
+ /** Run a message that an in-process queue already trusts. */
232
+ consume,
233
+ consumer,
234
+ create: () => getQueueProvider().createCallback(consumer),
235
+ registerDev: () => {
236
+ if (process.env["NODE_ENV"] !== "development") return;
237
+ return getQueueProvider().registerDevConsumer?.(consumer);
238
+ }
239
+ };
240
+ }
241
+ // src/chat/secrets.ts
242
+ /** Read the server secret that signs internal tokens and payloads. */
243
+ function readJuniorSecret() {
244
+ return process.env["JUNIOR_SECRET"]?.trim() || void 0;
245
+ }
246
+ /** Read the raw dashboard session secret, with `JUNIOR_SECRET` as fallback. */
247
+ function readSignInSecret() {
248
+ return process.env["BETTER_AUTH_SECRET"] ?? process.env["JUNIOR_SECRET"];
249
+ }
250
+ /** Read the bearer secret that internal cron requests must send. */
251
+ function readSchedulerSecret() {
252
+ return process.env["JUNIOR_SCHEDULER_SECRET"]?.trim() || process.env["CRON_SECRET"]?.trim();
253
+ }
254
+ /** Read the VAPID private key that signs web push messages. */
255
+ function readWebPushPrivateKey() {
256
+ return process.env["JUNIOR_WEB_PUSH_PRIVATE_KEY"]?.trim();
257
+ }
215
258
  // src/chat/queue/sign.ts
216
259
  /** Sign and check queue messages before public callbacks run them. */
217
260
  const QUEUE_SIGNATURE_MAX_AGE_MS = 36e5;
@@ -295,147 +338,88 @@ function verifyQueueMessage(config, value, nowMs = Date.now()) {
295
338
  message: message.data
296
339
  };
297
340
  }
298
- // src/chat/task-execution/queue-signing.ts
299
- const conversationQueueSign = {
300
- context: "junior.conversation_work_queue.v2",
301
- schema: conversationQueueMessageSchema,
302
- separator: ":",
303
- signatureVersion: "v2",
304
- parts: (message) => [message.conversationId]
305
- };
306
- const CONVERSATION_WORK_QUEUE_SIGNATURE_MAX_SKEW_MS = QUEUE_SIGNATURE_MAX_AGE_MS;
307
- /** Sign a conversation queue payload before it crosses the public callback route. */
308
- function signConversationQueueMessage(message, nowMs = Date.now()) {
309
- return signQueueMessage(conversationQueueSign, message, nowMs);
310
- }
311
- /** Explain whether a queue payload is verified, rejected, or unavailable. */
312
- function verifyConversationQueueMessage(value, nowMs = Date.now()) {
313
- return verifyQueueMessage(conversationQueueSign, value, nowMs);
314
- }
315
- const CONVERSATION_WORK_QUEUE_RETENTION_SECONDS = CONVERSATION_WORK_QUEUE_SIGNATURE_MAX_SKEW_MS / 1e3;
316
- let defaultQueue;
317
- /** Resolve the Vercel Queue topic used for conversation wake-up nudges. */
318
- function resolveConversationWorkQueueTopic(options = {}) {
319
- return options.topic?.trim() || process.env["JUNIOR_CONVERSATION_WORK_QUEUE_TOPIC"]?.trim() || "junior_conversation_work";
320
- }
321
- function toDelaySeconds(options) {
322
- if (!options?.delayMs || options.delayMs <= 0) return;
323
- return Math.ceil(options.delayMs / 1e3);
324
- }
325
- /** Create the Vercel Queue implementation for conversation wake-up nudges. */
326
- function createVercelConversationWorkQueue(options = {}) {
327
- const topic = resolveConversationWorkQueueTopic(options);
328
- const client = options.client ?? getQueueProvider();
329
- return { async send(message, sendOptions) {
330
- const payload = signConversationQueueMessage(message);
331
- return await withSpan("conversation.work.publish", "queue.publish", { conversationId: message.conversationId }, async (setSpanAttributes) => {
332
- const result = await client.send(topic, payload, {
333
- idempotencyKey: sendOptions?.idempotencyKey,
334
- delaySeconds: toDelaySeconds(sendOptions),
335
- retentionSeconds: options.retentionSeconds ?? CONVERSATION_WORK_QUEUE_RETENTION_SECONDS
336
- });
337
- if (!result.messageId) return {};
338
- setSpanAttributes({ "messaging.message.id": result.messageId });
339
- return { messageId: result.messageId };
340
- }, {
341
- "messaging.destination.name": topic,
342
- "messaging.message.body.size": Buffer.byteLength(JSON.stringify(payload)),
343
- "messaging.system": getQueueProvider().messagingSystem
344
- });
345
- } };
346
- }
347
- /** Return the default production conversation work queue. */
348
- function getVercelConversationWorkQueue() {
349
- defaultQueue ??= createVercelConversationWorkQueue();
350
- return defaultQueue;
351
- }
352
- // src/chat/queue/callback.ts
353
- /** Shared queue callback wiring for signed messages. */
354
- /** Build the HTTP callback and local-dev consumer for one signed queue. */
355
- function queueCallback(options) {
356
- const consume = async (message, metadata) => {
357
- if (options.skip?.(metadata)) return;
358
- try {
359
- await runWithTurnRequestDeadline(() => options.run(message, metadata));
360
- } catch (error) {
361
- const reason = options.permanentError?.(error);
362
- if (!reason) throw error;
363
- options.onRejected(reason, metadata, error);
364
- }
365
- };
366
- const handler = async (value, metadata) => {
367
- if (options.skip?.(metadata)) return;
368
- const checked = options.verify(value);
369
- if (checked.status === "rejected") {
370
- options.onRejected(checked.reason, metadata);
371
- return;
372
- }
373
- if (checked.status === "unavailable") throw new Error(`Queue message verification unavailable: ${checked.reason}`);
374
- await runWithNewTurnRequestDeadline(() => consume(checked.message, metadata));
375
- };
376
- const retry = (error, metadata) => {
377
- const reason = options.permanentError?.(error);
378
- if (reason) {
379
- options.onRejected(reason, metadata, error);
380
- return { acknowledge: true };
381
- }
382
- if (options.maxDeliveries !== null && metadata.deliveryCount >= options.maxDeliveries) return { acknowledge: true };
383
- };
384
- const consumer = {
385
- consumerGroup: options.consumerGroup,
386
- handler,
387
- retry,
388
- topic: options.topic,
389
- visibilityTimeoutSeconds: options.visibilityTimeoutSeconds
390
- };
391
- return {
392
- /** Run a message that an in-process queue already trusts. */
393
- consume,
394
- consumer,
395
- create: () => getQueueProvider().createCallback(consumer),
396
- registerDev: () => {
397
- if (process.env["NODE_ENV"] !== "development") return;
398
- return getQueueProvider().registerDevConsumer?.(consumer);
399
- }
400
- };
401
- }
402
- // src/chat/services/background-compaction-queue.ts
341
+ // src/chat/plugins/task-queue.ts
403
342
  /**
404
- * Messages of background compaction jobs.
343
+ * Delivery for plugin-registered tasks.
405
344
  *
406
- * A message names one `compaction_requested` event. The event log holds the
407
- * request, and the State adapter holds the request snapshot, so the message
408
- * stays small.
345
+ * Plugins register named tasks. This module owns the shared signed message,
346
+ * send path, and HTTP/local callback. Core keeps one topic and one runner.
409
347
  */
410
348
  /** Deploy topic name. Keep stable for Vercel queue wiring. */
411
- const BACKGROUND_COMPACTION_QUEUE_TOPIC = "junior_context_compaction";
412
- const backgroundCompactionSign = {
413
- context: "junior.context_compaction_queue.v1",
349
+ const PLUGIN_TASK_QUEUE_TOPIC = "junior_plugin_tasks";
350
+ const PLUGIN_TASK_DEV_CONSUMER_GROUP = "junior_plugin_tasks_dev";
351
+ const PLUGIN_TASK_MAX_DELIVERIES = 5;
352
+ const PLUGIN_TASK_SIGN_CONTEXT = "junior.plugin_task_queue.v1";
353
+ const PLUGIN_TASK_SIGN_VERSION = "v1";
354
+ const pluginTaskParamsSchema = z.object({
355
+ conversationId: z.string().min(1),
356
+ sessionId: z.string().min(1)
357
+ }).strict();
358
+ const pluginTaskSign = {
359
+ context: PLUGIN_TASK_SIGN_CONTEXT,
414
360
  schema: z.object({
415
- conversationId: z.string().min(1),
416
- historyVersion: z.number().int().nonnegative(),
417
- markSeq: z.number().int().nonnegative()
361
+ name: z.string().min(1),
362
+ params: pluginTaskParamsSchema,
363
+ plugin: z.string().min(1)
418
364
  }).strict(),
419
- signatureVersion: "v1",
365
+ signatureVersion: PLUGIN_TASK_SIGN_VERSION,
420
366
  parts: (message) => [
421
- message.conversationId,
422
- String(message.historyVersion),
423
- String(message.markSeq)
367
+ message.plugin,
368
+ message.name,
369
+ message.params.conversationId,
370
+ message.params.sessionId
424
371
  ]
425
372
  };
426
- /** Stable id of one request, for event, snapshot, and delivery dedupe. */
427
- function backgroundCompactionId(message) {
428
- return `context-compaction_${createHash("sha256").update(message.conversationId).update("\0").update(String(message.historyVersion)).update("\0").update(String(message.markSeq)).digest("hex").slice(0, 32)}`;
429
- }
430
- /** Check that a recent queue message came from Junior. */
431
- function verifyBackgroundCompactionMessage(value) {
432
- return verifyQueueMessage(backgroundCompactionSign, value);
433
- }
434
- /** The production queue for background compaction jobs. */
435
- const vercelBackgroundCompactionQueue = { send: async (message) => {
436
- await getQueueProvider().send(BACKGROUND_COMPACTION_QUEUE_TOPIC, signQueueMessage(backgroundCompactionSign, message), {
437
- idempotencyKey: backgroundCompactionId(message),
373
+ /** Build the stable id used for delivery dedupe and tracing. */
374
+ function pluginTaskId(args) {
375
+ return `plugin-task_${createHash("sha256").update(args.plugin).update("\0").update(args.name).update("\0").update(args.params.conversationId).update("\0").update(args.params.sessionId).digest("hex").slice(0, 32)}`;
376
+ }
377
+ /** Sign a plugin task message for tests and local checks. */
378
+ function signPluginTaskQueueMessage(message, nowMs = Date.now()) {
379
+ return signQueueMessage(pluginTaskSign, message, nowMs);
380
+ }
381
+ function verifyPluginTaskQueueMessage(value, nowMs = Date.now()) {
382
+ return verifyQueueMessage(pluginTaskSign, value, nowMs);
383
+ }
384
+ function logPluginTaskQueueMessageRejected(reason, metadata) {
385
+ logWarn("plugin.task.queue_message.rejected", {
386
+ "app.queue.consumer_group": metadata.consumerGroup,
387
+ "app.queue.delivery_count": metadata.deliveryCount,
388
+ "app.queue.message_id": metadata.messageId,
389
+ "app.queue.reject_reason": reason,
390
+ "app.queue.topic_name": metadata.topicName
391
+ });
392
+ }
393
+ function pluginTaskCallback() {
394
+ return queueCallback({
395
+ consumerGroup: PLUGIN_TASK_DEV_CONSUMER_GROUP,
396
+ maxDeliveries: PLUGIN_TASK_MAX_DELIVERIES,
397
+ onRejected: logPluginTaskQueueMessageRejected,
398
+ run: async (message) => {
399
+ const { processPluginTask } = await import("./task-runner-CoXmMlsW.js").then((n) => n.r);
400
+ await processPluginTask(message);
401
+ },
402
+ topic: PLUGIN_TASK_QUEUE_TOPIC,
403
+ verify: verifyPluginTaskQueueMessage
404
+ });
405
+ }
406
+ /** Send one plugin task through the shared signed delivery path. */
407
+ async function sendVercelPluginTask(message) {
408
+ await getQueueProvider().send(PLUGIN_TASK_QUEUE_TOPIC, signPluginTaskQueueMessage(message), {
409
+ idempotencyKey: pluginTaskId(message),
438
410
  retentionSeconds: QUEUE_SIGNATURE_MAX_AGE_MS / 1e3
439
411
  });
440
- } };
441
- export { nudgeIdempotencyKey as _, queueCallback as a, verifyConversationQueueMessage as c, verifyQueueMessage as d, getQueueProvider as f, isConversationQueueMessageRejectedError as g, conversationQueueMessageSchema as h, verifyBackgroundCompactionMessage as i, QUEUE_SIGNATURE_MAX_AGE_MS as l, ConversationQueueMessageRejectedError as m, backgroundCompactionId as n, getVercelConversationWorkQueue as o, getTurnRequestDeadline as p, vercelBackgroundCompactionQueue as r, resolveConversationWorkQueueTopic as s, BACKGROUND_COMPACTION_QUEUE_TOPIC as t, signQueueMessage as u };
412
+ }
413
+ /** Create the HTTP callback for plugin tasks. */
414
+ function createVercelPluginTaskCallback() {
415
+ return pluginTaskCallback().create();
416
+ }
417
+ /** Return the queue consumer for plugin tasks, for a pulling queue worker. */
418
+ function pluginTaskQueueConsumer() {
419
+ return pluginTaskCallback().consumer;
420
+ }
421
+ /** Register the local-dev consumer for plugin tasks. */
422
+ function registerVercelPluginTaskDevConsumer() {
423
+ return pluginTaskCallback().registerDev();
424
+ }
425
+ export { getQueueProvider as _, pluginTaskQueueConsumer as a, QUEUE_SIGNATURE_MAX_AGE_MS as c, readJuniorSecret as d, readSchedulerSecret as f, getTurnRequestDeadline as g, queueCallback as h, pluginTaskParamsSchema as i, signQueueMessage as l, readWebPushPrivateKey as m, createVercelPluginTaskCallback as n, registerVercelPluginTaskDevConsumer as o, readSignInSecret as p, pluginTaskId as r, sendVercelPluginTask as s, PLUGIN_TASK_QUEUE_TOPIC as t, verifyQueueMessage as u };
@@ -1,12 +1,13 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { Bi as createPluginState, Dn as instructionTextForProjection, Fn as stripRuntimeTurnContext, Mn as isToolResultMessage, Nn as normalizeToolNameFromResult, Oo as createPluginConversationEvents, Sn as getPiMessageRole, _o as createPluginLogger, cr as getPlugins, fr as coreTaskRegistrations, go as createPluginModelCostRecorder, io as createPluginModel, jn as isToolResultError, ks as createPluginCache, ro as createPluginEmbedder, st as getTurnRecord, v as hydrateConversationMessages } from "./projection-CcFBVFUo.js";
3
- import { X as getStateAdapter, a as getConversationStore, o as getDb } from "./db-DU84dCVu.js";
4
- import { E as withSpan } from "./logging-BPNTQVFu.js";
5
- import { a as getPersistedThreadState, c as coerceThreadConversationState, g as getDispatchRecord, t as resolveConversationRouting } from "./turn-session-routing-2bW2qfeb.js";
6
- import { i as readActorIdentity } from "./viewer-CxUiOraX.js";
2
+ import { Ha as createPluginModelCostRecorder, Ln as coreTaskRegistrations, Mi as createPluginState, Nn as getPlugins, Oa as createPluginEmbedder, Qn as getPiMessageRole, Ua as createPluginLogger, Yo as getDispatchRecord, at as getTurnRecord, cr as isToolResultMessage, dr as stripRuntimeTurnContext, eo as createPluginConversationEvents, ka as createPluginModel, lr as normalizeToolNameFromResult, rr as instructionTextForProjection, sr as isToolResultError, ul as createPluginCache, v as hydrateConversationMessages } from "./projection-xPpvqexa.js";
3
+ import { $ as getStateAdapter, a as getConversationStore, o as getDb } from "./db-Bcbd9zQc.js";
4
+ import { E as withSpan } from "./logging-CHCuQ5iz.js";
5
+ import { a as getPersistedThreadState, c as coerceThreadConversationState, t as resolveConversationRouting } from "./turn-session-routing-DFYak28Q.js";
6
+ import { i as readActorIdentity } from "./viewer-DN_xzVKj.js";
7
7
  import { v as parseSlackMessageTs } from "./actor-D2iXzvlN.js";
8
- import { m as sameActorIdentity } from "./history-m2-ceTTX.js";
9
- import { i as pluginTaskParamsSchema, r as pluginTaskId, s as sendVercelPluginTask } from "./task-queue-BLPZU6kC.js";
8
+ import { m as sameActorIdentity } from "./history-N7IVbUom.js";
9
+ import { i as pluginTaskParamsSchema, r as pluginTaskId } from "./task-queue-BcjAYWyB.js";
10
+ import pLimit from "p-limit";
10
11
  import { pluginRunContextSchema } from "@sentry/junior-plugin-api";
11
12
  // src/chat/plugins/task-runner.ts
12
13
  /**
@@ -17,6 +18,7 @@ import { pluginRunContextSchema } from "@sentry/junior-plugin-api";
17
18
  * payloads.
18
19
  */
19
20
  var task_runner_exports = /* @__PURE__ */ __exportAll({ processPluginTask: () => processPluginTask });
21
+ const PLUGIN_MESSAGE_SEND_CONCURRENCY = 5;
20
22
  const PLUGIN_TASK_LOCK_TTL_MS = 3e5;
21
23
  function isRecord(value) {
22
24
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
@@ -248,7 +250,7 @@ function findPluginTask(message) {
248
250
  };
249
251
  }
250
252
  /** Schedule all plugin tasks interested in a completed agent-run session. */
251
- async function scheduleSessionCompletedPluginTasks(params, options = {}) {
253
+ async function scheduleSessionCompletedPluginTasks(params, send) {
252
254
  const coreParams = pluginTaskParamsSchema.parse(params);
253
255
  const taskRegistrations = [...getPlugins(), ...coreTaskRegistrations()].flatMap((plugin) => Object.keys(plugin.tasks ?? {}).map((name) => ({
254
256
  name,
@@ -257,15 +259,15 @@ async function scheduleSessionCompletedPluginTasks(params, options = {}) {
257
259
  if (taskRegistrations.length === 0) return;
258
260
  const record = await getTurnRecord(coreParams.conversationId, coreParams.sessionId);
259
261
  if (!record || record.state !== "completed") throw new Error("Completed plugin task session record is not ready");
260
- const send = options.send ?? sendVercelPluginTask;
261
262
  const messages = taskRegistrations.map(({ name, plugin }) => ({
262
263
  name,
263
264
  params: coreParams,
264
265
  plugin: plugin.manifest.name
265
266
  }));
266
- await Promise.all(messages.map(async (message) => {
267
+ const limit = pLimit(PLUGIN_MESSAGE_SEND_CONCURRENCY);
268
+ await Promise.all(messages.map((message) => limit(async () => {
267
269
  await send(message);
268
- }));
270
+ })));
269
271
  }
270
272
  /**
271
273
  * Execute one parsed plugin task request in a `plugin.task` span. The span
@@ -1,11 +1,10 @@
1
- import { E as buildConversationContext, X as clearPendingAuth, j as markConversationMessage, v as hydrateConversationMessages, xs as listConversationAnnotations } from "./projection-CcFBVFUo.js";
2
- import { J as getProviderErrorUserMessage, K as findProviderError, U as ProviderError, q as getProviderErrorAttributes } from "./config-CBZp0udd.js";
3
- import { K as isRecord, b as setSpanAttributes, t as buildTurnFailureResponse } from "./logging-BPNTQVFu.js";
4
- import { o as getDb, r as getConversationEventStore } from "./db-DU84dCVu.js";
5
- import { H as removedCardSchema, U as resolveMessageCards, V as readMessageCardRefs } from "./conversation-BOqdRtUx.js";
6
- import { a as getPersistedThreadState, c as coerceThreadConversationState, s as persistThreadStateById } from "./turn-session-routing-2bW2qfeb.js";
7
- import { S as listChildMessages, m as markTurnCompleted, n as getTurnUserMessageId, p as markTurnClosed, x as isAgentInvocationResult } from "./turn-user-message-BrhuyYrH.js";
8
- import { _ as getConversationWorkState } from "./store-Ca6G962n.js";
1
+ import { J as clearPendingAuth, Po as listConversationAnnotations, k as markConversationMessage, v as hydrateConversationMessages, w as buildConversationContext } from "./projection-xPpvqexa.js";
2
+ import { K as isRecord, b as setSpanAttributes } from "./logging-CHCuQ5iz.js";
3
+ import { o as getDb, r as getConversationEventStore } from "./db-Bcbd9zQc.js";
4
+ import { J as readMessageCardRefs, X as resolveMessageCards, Y as removedCardSchema } from "./conversation--f85g4zL.js";
5
+ import { S as listChildMessages, m as markTurnCompleted, n as getTurnUserMessageId, p as markTurnClosed, x as isAgentInvocationResult } from "./turn-user-message-B1S8nOnG.js";
6
+ import { _ as getConversationWorkState } from "./store-CdWg2r2L.js";
7
+ import { a as getPersistedThreadState, c as coerceThreadConversationState, s as persistThreadStateById } from "./turn-session-routing-DFYak28Q.js";
9
8
  // src/chat/conversations/pending-cards.ts
10
9
  /**
11
10
  * Add the cards that tool results selected since the last visible assistant
@@ -111,88 +110,6 @@ async function persistAuthPauseTurnState(args) {
111
110
  });
112
111
  await persistThreadStateById(args.threadStateId, { conversation });
113
112
  }
114
- // src/chat/interruption-marker.ts
115
- const INTERRUPTED_MARKER = "\n\n[Response interrupted before completion]";
116
- /** Return the marker added when a visible reply ended mid-execution. */
117
- function getInterruptionMarker() {
118
- return INTERRUPTED_MARKER;
119
- }
120
- // src/chat/services/turn-failure-response.ts
121
- /** Require captured turn failures to carry a real Sentry event reference. */
122
- function requireTurnFailureEventId(eventId, eventName) {
123
- if (!eventId) throw new Error(`Sentry did not return an event ID for ${eventName}`);
124
- return eventId;
125
- }
126
- function getExecutionFailureReason(reply) {
127
- const errorMessage = reply.diagnostics.errorMessage?.trim();
128
- if (errorMessage) return errorMessage;
129
- if (reply.diagnostics.toolErrorCount > 0) return `${reply.diagnostics.toolErrorCount} tool result error(s)`;
130
- if (reply.diagnostics.assistantMessageCount > 0) return "assistant returned no text";
131
- return "empty assistant turn";
132
- }
133
- /** Return a fixed reason label for a failed model turn. */
134
- function getTurnFailureReason(reply) {
135
- if (reply.diagnostics.outcome === "success") return;
136
- if (reply.diagnostics.outcome === "provider_error") return findProviderError(reply.diagnostics.providerError)?.kind ?? "unknown";
137
- if (reply.diagnostics.toolErrorCount > 0) return "tool_errors";
138
- if (reply.diagnostics.usedPrimaryText && reply.diagnostics.assistantMessageCount > 0) return "suppressed_output";
139
- return "empty_output";
140
- }
141
- function getFailureCapture(reply) {
142
- if (reply.diagnostics.outcome === "provider_error") {
143
- const providerError = findProviderError(reply.diagnostics.providerError);
144
- return {
145
- eventName: "agent.turn.provider_error",
146
- error: reply.diagnostics.providerError ?? new Error(reply.diagnostics.errorMessage ?? "Provider error without explicit message"),
147
- attributes: providerError ? getProviderErrorAttributes(providerError) : {},
148
- body: "Agent turn failed with provider error"
149
- };
150
- }
151
- const failureReason = getExecutionFailureReason(reply);
152
- return {
153
- eventName: "agent.turn.execution.failed",
154
- error: /* @__PURE__ */ new Error(`Agent turn execution failure: ${failureReason}`),
155
- attributes: { "app.ai.execution_failure_reason": failureReason },
156
- body: "Agent turn completed with execution failure"
157
- };
158
- }
159
- /** Keep failed-turn Sentry captures and completion spans on the same keys. */
160
- function getAgentTurnDiagnosticsAttributes(reply) {
161
- return {
162
- "app.ai.outcome": reply.diagnostics.outcome,
163
- "app.ai.assistant_messages": reply.diagnostics.assistantMessageCount,
164
- "app.ai.tool_results": reply.diagnostics.toolResultCount,
165
- "app.ai.tool_error_results": reply.diagnostics.toolErrorCount,
166
- "app.ai.tool_call_count": reply.diagnostics.toolCalls.length,
167
- "app.ai.used_primary_text": reply.diagnostics.usedPrimaryText,
168
- ...reply.diagnostics.reasoningLevel ? { "gen_ai.request.reasoning.level": reply.diagnostics.reasoningLevel } : void 0,
169
- ...reply.diagnostics.stopReason ? { "gen_ai.response.finish_reasons": [reply.diagnostics.stopReason] } : void 0,
170
- ...reply.diagnostics.errorMessage && reply.diagnostics.outcome !== "provider_error" ? { "exception.message": reply.diagnostics.errorMessage } : void 0
171
- };
172
- }
173
- /** Enforce one captured failure response and return its structured correlation. */
174
- function finalizeFailedTurnReplyWithEvent(args) {
175
- if (args.reply.diagnostics.outcome === "success") return { reply: args.reply };
176
- const failureReason = getTurnFailureReason(args.reply);
177
- const capture = getFailureCapture(args.reply);
178
- const eventId = requireTurnFailureEventId(args.logException(capture.error, capture.eventName, {
179
- ...getAgentTurnDiagnosticsAttributes(args.reply),
180
- ...args.attributes,
181
- ...capture.attributes,
182
- ...failureReason ? { "app.ai.failure_reason": failureReason } : void 0
183
- }), capture.eventName);
184
- const providerPartialText = args.reply.diagnostics.outcome === "provider_error" && args.reply.diagnostics.assistantMessageCount > 0 ? args.reply.text.trim() : "";
185
- const providerUserMessage = args.reply.diagnostics.providerError instanceof ProviderError ? getProviderErrorUserMessage(args.reply.diagnostics.providerError) : "";
186
- const failureText = providerUserMessage ? `${providerUserMessage} Reference: \`event_id=${eventId}\`.` : buildTurnFailureResponse(eventId);
187
- return {
188
- eventId,
189
- ...failureReason ? { failureReason } : void 0,
190
- reply: {
191
- ...args.reply,
192
- text: providerPartialText ? `${providerPartialText}${getInterruptionMarker()}` : failureText
193
- }
194
- };
195
- }
196
113
  // src/chat/conversations/thread-context.ts
197
114
  const CURSOR_TURN_LOOKBACK = 10;
198
115
  async function loadThreadContextCursor(args) {
@@ -245,4 +162,4 @@ async function buildTurnThreadContext(args) {
245
162
  });
246
163
  return block.text;
247
164
  }
248
- export { requireTurnFailureEventId as a, buildDeliveredTurnStatePatch as c, getAgentTurnDiagnosticsAttributes as i, loadPendingMessageCards as l, loadThreadContextTrimFloor as n, completeAuthPauseTurn as o, finalizeFailedTurnReplyWithEvent as r, persistAuthPauseTurnState as s, buildTurnThreadContext as t };
165
+ export { buildDeliveredTurnStatePatch as a, persistAuthPauseTurnState as i, loadThreadContextTrimFloor as n, loadPendingMessageCards as o, completeAuthPauseTurn as r, buildTurnThreadContext as t };