@sentry/junior 0.312.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 (115) hide show
  1. package/dist/{adapter-iIq7ihf7.js → adapter-JARQvoLw.js} +1 -2
  2. package/dist/{adapter-context-BRjEWRy1.js → adapter-context-B4BrJZuS.js} +2 -2
  3. package/dist/{admin-DhInw5K9.js → admin-BXGAySz0.js} +1 -1
  4. package/dist/{agent-runner-C9iDurwX.js → agent-runner-qZU5TR8i.js} +865 -138
  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 +340 -106
  11. package/dist/{app-DRFrC8Mw.d.ts → app-D7tKnw9a.d.ts} +4 -21
  12. package/dist/app.d.ts +2 -2
  13. package/dist/app.js +80 -171
  14. package/dist/{background-compaction-queue-DrKi7w3d.js → background-compaction-queue-C_uIBUvS.js} +6 -17
  15. package/dist/{callback-mFlTUWWx.js → callback-C8SdXCwr.js} +4 -11
  16. package/dist/{catalog-runtime-D7xapBAX.js → catalog-runtime-BLKtnUL3.js} +1 -1
  17. package/dist/{channel-access-CJGfNTdn.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-kXB2Y5tl.js → config-BIfHKNXN.js} +40 -35
  27. package/dist/{continue-in-slack-O6pV5004.js → continue-in-slack-fnmD2Ifb.js} +5 -7
  28. package/dist/{conversation-feed-uNOv_x68.js → conversation-feed-DdFQuQDR.js} +13 -2
  29. package/dist/{logging-dQ9ZRGQ8.js → conversation-privacy-DtZhI91r.js} +188 -2
  30. package/dist/{conversation-turn-CeLbHqdw.js → conversation-turn-DScuDYmN.js} +465 -62
  31. package/dist/create-CrNt4Ewu.js +212 -0
  32. package/dist/{credential-sync-I8VBGk05.js → credential-sync-CtqsGjj1.js} +14 -18
  33. package/dist/{credentialed-Cb6E2phL.js → credentialed-dWRA3-oJ.js} +911 -429
  34. package/dist/{db-LAyyX8tk.js → db-BTmLKZrp.js} +2245 -50
  35. package/dist/{db-BbC5stfa.d.ts → db-DcmzbA55.d.ts} +2 -2
  36. package/dist/{history-CYstOMKX.js → history-CneKY7_V.js} +19 -1
  37. package/dist/{html-BCZ3Xtb_.js → html-B8rBt7F4.js} +5 -7
  38. package/dist/{install-DCFJFkC0.js → install-OtFboxOM.js} +2 -2
  39. package/dist/instrumentation.js +2 -2
  40. package/dist/{lineage-B_m-4TJw.js → lineage-EULJkGO1.js} +1 -2
  41. package/dist/{list-CN2QA2R9.js → list-C5400AlJ.js} +284 -113
  42. package/dist/{thread-state-DhPndWi1.js → mailbox-turn-DL3Lvsm0.js} +4830 -485
  43. package/dist/markers-DUP8aBOp.js +323 -0
  44. package/dist/{media-CYm1QD8T.js → media-FYM-Bl3H.js} +42 -14
  45. package/dist/{message-DSXGj1hM.js → message-DuDelZFr.js} +16 -15
  46. package/dist/{model-input--TrP9hYV.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-DHCZC6B4.js → oauth-callback-server-DX2fQ7Nq.js} +2 -2
  50. package/dist/{oauth-relay-pPMGnDZt.js → oauth-relay-PwPMdZJv.js} +1 -1
  51. package/dist/{plugins-Bkk0XRo2.js → plugins-BXMdNdyA.js} +1 -1
  52. package/dist/{registry-CZOzddwu.js → registry-D6kS6xYH.js} +1402 -64
  53. package/dist/{statuses-_cRJHXK7.js → reporting-window-C4dbzDiR.js} +1 -27
  54. package/dist/{resolve-cKOQ14Dh.js → resolve-D8CPJcNK.js} +3 -3
  55. package/dist/result-D090hxr5.js +402 -0
  56. package/dist/{runner-DBfUW44l.js → runner-BU7fgrm-.js} +7 -8
  57. package/dist/{sandbox-egress-signals-BVF_xAm1.js → sandbox-egress-signals-BUmVrsoG.js} +1 -1
  58. package/dist/{schema-Bk9Nm2E8.js → schema-7gW9vBpJ.js} +91 -10
  59. package/dist/{schema-BEHKxr4I.d.ts → schema-BB6E0wyV.d.ts} +2105 -2753
  60. package/dist/{service-account-CVYsFjty.js → service-account-plA-uzIB.js} +6 -5
  61. package/dist/{skills-VTnhAJWm.js → skills-CIosT6bS.js} +3 -3
  62. package/dist/{slack-conversation-unfurl-fuLnF1jE.js → slack-conversation-unfurl-CBgZqth6.js} +8 -10
  63. package/dist/spawn-DRjdzh3R.js +46 -0
  64. package/dist/{start-conversation-CEn2KH1A.js → start-conversation-a4NXH4X9.js} +13 -202
  65. package/dist/{store-DFZaN-Ix.js → store-BuhF1QDm.js} +2 -4
  66. package/dist/{task-queue-Cx4Lmjyk.js → task-queue-CrRjFzOh.js} +5 -16
  67. package/dist/{task-runner-CbTwFA6k.js → task-runner-C-pXsgHM.js} +105 -51
  68. package/dist/{thread-context-BkAZDTX2.js → thread-context-CDX4dSZd.js} +8 -10
  69. package/dist/turn-session-routing-CZTRU8IY.js +116 -0
  70. package/dist/turn-wake-Bzq1Efrm.js +154 -0
  71. package/dist/user-customization-B27StpVQ.js +9 -0
  72. package/dist/{validation-nIzMtAVJ.js → validation-bTq88sya.js} +1 -1
  73. package/dist/{vercel-queue-hW90XzbG.js → vercel-queue-nL0Hq3hr.js} +32 -147
  74. package/dist/{version-Brbtz4Qf.js → version-DGUa1dZK.js} +1 -1
  75. package/dist/version.js +1 -1
  76. package/dist/{warmup-BDA5myRK.js → warmup-CCOuIwAS.js} +831 -3254
  77. package/dist/{worker-D63RcaVD.js → worker-AkZg7Dg1.js} +5 -6
  78. package/migrations/0158_keep_legacy_archive_columns.sql +5 -0
  79. package/migrations/0159_conversation_embeddings_fk_validate.sql +5 -0
  80. package/migrations/0160_money_micro_usd_repair.sql +99 -0
  81. package/migrations/0161_agent_config_backfill.sql +34 -0
  82. package/migrations/0162_inbox_item_deliveries.sql +15 -0
  83. package/migrations/0163_pg_trgm.sql +2 -0
  84. package/migrations/0164_search_indexes.sql +4 -0
  85. package/migrations/0165_drop_legacy_archive_columns.sql +4 -0
  86. package/migrations/0166_memory_prefix_index.sql +1 -0
  87. package/migrations/0167_todo_search_indexes.sql +2 -0
  88. package/migrations/0168_todo_inbox_items.sql +4 -0
  89. package/migrations/0169_drop_code_urls.sql +2 -0
  90. package/migrations/meta/0158_snapshot.json +6515 -0
  91. package/migrations/meta/0159_snapshot.json +6515 -0
  92. package/migrations/meta/0160_snapshot.json +6515 -0
  93. package/migrations/meta/0161_snapshot.json +6278 -0
  94. package/migrations/meta/0162_snapshot.json +6404 -0
  95. package/migrations/meta/0163_snapshot.json +6404 -0
  96. package/migrations/meta/0164_snapshot.json +6466 -0
  97. package/migrations/meta/0165_snapshot.json +6466 -0
  98. package/migrations/meta/0166_snapshot.json +6494 -0
  99. package/migrations/meta/0167_snapshot.json +6525 -0
  100. package/migrations/meta/0168_snapshot.json +6525 -0
  101. package/migrations/meta/0169_snapshot.json +6513 -0
  102. package/migrations/meta/_journal.json +84 -0
  103. package/package.json +9 -18
  104. package/skills/design-automation-skill/SKILL.md +2 -3
  105. package/dist/actor-BsBdxDXQ.js +0 -208
  106. package/dist/child-message-DcsritGf.js +0 -179
  107. package/dist/conversation-privacy-L4ja1_W6.js +0 -189
  108. package/dist/executor-SCub-fAq.js +0 -1860
  109. package/dist/fan-out-Cod-yEHG.js +0 -10
  110. package/dist/ingest-BDf3D50j.js +0 -3836
  111. package/dist/result-DcvEOe1r.js +0 -574
  112. package/dist/result-event-type-BdIJuZxg.js +0 -48
  113. package/dist/service-account-Ts4ulcrV.js +0 -931
  114. package/dist/spawn-vxAarlX5.js +0 -73
  115. package/dist/state-C1P3_Ywk.js +0 -161
