@sentry/junior 0.285.0 → 0.286.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 (73) hide show
  1. package/dist/{adapter-DN5AB4VU.js → adapter-JQZaJ-B_.js} +1 -1
  2. package/dist/{admin-DOITMKnn.js → admin-Dm2bimJ-.js} +1 -1
  3. package/dist/{agent-runner-BsWhHe4N.js → agent-runner-DGCwOEyL.js} +1567 -1048
  4. package/dist/api/schema.d.ts +1 -1
  5. package/dist/api/schema.js +5 -5
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +70 -92
  8. package/dist/{app-DyMs9330.d.ts → app-BKq0JzWx.d.ts} +2 -3
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +37 -40
  11. package/dist/{assistant-reply-9Jip5bsr.js → assistant-reply-CAPafcUY.js} +1 -1
  12. package/dist/{automation-Mk8aaHzy.js → automation-B-jJN_gM.js} +1 -1
  13. package/dist/{background-compaction-queue-DXkLsWoH.js → background-compaction-queue-Btu2oab_.js} +137 -3
  14. package/dist/{briefs-Cl8-nK9B.js → briefs-UMeYehUe.js} +4 -4
  15. package/dist/{catalog-runtime-Bte6jRB2.js → catalog-runtime-Bym8GVdh.js} +1 -1
  16. package/dist/cli/chat.js +14 -14
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +5 -6
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +3 -3
  23. package/dist/{client-DDbBucBw.js → client-B0aAs7wC.js} +2 -2
  24. package/dist/{config-DqFnykQT.js → config-B9f9Lqo5.js} +1 -1
  25. package/dist/{connections-DA4LT9LL.js → connections-CQ7p0aNJ.js} +16 -50
  26. package/dist/{conversation-D8kVoCrP.js → conversation-BusI2uzj.js} +15 -6
  27. package/dist/{conversation-pending-messages-BvROq1bq.js → conversation-pending-messages-DwehU0Fd.js} +1 -1
  28. package/dist/{conversation-privacy-D0j_h70R.js → conversation-privacy-Cd_nZZBM.js} +1 -1
  29. package/dist/{credential-sync-hcsYatw-.js → credential-sync-DmiJi_At.js} +13 -13
  30. package/dist/{db-BhHZSuFw.d.ts → db-C5zi4ecs.d.ts} +4 -4
  31. package/dist/{executor-BLEMIgIZ.js → executor-Dipi2Ixl.js} +11 -17
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{logging-BfORLKoq.js → logging-CMFhLLj4.js} +1 -1
  34. package/dist/{media-Bu9C6lz0.js → media-B-BpXo41.js} +14 -2
  35. package/dist/{message-DqjuKzUx.js → message-D1xLljUF.js} +9 -9
  36. package/dist/nitro.d.ts +1 -1
  37. package/dist/nitro.js +2 -3
  38. package/dist/{oauth-callback-server-CFSRzu1n.js → oauth-callback-server-DCAFIUQr.js} +2 -2
  39. package/dist/{projection-DliWYrnT.js → projection-CoeMNxJ4.js} +286 -212
  40. package/dist/{prompt-BvIUzY4y.js → prompt-C9OQEfan.js} +1 -1
  41. package/dist/{registry-rC7MCxu8.js → registry-u-sFYtx_.js} +1 -1
  42. package/dist/{resolve-Biu8Qw3u.js → resolve-DYqgL3Eo.js} +3 -3
  43. package/dist/{result-DxJMCX47.js → result-CescSwAw.js} +8 -8
  44. package/dist/{runner-BQJSFLKg.js → runner-Cr67a8TB.js} +16 -12
  45. package/dist/{sandbox-egress-signals-6aMxJSDn.js → sandbox-egress-signals-DLOazy5W.js} +1 -1
  46. package/dist/{schema-BasXTvi2.js → schema-BUSi3sgv.js} +5 -5
  47. package/dist/{schema-BUviRAs8.d.ts → schema-Ih60j59-.d.ts} +44 -7
  48. package/dist/{service-account-BI5Wgx22.js → service-account-CGEqz9wG.js} +3 -3
  49. package/dist/{service-account-CAE-_1dR.js → service-account-CsKxktLk.js} +3 -3
  50. package/dist/{session-stop-CA-jOJ84.js → session-stop-CGz5DByb.js} +22 -20
  51. package/dist/{skills-B22duVJU.js → skills-COCqf61f.js} +2 -2
  52. package/dist/{spawn-BB2_4VYn.js → spawn-C8F_iXWO.js} +13 -2
  53. package/dist/{stop-DioIcEAu.js → stop-GyFZkHuQ.js} +242 -952
  54. package/dist/{store-Dn4W7qgH.js → store-D0-8plWp.js} +3 -3
  55. package/dist/{turn-session-routing-CGMKrYOj.js → task-runner-xPuQmEot.js} +1439 -993
  56. package/dist/{store-B26LV6UP.js → turn-failure-response-BOviBdT-.js} +331 -5
  57. package/dist/{validation-TzhfQABF.js → validation-DZDKorGz.js} +1 -1
  58. package/dist/{version-DSk8CFvA.js → version-BTIz7fGi.js} +1 -1
  59. package/dist/version.js +1 -1
  60. package/dist/{viewer-1Ea81s0b.js → viewer-CH-ASQzh.js} +39 -36
  61. package/dist/{work-ybG4_q5C.js → work-C75_IM5e.js} +92 -87
  62. package/dist/{worker-ccSyZRNz.js → worker-Dl47I729.js} +6 -6
  63. package/migrations/0086_shared_archive.sql +31 -0
  64. package/migrations/0087_child_location.sql +64 -0
  65. package/migrations/meta/0086_snapshot.json +4366 -0
  66. package/migrations/meta/0087_snapshot.json +4366 -0
  67. package/migrations/meta/_journal.json +14 -0
  68. package/package.json +5 -4
  69. package/dist/task-queue-Bt0IoR2i.js +0 -139
  70. package/dist/task-runner-D8lddjzp.js +0 -290
  71. package/dist/thread-state-CrFk3K_7.js +0 -173
  72. package/dist/turn-failure-response-DaJ04qVj.js +0 -224
  73. package/dist/turn-lifecycle-C2mXS7AZ.js +0 -58
