@sentry/junior 0.296.0 → 0.298.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 (82) hide show
  1. package/dist/{admin-z_lgDi-z.js → admin-BF3DbYGf.js} +2 -2
  2. package/dist/{agent-runner-HoQiUKLL.js → agent-runner-Q9GkoerG.js} +407 -1895
  3. package/dist/api/schema.d.ts +2 -2
  4. package/dist/api/schema.js +7 -7
  5. package/dist/api.d.ts +1 -1
  6. package/dist/api.js +38 -267
  7. package/dist/{app-C75Ft-A_.d.ts → app-DOg_mCtV.d.ts} +7 -2
  8. package/dist/app.d.ts +1 -1
  9. package/dist/app.js +64 -44
  10. package/dist/attempt-selection-ClP3MMPr.js +61 -0
  11. package/dist/{automation-yJX3C7i3.js → automation-Cn8qmbdr.js} +1 -1
  12. package/dist/{background-compaction-queue-Cre1wFt9.js → background-compaction-queue-BZhGFOK6.js} +4 -88
  13. package/dist/{briefs-BXECHduJ.js → briefs-CQrCRF6-.js} +3 -3
  14. package/dist/{catalog-runtime-CpCmlD9L.js → catalog-runtime-DZeD2WbL.js} +1 -1
  15. package/dist/cli/chat.js +19 -15
  16. package/dist/cli/check.js +3 -3
  17. package/dist/cli/main.js +3 -3
  18. package/dist/cli/plugins.js +4 -4
  19. package/dist/cli/snapshot-create.js +4 -4
  20. package/dist/cli/upgrade.d.ts +1 -1
  21. package/dist/cli/upgrade.js +3 -3
  22. package/dist/{config-CCPHvTqx.js → config-BOByVnxe.js} +2 -2
  23. package/dist/{connections-B5pWh8e2.js → connections-BNN5cJam.js} +6 -6
  24. package/dist/{conversation-CMkSmi02.js → conversation-DCkzvxqB.js} +51 -17
  25. package/dist/{conversation-feed-BVAOga0H.js → conversation-feed-CMA12Rjs.js} +1 -1
  26. package/dist/{conversation-privacy-CZD5soDW.js → conversation-privacy-C0eRxsgb.js} +1 -1
  27. package/dist/conversation-turn-D9qvcDX6.js +805 -0
  28. package/dist/{credential-sync-DwLkIvXI.js → credential-sync-B_iUpxGL.js} +14 -13
  29. package/dist/{db-C1M1y-bh.js → db-CoMNr2Zm.js} +43 -15
  30. package/dist/{db-B3iyr_Or.d.ts → db-DoMcnYol.d.ts} +13 -1
  31. package/dist/{executor-DUSEwXaO.js → executor-C-m8VrzX.js} +14 -6
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{logging-D0svFM8r.js → logging-CJTi5niy.js} +1 -1
  34. package/dist/{message-BFnIwKpx.js → message-Q6_5DAWR.js} +15 -13
  35. package/dist/nitro.d.ts +1 -1
  36. package/dist/nitro.js +3 -2
  37. package/dist/{session-stop-hYNTNpVf.js → notification-Bv25xbj0.js} +11 -930
  38. package/dist/{oauth-callback-server-BXRtD6Fk.js → oauth-callback-server-CH5XAyo-.js} +2 -2
  39. package/dist/{projection-B6VS7kbo.js → projection-BgwEE36_.js} +333 -106
  40. package/dist/{prompt-CD11tfG8.js → prompt-DXc9DYT9.js} +4 -4
  41. package/dist/prompt-input-BUr4J9RO.js +1424 -0
  42. package/dist/{registry-CHewwYEo.js → registry-9XwqSnM-.js} +1 -1
  43. package/dist/reporting-window-DopzcOHh.js +137 -0
  44. package/dist/{resolve-1owMH4qo.js → resolve-DUIAbcRL.js} +3 -3
  45. package/dist/result-C2Vn8QGn.js +463 -0
  46. package/dist/{runner-BtWvJslp.js → runner-CXGtw-Mc.js} +9 -8
  47. package/dist/{sandbox-egress-signals-ByftwJVt.js → sandbox-egress-signals-Di3S_dO7.js} +1 -1
  48. package/dist/{schema-Ct1Zf2xy.d.ts → schema-BnbZ-rKv.d.ts} +14 -107
  49. package/dist/{schema-D2iGyYIp.js → schema-Dyp7racy.js} +11 -48
  50. package/dist/{service-account-BZEuMKdo.js → service-account-DM3KBBeG.js} +3 -3
  51. package/dist/{service-account-DLoeoHww.js → service-account-GzAMUQ8a.js} +3 -3
  52. package/dist/session-stop-D4i7e6iT.js +181 -0
  53. package/dist/{skills-DXgd5Inh.js → skills-DCK9SD_l.js} +2 -2
  54. package/dist/{spawn-YeqlNDv8.js → spawn-6cX6xE9G.js} +6 -5
  55. package/dist/{state-C3CbtD_m.js → state-CSuA2J1V.js} +2 -2
  56. package/dist/{stop-Cze_pEL8.js → stop-Dh2DfwpK.js} +66 -159
  57. package/dist/{store-CZ9vqR4P.js → store-B1zepKG8.js} +11 -4
  58. package/dist/{task-runner-CMiNGsER.js → store-DrA17Fbz.js} +939 -1593
  59. package/dist/task-queue-D1rXWfFN.js +89 -0
  60. package/dist/task-runner-CT4M8oDz.js +291 -0
  61. package/dist/thread-context-DnqUkbzN.js +248 -0
  62. package/dist/turn-cancel-l460pfGW.js +201 -0
  63. package/dist/turn-session-routing-VXDVXLRl.js +380 -0
  64. package/dist/{turn-failure-response-pXhZ2wMK.js → turn-user-message-BSPmkm7X.js} +181 -392
  65. package/dist/turn-wake-DVFVXyhX.js +161 -0
  66. package/dist/{reporting-window-B3Ze-Qnt.js → user-input-request-CXNIov9n.js} +24 -143
  67. package/dist/{validation-Du7NdkOR.js → validation-zxAJBDDy.js} +1 -1
  68. package/dist/{version-EN3Wnq-R.js → version-DcZ40a0g.js} +1 -1
  69. package/dist/version.js +1 -1
  70. package/dist/{viewer-Agxi_o5c.js → viewer-CgiGjW10.js} +3 -3
  71. package/dist/warmup-CwKbxQLl.js +2698 -0
  72. package/dist/{worker-BALVdWbv.js → worker-CbDUzaBA.js} +20 -8
  73. package/migrations/0102_code_change_last_activity.sql +1 -0
  74. package/migrations/0103_agent_invocation_fork.sql +8 -0
  75. package/migrations/meta/0102_snapshot.json +4502 -0
  76. package/migrations/meta/0103_snapshot.json +4509 -0
  77. package/migrations/meta/_journal.json +14 -0
  78. package/package.json +4 -4
  79. package/dist/result-CEqQFrEf.js +0 -305
  80. package/dist/result-event-type-DD6BAgT7.js +0 -11
  81. package/dist/warmup-CY2ArYag.js +0 -2017
  82. package/dist/work-EA98F0ia.js +0 -768
