@sentry/junior 0.296.0 → 0.297.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-tmGIw4KS.js} +2 -2
  2. package/dist/{agent-runner-HoQiUKLL.js → agent-runner-CneTquAE.js} +378 -1919
  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-BJojZ7HL.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-BrP6ImrC.js} +1 -1
  12. package/dist/{background-compaction-queue-Cre1wFt9.js → background-compaction-queue-CwfJy3Cd.js} +4 -88
  13. package/dist/{briefs-BXECHduJ.js → briefs-uFTuhMqA.js} +3 -3
  14. package/dist/{catalog-runtime-CpCmlD9L.js → catalog-runtime-0kuQqYL4.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-Dj9M_nqB.js} +2 -2
  23. package/dist/{connections-B5pWh8e2.js → connections-B96JUM5o.js} +6 -6
  24. package/dist/{conversation-CMkSmi02.js → conversation-CvcBU1z2.js} +2 -16
  25. package/dist/{conversation-feed-BVAOga0H.js → conversation-feed-BSMlGZnS.js} +1 -1
  26. package/dist/{conversation-privacy-CZD5soDW.js → conversation-privacy-DI29jbZV.js} +1 -1
  27. package/dist/conversation-turn-CZWBr091.js +805 -0
  28. package/dist/{credential-sync-DwLkIvXI.js → credential-sync-Blhx4_xf.js} +14 -13
  29. package/dist/{db-C1M1y-bh.js → db-Br0tfAo7.js} +43 -15
  30. package/dist/{db-B3iyr_Or.d.ts → db-CrtyFRz7.d.ts} +13 -1
  31. package/dist/{executor-DUSEwXaO.js → executor-BMPipFVA.js} +14 -6
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{logging-D0svFM8r.js → logging-CQjlDQYX.js} +1 -1
  34. package/dist/{message-BFnIwKpx.js → message-BOZEIuxy.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-gusCgdQ6.js} +11 -930
  38. package/dist/{oauth-callback-server-BXRtD6Fk.js → oauth-callback-server-V_DuMuNX.js} +2 -2
  39. package/dist/{projection-B6VS7kbo.js → projection-B08mfi0u.js} +333 -106
  40. package/dist/{prompt-CD11tfG8.js → prompt-BlutWLNt.js} +4 -4
  41. package/dist/prompt-input-Dxn8cDC0.js +1424 -0
  42. package/dist/{registry-CHewwYEo.js → registry-BDWgCJDf.js} +1 -1
  43. package/dist/reporting-window-DopzcOHh.js +137 -0
  44. package/dist/{resolve-1owMH4qo.js → resolve-2Z_o_SsI.js} +3 -3
  45. package/dist/result-CAujiaci.js +463 -0
  46. package/dist/{runner-BtWvJslp.js → runner-D2Chc02N.js} +9 -8
  47. package/dist/{sandbox-egress-signals-ByftwJVt.js → sandbox-egress-signals-CFoJduFj.js} +1 -1
  48. package/dist/{schema-D2iGyYIp.js → schema-Bqa5NbcP.js} +11 -48
  49. package/dist/{schema-Ct1Zf2xy.d.ts → schema-Ce2XCS7O.d.ts} +8 -107
  50. package/dist/{service-account-DLoeoHww.js → service-account-C9kRQEb_.js} +3 -3
  51. package/dist/{service-account-BZEuMKdo.js → service-account-CERfXEVU.js} +3 -3
  52. package/dist/session-stop-B-I1rAS1.js +181 -0
  53. package/dist/{skills-DXgd5Inh.js → skills-B0m1nZ_j.js} +2 -2
  54. package/dist/{spawn-YeqlNDv8.js → spawn-CwMjRRtn.js} +6 -5
  55. package/dist/{state-C3CbtD_m.js → state-DFnmLmfn.js} +2 -2
  56. package/dist/{stop-Cze_pEL8.js → stop-BCH9VNGf.js} +63 -158
  57. package/dist/{store-CZ9vqR4P.js → store-B59rOYbS.js} +11 -4
  58. package/dist/{task-runner-CMiNGsER.js → store-m5bmdmsP.js} +939 -1593
  59. package/dist/task-queue-N0kuCknH.js +89 -0
  60. package/dist/task-runner-COOwR8qm.js +291 -0
  61. package/dist/thread-context-Cd44z_W5.js +248 -0
  62. package/dist/turn-cancel-DDu8TOwt.js +201 -0
  63. package/dist/turn-session-routing-BlCtVFRN.js +380 -0
  64. package/dist/{turn-failure-response-pXhZ2wMK.js → turn-user-message-ygLG3ylQ.js} +183 -361
  65. package/dist/turn-wake-DmQec4AG.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-Ba2OcUse.js} +1 -1
  68. package/dist/{version-EN3Wnq-R.js → version-KNDzIAh6.js} +1 -1
  69. package/dist/version.js +1 -1
  70. package/dist/{viewer-Agxi_o5c.js → viewer-BPpuN2f9.js} +3 -3
  71. package/dist/warmup-Bskrwmk1.js +2697 -0
  72. package/dist/{worker-BALVdWbv.js → worker-B1skZlit.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
@@ -0,0 +1,89 @@
1
+ import { h as logWarn } from "./logging-CQjlDQYX.js";
2
+ import { C as queueCallback, S as verifyQueueMessage, T as getQueueProvider, b as QUEUE_SIGNATURE_MAX_AGE_MS, x as signQueueMessage } from "./background-compaction-queue-CwfJy3Cd.js";
3
+ import { createHash } from "node:crypto";
4
+ import * as z from "zod";
5
+ // src/chat/plugins/task-queue.ts
6
+ /**
7
+ * Delivery for plugin-registered tasks.
8
+ *
9
+ * Plugins register named tasks. This module owns the shared signed message,
10
+ * send path, and HTTP/local callback. Core keeps one topic and one runner.
11
+ */
12
+ /** Deploy topic name. Keep stable for Vercel queue wiring. */
13
+ const PLUGIN_TASK_QUEUE_TOPIC = "junior_plugin_tasks";
14
+ const PLUGIN_TASK_DEV_CONSUMER_GROUP = "junior_plugin_tasks_dev";
15
+ const PLUGIN_TASK_MAX_DELIVERIES = 5;
16
+ const PLUGIN_TASK_SIGN_CONTEXT = "junior.plugin_task_queue.v1";
17
+ const PLUGIN_TASK_SIGN_VERSION = "v1";
18
+ const pluginTaskParamsSchema = z.object({
19
+ conversationId: z.string().min(1),
20
+ sessionId: z.string().min(1)
21
+ }).strict();
22
+ const pluginTaskSign = {
23
+ context: PLUGIN_TASK_SIGN_CONTEXT,
24
+ schema: z.object({
25
+ name: z.string().min(1),
26
+ params: pluginTaskParamsSchema,
27
+ plugin: z.string().min(1)
28
+ }).strict(),
29
+ signatureVersion: PLUGIN_TASK_SIGN_VERSION,
30
+ parts: (message) => [
31
+ message.plugin,
32
+ message.name,
33
+ message.params.conversationId,
34
+ message.params.sessionId
35
+ ]
36
+ };
37
+ /** Build the stable id used for delivery dedupe and tracing. */
38
+ function pluginTaskId(args) {
39
+ return `plugin-task_${createHash("sha256").update(args.plugin).update("\0").update(args.name).update("\0").update(args.params.conversationId).update("\0").update(args.params.sessionId).digest("hex").slice(0, 32)}`;
40
+ }
41
+ /** Sign a plugin task message for tests and local checks. */
42
+ function signPluginTaskQueueMessage(message, nowMs = Date.now()) {
43
+ return signQueueMessage(pluginTaskSign, message, nowMs);
44
+ }
45
+ function verifyPluginTaskQueueMessage(value, nowMs = Date.now()) {
46
+ return verifyQueueMessage(pluginTaskSign, value, nowMs);
47
+ }
48
+ function logPluginTaskQueueMessageRejected(reason, metadata) {
49
+ logWarn("plugin.task.queue_message.rejected", {
50
+ "app.queue.consumer_group": metadata.consumerGroup,
51
+ "app.queue.delivery_count": metadata.deliveryCount,
52
+ "app.queue.message_id": metadata.messageId,
53
+ "app.queue.reject_reason": reason,
54
+ "app.queue.topic_name": metadata.topicName
55
+ });
56
+ }
57
+ function pluginTaskCallback() {
58
+ return queueCallback({
59
+ consumerGroup: PLUGIN_TASK_DEV_CONSUMER_GROUP,
60
+ maxDeliveries: PLUGIN_TASK_MAX_DELIVERIES,
61
+ onRejected: logPluginTaskQueueMessageRejected,
62
+ run: async (message) => {
63
+ const { processPluginTask } = await import("./task-runner-COOwR8qm.js").then((n) => n.r);
64
+ await processPluginTask(message);
65
+ },
66
+ topic: PLUGIN_TASK_QUEUE_TOPIC,
67
+ verify: verifyPluginTaskQueueMessage
68
+ });
69
+ }
70
+ /** Send one plugin task through the shared signed delivery path. */
71
+ async function sendVercelPluginTask(message) {
72
+ await getQueueProvider().send(PLUGIN_TASK_QUEUE_TOPIC, signPluginTaskQueueMessage(message), {
73
+ idempotencyKey: pluginTaskId(message),
74
+ retentionSeconds: QUEUE_SIGNATURE_MAX_AGE_MS / 1e3
75
+ });
76
+ }
77
+ /** Create the HTTP callback for plugin tasks. */
78
+ function createVercelPluginTaskCallback() {
79
+ return pluginTaskCallback().create();
80
+ }
81
+ /** Return the queue consumer for plugin tasks, for a pulling queue worker. */
82
+ function pluginTaskQueueConsumer() {
83
+ return pluginTaskCallback().consumer;
84
+ }
85
+ /** Register the local-dev consumer for plugin tasks. */
86
+ function registerVercelPluginTaskDevConsumer() {
87
+ return pluginTaskCallback().registerDev();
88
+ }
89
+ export { pluginTaskQueueConsumer as a, pluginTaskParamsSchema as i, createVercelPluginTaskCallback as n, registerVercelPluginTaskDevConsumer as o, pluginTaskId as r, sendVercelPluginTask as s, PLUGIN_TASK_QUEUE_TOPIC as t };
@@ -0,0 +1,291 @@
1
+ import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
+ import { $a as createPluginModel, Co as createPluginConversationEvents, Di as createPluginState, Dn as normalizeToolNameFromResult, En as isToolResultMessage, Qa as createPluginEmbedder, Tn as isToolResultError, Zo as createPluginCache, ar as coreTaskRegistrations, do as createPluginModelCostRecorder, fo as createPluginLogger, gn as getPiMessageRole, kn as stripRuntimeTurnContext, nr as getPlugins, ot as getTurnRecord, v as hydrateConversationMessages, xn as instructionTextForProjection } from "./projection-B08mfi0u.js";
3
+ import { E as withSpan } from "./logging-CQjlDQYX.js";
4
+ import { h as parseSlackMessageTs } from "./actor-6jsm_v96.js";
5
+ import { a as getConversationStore, o as getDb } from "./db-Br0tfAo7.js";
6
+ import { v as sameActorIdentity } from "./media-BepyEUNm.js";
7
+ import { i as readActorIdentity } from "./viewer-BPpuN2f9.js";
8
+ import { a as getStateAdapter } from "./state-DFnmLmfn.js";
9
+ import { a as getPersistedThreadState, c as coerceThreadConversationState, t as resolveConversationRouting } from "./turn-session-routing-BlCtVFRN.js";
10
+ import { c as getDispatchRecord } from "./store-m5bmdmsP.js";
11
+ import { i as pluginTaskParamsSchema, r as pluginTaskId, s as sendVercelPluginTask } from "./task-queue-N0kuCknH.js";
12
+ import { pluginRunContextSchema } from "@sentry/junior-plugin-api";
13
+ // src/chat/plugins/task-runner.ts
14
+ /**
15
+ * Plugin background-task orchestration.
16
+ *
17
+ * Core schedules tasks from completed sessions and exposes plugins only a
18
+ * bounded run projection rather than live runtime internals or queue
19
+ * payloads.
20
+ */
21
+ var task_runner_exports = /* @__PURE__ */ __exportAll({
22
+ processPluginTask: () => processPluginTask,
23
+ scheduleSessionCompletedPluginTasks: () => scheduleSessionCompletedPluginTasks
24
+ });
25
+ const PLUGIN_TASK_LOCK_TTL_MS = 3e5;
26
+ function isRecord(value) {
27
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
28
+ }
29
+ function textPart(value) {
30
+ if (isRecord(value) && value.type === "text" && typeof value.text === "string") return value.text;
31
+ }
32
+ function messageText(message) {
33
+ const content = message.content;
34
+ if (typeof content === "string") return sanitizeText(content);
35
+ if (!Array.isArray(content)) return "";
36
+ return sanitizeText(content.map(textPart).filter(Boolean).join("\n"));
37
+ }
38
+ function toolResultText(message) {
39
+ const record = message;
40
+ return sanitizeText([
41
+ messageText(message),
42
+ record.output,
43
+ record.result,
44
+ record.stdout,
45
+ record.stderr,
46
+ record.toolResult
47
+ ].filter((value) => typeof value === "string" && value.length > 0).join("\n"));
48
+ }
49
+ function sanitizeText(text) {
50
+ return text.replace(/<data_base64>[\s\S]*?<\/data_base64>/g, "<data_base64>[omitted]</data_base64>").replace(/data:image\/[a-z0-9.+-]+;base64,[a-z0-9+/=]+/gi, "[image data omitted]").replaceAll("\0", " ").trim();
51
+ }
52
+ /** Build the transcript provenance for a user message from its Pi provenance. */
53
+ function messageProvenance(provenance) {
54
+ return {
55
+ authority: provenance.authority,
56
+ ...provenance.actor ? { actor: provenance.actor } : void 0
57
+ };
58
+ }
59
+ function runTranscriptEntry(message, provenance, runActor) {
60
+ const role = getPiMessageRole(message);
61
+ if (role === "user" || role === "assistant") {
62
+ const text = role === "user" ? instructionTextForProjection(messageText(message)) : messageText(message);
63
+ if (!text) return;
64
+ if (role === "assistant") return {
65
+ type: "message",
66
+ role,
67
+ text
68
+ };
69
+ return {
70
+ type: "message",
71
+ role,
72
+ text,
73
+ provenance: messageProvenance(provenance),
74
+ isRunActor: sameActorIdentity(provenance.actor, runActor)
75
+ };
76
+ }
77
+ if (!isToolResultMessage(message)) return;
78
+ const toolName = normalizeToolNameFromResult(message);
79
+ if (!toolName) return;
80
+ const text = toolResultText(message);
81
+ return {
82
+ type: "toolResult",
83
+ toolName,
84
+ isError: isToolResultError(message),
85
+ ...text ? { text } : void 0
86
+ };
87
+ }
88
+ /**
89
+ * Slice the current turn's Pi messages with their aligned provenance and strip
90
+ * runtime turn context, keeping each surviving message paired with the exact
91
+ * provenance recorded for it. Stripping can drop or rewrite messages, so the
92
+ * pairing is applied per message rather than by post-strip index.
93
+ */
94
+ function turnMessagesWithProvenance(record) {
95
+ const startIndex = record.turnStartMessageIndex ?? 0;
96
+ const messages = record.piMessages.slice(startIndex);
97
+ const provenance = record.piMessageProvenance.slice(startIndex);
98
+ const paired = [];
99
+ for (const [index, message] of messages.entries()) for (const stripped of stripRuntimeTurnContext([message])) paired.push({
100
+ message: stripped,
101
+ provenance: provenance[index] ?? { authority: "context" }
102
+ });
103
+ return paired;
104
+ }
105
+ /** Recover the Slack context author identity from a persisted thread message. */
106
+ function slackContextAuthor(location, message) {
107
+ const userId = message.author?.userId?.trim();
108
+ if (!userId) return;
109
+ return {
110
+ platform: "slack",
111
+ teamId: location.teamId,
112
+ userId,
113
+ ...message.author?.userName ? { userName: message.author.userName } : void 0,
114
+ ...message.author?.fullName ? { fullName: message.author.fullName } : void 0
115
+ };
116
+ }
117
+ function slackTimestampMs(value) {
118
+ const timestamp = parseSlackMessageTs(value);
119
+ if (!timestamp) return;
120
+ const timestampMs = Number(timestamp) * 1e3;
121
+ return Number.isFinite(timestampMs) ? timestampMs : void 0;
122
+ }
123
+ function conversationMessageTimestampMs(message) {
124
+ if (message.meta?.slackTs !== void 0) return slackTimestampMs(message.meta.slackTs);
125
+ return Number.isFinite(message.createdAtMs) ? message.createdAtMs : void 0;
126
+ }
127
+ function messageExistedAtRunCompletion(message, completedAtMs) {
128
+ const messageTimestampMs = conversationMessageTimestampMs(message);
129
+ return messageTimestampMs !== void 0 && messageTimestampMs <= completedAtMs;
130
+ }
131
+ /**
132
+ * Project bounded public-thread context into the run transcript.
133
+ *
134
+ * Prior public Slack messages from the current Conversation are durable
135
+ * evidence a completed run may have acted on, so passive consumers can cite
136
+ * them. They are always context authority (never instruction), and private or
137
+ * local Conversations add nothing here.
138
+ */
139
+ async function loadConversationContextTranscriptEntries(record, location, visibility, runActor) {
140
+ if (location?.provider !== "slack" || visibility !== "public") return [];
141
+ const state = await getPersistedThreadState(record.conversationId);
142
+ const conversation = coerceThreadConversationState(state);
143
+ await hydrateConversationMessages({
144
+ conversation,
145
+ conversationId: record.conversationId
146
+ });
147
+ const entries = [];
148
+ for (const message of conversation.messages) {
149
+ if (message.role !== "user") continue;
150
+ if (!messageExistedAtRunCompletion(message, record.updatedAtMs)) continue;
151
+ const text = sanitizeText(message.text);
152
+ if (!text) continue;
153
+ const author = slackContextAuthor(location, message);
154
+ entries.push({
155
+ type: "message",
156
+ role: "user",
157
+ text,
158
+ provenance: {
159
+ authority: "context",
160
+ ...author ? { actor: author } : void 0
161
+ },
162
+ isRunActor: sameActorIdentity(author, runActor)
163
+ });
164
+ }
165
+ return entries;
166
+ }
167
+ async function withPluginTaskLock(taskId, callback) {
168
+ const state = getStateAdapter();
169
+ await state.connect();
170
+ const lock = await state.acquireLock(`plugin:task:${taskId}`, PLUGIN_TASK_LOCK_TTL_MS);
171
+ if (!lock) throw new Error(`Could not acquire plugin task lock for ${taskId}`);
172
+ try {
173
+ return await callback();
174
+ } finally {
175
+ await state.releaseLock(lock);
176
+ }
177
+ }
178
+ /** Load the bounded completed-run projection exposed to plugin tasks. */
179
+ async function loadPluginRun(params) {
180
+ const record = await getTurnRecord(params.conversationId, params.sessionId);
181
+ if (!record) throw new Error("Completed plugin task session record is unavailable");
182
+ if (record.state !== "completed") throw new Error("Completed plugin task session record is not completed");
183
+ const conversationStore = getConversationStore();
184
+ const routing = await resolveConversationRouting({
185
+ conversationId: params.conversationId,
186
+ conversationStore
187
+ });
188
+ if (!routing) throw new Error(`Conversation ${params.conversationId} is missing durable routing metadata`);
189
+ const source = record.source ?? routing.source;
190
+ if (!source) throw new Error("Completed plugin task session record is missing Source");
191
+ const conversation = await conversationStore.get({ conversationId: params.conversationId });
192
+ const runActor = record.actor ?? record.actors[0] ?? (record.dispatchId ? (await getDispatchRecord(record.dispatchId))?.actor : void 0);
193
+ const actorUser = runActor ? (await readActorIdentity(runActor))?.user : void 0;
194
+ const runEntries = turnMessagesWithProvenance(record).map(({ message, provenance }) => runTranscriptEntry(message, provenance, runActor)).filter((entry) => Boolean(entry));
195
+ const runMessageTexts = new Set(runEntries.filter((entry) => entry.type === "message").map((entry) => entry.text));
196
+ const contextEntries = (await loadConversationContextTranscriptEntries(record, conversation?.location, conversation?.visibility, runActor)).filter((entry) => entry.type !== "message" || !runMessageTexts.has(entry.text));
197
+ return pluginRunContextSchema.parse({
198
+ ...actorUser ? { actorUserId: actorUser.id } : void 0,
199
+ completedAtMs: record.updatedAtMs,
200
+ conversationId: record.conversationId,
201
+ destination: routing.destination,
202
+ ...routing.location ? { locationId: routing.location.id } : void 0,
203
+ actors: record.actors,
204
+ ...runActor ? { actor: runActor } : void 0,
205
+ runId: record.turnId,
206
+ source,
207
+ transcript: [...contextEntries, ...runEntries]
208
+ });
209
+ }
210
+ /** Build the plugin-facing context for one claimed task attempt. */
211
+ function taskPluginContext(plugin, message, options = {}) {
212
+ const pluginName = plugin.manifest.name;
213
+ const sessionParams = pluginTaskParamsSchema.parse(message.params);
214
+ const onCost = createPluginModelCostRecorder({
215
+ conversationId: sessionParams.conversationId,
216
+ pluginName,
217
+ source: "task",
218
+ turnId: sessionParams.sessionId
219
+ });
220
+ return {
221
+ db: getDb(),
222
+ embedder: createPluginEmbedder(pluginName, {
223
+ onCost,
224
+ signal: options.signal
225
+ }),
226
+ events: createPluginConversationEvents({
227
+ conversationId: sessionParams.conversationId,
228
+ operationId: pluginTaskId(message),
229
+ plugin,
230
+ turnId: sessionParams.sessionId
231
+ }),
232
+ id: pluginTaskId(message),
233
+ log: createPluginLogger(pluginName),
234
+ model: createPluginModel(pluginName, plugin.model, {
235
+ onCost,
236
+ signal: options.signal
237
+ }),
238
+ name: message.name,
239
+ plugin: { name: pluginName },
240
+ cache: createPluginCache(pluginName),
241
+ run: { async load() {
242
+ return await loadPluginRun(sessionParams);
243
+ } },
244
+ state: createPluginState(pluginName)
245
+ };
246
+ }
247
+ function findPluginTask(message) {
248
+ const plugin = [...coreTaskRegistrations(), ...getPlugins()].find((candidate) => candidate.manifest.name === message.plugin);
249
+ if (!plugin?.tasks || !Object.hasOwn(plugin.tasks, message.name)) return;
250
+ return {
251
+ plugin,
252
+ task: plugin.tasks[message.name]
253
+ };
254
+ }
255
+ /** Schedule all plugin tasks interested in a completed agent-run session. */
256
+ async function scheduleSessionCompletedPluginTasks(params, options = {}) {
257
+ const coreParams = pluginTaskParamsSchema.parse(params);
258
+ const taskRegistrations = [...getPlugins(), ...coreTaskRegistrations()].flatMap((plugin) => Object.keys(plugin.tasks ?? {}).map((name) => ({
259
+ name,
260
+ plugin
261
+ })));
262
+ if (taskRegistrations.length === 0) return;
263
+ const record = await getTurnRecord(coreParams.conversationId, coreParams.sessionId);
264
+ if (!record || record.state !== "completed") throw new Error("Completed plugin task session record is not ready");
265
+ const send = options.send ?? sendVercelPluginTask;
266
+ const messages = taskRegistrations.map(({ name, plugin }) => ({
267
+ name,
268
+ params: coreParams,
269
+ plugin: plugin.manifest.name
270
+ }));
271
+ await Promise.all(messages.map(async (message) => {
272
+ await send(message);
273
+ }));
274
+ }
275
+ /**
276
+ * Execute one parsed plugin task request in a `plugin.task` span. The span
277
+ * includes the lock wait, because both delay the work that runs the task.
278
+ */
279
+ async function processPluginTask(message, options = {}) {
280
+ const params = pluginTaskParamsSchema.parse(message.params);
281
+ await withSpan(`plugin.task ${message.plugin}.${message.name}`, "plugin.task", { conversationId: params.conversationId }, () => withPluginTaskLock(pluginTaskId(message), async () => {
282
+ const resolved = findPluginTask(message);
283
+ if (!resolved?.task) throw new Error(`Plugin task "${message.plugin}.${message.name}" is not registered`);
284
+ await resolved.task.run(taskPluginContext(resolved.plugin, message, options));
285
+ }), {
286
+ "app.ai.turn.session_id": params.sessionId,
287
+ "app.plugin.name": message.plugin,
288
+ "app.plugin.task": message.name
289
+ });
290
+ }
291
+ export { scheduleSessionCompletedPluginTasks as n, task_runner_exports as r, processPluginTask as t };
@@ -0,0 +1,248 @@
1
+ import { E as buildConversationContext, Uo as listConversationAnnotations, X as clearPendingAuth, j as markConversationMessage, v as hydrateConversationMessages } from "./projection-B08mfi0u.js";
2
+ import { H as findProviderError, U as getProviderErrorAttributes, W as getProviderErrorUserMessage, z as ProviderError } from "./config-Dj9M_nqB.js";
3
+ import { G as isRecord, b as setSpanAttributes, t as buildTurnFailureResponse } from "./logging-CQjlDQYX.js";
4
+ import { o as getDb, r as getConversationEventStore } from "./db-Br0tfAo7.js";
5
+ import { I as readMessageCardRefs, L as removedCardSchema, R as resolveMessageCards } from "./conversation-CvcBU1z2.js";
6
+ import { dt as parseAgentReplyMessageId, ft as parseTurnReplyMessageId, m as markTurnCompleted, n as getTurnUserMessageId, p as markTurnClosed, rt as getAgentInvocationTurnId, ut as parseAgentInvocationResultMessageId, w as getAgentInvocation } from "./turn-user-message-ygLG3ylQ.js";
7
+ import { a as getPersistedThreadState, c as coerceThreadConversationState, s as persistThreadStateById } from "./turn-session-routing-BlCtVFRN.js";
8
+ // src/chat/conversations/pending-cards.ts
9
+ /**
10
+ * Add the cards that tool results selected since the last visible assistant
11
+ * Message or Turn start, scanning back from `beforeSeq`. Returns the input
12
+ * message ids of the Turn start that ended the scan.
13
+ */
14
+ async function selectTurnCards(conversationId, selection, beforeSeq) {
15
+ while (true) {
16
+ const page = await getConversationEventStore().query(conversationId, {
17
+ beforeSeq,
18
+ limit: 100,
19
+ types: [
20
+ "tool_result",
21
+ "message",
22
+ "turn_started"
23
+ ]
24
+ });
25
+ for (const event of [...page.events].reverse()) {
26
+ const data = event.data;
27
+ if (data.type === "turn_started") return data.inputMessageIds;
28
+ if (data.type === "message" && data.role === "assistant") return [];
29
+ if (data.type !== "tool_result" || data.isError || typeof data.toolName !== "string" || !isRecord(data.details)) continue;
30
+ if (data.details.timed_out === true) continue;
31
+ if (Array.isArray(data.details.removedCards)) for (const ref of removedCardSchema.array().parse(data.details.removedCards)) selection.deleted.add(JSON.stringify([ref.plugin, ref.key]));
32
+ for (const card of readMessageCardRefs(data.details)) {
33
+ const key = JSON.stringify([card.plugin, card.key]);
34
+ if (!selection.deleted.has(key) && !selection.cards.has(key)) selection.cards.set(key, card);
35
+ }
36
+ }
37
+ if (!page.hasOlder || page.events.length === 0) return [];
38
+ beforeSeq = page.events[0].seq;
39
+ }
40
+ }
41
+ /**
42
+ * Add the cards of child agents whose replies or results started this Turn.
43
+ * A child cannot reply to people, so its parent's reply delivers its cards.
44
+ */
45
+ async function selectChildResultCards(inputMessageIds, selection) {
46
+ const events = getConversationEventStore();
47
+ for (const messageId of [...inputMessageIds].reverse()) {
48
+ const replyInvocationId = parseAgentReplyMessageId(messageId);
49
+ const invocationId = replyInvocationId ?? parseAgentInvocationResultMessageId(messageId);
50
+ const invocation = invocationId ? await getAgentInvocation(invocationId) : void 0;
51
+ if (!invocation) continue;
52
+ const turnId = parseTurnReplyMessageId(messageId) ?? getAgentInvocationTurnId(invocation.invocationId);
53
+ const terminal = await events.loadByIdempotencyKey(invocation.childConversationId, `turn:${turnId}:terminal`);
54
+ if (!terminal && !replyInvocationId) continue;
55
+ await selectTurnCards(invocation.childConversationId, selection, terminal?.seq);
56
+ }
57
+ }
58
+ /** Select undelivered cards and load their latest saved facts. */
59
+ async function loadPendingMessageCards(conversationId) {
60
+ const selection = {
61
+ cards: /* @__PURE__ */ new Map(),
62
+ deleted: /* @__PURE__ */ new Set()
63
+ };
64
+ await selectChildResultCards(await selectTurnCards(conversationId, selection), selection);
65
+ if (selection.cards.size === 0) return [];
66
+ return resolveMessageCards([...selection.cards.values()].reverse(), await listConversationAnnotations(getDb(), conversationId));
67
+ }
68
+ // src/chat/runtime/delivered-turn-state.ts
69
+ /** Build state after destination delivery or intentional no-reply completion. */
70
+ function buildDeliveredTurnStatePatch(args) {
71
+ const conversation = structuredClone(args.conversation);
72
+ clearPendingAuth(conversation, args.sessionId);
73
+ markConversationMessage(conversation, args.userMessageId, {
74
+ replied: true,
75
+ skippedReason: void 0
76
+ });
77
+ markTurnCompleted({
78
+ conversation,
79
+ nowMs: Date.now(),
80
+ sessionId: args.sessionId
81
+ });
82
+ return {
83
+ conversation,
84
+ sandboxRef: args.reply.sandboxRef
85
+ };
86
+ }
87
+ // src/chat/runtime/auth-pause-state.ts
88
+ /** Mark an auth-paused turn complete after private authorization link delivery. */
89
+ function completeAuthPauseTurn(args) {
90
+ markConversationMessage(args.conversation, getTurnUserMessageId(args.conversation, args.sessionId), {
91
+ replied: true,
92
+ skippedReason: void 0
93
+ });
94
+ markTurnClosed({
95
+ conversation: args.conversation,
96
+ nowMs: Date.now(),
97
+ sessionId: args.sessionId
98
+ });
99
+ }
100
+ /** Reload thread state, mark the auth pause as parked, and persist it. */
101
+ async function persistAuthPauseTurnState(args) {
102
+ const currentState = await getPersistedThreadState(args.threadStateId);
103
+ const conversation = coerceThreadConversationState(currentState);
104
+ await hydrateConversationMessages({
105
+ conversation,
106
+ conversationId: args.threadStateId
107
+ });
108
+ completeAuthPauseTurn({
109
+ conversation,
110
+ sessionId: args.sessionId
111
+ });
112
+ await persistThreadStateById(args.threadStateId, { conversation });
113
+ }
114
+ // src/chat/interruption-marker.ts
115
+ const INTERRUPTED_MARKER = "\n\n[Response interrupted before completion]";
116
+ /** Return the marker added when a visible reply ended mid-execution. */
117
+ function getInterruptionMarker() {
118
+ return INTERRUPTED_MARKER;
119
+ }
120
+ // src/chat/services/turn-failure-response.ts
121
+ /** Require captured turn failures to carry a real Sentry event reference. */
122
+ function requireTurnFailureEventId(eventId, eventName) {
123
+ if (!eventId) throw new Error(`Sentry did not return an event ID for ${eventName}`);
124
+ return eventId;
125
+ }
126
+ function getExecutionFailureReason(reply) {
127
+ const errorMessage = reply.diagnostics.errorMessage?.trim();
128
+ if (errorMessage) return errorMessage;
129
+ if (reply.diagnostics.toolErrorCount > 0) return `${reply.diagnostics.toolErrorCount} tool result error(s)`;
130
+ if (reply.diagnostics.assistantMessageCount > 0) return "assistant returned no text";
131
+ return "empty assistant turn";
132
+ }
133
+ /** Return a fixed reason label for a failed model turn. */
134
+ function getTurnFailureReason(reply) {
135
+ if (reply.diagnostics.outcome === "success") return;
136
+ if (reply.diagnostics.outcome === "provider_error") return findProviderError(reply.diagnostics.providerError)?.kind ?? "unknown";
137
+ if (reply.diagnostics.toolErrorCount > 0) return "tool_errors";
138
+ if (reply.diagnostics.usedPrimaryText && reply.diagnostics.assistantMessageCount > 0) return "suppressed_output";
139
+ return "empty_output";
140
+ }
141
+ function getFailureCapture(reply) {
142
+ if (reply.diagnostics.outcome === "provider_error") {
143
+ const providerError = findProviderError(reply.diagnostics.providerError);
144
+ return {
145
+ eventName: "agent.turn.provider_error",
146
+ error: reply.diagnostics.providerError ?? new Error(reply.diagnostics.errorMessage ?? "Provider error without explicit message"),
147
+ attributes: providerError ? getProviderErrorAttributes(providerError) : {},
148
+ body: "Agent turn failed with provider error"
149
+ };
150
+ }
151
+ const failureReason = getExecutionFailureReason(reply);
152
+ return {
153
+ eventName: "agent.turn.execution.failed",
154
+ error: /* @__PURE__ */ new Error(`Agent turn execution failure: ${failureReason}`),
155
+ attributes: { "app.ai.execution_failure_reason": failureReason },
156
+ body: "Agent turn completed with execution failure"
157
+ };
158
+ }
159
+ /** Keep failed-turn Sentry captures and completion spans on the same keys. */
160
+ function getAgentTurnDiagnosticsAttributes(reply) {
161
+ return {
162
+ "app.ai.outcome": reply.diagnostics.outcome,
163
+ "app.ai.assistant_messages": reply.diagnostics.assistantMessageCount,
164
+ "app.ai.tool_results": reply.diagnostics.toolResultCount,
165
+ "app.ai.tool_error_results": reply.diagnostics.toolErrorCount,
166
+ "app.ai.tool_call_count": reply.diagnostics.toolCalls.length,
167
+ "app.ai.used_primary_text": reply.diagnostics.usedPrimaryText,
168
+ ...reply.diagnostics.reasoningLevel ? { "gen_ai.request.reasoning.level": reply.diagnostics.reasoningLevel } : void 0,
169
+ ...reply.diagnostics.stopReason ? { "gen_ai.response.finish_reasons": [reply.diagnostics.stopReason] } : void 0,
170
+ ...reply.diagnostics.errorMessage && reply.diagnostics.outcome !== "provider_error" ? { "exception.message": reply.diagnostics.errorMessage } : void 0
171
+ };
172
+ }
173
+ /** Enforce one captured failure response and return its structured correlation. */
174
+ function finalizeFailedTurnReplyWithEvent(args) {
175
+ if (args.reply.diagnostics.outcome === "success") return { reply: args.reply };
176
+ const failureReason = getTurnFailureReason(args.reply);
177
+ const capture = getFailureCapture(args.reply);
178
+ const eventId = requireTurnFailureEventId(args.logException(capture.error, capture.eventName, {
179
+ ...getAgentTurnDiagnosticsAttributes(args.reply),
180
+ ...args.attributes,
181
+ ...capture.attributes,
182
+ ...failureReason ? { "app.ai.failure_reason": failureReason } : void 0
183
+ }), capture.eventName);
184
+ const providerPartialText = args.reply.diagnostics.outcome === "provider_error" && args.reply.diagnostics.assistantMessageCount > 0 ? args.reply.text.trim() : "";
185
+ const providerUserMessage = args.reply.diagnostics.providerError instanceof ProviderError ? getProviderErrorUserMessage(args.reply.diagnostics.providerError) : "";
186
+ const failureText = providerUserMessage ? `${providerUserMessage} Reference: \`event_id=${eventId}\`.` : buildTurnFailureResponse(eventId);
187
+ return {
188
+ eventId,
189
+ ...failureReason ? { failureReason } : void 0,
190
+ reply: {
191
+ ...args.reply,
192
+ text: providerPartialText ? `${providerPartialText}${getInterruptionMarker()}` : failureText
193
+ }
194
+ };
195
+ }
196
+ // src/chat/conversations/thread-context.ts
197
+ const CURSOR_TURN_LOOKBACK = 10;
198
+ async function loadThreadContextCursor(args) {
199
+ const store = getConversationEventStore();
200
+ const [started, completed] = await Promise.all([store.query(args.conversationId, {
201
+ limit: CURSOR_TURN_LOOKBACK,
202
+ types: ["turn_started"]
203
+ }), store.query(args.conversationId, {
204
+ limit: CURSOR_TURN_LOOKBACK,
205
+ types: ["turn_completed"]
206
+ })]);
207
+ const finished = new Set(completed.events.flatMap((event) => event.data.type === "turn_completed" && event.data.outcome !== "cancelled" ? [event.data.turnId] : []));
208
+ const previous = [...started.events].reverse().find((event) => event.data.type === "turn_started" && event.data.turnId !== args.turnId && finished.has(event.data.turnId));
209
+ return previous?.data.type === "turn_started" ? previous.data.threadContextThroughSeq : void 0;
210
+ }
211
+ /**
212
+ * Return the oldest cursor of the Turns that the cursor lookup reads. Messages
213
+ * after it may still be in the thread context delta of the next Turn, also
214
+ * when the latest Turns failed or the next Turn retries.
215
+ */
216
+ async function loadThreadContextTrimFloor(conversationId) {
217
+ const cursors = (await getConversationEventStore().query(conversationId, {
218
+ limit: CURSOR_TURN_LOOKBACK,
219
+ types: ["turn_started"]
220
+ })).events.flatMap((event) => event.data.type === "turn_started" && event.data.threadContextThroughSeq !== void 0 ? [event.data.threadContextThroughSeq] : []);
221
+ return cursors.length > 0 ? Math.min(...cursors) : void 0;
222
+ }
223
+ /**
224
+ * Build the thread context of one Turn prompt. With agent history, show only
225
+ * the thread Messages saved after the cursor of the previous Turn.
226
+ *
227
+ * Sets `app.thread_context.*` on the active span: `chat.reply` in a Slack
228
+ * Turn, `chat.turn` in a web or Event Turn. Cursor `missing` means that the
229
+ * previous Turn ran before cursors existed.
230
+ */
231
+ async function buildTurnThreadContext(args) {
232
+ const afterSeq = args.hasHistory ? await loadThreadContextCursor({
233
+ conversationId: args.conversationId,
234
+ turnId: args.turnId
235
+ }) : void 0;
236
+ const block = buildConversationContext(args.conversation, {
237
+ excludeMessageIds: args.excludeMessageIds,
238
+ ...args.hasHistory ? { history: { afterSeq } } : void 0
239
+ });
240
+ setSpanAttributes({
241
+ "app.thread_context.chars": block.text?.length ?? 0,
242
+ "app.thread_context.shown_messages": block.shownMessages,
243
+ "app.thread_context.omitted_messages": block.omittedMessages,
244
+ "app.thread_context.cursor": !args.hasHistory ? "no_history" : afterSeq === void 0 ? "missing" : "found"
245
+ });
246
+ return block.text;
247
+ }
248
+ export { requireTurnFailureEventId as a, buildDeliveredTurnStatePatch as c, getAgentTurnDiagnosticsAttributes as i, loadPendingMessageCards as l, loadThreadContextTrimFloor as n, completeAuthPauseTurn as o, finalizeFailedTurnReplyWithEvent as r, persistAuthPauseTurnState as s, buildTurnThreadContext as t };