@sentry/junior 0.310.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 (157) hide show
  1. package/dist/{adapter-context-BhKpjpGD.js → adapter-context-BRjEWRy1.js} +2 -2
  2. package/dist/adapter-iIq7ihf7.js +259 -0
  3. package/dist/{admin-tgZEZAk2.js → admin-DhInw5K9.js} +1 -2
  4. package/dist/{agent-runner-D9cvNlQl.js → agent-runner-C9iDurwX.js} +6507 -7721
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +7 -6
  7. package/dist/api.d.ts +21 -3
  8. package/dist/api.js +1625 -535
  9. package/dist/{app-B_7Wn0en.d.ts → app-DRFrC8Mw.d.ts} +14 -10
  10. package/dist/app.d.ts +2 -2
  11. package/dist/app.js +454 -994
  12. package/dist/{background-compaction-queue-BGHqkhkY.js → background-compaction-queue-DrKi7w3d.js} +10 -85
  13. package/dist/callback-mFlTUWWx.js +75 -0
  14. package/dist/{catalog-runtime-BxwzbLKY.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 +23 -29
  19. package/dist/cli/init.js +1 -7
  20. package/dist/cli/main.js +3 -7
  21. package/dist/cli/plugins.js +8 -7
  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-Dkt2Le2b.js → config-kXB2Y5tl.js} +294 -28
  28. package/dist/{continue-in-slack-BWVwePKD.js → continue-in-slack-O6pV5004.js} +7 -7
  29. package/dist/{conversation-feed-Ci6YD1N-.js → conversation-feed-uNOv_x68.js} +87 -24
  30. package/dist/{conversation-privacy-C39g8BY4.js → conversation-privacy-L4ja1_W6.js} +1 -1
  31. package/dist/{conversation-turn-CBlZIH02.js → conversation-turn-CeLbHqdw.js} +56 -49
  32. package/dist/{credential-sync-vGnrB0BY.js → credential-sync-I8VBGk05.js} +16 -16
  33. package/dist/{projection-jZSlEAXG.js → credentialed-Cb6E2phL.js} +16268 -16821
  34. package/dist/{db-B4Hjxr-u.d.ts → db-BbC5stfa.d.ts} +13 -6
  35. package/dist/{db-CFZggNoy.js → db-LAyyX8tk.js} +1698 -1046
  36. package/dist/{executor-BPkZDx5-.js → executor-SCub-fAq.js} +552 -181
  37. package/dist/{html-2r2KmLwi.js → html-BCZ3Xtb_.js} +6 -6
  38. package/dist/{session-stop-BfY4rhJs.js → ingest-BDf3D50j.js} +2134 -2553
  39. package/dist/{install-C-oE6C_u.js → install-DCFJFkC0.js} +2 -2
  40. package/dist/instrumentation.js +4 -4
  41. package/dist/{lineage-CsvrEFQe.js → lineage-B_m-4TJw.js} +2 -2
  42. package/dist/{stop-DYzjRf2U.js → list-CN2QA2R9.js} +1656 -685
  43. package/dist/{logging-D5gkyvnK.js → logging-dQ9ZRGQ8.js} +47 -9
  44. package/dist/media-CYm1QD8T.js +2356 -0
  45. package/dist/{message-DwvJ-I3w.js → message-DSXGj1hM.js} +19 -29
  46. package/dist/{model-input-MAq2881y.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-DIF6Li06.js → oauth-callback-server-DHCZC6B4.js} +2 -2
  50. package/dist/{oauth-relay-DPE-wrwO.js → oauth-relay-pPMGnDZt.js} +1 -1
  51. package/dist/{registry-BBkWFCl8.js → registry-CZOzddwu.js} +5 -8
  52. package/dist/{resolve-B38MkHXE.js → resolve-cKOQ14Dh.js} +3 -3
  53. package/dist/{result-BaqSZcJb.js → result-DcvEOe1r.js} +119 -93
  54. package/dist/result-event-type-BdIJuZxg.js +48 -0
  55. package/dist/rule-DAxQY-1h.js +20 -0
  56. package/dist/{runner-11h8PrHh.js → runner-DBfUW44l.js} +14 -16
  57. package/dist/{sandbox-egress-signals-CTcACAtJ.js → sandbox-egress-signals-BVF_xAm1.js} +1 -1
  58. package/dist/{schema-DriSvB40.d.ts → schema-BEHKxr4I.d.ts} +861 -298
  59. package/dist/{schema-obw5jvR4.js → schema-Bk9Nm2E8.js} +344 -153
  60. package/dist/{service-account-Bx93N1n1.js → service-account-CVYsFjty.js} +3 -3
  61. package/dist/{service-account-Zc5bUcIJ.js → service-account-Ts4ulcrV.js} +68 -68
  62. package/dist/{skills-C8Npu5zO.js → skills-VTnhAJWm.js} +2 -2
  63. package/dist/{slack-conversation-unfurl-DlRVA02H.js → slack-conversation-unfurl-fuLnF1jE.js} +9 -11
  64. package/dist/{spawn-CXr58R0x.js → spawn-vxAarlX5.js} +6 -6
  65. package/dist/start-conversation-CEn2KH1A.js +941 -0
  66. package/dist/{state-CGrGVeQC.js → state-C1P3_Ywk.js} +4 -4
  67. package/dist/statuses-_cRJHXK7.js +150 -0
  68. package/dist/store-DFZaN-Ix.js +492 -0
  69. package/dist/task-queue-Cx4Lmjyk.js +90 -0
  70. package/dist/task-runner-CbTwFA6k.js +1432 -0
  71. package/dist/{thread-context-Dyj1KWaY.js → thread-context-BkAZDTX2.js} +13 -11
  72. package/dist/thread-state-DhPndWi1.js +5625 -0
  73. package/dist/{validation-DxVNIxA0.js → validation-nIzMtAVJ.js} +1 -1
  74. package/dist/{task-queue-CaZffYaH.js → vercel-queue-hW90XzbG.js} +93 -172
  75. package/dist/{version-Cr7Z71yG.js → version-Brbtz4Qf.js} +1 -1
  76. package/dist/version.js +1 -1
  77. package/dist/{warmup-C6LOZ2d2.js → warmup-BDA5myRK.js} +5832 -4567
  78. package/dist/web-message-id-C6P83ans.js +10 -0
  79. package/dist/{worker-CUBtu1Li.js → worker-D63RcaVD.js} +20 -8
  80. package/migrations/0126_artifact_drop_public.sql +8 -0
  81. package/migrations/0127_artifact_path.sql +4 -0
  82. package/migrations/0128_artifact_path_index.sql +1 -0
  83. package/migrations/0129_review_item_answered_index.sql +1 -0
  84. package/migrations/0130_review_item_status_index.sql +1 -0
  85. package/migrations/0131_brief_outcome_status.sql +1 -0
  86. package/migrations/0132_brief_outcome_status_backfill.sql +7 -0
  87. package/migrations/0133_brief_created_at_index.sql +1 -0
  88. package/migrations/0134_slack_person_search_index.sql +1 -0
  89. package/migrations/0135_code_change_size.sql +3 -0
  90. package/migrations/0136_merge_conflict_notice_dismiss.sql +16 -0
  91. package/migrations/0137_inbox_snoozes.sql +27 -0
  92. package/migrations/0138_code_change_search_index.sql +2 -0
  93. package/migrations/0139_review_item_owner.sql +22 -0
  94. package/migrations/0140_review_item_owner_index.sql +1 -0
  95. package/migrations/0141_memory_core_adoption.sql +89 -0
  96. package/migrations/0142_memory_core_indexes.sql +17 -0
  97. package/migrations/0143_todos.sql +14 -0
  98. package/migrations/0144_inbox_items.sql +32 -0
  99. package/migrations/0145_todo_changed_by_agent.sql +1 -0
  100. package/migrations/0146_inbox_item_subject_title_parts.sql +1 -0
  101. package/migrations/0147_inbox_snooze_wake_reason.sql +1 -0
  102. package/migrations/0148_authorization_request_index.sql +1 -0
  103. package/migrations/0149_conversation_metadata.sql +10 -0
  104. package/migrations/0150_conversation_metadata_fill.sql +39 -0
  105. package/migrations/0151_conversation_search_index.sql +1 -0
  106. package/migrations/0152_inbox_item_legacy_automation_keys.sql +21 -0
  107. package/migrations/0153_artifact_expiry.sql +1 -0
  108. package/migrations/0154_artifact_permanent_sha_index.sql +1 -0
  109. package/migrations/0155_artifact_drop_public_sha_index.sql +3 -0
  110. package/migrations/0156_conversation_kind_lead.sql +6 -0
  111. package/migrations/0157_conversation_lead_actor_index.sql +1 -0
  112. package/migrations/meta/0126_snapshot.json +5488 -0
  113. package/migrations/meta/0127_snapshot.json +5519 -0
  114. package/migrations/meta/0128_snapshot.json +5519 -0
  115. package/migrations/meta/0129_snapshot.json +5547 -0
  116. package/migrations/meta/0130_snapshot.json +5563 -0
  117. package/migrations/meta/0131_snapshot.json +5569 -0
  118. package/migrations/meta/0132_snapshot.json +5569 -0
  119. package/migrations/meta/0133_snapshot.json +5590 -0
  120. package/migrations/meta/0134_snapshot.json +5606 -0
  121. package/migrations/meta/0135_snapshot.json +5624 -0
  122. package/migrations/meta/0136_snapshot.json +5624 -0
  123. package/migrations/meta/0137_snapshot.json +5864 -0
  124. package/migrations/meta/0138_snapshot.json +5894 -0
  125. package/migrations/meta/0139_snapshot.json +5898 -0
  126. package/migrations/meta/0140_snapshot.json +5919 -0
  127. package/migrations/meta/0141_snapshot.json +6429 -0
  128. package/migrations/meta/0142_snapshot.json +6457 -0
  129. package/migrations/meta/0143_snapshot.json +6434 -0
  130. package/migrations/meta/0144_snapshot.json +6434 -0
  131. package/migrations/meta/0145_snapshot.json +6440 -0
  132. package/migrations/meta/0146_snapshot.json +6446 -0
  133. package/migrations/meta/0147_snapshot.json +6452 -0
  134. package/migrations/meta/0148_snapshot.json +6474 -0
  135. package/migrations/meta/0149_snapshot.json +6490 -0
  136. package/migrations/meta/0150_snapshot.json +6490 -0
  137. package/migrations/meta/0151_snapshot.json +6505 -0
  138. package/migrations/meta/0152_snapshot.json +6505 -0
  139. package/migrations/meta/0153_snapshot.json +6511 -0
  140. package/migrations/meta/0154_snapshot.json +6533 -0
  141. package/migrations/meta/0155_snapshot.json +6511 -0
  142. package/migrations/meta/0156_snapshot.json +6511 -0
  143. package/migrations/meta/0157_snapshot.json +6527 -0
  144. package/migrations/meta/_journal.json +224 -0
  145. package/package.json +7 -8
  146. package/skills/design-automation-skill/SKILL.md +108 -0
  147. package/dist/briefs-DKxkoruh.js +0 -395
  148. package/dist/conversation-M9KZ5JxF.js +0 -1024
  149. package/dist/prompt-CaMyeCpA.js +0 -910
  150. package/dist/schedule-DWxZ3kja.js +0 -1146
  151. package/dist/store-D4FQ1Nml.js +0 -335
  152. package/dist/task-runner-Dm7BHbGp.js +0 -287
  153. package/dist/turn-session-routing-CD0BRCex.js +0 -263
  154. package/dist/turn-user-message-9IxeEv5v.js +0 -364
  155. package/dist/users-CaUAYMb3.js +0 -181
  156. package/dist/viewer-AHldghAD.js +0 -212
  157. package/dist/web-message-id-BT8Mg8LL.js +0 -418
