@sentry/junior 0.317.0 → 0.319.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 (95) hide show
  1. package/dist/adapter-8_S6Birm.js +1833 -0
  2. package/dist/{admin-CAugg87B.js → admin-EsbUON1j.js} +1 -1
  3. package/dist/{agent-runner-AjrEV6Qe.js → agent-CtzMl32d.js} +19953 -6727
  4. package/dist/{agent-status-BA5x3Xtp.js → agent-status-Bq_AIpyp.js} +105 -1
  5. package/dist/{agent-update-delivery-B_YIZcgf.js → agent-update-delivery-pAvsbuGL.js} +4 -5
  6. package/dist/api/schema.d.ts +85 -51
  7. package/dist/api/schema.js +4 -4
  8. package/dist/api.js +81 -94
  9. package/dist/{app-MoNAsVV5.d.ts → app-tACXxJPI.d.ts} +8 -13
  10. package/dist/app.d.ts +2 -2
  11. package/dist/app.js +246 -153
  12. package/dist/{change-record-BzJgLsv7.d.ts → change-record-K-KsqNhT.d.ts} +9 -5
  13. package/dist/{channel-access-j-YAVYK4.js → channel-access-DET5hzZM.js} +1 -1
  14. package/dist/{chat-core-engine-aH85nEHv.js → chat-core-engine-DpM3tMVi.js} +7 -7
  15. package/dist/cli/chat.d.ts +1 -1
  16. package/dist/cli/chat.js +38 -30
  17. package/dist/cli/check.js +5 -5
  18. package/dist/cli/main.js +2 -2
  19. package/dist/cli/plugins.d.ts +1 -1
  20. package/dist/cli/plugins.js +8 -8
  21. package/dist/cli/snapshot-create.js +5 -6
  22. package/dist/cli/upgrade.d.ts +1 -1
  23. package/dist/cli/upgrade.js +3 -4
  24. package/dist/{continue-in-slack-D-FZ8Fin.js → continue-in-slack-CFzDyxkH.js} +3 -2
  25. package/dist/{conversation-feed--9S0_PXL.js → conversation-feed-DEUdD7mb.js} +2 -106
  26. package/dist/{conversation-privacy-B1uXn5sf.js → conversation-privacy-C2vYK55O.js} +1 -1
  27. package/dist/{create-DoDIYgtZ.js → create-Ta3SEIB5.js} +124 -16
  28. package/dist/{credential-sync-BJOqGnjV.js → credential-sync-DyRqDmY4.js} +17 -20
  29. package/dist/{db-BFmyYZtJ.js → db-BCaNWl9p.js} +6536 -1920
  30. package/dist/{deployment-DXq9ZLU4.js → deployment-CfOew1Tm.js} +3 -3
  31. package/dist/{engine-context-CgQ7mlHt.js → engine-context-CiExoy1B.js} +181 -155
  32. package/dist/{html-B3VKTGbJ.js → html-Bb2Si1bR.js} +6 -8
  33. package/dist/instrumentation.js +7 -23
  34. package/dist/list-wwDcROh9.js +5007 -0
  35. package/dist/{logging--smS7XRK.js → logging-BRPTXAdf.js} +10 -81
  36. package/dist/{mailbox-turn-uSXhUFc9.js → markers-9QoqW5ov.js} +1875 -1458
  37. package/dist/nitro.d.ts +2 -2
  38. package/dist/nitro.js +7 -8
  39. package/dist/{oauth-callback-server-CE4soEIY.js → oauth-callback-server-vhL9b-PZ.js} +2 -2
  40. package/dist/{oauth-relay-C36gX1gH.js → oauth-relay-CH2v7WiB.js} +1 -1
  41. package/dist/{plugins-fBrz8PCV.d.ts → plugins-DhGXZjlu.d.ts} +1 -0
  42. package/dist/{profile-BQ-iBDsZ.js → profile-D9LdwmZi.js} +17 -19
  43. package/dist/{prompt-Dv7gkpD6.js → prompt-3TqxEOtc.js} +10 -10
  44. package/dist/{reports-WKHfGTsU.js → reports-K-tbtEyx.js} +2 -2
  45. package/dist/{resolve-tony4ibz.js → resolve-BBV2qf8A.js} +5 -5
  46. package/dist/{result-Bta_dlWa.js → result-5IdGJP4M.js} +24 -13
  47. package/dist/{runner-BstDRbD9.js → runner-BK_joPlM.js} +9 -18
  48. package/dist/{sandbox-egress-signals-oSJMJOnn.js → sandbox-egress-signals-DXgWXXmm.js} +1 -1
  49. package/dist/{schema-DfqrHACA.js → schema-zWGG6VC1.js} +13 -7
  50. package/dist/{service-account-CTV_jaNu.js → service-account-CateFyhw.js} +4 -5
  51. package/dist/{skills-BCEU41zM.js → skills-Ccjw8h2P.js} +10 -9
  52. package/dist/{slack-conversation-unfurl-DxVmhbGP.js → slack-conversation-unfurl-ZC_TSpc4.js} +7 -7
  53. package/dist/storage-C9U7R5rM.js +273 -0
  54. package/dist/{system-prompt-table-CiXy0eNR.js → system-prompt-table-YBTHIFlP.js} +26 -84
  55. package/dist/topic-B2EWKKBT.js +6 -0
  56. package/dist/{package-discovery-DD9vencX.js → topics-DxuKurCX.js} +21 -1
  57. package/dist/{types-C4iC-IMC.js → types-BNHkJrOP.js} +79 -59
  58. package/dist/{users-ByG5RCEJ.js → users-CCRAqYb_.js} +1 -1
  59. package/dist/{validation-8gjfR91V.js → validation-BCUpJa8K.js} +4 -4
  60. package/dist/{version-BeZhWWBE.js → version-BNm0JYj3.js} +1 -1
  61. package/dist/version.js +1 -1
  62. package/dist/{worker-BqMQQNRk.js → worker-BhgpZ7_b.js} +5 -5
  63. package/migrations/20261127002500_turn_discarded_usage/migration.sql +2 -0
  64. package/migrations/20261127002500_turn_discarded_usage/snapshot.json +73 -0
  65. package/migrations/20261127052408_space_name_nullable/migration.sql +5 -0
  66. package/migrations/20261127052408_space_name_nullable/snapshot.json +29 -0
  67. package/migrations/20261127060000_annotation_object_id_index/migration.sql +1 -0
  68. package/migrations/20261127060000_annotation_object_id_index/snapshot.json +69 -0
  69. package/migrations/20261127060001_annotation_subjects/migration.sql +78 -0
  70. package/migrations/20261127060001_annotation_subjects/snapshot.json +104 -0
  71. package/migrations/20261127060002_annotation_subject_index/migration.sql +1 -0
  72. package/migrations/20261127060002_annotation_subject_index/snapshot.json +70 -0
  73. package/migrations/20261127060003_annotation_title_url/migration.sql +84 -0
  74. package/migrations/20261127060003_annotation_title_url/snapshot.json +73 -0
  75. package/package.json +9 -7
  76. package/dist/catalog-runtime-DfSpJZdY.js +0 -6
  77. package/dist/child-message-DHjQLEd1.js +0 -19
  78. package/dist/config-CHQ8X251.js +0 -2422
  79. package/dist/conversation-turn-BUE_7xaN.js +0 -1157
  80. package/dist/job-runner-A1lCkybD.js +0 -1506
  81. package/dist/lineage-Bktb0UcV.js +0 -36
  82. package/dist/list-Bxvg5wXf.js +0 -12623
  83. package/dist/message-BNenhsmB.js +0 -154
  84. package/dist/model-input-BReSnwHp.js +0 -82
  85. package/dist/parent-result-Ck1rFYRQ.js +0 -310
  86. package/dist/registry-iXMT5Jmh.js +0 -3279
  87. package/dist/run-conversation-DL6ru7iW.js +0 -336
  88. package/dist/sender-actors-CPglLd5R.js +0 -83
  89. package/dist/spawn-frczVPIr.js +0 -48
  90. package/dist/task-runner-C9Yc2_ae.js +0 -1526
  91. package/dist/thread-context-CqZDKErp.js +0 -166
  92. package/dist/topic-CRYYBYp-.js +0 -7
  93. package/dist/topics-SRN7IVX-.js +0 -24
  94. package/dist/turn-membership-CENFf3kI.js +0 -856
  95. package/dist/turn-wake-BhloiI2h.js +0 -151