@@ -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-Cb6E2phL.js";
3
- import { A as isTopLevelKind, F as turnBehavior, O as isPersonInput, a as getConversationStore, o as getDb } from "./db-LAyyX8tk.js";
4
- import { E as withSpan, S as setTags, h as logWarn, p as logException } from "./logging-dQ9ZRGQ8.js";
5
- import { kt as readMessageAttachments } from "./media-CYm1QD8T.js";
6
- import { C as isConversationDeliveryPaused } from "./agent-runner-C9iDurwX.js";
7
- import { a as buildDeliveredTurnStatePatch, o as loadPendingMessageCards, r as completeAuthPauseTurn, t as buildTurnThreadContext } from "./thread-context-BkAZDTX2.js";
8
- import { $ as eventInboxItemInputs, B as TurnInputCommitLostError, H as getConversationTurnBoundaryError, J as markTurnFailed, N as completeCancelledConversationTurn, P as getTurnUserMessage, W as isTurnInputCommitLostError, X as createWebAuthorization, Y as startActiveTurn, _ as timerWatchCredentialSubject, a as getEventBatchDelayMs, at as instructionActorFor, ct as turnRequestText, d as turnInputFactsFromConversationMessage, et as loadInboxItemInput, f as legacyWebMailboxMetadataSchema, g as renderEventBatchInputs, h as isEventMailboxMetadata, it as buildSteeringPiMessage, lt as withoutSavedSteeringMessages, m as eventBatchMessageMeta, ot as instructionForInputs, u as sourceFromTurnInput } from "./ingest-BDf3D50j.js";
9
- import { Dn as finalizeFailedTurnReplyWithEvent, Kn as getAssistantReplyText, L as buildDeterministicTurnId, R as commitAcceptedReply, V as loadConversationProjection, Wt as saveTurnCheckpoint, Yt as getTurnRecord, a as persistThreadStateById, ft as latestConversationMessageSeq, hn as getTurnLifecycle, ht as recordDeliveredAssistantMessage, it as persistConversationMessages, mt as normalizeConversationText, n as getPersistedSandboxState, nr as persistWithRetry, nt as hydrateConversationMessages, o as coerceThreadConversationState, pt as markConversationMessage, qt as failTurnRecord, r as getPersistedThreadState, vt as upsertConversationMessage, wt as isEventConversationMessage } from "./thread-state-DhPndWi1.js";
10
- import { Cn as recordFinishedTurnForAutomatedLimit, Ht as commitParentMessageFork, Kt as readParentMessage, Tn as executeTurn, Ut as isParentMessageMeta, Vt as childAgentTurnOptions, g as measureTurnCompactionWait, mn as stopAtAutomatedTurnLimit, on as supersedeOpenMailboxTurns, wn as AgentRunError } from "./warmup-BDA5myRK.js";
11
- import { p as credentialContextForActor } from "./registry-CZOzddwu.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";
12
11
  import { i as getActiveSpan, r as continueTrace } from "./sentry-CPbZjomA.js";
