@sentry/junior 0.298.0 → 0.299.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/dist/{actor-6jsm_v96.js → actor-D2iXzvlN.js} +2 -1
  2. package/dist/{state-CSuA2J1V.js → adapter-AgCNqqsG.js} +49 -133
  3. package/dist/{admin-BF3DbYGf.js → admin-1VwEXztm.js} +2 -2
  4. package/dist/{agent-runner-Q9GkoerG.js → agent-runner-Ciet8_nn.js} +977 -1316
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +8 -7
  7. package/dist/api.d.ts +1 -1
  8. package/dist/api.js +125 -43
  9. package/dist/{app-DOg_mCtV.d.ts → app--ky-Eu33.d.ts} +6 -4
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +126 -299
  12. package/dist/{automation-Cn8qmbdr.js → automation-M3RFJUBf.js} +1 -1
  13. package/dist/{background-compaction-queue-BZhGFOK6.js → background-compaction-queue-CnimvRdk.js} +4 -4
  14. package/dist/{briefs-CQrCRF6-.js → briefs-CwzvgdCa.js} +4 -4
  15. package/dist/{catalog-runtime-DZeD2WbL.js → catalog-runtime-DaBaHY7u.js} +1 -1
  16. package/dist/cli/chat.js +17 -17
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +5 -5
  20. package/dist/cli/snapshot-create.js +4 -4
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +4 -4
  23. package/dist/{config-BOByVnxe.js → config-CAXIpWQb.js} +80 -6
  24. package/dist/{connections-BNN5cJam.js → connections-Dy0hPdUq.js} +6 -6
  25. package/dist/continue-in-slack-DIOjFj76.js +176 -0
  26. package/dist/{conversation-DCkzvxqB.js → conversation-fCWD9Az3.js} +24 -12
  27. package/dist/{conversation-feed-CMA12Rjs.js → conversation-feed-BPK8vkkZ.js} +88 -3
  28. package/dist/{conversation-privacy-C0eRxsgb.js → conversation-privacy-DUgtRkf8.js} +1 -1
  29. package/dist/{conversation-turn-D9qvcDX6.js → conversation-turn-DkJB6yMF.js} +85 -68
  30. package/dist/{credential-sync-B_iUpxGL.js → credential-sync-RX24Y8aY.js} +18 -18
  31. package/dist/{db-DoMcnYol.d.ts → db-B07FtU9g.d.ts} +1 -1
  32. package/dist/{db-CoMNr2Zm.js → db-COYOGzYS.js} +171 -12
  33. package/dist/{executor-C-m8VrzX.js → executor-BWmAgSyi.js} +40 -11
  34. package/dist/{media-BepyEUNm.js → history-IjdmO_r6.js} +1 -85
  35. package/dist/instrumentation.js +2 -2
  36. package/dist/lineage-D-5jm_oj.js +37 -0
  37. package/dist/{logging-CJTi5niy.js → logging-DPLEa8Bn.js} +1 -1
  38. package/dist/media-BAHvgkok.js +85 -0
  39. package/dist/{message-Q6_5DAWR.js → message-BIHR1yRk.js} +9 -10
  40. package/dist/model-input-BPZYH8Nd.js +82 -0
  41. package/dist/nitro.d.ts +1 -1
  42. package/dist/nitro.js +17 -9
  43. package/dist/{oauth-callback-server-CH5XAyo-.js → oauth-callback-server-R7qvSzFG.js} +2 -2
  44. package/dist/{plugins-HYh_JOdw.js → plugins-CBW2Prb_.js} +1 -1
  45. package/dist/{projection-BgwEE36_.js → projection-DEdP1q6f.js} +261 -36
  46. package/dist/{prompt-DXc9DYT9.js → prompt-4M98h_tC.js} +4 -4
  47. package/dist/{registry-9XwqSnM-.js → registry-BTKmKM-r.js} +3 -3
  48. package/dist/{resolve-DUIAbcRL.js → resolve-B8hXNVZ3.js} +3 -3
  49. package/dist/{result-C2Vn8QGn.js → result-g-XAaOj6.js} +158 -69
  50. package/dist/{runner-CXGtw-Mc.js → runner-BlPSA5A8.js} +9 -9
  51. package/dist/{sandbox-egress-signals-Di3S_dO7.js → sandbox-egress-signals-Pai-MzEY.js} +1 -1
  52. package/dist/{schema-Dyp7racy.js → schema-BNnY_trV.js} +47 -7
  53. package/dist/{schema-BnbZ-rKv.d.ts → schema-DbuWR-DN.d.ts} +657 -346
  54. package/dist/{service-account-GzAMUQ8a.js → service-account-9OLNQMyz.js} +4 -4
  55. package/dist/{service-account-DM3KBBeG.js → service-account-BYGZ08DQ.js} +3 -3
  56. package/dist/session-stop-2XJrcNCy.js +3356 -0
  57. package/dist/{skills-DCK9SD_l.js → skills-DpBQoeHV.js} +3 -3
  58. package/dist/slack-conversation-unfurl-BcDIWo67.js +370 -0
  59. package/dist/spawn-09GssFod.js +73 -0
  60. package/dist/state-Cufq0_rH.js +132 -0
  61. package/dist/{user-input-request-CXNIov9n.js → statuses-B8mUfghF.js} +30 -25
  62. package/dist/{stop-Dh2DfwpK.js → stop-U7iUrR1g.js} +6008 -5772
  63. package/dist/{store-B1zepKG8.js → store-BHiaHCQu.js} +24 -4
  64. package/dist/{store-DrA17Fbz.js → store-CSgUTMdv.js} +10 -10
  65. package/dist/{task-queue-D1rXWfFN.js → task-queue-bMNq0clp.js} +4 -4
  66. package/dist/{task-runner-CT4M8oDz.js → task-runner-B__rxwxU.js} +10 -10
  67. package/dist/{thread-context-DnqUkbzN.js → thread-context-d0ceWbVT.js} +18 -18
  68. package/dist/{turn-session-routing-VXDVXLRl.js → turn-session-routing-BVZHBFCF.js} +5 -5
  69. package/dist/turn-user-message-BEw7acTP.js +355 -0
  70. package/dist/users-BK3dbxZL.js +424 -0
  71. package/dist/{validation-zxAJBDDy.js → validation-BDVJjO2E.js} +1 -1
  72. package/dist/{version-DcZ40a0g.js → version-DQgZoQ3D.js} +1 -1
  73. package/dist/version.js +1 -1
  74. package/dist/{viewer-CgiGjW10.js → viewer-CAWfFo29.js} +25 -54
  75. package/dist/{warmup-CwKbxQLl.js → warmup-9ySPacF9.js} +1137 -144
  76. package/dist/{worker-CbDUzaBA.js → worker-D8jJO-WO.js} +8 -7
  77. package/migrations/0104_code_change_draft.sql +1 -0
  78. package/migrations/0105_attachment_uploads.sql +14 -0
  79. package/migrations/0106_conversation_agent_config.sql +1 -0
  80. package/migrations/meta/0104_snapshot.json +4516 -0
  81. package/migrations/meta/0105_snapshot.json +4611 -0
  82. package/migrations/meta/0106_snapshot.json +4617 -0
  83. package/migrations/meta/_journal.json +21 -0
  84. package/package.json +4 -4
  85. package/dist/attempt-selection-ClP3MMPr.js +0 -61
  86. package/dist/locks-D-0h111u.js +0 -48
  87. package/dist/notification-Bv25xbj0.js +0 -1284
  88. package/dist/prompt-input-BUr4J9RO.js +0 -1424
  89. package/dist/session-stop-D4i7e6iT.js +0 -181
  90. package/dist/spawn-6cX6xE9G.js +0 -80
  91. package/dist/turn-cancel-l460pfGW.js +0 -201
  92. package/dist/turn-user-message-BSPmkm7X.js +0 -608
  93. package/dist/turn-wake-DVFVXyhX.js +0 -161
  94. package/dist/{oauth-relay-CsfIazeF.js → oauth-relay-DRzq73b6.js} +1 -1
@@ -1,27 +1,29 @@
1
1
  import { n as captureMessage, u as sentry_exports, v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { H as PluginCredentialFailureError, K as AuthorizationFlowDisabledError, Mo as FORK_INSTRUCTIONS, No as loadForkHistory, Pn as escapeClosingTags, Qt as isTurnExecutionLimitExceededError, Rn as renderTag, Zo as createPluginCache, _n as getTerminalAssistantMessages, an as getAssistantReplyText, at as failTurnRecord, et as lostWorkerBeforeFirstSave, fn as REPORT_BLOCKED_TOOL_NAME, fo as createPluginLogger, li as listWatches, nr as getPlugins, nt as saveTurnCheckpoint, ot as getTurnRecord, rt as abandonTurnRecord, s as openConversationProjection, sn as NO_REPLY_TOOL_NAME, tn as readTurnAnswer, tt as pauseLostWorkerTurn, v as hydrateConversationMessages } from "./projection-BgwEE36_.js";
3
- import { E as resolveGatewayModel, K as isProviderRetryError, i as getChatConfig, n as botConfig } from "./config-BOByVnxe.js";
4
- import { E as withSpan, h as logWarn, m as logInfo, x as setSpanStatus } from "./logging-CJTi5niy.js";
5
- import { D as turnBehavior, M as SYSTEM_IDENTITY_ID, O as conversationKindFromRow, Q as rootConversationIsArchived, a as getConversationStore, b as userMessageQueries, o as getDb, r as getConversationEventStore, s as getSqlExecutor, w as isPersonInput } from "./db-CoMNr2Zm.js";
6
- import { A as juniorConversations, g as juniorAgentInvocations, h as juniorAgentBindings } from "./executor-C-m8VrzX.js";
7
- import { h as contextProvenance, m as agentInstructionProvenance, v as sameActorIdentity } from "./media-BepyEUNm.js";
8
- import { u as completeText } from "./prompt-DXc9DYT9.js";
9
- import { a as getStateAdapter } from "./state-CSuA2J1V.js";
10
- import { O as agentTypeInstructions } from "./conversation-DCkzvxqB.js";
11
- import { T as systemPromptHash, l as withoutSavedSteeringMessages, o as buildSteeringPiMessage, s as instructionForInputs, v as listActiveMailboxTurns, w as buildDeploymentSystemPrompt } from "./prompt-input-BUr4J9RO.js";
12
- import { w as getTurnRequestDeadline, y as sendCacheWarmup } from "./background-compaction-queue-BZhGFOK6.js";
13
- import { c as conversationSubtreeColumns, i as resumeStoppedConversationTree, n as isSkippedAfterConversationStop, r as markConversationsStopped, s as conversationSubtree, t as getConversationStoppedAtMs } from "./session-stop-D4i7e6iT.js";
14
- import { A as listAgentInvocationsForConversation, C as getActiveAgentInvocationForConversation, D as invocationFromRow, E as getLatestAgentInvocationForConversation, G as agentBindingSchema, I as markAgentInvocationPaused, J as getAgentInvocationId, L as markAgentInvocationRunning, O as isStoppedAgentInvocation, P as markAgentInvocationMailboxAppended, Q as getAgentInvocationMessageId, R as markAgentInvocationSteered, S as completeAgentInvocation, U as CHILD_AGENT_RESULTS, V as sendsResultToParent, Z as getAgentInvocationIdForResult, _ as ConversationTurnLifecycleService, at as getUnnamedAgentConversationId, b as NON_TERMINAL_AGENT_INVOCATION_STATUSES, ct as parseAgentReplyMessageId, d as isTurnInputCommitLostError, dt as buildDeterministicTurnId, et as getAgentInvocationTurnId, j as listOpenAgentInvocations, k as isTerminalAgentInvocation, l as getConversationTurnBoundaryError, lt as parseTurnReplyMessageId, nt as getChildAgentLockName, ot as isAgentReplyMessageId, q as createAgentInvocationSchema, rt as getNamedAgentConversationId, s as TurnInputCommitLostError, st as parseAgentInvocationResultMessageId, w as getAgentInvocation, y as ACTIVE_AGENT_INVOCATION_STATUSES, z as reportReplacedAgentInvocation } from "./turn-user-message-BSPmkm7X.js";
15
- import { E as resetAutomatedTurnLimit, T as recordFinishedTurnForAutomatedLimit, i as isEventMailboxMetadata, y as maybePostAutomatedTurnLimitNotice } from "./notification-Bv25xbj0.js";
16
- import { E as stopConversationWork, _ as getConversationWorkState, m as dropPendingMessages, r as appendAndEnqueueInboundMessage } from "./store-B1zepKG8.js";
17
- import { a as getPersistedThreadState, c as coerceThreadConversationState, i as getPersistedSandboxState, s as persistThreadStateById } from "./turn-session-routing-VXDVXLRl.js";
18
- import { v as isAgentInvocationResultEventType } from "./user-input-request-CXNIov9n.js";
19
- import { a as AgentRunError, o as executeTurn, r as supersedeOpenMailboxTurns, s as finishTurn, t as cancelSignInWait } from "./turn-cancel-l460pfGW.js";
2
+ import { $ as loadTurnCheckpoint, Cn as getTerminalAssistantMessages, H as PluginCredentialFailureError, Jo as FORK_INSTRUCTIONS, K as AuthorizationFlowDisabledError, Oo as createPluginLogger, Un as escapeClosingTags, X as clearPendingAuth, Yo as loadForkHistory, at as failTurnRecord, dr as getPlugins, et as lostWorkerBeforeFirstSave, fn as NO_REPLY_TOOL_NAME, in as REPLY_TOOL_NAME, j as markConversationMessage, nt as saveTurnCheckpoint, on as readTurnAnswer, ps as createPluginCache, qn as renderTag, rn as isTurnExecutionLimitExceededError, rt as abandonTurnRecord, s as openConversationProjection, st as getTurnRecord, tt as pauseLostWorkerTurn, un as getAssistantReplyText, v as hydrateConversationMessages, vi as listWatches, vn as REPORT_BLOCKED_TOOL_NAME } from "./projection-DEdP1q6f.js";
3
+ import { E as resolveGatewayModel, K as isProviderRetryError, g as TURN_REASONING_LEVELS, i as getChatConfig, n as botConfig } from "./config-CAXIpWQb.js";
4
+ import { E as withSpan, h as logWarn, m as logInfo, x as setSpanStatus } from "./logging-DPLEa8Bn.js";
5
+ import { o as isUserActor } from "./actor-D2iXzvlN.js";
6
+ import { C as isPersonInput, D as conversationKindFromRow, E as turnBehavior, a as getConversationStore, et as rootConversationIsArchived, j as SYSTEM_IDENTITY_ID, o as getDb, r as getConversationEventStore, s as getSqlExecutor, w as isTopLevelKind, y as userMessageQueries } from "./db-COYOGzYS.js";
7
+ import { g as juniorAgentInvocations, h as juniorAgentBindings, j as juniorConversations, w as juniorConversationEvents } from "./executor-BWmAgSyi.js";
8
+ import { d as contextProvenance, m as sameActorIdentity, u as agentInstructionProvenance } from "./history-IjdmO_r6.js";
9
+ import { r as getStateAdapter } from "./adapter-AgCNqqsG.js";
10
+ import { p as credentialContextSchema } from "./registry-BTKmKM-r.js";
11
+ import { u as completeText } from "./prompt-4M98h_tC.js";
12
+ import { A as agentTypeSchema, k as agentTypeInstructions } from "./conversation-fCWD9Az3.js";
13
+ import { C as getAuthPausedConversationTurnId, E as listActiveMailboxTurns, F as isEventMailboxMetadata, T as listActiveMailboxTurnSources, X as maybePostAutomatedTurnLimitNotice, at as conversationSubtreeColumns, f as buildSteeringPiMessage, g as withoutSavedSteeringMessages, i as resumeStoppedConversationTree, it as conversationSubtree, m as instructionForInputs, n as isSkippedAfterConversationStop, nt as recordFinishedTurnForAutomatedLimit, ot as buildDeploymentSystemPrompt, r as markConversationsStopped, rt as resetAutomatedTurnLimit, st as systemPromptHash, t as getConversationStoppedAtMs } from "./session-stop-2XJrcNCy.js";
14
+ import { l as getVercelConversationWorkQueue, w as getTurnRequestDeadline, y as sendCacheWarmup } from "./background-compaction-queue-CnimvRdk.js";
15
+ import { A as getAgentInvocationResultMessageId, C as ownAgentInvocation, I as getUnnamedAgentConversationId, N as getChildAgentLockName, O as getAgentInvocationIdForResult, P as getNamedAgentConversationId, R as buildDeterministicTurnId, S as listChildMessages, T as getAgentInvocationId, _ as ConversationTurnLifecycleService, b as hasAgentInvocationReply, d as isTurnInputCommitLostError, j as getAgentInvocationTurnId, k as getAgentInvocationMessageId, l as getConversationTurnBoundaryError, p as markTurnClosed, s as TurnInputCommitLostError, t as getTurnUserMessage, w as readChildMessageSender } from "./turn-user-message-BEw7acTP.js";
16
+ import { D as stopConversationWork, _ as getConversationWorkState, h as ensureConversationWake, m as dropPendingMessages, r as appendAndEnqueueInboundMessage, v as getConversationWorkStates, w as requestConversationWork } from "./store-BHiaHCQu.js";
17
+ import { a as getPersistedThreadState, c as coerceThreadConversationState, i as getPersistedSandboxState, n as resolveTurnSessionRouting, s as persistThreadStateById } from "./turn-session-routing-BVZHBFCF.js";
18
+ import { g as AGENT_PARENT_MESSAGE_EVENT_TYPE, m as AGENT_INVOCATION_EVENT_NAMESPACE, n as AGENT_INVOCATION_PARENT_MAILBOX_STATUSES, t as AGENT_INVOCATION_MAILBOX_STATUSES, y as isAgentInvocationResultEventType } from "./statuses-B8mUfghF.js";
19
+ import * as z from "zod";
20
20
  import { streamSimple } from "@earendil-works/pi-ai/compat";
21
21
  import { isDeepStrictEqual, promisify } from "node:util";
22
22
  import { createHash, randomUUID } from "node:crypto";
23
- import * as z from "zod";
24
- import { and, desc, eq, gt, inArray, ne, or, sql } from "drizzle-orm";
23
+ import { and, asc, desc, eq, exists, gt, inArray, isNotNull, ne, notExists, or, sql } from "drizzle-orm";
24
+ import { actorSchema, destinationSchema, sourceSchema } from "@sentry/junior-plugin-api";
25
+ import { alias } from "drizzle-orm/pg-core";
26
+ import pLimit from "p-limit";
25
27
  import { constants, zstdCompress, zstdDecompress } from "node:zlib";
26
28
  // src/chat/cache-warming/model.ts
27
29
  /**
@@ -235,13 +237,18 @@ function parentGapSegment(input) {
235
237
  archived: false
236
238
  });
237
239
  }
240
+ const WAITING_SEGMENT_SUFFIXES = {
241
+ child: "child",
242
+ review: "review",
243
+ watch: "automation"
244
+ };
238
245
  /**
239
- * Child of a segment for an idle period that waits on a child agent or a
240
- * Review item. Its parent is the segment, so a thin child leans on the
241
- * segment, and a thin segment on its own parent.
246
+ * Child of a segment for an idle period that waits on a child agent, a
247
+ * Review item, or a Watch (`:automation`). Its parent is the segment, so a
248
+ * thin child leans on the segment, and a thin segment on its own parent.
242
249
  */
243
250
  function waitingGapSegment(segment, waitingOn) {
244
- return `${segment}:${waitingOn}`;
251
+ return `${segment}:${WAITING_SEGMENT_SUFFIXES[waitingOn]}`;
245
252
  }
246
253
  /** Whether a segment has too few gaps to stand without its parent. */
247
254
  function segmentNeedsParent(segmentGaps) {
@@ -684,6 +691,354 @@ function createToolWaitWarmer(conversationId) {
684
691
  }
685
692
  };
686
693
  }
