@sentry/junior 0.301.0 → 0.302.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 (79) hide show
  1. package/dist/adapter-context-Cx9fn9B3.js +43 -0
  2. package/dist/{admin-CRJHvCGg.js → admin-_poE5NKL.js} +2 -2
  3. package/dist/{agent-runner-H4YhvNBj.js → agent-runner-CY9RvsTX.js} +1380 -10601
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +4 -5
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +91 -68
  8. package/dist/{app-HDZglaIu.d.ts → app-BpY3wtRP.d.ts} +2 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +66 -296
  11. package/dist/{background-compaction-queue-CNrZ3QcU.js → background-compaction-queue-CXFq1_Cz.js} +94 -203
  12. package/dist/{briefs-x6Mzwxmg.js → briefs-B3NG-pid.js} +2 -2
  13. package/dist/{catalog-runtime-BEY6EGRi.js → catalog-runtime-Dss0lSV6.js} +1 -1
  14. package/dist/cli/chat.js +15 -15
  15. package/dist/cli/check.js +3 -3
  16. package/dist/cli/main.js +3 -3
  17. package/dist/cli/plugins.js +4 -4
  18. package/dist/cli/snapshot-create.js +4 -4
  19. package/dist/cli/upgrade.d.ts +1 -1
  20. package/dist/cli/upgrade.js +3 -3
  21. package/dist/{config-CmjhyqgB.js → config-CzeZiMKs.js} +2 -2
  22. package/dist/{connections-CfIRm0xv.js → connections-CDYhMfrs.js} +6 -6
  23. package/dist/{continue-in-slack-DPoABVkB.js → continue-in-slack-7Uf05ndC.js} +5 -6
  24. package/dist/{conversation-feed-CfpyFMHP.js → conversation-feed-Clf_cv0n.js} +1 -0
  25. package/dist/{conversation-privacy-0CM0V2qK.js → conversation-privacy-D9xnM5mK.js} +1 -1
  26. package/dist/{conversation-turn-C0sxyvS-.js → conversation-turn-D7SEZgTG.js} +15 -16
  27. package/dist/{credential-sync-tEMKZ_8M.js → credential-sync-DoD0gW-j.js} +13 -15
  28. package/dist/{db-Czra10QW.js → db-B-gtnNjr.js} +314 -5
  29. package/dist/{db-BdUHQhrC.d.ts → db-BdsCzytP.d.ts} +1 -1
  30. package/dist/{executor-D_023K0H.js → executor-DZg20EqU.js} +39 -4
  31. package/dist/install-t1KQyTUs.js +228 -0
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{state-CEbZuZD6.js → legacy-web-actor-id-C-cEeWqL.js} +33 -4
  34. package/dist/{lineage-DmMIE0VL.js → lineage-C79GjoQr.js} +2 -2
  35. package/dist/{logging-DcjLDDqi.js → logging-C9oDAg4M.js} +7 -3
  36. package/dist/{message-C0JY9RJP.js → message-BLUCzJXN.js} +8 -8
  37. package/dist/{model-input-CBp-p24N.js → model-input-5jwNC45G.js} +3 -3
  38. package/dist/nitro.d.ts +1 -1
  39. package/dist/nitro.js +4 -3
  40. package/dist/{oauth-callback-server-BRq9QNhU.js → oauth-callback-server-BBl66vCb.js} +2 -2
  41. package/dist/{projection-CQNDOi82.js → projection-CIBwgD3s.js} +282 -64
  42. package/dist/{prompt-DLUB5m72.js → prompt-CRQbzp5e.js} +14 -4
  43. package/dist/queue-DtCDaIct.js +115 -0
  44. package/dist/{registry-Dj377ADs.js → registry-DdFQHZ_d.js} +1 -1
  45. package/dist/{resolve-DJkh9Fky.js → resolve-CdW4BdrK.js} +4 -229
  46. package/dist/{result-C8iIpDl1.js → result-oOMv1t4O.js} +9 -9
  47. package/dist/{runner-DZqrOy8C.js → runner-DqitLtm-.js} +8 -8
  48. package/dist/{sandbox-egress-signals-CGwH86S9.js → sandbox-egress-signals-Bw9I0yfJ.js} +1 -1
  49. package/dist/{schema-CdZFn7Qd.d.ts → schema-BIFM-U1a.d.ts} +441 -30
  50. package/dist/{schema-DyHXiQKI.js → schema-DnVQepWP.js} +66 -29
  51. package/dist/{service-account-D6jGR4a1.js → service-account-B6mKAPVo.js} +3 -3
  52. package/dist/{service-account-suY004dx.js → service-account-CrZftRTb.js} +257 -6
  53. package/dist/{session-stop-BLmfFI3d.js → session-stop-DW63Z3kj.js} +543 -548
  54. package/dist/{skills-CmNG0dHb.js → skills-C16fz60Z.js} +2 -2
  55. package/dist/{slack-conversation-unfurl-Bty-DlHe.js → slack-conversation-unfurl-BHhefEb7.js} +8 -7
  56. package/dist/{spawn-CNjkpXpk.js → spawn-D_RnFYfy.js} +6 -6
  57. package/dist/{stop-Bjy2-K4H.js → stop-7p1i08CY.js} +724 -106
  58. package/dist/{store-DmV4CoNr.js → store-C28I0CVW.js} +5 -5
  59. package/dist/{task-queue-AhG1tSXR.js → task-queue-BVUJbQ28.js} +3 -3
  60. package/dist/{task-runner-BMxZI3o7.js → task-runner-CWi8j7Z6.js} +6 -8
  61. package/dist/{thread-context-CXLnbg7g.js → thread-context-D3-yYUd0.js} +7 -7
  62. package/dist/{store-Epv6t4vV.js → turn-session-routing-BFMS9ATF.js} +381 -10
  63. package/dist/{turn-user-message-DsUZi9gn.js → turn-user-message-C3-O8Omt.js} +3 -3
  64. package/dist/{validation-DOz8X9BU.js → validation-BSFKUIb4.js} +1 -1
  65. package/dist/{version-CGMRmMPK.js → version-BHHXNi-0.js} +1 -1
  66. package/dist/version.js +1 -1
  67. package/dist/{viewer-H3EsMWtJ.js → viewer-B1SO21Qa.js} +3 -3
  68. package/dist/warmup-Bz9bzkzN.js +13927 -0
  69. package/dist/{statuses-Hn-HsOph.js → web-message-id-lNodcCOI.js} +136 -1
  70. package/dist/{worker-ClphajjD.js → worker-BspReIIK.js} +7 -7
  71. package/migrations/0108_conversation_embeddings.sql +13 -0
  72. package/migrations/meta/0108_snapshot.json +4688 -0
  73. package/migrations/meta/_journal.json +7 -0
  74. package/package.json +8 -6
  75. package/dist/adapter-CNjGEJO9.js +0 -303
  76. package/dist/reporting-window-DopzcOHh.js +0 -137
  77. package/dist/turn-session-routing-BD3-jJl7.js +0 -380
  78. package/dist/users-BxvYclQg.js +0 -424
  79. package/dist/warmup-CdU5hR49.js +0 -3715
