@sentry/junior 0.318.0 → 0.319.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 (92) hide show
  1. package/dist/{context-BKF_5zzI.js → adapter-8_S6Birm.js} +537 -537
  2. package/dist/{admin-UOHix_5P.js → admin-EsbUON1j.js} +1 -1
  3. package/dist/{agent-runner-DeYymwh2.js → agent-CtzMl32d.js} +18608 -5452
  4. package/dist/{agent-status-BA5x3Xtp.js → agent-status-Bq_AIpyp.js} +105 -1
  5. package/dist/{agent-update-delivery-DH8bx7jU.js → agent-update-delivery-pAvsbuGL.js} +4 -5
  6. package/dist/api/schema.d.ts +43 -23
  7. package/dist/api/schema.js +4 -4
  8. package/dist/api.js +70 -80
  9. package/dist/{app-DKAOuaoC.d.ts → app-tACXxJPI.d.ts} +4 -4
  10. package/dist/app.d.ts +2 -2
  11. package/dist/app.js +213 -91
  12. package/dist/{change-record-BzJgLsv7.d.ts → change-record-K-KsqNhT.d.ts} +9 -5
  13. package/dist/{channel-access-A0de5lRv.js → channel-access-DET5hzZM.js} +1 -1
  14. package/dist/{chat-core-engine-D3Wd7f5n.js → chat-core-engine-DpM3tMVi.js} +5 -5
  15. package/dist/cli/chat.d.ts +1 -1
  16. package/dist/cli/chat.js +23 -23
  17. package/dist/cli/check.js +5 -5
  18. package/dist/cli/main.js +2 -2
  19. package/dist/cli/plugins.d.ts +1 -1
  20. package/dist/cli/plugins.js +8 -8
  21. package/dist/cli/snapshot-create.js +5 -5
  22. package/dist/cli/upgrade.d.ts +1 -1
  23. package/dist/cli/upgrade.js +3 -4
  24. package/dist/{continue-in-slack-YxwMQVeR.js → continue-in-slack-CFzDyxkH.js} +3 -3
  25. package/dist/{conversation-feed-Cj7IuBtM.js → conversation-feed-DEUdD7mb.js} +2 -106
  26. package/dist/{conversation-privacy-Cr_dNW1p.js → conversation-privacy-C2vYK55O.js} +1 -1
  27. package/dist/{create-Btl1y1rq.js → create-Ta3SEIB5.js} +115 -5
  28. package/dist/{credential-sync-DTarZ63K.js → credential-sync-DyRqDmY4.js} +15 -18
  29. package/dist/{db-of6e3sGt.js → db-BCaNWl9p.js} +4579 -717
  30. package/dist/{deployment-C0qXa0FD.js → deployment-CfOew1Tm.js} +3 -3
  31. package/dist/{engine-context-C_QL_bMQ.js → engine-context-CiExoy1B.js} +144 -149
  32. package/dist/{html-9_pS9SjY.js → html-Bb2Si1bR.js} +6 -8
  33. package/dist/instrumentation.js +7 -23
  34. package/dist/list-wwDcROh9.js +5007 -0
  35. package/dist/{logging-BnOG0qz2.js → logging-BRPTXAdf.js} +8 -33
  36. package/dist/{mailbox-turn-Byrry9o1.js → markers-9QoqW5ov.js} +1675 -1255
  37. package/dist/nitro.d.ts +2 -2
  38. package/dist/nitro.js +6 -7
  39. package/dist/{oauth-callback-server-CjnnUr4o.js → oauth-callback-server-vhL9b-PZ.js} +2 -2
  40. package/dist/{oauth-relay-BvHFH0fV.js → oauth-relay-CH2v7WiB.js} +1 -1
  41. package/dist/{plugins-fBrz8PCV.d.ts → plugins-DhGXZjlu.d.ts} +1 -0
  42. package/dist/{profile-iHw1uu32.js → profile-D9LdwmZi.js} +16 -18
  43. package/dist/{prompt-DEkStuxG.js → prompt-3TqxEOtc.js} +1 -1
  44. package/dist/{reports-C1d9azyV.js → reports-K-tbtEyx.js} +2 -2
  45. package/dist/{resolve-DC6zBuDV.js → resolve-BBV2qf8A.js} +5 -5
  46. package/dist/{result-DxewDuXb.js → result-5IdGJP4M.js} +20 -9
  47. package/dist/{runner-99YxVN_r.js → runner-BK_joPlM.js} +7 -8
  48. package/dist/{sandbox-egress-signals-CgoX5CTI.js → sandbox-egress-signals-DXgWXXmm.js} +1 -1
  49. package/dist/{schema-BTojNBr5.js → schema-zWGG6VC1.js} +13 -7
  50. package/dist/{service-account-YDCPSByj.js → service-account-CateFyhw.js} +4 -5
  51. package/dist/{skills-CleC0Hze.js → skills-Ccjw8h2P.js} +9 -9
  52. package/dist/{slack-conversation-unfurl-BNQLC12R.js → slack-conversation-unfurl-ZC_TSpc4.js} +7 -7
  53. package/dist/storage-C9U7R5rM.js +273 -0
  54. package/dist/{system-prompt-table-Ci6Ck4gk.js → system-prompt-table-YBTHIFlP.js} +26 -84
  55. package/dist/topic-B2EWKKBT.js +6 -0
  56. package/dist/{package-discovery-DD9vencX.js → topics-DxuKurCX.js} +21 -1
  57. package/dist/{types-DCzTAA63.js → types-BNHkJrOP.js} +25 -11
  58. package/dist/{users-Cb9c1k9q.js → users-CCRAqYb_.js} +1 -1
  59. package/dist/{validation-BiUmWPhy.js → validation-BCUpJa8K.js} +4 -4
  60. package/dist/{version-VEXiEcZu.js → version-BNm0JYj3.js} +1 -1
  61. package/dist/version.js +1 -1
  62. package/dist/{worker-ChWYQdhm.js → worker-BhgpZ7_b.js} +4 -4
  63. package/migrations/20261127052408_space_name_nullable/migration.sql +5 -0
  64. package/migrations/20261127052408_space_name_nullable/snapshot.json +29 -0
  65. package/migrations/20261127060000_annotation_object_id_index/migration.sql +1 -0
  66. package/migrations/20261127060000_annotation_object_id_index/snapshot.json +69 -0
  67. package/migrations/20261127060001_annotation_subjects/migration.sql +78 -0
  68. package/migrations/20261127060001_annotation_subjects/snapshot.json +104 -0
  69. package/migrations/20261127060002_annotation_subject_index/migration.sql +1 -0
  70. package/migrations/20261127060002_annotation_subject_index/snapshot.json +70 -0
  71. package/migrations/20261127060003_annotation_title_url/migration.sql +84 -0
  72. package/migrations/20261127060003_annotation_title_url/snapshot.json +73 -0
  73. package/package.json +9 -7
  74. package/dist/auth-pause-state-f9hJM_zO.js +0 -113
  75. package/dist/catalog-runtime-BfdAnztW.js +0 -6
  76. package/dist/child-message-peFWLcCZ.js +0 -15
  77. package/dist/conversation-turn-Bru4w_FD.js +0 -1250
  78. package/dist/job-runner-B2XEvpif.js +0 -1505
  79. package/dist/lineage-nh4z9iQN.js +0 -36
  80. package/dist/list-HRP3TIRl.js +0 -12631
  81. package/dist/markers-CTTtJqYn.js +0 -342
  82. package/dist/message-BRUuLgrY.js +0 -153
  83. package/dist/model-input-CFC62mf-.js +0 -82
  84. package/dist/registry-Cl7Labpe.js +0 -3279
  85. package/dist/run-conversation-Cz2ubZK-.js +0 -337
  86. package/dist/sender-actors-77zTQbSG.js +0 -84
  87. package/dist/spawn-DuZfodPa.js +0 -45
  88. package/dist/task-runner-BJ9Up3bG.js +0 -1529
  89. package/dist/topic-CRYYBYp-.js +0 -7
  90. package/dist/topics-BoCkoPJJ.js +0 -21
  91. package/dist/turn-membership-VT7XZh-L.js +0 -856
  92. package/dist/turn-wake-C7HeLHAM.js +0 -151