694
+ // src/chat/conversations/agent-config.ts
695
+ /**
696
+ * The agent settings that every Turn of one Conversation keeps, for any
697
+ * kind: its Agent type, its reasoning level, and whether it started with its
698
+ * parent's history. A kind sets only the fields that apply to it.
699
+ */
700
+ const agentConfigSchema = z.object({
701
+ agentType: agentTypeSchema.optional(),
702
+ fork: z.literal(true).optional(),
703
+ reasoningLevel: z.enum(TURN_REASONING_LEVELS).optional()
704
+ }).strict();
705
+ /**
706
+ * Read the agent config that one Conversation stores, or undefined when it
707
+ * stores none. Today only a child that a spawn created without an Agent
708
+ * invocation row stores one. A child that an Agent invocation names reads
709
+ * its settings from its row first.
710
+ */
711
+ async function readAgentConfig(conversationId) {
712
+ const [row] = await getSqlExecutor().db().select({ agentConfig: juniorConversations.agentConfig }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId));
713
+ return row?.agentConfig ? agentConfigSchema.parse(row.agentConfig) : void 0;
714
+ }
715
+ // src/chat/runtime/turn-execution.ts
716
+ /** An error thrown while the agent advances a Run. */
717
+ var AgentRunError = class extends Error {
718
+ constructor(cause) {
719
+ super(cause instanceof Error ? cause.message : "Agent Run failed", { cause });
720
+ this.name = "AgentRunError";
721
+ }
722
+ };
723
+ /**
724
+ * Run the agent and finish the Turn after the caller saves its result.
725
+ *
726
+ * A paused Run, or a Run waiting for authorization, leaves the Turn open. A
727
+ * save error also leaves the Turn open so the worker can retry or recover it.
728
+ */
729
+ async function executeTurn(agentRunner, run, saveResult) {
730
+ let outcome;
731
+ try {
732
+ outcome = await agentRunner.run(run);
733
+ } catch (error) {
734
+ throw new AgentRunError(error);
735
+ }
736
+ if (outcome.status !== "completed") return outcome;
737
+ const saved = await saveResult(outcome.result);
738
+ await finishTurn(run.conversationId, run.turnId, saved);
739
+ return { status: "completed" };
740
+ }
741
+ /** Record the terminal lifecycle event of a Turn from its saved result. */
742
+ async function finishTurn(conversationId, turnId, saved) {
743
+ const lifecycle = new ConversationTurnLifecycleService(getConversationEventStore());
744
+ const common = {
745
+ conversationId,
746
+ createdAtMs: saved.finishedAtMs ?? Date.now(),
747
+ turnId
748
+ };
749
+ if (saved.outcome === "failed") await lifecycle.fail({
750
+ ...common,
751
+ ...saved.eventId ? { eventId: saved.eventId } : void 0,
752
+ failureCode: saved.failureCode,
753
+ ...saved.failureReason ? { failureReason: saved.failureReason } : void 0
754
+ });
755
+ else await lifecycle.complete({
756
+ ...common,
757
+ outcome: saved.outcome
758
+ });
759
+ }
760
+ // src/chat/conversations/web-authorization.ts
761
+ const WEB_AUTHORIZATION_PREFIX = "junior:web_authorization:v1";
762
+ const WEB_AUTHORIZATION_TTL_MS = 864e5;
763
+ function authorizationKey$1(conversationId, actorId) {
764
+ return `${WEB_AUTHORIZATION_PREFIX}:${conversationId}:${actorId}`;
765
+ }
766
+ /** Build authorization delivery for one web turn. */
767
+ function createWebAuthorization(args) {
768
+ return {
769
+ createState: async () => randomUUID(),
770
+ deliver: async (request) => {
771
+ await getStateAdapter().set(authorizationKey$1(args.conversationId, args.actorId), JSON.stringify({
772
+ ...request,
773
+ ...args
774
+ }), WEB_AUTHORIZATION_TTL_MS);
775
+ }
776
+ };
777
+ }
778
+ /** Read the pending authorization request for one web actor. */
779
+ async function getWebAuthorization(args) {
780
+ const value = await getStateAdapter().get(authorizationKey$1(args.conversationId, args.actorId));
781
+ if (typeof value !== "string") return void 0;
782
+ try {
783
+ const parsed = JSON.parse(value);
784
+ if (parsed.actorId !== args.actorId || parsed.conversationId !== args.conversationId || typeof parsed.authorizationUrl !== "string" || typeof parsed.label !== "string" || typeof parsed.completionText !== "string") return;
785
+ return parsed;
786
+ } catch {
787
+ return;
788
+ }
789
+ }
790
+ /** Remove a web authorization request after the parked turn continues. */
791
+ async function deleteWebAuthorization(args) {
792
+ await getStateAdapter().delete(authorizationKey$1(args.conversationId, args.actorId));
793
+ }
794
+ // src/chat/task-execution/attempt-selection.ts
795
+ function inputOwner(message) {
796
+ return {
797
+ authorId: message.input.authorId,
798
+ identityId: message.input.authorIdentityId,
799
+ source: message.source
800
+ };
801
+ }
802
+ function turnOwner(turn) {
803
+ return {
804
+ authorId: isUserActor(turn.actor) ? turn.actor.userId : void 0,
805
+ identityId: turn.actorIdentityId,
806
+ source: turn.source?.kind
807
+ };
808
+ }
809
+ /**
810
+ * One Turn has one Actor and one Source: it runs with that Actor's
811
+ * credentials, so input from anyone else must not join it. Every value that
812
+ * both sides know must match, and they must share an Identity id or an author
813
+ * id. Input with no known author matches nothing.
814
+ */
815
+ function hasSameOwner(a, b) {
816
+ if (a.source && b.source && a.source !== b.source) return false;
817
+ const sameIdentity = a.identityId && b.identityId ? a.identityId === b.identityId : void 0;
818
+ const sameAuthor = a.authorId && b.authorId ? a.authorId === b.authorId : void 0;
819
+ return sameIdentity !== false && sameAuthor !== false && (sameIdentity ?? sameAuthor) === true;
820
+ }
821
+ /** True when two Inbound messages may share one Turn. */
822
+ function canShareTurn(a, b) {
823
+ return hasSameOwner(inputOwner(a), inputOwner(b));
824
+ }
825
+ /** True when an Inbound message may join `turn`. */
826
+ function canJoinTurn(turn, message) {
827
+ return hasSameOwner(turnOwner(turn), inputOwner(message));
828
+ }
829
+ function selectContiguousTurnBatch(messages) {
830
+ const first = messages[0];
831
+ if (!first) return [];
832
+ const nextTurnIndex = messages.findIndex((message, index) => index > 0 && !canShareTurn(first, message));
833
+ return messages.slice(0, nextTurnIndex === -1 ? messages.length : nextTurnIndex);
834
+ }
835
+ /**
836
+ * True when an interrupt can start its own attempt.
837
+ *
838
+ * A steered web message must not start a second Turn while a yielded Turn
839
+ * waits to resume. It stays pending for that Turn's drain or the next attempt.
840
+ */
841
+ function isAttemptInterrupt(message, work) {
842
+ return message.delivery === "interrupt" && !(work.execution.status === "paused" && message.source === "web");
843
+ }
844
+ /** Prioritize interrupts while keeping each attempt to one Actor and Source. */
845
+ function selectAttemptMessages(work) {
846
+ const messages = work.messages;
847
+ const interrupts = messages.filter((message) => isAttemptInterrupt(message, work));
848
+ if (interrupts.length > 0) return selectContiguousTurnBatch(interrupts);
849
+ if (work.execution.status === "paused") return [];
850
+ const nonEventMessages = messages.filter((message) => message.source !== "event");
851
+ return selectContiguousTurnBatch(nonEventMessages.length > 0 ? nonEventMessages : messages);
852
+ }
853
+ // src/chat/task-execution/authorized-turn.ts
854
+ /**
855
+ * OAuth callbacks save readiness, not agent history. The conversation worker
856
+ * consumes this event under its lease before it resumes the paused Turn.
857
+ */
858
+ const authorizationSchema = z.object({
859
+ kind: z.enum(["mcp", "plugin"]),
860
+ provider: z.string().min(1),
861
+ actorId: z.string().min(1),
862
+ authorizationId: z.string().min(1),
863
+ authSessionId: z.string().optional(),
864
+ scope: z.string().optional(),
865
+ configuration: z.record(z.string(), z.unknown()).optional(),
866
+ toolChannelId: z.string().optional()
867
+ });
868
+ function authorizationKey(turn) {
869
+ return `turn:${turn.turnId}:authorization:${turn.version}`;
870
+ }
871
+ /** Save authorization for this parked boundary without changing model history. */
872
+ async function recordTurnAuthorization(args) {
873
+ const turn = await getTurnRecord(args.conversationId, args.turnId);
874
+ if (!turn || turn.state !== "paused" || turn.resumeReason !== "auth") return;
875
+ await getConversationEventStore().append(args.conversationId, [{
876
+ idempotencyKey: authorizationKey(turn),
877
+ createdAtMs: Date.now(),
878
+ data: {
879
+ type: "structured_event",
880
+ namespace: "junior",
881
+ name: "turn_authorized",
882
+ version: 1,
883
+ turnId: turn.turnId,
884
+ content: authorizationSchema.parse(args)
885
+ }
886
+ }], { activity: "preserve" });
887
+ return {
888
+ conversationId: args.conversationId,
889
+ destination: args.destination,
890
+ turnId: turn.turnId,
891
+ expectedVersion: turn.version
892
+ };
893
+ }
894
+ /** Read authorization for the exact pause; a later auth pause needs its own callback. */
895
+ async function getTurnAuthorization(turn) {
896
+ const event = await getConversationEventStore().loadByIdempotencyKey(turn.conversationId, authorizationKey(turn));
897
+ if (event?.data.type !== "structured_event") return void 0;
898
+ return authorizationSchema.parse(event.data.content);
899
+ }
900
+ // src/chat/task-execution/turn-wake.ts
901
+ /** Build the worker input for a paused turn. */
902
+ async function getPausedTurnRequest(args) {
903
+ const turn = (await loadTurnCheckpoint({
904
+ conversationId: args.conversationId,
905
+ turnId: args.turnId
906
+ })).record;
907
+ if (!turn || turn.state !== "paused" || turn.resumeReason !== "timeout" && turn.resumeReason !== "yield" && turn.resumeReason !== "retry" && !(turn.resumeReason === "auth" && await getTurnAuthorization(turn)) || turn.resumeReason === "timeout" && turn.sliceId < 2) return;
908
+ let routing;
909
+ try {
910
+ routing = await resolveTurnSessionRouting({
911
+ conversationId: args.conversationId,
912
+ conversationStore: args.conversationStore
913
+ });
914
+ } catch (error) {
915
+ await failTurnRecord({
916
+ conversationId: args.conversationId,
917
+ expectedVersion: turn.version,
918
+ turnId: args.turnId,
919
+ errorMessage: error instanceof Error ? error.message : String(error)
920
+ });
921
+ return;
922
+ }
923
+ return {
924
+ conversationId: args.conversationId,
925
+ destination: routing.destination,
926
+ turnId: args.turnId,
927
+ expectedVersion: turn.version,
928
+ traceContext: turn.traceContext
929
+ };
930
+ }
931
+ /** Wake the conversation worker for a paused turn. */
932
+ async function wakePausedTurn(request, options = {}) {
933
+ const nowMs = options.nowMs ?? Date.now();
934
+ const conversation = await (options.conversationStore ?? getConversationStore()).get({ conversationId: request.conversationId });
935
+ await requestConversationWork({
936
+ conversationId: request.conversationId,
937
+ destination: conversation && !isTopLevelKind(conversation.kind) ? void 0 : request.destination,
938
+ nowMs,
939
+ state: options.state
940
+ });
941
+ const queue = options.queue ?? getVercelConversationWorkQueue();
942
+ await ensureConversationWake({
943
+ conversationId: request.conversationId,
944
+ idempotencyKey: [
945
+ "agent-continue",
946
+ request.conversationId,
947
+ request.turnId,
948
+ request.expectedVersion,
949
+ nowMs
950
+ ].join(":"),
951
+ nowMs,
952
+ queue,
953
+ state: options.state
954
+ });
955
+ }
956
+ /** Create paused Turn operations for one app. */
957
+ function createPausedTurns(options = {}) {
958
+ return {
959
+ get: (args) => getPausedTurnRequest({
960
+ ...args,
961
+ conversationStore: options.conversationStore
962
+ }),
963
+ wake: (request) => wakePausedTurn(request, options)
964
+ };
965
+ }
966
+ /** Record completed authorization and wake the sole execution owner. */
967
+ async function wakeAuthorizedTurn(args, queue) {
968
+ const request = await recordTurnAuthorization(args);
969
+ if (request) await wakePausedTurn(request, { queue });
970
+ }
971
+ // src/chat/task-execution/supersede-turns.ts
972
+ /**
973
+ * End every open mailbox Turn other than `keepTurnId`, so new input runs in
974
+ * the only open Turn. New input starts only when no yielded Turn waits, so an
975
+ * open Turn here waits for OAuth or was left open by a failed or stopped Run.
976
+ * The caller persists `conversation`. Returns false when `isStopped` turns
977
+ * true first.
978
+ */
979
+ async function supersedeOpenMailboxTurns(args) {
980
+ return await supersedeTurns({
981
+ ...args,
982
+ turns: (await listActiveMailboxTurns(args.conversationId)).filter((record) => record.turnId !== args.keepTurnId)
983
+ });
984
+ }
985
+ /**
986
+ * End open Turns that new input replaces. A late resume or OAuth callback
987
+ * for an ended Turn is a no-op. The caller persists `conversation`. Returns
988
+ * false when `isStopped` turns true first.
989
+ */
990
+ async function supersedeTurns(args) {
991
+ const pendingAuthorizationActorId = args.conversation.processing.pendingAuth?.actorId;
992
+ for (const stale of args.turns) {
993
+ if (args.isStopped?.()) return false;
994
+ await abandonTurnRecord({
995
+ conversationId: args.conversationId,
996
+ turnId: stale.turnId,
997
+ errorMessage: "Turn superseded by new input"
998
+ });
999
+ await new ConversationTurnLifecycleService(getConversationEventStore()).complete({
1000
+ conversationId: args.conversationId,
1001
+ createdAtMs: Date.now(),
1002
+ outcome: "cancelled",
1003
+ turnId: stale.turnId
1004
+ });
1005
+ markTurnClosed({
1006
+ conversation: args.conversation,
1007
+ nowMs: Date.now(),
1008
+ sessionId: stale.turnId
1009
+ });
1010
+ }
1011
+ if (args.turns.some((record) => record.state === "paused" && record.resumeReason === "auth") && pendingAuthorizationActorId) await deleteWebAuthorization({
1012
+ actorId: pendingAuthorizationActorId,
1013
+ conversationId: args.conversationId
1014
+ });
1015
+ return true;
1016
+ }
1017
+ /**
1018
+ * End the Turn that waits for its next Run when `message` cannot join it, so
1019
+ * the message starts its own Turn instead of running with that Turn's Actor.
1020
+ * A stored legacy Turn without an Actor keeps taking the input.
1021
+ */
1022
+ async function supersedeTurnForInput(args) {
1023
+ const conversation = coerceThreadConversationState(await getPersistedThreadState(args.conversationId));
1024
+ const turnId = conversation.processing.activeTurnId;
1025
+ if (!turnId || !await getPausedTurnRequest({
1026
+ conversationId: args.conversationId,
1027
+ turnId
1028
+ })) return;
1029
+ const turn = await getTurnRecord(args.conversationId, turnId);
1030
+ if (!turn?.actor || canJoinTurn(turn, args.message)) return;
1031
+ await hydrateConversationMessages({
1032
+ conversation,
1033
+ conversationId: args.conversationId
1034
+ });
1035
+ await supersedeTurns({
1036
+ conversation,
1037
+ conversationId: args.conversationId,
1038
+ turns: [turn]
1039
+ });
1040
+ await persistThreadStateById(args.conversationId, { conversation });
1041
+ }
687
1042
  // src/chat/agent-invocations/thread-turn.ts
