@sentry/junior 0.313.0 → 0.314.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 (108) hide show
  1. package/dist/{adapter-CYAvJzZS.js → adapter-JARQvoLw.js} +1 -2
  2. package/dist/{adapter-context-CVsHoVSf.js → adapter-context-B4BrJZuS.js} +2 -2
  3. package/dist/{admin-Cyhb4TwZ.js → admin-BXGAySz0.js} +1 -1
  4. package/dist/{agent-runner-B5y9MsT-.js → agent-runner-qZU5TR8i.js} +797 -118
  5. package/dist/agent-update-cS7Z9mnG.js +26 -0
  6. package/dist/agent-update-delivery-CZ5M8RDa.js +85 -0
  7. package/dist/api/schema.d.ts +2 -2
  8. package/dist/api/schema.js +6 -6
  9. package/dist/api.d.ts +1 -1
  10. package/dist/api.js +334 -100
  11. package/dist/{app-DA8-hCMj.d.ts → app-D7tKnw9a.d.ts} +4 -21
  12. package/dist/app.d.ts +2 -2
  13. package/dist/app.js +80 -169
  14. package/dist/{background-compaction-queue-iZXadLV3.js → background-compaction-queue-C_uIBUvS.js} +6 -67
  15. package/dist/callback-C8SdXCwr.js +68 -0
  16. package/dist/{catalog-runtime-kkE3hvCX.js → catalog-runtime-BLKtnUL3.js} +1 -1
  17. package/dist/{channel-access-mt7K6dPh.js → channel-access-BOL29BG3.js} +6 -6
  18. package/dist/child-message--2G3Ft26.js +19 -0
  19. package/dist/cli/chat.js +18 -21
  20. package/dist/cli/check.js +4 -4
  21. package/dist/cli/main.js +2 -2
  22. package/dist/cli/plugins.js +5 -5
  23. package/dist/cli/snapshot-create.js +5 -5
  24. package/dist/cli/upgrade.d.ts +1 -1
  25. package/dist/cli/upgrade.js +23 -4
  26. package/dist/{config-CWbwKj0j.js → config-BIfHKNXN.js} +40 -35
  27. package/dist/{continue-in-slack-CxyFzdlF.js → continue-in-slack-fnmD2Ifb.js} +5 -7
  28. package/dist/{conversation-feed-BEXLD3Me.js → conversation-feed-DdFQuQDR.js} +1 -1
  29. package/dist/{logging-DNt-qOIO.js → conversation-privacy-DtZhI91r.js} +188 -2
  30. package/dist/{conversation-turn-B35eu0uz.js → conversation-turn-DScuDYmN.js} +418 -33
  31. package/dist/create-CrNt4Ewu.js +212 -0
  32. package/dist/{credential-sync-DWTOEQrm.js → credential-sync-CtqsGjj1.js} +14 -17
  33. package/dist/{credentialed-Dyv8b-lu.js → credentialed-dWRA3-oJ.js} +910 -426
  34. package/dist/{db-PwSRzWWn.js → db-BTmLKZrp.js} +2235 -38
  35. package/dist/{db-DYGcXYl3.d.ts → db-DcmzbA55.d.ts} +2 -2
  36. package/dist/{history-CYstOMKX.js → history-CneKY7_V.js} +19 -1
  37. package/dist/{html-DidUcRhI.js → html-B8rBt7F4.js} +5 -7
  38. package/dist/{install-2urLLXNt.js → install-OtFboxOM.js} +2 -2
  39. package/dist/instrumentation.js +2 -2
  40. package/dist/{lineage-BXplQAVH.js → lineage-EULJkGO1.js} +1 -2
  41. package/dist/{list-DyIyReSV.js → list-C5400AlJ.js} +235 -77
  42. package/dist/{turn-membership-DTR3SaKD.js → mailbox-turn-DL3Lvsm0.js} +4698 -587
  43. package/dist/markers-DUP8aBOp.js +323 -0
  44. package/dist/{media-B0pZJ0bG.js → media-FYM-Bl3H.js} +33 -8
  45. package/dist/{message-Z5YKC-Af.js → message-DuDelZFr.js} +16 -29
  46. package/dist/{model-input-BhPJYdSV.js → model-input-0osF3pBS.js} +3 -3
  47. package/dist/nitro.d.ts +2 -4
  48. package/dist/nitro.js +340 -13
  49. package/dist/{oauth-callback-server-ByvDdcdY.js → oauth-callback-server-DX2fQ7Nq.js} +2 -2
  50. package/dist/{oauth-relay-D-kK0yoN.js → oauth-relay-PwPMdZJv.js} +1 -1
  51. package/dist/{plugins-Bkk0XRo2.js → plugins-BXMdNdyA.js} +1 -1
  52. package/dist/{registry-POH4bZC4.js → registry-D6kS6xYH.js} +1402 -64
  53. package/dist/{resolve-CWtBNSKP.js → resolve-D8CPJcNK.js} +3 -3
  54. package/dist/result-D090hxr5.js +402 -0
  55. package/dist/{runner-CsZ_VRxp.js → runner-BU7fgrm-.js} +7 -8
  56. package/dist/{sandbox-egress-signals-FbCk1FkN.js → sandbox-egress-signals-BUmVrsoG.js} +1 -1
  57. package/dist/{schema-DojR2uCL.js → schema-7gW9vBpJ.js} +90 -9
  58. package/dist/{schema-DBf18QPS.d.ts → schema-BB6E0wyV.d.ts} +138 -5
  59. package/dist/{service-account-CDYb9hfX.js → service-account-plA-uzIB.js} +6 -5
  60. package/dist/{skills-B0jP4whm.js → skills-CIosT6bS.js} +3 -3
  61. package/dist/{slack-conversation-unfurl-D26t9kBC.js → slack-conversation-unfurl-CBgZqth6.js} +8 -10
  62. package/dist/{spawn-BjljgExZ.js → spawn-DRjdzh3R.js} +9 -17
  63. package/dist/{start-conversation-DbVujrwO.js → start-conversation-a4NXH4X9.js} +12 -15
  64. package/dist/{store-CjXrp-Up.js → store-BuhF1QDm.js} +2 -4
  65. package/dist/{task-queue-Cwlatjz3.js → task-queue-CrRjFzOh.js} +5 -16
  66. package/dist/{task-runner--Ke8KSMf.js → task-runner-C-pXsgHM.js} +104 -50
  67. package/dist/{thread-context-B8exINEe.js → thread-context-CDX4dSZd.js} +8 -9
  68. package/dist/turn-session-routing-CZTRU8IY.js +116 -0
  69. package/dist/turn-wake-Bzq1Efrm.js +154 -0
  70. package/dist/user-customization-B27StpVQ.js +9 -0
  71. package/dist/{validation-Ce0qbMlT.js → validation-bTq88sya.js} +1 -1
  72. package/dist/{vercel-queue-q4z8w5QO.js → vercel-queue-nL0Hq3hr.js} +32 -147
  73. package/dist/{version-DFh4n9nr.js → version-DGUa1dZK.js} +1 -1
  74. package/dist/version.js +1 -1
  75. package/dist/{warmup-D5hzqTcp.js → warmup-CCOuIwAS.js} +639 -137
  76. package/dist/{worker-CDg9Lbpg.js → worker-AkZg7Dg1.js} +5 -6
  77. package/migrations/0160_money_micro_usd_repair.sql +99 -0
  78. package/migrations/0161_agent_config_backfill.sql +34 -0
  79. package/migrations/0162_inbox_item_deliveries.sql +15 -0
  80. package/migrations/0163_pg_trgm.sql +2 -0
  81. package/migrations/0164_search_indexes.sql +4 -0
  82. package/migrations/0165_drop_legacy_archive_columns.sql +4 -0
  83. package/migrations/0166_memory_prefix_index.sql +1 -0
  84. package/migrations/0167_todo_search_indexes.sql +2 -0
  85. package/migrations/0168_todo_inbox_items.sql +4 -0
  86. package/migrations/0169_drop_code_urls.sql +2 -0
  87. package/migrations/meta/0160_snapshot.json +6515 -0
  88. package/migrations/meta/0161_snapshot.json +6278 -0
  89. package/migrations/meta/0162_snapshot.json +6404 -0
  90. package/migrations/meta/0163_snapshot.json +6404 -0
  91. package/migrations/meta/0164_snapshot.json +6466 -0
  92. package/migrations/meta/0165_snapshot.json +6466 -0
  93. package/migrations/meta/0166_snapshot.json +6494 -0
  94. package/migrations/meta/0167_snapshot.json +6525 -0
  95. package/migrations/meta/0168_snapshot.json +6525 -0
  96. package/migrations/meta/0169_snapshot.json +6513 -0
  97. package/migrations/meta/_journal.json +70 -0
  98. package/package.json +9 -18
  99. package/skills/design-automation-skill/SKILL.md +2 -3
  100. package/dist/actor-BsBdxDXQ.js +0 -208
  101. package/dist/conversation-privacy-BrMiDN61.js +0 -189
  102. package/dist/executor-CgWyWfYz.js +0 -1858
  103. package/dist/fan-out-Cod-yEHG.js +0 -10
  104. package/dist/ingest-B0AggUEC.js +0 -7931
  105. package/dist/request-deadline-BUiRYQYj.js +0 -24
  106. package/dist/service-account-o15pZWcJ.js +0 -931
  107. package/dist/state-BTawTCme.js +0 -161
  108. package/dist/statuses-BKwqCPhj.js +0 -69
