@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
package/dist/work-yN_GAuXY.js
DELETED
|
@@ -1,768 +0,0 @@
|
|
|
1
|
-
import { H as PluginCredentialFailureError, K as AuthorizationFlowDisabledError, Sn as renderTag, Xt as isTurnExecutionLimitExceededError, at as failTurnRecord, et as lostWorkerBeforeFirstSave, go as loadForkHistory, nt as saveTurnCheckpoint, ot as getTurnRecord, rt as abandonTurnRecord, s as openConversationProjection, tn as getTerminalAssistantMessages, tt as pauseLostWorkerTurn, v as hydrateConversationMessages, vn as escapeClosingTags } from "./projection-BzJQncZV.js";
|
|
2
|
-
import { n as botConfig } from "./config-DvnTPCfp.js";
|
|
3
|
-
import { M as SYSTEM_IDENTITY_ID, a as getConversationStore, r as getConversationEventStore, s as getSqlExecutor } from "./db-Dts2XvLu.js";
|
|
4
|
-
import { g as juniorAgentInvocations, h as juniorAgentBindings } from "./executor-Ck73J0wP.js";
|
|
5
|
-
import { h as contextProvenance, m as agentInstructionProvenance, v as sameActorIdentity } from "./media-BepyEUNm.js";
|
|
6
|
-
import { Dt as stopChildAgentsOf, Gt as finishTurn, Mt as supersedeOpenMailboxTurns, Ot as recordSubagentEnded, Ut as AgentRunError, Wt as executeTurn, an as AgentNameInUseError, kt as recordSubagentStarted, rn as AgentMessageQueueFullError, tn as AgentInvocationLimitError } from "./agent-runner-DjMTPWEO.js";
|
|
7
|
-
import { D as getAssistantReplyText, P as readBlockedReport } from "./warmup-h6u1e9n0.js";
|
|
8
|
-
import { k as getTurnRequestDeadline } from "./background-compaction-queue-DUkHZjmL.js";
|
|
9
|
-
import { $ as getUnnamedAgentConversationId, A as markAgentInvocationPaused, C as isTerminalAgentInvocation, H as agentTypeStartsWithParentHistory, J as getAgentInvocationMessageId, L as agentBindingSchema, M as markAgentInvocationSteered, N as reportReplacedAgentInvocation, O as markAgentInvocationMailboxAppended, Q as getNamedAgentConversationId, T as listOpenAgentInvocations, V as agentTypeInstructions, W as getAgentInvocationId, X as getAgentInvocationTurnId, Z as getChildAgentLockName, _ as completeAgentInvocation, at as getConversationTurnBoundaryError, f as ConversationTurnLifecycleService, g as NON_TERMINAL_AGENT_INVOCATION_STATUSES, h as ACTIVE_AGENT_INVOCATION_STATUSES, j as markAgentInvocationRunning, rt as TurnInputCommitLostError, st as isTurnInputCommitLostError, v as getActiveAgentInvocationForConversation, w as listAgentInvocationsForConversation, x as getLatestAgentInvocationForConversation, y as getAgentInvocation, z as createAgentInvocationSchema } from "./turn-failure-response-BTSo6SMJ.js";
|
|
10
|
-
import { $ as withoutSavedSteeringMessages, B as maybePostAutomatedTurnLimitNotice, K as recordFinishedTurnForAutomatedLimit, X as buildSteeringPiMessage, Z as instructionForInputs, h as parseWebMessages, i as resumeStoppedConversationTree, p as listActiveMailboxTurns, q as resetAutomatedTurnLimit, u as getActiveConversationTurnId } from "./session-stop-DkxI5vc3.js";
|
|
11
|
-
import { r as appendAndEnqueueInboundMessage } from "./store-DgD78_NK.js";
|
|
12
|
-
import { ft as getPersistedSandboxState, gt as coerceThreadConversationState, ht as persistThreadStateById, pt as getPersistedThreadState } from "./task-runner-CKOj6xla.js";
|
|
13
|
-
import { isDeepStrictEqual } from "node:util";
|
|
14
|
-
import * as z from "zod";
|
|
15
|
-
import { and, eq } from "drizzle-orm";
|
|
16
|
-
// src/chat/agent-invocations/bindings.ts
|
|
17
|
-
function bindingFromRow(row) {
|
|
18
|
-
return agentBindingSchema.parse({
|
|
19
|
-
childConversationId: row.childConversationId,
|
|
20
|
-
name: row.name,
|
|
21
|
-
parentConversationId: row.parentConversationId
|
|
22
|
-
});
|
|
23
|
-
}
|
|
24
|
-
/** Read one named child binding in its parent-agent scope. */
|
|
25
|
-
async function getAgentBinding(args) {
|
|
26
|
-
const rows = await getSqlExecutor().db().select().from(juniorAgentBindings).where(and(eq(juniorAgentBindings.parentConversationId, args.parentConversationId), eq(juniorAgentBindings.name, args.name)));
|
|
27
|
-
return rows[0] ? bindingFromRow(rows[0]) : void 0;
|
|
28
|
-
}
|
|
29
|
-
/** Find a direct child agent of one parent by name or child Conversation id. */
|
|
30
|
-
async function findChildAgentConversationId(args) {
|
|
31
|
-
const binding = await getAgentBinding({
|
|
32
|
-
name: args.target,
|
|
33
|
-
parentConversationId: args.parentConversationId
|
|
34
|
-
});
|
|
35
|
-
if (binding) return binding.childConversationId;
|
|
36
|
-
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;
|
|
37
|
-
}
|
|
38
|
-
/**
|
|
39
|
-
* Cap the non-terminal agent invocations of one child, including the one that
|
|
40
|
-
* runs. Each message to a busy child queues one more.
|
|
41
|
-
*/
|
|
42
|
-
const MAX_OPEN_AGENT_INVOCATIONS_PER_CHILD = 4;
|
|
43
|
-
/**
|
|
44
|
-
* Insert one pending agent invocation and read it back. An existing row with
|
|
45
|
-
* the same id wins, so the caller checks that the row it reads is its own.
|
|
46
|
-
*/
|
|
47
|
-
async function insertAgentInvocation(invocation, nowMs) {
|
|
48
|
-
await getSqlExecutor().db().insert(juniorAgentInvocations).values({
|
|
49
|
-
...invocation,
|
|
50
|
-
agentName: invocation.agentName ?? null,
|
|
51
|
-
agentType: invocation.agentType ?? null,
|
|
52
|
-
credentialContext: invocation.credentialContext ?? null,
|
|
53
|
-
parentToolCallId: invocation.parentToolCallId ?? null,
|
|
54
|
-
reasoningLevel: invocation.reasoningLevel ?? null,
|
|
55
|
-
source: invocation.source ?? { kind: "agent_invocation" },
|
|
56
|
-
title: invocation.title ?? null,
|
|
57
|
-
status: "pending",
|
|
58
|
-
mailboxStatus: "pending",
|
|
59
|
-
createdAt: new Date(nowMs),
|
|
60
|
-
updatedAt: new Date(nowMs),
|
|
61
|
-
terminalAt: null
|
|
62
|
-
}).onConflictDoNothing();
|
|
63
|
-
return await getAgentInvocation(invocation.invocationId);
|
|
64
|
-
}
|
|
65
|
-
/**
|
|
66
|
-
* Require every durable creation input to match before replaying one key.
|
|
67
|
-
* The title is not compared: a retry can generate a different one, and the
|
|
68
|
-
* stored title wins.
|
|
69
|
-
*/
|
|
70
|
-
function sameCreateInput(invocation, input) {
|
|
71
|
-
return invocation.parentConversationId === input.parentConversationId && invocation.agentName === input.agentName && invocation.input === input.input && invocation.agentType === input.agentType && 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);
|
|
72
|
-
}
|
|
73
|
-
/**
|
|
74
|
-
* A child agent can only start or give work to child agents while it has
|
|
75
|
-
* open work. A stopped child has none. A root Conversation has no agent
|
|
76
|
-
* invocation, so it always passes. `open` is the parent's open work from
|
|
77
|
-
* `listOpenAgentInvocations`.
|
|
78
|
-
*/
|
|
79
|
-
async function assertCanGiveChildWork(parentConversationId, open) {
|
|
80
|
-
if (!open.some((row) => row.childConversationId === parentConversationId) && await getLatestAgentInvocationForConversation(parentConversationId)) throw new Error(`Agent conversation ${parentConversationId} has no open work and cannot give work to child agents`);
|
|
81
|
-
}
|
|
82
|
-
/**
|
|
83
|
-
* Throw when giving work to one child agent would put its parent over
|
|
84
|
-
* `MAX_ACTIVE_AGENT_INVOCATIONS_PER_PARENT`. A child agent is active while it
|
|
85
|
-
* has open work, so a busy child already counts and messages queued for it
|
|
86
|
-
* do not count again. A new or idle child becomes active. This is the only
|
|
87
|
-
* place the rule for which child agents count lives. `open` is the parent's
|
|
88
|
-
* open work from `listOpenAgentInvocations`.
|
|
89
|
-
*/
|
|
90
|
-
function assertChildAgentCapacity(open, args) {
|
|
91
|
-
const active = new Set(open.filter((row) => row.parentConversationId === args.parentConversationId).map((row) => row.childConversationId));
|
|
92
|
-
if (!active.has(args.childConversationId) && active.size >= 8) throw new AgentInvocationLimitError(8);
|
|
93
|
-
}
|
|
94
|
-
/**
|
|
95
|
-
* Create or replay the first invocation of one new child agent. A name gives
|
|
96
|
-
* the child a stable Conversation id that later messages can address. A name
|
|
97
|
-
* that is already used throws: later work for that child goes through
|
|
98
|
-
* `createAgentInvocationForMessage`.
|
|
99
|
-
*/
|
|
100
|
-
async function createAgentInvocation(rawInput, nowMs = Date.now()) {
|
|
101
|
-
const input = createAgentInvocationSchema.parse(rawInput);
|
|
102
|
-
const invocationId = getAgentInvocationId(input.parentConversationId, input.idempotencyKey);
|
|
103
|
-
const childConversationId = input.agentName ? getNamedAgentConversationId(input.parentConversationId, input.agentName) : getUnnamedAgentConversationId(invocationId);
|
|
104
|
-
const lockName = getChildAgentLockName(input.parentConversationId);
|
|
105
|
-
return await getSqlExecutor().withLock(lockName, async () => {
|
|
106
|
-
const existing = await getAgentInvocation(invocationId);
|
|
107
|
-
if (existing) {
|
|
108
|
-
const child = await getConversationStore().get({ conversationId: existing.childConversationId });
|
|
109
|
-
if (!sameCreateInput(existing, input) || child?.kind !== input.kind) throw new Error(`Agent invocation idempotency key was reused with different input for ${invocationId}`);
|
|
110
|
-
return existing;
|
|
111
|
-
}
|
|
112
|
-
const open = await listOpenAgentInvocations(input.parentConversationId);
|
|
113
|
-
await assertCanGiveChildWork(input.parentConversationId, open);
|
|
114
|
-
if (input.agentName && await getAgentBinding({
|
|
115
|
-
name: input.agentName,
|
|
116
|
-
parentConversationId: input.parentConversationId
|
|
117
|
-
})) throw new AgentNameInUseError(input.agentName);
|
|
118
|
-
assertChildAgentCapacity(open, {
|
|
119
|
-
childConversationId,
|
|
120
|
-
parentConversationId: input.parentConversationId
|
|
121
|
-
});
|
|
122
|
-
await getConversationStore().createChild({
|
|
123
|
-
childConversationId,
|
|
124
|
-
kind: input.kind,
|
|
125
|
-
parentConversationId: input.parentConversationId,
|
|
126
|
-
nowMs,
|
|
127
|
-
source: "internal",
|
|
128
|
-
...input.title ? { title: input.title } : void 0
|
|
129
|
-
});
|
|
130
|
-
if (input.agentName) await getSqlExecutor().db().insert(juniorAgentBindings).values({
|
|
131
|
-
childConversationId,
|
|
132
|
-
name: input.agentName,
|
|
133
|
-
parentConversationId: input.parentConversationId
|
|
134
|
-
});
|
|
135
|
-
const invocation = await insertAgentInvocation({
|
|
136
|
-
actor: input.actor,
|
|
137
|
-
agentName: input.agentName,
|
|
138
|
-
agentType: input.agentType,
|
|
139
|
-
childConversationId,
|
|
140
|
-
credentialContext: input.credentialContext,
|
|
141
|
-
destination: input.destination,
|
|
142
|
-
input: input.input,
|
|
143
|
-
invocationId,
|
|
144
|
-
parentConversationId: input.parentConversationId,
|
|
145
|
-
parentToolCallId: input.parentToolCallId,
|
|
146
|
-
reasoningLevel: input.reasoningLevel,
|
|
147
|
-
title: input.title
|
|
148
|
-
}, nowMs);
|
|
149
|
-
if (!invocation || !sameCreateInput(invocation, input)) throw new Error(`Agent invocation creation raced for ${invocationId}`);
|
|
150
|
-
return invocation;
|
|
151
|
-
});
|
|
152
|
-
}
|
|
153
|
-
/**
|
|
154
|
-
* Create or replay the agent invocation that gives one input to a child
|
|
155
|
-
* Conversation: a result or message from its own child agent, or its own
|
|
156
|
-
* watch events. It continues that Conversation for the same parent as
|
|
157
|
-
* `latest`, and for the same Actor and credentials unless `runAs` sets them.
|
|
158
|
-
* It skips the queue and active-count checks because it continues work that
|
|
159
|
-
* already passed them.
|
|
160
|
-
*/
|
|
161
|
-
async function createAgentInvocationFromLatest(args, nowMs = Date.now()) {
|
|
162
|
-
const { latest } = args;
|
|
163
|
-
const { actor, credentialContext } = args.runAs ?? latest;
|
|
164
|
-
const invocation = await insertAgentInvocation({
|
|
165
|
-
actor,
|
|
166
|
-
agentName: latest.agentName,
|
|
167
|
-
agentType: latest.agentType,
|
|
168
|
-
childConversationId: latest.childConversationId,
|
|
169
|
-
credentialContext,
|
|
170
|
-
destination: latest.destination,
|
|
171
|
-
input: args.input,
|
|
172
|
-
invocationId: args.invocationId,
|
|
173
|
-
parentConversationId: latest.parentConversationId,
|
|
174
|
-
reasoningLevel: latest.reasoningLevel,
|
|
175
|
-
source: args.runAs?.source
|
|
176
|
-
}, nowMs);
|
|
177
|
-
if (!invocation || invocation.childConversationId !== latest.childConversationId) throw new Error(`Agent invocation creation raced for ${args.invocationId}`);
|
|
178
|
-
return invocation;
|
|
179
|
-
}
|
|
180
|
-
/**
|
|
181
|
-
* Create or replay the agent invocation for one message from a parent to one
|
|
182
|
-
* of its child agents. The child continues its history. If the child already
|
|
183
|
-
* has open work, the new agent invocation waits for that work and the parent
|
|
184
|
-
* gets one report for both. A stopped child starts again.
|
|
185
|
-
*/
|
|
186
|
-
async function createAgentInvocationForMessage(input, nowMs = Date.now()) {
|
|
187
|
-
const invocationId = getAgentInvocationId(input.parentConversationId, input.idempotencyKey);
|
|
188
|
-
return await getSqlExecutor().withLock(getChildAgentLockName(input.parentConversationId), async () => {
|
|
189
|
-
const existing = await getAgentInvocation(invocationId);
|
|
190
|
-
if (existing) {
|
|
191
|
-
if (existing.childConversationId !== input.childConversationId || existing.input !== input.input) throw new Error(`Agent invocation idempotency key was reused with different input for ${invocationId}`);
|
|
192
|
-
return {
|
|
193
|
-
invocation: existing,
|
|
194
|
-
queued: existing.status === "pending" && (await listOpenAgentInvocations(input.parentConversationId)).some((row) => row.childConversationId === input.childConversationId && row.createdAtMs < existing.createdAtMs)
|
|
195
|
-
};
|
|
196
|
-
}
|
|
197
|
-
const latest = await getLatestAgentInvocationForConversation(input.childConversationId);
|
|
198
|
-
if (!latest || latest.parentConversationId !== input.parentConversationId) throw new Error(`${input.childConversationId} is not a child agent of ${input.parentConversationId}`);
|
|
199
|
-
const open = await listOpenAgentInvocations(input.parentConversationId);
|
|
200
|
-
await assertCanGiveChildWork(input.parentConversationId, open);
|
|
201
|
-
const openCount = open.filter((row) => row.childConversationId === input.childConversationId).length;
|
|
202
|
-
if (openCount >= MAX_OPEN_AGENT_INVOCATIONS_PER_CHILD) throw new AgentMessageQueueFullError(MAX_OPEN_AGENT_INVOCATIONS_PER_CHILD);
|
|
203
|
-
assertChildAgentCapacity(open, {
|
|
204
|
-
childConversationId: input.childConversationId,
|
|
205
|
-
parentConversationId: input.parentConversationId
|
|
206
|
-
});
|
|
207
|
-
const invocation = await insertAgentInvocation({
|
|
208
|
-
actor: input.actor,
|
|
209
|
-
agentName: latest.agentName,
|
|
210
|
-
agentType: latest.agentType,
|
|
211
|
-
childConversationId: input.childConversationId,
|
|
212
|
-
credentialContext: input.credentialContext,
|
|
213
|
-
destination: input.destination,
|
|
214
|
-
input: input.input,
|
|
215
|
-
invocationId,
|
|
216
|
-
parentConversationId: input.parentConversationId,
|
|
217
|
-
parentToolCallId: input.parentToolCallId,
|
|
218
|
-
reasoningLevel: latest.reasoningLevel
|
|
219
|
-
}, nowMs);
|
|
220
|
-
if (!invocation) throw new Error(`Agent invocation creation raced for ${invocationId}`);
|
|
221
|
-
return {
|
|
222
|
-
invocation,
|
|
223
|
-
queued: openCount > 0
|
|
224
|
-
};
|
|
225
|
-
});
|
|
226
|
-
}
|
|
227
|
-
// src/chat/agent-invocations/thread-turn.ts
|
|
228
|
-
/**
|
|
229
|
-
* A person's Turn in a Thread. People message a Thread like a root, but it
|
|
230
|
-
* stays a child: only a root delivers to its Location, so replies stay in
|
|
231
|
-
* Junior. Agent invocation input and watch Events keep the child worker. A
|
|
232
|
-
* person's Turn and an Agent invocation Turn are never open at the same time.
|
|
233
|
-
*/
|
|
234
|
-
/**
|
|
235
|
-
* Select the person's Turn work of a Thread, or undefined for Agent
|
|
236
|
-
* invocation work. A Thread has one open Turn at a time, like a root. Web
|
|
237
|
-
* Messages start a person's Turn, and an empty wake resumes the open person's
|
|
238
|
-
* Turn. Every other input and wake goes to the child worker.
|
|
239
|
-
*/
|
|
240
|
-
async function resolveThreadTurnWork(context) {
|
|
241
|
-
const batch = parseWebMessages(context.attempt.messages);
|
|
242
|
-
if (batch.length > 0) return {
|
|
243
|
-
kind: "mailbox",
|
|
244
|
-
batch
|
|
245
|
-
};
|
|
246
|
-
if (context.attempt.messages.length > 0) return;
|
|
247
|
-
const turnId = await getActiveConversationTurnId(context.conversationId);
|
|
248
|
-
return turnId ? {
|
|
249
|
-
kind: "resume",
|
|
250
|
-
turnId
|
|
251
|
-
} : void 0;
|
|
252
|
-
}
|
|
253
|
-
/**
|
|
254
|
-
* End a person's open Turn in a Thread before an agent invocation starts, as
|
|
255
|
-
* new input does on a root. Only a Turn that waits for sign-in or lost its
|
|
256
|
-
* worker can be open here: a yielded Turn resumes before new input.
|
|
257
|
-
*/
|
|
258
|
-
async function supersedeOpenPersonTurn(conversationId) {
|
|
259
|
-
if ((await listActiveMailboxTurns(conversationId)).length === 0) return;
|
|
260
|
-
const conversation = coerceThreadConversationState(await getPersistedThreadState(conversationId));
|
|
261
|
-
await hydrateConversationMessages({
|
|
262
|
-
conversation,
|
|
263
|
-
conversationId
|
|
264
|
-
});
|
|
265
|
-
await supersedeOpenMailboxTurns({
|
|
266
|
-
conversation,
|
|
267
|
-
conversationId
|
|
268
|
-
});
|
|
269
|
-
await persistThreadStateById(conversationId, { conversation });
|
|
270
|
-
}
|
|
271
|
-
// src/chat/agent-invocations/work.ts
|
|
272
|
-
const agentInvocationMailboxMetadataSchema = z.object({
|
|
273
|
-
agentInvocationId: z.string().min(1),
|
|
274
|
-
kind: z.literal("agent_invocation")
|
|
275
|
-
}).strict();
|
|
276
|
-
/** Map a durable invocation's model settings and depth to the child Run policy. */
|
|
277
|
-
function agentInvocationRunPolicy(invocation, canSpawn) {
|
|
278
|
-
return {
|
|
279
|
-
disabledFeatures: canSpawn ? ["interactive-auth"] : ["interactive-auth", "subagents"],
|
|
280
|
-
...invocation.reasoningLevel ? { reasoning: invocation.reasoningLevel } : void 0
|
|
281
|
-
};
|
|
282
|
-
}
|
|
283
|
-
/** Build destinationless mailbox work that references one durable invocation. */
|
|
284
|
-
function buildAgentInvocationInboundMessage(invocation, nowMs = Date.now()) {
|
|
285
|
-
return {
|
|
286
|
-
conversationId: invocation.childConversationId,
|
|
287
|
-
createdAtMs: invocation.createdAtMs,
|
|
288
|
-
delivery: "defer",
|
|
289
|
-
inboundMessageId: getAgentInvocationMessageId(invocation.invocationId),
|
|
290
|
-
input: {
|
|
291
|
-
authorId: invocation.invocationId,
|
|
292
|
-
authorIdentityId: SYSTEM_IDENTITY_ID,
|
|
293
|
-
text: "[agent invocation]",
|
|
294
|
-
metadata: {
|
|
295
|
-
agentInvocationId: invocation.invocationId,
|
|
296
|
-
kind: "agent_invocation"
|
|
297
|
-
}
|
|
298
|
-
},
|
|
299
|
-
receivedAtMs: nowMs,
|
|
300
|
-
source: "internal"
|
|
301
|
-
};
|
|
302
|
-
}
|
|
303
|
-
/** Append one invocation to its child mailbox and send the normal queue wake. */
|
|
304
|
-
async function enqueueAgentInvocation(invocation, options) {
|
|
305
|
-
if (invocation.mailboxStatus === "appended" || isTerminalAgentInvocation(invocation)) return;
|
|
306
|
-
await recordSubagentStarted(invocation, options.eventMeta);
|
|
307
|
-
if (invocation.parentToolCallId !== void 0) await resumeStoppedConversationTree(invocation.childConversationId, invocation.createdAtMs);
|
|
308
|
-
const nowMs = options.nowMs ?? Date.now();
|
|
309
|
-
await appendAndEnqueueInboundMessage({
|
|
310
|
-
message: buildAgentInvocationInboundMessage(invocation, nowMs),
|
|
311
|
-
conversationStore: options.conversationStore,
|
|
312
|
-
nowMs,
|
|
313
|
-
queue: options.queue,
|
|
314
|
-
state: options.state
|
|
315
|
-
});
|
|
316
|
-
await markAgentInvocationMailboxAppended(invocation.invocationId, nowMs);
|
|
317
|
-
}
|
|
318
|
-
/** Create or replay an invocation, then durably schedule its child work. */
|
|
319
|
-
async function createAndEnqueueAgentInvocation(input, options) {
|
|
320
|
-
const invocation = await createAgentInvocation(input, options.nowMs);
|
|
321
|
-
await enqueueAgentInvocation(invocation, options);
|
|
322
|
-
return await getAgentInvocation(invocation.invocationId) ?? invocation;
|
|
323
|
-
}
|
|
324
|
-
/** Require one invocation metadata reference for one leased mailbox attempt. */
|
|
325
|
-
function invocationIdFromMessages(messages) {
|
|
326
|
-
if (messages.length === 0) return;
|
|
327
|
-
const parsed = messages.map((message) => agentInvocationMailboxMetadataSchema.safeParse(message.input.metadata));
|
|
328
|
-
if (parsed.every((result) => !result.success)) return;
|
|
329
|
-
if (parsed.some((result) => !result.success)) throw new Error("Conversation mailbox mixes agent invocation and other input");
|
|
330
|
-
const invocationIds = new Set(parsed.map((result) => {
|
|
331
|
-
if (!result.success) throw new Error("Agent invocation mailbox metadata failed validation");
|
|
332
|
-
return result.data.agentInvocationId;
|
|
333
|
-
}));
|
|
334
|
-
if (invocationIds.size !== 1) throw new Error("Conversation mailbox contains multiple agent invocations in one attempt");
|
|
335
|
-
return invocationIds.values().next().value;
|
|
336
|
-
}
|
|
337
|
-
/**
|
|
338
|
-
* Text that the child agent model reads for one agent invocation. A parent
|
|
339
|
-
* agent task or message becomes one `<parent-agent-task>`. Results of the
|
|
340
|
-
* child's own child agents already have their own tag.
|
|
341
|
-
*/
|
|
342
|
-
function agentInvocationInputText(invocation) {
|
|
343
|
-
if (!invocation.parentToolCallId) return invocation.input;
|
|
344
|
-
const typeInstructions = agentTypeInstructions(invocation.agentType);
|
|
345
|
-
return renderTag("parent-agent-task", {}, [...typeInstructions ? [escapeClosingTags(typeInstructions), ""] : [], escapeClosingTags(invocation.input)]);
|
|
346
|
-
}
|
|
347
|
-
/**
|
|
348
|
-
* A parent agent task or message is the child's instruction. Another input,
|
|
349
|
-
* such as a result of the child's own child agent or an Event, is context.
|
|
350
|
-
*/
|
|
351
|
-
function agentInvocationProvenance(invocation) {
|
|
352
|
-
return invocation.parentToolCallId ? agentInstructionProvenance : contextProvenance;
|
|
353
|
-
}
|
|
354
|
-
/** Resolve invocation execution from mailbox input or durable active state. */
|
|
355
|
-
async function resolveAgentInvocationId(context) {
|
|
356
|
-
const mailboxInvocationId = invocationIdFromMessages(context.attempt.messages);
|
|
357
|
-
if (mailboxInvocationId) return mailboxInvocationId;
|
|
358
|
-
if (context.attempt.messages.length > 0) return;
|
|
359
|
-
const active = await getActiveAgentInvocationForConversation(context.conversationId);
|
|
360
|
-
if (active) return active.invocationId;
|
|
361
|
-
return (await getLatestAgentInvocationForConversation(context.conversationId))?.invocationId;
|
|
362
|
-
}
|
|
363
|
-
/**
|
|
364
|
-
* Give queued parent messages to the running agent invocation of a child as
|
|
365
|
-
* steering messages. A message joins only with the Actor and credentials of
|
|
366
|
-
* the running Turn. The first message that does not match stops the scan, so
|
|
367
|
-
* it and every later message wait for the current work. Each message that
|
|
368
|
-
* joins ends as `steered`, and the running agent invocation reports for it.
|
|
369
|
-
*/
|
|
370
|
-
function createAgentMessageSteeringDrain(context, running) {
|
|
371
|
-
const turnId = getAgentInvocationTurnId(running.invocationId);
|
|
372
|
-
return async (accept) => {
|
|
373
|
-
const accepted = [];
|
|
374
|
-
await context.attempt.drain(async (pending) => {
|
|
375
|
-
const readIds = [];
|
|
376
|
-
const joining = [];
|
|
377
|
-
for (const message of pending) {
|
|
378
|
-
const metadata = agentInvocationMailboxMetadataSchema.safeParse(message.input.metadata);
|
|
379
|
-
if (!metadata.success) continue;
|
|
380
|
-
const candidate = await getAgentInvocation(metadata.data.agentInvocationId);
|
|
381
|
-
if (!candidate?.parentToolCallId || candidate.invocationId === running.invocationId) continue;
|
|
382
|
-
if (isTerminalAgentInvocation(candidate)) {
|
|
383
|
-
if (candidate.parentMailboxStatus === "steered") readIds.push(message.inboundMessageId);
|
|
384
|
-
continue;
|
|
385
|
-
}
|
|
386
|
-
if (!sameActorIdentity(candidate.actor, running.actor) || !isDeepStrictEqual(candidate.credentialContext, running.credentialContext)) break;
|
|
387
|
-
joining.push(candidate);
|
|
388
|
-
readIds.push(message.inboundMessageId);
|
|
389
|
-
}
|
|
390
|
-
if (joining.length === 0) return readIds;
|
|
391
|
-
const saved = (await getTurnRecord(running.childConversationId, turnId))?.piMessages ?? [];
|
|
392
|
-
const messages = withoutSavedSteeringMessages(saved, joining.map((candidate) => ({
|
|
393
|
-
kind: "runtime",
|
|
394
|
-
provenance: agentInvocationProvenance(candidate),
|
|
395
|
-
text: agentInvocationInputText(candidate),
|
|
396
|
-
timestampMs: candidate.createdAtMs
|
|
397
|
-
})), buildSteeringPiMessage);
|
|
398
|
-
if (messages.length > 0) {
|
|
399
|
-
await accept(messages);
|
|
400
|
-
accepted.push(...messages);
|
|
401
|
-
}
|
|
402
|
-
for (const candidate of joining) {
|
|
403
|
-
const terminal = await markAgentInvocationSteered(candidate.invocationId);
|
|
404
|
-
if (terminal && isTerminalAgentInvocation(terminal)) await recordSubagentEnded(terminal);
|
|
405
|
-
}
|
|
406
|
-
return readIds;
|
|
407
|
-
}, { deferred: true });
|
|
408
|
-
return accepted;
|
|
409
|
-
};
|
|
410
|
-
}
|
|
411
|
-
/**
|
|
412
|
-
* How a terminal agent invocation ends its child Turn. The live save and the
|
|
413
|
-
* recovery paths both use this, so a status cannot end the Turn two ways.
|
|
414
|
-
*/
|
|
415
|
-
function agentInvocationTurnEnd(terminal) {
|
|
416
|
-
const finishedAtMs = terminal.terminalAtMs;
|
|
417
|
-
switch (terminal.status) {
|
|
418
|
-
case "completed": return {
|
|
419
|
-
finishedAtMs,
|
|
420
|
-
outcome: terminal.result.trim() ? "success" : "no_reply"
|
|
421
|
-
};
|
|
422
|
-
case "stopped": return {
|
|
423
|
-
finishedAtMs,
|
|
424
|
-
outcome: "cancelled"
|
|
425
|
-
};
|
|
426
|
-
case "blocked": return {
|
|
427
|
-
finishedAtMs,
|
|
428
|
-
outcome: "blocked"
|
|
429
|
-
};
|
|
430
|
-
case "failed": return {
|
|
431
|
-
failureCode: "model_execution_failed",
|
|
432
|
-
finishedAtMs,
|
|
433
|
-
outcome: "failed"
|
|
434
|
-
};
|
|
435
|
-
}
|
|
436
|
-
}
|
|
437
|
-
/** Project the terminal invocation into the idempotent turn lifecycle. */
|
|
438
|
-
async function persistTerminalLifecycle(terminal) {
|
|
439
|
-
const turnId = getAgentInvocationTurnId(terminal.invocationId);
|
|
440
|
-
if (terminal.status !== "completed") await abandonTurnRecord({
|
|
441
|
-
conversationId: terminal.childConversationId,
|
|
442
|
-
errorMessage: terminal.status === "stopped" ? "Turn cancelled" : terminal.errorMessage,
|
|
443
|
-
turnId
|
|
444
|
-
});
|
|
445
|
-
await finishTurn(terminal.childConversationId, turnId, agentInvocationTurnEnd(terminal));
|
|
446
|
-
}
|
|
447
|
-
/**
|
|
448
|
-
* Stop an invocation whose worker died, or project its terminal turn result.
|
|
449
|
-
* With `resumeLostWorker`, a Turn whose worker died resumes once from its last
|
|
450
|
-
* save, as a root Turn does. A second loss stops it.
|
|
451
|
-
*/
|
|
452
|
-
async function projectTerminalTurn(invocation, options = {}) {
|
|
453
|
-
const { resumeLostWorker, ...completeOptions } = options;
|
|
454
|
-
let turn = await getTurnRecord(invocation.childConversationId, getAgentInvocationTurnId(invocation.invocationId));
|
|
455
|
-
if (!turn) return;
|
|
456
|
-
if (resumeLostWorker && turn.state === "running" && await pauseLostWorkerTurn(turn)) return;
|
|
457
|
-
if (turn.state === "running" || resumeLostWorker && turn.state === "paused" && lostWorkerBeforeFirstSave(turn)) {
|
|
458
|
-
turn = await failTurnRecord({
|
|
459
|
-
conversationId: turn.conversationId,
|
|
460
|
-
expectedVersion: turn.version,
|
|
461
|
-
turnId: turn.turnId,
|
|
462
|
-
errorMessage: "Agent invocation lost its worker before it could pause"
|
|
463
|
-
});
|
|
464
|
-
if (!turn) return;
|
|
465
|
-
}
|
|
466
|
-
if (turn.state === "paused") return;
|
|
467
|
-
const result = getTerminalAssistantMessages(turn.piMessages).map(getAssistantReplyText).filter((text) => text !== void 0).join("\n\n");
|
|
468
|
-
const failed = turn.state !== "completed" || Boolean(turn.errorMessage);
|
|
469
|
-
const blocked = turn.turnStartMessageIndex === void 0 ? void 0 : readBlockedReport(turn.piMessages.slice(turn.turnStartMessageIndex));
|
|
470
|
-
return await completeAgentInvocation({
|
|
471
|
-
...completeOptions,
|
|
472
|
-
invocationId: invocation.invocationId,
|
|
473
|
-
...failed ? {
|
|
474
|
-
errorMessage: turn.errorMessage ?? "Agent invocation failed",
|
|
475
|
-
status: "failed"
|
|
476
|
-
} : blocked ? {
|
|
477
|
-
errorMessage: blocked.missing,
|
|
478
|
-
status: "blocked"
|
|
479
|
-
} : {
|
|
480
|
-
result,
|
|
481
|
-
status: "completed"
|
|
482
|
-
}
|
|
483
|
-
});
|
|
484
|
-
}
|
|
485
|
-
/**
|
|
486
|
-
* End every running or paused agent invocation of a child before other work
|
|
487
|
-
* opens a Turn there, so the child has one open Turn. A saved finished Turn
|
|
488
|
-
* gives its result. Every other one fails with `errorMessage`, because the
|
|
489
|
-
* newer work does not continue its task. Each reports on its own.
|
|
490
|
-
*/
|
|
491
|
-
async function endActiveAgentInvocations(conversationId, options) {
|
|
492
|
-
for (const active of await listAgentInvocationsForConversation(conversationId, ACTIVE_AGENT_INVOCATION_STATUSES)) {
|
|
493
|
-
if (active.invocationId === options.exceptInvocationId) continue;
|
|
494
|
-
const terminal = await projectTerminalTurn(active, { reportNow: true }) ?? await completeAgentInvocation({
|
|
495
|
-
invocationId: active.invocationId,
|
|
496
|
-
errorMessage: options.errorMessage,
|
|
497
|
-
reportNow: true,
|
|
498
|
-
status: "failed"
|
|
499
|
-
});
|
|
500
|
-
if (terminal && isTerminalAgentInvocation(terminal)) {
|
|
501
|
-
await persistTerminalLifecycle(terminal);
|
|
502
|
-
await recordSubagentEnded(terminal);
|
|
503
|
-
await options.enqueueResult?.(terminal);
|
|
504
|
-
}
|
|
505
|
-
}
|
|
506
|
-
}
|
|
507
|
-
/**
|
|
508
|
-
* End every agent invocation of a child whose last attempt lost its worker and
|
|
509
|
-
* whose input reached the child's mailbox. The worker ran no failure path, and
|
|
510
|
-
* the stop drops the mailbox, so none of them can run. The heartbeat sends
|
|
511
|
-
* each result.
|
|
512
|
-
*/
|
|
513
|
-
async function endAgentInvocationsOfStoppedWork(conversationId, inboundMessageIds) {
|
|
514
|
-
for (const invocation of await listAgentInvocationsForConversation(conversationId, NON_TERMINAL_AGENT_INVOCATION_STATUSES)) {
|
|
515
|
-
if (!inboundMessageIds.includes(getAgentInvocationMessageId(invocation.invocationId))) continue;
|
|
516
|
-
const terminal = await projectTerminalTurn(invocation, { reportNow: true }) ?? await completeAgentInvocation({
|
|
517
|
-
invocationId: invocation.invocationId,
|
|
518
|
-
errorMessage: "This task stopped because its worker failed repeatedly.",
|
|
519
|
-
reportNow: true,
|
|
520
|
-
status: "failed"
|
|
521
|
-
});
|
|
522
|
-
if (terminal && isTerminalAgentInvocation(terminal)) await persistTerminalLifecycle(terminal);
|
|
523
|
-
}
|
|
524
|
-
}
|
|
525
|
-
/** Classify authorization failures that terminally block background work. */
|
|
526
|
-
function blockingInvocationError(error) {
|
|
527
|
-
const cause = getConversationTurnBoundaryError(error)?.cause ?? error;
|
|
528
|
-
return cause instanceof AuthorizationFlowDisabledError || cause instanceof PluginCredentialFailureError ? cause : void 0;
|
|
529
|
-
}
|
|
530
|
-
function isInvocationInputCommitLost(error) {
|
|
531
|
-
const cause = getConversationTurnBoundaryError(error)?.cause ?? error;
|
|
532
|
-
return isTurnInputCommitLostError(cause);
|
|
533
|
-
}
|
|
534
|
-
/** Save one completed agent result on its child agent invocation. */
|
|
535
|
-
async function saveAgentInvocationResult(args) {
|
|
536
|
-
const failed = args.result.diagnostics.outcome !== "success";
|
|
537
|
-
await persistThreadStateById(args.invocation.childConversationId, { sandboxRef: args.result.sandboxRef ?? args.sandboxRef });
|
|
538
|
-
if (args.result.piMessages?.length) await saveTurnCheckpoint({
|
|
539
|
-
mode: "completed",
|
|
540
|
-
conversationId: args.invocation.childConversationId,
|
|
541
|
-
turnId: args.turnId,
|
|
542
|
-
durationMs: args.result.diagnostics.durationMs,
|
|
543
|
-
usage: args.result.diagnostics.usage,
|
|
544
|
-
destination: args.invocation.destination,
|
|
545
|
-
...failed ? { errorMessage: args.result.diagnostics.errorMessage ?? "Agent invocation failed" } : void 0,
|
|
546
|
-
messages: args.result.piMessages,
|
|
547
|
-
actor: args.invocation.actor,
|
|
548
|
-
source: args.invocation.source,
|
|
549
|
-
surface: "internal"
|
|
550
|
-
});
|
|
551
|
-
if (args.invocation.parentToolCallId) await resetAutomatedTurnLimit({ conversationId: args.invocation.childConversationId });
|
|
552
|
-
else if (args.invocation.source.kind !== "agent_invocation") {
|
|
553
|
-
const maxTurns = botConfig.maxConsecutiveAutomatedTurns;
|
|
554
|
-
await maybePostAutomatedTurnLimitNotice({
|
|
555
|
-
conversationId: args.invocation.childConversationId,
|
|
556
|
-
maxTurns,
|
|
557
|
-
update: await recordFinishedTurnForAutomatedLimit({
|
|
558
|
-
conversationId: args.invocation.childConversationId,
|
|
559
|
-
maxTurns,
|
|
560
|
-
source: args.invocation.source
|
|
561
|
-
})
|
|
562
|
-
});
|
|
563
|
-
}
|
|
564
|
-
const terminal = await completeAgentInvocation({
|
|
565
|
-
invocationId: args.invocation.invocationId,
|
|
566
|
-
...failed ? {
|
|
567
|
-
errorMessage: args.result.diagnostics.errorMessage ?? "Agent invocation failed",
|
|
568
|
-
status: "failed"
|
|
569
|
-
} : args.result.blocked ? {
|
|
570
|
-
errorMessage: args.result.blocked.missing,
|
|
571
|
-
status: "blocked"
|
|
572
|
-
} : {
|
|
573
|
-
result: args.result.text || (args.result.noReply?.note ?? ""),
|
|
574
|
-
status: "completed"
|
|
575
|
-
}
|
|
576
|
-
});
|
|
577
|
-
if (!terminal || !isTerminalAgentInvocation(terminal)) throw new Error(`Agent invocation did not finish for ${args.invocation.invocationId}`);
|
|
578
|
-
return agentInvocationTurnEnd(terminal);
|
|
579
|
-
}
|
|
580
|
-
/**
|
|
581
|
-
* Build the invocation consumer that advances work through the shared runner.
|
|
582
|
-
* `enqueueResult` sends each terminal result to the parent mailbox. Omit it
|
|
583
|
-
* only where the parent has no mailbox, such as the local CLI.
|
|
584
|
-
* `maxAgentDepth` is the number of child agent levels that can start their
|
|
585
|
-
* own child agents. The default, 0, lets only the root start child agents.
|
|
586
|
-
*/
|
|
587
|
-
function createAgentInvocationWorker(agentRunner, options = {}) {
|
|
588
|
-
const canSpawn = (options.maxAgentDepth ?? 0) > 0;
|
|
589
|
-
return async (context, invocationId) => {
|
|
590
|
-
let invocation = await getAgentInvocation(invocationId);
|
|
591
|
-
if (!invocation) throw new Error(`Agent invocation is missing for ${invocationId}`);
|
|
592
|
-
const report = async (terminal) => {
|
|
593
|
-
await recordSubagentEnded(terminal);
|
|
594
|
-
await options.enqueueResult?.(terminal);
|
|
595
|
-
};
|
|
596
|
-
const finish = async (terminal) => {
|
|
597
|
-
if (!terminal || !isTerminalAgentInvocation(terminal)) return;
|
|
598
|
-
if (terminal.parentMailboxStatus !== "steered") await persistTerminalLifecycle(terminal);
|
|
599
|
-
await report(terminal);
|
|
600
|
-
};
|
|
601
|
-
let acknowledged = context.attempt.messages.length === 0;
|
|
602
|
-
const acknowledge = async () => {
|
|
603
|
-
if (acknowledged) return;
|
|
604
|
-
try {
|
|
605
|
-
await context.attempt.ack();
|
|
606
|
-
} catch {
|
|
607
|
-
throw new TurnInputCommitLostError(`Conversation work lease lost before invocation inbox ack for ${context.conversationId}`);
|
|
608
|
-
}
|
|
609
|
-
acknowledged = true;
|
|
610
|
-
};
|
|
611
|
-
const stopSignal = context.stopSignal?.();
|
|
612
|
-
const finishStopped = async () => {
|
|
613
|
-
await finish(await completeAgentInvocation({
|
|
614
|
-
invocationId,
|
|
615
|
-
errorMessage: "Agent invocation was stopped",
|
|
616
|
-
status: "stopped"
|
|
617
|
-
}));
|
|
618
|
-
await stopChildAgentsOf(context.conversationId);
|
|
619
|
-
await acknowledge();
|
|
620
|
-
return { status: "completed" };
|
|
621
|
-
};
|
|
622
|
-
const turnId = getAgentInvocationTurnId(invocation.invocationId);
|
|
623
|
-
const lifecycle = new ConversationTurnLifecycleService(getConversationEventStore());
|
|
624
|
-
let sandboxRef;
|
|
625
|
-
let history;
|
|
626
|
-
let location;
|
|
627
|
-
try {
|
|
628
|
-
if (invocation.childConversationId !== context.conversationId) throw new Error(`Agent invocation ${invocationId} belongs to ${invocation.childConversationId}, not ${context.conversationId}`);
|
|
629
|
-
if (context.destination) throw new Error(`Agent invocation conversation ${context.conversationId} must not own a provider destination`);
|
|
630
|
-
if (isTerminalAgentInvocation(invocation)) {
|
|
631
|
-
await finish(invocation);
|
|
632
|
-
await acknowledge();
|
|
633
|
-
return { status: "completed" };
|
|
634
|
-
}
|
|
635
|
-
const projected = await projectTerminalTurn(invocation, { resumeLostWorker: true });
|
|
636
|
-
if (projected && isTerminalAgentInvocation(projected)) {
|
|
637
|
-
await finish(projected);
|
|
638
|
-
await acknowledge();
|
|
639
|
-
return { status: "completed" };
|
|
640
|
-
}
|
|
641
|
-
await endActiveAgentInvocations(invocation.childConversationId, {
|
|
642
|
-
enqueueResult: options.enqueueResult,
|
|
643
|
-
errorMessage: "This task was not resumed. Newer work for this child agent started, so this task ended without a result.",
|
|
644
|
-
exceptInvocationId: invocation.invocationId
|
|
645
|
-
});
|
|
646
|
-
await supersedeOpenPersonTurn(invocation.childConversationId);
|
|
647
|
-
invocation = await markAgentInvocationRunning(invocation.invocationId) ?? invocation;
|
|
648
|
-
if (isTerminalAgentInvocation(invocation)) {
|
|
649
|
-
await finish(invocation);
|
|
650
|
-
await acknowledge();
|
|
651
|
-
return { status: "completed" };
|
|
652
|
-
}
|
|
653
|
-
await lifecycle.start({
|
|
654
|
-
conversationId: invocation.childConversationId,
|
|
655
|
-
createdAtMs: invocation.createdAtMs,
|
|
656
|
-
inputMessageIds: [getAgentInvocationMessageId(invocation.invocationId)],
|
|
657
|
-
surface: "internal",
|
|
658
|
-
turnId
|
|
659
|
-
});
|
|
660
|
-
const [persisted, projection, child] = await Promise.all([
|
|
661
|
-
getPersistedThreadState(invocation.childConversationId),
|
|
662
|
-
openConversationProjection({ conversationId: invocation.childConversationId }),
|
|
663
|
-
getConversationStore().get({ conversationId: invocation.childConversationId })
|
|
664
|
-
]);
|
|
665
|
-
sandboxRef = getPersistedSandboxState(persisted);
|
|
666
|
-
history = agentTypeStartsWithParentHistory(invocation.agentType) && projection.messages.length === 0 ? await loadForkHistory(invocation) : projection.messages;
|
|
667
|
-
location = child?.location;
|
|
668
|
-
} catch (error) {
|
|
669
|
-
if (isInvocationInputCommitLost(error)) return { status: "lost_lease" };
|
|
670
|
-
if (!context.attempt.isFinalAttempt) throw error;
|
|
671
|
-
await finish(await completeAgentInvocation({
|
|
672
|
-
invocationId: invocation.invocationId,
|
|
673
|
-
errorMessage: error instanceof Error ? error.message : "Agent invocation failed",
|
|
674
|
-
status: "failed"
|
|
675
|
-
}));
|
|
676
|
-
await acknowledge();
|
|
677
|
-
return { status: "completed" };
|
|
678
|
-
}
|
|
679
|
-
let outcome;
|
|
680
|
-
try {
|
|
681
|
-
outcome = await executeTurn(agentRunner, {
|
|
682
|
-
conversationId: invocation.childConversationId,
|
|
683
|
-
agentInvocationId: invocation.invocationId,
|
|
684
|
-
parentConversationId: invocation.parentConversationId,
|
|
685
|
-
turnId,
|
|
686
|
-
runId: invocation.invocationId,
|
|
687
|
-
instruction: {
|
|
688
|
-
...instructionForInputs([{
|
|
689
|
-
kind: "runtime",
|
|
690
|
-
text: agentInvocationInputText(invocation)
|
|
691
|
-
}]),
|
|
692
|
-
provenance: agentInvocationProvenance(invocation)
|
|
693
|
-
},
|
|
694
|
-
history,
|
|
695
|
-
actor: invocation.actor,
|
|
696
|
-
credentialContext: invocation.credentialContext,
|
|
697
|
-
destination: invocation.destination,
|
|
698
|
-
source: invocation.source,
|
|
699
|
-
...location ? { location } : void 0,
|
|
700
|
-
surface: "internal",
|
|
701
|
-
deadlineAtMs: getTurnRequestDeadline()?.deadlineAtMs,
|
|
702
|
-
...stopSignal ? { signal: stopSignal } : void 0,
|
|
703
|
-
...agentInvocationRunPolicy(invocation, canSpawn),
|
|
704
|
-
state: { sandboxRef },
|
|
705
|
-
durability: {
|
|
706
|
-
drainSteeringMessages: createAgentMessageSteeringDrain(context, invocation),
|
|
707
|
-
onInputCommitted: acknowledge,
|
|
708
|
-
shouldYield: context.shouldYield,
|
|
709
|
-
checkIn: context.checkIn,
|
|
710
|
-
onSandboxRefChanged: async (nextSandboxRef) => {
|
|
711
|
-
sandboxRef = nextSandboxRef;
|
|
712
|
-
await persistThreadStateById(invocation.childConversationId, { sandboxRef });
|
|
713
|
-
}
|
|
714
|
-
}
|
|
715
|
-
}, async (result) => await saveAgentInvocationResult({
|
|
716
|
-
invocation,
|
|
717
|
-
result,
|
|
718
|
-
sandboxRef,
|
|
719
|
-
turnId
|
|
720
|
-
}));
|
|
721
|
-
} catch (error) {
|
|
722
|
-
const runError = error instanceof AgentRunError ? error.cause : error;
|
|
723
|
-
if (isInvocationInputCommitLost(runError)) return { status: "lost_lease" };
|
|
724
|
-
if (stopSignal?.aborted) return await finishStopped();
|
|
725
|
-
const blocking = blockingInvocationError(runError);
|
|
726
|
-
if (blocking) {
|
|
727
|
-
await finish(await completeAgentInvocation({
|
|
728
|
-
invocationId: invocation.invocationId,
|
|
729
|
-
errorMessage: blocking.message,
|
|
730
|
-
status: "blocked"
|
|
731
|
-
}));
|
|
732
|
-
await acknowledge();
|
|
733
|
-
return { status: "completed" };
|
|
734
|
-
}
|
|
735
|
-
if (!context.attempt.isFinalAttempt && !isTurnExecutionLimitExceededError(runError)) throw runError;
|
|
736
|
-
await finish(await completeAgentInvocation({
|
|
737
|
-
invocationId: invocation.invocationId,
|
|
738
|
-
errorMessage: runError instanceof Error ? runError.message : "Agent invocation failed",
|
|
739
|
-
status: "failed"
|
|
740
|
-
}));
|
|
741
|
-
await acknowledge();
|
|
742
|
-
return { status: "completed" };
|
|
743
|
-
}
|
|
744
|
-
if (outcome.status !== "completed" && stopSignal?.aborted) return await finishStopped();
|
|
745
|
-
if (outcome.status === "suspended") {
|
|
746
|
-
await markAgentInvocationPaused(invocation.invocationId);
|
|
747
|
-
return { status: "yielded" };
|
|
748
|
-
}
|
|
749
|
-
if (outcome.status === "awaiting_auth") {
|
|
750
|
-
await finish(await completeAgentInvocation({
|
|
751
|
-
invocationId: invocation.invocationId,
|
|
752
|
-
errorMessage: `Agent invocation requires ${outcome.providerDisplayName} authorization`,
|
|
753
|
-
status: "blocked"
|
|
754
|
-
}));
|
|
755
|
-
await acknowledge();
|
|
756
|
-
return { status: "completed" };
|
|
757
|
-
}
|
|
758
|
-
let terminal = await getAgentInvocation(invocation.invocationId);
|
|
759
|
-
if (stopSignal?.aborted) {
|
|
760
|
-
if (terminal && isTerminalAgentInvocation(terminal) && terminal.parentMailboxStatus === "replaced") terminal = await reportReplacedAgentInvocation(terminal.invocationId);
|
|
761
|
-
await stopChildAgentsOf(context.conversationId);
|
|
762
|
-
}
|
|
763
|
-
if (terminal && isTerminalAgentInvocation(terminal)) await report(terminal);
|
|
764
|
-
await acknowledge();
|
|
765
|
-
return { status: "completed" };
|
|
766
|
-
};
|
|
767
|
-
}
|
|
768
|
-
export { enqueueAgentInvocation as a, createAgentInvocationForMessage as c, endAgentInvocationsOfStoppedWork as i, createAgentInvocationFromLatest as l, createAndEnqueueAgentInvocation as n, resolveAgentInvocationId as o, endActiveAgentInvocations as r, resolveThreadTurnWork as s, createAgentInvocationWorker as t, findChildAgentConversationId as u };
|