@@ -1,3715 +0,0 @@
1
- import { n as captureMessage, u as sentry_exports, v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { $ as loadTurnCheckpoint, Cn as getTerminalAssistantMessages, H as PluginCredentialFailureError, K as AuthorizationFlowDisabledError, Lo as FORK_INSTRUCTIONS, Ro as loadForkHistory, Un as escapeClosingTags, X as clearPendingAuth, _o as createPluginLogger, at as failTurnRecord, et as lostWorkerBeforeFirstSave, fn as NO_REPLY_TOOL_NAME, fr as getPlugins, in as REPLY_TOOL_NAME, j as markConversationMessage, nt as saveTurnCheckpoint, on as readTurnAnswer, qn as renderTag, rn as isTurnExecutionLimitExceededError, rt as abandonTurnRecord, s as openConversationProjection, st as getTurnRecord, tt as pauseLostWorkerTurn, un as getAssistantReplyText, v as hydrateConversationMessages, vn as REPORT_BLOCKED_TOOL_NAME, yi as listWatches, ys as createPluginCache } from "./projection-CQNDOi82.js";
3
- import { D as resolveGatewayModel, _ as TURN_REASONING_LEVELS, i as getChatConfig, n as botConfig, q as isProviderRetryError } from "./config-CmjhyqgB.js";
4
- import { E as withSpan, h as logWarn, m as logInfo, x as setSpanStatus } from "./logging-DcjLDDqi.js";
5
- import { o as isUserActor } from "./actor-D2iXzvlN.js";
6
- import { C as isPersonInput, D as conversationKindFromRow, E as turnBehavior, a as getConversationStore, et as rootConversationIsArchived, j as SYSTEM_IDENTITY_ID, o as getDb, r as getConversationEventStore, s as getSqlExecutor, w as isTopLevelKind, y as userMessageQueries } from "./db-Czra10QW.js";
7
- import { g as juniorAgentInvocations, h as juniorAgentBindings, j as juniorConversations, w as juniorConversationEvents } from "./executor-D_023K0H.js";
8
- import { d as contextProvenance, m as sameActorIdentity, u as agentInstructionProvenance } from "./history-IjdmO_r6.js";
9
- import { r as getStateAdapter } from "./adapter-CNjGEJO9.js";
10
- import { p as credentialContextSchema } from "./registry-Dj377ADs.js";
11
- import { u as completeText } from "./prompt-DLUB5m72.js";
12
- import { A as agentTypeInstructions, j as agentTypeSchema } from "./conversation-BNXfq6Lb.js";
13
- import { C as getAuthPausedConversationTurnId, E as listActiveMailboxTurns, F as isEventMailboxMetadata, T as listActiveMailboxTurnSources, X as maybePostAutomatedTurnLimitNotice, at as conversationSubtree, ct as systemPromptHash, f as buildSteeringPiMessage, g as withoutSavedSteeringMessages, i as resumeStoppedConversationTree, it as resetAutomatedTurnLimit, m as instructionForInputs, n as isSkippedAfterConversationStop, ot as conversationSubtreeColumns, r as markConversationsStopped, rt as recordFinishedTurnForAutomatedLimit, st as buildDeploymentSystemPrompt, t as getConversationStoppedAtMs } from "./session-stop-BLmfFI3d.js";
14
- import { T as getTurnRequestDeadline, b as sendCacheWarmup, l as getVercelConversationWorkQueue } from "./background-compaction-queue-CNrZ3QcU.js";
15
- import { A as getAgentInvocationResultMessageId, C as ownAgentInvocation, I as getUnnamedAgentConversationId, N as getChildAgentLockName, O as getAgentInvocationIdForResult, P as getNamedAgentConversationId, R as buildDeterministicTurnId, S as listChildMessages, T as getAgentInvocationId, _ as ConversationTurnLifecycleService, b as hasAgentInvocationReply, d as isTurnInputCommitLostError, j as getAgentInvocationTurnId, k as getAgentInvocationMessageId, l as getConversationTurnBoundaryError, p as markTurnClosed, s as TurnInputCommitLostError, t as getTurnUserMessage, w as readChildMessageSender } from "./turn-user-message-DsUZi9gn.js";
16
- import { D as stopConversationWork, _ as getConversationWorkState, h as ensureConversationWake, m as dropPendingMessages, r as appendAndEnqueueInboundMessage, v as getConversationWorkStates, w as requestConversationWork } from "./store-DmV4CoNr.js";
17
- import { a as getPersistedThreadState, c as coerceThreadConversationState, i as getPersistedSandboxState, n as resolveTurnSessionRouting, s as persistThreadStateById } from "./turn-session-routing-BD3-jJl7.js";
18
- import { C as isAgentInvocationResultEventType, b as AGENT_PARENT_MESSAGE_EVENT_TYPE, n as AGENT_INVOCATION_PARENT_MAILBOX_STATUSES, t as AGENT_INVOCATION_MAILBOX_STATUSES, v as AGENT_INVOCATION_EVENT_NAMESPACE } from "./statuses-Hn-HsOph.js";
19
- import * as z from "zod";
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 { and, asc, desc, eq, exists, gt, inArray, isNotNull, ne, notExists, or, sql } from "drizzle-orm";
24
- import { actorSchema, destinationSchema, sourceSchema } from "@sentry/junior-plugin-api";
25
- import { alias } from "drizzle-orm/pg-core";
26
- import pLimit from "p-limit";
27
- import { constants, zstdCompress, zstdDecompress } from "node:zlib";
28
- // src/chat/cache-warming/model.ts
29
- /**
30
- * Cost model for prompt cache warming.
31
- *
32
- * Ported from Lore's cache warmer (BYK/loreai,
33
- * `packages/gateway/src/cache-warmer.ts`). The model estimates the chance that
34
- * a person returns to an idle conversation before the cache expires. It then
35
- * compares that chance with the cost of one more warmup.
36
- */
37
- /** One minute in milliseconds. */
38
- const MINUTE_MS = 6e4;
39
- /** Upper edges (ms) of the gap histogram bins. */
40
- const GAP_BIN_EDGES_MS = [
41
- 1e4,
42
- 2e4,
43
- 3e4,
44
- 45e3,
45
- MINUTE_MS,
46
- 1.5 * MINUTE_MS,
47
- 2 * MINUTE_MS,
48
- 3 * MINUTE_MS,
49
- 4 * MINUTE_MS,
50
- 5 * MINUTE_MS,
51
- 7 * MINUTE_MS,
52
- 10 * MINUTE_MS,
53
- 15 * MINUTE_MS,
54
- 20 * MINUTE_MS,
55
- 30 * MINUTE_MS,
56
- 45 * MINUTE_MS,
57
- 60 * MINUTE_MS,
58
- 90 * MINUTE_MS,
59
- 120 * MINUTE_MS,
60
- 240 * MINUTE_MS,
61
- Infinity
62
- ];
63
- const GAP_BIN_COUNT = GAP_BIN_EDGES_MS.length;
64
- /**
65
- * Gaps that a segment needs before its gaps replace its parent segment's
66
- * gaps (`parentGapSegment`, or the segment of a `waitingGapSegment`). A new
67
- * or rare segment starts with its parent's return chances, so it can warm
68
- * before it has gaps of its own.
69
- */
70
- const BLEND_PSEUDOCOUNT = 20;
71
- /**
72
- * Gaps that a Conversation needs before its gaps replace its segment's gaps.
73
- * One Conversation has few gaps, and a few unusual replies say little about
74
- * its next one. A backtest of time-ordered decisions showed that a weight
75
- * this slow predicts returns better than both a faster weight and no
76
- * Conversation weight at all.
77
- */
78
- const CONVERSATION_BLEND_PSEUDOCOUNT = 100;
79
- /** Below this prefix size, one cache miss costs too little to warm for. */
80
- const MIN_WARMUP_PREFIX_TOKENS = 5e4;
81
- /**
82
- * Junior watches an idle period for this long. A person who replies later
83
- * counts as a person who did not reply. The reply chance of a warmup counts
84
- * only replies before this time. For a cache that outlives the horizon, this
85
- * is less than the real chance, so Junior warms less, never more.
86
- *
87
- * The horizon message is signed when the idle period starts, and a queue
88
- * signature is valid for 60 minutes (`QUEUE_SIGNATURE_MAX_AGE_MS`). The other
89
- * 5 minutes let a late horizon still record its no-reply gap.
90
- */
91
- const IDLE_HORIZON_MS = 55 * MINUTE_MS;
92
- /**
93
- * Whether a failed warmup request counts as a miss for the provider breaker.
94
- * A request that the provider rejects fails the same way for each
95
- * Conversation, so it counts. A retryable failure, such as an overload or a
96
- * timeout, says nothing about the cache, so it must not stop warming for
97
- * every Conversation.
98
- */
99
- function warmupFailureCountsAsMiss(error) {
100
- return !isProviderRetryError(error);
101
- }
102
- /**
103
- * Time from a timer's due time to the request of its Turn: the heartbeat
104
- * fires due timers once a minute, and the Turn then starts.
105
- */
106
- const TIMER_START_DELAY_MS = 2 * MINUTE_MS;
107
- /**
108
- * Latest timer due time, as idle time, that the timer floor warms for. A
109
- * warmup costs one cache read, and a miss costs one write minus one read, so
110
- * the floor sends fewer warmups than the miss costs in reads. The cache of
111
- * the last warmup must last until the timer's Turn starts. A later timer
112
- * changes nothing: warming for it costs more than it saves.
113
- */
114
- function timerFloorMaxDueIdleMs(prices) {
115
- const savedPerReturn = prices.cacheWritePrice - prices.cacheReadPrice;
116
- if (prices.cacheReadPrice <= 0 || savedPerReturn <= 0) return 0;
117
- const maxWarmups = Math.ceil(savedPerReturn / prices.cacheReadPrice) - 1;
118
- return prices.cacheTtlMs + maxWarmups * (prices.cacheTtlMs - WARMUP_MARGIN_MS) - TIMER_START_DELAY_MS;
119
- }
120
- /** Gap that Junior records for an idle period with no reply in the horizon. */
121
- const NO_REPLY_GAP_MS = 1440 * MINUTE_MS;
122
- function binIndex(gapMs) {
123
- return GAP_BIN_EDGES_MS.findIndex((edge) => gapMs < edge);
124
- }
125
- function histogramOf(gapsMs) {
126
- const counts = Array.from({ length: GAP_BIN_COUNT }, () => 0);
127
- for (const gap of gapsMs) counts[binIndex(gap)] += 1;
128
- return {
129
- counts,
130
- total: gapsMs.length
131
- };
132
- }
133
- function blendHistograms(own, prior, pseudocount) {
134
- if (own.total === 0 || prior.total === 0) return own.total === 0 ? prior : own;
135
- const weight = Math.min(own.total / pseudocount, 1);
136
- return {
137
- counts: own.counts.map((count, index) => weight * count / own.total + (1 - weight) * prior.counts[index] / prior.total),
138
- total: 1
139
- };
140
- }
141
- function survival(histogram, tMs) {
142
- if (histogram.total === 0) return 1;
143
- const index = binIndex(tMs);
144
- let surviving = 0;
145
- for (let i = index + 1; i < GAP_BIN_COUNT; i++) surviving += histogram.counts[i];
146
- const binStart = index > 0 ? GAP_BIN_EDGES_MS[index - 1] : 0;
147
- const fractionPast = Math.min(1, Math.max(0, (tMs - binStart) / (GAP_BIN_EDGES_MS[index] - binStart)));
148
- surviving += histogram.counts[index] * (1 - fractionPast);
149
- return surviving / histogram.total;
150
- }
151
- function returnProbability(histogram, idleMs, windowMs) {
152
- const now = survival(histogram, idleMs);
153
- if (now < .001) return 0;
154
- return Math.max(0, (now - survival(histogram, idleMs + windowMs)) / now);
155
- }
156
- /**
157
- * How long before cache expiry Junior sends a warmup. A warmup reads each
158
- * cache block of the prefix in one request, so the provider refreshes all
159
- * blocks together. A margin that grows with the prefix size gains nothing.
160
- * The margin covers only the queue delay and the time of the warmup request.
161
- */
162
- const WARMUP_MARGIN_MS = 45e3;
163
- /**
164
- * Pick the gap histogram for an idle period. Return chances differ most by
165
- * who started the Turn and by how many Turns the Conversation had before it.
166
- * Turns that no person started rarely get a quick reply. In 30 days of
167
- * production data, segments by these two keys saved more than one histogram.
168
- * Local time of day did not improve the result, so it is not a key.
169
- *
170
- * The work state lets the histograms learn how often anything returns after
171
- * the work is done. An event does not restore an archived Conversation, so
172
- * most returns to one are events, not people. Its segment has only the work
173
- * state, which keeps the number of segments small.
174
- */
175
- function gapSegment(input) {
176
- if (input.archived) return `archived:${input.workState}`;
177
- const depth = input.endedTurns === 0 ? "1" : input.endedTurns < 3 ? "2-3" : "4+";
178
- return `${input.userActor ? "user" : "system"}:${depth}:${input.workState}`;
179
- }
180
- /** Each segment that `gapSegment` returns, in display order. */
181
- const GAP_SEGMENTS = [...[true, false].flatMap((userActor) => [
182
- 0,
183
- 1,
184
- 3
185
- ].flatMap((endedTurns) => [
186
- "open",
187
- "done",
188
- "none"
189
- ].map((workState) => gapSegment({
190
- userActor,
191
- endedTurns,
192
- workState,
193
- archived: false
194
- })))), ...[
195
- "open",
196
- "done",
197
- "none"
198
- ].map((workState) => gapSegment({
199
- userActor: false,
200
- endedTurns: 0,
201
- workState,
202
- archived: true
203
- }))];
204
- /**
205
- * Count gaps in the bins that `decideWarmup` uses, for reports. A gap at or
206
- * after `IDLE_HORIZON_MS` is a no-reply gap, as the recorder stores it. The
207
- * bins after the horizon never get a gap, so they are left out.
208
- */
209
- function gapHistogramReport(gapsMs) {
210
- const { counts } = histogramOf(gapsMs.filter((gapMs) => gapMs < IDLE_HORIZON_MS));
211
- const bins = [];
212
- for (const [index, endMs] of GAP_BIN_EDGES_MS.entries()) {
213
- const startMs = index > 0 ? GAP_BIN_EDGES_MS[index - 1] : 0;
214
- if (startMs >= 33e5) break;
215
- bins.push({
216
- startMs,
217
- endMs: Math.min(endMs, IDLE_HORIZON_MS),
218
- count: counts[index]
219
- });
220
- }
221
- return {
222
- bins,
223
- noReply: gapsMs.filter((gapMs) => gapMs >= IDLE_HORIZON_MS).length,
224
- total: gapsMs.length
225
- };
226
- }
227
- /**
228
- * Segment whose gaps a thin segment leans on: the `none` segment with the
229
- * same Actor and Turn depth. The backfill and most traffic keep the `none`
230
- * segments full. A `none` segment that is not archived has no parent.
231
- */
232
- function parentGapSegment(input) {
233
- if (!input.archived && input.workState === "none") return void 0;
234
- return gapSegment({
235
- ...input,
236
- workState: "none",
237
- archived: false
238
- });
239
- }
240
- const WAITING_SEGMENT_SUFFIXES = {
241
- child: "child",
242
- review: "review",
243
- watch: "automation"
244
- };
245
- /**
246
- * Child of a segment for an idle period that waits on a child agent, a
247
- * Review item, or a Watch (`:automation`). Its parent is the segment, so a
248
- * thin child leans on the segment, and a thin segment on its own parent.
249
- */
250
- function waitingGapSegment(segment, waitingOn) {
251
- return `${segment}:${WAITING_SEGMENT_SUFFIXES[waitingOn]}`;
252
- }
253
- /** Whether a segment has too few gaps to stand without its parent. */
254
- function segmentNeedsParent(segmentGaps) {
255
- return segmentGaps < BLEND_PSEUDOCOUNT;
256
- }
257
- /**
258
- * Decide whether to send the next warmup.
259
- *
260
- * A warmup costs one cache read of the prefix. A return to a warm cache saves
261
- * one write minus one read. So warming pays when the expected returns per
262
- * warmup are above read/(write − read). Earlier warmups are already paid, so
263
- * the threshold is the same for each warmup.
264
- *
265
- * One warmup alone can be useless when people return a little after the next
266
- * TTL, while two or three warmups in a row would reach them. So the decision
267
- * compares plans of 1, 2, ... warmups up to the horizon. Each plan sends its
268
- * next warmup only while nobody returned. Junior warms when the best plan
269
- * pays, and decides again at the next warmup.
270
- *
271
- * The timer floor: while the cache would expire before a timer's Turn
272
- * starts, Junior warms even when no plan pays and after the horizon (reason
273
- * `timer`). The timer's Turn then reads the cache. The floor only adds
274
- * warmups, so it never warms less than the decision without a timer.
275
- */
276
- function decideWarmup(input) {
277
- const savedPerReturn = input.cacheWritePrice - input.cacheReadPrice;
278
- const threshold = savedPerReturn > 0 ? Math.min(input.cacheReadPrice / savedPerReturn, 1) : 1;
279
- const conversation = histogramOf(input.conversationGapsMs);
280
- const segments = [histogramOf(input.globalGapsMs)];
281
- for (const gapsMs of input.priorGapsMs ?? []) {
282
- if (!segmentNeedsParent(segments.at(-1).total)) break;
283
- segments.push(histogramOf(gapsMs));
284
- }
285
- const segmentGaps = segments.reduce((sum, list) => sum + list.total, 0);
286
- const histogram = blendHistograms(conversation, segments.reduceRight((prior, own) => blendHistograms(own, prior, BLEND_PSEUDOCOUNT)), CONVERSATION_BLEND_PSEUDOCOUNT);
287
- const probability = returnProbability(histogram, input.idleMs, Math.min(input.cacheTtlMs, IDLE_HORIZON_MS - input.idleMs));
288
- const perWarmup = returnsPerWarmup(histogram, input.idleMs, input.cacheExpiryIdleMs, input.cacheTtlMs);
289
- const decision = (reason) => ({
290
- warm: reason === "warm" || reason === "timer",
291
- reason,
292
- returnProbability: probability,
293
- returnsPerWarmup: perWarmup,
294
- threshold,
295
- parentPrior: segmentGaps > segments[0].total
296
- });
297
- if (input.prefixTokens < 5e4) return decision("prefix_too_small");
298
- if (threshold >= 1) return decision("no_savings");
299
- const timerFloor = input.timerDueIdleMs !== void 0 && input.cacheExpiryIdleMs < input.timerDueIdleMs + 12e4;
300
- const reason = input.idleMs >= 33e5 ? "horizon" : conversation.total + segmentGaps < 20 ? "few_gaps" : perWarmup >= threshold ? "warm" : "unlikely_return";
301
- return decision(reason !== "warm" && timerFloor ? "timer" : reason);
302
- }
303
- function returnsPerWarmup(histogram, idleMs, cacheExpiryIdleMs, ttlMs) {
304
- const now = survival(histogram, idleMs);
305
- const intervalMs = ttlMs - WARMUP_MARGIN_MS;
306
- if (now < .001 || intervalMs <= 0) return 0;
307
- const leftAtExpiry = survival(histogram, Math.min(cacheExpiryIdleMs, IDLE_HORIZON_MS));
308
- let best = 0;
309
- let warmups = 0;
310
- for (let startMs = idleMs; startMs < IDLE_HORIZON_MS; startMs += intervalMs) {
311
- warmups += survival(histogram, startMs) / now;
312
- const endMs = Math.min(startMs + ttlMs, IDLE_HORIZON_MS);
313
- const returns = Math.max(0, leftAtExpiry - survival(histogram, endMs)) / now;
314
- best = Math.max(best, returns / warmups);
315
- }
316
- return best;
317
- }
318
- // src/chat/cache-warming/request.ts
319
- const KEY_PREFIX = "junior:cache_warming";
320
- const CACHE_RETENTION = "short";
321
- const REFRESHED_READ_FRACTION = .9;
322
- const BREAKER_OUTCOMES_MAX = 20;
323
- const BREAKER_MAX_MISSES = 10;
324
- const BREAKER_OUTCOMES_TTL_MS = 360 * MINUTE_MS;
325
- const BREAKER_OPEN_TTL_MS = 30 * MINUTE_MS;
326
- const breakerOutcomesKey = (provider) => `${KEY_PREFIX}:breaker:${provider}:outcomes`;
327
- const breakerOpenKey = (provider) => `${KEY_PREFIX}:breaker:${provider}:open`;
328
- const providerOf = (modelId) => modelId.split("/")[0] ?? "";
329
- /** Connect the state adapter that holds cache warming state. */
330
- async function connectedState() {
331
- const state = getStateAdapter();
332
- await state.connect();
333
- return state;
334
- }
335
- const CACHE_TTL_MS = {
336
- anthropic: 5 * MINUTE_MS,
337
- alibaba: 5 * MINUTE_MS,
338
- openai: 30 * MINUTE_MS
339
- };
340
- /**
341
- * Return true when warmups can refresh the prompt cache of this request.
342
- * Warming pays only when a cache write costs more than a read. Pi adds a
343
- * thinking budget to the one-token output limit on the Anthropic Messages API
344
- * for models without adaptive thinking. Then a warmup could cost as much as a
345
- * short answer, and a smaller budget would miss the cached messages.
346
- */
347
- function supportsWarming(request) {
348
- const { model, reasoning } = request;
349
- const budgetThinking = reasoning !== void 0 && model.api === "anthropic-messages" && model.compat?.forceAdaptiveThinking !== true;
350
- return CACHE_TTL_MS[providerOf(model.id)] !== void 0 && model.cost.cacheRead > 0 && model.cost.cacheWrite > model.cost.cacheRead && !budgetThinking && request.cacheRetention === "short";
351
- }
352
- /** Return the cache TTL of a request that Junior can warm. */
353
- function cacheTtlMs(request) {
354
- return supportsWarming(request) ? CACHE_TTL_MS[providerOf(request.model.id)] : void 0;
355
- }
356
- /** Return the cached prefix tokens of a finished model request. */
357
- function cachedPrefixTokens(message) {
358
- return message.usage.cacheRead + message.usage.cacheWrite;
359
- }
360
- /**
361
- * Return when the cache that a request at `requestStartedAtMs` read or wrote
362
- * expires, and the delay until the warmup that refreshes it.
363
- */
364
- function warmupTiming(requestStartedAtMs, ttlMs) {
365
- const cacheExpiresAtMs = requestStartedAtMs + ttlMs;
366
- return {
367
- cacheExpiresAtMs,
368
- delayMs: cacheExpiresAtMs - WARMUP_MARGIN_MS - Date.now()
369
- };
370
- }
371
- const LATE_WARMUP_MS = 1e4;
372
- /**
373
- * Return true when a warmup is too late to refresh the cache. The cache is
374
- * gone, so the warmup must not run or count as a miss.
375
- */
376
- function warmupTooLate(cacheExpiresAtMs) {
377
- return Date.now() + LATE_WARMUP_MS >= cacheExpiresAtMs;
378
- }
379
- /**
380
- * Return true while too many recent warmups of the model's provider missed,
381
- * so its warming is off.
382
- */
383
- async function breakerOpen(state, modelId) {
384
- return await state.get(breakerOpenKey(providerOf(modelId))) === true;
385
- }
386
- /** Report whether each warmed provider's breaker is open. */
387
- async function breakerStates(state) {
388
- return Promise.all(Object.keys(CACHE_TTL_MS).map(async (provider) => ({
389
- provider,
390
- open: await state.get(breakerOpenKey(provider)) === true
391
- })));
392
- }
393
- /**
394
- * Close a provider's breaker so warming starts again, and forget its recent
395
- * outcomes so old misses cannot reopen it. Returns false for a provider that
396
- * is not warmed.
397
- */
398
- async function closeBreaker(state, provider) {
399
- if (!Object.hasOwn(CACHE_TTL_MS, provider)) return false;
400
- await state.delete(breakerOutcomesKey(provider));
401
- await state.delete(breakerOpenKey(provider));
402
- return true;
403
- }
404
- async function countOutcome(state, modelId, miss) {
405
- const provider = providerOf(modelId);
406
- if (await breakerOpen(state, modelId)) return;
407
- await state.appendToList(breakerOutcomesKey(provider), miss ? 1 : 0, {
408
- maxLength: BREAKER_OUTCOMES_MAX,
409
- ttlMs: BREAKER_OUTCOMES_TTL_MS
410
- });
411
- if (!miss) return;
412
- const outcomes = await state.getList(breakerOutcomesKey(provider));
413
- const misses = outcomes.filter((outcome) => outcome === 1).length;
414
- if (misses >= BREAKER_MAX_MISSES && await state.setIfNotExists(breakerOpenKey(provider), true, BREAKER_OPEN_TTL_MS)) {
415
- await state.delete(breakerOutcomesKey(provider));
416
- captureMessage("Cache warming stopped: too many warmups missed the cache", {
417
- level: "error",
418
- fingerprint: ["cache_warming.breaker.opened", provider],
419
- tags: { "gen_ai.request.model": modelId },
420
- extra: {
421
- "app.cache_warming.misses": misses,
422
- "app.cache_warming.outcomes": outcomes.length
423
- }
424
- });
425
- }
426
- }
427
- /**
428
- * Send one warmup: the same request with a one-token output limit. Count its
429
- * outcome for the breaker, and report a miss to Sentry. A rejected request
430
- * counts as a miss and rethrows, because it fails the same way for each
431
- * Conversation.
432
- */
433
- async function sendWarmup(state, params) {
434
- const { conversationId, modelId, context, prefixTokens } = params;
435
- const { message: result } = await completeText({
436
- modelId,
437
- system: context.systemPrompt,
438
- messages: context.messages,
439
- ...context.tools ? { tools: context.tools } : void 0,
440
- ...params.reasoning ? { thinkingLevel: params.reasoning } : void 0,
441
- cacheRetention: CACHE_RETENTION,
442
- maxTokens: 1,
443
- messageAttributeMode: "metadata",
444
- metadata: { conversationId },
445
- operation: "cache_warmup",
446
- cost: { conversationId },
447
- sessionId: conversationId
448
- }).catch(async (error) => {
449
- if (warmupFailureCountsAsMiss(error)) await countOutcome(state, modelId, true);
450
- throw error;
451
- });
452
- const attributes = {
453
- "app.cost.total_usd": result.usage.cost.total,
454
- "gen_ai.usage.cache_read.input_tokens": result.usage.cacheRead,
455
- "gen_ai.usage.cache_creation.input_tokens": result.usage.cacheWrite
456
- };
457
- const refreshed = result.usage.cacheRead >= prefixTokens * REFRESHED_READ_FRACTION;
458
- if (!refreshed) captureMessage("Cache warmup missed the cache", {
459
- level: "warning",
460
- fingerprint: ["cache_warming.warmup.missed", modelId],
461
- tags: { "gen_ai.request.model": modelId },
462
- extra: { "app.cache_warming.read_fraction": result.usage.cacheRead / prefixTokens }
463
- });
464
- await countOutcome(state, modelId, !refreshed);
465
- return {
466
- refreshed,
467
- attributes
468
- };
469
- }
470
- // src/chat/cache-warming/snapshot.ts
471
- /**
472
- * Storage format of the idle-period snapshot: the exact Pi context of the
473
- * request that ended a Turn, which each idle warmup sends again.
474
- *
475
- * Base64 image data does not compress, so one screenshot can make a snapshot
476
- * too large to store. The data of each image part moves to its own state key,
477
- * named by its SHA-256 hash, and the snapshot keeps `sha256:<hash>` in its
478
- * place. Base64 has no `:`, so a reference cannot be image data.
479
- * The next Turn's snapshot often holds the same images, so it writes the same
480
- * keys again and refreshes their TTL. A loaded snapshot gets each image's
481
- * data back at the same JSON position, so the warmup request is the same as
482
- * the original request and reads its cached prefix. A snapshot with a missing
483
- * image does not load: a changed request would write a new cache entry.
484
- * Deleting a snapshot keeps its images, because the next snapshot of the
485
- * Conversation likely holds them. They expire with their TTL.
486
- * A snapshot whose images are over their own limit is not stored, so one
487
- * Conversation cannot keep an unbounded amount of image data in state.
488
- * Removing its images would change the request, so it would miss the cache.
489
- */
490
- const zstdCompress$1 = promisify(zstdCompress);
491
- const zstdDecompress$1 = promisify(zstdDecompress);
492
- const SNAPSHOT_ZSTD_PARAMS = { params: { [constants.ZSTD_c_compressionLevel]: 1 } };
493
- const MAX_SNAPSHOT_BYTES = 1048576;
494
- const MAX_SNAPSHOT_IMAGE_BYTES = 33554432;
495
- const IMAGE_REF_PREFIX = "sha256:";
496
- const imageKey = (conversationId, sha256) => `${KEY_PREFIX}:image:${conversationId}:${sha256}`;
497
- function imageParts(message) {
498
- if (message.role === "assistant" || typeof message.content === "string") return [];
499
- const images = [];
500
- for (const part of message.content) if (part.type === "image") images.push(part);
501
- return images;
502
- }
503
- function snapshotContext(context, toRef) {
504
- return {
505
- ...context.systemPrompt !== void 0 ? { systemPrompt: context.systemPrompt } : void 0,
506
- messages: context.messages.map((message) => message.role === "assistant" || typeof message.content === "string" ? message : {
507
- ...message,
508
- content: message.content.map(toRef)
509
- }),
510
- ...context.tools ? { tools: context.tools.map((tool) => ({
511
- name: tool.name,
512
- description: tool.description,
513
- parameters: tool.parameters,
514
- ...tool.constrainedSampling !== void 0 ? { constrainedSampling: tool.constrainedSampling } : void 0
515
- })) } : void 0
516
- };
517
- }
518
- /**
519
- * Store the snapshot of a request context with its images under hash keys.
520
- * Stores nothing and returns a `skipReason` when the snapshot without its
521
- * images or the images are over their limit. Every key expires after `ttlMs`.
522
- */
523
- async function saveSnapshot(state, conversationId, key, context, ttlMs) {
524
- const images = /* @__PURE__ */ new Map();
525
- const toRef = (part) => {
526
- if (part.type !== "image") return part;
527
- const sha256 = createHash("sha256").update(part.data).digest("hex");
528
- images.set(sha256, part.data);
529
- return {
530
- ...part,
531
- data: `${IMAGE_REF_PREFIX}${sha256}`
532
- };
533
- };
534
- const snapshot = (await zstdCompress$1(JSON.stringify(snapshotContext(context, toRef)), SNAPSHOT_ZSTD_PARAMS)).toString("base64");
535
- const size = {
536
- bytes: snapshot.length,
537
- imageCount: images.size,
538
- imageBytes: [...images.values()].reduce((sum, data) => sum + data.length, 0)
539
- };
540
- if (size.bytes > MAX_SNAPSHOT_BYTES) return {
541
- ...size,
542
- skipReason: "snapshot_too_large"
543
- };
544
- if (size.imageBytes > MAX_SNAPSHOT_IMAGE_BYTES) return {
545
- ...size,
546
- skipReason: "images_too_large"
547
- };
548
- await state.set(key, snapshot, ttlMs);
549
- await Promise.all([...images].map(([sha256, data]) => state.set(imageKey(conversationId, sha256), data, ttlMs)));
550
- return size;
551
- }
552
- /**
553
- * Load a stored snapshot with its image data. Returns `stopped` when the
554
- * snapshot is gone and `image_missing` when one of its images is gone.
555
- */
556
- async function loadSnapshot(state, conversationId, key) {
557
- const snapshot = await state.get(key);
558
- if (!snapshot) return "stopped";
559
- const context = JSON.parse((await zstdDecompress$1(Buffer.from(snapshot, "base64"))).toString("utf8"));
560
- for (const part of context.messages.flatMap(imageParts)) {
561
- if (!part.data.startsWith(IMAGE_REF_PREFIX)) continue;
562
- const sha256 = part.data.slice(7);
563
- const data = await state.get(imageKey(conversationId, sha256));
564
- if (data === null) return "image_missing";
565
- part.data = data;
566
- }
567
- return context;
568
- }
569
- // src/chat/cache-warming/tool-wait.ts
570
- const TOOL_WAIT_GAPS_KEY = `${KEY_PREFIX}:gaps:tool_wait`;
571
- const TOOL_WAIT_GAPS_MAX = 2e3;
572
- const TOOL_WAIT_GAPS_TTL_MS = 43200 * MINUTE_MS;
573
- const MIN_RECORDED_TOOL_WAIT_MS = 2 * MINUTE_MS;
574
- /** Create the tool wait warmer of one agent run. */
575
- function createToolWaitWarmer(conversationId) {
576
- let timer;
577
- let waiting;
578
- let returnedAtMs;
579
- let generation = 0;
580
- const schedule = (cache, refreshedAtMs, cycle) => {
581
- const current = generation;
582
- const { cacheExpiresAtMs, delayMs } = warmupTiming(refreshedAtMs, cache.ttlMs);
583
- timer = setTimeout(() => {
584
- timer = void 0;
585
- warm(cache, cacheExpiresAtMs, cycle, current);
586
- }, Math.max(0, delayMs));
587
- timer.unref?.();
588
- };
589
- const warm = (cache, cacheExpiresAtMs, cycle, current) => {
590
- const { request, prefixTokens } = cache;
591
- const attributes = {
592
- "app.cache_warming.cycle": cycle,
593
- "app.cache_warming.prefix_tokens": prefixTokens,
594
- "app.cache_warming.trigger": "tool_wait"
595
- };
596
- return withSpan("cache_warming.warmup", "cache_warming.warmup", {
597
- conversationId,
598
- modelId: request.model.id
599
- }, async (setSpanAttributes) => {
600
- const setOutcome = (outcome, extra = {}) => setSpanAttributes({
601
- ...attributes,
602
- ...extra,
603
- "app.cache_warming.outcome": outcome
604
- });
605
- const skip = (reason) => {
606
- const skipReason = { "app.cache_warming.skip_reason": reason };
607
- logInfo("cache_warming.warmup.skipped", {
608
- ...attributes,
609
- ...skipReason
610
- });
611
- setOutcome("skipped", skipReason);
612
- };
613
- if (warmupTooLate(cacheExpiresAtMs)) {
614
- skip("cache_expired");
615
- return;
616
- }
617
- try {
618
- const state = await connectedState();
619
- if (await breakerOpen(state, request.model.id)) {
620
- skip("breaker_open");
621
- return;
622
- }
623
- const decision = decideWarmup({
624
- conversationGapsMs: [],
625
- globalGapsMs: await state.getList(TOOL_WAIT_GAPS_KEY),
626
- idleMs: Date.now() - request.startedAtMs,
627
- cacheExpiryIdleMs: cacheExpiresAtMs - request.startedAtMs,
628
- cacheTtlMs: cache.ttlMs,
629
- prefixTokens,
630
- cacheReadPrice: request.model.cost.cacheRead,
631
- cacheWritePrice: request.model.cost.cacheWrite
632
- });
633
- attributes["app.cache_warming.return_probability"] = decision.returnProbability;
634
- attributes["app.cache_warming.returns_per_warmup"] = decision.returnsPerWarmup;
635
- attributes["app.cache_warming.threshold"] = decision.threshold;
636
- if (current !== generation) {
637
- setOutcome("skipped", { "app.cache_warming.skip_reason": "stopped" });
638
- return;
639
- }
640
- if (!decision.warm) {
641
- skip(decision.reason);
642
- return;
643
- }
644
- const startedAtMs = Date.now();
645
- const warmup = await sendWarmup(state, {
646
- conversationId,
647
- modelId: request.model.id,
648
- context: request.context,
649
- ...request.reasoning ? { reasoning: request.reasoning } : void 0,
650
- prefixTokens
651
- });
652
- Object.assign(attributes, warmup.attributes);
653
- if (!warmup.refreshed) {
654
- logWarn("cache_warming.warmup.failed", attributes);
655
- setOutcome("missed");
656
- return;
657
- }
658
- logInfo("cache_warming.warmup.completed", attributes);
659
- setOutcome("completed");
660
- if (current === generation) schedule(cache, startedAtMs, cycle + 1);
661
- } catch (error) {
662
- logWarn("cache_warming.warmup.failed", {
663
- ...attributes,
664
- "exception.message": error instanceof Error ? error.message : String(error)
665
- });
666
- setOutcome("failed", { "error.type": error instanceof Error ? error.name : typeof error });
667
- setSpanStatus("error");
668
- }
669
- }, attributes);
670
- };
671
- const stop = () => {
672
- generation += 1;
673
- clearTimeout(timer);
674
- timer = void 0;
675
- };
676
- const recordWait = async (waitMs) => {
677
- if (waitMs < MIN_RECORDED_TOOL_WAIT_MS) return;
678
- await (await connectedState()).appendToList(TOOL_WAIT_GAPS_KEY, waitMs, {
679
- maxLength: TOOL_WAIT_GAPS_MAX,
680
- ttlMs: TOOL_WAIT_GAPS_TTL_MS
681
- });
682
- };
683
- return {
684
- async record(request, message) {
685
- stop();
686
- const previous = waiting;
687
- waiting = message.stopReason === "toolUse" ? request : void 0;
688
- returnedAtMs = void 0;
689
- const prefixTokens = cachedPrefixTokens(message);
690
- const ttlMs = cacheTtlMs(request);
691
- if (waiting && prefixTokens >= 5e4 && ttlMs !== void 0) schedule({
692
- request,
693
- prefixTokens,
694
- ttlMs
695
- }, request.startedAtMs, 1);
696
- if (previous) await recordWait(request.startedAtMs - previous.startedAtMs);
697
- },
698
- stop,
699
- toolsReturned() {
700
- stop();
701
- if (waiting) returnedAtMs ??= Date.now();
702
- },
703
- async end() {
704
- stop();
705
- const open = waiting;
706
- const returned = returnedAtMs;
707
- waiting = void 0;
708
- returnedAtMs = void 0;
709
- if (!open) return;
710
- if (returned !== void 0) {
711
- await recordWait(returned - open.startedAtMs);
712
- return;
713
- }
714
- if (Date.now() - open.startedAtMs >= MIN_RECORDED_TOOL_WAIT_MS) await recordWait(NO_REPLY_GAP_MS);
715
- }
716
- };
717
- }
718
- // src/chat/conversations/agent-config.ts
719
- /**
720
- * The agent settings that every Turn of one Conversation keeps, for any
721
- * kind: its Agent type, its reasoning level, and whether it started with its
722
- * parent's history. A kind sets only the fields that apply to it.
723
- */
724
- const agentConfigSchema = z.object({
725
- agentType: agentTypeSchema.optional(),
726
- fork: z.literal(true).optional(),
727
- reasoningLevel: z.enum(TURN_REASONING_LEVELS).optional()
728
- }).strict();
729
- /**
730
- * Read the agent config that one Conversation stores, or undefined when it
731
- * stores none. Today only a child that a spawn created without an Agent
732
- * invocation row stores one. A child that an Agent invocation names reads
733
- * its settings from its row first.
734
- */
735
- async function readAgentConfig(conversationId) {
736
- const [row] = await getSqlExecutor().db().select({ agentConfig: juniorConversations.agentConfig }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId));
737
- return row?.agentConfig ? agentConfigSchema.parse(row.agentConfig) : void 0;
738
- }
739
- // src/chat/runtime/turn-execution.ts
740
- /** An error thrown while the agent advances a Run. */
741
- var AgentRunError = class extends Error {
742
- constructor(cause) {
743
- super(cause instanceof Error ? cause.message : "Agent Run failed", { cause });
744
- this.name = "AgentRunError";
745
- }
746
- };
747
- /**
748
- * Run the agent and finish the Turn after the caller saves its result.
749
- *
750
- * A paused Run, or a Run waiting for authorization, leaves the Turn open. A
751
- * save error also leaves the Turn open so the worker can retry or recover it.
752
- */
753
- async function executeTurn(agentRunner, run, saveResult) {
754
- let outcome;
755
- try {
756
- outcome = await agentRunner.run(run);
757
- } catch (error) {
758
- throw new AgentRunError(error);
759
- }
760
- if (outcome.status !== "completed") return outcome;
761
- const saved = await saveResult(outcome.result);
762
- await finishTurn(run.conversationId, run.turnId, saved);
763
- return { status: "completed" };
764
- }
765
- /** Record the terminal lifecycle event of a Turn from its saved result. */
766
- async function finishTurn(conversationId, turnId, saved) {
767
- const lifecycle = new ConversationTurnLifecycleService(getConversationEventStore());
768
- const common = {
769
- conversationId,
770
- createdAtMs: saved.finishedAtMs ?? Date.now(),
771
- turnId
772
- };
773
- if (saved.outcome === "failed") await lifecycle.fail({
774
- ...common,
775
- ...saved.eventId ? { eventId: saved.eventId } : void 0,
776
- failureCode: saved.failureCode,
777
- ...saved.failureReason ? { failureReason: saved.failureReason } : void 0
778
- });
779
- else await lifecycle.complete({
780
- ...common,
781
- outcome: saved.outcome
782
- });
783
- }
784
- // src/chat/conversations/web-authorization.ts
785
- const WEB_AUTHORIZATION_PREFIX = "junior:web_authorization:v1";
786
- const WEB_AUTHORIZATION_TTL_MS = 864e5;
787
- function authorizationKey$1(conversationId, actorId) {
788
- return `${WEB_AUTHORIZATION_PREFIX}:${conversationId}:${actorId}`;
789
- }
790
- /** Build authorization delivery for one web turn. */
791
- function createWebAuthorization(args) {
792
- return {
793
- createState: async () => randomUUID(),
794
- deliver: async (request) => {
795
- await getStateAdapter().set(authorizationKey$1(args.conversationId, args.actorId), JSON.stringify({
796
- ...request,
797
- ...args
798
- }), WEB_AUTHORIZATION_TTL_MS);
799
- }
800
- };
801
- }
802
- /** Read the pending authorization request for one web actor. */
803
- async function getWebAuthorization(args) {
804
- const value = await getStateAdapter().get(authorizationKey$1(args.conversationId, args.actorId));
805
- if (typeof value !== "string") return void 0;
806
- try {
807
- const parsed = JSON.parse(value);
808
- if (parsed.actorId !== args.actorId || parsed.conversationId !== args.conversationId || typeof parsed.authorizationUrl !== "string" || typeof parsed.label !== "string" || typeof parsed.completionText !== "string") return;
809
- return parsed;
810
- } catch {
811
- return;
812
- }
813
- }
814
- /** Remove a web authorization request after the parked turn continues. */
815
- async function deleteWebAuthorization(args) {
816
- await getStateAdapter().delete(authorizationKey$1(args.conversationId, args.actorId));
817
- }
818
- // src/chat/task-execution/attempt-selection.ts
819
- function inputOwner(message) {
820
- return {
821
- authorId: message.input.authorId,
822
- identityId: message.input.authorIdentityId,
823
- source: message.source
824
- };
825
- }
826
- function turnOwner(turn) {
827
- return {
828
- authorId: isUserActor(turn.actor) ? turn.actor.userId : void 0,
829
- identityId: turn.actorIdentityId,
830
- source: turn.source?.kind
831
- };
832
- }
833
- /**
834
- * One Turn has one Actor and one Source: it runs with that Actor's
835
- * credentials, so input from anyone else must not join it. Every value that
836
- * both sides know must match, and they must share an Identity id or an author
837
- * id. Input with no known author matches nothing.
838
- */
839
- function hasSameOwner(a, b) {
840
- if (a.source && b.source && a.source !== b.source) return false;
841
- const sameIdentity = a.identityId && b.identityId ? a.identityId === b.identityId : void 0;
842
- const sameAuthor = a.authorId && b.authorId ? a.authorId === b.authorId : void 0;
843
- return sameIdentity !== false && sameAuthor !== false && (sameIdentity ?? sameAuthor) === true;
844
- }
845
- /** True when two Inbound messages may share one Turn. */
846
- function canShareTurn(a, b) {
847
- return hasSameOwner(inputOwner(a), inputOwner(b));
848
- }
849
- /** True when an Inbound message may join `turn`. */
850
- function canJoinTurn(turn, message) {
851
- return hasSameOwner(turnOwner(turn), inputOwner(message));
852
- }
853
- function selectContiguousTurnBatch(messages) {
854
- const first = messages[0];
855
- if (!first) return [];
856
- const nextTurnIndex = messages.findIndex((message, index) => index > 0 && !canShareTurn(first, message));
857
- return messages.slice(0, nextTurnIndex === -1 ? messages.length : nextTurnIndex);
858
- }
859
- /**
860
- * True when an interrupt can start its own attempt.
861
- *
862
- * A steered web message must not start a second Turn while a yielded Turn
863
- * waits to resume. It stays pending for that Turn's drain or the next attempt.
864
- */
865
- function isAttemptInterrupt(message, work) {
866
- return message.delivery === "interrupt" && !(work.execution.status === "paused" && message.source === "web");
867
- }
868
- /** Prioritize interrupts while keeping each attempt to one Actor and Source. */
869
- function selectAttemptMessages(work) {
870
- const messages = work.messages;
871
- const interrupts = messages.filter((message) => isAttemptInterrupt(message, work));
872
- if (interrupts.length > 0) return selectContiguousTurnBatch(interrupts);
873
- if (work.execution.status === "paused") return [];
874
- const nonEventMessages = messages.filter((message) => message.source !== "event");
875
- return selectContiguousTurnBatch(nonEventMessages.length > 0 ? nonEventMessages : messages);
876
- }
877
- // src/chat/task-execution/authorized-turn.ts
878
- /**
879
- * OAuth callbacks save readiness, not agent history. The conversation worker
880
- * consumes this event under its lease before it resumes the paused Turn.
881
- */
882
- const authorizationSchema = z.object({
883
- kind: z.enum(["mcp", "plugin"]),
884
- provider: z.string().min(1),
885
- actorId: z.string().min(1),
886
- authorizationId: z.string().min(1),
887
- authSessionId: z.string().optional(),
888
- scope: z.string().optional(),
889
- configuration: z.record(z.string(), z.unknown()).optional(),
890
- toolChannelId: z.string().optional()
891
- });
892
- function authorizationKey(turn) {
893
- return `turn:${turn.turnId}:authorization:${turn.version}`;
894
- }
895
- /** Save authorization for this parked boundary without changing model history. */
896
- async function recordTurnAuthorization(args) {
897
- const turn = await getTurnRecord(args.conversationId, args.turnId);
898
- if (!turn || turn.state !== "paused" || turn.resumeReason !== "auth") return;
899
- await getConversationEventStore().append(args.conversationId, [{
900
- idempotencyKey: authorizationKey(turn),
901
- createdAtMs: Date.now(),
902
- data: {
903
- type: "structured_event",
904
- namespace: "junior",
905
- name: "turn_authorized",
906
- version: 1,
907
- turnId: turn.turnId,
908
- content: authorizationSchema.parse(args)
909
- }
910
- }], { activity: "preserve" });
911
- return {
912
- conversationId: args.conversationId,
913
- destination: args.destination,
914
- turnId: turn.turnId,
915
- expectedVersion: turn.version
916
- };
917
- }
918
- /** Read authorization for the exact pause; a later auth pause needs its own callback. */
919
- async function getTurnAuthorization(turn) {
920
- const event = await getConversationEventStore().loadByIdempotencyKey(turn.conversationId, authorizationKey(turn));
921
- if (event?.data.type !== "structured_event") return void 0;
922
- return authorizationSchema.parse(event.data.content);
923
- }
924
- // src/chat/task-execution/turn-wake.ts
925
- /** Build the worker input for a paused turn. */
926
- async function getPausedTurnRequest(args) {
927
- const turn = (await loadTurnCheckpoint({
928
- conversationId: args.conversationId,
929
- turnId: args.turnId
930
- })).record;
931
- if (!turn || turn.state !== "paused" || turn.resumeReason !== "timeout" && turn.resumeReason !== "yield" && turn.resumeReason !== "retry" && !(turn.resumeReason === "auth" && await getTurnAuthorization(turn)) || turn.resumeReason === "timeout" && turn.sliceId < 2) return;
932
- let routing;
933
- try {
934
- routing = await resolveTurnSessionRouting({
935
- conversationId: args.conversationId,
936
- conversationStore: args.conversationStore
937
- });
938
- } catch (error) {
939
- await failTurnRecord({
940
- conversationId: args.conversationId,
941
- expectedVersion: turn.version,
942
- turnId: args.turnId,
943
- errorMessage: error instanceof Error ? error.message : String(error)
944
- });
945
- return;
946
- }
947
- return {
948
- conversationId: args.conversationId,
949
- destination: routing.destination,
950
- turnId: args.turnId,
951
- expectedVersion: turn.version,
952
- traceContext: turn.traceContext
953
- };
954
- }
955
- /** Wake the conversation worker for a paused turn. */
956
- async function wakePausedTurn(request, options = {}) {
957
- const nowMs = options.nowMs ?? Date.now();
958
- const conversation = await (options.conversationStore ?? getConversationStore()).get({ conversationId: request.conversationId });
959
- await requestConversationWork({
960
- conversationId: request.conversationId,
961
- destination: conversation && !isTopLevelKind(conversation.kind) ? void 0 : request.destination,
962
- nowMs,
963
- state: options.state
964
- });
965
- const queue = options.queue ?? getVercelConversationWorkQueue();
966
- await ensureConversationWake({
967
- conversationId: request.conversationId,
968
- idempotencyKey: [
969
- "agent-continue",
970
- request.conversationId,
971
- request.turnId,
972
- request.expectedVersion,
973
- nowMs
974
- ].join(":"),
975
- nowMs,
976
- queue,
977
- state: options.state
978
- });
979
- }
980
- /** Create paused Turn operations for one app. */
981
- function createPausedTurns(options = {}) {
982
- return {
983
- get: (args) => getPausedTurnRequest({
984
- ...args,
985
- conversationStore: options.conversationStore
986
- }),
987
- wake: (request) => wakePausedTurn(request, options)
988
- };
989
- }
990
- /** Record completed authorization and wake the sole execution owner. */
991
- async function wakeAuthorizedTurn(args, queue) {
992
- const request = await recordTurnAuthorization(args);
993
- if (request) await wakePausedTurn(request, { queue });
994
- }
995
- // src/chat/task-execution/supersede-turns.ts
996
- /**
997
- * End every open mailbox Turn other than `keepTurnId`, so new input runs in
998
- * the only open Turn. New input starts only when no yielded Turn waits, so an
999
- * open Turn here waits for OAuth or was left open by a failed or stopped Run.
1000
- * The caller persists `conversation`. Returns false when `isStopped` turns
1001
- * true first.
1002
- */
1003
- async function supersedeOpenMailboxTurns(args) {
1004
- return await supersedeTurns({
1005
- ...args,
1006
- turns: (await listActiveMailboxTurns(args.conversationId)).filter((record) => record.turnId !== args.keepTurnId)
1007
- });
1008
- }
1009
- /**
1010
- * End open Turns that new input replaces. A late resume or OAuth callback
1011
- * for an ended Turn is a no-op. The caller persists `conversation`. Returns
1012
- * false when `isStopped` turns true first.
1013
- */
1014
- async function supersedeTurns(args) {
1015
- const pendingAuthorizationActorId = args.conversation.processing.pendingAuth?.actorId;
1016
- for (const stale of args.turns) {
1017
- if (args.isStopped?.()) return false;
1018
- await abandonTurnRecord({
1019
- conversationId: args.conversationId,
1020
- turnId: stale.turnId,
1021
- errorMessage: "Turn superseded by new input"
1022
- });
1023
- await new ConversationTurnLifecycleService(getConversationEventStore()).complete({
1024
- conversationId: args.conversationId,
1025
- createdAtMs: Date.now(),
1026
- outcome: "cancelled",
1027
- turnId: stale.turnId
1028
- });
1029
- markTurnClosed({
1030
- conversation: args.conversation,
1031
- nowMs: Date.now(),
1032
- sessionId: stale.turnId
1033
- });
1034
- }
1035
- if (args.turns.some((record) => record.state === "paused" && record.resumeReason === "auth") && pendingAuthorizationActorId) await deleteWebAuthorization({
1036
- actorId: pendingAuthorizationActorId,
1037
- conversationId: args.conversationId
1038
- });
1039
- return true;
1040
- }
1041
- /**
1042
- * End the Turn that waits for its next Run when `message` cannot join it, so
1043
- * the message starts its own Turn instead of running with that Turn's Actor.
1044
- * A stored legacy Turn without an Actor keeps taking the input.
1045
- */
1046
- async function supersedeTurnForInput(args) {
1047
- const conversation = coerceThreadConversationState(await getPersistedThreadState(args.conversationId));
1048
- const turnId = conversation.processing.activeTurnId;
1049
- if (!turnId || !await getPausedTurnRequest({
1050
- conversationId: args.conversationId,
1051
- turnId
1052
- })) return;
1053
- const turn = await getTurnRecord(args.conversationId, turnId);
1054
- if (!turn?.actor || canJoinTurn(turn, args.message)) return;
1055
- await hydrateConversationMessages({
1056
- conversation,
1057
- conversationId: args.conversationId
1058
- });
1059
- await supersedeTurns({
1060
- conversation,
1061
- conversationId: args.conversationId,
1062
- turns: [turn]
1063
- });
1064
- await persistThreadStateById(args.conversationId, { conversation });
1065
- }
1066
- // src/chat/agent-invocations/thread-turn.ts
1067
- /**
1068
- * A person's Turn in a Thread runs on the Conversation loop. A
1069
- * person's Turn and an Agent invocation Turn are never open at the same time.
1070
- */
1071
- /**
1072
- * End a person's open Turn in a Thread before an agent invocation starts, as
1073
- * new input does on a root. Only a Turn that waits for sign-in or lost its
1074
- * worker can be open here: a yielded Turn resumes before new input.
1075
- */
1076
- async function supersedeOpenMailboxTurn(conversationId) {
1077
- if ((await listActiveMailboxTurns(conversationId)).length === 0) return;
1078
- const conversation = coerceThreadConversationState(await getPersistedThreadState(conversationId));
1079
- await hydrateConversationMessages({
1080
- conversation,
1081
- conversationId
1082
- });
1083
- await supersedeOpenMailboxTurns({
1084
- conversation,
1085
- conversationId
1086
- });
1087
- await persistThreadStateById(conversationId, { conversation });
1088
- }
1089
- // src/chat/agent-invocations/types.ts
1090
- const exactStringSchema = z.string().min(1).refine((value) => value === value.trim());
1091
- const agentNameSchema = exactStringSchema.max(64);
1092
- /**
1093
- * Kind of a new child Conversation. A Thread is a child that people can
1094
- * message; a Task is one that only its parent messages.
1095
- */
1096
- const CHILD_AGENT_KINDS = ["thread", "task"];
1097
- /** `messageAgent` target for the parent of a child agent. */
1098
- const PARENT_AGENT_TARGET = "parent";
1099
- const agentInvocationMailboxStatusSchema = z.enum(AGENT_INVOCATION_MAILBOX_STATUSES);
1100
- const agentInvocationParentMailboxStatusSchema = z.enum(AGENT_INVOCATION_PARENT_MAILBOX_STATUSES);
1101
- const agentBindingSchema = z.object({
1102
- childConversationId: exactStringSchema,
1103
- name: agentNameSchema,
1104
- parentConversationId: exactStringSchema
1105
- }).strict();
1106
- const agentInvocationBaseSchema = z.object({
1107
- actor: actorSchema,
1108
- agentName: agentNameSchema.optional(),
1109
- childConversationId: exactStringSchema,
1110
- createdAtMs: z.number().finite(),
1111
- credentialContext: credentialContextSchema.optional(),
1112
- destination: destinationSchema,
1113
- input: exactStringSchema,
1114
- invocationId: exactStringSchema,
1115
- mailboxStatus: agentInvocationMailboxStatusSchema,
1116
- parentConversationId: exactStringSchema,
1117
- parentToolCallId: exactStringSchema.optional(),
1118
- agentType: agentTypeSchema.optional(),
1119
- /** The child starts with its parent's history. */
1120
- fork: z.literal(true).optional(),
1121
- reasoningLevel: z.enum(TURN_REASONING_LEVELS).optional(),
1122
- source: sourceSchema,
1123
- title: exactStringSchema.optional(),
1124
- updatedAtMs: z.number().finite()
1125
- }).strict();
1126
- const agentInvocationSchema = z.discriminatedUnion("status", [
1127
- agentInvocationBaseSchema.extend({ status: z.enum([
1128
- "pending",
1129
- "running",
1130
- "paused"
1131
- ]) }),
1132
- agentInvocationBaseSchema.extend({
1133
- parentMailboxStatus: agentInvocationParentMailboxStatusSchema,
1134
- result: z.string(),
1135
- status: z.literal("completed"),
1136
- terminalAtMs: z.number().finite()
1137
- }),
1138
- agentInvocationBaseSchema.extend({
1139
- errorMessage: z.string(),
1140
- parentMailboxStatus: agentInvocationParentMailboxStatusSchema,
1141
- status: z.enum([
1142
- "blocked",
1143
- "failed",
1144
- "stopped"
1145
- ]),
1146
- terminalAtMs: z.number().finite()
1147
- })
1148
- ]);
1149
- const createAgentInvocationSchema = z.object({
1150
- actor: actorSchema,
1151
- agentName: agentNameSchema.optional(),
1152
- credentialContext: credentialContextSchema.optional(),
1153
- destination: destinationSchema,
1154
- idempotencyKey: exactStringSchema,
1155
- input: exactStringSchema,
1156
- kind: z.enum(CHILD_AGENT_KINDS).default("task"),
1157
- parentConversationId: exactStringSchema,
1158
- parentToolCallId: exactStringSchema.optional(),
1159
- agentType: agentTypeSchema.optional(),
1160
- fork: z.literal(true).optional(),
1161
- reasoningLevel: z.enum(TURN_REASONING_LEVELS).optional(),
1162
- title: exactStringSchema.optional()
1163
- }).strict();
1164
- /** How a finished task of a child agent ended. A stop is not a result. */
1165
- const CHILD_AGENT_RESULTS = [
1166
- "completed",
1167
- "blocked",
1168
- "failed"
1169
- ];
1170
- // src/chat/agent-invocations/bindings.ts
1171
- function bindingFromRow(row) {
1172
- return agentBindingSchema.parse({
1173
- childConversationId: row.childConversationId,
1174
- name: row.name,
1175
- parentConversationId: row.parentConversationId
1176
- });
1177
- }
1178
- /** Read one named child binding in its parent-agent scope. */
1179
- async function getAgentBinding(args) {
1180
- const rows = await getSqlExecutor().db().select().from(juniorAgentBindings).where(and(eq(juniorAgentBindings.parentConversationId, args.parentConversationId), eq(juniorAgentBindings.name, args.name)));
1181
- return rows[0] ? bindingFromRow(rows[0]) : void 0;
1182
- }
1183
- /**
1184
- * Find a direct child agent of one parent by name or child Conversation id.
1185
- * A child that no Agent invocation names stores its agent config.
1186
- */
1187
- async function findChildAgentConversationId(args) {
1188
- const binding = await getAgentBinding({
1189
- name: args.target,
1190
- parentConversationId: args.parentConversationId
1191
- });
1192
- if (binding) return binding.childConversationId;
1193
- const db = getSqlExecutor().db();
1194
- return (await db.select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(eq(juniorConversations.parentConversationId, args.parentConversationId), eq(juniorConversations.conversationId, args.target), or(isNotNull(juniorConversations.agentConfig), exists(db.select({ invocationId: juniorAgentInvocations.invocationId }).from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, args.target)))))).limit(1))[0]?.conversationId;
1195
- }
1196
- // src/chat/agent-invocations/errors.ts
1197
- /** A child agent already uses this name in the parent Conversation. */
1198
- var AgentNameInUseError = class extends Error {
1199
- constructor(name) {
1200
- super(`A child agent named "${name}" already exists`);
1201
- this.name = "AgentNameInUseError";
1202
- }
1203
- };
1204
- /** Parent already has the maximum number of non-terminal child invocations. */
1205
- var AgentInvocationLimitError = class extends Error {
1206
- constructor(limit) {
1207
- super(`Parent already has ${limit} active child agent invocations (limit ${limit})`);
1208
- this.name = "AgentInvocationLimitError";
1209
- }
1210
- };
1211
- /**
1212
- * The Conversation that calls spawnAgent is too deep to start child agents,
1213
- * or its parent chain does not end at a root.
1214
- */
1215
- var AgentDepthLimitError = class extends Error {
1216
- constructor(maxAgentDepth) {
1217
- super(`This agent cannot start child agents: only ${maxAgentDepth} level(s) of child agents can start their own`);
1218
- this.name = "AgentDepthLimitError";
1219
- }
1220
- };
1221
- /** A child agent already has the maximum number of open tasks. */
1222
- var AgentMessageQueueFullError = class extends Error {
1223
- constructor(limit) {
1224
- super(`The child agent already has ${limit} open tasks`);
1225
- this.name = "AgentMessageQueueFullError";
1226
- }
1227
- };
1228
- /**
1229
- * A messageAgent target is not the parent, a child, or a top-level agent that
1230
- * the sender can message.
1231
- */
1232
- var AgentMessageTargetError = class extends Error {
1233
- constructor(message) {
1234
- super(message);
1235
- this.name = "AgentMessageTargetError";
1236
- }
1237
- };
1238
- /** A top-level agent paused automated Turns, so it takes no agent message. */
1239
- var AgentMessagePausedError = class extends Error {
1240
- constructor(conversationId) {
1241
- super(`${conversationId} paused automated work until a person replies there`);
1242
- this.name = "AgentMessagePausedError";
1243
- }
1244
- };
1245
- /**
1246
- * Cap the non-terminal agent invocations of one child, including the one that
1247
- * runs. Each message to a busy child queues one more.
1248
- */
1249
- const MAX_OPEN_AGENT_INVOCATIONS_PER_CHILD = 4;
1250
- /**
1251
- * Insert one pending agent invocation and read it back. An existing row with
1252
- * the same id wins, so the caller checks that the row it reads is its own.
1253
- */
1254
- async function insertAgentInvocation(invocation, nowMs) {
1255
- await getSqlExecutor().db().insert(juniorAgentInvocations).values({
1256
- ...invocation,
1257
- agentName: invocation.agentName ?? null,
1258
- agentType: invocation.agentType ?? null,
1259
- fork: invocation.fork ?? false,
1260
- credentialContext: invocation.credentialContext ?? null,
1261
- parentToolCallId: invocation.parentToolCallId ?? null,
1262
- reasoningLevel: invocation.reasoningLevel ?? null,
1263
- source: invocation.source ?? { kind: "agent_invocation" },
1264
- title: invocation.title ?? null,
1265
- status: "pending",
1266
- mailboxStatus: "pending",
1267
- createdAt: new Date(nowMs),
1268
- updatedAt: new Date(nowMs),
1269
- terminalAt: null
1270
- }).onConflictDoNothing();
1271
- return await getAgentInvocation(invocation.invocationId);
1272
- }
1273
- /**
1274
- * Require every durable creation input to match before replaying one key.
1275
- * The title is not compared: a retry can generate a different one, and the
1276
- * stored title wins.
1277
- */
1278
- function sameCreateInput(invocation, input) {
1279
- 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);
1280
- }
1281
- /**
1282
- * A stopped child agent cannot start or give work to child agents until its
1283
- * parent gives it new work. A Turn on the child's Conversation loop
1284
- * has no open agent invocation, but it can. A root Conversation has no agent
1285
- * invocation or agent config, so it always passes. `open` is the parent's open work from
1286
- * `listOpenAgentInvocations`.
1287
- */
1288
- async function assertCanGiveChildWork(parentConversationId, open) {
1289
- if (open.some((row) => row.childConversationId === parentConversationId)) return;
1290
- const latest = await getLatestAgentInvocationForConversation(parentConversationId);
1291
- if (latest ? isStoppedAgentInvocation(latest) : await readAgentConfig(parentConversationId) !== void 0 && await getConversationStoppedAtMs(parentConversationId) !== void 0) throw new Error(`Agent conversation ${parentConversationId} is stopped and cannot give work to child agents`);
1292
- }
1293
- /**
1294
- * Throw when giving work to one child agent would put its parent over
1295
- * `MAX_ACTIVE_AGENT_INVOCATIONS_PER_PARENT`. A child agent is active while it
1296
- * has open work, so a busy child already counts and messages queued for it
1297
- * do not count again. A new or idle child becomes active. This is the only
1298
- * place the rule for which child agents count lives. `open` is the parent's
1299
- * open work from `listOpenAgentInvocations`. A child that no agent
1300
- * invocation names is active while its listing shows open work.
1301
- */
1302
- async function assertChildAgentCapacity(open, args) {
1303
- const active = /* @__PURE__ */ new Set([...open.filter((row) => row.parentConversationId === args.parentConversationId).map((row) => row.childConversationId), ...await listOpenChildAgentsWithoutAgentInvocations(args.parentConversationId)]);
1304
- if (!active.has(args.childConversationId) && active.size >= 8) throw new AgentInvocationLimitError(8);
1305
- }
1306
- /**
1307
- * Create or replay the first invocation of one new child agent. A name gives
1308
- * the child a stable Conversation id that later messages can address. A name
1309
- * that is already used throws: later work for that child goes through
1310
- * `createAgentInvocationForMessage`.
1311
- */
1312
- async function createAgentInvocation(rawInput, nowMs = Date.now()) {
1313
- const input = createAgentInvocationSchema.parse(rawInput);
1314
- const invocationId = getAgentInvocationId(input.parentConversationId, input.idempotencyKey);
1315
- const childConversationId = input.agentName ? getNamedAgentConversationId(input.parentConversationId, input.agentName) : getUnnamedAgentConversationId(invocationId);
1316
- const lockName = getChildAgentLockName(input.parentConversationId);
1317
- return await getSqlExecutor().withLock(lockName, async () => {
1318
- const existing = await getAgentInvocation(invocationId);
1319
- if (existing) {
1320
- const child = await getConversationStore().get({ conversationId: existing.childConversationId });
1321
- if (!sameCreateInput(existing, input) || child?.kind !== input.kind) throw new Error(`Agent invocation idempotency key was reused with different input for ${invocationId}`);
1322
- return existing;
1323
- }
1324
- const open = await listOpenAgentInvocations(input.parentConversationId);
1325
- await assertCanGiveChildWork(input.parentConversationId, open);
1326
- if (input.agentName && await getAgentBinding({
1327
- name: input.agentName,
1328
- parentConversationId: input.parentConversationId
1329
- })) throw new AgentNameInUseError(input.agentName);
1330
- await assertChildAgentCapacity(open, {
1331
- childConversationId,
1332
- parentConversationId: input.parentConversationId
1333
- });
1334
- await getConversationStore().createChild({
1335
- childConversationId,
1336
- kind: input.kind,
1337
- parentConversationId: input.parentConversationId,
1338
- nowMs,
1339
- source: "internal",
1340
- ...input.title ? { title: input.title } : void 0
1341
- });
1342
- if (input.agentName) await getSqlExecutor().db().insert(juniorAgentBindings).values({
1343
- childConversationId,
1344
- name: input.agentName,
1345
- parentConversationId: input.parentConversationId
1346
- });
1347
- const invocation = await insertAgentInvocation({
1348
- actor: input.actor,
1349
- agentName: input.agentName,
1350
- agentType: input.agentType,
1351
- childConversationId,
1352
- credentialContext: input.credentialContext,
1353
- destination: input.destination,
1354
- fork: input.fork,
1355
- input: input.input,
1356
- invocationId,
1357
- parentConversationId: input.parentConversationId,
1358
- parentToolCallId: input.parentToolCallId,
1359
- reasoningLevel: input.reasoningLevel,
1360
- title: input.title
1361
- }, nowMs);
1362
- if (!invocation || !sameCreateInput(invocation, input)) throw new Error(`Agent invocation creation raced for ${invocationId}`);
1363
- return invocation;
1364
- });
1365
- }
1366
- /**
1367
- * Create or replay the agent invocation that gives one input to a child
1368
- * Conversation: a result or message from its own child agent, or its own
1369
- * watch events. It continues that Conversation for the same parent as
1370
- * `latest`, and for the same Actor and credentials unless `runAs` sets them.
1371
- * It skips the queue and active-count checks because it continues work that
1372
- * already passed them.
1373
- */
1374
- async function createAgentInvocationFromLatest(args, nowMs = Date.now()) {
1375
- const { latest } = args;
1376
- const { actor, credentialContext } = args.runAs ?? latest;
1377
- const invocation = await insertAgentInvocation({
1378
- actor,
1379
- agentName: latest.agentName,
1380
- agentType: latest.agentType,
1381
- childConversationId: latest.childConversationId,
1382
- credentialContext,
1383
- destination: latest.destination,
1384
- fork: args.runAs?.fork,
1385
- input: args.input,
1386
- invocationId: args.invocationId,
1387
- parentConversationId: latest.parentConversationId,
1388
- parentToolCallId: args.runAs?.parentToolCallId,
1389
- reasoningLevel: latest.reasoningLevel,
1390
- source: args.runAs?.source
1391
- }, nowMs);
1392
- if (!invocation || invocation.childConversationId !== latest.childConversationId) throw new Error(`Agent invocation creation raced for ${args.invocationId}`);
1393
- return invocation;
1394
- }
1395
- /**
1396
- * Create or replay the agent invocation for one message from a parent to one
1397
- * of its child agents. The child continues its history. If the child already
1398
- * has open work, the new agent invocation waits for that work and the parent
1399
- * gets one report for both. A stopped child starts again.
1400
- */
1401
- async function createAgentInvocationForMessage(input, nowMs = Date.now()) {
1402
- const invocationId = getAgentInvocationId(input.parentConversationId, input.idempotencyKey);
1403
- return await getSqlExecutor().withLock(getChildAgentLockName(input.parentConversationId), async () => {
1404
- const existing = await getAgentInvocation(invocationId);
1405
- if (existing) {
1406
- if (existing.childConversationId !== input.childConversationId || existing.input !== input.input) throw new Error(`Agent invocation idempotency key was reused with different input for ${invocationId}`);
1407
- return {
1408
- invocation: existing,
1409
- queued: existing.status === "pending" && (await listOpenAgentInvocations(input.parentConversationId)).some((row) => row.childConversationId === input.childConversationId && row.createdAtMs < existing.createdAtMs)
1410
- };
1411
- }
1412
- const latest = await getLatestAgentInvocationForConversation(input.childConversationId);
1413
- const child = latest ?? await readChildConversationSender(input.childConversationId);
1414
- if (!child || child.parentConversationId !== input.parentConversationId) throw new Error(`${input.childConversationId} is not a child agent of ${input.parentConversationId}`);
1415
- const agentConfig = latest ?? await readAgentConfig(input.childConversationId) ?? {};
1416
- const open = await listOpenAgentInvocations(input.parentConversationId);
1417
- await assertCanGiveChildWork(input.parentConversationId, open);
1418
- const openCount = open.filter((row) => row.childConversationId === input.childConversationId).length + (latest ? 0 : await countOpenParentMessages(input.childConversationId));
1419
- if (openCount >= MAX_OPEN_AGENT_INVOCATIONS_PER_CHILD) throw new AgentMessageQueueFullError(MAX_OPEN_AGENT_INVOCATIONS_PER_CHILD);
1420
- await assertChildAgentCapacity(open, {
1421
- childConversationId: input.childConversationId,
1422
- parentConversationId: input.parentConversationId
1423
- });
1424
- const invocation = await insertAgentInvocation({
1425
- actor: input.actor,
1426
- agentName: child.agentName,
1427
- agentType: agentConfig.agentType,
1428
- childConversationId: input.childConversationId,
1429
- credentialContext: input.credentialContext,
1430
- destination: input.destination,
1431
- input: input.input,
1432
- invocationId,
1433
- parentConversationId: input.parentConversationId,
1434
- parentToolCallId: input.parentToolCallId,
1435
- reasoningLevel: agentConfig.reasoningLevel
1436
- }, nowMs);
1437
- if (!invocation) throw new Error(`Agent invocation creation raced for ${invocationId}`);
1438
- return {
1439
- invocation,
1440
- queued: openCount > 0
1441
- };
1442
- });
1443
- }
1444
- // src/chat/agent-invocations/markers.ts
1445
- /**
1446
- * Dashboard records for agent invocations. The parent Conversation gets one
1447
- * `subagent_started` and one `subagent_ended` event for each agent invocation.
1448
- * The child Conversation gets `message` events for its input and its result,
1449
- * because a child posts nothing to its Location.
1450
- */
1451
- const SUBAGENT_KIND = "agent";
1452
- /**
1453
- * Record in the parent Conversation that one agent invocation started, and
1454
- * record its input as a user message in the child Conversation. The dashboard
1455
- * pairs the parent event with `subagent_ended` to show the child and its
1456
- * status. It must be written before the child mailbox append, so the child
1457
- * cannot end first. An agent wrote the input, not a person, so the message
1458
- * names its agent invocation instead of an author. Input from Events, such as
1459
- * the child's own Watch Events, passes their Event fields, so the dashboard
1460
- * shows it as an Event, as on a root.
1461
- */
1462
- async function recordSubagentStarted(invocation, eventMeta) {
1463
- const eventStore = getConversationEventStore();
1464
- const messageId = getAgentInvocationMessageId(invocation.invocationId);
1465
- await eventStore.append(invocation.childConversationId, [{
1466
- idempotencyKey: `message:${messageId}`,
1467
- data: {
1468
- type: "message",
1469
- messageId,
1470
- role: "user",
1471
- text: invocation.input,
1472
- meta: {
1473
- ...eventMeta,
1474
- agentInvocationId: invocation.invocationId
1475
- }
1476
- },
1477
- createdAtMs: invocation.createdAtMs
1478
- }]);
1479
- await eventStore.append(invocation.parentConversationId, [{
1480
- idempotencyKey: `subagent_started:${invocation.invocationId}`,
1481
- data: {
1482
- type: "subagent_started",
1483
- subagentInvocationId: invocation.invocationId,
1484
- subagentKind: SUBAGENT_KIND,
1485
- childConversationId: invocation.childConversationId,
1486
- ...invocation.agentName ? { agentName: invocation.agentName } : void 0,
1487
- ...invocation.parentToolCallId ? {
1488
- parentToolCallId: invocation.parentToolCallId,
1489
- task: invocation.input
1490
- } : void 0,
1491
- ...invocation.title ? { title: invocation.title } : void 0,
1492
- ...invocation.reasoningLevel ? { reasoningLevel: invocation.reasoningLevel } : void 0
1493
- },
1494
- createdAtMs: invocation.createdAtMs
1495
- }]);
1496
- }
1497
- const SUBAGENT_OUTCOMES = {
1498
- blocked: "blocked",
1499
- completed: "success",
1500
- failed: "error",
1501
- stopped: "aborted"
1502
- };
1503
- /**
1504
- * Record in the parent Conversation how one agent invocation ended, and record
1505
- * a completed result as an assistant message in the child Conversation. The
1506
- * heartbeat result repair also calls this, because the child work can be
1507
- * acknowledged before the worker reports the result.
1508
- */
1509
- async function recordSubagentEnded(invocation) {
1510
- const eventStore = getConversationEventStore();
1511
- await eventStore.append(invocation.parentConversationId, [{
1512
- idempotencyKey: `subagent_ended:${invocation.invocationId}`,
1513
- data: {
1514
- type: "subagent_ended",
1515
- subagentInvocationId: invocation.invocationId,
1516
- outcome: SUBAGENT_OUTCOMES[invocation.status]
1517
- },
1518
- createdAtMs: invocation.terminalAtMs
1519
- }]);
1520
- const result = invocation.status === "completed" ? invocation.result.trim() : "";
1521
- if (!result) return;
1522
- const messageId = `agent-invocation:${invocation.invocationId}:reply`;
1523
- await eventStore.append(invocation.childConversationId, [{
1524
- idempotencyKey: `message:${messageId}`,
1525
- data: {
1526
- type: "message",
1527
- messageId,
1528
- role: "assistant",
1529
- text: result
1530
- },
1531
- createdAtMs: invocation.terminalAtMs
1532
- }]);
1533
- }
1534
- // src/chat/agent-invocations/turn-end.ts
1535
- /**
1536
- * How a terminal agent invocation ends its child Turn. The live save and the
1537
- * recovery paths both use this, so a status cannot end the Turn two ways.
1538
- */
1539
- function agentInvocationTurnEnd(terminal) {
1540
- const finishedAtMs = terminal.terminalAtMs;
1541
- switch (terminal.status) {
1542
- case "completed": return {
1543
- finishedAtMs,
1544
- outcome: terminal.result.trim() ? "success" : "no_reply"
1545
- };
1546
- case "stopped": return {
1547
- finishedAtMs,
1548
- outcome: "cancelled"
1549
- };
1550
- case "blocked": return {
1551
- finishedAtMs,
1552
- outcome: "blocked"
1553
- };
1554
- case "failed": return {
1555
- failureCode: "model_execution_failed",
1556
- finishedAtMs,
1557
- outcome: "failed"
1558
- };
1559
- }
1560
- }
1561
- /**
1562
- * Read how one saved child Turn ends its agent invocation. A saved `reply`
1563
- * completes it, also when a newer Turn or a lost worker ended the Turn after
1564
- * that, or the Turn is paused. Returns undefined for a paused Turn without a
1565
- * `reply`, which can still resume.
1566
- */
1567
- function savedTurnEnd(turn) {
1568
- const answer = turn.turnStartMessageIndex === void 0 ? void 0 : readTurnAnswer(turn.piMessages.slice(turn.turnStartMessageIndex));
1569
- if (answer && "reply" in answer) return {
1570
- result: answer.reply.text,
1571
- status: "completed"
1572
- };
1573
- if (turn.state === "paused") return;
1574
- if (turn.state !== "completed" || turn.errorMessage) return {
1575
- errorMessage: turn.errorMessage ?? "Agent invocation failed",
1576
- status: "failed"
1577
- };
1578
- if (answer && "blocked" in answer) return {
1579
- errorMessage: answer.blocked.missing,
1580
- status: "blocked"
1581
- };
1582
- return {
1583
- result: answer ? "" : getTerminalAssistantMessages(turn.piMessages).map(getAssistantReplyText).filter((text) => text !== void 0).join("\n\n"),
1584
- status: "completed"
1585
- };
1586
- }
1587
- // src/chat/task-execution/turn-cancel.ts
1588
- /**
1589
- * End a cancelled Turn: a stop that a worker saw, or a stop of a Turn that
1590
- * waits for sign-in with no worker.
1591
- */
1592
- /** Close a cancelled Turn, save it, and acknowledge its input. */
1593
- async function completeCancelledConversationTurn(args) {
1594
- const pendingAuthorization = args.conversation.processing.pendingAuth?.sessionId === args.turnId ? args.conversation.processing.pendingAuth : void 0;
1595
- await abandonTurnRecord({
1596
- conversationId: args.conversationId,
1597
- turnId: args.turnId,
1598
- errorMessage: "Turn cancelled"
1599
- });
1600
- clearPendingAuth(args.conversation, args.turnId);
1601
- markConversationMessage(args.conversation, args.userMessageId, {
1602
- replied: false,
1603
- skippedReason: "turn cancelled"
1604
- });
1605
- markTurnClosed({
1606
- conversation: args.conversation,
1607
- nowMs: Date.now(),
1608
- sessionId: args.turnId
1609
- });
1610
- if (pendingAuthorization) await deleteWebAuthorization({
1611
- actorId: pendingAuthorization.actorId,
1612
- conversationId: args.conversationId
1613
- });
1614
- await persistThreadStateById(args.conversationId, {
1615
- conversation: args.conversation,
1616
- sandboxRef: args.sandboxRef
1617
- });
1618
- await new ConversationTurnLifecycleService(getConversationEventStore()).complete({
1619
- conversationId: args.conversationId,
1620
- createdAtMs: Date.now(),
1621
- outcome: "cancelled",
1622
- turnId: args.turnId
1623
- });
1624
- await args.acknowledge();
1625
- }
1626
- /**
1627
- * End the Turn of a stopped Conversation that waits for sign-in, so a later
1628
- * sign-in cannot resume it. A web Turn waits as an auth-paused Turn record. A
1629
- * Slack request waits as the thread's pending sign-in. Every stop path calls
1630
- * this, because no worker holds a waiting Turn and the stop wake can go to
1631
- * queued input first.
1632
- */
1633
- async function cancelSignInWait(conversationId) {
1634
- const turnId = await getAuthPausedConversationTurnId(conversationId) ?? coerceThreadConversationState(await getPersistedThreadState(conversationId)).processing.pendingAuth?.sessionId;
1635
- if (turnId) await cancelSignInPausedTurn({
1636
- conversationId,
1637
- turnId
1638
- });
1639
- }
1640
- /**
1641
- * Cancel a Turn that waits for sign-in outside its worker, with the same
1642
- * cleanup as a stopped resume.
1643
- */
1644
- async function cancelSignInPausedTurn(args) {
1645
- if (!await abandonTurnRecord({
1646
- conversationId: args.conversationId,
1647
- errorMessage: "Turn cancelled",
1648
- onlyIfAuthPaused: true,
1649
- turnId: args.turnId
1650
- })) return;
1651
- const conversation = coerceThreadConversationState(await getPersistedThreadState(args.conversationId));
1652
- await hydrateConversationMessages({
1653
- conversation,
1654
- conversationId: args.conversationId
1655
- });
1656
- await completeCancelledConversationTurn({
1657
- acknowledge: async () => {},
1658
- conversation,
1659
- conversationId: args.conversationId,
1660
- turnId: args.turnId,
1661
- userMessageId: getTurnUserMessage(conversation, args.turnId)?.id
1662
- });
1663
- }
1664
- // src/chat/agent-invocations/stop.ts
1665
- /**
1666
- * Stop one child agent of a parent Conversation and every child agent below
1667
- * it. The parent gets no result. SQL stops the work first. Then each
1668
- * Conversation in the tree ends its session. An agent stop is not a person
1669
- * stop, so their Watches end. A Conversation stop request aborts each run
1670
- * that is still working.
1671
- *
1672
- * Returns undefined when the child does not belong to the parent.
1673
- */
1674
- async function stopChildAgent(args) {
1675
- const [latest, stoppedAtMs] = await Promise.all([getLatestAgentInvocationForConversation(args.childConversationId), getConversationStoppedAtMs(args.childConversationId)]);
1676
- const wasStopped = latest ? latest.status === "stopped" || isChildAgentSessionStopped(latest, stoppedAtMs) : stoppedAtMs !== void 0;
1677
- const tree = await stopChildAgentInvocations(args);
1678
- if (!tree) return;
1679
- await finishStoppedTree(tree, tree.conversationIds, {
1680
- cancelWatches: true,
1681
- state: args.state
1682
- });
1683
- await dropUnreadLoopReplies([args.parentConversationId, ...tree.conversationIds], tree.conversationIds, args.state);
1684
- return { stopped: tree.stopped.length > 0 || !wasStopped };
1685
- }
1686
- /**
1687
- * Stop the child agents of a Conversation whose run saw its stop. A child
1688
- * agent's worker calls this after it records its own stop, and the root work
1689
- * path in `app/conversation-work.ts` calls it for a root. So this sends no
1690
- * stop request to that Conversation.
1691
- *
1692
- * The worker can see its stop late. The stop already reached every child
1693
- * agent that existed then, so this stops only child agents that this
1694
- * Conversation spawned or gave new work to after its stop, even when they
1695
- * already finished, and everything below them. When the stop already ended,
1696
- * because a person or the parent gave the Conversation new input, this does
1697
- * nothing.
1698
- *
1699
- * Only a person's stop of this Conversation itself leaves child agents to
1700
- * stop here: an agent stop, or a stop of a Conversation above it, stops this
1701
- * Conversation's own agent invocations first, so it cannot spawn more. So
1702
- * this keeps their Watches, as a person's stop does.
1703
- */
1704
- async function stopChildAgentsOf(conversationId, state) {
1705
- const stoppedAtMs = await getConversationStoppedAtMs(conversationId);
1706
- if (stoppedAtMs === void 0) return;
1707
- const nowMs = Date.now();
1708
- const tree = await stopAgentInvocationTree(conversationId, nowMs, {
1709
- includeRoot: false,
1710
- taskedAfterMs: stoppedAtMs
1711
- });
1712
- await skipUnreadResults(conversationId, nowMs, state);
1713
- const stoppedIds = tree.conversationIds.filter((id) => id !== conversationId);
1714
- await finishStoppedTree(tree, stoppedIds, {
1715
- cancelWatches: false,
1716
- nowMs: stoppedAtMs,
1717
- state
1718
- });
1719
- await dropUnreadLoopReplies(tree.conversationIds, stoppedIds, state);
1720
- await dropOwnUnreadLoopReplies(conversationId, state);
1721
- }
1722
- /**
1723
- * Stop every child agent below a Conversation that a person stops. The
1724
- * Conversation's own agent invocations stay as they are: when it is a child
1725
- * agent, its worker records the stop and reports it to its parent. Call it
1726
- * through `stopConversation`, which stops the Conversation's Turn next.
1727
- *
1728
- * The Conversation's run sees its stop only at its next stop signal check.
1729
- * When it does, `stopChildAgentsOf` stops the child agents that it spawned or
1730
- * gave new work to before then, at the time of this stop. So input that ends
1731
- * this stop ends theirs too.
1732
- */
1733
- async function stopChildAgentsBelow(conversationId, options) {
1734
- const { nowMs, stoppedAtMs, state } = options;
1735
- const tree = await stopAgentInvocationTree(conversationId, nowMs, { includeRoot: false });
1736
- await skipUnreadResults(conversationId, nowMs, state);
1737
- const stoppedIds = tree.conversationIds.filter((id) => id !== conversationId);
1738
- await finishStoppedTree(tree, stoppedIds, {
1739
- cancelWatches: false,
1740
- nowMs: stoppedAtMs,
1741
- state
1742
- });
1743
- await dropUnreadLoopReplies(tree.conversationIds, stoppedIds, state);
1744
- }
1745
- /**
1746
- * Skip the `appended` results and replies that still wait in a Conversation's
1747
- * mailbox, so they start no Turn. A result that the Conversation already read keeps its
1748
- * status. Call this after the tree stop: it skipped each `pending` result and
1749
- * stopped each child agent, so no result becomes `appended` after this read.
1750
- *
1751
- * The mailbox read is not atomic with the parent worker. A worker that takes
1752
- * a result before this update holds the work lease, so the stop request of
1753
- * the Conversation stops its Turn. A result that such a Turn took but did not
1754
- * ack yet is marked `skipped`.
1755
- */
1756
- async function skipUnreadResults(conversationId, nowMs, state) {
1757
- const messages = (await getConversationWorkState({
1758
- conversationId,
1759
- state
1760
- }))?.messages ?? [];
1761
- const invocationIds = [];
1762
- for (const message of messages) {
1763
- const sender = await readChildMessageSender(message);
1764
- const invocation = sender && ownAgentInvocation(sender);
1765
- if (invocation) invocationIds.push(invocation);
1766
- }
1767
- if (invocationIds.length === 0) return;
1768
- await getSqlExecutor().db().update(juniorAgentInvocations).set({
1769
- parentMailboxStatus: "skipped",
1770
- updatedAt: new Date(nowMs)
1771
- }).where(and(eq(juniorAgentInvocations.parentConversationId, conversationId), inArray(juniorAgentInvocations.invocationId, invocationIds), eq(juniorAgentInvocations.parentMailboxStatus, "appended")));
1772
- }
1773
- /**
1774
- * Drop the unread replies that Turns on the Conversation loop of the stopped
1775
- * Conversations left in each mailbox of `mailboxIds`. Such a reply names
1776
- * no work that the stop skips, so the stop drops it by its sender fields.
1777
- * A reply sent after the stop is dropped when it is read, while the sender
1778
- * is stopped. Call this after the stop is stored.
1779
- *
1780
- * A reply that a running Turn already took leaves the mailbox like one that
1781
- * it read: the Turn's own ack removes nothing more.
1782
- */
1783
- async function dropUnreadLoopReplies(mailboxIds, stoppedIds, state) {
1784
- const stopped = new Set(stoppedIds);
1785
- for (const conversationId of mailboxIds) {
1786
- const messages = (await getConversationWorkState({
1787
- conversationId,
1788
- state
1789
- }))?.messages ?? [];
1790
- const inboundMessageIds = [];
1791
- for (const message of messages) {
1792
- const sender = await readChildMessageSender(message);
1793
- if (sender && !ownAgentInvocation(sender) && stopped.has(sender.conversationId)) inboundMessageIds.push(message.inboundMessageId);
1794
- }
1795
- if (inboundMessageIds.length > 0) await dropPendingMessages({
1796
- conversationId,
1797
- inboundMessageIds,
1798
- state
1799
- });
1800
- }
1801
- }
1802
- /**
1803
- * Drop the unread loop replies that a Conversation that a person stopped
1804
- * left in its parent's mailbox, outside its tree. Call this after its stop
1805
- * is stored: the parent mailbox lock then drops a later reply.
1806
- */
1807
- async function dropOwnUnreadLoopReplies(conversationId, state) {
1808
- await dropUnreadLoopReplies((await getSqlExecutor().db().select({ id: juniorConversations.parentConversationId }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId))).flatMap((parent) => parent.id ? [parent.id] : []), [conversationId], state);
1809
- }
1810
- /**
1811
- * A Thread can hold a person's Turn that waits for sign-in. The stop ends
1812
- * that Turn here, because no worker holds it. Then a later sign-in callback
1813
- * cannot resume a stopped Thread.
1814
- */
1815
- async function finishStoppedTree(tree, conversationIdsToStop, options) {
1816
- for (const invocation of tree.stopped) await recordSubagentEnded(invocation);
1817
- await markConversationsStopped(conversationIdsToStop, options);
1818
- for (const conversationId of conversationIdsToStop) {
1819
- await cancelSignInWait(conversationId);
1820
- await stopConversationWork({
1821
- conversationId,
1822
- state: options.state
1823
- });
1824
- }
1825
- }
1826
- /**
1827
- * List one child Conversation and every Conversation below it, child first.
1828
- * It takes the create lock of each Conversation before it reads that
1829
- * Conversation's children, so no child agent can start in the tree until the
1830
- * caller's transaction ends.
1831
- */
1832
- async function lockAgentConversationTree(childConversationId) {
1833
- const executor = getSqlExecutor();
1834
- const conversationIds = [childConversationId];
1835
- let parents = conversationIds;
1836
- while (parents.length > 0) {
1837
- for (const parent of parents) await executor.withLock(getChildAgentLockName(parent), async () => void 0);
1838
- const rows = await executor.db().selectDistinct({ childConversationId: juniorAgentInvocations.childConversationId }).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.parentConversationId, parents));
1839
- const withoutInvocations = await executor.db().select({ childConversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(inArray(juniorConversations.parentConversationId, parents), isNotNull(juniorConversations.agentConfig)));
1840
- parents = [...new Set([...rows, ...withoutInvocations].map((row) => row.childConversationId))].filter((id) => !conversationIds.includes(id));
1841
- conversationIds.push(...parents);
1842
- }
1843
- return conversationIds;
1844
- }
1845
- /**
1846
- * Keep a Conversation, the child agents that it spawned or gave new work to
1847
- * after `taskedAfterMs`, and every Conversation below those child agents.
1848
- */
1849
- async function withChildAgentsTaskedAfter(conversationId, conversationIds, taskedAfterMs) {
1850
- const links = await getSqlExecutor().db().selectDistinct({
1851
- childConversationId: juniorAgentInvocations.childConversationId,
1852
- parentConversationId: juniorAgentInvocations.parentConversationId
1853
- }).from(juniorAgentInvocations).where(and(inArray(juniorAgentInvocations.parentConversationId, [...conversationIds]), or(ne(juniorAgentInvocations.parentConversationId, conversationId), gt(juniorAgentInvocations.createdAt, new Date(taskedAfterMs)))));
1854
- const withoutInvocations = await getSqlExecutor().db().select({
1855
- childConversationId: juniorConversations.conversationId,
1856
- parentConversationId: juniorConversations.parentConversationId
1857
- }).from(juniorConversations).where(and(inArray(juniorConversations.parentConversationId, [...conversationIds]), isNotNull(juniorConversations.agentConfig), or(ne(juniorConversations.parentConversationId, conversationId), gt(juniorConversations.createdAt, new Date(taskedAfterMs)))));
1858
- const kept = [conversationId];
1859
- for (let index = 0; index < kept.length; index += 1) for (const link of [...links, ...withoutInvocations]) if (link.parentConversationId === kept[index] && !kept.includes(link.childConversationId)) kept.push(link.childConversationId);
1860
- return kept;
1861
- }
1862
- /**
1863
- * Stop the agent invocations of one direct child agent and of every child
1864
- * agent below it. Returns undefined when the child does not belong to the
1865
- * parent.
1866
- */
1867
- async function stopChildAgentInvocations(args) {
1868
- const db = getSqlExecutor().db();
1869
- const [owned, child] = await Promise.all([db.select({ invocationId: juniorAgentInvocations.invocationId }).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, args.parentConversationId), eq(juniorAgentInvocations.childConversationId, args.childConversationId))).limit(1), db.select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(eq(juniorConversations.conversationId, args.childConversationId), eq(juniorConversations.parentConversationId, args.parentConversationId), isNotNull(juniorConversations.agentConfig)))]);
1870
- if (owned.length === 0 && child.length === 0) return;
1871
- return await stopAgentInvocationTree(args.childConversationId, args.nowMs);
1872
- }
1873
- /**
1874
- * Stop the agent invocations of one agent Conversation and of every child
1875
- * agent below it. Open agent invocations become `stopped`. Results that would
1876
- * still start or report work in the tree become `skipped`. With
1877
- * `includeRoot: false`, the agent invocations of the Conversation itself stay
1878
- * as they are, and only `pending` results sent to it become `skipped`. With
1879
- * `taskedAfterMs`, only the direct child agents that got an agent invocation
1880
- * after that time, and the Conversations below them, stop.
1881
- */
1882
- async function stopAgentInvocationTree(conversationId, nowMs = Date.now(), options = { includeRoot: true }) {
1883
- return await getSqlExecutor().withLock(getChildAgentLockName(conversationId), () => stopLockedAgentInvocationTree(conversationId, nowMs, options));
1884
- }
1885
- async function stopLockedAgentInvocationTree(conversationId, nowMs, options) {
1886
- const db = getSqlExecutor().db();
1887
- const now = new Date(nowMs);
1888
- const lockedIds = await lockAgentConversationTree(conversationId);
1889
- const conversationIds = options.taskedAfterMs === void 0 ? lockedIds : await withChildAgentsTaskedAfter(conversationId, lockedIds, options.taskedAfterMs);
1890
- const stoppedChildIds = options.includeRoot ? conversationIds : conversationIds.filter((id) => id !== conversationId);
1891
- const stopped = await db.update(juniorAgentInvocations).set({
1892
- errorMessage: "Stopped by the parent conversation",
1893
- parentMailboxStatus: "skipped",
1894
- result: null,
1895
- status: "stopped",
1896
- terminalAt: now,
1897
- updatedAt: now
1898
- }).where(and(inArray(juniorAgentInvocations.childConversationId, stoppedChildIds), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES))).returning();
1899
- await db.update(juniorAgentInvocations).set({
1900
- parentMailboxStatus: "skipped",
1901
- updatedAt: now
1902
- }).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"))));
1903
- return {
1904
- conversationIds,
1905
- stopped: stopped.map(invocationFromRow).filter(isTerminalAgentInvocation)
1906
- };
1907
- }
1908
- // src/chat/agent-invocations/work.ts
1909
- const agentInvocationMailboxMetadataSchema = z.object({
1910
- agentInvocationId: z.string().min(1),
1911
- kind: z.literal("agent_invocation")
1912
- }).strict();
1913
- /** Map a durable invocation's model settings and depth to the child Run policy. */
1914
- function agentInvocationRunPolicy(invocation, canSpawn) {
1915
- return {
1916
- disabledFeatures: canSpawn ? ["interactive-auth"] : ["interactive-auth", "subagents"],
1917
- ...invocation.reasoningLevel ? { reasoning: invocation.reasoningLevel } : void 0
1918
- };
1919
- }
1920
- /** Build destinationless mailbox work that references one durable invocation. */
1921
- function buildAgentInvocationInboundMessage(invocation, nowMs = Date.now()) {
1922
- return {
1923
- conversationId: invocation.childConversationId,
1924
- createdAtMs: invocation.createdAtMs,
1925
- delivery: "defer",
1926
- inboundMessageId: getAgentInvocationMessageId(invocation.invocationId),
1927
- input: {
1928
- authorId: invocation.invocationId,
1929
- authorIdentityId: SYSTEM_IDENTITY_ID,
1930
- text: "[agent invocation]",
1931
- metadata: {
1932
- agentInvocationId: invocation.invocationId,
1933
- kind: "agent_invocation"
1934
- }
1935
- },
1936
- receivedAtMs: nowMs,
1937
- source: "internal"
1938
- };
1939
- }
1940
- /** Append one invocation to its child mailbox and send the normal queue wake. */
1941
- async function enqueueAgentInvocation(invocation, options) {
1942
- if (invocation.mailboxStatus === "appended" || isTerminalAgentInvocation(invocation)) return;
1943
- await recordSubagentStarted(invocation, options.eventMeta);
1944
- if (invocation.parentToolCallId !== void 0) await resumeStoppedConversationTree(invocation.childConversationId, invocation.createdAtMs);
1945
- const nowMs = options.nowMs ?? Date.now();
1946
- await appendAndEnqueueInboundMessage({
1947
- message: buildAgentInvocationInboundMessage(invocation, nowMs),
1948
- conversationStore: options.conversationStore,
1949
- nowMs,
1950
- queue: options.queue,
1951
- state: options.state
1952
- });
1953
- await markAgentInvocationMailboxAppended(invocation.invocationId, nowMs);
1954
- }
1955
- /** Create or replay an invocation, then durably schedule its child work. */
1956
- async function createAndEnqueueAgentInvocation(input, options) {
1957
- const invocation = await createAgentInvocation(input, options.nowMs);
1958
- await enqueueAgentInvocation(invocation, options);
1959
- return await getAgentInvocation(invocation.invocationId) ?? invocation;
1960
- }
1961
- /** Require one invocation metadata reference for one leased mailbox attempt. */
1962
- /** Return whether one mailbox input is a parent task or message for an agent invocation. */
1963
- function isAgentInvocationInput(message) {
1964
- return agentInvocationMailboxMetadataSchema.safeParse(message.input.metadata).success;
1965
- }
1966
- function invocationIdFromMessages(messages) {
1967
- if (messages.length === 0) return;
1968
- const parsed = messages.map((message) => agentInvocationMailboxMetadataSchema.safeParse(message.input.metadata));
1969
- if (parsed.every((result) => !result.success)) return;
1970
- if (parsed.some((result) => !result.success)) throw new Error("Conversation mailbox mixes agent invocation and other input");
1971
- const invocationIds = new Set(parsed.map((result) => {
1972
- if (!result.success) throw new Error("Agent invocation mailbox metadata failed validation");
1973
- return result.data.agentInvocationId;
1974
- }));
1975
- if (invocationIds.size !== 1) throw new Error("Conversation mailbox contains multiple agent invocations in one attempt");
1976
- return invocationIds.values().next().value;
1977
- }
1978
- /**
1979
- * Text that the child agent model reads for one agent invocation. A parent
1980
- * agent task or message becomes one `<parent-agent-task>`. Results of the
1981
- * child's own child agents already have their own tag.
1982
- */
1983
- function agentInvocationInputText(invocation) {
1984
- if (!invocation.parentToolCallId) return invocation.input;
1985
- const instructions = [invocation.fork ? FORK_INSTRUCTIONS : void 0, agentTypeInstructions(invocation.agentType)].filter((text) => text !== void 0);
1986
- return renderTag("parent-agent-task", {}, [...instructions.flatMap((text) => [escapeClosingTags(text), ""]), escapeClosingTags(invocation.input)]);
1987
- }
1988
- /**
1989
- * A parent agent task or message is the child's instruction. Another input,
1990
- * such as a result of the child's own child agent or an Event, is context.
1991
- */
1992
- function agentInvocationProvenance(invocation) {
1993
- return invocation.parentToolCallId ? agentInstructionProvenance : contextProvenance;
1994
- }
1995
- /**
1996
- * Resolve the agent invocation that owns this work: the one named by its
1997
- * mailbox input, or for an empty wake the open one. Other work has none.
1998
- */
1999
- async function resolveAgentInvocationId(context) {
2000
- const mailboxInvocationId = invocationIdFromMessages(context.attempt.messages);
2001
- if (mailboxInvocationId || context.attempt.messages.length > 0) return mailboxInvocationId;
2002
- const active = await getActiveAgentInvocationForConversation(context.conversationId);
2003
- if (active) return active.invocationId;
2004
- const latest = await getLatestAgentInvocationForConversation(context.conversationId);
2005
- const turn = latest ? await getTurnRecord(context.conversationId, getAgentInvocationTurnId(latest.invocationId)) : void 0;
2006
- return turn?.state === "paused" || turn?.state === "running" ? latest?.invocationId : void 0;
2007
- }
2008
- /**
2009
- * Give queued parent messages to the running agent invocation of a child as
2010
- * steering messages. A message joins only with the Actor and credentials of
2011
- * the running Turn. The first message that does not match stops the scan, so
2012
- * it and every later message wait for the current work. Each message that
2013
- * joins ends as `steered`, and the running agent invocation reports for it.
2014
- */
2015
- function createAgentMessageSteeringDrain(context, running) {
2016
- const turnId = getAgentInvocationTurnId(running.invocationId);
2017
- return async (accept) => {
2018
- const accepted = [];
2019
- await context.attempt.drain(async (pending) => {
2020
- const readIds = [];
2021
- const joining = [];
2022
- for (const message of pending) {
2023
- const metadata = agentInvocationMailboxMetadataSchema.safeParse(message.input.metadata);
2024
- if (!metadata.success) continue;
2025
- const candidate = await getAgentInvocation(metadata.data.agentInvocationId);
2026
- if (!candidate?.parentToolCallId || candidate.invocationId === running.invocationId) continue;
2027
- if (isTerminalAgentInvocation(candidate)) {
2028
- if (candidate.parentMailboxStatus === "steered") readIds.push(message.inboundMessageId);
2029
- continue;
2030
- }
2031
- if (!sameActorIdentity(candidate.actor, running.actor) || !isDeepStrictEqual(candidate.credentialContext, running.credentialContext)) break;
2032
- joining.push(candidate);
2033
- readIds.push(message.inboundMessageId);
2034
- }
2035
- if (joining.length === 0) return readIds;
2036
- const saved = (await getTurnRecord(running.childConversationId, turnId))?.piMessages ?? [];
2037
- const messages = withoutSavedSteeringMessages(saved, joining.map((candidate) => ({
2038
- kind: "runtime",
2039
- provenance: agentInvocationProvenance(candidate),
2040
- text: agentInvocationInputText(candidate),
2041
- timestampMs: candidate.createdAtMs
2042
- })), buildSteeringPiMessage);
2043
- if (messages.length > 0) {
2044
- await accept(messages);
2045
- accepted.push(...messages);
2046
- }
2047
- for (const candidate of joining) {
2048
- const terminal = await markAgentInvocationSteered(candidate.invocationId);
2049
- if (terminal && isTerminalAgentInvocation(terminal)) await recordSubagentEnded(terminal);
2050
- }
2051
- return readIds;
2052
- }, { deferred: true });
2053
- return accepted;
2054
- };
2055
- }
2056
- /** Project the terminal invocation into the idempotent turn lifecycle. */
2057
- async function persistTerminalLifecycle(terminal) {
2058
- const turnId = getAgentInvocationTurnId(terminal.invocationId);
2059
- if (terminal.status !== "completed") await abandonTurnRecord({
2060
- conversationId: terminal.childConversationId,
2061
- errorMessage: terminal.status === "stopped" ? "Turn cancelled" : terminal.errorMessage,
2062
- turnId
2063
- });
2064
- await finishTurn(terminal.childConversationId, turnId, agentInvocationTurnEnd(terminal));
2065
- }
2066
- /**
2067
- * Stop an invocation whose worker died, or project its terminal turn result.
2068
- * With `resumeLostWorker`, a Turn whose worker died resumes once from its last
2069
- * save, as a root Turn does. A second loss stops it.
2070
- */
2071
- async function projectTerminalTurn(invocation, options = {}) {
2072
- const { resumeLostWorker, ...completeOptions } = options;
2073
- let turn = await getTurnRecord(invocation.childConversationId, getAgentInvocationTurnId(invocation.invocationId));
2074
- if (!turn) return;
2075
- if (resumeLostWorker && turn.state === "running" && await pauseLostWorkerTurn(turn)) return;
2076
- if (turn.state === "running" || resumeLostWorker && turn.state === "paused" && lostWorkerBeforeFirstSave(turn)) {
2077
- turn = await failTurnRecord({
2078
- conversationId: turn.conversationId,
2079
- expectedVersion: turn.version,
2080
- turnId: turn.turnId,
2081
- errorMessage: "Agent invocation lost its worker before it could pause"
2082
- });
2083
- if (!turn) return;
2084
- }
2085
- const end = savedTurnEnd(turn);
2086
- if (!end) return;
2087
- if (turn.state === "paused") await abandonTurnRecord({
2088
- conversationId: turn.conversationId,
2089
- turnId: turn.turnId
2090
- });
2091
- return await completeAgentInvocation({
2092
- ...completeOptions,
2093
- invocationId: invocation.invocationId,
2094
- ...end
2095
- });
2096
- }
2097
- /**
2098
- * End every running or paused agent invocation of a child before other work
2099
- * opens a Turn there, so the child has one open Turn. A saved finished Turn
2100
- * gives its result. Every other one fails with `errorMessage`, because the
2101
- * newer work does not continue its task. Each reports on its own.
2102
- */
2103
- async function endActiveAgentInvocations(conversationId, options) {
2104
- for (const active of await listAgentInvocationsForConversation(conversationId, ACTIVE_AGENT_INVOCATION_STATUSES)) {
2105
- if (active.invocationId === options.exceptInvocationId) continue;
2106
- const terminal = await projectTerminalTurn(active, { reportNow: true }) ?? await completeAgentInvocation({
2107
- invocationId: active.invocationId,
2108
- errorMessage: options.errorMessage,
2109
- reportNow: true,
2110
- status: "failed"
2111
- });
2112
- if (terminal && isTerminalAgentInvocation(terminal)) {
2113
- await persistTerminalLifecycle(terminal);
2114
- await recordSubagentEnded(terminal);
2115
- await options.enqueueResult?.(terminal);
2116
- }
2117
- }
2118
- }
2119
- /**
2120
- * End every agent invocation of a child whose last attempt lost its worker and
2121
- * whose input reached the child's mailbox. The worker ran no failure path, and
2122
- * the stop drops the mailbox, so none of them can run. The heartbeat sends
2123
- * each result.
2124
- */
2125
- async function endAgentInvocationsOfStoppedWork(conversationId, inboundMessageIds) {
2126
- for (const invocation of await listAgentInvocationsForConversation(conversationId, NON_TERMINAL_AGENT_INVOCATION_STATUSES)) {
2127
- if (!inboundMessageIds.includes(getAgentInvocationMessageId(invocation.invocationId))) continue;
2128
- const terminal = await projectTerminalTurn(invocation, { reportNow: true }) ?? await completeAgentInvocation({
2129
- invocationId: invocation.invocationId,
2130
- errorMessage: "This task stopped because its worker failed repeatedly.",
2131
- reportNow: true,
2132
- status: "failed"
2133
- });
2134
- if (terminal && isTerminalAgentInvocation(terminal)) await persistTerminalLifecycle(terminal);
2135
- }
2136
- }
2137
- /** Classify authorization failures that terminally block background work. */
2138
- function blockingInvocationError(error) {
2139
- const cause = getConversationTurnBoundaryError(error)?.cause ?? error;
2140
- return cause instanceof AuthorizationFlowDisabledError || cause instanceof PluginCredentialFailureError ? cause : void 0;
2141
- }
2142
- function isInvocationInputCommitLost(error) {
2143
- const cause = getConversationTurnBoundaryError(error)?.cause ?? error;
2144
- return isTurnInputCommitLostError(cause);
2145
- }
2146
- /**
2147
- * Save one completed agent result on its child agent invocation. A `reply`
2148
- * goes to the parent before the Turn is saved, so a lost worker cannot save
2149
- * the Turn and drop its reply.
2150
- */
2151
- async function saveAgentInvocationResult(args) {
2152
- const failed = args.result.diagnostics.outcome !== "success";
2153
- if (args.result.reply) await args.sendReply?.(args.invocation, args.result.reply);
2154
- await persistThreadStateById(args.invocation.childConversationId, { sandboxRef: args.result.sandboxRef ?? args.sandboxRef });
2155
- if (args.result.piMessages?.length) await saveTurnCheckpoint({
2156
- mode: "completed",
2157
- conversationId: args.invocation.childConversationId,
2158
- turnId: args.turnId,
2159
- durationMs: args.result.diagnostics.durationMs,
2160
- usage: args.result.diagnostics.usage,
2161
- destination: args.invocation.destination,
2162
- ...failed ? { errorMessage: args.result.diagnostics.errorMessage ?? "Agent invocation failed" } : void 0,
2163
- messages: args.result.piMessages,
2164
- actor: args.invocation.actor,
2165
- source: args.invocation.source,
2166
- surface: "internal"
2167
- });
2168
- if (args.invocation.parentToolCallId) await resetAutomatedTurnLimit({ conversationId: args.invocation.childConversationId });
2169
- else if (args.invocation.source.kind !== "agent_invocation") {
2170
- const maxTurns = botConfig.maxConsecutiveAutomatedTurns;
2171
- await maybePostAutomatedTurnLimitNotice({
2172
- conversationId: args.invocation.childConversationId,
2173
- maxTurns,
2174
- update: await recordFinishedTurnForAutomatedLimit({
2175
- conversationId: args.invocation.childConversationId,
2176
- maxTurns,
2177
- source: args.invocation.source
2178
- })
2179
- });
2180
- }
2181
- const terminal = await completeAgentInvocation({
2182
- invocationId: args.invocation.invocationId,
2183
- ...failed ? {
2184
- errorMessage: args.result.diagnostics.errorMessage ?? "Agent invocation failed",
2185
- status: "failed"
2186
- } : args.result.blocked ? {
2187
- errorMessage: args.result.blocked.missing,
2188
- status: "blocked"
2189
- } : {
2190
- result: args.result.reply?.text ?? "",
2191
- status: "completed"
2192
- }
2193
- });
2194
- if (!terminal || !isTerminalAgentInvocation(terminal)) throw new Error(`Agent invocation did not finish for ${args.invocation.invocationId}`);
2195
- return agentInvocationTurnEnd(terminal);
2196
- }
2197
- /**
2198
- * Build the invocation consumer that advances work through the shared runner.
2199
- * `enqueueResult` sends each terminal result to the parent mailbox. Omit it
2200
- * only where the parent has no mailbox, such as the local CLI.
2201
- * `maxAgentDepth` is the number of child agent levels that can start their
2202
- * own child agents. The default, 0, lets only the root start child agents.
2203
- */
2204
- function createAgentInvocationWorker(agentRunner, options = {}) {
2205
- const canSpawn = (options.maxAgentDepth ?? 0) > 0;
2206
- return async (context, invocationId) => {
2207
- let invocation = await getAgentInvocation(invocationId);
2208
- if (!invocation) throw new Error(`Agent invocation is missing for ${invocationId}`);
2209
- const report = async (terminal) => {
2210
- await recordSubagentEnded(terminal);
2211
- await options.enqueueResult?.(terminal);
2212
- };
2213
- const finish = async (terminal) => {
2214
- if (!terminal || !isTerminalAgentInvocation(terminal)) return;
2215
- if (terminal.parentMailboxStatus !== "steered") await persistTerminalLifecycle(terminal);
2216
- await report(terminal);
2217
- };
2218
- let acknowledged = context.attempt.messages.length === 0;
2219
- const acknowledge = async () => {
2220
- if (acknowledged) return;
2221
- try {
2222
- await context.attempt.ack();
2223
- } catch {
2224
- throw new TurnInputCommitLostError(`Conversation work lease lost before invocation inbox ack for ${context.conversationId}`);
2225
- }
2226
- acknowledged = true;
2227
- };
2228
- const stopSignal = context.stopSignal?.();
2229
- const finishStopped = async () => {
2230
- await finish(await completeAgentInvocation({
2231
- invocationId,
2232
- errorMessage: "Agent invocation was stopped",
2233
- status: "stopped"
2234
- }));
2235
- await stopChildAgentsOf(context.conversationId);
2236
- await acknowledge();
2237
- return { status: "completed" };
2238
- };
2239
- const turnId = getAgentInvocationTurnId(invocation.invocationId);
2240
- const lifecycle = new ConversationTurnLifecycleService(getConversationEventStore());
2241
- let sandboxRef;
2242
- let history;
2243
- let location;
2244
- try {
2245
- if (invocation.childConversationId !== context.conversationId) throw new Error(`Agent invocation ${invocationId} belongs to ${invocation.childConversationId}, not ${context.conversationId}`);
2246
- if (context.destination) throw new Error(`Agent invocation conversation ${context.conversationId} must not own a provider destination`);
2247
- if (isTerminalAgentInvocation(invocation)) {
2248
- await finish(invocation);
2249
- await acknowledge();
2250
- return { status: "completed" };
2251
- }
2252
- const projected = await projectTerminalTurn(invocation, { resumeLostWorker: true });
2253
- if (projected && isTerminalAgentInvocation(projected)) {
2254
- await finish(projected);
2255
- await acknowledge();
2256
- return { status: "completed" };
2257
- }
2258
- await endActiveAgentInvocations(invocation.childConversationId, {
2259
- enqueueResult: options.enqueueResult,
2260
- errorMessage: "This task was not resumed. Newer work for this child agent started, so this task ended without a result.",
2261
- exceptInvocationId: invocation.invocationId
2262
- });
2263
- await supersedeOpenMailboxTurn(invocation.childConversationId);
2264
- invocation = await markAgentInvocationRunning(invocation.invocationId) ?? invocation;
2265
- if (isTerminalAgentInvocation(invocation)) {
2266
- await finish(invocation);
2267
- await acknowledge();
2268
- return { status: "completed" };
2269
- }
2270
- await lifecycle.start({
2271
- conversationId: invocation.childConversationId,
2272
- createdAtMs: invocation.createdAtMs,
2273
- inputMessageIds: [getAgentInvocationMessageId(invocation.invocationId)],
2274
- surface: "internal",
2275
- turnId
2276
- });
2277
- const [persisted, projection, child] = await Promise.all([
2278
- getPersistedThreadState(invocation.childConversationId),
2279
- openConversationProjection({ conversationId: invocation.childConversationId }),
2280
- getConversationStore().get({ conversationId: invocation.childConversationId })
2281
- ]);
2282
- sandboxRef = getPersistedSandboxState(persisted);
2283
- history = invocation.fork && projection.messages.length === 0 ? await loadForkHistory(invocation) : projection.messages;
2284
- location = child?.location;
2285
- } catch (error) {
2286
- if (isInvocationInputCommitLost(error)) return { status: "lost_lease" };
2287
- if (!context.attempt.isFinalAttempt) throw error;
2288
- await finish(await completeAgentInvocation({
2289
- invocationId: invocation.invocationId,
2290
- errorMessage: error instanceof Error ? error.message : "Agent invocation failed",
2291
- status: "failed"
2292
- }));
2293
- await acknowledge();
2294
- return { status: "completed" };
2295
- }
2296
- let outcome;
2297
- try {
2298
- outcome = await executeTurn(agentRunner, {
2299
- conversationId: invocation.childConversationId,
2300
- agentInvocationId: invocation.invocationId,
2301
- parentConversationId: invocation.parentConversationId,
2302
- turnId,
2303
- runId: invocation.invocationId,
2304
- instruction: {
2305
- ...instructionForInputs([{
2306
- kind: "runtime",
2307
- text: agentInvocationInputText(invocation)
2308
- }]),
2309
- provenance: agentInvocationProvenance(invocation)
2310
- },
2311
- history,
2312
- actor: invocation.actor,
2313
- credentialContext: invocation.credentialContext,
2314
- destination: invocation.destination,
2315
- source: invocation.source,
2316
- ...location ? { location } : void 0,
2317
- surface: "internal",
2318
- deadlineAtMs: getTurnRequestDeadline()?.deadlineAtMs,
2319
- ...stopSignal ? { signal: stopSignal } : void 0,
2320
- ...agentInvocationRunPolicy(invocation, canSpawn),
2321
- state: { sandboxRef },
2322
- durability: {
2323
- drainSteeringMessages: createAgentMessageSteeringDrain(context, invocation),
2324
- onInputCommitted: acknowledge,
2325
- shouldYield: context.shouldYield,
2326
- checkIn: context.checkIn,
2327
- checkStop: context.checkStop,
2328
- onSandboxRefChanged: async (nextSandboxRef) => {
2329
- sandboxRef = nextSandboxRef;
2330
- await persistThreadStateById(invocation.childConversationId, { sandboxRef });
2331
- }
2332
- }
2333
- }, async (result) => {
2334
- if (result.diagnostics.outcome !== "success") stopSignal?.throwIfAborted();
2335
- return await saveAgentInvocationResult({
2336
- invocation,
2337
- result,
2338
- sandboxRef,
2339
- sendReply: options.sendReply,
2340
- turnId
2341
- });
2342
- });
2343
- } catch (error) {
2344
- const runError = error instanceof AgentRunError ? error.cause : error;
2345
- if (isInvocationInputCommitLost(runError)) return { status: "lost_lease" };
2346
- if (stopSignal?.aborted) return await finishStopped();
2347
- const blocking = blockingInvocationError(runError);
2348
- if (blocking) {
2349
- await finish(await completeAgentInvocation({
2350
- invocationId: invocation.invocationId,
2351
- errorMessage: blocking.message,
2352
- status: "blocked"
2353
- }));
2354
- await acknowledge();
2355
- return { status: "completed" };
2356
- }
2357
- if (!context.attempt.isFinalAttempt && !isTurnExecutionLimitExceededError(runError)) throw runError;
2358
- await finish(await completeAgentInvocation({
2359
- invocationId: invocation.invocationId,
2360
- errorMessage: runError instanceof Error ? runError.message : "Agent invocation failed",
2361
- status: "failed"
2362
- }));
2363
- await acknowledge();
2364
- return { status: "completed" };
2365
- }
2366
- if (outcome.status !== "completed" && stopSignal?.aborted) return await finishStopped();
2367
- if (outcome.status === "suspended") {
2368
- await markAgentInvocationPaused(invocation.invocationId);
2369
- return { status: "yielded" };
2370
- }
2371
- if (outcome.status === "awaiting_auth") {
2372
- await finish(await completeAgentInvocation({
2373
- invocationId: invocation.invocationId,
2374
- errorMessage: `Agent invocation requires ${outcome.providerDisplayName} authorization`,
2375
- status: "blocked"
2376
- }));
2377
- await acknowledge();
2378
- return { status: "completed" };
2379
- }
2380
- let terminal = await getAgentInvocation(invocation.invocationId);
2381
- if (stopSignal?.aborted) {
2382
- if (terminal && isTerminalAgentInvocation(terminal) && terminal.parentMailboxStatus === "replaced") terminal = await reportReplacedAgentInvocation(terminal.invocationId);
2383
- await stopChildAgentsOf(context.conversationId);
2384
- }
2385
- if (terminal && isTerminalAgentInvocation(terminal)) await report(terminal);
2386
- await acknowledge();
2387
- return { status: "completed" };
2388
- };
2389
- }
2390
- // src/chat/agent-invocations/parent-message.ts
2391
- /**
2392
- * A parent agent task or message to a child that no Agent invocation names.
2393
- * It is an Event from the parent Conversation (`event.identifier`) with the
2394
- * Actor and grants of the parent's Turn, and the `spawnAgent` or
2395
- * `messageAgent` tool call that sent it. Its text is the raw task. `fork`
2396
- * marks the task of a fork spawn.
2397
- */
2398
- const parentMessageSchema = z.object({
2399
- actor: actorSchema,
2400
- credentialContext: credentialContextSchema.optional(),
2401
- event: z.object({
2402
- eventType: z.literal(AGENT_PARENT_MESSAGE_EVENT_TYPE),
2403
- identifier: z.string().min(1),
2404
- namespace: z.literal(AGENT_INVOCATION_EVENT_NAMESPACE)
2405
- }),
2406
- fork: z.literal(true).optional(),
2407
- kind: z.literal("event"),
2408
- parentToolCallId: z.string().min(1)
2409
- });
2410
- /**
2411
- * Return the author id of every parent message from one parent. It matches
2412
- * no other input, so a parent message never shares a Turn with another
2413
- * sender's input.
2414
- */
2415
- function parentMessageAuthorId(parentConversationId) {
2416
- return `parent-agent:${parentConversationId}`;
2417
- }
2418
- /**
2419
- * Read the parent message that one mailbox input is, if it is one. Check its
2420
- * sender with `isFromStoredParent` before it gets any authority.
2421
- */
2422
- function readParentMessage(message) {
2423
- if (message.source !== "event") return;
2424
- const parsed = parentMessageSchema.safeParse(message.input.metadata);
2425
- return parsed.success ? parsed.data : void 0;
2426
- }
2427
- /**
2428
- * Return whether a parent message names the stored parent of the child that
2429
- * received it, with that parent's author id. The caller drops another
2430
- * message.
2431
- */
2432
- async function isFromStoredParent(message, parentMessage) {
2433
- return (message.input.authorId === parentMessageAuthorId(parentMessage.event.identifier) ? await getSqlExecutor().db().select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(eq(juniorConversations.conversationId, message.conversationId), eq(juniorConversations.parentConversationId, parentMessage.event.identifier))) : []).length > 0;
2434
- }
2435
- /**
2436
- * Log a parent message that a child dropped: its sender check failed, or a
2437
- * stop skipped it. Call it once, where the child drops the message.
2438
- */
2439
- function logDroppedParentMessage(message, parentMessage) {
2440
- logWarn("agent.parent_message.dropped", {
2441
- "app.conversation_id": message.conversationId,
2442
- "app.inbound_message_id": message.inboundMessageId,
2443
- "app.parent_conversation_id": parentMessage.event.identifier
2444
- });
2445
- }
2446
- /**
2447
- * Render a parent message as the child model reads it, as an Agent
2448
- * invocation renders its task.
2449
- */
2450
- async function parentMessageText(message, parentMessage) {
2451
- return agentInvocationInputText({
2452
- agentType: (await readAgentConfig(message.conversationId))?.agentType,
2453
- fork: parentMessage.fork,
2454
- input: message.input.text,
2455
- parentToolCallId: parentMessage.parentToolCallId
2456
- });
2457
- }
2458
- /**
2459
- * Return whether a saved transcript Message is a parent message. Only the
2460
- * root Turn code saves one, after its sender check.
2461
- */
2462
- function isParentMessageMeta(meta) {
2463
- return meta?.eventNamespace === "junior" && meta.eventType === "agent.parent_message";
2464
- }
2465
- /**
2466
- * Read when the root Turn code last saved a parent message to one child, or
2467
- * undefined when it saved none.
2468
- */
2469
- async function readLastParentMessageAtMs(conversationId) {
2470
- const payload = juniorConversationEvents.payload;
2471
- const [row] = await getSqlExecutor().db().select({ createdAt: juniorConversationEvents.createdAt }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "message"), sql`${payload}->'meta'->>'eventNamespace' = ${AGENT_INVOCATION_EVENT_NAMESPACE}`, sql`${payload}->'meta'->>'eventType' = ${AGENT_PARENT_MESSAGE_EVENT_TYPE}`)).orderBy(desc(juniorConversationEvents.createdAt)).limit(1);
2472
- return row?.createdAt.getTime();
2473
- }
2474
- /**
2475
- * Apply the agent config of a child agent to one of its Turns on the root
2476
- * Turn code. Every Turn keeps the reasoning level. A fork's first Turn
2477
- * starts with its parent's history. A parent message is the child's
2478
- * instruction, as on an Agent invocation, also when its Turn resumes
2479
- * (`savedParentMessage`). `inputs` passed the sender check.
2480
- */
2481
- async function childAgentTurnOptions(args) {
2482
- const options = await readAgentConfig(args.conversationId);
2483
- const parentMessage = args.inputs.map(readParentMessage).find((input) => input !== void 0);
2484
- return {
2485
- history: parentMessage?.fork && args.history.length === 0 ? await loadForkHistory({
2486
- parentConversationId: parentMessage.event.identifier,
2487
- parentToolCallId: parentMessage.parentToolCallId
2488
- }) : args.history,
2489
- instruction: parentMessage || args.savedParentMessage ? { provenance: agentInstructionProvenance } : {},
2490
- run: options?.reasoningLevel ? { reasoning: options.reasoningLevel } : {}
2491
- };
2492
- }
2493
- // src/chat/agent-invocations/child-input.ts
2494
- /**
2495
- * Read the sender that one result, reply, or message Event names: the
2496
- * finished child work for a result, or the sender for a reply or message.
2497
- */
2498
- function childAgentInput(message) {
2499
- const metadata = message.input.metadata;
2500
- if (!isEventMailboxMetadata(metadata) || metadata.event.namespace !== "junior") return;
2501
- if (metadata.event.eventType === "agent.message") return {
2502
- kind: "message",
2503
- senderId: metadata.event.identifier
2504
- };
2505
- if (metadata.event.eventType === "agent.reply") return {
2506
- kind: "reply",
2507
- senderId: metadata.event.identifier
2508
- };
2509
- return isAgentInvocationResultEventType(metadata.event.eventType) ? {
2510
- kind: "result",
2511
- senderId: metadata.event.identifier
2512
- } : void 0;
2513
- }
2514
- /**
2515
- * Route one input to a Conversation. Routing, the stop skips, and the child
2516
- * agent status all read this, so they agree on which input starts work.
2517
- *
2518
- * A parent task or message goes to its agent invocation. `latest` is the
2519
- * Conversation's newest agent invocation; a root has none. A parent message
2520
- * that no Agent invocation names is dropped when it does not come from the
2521
- * stored parent. With an open Agent invocation, that parent message, a Watch
2522
- * Event, and input from a child agent go to an agent invocation, and so do a
2523
- * result, and input to a child that waits for its own child agents
2524
- * (`replaced`). A stopped child drops input from its own child agents, also
2525
- * input sent before the stop. A session stop at `stoppedAtMs` skips Events
2526
- * as `skipInputAfterConversationStop` does.
2527
- *
2528
- * TODO(dcramer): Drop the agent invocation route with the legacy child worker
2529
- * (#3060 step 7).
2530
- */
2531
- async function routeChildInput(message, latest, stoppedAtMs) {
2532
- if (isPersonInput(message.source)) return "Conversation loop";
2533
- if (isAgentInvocationInput(message)) return "agent invocation";
2534
- const open = latest !== void 0 && !isTerminalAgentInvocation(latest);
2535
- const parentMessage = readParentMessage(message);
2536
- if (parentMessage) {
2537
- if (!await isFromStoredParent(message, parentMessage)) return "dropped";
2538
- if (open) return "agent invocation";
2539
- return isSkippedAfterConversationStop(message, stoppedAtMs) ? "dropped" : "Conversation loop";
2540
- }
2541
- const input = childAgentInput(message);
2542
- if (!input) {
2543
- if (open && isEventMailboxMetadata(message.input.metadata)) return "agent invocation";
2544
- return isSkippedAfterConversationStop(message, stoppedAtMs) ? "dropped" : "Conversation loop";
2545
- }
2546
- if (latest && isStoppedAgentInvocation(latest)) return "dropped";
2547
- if (await isSkippedAgentResult(input, message)) return "dropped";
2548
- if (latest && (open || input.kind === "result" || latest.parentMailboxStatus === "replaced")) return "agent invocation";
2549
- return isSkippedAfterConversationStop(message, stoppedAtMs) ? "dropped" : "Conversation loop";
2550
- }
2551
- /**
2552
- * Return whether a stop skipped this result or reply, so it starts no work.
2553
- * A message that a child sent before its stop is still delivered. A reply
2554
- * that an agent invocation sent names its own work, so it is dropped with
2555
- * that work. A reply from a Turn on the Conversation loop names no work of
2556
- * its own: the stop drops it from the parent's mailbox. While the sending
2557
- * child is stopped, a reply that it sent after the stop is also dropped.
2558
- */
2559
- async function isSkippedAgentResult(input, message) {
2560
- if (input.kind === "message") return false;
2561
- const { invocation, sender } = await getChildAgentInputSender(message, input);
2562
- const skipped = invocation !== void 0 && isTerminalAgentInvocation(invocation) && invocation.parentMailboxStatus === "skipped";
2563
- if (input.kind === "result") return skipped;
2564
- if (skipped) {
2565
- const fields = await readChildMessageSender(message);
2566
- if (!fields || ownAgentInvocation(fields)) return true;
2567
- }
2568
- const senderStoppedAtMs = await getConversationStoppedAtMs(sender.childConversationId);
2569
- return senderStoppedAtMs !== void 0 && message.createdAtMs >= senderStoppedAtMs;
2570
- }
2571
- /**
2572
- * Read the sender of one child Conversation that no Agent invocation names,
2573
- * from its parent edge and its binding. A Conversation without a parent has
2574
- * none.
2575
- */
2576
- async function readChildConversationSender(childConversationId) {
2577
- const parent = alias(juniorConversations, "parent");
2578
- const [row] = await getSqlExecutor().db().select({
2579
- agentName: juniorAgentBindings.name,
2580
- parentConversationId: parent.conversationId,
2581
- title: juniorConversations.title
2582
- }).from(juniorConversations).innerJoin(parent, eq(parent.conversationId, juniorConversations.parentConversationId)).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(eq(juniorConversations.conversationId, childConversationId));
2583
- return row ? {
2584
- ...row.agentName ? { agentName: row.agentName } : void 0,
2585
- childConversationId,
2586
- parentConversationId: row.parentConversationId,
2587
- ...row.title ? { title: row.title } : void 0
2588
- } : void 0;
2589
- }
2590
- /**
2591
- * Read the sender of one result, reply, or message and check that it is a
2592
- * child of the Conversation that received it. The Agent invocation that the
2593
- * input names wins. A reply or message from a child that no Agent invocation
2594
- * names comes from its child Conversation, and has no `invocation`.
2595
- */
2596
- async function getChildAgentInputSender(message, input) {
2597
- const invocation = await getAgentInvocation(input.senderId);
2598
- const sender = invocation ? input.kind === "result" && !isTerminalAgentInvocation(invocation) ? void 0 : invocation : input.kind === "result" ? void 0 : await readChildConversationSender(input.senderId);
2599
- if (!sender || sender.parentConversationId !== message.conversationId) throw new Error(`Agent invocation ${input.kind} ${input.senderId} does not belong to ${message.conversationId}`);
2600
- return invocation ? {
2601
- invocation,
2602
- sender
2603
- } : { sender };
2604
- }
2605
- // src/chat/agent-invocations/store.ts
2606
- /** Statuses of a finished agent invocation. */
2607
- const TERMINAL_AGENT_INVOCATION_STATUSES = [
2608
- "blocked",
2609
- "completed",
2610
- "failed",
2611
- "stopped"
2612
- ];
2613
- /** Statuses of an agent invocation that owns its child's Turn. */
2614
- const ACTIVE_AGENT_INVOCATION_STATUSES = ["running", "paused"];
2615
- /** Statuses of an agent invocation that has not finished. */
2616
- const NON_TERMINAL_AGENT_INVOCATION_STATUSES = [
2617
- "pending",
2618
- "running",
2619
- "paused"
2620
- ];
2621
- /** Parse one agent invocation row. */
2622
- function invocationFromRow(row) {
2623
- return agentInvocationSchema.parse({
2624
- actor: row.actor,
2625
- ...row.agentName ? { agentName: row.agentName } : void 0,
2626
- childConversationId: row.childConversationId,
2627
- createdAtMs: row.createdAt.getTime(),
2628
- ...row.credentialContext ? { credentialContext: row.credentialContext } : void 0,
2629
- destination: row.destination,
2630
- ...row.errorMessage !== null ? { errorMessage: row.errorMessage } : void 0,
2631
- input: row.input,
2632
- invocationId: row.invocationId,
2633
- mailboxStatus: row.mailboxStatus,
2634
- parentConversationId: row.parentConversationId,
2635
- ...row.parentMailboxStatus ? { parentMailboxStatus: row.parentMailboxStatus } : void 0,
2636
- ...row.parentToolCallId ? { parentToolCallId: row.parentToolCallId } : void 0,
2637
- ...row.agentType ? { agentType: row.agentType } : void 0,
2638
- ...row.fork ? { fork: true } : void 0,
2639
- ...row.reasoningLevel ? { reasoningLevel: row.reasoningLevel } : void 0,
2640
- ...row.result !== null ? { result: row.result } : void 0,
2641
- source: row.source,
2642
- status: row.status,
2643
- ...row.terminalAt ? { terminalAtMs: row.terminalAt.getTime() } : void 0,
2644
- ...row.title ? { title: row.title } : void 0,
2645
- updatedAtMs: row.updatedAt.getTime()
2646
- });
2647
- }
2648
- /** Read one durable agent invocation. */
2649
- async function getAgentInvocation(invocationId) {
2650
- const rows = await getSqlExecutor().db().select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.invocationId, invocationId));
2651
- return rows[0] ? invocationFromRow(rows[0]) : void 0;
2652
- }
2653
- /** List the agent invocations of one child Conversation in the given statuses. */
2654
- async function listAgentInvocationsForConversation(childConversationId, statuses) {
2655
- return (await getSqlExecutor().db().select().from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.childConversationId, childConversationId), inArray(juniorAgentInvocations.status, [...statuses]))).orderBy(asc(juniorAgentInvocations.createdAt))).map(invocationFromRow);
2656
- }
2657
- /** Resolve the single invocation that may resume for one child conversation. */
2658
- async function getActiveAgentInvocationForConversation(childConversationId) {
2659
- const active = await listAgentInvocationsForConversation(childConversationId, ACTIVE_AGENT_INVOCATION_STATUSES);
2660
- if (active.length > 1) throw new Error(`Child conversation ${childConversationId} has multiple active agent invocations`);
2661
- return active[0];
2662
- }
2663
- /** Read the newest agent invocation of one child Conversation. */
2664
- async function getLatestAgentInvocationForConversation(childConversationId) {
2665
- const rows = await getSqlExecutor().db().select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, childConversationId)).orderBy(desc(juniorAgentInvocations.createdAt)).limit(1);
2666
- return rows[0] ? invocationFromRow(rows[0]) : void 0;
2667
- }
2668
- /**
2669
- * Read the name, agent type, fork flag, and newest task title of one child
2670
- * Conversation, for labels. Agent invocations that give a nested result to
2671
- * the child have no title, so an agent invocation with a title comes first.
2672
- * Each agent invocation keeps the child's agent type, but only the one that
2673
- * started a fork has `fork` set, so the flag reads every agent invocation.
2674
- * A child that no Agent invocation names reads its binding, title, and
2675
- * agent config.
2676
- */
2677
- async function getChildAgentLabel(childConversationId) {
2678
- const [row] = await getSqlExecutor().db().select({
2679
- agentName: juniorAgentInvocations.agentName,
2680
- agentType: juniorAgentInvocations.agentType,
2681
- fork: sql`bool_or(${juniorAgentInvocations.fork}) over ()`,
2682
- title: juniorAgentInvocations.title
2683
- }).from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, childConversationId)).orderBy(sql`${juniorAgentInvocations.title} is null`, desc(juniorAgentInvocations.createdAt)).limit(1);
2684
- if (row) return row;
2685
- const [sender, options] = await Promise.all([readChildConversationSender(childConversationId), readAgentConfig(childConversationId)]);
2686
- return sender && options ? {
2687
- agentName: sender.agentName ?? null,
2688
- agentType: options.agentType ?? null,
2689
- fork: options.fork ?? false,
2690
- title: sender.title ?? null
2691
- } : void 0;
2692
- }
2693
- /**
2694
- * List the open agent invocations that run on one Conversation or on its
2695
- * child agents, oldest first. Open-work checks read this once and filter it.
2696
- */
2697
- async function listOpenAgentInvocations(conversationId) {
2698
- return (await getSqlExecutor().db().select().from(juniorAgentInvocations).where(and(or(eq(juniorAgentInvocations.childConversationId, conversationId), eq(juniorAgentInvocations.parentConversationId, conversationId)), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES))).orderBy(asc(juniorAgentInvocations.createdAt))).map(invocationFromRow);
2699
- }
2700
- /**
2701
- * Return whether a terminal agent invocation sends its result to the parent.
2702
- * A child's final response stays in its Conversation, and a `reply` that
2703
- * reached the parent (one of `parentMessages`) answered for the Agent
2704
- * invocation. A failure after that, such as a lost worker before the
2705
- * Turn was saved, is not sent either.
2706
- */
2707
- function sendsResultToParent(invocation, parentMessages) {
2708
- const replied = hasAgentInvocationReply(parentMessages, invocation.invocationId);
2709
- switch (invocation.status) {
2710
- case "completed": return !replied && Boolean(invocation.result?.trim());
2711
- case "failed": return !replied;
2712
- default: return true;
2713
- }
2714
- }
2715
- /**
2716
- * Return whether a child Conversation has work that will start another agent
2717
- * invocation on it: another open agent invocation, an open child agent, or a
2718
- * child agent result that is sent but still waits in its mailbox. A child
2719
- * agent that no Agent invocation names is open as `listAgents` shows it,
2720
- * and its unread result or reply also waits.
2721
- */
2722
- async function hasOpenChildWork(invocation) {
2723
- const conversationId = invocation.childConversationId;
2724
- if ((await listOpenAgentInvocations(conversationId)).some((row) => row.invocationId !== invocation.invocationId) || (await listOpenChildAgentsWithoutAgentInvocations(conversationId)).length > 0) return true;
2725
- const work = await getConversationWorkState({ conversationId });
2726
- for (const message of work?.messages ?? []) {
2727
- const sender = await readChildMessageSender(message);
2728
- if (sender && !sender.agentInvocationId) return true;
2729
- }
2730
- const marked = await getSqlExecutor().db().select({
2731
- invocationId: juniorAgentInvocations.invocationId,
2732
- parentMailboxStatus: juniorAgentInvocations.parentMailboxStatus,
2733
- result: juniorAgentInvocations.result,
2734
- status: juniorAgentInvocations.status
2735
- }).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, conversationId), inArray(juniorAgentInvocations.parentMailboxStatus, ["pending", "appended"])));
2736
- if (marked.length === 0) return false;
2737
- const unread = new Set(work?.messages.map((message) => message.inboundMessageId));
2738
- const parentMessages = await listChildMessages(work?.execution.inboundMessageIds ?? [], work?.execution.messageSenders ?? {});
2739
- return marked.some((row) => sendsResultToParent(row, parentMessages) && (row.parentMailboxStatus === "pending" || unread.has(getAgentInvocationResultMessageId(row.invocationId))));
2740
- }
2741
- /** List bounded invocation records whose mailbox append still needs repair. */
2742
- async function listPendingAgentInvocationMailboxAppends(limit = 100) {
2743
- return (await getSqlExecutor().db().select().from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.mailboxStatus, "pending"), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES))).orderBy(asc(juniorAgentInvocations.createdAt)).limit(limit)).map(invocationFromRow);
2744
- }
2745
- /** List terminal agent invocation results that still need a parent mailbox append. */
2746
- async function listPendingAgentInvocationResults(limit = 100) {
2747
- return (await getSqlExecutor().db().select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.parentMailboxStatus, "pending")).orderBy(asc(juniorAgentInvocations.terminalAt)).limit(limit)).map(invocationFromRow).filter(isTerminalAgentInvocation);
2748
- }
2749
- /**
2750
- * Send a `replaced` result to the parent now. A stop ended the open work of
2751
- * the child, so no later agent invocation sends the report.
2752
- */
2753
- async function reportReplacedAgentInvocation(invocationId, nowMs = Date.now()) {
2754
- await getSqlExecutor().db().update(juniorAgentInvocations).set({
2755
- parentMailboxStatus: "pending",
2756
- updatedAt: new Date(nowMs)
2757
- }).where(and(eq(juniorAgentInvocations.invocationId, invocationId), eq(juniorAgentInvocations.parentMailboxStatus, "replaced")));
2758
- return await getAgentInvocation(invocationId);
2759
- }
2760
- /**
2761
- * Send the `replaced` result of a child Conversation when its open child work
2762
- * ended and sent it nothing, such as a helper that ended with `noReply`. No
2763
- * later agent invocation of the child would send the report. Input from its
2764
- * own child agents that still waits in its mailbox starts one, so that one
2765
- * reports instead.
2766
- */
2767
- async function reportReplacedWithoutOpenWork(conversationId, nowMs = Date.now()) {
2768
- const latest = await getLatestAgentInvocationForConversation(conversationId);
2769
- if (!latest || !isTerminalAgentInvocation(latest) || latest.parentMailboxStatus !== "replaced" || await hasOpenChildWork(latest)) return;
2770
- if ((await getConversationWorkState({ conversationId }))?.messages.some(isChildAgentInputMessage)) return;
2771
- return await reportReplacedAgentInvocation(latest.invocationId, nowMs);
2772
- }
2773
- function isChildAgentInputMessage(message) {
2774
- const metadata = message.input.metadata;
2775
- return isEventMailboxMetadata(metadata) && metadata.event.namespace === "junior" && metadata.event.eventType !== "agent.parent_message";
2776
- }
2777
- /** Record that one terminal result is in its parent mailbox. */
2778
- async function markAgentInvocationParentMailboxAppended(invocationId, nowMs = Date.now()) {
2779
- await getSqlExecutor().db().update(juniorAgentInvocations).set({
2780
- parentMailboxStatus: "appended",
2781
- updatedAt: new Date(nowMs)
2782
- }).where(and(eq(juniorAgentInvocations.invocationId, invocationId), eq(juniorAgentInvocations.parentMailboxStatus, "pending")));
2783
- }
2784
- /** Record that the invocation's idempotent mailbox append completed. */
2785
- async function markAgentInvocationMailboxAppended(invocationId, nowMs = Date.now()) {
2786
- await getSqlExecutor().db().update(juniorAgentInvocations).set({
2787
- mailboxStatus: "appended",
2788
- updatedAt: new Date(nowMs)
2789
- }).where(eq(juniorAgentInvocations.invocationId, invocationId));
2790
- }
2791
- /** Mark one non-terminal invocation as actively executing. */
2792
- async function markAgentInvocationRunning(invocationId, nowMs = Date.now()) {
2793
- await getSqlExecutor().db().update(juniorAgentInvocations).set({
2794
- status: "running",
2795
- updatedAt: new Date(nowMs)
2796
- }).where(and(eq(juniorAgentInvocations.invocationId, invocationId), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES)));
2797
- return await getAgentInvocation(invocationId);
2798
- }
2799
- /** Mark one invocation as waiting for another shared execution slice. */
2800
- async function markAgentInvocationPaused(invocationId, nowMs = Date.now()) {
2801
- await getSqlExecutor().db().update(juniorAgentInvocations).set({
2802
- status: "paused",
2803
- updatedAt: new Date(nowMs)
2804
- }).where(and(eq(juniorAgentInvocations.invocationId, invocationId), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES)));
2805
- }
2806
- /**
2807
- * Persist one terminal invocation result without overwriting an earlier
2808
- * result. The same write marks the result for the parent mailbox. If the
2809
- * child still has open work, the result is `replaced`: the parent gets one
2810
- * report, from the agent invocation that finishes the child's work.
2811
- * `reportNow` sends the result even then, when that open work does not
2812
- * continue this task.
2813
- */
2814
- async function completeAgentInvocation(args) {
2815
- const nowMs = args.nowMs ?? Date.now();
2816
- const current = await getAgentInvocation(args.invocationId);
2817
- if (!current || isTerminalAgentInvocation(current)) return current;
2818
- const parentMailboxStatus = !args.reportNow && args.status !== "stopped" && await hasOpenChildWork(current) ? "replaced" : "pending";
2819
- await getSqlExecutor().db().update(juniorAgentInvocations).set({
2820
- status: args.status,
2821
- result: args.status === "completed" ? args.result : null,
2822
- errorMessage: args.status === "completed" ? null : args.errorMessage,
2823
- parentMailboxStatus,
2824
- terminalAt: new Date(nowMs),
2825
- updatedAt: new Date(nowMs)
2826
- }).where(and(eq(juniorAgentInvocations.invocationId, args.invocationId), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES)));
2827
- return await getAgentInvocation(args.invocationId);
2828
- }
2829
- /**
2830
- * End a pending agent invocation whose input the running agent invocation of
2831
- * the same child read as a steering message. The running agent invocation
2832
- * reports for both, so this one is never sent to the parent.
2833
- */
2834
- async function markAgentInvocationSteered(invocationId, nowMs = Date.now()) {
2835
- await getSqlExecutor().db().update(juniorAgentInvocations).set({
2836
- status: "completed",
2837
- result: "",
2838
- parentMailboxStatus: "steered",
2839
- terminalAt: new Date(nowMs),
2840
- updatedAt: new Date(nowMs)
2841
- }).where(and(eq(juniorAgentInvocations.invocationId, invocationId), eq(juniorAgentInvocations.status, "pending")));
2842
- return await getAgentInvocation(invocationId);
2843
- }
2844
- /** Return whether an agent invocation has finished. */
2845
- function isTerminalAgentInvocation(invocation) {
2846
- return TERMINAL_AGENT_INVOCATION_STATUSES.includes(invocation.status);
2847
- }
2848
- /**
2849
- * Return whether the newest agent invocation of a child shows a stop. A tree
2850
- * stop leaves a `replaced` agent invocation with its finished status and
2851
- * marks it `skipped`, so that also means stopped.
2852
- */
2853
- function isStoppedAgentInvocation(invocation) {
2854
- return invocation.status === "stopped" || isTerminalAgentInvocation(invocation) && invocation.parentMailboxStatus === "skipped";
2855
- }
2856
- // src/chat/agent-invocations/list.ts
2857
- function isChildAgentResult(status) {
2858
- return CHILD_AGENT_RESULTS.includes(status);
2859
- }
2860
- const childAgentKindSchema = z.enum(CHILD_AGENT_KINDS);
2861
- /** Bound the agent invocations that one child agent listing reads. */
2862
- const CHILD_AGENT_LIST_INVOCATION_LIMIT = 200;
2863
- const CONVERSATION_LOOP_CHECK_CONCURRENCY = 8;
2864
- /** Return whether a child's session stopped after its latest agent invocation. */
2865
- function isChildAgentSessionStopped(latest, stoppedAtMs) {
2866
- return stoppedAtMs !== void 0 && stoppedAtMs >= latest.createdAtMs;
2867
- }
2868
- /** Return the child state that one child's agent invocations show. */
2869
- function childAgentFromInvocations(invocations, resultInvocationIds, facts) {
2870
- const { stoppedAtMs } = facts;
2871
- const latest = invocations[0];
2872
- let current = invocations.find((invocation) => !isTerminalAgentInvocation(invocation) || invocation.parentMailboxStatus !== "steered") ?? latest;
2873
- for (const invocation of invocations) if (!isTerminalAgentInvocation(invocation)) current = invocation;
2874
- const tasks = invocations.filter((invocation) => invocation.source.kind === "agent_invocation" && !resultInvocationIds.has(invocation.invocationId));
2875
- const task = tasks.find((invocation) => invocation.parentToolCallId) ?? tasks[0] ?? invocations[invocations.length - 1];
2876
- const terminal = isTerminalAgentInvocation(current) ? current : void 0;
2877
- const lastResult = invocations.filter(isTerminalAgentInvocation).filter((invocation) => invocation.parentMailboxStatus !== "replaced" && invocation.parentMailboxStatus !== "skipped" && invocation.parentMailboxStatus !== "steered").map((invocation) => invocation.status).find(isChildAgentResult);
2878
- return {
2879
- ...latest.agentName ? { agentName: latest.agentName } : void 0,
2880
- ...facts.archivedAtMs !== void 0 ? { archivedAtMs: facts.archivedAtMs } : void 0,
2881
- childConversationId: latest.childConversationId,
2882
- ...terminal && terminal.status !== "completed" ? { errorMessage: terminal.errorMessage } : void 0,
2883
- kind: facts.kind,
2884
- ...lastResult ? { lastResult } : void 0,
2885
- status: isChildAgentSessionStopped(latest, stoppedAtMs) ? "stopped" : terminal && facts.onConversationLoop ? "running" : terminal?.parentMailboxStatus === "replaced" ? "pending" : terminal?.parentMailboxStatus === "skipped" ? "stopped" : current.status,
2886
- task: task.input,
2887
- ...task.title ? { title: task.title } : void 0,
2888
- updatedAtMs: Math.max(...invocations.map((invocation) => invocation.updatedAtMs))
2889
- };
2890
- }
2891
- /**
2892
- * List the direct child agents of one parent Conversation, with the newest
2893
- * activity first. The state comes from SQL agent invocation records, not from
2894
- * model output. A child that no agent invocation names shows the state of
2895
- * its Turns and mailbox.
2896
- */
2897
- async function listChildAgents(parentConversationId) {
2898
- const [withInvocations, withoutInvocations] = await Promise.all([listChildAgentsFromInvocations(parentConversationId), listChildAgentsWithoutAgentInvocations(parentConversationId)]);
2899
- return [...withInvocations, ...withoutInvocations].sort((left, right) => right.updatedAtMs - left.updatedAtMs);
2900
- }
2901
- async function listChildAgentsFromInvocations(parentConversationId) {
2902
- const db = getSqlExecutor().db();
2903
- const rows = await db.select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.parentConversationId, parentConversationId)).orderBy(desc(juniorAgentInvocations.createdAt)).limit(CHILD_AGENT_LIST_INVOCATION_LIMIT);
2904
- if (rows.length === 0) return [];
2905
- const byChild = /* @__PURE__ */ new Map();
2906
- for (const invocation of rows.map(invocationFromRow)) {
2907
- const invocations = byChild.get(invocation.childConversationId) ?? [];
2908
- invocations.push(invocation);
2909
- byChild.set(invocation.childConversationId, invocations);
2910
- }
2911
- const grandchildren = await db.select({ invocationId: juniorAgentInvocations.invocationId }).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.parentConversationId, [...byChild.keys()]));
2912
- const resultInvocationIds = new Set(grandchildren.map((row) => getAgentInvocationIdForResult(row.invocationId)));
2913
- const conversations = await db.select({
2914
- archivedAt: juniorConversations.archivedAt,
2915
- conversationId: juniorConversations.conversationId,
2916
- executionStatus: juniorConversations.executionStatus,
2917
- kind: juniorConversations.kind,
2918
- parentConversationId: juniorConversations.parentConversationId,
2919
- stoppedAt: juniorConversations.stoppedAt
2920
- }).from(juniorConversations).where(inArray(juniorConversations.conversationId, [...byChild.keys()]));
2921
- const active = conversations.filter((row) => row.executionStatus === "pending" || row.executionStatus === "running" || row.executionStatus === "paused");
2922
- const activeIds = active.map((row) => row.conversationId);
2923
- const [workStates, mailboxTurnSources] = await Promise.all([getConversationWorkStates(activeIds), listActiveMailboxTurnSources(activeIds)]);
2924
- const limit = pLimit(CONVERSATION_LOOP_CHECK_CONCURRENCY);
2925
- const onConversationLoop = new Set((await Promise.all(active.map((row) => limit(async () => await runsOnConversationLoop(conversationKindFromRow(row), byChild.get(row.conversationId)[0], row.stoppedAt?.getTime(), workStates.get(row.conversationId)?.execution.pendingMessages ?? [], mailboxTurnSources.get(row.conversationId) ?? []) ? row.conversationId : void 0)))).filter((id) => id !== void 0));
2926
- const factsByChild = new Map(conversations.map((row) => [row.conversationId, {
2927
- ...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
2928
- kind: conversationKindFromRow(row) === "thread" ? "thread" : "task",
2929
- ...row.stoppedAt ? { stoppedAtMs: row.stoppedAt.getTime() } : void 0,
2930
- onConversationLoop: onConversationLoop.has(row.conversationId)
2931
- }]));
2932
- return [...byChild.entries()].map(([childConversationId, invocations]) => childAgentFromInvocations(invocations, resultInvocationIds, factsByChild.get(childConversationId) ?? { kind: "task" }));
2933
- }
2934
- /**
2935
- * List the ids of the child agents of one parent that no agent invocation
2936
- * names and that have open work.
2937
- */
2938
- async function listOpenChildAgentsWithoutAgentInvocations(parentConversationId) {
2939
- return (await listChildAgentsWithoutAgentInvocations(parentConversationId)).filter((child) => NON_TERMINAL_AGENT_INVOCATION_STATUSES.includes(child.status)).map((child) => child.childConversationId);
2940
- }
2941
- /**
2942
- * Count the open parent messages of one child that no Agent invocation
2943
- * names: each one that waits in its mailbox, and each open Turn, which runs
2944
- * one. This is the queue that `MAX_OPEN_AGENT_INVOCATIONS_PER_CHILD` caps.
2945
- */
2946
- async function countOpenParentMessages(childConversationId) {
2947
- const [turns, work] = await Promise.all([listActiveMailboxTurns(childConversationId), getConversationWorkState({ conversationId: childConversationId })]);
2948
- return turns.length + (work?.messages ?? []).filter((message) => readParentMessage(message) !== void 0).length;
2949
- }
2950
- /**
2951
- * List the child agents of one parent that no agent invocation names. Each
2952
- * stores its agent config, so older children of a parent, such as ones
2953
- * that a removed feature created, are not listed. A child is `running` while
2954
- * a Turn or mailbox input that answers its parent is open, and is `failed`
2955
- * when its last Turn failed.
2956
- *
2957
- * TODO(dcramer): Make this the only listing when #3060 step 7 drops the
2958
- * agent invocation table.
2959
- */
2960
- async function listChildAgentsWithoutAgentInvocations(parentConversationId) {
2961
- const db = getSqlExecutor().db();
2962
- const rows = await db.select({
2963
- agentName: juniorAgentBindings.name,
2964
- archivedAt: juniorConversations.archivedAt,
2965
- conversationId: juniorConversations.conversationId,
2966
- executionStatus: juniorConversations.executionStatus,
2967
- executionUpdatedAt: juniorConversations.executionUpdatedAt,
2968
- kind: juniorConversations.kind,
2969
- parentConversationId: juniorConversations.parentConversationId,
2970
- stoppedAt: juniorConversations.stoppedAt,
2971
- title: juniorConversations.title,
2972
- updatedAt: juniorConversations.updatedAt
2973
- }).from(juniorConversations).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(and(eq(juniorConversations.parentConversationId, parentConversationId), isNotNull(juniorConversations.agentConfig), notExists(db.select({ invocationId: juniorAgentInvocations.invocationId }).from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, juniorConversations.conversationId))))).limit(CHILD_AGENT_LIST_INVOCATION_LIMIT);
2974
- const ids = rows.map((row) => row.conversationId);
2975
- const [workStates, mailboxTurnSources] = await Promise.all([getConversationWorkStates(ids), listActiveMailboxTurnSources(ids)]);
2976
- const limit = pLimit(CONVERSATION_LOOP_CHECK_CONCURRENCY);
2977
- return await Promise.all(rows.map(async (row) => {
2978
- const kind = childAgentKindSchema.parse(row.kind);
2979
- const stoppedAtMs = row.stoppedAt?.getTime();
2980
- const running = stoppedAtMs === void 0 && await limit(() => runsOnConversationLoop(kind, void 0, void 0, workStates.get(row.conversationId)?.execution.pendingMessages ?? [], mailboxTurnSources.get(row.conversationId) ?? []));
2981
- return {
2982
- ...row.agentName ? { agentName: row.agentName } : void 0,
2983
- ...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
2984
- childConversationId: row.conversationId,
2985
- kind,
2986
- status: stoppedAtMs !== void 0 ? "stopped" : running ? "running" : row.executionStatus === "failed" ? "failed" : "completed",
2987
- task: row.title ?? "",
2988
- ...row.title ? { title: row.title } : void 0,
2989
- updatedAtMs: (row.executionUpdatedAt ?? row.updatedAt).getTime()
2990
- };
2991
- }));
2992
- }
2993
- function answersParent(kind, source) {
2994
- const personInput = isPersonInput(source);
2995
- return !personInput && turnBehavior({
2996
- kind,
2997
- personInput
2998
- }).gated;
2999
- }
3000
- /**
3001
- * Return whether a child whose `latest` agent invocation ended has work on
3002
- * the Conversation loop that will answer its parent: `pending` input that
3003
- * waits in the mailbox until its Turn commits it, such as a Watch Event in
3004
- * its debounce window, or an open mailbox Turn that answers.
3005
- */
3006
- async function runsOnConversationLoop(kind, latest, stoppedAtMs, pending, mailboxTurnSources) {
3007
- for (const message of pending) if (answersParent(kind, message.source) && await routeChildInput(message, latest, stoppedAtMs) === "Conversation loop") return true;
3008
- return mailboxTurnSources.some((source) => answersParent(kind, source?.kind));
3009
- }
3010
- /**
3011
- * List the ids of a child's open Turns on the Conversation loop. A Turn keeps
3012
- * its input in the mailbox until it commits it, so before its first
3013
- * checkpoint its id comes from its first input. Attempt selection can take
3014
- * any pending input first, so each one gives a candidate id.
3015
- */
3016
- async function listOpenLoopTurnIds(conversationId) {
3017
- const [turns, work] = await Promise.all([listActiveMailboxTurns(conversationId), getConversationWorkState({ conversationId })]);
3018
- return [...turns.map((turn) => turn.turnId), ...(work?.execution.pendingMessages ?? []).map((message) => buildDeterministicTurnId(message.inboundMessageId))];
3019
- }
3020
- async function listAnsweredLoopChildren(children, parentMessages) {
3021
- if (children.length === 0 || parentMessages.length === 0) return [];
3022
- return (await Promise.all(children.map(async ({ childConversationId }) => {
3023
- const turnIds = await listOpenLoopTurnIds(childConversationId);
3024
- return parentMessages.some(({ sender }) => sender.conversationId === childConversationId && turnIds.includes(sender.turnId)) ? childConversationId : void 0;
3025
- }))).filter((id) => id !== void 0);
3026
- }
3027
- /**
3028
- * List the other child agents of one parent whose results have not reached
3029
- * the parent yet. A child counts while it runs and after it finishes until its
3030
- * result is appended to the parent mailbox. A running child whose `reply` is
3031
- * already among `parentMessages`, the child replies and results that reached
3032
- * the parent's mailbox, has answered, so it does not count.
3033
- */
3034
- async function listUnreportedSiblingAgents(parentConversationId, childConversationId, parentMessages) {
3035
- const db = getSqlExecutor().db();
3036
- const [children, pendingResults, openInvocations] = await Promise.all([
3037
- listChildAgents(parentConversationId),
3038
- db.select({
3039
- childConversationId: juniorAgentInvocations.childConversationId,
3040
- invocationId: juniorAgentInvocations.invocationId,
3041
- result: juniorAgentInvocations.result,
3042
- status: juniorAgentInvocations.status
3043
- }).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, parentConversationId), eq(juniorAgentInvocations.parentMailboxStatus, "pending"))),
3044
- db.select({
3045
- childConversationId: juniorAgentInvocations.childConversationId,
3046
- invocationId: juniorAgentInvocations.invocationId
3047
- }).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, parentConversationId), inArray(juniorAgentInvocations.status, [...NON_TERMINAL_AGENT_INVOCATION_STATUSES])))
3048
- ]);
3049
- const withPendingResult = new Set(pendingResults.filter((row) => sendsResultToParent(row, parentMessages)).map((row) => row.childConversationId));
3050
- const unanswered = new Set(openInvocations.filter((row) => !hasAgentInvocationReply(parentMessages, row.invocationId)).map((row) => row.childConversationId));
3051
- const answered = new Set(openInvocations.map((row) => row.childConversationId).filter((child) => !unanswered.has(child)));
3052
- for (const child of await listAnsweredLoopChildren(children.filter((child) => child.status === "running" && !openInvocations.some((row) => row.childConversationId === child.childConversationId)), parentMessages)) answered.add(child);
3053
- return children.filter((child) => child.childConversationId !== childConversationId && (NON_TERMINAL_AGENT_INVOCATION_STATUSES.includes(child.status) && !answered.has(child.childConversationId) || withPendingResult.has(child.childConversationId)));
3054
- }
3055
- /**
3056
- * List every child agent below one Conversation, at any depth. A parent owns
3057
- * the work of its child agents and of their child agents. The list never has
3058
- * the Conversation itself, its parent, or a sibling.
3059
- */
3060
- async function listDescendantAgents(conversationId) {
3061
- return (await getSqlExecutor().db().select({
3062
- conversationId: juniorConversations.conversationId,
3063
- name: juniorAgentBindings.name
3064
- }).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) => ({
3065
- conversationId: row.conversationId,
3066
- ...row.name ? { name: row.name } : void 0
3067
- }));
3068
- }
3069
- /**
3070
- * List the agents that one Conversation can see. A root Conversation sees
3071
- * only its child agents. A child agent also sees itself, its parent, and the
3072
- * other child agents of its parent.
3073
- */
3074
- async function listAgentRelatives(input) {
3075
- const { conversationId, parentConversationId } = input;
3076
- const [children, family, parent] = await Promise.all([
3077
- listChildAgents(conversationId),
3078
- parentConversationId ? listChildAgents(parentConversationId) : [],
3079
- parentConversationId ? getConversationStore().get({ conversationId: parentConversationId }) : void 0
3080
- ]);
3081
- const self = family.find((agent) => agent.childConversationId === conversationId);
3082
- return {
3083
- children,
3084
- ...parent ? { parent: {
3085
- conversationId: parent.conversationId,
3086
- status: parent.execution.status,
3087
- updatedAtMs: parent.execution.updatedAtMs ?? parent.updatedAtMs
3088
- } } : void 0,
3089
- ...self ? { self } : void 0,
3090
- siblings: family.filter((agent) => agent.childConversationId !== conversationId)
3091
- };
3092
- }
3093
- // src/chat/cache-warming/waiting.ts
3094
- /**
3095
- * Idle time at which the earliest timer Watch of the Conversation is due,
3096
- * when it is due by `maxDueIdleMs` (`timerFloorMaxDueIdleMs`). A later timer
3097
- * changes nothing, so the idle period warms as without a timer.
3098
- */
3099
- function earliestTimerDueIdleMs(watches, sinceMs, maxDueIdleMs) {
3100
- const dueIdleMs = Math.min(...watches.map((watch) => watch.firesAtMs ?? Infinity)) - sinceMs;
3101
- return dueIdleMs <= maxDueIdleMs ? dueIdleMs : void 0;
3102
- }
3103
- function askedReviewItem(messages, final) {
3104
- for (const message of [final, ...[...messages].reverse()]) {
3105
- if (message.role === "user") return false;
3106
- if (message.role === "assistant" && message.content.some((part) => part.type === "toolCall" && part.name === "addReviewItem")) return true;
3107
- }
3108
- return false;
3109
- }
3110
- /**
3111
- * The active Watches of the Conversation, and what else its idle period
3112
- * waits on. Watches include timers and the event Watches that tools such as
3113
- * `createPullRequest` add. A child agent that still runs comes first: its
3114
- * result starts a Turn without a person. In an Automation run, only a child
3115
- * agent or a Watch can start a later Turn, so a Review item does not count.
3116
- */
3117
- async function readPendingWork(conversationId, messages, final, automation) {
3118
- const [watches, children] = await Promise.all([listWatches({ conversationId }), listChildAgents(conversationId)]);
3119
- if (children.some((child) => NON_TERMINAL_AGENT_INVOCATION_STATUSES.includes(child.status))) return {
3120
- watches,
3121
- waitingOn: "child"
3122
- };
3123
- if (automation) return watches.length > 0 ? {
3124
- watches,
3125
- waitingOn: "watch"
3126
- } : { watches };
3127
- return askedReviewItem(messages, final) ? {
3128
- watches,
3129
- waitingOn: "review"
3130
- } : { watches };
3131
- }
3132
- // src/api/conversations/user-message-activity.ts
3133
- function latestIso(times) {
3134
- const ms = times.flatMap((at) => at ? [at.getTime()] : []);
3135
- return ms.length > 0 ? new Date(Math.max(...ms)).toISOString() : void 0;
3136
- }
3137
- /** Read the latest true user message time for each selected conversation. */
3138
- async function readLastUserMessageAtByConversation(db, conversationIds) {
3139
- if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
3140
- const queries = userMessageQueries(db);
3141
- const instruction = queries.instruction.as("latest_instruction");
3142
- const message = queries.message.as("latest_user_message");
3143
- const rows = await db.select({
3144
- conversationId: juniorConversations.conversationId,
3145
- instructionAt: instruction.createdAt,
3146
- messageAt: message.createdAt
3147
- }).from(juniorConversations).leftJoinLateral(instruction, sql`true`).leftJoinLateral(message, sql`true`).where(inArray(juniorConversations.conversationId, conversationIds));
3148
- const result = /* @__PURE__ */ new Map();
3149
- for (const { conversationId, instructionAt, messageAt } of rows) {
3150
- const at = latestIso([instructionAt, messageAt]);
3151
- if (at) result.set(conversationId, at);
3152
- }
3153
- return result;
3154
- }
3155
- // src/chat/plugins/unfinished-work.ts
3156
- /**
3157
- * Decide whether a conversation's work finished at or before the cutoff,
3158
- * with no person's message after it finished. Auto-archive passes now minus
3159
- * the grace period. A conversation without plugin-reported work has nothing
3160
- * to wait for, so it counts as done here; cache warming needs reported work
3161
- * and checks `assignedWork` itself.
3162
- */
3163
- function isConversationWorkDone(conversation, cutoffMs) {
3164
- if (conversation.unfinishedWork) return false;
3165
- if (!conversation.assignedWork) return true;
3166
- const finishedAt = Date.parse(conversation.finishedWorkAt ?? "");
3167
- if (!Number.isFinite(finishedAt) || finishedAt > cutoffMs) return false;
3168
- const lastUserMessageAt = Date.parse(conversation.lastUserMessageAt ?? "");
3169
- return !(Number.isFinite(lastUserMessageAt) && lastUserMessageAt > finishedAt);
3170
- }
3171
- /**
3172
- * Map each candidate and each child of a candidate root to the candidate it
3173
- * counts for. A child agent runs under its own conversation id, so a plugin
3174
- * links the work that the child does, such as a pull request, to the child.
3175
- */
3176
- async function readWorkOwners(conversationIds) {
3177
- const owners = new Map(conversationIds.map((id) => [id, id]));
3178
- const children = await getDb().select({
3179
- conversationId: juniorConversations.conversationId,
3180
- rootConversationId: juniorConversations.rootConversationId
3181
- }).from(juniorConversations).where(inArray(juniorConversations.rootConversationId, conversationIds));
3182
- for (const child of children) if (child.rootConversationId && !owners.has(child.conversationId)) owners.set(child.conversationId, child.rootConversationId);
3183
- return owners;
3184
- }
3185
- /**
3186
- * Return assigned and unfinished plugin work for the candidate conversations.
3187
- * Work in a child conversation counts for its root candidate. Feed Priority
3188
- * combines these signals with conversation activity on the host.
3189
- */
3190
- async function listConversationWork(conversationIds) {
3191
- if (conversationIds.length === 0) return {
3192
- assignedIds: [],
3193
- failed: false,
3194
- finishedAtById: {},
3195
- unfinishedIds: []
3196
- };
3197
- const owners = await readWorkOwners(conversationIds);
3198
- const queriedIds = [...owners.keys()];
3199
- const assigned = /* @__PURE__ */ new Set();
3200
- const finishedAtById = /* @__PURE__ */ new Map();
3201
- const unfinished = /* @__PURE__ */ new Set();
3202
- let failed = false;
3203
- for (const plugin of getPlugins()) {
3204
- const hook = plugin.hooks?.unfinishedWork;
3205
- if (!hook) continue;
3206
- try {
3207
- const result = await hook({
3208
- conversationIds: queriedIds,
3209
- db: getDb(),
3210
- log: createPluginLogger(plugin.manifest.name),
3211
- plugin: { name: plugin.manifest.name },
3212
- cache: createPluginCache(plugin.manifest.name)
3213
- });
3214
- for (const workId of result.conversationIds) {
3215
- const conversationId = owners.get(workId);
3216
- if (!conversationId) continue;
3217
- unfinished.add(conversationId);
3218
- assigned.add(conversationId);
3219
- }
3220
- for (const workId of result.assignedConversationIds ?? []) {
3221
- const conversationId = owners.get(workId);
3222
- if (conversationId) assigned.add(conversationId);
3223
- }
3224
- for (const [workId, finishedAt] of Object.entries(result.finishedWorkAtByConversationId ?? {})) {
3225
- const conversationId = owners.get(workId);
3226
- if (!conversationId) continue;
3227
- const time = Date.parse(finishedAt);
3228
- if (!Number.isFinite(time)) continue;
3229
- const current = finishedAtById.get(conversationId);
3230
- if (!current || time > Date.parse(current)) finishedAtById.set(conversationId, finishedAt);
3231
- }
3232
- } catch (error) {
3233
- failed = true;
3234
- logWarn("plugin.unfinished_work.hook.failed", {
3235
- "app.plugin.name": plugin.manifest.name,
3236
- "exception.message": error instanceof Error ? error.message : String(error)
3237
- });
3238
- }
3239
- }
3240
- return {
3241
- assignedIds: conversationIds.filter((conversationId) => assigned.has(conversationId)),
3242
- failed,
3243
- finishedAtById: Object.fromEntries(conversationIds.flatMap((conversationId) => {
3244
- const finishedAt = finishedAtById.get(conversationId);
3245
- return finishedAt ? [[conversationId, finishedAt]] : [];
3246
- })),
3247
- unfinishedIds: conversationIds.filter((conversationId) => unfinished.has(conversationId))
3248
- };
3249
- }
3250
- // src/chat/cache-warming/work-state.ts
3251
- /**
3252
- * Read the plugin work state and the archive state of a Conversation when an
3253
- * idle period starts that Junior can warm. Work of child Conversations counts
3254
- * for their root. A child counts as archived when it or its root is: a manual
3255
- * archive also archives the children, but auto-archive sets only the root.
3256
- */
3257
- async function readSegmentState(conversationId, nowMs) {
3258
- const [work, conversation, rootArchived] = await Promise.all([
3259
- listConversationWork([conversationId]),
3260
- getConversationStore().get({ conversationId }),
3261
- rootConversationIsArchived(getSqlExecutor(), conversationId)
3262
- ]);
3263
- const archived = rootArchived || conversation?.archivedAtMs !== void 0;
3264
- if (work.failed || !work.assignedIds.includes(conversationId)) return {
3265
- workState: "none",
3266
- archived
3267
- };
3268
- if (work.unfinishedIds.includes(conversationId)) return {
3269
- workState: "open",
3270
- archived
3271
- };
3272
- const lastUserMessageAt = (await readLastUserMessageAtByConversation(getDb(), [conversationId])).get(conversationId);
3273
- return {
3274
- workState: isConversationWorkDone({
3275
- assignedWork: true,
3276
- finishedWorkAt: work.finishedAtById[conversationId],
3277
- lastUserMessageAt
3278
- }, nowMs) ? "done" : "none",
3279
- archived
3280
- };
3281
- }
3282
- // src/chat/cache-warming/warmup.ts
3283
- /**
3284
- * Prompt cache warming for idle Conversations.
3285
- *
3286
- * After a turn ends, the next human message often arrives after the short
3287
- * prompt cache TTL. Then the full history is written to the cache again. A
3288
- * warmup sends the same request again with a one-token output limit before
3289
- * the cache expires. The provider reads the cached prefix and refreshes its
3290
- * TTL. `model.ts` owns the cost model.
3291
- *
3292
- * Each idle period gets one recorded reply gap, so the model also sees the
3293
- * people who do not reply. A reply records its gap. A delayed `horizon`
3294
- * message records `NO_REPLY_GAP_MS` when no reply came in the idle horizon.
3295
- *
3296
- * Only a Turn writes the Conversation state. Warmups and the horizon run
3297
- * while the next Turn can start, so they write only keys of their own idle
3298
- * period (`generation`): the snapshot, the warmup count, and the gap claim.
3299
- * Work for an old idle period then cannot change a newer one.
3300
- */
3301
- var warmup_exports = /* @__PURE__ */ __exportAll({
3302
- CONVERSATION_STATE_TTL_MS: () => CONVERSATION_STATE_TTL_MS,
3303
- GLOBAL_GAPS_MAX: () => GLOBAL_GAPS_MAX,
3304
- GLOBAL_GAPS_TTL_MS: () => GLOBAL_GAPS_TTL_MS,
3305
- createCacheWarmingRecorder: () => createCacheWarmingRecorder,
3306
- runCacheWarmup: () => runCacheWarmup,
3307
- segmentGapsKey: () => segmentGapsKey
3308
- });
3309
- /** Gaps kept in each segment list. */
3310
- const GLOBAL_GAPS_MAX = 2e3;
3311
- /** A segment list expires this long after its last gap. */
3312
- const GLOBAL_GAPS_TTL_MS = 43200 * MINUTE_MS;
3313
- const CONVERSATION_GAPS_MAX = 50;
3314
- /** The Turn count of a Conversation resets after this long with no call. */
3315
- const CONVERSATION_STATE_TTL_MS = 10080 * MINUTE_MS;
3316
- const ANSWER_TOOL_ENDINGS = {
3317
- [REPLY_TOOL_NAME]: "reply",
3318
- [NO_REPLY_TOOL_NAME]: "no_reply",
3319
- [REPORT_BLOCKED_TOOL_NAME]: "blocked"
3320
- };
3321
- /** State list of the recent reply gaps (ms) of one `gapSegment`. */
3322
- const segmentGapsKey = (segment) => `${KEY_PREFIX}:gaps:${segment}`;
3323
- const conversationKey = (conversationId) => `${KEY_PREFIX}:conversation:${conversationId}`;
3324
- /**
3325
- * Recent reply gaps (ms) of the idle periods of this Conversation, per
3326
- * `gapSegment`. A person's quick replies must not set the return chance of an
3327
- * idle period that a system Turn started.
3328
- */
3329
- const conversationGapsKey = (conversationId, segment) => `${KEY_PREFIX}:gaps:conversation:${conversationId}:${segment}`;
3330
- const snapshotKey = (conversationId, generation) => `${KEY_PREFIX}:snapshot:${conversationId}:${generation}`;
3331
- /** Warmups that completed in the idle period. */
3332
- const warmupsKey = (conversationId, generation) => `${KEY_PREFIX}:warmups:${conversationId}:${generation}`;
3333
- /** Set by the first of the reply and the horizon to record the gap. */
3334
- const gapClaimKey = (conversationId, generation) => `${KEY_PREFIX}:gap_claim:${conversationId}:${generation}`;
3335
- const segmentAttributes = (warm) => ({
3336
- "app.cache_warming.work_state": warm.workState,
3337
- "app.cache_warming.archived": warm.archived,
3338
- ...warm.turnEnding ? { "app.cache_warming.turn_ending": warm.turnEnding } : void 0,
3339
- ...warm.waitingOn ? { "app.cache_warming.waiting_on": warm.waitingOn } : void 0,
3340
- ...warm.timerDueIdleMs !== void 0 ? { "app.cache_warming.timer_due_ms": warm.timerDueIdleMs } : void 0
3341
- });
3342
- const decisionSegment = (warm) => warm.waitingOn ? waitingGapSegment(warm.segment, warm.waitingOn) : warm.segment;
3343
- const recordedSegments = (warm) => warm.waitingOn ? [decisionSegment(warm), warm.segment] : [warm.segment];
3344
- const timerPending = (warm, idleMs) => warm.timerDueIdleMs !== void 0 && idleMs < warm.timerDueIdleMs + 12e4;
3345
- const snapshotAttributes = (size) => ({
3346
- "app.cache_warming.snapshot_bytes": size.bytes,
3347
- "app.cache_warming.snapshot_image_count": size.imageCount,
3348
- "app.cache_warming.snapshot_image_bytes": size.imageBytes
3349
- });
3350
- async function scheduleWarmup(message, requestStartedAtMs, warm) {
3351
- const { cacheExpiresAtMs, delayMs } = warmupTiming(requestStartedAtMs, warm.cacheTtlMs);
3352
- await sendCacheWarmup({
3353
- ...message,
3354
- cacheExpiresAtMs
3355
- }, delayMs);
3356
- }
3357
- async function recordGap(state, conversationId, generation, warm, gapMs) {
3358
- if (!await state.setIfNotExists(gapClaimKey(conversationId, generation), true, CONVERSATION_STATE_TTL_MS)) return;
3359
- for (const segment of recordedSegments(warm)) await state.appendToList(segmentGapsKey(segment), gapMs, {
3360
- maxLength: GLOBAL_GAPS_MAX,
3361
- ttlMs: GLOBAL_GAPS_TTL_MS
3362
- });
3363
- await state.appendToList(conversationGapsKey(conversationId, decisionSegment(warm)), gapMs, {
3364
- maxLength: CONVERSATION_GAPS_MAX,
3365
- ttlMs: CONVERSATION_STATE_TTL_MS
3366
- });
3367
- }
3368
- async function startIdlePeriod(state, conversationId, request, message, turn, systemPrompt, turnEnding) {
3369
- const automation = systemPrompt.mode === "automation";
3370
- const { watches, waitingOn } = await readPendingWork(conversationId, request.context.messages, message, automation);
3371
- if (automation && !waitingOn) return void 0;
3372
- const idle = {
3373
- generation: randomUUID(),
3374
- sinceMs: request.startedAtMs
3375
- };
3376
- const prefixTokens = cachedPrefixTokens(message);
3377
- const ttlMs = cacheTtlMs(request);
3378
- if (ttlMs === void 0 || prefixTokens < 5e4) return idle;
3379
- const timerDueIdleMs = earliestTimerDueIdleMs(watches, idle.sinceMs, timerFloorMaxDueIdleMs({
3380
- cacheReadPrice: request.model.cost.cacheRead,
3381
- cacheWritePrice: request.model.cost.cacheWrite,
3382
- cacheTtlMs: ttlMs
3383
- }));
3384
- 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()));
3385
- const metricOptions = {
3386
- unit: "byte",
3387
- attributes: { "app.cache_warming.stored": skipReason === void 0 }
3388
- };
3389
- sentry_exports.metrics.distribution("cache_warming.snapshot.bytes", snapshot.bytes, metricOptions);
3390
- sentry_exports.metrics.distribution("cache_warming.snapshot.image_bytes", snapshot.imageBytes, metricOptions);
3391
- if (skipReason) {
3392
- logWarn("cache_warming.snapshot.skipped", {
3393
- "app.cache_warming.skip_reason": skipReason,
3394
- "app.cache_warming.prefix_tokens": prefixTokens,
3395
- ...snapshotAttributes(snapshot)
3396
- });
3397
- return idle;
3398
- }
3399
- const segmentState = await readSegmentState(conversationId, Date.now());
3400
- const segmentInput = {
3401
- ...turn,
3402
- ...segmentState
3403
- };
3404
- const parentSegment = parentGapSegment(segmentInput);
3405
- return {
3406
- ...idle,
3407
- warm: {
3408
- segment: gapSegment(segmentInput),
3409
- turnEnding,
3410
- ...parentSegment ? { parentSegment } : void 0,
3411
- ...waitingOn ? { waitingOn } : void 0,
3412
- ...timerDueIdleMs !== void 0 ? { timerDueIdleMs } : void 0,
3413
- ...request.context.systemPrompt !== void 0 ? { systemPrompt: {
3414
- ...systemPrompt,
3415
- hash: systemPromptHash(request.context.systemPrompt)
3416
- } } : void 0,
3417
- ...segmentState,
3418
- modelId: request.model.id,
3419
- prefixTokens,
3420
- cacheTtlMs: ttlMs,
3421
- ...request.reasoning ? { reasoning: request.reasoning } : void 0,
3422
- snapshot
3423
- }
3424
- };
3425
- }
3426
- async function recordModelCall(conversationId, userActor, systemPrompt, request, message, turnEnding) {
3427
- const state = await connectedState();
3428
- const previous = await state.get(conversationKey(conversationId));
3429
- const idle = previous?.idle;
3430
- if (idle?.warm) {
3431
- const gapMs = request.startedAtMs - idle.sinceMs;
3432
- if (gapMs > 0) await recordGap(state, conversationId, idle.generation, idle.warm, gapMs);
3433
- await state.delete(snapshotKey(conversationId, idle.generation));
3434
- const warmups = await state.get(warmupsKey(conversationId, idle.generation)) ?? 0;
3435
- if (warmups > 0) logInfo("cache_warming.conversation.returned", {
3436
- "app.cache_warming.gap_ms": gapMs,
3437
- "app.cache_warming.prefix_tokens": idle.warm.prefixTokens,
3438
- "app.cache_warming.warmup_count": warmups,
3439
- ...segmentAttributes(idle.warm),
3440
- "gen_ai.usage.cache_read.input_tokens": message.usage.cacheRead,
3441
- "gen_ai.usage.cache_creation.input_tokens": message.usage.cacheWrite
3442
- });
3443
- }
3444
- const endedTurns = previous?.endedTurns ?? 0;
3445
- const nextIdle = turnEnding ? await startIdlePeriod(state, conversationId, request, message, {
3446
- userActor,
3447
- endedTurns
3448
- }, systemPrompt, turnEnding) : void 0;
3449
- const next = nextIdle ? {
3450
- endedTurns: endedTurns + 1,
3451
- idle: nextIdle
3452
- } : { endedTurns };
3453
- if (!idle && !next.idle) return;
3454
- await state.set(conversationKey(conversationId), next, CONVERSATION_STATE_TTL_MS);
3455
- if (next.idle?.warm) {
3456
- const { generation } = next.idle;
3457
- await sendCacheWarmup({
3458
- kind: "horizon",
3459
- conversationId,
3460
- generation
3461
- }, request.startedAtMs + IDLE_HORIZON_MS - Date.now());
3462
- await scheduleWarmup({
3463
- kind: "warmup",
3464
- conversationId,
3465
- cycle: 1,
3466
- generation
3467
- }, request.startedAtMs, next.idle.warm);
3468
- }
3469
- }
3470
- async function stopIdleWarmups(conversationId) {
3471
- try {
3472
- const state = await connectedState();
3473
- const idle = (await state.get(conversationKey(conversationId)))?.idle;
3474
- if (idle?.warm) await state.delete(snapshotKey(conversationId, idle.generation));
3475
- } catch (error) {
3476
- logWarn("cache_warming.idle_period.stop_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
3477
- }
3478
- }
3479
- /**
3480
- * Create a recorder for one agent run. `userActor` is true when a person
3481
- * started the Turn. A failure to record only loses cache warming, so it is
3482
- * logged and does not stop the run.
3483
- */
3484
- function createCacheWarmingRecorder(conversationId, userActor, systemPrompt) {
3485
- let lastRequest;
3486
- let lastCall;
3487
- let answerToolEnding;
3488
- let idleEnded = false;
3489
- let warmupsStopped;
3490
- const toolWait = createToolWaitWarmer(conversationId);
3491
- return {
3492
- wrap: (base = streamSimple) => (model, context, options) => {
3493
- if (!warmupsStopped && getChatConfig().cacheWarmingEnabled) warmupsStopped = stopIdleWarmups(conversationId);
3494
- toolWait.stop();
3495
- const cacheRetention = options?.cacheRetention ?? (getChatConfig().cacheWarmingEnabled ? "short" : void 0);
3496
- lastRequest = {
3497
- model,
3498
- context: {
3499
- ...context,
3500
- messages: [...context.messages]
3501
- },
3502
- ...options?.reasoning ? { reasoning: options.reasoning } : void 0,
3503
- ...cacheRetention ? { cacheRetention } : void 0,
3504
- startedAtMs: Date.now()
3505
- };
3506
- return base(model, context, cacheRetention ? {
3507
- ...options,
3508
- cacheRetention
3509
- } : options);
3510
- },
3511
- record: async (message) => {
3512
- const request = lastRequest;
3513
- lastRequest = void 0;
3514
- await warmupsStopped;
3515
- if (!getChatConfig().cacheWarmingEnabled || !request) return;
3516
- try {
3517
- await toolWait.record(request, message);
3518
- } catch (error) {
3519
- logWarn("cache_warming.tool_wait.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
3520
- }
3521
- if (message.stopReason === "error" || message.stopReason === "aborted") return;
3522
- lastCall = {
3523
- request,
3524
- message
3525
- };
3526
- if (idleEnded && message.stopReason !== "stop") return;
3527
- idleEnded = message.stopReason !== "stop";
3528
- try {
3529
- await recordModelCall(conversationId, userActor, systemPrompt, request, message, message.stopReason === "stop" ? "reply" : void 0);
3530
- } catch (error) {
3531
- logWarn("cache_warming.model_call.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
3532
- }
3533
- },
3534
- toolsReturned: toolWait.toolsReturned,
3535
- answerToolEnded: (toolName) => {
3536
- answerToolEnding = ANSWER_TOOL_ENDINGS[toolName];
3537
- },
3538
- stop: async () => {
3539
- try {
3540
- await toolWait.end();
3541
- } catch (error) {
3542
- logWarn("cache_warming.tool_wait.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
3543
- }
3544
- if (!answerToolEnding || !lastCall) return;
3545
- try {
3546
- await recordModelCall(conversationId, userActor, systemPrompt, lastCall.request, lastCall.message, answerToolEnding);
3547
- } catch (error) {
3548
- logWarn("cache_warming.model_call.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
3549
- }
3550
- }
3551
- };
3552
- }
3553
- /**
3554
- * Run one scheduled cache warming message. A message for an idle period that
3555
- * already ended does nothing and makes no span.
3556
- *
3557
- * Each warmup decision has one `cache_warming.warmup` span, with the warmup
3558
- * call as a child `gen_ai.chat` span (`junior.cache_warmup`). A tool wait
3559
- * warmup (`tool-wait.ts`) has the same span in the trace of its Turn.
3560
- * `app.cache_warming.outcome`:
3561
- * - `missed`: the warmup call did not read the cached prefix. It logs
3562
- * `cache_warming.warmup.failed` and reports to Sentry.
3563
- * - `failed`: the warmup call threw.
3564
- * - `skipped`: `skip_reason` is `cache_expired`, `breaker_open`,
3565
- * `prompt_changed` (a deploy changed the system prompt, so the idle period
3566
- * stops), `stopped` (warming stopped or the tools returned first; no log),
3567
- * `image_missing` (an image key of the snapshot expired, so the idle period
3568
- * stops), or a `decideWarmup` reason.
3569
- *
3570
- * Idle warmups carry the sizes of the idle period's snapshot:
3571
- * `snapshot_bytes` (compressed, without images), `snapshot_image_count`
3572
- * (distinct images stored under hash keys), and `snapshot_image_bytes`
3573
- * (their base64 data). A snapshot over a limit stores nothing and warns
3574
- * `cache_warming.snapshot.skipped` with `prefix_tokens`, the same sizes, and
3575
- * `skip_reason` `snapshot_too_large` (still over the limit without its
3576
- * images) or `images_too_large` (its images are over their limit). Each
3577
- * snapshot also records the unsampled distribution metrics
3578
- * `cache_warming.snapshot.bytes` and `cache_warming.snapshot.image_bytes`,
3579
- * with `app.cache_warming.stored` false for a snapshot over a limit.
3580
- *
3581
- * `work_state` and `archived` are read when the idle period starts and pick
3582
- * its `gapSegment`. `turn_ending` is how the Turn before the idle period
3583
- * ended: `reply` (a final response or `reply`), `no_reply` (`noReply`), or
3584
- * `blocked` (`reportBlocked`). `waiting_on` is `child` (a child agent still
3585
- * ran), `review` (the Turn asked a Review item), or `watch` (an Automation
3586
- * run had an active Watch and no child agent) when the idle period starts,
3587
- * and picks the segment's `waitingGapSegment` child. `timer_due_ms`
3588
- * is the idle time at which a timer is due, when it is due within
3589
- * `timerFloorMaxDueIdleMs`. The `conversation.returned` log has the same
3590
- * five. Decision attributes are absent when the warmup skipped before the
3591
- * decision. Of them, `timer_floor` is true for a warmup that only the timer
3592
- * floor sends (`decideWarmup` reason `timer`). Cost and usage are absent
3593
- * when no call completed.
3594
- */
3595
- async function runCacheWarmup(message) {
3596
- const { conversationId } = message;
3597
- const state = await connectedState();
3598
- const idle = (await state.get(conversationKey(conversationId)))?.idle;
3599
- const warm = idle?.warm;
3600
- if (!idle || !warm || idle.generation !== message.generation) return;
3601
- const { generation } = idle;
3602
- const stop = () => state.delete(snapshotKey(conversationId, generation));
3603
- if (message.kind === "horizon") {
3604
- if (!timerPending(warm, Date.now() - idle.sinceMs)) await stop();
3605
- await recordGap(state, conversationId, generation, warm, NO_REPLY_GAP_MS);
3606
- return;
3607
- }
3608
- if ((await state.get(warmupsKey(conversationId, generation)) ?? 0) !== message.cycle - 1) return;
3609
- const attributes = {
3610
- "app.cache_warming.cycle": message.cycle,
3611
- "app.cache_warming.prefix_tokens": warm.prefixTokens,
3612
- "app.cache_warming.trigger": "idle",
3613
- ...segmentAttributes(warm),
3614
- ...warm.snapshot ? snapshotAttributes(warm.snapshot) : void 0,
3615
- "app.cache_warming.cache_ttl_left_ms": message.cacheExpiresAtMs - Date.now()
3616
- };
3617
- await withSpan("cache_warming.warmup", "cache_warming.warmup", {
3618
- conversationId,
3619
- modelId: warm.modelId
3620
- }, async (setSpanAttributes) => {
3621
- const setOutcome = (outcome, extra = {}) => setSpanAttributes({
3622
- ...attributes,
3623
- ...extra,
3624
- "app.cache_warming.outcome": outcome
3625
- });
3626
- const skip = async (reason) => {
3627
- const skipReason = { "app.cache_warming.skip_reason": reason };
3628
- logInfo("cache_warming.warmup.skipped", {
3629
- ...attributes,
3630
- ...skipReason
3631
- });
3632
- setOutcome("skipped", skipReason);
3633
- await stop();
3634
- };
3635
- if (warmupTooLate(message.cacheExpiresAtMs)) {
3636
- await skip("cache_expired");
3637
- return;
3638
- }
3639
- if (await breakerOpen(state, warm.modelId)) {
3640
- await skip("breaker_open");
3641
- return;
3642
- }
3643
- if (warm.systemPrompt && warm.systemPrompt.hash !== systemPromptHash(await buildDeploymentSystemPrompt(warm.systemPrompt.platform, warm.systemPrompt.mode))) {
3644
- await skip("prompt_changed");
3645
- return;
3646
- }
3647
- const model = resolveGatewayModel(warm.modelId);
3648
- const [segment, ...parents] = [...recordedSegments(warm), ...warm.parentSegment ? [warm.parentSegment] : []];
3649
- const globalGapsMs = await state.getList(segmentGapsKey(segment));
3650
- const priorGapsMs = [];
3651
- for (const parent of parents) {
3652
- if (!segmentNeedsParent((priorGapsMs.at(-1) ?? globalGapsMs).length)) break;
3653
- priorGapsMs.push(await state.getList(segmentGapsKey(parent)));
3654
- }
3655
- const decision = decideWarmup({
3656
- conversationGapsMs: await state.getList(conversationGapsKey(conversationId, decisionSegment(warm))),
3657
- globalGapsMs,
3658
- priorGapsMs,
3659
- ...warm.timerDueIdleMs !== void 0 ? { timerDueIdleMs: warm.timerDueIdleMs } : void 0,
3660
- idleMs: Date.now() - idle.sinceMs,
3661
- cacheExpiryIdleMs: message.cacheExpiresAtMs - idle.sinceMs,
3662
- cacheTtlMs: warm.cacheTtlMs,
3663
- prefixTokens: warm.prefixTokens,
3664
- cacheReadPrice: model.cost.cacheRead,
3665
- cacheWritePrice: model.cost.cacheWrite
3666
- });
3667
- attributes["app.cache_warming.return_probability"] = decision.returnProbability;
3668
- attributes["app.cache_warming.returns_per_warmup"] = decision.returnsPerWarmup;
3669
- attributes["app.cache_warming.threshold"] = decision.threshold;
3670
- attributes["app.cache_warming.parent_prior"] = decision.parentPrior;
3671
- attributes["app.cache_warming.timer_floor"] = decision.reason === "timer";
3672
- if (!decision.warm) {
3673
- await skip(decision.reason);
3674
- return;
3675
- }
3676
- const context = await loadSnapshot(state, conversationId, snapshotKey(conversationId, generation));
3677
- if (context === "stopped") {
3678
- setOutcome("skipped", { "app.cache_warming.skip_reason": "stopped" });
3679
- return;
3680
- }
3681
- if (context === "image_missing") {
3682
- await skip("image_missing");
3683
- return;
3684
- }
3685
- const startedAtMs = Date.now();
3686
- const warmup = await sendWarmup(state, {
3687
- conversationId,
3688
- modelId: warm.modelId,
3689
- context,
3690
- ...warm.reasoning ? { reasoning: warm.reasoning } : void 0,
3691
- prefixTokens: warm.prefixTokens
3692
- }).catch(async (error) => {
3693
- setOutcome("failed");
3694
- await stop();
3695
- throw error;
3696
- });
3697
- Object.assign(attributes, warmup.attributes);
3698
- if (!warmup.refreshed) {
3699
- logWarn("cache_warming.warmup.failed", attributes);
3700
- setOutcome("missed");
3701
- await stop();
3702
- return;
3703
- }
3704
- logInfo("cache_warming.warmup.completed", attributes);
3705
- setOutcome("completed");
3706
- await state.set(warmupsKey(conversationId, generation), message.cycle, IDLE_HORIZON_MS);
3707
- if (await state.get(snapshotKey(conversationId, generation))) await scheduleWarmup({
3708
- kind: "warmup",
3709
- conversationId,
3710
- cycle: message.cycle + 1,
3711
- generation
3712
- }, startedAtMs, warm);
3713
- }, attributes);
3714
- }
3715
- export { AgentDepthLimitError as $, readChildConversationSender as A, GAP_SEGMENTS as At, endActiveAgentInvocations as B, listPendingAgentInvocationMailboxAppends as C, deleteWebAuthorization as Ct, sendsResultToParent as D, breakerStates as Dt, reportReplacedWithoutOpenWork as E, executeTurn as Et, parentMessageText as F, gapHistogramReport as Ft, stopChildAgent as G, enqueueAgentInvocation as H, readLastParentMessageAtMs as I, gapSegment as It, cancelSignInWait as J, stopChildAgentsBelow as K, readParentMessage as L, childAgentTurnOptions as M, MINUTE_MS as Mt, isParentMessageMeta as N, MIN_WARMUP_PREFIX_TOKENS as Nt, childAgentInput as O, closeBreaker as Ot, logDroppedParentMessage as P, NO_REPLY_GAP_MS as Pt, createAgentInvocationFromLatest as Q, createAgentInvocationWorker as R, listOpenAgentInvocations as S, createWebAuthorization as St, markAgentInvocationParentMailboxAppended as T, AgentRunError as Tt, resolveAgentInvocationId as U, endAgentInvocationsOfStoppedWork as V, dropOwnUnreadLoopReplies as W, recordSubagentEnded as X, completeCancelledConversationTurn as Y, createAgentInvocationForMessage as Z, getAgentInvocation as _, getTurnAuthorization as _t, segmentGapsKey as a, findChildAgentConversationId as at, isTerminalAgentInvocation as b, isAttemptInterrupt as bt, listConversationWork as c, CHILD_AGENT_RESULTS as ct, listChildAgents as d, supersedeOpenMailboxTurns as dt, AgentInvocationLimitError as et, listDescendantAgents as f, supersedeTurnForInput as ft, getActiveAgentInvocationForConversation as g, wakePausedTurn as gt, TERMINAL_AGENT_INVOCATION_STATUSES as h, wakeAuthorizedTurn as ht, createCacheWarmingRecorder as i, AgentNameInUseError as it, routeChildInput as j, IDLE_HORIZON_MS as jt, getChildAgentInputSender as k, connectedState as kt, readLastUserMessageAtByConversation as l, PARENT_AGENT_TARGET as lt, NON_TERMINAL_AGENT_INVOCATION_STATUSES as m, getPausedTurnRequest as mt, GLOBAL_GAPS_MAX as n, AgentMessageQueueFullError as nt, warmup_exports as o, getAgentBinding as ot, listUnreportedSiblingAgents as p, createPausedTurns as pt, stopChildAgentsOf as q, GLOBAL_GAPS_TTL_MS as r, AgentMessageTargetError as rt, isConversationWorkDone as s, CHILD_AGENT_KINDS as st, CONVERSATION_STATE_TTL_MS as t, AgentMessagePausedError as tt, listAgentRelatives as u, agentNameSchema as ut, getChildAgentLabel as v, canJoinTurn as vt, listPendingAgentInvocationResults as w, getWebAuthorization as wt, listAgentInvocationsForConversation as x, selectAttemptMessages as xt, getLatestAgentInvocationForConversation as y, canShareTurn as yt, createAndEnqueueAgentInvocation as z };