13
- import { n as botConfig } from "./config-kXB2Y5tl.js";
14
- import { n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-CbTwFA6k.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-CEn2KH1A.js";
18
- import { t as readConversationLineage } from "./lineage-B_m-4TJw.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
@@ -174,6 +548,34 @@ function savedTurnInputMessages(conversation, turnMessage, inputMessageIds) {
174
548
  const saved = (inputMessageIds ?? []).flatMap((id) => conversation.messages.find((message) => message.id === id && message.role === "user") ?? []);
175
549
  return saved.some((message) => message.id === turnMessage.id) ? saved : [turnMessage];
176
550
  }
551
+ /**
552
+ * Render the Turn inputs of one new mailbox batch. A parent batch is the
553
+ * parent's task. An Event batch also returns the
554
+ * meta of its one saved Message. A web batch returns one transcript Message
555
+ * per input.
556
+ */
557
+ async function mailboxTurnInputs(batch, fromParent) {
558
+ const messages = batch.map((entry) => entry.message);
559
+ if (fromParent) return {
560
+ eventMeta: {},
561
+ inputs: batch.map(({ message, requestText }) => ({
562
+ kind: "runtime",
563
+ text: message.input.text.trim(),
564
+ ...requestText ? { requestText } : void 0
565
+ })),
566
+ webInputMessages: []
567
+ };
568
+ if (isEventMailboxMetadata(messages[0]?.input.metadata)) return {
569
+ eventMeta: eventBatchMessageMeta(messages),
570
+ inputs: renderEventBatchInputs(messages, await eventInboxItemInputs(messages)),
571
+ webInputMessages: []
572
+ };
573
+ return {
574
+ eventMeta: {},
575
+ inputs: await webTurnInputs(messages.map((message) => message.input)),
576
+ webInputMessages: batch.map((entry) => webConversationMessage(entry.message, entry.author))
577
+ };
578
+ }
177
579
  // src/chat/task-execution/web-steering.ts
178
580
  async function steeringMessageFromWeb(message, actor) {
179
581
  const storedAttachments = readMessageAttachments(message.input.attachments);
@@ -290,6 +692,7 @@ function createConversationTurnWorker(agentRunner, deliverMessage, deliverToPare
290
692
  let startedAtMs = Date.now();
291
693
  let inputMessageIds = [];
292
694
  let eventMeta = {};
695
+ let fromParent = resolved.kind === "mailbox" && resolved.batch.every((entry) => readParentMessage(entry.message));
293
696
  let authorIdentityId;
294
697
  let webInputMessages = [];
295
698
  const storedConversation = await getConversationStore().get({ conversationId: context.conversationId });
@@ -303,20 +706,7 @@ function createConversationTurnWorker(agentRunner, deliverMessage, deliverToPare
303
706
  if (resolved.kind === "mailbox") {
304
707
  const first = resolved.batch[0];
305
708
  const messages = resolved.batch.map((entry) => entry.message);
306
- const firstMetadata = first.message.input.metadata;
307
- if (isEventMailboxMetadata(firstMetadata)) {
308
- const rendered = await eventInboxItemInputs(messages);
309
- for (const { message, requestText } of resolved.batch) if (requestText) rendered.set(message.inboundMessageId, {
310
- kind: "runtime",
311
- text: message.input.text.trim(),
312
- requestText
313
- });
314
- inputs = renderEventBatchInputs(messages, rendered);
315
- eventMeta = eventBatchMessageMeta(messages);
316
- } else {
317
- inputs = await webTurnInputs(messages.map((message) => message.input));
318
- webInputMessages = resolved.batch.map((entry) => webConversationMessage(entry.message, entry.author));
319
- }
709
+ ({eventMeta, inputs, webInputMessages} = await mailboxTurnInputs(resolved.batch, fromParent));
320
710
  attachments = resolved.batch.flatMap((entry) => readMessageAttachments(entry.message.input.attachments));
321
711
  startedAtMs = first.message.createdAtMs;
322
712
  userMessageId = first.message.inboundMessageId;
@@ -333,12 +723,11 @@ function createConversationTurnWorker(agentRunner, deliverMessage, deliverToPare
333
723
  });
334
724
  const savedTurn = isResume ? await getTurnRecord(context.conversationId, turnId) : void 0;
335
725
  let savedMessageIsEvent = false;
336
- let savedParentMessage = false;
337
726
  if (isResume) {
338
727
  const userMessage = getTurnUserMessage(conversation, turnId);
339
728
  if (!userMessage) throw new Error(`Unable to locate the persisted user message for Turn "${turnId}"`);
340
729
  savedMessageIsEvent = isEventConversationMessage(userMessage);
341
- savedParentMessage = isParentMessageMeta(userMessage.meta);
730
+ fromParent = isParentMessageAuthor(userMessage.author);
342
731
  turnInputFacts = turnInputFactsFromConversationMessage(userMessage, {
343
732
  conversationId: context.conversationId,
344
733
  location: storedConversation?.location,
@@ -348,7 +737,7 @@ function createConversationTurnWorker(agentRunner, deliverMessage, deliverToPare
348
737
  });
349
738
  const turnInputs = savedTurnInputMessages(conversation, userMessage, await lifecycle.loadInputMessageIds(context.conversationId, turnId));
350
739
  userMessageId = userMessage.id;
351
- inputs = savedMessageIsEvent ? [{
740
+ inputs = savedMessageIsEvent || fromParent ? [{
352
741
  kind: "runtime",
353
742
  text: userMessage.text,
354
743
  ...userMessage.meta?.requestText ? { requestText: userMessage.meta.requestText } : void 0
@@ -366,7 +755,7 @@ function createConversationTurnWorker(agentRunner, deliverMessage, deliverToPare
366
755
  const { text } = instructionInputs;
367
756
  const instructionActor = instructionActorFor(actor);
368
757
  let credentialSubject;
369
- if (actor.platform === "system") credentialSubject = resolved.kind === "mailbox" ? timerWatchCredentialSubject(context.conversationId, resolved.batch.map((entry) => entry.message)) ?? await verifiedTimerWatchSubject(context.conversationId, sharedDelegatedSubject(resolved.batch), resolved.batch.every((entry) => readParentMessage(entry.message))) : await verifiedTimerWatchSubject(context.conversationId, savedTurn?.credentialSubject, savedParentMessage);
758
+ 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);
370
759
  const source = sourceFromTurnInput({
371
760
  conversationId: context.conversationId,
372
761
  source: turnInputFacts.source,
@@ -386,12 +775,18 @@ function createConversationTurnWorker(agentRunner, deliverMessage, deliverToPare
386
775
  const sendToParent = async (result) => {
387
776
  if (!deliverToParent) throw new Error(`Conversation ${context.conversationId} cannot reach its parent agent`);
388
777
  await deliverToParent({
389
- actor,
778
+ actor: parentResultActor(actor, source.kind),
390
779
  result,
391
780
  conversationId: context.conversationId,
392
781
  turnId
393
782
  });
394
783
  };
784
+ const reportFailure = async (text) => {
785
+ if (behavior.failureNotice === "parent") await sendToParent({
786
+ kind: "failed",
787
+ text
788
+ });
789
+ };
395
790
  const surface = postsToProvider ? "slack" : "api";
396
791
  const inputTelemetry = resolved.kind === "mailbox" ? turnInputTelemetry(resolved.batch.map((entry) => entry.message)) : void 0;
397
792
  const turnTrace = inputTelemetry ?? (savedTurn?.traceContext ? { traceContexts: [savedTurn.traceContext] } : void 0);
@@ -531,8 +926,7 @@ function createConversationTurnWorker(agentRunner, deliverMessage, deliverToPare
531
926
  if (stopSignal?.aborted) return await completeCancelledTurn();
532
927
  const childTurn = await childAgentTurnOptions({
533
928
  conversationId: context.conversationId,
534
- inputs: resolved.kind === "mailbox" ? resolved.batch.map((entry) => entry.message) : [],
535
- savedParentMessage
929
+ fromParent
536
930
  });
537
931
  const history = await loadConversationProjection({ conversationId: context.conversationId });
538
932
  failureCode = "agent_run_failed";
@@ -611,20 +1005,28 @@ function createConversationTurnWorker(agentRunner, deliverMessage, deliverToPare
611
1005
  modelFailureEventId = finalized.eventId;
612
1006
  if (reply.diagnostics.outcome !== "success") {
613
1007
  await deliverAssistantMessage(reply.text);
614
- if (behavior.failureNotice === "parent") await sendToParent({
615
- kind: "failed",
616
- 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
617
1013
  });
618
- } else if (reply.reply && behavior.tools.reply === "parent") await sendToParent({
619
- kind: "reply",
620
- reply: reply.reply
621
- });
622
- 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 });
623
1016
  else if (reply.blocked && behavior.tools.reportBlocked === "parent") await sendToParent({
624
1017
  kind: "blocked",
625
1018
  text: reply.blocked.missing
626
1019
  });
627
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
+ });
628
1030
  const completedState = buildDeliveredTurnStatePatch({
629
1031
  conversation,
630
1032
  reply,
@@ -651,19 +1053,23 @@ function createConversationTurnWorker(agentRunner, deliverMessage, deliverToPare
651
1053
  surface
652
1054
  });
653
1055
  }
654
- const automatedTurnLimit = await recordFinishedTurnForAutomatedLimit({
655
- conversationId: context.conversationId,
656
- maxTurns: botConfig.maxConsecutiveAutomatedTurns,
657
- source
658
- });
659
- await stopAtAutomatedTurnLimit({
660
- conversationId: context.conversationId,
661
- maxTurns: botConfig.maxConsecutiveAutomatedTurns,
662
- source,
663
- update: automatedTurnLimit
664
- });
1056
+ if (fromParent) await resetAutomatedTurnLimit({ conversationId: context.conversationId });
1057
+ else {
1058
+ const automatedTurnLimit = await recordFinishedTurnForAutomatedLimit({
1059
+ conversationId: context.conversationId,
1060
+ maxTurns: botConfig.maxConsecutiveAutomatedTurns,
1061
+ source
1062
+ });
1063
+ await stopAtAutomatedTurnLimit({
1064
+ conversationId: context.conversationId,
1065
+ maxTurns: botConfig.maxConsecutiveAutomatedTurns,
1066
+ source,
1067
+ update: automatedTurnLimit
1068
+ });
1069
+ }
665
1070
  completedSuccessfully = reply.diagnostics.outcome === "success";
666
- return completedSuccessfully ? { outcome: assistantMessageDelivered ? "success" : "no_reply" } : {
1071
+ const delivered = assistantMessageDelivered ? "success" : "no_reply";
1072
+ return completedSuccessfully ? { outcome: reply.blocked ? "blocked" : delivered } : {
667
1073
  ...modelFailureEventId ? { eventId: modelFailureEventId } : void 0,
668
1074
  failureCode: "model_execution_failed",
669
1075
  ...modelFailureReason ? { failureReason: modelFailureReason } : void 0,
@@ -765,14 +1171,11 @@ function createConversationTurnWorker(agentRunner, deliverMessage, deliverToPare
765
1171
  failureCode,
766
1172
  turnId
767
1173
  });
768
- if (behavior.failureNotice === "parent") await sendToParent({
769
- kind: "failed",
770
- text: failure instanceof Error ? failure.message : String(failure)
771
- });
1174
+ await reportFailure(failure instanceof Error ? failure.message : String(failure));
772
1175
  await acknowledge();
773
1176
  return { status: "completed" };
774
1177
  }
775
1178
  });
776
1179
  };
777
1180
  }
778
- 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 };