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