@sentry/junior 0.296.0 → 0.298.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/dist/{admin-z_lgDi-z.js → admin-BF3DbYGf.js} +2 -2
  2. package/dist/{agent-runner-HoQiUKLL.js → agent-runner-Q9GkoerG.js} +407 -1895
  3. package/dist/api/schema.d.ts +2 -2
  4. package/dist/api/schema.js +7 -7
  5. package/dist/api.d.ts +1 -1
  6. package/dist/api.js +38 -267
  7. package/dist/{app-C75Ft-A_.d.ts → app-DOg_mCtV.d.ts} +7 -2
  8. package/dist/app.d.ts +1 -1
  9. package/dist/app.js +64 -44
  10. package/dist/attempt-selection-ClP3MMPr.js +61 -0
  11. package/dist/{automation-yJX3C7i3.js → automation-Cn8qmbdr.js} +1 -1
  12. package/dist/{background-compaction-queue-Cre1wFt9.js → background-compaction-queue-BZhGFOK6.js} +4 -88
  13. package/dist/{briefs-BXECHduJ.js → briefs-CQrCRF6-.js} +3 -3
  14. package/dist/{catalog-runtime-CpCmlD9L.js → catalog-runtime-DZeD2WbL.js} +1 -1
  15. package/dist/cli/chat.js +19 -15
  16. package/dist/cli/check.js +3 -3
  17. package/dist/cli/main.js +3 -3
  18. package/dist/cli/plugins.js +4 -4
  19. package/dist/cli/snapshot-create.js +4 -4
  20. package/dist/cli/upgrade.d.ts +1 -1
  21. package/dist/cli/upgrade.js +3 -3
  22. package/dist/{config-CCPHvTqx.js → config-BOByVnxe.js} +2 -2
  23. package/dist/{connections-B5pWh8e2.js → connections-BNN5cJam.js} +6 -6
  24. package/dist/{conversation-CMkSmi02.js → conversation-DCkzvxqB.js} +51 -17
  25. package/dist/{conversation-feed-BVAOga0H.js → conversation-feed-CMA12Rjs.js} +1 -1
  26. package/dist/{conversation-privacy-CZD5soDW.js → conversation-privacy-C0eRxsgb.js} +1 -1
  27. package/dist/conversation-turn-D9qvcDX6.js +805 -0
  28. package/dist/{credential-sync-DwLkIvXI.js → credential-sync-B_iUpxGL.js} +14 -13
  29. package/dist/{db-C1M1y-bh.js → db-CoMNr2Zm.js} +43 -15
  30. package/dist/{db-B3iyr_Or.d.ts → db-DoMcnYol.d.ts} +13 -1
  31. package/dist/{executor-DUSEwXaO.js → executor-C-m8VrzX.js} +14 -6
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{logging-D0svFM8r.js → logging-CJTi5niy.js} +1 -1
  34. package/dist/{message-BFnIwKpx.js → message-Q6_5DAWR.js} +15 -13
  35. package/dist/nitro.d.ts +1 -1
  36. package/dist/nitro.js +3 -2
  37. package/dist/{session-stop-hYNTNpVf.js → notification-Bv25xbj0.js} +11 -930
  38. package/dist/{oauth-callback-server-BXRtD6Fk.js → oauth-callback-server-CH5XAyo-.js} +2 -2
  39. package/dist/{projection-B6VS7kbo.js → projection-BgwEE36_.js} +333 -106
  40. package/dist/{prompt-CD11tfG8.js → prompt-DXc9DYT9.js} +4 -4
  41. package/dist/prompt-input-BUr4J9RO.js +1424 -0
  42. package/dist/{registry-CHewwYEo.js → registry-9XwqSnM-.js} +1 -1
  43. package/dist/reporting-window-DopzcOHh.js +137 -0
  44. package/dist/{resolve-1owMH4qo.js → resolve-DUIAbcRL.js} +3 -3
  45. package/dist/result-C2Vn8QGn.js +463 -0
  46. package/dist/{runner-BtWvJslp.js → runner-CXGtw-Mc.js} +9 -8
  47. package/dist/{sandbox-egress-signals-ByftwJVt.js → sandbox-egress-signals-Di3S_dO7.js} +1 -1
  48. package/dist/{schema-Ct1Zf2xy.d.ts → schema-BnbZ-rKv.d.ts} +14 -107
  49. package/dist/{schema-D2iGyYIp.js → schema-Dyp7racy.js} +11 -48
  50. package/dist/{service-account-BZEuMKdo.js → service-account-DM3KBBeG.js} +3 -3
  51. package/dist/{service-account-DLoeoHww.js → service-account-GzAMUQ8a.js} +3 -3
  52. package/dist/session-stop-D4i7e6iT.js +181 -0
  53. package/dist/{skills-DXgd5Inh.js → skills-DCK9SD_l.js} +2 -2
  54. package/dist/{spawn-YeqlNDv8.js → spawn-6cX6xE9G.js} +6 -5
  55. package/dist/{state-C3CbtD_m.js → state-CSuA2J1V.js} +2 -2
  56. package/dist/{stop-Cze_pEL8.js → stop-Dh2DfwpK.js} +66 -159
  57. package/dist/{store-CZ9vqR4P.js → store-B1zepKG8.js} +11 -4
  58. package/dist/{task-runner-CMiNGsER.js → store-DrA17Fbz.js} +939 -1593
  59. package/dist/task-queue-D1rXWfFN.js +89 -0
  60. package/dist/task-runner-CT4M8oDz.js +291 -0
  61. package/dist/thread-context-DnqUkbzN.js +248 -0
  62. package/dist/turn-cancel-l460pfGW.js +201 -0
  63. package/dist/turn-session-routing-VXDVXLRl.js +380 -0
  64. package/dist/{turn-failure-response-pXhZ2wMK.js → turn-user-message-BSPmkm7X.js} +181 -392
  65. package/dist/turn-wake-DVFVXyhX.js +161 -0
  66. package/dist/{reporting-window-B3Ze-Qnt.js → user-input-request-CXNIov9n.js} +24 -143
  67. package/dist/{validation-Du7NdkOR.js → validation-zxAJBDDy.js} +1 -1
  68. package/dist/{version-EN3Wnq-R.js → version-DcZ40a0g.js} +1 -1
  69. package/dist/version.js +1 -1
  70. package/dist/{viewer-Agxi_o5c.js → viewer-CgiGjW10.js} +3 -3
  71. package/dist/warmup-CwKbxQLl.js +2698 -0
  72. package/dist/{worker-BALVdWbv.js → worker-CbDUzaBA.js} +20 -8
  73. package/migrations/0102_code_change_last_activity.sql +1 -0
  74. package/migrations/0103_agent_invocation_fork.sql +8 -0
  75. package/migrations/meta/0102_snapshot.json +4502 -0
  76. package/migrations/meta/0103_snapshot.json +4509 -0
  77. package/migrations/meta/_journal.json +14 -0
  78. package/package.json +4 -4
  79. package/dist/result-CEqQFrEf.js +0 -305
  80. package/dist/result-event-type-DD6BAgT7.js +0 -11
  81. package/dist/warmup-CY2ArYag.js +0 -2017
  82. package/dist/work-EA98F0ia.js +0 -768
