@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,805 @@
|
|
|
1
|
+
import { i as getActiveSpan, r as continueTrace, v as __exportAll } from "./sentry-BRTJqumy.js";
|
|
2
|
+
import { A as latestConversationMessageSeq, I as upsertConversationMessage, M as normalizeConversationText, N as recordDeliveredAssistantMessage, _i as verifyTimerWatchCredentialSubject, a as loadProjection, an as getAssistantReplyText, at as failTurnRecord, b as persistConversationMessages, j as markConversationMessage, mn as persistWithRetry, nt as saveTurnCheckpoint, ot as getTurnRecord, t as commitAcceptedReply, v as hydrateConversationMessages } from "./projection-B08mfi0u.js";
|
|
3
|
+
import { n as botConfig } from "./config-Dj9M_nqB.js";
|
|
4
|
+
import { E as withSpan, S as setTags, h as logWarn, p as logException } from "./logging-CQjlDQYX.js";
|
|
5
|
+
import { D as turnBehavior, T as isTopLevelKind, a as getConversationStore, et as nextDetailVersion, o as getDb, r as getConversationEventStore, s as getSqlExecutor, w as isPersonInput } from "./db-Br0tfAo7.js";
|
|
6
|
+
import { A as juniorConversations } from "./executor-BMPipFVA.js";
|
|
7
|
+
import { _ as instructionProvenanceFor } from "./media-BepyEUNm.js";
|
|
8
|
+
import { f as credentialContextForActor } from "./registry-BDWgCJDf.js";
|
|
9
|
+
import { gt as resolveConversationDestination, i as measureTurnCompactionWait } from "./agent-runner-CneTquAE.js";
|
|
10
|
+
import { o as isEventConversationMessage } from "./prompt-BlutWLNt.js";
|
|
11
|
+
import { H as readMessageAttachments } from "./conversation-CvcBU1z2.js";
|
|
12
|
+
import { C as legacyWebMailboxMetadataSchema, S as turnInputFactsFromConversationMessage, _ as getEventBatchDelayMs, l as withoutSavedSteeringMessages, n as loadReviewItemInput, o as buildSteeringPiMessage, s as instructionForInputs, t as eventReviewItemInputs, x as sourceFromTurnInput } from "./prompt-input-Dxn8cDC0.js";
|
|
13
|
+
import { _ as ConversationTurnLifecycleService, d as isTurnInputCommitLostError, g as startActiveTurn, h as markTurnFailed, l as getConversationTurnBoundaryError, mt as buildDeterministicTurnId, s as TurnInputCommitLostError, t as getTurnUserMessage } from "./turn-user-message-ygLG3ylQ.js";
|
|
14
|
+
import { T as recordFinishedTurnForAutomatedLimit, a as renderEventBatchInputs, i as isEventMailboxMetadata, o as timerWatchCredentialSubject, r as eventBatchMessageMeta, y as maybePostAutomatedTurnLimitNotice } from "./notification-gusCgdQ6.js";
|
|
15
|
+
import { a as getPersistedThreadState, c as coerceThreadConversationState, i as getPersistedSandboxState, s as persistThreadStateById } from "./turn-session-routing-BlCtVFRN.js";
|
|
16
|
+
import { a as AgentRunError, n as completeCancelledConversationTurn, o as executeTurn, r as supersedeOpenMailboxTurns } from "./turn-cancel-DDu8TOwt.js";
|
|
17
|
+
import { o as createWebAuthorization } from "./turn-wake-DmQec4AG.js";
|
|
18
|
+
import { H as blockEventAutomation, M as blockScheduledAutomation, c as getDispatchRecord, o as getDispatchIdForConversation, v as notifyAutomationBlocked, x as readAutomationExecutionByConversationId } from "./store-m5bmdmsP.js";
|
|
19
|
+
import { n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-COOwR8qm.js";
|
|
20
|
+
import { c as buildDeliveredTurnStatePatch, l as loadPendingMessageCards, o as completeAuthPauseTurn, r as finalizeFailedTurnReplyWithEvent, t as buildTurnThreadContext } from "./thread-context-Cd44z_W5.js";
|
|
21
|
+
import { isDeepStrictEqual } from "node:util";
|
|
22
|
+
import { createHash } from "node:crypto";
|
|
23
|
+
import { and, eq, isNotNull, isNull } from "drizzle-orm";
|
|
24
|
+
// src/chat/conversations/delivery-pause.ts
|
|
25
|
+
/** True when the Conversation is a root that delivers to a Location. */
|
|
26
|
+
function canPauseConversationDelivery(conversation) {
|
|
27
|
+
return isTopLevelKind(conversation.kind) && conversation.location !== void 0;
|
|
28
|
+
}
|
|
29
|
+
const rootConversation = (conversationId) => and(eq(juniorConversations.conversationId, conversationId), isNull(juniorConversations.parentConversationId));
|
|
30
|
+
/**
|
|
31
|
+
* Stop Delivery of a root's Event Turn replies to its Location. Returns false
|
|
32
|
+
* when Delivery was already paused or the root does not exist.
|
|
33
|
+
*/
|
|
34
|
+
async function pauseConversationDelivery(conversationId) {
|
|
35
|
+
return (await getSqlExecutor().db().update(juniorConversations).set({
|
|
36
|
+
deliveryPausedAt: /* @__PURE__ */ new Date(),
|
|
37
|
+
detailVersion: nextDetailVersion
|
|
38
|
+
}).where(and(rootConversation(conversationId), isNull(juniorConversations.deliveryPausedAt))).returning({ conversationId: juniorConversations.conversationId })).length > 0;
|
|
39
|
+
}
|
|
40
|
+
/** Deliver a root's Event Turn replies to its Location again. */
|
|
41
|
+
async function resumeConversationDelivery(conversationId) {
|
|
42
|
+
await getSqlExecutor().db().update(juniorConversations).set({
|
|
43
|
+
deliveryPausedAt: null,
|
|
44
|
+
detailVersion: nextDetailVersion
|
|
45
|
+
}).where(and(rootConversation(conversationId), isNotNull(juniorConversations.deliveryPausedAt)));
|
|
46
|
+
}
|
|
47
|
+
/** True while a root's Event Turn replies stay out of its Location. */
|
|
48
|
+
async function isConversationDeliveryPaused(conversationId) {
|
|
49
|
+
const [row] = await getSqlExecutor().db().select({ pausedAt: juniorConversations.deliveryPausedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
|
|
50
|
+
return Boolean(row?.pausedAt);
|
|
51
|
+
}
|
|
52
|
+
// src/chat/task-execution/turn-telemetry.ts
|
|
53
|
+
/** Read the turn input timing facts from a mailbox batch, oldest first. */
|
|
54
|
+
function turnInputTelemetry(messages) {
|
|
55
|
+
const oldest = messages[0];
|
|
56
|
+
if (!oldest) return void 0;
|
|
57
|
+
return {
|
|
58
|
+
count: messages.length,
|
|
59
|
+
oldestCreatedAtMs: oldest.createdAtMs,
|
|
60
|
+
oldestReceivedAtMs: oldest.receivedAtMs,
|
|
61
|
+
traceContexts: messages.flatMap((message) => message.traceContext ?? [])
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
const SENTRY_TRACE_PATTERN = /^([0-9a-f]{32})-([0-9a-f]{16})(?:-([01]))?$/;
|
|
65
|
+
function spanLinks({ sentryTrace }) {
|
|
66
|
+
const [, traceId, spanId, sampled] = SENTRY_TRACE_PATTERN.exec(sentryTrace) ?? [];
|
|
67
|
+
return traceId && spanId ? [{ context: {
|
|
68
|
+
traceId,
|
|
69
|
+
spanId,
|
|
70
|
+
traceFlags: sampled === "1" ? 1 : 0
|
|
71
|
+
} }] : [];
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Run a `chat.turn` span in the trace of the first trace context.
|
|
75
|
+
*
|
|
76
|
+
* The span links to the other trace contexts and to the span that was active,
|
|
77
|
+
* such as the worker span. Without a trace context, the span is a child of the
|
|
78
|
+
* active span. A malformed trace context starts a new trace. The span records
|
|
79
|
+
* how long the Turn waited on context compaction.
|
|
80
|
+
*/
|
|
81
|
+
async function withTurnSpan(context, input, callback) {
|
|
82
|
+
const [parent, ...others] = input?.traceContexts ?? [];
|
|
83
|
+
if (!parent) return await withSpan("chat.turn", "chat.turn", context, (set) => measureTurnCompactionWait(set, () => callback(set)));
|
|
84
|
+
const activeSpan = getActiveSpan();
|
|
85
|
+
const links = [...others.flatMap(spanLinks), ...activeSpan ? [{ context: activeSpan.spanContext() }] : []];
|
|
86
|
+
const { baggage, sentryTrace } = parent;
|
|
87
|
+
return await continueTrace({
|
|
88
|
+
baggage,
|
|
89
|
+
sentryTrace
|
|
90
|
+
}, () => withSpan("chat.turn", "chat.turn", context, async (setSpanAttributes) => {
|
|
91
|
+
getActiveSpan()?.addLinks(links);
|
|
92
|
+
return await measureTurnCompactionWait(setSpanAttributes, () => callback(setSpanAttributes));
|
|
93
|
+
}));
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Build the `chat.turn` timing attributes for the oldest input message.
|
|
97
|
+
*
|
|
98
|
+
* The provider, the ingress host, and the worker host use separate clocks. A negative
|
|
99
|
+
* duration is clock skew, not latency, so it is left out.
|
|
100
|
+
*/
|
|
101
|
+
function getTurnInputSpanAttributes(input, turnStartedAtMs) {
|
|
102
|
+
const attributes = { "app.turn.input_count": input.count };
|
|
103
|
+
const deliveryLagMs = input.oldestReceivedAtMs - input.oldestCreatedAtMs;
|
|
104
|
+
if (deliveryLagMs >= 0) attributes["app.turn.delivery_lag_ms"] = Math.round(deliveryLagMs);
|
|
105
|
+
const waitMs = turnStartedAtMs - input.oldestReceivedAtMs;
|
|
106
|
+
if (waitMs >= 0) attributes["app.turn.wait_ms"] = Math.round(waitMs);
|
|
107
|
+
return attributes;
|
|
108
|
+
}
|
|
109
|
+
// src/chat/automations/block-run.ts
|
|
110
|
+
/**
|
|
111
|
+
* Find the Automation of a run. The SQL run row lasts as long as the
|
|
112
|
+
* Automation, but a Watch can outlive the dispatch record. The dispatch record
|
|
113
|
+
* covers a run whose row does not link its Conversation yet.
|
|
114
|
+
*/
|
|
115
|
+
async function findRunAutomation(conversationId, dispatchId) {
|
|
116
|
+
const run = await readAutomationExecutionByConversationId({ conversationId });
|
|
117
|
+
if (run) return run;
|
|
118
|
+
const source = dispatchId ? (await getDispatchRecord(dispatchId))?.source : void 0;
|
|
119
|
+
if (!source || !("automationId" in source) || !source.automationId) return;
|
|
120
|
+
return {
|
|
121
|
+
automationId: source.automationId,
|
|
122
|
+
kind: source.kind === "scheduled_automation" ? "scheduled" : "event"
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Block the Automation of a run from a later Turn of the run, such as a Watch
|
|
127
|
+
* Event or child result Turn. The dispatch Turn blocks through its dispatch
|
|
128
|
+
* outcome. Its creator is told when the block is first stored.
|
|
129
|
+
*/
|
|
130
|
+
async function blockRunAutomation(conversationId, blocked) {
|
|
131
|
+
const dispatchId = getDispatchIdForConversation(conversationId);
|
|
132
|
+
const automation = await findRunAutomation(conversationId, dispatchId);
|
|
133
|
+
if (!automation) {
|
|
134
|
+
logWarn("automation.block.unresolved", { "gen_ai.conversation.id": conversationId });
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
const { automationId, kind } = automation;
|
|
138
|
+
if (kind === "scheduled" ? await blockScheduledAutomation(getDb(), automationId, blocked.missing) : await blockEventAutomation(getDb(), automationId, blocked.missing)) await notifyAutomationBlocked({
|
|
139
|
+
automationId,
|
|
140
|
+
...dispatchId ? { dispatchId } : void 0,
|
|
141
|
+
kind,
|
|
142
|
+
reason: blocked.missing
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
// src/chat/task-execution/assistant-message.ts
|
|
146
|
+
/** Store one assistant Message and its Agent history. */
|
|
147
|
+
async function commitAssistantMessage(args) {
|
|
148
|
+
const conversationMessageId = recordDeliveredAssistantMessage({
|
|
149
|
+
cards: args.cards,
|
|
150
|
+
conversation: args.conversation,
|
|
151
|
+
...args.quiet ? { quiet: args.quiet } : void 0,
|
|
152
|
+
sessionId: args.sessionId,
|
|
153
|
+
source: args.source,
|
|
154
|
+
text: args.text,
|
|
155
|
+
userMessageId: args.userMessageId
|
|
156
|
+
});
|
|
157
|
+
if (args.deliveryResult?.providerMessageId) markConversationMessage(args.conversation, conversationMessageId, { slackTs: args.deliveryResult.providerMessageId });
|
|
158
|
+
try {
|
|
159
|
+
await persistWithRetry(() => commitAcceptedReply({
|
|
160
|
+
...args.agentMessage ? { agentMessage: args.agentMessage } : void 0,
|
|
161
|
+
conversation: args.conversation,
|
|
162
|
+
conversationMessageId,
|
|
163
|
+
conversationId: args.conversationId,
|
|
164
|
+
providerConversationBindings: args.deliveryResult?.providerConversationBindings
|
|
165
|
+
}));
|
|
166
|
+
} catch (error) {
|
|
167
|
+
logException(error, "conversation.assistant.message_persist.failed");
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
// src/chat/task-execution/mailbox-input.ts
|
|
171
|
+
/**
|
|
172
|
+
* Return the Turn inputs of web Messages, one per non-empty Message, in
|
|
173
|
+
* order. Each one becomes its own prompt content part. A Message that
|
|
174
|
+
* records an answer becomes its Review item tag. A batch with only
|
|
175
|
+
* attachments keeps one empty input, so the prompt still has an instruction.
|
|
176
|
+
*/
|
|
177
|
+
async function webTurnInputs(messages) {
|
|
178
|
+
const flat = (await Promise.all(messages.map(async (message) => {
|
|
179
|
+
const reviewItem = await loadReviewItemInput(message.reviewItemChange);
|
|
180
|
+
if (reviewItem) return [{
|
|
181
|
+
kind: "runtime",
|
|
182
|
+
text: reviewItem
|
|
183
|
+
}];
|
|
184
|
+
const text = message.text.trim();
|
|
185
|
+
return text ? [{
|
|
186
|
+
kind: "person",
|
|
187
|
+
text
|
|
188
|
+
}] : [];
|
|
189
|
+
}))).flat();
|
|
190
|
+
return flat.length ? flat : [{
|
|
191
|
+
kind: "person",
|
|
192
|
+
text: ""
|
|
193
|
+
}];
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Build the transcript Message for one web mailbox Message. Each web Message
|
|
197
|
+
* keeps its own transcript Message and Review item change record, so the
|
|
198
|
+
* dashboard shows what each Message did even when several share a Turn.
|
|
199
|
+
*/
|
|
200
|
+
function webConversationMessage(message, author) {
|
|
201
|
+
const attachments = readMessageAttachments(message.input.attachments);
|
|
202
|
+
const { reviewItemChange } = message.input;
|
|
203
|
+
return {
|
|
204
|
+
id: message.inboundMessageId,
|
|
205
|
+
role: "user",
|
|
206
|
+
text: normalizeConversationText(message.input.text),
|
|
207
|
+
createdAtMs: message.createdAtMs,
|
|
208
|
+
author,
|
|
209
|
+
...message.input.authorIdentityId ? { authorIdentityId: message.input.authorIdentityId } : void 0,
|
|
210
|
+
meta: {
|
|
211
|
+
...attachments.length ? { attachments } : void 0,
|
|
212
|
+
explicitMention: true,
|
|
213
|
+
...reviewItemChange ? { reviewItemChanges: [reviewItemChange] } : void 0,
|
|
214
|
+
source: "web"
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Return the saved input Messages of a resumed Turn in input order. A web
|
|
220
|
+
* batch saves each Message apart. An older Turn saved one joined Message, so
|
|
221
|
+
* its other input ids have no saved Message.
|
|
222
|
+
*/
|
|
223
|
+
function savedTurnInputMessages(conversation, turnMessage, inputMessageIds) {
|
|
224
|
+
const saved = (inputMessageIds ?? []).flatMap((id) => conversation.messages.find((message) => message.id === id && message.role === "user") ?? []);
|
|
225
|
+
return saved.some((message) => message.id === turnMessage.id) ? saved : [turnMessage];
|
|
226
|
+
}
|
|
227
|
+
// src/chat/task-execution/web-steering.ts
|
|
228
|
+
async function steeringMessageFromWeb(message, actor) {
|
|
229
|
+
const storedAttachments = readMessageAttachments(message.input.attachments);
|
|
230
|
+
const reviewItemInput = await loadReviewItemInput(message.input.reviewItemChange);
|
|
231
|
+
return {
|
|
232
|
+
actor: {
|
|
233
|
+
authorId: actor.userId,
|
|
234
|
+
...actor.fullName ? { authorName: actor.fullName } : void 0
|
|
235
|
+
},
|
|
236
|
+
...reviewItemInput ? { kind: "runtime" } : void 0,
|
|
237
|
+
provenance: instructionProvenanceFor(actor),
|
|
238
|
+
text: reviewItemInput ?? message.input.text.trim(),
|
|
239
|
+
timestampMs: message.createdAtMs,
|
|
240
|
+
...storedAttachments.length ? { storedAttachments } : void 0
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Drain steered web messages into the active web Turn.
|
|
245
|
+
*
|
|
246
|
+
* Only messages from the Turn Actor join. Steered messages from another
|
|
247
|
+
* participant stay pending and start their own Turn next, so they never act
|
|
248
|
+
* with this Actor's credentials.
|
|
249
|
+
*/
|
|
250
|
+
function createWebSteeringDrain(args) {
|
|
251
|
+
const { actor, author, context, conversation, turnId } = args;
|
|
252
|
+
return async (accept) => {
|
|
253
|
+
const accepted = [];
|
|
254
|
+
await context.attempt.drain(async (pending) => {
|
|
255
|
+
const joining = pending.filter((message) => message.source === "web" && message.input.authorId === actor.userId && legacyWebMailboxMetadataSchema.safeParse(message.input.metadata).success);
|
|
256
|
+
if (joining.length === 0) return [];
|
|
257
|
+
for (const message of joining) upsertConversationMessage(conversation, webConversationMessage(message, author));
|
|
258
|
+
await persistConversationMessages({
|
|
259
|
+
conversation,
|
|
260
|
+
conversationId: context.conversationId
|
|
261
|
+
});
|
|
262
|
+
const saved = (await getTurnRecord(context.conversationId, turnId))?.piMessages ?? [];
|
|
263
|
+
const messages = withoutSavedSteeringMessages(saved, await Promise.all(joining.map((message) => steeringMessageFromWeb(message, actor))), buildSteeringPiMessage);
|
|
264
|
+
if (messages.length > 0) {
|
|
265
|
+
await accept(messages);
|
|
266
|
+
accepted.push(...messages);
|
|
267
|
+
}
|
|
268
|
+
return joining.map((message) => message.inboundMessageId);
|
|
269
|
+
});
|
|
270
|
+
return accepted;
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
// src/chat/task-execution/conversation-turn.ts
|
|
274
|
+
/** Run a mailbox Turn and store its assistant Messages. */
|
|
275
|
+
var conversation_turn_exports = /* @__PURE__ */ __exportAll({ createConversationTurnWorker: () => createConversationTurnWorker });
|
|
276
|
+
function stableHex(...parts) {
|
|
277
|
+
return createHash("sha256").update(parts.join("\0")).digest("hex").slice(0, 24);
|
|
278
|
+
}
|
|
279
|
+
function captureConversationTurnFailure(args) {
|
|
280
|
+
const eventId = logException(args.error, `conversation.turn.${args.failureCode}`, {
|
|
281
|
+
conversationId: args.conversationId,
|
|
282
|
+
...args.runId ? { runId: args.runId } : void 0,
|
|
283
|
+
turnId: args.turnId
|
|
284
|
+
});
|
|
285
|
+
return typeof eventId === "string" ? eventId : void 0;
|
|
286
|
+
}
|
|
287
|
+
/** Return the saved timer creator subject when it is still valid here. */
|
|
288
|
+
function resumedTimerWatchCredentialSubject(conversationId, subject) {
|
|
289
|
+
if (subject?.binding.type !== "timer-watch") return void 0;
|
|
290
|
+
return verifyTimerWatchCredentialSubject({
|
|
291
|
+
conversationId,
|
|
292
|
+
subject,
|
|
293
|
+
watchId: subject.binding.watchId
|
|
294
|
+
}) ? subject : void 0;
|
|
295
|
+
}
|
|
296
|
+
function sharedDelegatedSubject(batch) {
|
|
297
|
+
const subjects = batch.map((entry) => entry.credentialContext && "subject" in entry.credentialContext ? entry.credentialContext.subject : void 0);
|
|
298
|
+
const first = subjects[0];
|
|
299
|
+
return first && subjects.every((subject) => isDeepStrictEqual(subject, first)) ? first : void 0;
|
|
300
|
+
}
|
|
301
|
+
function hasLostTurnInputCommit(error) {
|
|
302
|
+
const cause = getConversationTurnBoundaryError(error)?.cause ?? error;
|
|
303
|
+
return isTurnInputCommitLostError(error) || isTurnInputCommitLostError(cause);
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Return the author Identity id that every batched input shares.
|
|
307
|
+
* A batch with more than one author has no single author yet.
|
|
308
|
+
*/
|
|
309
|
+
function sharedAuthorIdentityId(messages) {
|
|
310
|
+
const ids = new Set(messages.map((message) => message.input.authorIdentityId));
|
|
311
|
+
return ids.size === 1 ? [...ids][0] : void 0;
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Create the shared mailbox worker for web and event Turns of every
|
|
315
|
+
* Conversation kind. `deliverMessage` posts to a Location, and
|
|
316
|
+
* `deliverToParent` sends a child agent's results to its parent.
|
|
317
|
+
*/
|
|
318
|
+
function createConversationTurnWorker(agentRunner, deliverMessage, deliverToParent) {
|
|
319
|
+
return async (context, resolved) => {
|
|
320
|
+
if (resolved.kind === "mailbox") {
|
|
321
|
+
const delayMs = getEventBatchDelayMs(resolved.batch.map((entry) => entry.message));
|
|
322
|
+
if (delayMs > 0) return {
|
|
323
|
+
status: "deferred",
|
|
324
|
+
delayMs
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
const lifecycle = new ConversationTurnLifecycleService(getConversationEventStore());
|
|
328
|
+
const isResume = resolved.kind === "resume";
|
|
329
|
+
let turnInputFacts;
|
|
330
|
+
let inputs = [];
|
|
331
|
+
let attachments = [];
|
|
332
|
+
let turnId = "";
|
|
333
|
+
let userMessageId = "";
|
|
334
|
+
let startedAtMs = Date.now();
|
|
335
|
+
let inputMessageIds = [];
|
|
336
|
+
let eventMeta = {};
|
|
337
|
+
let authorIdentityId;
|
|
338
|
+
let webInputMessages = [];
|
|
339
|
+
const storedConversation = await getConversationStore().get({ conversationId: context.conversationId });
|
|
340
|
+
const kind = storedConversation?.kind ?? "root";
|
|
341
|
+
const visibility = isTopLevelKind(kind) ? storedConversation?.visibility : storedConversation?.visibility ?? "private";
|
|
342
|
+
const mailboxDestination = resolved.kind === "mailbox" ? resolved.batch[0]?.message.destination : void 0;
|
|
343
|
+
const destination = resolveConversationDestination({
|
|
344
|
+
conversationId: context.conversationId,
|
|
345
|
+
existing: context.destination ?? mailboxDestination ?? storedConversation?.destination
|
|
346
|
+
});
|
|
347
|
+
if (resolved.kind === "mailbox") {
|
|
348
|
+
const first = resolved.batch[0];
|
|
349
|
+
const messages = resolved.batch.map((entry) => entry.message);
|
|
350
|
+
const firstMetadata = first.message.input.metadata;
|
|
351
|
+
if (isEventMailboxMetadata(firstMetadata)) {
|
|
352
|
+
inputs = renderEventBatchInputs(messages, await eventReviewItemInputs(messages)).map((text) => ({
|
|
353
|
+
kind: "runtime",
|
|
354
|
+
text
|
|
355
|
+
}));
|
|
356
|
+
eventMeta = eventBatchMessageMeta(messages);
|
|
357
|
+
} else {
|
|
358
|
+
inputs = await webTurnInputs(messages.map((message) => message.input));
|
|
359
|
+
webInputMessages = resolved.batch.map((entry) => webConversationMessage(entry.message, entry.author));
|
|
360
|
+
}
|
|
361
|
+
attachments = resolved.batch.flatMap((entry) => readMessageAttachments(entry.message.input.attachments));
|
|
362
|
+
startedAtMs = first.message.createdAtMs;
|
|
363
|
+
userMessageId = first.message.inboundMessageId;
|
|
364
|
+
turnId = buildDeterministicTurnId(userMessageId);
|
|
365
|
+
inputMessageIds = resolved.batch.map((entry) => entry.message.inboundMessageId);
|
|
366
|
+
authorIdentityId = sharedAuthorIdentityId(messages);
|
|
367
|
+
turnInputFacts = first;
|
|
368
|
+
} else turnId = resolved.turnId;
|
|
369
|
+
const persisted = await getPersistedThreadState(context.conversationId);
|
|
370
|
+
const conversation = coerceThreadConversationState(persisted);
|
|
371
|
+
await hydrateConversationMessages({
|
|
372
|
+
conversation,
|
|
373
|
+
conversationId: context.conversationId
|
|
374
|
+
});
|
|
375
|
+
const savedTurn = isResume ? await getTurnRecord(context.conversationId, turnId) : void 0;
|
|
376
|
+
let savedMessageIsEvent = false;
|
|
377
|
+
if (isResume) {
|
|
378
|
+
const userMessage = getTurnUserMessage(conversation, turnId);
|
|
379
|
+
if (!userMessage) throw new Error(`Unable to locate the persisted user message for Turn "${turnId}"`);
|
|
380
|
+
savedMessageIsEvent = isEventConversationMessage(userMessage);
|
|
381
|
+
turnInputFacts = turnInputFactsFromConversationMessage(userMessage, {
|
|
382
|
+
conversationId: context.conversationId,
|
|
383
|
+
location: storedConversation?.location,
|
|
384
|
+
savedActor: savedTurn?.actor,
|
|
385
|
+
savedSource: savedTurn?.source,
|
|
386
|
+
visibility: storedConversation?.visibility
|
|
387
|
+
});
|
|
388
|
+
const turnInputs = savedTurnInputMessages(conversation, userMessage, await lifecycle.loadInputMessageIds(context.conversationId, turnId));
|
|
389
|
+
userMessageId = userMessage.id;
|
|
390
|
+
inputs = savedMessageIsEvent ? [{
|
|
391
|
+
kind: "runtime",
|
|
392
|
+
text: userMessage.text
|
|
393
|
+
}] : await webTurnInputs(turnInputs.map((message) => ({
|
|
394
|
+
reviewItemChange: message.meta?.reviewItemChanges?.[0],
|
|
395
|
+
text: message.text
|
|
396
|
+
})));
|
|
397
|
+
attachments = turnInputs.flatMap((message) => message.meta?.attachments ?? []);
|
|
398
|
+
startedAtMs = userMessage.createdAtMs;
|
|
399
|
+
inputMessageIds = turnInputs.map((message) => message.id);
|
|
400
|
+
}
|
|
401
|
+
if (!turnInputFacts) throw new Error(`Resumed Turn is missing an Actor for Conversation ${context.conversationId}`);
|
|
402
|
+
const { actor, author } = turnInputFacts;
|
|
403
|
+
const instructionInputs = instructionForInputs(inputs);
|
|
404
|
+
const { text } = instructionInputs;
|
|
405
|
+
let credentialSubject;
|
|
406
|
+
if (actor.platform === "system") credentialSubject = resolved.kind === "mailbox" ? timerWatchCredentialSubject(context.conversationId, resolved.batch.map((entry) => entry.message)) ?? resumedTimerWatchCredentialSubject(context.conversationId, sharedDelegatedSubject(resolved.batch)) : resumedTimerWatchCredentialSubject(context.conversationId, savedTurn?.credentialSubject);
|
|
407
|
+
const source = sourceFromTurnInput({
|
|
408
|
+
conversationId: context.conversationId,
|
|
409
|
+
source: turnInputFacts.source,
|
|
410
|
+
visibility
|
|
411
|
+
});
|
|
412
|
+
const conversationLocation = storedConversation?.location;
|
|
413
|
+
const isEventTurn = source.kind === "event" || savedMessageIsEvent;
|
|
414
|
+
const postsToProvider = Boolean(conversationLocation) && isEventTurn;
|
|
415
|
+
const behavior = turnBehavior({
|
|
416
|
+
kind,
|
|
417
|
+
personInput: isPersonInput(source.kind)
|
|
418
|
+
});
|
|
419
|
+
const webActor = actor.platform === "web" ? actor : void 0;
|
|
420
|
+
const signInActor = behavior.promptMode === "child_agent" ? void 0 : webActor;
|
|
421
|
+
const disabledFeatures = signInActor ? [] : ["interactive-auth"];
|
|
422
|
+
const deliverToProvider = postsToProvider && behavior.delivery === "location";
|
|
423
|
+
const sendToParent = async (result) => {
|
|
424
|
+
if (!deliverToParent) throw new Error(`Conversation ${context.conversationId} cannot reach its parent agent`);
|
|
425
|
+
await deliverToParent({
|
|
426
|
+
actor,
|
|
427
|
+
result,
|
|
428
|
+
conversationId: context.conversationId,
|
|
429
|
+
turnId
|
|
430
|
+
});
|
|
431
|
+
};
|
|
432
|
+
const surface = postsToProvider ? "slack" : "api";
|
|
433
|
+
const inputTelemetry = resolved.kind === "mailbox" ? turnInputTelemetry(resolved.batch.map((entry) => entry.message)) : void 0;
|
|
434
|
+
const turnTrace = inputTelemetry ?? (savedTurn?.traceContext ? { traceContexts: [savedTurn.traceContext] } : void 0);
|
|
435
|
+
return await withTurnSpan({
|
|
436
|
+
conversationId: context.conversationId,
|
|
437
|
+
platform: actor.platform,
|
|
438
|
+
...webActor ? {
|
|
439
|
+
userId: webActor.userId,
|
|
440
|
+
...webActor.userName ? { userName: webActor.userName } : void 0
|
|
441
|
+
} : void 0
|
|
442
|
+
}, turnTrace, async (setTurnSpanAttributes) => {
|
|
443
|
+
if (inputTelemetry) setTurnSpanAttributes(getTurnInputSpanAttributes(inputTelemetry, Date.now()));
|
|
444
|
+
let acknowledged = isResume || context.attempt.messages.length === 0;
|
|
445
|
+
const acknowledge = async () => {
|
|
446
|
+
if (acknowledged) return;
|
|
447
|
+
try {
|
|
448
|
+
await context.attempt.ack();
|
|
449
|
+
} catch {
|
|
450
|
+
throw new TurnInputCommitLostError(`Conversation work lease lost before mailbox Message acknowledgement for ${context.conversationId}`);
|
|
451
|
+
}
|
|
452
|
+
acknowledged = true;
|
|
453
|
+
};
|
|
454
|
+
let sandboxRef = getPersistedSandboxState(persisted);
|
|
455
|
+
const initialSandboxRef = sandboxRef;
|
|
456
|
+
const stopSignal = context.stopSignal?.();
|
|
457
|
+
const completeCancelledTurn = async () => {
|
|
458
|
+
try {
|
|
459
|
+
await completeCancelledConversationTurn({
|
|
460
|
+
acknowledge,
|
|
461
|
+
conversation,
|
|
462
|
+
conversationId: context.conversationId,
|
|
463
|
+
sandboxRef,
|
|
464
|
+
turnId,
|
|
465
|
+
userMessageId
|
|
466
|
+
});
|
|
467
|
+
} catch (error) {
|
|
468
|
+
if (hasLostTurnInputCommit(error)) return { status: "lost_lease" };
|
|
469
|
+
throw error;
|
|
470
|
+
}
|
|
471
|
+
return { status: "completed" };
|
|
472
|
+
};
|
|
473
|
+
if (isResume) {
|
|
474
|
+
if (stopSignal?.aborted) return await completeCancelledTurn();
|
|
475
|
+
} else {
|
|
476
|
+
for (const [index, message] of webInputMessages.entries()) upsertConversationMessage(conversation, index === 0 ? {
|
|
477
|
+
...message,
|
|
478
|
+
meta: {
|
|
479
|
+
...message.meta,
|
|
480
|
+
replied: false
|
|
481
|
+
}
|
|
482
|
+
} : message);
|
|
483
|
+
if (webInputMessages.length === 0) upsertConversationMessage(conversation, {
|
|
484
|
+
id: userMessageId,
|
|
485
|
+
role: "user",
|
|
486
|
+
text: normalizeConversationText(text),
|
|
487
|
+
createdAtMs: startedAtMs,
|
|
488
|
+
author,
|
|
489
|
+
...authorIdentityId ? { authorIdentityId } : void 0,
|
|
490
|
+
meta: {
|
|
491
|
+
...attachments.length ? { attachments } : void 0,
|
|
492
|
+
explicitMention: true,
|
|
493
|
+
replied: false,
|
|
494
|
+
...eventMeta
|
|
495
|
+
}
|
|
496
|
+
});
|
|
497
|
+
await persistConversationMessages({
|
|
498
|
+
conversation,
|
|
499
|
+
conversationId: context.conversationId
|
|
500
|
+
});
|
|
501
|
+
await lifecycle.start({
|
|
502
|
+
conversationId: context.conversationId,
|
|
503
|
+
createdAtMs: Date.now(),
|
|
504
|
+
inputMessageIds,
|
|
505
|
+
surface,
|
|
506
|
+
threadContextThroughSeq: latestConversationMessageSeq(conversation),
|
|
507
|
+
turnId
|
|
508
|
+
});
|
|
509
|
+
if (stopSignal?.aborted) return await completeCancelledTurn();
|
|
510
|
+
startActiveTurn({
|
|
511
|
+
conversation,
|
|
512
|
+
nextTurnId: turnId
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
let currentRunId;
|
|
516
|
+
let assistantMessageDelivered = false;
|
|
517
|
+
let failureCode = "persistence_failed";
|
|
518
|
+
let modelFailureEventId;
|
|
519
|
+
let modelFailureCaptureAttempted = false;
|
|
520
|
+
let completedSuccessfully = false;
|
|
521
|
+
const deliverAssistantMessage = async (value, options) => {
|
|
522
|
+
const agentMessage = typeof value === "string" ? void 0 : value;
|
|
523
|
+
const replyText = typeof value === "string" ? value : getAssistantReplyText(value);
|
|
524
|
+
if (!replyText?.trim()) return;
|
|
525
|
+
failureCode = "delivery_failed";
|
|
526
|
+
const cards = await loadPendingMessageCards(context.conversationId);
|
|
527
|
+
const quiet = options?.quiet === true && isEventTurn && cards.length === 0;
|
|
528
|
+
let deliveryResult;
|
|
529
|
+
if ((options?.reply ? postsToProvider : deliverToProvider) && !quiet && !await isConversationDeliveryPaused(context.conversationId)) {
|
|
530
|
+
if (!conversationLocation || !deliverMessage) throw new Error(`Conversation ${context.conversationId} cannot deliver to its Location`);
|
|
531
|
+
deliveryResult = await deliverMessage({
|
|
532
|
+
cards,
|
|
533
|
+
conversationId: context.conversationId,
|
|
534
|
+
location: conversationLocation,
|
|
535
|
+
text: replyText
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
await commitAssistantMessage({
|
|
539
|
+
cards,
|
|
540
|
+
...agentMessage ? { agentMessage } : void 0,
|
|
541
|
+
conversation,
|
|
542
|
+
conversationId: context.conversationId,
|
|
543
|
+
...deliveryResult ? { deliveryResult } : void 0,
|
|
544
|
+
...quiet ? { quiet } : void 0,
|
|
545
|
+
sessionId: turnId,
|
|
546
|
+
...deliveryResult ? { source: "slack" } : source.kind === "web" ? { source: "web" } : void 0,
|
|
547
|
+
text: replyText,
|
|
548
|
+
userMessageId
|
|
549
|
+
});
|
|
550
|
+
assistantMessageDelivered = true;
|
|
551
|
+
failureCode = "agent_run_failed";
|
|
552
|
+
};
|
|
553
|
+
try {
|
|
554
|
+
if (stopSignal?.aborted) return await completeCancelledTurn();
|
|
555
|
+
if (!isResume && !await supersedeOpenMailboxTurns({
|
|
556
|
+
conversation,
|
|
557
|
+
conversationId: context.conversationId,
|
|
558
|
+
isStopped: () => Boolean(stopSignal?.aborted),
|
|
559
|
+
keepTurnId: turnId
|
|
560
|
+
})) return await completeCancelledTurn();
|
|
561
|
+
await persistThreadStateById(context.conversationId, { conversation });
|
|
562
|
+
if (stopSignal?.aborted) return await completeCancelledTurn();
|
|
563
|
+
const piMessages = await loadProjection({ conversationId: context.conversationId });
|
|
564
|
+
failureCode = "agent_run_failed";
|
|
565
|
+
currentRunId = `conversation-run:${stableHex(turnId, String(startedAtMs))}`;
|
|
566
|
+
setTags({ runId: currentRunId });
|
|
567
|
+
const outcome = await executeTurn(agentRunner, {
|
|
568
|
+
conversationId: context.conversationId,
|
|
569
|
+
...storedConversation?.parentConversationId ? { parentConversationId: storedConversation.parentConversationId } : void 0,
|
|
570
|
+
turnId,
|
|
571
|
+
runId: currentRunId,
|
|
572
|
+
instruction: {
|
|
573
|
+
...instructionInputs,
|
|
574
|
+
storedAttachments: attachments,
|
|
575
|
+
context: await buildTurnThreadContext({
|
|
576
|
+
conversation,
|
|
577
|
+
conversationId: context.conversationId,
|
|
578
|
+
excludeMessageIds: inputMessageIds,
|
|
579
|
+
hasHistory: piMessages.length > 0,
|
|
580
|
+
turnId
|
|
581
|
+
})
|
|
582
|
+
},
|
|
583
|
+
history: piMessages,
|
|
584
|
+
actor,
|
|
585
|
+
credentialContext: credentialContextForActor(actor, credentialSubject),
|
|
586
|
+
destination,
|
|
587
|
+
source,
|
|
588
|
+
...conversationLocation ? { location: conversationLocation } : void 0,
|
|
589
|
+
surface,
|
|
590
|
+
...stopSignal ? { signal: stopSignal } : void 0,
|
|
591
|
+
...signInActor ? { authorization: createWebAuthorization({
|
|
592
|
+
actorId: signInActor.userId,
|
|
593
|
+
conversationId: context.conversationId
|
|
594
|
+
}) } : void 0,
|
|
595
|
+
...disabledFeatures.length > 0 ? { disabledFeatures } : void 0,
|
|
596
|
+
state: {
|
|
597
|
+
pendingAuth: conversation.processing.pendingAuth,
|
|
598
|
+
sandboxRef
|
|
599
|
+
},
|
|
600
|
+
delivery: deliverAssistantMessage,
|
|
601
|
+
durability: {
|
|
602
|
+
...webActor ? { drainSteeringMessages: createWebSteeringDrain({
|
|
603
|
+
actor: webActor,
|
|
604
|
+
author,
|
|
605
|
+
context,
|
|
606
|
+
conversation,
|
|
607
|
+
turnId
|
|
608
|
+
}) } : void 0,
|
|
609
|
+
onInputCommitted: acknowledge,
|
|
610
|
+
shouldYield: context.shouldYield,
|
|
611
|
+
checkIn: context.checkIn,
|
|
612
|
+
checkStop: context.checkStop,
|
|
613
|
+
onSandboxRefChanged: async (nextSandboxRef) => {
|
|
614
|
+
sandboxRef = nextSandboxRef;
|
|
615
|
+
await persistThreadStateById(context.conversationId, {
|
|
616
|
+
conversation,
|
|
617
|
+
sandboxRef
|
|
618
|
+
});
|
|
619
|
+
},
|
|
620
|
+
recordPendingAuth: async (pendingAuth) => {
|
|
621
|
+
conversation.processing.pendingAuth = pendingAuth;
|
|
622
|
+
await persistThreadStateById(context.conversationId, {
|
|
623
|
+
conversation,
|
|
624
|
+
sandboxRef
|
|
625
|
+
});
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
}, async (result) => {
|
|
629
|
+
if (stopSignal?.aborted) throw stopSignal.reason ?? new DOMException("Turn cancelled", "AbortError");
|
|
630
|
+
modelFailureCaptureAttempted = result.diagnostics.outcome !== "success";
|
|
631
|
+
const finalized = finalizeFailedTurnReplyWithEvent({
|
|
632
|
+
reply: result,
|
|
633
|
+
logException
|
|
634
|
+
});
|
|
635
|
+
const modelFailureReason = finalized.failureReason;
|
|
636
|
+
const reply = finalized.reply;
|
|
637
|
+
modelFailureEventId = finalized.eventId;
|
|
638
|
+
if (reply.diagnostics.outcome !== "success") {
|
|
639
|
+
await deliverAssistantMessage(reply.text);
|
|
640
|
+
if (behavior.failureNotice === "parent") await sendToParent({
|
|
641
|
+
kind: "failed",
|
|
642
|
+
text: reply.diagnostics.errorMessage ?? reply.text
|
|
643
|
+
});
|
|
644
|
+
} else if (reply.reply && behavior.tools.reply === "parent") await sendToParent({
|
|
645
|
+
kind: "reply",
|
|
646
|
+
reply: reply.reply
|
|
647
|
+
});
|
|
648
|
+
else if (reply.reply) await deliverAssistantMessage(reply.reply.text, { reply: true });
|
|
649
|
+
else if (reply.blocked && behavior.tools.reportBlocked === "parent") await sendToParent({
|
|
650
|
+
kind: "blocked",
|
|
651
|
+
text: reply.blocked.missing
|
|
652
|
+
});
|
|
653
|
+
else if (reply.blocked) await blockRunAutomation(context.conversationId, reply.blocked);
|
|
654
|
+
else if (reply.noReply?.note && isEventTurn) await deliverAssistantMessage(reply.noReply.note, { quiet: true });
|
|
655
|
+
const completedState = buildDeliveredTurnStatePatch({
|
|
656
|
+
conversation,
|
|
657
|
+
reply,
|
|
658
|
+
sessionId: turnId,
|
|
659
|
+
userMessageId
|
|
660
|
+
});
|
|
661
|
+
await persistThreadStateById(context.conversationId, {
|
|
662
|
+
conversation: completedState.conversation,
|
|
663
|
+
sandboxRef: reply.sandboxRef ?? sandboxRef
|
|
664
|
+
});
|
|
665
|
+
if (reply.piMessages?.length) {
|
|
666
|
+
const latest = await getTurnRecord(context.conversationId, turnId);
|
|
667
|
+
await saveTurnCheckpoint({
|
|
668
|
+
mode: "completed",
|
|
669
|
+
conversationId: context.conversationId,
|
|
670
|
+
turnId,
|
|
671
|
+
sliceId: latest?.sliceId ?? 1,
|
|
672
|
+
messages: reply.piMessages,
|
|
673
|
+
durationMs: reply.diagnostics.durationMs,
|
|
674
|
+
usage: reply.diagnostics.usage,
|
|
675
|
+
destination,
|
|
676
|
+
source,
|
|
677
|
+
actor,
|
|
678
|
+
surface
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
const automatedTurnLimit = await recordFinishedTurnForAutomatedLimit({
|
|
682
|
+
conversationId: context.conversationId,
|
|
683
|
+
maxTurns: botConfig.maxConsecutiveAutomatedTurns,
|
|
684
|
+
source
|
|
685
|
+
});
|
|
686
|
+
await maybePostAutomatedTurnLimitNotice({
|
|
687
|
+
conversationId: context.conversationId,
|
|
688
|
+
maxTurns: botConfig.maxConsecutiveAutomatedTurns,
|
|
689
|
+
source,
|
|
690
|
+
update: automatedTurnLimit
|
|
691
|
+
});
|
|
692
|
+
completedSuccessfully = reply.diagnostics.outcome === "success";
|
|
693
|
+
return completedSuccessfully ? { outcome: assistantMessageDelivered ? "success" : "no_reply" } : {
|
|
694
|
+
...modelFailureEventId ? { eventId: modelFailureEventId } : void 0,
|
|
695
|
+
failureCode: "model_execution_failed",
|
|
696
|
+
...modelFailureReason ? { failureReason: modelFailureReason } : void 0,
|
|
697
|
+
outcome: "failed"
|
|
698
|
+
};
|
|
699
|
+
});
|
|
700
|
+
if (outcome.status !== "completed" && stopSignal?.aborted) return await completeCancelledTurn();
|
|
701
|
+
if (outcome.status === "suspended") return { status: "yielded" };
|
|
702
|
+
if (outcome.status === "awaiting_auth") {
|
|
703
|
+
completeAuthPauseTurn({
|
|
704
|
+
conversation,
|
|
705
|
+
sessionId: turnId
|
|
706
|
+
});
|
|
707
|
+
await persistThreadStateById(context.conversationId, {
|
|
708
|
+
conversation,
|
|
709
|
+
sandboxRef
|
|
710
|
+
});
|
|
711
|
+
await acknowledge();
|
|
712
|
+
return { status: "paused" };
|
|
713
|
+
}
|
|
714
|
+
if (completedSuccessfully && behavior.sessionTasks) try {
|
|
715
|
+
await scheduleSessionCompletedPluginTasks({
|
|
716
|
+
conversationId: context.conversationId,
|
|
717
|
+
sessionId: turnId
|
|
718
|
+
}, { send: async (message) => {
|
|
719
|
+
try {
|
|
720
|
+
await processPluginTask(message);
|
|
721
|
+
} catch (error) {
|
|
722
|
+
logException(error, "conversation.plugin.session_completion_task.failed", {
|
|
723
|
+
conversationId: context.conversationId,
|
|
724
|
+
pluginName: message.plugin,
|
|
725
|
+
taskName: message.name,
|
|
726
|
+
turnId
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
} });
|
|
730
|
+
} catch (error) {
|
|
731
|
+
logException(error, "conversation.plugin.session_completion_task.failed", {
|
|
732
|
+
conversationId: context.conversationId,
|
|
733
|
+
turnId
|
|
734
|
+
});
|
|
735
|
+
}
|
|
736
|
+
await acknowledge();
|
|
737
|
+
return { status: "completed" };
|
|
738
|
+
} catch (error) {
|
|
739
|
+
const failure = error instanceof AgentRunError ? error.cause : error;
|
|
740
|
+
if (hasLostTurnInputCommit(failure)) return { status: "lost_lease" };
|
|
741
|
+
if (stopSignal?.aborted) return await completeCancelledTurn();
|
|
742
|
+
if (!context.attempt.isFinalAttempt) throw failure;
|
|
743
|
+
const failureEventId = modelFailureCaptureAttempted && failureCode === "agent_run_failed" ? modelFailureEventId : captureConversationTurnFailure({
|
|
744
|
+
conversationId: context.conversationId,
|
|
745
|
+
error: failure,
|
|
746
|
+
failureCode,
|
|
747
|
+
runId: currentRunId,
|
|
748
|
+
turnId
|
|
749
|
+
});
|
|
750
|
+
try {
|
|
751
|
+
const latest = await getTurnRecord(context.conversationId, turnId);
|
|
752
|
+
if (latest) await failTurnRecord({
|
|
753
|
+
conversationId: context.conversationId,
|
|
754
|
+
errorMessage: failure instanceof Error ? failure.message : String(failure),
|
|
755
|
+
expectedVersion: latest.version,
|
|
756
|
+
turnId
|
|
757
|
+
});
|
|
758
|
+
} catch (turnRecordError) {
|
|
759
|
+
captureConversationTurnFailure({
|
|
760
|
+
conversationId: context.conversationId,
|
|
761
|
+
error: turnRecordError,
|
|
762
|
+
failureCode: "persistence_failed",
|
|
763
|
+
runId: currentRunId,
|
|
764
|
+
turnId
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
try {
|
|
768
|
+
markTurnFailed({
|
|
769
|
+
conversation,
|
|
770
|
+
nowMs: Date.now(),
|
|
771
|
+
sessionId: turnId,
|
|
772
|
+
userMessageId,
|
|
773
|
+
markConversationMessage
|
|
774
|
+
});
|
|
775
|
+
await persistThreadStateById(context.conversationId, {
|
|
776
|
+
conversation,
|
|
777
|
+
sandboxRef: initialSandboxRef ?? null
|
|
778
|
+
});
|
|
779
|
+
} catch (persistenceError) {
|
|
780
|
+
captureConversationTurnFailure({
|
|
781
|
+
conversationId: context.conversationId,
|
|
782
|
+
error: persistenceError,
|
|
783
|
+
failureCode: "persistence_failed",
|
|
784
|
+
runId: currentRunId,
|
|
785
|
+
turnId
|
|
786
|
+
});
|
|
787
|
+
}
|
|
788
|
+
await lifecycle.fail({
|
|
789
|
+
conversationId: context.conversationId,
|
|
790
|
+
createdAtMs: Date.now(),
|
|
791
|
+
...failureEventId ? { eventId: failureEventId } : void 0,
|
|
792
|
+
failureCode,
|
|
793
|
+
turnId
|
|
794
|
+
});
|
|
795
|
+
if (behavior.failureNotice === "parent") await sendToParent({
|
|
796
|
+
kind: "failed",
|
|
797
|
+
text: failure instanceof Error ? failure.message : String(failure)
|
|
798
|
+
});
|
|
799
|
+
await acknowledge();
|
|
800
|
+
return { status: "completed" };
|
|
801
|
+
}
|
|
802
|
+
});
|
|
803
|
+
};
|
|
804
|
+
}
|
|
805
|
+
export { withTurnSpan as a, resumeConversationDelivery as c, turnInputTelemetry as i, createConversationTurnWorker as n, canPauseConversationDelivery as o, getTurnInputSpanAttributes as r, pauseConversationDelivery as s, conversation_turn_exports as t };
|