@@ -603,6 +603,20 @@
603
603
  "when": 1794019929847,
604
604
  "tag": "0085_child_archived_at",
605
605
  "breakpoints": true
606
+ },
607
+ {
608
+ "idx": 86,
609
+ "version": "7",
610
+ "when": 1794023855568,
611
+ "tag": "0086_shared_archive",
612
+ "breakpoints": true
613
+ },
614
+ {
615
+ "idx": 87,
616
+ "version": "7",
617
+ "when": 1794088255456,
618
+ "tag": "0087_child_location",
619
+ "breakpoints": true
606
620
  }
607
621
  ]
608
622
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sentry/junior",
3
- "version": "0.285.0",
3
+ "version": "0.286.0",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -87,12 +87,13 @@
87
87
  "jose": "^6.2.3",
88
88
  "just-bash": "3.0.1",
89
89
  "node-html-markdown": "^2.0.0",
90
+ "p-limit": "^7.3.1",
90
91
  "pg": "^8.16.3",
91
92
  "sharp": "^0.35.3",
92
93
  "web-push": "^3.6.7",
93
94
  "yaml": "^2.9.0",
94
95
  "zod": "^4.5.4",
95
- "@sentry/junior-plugin-api": "0.285.0"
96
+ "@sentry/junior-plugin-api": "0.286.0"
96
97
  },
97
98
  "peerDependencies": {
98
99
  "bullmq": "^6.5.0",
@@ -128,8 +129,8 @@
128
129
  "typescript": "^7.0.2",
129
130
  "vercel": "^54.4.0",
130
131
  "vitest": "^4.1.12",
131
- "@sentry/junior-github": "0.285.0",
132
- "@sentry/junior-memory": "0.285.0",
132
+ "@sentry/junior-github": "0.286.0",
133
+ "@sentry/junior-memory": "0.286.0",
133
134
  "@sentry/junior-testing": "0.0.0"
134
135
  },