@@ -1,21 +1,23 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { Ii as blockEventAutomation, To as verifyTimerWatchCredentialSubject, Tr as readConversationAutomationRun, Ur as notifyAutomationBlocked, jr as getDispatchIdForConversation, mi as blockScheduledAutomation } from "./credentialed-Dyv8b-lu.js";
3
- import { A as isTopLevelKind, F as turnBehavior, O as isPersonInput, a as getConversationStore, o as getDb } from "./db-PwSRzWWn.js";
4
- import { E as withSpan, S as setTags, h as logWarn, p as logException } from "./logging-DNt-qOIO.js";
5
- import { kt as readMessageAttachments } from "./media-B0pZJ0bG.js";
6
- import { C as isConversationDeliveryPaused } from "./agent-runner-B5y9MsT-.js";
7
- import { a as buildDeliveredTurnStatePatch, o as loadPendingMessageCards, r as completeAuthPauseTurn, t as buildTurnThreadContext } from "./thread-context-B8exINEe.js";
8
- import { Bt as getTurnUserMessage, Ct as isEventMailboxMetadata, E as stopAtAutomatedTurnLimit, Jt as getConversationTurnBoundaryError, Kt as TurnInputCommitLostError, Q as recordChildAgentEnded, St as eventBatchMessageMeta, Tt as timerWatchCredentialSubject, Xt as isTurnInputCommitLostError, _t as resetAutomatedTurnLimit, an as eventInboxItemInputs, d as legacyWebMailboxMetadataSchema, dn as instructionActorFor, en as markTurnFailed, f as childAgentTurnOptions, fn as instructionForInputs, gt as recordFinishedTurnForAutomatedLimit, hn as withoutSavedSteeringMessages, l as sourceFromTurnInput, m as isParentMessageAuthor, mn as turnRequestText, nn as createWebAuthorization, on as loadInboxItemInput, p as commitParentMessageFork, s as getEventBatchDelayMs, tn as startActiveTurn, u as turnInputFactsFromConversationMessage, un as buildSteeringPiMessage, v as supersedeOpenMailboxTurns, vt as AgentRunError, wt as renderEventBatchInputs, yt as executeTurn, zt as completeCancelledConversationTurn } from "./ingest-B0AggUEC.js";
9
- import { Cn as readParentMessage, Ct as recordDeliveredAssistantMessage, Et as upsertConversationMessage, In as finalizeFailedTurnReplyWithEvent, K as buildDeterministicTurnId, Mt as isEventConversationMessage, Qt as saveTurnCheckpoint, St as normalizeConversationText, X as loadConversationProjection, bt as latestConversationMessageSeq, d as getPersistedThreadState, dr as persistWithRetry, ft as persistConversationMessages, m as coerceThreadConversationState, p as persistThreadStateById, q as commitAcceptedReply, rn as getTurnRecord, tn as failTurnRecord, tr as getAssistantReplyText, u as getPersistedSandboxState, ut as hydrateConversationMessages, wn as getTurnLifecycle, xt as markConversationMessage } from "./turn-membership-DTR3SaKD.js";
10
- import { p as credentialContextForActor } from "./registry-POH4bZC4.js";
2
+ import { Gr as getDispatchIdForConversation, Oi as blockScheduledAutomation, Wo as verifyTimerWatchCredentialSubject, Xi as blockEventAutomation, ri as notifyAutomationBlocked, xs as JUNIOR_THREAD_STATE_TTL_MS, zr as readConversationAutomationRun } from "./credentialed-dWRA3-oJ.js";
3
+ import { L as isPersonInput, W as turnBehavior, a as getDb, i as getConversationStore, z as isTopLevelKind } from "./db-BTmLKZrp.js";
4
+ import { F as withSpan, S as logException, j as setTags, w as logWarn } from "./conversation-privacy-DtZhI91r.js";
5
+ import { kt as readMessageAttachments } from "./media-FYM-Bl3H.js";
6
+ import { E as sendSlackReply, T as resolveSlackReplyTarget, j as isConversationDeliveryPaused } from "./agent-runner-qZU5TR8i.js";
7
+ import { a as buildDeliveredTurnStatePatch, o as loadPendingMessageCards, r as completeAuthPauseTurn, t as buildTurnThreadContext } from "./thread-context-CDX4dSZd.js";
8
+ import { $r as failTurnRecord, Ar as isEventConversationMessage, At as claimInboundMessage, Bt as getConversationWorkState, Cr as recordDeliveredAssistantMessage, Er as upsertConversationMessage, F as renderEventBatchInputs, I as timerWatchCredentialSubject, Jn as commitAcceptedReply, Mi as finalizeFailedTurnReplyWithEvent, N as eventBatchMessageMeta, On as buildDeterministicTurnId, P as isEventMailboxMetadata, Q as getTurnUserMessage, Rt as ensureConversationWake, Sr as normalizeConversationText, X as stopConversationTree, Xr as saveTurnCheckpoint, Xt as eventInboxItemInputs, Z as completeCancelledConversationTurn, Zi as getAssistantReplyText, Zn as loadConversationProjection, Zr as abandonTurnRecord, Zt as loadInboxItemInput, an as turnRequestText, bi as readParentMessage, br as latestConversationMessageSeq, bt as createWebAuthorization, c as legacyWebMailboxMetadataSchema, ct as isTurnInputCommitLostError, d as childAgentTurnOptions, dr as hydrateConversationMessages, ei as getTurnRecord, f as commitParentMessageFork, ft as markTurnFailed, gi as canJoinTurn, gt as getPersistedThreadState, ht as getPersistedSandboxState, i as listActiveMailboxTurns, it as TurnInputCommitLostError, m as isParentMessageAuthor, n as getEventBatchDelayMs, nn as instructionActorFor, o as sourceFromTurnInput, on as withoutSavedSteeringMessages, ot as getConversationTurnBoundaryError, pi as releaseInboundMessage, pr as persistConversationMessages, pt as startActiveTurn, rn as instructionForInputs, s as turnInputFactsFromConversationMessage, sa as persistWithRetry, tn as buildSteeringPiMessage, ut as markTurnClosed, vt as persistThreadStateById, xi as getTurnLifecycle, xr as markConversationMessage, xt as deleteWebAuthorization, yt as coerceThreadConversationState } from "./mailbox-turn-DL3Lvsm0.js";
9
+ import { c as parentResultActor, s as childWorkEnded } from "./result-D090hxr5.js";
10
+ import { K as credentialContextForActor } from "./registry-D6kS6xYH.js";
11
11
  import { i as getActiveSpan, r as continueTrace } from "./sentry-CPbZjomA.js";
