@sentry/junior 0.317.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 (95) hide show
  1. package/dist/adapter-8_S6Birm.js +1833 -0
  2. package/dist/{admin-CAugg87B.js → admin-EsbUON1j.js} +1 -1
  3. package/dist/{agent-runner-AjrEV6Qe.js → agent-CtzMl32d.js} +19953 -6727
  4. package/dist/{agent-status-BA5x3Xtp.js → agent-status-Bq_AIpyp.js} +105 -1
  5. package/dist/{agent-update-delivery-B_YIZcgf.js → agent-update-delivery-pAvsbuGL.js} +4 -5
  6. package/dist/api/schema.d.ts +85 -51
  7. package/dist/api/schema.js +4 -4
  8. package/dist/api.js +81 -94
  9. package/dist/{app-MoNAsVV5.d.ts → app-tACXxJPI.d.ts} +8 -13
  10. package/dist/app.d.ts +2 -2
  11. package/dist/app.js +246 -153
  12. package/dist/{change-record-BzJgLsv7.d.ts → change-record-K-KsqNhT.d.ts} +9 -5
  13. package/dist/{channel-access-j-YAVYK4.js → channel-access-DET5hzZM.js} +1 -1
  14. package/dist/{chat-core-engine-aH85nEHv.js → chat-core-engine-DpM3tMVi.js} +7 -7
  15. package/dist/cli/chat.d.ts +1 -1
  16. package/dist/cli/chat.js +38 -30
  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 -6
  22. package/dist/cli/upgrade.d.ts +1 -1
  23. package/dist/cli/upgrade.js +3 -4
  24. package/dist/{continue-in-slack-D-FZ8Fin.js → continue-in-slack-CFzDyxkH.js} +3 -2
  25. package/dist/{conversation-feed--9S0_PXL.js → conversation-feed-DEUdD7mb.js} +2 -106
  26. package/dist/{conversation-privacy-B1uXn5sf.js → conversation-privacy-C2vYK55O.js} +1 -1
  27. package/dist/{create-DoDIYgtZ.js → create-Ta3SEIB5.js} +124 -16
  28. package/dist/{credential-sync-BJOqGnjV.js → credential-sync-DyRqDmY4.js} +17 -20
  29. package/dist/{db-BFmyYZtJ.js → db-BCaNWl9p.js} +6536 -1920
  30. package/dist/{deployment-DXq9ZLU4.js → deployment-CfOew1Tm.js} +3 -3
  31. package/dist/{engine-context-CgQ7mlHt.js → engine-context-CiExoy1B.js} +181 -155
  32. package/dist/{html-B3VKTGbJ.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--smS7XRK.js → logging-BRPTXAdf.js} +10 -81
  36. package/dist/{mailbox-turn-uSXhUFc9.js → markers-9QoqW5ov.js} +1875 -1458
  37. package/dist/nitro.d.ts +2 -2
  38. package/dist/nitro.js +7 -8
  39. package/dist/{oauth-callback-server-CE4soEIY.js → oauth-callback-server-vhL9b-PZ.js} +2 -2
  40. package/dist/{oauth-relay-C36gX1gH.js → oauth-relay-CH2v7WiB.js} +1 -1
  41. package/dist/{plugins-fBrz8PCV.d.ts → plugins-DhGXZjlu.d.ts} +1 -0
  42. package/dist/{profile-BQ-iBDsZ.js → profile-D9LdwmZi.js} +17 -19
  43. package/dist/{prompt-Dv7gkpD6.js → prompt-3TqxEOtc.js} +10 -10
  44. package/dist/{reports-WKHfGTsU.js → reports-K-tbtEyx.js} +2 -2
  45. package/dist/{resolve-tony4ibz.js → resolve-BBV2qf8A.js} +5 -5
  46. package/dist/{result-Bta_dlWa.js → result-5IdGJP4M.js} +24 -13
  47. package/dist/{runner-BstDRbD9.js → runner-BK_joPlM.js} +9 -18
  48. package/dist/{sandbox-egress-signals-oSJMJOnn.js → sandbox-egress-signals-DXgWXXmm.js} +1 -1
  49. package/dist/{schema-DfqrHACA.js → schema-zWGG6VC1.js} +13 -7
  50. package/dist/{service-account-CTV_jaNu.js → service-account-CateFyhw.js} +4 -5
  51. package/dist/{skills-BCEU41zM.js → skills-Ccjw8h2P.js} +10 -9
  52. package/dist/{slack-conversation-unfurl-DxVmhbGP.js → slack-conversation-unfurl-ZC_TSpc4.js} +7 -7
  53. package/dist/storage-C9U7R5rM.js +273 -0
  54. package/dist/{system-prompt-table-CiXy0eNR.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-C4iC-IMC.js → types-BNHkJrOP.js} +79 -59
  58. package/dist/{users-ByG5RCEJ.js → users-CCRAqYb_.js} +1 -1
  59. package/dist/{validation-8gjfR91V.js → validation-BCUpJa8K.js} +4 -4
  60. package/dist/{version-BeZhWWBE.js → version-BNm0JYj3.js} +1 -1
  61. package/dist/version.js +1 -1
  62. package/dist/{worker-BqMQQNRk.js → worker-BhgpZ7_b.js} +5 -5
  63. package/migrations/20261127002500_turn_discarded_usage/migration.sql +2 -0
  64. package/migrations/20261127002500_turn_discarded_usage/snapshot.json +73 -0
  65. package/migrations/20261127052408_space_name_nullable/migration.sql +5 -0
  66. package/migrations/20261127052408_space_name_nullable/snapshot.json +29 -0
  67. package/migrations/20261127060000_annotation_object_id_index/migration.sql +1 -0
  68. package/migrations/20261127060000_annotation_object_id_index/snapshot.json +69 -0
  69. package/migrations/20261127060001_annotation_subjects/migration.sql +78 -0
  70. package/migrations/20261127060001_annotation_subjects/snapshot.json +104 -0
  71. package/migrations/20261127060002_annotation_subject_index/migration.sql +1 -0
  72. package/migrations/20261127060002_annotation_subject_index/snapshot.json +70 -0
  73. package/migrations/20261127060003_annotation_title_url/migration.sql +84 -0
  74. package/migrations/20261127060003_annotation_title_url/snapshot.json +73 -0
  75. package/package.json +9 -7
  76. package/dist/catalog-runtime-DfSpJZdY.js +0 -6
  77. package/dist/child-message-DHjQLEd1.js +0 -19
  78. package/dist/config-CHQ8X251.js +0 -2422
  79. package/dist/conversation-turn-BUE_7xaN.js +0 -1157
  80. package/dist/job-runner-A1lCkybD.js +0 -1506
  81. package/dist/lineage-Bktb0UcV.js +0 -36
  82. package/dist/list-Bxvg5wXf.js +0 -12623
  83. package/dist/message-BNenhsmB.js +0 -154
  84. package/dist/model-input-BReSnwHp.js +0 -82
  85. package/dist/parent-result-Ck1rFYRQ.js +0 -310
  86. package/dist/registry-iXMT5Jmh.js +0 -3279
  87. package/dist/run-conversation-DL6ru7iW.js +0 -336
  88. package/dist/sender-actors-CPglLd5R.js +0 -83
  89. package/dist/spawn-frczVPIr.js +0 -48
  90. package/dist/task-runner-C9Yc2_ae.js +0 -1526
  91. package/dist/thread-context-CqZDKErp.js +0 -166
  92. package/dist/topic-CRYYBYp-.js +0 -7
  93. package/dist/topics-SRN7IVX-.js +0 -24
  94. package/dist/turn-membership-CENFf3kI.js +0 -856
  95. package/dist/turn-wake-BhloiI2h.js +0 -151
