@sentry/junior 0.318.0 → 0.319.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/{context-BKF_5zzI.js → adapter-8_S6Birm.js} +537 -537
- package/dist/{admin-UOHix_5P.js → admin-EsbUON1j.js} +1 -1
- package/dist/{agent-runner-DeYymwh2.js → agent-CtzMl32d.js} +18608 -5452
- package/dist/{agent-status-BA5x3Xtp.js → agent-status-Bq_AIpyp.js} +105 -1
- package/dist/{agent-update-delivery-DH8bx7jU.js → agent-update-delivery-pAvsbuGL.js} +4 -5
- package/dist/api/schema.d.ts +43 -23
- package/dist/api/schema.js +4 -4
- package/dist/api.js +70 -80
- package/dist/{app-DKAOuaoC.d.ts → app-tACXxJPI.d.ts} +4 -4
- package/dist/app.d.ts +2 -2
- package/dist/app.js +213 -91
- package/dist/{change-record-BzJgLsv7.d.ts → change-record-K-KsqNhT.d.ts} +9 -5
- package/dist/{channel-access-A0de5lRv.js → channel-access-DET5hzZM.js} +1 -1
- package/dist/{chat-core-engine-D3Wd7f5n.js → chat-core-engine-DpM3tMVi.js} +5 -5
- package/dist/cli/chat.d.ts +1 -1
- package/dist/cli/chat.js +23 -23
- package/dist/cli/check.js +5 -5
- package/dist/cli/main.js +2 -2
- package/dist/cli/plugins.d.ts +1 -1
- package/dist/cli/plugins.js +8 -8
- package/dist/cli/snapshot-create.js +5 -5
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +3 -4
- package/dist/{continue-in-slack-YxwMQVeR.js → continue-in-slack-CFzDyxkH.js} +3 -3
- package/dist/{conversation-feed-Cj7IuBtM.js → conversation-feed-DEUdD7mb.js} +2 -106
- package/dist/{conversation-privacy-Cr_dNW1p.js → conversation-privacy-C2vYK55O.js} +1 -1
- package/dist/{create-Btl1y1rq.js → create-Ta3SEIB5.js} +115 -5
- package/dist/{credential-sync-DTarZ63K.js → credential-sync-DyRqDmY4.js} +15 -18
- package/dist/{db-of6e3sGt.js → db-BCaNWl9p.js} +4579 -717
- package/dist/{deployment-C0qXa0FD.js → deployment-CfOew1Tm.js} +3 -3
- package/dist/{engine-context-C_QL_bMQ.js → engine-context-CiExoy1B.js} +144 -149
- package/dist/{html-9_pS9SjY.js → html-Bb2Si1bR.js} +6 -8
- package/dist/instrumentation.js +7 -23
- package/dist/list-wwDcROh9.js +5007 -0
- package/dist/{logging-BnOG0qz2.js → logging-BRPTXAdf.js} +8 -33
- package/dist/{mailbox-turn-Byrry9o1.js → markers-9QoqW5ov.js} +1675 -1255
- package/dist/nitro.d.ts +2 -2
- package/dist/nitro.js +6 -7
- package/dist/{oauth-callback-server-CjnnUr4o.js → oauth-callback-server-vhL9b-PZ.js} +2 -2
- package/dist/{oauth-relay-BvHFH0fV.js → oauth-relay-CH2v7WiB.js} +1 -1
- package/dist/{plugins-fBrz8PCV.d.ts → plugins-DhGXZjlu.d.ts} +1 -0
- package/dist/{profile-iHw1uu32.js → profile-D9LdwmZi.js} +16 -18
- package/dist/{prompt-DEkStuxG.js → prompt-3TqxEOtc.js} +1 -1
- package/dist/{reports-C1d9azyV.js → reports-K-tbtEyx.js} +2 -2
- package/dist/{resolve-DC6zBuDV.js → resolve-BBV2qf8A.js} +5 -5
- package/dist/{result-DxewDuXb.js → result-5IdGJP4M.js} +20 -9
- package/dist/{runner-99YxVN_r.js → runner-BK_joPlM.js} +7 -8
- package/dist/{sandbox-egress-signals-CgoX5CTI.js → sandbox-egress-signals-DXgWXXmm.js} +1 -1
- package/dist/{schema-BTojNBr5.js → schema-zWGG6VC1.js} +13 -7
- package/dist/{service-account-YDCPSByj.js → service-account-CateFyhw.js} +4 -5
- package/dist/{skills-CleC0Hze.js → skills-Ccjw8h2P.js} +9 -9
- package/dist/{slack-conversation-unfurl-BNQLC12R.js → slack-conversation-unfurl-ZC_TSpc4.js} +7 -7
- package/dist/storage-C9U7R5rM.js +273 -0
- package/dist/{system-prompt-table-Ci6Ck4gk.js → system-prompt-table-YBTHIFlP.js} +26 -84
- package/dist/topic-B2EWKKBT.js +6 -0
- package/dist/{package-discovery-DD9vencX.js → topics-DxuKurCX.js} +21 -1
- package/dist/{types-DCzTAA63.js → types-BNHkJrOP.js} +25 -11
- package/dist/{users-Cb9c1k9q.js → users-CCRAqYb_.js} +1 -1
- package/dist/{validation-BiUmWPhy.js → validation-BCUpJa8K.js} +4 -4
- package/dist/{version-VEXiEcZu.js → version-BNm0JYj3.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{worker-ChWYQdhm.js → worker-BhgpZ7_b.js} +4 -4
- package/migrations/20261127052408_space_name_nullable/migration.sql +5 -0
- package/migrations/20261127052408_space_name_nullable/snapshot.json +29 -0
- package/migrations/20261127060000_annotation_object_id_index/migration.sql +1 -0
- package/migrations/20261127060000_annotation_object_id_index/snapshot.json +69 -0
- package/migrations/20261127060001_annotation_subjects/migration.sql +78 -0
- package/migrations/20261127060001_annotation_subjects/snapshot.json +104 -0
- package/migrations/20261127060002_annotation_subject_index/migration.sql +1 -0
- package/migrations/20261127060002_annotation_subject_index/snapshot.json +70 -0
- package/migrations/20261127060003_annotation_title_url/migration.sql +84 -0
- package/migrations/20261127060003_annotation_title_url/snapshot.json +73 -0
- package/package.json +9 -7
- package/dist/auth-pause-state-f9hJM_zO.js +0 -113
- package/dist/catalog-runtime-BfdAnztW.js +0 -6
- package/dist/child-message-peFWLcCZ.js +0 -15
- package/dist/conversation-turn-Bru4w_FD.js +0 -1250
- package/dist/job-runner-B2XEvpif.js +0 -1505
- package/dist/lineage-nh4z9iQN.js +0 -36
- package/dist/list-HRP3TIRl.js +0 -12631
- package/dist/markers-CTTtJqYn.js +0 -342
- package/dist/message-BRUuLgrY.js +0 -153
- package/dist/model-input-CFC62mf-.js +0 -82
- package/dist/registry-Cl7Labpe.js +0 -3279
- package/dist/run-conversation-Cz2ubZK-.js +0 -337
- package/dist/sender-actors-77zTQbSG.js +0 -84
- package/dist/spawn-DuZfodPa.js +0 -45
- package/dist/task-runner-BJ9Up3bG.js +0 -1529
- package/dist/topic-CRYYBYp-.js +0 -7
- package/dist/topics-BoCkoPJJ.js +0 -21
- package/dist/turn-membership-VT7XZh-L.js +0 -856
- package/dist/turn-wake-C7HeLHAM.js +0 -151
|
@@ -1,1250 +0,0 @@
|
|
|
1
|
-
import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
|
|
2
|
-
import { $o as isConversationDeliveryPaused, An as canJoinTurn, Gl as isEventConversationMessage, Go as JUNIOR_THREAD_STATE_TTL_MS, In as isEventMailboxMetadata, Nl as isTopLevel, Pl as parentResultActor, Pn as readParentMessage, Qn as sendSlackReply, Rl as turnBehavior, Uo as verifyTimerWatchCredentialSubject, Zn as resolveSlackReplyTarget, _i as notifyAutomationBlocked, a as getDb, ai as getDispatchIdForConversation, an as getConversationWorkState, i as getConversationStore, jl as isPersonInput, n as getConversationEventStore, pa as blockEventAutomation, ra as blockScheduledAutomation, ur as getTurnRequestDeadline, uu as indexEndedTurnEvents } from "./db-of6e3sGt.js";
|
|
3
|
-
import { Lt as readConversationAutomationRun, M as measureTurnCompactionWait, mt as resolveConversationDestination, q as stopConversationAndChildAgents } from "./agent-runner-DeYymwh2.js";
|
|
4
|
-
import { T as withSpan, f as logException, m as logWarn, x as setTags, y as setSpanAttributes } from "./logging-BnOG0qz2.js";
|
|
5
|
-
import { Xt as readMessageAttachments, wt as instructionProvenanceFor } from "./types-DCzTAA63.js";
|
|
6
|
-
import { i as loadPendingMessageCards, r as buildDeliveredTurnStatePatch, t as completeAuthPauseTurn } from "./auth-pause-state-f9hJM_zO.js";
|
|
7
|
-
import { At as instructionActorFor, Cr as ConversationTurnLifecycleService, Ct as isHeldInputMessage, Gn as normalizeConversationText, In as persistConversationMessages, J as completeCancelledConversationTurn, Kn as recordDeliveredAssistantMessage, Lr as finalizeFailedTurnReplyWithEvent, M as eventBatchMessageMeta, N as renderEventBatchInputs, Nt as turnRequestText, P as timerWatchCredentialSubject, Pn as hydrateConversationMessages, Pt as withoutSavedSteeringMessages, Tt as loadThreadContextCursor, Un as latestConversationMessageSeq, Vt as buildDeterministicTurnId, Wn as markConversationMessage, Xn as upsertConversationMessage, Y as getTurnUserMessage, _n as commitAcceptedReply, _r as abandonTurnRecord, _t as createWebAuthorization, at as isTurnInputCommitLostError, bn as loadConversationProjection, br as getTurnRecord, bt as eventInboxItemInputs, c as legacyWebMailboxMetadataSchema, d as childAgentTurnOptions, ei as persistWithRetry, f as commitParentMessageFork, ft as getPersistedSandboxState, gr as saveTurnCheckpoint, gt as coerceThreadConversationState, h as isParentMessageAuthor, ht as persistThreadStateById, i as listActiveMailboxTurns, jt as instructionForInputs, kt as buildSteeringPiMessage, lt as markTurnFailed, n as getEventBatchDelayMs, o as sourceFromTurnInput, pt as getPersistedThreadState, qn as renderConversationMessageLine, rt as getConversationTurnBoundaryError, s as turnInputFactsFromConversationMessage, st as markTurnClosed, tt as TurnInputCommitLostError, ut as startActiveTurn, vt as deleteWebAuthorization, wr as getTurnLifecycle, wt as withHeldInput, xt as loadInboxItemInput, yr as failTurnRecord, zn as conversationAuthorDisplayName } from "./mailbox-turn-Byrry9o1.js";
|
|
8
|
-
import { u as isChildAgentEvent } from "./markers-CTTtJqYn.js";
|
|
9
|
-
import { B as authorAttrs, G as mapBounded, W as renderThreadContext } from "./prompt-DEkStuxG.js";
|
|
10
|
-
import { L as botConfig, n as credentialContextForActor, y as getStateAdapter } from "./context-BKF_5zzI.js";
|
|
11
|
-
import { i as getActiveSpan, r as continueTrace } from "./sentry-CPbZjomA.js";
|
|
12
|
-
import { h as getAssistantReplyText } from "./system-prompt-table-Ci6Ck4gk.js";
|
|
13
|
-
import { i as CONVERSATION_METADATA_TASK, n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-BJ9Up3bG.js";
|
|
14
|
-
import { n as getPausedTurnRequest } from "./turn-wake-C7HeLHAM.js";
|
|
15
|
-
import { t as readConversationLineage } from "./lineage-nh4z9iQN.js";
|
|
16
|
-
import * as z from "zod";
|
|
17
|
-
import { indentTagLines, renderTag } from "@sentry/junior-plugin-api";
|
|
18
|
-
import { isDeepStrictEqual } from "node:util";
|
|
19
|
-
import { createHash } from "node:crypto";
|
|
20
|
-
// src/chat/task-execution/turn-telemetry.ts
|
|
21
|
-
/** Read the turn input timing facts from a mailbox batch, oldest first. */
|
|
22
|
-
function turnInputTelemetry(messages) {
|
|
23
|
-
const oldest = messages[0];
|
|
24
|
-
if (!oldest) return void 0;
|
|
25
|
-
return {
|
|
26
|
-
count: messages.length,
|
|
27
|
-
oldestCreatedAtMs: oldest.createdAtMs,
|
|
28
|
-
oldestReceivedAtMs: oldest.receivedAtMs,
|
|
29
|
-
traceContexts: messages.flatMap((message) => message.traceContext ?? [])
|
|
30
|
-
};
|
|
31
|
-
}
|
|
32
|
-
const SENTRY_TRACE_PATTERN = /^([0-9a-f]{32})-([0-9a-f]{16})(?:-([01]))?$/;
|
|
33
|
-
function spanLinks({ sentryTrace }) {
|
|
34
|
-
const [, traceId, spanId, sampled] = SENTRY_TRACE_PATTERN.exec(sentryTrace) ?? [];
|
|
35
|
-
return traceId && spanId ? [{ context: {
|
|
36
|
-
traceId,
|
|
37
|
-
spanId,
|
|
38
|
-
traceFlags: sampled === "1" ? 1 : 0
|
|
39
|
-
} }] : [];
|
|
40
|
-
}
|
|
41
|
-
/**
|
|
42
|
-
* Run a `chat.turn` span in the trace of the first trace context.
|
|
43
|
-
*
|
|
44
|
-
* The span links to the other trace contexts and to the span that was active,
|
|
45
|
-
* such as the worker span. Without a trace context, the span is a child of the
|
|
46
|
-
* active span. A malformed trace context starts a new trace. The span records
|
|
47
|
-
* how long the Turn waited on context compaction.
|
|
48
|
-
*/
|
|
49
|
-
async function withTurnSpan(context, input, callback) {
|
|
50
|
-
const [parent, ...others] = input?.traceContexts ?? [];
|
|
51
|
-
if (!parent) return await withSpan("chat.turn", "chat.turn", context, (set) => measureTurnCompactionWait(set, () => callback(set)));
|
|
52
|
-
const activeSpan = getActiveSpan();
|
|
53
|
-
const links = [...others.flatMap(spanLinks), ...activeSpan ? [{ context: activeSpan.spanContext() }] : []];
|
|
54
|
-
const { baggage, sentryTrace } = parent;
|
|
55
|
-
return await continueTrace({
|
|
56
|
-
baggage,
|
|
57
|
-
sentryTrace
|
|
58
|
-
}, () => withSpan("chat.turn", "chat.turn", context, async (setSpanAttributes) => {
|
|
59
|
-
getActiveSpan()?.addLinks(links);
|
|
60
|
-
return await measureTurnCompactionWait(setSpanAttributes, () => callback(setSpanAttributes));
|
|
61
|
-
}));
|
|
62
|
-
}
|
|
63
|
-
/**
|
|
64
|
-
* Build the `chat.turn` timing attributes for the oldest input message.
|
|
65
|
-
*
|
|
66
|
-
* The provider, the ingress host, and the worker host use separate clocks. A negative
|
|
67
|
-
* duration is clock skew, not latency, so it is left out.
|
|
68
|
-
*/
|
|
69
|
-
function getTurnInputSpanAttributes(input, turnStartedAtMs) {
|
|
70
|
-
const attributes = { "app.turn.input_count": input.count };
|
|
71
|
-
const deliveryLagMs = input.oldestReceivedAtMs - input.oldestCreatedAtMs;
|
|
72
|
-
if (deliveryLagMs >= 0) attributes["app.turn.delivery_lag_ms"] = Math.round(deliveryLagMs);
|
|
73
|
-
const waitMs = turnStartedAtMs - input.oldestReceivedAtMs;
|
|
74
|
-
if (waitMs >= 0) attributes["app.turn.wait_ms"] = Math.round(waitMs);
|
|
75
|
-
return attributes;
|
|
76
|
-
}
|
|
77
|
-
// src/chat/runtime/turn-execution.ts
|
|
78
|
-
/** An error thrown while the agent advances a Run. */
|
|
79
|
-
var AgentRunError = class extends Error {
|
|
80
|
-
constructor(cause) {
|
|
81
|
-
super(cause instanceof Error ? cause.message : "Agent Run failed", { cause });
|
|
82
|
-
this.name = "AgentRunError";
|
|
83
|
-
}
|
|
84
|
-
};
|
|
85
|
-
/**
|
|
86
|
-
* Run the agent and finish the Turn after the caller saves its result.
|
|
87
|
-
*
|
|
88
|
-
* A paused Run, or a Run waiting for authorization, leaves the Turn open. A
|
|
89
|
-
* save error also leaves the Turn open so the worker can retry or recover it.
|
|
90
|
-
* `lifecycle` records the end and sends its agent update.
|
|
91
|
-
*/
|
|
92
|
-
async function executeTurn(agentRunner, run, saveResult, lifecycle = getTurnLifecycle()) {
|
|
93
|
-
let outcome;
|
|
94
|
-
try {
|
|
95
|
-
outcome = await agentRunner.run(run);
|
|
96
|
-
} catch (error) {
|
|
97
|
-
throw new AgentRunError(error);
|
|
98
|
-
}
|
|
99
|
-
if (outcome.status !== "completed") return outcome;
|
|
100
|
-
await finishTurn(lifecycle, run, await saveResult(outcome.result));
|
|
101
|
-
return { status: "completed" };
|
|
102
|
-
}
|
|
103
|
-
async function finishTurn(lifecycle, run, saved) {
|
|
104
|
-
const common = {
|
|
105
|
-
conversationId: run.conversationId,
|
|
106
|
-
createdAtMs: saved.finishedAtMs ?? Date.now(),
|
|
107
|
-
...run.actor ? { reportAs: parentResultActor(run.actor, run.source.kind) } : void 0,
|
|
108
|
-
turnId: run.turnId
|
|
109
|
-
};
|
|
110
|
-
if (saved.outcome === "failed") await lifecycle.fail({
|
|
111
|
-
...common,
|
|
112
|
-
...saved.eventId ? { eventId: saved.eventId } : void 0,
|
|
113
|
-
failureCode: saved.failureCode,
|
|
114
|
-
...saved.failureReason ? { failureReason: saved.failureReason } : void 0,
|
|
115
|
-
...saved.failureText ? { failureText: saved.failureText } : void 0
|
|
116
|
-
});
|
|
117
|
-
else await lifecycle.complete({
|
|
118
|
-
...common,
|
|
119
|
-
...saved.answer ? { answer: saved.answer } : void 0,
|
|
120
|
-
outcome: saved.outcome
|
|
121
|
-
});
|
|
122
|
-
}
|
|
123
|
-
// src/chat/services/automated-turn-limit.ts
|
|
124
|
-
const AUTOMATED_TURN_LIMIT_PREFIX = "junior:automated_turn_limit:v1";
|
|
125
|
-
const AUTOMATED_TURN_LIMIT_LOCK_TTL_MS = 5e3;
|
|
126
|
-
const AUTOMATED_TURN_LIMIT_LOCK_WAIT_MS = 2e3;
|
|
127
|
-
const AUTOMATED_TURN_LIMIT_LOCK_RETRY_MS = 25;
|
|
128
|
-
/**
|
|
129
|
-
* Stored consecutive automated-turn count for one Conversation. Parsing
|
|
130
|
-
* strips the fields of the old pause, so its count still applies.
|
|
131
|
-
*/
|
|
132
|
-
const automatedTurnLimitStateSchema = z.object({
|
|
133
|
-
consecutiveAutomatedTurns: z.number().int().nonnegative(),
|
|
134
|
-
updatedAtMs: z.number().finite().nonnegative()
|
|
135
|
-
});
|
|
136
|
-
function sleep(ms) {
|
|
137
|
-
return new Promise((resolve) => {
|
|
138
|
-
setTimeout(resolve, ms).unref?.();
|
|
139
|
-
});
|
|
140
|
-
}
|
|
141
|
-
function conversationKey(conversationId) {
|
|
142
|
-
return `${AUTOMATED_TURN_LIMIT_PREFIX}:conversation:${conversationId}`;
|
|
143
|
-
}
|
|
144
|
-
function lockKey(key) {
|
|
145
|
-
return `${key}:lock`;
|
|
146
|
-
}
|
|
147
|
-
function parseState(value) {
|
|
148
|
-
const parsed = automatedTurnLimitStateSchema.safeParse(value);
|
|
149
|
-
return parsed.success ? parsed.data : void 0;
|
|
150
|
-
}
|
|
151
|
-
async function acquireConversationLock(state, key, waitDeadlineMs = Date.now() + AUTOMATED_TURN_LIMIT_LOCK_WAIT_MS) {
|
|
152
|
-
while (true) {
|
|
153
|
-
const lock = await state.acquireLock(lockKey(key), AUTOMATED_TURN_LIMIT_LOCK_TTL_MS);
|
|
154
|
-
if (lock) return lock;
|
|
155
|
-
if (Date.now() >= waitDeadlineMs) throw new Error(`Could not acquire automated turn limit lock for ${key}`);
|
|
156
|
-
await sleep(AUTOMATED_TURN_LIMIT_LOCK_RETRY_MS);
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
async function withConversationLock(state, key, callback) {
|
|
160
|
-
const lock = await acquireConversationLock(state, key);
|
|
161
|
-
try {
|
|
162
|
-
return await callback();
|
|
163
|
-
} finally {
|
|
164
|
-
await state.releaseLock(lock);
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
function emptyState(nowMs) {
|
|
168
|
-
return {
|
|
169
|
-
consecutiveAutomatedTurns: 0,
|
|
170
|
-
updatedAtMs: nowMs
|
|
171
|
-
};
|
|
172
|
-
}
|
|
173
|
-
/** True when this Source starts an automated Turn rather than a user Turn. */
|
|
174
|
-
function isAutomatedTurnSource(source) {
|
|
175
|
-
if (!source) return false;
|
|
176
|
-
return source.kind === "event" || source.kind === "event_automation" || source.kind === "scheduled_automation" || source.kind === "plugin_dispatch" || source.kind === "parent_message";
|
|
177
|
-
}
|
|
178
|
-
/** Plain notice when automatic updates stop until the user replies. */
|
|
179
|
-
function buildAutomatedTurnLimitResponse(args) {
|
|
180
|
-
return `I stopped automatic updates after ${args.maxTurns} automated turns without a new message from you. Turns with no reply also count. Send a message or @mention me in this thread to continue.`;
|
|
181
|
-
}
|
|
182
|
-
/** Count one finished automated Turn toward the consecutive-turn limit. */
|
|
183
|
-
async function countAutomatedTurn(args) {
|
|
184
|
-
if (args.maxTurns < 1) throw new Error("Automated turn limit must be at least 1");
|
|
185
|
-
const state = args.state ?? getStateAdapter();
|
|
186
|
-
await state.connect();
|
|
187
|
-
const nowMs = args.nowMs ?? Date.now();
|
|
188
|
-
const key = conversationKey(args.conversationId);
|
|
189
|
-
return await withConversationLock(state, key, async () => {
|
|
190
|
-
const consecutiveAutomatedTurns = (parseState(await state.get(key)) ?? emptyState(nowMs)).consecutiveAutomatedTurns + 1;
|
|
191
|
-
await state.set(key, {
|
|
192
|
-
consecutiveAutomatedTurns,
|
|
193
|
-
updatedAtMs: nowMs
|
|
194
|
-
}, JUNIOR_THREAD_STATE_TTL_MS);
|
|
195
|
-
return {
|
|
196
|
-
consecutiveAutomatedTurns,
|
|
197
|
-
reached: consecutiveAutomatedTurns >= args.maxTurns
|
|
198
|
-
};
|
|
199
|
-
});
|
|
200
|
-
}
|
|
201
|
-
/** Clear the consecutive automated-turn count after a user-owned Turn. */
|
|
202
|
-
async function resetAutomatedTurnLimit(args) {
|
|
203
|
-
const state = args.state ?? getStateAdapter();
|
|
204
|
-
await state.connect();
|
|
205
|
-
const key = conversationKey(args.conversationId);
|
|
206
|
-
await withConversationLock(state, key, async () => {
|
|
207
|
-
await state.delete(key);
|
|
208
|
-
});
|
|
209
|
-
}
|
|
210
|
-
/**
|
|
211
|
-
* Update consecutive automated-turn counts after one finished Turn.
|
|
212
|
-
*
|
|
213
|
-
* Automated Turns count on the Conversation. User Turns clear that count.
|
|
214
|
-
*/
|
|
215
|
-
async function recordFinishedTurnForAutomatedLimit(args) {
|
|
216
|
-
const nowMs = args.nowMs ?? Date.now();
|
|
217
|
-
if (isAutomatedTurnSource(args.source)) return await countAutomatedTurn({
|
|
218
|
-
conversationId: args.conversationId,
|
|
219
|
-
maxTurns: args.maxTurns,
|
|
220
|
-
nowMs,
|
|
221
|
-
state: args.state
|
|
222
|
-
});
|
|
223
|
-
await resetAutomatedTurnLimit({
|
|
224
|
-
conversationId: args.conversationId,
|
|
225
|
-
nowMs,
|
|
226
|
-
state: args.state
|
|
227
|
-
});
|
|
228
|
-
}
|
|
229
|
-
// src/chat/slack/automated-turn-limit-notice.ts
|
|
230
|
-
/**
|
|
231
|
-
* Stop and notice for the consecutive automated-turn limit.
|
|
232
|
-
*
|
|
233
|
-
* The notice is best-effort: a failed post must not fail the Turn or undo the
|
|
234
|
-
* stop.
|
|
235
|
-
*/
|
|
236
|
-
/**
|
|
237
|
-
* Post the stop notice to the Conversation Location when known. A child
|
|
238
|
-
* agent posts none: its parent sees it as stopped in `listAgents`.
|
|
239
|
-
*/
|
|
240
|
-
async function postAutomatedTurnLimitNotice(args) {
|
|
241
|
-
try {
|
|
242
|
-
const conversation = await getConversationStore().get({ conversationId: args.conversationId });
|
|
243
|
-
const location = conversation?.parentConversationId ? void 0 : conversation?.location;
|
|
244
|
-
if (!location || location.provider !== "slack" || conversation?.deliveryPausedAtMs !== void 0) {
|
|
245
|
-
logWarn("automated_turn_limit.notice.skipped", {
|
|
246
|
-
conversationId: args.conversationId,
|
|
247
|
-
"app.automated_turn_limit.reason": !location ? "missing_location" : location.provider !== "slack" ? "unsupported_location" : "delivery_paused"
|
|
248
|
-
});
|
|
249
|
-
return;
|
|
250
|
-
}
|
|
251
|
-
await sendSlackReply({
|
|
252
|
-
...resolveSlackReplyTarget({
|
|
253
|
-
destination: location,
|
|
254
|
-
location,
|
|
255
|
-
source: args.source
|
|
256
|
-
}),
|
|
257
|
-
conversationId: args.conversationId,
|
|
258
|
-
text: buildAutomatedTurnLimitResponse({ maxTurns: args.maxTurns })
|
|
259
|
-
});
|
|
260
|
-
} catch (error) {
|
|
261
|
-
logException(error, "automated_turn_limit.notice.failed", { conversationId: args.conversationId });
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
/**
|
|
265
|
-
* Stop the Conversation tree after a finished Turn reaches the automated-turn
|
|
266
|
-
* limit, then post the notice. Person input that already waits ends the loop
|
|
267
|
-
* by itself, so then nothing stops.
|
|
268
|
-
*/
|
|
269
|
-
async function stopAtAutomatedTurnLimit(args) {
|
|
270
|
-
if (!args.update?.reached) return;
|
|
271
|
-
if (((await getConversationWorkState({ conversationId: args.conversationId }))?.messages ?? []).some((message) => isPersonInput(message.source))) return;
|
|
272
|
-
const nowMs = Date.now();
|
|
273
|
-
await stopConversationAndChildAgents({
|
|
274
|
-
conversationId: args.conversationId,
|
|
275
|
-
finishedRunOf: args.conversationId,
|
|
276
|
-
nowMs,
|
|
277
|
-
stoppedAtMs: nowMs
|
|
278
|
-
});
|
|
279
|
-
await postAutomatedTurnLimitNotice({
|
|
280
|
-
conversationId: args.conversationId,
|
|
281
|
-
maxTurns: args.maxTurns,
|
|
282
|
-
source: args.source
|
|
283
|
-
});
|
|
284
|
-
}
|
|
285
|
-
// src/chat/slack/thread-context.ts
|
|
286
|
-
const CONTEXT_MAX_MESSAGE_CHARS = 8e3;
|
|
287
|
-
const TRUNCATED_MESSAGE_NOTE = " [truncated: read the full Message with slackThreadRead]";
|
|
288
|
-
const THREAD_CONTEXT_MAX_CHARS = 6e4;
|
|
289
|
-
const THREAD_CONTEXT_OMITTED_NOTE = "Older Messages of this thread are not shown. Find them with a searchConversationEvents query, then read them with readConversationEvent.";
|
|
290
|
-
function isTakeOrDismissOnly(message) {
|
|
291
|
-
const changes = message.meta?.reviewItemChanges;
|
|
292
|
-
return Boolean(changes?.length && changes.every((change) => change.kind === "taken" || change.kind === "dismissed"));
|
|
293
|
-
}
|
|
294
|
-
function capMessageText(text) {
|
|
295
|
-
const compact = text.replace(/\s+/g, " ");
|
|
296
|
-
return compact.length > CONTEXT_MAX_MESSAGE_CHARS ? `${compact.slice(0, CONTEXT_MAX_MESSAGE_CHARS)}${TRUNCATED_MESSAGE_NOTE}` : compact;
|
|
297
|
-
}
|
|
298
|
-
function renderThreadContextMessage(message, conversation, index) {
|
|
299
|
-
return indentTagLines(renderTag("message", {
|
|
300
|
-
index,
|
|
301
|
-
sent_at: new Date(message.createdAtMs).toISOString(),
|
|
302
|
-
role: message.role,
|
|
303
|
-
...authorAttrs({
|
|
304
|
-
authorId: message.author?.userId,
|
|
305
|
-
authorName: conversationAuthorDisplayName(message)
|
|
306
|
-
}),
|
|
307
|
-
slack_ts: message.meta?.slackTs
|
|
308
|
-
}, [renderConversationMessageLine(message, conversation, capMessageText(message.text))]), " ");
|
|
309
|
-
}
|
|
310
|
-
function isUntaggedThreadMessage(message) {
|
|
311
|
-
return message.role === "user" && !message.meta?.explicitMention && !isEventConversationMessage(message);
|
|
312
|
-
}
|
|
313
|
-
/**
|
|
314
|
-
* Render the thread Messages that this Turn needs as one evidence-only block.
|
|
315
|
-
*
|
|
316
|
-
* With agent history, earlier Turns already hold their thread context, Turn
|
|
317
|
-
* input, and replies. So only untagged Messages saved after the cursor of the
|
|
318
|
-
* previous Turn are new. Without history, show the latest Messages. Both keep
|
|
319
|
-
* the newest Messages under one hard size cap, so the block cannot grow with
|
|
320
|
-
* the thread.
|
|
321
|
-
*/
|
|
322
|
-
function buildConversationContext(conversation, options = {}) {
|
|
323
|
-
const { history } = options;
|
|
324
|
-
const candidates = conversation.messages.filter((entry) => !options.excludeMessageIds?.includes(entry.id) && !isTakeOrDismissOnly(entry) && !isHeldInputMessage(entry) && (!history || isUntaggedThreadMessage(entry) && (history.afterSeq === void 0 || entry.seq === void 0 || entry.seq > history.afterSeq)));
|
|
325
|
-
let first = candidates.length;
|
|
326
|
-
let chars = 0;
|
|
327
|
-
while (first > 0) {
|
|
328
|
-
const size = renderThreadContextMessage(candidates[first - 1], conversation, first).length;
|
|
329
|
-
if (chars + size > THREAD_CONTEXT_MAX_CHARS) break;
|
|
330
|
-
chars += size;
|
|
331
|
-
first -= 1;
|
|
332
|
-
}
|
|
333
|
-
const shown = candidates.slice(first).map((message, index) => renderThreadContextMessage(message, conversation, index + 1));
|
|
334
|
-
const counts = {
|
|
335
|
-
shownMessages: shown.length,
|
|
336
|
-
omittedMessages: candidates.length - shown.length
|
|
337
|
-
};
|
|
338
|
-
if (shown.length === 0) return counts;
|
|
339
|
-
const lines = [renderThreadContext(shown)];
|
|
340
|
-
if (shown.length < candidates.length || !history && conversation.historyFromSeq !== void 0) lines.push(THREAD_CONTEXT_OMITTED_NOTE);
|
|
341
|
-
return {
|
|
342
|
-
...counts,
|
|
343
|
-
text: lines.join("\n")
|
|
344
|
-
};
|
|
345
|
-
}
|
|
346
|
-
/**
|
|
347
|
-
* Build the thread context of one Turn prompt in a Slack thread. With agent
|
|
348
|
-
* history, show only the thread Messages saved after the cursor of the
|
|
349
|
-
* previous Turn.
|
|
350
|
-
*
|
|
351
|
-
* Sets `app.thread_context.*` on the active span: `chat.reply` in a Slack
|
|
352
|
-
* Turn, `chat.turn` in a web or Event Turn. Cursor `missing` means that the
|
|
353
|
-
* previous Turn ran before cursors existed.
|
|
354
|
-
*/
|
|
355
|
-
async function buildTurnThreadContext(args) {
|
|
356
|
-
const afterSeq = args.hasHistory ? await loadThreadContextCursor({
|
|
357
|
-
conversationId: args.conversationId,
|
|
358
|
-
turnId: args.turnId
|
|
359
|
-
}) : void 0;
|
|
360
|
-
const block = buildConversationContext(args.conversation, {
|
|
361
|
-
excludeMessageIds: args.excludeMessageIds,
|
|
362
|
-
...args.hasHistory ? { history: { afterSeq } } : void 0
|
|
363
|
-
});
|
|
364
|
-
setSpanAttributes({
|
|
365
|
-
"app.thread_context.chars": block.text?.length ?? 0,
|
|
366
|
-
"app.thread_context.shown_messages": block.shownMessages,
|
|
367
|
-
"app.thread_context.omitted_messages": block.omittedMessages,
|
|
368
|
-
"app.thread_context.cursor": !args.hasHistory ? "no_history" : afterSeq === void 0 ? "missing" : "found"
|
|
369
|
-
});
|
|
370
|
-
return block.text;
|
|
371
|
-
}
|
|
372
|
-
// src/chat/task-execution/supersede-turns.ts
|
|
373
|
-
/**
|
|
374
|
-
* End every open mailbox Turn other than `keepTurnId`, so new input runs in
|
|
375
|
-
* the only open Turn. New input starts only when no yielded Turn waits, so an
|
|
376
|
-
* open Turn here waits for OAuth or was left open by a failed or stopped Run.
|
|
377
|
-
* The caller persists `conversation`. Returns false when `isStopped` turns
|
|
378
|
-
* true first.
|
|
379
|
-
*/
|
|
380
|
-
async function supersedeOpenMailboxTurns(args) {
|
|
381
|
-
return await supersedeTurns({
|
|
382
|
-
...args,
|
|
383
|
-
turns: (await listActiveMailboxTurns(args.conversationId)).filter((record) => record.turnId !== args.keepTurnId)
|
|
384
|
-
});
|
|
385
|
-
}
|
|
386
|
-
/**
|
|
387
|
-
* End open Turns that new input replaces. A late resume or OAuth callback
|
|
388
|
-
* for an ended Turn is a no-op. The caller persists `conversation`. Returns
|
|
389
|
-
* false when `isStopped` turns true first.
|
|
390
|
-
*/
|
|
391
|
-
async function supersedeTurns(args) {
|
|
392
|
-
const pendingAuthorizationActorId = args.conversation.processing.pendingAuth?.actorId;
|
|
393
|
-
for (const stale of args.turns) {
|
|
394
|
-
if (args.isStopped?.()) return false;
|
|
395
|
-
await abandonTurnRecord({
|
|
396
|
-
conversationId: args.conversationId,
|
|
397
|
-
turnId: stale.turnId,
|
|
398
|
-
errorMessage: "Turn superseded by new input"
|
|
399
|
-
});
|
|
400
|
-
await getTurnLifecycle().complete({
|
|
401
|
-
conversationId: args.conversationId,
|
|
402
|
-
createdAtMs: Date.now(),
|
|
403
|
-
outcome: "cancelled",
|
|
404
|
-
turnId: stale.turnId
|
|
405
|
-
});
|
|
406
|
-
markTurnClosed({
|
|
407
|
-
conversation: args.conversation,
|
|
408
|
-
nowMs: Date.now(),
|
|
409
|
-
sessionId: stale.turnId
|
|
410
|
-
});
|
|
411
|
-
}
|
|
412
|
-
if (args.turns.some((record) => record.state === "paused" && record.resumeReason === "auth") && pendingAuthorizationActorId) await deleteWebAuthorization({
|
|
413
|
-
actorId: pendingAuthorizationActorId,
|
|
414
|
-
conversationId: args.conversationId
|
|
415
|
-
});
|
|
416
|
-
return true;
|
|
417
|
-
}
|
|
418
|
-
/**
|
|
419
|
-
* End the Turn that waits for its next Run when `message` cannot join it, so
|
|
420
|
-
* the message starts its own Turn instead of running with that Turn's Actor.
|
|
421
|
-
* A stored legacy Turn without an Actor keeps taking the input.
|
|
422
|
-
*/
|
|
423
|
-
async function supersedeTurnForInput(args) {
|
|
424
|
-
const conversation = coerceThreadConversationState(await getPersistedThreadState(args.conversationId));
|
|
425
|
-
const turnId = conversation.processing.activeTurnId;
|
|
426
|
-
if (!turnId || !await getPausedTurnRequest({
|
|
427
|
-
conversationId: args.conversationId,
|
|
428
|
-
turnId
|
|
429
|
-
})) return;
|
|
430
|
-
const turn = await getTurnRecord(args.conversationId, turnId);
|
|
431
|
-
if (!turn?.actor || canJoinTurn(turn, args.message)) return;
|
|
432
|
-
await hydrateConversationMessages({
|
|
433
|
-
conversation,
|
|
434
|
-
conversationId: args.conversationId
|
|
435
|
-
});
|
|
436
|
-
await supersedeTurns({
|
|
437
|
-
conversation,
|
|
438
|
-
conversationId: args.conversationId,
|
|
439
|
-
turns: [turn]
|
|
440
|
-
});
|
|
441
|
-
await persistThreadStateById(args.conversationId, { conversation });
|
|
442
|
-
}
|
|
443
|
-
// src/chat/automations/block-run.ts
|
|
444
|
-
/**
|
|
445
|
-
* Block the Automation of a run from a later Turn of the run, such as a Watch
|
|
446
|
-
* Event or child result Turn. The dispatch Turn blocks through its dispatch
|
|
447
|
-
* outcome. Its creator is told when the block is first stored.
|
|
448
|
-
*/
|
|
449
|
-
async function blockRunAutomation(conversationId, blocked) {
|
|
450
|
-
const dispatchId = getDispatchIdForConversation(conversationId);
|
|
451
|
-
const automation = await readConversationAutomationRun(conversationId);
|
|
452
|
-
if (!automation) {
|
|
453
|
-
logWarn("automation.block.unresolved", { "gen_ai.conversation.id": conversationId });
|
|
454
|
-
return;
|
|
455
|
-
}
|
|
456
|
-
const { automationId, kind } = automation;
|
|
457
|
-
if (kind === "scheduled" ? await blockScheduledAutomation(getDb(), automationId, blocked.missing) : await blockEventAutomation(getDb(), automationId, blocked.missing)) await notifyAutomationBlocked({
|
|
458
|
-
automationId,
|
|
459
|
-
...dispatchId ? { dispatchId } : void 0,
|
|
460
|
-
kind,
|
|
461
|
-
reason: blocked.missing
|
|
462
|
-
});
|
|
463
|
-
}
|
|
464
|
-
// src/chat/task-execution/assistant-message.ts
|
|
465
|
-
/** Store one assistant Message and its Agent history. */
|
|
466
|
-
async function commitAssistantMessage(args) {
|
|
467
|
-
const conversationMessageId = recordDeliveredAssistantMessage({
|
|
468
|
-
cards: args.cards,
|
|
469
|
-
conversation: args.conversation,
|
|
470
|
-
sessionId: args.sessionId,
|
|
471
|
-
source: args.source,
|
|
472
|
-
text: args.text,
|
|
473
|
-
userMessageId: args.userMessageId
|
|
474
|
-
});
|
|
475
|
-
if (args.deliveryResult?.providerMessageId) markConversationMessage(args.conversation, conversationMessageId, { slackTs: args.deliveryResult.providerMessageId });
|
|
476
|
-
try {
|
|
477
|
-
await persistWithRetry(() => commitAcceptedReply({
|
|
478
|
-
...args.agentMessage ? { agentMessage: args.agentMessage } : void 0,
|
|
479
|
-
conversation: args.conversation,
|
|
480
|
-
conversationMessageId,
|
|
481
|
-
conversationId: args.conversationId,
|
|
482
|
-
providerConversationBindings: args.deliveryResult?.providerConversationBindings
|
|
483
|
-
}));
|
|
484
|
-
} catch (error) {
|
|
485
|
-
logException(error, "conversation.assistant.message_persist.failed");
|
|
486
|
-
}
|
|
487
|
-
}
|
|
488
|
-
// src/chat/task-execution/turn-end-tasks.ts
|
|
489
|
-
/**
|
|
490
|
-
* The background work after a Turn ends: plugin session tasks, event search,
|
|
491
|
-
* and Conversation metadata. A failure is logged, so this work never changes
|
|
492
|
-
* the Turn's outcome.
|
|
493
|
-
*/
|
|
494
|
-
async function runTask(message, conversationId, turnId) {
|
|
495
|
-
try {
|
|
496
|
-
await processPluginTask(message);
|
|
497
|
-
} catch (error) {
|
|
498
|
-
logException(error, "conversation.plugin.session_completion_task.failed", {
|
|
499
|
-
conversationId,
|
|
500
|
-
pluginName: message.plugin,
|
|
501
|
-
taskName: message.name,
|
|
502
|
-
turnId
|
|
503
|
-
});
|
|
504
|
-
}
|
|
505
|
-
}
|
|
506
|
-
/**
|
|
507
|
-
* Run the work after one ended Turn. A completed Turn with session tasks
|
|
508
|
-
* runs every session task, which includes event search and metadata. Any
|
|
509
|
-
* other Turn indexes its events, and a completed one also updates its
|
|
510
|
-
* metadata when its behavior asks for it, as a Thread's does.
|
|
511
|
-
*/
|
|
512
|
-
async function runTurnEndTasks(args) {
|
|
513
|
-
const { behavior, conversationId, turnId } = args;
|
|
514
|
-
const params = {
|
|
515
|
-
conversationId,
|
|
516
|
-
sessionId: turnId
|
|
517
|
-
};
|
|
518
|
-
if (args.completed && behavior.sessionTasks) {
|
|
519
|
-
try {
|
|
520
|
-
await scheduleSessionCompletedPluginTasks(params, async (message) => {
|
|
521
|
-
await runTask(message, conversationId, turnId);
|
|
522
|
-
});
|
|
523
|
-
} catch (error) {
|
|
524
|
-
logException(error, "conversation.plugin.session_completion_task.failed", {
|
|
525
|
-
conversationId,
|
|
526
|
-
turnId
|
|
527
|
-
});
|
|
528
|
-
}
|
|
529
|
-
return;
|
|
530
|
-
}
|
|
531
|
-
await indexEndedTurnEvents({
|
|
532
|
-
conversationId,
|
|
533
|
-
turnId
|
|
534
|
-
});
|
|
535
|
-
if (args.completed && behavior.conversationMetadata) await runTask({
|
|
536
|
-
...CONVERSATION_METADATA_TASK,
|
|
537
|
-
params
|
|
538
|
-
}, conversationId, turnId);
|
|
539
|
-
}
|
|
540
|
-
// src/chat/task-execution/turn-failure.ts
|
|
541
|
-
function captureConversationTurnFailure(args) {
|
|
542
|
-
const eventId = logException(args.error, `conversation.turn.${args.failureCode}`, {
|
|
543
|
-
conversationId: args.conversationId,
|
|
544
|
-
...args.runId ? { runId: args.runId } : void 0,
|
|
545
|
-
turnId: args.turnId
|
|
546
|
-
});
|
|
547
|
-
return typeof eventId === "string" ? eventId : void 0;
|
|
548
|
-
}
|
|
549
|
-
/**
|
|
550
|
-
* Record a final-attempt failure on the Turn record, the Conversation, and
|
|
551
|
-
* the Turn lifecycle, so the Turn ends failed and its update reaches the
|
|
552
|
-
* starter and Watches. The caller still acknowledges the input.
|
|
553
|
-
*/
|
|
554
|
-
async function failConversationTurn(args) {
|
|
555
|
-
const { conversation, conversationId, failure, failureCode, runId, turnId, userMessageId } = args;
|
|
556
|
-
const failureEventId = args.modelFailureCaptureAttempted && failureCode === "agent_run_failed" ? args.modelFailureEventId : captureConversationTurnFailure({
|
|
557
|
-
conversationId,
|
|
558
|
-
error: failure,
|
|
559
|
-
failureCode,
|
|
560
|
-
runId,
|
|
561
|
-
turnId
|
|
562
|
-
});
|
|
563
|
-
try {
|
|
564
|
-
const latest = await getTurnRecord(conversationId, turnId);
|
|
565
|
-
if (latest) await failTurnRecord({
|
|
566
|
-
conversationId,
|
|
567
|
-
errorMessage: failure instanceof Error ? failure.message : String(failure),
|
|
568
|
-
expectedVersion: latest.version,
|
|
569
|
-
turnId
|
|
570
|
-
});
|
|
571
|
-
} catch (turnRecordError) {
|
|
572
|
-
captureConversationTurnFailure({
|
|
573
|
-
conversationId,
|
|
574
|
-
error: turnRecordError,
|
|
575
|
-
failureCode: "persistence_failed",
|
|
576
|
-
runId,
|
|
577
|
-
turnId
|
|
578
|
-
});
|
|
579
|
-
}
|
|
580
|
-
try {
|
|
581
|
-
markTurnFailed({
|
|
582
|
-
conversation,
|
|
583
|
-
nowMs: Date.now(),
|
|
584
|
-
sessionId: turnId,
|
|
585
|
-
userMessageId,
|
|
586
|
-
markConversationMessage
|
|
587
|
-
});
|
|
588
|
-
await persistThreadStateById(conversationId, {
|
|
589
|
-
conversation,
|
|
590
|
-
sandboxRef: args.sandboxRef ?? null
|
|
591
|
-
});
|
|
592
|
-
} catch (persistenceError) {
|
|
593
|
-
captureConversationTurnFailure({
|
|
594
|
-
conversationId,
|
|
595
|
-
error: persistenceError,
|
|
596
|
-
failureCode: "persistence_failed",
|
|
597
|
-
runId,
|
|
598
|
-
turnId
|
|
599
|
-
});
|
|
600
|
-
}
|
|
601
|
-
await args.lifecycle.fail({
|
|
602
|
-
conversationId,
|
|
603
|
-
createdAtMs: Date.now(),
|
|
604
|
-
...failureEventId ? { eventId: failureEventId } : void 0,
|
|
605
|
-
failureCode,
|
|
606
|
-
failureText: failure instanceof Error ? failure.message : String(failure),
|
|
607
|
-
reportAs: args.reportAs,
|
|
608
|
-
turnId
|
|
609
|
-
});
|
|
610
|
-
await indexEndedTurnEvents({
|
|
611
|
-
conversationId,
|
|
612
|
-
turnId
|
|
613
|
-
});
|
|
614
|
-
}
|
|
615
|
-
// src/chat/task-execution/mailbox-input.ts
|
|
616
|
-
/**
|
|
617
|
-
* Return the Turn inputs of web Messages, one per non-empty Message, in
|
|
618
|
-
* order. Each one becomes its own prompt content part. A Message that
|
|
619
|
-
* records an answer becomes its Inbox item tag. A batch with only
|
|
620
|
-
* attachments keeps one empty input, so the prompt still has an instruction.
|
|
621
|
-
*/
|
|
622
|
-
async function webTurnInputs(messages) {
|
|
623
|
-
const flat = (await mapBounded(messages, async (message) => {
|
|
624
|
-
const inboxItem = await loadInboxItemInput(message.reviewItemChange);
|
|
625
|
-
if (inboxItem) return [inboxItem];
|
|
626
|
-
const text = message.text.trim();
|
|
627
|
-
return text ? [{
|
|
628
|
-
kind: "person",
|
|
629
|
-
text
|
|
630
|
-
}] : [];
|
|
631
|
-
})).flat();
|
|
632
|
-
return flat.length ? flat : [{
|
|
633
|
-
kind: "person",
|
|
634
|
-
text: ""
|
|
635
|
-
}];
|
|
636
|
-
}
|
|
637
|
-
/**
|
|
638
|
-
* Build the transcript Message for one web mailbox Message. Each web Message
|
|
639
|
-
* keeps its own transcript Message and Inbox item change record, so the
|
|
640
|
-
* dashboard shows what each Message did even when several share a Turn.
|
|
641
|
-
*/
|
|
642
|
-
function webConversationMessage(message, author) {
|
|
643
|
-
const attachments = readMessageAttachments(message.input.attachments);
|
|
644
|
-
const { reviewItemChange } = message.input;
|
|
645
|
-
return {
|
|
646
|
-
id: message.inboundMessageId,
|
|
647
|
-
role: "user",
|
|
648
|
-
text: normalizeConversationText(message.input.text),
|
|
649
|
-
createdAtMs: message.createdAtMs,
|
|
650
|
-
author,
|
|
651
|
-
...message.input.authorIdentityId ? { authorIdentityId: message.input.authorIdentityId } : void 0,
|
|
652
|
-
meta: {
|
|
653
|
-
...attachments.length ? { attachments } : void 0,
|
|
654
|
-
explicitMention: true,
|
|
655
|
-
...reviewItemChange ? { reviewItemChanges: [reviewItemChange] } : void 0,
|
|
656
|
-
source: "web"
|
|
657
|
-
}
|
|
658
|
-
};
|
|
659
|
-
}
|
|
660
|
-
/**
|
|
661
|
-
* Build the transcript Messages of a new web Turn, in input order. The Turn
|
|
662
|
-
* saves its first input unreplied. `message_handled` records the reply.
|
|
663
|
-
*/
|
|
664
|
-
function webTurnInputMessages(batch) {
|
|
665
|
-
return batch.map((entry, index) => {
|
|
666
|
-
const message = webConversationMessage(entry.message, entry.author);
|
|
667
|
-
return index === 0 ? {
|
|
668
|
-
...message,
|
|
669
|
-
meta: {
|
|
670
|
-
...message.meta,
|
|
671
|
-
replied: false
|
|
672
|
-
}
|
|
673
|
-
} : message;
|
|
674
|
-
});
|
|
675
|
-
}
|
|
676
|
-
/**
|
|
677
|
-
* Return the saved input Messages of a resumed Turn in input order. A web
|
|
678
|
-
* batch saves each Message apart. An older Turn saved one joined Message, so
|
|
679
|
-
* its other input ids have no saved Message.
|
|
680
|
-
*/
|
|
681
|
-
function savedTurnInputMessages(conversation, turnMessage, inputMessageIds) {
|
|
682
|
-
const saved = (inputMessageIds ?? []).flatMap((id) => conversation.messages.find((message) => message.id === id && message.role === "user") ?? []);
|
|
683
|
-
return saved.some((message) => message.id === turnMessage.id) ? saved : [turnMessage];
|
|
684
|
-
}
|
|
685
|
-
/**
|
|
686
|
-
* Render the Turn inputs of one new mailbox batch. A parent batch is the
|
|
687
|
-
* parent's task. An Event batch also returns the
|
|
688
|
-
* meta of its one saved Message. A web batch returns one transcript Message
|
|
689
|
-
* per input.
|
|
690
|
-
*/
|
|
691
|
-
async function mailboxTurnInputs(batch, fromParent) {
|
|
692
|
-
const messages = batch.map((entry) => entry.message);
|
|
693
|
-
if (fromParent) return {
|
|
694
|
-
eventMeta: {},
|
|
695
|
-
inputs: batch.map(({ message, requestText }) => ({
|
|
696
|
-
kind: "runtime",
|
|
697
|
-
text: message.input.text.trim(),
|
|
698
|
-
...requestText ? { requestText } : void 0
|
|
699
|
-
})),
|
|
700
|
-
webInputMessages: []
|
|
701
|
-
};
|
|
702
|
-
if (isEventMailboxMetadata(messages[0]?.input.metadata)) return {
|
|
703
|
-
eventMeta: eventBatchMessageMeta(messages),
|
|
704
|
-
inputs: renderEventBatchInputs(messages, await eventInboxItemInputs(messages)),
|
|
705
|
-
webInputMessages: []
|
|
706
|
-
};
|
|
707
|
-
return {
|
|
708
|
-
eventMeta: {},
|
|
709
|
-
inputs: await webTurnInputs(messages.map((message) => message.input)),
|
|
710
|
-
webInputMessages: webTurnInputMessages(batch)
|
|
711
|
-
};
|
|
712
|
-
}
|
|
713
|
-
// src/chat/task-execution/web-steering.ts
|
|
714
|
-
async function steeringMessageFromWeb(message, actor) {
|
|
715
|
-
const storedAttachments = readMessageAttachments(message.input.attachments);
|
|
716
|
-
const inboxItemInput = await loadInboxItemInput(message.input.reviewItemChange);
|
|
717
|
-
return {
|
|
718
|
-
actor: instructionActorFor(actor),
|
|
719
|
-
...inboxItemInput ? { kind: "runtime" } : void 0,
|
|
720
|
-
provenance: instructionProvenanceFor(actor),
|
|
721
|
-
text: inboxItemInput?.text ?? message.input.text.trim(),
|
|
722
|
-
timestampMs: message.createdAtMs,
|
|
723
|
-
...storedAttachments.length ? { storedAttachments } : void 0
|
|
724
|
-
};
|
|
725
|
-
}
|
|
726
|
-
/**
|
|
727
|
-
* Drain steered web messages into the active web Turn.
|
|
728
|
-
*
|
|
729
|
-
* Only messages from the Turn Actor join. Steered messages from another
|
|
730
|
-
* participant stay pending and start their own Turn next, so they never act
|
|
731
|
-
* with this Actor's credentials.
|
|
732
|
-
*/
|
|
733
|
-
function createWebSteeringDrain(args) {
|
|
734
|
-
const { actor, author, context, conversation, turnId } = args;
|
|
735
|
-
return async (accept) => {
|
|
736
|
-
const accepted = [];
|
|
737
|
-
await context.attempt.drain(async (pending) => {
|
|
738
|
-
const joining = pending.filter((message) => message.source === "web" && message.input.authorId === actor.userId && legacyWebMailboxMetadataSchema.safeParse(message.input.metadata).success);
|
|
739
|
-
if (joining.length === 0) return [];
|
|
740
|
-
for (const message of joining) upsertConversationMessage(conversation, webConversationMessage(message, author));
|
|
741
|
-
await persistConversationMessages({
|
|
742
|
-
conversation,
|
|
743
|
-
conversationId: context.conversationId
|
|
744
|
-
});
|
|
745
|
-
const saved = (await getTurnRecord(context.conversationId, turnId))?.piMessages ?? [];
|
|
746
|
-
const messages = withoutSavedSteeringMessages(saved, await mapBounded(joining, (message) => steeringMessageFromWeb(message, actor)), buildSteeringPiMessage);
|
|
747
|
-
if (messages.length > 0) {
|
|
748
|
-
await accept(messages);
|
|
749
|
-
accepted.push(...messages);
|
|
750
|
-
}
|
|
751
|
-
return joining.map((message) => message.inboundMessageId);
|
|
752
|
-
});
|
|
753
|
-
return accepted;
|
|
754
|
-
};
|
|
755
|
-
}
|
|
756
|
-
// src/chat/task-execution/turn-credentials.ts
|
|
757
|
-
/**
|
|
758
|
-
* Return a saved timer creator subject when it is still valid here. The
|
|
759
|
-
* timer's Watch belongs to this Conversation. It may also belong to an
|
|
760
|
-
* ancestor when `fromParent`: the input is a parent message that passed its
|
|
761
|
-
* sender check, so the child continues the work of the parent's timer Turn.
|
|
762
|
-
*/
|
|
763
|
-
async function verifiedTimerWatchSubject(conversationId, subject, fromParent) {
|
|
764
|
-
if (subject?.binding.type !== "timer-watch") return void 0;
|
|
765
|
-
const watchConversationId = subject.binding.conversationId;
|
|
766
|
-
if (watchConversationId !== conversationId && !(fromParent && (await readConversationLineage(conversationId)).some((entry) => entry.conversationId === watchConversationId))) return;
|
|
767
|
-
return verifyTimerWatchCredentialSubject({
|
|
768
|
-
conversationId: watchConversationId,
|
|
769
|
-
subject,
|
|
770
|
-
watchId: subject.binding.watchId
|
|
771
|
-
}) ? subject : void 0;
|
|
772
|
-
}
|
|
773
|
-
/** Return the delegated subject that every input of a batch carries, if any. */
|
|
774
|
-
function sharedDelegatedSubject(batch) {
|
|
775
|
-
const subjects = batch.map((entry) => entry.credentialContext && "subject" in entry.credentialContext ? entry.credentialContext.subject : void 0);
|
|
776
|
-
const first = subjects[0];
|
|
777
|
-
return first && subjects.every((subject) => isDeepStrictEqual(subject, first)) ? first : void 0;
|
|
778
|
-
}
|
|
779
|
-
// src/chat/task-execution/conversation-turn.ts
|
|
780
|
-
/** Run a mailbox Turn and store its assistant Messages. */
|
|
781
|
-
var conversation_turn_exports = /* @__PURE__ */ __exportAll({ createConversationTurnWorker: () => createConversationTurnWorker });
|
|
782
|
-
function stableHex(...parts) {
|
|
783
|
-
return createHash("sha256").update(parts.join("\0")).digest("hex").slice(0, 24);
|
|
784
|
-
}
|
|
785
|
-
function hasLostTurnInputCommit(error) {
|
|
786
|
-
const cause = getConversationTurnBoundaryError(error)?.cause ?? error;
|
|
787
|
-
return isTurnInputCommitLostError(error) || isTurnInputCommitLostError(cause);
|
|
788
|
-
}
|
|
789
|
-
/**
|
|
790
|
-
* Return the author Identity id that every batched input shares.
|
|
791
|
-
* A batch with more than one author has no single author yet.
|
|
792
|
-
*/
|
|
793
|
-
function sharedAuthorIdentityId(messages) {
|
|
794
|
-
const ids = new Set(messages.map((message) => message.input.authorIdentityId));
|
|
795
|
-
return ids.size === 1 ? [...ids][0] : void 0;
|
|
796
|
-
}
|
|
797
|
-
function turnAnswerText(reply) {
|
|
798
|
-
if (reply.reply) return void 0;
|
|
799
|
-
if (reply.blocked) return {
|
|
800
|
-
kind: "note",
|
|
801
|
-
text: reply.blocked.missing
|
|
802
|
-
};
|
|
803
|
-
if (reply.noReply) return {
|
|
804
|
-
kind: "note",
|
|
805
|
-
text: reply.noReply.note ?? ""
|
|
806
|
-
};
|
|
807
|
-
const text = reply.text.trim();
|
|
808
|
-
return text ? {
|
|
809
|
-
kind: "final_text",
|
|
810
|
-
text
|
|
811
|
-
} : void 0;
|
|
812
|
-
}
|
|
813
|
-
/**
|
|
814
|
-
* Create the shared mailbox worker for web and event Turns of every
|
|
815
|
-
* Conversation kind. `deliverMessage` posts to a Location. `updates` is
|
|
816
|
-
* where each Turn's agent update goes, to the starter of a child agent and
|
|
817
|
-
* to the Watches of any Conversation, by default the production queue.
|
|
818
|
-
*/
|
|
819
|
-
function createConversationTurnWorker(agentRunner, deliverMessage, updates) {
|
|
820
|
-
const lifecycle = updates ? new ConversationTurnLifecycleService(getConversationEventStore(), {
|
|
821
|
-
state: updates.state,
|
|
822
|
-
watchQueue: () => updates.queue
|
|
823
|
-
}) : getTurnLifecycle();
|
|
824
|
-
return async (context, resolved) => {
|
|
825
|
-
if (resolved.kind === "mailbox") {
|
|
826
|
-
const delayMs = getEventBatchDelayMs(resolved.batch.map((entry) => entry.message));
|
|
827
|
-
if (delayMs > 0) return {
|
|
828
|
-
status: "deferred",
|
|
829
|
-
delayMs
|
|
830
|
-
};
|
|
831
|
-
}
|
|
832
|
-
const isResume = resolved.kind === "resume";
|
|
833
|
-
let turnInputFacts;
|
|
834
|
-
let inputs = [];
|
|
835
|
-
let attachments = [];
|
|
836
|
-
let turnId = "";
|
|
837
|
-
let userMessageId = "";
|
|
838
|
-
let startedAtMs = Date.now();
|
|
839
|
-
let inputMessageIds = [];
|
|
840
|
-
let eventMeta = {};
|
|
841
|
-
let fromParent = resolved.kind === "mailbox" && resolved.batch.every((entry) => readParentMessage(entry.message));
|
|
842
|
-
let fromChildAgent = false;
|
|
843
|
-
let authorIdentityId;
|
|
844
|
-
let webInputMessages = [];
|
|
845
|
-
const storedConversation = await getConversationStore().get({ conversationId: context.conversationId });
|
|
846
|
-
const kind = storedConversation?.kind ?? "thread";
|
|
847
|
-
const visibility = isTopLevel({ parentConversationId: storedConversation?.parentConversationId }) ? storedConversation?.visibility : storedConversation?.visibility ?? "private";
|
|
848
|
-
const mailboxDestination = resolved.kind === "mailbox" ? resolved.batch[0]?.message.destination : void 0;
|
|
849
|
-
const destination = resolveConversationDestination({
|
|
850
|
-
conversationId: context.conversationId,
|
|
851
|
-
existing: context.destination ?? mailboxDestination ?? storedConversation?.destination
|
|
852
|
-
});
|
|
853
|
-
if (resolved.kind === "mailbox") {
|
|
854
|
-
const first = resolved.batch[0];
|
|
855
|
-
const messages = resolved.batch.map((entry) => entry.message);
|
|
856
|
-
({eventMeta, inputs, webInputMessages} = await mailboxTurnInputs(resolved.batch, fromParent));
|
|
857
|
-
fromChildAgent = isChildAgentEvent(eventMeta);
|
|
858
|
-
attachments = resolved.batch.flatMap((entry) => readMessageAttachments(entry.message.input.attachments));
|
|
859
|
-
startedAtMs = first.message.createdAtMs;
|
|
860
|
-
userMessageId = first.message.inboundMessageId;
|
|
861
|
-
turnId = buildDeterministicTurnId(userMessageId);
|
|
862
|
-
inputMessageIds = resolved.batch.map((entry) => entry.message.inboundMessageId);
|
|
863
|
-
authorIdentityId = sharedAuthorIdentityId(messages);
|
|
864
|
-
turnInputFacts = first;
|
|
865
|
-
} else turnId = resolved.turnId;
|
|
866
|
-
const persisted = await getPersistedThreadState(context.conversationId);
|
|
867
|
-
const conversation = coerceThreadConversationState(persisted);
|
|
868
|
-
await hydrateConversationMessages({
|
|
869
|
-
conversation,
|
|
870
|
-
conversationId: context.conversationId
|
|
871
|
-
});
|
|
872
|
-
const savedTurn = isResume ? await getTurnRecord(context.conversationId, turnId) : void 0;
|
|
873
|
-
let savedMessageIsEvent = false;
|
|
874
|
-
if (isResume) {
|
|
875
|
-
const userMessage = getTurnUserMessage(conversation, turnId);
|
|
876
|
-
if (!userMessage) throw new Error(`Unable to locate the persisted user message for Turn "${turnId}"`);
|
|
877
|
-
savedMessageIsEvent = isEventConversationMessage(userMessage);
|
|
878
|
-
fromParent = isParentMessageAuthor(userMessage.author);
|
|
879
|
-
fromChildAgent = isChildAgentEvent(userMessage.meta);
|
|
880
|
-
turnInputFacts = turnInputFactsFromConversationMessage(userMessage, {
|
|
881
|
-
conversationId: context.conversationId,
|
|
882
|
-
location: storedConversation?.location,
|
|
883
|
-
savedActor: savedTurn?.actor,
|
|
884
|
-
savedSource: savedTurn?.source,
|
|
885
|
-
visibility: storedConversation?.visibility
|
|
886
|
-
});
|
|
887
|
-
const turnInputs = savedTurnInputMessages(conversation, userMessage, await lifecycle.loadInputMessageIds(context.conversationId, turnId));
|
|
888
|
-
userMessageId = userMessage.id;
|
|
889
|
-
inputs = savedMessageIsEvent || fromParent ? [{
|
|
890
|
-
kind: "runtime",
|
|
891
|
-
text: userMessage.text,
|
|
892
|
-
...userMessage.meta?.requestText ? { requestText: userMessage.meta.requestText } : void 0
|
|
893
|
-
}] : await webTurnInputs(turnInputs.map((message) => ({
|
|
894
|
-
reviewItemChange: message.meta?.reviewItemChanges?.[0],
|
|
895
|
-
text: message.text
|
|
896
|
-
})));
|
|
897
|
-
attachments = turnInputs.flatMap((message) => message.meta?.attachments ?? []);
|
|
898
|
-
startedAtMs = userMessage.createdAtMs;
|
|
899
|
-
inputMessageIds = turnInputs.map((message) => message.id);
|
|
900
|
-
}
|
|
901
|
-
if (!turnInputFacts) throw new Error(`Resumed Turn is missing an Actor for Conversation ${context.conversationId}`);
|
|
902
|
-
const { actor, author } = turnInputFacts;
|
|
903
|
-
const instructionInputs = instructionForInputs(inputs);
|
|
904
|
-
const { text } = instructionInputs;
|
|
905
|
-
const instructionActor = instructionActorFor(actor);
|
|
906
|
-
let credentialSubject;
|
|
907
|
-
if (actor.platform === "system") credentialSubject = resolved.kind === "mailbox" ? timerWatchCredentialSubject(context.conversationId, resolved.batch.map((entry) => entry.message)) ?? await verifiedTimerWatchSubject(context.conversationId, sharedDelegatedSubject(resolved.batch), fromParent) : await verifiedTimerWatchSubject(context.conversationId, savedTurn?.credentialSubject, fromParent);
|
|
908
|
-
const source = sourceFromTurnInput({
|
|
909
|
-
conversationId: context.conversationId,
|
|
910
|
-
source: turnInputFacts.source,
|
|
911
|
-
visibility
|
|
912
|
-
});
|
|
913
|
-
const conversationLocation = storedConversation?.location;
|
|
914
|
-
const isEventTurn = source.kind === "event" || savedMessageIsEvent;
|
|
915
|
-
const postsToProvider = Boolean(conversationLocation) && isEventTurn;
|
|
916
|
-
const behavior = turnBehavior({
|
|
917
|
-
kind,
|
|
918
|
-
hasParent: !isTopLevel({ parentConversationId: storedConversation?.parentConversationId }),
|
|
919
|
-
personInput: isPersonInput(source.kind)
|
|
920
|
-
});
|
|
921
|
-
const webActor = actor.platform === "web" ? actor : void 0;
|
|
922
|
-
const signInActor = behavior.waitsForSignIn ? webActor : void 0;
|
|
923
|
-
const disabledFeatures = signInActor ? [] : ["interactive-auth"];
|
|
924
|
-
const deliverToProvider = postsToProvider && (behavior.delivery === "location" || !behavior.gated && storedConversation !== void 0 && isTopLevel(storedConversation));
|
|
925
|
-
const surface = postsToProvider ? "slack" : "api";
|
|
926
|
-
const inputTelemetry = resolved.kind === "mailbox" ? turnInputTelemetry(resolved.batch.map((entry) => entry.message)) : void 0;
|
|
927
|
-
const turnTrace = inputTelemetry ?? (savedTurn?.traceContext ? { traceContexts: [savedTurn.traceContext] } : void 0);
|
|
928
|
-
return await withTurnSpan({
|
|
929
|
-
conversationId: context.conversationId,
|
|
930
|
-
platform: actor.platform,
|
|
931
|
-
...webActor ? {
|
|
932
|
-
userId: webActor.userId,
|
|
933
|
-
...webActor.userName ? { userName: webActor.userName } : void 0
|
|
934
|
-
} : void 0
|
|
935
|
-
}, turnTrace, async (setTurnSpanAttributes) => {
|
|
936
|
-
if (inputTelemetry) setTurnSpanAttributes(getTurnInputSpanAttributes(inputTelemetry, Date.now()));
|
|
937
|
-
let acknowledged = isResume || context.attempt.messages.length === 0;
|
|
938
|
-
const acknowledge = async () => {
|
|
939
|
-
if (acknowledged) return;
|
|
940
|
-
try {
|
|
941
|
-
await context.attempt.ack();
|
|
942
|
-
} catch {
|
|
943
|
-
throw new TurnInputCommitLostError(`Conversation work lease lost before mailbox Message acknowledgement for ${context.conversationId}`);
|
|
944
|
-
}
|
|
945
|
-
acknowledged = true;
|
|
946
|
-
};
|
|
947
|
-
let sandboxRef = getPersistedSandboxState(persisted);
|
|
948
|
-
const initialSandboxRef = sandboxRef;
|
|
949
|
-
const stopSignal = context.stopSignal?.();
|
|
950
|
-
const completeCancelledTurn = async () => {
|
|
951
|
-
try {
|
|
952
|
-
await completeCancelledConversationTurn({
|
|
953
|
-
acknowledge,
|
|
954
|
-
conversation,
|
|
955
|
-
conversationId: context.conversationId,
|
|
956
|
-
sandboxRef,
|
|
957
|
-
turnId,
|
|
958
|
-
userMessageId
|
|
959
|
-
});
|
|
960
|
-
} catch (error) {
|
|
961
|
-
if (hasLostTurnInputCommit(error)) return { status: "lost_lease" };
|
|
962
|
-
throw error;
|
|
963
|
-
}
|
|
964
|
-
await indexEndedTurnEvents({
|
|
965
|
-
conversationId: context.conversationId,
|
|
966
|
-
turnId
|
|
967
|
-
});
|
|
968
|
-
return { status: "completed" };
|
|
969
|
-
};
|
|
970
|
-
if (isResume) {
|
|
971
|
-
if (stopSignal?.aborted) return await completeCancelledTurn();
|
|
972
|
-
} else {
|
|
973
|
-
for (const message of webInputMessages) upsertConversationMessage(conversation, message);
|
|
974
|
-
if (webInputMessages.length === 0) {
|
|
975
|
-
const requestText = turnRequestText({ instruction: instructionInputs });
|
|
976
|
-
upsertConversationMessage(conversation, {
|
|
977
|
-
id: userMessageId,
|
|
978
|
-
role: "user",
|
|
979
|
-
text: normalizeConversationText(text),
|
|
980
|
-
createdAtMs: startedAtMs,
|
|
981
|
-
author,
|
|
982
|
-
...authorIdentityId ? { authorIdentityId } : void 0,
|
|
983
|
-
meta: {
|
|
984
|
-
...attachments.length ? { attachments } : void 0,
|
|
985
|
-
explicitMention: true,
|
|
986
|
-
replied: false,
|
|
987
|
-
...requestText ? { requestText } : void 0,
|
|
988
|
-
...eventMeta
|
|
989
|
-
}
|
|
990
|
-
});
|
|
991
|
-
}
|
|
992
|
-
await persistConversationMessages({
|
|
993
|
-
conversation,
|
|
994
|
-
conversationId: context.conversationId
|
|
995
|
-
});
|
|
996
|
-
await commitParentMessageFork({
|
|
997
|
-
conversationId: context.conversationId,
|
|
998
|
-
inputs: resolved.batch.map((entry) => entry.message)
|
|
999
|
-
});
|
|
1000
|
-
await lifecycle.start({
|
|
1001
|
-
conversationId: context.conversationId,
|
|
1002
|
-
createdAtMs: Date.now(),
|
|
1003
|
-
inputMessageIds,
|
|
1004
|
-
surface,
|
|
1005
|
-
threadContextThroughSeq: latestConversationMessageSeq(conversation),
|
|
1006
|
-
turnId
|
|
1007
|
-
});
|
|
1008
|
-
if (stopSignal?.aborted) return await completeCancelledTurn();
|
|
1009
|
-
startActiveTurn({
|
|
1010
|
-
conversation,
|
|
1011
|
-
nextTurnId: turnId
|
|
1012
|
-
});
|
|
1013
|
-
}
|
|
1014
|
-
let currentRunId;
|
|
1015
|
-
let assistantMessageDelivered = false;
|
|
1016
|
-
let failureCode = "persistence_failed";
|
|
1017
|
-
let modelFailureEventId;
|
|
1018
|
-
let modelFailureCaptureAttempted = false;
|
|
1019
|
-
let completedSuccessfully = false;
|
|
1020
|
-
const deliverAssistantMessage = async (value, options) => {
|
|
1021
|
-
const agentMessage = typeof value === "string" ? void 0 : value;
|
|
1022
|
-
const replyText = typeof value === "string" ? value : getAssistantReplyText(value);
|
|
1023
|
-
if (!replyText?.trim()) return;
|
|
1024
|
-
failureCode = "delivery_failed";
|
|
1025
|
-
const cards = await loadPendingMessageCards(context.conversationId);
|
|
1026
|
-
let deliveryResult;
|
|
1027
|
-
if ((options?.reply ? postsToProvider : deliverToProvider) && !await isConversationDeliveryPaused(context.conversationId)) {
|
|
1028
|
-
if (!conversationLocation || !deliverMessage) throw new Error(`Conversation ${context.conversationId} cannot deliver to its Location`);
|
|
1029
|
-
deliveryResult = await deliverMessage({
|
|
1030
|
-
cards,
|
|
1031
|
-
conversationId: context.conversationId,
|
|
1032
|
-
location: conversationLocation,
|
|
1033
|
-
text: replyText
|
|
1034
|
-
});
|
|
1035
|
-
}
|
|
1036
|
-
await commitAssistantMessage({
|
|
1037
|
-
cards,
|
|
1038
|
-
...agentMessage ? { agentMessage } : void 0,
|
|
1039
|
-
conversation,
|
|
1040
|
-
conversationId: context.conversationId,
|
|
1041
|
-
...deliveryResult ? { deliveryResult } : void 0,
|
|
1042
|
-
sessionId: turnId,
|
|
1043
|
-
...deliveryResult ? { source: "slack" } : source.kind === "web" ? { source: "web" } : void 0,
|
|
1044
|
-
text: replyText,
|
|
1045
|
-
userMessageId
|
|
1046
|
-
});
|
|
1047
|
-
assistantMessageDelivered = true;
|
|
1048
|
-
failureCode = "agent_run_failed";
|
|
1049
|
-
};
|
|
1050
|
-
try {
|
|
1051
|
-
if (stopSignal?.aborted) return await completeCancelledTurn();
|
|
1052
|
-
if (!isResume && !await supersedeOpenMailboxTurns({
|
|
1053
|
-
conversation,
|
|
1054
|
-
conversationId: context.conversationId,
|
|
1055
|
-
isStopped: () => Boolean(stopSignal?.aborted),
|
|
1056
|
-
keepTurnId: turnId
|
|
1057
|
-
})) return await completeCancelledTurn();
|
|
1058
|
-
await persistThreadStateById(context.conversationId, { conversation });
|
|
1059
|
-
if (stopSignal?.aborted) return await completeCancelledTurn();
|
|
1060
|
-
const childTurn = await childAgentTurnOptions({
|
|
1061
|
-
actor,
|
|
1062
|
-
conversationId: context.conversationId,
|
|
1063
|
-
fromChildAgent,
|
|
1064
|
-
fromParent
|
|
1065
|
-
});
|
|
1066
|
-
const history = await loadConversationProjection({ conversationId: context.conversationId });
|
|
1067
|
-
failureCode = "agent_run_failed";
|
|
1068
|
-
currentRunId = `conversation-run:${stableHex(turnId, String(startedAtMs))}`;
|
|
1069
|
-
setTags({ runId: currentRunId });
|
|
1070
|
-
const outcome = await executeTurn(agentRunner, {
|
|
1071
|
-
conversationId: context.conversationId,
|
|
1072
|
-
...storedConversation?.parentConversationId ? { parentConversationId: storedConversation.parentConversationId } : void 0,
|
|
1073
|
-
turnId,
|
|
1074
|
-
runId: currentRunId,
|
|
1075
|
-
instruction: {
|
|
1076
|
-
...await withHeldInput({
|
|
1077
|
-
conversation,
|
|
1078
|
-
conversationId: context.conversationId,
|
|
1079
|
-
turnId
|
|
1080
|
-
}, instructionInputs),
|
|
1081
|
-
...instructionActor ? { actor: instructionActor } : void 0,
|
|
1082
|
-
...childTurn.instruction,
|
|
1083
|
-
storedAttachments: attachments,
|
|
1084
|
-
context: conversationLocation?.provider === "slack" ? await buildTurnThreadContext({
|
|
1085
|
-
conversation,
|
|
1086
|
-
conversationId: context.conversationId,
|
|
1087
|
-
excludeMessageIds: inputMessageIds,
|
|
1088
|
-
hasHistory: history.messages.length > 0,
|
|
1089
|
-
turnId
|
|
1090
|
-
}) : void 0
|
|
1091
|
-
},
|
|
1092
|
-
history,
|
|
1093
|
-
...childTurn.run,
|
|
1094
|
-
actor,
|
|
1095
|
-
credentialContext: credentialContextForActor(actor, credentialSubject),
|
|
1096
|
-
destination,
|
|
1097
|
-
source,
|
|
1098
|
-
...conversationLocation ? { location: conversationLocation } : void 0,
|
|
1099
|
-
surface,
|
|
1100
|
-
deadlineAtMs: getTurnRequestDeadline()?.deadlineAtMs,
|
|
1101
|
-
...stopSignal ? { signal: stopSignal } : void 0,
|
|
1102
|
-
...signInActor ? { authorization: createWebAuthorization({
|
|
1103
|
-
actorId: signInActor.userId,
|
|
1104
|
-
conversationId: context.conversationId
|
|
1105
|
-
}) } : void 0,
|
|
1106
|
-
...disabledFeatures.length > 0 ? { disabledFeatures } : void 0,
|
|
1107
|
-
state: {
|
|
1108
|
-
pendingAuth: conversation.processing.pendingAuth,
|
|
1109
|
-
sandboxRef
|
|
1110
|
-
},
|
|
1111
|
-
delivery: deliverAssistantMessage,
|
|
1112
|
-
durability: {
|
|
1113
|
-
...webActor ? { drainSteeringMessages: createWebSteeringDrain({
|
|
1114
|
-
actor: webActor,
|
|
1115
|
-
author,
|
|
1116
|
-
context,
|
|
1117
|
-
conversation,
|
|
1118
|
-
turnId
|
|
1119
|
-
}) } : void 0,
|
|
1120
|
-
onInputCommitted: acknowledge,
|
|
1121
|
-
shouldYield: context.shouldYield,
|
|
1122
|
-
checkIn: context.checkIn,
|
|
1123
|
-
checkStop: context.checkStop,
|
|
1124
|
-
onSandboxRefChanged: async (nextSandboxRef) => {
|
|
1125
|
-
sandboxRef = nextSandboxRef;
|
|
1126
|
-
await persistThreadStateById(context.conversationId, {
|
|
1127
|
-
conversation,
|
|
1128
|
-
sandboxRef
|
|
1129
|
-
});
|
|
1130
|
-
},
|
|
1131
|
-
recordPendingAuth: async (pendingAuth) => {
|
|
1132
|
-
conversation.processing.pendingAuth = pendingAuth;
|
|
1133
|
-
await persistThreadStateById(context.conversationId, {
|
|
1134
|
-
conversation,
|
|
1135
|
-
sandboxRef
|
|
1136
|
-
});
|
|
1137
|
-
}
|
|
1138
|
-
}
|
|
1139
|
-
}, async (result) => {
|
|
1140
|
-
if (stopSignal?.aborted) throw stopSignal.reason ?? new DOMException("Turn cancelled", "AbortError");
|
|
1141
|
-
modelFailureCaptureAttempted = result.diagnostics.outcome !== "success";
|
|
1142
|
-
const finalized = finalizeFailedTurnReplyWithEvent({ reply: result });
|
|
1143
|
-
const modelFailureReason = finalized.failureReason;
|
|
1144
|
-
const reply = finalized.reply;
|
|
1145
|
-
modelFailureEventId = finalized.eventId;
|
|
1146
|
-
if (reply.diagnostics.outcome !== "success") await deliverAssistantMessage(reply.text);
|
|
1147
|
-
else if (reply.reply) await deliverAssistantMessage(reply.reply.text, { reply: true });
|
|
1148
|
-
else if (reply.blocked && behavior.tools.reportBlocked === "automation") await blockRunAutomation(context.conversationId, reply.blocked);
|
|
1149
|
-
const completedState = buildDeliveredTurnStatePatch({
|
|
1150
|
-
conversation,
|
|
1151
|
-
reply,
|
|
1152
|
-
sessionId: turnId,
|
|
1153
|
-
userMessageId
|
|
1154
|
-
});
|
|
1155
|
-
await persistThreadStateById(context.conversationId, {
|
|
1156
|
-
conversation: completedState.conversation,
|
|
1157
|
-
sandboxRef: reply.sandboxRef ?? sandboxRef
|
|
1158
|
-
});
|
|
1159
|
-
if (reply.piMessages?.length) {
|
|
1160
|
-
const latest = await getTurnRecord(context.conversationId, turnId);
|
|
1161
|
-
await saveTurnCheckpoint({
|
|
1162
|
-
mode: "completed",
|
|
1163
|
-
conversationId: context.conversationId,
|
|
1164
|
-
turnId,
|
|
1165
|
-
sliceId: latest?.sliceId ?? 1,
|
|
1166
|
-
messages: reply.piMessages,
|
|
1167
|
-
durationMs: reply.diagnostics.durationMs,
|
|
1168
|
-
usage: reply.diagnostics.usage,
|
|
1169
|
-
destination,
|
|
1170
|
-
source,
|
|
1171
|
-
actor,
|
|
1172
|
-
surface
|
|
1173
|
-
});
|
|
1174
|
-
}
|
|
1175
|
-
if (fromParent) await resetAutomatedTurnLimit({ conversationId: context.conversationId });
|
|
1176
|
-
else {
|
|
1177
|
-
const automatedTurnLimit = await recordFinishedTurnForAutomatedLimit({
|
|
1178
|
-
conversationId: context.conversationId,
|
|
1179
|
-
maxTurns: botConfig.maxConsecutiveAutomatedTurns,
|
|
1180
|
-
source
|
|
1181
|
-
});
|
|
1182
|
-
await stopAtAutomatedTurnLimit({
|
|
1183
|
-
conversationId: context.conversationId,
|
|
1184
|
-
maxTurns: botConfig.maxConsecutiveAutomatedTurns,
|
|
1185
|
-
source,
|
|
1186
|
-
update: automatedTurnLimit
|
|
1187
|
-
});
|
|
1188
|
-
}
|
|
1189
|
-
completedSuccessfully = reply.diagnostics.outcome === "success";
|
|
1190
|
-
const delivered = assistantMessageDelivered ? "success" : "no_reply";
|
|
1191
|
-
const answer = turnAnswerText(reply);
|
|
1192
|
-
return completedSuccessfully ? {
|
|
1193
|
-
...answer ? { answer } : void 0,
|
|
1194
|
-
outcome: reply.blocked ? "blocked" : delivered
|
|
1195
|
-
} : {
|
|
1196
|
-
...modelFailureEventId ? { eventId: modelFailureEventId } : void 0,
|
|
1197
|
-
failureCode: "model_execution_failed",
|
|
1198
|
-
...modelFailureReason ? { failureReason: modelFailureReason } : void 0,
|
|
1199
|
-
failureText: reply.diagnostics.errorMessage ?? reply.text,
|
|
1200
|
-
outcome: "failed"
|
|
1201
|
-
};
|
|
1202
|
-
}, lifecycle);
|
|
1203
|
-
if (outcome.status !== "completed" && stopSignal?.aborted) return await completeCancelledTurn();
|
|
1204
|
-
if (outcome.status === "suspended") return { status: "yielded" };
|
|
1205
|
-
if (outcome.status === "awaiting_auth") {
|
|
1206
|
-
completeAuthPauseTurn({
|
|
1207
|
-
conversation,
|
|
1208
|
-
sessionId: turnId
|
|
1209
|
-
});
|
|
1210
|
-
await persistThreadStateById(context.conversationId, {
|
|
1211
|
-
conversation,
|
|
1212
|
-
sandboxRef
|
|
1213
|
-
});
|
|
1214
|
-
await acknowledge();
|
|
1215
|
-
return { status: "paused" };
|
|
1216
|
-
}
|
|
1217
|
-
await runTurnEndTasks({
|
|
1218
|
-
behavior,
|
|
1219
|
-
completed: completedSuccessfully,
|
|
1220
|
-
conversationId: context.conversationId,
|
|
1221
|
-
turnId
|
|
1222
|
-
});
|
|
1223
|
-
await acknowledge();
|
|
1224
|
-
return { status: "completed" };
|
|
1225
|
-
} catch (error) {
|
|
1226
|
-
const failure = error instanceof AgentRunError ? error.cause : error;
|
|
1227
|
-
if (hasLostTurnInputCommit(failure)) return { status: "lost_lease" };
|
|
1228
|
-
if (stopSignal?.aborted) return await completeCancelledTurn();
|
|
1229
|
-
if (!context.attempt.isFinalAttempt) throw failure;
|
|
1230
|
-
await failConversationTurn({
|
|
1231
|
-
conversation,
|
|
1232
|
-
conversationId: context.conversationId,
|
|
1233
|
-
failure,
|
|
1234
|
-
failureCode,
|
|
1235
|
-
lifecycle,
|
|
1236
|
-
modelFailureCaptureAttempted,
|
|
1237
|
-
modelFailureEventId,
|
|
1238
|
-
reportAs: parentResultActor(actor, source.kind),
|
|
1239
|
-
runId: currentRunId,
|
|
1240
|
-
sandboxRef: initialSandboxRef,
|
|
1241
|
-
turnId,
|
|
1242
|
-
userMessageId
|
|
1243
|
-
});
|
|
1244
|
-
await acknowledge();
|
|
1245
|
-
return { status: "completed" };
|
|
1246
|
-
}
|
|
1247
|
-
});
|
|
1248
|
-
};
|
|
1249
|
-
}
|
|
1250
|
-
export { buildTurnThreadContext as a, AgentRunError as c, turnInputTelemetry as d, withTurnSpan as f, buildConversationContext as i, executeTurn as l, createConversationTurnWorker as n, stopAtAutomatedTurnLimit as o, supersedeTurnForInput as r, recordFinishedTurnForAutomatedLimit as s, conversation_turn_exports as t, getTurnInputSpanAttributes as u };
|