12
- import { g as measureTurnCompactionWait } from "./warmup-D5hzqTcp.js";
13
- import { n as botConfig } from "./config-CWbwKj0j.js";
14
- import { n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner--Ke8KSMf.js";
15
- import { t as mapBounded } from "./fan-out-Cod-yEHG.js";
16
- import { p as instructionProvenanceFor } from "./history-CYstOMKX.js";
17
- import { p as resolveConversationDestination } from "./start-conversation-DbVujrwO.js";
18
- import { t as readConversationLineage } from "./lineage-BXplQAVH.js";
12
+ import { at as reportPersonStopToParent, g as measureTurnCompactionWait, it as dropOwnUnreadLoopReplies, ot as stopChildAgentsBelow, rt as cancelWaitingParentMessages } from "./warmup-CCOuIwAS.js";
13
+ import { gt as mapBounded, n as botConfig } from "./config-BIfHKNXN.js";
14
+ import { i as getStateAdapter } from "./adapter-JARQvoLw.js";
15
+ import { n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-C-pXsgHM.js";
16
+ import { n as getPausedTurnRequest } from "./turn-wake-Bzq1Efrm.js";
17
+ import { p as instructionProvenanceFor } from "./history-CneKY7_V.js";
18
+ import { p as resolveConversationDestination } from "./start-conversation-a4NXH4X9.js";
19
+ import { t as readConversationLineage } from "./lineage-EULJkGO1.js";
20
+ import * as z from "zod";
19
21
  import { isDeepStrictEqual } from "node:util";
20
22
  import { createHash } from "node:crypto";
21
23
  // src/chat/task-execution/turn-telemetry.ts
@@ -75,6 +77,378 @@ function getTurnInputSpanAttributes(input, turnStartedAtMs) {
75
77
  if (waitMs >= 0) attributes["app.turn.wait_ms"] = Math.round(waitMs);
76
78
  return attributes;
77
79
  }
80
+ // src/chat/runtime/turn-execution.ts
81
+ /** An error thrown while the agent advances a Run. */
82
+ var AgentRunError = class extends Error {
83
+ constructor(cause) {
84
+ super(cause instanceof Error ? cause.message : "Agent Run failed", { cause });
85
+ this.name = "AgentRunError";
86
+ }
87
+ };
88
+ /**
89
+ * Run the agent and finish the Turn after the caller saves its result.
90
+ *
91
+ * A paused Run, or a Run waiting for authorization, leaves the Turn open. A
92
+ * save error also leaves the Turn open so the worker can retry or recover it.
93
+ */
94
+ async function executeTurn(agentRunner, run, saveResult) {
95
+ let outcome;
96
+ try {
97
+ outcome = await agentRunner.run(run);
98
+ } catch (error) {
99
+ throw new AgentRunError(error);
100
+ }
101
+ if (outcome.status !== "completed") return outcome;
102
+ const saved = await saveResult(outcome.result);
103
+ await finishTurn(run.conversationId, run.turnId, saved);
104
+ return { status: "completed" };
105
+ }
106
+ /** Record the terminal lifecycle event of a Turn from its saved result. */
107
+ async function finishTurn(conversationId, turnId, saved) {
108
+ const lifecycle = getTurnLifecycle();
109
+ const common = {
110
+ conversationId,
111
+ createdAtMs: saved.finishedAtMs ?? Date.now(),
112
+ turnId
113
+ };
114
+ if (saved.outcome === "failed") await lifecycle.fail({
115
+ ...common,
116
+ ...saved.eventId ? { eventId: saved.eventId } : void 0,
117
+ failureCode: saved.failureCode,
118
+ ...saved.failureReason ? { failureReason: saved.failureReason } : void 0
119
+ });
120
+ else await lifecycle.complete({
121
+ ...common,
122
+ outcome: saved.outcome
123
+ });
124
+ }
125
+ // src/chat/services/automated-turn-limit.ts
126
+ const AUTOMATED_TURN_LIMIT_PREFIX = "junior:automated_turn_limit:v1";
127
+ const AUTOMATED_TURN_LIMIT_LOCK_TTL_MS = 5e3;
128
+ const AUTOMATED_TURN_LIMIT_LOCK_WAIT_MS = 2e3;
129
+ const AUTOMATED_TURN_LIMIT_LOCK_RETRY_MS = 25;
130
+ /**
131
+ * Stored consecutive automated-turn count for one Conversation. Parsing
132
+ * strips the fields of the old pause, so its count still applies.
133
+ */
134
+ const automatedTurnLimitStateSchema = z.object({
135
+ consecutiveAutomatedTurns: z.number().int().nonnegative(),
136
+ updatedAtMs: z.number().finite().nonnegative()
137
+ });
138
+ function sleep(ms) {
139
+ return new Promise((resolve) => {
140
+ setTimeout(resolve, ms).unref?.();
141
+ });
142
+ }
143
+ function conversationKey(conversationId) {
144
+ return `${AUTOMATED_TURN_LIMIT_PREFIX}:conversation:${conversationId}`;
145
+ }
146
+ function lockKey(key) {
147
+ return `${key}:lock`;
148
+ }
149
+ function parseState(value) {
150
+ const parsed = automatedTurnLimitStateSchema.safeParse(value);
151
+ return parsed.success ? parsed.data : void 0;
152
+ }
153
+ async function acquireConversationLock(state, key, waitDeadlineMs = Date.now() + AUTOMATED_TURN_LIMIT_LOCK_WAIT_MS) {
154
+ while (true) {
155
+ const lock = await state.acquireLock(lockKey(key), AUTOMATED_TURN_LIMIT_LOCK_TTL_MS);
156
+ if (lock) return lock;
157
+ if (Date.now() >= waitDeadlineMs) throw new Error(`Could not acquire automated turn limit lock for ${key}`);
158
+ await sleep(AUTOMATED_TURN_LIMIT_LOCK_RETRY_MS);
159
+ }
160
+ }
161
+ async function withConversationLock(state, key, callback) {
162
+ const lock = await acquireConversationLock(state, key);
163
+ try {
164
+ return await callback();
165
+ } finally {
166
+ await state.releaseLock(lock);
167
+ }
168
+ }
169
+ function emptyState(nowMs) {
170
+ return {
171
+ consecutiveAutomatedTurns: 0,
172
+ updatedAtMs: nowMs
173
+ };
174
+ }
175
+ /** True when this Source starts an automated Turn rather than a user Turn. */
176
+ function isAutomatedTurnSource(source) {
177
+ if (!source) return false;
178
+ return source.kind === "event" || source.kind === "event_automation" || source.kind === "scheduled_automation" || source.kind === "plugin_dispatch" || source.kind === "parent_message";
179
+ }
180
+ /** Plain notice when automatic updates stop until the user replies. */
181
+ function buildAutomatedTurnLimitResponse(args) {
182
+ 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.`;
183
+ }
184
+ /** Count one finished automated Turn toward the consecutive-turn limit. */
185
+ async function countAutomatedTurn(args) {
186
+ if (args.maxTurns < 1) throw new Error("Automated turn limit must be at least 1");
187
+ const state = args.state ?? getStateAdapter();
188
+ await state.connect();
189
+ const nowMs = args.nowMs ?? Date.now();
190
+ const key = conversationKey(args.conversationId);
191
+ return await withConversationLock(state, key, async () => {
192
+ const consecutiveAutomatedTurns = (parseState(await state.get(key)) ?? emptyState(nowMs)).consecutiveAutomatedTurns + 1;
193
+ await state.set(key, {
194
+ consecutiveAutomatedTurns,
195
+ updatedAtMs: nowMs
196
+ }, JUNIOR_THREAD_STATE_TTL_MS);
197
+ return {
198
+ consecutiveAutomatedTurns,
199
+ reached: consecutiveAutomatedTurns >= args.maxTurns
200
+ };
201
+ });
202
+ }
203
+ /** Clear the consecutive automated-turn count after a user-owned Turn. */
204
+ async function resetAutomatedTurnLimit(args) {
205
+ const state = args.state ?? getStateAdapter();
206
+ await state.connect();
207
+ const key = conversationKey(args.conversationId);
208
+ await withConversationLock(state, key, async () => {
209
+ await state.delete(key);
210
+ });
211
+ }
212
+ /**
213
+ * Update consecutive automated-turn counts after one finished Turn.
214
+ *
215
+ * Automated Turns count on the Conversation. User Turns clear that count.
216
+ */
217
+ async function recordFinishedTurnForAutomatedLimit(args) {
218
+ const nowMs = args.nowMs ?? Date.now();
219
+ if (isAutomatedTurnSource(args.source)) return await countAutomatedTurn({
220
+ conversationId: args.conversationId,
221
+ maxTurns: args.maxTurns,
222
+ nowMs,
223
+ state: args.state
224
+ });
225
+ await resetAutomatedTurnLimit({
226
+ conversationId: args.conversationId,
227
+ nowMs,
228
+ state: args.state
229
+ });
230
+ }
231
+ // src/chat/conversations/stop.ts
232
+ /**
233
+ * Stop a Conversation for a person, on every stop path. Every child agent
234
+ * below it stops, then it and they are stopped Conversations until a person
235
+ * sends input, and then its Turn stops. A Turn that waits for sign-in ends
236
+ * too, so a later sign-in does not resume it. Their automated input is held.
237
+ * Nothing above it changes: this reports the stop of a Task to its parent.
238
+ *
239
+ * A stop that comes from a message or a button press, such as the Slack
240
+ * `stop` keyword or stop button, passes it. Its id is claimed in the mailbox
241
+ * first, so a redelivery returns `duplicate` and stops nothing, not even
242
+ * newer work. A stop that fails before its stop request is saved releases
243
+ * its claim, so a redelivery can stop again. A failed claim check keeps a
244
+ * claim that an earlier delivery saved. A failure after the stop request is
245
+ * saved keeps the claim, as does a failed reply: the work is already
246
+ * stopped, and a redelivery must not stop newer work. Its send time
247
+ * is the stop time, and only person input sent at or before it is dropped.
248
+ * So a retry writes the same stop and keeps input that the person sent after
249
+ * it.
250
+ *
251
+ * The child agents and sessions stop first, so a failure leaves the Turn
252
+ * running and the stop can be retried. A child agent can outlive the parent
253
+ * Turn, so this runs even when no Turn runs.
254
+ */
255
+ async function stopConversation(args) {
256
+ if (args.message && (await claimInboundMessage({
257
+ conversationStore: args.conversationStore,
258
+ message: args.message,
259
+ state: args.state
260
+ })).status === "duplicate") return { status: "duplicate" };
261
+ let stopSaved = false;
262
+ try {
263
+ const nowMs = Date.now();
264
+ const stoppedAtMs = args.message?.createdAtMs ?? nowMs;
265
+ await reportPersonStopToParent(args.conversationId, {
266
+ queue: args.queue,
267
+ state: args.state,
268
+ stoppedAtMs
269
+ });
270
+ const result = await stopConversationAndChildAgents({
271
+ conversationId: args.conversationId,
272
+ conversationStore: args.conversationStore,
273
+ nowMs,
274
+ onStopSaved: () => {
275
+ stopSaved = true;
276
+ },
277
+ queue: args.queue,
278
+ sentAtOrBeforeMs: args.message ? stoppedAtMs : void 0,
279
+ state: args.state,
280
+ stoppedAtMs
281
+ });
282
+ if (result.status === "requested") await ensureConversationWake({
283
+ conversationId: args.conversationId,
284
+ conversationStore: args.conversationStore,
285
+ idempotencyKey: `conversation-stop:${args.conversationId}:${result.runId}`,
286
+ nowMs,
287
+ queue: args.queue,
288
+ replaceExistingWake: true,
289
+ state: args.state
290
+ });
291
+ return result;
292
+ } catch (error) {
293
+ if (args.message && !stopSaved) await releaseInboundMessage({
294
+ message: args.message,
295
+ state: args.state
296
+ });
297
+ throw error;
298
+ }
299
+ }
300
+ /**
301
+ * Stop a Conversation and every child agent below it, through
302
+ * `stopConversationTree`. A person's stop and the automated-turn limit call
303
+ * this. The child agents stop first, so a failure leaves the Conversation
304
+ * running and the stop can be retried. Its waiting parent messages are
305
+ * dropped before its stop request is saved, so no stop request outlives
306
+ * the stop.
307
+ */
308
+ async function stopConversationAndChildAgents(args) {
309
+ const { conversationId, ...options } = args;
310
+ await stopChildAgentsBelow(conversationId, {
311
+ nowMs: options.nowMs,
312
+ queue: options.queue,
313
+ stoppedAtMs: options.stoppedAtMs,
314
+ state: options.state
315
+ });
316
+ await cancelWaitingParentMessages(conversationId, {
317
+ nowMs: options.stoppedAtMs,
318
+ state: options.state
319
+ });
320
+ const [result] = await stopConversationTree([conversationId], options);
321
+ if (!result) throw new Error("Stop returned no result");
322
+ await dropOwnUnreadLoopReplies(conversationId, options.state);
323
+ return result;
324
+ }
325
+ // src/chat/slack/automated-turn-limit-notice.ts
326
+ /**
327
+ * Stop and notice for the consecutive automated-turn limit.
328
+ *
329
+ * The notice is best-effort: a failed post must not fail the Turn or undo the
330
+ * stop.
331
+ */
332
+ /**
333
+ * Post the stop notice to the Conversation Location when known. A child
334
+ * agent posts none: its parent sees it as stopped in `listAgents`.
335
+ */
336
+ async function postAutomatedTurnLimitNotice(args) {
337
+ try {
338
+ const conversation = await getConversationStore().get({ conversationId: args.conversationId });
339
+ const location = conversation?.parentConversationId ? void 0 : conversation?.location;
340
+ if (!location || location.provider !== "slack" || conversation?.deliveryPausedAtMs !== void 0) {
341
+ logWarn("automated_turn_limit.notice.skipped", {
342
+ conversationId: args.conversationId,
343
+ "app.automated_turn_limit.reason": !location ? "missing_location" : location.provider !== "slack" ? "unsupported_location" : "delivery_paused"
344
+ });
345
+ return;
346
+ }
347
+ await sendSlackReply({
348
+ ...resolveSlackReplyTarget({
349
+ destination: location,
350
+ location,
351
+ source: args.source
352
+ }),
353
+ conversationId: args.conversationId,
354
+ text: buildAutomatedTurnLimitResponse({ maxTurns: args.maxTurns })
355
+ });
356
+ } catch (error) {
357
+ logException(error, "automated_turn_limit.notice.failed", { conversationId: args.conversationId });
358
+ }
359
+ }
360
+ /**
361
+ * Stop the Conversation tree after a finished Turn reaches the automated-turn
362
+ * limit, then post the notice. Person input that already waits ends the loop
363
+ * by itself, so then nothing stops.
364
+ */
365
+ async function stopAtAutomatedTurnLimit(args) {
366
+ if (!args.update?.reached) return;
367
+ if (((await getConversationWorkState({ conversationId: args.conversationId }))?.messages ?? []).some((message) => isPersonInput(message.source))) return;
368
+ const nowMs = Date.now();
369
+ await stopConversationAndChildAgents({
370
+ conversationId: args.conversationId,
371
+ finishedRunOf: args.conversationId,
372
+ nowMs,
373
+ stoppedAtMs: nowMs
374
+ });
375
+ await postAutomatedTurnLimitNotice({
376
+ conversationId: args.conversationId,
377
+ maxTurns: args.maxTurns,
378
+ source: args.source
379
+ });
380
+ }
381
+ // src/chat/task-execution/supersede-turns.ts
382
+ /**
383
+ * End every open mailbox Turn other than `keepTurnId`, so new input runs in
384
+ * the only open Turn. New input starts only when no yielded Turn waits, so an
385
+ * open Turn here waits for OAuth or was left open by a failed or stopped Run.
386
+ * The caller persists `conversation`. Returns false when `isStopped` turns
387
+ * true first.
388
+ */
389
+ async function supersedeOpenMailboxTurns(args) {
390
+ return await supersedeTurns({
391
+ ...args,
392
+ turns: (await listActiveMailboxTurns(args.conversationId)).filter((record) => record.turnId !== args.keepTurnId)
393
+ });
394
+ }
395
+ /**
396
+ * End open Turns that new input replaces. A late resume or OAuth callback
397
+ * for an ended Turn is a no-op. The caller persists `conversation`. Returns
398
+ * false when `isStopped` turns true first.
399
+ */
400
+ async function supersedeTurns(args) {
401
+ const pendingAuthorizationActorId = args.conversation.processing.pendingAuth?.actorId;
402
+ for (const stale of args.turns) {
403
+ if (args.isStopped?.()) return false;
404
+ await abandonTurnRecord({
405
+ conversationId: args.conversationId,
406
+ turnId: stale.turnId,
407
+ errorMessage: "Turn superseded by new input"
408
+ });
409
+ await getTurnLifecycle().complete({
410
+ conversationId: args.conversationId,
411
+ createdAtMs: Date.now(),
412
+ outcome: "cancelled",
413
+ turnId: stale.turnId
414
+ });
415
+ markTurnClosed({
416
+ conversation: args.conversation,
417
+ nowMs: Date.now(),
418
+ sessionId: stale.turnId
419
+ });
420
+ }
421
+ if (args.turns.some((record) => record.state === "paused" && record.resumeReason === "auth") && pendingAuthorizationActorId) await deleteWebAuthorization({
422
+ actorId: pendingAuthorizationActorId,
423
+ conversationId: args.conversationId
424
+ });
425
+ return true;
426
+ }
427
+ /**
428
+ * End the Turn that waits for its next Run when `message` cannot join it, so
429
+ * the message starts its own Turn instead of running with that Turn's Actor.
430
+ * A stored legacy Turn without an Actor keeps taking the input.
431
+ */
432
+ async function supersedeTurnForInput(args) {
433
+ const conversation = coerceThreadConversationState(await getPersistedThreadState(args.conversationId));
434
+ const turnId = conversation.processing.activeTurnId;
435
+ if (!turnId || !await getPausedTurnRequest({
436
+ conversationId: args.conversationId,
437
+ turnId
438
+ })) return;
439
+ const turn = await getTurnRecord(args.conversationId, turnId);
440
+ if (!turn?.actor || canJoinTurn(turn, args.message)) return;
441
+ await hydrateConversationMessages({
442
+ conversation,
443
+ conversationId: args.conversationId
444
+ });
445
+ await supersedeTurns({
446
+ conversation,
447
+ conversationId: args.conversationId,
448
+ turns: [turn]
449
+ });
450
+ await persistThreadStateById(args.conversationId, { conversation });
451
+ }
78
452
  // src/chat/automations/block-run.ts
79
453
  /**
80
454
  * Block the Automation of a run from a later Turn of the run, such as a Watch
@@ -176,7 +550,7 @@ function savedTurnInputMessages(conversation, turnMessage, inputMessageIds) {
176
550
  }
177
551
  /**
178
552
  * Render the Turn inputs of one new mailbox batch. A parent batch is the
179
- * parent's task, as on an Agent invocation. An Event batch also returns the
553
+ * parent's task. An Event batch also returns the
180
554
  * meta of its one saved Message. A web batch returns one transcript Message
181
555
  * per input.
182
556
  */
@@ -401,12 +775,18 @@ function createConversationTurnWorker(agentRunner, deliverMessage, deliverToPare
401
775
  const sendToParent = async (result) => {
402
776
  if (!deliverToParent) throw new Error(`Conversation ${context.conversationId} cannot reach its parent agent`);
403
777
  await deliverToParent({
404
- actor,
778
+ actor: parentResultActor(actor, source.kind),
405
779
  result,
406
780
  conversationId: context.conversationId,
407
781
  turnId
408
782
  });
409
783
  };
784
+ const reportFailure = async (text) => {
785
+ if (behavior.failureNotice === "parent") await sendToParent({
786
+ kind: "failed",
787
+ text
788
+ });
789
+ };
410
790
  const surface = postsToProvider ? "slack" : "api";
411
791
  const inputTelemetry = resolved.kind === "mailbox" ? turnInputTelemetry(resolved.batch.map((entry) => entry.message)) : void 0;
412
792
  const turnTrace = inputTelemetry ?? (savedTurn?.traceContext ? { traceContexts: [savedTurn.traceContext] } : void 0);
@@ -625,20 +1005,28 @@ function createConversationTurnWorker(agentRunner, deliverMessage, deliverToPare
625
1005
  modelFailureEventId = finalized.eventId;
626
1006
  if (reply.diagnostics.outcome !== "success") {
627
1007
  await deliverAssistantMessage(reply.text);
628
- if (behavior.failureNotice === "parent") await sendToParent({
629
- kind: "failed",
630
- text: reply.diagnostics.errorMessage ?? reply.text
1008
+ await reportFailure(reply.diagnostics.errorMessage ?? reply.text);
1009
+ } else if (reply.reply && behavior.tools.reply === "parent") {
1010
+ await sendToParent({
1011
+ kind: "reply",
1012
+ reply: reply.reply
631
1013
  });
632
- } else if (reply.reply && behavior.tools.reply === "parent") await sendToParent({
633
- kind: "reply",
634
- reply: reply.reply
635
- });
636
- else if (reply.reply) await deliverAssistantMessage(reply.reply.text, { reply: true });
1014
+ await deliverAssistantMessage(reply.reply.text);
1015
+ } else if (reply.reply) await deliverAssistantMessage(reply.reply.text, { reply: true });
637
1016
  else if (reply.blocked && behavior.tools.reportBlocked === "parent") await sendToParent({
638
1017
  kind: "blocked",
639
1018
  text: reply.blocked.missing
640
1019
  });
641
1020
  else if (reply.blocked) await blockRunAutomation(context.conversationId, reply.blocked);
1021
+ else if (reply.noReply) {
1022
+ if (behavior.endResult === "parent" && await childWorkEnded(context.conversationId, turnId)) await sendToParent({
1023
+ kind: "completed",
1024
+ text: reply.noReply.note ?? ""
1025
+ });
1026
+ } else if (behavior.endResult === "parent" && reply.text) await sendToParent({
1027
+ kind: "completed",
1028
+ text: reply.text
1029
+ });
642
1030
  const completedState = buildDeliveredTurnStatePatch({
643
1031
  conversation,
644
1032
  reply,
@@ -680,7 +1068,8 @@ function createConversationTurnWorker(agentRunner, deliverMessage, deliverToPare
680
1068
  });
681
1069
  }
682
1070
  completedSuccessfully = reply.diagnostics.outcome === "success";
683
- return completedSuccessfully ? { outcome: assistantMessageDelivered ? "success" : "no_reply" } : {
1071
+ const delivered = assistantMessageDelivered ? "success" : "no_reply";
1072
+ return completedSuccessfully ? { outcome: reply.blocked ? "blocked" : delivered } : {
684
1073
  ...modelFailureEventId ? { eventId: modelFailureEventId } : void 0,
685
1074
  failureCode: "model_execution_failed",
686
1075
  ...modelFailureReason ? { failureReason: modelFailureReason } : void 0,
@@ -782,15 +1171,11 @@ function createConversationTurnWorker(agentRunner, deliverMessage, deliverToPare
782
1171
  failureCode,
783
1172
  turnId
784
1173
  });
785
- if (behavior.failureNotice === "parent") await sendToParent({
786
- kind: "failed",
787
- text: failure instanceof Error ? failure.message : String(failure)
788
- });
789
- else await recordChildAgentEnded(context.conversationId, "error");
1174
+ await reportFailure(failure instanceof Error ? failure.message : String(failure));
790
1175
  await acknowledge();
791
1176
  return { status: "completed" };
792
1177
  }
793
1178
  });
794
1179
  };
795
1180
  }
796
- export { withTurnSpan as a, turnInputTelemetry as i, createConversationTurnWorker as n, getTurnInputSpanAttributes as r, conversation_turn_exports as t };
1181
+ export { stopConversation as a, executeTurn as c, withTurnSpan as d, stopAtAutomatedTurnLimit as i, getTurnInputSpanAttributes as l, createConversationTurnWorker as n, recordFinishedTurnForAutomatedLimit as o, supersedeTurnForInput as r, AgentRunError as s, conversation_turn_exports as t, turnInputTelemetry as u };