688
1043
  /**
689
1044
  * A person's Turn in a Thread runs on the Conversation loop. A
@@ -707,6 +1062,87 @@ async function supersedeOpenMailboxTurn(conversationId) {
707
1062
  });
708
1063
  await persistThreadStateById(conversationId, { conversation });
709
1064
  }
1065
+ // src/chat/agent-invocations/types.ts
1066
+ const exactStringSchema = z.string().min(1).refine((value) => value === value.trim());
1067
+ const agentNameSchema = exactStringSchema.max(64);
1068
+ /**
1069
+ * Kind of a new child Conversation. A Thread is a child that people can
1070
+ * message; a Task is one that only its parent messages.
1071
+ */
1072
+ const CHILD_AGENT_KINDS = ["thread", "task"];
1073
+ /** `messageAgent` target for the parent of a child agent. */
1074
+ const PARENT_AGENT_TARGET = "parent";
1075
+ const agentInvocationMailboxStatusSchema = z.enum(AGENT_INVOCATION_MAILBOX_STATUSES);
1076
+ const agentInvocationParentMailboxStatusSchema = z.enum(AGENT_INVOCATION_PARENT_MAILBOX_STATUSES);
1077
+ const agentBindingSchema = z.object({
1078
+ childConversationId: exactStringSchema,
1079
+ name: agentNameSchema,
1080
+ parentConversationId: exactStringSchema
1081
+ }).strict();
1082
+ const agentInvocationBaseSchema = z.object({
1083
+ actor: actorSchema,
1084
+ agentName: agentNameSchema.optional(),
1085
+ childConversationId: exactStringSchema,
1086
+ createdAtMs: z.number().finite(),
1087
+ credentialContext: credentialContextSchema.optional(),
1088
+ destination: destinationSchema,
1089
+ input: exactStringSchema,
1090
+ invocationId: exactStringSchema,
1091
+ mailboxStatus: agentInvocationMailboxStatusSchema,
1092
+ parentConversationId: exactStringSchema,
1093
+ parentToolCallId: exactStringSchema.optional(),
1094
+ agentType: agentTypeSchema.optional(),
1095
+ /** The child starts with its parent's history. */
1096
+ fork: z.literal(true).optional(),
1097
+ reasoningLevel: z.enum(TURN_REASONING_LEVELS).optional(),
1098
+ source: sourceSchema,
1099
+ title: exactStringSchema.optional(),
1100
+ updatedAtMs: z.number().finite()
1101
+ }).strict();
1102
+ const agentInvocationSchema = z.discriminatedUnion("status", [
1103
+ agentInvocationBaseSchema.extend({ status: z.enum([
1104
+ "pending",
1105
+ "running",
1106
+ "paused"
1107
+ ]) }),
1108
+ agentInvocationBaseSchema.extend({
1109
+ parentMailboxStatus: agentInvocationParentMailboxStatusSchema,
1110
+ result: z.string(),
1111
+ status: z.literal("completed"),
1112
+ terminalAtMs: z.number().finite()
1113
+ }),
1114
+ agentInvocationBaseSchema.extend({
1115
+ errorMessage: z.string(),
1116
+ parentMailboxStatus: agentInvocationParentMailboxStatusSchema,
1117
+ status: z.enum([
1118
+ "blocked",
1119
+ "failed",
1120
+ "stopped"
1121
+ ]),
1122
+ terminalAtMs: z.number().finite()
1123
+ })
1124
+ ]);
1125
+ const createAgentInvocationSchema = z.object({
1126
+ actor: actorSchema,
1127
+ agentName: agentNameSchema.optional(),
1128
+ credentialContext: credentialContextSchema.optional(),
1129
+ destination: destinationSchema,
1130
+ idempotencyKey: exactStringSchema,
1131
+ input: exactStringSchema,
1132
+ kind: z.enum(CHILD_AGENT_KINDS).default("task"),
1133
+ parentConversationId: exactStringSchema,
1134
+ parentToolCallId: exactStringSchema.optional(),
1135
+ agentType: agentTypeSchema.optional(),
1136
+ fork: z.literal(true).optional(),
1137
+ reasoningLevel: z.enum(TURN_REASONING_LEVELS).optional(),
1138
+ title: exactStringSchema.optional()
1139
+ }).strict();
1140
+ /** How a finished task of a child agent ended. A stop is not a result. */
1141
+ const CHILD_AGENT_RESULTS = [
1142
+ "completed",
1143
+ "blocked",
1144
+ "failed"
1145
+ ];
710
1146
  // src/chat/agent-invocations/bindings.ts
711
1147
  function bindingFromRow(row) {
712
1148
  return agentBindingSchema.parse({
@@ -720,14 +1156,18 @@ async function getAgentBinding(args) {
720
1156
  const rows = await getSqlExecutor().db().select().from(juniorAgentBindings).where(and(eq(juniorAgentBindings.parentConversationId, args.parentConversationId), eq(juniorAgentBindings.name, args.name)));
721
1157
  return rows[0] ? bindingFromRow(rows[0]) : void 0;
722
1158
  }
723
- /** Find a direct child agent of one parent by name or child Conversation id. */
1159
+ /**
1160
+ * Find a direct child agent of one parent by name or child Conversation id.
1161
+ * A child that no Agent invocation names stores its agent config.
1162
+ */
724
1163
  async function findChildAgentConversationId(args) {
725
1164
  const binding = await getAgentBinding({
726
1165
  name: args.target,
727
1166
  parentConversationId: args.parentConversationId
728
1167
  });
729
1168
  if (binding) return binding.childConversationId;
730
- return (await getSqlExecutor().db().select({ childConversationId: juniorAgentInvocations.childConversationId }).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, args.parentConversationId), eq(juniorAgentInvocations.childConversationId, args.target))).limit(1))[0]?.childConversationId;
1169
+ const db = getSqlExecutor().db();
1170
+ return (await db.select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(eq(juniorConversations.parentConversationId, args.parentConversationId), eq(juniorConversations.conversationId, args.target), or(isNotNull(juniorConversations.agentConfig), exists(db.select({ invocationId: juniorAgentInvocations.invocationId }).from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, args.target)))))).limit(1))[0]?.conversationId;
731
1171
  }
732
1172
  // src/chat/agent-invocations/errors.ts
733
1173
  /** A child agent already uses this name in the parent Conversation. */
