@sentry/junior 0.309.0 → 0.311.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 (117) hide show
  1. package/dist/adapter-B1wujchl.js +259 -0
  2. package/dist/{adapter-context-1YUbMpD3.js → adapter-context-G2M0y6rP.js} +2 -2
  3. package/dist/{admin-u30A8TcD.js → admin-DCiBhUT1.js} +1 -2
  4. package/dist/{agent-runner-sJLhgPQV.js → agent-runner-BVHPUIc8.js} +695 -1817
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +8 -7
  7. package/dist/api.d.ts +21 -3
  8. package/dist/api.js +1479 -372
  9. package/dist/{app-B_7Wn0en.d.ts → app-Cw5Vy6H6.d.ts} +14 -3
  10. package/dist/app.d.ts +2 -2
  11. package/dist/app.js +233 -506
  12. package/dist/{background-compaction-queue-CUJXVKG3.js → background-compaction-queue-CJDnWVOJ.js} +4 -4
  13. package/dist/{briefs-BHi70IR5.js → briefs-BDjnug6Y.js} +3 -3
  14. package/dist/{catalog-runtime-Chc_IP2o.js → catalog-runtime-DMY3VV-D.js} +1 -1
  15. package/dist/cli/chat.js +16 -16
  16. package/dist/cli/check.js +23 -29
  17. package/dist/cli/init.js +1 -6
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +8 -7
  20. package/dist/cli/snapshot-create.js +5 -5
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +3 -3
  23. package/dist/{config-BIyIdTtA.js → config-BrXDQefC.js} +239 -5
  24. package/dist/{continue-in-slack-BQJBfiQh.js → continue-in-slack-DNXSC9So.js} +6 -5
  25. package/dist/{conversation-CzrLhdHG.js → conversation-ca__NDQW.js} +48 -9
  26. package/dist/{conversation-feed-B9e3_gxz.js → conversation-feed-DkinDu5o.js} +15 -6
  27. package/dist/{conversation-privacy-CkTW29hd.js → conversation-privacy-DxttrKb9.js} +1 -1
  28. package/dist/{conversation-turn-CZaYQUum.js → conversation-turn-DWw7Xhdr.js} +42 -39
  29. package/dist/{credential-sync-58m_CyIJ.js → credential-sync-Bk8wGb8Y.js} +15 -16
  30. package/dist/{db-B4Hjxr-u.d.ts → db-7ETESH44.d.ts} +3 -1
  31. package/dist/{db-CFUpEZi9.js → db-DTxzH7u5.js} +1618 -1041
  32. package/dist/{executor-DXL0O0MV.js → executor-DqTiYj9S.js} +454 -96
  33. package/dist/{history-N7IVbUom.js → history-CYstOMKX.js} +6 -0
  34. package/dist/{html-CaBu2VbT.js → html-B9Sl4Axb.js} +6 -6
  35. package/dist/{install-DhTBUUov.js → install-Sg4ePfLl.js} +2 -2
  36. package/dist/instrumentation.js +3 -3
  37. package/dist/{lineage-CxtOI2_p.js → lineage-BHAMpNKr.js} +2 -2
  38. package/dist/{logging-BNUovdcX.js → logging-FjclQsXu.js} +47 -9
  39. package/dist/{message-DcUsS2vg.js → message-CJ7_RL50.js} +5 -8
  40. package/dist/{model-input-o3rEqgwM.js → model-input-CMLh4Cwq.js} +3 -3
  41. package/dist/nitro.d.ts +1 -1
  42. package/dist/nitro.js +3 -3
  43. package/dist/{oauth-callback-server-1Fizd1EM.js → oauth-callback-server-RVcbiDjL.js} +2 -2
  44. package/dist/{oauth-relay-DOwngqdM.js → oauth-relay-Bu9kkaQu.js} +1 -1
  45. package/dist/{projection-Ce4pmhKP.js → projection-Cns7XwWa.js} +9206 -5318
  46. package/dist/{prompt-DEqjDVMs.js → prompt-CDqcsDYC.js} +4 -4
  47. package/dist/{registry-CNE4ZBnG.js → registry-BPwuOP2O.js} +5 -8
  48. package/dist/{resolve-qbPg-aC-.js → resolve-BK29bBry.js} +3 -3
  49. package/dist/rule-DAxQY-1h.js +20 -0
  50. package/dist/{runner-eGIxpAMf.js → runner-BcAE-cJm.js} +10 -10
  51. package/dist/{sandbox-egress-signals-DMFB1kCp.js → sandbox-egress-signals-C-q0go5b.js} +1 -1
  52. package/dist/{schedule-Cire6NU7.js → schedule-BLJ476XQ.js} +209 -43
  53. package/dist/{schema-CfIey9Ao.js → schema-BLgSZXcL.js} +255 -49
  54. package/dist/{schema-DriSvB40.d.ts → schema-DYcJeV7d.d.ts} +701 -62
  55. package/dist/{service-account-Cw_LWZ4-.js → service-account-gN0zqf0S.js} +68 -68
  56. package/dist/{service-account-B1VXCTqg.js → service-account-iJoCtkHR.js} +3 -3
  57. package/dist/{skills-Zg8-vrje.js → skills-BoZ80epJ.js} +77 -31
  58. package/dist/{slack-conversation-unfurl-DA51qH0c.js → slack-conversation-unfurl-CogYrITA.js} +8 -10
  59. package/dist/{spawn-DBi4-zD8.js → spawn-Dk92r7mX.js} +5 -6
  60. package/dist/{state-C-Ftk23K.js → state-DH3Cmgp3.js} +4 -4
  61. package/dist/{stop-D9xideLM.js → stop-CYsfc0Ed.js} +1064 -314
  62. package/dist/{store-BjIXA0Al.js → store-DmmMIrQi.js} +5 -5
  63. package/dist/{task-queue-D0_qbnpo.js → task-queue-C_zldF5J.js} +3 -3
  64. package/dist/{task-runner-DQMq4XY0.js → task-runner-C7oCJQIx.js} +21 -14
  65. package/dist/{thread-context-D0i1e-5O.js → thread-context-BW2BsQbH.js} +13 -11
  66. package/dist/{turn-session-routing-C0l68I_O.js → turn-session-routing-Xh_2nSQe.js} +52 -54
  67. package/dist/{validation-CRbvRPvu.js → validation-DrJd0nnq.js} +1 -1
  68. package/dist/{version-BYdVs12p.js → version-CNKZ8owc.js} +1 -1
  69. package/dist/version.js +1 -1
  70. package/dist/{warmup-DN9OHN1-.js → warmup-BWdHew2H.js} +14289 -7197
  71. package/dist/{web-message-id-BT8Mg8LL.js → web-message-id-Ch5dPq-a.js} +32 -144
  72. package/dist/{worker-C9ZfJXmV.js → worker-t9qpu_Zx.js} +7 -8
  73. package/migrations/0124_artifact_visibility.sql +9 -0
  74. package/migrations/0125_artifact_public_sha_index.sql +1 -0
  75. package/migrations/0126_artifact_drop_public.sql +8 -0
  76. package/migrations/0127_artifact_path.sql +4 -0
  77. package/migrations/0128_artifact_path_index.sql +1 -0
  78. package/migrations/0129_review_item_answered_index.sql +1 -0
  79. package/migrations/0130_review_item_status_index.sql +1 -0
  80. package/migrations/0131_brief_outcome_status.sql +1 -0
  81. package/migrations/0132_brief_outcome_status_backfill.sql +7 -0
  82. package/migrations/0133_brief_created_at_index.sql +1 -0
  83. package/migrations/0134_slack_person_search_index.sql +1 -0
  84. package/migrations/0135_code_change_size.sql +3 -0
  85. package/migrations/0136_merge_conflict_notice_dismiss.sql +16 -0
  86. package/migrations/0137_inbox_snoozes.sql +27 -0
  87. package/migrations/0138_code_change_search_index.sql +2 -0
  88. package/migrations/0139_review_item_owner.sql +22 -0
  89. package/migrations/0140_review_item_owner_index.sql +1 -0
  90. package/migrations/0141_memory_core_adoption.sql +89 -0
  91. package/migrations/0142_memory_core_indexes.sql +17 -0
  92. package/migrations/meta/0124_snapshot.json +5516 -0
  93. package/migrations/meta/0125_snapshot.json +5516 -0
  94. package/migrations/meta/0126_snapshot.json +5488 -0
  95. package/migrations/meta/0127_snapshot.json +5519 -0
  96. package/migrations/meta/0128_snapshot.json +5519 -0
  97. package/migrations/meta/0129_snapshot.json +5547 -0
  98. package/migrations/meta/0130_snapshot.json +5563 -0
  99. package/migrations/meta/0131_snapshot.json +5569 -0
  100. package/migrations/meta/0132_snapshot.json +5569 -0
  101. package/migrations/meta/0133_snapshot.json +5590 -0
  102. package/migrations/meta/0134_snapshot.json +5606 -0
  103. package/migrations/meta/0135_snapshot.json +5624 -0
  104. package/migrations/meta/0136_snapshot.json +5624 -0
  105. package/migrations/meta/0137_snapshot.json +5864 -0
  106. package/migrations/meta/0138_snapshot.json +5894 -0
  107. package/migrations/meta/0139_snapshot.json +5898 -0
  108. package/migrations/meta/0140_snapshot.json +5919 -0
  109. package/migrations/meta/0141_snapshot.json +6429 -0
  110. package/migrations/meta/0142_snapshot.json +6457 -0
  111. package/migrations/meta/_journal.json +134 -1
  112. package/package.json +6 -7
  113. package/dist/result-ZGnDzcsb.js +0 -548
  114. package/dist/session-stop-P2XdTiwr.js +0 -4252
  115. package/dist/turn-user-message-nBVvOXjs.js +0 -364
  116. package/dist/users-DdjMjbmM.js +0 -181
  117. package/dist/viewer-DudYrQGj.js +0 -212