@@ -1,154 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { F as AgentMessageTargetError, b as actorFromRun } from "./agent-runner-AjrEV6Qe.js";
3
- import { Pt as PARENT_AGENT_TARGET, Sr as readConversationAccessFromSql, a as getDb, hr as canAccessConversation, i as getConversationStore, jt as findChildAgentConversationId, oc as SYSTEM_IDENTITY_ID } from "./db-BFmyYZtJ.js";
4
- import { m as readChildConversationSender } from "./parent-result-Ck1rFYRQ.js";
5
- import { n as enqueueAgentMessageToParent } from "./result-Bta_dlWa.js";
6
- import { t as messageChildAgent } from "./create-DoDIYgtZ.js";
7
- import { O as EVENT_WAIT_MS, U as enqueueAutomatedInput } from "./mailbox-turn-uSXhUFc9.js";
8
- import { U as renderDataTag } from "./prompt-Dv7gkpD6.js";
9
- import { Dn as TOP_LEVEL_AGENT_MESSAGE_EVENT_TYPE } from "./types-C4iC-IMC.js";
10
- // src/chat/child-agents/top-level-message.ts
11
- const AGENT_MESSAGE_EVENT_NAMESPACE = "junior";
12
- /**
13
- * Check that a top-level agent can message another top-level agent under
14
- * `policies/conversation-access.md`. Public agents can message each other.
15
- * A private agent can message only agents at its own Destination, such as
16
- * another thread in the same private Slack channel.
17
- * Every target that the sender cannot reach gets the same error, so the
18
- * error does not show that a private Conversation exists.
19
- */
20
- async function requireTopLevelAgentAccess(args) {
21
- 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`);
22
- if (args.to === args.senderConversationId) throw new AgentMessageTargetError(`"${args.to}" is this conversation`);
23
- const conversationStore = getConversationStore();
24
- const [senderConversation, target] = await Promise.all([conversationStore.get({ conversationId: args.senderConversationId }), conversationStore.get({ conversationId: args.to })]);
25
- if (senderConversation?.parentConversationId) throw new AgentMessageTargetError(`"${args.to}" is not "${PARENT_AGENT_TARGET}" or a child agent of this conversation`);
26
- if (!target || target.parentConversationId) throw notReachable;
27
- const access = await readConversationAccessFromSql(getDb(), [args.senderConversationId, args.to]);
28
- const sender = access.get(args.senderConversationId);
29
- const receiver = access.get(args.to);
30
- if (!sender || !receiver || !canAccessConversation({
31
- requester: sender,
32
- target: receiver
33
- })) throw notReachable;
34
- 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`);
35
- }
36
- function renderTopLevelMessageInput(args) {
37
- return renderDataTag("agent-message", {
38
- conversation_id: args.senderConversationId,
39
- source: "top_level_agent"
40
- }, "Another top-level agent", args.text.trim());
41
- }
42
- /**
43
- * Send one message from a top-level agent to another top-level agent and
44
- * wake the target. The access check runs on each call. A stopped target
45
- * holds the message, so once the automated-turn limit stops one of two
46
- * agents, they cannot keep each other running. Repeat calls with the same
47
- * `messageKey` are safe.
48
- */
49
- async function enqueueTopLevelAgentMessage(args) {
50
- await requireTopLevelAgentAccess(args);
51
- const nowMs = args.nowMs ?? Date.now();
52
- const inboundMessageId = `agent-message:${args.senderConversationId}:${args.messageKey}`;
53
- const summary = `Top-level agent ${args.senderConversationId} sent a message.`;
54
- const metadata = {
55
- kind: "event",
56
- event: {
57
- eventKey: inboundMessageId,
58
- eventType: TOP_LEVEL_AGENT_MESSAGE_EVENT_TYPE,
59
- identifier: args.senderConversationId,
60
- namespace: AGENT_MESSAGE_EVENT_NAMESPACE,
61
- trustedSummary: summary
62
- }
63
- };
64
- await enqueueAutomatedInput({
65
- message: {
66
- conversationId: args.to,
67
- createdAtMs: nowMs,
68
- delivery: "defer",
69
- inboundMessageId,
70
- input: {
71
- authorId: `agent-message:${args.senderConversationId}`,
72
- authorIdentityId: SYSTEM_IDENTITY_ID,
73
- metadata,
74
- text: renderTopLevelMessageInput({
75
- senderConversationId: args.senderConversationId,
76
- text: args.text
77
- })
78
- },
79
- receivedAtMs: nowMs,
80
- source: "event"
81
- },
82
- queue: args.queue,
83
- queueDelayMs: EVENT_WAIT_MS,
84
- state: args.state
85
- });
86
- }
87
- // src/chat/child-agents/message.ts
88
- var message_exports = /* @__PURE__ */ __exportAll({ bindMessageAgent: () => bindMessageAgent });
89
- /**
90
- * Bind a Run's Actor and credentials to messages for its parent and child
91
- * agents, and for other top-level agents. A message to a child continues that
92
- * child. A message to the parent wakes the parent like a result. A top-level
93
- * agent can also message another top-level agent that it has access to.
94
- */
95
- function bindMessageAgent(run, options) {
96
- const actor = actorFromRun(run);
97
- if (!actor) return;
98
- return async (input, call) => {
99
- call.signal?.throwIfAborted();
100
- const queue = typeof options.queue === "function" ? options.queue() : options.queue;
101
- if (input.to === "parent") {
102
- const sender = await readChildConversationSender(run.conversationId);
103
- if (!sender) throw new AgentMessageTargetError("This conversation has no parent agent");
104
- await enqueueAgentMessageToParent({
105
- actor,
106
- messageKey: `${run.turnId}:${call.toolCallId}`,
107
- queue,
108
- sender,
109
- state: options.state,
110
- text: input.text
111
- });
112
- return {
113
- conversationId: sender.parentConversationId,
114
- delivery: "queued"
115
- };
116
- }
117
- const childConversationId = await findChildAgentConversationId({
118
- parentConversationId: run.conversationId,
119
- target: input.to
120
- });
121
- if (!childConversationId) {
122
- await enqueueTopLevelAgentMessage({
123
- messageKey: `${run.turnId}:${call.toolCallId}`,
124
- queue,
125
- senderConversationId: run.conversationId,
126
- state: options.state,
127
- text: input.text,
128
- to: input.to
129
- });
130
- return {
131
- conversationId: input.to,
132
- delivery: "queued"
133
- };
134
- }
135
- const { delivery } = await messageChildAgent({
136
- actor,
137
- childConversationId,
138
- ...run.credentialContext ? { credentialContext: run.credentialContext } : void 0,
139
- idempotencyKey: `${run.turnId}:${call.toolCallId}`,
140
- input: input.text,
141
- parentConversationId: run.conversationId,
142
- parentToolCallId: call.toolCallId,
143
- parentTurnId: run.turnId
144
- }, {
145
- ...options,
146
- queue
147
- });
148
- return {
149
- conversationId: childConversationId,
150
- delivery
151
- };
152
- };
153
- }
154
- 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-BFmyYZtJ.js";
3
- import { o as detectImageMediaType, s as isVisionImageMediaType } from "./user-customization-CvfuY9Eo.js";
4
- import { d as readLiveAttachment } from "./turn-membership-CENFf3kI.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 };
@@ -1,310 +0,0 @@
1
- import { Gd as juniorAgentBindings, Mn as readParentMessage, Nn as readInboundMessageSender, Pn as isEventMailboxMetadata, Qd as juniorConversationEvents, V as conversationLastTurnOutcomeSql, fs as conversationSubtree, i as getConversationStore, in as getConversationWorkStates, lf as juniorConversations, n as getConversationEventStore, nu as isPersonInput, o as getSqlExecutor, ps as conversationSubtreeColumns, rn as getConversationWorkState } from "./db-BFmyYZtJ.js";
2
- import { L as mapBounded } from "./prompt-Dv7gkpD6.js";
3
- import { kn as isAgentUpdateEventType } from "./types-C4iC-IMC.js";
4
- import { Or as TURN_OUTCOME_STATUSES, Rt as buildDeterministicTurnId, W as getConversationStoppedAtMs, Xn as EVENT_SYSTEM_ACTOR, _ as readChildOfStoredParent, b as readAgentConfig, i as listActiveMailboxTurns, r as listActiveMailboxTurnSources } from "./mailbox-turn-uSXhUFc9.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
- import pLimit from "p-limit";
9
- // src/chat/child-agents/child-input.ts
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 whether a Conversation drops one input, so it starts no work.
43
- * Routing, the stop skips, and the child agent status all read this, so they
44
- * agree on which input starts work.
45
- *
46
- * A parent message is dropped when it does not come from the stored parent,
47
- * or when it was sent before the child's stop. A child reply that a stop
48
- * skips is dropped too. A stopped Conversation never reads other automated
49
- * input: `enqueueAutomatedInput` and the stop hold it first.
50
- */
51
- async function isDroppedChildInput(message) {
52
- if (isPersonInput(message.source)) return false;
53
- const parentMessage = readParentMessage(message);
54
- if (parentMessage) {
55
- const child = await readChildOfStoredParent(message, parentMessage);
56
- if (!child) return true;
57
- const stoppedAtMs = child.stoppedAt?.getTime();
58
- return stoppedAtMs !== void 0 && message.receivedAtMs <= stoppedAtMs;
59
- }
60
- return childAgentInput(message)?.kind === "reply" && await isSkippedReply(message);
61
- }
62
- /**
63
- * Return whether a stop skipped this reply. A stop drops a child's unread
64
- * replies from the parent's mailbox. One sent before the stop can reach the
65
- * mailbox after that drop, so while the sending child is stopped, a reply
66
- * that it sent after the stop is dropped too, except the `stopped` result
67
- * that a person's stop sends. A message that a child sent is still
68
- * delivered.
69
- */
70
- async function isSkippedReply(message) {
71
- const sender = readInboundMessageSender(message);
72
- if (!sender || isStopResult(message)) return false;
73
- const senderStoppedAtMs = await getConversationStoppedAtMs(sender.conversationId);
74
- return senderStoppedAtMs !== void 0 && message.createdAtMs >= senderStoppedAtMs;
75
- }
76
- /**
77
- * Read the sender of one child Conversation from its parent edge and its
78
- * binding. A Conversation without a parent has none.
79
- */
80
- async function readChildConversationSender(childConversationId) {
81
- const parent = alias(juniorConversations, "parent");
82
- const [row] = await getSqlExecutor().db().select({
83
- agentName: juniorAgentBindings.name,
84
- parentConversationId: parent.conversationId,
85
- parentKind: parent.kind,
86
- title: juniorConversations.title
87
- }).from(juniorConversations).innerJoin(parent, eq(parent.conversationId, juniorConversations.parentConversationId)).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(eq(juniorConversations.conversationId, childConversationId));
88
- return row ? {
89
- ...row.agentName ? { agentName: row.agentName } : void 0,
90
- childConversationId,
91
- parentConversationId: row.parentConversationId,
92
- ...row.parentKind ? { parentKind: row.parentKind } : void 0,
93
- ...row.title ? { title: row.title } : void 0
94
- } : void 0;
95
- }
96
- /**
97
- * Read the sender of one reply or message, when it is a child of the
98
- * Conversation that received it. Otherwise the input has no child sender,
99
- * such as one that an earlier release sent.
100
- */
101
- async function getChildAgentInputSender(message, input) {
102
- const sender = await readChildConversationSender(input.senderId);
103
- return sender?.parentConversationId === message.conversationId ? sender : void 0;
104
- }
105
- // src/chat/child-agents/list.ts
106
- const childConversationKindSchema = z.enum(["thread", "task"]);
107
- /** Bound the child agents that one listing reads. */
108
- const CHILD_AGENT_LIST_LIMIT = 200;
109
- /**
110
- * List the direct child agents of one parent Conversation, with the newest
111
- * activity first. The state comes from each child's Turns and mailbox, not
112
- * from model output. Each child agent stores its agent config, so older
113
- * children of a parent, such as ones that a removed feature created, are not
114
- * listed. A child is `stopped` while stopped, `running` while a Turn or
115
- * mailbox input that answers its parent is open, `failed` when its stored
116
- * execution failed, such as when its worker gave up and no Turn ended, and
117
- * else `idle`.
118
- * `lastResult` is how its newest finished Turn that was not stopped ended:
119
- * the status that `readTurnUpdate` gives it, or `failed`.
120
- */
121
- async function listChildAgents(parentConversationId) {
122
- const rows = await getSqlExecutor().db().select({
123
- agentName: juniorAgentBindings.name,
124
- archivedAt: juniorConversations.archivedAt,
125
- conversationId: juniorConversations.conversationId,
126
- executionStatus: juniorConversations.executionStatus,
127
- executionUpdatedAt: juniorConversations.executionUpdatedAt,
128
- kind: juniorConversations.kind,
129
- lastTurnOutcome: conversationLastTurnOutcomeSql(juniorConversations),
130
- stoppedAt: juniorConversations.stoppedAt,
131
- title: juniorConversations.title,
132
- updatedAt: juniorConversations.updatedAt
133
- }).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);
134
- const ids = rows.map((row) => row.conversationId);
135
- const [workStates, mailboxTurnSources] = await Promise.all([getConversationWorkStates(ids), listActiveMailboxTurnSources(ids)]);
136
- const limit = pLimit(8);
137
- return (await Promise.all(rows.map(async (row) => {
138
- const kind = childConversationKindSchema.parse(row.kind);
139
- const stoppedAtMs = row.stoppedAt?.getTime();
140
- const running = stoppedAtMs === void 0 && await limit(() => runsOnConversationLoop(workStates.get(row.conversationId)?.execution.pendingMessages ?? [], mailboxTurnSources.get(row.conversationId) ?? []));
141
- const outcome = row.lastTurnOutcome;
142
- const lastResult = outcome === "failed" ? "failed" : outcome ? TURN_OUTCOME_STATUSES[outcome] : void 0;
143
- return {
144
- ...row.agentName ? { agentName: row.agentName } : void 0,
145
- ...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
146
- childConversationId: row.conversationId,
147
- kind,
148
- ...lastResult ? { lastResult } : void 0,
149
- status: stoppedAtMs !== void 0 ? "stopped" : running ? "running" : row.executionStatus === "failed" ? "failed" : "idle",
150
- ...row.title ? { title: row.title } : void 0,
151
- updatedAtMs: (row.executionUpdatedAt ?? row.updatedAt).getTime()
152
- };
153
- }))).sort((left, right) => right.updatedAtMs - left.updatedAtMs);
154
- }
155
- /** List the ids of the child agents of one parent that have open work. */
156
- async function listOpenChildAgents(parentConversationId) {
157
- return (await listChildAgents(parentConversationId)).filter((child) => child.status === "running").map((child) => child.childConversationId);
158
- }
159
- /**
160
- * Return whether a child has work that will answer its parent: `pending`
161
- * input that waits in the mailbox until its Turn commits it, such as a Watch
162
- * Event in its debounce window, or an open mailbox Turn. Every Turn of a
163
- * child answers its parent, whoever started it.
164
- */
165
- async function runsOnConversationLoop(pending, mailboxTurnSources) {
166
- if (mailboxTurnSources.length > 0) return true;
167
- for (const message of pending) if (!await isDroppedChildInput(message)) return true;
168
- return false;
169
- }
170
- /**
171
- * List the ids of a child's open Turns on the Conversation loop. A Turn keeps
172
- * its input in the mailbox until it commits it, so before its first
173
- * checkpoint its id comes from its first input. Attempt selection can take
174
- * any pending input first, so each one gives a candidate id.
175
- */
176
- async function listOpenLoopTurnIds(conversationId) {
177
- const [turns, work] = await Promise.all([listActiveMailboxTurns(conversationId), getConversationWorkState({ conversationId })]);
178
- return [...turns.map((turn) => turn.turnId), ...(work?.execution.pendingMessages ?? []).map((message) => buildDeterministicTurnId(message.inboundMessageId))];
179
- }
180
- async function listAnsweredLoopChildren(children, parentMessages) {
181
- if (children.length === 0 || parentMessages.length === 0) return [];
182
- return (await mapBounded(children, async ({ childConversationId }) => {
183
- const turnIds = await listOpenLoopTurnIds(childConversationId);
184
- return parentMessages.some(({ sender }) => sender.conversationId === childConversationId && turnIds.includes(sender.turnId)) ? childConversationId : void 0;
185
- })).filter((id) => id !== void 0);
186
- }
187
- /**
188
- * List the other child agents of one parent that still run and have not
189
- * answered. A running child whose open Turn's result is already among
190
- * `parentMessages`, the child replies and results that reached the parent's
191
- * mailbox, has answered, so it does not count.
192
- */
193
- async function listUnreportedSiblingAgents(parentConversationId, childConversationId, parentMessages) {
194
- const running = (await listChildAgents(parentConversationId)).filter((child) => child.childConversationId !== childConversationId && child.status === "running");
195
- const answered = new Set(await listAnsweredLoopChildren(running, parentMessages));
196
- return running.filter((child) => !answered.has(child.childConversationId));
197
- }
198
- /**
199
- * List every child agent below one Conversation, at any depth. A parent owns
200
- * the work of its child agents and of their child agents. The list never has
201
- * the Conversation itself, its parent, or a sibling.
202
- */
203
- async function listDescendantAgents(conversationId) {
204
- return (await getSqlExecutor().db().select({
205
- conversationId: juniorConversations.conversationId,
206
- name: juniorAgentBindings.name
207
- }).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) => ({
208
- conversationId: row.conversationId,
209
- ...row.name ? { name: row.name } : void 0
210
- }));
211
- }
212
- /**
213
- * List the agents that one Conversation can see. A root Conversation sees
214
- * only its child agents. A child agent also sees itself, its parent, and the
215
- * other child agents of its parent.
216
- */
217
- async function listAgentRelatives(input) {
218
- const { conversationId, parentConversationId } = input;
219
- const [children, family, parent] = await Promise.all([
220
- listChildAgents(conversationId),
221
- parentConversationId ? listChildAgents(parentConversationId) : [],
222
- parentConversationId ? getConversationStore().get({ conversationId: parentConversationId }) : void 0
223
- ]);
224
- const self = family.find((agent) => agent.childConversationId === conversationId);
225
- return {
226
- children,
227
- ...parent ? { parent: {
228
- conversationId: parent.conversationId,
229
- status: parent.execution.status,
230
- updatedAtMs: parent.execution.updatedAtMs ?? parent.updatedAtMs
231
- } } : void 0,
232
- ...self ? { self } : void 0,
233
- siblings: family.filter((agent) => agent.childConversationId !== conversationId)
234
- };
235
- }
236
- // src/chat/child-agents/markers.ts
237
- const SUBAGENT_KIND = "agent";
238
- const SUBAGENT_STARTED_KEY_PREFIX = "subagent_started:";
239
- const SUBAGENT_ENDED_KEY_PREFIX = "subagent_ended:";
240
- /**
241
- * Record in the parent Conversation that a child agent got one task or
242
- * message. Write it before the input reaches the child's mailbox, so the
243
- * child cannot end first.
244
- */
245
- async function recordSubagentStartedMarker(start) {
246
- await getConversationEventStore().append(start.parentConversationId, [{
247
- idempotencyKey: `${SUBAGENT_STARTED_KEY_PREFIX}${start.markerId}`,
248
- data: {
249
- type: "subagent_started",
250
- subagentInvocationId: start.markerId,
251
- subagentKind: SUBAGENT_KIND,
252
- childConversationId: start.childConversationId,
253
- ...start.agentName ? { agentName: start.agentName } : void 0,
254
- parentToolCallId: start.parentToolCallId,
255
- task: start.input,
256
- ...start.title ? { title: start.title } : void 0,
257
- ...start.reasoningLevel ? { reasoningLevel: start.reasoningLevel } : void 0
258
- },
259
- createdAtMs: start.createdAtMs
260
- }]);
261
- }
262
- /**
263
- * Record in the parent Conversation how the work of a child agent ended.
264
- * Each parent message has its own `subagent_started` marker, named by the
265
- * message id, and each one that the child already took ends with `outcome`.
266
- * A parent message that still waits in the child's mailbox stays open,
267
- * because later work reads it, unless `includeWaiting` is set, as for a stop
268
- * that skips it. Write it before the child's result reaches the parent.
269
- */
270
- async function recordChildAgentEnded(childConversationId, outcome, options = {}) {
271
- if (!await readAgentConfig(childConversationId)) return;
272
- const work = await getConversationWorkState({
273
- conversationId: childConversationId,
274
- state: options.state
275
- });
276
- const running = new Set(work?.runningInboundMessageIds);
277
- const waiting = new Set(options.includeWaiting ? [] : (work?.messages ?? []).map((message) => message.inboundMessageId).filter((id) => !running.has(id)));
278
- const taken = (work?.execution.inboundMessageIds ?? []).filter((id) => !waiting.has(id));
279
- if (taken.length === 0) return;
280
- const sender = await readChildConversationSender(childConversationId);
281
- if (!sender) return;
282
- 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}`]))));
283
- const found = new Set(keys.map((row) => row.idempotencyKey));
284
- const open = taken.filter((id) => found.has(`${SUBAGENT_STARTED_KEY_PREFIX}${id}`) && !found.has(`${SUBAGENT_ENDED_KEY_PREFIX}${id}`));
285
- if (open.length > 0) await appendSubagentEnded(sender.parentConversationId, open, outcome, options.nowMs ?? Date.now());
286
- }
287
- async function appendSubagentEnded(parentConversationId, markerIds, outcome, createdAtMs) {
288
- await getConversationEventStore().append(parentConversationId, markerIds.map((id) => ({
289
- idempotencyKey: `${SUBAGENT_ENDED_KEY_PREFIX}${id}`,
290
- data: {
291
- type: "subagent_ended",
292
- subagentInvocationId: id,
293
- outcome
294
- },
295
- createdAtMs
296
- })));
297
- }
298
- // src/chat/child-agents/parent-result.ts
299
- /**
300
- * Return the Actor that a child Turn's update carries to its parent, whose
301
- * Turn for it runs as that Actor. Only a Turn that agent work started, a
302
- * parent message or an Event such as a child result, keeps its Actor. Any
303
- * other Turn, such as a person's Turn in a Thread or a saved Turn with no
304
- * Source, reports as the Event system Actor, so the parent never gets a
305
- * person's access.
306
- */
307
- function parentResultActor(actor, source) {
308
- return source === "parent_message" || source === "event" ? actor : EVENT_SYSTEM_ACTOR;
309
- }
310
- export { listChildAgents as a, listUnreportedSiblingAgents as c, isChildAgentEvent as d, isDroppedChildInput as f, listAgentRelatives as i, childAgentInput as l, readChildConversationSender as m, recordChildAgentEnded as n, listDescendantAgents as o, isStopResult as p, recordSubagentStartedMarker as r, listOpenChildAgents as s, parentResultActor as t, getChildAgentInputSender as u };