@sentry/junior 0.297.0 → 0.299.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 (94) hide show
  1. package/dist/{actor-6jsm_v96.js → actor-D2iXzvlN.js} +2 -1
  2. package/dist/{state-DFnmLmfn.js → adapter-AgCNqqsG.js} +49 -133
  3. package/dist/{admin-tmGIw4KS.js → admin-1VwEXztm.js} +2 -2
  4. package/dist/{agent-runner-CneTquAE.js → agent-runner-Ciet8_nn.js} +1067 -1353
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +8 -7
  7. package/dist/api.d.ts +1 -1
  8. package/dist/api.js +125 -43
  9. package/dist/{app-BJojZ7HL.d.ts → app--ky-Eu33.d.ts} +6 -4
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +126 -299
  12. package/dist/{automation-BrP6ImrC.js → automation-M3RFJUBf.js} +1 -1
  13. package/dist/{background-compaction-queue-CwfJy3Cd.js → background-compaction-queue-CnimvRdk.js} +4 -4
  14. package/dist/{briefs-uFTuhMqA.js → briefs-CwzvgdCa.js} +4 -4
  15. package/dist/{catalog-runtime-0kuQqYL4.js → catalog-runtime-DaBaHY7u.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-Dj9M_nqB.js → config-CAXIpWQb.js} +80 -6
  24. package/dist/{connections-B96JUM5o.js → connections-Dy0hPdUq.js} +6 -6
  25. package/dist/continue-in-slack-DIOjFj76.js +176 -0
  26. package/dist/{conversation-CvcBU1z2.js → conversation-fCWD9Az3.js} +73 -13
  27. package/dist/{conversation-feed-BSMlGZnS.js → conversation-feed-BPK8vkkZ.js} +88 -3
  28. package/dist/{conversation-privacy-DI29jbZV.js → conversation-privacy-DUgtRkf8.js} +1 -1
  29. package/dist/{conversation-turn-CZWBr091.js → conversation-turn-DkJB6yMF.js} +85 -68
  30. package/dist/{credential-sync-Blhx4_xf.js → credential-sync-RX24Y8aY.js} +18 -18
  31. package/dist/{db-CrtyFRz7.d.ts → db-B07FtU9g.d.ts} +1 -1
  32. package/dist/{db-Br0tfAo7.js → db-COYOGzYS.js} +171 -12
  33. package/dist/{executor-BMPipFVA.js → executor-BWmAgSyi.js} +40 -11
  34. package/dist/{media-BepyEUNm.js → history-IjdmO_r6.js} +1 -85
  35. package/dist/instrumentation.js +2 -2
  36. package/dist/lineage-D-5jm_oj.js +37 -0
  37. package/dist/{logging-CQjlDQYX.js → logging-DPLEa8Bn.js} +1 -1
  38. package/dist/media-BAHvgkok.js +85 -0
  39. package/dist/{message-BOZEIuxy.js → message-BIHR1yRk.js} +9 -10
  40. package/dist/model-input-BPZYH8Nd.js +82 -0
  41. package/dist/nitro.d.ts +1 -1
  42. package/dist/nitro.js +17 -9
  43. package/dist/{oauth-callback-server-V_DuMuNX.js → oauth-callback-server-R7qvSzFG.js} +2 -2
  44. package/dist/{plugins-HYh_JOdw.js → plugins-CBW2Prb_.js} +1 -1
  45. package/dist/{projection-B08mfi0u.js → projection-DEdP1q6f.js} +261 -36
  46. package/dist/{prompt-BlutWLNt.js → prompt-4M98h_tC.js} +4 -4
  47. package/dist/{registry-BDWgCJDf.js → registry-BTKmKM-r.js} +3 -3
  48. package/dist/{resolve-2Z_o_SsI.js → resolve-B8hXNVZ3.js} +3 -3
  49. package/dist/{result-CAujiaci.js → result-g-XAaOj6.js} +158 -69
  50. package/dist/{runner-D2Chc02N.js → runner-BlPSA5A8.js} +9 -9
  51. package/dist/{sandbox-egress-signals-CFoJduFj.js → sandbox-egress-signals-Pai-MzEY.js} +1 -1
  52. package/dist/{schema-Bqa5NbcP.js → schema-BNnY_trV.js} +47 -7
  53. package/dist/{schema-Ce2XCS7O.d.ts → schema-DbuWR-DN.d.ts} +663 -346
  54. package/dist/{service-account-C9kRQEb_.js → service-account-9OLNQMyz.js} +4 -4
  55. package/dist/{service-account-CERfXEVU.js → service-account-BYGZ08DQ.js} +3 -3
  56. package/dist/session-stop-2XJrcNCy.js +3356 -0
  57. package/dist/{skills-B0m1nZ_j.js → skills-DpBQoeHV.js} +3 -3
  58. package/dist/slack-conversation-unfurl-BcDIWo67.js +370 -0
  59. package/dist/spawn-09GssFod.js +73 -0
  60. package/dist/state-Cufq0_rH.js +132 -0
  61. package/dist/{user-input-request-CXNIov9n.js → statuses-B8mUfghF.js} +30 -25
  62. package/dist/{stop-BCH9VNGf.js → stop-U7iUrR1g.js} +6011 -5773
  63. package/dist/{store-B59rOYbS.js → store-BHiaHCQu.js} +24 -4
  64. package/dist/{store-m5bmdmsP.js → store-CSgUTMdv.js} +10 -10
  65. package/dist/{task-queue-N0kuCknH.js → task-queue-bMNq0clp.js} +4 -4
  66. package/dist/{task-runner-COOwR8qm.js → task-runner-B__rxwxU.js} +10 -10
  67. package/dist/{thread-context-Cd44z_W5.js → thread-context-d0ceWbVT.js} +18 -18
  68. package/dist/{turn-session-routing-BlCtVFRN.js → turn-session-routing-BVZHBFCF.js} +5 -5
  69. package/dist/turn-user-message-BEw7acTP.js +355 -0
  70. package/dist/users-BK3dbxZL.js +424 -0
  71. package/dist/{validation-Ba2OcUse.js → validation-BDVJjO2E.js} +1 -1
  72. package/dist/{version-KNDzIAh6.js → version-DQgZoQ3D.js} +1 -1
  73. package/dist/version.js +1 -1
  74. package/dist/{viewer-BPpuN2f9.js → viewer-CAWfFo29.js} +25 -54
  75. package/dist/{warmup-Bskrwmk1.js → warmup-9ySPacF9.js} +1137 -143
  76. package/dist/{worker-B1skZlit.js → worker-D8jJO-WO.js} +8 -7
  77. package/migrations/0104_code_change_draft.sql +1 -0
  78. package/migrations/0105_attachment_uploads.sql +14 -0
  79. package/migrations/0106_conversation_agent_config.sql +1 -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/_journal.json +21 -0
  84. package/package.json +4 -4
  85. package/dist/attempt-selection-ClP3MMPr.js +0 -61
  86. package/dist/locks-D-0h111u.js +0 -48
  87. package/dist/notification-gusCgdQ6.js +0 -1284
  88. package/dist/prompt-input-Dxn8cDC0.js +0 -1424
  89. package/dist/session-stop-B-I1rAS1.js +0 -181
  90. package/dist/spawn-CwMjRRtn.js +0 -80
  91. package/dist/turn-cancel-DDu8TOwt.js +0 -201
  92. package/dist/turn-user-message-ygLG3ylQ.js +0 -641
  93. package/dist/turn-wake-DmQec4AG.js +0 -161
  94. package/dist/{oauth-relay-CsfIazeF.js → oauth-relay-DRzq73b6.js} +1 -1