@@ -1,342 +0,0 @@
1
- import { Fn as readInboundMessageSender, In as isEventMailboxMetadata, Pn as readParentMessage, U as conversationLastTurnOutcomeSql, Zd as juniorAgentBindings, an as getConversationWorkState, cs as conversationSubtreeColumns, hf as juniorConversations, i as getConversationStore, if as juniorConversationEvents, jl as isPersonInput, n as getConversationEventStore, o as getSqlExecutor, on as getConversationWorkStates, ss as conversationSubtree } from "./db-of6e3sGt.js";
2
- import { Hn as isAgentUpdateEventType } from "./types-DCzTAA63.js";
3
- import { G as mapBounded } from "./prompt-DEkStuxG.js";
4
- import { Er as TURN_OUTCOME_STATUSES, Vt as buildDeterministicTurnId, b as readAgentConfig, i as listActiveMailboxTurns, m as hasParentMessageAuthor, r as listActiveMailboxTurnSources } from "./mailbox-turn-Byrry9o1.js";
5
- import * as z from "zod";
6
- import { and, desc, eq, inArray, isNotNull, ne, sql } from "drizzle-orm";
7
- import { alias } from "drizzle-orm/pg-core";
8
- // src/chat/child-agents/child-input.ts
9
- const parent = alias(juniorConversations, "parent");
10
- function childAgentInputKind(namespace, eventType, watchId) {
11
- if (namespace !== "junior" || !eventType) return;
12
- if (eventType === "agent.message") return "message";
13
- return isAgentUpdateEventType(eventType) && watchId === void 0 ? "reply" : void 0;
14
- }
15
- /** Read the child that one reply or message Event names. */
16
- function childAgentInput(message) {
17
- const metadata = message.input.metadata;
18
- if (!isEventMailboxMetadata(metadata)) return;
19
- const kind = childAgentInputKind(metadata.event.namespace, metadata.event.eventType, metadata.event.subscriptionId);
20
- return kind ? {
21
- kind,
22
- senderId: metadata.event.identifier
23
- } : void 0;
24
- }
25
- /**
26
- * Whether one input is the `stopped` result that the stop of its sender
27
- * sends. Only a stop reports `stopped`, so the stored status tells this
28
- * result from the reply of a Turn.
29
- */
30
- function isStopResult(message) {
31
- const metadata = message.input.metadata;
32
- return isEventMailboxMetadata(metadata) && metadata.event.namespace === "junior" && isAgentUpdateEventType(metadata.event.eventType) && metadata.event.status === "stopped";
33
- }
34
- /**
35
- * Whether the saved Event fields of a Turn's input Message name a child
36
- * agent's reply or message. A new and a resumed Turn read the same fields.
37
- */
38
- function isChildAgentEvent(meta) {
39
- return Boolean(childAgentInputKind(meta?.eventNamespace, meta?.eventType, meta?.eventWatchId));
40
- }
41
- /**
42
- * Return the stored parent edge that a parent message claims, or undefined
43
- * when its author id is not that parent's, so it is dropped with no read.
44
- */
45
- function claimedParentEdge(message, parentMessage) {
46
- return hasParentMessageAuthor(message, parentMessage) ? parentEdgeKey(message.conversationId, parentMessage.parentConversationId) : void 0;
47
- }
48
- function parentEdgeKey(childConversationId, parentConversationId) {
49
- return JSON.stringify([childConversationId, parentConversationId]);
50
- }
51
- /**
52
- * Return the child that sent a reply that a stop can skip. A message that a
53
- * child sent is still delivered, and so is the `stopped` result that a
54
- * person's stop sends.
55
- */
56
- function skippableReplySender(message) {
57
- if (childAgentInput(message)?.kind !== "reply" || isStopResult(message)) return;
58
- return readInboundMessageSender(message)?.conversationId;
59
- }
60
- /**
61
- * Read the stops that `isDroppedChildInput` needs for many inputs, with one
62
- * query for the receiving children and one for the reply senders.
63
- */
64
- async function readChildInputDropFacts(messages) {
65
- const childIds = /* @__PURE__ */ new Set();
66
- const parentIds = /* @__PURE__ */ new Set();
67
- const senderIds = /* @__PURE__ */ new Set();
68
- for (const message of messages) {
69
- const parentMessage = readParentMessage(message);
70
- if (parentMessage) {
71
- if (claimedParentEdge(message, parentMessage)) {
72
- childIds.add(message.conversationId);
73
- parentIds.add(parentMessage.parentConversationId);
74
- }
75
- continue;
76
- }
77
- const sender = skippableReplySender(message);
78
- if (sender) senderIds.add(sender);
79
- }
80
- const db = getSqlExecutor().db();
81
- const [children, senders] = await Promise.all([childIds.size > 0 ? db.select({
82
- conversationId: juniorConversations.conversationId,
83
- parentConversationId: parent.conversationId,
84
- stoppedAt: juniorConversations.stoppedAt
85
- }).from(juniorConversations).innerJoin(parent, eq(parent.conversationId, juniorConversations.parentConversationId)).where(and(inArray(juniorConversations.conversationId, [...childIds]), inArray(parent.conversationId, [...parentIds]))) : [], senderIds.size > 0 ? db.select({
86
- conversationId: juniorConversations.conversationId,
87
- stoppedAt: juniorConversations.stoppedAt
88
- }).from(juniorConversations).where(inArray(juniorConversations.conversationId, [...senderIds])) : []]);
89
- return {
90
- childStops: new Map(children.map((row) => [parentEdgeKey(row.conversationId, row.parentConversationId), row.stoppedAt])),
91
- senderStops: new Map(senders.flatMap((row) => row.stoppedAt ? [[row.conversationId, row.stoppedAt]] : []))
92
- };
93
- }
94
- /**
95
- * Return whether a Conversation drops one input, so it starts no work.
96
- * Routing and the child agent status both read this, so they agree on which
97
- * input starts work. `facts` must come from `readChildInputDropFacts` for
98
- * this input.
99
- *
100
- * A parent message is dropped when it does not come from the stored parent,
101
- * or when it was sent before the child's stop. A stop drops a child's unread
102
- * replies from the parent's mailbox. One sent before the stop can reach the
103
- * mailbox after that drop, so while the sending child is stopped, a reply
104
- * that it sent after the stop is dropped too. A stopped Conversation never
105
- * reads other automated input: `enqueueAutomatedInput` and the stop hold it
106
- * first.
107
- */
108
- function isDroppedChildInput(message, facts) {
109
- if (isPersonInput(message.source)) return false;
110
- const parentMessage = readParentMessage(message);
111
- if (parentMessage) {
112
- const edge = claimedParentEdge(message, parentMessage);
113
- if (!edge || !facts.childStops.has(edge)) return true;
114
- const stoppedAtMs = facts.childStops.get(edge)?.getTime();
115
- return stoppedAtMs !== void 0 && message.receivedAtMs <= stoppedAtMs;
116
- }
117
- const sender = skippableReplySender(message);
118
- const senderStoppedAtMs = sender ? facts.senderStops.get(sender)?.getTime() : void 0;
119
- return senderStoppedAtMs !== void 0 && message.createdAtMs >= senderStoppedAtMs;
120
- }
121
- /**
122
- * Read the sender of one child Conversation from its parent edge and its
123
- * binding. A Conversation without a parent has none.
124
- */
125
- async function readChildConversationSender(childConversationId) {
126
- const [row] = await getSqlExecutor().db().select({
127
- agentName: juniorAgentBindings.name,
128
- parentConversationId: parent.conversationId,
129
- parentKind: parent.kind,
130
- title: juniorConversations.title
131
- }).from(juniorConversations).innerJoin(parent, eq(parent.conversationId, juniorConversations.parentConversationId)).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(eq(juniorConversations.conversationId, childConversationId));
132
- return row ? {
133
- ...row.agentName ? { agentName: row.agentName } : void 0,
134
- childConversationId,
135
- parentConversationId: row.parentConversationId,
136
- ...row.parentKind ? { parentKind: row.parentKind } : void 0,
137
- ...row.title ? { title: row.title } : void 0
138
- } : void 0;
139
- }
140
- /**
141
- * Read the sender of one reply or message, when it is a child of the
142
- * Conversation that received it. Input that names no child of this
143
- * Conversation has no sender, so `withSenderActors` runs it as the Event
144
- * system Actor and it gets no child's authority.
145
- */
146
- async function getChildAgentInputSender(message, input) {
147
- const sender = await readChildConversationSender(input.senderId);
148
- return sender?.parentConversationId === message.conversationId ? sender : void 0;
149
- }
150
- // src/chat/child-agents/list.ts
151
- const childConversationKindSchema = z.enum(["thread", "task"]);
152
- /** Bound the child agents that one listing reads. */
153
- const CHILD_AGENT_LIST_LIMIT = 200;
154
- /**
155
- * List the direct child agents of one parent Conversation, with the newest
156
- * activity first. The state comes from each child's Turns and mailbox, not
157
- * from model output. Each child agent stores its agent config, so older
158
- * children of a parent, such as ones that a removed feature created, are not
159
- * listed. A child is `stopped` while stopped, `running` while a Turn or
160
- * mailbox input that answers its parent is open, `failed` when its stored
161
- * execution failed, such as when its worker gave up and no Turn ended, and
162
- * else `idle`.
163
- * `lastResult` is how its newest finished Turn that was not stopped ended:
164
- * the status that `readTurnUpdate` gives it, or `failed`.
165
- */
166
- async function listChildAgents(parentConversationId) {
167
- const rows = await getSqlExecutor().db().select({
168
- agentName: juniorAgentBindings.name,
169
- archivedAt: juniorConversations.archivedAt,
170
- conversationId: juniorConversations.conversationId,
171
- executionStatus: juniorConversations.executionStatus,
172
- executionUpdatedAt: juniorConversations.executionUpdatedAt,
173
- kind: juniorConversations.kind,
174
- lastTurnOutcome: conversationLastTurnOutcomeSql(juniorConversations),
175
- stoppedAt: juniorConversations.stoppedAt,
176
- title: juniorConversations.title,
177
- updatedAt: juniorConversations.updatedAt
178
- }).from(juniorConversations).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(and(eq(juniorConversations.parentConversationId, parentConversationId), isNotNull(juniorConversations.agentConfig))).orderBy(desc(sql`coalesce(${juniorConversations.executionUpdatedAt}, ${juniorConversations.updatedAt})`)).limit(CHILD_AGENT_LIST_LIMIT);
179
- const ids = rows.map((row) => row.conversationId);
180
- const [workStates, mailboxTurnSources] = await Promise.all([getConversationWorkStates(ids), listActiveMailboxTurnSources(ids)]);
181
- const pendingInput = (conversationId) => workStates.get(conversationId)?.execution.pendingMessages ?? [];
182
- const dropFacts = await readChildInputDropFacts(rows.flatMap((row) => row.stoppedAt ? [] : pendingInput(row.conversationId)));
183
- return rows.map((row) => {
184
- const kind = childConversationKindSchema.parse(row.kind);
185
- const stoppedAtMs = row.stoppedAt?.getTime();
186
- const running = stoppedAtMs === void 0 && runsOnConversationLoop(pendingInput(row.conversationId), mailboxTurnSources.get(row.conversationId) ?? [], dropFacts);
187
- const outcome = row.lastTurnOutcome;
188
- const lastResult = outcome === "failed" ? "failed" : outcome ? TURN_OUTCOME_STATUSES[outcome] : void 0;
189
- return {
190
- ...row.agentName ? { agentName: row.agentName } : void 0,
191
- ...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
192
- childConversationId: row.conversationId,
193
- kind,
194
- ...lastResult ? { lastResult } : void 0,
195
- status: stoppedAtMs !== void 0 ? "stopped" : running ? "running" : row.executionStatus === "failed" ? "failed" : "idle",
196
- ...row.title ? { title: row.title } : void 0,
197
- updatedAtMs: (row.executionUpdatedAt ?? row.updatedAt).getTime()
198
- };
199
- }).sort((left, right) => right.updatedAtMs - left.updatedAtMs);
200
- }
201
- /** List the ids of the child agents of one parent that have open work. */
202
- async function listOpenChildAgents(parentConversationId) {
203
- return (await listChildAgents(parentConversationId)).filter((child) => child.status === "running").map((child) => child.childConversationId);
204
- }
205
- /**
206
- * Return whether a child has work that will answer its parent: `pending`
207
- * input that waits in the mailbox until its Turn commits it, such as a Watch
208
- * Event in its debounce window, or an open mailbox Turn. Every Turn of a
209
- * child answers its parent, whoever started it.
210
- */
211
- function runsOnConversationLoop(pending, mailboxTurnSources, dropFacts) {
212
- return mailboxTurnSources.length > 0 || pending.some((message) => !isDroppedChildInput(message, dropFacts));
213
- }
214
- /**
215
- * List the ids of a child's open Turns on the Conversation loop. A Turn keeps
216
- * its input in the mailbox until it commits it, so before its first
217
- * checkpoint its id comes from its first input. Attempt selection can take
218
- * any pending input first, so each one gives a candidate id.
219
- */
220
- async function listOpenLoopTurnIds(conversationId) {
221
- const [turns, work] = await Promise.all([listActiveMailboxTurns(conversationId), getConversationWorkState({ conversationId })]);
222
- return [...turns.map((turn) => turn.turnId), ...(work?.execution.pendingMessages ?? []).map((message) => buildDeterministicTurnId(message.inboundMessageId))];
223
- }
224
- async function listAnsweredLoopChildren(children, parentMessages) {
225
- if (children.length === 0 || parentMessages.length === 0) return [];
226
- return (await mapBounded(children, async ({ childConversationId }) => {
227
- const turnIds = await listOpenLoopTurnIds(childConversationId);
228
- return parentMessages.some(({ sender }) => sender.conversationId === childConversationId && turnIds.includes(sender.turnId)) ? childConversationId : void 0;
229
- })).filter((id) => id !== void 0);
230
- }
231
- /**
232
- * List the other child agents of one parent that still run and have not
233
- * answered. A running child whose open Turn's result is already among
234
- * `parentMessages`, the child replies and results that reached the parent's
235
- * mailbox, has answered, so it does not count.
236
- */
237
- async function listUnreportedSiblingAgents(parentConversationId, childConversationId, parentMessages) {
238
- const running = (await listChildAgents(parentConversationId)).filter((child) => child.childConversationId !== childConversationId && child.status === "running");
239
- const answered = new Set(await listAnsweredLoopChildren(running, parentMessages));
240
- return running.filter((child) => !answered.has(child.childConversationId));
241
- }
242
- /**
243
- * List every child agent below one Conversation, at any depth. A parent owns
244
- * the work of its child agents and of their child agents. The list never has
245
- * the Conversation itself, its parent, or a sibling.
246
- */
247
- async function listDescendantAgents(conversationId) {
248
- return (await getSqlExecutor().db().select({
249
- conversationId: juniorConversations.conversationId,
250
- name: juniorAgentBindings.name
251
- }).from(juniorConversations).innerJoin(conversationSubtree([conversationId]), eq(conversationSubtreeColumns.conversationId, juniorConversations.conversationId)).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(ne(juniorConversations.conversationId, conversationId)).orderBy(juniorConversations.conversationId)).map((row) => ({
252
- conversationId: row.conversationId,
253
- ...row.name ? { name: row.name } : void 0
254
- }));
255
- }
256
- /**
257
- * List the agents that one Conversation can see. A root Conversation sees
258
- * only its child agents. A child agent also sees itself, its parent, and the
259
- * other child agents of its parent.
260
- */
261
- async function listAgentRelatives(input) {
262
- const { conversationId, parentConversationId } = input;
263
- const [children, family, parent] = await Promise.all([
264
- listChildAgents(conversationId),
265
- parentConversationId ? listChildAgents(parentConversationId) : [],
266
- parentConversationId ? getConversationStore().get({ conversationId: parentConversationId }) : void 0
267
- ]);
268
- const self = family.find((agent) => agent.childConversationId === conversationId);
269
- return {
270
- children,
271
- ...parent ? { parent: {
272
- conversationId: parent.conversationId,
273
- status: parent.execution.status,
274
- updatedAtMs: parent.execution.updatedAtMs ?? parent.updatedAtMs
275
- } } : void 0,
276
- ...self ? { self } : void 0,
277
- siblings: family.filter((agent) => agent.childConversationId !== conversationId)
278
- };
279
- }
280
- // src/chat/child-agents/markers.ts
281
- const SUBAGENT_KIND = "agent";
282
- const SUBAGENT_STARTED_KEY_PREFIX = "subagent_started:";
283
- const SUBAGENT_ENDED_KEY_PREFIX = "subagent_ended:";
284
- /**
285
- * Record in the parent Conversation that a child agent got one task or
286
- * message. Write it before the input reaches the child's mailbox, so the
287
- * child cannot end first.
288
- */
289
- async function recordSubagentStartedMarker(start) {
290
- await getConversationEventStore().append(start.parentConversationId, [{
291
- idempotencyKey: `${SUBAGENT_STARTED_KEY_PREFIX}${start.markerId}`,
292
- data: {
293
- type: "subagent_started",
294
- subagentInvocationId: start.markerId,
295
- subagentKind: SUBAGENT_KIND,
296
- childConversationId: start.childConversationId,
297
- ...start.agentName ? { agentName: start.agentName } : void 0,
298
- parentToolCallId: start.parentToolCallId,
299
- task: start.input,
300
- ...start.title ? { title: start.title } : void 0,
301
- ...start.reasoningLevel ? { reasoningLevel: start.reasoningLevel } : void 0
302
- },
303
- createdAtMs: start.createdAtMs
304
- }]);
305
- }
306
- /**
307
- * Record in the parent Conversation how the work of a child agent ended.
308
- * Each parent message has its own `subagent_started` marker, named by the
309
- * message id, and each one that the child already took ends with `outcome`.
310
- * A parent message that still waits in the child's mailbox stays open,
311
- * because later work reads it, unless `includeWaiting` is set, as for a stop
312
- * that skips it. Write it before the child's result reaches the parent.
313
- */
314
- async function recordChildAgentEnded(childConversationId, outcome, options = {}) {
315
- if (!await readAgentConfig(childConversationId)) return;
316
- const work = await getConversationWorkState({
317
- conversationId: childConversationId,
318
- state: options.state
319
- });
320
- const running = new Set(work?.runningInboundMessageIds);
321
- const waiting = new Set(options.includeWaiting ? [] : (work?.messages ?? []).map((message) => message.inboundMessageId).filter((id) => !running.has(id)));
322
- const taken = (work?.execution.inboundMessageIds ?? []).filter((id) => !waiting.has(id));
323
- if (taken.length === 0) return;
324
- const sender = await readChildConversationSender(childConversationId);
325
- if (!sender) return;
326
- const keys = await getSqlExecutor().db().select({ idempotencyKey: juniorConversationEvents.idempotencyKey }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, sender.parentConversationId), inArray(juniorConversationEvents.idempotencyKey, taken.flatMap((id) => [`${SUBAGENT_STARTED_KEY_PREFIX}${id}`, `${SUBAGENT_ENDED_KEY_PREFIX}${id}`]))));
327
- const found = new Set(keys.map((row) => row.idempotencyKey));
328
- const open = taken.filter((id) => found.has(`${SUBAGENT_STARTED_KEY_PREFIX}${id}`) && !found.has(`${SUBAGENT_ENDED_KEY_PREFIX}${id}`));
329
- if (open.length > 0) await appendSubagentEnded(sender.parentConversationId, open, outcome, options.nowMs ?? Date.now());
330
- }
331
- async function appendSubagentEnded(parentConversationId, markerIds, outcome, createdAtMs) {
332
- await getConversationEventStore().append(parentConversationId, markerIds.map((id) => ({
333
- idempotencyKey: `${SUBAGENT_ENDED_KEY_PREFIX}${id}`,
334
- data: {
335
- type: "subagent_ended",
336
- subagentInvocationId: id,
337
- outcome
338
- },
339
- createdAtMs
340
- })));
341
- }
342
- export { listDescendantAgents as a, childAgentInput as c, isDroppedChildInput as d, isStopResult as f, listChildAgents as i, getChildAgentInputSender as l, readChildInputDropFacts as m, recordSubagentStartedMarker as n, listOpenChildAgents as o, readChildConversationSender as p, listAgentRelatives as r, listUnreportedSiblingAgents as s, recordChildAgentEnded as t, isChildAgentEvent as u };
@@ -1,153 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { F as AgentMessageTargetError, b as actorFromRun } from "./agent-runner-DeYymwh2.js";
3
- import { $s as SYSTEM_IDENTITY_ID, It as PARENT_AGENT_TARGET, Kl as CORE_EVENT_NAMESPACE, Nt as findChildAgentConversationId, _r as canAccessConversation, a as getDb, i as getConversationStore, wr as readConversationAccessFromSql } from "./db-of6e3sGt.js";
4
- import { p as readChildConversationSender } from "./markers-CTTtJqYn.js";
5
- import { n as enqueueAgentMessageToParent } from "./result-DxewDuXb.js";
6
- import { t as messageChildAgent } from "./create-Btl1y1rq.js";
7
- import { H as enqueueAutomatedInput, O as EVENT_WAIT_MS } from "./mailbox-turn-Byrry9o1.js";
8
- import { H as renderDataTag } from "./prompt-DEkStuxG.js";
9
- import { Bn as TOP_LEVEL_AGENT_MESSAGE_EVENT_TYPE } from "./types-DCzTAA63.js";
10
- // src/chat/child-agents/top-level-message.ts
11
- /**
12
- * Check that a top-level agent can message another top-level agent under
13
- * `policies/conversation-access.md`. Public agents can message each other.
14
- * A private agent can message only agents at its own Destination, such as
15
- * another thread in the same private Slack channel.
16
- * Every target that the sender cannot reach gets the same error, so the
17
- * error does not show that a private Conversation exists.
18
- */
19
- async function requireTopLevelAgentAccess(args) {
20
- const notReachable = new AgentMessageTargetError(`"${args.to}" is not "${PARENT_AGENT_TARGET}", a child agent of this conversation, or a top-level agent that you can message`);
21
- if (args.to === args.senderConversationId) throw new AgentMessageTargetError(`"${args.to}" is this conversation`);
22
- const conversationStore = getConversationStore();
23
- const [senderConversation, target] = await Promise.all([conversationStore.get({ conversationId: args.senderConversationId }), conversationStore.get({ conversationId: args.to })]);
24
- if (senderConversation?.parentConversationId) throw new AgentMessageTargetError(`"${args.to}" is not "${PARENT_AGENT_TARGET}" or a child agent of this conversation`);
25
- if (!target || target.parentConversationId) throw notReachable;
26
- const access = await readConversationAccessFromSql(getDb(), [args.senderConversationId, args.to]);
27
- const sender = access.get(args.senderConversationId);
28
- const receiver = access.get(args.to);
29
- if (!sender || !receiver || !canAccessConversation({
30
- requester: sender,
31
- target: receiver
32
- })) throw notReachable;
33
- if (receiver.visibility === "public" && sender.visibility !== "public") throw new AgentMessageTargetError(`"${args.to}" is a public conversation and this conversation is private. A private conversation can message only conversations in its own channel or DM`);
34
- }
35
- function renderTopLevelMessageInput(args) {
36
- return renderDataTag("agent-message", {
37
- conversation_id: args.senderConversationId,
38
- source: "top_level_agent"
39
- }, "Another top-level agent", args.text.trim());
40
- }
41
- /**
42
- * Send one message from a top-level agent to another top-level agent and
43
- * wake the target. The access check runs on each call. A stopped target
44
- * holds the message, so once the automated-turn limit stops one of two
45
- * agents, they cannot keep each other running. Repeat calls with the same
46
- * `messageKey` are safe.
47
- */
48
- async function enqueueTopLevelAgentMessage(args) {
49
- await requireTopLevelAgentAccess(args);
50
- const nowMs = args.nowMs ?? Date.now();
51
- const inboundMessageId = `agent-message:${args.senderConversationId}:${args.messageKey}`;
52
- const summary = `Top-level agent ${args.senderConversationId} sent a message.`;
53
- const metadata = {
54
- kind: "event",
55
- event: {
56
- eventKey: inboundMessageId,
57
- eventType: TOP_LEVEL_AGENT_MESSAGE_EVENT_TYPE,
58
- identifier: args.senderConversationId,
59
- namespace: CORE_EVENT_NAMESPACE,
60
- trustedSummary: summary
61
- }
62
- };
63
- await enqueueAutomatedInput({
64
- message: {
65
- conversationId: args.to,
66
- createdAtMs: nowMs,
67
- delivery: "defer",
68
- inboundMessageId,
69
- input: {
70
- authorId: `agent-message:${args.senderConversationId}`,
71
- authorIdentityId: SYSTEM_IDENTITY_ID,
72
- metadata,
73
- text: renderTopLevelMessageInput({
74
- senderConversationId: args.senderConversationId,
75
- text: args.text
76
- })
77
- },
78
- receivedAtMs: nowMs,
79
- source: "event"
80
- },
81
- queue: args.queue,
82
- queueDelayMs: EVENT_WAIT_MS,
83
- state: args.state
84
- });
85
- }
86
- // src/chat/child-agents/message.ts
87
- var message_exports = /* @__PURE__ */ __exportAll({ bindMessageAgent: () => bindMessageAgent });
88
- /**
89
- * Bind a Run's Actor and credentials to messages for its parent and child
90
- * agents, and for other top-level agents. A message to a child continues that
91
- * child. A message to the parent wakes the parent like a result. A top-level
92
- * agent can also message another top-level agent that it has access to.
93
- */
94
- function bindMessageAgent(run, options) {
95
- const actor = actorFromRun(run);
96
- if (!actor) return;
97
- return async (input, call) => {
98
- call.signal?.throwIfAborted();
99
- const queue = typeof options.queue === "function" ? options.queue() : options.queue;
100
- if (input.to === "parent") {
101
- const sender = await readChildConversationSender(run.conversationId);
102
- if (!sender) throw new AgentMessageTargetError("This conversation has no parent agent");
103
- await enqueueAgentMessageToParent({
104
- actor,
105
- messageKey: `${run.turnId}:${call.toolCallId}`,
106
- queue,
107
- sender,
108
- state: options.state,
109
- text: input.text
110
- });
111
- return {
112
- conversationId: sender.parentConversationId,
113
- delivery: "queued"
114
- };
115
- }
116
- const childConversationId = await findChildAgentConversationId({
117
- parentConversationId: run.conversationId,
118
- target: input.to
119
- });
120
- if (!childConversationId) {
121
- await enqueueTopLevelAgentMessage({
122
- messageKey: `${run.turnId}:${call.toolCallId}`,
123
- queue,
124
- senderConversationId: run.conversationId,
125
- state: options.state,
126
- text: input.text,
127
- to: input.to
128
- });
129
- return {
130
- conversationId: input.to,
131
- delivery: "queued"
132
- };
133
- }
134
- const { delivery } = await messageChildAgent({
135
- actor,
136
- childConversationId,
137
- ...run.credentialContext ? { credentialContext: run.credentialContext } : void 0,
138
- idempotencyKey: `${run.turnId}:${call.toolCallId}`,
139
- input: input.text,
140
- parentConversationId: run.conversationId,
141
- parentToolCallId: call.toolCallId,
142
- parentTurnId: run.turnId
143
- }, {
144
- ...options,
145
- queue
146
- });
147
- return {
148
- conversationId: childConversationId,
149
- delivery
150
- };
151
- };
152
- }
153
- export { message_exports as n, bindMessageAgent as t };
@@ -1,82 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { o as getSqlExecutor } from "./db-of6e3sGt.js";
3
- import { o as detectImageMediaType, s as isVisionImageMediaType } from "./user-customization-CvfuY9Eo.js";
4
- import { d as readLiveAttachment } from "./turn-membership-VT7XZh-L.js";
5
- import { escapeTagText, renderTag } from "@sentry/junior-plugin-api";
6
- // src/chat/attachments/model-input.ts
7
- var model_input_exports = /* @__PURE__ */ __exportAll({ loadInputAttachments: () => loadInputAttachments });
8
- /** Largest file that Slack and web send to the model in the prompt. */
9
- const MAX_MODEL_ATTACHMENT_BYTES = 5242880;
10
- /**
11
- * Render the name and type lines of an attachment tag. The person who
12
- * attached the file chose its name, so both are escaped.
13
- */
14
- function attachmentFactLines(args) {
15
- return [`filename: ${escapeTagText(args.filename ?? "unnamed")}`, `media_type: ${escapeTagText(args.mediaType)}`];
16
- }
17
- /** Tell the model how to read a stored file that the prompt does not carry. */
18
- function buildStoredAttachmentPromptText(args) {
19
- return renderTag("attachment", {}, [
20
- ...attachmentFactLines(args),
21
- `attachment_id: ${args.attachmentId}`,
22
- "Use loadAttachment with this id to access the original file."
23
- ]);
24
- }
25
- async function readStoredBytes(args) {
26
- const record = await readLiveAttachment({
27
- attachmentId: args.attachment.id,
28
- conversationId: args.conversationId,
29
- db: getSqlExecutor()
30
- });
31
- if (!record || record.storageProvider !== args.storage.provider || record.storageKey === null) throw new Error("Input attachment is no longer available.");
32
- const body = await args.storage.get(record.storageKey);
33
- if (!body) throw new Error("Input attachment contents are unavailable.");
34
- const data = Buffer.from(await new Response(body).arrayBuffer());
35
- if (data.byteLength !== record.bytes) throw new Error("Input attachment size does not match stored metadata.");
36
- return data;
37
- }
38
- /**
39
- * Build model input for the stored files of one web Message.
40
- *
41
- * Like Slack, the first images within the size limit go to the model as
42
- * images. Every other file gets a note that points to `loadAttachment`.
43
- */
44
- async function loadInputAttachments(args) {
45
- let images = 0;
46
- return await Promise.all(args.attachments.map(async (attachment) => {
47
- const base = {
48
- attachmentId: attachment.id,
49
- filename: attachment.filename,
50
- mediaType: attachment.contentType
51
- };
52
- if (!(isVisionImageMediaType(attachment.contentType) && attachment.bytes <= 5242880 && images < 3)) return {
53
- ...base,
54
- promptText: buildStoredAttachmentPromptText({
55
- attachmentId: attachment.id,
56
- filename: attachment.filename,
57
- mediaType: attachment.contentType
58
- })
59
- };
60
- images += 1;
61
- const data = await readStoredBytes({
62
- attachment,
63
- conversationId: args.conversationId,
64
- storage: args.storage
65
- });
66
- const mediaType = detectImageMediaType(data);
67
- if (!mediaType) return {
68
- ...base,
69
- promptText: buildStoredAttachmentPromptText({
70
- attachmentId: attachment.id,
71
- filename: attachment.filename,
72
- mediaType: attachment.contentType
73
- })
74
- };
75
- return {
76
- ...base,
77
- data,
78
- mediaType
79
- };
80
- }));
81
- }
82
- export { model_input_exports as i, attachmentFactLines as n, buildStoredAttachmentPromptText as r, MAX_MODEL_ATTACHMENT_BYTES as t };