@@ -1,85 +1,9 @@
1
- import { i as getChatConfig } from "./config-Dkt2Le2b.js";
2
- import { E as withSpan, h as logWarn } from "./logging-D5gkyvnK.js";
3
- import { _ as getQueueProvider, c as QUEUE_SIGNATURE_MAX_AGE_MS, h as queueCallback, l as signQueueMessage, u as verifyQueueMessage } from "./task-queue-CaZffYaH.js";
1
+ import { r as getChatConfig } from "./config-kXB2Y5tl.js";
2
+ import { h as logWarn } from "./logging-dQ9ZRGQ8.js";
3
+ import { c as QUEUE_SIGNATURE_MAX_AGE_MS, d as getQueueProvider, l as signQueueMessage, u as verifyQueueMessage } from "./vercel-queue-hW90XzbG.js";
4
+ import { t as queueCallback } from "./callback-mFlTUWWx.js";
4
5
  import * as z from "zod";
5
6
  import { createHash } from "node:crypto";
6
- /** Validate the v2 conversation work hint sent through Vercel Queue. */
7
- const conversationQueueMessageSchema = z.object({
8
- schemaVersion: z.literal(2),
9
- conversationId: z.string().trim().min(1)
10
- }).strict();
11
- var ConversationQueueMessageRejectedError = class extends Error {
12
- conversationId;
13
- reason;
14
- constructor(reason, message, options = {}) {
15
- super(message);
16
- this.name = "ConversationQueueMessageRejectedError";
17
- this.reason = reason;
18
- this.conversationId = options.conversationId;
19
- }
20
- };
21
- /** Return whether an error means the queue message was permanently rejected. */
22
- function isConversationQueueMessageRejectedError(error) {
23
- return error instanceof ConversationQueueMessageRejectedError;
24
- }
25
- /** Build the idempotency key of a wake that one worker event sends. */
26
- function nudgeIdempotencyKey(reason, conversationId, nowMs) {
27
- return `${reason}:${conversationId}:${nowMs}`;
28
- }
29
- // src/chat/task-execution/queue-signing.ts
30
- const conversationQueueSign = {
31
- context: "junior.conversation_work_queue.v2",
32
- schema: conversationQueueMessageSchema,
33
- separator: ":",
34
- signatureVersion: "v2",
35
- parts: (message) => [message.conversationId]
36
- };
37
- const CONVERSATION_WORK_QUEUE_SIGNATURE_MAX_SKEW_MS = QUEUE_SIGNATURE_MAX_AGE_MS;
38
- /** Sign a conversation queue payload before it crosses the public callback route. */
39
- function signConversationQueueMessage(message, nowMs = Date.now()) {
40
- return signQueueMessage(conversationQueueSign, message, nowMs);
41
- }
42
- /** Explain whether a queue payload is verified, rejected, or unavailable. */
43
- function verifyConversationQueueMessage(value, nowMs = Date.now()) {
44
- return verifyQueueMessage(conversationQueueSign, value, nowMs);
45
- }
46
- const CONVERSATION_WORK_QUEUE_RETENTION_SECONDS = CONVERSATION_WORK_QUEUE_SIGNATURE_MAX_SKEW_MS / 1e3;
47
- let defaultQueue;
48
- /** Resolve the Vercel Queue topic used for conversation wake-up nudges. */
49
- function resolveConversationWorkQueueTopic(options = {}) {
50
- return options.topic?.trim() || process.env["JUNIOR_CONVERSATION_WORK_QUEUE_TOPIC"]?.trim() || "junior_conversation_work";
51
- }
52
- function toDelaySeconds(options) {
53
- if (!options?.delayMs || options.delayMs <= 0) return;
54
- return Math.ceil(options.delayMs / 1e3);
55
- }
56
- /** Create the Vercel Queue implementation for conversation wake-up nudges. */
57
- function createVercelConversationWorkQueue(options = {}) {
58
- const topic = resolveConversationWorkQueueTopic(options);
59
- const client = options.client ?? getQueueProvider();
60
- return { async send(message, sendOptions) {
61
- const payload = signConversationQueueMessage(message);
62
- return await withSpan("conversation.work.publish", "queue.publish", { conversationId: message.conversationId }, async (setSpanAttributes) => {
63
- const result = await client.send(topic, payload, {
64
- idempotencyKey: sendOptions?.idempotencyKey,
65
- delaySeconds: toDelaySeconds(sendOptions),
66
- retentionSeconds: options.retentionSeconds ?? CONVERSATION_WORK_QUEUE_RETENTION_SECONDS
67
- });
68
- if (!result.messageId) return {};
69
- setSpanAttributes({ "messaging.message.id": result.messageId });
70
- return { messageId: result.messageId };
71
- }, {
72
- "messaging.destination.name": topic,
73
- "messaging.message.body.size": Buffer.byteLength(JSON.stringify(payload)),
74
- "messaging.system": getQueueProvider().messagingSystem
75
- });
76
- } };
77
- }
78
- /** Return the default production conversation work queue. */
79
- function getVercelConversationWorkQueue() {
80
- defaultQueue ??= createVercelConversationWorkQueue();
81
- return defaultQueue;
82
- }
83
7
  // src/chat/sandbox/snapshot/job-queue.ts