@@ -1,641 +0,0 @@
1
- import { g as TURN_REASONING_LEVELS } from "./config-Dj9M_nqB.js";
2
- import { h as parseSlackMessageTs } from "./actor-6jsm_v96.js";
3
- import { r as getConversationEventStore, s as getSqlExecutor } from "./db-Br0tfAo7.js";
4
- import { g as juniorAgentInvocations } from "./executor-BMPipFVA.js";
5
- import { p as credentialContextSchema } from "./registry-BDWgCJDf.js";
6
- import { i as isEventMailboxMetadata } from "./notification-gusCgdQ6.js";
7
- import { _ as getConversationWorkState } from "./store-B59rOYbS.js";
8
- import { d as AGENT_INVOCATION_MAILBOX_STATUSES, f as AGENT_INVOCATION_PARENT_MAILBOX_STATUSES } from "./user-input-request-CXNIov9n.js";
9
- import { createHash } from "node:crypto";
10
- import * as z from "zod";
11
- import { and, asc, desc, eq, inArray, or, sql } from "drizzle-orm";
12
- import { actorSchema, destinationSchema, sourceSchema } from "@sentry/junior-plugin-api";
13
- // src/chat/state/turn-id.ts
14
- /** Build a stable turn identifier from a message ID. */
15
- function buildDeterministicTurnId(messageId) {
16
- return `turn_${messageId.replace(/[^a-zA-Z0-9_-]/g, "_")}`;
17
- }
18
- /** Build the stable visible assistant-message identity for one logical turn. */
19
- function buildDeterministicAssistantMessageId(turnId) {
20
- return `${turnId}:assistant:1`;
21
- }
22
- // src/chat/agent-invocations/ids.ts
23
- const CREATE_LOCK_PREFIX = "junior:agent_invocation:create";
24
- /**
25
- * Return the SQL lock that one parent Conversation takes to start, message,
26
- * or stop its child agents.
27
- */
28
- function getChildAgentLockName(parentConversationId) {
29
- return `${CREATE_LOCK_PREFIX}:${parentConversationId}`;
30
- }
31
- function stableId(prefix, ...parts) {
32
- return `${prefix}:${createHash("sha256").update(parts.join("\0")).digest("hex").slice(0, 32)}`;
33
- }
34
- /** Return the stable identity for one retry-safe delegated task. */
35
- function getAgentInvocationId(parentConversationId, idempotencyKey) {
36
- return stableId("agent-invocation", parentConversationId, idempotencyKey);
37
- }
38
- /** Return the stable child identity for one invocation without a named binding. */
39
- function getUnnamedAgentConversationId(invocationId) {
40
- return stableId("agent", invocationId);
41
- }
42
- /** Return the stable child identity for one named binding. */
43
- function getNamedAgentConversationId(parentConversationId, name) {
44
- return stableId("agent", parentConversationId, name);
45
- }
46
- /**
47
- * Return the stable identity of the agent invocation that gives one child
48
- * agent result to the child Conversation that started that child agent.
49
- */
50
- function getAgentInvocationIdForResult(resultInvocationId) {
51
- return stableId("agent-invocation", "result", resultInvocationId);
52
- }
53
- /**
54
- * Return the stable identity of the agent invocation that gives one message
55
- * from a child agent to the child Conversation that started that child agent.
56
- */
57
- function getAgentInvocationIdForMessage(messageId) {
58
- return stableId("agent-invocation", "message", messageId);
59
- }
60
- /**
61
- * Return the stable identity of the agent invocation that gives one batch of
62
- * watch events to a child Conversation. The first message of the batch names
63
- * it.
64
- */
65
- function getAgentInvocationIdForEvents(messageId) {
66
- return stableId("agent-invocation", "events", messageId);
67
- }
68
- /** Return the stable turn identity advanced by one agent invocation. */
69
- function getAgentInvocationTurnId(invocationId) {
70
- return `agent-invocation:${invocationId}`;
71
- }
72
- /** Return the stable mailbox identity for one agent invocation. */
73
- function getAgentInvocationMessageId(invocationId) {
74
- return `agent-invocation:${invocationId}:input`;
75
- }
76
- const REPLY_MESSAGE_PREFIX = "agent-reply:";
77
- /** Return the parent mailbox identity of one child agent `reply` call. */
78
- function getAgentReplyMessageId(invocationId, toolCallId) {
79
- return `${REPLY_MESSAGE_PREFIX}${invocationId}:${toolCallId}`;
80
- }
81
- /**
82
- * Return the key of the `reply` of one Turn on a child's Conversation loop.
83
- * It starts with the Turn id, so the parent can tell that the Turn replied.
84
- */
85
- function getTurnReplyKey(turnId, toolCallId) {
86
- return `${turnId}:${toolCallId}`;
87
- }
88
- const REPLY_MESSAGE_ID = /^agent-reply:(agent-invocation:[0-9a-f]{32}):/;
89
- /** Read the agent invocation identity from one parent `reply` mailbox identity. */
90
- function parseAgentReplyMessageId(messageId) {
91
- return REPLY_MESSAGE_ID.exec(messageId)?.[1];
92
- }
93
- const TURN_REPLY_MESSAGE_ID = /^agent-reply:agent-invocation:[0-9a-f]{32}:(turn_[A-Za-z0-9_-]+)(?::|$)/;
94
- /**
95
- * Read the Turn id from one parent mailbox identity that a Turn on a child's
96
- * Conversation loop sent. A `reply` of an agent invocation has none.
97
- */
98
- function parseTurnReplyMessageId(messageId) {
99
- return TURN_REPLY_MESSAGE_ID.exec(messageId)?.[1];
100
- }
101
- /** Return whether one parent mailbox identity is a `reply` of an agent invocation. */
102
- function isAgentReplyMessageId(messageId, invocationId) {
103
- return messageId.startsWith(`${REPLY_MESSAGE_PREFIX}${invocationId}:`);
104
- }
105
- const RESULT_MESSAGE_PREFIX = "agent-invocation:";
106
- const RESULT_MESSAGE_SUFFIX = ":result";
107
- /** Return the stable parent mailbox identity for one terminal result. */
108
- function getAgentInvocationResultMessageId(invocationId) {
109
- return `${RESULT_MESSAGE_PREFIX}${invocationId}${RESULT_MESSAGE_SUFFIX}`;
110
- }
111
- /** Read the invocation identity from one parent result mailbox identity. */
112
- function parseAgentInvocationResultMessageId(messageId) {
113
- if (!messageId.startsWith(RESULT_MESSAGE_PREFIX) || !messageId.endsWith(RESULT_MESSAGE_SUFFIX)) return;
114
- return messageId.slice(17, -7) || void 0;
115
- }
116
- // src/chat/agent-invocations/agent-types.ts
117
- /**
118
- * Child agent types. A type is plain data: when to pick it and what the child
119
- * reads with its task. Runtime code reads only these fields, never a type
120
- * name, so types can later come from configuration. Types do not limit tools:
121
- * Guardian reviews each child action against the root user's messages, as for
122
- * any child. A child keeps its type for later agent invocations. How a child
123
- * starts, fresh or forked from its parent's history, is not a type: see
124
- * `fork` on the agent invocation.
125
- */
126
- const AGENT_TYPES = ["explore", "reviewer"];
127
- /**
128
- * Stored name of a child agent type. A stored name stays readable after its
129
- * type is removed; the runtime then treats the child as a
130
- * child without a type.
131
- */
132
- const agentTypeSchema = z.string().regex(/^[a-z][a-z0-9_-]*$/);
133
- const AGENT_TYPE_DEFINITIONS = {
134
- explore: {
135
- whenToUse: "Investigation across code, docs, logs, telemetry, or the web. Use it when an answer needs reading across many files or sources and you need the conclusion with evidence, not the raw output.",
136
- instructions: "You are an explore agent. Your job is to investigate and report, so do not change anything outside your sandbox unless the task asks for it. Report what you found with exact evidence, such as paths, lines, links, and ids, and say what you could not verify."
137
- },
138
- reviewer: {
139
- whenToUse: "An independent second opinion on a change, plan, or claim. Give it the evidence to judge, not your conclusion.",
140
- instructions: "You are a reviewer agent. Give an independent assessment. Do not assume that the parent's framing is correct: verify each claim against the evidence. Do not change anything outside your own sandbox. Report concrete problems ranked by severity, each with its evidence, and say clearly when you found none."
141
- }
142
- };
143
- function agentTypeDefinition(type) {
144
- return type && Object.hasOwn(AGENT_TYPE_DEFINITIONS, type) ? AGENT_TYPE_DEFINITIONS[type] : void 0;
145
- }
146
- /** Model-facing list of child agent types. */
147
- function formatAgentTypes() {
148
- return AGENT_TYPES.map((type) => `- "${type}": ${AGENT_TYPE_DEFINITIONS[type].whenToUse}`).join("\n");
149
- }
150
- /** Return the instructions that a child of this type reads with its task. */
151
- function agentTypeInstructions(type) {
152
- return agentTypeDefinition(type)?.instructions;
153
- }
154
- // src/chat/agent-invocations/types.ts
155
- const exactStringSchema = z.string().min(1).refine((value) => value === value.trim());
156
- const agentNameSchema = exactStringSchema.max(64);
157
- /**
158
- * Kind of a new child Conversation. A Thread is a child that people can
159
- * message; a Task is one that only its parent messages.
160
- */
161
- const CHILD_AGENT_KINDS = ["thread", "task"];
162
- /** `messageAgent` target for the parent of a child agent. */
163
- const PARENT_AGENT_TARGET = "parent";
164
- const agentInvocationMailboxStatusSchema = z.enum(AGENT_INVOCATION_MAILBOX_STATUSES);
165
- const agentInvocationParentMailboxStatusSchema = z.enum(AGENT_INVOCATION_PARENT_MAILBOX_STATUSES);
166
- const agentBindingSchema = z.object({
167
- childConversationId: exactStringSchema,
168
- name: agentNameSchema,
169
- parentConversationId: exactStringSchema
170
- }).strict();
171
- const agentInvocationBaseSchema = z.object({
172
- actor: actorSchema,
173
- agentName: agentNameSchema.optional(),
174
- childConversationId: exactStringSchema,
175
- createdAtMs: z.number().finite(),
176
- credentialContext: credentialContextSchema.optional(),
177
- destination: destinationSchema,
178
- input: exactStringSchema,
179
- invocationId: exactStringSchema,
180
- mailboxStatus: agentInvocationMailboxStatusSchema,
181
- parentConversationId: exactStringSchema,
182
- parentToolCallId: exactStringSchema.optional(),
183
- agentType: agentTypeSchema.optional(),
184
- /** The child starts with its parent's history. */
185
- fork: z.literal(true).optional(),
186
- reasoningLevel: z.enum(TURN_REASONING_LEVELS).optional(),
187
- source: sourceSchema,
188
- title: exactStringSchema.optional(),
189
- updatedAtMs: z.number().finite()
190
- }).strict();
191
- const agentInvocationSchema = z.discriminatedUnion("status", [
192
- agentInvocationBaseSchema.extend({ status: z.enum([
193
- "pending",
194
- "running",
195
- "paused"
196
- ]) }),
197
- agentInvocationBaseSchema.extend({
198
- parentMailboxStatus: agentInvocationParentMailboxStatusSchema,
199
- result: z.string(),
200
- status: z.literal("completed"),
201
- terminalAtMs: z.number().finite()
202
- }),
203
- agentInvocationBaseSchema.extend({
204
- errorMessage: z.string(),
205
- parentMailboxStatus: agentInvocationParentMailboxStatusSchema,
206
- status: z.enum([
207
- "blocked",
208
- "failed",
209
- "stopped"
210
- ]),
211
- terminalAtMs: z.number().finite()
212
- })
213
- ]);
214
- const createAgentInvocationSchema = z.object({
215
- actor: actorSchema,
216
- agentName: agentNameSchema.optional(),
217
- credentialContext: credentialContextSchema.optional(),
218
- destination: destinationSchema,
219
- idempotencyKey: exactStringSchema,
220
- input: exactStringSchema,
221
- kind: z.enum(CHILD_AGENT_KINDS).default("task"),
222
- parentConversationId: exactStringSchema,
223
- parentToolCallId: exactStringSchema.optional(),
224
- agentType: agentTypeSchema.optional(),
225
- fork: z.literal(true).optional(),
226
- reasoningLevel: z.enum(TURN_REASONING_LEVELS).optional(),
227
- title: exactStringSchema.optional()
228
- }).strict();
229
- /** How a finished task of a child agent ended. A stop is not a result. */
230
- const CHILD_AGENT_RESULTS = [
231
- "completed",
232
- "blocked",
233
- "failed"
234
- ];
235
- // src/chat/agent-invocations/store.ts
236
- /** Statuses of a finished agent invocation. */
237
- const TERMINAL_AGENT_INVOCATION_STATUSES = [
238
- "blocked",
239
- "completed",
240
- "failed",
241
- "stopped"
242
- ];
243
- /** Statuses of an agent invocation that owns its child's Turn. */
244
- const ACTIVE_AGENT_INVOCATION_STATUSES = ["running", "paused"];
245
- /** Statuses of an agent invocation that has not finished. */
246
- const NON_TERMINAL_AGENT_INVOCATION_STATUSES = [
247
- "pending",
248
- "running",
249
- "paused"
250
- ];
251
- /** Parse one agent invocation row. */
252
- function invocationFromRow(row) {
253
- return agentInvocationSchema.parse({
254
- actor: row.actor,
255
- ...row.agentName ? { agentName: row.agentName } : void 0,
256
- childConversationId: row.childConversationId,
257
- createdAtMs: row.createdAt.getTime(),
258
- ...row.credentialContext ? { credentialContext: row.credentialContext } : void 0,
259
- destination: row.destination,
260
- ...row.errorMessage !== null ? { errorMessage: row.errorMessage } : void 0,
261
- input: row.input,
262
- invocationId: row.invocationId,
263
- mailboxStatus: row.mailboxStatus,
264
- parentConversationId: row.parentConversationId,
265
- ...row.parentMailboxStatus ? { parentMailboxStatus: row.parentMailboxStatus } : void 0,
266
- ...row.parentToolCallId ? { parentToolCallId: row.parentToolCallId } : void 0,
267
- ...row.agentType ? { agentType: row.agentType } : void 0,
268
- ...row.fork ? { fork: true } : void 0,
269
- ...row.reasoningLevel ? { reasoningLevel: row.reasoningLevel } : void 0,
270
- ...row.result !== null ? { result: row.result } : void 0,
271
- source: row.source,
272
- status: row.status,
273
- ...row.terminalAt ? { terminalAtMs: row.terminalAt.getTime() } : void 0,
274
- ...row.title ? { title: row.title } : void 0,
275
- updatedAtMs: row.updatedAt.getTime()
276
- });
277
- }
278
- /** Read one durable agent invocation. */
279
- async function getAgentInvocation(invocationId) {
280
- const rows = await getSqlExecutor().db().select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.invocationId, invocationId));
281
- return rows[0] ? invocationFromRow(rows[0]) : void 0;
282
- }
283
- /** List the agent invocations of one child Conversation in the given statuses. */
284
- async function listAgentInvocationsForConversation(childConversationId, statuses) {
285
- return (await getSqlExecutor().db().select().from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.childConversationId, childConversationId), inArray(juniorAgentInvocations.status, [...statuses]))).orderBy(asc(juniorAgentInvocations.createdAt))).map(invocationFromRow);
286
- }
287
- /** Resolve the single invocation that may resume for one child conversation. */
288
- async function getActiveAgentInvocationForConversation(childConversationId) {
289
- const active = await listAgentInvocationsForConversation(childConversationId, ACTIVE_AGENT_INVOCATION_STATUSES);
290
- if (active.length > 1) throw new Error(`Child conversation ${childConversationId} has multiple active agent invocations`);
291
- return active[0];
292
- }
293
- /** Read the newest agent invocation of one child Conversation. */
294
- async function getLatestAgentInvocationForConversation(childConversationId) {
295
- const rows = await getSqlExecutor().db().select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, childConversationId)).orderBy(desc(juniorAgentInvocations.createdAt)).limit(1);
296
- return rows[0] ? invocationFromRow(rows[0]) : void 0;
297
- }
298
- /**
299
- * Read the name and the newest task title of one child Conversation, for
300
- * labels. Agent invocations that give a nested result to the child have no
301
- * title, so an agent invocation with a title comes first.
302
- */
303
- async function getChildAgentLabel(childConversationId) {
304
- const [row] = await getSqlExecutor().db().select({
305
- agentName: juniorAgentInvocations.agentName,
306
- title: juniorAgentInvocations.title
307
- }).from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, childConversationId)).orderBy(sql`${juniorAgentInvocations.title} is null`, desc(juniorAgentInvocations.createdAt)).limit(1);
308
- return row;
309
- }
310
- /**
311
- * List the open agent invocations that run on one Conversation or on its
312
- * child agents, oldest first. Open-work checks read this once and filter it.
313
- */
314
- async function listOpenAgentInvocations(conversationId) {
315
- 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);
316
- }
317
- /**
318
- * Return whether a terminal agent invocation sends its result to the parent.
319
- * A child's final response stays in its Conversation, and a `reply` that
320
- * reached the parent (its id is in `parentInboundMessageIds`) answered for
321
- * the invocation. A failure after that, such as a lost worker before the
322
- * Turn was saved, is not sent either.
323
- */
324
- function sendsResultToParent(invocation, parentInboundMessageIds) {
325
- const replied = parentInboundMessageIds.some((messageId) => isAgentReplyMessageId(messageId, invocation.invocationId));
326
- switch (invocation.status) {
327
- case "completed": return !replied && Boolean(invocation.result?.trim());
328
- case "failed": return !replied;
329
- default: return true;
330
- }
331
- }
332
- /**
333
- * Return whether a child Conversation has work that will start another agent
334
- * invocation on it: another open agent invocation, an open child agent, or a
335
- * child agent result that is sent but still waits in its mailbox.
336
- */
337
- async function hasOpenChildWork(invocation) {
338
- const conversationId = invocation.childConversationId;
339
- if ((await listOpenAgentInvocations(conversationId)).some((row) => row.invocationId !== invocation.invocationId)) return true;
340
- const marked = await getSqlExecutor().db().select({
341
- invocationId: juniorAgentInvocations.invocationId,
342
- parentMailboxStatus: juniorAgentInvocations.parentMailboxStatus,
343
- result: juniorAgentInvocations.result,
344
- status: juniorAgentInvocations.status
345
- }).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, conversationId), inArray(juniorAgentInvocations.parentMailboxStatus, ["pending", "appended"])));
346
- if (marked.length === 0) return false;
347
- const work = await getConversationWorkState({ conversationId });
348
- const unread = new Set(work?.messages.map((message) => message.inboundMessageId));
349
- return marked.some((row) => sendsResultToParent(row, work?.execution.inboundMessageIds ?? []) && (row.parentMailboxStatus === "pending" || unread.has(getAgentInvocationResultMessageId(row.invocationId))));
350
- }
351
- /** List bounded invocation records whose mailbox append still needs repair. */
352
- async function listPendingAgentInvocationMailboxAppends(limit = 100) {
353
- 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);
354
- }
355
- /** List terminal agent invocation results that still need a parent mailbox append. */
356
- async function listPendingAgentInvocationResults(limit = 100) {
357
- return (await getSqlExecutor().db().select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.parentMailboxStatus, "pending")).orderBy(asc(juniorAgentInvocations.terminalAt)).limit(limit)).map(invocationFromRow).filter(isTerminalAgentInvocation);
358
- }
359
- /**
360
- * Send a `replaced` result to the parent now. A stop ended the open work of
361
- * the child, so no later agent invocation sends the report.
362
- */
363
- async function reportReplacedAgentInvocation(invocationId, nowMs = Date.now()) {
364
- await getSqlExecutor().db().update(juniorAgentInvocations).set({
365
- parentMailboxStatus: "pending",
366
- updatedAt: new Date(nowMs)
367
- }).where(and(eq(juniorAgentInvocations.invocationId, invocationId), eq(juniorAgentInvocations.parentMailboxStatus, "replaced")));
368
- return await getAgentInvocation(invocationId);
369
- }
370
- /**
371
- * Send the `replaced` result of a child Conversation when its open child work
372
- * ended and sent it nothing, such as a helper that ended with `noReply`. No
373
- * later agent invocation of the child would send the report. Input from its
374
- * own child agents that still waits in its mailbox starts one, so that one
375
- * reports instead.
376
- */
377
- async function reportReplacedWithoutOpenWork(conversationId, nowMs = Date.now()) {
378
- const latest = await getLatestAgentInvocationForConversation(conversationId);
379
- if (!latest || !isTerminalAgentInvocation(latest) || latest.parentMailboxStatus !== "replaced" || await hasOpenChildWork(latest)) return;
380
- if ((await getConversationWorkState({ conversationId }))?.messages.some(isChildAgentInputMessage)) return;
381
- return await reportReplacedAgentInvocation(latest.invocationId, nowMs);
382
- }
383
- function isChildAgentInputMessage(message) {
384
- const metadata = message.input.metadata;
385
- return isEventMailboxMetadata(metadata) && metadata.event.namespace === "junior";
386
- }
387
- /** Record that one terminal result is in its parent mailbox. */
388
- async function markAgentInvocationParentMailboxAppended(invocationId, nowMs = Date.now()) {
389
- await getSqlExecutor().db().update(juniorAgentInvocations).set({
390
- parentMailboxStatus: "appended",
391
- updatedAt: new Date(nowMs)
392
- }).where(and(eq(juniorAgentInvocations.invocationId, invocationId), eq(juniorAgentInvocations.parentMailboxStatus, "pending")));
393
- }
394
- /** Record that the invocation's idempotent mailbox append completed. */
395
- async function markAgentInvocationMailboxAppended(invocationId, nowMs = Date.now()) {
396
- await getSqlExecutor().db().update(juniorAgentInvocations).set({
397
- mailboxStatus: "appended",
398
- updatedAt: new Date(nowMs)
399
- }).where(eq(juniorAgentInvocations.invocationId, invocationId));
400
- }
401
- /** Mark one non-terminal invocation as actively executing. */
402
- async function markAgentInvocationRunning(invocationId, nowMs = Date.now()) {
403
- await getSqlExecutor().db().update(juniorAgentInvocations).set({
404
- status: "running",
405
- updatedAt: new Date(nowMs)
406
- }).where(and(eq(juniorAgentInvocations.invocationId, invocationId), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES)));
407
- return await getAgentInvocation(invocationId);
408
- }
409
- /** Mark one invocation as waiting for another shared execution slice. */
410
- async function markAgentInvocationPaused(invocationId, nowMs = Date.now()) {
411
- await getSqlExecutor().db().update(juniorAgentInvocations).set({
412
- status: "paused",
413
- updatedAt: new Date(nowMs)
414
- }).where(and(eq(juniorAgentInvocations.invocationId, invocationId), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES)));
415
- }
416
- /**
417
- * Persist one terminal invocation result without overwriting an earlier
418
- * result. The same write marks the result for the parent mailbox. If the
419
- * child still has open work, the result is `replaced`: the parent gets one
420
- * report, from the agent invocation that finishes the child's work.
421
- * `reportNow` sends the result even then, when that open work does not
422
- * continue this task.
423
- */
424
- async function completeAgentInvocation(args) {
425
- const nowMs = args.nowMs ?? Date.now();
426
- const current = await getAgentInvocation(args.invocationId);
427
- if (!current || isTerminalAgentInvocation(current)) return current;
428
- const parentMailboxStatus = !args.reportNow && args.status !== "stopped" && await hasOpenChildWork(current) ? "replaced" : "pending";
429
- await getSqlExecutor().db().update(juniorAgentInvocations).set({
430
- status: args.status,
431
- result: args.status === "completed" ? args.result : null,
432
- errorMessage: args.status === "completed" ? null : args.errorMessage,
433
- parentMailboxStatus,
434
- terminalAt: new Date(nowMs),
435
- updatedAt: new Date(nowMs)
436
- }).where(and(eq(juniorAgentInvocations.invocationId, args.invocationId), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES)));
437
- return await getAgentInvocation(args.invocationId);
438
- }
439
- /**
440
- * End a pending agent invocation whose input the running agent invocation of
441
- * the same child read as a steering message. The running agent invocation
442
- * reports for both, so this one is never sent to the parent.
443
- */
444
- async function markAgentInvocationSteered(invocationId, nowMs = Date.now()) {
445
- await getSqlExecutor().db().update(juniorAgentInvocations).set({
446
- status: "completed",
447
- result: "",
448
- parentMailboxStatus: "steered",
449
- terminalAt: new Date(nowMs),
450
- updatedAt: new Date(nowMs)
451
- }).where(and(eq(juniorAgentInvocations.invocationId, invocationId), eq(juniorAgentInvocations.status, "pending")));
452
- return await getAgentInvocation(invocationId);
453
- }
454
- /** Return whether an agent invocation has finished. */
455
- function isTerminalAgentInvocation(invocation) {
456
- return TERMINAL_AGENT_INVOCATION_STATUSES.includes(invocation.status);
457
- }
458
- /**
459
- * Return whether the newest agent invocation of a child shows a stop. A tree
460
- * stop leaves a `replaced` agent invocation with its finished status and
461
- * marks it `skipped`, so that also means stopped.
462
- */
463
- function isStoppedAgentInvocation(invocation) {
464
- return invocation.status === "stopped" || isTerminalAgentInvocation(invocation) && invocation.parentMailboxStatus === "skipped";
465
- }
466
- // src/chat/conversations/turn-lifecycle.ts
467
- /** Persist correlated turn lifecycle facts with retry-safe terminal exclusion. */
468
- var ConversationTurnLifecycleService = class {
469
- events;
470
- constructor(events) {
471
- this.events = events;
472
- }
473
- /** Record the turn start once after every input message is durable. */
474
- async start(input) {
475
- await this.events.append(input.conversationId, [{
476
- idempotencyKey: `turn:${input.turnId}:started`,
477
- createdAtMs: input.createdAtMs,
478
- data: {
479
- type: "turn_started",
480
- turnId: input.turnId,
481
- inputMessageIds: input.inputMessageIds,
482
- surface: input.surface,
483
- ...input.threadContextThroughSeq === void 0 ? void 0 : { threadContextThroughSeq: input.threadContextThroughSeq }
484
- }
485
- }]);
486
- }
487
- /** Return the input message ids that started a Turn, when it started. */
488
- async loadInputMessageIds(conversationId, turnId) {
489
- const event = await this.events.loadByIdempotencyKey(conversationId, `turn:${turnId}:started`);
490
- return event?.data.type === "turn_started" ? event.data.inputMessageIds : void 0;
491
- }
492
- /** Record a completion that is not a failure once. */
493
- async complete(input) {
494
- await this.events.append(input.conversationId, [{
495
- idempotencyKey: `turn:${input.turnId}:terminal`,
496
- createdAtMs: input.createdAtMs,
497
- data: {
498
- type: "turn_completed",
499
- turnId: input.turnId,
500
- outcome: input.outcome
501
- }
502
- }]);
503
- }
504
- /** Record a classified failure once. Do not store raw error text. */
505
- async fail(input) {
506
- await this.events.append(input.conversationId, [{
507
- idempotencyKey: `turn:${input.turnId}:terminal`,
508
- createdAtMs: input.createdAtMs,
509
- data: {
510
- type: "turn_failed",
511
- turnId: input.turnId,
512
- failureCode: input.failureCode,
513
- ...input.failureReason ? { failureReason: input.failureReason } : void 0,
514
- ...input.eventId ? { eventId: input.eventId } : void 0
515
- }
516
- }]);
517
- }
518
- };
519
- /** Return the Turn lifecycle that records Conversation events. */
520
- function getTurnLifecycle() {
521
- return new ConversationTurnLifecycleService(getConversationEventStore());
522
- }
523
- // src/chat/runtime/turn.ts
524
- /** Classified Slack turn failure carrying the owning Sentry capture outward. */
525
- var ConversationTurnBoundaryError = class extends Error {
526
- eventId;
527
- failureCode;
528
- constructor(args) {
529
- super(args.cause instanceof Error ? args.cause.message : String(args.cause), { cause: args.cause });
530
- this.name = "ConversationTurnBoundaryError";
531
- this.eventId = args.eventId;
532
- this.failureCode = args.failureCode;
533
- }
534
- };
535
- /** Return a classified Slack boundary failure without erasing its cause. */
536
- function getConversationTurnBoundaryError(error) {
537
- return error instanceof ConversationTurnBoundaryError ? error : void 0;
538
- }
539
- /**
540
- * Queue-worker yield routing: respond.ts returns a suspended AgentRunOutcome
541
- * and the Slack executor raises this at the worker boundary so the lease owner
542
- * requeues the conversation.
543
- */
544
- var CooperativeTurnYieldError = class extends Error {
545
- code = "cooperative_turn_yield";
546
- constructor(message = "Agent turn yielded at a safe boundary") {
547
- super(message);
548
- this.name = "CooperativeTurnYieldError";
549
- }
550
- };
551
- function isCooperativeTurnYieldError(error) {
552
- return error instanceof CooperativeTurnYieldError;
553
- }
554
- /** Error indicating durable turn input could not be committed by the worker owner. */
555
- var TurnInputCommitLostError = class extends Error {
556
- code = "turn_input_commit_lost";
557
- constructor(message = "Turn input commit lost its durable owner") {
558
- super(message);
559
- this.name = "TurnInputCommitLostError";
560
- }
561
- };
562
- /** Return whether an error means the durable worker lost input ownership. */
563
- function isTurnInputCommitLostError(error) {
564
- return error instanceof TurnInputCommitLostError;
565
- }
566
- /** Error indicating durable turn input should stay pending for a later worker. */
567
- var TurnInputDeferredError = class extends Error {
568
- code = "turn_input_deferred";
569
- constructor(message = "Turn input is deferred until the active resume ends") {
570
- super(message);
571
- this.name = "TurnInputDeferredError";
572
- }
573
- };
574
- /** Return whether an error means the durable worker should redeliver input later. */
575
- function isTurnInputDeferredError(error) {
576
- return error instanceof TurnInputDeferredError;
577
- }
578
- /** Mark a turn as the active turn in conversation state. */
579
- function startActiveTurn(args) {
580
- args.conversation.processing.activeTurnId = args.nextTurnId;
581
- }
582
- function clearActiveTurn(conversation, sessionId) {
583
- if (!sessionId || conversation.processing.activeTurnId === sessionId) conversation.processing.activeTurnId = void 0;
584
- }
585
- /**
586
- * Close the active turn without marking a Pi session reusable for future
587
- * history. Use this for auth handoffs and recovery replies that end the live
588
- * turn but do not produce a completed Pi session.
589
- */
590
- function markTurnClosed(args) {
591
- clearActiveTurn(args.conversation, args.sessionId);
592
- args.conversation.processing.lastCompletedAtMs = args.nowMs;
593
- }
594
- /**
595
- * Mark a turn as completed after its assistant output has been handled.
596
- */
597
- function markTurnCompleted(args) {
598
- clearActiveTurn(args.conversation, args.sessionId);
599
- args.conversation.processing.lastCompletedAtMs = args.nowMs;
600
- }
601
- /**
602
- * Mark a turn as failed when execution or final user-visible reply delivery
603
- * cannot be completed. If `sessionId` is provided, `activeTurnId` is only
604
- * cleared when it still matches the failing turn.
605
- */
606
- function markTurnFailed(args) {
607
- clearActiveTurn(args.conversation, args.sessionId);
608
- args.conversation.processing.lastCompletedAtMs = args.nowMs;
609
- args.markConversationMessage(args.conversation, args.userMessageId, {
610
- replied: false,
611
- skippedReason: "reply failed"
612
- });
613
- }
614
- // src/chat/runtime/turn-user-message.ts
615
- /** Return the user message for a persisted turn/session, if one exists. */
616
- function getTurnUserMessage(conversation, sessionId) {
617
- for (let index = conversation.messages.length - 1; index >= 0; index -= 1) {
618
- const message = conversation.messages[index];
619
- if (message?.role !== "user") continue;
620
- if (buildDeterministicTurnId(message.id) === sessionId) return message;
621
- }
622
- }
623
- /** Return the persisted user-message id for a turn/session, if one exists. */
624
- function getTurnUserMessageId(conversation, sessionId) {
625
- return getTurnUserMessage(conversation, sessionId)?.id;
626
- }
627
- /** Return the Slack timestamp for the user message that a resumed turn acts on. */
628
- function getTurnUserSlackMessageTs(message) {
629
- return parseSlackMessageTs(message?.meta?.slackTs);
630
- }
631
- /** Rebuild attachment context for a resumed turn from the persisted user message. */
632
- function getTurnUserReplyAttachmentContext(message) {
633
- const inboundAttachmentCount = message?.meta?.attachmentCount ?? 0;
634
- const imageAttachmentCount = message?.meta?.imageAttachmentCount ?? 0;
635
- const imagesHydrated = message?.meta?.imagesHydrated === true;
636
- return {
637
- ...inboundAttachmentCount > 0 ? { inboundAttachmentCount } : void 0,
638
- ...!imagesHydrated && imageAttachmentCount > 0 ? { omittedImageAttachmentCount: imageAttachmentCount } : void 0
639
- };
640
- }
641
- export { getAgentInvocationIdForMessage 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, AGENT_TYPES as J, agentNameSchema as K, markAgentInvocationRunning as L, listPendingAgentInvocationMailboxAppends as M, listPendingAgentInvocationResults as N, isStoppedAgentInvocation as O, markAgentInvocationMailboxAppended as P, getAgentInvocationIdForEvents as Q, markAgentInvocationSteered as R, completeAgentInvocation as S, getChildAgentLabel as T, CHILD_AGENT_RESULTS as U, sendsResultToParent as V, PARENT_AGENT_TARGET as W, formatAgentTypes as X, agentTypeInstructions as Y, getAgentInvocationId as Z, ConversationTurnLifecycleService as _, ConversationTurnBoundaryError as a, getChildAgentLockName as at, NON_TERMINAL_AGENT_INVOCATION_STATUSES as b, TurnInputDeferredError as c, getUnnamedAgentConversationId as ct, isTurnInputCommitLostError as d, parseAgentReplyMessageId as dt, getAgentInvocationIdForResult as et, isTurnInputDeferredError as f, parseTurnReplyMessageId as ft, startActiveTurn as g, markTurnFailed as h, getTurnUserSlackMessageTs as i, getAgentReplyMessageId as it, listOpenAgentInvocations as j, isTerminalAgentInvocation as k, getConversationTurnBoundaryError as l, isAgentReplyMessageId as lt, markTurnCompleted as m, buildDeterministicTurnId as mt, getTurnUserMessageId as n, getAgentInvocationResultMessageId as nt, CooperativeTurnYieldError as o, getNamedAgentConversationId as ot, markTurnClosed as p, buildDeterministicAssistantMessageId as pt, createAgentInvocationSchema as q, getTurnUserReplyAttachmentContext as r, getAgentInvocationTurnId as rt, TurnInputCommitLostError as s, getTurnReplyKey as st, getTurnUserMessage as t, getAgentInvocationMessageId as tt, isCooperativeTurnYieldError as u, parseAgentInvocationResultMessageId as ut, getTurnLifecycle as v, getAgentInvocation as w, TERMINAL_AGENT_INVOCATION_STATUSES as x, ACTIVE_AGENT_INVOCATION_STATUSES as y, reportReplacedAgentInvocation as z };