@@ -1,554 +1,14 @@
1
- import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { Bn as getPlugins, Cn as renderUntrustedTag, Ga as sandboxSkillPathResolution, In as getPluginSlackConversationLink, Li as escapeSlackMrkdwnText, M as normalizeConversationText, Ri as formatSlackLink, Sn as renderTag, Ua as sandboxSkillDir, Wa as sandboxSkillFile, Yi as postSlackMessage, _i as listWorkspaces, fn as retainRuntimeTurnContext, ho as buildSentryConversationUrl, ii as getDashboardObjectIconLink, ni as JUNIOR_THREAD_STATE_TTL_MS, ot as getTurnRecord, pn as stripRuntimeTurnContext, ri as getDashboardConversationLink, rn as hasRuntimeTurnContext, sr as getReviewItem, st as listTurnSummaries, ti as verifyTimerWatchCredentialSubject, ui as ToolInputError, vn as escapeClosingTags, wn as tagJson, x as toStoredConversationMessage, xn as renderChildTag, yn as escapeTagText, zi as normalizeSlackReplyMarkdown, zn as getPluginUserPromptContributions, zr as cancelSubscriptions } from "./projection-B6VS7kbo.js";
3
- import { F as renderCurrentInstruction, L as escapeXml, n as botConfig } from "./config-CCPHvTqx.js";
4
- import { h as logWarn, m as logInfo, p as logException, v as serializeGenAiAttribute } from "./logging-D0svFM8r.js";
5
- import { o as isUserActor, t as createActor } from "./actor-6jsm_v96.js";
6
- import { M as SYSTEM_IDENTITY_ID, a as getConversationStore, o as getDb, r as getConversationEventStore, s as getSqlExecutor, tt as nextDetailVersion, w as isPersonInput } from "./db-C1M1y-bh.js";
7
- import { A as juniorConversations, M as juniorUsers } from "./executor-DUSEwXaO.js";
8
- import { i as isVisionImageMediaType } from "./media-BepyEUNm.js";
9
- import { h as credentialSubjectSchema } from "./registry-CHewwYEo.js";
10
- import { a as EVENT_SYSTEM_ACTOR, d as JUNIOR_NATIVE_EVENT_NAMESPACE, h as conversationNoteEvent, i as EVENT_MESSAGE_AUTHOR, o as isEventConversationMessage, r as EVENT_AUTHOR_ID } from "./prompt-CD11tfG8.js";
11
- import { a as getStateAdapter } from "./state-C3CbtD_m.js";
12
- import { D as NO_REPLY_TOOL_NAME, _ as buildDeploymentSystemPrompt, b as REPLY_TOOL_NAME, j as REPORT_BLOCKED_TOOL_NAME, y as buildTurnContextPrompt } from "./warmup-CY2ArYag.js";
13
- import { D as userCustomizationTextSchema, v as formatUserInputAnswer } from "./reporting-window-B3Ze-Qnt.js";
14
- import { r as appendAndEnqueueInboundMessage } from "./store-CZ9vqR4P.js";
15
- import { Ct as eventGuidance, St as eventCatalogEntry, yt as CORE_EVENT_NAMESPACE } from "./task-runner-CMiNGsER.js";
16
- import { isDeepStrictEqual } from "node:util";
1
+ import { $i as escapeSlackMrkdwnText, $t as REPLY_TOOL_NAME, Bn as tagJson, Ei as ToolInputError, Ln as renderChildTag, Pn as escapeClosingTags, Qn as getPluginSlackConversationLink, Rn as renderTag, _i as verifyTimerWatchCredentialSubject, bi as getDashboardObjectIconLink, da as postSlackMessage, ea as formatSlackLink, fn as REPORT_BLOCKED_TOOL_NAME, jo as buildSentryConversationUrl, nr as getPlugins, sn as NO_REPLY_TOOL_NAME, ta as normalizeSlackReplyMarkdown, vi as JUNIOR_THREAD_STATE_TTL_MS, yi as getDashboardConversationLink, zn as renderUntrustedTag } from "./projection-BgwEE36_.js";
2
+ import { n as botConfig } from "./config-BOByVnxe.js";
3
+ import { h as logWarn, m as logInfo, p as logException } from "./logging-CJTi5niy.js";
4
+ import { M as SYSTEM_IDENTITY_ID, a as getConversationStore } from "./db-CoMNr2Zm.js";
5
+ import { h as credentialSubjectSchema } from "./registry-9XwqSnM-.js";
6
+ import { r as EVENT_AUTHOR_ID } from "./prompt-DXc9DYT9.js";
7
+ import { a as getStateAdapter } from "./state-CSuA2J1V.js";
8
+ import { r as appendAndEnqueueInboundMessage } from "./store-B1zepKG8.js";
9
+ import { f as eventCatalogEntry, l as CORE_EVENT_NAMESPACE, p as eventGuidance } from "./turn-session-routing-VXDVXLRl.js";
17
10
  import * as z from "zod";