@@ -818,13 +1258,13 @@ function sameCreateInput(invocation, input) {
818
1258
  * A stopped child agent cannot start or give work to child agents until its
819
1259
  * parent gives it new work. A Turn on the child's Conversation loop
820
1260
  * has no open agent invocation, but it can. A root Conversation has no agent
821
- * invocation, so it always passes. `open` is the parent's open work from
1261
+ * invocation or agent config, so it always passes. `open` is the parent's open work from
822
1262
  * `listOpenAgentInvocations`.
823
1263
  */
824
1264
  async function assertCanGiveChildWork(parentConversationId, open) {
825
1265
  if (open.some((row) => row.childConversationId === parentConversationId)) return;
826
1266
  const latest = await getLatestAgentInvocationForConversation(parentConversationId);
827
- if (latest && isStoppedAgentInvocation(latest)) throw new Error(`Agent conversation ${parentConversationId} is stopped and cannot give work to child agents`);
1267
+ if (latest ? isStoppedAgentInvocation(latest) : await readAgentConfig(parentConversationId) !== void 0 && await getConversationStoppedAtMs(parentConversationId) !== void 0) throw new Error(`Agent conversation ${parentConversationId} is stopped and cannot give work to child agents`);
828
1268
  }
829
1269
  /**
830
1270
  * Throw when giving work to one child agent would put its parent over
@@ -832,10 +1272,11 @@ async function assertCanGiveChildWork(parentConversationId, open) {
832
1272
  * has open work, so a busy child already counts and messages queued for it
833
1273
  * do not count again. A new or idle child becomes active. This is the only
834
1274
  * place the rule for which child agents count lives. `open` is the parent's
835
- * open work from `listOpenAgentInvocations`.
1275
+ * open work from `listOpenAgentInvocations`. A child that no agent
1276
+ * invocation names is active while its listing shows open work.
836
1277
  */
837
- function assertChildAgentCapacity(open, args) {
838
- const active = new Set(open.filter((row) => row.parentConversationId === args.parentConversationId).map((row) => row.childConversationId));
1278
+ async function assertChildAgentCapacity(open, args) {
1279
+ const active = /* @__PURE__ */ new Set([...open.filter((row) => row.parentConversationId === args.parentConversationId).map((row) => row.childConversationId), ...await listOpenChildAgentsWithoutAgentInvocations(args.parentConversationId)]);
839
1280
  if (!active.has(args.childConversationId) && active.size >= 8) throw new AgentInvocationLimitError(8);
840
1281
  }
841
1282
  /**
@@ -862,7 +1303,7 @@ async function createAgentInvocation(rawInput, nowMs = Date.now()) {
862
1303
  name: input.agentName,
863
1304
  parentConversationId: input.parentConversationId
864
1305
  })) throw new AgentNameInUseError(input.agentName);
865
- assertChildAgentCapacity(open, {
1306
+ await assertChildAgentCapacity(open, {
866
1307
  childConversationId,
867
1308
  parentConversationId: input.parentConversationId
868
1309
  });
@@ -916,9 +1357,11 @@ async function createAgentInvocationFromLatest(args, nowMs = Date.now()) {
916
1357
  childConversationId: latest.childConversationId,
917
1358
  credentialContext,
918
1359
  destination: latest.destination,
1360
+ fork: args.runAs?.fork,
919
1361
  input: args.input,
920
1362
  invocationId: args.invocationId,
921
1363
  parentConversationId: latest.parentConversationId,
1364
+ parentToolCallId: args.runAs?.parentToolCallId,
922
1365
  reasoningLevel: latest.reasoningLevel,
923
1366
  source: args.runAs?.source
924
1367
  }, nowMs);
@@ -943,19 +1386,21 @@ async function createAgentInvocationForMessage(input, nowMs = Date.now()) {
943
1386
  };
944
1387
  }
945
1388
  const latest = await getLatestAgentInvocationForConversation(input.childConversationId);
946
- if (!latest || latest.parentConversationId !== input.parentConversationId) throw new Error(`${input.childConversationId} is not a child agent of ${input.parentConversationId}`);
1389
+ const child = latest ?? await readChildConversationSender(input.childConversationId);
1390
+ if (!child || child.parentConversationId !== input.parentConversationId) throw new Error(`${input.childConversationId} is not a child agent of ${input.parentConversationId}`);
1391
+ const agentConfig = latest ?? await readAgentConfig(input.childConversationId) ?? {};
947
1392
  const open = await listOpenAgentInvocations(input.parentConversationId);
948
1393
  await assertCanGiveChildWork(input.parentConversationId, open);
949
- const openCount = open.filter((row) => row.childConversationId === input.childConversationId).length;
1394
+ const openCount = open.filter((row) => row.childConversationId === input.childConversationId).length + (latest ? 0 : await countOpenParentMessages(input.childConversationId));
950
1395
  if (openCount >= MAX_OPEN_AGENT_INVOCATIONS_PER_CHILD) throw new AgentMessageQueueFullError(MAX_OPEN_AGENT_INVOCATIONS_PER_CHILD);
951
- assertChildAgentCapacity(open, {
1396
+ await assertChildAgentCapacity(open, {
952
1397
  childConversationId: input.childConversationId,
953
1398
  parentConversationId: input.parentConversationId
954
1399
  });
955
1400
  const invocation = await insertAgentInvocation({
956
1401
  actor: input.actor,
957
- agentName: latest.agentName,
958
- agentType: latest.agentType,
1402
+ agentName: child.agentName,
1403
+ agentType: agentConfig.agentType,
959
1404
  childConversationId: input.childConversationId,
960
1405
  credentialContext: input.credentialContext,
961
1406
  destination: input.destination,
@@ -963,7 +1408,7 @@ async function createAgentInvocationForMessage(input, nowMs = Date.now()) {
963
1408
  invocationId,
964
1409
  parentConversationId: input.parentConversationId,
965
1410
  parentToolCallId: input.parentToolCallId,
966
- reasoningLevel: latest.reasoningLevel
1411
+ reasoningLevel: agentConfig.reasoningLevel
967
1412
  }, nowMs);
968
1413
  if (!invocation) throw new Error(`Agent invocation creation raced for ${invocationId}`);
969
1414
  return {
@@ -1115,6 +1560,83 @@ function savedTurnEnd(turn) {
1115
1560
  status: "completed"
1116
1561
  };
1117
1562
  }
1563
+ // src/chat/task-execution/turn-cancel.ts
1564
+ /**
1565
+ * End a cancelled Turn: a stop that a worker saw, or a stop of a Turn that
1566
+ * waits for sign-in with no worker.
1567
+ */
1568
+ /** Close a cancelled Turn, save it, and acknowledge its input. */
1569
+ async function completeCancelledConversationTurn(args) {
1570
+ const pendingAuthorization = args.conversation.processing.pendingAuth?.sessionId === args.turnId ? args.conversation.processing.pendingAuth : void 0;
1571
+ await abandonTurnRecord({
1572
+ conversationId: args.conversationId,
1573
+ turnId: args.turnId,
1574
+ errorMessage: "Turn cancelled"
1575
+ });
1576
+ clearPendingAuth(args.conversation, args.turnId);
1577
+ markConversationMessage(args.conversation, args.userMessageId, {
1578
+ replied: false,
1579
+ skippedReason: "turn cancelled"
1580
+ });
1581
+ markTurnClosed({
1582
+ conversation: args.conversation,
1583
+ nowMs: Date.now(),
1584
+ sessionId: args.turnId
1585
+ });
1586
+ if (pendingAuthorization) await deleteWebAuthorization({
1587
+ actorId: pendingAuthorization.actorId,
1588
+ conversationId: args.conversationId
1589
+ });
1590
+ await persistThreadStateById(args.conversationId, {
1591
+ conversation: args.conversation,
1592
+ sandboxRef: args.sandboxRef
1593
+ });
1594
+ await new ConversationTurnLifecycleService(getConversationEventStore()).complete({
1595
+ conversationId: args.conversationId,
1596
+ createdAtMs: Date.now(),
1597
+ outcome: "cancelled",
1598
+ turnId: args.turnId
1599
+ });
1600
+ await args.acknowledge();
1601
+ }
1602
+ /**
1603
+ * End the Turn of a stopped Conversation that waits for sign-in, so a later
1604
+ * sign-in cannot resume it. A web Turn waits as an auth-paused Turn record. A
1605
+ * Slack request waits as the thread's pending sign-in. Every stop path calls
1606
+ * this, because no worker holds a waiting Turn and the stop wake can go to
1607
+ * queued input first.
1608
+ */
1609
+ async function cancelSignInWait(conversationId) {
1610
+ const turnId = await getAuthPausedConversationTurnId(conversationId) ?? coerceThreadConversationState(await getPersistedThreadState(conversationId)).processing.pendingAuth?.sessionId;
1611
+ if (turnId) await cancelSignInPausedTurn({
1612
+ conversationId,
1613
+ turnId
1614
+ });
1615
+ }
1616
+ /**
1617
+ * Cancel a Turn that waits for sign-in outside its worker, with the same
1618
+ * cleanup as a stopped resume.
1619
+ */
1620
+ async function cancelSignInPausedTurn(args) {
1621
+ if (!await abandonTurnRecord({
1622
+ conversationId: args.conversationId,
1623
+ errorMessage: "Turn cancelled",
1624
+ onlyIfAuthPaused: true,
1625
+ turnId: args.turnId
1626
+ })) return;
1627
+ const conversation = coerceThreadConversationState(await getPersistedThreadState(args.conversationId));
1628
+ await hydrateConversationMessages({
1629
+ conversation,
1630
+ conversationId: args.conversationId
1631
+ });
1632
+ await completeCancelledConversationTurn({
1633
+ acknowledge: async () => {},
1634
+ conversation,
1635
+ conversationId: args.conversationId,
1636
+ turnId: args.turnId,
1637
+ userMessageId: getTurnUserMessage(conversation, args.turnId)?.id
1638
+ });
1639
+ }
1118
1640
  // src/chat/agent-invocations/stop.ts
1119
1641
  /**
1120
1642
  * Stop one child agent of a parent Conversation and every child agent below
@@ -1126,8 +1648,8 @@ function savedTurnEnd(turn) {
1126
1648
  * Returns undefined when the child does not belong to the parent.
1127
1649
  */
1128
1650
  async function stopChildAgent(args) {
1129
- const latest = await getLatestAgentInvocationForConversation(args.childConversationId);
1130
- const wasStopped = latest !== void 0 && (latest.status === "stopped" || isChildAgentSessionStopped(latest, await getConversationStoppedAtMs(args.childConversationId)));
1651
+ const [latest, stoppedAtMs] = await Promise.all([getLatestAgentInvocationForConversation(args.childConversationId), getConversationStoppedAtMs(args.childConversationId)]);
1652
+ const wasStopped = latest ? latest.status === "stopped" || isChildAgentSessionStopped(latest, stoppedAtMs) : stoppedAtMs !== void 0;
1131
1653
  const tree = await stopChildAgentInvocations(args);
1132
1654
  if (!tree) return;
1133
1655
  await finishStoppedTree(tree, tree.conversationIds, {
@@ -1208,13 +1730,16 @@ async function stopChildAgentsBelow(conversationId, options) {
1208
1730
  * ack yet is marked `skipped`.
1209
1731
  */
1210
1732
  async function skipUnreadResults(conversationId, nowMs, state) {
1211
- const invocationIds = ((await getConversationWorkState({
1733
+ const messages = (await getConversationWorkState({
1212
1734
  conversationId,
1213
1735
  state
1214
- }))?.messages ?? []).flatMap((message) => {
1215
- const invocationId = parseAgentInvocationResultMessageId(message.inboundMessageId) ?? (parseTurnReplyMessageId(message.inboundMessageId) === void 0 ? parseAgentReplyMessageId(message.inboundMessageId) : void 0);
1216
- return invocationId ? [invocationId] : [];
1217
- });
1736
+ }))?.messages ?? [];
1737
+ const invocationIds = [];
1738
+ for (const message of messages) {
1739
+ const sender = await readChildMessageSender(message);
1740
+ const invocation = sender && ownAgentInvocation(sender);
1741
+ if (invocation) invocationIds.push(invocation);
1742
+ }
1218
1743
  if (invocationIds.length === 0) return;
1219
1744
  await getSqlExecutor().db().update(juniorAgentInvocations).set({
1220
1745
  parentMailboxStatus: "skipped",
@@ -1223,11 +1748,10 @@ async function skipUnreadResults(conversationId, nowMs, state) {
1223
1748
  }
1224
1749
  /**
1225
1750
  * Drop the unread replies that Turns on the Conversation loop of the stopped
1226
- * Conversations left in each mailbox of `mailboxIds`. Such a reply names the
1227
- * sender's newest finished agent invocation, not work that the stop skips,
1228
- * so the stop drops it by its message id. A reply sent after the stop is
1229
- * dropped when it is read, while the sender is stopped. Call this after the
1230
- * stop is stored.
1751
+ * Conversations left in each mailbox of `mailboxIds`. Such a reply names
1752
+ * no work that the stop skips, so the stop drops it by its sender fields.
1753
+ * A reply sent after the stop is dropped when it is read, while the sender
1754
+ * is stopped. Call this after the stop is stored.
1231
1755
  *
1232
1756
  * A reply that a running Turn already took leaves the mailbox like one that
1233
1757
  * it read: the Turn's own ack removes nothing more.
@@ -1235,23 +1759,15 @@ async function skipUnreadResults(conversationId, nowMs, state) {
1235
1759
  async function dropUnreadLoopReplies(mailboxIds, stoppedIds, state) {
1236
1760
  const stopped = new Set(stoppedIds);
1237
1761
  for (const conversationId of mailboxIds) {
1238
- const replies = ((await getConversationWorkState({
1762
+ const messages = (await getConversationWorkState({
1239
1763
  conversationId,
1240
1764
  state
1241
- }))?.messages ?? []).flatMap((message) => {
1242
- const invocationId = parseTurnReplyMessageId(message.inboundMessageId) === void 0 ? void 0 : parseAgentReplyMessageId(message.inboundMessageId);
1243
- return invocationId ? [{
1244
- invocationId,
1245
- messageId: message.inboundMessageId
1246
- }] : [];
1247
- });
1248
- if (replies.length === 0) continue;
1249
- const senders = await getSqlExecutor().db().select({
1250
- childConversationId: juniorAgentInvocations.childConversationId,
1251
- invocationId: juniorAgentInvocations.invocationId
1252
- }).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.invocationId, replies.map((reply) => reply.invocationId)));
1253
- const stoppedSenders = new Set(senders.filter((sender) => stopped.has(sender.childConversationId)).map((sender) => sender.invocationId));
1254
- const inboundMessageIds = replies.filter((reply) => stoppedSenders.has(reply.invocationId)).map((reply) => reply.messageId);
1765
+ }))?.messages ?? [];
1766
+ const inboundMessageIds = [];
1767
+ for (const message of messages) {
1768
+ const sender = await readChildMessageSender(message);
1769
+ if (sender && !ownAgentInvocation(sender) && stopped.has(sender.conversationId)) inboundMessageIds.push(message.inboundMessageId);
1770
+ }
1255
1771
  if (inboundMessageIds.length > 0) await dropPendingMessages({
1256
1772
  conversationId,
1257
1773
  inboundMessageIds,
@@ -1265,7 +1781,7 @@ async function dropUnreadLoopReplies(mailboxIds, stoppedIds, state) {
1265
1781
  * is stored: the parent mailbox lock then drops a later reply.
1266
1782
  */
1267
1783
  async function dropOwnUnreadLoopReplies(conversationId, state) {
1268
- await dropUnreadLoopReplies((await getSqlExecutor().db().selectDistinct({ id: juniorAgentInvocations.parentConversationId }).from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, conversationId))).map((parent) => parent.id), [conversationId], state);
1784
+ await dropUnreadLoopReplies((await getSqlExecutor().db().select({ id: juniorConversations.parentConversationId }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId))).flatMap((parent) => parent.id ? [parent.id] : []), [conversationId], state);
1269
1785
  }
1270
1786
  /**
1271
1787
  * A Thread can hold a person's Turn that waits for sign-in. The stop ends
@@ -1295,7 +1811,9 @@ async function lockAgentConversationTree(childConversationId) {
1295
1811
  let parents = conversationIds;
1296
1812
  while (parents.length > 0) {
1297
1813
  for (const parent of parents) await executor.withLock(getChildAgentLockName(parent), async () => void 0);
1298
- parents = (await executor.db().selectDistinct({ childConversationId: juniorAgentInvocations.childConversationId }).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.parentConversationId, parents))).map((row) => row.childConversationId).filter((id) => !conversationIds.includes(id));
1814
+ const rows = await executor.db().selectDistinct({ childConversationId: juniorAgentInvocations.childConversationId }).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.parentConversationId, parents));
1815
+ const withoutInvocations = await executor.db().select({ childConversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(inArray(juniorConversations.parentConversationId, parents), isNotNull(juniorConversations.agentConfig)));
1816
+ parents = [...new Set([...rows, ...withoutInvocations].map((row) => row.childConversationId))].filter((id) => !conversationIds.includes(id));
1299
1817
  conversationIds.push(...parents);
1300
1818
  }
1301
1819
  return conversationIds;
@@ -1309,8 +1827,12 @@ async function withChildAgentsTaskedAfter(conversationId, conversationIds, taske
1309
1827
  childConversationId: juniorAgentInvocations.childConversationId,
1310
1828
  parentConversationId: juniorAgentInvocations.parentConversationId
1311
1829
  }).from(juniorAgentInvocations).where(and(inArray(juniorAgentInvocations.parentConversationId, [...conversationIds]), or(ne(juniorAgentInvocations.parentConversationId, conversationId), gt(juniorAgentInvocations.createdAt, new Date(taskedAfterMs)))));
1830
+ const withoutInvocations = await getSqlExecutor().db().select({
1831
+ childConversationId: juniorConversations.conversationId,
1832
+ parentConversationId: juniorConversations.parentConversationId
1833
+ }).from(juniorConversations).where(and(inArray(juniorConversations.parentConversationId, [...conversationIds]), isNotNull(juniorConversations.agentConfig), or(ne(juniorConversations.parentConversationId, conversationId), gt(juniorConversations.createdAt, new Date(taskedAfterMs)))));
1312
1834
  const kept = [conversationId];
1313
- for (let index = 0; index < kept.length; index += 1) for (const link of links) if (link.parentConversationId === kept[index] && !kept.includes(link.childConversationId)) kept.push(link.childConversationId);
1835
+ for (let index = 0; index < kept.length; index += 1) for (const link of [...links, ...withoutInvocations]) if (link.parentConversationId === kept[index] && !kept.includes(link.childConversationId)) kept.push(link.childConversationId);
1314
1836
  return kept;
1315
1837
  }
1316
1838
  /**
@@ -1319,7 +1841,9 @@ async function withChildAgentsTaskedAfter(conversationId, conversationIds, taske
1319
1841
  * parent.
1320
1842
  */
1321
1843
  async function stopChildAgentInvocations(args) {
1322
- if ((await getSqlExecutor().db().select({ invocationId: juniorAgentInvocations.invocationId }).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, args.parentConversationId), eq(juniorAgentInvocations.childConversationId, args.childConversationId))).limit(1)).length === 0) return;
1844
+ const db = getSqlExecutor().db();
1845
+ const [owned, child] = await Promise.all([db.select({ invocationId: juniorAgentInvocations.invocationId }).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, args.parentConversationId), eq(juniorAgentInvocations.childConversationId, args.childConversationId))).limit(1), db.select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(eq(juniorConversations.conversationId, args.childConversationId), eq(juniorConversations.parentConversationId, args.parentConversationId), isNotNull(juniorConversations.agentConfig)))]);
1846
+ if (owned.length === 0 && child.length === 0) return;
1323
1847
  return await stopAgentInvocationTree(args.childConversationId, args.nowMs);