84
8
  /** Send Workspace snapshot build messages. */
85
9
  const SIGNATURE_CONTEXT = "junior.workspace_snapshot_queue.v1";
@@ -134,14 +58,15 @@ const cacheWarmupSign = {
134
58
  }).strict(), z.object({
135
59
  kind: z.literal("horizon"),
136
60
  conversationId: z.string().min(1),
137
- generation: z.string().min(1)
61
+ generation: z.string().min(1),
62
+ step: z.number().int().min(2).optional()
138
63
  }).strict()]),
139
64
  signatureVersion: "v1",
140
65
  parts: (message) => [
141
66
  message.kind,
142
67
  message.conversationId,
143
68
  message.generation,
144
- message.kind === "warmup" ? String(message.cycle) : "",
69
+ message.kind === "warmup" ? String(message.cycle) : message.step ? String(message.step) : "",
145
70
  message.kind === "warmup" ? String(message.cacheExpiresAtMs) : ""
146
71
  ]
147
72
  };
@@ -150,7 +75,7 @@ async function sendCacheWarmup(message, delayMs) {
150
75
  await getQueueProvider().send(CACHE_WARMUP_QUEUE_TOPIC, signQueueMessage(cacheWarmupSign, message), {
151
76
  delaySeconds: Math.max(0, Math.floor(delayMs / 1e3)),
152
77
  retentionSeconds: message.kind === "warmup" ? Math.min(QUEUE_SIGNATURE_MAX_AGE_MS / 1e3, Math.ceil(Math.max(0, delayMs) / 1e3) + 120) : QUEUE_SIGNATURE_MAX_AGE_MS / 1e3,
153
- idempotencyKey: `cache-warmup_${message.generation}_${message.kind === "warmup" ? message.cycle : message.kind}`
78
+ idempotencyKey: `cache-warmup_${message.generation}_${message.kind === "warmup" ? message.cycle : `${message.kind}${message.step ? `_${message.step}` : ""}`}`
154
79
  });
155
80
  }