@@ -1,548 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { t as mapBounded } from "./fan-out-Cod-yEHG.js";
3
- import { P as SYSTEM_IDENTITY_ID, a as getConversationStore, k as turnBehavior } from "./db-CFUpEZi9.js";
4
- import { A as parseEventMessages, B as renderEventBatchInputs, D as getEventBatchDelayMs, F as EVENT_WAIT_MS, R as eventBatchMessageMeta, V as timerWatchCredentialSubject, j as resolveMailboxTurnWork, k as listActiveMailboxTurns, s as eventReviewItemInputs, t as getConversationStoppedAtMs } from "./session-stop-P2XdTiwr.js";
5
- import { a as EVENT_SYSTEM_ACTOR } from "./prompt-DEqjDVMs.js";
6
- import { p as credentialContextForActor } from "./registry-CNE4ZBnG.js";
7
- import { C as ownAgentInvocation, D as getAgentInvocationIdForEvents, I as getTurnReplyKey, M as getAgentInvocationTurnId, N as getAgentReplyMessageId, O as getAgentInvocationIdForMessage, S as listChildMessages, b as hasAgentInvocationReply, j as getAgentInvocationResultMessageId, k as getAgentInvocationIdForResult, y as childMessageSenderMetadata, z as buildDeterministicTurnId } from "./turn-user-message-nBVvOXjs.js";
8
- import { _ as getConversationWorkState, r as appendAndEnqueueInboundMessage } from "./store-BjIXA0Al.js";
9
- import { $t as getChildAgentInputSender, Bt as TERMINAL_AGENT_INVOCATION_STATUSES, Gt as isTerminalAgentInvocation, Kt as listAgentInvocationsForConversation, Qt as childAgentInput, Rt as listUnreportedSiblingAgents, Wt as getLatestAgentInvocationForConversation, Xt as reportReplacedWithoutOpenWork, Yt as markAgentInvocationParentMailboxAppended, Zt as sendsResultToParent, an as parentMessageText, bn as createAgentInvocationFromLatest, dn as enqueueAgentInvocation, en as readChildConversationSender, fn as resolveAgentInvocationId, in as logDroppedParentMessage, ln as endActiveAgentInvocations, on as readParentMessage, sn as createAgentInvocationWorker, tn as routeChildInput, un as endAgentInvocationsOfStoppedWork, zt as NON_TERMINAL_AGENT_INVOCATION_STATUSES } from "./warmup-DN9OHN1-.js";
10
- import { J as renderUntrustedTag } from "./config-BIyIdTtA.js";
11
- import { C as AGENT_MESSAGE_EVENT_TYPE, E as agentInvocationResultEventType, S as AGENT_INVOCATION_EVENT_NAMESPACE, T as AGENT_REPLY_EVENT_TYPE } from "./web-message-id-BT8Mg8LL.js";
12
- import { actorSchema } from "@sentry/junior-plugin-api";
13
- // src/chat/agent-invocations/result.ts
14
- var result_exports = /* @__PURE__ */ __exportAll({
15
- createChildConversationWorker: () => createChildConversationWorker,
16
- createDeliverToParent: () => createDeliverToParent
17
- });
18
- const AGENT_INVOCATION_RESULT_MAX_LENGTH = 12e3;
19
- /**
20
- * Return the Inbound message author id for results sent by one Actor.
21
- * `selectContiguousTurnBatch` in `task-execution/worker.ts` puts messages in
22
- * one attempt only when their author ids and sources match. Mid-Turn drains
23
- * take only `interrupt` messages, and results are `defer`. So results never
24
- * share a Turn and its credentials with another Actor or with watch Events.
25
- * Keep this id unique per Actor if either rule changes.
26
- */
27
- function resultAuthorId(actor) {
28
- switch (actor.platform) {
29
- case "system": return `agent-invocation:system:${actor.name}`;
30
- case "slack": return `agent-invocation:slack:${actor.teamId}:${actor.userId}`;
31
- default: return `agent-invocation:${actor.platform}:${actor.userId}`;
32
- }
33
- }
34
- /**
35
- * Error messages can contain text from tools or providers, so the trusted
36
- * summary in the mailbox metadata has only the status.
37
- */
38
- function trustedSummary(invocation, agent) {
39
- switch (invocation.status) {
40
- case "completed": return `${agent} finished its task.`;
41
- case "blocked": return `${agent} is blocked.`;
42
- case "failed": return `${agent} failed.`;
43
- case "stopped": return `${agent} was stopped.`;
44
- }
45
- }
46
- /**
47
- * Render the parent agent input for one child agent result as one
48
- * `<agent-result>`. A child agent wrote the output, so it is escaped data.
49
- * `status` and `waiting_on` are runtime facts. The system prompt says what to
50
- * do for each status, so the input repeats no guidance.
51
- */
52
- function renderResultInput(sender, result, openSiblings) {
53
- const output = result.output.trim().slice(0, AGENT_INVOCATION_RESULT_MAX_LENGTH);
54
- return renderUntrustedTag("agent-result", {
55
- conversation_id: sender.childConversationId,
56
- name: sender.agentName,
57
- source: "child_agent",
58
- status: result.status,
59
- title: sender.title,
60
- waiting_on: openSiblings.length ? openSiblings.map(siblingLabel).join(", ") : void 0
61
- }, "A child agent that you started", output || "(empty)");
62
- }
63
- function siblingLabel(sibling) {
64
- return sibling.agentName ?? sibling.title ?? sibling.childConversationId;
65
- }
66
- /**
67
- * Render one `<agent-result>` under the parent's mailbox lock. `waiting_on`
68
- * then sees every `reply` that reached the parent, also one that a sibling
69
- * sent at the same moment, so two siblings cannot each name the other.
70
- */
71
- function renderResultUnderLock(sender, result) {
72
- return async (parentInboundMessageIds, messageSenders) => renderResultInput(sender, result, await listUnreportedSiblingAgents(sender.parentConversationId, sender.childConversationId, await listChildMessages(parentInboundMessageIds, messageSenders)));
73
- }
74
- function terminalResult(invocation) {
75
- return {
76
- output: invocation.status === "completed" ? invocation.result : invocation.errorMessage,
77
- status: invocation.status
78
- };
79
- }
80
- /**
81
- * Build the parent Inbound message for one terminal agent invocation. Its
82
- * text names no siblings: `renderResultUnderLock` adds `waiting_on`.
83
- */
84
- function buildResultInboundMessage(invocation, nowMs) {
85
- const summary = trustedSummary(invocation, childAgentLabel(invocation));
86
- const metadata = {
87
- kind: "event",
88
- event: {
89
- eventKey: invocation.invocationId,
90
- eventType: agentInvocationResultEventType(invocation.status),
91
- identifier: invocation.invocationId,
92
- namespace: AGENT_INVOCATION_EVENT_NAMESPACE,
93
- trustedSummary: summary
94
- },
95
- ...childMessageSenderMetadata({
96
- agentInvocationId: invocation.invocationId,
97
- conversationId: invocation.childConversationId,
98
- turnId: getAgentInvocationTurnId(invocation.invocationId)
99
- })
100
- };
101
- return {
102
- conversationId: invocation.parentConversationId,
103
- createdAtMs: invocation.terminalAtMs,
104
- delivery: "defer",
105
- inboundMessageId: getAgentInvocationResultMessageId(invocation.invocationId),
106
- input: {
107
- authorId: resultAuthorId(invocation.actor),
108
- authorIdentityId: SYSTEM_IDENTITY_ID,
109
- metadata,
110
- text: renderResultInput(invocation, terminalResult(invocation), [])
111
- },
112
- receivedAtMs: nowMs,
113
- source: "event"
114
- };
115
- }
116
- /**
117
- * Append one terminal agent invocation result to the parent mailbox and wake
118
- * the parent. Repeat calls are safe.
119
- *
120
- * Results do not go through `admitAutomatedTurn`, so the automated-turn limit
121
- * never drops them. Result Turns still count toward that limit.
122
- * TODO(dcramer): Add a per-parent total invocation limit as the loop guard
123
- * for spawn -> result -> spawn chains (#881).
124
- */
125
- async function enqueueAgentInvocationResult(invocation, options) {
126
- if (invocation.parentMailboxStatus !== "pending") return;
127
- const nowMs = options.nowMs ?? Date.now();
128
- const parentMessages = await readParentChildMessages(invocation.parentConversationId, options.state);
129
- if (!sendsResultToParent(invocation, parentMessages)) {
130
- await markAgentInvocationParentMailboxAppended(invocation.invocationId, nowMs);
131
- const replaced = hasAgentInvocationReply(parentMessages, invocation.invocationId) ? void 0 : await reportReplacedWithoutOpenWork(invocation.parentConversationId, nowMs);
132
- if (replaced && isTerminalAgentInvocation(replaced)) await enqueueAgentInvocationResult(replaced, options);
133
- return;
134
- }
135
- await appendAndEnqueueInboundMessage({
136
- message: buildResultInboundMessage(invocation, nowMs),
137
- renderText: renderResultUnderLock(invocation, terminalResult(invocation)),
138
- queue: options.queue,
139
- queueDelayMs: EVENT_WAIT_MS,
140
- state: options.state
141
- });
142
- await markAgentInvocationParentMailboxAppended(invocation.invocationId, nowMs);
143
- }
144
- /**
145
- * Read every child reply and result that reached the parent's mailbox. A
146
- * sibling whose `reply` is among them has answered.
147
- */
148
- async function readParentChildMessages(parentConversationId, state) {
149
- const work = await getConversationWorkState({
150
- conversationId: parentConversationId,
151
- state
152
- });
153
- return await listChildMessages(work?.execution.inboundMessageIds ?? [], work?.execution.messageSenders ?? {});
154
- }
155
- function childAgentLabel(sender) {
156
- return sender.agentName ? `Child agent "${sender.agentName}"` : "Child agent";
157
- }
158
- /**
159
- * Mailbox metadata of a reply or message from a child that no Agent
160
- * invocation names. It carries the Actor of the child's Turn, so the parent
161
- * runs with no more authority than that Turn. The author id must match it.
162
- */
163
- function senderEventMetadata(sender, actor, event) {
164
- return sender.invocationId ? {
165
- kind: "event",
166
- event
167
- } : {
168
- kind: "event",
169
- event,
170
- actor
171
- };
172
- }
173
- /** Read the Actor that a reply or message from a child without an Agent invocation carries. */
174
- function senderActorFromMetadata(metadata) {
175
- const actor = metadata?.actor;
176
- const parsed = actorSchema.safeParse(actor);
177
- return parsed.success ? parsed.data : void 0;
178
- }
179
- function renderMessageInput(sender, text) {
180
- return renderUntrustedTag("agent-message", {
181
- conversation_id: sender.childConversationId,
182
- name: sender.agentName,
183
- source: "child_agent",
184
- title: sender.title
185
- }, "A child agent that you started", text.trim());
186
- }
187
- /**
188
- * Append one message from a child agent to its parent mailbox and wake the
189
- * parent. `sender` names the child, and `actor` is the Actor of the child's
190
- * Turn. The parent handles the message like a result. Repeat calls with the
191
- * same `messageKey` are safe.
192
- */
193
- async function enqueueAgentMessageToParent(args) {
194
- const nowMs = args.nowMs ?? Date.now();
195
- const senderId = args.sender.invocationId ?? args.sender.childConversationId;
196
- const inboundMessageId = `agent-invocation:${senderId}:message:${args.messageKey}`;
197
- const summary = `${childAgentLabel(args.sender)} sent a message.`;
198
- const metadata = senderEventMetadata(args.sender, args.actor, {
199
- eventKey: inboundMessageId,
200
- eventType: AGENT_MESSAGE_EVENT_TYPE,
201
- identifier: senderId,
202
- namespace: AGENT_INVOCATION_EVENT_NAMESPACE,
203
- trustedSummary: summary
204
- });
205
- await appendAndEnqueueInboundMessage({
206
- message: {
207
- conversationId: args.sender.parentConversationId,
208
- createdAtMs: nowMs,
209
- delivery: "defer",
210
- inboundMessageId,
211
- input: {
212
- authorId: resultAuthorId(args.actor),
213
- authorIdentityId: SYSTEM_IDENTITY_ID,
214
- metadata,
215
- text: renderMessageInput(args.sender, args.text)
216
- },
217
- receivedAtMs: nowMs,
218
- source: "event"
219
- },
220
- queue: args.queue,
221
- queueDelayMs: EVENT_WAIT_MS,
222
- state: args.state
223
- });
224
- }
225
- const RESULT_SUMMARIES = {
226
- blocked: "is blocked.",
227
- failed: "failed.",
228
- reply: "replied."
229
- };
230
- /**
231
- * Append the result of one child agent Turn to its parent mailbox and wake
232
- * the parent: a `reply`, which the parent reads as a completed
233
- * `<agent-result>`, or a blocked or failed result. `sender` names the child:
234
- * an agent invocation, open or not, or the child Conversation when none
235
- * names it. `actor` is the Actor of the child's Turn; the parent never runs
236
- * with more authority than it. The key of the result, the `reply` tool call
237
- * id or the Turn id, keys the message, so a repeat call is safe.
238
- */
239
- async function enqueueChildResultToParent(args) {
240
- const nowMs = args.nowMs ?? Date.now();
241
- const actor = args.actor ?? args.sender.actor;
242
- if (!actor) throw new Error(`Reply of ${args.sender.childConversationId} has no Actor for its parent`);
243
- const senderId = args.sender.invocationId ?? args.sender.childConversationId;
244
- const inboundMessageId = getAgentReplyMessageId(senderId, args.messageKey);
245
- const rendered = args.result.kind === "reply" ? {
246
- output: args.result.reply.text,
247
- status: "completed"
248
- } : {
249
- output: args.result.text,
250
- status: args.result.kind
251
- };
252
- const sender = {
253
- ...args.sender.invocationId ? { agentInvocationId: args.sender.invocationId } : void 0,
254
- conversationId: args.sender.childConversationId,
255
- turnId: args.turnId
256
- };
257
- const metadata = {
258
- ...senderEventMetadata(args.sender, actor, {
259
- eventKey: inboundMessageId,
260
- eventType: AGENT_REPLY_EVENT_TYPE,
261
- identifier: senderId,
262
- namespace: AGENT_INVOCATION_EVENT_NAMESPACE,
263
- trustedSummary: `${childAgentLabel(args.sender)} ${RESULT_SUMMARIES[args.result.kind]}`
264
- }),
265
- ...childMessageSenderMetadata(sender)
266
- };
267
- await appendAndEnqueueInboundMessage({
268
- message: {
269
- conversationId: args.sender.parentConversationId,
270
- createdAtMs: nowMs,
271
- delivery: "defer",
272
- inboundMessageId,
273
- input: {
274
- authorId: resultAuthorId(actor),
275
- authorIdentityId: SYSTEM_IDENTITY_ID,
276
- metadata,
277
- text: renderResultInput(args.sender, rendered, [])
278
- },
279
- receivedAtMs: nowMs,
280
- source: "event"
281
- },
282
- renderText: async (parentInboundMessageIds, messageSenders) => !ownAgentInvocation(sender) && await getConversationStoppedAtMs(args.sender.childConversationId) !== void 0 ? void 0 : await renderResultUnderLock(args.sender, rendered)(parentInboundMessageIds, messageSenders),
283
- queue: args.queue,
284
- queueDelayMs: EVENT_WAIT_MS,
285
- state: args.state
286
- });
287
- }
288
- /**
289
- * Build the parent delivery of child agent Turns that run on the
290
- * Conversation loop. Such a Turn has no open agent invocation, so its
291
- * newest finished agent invocation names the child for the parent. A child
292
- * that no agent invocation names is named by its child Conversation.
293
- */
294
- function createDeliverToParent(options) {
295
- return async ({ actor, result, conversationId, turnId }) => {
296
- const sender = (await listAgentInvocationsForConversation(conversationId, TERMINAL_AGENT_INVOCATION_STATUSES)).at(-1) ?? await readChildConversationSender(conversationId);
297
- if (!sender) throw new Error(`Conversation ${conversationId} has no parent agent`);
298
- await enqueueChildResultToParent({
299
- actor,
300
- result,
301
- messageKey: result.kind === "reply" ? getTurnReplyKey(turnId, result.reply.toolCallId) : turnId,
302
- queue: options.queue,
303
- sender,
304
- state: options.state,
305
- turnId
306
- });
307
- };
308
- }
309
- /**
310
- * End the work of a child Conversation whose last attempt lost its worker.
311
- * Its open agent invocations end as before. A Turn on the Conversation loop
312
- * has none, so a Task tells its parent that it failed, as a failed Turn
313
- * does. A Thread keeps the stored failure and its telemetry.
314
- */
315
- function createEndStoppedChildWork(options) {
316
- const deliverToParent = createDeliverToParent(options);
317
- return async (conversationId, inboundMessageIds) => {
318
- if ((await listAgentInvocationsForConversation(conversationId, NON_TERMINAL_AGENT_INVOCATION_STATUSES)).length > 0) {
319
- await endAgentInvocationsOfStoppedWork(conversationId, inboundMessageIds);
320
- return;
321
- }
322
- const conversation = await getConversationStore().get({ conversationId });
323
- if (!conversation || turnBehavior({
324
- kind: conversation.kind,
325
- personInput: false
326
- }).failureNotice !== "parent") return;
327
- const turns = await listActiveMailboxTurns(conversationId);
328
- const pending = (await getConversationWorkState({ conversationId }))?.execution.pendingMessages ?? [];
329
- const turnIds = /* @__PURE__ */ new Set([...turns.map((turn) => turn.turnId), ...pending.map((message) => buildDeterministicTurnId(message.inboundMessageId))]);
330
- const sender = await getLatestAgentInvocationForConversation(conversationId) ?? await readChildConversationSender(conversationId);
331
- if (sender && (await readParentChildMessages(sender.parentConversationId, void 0)).some((message) => message.sender.conversationId === conversationId && turnIds.has(message.sender.turnId))) return;
332
- const [turn] = turns;
333
- await deliverToParent({
334
- actor: turn?.actor ?? EVENT_SYSTEM_ACTOR,
335
- result: {
336
- kind: "failed",
337
- text: "This task stopped because its worker failed repeatedly."
338
- },
339
- conversationId,
340
- turnId: turn?.turnId ?? `lost:${inboundMessageIds.at(-1) ?? "input"}`
341
- });
342
- };
343
- }
344
- /**
345
- * Give input to a child Conversation whose task is not done to that task, as
346
- * `routeChildInput` decides. Each result or message from its own child
347
- * agents, or each batch of its watch events while an agent invocation is
348
- * open, starts a new agent invocation that reports to the parent. Returns
349
- * undefined when no input goes to an agent invocation: the Conversation loop
350
- * runs it and drops what a stop skips.
351
- *
352
- * TODO(dcramer): Remove with the legacy child worker (#3060 step 7).
353
- */
354
- async function startAgentInvocationsForChildInput(context, options) {
355
- const messages = context.attempt.messages;
356
- const latest = await getLatestAgentInvocationForConversation(context.conversationId);
357
- if (messages.length === 0 || !latest) return;
358
- const stoppedAtMs = await getConversationStoppedAtMs(context.conversationId);
359
- const routes = await mapBounded(messages, (message) => routeChildInput(message, latest, stoppedAtMs));
360
- if (!routes.includes("agent invocation")) return;
361
- const inputs = messages.map(childAgentInput);
362
- const isAgentInput = messages.every((message, index) => inputs[index] !== void 0 || readParentMessage(message) !== void 0);
363
- const events = isAgentInput ? [] : parseEventMessages(messages);
364
- if (!isAgentInput && events.length === 0) return;
365
- if (!isAgentInput) {
366
- const delayMs = getEventBatchDelayMs(messages);
367
- if (delayMs > 0) return {
368
- status: "deferred",
369
- delayMs
370
- };
371
- const { actor, source } = events[0];
372
- const invocation = await createAgentInvocationFromLatest({
373
- input: renderEventBatchInputs(messages, await eventReviewItemInputs(messages)).join("\n\n"),
374
- invocationId: getAgentInvocationIdForEvents(messages[0].inboundMessageId),
375
- latest,
376
- runAs: {
377
- actor,
378
- credentialContext: credentialContextForActor(actor, timerWatchCredentialSubject(context.conversationId, messages)),
379
- source
380
- }
381
- });
382
- await enqueueAgentInvocation(invocation, {
383
- ...options,
384
- eventMeta: eventBatchMessageMeta(messages)
385
- });
386
- await context.attempt.ack();
387
- return { status: "completed" };
388
- }
389
- for (const [index, message] of messages.entries()) {
390
- const parentMessage = readParentMessage(message);
391
- if (routes[index] === "dropped") {
392
- if (parentMessage) logDroppedParentMessage(message, parentMessage);
393
- continue;
394
- }
395
- if (parentMessage) {
396
- await enqueueAgentInvocation(await createAgentInvocationFromLatest({
397
- input: message.input.text.trim(),
398
- invocationId: getAgentInvocationIdForMessage(message.inboundMessageId),
399
- latest,
400
- runAs: {
401
- actor: parentMessage.actor,
402
- credentialContext: parentMessage.credentialContext,
403
- fork: parentMessage.fork,
404
- parentToolCallId: parentMessage.parentToolCallId
405
- }
406
- }), options);
407
- continue;
408
- }
409
- const input = inputs[index];
410
- const { invocation: source } = await getChildAgentInputSender(message, input);
411
- const invocation = await createAgentInvocationFromLatest({
412
- input: message.input.text.trim(),
413
- invocationId: input.kind === "result" && source ? getAgentInvocationIdForResult(source.invocationId) : getAgentInvocationIdForMessage(message.inboundMessageId),
414
- latest,
415
- ...input.kind === "result" && source ? { runAs: {
416
- actor: source.actor,
417
- credentialContext: source.credentialContext
418
- } } : void 0
419
- });
420
- await enqueueAgentInvocation(invocation, {
421
- ...options,
422
- eventMeta: eventBatchMessageMeta([message])
423
- });
424
- }
425
- await context.attempt.ack();
426
- return { status: "completed" };
427
- }
428
- /**
429
- * Build the worker for all work of a child Conversation. The caller selects
430
- * it from the stored kind of the Conversation, never from a Turn Source. A
431
- * parent task or message runs on its agent invocation. Every other input,
432
- * such as a person's Message in a Thread, a Watch Event, or a reply or result
433
- * of the child's own child agent, runs on the Conversation loop,
434
- * like input to a root.
435
- */
436
- function createChildConversationWorker(agentRunner, options) {
437
- const invocationWorker = createAgentInvocationWorker(agentRunner, {
438
- ...options,
439
- sendReply: async (sender, reply) => await enqueueChildResultToParent({
440
- result: {
441
- kind: "reply",
442
- reply
443
- },
444
- messageKey: reply.toolCallId,
445
- queue: options.queue,
446
- sender,
447
- state: options.state,
448
- turnId: getAgentInvocationTurnId(sender.invocationId)
449
- })
450
- });
451
- return async (context) => {
452
- const invocationId = await resolveAgentInvocationId(context);
453
- if (invocationId) return await invocationWorker(context, invocationId);
454
- const started = await startAgentInvocationsForChildInput(context, options);
455
- if (started) return started;
456
- const work = await resolveMailboxTurnWork(context);
457
- if (!work) {
458
- await context.attempt.ack();
459
- return { status: "completed" };
460
- }
461
- if (work.kind === "mailbox") await endActiveAgentInvocations(context.conversationId, {
462
- enqueueResult: options.enqueueResult,
463
- errorMessage: "A person sent a Message in this Thread, so this task ended without a result. Send messageAgent again if you still need this work."
464
- });
465
- const kept = await withAgentInvocationResultActors(work);
466
- if (!kept) {
467
- await context.attempt.ack();
468
- return { status: "completed" };
469
- }
470
- const result = await options.runTurn(context, kept);
471
- if (result.status === "completed") await reportParentWithoutOpenWork(context.conversationId, options);
472
- return result;
473
- };
474
- }
475
- /**
476
- * A completed Turn of a child that no Agent invocation names can end the
477
- * last open work of its parent, such as a Turn that ends with `noReply`. A
478
- * `replaced` result of that parent then reports, as when a child row ends.
479
- * A child with a row reports when its row ends, as on `main`.
480
- *
481
- * TODO(dcramer): Remove with the `replaced` result (#3060 step 7).
482
- */
483
- async function reportParentWithoutOpenWork(conversationId, options) {
484
- if (await getLatestAgentInvocationForConversation(conversationId)) return;
485
- const sender = await readChildConversationSender(conversationId);
486
- const replaced = sender ? await reportReplacedWithoutOpenWork(sender.parentConversationId) : void 0;
487
- if (replaced && isTerminalAgentInvocation(replaced)) await enqueueAgentInvocationResult(replaced, options);
488
- }
489
- /**
490
- * Run each agent invocation result or message as the Actor that triggered the
491
- * child, user or system, with its grants. This is on purpose: the result
492
- * continues that Actor's work. The Actor comes from SQL when an agent
493
- * invocation names the child, so the parent Turn has the same authority it
494
- * had at spawn time. Otherwise the input carries it, and so does a parent
495
- * task to a child.
496
- * Input that a child's Turn with another Actor sent runs as the Event system
497
- * Actor, so it never gets more authority than that Turn. A result that a stop
498
- * skipped is dropped. Returns undefined when no input is left.
499
- */
500
- async function withAgentInvocationResultActors(work) {
501
- if (work.kind !== "mailbox") return work;
502
- const conversationId = work.batch[0]?.message.conversationId;
503
- const [latest, stoppedAtMs] = conversationId ? await Promise.all([getLatestAgentInvocationForConversation(conversationId), getConversationStoppedAtMs(conversationId)]) : [void 0, void 0];
504
- const kept = (await mapBounded(work.batch, async (entry) => {
505
- const parentMessage = readParentMessage(entry.message);
506
- if (parentMessage) {
507
- if (await routeChildInput(entry.message, latest, stoppedAtMs) === "dropped") {
508
- logDroppedParentMessage(entry.message, parentMessage);
509
- return;
510
- }
511
- const text = await parentMessageText(entry.message, parentMessage);
512
- return {
513
- ...entry,
514
- actor: parentMessage.actor,
515
- ...parentMessage.credentialContext ? { credentialContext: parentMessage.credentialContext } : void 0,
516
- message: {
517
- ...entry.message,
518
- input: {
519
- ...entry.message.input,
520
- text
521
- }
522
- }
523
- };
524
- }
525
- const input = childAgentInput(entry.message);
526
- if (!input) return entry;
527
- if (await routeChildInput(entry.message, latest, stoppedAtMs) === "dropped") return;
528
- const { invocation } = await getChildAgentInputSender(entry.message, input);
529
- const actor = invocation?.actor ?? senderActorFromMetadata(entry.message.input.metadata);
530
- if (!actor || entry.message.input.authorId !== resultAuthorId(actor)) return {
531
- ...entry,
532
- actor: EVENT_SYSTEM_ACTOR
533
- };
534
- return input.kind === "result" && invocation?.credentialContext ? {
535
- ...entry,
536
- actor,
537
- credentialContext: invocation.credentialContext
538
- } : {
539
- ...entry,
540
- actor
541
- };
542
- })).filter((entry) => entry !== void 0);
543
- return kept.length > 0 ? {
544
- kind: "mailbox",
545
- batch: kept
546
- } : void 0;
547
- }
548
- export { enqueueAgentMessageToParent as a, enqueueAgentInvocationResult as i, createDeliverToParent as n, result_exports as o, createEndStoppedChildWork as r, withAgentInvocationResultActors as s, createChildConversationWorker as t };