@sentry/junior 0.297.0 → 0.299.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 (94) hide show
  1. package/dist/{actor-6jsm_v96.js → actor-D2iXzvlN.js} +2 -1
  2. package/dist/{state-DFnmLmfn.js → adapter-AgCNqqsG.js} +49 -133
  3. package/dist/{admin-tmGIw4KS.js → admin-1VwEXztm.js} +2 -2
  4. package/dist/{agent-runner-CneTquAE.js → agent-runner-Ciet8_nn.js} +1067 -1353
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +8 -7
  7. package/dist/api.d.ts +1 -1
  8. package/dist/api.js +125 -43
  9. package/dist/{app-BJojZ7HL.d.ts → app--ky-Eu33.d.ts} +6 -4
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +126 -299
  12. package/dist/{automation-BrP6ImrC.js → automation-M3RFJUBf.js} +1 -1
  13. package/dist/{background-compaction-queue-CwfJy3Cd.js → background-compaction-queue-CnimvRdk.js} +4 -4
  14. package/dist/{briefs-uFTuhMqA.js → briefs-CwzvgdCa.js} +4 -4
  15. package/dist/{catalog-runtime-0kuQqYL4.js → catalog-runtime-DaBaHY7u.js} +1 -1
  16. package/dist/cli/chat.js +17 -17
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +5 -5
  20. package/dist/cli/snapshot-create.js +4 -4
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +4 -4
  23. package/dist/{config-Dj9M_nqB.js → config-CAXIpWQb.js} +80 -6
  24. package/dist/{connections-B96JUM5o.js → connections-Dy0hPdUq.js} +6 -6
  25. package/dist/continue-in-slack-DIOjFj76.js +176 -0
  26. package/dist/{conversation-CvcBU1z2.js → conversation-fCWD9Az3.js} +73 -13
  27. package/dist/{conversation-feed-BSMlGZnS.js → conversation-feed-BPK8vkkZ.js} +88 -3
  28. package/dist/{conversation-privacy-DI29jbZV.js → conversation-privacy-DUgtRkf8.js} +1 -1
  29. package/dist/{conversation-turn-CZWBr091.js → conversation-turn-DkJB6yMF.js} +85 -68
  30. package/dist/{credential-sync-Blhx4_xf.js → credential-sync-RX24Y8aY.js} +18 -18
  31. package/dist/{db-CrtyFRz7.d.ts → db-B07FtU9g.d.ts} +1 -1
  32. package/dist/{db-Br0tfAo7.js → db-COYOGzYS.js} +171 -12
  33. package/dist/{executor-BMPipFVA.js → executor-BWmAgSyi.js} +40 -11
  34. package/dist/{media-BepyEUNm.js → history-IjdmO_r6.js} +1 -85
  35. package/dist/instrumentation.js +2 -2
  36. package/dist/lineage-D-5jm_oj.js +37 -0
  37. package/dist/{logging-CQjlDQYX.js → logging-DPLEa8Bn.js} +1 -1
  38. package/dist/media-BAHvgkok.js +85 -0
  39. package/dist/{message-BOZEIuxy.js → message-BIHR1yRk.js} +9 -10
  40. package/dist/model-input-BPZYH8Nd.js +82 -0
  41. package/dist/nitro.d.ts +1 -1
  42. package/dist/nitro.js +17 -9
  43. package/dist/{oauth-callback-server-V_DuMuNX.js → oauth-callback-server-R7qvSzFG.js} +2 -2
  44. package/dist/{plugins-HYh_JOdw.js → plugins-CBW2Prb_.js} +1 -1
  45. package/dist/{projection-B08mfi0u.js → projection-DEdP1q6f.js} +261 -36
  46. package/dist/{prompt-BlutWLNt.js → prompt-4M98h_tC.js} +4 -4
  47. package/dist/{registry-BDWgCJDf.js → registry-BTKmKM-r.js} +3 -3
  48. package/dist/{resolve-2Z_o_SsI.js → resolve-B8hXNVZ3.js} +3 -3
  49. package/dist/{result-CAujiaci.js → result-g-XAaOj6.js} +158 -69
  50. package/dist/{runner-D2Chc02N.js → runner-BlPSA5A8.js} +9 -9
  51. package/dist/{sandbox-egress-signals-CFoJduFj.js → sandbox-egress-signals-Pai-MzEY.js} +1 -1
  52. package/dist/{schema-Bqa5NbcP.js → schema-BNnY_trV.js} +47 -7
  53. package/dist/{schema-Ce2XCS7O.d.ts → schema-DbuWR-DN.d.ts} +663 -346
  54. package/dist/{service-account-C9kRQEb_.js → service-account-9OLNQMyz.js} +4 -4
  55. package/dist/{service-account-CERfXEVU.js → service-account-BYGZ08DQ.js} +3 -3
  56. package/dist/session-stop-2XJrcNCy.js +3356 -0
  57. package/dist/{skills-B0m1nZ_j.js → skills-DpBQoeHV.js} +3 -3
  58. package/dist/slack-conversation-unfurl-BcDIWo67.js +370 -0
  59. package/dist/spawn-09GssFod.js +73 -0
  60. package/dist/state-Cufq0_rH.js +132 -0
  61. package/dist/{user-input-request-CXNIov9n.js → statuses-B8mUfghF.js} +30 -25
  62. package/dist/{stop-BCH9VNGf.js → stop-U7iUrR1g.js} +6011 -5773
  63. package/dist/{store-B59rOYbS.js → store-BHiaHCQu.js} +24 -4
  64. package/dist/{store-m5bmdmsP.js → store-CSgUTMdv.js} +10 -10
  65. package/dist/{task-queue-N0kuCknH.js → task-queue-bMNq0clp.js} +4 -4
  66. package/dist/{task-runner-COOwR8qm.js → task-runner-B__rxwxU.js} +10 -10
  67. package/dist/{thread-context-Cd44z_W5.js → thread-context-d0ceWbVT.js} +18 -18
  68. package/dist/{turn-session-routing-BlCtVFRN.js → turn-session-routing-BVZHBFCF.js} +5 -5
  69. package/dist/turn-user-message-BEw7acTP.js +355 -0
  70. package/dist/users-BK3dbxZL.js +424 -0
  71. package/dist/{validation-Ba2OcUse.js → validation-BDVJjO2E.js} +1 -1
  72. package/dist/{version-KNDzIAh6.js → version-DQgZoQ3D.js} +1 -1
  73. package/dist/version.js +1 -1
  74. package/dist/{viewer-BPpuN2f9.js → viewer-CAWfFo29.js} +25 -54
  75. package/dist/{warmup-Bskrwmk1.js → warmup-9ySPacF9.js} +1137 -143
  76. package/dist/{worker-B1skZlit.js → worker-D8jJO-WO.js} +8 -7
  77. package/migrations/0104_code_change_draft.sql +1 -0
  78. package/migrations/0105_attachment_uploads.sql +14 -0
  79. package/migrations/0106_conversation_agent_config.sql +1 -0
  80. package/migrations/meta/0104_snapshot.json +4516 -0
  81. package/migrations/meta/0105_snapshot.json +4611 -0
  82. package/migrations/meta/0106_snapshot.json +4617 -0
  83. package/migrations/meta/_journal.json +21 -0
  84. package/package.json +4 -4
  85. package/dist/attempt-selection-ClP3MMPr.js +0 -61
  86. package/dist/locks-D-0h111u.js +0 -48
  87. package/dist/notification-gusCgdQ6.js +0 -1284
  88. package/dist/prompt-input-Dxn8cDC0.js +0 -1424
  89. package/dist/session-stop-B-I1rAS1.js +0 -181
  90. package/dist/spawn-CwMjRRtn.js +0 -80
  91. package/dist/turn-cancel-DDu8TOwt.js +0 -201
  92. package/dist/turn-user-message-ygLG3ylQ.js +0 -641
  93. package/dist/turn-wake-DmQec4AG.js +0 -161
  94. package/dist/{oauth-relay-CsfIazeF.js → oauth-relay-DRzq73b6.js} +1 -1
