@sentry/junior 0.284.0 → 0.286.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/{adapter-CW5UW7vL.js → adapter-JQZaJ-B_.js} +37 -3
- package/dist/{admin-DUWN8zZX.js → admin-Dm2bimJ-.js} +1 -1
- package/dist/{agent-runner-Cqr21pOU.js → agent-runner-DGCwOEyL.js} +2180 -2735
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +8 -7
- package/dist/api.d.ts +1 -1
- package/dist/api.js +166 -90
- package/dist/{app-CvGalMxi.d.ts → app-BKq0JzWx.d.ts} +2 -3
- package/dist/app.d.ts +1 -1
- package/dist/app.js +225 -188
- package/dist/{assistant-reply-CFE-OZMS.js → assistant-reply-CAPafcUY.js} +1 -1
- package/dist/{automation-Zvx_I9Z5.js → automation-B-jJN_gM.js} +1 -1
- package/dist/{background-compaction-queue-CHFzrQbS.js → background-compaction-queue-Btu2oab_.js} +137 -3
- package/dist/{briefs-Cx7mkfSk.js → briefs-UMeYehUe.js} +5 -5
- package/dist/{catalog-runtime-dKOVbR7l.js → catalog-runtime-Bym8GVdh.js} +1 -1
- package/dist/cli/chat.js +19 -16
- package/dist/cli/check.js +3 -3
- package/dist/cli/init.js +3 -0
- package/dist/cli/main.js +3 -3
- package/dist/cli/plugins.js +4 -4
- package/dist/cli/snapshot-create.js +5 -6
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +12 -17
- package/dist/{client-CMyH5rDz.js → client-B0aAs7wC.js} +2 -2
- package/dist/{config-Dt3CpG17.js → config-B9f9Lqo5.js} +1 -1
- package/dist/{connections-CCHPybZP.js → connections-CQ7p0aNJ.js} +16 -50
- package/dist/{conversation-DdT7SNar.js → conversation-BusI2uzj.js} +68 -7
- package/dist/{conversation-pending-messages-Dct5pheX.js → conversation-pending-messages-DwehU0Fd.js} +1 -1
- package/dist/{conversation-privacy-BpHHhEVp.js → conversation-privacy-Cd_nZZBM.js} +1 -1
- package/dist/{credential-sync-BBPw8dam.js → credential-sync-DmiJi_At.js} +13 -13
- package/dist/{db-D7CCwAo8.d.ts → db-C5zi4ecs.d.ts} +18 -2
- package/dist/{executor-CyIwHz9r.js → executor-Dipi2Ixl.js} +19 -17
- package/dist/instrumentation.js +2 -2
- package/dist/{logging-Qo-7xGp1.js → logging-CMFhLLj4.js} +1 -1
- package/dist/{media-Bu9C6lz0.js → media-B-BpXo41.js} +14 -2
- package/dist/{message-DFbtOWqv.js → message-D1xLljUF.js} +13 -23
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +2 -3
- package/dist/{oauth-callback-server-BB1gixWo.js → oauth-callback-server-DCAFIUQr.js} +2 -2
- package/dist/{projection-0UcUeuzn.js → projection-CoeMNxJ4.js} +545 -262
- package/dist/{prompt-CCtaGgbI.js → prompt-C9OQEfan.js} +8 -6
- package/dist/{registry-DOnPkI8g.js → registry-u-sFYtx_.js} +1 -1
- package/dist/{reporting-window-B-QP9zX1.js → reporting-window-B4TwyuJo.js} +14 -14
- package/dist/{resolve-Di3omymY.js → resolve-DYqgL3Eo.js} +3 -3
- package/dist/result-CescSwAw.js +299 -0
- package/dist/result-event-type-DD6BAgT7.js +11 -0
- package/dist/{runner-CnX_dTKw.js → runner-Cr67a8TB.js} +16 -12
- package/dist/{sandbox-egress-signals-CtxLJmmg.js → sandbox-egress-signals-DLOazy5W.js} +1 -1
- package/dist/{schema-Bn3miEd_.js → schema-BUSi3sgv.js} +63 -5
- package/dist/{schema-B017enNE.d.ts → schema-Ih60j59-.d.ts} +194 -220
- package/dist/{service-account-KhZIqXRi.js → service-account-CGEqz9wG.js} +3 -3
- package/dist/{service-account-ewDAx4Mx.js → service-account-CsKxktLk.js} +3 -3
- package/dist/session-stop-CGz5DByb.js +2926 -0
- package/dist/{skills-CKyotM4g.js → skills-COCqf61f.js} +2 -2
- package/dist/{spawn-D5D2MQdz.js → spawn-C8F_iXWO.js} +13 -2
- package/dist/{stop-BSKRTaRS.js → stop-GyFZkHuQ.js} +7730 -7818
- package/dist/{store-ymkEUWe4.js → store-D0-8plWp.js} +30 -5
- package/dist/{turn-session-routing-D_GXfcAG.js → task-runner-xPuQmEot.js} +1440 -994
- package/dist/{store-G3S0kWSD.js → turn-failure-response-BOviBdT-.js} +404 -311
- package/dist/{validation-DJG_wrg2.js → validation-DZDKorGz.js} +1 -1
- package/dist/{version-i1An1eTS.js → version-BTIz7fGi.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-BlpnzZZa.js → viewer-CH-ASQzh.js} +208 -68
- package/dist/{work-BgCW3FDC.js → work-C75_IM5e.js} +311 -100
- package/dist/{worker-BJz1mwYt.js → worker-Dl47I729.js} +6 -6
- package/migrations/0083_conversation_kind.sql +11 -0
- package/migrations/0084_read_position_backfill.sql +25 -0
- package/migrations/0085_child_archived_at.sql +1 -0
- package/migrations/0086_shared_archive.sql +31 -0
- package/migrations/0087_child_location.sql +64 -0
- package/migrations/meta/0083_snapshot.json +4388 -0
- package/migrations/meta/0084_snapshot.json +4388 -0
- package/migrations/meta/0085_snapshot.json +4394 -0
- package/migrations/meta/0086_snapshot.json +4366 -0
- package/migrations/meta/0087_snapshot.json +4366 -0
- package/migrations/meta/_journal.json +35 -0
- package/package.json +5 -4
- package/dist/result-NvndYzCb.js +0 -483
- package/dist/session-stop-D_1SysjC.js +0 -1438
- package/dist/task-queue-BcOHzXxe.js +0 -139
- package/dist/task-runner-B65cDumh.js +0 -290
- package/dist/thread-state-D6rNGQu9.js +0 -173
- package/dist/turn-failure-response-BlO4nuDJ.js +0 -224
- package/dist/turn-lifecycle-BQ8ETk63.js +0 -58
|
@@ -1,11 +1,17 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { g as
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
1
|
+
import { D as buildConversationContext, Eo as listConversationAnnotations, M as markConversationMessage, Sn as buildDeterministicTurnId, q as clearPendingAuth, v as hydrateConversationMessages } from "./projection-CoeMNxJ4.js";
|
|
2
|
+
import { b as getProviderErrorUserMessage, g as ProviderError, v as findProviderError, y as getProviderErrorAttributes } from "./client-B0aAs7wC.js";
|
|
3
|
+
import { g as TURN_REASONING_LEVELS } from "./config-B9f9Lqo5.js";
|
|
4
|
+
import { W as isRecord, b as setSpanAttributes, t as buildTurnFailureResponse } from "./logging-CMFhLLj4.js";
|
|
5
|
+
import { h as parseSlackMessageTs } from "./actor-6jsm_v96.js";
|
|
6
|
+
import { C as getSqlExecutor, S as getDb, y as getConversationEventStore } from "./viewer-CH-ASQzh.js";
|
|
7
|
+
import { g as juniorAgentInvocations } from "./executor-Dipi2Ixl.js";
|
|
8
|
+
import { p as credentialContextSchema } from "./registry-u-sFYtx_.js";
|
|
9
|
+
import { F as removedCardSchema, I as resolveMessageCards, P as readMessageCardRefs } from "./conversation-BusI2uzj.js";
|
|
10
|
+
import { S as AGENT_INVOCATION_PARENT_MAILBOX_STATUSES, x as AGENT_INVOCATION_MAILBOX_STATUSES } from "./reporting-window-B4TwyuJo.js";
|
|
11
|
+
import { _t as getPersistedThreadState, bt as coerceThreadConversationState, yt as persistThreadStateById } from "./task-runner-xPuQmEot.js";
|
|
6
12
|
import { createHash } from "node:crypto";
|
|
7
13
|
import * as z from "zod";
|
|
8
|
-
import { and, asc,
|
|
14
|
+
import { and, asc, desc, eq, inArray, or, sql } from "drizzle-orm";
|
|
9
15
|
import { actorSchema, destinationSchema, sourceSchema } from "@sentry/junior-plugin-api";
|
|
10
16
|
// src/chat/runtime/turn.ts
|
|
11
17
|
/** Classified Slack turn failure carrying the owning Sentry capture outward. */
|
|
@@ -98,6 +104,71 @@ function markTurnFailed(args) {
|
|
|
98
104
|
skippedReason: "reply failed"
|
|
99
105
|
});
|
|
100
106
|
}
|
|
107
|
+
// src/chat/agent-invocations/ids.ts
|
|
108
|
+
const CREATE_LOCK_PREFIX = "junior:agent_invocation:create";
|
|
109
|
+
/**
|
|
110
|
+
* Return the SQL lock that one parent Conversation takes to start, message,
|
|
111
|
+
* or stop its child agents.
|
|
112
|
+
*/
|
|
113
|
+
function getChildAgentLockName(parentConversationId) {
|
|
114
|
+
return `${CREATE_LOCK_PREFIX}:${parentConversationId}`;
|
|
115
|
+
}
|
|
116
|
+
function stableId(prefix, ...parts) {
|
|
117
|
+
return `${prefix}:${createHash("sha256").update(parts.join("\0")).digest("hex").slice(0, 32)}`;
|
|
118
|
+
}
|
|
119
|
+
/** Return the stable identity for one retry-safe delegated task. */
|
|
120
|
+
function getAgentInvocationId(parentConversationId, idempotencyKey) {
|
|
121
|
+
return stableId("agent-invocation", parentConversationId, idempotencyKey);
|
|
122
|
+
}
|
|
123
|
+
/** Return the stable child identity for one invocation without a named binding. */
|
|
124
|
+
function getUnnamedAgentConversationId(invocationId) {
|
|
125
|
+
return stableId("agent", invocationId);
|
|
126
|
+
}
|
|
127
|
+
/** Return the stable child identity for one named binding. */
|
|
128
|
+
function getNamedAgentConversationId(parentConversationId, name) {
|
|
129
|
+
return stableId("agent", parentConversationId, name);
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Return the stable identity of the agent invocation that gives one child
|
|
133
|
+
* agent result to the child Conversation that started that child agent.
|
|
134
|
+
*/
|
|
135
|
+
function getAgentInvocationIdForResult(resultInvocationId) {
|
|
136
|
+
return stableId("agent-invocation", "result", resultInvocationId);
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Return the stable identity of the agent invocation that gives one message
|
|
140
|
+
* from a child agent to the child Conversation that started that child agent.
|
|
141
|
+
*/
|
|
142
|
+
function getAgentInvocationIdForMessage(messageId) {
|
|
143
|
+
return stableId("agent-invocation", "message", messageId);
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Return the stable identity of the agent invocation that gives one batch of
|
|
147
|
+
* watch events to a child Conversation. The first message of the batch names
|
|
148
|
+
* it.
|
|
149
|
+
*/
|
|
150
|
+
function getAgentInvocationIdForEvents(messageId) {
|
|
151
|
+
return stableId("agent-invocation", "events", messageId);
|
|
152
|
+
}
|
|
153
|
+
/** Return the stable turn identity advanced by one agent invocation. */
|
|
154
|
+
function getAgentInvocationTurnId(invocationId) {
|
|
155
|
+
return `agent-invocation:${invocationId}`;
|
|
156
|
+
}
|
|
157
|
+
/** Return the stable mailbox identity for one agent invocation. */
|
|
158
|
+
function getAgentInvocationMessageId(invocationId) {
|
|
159
|
+
return `agent-invocation:${invocationId}:input`;
|
|
160
|
+
}
|
|
161
|
+
const RESULT_MESSAGE_PREFIX = "agent-invocation:";
|
|
162
|
+
const RESULT_MESSAGE_SUFFIX = ":result";
|
|
163
|
+
/** Return the stable parent mailbox identity for one terminal result. */
|
|
164
|
+
function getAgentInvocationResultMessageId(invocationId) {
|
|
165
|
+
return `${RESULT_MESSAGE_PREFIX}${invocationId}${RESULT_MESSAGE_SUFFIX}`;
|
|
166
|
+
}
|
|
167
|
+
/** Read the invocation identity from one parent result mailbox identity. */
|
|
168
|
+
function parseAgentInvocationResultMessageId(messageId) {
|
|
169
|
+
if (!messageId.startsWith(RESULT_MESSAGE_PREFIX) || !messageId.endsWith(RESULT_MESSAGE_SUFFIX)) return;
|
|
170
|
+
return messageId.slice(17, -7) || void 0;
|
|
171
|
+
}
|
|
101
172
|
// src/chat/agent-invocations/agent-types.ts
|
|
102
173
|
/**
|
|
103
174
|
* Child agent types. A type is plain data: when to pick it, whether the child
|
|
@@ -225,76 +296,7 @@ const CHILD_AGENT_RESULTS = [
|
|
|
225
296
|
"blocked",
|
|
226
297
|
"failed"
|
|
227
298
|
];
|
|
228
|
-
// src/chat/agent-invocations/bindings.ts
|
|
229
|
-
function bindingFromRow(row) {
|
|
230
|
-
return agentBindingSchema.parse({
|
|
231
|
-
childConversationId: row.childConversationId,
|
|
232
|
-
name: row.name,
|
|
233
|
-
parentConversationId: row.parentConversationId
|
|
234
|
-
});
|
|
235
|
-
}
|
|
236
|
-
/** Read one named child binding in its parent-agent scope. */
|
|
237
|
-
async function getAgentBinding(args) {
|
|
238
|
-
const rows = await getSqlExecutor().db().select().from(juniorAgentBindings).where(and(eq(juniorAgentBindings.parentConversationId, args.parentConversationId), eq(juniorAgentBindings.name, args.name)));
|
|
239
|
-
return rows[0] ? bindingFromRow(rows[0]) : void 0;
|
|
240
|
-
}
|
|
241
|
-
/** Find a direct child agent of one parent by name or child Conversation id. */
|
|
242
|
-
async function findChildAgentConversationId(args) {
|
|
243
|
-
const binding = await getAgentBinding({
|
|
244
|
-
name: args.target,
|
|
245
|
-
parentConversationId: args.parentConversationId
|
|
246
|
-
});
|
|
247
|
-
if (binding) return binding.childConversationId;
|
|
248
|
-
return (await getSqlExecutor().db().select({ childConversationId: juniorAgentInvocations.childConversationId }).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, args.parentConversationId), eq(juniorAgentInvocations.childConversationId, args.target))).limit(1))[0]?.childConversationId;
|
|
249
|
-
}
|
|
250
|
-
// src/chat/agent-invocations/errors.ts
|
|
251
|
-
/** A child agent already uses this name in the parent Conversation. */
|
|
252
|
-
var AgentNameInUseError = class extends Error {
|
|
253
|
-
constructor(name) {
|
|
254
|
-
super(`A child agent named "${name}" already exists`);
|
|
255
|
-
this.name = "AgentNameInUseError";
|
|
256
|
-
}
|
|
257
|
-
};
|
|
258
|
-
/** Parent already has the maximum number of non-terminal child invocations. */
|
|
259
|
-
var AgentInvocationLimitError = class extends Error {
|
|
260
|
-
constructor(limit) {
|
|
261
|
-
super(`Parent already has ${limit} active child agent invocations (limit ${limit})`);
|
|
262
|
-
this.name = "AgentInvocationLimitError";
|
|
263
|
-
}
|
|
264
|
-
};
|
|
265
|
-
/** A child agent already has the maximum number of open tasks. */
|
|
266
|
-
var AgentMessageQueueFullError = class extends Error {
|
|
267
|
-
constructor(limit) {
|
|
268
|
-
super(`The child agent already has ${limit} open tasks`);
|
|
269
|
-
this.name = "AgentMessageQueueFullError";
|
|
270
|
-
}
|
|
271
|
-
};
|
|
272
|
-
/**
|
|
273
|
-
* A messageAgent target is not the parent, a child, or a top-level agent that
|
|
274
|
-
* the sender can message.
|
|
275
|
-
*/
|
|
276
|
-
var AgentMessageTargetError = class extends Error {
|
|
277
|
-
constructor(message) {
|
|
278
|
-
super(message);
|
|
279
|
-
this.name = "AgentMessageTargetError";
|
|
280
|
-
}
|
|
281
|
-
};
|
|
282
|
-
/** A top-level agent paused automated Turns, so it takes no agent message. */
|
|
283
|
-
var AgentMessagePausedError = class extends Error {
|
|
284
|
-
constructor(conversationId) {
|
|
285
|
-
super(`${conversationId} paused automated work until a person replies there`);
|
|
286
|
-
this.name = "AgentMessagePausedError";
|
|
287
|
-
}
|
|
288
|
-
};
|
|
289
299
|
// src/chat/agent-invocations/store.ts
|
|
290
|
-
const CREATE_LOCK_PREFIX = "junior:agent_invocation:create";
|
|
291
|
-
/**
|
|
292
|
-
* Return the SQL lock that one parent Conversation takes to start, message,
|
|
293
|
-
* or stop its child agents.
|
|
294
|
-
*/
|
|
295
|
-
function getChildAgentLockName(parentConversationId) {
|
|
296
|
-
return `${CREATE_LOCK_PREFIX}:${parentConversationId}`;
|
|
297
|
-
}
|
|
298
300
|
const TERMINAL_AGENT_INVOCATION_STATUSES = [
|
|
299
301
|
"blocked",
|
|
300
302
|
"completed",
|
|
@@ -309,62 +311,6 @@ const NON_TERMINAL_AGENT_INVOCATION_STATUSES = [
|
|
|
309
311
|
"running",
|
|
310
312
|
"paused"
|
|
311
313
|
];
|
|
312
|
-
function stableId(prefix, ...parts) {
|
|
313
|
-
return `${prefix}:${createHash("sha256").update(parts.join("\0")).digest("hex").slice(0, 32)}`;
|
|
314
|
-
}
|
|
315
|
-
/** Return the stable identity for one retry-safe delegated task. */
|
|
316
|
-
function getAgentInvocationId(parentConversationId, idempotencyKey) {
|
|
317
|
-
return stableId("agent-invocation", parentConversationId, idempotencyKey);
|
|
318
|
-
}
|
|
319
|
-
/** Return the stable child identity for one invocation without a named binding. */
|
|
320
|
-
function getUnnamedAgentConversationId(invocationId) {
|
|
321
|
-
return stableId("agent", invocationId);
|
|
322
|
-
}
|
|
323
|
-
/** Return the stable child identity for one named binding. */
|
|
324
|
-
function getNamedAgentConversationId(parentConversationId, name) {
|
|
325
|
-
return stableId("agent", parentConversationId, name);
|
|
326
|
-
}
|
|
327
|
-
/**
|
|
328
|
-
* Return the stable identity of the agent invocation that gives one child
|
|
329
|
-
* agent result to the child Conversation that started that child agent.
|
|
330
|
-
*/
|
|
331
|
-
function getAgentInvocationIdForResult(resultInvocationId) {
|
|
332
|
-
return stableId("agent-invocation", "result", resultInvocationId);
|
|
333
|
-
}
|
|
334
|
-
/**
|
|
335
|
-
* Return the stable identity of the agent invocation that gives one message
|
|
336
|
-
* from a child agent to the child Conversation that started that child agent.
|
|
337
|
-
*/
|
|
338
|
-
function getAgentInvocationIdForMessage(messageId) {
|
|
339
|
-
return stableId("agent-invocation", "message", messageId);
|
|
340
|
-
}
|
|
341
|
-
/**
|
|
342
|
-
* Return the stable identity of the agent invocation that gives one batch of
|
|
343
|
-
* watch events to a child Conversation. The first message of the batch names
|
|
344
|
-
* it.
|
|
345
|
-
*/
|
|
346
|
-
function getAgentInvocationIdForEvents(messageId) {
|
|
347
|
-
return stableId("agent-invocation", "events", messageId);
|
|
348
|
-
}
|
|
349
|
-
/** Return the stable turn identity advanced by one agent invocation. */
|
|
350
|
-
function getAgentInvocationTurnId(invocationId) {
|
|
351
|
-
return `agent-invocation:${invocationId}`;
|
|
352
|
-
}
|
|
353
|
-
/** Return the stable mailbox identity for one agent invocation. */
|
|
354
|
-
function getAgentInvocationMessageId(invocationId) {
|
|
355
|
-
return `agent-invocation:${invocationId}:input`;
|
|
356
|
-
}
|
|
357
|
-
const RESULT_MESSAGE_PREFIX = "agent-invocation:";
|
|
358
|
-
const RESULT_MESSAGE_SUFFIX = ":result";
|
|
359
|
-
/** Return the stable parent mailbox identity for one terminal result. */
|
|
360
|
-
function getAgentInvocationResultMessageId(invocationId) {
|
|
361
|
-
return `${RESULT_MESSAGE_PREFIX}${invocationId}${RESULT_MESSAGE_SUFFIX}`;
|
|
362
|
-
}
|
|
363
|
-
/** Read the invocation identity from one parent result mailbox identity. */
|
|
364
|
-
function parseAgentInvocationResultMessageId(messageId) {
|
|
365
|
-
if (!messageId.startsWith(RESULT_MESSAGE_PREFIX) || !messageId.endsWith(RESULT_MESSAGE_SUFFIX)) return;
|
|
366
|
-
return messageId.slice(17, -7) || void 0;
|
|
367
|
-
}
|
|
368
314
|
/** Parse one agent invocation row. */
|
|
369
315
|
function invocationFromRow(row) {
|
|
370
316
|
return agentInvocationSchema.parse({
|
|
@@ -391,14 +337,6 @@ function invocationFromRow(row) {
|
|
|
391
337
|
updatedAtMs: row.updatedAt.getTime()
|
|
392
338
|
});
|
|
393
339
|
}
|
|
394
|
-
/**
|
|
395
|
-
* Require every durable creation input to match before replaying one key.
|
|
396
|
-
* The title is not compared: a retry can generate a different one, and the
|
|
397
|
-
* stored title wins.
|
|
398
|
-
*/
|
|
399
|
-
function sameCreateInput(invocation, input) {
|
|
400
|
-
return invocation.parentConversationId === input.parentConversationId && invocation.agentName === input.agentName && invocation.input === input.input && invocation.agentType === input.agentType && invocation.reasoningLevel === input.reasoningLevel && JSON.stringify(invocation.actor) === JSON.stringify(input.actor) && JSON.stringify(invocation.credentialContext) === JSON.stringify(input.credentialContext) && JSON.stringify(invocation.destination) === JSON.stringify(input.destination);
|
|
401
|
-
}
|
|
402
340
|
/** Read one durable agent invocation. */
|
|
403
341
|
async function getAgentInvocation(invocationId) {
|
|
404
342
|
const rows = await getSqlExecutor().db().select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.invocationId, invocationId));
|
|
@@ -431,177 +369,12 @@ async function getChildAgentLabel(childConversationId) {
|
|
|
431
369
|
}).from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, childConversationId)).orderBy(sql`${juniorAgentInvocations.title} is null`, desc(juniorAgentInvocations.createdAt)).limit(1);
|
|
432
370
|
return row;
|
|
433
371
|
}
|
|
434
|
-
async function getNonTerminalAgentInvocationForConversation(childConversationId) {
|
|
435
|
-
const rows = await getSqlExecutor().db().select().from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.childConversationId, childConversationId), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES))).orderBy(asc(juniorAgentInvocations.createdAt)).limit(1);
|
|
436
|
-
return rows[0] ? invocationFromRow(rows[0]) : void 0;
|
|
437
|
-
}
|
|
438
|
-
async function countNonTerminalAgentInvocationsForChild(childConversationId) {
|
|
439
|
-
return (await getSqlExecutor().db().select({ value: count() }).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.childConversationId, childConversationId), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES))))[0]?.value ?? 0;
|
|
440
|
-
}
|
|
441
372
|
/**
|
|
442
|
-
*
|
|
443
|
-
*
|
|
444
|
-
* invocation, so it always passes.
|
|
373
|
+
* List the open agent invocations that run on one Conversation or on its
|
|
374
|
+
* child agents, oldest first. Open-work checks read this once and filter it.
|
|
445
375
|
*/
|
|
446
|
-
async function
|
|
447
|
-
|
|
448
|
-
}
|
|
449
|
-
/**
|
|
450
|
-
* Count the child agents of one parent that have open work. Messages queued
|
|
451
|
-
* for a busy child do not count again.
|
|
452
|
-
*/
|
|
453
|
-
async function countActiveChildAgentsForParent(parentConversationId) {
|
|
454
|
-
return (await getSqlExecutor().db().select({ value: countDistinct(juniorAgentInvocations.childConversationId) }).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, parentConversationId), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES))))[0]?.value ?? 0;
|
|
455
|
-
}
|
|
456
|
-
/**
|
|
457
|
-
* Create or replay the first invocation of one new child agent. A name gives
|
|
458
|
-
* the child a stable Conversation id that later messages can address. A name
|
|
459
|
-
* that is already used throws: later work for that child goes through
|
|
460
|
-
* `createAgentInvocationForMessage`.
|
|
461
|
-
*/
|
|
462
|
-
async function createAgentInvocation(rawInput, nowMs = Date.now()) {
|
|
463
|
-
const input = createAgentInvocationSchema.parse(rawInput);
|
|
464
|
-
const invocationId = getAgentInvocationId(input.parentConversationId, input.idempotencyKey);
|
|
465
|
-
const childConversationId = input.agentName ? getNamedAgentConversationId(input.parentConversationId, input.agentName) : getUnnamedAgentConversationId(invocationId);
|
|
466
|
-
const lockName = getChildAgentLockName(input.parentConversationId);
|
|
467
|
-
return await getSqlExecutor().withLock(lockName, async () => {
|
|
468
|
-
const existing = await getAgentInvocation(invocationId);
|
|
469
|
-
if (existing) {
|
|
470
|
-
if (!sameCreateInput(existing, input)) throw new Error(`Agent invocation idempotency key was reused with different input for ${invocationId}`);
|
|
471
|
-
return existing;
|
|
472
|
-
}
|
|
473
|
-
await assertCanGiveChildWork(input.parentConversationId);
|
|
474
|
-
if (input.agentName && await getAgentBinding({
|
|
475
|
-
name: input.agentName,
|
|
476
|
-
parentConversationId: input.parentConversationId
|
|
477
|
-
})) throw new AgentNameInUseError(input.agentName);
|
|
478
|
-
if (await countActiveChildAgentsForParent(input.parentConversationId) >= 8) throw new AgentInvocationLimitError(8);
|
|
479
|
-
await getConversationStore().createChild({
|
|
480
|
-
childConversationId,
|
|
481
|
-
parentConversationId: input.parentConversationId,
|
|
482
|
-
nowMs,
|
|
483
|
-
source: "internal"
|
|
484
|
-
});
|
|
485
|
-
if (input.agentName) await getSqlExecutor().db().insert(juniorAgentBindings).values({
|
|
486
|
-
childConversationId,
|
|
487
|
-
name: input.agentName,
|
|
488
|
-
parentConversationId: input.parentConversationId
|
|
489
|
-
});
|
|
490
|
-
await getSqlExecutor().db().insert(juniorAgentInvocations).values({
|
|
491
|
-
invocationId,
|
|
492
|
-
parentConversationId: input.parentConversationId,
|
|
493
|
-
childConversationId,
|
|
494
|
-
agentName: input.agentName ?? null,
|
|
495
|
-
input: input.input,
|
|
496
|
-
title: input.title ?? null,
|
|
497
|
-
actor: input.actor,
|
|
498
|
-
credentialContext: input.credentialContext ?? null,
|
|
499
|
-
source: { kind: "agent_invocation" },
|
|
500
|
-
destination: input.destination,
|
|
501
|
-
agentType: input.agentType ?? null,
|
|
502
|
-
reasoningLevel: input.reasoningLevel ?? null,
|
|
503
|
-
parentToolCallId: input.parentToolCallId ?? null,
|
|
504
|
-
status: "pending",
|
|
505
|
-
mailboxStatus: "pending",
|
|
506
|
-
createdAt: new Date(nowMs),
|
|
507
|
-
updatedAt: new Date(nowMs),
|
|
508
|
-
terminalAt: null
|
|
509
|
-
}).onConflictDoNothing();
|
|
510
|
-
const invocation = await getAgentInvocation(invocationId);
|
|
511
|
-
if (!invocation || !sameCreateInput(invocation, input)) throw new Error(`Agent invocation creation raced for ${invocationId}`);
|
|
512
|
-
return invocation;
|
|
513
|
-
});
|
|
514
|
-
}
|
|
515
|
-
/**
|
|
516
|
-
* Create or replay the agent invocation that gives one input to a child
|
|
517
|
-
* Conversation: a result or message from its own child agent, or its own
|
|
518
|
-
* watch events. It continues that Conversation for the same parent as
|
|
519
|
-
* `latest`, and for the same Actor and credentials unless `runAs` sets them.
|
|
520
|
-
* It skips the queue and active-count checks because it continues work that
|
|
521
|
-
* already passed them.
|
|
522
|
-
*/
|
|
523
|
-
async function createAgentInvocationFromLatest(args, nowMs = Date.now()) {
|
|
524
|
-
const { invocationId } = args;
|
|
525
|
-
await getSqlExecutor().db().insert(juniorAgentInvocations).values({
|
|
526
|
-
invocationId,
|
|
527
|
-
parentConversationId: args.latest.parentConversationId,
|
|
528
|
-
childConversationId: args.latest.childConversationId,
|
|
529
|
-
agentName: args.latest.agentName ?? null,
|
|
530
|
-
input: args.input,
|
|
531
|
-
actor: (args.runAs ?? args.latest).actor,
|
|
532
|
-
credentialContext: (args.runAs ?? args.latest).credentialContext ?? null,
|
|
533
|
-
source: args.runAs?.source ?? { kind: "agent_invocation" },
|
|
534
|
-
destination: args.latest.destination,
|
|
535
|
-
agentType: args.latest.agentType ?? null,
|
|
536
|
-
reasoningLevel: args.latest.reasoningLevel ?? null,
|
|
537
|
-
status: "pending",
|
|
538
|
-
mailboxStatus: "pending",
|
|
539
|
-
createdAt: new Date(nowMs),
|
|
540
|
-
updatedAt: new Date(nowMs),
|
|
541
|
-
terminalAt: null
|
|
542
|
-
}).onConflictDoNothing();
|
|
543
|
-
const invocation = await getAgentInvocation(invocationId);
|
|
544
|
-
if (!invocation || invocation.childConversationId !== args.latest.childConversationId) throw new Error(`Agent invocation creation raced for ${invocationId}`);
|
|
545
|
-
return invocation;
|
|
546
|
-
}
|
|
547
|
-
/**
|
|
548
|
-
* Return whether a pending agent invocation still waits for older open work
|
|
549
|
-
* on its child.
|
|
550
|
-
*/
|
|
551
|
-
async function isQueuedBehindOpenWork(invocation) {
|
|
552
|
-
if (invocation.status !== "pending") return false;
|
|
553
|
-
return (await getSqlExecutor().db().select({ invocationId: juniorAgentInvocations.invocationId }).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.childConversationId, invocation.childConversationId), lt(juniorAgentInvocations.createdAt, new Date(invocation.createdAtMs)), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES))).limit(1)).length > 0;
|
|
554
|
-
}
|
|
555
|
-
/**
|
|
556
|
-
* Create or replay the agent invocation for one message from a parent to one
|
|
557
|
-
* of its child agents. The child continues its history. If the child already
|
|
558
|
-
* has open work, the new agent invocation waits for that work and the parent
|
|
559
|
-
* gets one report for both. A stopped child starts again.
|
|
560
|
-
*/
|
|
561
|
-
async function createAgentInvocationForMessage(input, nowMs = Date.now()) {
|
|
562
|
-
const invocationId = getAgentInvocationId(input.parentConversationId, input.idempotencyKey);
|
|
563
|
-
return await getSqlExecutor().withLock(getChildAgentLockName(input.parentConversationId), async () => {
|
|
564
|
-
const existing = await getAgentInvocation(invocationId);
|
|
565
|
-
if (existing) {
|
|
566
|
-
if (existing.childConversationId !== input.childConversationId || existing.input !== input.input) throw new Error(`Agent invocation idempotency key was reused with different input for ${invocationId}`);
|
|
567
|
-
return {
|
|
568
|
-
invocation: existing,
|
|
569
|
-
queued: await isQueuedBehindOpenWork(existing)
|
|
570
|
-
};
|
|
571
|
-
}
|
|
572
|
-
const latest = await getLatestAgentInvocationForConversation(input.childConversationId);
|
|
573
|
-
if (!latest || latest.parentConversationId !== input.parentConversationId) throw new Error(`${input.childConversationId} is not a child agent of ${input.parentConversationId}`);
|
|
574
|
-
await assertCanGiveChildWork(input.parentConversationId);
|
|
575
|
-
const openCount = await countNonTerminalAgentInvocationsForChild(input.childConversationId);
|
|
576
|
-
if (openCount >= 4) throw new AgentMessageQueueFullError(4);
|
|
577
|
-
if (openCount === 0 && await countActiveChildAgentsForParent(input.parentConversationId) >= 8) throw new AgentInvocationLimitError(8);
|
|
578
|
-
await getSqlExecutor().db().insert(juniorAgentInvocations).values({
|
|
579
|
-
invocationId,
|
|
580
|
-
parentConversationId: input.parentConversationId,
|
|
581
|
-
childConversationId: input.childConversationId,
|
|
582
|
-
agentName: latest.agentName ?? null,
|
|
583
|
-
input: input.input,
|
|
584
|
-
title: null,
|
|
585
|
-
actor: input.actor,
|
|
586
|
-
credentialContext: input.credentialContext ?? null,
|
|
587
|
-
source: { kind: "agent_invocation" },
|
|
588
|
-
destination: input.destination,
|
|
589
|
-
agentType: latest.agentType ?? null,
|
|
590
|
-
reasoningLevel: latest.reasoningLevel ?? null,
|
|
591
|
-
parentToolCallId: input.parentToolCallId,
|
|
592
|
-
status: "pending",
|
|
593
|
-
mailboxStatus: "pending",
|
|
594
|
-
createdAt: new Date(nowMs),
|
|
595
|
-
updatedAt: new Date(nowMs),
|
|
596
|
-
terminalAt: null
|
|
597
|
-
}).onConflictDoNothing();
|
|
598
|
-
const invocation = await getAgentInvocation(invocationId);
|
|
599
|
-
if (!invocation) throw new Error(`Agent invocation creation raced for ${invocationId}`);
|
|
600
|
-
return {
|
|
601
|
-
invocation,
|
|
602
|
-
queued: openCount > 0
|
|
603
|
-
};
|
|
604
|
-
});
|
|
376
|
+
async function listOpenAgentInvocations(conversationId) {
|
|
377
|
+
return (await getSqlExecutor().db().select().from(juniorAgentInvocations).where(and(or(eq(juniorAgentInvocations.childConversationId, conversationId), eq(juniorAgentInvocations.parentConversationId, conversationId)), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES))).orderBy(asc(juniorAgentInvocations.createdAt))).map(invocationFromRow);
|
|
605
378
|
}
|
|
606
379
|
/**
|
|
607
380
|
* Return whether a child Conversation has work that will start another agent
|
|
@@ -609,9 +382,9 @@ async function createAgentInvocationForMessage(input, nowMs = Date.now()) {
|
|
|
609
382
|
* sent child agent result that no agent invocation has received yet.
|
|
610
383
|
*/
|
|
611
384
|
async function hasOpenChildWork(invocation) {
|
|
612
|
-
const db = getSqlExecutor().db();
|
|
613
385
|
const conversationId = invocation.childConversationId;
|
|
614
|
-
if ((await
|
|
386
|
+
if ((await listOpenAgentInvocations(conversationId)).some((row) => row.invocationId !== invocation.invocationId)) return true;
|
|
387
|
+
const db = getSqlExecutor().db();
|
|
615
388
|
const sent = await db.select({ invocationId: juniorAgentInvocations.invocationId }).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, conversationId), inArray(juniorAgentInvocations.parentMailboxStatus, ["pending", "appended"])));
|
|
616
389
|
if (sent.length === 0) return false;
|
|
617
390
|
return (await db.select({ invocationId: juniorAgentInvocations.invocationId }).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.invocationId, sent.map((row) => getAgentInvocationIdForResult(row.invocationId))))).length < sent.length;
|
|
@@ -706,4 +479,324 @@ async function markAgentInvocationSteered(invocationId, nowMs = Date.now()) {
|
|
|
706
479
|
function isTerminalAgentInvocation(invocation) {
|
|
707
480
|
return TERMINAL_AGENT_INVOCATION_STATUSES.includes(invocation.status);
|
|
708
481
|
}
|
|
709
|
-
|
|
482
|
+
// src/chat/conversations/pending-cards.ts
|
|
483
|
+
/**
|
|
484
|
+
* Add the cards that tool results selected since the last visible assistant
|
|
485
|
+
* Message or Turn start, scanning back from `beforeSeq`. Returns the input
|
|
486
|
+
* message ids of the Turn start that ended the scan.
|
|
487
|
+
*/
|
|
488
|
+
async function selectTurnCards(conversationId, selection, beforeSeq) {
|
|
489
|
+
while (true) {
|
|
490
|
+
const page = await getConversationEventStore().query(conversationId, {
|
|
491
|
+
beforeSeq,
|
|
492
|
+
limit: 100,
|
|
493
|
+
types: [
|
|
494
|
+
"tool_result",
|
|
495
|
+
"message",
|
|
496
|
+
"turn_started"
|
|
497
|
+
]
|
|
498
|
+
});
|
|
499
|
+
for (const event of [...page.events].reverse()) {
|
|
500
|
+
const data = event.data;
|
|
501
|
+
if (data.type === "turn_started") return data.inputMessageIds;
|
|
502
|
+
if (data.type === "message" && data.role === "assistant") return [];
|
|
503
|
+
if (data.type !== "tool_result" || data.isError || typeof data.toolName !== "string" || !isRecord(data.details)) continue;
|
|
504
|
+
if (data.details.timed_out === true) continue;
|
|
505
|
+
if (Array.isArray(data.details.removedCards)) for (const ref of removedCardSchema.array().parse(data.details.removedCards)) selection.deleted.add(JSON.stringify([ref.plugin, ref.key]));
|
|
506
|
+
for (const card of readMessageCardRefs(data.details)) {
|
|
507
|
+
const key = JSON.stringify([card.plugin, card.key]);
|
|
508
|
+
if (!selection.deleted.has(key) && !selection.cards.has(key)) selection.cards.set(key, card);
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
if (!page.hasOlder || page.events.length === 0) return [];
|
|
512
|
+
beforeSeq = page.events[0].seq;
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* Add the cards of child agents whose results started this Turn. A child
|
|
517
|
+
* cannot reply to people, so its parent's reply delivers its cards.
|
|
518
|
+
*/
|
|
519
|
+
async function selectChildResultCards(inputMessageIds, selection) {
|
|
520
|
+
const events = getConversationEventStore();
|
|
521
|
+
for (const messageId of [...inputMessageIds].reverse()) {
|
|
522
|
+
const invocationId = parseAgentInvocationResultMessageId(messageId);
|
|
523
|
+
const invocation = invocationId ? await getAgentInvocation(invocationId) : void 0;
|
|
524
|
+
if (!invocation) continue;
|
|
525
|
+
const turnId = getAgentInvocationTurnId(invocation.invocationId);
|
|
526
|
+
const terminal = await events.loadByIdempotencyKey(invocation.childConversationId, `turn:${turnId}:terminal`);
|
|
527
|
+
if (!terminal) continue;
|
|
528
|
+
await selectTurnCards(invocation.childConversationId, selection, terminal.seq);
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
/** Select undelivered cards and load their latest saved facts. */
|
|
532
|
+
async function loadPendingMessageCards(conversationId) {
|
|
533
|
+
const selection = {
|
|
534
|
+
cards: /* @__PURE__ */ new Map(),
|
|
535
|
+
deleted: /* @__PURE__ */ new Set()
|
|
536
|
+
};
|
|
537
|
+
await selectChildResultCards(await selectTurnCards(conversationId, selection), selection);
|
|
538
|
+
if (selection.cards.size === 0) return [];
|
|
539
|
+
return resolveMessageCards([...selection.cards.values()].reverse(), await listConversationAnnotations(getDb(), conversationId));
|
|
540
|
+
}
|
|
541
|
+
// src/chat/conversations/turn-lifecycle.ts
|
|
542
|
+
/** Persist correlated turn lifecycle facts with retry-safe terminal exclusion. */
|
|
543
|
+
var ConversationTurnLifecycleService = class {
|
|
544
|
+
events;
|
|
545
|
+
constructor(events) {
|
|
546
|
+
this.events = events;
|
|
547
|
+
}
|
|
548
|
+
/** Record the turn start once after every input message is durable. */
|
|
549
|
+
async start(input) {
|
|
550
|
+
await this.events.append(input.conversationId, [{
|
|
551
|
+
idempotencyKey: `turn:${input.turnId}:started`,
|
|
552
|
+
createdAtMs: input.createdAtMs,
|
|
553
|
+
data: {
|
|
554
|
+
type: "turn_started",
|
|
555
|
+
turnId: input.turnId,
|
|
556
|
+
inputMessageIds: input.inputMessageIds,
|
|
557
|
+
surface: input.surface,
|
|
558
|
+
...input.threadContextThroughSeq === void 0 ? void 0 : { threadContextThroughSeq: input.threadContextThroughSeq }
|
|
559
|
+
}
|
|
560
|
+
}]);
|
|
561
|
+
}
|
|
562
|
+
/** Return the input message ids that started a Turn, when it started. */
|
|
563
|
+
async loadInputMessageIds(conversationId, turnId) {
|
|
564
|
+
const event = await this.events.loadByIdempotencyKey(conversationId, `turn:${turnId}:started`);
|
|
565
|
+
return event?.data.type === "turn_started" ? event.data.inputMessageIds : void 0;
|
|
566
|
+
}
|
|
567
|
+
/** Record a completion that is not a failure once. */
|
|
568
|
+
async complete(input) {
|
|
569
|
+
await this.events.append(input.conversationId, [{
|
|
570
|
+
idempotencyKey: `turn:${input.turnId}:terminal`,
|
|
571
|
+
createdAtMs: input.createdAtMs,
|
|
572
|
+
data: {
|
|
573
|
+
type: "turn_completed",
|
|
574
|
+
turnId: input.turnId,
|
|
575
|
+
outcome: input.outcome
|
|
576
|
+
}
|
|
577
|
+
}]);
|
|
578
|
+
}
|
|
579
|
+
/** Record a classified failure once. Do not store raw error text. */
|
|
580
|
+
async fail(input) {
|
|
581
|
+
await this.events.append(input.conversationId, [{
|
|
582
|
+
idempotencyKey: `turn:${input.turnId}:terminal`,
|
|
583
|
+
createdAtMs: input.createdAtMs,
|
|
584
|
+
data: {
|
|
585
|
+
type: "turn_failed",
|
|
586
|
+
turnId: input.turnId,
|
|
587
|
+
failureCode: input.failureCode,
|
|
588
|
+
...input.failureReason ? { failureReason: input.failureReason } : void 0,
|
|
589
|
+
...input.eventId ? { eventId: input.eventId } : void 0
|
|
590
|
+
}
|
|
591
|
+
}]);
|
|
592
|
+
}
|
|
593
|
+
};
|
|
594
|
+
/** Return the Turn lifecycle that records Conversation events. */
|
|
595
|
+
function getTurnLifecycle() {
|
|
596
|
+
return new ConversationTurnLifecycleService(getConversationEventStore());
|
|
597
|
+
}
|
|
598
|
+
// src/chat/conversations/thread-context.ts
|
|
599
|
+
const CURSOR_TURN_LOOKBACK = 10;
|
|
600
|
+
async function loadThreadContextCursor(args) {
|
|
601
|
+
const store = getConversationEventStore();
|
|
602
|
+
const [started, completed] = await Promise.all([store.query(args.conversationId, {
|
|
603
|
+
limit: CURSOR_TURN_LOOKBACK,
|
|
604
|
+
types: ["turn_started"]
|
|
605
|
+
}), store.query(args.conversationId, {
|
|
606
|
+
limit: CURSOR_TURN_LOOKBACK,
|
|
607
|
+
types: ["turn_completed"]
|
|
608
|
+
})]);
|
|
609
|
+
const finished = new Set(completed.events.flatMap((event) => event.data.type === "turn_completed" && event.data.outcome !== "cancelled" ? [event.data.turnId] : []));
|
|
610
|
+
const previous = [...started.events].reverse().find((event) => event.data.type === "turn_started" && event.data.turnId !== args.turnId && finished.has(event.data.turnId));
|
|
611
|
+
return previous?.data.type === "turn_started" ? previous.data.threadContextThroughSeq : void 0;
|
|
612
|
+
}
|
|
613
|
+
/**
|
|
614
|
+
* Return the oldest cursor of the Turns that the cursor lookup reads. Messages
|
|
615
|
+
* after it may still be in the thread context delta of the next Turn, also
|
|
616
|
+
* when the latest Turns failed or the next Turn retries.
|
|
617
|
+
*/
|
|
618
|
+
async function loadThreadContextTrimFloor(conversationId) {
|
|
619
|
+
const cursors = (await getConversationEventStore().query(conversationId, {
|
|
620
|
+
limit: CURSOR_TURN_LOOKBACK,
|
|
621
|
+
types: ["turn_started"]
|
|
622
|
+
})).events.flatMap((event) => event.data.type === "turn_started" && event.data.threadContextThroughSeq !== void 0 ? [event.data.threadContextThroughSeq] : []);
|
|
623
|
+
return cursors.length > 0 ? Math.min(...cursors) : void 0;
|
|
624
|
+
}
|
|
625
|
+
/**
|
|
626
|
+
* Build the thread context of one Turn prompt. With agent history, show only
|
|
627
|
+
* the thread Messages saved after the cursor of the previous Turn.
|
|
628
|
+
*/
|
|
629
|
+
async function buildTurnThreadContext(args) {
|
|
630
|
+
const afterSeq = args.hasHistory ? await loadThreadContextCursor({
|
|
631
|
+
conversationId: args.conversationId,
|
|
632
|
+
turnId: args.turnId
|
|
633
|
+
}) : void 0;
|
|
634
|
+
const block = buildConversationContext(args.conversation, {
|
|
635
|
+
excludeMessageIds: args.excludeMessageIds,
|
|
636
|
+
...args.hasHistory ? { history: { afterSeq } } : void 0
|
|
637
|
+
});
|
|
638
|
+
setSpanAttributes({
|
|
639
|
+
"app.thread_context.chars": block.text?.length ?? 0,
|
|
640
|
+
"app.thread_context.shown_messages": block.shownMessages,
|
|
641
|
+
"app.thread_context.omitted_messages": block.omittedMessages,
|
|
642
|
+
"app.thread_context.cursor": !args.hasHistory ? "no_history" : afterSeq === void 0 ? "missing" : "found"
|
|
643
|
+
});
|
|
644
|
+
return block.text;
|
|
645
|
+
}
|
|
646
|
+
// src/chat/runtime/delivered-turn-state.ts
|
|
647
|
+
/** Build state after destination delivery or intentional no-reply completion. */
|
|
648
|
+
function buildDeliveredTurnStatePatch(args) {
|
|
649
|
+
const conversation = structuredClone(args.conversation);
|
|
650
|
+
clearPendingAuth(conversation, args.sessionId);
|
|
651
|
+
markConversationMessage(conversation, args.userMessageId, {
|
|
652
|
+
replied: true,
|
|
653
|
+
skippedReason: void 0
|
|
654
|
+
});
|
|
655
|
+
markTurnCompleted({
|
|
656
|
+
conversation,
|
|
657
|
+
nowMs: Date.now(),
|
|
658
|
+
sessionId: args.sessionId
|
|
659
|
+
});
|
|
660
|
+
return {
|
|
661
|
+
conversation,
|
|
662
|
+
sandboxRef: args.reply.sandboxRef
|
|
663
|
+
};
|
|
664
|
+
}
|
|
665
|
+
// src/chat/runtime/turn-user-message.ts
|
|
666
|
+
/** Return the user message for a persisted turn/session, if one exists. */
|
|
667
|
+
function getTurnUserMessage(conversation, sessionId) {
|
|
668
|
+
for (let index = conversation.messages.length - 1; index >= 0; index -= 1) {
|
|
669
|
+
const message = conversation.messages[index];
|
|
670
|
+
if (message?.role !== "user") continue;
|
|
671
|
+
if (buildDeterministicTurnId(message.id) === sessionId) return message;
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
/** Return the persisted user-message id for a turn/session, if one exists. */
|
|
675
|
+
function getTurnUserMessageId(conversation, sessionId) {
|
|
676
|
+
return getTurnUserMessage(conversation, sessionId)?.id;
|
|
677
|
+
}
|
|
678
|
+
/** Return the Slack timestamp for the user message that a resumed turn acts on. */
|
|
679
|
+
function getTurnUserSlackMessageTs(message) {
|
|
680
|
+
return parseSlackMessageTs(message?.meta?.slackTs);
|
|
681
|
+
}
|
|
682
|
+
/** Rebuild attachment context for a resumed turn from the persisted user message. */
|
|
683
|
+
function getTurnUserReplyAttachmentContext(message) {
|
|
684
|
+
const inboundAttachmentCount = message?.meta?.attachmentCount ?? 0;
|
|
685
|
+
const imageAttachmentCount = message?.meta?.imageAttachmentCount ?? 0;
|
|
686
|
+
const imagesHydrated = message?.meta?.imagesHydrated === true;
|
|
687
|
+
return {
|
|
688
|
+
...inboundAttachmentCount > 0 ? { inboundAttachmentCount } : void 0,
|
|
689
|
+
...!imagesHydrated && imageAttachmentCount > 0 ? { omittedImageAttachmentCount: imageAttachmentCount } : void 0
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
// src/chat/runtime/auth-pause-state.ts
|
|
693
|
+
/** Mark an auth-paused turn complete after private authorization link delivery. */
|
|
694
|
+
function completeAuthPauseTurn(args) {
|
|
695
|
+
markConversationMessage(args.conversation, getTurnUserMessageId(args.conversation, args.sessionId), {
|
|
696
|
+
replied: true,
|
|
697
|
+
skippedReason: void 0
|
|
698
|
+
});
|
|
699
|
+
markTurnClosed({
|
|
700
|
+
conversation: args.conversation,
|
|
701
|
+
nowMs: Date.now(),
|
|
702
|
+
sessionId: args.sessionId
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
/** Reload thread state, mark the auth pause as parked, and persist it. */
|
|
706
|
+
async function persistAuthPauseTurnState(args) {
|
|
707
|
+
const currentState = await getPersistedThreadState(args.threadStateId);
|
|
708
|
+
const conversation = coerceThreadConversationState(currentState);
|
|
709
|
+
await hydrateConversationMessages({
|
|
710
|
+
conversation,
|
|
711
|
+
conversationId: args.threadStateId
|
|
712
|
+
});
|
|
713
|
+
completeAuthPauseTurn({
|
|
714
|
+
conversation,
|
|
715
|
+
sessionId: args.sessionId
|
|
716
|
+
});
|
|
717
|
+
await persistThreadStateById(args.threadStateId, { conversation });
|
|
718
|
+
}
|
|
719
|
+
// src/chat/interruption-marker.ts
|
|
720
|
+
const INTERRUPTED_MARKER = "\n\n[Response interrupted before completion]";
|
|
721
|
+
/** Return the marker added when a visible reply ended mid-execution. */
|
|
722
|
+
function getInterruptionMarker() {
|
|
723
|
+
return INTERRUPTED_MARKER;
|
|
724
|
+
}
|
|
725
|
+
// src/chat/services/turn-failure-response.ts
|
|
726
|
+
/** Require captured turn failures to carry a real Sentry event reference. */
|
|
727
|
+
function requireTurnFailureEventId(eventId, eventName) {
|
|
728
|
+
if (!eventId) throw new Error(`Sentry did not return an event ID for ${eventName}`);
|
|
729
|
+
return eventId;
|
|
730
|
+
}
|
|
731
|
+
function getExecutionFailureReason(reply) {
|
|
732
|
+
const errorMessage = reply.diagnostics.errorMessage?.trim();
|
|
733
|
+
if (errorMessage) return errorMessage;
|
|
734
|
+
if (reply.diagnostics.toolErrorCount > 0) return `${reply.diagnostics.toolErrorCount} tool result error(s)`;
|
|
735
|
+
if (reply.diagnostics.assistantMessageCount > 0) return "assistant returned no text";
|
|
736
|
+
return "empty assistant turn";
|
|
737
|
+
}
|
|
738
|
+
/** Return a fixed reason label for a failed model turn. */
|
|
739
|
+
function getTurnFailureReason(reply) {
|
|
740
|
+
if (reply.diagnostics.outcome === "success") return;
|
|
741
|
+
if (reply.diagnostics.outcome === "provider_error") return findProviderError(reply.diagnostics.providerError)?.kind ?? "unknown";
|
|
742
|
+
if (reply.diagnostics.toolErrorCount > 0) return "tool_errors";
|
|
743
|
+
if (reply.diagnostics.usedPrimaryText && reply.diagnostics.assistantMessageCount > 0) return "suppressed_output";
|
|
744
|
+
return "empty_output";
|
|
745
|
+
}
|
|
746
|
+
function getFailureCapture(reply) {
|
|
747
|
+
if (reply.diagnostics.outcome === "provider_error") {
|
|
748
|
+
const providerError = findProviderError(reply.diagnostics.providerError);
|
|
749
|
+
return {
|
|
750
|
+
eventName: "agent.turn.provider_error",
|
|
751
|
+
error: reply.diagnostics.providerError ?? new Error(reply.diagnostics.errorMessage ?? "Provider error without explicit message"),
|
|
752
|
+
attributes: providerError ? getProviderErrorAttributes(providerError) : {},
|
|
753
|
+
body: "Agent turn failed with provider error"
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
const failureReason = getExecutionFailureReason(reply);
|
|
757
|
+
return {
|
|
758
|
+
eventName: "agent.turn.execution.failed",
|
|
759
|
+
error: /* @__PURE__ */ new Error(`Agent turn execution failure: ${failureReason}`),
|
|
760
|
+
attributes: { "app.ai.execution_failure_reason": failureReason },
|
|
761
|
+
body: "Agent turn completed with execution failure"
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
/** Keep failed-turn Sentry captures and completion spans on the same keys. */
|
|
765
|
+
function getAgentTurnDiagnosticsAttributes(reply) {
|
|
766
|
+
return {
|
|
767
|
+
"app.ai.outcome": reply.diagnostics.outcome,
|
|
768
|
+
"app.ai.assistant_messages": reply.diagnostics.assistantMessageCount,
|
|
769
|
+
"app.ai.tool_results": reply.diagnostics.toolResultCount,
|
|
770
|
+
"app.ai.tool_error_results": reply.diagnostics.toolErrorCount,
|
|
771
|
+
"app.ai.tool_call_count": reply.diagnostics.toolCalls.length,
|
|
772
|
+
"app.ai.used_primary_text": reply.diagnostics.usedPrimaryText,
|
|
773
|
+
...reply.automation ? { "app.automation.result": reply.automation.result } : void 0,
|
|
774
|
+
...reply.diagnostics.reasoningLevel ? { "gen_ai.request.reasoning.level": reply.diagnostics.reasoningLevel } : void 0,
|
|
775
|
+
...reply.diagnostics.stopReason ? { "gen_ai.response.finish_reasons": [reply.diagnostics.stopReason] } : void 0,
|
|
776
|
+
...reply.diagnostics.errorMessage && reply.diagnostics.outcome !== "provider_error" ? { "exception.message": reply.diagnostics.errorMessage } : void 0
|
|
777
|
+
};
|
|
778
|
+
}
|
|
779
|
+
/** Enforce one captured failure response and return its structured correlation. */
|
|
780
|
+
function finalizeFailedTurnReplyWithEvent(args) {
|
|
781
|
+
if (args.reply.diagnostics.outcome === "success") return { reply: args.reply };
|
|
782
|
+
const failureReason = getTurnFailureReason(args.reply);
|
|
783
|
+
const capture = getFailureCapture(args.reply);
|
|
784
|
+
const eventId = requireTurnFailureEventId(args.logException(capture.error, capture.eventName, {
|
|
785
|
+
...getAgentTurnDiagnosticsAttributes(args.reply),
|
|
786
|
+
...args.attributes,
|
|
787
|
+
...capture.attributes,
|
|
788
|
+
...failureReason ? { "app.ai.failure_reason": failureReason } : void 0
|
|
789
|
+
}), capture.eventName);
|
|
790
|
+
const providerPartialText = args.reply.diagnostics.outcome === "provider_error" && args.reply.diagnostics.assistantMessageCount > 0 ? args.reply.text.trim() : "";
|
|
791
|
+
const providerUserMessage = args.reply.diagnostics.providerError instanceof ProviderError ? getProviderErrorUserMessage(args.reply.diagnostics.providerError) : "";
|
|
792
|
+
const failureText = providerUserMessage ? `${providerUserMessage} Reference: \`event_id=${eventId}\`.` : buildTurnFailureResponse(eventId);
|
|
793
|
+
return {
|
|
794
|
+
eventId,
|
|
795
|
+
...failureReason ? { failureReason } : void 0,
|
|
796
|
+
reply: {
|
|
797
|
+
...args.reply,
|
|
798
|
+
text: providerPartialText ? `${providerPartialText}${getInterruptionMarker()}` : failureText
|
|
799
|
+
}
|
|
800
|
+
};
|
|
801
|
+
}
|
|
802
|
+
export { parseAgentInvocationResultMessageId as $, markAgentInvocationPaused as A, agentTypeInstructions as B, isTerminalAgentInvocation as C, listPendingAgentInvocationResults as D, listPendingAgentInvocationMailboxAppends as E, PARENT_AGENT_TARGET as F, getAgentInvocationIdForMessage as G, formatAgentTypes as H, agentBindingSchema as I, getAgentInvocationResultMessageId as J, getAgentInvocationIdForResult as K, agentNameSchema as L, markAgentInvocationSteered as M, reportReplacedAgentInvocation as N, markAgentInvocationMailboxAppended as O, CHILD_AGENT_RESULTS as P, getUnnamedAgentConversationId as Q, createAgentInvocationSchema as R, invocationFromRow as S, listOpenAgentInvocations as T, getAgentInvocationId as U, agentTypeStartsWithParentHistory as V, getAgentInvocationIdForEvents as W, getChildAgentLockName as X, getAgentInvocationTurnId as Y, getNamedAgentConversationId as Z, completeAgentInvocation as _, persistAuthPauseTurnState as a, isCooperativeTurnYieldError as at, getChildAgentLabel as b, getTurnUserSlackMessageTs as c, markTurnClosed as ct, loadThreadContextTrimFloor as d, startActiveTurn as dt, ConversationTurnBoundaryError as et, ConversationTurnLifecycleService as f, NON_TERMINAL_AGENT_INVOCATION_STATUSES as g, ACTIVE_AGENT_INVOCATION_STATUSES as h, completeAuthPauseTurn as i, getConversationTurnBoundaryError as it, markAgentInvocationRunning as j, markAgentInvocationParentMailboxAppended as k, buildDeliveredTurnStatePatch as l, markTurnCompleted as lt, loadPendingMessageCards as m, getAgentTurnDiagnosticsAttributes as n, TurnInputCommitLostError as nt, getTurnUserMessage as o, isTurnInputCommitLostError as ot, getTurnLifecycle as p, getAgentInvocationMessageId as q, requireTurnFailureEventId as r, TurnInputDeferredError as rt, getTurnUserReplyAttachmentContext as s, isTurnInputDeferredError as st, finalizeFailedTurnReplyWithEvent as t, CooperativeTurnYieldError as tt, buildTurnThreadContext as u, markTurnFailed as ut, getActiveAgentInvocationForConversation as v, listAgentInvocationsForConversation as w, getLatestAgentInvocationForConversation as x, getAgentInvocation as y, AGENT_TYPES as z };
|