1324
1848
  }
1325
1849
  /**
@@ -1839,25 +2363,128 @@ function createAgentInvocationWorker(agentRunner, options = {}) {
1839
2363
  return { status: "completed" };
1840
2364
  };
1841
2365
  }
2366
+ // src/chat/agent-invocations/parent-message.ts
2367
+ /**
2368
+ * A parent agent task or message to a child that no Agent invocation names.
2369
+ * It is an Event from the parent Conversation (`event.identifier`) with the
2370
+ * Actor and grants of the parent's Turn, and the `spawnAgent` or
2371
+ * `messageAgent` tool call that sent it. Its text is the raw task. `fork`
2372
+ * marks the task of a fork spawn.
2373
+ */
2374
+ const parentMessageSchema = z.object({
2375
+ actor: actorSchema,
2376
+ credentialContext: credentialContextSchema.optional(),
2377
+ event: z.object({
2378
+ eventType: z.literal(AGENT_PARENT_MESSAGE_EVENT_TYPE),
2379
+ identifier: z.string().min(1),
2380
+ namespace: z.literal(AGENT_INVOCATION_EVENT_NAMESPACE)
2381
+ }),
2382
+ fork: z.literal(true).optional(),
2383
+ kind: z.literal("event"),
2384
+ parentToolCallId: z.string().min(1)
2385
+ });
2386
+ /**
2387
+ * Return the author id of every parent message from one parent. It matches
2388
+ * no other input, so a parent message never shares a Turn with another
2389
+ * sender's input.
2390
+ */
2391
+ function parentMessageAuthorId(parentConversationId) {
2392
+ return `parent-agent:${parentConversationId}`;
2393
+ }
2394
+ /**
2395
+ * Read the parent message that one mailbox input is, if it is one. Check its
2396
+ * sender with `isFromStoredParent` before it gets any authority.
2397
+ */
2398
+ function readParentMessage(message) {
2399
+ if (message.source !== "event") return;
2400
+ const parsed = parentMessageSchema.safeParse(message.input.metadata);
2401
+ return parsed.success ? parsed.data : void 0;
2402
+ }
2403
+ /**
2404
+ * Return whether a parent message names the stored parent of the child that
2405
+ * received it, with that parent's author id. The caller drops another
2406
+ * message.
2407
+ */
2408
+ async function isFromStoredParent(message, parentMessage) {
2409
+ return (message.input.authorId === parentMessageAuthorId(parentMessage.event.identifier) ? await getSqlExecutor().db().select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(eq(juniorConversations.conversationId, message.conversationId), eq(juniorConversations.parentConversationId, parentMessage.event.identifier))) : []).length > 0;
2410
+ }
2411
+ /**
2412
+ * Log a parent message that a child dropped: its sender check failed, or a
2413
+ * stop skipped it. Call it once, where the child drops the message.
2414
+ */
2415
+ function logDroppedParentMessage(message, parentMessage) {
2416
+ logWarn("agent.parent_message.dropped", {
2417
+ "app.conversation_id": message.conversationId,
2418
+ "app.inbound_message_id": message.inboundMessageId,
2419
+ "app.parent_conversation_id": parentMessage.event.identifier
2420
+ });
2421
+ }
2422
+ /**
2423
+ * Render a parent message as the child model reads it, as an Agent
2424
+ * invocation renders its task.
2425
+ */
2426
+ async function parentMessageText(message, parentMessage) {
2427
+ return agentInvocationInputText({
2428
+ agentType: (await readAgentConfig(message.conversationId))?.agentType,
2429
+ fork: parentMessage.fork,
2430
+ input: message.input.text,
2431
+ parentToolCallId: parentMessage.parentToolCallId
2432
+ });
2433
+ }
2434
+ /**
2435
+ * Return whether a saved transcript Message is a parent message. Only the
2436
+ * root Turn code saves one, after its sender check.
2437
+ */
2438
+ function isParentMessageMeta(meta) {
2439
+ return meta?.eventNamespace === "junior" && meta.eventType === "agent.parent_message";
2440
+ }
2441
+ /**
2442
+ * Read when the root Turn code last saved a parent message to one child, or
2443
+ * undefined when it saved none.
2444
+ */
2445
+ async function readLastParentMessageAtMs(conversationId) {
2446
+ const payload = juniorConversationEvents.payload;
2447
+ const [row] = await getSqlExecutor().db().select({ createdAt: juniorConversationEvents.createdAt }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "message"), sql`${payload}->'meta'->>'eventNamespace' = ${AGENT_INVOCATION_EVENT_NAMESPACE}`, sql`${payload}->'meta'->>'eventType' = ${AGENT_PARENT_MESSAGE_EVENT_TYPE}`)).orderBy(desc(juniorConversationEvents.createdAt)).limit(1);
2448
+ return row?.createdAt.getTime();
2449
+ }
2450
+ /**
2451
+ * Apply the agent config of a child agent to one of its Turns on the root
2452
+ * Turn code. Every Turn keeps the reasoning level. A fork's first Turn
2453
+ * starts with its parent's history. A parent message is the child's
2454
+ * instruction, as on an Agent invocation, also when its Turn resumes
2455
+ * (`savedParentMessage`). `inputs` passed the sender check.
2456
+ */
2457
+ async function childAgentTurnOptions(args) {
2458
+ const options = await readAgentConfig(args.conversationId);
2459
+ const parentMessage = args.inputs.map(readParentMessage).find((input) => input !== void 0);
2460
+ return {
2461
+ history: parentMessage?.fork && args.history.length === 0 ? await loadForkHistory({
2462
+ parentConversationId: parentMessage.event.identifier,
2463
+ parentToolCallId: parentMessage.parentToolCallId
2464
+ }) : args.history,
2465
+ instruction: parentMessage || args.savedParentMessage ? { provenance: agentInstructionProvenance } : {},
2466
+ run: options?.reasoningLevel ? { reasoning: options.reasoningLevel } : {}
2467
+ };
2468
+ }
1842
2469
  // src/chat/agent-invocations/child-input.ts
1843
2470
  /**
1844
- * Read the agent invocation that one result or message Event refers to: the
1845
- * finished child work for a result, or the open sender work for a message.
2471
+ * Read the sender that one result, reply, or message Event names: the
2472
+ * finished child work for a result, or the sender for a reply or message.
1846
2473
  */
1847
2474
  function childAgentInput(message) {
1848
2475
  const metadata = message.input.metadata;
1849
2476
  if (!isEventMailboxMetadata(metadata) || metadata.event.namespace !== "junior") return;
1850
2477
  if (metadata.event.eventType === "agent.message") return {
1851
- invocationId: metadata.event.identifier,
1852
- kind: "message"
2478
+ kind: "message",
2479
+ senderId: metadata.event.identifier
1853
2480
  };
1854
2481
  if (metadata.event.eventType === "agent.reply") return {
1855
- invocationId: metadata.event.identifier,
1856
- kind: "reply"
2482
+ kind: "reply",
2483
+ senderId: metadata.event.identifier
1857
2484
  };
1858
2485
  return isAgentInvocationResultEventType(metadata.event.eventType) ? {
1859
- invocationId: metadata.event.identifier,
1860
- kind: "result"
2486
+ kind: "result",
2487
+ senderId: metadata.event.identifier
1861
2488
  } : void 0;
1862
2489
  }
1863
2490
  /**
@@ -1865,11 +2492,14 @@ function childAgentInput(message) {
1865
2492
  * agent status all read this, so they agree on which input starts work.
1866
2493
  *
1867
2494
  * A parent task or message goes to its agent invocation. `latest` is the
1868
- * Conversation's newest agent invocation; a root has none. With an open one, a Watch Event and input from a child agent go to an agent
1869
- * invocation, and so do a result, and input to a child that waits for its own
1870
- * child agents (`replaced`). A stopped child drops input from its own child
1871
- * agents, also input sent before the stop. A session stop at `stoppedAtMs`
1872
- * skips Events as `skipInputAfterConversationStop` does.
2495
+ * Conversation's newest agent invocation; a root has none. A parent message
2496
+ * that no Agent invocation names is dropped when it does not come from the
2497
+ * stored parent. With an open Agent invocation, that parent message, a Watch
2498
+ * Event, and input from a child agent go to an agent invocation, and so do a
2499
+ * result, and input to a child that waits for its own child agents
2500
+ * (`replaced`). A stopped child drops input from its own child agents, also
2501
+ * input sent before the stop. A session stop at `stoppedAtMs` skips Events
2502
+ * as `skipInputAfterConversationStop` does.
1873
2503
  *
1874
2504
  * TODO(dcramer): Drop the agent invocation route with the legacy child worker
1875
2505
  * (#3060 step 7).
@@ -1878,13 +2508,19 @@ async function routeChildInput(message, latest, stoppedAtMs) {
1878
2508
  if (isPersonInput(message.source)) return "Conversation loop";
1879
2509
  if (isAgentInvocationInput(message)) return "agent invocation";
1880
2510
  const open = latest !== void 0 && !isTerminalAgentInvocation(latest);
2511
+ const parentMessage = readParentMessage(message);
2512
+ if (parentMessage) {
2513
+ if (!await isFromStoredParent(message, parentMessage)) return "dropped";
2514
+ if (open) return "agent invocation";
2515
+ return isSkippedAfterConversationStop(message, stoppedAtMs) ? "dropped" : "Conversation loop";
2516
+ }
1881
2517
  const input = childAgentInput(message);
1882
2518
  if (!input) {
1883
2519
  if (open && isEventMailboxMetadata(message.input.metadata)) return "agent invocation";
1884
2520
  return isSkippedAfterConversationStop(message, stoppedAtMs) ? "dropped" : "Conversation loop";
1885
2521
  }
1886
2522
  if (latest && isStoppedAgentInvocation(latest)) return "dropped";
1887
- if (await isSkippedAgentResult(input, await getChildAgentInputInvocation(message, input), message)) return "dropped";
2523
+ if (await isSkippedAgentResult(input, message)) return "dropped";
1888
2524
  if (latest && (open || input.kind === "result" || latest.parentMailboxStatus === "replaced")) return "agent invocation";
1889
2525
  return isSkippedAfterConversationStop(message, stoppedAtMs) ? "dropped" : "Conversation loop";
1890
2526
  }
@@ -1896,29 +2532,311 @@ async function routeChildInput(message, latest, stoppedAtMs) {
1896
2532
  * its own: the stop drops it from the parent's mailbox. While the sending
1897
2533
  * child is stopped, a reply that it sent after the stop is also dropped.
1898
2534
  */