18
- import { and, eq, inArray, isNull, lt, lte, or, sql } from "drizzle-orm";
19
- import { agentEventKeys, createEventSource, createLocalSource, createWebSource, eventMatchFieldsSchema, objectFactFields, objectPresentation, objectTypeSchema } from "@sentry/junior-plugin-api";
20
- // src/chat/conversations/notes.ts
21
- /**
22
- * Conversation notes: short facts that core attaches to a Conversation without
23
- * starting a Turn. The next Turn shows them to the model in its runtime turn
24
- * context. A failed Turn also becomes a note for the next Turn. A note is
25
- * context, never user intent, and only core adds one.
26
- */
27
- /**
28
- * Tell the next Turn that a Turn failed. Pi drops a failed assistant message
29
- * before it calls the model, so without this note the model cannot see it.
30
- * The note has the error reference, never the raw error.
31
- */
32
- function failedTurnNote(failureCode, eventId) {
33
- const reference = eventId ? ` Error reference: event_id=${eventId}.` : "";
34
- return `Your previous turn failed before it finished. ${failureCode === "delivery_failed" ? "Your reply was not delivered, so the person did not see it. They may have seen an error reply." : "The person may have seen an error reply or no reply."}${reference} Do not assume that request was completed.`;
35
- }
36
- /** Most notes that one Turn shows. Older notes in the window are dropped. */
37
- const MAX_CONVERSATION_NOTES_PER_TURN = 20;
38
- /**
39
- * Attach a core-written note to a Conversation. It does not start a Turn or
40
- * change Conversation activity. The key makes a retry add nothing. Long text
41
- * is cut at the end.
42
- */
43
- async function addConversationNote(input) {
44
- const line = input.text.replace(/\s+/g, " ").trim();
45
- const text = line.length > 500 ? `${line.slice(0, 499)}…` : line;
46
- await getConversationEventStore().append(input.conversationId, [{
47
- createdAtMs: input.createdAtMs,
48
- idempotencyKey: `native:${JUNIOR_NATIVE_EVENT_NAMESPACE}:conversation_note:${input.key}`,
49
- data: {
50
- type: "structured_event",
51
- namespace: JUNIOR_NATIVE_EVENT_NAMESPACE,
52
- name: conversationNoteEvent.eventName,
53
- version: conversationNoteEvent.version,
54
- content: conversationNoteEvent.parse({ text })
55
- }
56
- }], { activity: "preserve" });
57
- }
58
- /**
59
- * Load the note texts for one Turn, oldest first: the notes added after the
60
- * previous Turn started and before this Turn started, plus a note for each
61
- * `turn_failed` event in that window. A retry of the Turn reads the same
62
- * window, so each note is shown to one Turn. A Turn that is not the newest
63
- * started Turn gets no notes.
64
- */
65
- async function loadTurnConversationNotes(input) {
66
- const newestFirst = [];
67
- let foundTurn = false;
68
- let beforeSeq;
69
- scan: while (true) {
70
- const page = await getConversationEventStore().query(input.conversationId, {
71
- beforeSeq,
72
- limit: 100,
73
- types: [
74
- "turn_started",
75
- "turn_failed",
76
- "structured_event"
77
- ]
78
- });
79
- for (const { data } of [...page.events].reverse()) if (data.type === "turn_started") {
80
- if (foundTurn) break scan;
81
- if (data.turnId !== input.turnId) return [];
82
- foundTurn = true;
83
- } else if (foundTurn && data.type === "turn_failed") {
84
- newestFirst.push(failedTurnNote(data.failureCode, data.eventId));
85
- if (newestFirst.length === MAX_CONVERSATION_NOTES_PER_TURN) break scan;
86
- } else if (foundTurn && data.type === "structured_event" && data.namespace === "junior" && data.name === conversationNoteEvent.eventName && data.version === conversationNoteEvent.version) {
87
- newestFirst.push(conversationNoteEvent.parse(data.content).text);
88
- if (newestFirst.length === MAX_CONVERSATION_NOTES_PER_TURN) break scan;
89
- }
90
- if (!page.hasOlder || page.events.length === 0) break;
91
- beforeSeq = page.events[0].seq;
92
- }
93
- return newestFirst.reverse();
94
- }
95
- // src/chat/experimental.ts
96
- /**
97
- * Known unstable product features that must be opted into explicitly.
98
- * Add new keys here as features graduate from private experiments; remove them
99
- * once they become stable defaults.
100
- */
101
- const EXPERIMENTAL_FEATURES = [
102
- "operator-tools",
103
- "passive-routing",
104
- "user-customization"
105
- ];
106
- const EXPERIMENTAL_FEATURE_SET = new Set(EXPERIMENTAL_FEATURES);
107
- let configuredExperimental = {};
108
- function isExperimentalFeature(value) {
109
- return EXPERIMENTAL_FEATURE_SET.has(value);
110
- }
111
- /** Replace app-level experimental opt-ins and return the previous setting. */
112
- function setExperimentalFeatures(config) {
113
- const previous = { ...configuredExperimental };
114
- if (config === void 0) {
115
- configuredExperimental = {};
116
- return previous;
117
- }
118
- const next = {};
119
- for (const [rawName, enabled] of Object.entries(config)) {
120
- if (enabled === void 0) continue;
121
- if (typeof enabled !== "boolean") throw new Error(`experimental.${rawName} must be a boolean when provided`);
122
- if (!isExperimentalFeature(rawName)) throw new Error(`experimental.${rawName} is not a known experimental feature. Known features: ${EXPERIMENTAL_FEATURES.join(", ")}`);
123
- next[rawName] = enabled;
124
- }
125
- configuredExperimental = next;
126
- return previous;
127
- }
128
- /** Return a copy of the app-level experimental opt-ins configured by createApp(). */
129
- function getExperimentalFeatures() {
130
- return { ...configuredExperimental };
131
- }
132
- /** Return whether one experimental feature is enabled via createApp({ experimental }). */
133
- function isExperimentalFeatureEnabled(feature) {
134
- return configuredExperimental[feature] === true;
135
- }
136
- // src/chat/identities/customization.ts
137
- /** Read the saved customization for one user. */
138
- async function readUserCustomization(userId) {
139
- return (await getDb().select({ customization: juniorUsers.customization }).from(juniorUsers).where(eq(juniorUsers.id, userId)).limit(1))[0]?.customization ?? void 0;
140
- }
141
- /**
142
- * Save or clear the customization for one user. Returns false when the user
143
- * does not exist.
144
- */
145
- async function saveUserCustomization(userId, customization) {
146
- const text = userCustomizationTextSchema.parse(customization);
147
- return (await getDb().update(juniorUsers).set({
148
- customization: text || null,
149
- updatedAt: /* @__PURE__ */ new Date()
150
- }).where(eq(juniorUsers.id, userId)).returning({ id: juniorUsers.id })).length > 0;
151
- }
152
- // src/chat/agent/prompt.ts
153
- /**
154
- * Per-run prompt assembly.
155
- *
156
- * Builds the user-turn content parts (text, attachments, omitted-image
157
- * notices) and the full prompt for one run slice: system instructions, plugin
158
- * contributions, bootstrap turn context, resume-safe history trimming, and
159
- * the optional canonical telemetry view of public input messages.
160
- */
161
- const MAX_INLINE_ATTACHMENT_BASE64_CHARS = 12e4;
162
- /**
163
- * Keep host-owned thread history as one evidence-only block.
164
- *
165
- * Producers already emit `<thread-context>`. Only wrap plain unstructured
166
- * background text so ambient messages never look like more instruction.
167
- */
168
- function renderThreadContextForPrompt(context) {
169
- if (/^<(?:thread-context|thread-transcript|thread-background|recent-thread-messages)(?:\s|>)/.test(context)) return context;
170
- return [
171
- "<thread-context authority=\"evidence-only\">",
172
- context,
173
- "</thread-context>"
174
- ].join("\n");
175
- }
176
- /** Render the current actor's instruction without host-owned thread context. */
177
- function buildUserTurnText(userInput, actor) {
178
- return renderCurrentInstruction(userInput, actor);
179
- }
180
- /**
181
- * Build the instruction for Turn inputs. Each input keeps its own prompt
182
- * content part, and `text` joins them for action review.
183
- */
184
- function instructionForInputs(inputs) {
185
- return {
186
- inputs,
187
- text: inputs.map((input) => input.text.trim()).filter(Boolean).join("\n\n")
188
- };
189
- }
190
- function renderInputParts(instruction) {
191
- return (instruction.inputs ?? [{
192
- kind: "person",
193
- text: instruction.text
194
- }]).map((input) => input.kind === "person" ? buildUserTurnText(input.text, instruction.actor) : input.text.trim());
195
- }
196
- /** Render an explicitly selected skill as instructions for the current turn. */
197
- function renderExplicitSkillInstructions(skill) {
198
- return [
199
- "<skill>",
200
- `<name>${escapeXml(skill.name)}</name>`,
201
- `<path>${escapeXml(sandboxSkillFile(skill.name))}</path>`,
202
- `<working_directory>${escapeXml(sandboxSkillDir(skill.name))}</working_directory>`,
203
- `<path_resolution>${escapeXml(sandboxSkillPathResolution(skill.name))}</path_resolution>`,
204
- skill.body,
205
- "</skill>"
206
- ].join("\n");
207
- }
208
- /** Encode a non-image attachment as base64 XML for the prompt. */
209
- function encodeNonImageAttachmentForPrompt(attachment) {
210
- const base64 = attachment.data.toString("base64");
211
- const wasTruncated = base64.length > MAX_INLINE_ATTACHMENT_BASE64_CHARS;
212
- const encodedPayload = wasTruncated ? `${base64.slice(0, MAX_INLINE_ATTACHMENT_BASE64_CHARS)}...` : base64;
213
- return [
214
- "<attachment>",
215
- `filename: ${attachment.filename ?? "unnamed"}`,
216
- `media_type: ${attachment.mediaType}`,
217
- "encoding: base64",
218
- `truncated: ${wasTruncated ? "true" : "false"}`,
219
- "<data_base64>",
220
- encodedPayload,
221
- "</data_base64>",
222
- "</attachment>"
223
- ].join("\n");
224
- }
225
- /** Redact image data from prompt content parts for observability. */
226
- function toObservablePromptPart(part) {
227
- if (part.type === "text") return {
228
- type: "text",
229
- text: part.text
230
- };
231
- return {
232
- type: "image",
233
- mimeType: part.mimeType,
234
- data: `[omitted:${part.data.length}]`
235
- };
236
- }
237
- function buildOmittedImageAttachmentNotice(count) {
238
- return [
239
- "<omitted-image-attachments>",
240
- `count: ${count}`,
241
- "Slack included image attachments with this turn, but this runtime cannot analyze images because no vision model is configured.",
242
- "Do not claim that no image was attached.",
243
- "If the user asks about image contents, explain that image analysis is unavailable in this runtime and continue with any text or non-image files that are still available.",
244
- "</omitted-image-attachments>"
245
- ].join("\n");
246
- }
247
- function buildUserTurnInput(args) {
248
- const userContentParts = args.inputParts.map((text) => ({
249
- type: "text",
250
- text
251
- }));
252
- if (args.omittedImageAttachmentCount > 0) {
253
- const omittedImagesNotice = buildOmittedImageAttachmentNotice(args.omittedImageAttachmentCount);
254
- userContentParts.push({
255
- type: "text",
256
- text: omittedImagesNotice
257
- });
258
- }
259
- for (const attachment of args.userAttachments ?? []) {
260
- if (attachment.promptText) {
261
- userContentParts.push({
262
- type: "text",
263
- text: attachment.promptText
264
- });
265
- continue;
266
- }
267
- if (attachment.attachmentId) userContentParts.push({
268
- type: "text",
269
- text: `Stored attachment: ${JSON.stringify({
270
- attachment_id: attachment.attachmentId,
271
- filename: attachment.filename,
272
- media_type: attachment.mediaType
273
- })}. Use loadAttachment to access the original file.`
274
- });
275
- if (isVisionImageMediaType(attachment.mediaType)) {
276
- if (!attachment.data) throw new Error("Image attachment is missing image data");
277
- userContentParts.push({
278
- type: "image",
279
- data: attachment.data.toString("base64"),
280
- mimeType: attachment.mediaType
281
- });
282
- continue;
283
- }
284
- if (!attachment.data) throw new Error("Attachment is missing attachment data");
285
- userContentParts.push({
286
- type: "text",
287
- text: encodeNonImageAttachmentForPrompt({
288
- data: attachment.data,
289
- mediaType: attachment.mediaType,
290
- filename: attachment.filename
291
- })
292
- });
293
- }
294
- return {
295
- contextContentParts: [],
296
- userContentParts
297
- };
298
- }
299
- /** Build the prompt-facing user input. */
300
- function buildPromptInput(args) {
301
- const { instruction } = args;
302
- const promptInput = buildUserTurnInput({
303
- omittedImageAttachmentCount: instruction.omittedImageAttachmentCount ?? 0,
304
- userAttachments: instruction.attachments ? [...instruction.attachments] : void 0,
305
- inputParts: renderInputParts(instruction)
306
- });
307
- const trimmedContext = instruction.context?.trim();
308
- return {
309
- ...promptInput,
310
- contextContentParts: trimmedContext ? [{
311
- type: "text",
312
- text: renderThreadContextForPrompt(trimmedContext)
313
- }] : []
314
- };
315
- }
316
- /**
317
- * Convert a mid-run user message into the Pi user message shape used for
318
- * steering injection and parked-conversation event-log appends, so both
319
- * paths store identical durable history.
320
- */
321
- function buildSteeringPiMessage(message) {
322
- const { userContentParts } = buildUserTurnInput({
323
- inputParts: [message.kind === "runtime" ? message.text.trim() : buildUserTurnText(message.text, message.actor)],
324
- userAttachments: message.attachments ? [...message.attachments] : void 0,
325
- omittedImageAttachmentCount: message.omittedImageAttachmentCount ?? 0
326
- });
327
- return {
328
- role: "user",
329
- content: userContentParts,
330
- timestamp: message.timestampMs ?? Date.now()
331
- };
332
- }
333
- /**
334
- * Return a stable key for one steering message. Resolved attachments may change
335
- * when Junior retries a mailbox delivery, so only the message time and text
336
- * form the key.
337
- */
338
- function steeringMessageKey(message) {
339
- if (message.role !== "user") return;
340
- const first = Array.isArray(message.content) ? message.content[0] : void 0;
341
- const text = first && typeof first === "object" && "text" in first ? String(first.text ?? "") : "";
342
- return `${message.timestamp}:${text}`;
343
- }
344
- /**
345
- * Remove steering messages that saved history already holds. A repeated
346
- * mailbox delivery can contain saved and unsaved messages.
347
- */
348
- function withoutSavedSteeringMessages(saved, entries, toMessage) {
349
- const savedKeys = new Set(saved.map(steeringMessageKey).filter((key) => key !== void 0));
350
- return entries.filter((entry) => {
351
- const key = steeringMessageKey(toMessage(entry));
352
- return key === void 0 || !savedKeys.has(key);
353
- });
354
- }
355
- function withoutTrailingUncheckpointedUserPrompt(messages, userContentParts) {
356
- if (!messages || messages.length === 0) return { messages: [] };
357
- const lastMessage = messages.at(-1);
358
- if (lastMessage?.role !== "user") return { messages };
359
- const comparableLastMessage = stripRuntimeTurnContext([lastMessage])[0];
360
- if (!userPromptContentMatches(comparableLastMessage?.content, userContentParts)) return { messages };
361
- const promptTimestamp = typeof lastMessage.timestamp === "number" ? lastMessage.timestamp : void 0;
362
- const withoutPrompt = messages.slice(0, -1);
363
- const previousMessage = withoutPrompt.at(-1);
364
- if (previousMessage && stripRuntimeTurnContext([previousMessage, lastMessage]).length === 1) return {
365
- messages: withoutPrompt.slice(0, -1),
366
- promptTimestamp
367
- };
368
- return {
369
- messages: withoutPrompt,
370
- promptTimestamp
371
- };
372
- }
373
- function userPromptContentMatches(storedContent, currentContent) {
374
- return isDeepStrictEqual(storedContent, currentContent);
375
- }
376
- function isUserContentPart(value) {
377
- if (typeof value !== "object" || value === null || !("type" in value)) return false;
378
- if (value.type === "text") return "text" in value && typeof value.text === "string";
379
- return value.type === "image" && "data" in value && typeof value.data === "string" && "mimeType" in value && typeof value.mimeType === "string";
380
- }
381
- async function loadUserCustomization(context) {
382
- if (!isExperimentalFeatureEnabled("user-customization")) return void 0;
383
- const user = (await context.resolveActorIdentity?.())?.user;
384
- return user ? await readUserCustomization(user.id) : void 0;
385
- }
386
- function userCustomizationTurnContext(text) {
387
- return {
388
- pluginName: "junior",
389
- kind: "user_customization",
390
- version: 1,
391
- content: { text },
392
- loadedAtMs: Date.now()
393
- };
394
- }
395
- function checkpointedPrompt(args) {
396
- if (!args.messages || args.turnStartMessageIndex === void 0 || args.turnStartMessageIndex >= args.messages.length) return;
397
- const turnMessages = args.messages.slice(args.turnStartMessageIndex);
398
- const durableTurnMessages = stripRuntimeTurnContext(turnMessages);
399
- if (durableTurnMessages.length !== 1) return;
400
- const message = durableTurnMessages[0];
401
- if (message?.role !== "user" || !Array.isArray(message.content)) return;
402
- if (!userPromptContentMatches(message.content, args.userContentParts)) return;
403
- if (!message.content.every(isUserContentPart)) return;
404
- return {
405
- contextContentParts: retainRuntimeTurnContext(turnMessages).flatMap((runtimeMessage) => {
406
- const content = runtimeMessage.content;
407
- return Array.isArray(content) && content.every(isUserContentPart) ? content : [];
408
- }),
409
- userContentParts: message.content
410
- };
411
- }
412
- function planPromptReplay(args) {
413
- const hasPromptCheckpoint = args.resumedFromSessionRecord && args.existingTurnStartMessageIndex !== void 0;
414
- const shouldPromptAgent = !args.resumedFromSessionRecord || !hasPromptCheckpoint;
415
- const replayedPrompt = shouldPromptAgent && !args.resumedFromSessionRecord ? checkpointedPrompt({
416
- messages: args.existingSessionPiMessages,
417
- turnStartMessageIndex: args.existingTurnStartMessageIndex,
418
- userContentParts: args.userContentParts
419
- }) : void 0;
420
- return {
421
- loadsTurnContext: shouldPromptAgent && !replayedPrompt,
422
- replayedPrompt,
423
- shouldPromptAgent
424
- };
425
- }
426
- /**
427
- * Load the Turn context for a new prompt: plugin prompt hooks, such as
428
- * memory recall, Conversation notes, and the user customization.
429
- *
430
- * It needs no tool wiring, so the caller can run it while sandbox setup
431
- * runs.
432
- */
433
- async function loadPromptTurnContext(args) {
434
- if (!planPromptReplay(args).loadsTurnContext) return { pluginUserPromptContributions: [] };
435
- const [pluginUserPromptContributions, conversationNotes, userCustomization, workspaces] = await Promise.all([
436
- getPluginUserPromptContributions({
437
- context: args.context,
438
- turnId: args.turnId
439
- }),
440
- loadTurnConversationNotes({
441
- conversationId: args.context.conversationId,
442
- turnId: args.turnId
443
- }),
444
- isUserActor(args.currentActor) ? loadUserCustomization(args.context) : void 0,
445
- listWorkspaces(getDb())
446
- ]);
447
- return {
448
- conversationNotes,
449
- pluginUserPromptContributions,
450
- userCustomization,
451
- workspaces
452
- };
453
- }
454
- /** Assemble prompt history, instructions, and telemetry input for one slice. */
455
- async function assemblePrompt(args) {
456
- const source = args.run.source;
457
- const { loadsTurnContext, replayedPrompt, shouldPromptAgent } = planPromptReplay(args);
458
- const requestContentParts = args.userContentParts;
459
- const trimmedPrompt = shouldPromptAgent ? withoutTrailingUncheckpointedUserPrompt(args.priorPiMessages, requestContentParts) : { messages: args.existingSessionPiMessages };
460
- const promptHistoryMessages = trimmedPrompt.messages;
461
- const needsBootstrapContextForPrompt = shouldPromptAgent && !replayedPrompt && !hasRuntimeTurnContext(promptHistoryMessages);
462
- const platform = (args.run.delivery || args.promptMode === "automation") && args.run.location?.provider === "slack" ? "slack" : "local";
463
- const baseInstructions = await buildDeploymentSystemPrompt(platform, args.promptMode);
464
- const { conversationNotes, pluginUserPromptContributions, userCustomization, workspaces } = args.turnContext;
465
- const disabledTools = loadsTurnContext ? args.disabledTools : [];
466
- const turnContextPrompt = needsBootstrapContextForPrompt || pluginUserPromptContributions.length > 0 || (conversationNotes?.length ?? 0) > 0 || disabledTools.length > 0 || userCustomization ? buildTurnContextPrompt({
467
- availableSkills: args.availableSkills,
468
- activeMcpCatalogs: args.activeMcpCatalogs,
469
- conversationNotes,
470
- disabledTools,
471
- includeSessionContext: needsBootstrapContextForPrompt,
472
- pluginPromptContributions: pluginUserPromptContributions,
473
- toolGuidance: args.toolGuidance,
474
- userCustomization,
475
- workspaces,
476
- runtime: {
477
- conversationId: args.spanContext.conversationId,
478
- slackConversation: args.run.slackConversation
479
- },
480
- dispatch: args.run.dispatch ? {
481
- ...args.run.dispatch,
482
- destination: args.run.destination,
483
- source
484
- } : void 0,
485
- actor: isUserActor(args.currentActor) ? args.currentActor : void 0,
486
- configuration: args.configurationValues
487
- }) : null;
488
- const turnContextParts = turnContextPrompt ? [{
489
- type: "text",
490
- text: turnContextPrompt
491
- }] : [];
492
- const contextContentParts = replayedPrompt?.contextContentParts ?? [
493
- ...turnContextParts,
494
- ...args.explicitSkill ? [{
495
- type: "text",
496
- text: renderExplicitSkillInstructions(args.explicitSkill)
497
- }] : [],
498
- ...args.contextContentParts
499
- ];
500
- const userContentParts = replayedPrompt?.userContentParts ?? requestContentParts;
501
- return {
502
- baseInstructions,
503
- contextContentParts,
504
- inputMessages: [
505
- {
506
- role: "system",
507
- content: [{
508
- type: "text",
509
- text: baseInstructions
510
- }]
511
- },
512
- ...contextContentParts.length > 0 ? [{
513
- role: "user",
514
- content: contextContentParts.map((part) => toObservablePromptPart(part))
515
- }] : [],
516
- {
517
- role: "user",
518
- content: userContentParts.map((part) => toObservablePromptPart(part))
519
- }
520
- ],
521
- inputMessagesAttribute: serializeGenAiAttribute(args.conversationPrivacy === "public" ? [
522
- {
523
- role: "system",
524
- parts: [{
525
- type: "text",
526
- content: baseInstructions
527
- }]
528
- },
529
- ...contextContentParts.length > 0 ? [{
530
- role: "user",
531
- parts: contextContentParts.flatMap((part) => part.type === "text" ? [{
532
- type: "text",
533
- content: part.text
534
- }] : [])
535
- }] : [],
536
- {
537
- role: "user",
538
- parts: userContentParts.flatMap((part) => part.type === "text" ? [{
539
- type: "text",
540
- content: part.text
541
- }] : [])
542
- }
543
- ] : void 0),
544
- platform,
545
- ...trimmedPrompt.promptTimestamp !== void 0 ? { promptTimestamp: trimmedPrompt.promptTimestamp } : void 0,
546
- promptHistoryMessages,
547
- shouldPromptAgent,
548
- turnContexts: [...userCustomization ? [userCustomizationTurnContext(userCustomization)] : [], ...pluginUserPromptContributions.flatMap((contribution) => contribution.context ? [contribution.context] : [])],
549
- userContentParts
550
- };
551
- }
11
+ import { agentEventKeys, eventMatchFieldsSchema, objectFactFields, objectPresentation, objectTypeSchema } from "@sentry/junior-plugin-api";
552
12
  // src/chat/services/automated-turn-limit.ts
