@sentry/junior 0.298.0 → 0.300.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.
Files changed (95) hide show
  1. package/dist/{actor-6jsm_v96.js → actor-D2iXzvlN.js} +2 -1
  2. package/dist/{state-CSuA2J1V.js → adapter-S5UkjNK3.js} +53 -136
  3. package/dist/{admin-BF3DbYGf.js → admin-UrTniSPO.js} +2 -2
  4. package/dist/{agent-runner-Q9GkoerG.js → agent-runner-bY4_0UPm.js} +1444 -1478
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +7 -7
  7. package/dist/api.d.ts +1 -1
  8. package/dist/api.js +382 -68
  9. package/dist/{app-DOg_mCtV.d.ts → app-D-AcIcCV.d.ts} +17 -4
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +148 -483
  12. package/dist/{automation-Cn8qmbdr.js → automation-Dw82oQ-h.js} +2 -2
  13. package/dist/{background-compaction-queue-BZhGFOK6.js → background-compaction-queue-B6U3060-.js} +9 -5
  14. package/dist/{briefs-CQrCRF6-.js → briefs-DqiwWu-n.js} +4 -4
  15. package/dist/{catalog-runtime-DZeD2WbL.js → catalog-runtime-D1oYNv04.js} +1 -1
  16. package/dist/cli/chat.js +17 -17
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +5 -5
  20. package/dist/cli/snapshot-create.js +4 -4
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +4 -4
  23. package/dist/{config-BOByVnxe.js → config-9nHoFiJP.js} +117 -12
  24. package/dist/{connections-BNN5cJam.js → connections-DZjTN3JC.js} +6 -6
  25. package/dist/continue-in-slack-Dtv7_U42.js +176 -0
  26. package/dist/{conversation-DCkzvxqB.js → conversation-Dyjq2CZ8.js} +36 -13
  27. package/dist/{conversation-feed-CMA12Rjs.js → conversation-feed-CcDxlrlQ.js} +109 -3
  28. package/dist/{conversation-privacy-C0eRxsgb.js → conversation-privacy-D-5HTXjS.js} +1 -1
  29. package/dist/{conversation-turn-D9qvcDX6.js → conversation-turn-Cxl8WZD7.js} +85 -68
  30. package/dist/{credential-sync-B_iUpxGL.js → credential-sync-C49ClwDX.js} +18 -18
  31. package/dist/{db-DoMcnYol.d.ts → db-2resqBh1.d.ts} +1 -1
  32. package/dist/{db-CoMNr2Zm.js → db-BJNo6fK5.js} +176 -12
  33. package/dist/{executor-C-m8VrzX.js → executor-DBIaOeJ_.js} +47 -13
  34. package/dist/{media-BepyEUNm.js → history-IjdmO_r6.js} +1 -85
  35. package/dist/instrumentation.js +14 -5
  36. package/dist/lineage-0dereG7H.js +37 -0
  37. package/dist/{logging-CJTi5niy.js → logging-BIclibct.js} +1 -1
  38. package/dist/{message-Q6_5DAWR.js → message-dkOl-Iii.js} +9 -10
  39. package/dist/model-input-CLo9TaUd.js +82 -0
  40. package/dist/nitro.d.ts +1 -1
  41. package/dist/nitro.js +17 -9
  42. package/dist/{oauth-callback-server-CH5XAyo-.js → oauth-callback-server-WmpjfJgQ.js} +2 -2
  43. package/dist/{plugins-HYh_JOdw.js → plugins-BBX07Jzt.js} +1 -1
  44. package/dist/{projection-BgwEE36_.js → projection-w_X-zi7v.js} +1035 -692
  45. package/dist/{prompt-DXc9DYT9.js → prompt-B1Xw46-S.js} +4 -4
  46. package/dist/{registry-9XwqSnM-.js → registry-BmP5vnlj.js} +4 -4
  47. package/dist/{resolve-DUIAbcRL.js → resolve-goo34bJK.js} +3 -3
  48. package/dist/{result-C2Vn8QGn.js → result-PVBeU0Wf.js} +158 -69
  49. package/dist/{runner-CXGtw-Mc.js → runner-DKrfvNV6.js} +9 -9
  50. package/dist/{sandbox-egress-signals-Di3S_dO7.js → sandbox-egress-signals-DsUcqrI0.js} +1 -1
  51. package/dist/{schema-Dyp7racy.js → schema-C9iNFz5n.js} +51 -7
  52. package/dist/{schema-BnbZ-rKv.d.ts → schema-Dns-sTas.d.ts} +1285 -761
  53. package/dist/{service-account-DM3KBBeG.js → service-account-CMAAloAL.js} +3 -3
  54. package/dist/{service-account-GzAMUQ8a.js → service-account-CmowamcB.js} +4 -4
  55. package/dist/session-stop-BcAXze8a.js +3330 -0
  56. package/dist/{skills-DCK9SD_l.js → skills-DfsazET6.js} +3 -3
  57. package/dist/slack-conversation-unfurl-CzQonuWz.js +370 -0
  58. package/dist/spawn-C7o0FDDp.js +73 -0
  59. package/dist/state-zSilNpbi.js +132 -0
  60. package/dist/{user-input-request-CXNIov9n.js → statuses-Hn-HsOph.js} +115 -26
  61. package/dist/{stop-Dh2DfwpK.js → stop-CFOujp8C.js} +9105 -6007
  62. package/dist/{store-DrA17Fbz.js → store-Dkeis_8o.js} +10 -10
  63. package/dist/{store-B1zepKG8.js → store-E3x2Fg_F.js} +24 -4
  64. package/dist/{task-queue-D1rXWfFN.js → task-queue-D-hCqdZW.js} +4 -4
  65. package/dist/{task-runner-CT4M8oDz.js → task-runner-vohUPLHe.js} +10 -10
  66. package/dist/{thread-context-DnqUkbzN.js → thread-context-BzvdkgI9.js} +18 -18
  67. package/dist/{turn-session-routing-VXDVXLRl.js → turn-session-routing-Bo_LxFum.js} +5 -5
  68. package/dist/turn-user-message-D5RnVmxQ.js +355 -0
  69. package/dist/users-2bggndVg.js +424 -0
  70. package/dist/{validation-zxAJBDDy.js → validation-BbWikeSa.js} +1 -1
  71. package/dist/{version-DcZ40a0g.js → version-GVBMW2jA.js} +1 -1
  72. package/dist/version.js +1 -1
  73. package/dist/{viewer-CgiGjW10.js → viewer-BpxRliyO.js} +36 -163
  74. package/dist/{warmup-CwKbxQLl.js → warmup-BW2qwnal.js} +1140 -145
  75. package/dist/{worker-CbDUzaBA.js → worker-Cbd-iuwZ.js} +25 -20
  76. package/migrations/0104_code_change_draft.sql +1 -0
  77. package/migrations/0105_attachment_uploads.sql +14 -0
  78. package/migrations/0106_conversation_agent_config.sql +1 -0
  79. package/migrations/0107_attachment_deferred_download.sql +2 -0
  80. package/migrations/meta/0104_snapshot.json +4516 -0
  81. package/migrations/meta/0105_snapshot.json +4611 -0
  82. package/migrations/meta/0106_snapshot.json +4617 -0
  83. package/migrations/meta/0107_snapshot.json +4617 -0
  84. package/migrations/meta/_journal.json +28 -0
  85. package/package.json +10 -8
  86. package/dist/attempt-selection-ClP3MMPr.js +0 -61
  87. package/dist/locks-D-0h111u.js +0 -48
  88. package/dist/notification-Bv25xbj0.js +0 -1284
  89. package/dist/prompt-input-BUr4J9RO.js +0 -1424
  90. package/dist/session-stop-D4i7e6iT.js +0 -181
  91. package/dist/spawn-6cX6xE9G.js +0 -80
  92. package/dist/turn-cancel-l460pfGW.js +0 -201
  93. package/dist/turn-user-message-BSPmkm7X.js +0 -608
  94. package/dist/turn-wake-DVFVXyhX.js +0 -161
  95. package/dist/{oauth-relay-CsfIazeF.js → oauth-relay-DRzq73b6.js} +1 -1
