@sentry/junior 0.312.0 → 0.314.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 (115) hide show
  1. package/dist/{adapter-iIq7ihf7.js → adapter-JARQvoLw.js} +1 -2
  2. package/dist/{adapter-context-BRjEWRy1.js → adapter-context-B4BrJZuS.js} +2 -2
  3. package/dist/{admin-DhInw5K9.js → admin-BXGAySz0.js} +1 -1
  4. package/dist/{agent-runner-C9iDurwX.js → agent-runner-qZU5TR8i.js} +865 -138
  5. package/dist/agent-update-cS7Z9mnG.js +26 -0
  6. package/dist/agent-update-delivery-CZ5M8RDa.js +85 -0
  7. package/dist/api/schema.d.ts +2 -2
  8. package/dist/api/schema.js +6 -6
  9. package/dist/api.d.ts +1 -1
  10. package/dist/api.js +340 -106
  11. package/dist/{app-DRFrC8Mw.d.ts → app-D7tKnw9a.d.ts} +4 -21
  12. package/dist/app.d.ts +2 -2
  13. package/dist/app.js +80 -171
  14. package/dist/{background-compaction-queue-DrKi7w3d.js → background-compaction-queue-C_uIBUvS.js} +6 -17
  15. package/dist/{callback-mFlTUWWx.js → callback-C8SdXCwr.js} +4 -11
  16. package/dist/{catalog-runtime-D7xapBAX.js → catalog-runtime-BLKtnUL3.js} +1 -1
  17. package/dist/{channel-access-CJGfNTdn.js → channel-access-BOL29BG3.js} +6 -6
  18. package/dist/child-message--2G3Ft26.js +19 -0
  19. package/dist/cli/chat.js +18 -21
  20. package/dist/cli/check.js +4 -4
  21. package/dist/cli/main.js +2 -2
  22. package/dist/cli/plugins.js +5 -5
  23. package/dist/cli/snapshot-create.js +5 -5
  24. package/dist/cli/upgrade.d.ts +1 -1
  25. package/dist/cli/upgrade.js +23 -4
  26. package/dist/{config-kXB2Y5tl.js → config-BIfHKNXN.js} +40 -35
  27. package/dist/{continue-in-slack-O6pV5004.js → continue-in-slack-fnmD2Ifb.js} +5 -7
  28. package/dist/{conversation-feed-uNOv_x68.js → conversation-feed-DdFQuQDR.js} +13 -2
  29. package/dist/{logging-dQ9ZRGQ8.js → conversation-privacy-DtZhI91r.js} +188 -2
  30. package/dist/{conversation-turn-CeLbHqdw.js → conversation-turn-DScuDYmN.js} +465 -62
  31. package/dist/create-CrNt4Ewu.js +212 -0
  32. package/dist/{credential-sync-I8VBGk05.js → credential-sync-CtqsGjj1.js} +14 -18
  33. package/dist/{credentialed-Cb6E2phL.js → credentialed-dWRA3-oJ.js} +911 -429
  34. package/dist/{db-LAyyX8tk.js → db-BTmLKZrp.js} +2245 -50
  35. package/dist/{db-BbC5stfa.d.ts → db-DcmzbA55.d.ts} +2 -2
  36. package/dist/{history-CYstOMKX.js → history-CneKY7_V.js} +19 -1
  37. package/dist/{html-BCZ3Xtb_.js → html-B8rBt7F4.js} +5 -7
  38. package/dist/{install-DCFJFkC0.js → install-OtFboxOM.js} +2 -2
  39. package/dist/instrumentation.js +2 -2
  40. package/dist/{lineage-B_m-4TJw.js → lineage-EULJkGO1.js} +1 -2
  41. package/dist/{list-CN2QA2R9.js → list-C5400AlJ.js} +284 -113
  42. package/dist/{thread-state-DhPndWi1.js → mailbox-turn-DL3Lvsm0.js} +4830 -485
  43. package/dist/markers-DUP8aBOp.js +323 -0
  44. package/dist/{media-CYm1QD8T.js → media-FYM-Bl3H.js} +42 -14
  45. package/dist/{message-DSXGj1hM.js → message-DuDelZFr.js} +16 -15
  46. package/dist/{model-input--TrP9hYV.js → model-input-0osF3pBS.js} +3 -3
  47. package/dist/nitro.d.ts +2 -4
  48. package/dist/nitro.js +340 -13
  49. package/dist/{oauth-callback-server-DHCZC6B4.js → oauth-callback-server-DX2fQ7Nq.js} +2 -2
  50. package/dist/{oauth-relay-pPMGnDZt.js → oauth-relay-PwPMdZJv.js} +1 -1
  51. package/dist/{plugins-Bkk0XRo2.js → plugins-BXMdNdyA.js} +1 -1
  52. package/dist/{registry-CZOzddwu.js → registry-D6kS6xYH.js} +1402 -64
  53. package/dist/{statuses-_cRJHXK7.js → reporting-window-C4dbzDiR.js} +1 -27
  54. package/dist/{resolve-cKOQ14Dh.js → resolve-D8CPJcNK.js} +3 -3
  55. package/dist/result-D090hxr5.js +402 -0
  56. package/dist/{runner-DBfUW44l.js → runner-BU7fgrm-.js} +7 -8
  57. package/dist/{sandbox-egress-signals-BVF_xAm1.js → sandbox-egress-signals-BUmVrsoG.js} +1 -1
  58. package/dist/{schema-Bk9Nm2E8.js → schema-7gW9vBpJ.js} +91 -10
  59. package/dist/{schema-BEHKxr4I.d.ts → schema-BB6E0wyV.d.ts} +2105 -2753
  60. package/dist/{service-account-CVYsFjty.js → service-account-plA-uzIB.js} +6 -5
  61. package/dist/{skills-VTnhAJWm.js → skills-CIosT6bS.js} +3 -3
  62. package/dist/{slack-conversation-unfurl-fuLnF1jE.js → slack-conversation-unfurl-CBgZqth6.js} +8 -10
  63. package/dist/spawn-DRjdzh3R.js +46 -0
  64. package/dist/{start-conversation-CEn2KH1A.js → start-conversation-a4NXH4X9.js} +13 -202
  65. package/dist/{store-DFZaN-Ix.js → store-BuhF1QDm.js} +2 -4
  66. package/dist/{task-queue-Cx4Lmjyk.js → task-queue-CrRjFzOh.js} +5 -16
  67. package/dist/{task-runner-CbTwFA6k.js → task-runner-C-pXsgHM.js} +105 -51
  68. package/dist/{thread-context-BkAZDTX2.js → thread-context-CDX4dSZd.js} +8 -10
  69. package/dist/turn-session-routing-CZTRU8IY.js +116 -0
  70. package/dist/turn-wake-Bzq1Efrm.js +154 -0
  71. package/dist/user-customization-B27StpVQ.js +9 -0
  72. package/dist/{validation-nIzMtAVJ.js → validation-bTq88sya.js} +1 -1
  73. package/dist/{vercel-queue-hW90XzbG.js → vercel-queue-nL0Hq3hr.js} +32 -147
  74. package/dist/{version-Brbtz4Qf.js → version-DGUa1dZK.js} +1 -1
  75. package/dist/version.js +1 -1
  76. package/dist/{warmup-BDA5myRK.js → warmup-CCOuIwAS.js} +831 -3254
  77. package/dist/{worker-D63RcaVD.js → worker-AkZg7Dg1.js} +5 -6
  78. package/migrations/0158_keep_legacy_archive_columns.sql +5 -0
  79. package/migrations/0159_conversation_embeddings_fk_validate.sql +5 -0
  80. package/migrations/0160_money_micro_usd_repair.sql +99 -0
  81. package/migrations/0161_agent_config_backfill.sql +34 -0
  82. package/migrations/0162_inbox_item_deliveries.sql +15 -0
  83. package/migrations/0163_pg_trgm.sql +2 -0
  84. package/migrations/0164_search_indexes.sql +4 -0
  85. package/migrations/0165_drop_legacy_archive_columns.sql +4 -0
  86. package/migrations/0166_memory_prefix_index.sql +1 -0
  87. package/migrations/0167_todo_search_indexes.sql +2 -0
  88. package/migrations/0168_todo_inbox_items.sql +4 -0
  89. package/migrations/0169_drop_code_urls.sql +2 -0
  90. package/migrations/meta/0158_snapshot.json +6515 -0
  91. package/migrations/meta/0159_snapshot.json +6515 -0
  92. package/migrations/meta/0160_snapshot.json +6515 -0
  93. package/migrations/meta/0161_snapshot.json +6278 -0
  94. package/migrations/meta/0162_snapshot.json +6404 -0
  95. package/migrations/meta/0163_snapshot.json +6404 -0
  96. package/migrations/meta/0164_snapshot.json +6466 -0
  97. package/migrations/meta/0165_snapshot.json +6466 -0
  98. package/migrations/meta/0166_snapshot.json +6494 -0
  99. package/migrations/meta/0167_snapshot.json +6525 -0
  100. package/migrations/meta/0168_snapshot.json +6525 -0
  101. package/migrations/meta/0169_snapshot.json +6513 -0
  102. package/migrations/meta/_journal.json +84 -0
  103. package/package.json +9 -18
  104. package/skills/design-automation-skill/SKILL.md +2 -3
  105. package/dist/actor-BsBdxDXQ.js +0 -208
  106. package/dist/child-message-DcsritGf.js +0 -179
  107. package/dist/conversation-privacy-L4ja1_W6.js +0 -189
  108. package/dist/executor-SCub-fAq.js +0 -1860
  109. package/dist/fan-out-Cod-yEHG.js +0 -10
  110. package/dist/ingest-BDf3D50j.js +0 -3836
  111. package/dist/result-DcvEOe1r.js +0 -574
  112. package/dist/result-event-type-BdIJuZxg.js +0 -48
  113. package/dist/service-account-Ts4ulcrV.js +0 -931
  114. package/dist/spawn-vxAarlX5.js +0 -73
  115. package/dist/state-C1P3_Ywk.js +0 -161