156
81
  function logCacheWarmupRejected(reason, metadata, error) {
@@ -169,7 +94,7 @@ function cacheWarmupCallback() {
169
94
  maxDeliveries: 1,
170
95
  onRejected: logCacheWarmupRejected,
171
96
  run: async (message) => {
172
- const { runCacheWarmup } = await import("./warmup-C6LOZ2d2.js").then((n) => n.s);
97
+ const { runCacheWarmup } = await import("./warmup-BDA5myRK.js").then((n) => n.c);
173
98
  await runCacheWarmup(message);
174
99
  },
175
100
  skip: () => !getChatConfig().cacheWarmingEnabled,
@@ -228,4 +153,4 @@ const vercelBackgroundCompactionQueue = { send: async (message) => {
228
153
  retentionSeconds: QUEUE_SIGNATURE_MAX_AGE_MS / 1e3
229
154
  });
230
155
  } };
231
- export { ConversationQueueMessageRejectedError as _, CACHE_WARMUP_QUEUE_TOPIC as a, nudgeIdempotencyKey as b, registerVercelCacheWarmupDevConsumer as c, sendNextWorkspaceSnapshotJob as d, sendWorkspaceSnapshotJob as f, verifyConversationQueueMessage as g, resolveConversationWorkQueueTopic as h, verifyBackgroundCompactionMessage as i, sendCacheWarmup as l, getVercelConversationWorkQueue as m, backgroundCompactionId as n, cacheWarmupQueueConsumer as o, verifyWorkspaceSnapshotJobMessage as p, vercelBackgroundCompactionQueue as r, createVercelCacheWarmupCallback as s, BACKGROUND_COMPACTION_QUEUE_TOPIC as t, WORKSPACE_SNAPSHOT_JOB_QUEUE_TOPIC as u, conversationQueueMessageSchema as v, isConversationQueueMessageRejectedError as y };
156
+ export { CACHE_WARMUP_QUEUE_TOPIC as a, registerVercelCacheWarmupDevConsumer as c, sendNextWorkspaceSnapshotJob as d, sendWorkspaceSnapshotJob as f, verifyBackgroundCompactionMessage as i, sendCacheWarmup as l, backgroundCompactionId as n, cacheWarmupQueueConsumer as o, verifyWorkspaceSnapshotJobMessage as p, vercelBackgroundCompactionQueue as r, createVercelCacheWarmupCallback as s, BACKGROUND_COMPACTION_QUEUE_TOPIC as t, WORKSPACE_SNAPSHOT_JOB_QUEUE_TOPIC as u };
@@ -0,0 +1,75 @@
1
+ import { d as getQueueProvider } from "./vercel-queue-hW90XzbG.js";
2
+ import { r as getChatConfig } from "./config-kXB2Y5tl.js";
3
+ import { AsyncLocalStorage } from "node:async_hooks";
4
+ // src/chat/runtime/request-deadline.ts
5
+ const requestDeadlineStorage = new AsyncLocalStorage();
6
+ function createTurnRequestDeadline(startedAtMs) {
7
+ return {
8
+ startedAtMs,
9
+ deadlineAtMs: startedAtMs + Math.max(1, getChatConfig().functionMaxDurationSeconds * 1e3 - 2e4)
10
+ };
11
+ }
12
+ /** Return the host request deadline inherited by the current async turn. */
13
+ function getTurnRequestDeadline() {
14
+ return requestDeadlineStorage.getStore();
15
+ }
16
+ /** Run work under the current host request deadline, or start one. */
17
+ function runWithTurnRequestDeadline(callback, startedAtMs = Date.now()) {
18
+ if (requestDeadlineStorage.getStore()) return callback();
19
+ return runWithNewTurnRequestDeadline(callback, startedAtMs);
20
+ }
21
+ /** Run work that a new host request owns, even inside another request. */
22
+ function runWithNewTurnRequestDeadline(callback, startedAtMs = Date.now()) {
23
+ return requestDeadlineStorage.run(createTurnRequestDeadline(startedAtMs), callback);
24
+ }
25
+ // src/chat/queue/callback.ts
26
+ /** Shared queue callback wiring for signed messages. */
27
+ /** Build the HTTP callback and local-dev consumer for one signed queue. */
28
+ function queueCallback(options) {
29
+ const consume = async (message, metadata) => {
30
+ if (options.skip?.(metadata)) return;
31
+ try {
32
+ await runWithTurnRequestDeadline(() => options.run(message, metadata));
33
+ } catch (error) {
34
+ const reason = options.permanentError?.(error);
35
+ if (!reason) throw error;
36
+ options.onRejected(reason, metadata, error);
37
+ }
38
+ };
39
+ const handler = async (value, metadata) => {
40
+ if (options.skip?.(metadata)) return;
41
+ const checked = options.verify(value);
42
+ if (checked.status === "rejected") {
43
+ options.onRejected(checked.reason, metadata);
44
+ return;
45
+ }
46
+ if (checked.status === "unavailable") throw new Error(`Queue message verification unavailable: ${checked.reason}`);
47
+ await runWithNewTurnRequestDeadline(() => consume(checked.message, metadata));
48
+ };
49
+ const retry = (error, metadata) => {
50
+ const reason = options.permanentError?.(error);
51
+ if (reason) {
52
+ options.onRejected(reason, metadata, error);
53
+ return { acknowledge: true };
54
+ }
55
+ if (options.maxDeliveries !== null && metadata.deliveryCount >= options.maxDeliveries) return { acknowledge: true };
56
+ };
57
+ const consumer = {
58
+ consumerGroup: options.consumerGroup,
59
+ handler,
60
+ retry,
61
+ topic: options.topic,
62
+ visibilityTimeoutSeconds: options.visibilityTimeoutSeconds
63
+ };
64
+ return {
65
+ /** Run a message that an in-process queue already trusts. */
66
+ consume,
67
+ consumer,
68
+ create: () => getQueueProvider().createCallback(consumer),
69
+ registerDev: () => {
70
+ if (process.env["NODE_ENV"] !== "development") return;
71
+ return getQueueProvider().registerDevConsumer?.(consumer);
72
+ }
73
+ };
74
+ }
75
+ export { getTurnRequestDeadline as n, queueCallback as t };
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { t as createPluginCatalogRuntime } from "./registry-BBkWFCl8.js";
2
+ import { t as createPluginCatalogRuntime } from "./registry-CZOzddwu.js";
3
3
  // src/chat/plugins/catalog-runtime.ts