@@ -1,9 +1,9 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { h as logWarn } from "./logging-CQjlDQYX.js";
2
+ import { h as logWarn } from "./logging-DPLEa8Bn.js";
3
3
  import { s as skillRoots } from "./package-discovery-DJhGdS4c.js";
4
- import { n as pluginCatalogRuntime } from "./catalog-runtime-0kuQqYL4.js";
5
- import path from "node:path";
4
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-DaBaHY7u.js";
6
5
  import * as z from "zod";
6
+ import path from "node:path";
7
7
  import fs from "node:fs/promises";
8
8
  import { parse } from "yaml";
9
9
  // src/chat/skills.ts
@@ -0,0 +1,370 @@
1
+ import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
+ import { Ca as postSlackEphemeralMessage, Ea as unfurlSlackLinks, Fi as parseDashboardConversationLink, Ha as getWorkspaceTeamId, Mo as readConversationAccessFromSql, Tt as deferConversationMove, Vo as readLatestConversationBrief, da as escapeSlackMrkdwnText, fa as formatSlackLink } from "./projection-DEdP1q6f.js";
3
+ import { E as withSpan } from "./logging-DPLEa8Bn.js";
4
+ import { _ as slackUserIdSchema, b as slackMessageTsSchema, f as parseSlackTeamId, g as slackTeamIdSchema, h as slackChannelIdSchema, m as slackBotIdSchema, n as createSlackActor, p as parseSlackUserId, s as parseActorUserId, u as parseSlackChannelId } from "./actor-D2iXzvlN.js";
5
+ import { K as getConversationIdByProviderConversation, W as createCache, a as getConversationStore, o as getDb, s as getSqlExecutor } from "./db-COYOGzYS.js";
6
+ import { i as readActorIdentity } from "./viewer-CAWfFo29.js";
7
+ import "./store-BHiaHCQu.js";
8
+ import { a as runWithSlackInstallation, r as lookupSlackUserProfile, s as checkSlackChannelReadAccess, t as lookupSlackBot } from "./users-BK3dbxZL.js";
9
+ import { a as isMovableToSlack, i as continueConversationInSlack, n as alreadyContinuesInSlackMessage, t as BUSY } from "./continue-in-slack-DIOjFj76.js";
10
+ import * as z from "zod";
11
+ // src/chat/ingress/workspace-membership.ts
12
+ const MEMBER_TTL_MS = 3e5;
13
+ const NON_MEMBER_TTL_MS = 3e4;
14
+ const authorTeamSchema = z.object({
15
+ user_team: z.string().optional(),
16
+ source_team: z.string().optional(),
17
+ user: z.unknown().optional()
18
+ });
19
+ /** Accept only verified workspace authors, reusing recent membership lookups. */
20
+ async function isSlackWorkspaceMember(raw, state) {
21
+ const workspaceTeamId = getWorkspaceTeamId();
22
+ if (!workspaceTeamId) return false;
23
+ const parsed = authorTeamSchema.safeParse(raw);
24
+ if (!parsed.success) return false;
25
+ const event = parsed.data;
26
+ const userId = parseSlackUserId(event.user);
27
+ if (!userId) return false;
28
+ const cache = createCache(state, "core");
29
+ const key = `slack:membership:${workspaceTeamId}:${userId}`;
30
+ const authorTeam = parseSlackTeamId(event.user_team);
31
+ if (authorTeam === workspaceTeamId) return true;
32
+ if (event.user_team !== void 0 && !authorTeam && !/^E[A-Z0-9]+$/.test(event.user_team)) return false;
33
+ if (authorTeam !== void 0) return await cache.getOrLoad(key, async () => ({
34
+ value: false,
35
+ ttlMs: NON_MEMBER_TTL_MS
36
+ }), { refresh: true });
37
+ return await isCachedWorkspaceUser(userId, workspaceTeamId, state);
38
+ }
39
+ async function isCachedWorkspaceUser(userId, workspaceTeamId, state) {
40
+ return await createCache(state, "core").getOrLoad(`slack:membership:${workspaceTeamId}:${userId}`, async () => {
41
+ const user = await lookupSlackUserProfile(userId);
42
+ const authorTeam = parseSlackTeamId(user.team_id);
43
+ if (user.id !== userId || !authorTeam) return { value: false };
44
+ const member = authorTeam === workspaceTeamId && !user.is_deleted;
45
+ return {
46
+ value: member,
47
+ ttlMs: member ? MEMBER_TTL_MS : NON_MEMBER_TTL_MS
48
+ };
49
+ });
50
+ }
51
+ const botPostSchema = z.object({
52
+ bot_id: slackBotIdSchema,
53
+ bot_profile: z.object({
54
+ deleted: z.boolean(),
55
+ id: z.string(),
56
+ team_id: z.string()
57
+ }).optional(),
58
+ user: z.undefined().optional()
59
+ });
60
+ /**
61
+ * Return the bot ID of a post from an app in this workspace that has a bot ID
62
+ * and no user, or nothing. The channel must not be shared outside this
63
+ * workspace or its Enterprise Grid org. When Slack names the bot's workspace,
64
+ * in `bot_profile` or through the bot user of `bots.info`, it must be this
65
+ * workspace. On Enterprise Grid, Slack must name it.
66
+ */
67
+ async function slackWorkspaceBotId(raw, channelScope, state) {
68
+ const workspaceTeamId = getWorkspaceTeamId();
69
+ if (!workspaceTeamId || channelScope !== "workspace" && channelScope !== "enterprise") return;
70
+ const parsed = botPostSchema.safeParse(raw);
71
+ if (!parsed.success) return void 0;
72
+ const botId = parsed.data.bot_id;
73
+ const profile = parsed.data.bot_profile;
74
+ if (profile) return profile.id === botId && profile.team_id === workspaceTeamId && !profile.deleted ? botId : void 0;
75
+ const bot = await createCache(state, "core").getOrLoad(`slack:bot:${workspaceTeamId}:${botId}`, async () => {
76
+ const bot = await lookupSlackBot(botId);
77
+ if (!bot || bot.deleted) return {
78
+ value: { kind: "none" },
79
+ ttlMs: NON_MEMBER_TTL_MS
80
+ };
81
+ if (bot.id !== botId) return { value: { kind: "none" } };
82
+ if (bot.user_id === void 0) return {
83
+ value: { kind: "classic" },
84
+ ttlMs: MEMBER_TTL_MS
85
+ };
86
+ const userId = parseSlackUserId(bot.user_id);
87
+ if (!userId) return { value: { kind: "none" } };
88
+ return {
89
+ value: {
90
+ kind: "bot_user",
91
+ userId
92
+ },
93
+ ttlMs: MEMBER_TTL_MS
94
+ };
95
+ });
96
+ return (bot.kind === "bot_user" ? await isCachedWorkspaceUser(bot.userId, workspaceTeamId, state) : bot.kind === "classic" && channelScope === "workspace") ? botId : void 0;
97
+ }
98
+ // src/chat/ingress/slack-acting-user.ts
99
+ /**
100
+ * Resolve the Junior User of the person who clicked a Slack control. The
101
+ * click acts as that person, so it needs the same workspace and allowed
102
+ * domain checks as a Slack mention. A person Junior does not know yet gets
103
+ * a note to sign in.
104
+ */
105
+ async function resolveSlackActingUser(args) {
106
+ const { payload } = args;
107
+ const slackUserId = parseActorUserId(payload.user?.id);
108
+ const teamId = parseSlackTeamId(payload.team?.id ?? payload.user?.team_id);
109
+ if (!slackUserId || !teamId) throw new Error("Slack interaction payload is missing a user or team");
110
+ if (!await isSlackWorkspaceMember({
111
+ user: slackUserId,
112
+ user_team: payload.user?.team_id
113
+ }, args.state) || !await args.isAuthorAllowed(slackUserId)) return;
114
+ const user = (await readActorIdentity(createSlackActor(teamId, slackUserId, void 0)))?.user;
115
+ if (!user) {
116
+ await args.tell(slackUserId, "Junior does not know your account yet. Sign in to the Junior dashboard, then try again.");
117
+ return;
118
+ }
119
+ return {
120
+ slackUserId,
121
+ teamId,
122
+ user
123
+ };
124
+ }
125
+ // src/chat/ingress/slack-conversation-unfurl.ts
126
+ var slack_conversation_unfurl_exports = /* @__PURE__ */ __exportAll({
127
+ SLACK_CONTINUE_HERE_ACTION_ID: () => SLACK_CONTINUE_HERE_ACTION_ID,
128
+ continueDeferredSlackClick: () => continueDeferredSlackClick,
129
+ handleSlackContinueHereClick: () => handleSlackContinueHereClick,
130
+ unfurlDashboardConversationLinks: () => unfurlDashboardConversationLinks
131
+ });
132
+ /** Action id of the "Continue here" button on a dashboard link preview. */
133
+ const SLACK_CONTINUE_HERE_ACTION_ID = "junior_continue_here";
134
+ const MAX_LINKS = 5;
135
+ const MAX_SUMMARY_CHARS = 300;
136
+ const linkSharedEventSchema = z.object({
137
+ channel: z.string(),
138
+ links: z.array(z.object({ url: z.string() })),
139
+ message_ts: z.string(),
140
+ source: z.string().optional(),
141
+ thread_ts: slackMessageTsSchema.optional(),
142
+ unfurl_id: z.string().min(1).optional()
143
+ });
144
+ const continueHereValueSchema = z.object({
145
+ conversationId: z.string().min(1),
146
+ messageTs: slackMessageTsSchema,
147
+ threadTs: slackMessageTsSchema,
148
+ url: z.string().min(1)
149
+ });
150
+ function parseContinueHereValue(raw) {
151
+ try {
152
+ return continueHereValueSchema.parse(JSON.parse(raw ?? ""));
153
+ } catch {
154
+ return;
155
+ }
156
+ }
157
+ async function previewBlocks(args) {
158
+ const title = args.conversation.title ?? "Junior conversation";
159
+ const summary = (await readLatestConversationBrief(getDb(), args.conversation.conversationId))?.content.summary.trim();
160
+ const shortSummary = summary && summary.length > MAX_SUMMARY_CHARS ? `${summary.slice(0, 299)}…` : summary;
161
+ return [{
162
+ type: "section",
163
+ text: {
164
+ type: "mrkdwn",
165
+ text: [`*${formatSlackLink(args.url, title)}*`, ...shortSummary ? [escapeSlackMrkdwnText(shortSummary)] : []].join("\n")
166
+ }
167
+ }, ...args.footer ? [args.footer] : []];
168
+ }
169
+ function continueHereButton(value) {
170
+ return {
171
+ type: "actions",
172
+ elements: [{
173
+ type: "button",
174
+ action_id: SLACK_CONTINUE_HERE_ACTION_ID,
175
+ text: {
176
+ type: "plain_text",
177
+ text: "Continue here"
178
+ },
179
+ value: JSON.stringify(value)
180
+ }]
181
+ };
182
+ }
183
+ async function readPublicConversation(conversationId) {
184
+ const conversation = await getConversationStore().get({ conversationId });
185
+ if (!conversation || conversation.parentConversationId) return void 0;
186
+ return (await readConversationAccessFromSql(getDb(), [conversationId])).get(conversationId)?.visibility === "public" ? conversation : void 0;
187
+ }
188
+ /** Whether a thread in this channel can take a moved Conversation. */
189
+ async function canReceiveConversation(teamId, channelId, threadTs) {
190
+ return !await getConversationIdByProviderConversation(getSqlExecutor(), {
191
+ provider: "slack",
192
+ providerDestinationId: channelId,
193
+ providerTenantId: teamId,
194
+ providerConversationId: threadTs
195
+ }) && await isPublicChannel(teamId, channelId);
196
+ }
197
+ async function isPublicChannel(teamId, channelId) {
198
+ const access = await checkSlackChannelReadAccess({
199
+ currentChannelIds: [],
200
+ targetChannelId: channelId,
201
+ teamId
202
+ });
203
+ return access.allowed && access.isPublic === true;
204
+ }
205
+ /**
206
+ * Preview dashboard conversation links that a workspace member posted.
207
+ *
208
+ * Only public root Conversations get a preview, and only in channels that are
209
+ * not shared with other organizations. A public dashboard Conversation that
210
+ * can still move gets a "Continue here" button when the channel is public.
211
+ */
212
+ async function unfurlDashboardConversationLinks(args) {
213
+ const parsed = linkSharedEventSchema.safeParse(args.event);
214
+ const teamId = parseSlackTeamId(args.teamId);
215
+ if (!parsed.success || !teamId || parsed.data.source === "composer" || args.channelScope === "external" || !await isSlackWorkspaceMember(args.event, args.state)) return;
216
+ const event = parsed.data;
217
+ const channelId = parseSlackChannelId(event.channel);
218
+ const messageTs = slackMessageTsSchema.safeParse(event.message_ts);
219
+ if (!channelId || !messageTs.success) return;
220
+ const threadTs = event.thread_ts ?? messageTs.data;
221
+ const unfurls = {};
222
+ let canReceive;
223
+ const urls = [...new Set(event.links.map((link) => link.url))];
224
+ for (const url of urls.slice(0, MAX_LINKS)) {
225
+ const conversationId = parseDashboardConversationLink(url);
226
+ const conversation = conversationId ? await readPublicConversation(conversationId) : void 0;
227
+ if (!conversation) continue;
228
+ unfurls[url] = { blocks: await previewBlocks({
229
+ conversation,
230
+ url,
231
+ ...isMovableToSlack(conversation) && await (canReceive ??= canReceiveConversation(teamId, channelId, threadTs)) ? { footer: continueHereButton({
232
+ conversationId: conversation.conversationId,
233
+ messageTs: messageTs.data,
234
+ threadTs,
235
+ url
236
+ }) } : void 0
237
+ }) };
238
+ }
239
+ if (Object.keys(unfurls).length === 0) return;
240
+ await unfurlSlackLinks({
241
+ channelId,
242
+ messageTs: messageTs.data,
243
+ ...event.unfurl_id ? { unfurlId: event.unfurl_id } : void 0,
244
+ unfurls
245
+ });
246
+ }
247
+ const continueHereClickSchema = continueHereValueSchema.extend({
248
+ channelId: slackChannelIdSchema,
249
+ slackUserId: slackUserIdSchema,
250
+ teamId: slackTeamIdSchema
251
+ });
252
+ function tellClicker(click, userId, text) {
253
+ return postSlackEphemeralMessage({
254
+ channelId: click.channelId,
255
+ text,
256
+ ...click.threadTs !== click.messageTs ? { threadTs: click.threadTs } : void 0,
257
+ userId
258
+ });
259
+ }
260
+ async function showContinuesIn(conversation, click, locationUrl) {
261
+ await unfurlSlackLinks({
262
+ channelId: click.channelId,
263
+ messageTs: click.messageTs,
264
+ unfurls: { [click.url]: { blocks: await previewBlocks({
265
+ conversation,
266
+ footer: {
267
+ type: "context",
268
+ elements: [{
269
+ type: "mrkdwn",
270
+ text: locationUrl ? `Continues in ${formatSlackLink(locationUrl, "this thread")}.` : "Continues in this thread."
271
+ }]
272
+ },
273
+ url: click.url
274
+ }) } }
275
+ });
276
+ }
277
+ /**
278
+ * Move the Conversation of a click into its thread, or store the click until
279
+ * the Run that holds the Conversation ends. The clicker gets each refusal.
280
+ * A stored click (`deferred`) stays quiet when it has to wait again.
281
+ */
282
+ async function continueHere(click, user, deferred) {
283
+ const tell = (text) => tellClicker(click, click.slackUserId, text);
284
+ for (let attempt = 0; attempt < 3; attempt += 1) {
285
+ const conversation = await getConversationStore().get({ conversationId: click.conversationId });
286
+ const access = conversation ? (await readConversationAccessFromSql(getDb(), [click.conversationId], user)).get(click.conversationId) : void 0;
287
+ if (!conversation || access?.visibility !== "public") {
288
+ await tell("Only public conversations can move here.");
289
+ return;
290
+ }
291
+ if (!isMovableToSlack(conversation)) {
292
+ await tell(conversation.location ? await alreadyContinuesInSlackMessage(conversation) : "This conversation can no longer move to Slack.");
293
+ return;
294
+ }
295
+ const result = await continueConversationInSlack({
296
+ actorName: user.displayName ?? user.email,
297
+ channel: {
298
+ channelId: click.channelId,
299
+ teamId: click.teamId
300
+ },
301
+ conversation,
302
+ threadTs: click.threadTs
303
+ });
304
+ if (result.status === "refused") {
305
+ await tell(result.message);
306
+ return;
307
+ }
308
+ if (result.status === "moved") {
309
+ await showContinuesIn(conversation, click, result.locationUrl);
310
+ return;
311
+ }
312
+ const waiting = await deferConversationMove({
313
+ conversationId: click.conversationId,
314
+ move: click
315
+ });
316
+ if (waiting.status === "idle") continue;
317
+ if (deferred && waiting.move === click) return;
318
+ const first = continueHereClickSchema.safeParse(waiting.move).data;
319
+ await tell(first?.channelId === click.channelId && first.threadTs === click.threadTs ? "This conversation moves here when Junior finishes." : "This conversation moves to another thread when Junior finishes.");
320
+ return;
321
+ }
322
+ await tell(BUSY);
323
+ }
324
+ /**
325
+ * Move a dashboard Conversation into the thread of the message that shared
326
+ * its link, as the person who clicked "Continue here". While a Run holds
327
+ * the Conversation, the move waits for that Run to end.
328
+ */
329
+ async function handleSlackContinueHereClick(args) {
330
+ const target = parseContinueHereValue(args.value);
331
+ const channelId = parseSlackChannelId(args.payload.channel?.id);
332
+ if (!target || !channelId) throw new Error("Slack Continue here payload is incomplete");
333
+ const actor = await resolveSlackActingUser({
334
+ isAuthorAllowed: args.isAuthorAllowed,
335
+ payload: args.payload,
336
+ state: args.state,
337
+ tell: (userId, text) => tellClicker({
338
+ ...target,
339
+ channelId
340
+ }, userId, text)
341
+ });
342
+ if (!actor) return;
343
+ const slackUserId = parseSlackUserId(actor.slackUserId);
344
+ if (!slackUserId) throw new Error("Slack Continue here user is invalid");
345
+ await continueHere({
346
+ ...target,
347
+ channelId,
348
+ slackUserId,
349
+ teamId: actor.teamId
350
+ }, actor.user, false);
351
+ }
352
+ /**
353
+ * Run a stored "Continue here" click, as the person who clicked, after the
354
+ * Run that held its Conversation ended. Without an adapter, Slack calls use
355
+ * the default bot token.
356
+ */
357
+ async function continueDeferredSlackClick(value, getSlackAdapter) {
358
+ const click = continueHereClickSchema.parse(value);
359
+ const task = async () => {
360
+ const user = (await readActorIdentity(createSlackActor(click.teamId, click.slackUserId, void 0)))?.user;
361
+ if (!user) throw new Error("Slack Continue here clicker is unknown");
362
+ await continueHere(click, user, true);
363
+ };
364
+ await withSpan("chat.slack_continue_here_deferred", "chat.slack_continue_here_deferred", { conversationId: click.conversationId }, () => getSlackAdapter ? runWithSlackInstallation({
365
+ adapter: getSlackAdapter(),
366
+ installation: { teamId: click.teamId },
367
+ task
368
+ }) : task());
369
+ }
370
+ export { resolveSlackActingUser as a, unfurlDashboardConversationLinks as i, handleSlackContinueHereClick as n, isSlackWorkspaceMember as o, slack_conversation_unfurl_exports as r, slackWorkspaceBotId as s, SLACK_CONTINUE_HERE_ACTION_ID as t };
@@ -0,0 +1,73 @@
1
+ import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
+ import { n as botConfig } from "./config-CAXIpWQb.js";
3
+ import { Mt as actorFromRun, Nt as toolInvocationDestination } from "./agent-runner-Ciet8_nn.js";
4
+ import { $ as AgentDepthLimitError, _ as getAgentInvocation, ot as getAgentBinding, z as createAndEnqueueAgentInvocation } from "./warmup-9ySPacF9.js";
5
+ import { I as getUnnamedAgentConversationId, T as getAgentInvocationId, k as getAgentInvocationMessageId } from "./turn-user-message-BEw7acTP.js";
6
+ import { _ as getConversationWorkState } from "./store-BHiaHCQu.js";
7
+ import { t as readConversationLineage } from "./lineage-D-5jm_oj.js";
8
+ // src/chat/agent-invocations/spawn.ts
9
+ var spawn_exports = /* @__PURE__ */ __exportAll({ bindSpawnAgent: () => bindSpawnAgent });
10
+ /**
11
+ * Count the parents of the Conversation that starts a child agent. A chain
12
+ * that does not end at a root, such as a cycle, cannot start one.
13
+ */
14
+ async function assertCanStartChildAgent(conversationId, maxAgentDepth) {
15
+ const lineage = await readConversationLineage(conversationId);
16
+ const root = lineage[0];
17
+ if (!root || root.parentConversationId || lineage.length - 1 > maxAgentDepth) throw new AgentDepthLimitError(maxAgentDepth);
18
+ }
19
+ /**
20
+ * Return the child of a spawn that already ran without an agent invocation.
21
+ * Its idempotency key keys the task in the child's mailbox. A spawn with an
22
+ * agent invocation replays through that row instead.
23
+ */
24
+ async function findSpawnedChildAgent(args) {
25
+ const invocationId = getAgentInvocationId(args.parentConversationId, args.idempotencyKey);
26
+ if (await getAgentInvocation(invocationId)) return;
27
+ const childConversationId = args.agentName ? (await getAgentBinding({
28
+ name: args.agentName,
29
+ parentConversationId: args.parentConversationId
30
+ }))?.childConversationId : getUnnamedAgentConversationId(invocationId);
31
+ if (!childConversationId) return;
32
+ return (await getConversationWorkState({
33
+ conversationId: childConversationId,
34
+ state: args.state
35
+ }))?.execution.inboundMessageIds.includes(getAgentInvocationMessageId(invocationId)) ? childConversationId : void 0;
36
+ }
37
+ /** Bind a Run's Actor and credentials to new Agent invocations. */
38
+ function bindSpawnAgent(run, options) {
39
+ const actor = actorFromRun(run);
40
+ if (!actor) return;
41
+ return async (input, call) => {
42
+ call.signal?.throwIfAborted();
43
+ await assertCanStartChildAgent(run.conversationId, options.maxAgentDepth ?? botConfig.maxAgentDepth);
44
+ const idempotencyKey = `${run.turnId}:${call.toolCallId}`;
45
+ const spawned = await findSpawnedChildAgent({
46
+ ...input.name ? { agentName: input.name } : void 0,
47
+ idempotencyKey,
48
+ parentConversationId: run.conversationId,
49
+ state: options.state
50
+ });
51
+ if (spawned) return { childConversationId: spawned };
52
+ const queue = typeof options.queue === "function" ? options.queue() : options.queue;
53
+ return { childConversationId: (await createAndEnqueueAgentInvocation({
54
+ actor,
55
+ ...input.name ? { agentName: input.name } : void 0,
56
+ ...input.agentType ? { agentType: input.agentType } : void 0,
57
+ ...input.fork ? { fork: true } : void 0,
58
+ ...run.credentialContext ? { credentialContext: run.credentialContext } : void 0,
59
+ destination: toolInvocationDestination(run),
60
+ idempotencyKey,
61
+ input: input.task,
62
+ ...input.kind ? { kind: input.kind } : void 0,
63
+ parentConversationId: run.conversationId,
64
+ parentToolCallId: call.toolCallId,
65
+ ...input.reasoningLevel ? { reasoningLevel: input.reasoningLevel } : void 0,
66
+ ...input.title ? { title: input.title } : void 0
67
+ }, {
68
+ ...options,
69
+ queue
70
+ })).childConversationId };
71
+ };
72
+ }
73
+ export { spawn_exports as n, bindSpawnAgent as t };
@@ -0,0 +1,132 @@
1
+ import { i as getChatConfig } from "./config-CAXIpWQb.js";
2
+ import { h as logWarn } from "./logging-DPLEa8Bn.js";
3
+ import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
4
+ // src/chat/encryption/secret.ts
5
+ /**
6
+ * Encrypt secrets that Junior keeps at rest, such as provider credentials.
7
+ *
8
+ * AES-256-GCM with keys from `JUNIOR_ENCRYPTION_KEYS` (see `keyring.ts`).
9
+ * Each value is bound to a context, usually its storage key, and to its key
10
+ * id as additional authenticated data. A value copied to another key does not
11
+ * decrypt.
12
+ *
13
+ * New values use the active key. Any listed key decrypts. A value from a key
14
+ * that is not active reports `stale`, so its owner can save it again with the
15
+ * active key. A value that cannot be decrypted gives `UnreadableSecretError`:
16
+ * `unknown_key` when its key id is not listed, `invalid` when it is malformed,
17
+ * altered, or bound to another context.
18
+ *
19
+ * There is no per-value salt. The keys are random, not passwords, and each
20
+ * value has a random IV. The storage key in the AAD already names the
21
+ * identity that owns the value.
22
+ *
23
+ * Envelope: `jenc:v1:<keyId>:<iv>.<ciphertext>.<tag>` (base64url parts).
24
+ */
25
+ const ENVELOPE_PREFIX = "jenc:v1:";
26
+ const ALGORITHM = "aes-256-gcm";
27
+ const IV_BYTES = 12;
28
+ const TAG_BYTES = 16;
29
+ /** A stored secret that cannot be decrypted with the configured keys. */
30
+ var UnreadableSecretError = class extends Error {
31
+ reason;
32
+ constructor(reason) {
33
+ super(reason === "unknown_key" ? "Stored secret was encrypted with a key that is not configured" : "Stored secret is malformed or failed authentication");
34
+ this.name = "UnreadableSecretError";
35
+ this.reason = reason;
36
+ }
37
+ };
38
+ function additionalData(keyId, context) {
39
+ return Buffer.from(`${ENVELOPE_PREFIX}${keyId}\0${context}`, "utf8");
40
+ }
41
+ /** Check whether a stored value is an encryption envelope. */
42
+ function isEncryptedSecret(value) {
43
+ return typeof value === "string" && value.startsWith(ENVELOPE_PREFIX);
44
+ }
45
+ /** Encrypt one secret with the active key and bind it to `context`. */
46
+ function encryptSecret(plaintext, context, keyring = getChatConfig().encryption) {
47
+ const { id, key } = keyring.active;
48
+ const iv = randomBytes(IV_BYTES);
49
+ const cipher = createCipheriv(ALGORITHM, key, iv, { authTagLength: TAG_BYTES });
50
+ cipher.setAAD(additionalData(id, context));
51
+ const parts = [
52
+ iv,
53
+ Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]),
54
+ cipher.getAuthTag()
55
+ ].map((part) => part.toString("base64url"));
56
+ return `${ENVELOPE_PREFIX}${id}:${parts.join(".")}`;
57
+ }
58
+ /** Decrypt an `encryptSecret` envelope with the same `context`. */
59
+ function decryptSecret(envelope, context, keyring = getChatConfig().encryption) {
60
+ if (!isEncryptedSecret(envelope)) throw new Error("Stored secret is not an encryption envelope");
61
+ const [keyId, payload] = envelope.slice(8).split(":");
62
+ const [iv, ciphertext, tag] = (payload ?? "").split(".").map((part) => Buffer.from(part, "base64url"));
63
+ if (!keyId || !iv || iv.length !== IV_BYTES || !ciphertext || !tag || tag.length !== TAG_BYTES) throw new UnreadableSecretError("invalid");
64
+ const match = keyring.keys.find((candidate) => candidate.id === keyId);
65
+ if (!match) throw new UnreadableSecretError("unknown_key");
66
+ const decipher = createDecipheriv(ALGORITHM, match.key, iv, { authTagLength: TAG_BYTES });
67
+ decipher.setAAD(additionalData(keyId, context));
68
+ decipher.setAuthTag(tag);
69
+ let text;
70
+ try {
71
+ text = Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("utf8");
72
+ } catch {
73
+ throw new UnreadableSecretError("invalid");
74
+ }
75
+ return {
76
+ stale: match.id !== keyring.active.id,
77
+ text
78
+ };
79
+ }
80
+ // src/chat/encryption/state.ts
81
+ /**
82
+ * Decrypt one stored envelope. The storage key is the encryption context.
83
+ * A value that cannot be decrypted, such as one from a key that is no longer
84
+ * configured or one that was altered, reads as missing. The owner then asks
85
+ * for the credential again and saves it with the active key.
86
+ */
87
+ function decode(key, envelope) {
88
+ let decrypted;
89
+ try {
90
+ decrypted = decryptSecret(envelope, key);
91
+ } catch (error) {
92
+ if (!(error instanceof UnreadableSecretError)) throw error;
93
+ logWarn("encryption.secret_unreadable", { "error.type": error.reason });
94
+ return;
95
+ }
96
+ return {
97
+ stale: decrypted.stale,
98
+ value: JSON.parse(decrypted.text)
99
+ };
100
+ }
101
+ /**
102
+ * Wrap a state adapter so values are JSON-encoded and encrypted before they
103
+ * reach storage. Keys and TTLs stay readable. Use it for credentials and
104
+ * other secrets; delete, lock, and keep plain state on the base adapter.
105
+ */
106
+ function createEncryptedState(state) {
107
+ return {
108
+ async get(key) {
109
+ const stored = await state.get(key);
110
+ if (!isEncryptedSecret(stored)) return void 0;
111
+ return decode(key, stored)?.value;
112
+ },
113
+ async set(key, value, ttlMs) {
114
+ await state.set(key, encryptSecret(JSON.stringify(value), key), ttlMs);
115
+ }
116
+ };
117
+ }
118
+ /**
119
+ * Read a value and report whether it is stale: encrypted with a key that is
120
+ * not active, or saved before encryption. Long-lived owners save stale values
121
+ * again, so they move to the active key.
122
+ */
123
+ async function readEncryptedState(state, key) {
124
+ const stored = await state.get(key);
125
+ if (stored === null || stored === void 0) return void 0;
126
+ if (!isEncryptedSecret(stored)) return {
127
+ stale: true,
128
+ value: stored
129
+ };
130
+ return decode(key, stored);
131
+ }
132
+ export { readEncryptedState as n, createEncryptedState as t };
@@ -15,32 +15,11 @@ function isAgentInvocationResultEventType(eventType) {
15
15
  const AGENT_REPLY_EVENT_TYPE = "agent.reply";
16
16
  /** Event type of a message that a child agent sends to its parent. */
17
17
  const AGENT_MESSAGE_EVENT_TYPE = "agent.message";
18
- // src/chat/agent-invocations/statuses.ts
19
- const AGENT_INVOCATION_STATUSES = [
20
- "pending",
21
- "running",
22
- "paused",
23
- "blocked",
24
- "completed",
25
- "failed",
26
- "stopped"
27
- ];
28
- const AGENT_INVOCATION_MAILBOX_STATUSES = ["pending", "appended"];
29
18
  /**
30
- * Parent mailbox append state. Only terminal invocations have a value.
31
- * `replaced` means the child still had open work, so a later agent invocation
32
- * on the same child sends the result instead. `skipped` means a stop ended
33
- * the work, so the result is never used. `steered` means the agent invocation
34
- * that was running read the input as a steering message, so its result covers
35
- * this one.
19
+ * Event type of a parent agent task or message to a child that no agent
20
+ * invocation names.
36
21
  */
37
- const AGENT_INVOCATION_PARENT_MAILBOX_STATUSES = [
38
- "pending",
39
- "appended",
40
- "replaced",
41
- "skipped",
42
- "steered"
43
- ];
22
+ const AGENT_PARENT_MESSAGE_EVENT_TYPE = "agent.parent_message";
44
23
  // src/api/schema/user-customization.ts
45
24
  /** Longest customization text one user can save. */
46
25
  const USER_CUSTOMIZATION_MAX_CHARS = 1e3;
@@ -176,4 +155,30 @@ function formatUserInputAnswer(request, answer) {
176
155
  if (normalized.other) lines.push(answerLine(`Other: ${normalized.other}`));
177
156
  return lines.join("\n");
178
157
  }
179
- export { agentInvocationResultEventType as _, isEmptyUserInputAnswer as a, USER_CUSTOMIZATION_MAX_CHARS as c, AGENT_INVOCATION_MAILBOX_STATUSES as d, AGENT_INVOCATION_PARENT_MAILBOX_STATUSES as f, AGENT_REPLY_EVENT_TYPE as g, AGENT_MESSAGE_EVENT_TYPE as h, formatUserInputAnswer as i, userCustomizationSchema as l, AGENT_INVOCATION_EVENT_NAMESPACE as m, USER_INPUT_NOTE as n, normalizeUserInputAnswer as o, AGENT_INVOCATION_STATUSES as p, buttonUserInputField as r, userInputRequestSchema as s, USER_INPUT_LIMITS as t, userCustomizationTextSchema as u, isAgentInvocationResultEventType as v };
158
+ // src/chat/agent-invocations/statuses.ts
159
+ const AGENT_INVOCATION_STATUSES = [
160
+ "pending",
161
+ "running",
162
+ "paused",
163
+ "blocked",
164
+ "completed",
165
+ "failed",
166
+ "stopped"
167
+ ];
168
+ const AGENT_INVOCATION_MAILBOX_STATUSES = ["pending", "appended"];
169
+ /**
170
+ * Parent mailbox append state. Only terminal invocations have a value.
171
+ * `replaced` means the child still had open work, so a later agent invocation
172
+ * on the same child sends the result instead. `skipped` means a stop ended
173
+ * the work, so the result is never used. `steered` means the agent invocation
174
+ * that was running read the input as a steering message, so its result covers
175
+ * this one.
176
+ */
177
+ const AGENT_INVOCATION_PARENT_MAILBOX_STATUSES = [
178
+ "pending",
179
+ "appended",
180
+ "replaced",
181
+ "skipped",
182
+ "steered"
183
+ ];
184
+ export { AGENT_REPLY_EVENT_TYPE as _, USER_INPUT_NOTE as a, isEmptyUserInputAnswer as c, USER_CUSTOMIZATION_MAX_CHARS as d, userCustomizationSchema as f, AGENT_PARENT_MESSAGE_EVENT_TYPE as g, AGENT_MESSAGE_EVENT_TYPE as h, USER_INPUT_LIMITS as i, normalizeUserInputAnswer as l, AGENT_INVOCATION_EVENT_NAMESPACE as m, AGENT_INVOCATION_PARENT_MAILBOX_STATUSES as n, buttonUserInputField as o, userCustomizationTextSchema as p, AGENT_INVOCATION_STATUSES as r, formatUserInputAnswer as s, AGENT_INVOCATION_MAILBOX_STATUSES as t, userInputRequestSchema as u, agentInvocationResultEventType as v, isAgentInvocationResultEventType as y };