@@ -1,1157 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { $r as getDispatchIdForConversation, Bo as credentialContextForActor, Io as verifyTimerWatchCredentialSubject, Ku as getStateAdapter, Mn as readParentMessage, On as canJoinTurn, Pn as isEventMailboxMetadata, Qo as isConversationDeliveryPaused, Ro as JUNIOR_THREAD_STATE_TTL_MS, Xi as blockScheduledAutomation, Xn as sendSlackReply, Yn as resolveSlackReplyTarget, a as getDb, di as notifyAutomationBlocked, hu as indexEndedTurnEvents, i as getConversationStore, iu as isTopLevel, n as getConversationEventStore, nu as isPersonInput, oa as blockEventAutomation, ou as ownsLocation, rn as getConversationWorkState, uu as turnBehavior, yf as resolveConversationDestination } from "./db-BFmyYZtJ.js";
3
- import { Lt as readConversationAutomationRun, M as measureTurnCompactionWait, q as stopConversationAndChildAgents } from "./agent-runner-AjrEV6Qe.js";
4
- import { E as withSpan, S as setTags, h as logWarn, p as logException } from "./logging--smS7XRK.js";
5
- import { Xt as readMessageAttachments, wt as instructionProvenanceFor } from "./types-C4iC-IMC.js";
6
- import { a as buildDeliveredTurnStatePatch, o as loadPendingMessageCards, r as completeAuthPauseTurn, t as buildTurnThreadContext } from "./thread-context-CqZDKErp.js";
7
- import { At as turnRequestText, Dt as instructionActorFor, Er as getTurnLifecycle, Et as buildSteeringPiMessage, Fn as persistConversationMessages, Gn as recordDeliveredAssistantMessage, Hn as latestConversationMessageSeq, Jn as upsertConversationMessage, M as eventBatchMessageMeta, N as renderEventBatchInputs, Nn as hydrateConversationMessages, Ot as instructionForInputs, P as timerWatchCredentialSubject, Qn as isEventConversationMessage, Rr as finalizeFailedTurnReplyWithEvent, Rt as buildDeterministicTurnId, Sr as getTurnRecord, St as loadInboxItemInput, Tr as ConversationTurnLifecycleService, Un as markConversationMessage, Wn as normalizeConversationText, X as getTurnUserMessage, Y as completeCancelledConversationTurn, _t as coerceThreadConversationState, c as legacyWebMailboxMetadataSchema, ct as markTurnClosed, d as childAgentTurnOptions, dt as startActiveTurn, f as commitParentMessageFork, gn as commitAcceptedReply, gt as persistThreadStateById, i as listActiveMailboxTurns, it as getConversationTurnBoundaryError, jt as withoutSavedSteeringMessages, m as isParentMessageAuthor, mt as getPersistedThreadState, n as getEventBatchDelayMs, nt as TurnInputCommitLostError, o as sourceFromTurnInput, ot as isTurnInputCommitLostError, pt as getPersistedSandboxState, s as turnInputFactsFromConversationMessage, ti as persistWithRetry, ut as markTurnFailed, vr as saveTurnCheckpoint, vt as createWebAuthorization, xr as failTurnRecord, xt as eventInboxItemInputs, yn as loadConversationProjection, yr as abandonTurnRecord, yt as deleteWebAuthorization } from "./mailbox-turn-uSXhUFc9.js";
8
- import { d as isChildAgentEvent, t as parentResultActor } from "./parent-result-Ck1rFYRQ.js";
9
- import { i as getActiveSpan, r as continueTrace } from "./sentry-CPbZjomA.js";
10
- import { h as getAssistantReplyText } from "./system-prompt-table-CiXy0eNR.js";
11
- import { t as botConfig } from "./config-CHQ8X251.js";
12
- import { i as CONVERSATION_METADATA_TASK, n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-C9Yc2_ae.js";
13
- import { n as getPausedTurnRequest } from "./turn-wake-BhloiI2h.js";
14
- import { L as mapBounded } from "./prompt-Dv7gkpD6.js";
15
- import { t as readConversationLineage } from "./lineage-Bktb0UcV.js";
16
- import * as z from "zod";
17
- import { isDeepStrictEqual } from "node:util";
18
- import { createHash } from "node:crypto";
19
- // src/chat/task-execution/turn-telemetry.ts
20
- /** Read the turn input timing facts from a mailbox batch, oldest first. */
21
- function turnInputTelemetry(messages) {
22
- const oldest = messages[0];
23
- if (!oldest) return void 0;
24
- return {
25
- count: messages.length,
26
- oldestCreatedAtMs: oldest.createdAtMs,
27
- oldestReceivedAtMs: oldest.receivedAtMs,
28
- traceContexts: messages.flatMap((message) => message.traceContext ?? [])
29
- };
30
- }
31
- const SENTRY_TRACE_PATTERN = /^([0-9a-f]{32})-([0-9a-f]{16})(?:-([01]))?$/;
32
- function spanLinks({ sentryTrace }) {
33
- const [, traceId, spanId, sampled] = SENTRY_TRACE_PATTERN.exec(sentryTrace) ?? [];
34
- return traceId && spanId ? [{ context: {
35
- traceId,
36
- spanId,
37
- traceFlags: sampled === "1" ? 1 : 0
38
- } }] : [];
39
- }
40
- /**
41
- * Run a `chat.turn` span in the trace of the first trace context.
42
- *
43
- * The span links to the other trace contexts and to the span that was active,
44
- * such as the worker span. Without a trace context, the span is a child of the
45
- * active span. A malformed trace context starts a new trace. The span records
46
- * how long the Turn waited on context compaction.
47
- */
48
- async function withTurnSpan(context, input, callback) {
49
- const [parent, ...others] = input?.traceContexts ?? [];
50
- if (!parent) return await withSpan("chat.turn", "chat.turn", context, (set) => measureTurnCompactionWait(set, () => callback(set)));
51
- const activeSpan = getActiveSpan();
52
- const links = [...others.flatMap(spanLinks), ...activeSpan ? [{ context: activeSpan.spanContext() }] : []];
53
- const { baggage, sentryTrace } = parent;
54
- return await continueTrace({
55
- baggage,
56
- sentryTrace
57
- }, () => withSpan("chat.turn", "chat.turn", context, async (setSpanAttributes) => {
58
- getActiveSpan()?.addLinks(links);
59
- return await measureTurnCompactionWait(setSpanAttributes, () => callback(setSpanAttributes));
60
- }));
61
- }
62
- /**
63
- * Build the `chat.turn` timing attributes for the oldest input message.
64
- *
65
- * The provider, the ingress host, and the worker host use separate clocks. A negative
66
- * duration is clock skew, not latency, so it is left out.
67
- */
68
- function getTurnInputSpanAttributes(input, turnStartedAtMs) {
69
- const attributes = { "app.turn.input_count": input.count };
70
- const deliveryLagMs = input.oldestReceivedAtMs - input.oldestCreatedAtMs;
71
- if (deliveryLagMs >= 0) attributes["app.turn.delivery_lag_ms"] = Math.round(deliveryLagMs);
72
- const waitMs = turnStartedAtMs - input.oldestReceivedAtMs;
73
- if (waitMs >= 0) attributes["app.turn.wait_ms"] = Math.round(waitMs);
74
- return attributes;
75
- }
76
- // src/chat/runtime/turn-execution.ts
77
- /** An error thrown while the agent advances a Run. */
78
- var AgentRunError = class extends Error {
79
- constructor(cause) {
80
- super(cause instanceof Error ? cause.message : "Agent Run failed", { cause });
81
- this.name = "AgentRunError";
82
- }
83
- };
84
- /**
85
- * Run the agent and finish the Turn after the caller saves its result.
86
- *
87
- * A paused Run, or a Run waiting for authorization, leaves the Turn open. A
88
- * save error also leaves the Turn open so the worker can retry or recover it.
89
- * `lifecycle` records the end and sends its agent update.
90
- */
91
- async function executeTurn(agentRunner, run, saveResult, lifecycle = getTurnLifecycle()) {
92
- let outcome;
93
- try {
94
- outcome = await agentRunner.run(run);
95
- } catch (error) {
96
- throw new AgentRunError(error);
97
- }
98
- if (outcome.status !== "completed") return outcome;
99
- await finishTurn(lifecycle, run, await saveResult(outcome.result));
100
- return { status: "completed" };
101
- }
102
- async function finishTurn(lifecycle, run, saved) {
103
- const common = {
104
- conversationId: run.conversationId,
105
- createdAtMs: saved.finishedAtMs ?? Date.now(),
106
- ...run.actor ? { reportAs: parentResultActor(run.actor, run.source.kind) } : void 0,
107
- turnId: run.turnId
108
- };
109
- if (saved.outcome === "failed") await lifecycle.fail({
110
- ...common,
111
- ...saved.eventId ? { eventId: saved.eventId } : void 0,
112
- failureCode: saved.failureCode,
113
- ...saved.failureReason ? { failureReason: saved.failureReason } : void 0,
114
- ...saved.failureText ? { failureText: saved.failureText } : void 0
115
- });
116
- else await lifecycle.complete({
117
- ...common,
118
- ...saved.answer ? { answer: saved.answer } : void 0,
119
- outcome: saved.outcome
120
- });
121
- }
122
- // src/chat/services/automated-turn-limit.ts
123
- const AUTOMATED_TURN_LIMIT_PREFIX = "junior:automated_turn_limit:v1";
124
- const AUTOMATED_TURN_LIMIT_LOCK_TTL_MS = 5e3;
125
- const AUTOMATED_TURN_LIMIT_LOCK_WAIT_MS = 2e3;
126
- const AUTOMATED_TURN_LIMIT_LOCK_RETRY_MS = 25;
127
- /**
128
- * Stored consecutive automated-turn count for one Conversation. Parsing
129
- * strips the fields of the old pause, so its count still applies.
130
- */
131
- const automatedTurnLimitStateSchema = z.object({
132
- consecutiveAutomatedTurns: z.number().int().nonnegative(),
133
- updatedAtMs: z.number().finite().nonnegative()
134
- });
135
- function sleep(ms) {
136
- return new Promise((resolve) => {
137
- setTimeout(resolve, ms).unref?.();
138
- });
139
- }
140
- function conversationKey(conversationId) {
141
- return `${AUTOMATED_TURN_LIMIT_PREFIX}:conversation:${conversationId}`;
142
- }
143
- function lockKey(key) {
144
- return `${key}:lock`;
145
- }
146
- function parseState(value) {
147
- const parsed = automatedTurnLimitStateSchema.safeParse(value);
148
- return parsed.success ? parsed.data : void 0;
149
- }
150
- async function acquireConversationLock(state, key, waitDeadlineMs = Date.now() + AUTOMATED_TURN_LIMIT_LOCK_WAIT_MS) {
151
- while (true) {
152
- const lock = await state.acquireLock(lockKey(key), AUTOMATED_TURN_LIMIT_LOCK_TTL_MS);
153
- if (lock) return lock;
154
- if (Date.now() >= waitDeadlineMs) throw new Error(`Could not acquire automated turn limit lock for ${key}`);
155
- await sleep(AUTOMATED_TURN_LIMIT_LOCK_RETRY_MS);
156
- }
157
- }
158
- async function withConversationLock(state, key, callback) {
159
- const lock = await acquireConversationLock(state, key);
160
- try {
161
- return await callback();
162
- } finally {
163
- await state.releaseLock(lock);
164
- }
165
- }
166
- function emptyState(nowMs) {
167
- return {
168
- consecutiveAutomatedTurns: 0,
169
- updatedAtMs: nowMs
170
- };
171
- }
172
- /** True when this Source starts an automated Turn rather than a user Turn. */
173
- function isAutomatedTurnSource(source) {
174
- if (!source) return false;
175
- return source.kind === "event" || source.kind === "event_automation" || source.kind === "scheduled_automation" || source.kind === "plugin_dispatch" || source.kind === "parent_message";
176
- }
177
- /** Plain notice when automatic updates stop until the user replies. */
178
- function buildAutomatedTurnLimitResponse(args) {
179
- return `I stopped automatic updates after ${args.maxTurns} automated turns without a new message from you. Turns with no reply also count. Send a message or @mention me in this thread to continue.`;
180
- }
181
- /** Count one finished automated Turn toward the consecutive-turn limit. */
182
- async function countAutomatedTurn(args) {
183
- if (args.maxTurns < 1) throw new Error("Automated turn limit must be at least 1");
184
- const state = args.state ?? getStateAdapter();
185
- await state.connect();
186
- const nowMs = args.nowMs ?? Date.now();
187
- const key = conversationKey(args.conversationId);
188
- return await withConversationLock(state, key, async () => {
189
- const consecutiveAutomatedTurns = (parseState(await state.get(key)) ?? emptyState(nowMs)).consecutiveAutomatedTurns + 1;
190
- await state.set(key, {
191
- consecutiveAutomatedTurns,
192
- updatedAtMs: nowMs
193
- }, JUNIOR_THREAD_STATE_TTL_MS);
194
- return {
195
- consecutiveAutomatedTurns,
196
- reached: consecutiveAutomatedTurns >= args.maxTurns
197
- };
198
- });
199
- }
200
- /** Clear the consecutive automated-turn count after a user-owned Turn. */
201
- async function resetAutomatedTurnLimit(args) {
202
- const state = args.state ?? getStateAdapter();
203
- await state.connect();
204
- const key = conversationKey(args.conversationId);
205
- await withConversationLock(state, key, async () => {
206
- await state.delete(key);
207
- });
208
- }
209
- /**
210
- * Update consecutive automated-turn counts after one finished Turn.
211
- *
212
- * Automated Turns count on the Conversation. User Turns clear that count.
213
- */
214
- async function recordFinishedTurnForAutomatedLimit(args) {
215
- const nowMs = args.nowMs ?? Date.now();
216
- if (isAutomatedTurnSource(args.source)) return await countAutomatedTurn({
217
- conversationId: args.conversationId,
218
- maxTurns: args.maxTurns,
219
- nowMs,
220
- state: args.state
221
- });
222
- await resetAutomatedTurnLimit({
223
- conversationId: args.conversationId,
224
- nowMs,
225
- state: args.state
226
- });
227
- }
228
- // src/chat/slack/automated-turn-limit-notice.ts
229
- /**
230
- * Stop and notice for the consecutive automated-turn limit.
231
- *
232
- * The notice is best-effort: a failed post must not fail the Turn or undo the
233
- * stop.
234
- */
235
- /**
236
- * Post the stop notice to the Conversation Location when known. A child
237
- * agent posts none: its parent sees it as stopped in `listAgents`.
238
- */
239
- async function postAutomatedTurnLimitNotice(args) {
240
- try {
241
- const conversation = await getConversationStore().get({ conversationId: args.conversationId });
242
- const location = conversation?.parentConversationId ? void 0 : conversation?.location;
243
- if (!location || location.provider !== "slack" || conversation?.deliveryPausedAtMs !== void 0) {
244
- logWarn("automated_turn_limit.notice.skipped", {
245
- conversationId: args.conversationId,
246
- "app.automated_turn_limit.reason": !location ? "missing_location" : location.provider !== "slack" ? "unsupported_location" : "delivery_paused"
247
- });
248
- return;
249
- }
250
- await sendSlackReply({
251
- ...resolveSlackReplyTarget({
252
- destination: location,
253
- location,
254
- source: args.source
255
- }),
256
- conversationId: args.conversationId,
257
- text: buildAutomatedTurnLimitResponse({ maxTurns: args.maxTurns })
258
- });
259
- } catch (error) {
260
- logException(error, "automated_turn_limit.notice.failed", { conversationId: args.conversationId });
261
- }
262
- }
263
- /**
264
- * Stop the Conversation tree after a finished Turn reaches the automated-turn
265
- * limit, then post the notice. Person input that already waits ends the loop
266
- * by itself, so then nothing stops.
267
- */
268
- async function stopAtAutomatedTurnLimit(args) {
269
- if (!args.update?.reached) return;
270
- if (((await getConversationWorkState({ conversationId: args.conversationId }))?.messages ?? []).some((message) => isPersonInput(message.source))) return;
271
- const nowMs = Date.now();
272
- await stopConversationAndChildAgents({
273
- conversationId: args.conversationId,
274
- finishedRunOf: args.conversationId,
275
- nowMs,
276
- stoppedAtMs: nowMs
277
- });
278
- await postAutomatedTurnLimitNotice({
279
- conversationId: args.conversationId,
280
- maxTurns: args.maxTurns,
281
- source: args.source
282
- });
283
- }
284
- // src/chat/task-execution/supersede-turns.ts
285
- /**
286
- * End every open mailbox Turn other than `keepTurnId`, so new input runs in
287
- * the only open Turn. New input starts only when no yielded Turn waits, so an
288
- * open Turn here waits for OAuth or was left open by a failed or stopped Run.
289
- * The caller persists `conversation`. Returns false when `isStopped` turns
290
- * true first.
291
- */
292
- async function supersedeOpenMailboxTurns(args) {
293
- return await supersedeTurns({
294
- ...args,
295
- turns: (await listActiveMailboxTurns(args.conversationId)).filter((record) => record.turnId !== args.keepTurnId)
296
- });
297
- }
298
- /**
299
- * End open Turns that new input replaces. A late resume or OAuth callback
300
- * for an ended Turn is a no-op. The caller persists `conversation`. Returns
301
- * false when `isStopped` turns true first.
302
- */
303
- async function supersedeTurns(args) {
304
- const pendingAuthorizationActorId = args.conversation.processing.pendingAuth?.actorId;
305
- for (const stale of args.turns) {
306
- if (args.isStopped?.()) return false;
307
- await abandonTurnRecord({
308
- conversationId: args.conversationId,
309
- turnId: stale.turnId,
310
- errorMessage: "Turn superseded by new input"
311
- });
312
- await getTurnLifecycle().complete({
313
- conversationId: args.conversationId,
314
- createdAtMs: Date.now(),
315
- outcome: "cancelled",
316
- turnId: stale.turnId
317
- });
318
- markTurnClosed({
319
- conversation: args.conversation,
320
- nowMs: Date.now(),
321
- sessionId: stale.turnId
322
- });
323
- }
324
- if (args.turns.some((record) => record.state === "paused" && record.resumeReason === "auth") && pendingAuthorizationActorId) await deleteWebAuthorization({
325
- actorId: pendingAuthorizationActorId,
326
- conversationId: args.conversationId
327
- });
328
- return true;
329
- }
330
- /**
331
- * End the Turn that waits for its next Run when `message` cannot join it, so
332
- * the message starts its own Turn instead of running with that Turn's Actor.
333
- * A stored legacy Turn without an Actor keeps taking the input.
334
- */
335
- async function supersedeTurnForInput(args) {
336
- const conversation = coerceThreadConversationState(await getPersistedThreadState(args.conversationId));
337
- const turnId = conversation.processing.activeTurnId;
338
- if (!turnId || !await getPausedTurnRequest({
339
- conversationId: args.conversationId,
340
- turnId
341
- })) return;
342
- const turn = await getTurnRecord(args.conversationId, turnId);
343
- if (!turn?.actor || canJoinTurn(turn, args.message)) return;
344
- await hydrateConversationMessages({
345
- conversation,
346
- conversationId: args.conversationId
347
- });
348
- await supersedeTurns({
349
- conversation,
350
- conversationId: args.conversationId,
351
- turns: [turn]
352
- });
353
- await persistThreadStateById(args.conversationId, { conversation });
354
- }
355
- // src/chat/automations/block-run.ts
356
- /**
357
- * Block the Automation of a run from a later Turn of the run, such as a Watch
358
- * Event or child result Turn. The dispatch Turn blocks through its dispatch
359
- * outcome. Its creator is told when the block is first stored.
360
- */
361
- async function blockRunAutomation(conversationId, blocked) {
362
- const dispatchId = getDispatchIdForConversation(conversationId);
363
- const automation = await readConversationAutomationRun(conversationId);
364
- if (!automation) {
365
- logWarn("automation.block.unresolved", { "gen_ai.conversation.id": conversationId });
366
- return;
367
- }
368
- const { automationId, kind } = automation;
369
- if (kind === "scheduled" ? await blockScheduledAutomation(getDb(), automationId, blocked.missing) : await blockEventAutomation(getDb(), automationId, blocked.missing)) await notifyAutomationBlocked({
370
- automationId,
371
- ...dispatchId ? { dispatchId } : void 0,
372
- kind,
373
- reason: blocked.missing
374
- });
375
- }
376
- // src/chat/task-execution/assistant-message.ts
377
- /** Store one assistant Message and its Agent history. */
378
- async function commitAssistantMessage(args) {
379
- const conversationMessageId = recordDeliveredAssistantMessage({
380
- cards: args.cards,
381
- conversation: args.conversation,
382
- sessionId: args.sessionId,
383
- source: args.source,
384
- text: args.text,
385
- userMessageId: args.userMessageId
386
- });
387
- if (args.deliveryResult?.providerMessageId) markConversationMessage(args.conversation, conversationMessageId, { slackTs: args.deliveryResult.providerMessageId });
388
- try {
389
- await persistWithRetry(() => commitAcceptedReply({
390
- ...args.agentMessage ? { agentMessage: args.agentMessage } : void 0,
391
- conversation: args.conversation,
392
- conversationMessageId,
393
- conversationId: args.conversationId,
394
- providerConversationBindings: args.deliveryResult?.providerConversationBindings
395
- }));
396
- } catch (error) {
397
- logException(error, "conversation.assistant.message_persist.failed");
398
- }
399
- }
400
- // src/chat/task-execution/turn-end-tasks.ts
401
- /**
402
- * The background work after a Turn ends: plugin session tasks, event search,
403
- * and Conversation metadata. A failure is logged, so this work never changes
404
- * the Turn's outcome.
405
- */
406
- async function runTask(message, conversationId, turnId) {
407
- try {
408
- await processPluginTask(message);
409
- } catch (error) {
410
- logException(error, "conversation.plugin.session_completion_task.failed", {
411
- conversationId,
412
- pluginName: message.plugin,
413
- taskName: message.name,
414
- turnId
415
- });
416
- }
417
- }
418
- /**
419
- * Run the work after one ended Turn. A completed Turn with session tasks
420
- * runs every session task, which includes event search and metadata. Any
421
- * other Turn indexes its events, and a completed one also updates its
422
- * metadata when its behavior asks for it, as a Thread's does.
423
- */
424
- async function runTurnEndTasks(args) {
425
- const { behavior, conversationId, turnId } = args;
426
- const params = {
427
- conversationId,
428
- sessionId: turnId
429
- };
430
- if (args.completed && behavior.sessionTasks) {
431
- try {
432
- await scheduleSessionCompletedPluginTasks(params, async (message) => {
433
- await runTask(message, conversationId, turnId);
434
- });
435
- } catch (error) {
436
- logException(error, "conversation.plugin.session_completion_task.failed", {
437
- conversationId,
438
- turnId
439
- });
440
- }
441
- return;
442
- }
443
- await indexEndedTurnEvents({
444
- conversationId,
445
- turnId
446
- });
447
- if (args.completed && behavior.conversationMetadata) await runTask({
448
- ...CONVERSATION_METADATA_TASK,
449
- params
450
- }, conversationId, turnId);
451
- }
452
- // src/chat/task-execution/turn-failure.ts
453
- function captureConversationTurnFailure(args) {
454
- const eventId = logException(args.error, `conversation.turn.${args.failureCode}`, {
455
- conversationId: args.conversationId,
456
- ...args.runId ? { runId: args.runId } : void 0,
457
- turnId: args.turnId
458
- });
459
- return typeof eventId === "string" ? eventId : void 0;
460
- }
461
- /**
462
- * Record a final-attempt failure on the Turn record, the Conversation, and
463
- * the Turn lifecycle, so the Turn ends failed and its update reaches the
464
- * starter and Watches. The caller still acknowledges the input.
465
- */
466
- async function failConversationTurn(args) {
467
- const { conversation, conversationId, failure, failureCode, runId, turnId, userMessageId } = args;
468
- const failureEventId = args.modelFailureCaptureAttempted && failureCode === "agent_run_failed" ? args.modelFailureEventId : captureConversationTurnFailure({
469
- conversationId,
470
- error: failure,
471
- failureCode,
472
- runId,
473
- turnId
474
- });
475
- try {
476
- const latest = await getTurnRecord(conversationId, turnId);
477
- if (latest) await failTurnRecord({
478
- conversationId,
479
- errorMessage: failure instanceof Error ? failure.message : String(failure),
480
- expectedVersion: latest.version,
481
- turnId
482
- });
483
- } catch (turnRecordError) {
484
- captureConversationTurnFailure({
485
- conversationId,
486
- error: turnRecordError,
487
- failureCode: "persistence_failed",
488
- runId,
489
- turnId
490
- });
491
- }
492
- try {
493
- markTurnFailed({
494
- conversation,
495
- nowMs: Date.now(),
496
- sessionId: turnId,
497
- userMessageId,
498
- markConversationMessage
499
- });
500
- await persistThreadStateById(conversationId, {
501
- conversation,
502
- sandboxRef: args.sandboxRef ?? null
503
- });
504
- } catch (persistenceError) {
505
- captureConversationTurnFailure({
506
- conversationId,
507
- error: persistenceError,
508
- failureCode: "persistence_failed",
509
- runId,
510
- turnId
511
- });
512
- }
513
- await args.lifecycle.fail({
514
- conversationId,
515
- createdAtMs: Date.now(),
516
- ...failureEventId ? { eventId: failureEventId } : void 0,
517
- failureCode,
518
- failureText: failure instanceof Error ? failure.message : String(failure),
519
- reportAs: args.reportAs,
520
- turnId
521
- });
522
- await indexEndedTurnEvents({
523
- conversationId,
524
- turnId
525
- });
526
- }
527
- // src/chat/task-execution/mailbox-input.ts
528
- /**
529
- * Return the Turn inputs of web Messages, one per non-empty Message, in
530
- * order. Each one becomes its own prompt content part. A Message that
531
- * records an answer becomes its Inbox item tag. A batch with only
532
- * attachments keeps one empty input, so the prompt still has an instruction.
533
- */
534
- async function webTurnInputs(messages) {
535
- const flat = (await mapBounded(messages, async (message) => {
536
- const inboxItem = await loadInboxItemInput(message.reviewItemChange);
537
- if (inboxItem) return [inboxItem];
538
- const text = message.text.trim();
539
- return text ? [{
540
- kind: "person",
541
- text
542
- }] : [];
543
- })).flat();
544
- return flat.length ? flat : [{
545
- kind: "person",
546
- text: ""
547
- }];
548
- }
549
- /**
550
- * Build the transcript Message for one web mailbox Message. Each web Message
551
- * keeps its own transcript Message and Inbox item change record, so the
552
- * dashboard shows what each Message did even when several share a Turn.
553
- */
554
- function webConversationMessage(message, author) {
555
- const attachments = readMessageAttachments(message.input.attachments);
556
- const { reviewItemChange } = message.input;
557
- return {
558
- id: message.inboundMessageId,
559
- role: "user",
560
- text: normalizeConversationText(message.input.text),
561
- createdAtMs: message.createdAtMs,
562
- author,
563
- ...message.input.authorIdentityId ? { authorIdentityId: message.input.authorIdentityId } : void 0,
564
- meta: {
565
- ...attachments.length ? { attachments } : void 0,
566
- explicitMention: true,
567
- ...reviewItemChange ? { reviewItemChanges: [reviewItemChange] } : void 0,
568
- source: "web"
569
- }
570
- };
571
- }
572
- /**
573
- * Build the transcript Messages of a new web Turn, in input order. The Turn
574
- * saves its first input unreplied. `message_handled` records the reply.
575
- */
576
- function webTurnInputMessages(batch) {
577
- return batch.map((entry, index) => {
578
- const message = webConversationMessage(entry.message, entry.author);
579
- return index === 0 ? {
580
- ...message,
581
- meta: {
582
- ...message.meta,
583
- replied: false
584
- }
585
- } : message;
586
- });
587
- }
588
- /**
589
- * Return the saved input Messages of a resumed Turn in input order. A web
590
- * batch saves each Message apart. An older Turn saved one joined Message, so
591
- * its other input ids have no saved Message.
592
- */
593
- function savedTurnInputMessages(conversation, turnMessage, inputMessageIds) {
594
- const saved = (inputMessageIds ?? []).flatMap((id) => conversation.messages.find((message) => message.id === id && message.role === "user") ?? []);
595
- return saved.some((message) => message.id === turnMessage.id) ? saved : [turnMessage];
596
- }
597
- /**
598
- * Render the Turn inputs of one new mailbox batch. A parent batch is the
599
- * parent's task. An Event batch also returns the
600
- * meta of its one saved Message. A web batch returns one transcript Message
601
- * per input.
602
- */
603
- async function mailboxTurnInputs(batch, fromParent) {
604
- const messages = batch.map((entry) => entry.message);
605
- if (fromParent) return {
606
- eventMeta: {},
607
- inputs: batch.map(({ message, requestText }) => ({
608
- kind: "runtime",
609
- text: message.input.text.trim(),
610
- ...requestText ? { requestText } : void 0
611
- })),
612
- webInputMessages: []
613
- };
614
- if (isEventMailboxMetadata(messages[0]?.input.metadata)) return {
615
- eventMeta: eventBatchMessageMeta(messages),
616
- inputs: renderEventBatchInputs(messages, await eventInboxItemInputs(messages)),
617
- webInputMessages: []
618
- };
619
- return {
620
- eventMeta: {},
621
- inputs: await webTurnInputs(messages.map((message) => message.input)),
622
- webInputMessages: webTurnInputMessages(batch)
623
- };
624
- }
625
- // src/chat/task-execution/web-steering.ts
626
- async function steeringMessageFromWeb(message, actor) {
627
- const storedAttachments = readMessageAttachments(message.input.attachments);
628
- const inboxItemInput = await loadInboxItemInput(message.input.reviewItemChange);
629
- return {
630
- actor: instructionActorFor(actor),
631
- ...inboxItemInput ? { kind: "runtime" } : void 0,
632
- provenance: instructionProvenanceFor(actor),
633
- text: inboxItemInput?.text ?? message.input.text.trim(),
634
- timestampMs: message.createdAtMs,
635
- ...storedAttachments.length ? { storedAttachments } : void 0
636
- };
637
- }
638
- /**
639
- * Drain steered web messages into the active web Turn.
640
- *
641
- * Only messages from the Turn Actor join. Steered messages from another
642
- * participant stay pending and start their own Turn next, so they never act
643
- * with this Actor's credentials.
644
- */
645
- function createWebSteeringDrain(args) {
646
- const { actor, author, context, conversation, turnId } = args;
647
- return async (accept) => {
648
- const accepted = [];
649
- await context.attempt.drain(async (pending) => {
650
- const joining = pending.filter((message) => message.source === "web" && message.input.authorId === actor.userId && legacyWebMailboxMetadataSchema.safeParse(message.input.metadata).success);
651
- if (joining.length === 0) return [];
652
- for (const message of joining) upsertConversationMessage(conversation, webConversationMessage(message, author));
653
- await persistConversationMessages({
654
- conversation,
655
- conversationId: context.conversationId
656
- });
657
- const saved = (await getTurnRecord(context.conversationId, turnId))?.piMessages ?? [];
658
- const messages = withoutSavedSteeringMessages(saved, await mapBounded(joining, (message) => steeringMessageFromWeb(message, actor)), buildSteeringPiMessage);
659
- if (messages.length > 0) {
660
- await accept(messages);
661
- accepted.push(...messages);
662
- }
663
- return joining.map((message) => message.inboundMessageId);
664
- });
665
- return accepted;
666
- };
667
- }
668
- // src/chat/task-execution/turn-credentials.ts
669
- /**
670
- * Return a saved timer creator subject when it is still valid here. The
671
- * timer's Watch belongs to this Conversation. It may also belong to an
672
- * ancestor when `fromParent`: the input is a parent message that passed its
673
- * sender check, so the child continues the work of the parent's timer Turn.
674
- */
675
- async function verifiedTimerWatchSubject(conversationId, subject, fromParent) {
676
- if (subject?.binding.type !== "timer-watch") return void 0;
677
- const watchConversationId = subject.binding.conversationId;
678
- if (watchConversationId !== conversationId && !(fromParent && (await readConversationLineage(conversationId)).some((entry) => entry.conversationId === watchConversationId))) return;
679
- return verifyTimerWatchCredentialSubject({
680
- conversationId: watchConversationId,
681
- subject,
682
- watchId: subject.binding.watchId
683
- }) ? subject : void 0;
684
- }
685
- /** Return the delegated subject that every input of a batch carries, if any. */
686
- function sharedDelegatedSubject(batch) {
687
- const subjects = batch.map((entry) => entry.credentialContext && "subject" in entry.credentialContext ? entry.credentialContext.subject : void 0);
688
- const first = subjects[0];
689
- return first && subjects.every((subject) => isDeepStrictEqual(subject, first)) ? first : void 0;
690
- }
691
- // src/chat/task-execution/conversation-turn.ts
692
- /** Run a mailbox Turn and store its assistant Messages. */
693
- var conversation_turn_exports = /* @__PURE__ */ __exportAll({ createConversationTurnWorker: () => createConversationTurnWorker });
694
- function stableHex(...parts) {
695
- return createHash("sha256").update(parts.join("\0")).digest("hex").slice(0, 24);
696
- }
697
- function hasLostTurnInputCommit(error) {
698
- const cause = getConversationTurnBoundaryError(error)?.cause ?? error;
699
- return isTurnInputCommitLostError(error) || isTurnInputCommitLostError(cause);
700
- }
701
- /**
702
- * Return the author Identity id that every batched input shares.
703
- * A batch with more than one author has no single author yet.
704
- */
705
- function sharedAuthorIdentityId(messages) {
706
- const ids = new Set(messages.map((message) => message.input.authorIdentityId));
707
- return ids.size === 1 ? [...ids][0] : void 0;
708
- }
709
- function turnAnswerText(reply) {
710
- if (reply.reply) return void 0;
711
- if (reply.blocked) return {
712
- kind: "note",
713
- text: reply.blocked.missing
714
- };
715
- if (reply.noReply) return {
716
- kind: "note",
717
- text: reply.noReply.note ?? ""
718
- };
719
- const text = reply.text.trim();
720
- return text ? {
721
- kind: "final_text",
722
- text
723
- } : void 0;
724
- }
725
- /**
726
- * Create the shared mailbox worker for web and event Turns of every
727
- * Conversation kind. `deliverMessage` posts to a Location. `updates` is
728
- * where each Turn's agent update goes, to the starter of a child agent and
729
- * to the Watches of any Conversation, by default the production queue.
730
- */
731
- function createConversationTurnWorker(agentRunner, deliverMessage, updates) {
732
- const lifecycle = updates ? new ConversationTurnLifecycleService(getConversationEventStore(), {
733
- state: updates.state,
734
- watchQueue: () => updates.queue
735
- }) : getTurnLifecycle();
736
- return async (context, resolved) => {
737
- if (resolved.kind === "mailbox") {
738
- const delayMs = getEventBatchDelayMs(resolved.batch.map((entry) => entry.message));
739
- if (delayMs > 0) return {
740
- status: "deferred",
741
- delayMs
742
- };
743
- }
744
- const isResume = resolved.kind === "resume";
745
- let turnInputFacts;
746
- let inputs = [];
747
- let attachments = [];
748
- let turnId = "";
749
- let userMessageId = "";
750
- let startedAtMs = Date.now();
751
- let inputMessageIds = [];
752
- let eventMeta = {};
753
- let fromParent = resolved.kind === "mailbox" && resolved.batch.every((entry) => readParentMessage(entry.message));
754
- let fromChildAgent = false;
755
- let authorIdentityId;
756
- let webInputMessages = [];
757
- const storedConversation = await getConversationStore().get({ conversationId: context.conversationId });
758
- const kind = storedConversation?.kind ?? "thread";
759
- const visibility = isTopLevel({ parentConversationId: storedConversation?.parentConversationId }) ? storedConversation?.visibility : storedConversation?.visibility ?? "private";
760
- const mailboxDestination = resolved.kind === "mailbox" ? resolved.batch[0]?.message.destination : void 0;
761
- const destination = resolveConversationDestination({
762
- conversationId: context.conversationId,
763
- existing: context.destination ?? mailboxDestination ?? storedConversation?.destination
764
- });
765
- if (resolved.kind === "mailbox") {
766
- const first = resolved.batch[0];
767
- const messages = resolved.batch.map((entry) => entry.message);
768
- ({eventMeta, inputs, webInputMessages} = await mailboxTurnInputs(resolved.batch, fromParent));
769
- fromChildAgent = isChildAgentEvent(eventMeta);
770
- attachments = resolved.batch.flatMap((entry) => readMessageAttachments(entry.message.input.attachments));
771
- startedAtMs = first.message.createdAtMs;
772
- userMessageId = first.message.inboundMessageId;
773
- turnId = buildDeterministicTurnId(userMessageId);
774
- inputMessageIds = resolved.batch.map((entry) => entry.message.inboundMessageId);
775
- authorIdentityId = sharedAuthorIdentityId(messages);
776
- turnInputFacts = first;
777
- } else turnId = resolved.turnId;
778
- const persisted = await getPersistedThreadState(context.conversationId);
779
- const conversation = coerceThreadConversationState(persisted);
780
- await hydrateConversationMessages({
781
- conversation,
782
- conversationId: context.conversationId
783
- });
784
- const savedTurn = isResume ? await getTurnRecord(context.conversationId, turnId) : void 0;
785
- let savedMessageIsEvent = false;
786
- if (isResume) {
787
- const userMessage = getTurnUserMessage(conversation, turnId);
788
- if (!userMessage) throw new Error(`Unable to locate the persisted user message for Turn "${turnId}"`);
789
- savedMessageIsEvent = isEventConversationMessage(userMessage);
790
- fromParent = isParentMessageAuthor(userMessage.author);
791
- fromChildAgent = isChildAgentEvent(userMessage.meta);
792
- turnInputFacts = turnInputFactsFromConversationMessage(userMessage, {
793
- conversationId: context.conversationId,
794
- location: storedConversation?.location,
795
- savedActor: savedTurn?.actor,
796
- savedSource: savedTurn?.source,
797
- visibility: storedConversation?.visibility
798
- });
799
- const turnInputs = savedTurnInputMessages(conversation, userMessage, await lifecycle.loadInputMessageIds(context.conversationId, turnId));
800
- userMessageId = userMessage.id;
801
- inputs = savedMessageIsEvent || fromParent ? [{
802
- kind: "runtime",
803
- text: userMessage.text,
804
- ...userMessage.meta?.requestText ? { requestText: userMessage.meta.requestText } : void 0
805
- }] : await webTurnInputs(turnInputs.map((message) => ({
806
- reviewItemChange: message.meta?.reviewItemChanges?.[0],
807
- text: message.text
808
- })));
809
- attachments = turnInputs.flatMap((message) => message.meta?.attachments ?? []);
810
- startedAtMs = userMessage.createdAtMs;
811
- inputMessageIds = turnInputs.map((message) => message.id);
812
- }
813
- if (!turnInputFacts) throw new Error(`Resumed Turn is missing an Actor for Conversation ${context.conversationId}`);
814
- const { actor, author } = turnInputFacts;
815
- const instructionInputs = instructionForInputs(inputs);
816
- const { text } = instructionInputs;
817
- const instructionActor = instructionActorFor(actor);
818
- let credentialSubject;
819
- if (actor.platform === "system") credentialSubject = resolved.kind === "mailbox" ? timerWatchCredentialSubject(context.conversationId, resolved.batch.map((entry) => entry.message)) ?? await verifiedTimerWatchSubject(context.conversationId, sharedDelegatedSubject(resolved.batch), fromParent) : await verifiedTimerWatchSubject(context.conversationId, savedTurn?.credentialSubject, fromParent);
820
- const source = sourceFromTurnInput({
821
- conversationId: context.conversationId,
822
- source: turnInputFacts.source,
823
- visibility
824
- });
825
- const conversationLocation = storedConversation?.location;
826
- const isEventTurn = source.kind === "event" || savedMessageIsEvent;
827
- const postsToProvider = Boolean(conversationLocation) && isEventTurn;
828
- const behavior = turnBehavior({
829
- kind,
830
- hasParent: !isTopLevel({ parentConversationId: storedConversation?.parentConversationId }),
831
- personInput: isPersonInput(source.kind)
832
- });
833
- const webActor = actor.platform === "web" ? actor : void 0;
834
- const signInActor = behavior.waitsForSignIn ? webActor : void 0;
835
- const disabledFeatures = signInActor ? [] : ["interactive-auth"];
836
- const deliverToProvider = postsToProvider && (behavior.delivery === "location" || !behavior.gated && storedConversation !== void 0 && ownsLocation(storedConversation));
837
- const surface = postsToProvider ? "slack" : "api";
838
- const inputTelemetry = resolved.kind === "mailbox" ? turnInputTelemetry(resolved.batch.map((entry) => entry.message)) : void 0;
839
- const turnTrace = inputTelemetry ?? (savedTurn?.traceContext ? { traceContexts: [savedTurn.traceContext] } : void 0);
840
- return await withTurnSpan({
841
- conversationId: context.conversationId,
842
- platform: actor.platform,
843
- ...webActor ? {
844
- userId: webActor.userId,
845
- ...webActor.userName ? { userName: webActor.userName } : void 0
846
- } : void 0
847
- }, turnTrace, async (setTurnSpanAttributes) => {
848
- if (inputTelemetry) setTurnSpanAttributes(getTurnInputSpanAttributes(inputTelemetry, Date.now()));
849
- let acknowledged = isResume || context.attempt.messages.length === 0;
850
- const acknowledge = async () => {
851
- if (acknowledged) return;
852
- try {
853
- await context.attempt.ack();
854
- } catch {
855
- throw new TurnInputCommitLostError(`Conversation work lease lost before mailbox Message acknowledgement for ${context.conversationId}`);
856
- }
857
- acknowledged = true;
858
- };
859
- let sandboxRef = getPersistedSandboxState(persisted);
860
- const initialSandboxRef = sandboxRef;
861
- const stopSignal = context.stopSignal?.();
862
- const completeCancelledTurn = async () => {
863
- try {
864
- await completeCancelledConversationTurn({
865
- acknowledge,
866
- conversation,
867
- conversationId: context.conversationId,
868
- sandboxRef,
869
- turnId,
870
- userMessageId
871
- });
872
- } catch (error) {
873
- if (hasLostTurnInputCommit(error)) return { status: "lost_lease" };
874
- throw error;
875
- }
876
- await indexEndedTurnEvents({
877
- conversationId: context.conversationId,
878
- turnId
879
- });
880
- return { status: "completed" };
881
- };
882
- if (isResume) {
883
- if (stopSignal?.aborted) return await completeCancelledTurn();
884
- } else {
885
- for (const message of webInputMessages) upsertConversationMessage(conversation, message);
886
- if (webInputMessages.length === 0) {
887
- const requestText = turnRequestText({ instruction: instructionInputs });
888
- upsertConversationMessage(conversation, {
889
- id: userMessageId,
890
- role: "user",
891
- text: normalizeConversationText(text),
892
- createdAtMs: startedAtMs,
893
- author,
894
- ...authorIdentityId ? { authorIdentityId } : void 0,
895
- meta: {
896
- ...attachments.length ? { attachments } : void 0,
897
- explicitMention: true,
898
- replied: false,
899
- ...requestText ? { requestText } : void 0,
900
- ...eventMeta
901
- }
902
- });
903
- }
904
- await persistConversationMessages({
905
- conversation,
906
- conversationId: context.conversationId
907
- });
908
- await commitParentMessageFork({
909
- conversationId: context.conversationId,
910
- inputs: resolved.batch.map((entry) => entry.message)
911
- });
912
- await lifecycle.start({
913
- conversationId: context.conversationId,
914
- createdAtMs: Date.now(),
915
- inputMessageIds,
916
- surface,
917
- threadContextThroughSeq: latestConversationMessageSeq(conversation),
918
- turnId
919
- });
920
- if (stopSignal?.aborted) return await completeCancelledTurn();
921
- startActiveTurn({
922
- conversation,
923
- nextTurnId: turnId
924
- });
925
- }
926
- let currentRunId;
927
- let assistantMessageDelivered = false;
928
- let failureCode = "persistence_failed";
929
- let modelFailureEventId;
930
- let modelFailureCaptureAttempted = false;
931
- let completedSuccessfully = false;
932
- const deliverAssistantMessage = async (value, options) => {
933
- const agentMessage = typeof value === "string" ? void 0 : value;
934
- const replyText = typeof value === "string" ? value : getAssistantReplyText(value);
935
- if (!replyText?.trim()) return;
936
- failureCode = "delivery_failed";
937
- const cards = await loadPendingMessageCards(context.conversationId);
938
- let deliveryResult;
939
- if ((options?.reply ? postsToProvider : deliverToProvider) && !await isConversationDeliveryPaused(context.conversationId)) {
940
- if (!conversationLocation || !deliverMessage) throw new Error(`Conversation ${context.conversationId} cannot deliver to its Location`);
941
- deliveryResult = await deliverMessage({
942
- cards,
943
- conversationId: context.conversationId,
944
- location: conversationLocation,
945
- text: replyText
946
- });
947
- }
948
- await commitAssistantMessage({
949
- cards,
950
- ...agentMessage ? { agentMessage } : void 0,
951
- conversation,
952
- conversationId: context.conversationId,
953
- ...deliveryResult ? { deliveryResult } : void 0,
954
- sessionId: turnId,
955
- ...deliveryResult ? { source: "slack" } : source.kind === "web" ? { source: "web" } : void 0,
956
- text: replyText,
957
- userMessageId
958
- });
959
- assistantMessageDelivered = true;
960
- failureCode = "agent_run_failed";
961
- };
962
- try {
963
- if (stopSignal?.aborted) return await completeCancelledTurn();
964
- if (!isResume && !await supersedeOpenMailboxTurns({
965
- conversation,
966
- conversationId: context.conversationId,
967
- isStopped: () => Boolean(stopSignal?.aborted),
968
- keepTurnId: turnId
969
- })) return await completeCancelledTurn();
970
- await persistThreadStateById(context.conversationId, { conversation });
971
- if (stopSignal?.aborted) return await completeCancelledTurn();
972
- const childTurn = await childAgentTurnOptions({
973
- actor,
974
- conversationId: context.conversationId,
975
- fromChildAgent,
976
- fromParent
977
- });
978
- const history = await loadConversationProjection({ conversationId: context.conversationId });
979
- failureCode = "agent_run_failed";
980
- currentRunId = `conversation-run:${stableHex(turnId, String(startedAtMs))}`;
981
- setTags({ runId: currentRunId });
982
- const outcome = await executeTurn(agentRunner, {
983
- conversationId: context.conversationId,
984
- ...storedConversation?.parentConversationId ? { parentConversationId: storedConversation.parentConversationId } : void 0,
985
- turnId,
986
- runId: currentRunId,
987
- instruction: {
988
- ...instructionInputs,
989
- ...instructionActor ? { actor: instructionActor } : void 0,
990
- ...childTurn.instruction,
991
- storedAttachments: attachments,
992
- context: await buildTurnThreadContext({
993
- conversation,
994
- conversationId: context.conversationId,
995
- excludeMessageIds: inputMessageIds,
996
- hasHistory: history.messages.length > 0,
997
- turnId
998
- })
999
- },
1000
- history,
1001
- ...childTurn.run,
1002
- actor,
1003
- credentialContext: credentialContextForActor(actor, credentialSubject),
1004
- destination,
1005
- source,
1006
- ...conversationLocation ? { location: conversationLocation } : void 0,
1007
- surface,
1008
- ...stopSignal ? { signal: stopSignal } : void 0,
1009
- ...signInActor ? { authorization: createWebAuthorization({
1010
- actorId: signInActor.userId,
1011
- conversationId: context.conversationId
1012
- }) } : void 0,
1013
- ...disabledFeatures.length > 0 ? { disabledFeatures } : void 0,
1014
- state: {
1015
- pendingAuth: conversation.processing.pendingAuth,
1016
- sandboxRef
1017
- },
1018
- delivery: deliverAssistantMessage,
1019
- durability: {
1020
- ...webActor ? { drainSteeringMessages: createWebSteeringDrain({
1021
- actor: webActor,
1022
- author,
1023
- context,
1024
- conversation,
1025
- turnId
1026
- }) } : void 0,
1027
- onInputCommitted: acknowledge,
1028
- shouldYield: context.shouldYield,
1029
- checkIn: context.checkIn,
1030
- checkStop: context.checkStop,
1031
- onSandboxRefChanged: async (nextSandboxRef) => {
1032
- sandboxRef = nextSandboxRef;
1033
- await persistThreadStateById(context.conversationId, {
1034
- conversation,
1035
- sandboxRef
1036
- });
1037
- },
1038
- recordPendingAuth: async (pendingAuth) => {
1039
- conversation.processing.pendingAuth = pendingAuth;
1040
- await persistThreadStateById(context.conversationId, {
1041
- conversation,
1042
- sandboxRef
1043
- });
1044
- }
1045
- }
1046
- }, async (result) => {
1047
- if (stopSignal?.aborted) throw stopSignal.reason ?? new DOMException("Turn cancelled", "AbortError");
1048
- modelFailureCaptureAttempted = result.diagnostics.outcome !== "success";
1049
- const finalized = finalizeFailedTurnReplyWithEvent({ reply: result });
1050
- const modelFailureReason = finalized.failureReason;
1051
- const reply = finalized.reply;
1052
- modelFailureEventId = finalized.eventId;
1053
- if (reply.diagnostics.outcome !== "success") await deliverAssistantMessage(reply.text);
1054
- else if (reply.reply) await deliverAssistantMessage(reply.reply.text, { reply: true });
1055
- else if (reply.blocked && behavior.tools.reportBlocked === "automation") await blockRunAutomation(context.conversationId, reply.blocked);
1056
- const completedState = buildDeliveredTurnStatePatch({
1057
- conversation,
1058
- reply,
1059
- sessionId: turnId,
1060
- userMessageId
1061
- });
1062
- await persistThreadStateById(context.conversationId, {
1063
- conversation: completedState.conversation,
1064
- sandboxRef: reply.sandboxRef ?? sandboxRef
1065
- });
1066
- if (reply.piMessages?.length) {
1067
- const latest = await getTurnRecord(context.conversationId, turnId);
1068
- await saveTurnCheckpoint({
1069
- mode: "completed",
1070
- conversationId: context.conversationId,
1071
- turnId,
1072
- sliceId: latest?.sliceId ?? 1,
1073
- messages: reply.piMessages,
1074
- durationMs: reply.diagnostics.durationMs,
1075
- usage: reply.diagnostics.usage,
1076
- destination,
1077
- source,
1078
- actor,
1079
- surface
1080
- });
1081
- }
1082
- if (fromParent) await resetAutomatedTurnLimit({ conversationId: context.conversationId });
1083
- else {
1084
- const automatedTurnLimit = await recordFinishedTurnForAutomatedLimit({
1085
- conversationId: context.conversationId,
1086
- maxTurns: botConfig.maxConsecutiveAutomatedTurns,
1087
- source
1088
- });
1089
- await stopAtAutomatedTurnLimit({
1090
- conversationId: context.conversationId,
1091
- maxTurns: botConfig.maxConsecutiveAutomatedTurns,
1092
- source,
1093
- update: automatedTurnLimit
1094
- });
1095
- }
1096
- completedSuccessfully = reply.diagnostics.outcome === "success";
1097
- const delivered = assistantMessageDelivered ? "success" : "no_reply";
1098
- const answer = turnAnswerText(reply);
1099
- return completedSuccessfully ? {
1100
- ...answer ? { answer } : void 0,
1101
- outcome: reply.blocked ? "blocked" : delivered
1102
- } : {
1103
- ...modelFailureEventId ? { eventId: modelFailureEventId } : void 0,
1104
- failureCode: "model_execution_failed",
1105
- ...modelFailureReason ? { failureReason: modelFailureReason } : void 0,
1106
- failureText: reply.diagnostics.errorMessage ?? reply.text,
1107
- outcome: "failed"
1108
- };
1109
- }, lifecycle);
1110
- if (outcome.status !== "completed" && stopSignal?.aborted) return await completeCancelledTurn();
1111
- if (outcome.status === "suspended") return { status: "yielded" };
1112
- if (outcome.status === "awaiting_auth") {
1113
- completeAuthPauseTurn({
1114
- conversation,
1115
- sessionId: turnId
1116
- });
1117
- await persistThreadStateById(context.conversationId, {
1118
- conversation,
1119
- sandboxRef
1120
- });
1121
- await acknowledge();
1122
- return { status: "paused" };
1123
- }
1124
- await runTurnEndTasks({
1125
- behavior,
1126
- completed: completedSuccessfully,
1127
- conversationId: context.conversationId,
1128
- turnId
1129
- });
1130
- await acknowledge();
1131
- return { status: "completed" };
1132
- } catch (error) {
1133
- const failure = error instanceof AgentRunError ? error.cause : error;
1134
- if (hasLostTurnInputCommit(failure)) return { status: "lost_lease" };
1135
- if (stopSignal?.aborted) return await completeCancelledTurn();
1136
- if (!context.attempt.isFinalAttempt) throw failure;
1137
- await failConversationTurn({
1138
- conversation,
1139
- conversationId: context.conversationId,
1140
- failure,
1141
- failureCode,
1142
- lifecycle,
1143
- modelFailureCaptureAttempted,
1144
- modelFailureEventId,
1145
- reportAs: parentResultActor(actor, source.kind),
1146
- runId: currentRunId,
1147
- sandboxRef: initialSandboxRef,
1148
- turnId,
1149
- userMessageId
1150
- });
1151
- await acknowledge();
1152
- return { status: "completed" };
1153
- }
1154
- });
1155
- };
1156
- }
1157
- export { recordFinishedTurnForAutomatedLimit as a, getTurnInputSpanAttributes as c, stopAtAutomatedTurnLimit as i, turnInputTelemetry as l, createConversationTurnWorker as n, AgentRunError as o, supersedeTurnForInput as r, executeTurn as s, conversation_turn_exports as t, withTurnSpan as u };