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