@@ -1,608 +0,0 @@
1
- import { g as TURN_REASONING_LEVELS } from "./config-BOByVnxe.js";
2
- import { h as parseSlackMessageTs } from "./actor-6jsm_v96.js";
3
- import { r as getConversationEventStore, s as getSqlExecutor } from "./db-CoMNr2Zm.js";
4
- import { g as juniorAgentInvocations } from "./executor-C-m8VrzX.js";
5
- import { p as credentialContextSchema } from "./registry-9XwqSnM-.js";
6
- import { k as agentTypeSchema } from "./conversation-DCkzvxqB.js";
7
- import { i as isEventMailboxMetadata } from "./notification-Bv25xbj0.js";
8
- import { _ as getConversationWorkState } from "./store-B1zepKG8.js";
9
- import { d as AGENT_INVOCATION_MAILBOX_STATUSES, f as AGENT_INVOCATION_PARENT_MAILBOX_STATUSES } from "./user-input-request-CXNIov9n.js";
10
- import { createHash } from "node:crypto";
11
- import * as z from "zod";
12
- import { and, asc, desc, eq, inArray, or, sql } from "drizzle-orm";
13
- import { actorSchema, destinationSchema, sourceSchema } from "@sentry/junior-plugin-api";
14
- // src/chat/state/turn-id.ts
15
- /** Build a stable turn identifier from a message ID. */
16
- function buildDeterministicTurnId(messageId) {
17
- return `turn_${messageId.replace(/[^a-zA-Z0-9_-]/g, "_")}`;
18
- }
19
- /** Build the stable visible assistant-message identity for one logical turn. */
20
- function buildDeterministicAssistantMessageId(turnId) {
21
- return `${turnId}:assistant:1`;
22
- }
23
- // src/chat/agent-invocations/ids.ts
24
- const CREATE_LOCK_PREFIX = "junior:agent_invocation:create";
25
- /**
26
- * Return the SQL lock that one parent Conversation takes to start, message,
27
- * or stop its child agents.
28
- */
29
- function getChildAgentLockName(parentConversationId) {
30
- return `${CREATE_LOCK_PREFIX}:${parentConversationId}`;
31
- }
32
- function stableId(prefix, ...parts) {
33
- return `${prefix}:${createHash("sha256").update(parts.join("\0")).digest("hex").slice(0, 32)}`;
34
- }
35
- /** Return the stable identity for one retry-safe delegated task. */
36
- function getAgentInvocationId(parentConversationId, idempotencyKey) {
37
- return stableId("agent-invocation", parentConversationId, idempotencyKey);
38
- }
39
- /** Return the stable child identity for one invocation without a named binding. */
40
- function getUnnamedAgentConversationId(invocationId) {
41
- return stableId("agent", invocationId);
42
- }
43
- /** Return the stable child identity for one named binding. */
44
- function getNamedAgentConversationId(parentConversationId, name) {
45
- return stableId("agent", parentConversationId, name);
46
- }
47
- /**
48
- * Return the stable identity of the agent invocation that gives one child
49
- * agent result to the child Conversation that started that child agent.
50
- */
51
- function getAgentInvocationIdForResult(resultInvocationId) {
52
- return stableId("agent-invocation", "result", resultInvocationId);
53
- }
54
- /**
55
- * Return the stable identity of the agent invocation that gives one message
56
- * from a child agent to the child Conversation that started that child agent.
57
- */
58
- function getAgentInvocationIdForMessage(messageId) {
59
- return stableId("agent-invocation", "message", messageId);
60
- }
61
- /**
62
- * Return the stable identity of the agent invocation that gives one batch of
63
- * watch events to a child Conversation. The first message of the batch names
64
- * it.
65
- */
66
- function getAgentInvocationIdForEvents(messageId) {
67
- return stableId("agent-invocation", "events", messageId);
68
- }
69
- /** Return the stable turn identity advanced by one agent invocation. */
70
- function getAgentInvocationTurnId(invocationId) {
71
- return `agent-invocation:${invocationId}`;
72
- }
73
- /** Return the stable mailbox identity for one agent invocation. */
74
- function getAgentInvocationMessageId(invocationId) {
75
- return `agent-invocation:${invocationId}:input`;
76
- }
77
- const REPLY_MESSAGE_PREFIX = "agent-reply:";
78
- /** Return the parent mailbox identity of one child agent `reply` call. */
79
- function getAgentReplyMessageId(invocationId, toolCallId) {
80
- return `${REPLY_MESSAGE_PREFIX}${invocationId}:${toolCallId}`;
81
- }
82
- /**
83
- * Return the key of the `reply` of one Turn on a child's Conversation loop.
84
- * It starts with the Turn id, so the parent can tell that the Turn replied.
85
- */
86
- function getTurnReplyKey(turnId, toolCallId) {
87
- return `${turnId}:${toolCallId}`;
88
- }
89
- const REPLY_MESSAGE_ID = /^agent-reply:(agent-invocation:[0-9a-f]{32}):/;
90
- /** Read the agent invocation identity from one parent `reply` mailbox identity. */
91
- function parseAgentReplyMessageId(messageId) {
92
- return REPLY_MESSAGE_ID.exec(messageId)?.[1];
93
- }
94
- const TURN_REPLY_MESSAGE_ID = /^agent-reply:agent-invocation:[0-9a-f]{32}:(turn_[A-Za-z0-9_-]+)(?::|$)/;
95
- /**
96
- * Read the Turn id from one parent mailbox identity that a Turn on a child's
97
- * Conversation loop sent. A `reply` of an agent invocation has none.
98
- */
99
- function parseTurnReplyMessageId(messageId) {
100
- return TURN_REPLY_MESSAGE_ID.exec(messageId)?.[1];
101
- }
102
- /** Return whether one parent mailbox identity is a `reply` of an agent invocation. */
103
- function isAgentReplyMessageId(messageId, invocationId) {
104
- return messageId.startsWith(`${REPLY_MESSAGE_PREFIX}${invocationId}:`);
105
- }
106
- const RESULT_MESSAGE_PREFIX = "agent-invocation:";
107
- const RESULT_MESSAGE_SUFFIX = ":result";
108
- /** Return the stable parent mailbox identity for one terminal result. */
109
- function getAgentInvocationResultMessageId(invocationId) {
110
- return `${RESULT_MESSAGE_PREFIX}${invocationId}${RESULT_MESSAGE_SUFFIX}`;
111
- }
112
- /** Read the invocation identity from one parent result mailbox identity. */
113
- function parseAgentInvocationResultMessageId(messageId) {
114
- if (!messageId.startsWith(RESULT_MESSAGE_PREFIX) || !messageId.endsWith(RESULT_MESSAGE_SUFFIX)) return;
115
- return messageId.slice(17, -7) || void 0;
116
- }
117
- // src/chat/agent-invocations/types.ts
118
- const exactStringSchema = z.string().min(1).refine((value) => value === value.trim());
119
- const agentNameSchema = exactStringSchema.max(64);
120
- /**
121
- * Kind of a new child Conversation. A Thread is a child that people can
122
- * message; a Task is one that only its parent messages.
123
- */
124
- const CHILD_AGENT_KINDS = ["thread", "task"];
125
- /** `messageAgent` target for the parent of a child agent. */
126
- const PARENT_AGENT_TARGET = "parent";
127
- const agentInvocationMailboxStatusSchema = z.enum(AGENT_INVOCATION_MAILBOX_STATUSES);
128
- const agentInvocationParentMailboxStatusSchema = z.enum(AGENT_INVOCATION_PARENT_MAILBOX_STATUSES);
129
- const agentBindingSchema = z.object({
130
- childConversationId: exactStringSchema,
131
- name: agentNameSchema,
132
- parentConversationId: exactStringSchema
133
- }).strict();
134
- const agentInvocationBaseSchema = z.object({
135
- actor: actorSchema,
136
- agentName: agentNameSchema.optional(),
137
- childConversationId: exactStringSchema,
138
- createdAtMs: z.number().finite(),
139
- credentialContext: credentialContextSchema.optional(),
140
- destination: destinationSchema,
141
- input: exactStringSchema,
142
- invocationId: exactStringSchema,
143
- mailboxStatus: agentInvocationMailboxStatusSchema,
144
- parentConversationId: exactStringSchema,
145
- parentToolCallId: exactStringSchema.optional(),
146
- agentType: agentTypeSchema.optional(),
147
- /** The child starts with its parent's history. */
148
- fork: z.literal(true).optional(),
149
- reasoningLevel: z.enum(TURN_REASONING_LEVELS).optional(),
150
- source: sourceSchema,
151
- title: exactStringSchema.optional(),
152
- updatedAtMs: z.number().finite()
153
- }).strict();
154
- const agentInvocationSchema = z.discriminatedUnion("status", [
155
- agentInvocationBaseSchema.extend({ status: z.enum([
156
- "pending",
157
- "running",
158
- "paused"
159
- ]) }),
160
- agentInvocationBaseSchema.extend({
161
- parentMailboxStatus: agentInvocationParentMailboxStatusSchema,
162
- result: z.string(),
163
- status: z.literal("completed"),
164
- terminalAtMs: z.number().finite()
165
- }),
166
- agentInvocationBaseSchema.extend({
167
- errorMessage: z.string(),
168
- parentMailboxStatus: agentInvocationParentMailboxStatusSchema,
169
- status: z.enum([
170
- "blocked",
171
- "failed",
172
- "stopped"
173
- ]),
174
- terminalAtMs: z.number().finite()
175
- })
176
- ]);
177
- const createAgentInvocationSchema = z.object({
178
- actor: actorSchema,
179
- agentName: agentNameSchema.optional(),
180
- credentialContext: credentialContextSchema.optional(),
181
- destination: destinationSchema,
182
- idempotencyKey: exactStringSchema,
183
- input: exactStringSchema,
184
- kind: z.enum(CHILD_AGENT_KINDS).default("task"),
185
- parentConversationId: exactStringSchema,
186
- parentToolCallId: exactStringSchema.optional(),
187
- agentType: agentTypeSchema.optional(),
188
- fork: z.literal(true).optional(),
189
- reasoningLevel: z.enum(TURN_REASONING_LEVELS).optional(),
190
- title: exactStringSchema.optional()
191
- }).strict();
192
- /** How a finished task of a child agent ended. A stop is not a result. */
193
- const CHILD_AGENT_RESULTS = [
194
- "completed",
195
- "blocked",
196
- "failed"
197
- ];
198
- // src/chat/agent-invocations/store.ts
199
- /** Statuses of a finished agent invocation. */
200
- const TERMINAL_AGENT_INVOCATION_STATUSES = [
201
- "blocked",
202
- "completed",
203
- "failed",
204
- "stopped"
205
- ];
206
- /** Statuses of an agent invocation that owns its child's Turn. */
207
- const ACTIVE_AGENT_INVOCATION_STATUSES = ["running", "paused"];
208
- /** Statuses of an agent invocation that has not finished. */
209
- const NON_TERMINAL_AGENT_INVOCATION_STATUSES = [
210
- "pending",
211
- "running",
212
- "paused"
213
- ];
214
- /** Parse one agent invocation row. */
215
- function invocationFromRow(row) {
216
- return agentInvocationSchema.parse({
217
- actor: row.actor,
218
- ...row.agentName ? { agentName: row.agentName } : void 0,
219
- childConversationId: row.childConversationId,
220
- createdAtMs: row.createdAt.getTime(),
221
- ...row.credentialContext ? { credentialContext: row.credentialContext } : void 0,
222
- destination: row.destination,
223
- ...row.errorMessage !== null ? { errorMessage: row.errorMessage } : void 0,
224
- input: row.input,
225
- invocationId: row.invocationId,
226
- mailboxStatus: row.mailboxStatus,
227
- parentConversationId: row.parentConversationId,
228
- ...row.parentMailboxStatus ? { parentMailboxStatus: row.parentMailboxStatus } : void 0,
229
- ...row.parentToolCallId ? { parentToolCallId: row.parentToolCallId } : void 0,
230
- ...row.agentType ? { agentType: row.agentType } : void 0,
231
- ...row.fork ? { fork: true } : void 0,
232
- ...row.reasoningLevel ? { reasoningLevel: row.reasoningLevel } : void 0,
233
- ...row.result !== null ? { result: row.result } : void 0,
234
- source: row.source,
235
- status: row.status,
236
- ...row.terminalAt ? { terminalAtMs: row.terminalAt.getTime() } : void 0,
237
- ...row.title ? { title: row.title } : void 0,
238
- updatedAtMs: row.updatedAt.getTime()
239
- });
240
- }
241
- /** Read one durable agent invocation. */
242
- async function getAgentInvocation(invocationId) {
243
- const rows = await getSqlExecutor().db().select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.invocationId, invocationId));
244
- return rows[0] ? invocationFromRow(rows[0]) : void 0;
245
- }
246
- /** List the agent invocations of one child Conversation in the given statuses. */
247
- async function listAgentInvocationsForConversation(childConversationId, statuses) {
248
- return (await getSqlExecutor().db().select().from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.childConversationId, childConversationId), inArray(juniorAgentInvocations.status, [...statuses]))).orderBy(asc(juniorAgentInvocations.createdAt))).map(invocationFromRow);
249
- }
250
- /** Resolve the single invocation that may resume for one child conversation. */
251
- async function getActiveAgentInvocationForConversation(childConversationId) {
252
- const active = await listAgentInvocationsForConversation(childConversationId, ACTIVE_AGENT_INVOCATION_STATUSES);
253
- if (active.length > 1) throw new Error(`Child conversation ${childConversationId} has multiple active agent invocations`);
254
- return active[0];
255
- }
256
- /** Read the newest agent invocation of one child Conversation. */
257
- async function getLatestAgentInvocationForConversation(childConversationId) {
258
- const rows = await getSqlExecutor().db().select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, childConversationId)).orderBy(desc(juniorAgentInvocations.createdAt)).limit(1);
259
- return rows[0] ? invocationFromRow(rows[0]) : void 0;
260
- }
261
- /**
262
- * Read the name, agent type, fork flag, and newest task title of one child
263
- * Conversation, for labels. Agent invocations that give a nested result to
264
- * the child have no title, so an agent invocation with a title comes first.
265
- * Each agent invocation keeps the child's agent type, but only the one that
266
- * started a fork has `fork` set, so the flag reads every agent invocation.
267
- */
268
- async function getChildAgentLabel(childConversationId) {
269
- const [row] = await getSqlExecutor().db().select({
270
- agentName: juniorAgentInvocations.agentName,
271
- agentType: juniorAgentInvocations.agentType,
272
- fork: sql`bool_or(${juniorAgentInvocations.fork}) over ()`,
273
- title: juniorAgentInvocations.title
274
- }).from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, childConversationId)).orderBy(sql`${juniorAgentInvocations.title} is null`, desc(juniorAgentInvocations.createdAt)).limit(1);
275
- return row;
276
- }
277
- /**
278
- * List the open agent invocations that run on one Conversation or on its
279
- * child agents, oldest first. Open-work checks read this once and filter it.
280
- */
281
- async function listOpenAgentInvocations(conversationId) {
282
- 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);
283
- }
284
- /**
285
- * Return whether a terminal agent invocation sends its result to the parent.
286
- * A child's final response stays in its Conversation, and a `reply` that
287
- * reached the parent (its id is in `parentInboundMessageIds`) answered for
288
- * the invocation. A failure after that, such as a lost worker before the
289
- * Turn was saved, is not sent either.
290
- */
291
- function sendsResultToParent(invocation, parentInboundMessageIds) {
292
- const replied = parentInboundMessageIds.some((messageId) => isAgentReplyMessageId(messageId, invocation.invocationId));
293
- switch (invocation.status) {
294
- case "completed": return !replied && Boolean(invocation.result?.trim());
295
- case "failed": return !replied;
296
- default: return true;
297
- }
298
- }
299
- /**
300
- * Return whether a child Conversation has work that will start another agent
301
- * invocation on it: another open agent invocation, an open child agent, or a
302
- * child agent result that is sent but still waits in its mailbox.
303
- */
304
- async function hasOpenChildWork(invocation) {
305
- const conversationId = invocation.childConversationId;
306
- if ((await listOpenAgentInvocations(conversationId)).some((row) => row.invocationId !== invocation.invocationId)) return true;
307
- const marked = await getSqlExecutor().db().select({
308
- invocationId: juniorAgentInvocations.invocationId,
309
- parentMailboxStatus: juniorAgentInvocations.parentMailboxStatus,
310
- result: juniorAgentInvocations.result,
311
- status: juniorAgentInvocations.status
312
- }).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, conversationId), inArray(juniorAgentInvocations.parentMailboxStatus, ["pending", "appended"])));
313
- if (marked.length === 0) return false;
314
- const work = await getConversationWorkState({ conversationId });
315
- const unread = new Set(work?.messages.map((message) => message.inboundMessageId));
316
- return marked.some((row) => sendsResultToParent(row, work?.execution.inboundMessageIds ?? []) && (row.parentMailboxStatus === "pending" || unread.has(getAgentInvocationResultMessageId(row.invocationId))));
317
- }
318
- /** List bounded invocation records whose mailbox append still needs repair. */
319
- async function listPendingAgentInvocationMailboxAppends(limit = 100) {
320
- return (await getSqlExecutor().db().select().from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.mailboxStatus, "pending"), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES))).orderBy(asc(juniorAgentInvocations.createdAt)).limit(limit)).map(invocationFromRow);
321
- }
322
- /** List terminal agent invocation results that still need a parent mailbox append. */
323
- async function listPendingAgentInvocationResults(limit = 100) {
324
- return (await getSqlExecutor().db().select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.parentMailboxStatus, "pending")).orderBy(asc(juniorAgentInvocations.terminalAt)).limit(limit)).map(invocationFromRow).filter(isTerminalAgentInvocation);
325
- }
326
- /**
327
- * Send a `replaced` result to the parent now. A stop ended the open work of
328
- * the child, so no later agent invocation sends the report.
329
- */
330
- async function reportReplacedAgentInvocation(invocationId, nowMs = Date.now()) {
331
- await getSqlExecutor().db().update(juniorAgentInvocations).set({
332
- parentMailboxStatus: "pending",
333
- updatedAt: new Date(nowMs)
334
- }).where(and(eq(juniorAgentInvocations.invocationId, invocationId), eq(juniorAgentInvocations.parentMailboxStatus, "replaced")));
335
- return await getAgentInvocation(invocationId);
336
- }
337
- /**
338
- * Send the `replaced` result of a child Conversation when its open child work
339
- * ended and sent it nothing, such as a helper that ended with `noReply`. No
340
- * later agent invocation of the child would send the report. Input from its
341
- * own child agents that still waits in its mailbox starts one, so that one
342
- * reports instead.
343
- */
344
- async function reportReplacedWithoutOpenWork(conversationId, nowMs = Date.now()) {
345
- const latest = await getLatestAgentInvocationForConversation(conversationId);
346
- if (!latest || !isTerminalAgentInvocation(latest) || latest.parentMailboxStatus !== "replaced" || await hasOpenChildWork(latest)) return;
347
- if ((await getConversationWorkState({ conversationId }))?.messages.some(isChildAgentInputMessage)) return;
348
- return await reportReplacedAgentInvocation(latest.invocationId, nowMs);
349
- }
350
- function isChildAgentInputMessage(message) {
351
- const metadata = message.input.metadata;
352
- return isEventMailboxMetadata(metadata) && metadata.event.namespace === "junior";
353
- }
354
- /** Record that one terminal result is in its parent mailbox. */
355
- async function markAgentInvocationParentMailboxAppended(invocationId, nowMs = Date.now()) {
356
- await getSqlExecutor().db().update(juniorAgentInvocations).set({
357
- parentMailboxStatus: "appended",
358
- updatedAt: new Date(nowMs)
359
- }).where(and(eq(juniorAgentInvocations.invocationId, invocationId), eq(juniorAgentInvocations.parentMailboxStatus, "pending")));
360
- }
361
- /** Record that the invocation's idempotent mailbox append completed. */
362
- async function markAgentInvocationMailboxAppended(invocationId, nowMs = Date.now()) {
363
- await getSqlExecutor().db().update(juniorAgentInvocations).set({
364
- mailboxStatus: "appended",
365
- updatedAt: new Date(nowMs)
366
- }).where(eq(juniorAgentInvocations.invocationId, invocationId));
367
- }
368
- /** Mark one non-terminal invocation as actively executing. */
369
- async function markAgentInvocationRunning(invocationId, nowMs = Date.now()) {
370
- await getSqlExecutor().db().update(juniorAgentInvocations).set({
371
- status: "running",
372
- updatedAt: new Date(nowMs)
373
- }).where(and(eq(juniorAgentInvocations.invocationId, invocationId), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES)));
374
- return await getAgentInvocation(invocationId);
375
- }
376
- /** Mark one invocation as waiting for another shared execution slice. */
377
- async function markAgentInvocationPaused(invocationId, nowMs = Date.now()) {
378
- await getSqlExecutor().db().update(juniorAgentInvocations).set({
379
- status: "paused",
380
- updatedAt: new Date(nowMs)
381
- }).where(and(eq(juniorAgentInvocations.invocationId, invocationId), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES)));
382
- }
383
- /**
384
- * Persist one terminal invocation result without overwriting an earlier
385
- * result. The same write marks the result for the parent mailbox. If the
386
- * child still has open work, the result is `replaced`: the parent gets one
387
- * report, from the agent invocation that finishes the child's work.
388
- * `reportNow` sends the result even then, when that open work does not
389
- * continue this task.
390
- */
391
- async function completeAgentInvocation(args) {
392
- const nowMs = args.nowMs ?? Date.now();
393
- const current = await getAgentInvocation(args.invocationId);
394
- if (!current || isTerminalAgentInvocation(current)) return current;
395
- const parentMailboxStatus = !args.reportNow && args.status !== "stopped" && await hasOpenChildWork(current) ? "replaced" : "pending";
396
- await getSqlExecutor().db().update(juniorAgentInvocations).set({
397
- status: args.status,
398
- result: args.status === "completed" ? args.result : null,
399
- errorMessage: args.status === "completed" ? null : args.errorMessage,
400
- parentMailboxStatus,
401
- terminalAt: new Date(nowMs),
402
- updatedAt: new Date(nowMs)
403
- }).where(and(eq(juniorAgentInvocations.invocationId, args.invocationId), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES)));
404
- return await getAgentInvocation(args.invocationId);
405
- }
406
- /**
407
- * End a pending agent invocation whose input the running agent invocation of
408
- * the same child read as a steering message. The running agent invocation
409
- * reports for both, so this one is never sent to the parent.
410
- */
411
- async function markAgentInvocationSteered(invocationId, nowMs = Date.now()) {
412
- await getSqlExecutor().db().update(juniorAgentInvocations).set({
413
- status: "completed",
414
- result: "",
415
- parentMailboxStatus: "steered",
416
- terminalAt: new Date(nowMs),
417
- updatedAt: new Date(nowMs)
418
- }).where(and(eq(juniorAgentInvocations.invocationId, invocationId), eq(juniorAgentInvocations.status, "pending")));
419
- return await getAgentInvocation(invocationId);
420
- }
421
- /** Return whether an agent invocation has finished. */
422
- function isTerminalAgentInvocation(invocation) {
423
- return TERMINAL_AGENT_INVOCATION_STATUSES.includes(invocation.status);
424
- }
425
- /**
426
- * Return whether the newest agent invocation of a child shows a stop. A tree
427
- * stop leaves a `replaced` agent invocation with its finished status and
428
- * marks it `skipped`, so that also means stopped.
429
- */
430
- function isStoppedAgentInvocation(invocation) {
431
- return invocation.status === "stopped" || isTerminalAgentInvocation(invocation) && invocation.parentMailboxStatus === "skipped";
432
- }
433
- // src/chat/conversations/turn-lifecycle.ts
434
- /** Persist correlated turn lifecycle facts with retry-safe terminal exclusion. */
435
- var ConversationTurnLifecycleService = class {
436
- events;
437
- constructor(events) {
438
- this.events = events;
439
- }
440
- /** Record the turn start once after every input message is durable. */
441
- async start(input) {
442
- await this.events.append(input.conversationId, [{
443
- idempotencyKey: `turn:${input.turnId}:started`,
444
- createdAtMs: input.createdAtMs,
445
- data: {
446
- type: "turn_started",
447
- turnId: input.turnId,
448
- inputMessageIds: input.inputMessageIds,
449
- surface: input.surface,
450
- ...input.threadContextThroughSeq === void 0 ? void 0 : { threadContextThroughSeq: input.threadContextThroughSeq }
451
- }
452
- }]);
453
- }
454
- /** Return the input message ids that started a Turn, when it started. */
455
- async loadInputMessageIds(conversationId, turnId) {
456
- const event = await this.events.loadByIdempotencyKey(conversationId, `turn:${turnId}:started`);
457
- return event?.data.type === "turn_started" ? event.data.inputMessageIds : void 0;
458
- }
459
- /** Record a completion that is not a failure once. */
460
- async complete(input) {
461
- await this.events.append(input.conversationId, [{
462
- idempotencyKey: `turn:${input.turnId}:terminal`,
463
- createdAtMs: input.createdAtMs,
464
- data: {
465
- type: "turn_completed",
466
- turnId: input.turnId,
467
- outcome: input.outcome
468
- }
469
- }]);
470
- }
471
- /** Record a classified failure once. Do not store raw error text. */
472
- async fail(input) {
473
- await this.events.append(input.conversationId, [{
474
- idempotencyKey: `turn:${input.turnId}:terminal`,
475
- createdAtMs: input.createdAtMs,
476
- data: {
477
- type: "turn_failed",
478
- turnId: input.turnId,
479
- failureCode: input.failureCode,
480
- ...input.failureReason ? { failureReason: input.failureReason } : void 0,
481
- ...input.eventId ? { eventId: input.eventId } : void 0
482
- }
483
- }]);
484
- }
485
- };
486
- /** Return the Turn lifecycle that records Conversation events. */
487
- function getTurnLifecycle() {
488
- return new ConversationTurnLifecycleService(getConversationEventStore());
489
- }
490
- // src/chat/runtime/turn.ts
491
- /** Classified Slack turn failure carrying the owning Sentry capture outward. */
492
- var ConversationTurnBoundaryError = class extends Error {
493
- eventId;
494
- failureCode;
495
- constructor(args) {
496
- super(args.cause instanceof Error ? args.cause.message : String(args.cause), { cause: args.cause });
497
- this.name = "ConversationTurnBoundaryError";
498
- this.eventId = args.eventId;
499
- this.failureCode = args.failureCode;
500
- }
501
- };
502
- /** Return a classified Slack boundary failure without erasing its cause. */
503
- function getConversationTurnBoundaryError(error) {
504
- return error instanceof ConversationTurnBoundaryError ? error : void 0;
505
- }
506
- /**
507
- * Queue-worker yield routing: respond.ts returns a suspended AgentRunOutcome
508
- * and the Slack executor raises this at the worker boundary so the lease owner
509
- * requeues the conversation.
510
- */
511
- var CooperativeTurnYieldError = class extends Error {
512
- code = "cooperative_turn_yield";
513
- constructor(message = "Agent turn yielded at a safe boundary") {
514
- super(message);
515
- this.name = "CooperativeTurnYieldError";
516
- }
517
- };
518
- function isCooperativeTurnYieldError(error) {
519
- return error instanceof CooperativeTurnYieldError;
520
- }
521
- /** Error indicating durable turn input could not be committed by the worker owner. */
522
- var TurnInputCommitLostError = class extends Error {
523
- code = "turn_input_commit_lost";
524
- constructor(message = "Turn input commit lost its durable owner") {
525
- super(message);
526
- this.name = "TurnInputCommitLostError";
527
- }
528
- };
529
- /** Return whether an error means the durable worker lost input ownership. */
530
- function isTurnInputCommitLostError(error) {
531
- return error instanceof TurnInputCommitLostError;
532
- }
533
- /** Error indicating durable turn input should stay pending for a later worker. */
534
- var TurnInputDeferredError = class extends Error {
535
- code = "turn_input_deferred";
536
- constructor(message = "Turn input is deferred until the active resume ends") {
537
- super(message);
538
- this.name = "TurnInputDeferredError";
539
- }
540
- };
541
- /** Return whether an error means the durable worker should redeliver input later. */
542
- function isTurnInputDeferredError(error) {
543
- return error instanceof TurnInputDeferredError;
544
- }
545
- /** Mark a turn as the active turn in conversation state. */
546
- function startActiveTurn(args) {
547
- args.conversation.processing.activeTurnId = args.nextTurnId;
548
- }
549
- function clearActiveTurn(conversation, sessionId) {
550
- if (!sessionId || conversation.processing.activeTurnId === sessionId) conversation.processing.activeTurnId = void 0;
551
- }
552
- /**
553
- * Close the active turn without marking a Pi session reusable for future
554
- * history. Use this for auth handoffs and recovery replies that end the live
555
- * turn but do not produce a completed Pi session.
556
- */
557
- function markTurnClosed(args) {
558
- clearActiveTurn(args.conversation, args.sessionId);
559
- args.conversation.processing.lastCompletedAtMs = args.nowMs;
560
- }
561
- /**
562
- * Mark a turn as completed after its assistant output has been handled.
563
- */
564
- function markTurnCompleted(args) {
565
- clearActiveTurn(args.conversation, args.sessionId);
566
- args.conversation.processing.lastCompletedAtMs = args.nowMs;
567
- }
568
- /**
569
- * Mark a turn as failed when execution or final user-visible reply delivery
570
- * cannot be completed. If `sessionId` is provided, `activeTurnId` is only
571
- * cleared when it still matches the failing turn.
572
- */
573
- function markTurnFailed(args) {
574
- clearActiveTurn(args.conversation, args.sessionId);
575
- args.conversation.processing.lastCompletedAtMs = args.nowMs;
576
- args.markConversationMessage(args.conversation, args.userMessageId, {
577
- replied: false,
578
- skippedReason: "reply failed"
579
- });
580
- }
581
- // src/chat/runtime/turn-user-message.ts
582
- /** Return the user message for a persisted turn/session, if one exists. */
583
- function getTurnUserMessage(conversation, sessionId) {
584
- for (let index = conversation.messages.length - 1; index >= 0; index -= 1) {
585
- const message = conversation.messages[index];
586
- if (message?.role !== "user") continue;
587
- if (buildDeterministicTurnId(message.id) === sessionId) return message;
588
- }
589
- }
590
- /** Return the persisted user-message id for a turn/session, if one exists. */
591
- function getTurnUserMessageId(conversation, sessionId) {
592
- return getTurnUserMessage(conversation, sessionId)?.id;
593
- }
594
- /** Return the Slack timestamp for the user message that a resumed turn acts on. */
595
- function getTurnUserSlackMessageTs(message) {
596
- return parseSlackMessageTs(message?.meta?.slackTs);
597
- }
598
- /** Rebuild attachment context for a resumed turn from the persisted user message. */
599
- function getTurnUserReplyAttachmentContext(message) {
600
- const inboundAttachmentCount = message?.meta?.attachmentCount ?? 0;
601
- const imageAttachmentCount = message?.meta?.imageAttachmentCount ?? 0;
602
- const imagesHydrated = message?.meta?.imagesHydrated === true;
603
- return {
604
- ...inboundAttachmentCount > 0 ? { inboundAttachmentCount } : void 0,
605
- ...!imagesHydrated && imageAttachmentCount > 0 ? { omittedImageAttachmentCount: imageAttachmentCount } : void 0
606
- };
607
- }
608
- export { getAgentInvocationResultMessageId as $, listAgentInvocationsForConversation as A, reportReplacedWithoutOpenWork as B, getActiveAgentInvocationForConversation as C, invocationFromRow as D, getLatestAgentInvocationForConversation as E, markAgentInvocationParentMailboxAppended as F, agentBindingSchema as G, CHILD_AGENT_KINDS as H, markAgentInvocationPaused as I, getAgentInvocationId as J, agentNameSchema as K, markAgentInvocationRunning as L, listPendingAgentInvocationMailboxAppends as M, listPendingAgentInvocationResults as N, isStoppedAgentInvocation as O, markAgentInvocationMailboxAppended as P, getAgentInvocationMessageId as Q, markAgentInvocationSteered as R, completeAgentInvocation as S, getChildAgentLabel as T, CHILD_AGENT_RESULTS as U, sendsResultToParent as V, PARENT_AGENT_TARGET as W, getAgentInvocationIdForMessage as X, getAgentInvocationIdForEvents as Y, getAgentInvocationIdForResult as Z, ConversationTurnLifecycleService as _, ConversationTurnBoundaryError as a, getUnnamedAgentConversationId as at, NON_TERMINAL_AGENT_INVOCATION_STATUSES as b, TurnInputDeferredError as c, parseAgentReplyMessageId as ct, isTurnInputCommitLostError as d, buildDeterministicTurnId as dt, getAgentInvocationTurnId as et, isTurnInputDeferredError as f, startActiveTurn as g, markTurnFailed as h, getTurnUserSlackMessageTs as i, getTurnReplyKey as it, listOpenAgentInvocations as j, isTerminalAgentInvocation as k, getConversationTurnBoundaryError as l, parseTurnReplyMessageId as lt, markTurnCompleted as m, getTurnUserMessageId as n, getChildAgentLockName as nt, CooperativeTurnYieldError as o, isAgentReplyMessageId as ot, markTurnClosed as p, createAgentInvocationSchema as q, getTurnUserReplyAttachmentContext as r, getNamedAgentConversationId as rt, TurnInputCommitLostError as s, parseAgentInvocationResultMessageId as st, getTurnUserMessage as t, getAgentReplyMessageId as tt, isCooperativeTurnYieldError as u, buildDeterministicAssistantMessageId as ut, getTurnLifecycle as v, getAgentInvocation as w, TERMINAL_AGENT_INVOCATION_STATUSES as x, ACTIVE_AGENT_INVOCATION_STATUSES as y, reportReplacedAgentInvocation as z };