1899
- async function isSkippedAgentResult(input, invocation, message) {
2535
+ async function isSkippedAgentResult(input, message) {
1900
2536
  if (input.kind === "message") return false;
1901
- const skipped = isTerminalAgentInvocation(invocation) && invocation.parentMailboxStatus === "skipped";
2537
+ const { invocation, sender } = await getChildAgentInputSender(message, input);
2538
+ const skipped = invocation !== void 0 && isTerminalAgentInvocation(invocation) && invocation.parentMailboxStatus === "skipped";
1902
2539
  if (input.kind === "result") return skipped;
1903
- if (skipped && parseTurnReplyMessageId(message.inboundMessageId) === void 0) return true;
1904
- const senderStoppedAtMs = await getConversationStoppedAtMs(invocation.childConversationId);
2540
+ if (skipped) {
2541
+ const fields = await readChildMessageSender(message);
2542
+ if (!fields || ownAgentInvocation(fields)) return true;
2543
+ }
2544
+ const senderStoppedAtMs = await getConversationStoppedAtMs(sender.childConversationId);
1905
2545
  return senderStoppedAtMs !== void 0 && message.createdAtMs >= senderStoppedAtMs;
1906
2546
  }
1907
2547
  /**
1908
- * Read the agent invocation of one result or message and check that it
1909
- * belongs to a child of the Conversation that received it.
2548
+ * Read the sender of one child Conversation that no Agent invocation names,
2549
+ * from its parent edge and its binding. A Conversation without a parent has
2550
+ * none.
2551
+ */
2552
+ async function readChildConversationSender(childConversationId) {
2553
+ const parent = alias(juniorConversations, "parent");
2554
+ const [row] = await getSqlExecutor().db().select({
2555
+ agentName: juniorAgentBindings.name,
2556
+ parentConversationId: parent.conversationId,
2557
+ title: juniorConversations.title
2558
+ }).from(juniorConversations).innerJoin(parent, eq(parent.conversationId, juniorConversations.parentConversationId)).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(eq(juniorConversations.conversationId, childConversationId));
2559
+ return row ? {
2560
+ ...row.agentName ? { agentName: row.agentName } : void 0,
2561
+ childConversationId,
2562
+ parentConversationId: row.parentConversationId,
2563
+ ...row.title ? { title: row.title } : void 0
2564
+ } : void 0;
2565
+ }
2566
+ /**
2567
+ * Read the sender of one result, reply, or message and check that it is a
2568
+ * child of the Conversation that received it. The Agent invocation that the
2569
+ * input names wins. A reply or message from a child that no Agent invocation
2570
+ * names comes from its child Conversation, and has no `invocation`.
2571
+ */
2572
+ async function getChildAgentInputSender(message, input) {
2573
+ const invocation = await getAgentInvocation(input.senderId);
2574
+ const sender = invocation ? input.kind === "result" && !isTerminalAgentInvocation(invocation) ? void 0 : invocation : input.kind === "result" ? void 0 : await readChildConversationSender(input.senderId);
2575
+ if (!sender || sender.parentConversationId !== message.conversationId) throw new Error(`Agent invocation ${input.kind} ${input.senderId} does not belong to ${message.conversationId}`);
2576
+ return invocation ? {
2577
+ invocation,
2578
+ sender
2579
+ } : { sender };
2580
+ }
2581
+ // src/chat/agent-invocations/store.ts
2582
+ /** Statuses of a finished agent invocation. */
2583
+ const TERMINAL_AGENT_INVOCATION_STATUSES = [
2584
+ "blocked",
2585
+ "completed",
2586
+ "failed",
2587
+ "stopped"
2588
+ ];
2589
+ /** Statuses of an agent invocation that owns its child's Turn. */
2590
+ const ACTIVE_AGENT_INVOCATION_STATUSES = ["running", "paused"];
2591
+ /** Statuses of an agent invocation that has not finished. */
2592
+ const NON_TERMINAL_AGENT_INVOCATION_STATUSES = [
2593
+ "pending",
2594
+ "running",
2595
+ "paused"
2596
+ ];
2597
+ /** Parse one agent invocation row. */
2598
+ function invocationFromRow(row) {
2599
+ return agentInvocationSchema.parse({
2600
+ actor: row.actor,
2601
+ ...row.agentName ? { agentName: row.agentName } : void 0,
2602
+ childConversationId: row.childConversationId,
2603
+ createdAtMs: row.createdAt.getTime(),
2604
+ ...row.credentialContext ? { credentialContext: row.credentialContext } : void 0,
2605
+ destination: row.destination,
2606
+ ...row.errorMessage !== null ? { errorMessage: row.errorMessage } : void 0,
2607
+ input: row.input,
2608
+ invocationId: row.invocationId,
2609
+ mailboxStatus: row.mailboxStatus,
2610
+ parentConversationId: row.parentConversationId,
2611
+ ...row.parentMailboxStatus ? { parentMailboxStatus: row.parentMailboxStatus } : void 0,
2612
+ ...row.parentToolCallId ? { parentToolCallId: row.parentToolCallId } : void 0,
2613
+ ...row.agentType ? { agentType: row.agentType } : void 0,
2614
+ ...row.fork ? { fork: true } : void 0,
2615
+ ...row.reasoningLevel ? { reasoningLevel: row.reasoningLevel } : void 0,
2616
+ ...row.result !== null ? { result: row.result } : void 0,
2617
+ source: row.source,
2618
+ status: row.status,
2619
+ ...row.terminalAt ? { terminalAtMs: row.terminalAt.getTime() } : void 0,
2620
+ ...row.title ? { title: row.title } : void 0,
2621
+ updatedAtMs: row.updatedAt.getTime()
2622
+ });
2623
+ }
2624
+ /** Read one durable agent invocation. */
2625
+ async function getAgentInvocation(invocationId) {
2626
+ const rows = await getSqlExecutor().db().select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.invocationId, invocationId));
2627
+ return rows[0] ? invocationFromRow(rows[0]) : void 0;
2628
+ }
2629
+ /** List the agent invocations of one child Conversation in the given statuses. */
2630
+ async function listAgentInvocationsForConversation(childConversationId, statuses) {
2631
+ return (await getSqlExecutor().db().select().from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.childConversationId, childConversationId), inArray(juniorAgentInvocations.status, [...statuses]))).orderBy(asc(juniorAgentInvocations.createdAt))).map(invocationFromRow);
2632
+ }
2633
+ /** Resolve the single invocation that may resume for one child conversation. */
2634
+ async function getActiveAgentInvocationForConversation(childConversationId) {
2635
+ const active = await listAgentInvocationsForConversation(childConversationId, ACTIVE_AGENT_INVOCATION_STATUSES);
2636
+ if (active.length > 1) throw new Error(`Child conversation ${childConversationId} has multiple active agent invocations`);
2637
+ return active[0];
2638
+ }
2639
+ /** Read the newest agent invocation of one child Conversation. */
2640
+ async function getLatestAgentInvocationForConversation(childConversationId) {
2641
+ const rows = await getSqlExecutor().db().select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, childConversationId)).orderBy(desc(juniorAgentInvocations.createdAt)).limit(1);
2642
+ return rows[0] ? invocationFromRow(rows[0]) : void 0;
2643
+ }
2644
+ /**
2645
+ * Read the name, agent type, fork flag, and newest task title of one child
2646
+ * Conversation, for labels. Agent invocations that give a nested result to
2647
+ * the child have no title, so an agent invocation with a title comes first.
2648
+ * Each agent invocation keeps the child's agent type, but only the one that
2649
+ * started a fork has `fork` set, so the flag reads every agent invocation.
2650
+ * A child that no Agent invocation names reads its binding, title, and
2651
+ * agent config.
2652
+ */
2653
+ async function getChildAgentLabel(childConversationId) {
2654
+ const [row] = await getSqlExecutor().db().select({
2655
+ agentName: juniorAgentInvocations.agentName,
2656
+ agentType: juniorAgentInvocations.agentType,
2657
+ fork: sql`bool_or(${juniorAgentInvocations.fork}) over ()`,
2658
+ title: juniorAgentInvocations.title
2659
+ }).from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, childConversationId)).orderBy(sql`${juniorAgentInvocations.title} is null`, desc(juniorAgentInvocations.createdAt)).limit(1);
2660
+ if (row) return row;
2661
+ const [sender, options] = await Promise.all([readChildConversationSender(childConversationId), readAgentConfig(childConversationId)]);
2662
+ return sender && options ? {
2663
+ agentName: sender.agentName ?? null,
2664
+ agentType: options.agentType ?? null,
2665
+ fork: options.fork ?? false,
2666
+ title: sender.title ?? null
2667
+ } : void 0;
2668
+ }
2669
+ /**
2670
+ * List the open agent invocations that run on one Conversation or on its
2671
+ * child agents, oldest first. Open-work checks read this once and filter it.
1910
2672
  */
1911
- async function getChildAgentInputInvocation(message, input) {
1912
- const invocation = await getAgentInvocation(input.invocationId);
1913
- if (!invocation || input.kind === "result" && !isTerminalAgentInvocation(invocation) || invocation.parentConversationId !== message.conversationId) throw new Error(`Agent invocation ${input.kind} ${input.invocationId} does not belong to ${message.conversationId}`);
1914
- return invocation;
2673
+ async function listOpenAgentInvocations(conversationId) {
2674
+ return (await getSqlExecutor().db().select().from(juniorAgentInvocations).where(and(or(eq(juniorAgentInvocations.childConversationId, conversationId), eq(juniorAgentInvocations.parentConversationId, conversationId)), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES))).orderBy(asc(juniorAgentInvocations.createdAt))).map(invocationFromRow);
2675
+ }
2676
+ /**
2677
+ * Return whether a terminal agent invocation sends its result to the parent.
2678
+ * A child's final response stays in its Conversation, and a `reply` that
2679
+ * reached the parent (one of `parentMessages`) answered for the Agent
2680
+ * invocation. A failure after that, such as a lost worker before the
2681
+ * Turn was saved, is not sent either.
2682
+ */
2683
+ function sendsResultToParent(invocation, parentMessages) {
2684
+ const replied = hasAgentInvocationReply(parentMessages, invocation.invocationId);
2685
+ switch (invocation.status) {
2686
+ case "completed": return !replied && Boolean(invocation.result?.trim());
2687
+ case "failed": return !replied;
2688
+ default: return true;
2689
+ }
2690
+ }
2691
+ /**
2692
+ * Return whether a child Conversation has work that will start another agent
2693
+ * invocation on it: another open agent invocation, an open child agent, or a
2694
+ * child agent result that is sent but still waits in its mailbox. A child
2695
+ * agent that no Agent invocation names is open as `listAgents` shows it,
2696
+ * and its unread result or reply also waits.
2697
+ */
2698
+ async function hasOpenChildWork(invocation) {
2699
+ const conversationId = invocation.childConversationId;
2700
+ if ((await listOpenAgentInvocations(conversationId)).some((row) => row.invocationId !== invocation.invocationId) || (await listOpenChildAgentsWithoutAgentInvocations(conversationId)).length > 0) return true;
2701
+ const work = await getConversationWorkState({ conversationId });
2702
+ for (const message of work?.messages ?? []) {
2703
+ const sender = await readChildMessageSender(message);
2704
+ if (sender && !sender.agentInvocationId) return true;
2705
+ }
2706
+ const marked = await getSqlExecutor().db().select({
2707
+ invocationId: juniorAgentInvocations.invocationId,
2708
+ parentMailboxStatus: juniorAgentInvocations.parentMailboxStatus,
2709
+ result: juniorAgentInvocations.result,
2710
+ status: juniorAgentInvocations.status
2711
+ }).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, conversationId), inArray(juniorAgentInvocations.parentMailboxStatus, ["pending", "appended"])));
2712
+ if (marked.length === 0) return false;
2713
+ const unread = new Set(work?.messages.map((message) => message.inboundMessageId));
2714
+ const parentMessages = await listChildMessages(work?.execution.inboundMessageIds ?? [], work?.execution.messageSenders ?? {});
2715
+ return marked.some((row) => sendsResultToParent(row, parentMessages) && (row.parentMailboxStatus === "pending" || unread.has(getAgentInvocationResultMessageId(row.invocationId))));
2716
+ }
2717
+ /** List bounded invocation records whose mailbox append still needs repair. */
2718
+ async function listPendingAgentInvocationMailboxAppends(limit = 100) {
2719
+ return (await getSqlExecutor().db().select().from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.mailboxStatus, "pending"), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES))).orderBy(asc(juniorAgentInvocations.createdAt)).limit(limit)).map(invocationFromRow);
2720
+ }
2721
+ /** List terminal agent invocation results that still need a parent mailbox append. */
2722
+ async function listPendingAgentInvocationResults(limit = 100) {
2723
+ return (await getSqlExecutor().db().select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.parentMailboxStatus, "pending")).orderBy(asc(juniorAgentInvocations.terminalAt)).limit(limit)).map(invocationFromRow).filter(isTerminalAgentInvocation);
2724
+ }
2725
+ /**
2726
+ * Send a `replaced` result to the parent now. A stop ended the open work of
2727
+ * the child, so no later agent invocation sends the report.
2728
+ */
2729
+ async function reportReplacedAgentInvocation(invocationId, nowMs = Date.now()) {
2730
+ await getSqlExecutor().db().update(juniorAgentInvocations).set({
2731
+ parentMailboxStatus: "pending",
2732
+ updatedAt: new Date(nowMs)
2733
+ }).where(and(eq(juniorAgentInvocations.invocationId, invocationId), eq(juniorAgentInvocations.parentMailboxStatus, "replaced")));
2734
+ return await getAgentInvocation(invocationId);
2735
+ }
2736
+ /**
2737
+ * Send the `replaced` result of a child Conversation when its open child work
2738
+ * ended and sent it nothing, such as a helper that ended with `noReply`. No
2739
+ * later agent invocation of the child would send the report. Input from its
2740
+ * own child agents that still waits in its mailbox starts one, so that one
2741
+ * reports instead.
2742
+ */
2743
+ async function reportReplacedWithoutOpenWork(conversationId, nowMs = Date.now()) {
2744
+ const latest = await getLatestAgentInvocationForConversation(conversationId);
2745
+ if (!latest || !isTerminalAgentInvocation(latest) || latest.parentMailboxStatus !== "replaced" || await hasOpenChildWork(latest)) return;
2746
+ if ((await getConversationWorkState({ conversationId }))?.messages.some(isChildAgentInputMessage)) return;
2747
+ return await reportReplacedAgentInvocation(latest.invocationId, nowMs);
2748
+ }
2749
+ function isChildAgentInputMessage(message) {
2750
+ const metadata = message.input.metadata;
2751
+ return isEventMailboxMetadata(metadata) && metadata.event.namespace === "junior" && metadata.event.eventType !== "agent.parent_message";
2752
+ }
2753
+ /** Record that one terminal result is in its parent mailbox. */
2754
+ async function markAgentInvocationParentMailboxAppended(invocationId, nowMs = Date.now()) {
2755
+ await getSqlExecutor().db().update(juniorAgentInvocations).set({
2756
+ parentMailboxStatus: "appended",
2757
+ updatedAt: new Date(nowMs)
2758
+ }).where(and(eq(juniorAgentInvocations.invocationId, invocationId), eq(juniorAgentInvocations.parentMailboxStatus, "pending")));
2759
+ }
2760
+ /** Record that the invocation's idempotent mailbox append completed. */
2761
+ async function markAgentInvocationMailboxAppended(invocationId, nowMs = Date.now()) {
2762
+ await getSqlExecutor().db().update(juniorAgentInvocations).set({
2763
+ mailboxStatus: "appended",
2764
+ updatedAt: new Date(nowMs)
2765
+ }).where(eq(juniorAgentInvocations.invocationId, invocationId));
2766
+ }
2767
+ /** Mark one non-terminal invocation as actively executing. */
2768
+ async function markAgentInvocationRunning(invocationId, nowMs = Date.now()) {
2769
+ await getSqlExecutor().db().update(juniorAgentInvocations).set({
2770
+ status: "running",
2771
+ updatedAt: new Date(nowMs)
2772
+ }).where(and(eq(juniorAgentInvocations.invocationId, invocationId), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES)));
2773
+ return await getAgentInvocation(invocationId);
2774
+ }
2775
+ /** Mark one invocation as waiting for another shared execution slice. */
2776
+ async function markAgentInvocationPaused(invocationId, nowMs = Date.now()) {
2777
+ await getSqlExecutor().db().update(juniorAgentInvocations).set({
2778
+ status: "paused",
2779
+ updatedAt: new Date(nowMs)
2780
+ }).where(and(eq(juniorAgentInvocations.invocationId, invocationId), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES)));
2781
+ }
2782
+ /**
2783
+ * Persist one terminal invocation result without overwriting an earlier
2784
+ * result. The same write marks the result for the parent mailbox. If the
2785
+ * child still has open work, the result is `replaced`: the parent gets one
2786
+ * report, from the agent invocation that finishes the child's work.
2787
+ * `reportNow` sends the result even then, when that open work does not
2788
+ * continue this task.
2789
+ */
2790
+ async function completeAgentInvocation(args) {
2791
+ const nowMs = args.nowMs ?? Date.now();
2792
+ const current = await getAgentInvocation(args.invocationId);
2793
+ if (!current || isTerminalAgentInvocation(current)) return current;
2794
+ const parentMailboxStatus = !args.reportNow && args.status !== "stopped" && await hasOpenChildWork(current) ? "replaced" : "pending";
2795
+ await getSqlExecutor().db().update(juniorAgentInvocations).set({
2796
+ status: args.status,
2797
+ result: args.status === "completed" ? args.result : null,
2798
+ errorMessage: args.status === "completed" ? null : args.errorMessage,
2799
+ parentMailboxStatus,
2800
+ terminalAt: new Date(nowMs),
2801
+ updatedAt: new Date(nowMs)
2802
+ }).where(and(eq(juniorAgentInvocations.invocationId, args.invocationId), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES)));
2803
+ return await getAgentInvocation(args.invocationId);
2804
+ }
2805
+ /**
2806
+ * End a pending agent invocation whose input the running agent invocation of
2807
+ * the same child read as a steering message. The running agent invocation
2808
+ * reports for both, so this one is never sent to the parent.
2809
+ */
2810
+ async function markAgentInvocationSteered(invocationId, nowMs = Date.now()) {
2811
+ await getSqlExecutor().db().update(juniorAgentInvocations).set({
2812
+ status: "completed",
2813
+ result: "",
2814
+ parentMailboxStatus: "steered",
2815
+ terminalAt: new Date(nowMs),
2816
+ updatedAt: new Date(nowMs)
2817
+ }).where(and(eq(juniorAgentInvocations.invocationId, invocationId), eq(juniorAgentInvocations.status, "pending")));
2818
+ return await getAgentInvocation(invocationId);
2819
+ }
2820
+ /** Return whether an agent invocation has finished. */
2821
+ function isTerminalAgentInvocation(invocation) {
2822
+ return TERMINAL_AGENT_INVOCATION_STATUSES.includes(invocation.status);
2823
+ }
2824
+ /**
2825
+ * Return whether the newest agent invocation of a child shows a stop. A tree
2826
+ * stop leaves a `replaced` agent invocation with its finished status and
2827
+ * marks it `skipped`, so that also means stopped.
2828
+ */
2829
+ function isStoppedAgentInvocation(invocation) {
2830
+ return invocation.status === "stopped" || isTerminalAgentInvocation(invocation) && invocation.parentMailboxStatus === "skipped";
1915
2831
  }