553
13
  const AUTOMATED_TURN_LIMIT_PREFIX = "junior:automated_turn_limit:v1";
554
14
  const AUTOMATED_TURN_LIMIT_LOCK_TTL_MS = 5e3;
@@ -1821,383 +1281,4 @@ async function enqueueEventNotification(args) {
1821
1281
  state: args.state
1822
1282
  });
1823
1283
  }
1824
- // src/chat/conversations/sql/subtree.ts
1825
- /** Columns of the `conversation_subtree` table that `conversationSubtree` returns. */
1826
- const conversationSubtreeColumns = {
1827
- conversationId: sql`conversation_subtree.conversation_id`,
1828
- scopeConversationId: sql`conversation_subtree.scope_conversation_id`
1829
- };
1830
- /**
1831
- * Return a joinable `conversation_subtree` table. It maps each selected
1832
- * Conversation to itself and to each descendant child Conversation at any
1833
- * depth. Reports use it so that a total for a Conversation always includes the
1834
- * work of all its child agents.
1835
- *
1836
- * A descendant must have the same root as the selected Conversation. Thus a
1837
- * Conversation that has no valid root gets only its own work.
1838
- */
1839
- function conversationSubtree(conversationIds) {
1840
- const selectedIds = sql.join(conversationIds.map((conversationId) => sql`${conversationId}`), sql`, `);
1841
- return sql`(
1842
- with recursive tree(scope_conversation_id, conversation_id, root_conversation_id) as (
1843
- select selected.conversation_id, selected.conversation_id, selected.root_conversation_id
1844
- from junior_conversations selected
1845
- where selected.conversation_id in (${selectedIds})
1846
- union
1847
- select tree.scope_conversation_id, child.conversation_id, child.root_conversation_id
1848
- from junior_conversations child
1849
- join tree
1850
- on child.parent_conversation_id = tree.conversation_id
1851
- and (child.root_conversation_id || '') = tree.root_conversation_id
1852
- )
1853
- select scope_conversation_id, conversation_id from tree
1854
- ) conversation_subtree`;
1855
- }
1856
- // src/chat/conversations/web-mailbox.ts
1857
- /** Parse web mailbox metadata written before Source and Actor were complete. */
1858
- const legacyWebMailboxMetadataSchema = z.object({
1859
- authorEmail: z.string().email(),
1860
- authorFullName: z.string().min(1).optional(),
1861
- authorUserId: z.string().min(1),
1862
- authorUserName: z.string().min(1).optional(),
1863
- kind: z.literal("api_turn"),
1864
- messageId: z.string().min(1)
1865
- }).strict();
1866
- // src/chat/task-execution/mailbox-turn.ts
1867
- /**
1868
- * Restore Turn input facts, with saved Message fallback for legacy cursors.
1869
- *
1870
- * TODO(dcramer): Remove Actor and Source reconstruction from the saved Message
1871
- * after no deployed Turn cursor can omit either field.
1872
- */
1873
- function turnInputFactsFromConversationMessage(message, args) {
1874
- if (isEventConversationMessage(message)) return {
1875
- actor: args.savedActor ?? EVENT_SYSTEM_ACTOR,
1876
- author: message.author ?? EVENT_MESSAGE_AUTHOR,
1877
- source: args.savedSource ?? (args.location ? createWebSource(args.conversationId, args.visibility === "private" ? "private" : "public") : createLocalSource(args.conversationId))
1878
- };
1879
- const actor = args.savedActor ?? createActor(message.author, {
1880
- platform: "web",
1881
- userId: message.author?.userId
1882
- });
1883
- if (actor?.platform !== "web") return;
1884
- return {
1885
- actor,
1886
- author: message.author ?? { userId: actor.userId },
1887
- source: args.savedSource?.kind === "web" ? args.savedSource : createWebSource(args.conversationId, args.visibility === "private" ? "private" : "public")
1888
- };
1889
- }
1890
- /** Normalize the selected mailbox Source with current Conversation visibility. */
1891
- function sourceFromTurnInput(args) {
1892
- if (args.source.kind === "web") return createWebSource(args.conversationId, args.visibility === "private" ? "private" : "public");
1893
- return args.source;
1894
- }
1895
- function hasEventActor(actors) {
1896
- return Boolean(actors?.some((actor) => actor.platform === "system" && actor.name === EVENT_SYSTEM_ACTOR.name));
1897
- }
1898
- /** Return the active web Turn for one Conversation, if it has one. */
1899
- async function getActiveConversationTurnId(conversationId) {
1900
- const active = (await listTurnSummaries(conversationId)).filter((summary) => summary.surface === "api" && !summary.dispatchId && (summary.state === "paused" || summary.state === "running"));
1901
- if (active.length > 1) throw new Error(`Conversation ${conversationId} has multiple active web turns`);
1902
- const turnId = active[0]?.turnId;
1903
- if (!turnId) return void 0;
1904
- const record = await getTurnRecord(conversationId, turnId);
1905
- return record && (record.source?.kind === "web" || !record.source && record.surface === "api") && !record.dispatchId && (record.state === "paused" || record.state === "running") ? turnId : void 0;
1906
- }
1907
- /** Return the web and event mailbox Turns that are paused or running. */
1908
- async function listActiveMailboxTurns(conversationId) {
1909
- const summaries = await listTurnSummaries(conversationId);
1910
- return (await Promise.all(summaries.filter((summary) => !summary.dispatchId && (summary.state === "paused" || summary.state === "running")).map((summary) => getTurnRecord(conversationId, summary.turnId)))).filter((record) => record !== void 0 && !record.dispatchId && record.surface !== "internal" && (record.source?.kind === "web" || record.source?.kind === "event" || !record.source && (record.surface === "api" || hasEventActor(record.actors))) && (record.state === "paused" || record.state === "running"));
1911
- }
1912
- /** Return the active web or event mailbox Turn. */
1913
- async function getActiveMailboxTurnId(conversationId) {
1914
- const active = await listActiveMailboxTurns(conversationId);
1915
- if (active.length > 1) throw new Error(`Conversation ${conversationId} has multiple active mailbox Turns`);
1916
- return active[0]?.turnId;
1917
- }
1918
- /** Return the idle auth-paused web Turn for one Conversation. */
1919
- async function getAuthPausedConversationTurnId(conversationId) {
1920
- const turnId = await getActiveConversationTurnId(conversationId);
1921
- if (!turnId) return void 0;
1922
- const record = await getTurnRecord(conversationId, turnId);
1923
- return record?.state === "paused" && record.resumeReason === "auth" ? turnId : void 0;
1924
- }
1925
- /** Read one web input batch as Turn input. A batch with no web input gives []. */
1926
- function parseWebMessages(messages) {
1927
- if (messages.length === 0) return [];
1928
- const parsed = messages.map((message) => ({
1929
- message,
1930
- metadata: legacyWebMailboxMetadataSchema.safeParse(message.input.metadata)
1931
- }));
1932
- if (parsed.every((entry) => !entry.metadata.success)) return [];
1933
- if (parsed.some((entry) => !entry.metadata.success)) throw new Error("A Turn cannot combine different kinds of input");
1934
- return parsed.map((entry) => {
1935
- if (!entry.metadata.success) throw new Error("User message has invalid metadata");
1936
- const metadata = entry.metadata.data;
1937
- const actor = {
1938
- platform: "web",
1939
- userId: metadata.authorUserId,
1940
- email: metadata.authorEmail.trim().toLowerCase(),
1941
- ...metadata.authorFullName ? { fullName: metadata.authorFullName } : void 0,
1942
- ...metadata.authorUserName ? { userName: metadata.authorUserName } : void 0
1943
- };
1944
- return {
1945
- actor,
1946
- author: {
1947
- email: actor.email,
1948
- ...actor.fullName ? { fullName: actor.fullName } : void 0,
1949
- userId: actor.userId,
1950
- ...actor.userName ? { userName: actor.userName } : void 0
1951
- },
1952
- message: entry.message,
1953
- source: createWebSource(entry.message.conversationId)
1954
- };
1955
- });
1956
- }
1957
- /** Extra debounce time added per additional event already batched. */
1958
- const EVENT_WAIT_PER_EXTRA_MESSAGE_MS = 5e3;
1959
- /** Upper bound on the debounce window regardless of batch size. */
1960
- const EVENT_MAX_WAIT_MS = 6e4;
1961
- /**
1962
- * Return how long an event batch must wait before its Turn starts.
1963
- *
1964
- * A resource-event burst (e.g. several check runs on one PR) should produce
1965
- * one Turn instead of one per event. The window grows with batch size up to
1966
- * EVENT_MAX_WAIT_MS, so later events in the same burst land in this batch.
1967
- * Returns 0 when the batch can run now or does not start with an event.
1968
- */
1969
- function getEventBatchDelayMs(messages, nowMs = Date.now()) {
1970
- const first = messages[0];
1971
- if (!first || !isEventMailboxMetadata(first.input.metadata)) return 0;
1972
- const waitMs = Math.min(EVENT_MAX_WAIT_MS, EVENT_WAIT_MS + EVENT_WAIT_PER_EXTRA_MESSAGE_MS * (messages.length - 1));
1973
- return Math.max(0, first.receivedAtMs + waitMs - nowMs);
1974
- }
1975
- /** Read an event batch as Turn input, or return [] when it is not only events. */
1976
- function parseEventMessages(messages) {
1977
- if (messages.length === 0) return [];
1978
- if (!messages.every((message) => message.source === "event" && isEventMailboxMetadata(message.input.metadata))) return [];
1979
- return messages.map((message) => {
1980
- if (!isEventMailboxMetadata(message.input.metadata)) throw new Error("Event has invalid metadata");
1981
- return {
1982
- actor: EVENT_SYSTEM_ACTOR,
1983
- author: EVENT_MESSAGE_AUTHOR,
1984
- message,
1985
- source: createEventSource({
1986
- eventKey: message.input.metadata.event.eventKey,
1987
- eventType: message.input.metadata.event.eventType,
1988
- identifier: message.input.metadata.event.identifier,
1989
- namespace: message.input.metadata.event.namespace
1990
- })
1991
- };
1992
- });
1993
- }
1994
- /**
1995
- * Select web or event work from new mailbox input or a saved Turn.
1996
- * Saved Actor data identifies a resumed event Turn.
1997
- */
1998
- async function resolveMailboxTurnWork(context) {
1999
- const batch = parseWebMessages(context.attempt.messages);
2000
- if (batch.length > 0) return {
2001
- kind: "mailbox",
2002
- batch
2003
- };
2004
- const resourceBatch = parseEventMessages(context.attempt.messages);
2005
- if (resourceBatch.length > 0) return {
2006
- kind: "mailbox",
2007
- batch: resourceBatch
2008
- };
2009
- if (context.attempt.messages.length > 0) return;
2010
- const turnId = await getActiveMailboxTurnId(context.conversationId);
2011
- return turnId ? {
2012
- kind: "resume",
2013
- turnId
2014
- } : void 0;
2015
- }
2016
- // src/chat/review-items/prompt-input.ts
2017
- /**
2018
- * Prompt inputs for person changes to Review items. An answer or a dismiss
2019
- * is its own prompt content part, keyed by the item id that `addReviewItem`
2020
- * returned. The runtime builds it from the stored change record and the
2021
- * item, so the model never reads status prose. `policies/prompt-markers.md`
2022
- * owns the tags.
2023
- */
2024
- const ITEM_TEXT_MAX_LENGTH = 512;
2025
- function questionLine(item) {
2026
- const [label, text] = item.request ? ["Question", item.request.question.trim()] : ["Title", item.title.trim()];
2027
- return `${label}: ${text.length > ITEM_TEXT_MAX_LENGTH ? `${text.slice(0, 511)}…` : text}`;
2028
- }
2029
- function bodyLines(item, kind) {
2030
- return [questionLine(item), ...kind === "submitted" && item.request && item.answer ? [formatUserInputAnswer(item.request, item.answer)] : []];
2031
- }
2032
- function renderReviewItemInput(item, record) {
2033
- if (record.kind === "taken") return void 0;
2034
- const tag = record.kind === "submitted" ? "review-item-answer" : "review-item-dismissed";
2035
- return renderTag(tag, { id: item.id }, bodyLines(item, record.kind).map(escapeTagText));
2036
- }
2037
- /**
2038
- * Render the prompt input of a message that records a person change, or
2039
- * undefined when it has none. A message without an answer or dismiss, or
2040
- * whose item is gone, goes to the model as written.
2041
- */
2042
- async function loadReviewItemInput(record) {
2043
- if (!record || record.kind === "taken") return void 0;
2044
- const item = await getReviewItem(getDb(), record.reviewItemId);
2045
- return item ? renderReviewItemInput(item, record) : void 0;
2046
- }
2047
- /**
2048
- * Return the instruction of one saved input. `runtime` text, such as an
2049
- * Automation dispatch or an Event Turn, is already rendered as its tags.
2050
- * An answer or a dismiss is its Review item tag. Neither is typed text, so
2051
- * neither goes in `<current-instruction>`.
2052
- */
2053
- async function savedInputInstruction(args) {
2054
- const reviewItemInput = args.runtime ? void 0 : await loadReviewItemInput(args.reviewItemChange);
2055
- if (!args.runtime && !reviewItemInput) return { text: args.text };
2056
- return instructionForInputs([{
2057
- kind: "runtime",
2058
- text: reviewItemInput ?? args.text
2059
- }]);
2060
- }
2061
- /**
2062
- * Render the Review item input of each Event in a batch that records an
2063
- * answer or a dismiss, keyed by inbound message id. A Conversation with no
2064
- * web identity, such as a local CLI Conversation, gets the change as a
2065
- * system Event, but the input is the same as on web.
2066
- */
2067
- async function eventReviewItemInputs(messages) {
2068
- const rendered = await Promise.all(messages.map(async (message) => [message.inboundMessageId, await loadReviewItemInput(message.input.reviewItemChange)]));
2069
- return new Map(rendered.flatMap(([id, text]) => text ? [[id, text]] : []));
2070
- }
2071
- // src/chat/conversations/session-stop.ts
2072
- var session_stop_exports = /* @__PURE__ */ __exportAll({
2073
- getConversationStoppedAtMs: () => getConversationStoppedAtMs,
2074
- isWatchEvent: () => isWatchEvent,
2075
- markConversationsStopped: () => markConversationsStopped,
2076
- resumeStoppedConversationTree: () => resumeStoppedConversationTree,
2077
- skipInputAfterConversationStop: () => skipInputAfterConversationStop
2078
- });
2079
- /** Skip reason on the Message that saves Events for a stopped Conversation. */
2080
- const STOPPED_CONVERSATION_SKIP_REASON = "stopped conversation";
2081
- /**
2082
- * Stop each Conversation until a person sends it input or its parent gives
2083
- * it new work. With `cancelWatches`, an agent stopped them, so their Watches
2084
- * end first: a Watch delivers under its lock, so every Event of a cancelled
2085
- * Watch was received before the stop. A Conversation that already stopped
2086
- * later keeps that stop, so a retried or cascaded stop does not move it back.
2087
- */
2088
- async function markConversationsStopped(conversationIds, options) {
2089
- if (conversationIds.length === 0) return;
2090
- if (options.cancelWatches) for (const conversationId of conversationIds) await cancelSubscriptions({
2091
- conversationId,
2092
- state: options.state
2093
- });
2094
- const stoppedAt = new Date(options.nowMs ?? Date.now());
2095
- await getSqlExecutor().db().update(juniorConversations).set({
2096
- stoppedAt,
2097
- detailVersion: nextDetailVersion
2098
- }).where(and(inArray(juniorConversations.conversationId, [...conversationIds]), or(isNull(juniorConversations.stoppedAt), lt(juniorConversations.stoppedAt, stoppedAt))));
2099
- }
2100
- /** Return when a Conversation stopped, or undefined when it is not stopped. */
2101
- async function getConversationStoppedAtMs(conversationId) {
2102
- const [row] = await getSqlExecutor().db().select({ stoppedAt: juniorConversations.stoppedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
2103
- return row?.stoppedAt?.getTime();
2104
- }
2105
- /**
2106
- * End the stop of a Conversation and of the child agents below it, for new
2107
- * work sent at `sentAtMs`. Nothing changes for work sent at or before the
2108
- * stop, so the input that a stop drops does not undo it.
2109
- * Only Conversations that stopped no later than this Conversation change, so
2110
- * a later stop of one child agent stays in effect.
2111
- */
2112
- async function resumeStoppedConversationTree(conversationId, sentAtMs) {
2113
- const stoppedAtMs = await getConversationStoppedAtMs(conversationId);
2114
- if (stoppedAtMs === void 0 || sentAtMs <= stoppedAtMs) return;
2115
- await getSqlExecutor().db().update(juniorConversations).set({
2116
- stoppedAt: null,
2117
- detailVersion: nextDetailVersion
2118
- }).where(and(inArray(juniorConversations.conversationId, sql`(select ${conversationSubtreeColumns.conversationId} from ${conversationSubtree([conversationId])})`), lte(juniorConversations.stoppedAt, new Date(stoppedAtMs))));
2119
- }
2120
- /**
2121
- * Apply a session stop to automated input. Input from a person always runs.
2122
- * When a person sent it after the stop, the Conversation and its child agents
2123
- * stop no more. Input from a parent tool call also runs. While the
2124
- * Conversation is stopped, its Watch Events are saved as one Message and
2125
- * start no Turn, and other Events received at or before the stop are
2126
- * dropped. Returns the work to run, with only the Events that are left, or
2127
- * the finished result when nothing is left.
2128
- */
2129
- async function skipInputAfterConversationStop(context) {
2130
- const messages = context.attempt.messages;
2131
- const personInput = messages.filter((message) => isPersonInput(message.source));
2132
- if (personInput.length > 0) {
2133
- await resumeStoppedConversationTree(context.conversationId, Math.max(...personInput.map((message) => message.createdAtMs)));
2134
- return { context };
2135
- }
2136
- if (messages.length === 0 || !messages.every(isEventInput)) return { context };
2137
- const stoppedAtMs = await getConversationStoppedAtMs(context.conversationId);
2138
- if (stoppedAtMs === void 0) return { context };
2139
- const saved = messages.filter(isWatchEvent);
2140
- const live = messages.filter((message) => !isWatchEvent(message) && message.receivedAtMs > stoppedAtMs);
2141
- if (live.length > 0 && saved.length > 0) {
2142
- const delayMs = Math.max(getEventBatchDelayMs(messages), getEventBatchDelayMs(live));
2143
- if (delayMs > 0) return { skipped: {
2144
- status: "deferred",
2145
- delayMs
2146
- } };
2147
- }
2148
- if (saved.length > 0) await saveStoppedConversationEvents(context.conversationId, saved);
2149
- if (live.length === messages.length) return { context };
2150
- if (live.length > 0) return { context: {
2151
- ...context,
2152
- attempt: {
2153
- ...context.attempt,
2154
- messages: live
2155
- }
2156
- } };
2157
- await context.attempt.ack();
2158
- return { skipped: { status: "completed" } };
2159
- }
2160
- function isEventInput(message) {
2161
- return message.source === "event" && isEventMailboxMetadata(message.input.metadata);
2162
- }
2163
- /** Return whether a Watch delivered this input. Agent input has none. */
2164
- function isWatchEvent(message) {
2165
- const metadata = message.input.metadata;
2166
- return isEventMailboxMetadata(metadata) && metadata.event.subscriptionId !== void 0;
2167
- }
2168
- /**
2169
- * Save Events as the one Message that a Turn would save for them. The append
2170
- * is idempotent by Message id, so a retried batch saves nothing new. The
2171
- * Message takes the id of the first saved Event, so when an ack is lost and
2172
- * the retry carries more Events to save, the extra Events are deduplicated
2173
- * away.
2174
- */
2175
- async function saveStoppedConversationEvents(conversationId, messages) {
2176
- const first = messages[0];
2177
- const { text } = instructionForInputs(renderEventBatchInputs(messages, await eventReviewItemInputs(messages)).map((input) => ({
2178
- kind: "runtime",
2179
- text: input
2180
- })));
2181
- const stored = toStoredConversationMessage({
2182
- id: first.inboundMessageId,
2183
- role: "user",
2184
- text: normalizeConversationText(text),
2185
- createdAtMs: first.createdAtMs,
2186
- ...first.input.authorIdentityId ? { authorIdentityId: first.input.authorIdentityId } : void 0,
2187
- meta: {
2188
- replied: false,
2189
- skippedReason: STOPPED_CONVERSATION_SKIP_REASON,
2190
- ...eventBatchMessageMeta(messages)
2191
- }
2192
- });
2193
- const { createdAtMs, ...data } = stored;
2194
- await getConversationEventStore().append(conversationId, [{
2195
- idempotencyKey: `message:${stored.messageId}`,
2196
- createdAtMs,
2197
- data: {
2198
- type: "message",
2199
- ...data
2200
- }
2201
- }]);
2202
- }
2203
- export { withoutSavedSteeringMessages as $, requireSlackChannelMessageScope as A, maybePostAutomatedTurnLimitNotice as B, enqueueEventNotification as C, timerWatchCredentialSubject as D, renderEventBatchInputs as E, WORKSPACE_SNAPSHOT_FAILED_EVENT as F, admitAutomatedTurn as G, resolveSlackReplyTarget as H, WORKSPACE_SNAPSHOT_READY_EVENT as I, assemblePrompt as J, recordFinishedTurnForAutomatedLimit as K, workspaceSnapshotFinishedEvent as L, slackChannelMessageReplyThreadTs as M, slackChannelMessageRunsAutomation as N, getEventCatalog as O, slackChannelMessageTrigger as P, loadPromptTurnContext as Q, workspaceSnapshotWatch as R, EVENT_WAIT_MS as S, isEventMailboxMetadata as T, sendSlackReply as U, postAutomatedTurnLimitNoticeForConversation as V, renderSlackObjectCard as W, buildSteeringPiMessage as X, buildPromptInput as Y, instructionForInputs as Z, sourceFromTurnInput as _, session_stop_exports as a, addConversationNote as at, conversationSubtree as b, loadReviewItemInput as c, getAuthPausedConversationTurnId as d, readUserCustomization as et, getEventBatchDelayMs as f, resolveMailboxTurnWork as g, parseWebMessages as h, resumeStoppedConversationTree as i, setExperimentalFeatures as it, slackChannelMessageEvent as j, SLACK_EVENT_NAMESPACE as k, savedInputInstruction as l, parseEventMessages as m, isWatchEvent as n, getExperimentalFeatures as nt, skipInputAfterConversationStop as o, listActiveMailboxTurns as p, resetAutomatedTurnLimit as q, markConversationsStopped as r, isExperimentalFeatureEnabled as rt, eventReviewItemInputs as s, getConversationStoppedAtMs as t, saveUserCustomization as tt, getActiveConversationTurnId as u, turnInputFactsFromConversationMessage as v, eventBatchMessageMeta as w, conversationSubtreeColumns as x, legacyWebMailboxMetadataSchema as y, renderTaskInput as z };
1284
+ export { renderSlackObjectCard as C, resetAutomatedTurnLimit as E, sendSlackReply as S, recordFinishedTurnForAutomatedLimit as T, workspaceSnapshotWatch as _, renderEventBatchInputs as a, postAutomatedTurnLimitNoticeForConversation as b, SLACK_EVENT_NAMESPACE as c, slackChannelMessageReplyThreadTs as d, slackChannelMessageRunsAutomation as f, workspaceSnapshotFinishedEvent as g, WORKSPACE_SNAPSHOT_READY_EVENT as h, isEventMailboxMetadata as i, requireSlackChannelMessageScope as l, WORKSPACE_SNAPSHOT_FAILED_EVENT as m, enqueueEventNotification as n, timerWatchCredentialSubject as o, slackChannelMessageTrigger as p, eventBatchMessageMeta as r, getEventCatalog as s, EVENT_WAIT_MS as t, slackChannelMessageEvent as u, renderTaskInput as v, admitAutomatedTurn as w, resolveSlackReplyTarget as x, maybePostAutomatedTurnLimitNotice as y };