@@ -1,574 +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 { F as turnBehavior, Qt as SYSTEM_IDENTITY_ID, a as getConversationStore, s as getSqlExecutor } from "./db-LAyyX8tk.js";
4
- import { $ as eventInboxItemInputs, D as getConversationStoppedAtMs, E as enqueueAutomatedInput, _ as timerWatchCredentialSubject, a as getEventBatchDelayMs, c as parseEventMessages, g as renderEventBatchInputs, ht as closeOpenTodosOfChild, l as resolveMailboxTurnWork, m as eventBatchMessageMeta, p as EVENT_WAIT_MS, s as listActiveMailboxTurns } from "./ingest-BDf3D50j.js";
5
- import { L as buildDeterministicTurnId, w as getConversationWorkState, xt as EVENT_SYSTEM_ACTOR } from "./thread-state-DhPndWi1.js";
6
- import { p as credentialContextForActor } from "./registry-CZOzddwu.js";
7
- import { At as isTerminalAgentInvocation, Bt as routeChildInput, Ct as NON_TERMINAL_AGENT_INVOCATION_STATUSES, Ft as reportReplacedWithoutOpenWork, Gt as parentMessageText, It as sendsResultToParent, Kt as readParentMessage, Lt as childAgentInput, Pt as markAgentInvocationParentMailboxAppended, Qt as resolveAgentInvocationId, Rt as getChildAgentInputSender, St as listUnreportedSiblingAgents, Tt as childAgentStillWorks, Wt as logDroppedParentMessage, Xt as endAgentInvocationsOfStoppedWork, Yt as endActiveAgentInvocations, Zt as enqueueAgentInvocation, en as createAgentInvocationFromLatest, jt as listAgentInvocationsForConversation, kt as getLatestAgentInvocationForConversation, qt as createAgentInvocationWorker, wt as TERMINAL_AGENT_INVOCATION_STATUSES, zt as readChildConversationSender } from "./warmup-BDA5myRK.js";
8
- import { a as ownAgentInvocation, d as getAgentInvocationIdForResult, h as getAgentReplyMessageId, i as listChildMessages, l as getAgentInvocationIdForEvents, m as getAgentInvocationTurnId, n as hasAgentInvocationReply, p as getAgentInvocationResultMessageId, t as childMessageSenderMetadata, u as getAgentInvocationIdForMessage, v as getTurnReplyKey } from "./child-message-DcsritGf.js";
9
- import { it as renderUntrustedTag } from "./config-kXB2Y5tl.js";
10
- import { a as agentInvocationResultEventType, i as AGENT_REPLY_EVENT_TYPE, n as AGENT_MESSAGE_EVENT_TYPE, t as AGENT_INVOCATION_EVENT_NAMESPACE } from "./result-event-type-BdIJuZxg.js";
11
- import * as z from "zod";
12
- import { actorSchema } from "@sentry/junior-plugin-api";
13
- // src/chat/agent-invocations/result-actors.ts
14
- const senderActorMetadataSchema = z.object({ actor: actorSchema });
15
- /**
16
- * Return the Inbound message author id for results sent by one Actor.
17
- * `selectContiguousTurnBatch` in `task-execution/worker.ts` puts messages in
18
- * one attempt only when their author ids and sources match. Mid-Turn drains
19
- * take only `interrupt` messages, and results are `defer`. So results never
20
- * share a Turn and its credentials with another Actor or with watch Events.
21
- * Keep this id unique per Actor if either rule changes.
22
- */
23
- function resultAuthorId(actor) {
24
- switch (actor.platform) {
25
- case "system": return `agent-invocation:system:${actor.name}`;
26
- case "slack": return `agent-invocation:slack:${actor.teamId}:${actor.userId}`;
27
- default: return `agent-invocation:${actor.platform}:${actor.userId}`;
28
- }
29
- }
30
- /** Read the Actor that a reply or message from a child without an Agent invocation carries. */
31
- function senderActorFromMetadata(metadata) {
32
- const parsed = senderActorMetadataSchema.safeParse(metadata);
33
- return parsed.success ? parsed.data.actor : void 0;
34
- }
35
- /**
36
- * Run each agent invocation result or message as the Actor that triggered the
37
- * child, user or system, with its grants. This is on purpose: the result
38
- * continues that Actor's work. The Actor comes from SQL when an agent
39
- * invocation names the child, so the parent Turn has the same authority it
40
- * had at spawn time. Otherwise the input carries it, and so does a parent
41
- * task to a child.
42
- * Input that a child's Turn with another Actor sent runs as the Event system
43
- * Actor, so it never gets more authority than that Turn. A result that a stop
44
- * skipped is dropped. Returns undefined when no input is left.
45
- */
46
- async function withAgentInvocationResultActors(work) {
47
- if (work.kind !== "mailbox") return work;
48
- const conversationId = work.batch[0]?.message.conversationId;
49
- const latest = conversationId ? await getLatestAgentInvocationForConversation(conversationId) : void 0;
50
- const kept = (await mapBounded(work.batch, async (entry) => {
51
- const parentMessage = readParentMessage(entry.message);
52
- if (parentMessage) {
53
- if (await routeChildInput(entry.message, latest) === "dropped") {
54
- logDroppedParentMessage(entry.message, parentMessage);
55
- return;
56
- }
57
- const text = await parentMessageText(entry.message, parentMessage);
58
- return {
59
- ...entry,
60
- actor: parentMessage.actor,
61
- requestText: entry.message.input.text.trim(),
62
- ...parentMessage.credentialContext ? { credentialContext: parentMessage.credentialContext } : void 0,
63
- message: {
64
- ...entry.message,
65
- input: {
66
- ...entry.message.input,
67
- text
68
- }
69
- }
70
- };
71
- }
72
- const input = childAgentInput(entry.message);
73
- if (!input) return entry;
74
- if (await routeChildInput(entry.message, latest) === "dropped") return;
75
- const { invocation } = await getChildAgentInputSender(entry.message, input);
76
- const actor = invocation?.actor ?? senderActorFromMetadata(entry.message.input.metadata);
77
- if (!actor || entry.message.input.authorId !== resultAuthorId(actor)) return {
78
- ...entry,
79
- actor: EVENT_SYSTEM_ACTOR
80
- };
81
- return input.kind === "result" && invocation?.credentialContext ? {
82
- ...entry,
83
- actor,
84
- credentialContext: invocation.credentialContext
85
- } : {
86
- ...entry,
87
- actor
88
- };
89
- })).filter((entry) => entry !== void 0);
90
- return kept.length > 0 ? {
91
- kind: "mailbox",
92
- batch: kept
93
- } : void 0;
94
- }
95
- // src/chat/agent-invocations/result.ts
96
- var result_exports = /* @__PURE__ */ __exportAll({
97
- createChildConversationWorker: () => createChildConversationWorker,
98
- createDeliverToParent: () => createDeliverToParent
99
- });
100
- const AGENT_INVOCATION_RESULT_MAX_LENGTH = 12e3;
101
- /**
102
- * Error messages can contain text from tools or providers, so the trusted
103
- * summary in the mailbox metadata has only the status.
104
- */
105
- function trustedSummary(invocation, agent) {
106
- switch (invocation.status) {
107
- case "completed": return `${agent} finished its task.`;
108
- case "blocked": return `${agent} is blocked.`;
109
- case "failed": return `${agent} failed.`;
110
- case "stopped": return `${agent} was stopped.`;
111
- }
112
- }
113
- /**
114
- * Render the parent agent input for one child agent result as one
115
- * `<agent-result>`. A child agent wrote the output, so it is escaped data.
116
- * `status` and `waiting_on` are runtime facts. The system prompt says what to
117
- * do for each status, so the input repeats no guidance.
118
- */
119
- function renderResultInput(sender, result, openSiblings) {
120
- const output = result.output.trim().slice(0, AGENT_INVOCATION_RESULT_MAX_LENGTH);
121
- return renderUntrustedTag("agent-result", {
122
- conversation_id: sender.childConversationId,
123
- name: sender.agentName,
124
- source: "child_agent",
125
- status: result.status,
126
- title: sender.title,
127
- waiting_on: openSiblings.length ? openSiblings.map(siblingLabel).join(", ") : void 0
128
- }, "A child agent that you started", output || "(empty)");
129
- }
130
- function siblingLabel(sibling) {
131
- return sibling.agentName ?? sibling.title ?? sibling.childConversationId;
132
- }
133
- /**
134
- * Render one `<agent-result>` under the parent's mailbox lock. `waiting_on`
135
- * then sees every `reply` that reached the parent, also one that a sibling
136
- * sent at the same moment, so two siblings cannot each name the other.
137
- */
138
- function renderResultUnderLock(sender, result) {
139
- return async (parentInboundMessageIds, messageSenders) => renderResultInput(sender, result, await listUnreportedSiblingAgents(sender.parentConversationId, sender.childConversationId, await listChildMessages(parentInboundMessageIds, messageSenders)));
140
- }
141
- function terminalResult(invocation) {
142
- return {
143
- output: invocation.status === "completed" ? invocation.result : invocation.errorMessage,
144
- status: invocation.status
145
- };
146
- }
147
- /**
148
- * Build the parent Inbound message for one terminal agent invocation. Its
149
- * text names no siblings: `renderResultUnderLock` adds `waiting_on`.
150
- */
151
- function buildResultInboundMessage(invocation, nowMs) {
152
- const summary = trustedSummary(invocation, childAgentLabel(invocation));
153
- const metadata = {
154
- kind: "event",
155
- event: {
156
- eventKey: invocation.invocationId,
157
- eventType: agentInvocationResultEventType(invocation.status),
158
- identifier: invocation.invocationId,
159
- namespace: AGENT_INVOCATION_EVENT_NAMESPACE,
160
- trustedSummary: summary
161
- },
162
- ...childMessageSenderMetadata({
163
- agentInvocationId: invocation.invocationId,
164
- conversationId: invocation.childConversationId,
165
- turnId: getAgentInvocationTurnId(invocation.invocationId)
166
- })
167
- };
168
- return {
169
- conversationId: invocation.parentConversationId,
170
- createdAtMs: invocation.terminalAtMs,
171
- delivery: "defer",
172
- inboundMessageId: getAgentInvocationResultMessageId(invocation.invocationId),
173
- input: {
174
- authorId: resultAuthorId(invocation.actor),
175
- authorIdentityId: SYSTEM_IDENTITY_ID,
176
- metadata,
177
- text: renderResultInput(invocation, terminalResult(invocation), [])
178
- },
179
- receivedAtMs: nowMs,
180
- source: "event"
181
- };
182
- }
183
- /**
184
- * Append one terminal agent invocation result to the parent mailbox and wake
185
- * the parent. Repeat calls are safe.
186
- *
187
- * A stopped parent holds the result. Result Turns count toward the
188
- * automated-turn limit.
189
- * TODO(dcramer): Add a per-parent total invocation limit as the loop guard
190
- * for spawn -> result -> spawn chains (#881).
191
- */
192
- async function enqueueAgentInvocationResult(invocation, options) {
193
- if (invocation.parentMailboxStatus !== "pending") return;
194
- const nowMs = options.nowMs ?? Date.now();
195
- const parentMessages = await readParentChildMessages(invocation.parentConversationId, options.state);
196
- if (!sendsResultToParent(invocation, parentMessages)) {
197
- await markAgentInvocationParentMailboxAppended(invocation.invocationId, nowMs);
198
- const replaced = hasAgentInvocationReply(parentMessages, invocation.invocationId) ? void 0 : await reportReplacedWithoutOpenWork(invocation.parentConversationId, nowMs);
199
- if (replaced && isTerminalAgentInvocation(replaced)) await enqueueAgentInvocationResult(replaced, options);
200
- return;
201
- }
202
- const resultMessageId = getAgentInvocationResultMessageId(invocation.invocationId);
203
- if (!parentMessages.some((message) => message.inboundMessageId === resultMessageId)) await closeTodosForResult(invocation, invocation.status, nowMs);
204
- await enqueueAutomatedInput({
205
- message: buildResultInboundMessage(invocation, nowMs),
206
- renderText: renderResultUnderLock(invocation, terminalResult(invocation)),
207
- queue: options.queue,
208
- queueDelayMs: EVENT_WAIT_MS,
209
- state: options.state
210
- });
211
- await markAgentInvocationParentMailboxAppended(invocation.invocationId, nowMs);
212
- }
213
- /**
214
- * Close the child's open To-dos of the parent before the parent reads the
215
- * child's result: done when it completed, dropped when it stopped. A
216
- * blocked or failed child did not finish that work.
217
- */
218
- async function closeTodosForResult(sender, status, nowMs) {
219
- if (status !== "completed" && status !== "stopped") return;
220
- await closeOpenTodosOfChild(getSqlExecutor(), {
221
- childConversationId: sender.childConversationId,
222
- nowMs,
223
- parentConversationId: sender.parentConversationId,
224
- status: status === "completed" ? "done" : "dropped"
225
- });
226
- }
227
- /**
228
- * Read every child reply and result that reached the parent's mailbox. A
229
- * sibling whose `reply` is among them has answered.
230
- */
231
- async function readParentChildMessages(parentConversationId, state) {
232
- const work = await getConversationWorkState({
233
- conversationId: parentConversationId,
234
- state
235
- });
236
- return await listChildMessages(work?.execution.inboundMessageIds ?? [], work?.execution.messageSenders ?? {});
237
- }
238
- function childAgentLabel(sender) {
239
- return sender.agentName ? `Child agent "${sender.agentName}"` : "Child agent";
240
- }
241
- /**
242
- * Mailbox metadata of a reply or message from a child that no Agent
243
- * invocation names. It carries the Actor of the child's Turn, so the parent
244
- * runs with no more authority than that Turn. The author id must match it.
245
- */
246
- function senderEventMetadata(sender, actor, event) {
247
- return sender.invocationId ? {
248
- kind: "event",
249
- event
250
- } : {
251
- kind: "event",
252
- event,
253
- actor
254
- };
255
- }
256
- function renderMessageInput(sender, text) {
257
- return renderUntrustedTag("agent-message", {
258
- conversation_id: sender.childConversationId,
259
- name: sender.agentName,
260
- source: "child_agent",
261
- title: sender.title
262
- }, "A child agent that you started", text.trim());
263
- }
264
- /**
265
- * Append one message from a child agent to its parent mailbox and wake the
266
- * parent. `sender` names the child, and `actor` is the Actor of the child's
267
- * Turn. The parent handles the message like a result. Repeat calls with the
268
- * same `messageKey` are safe.
269
- */
270
- async function enqueueAgentMessageToParent(args) {
271
- const nowMs = args.nowMs ?? Date.now();
272
- const senderId = args.sender.invocationId ?? args.sender.childConversationId;
273
- const inboundMessageId = `agent-invocation:${senderId}:message:${args.messageKey}`;
274
- const summary = `${childAgentLabel(args.sender)} sent a message.`;
275
- const metadata = senderEventMetadata(args.sender, args.actor, {
276
- eventKey: inboundMessageId,
277
- eventType: AGENT_MESSAGE_EVENT_TYPE,
278
- identifier: senderId,
279
- namespace: AGENT_INVOCATION_EVENT_NAMESPACE,
280
- trustedSummary: summary
281
- });
282
- await enqueueAutomatedInput({
283
- message: {
284
- conversationId: args.sender.parentConversationId,
285
- createdAtMs: nowMs,
286
- delivery: "defer",
287
- inboundMessageId,
288
- input: {
289
- authorId: resultAuthorId(args.actor),
290
- authorIdentityId: SYSTEM_IDENTITY_ID,
291
- metadata,
292
- text: renderMessageInput(args.sender, args.text)
293
- },
294
- receivedAtMs: nowMs,
295
- source: "event"
296
- },
297
- queue: args.queue,
298
- queueDelayMs: EVENT_WAIT_MS,
299
- state: args.state
300
- });
301
- }
302
- const RESULT_SUMMARIES = {
303
- blocked: "is blocked.",
304
- failed: "failed.",
305
- reply: "replied."
306
- };
307
- /**
308
- * Append the result of one child agent Turn to its parent mailbox and wake
309
- * the parent: a `reply`, which the parent reads as a completed
310
- * `<agent-result>` or, while the child still works, as a message, or a
311
- * blocked or failed result. `sender` names the child:
312
- * an agent invocation, open or not, or the child Conversation when none
313
- * names it. `actor` is the Actor of the child's Turn; the parent never runs
314
- * with more authority than it. The key of the result, the `reply` tool call
315
- * id or the Turn id, keys the message, so a repeat call is safe.
316
- */
317
- async function enqueueChildResultToParent(args) {
318
- const nowMs = args.nowMs ?? Date.now();
319
- const actor = args.actor ?? args.sender.actor;
320
- if (!actor) throw new Error(`Reply of ${args.sender.childConversationId} has no Actor for its parent`);
321
- const senderId = args.sender.invocationId ?? args.sender.childConversationId;
322
- const inboundMessageId = getAgentReplyMessageId(senderId, args.messageKey);
323
- const rendered = args.result.kind === "reply" ? {
324
- output: args.result.reply.text,
325
- status: "completed"
326
- } : {
327
- output: args.result.text,
328
- status: args.result.kind
329
- };
330
- const replyTurn = {
331
- ...args.sender.invocationId ? { agentInvocationId: args.sender.invocationId } : void 0,
332
- conversationId: args.sender.childConversationId,
333
- turnId: args.turnId
334
- };
335
- const stillWorks = args.result.kind === "reply" && await childAgentStillWorks(args.sender.childConversationId, ownAgentInvocation(replyTurn));
336
- const sender = stillWorks ? {
337
- conversationId: replyTurn.conversationId,
338
- turnId: replyTurn.turnId
339
- } : replyTurn;
340
- const text = stillWorks ? renderMessageInput(args.sender, rendered.output) : renderResultInput(args.sender, rendered, []);
341
- const metadata = {
342
- ...senderEventMetadata(args.sender, actor, {
343
- eventKey: inboundMessageId,
344
- eventType: AGENT_REPLY_EVENT_TYPE,
345
- identifier: senderId,
346
- namespace: AGENT_INVOCATION_EVENT_NAMESPACE,
347
- trustedSummary: `${childAgentLabel(args.sender)} ${stillWorks ? "sent a message." : RESULT_SUMMARIES[args.result.kind]}`
348
- }),
349
- ...childMessageSenderMetadata(sender)
350
- };
351
- const replyingInvocationId = args.result.kind === "reply" ? ownAgentInvocation(sender) : void 0;
352
- if (replyingInvocationId && !hasAgentInvocationReply(await readParentChildMessages(args.sender.parentConversationId, args.state), replyingInvocationId)) await closeTodosForResult(args.sender, "completed", nowMs);
353
- await enqueueAutomatedInput({
354
- message: {
355
- conversationId: args.sender.parentConversationId,
356
- createdAtMs: nowMs,
357
- delivery: "defer",
358
- inboundMessageId,
359
- input: {
360
- authorId: resultAuthorId(actor),
361
- authorIdentityId: SYSTEM_IDENTITY_ID,
362
- metadata,
363
- text
364
- },
365
- receivedAtMs: nowMs,
366
- source: "event"
367
- },
368
- renderText: async (parentInboundMessageIds, messageSenders) => !ownAgentInvocation(sender) && await getConversationStoppedAtMs(args.sender.childConversationId) !== void 0 ? void 0 : stillWorks ? text : await renderResultUnderLock(args.sender, rendered)(parentInboundMessageIds, messageSenders),
369
- queue: args.queue,
370
- queueDelayMs: EVENT_WAIT_MS,
371
- state: args.state
372
- });
373
- }
374
- /**
375
- * Build the parent delivery of child agent Turns that run on the
376
- * Conversation loop. Such a Turn has no open agent invocation, so its
377
- * newest finished agent invocation names the child for the parent. A child
378
- * that no agent invocation names is named by its child Conversation.
379
- */
380
- function createDeliverToParent(options) {
381
- return async ({ actor, result, conversationId, turnId }) => {
382
- const sender = (await listAgentInvocationsForConversation(conversationId, TERMINAL_AGENT_INVOCATION_STATUSES)).at(-1) ?? await readChildConversationSender(conversationId);
383
- if (!sender) throw new Error(`Conversation ${conversationId} has no parent agent`);
384
- await enqueueChildResultToParent({
385
- actor,
386
- result,
387
- messageKey: result.kind === "reply" ? getTurnReplyKey(turnId, result.reply.toolCallId) : turnId,
388
- queue: options.queue,
389
- sender,
390
- state: options.state,
391
- turnId
392
- });
393
- };
394
- }
395
- /**
396
- * End the work of a child Conversation whose last attempt lost its worker.
397
- * Its open agent invocations end as before. A Turn on the Conversation loop
398
- * has none, so a Task tells its parent that it failed, as a failed Turn
399
- * does. A Thread keeps the stored failure and its telemetry.
400
- */
401
- function createEndStoppedChildWork(options) {
402
- const deliverToParent = createDeliverToParent(options);
403
- return async (conversationId, inboundMessageIds) => {
404
- if ((await listAgentInvocationsForConversation(conversationId, NON_TERMINAL_AGENT_INVOCATION_STATUSES)).length > 0) {
405
- await endAgentInvocationsOfStoppedWork(conversationId, inboundMessageIds);
406
- return;
407
- }
408
- const conversation = await getConversationStore().get({ conversationId });
409
- if (!conversation || turnBehavior({
410
- kind: conversation.kind,
411
- personInput: false
412
- }).failureNotice !== "parent") return;
413
- const turns = await listActiveMailboxTurns(conversationId);
414
- const pending = (await getConversationWorkState({ conversationId }))?.execution.pendingMessages ?? [];
415
- const turnIds = /* @__PURE__ */ new Set([...turns.map((turn) => turn.turnId), ...pending.map((message) => buildDeterministicTurnId(message.inboundMessageId))]);
416
- const sender = await getLatestAgentInvocationForConversation(conversationId) ?? await readChildConversationSender(conversationId);
417
- if (sender && (await readParentChildMessages(sender.parentConversationId, void 0)).some((message) => message.sender.conversationId === conversationId && turnIds.has(message.sender.turnId))) return;
418
- const [turn] = turns;
419
- await deliverToParent({
420
- actor: turn?.actor ?? EVENT_SYSTEM_ACTOR,
421
- result: {
422
- kind: "failed",
423
- text: "This task stopped because its worker failed repeatedly."
424
- },
425
- conversationId,
426
- turnId: turn?.turnId ?? `lost:${inboundMessageIds.at(-1) ?? "input"}`
427
- });
428
- };
429
- }
430
- /**
431
- * Give input to a child Conversation whose task is not done to that task, as
432
- * `routeChildInput` decides. Each result or message from its own child
433
- * agents, or each batch of its watch events while an agent invocation is
434
- * open, starts a new agent invocation that reports to the parent. Returns
435
- * undefined when no input goes to an agent invocation: the Conversation loop
436
- * runs it and drops what a stop skips.
437
- *
438
- * TODO(dcramer): Remove with the legacy child worker (#3060 step 7).
439
- */
440
- async function startAgentInvocationsForChildInput(context, options) {
441
- const messages = context.attempt.messages;
442
- const latest = await getLatestAgentInvocationForConversation(context.conversationId);
443
- if (messages.length === 0 || !latest) return;
444
- const routes = await mapBounded(messages, (message) => routeChildInput(message, latest));
445
- if (!routes.includes("agent invocation")) return;
446
- const inputs = messages.map(childAgentInput);
447
- const isAgentInput = messages.every((message, index) => inputs[index] !== void 0 || readParentMessage(message) !== void 0);
448
- const events = isAgentInput ? [] : parseEventMessages(messages);
449
- if (!isAgentInput && events.length === 0) return;
450
- if (!isAgentInput) {
451
- const delayMs = getEventBatchDelayMs(messages);
452
- if (delayMs > 0) return {
453
- status: "deferred",
454
- delayMs
455
- };
456
- const { actor, source } = events[0];
457
- const invocation = await createAgentInvocationFromLatest({
458
- input: renderEventBatchInputs(messages, await eventInboxItemInputs(messages)).map((input) => input.text).join("\n\n"),
459
- invocationId: getAgentInvocationIdForEvents(messages[0].inboundMessageId),
460
- latest,
461
- runAs: {
462
- actor,
463
- credentialContext: credentialContextForActor(actor, timerWatchCredentialSubject(context.conversationId, messages)),
464
- source
465
- }
466
- });
467
- await enqueueAgentInvocation(invocation, {
468
- ...options,
469
- eventMeta: eventBatchMessageMeta(messages)
470
- });
471
- await context.attempt.ack();
472
- return { status: "completed" };
473
- }
474
- for (const [index, message] of messages.entries()) {
475
- const parentMessage = readParentMessage(message);
476
- if (routes[index] === "dropped") {
477
- if (parentMessage) logDroppedParentMessage(message, parentMessage);
478
- continue;
479
- }
480
- if (parentMessage) {
481
- await enqueueAgentInvocation(await createAgentInvocationFromLatest({
482
- input: message.input.text.trim(),
483
- invocationId: getAgentInvocationIdForMessage(message.inboundMessageId),
484
- latest,
485
- runAs: {
486
- actor: parentMessage.actor,
487
- credentialContext: parentMessage.credentialContext,
488
- fork: parentMessage.fork,
489
- parentToolCallId: parentMessage.parentToolCallId
490
- }
491
- }), options);
492
- continue;
493
- }
494
- const input = inputs[index];
495
- const { invocation: source } = await getChildAgentInputSender(message, input);
496
- const invocation = await createAgentInvocationFromLatest({
497
- input: message.input.text.trim(),
498
- invocationId: input.kind === "result" && source ? getAgentInvocationIdForResult(source.invocationId) : getAgentInvocationIdForMessage(message.inboundMessageId),
499
- latest,
500
- ...input.kind === "result" && source ? { runAs: {
501
- actor: source.actor,
502
- credentialContext: source.credentialContext
503
- } } : void 0
504
- });
505
- await enqueueAgentInvocation(invocation, {
506
- ...options,
507
- eventMeta: eventBatchMessageMeta([message])
508
- });
509
- }
510
- await context.attempt.ack();
511
- return { status: "completed" };
512
- }
513
- /**
514
- * Build the worker for all work of a child Conversation. The caller selects
515
- * it from the stored kind of the Conversation, never from a Turn Source. A
516
- * parent task or message runs on its agent invocation. Every other input,
517
- * such as a person's Message in a Thread, a Watch Event, or a reply or result
518
- * of the child's own child agent, runs on the Conversation loop,
519
- * like input to a root.
520
- */
521
- function createChildConversationWorker(agentRunner, options) {
522
- const invocationWorker = createAgentInvocationWorker(agentRunner, {
523
- ...options,
524
- sendReply: async (sender, reply) => await enqueueChildResultToParent({
525
- result: {
526
- kind: "reply",
527
- reply
528
- },
529
- messageKey: reply.toolCallId,
530
- queue: options.queue,
531
- sender,
532
- state: options.state,
533
- turnId: getAgentInvocationTurnId(sender.invocationId)
534
- })
535
- });
536
- return async (context) => {
537
- const invocationId = await resolveAgentInvocationId(context);
538
- if (invocationId) return await invocationWorker(context, invocationId);
539
- const started = await startAgentInvocationsForChildInput(context, options);
540
- if (started) return started;
541
- const work = await resolveMailboxTurnWork(context);
542
- if (!work) {
543
- await context.attempt.ack();
544
- return { status: "completed" };
545
- }
546
- if (work.kind === "mailbox") await endActiveAgentInvocations(context.conversationId, {
547
- enqueueResult: options.enqueueResult,
548
- 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."
549
- });
550
- const kept = await withAgentInvocationResultActors(work);
551
- if (!kept) {
552
- await context.attempt.ack();
553
- return { status: "completed" };
554
- }
555
- const result = await options.runTurn(context, kept);
556
- if (result.status === "completed") await reportParentWithoutOpenWork(context.conversationId, options);
557
- return result;
558
- };
559
- }
560
- /**
561
- * A completed Turn of a child that no Agent invocation names can end the
562
- * last open work of its parent, such as a Turn that ends with `noReply`. A
563
- * `replaced` result of that parent then reports, as when a child row ends.
564
- * A child with a row reports when its row ends, as on `main`.
565
- *
566
- * TODO(dcramer): Remove with the `replaced` result (#3060 step 7).
567
- */
568
- async function reportParentWithoutOpenWork(conversationId, options) {
569
- if (await getLatestAgentInvocationForConversation(conversationId)) return;
570
- const sender = await readChildConversationSender(conversationId);
571
- const replaced = sender ? await reportReplacedWithoutOpenWork(sender.parentConversationId) : void 0;
572
- if (replaced && isTerminalAgentInvocation(replaced)) await enqueueAgentInvocationResult(replaced, options);
573
- }
574
- export { enqueueAgentMessageToParent as a, enqueueAgentInvocationResult as i, createDeliverToParent as n, result_exports as o, createEndStoppedChildWork as r, withAgentInvocationResultActors as s, createChildConversationWorker as t };
@@ -1,48 +0,0 @@
1
- import * as z from "zod";
2
- // src/chat/todos/types.ts
3
- /** Statuses of a To-do. `done` and `dropped` close it. */
4
- const TODO_STATUSES = [
5
- "open",
6
- "in_progress",
7
- "done",
8
- "dropped"
9
- ];
10
- /** Statuses of a To-do that is still work to do. */
11
- const OPEN_TODO_STATUSES = ["open", "in_progress"];
12
- /** Whether a To-do with this status is still work to do. */
13
- function isOpenTodoStatus(status) {
14
- return status === "open" || status === "in_progress";
15
- }
16
- /** Model-facing tool that changes the To-dos. */
17
- const UPDATE_TODOS_TOOL_NAME = "updateTodos";
18
- /** Assignee text for the list's own agent, in tool results and blocks. */
19
- const SELF_TODO_ASSIGNEE = "self";
20
- // src/api/schema/user-customization.ts
21
- /** Longest customization text one user can save. */
22
- const USER_CUSTOMIZATION_MAX_CHARS = 1e3;
23
- /** Saved customization text. An empty string means none. */
24
- const userCustomizationTextSchema = z.string().trim().max(USER_CUSTOMIZATION_MAX_CHARS);
25
- /** Request and response body for the viewer's customization. */
26
- const userCustomizationSchema = z.object({ customization: userCustomizationTextSchema }).strict();
27
- // src/chat/agent-invocations/result-event-type.ts
28
- /** Event namespace of the messages between a parent and its child agents. */
29
- const AGENT_INVOCATION_EVENT_NAMESPACE = "junior";
30
- const AGENT_INVOCATION_RESULT_EVENT_TYPE_PREFIX = "agent_invocation.";
31
- /** Build the Event type of the parent message for one agent invocation result. */
32
- function agentInvocationResultEventType(status) {
33
- return `${AGENT_INVOCATION_RESULT_EVENT_TYPE_PREFIX}${status}`;
34
- }
35
- /** True when an Event type names an agent invocation result. */
36
- function isAgentInvocationResultEventType(eventType) {
37
- return eventType.startsWith(AGENT_INVOCATION_RESULT_EVENT_TYPE_PREFIX);
38
- }
39
- /** Event type of the `reply` that ends a child agent's Turn. */
40
- const AGENT_REPLY_EVENT_TYPE = "agent.reply";
41
- /** Event type of a message that a child agent sends to its parent. */
42
- const AGENT_MESSAGE_EVENT_TYPE = "agent.message";
43
- /**
44
- * Event type of a parent agent task or message to a child that no agent
45
- * invocation names.
46
- */
47
- const AGENT_PARENT_MESSAGE_EVENT_TYPE = "agent.parent_message";
48
- export { agentInvocationResultEventType as a, userCustomizationSchema as c, SELF_TODO_ASSIGNEE as d, TODO_STATUSES as f, AGENT_REPLY_EVENT_TYPE as i, userCustomizationTextSchema as l, isOpenTodoStatus as m, AGENT_MESSAGE_EVENT_TYPE as n, isAgentInvocationResultEventType as o, UPDATE_TODOS_TOOL_NAME as p, AGENT_PARENT_MESSAGE_EVENT_TYPE as r, USER_CUSTOMIZATION_MAX_CHARS as s, AGENT_INVOCATION_EVENT_NAMESPACE as t, OPEN_TODO_STATUSES as u };