@@ -0,0 +1,2698 @@
1
+ import { n as captureMessage, u as sentry_exports, v as __exportAll } from "./sentry-BRTJqumy.js";
2
+ import { H as PluginCredentialFailureError, K as AuthorizationFlowDisabledError, Mo as FORK_INSTRUCTIONS, No as loadForkHistory, Pn as escapeClosingTags, Qt as isTurnExecutionLimitExceededError, Rn as renderTag, Zo as createPluginCache, _n as getTerminalAssistantMessages, an as getAssistantReplyText, at as failTurnRecord, et as lostWorkerBeforeFirstSave, fn as REPORT_BLOCKED_TOOL_NAME, fo as createPluginLogger, li as listWatches, nr as getPlugins, nt as saveTurnCheckpoint, ot as getTurnRecord, rt as abandonTurnRecord, s as openConversationProjection, sn as NO_REPLY_TOOL_NAME, tn as readTurnAnswer, tt as pauseLostWorkerTurn, v as hydrateConversationMessages } from "./projection-BgwEE36_.js";
3
+ import { E as resolveGatewayModel, K as isProviderRetryError, i as getChatConfig, n as botConfig } from "./config-BOByVnxe.js";
4
+ import { E as withSpan, h as logWarn, m as logInfo, x as setSpanStatus } from "./logging-CJTi5niy.js";
5
+ import { D as turnBehavior, M as SYSTEM_IDENTITY_ID, O as conversationKindFromRow, Q as rootConversationIsArchived, a as getConversationStore, b as userMessageQueries, o as getDb, r as getConversationEventStore, s as getSqlExecutor, w as isPersonInput } from "./db-CoMNr2Zm.js";
6
+ import { A as juniorConversations, g as juniorAgentInvocations, h as juniorAgentBindings } from "./executor-C-m8VrzX.js";
7
+ import { h as contextProvenance, m as agentInstructionProvenance, v as sameActorIdentity } from "./media-BepyEUNm.js";
8
+ import { u as completeText } from "./prompt-DXc9DYT9.js";
9
+ import { a as getStateAdapter } from "./state-CSuA2J1V.js";
10
+ import { O as agentTypeInstructions } from "./conversation-DCkzvxqB.js";
11
+ import { T as systemPromptHash, l as withoutSavedSteeringMessages, o as buildSteeringPiMessage, s as instructionForInputs, v as listActiveMailboxTurns, w as buildDeploymentSystemPrompt } from "./prompt-input-BUr4J9RO.js";
12
+ import { w as getTurnRequestDeadline, y as sendCacheWarmup } from "./background-compaction-queue-BZhGFOK6.js";
13
+ import { c as conversationSubtreeColumns, i as resumeStoppedConversationTree, n as isSkippedAfterConversationStop, r as markConversationsStopped, s as conversationSubtree, t as getConversationStoppedAtMs } from "./session-stop-D4i7e6iT.js";
14
+ import { A as listAgentInvocationsForConversation, C as getActiveAgentInvocationForConversation, D as invocationFromRow, E as getLatestAgentInvocationForConversation, G as agentBindingSchema, I as markAgentInvocationPaused, J as getAgentInvocationId, L as markAgentInvocationRunning, O as isStoppedAgentInvocation, P as markAgentInvocationMailboxAppended, Q as getAgentInvocationMessageId, R as markAgentInvocationSteered, S as completeAgentInvocation, U as CHILD_AGENT_RESULTS, V as sendsResultToParent, Z as getAgentInvocationIdForResult, _ as ConversationTurnLifecycleService, at as getUnnamedAgentConversationId, b as NON_TERMINAL_AGENT_INVOCATION_STATUSES, ct as parseAgentReplyMessageId, d as isTurnInputCommitLostError, dt as buildDeterministicTurnId, et as getAgentInvocationTurnId, j as listOpenAgentInvocations, k as isTerminalAgentInvocation, l as getConversationTurnBoundaryError, lt as parseTurnReplyMessageId, nt as getChildAgentLockName, ot as isAgentReplyMessageId, q as createAgentInvocationSchema, rt as getNamedAgentConversationId, s as TurnInputCommitLostError, st as parseAgentInvocationResultMessageId, w as getAgentInvocation, y as ACTIVE_AGENT_INVOCATION_STATUSES, z as reportReplacedAgentInvocation } from "./turn-user-message-BSPmkm7X.js";
15
+ import { E as resetAutomatedTurnLimit, T as recordFinishedTurnForAutomatedLimit, i as isEventMailboxMetadata, y as maybePostAutomatedTurnLimitNotice } from "./notification-Bv25xbj0.js";
16
+ import { E as stopConversationWork, _ as getConversationWorkState, m as dropPendingMessages, r as appendAndEnqueueInboundMessage } from "./store-B1zepKG8.js";
17
+ import { a as getPersistedThreadState, c as coerceThreadConversationState, i as getPersistedSandboxState, s as persistThreadStateById } from "./turn-session-routing-VXDVXLRl.js";
18
+ import { v as isAgentInvocationResultEventType } from "./user-input-request-CXNIov9n.js";
19
+ import { a as AgentRunError, o as executeTurn, r as supersedeOpenMailboxTurns, s as finishTurn, t as cancelSignInWait } from "./turn-cancel-l460pfGW.js";
20
+ import { streamSimple } from "@earendil-works/pi-ai/compat";
21
+ import { isDeepStrictEqual, promisify } from "node:util";
22
+ import { createHash, randomUUID } from "node:crypto";
23
+ import * as z from "zod";
24
+ import { and, desc, eq, gt, inArray, ne, or, sql } from "drizzle-orm";
25
+ import { constants, zstdCompress, zstdDecompress } from "node:zlib";
26
+ // src/chat/cache-warming/model.ts
27
+ /**
28
+ * Cost model for prompt cache warming.
29
+ *
30
+ * Ported from Lore's cache warmer (BYK/loreai,
31
+ * `packages/gateway/src/cache-warmer.ts`). The model estimates the chance that
32
+ * a person returns to an idle conversation before the cache expires. It then
33
+ * compares that chance with the cost of one more warmup.
34
+ */
35
+ /** One minute in milliseconds. */
36
+ const MINUTE_MS = 6e4;
37
+ /** Upper edges (ms) of the gap histogram bins. */
38
+ const GAP_BIN_EDGES_MS = [
39
+ 1e4,
40
+ 2e4,
41
+ 3e4,
42
+ 45e3,
43
+ MINUTE_MS,
44
+ 1.5 * MINUTE_MS,
45
+ 2 * MINUTE_MS,
46
+ 3 * MINUTE_MS,
47
+ 4 * MINUTE_MS,
48
+ 5 * MINUTE_MS,
49
+ 7 * MINUTE_MS,
50
+ 10 * MINUTE_MS,
51
+ 15 * MINUTE_MS,
52
+ 20 * MINUTE_MS,
53
+ 30 * MINUTE_MS,
54
+ 45 * MINUTE_MS,
55
+ 60 * MINUTE_MS,
56
+ 90 * MINUTE_MS,
57
+ 120 * MINUTE_MS,
58
+ 240 * MINUTE_MS,
59
+ Infinity
60
+ ];
61
+ const GAP_BIN_COUNT = GAP_BIN_EDGES_MS.length;
62
+ /**
63
+ * Gaps that a segment needs before its gaps replace its parent segment's
64
+ * gaps (`parentGapSegment`, or the segment of a `waitingGapSegment`). A new
65
+ * or rare segment starts with its parent's return chances, so it can warm
66
+ * before it has gaps of its own.
67
+ */
68
+ const BLEND_PSEUDOCOUNT = 20;
69
+ /**
70
+ * Gaps that a Conversation needs before its gaps replace its segment's gaps.
71
+ * One Conversation has few gaps, and a few unusual replies say little about
72
+ * its next one. A backtest of time-ordered decisions showed that a weight
73
+ * this slow predicts returns better than both a faster weight and no
74
+ * Conversation weight at all.
75
+ */
76
+ const CONVERSATION_BLEND_PSEUDOCOUNT = 100;
77
+ /** Below this prefix size, one cache miss costs too little to warm for. */
78
+ const MIN_WARMUP_PREFIX_TOKENS = 5e4;
79
+ /**
80
+ * Junior watches an idle period for this long. A person who replies later
81
+ * counts as a person who did not reply. The reply chance of a warmup counts
82
+ * only replies before this time. For a cache that outlives the horizon, this
83
+ * is less than the real chance, so Junior warms less, never more.
84
+ *
85
+ * The horizon message is signed when the idle period starts, and a queue
86
+ * signature is valid for 60 minutes (`QUEUE_SIGNATURE_MAX_AGE_MS`). The other
87
+ * 5 minutes let a late horizon still record its no-reply gap.
88
+ */
89
+ const IDLE_HORIZON_MS = 55 * MINUTE_MS;
90
+ /**
91
+ * Whether a failed warmup request counts as a miss for the provider breaker.
92
+ * A request that the provider rejects fails the same way for each
93
+ * Conversation, so it counts. A retryable failure, such as an overload or a
94
+ * timeout, says nothing about the cache, so it must not stop warming for
95
+ * every Conversation.
96
+ */
97
+ function warmupFailureCountsAsMiss(error) {
98
+ return !isProviderRetryError(error);
99
+ }
100
+ /**
101
+ * Time from a timer's due time to the request of its Turn: the heartbeat
102
+ * fires due timers once a minute, and the Turn then starts.
103
+ */
104
+ const TIMER_START_DELAY_MS = 2 * MINUTE_MS;
105
+ /**
106
+ * Latest timer due time, as idle time, that the timer floor warms for. A
107
+ * warmup costs one cache read, and a miss costs one write minus one read, so
108
+ * the floor sends fewer warmups than the miss costs in reads. The cache of
109
+ * the last warmup must last until the timer's Turn starts. A later timer
110
+ * changes nothing: warming for it costs more than it saves.
111
+ */
112
+ function timerFloorMaxDueIdleMs(prices) {
113
+ const savedPerReturn = prices.cacheWritePrice - prices.cacheReadPrice;
114
+ if (prices.cacheReadPrice <= 0 || savedPerReturn <= 0) return 0;
115
+ const maxWarmups = Math.ceil(savedPerReturn / prices.cacheReadPrice) - 1;
116
+ return prices.cacheTtlMs + maxWarmups * (prices.cacheTtlMs - WARMUP_MARGIN_MS) - TIMER_START_DELAY_MS;
117
+ }
118
+ /** Gap that Junior records for an idle period with no reply in the horizon. */
119
+ const NO_REPLY_GAP_MS = 1440 * MINUTE_MS;
120
+ function binIndex(gapMs) {
121
+ return GAP_BIN_EDGES_MS.findIndex((edge) => gapMs < edge);
122
+ }
123
+ function histogramOf(gapsMs) {
124
+ const counts = Array.from({ length: GAP_BIN_COUNT }, () => 0);
125
+ for (const gap of gapsMs) counts[binIndex(gap)] += 1;
126
+ return {
127
+ counts,
128
+ total: gapsMs.length
129
+ };
130
+ }
131
+ function blendHistograms(own, prior, pseudocount) {
132
+ if (own.total === 0 || prior.total === 0) return own.total === 0 ? prior : own;
133
+ const weight = Math.min(own.total / pseudocount, 1);
134
+ return {
135
+ counts: own.counts.map((count, index) => weight * count / own.total + (1 - weight) * prior.counts[index] / prior.total),
136
+ total: 1
137
+ };
138
+ }
139
+ function survival(histogram, tMs) {
140
+ if (histogram.total === 0) return 1;
141
+ const index = binIndex(tMs);
142
+ let surviving = 0;
143
+ for (let i = index + 1; i < GAP_BIN_COUNT; i++) surviving += histogram.counts[i];
144
+ const binStart = index > 0 ? GAP_BIN_EDGES_MS[index - 1] : 0;
145
+ const fractionPast = Math.min(1, Math.max(0, (tMs - binStart) / (GAP_BIN_EDGES_MS[index] - binStart)));
146
+ surviving += histogram.counts[index] * (1 - fractionPast);
147
+ return surviving / histogram.total;
148
+ }
149
+ function returnProbability(histogram, idleMs, windowMs) {
150
+ const now = survival(histogram, idleMs);
151
+ if (now < .001) return 0;
152
+ return Math.max(0, (now - survival(histogram, idleMs + windowMs)) / now);
153
+ }
154
+ /**
155
+ * How long before cache expiry Junior sends a warmup. A warmup reads each
156
+ * cache block of the prefix in one request, so the provider refreshes all
157
+ * blocks together. A margin that grows with the prefix size gains nothing.
158
+ * The margin covers only the queue delay and the time of the warmup request.
159
+ */
160
+ const WARMUP_MARGIN_MS = 45e3;
161
+ /**
162
+ * Pick the gap histogram for an idle period. Return chances differ most by
163
+ * who started the Turn and by how many Turns the Conversation had before it.
164
+ * Turns that no person started rarely get a quick reply. In 30 days of
165
+ * production data, segments by these two keys saved more than one histogram.
166
+ * Local time of day did not improve the result, so it is not a key.
167
+ *
168
+ * The work state lets the histograms learn how often anything returns after
169
+ * the work is done. An event does not restore an archived Conversation, so
170
+ * most returns to one are events, not people. Its segment has only the work
171
+ * state, which keeps the number of segments small.
172
+ */
173
+ function gapSegment(input) {
174
+ if (input.archived) return `archived:${input.workState}`;
175
+ const depth = input.endedTurns === 0 ? "1" : input.endedTurns < 3 ? "2-3" : "4+";
176
+ return `${input.userActor ? "user" : "system"}:${depth}:${input.workState}`;
177
+ }
178
+ /** Each segment that `gapSegment` returns, in display order. */
179
+ const GAP_SEGMENTS = [...[true, false].flatMap((userActor) => [
180
+ 0,
181
+ 1,
182
+ 3
183
+ ].flatMap((endedTurns) => [
184
+ "open",
185
+ "done",
186
+ "none"
187
+ ].map((workState) => gapSegment({
188
+ userActor,
189
+ endedTurns,
190
+ workState,
191
+ archived: false
192
+ })))), ...[
193
+ "open",
194
+ "done",
195
+ "none"
196
+ ].map((workState) => gapSegment({
197
+ userActor: false,
198
+ endedTurns: 0,
199
+ workState,
200
+ archived: true
201
+ }))];
202
+ /**
203
+ * Count gaps in the bins that `decideWarmup` uses, for reports. A gap at or
204
+ * after `IDLE_HORIZON_MS` is a no-reply gap, as the recorder stores it. The
205
+ * bins after the horizon never get a gap, so they are left out.
206
+ */
207
+ function gapHistogramReport(gapsMs) {
208
+ const { counts } = histogramOf(gapsMs.filter((gapMs) => gapMs < IDLE_HORIZON_MS));
209
+ const bins = [];
210
+ for (const [index, endMs] of GAP_BIN_EDGES_MS.entries()) {
211
+ const startMs = index > 0 ? GAP_BIN_EDGES_MS[index - 1] : 0;
212
+ if (startMs >= 33e5) break;
213
+ bins.push({
214
+ startMs,
215
+ endMs: Math.min(endMs, IDLE_HORIZON_MS),
216
+ count: counts[index]
217
+ });
218
+ }
219
+ return {
220
+ bins,
221
+ noReply: gapsMs.filter((gapMs) => gapMs >= IDLE_HORIZON_MS).length,
222
+ total: gapsMs.length
223
+ };
224
+ }
225
+ /**
226
+ * Segment whose gaps a thin segment leans on: the `none` segment with the
227
+ * same Actor and Turn depth. The backfill and most traffic keep the `none`
228
+ * segments full. A `none` segment that is not archived has no parent.
229
+ */
230
+ function parentGapSegment(input) {
231
+ if (!input.archived && input.workState === "none") return void 0;
232
+ return gapSegment({
233
+ ...input,
234
+ workState: "none",
235
+ archived: false
236
+ });
237
+ }
238
+ /**
239
+ * Child of a segment for an idle period that waits on a child agent or a
240
+ * Review item. Its parent is the segment, so a thin child leans on the
241
+ * segment, and a thin segment on its own parent.
242
+ */
243
+ function waitingGapSegment(segment, waitingOn) {
244
+ return `${segment}:${waitingOn}`;
245
+ }
246
+ /** Whether a segment has too few gaps to stand without its parent. */
247
+ function segmentNeedsParent(segmentGaps) {
248
+ return segmentGaps < BLEND_PSEUDOCOUNT;
249
+ }
250
+ /**
251
+ * Decide whether to send the next warmup.
252
+ *
253
+ * A warmup costs one cache read of the prefix. A return to a warm cache saves
254
+ * one write minus one read. So warming pays when the expected returns per
255
+ * warmup are above read/(write − read). Earlier warmups are already paid, so
256
+ * the threshold is the same for each warmup.
257
+ *
258
+ * One warmup alone can be useless when people return a little after the next
259
+ * TTL, while two or three warmups in a row would reach them. So the decision
260
+ * compares plans of 1, 2, ... warmups up to the horizon. Each plan sends its
261
+ * next warmup only while nobody returned. Junior warms when the best plan
262
+ * pays, and decides again at the next warmup.
263
+ *
264
+ * The timer floor: while the cache would expire before a timer's Turn
265
+ * starts, Junior warms even when no plan pays and after the horizon (reason
266
+ * `timer`). The timer's Turn then reads the cache. The floor only adds
267
+ * warmups, so it never warms less than the decision without a timer.
268
+ */
269
+ function decideWarmup(input) {
270
+ const savedPerReturn = input.cacheWritePrice - input.cacheReadPrice;
271
+ const threshold = savedPerReturn > 0 ? Math.min(input.cacheReadPrice / savedPerReturn, 1) : 1;
272
+ const conversation = histogramOf(input.conversationGapsMs);
273
+ const segments = [histogramOf(input.globalGapsMs)];
274
+ for (const gapsMs of input.priorGapsMs ?? []) {
275
+ if (!segmentNeedsParent(segments.at(-1).total)) break;
276
+ segments.push(histogramOf(gapsMs));
277
+ }
278
+ const segmentGaps = segments.reduce((sum, list) => sum + list.total, 0);
279
+ const histogram = blendHistograms(conversation, segments.reduceRight((prior, own) => blendHistograms(own, prior, BLEND_PSEUDOCOUNT)), CONVERSATION_BLEND_PSEUDOCOUNT);
280
+ const probability = returnProbability(histogram, input.idleMs, Math.min(input.cacheTtlMs, IDLE_HORIZON_MS - input.idleMs));
281
+ const perWarmup = returnsPerWarmup(histogram, input.idleMs, input.cacheExpiryIdleMs, input.cacheTtlMs);
282
+ const decision = (reason) => ({
283
+ warm: reason === "warm" || reason === "timer",
284
+ reason,
285
+ returnProbability: probability,
286
+ returnsPerWarmup: perWarmup,
287
+ threshold,
288
+ parentPrior: segmentGaps > segments[0].total
289
+ });
290
+ if (input.prefixTokens < 5e4) return decision("prefix_too_small");
291
+ if (threshold >= 1) return decision("no_savings");
292
+ const timerFloor = input.timerDueIdleMs !== void 0 && input.cacheExpiryIdleMs < input.timerDueIdleMs + 12e4;
293
+ const reason = input.idleMs >= 33e5 ? "horizon" : conversation.total + segmentGaps < 20 ? "few_gaps" : perWarmup >= threshold ? "warm" : "unlikely_return";
294
+ return decision(reason !== "warm" && timerFloor ? "timer" : reason);
295
+ }
296
+ function returnsPerWarmup(histogram, idleMs, cacheExpiryIdleMs, ttlMs) {
297
+ const now = survival(histogram, idleMs);
298
+ const intervalMs = ttlMs - WARMUP_MARGIN_MS;
299
+ if (now < .001 || intervalMs <= 0) return 0;
300
+ const leftAtExpiry = survival(histogram, Math.min(cacheExpiryIdleMs, IDLE_HORIZON_MS));
301
+ let best = 0;
302
+ let warmups = 0;
303
+ for (let startMs = idleMs; startMs < IDLE_HORIZON_MS; startMs += intervalMs) {
304
+ warmups += survival(histogram, startMs) / now;
305
+ const endMs = Math.min(startMs + ttlMs, IDLE_HORIZON_MS);
306
+ const returns = Math.max(0, leftAtExpiry - survival(histogram, endMs)) / now;
307
+ best = Math.max(best, returns / warmups);
308
+ }
309
+ return best;
310
+ }
311
+ // src/chat/cache-warming/request.ts
312
+ const KEY_PREFIX = "junior:cache_warming";
313
+ const CACHE_RETENTION = "short";
314
+ const REFRESHED_READ_FRACTION = .9;
315
+ const BREAKER_OUTCOMES_MAX = 20;
316
+ const BREAKER_MAX_MISSES = 10;
317
+ const BREAKER_OUTCOMES_TTL_MS = 360 * MINUTE_MS;
318
+ const BREAKER_OPEN_TTL_MS = 1440 * MINUTE_MS;
319
+ const breakerOutcomesKey = (provider) => `${KEY_PREFIX}:breaker:${provider}:outcomes`;
320
+ const breakerOpenKey = (provider) => `${KEY_PREFIX}:breaker:${provider}:open`;
321
+ const providerOf = (modelId) => modelId.split("/")[0] ?? "";
322
+ /** Connect the state adapter that holds cache warming state. */
323
+ async function connectedState() {
324
+ const state = getStateAdapter();
325
+ await state.connect();
326
+ return state;
327
+ }
328
+ const CACHE_TTL_MS = {
329
+ anthropic: 5 * MINUTE_MS,
330
+ alibaba: 5 * MINUTE_MS,
331
+ openai: 30 * MINUTE_MS
332
+ };
333
+ /**
334
+ * Return true when warmups can refresh the prompt cache of this request.
335
+ * Warming pays only when a cache write costs more than a read. Pi adds a
336
+ * thinking budget to the one-token output limit on the Anthropic Messages API
337
+ * for models without adaptive thinking. Then a warmup could cost as much as a
338
+ * short answer, and a smaller budget would miss the cached messages.
339
+ */
340
+ function supportsWarming(request) {
341
+ const { model, reasoning } = request;
342
+ const budgetThinking = reasoning !== void 0 && model.api === "anthropic-messages" && model.compat?.forceAdaptiveThinking !== true;
343
+ return CACHE_TTL_MS[providerOf(model.id)] !== void 0 && model.cost.cacheRead > 0 && model.cost.cacheWrite > model.cost.cacheRead && !budgetThinking && request.cacheRetention === "short";
344
+ }
345
+ /** Return the cache TTL of a request that Junior can warm. */
346
+ function cacheTtlMs(request) {
347
+ return supportsWarming(request) ? CACHE_TTL_MS[providerOf(request.model.id)] : void 0;
348
+ }
349
+ /** Return the cached prefix tokens of a finished model request. */
350
+ function cachedPrefixTokens(message) {
351
+ return message.usage.cacheRead + message.usage.cacheWrite;
352
+ }
353
+ /**
354
+ * Return when the cache that a request at `requestStartedAtMs` read or wrote
355
+ * expires, and the delay until the warmup that refreshes it.
356
+ */
357
+ function warmupTiming(requestStartedAtMs, ttlMs) {
358
+ const cacheExpiresAtMs = requestStartedAtMs + ttlMs;
359
+ return {
360
+ cacheExpiresAtMs,
361
+ delayMs: cacheExpiresAtMs - WARMUP_MARGIN_MS - Date.now()
362
+ };
363
+ }
364
+ const LATE_WARMUP_MS = 1e4;
365
+ /**
366
+ * Return true when a warmup is too late to refresh the cache. The cache is
367
+ * gone, so the warmup must not run or count as a miss.
368
+ */
369
+ function warmupTooLate(cacheExpiresAtMs) {
370
+ return Date.now() + LATE_WARMUP_MS >= cacheExpiresAtMs;
371
+ }
372
+ /**
373
+ * Return true while too many recent warmups of the model's provider missed,
374
+ * so its warming is off.
375
+ */
376
+ async function breakerOpen(state, modelId) {
377
+ return await state.get(breakerOpenKey(providerOf(modelId))) === true;
378
+ }
379
+ async function countOutcome(state, modelId, miss) {
380
+ const provider = providerOf(modelId);
381
+ await state.appendToList(breakerOutcomesKey(provider), miss ? 1 : 0, {
382
+ maxLength: BREAKER_OUTCOMES_MAX,
383
+ ttlMs: BREAKER_OUTCOMES_TTL_MS
384
+ });
385
+ if (!miss) return;
386
+ const outcomes = await state.getList(breakerOutcomesKey(provider));
387
+ const misses = outcomes.filter((outcome) => outcome === 1).length;
388
+ if (misses >= BREAKER_MAX_MISSES && await state.setIfNotExists(breakerOpenKey(provider), true, BREAKER_OPEN_TTL_MS)) captureMessage("Cache warming stopped: too many warmups missed the cache", {
389
+ level: "error",
390
+ fingerprint: ["cache_warming.breaker.opened", provider],
391
+ tags: { "gen_ai.request.model": modelId },
392
+ extra: {
393
+ "app.cache_warming.misses": misses,
394
+ "app.cache_warming.outcomes": outcomes.length
395
+ }
396
+ });
397
+ }
398
+ /**
399
+ * Send one warmup: the same request with a one-token output limit. Count its
400
+ * outcome for the breaker, and report a miss to Sentry. A rejected request
401
+ * counts as a miss and rethrows, because it fails the same way for each
402
+ * Conversation.
403
+ */
404
+ async function sendWarmup(state, params) {
405
+ const { conversationId, modelId, context, prefixTokens } = params;
406
+ const { message: result } = await completeText({
407
+ modelId,
408
+ system: context.systemPrompt,
409
+ messages: context.messages,
410
+ ...context.tools ? { tools: context.tools } : void 0,
411
+ ...params.reasoning ? { thinkingLevel: params.reasoning } : void 0,
412
+ cacheRetention: CACHE_RETENTION,
413
+ maxTokens: 1,
414
+ messageAttributeMode: "metadata",
415
+ metadata: { conversationId },
416
+ operation: "cache_warmup",
417
+ cost: { conversationId },
418
+ sessionId: conversationId
419
+ }).catch(async (error) => {
420
+ if (warmupFailureCountsAsMiss(error)) await countOutcome(state, modelId, true);
421
+ throw error;
422
+ });
423
+ const attributes = {
424
+ "app.cost.total_usd": result.usage.cost.total,
425
+ "gen_ai.usage.cache_read.input_tokens": result.usage.cacheRead,
426
+ "gen_ai.usage.cache_creation.input_tokens": result.usage.cacheWrite
427
+ };
428
+ const refreshed = result.usage.cacheRead >= prefixTokens * REFRESHED_READ_FRACTION;
429
+ if (!refreshed) captureMessage("Cache warmup missed the cache", {
430
+ level: "warning",
431
+ fingerprint: ["cache_warming.warmup.missed", modelId],
432
+ tags: { "gen_ai.request.model": modelId },
433
+ extra: { "app.cache_warming.read_fraction": result.usage.cacheRead / prefixTokens }
434
+ });
435
+ await countOutcome(state, modelId, !refreshed);
436
+ return {
437
+ refreshed,
438
+ attributes
439
+ };
440
+ }
441
+ // src/chat/cache-warming/snapshot.ts
442
+ /**
443
+ * Storage format of the idle-period snapshot: the exact Pi context of the
444
+ * request that ended a Turn, which each idle warmup sends again.
445
+ *
446
+ * Base64 image data does not compress, so one screenshot can make a snapshot
447
+ * too large to store. The data of each image part moves to its own state key,
448
+ * named by its SHA-256 hash, and the snapshot keeps `sha256:<hash>` in its
449
+ * place. Base64 has no `:`, so a reference cannot be image data.
450
+ * The next Turn's snapshot often holds the same images, so it writes the same
451
+ * keys again and refreshes their TTL. A loaded snapshot gets each image's
452
+ * data back at the same JSON position, so the warmup request is the same as
453
+ * the original request and reads its cached prefix. A snapshot with a missing
454
+ * image does not load: a changed request would write a new cache entry.
455
+ * Deleting a snapshot keeps its images, because the next snapshot of the
456
+ * Conversation likely holds them. They expire with their TTL.
457
+ * A snapshot whose images are over their own limit is not stored, so one
458
+ * Conversation cannot keep an unbounded amount of image data in state.
459
+ * Removing its images would change the request, so it would miss the cache.
460
+ */
461
+ const zstdCompress$1 = promisify(zstdCompress);
462
+ const zstdDecompress$1 = promisify(zstdDecompress);
463
+ const SNAPSHOT_ZSTD_PARAMS = { params: { [constants.ZSTD_c_compressionLevel]: 1 } };
464
+ const MAX_SNAPSHOT_BYTES = 1048576;
465
+ const MAX_SNAPSHOT_IMAGE_BYTES = 33554432;
466
+ const IMAGE_REF_PREFIX = "sha256:";
467
+ const imageKey = (conversationId, sha256) => `${KEY_PREFIX}:image:${conversationId}:${sha256}`;
468
+ function imageParts(message) {
469
+ if (message.role === "assistant" || typeof message.content === "string") return [];
470
+ return message.content.filter((part) => part.type === "image");
471
+ }
472
+ function snapshotContext(context, toRef) {
473
+ return {
474
+ ...context.systemPrompt !== void 0 ? { systemPrompt: context.systemPrompt } : void 0,
475
+ messages: context.messages.map((message) => message.role === "assistant" || typeof message.content === "string" ? message : {
476
+ ...message,
477
+ content: message.content.map(toRef)
478
+ }),
479
+ ...context.tools ? { tools: context.tools.map((tool) => ({
480
+ name: tool.name,
481
+ description: tool.description,
482
+ parameters: tool.parameters,
483
+ ...tool.constrainedSampling !== void 0 ? { constrainedSampling: tool.constrainedSampling } : void 0
484
+ })) } : void 0
485
+ };
486
+ }
487
+ /**
488
+ * Store the snapshot of a request context with its images under hash keys.
489
+ * Stores nothing and returns a `skipReason` when the snapshot without its
490
+ * images or the images are over their limit. Every key expires after `ttlMs`.
491
+ */
492
+ async function saveSnapshot(state, conversationId, key, context, ttlMs) {
493
+ const images = /* @__PURE__ */ new Map();
494
+ const toRef = (part) => {
495
+ if (part.type !== "image") return part;
496
+ const sha256 = createHash("sha256").update(part.data).digest("hex");
497
+ images.set(sha256, part.data);
498
+ return {
499
+ ...part,
500
+ data: `${IMAGE_REF_PREFIX}${sha256}`
501
+ };
502
+ };
503
+ const snapshot = (await zstdCompress$1(JSON.stringify(snapshotContext(context, toRef)), SNAPSHOT_ZSTD_PARAMS)).toString("base64");
504
+ const size = {
505
+ bytes: snapshot.length,
506
+ imageCount: images.size,
507
+ imageBytes: [...images.values()].reduce((sum, data) => sum + data.length, 0)
508
+ };
509
+ if (size.bytes > MAX_SNAPSHOT_BYTES) return {
510
+ ...size,
511
+ skipReason: "snapshot_too_large"
512
+ };
513
+ if (size.imageBytes > MAX_SNAPSHOT_IMAGE_BYTES) return {
514
+ ...size,
515
+ skipReason: "images_too_large"
516
+ };
517
+ await state.set(key, snapshot, ttlMs);
518
+ await Promise.all([...images].map(([sha256, data]) => state.set(imageKey(conversationId, sha256), data, ttlMs)));
519
+ return size;
520
+ }
521
+ /**
522
+ * Load a stored snapshot with its image data. Returns `stopped` when the
523
+ * snapshot is gone and `image_missing` when one of its images is gone.
524
+ */
525
+ async function loadSnapshot(state, conversationId, key) {
526
+ const snapshot = await state.get(key);
527
+ if (!snapshot) return "stopped";
528
+ const context = JSON.parse((await zstdDecompress$1(Buffer.from(snapshot, "base64"))).toString("utf8"));
529
+ for (const part of context.messages.flatMap(imageParts)) {
530
+ if (!part.data.startsWith(IMAGE_REF_PREFIX)) continue;
531
+ const sha256 = part.data.slice(7);
532
+ const data = await state.get(imageKey(conversationId, sha256));
533
+ if (data === null) return "image_missing";
534
+ part.data = data;
535
+ }
536
+ return context;
537
+ }
538
+ // src/chat/cache-warming/tool-wait.ts
539
+ const TOOL_WAIT_GAPS_KEY = `${KEY_PREFIX}:gaps:tool_wait`;
540
+ const TOOL_WAIT_GAPS_MAX = 2e3;
541
+ const TOOL_WAIT_GAPS_TTL_MS = 43200 * MINUTE_MS;
542
+ const MIN_RECORDED_TOOL_WAIT_MS = 2 * MINUTE_MS;
543
+ /** Create the tool wait warmer of one agent run. */
544
+ function createToolWaitWarmer(conversationId) {
545
+ let timer;
546
+ let waiting;
547
+ let returnedAtMs;
548
+ let generation = 0;
549
+ const schedule = (cache, refreshedAtMs, cycle) => {
550
+ const current = generation;
551
+ const { cacheExpiresAtMs, delayMs } = warmupTiming(refreshedAtMs, cache.ttlMs);
552
+ timer = setTimeout(() => {
553
+ timer = void 0;
554
+ warm(cache, cacheExpiresAtMs, cycle, current);
555
+ }, Math.max(0, delayMs));
556
+ timer.unref?.();
557
+ };
558
+ const warm = (cache, cacheExpiresAtMs, cycle, current) => {
559
+ const { request, prefixTokens } = cache;
560
+ const attributes = {
561
+ "app.cache_warming.cycle": cycle,
562
+ "app.cache_warming.prefix_tokens": prefixTokens,
563
+ "app.cache_warming.trigger": "tool_wait"
564
+ };
565
+ return withSpan("cache_warming.warmup", "cache_warming.warmup", {
566
+ conversationId,
567
+ modelId: request.model.id
568
+ }, async (setSpanAttributes) => {
569
+ const setOutcome = (outcome, extra = {}) => setSpanAttributes({
570
+ ...attributes,
571
+ ...extra,
572
+ "app.cache_warming.outcome": outcome
573
+ });
574
+ const skip = (reason) => {
575
+ const skipReason = { "app.cache_warming.skip_reason": reason };
576
+ logInfo("cache_warming.warmup.skipped", {
577
+ ...attributes,
578
+ ...skipReason
579
+ });
580
+ setOutcome("skipped", skipReason);
581
+ };
582
+ if (warmupTooLate(cacheExpiresAtMs)) {
583
+ skip("cache_expired");
584
+ return;
585
+ }
586
+ try {
587
+ const state = await connectedState();
588
+ if (await breakerOpen(state, request.model.id)) {
589
+ skip("breaker_open");
590
+ return;
591
+ }
592
+ const decision = decideWarmup({
593
+ conversationGapsMs: [],
594
+ globalGapsMs: await state.getList(TOOL_WAIT_GAPS_KEY),
595
+ idleMs: Date.now() - request.startedAtMs,
596
+ cacheExpiryIdleMs: cacheExpiresAtMs - request.startedAtMs,
597
+ cacheTtlMs: cache.ttlMs,
598
+ prefixTokens,
599
+ cacheReadPrice: request.model.cost.cacheRead,
600
+ cacheWritePrice: request.model.cost.cacheWrite
601
+ });
602
+ attributes["app.cache_warming.return_probability"] = decision.returnProbability;
603
+ attributes["app.cache_warming.returns_per_warmup"] = decision.returnsPerWarmup;
604
+ attributes["app.cache_warming.threshold"] = decision.threshold;
605
+ if (current !== generation) {
606
+ setOutcome("skipped", { "app.cache_warming.skip_reason": "stopped" });
607
+ return;
608
+ }
609
+ if (!decision.warm) {
610
+ skip(decision.reason);
611
+ return;
612
+ }
613
+ const startedAtMs = Date.now();
614
+ const warmup = await sendWarmup(state, {
615
+ conversationId,
616
+ modelId: request.model.id,
617
+ context: request.context,
618
+ ...request.reasoning ? { reasoning: request.reasoning } : void 0,
619
+ prefixTokens
620
+ });
621
+ Object.assign(attributes, warmup.attributes);
622
+ if (!warmup.refreshed) {
623
+ logWarn("cache_warming.warmup.failed", attributes);
624
+ setOutcome("missed");
625
+ return;
626
+ }
627
+ logInfo("cache_warming.warmup.completed", attributes);
628
+ setOutcome("completed");
629
+ if (current === generation) schedule(cache, startedAtMs, cycle + 1);
630
+ } catch (error) {
631
+ logWarn("cache_warming.warmup.failed", {
632
+ ...attributes,
633
+ "exception.message": error instanceof Error ? error.message : String(error)
634
+ });
635
+ setOutcome("failed", { "error.type": error instanceof Error ? error.name : typeof error });
636
+ setSpanStatus("error");
637
+ }
638
+ }, attributes);
639
+ };
640
+ const stop = () => {
641
+ generation += 1;
642
+ clearTimeout(timer);
643
+ timer = void 0;
644
+ };
645
+ const recordWait = async (waitMs) => {
646
+ if (waitMs < MIN_RECORDED_TOOL_WAIT_MS) return;
647
+ await (await connectedState()).appendToList(TOOL_WAIT_GAPS_KEY, waitMs, {
648
+ maxLength: TOOL_WAIT_GAPS_MAX,
649
+ ttlMs: TOOL_WAIT_GAPS_TTL_MS
650
+ });
651
+ };
652
+ return {
653
+ async record(request, message) {
654
+ stop();
655
+ const previous = waiting;
656
+ waiting = message.stopReason === "toolUse" ? request : void 0;
657
+ returnedAtMs = void 0;
658
+ const prefixTokens = cachedPrefixTokens(message);
659
+ const ttlMs = cacheTtlMs(request);
660
+ if (waiting && prefixTokens >= 5e4 && ttlMs !== void 0) schedule({
661
+ request,
662
+ prefixTokens,
663
+ ttlMs
664
+ }, request.startedAtMs, 1);
665
+ if (previous) await recordWait(request.startedAtMs - previous.startedAtMs);
666
+ },
667
+ stop,
668
+ toolsReturned() {
669
+ stop();
670
+ if (waiting) returnedAtMs ??= Date.now();
671
+ },
672
+ async end() {
673
+ stop();
674
+ const open = waiting;
675
+ const returned = returnedAtMs;
676
+ waiting = void 0;
677
+ returnedAtMs = void 0;
678
+ if (!open) return;
679
+ if (returned !== void 0) {
680
+ await recordWait(returned - open.startedAtMs);
681
+ return;
682
+ }
683
+ if (Date.now() - open.startedAtMs >= MIN_RECORDED_TOOL_WAIT_MS) await recordWait(NO_REPLY_GAP_MS);
684
+ }
685
+ };
686
+ }
687
+ // src/chat/agent-invocations/thread-turn.ts
688
+ /**
689
+ * A person's Turn in a Thread runs on the Conversation loop. A
690
+ * person's Turn and an Agent invocation Turn are never open at the same time.
691
+ */
692
+ /**
693
+ * End a person's open Turn in a Thread before an agent invocation starts, as
694
+ * new input does on a root. Only a Turn that waits for sign-in or lost its
695
+ * worker can be open here: a yielded Turn resumes before new input.
696
+ */
697
+ async function supersedeOpenMailboxTurn(conversationId) {
698
+ if ((await listActiveMailboxTurns(conversationId)).length === 0) return;
699
+ const conversation = coerceThreadConversationState(await getPersistedThreadState(conversationId));
700
+ await hydrateConversationMessages({
701
+ conversation,
702
+ conversationId
703
+ });
704
+ await supersedeOpenMailboxTurns({
705
+ conversation,
706
+ conversationId
707
+ });
708
+ await persistThreadStateById(conversationId, { conversation });
709
+ }
710
+ // src/chat/agent-invocations/bindings.ts
711
+ function bindingFromRow(row) {
712
+ return agentBindingSchema.parse({
713
+ childConversationId: row.childConversationId,
714
+ name: row.name,
715
+ parentConversationId: row.parentConversationId
716
+ });
717
+ }
718
+ /** Read one named child binding in its parent-agent scope. */
719
+ async function getAgentBinding(args) {
720
+ const rows = await getSqlExecutor().db().select().from(juniorAgentBindings).where(and(eq(juniorAgentBindings.parentConversationId, args.parentConversationId), eq(juniorAgentBindings.name, args.name)));
721
+ return rows[0] ? bindingFromRow(rows[0]) : void 0;
722
+ }
723
+ /** Find a direct child agent of one parent by name or child Conversation id. */
724
+ async function findChildAgentConversationId(args) {
725
+ const binding = await getAgentBinding({
726
+ name: args.target,
727
+ parentConversationId: args.parentConversationId
728
+ });
729
+ if (binding) return binding.childConversationId;
730
+ return (await getSqlExecutor().db().select({ childConversationId: juniorAgentInvocations.childConversationId }).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, args.parentConversationId), eq(juniorAgentInvocations.childConversationId, args.target))).limit(1))[0]?.childConversationId;
731
+ }
732
+ // src/chat/agent-invocations/errors.ts
733
+ /** A child agent already uses this name in the parent Conversation. */
734
+ var AgentNameInUseError = class extends Error {
735
+ constructor(name) {
736
+ super(`A child agent named "${name}" already exists`);
737
+ this.name = "AgentNameInUseError";
738
+ }
739
+ };
740
+ /** Parent already has the maximum number of non-terminal child invocations. */
741
+ var AgentInvocationLimitError = class extends Error {
742
+ constructor(limit) {
743
+ super(`Parent already has ${limit} active child agent invocations (limit ${limit})`);
744
+ this.name = "AgentInvocationLimitError";
745
+ }
746
+ };
747
+ /**
748
+ * The Conversation that calls spawnAgent is too deep to start child agents,
749
+ * or its parent chain does not end at a root.
750
+ */
751
+ var AgentDepthLimitError = class extends Error {
752
+ constructor(maxAgentDepth) {
753
+ super(`This agent cannot start child agents: only ${maxAgentDepth} level(s) of child agents can start their own`);
754
+ this.name = "AgentDepthLimitError";
755
+ }
756
+ };
757
+ /** A child agent already has the maximum number of open tasks. */
758
+ var AgentMessageQueueFullError = class extends Error {
759
+ constructor(limit) {
760
+ super(`The child agent already has ${limit} open tasks`);
761
+ this.name = "AgentMessageQueueFullError";
762
+ }
763
+ };
764
+ /**
765
+ * A messageAgent target is not the parent, a child, or a top-level agent that
766
+ * the sender can message.
767
+ */
768
+ var AgentMessageTargetError = class extends Error {
769
+ constructor(message) {
770
+ super(message);
771
+ this.name = "AgentMessageTargetError";
772
+ }
773
+ };
774
+ /** A top-level agent paused automated Turns, so it takes no agent message. */
775
+ var AgentMessagePausedError = class extends Error {
776
+ constructor(conversationId) {
777
+ super(`${conversationId} paused automated work until a person replies there`);
778
+ this.name = "AgentMessagePausedError";
779
+ }
780
+ };
781
+ /**
782
+ * Cap the non-terminal agent invocations of one child, including the one that
783
+ * runs. Each message to a busy child queues one more.
784
+ */
785
+ const MAX_OPEN_AGENT_INVOCATIONS_PER_CHILD = 4;
786
+ /**
787
+ * Insert one pending agent invocation and read it back. An existing row with
788
+ * the same id wins, so the caller checks that the row it reads is its own.
789
+ */
790
+ async function insertAgentInvocation(invocation, nowMs) {
791
+ await getSqlExecutor().db().insert(juniorAgentInvocations).values({
792
+ ...invocation,
793
+ agentName: invocation.agentName ?? null,
794
+ agentType: invocation.agentType ?? null,
795
+ fork: invocation.fork ?? false,
796
+ credentialContext: invocation.credentialContext ?? null,
797
+ parentToolCallId: invocation.parentToolCallId ?? null,
798
+ reasoningLevel: invocation.reasoningLevel ?? null,
799
+ source: invocation.source ?? { kind: "agent_invocation" },
800
+ title: invocation.title ?? null,
801
+ status: "pending",
802
+ mailboxStatus: "pending",
803
+ createdAt: new Date(nowMs),
804
+ updatedAt: new Date(nowMs),
805
+ terminalAt: null
806
+ }).onConflictDoNothing();
807
+ return await getAgentInvocation(invocation.invocationId);
808
+ }
809
+ /**
810
+ * Require every durable creation input to match before replaying one key.
811
+ * The title is not compared: a retry can generate a different one, and the
812
+ * stored title wins.
813
+ */
814
+ function sameCreateInput(invocation, input) {
815
+ return invocation.parentConversationId === input.parentConversationId && invocation.agentName === input.agentName && invocation.input === input.input && invocation.agentType === input.agentType && invocation.fork === input.fork && invocation.reasoningLevel === input.reasoningLevel && JSON.stringify(invocation.actor) === JSON.stringify(input.actor) && JSON.stringify(invocation.credentialContext) === JSON.stringify(input.credentialContext) && JSON.stringify(invocation.destination) === JSON.stringify(input.destination);
816
+ }
817
+ /**
818
+ * A stopped child agent cannot start or give work to child agents until its
819
+ * parent gives it new work. A Turn on the child's Conversation loop
820
+ * has no open agent invocation, but it can. A root Conversation has no agent
821
+ * invocation, so it always passes. `open` is the parent's open work from
822
+ * `listOpenAgentInvocations`.
823
+ */
824
+ async function assertCanGiveChildWork(parentConversationId, open) {
825
+ if (open.some((row) => row.childConversationId === parentConversationId)) return;
826
+ const latest = await getLatestAgentInvocationForConversation(parentConversationId);
827
+ if (latest && isStoppedAgentInvocation(latest)) throw new Error(`Agent conversation ${parentConversationId} is stopped and cannot give work to child agents`);
828
+ }
829
+ /**
830
+ * Throw when giving work to one child agent would put its parent over
831
+ * `MAX_ACTIVE_AGENT_INVOCATIONS_PER_PARENT`. A child agent is active while it
832
+ * has open work, so a busy child already counts and messages queued for it
833
+ * do not count again. A new or idle child becomes active. This is the only
834
+ * place the rule for which child agents count lives. `open` is the parent's
835
+ * open work from `listOpenAgentInvocations`.
836
+ */
837
+ function assertChildAgentCapacity(open, args) {
838
+ const active = new Set(open.filter((row) => row.parentConversationId === args.parentConversationId).map((row) => row.childConversationId));
839
+ if (!active.has(args.childConversationId) && active.size >= 8) throw new AgentInvocationLimitError(8);
840
+ }
841
+ /**
842
+ * Create or replay the first invocation of one new child agent. A name gives
843
+ * the child a stable Conversation id that later messages can address. A name
844
+ * that is already used throws: later work for that child goes through
845
+ * `createAgentInvocationForMessage`.
846
+ */
847
+ async function createAgentInvocation(rawInput, nowMs = Date.now()) {
848
+ const input = createAgentInvocationSchema.parse(rawInput);
849
+ const invocationId = getAgentInvocationId(input.parentConversationId, input.idempotencyKey);
850
+ const childConversationId = input.agentName ? getNamedAgentConversationId(input.parentConversationId, input.agentName) : getUnnamedAgentConversationId(invocationId);
851
+ const lockName = getChildAgentLockName(input.parentConversationId);
852
+ return await getSqlExecutor().withLock(lockName, async () => {
853
+ const existing = await getAgentInvocation(invocationId);
854
+ if (existing) {
855
+ const child = await getConversationStore().get({ conversationId: existing.childConversationId });
856
+ if (!sameCreateInput(existing, input) || child?.kind !== input.kind) throw new Error(`Agent invocation idempotency key was reused with different input for ${invocationId}`);
857
+ return existing;
858
+ }
859
+ const open = await listOpenAgentInvocations(input.parentConversationId);
860
+ await assertCanGiveChildWork(input.parentConversationId, open);
861
+ if (input.agentName && await getAgentBinding({
862
+ name: input.agentName,
863
+ parentConversationId: input.parentConversationId
864
+ })) throw new AgentNameInUseError(input.agentName);
865
+ assertChildAgentCapacity(open, {
866
+ childConversationId,
867
+ parentConversationId: input.parentConversationId
868
+ });
869
+ await getConversationStore().createChild({
870
+ childConversationId,
871
+ kind: input.kind,
872
+ parentConversationId: input.parentConversationId,
873
+ nowMs,
874
+ source: "internal",
875
+ ...input.title ? { title: input.title } : void 0
876
+ });
877
+ if (input.agentName) await getSqlExecutor().db().insert(juniorAgentBindings).values({
878
+ childConversationId,
879
+ name: input.agentName,
880
+ parentConversationId: input.parentConversationId
881
+ });
882
+ const invocation = await insertAgentInvocation({
883
+ actor: input.actor,
884
+ agentName: input.agentName,
885
+ agentType: input.agentType,
886
+ childConversationId,
887
+ credentialContext: input.credentialContext,
888
+ destination: input.destination,
889
+ fork: input.fork,
890
+ input: input.input,
891
+ invocationId,
892
+ parentConversationId: input.parentConversationId,
893
+ parentToolCallId: input.parentToolCallId,
894
+ reasoningLevel: input.reasoningLevel,
895
+ title: input.title
896
+ }, nowMs);
897
+ if (!invocation || !sameCreateInput(invocation, input)) throw new Error(`Agent invocation creation raced for ${invocationId}`);
898
+ return invocation;
899
+ });
900
+ }
901
+ /**
902
+ * Create or replay the agent invocation that gives one input to a child
903
+ * Conversation: a result or message from its own child agent, or its own
904
+ * watch events. It continues that Conversation for the same parent as
905
+ * `latest`, and for the same Actor and credentials unless `runAs` sets them.
906
+ * It skips the queue and active-count checks because it continues work that
907
+ * already passed them.
908
+ */
909
+ async function createAgentInvocationFromLatest(args, nowMs = Date.now()) {
910
+ const { latest } = args;
911
+ const { actor, credentialContext } = args.runAs ?? latest;
912
+ const invocation = await insertAgentInvocation({
913
+ actor,
914
+ agentName: latest.agentName,
915
+ agentType: latest.agentType,
916
+ childConversationId: latest.childConversationId,
917
+ credentialContext,
918
+ destination: latest.destination,
919
+ input: args.input,
920
+ invocationId: args.invocationId,
921
+ parentConversationId: latest.parentConversationId,
922
+ reasoningLevel: latest.reasoningLevel,
923
+ source: args.runAs?.source
924
+ }, nowMs);
925
+ if (!invocation || invocation.childConversationId !== latest.childConversationId) throw new Error(`Agent invocation creation raced for ${args.invocationId}`);
926
+ return invocation;
927
+ }
928
+ /**
929
+ * Create or replay the agent invocation for one message from a parent to one
930
+ * of its child agents. The child continues its history. If the child already
931
+ * has open work, the new agent invocation waits for that work and the parent
932
+ * gets one report for both. A stopped child starts again.
933
+ */
934
+ async function createAgentInvocationForMessage(input, nowMs = Date.now()) {
935
+ const invocationId = getAgentInvocationId(input.parentConversationId, input.idempotencyKey);
936
+ return await getSqlExecutor().withLock(getChildAgentLockName(input.parentConversationId), async () => {
937
+ const existing = await getAgentInvocation(invocationId);
938
+ if (existing) {
939
+ if (existing.childConversationId !== input.childConversationId || existing.input !== input.input) throw new Error(`Agent invocation idempotency key was reused with different input for ${invocationId}`);
940
+ return {
941
+ invocation: existing,
942
+ queued: existing.status === "pending" && (await listOpenAgentInvocations(input.parentConversationId)).some((row) => row.childConversationId === input.childConversationId && row.createdAtMs < existing.createdAtMs)
943
+ };
944
+ }
945
+ const latest = await getLatestAgentInvocationForConversation(input.childConversationId);
946
+ if (!latest || latest.parentConversationId !== input.parentConversationId) throw new Error(`${input.childConversationId} is not a child agent of ${input.parentConversationId}`);
947
+ const open = await listOpenAgentInvocations(input.parentConversationId);
948
+ await assertCanGiveChildWork(input.parentConversationId, open);
949
+ const openCount = open.filter((row) => row.childConversationId === input.childConversationId).length;
950
+ if (openCount >= MAX_OPEN_AGENT_INVOCATIONS_PER_CHILD) throw new AgentMessageQueueFullError(MAX_OPEN_AGENT_INVOCATIONS_PER_CHILD);
951
+ assertChildAgentCapacity(open, {
952
+ childConversationId: input.childConversationId,
953
+ parentConversationId: input.parentConversationId
954
+ });
955
+ const invocation = await insertAgentInvocation({
956
+ actor: input.actor,
957
+ agentName: latest.agentName,
958
+ agentType: latest.agentType,
959
+ childConversationId: input.childConversationId,
960
+ credentialContext: input.credentialContext,
961
+ destination: input.destination,
962
+ input: input.input,
963
+ invocationId,
964
+ parentConversationId: input.parentConversationId,
965
+ parentToolCallId: input.parentToolCallId,
966
+ reasoningLevel: latest.reasoningLevel
967
+ }, nowMs);
968
+ if (!invocation) throw new Error(`Agent invocation creation raced for ${invocationId}`);
969
+ return {
970
+ invocation,
971
+ queued: openCount > 0
972
+ };
973
+ });
974
+ }
975
+ // src/chat/agent-invocations/markers.ts
976
+ /**
977
+ * Dashboard records for agent invocations. The parent Conversation gets one
978
+ * `subagent_started` and one `subagent_ended` event for each agent invocation.
979
+ * The child Conversation gets `message` events for its input and its result,
980
+ * because a child posts nothing to its Location.
981
+ */
982
+ const SUBAGENT_KIND = "agent";
983
+ /**
984
+ * Record in the parent Conversation that one agent invocation started, and
985
+ * record its input as a user message in the child Conversation. The dashboard
986
+ * pairs the parent event with `subagent_ended` to show the child and its
987
+ * status. It must be written before the child mailbox append, so the child
988
+ * cannot end first. An agent wrote the input, not a person, so the message
989
+ * names its agent invocation instead of an author. Input from Events, such as
990
+ * the child's own Watch Events, passes their Event fields, so the dashboard
991
+ * shows it as an Event, as on a root.
992
+ */
993
+ async function recordSubagentStarted(invocation, eventMeta) {
994
+ const eventStore = getConversationEventStore();
995
+ const messageId = getAgentInvocationMessageId(invocation.invocationId);
996
+ await eventStore.append(invocation.childConversationId, [{
997
+ idempotencyKey: `message:${messageId}`,
998
+ data: {
999
+ type: "message",
1000
+ messageId,
1001
+ role: "user",
1002
+ text: invocation.input,
1003
+ meta: {
1004
+ ...eventMeta,
1005
+ agentInvocationId: invocation.invocationId
1006
+ }
1007
+ },
1008
+ createdAtMs: invocation.createdAtMs
1009
+ }]);
1010
+ await eventStore.append(invocation.parentConversationId, [{
1011
+ idempotencyKey: `subagent_started:${invocation.invocationId}`,
1012
+ data: {
1013
+ type: "subagent_started",
1014
+ subagentInvocationId: invocation.invocationId,
1015
+ subagentKind: SUBAGENT_KIND,
1016
+ childConversationId: invocation.childConversationId,
1017
+ ...invocation.agentName ? { agentName: invocation.agentName } : void 0,
1018
+ ...invocation.parentToolCallId ? {
1019
+ parentToolCallId: invocation.parentToolCallId,
1020
+ task: invocation.input
1021
+ } : void 0,
1022
+ ...invocation.title ? { title: invocation.title } : void 0,
1023
+ ...invocation.reasoningLevel ? { reasoningLevel: invocation.reasoningLevel } : void 0
1024
+ },
1025
+ createdAtMs: invocation.createdAtMs
1026
+ }]);
1027
+ }
1028
+ const SUBAGENT_OUTCOMES = {
1029
+ blocked: "blocked",
1030
+ completed: "success",
1031
+ failed: "error",
1032
+ stopped: "aborted"
1033
+ };
1034
+ /**
1035
+ * Record in the parent Conversation how one agent invocation ended, and record
1036
+ * a completed result as an assistant message in the child Conversation. The
1037
+ * heartbeat result repair also calls this, because the child work can be
1038
+ * acknowledged before the worker reports the result.
1039
+ */
1040
+ async function recordSubagentEnded(invocation) {
1041
+ const eventStore = getConversationEventStore();
1042
+ await eventStore.append(invocation.parentConversationId, [{
1043
+ idempotencyKey: `subagent_ended:${invocation.invocationId}`,
1044
+ data: {
1045
+ type: "subagent_ended",
1046
+ subagentInvocationId: invocation.invocationId,
1047
+ outcome: SUBAGENT_OUTCOMES[invocation.status]
1048
+ },
1049
+ createdAtMs: invocation.terminalAtMs
1050
+ }]);
1051
+ const result = invocation.status === "completed" ? invocation.result.trim() : "";
1052
+ if (!result) return;
1053
+ const messageId = `agent-invocation:${invocation.invocationId}:reply`;
1054
+ await eventStore.append(invocation.childConversationId, [{
1055
+ idempotencyKey: `message:${messageId}`,
1056
+ data: {
1057
+ type: "message",
1058
+ messageId,
1059
+ role: "assistant",
1060
+ text: result
1061
+ },
1062
+ createdAtMs: invocation.terminalAtMs
1063
+ }]);
1064
+ }
1065
+ // src/chat/agent-invocations/turn-end.ts
1066
+ /**
1067
+ * How a terminal agent invocation ends its child Turn. The live save and the
1068
+ * recovery paths both use this, so a status cannot end the Turn two ways.
1069
+ */
1070
+ function agentInvocationTurnEnd(terminal) {
1071
+ const finishedAtMs = terminal.terminalAtMs;
1072
+ switch (terminal.status) {
1073
+ case "completed": return {
1074
+ finishedAtMs,
1075
+ outcome: terminal.result.trim() ? "success" : "no_reply"
1076
+ };
1077
+ case "stopped": return {
1078
+ finishedAtMs,
1079
+ outcome: "cancelled"
1080
+ };
1081
+ case "blocked": return {
1082
+ finishedAtMs,
1083
+ outcome: "blocked"
1084
+ };
1085
+ case "failed": return {
1086
+ failureCode: "model_execution_failed",
1087
+ finishedAtMs,
1088
+ outcome: "failed"
1089
+ };
1090
+ }
1091
+ }
1092
+ /**
1093
+ * Read how one saved child Turn ends its agent invocation. A saved `reply`
1094
+ * completes it, also when a newer Turn or a lost worker ended the Turn after
1095
+ * that, or the Turn is paused. Returns undefined for a paused Turn without a
1096
+ * `reply`, which can still resume.
1097
+ */
1098
+ function savedTurnEnd(turn) {
1099
+ const answer = turn.turnStartMessageIndex === void 0 ? void 0 : readTurnAnswer(turn.piMessages.slice(turn.turnStartMessageIndex));
1100
+ if (answer && "reply" in answer) return {
1101
+ result: answer.reply.text,
1102
+ status: "completed"
1103
+ };
1104
+ if (turn.state === "paused") return;
1105
+ if (turn.state !== "completed" || turn.errorMessage) return {
1106
+ errorMessage: turn.errorMessage ?? "Agent invocation failed",
1107
+ status: "failed"
1108
+ };
1109
+ if (answer && "blocked" in answer) return {
1110
+ errorMessage: answer.blocked.missing,
1111
+ status: "blocked"
1112
+ };
1113
+ return {
1114
+ result: answer ? "" : getTerminalAssistantMessages(turn.piMessages).map(getAssistantReplyText).filter((text) => text !== void 0).join("\n\n"),
1115
+ status: "completed"
1116
+ };
1117
+ }
1118
+ // src/chat/agent-invocations/stop.ts
1119
+ /**
1120
+ * Stop one child agent of a parent Conversation and every child agent below
1121
+ * it. The parent gets no result. SQL stops the work first. Then each
1122
+ * Conversation in the tree ends its session. An agent stop is not a person
1123
+ * stop, so their Watches end. A Conversation stop request aborts each run
1124
+ * that is still working.
1125
+ *
1126
+ * Returns undefined when the child does not belong to the parent.
1127
+ */
1128
+ async function stopChildAgent(args) {
1129
+ const latest = await getLatestAgentInvocationForConversation(args.childConversationId);
1130
+ const wasStopped = latest !== void 0 && (latest.status === "stopped" || isChildAgentSessionStopped(latest, await getConversationStoppedAtMs(args.childConversationId)));
1131
+ const tree = await stopChildAgentInvocations(args);
1132
+ if (!tree) return;
1133
+ await finishStoppedTree(tree, tree.conversationIds, {
1134
+ cancelWatches: true,
1135
+ state: args.state
1136
+ });
1137
+ await dropUnreadLoopReplies([args.parentConversationId, ...tree.conversationIds], tree.conversationIds, args.state);
1138
+ return { stopped: tree.stopped.length > 0 || !wasStopped };
1139
+ }
1140
+ /**
1141
+ * Stop the child agents of a Conversation whose run saw its stop. A child
1142
+ * agent's worker calls this after it records its own stop, and the root work
1143
+ * path in `app/conversation-work.ts` calls it for a root. So this sends no
1144
+ * stop request to that Conversation.
1145
+ *
1146
+ * The worker can see its stop late. The stop already reached every child
1147
+ * agent that existed then, so this stops only child agents that this
1148
+ * Conversation spawned or gave new work to after its stop, even when they
1149
+ * already finished, and everything below them. When the stop already ended,
1150
+ * because a person or the parent gave the Conversation new input, this does
1151
+ * nothing.
1152
+ *
1153
+ * Only a person's stop of this Conversation itself leaves child agents to
1154
+ * stop here: an agent stop, or a stop of a Conversation above it, stops this
1155
+ * Conversation's own agent invocations first, so it cannot spawn more. So
1156
+ * this keeps their Watches, as a person's stop does.
1157
+ */
1158
+ async function stopChildAgentsOf(conversationId, state) {
1159
+ const stoppedAtMs = await getConversationStoppedAtMs(conversationId);
1160
+ if (stoppedAtMs === void 0) return;
1161
+ const nowMs = Date.now();
1162
+ const tree = await stopAgentInvocationTree(conversationId, nowMs, {
1163
+ includeRoot: false,
1164
+ taskedAfterMs: stoppedAtMs
1165
+ });
1166
+ await skipUnreadResults(conversationId, nowMs, state);
1167
+ const stoppedIds = tree.conversationIds.filter((id) => id !== conversationId);
1168
+ await finishStoppedTree(tree, stoppedIds, {
1169
+ cancelWatches: false,
1170
+ nowMs: stoppedAtMs,
1171
+ state
1172
+ });
1173
+ await dropUnreadLoopReplies(tree.conversationIds, stoppedIds, state);
1174
+ await dropOwnUnreadLoopReplies(conversationId, state);
1175
+ }
1176
+ /**
1177
+ * Stop every child agent below a Conversation that a person stops. The
1178
+ * Conversation's own agent invocations stay as they are: when it is a child
1179
+ * agent, its worker records the stop and reports it to its parent. Call it
1180
+ * through `stopConversation`, which stops the Conversation's Turn next.
1181
+ *
1182
+ * The Conversation's run sees its stop only at its next stop signal check.
1183
+ * When it does, `stopChildAgentsOf` stops the child agents that it spawned or
1184
+ * gave new work to before then, at the time of this stop. So input that ends
1185
+ * this stop ends theirs too.
1186
+ */
1187
+ async function stopChildAgentsBelow(conversationId, options) {
1188
+ const { nowMs, stoppedAtMs, state } = options;
1189
+ const tree = await stopAgentInvocationTree(conversationId, nowMs, { includeRoot: false });
1190
+ await skipUnreadResults(conversationId, nowMs, state);
1191
+ const stoppedIds = tree.conversationIds.filter((id) => id !== conversationId);
1192
+ await finishStoppedTree(tree, stoppedIds, {
1193
+ cancelWatches: false,
1194
+ nowMs: stoppedAtMs,
1195
+ state
1196
+ });
1197
+ await dropUnreadLoopReplies(tree.conversationIds, stoppedIds, state);
1198
+ }
1199
+ /**
1200
+ * Skip the `appended` results and replies that still wait in a Conversation's
1201
+ * mailbox, so they start no Turn. A result that the Conversation already read keeps its
1202
+ * status. Call this after the tree stop: it skipped each `pending` result and
1203
+ * stopped each child agent, so no result becomes `appended` after this read.
1204
+ *
1205
+ * The mailbox read is not atomic with the parent worker. A worker that takes
1206
+ * a result before this update holds the work lease, so the stop request of
1207
+ * the Conversation stops its Turn. A result that such a Turn took but did not
1208
+ * ack yet is marked `skipped`.
1209
+ */
1210
+ async function skipUnreadResults(conversationId, nowMs, state) {
1211
+ const invocationIds = ((await getConversationWorkState({
1212
+ conversationId,
1213
+ state
1214
+ }))?.messages ?? []).flatMap((message) => {
1215
+ const invocationId = parseAgentInvocationResultMessageId(message.inboundMessageId) ?? (parseTurnReplyMessageId(message.inboundMessageId) === void 0 ? parseAgentReplyMessageId(message.inboundMessageId) : void 0);
1216
+ return invocationId ? [invocationId] : [];
1217
+ });
1218
+ if (invocationIds.length === 0) return;
1219
+ await getSqlExecutor().db().update(juniorAgentInvocations).set({
1220
+ parentMailboxStatus: "skipped",
1221
+ updatedAt: new Date(nowMs)
1222
+ }).where(and(eq(juniorAgentInvocations.parentConversationId, conversationId), inArray(juniorAgentInvocations.invocationId, invocationIds), eq(juniorAgentInvocations.parentMailboxStatus, "appended")));
1223
+ }
1224
+ /**
1225
+ * Drop the unread replies that Turns on the Conversation loop of the stopped
1226
+ * Conversations left in each mailbox of `mailboxIds`. Such a reply names the
1227
+ * sender's newest finished agent invocation, not work that the stop skips,
1228
+ * so the stop drops it by its message id. A reply sent after the stop is
1229
+ * dropped when it is read, while the sender is stopped. Call this after the
1230
+ * stop is stored.
1231
+ *
1232
+ * A reply that a running Turn already took leaves the mailbox like one that
1233
+ * it read: the Turn's own ack removes nothing more.
1234
+ */
1235
+ async function dropUnreadLoopReplies(mailboxIds, stoppedIds, state) {
1236
+ const stopped = new Set(stoppedIds);
1237
+ for (const conversationId of mailboxIds) {
1238
+ const replies = ((await getConversationWorkState({
1239
+ conversationId,
1240
+ state
1241
+ }))?.messages ?? []).flatMap((message) => {
1242
+ const invocationId = parseTurnReplyMessageId(message.inboundMessageId) === void 0 ? void 0 : parseAgentReplyMessageId(message.inboundMessageId);
1243
+ return invocationId ? [{
1244
+ invocationId,
1245
+ messageId: message.inboundMessageId
1246
+ }] : [];
1247
+ });
1248
+ if (replies.length === 0) continue;
1249
+ const senders = await getSqlExecutor().db().select({
1250
+ childConversationId: juniorAgentInvocations.childConversationId,
1251
+ invocationId: juniorAgentInvocations.invocationId
1252
+ }).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.invocationId, replies.map((reply) => reply.invocationId)));
1253
+ const stoppedSenders = new Set(senders.filter((sender) => stopped.has(sender.childConversationId)).map((sender) => sender.invocationId));
1254
+ const inboundMessageIds = replies.filter((reply) => stoppedSenders.has(reply.invocationId)).map((reply) => reply.messageId);
1255
+ if (inboundMessageIds.length > 0) await dropPendingMessages({
1256
+ conversationId,
1257
+ inboundMessageIds,
1258
+ state
1259
+ });
1260
+ }
1261
+ }
1262
+ /**
1263
+ * Drop the unread loop replies that a Conversation that a person stopped
1264
+ * left in its parent's mailbox, outside its tree. Call this after its stop
1265
+ * is stored: the parent mailbox lock then drops a later reply.
1266
+ */
1267
+ async function dropOwnUnreadLoopReplies(conversationId, state) {
1268
+ await dropUnreadLoopReplies((await getSqlExecutor().db().selectDistinct({ id: juniorAgentInvocations.parentConversationId }).from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, conversationId))).map((parent) => parent.id), [conversationId], state);
1269
+ }
1270
+ /**
1271
+ * A Thread can hold a person's Turn that waits for sign-in. The stop ends
1272
+ * that Turn here, because no worker holds it. Then a later sign-in callback
1273
+ * cannot resume a stopped Thread.
1274
+ */
1275
+ async function finishStoppedTree(tree, conversationIdsToStop, options) {
1276
+ for (const invocation of tree.stopped) await recordSubagentEnded(invocation);
1277
+ await markConversationsStopped(conversationIdsToStop, options);
1278
+ for (const conversationId of conversationIdsToStop) {
1279
+ await cancelSignInWait(conversationId);
1280
+ await stopConversationWork({
1281
+ conversationId,
1282
+ state: options.state
1283
+ });
1284
+ }
1285
+ }
1286
+ /**
1287
+ * List one child Conversation and every Conversation below it, child first.
1288
+ * It takes the create lock of each Conversation before it reads that
1289
+ * Conversation's children, so no child agent can start in the tree until the
1290
+ * caller's transaction ends.
1291
+ */
1292
+ async function lockAgentConversationTree(childConversationId) {
1293
+ const executor = getSqlExecutor();
1294
+ const conversationIds = [childConversationId];
1295
+ let parents = conversationIds;
1296
+ while (parents.length > 0) {
1297
+ for (const parent of parents) await executor.withLock(getChildAgentLockName(parent), async () => void 0);
1298
+ parents = (await executor.db().selectDistinct({ childConversationId: juniorAgentInvocations.childConversationId }).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.parentConversationId, parents))).map((row) => row.childConversationId).filter((id) => !conversationIds.includes(id));
1299
+ conversationIds.push(...parents);
1300
+ }
1301
+ return conversationIds;
1302
+ }
1303
+ /**
1304
+ * Keep a Conversation, the child agents that it spawned or gave new work to
1305
+ * after `taskedAfterMs`, and every Conversation below those child agents.
1306
+ */
1307
+ async function withChildAgentsTaskedAfter(conversationId, conversationIds, taskedAfterMs) {
1308
+ const links = await getSqlExecutor().db().selectDistinct({
1309
+ childConversationId: juniorAgentInvocations.childConversationId,
1310
+ parentConversationId: juniorAgentInvocations.parentConversationId
1311
+ }).from(juniorAgentInvocations).where(and(inArray(juniorAgentInvocations.parentConversationId, [...conversationIds]), or(ne(juniorAgentInvocations.parentConversationId, conversationId), gt(juniorAgentInvocations.createdAt, new Date(taskedAfterMs)))));
1312
+ const kept = [conversationId];
1313
+ for (let index = 0; index < kept.length; index += 1) for (const link of links) if (link.parentConversationId === kept[index] && !kept.includes(link.childConversationId)) kept.push(link.childConversationId);
1314
+ return kept;
1315
+ }
1316
+ /**
1317
+ * Stop the agent invocations of one direct child agent and of every child
1318
+ * agent below it. Returns undefined when the child does not belong to the
1319
+ * parent.
1320
+ */
1321
+ async function stopChildAgentInvocations(args) {
1322
+ if ((await getSqlExecutor().db().select({ invocationId: juniorAgentInvocations.invocationId }).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, args.parentConversationId), eq(juniorAgentInvocations.childConversationId, args.childConversationId))).limit(1)).length === 0) return;
1323
+ return await stopAgentInvocationTree(args.childConversationId, args.nowMs);
1324
+ }
1325
+ /**
1326
+ * Stop the agent invocations of one agent Conversation and of every child
1327
+ * agent below it. Open agent invocations become `stopped`. Results that would
1328
+ * still start or report work in the tree become `skipped`. With
1329
+ * `includeRoot: false`, the agent invocations of the Conversation itself stay
1330
+ * as they are, and only `pending` results sent to it become `skipped`. With
1331
+ * `taskedAfterMs`, only the direct child agents that got an agent invocation
1332
+ * after that time, and the Conversations below them, stop.
1333
+ */
1334
+ async function stopAgentInvocationTree(conversationId, nowMs = Date.now(), options = { includeRoot: true }) {
1335
+ return await getSqlExecutor().withLock(getChildAgentLockName(conversationId), () => stopLockedAgentInvocationTree(conversationId, nowMs, options));
1336
+ }
1337
+ async function stopLockedAgentInvocationTree(conversationId, nowMs, options) {
1338
+ const db = getSqlExecutor().db();
1339
+ const now = new Date(nowMs);
1340
+ const lockedIds = await lockAgentConversationTree(conversationId);
1341
+ const conversationIds = options.taskedAfterMs === void 0 ? lockedIds : await withChildAgentsTaskedAfter(conversationId, lockedIds, options.taskedAfterMs);
1342
+ const stoppedChildIds = options.includeRoot ? conversationIds : conversationIds.filter((id) => id !== conversationId);
1343
+ const stopped = await db.update(juniorAgentInvocations).set({
1344
+ errorMessage: "Stopped by the parent conversation",
1345
+ parentMailboxStatus: "skipped",
1346
+ result: null,
1347
+ status: "stopped",
1348
+ terminalAt: now,
1349
+ updatedAt: now
1350
+ }).where(and(inArray(juniorAgentInvocations.childConversationId, stoppedChildIds), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES))).returning();
1351
+ await db.update(juniorAgentInvocations).set({
1352
+ parentMailboxStatus: "skipped",
1353
+ updatedAt: now
1354
+ }).where(or(and(inArray(juniorAgentInvocations.parentConversationId, stoppedChildIds), inArray(juniorAgentInvocations.parentMailboxStatus, ["pending", "appended"])), and(eq(juniorAgentInvocations.parentConversationId, conversationId), eq(juniorAgentInvocations.parentMailboxStatus, "pending")), and(inArray(juniorAgentInvocations.childConversationId, stoppedChildIds), eq(juniorAgentInvocations.parentMailboxStatus, "replaced"))));
1355
+ return {
1356
+ conversationIds,
1357
+ stopped: stopped.map(invocationFromRow).filter(isTerminalAgentInvocation)
1358
+ };
1359
+ }
1360
+ // src/chat/agent-invocations/work.ts
1361
+ const agentInvocationMailboxMetadataSchema = z.object({
1362
+ agentInvocationId: z.string().min(1),
1363
+ kind: z.literal("agent_invocation")
1364
+ }).strict();
1365
+ /** Map a durable invocation's model settings and depth to the child Run policy. */
1366
+ function agentInvocationRunPolicy(invocation, canSpawn) {
1367
+ return {
1368
+ disabledFeatures: canSpawn ? ["interactive-auth"] : ["interactive-auth", "subagents"],
1369
+ ...invocation.reasoningLevel ? { reasoning: invocation.reasoningLevel } : void 0
1370
+ };
1371
+ }
1372
+ /** Build destinationless mailbox work that references one durable invocation. */
1373
+ function buildAgentInvocationInboundMessage(invocation, nowMs = Date.now()) {
1374
+ return {
1375
+ conversationId: invocation.childConversationId,
1376
+ createdAtMs: invocation.createdAtMs,
1377
+ delivery: "defer",
1378
+ inboundMessageId: getAgentInvocationMessageId(invocation.invocationId),
1379
+ input: {
1380
+ authorId: invocation.invocationId,
1381
+ authorIdentityId: SYSTEM_IDENTITY_ID,
1382
+ text: "[agent invocation]",
1383
+ metadata: {
1384
+ agentInvocationId: invocation.invocationId,
1385
+ kind: "agent_invocation"
1386
+ }
1387
+ },
1388
+ receivedAtMs: nowMs,
1389
+ source: "internal"
1390
+ };
1391
+ }
1392
+ /** Append one invocation to its child mailbox and send the normal queue wake. */
1393
+ async function enqueueAgentInvocation(invocation, options) {
1394
+ if (invocation.mailboxStatus === "appended" || isTerminalAgentInvocation(invocation)) return;
1395
+ await recordSubagentStarted(invocation, options.eventMeta);
1396
+ if (invocation.parentToolCallId !== void 0) await resumeStoppedConversationTree(invocation.childConversationId, invocation.createdAtMs);
1397
+ const nowMs = options.nowMs ?? Date.now();
1398
+ await appendAndEnqueueInboundMessage({
1399
+ message: buildAgentInvocationInboundMessage(invocation, nowMs),
1400
+ conversationStore: options.conversationStore,
1401
+ nowMs,
1402
+ queue: options.queue,
1403
+ state: options.state
1404
+ });
1405
+ await markAgentInvocationMailboxAppended(invocation.invocationId, nowMs);
1406
+ }
1407
+ /** Create or replay an invocation, then durably schedule its child work. */
1408
+ async function createAndEnqueueAgentInvocation(input, options) {
1409
+ const invocation = await createAgentInvocation(input, options.nowMs);
1410
+ await enqueueAgentInvocation(invocation, options);
1411
+ return await getAgentInvocation(invocation.invocationId) ?? invocation;
1412
+ }
1413
+ /** Require one invocation metadata reference for one leased mailbox attempt. */
1414
+ /** Return whether one mailbox input is a parent task or message for an agent invocation. */
1415
+ function isAgentInvocationInput(message) {
1416
+ return agentInvocationMailboxMetadataSchema.safeParse(message.input.metadata).success;
1417
+ }
1418
+ function invocationIdFromMessages(messages) {
1419
+ if (messages.length === 0) return;
1420
+ const parsed = messages.map((message) => agentInvocationMailboxMetadataSchema.safeParse(message.input.metadata));
1421
+ if (parsed.every((result) => !result.success)) return;
1422
+ if (parsed.some((result) => !result.success)) throw new Error("Conversation mailbox mixes agent invocation and other input");
1423
+ const invocationIds = new Set(parsed.map((result) => {
1424
+ if (!result.success) throw new Error("Agent invocation mailbox metadata failed validation");
1425
+ return result.data.agentInvocationId;
1426
+ }));
1427
+ if (invocationIds.size !== 1) throw new Error("Conversation mailbox contains multiple agent invocations in one attempt");
1428
+ return invocationIds.values().next().value;
1429
+ }
1430
+ /**
1431
+ * Text that the child agent model reads for one agent invocation. A parent
1432
+ * agent task or message becomes one `<parent-agent-task>`. Results of the
1433
+ * child's own child agents already have their own tag.
1434
+ */
1435
+ function agentInvocationInputText(invocation) {
1436
+ if (!invocation.parentToolCallId) return invocation.input;
1437
+ const instructions = [invocation.fork ? FORK_INSTRUCTIONS : void 0, agentTypeInstructions(invocation.agentType)].filter((text) => text !== void 0);
1438
+ return renderTag("parent-agent-task", {}, [...instructions.flatMap((text) => [escapeClosingTags(text), ""]), escapeClosingTags(invocation.input)]);
1439
+ }
1440
+ /**
1441
+ * A parent agent task or message is the child's instruction. Another input,
1442
+ * such as a result of the child's own child agent or an Event, is context.
1443
+ */
1444
+ function agentInvocationProvenance(invocation) {
1445
+ return invocation.parentToolCallId ? agentInstructionProvenance : contextProvenance;
1446
+ }
1447
+ /**
1448
+ * Resolve the agent invocation that owns this work: the one named by its
1449
+ * mailbox input, or for an empty wake the open one. Other work has none.
1450
+ */
1451
+ async function resolveAgentInvocationId(context) {
1452
+ const mailboxInvocationId = invocationIdFromMessages(context.attempt.messages);
1453
+ if (mailboxInvocationId || context.attempt.messages.length > 0) return mailboxInvocationId;
1454
+ const active = await getActiveAgentInvocationForConversation(context.conversationId);
1455
+ if (active) return active.invocationId;
1456
+ const latest = await getLatestAgentInvocationForConversation(context.conversationId);
1457
+ const turn = latest ? await getTurnRecord(context.conversationId, getAgentInvocationTurnId(latest.invocationId)) : void 0;
1458
+ return turn?.state === "paused" || turn?.state === "running" ? latest?.invocationId : void 0;
1459
+ }
1460
+ /**
1461
+ * Give queued parent messages to the running agent invocation of a child as
1462
+ * steering messages. A message joins only with the Actor and credentials of
1463
+ * the running Turn. The first message that does not match stops the scan, so
1464
+ * it and every later message wait for the current work. Each message that
1465
+ * joins ends as `steered`, and the running agent invocation reports for it.
1466
+ */
1467
+ function createAgentMessageSteeringDrain(context, running) {
1468
+ const turnId = getAgentInvocationTurnId(running.invocationId);
1469
+ return async (accept) => {
1470
+ const accepted = [];
1471
+ await context.attempt.drain(async (pending) => {
1472
+ const readIds = [];
1473
+ const joining = [];
1474
+ for (const message of pending) {
1475
+ const metadata = agentInvocationMailboxMetadataSchema.safeParse(message.input.metadata);
1476
+ if (!metadata.success) continue;
1477
+ const candidate = await getAgentInvocation(metadata.data.agentInvocationId);
1478
+ if (!candidate?.parentToolCallId || candidate.invocationId === running.invocationId) continue;
1479
+ if (isTerminalAgentInvocation(candidate)) {
1480
+ if (candidate.parentMailboxStatus === "steered") readIds.push(message.inboundMessageId);
1481
+ continue;
1482
+ }
1483
+ if (!sameActorIdentity(candidate.actor, running.actor) || !isDeepStrictEqual(candidate.credentialContext, running.credentialContext)) break;
1484
+ joining.push(candidate);
1485
+ readIds.push(message.inboundMessageId);
1486
+ }
1487
+ if (joining.length === 0) return readIds;
1488
+ const saved = (await getTurnRecord(running.childConversationId, turnId))?.piMessages ?? [];
1489
+ const messages = withoutSavedSteeringMessages(saved, joining.map((candidate) => ({
1490
+ kind: "runtime",
1491
+ provenance: agentInvocationProvenance(candidate),
1492
+ text: agentInvocationInputText(candidate),
1493
+ timestampMs: candidate.createdAtMs
1494
+ })), buildSteeringPiMessage);
1495
+ if (messages.length > 0) {
1496
+ await accept(messages);
1497
+ accepted.push(...messages);
1498
+ }
1499
+ for (const candidate of joining) {
1500
+ const terminal = await markAgentInvocationSteered(candidate.invocationId);
1501
+ if (terminal && isTerminalAgentInvocation(terminal)) await recordSubagentEnded(terminal);
1502
+ }
1503
+ return readIds;
1504
+ }, { deferred: true });
1505
+ return accepted;
1506
+ };
1507
+ }
1508
+ /** Project the terminal invocation into the idempotent turn lifecycle. */
1509
+ async function persistTerminalLifecycle(terminal) {
1510
+ const turnId = getAgentInvocationTurnId(terminal.invocationId);
1511
+ if (terminal.status !== "completed") await abandonTurnRecord({
1512
+ conversationId: terminal.childConversationId,
1513
+ errorMessage: terminal.status === "stopped" ? "Turn cancelled" : terminal.errorMessage,
1514
+ turnId
1515
+ });
1516
+ await finishTurn(terminal.childConversationId, turnId, agentInvocationTurnEnd(terminal));
1517
+ }
1518
+ /**
1519
+ * Stop an invocation whose worker died, or project its terminal turn result.
1520
+ * With `resumeLostWorker`, a Turn whose worker died resumes once from its last
1521
+ * save, as a root Turn does. A second loss stops it.
1522
+ */
1523
+ async function projectTerminalTurn(invocation, options = {}) {
1524
+ const { resumeLostWorker, ...completeOptions } = options;
1525
+ let turn = await getTurnRecord(invocation.childConversationId, getAgentInvocationTurnId(invocation.invocationId));
1526
+ if (!turn) return;
1527
+ if (resumeLostWorker && turn.state === "running" && await pauseLostWorkerTurn(turn)) return;
1528
+ if (turn.state === "running" || resumeLostWorker && turn.state === "paused" && lostWorkerBeforeFirstSave(turn)) {
1529
+ turn = await failTurnRecord({
1530
+ conversationId: turn.conversationId,
1531
+ expectedVersion: turn.version,
1532
+ turnId: turn.turnId,
1533
+ errorMessage: "Agent invocation lost its worker before it could pause"
1534
+ });
1535
+ if (!turn) return;
1536
+ }
1537
+ const end = savedTurnEnd(turn);
1538
+ if (!end) return;
1539
+ if (turn.state === "paused") await abandonTurnRecord({
1540
+ conversationId: turn.conversationId,
1541
+ turnId: turn.turnId
1542
+ });
1543
+ return await completeAgentInvocation({
1544
+ ...completeOptions,
1545
+ invocationId: invocation.invocationId,
1546
+ ...end
1547
+ });
1548
+ }
1549
+ /**
1550
+ * End every running or paused agent invocation of a child before other work
1551
+ * opens a Turn there, so the child has one open Turn. A saved finished Turn
1552
+ * gives its result. Every other one fails with `errorMessage`, because the
1553
+ * newer work does not continue its task. Each reports on its own.
1554
+ */
1555
+ async function endActiveAgentInvocations(conversationId, options) {
1556
+ for (const active of await listAgentInvocationsForConversation(conversationId, ACTIVE_AGENT_INVOCATION_STATUSES)) {
1557
+ if (active.invocationId === options.exceptInvocationId) continue;
1558
+ const terminal = await projectTerminalTurn(active, { reportNow: true }) ?? await completeAgentInvocation({
1559
+ invocationId: active.invocationId,
1560
+ errorMessage: options.errorMessage,
1561
+ reportNow: true,
1562
+ status: "failed"
1563
+ });
1564
+ if (terminal && isTerminalAgentInvocation(terminal)) {
1565
+ await persistTerminalLifecycle(terminal);
1566
+ await recordSubagentEnded(terminal);
1567
+ await options.enqueueResult?.(terminal);
1568
+ }
1569
+ }
1570
+ }
1571
+ /**
1572
+ * End every agent invocation of a child whose last attempt lost its worker and
1573
+ * whose input reached the child's mailbox. The worker ran no failure path, and
1574
+ * the stop drops the mailbox, so none of them can run. The heartbeat sends
1575
+ * each result.
1576
+ */
1577
+ async function endAgentInvocationsOfStoppedWork(conversationId, inboundMessageIds) {
1578
+ for (const invocation of await listAgentInvocationsForConversation(conversationId, NON_TERMINAL_AGENT_INVOCATION_STATUSES)) {
1579
+ if (!inboundMessageIds.includes(getAgentInvocationMessageId(invocation.invocationId))) continue;
1580
+ const terminal = await projectTerminalTurn(invocation, { reportNow: true }) ?? await completeAgentInvocation({
1581
+ invocationId: invocation.invocationId,
1582
+ errorMessage: "This task stopped because its worker failed repeatedly.",
1583
+ reportNow: true,
1584
+ status: "failed"
1585
+ });
1586
+ if (terminal && isTerminalAgentInvocation(terminal)) await persistTerminalLifecycle(terminal);
1587
+ }
1588
+ }
1589
+ /** Classify authorization failures that terminally block background work. */
1590
+ function blockingInvocationError(error) {
1591
+ const cause = getConversationTurnBoundaryError(error)?.cause ?? error;
1592
+ return cause instanceof AuthorizationFlowDisabledError || cause instanceof PluginCredentialFailureError ? cause : void 0;
1593
+ }
1594
+ function isInvocationInputCommitLost(error) {
1595
+ const cause = getConversationTurnBoundaryError(error)?.cause ?? error;
1596
+ return isTurnInputCommitLostError(cause);
1597
+ }
1598
+ /**
1599
+ * Save one completed agent result on its child agent invocation. A `reply`
1600
+ * goes to the parent before the Turn is saved, so a lost worker cannot save
1601
+ * the Turn and drop its reply.
1602
+ */
1603
+ async function saveAgentInvocationResult(args) {
1604
+ const failed = args.result.diagnostics.outcome !== "success";
1605
+ if (args.result.reply) await args.sendReply?.(args.invocation, args.result.reply);
1606
+ await persistThreadStateById(args.invocation.childConversationId, { sandboxRef: args.result.sandboxRef ?? args.sandboxRef });
1607
+ if (args.result.piMessages?.length) await saveTurnCheckpoint({
1608
+ mode: "completed",
1609
+ conversationId: args.invocation.childConversationId,
1610
+ turnId: args.turnId,
1611
+ durationMs: args.result.diagnostics.durationMs,
1612
+ usage: args.result.diagnostics.usage,
1613
+ destination: args.invocation.destination,
1614
+ ...failed ? { errorMessage: args.result.diagnostics.errorMessage ?? "Agent invocation failed" } : void 0,
1615
+ messages: args.result.piMessages,
1616
+ actor: args.invocation.actor,
1617
+ source: args.invocation.source,
1618
+ surface: "internal"
1619
+ });
1620
+ if (args.invocation.parentToolCallId) await resetAutomatedTurnLimit({ conversationId: args.invocation.childConversationId });
1621
+ else if (args.invocation.source.kind !== "agent_invocation") {
1622
+ const maxTurns = botConfig.maxConsecutiveAutomatedTurns;
1623
+ await maybePostAutomatedTurnLimitNotice({
1624
+ conversationId: args.invocation.childConversationId,
1625
+ maxTurns,
1626
+ update: await recordFinishedTurnForAutomatedLimit({
1627
+ conversationId: args.invocation.childConversationId,
1628
+ maxTurns,
1629
+ source: args.invocation.source
1630
+ })
1631
+ });
1632
+ }
1633
+ const terminal = await completeAgentInvocation({
1634
+ invocationId: args.invocation.invocationId,
1635
+ ...failed ? {
1636
+ errorMessage: args.result.diagnostics.errorMessage ?? "Agent invocation failed",
1637
+ status: "failed"
1638
+ } : args.result.blocked ? {
1639
+ errorMessage: args.result.blocked.missing,
1640
+ status: "blocked"
1641
+ } : {
1642
+ result: args.result.reply?.text ?? "",
1643
+ status: "completed"
1644
+ }
1645
+ });
1646
+ if (!terminal || !isTerminalAgentInvocation(terminal)) throw new Error(`Agent invocation did not finish for ${args.invocation.invocationId}`);
1647
+ return agentInvocationTurnEnd(terminal);
1648
+ }
1649
+ /**
1650
+ * Build the invocation consumer that advances work through the shared runner.
1651
+ * `enqueueResult` sends each terminal result to the parent mailbox. Omit it
1652
+ * only where the parent has no mailbox, such as the local CLI.
1653
+ * `maxAgentDepth` is the number of child agent levels that can start their
1654
+ * own child agents. The default, 0, lets only the root start child agents.
1655
+ */
1656
+ function createAgentInvocationWorker(agentRunner, options = {}) {
1657
+ const canSpawn = (options.maxAgentDepth ?? 0) > 0;
1658
+ return async (context, invocationId) => {
1659
+ let invocation = await getAgentInvocation(invocationId);
1660
+ if (!invocation) throw new Error(`Agent invocation is missing for ${invocationId}`);
1661
+ const report = async (terminal) => {
1662
+ await recordSubagentEnded(terminal);
1663
+ await options.enqueueResult?.(terminal);
1664
+ };
1665
+ const finish = async (terminal) => {
1666
+ if (!terminal || !isTerminalAgentInvocation(terminal)) return;
1667
+ if (terminal.parentMailboxStatus !== "steered") await persistTerminalLifecycle(terminal);
1668
+ await report(terminal);
1669
+ };
1670
+ let acknowledged = context.attempt.messages.length === 0;
1671
+ const acknowledge = async () => {
1672
+ if (acknowledged) return;
1673
+ try {
1674
+ await context.attempt.ack();
1675
+ } catch {
1676
+ throw new TurnInputCommitLostError(`Conversation work lease lost before invocation inbox ack for ${context.conversationId}`);
1677
+ }
1678
+ acknowledged = true;
1679
+ };
1680
+ const stopSignal = context.stopSignal?.();
1681
+ const finishStopped = async () => {
1682
+ await finish(await completeAgentInvocation({
1683
+ invocationId,
1684
+ errorMessage: "Agent invocation was stopped",
1685
+ status: "stopped"
1686
+ }));
1687
+ await stopChildAgentsOf(context.conversationId);
1688
+ await acknowledge();
1689
+ return { status: "completed" };
1690
+ };
1691
+ const turnId = getAgentInvocationTurnId(invocation.invocationId);
1692
+ const lifecycle = new ConversationTurnLifecycleService(getConversationEventStore());
1693
+ let sandboxRef;
1694
+ let history;
1695
+ let location;
1696
+ try {
1697
+ if (invocation.childConversationId !== context.conversationId) throw new Error(`Agent invocation ${invocationId} belongs to ${invocation.childConversationId}, not ${context.conversationId}`);
1698
+ if (context.destination) throw new Error(`Agent invocation conversation ${context.conversationId} must not own a provider destination`);
1699
+ if (isTerminalAgentInvocation(invocation)) {
1700
+ await finish(invocation);
1701
+ await acknowledge();
1702
+ return { status: "completed" };
1703
+ }
1704
+ const projected = await projectTerminalTurn(invocation, { resumeLostWorker: true });
1705
+ if (projected && isTerminalAgentInvocation(projected)) {
1706
+ await finish(projected);
1707
+ await acknowledge();
1708
+ return { status: "completed" };
1709
+ }
1710
+ await endActiveAgentInvocations(invocation.childConversationId, {
1711
+ enqueueResult: options.enqueueResult,
1712
+ errorMessage: "This task was not resumed. Newer work for this child agent started, so this task ended without a result.",
1713
+ exceptInvocationId: invocation.invocationId
1714
+ });
1715
+ await supersedeOpenMailboxTurn(invocation.childConversationId);
1716
+ invocation = await markAgentInvocationRunning(invocation.invocationId) ?? invocation;
1717
+ if (isTerminalAgentInvocation(invocation)) {
1718
+ await finish(invocation);
1719
+ await acknowledge();
1720
+ return { status: "completed" };
1721
+ }
1722
+ await lifecycle.start({
1723
+ conversationId: invocation.childConversationId,
1724
+ createdAtMs: invocation.createdAtMs,
1725
+ inputMessageIds: [getAgentInvocationMessageId(invocation.invocationId)],
1726
+ surface: "internal",
1727
+ turnId
1728
+ });
1729
+ const [persisted, projection, child] = await Promise.all([
1730
+ getPersistedThreadState(invocation.childConversationId),
1731
+ openConversationProjection({ conversationId: invocation.childConversationId }),
1732
+ getConversationStore().get({ conversationId: invocation.childConversationId })
1733
+ ]);
1734
+ sandboxRef = getPersistedSandboxState(persisted);
1735
+ history = invocation.fork && projection.messages.length === 0 ? await loadForkHistory(invocation) : projection.messages;
1736
+ location = child?.location;
1737
+ } catch (error) {
1738
+ if (isInvocationInputCommitLost(error)) return { status: "lost_lease" };
1739
+ if (!context.attempt.isFinalAttempt) throw error;
1740
+ await finish(await completeAgentInvocation({
1741
+ invocationId: invocation.invocationId,
1742
+ errorMessage: error instanceof Error ? error.message : "Agent invocation failed",
1743
+ status: "failed"
1744
+ }));
1745
+ await acknowledge();
1746
+ return { status: "completed" };
1747
+ }
1748
+ let outcome;
1749
+ try {
1750
+ outcome = await executeTurn(agentRunner, {
1751
+ conversationId: invocation.childConversationId,
1752
+ agentInvocationId: invocation.invocationId,
1753
+ parentConversationId: invocation.parentConversationId,
1754
+ turnId,
1755
+ runId: invocation.invocationId,
1756
+ instruction: {
1757
+ ...instructionForInputs([{
1758
+ kind: "runtime",
1759
+ text: agentInvocationInputText(invocation)
1760
+ }]),
1761
+ provenance: agentInvocationProvenance(invocation)
1762
+ },
1763
+ history,
1764
+ actor: invocation.actor,
1765
+ credentialContext: invocation.credentialContext,
1766
+ destination: invocation.destination,
1767
+ source: invocation.source,
1768
+ ...location ? { location } : void 0,
1769
+ surface: "internal",
1770
+ deadlineAtMs: getTurnRequestDeadline()?.deadlineAtMs,
1771
+ ...stopSignal ? { signal: stopSignal } : void 0,
1772
+ ...agentInvocationRunPolicy(invocation, canSpawn),
1773
+ state: { sandboxRef },
1774
+ durability: {
1775
+ drainSteeringMessages: createAgentMessageSteeringDrain(context, invocation),
1776
+ onInputCommitted: acknowledge,
1777
+ shouldYield: context.shouldYield,
1778
+ checkIn: context.checkIn,
1779
+ checkStop: context.checkStop,
1780
+ onSandboxRefChanged: async (nextSandboxRef) => {
1781
+ sandboxRef = nextSandboxRef;
1782
+ await persistThreadStateById(invocation.childConversationId, { sandboxRef });
1783
+ }
1784
+ }
1785
+ }, async (result) => {
1786
+ if (result.diagnostics.outcome !== "success") stopSignal?.throwIfAborted();
1787
+ return await saveAgentInvocationResult({
1788
+ invocation,
1789
+ result,
1790
+ sandboxRef,
1791
+ sendReply: options.sendReply,
1792
+ turnId
1793
+ });
1794
+ });
1795
+ } catch (error) {
1796
+ const runError = error instanceof AgentRunError ? error.cause : error;
1797
+ if (isInvocationInputCommitLost(runError)) return { status: "lost_lease" };
1798
+ if (stopSignal?.aborted) return await finishStopped();
1799
+ const blocking = blockingInvocationError(runError);
1800
+ if (blocking) {
1801
+ await finish(await completeAgentInvocation({
1802
+ invocationId: invocation.invocationId,
1803
+ errorMessage: blocking.message,
1804
+ status: "blocked"
1805
+ }));
1806
+ await acknowledge();
1807
+ return { status: "completed" };
1808
+ }
1809
+ if (!context.attempt.isFinalAttempt && !isTurnExecutionLimitExceededError(runError)) throw runError;
1810
+ await finish(await completeAgentInvocation({
1811
+ invocationId: invocation.invocationId,
1812
+ errorMessage: runError instanceof Error ? runError.message : "Agent invocation failed",
1813
+ status: "failed"
1814
+ }));
1815
+ await acknowledge();
1816
+ return { status: "completed" };
1817
+ }
1818
+ if (outcome.status !== "completed" && stopSignal?.aborted) return await finishStopped();
1819
+ if (outcome.status === "suspended") {
1820
+ await markAgentInvocationPaused(invocation.invocationId);
1821
+ return { status: "yielded" };
1822
+ }
1823
+ if (outcome.status === "awaiting_auth") {
1824
+ await finish(await completeAgentInvocation({
1825
+ invocationId: invocation.invocationId,
1826
+ errorMessage: `Agent invocation requires ${outcome.providerDisplayName} authorization`,
1827
+ status: "blocked"
1828
+ }));
1829
+ await acknowledge();
1830
+ return { status: "completed" };
1831
+ }
1832
+ let terminal = await getAgentInvocation(invocation.invocationId);
1833
+ if (stopSignal?.aborted) {
1834
+ if (terminal && isTerminalAgentInvocation(terminal) && terminal.parentMailboxStatus === "replaced") terminal = await reportReplacedAgentInvocation(terminal.invocationId);
1835
+ await stopChildAgentsOf(context.conversationId);
1836
+ }
1837
+ if (terminal && isTerminalAgentInvocation(terminal)) await report(terminal);
1838
+ await acknowledge();
1839
+ return { status: "completed" };
1840
+ };
1841
+ }
1842
+ // src/chat/agent-invocations/child-input.ts
1843
+ /**
1844
+ * Read the agent invocation that one result or message Event refers to: the
1845
+ * finished child work for a result, or the open sender work for a message.
1846
+ */
1847
+ function childAgentInput(message) {
1848
+ const metadata = message.input.metadata;
1849
+ if (!isEventMailboxMetadata(metadata) || metadata.event.namespace !== "junior") return;
1850
+ if (metadata.event.eventType === "agent.message") return {
1851
+ invocationId: metadata.event.identifier,
1852
+ kind: "message"
1853
+ };
1854
+ if (metadata.event.eventType === "agent.reply") return {
1855
+ invocationId: metadata.event.identifier,
1856
+ kind: "reply"
1857
+ };
1858
+ return isAgentInvocationResultEventType(metadata.event.eventType) ? {
1859
+ invocationId: metadata.event.identifier,
1860
+ kind: "result"
1861
+ } : void 0;
1862
+ }
1863
+ /**
1864
+ * Route one input to a Conversation. Routing, the stop skips, and the child
1865
+ * agent status all read this, so they agree on which input starts work.
1866
+ *
1867
+ * A parent task or message goes to its agent invocation. `latest` is the
1868
+ * Conversation's newest agent invocation; a root has none. With an open one, a Watch Event and input from a child agent go to an agent
1869
+ * invocation, and so do a result, and input to a child that waits for its own
1870
+ * child agents (`replaced`). A stopped child drops input from its own child
1871
+ * agents, also input sent before the stop. A session stop at `stoppedAtMs`
1872
+ * skips Events as `skipInputAfterConversationStop` does.
1873
+ *
1874
+ * TODO(dcramer): Drop the agent invocation route with the legacy child worker
1875
+ * (#3060 step 7).
1876
+ */
1877
+ async function routeChildInput(message, latest, stoppedAtMs) {
1878
+ if (isPersonInput(message.source)) return "Conversation loop";
1879
+ if (isAgentInvocationInput(message)) return "agent invocation";
1880
+ const open = latest !== void 0 && !isTerminalAgentInvocation(latest);
1881
+ const input = childAgentInput(message);
1882
+ if (!input) {
1883
+ if (open && isEventMailboxMetadata(message.input.metadata)) return "agent invocation";
1884
+ return isSkippedAfterConversationStop(message, stoppedAtMs) ? "dropped" : "Conversation loop";
1885
+ }
1886
+ if (latest && isStoppedAgentInvocation(latest)) return "dropped";
1887
+ if (await isSkippedAgentResult(input, await getChildAgentInputInvocation(message, input), message)) return "dropped";
1888
+ if (latest && (open || input.kind === "result" || latest.parentMailboxStatus === "replaced")) return "agent invocation";
1889
+ return isSkippedAfterConversationStop(message, stoppedAtMs) ? "dropped" : "Conversation loop";
1890
+ }
1891
+ /**
1892
+ * Return whether a stop skipped this result or reply, so it starts no work.
1893
+ * A message that a child sent before its stop is still delivered. A reply
1894
+ * that an agent invocation sent names its own work, so it is dropped with
1895
+ * that work. A reply from a Turn on the Conversation loop names no work of
1896
+ * its own: the stop drops it from the parent's mailbox. While the sending
1897
+ * child is stopped, a reply that it sent after the stop is also dropped.
1898
+ */
1899
+ async function isSkippedAgentResult(input, invocation, message) {
1900
+ if (input.kind === "message") return false;
1901
+ const skipped = isTerminalAgentInvocation(invocation) && invocation.parentMailboxStatus === "skipped";
1902
+ if (input.kind === "result") return skipped;
1903
+ if (skipped && parseTurnReplyMessageId(message.inboundMessageId) === void 0) return true;
1904
+ const senderStoppedAtMs = await getConversationStoppedAtMs(invocation.childConversationId);
1905
+ return senderStoppedAtMs !== void 0 && message.createdAtMs >= senderStoppedAtMs;
1906
+ }
1907
+ /**
1908
+ * Read the agent invocation of one result or message and check that it
1909
+ * belongs to a child of the Conversation that received it.
1910
+ */
1911
+ async function getChildAgentInputInvocation(message, input) {
1912
+ const invocation = await getAgentInvocation(input.invocationId);
1913
+ if (!invocation || input.kind === "result" && !isTerminalAgentInvocation(invocation) || invocation.parentConversationId !== message.conversationId) throw new Error(`Agent invocation ${input.kind} ${input.invocationId} does not belong to ${message.conversationId}`);
1914
+ return invocation;
1915
+ }
1916
+ // src/chat/agent-invocations/list.ts
1917
+ function isChildAgentResult(status) {
1918
+ return CHILD_AGENT_RESULTS.includes(status);
1919
+ }
1920
+ /** Bound the agent invocations that one child agent listing reads. */
1921
+ const CHILD_AGENT_LIST_INVOCATION_LIMIT = 200;
1922
+ /** Return whether a child's session stopped after its latest agent invocation. */
1923
+ function isChildAgentSessionStopped(latest, stoppedAtMs) {
1924
+ return stoppedAtMs !== void 0 && stoppedAtMs >= latest.createdAtMs;
1925
+ }
1926
+ /** Return the child state that one child's agent invocations show. */
1927
+ function childAgentFromInvocations(invocations, resultInvocationIds, facts) {
1928
+ const { stoppedAtMs } = facts;
1929
+ const latest = invocations[0];
1930
+ let current = invocations.find((invocation) => !isTerminalAgentInvocation(invocation) || invocation.parentMailboxStatus !== "steered") ?? latest;
1931
+ for (const invocation of invocations) if (!isTerminalAgentInvocation(invocation)) current = invocation;
1932
+ const tasks = invocations.filter((invocation) => invocation.source.kind === "agent_invocation" && !resultInvocationIds.has(invocation.invocationId));
1933
+ const task = tasks.find((invocation) => invocation.parentToolCallId) ?? tasks[0] ?? invocations[invocations.length - 1];
1934
+ const terminal = isTerminalAgentInvocation(current) ? current : void 0;
1935
+ const lastResult = invocations.filter(isTerminalAgentInvocation).filter((invocation) => invocation.parentMailboxStatus !== "replaced" && invocation.parentMailboxStatus !== "skipped" && invocation.parentMailboxStatus !== "steered").map((invocation) => invocation.status).find(isChildAgentResult);
1936
+ return {
1937
+ ...latest.agentName ? { agentName: latest.agentName } : void 0,
1938
+ ...facts.archivedAtMs !== void 0 ? { archivedAtMs: facts.archivedAtMs } : void 0,
1939
+ childConversationId: latest.childConversationId,
1940
+ ...terminal && terminal.status !== "completed" ? { errorMessage: terminal.errorMessage } : void 0,
1941
+ kind: facts.kind,
1942
+ ...lastResult ? { lastResult } : void 0,
1943
+ status: isChildAgentSessionStopped(latest, stoppedAtMs) ? "stopped" : terminal && facts.onConversationLoop ? "running" : terminal?.parentMailboxStatus === "replaced" ? "pending" : terminal?.parentMailboxStatus === "skipped" ? "stopped" : current.status,
1944
+ task: task.input,
1945
+ ...task.title ? { title: task.title } : void 0,
1946
+ updatedAtMs: Math.max(...invocations.map((invocation) => invocation.updatedAtMs))
1947
+ };
1948
+ }
1949
+ /**
1950
+ * List the direct child agents of one parent Conversation, with the newest
1951
+ * activity first. The state comes from SQL agent invocation records, not from
1952
+ * model output.
1953
+ */
1954
+ async function listChildAgents(parentConversationId) {
1955
+ const db = getSqlExecutor().db();
1956
+ const rows = await db.select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.parentConversationId, parentConversationId)).orderBy(desc(juniorAgentInvocations.createdAt)).limit(CHILD_AGENT_LIST_INVOCATION_LIMIT);
1957
+ if (rows.length === 0) return [];
1958
+ const byChild = /* @__PURE__ */ new Map();
1959
+ for (const invocation of rows.map(invocationFromRow)) {
1960
+ const invocations = byChild.get(invocation.childConversationId) ?? [];
1961
+ invocations.push(invocation);
1962
+ byChild.set(invocation.childConversationId, invocations);
1963
+ }
1964
+ const grandchildren = await db.select({ invocationId: juniorAgentInvocations.invocationId }).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.parentConversationId, [...byChild.keys()]));
1965
+ const resultInvocationIds = new Set(grandchildren.map((row) => getAgentInvocationIdForResult(row.invocationId)));
1966
+ const conversations = await db.select({
1967
+ archivedAt: juniorConversations.archivedAt,
1968
+ conversationId: juniorConversations.conversationId,
1969
+ executionStatus: juniorConversations.executionStatus,
1970
+ kind: juniorConversations.kind,
1971
+ parentConversationId: juniorConversations.parentConversationId,
1972
+ stoppedAt: juniorConversations.stoppedAt
1973
+ }).from(juniorConversations).where(inArray(juniorConversations.conversationId, [...byChild.keys()]));
1974
+ const onConversationLoop = new Set((await Promise.all(conversations.filter((row) => row.executionStatus === "pending" || row.executionStatus === "running" || row.executionStatus === "paused").map(async (row) => await runsOnConversationLoop(row.conversationId, conversationKindFromRow(row), byChild.get(row.conversationId)[0], row.stoppedAt?.getTime()) ? row.conversationId : void 0))).filter((id) => id !== void 0));
1975
+ const factsByChild = new Map(conversations.map((row) => [row.conversationId, {
1976
+ ...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
1977
+ kind: conversationKindFromRow(row) === "thread" ? "thread" : "task",
1978
+ ...row.stoppedAt ? { stoppedAtMs: row.stoppedAt.getTime() } : void 0,
1979
+ onConversationLoop: onConversationLoop.has(row.conversationId)
1980
+ }]));
1981
+ return [...byChild.entries()].map(([childConversationId, invocations]) => childAgentFromInvocations(invocations, resultInvocationIds, factsByChild.get(childConversationId) ?? { kind: "task" })).sort((left, right) => right.updatedAtMs - left.updatedAtMs);
1982
+ }
1983
+ function answersParent(kind, source) {
1984
+ const personInput = isPersonInput(source);
1985
+ return !personInput && turnBehavior({
1986
+ kind,
1987
+ personInput
1988
+ }).gated;
1989
+ }
1990
+ /**
1991
+ * Return whether a child whose `latest` agent invocation ended has work on
1992
+ * the Conversation loop that will answer its parent: input that waits in the
1993
+ * mailbox until its Turn commits it, such as a Watch Event in its debounce
1994
+ * window, or an open mailbox Turn that answers.
1995
+ */
1996
+ async function runsOnConversationLoop(conversationId, kind, latest, stoppedAtMs) {
1997
+ const pending = (await getConversationWorkState({ conversationId }))?.execution.pendingMessages ?? [];
1998
+ for (const message of pending) if (answersParent(kind, message.source) && await routeChildInput(message, latest, stoppedAtMs) === "Conversation loop") return true;
1999
+ return (await listActiveMailboxTurns(conversationId)).some((turn) => answersParent(kind, turn.source?.kind));
2000
+ }
2001
+ /**
2002
+ * List the ids of a child's open Turns on the Conversation loop. A Turn keeps
2003
+ * its input in the mailbox until it commits it, so before its first
2004
+ * checkpoint its id comes from its first input. Attempt selection can take
2005
+ * any pending input first, so each one gives a candidate id.
2006
+ */
2007
+ async function listOpenLoopTurnIds(conversationId) {
2008
+ const [turns, work] = await Promise.all([listActiveMailboxTurns(conversationId), getConversationWorkState({ conversationId })]);
2009
+ return [...turns.map((turn) => turn.turnId), ...(work?.execution.pendingMessages ?? []).map((message) => buildDeterministicTurnId(message.inboundMessageId))];
2010
+ }
2011
+ async function listAnsweredLoopChildren(children, parentInboundMessageIds) {
2012
+ const replies = parentInboundMessageIds.flatMap((messageId) => {
2013
+ const invocationId = parseAgentReplyMessageId(messageId);
2014
+ return invocationId ? [{
2015
+ invocationId,
2016
+ messageId
2017
+ }] : [];
2018
+ });
2019
+ if (children.length === 0 || replies.length === 0) return [];
2020
+ const senders = await getSqlExecutor().db().select({
2021
+ childConversationId: juniorAgentInvocations.childConversationId,
2022
+ invocationId: juniorAgentInvocations.invocationId
2023
+ }).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.invocationId, replies.map((reply) => reply.invocationId)));
2024
+ return (await Promise.all(children.map(async ({ childConversationId }) => {
2025
+ const turnIds = await listOpenLoopTurnIds(childConversationId);
2026
+ return replies.some((reply) => senders.some((sender) => sender.invocationId === reply.invocationId && sender.childConversationId === childConversationId) && turnIds.includes(parseTurnReplyMessageId(reply.messageId) ?? "")) ? childConversationId : void 0;
2027
+ }))).filter((id) => id !== void 0);
2028
+ }
2029
+ /**
2030
+ * List the other child agents of one parent whose results have not reached
2031
+ * the parent yet. A child counts while it runs and after it finishes until its
2032
+ * result is appended to the parent mailbox. A running child whose `reply` is
2033
+ * already in `parentInboundMessageIds`, the ids that reached the parent's
2034
+ * mailbox, has answered, so it does not count.
2035
+ */
2036
+ async function listUnreportedSiblingAgents(parentConversationId, childConversationId, parentInboundMessageIds) {
2037
+ const db = getSqlExecutor().db();
2038
+ const [children, pendingResults, openInvocations] = await Promise.all([
2039
+ listChildAgents(parentConversationId),
2040
+ db.select({
2041
+ childConversationId: juniorAgentInvocations.childConversationId,
2042
+ invocationId: juniorAgentInvocations.invocationId,
2043
+ result: juniorAgentInvocations.result,
2044
+ status: juniorAgentInvocations.status
2045
+ }).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, parentConversationId), eq(juniorAgentInvocations.parentMailboxStatus, "pending"))),
2046
+ db.select({
2047
+ childConversationId: juniorAgentInvocations.childConversationId,
2048
+ invocationId: juniorAgentInvocations.invocationId
2049
+ }).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, parentConversationId), inArray(juniorAgentInvocations.status, [...NON_TERMINAL_AGENT_INVOCATION_STATUSES])))
2050
+ ]);
2051
+ const withPendingResult = new Set(pendingResults.filter((row) => sendsResultToParent(row, parentInboundMessageIds)).map((row) => row.childConversationId));
2052
+ const unanswered = new Set(openInvocations.filter((row) => !parentInboundMessageIds.some((messageId) => isAgentReplyMessageId(messageId, row.invocationId))).map((row) => row.childConversationId));
2053
+ const answered = new Set(openInvocations.map((row) => row.childConversationId).filter((child) => !unanswered.has(child)));
2054
+ for (const child of await listAnsweredLoopChildren(children.filter((child) => child.status === "running" && !openInvocations.some((row) => row.childConversationId === child.childConversationId)), parentInboundMessageIds)) answered.add(child);
2055
+ return children.filter((child) => child.childConversationId !== childConversationId && (NON_TERMINAL_AGENT_INVOCATION_STATUSES.includes(child.status) && !answered.has(child.childConversationId) || withPendingResult.has(child.childConversationId)));
2056
+ }
2057
+ /**
2058
+ * List every child agent below one Conversation, at any depth. A parent owns
2059
+ * the work of its child agents and of their child agents. The list never has
2060
+ * the Conversation itself, its parent, or a sibling.
2061
+ */
2062
+ async function listDescendantAgents(conversationId) {
2063
+ return (await getSqlExecutor().db().select({
2064
+ conversationId: juniorConversations.conversationId,
2065
+ name: juniorAgentBindings.name
2066
+ }).from(juniorConversations).innerJoin(conversationSubtree([conversationId]), eq(conversationSubtreeColumns.conversationId, juniorConversations.conversationId)).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(ne(juniorConversations.conversationId, conversationId)).orderBy(juniorConversations.conversationId)).map((row) => ({
2067
+ conversationId: row.conversationId,
2068
+ ...row.name ? { name: row.name } : void 0
2069
+ }));
2070
+ }
2071
+ /**
2072
+ * List the agents that one Conversation can see. A root Conversation sees
2073
+ * only its child agents. A child agent also sees itself, its parent, and the
2074
+ * other child agents of its parent.
2075
+ */
2076
+ async function listAgentRelatives(input) {
2077
+ const { conversationId, parentConversationId } = input;
2078
+ const [children, family, parent] = await Promise.all([
2079
+ listChildAgents(conversationId),
2080
+ parentConversationId ? listChildAgents(parentConversationId) : [],
2081
+ parentConversationId ? getConversationStore().get({ conversationId: parentConversationId }) : void 0
2082
+ ]);
2083
+ const self = family.find((agent) => agent.childConversationId === conversationId);
2084
+ return {
2085
+ children,
2086
+ ...parent ? { parent: {
2087
+ conversationId: parent.conversationId,
2088
+ status: parent.execution.status,
2089
+ updatedAtMs: parent.execution.updatedAtMs ?? parent.updatedAtMs
2090
+ } } : void 0,
2091
+ ...self ? { self } : void 0,
2092
+ siblings: family.filter((agent) => agent.childConversationId !== conversationId)
2093
+ };
2094
+ }
2095
+ // src/chat/cache-warming/waiting.ts
2096
+ /**
2097
+ * Idle time at which the earliest timer Watch of the Conversation is due,
2098
+ * when it is due by `maxDueIdleMs` (`timerFloorMaxDueIdleMs`). A later timer
2099
+ * changes nothing, so the idle period warms as without a timer.
2100
+ */
2101
+ async function readTimerDueIdleMs(conversationId, sinceMs, maxDueIdleMs) {
2102
+ const dueIdleMs = Math.min(...(await listWatches({ conversationId })).map((watch) => watch.firesAtMs ?? Infinity)) - sinceMs;
2103
+ return dueIdleMs <= maxDueIdleMs ? dueIdleMs : void 0;
2104
+ }
2105
+ function askedReviewItem(messages, final) {
2106
+ for (const message of [final, ...[...messages].reverse()]) {
2107
+ if (message.role === "user") return false;
2108
+ if (message.role === "assistant" && message.content.some((part) => part.type === "toolCall" && part.name === "addReviewItem")) return true;
2109
+ }
2110
+ return false;
2111
+ }
2112
+ /**
2113
+ * Whether the idle period also waits on a child agent that still runs, or
2114
+ * on a Review item that the Turn asked. A running child agent comes first:
2115
+ * its result starts a Turn without a person.
2116
+ */
2117
+ async function readWaitingOn(conversationId, messages, final) {
2118
+ if ((await listChildAgents(conversationId)).some((child) => NON_TERMINAL_AGENT_INVOCATION_STATUSES.includes(child.status))) return "child";
2119
+ return askedReviewItem(messages, final) ? "review" : void 0;
2120
+ }
2121
+ // src/api/conversations/user-message-activity.ts
2122
+ function latestIso(times) {
2123
+ const ms = times.flatMap((at) => at ? [at.getTime()] : []);
2124
+ return ms.length > 0 ? new Date(Math.max(...ms)).toISOString() : void 0;
2125
+ }
2126
+ /** Read the latest true user message time for each selected conversation. */
2127
+ async function readLastUserMessageAtByConversation(db, conversationIds) {
2128
+ if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
2129
+ const queries = userMessageQueries(db);
2130
+ const instruction = queries.instruction.as("latest_instruction");
2131
+ const message = queries.message.as("latest_user_message");
2132
+ const rows = await db.select({
2133
+ conversationId: juniorConversations.conversationId,
2134
+ instructionAt: instruction.createdAt,
2135
+ messageAt: message.createdAt
2136
+ }).from(juniorConversations).leftJoinLateral(instruction, sql`true`).leftJoinLateral(message, sql`true`).where(inArray(juniorConversations.conversationId, conversationIds));
2137
+ const result = /* @__PURE__ */ new Map();
2138
+ for (const { conversationId, instructionAt, messageAt } of rows) {
2139
+ const at = latestIso([instructionAt, messageAt]);
2140
+ if (at) result.set(conversationId, at);
2141
+ }
2142
+ return result;
2143
+ }
2144
+ // src/chat/plugins/unfinished-work.ts
2145
+ /**
2146
+ * Decide whether a conversation's work finished at or before the cutoff,
2147
+ * with no person's message after it finished. Auto-archive passes now minus
2148
+ * the grace period. A conversation without plugin-reported work has nothing
2149
+ * to wait for, so it counts as done here; cache warming needs reported work
2150
+ * and checks `assignedWork` itself.
2151
+ */
2152
+ function isConversationWorkDone(conversation, cutoffMs) {
2153
+ if (conversation.unfinishedWork) return false;
2154
+ if (!conversation.assignedWork) return true;
2155
+ const finishedAt = Date.parse(conversation.finishedWorkAt ?? "");
2156
+ if (!Number.isFinite(finishedAt) || finishedAt > cutoffMs) return false;
2157
+ const lastUserMessageAt = Date.parse(conversation.lastUserMessageAt ?? "");
2158
+ return !(Number.isFinite(lastUserMessageAt) && lastUserMessageAt > finishedAt);
2159
+ }
2160
+ /**
2161
+ * Map each candidate and each child of a candidate root to the candidate it
2162
+ * counts for. A child agent runs under its own conversation id, so a plugin
2163
+ * links the work that the child does, such as a pull request, to the child.
2164
+ */
2165
+ async function readWorkOwners(conversationIds) {
2166
+ const owners = new Map(conversationIds.map((id) => [id, id]));
2167
+ const children = await getDb().select({
2168
+ conversationId: juniorConversations.conversationId,
2169
+ rootConversationId: juniorConversations.rootConversationId
2170
+ }).from(juniorConversations).where(inArray(juniorConversations.rootConversationId, conversationIds));
2171
+ for (const child of children) if (child.rootConversationId && !owners.has(child.conversationId)) owners.set(child.conversationId, child.rootConversationId);
2172
+ return owners;
2173
+ }
2174
+ /**
2175
+ * Return assigned and unfinished plugin work for the candidate conversations.
2176
+ * Work in a child conversation counts for its root candidate. Feed Priority
2177
+ * combines these signals with conversation activity on the host.
2178
+ */
2179
+ async function listConversationWork(conversationIds) {
2180
+ if (conversationIds.length === 0) return {
2181
+ assignedIds: [],
2182
+ failed: false,
2183
+ finishedAtById: {},
2184
+ unfinishedIds: []
2185
+ };
2186
+ const owners = await readWorkOwners(conversationIds);
2187
+ const queriedIds = [...owners.keys()];
2188
+ const assigned = /* @__PURE__ */ new Set();
2189
+ const finishedAtById = /* @__PURE__ */ new Map();
2190
+ const unfinished = /* @__PURE__ */ new Set();
2191
+ let failed = false;
2192
+ for (const plugin of getPlugins()) {
2193
+ const hook = plugin.hooks?.unfinishedWork;
2194
+ if (!hook) continue;
2195
+ try {
2196
+ const result = await hook({
2197
+ conversationIds: queriedIds,
2198
+ db: getDb(),
2199
+ log: createPluginLogger(plugin.manifest.name),
2200
+ plugin: { name: plugin.manifest.name },
2201
+ cache: createPluginCache(plugin.manifest.name)
2202
+ });
2203
+ for (const workId of result.conversationIds) {
2204
+ const conversationId = owners.get(workId);
2205
+ if (!conversationId) continue;
2206
+ unfinished.add(conversationId);
2207
+ assigned.add(conversationId);
2208
+ }
2209
+ for (const workId of result.assignedConversationIds ?? []) {
2210
+ const conversationId = owners.get(workId);
2211
+ if (conversationId) assigned.add(conversationId);
2212
+ }
2213
+ for (const [workId, finishedAt] of Object.entries(result.finishedWorkAtByConversationId ?? {})) {
2214
+ const conversationId = owners.get(workId);
2215
+ if (!conversationId) continue;
2216
+ const time = Date.parse(finishedAt);
2217
+ if (!Number.isFinite(time)) continue;
2218
+ const current = finishedAtById.get(conversationId);
2219
+ if (!current || time > Date.parse(current)) finishedAtById.set(conversationId, finishedAt);
2220
+ }
2221
+ } catch (error) {
2222
+ failed = true;
2223
+ logWarn("plugin.unfinished_work.hook.failed", {
2224
+ "app.plugin.name": plugin.manifest.name,
2225
+ "exception.message": error instanceof Error ? error.message : String(error)
2226
+ });
2227
+ }
2228
+ }
2229
+ return {
2230
+ assignedIds: conversationIds.filter((conversationId) => assigned.has(conversationId)),
2231
+ failed,
2232
+ finishedAtById: Object.fromEntries(conversationIds.flatMap((conversationId) => {
2233
+ const finishedAt = finishedAtById.get(conversationId);
2234
+ return finishedAt ? [[conversationId, finishedAt]] : [];
2235
+ })),
2236
+ unfinishedIds: conversationIds.filter((conversationId) => unfinished.has(conversationId))
2237
+ };
2238
+ }
2239
+ // src/chat/cache-warming/work-state.ts
2240
+ /**
2241
+ * Read the plugin work state and the archive state of a Conversation when an
2242
+ * idle period starts that Junior can warm. Work of child Conversations counts
2243
+ * for their root. A child counts as archived when it or its root is: a manual
2244
+ * archive also archives the children, but auto-archive sets only the root.
2245
+ */
2246
+ async function readSegmentState(conversationId, nowMs) {
2247
+ const [work, conversation, rootArchived] = await Promise.all([
2248
+ listConversationWork([conversationId]),
2249
+ getConversationStore().get({ conversationId }),
2250
+ rootConversationIsArchived(getSqlExecutor(), conversationId)
2251
+ ]);
2252
+ const archived = rootArchived || conversation?.archivedAtMs !== void 0;
2253
+ if (work.failed || !work.assignedIds.includes(conversationId)) return {
2254
+ workState: "none",
2255
+ archived
2256
+ };
2257
+ if (work.unfinishedIds.includes(conversationId)) return {
2258
+ workState: "open",
2259
+ archived
2260
+ };
2261
+ const lastUserMessageAt = (await readLastUserMessageAtByConversation(getDb(), [conversationId])).get(conversationId);
2262
+ return {
2263
+ workState: isConversationWorkDone({
2264
+ assignedWork: true,
2265
+ finishedWorkAt: work.finishedAtById[conversationId],
2266
+ lastUserMessageAt
2267
+ }, nowMs) ? "done" : "none",
2268
+ archived
2269
+ };
2270
+ }
2271
+ // src/chat/cache-warming/warmup.ts
2272
+ /**
2273
+ * Prompt cache warming for idle Conversations.
2274
+ *
2275
+ * After a turn ends, the next human message often arrives after the short
2276
+ * prompt cache TTL. Then the full history is written to the cache again. A
2277
+ * warmup sends the same request again with a one-token output limit before
2278
+ * the cache expires. The provider reads the cached prefix and refreshes its
2279
+ * TTL. `model.ts` owns the cost model.
2280
+ *
2281
+ * Each idle period gets one recorded reply gap, so the model also sees the
2282
+ * people who do not reply. A reply records its gap. A delayed `horizon`
2283
+ * message records `NO_REPLY_GAP_MS` when no reply came in the idle horizon.
2284
+ *
2285
+ * Only a Turn writes the Conversation state. Warmups and the horizon run
2286
+ * while the next Turn can start, so they write only keys of their own idle
2287
+ * period (`generation`): the snapshot, the warmup count, and the gap claim.
2288
+ * Work for an old idle period then cannot change a newer one.
2289
+ */
2290
+ var warmup_exports = /* @__PURE__ */ __exportAll({
2291
+ CONVERSATION_STATE_TTL_MS: () => CONVERSATION_STATE_TTL_MS,
2292
+ GLOBAL_GAPS_MAX: () => GLOBAL_GAPS_MAX,
2293
+ GLOBAL_GAPS_TTL_MS: () => GLOBAL_GAPS_TTL_MS,
2294
+ createCacheWarmingRecorder: () => createCacheWarmingRecorder,
2295
+ runCacheWarmup: () => runCacheWarmup,
2296
+ segmentGapsKey: () => segmentGapsKey
2297
+ });
2298
+ /** Gaps kept in each segment list. */
2299
+ const GLOBAL_GAPS_MAX = 2e3;
2300
+ /** A segment list expires this long after its last gap. */
2301
+ const GLOBAL_GAPS_TTL_MS = 43200 * MINUTE_MS;
2302
+ const CONVERSATION_GAPS_MAX = 50;
2303
+ /** The Turn count of a Conversation resets after this long with no call. */
2304
+ const CONVERSATION_STATE_TTL_MS = 10080 * MINUTE_MS;
2305
+ const ANSWER_TOOL_ENDINGS = {
2306
+ [NO_REPLY_TOOL_NAME]: "no_reply",
2307
+ [REPORT_BLOCKED_TOOL_NAME]: "blocked"
2308
+ };
2309
+ /** State list of the recent reply gaps (ms) of one `gapSegment`. */
2310
+ const segmentGapsKey = (segment) => `${KEY_PREFIX}:gaps:${segment}`;
2311
+ const conversationKey = (conversationId) => `${KEY_PREFIX}:conversation:${conversationId}`;
2312
+ /**
2313
+ * Recent reply gaps (ms) of the idle periods of this Conversation, per
2314
+ * `gapSegment`. A person's quick replies must not set the return chance of an
2315
+ * idle period that a system Turn started.
2316
+ */
2317
+ const conversationGapsKey = (conversationId, segment) => `${KEY_PREFIX}:gaps:conversation:${conversationId}:${segment}`;
2318
+ const snapshotKey = (conversationId, generation) => `${KEY_PREFIX}:snapshot:${conversationId}:${generation}`;
2319
+ /** Warmups that completed in the idle period. */
2320
+ const warmupsKey = (conversationId, generation) => `${KEY_PREFIX}:warmups:${conversationId}:${generation}`;
2321
+ /** Set by the first of the reply and the horizon to record the gap. */
2322
+ const gapClaimKey = (conversationId, generation) => `${KEY_PREFIX}:gap_claim:${conversationId}:${generation}`;
2323
+ const segmentAttributes = (warm) => ({
2324
+ "app.cache_warming.work_state": warm.workState,
2325
+ "app.cache_warming.archived": warm.archived,
2326
+ ...warm.turnEnding ? { "app.cache_warming.turn_ending": warm.turnEnding } : void 0,
2327
+ ...warm.waitingOn ? { "app.cache_warming.waiting_on": warm.waitingOn } : void 0,
2328
+ ...warm.timerDueIdleMs !== void 0 ? { "app.cache_warming.timer_due_ms": warm.timerDueIdleMs } : void 0
2329
+ });
2330
+ const decisionSegment = (warm) => warm.waitingOn ? waitingGapSegment(warm.segment, warm.waitingOn) : warm.segment;
2331
+ const recordedSegments = (warm) => warm.waitingOn ? [decisionSegment(warm), warm.segment] : [warm.segment];
2332
+ const timerPending = (warm, idleMs) => warm.timerDueIdleMs !== void 0 && idleMs < warm.timerDueIdleMs + 12e4;
2333
+ const snapshotAttributes = (size) => ({
2334
+ "app.cache_warming.snapshot_bytes": size.bytes,
2335
+ "app.cache_warming.snapshot_image_count": size.imageCount,
2336
+ "app.cache_warming.snapshot_image_bytes": size.imageBytes
2337
+ });
2338
+ async function scheduleWarmup(message, requestStartedAtMs, warm) {
2339
+ const { cacheExpiresAtMs, delayMs } = warmupTiming(requestStartedAtMs, warm.cacheTtlMs);
2340
+ await sendCacheWarmup({
2341
+ ...message,
2342
+ cacheExpiresAtMs
2343
+ }, delayMs);
2344
+ }
2345
+ async function recordGap(state, conversationId, generation, warm, gapMs) {
2346
+ if (!await state.setIfNotExists(gapClaimKey(conversationId, generation), true, CONVERSATION_STATE_TTL_MS)) return;
2347
+ for (const segment of recordedSegments(warm)) await state.appendToList(segmentGapsKey(segment), gapMs, {
2348
+ maxLength: GLOBAL_GAPS_MAX,
2349
+ ttlMs: GLOBAL_GAPS_TTL_MS
2350
+ });
2351
+ await state.appendToList(conversationGapsKey(conversationId, decisionSegment(warm)), gapMs, {
2352
+ maxLength: CONVERSATION_GAPS_MAX,
2353
+ ttlMs: CONVERSATION_STATE_TTL_MS
2354
+ });
2355
+ }
2356
+ async function startIdlePeriod(state, conversationId, request, message, turn, systemPrompt, turnEnding) {
2357
+ const idle = {
2358
+ generation: randomUUID(),
2359
+ sinceMs: request.startedAtMs
2360
+ };
2361
+ const prefixTokens = cachedPrefixTokens(message);
2362
+ const ttlMs = cacheTtlMs(request);
2363
+ if (ttlMs === void 0 || prefixTokens < 5e4) return idle;
2364
+ const timerDueIdleMs = await readTimerDueIdleMs(conversationId, idle.sinceMs, timerFloorMaxDueIdleMs({
2365
+ cacheReadPrice: request.model.cost.cacheRead,
2366
+ cacheWritePrice: request.model.cost.cacheWrite,
2367
+ cacheTtlMs: ttlMs
2368
+ }));
2369
+ const { skipReason, ...snapshot } = await saveSnapshot(state, conversationId, snapshotKey(conversationId, idle.generation), request.context, Math.max(IDLE_HORIZON_MS, (timerDueIdleMs ?? 0) + TIMER_START_DELAY_MS + idle.sinceMs - Date.now()));
2370
+ const metricOptions = {
2371
+ unit: "byte",
2372
+ attributes: { "app.cache_warming.stored": skipReason === void 0 }
2373
+ };
2374
+ sentry_exports.metrics.distribution("cache_warming.snapshot.bytes", snapshot.bytes, metricOptions);
2375
+ sentry_exports.metrics.distribution("cache_warming.snapshot.image_bytes", snapshot.imageBytes, metricOptions);
2376
+ if (skipReason) {
2377
+ logWarn("cache_warming.snapshot.skipped", {
2378
+ "app.cache_warming.skip_reason": skipReason,
2379
+ "app.cache_warming.prefix_tokens": prefixTokens,
2380
+ ...snapshotAttributes(snapshot)
2381
+ });
2382
+ return idle;
2383
+ }
2384
+ const [segmentState, waitingOn] = await Promise.all([readSegmentState(conversationId, Date.now()), readWaitingOn(conversationId, request.context.messages, message)]);
2385
+ const segmentInput = {
2386
+ ...turn,
2387
+ ...segmentState
2388
+ };
2389
+ const parentSegment = parentGapSegment(segmentInput);
2390
+ return {
2391
+ ...idle,
2392
+ warm: {
2393
+ segment: gapSegment(segmentInput),
2394
+ turnEnding,
2395
+ ...parentSegment ? { parentSegment } : void 0,
2396
+ ...waitingOn ? { waitingOn } : void 0,
2397
+ ...timerDueIdleMs !== void 0 ? { timerDueIdleMs } : void 0,
2398
+ ...request.context.systemPrompt !== void 0 ? { systemPrompt: {
2399
+ ...systemPrompt,
2400
+ hash: systemPromptHash(request.context.systemPrompt)
2401
+ } } : void 0,
2402
+ ...segmentState,
2403
+ modelId: request.model.id,
2404
+ prefixTokens,
2405
+ cacheTtlMs: ttlMs,
2406
+ ...request.reasoning ? { reasoning: request.reasoning } : void 0,
2407
+ snapshot
2408
+ }
2409
+ };
2410
+ }
2411
+ async function recordModelCall(conversationId, userActor, systemPrompt, request, message, turnEnding) {
2412
+ const state = await connectedState();
2413
+ const previous = await state.get(conversationKey(conversationId));
2414
+ const idle = previous?.idle;
2415
+ if (idle?.warm) {
2416
+ const gapMs = request.startedAtMs - idle.sinceMs;
2417
+ if (gapMs > 0) await recordGap(state, conversationId, idle.generation, idle.warm, gapMs);
2418
+ await state.delete(snapshotKey(conversationId, idle.generation));
2419
+ const warmups = await state.get(warmupsKey(conversationId, idle.generation)) ?? 0;
2420
+ if (warmups > 0) logInfo("cache_warming.conversation.returned", {
2421
+ "app.cache_warming.gap_ms": gapMs,
2422
+ "app.cache_warming.prefix_tokens": idle.warm.prefixTokens,
2423
+ "app.cache_warming.warmup_count": warmups,
2424
+ ...segmentAttributes(idle.warm),
2425
+ "gen_ai.usage.cache_read.input_tokens": message.usage.cacheRead,
2426
+ "gen_ai.usage.cache_creation.input_tokens": message.usage.cacheWrite
2427
+ });
2428
+ }
2429
+ const endedTurns = previous?.endedTurns ?? 0;
2430
+ const next = turnEnding ? {
2431
+ endedTurns: endedTurns + 1,
2432
+ idle: await startIdlePeriod(state, conversationId, request, message, {
2433
+ userActor,
2434
+ endedTurns
2435
+ }, systemPrompt, turnEnding)
2436
+ } : { endedTurns };
2437
+ if (!idle && !next.idle) return;
2438
+ await state.set(conversationKey(conversationId), next, CONVERSATION_STATE_TTL_MS);
2439
+ if (next.idle?.warm) {
2440
+ const { generation } = next.idle;
2441
+ await sendCacheWarmup({
2442
+ kind: "horizon",
2443
+ conversationId,
2444
+ generation
2445
+ }, request.startedAtMs + IDLE_HORIZON_MS - Date.now());
2446
+ await scheduleWarmup({
2447
+ kind: "warmup",
2448
+ conversationId,
2449
+ cycle: 1,
2450
+ generation
2451
+ }, request.startedAtMs, next.idle.warm);
2452
+ }
2453
+ }
2454
+ async function stopIdleWarmups(conversationId) {
2455
+ try {
2456
+ const state = await connectedState();
2457
+ const idle = (await state.get(conversationKey(conversationId)))?.idle;
2458
+ if (idle?.warm) await state.delete(snapshotKey(conversationId, idle.generation));
2459
+ } catch (error) {
2460
+ logWarn("cache_warming.idle_period.stop_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
2461
+ }
2462
+ }
2463
+ /**
2464
+ * Create a recorder for one agent run. `userActor` is true when a person
2465
+ * started the Turn. A failure to record only loses cache warming, so it is
2466
+ * logged and does not stop the run.
2467
+ */
2468
+ function createCacheWarmingRecorder(conversationId, userActor, systemPrompt) {
2469
+ let lastRequest;
2470
+ let lastCall;
2471
+ let answerToolEnding;
2472
+ let idleEnded = false;
2473
+ let warmupsStopped;
2474
+ const toolWait = createToolWaitWarmer(conversationId);
2475
+ return {
2476
+ wrap: (base = streamSimple) => (model, context, options) => {
2477
+ if (!warmupsStopped && getChatConfig().cacheWarmingEnabled) warmupsStopped = stopIdleWarmups(conversationId);
2478
+ toolWait.stop();
2479
+ const cacheRetention = options?.cacheRetention ?? (getChatConfig().cacheWarmingEnabled ? "short" : void 0);
2480
+ lastRequest = {
2481
+ model,
2482
+ context: {
2483
+ ...context,
2484
+ messages: [...context.messages]
2485
+ },
2486
+ ...options?.reasoning ? { reasoning: options.reasoning } : void 0,
2487
+ ...cacheRetention ? { cacheRetention } : void 0,
2488
+ startedAtMs: Date.now()
2489
+ };
2490
+ return base(model, context, cacheRetention ? {
2491
+ ...options,
2492
+ cacheRetention
2493
+ } : options);
2494
+ },
2495
+ record: async (message) => {
2496
+ const request = lastRequest;
2497
+ lastRequest = void 0;
2498
+ await warmupsStopped;
2499
+ if (!getChatConfig().cacheWarmingEnabled || !request) return;
2500
+ try {
2501
+ await toolWait.record(request, message);
2502
+ } catch (error) {
2503
+ logWarn("cache_warming.tool_wait.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
2504
+ }
2505
+ if (message.stopReason === "error" || message.stopReason === "aborted") return;
2506
+ lastCall = {
2507
+ request,
2508
+ message
2509
+ };
2510
+ if (idleEnded && message.stopReason !== "stop") return;
2511
+ idleEnded = message.stopReason !== "stop";
2512
+ try {
2513
+ await recordModelCall(conversationId, userActor, systemPrompt, request, message, message.stopReason === "stop" ? "reply" : void 0);
2514
+ } catch (error) {
2515
+ logWarn("cache_warming.model_call.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
2516
+ }
2517
+ },
2518
+ toolsReturned: toolWait.toolsReturned,
2519
+ answerToolEnded: (toolName) => {
2520
+ answerToolEnding = systemPrompt.mode === "automation" ? void 0 : ANSWER_TOOL_ENDINGS[toolName];
2521
+ },
2522
+ stop: async () => {
2523
+ try {
2524
+ await toolWait.end();
2525
+ } catch (error) {
2526
+ logWarn("cache_warming.tool_wait.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
2527
+ }
2528
+ if (!answerToolEnding || !lastCall) return;
2529
+ try {
2530
+ await recordModelCall(conversationId, userActor, systemPrompt, lastCall.request, lastCall.message, answerToolEnding);
2531
+ } catch (error) {
2532
+ logWarn("cache_warming.model_call.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
2533
+ }
2534
+ }
2535
+ };
2536
+ }
2537
+ /**
2538
+ * Run one scheduled cache warming message. A message for an idle period that
2539
+ * already ended does nothing and makes no span.
2540
+ *
2541
+ * Each warmup decision has one `cache_warming.warmup` span, with the warmup
2542
+ * call as a child `gen_ai.chat` span (`junior.cache_warmup`). A tool wait
2543
+ * warmup (`tool-wait.ts`) has the same span in the trace of its Turn.
2544
+ * `app.cache_warming.outcome`:
2545
+ * - `missed`: the warmup call did not read the cached prefix. It logs
2546
+ * `cache_warming.warmup.failed` and reports to Sentry.
2547
+ * - `failed`: the warmup call threw.
2548
+ * - `skipped`: `skip_reason` is `cache_expired`, `breaker_open`,
2549
+ * `prompt_changed` (a deploy changed the system prompt, so the idle period
2550
+ * stops), `stopped` (warming stopped or the tools returned first; no log),
2551
+ * `image_missing` (an image key of the snapshot expired, so the idle period
2552
+ * stops), or a `decideWarmup` reason.
2553
+ *
2554
+ * Idle warmups carry the sizes of the idle period's snapshot:
2555
+ * `snapshot_bytes` (compressed, without images), `snapshot_image_count`
2556
+ * (distinct images stored under hash keys), and `snapshot_image_bytes`
2557
+ * (their base64 data). A snapshot over a limit stores nothing and warns
2558
+ * `cache_warming.snapshot.skipped` with `prefix_tokens`, the same sizes, and
2559
+ * `skip_reason` `snapshot_too_large` (still over the limit without its
2560
+ * images) or `images_too_large` (its images are over their limit). Each
2561
+ * snapshot also records the unsampled distribution metrics
2562
+ * `cache_warming.snapshot.bytes` and `cache_warming.snapshot.image_bytes`,
2563
+ * with `app.cache_warming.stored` false for a snapshot over a limit.
2564
+ *
2565
+ * `work_state` and `archived` are read when the idle period starts and pick
2566
+ * its `gapSegment`. `turn_ending` is how the Turn before the idle period
2567
+ * ended: `reply` (a final response), `no_reply` (`noReply`), or `blocked`
2568
+ * (`reportBlocked`). `waiting_on` is `child` (a child agent still ran) or
2569
+ * `review` (the Turn asked a Review item) when the idle period starts, and
2570
+ * picks the segment's `waitingGapSegment` child. `timer_due_ms` is the idle
2571
+ * time at which a timer is due, when it is due within
2572
+ * `timerFloorMaxDueIdleMs`. The `conversation.returned` log has the same
2573
+ * five. Decision attributes are absent when the warmup skipped before the
2574
+ * decision. Of them, `timer_floor` is true for a warmup that only the timer
2575
+ * floor sends (`decideWarmup` reason `timer`). Cost and usage are absent
2576
+ * when no call completed.
2577
+ */
2578
+ async function runCacheWarmup(message) {
2579
+ const { conversationId } = message;
2580
+ const state = await connectedState();
2581
+ const idle = (await state.get(conversationKey(conversationId)))?.idle;
2582
+ const warm = idle?.warm;
2583
+ if (!idle || !warm || idle.generation !== message.generation) return;
2584
+ const { generation } = idle;
2585
+ const stop = () => state.delete(snapshotKey(conversationId, generation));
2586
+ if (message.kind === "horizon") {
2587
+ if (!timerPending(warm, Date.now() - idle.sinceMs)) await stop();
2588
+ await recordGap(state, conversationId, generation, warm, NO_REPLY_GAP_MS);
2589
+ return;
2590
+ }
2591
+ if ((await state.get(warmupsKey(conversationId, generation)) ?? 0) !== message.cycle - 1) return;
2592
+ const attributes = {
2593
+ "app.cache_warming.cycle": message.cycle,
2594
+ "app.cache_warming.prefix_tokens": warm.prefixTokens,
2595
+ "app.cache_warming.trigger": "idle",
2596
+ ...segmentAttributes(warm),
2597
+ ...warm.snapshot ? snapshotAttributes(warm.snapshot) : void 0,
2598
+ "app.cache_warming.cache_ttl_left_ms": message.cacheExpiresAtMs - Date.now()
2599
+ };
2600
+ await withSpan("cache_warming.warmup", "cache_warming.warmup", {
2601
+ conversationId,
2602
+ modelId: warm.modelId
2603
+ }, async (setSpanAttributes) => {
2604
+ const setOutcome = (outcome, extra = {}) => setSpanAttributes({
2605
+ ...attributes,
2606
+ ...extra,
2607
+ "app.cache_warming.outcome": outcome
2608
+ });
2609
+ const skip = async (reason) => {
2610
+ const skipReason = { "app.cache_warming.skip_reason": reason };
2611
+ logInfo("cache_warming.warmup.skipped", {
2612
+ ...attributes,
2613
+ ...skipReason
2614
+ });
2615
+ setOutcome("skipped", skipReason);
2616
+ await stop();
2617
+ };
2618
+ if (warmupTooLate(message.cacheExpiresAtMs)) {
2619
+ await skip("cache_expired");
2620
+ return;
2621
+ }
2622
+ if (await breakerOpen(state, warm.modelId)) {
2623
+ await skip("breaker_open");
2624
+ return;
2625
+ }
2626
+ if (warm.systemPrompt && warm.systemPrompt.hash !== systemPromptHash(await buildDeploymentSystemPrompt(warm.systemPrompt.platform, warm.systemPrompt.mode))) {
2627
+ await skip("prompt_changed");
2628
+ return;
2629
+ }
2630
+ const model = resolveGatewayModel(warm.modelId);
2631
+ const [segment, ...parents] = [...recordedSegments(warm), ...warm.parentSegment ? [warm.parentSegment] : []];
2632
+ const globalGapsMs = await state.getList(segmentGapsKey(segment));
2633
+ const priorGapsMs = [];
2634
+ for (const parent of parents) {
2635
+ if (!segmentNeedsParent((priorGapsMs.at(-1) ?? globalGapsMs).length)) break;
2636
+ priorGapsMs.push(await state.getList(segmentGapsKey(parent)));
2637
+ }
2638
+ const decision = decideWarmup({
2639
+ conversationGapsMs: await state.getList(conversationGapsKey(conversationId, decisionSegment(warm))),
2640
+ globalGapsMs,
2641
+ priorGapsMs,
2642
+ ...warm.timerDueIdleMs !== void 0 ? { timerDueIdleMs: warm.timerDueIdleMs } : void 0,
2643
+ idleMs: Date.now() - idle.sinceMs,
2644
+ cacheExpiryIdleMs: message.cacheExpiresAtMs - idle.sinceMs,
2645
+ cacheTtlMs: warm.cacheTtlMs,
2646
+ prefixTokens: warm.prefixTokens,
2647
+ cacheReadPrice: model.cost.cacheRead,
2648
+ cacheWritePrice: model.cost.cacheWrite
2649
+ });
2650
+ attributes["app.cache_warming.return_probability"] = decision.returnProbability;
2651
+ attributes["app.cache_warming.returns_per_warmup"] = decision.returnsPerWarmup;
2652
+ attributes["app.cache_warming.threshold"] = decision.threshold;
2653
+ attributes["app.cache_warming.parent_prior"] = decision.parentPrior;
2654
+ attributes["app.cache_warming.timer_floor"] = decision.reason === "timer";
2655
+ if (!decision.warm) {
2656
+ await skip(decision.reason);
2657
+ return;
2658
+ }
2659
+ const context = await loadSnapshot(state, conversationId, snapshotKey(conversationId, generation));
2660
+ if (context === "stopped") {
2661
+ setOutcome("skipped", { "app.cache_warming.skip_reason": "stopped" });
2662
+ return;
2663
+ }
2664
+ if (context === "image_missing") {
2665
+ await skip("image_missing");
2666
+ return;
2667
+ }
2668
+ const startedAtMs = Date.now();
2669
+ const warmup = await sendWarmup(state, {
2670
+ conversationId,
2671
+ modelId: warm.modelId,
2672
+ context,
2673
+ ...warm.reasoning ? { reasoning: warm.reasoning } : void 0,
2674
+ prefixTokens: warm.prefixTokens
2675
+ }).catch(async (error) => {
2676
+ setOutcome("failed");
2677
+ await stop();
2678
+ throw error;
2679
+ });
2680
+ Object.assign(attributes, warmup.attributes);
2681
+ if (!warmup.refreshed) {
2682
+ logWarn("cache_warming.warmup.failed", attributes);
2683
+ setOutcome("missed");
2684
+ await stop();
2685
+ return;
2686
+ }
2687
+ logInfo("cache_warming.warmup.completed", attributes);
2688
+ setOutcome("completed");
2689
+ await state.set(warmupsKey(conversationId, generation), message.cycle, IDLE_HORIZON_MS);
2690
+ if (await state.get(snapshotKey(conversationId, generation))) await scheduleWarmup({
2691
+ kind: "warmup",
2692
+ conversationId,
2693
+ cycle: message.cycle + 1,
2694
+ generation
2695
+ }, startedAtMs, warm);
2696
+ }, attributes);
2697
+ }
2698
+ export { AgentDepthLimitError as A, MIN_WARMUP_PREFIX_TOKENS as B, dropOwnUnreadLoopReplies as C, recordSubagentEnded as D, stopChildAgentsOf as E, AgentNameInUseError as F, gapHistogramReport as H, findChildAgentConversationId as I, GAP_SEGMENTS as L, AgentMessagePausedError as M, AgentMessageQueueFullError as N, createAgentInvocationForMessage as O, AgentMessageTargetError as P, IDLE_HORIZON_MS as R, resolveAgentInvocationId as S, stopChildAgentsBelow as T, gapSegment as U, NO_REPLY_GAP_MS as V, createAgentInvocationWorker as _, segmentGapsKey as a, endAgentInvocationsOfStoppedWork as b, listConversationWork as c, listChildAgents as d, listDescendantAgents as f, routeChildInput as g, getChildAgentInputInvocation as h, createCacheWarmingRecorder as i, AgentInvocationLimitError as j, createAgentInvocationFromLatest as k, readLastUserMessageAtByConversation as l, childAgentInput as m, GLOBAL_GAPS_MAX as n, warmup_exports as o, listUnreportedSiblingAgents as p, GLOBAL_GAPS_TTL_MS as r, isConversationWorkDone as s, CONVERSATION_STATE_TTL_MS as t, listAgentRelatives as u, createAndEnqueueAgentInvocation as v, stopChildAgent as w, enqueueAgentInvocation as x, endActiveAgentInvocations as y, MINUTE_MS as z };