4
4
  var catalog_runtime_exports = /* @__PURE__ */ __exportAll({ pluginCatalogRuntime: () => pluginCatalogRuntime });
5
5
  const pluginCatalogRuntime = createPluginCatalogRuntime();
@@ -0,0 +1,221 @@
1
+ import { a as getConversationStore } from "./db-LAyyX8tk.js";
2
+ import { Ao as getSlackClient, Eo as SlackActionError, Ro as withSlackRetries } from "./credentialed-Cb6E2phL.js";
3
+ import * as z from "zod";
4
+ // src/chat/slack/channel.ts
5
+ const replySubtypeSchema = z.object({ subtype: z.string().optional() });
6
+ /** List channel history using Slack-native, pre-validated timestamp bounds. */
7
+ async function listChannelMessages(input) {
8
+ const client = getSlackClient();
9
+ const channelId = input.channelId;
10
+ const targetLimit = Math.max(1, Math.min(input.limit, 1e3));
11
+ const maxPages = Math.max(1, Math.min(input.maxPages ?? 5, 10));
12
+ const messages = [];
13
+ let cursor = input.cursor;
14
+ let pages = 0;
15
+ while (messages.length < targetLimit && pages < maxPages) {
16
+ pages += 1;
17
+ const pageLimit = Math.max(1, Math.min(200, targetLimit - messages.length));
18
+ const response = await withSlackRetries(() => client.conversations.history({
19
+ channel: channelId,
20
+ limit: pageLimit,
21
+ cursor,
22
+ oldest: input.oldest,
23
+ latest: input.latest,
24
+ inclusive: input.inclusive
25
+ }), 3, { action: "conversations.history" });
26
+ const batch = response.messages ?? [];
27
+ messages.push(...batch);
28
+ cursor = response.response_metadata?.next_cursor || void 0;
29
+ if (!cursor) break;
30
+ }
31
+ return {
32
+ messages: messages.slice(0, targetLimit),
33
+ nextCursor: cursor
34
+ };
35
+ }
36
+ /** Read replies from a Slack thread identified by a validated native thread timestamp. */
37
+ async function listThreadReplies(input) {
38
+ const client = getSlackClient();
39
+ const channelId = input.channelId;
40
+ const targetLimit = Math.max(1, Math.min(input.limit ?? 1e3, 1e3));
41
+ const maxPages = Math.max(1, Math.min(input.maxPages ?? 10, 10));
42
+ const pendingTargets = new Set((input.targetMessageTs ?? []).filter((value) => typeof value === "string" && value.length > 0));
43
+ const hasTargetMessages = pendingTargets.size > 0;
44
+ const replies = [];
45
+ let cursor;
46
+ let pages = 0;
47
+ while (replies.length < targetLimit && pages < maxPages) {
48
+ pages += 1;
49
+ const pageLimit = Math.max(1, Math.min(200, targetLimit - replies.length));
50
+ const response = await withSlackRetries(() => client.conversations.replies({
51
+ channel: channelId,
52
+ ts: input.threadTs,
53
+ limit: pageLimit,
54
+ cursor
55
+ }), 3, { action: "conversations.replies" });
56
+ const batch = response.messages ?? [];
57
+ replies.push(...batch.map((reply) => ({
58
+ ...reply,
59
+ ...replySubtypeSchema.parse(reply)
60
+ })));
61
+ for (const reply of batch) if (typeof reply.ts === "string" && pendingTargets.size > 0) pendingTargets.delete(reply.ts);
62
+ cursor = response.response_metadata?.next_cursor || void 0;
63
+ if (!cursor || hasTargetMessages && pendingTargets.size === 0) break;
64
+ }
65
+ return replies.slice(0, targetLimit);
66
+ }
67
+ /** Return whether anyone in the workspace can read the conversation. */
68
+ function isPublicSlackChannel(info) {
69
+ return info.isChannel && !info.isPrivate && !info.isIm && !info.isMpim;
70
+ }
71
+ /** Load conversation metadata used for cross-channel read access checks. */
72
+ async function getConversationInfo(channelId) {
73
+ const client = getSlackClient();
74
+ const channel = (await withSlackRetries(() => client.conversations.info({ channel: channelId }), 3, {
75
+ action: "conversations.info",
76
+ idempotent: true
77
+ })).channel;
78
+ if (!channel || typeof channel !== "object") throw new Error(`Slack conversations.info returned no channel for ${channelId}`);
79
+ return {
80
+ id: channelId,
81
+ ...typeof channel.name === "string" && channel.name ? { name: channel.name } : void 0,
82
+ ...channel.topic?.value ? { topic: channel.topic.value } : void 0,
83
+ ...channel.purpose?.value ? { description: channel.purpose.value } : void 0,
84
+ isChannel: channel.is_channel === true,
85
+ isPrivate: channel.is_private === true,
86
+ isIm: channel.is_im === true,
87
+ isMpim: channel.is_mpim === true,
88
+ ...typeof channel.is_member === "boolean" ? { isMember: channel.is_member } : void 0
89
+ };
90
+ }
91
+ /** Join a public channel so the bot can read history and threads there. */
92
+ async function joinPublicChannel(channelId) {
93
+ const client = getSlackClient();
94
+ await withSlackRetries(() => client.conversations.join({ channel: channelId }), 3, {
95
+ action: "conversations.join",
96
+ idempotent: true
97
+ });
98
+ }
99
+ const MAX_MEMBER_PAGES = 5;
100
+ /** Return whether a Slack user is a member of a channel, DM, or group DM. */
101
+ async function isConversationMember(channelId, userId) {
102
+ const client = getSlackClient();
103
+ let cursor;
104
+ for (let page = 0; page < MAX_MEMBER_PAGES; page += 1) {
105
+ const response = await withSlackRetries(() => client.conversations.members({
106
+ channel: channelId,
107
+ cursor,
108
+ limit: 1e3
109
+ }), 3, {
110
+ action: "conversations.members",
111
+ idempotent: true
112
+ });
113
+ if (response.members?.includes(userId)) return true;
114
+ cursor = response.response_metadata?.next_cursor || void 0;
115
+ if (!cursor) return false;
116
+ }
117
+ return false;
118
+ }
119
+ /** Read one message by its timestamp. A thread reply needs its thread. */
120
+ async function getChannelMessage(input) {
121
+ const client = getSlackClient();
122
+ return (await withSlackRetries(() => client.conversations.replies({
123
+ channel: input.channelId,
124
+ ts: input.threadTs ?? input.messageTs,
125
+ oldest: input.messageTs,
126
+ latest: input.messageTs,
127
+ inclusive: true,
128
+ limit: 2
129
+ }), 3, {
130
+ action: "conversations.replies",
131
+ idempotent: true
132
+ })).messages?.find((message) => message.ts === input.messageTs);
133
+ }
134
+ // src/chat/slack/tool-support/channel-access.ts
135
+ const DENIED_PRIVATE = "Cannot read this Slack conversation because it is private. Only the current conversation or public channels are readable.";
136
+ const DENIED_NOT_FOUND = "Cannot read this Slack conversation because the channel was not found or the bot cannot see it.";
137
+ const DENIED_NOT_IN_CHANNEL = "Cannot read this Slack conversation because the bot is not in the channel.";
138
+ const DENIED_MISSING_SCOPE = "Cannot verify Slack channel access because this installation is missing channel read scopes.";
139
+ function deny(reason, error) {
140
+ return {
141
+ allowed: false,
142
+ reason,
143
+ error
144
+ };
145
+ }
146
+ /**
147
+ * Decide whether the model may read Slack content from a target channel.
148
+ *
149
+ * The current conversation is always readable. Any other channel first checks
150
+ * persisted visibility in the same workspace. Cross-channel reads require live
151
+ * `conversations.info` proof that the destination is public. Stale persisted
152
+ * public rows are not enough, so a channel that later becomes private fails
153
+ * closed. Channel-id prefixes alone cannot prove a channel public.
154
+ */
155
+ async function checkSlackChannelReadAccess(args) {
156
+ if (args.currentChannelIds.filter((channelId) => Boolean(channelId)).includes(args.targetChannelId)) return {
157
+ allowed: true,
158
+ isMember: true
159
+ };
160
+ if (await getConversationStore().getDestinationVisibility({
161
+ provider: "slack",
162
+ providerTenantId: args.teamId,
163
+ providerDestinationId: args.targetChannelId
164
+ }) === "private") return deny("private", DENIED_PRIVATE);
165
+ try {
166
+ const info = await getConversationInfo(args.targetChannelId);
167
+ if (!isPublicSlackChannel(info)) return deny("private", DENIED_PRIVATE);
168
+ return {
169
+ allowed: true,
170
+ isPublic: true,
171
+ ...info.name ? { channelName: info.name } : void 0,
172
+ ...typeof info.isMember === "boolean" ? { isMember: info.isMember } : void 0
173
+ };
174
+ } catch (error) {
175
+ if (error instanceof SlackActionError) {
176
+ if (error.code === "not_found") return deny("not_found", DENIED_NOT_FOUND);
177
+ if (error.code === "not_in_channel") return deny("not_in_channel", DENIED_NOT_IN_CHANNEL);
178
+ if (error.code === "missing_scope") return deny("missing_scope", DENIED_MISSING_SCOPE);
179
+ }
180
+ throw error;
181
+ }
182
+ }
183
+ /**
184
+ * Join one public channel when a read failed because the bot is not a member.
185
+ *
186
+ * Callers should try the read first, then use this helper on `not_in_channel`.
187
+ */
188
+ async function joinPublicChannelForRead(args) {
189
+ try {
190
+ await joinPublicChannel(args.targetChannelId);
191
+ return {
192
+ ok: true,
193
+ ...args.channelName ? { channelName: args.channelName } : void 0
194
+ };
195
+ } catch (error) {
196
+ if (error instanceof SlackActionError) {
197
+ if (error.code === "missing_scope") return {
198
+ ok: false,
199
+ reason: "missing_scope",
200
+ error: "Cannot join this public Slack channel because this installation is missing the `channels:join` scope."
201
+ };
202
+ if (error.code === "not_found") return {
203
+ ok: false,
204
+ reason: "not_found",
205
+ error: DENIED_NOT_FOUND
206
+ };
207
+ if (error.apiError === "method_not_supported_for_channel_type" || error.apiError === "is_archived" || error.apiError === "cant_invite_self") return {
208
+ ok: false,
209
+ reason: "private",
210
+ error: DENIED_PRIVATE
211
+ };
212
+ return {
213
+ ok: false,
214
+ reason: "not_in_channel",
215
+ error: "Could not join this public Slack channel. Ask an admin to add the bot, then retry."
216
+ };
217
+ }
218
+ throw error;
219
+ }
220
+ }
221
+ export { isConversationMember as a, listChannelMessages as c, getConversationInfo as i, listThreadReplies as l, joinPublicChannelForRead as n, isPublicSlackChannel as o, getChannelMessage as r, joinPublicChannel as s, checkSlackChannelReadAccess as t };
@@ -0,0 +1,179 @@
1
+ import { s as getSqlExecutor } from "./db-LAyyX8tk.js";
2
+ import { un as readInboundMessageSender } from "./thread-state-DhPndWi1.js";
3
+ import { x as juniorAgentInvocations } from "./executor-SCub-fAq.js";
4
+ import { createHash } from "node:crypto";
5
+ import { inArray } from "drizzle-orm";
6
+ // src/chat/agent-invocations/ids.ts
7
+ const CREATE_LOCK_PREFIX = "junior:agent_invocation:create";
8
+ /**
9
+ * Return the SQL lock that one parent Conversation takes to start, message,
10
+ * or stop its child agents.
11
+ */
12
+ function getChildAgentLockName(parentConversationId) {
13
+ return `${CREATE_LOCK_PREFIX}:${parentConversationId}`;
14
+ }
15
+ function stableId(prefix, ...parts) {
16
+ return `${prefix}:${createHash("sha256").update(parts.join("\0")).digest("hex").slice(0, 32)}`;
17
+ }
18
+ /** Return the stable identity for one retry-safe delegated task. */
19
+ function getAgentInvocationId(parentConversationId, idempotencyKey) {
20
+ return stableId("agent-invocation", parentConversationId, idempotencyKey);
21
+ }
22
+ /** Return the stable child identity for one invocation without a named binding. */
23
+ function getUnnamedAgentConversationId(invocationId) {
24
+ return stableId("agent", invocationId);
25
+ }
26
+ /** Return the stable child identity for one named binding. */
27
+ function getNamedAgentConversationId(parentConversationId, name) {
28
+ return stableId("agent", parentConversationId, name);
29
+ }
30
+ /**
31
+ * Return the stable identity of the agent invocation that gives one child
32
+ * agent result to the child Conversation that started that child agent.
33
+ */
34
+ function getAgentInvocationIdForResult(resultInvocationId) {
35
+ return stableId("agent-invocation", "result", resultInvocationId);
36
+ }
37
+ /**
38
+ * Return the stable identity of the agent invocation that gives one message
39
+ * from a child agent to the child Conversation that started that child agent.
40
+ */
41
+ function getAgentInvocationIdForMessage(messageId) {
42
+ return stableId("agent-invocation", "message", messageId);
43
+ }
44
+ /**
45
+ * Return the stable identity of the agent invocation that gives one batch of
46
+ * watch events to a child Conversation. The first message of the batch names
47
+ * it.
48
+ */
49
+ function getAgentInvocationIdForEvents(messageId) {
50
+ return stableId("agent-invocation", "events", messageId);
51
+ }
52
+ /** Return the stable turn identity advanced by one agent invocation. */
53
+ function getAgentInvocationTurnId(invocationId) {
54
+ return `agent-invocation:${invocationId}`;
55
+ }
56
+ /** Return the stable mailbox identity for one agent invocation. */
57
+ function getAgentInvocationMessageId(invocationId) {
58
+ return `agent-invocation:${invocationId}:input`;
59
+ }
60
+ const REPLY_MESSAGE_PREFIX = "agent-reply:";
61
+ /**
62
+ * Return the parent mailbox identity of one child agent `reply` call.
63
+ * `senderId` is the Agent invocation that sent it, or the child Conversation
64
+ * when no Agent invocation names the child.
65
+ */
66
+ function getAgentReplyMessageId(senderId, toolCallId) {
67
+ return `${REPLY_MESSAGE_PREFIX}${senderId}:${toolCallId}`;
68
+ }
69
+ /**
70
+ * Return the key of the `reply` of one Turn on a child's Conversation loop.
71
+ * Readers take the sender from the message's sender fields, not this key.
72
+ */
73
+ function getTurnReplyKey(turnId, toolCallId) {
74
+ return `${turnId}:${toolCallId}`;
75
+ }
76
+ /** Return the stable parent mailbox identity for one terminal result. */
77
+ function getAgentInvocationResultMessageId(invocationId) {
78
+ return `agent-invocation:${invocationId}:result`;
79
+ }
80
+ // src/chat/agent-invocations/child-message.ts
81
+ /** Mailbox metadata that stores who sent one child reply or result. */
82
+ function childMessageSenderMetadata(sender) {
83
+ return { sender };
84
+ }
85
+ /** Read who sent one child reply or result in a parent's mailbox. */
86
+ async function readChildMessageSender(message) {
87
+ return readInboundMessageSender(message) ?? (await readLegacyChildMessageSenders([message.inboundMessageId])).get(message.inboundMessageId);
88
+ }
89
+ /**
90
+ * Read who sent each child reply or result, in message order. Messages
91
+ * without stored sender fields share one legacy read.
92
+ */
93
+ async function readChildMessageSenders(messages) {
94
+ const stored = messages.map((message) => readInboundMessageSender(message));
95
+ const legacy = await readLegacyChildMessageSenders(messages.flatMap((message, index) => stored[index] ? [] : [message.inboundMessageId]));
96
+ return messages.map((message, index) => stored[index] ?? legacy.get(message.inboundMessageId));
97
+ }
98
+ /**
99
+ * List the child replies and results among the ids that reached one
100
+ * mailbox, oldest first, with the sender fields that the mailbox keeps.
101
+ */
102
+ async function listChildMessages(inboundMessageIds, messageSenders) {
103
+ const legacy = await readLegacyChildMessageSenders(inboundMessageIds.filter((id) => !messageSenders[id]));
104
+ return inboundMessageIds.flatMap((inboundMessageId) => {
105
+ const sender = messageSenders[inboundMessageId] ?? legacy.get(inboundMessageId);
106
+ return sender ? [{
107
+ inboundMessageId,
108
+ sender
109
+ }] : [];
110
+ });
111
+ }
112
+ /**
113
+ * Return the Agent invocation whose own Turn sent the message. A Turn on the
114
+ * child's Conversation loop has none, even when the message names the
115
+ * child's newest Agent invocation.
116
+ *
117
+ * TODO(dcramer): Remove with Agent invocation rows (#3060 step 7).
118
+ */
119
+ function ownAgentInvocation(sender) {
120
+ const { agentInvocationId } = sender;
121
+ return agentInvocationId && sender.turnId === getAgentInvocationTurnId(agentInvocationId) ? agentInvocationId : void 0;
122
+ }
123
+ /** Return whether the message is the result of an Agent invocation. */
124
+ function isAgentInvocationResult(message) {
125
+ const agentInvocationId = ownAgentInvocation(message.sender);
126
+ return agentInvocationId !== void 0 && message.inboundMessageId === getAgentInvocationResultMessageId(agentInvocationId);
127
+ }
128
+ /**
129
+ * Return whether one Agent invocation sent a reply to its parent: a message
130
+ * names it as sender and is not its own result.
131
+ */
132
+ function hasAgentInvocationReply(messages, agentInvocationId) {
133
+ return messages.some((message) => message.sender.agentInvocationId === agentInvocationId && !isAgentInvocationResult(message));
134
+ }
135
+ const LEGACY_REPLY_ID = /^agent-reply:(agent(?:-invocation)?:[0-9a-f]{32}):(?:(turn_[A-Za-z0-9_-]+)(?::|$))?/;
136
+ const LEGACY_RESULT_ID = /^agent-invocation:(agent-invocation:[0-9a-f]{32}):result$/;
137
+ /**
138
+ * Read the sender of child messages that reached a mailbox before senders
139
+ * stored their fields, from their ids.
140
+ *
141
+ * TODO: remove one release after this ships. Step 7 of #3060 deletes it and
142
+ * makes the id a plain generated key.
143
+ */
144
+ async function readLegacyChildMessageSenders(inboundMessageIds) {
145
+ const senders = /* @__PURE__ */ new Map();
146
+ const byAgentInvocation = /* @__PURE__ */ new Map();
147
+ for (const id of inboundMessageIds) {
148
+ const result = LEGACY_RESULT_ID.exec(id);
149
+ const reply = result ? void 0 : LEGACY_REPLY_ID.exec(id);
150
+ const senderId = result?.[1] ?? reply?.[1];
151
+ if (!senderId) continue;
152
+ const turnId = reply?.[2];
153
+ if (senderId.startsWith("agent-invocation:")) byAgentInvocation.set(id, {
154
+ agentInvocationId: senderId,
155
+ turnId
156
+ });
157
+ else if (turnId) senders.set(id, {
158
+ conversationId: senderId,
159
+ turnId
160
+ });
161
+ }
162
+ if (byAgentInvocation.size === 0) return senders;
163
+ const rows = await getSqlExecutor().db().select({
164
+ childConversationId: juniorAgentInvocations.childConversationId,
165
+ invocationId: juniorAgentInvocations.invocationId
166
+ }).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.invocationId, [...new Set([...byAgentInvocation.values()].map((s) => s.agentInvocationId))]));
167
+ const childOf = new Map(rows.map((row) => [row.invocationId, row.childConversationId]));
168
+ for (const [id, { agentInvocationId, turnId }] of byAgentInvocation) {
169
+ const conversationId = childOf.get(agentInvocationId);
170
+ if (!conversationId) continue;
171
+ senders.set(id, {
172
+ agentInvocationId,
173
+ conversationId,
174
+ turnId: turnId ?? getAgentInvocationTurnId(agentInvocationId)
175
+ });
176
+ }
177
+ return senders;
178
+ }
179
+ export { getNamedAgentConversationId as _, ownAgentInvocation as a, getAgentInvocationId as c, getAgentInvocationIdForResult as d, getAgentInvocationMessageId as f, getChildAgentLockName as g, getAgentReplyMessageId as h, listChildMessages as i, getAgentInvocationIdForEvents as l, getAgentInvocationTurnId as m, hasAgentInvocationReply as n, readChildMessageSender as o, getAgentInvocationResultMessageId as p, isAgentInvocationResult as r, readChildMessageSenders as s, childMessageSenderMetadata as t, getAgentInvocationIdForMessage as u, getTurnReplyKey as v, getUnnamedAgentConversationId as y };