135
136
  "scripts": {
@@ -1,139 +0,0 @@
1
- import { h as logWarn } from "./logging-BfORLKoq.js";
2
- import { _ as runWithTurnRequestDeadline, f as QUEUE_SIGNATURE_MAX_AGE_MS, h as getQueueProvider, m as verifyQueueMessage, p as signQueueMessage } from "./background-compaction-queue-DXkLsWoH.js";
3
- import { createHash } from "node:crypto";
4
- import * as z from "zod";
5
- // src/chat/queue/callback.ts
6
- /** Shared queue callback wiring for signed messages. */
7
- /** Build the HTTP callback and local-dev consumer for one signed queue. */
8
- function queueCallback(options) {
9
- const consume = async (message, metadata) => {
10
- if (options.skip?.(metadata)) return;
11
- try {
12
- await runWithTurnRequestDeadline(() => options.run(message, metadata));
13
- } catch (error) {
14
- const reason = options.permanentError?.(error);
15
- if (!reason) throw error;
16
- options.onRejected(reason, metadata, error);
17
- }
18
- };
19
- const handler = async (value, metadata) => {
20
- if (options.skip?.(metadata)) return;
21
- const checked = options.verify(value);
22
- if (checked.status === "rejected") {
23
- options.onRejected(checked.reason, metadata);
24
- return;
25
- }
26
- if (checked.status === "unavailable") throw new Error(`Queue message verification unavailable: ${checked.reason}`);
27
- await consume(checked.message, metadata);
28
- };
29
- const retry = (error, metadata) => {
30
- const reason = options.permanentError?.(error);
31
- if (reason) {
32
- options.onRejected(reason, metadata, error);
33
- return { acknowledge: true };
34
- }
35
- if (options.maxDeliveries !== null && metadata.deliveryCount >= options.maxDeliveries) return { acknowledge: true };
36
- };
37
- const consumer = {
38
- consumerGroup: options.consumerGroup,
39
- handler,
40
- retry,
41
- topic: options.topic,
42
- visibilityTimeoutSeconds: options.visibilityTimeoutSeconds
43
- };
44
- return {
45
- /** Run a message that an in-process queue already trusts. */
46
- consume,
47
- consumer,
48
- create: () => getQueueProvider().createCallback(consumer),
49
- registerDev: () => {
50
- if (process.env.NODE_ENV !== "development") return;
51
- return getQueueProvider().registerDevConsumer?.(consumer);
52
- }
53
- };
54
- }
55
- // src/chat/plugins/task-queue.ts
56
- /**
57
- * Delivery for plugin-registered tasks.
58
- *
59
- * Plugins register named tasks. This module owns the shared signed message,
60
- * send path, and HTTP/local callback. Core keeps one topic and one runner.
61
- */
62
- /** Deploy topic name. Keep stable for Vercel queue wiring. */
63
- const PLUGIN_TASK_QUEUE_TOPIC = "junior_plugin_tasks";
64
- const PLUGIN_TASK_DEV_CONSUMER_GROUP = "junior_plugin_tasks_dev";
65
- const PLUGIN_TASK_MAX_DELIVERIES = 5;
66
- const PLUGIN_TASK_SIGN_CONTEXT = "junior.plugin_task_queue.v1";
67
- const PLUGIN_TASK_SIGN_VERSION = "v1";
68
- const pluginTaskParamsSchema = z.object({
69
- conversationId: z.string().min(1),
70
- sessionId: z.string().min(1)
71
- }).strict();
72
- const pluginTaskSign = {
73
- context: PLUGIN_TASK_SIGN_CONTEXT,
74
- schema: z.object({
75
- name: z.string().min(1),
76
- params: pluginTaskParamsSchema,
77
- plugin: z.string().min(1)
78
- }).strict(),
79
- signatureVersion: PLUGIN_TASK_SIGN_VERSION,
80
- parts: (message) => [
81
- message.plugin,
82
- message.name,
83
- message.params.conversationId,
84
- message.params.sessionId
85
- ]
86
- };
87
- /** Build the stable id used for delivery dedupe and tracing. */
88
- function pluginTaskId(args) {
89
- 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)}`;
90
- }
91
- /** Sign a plugin task message for tests and local checks. */
92
- function signPluginTaskQueueMessage(message, nowMs = Date.now()) {
93
- return signQueueMessage(pluginTaskSign, message, nowMs);
94
- }
95
- function verifyPluginTaskQueueMessage(value, nowMs = Date.now()) {
96
- return verifyQueueMessage(pluginTaskSign, value, nowMs);
97
- }
98
- function logPluginTaskQueueMessageRejected(reason, metadata) {
99
- logWarn("plugin.task.queue_message.rejected", {
100
- "app.queue.consumer_group": metadata.consumerGroup,
101
- "app.queue.delivery_count": metadata.deliveryCount,
102
- "app.queue.message_id": metadata.messageId,
103
- "app.queue.reject_reason": reason,
104
- "app.queue.topic_name": metadata.topicName
105
- });
106
- }
107
- function pluginTaskCallback() {
108
- return queueCallback({
109
- consumerGroup: PLUGIN_TASK_DEV_CONSUMER_GROUP,
110
- maxDeliveries: PLUGIN_TASK_MAX_DELIVERIES,
111
- onRejected: logPluginTaskQueueMessageRejected,
112
- run: async (message) => {
113
- const { processPluginTask } = await import("./task-runner-D8lddjzp.js").then((n) => n.r);
114
- await processPluginTask(message);
115
- },
116
- topic: PLUGIN_TASK_QUEUE_TOPIC,
117
- verify: verifyPluginTaskQueueMessage
118
- });
119
- }
120
- /** Send one plugin task through the shared signed delivery path. */
121
- async function sendVercelPluginTask(message) {
122
- await getQueueProvider().send(PLUGIN_TASK_QUEUE_TOPIC, signPluginTaskQueueMessage(message), {
123
- idempotencyKey: pluginTaskId(message),
124
- retentionSeconds: QUEUE_SIGNATURE_MAX_AGE_MS / 1e3
125
- });
126
- }
127
- /** Create the HTTP callback for plugin tasks. */
128
- function createVercelPluginTaskCallback() {
129
- return pluginTaskCallback().create();
130
- }
131
- /** Return the queue consumer for plugin tasks, for a pulling queue worker. */
132
- function pluginTaskQueueConsumer() {
133
- return pluginTaskCallback().consumer;
134
- }
135
- /** Register the local-dev consumer for plugin tasks. */
136
- function registerVercelPluginTaskDevConsumer() {
137
- return pluginTaskCallback().registerDev();
138
- }
139
- export { pluginTaskQueueConsumer as a, queueCallback as c, pluginTaskParamsSchema as i, createVercelPluginTaskCallback as n, registerVercelPluginTaskDevConsumer as o, pluginTaskId as r, sendVercelPluginTask as s, PLUGIN_TASK_QUEUE_TOPIC as t };
@@ -1,290 +0,0 @@
1
- import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { Fa as createPluginEmbedder, Ia as createPluginModel, Ja as createPluginModelCostRecorder, Xn as coreTaskRegistrations, Ya as createPluginLogger, Yt as getPiMessageRole, an as isToolResultMessage, cn as stripRuntimeTurnContext, di as createPluginState, en as instructionTextForProjection, in as isToolResultError, jo as createPluginCache, nt as getTurnRecord, on as normalizeToolNameFromResult, qn as getPlugins, so as createPluginConversationEvents, v as hydrateConversationMessages } from "./projection-DliWYrnT.js";
3
- import { E as withSpan } from "./logging-BfORLKoq.js";
4
- import { h as parseSlackMessageTs } from "./actor-6jsm_v96.js";
5
- import { S as getDb, i as readActorIdentity, x as getConversationStore } from "./viewer-1Ea81s0b.js";
6
- import { v as sameActorIdentity } from "./media-Bu9C6lz0.js";
7
- import { r as getStateAdapter } from "./adapter-DN5AB4VU.js";
8
- import { t as resolveConversationRouting, u as getDispatchRecord } from "./turn-session-routing-CGMKrYOj.js";
9
- import { o as coerceThreadConversationState, r as getPersistedThreadState } from "./thread-state-CrFk3K_7.js";
10
- import { i as pluginTaskParamsSchema, r as pluginTaskId, s as sendVercelPluginTask } from "./task-queue-Bt0IoR2i.js";
11
- import { pluginRunContextSchema } from "@sentry/junior-plugin-api";
12
- // src/chat/plugins/task-runner.ts
13
- /**
14
- * Plugin background-task orchestration.
15
- *
16
- * Core schedules tasks from completed sessions and exposes plugins only a
17
- * bounded run projection rather than live runtime internals or queue
18
- * payloads.
19
- */
20
- var task_runner_exports = /* @__PURE__ */ __exportAll({
21
- processPluginTask: () => processPluginTask,
22
- scheduleSessionCompletedPluginTasks: () => scheduleSessionCompletedPluginTasks
23
- });
24
- const PLUGIN_TASK_LOCK_TTL_MS = 3e5;
25
- function isRecord(value) {
26
- return Boolean(value && typeof value === "object" && !Array.isArray(value));
27
- }
28
- function textPart(value) {
29
- if (isRecord(value) && value.type === "text" && typeof value.text === "string") return value.text;
30
- }
31
- function messageText(message) {
32
- const content = message.content;
33
- if (typeof content === "string") return sanitizeText(content);
34
- if (!Array.isArray(content)) return "";
35
- return sanitizeText(content.map(textPart).filter(Boolean).join("\n"));
36
- }
37
- function toolResultText(message) {
38
- const record = message;
39
- return sanitizeText([
40
- messageText(message),
41
- record.output,
42
- record.result,
43
- record.stdout,
44
- record.stderr,
45
- record.toolResult
46
- ].filter((value) => typeof value === "string" && value.length > 0).join("\n"));
47
- }
48
- function sanitizeText(text) {
49
- 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();
50
- }
51
- /** Build the transcript provenance for a user message from its Pi provenance. */
52
- function messageProvenance(provenance) {
53
- return {
54
- authority: provenance.authority,
55
- ...provenance.actor ? { actor: provenance.actor } : void 0
56
- };
57
- }
58
- function runTranscriptEntry(message, provenance, runActor) {
59
- const role = getPiMessageRole(message);
60
- if (role === "user" || role === "assistant") {
61
- const text = role === "user" ? instructionTextForProjection(messageText(message)) : messageText(message);
62
- if (!text) return;
63
- if (role === "assistant") return {
64
- type: "message",
65
- role,
66
- text
67
- };
68
- return {
69
- type: "message",
70
- role,
71
- text,
72
- provenance: messageProvenance(provenance),
73
- isRunActor: sameActorIdentity(provenance.actor, runActor)
74
- };
75
- }
76
- if (!isToolResultMessage(message)) return;
77
- const toolName = normalizeToolNameFromResult(message);
78
- if (!toolName) return;
79
- const text = toolResultText(message);
80
- return {
81
- type: "toolResult",
82
- toolName,
83
- isError: isToolResultError(message),
84
- ...text ? { text } : void 0
85
- };
86
- }
87
- /**
88
- * Slice the current turn's Pi messages with their aligned provenance and strip
89
- * runtime turn context, keeping each surviving message paired with the exact
90
- * provenance recorded for it. Stripping can drop or rewrite messages, so the
91
- * pairing is applied per message rather than by post-strip index.
92
- */
93
- function turnMessagesWithProvenance(record) {
94
- const startIndex = record.turnStartMessageIndex ?? 0;
95
- const messages = record.piMessages.slice(startIndex);
96
- const provenance = record.piMessageProvenance.slice(startIndex);
97
- const paired = [];
98
- for (const [index, message] of messages.entries()) for (const stripped of stripRuntimeTurnContext([message])) paired.push({
99
- message: stripped,
100
- provenance: provenance[index] ?? { authority: "context" }
101
- });
102
- return paired;
103
- }
104
- /** Recover the Slack context author identity from a persisted thread message. */
105
- function slackContextAuthor(location, message) {
106
- const userId = message.author?.userId?.trim();
107
- if (!userId) return;
108
- return {
109
- platform: "slack",
110
- teamId: location.teamId,
111
- userId,
112
- ...message.author?.userName ? { userName: message.author.userName } : void 0,
113
- ...message.author?.fullName ? { fullName: message.author.fullName } : void 0
114
- };
115
- }
116
- function slackTimestampMs(value) {
117
- const timestamp = parseSlackMessageTs(value);
118
- if (!timestamp) return;
119
- const timestampMs = Number(timestamp) * 1e3;
120
- return Number.isFinite(timestampMs) ? timestampMs : void 0;
121
- }
122
- function conversationMessageTimestampMs(message) {
123
- if (message.meta?.slackTs !== void 0) return slackTimestampMs(message.meta.slackTs);
124
- return Number.isFinite(message.createdAtMs) ? message.createdAtMs : void 0;
125
- }
126
- function messageExistedAtRunCompletion(message, completedAtMs) {
127
- const messageTimestampMs = conversationMessageTimestampMs(message);
128
- return messageTimestampMs !== void 0 && messageTimestampMs <= completedAtMs;
129
- }
130
- /**
131
- * Project bounded public-thread context into the run transcript.
132
- *
133
- * Prior public Slack messages from the current Conversation are durable
134
- * evidence a completed run may have acted on, so passive consumers can cite
135
- * them. They are always context authority (never instruction), and private or
136
- * local Conversations add nothing here.
137
- */
138
- async function loadConversationContextTranscriptEntries(record, location, visibility, runActor) {
139
- if (location?.provider !== "slack" || visibility !== "public") return [];
140
- const state = await getPersistedThreadState(record.conversationId);
141
- const conversation = coerceThreadConversationState(state);
142
- await hydrateConversationMessages({
143
- conversation,
144
- conversationId: record.conversationId
145
- });
146
- const entries = [];
147
- for (const message of conversation.messages) {
148
- if (message.role !== "user") continue;
149
- if (!messageExistedAtRunCompletion(message, record.updatedAtMs)) continue;
150
- const text = sanitizeText(message.text);
151
- if (!text) continue;
152
- const author = slackContextAuthor(location, message);
153
- entries.push({
154
- type: "message",
155
- role: "user",
156
- text,
157
- provenance: {
158
- authority: "context",
159
- ...author ? { actor: author } : void 0
160
- },
161
- isRunActor: sameActorIdentity(author, runActor)
162
- });
163
- }
164
- return entries;
165
- }
166
- async function withPluginTaskLock(taskId, callback) {
167
- const state = getStateAdapter();
168
- await state.connect();
169
- const lock = await state.acquireLock(`plugin:task:${taskId}`, PLUGIN_TASK_LOCK_TTL_MS);
170
- if (!lock) throw new Error(`Could not acquire plugin task lock for ${taskId}`);
171
- try {
172
- return await callback();
173
- } finally {
174
- await state.releaseLock(lock);
175
- }
176
- }
177
- /** Load the bounded completed-run projection exposed to plugin tasks. */
178
- async function loadPluginRun(params) {
179
- const record = await getTurnRecord(params.conversationId, params.sessionId);
180
- if (!record) throw new Error("Completed plugin task session record is unavailable");
181
- if (record.state !== "completed") throw new Error("Completed plugin task session record is not completed");
182
- const conversationStore = getConversationStore();
183
- const routing = await resolveConversationRouting({
184
- conversationId: params.conversationId,
185
- conversationStore
186
- });
187
- if (!routing) throw new Error(`Conversation ${params.conversationId} is missing durable routing metadata`);
188
- const source = record.source ?? routing.source;
189
- if (!source) throw new Error("Completed plugin task session record is missing Source");
190
- const conversation = await conversationStore.get({ conversationId: params.conversationId });
191
- const runActor = record.actor ?? record.actors[0] ?? (record.dispatchId ? (await getDispatchRecord(record.dispatchId))?.actor : void 0);
192
- const actorUser = runActor ? (await readActorIdentity(runActor))?.user : void 0;
193
- const runEntries = turnMessagesWithProvenance(record).map(({ message, provenance }) => runTranscriptEntry(message, provenance, runActor)).filter((entry) => Boolean(entry));
194
- const runMessageTexts = new Set(runEntries.filter((entry) => entry.type === "message").map((entry) => entry.text));
195
- const contextEntries = (await loadConversationContextTranscriptEntries(record, conversation?.location, conversation?.visibility, runActor)).filter((entry) => entry.type !== "message" || !runMessageTexts.has(entry.text));
196
- return pluginRunContextSchema.parse({
197
- ...actorUser ? { actorUserId: actorUser.id } : void 0,
198
- completedAtMs: record.updatedAtMs,
199
- conversationId: record.conversationId,
200
- destination: routing.destination,
201
- ...routing.location ? { locationId: routing.location.id } : void 0,
202
- actors: record.actors,
203
- ...runActor ? { actor: runActor } : void 0,
204
- runId: record.turnId,
205
- source,
206
- transcript: [...contextEntries, ...runEntries]
207
- });
208
- }
209
- /** Build the plugin-facing context for one claimed task attempt. */
210
- function taskPluginContext(plugin, message, options = {}) {
211
- const pluginName = plugin.manifest.name;
212
- const sessionParams = pluginTaskParamsSchema.parse(message.params);
213
- const onCost = createPluginModelCostRecorder({
214
- conversationId: sessionParams.conversationId,
215
- pluginName,
216
- source: "task",
217
- turnId: sessionParams.sessionId
218
- });
219
- return {
220
- db: getDb(),
221
- embedder: createPluginEmbedder(pluginName, {
222
- onCost,
223
- signal: options.signal
224
- }),
225
- events: createPluginConversationEvents({
226
- conversationId: sessionParams.conversationId,
227
- operationId: pluginTaskId(message),
228
- plugin,
229
- turnId: sessionParams.sessionId
230
- }),
231
- id: pluginTaskId(message),
232
- log: createPluginLogger(pluginName),
233
- model: createPluginModel(pluginName, plugin.model, {
234
- onCost,
235
- signal: options.signal
236
- }),
237
- name: message.name,
238
- plugin: { name: pluginName },
239
- cache: createPluginCache(pluginName),
240
- run: { async load() {
241
- return await loadPluginRun(sessionParams);
242
- } },
243
- state: createPluginState(pluginName)
244
- };
245
- }
246
- function findPluginTask(message) {
247
- const plugin = [...coreTaskRegistrations(), ...getPlugins()].find((candidate) => candidate.manifest.name === message.plugin);
248
- if (!plugin?.tasks || !Object.hasOwn(plugin.tasks, message.name)) return;
249
- return {
250
- plugin,
251
- task: plugin.tasks[message.name]
252
- };
253
- }
254
- /** Schedule all plugin tasks interested in a completed agent-run session. */
255
- async function scheduleSessionCompletedPluginTasks(params, options = {}) {
256
- const coreParams = pluginTaskParamsSchema.parse(params);
257
- const taskRegistrations = [...getPlugins(), ...coreTaskRegistrations()].flatMap((plugin) => Object.keys(plugin.tasks ?? {}).map((name) => ({
258
- name,
259
- plugin
260
- })));
261
- if (taskRegistrations.length === 0) return;
262
- const record = await getTurnRecord(coreParams.conversationId, coreParams.sessionId);
263
- if (!record || record.state !== "completed") throw new Error("Completed plugin task session record is not ready");
264
- const send = options.send ?? sendVercelPluginTask;
265
- const messages = taskRegistrations.map(({ name, plugin }) => ({
266
- name,
267
- params: coreParams,
268
- plugin: plugin.manifest.name
269
- }));
270
- await Promise.all(messages.map(async (message) => {
271
- await send(message);
272
- }));
273
- }
274
- /**
275
- * Execute one parsed plugin task request in a `plugin.task` span. The span
276
- * includes the lock wait, because both delay the work that runs the task.
277
- */
278
- async function processPluginTask(message, options = {}) {
279
- const params = pluginTaskParamsSchema.parse(message.params);
280
- await withSpan(`plugin.task ${message.plugin}.${message.name}`, "plugin.task", { conversationId: params.conversationId }, () => withPluginTaskLock(pluginTaskId(message), async () => {
281
- const resolved = findPluginTask(message);
282
- if (!resolved?.task) throw new Error(`Plugin task "${message.plugin}.${message.name}" is not registered`);
283
- await resolved.task.run(taskPluginContext(resolved.plugin, message, options));
284
- }), {
285
- "app.ai.turn.session_id": params.sessionId,
286
- "app.plugin.name": message.plugin,
287
- "app.plugin.task": message.name
288
- });
289
- }
290
- export { scheduleSessionCompletedPluginTasks as n, task_runner_exports as r, processPluginTask as t };
@@ -1,173 +0,0 @@
1
- import { Mo as createDurableLocationConfigurationService, ri as JUNIOR_THREAD_STATE_TTL_MS, y as persistConversationMessages } from "./projection-DliWYrnT.js";
2
- import { G as toOptionalNumber, K as toOptionalString, W as isRecord } from "./logging-BfORLKoq.js";
3
- import { S as getDb } from "./viewer-1Ea81s0b.js";
4
- import { r as getStateAdapter } from "./adapter-DN5AB4VU.js";
5
- // src/chat/state/conversation.ts
6
- function defaultConversationState() {
7
- return {
8
- schemaVersion: 1,
9
- messages: [],
10
- compactions: [],
11
- processing: {},
12
- vision: { byFileId: {} }
13
- };
14
- }
15
- function coercePendingAuthState(value) {
16
- if (!isRecord(value)) return;
17
- const kind = value.kind;
18
- const provider = toOptionalString(value.provider);
19
- const actorId = toOptionalString(value.actorId);
20
- const authSessionId = toOptionalString(value.authSessionId);
21
- const scope = toOptionalString(value.scope);
22
- const sessionId = toOptionalString(value.sessionId);
23
- const linkSentAtMs = toOptionalNumber(value.linkSentAtMs);
24
- if (kind !== "mcp" && kind !== "plugin" || !provider || !actorId || kind === "mcp" && !authSessionId || !sessionId || typeof linkSentAtMs !== "number") return;
25
- const base = {
26
- provider,
27
- actorId,
28
- ...scope ? { scope } : void 0,
29
- sessionId,
30
- linkSentAtMs
31
- };
32
- return kind === "mcp" ? {
33
- ...base,
34
- authSessionId,
35
- kind
36
- } : {
37
- ...base,
38
- kind
39
- };
40
- }
41
- /** Safely coerce an unknown persisted value into a ThreadConversationState. */
42
- function coerceThreadConversationState(value) {
43
- if (!isRecord(value)) return defaultConversationState();
44
- const root = value;
45
- const rawConversation = isRecord(root.conversation) ? root.conversation : {};
46
- const messages = [];
47
- const compactions = [];
48
- const rawProcessing = isRecord(rawConversation.processing) ? rawConversation.processing : {};
49
- const processing = {
50
- activeTurnId: toOptionalString(rawProcessing.activeTurnId),
51
- lastCompletedAtMs: toOptionalNumber(rawProcessing.lastCompletedAtMs),
52
- pendingAuth: coercePendingAuthState(rawProcessing.pendingAuth)
53
- };
54
- const rawVision = isRecord(rawConversation.vision) ? rawConversation.vision : {};
55
- const rawVisionByFileId = isRecord(rawVision.byFileId) ? rawVision.byFileId : {};
56
- const byFileId = {};
57
- for (const [fileId, value] of Object.entries(rawVisionByFileId)) {
58
- if (typeof fileId !== "string" || fileId.trim().length === 0) continue;
59
- if (!isRecord(value)) continue;
60
- const summary = toOptionalString(value.summary);
61
- const analyzedAtMs = toOptionalNumber(value.analyzedAtMs);
62
- if (!summary || !analyzedAtMs) continue;
63
- byFileId[fileId] = {
64
- summary,
65
- analyzedAtMs
66
- };
67
- }
68
- return {
69
- schemaVersion: 1,
70
- messages,
71
- compactions,
72
- processing,
73
- vision: {
74
- backfillCompletedAtMs: toOptionalNumber(rawVision.backfillCompletedAtMs),
75
- byFileId
76
- }
77
- };
78
- }
79
- /**
80
- * Wrap active conversation control into the thread scratch envelope.
81
- *
82
- * Visible history lives in SQL. Image summaries use a separate disposable
83
- * cache, so thread scratch does not retain them.
84
- */
85
- function buildConversationStatePatch(conversation) {
86
- return { conversation: {
87
- schemaVersion: 1,
88
- processing: { ...conversation.processing }
89
- } };
90
- }
91
- // src/chat/runtime/thread-state.ts
92
- function threadStateKey(threadId) {
93
- return `thread-state:${threadId}`;
94
- }
95
- function channelStateKey(channelId) {
96
- return `channel-state:${channelId}`;
97
- }
98
- function buildThreadStatePayload(patch) {
99
- const payload = {};
100
- if (patch.conversation) Object.assign(payload, buildConversationStatePatch(patch.conversation));
101
- if (patch.sandboxRef !== void 0) {
102
- payload.app_sandbox_id = patch.sandboxRef?.id ?? "";
103
- payload.app_sandbox_dependency_profile_hash = patch.sandboxRef?.profileHash ?? "";
104
- payload.app_sandbox_workspace_id = patch.sandboxRef?.workspaceId ?? "";
105
- }
106
- return payload;
107
- }
108
- /**
109
- * Merge a payload into thread scratch with Junior's TTL.
110
- *
111
- * Chat SDK state writes hardcode a 30-day TTL. This boundary owns Junior's
112
- * shorter retention policy for the same scratch keys.
113
- */
114
- async function mergePersistedState(key, payload) {
115
- if (Object.keys(payload).length === 0) return;
116
- const stateAdapter = getStateAdapter();
117
- await stateAdapter.connect();
118
- const existing = await stateAdapter.get(key) ?? {};
119
- await stateAdapter.set(key, {
120
- ...existing,
121
- ...payload
122
- }, JUNIOR_THREAD_STATE_TTL_MS);
123
- }
124
- /** Extract persisted sandbox metadata from thread state payload. */
125
- function getPersistedSandboxState(state) {
126
- const id = toOptionalString(state.app_sandbox_id);
127
- if (!id) return;
128
- const profileHash = toOptionalString(state.app_sandbox_dependency_profile_hash);
129
- const workspaceId = toOptionalString(state.app_sandbox_workspace_id);
130
- return {
131
- id,
132
- ...profileHash ? { profileHash } : void 0,
133
- ...workspaceId ? { workspaceId } : void 0
134
- };
135
- }
136
- /** Persist only the Redis-backed runtime scratch in a thread-state patch. */
137
- async function persistThreadRuntimeState(conversationId, patch) {
138
- await mergePersistedState(threadStateKey(conversationId), buildThreadStatePayload(patch));
139
- }
140
- /** Load the persisted state payload for a thread without requiring a Chat singleton. */
141
- async function getPersistedThreadState(threadId) {
142
- const stateAdapter = getStateAdapter();
143
- await stateAdapter.connect();
144
- return await stateAdapter.get(threadStateKey(threadId)) ?? {};
145
- }
146
- /** Persist a thread-state patch by thread id without constructing a Chat thread. */
147
- async function persistThreadStateById(threadId, patch) {
148
- if (patch.conversation) await persistConversationMessages({
149
- conversation: patch.conversation,
150
- conversationId: threadId
151
- });
152
- await mergePersistedState(threadStateKey(threadId), buildThreadStatePayload(patch));
153
- }
154
- /** Load legacy Redis-backed channel state during the SQL cutover. */
155
- async function getLegacyChannelState(channelId) {
156
- const stateAdapter = getStateAdapter();
157
- await stateAdapter.connect();
158
- return await stateAdapter.get(channelStateKey(channelId)) ?? {};
159
- }
160
- /**
161
- * Resolve durable location configuration.
162
- *
163
- * Slack still reads the old channel-id Redis bag once during cutover.
164
- */
165
- function getLocationConfigurationService(destination) {
166
- if (destination.platform !== "slack") throw new Error("Location configuration requires a Slack Location");
167
- return createDurableLocationConfigurationService({
168
- destination,
169
- db: getDb(),
170
- loadLegacy: async () => await getLegacyChannelState(destination.channelId)
171
- });
172
- }
173
- export { persistThreadStateById as a, persistThreadRuntimeState as i, getPersistedSandboxState as n, coerceThreadConversationState as o, getPersistedThreadState as r, getLocationConfigurationService as t };