1916
2832
  // src/chat/agent-invocations/list.ts
1917
2833
  function isChildAgentResult(status) {
1918
2834
  return CHILD_AGENT_RESULTS.includes(status);
1919
2835
  }
2836
+ const childAgentKindSchema = z.enum(CHILD_AGENT_KINDS);
1920
2837
  /** Bound the agent invocations that one child agent listing reads. */
1921
2838
  const CHILD_AGENT_LIST_INVOCATION_LIMIT = 200;
2839
+ const CONVERSATION_LOOP_CHECK_CONCURRENCY = 8;
1922
2840
  /** Return whether a child's session stopped after its latest agent invocation. */
1923
2841
  function isChildAgentSessionStopped(latest, stoppedAtMs) {
1924
2842
  return stoppedAtMs !== void 0 && stoppedAtMs >= latest.createdAtMs;
@@ -1949,9 +2867,14 @@ function childAgentFromInvocations(invocations, resultInvocationIds, facts) {
1949
2867
  /**
1950
2868
  * List the direct child agents of one parent Conversation, with the newest
1951
2869
  * activity first. The state comes from SQL agent invocation records, not from
1952
- * model output.
2870
+ * model output. A child that no agent invocation names shows the state of
2871
+ * its Turns and mailbox.
1953
2872
  */
1954
2873
  async function listChildAgents(parentConversationId) {
2874
+ const [withInvocations, withoutInvocations] = await Promise.all([listChildAgentsFromInvocations(parentConversationId), listChildAgentsWithoutAgentInvocations(parentConversationId)]);
2875
+ return [...withInvocations, ...withoutInvocations].sort((left, right) => right.updatedAtMs - left.updatedAtMs);
2876
+ }
2877
+ async function listChildAgentsFromInvocations(parentConversationId) {
1955
2878
  const db = getSqlExecutor().db();
1956
2879
  const rows = await db.select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.parentConversationId, parentConversationId)).orderBy(desc(juniorAgentInvocations.createdAt)).limit(CHILD_AGENT_LIST_INVOCATION_LIMIT);
1957
2880
  if (rows.length === 0) return [];
@@ -1971,14 +2894,77 @@ async function listChildAgents(parentConversationId) {
1971
2894
  parentConversationId: juniorConversations.parentConversationId,
1972
2895
  stoppedAt: juniorConversations.stoppedAt
1973
2896
  }).from(juniorConversations).where(inArray(juniorConversations.conversationId, [...byChild.keys()]));
1974
- const onConversationLoop = new Set((await Promise.all(conversations.filter((row) => row.executionStatus === "pending" || row.executionStatus === "running" || row.executionStatus === "paused").map(async (row) => await runsOnConversationLoop(row.conversationId, conversationKindFromRow(row), byChild.get(row.conversationId)[0], row.stoppedAt?.getTime()) ? row.conversationId : void 0))).filter((id) => id !== void 0));
2897
+ const active = conversations.filter((row) => row.executionStatus === "pending" || row.executionStatus === "running" || row.executionStatus === "paused");
2898
+ const activeIds = active.map((row) => row.conversationId);
2899
+ const [workStates, mailboxTurnSources] = await Promise.all([getConversationWorkStates(activeIds), listActiveMailboxTurnSources(activeIds)]);
2900
+ const limit = pLimit(CONVERSATION_LOOP_CHECK_CONCURRENCY);
2901
+ const onConversationLoop = new Set((await Promise.all(active.map((row) => limit(async () => await runsOnConversationLoop(conversationKindFromRow(row), byChild.get(row.conversationId)[0], row.stoppedAt?.getTime(), workStates.get(row.conversationId)?.execution.pendingMessages ?? [], mailboxTurnSources.get(row.conversationId) ?? []) ? row.conversationId : void 0)))).filter((id) => id !== void 0));
1975
2902
  const factsByChild = new Map(conversations.map((row) => [row.conversationId, {
1976
2903
  ...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
1977
2904
  kind: conversationKindFromRow(row) === "thread" ? "thread" : "task",
1978
2905
  ...row.stoppedAt ? { stoppedAtMs: row.stoppedAt.getTime() } : void 0,
1979
2906
  onConversationLoop: onConversationLoop.has(row.conversationId)
1980
2907
  }]));
1981
- return [...byChild.entries()].map(([childConversationId, invocations]) => childAgentFromInvocations(invocations, resultInvocationIds, factsByChild.get(childConversationId) ?? { kind: "task" })).sort((left, right) => right.updatedAtMs - left.updatedAtMs);
2908
+ return [...byChild.entries()].map(([childConversationId, invocations]) => childAgentFromInvocations(invocations, resultInvocationIds, factsByChild.get(childConversationId) ?? { kind: "task" }));
2909
+ }
2910
+ /**
2911
+ * List the ids of the child agents of one parent that no agent invocation
2912
+ * names and that have open work.
2913
+ */
2914
+ async function listOpenChildAgentsWithoutAgentInvocations(parentConversationId) {
2915
+ return (await listChildAgentsWithoutAgentInvocations(parentConversationId)).filter((child) => NON_TERMINAL_AGENT_INVOCATION_STATUSES.includes(child.status)).map((child) => child.childConversationId);
2916
+ }
2917
+ /**
2918
+ * Count the open parent messages of one child that no Agent invocation
2919
+ * names: each one that waits in its mailbox, and each open Turn, which runs
2920
+ * one. This is the queue that `MAX_OPEN_AGENT_INVOCATIONS_PER_CHILD` caps.
2921
+ */
2922
+ async function countOpenParentMessages(childConversationId) {
2923
+ const [turns, work] = await Promise.all([listActiveMailboxTurns(childConversationId), getConversationWorkState({ conversationId: childConversationId })]);
2924
+ return turns.length + (work?.messages ?? []).filter((message) => readParentMessage(message) !== void 0).length;
2925
+ }
2926
+ /**
2927
+ * List the child agents of one parent that no agent invocation names. Each
2928
+ * stores its agent config, so older children of a parent, such as ones
2929
+ * that a removed feature created, are not listed. A child is `running` while
2930
+ * a Turn or mailbox input that answers its parent is open, and is `failed`
2931
+ * when its last Turn failed.
2932
+ *
2933
+ * TODO(dcramer): Make this the only listing when #3060 step 7 drops the
2934
+ * agent invocation table.
2935
+ */
2936
+ async function listChildAgentsWithoutAgentInvocations(parentConversationId) {
2937
+ const db = getSqlExecutor().db();
2938
+ const rows = await db.select({
2939
+ agentName: juniorAgentBindings.name,
2940
+ archivedAt: juniorConversations.archivedAt,
2941
+ conversationId: juniorConversations.conversationId,
2942
+ executionStatus: juniorConversations.executionStatus,
2943
+ executionUpdatedAt: juniorConversations.executionUpdatedAt,
2944
+ kind: juniorConversations.kind,
2945
+ parentConversationId: juniorConversations.parentConversationId,
2946
+ stoppedAt: juniorConversations.stoppedAt,
2947
+ title: juniorConversations.title,
2948
+ updatedAt: juniorConversations.updatedAt
2949
+ }).from(juniorConversations).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(and(eq(juniorConversations.parentConversationId, parentConversationId), isNotNull(juniorConversations.agentConfig), notExists(db.select({ invocationId: juniorAgentInvocations.invocationId }).from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, juniorConversations.conversationId))))).limit(CHILD_AGENT_LIST_INVOCATION_LIMIT);
2950
+ const ids = rows.map((row) => row.conversationId);
2951
+ const [workStates, mailboxTurnSources] = await Promise.all([getConversationWorkStates(ids), listActiveMailboxTurnSources(ids)]);
2952
+ const limit = pLimit(CONVERSATION_LOOP_CHECK_CONCURRENCY);
2953
+ return await Promise.all(rows.map(async (row) => {
2954
+ const kind = childAgentKindSchema.parse(row.kind);
2955
+ const stoppedAtMs = row.stoppedAt?.getTime();
2956
+ const running = stoppedAtMs === void 0 && await limit(() => runsOnConversationLoop(kind, void 0, void 0, workStates.get(row.conversationId)?.execution.pendingMessages ?? [], mailboxTurnSources.get(row.conversationId) ?? []));
2957
+ return {
2958
+ ...row.agentName ? { agentName: row.agentName } : void 0,
2959
+ ...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
2960
+ childConversationId: row.conversationId,
2961
+ kind,
2962
+ status: stoppedAtMs !== void 0 ? "stopped" : running ? "running" : row.executionStatus === "failed" ? "failed" : "completed",
2963
+ task: row.title ?? "",
2964
+ ...row.title ? { title: row.title } : void 0,
2965
+ updatedAtMs: (row.executionUpdatedAt ?? row.updatedAt).getTime()
2966
+ };
2967
+ }));
1982
2968
  }
1983
2969
  function answersParent(kind, source) {
1984
2970
  const personInput = isPersonInput(source);
@@ -1989,14 +2975,13 @@ function answersParent(kind, source) {
1989
2975
  }
1990
2976
  /**
1991
2977
  * Return whether a child whose `latest` agent invocation ended has work on
1992
- * the Conversation loop that will answer its parent: input that waits in the
1993
- * mailbox until its Turn commits it, such as a Watch Event in its debounce
1994
- * window, or an open mailbox Turn that answers.
2978
+ * the Conversation loop that will answer its parent: `pending` input that
2979
+ * waits in the mailbox until its Turn commits it, such as a Watch Event in
2980
+ * its debounce window, or an open mailbox Turn that answers.
1995
2981
  */
1996
- async function runsOnConversationLoop(conversationId, kind, latest, stoppedAtMs) {
1997
- const pending = (await getConversationWorkState({ conversationId }))?.execution.pendingMessages ?? [];
2982
+ async function runsOnConversationLoop(kind, latest, stoppedAtMs, pending, mailboxTurnSources) {
1998
2983
  for (const message of pending) if (answersParent(kind, message.source) && await routeChildInput(message, latest, stoppedAtMs) === "Conversation loop") return true;
1999
- return (await listActiveMailboxTurns(conversationId)).some((turn) => answersParent(kind, turn.source?.kind));
2984
+ return mailboxTurnSources.some((source) => answersParent(kind, source?.kind));
2000
2985
  }
2001
2986
  /**
2002
2987
  * List the ids of a child's open Turns on the Conversation loop. A Turn keeps
@@ -2008,32 +2993,21 @@ async function listOpenLoopTurnIds(conversationId) {
2008
2993
  const [turns, work] = await Promise.all([listActiveMailboxTurns(conversationId), getConversationWorkState({ conversationId })]);
2009
2994
  return [...turns.map((turn) => turn.turnId), ...(work?.execution.pendingMessages ?? []).map((message) => buildDeterministicTurnId(message.inboundMessageId))];
2010
2995
  }
2011
- async function listAnsweredLoopChildren(children, parentInboundMessageIds) {
2012
- const replies = parentInboundMessageIds.flatMap((messageId) => {
2013
- const invocationId = parseAgentReplyMessageId(messageId);
2014
- return invocationId ? [{
2015
- invocationId,
2016
- messageId
2017
- }] : [];
2018
- });
2019
- if (children.length === 0 || replies.length === 0) return [];
2020
- const senders = await getSqlExecutor().db().select({
2021
- childConversationId: juniorAgentInvocations.childConversationId,
2022
- invocationId: juniorAgentInvocations.invocationId
2023
- }).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.invocationId, replies.map((reply) => reply.invocationId)));
2996
+ async function listAnsweredLoopChildren(children, parentMessages) {
2997
+ if (children.length === 0 || parentMessages.length === 0) return [];
2024
2998
  return (await Promise.all(children.map(async ({ childConversationId }) => {
2025
2999
  const turnIds = await listOpenLoopTurnIds(childConversationId);
2026
- return replies.some((reply) => senders.some((sender) => sender.invocationId === reply.invocationId && sender.childConversationId === childConversationId) && turnIds.includes(parseTurnReplyMessageId(reply.messageId) ?? "")) ? childConversationId : void 0;
3000
+ return parentMessages.some(({ sender }) => sender.conversationId === childConversationId && turnIds.includes(sender.turnId)) ? childConversationId : void 0;
2027
3001
  }))).filter((id) => id !== void 0);
2028
3002
  }
2029
3003
  /**
2030
3004
  * List the other child agents of one parent whose results have not reached
2031
3005
  * the parent yet. A child counts while it runs and after it finishes until its
2032
3006
  * result is appended to the parent mailbox. A running child whose `reply` is
2033
- * already in `parentInboundMessageIds`, the ids that reached the parent's
2034
- * mailbox, has answered, so it does not count.
3007
+ * already among `parentMessages`, the child replies and results that reached
3008
+ * the parent's mailbox, has answered, so it does not count.
2035
3009
  */
2036
- async function listUnreportedSiblingAgents(parentConversationId, childConversationId, parentInboundMessageIds) {
3010
+ async function listUnreportedSiblingAgents(parentConversationId, childConversationId, parentMessages) {
2037
3011
  const db = getSqlExecutor().db();
2038
3012
  const [children, pendingResults, openInvocations] = await Promise.all([
2039
3013
  listChildAgents(parentConversationId),
@@ -2048,10 +3022,10 @@ async function listUnreportedSiblingAgents(parentConversationId, childConversati
2048
3022
  invocationId: juniorAgentInvocations.invocationId
2049
3023
  }).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, parentConversationId), inArray(juniorAgentInvocations.status, [...NON_TERMINAL_AGENT_INVOCATION_STATUSES])))
2050
3024
  ]);
2051
- const withPendingResult = new Set(pendingResults.filter((row) => sendsResultToParent(row, parentInboundMessageIds)).map((row) => row.childConversationId));
2052
- const unanswered = new Set(openInvocations.filter((row) => !parentInboundMessageIds.some((messageId) => isAgentReplyMessageId(messageId, row.invocationId))).map((row) => row.childConversationId));
3025
+ const withPendingResult = new Set(pendingResults.filter((row) => sendsResultToParent(row, parentMessages)).map((row) => row.childConversationId));
3026
+ const unanswered = new Set(openInvocations.filter((row) => !hasAgentInvocationReply(parentMessages, row.invocationId)).map((row) => row.childConversationId));
2053
3027
  const answered = new Set(openInvocations.map((row) => row.childConversationId).filter((child) => !unanswered.has(child)));
2054
- for (const child of await listAnsweredLoopChildren(children.filter((child) => child.status === "running" && !openInvocations.some((row) => row.childConversationId === child.childConversationId)), parentInboundMessageIds)) answered.add(child);
3028
+ for (const child of await listAnsweredLoopChildren(children.filter((child) => child.status === "running" && !openInvocations.some((row) => row.childConversationId === child.childConversationId)), parentMessages)) answered.add(child);
2055
3029
  return children.filter((child) => child.childConversationId !== childConversationId && (NON_TERMINAL_AGENT_INVOCATION_STATUSES.includes(child.status) && !answered.has(child.childConversationId) || withPendingResult.has(child.childConversationId)));
2056
3030
  }
2057
3031
  /**
@@ -2098,8 +3072,8 @@ async function listAgentRelatives(input) {
2098
3072
  * when it is due by `maxDueIdleMs` (`timerFloorMaxDueIdleMs`). A later timer
2099
3073
  * changes nothing, so the idle period warms as without a timer.
2100
3074
  */
2101
- async function readTimerDueIdleMs(conversationId, sinceMs, maxDueIdleMs) {
2102
- const dueIdleMs = Math.min(...(await listWatches({ conversationId })).map((watch) => watch.firesAtMs ?? Infinity)) - sinceMs;
3075
+ function earliestTimerDueIdleMs(watches, sinceMs, maxDueIdleMs) {
3076
+ const dueIdleMs = Math.min(...watches.map((watch) => watch.firesAtMs ?? Infinity)) - sinceMs;
2103
3077
  return dueIdleMs <= maxDueIdleMs ? dueIdleMs : void 0;
2104
3078
  }
2105
3079
  function askedReviewItem(messages, final) {
@@ -2110,13 +3084,26 @@ function askedReviewItem(messages, final) {
2110
3084
  return false;
2111
3085
  }
2112
3086
  /**
2113
- * Whether the idle period also waits on a child agent that still runs, or
2114
- * on a Review item that the Turn asked. A running child agent comes first:
2115
- * its result starts a Turn without a person.
3087
+ * The active Watches of the Conversation, and what else its idle period
3088
+ * waits on. Watches include timers and the event Watches that tools such as
3089
+ * `createPullRequest` add. A child agent that still runs comes first: its
3090
+ * result starts a Turn without a person. In an Automation run, only a child
3091
+ * agent or a Watch can start a later Turn, so a Review item does not count.
2116
3092
  */
2117
- async function readWaitingOn(conversationId, messages, final) {
2118
- if ((await listChildAgents(conversationId)).some((child) => NON_TERMINAL_AGENT_INVOCATION_STATUSES.includes(child.status))) return "child";
2119
- return askedReviewItem(messages, final) ? "review" : void 0;
3093
+ async function readPendingWork(conversationId, messages, final, automation) {
3094
+ const [watches, children] = await Promise.all([listWatches({ conversationId }), listChildAgents(conversationId)]);
3095
+ if (children.some((child) => NON_TERMINAL_AGENT_INVOCATION_STATUSES.includes(child.status))) return {
3096
+ watches,
3097
+ waitingOn: "child"
3098
+ };
3099
+ if (automation) return watches.length > 0 ? {
3100
+ watches,
3101
+ waitingOn: "watch"
3102
+ } : { watches };
3103
+ return askedReviewItem(messages, final) ? {
3104
+ watches,
3105
+ waitingOn: "review"
3106
+ } : { watches };
2120
3107
  }
2121
3108
  // src/api/conversations/user-message-activity.ts
2122
3109
  function latestIso(times) {
@@ -2303,6 +3290,7 @@ const CONVERSATION_GAPS_MAX = 50;
2303
3290
  /** The Turn count of a Conversation resets after this long with no call. */
2304
3291
  const CONVERSATION_STATE_TTL_MS = 10080 * MINUTE_MS;
2305
3292
  const ANSWER_TOOL_ENDINGS = {
3293
+ [REPLY_TOOL_NAME]: "reply",
2306
3294
  [NO_REPLY_TOOL_NAME]: "no_reply",
2307
3295
  [REPORT_BLOCKED_TOOL_NAME]: "blocked"
2308
3296
  };
@@ -2354,6 +3342,9 @@ async function recordGap(state, conversationId, generation, warm, gapMs) {
2354
3342
  });
2355
3343
  }
2356
3344
  async function startIdlePeriod(state, conversationId, request, message, turn, systemPrompt, turnEnding) {
3345
+ const automation = systemPrompt.mode === "automation";
3346
+ const { watches, waitingOn } = await readPendingWork(conversationId, request.context.messages, message, automation);
3347
+ if (automation && !waitingOn) return void 0;
2357
3348
  const idle = {
2358
3349
  generation: randomUUID(),
2359
3350
  sinceMs: request.startedAtMs
@@ -2361,7 +3352,7 @@ async function startIdlePeriod(state, conversationId, request, message, turn, sy
2361
3352
  const prefixTokens = cachedPrefixTokens(message);
2362
3353
  const ttlMs = cacheTtlMs(request);
2363
3354
  if (ttlMs === void 0 || prefixTokens < 5e4) return idle;
2364
- const timerDueIdleMs = await readTimerDueIdleMs(conversationId, idle.sinceMs, timerFloorMaxDueIdleMs({
3355
+ const timerDueIdleMs = earliestTimerDueIdleMs(watches, idle.sinceMs, timerFloorMaxDueIdleMs({
2365
3356
  cacheReadPrice: request.model.cost.cacheRead,
2366
3357
  cacheWritePrice: request.model.cost.cacheWrite,
2367
3358
  cacheTtlMs: ttlMs
@@ -2381,7 +3372,7 @@ async function startIdlePeriod(state, conversationId, request, message, turn, sy
2381
3372
  });
2382
3373
  return idle;
2383
3374
  }
2384
- const [segmentState, waitingOn] = await Promise.all([readSegmentState(conversationId, Date.now()), readWaitingOn(conversationId, request.context.messages, message)]);
3375
+ const segmentState = await readSegmentState(conversationId, Date.now());
2385
3376
  const segmentInput = {
2386
3377
  ...turn,
2387
3378
  ...segmentState
@@ -2427,12 +3418,13 @@ async function recordModelCall(conversationId, userActor, systemPrompt, request,
2427
3418
  });
2428
3419
  }
2429
3420
  const endedTurns = previous?.endedTurns ?? 0;
2430
- const next = turnEnding ? {
3421
+ const nextIdle = turnEnding ? await startIdlePeriod(state, conversationId, request, message, {
3422
+ userActor,
3423
+ endedTurns
3424
+ }, systemPrompt, turnEnding) : void 0;
3425
+ const next = nextIdle ? {
2431
3426
  endedTurns: endedTurns + 1,
2432
- idle: await startIdlePeriod(state, conversationId, request, message, {
2433
- userActor,
2434
- endedTurns
2435
- }, systemPrompt, turnEnding)
3427
+ idle: nextIdle
2436
3428
  } : { endedTurns };
2437
3429
  if (!idle && !next.idle) return;
2438
3430
  await state.set(conversationKey(conversationId), next, CONVERSATION_STATE_TTL_MS);
@@ -2517,7 +3509,7 @@ function createCacheWarmingRecorder(conversationId, userActor, systemPrompt) {
2517
3509
  },
2518
3510
  toolsReturned: toolWait.toolsReturned,
2519
3511
  answerToolEnded: (toolName) => {
2520
- answerToolEnding = systemPrompt.mode === "automation" ? void 0 : ANSWER_TOOL_ENDINGS[toolName];
3512
+ answerToolEnding = ANSWER_TOOL_ENDINGS[toolName];
2521
3513
  },
2522
3514
  stop: async () => {
2523
3515
  try {
@@ -2564,11 +3556,12 @@ function createCacheWarmingRecorder(conversationId, userActor, systemPrompt) {
2564
3556
  *
2565
3557
  * `work_state` and `archived` are read when the idle period starts and pick
2566
3558
  * its `gapSegment`. `turn_ending` is how the Turn before the idle period
2567
- * ended: `reply` (a final response), `no_reply` (`noReply`), or `blocked`
2568
- * (`reportBlocked`). `waiting_on` is `child` (a child agent still ran) or
2569
- * `review` (the Turn asked a Review item) when the idle period starts, and
2570
- * picks the segment's `waitingGapSegment` child. `timer_due_ms` is the idle
2571
- * time at which a timer is due, when it is due within
3559
+ * ended: `reply` (a final response or `reply`), `no_reply` (`noReply`), or
3560
+ * `blocked` (`reportBlocked`). `waiting_on` is `child` (a child agent still
3561
+ * ran), `review` (the Turn asked a Review item), or `watch` (an Automation
3562
+ * run had an active Watch and no child agent) when the idle period starts,
3563
+ * and picks the segment's `waitingGapSegment` child. `timer_due_ms`
3564
+ * is the idle time at which a timer is due, when it is due within
2572
3565
  * `timerFloorMaxDueIdleMs`. The `conversation.returned` log has the same
2573
3566
  * five. Decision attributes are absent when the warmup skipped before the
2574
3567
  * decision. Of them, `timer_floor` is true for a warmup that only the timer
@@ -2695,4 +3688,4 @@ async function runCacheWarmup(message) {
2695
3688
  }, startedAtMs, warm);
2696
3689
  }, attributes);
2697
3690
  }
2698
- export { AgentDepthLimitError as A, MIN_WARMUP_PREFIX_TOKENS as B, dropOwnUnreadLoopReplies as C, recordSubagentEnded as D, stopChildAgentsOf as E, AgentNameInUseError as F, gapHistogramReport as H, findChildAgentConversationId as I, GAP_SEGMENTS as L, AgentMessagePausedError as M, AgentMessageQueueFullError as N, createAgentInvocationForMessage as O, AgentMessageTargetError as P, IDLE_HORIZON_MS as R, resolveAgentInvocationId as S, stopChildAgentsBelow as T, gapSegment as U, NO_REPLY_GAP_MS as V, createAgentInvocationWorker as _, segmentGapsKey as a, endAgentInvocationsOfStoppedWork as b, listConversationWork as c, listChildAgents as d, listDescendantAgents as f, routeChildInput as g, getChildAgentInputInvocation as h, createCacheWarmingRecorder as i, AgentInvocationLimitError as j, createAgentInvocationFromLatest as k, readLastUserMessageAtByConversation as l, childAgentInput as m, GLOBAL_GAPS_MAX as n, warmup_exports as o, listUnreportedSiblingAgents as p, GLOBAL_GAPS_TTL_MS as r, isConversationWorkDone as s, CONVERSATION_STATE_TTL_MS as t, listAgentRelatives as u, createAndEnqueueAgentInvocation as v, stopChildAgent as w, enqueueAgentInvocation as x, endActiveAgentInvocations as y, MINUTE_MS as z };
3691
+ export { AgentDepthLimitError as $, readChildConversationSender as A, MIN_WARMUP_PREFIX_TOKENS as At, endActiveAgentInvocations as B, listPendingAgentInvocationMailboxAppends as C, deleteWebAuthorization as Ct, sendsResultToParent as D, GAP_SEGMENTS as Dt, reportReplacedWithoutOpenWork as E, executeTurn as Et, parentMessageText as F, stopChildAgent as G, enqueueAgentInvocation as H, readLastParentMessageAtMs as I, cancelSignInWait as J, stopChildAgentsBelow as K, readParentMessage as L, childAgentTurnOptions as M, gapHistogramReport as Mt, isParentMessageMeta as N, gapSegment as Nt, childAgentInput as O, IDLE_HORIZON_MS as Ot, logDroppedParentMessage as P, createAgentInvocationFromLatest as Q, createAgentInvocationWorker as R, listOpenAgentInvocations as S, createWebAuthorization as St, markAgentInvocationParentMailboxAppended as T, AgentRunError as Tt, resolveAgentInvocationId as U, endAgentInvocationsOfStoppedWork as V, dropOwnUnreadLoopReplies as W, recordSubagentEnded as X, completeCancelledConversationTurn as Y, createAgentInvocationForMessage as Z, getAgentInvocation as _, getTurnAuthorization as _t, segmentGapsKey as a, findChildAgentConversationId as at, isTerminalAgentInvocation as b, isAttemptInterrupt as bt, listConversationWork as c, CHILD_AGENT_RESULTS as ct, listChildAgents as d, supersedeOpenMailboxTurns as dt, AgentInvocationLimitError as et, listDescendantAgents as f, supersedeTurnForInput as ft, getActiveAgentInvocationForConversation as g, wakePausedTurn as gt, TERMINAL_AGENT_INVOCATION_STATUSES as h, wakeAuthorizedTurn as ht, createCacheWarmingRecorder as i, AgentNameInUseError as it, routeChildInput as j, NO_REPLY_GAP_MS as jt, getChildAgentInputSender as k, MINUTE_MS as kt, readLastUserMessageAtByConversation as l, PARENT_AGENT_TARGET as lt, NON_TERMINAL_AGENT_INVOCATION_STATUSES as m, getPausedTurnRequest as mt, GLOBAL_GAPS_MAX as n, AgentMessageQueueFullError as nt, warmup_exports as o, getAgentBinding as ot, listUnreportedSiblingAgents as p, createPausedTurns as pt, stopChildAgentsOf as q, GLOBAL_GAPS_TTL_MS as r, AgentMessageTargetError as rt, isConversationWorkDone as s, CHILD_AGENT_KINDS as st, CONVERSATION_STATE_TTL_MS as t, AgentMessagePausedError as tt, listAgentRelatives as u, agentNameSchema as ut, getChildAgentLabel as v, canJoinTurn as vt, listPendingAgentInvocationResults as w, getWebAuthorization as wt, listAgentInvocationsForConversation as x, selectAttemptMessages as xt, getLatestAgentInvocationForConversation as y, canShareTurn as yt, createAndEnqueueAgentInvocation as z };