@sentry/junior 0.318.0 → 0.319.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/dist/{context-BKF_5zzI.js → adapter-8_S6Birm.js} +537 -537
  2. package/dist/{admin-UOHix_5P.js → admin-EsbUON1j.js} +1 -1
  3. package/dist/{agent-runner-DeYymwh2.js → agent-CtzMl32d.js} +18608 -5452
  4. package/dist/{agent-status-BA5x3Xtp.js → agent-status-Bq_AIpyp.js} +105 -1
  5. package/dist/{agent-update-delivery-DH8bx7jU.js → agent-update-delivery-pAvsbuGL.js} +4 -5
  6. package/dist/api/schema.d.ts +43 -23
  7. package/dist/api/schema.js +4 -4
  8. package/dist/api.js +70 -80
  9. package/dist/{app-DKAOuaoC.d.ts → app-tACXxJPI.d.ts} +4 -4
  10. package/dist/app.d.ts +2 -2
  11. package/dist/app.js +213 -91
  12. package/dist/{change-record-BzJgLsv7.d.ts → change-record-K-KsqNhT.d.ts} +9 -5
  13. package/dist/{channel-access-A0de5lRv.js → channel-access-DET5hzZM.js} +1 -1
  14. package/dist/{chat-core-engine-D3Wd7f5n.js → chat-core-engine-DpM3tMVi.js} +5 -5
  15. package/dist/cli/chat.d.ts +1 -1
  16. package/dist/cli/chat.js +23 -23
  17. package/dist/cli/check.js +5 -5
  18. package/dist/cli/main.js +2 -2
  19. package/dist/cli/plugins.d.ts +1 -1
  20. package/dist/cli/plugins.js +8 -8
  21. package/dist/cli/snapshot-create.js +5 -5
  22. package/dist/cli/upgrade.d.ts +1 -1
  23. package/dist/cli/upgrade.js +3 -4
  24. package/dist/{continue-in-slack-YxwMQVeR.js → continue-in-slack-CFzDyxkH.js} +3 -3
  25. package/dist/{conversation-feed-Cj7IuBtM.js → conversation-feed-DEUdD7mb.js} +2 -106
  26. package/dist/{conversation-privacy-Cr_dNW1p.js → conversation-privacy-C2vYK55O.js} +1 -1
  27. package/dist/{create-Btl1y1rq.js → create-Ta3SEIB5.js} +115 -5
  28. package/dist/{credential-sync-DTarZ63K.js → credential-sync-DyRqDmY4.js} +15 -18
  29. package/dist/{db-of6e3sGt.js → db-BCaNWl9p.js} +4579 -717
  30. package/dist/{deployment-C0qXa0FD.js → deployment-CfOew1Tm.js} +3 -3
  31. package/dist/{engine-context-C_QL_bMQ.js → engine-context-CiExoy1B.js} +144 -149
  32. package/dist/{html-9_pS9SjY.js → html-Bb2Si1bR.js} +6 -8
  33. package/dist/instrumentation.js +7 -23
  34. package/dist/list-wwDcROh9.js +5007 -0
  35. package/dist/{logging-BnOG0qz2.js → logging-BRPTXAdf.js} +8 -33
  36. package/dist/{mailbox-turn-Byrry9o1.js → markers-9QoqW5ov.js} +1675 -1255
  37. package/dist/nitro.d.ts +2 -2
  38. package/dist/nitro.js +6 -7
  39. package/dist/{oauth-callback-server-CjnnUr4o.js → oauth-callback-server-vhL9b-PZ.js} +2 -2
  40. package/dist/{oauth-relay-BvHFH0fV.js → oauth-relay-CH2v7WiB.js} +1 -1
  41. package/dist/{plugins-fBrz8PCV.d.ts → plugins-DhGXZjlu.d.ts} +1 -0
  42. package/dist/{profile-iHw1uu32.js → profile-D9LdwmZi.js} +16 -18
  43. package/dist/{prompt-DEkStuxG.js → prompt-3TqxEOtc.js} +1 -1
  44. package/dist/{reports-C1d9azyV.js → reports-K-tbtEyx.js} +2 -2
  45. package/dist/{resolve-DC6zBuDV.js → resolve-BBV2qf8A.js} +5 -5
  46. package/dist/{result-DxewDuXb.js → result-5IdGJP4M.js} +20 -9
  47. package/dist/{runner-99YxVN_r.js → runner-BK_joPlM.js} +7 -8
  48. package/dist/{sandbox-egress-signals-CgoX5CTI.js → sandbox-egress-signals-DXgWXXmm.js} +1 -1
  49. package/dist/{schema-BTojNBr5.js → schema-zWGG6VC1.js} +13 -7
  50. package/dist/{service-account-YDCPSByj.js → service-account-CateFyhw.js} +4 -5
  51. package/dist/{skills-CleC0Hze.js → skills-Ccjw8h2P.js} +9 -9
  52. package/dist/{slack-conversation-unfurl-BNQLC12R.js → slack-conversation-unfurl-ZC_TSpc4.js} +7 -7
  53. package/dist/storage-C9U7R5rM.js +273 -0
  54. package/dist/{system-prompt-table-Ci6Ck4gk.js → system-prompt-table-YBTHIFlP.js} +26 -84
  55. package/dist/topic-B2EWKKBT.js +6 -0
  56. package/dist/{package-discovery-DD9vencX.js → topics-DxuKurCX.js} +21 -1
  57. package/dist/{types-DCzTAA63.js → types-BNHkJrOP.js} +25 -11
  58. package/dist/{users-Cb9c1k9q.js → users-CCRAqYb_.js} +1 -1
  59. package/dist/{validation-BiUmWPhy.js → validation-BCUpJa8K.js} +4 -4
  60. package/dist/{version-VEXiEcZu.js → version-BNm0JYj3.js} +1 -1
  61. package/dist/version.js +1 -1
  62. package/dist/{worker-ChWYQdhm.js → worker-BhgpZ7_b.js} +4 -4
  63. package/migrations/20261127052408_space_name_nullable/migration.sql +5 -0
  64. package/migrations/20261127052408_space_name_nullable/snapshot.json +29 -0
  65. package/migrations/20261127060000_annotation_object_id_index/migration.sql +1 -0
  66. package/migrations/20261127060000_annotation_object_id_index/snapshot.json +69 -0
  67. package/migrations/20261127060001_annotation_subjects/migration.sql +78 -0
  68. package/migrations/20261127060001_annotation_subjects/snapshot.json +104 -0
  69. package/migrations/20261127060002_annotation_subject_index/migration.sql +1 -0
  70. package/migrations/20261127060002_annotation_subject_index/snapshot.json +70 -0
  71. package/migrations/20261127060003_annotation_title_url/migration.sql +84 -0
  72. package/migrations/20261127060003_annotation_title_url/snapshot.json +73 -0
  73. package/package.json +9 -7
  74. package/dist/auth-pause-state-f9hJM_zO.js +0 -113
  75. package/dist/catalog-runtime-BfdAnztW.js +0 -6
  76. package/dist/child-message-peFWLcCZ.js +0 -15
  77. package/dist/conversation-turn-Bru4w_FD.js +0 -1250
  78. package/dist/job-runner-B2XEvpif.js +0 -1505
  79. package/dist/lineage-nh4z9iQN.js +0 -36
  80. package/dist/list-HRP3TIRl.js +0 -12631
  81. package/dist/markers-CTTtJqYn.js +0 -342
  82. package/dist/message-BRUuLgrY.js +0 -153
  83. package/dist/model-input-CFC62mf-.js +0 -82
  84. package/dist/registry-Cl7Labpe.js +0 -3279
  85. package/dist/run-conversation-Cz2ubZK-.js +0 -337
  86. package/dist/sender-actors-77zTQbSG.js +0 -84
  87. package/dist/spawn-DuZfodPa.js +0 -45
  88. package/dist/task-runner-BJ9Up3bG.js +0 -1529
  89. package/dist/topic-CRYYBYp-.js +0 -7
  90. package/dist/topics-BoCkoPJJ.js +0 -21
  91. package/dist/turn-membership-VT7XZh-L.js +0 -856
  92. package/dist/turn-wake-C7HeLHAM.js +0 -151
@@ -1,21 +1,20 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { A as retainRuntimeTurnContext, B as authorAttrs, D as isToolResultError, G as mapBounded, I as TURN_CONTEXT_TAG, L as renderCurrentInstruction, M as trimTrailingAssistantMessages, O as isToolResultMessage, T as isContinuablePiBoundary, U as renderParentAgentTask, W as renderThreadContext, _ as extractAssistantText, c as SANDBOX_REPOS_ROOT, d as SANDBOX_WORKSPACE_ROOT, h as createPluginLogger, j as stripRuntimeTurnContext, k as normalizeToolNameFromResult, w as isAssistantMessage, x as hasRuntimeTurnContext, y as getTerminalAssistantMessages, z as THREAD_CONTEXT_TAGS } from "./prompt-DEkStuxG.js";
3
- import { $ as resolveGatewayModel, B as getSlackBotToken, L as botConfig, P as parseSlackMessageTs, R as getChatConfig, S as MUTATION_LOCK_TTL_MS, T as withLock, Y as TURN_REASONING_LEVELS, a as credentialSubjectSchema, b as getStateValues, f as isUserActor, h as toStoredSlackActor, k as parseSlackUserId, n as credentialContextForActor, s as createActor, w as fenceLock, y as getStateAdapter } from "./context-BKF_5zzI.js";
4
- import { A as toOptionalString, O as isNativeIdentityProvider, S as summarizeMessageText, T as withSpan, _ as serializeGenAiAttribute, a as getActiveTraceContext, f as logException, m as logWarn, p as logInfo, y as setSpanAttributes } from "./logging-BnOG0qz2.js";
5
- import { $a as fallbackShortTitle, $s as SYSTEM_IDENTITY_ID, $u as findProviderError, Al as instructionAuthor, Bl as EVENT_AUTHOR_ID, Bs as withSlackRetries, Ci as postSlackEphemeralMessage, Ct as getPlugins, Dn as releaseInboundMessage, Du as completeText, Fs as isDmChannel, Gl as isEventConversationMessage, Go as JUNIOR_THREAD_STATE_TTL_MS, Hl as EVENT_SYSTEM_ACTOR, In as isEventMailboxMetadata, Kr as formatSentryEventReference, Md as juniorSnapshots, Mi as formatSlackLink, Ms as getSlackClient, N as claimProviderConversation, Nd as juniorWorkspaceRepos, Nr as getVercelConversationWorkQueue, Ol as dispatchInstructionsInvokeSkills, On as traceContextSchema, Pd as juniorWorkspaces, Pn as readParentMessage, Qu as createProviderError, Ri as getPluginUserPromptContributions, Ru as createCache, Sf as juniorDestinations, Ul as eventBotAuthorId, Uo as verifyTimerWatchCredentialSubject, Ut as appendAndEnqueueInboundMessage, Uu as estimateTextTokens, Vl as EVENT_MESSAGE_AUTHOR, Vs as sleep, Wt as appendInboundMessage, Xd as juniorLocationConfigurations, Yi as pluginConfigValues, Yl as eventGuidance, Yu as isCompactionSummaryText, Zu as createAssistantProviderError, a as getDb, ac as findSlackUserByPrimaryEmail, ad as JUNIOR_NATIVE_EVENT_NAMESPACE, an as getConversationWorkState, au as ToolInputError, bc as getInboxItem, cd as conversationNoteEvent, cs as conversationSubtreeColumns, d as createSqlConversationEventStore, dl as projectConversationMessages, ea as createPluginCache, ec as resolveActorIdentityId, ed as getProviderErrorAttributes, eo as generateShortTitle, gn as takePendingEventMessages, hf as juniorConversations, hn as stopConversationWork, i as getConversationStore, ic as findLinkedSlackUser, if as juniorConversationEvents, j as startLocationThread, ji as escapeSlackMrkdwnText, jl as isPersonInput, n as getConversationEventStore, nn as dropPendingMessages, o as getSqlExecutor, od as agentsInstructionsUpdatedEvent, sd as authenticationLinkedEvent, so as getEventCatalog, ss as conversationSubtree, ta as getConfigDefaults, td as getProviderErrorUserMessage, u as isPostgresErrorCode, ud as addAgentTurnUsage, v as withConversationEventLock, vs as findActorTimezone, wi as postSlackMessage, wt as getRegistrations, xf as juniorUsers, xo as publishAgentUpdate, yd as nextDetailVersion } from "./db-of6e3sGt.js";
6
- import { S as readBlockedReport, _ as NO_REPLY_TOOL_NAME, a as buildCapabilitySections, b as readNoReply, d as readTurnAnswer, g as sanitizeAssistantText, l as REPLY_TOOL_NAME, m as decideReply, n as buildPluginSections, o as buildTurnContextPrompt, s as readPluginContributions, t as buildModeSections, x as REPORT_BLOCKED_TOOL_NAME, y as isLegacyNoReplyMarker } from "./system-prompt-table-Ci6Ck4gk.js";
7
- import { N as resolveSandboxEgressProviderForHost, O as parseSandboxEgressAuthRequiredSignal, f as findInErrorChain, n as hash, o as getSandboxProvider, u as SANDBOX_RUNTIME, x as executeCredentialedEgressRequest } from "./profile-iHw1uu32.js";
8
- import { Ct as instructionActors, St as contextProvenance, Vt as messageCardRef, bn as normalizeUserInputAnswer, bt as piMessageSchema, fn as inboxItemQuestion, gt as historyItemFromPiMessage, nt as agentTypeInstructions, rt as agentTypeSchema, vn as formatUserInputAnswer, wt as instructionProvenanceFor, xt as agentInstructionProvenance, yt as piMessageFromHistoryItem } from "./types-DCzTAA63.js";
9
- import { n as pluginCatalogRuntime } from "./catalog-runtime-BfdAnztW.js";
2
+ import { $ as resolveGatewayModel, B as getSlackBotToken, L as botConfig, P as parseSlackMessageTs, R as getChatConfig, S as isUserActor, T as toStoredSlackActor, Y as TURN_REASONING_LEVELS, _ as createActor, a as getStateValues, f as credentialContextForActor, h as credentialSubjectSchema, i as getStateAdapter, k as parseSlackUserId, l as fenceLock, s as MUTATION_LOCK_TTL_MS, u as withLock } from "./adapter-8_S6Birm.js";
3
+ import { $l as instructionAuthor, Ad as authenticationLinkedEvent, Ai as postSlackMessage, Bc as getInboxItem, Bp as juniorConversations, Cd as getProviderErrorAttributes, Do as publishAgentUpdate, Dt as getRegistrations, Es as conversationSubtreeColumns, Et as getPlugins, Fd as getAppContext, Ff as addAgentTurnUsage, Fn as readParentMessage, Gt as appendInboundMessage, In as readInboundMessageSender, Kp as juniorUsers, Li as escapeSlackMrkdwnText, Ln as isEventMailboxMetadata, Ls as findActorTimezone, N as claimProviderConversation, Od as JUNIOR_NATIVE_EVENT_NAMESPACE, On as releaseInboundMessage, Ou as ToolInputError, Pl as projectConversationMessages, Qr as formatSentryEventReference, Ri as formatSlackLink, Sd as findProviderError, Sp as juniorAgentBindings, Tc as findSlackUserByPrimaryEmail, Ts as conversationSubtree, W as conversationLastTurnOutcomeSql, Wf as nextDetailVersion, Wi as getPluginUserPromptContributions, Wt as appendAndEnqueueInboundMessage, Xu as completeText, Yo as verifyTimerWatchCredentialSubject, Zl as dispatchInstructionsInvokeSkills, Zo as JUNIOR_THREAD_STATE_TTL_MS, Zs as getSlackClient, _n as takePendingEventMessages, a as getDb, ac as withSlackRetries, ao as fallbackShortTitle, ap as juniorWorkspaces, bc as resolveActorIdentityId, bd as createAssistantProviderError, d as createSqlConversationEventStore, du as EVENT_SYSTEM_ACTOR, ec as isDmChannel, eu as isPersonInput, fd as estimateTextTokens, fr as readThroughHttpCache, fu as eventBotAuthorId, gn as stopConversationWork, i as getConversationStore, ip as juniorWorkspaceRepos, j as startLocationThread, jd as conversationNoteEvent, kd as agentsInstructionsUpdatedEvent, ki as postSlackEphemeralMessage, kn as traceContextSchema, kp as juniorConversationEvents, lu as EVENT_AUTHOR_ID, mu as isEventConversationMessage, n as getConversationEventStore, o as getSqlExecutor, oa as createPluginCache, oc as sleep, on as getConversationWorkState, oo as generateShortTitle, po as getEventCatalog, qp as juniorDestinations, rn as dropPendingMessages, rp as juniorSnapshots, sa as getConfigDefaults, sd as createCache, sn as getConversationWorkStates, ta as pluginConfigValues, u as isPostgresErrorCode, uu as EVENT_MESSAGE_AUTHOR, v as withConversationEventLock, vd as isCompactionSummaryText, vu as eventGuidance, wc as findLinkedSlackUser, wd as getProviderErrorUserMessage, xd as createProviderError, xp as juniorLocationConfigurations, yc as SYSTEM_IDENTITY_ID, zr as getVercelConversationWorkQueue } from "./db-BCaNWl9p.js";
4
+ import { Ct as instructionActors, St as contextProvenance, Un as isAgentUpdateEventType, Vt as messageCardRef, bt as piMessageSchema, gt as historyItemFromPiMessage, nt as agentTypeInstructions, pn as inboxItemQuestion, rt as agentTypeSchema, wt as instructionProvenanceFor, xn as normalizeUserInputAnswer, xt as agentInstructionProvenance, yn as formatUserInputAnswer, yt as piMessageFromHistoryItem } from "./types-BNHkJrOP.js";
5
+ import { A as toOptionalString, O as isNativeIdentityProvider, S as summarizeMessageText, T as withSpan, _ as serializeGenAiAttribute, a as getActiveTraceContext, f as logException, m as logWarn, p as logInfo, y as setSpanAttributes } from "./logging-BRPTXAdf.js";
6
+ import { A as retainRuntimeTurnContext, B as authorAttrs, D as isToolResultError, G as mapBounded, I as TURN_CONTEXT_TAG, L as renderCurrentInstruction, M as trimTrailingAssistantMessages, O as isToolResultMessage, T as isContinuablePiBoundary, U as renderParentAgentTask, W as renderThreadContext, _ as extractAssistantText, c as SANDBOX_REPOS_ROOT, d as SANDBOX_WORKSPACE_ROOT, h as createPluginLogger, j as stripRuntimeTurnContext, k as normalizeToolNameFromResult, w as isAssistantMessage, x as hasRuntimeTurnContext, y as getTerminalAssistantMessages, z as THREAD_CONTEXT_TAGS } from "./prompt-3TqxEOtc.js";
7
+ import { a as toCanonicalInputMessage } from "./conversation-privacy-C2vYK55O.js";
8
+ import { a as parseSkillFile, i as openAiPolicyDisablesImplicitInvocation } from "./skills-Ccjw8h2P.js";
9
+ import { N as resolveSandboxEgressProviderForHost, O as parseSandboxEgressAuthRequiredSignal, f as findInErrorChain, n as hash, o as getSandboxProvider, u as SANDBOX_RUNTIME, x as executeCredentialedEgressRequest } from "./profile-D9LdwmZi.js";
10
+ import { S as readBlockedReport, _ as NO_REPLY_TOOL_NAME, a as buildCapabilitySections, b as readNoReply, d as readTurnAnswer, g as sanitizeAssistantText, l as REPLY_TOOL_NAME, m as decideReply, n as buildPluginSections, o as buildTurnContextPrompt, s as readPluginContributions, t as buildModeSections, x as REPORT_BLOCKED_TOOL_NAME, y as isLegacyNoReplyMarker } from "./system-prompt-table-YBTHIFlP.js";
10
11
  import { t as isMissingVirtualModule } from "./virtual-module-BeKA_EII.js";
12
+ import { i as lookupSlackUserProfile, t as lookupActiveSlackWorkspaceMember } from "./users-CCRAqYb_.js";
11
13
  import { r as userCustomizationTextSchema, s as isVisionImageMediaType } from "./user-customization-CvfuY9Eo.js";
12
- import { a as parseSkillFile, i as openAiPolicyDisablesImplicitInvocation } from "./skills-CleC0Hze.js";
13
- import { a as toCanonicalInputMessage } from "./conversation-privacy-Cr_dNW1p.js";
14
- import { i as lookupSlackUserProfile, t as lookupActiveSlackWorkspaceMember } from "./users-Cb9c1k9q.js";
15
14
  import * as z from "zod";
16
15
  import { getCurrentSystemMessage, getSystemMessageText } from "@earendil-works/pi-ai/compat";
17
16
  import path from "node:path";
18
- import { and, asc, desc, eq, inArray, isNull, like, lt, lte, ne, or, sql } from "drizzle-orm";
17
+ import { and, asc, desc, eq, inArray, isNotNull, isNull, like, lt, lte, ne, or, sql } from "drizzle-orm";
19
18
  import { alias } from "drizzle-orm/pg-core";
20
19
  import { actorSchema, agentEventKeys, createEventSource, createLocalSource, createWebSource, destinationSchema, escapeClosingTag, escapeClosingTags, escapeTagText, escapeTagTextAndQuotes, findTag, readTag, renderInlineTag, renderTag, sourceSchema, startsWithTag, tagJson, unescapeClosingTag, unescapeClosingTags } from "@sentry/junior-plugin-api";
21
20
  import { isDeepStrictEqual } from "node:util";
@@ -388,7 +387,7 @@ function parseOAuthStatePayload(value) {
388
387
  }
389
388
  /** Return the manifest-owned display label for a provider. */
390
389
  function formatProviderLabel(provider) {
391
- const displayName = pluginCatalogRuntime.getDisplayName(provider);
390
+ const displayName = getAppContext().catalog.getDisplayName(provider);
392
391
  if (!displayName) throw new Error(`Unknown plugin provider display name: "${provider}"`);
393
392
  return displayName;
394
393
  }
@@ -460,7 +459,7 @@ async function deliverOAuthAuthorization(request, input) {
460
459
  }
461
460
  /** Initiate an OAuth authorization code flow for a provider and deliver the auth link to the user. */
462
461
  async function startOAuthFlow(provider, input) {
463
- const providerConfig = pluginCatalogRuntime.getOAuthConfig(provider);
462
+ const providerConfig = getAppContext().catalog.getOAuthConfig(provider);
464
463
  if (!providerConfig) return {
465
464
  ok: false,
466
465
  error: `Provider "${provider}" does not support OAuth authorization`
@@ -703,14 +702,11 @@ function currentAuthor(context) {
703
702
  return author === "person" && context.actor.platform === "system" ? "event" : author;
704
703
  }
705
704
  /**
706
- * The ordered messages of the work for one batch. Every proposal of a
707
- * batch has the same context and root Conversation, so the first one is
708
- * enough.
709
- *
710
- * Core labels only the requester's root messages `user`, so only they and
711
- * the current instruction are `instruction`. A gap note stays as context,
712
- * so a later reply does not read as an answer to a message that is not
713
- * shown.
705
+ * The ordered messages of the work for one batch. Every proposal of a batch
706
+ * has the same context and root Conversation, so the first one is enough.
707
+ * Only the requester's root messages, which core labels `user`, and the
708
+ * current instruction are `instruction`. A gap note stays as context, so a
709
+ * later reply does not read as an answer to a message that is not shown.
714
710
  */
715
711
  function guardianMessages(proposal) {
716
712
  const { context, rootConversation } = proposal;
@@ -790,14 +786,12 @@ var ToolActionReviewLimitError = class extends Error {
790
786
  }
791
787
  };
792
788
  /**
793
- * True when an `auto` action must enter review. The tool's annotations alone
794
- * decide: an action marked read-only and not destructive skips review, like
795
- * MCP clients such as Codex do. MCP annotations come from the server, and
796
- * plugin annotations from the plugin. Anything else, including missing
797
- * annotations, is unknown risk.
789
+ * True when an `auto` action must enter review. Only the annotations that
790
+ * Junior or plugin code declares on the tool can skip review: read-only and
791
+ * not destructive. Annotations that an MCP server sends reach Guardian only as
792
+ * hints, because a server can mark a write as read-only.
798
793
  */
799
- function autoActionNeedsReview(tool, resolved) {
800
- const annotations = resolved?.annotations ?? tool.annotations;
794
+ function autoActionNeedsReview({ annotations }) {
801
795
  return !(annotations?.readOnlyHint === true && annotations.destructiveHint !== true);
802
796
  }
803
797
  function actionActor(actor) {
@@ -846,7 +840,7 @@ function assertAuthoritativeContext(context) {
846
840
  }
847
841
  if (context.actor.platform !== "system" || context.actor.name !== credentialActor.name) throw new ToolActionReviewUnavailableError();
848
842
  }
849
- /** Build the bounded wire proposal without treating tool metadata as authority. */
843
+ /** Build the bounded wire proposal. Tool metadata is not authority. */
850
844
  function buildProposal(toolName, tool, input, resolved, context, priorRejections, rootConversation, script) {
851
845
  const credential = actionCredential(context.credentialContext);
852
846
  return {
@@ -929,16 +923,16 @@ function projectedRejection(proposal, decision) {
929
923
  tool: proposal.tool
930
924
  };
931
925
  }
932
- /** A core tool stays outside review unless it opts in. Plugin tools default to `auto`. */
926
+ /** Core tools skip review unless they opt in; plugin tools default `auto`. */
933
927
  function mayNeedReview(tool) {
934
928
  return tool.approvalMode !== void 0 && tool.approvalMode !== "approve";
935
929
  }
936
- /** Prepare the exact action that Guardian must review, when review is required. */
930
+ /** Prepare the exact action that Guardian must review, when it must. */
937
931
  async function prepareToolActionReview(action, context, priorRejections) {
938
932
  const { tool, input } = action;
939
933
  if (!mayNeedReview(tool)) return;
940
934
  const resolved = await tool.resolveApprovalMetadata?.(input);
941
- if (tool.approvalMode === "auto" && !autoActionNeedsReview(tool, resolved)) return;
935
+ if (tool.approvalMode === "auto" && !autoActionNeedsReview(tool)) return;
942
936
  assertAuthoritativeContext(context);
943
937
  const proposal = buildProposal(action.toolName, tool, input, resolved, context, priorRejections, await context.rootConversation?.(), action.script);
944
938
  return {
@@ -951,7 +945,7 @@ async function prepareToolActionReview(action, context, priorRejections) {
951
945
  proposal
952
946
  };
953
947
  }
954
- /** Most actions of one batch that the gate prepares or records at the same time. */
948
+ /** Most actions of one batch that the gate prepares or records at once. */
955
949
  const MAX_CONCURRENT_PREPARATIONS = 4;
956
950
  function unavailableStep(error) {
957
951
  return {
@@ -959,7 +953,7 @@ function unavailableStep(error) {
959
953
  error: error instanceof ToolActionReviewUnavailableError ? error : new ToolActionReviewUnavailableError({ cause: error })
960
954
  };
961
955
  }
962
- /** Create the core review path that prepares actions and enforces Guardian decisions. */
956
+ /** Create the review path that prepares actions and enforces decisions. */
963
957
  function createToolActionReview(options) {
964
958
  const priorRejections = [...options.priorRejections ?? []];
965
959
  const pendingRejections = /* @__PURE__ */ new Map();
@@ -2619,7 +2613,7 @@ function createPluginAuthOrchestration(input) {
2619
2613
  let pendingPause;
2620
2614
  const startAuthorizationPause = async (provider, options) => {
2621
2615
  if (pendingPause) throw pendingPause;
2622
- if (!input.actorId || !pluginCatalogRuntime.getOAuthConfig(provider)) throw new Error(`Cannot start plugin authorization for ${provider}`);
2616
+ if (!input.actorId || !getAppContext().catalog.getOAuthConfig(provider)) throw new Error(`Cannot start plugin authorization for ${provider}`);
2623
2617
  if (input.interactiveAuthEnabled === false) throw new AuthorizationFlowDisabledError("plugin", provider);
2624
2618
  const recordPendingAuth = input.sessionId ? input.recordPendingAuth : void 0;
2625
2619
  if (input.sessionId && !recordPendingAuth) throw new Error(`Missing pending auth recorder for plugin authorization pause "${provider}"`);
@@ -2691,7 +2685,7 @@ function createPluginAuthOrchestration(input) {
2691
2685
  if (input.interactiveAuthEnabled === false) throw new AuthorizationFlowDisabledError("plugin", provider);
2692
2686
  throw new PluginCredentialFailureError(provider, signal.message ?? `${formatProviderLabel(provider)} credentials are required. Please connect your ${formatProviderLabel(provider)} account and try again.`);
2693
2687
  }
2694
- if (!pluginCatalogRuntime.getOAuthConfig(authorization.provider)) throw new PluginCredentialFailureError(provider, signal.message ?? `${formatProviderLabel(provider)} credentials are required but the provider is not configured for OAuth.`);
2688
+ if (!getAppContext().catalog.getOAuthConfig(authorization.provider)) throw new PluginCredentialFailureError(provider, signal.message ?? `${formatProviderLabel(provider)} credentials are required but the provider is not configured for OAuth.`);
2695
2689
  await startAuthorizationPause(authorization.provider, authorization.scope ? { scope: authorization.scope } : void 0);
2696
2690
  },
2697
2691
  getPendingPause: () => pendingPause
@@ -2710,7 +2704,7 @@ function credentialContextForPluginEgress(credentialContext, source) {
2710
2704
  /** Create host-owned provider egress for plugin runtime tools. */
2711
2705
  function createPluginEgress(deps) {
2712
2706
  const credentialContext = deps.credentialContext ? credentialContextForPluginEgress(deps.credentialContext, deps.credentialAuditSource) : void 0;
2713
- return { async fetch(input) {
2707
+ const egress = { async fetch(input) {
2714
2708
  const operation = input.operation.trim();
2715
2709
  if (!operation) throw new Error("Plugin egress operation is required");
2716
2710
  if (!credentialContext) throw new PluginCredentialFailureError(input.provider, `Cannot issue ${input.provider} credentials without a credential context.`);
@@ -2733,6 +2727,25 @@ function createPluginEgress(deps) {
2733
2727
  if (result.authRequired) await deps.pluginAuth.handleAuthRequired(result.authRequired);
2734
2728
  return result.response;
2735
2729
  } };
2730
+ const { httpCache } = deps;
2731
+ if (!httpCache || !deps.credentialContext) return egress;
2732
+ const scope = `egress:${JSON.stringify([deps.credentialContext, deps.userOAuthOnly ? "user-oauth" : "any"])}`;
2733
+ return { async fetch(input) {
2734
+ if (input.request.method !== "GET") return await egress.fetch(input);
2735
+ return await readThroughHttpCache({
2736
+ ...httpCache,
2737
+ request: input.request,
2738
+ scope,
2739
+ send: async (headers) => {
2740
+ const request = new Request(input.request);
2741
+ for (const [name, value] of Object.entries(headers)) request.headers.set(name, value);
2742
+ return await egress.fetch({
2743
+ ...input,
2744
+ request
2745
+ });
2746
+ }
2747
+ });
2748
+ } };
2736
2749
  }
2737
2750
  // src/chat/plugins/conversation-title-context.ts
2738
2751
  const TITLE_CONTEXT_TIMEOUT_MS = 5e3;
@@ -4620,6 +4633,97 @@ function buildDeterministicTurnId(messageId) {
4620
4633
  function buildDeterministicAssistantMessageId(turnId) {
4621
4634
  return `${turnId}:assistant:1`;
4622
4635
  }
4636
+ // src/chat/runtime/turn.ts
4637
+ /** Classified Slack turn failure carrying the owning Sentry capture outward. */
4638
+ var ConversationTurnBoundaryError = class extends Error {
4639
+ eventId;
4640
+ failureCode;
4641
+ constructor(args) {
4642
+ super(args.cause instanceof Error ? args.cause.message : String(args.cause), { cause: args.cause });
4643
+ this.name = "ConversationTurnBoundaryError";
4644
+ this.eventId = args.eventId;
4645
+ this.failureCode = args.failureCode;
4646
+ }
4647
+ };
4648
+ /** Return a classified Slack boundary failure without erasing its cause. */
4649
+ function getConversationTurnBoundaryError(error) {
4650
+ return error instanceof ConversationTurnBoundaryError ? error : void 0;
4651
+ }
4652
+ /**
4653
+ * Queue-worker yield routing: respond.ts returns a suspended AgentRunOutcome
4654
+ * and the Slack executor raises this at the worker boundary so the lease owner
4655
+ * requeues the conversation.
4656
+ */
4657
+ var CooperativeTurnYieldError = class extends Error {
4658
+ code = "cooperative_turn_yield";
4659
+ constructor(message = "Agent turn yielded at a safe boundary") {
4660
+ super(message);
4661
+ this.name = "CooperativeTurnYieldError";
4662
+ }
4663
+ };
4664
+ function isCooperativeTurnYieldError(error) {
4665
+ return error instanceof CooperativeTurnYieldError;
4666
+ }
4667
+ /** Error indicating durable turn input could not be committed by the worker owner. */
4668
+ var TurnInputCommitLostError = class extends Error {
4669
+ code = "turn_input_commit_lost";
4670
+ constructor(message = "Turn input commit lost its durable owner") {
4671
+ super(message);
4672
+ this.name = "TurnInputCommitLostError";
4673
+ }
4674
+ };
4675
+ /** Return whether an error means the durable worker lost input ownership. */
4676
+ function isTurnInputCommitLostError(error) {
4677
+ return error instanceof TurnInputCommitLostError;
4678
+ }
4679
+ /** Error indicating durable turn input should stay pending for a later worker. */
4680
+ var TurnInputDeferredError = class extends Error {
4681
+ code = "turn_input_deferred";
4682
+ constructor(message = "Turn input is deferred until the active resume ends") {
4683
+ super(message);
4684
+ this.name = "TurnInputDeferredError";
4685
+ }
4686
+ };
4687
+ /** Return whether an error means the durable worker should redeliver input later. */
4688
+ function isTurnInputDeferredError(error) {
4689
+ return error instanceof TurnInputDeferredError;
4690
+ }
4691
+ /** Mark a turn as the active turn in conversation state. */
4692
+ function startActiveTurn(args) {
4693
+ args.conversation.processing.activeTurnId = args.nextTurnId;
4694
+ }
4695
+ function clearActiveTurn(conversation, sessionId) {
4696
+ if (!sessionId || conversation.processing.activeTurnId === sessionId) conversation.processing.activeTurnId = void 0;
4697
+ }
4698
+ /**
4699
+ * Close the active turn without marking a Pi session reusable for future
4700
+ * history. Use this for auth handoffs and recovery replies that end the live
4701
+ * turn but do not produce a completed Pi session.
4702
+ */
4703
+ function markTurnClosed(args) {
4704
+ clearActiveTurn(args.conversation, args.sessionId);
4705
+ args.conversation.processing.lastCompletedAtMs = args.nowMs;
4706
+ }
4707
+ /**
4708
+ * Mark a turn as completed after its assistant output has been handled.
4709
+ */
4710
+ function markTurnCompleted(args) {
4711
+ clearActiveTurn(args.conversation, args.sessionId);
4712
+ args.conversation.processing.lastCompletedAtMs = args.nowMs;
4713
+ }
4714
+ /**
4715
+ * Mark a turn as failed when execution or final user-visible reply delivery
4716
+ * cannot be completed. If `sessionId` is provided, `activeTurnId` is only
4717
+ * cleared when it still matches the failing turn.
4718
+ */
4719
+ function markTurnFailed(args) {
4720
+ clearActiveTurn(args.conversation, args.sessionId);
4721
+ args.conversation.processing.lastCompletedAtMs = args.nowMs;
4722
+ args.markConversationMessage(args.conversation, args.userMessageId, {
4723
+ replied: false,
4724
+ skippedReason: "reply failed"
4725
+ });
4726
+ }
4623
4727
  // src/chat/plugins/prompt-history-messages.ts
4624
4728
  function textParts(message) {
4625
4729
  if (!("role" in message) || message.role !== "user") return [];
@@ -5424,1170 +5528,1300 @@ async function withHeldInput(args, instruction) {
5424
5528
  text: instruction.text
5425
5529
  }]]);
5426
5530
  }
5427
- // src/chat/inbox-items/prompt-input.ts
5531
+ // src/chat/events/workspace.ts
5532
+ const teamIdsByToken = /* @__PURE__ */ new Map();
5428
5533
  /**
5429
- * Prompt inputs for person answers to Inbox items. An answer is its own
5430
- * prompt content part, keyed by the item id that `addInboxItem` returned.
5431
- * The runtime builds it from the stored change record and the item, so the
5432
- * model never reads status prose. It repeats the question, then one line for
5433
- * each answered field. `input-tags.ts` lists the input tags.
5534
+ * Resolve the single-bot Slack team id for event-automation indexing, Event
5535
+ * people mentions, and author trust.
5536
+ *
5537
+ * Watch matching does not use this. Event automations still key by
5538
+ * destination team until that store is conversation-owned. System Events are
5539
+ * not gated on Slack. Without a Slack bot, only a listed Event author is
5540
+ * trusted.
5434
5541
  */
5435
- const QUESTION_MAX_LENGTH = 512;
5436
- function typedAnswerText(request, answer) {
5437
- const normalized = normalizeUserInputAnswer(request, answer);
5438
- return [...request.fields.flatMap((field) => field.kind === "text" ? normalized.values[field.id] ?? [] : []), ...normalized.other ? [normalized.other] : []].join("\n\n");
5542
+ async function resolveBotSlackTeamId() {
5543
+ const token = getSlackBotToken();
5544
+ if (!token) return void 0;
5545
+ let pending = teamIdsByToken.get(token);
5546
+ if (!pending) {
5547
+ pending = getSlackClient().auth.test().then((result) => {
5548
+ const teamId = result.team_id?.trim();
5549
+ if (!teamId) throw new Error("Slack auth.test did not return a team id");
5550
+ return teamId;
5551
+ });
5552
+ teamIdsByToken.set(token, pending);
5553
+ pending.catch(() => teamIdsByToken.delete(token));
5554
+ }
5555
+ return await pending;
5439
5556
  }
5440
- function renderInboxItemAnswer(item) {
5441
- const request = inboxItemQuestion(item.request);
5442
- if (!request || !item.answer) return void 0;
5443
- const question = request.question.trim();
5444
- const requestText = typedAnswerText(request, item.answer);
5557
+ // src/chat/identities/trust.ts
5558
+ const emailSchema = z.string().trim().toLowerCase().pipe(z.email());
5559
+ /**
5560
+ * Parse a value that must be an email, such as a sign-in or a verified email
5561
+ * from a plugin. Return the normalized email and its domain, or undefined
5562
+ * when the value is not a valid email.
5563
+ */
5564
+ function parseEmail(value) {
5565
+ const parsed = emailSchema.safeParse(value);
5566
+ if (!parsed.success) return void 0;
5567
+ const email = parsed.data;
5445
5568
  return {
5446
- kind: "runtime",
5447
- text: renderTag("inbox-item-answer", { id: item.id }, [`Question: ${question.length > QUESTION_MAX_LENGTH ? `${question.slice(0, 511)}…` : question}`, formatUserInputAnswer(request, item.answer)].map(escapeTagText)),
5448
- ...requestText ? { requestText } : void 0
5569
+ email,
5570
+ domain: email.slice(email.lastIndexOf("@") + 1)
5449
5571
  };
5450
5572
  }
5451
5573
  /**
5452
- * Render the prompt input of a message that records an answer, or undefined
5453
- * when it has none. A take or a dismiss starts no Turn, so it has no input.
5454
- * A message without an answer, or whose item is gone, goes to the model as
5455
- * written.
5574
+ * Return whether a domain, such as the domain of a parsed email or Google's
5575
+ * `hd` claim, is on the allowed domains. It only compares domains.
5576
+ * `ifNoDomains` says what an empty list means: Slack authors allow every
5577
+ * domain, and sign-ins allow none.
5456
5578
  */
5457
- async function loadInboxItemInput(record) {
5458
- if (record?.kind !== "submitted") return void 0;
5459
- const item = await getInboxItem(getDb(), record.reviewItemId);
5460
- return item ? renderInboxItemAnswer(item) : void 0;
5579
+ function isAllowedDomain(domain, options) {
5580
+ if (options.allowedDomains.length === 0) return options.ifNoDomains === "allow";
5581
+ const normalized = domain?.trim().toLowerCase();
5582
+ return normalized ? options.allowedDomains.includes(normalized) : false;
5583
+ }
5584
+ function isCoreIdentityProvider(provider) {
5585
+ return provider === "junior" || isNativeIdentityProvider(provider);
5586
+ }
5587
+ function isSlackProfileDomainAllowed(profile) {
5588
+ const email = profile.email?.trim();
5589
+ const separator = email?.lastIndexOf("@") ?? -1;
5590
+ const allowed = isAllowedDomain(separator > 0 ? email?.slice(separator + 1) : void 0, {
5591
+ allowedDomains: getChatConfig().trust.allowedDomains,
5592
+ ifNoDomains: "allow"
5593
+ });
5594
+ if (!allowed) logWarn("slack.allowed_domain.rejected", { "app.reason": email ? "domain_not_allowed" : "missing_email" });
5595
+ return allowed;
5596
+ }
5597
+ const SLACK_TRUSTED_TTL_MS = 3e5;
5598
+ const SLACK_UNTRUSTED_TTL_MS = 3e4;
5599
+ async function readActiveMember(userId, teamId) {
5600
+ return await createCache(getStateAdapter(), "core").getOrLoad(`slack:active-member:${teamId}:${userId}`, async () => {
5601
+ const member = await lookupActiveSlackWorkspaceMember(userId, teamId);
5602
+ const value = member ? {
5603
+ email: member.email,
5604
+ name: member.name,
5605
+ real_name: member.real_name
5606
+ } : null;
5607
+ return {
5608
+ value,
5609
+ ttlMs: value ? SLACK_TRUSTED_TTL_MS : SLACK_UNTRUSTED_TTL_MS
5610
+ };
5611
+ });
5461
5612
  }
5462
5613
  /**
5463
- * Return the instruction of one saved input. `runtime` text, such as an
5464
- * Automation dispatch or an Event Turn, is already rendered as its tags.
5465
- * An answer is its Inbox item tag. It is not typed text, so it does not go
5466
- * in `<current-instruction>`.
5614
+ * Accept one stored Slack link only when it is a current human member of the
5615
+ * workspace whose Slack email is on the allowed domains. With `email`, the
5616
+ * Slack email must also still be that address, so a stale stored email does
5617
+ * not match.
5467
5618
  */
5468
- async function savedInputInstruction(args) {
5469
- const inboxItemInput = args.runtime ? void 0 : await loadInboxItemInput(args.reviewItemChange);
5470
- if (!args.runtime && !inboxItemInput) return { text: args.text };
5471
- return instructionForInputs([inboxItemInput ?? {
5472
- kind: "runtime",
5473
- text: args.text,
5474
- ...args.requestText ? { requestText: args.requestText } : void 0
5475
- }]);
5619
+ async function linkedMemberDecision(args) {
5620
+ const userId = parseSlackUserId(args.linked?.slackUserId);
5621
+ if (!args.linked || !userId) return {
5622
+ trusted: false,
5623
+ reason: "no_single_link"
5624
+ };
5625
+ const member = await readActiveMember(userId, args.teamId);
5626
+ if (!member) return {
5627
+ trusted: false,
5628
+ reason: "inactive_member"
5629
+ };
5630
+ if (args.email && member.email?.trim().toLowerCase() !== args.email) return {
5631
+ trusted: false,
5632
+ reason: "email_changed"
5633
+ };
5634
+ if (!isSlackProfileDomainAllowed(member)) return {
5635
+ trusted: false,
5636
+ reason: "domain_not_allowed"
5637
+ };
5638
+ const fullName = member.real_name?.trim() || void 0;
5639
+ const userName = member.name?.trim() || void 0;
5640
+ return {
5641
+ trusted: true,
5642
+ actor: {
5643
+ platform: "slack",
5644
+ teamId: args.teamId,
5645
+ userId,
5646
+ ...fullName ? { fullName } : void 0,
5647
+ ...userName ? { userName } : void 0
5648
+ },
5649
+ user: args.linked.user
5650
+ };
5476
5651
  }
5477
5652
  /**
5478
- * Render the Inbox item input of each Event in a batch that records an
5479
- * answer, keyed by inbound message id. A Conversation with no web identity,
5480
- * such as a local CLI Conversation, gets the answer as a system Event, but
5481
- * the input is the same as on web.
5653
+ * A plugin account is trusted when the plugin lists it, or through its exact
5654
+ * `subjectId`, linked by the OAuth account-linking flow to one Slack user who
5655
+ * is a current human member on the allowed domains. Handles, emails, and
5656
+ * display names never match.
5482
5657
  */
5483
- async function eventInboxItemInputs(messages) {
5484
- const rendered = await mapBounded(messages, async (message) => [message.inboundMessageId, await loadInboxItemInput(message.input.reviewItemChange)]);
5485
- return new Map(rendered.flatMap(([id, input]) => input ? [[id, input]] : []));
5658
+ async function accountDecision(args) {
5659
+ if (isCoreIdentityProvider(args.provider)) return {
5660
+ trusted: false,
5661
+ reason: "core_provider"
5662
+ };
5663
+ if (args.listed) return { trusted: true };
5664
+ if (!args.subjectId) return {
5665
+ trusted: false,
5666
+ reason: "unknown_author"
5667
+ };
5668
+ const teamId = await resolveBotSlackTeamId();
5669
+ if (!teamId) return {
5670
+ trusted: false,
5671
+ reason: "no_workspace"
5672
+ };
5673
+ return await linkedMemberDecision({
5674
+ linked: await findLinkedSlackUser(getSqlExecutor(), {
5675
+ provider: args.provider,
5676
+ providerSubjectId: args.subjectId,
5677
+ slackTeamId: teamId
5678
+ }),
5679
+ teamId
5680
+ });
5486
5681
  }
5487
- // src/chat/conversations/web-authorization.ts
5488
- const WEB_AUTHORIZATION_PREFIX = "junior:web_authorization:v1";
5489
- const WEB_AUTHORIZATION_TTL_MS = 864e5;
5490
- function authorizationKey(conversationId, actorId) {
5491
- return `${WEB_AUTHORIZATION_PREFIX}:${conversationId}:${actorId}`;
5682
+ /**
5683
+ * Return whether a Slack author may start a Turn. The caller must have
5684
+ * checked that the author is a member of the workspace `teamId`. A member is
5685
+ * trusted when their Slack email is on the allowed domains, or when the app
5686
+ * lists them as a bot user. Without allowed domains, every member is.
5687
+ */
5688
+ async function isTrustedSlackAuthor(args) {
5689
+ const userId = parseSlackUserId(args.user);
5690
+ if (!userId || !args.teamId) return false;
5691
+ const { allowedBotUserIds, allowedDomains } = getChatConfig().trust;
5692
+ if (allowedBotUserIds.includes(userId) || allowedDomains.length === 0) return true;
5693
+ return await createCache(args.state, "core").getOrLoad(`slack:allowed-domain:${args.teamId}:${userId}`, async () => {
5694
+ const profile = await lookupSlackUserProfile(userId);
5695
+ const trusted = profile.id === userId && isSlackProfileDomainAllowed(profile);
5696
+ return {
5697
+ value: trusted,
5698
+ ttlMs: trusted ? SLACK_TRUSTED_TTL_MS : SLACK_UNTRUSTED_TTL_MS
5699
+ };
5700
+ });
5492
5701
  }
5493
- /** Build authorization delivery for one web turn. */
5494
- function createWebAuthorization(args) {
5495
- return {
5496
- createState: async () => randomUUID(),
5497
- deliver: async (request) => {
5498
- await getStateAdapter().set(authorizationKey(args.conversationId, args.actorId), JSON.stringify({
5499
- ...request,
5500
- ...args
5501
- }), WEB_AUTHORIZATION_TTL_MS);
5502
- }
5702
+ async function verifiedEmailDecision(value) {
5703
+ const email = parseEmail(value)?.email;
5704
+ if (!email) return {
5705
+ trusted: false,
5706
+ reason: "invalid_email"
5503
5707
  };
5708
+ const teamId = await resolveBotSlackTeamId();
5709
+ if (!teamId) return {
5710
+ trusted: false,
5711
+ reason: "no_workspace"
5712
+ };
5713
+ return await linkedMemberDecision({
5714
+ email,
5715
+ linked: await findSlackUserByPrimaryEmail(getSqlExecutor(), {
5716
+ normalizedEmail: email,
5717
+ slackTeamId: teamId
5718
+ }),
5719
+ teamId
5720
+ });
5504
5721
  }
5505
- /** Read the pending authorization request for one web actor. */
5506
- async function getWebAuthorization(args) {
5507
- const value = await getStateAdapter().get(authorizationKey(args.conversationId, args.actorId));
5508
- if (typeof value !== "string") return void 0;
5722
+ /**
5723
+ * Find the trusted person behind an account of a plugin's provider or behind
5724
+ * a verified email, for work that runs as that person. A verified email is
5725
+ * trusted when it is the primary email of the User of one Slack member on
5726
+ * the allowed domains, and Slack still shows that email. Slack and storage
5727
+ * errors propagate.
5728
+ */
5729
+ async function findTrustedUser(author) {
5730
+ let decision;
5731
+ if ("subjectId" in author) decision = await accountDecision({
5732
+ ...author,
5733
+ listed: false
5734
+ });
5735
+ else decision = await verifiedEmailDecision(author.verifiedEmail);
5736
+ if (!decision.trusted) return {
5737
+ status: "untrusted",
5738
+ reason: decision.reason
5739
+ };
5740
+ return decision.user ? {
5741
+ status: "trusted",
5742
+ user: decision.user
5743
+ } : {
5744
+ status: "untrusted",
5745
+ reason: "no_single_link"
5746
+ };
5747
+ }
5748
+ /**
5749
+ * Resolve the author of an Event, the same way Slack ingress resolves a
5750
+ * Slack author. It never throws: a failed check gives an untrusted author,
5751
+ * so the Event still runs and the author's text stays context.
5752
+ */
5753
+ async function resolveEventAuthor(event) {
5754
+ const author = event.author;
5755
+ if (!author) return { status: "system" };
5756
+ const facts = {
5757
+ ...author.bot ? { bot: true } : void 0,
5758
+ handle: author.handle,
5759
+ provider: event.namespace,
5760
+ ...author.text?.trim() ? { text: author.text.trim() } : void 0
5761
+ };
5509
5762
  try {
5510
- const parsed = JSON.parse(value);
5511
- if (parsed.actorId !== args.actorId || parsed.conversationId !== args.conversationId || typeof parsed.authorizationUrl !== "string" || typeof parsed.label !== "string" || typeof parsed.completionText !== "string") return;
5512
- return parsed;
5513
- } catch {
5514
- return;
5763
+ const decision = await accountDecision({
5764
+ listed: author.trusted === true,
5765
+ provider: event.namespace,
5766
+ ...author.subjectId ? { subjectId: author.subjectId } : void 0
5767
+ });
5768
+ if (!decision.trusted) return {
5769
+ status: "untrusted",
5770
+ reason: decision.reason,
5771
+ ...facts
5772
+ };
5773
+ if (!decision.actor) return {
5774
+ status: "trusted",
5775
+ ...facts
5776
+ };
5777
+ return {
5778
+ status: "trusted",
5779
+ actor: decision.actor,
5780
+ identityId: await resolveActorIdentityId(getSqlExecutor(), decision.actor),
5781
+ ...facts
5782
+ };
5783
+ } catch (error) {
5784
+ logException(error, "event.author.trust_check_failed", {
5785
+ "app.event.event_type": event.eventType,
5786
+ "app.event.namespace": event.namespace
5787
+ });
5788
+ return {
5789
+ status: "untrusted",
5790
+ reason: "check_failed",
5791
+ ...facts
5792
+ };
5515
5793
  }
5516
5794
  }
5517
- /** Remove a web authorization request after the parked turn continues. */
5518
- async function deleteWebAuthorization(args) {
5519
- await getStateAdapter().delete(authorizationKey(args.conversationId, args.actorId));
5795
+ function safeId(value) {
5796
+ return value.replace(/[^A-Za-z0-9._:@/#+[\]-]/g, "_");
5520
5797
  }
5521
- // src/chat/state/conversation.ts
5522
- function defaultConversationState() {
5798
+ /**
5799
+ * Return an Event author's own text and who wrote it. A linked person has
5800
+ * the same author ID and name as on their Slack messages. Other authors
5801
+ * show their handle on the provider.
5802
+ */
5803
+ function eventAuthorText(author) {
5804
+ if (author.status === "system" || !author.text) return void 0;
5805
+ const actor = author.status === "trusted" ? author.actor : void 0;
5806
+ const name = actor?.fullName ?? actor?.userName ?? `${safeId(author.handle)} on ${safeId(author.provider)}${author.bot ? " (a bot)" : ""}`;
5523
5807
  return {
5524
- schemaVersion: 1,
5525
- messages: [],
5526
- processing: {},
5527
- vision: { byFileId: {} }
5808
+ text: author.text,
5809
+ ...actor ? { authorId: actor.userId } : void 0,
5810
+ authorName: name,
5811
+ verified: author.status === "trusted"
5528
5812
  };
5529
5813
  }
5530
- const nonEmptyString = z.string().refine((value) => value.trim().length > 0);
5531
- const optionalString = nonEmptyString.optional().catch(void 0);
5532
- const optionalNumber = z.number().optional().catch(void 0);
5533
- const pendingAuthCommonFields = {
5534
- provider: nonEmptyString,
5535
- actorId: nonEmptyString,
5536
- sessionId: nonEmptyString,
5537
- linkSentAtMs: z.number(),
5538
- scope: optionalString
5539
- };
5540
- const pendingAuthSchema = z.discriminatedUnion("kind", [z.object({
5541
- ...pendingAuthCommonFields,
5542
- kind: z.literal("mcp"),
5543
- authSessionId: nonEmptyString
5544
- }), z.object({
5545
- ...pendingAuthCommonFields,
5546
- kind: z.literal("plugin")
5547
- })]);
5548
- const visionSummarySchema = z.object({
5549
- summary: nonEmptyString,
5550
- analyzedAtMs: z.number().refine((value) => value !== 0)
5814
+ // src/chat/events/notification.ts
5815
+ const EVENT_WAIT_MS = 3e4;
5816
+ const eventTaskFactsSchema = z.object({
5817
+ about: z.string().optional(),
5818
+ instructions: z.string().min(1),
5819
+ guidance: z.string().optional(),
5820
+ people: z.array(z.string()).optional(),
5821
+ trustedSummary: z.string().optional(),
5822
+ verifiedDetails: z.record(z.string(), z.unknown()).optional(),
5823
+ externalText: z.string().optional(),
5824
+ doneBy: z.object({
5825
+ mention: z.string(),
5826
+ handle: z.string().optional()
5827
+ }).optional(),
5828
+ /** The Event author's own text and who wrote it. It is context. */
5829
+ authorText: z.object({
5830
+ text: z.string().min(1),
5831
+ authorId: z.string().optional(),
5832
+ authorName: z.string().optional(),
5833
+ verified: z.boolean()
5834
+ }).optional()
5551
5835
  });
5552
- const storedThreadStateSchema = z.object({ conversation: z.object({
5553
- processing: z.object({
5554
- activeTurnId: optionalString,
5555
- lastCompletedAtMs: optionalNumber,
5556
- pendingAuth: pendingAuthSchema.optional().catch(void 0)
5557
- }).catch({}),
5558
- vision: z.object({
5559
- backfillCompletedAtMs: optionalNumber,
5560
- byFileId: z.record(z.string(), z.unknown()).catch({})
5561
- }).catch({ byFileId: {} })
5562
- }).catch({
5563
- processing: {},
5564
- vision: { byFileId: {} }
5565
- }) });
5566
- /** Safely coerce an unknown persisted value into a ThreadConversationState. */
5567
- function coerceThreadConversationState(value) {
5568
- const parsed = storedThreadStateSchema.safeParse(value);
5569
- if (!parsed.success) return defaultConversationState();
5570
- const { processing, vision } = parsed.data.conversation;
5571
- const byFileId = {};
5572
- for (const [fileId, entry] of Object.entries(vision.byFileId)) {
5573
- if (fileId.trim().length === 0) continue;
5574
- const summary = visionSummarySchema.safeParse(entry);
5575
- if (!summary.success) continue;
5576
- byFileId[fileId] = summary.data;
5577
- }
5578
- return {
5579
- schemaVersion: 1,
5580
- messages: [],
5581
- processing,
5582
- vision: {
5583
- backfillCompletedAtMs: vision.backfillCompletedAtMs,
5584
- byFileId
5585
- }
5586
- };
5587
- }
5588
5836
  /**
5589
- * Wrap active conversation control into the thread scratch envelope.
5837
+ * Collect the task facts for one subscribed Event.
5590
5838
  *
5591
- * Visible history lives in SQL. Image summaries use a separate disposable
5592
- * cache, so thread scratch does not retain them.
5839
+ * Keep this short: facts the model cannot reconstruct, plus a one-line handling
5840
+ * contract. Stable delivery rules live in runtime and docs, not this prompt.
5593
5841
  */
5594
- function buildConversationStatePatch(conversation) {
5595
- return { conversation: {
5596
- schemaVersion: 1,
5597
- processing: { ...conversation.processing }
5598
- } };
5842
+ function eventTaskFacts(subscription, event, people = [], doneBy, author = { status: "system" }) {
5843
+ const guidance = [eventGuidance(getEventCatalog(), event.namespace, event.eventType), subscription.guidance?.[event.eventType]].filter((text) => Boolean(text?.trim())).join(" ");
5844
+ const authorText = eventAuthorText(author);
5845
+ return {
5846
+ about: subscription.label,
5847
+ instructions: subscription.intent,
5848
+ ...guidance ? { guidance } : void 0,
5849
+ ...people.length > 0 ? { people: [...people] } : void 0,
5850
+ trustedSummary: event.trustedSummary,
5851
+ ...event.data ? { verifiedDetails: event.data } : void 0,
5852
+ ...authorText ? { authorText } : void 0,
5853
+ ...event.untrustedText ? { externalText: event.untrustedText } : void 0,
5854
+ ...doneBy ? { doneBy } : void 0
5855
+ };
5599
5856
  }
5600
- // src/chat/runtime/thread-state.ts
5601
- function threadStateKey(threadId) {
5602
- return `thread-state:${threadId}`;
5857
+ /**
5858
+ * Return the timer creator subject when every event in the batch carries a
5859
+ * valid subject for its own Watch and the same user.
5860
+ */
5861
+ function timerWatchCredentialSubject(conversationId, messages) {
5862
+ let shared;
5863
+ for (const message of messages) {
5864
+ const metadata = message.input.metadata;
5865
+ if (!isEventMailboxMetadata(metadata)) return void 0;
5866
+ const parsed = credentialSubjectSchema.safeParse(metadata.credentialSubject);
5867
+ if (!parsed.success || !metadata.event.subscriptionId || !verifyTimerWatchCredentialSubject({
5868
+ conversationId,
5869
+ subject: parsed.data,
5870
+ watchId: metadata.event.subscriptionId
5871
+ }) || shared && shared.userId !== parsed.data.userId) return;
5872
+ shared ??= parsed.data;
5873
+ }
5874
+ return shared;
5603
5875
  }
5604
- function channelStateKey(channelId) {
5605
- return `channel-state:${channelId}`;
5876
+ /**
5877
+ * Read the saved Watch task facts from one Event mailbox entry. Entries
5878
+ * without a Watch or saved facts, such as child agent results and input queued
5879
+ * before facts were saved, return undefined and keep their own text.
5880
+ */
5881
+ function readEventTaskFacts(message) {
5882
+ const metadata = message.input.metadata;
5883
+ if (!isEventMailboxMetadata(metadata)) return void 0;
5884
+ const watchId = metadata.event.subscriptionId;
5885
+ if (!watchId) return void 0;
5886
+ const parsed = eventTaskFactsSchema.safeParse(metadata.task);
5887
+ return parsed.success ? {
5888
+ facts: parsed.data,
5889
+ metadata,
5890
+ watchId
5891
+ } : void 0;
5606
5892
  }
5607
- function buildThreadStatePayload(patch) {
5608
- const payload = {};
5609
- if (patch.conversation) Object.assign(payload, buildConversationStatePatch(patch.conversation));
5610
- if (patch.sandboxRef !== void 0) {
5611
- payload["app_sandbox_id"] = patch.sandboxRef?.id ?? "";
5612
- payload["app_sandbox_dependency_profile_hash"] = patch.sandboxRef?.profileHash ?? "";
5613
- payload["app_sandbox_workspace_id"] = patch.sandboxRef?.workspaceId ?? "";
5614
- const toolSession = patch.sandboxRef?.toolSession;
5615
- payload["app_sandbox_tool_sandbox_id"] = toolSession?.sandboxId ?? "";
5616
- payload["app_sandbox_tool_session_id"] = toolSession?.sessionId ?? "";
5893
+ /**
5894
+ * Write the agent inputs for an Event batch, one prompt content part each.
5895
+ *
5896
+ * One Event keeps its own text. Several Watch Events become one `<task>`
5897
+ * with one group per Watch, so shared instructions appear once. Entries
5898
+ * without task facts, such as child agent results, keep their own text as
5899
+ * their own inputs after the task. `rendered` replaces the input of an entry
5900
+ * by inbound message id, such as a person change to an Inbox item.
5901
+ */
5902
+ function renderEventBatchInputs(messages, rendered = /* @__PURE__ */ new Map()) {
5903
+ const groups = /* @__PURE__ */ new Map();
5904
+ const others = [];
5905
+ for (const message of messages) {
5906
+ const saved = readEventTaskFacts(message);
5907
+ if (!saved) {
5908
+ others.push(message);
5909
+ continue;
5910
+ }
5911
+ const { facts, metadata, watchId } = saved;
5912
+ let group = groups.get(watchId);
5913
+ if (!group) {
5914
+ group = {
5915
+ about: facts.about,
5916
+ instructions: facts.instructions,
5917
+ people: [],
5918
+ events: []
5919
+ };
5920
+ groups.set(watchId, group);
5921
+ }
5922
+ for (const person of facts.people ?? []) if (!group.people.includes(person)) group.people.push(person);
5923
+ group.events.push({
5924
+ eventType: metadata.event.eventType,
5925
+ guidance: facts.guidance,
5926
+ source: metadata.event.namespace,
5927
+ trustedSummary: facts.trustedSummary,
5928
+ verifiedDetails: facts.verifiedDetails,
5929
+ authorText: facts.authorText,
5930
+ externalText: facts.externalText,
5931
+ doneBy: facts.doneBy
5932
+ });
5617
5933
  }
5618
- return payload;
5934
+ const ownInputs = (entries) => entries.map((message) => rendered.get(message.inboundMessageId) ?? {
5935
+ kind: "runtime",
5936
+ text: message.input.text.trim()
5937
+ }).filter((input) => input.text);
5938
+ if (messages.length - others.length < 2) return ownInputs(messages);
5939
+ return [{
5940
+ kind: "runtime",
5941
+ text: renderTaskBatchInput({ groups: [...groups.values()] })
5942
+ }, ...ownInputs(others)];
5943
+ }
5944
+ /** Return the conversation message entry for one Event input. */
5945
+ function messageEvent(message) {
5946
+ const metadata = message.input.metadata;
5947
+ if (!isEventMailboxMetadata(metadata)) return [];
5948
+ const label = readEventTaskFacts(message)?.facts.about;
5949
+ return [{
5950
+ eventType: metadata.event.eventType,
5951
+ ...label ? { label } : void 0,
5952
+ ...metadata.event.objectType ? { objectType: metadata.event.objectType } : void 0,
5953
+ ...metadata.event.trustedSummary ? { trustedSummary: metadata.event.trustedSummary } : void 0
5954
+ }];
5619
5955
  }
5620
5956
  /**
5621
- * Merge a payload into thread scratch with Junior's TTL.
5957
+ * Return the saved Message fields for the Event inputs of one Turn.
5622
5958
  *
5623
- * Chat SDK state writes hardcode a 30-day TTL. This boundary owns Junior's
5624
- * shorter retention policy for the same scratch keys.
5959
+ * A person change to an Inbox item is not one of the Message's own Events:
5960
+ * its record goes to `reviewItemChanges`, and the dashboard shows it as a
5961
+ * change row. The Message's own Event is its first Watch Event, the
5962
+ * kind the task message counts, or else its first other input, such as an
5963
+ * agent result. `events` lists the Watch Events when several arrived. When
5964
+ * changes share the Message with one own Event, `events` lists that Event, so
5965
+ * a reader can tell it from a Message that only records changes.
5625
5966
  */
5626
- async function mergePersistedState(key, payload) {
5627
- if (Object.keys(payload).length === 0) return;
5628
- const stateAdapter = getStateAdapter();
5629
- await stateAdapter.connect();
5630
- const existing = await stateAdapter.get(key) ?? {};
5631
- await stateAdapter.set(key, {
5632
- ...existing,
5633
- ...payload
5634
- }, JUNIOR_THREAD_STATE_TTL_MS);
5635
- }
5636
- /** Extract persisted sandbox metadata from thread state payload. */
5637
- function getPersistedSandboxState(state) {
5638
- const id = toOptionalString(state["app_sandbox_id"]);
5639
- if (!id) return;
5640
- const profileHash = toOptionalString(state["app_sandbox_dependency_profile_hash"]);
5641
- const workspaceId = toOptionalString(state["app_sandbox_workspace_id"]);
5642
- const toolSandboxId = toOptionalString(state["app_sandbox_tool_sandbox_id"]);
5643
- const toolSessionId = toOptionalString(state["app_sandbox_tool_session_id"]);
5967
+ function eventBatchMessageMeta(messages) {
5968
+ const reviewItemChanges = messages.flatMap((message) => message.input.reviewItemChange ? [message.input.reviewItemChange] : []);
5969
+ const own = messages.filter((message) => !message.input.reviewItemChange);
5970
+ const watched = own.filter((message) => readEventTaskFacts(message));
5971
+ const primary = watched[0] ?? own[0];
5972
+ const metadata = (primary ?? messages[0])?.input.metadata;
5973
+ if (!isEventMailboxMetadata(metadata)) return {};
5974
+ const events = watched.length > 1 ? watched.flatMap(messageEvent) : reviewItemChanges.length && primary ? messageEvent(primary) : [];
5644
5975
  return {
5645
- id,
5646
- ...profileHash ? { profileHash } : void 0,
5647
- ...workspaceId ? { workspaceId } : void 0,
5648
- ...toolSandboxId && toolSessionId ? { toolSession: {
5649
- sandboxId: toolSandboxId,
5650
- sessionId: toolSessionId
5651
- } } : void 0
5976
+ eventType: metadata.event.eventType,
5977
+ eventNamespace: metadata.event.namespace,
5978
+ eventIdentifier: metadata.event.identifier,
5979
+ eventObjectType: metadata.event.objectType,
5980
+ ...metadata.event.status ? { eventStatus: metadata.event.status } : void 0,
5981
+ ...metadata.event.subscriptionId ? { eventWatchId: metadata.event.subscriptionId } : void 0,
5982
+ ...metadata.event.trustedSummary ? { trustedSummary: metadata.event.trustedSummary } : void 0,
5983
+ ...events.length ? { events } : void 0,
5984
+ ...reviewItemChanges.length ? { reviewItemChanges } : void 0
5652
5985
  };
5653
5986
  }
5654
- /** Persist only the Redis-backed runtime scratch in a thread-state patch. */
5655
- async function persistThreadRuntimeState(conversationId, patch) {
5656
- await mergePersistedState(threadStateKey(conversationId), buildThreadStatePayload(patch));
5657
- }
5658
- /** Load the persisted state payload for a thread without requiring a Chat singleton. */
5659
- async function getPersistedThreadState(threadId) {
5660
- const stateAdapter = getStateAdapter();
5661
- await stateAdapter.connect();
5662
- return await stateAdapter.get(threadStateKey(threadId)) ?? {};
5663
- }
5664
- /** Persist a thread-state patch by thread id without constructing a Chat thread. */
5665
- async function persistThreadStateById(threadId, patch) {
5666
- if (patch.conversation) await persistConversationMessages({
5667
- conversation: patch.conversation,
5668
- conversationId: threadId
5669
- });
5670
- await mergePersistedState(threadStateKey(threadId), buildThreadStatePayload(patch));
5987
+ function eventMessageAuthor(author) {
5988
+ if (author?.status !== "trusted") return {
5989
+ authorId: EVENT_AUTHOR_ID,
5990
+ authorIdentityId: SYSTEM_IDENTITY_ID
5991
+ };
5992
+ if (author.identityId) return {
5993
+ authorId: EVENT_AUTHOR_ID,
5994
+ authorIdentityId: author.identityId
5995
+ };
5996
+ return { authorId: eventBotAuthorId(author.provider, author.handle) };
5671
5997
  }
5672
- /** Load legacy Redis-backed channel state during the SQL cutover. */
5673
- async function getLegacyChannelState(channelId) {
5674
- const stateAdapter = getStateAdapter();
5675
- await stateAdapter.connect();
5676
- return await stateAdapter.get(channelStateKey(channelId)) ?? {};
5998
+ /** Build plain conversation mailbox input for one matched watch. */
5999
+ function createEventInboundMessage(input) {
6000
+ const metadata = {
6001
+ kind: "event",
6002
+ ...input.task ? { task: input.task } : void 0,
6003
+ ...input.subscription.credentialSubject ? { credentialSubject: input.subscription.credentialSubject } : void 0,
6004
+ event: {
6005
+ eventKey: input.event.eventKey,
6006
+ eventType: input.event.eventType,
6007
+ namespace: input.event.namespace,
6008
+ identifier: input.event.identifier,
6009
+ subscriptionId: input.subscription.id,
6010
+ trustedSummary: input.event.trustedSummary,
6011
+ objectType: input.event.objectType,
6012
+ ...input.status ? { status: input.status } : void 0
6013
+ }
6014
+ };
6015
+ return {
6016
+ conversationId: input.subscription.conversationId,
6017
+ createdAtMs: input.event.occurredAtMs,
6018
+ inboundMessageId: eventInboundMessageId(input.subscription.id, input.event.eventKey),
6019
+ delivery: "defer",
6020
+ source: "event",
6021
+ receivedAtMs: input.receivedAtMs ?? Date.now(),
6022
+ input: {
6023
+ text: input.text,
6024
+ ...eventMessageAuthor(input.author),
6025
+ metadata
6026
+ }
6027
+ };
5677
6028
  }
5678
6029
  /**
5679
- * Resolve durable location configuration.
5680
- *
5681
- * Slack still reads the old channel-id Redis bag once during cutover.
6030
+ * Deliver a Quiet Event as a Conversation note. It starts no Turn, so the
6031
+ * automated-turn limit does not apply. The next Turn sees the note as
6032
+ * runtime context. Core writes how to use it before the Event facts, so a
6033
+ * long summary that the note limit cuts never loses that rule.
5682
6034
  */
5683
- function getLocationConfigurationService(destination) {
5684
- if (destination.platform !== "slack") throw new Error("Location configuration requires a Slack Location");
5685
- return createDurableLocationConfigurationService({
5686
- destination,
5687
- db: getDb(),
5688
- loadLegacy: async () => await getLegacyChannelState(destination.channelId)
6035
+ async function addQuietEventNote(args) {
6036
+ const { event, subscription } = args;
6037
+ await addConversationNote({
6038
+ conversationId: subscription.conversationId,
6039
+ createdAtMs: event.occurredAtMs,
6040
+ key: `quiet_event:${subscription.id}:${event.eventKey}`,
6041
+ text: `A Watch received this Event quietly: it started no Turn, and nobody was told. Use it as current state. Do not tell people about it unless they ask or your work needs it. ${subscription.label}, ${event.eventType}: ${event.trustedSummary}`
5689
6042
  });
5690
6043
  }
5691
- // src/chat/runtime/turn.ts
5692
- /** Classified Slack turn failure carrying the owning Sentry capture outward. */
5693
- var ConversationTurnBoundaryError = class extends Error {
5694
- eventId;
5695
- failureCode;
5696
- constructor(args) {
5697
- super(args.cause instanceof Error ? args.cause.message : String(args.cause), { cause: args.cause });
5698
- this.name = "ConversationTurnBoundaryError";
5699
- this.eventId = args.eventId;
5700
- this.failureCode = args.failureCode;
5701
- }
5702
- };
5703
- /** Return a classified Slack boundary failure without erasing its cause. */
5704
- function getConversationTurnBoundaryError(error) {
5705
- return error instanceof ConversationTurnBoundaryError ? error : void 0;
5706
- }
5707
6044
  /**
5708
- * Queue-worker yield routing: respond.ts returns a suspended AgentRunOutcome
5709
- * and the Slack executor raises this at the worker boundary so the lease owner
5710
- * requeues the conversation.
6045
+ * Enqueue a event as normal conversation mailbox input.
6046
+ *
6047
+ * The watch only names the conversation. Destination stays on the conversation
6048
+ * and is applied when the worker runs. A stopped Conversation holds the Event.
5711
6049
  */
5712
- var CooperativeTurnYieldError = class extends Error {
5713
- code = "cooperative_turn_yield";
5714
- constructor(message = "Agent turn yielded at a safe boundary") {
5715
- super(message);
5716
- this.name = "CooperativeTurnYieldError";
5717
- }
5718
- };
5719
- function isCooperativeTurnYieldError(error) {
5720
- return error instanceof CooperativeTurnYieldError;
5721
- }
5722
- /** Error indicating durable turn input could not be committed by the worker owner. */
5723
- var TurnInputCommitLostError = class extends Error {
5724
- code = "turn_input_commit_lost";
5725
- constructor(message = "Turn input commit lost its durable owner") {
5726
- super(message);
5727
- this.name = "TurnInputCommitLostError";
5728
- }
5729
- };
5730
- /** Return whether an error means the durable worker lost input ownership. */
5731
- function isTurnInputCommitLostError(error) {
5732
- return error instanceof TurnInputCommitLostError;
5733
- }
5734
- /** Error indicating durable turn input should stay pending for a later worker. */
5735
- var TurnInputDeferredError = class extends Error {
5736
- code = "turn_input_deferred";
5737
- constructor(message = "Turn input is deferred until the active resume ends") {
5738
- super(message);
5739
- this.name = "TurnInputDeferredError";
5740
- }
5741
- };
5742
- /** Return whether an error means the durable worker should redeliver input later. */
5743
- function isTurnInputDeferredError(error) {
5744
- return error instanceof TurnInputDeferredError;
6050
+ async function enqueueEventNotification(args) {
6051
+ const task = eventTaskFacts(args.subscription, args.event, args.people, args.doneBy, args.author);
6052
+ return await enqueueAutomatedInput({
6053
+ message: createEventInboundMessage({
6054
+ author: args.author,
6055
+ event: args.event,
6056
+ subscription: {
6057
+ conversationId: args.subscription.conversationId,
6058
+ credentialSubject: args.subscription.credentialSubject,
6059
+ id: args.subscription.id
6060
+ },
6061
+ task,
6062
+ text: renderTaskInput({
6063
+ ...task,
6064
+ event: args.event.eventType,
6065
+ source: args.event.namespace
6066
+ })
6067
+ }),
6068
+ queue: args.queue,
6069
+ queueDelayMs: EVENT_WAIT_MS,
6070
+ state: args.state
6071
+ });
5745
6072
  }
5746
- /** Mark a turn as the active turn in conversation state. */
5747
- function startActiveTurn(args) {
5748
- args.conversation.processing.activeTurnId = args.nextTurnId;
6073
+ // src/chat/inbox-items/prompt-input.ts
6074
+ /**
6075
+ * Prompt inputs for person answers to Inbox items. An answer is its own
6076
+ * prompt content part, keyed by the item id that `addInboxItem` returned.
6077
+ * The runtime builds it from the stored change record and the item, so the
6078
+ * model never reads status prose. It repeats the question, then one line for
6079
+ * each answered field. `input-tags.ts` lists the input tags.
6080
+ */
6081
+ const QUESTION_MAX_LENGTH = 512;
6082
+ function typedAnswerText(request, answer) {
6083
+ const normalized = normalizeUserInputAnswer(request, answer);
6084
+ return [...request.fields.flatMap((field) => field.kind === "text" ? normalized.values[field.id] ?? [] : []), ...normalized.other ? [normalized.other] : []].join("\n\n");
5749
6085
  }
5750
- function clearActiveTurn(conversation, sessionId) {
5751
- if (!sessionId || conversation.processing.activeTurnId === sessionId) conversation.processing.activeTurnId = void 0;
6086
+ function renderInboxItemAnswer(item) {
6087
+ const request = inboxItemQuestion(item.request);
6088
+ if (!request || !item.answer) return void 0;
6089
+ const question = request.question.trim();
6090
+ const requestText = typedAnswerText(request, item.answer);
6091
+ return {
6092
+ kind: "runtime",
6093
+ text: renderTag("inbox-item-answer", { id: item.id }, [`Question: ${question.length > QUESTION_MAX_LENGTH ? `${question.slice(0, 511)}…` : question}`, formatUserInputAnswer(request, item.answer)].map(escapeTagText)),
6094
+ ...requestText ? { requestText } : void 0
6095
+ };
5752
6096
  }
5753
6097
  /**
5754
- * Close the active turn without marking a Pi session reusable for future
5755
- * history. Use this for auth handoffs and recovery replies that end the live
5756
- * turn but do not produce a completed Pi session.
6098
+ * Render the prompt input of a message that records an answer, or undefined
6099
+ * when it has none. A take or a dismiss starts no Turn, so it has no input.
6100
+ * A message without an answer, or whose item is gone, goes to the model as
6101
+ * written.
5757
6102
  */
5758
- function markTurnClosed(args) {
5759
- clearActiveTurn(args.conversation, args.sessionId);
5760
- args.conversation.processing.lastCompletedAtMs = args.nowMs;
6103
+ async function loadInboxItemInput(record) {
6104
+ if (record?.kind !== "submitted") return void 0;
6105
+ const item = await getInboxItem(getDb(), record.reviewItemId);
6106
+ return item ? renderInboxItemAnswer(item) : void 0;
5761
6107
  }
5762
6108
  /**
5763
- * Mark a turn as completed after its assistant output has been handled.
6109
+ * Return the instruction of one saved input. `runtime` text, such as an
6110
+ * Automation dispatch or an Event Turn, is already rendered as its tags.
6111
+ * An answer is its Inbox item tag. It is not typed text, so it does not go
6112
+ * in `<current-instruction>`.
5764
6113
  */
5765
- function markTurnCompleted(args) {
5766
- clearActiveTurn(args.conversation, args.sessionId);
5767
- args.conversation.processing.lastCompletedAtMs = args.nowMs;
6114
+ async function savedInputInstruction(args) {
6115
+ const inboxItemInput = args.runtime ? void 0 : await loadInboxItemInput(args.reviewItemChange);
6116
+ if (!args.runtime && !inboxItemInput) return { text: args.text };
6117
+ return instructionForInputs([inboxItemInput ?? {
6118
+ kind: "runtime",
6119
+ text: args.text,
6120
+ ...args.requestText ? { requestText: args.requestText } : void 0
6121
+ }]);
5768
6122
  }
5769
6123
  /**
5770
- * Mark a turn as failed when execution or final user-visible reply delivery
5771
- * cannot be completed. If `sessionId` is provided, `activeTurnId` is only
5772
- * cleared when it still matches the failing turn.
6124
+ * Render the Inbox item input of each Event in a batch that records an
6125
+ * answer, keyed by inbound message id. A Conversation with no web identity,
6126
+ * such as a local CLI Conversation, gets the answer as a system Event, but
6127
+ * the input is the same as on web.
5773
6128
  */
5774
- function markTurnFailed(args) {
5775
- clearActiveTurn(args.conversation, args.sessionId);
5776
- args.conversation.processing.lastCompletedAtMs = args.nowMs;
5777
- args.markConversationMessage(args.conversation, args.userMessageId, {
5778
- replied: false,
5779
- skippedReason: "reply failed"
5780
- });
6129
+ async function eventInboxItemInputs(messages) {
6130
+ const rendered = await mapBounded(messages, async (message) => [message.inboundMessageId, await loadInboxItemInput(message.input.reviewItemChange)]);
6131
+ return new Map(rendered.flatMap(([id, input]) => input ? [[id, input]] : []));
5781
6132
  }
5782
- // src/chat/runtime/turn-user-message.ts
5783
- /** Return the user message for a persisted turn/session, if one exists. */
5784
- function getTurnUserMessage(conversation, sessionId) {
5785
- for (let index = conversation.messages.length - 1; index >= 0; index -= 1) {
5786
- const message = conversation.messages[index];
5787
- if (message?.role !== "user") continue;
5788
- if (buildDeterministicTurnId(message.id) === sessionId) return message;
5789
- }
6133
+ // src/chat/conversations/web-authorization.ts
6134
+ const WEB_AUTHORIZATION_PREFIX = "junior:web_authorization:v1";
6135
+ const WEB_AUTHORIZATION_TTL_MS = 864e5;
6136
+ function authorizationKey(conversationId, actorId) {
6137
+ return `${WEB_AUTHORIZATION_PREFIX}:${conversationId}:${actorId}`;
5790
6138
  }
5791
- /** Return the persisted user-message id for a turn/session, if one exists. */
5792
- function getTurnUserMessageId(conversation, sessionId) {
5793
- return getTurnUserMessage(conversation, sessionId)?.id;
6139
+ /** Build authorization delivery for one web turn. */
6140
+ function createWebAuthorization(args) {
6141
+ return {
6142
+ createState: async () => randomUUID(),
6143
+ deliver: async (request) => {
6144
+ await getStateAdapter().set(authorizationKey(args.conversationId, args.actorId), JSON.stringify({
6145
+ ...request,
6146
+ ...args
6147
+ }), WEB_AUTHORIZATION_TTL_MS);
6148
+ }
6149
+ };
5794
6150
  }
5795
- /** Return the Slack timestamp for the user message that a resumed turn acts on. */
5796
- function getTurnUserSlackMessageTs(message) {
5797
- return parseSlackMessageTs(message?.meta?.slackTs);
6151
+ /** Read the pending authorization request for one web actor. */
6152
+ async function getWebAuthorization(args) {
6153
+ const value = await getStateAdapter().get(authorizationKey(args.conversationId, args.actorId));
6154
+ if (typeof value !== "string") return void 0;
6155
+ try {
6156
+ const parsed = JSON.parse(value);
6157
+ if (parsed.actorId !== args.actorId || parsed.conversationId !== args.conversationId || typeof parsed.authorizationUrl !== "string" || typeof parsed.label !== "string" || typeof parsed.completionText !== "string") return;
6158
+ return parsed;
6159
+ } catch {
6160
+ return;
6161
+ }
5798
6162
  }
5799
- /** Rebuild attachment context for a resumed turn from the persisted user message. */
5800
- function getTurnUserReplyAttachmentContext(message) {
5801
- const inboundAttachmentCount = message?.meta?.attachmentCount ?? 0;
5802
- const imageAttachmentCount = message?.meta?.imageAttachmentCount ?? 0;
5803
- const imagesHydrated = message?.meta?.imagesHydrated === true;
6163
+ /** Remove a web authorization request after the parked turn continues. */
6164
+ async function deleteWebAuthorization(args) {
6165
+ await getStateAdapter().delete(authorizationKey(args.conversationId, args.actorId));
6166
+ }
6167
+ // src/chat/state/conversation.ts
6168
+ function defaultConversationState() {
5804
6169
  return {
5805
- ...inboundAttachmentCount > 0 ? { inboundAttachmentCount } : void 0,
5806
- ...!imagesHydrated && imageAttachmentCount > 0 ? { omittedImageAttachmentCount: imageAttachmentCount } : void 0
6170
+ schemaVersion: 1,
6171
+ messages: [],
6172
+ processing: {},
6173
+ vision: { byFileId: {} }
5807
6174
  };
5808
6175
  }
5809
- // src/chat/task-execution/turn-cancel.ts
5810
- /**
5811
- * End a cancelled Turn: a stop that a worker saw, or a stop of a Turn that
5812
- * waits for sign-in with no worker.
5813
- */
5814
- /** Close a cancelled Turn, save it, and acknowledge its input. */
5815
- async function completeCancelledConversationTurn(args) {
5816
- const pendingAuthorization = args.conversation.processing.pendingAuth?.sessionId === args.turnId ? args.conversation.processing.pendingAuth : void 0;
5817
- await abandonTurnRecord({
5818
- conversationId: args.conversationId,
5819
- turnId: args.turnId,
5820
- errorMessage: "Turn cancelled"
5821
- });
5822
- clearPendingAuth(args.conversation, args.turnId);
5823
- markConversationMessage(args.conversation, args.userMessageId, {
5824
- replied: false,
5825
- skippedReason: "turn cancelled"
5826
- });
5827
- markTurnClosed({
5828
- conversation: args.conversation,
5829
- nowMs: Date.now(),
5830
- sessionId: args.turnId
5831
- });
5832
- if (pendingAuthorization) await deleteWebAuthorization({
5833
- actorId: pendingAuthorization.actorId,
5834
- conversationId: args.conversationId
5835
- });
5836
- await persistThreadStateById(args.conversationId, {
5837
- conversation: args.conversation,
5838
- sandboxRef: args.sandboxRef
5839
- });
5840
- await getTurnLifecycle().complete({
5841
- conversationId: args.conversationId,
5842
- createdAtMs: Date.now(),
5843
- outcome: "cancelled",
5844
- turnId: args.turnId
5845
- });
5846
- await args.acknowledge();
6176
+ const nonEmptyString = z.string().refine((value) => value.trim().length > 0);
6177
+ const optionalString = nonEmptyString.optional().catch(void 0);
6178
+ const optionalNumber = z.number().optional().catch(void 0);
6179
+ const pendingAuthCommonFields = {
6180
+ provider: nonEmptyString,
6181
+ actorId: nonEmptyString,
6182
+ sessionId: nonEmptyString,
6183
+ linkSentAtMs: z.number(),
6184
+ scope: optionalString
6185
+ };
6186
+ const pendingAuthSchema = z.discriminatedUnion("kind", [z.object({
6187
+ ...pendingAuthCommonFields,
6188
+ kind: z.literal("mcp"),
6189
+ authSessionId: nonEmptyString
6190
+ }), z.object({
6191
+ ...pendingAuthCommonFields,
6192
+ kind: z.literal("plugin")
6193
+ })]);
6194
+ const visionSummarySchema = z.object({
6195
+ summary: nonEmptyString,
6196
+ analyzedAtMs: z.number().refine((value) => value !== 0)
6197
+ });
6198
+ const storedThreadStateSchema = z.object({ conversation: z.object({
6199
+ processing: z.object({
6200
+ activeTurnId: optionalString,
6201
+ lastCompletedAtMs: optionalNumber,
6202
+ pendingAuth: pendingAuthSchema.optional().catch(void 0)
6203
+ }).catch(() => ({})),
6204
+ vision: z.object({
6205
+ backfillCompletedAtMs: optionalNumber,
6206
+ byFileId: z.record(z.string(), z.unknown()).catch(() => ({}))
6207
+ }).catch(() => ({ byFileId: {} }))
6208
+ }).catch(() => ({
6209
+ processing: {},
6210
+ vision: { byFileId: {} }
6211
+ })) });
6212
+ /** Safely coerce an unknown persisted value into a ThreadConversationState. */
6213
+ function coerceThreadConversationState(value) {
6214
+ const parsed = storedThreadStateSchema.safeParse(value);
6215
+ if (!parsed.success) return defaultConversationState();
6216
+ const { processing, vision } = parsed.data.conversation;
6217
+ const byFileId = {};
6218
+ for (const [fileId, entry] of Object.entries(vision.byFileId)) {
6219
+ if (fileId.trim().length === 0) continue;
6220
+ const summary = visionSummarySchema.safeParse(entry);
6221
+ if (!summary.success) continue;
6222
+ byFileId[fileId] = summary.data;
6223
+ }
6224
+ return {
6225
+ schemaVersion: 1,
6226
+ messages: [],
6227
+ processing,
6228
+ vision: {
6229
+ backfillCompletedAtMs: vision.backfillCompletedAtMs,
6230
+ byFileId
6231
+ }
6232
+ };
5847
6233
  }
5848
6234
  /**
5849
- * End the Turn of a stopped Conversation that waits for sign-in, so a later
5850
- * sign-in cannot resume it. A web Turn waits as an auth-paused Turn record. A
5851
- * Slack request waits as the thread's pending sign-in. Every stop path calls
5852
- * this, because no worker holds a waiting Turn and the stop wake can go to
5853
- * queued input first.
6235
+ * Wrap active conversation control into the thread scratch envelope.
6236
+ *
6237
+ * Visible history lives in SQL. Image summaries use a separate disposable
6238
+ * cache, so thread scratch does not retain them.
5854
6239
  */
5855
- async function cancelSignInWait(conversationId) {
5856
- const turnId = await getAuthPausedConversationTurnId(conversationId) ?? coerceThreadConversationState(await getPersistedThreadState(conversationId)).processing.pendingAuth?.sessionId;
5857
- if (turnId) await cancelSignInPausedTurn({
5858
- conversationId,
5859
- turnId
5860
- });
6240
+ function buildConversationStatePatch(conversation) {
6241
+ return { conversation: {
6242
+ schemaVersion: 1,
6243
+ processing: { ...conversation.processing }
6244
+ } };
5861
6245
  }
5862
- /**
5863
- * Cancel a Turn that waits for sign-in outside its worker, with the same
5864
- * cleanup as a stopped resume.
5865
- */
5866
- async function cancelSignInPausedTurn(args) {
5867
- if (!await abandonTurnRecord({
5868
- conversationId: args.conversationId,
5869
- errorMessage: "Turn cancelled",
5870
- onlyIfAuthPaused: true,
5871
- turnId: args.turnId
5872
- })) return;
5873
- const conversation = coerceThreadConversationState(await getPersistedThreadState(args.conversationId));
5874
- await hydrateConversationMessages({
5875
- conversation,
5876
- conversationId: args.conversationId
5877
- });
5878
- await completeCancelledConversationTurn({
5879
- acknowledge: async () => {},
5880
- conversation,
5881
- conversationId: args.conversationId,
5882
- turnId: args.turnId,
5883
- userMessageId: getTurnUserMessage(conversation, args.turnId)?.id
5884
- });
6246
+ // src/chat/runtime/thread-state.ts
6247
+ function threadStateKey(threadId) {
6248
+ return `thread-state:${threadId}`;
5885
6249
  }
5886
- // src/chat/conversations/session-stop.ts
5887
- var session_stop_exports = /* @__PURE__ */ __exportAll({ resumeForPersonInput: () => resumeForPersonInput });
5888
- /** Return when a Conversation stopped, or undefined when it is not stopped. */
5889
- async function getConversationStoppedAtMs(conversationId) {
5890
- const [row] = await getSqlExecutor().db().select({ stoppedAt: juniorConversations.stoppedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
5891
- return row?.stoppedAt?.getTime();
6250
+ function channelStateKey(channelId) {
6251
+ return `channel-state:${channelId}`;
5892
6252
  }
5893
- /**
5894
- * The hold rule: a Conversation holds automated input only while it is
5895
- * stopped. Status and failure do not hold input.
5896
- */
5897
- async function isHeld(conversationId) {
5898
- return await getConversationStoppedAtMs(conversationId) !== void 0;
6253
+ function buildThreadStatePayload(patch) {
6254
+ const payload = {};
6255
+ if (patch.conversation) Object.assign(payload, buildConversationStatePatch(patch.conversation));
6256
+ if (patch.sandboxRef !== void 0) {
6257
+ payload["app_sandbox_id"] = patch.sandboxRef?.id ?? "";
6258
+ payload["app_sandbox_dependency_profile_hash"] = patch.sandboxRef?.profileHash ?? "";
6259
+ payload["app_sandbox_workspace_id"] = patch.sandboxRef?.workspaceId ?? "";
6260
+ const toolSession = patch.sandboxRef?.toolSession;
6261
+ payload["app_sandbox_tool_sandbox_id"] = toolSession?.sandboxId ?? "";
6262
+ payload["app_sandbox_tool_session_id"] = toolSession?.sessionId ?? "";
6263
+ }
6264
+ return payload;
5899
6265
  }
5900
6266
  /**
5901
- * Accept automated input, such as a Watch Event, a message from another
5902
- * agent, or a child result. This is the only place that holds input. It
5903
- * checks the hold under the mailbox lock, so it cannot race a stop: held
5904
- * input is saved as a skipped Message and never reaches `pending`, and the
5905
- * stop holds input that was appended before it.
6267
+ * Merge a payload into thread scratch with Junior's TTL.
6268
+ *
6269
+ * Chat SDK state writes hardcode a 30-day TTL. This boundary owns Junior's
6270
+ * shorter retention policy for the same scratch keys.
5906
6271
  */
5907
- async function enqueueAutomatedInput(args) {
5908
- if (args.message.source !== "event") throw new Error("Automated input must be an Event");
5909
- let held = false;
5910
- const result = await appendAndEnqueueInboundMessage({
5911
- ...args,
5912
- renderText: async (inboundMessageIds, messageSenders) => {
5913
- const text = args.renderText ? await args.renderText(inboundMessageIds, messageSenders) : args.message.input.text;
5914
- if (text === void 0 || !await isHeld(args.message.conversationId)) return text;
5915
- await saveHeldInput(args.message.conversationId, [{
5916
- ...args.message,
5917
- input: {
5918
- ...args.message.input,
5919
- text
5920
- }
5921
- }]);
5922
- held = true;
5923
- }
6272
+ async function mergePersistedState(key, payload) {
6273
+ if (Object.keys(payload).length === 0) return;
6274
+ const stateAdapter = getStateAdapter();
6275
+ await stateAdapter.connect();
6276
+ const existing = await stateAdapter.get(key) ?? {};
6277
+ await stateAdapter.set(key, {
6278
+ ...existing,
6279
+ ...payload
6280
+ }, JUNIOR_THREAD_STATE_TTL_MS);
6281
+ }
6282
+ /** Extract persisted sandbox metadata from thread state payload. */
6283
+ function getPersistedSandboxState(state) {
6284
+ const id = toOptionalString(state["app_sandbox_id"]);
6285
+ if (!id) return;
6286
+ const profileHash = toOptionalString(state["app_sandbox_dependency_profile_hash"]);
6287
+ const workspaceId = toOptionalString(state["app_sandbox_workspace_id"]);
6288
+ const toolSandboxId = toOptionalString(state["app_sandbox_tool_sandbox_id"]);
6289
+ const toolSessionId = toOptionalString(state["app_sandbox_tool_session_id"]);
6290
+ return {
6291
+ id,
6292
+ ...profileHash ? { profileHash } : void 0,
6293
+ ...workspaceId ? { workspaceId } : void 0,
6294
+ ...toolSandboxId && toolSessionId ? { toolSession: {
6295
+ sandboxId: toolSandboxId,
6296
+ sessionId: toolSessionId
6297
+ } } : void 0
6298
+ };
6299
+ }
6300
+ /** Persist only the Redis-backed runtime scratch in a thread-state patch. */
6301
+ async function persistThreadRuntimeState(conversationId, patch) {
6302
+ await mergePersistedState(threadStateKey(conversationId), buildThreadStatePayload(patch));
6303
+ }
6304
+ /** Load the persisted state payload for a thread without requiring a Chat singleton. */
6305
+ async function getPersistedThreadState(threadId) {
6306
+ const stateAdapter = getStateAdapter();
6307
+ await stateAdapter.connect();
6308
+ return await stateAdapter.get(threadStateKey(threadId)) ?? {};
6309
+ }
6310
+ /** Persist a thread-state patch by thread id without constructing a Chat thread. */
6311
+ async function persistThreadStateById(threadId, patch) {
6312
+ if (patch.conversation) await persistConversationMessages({
6313
+ conversation: patch.conversation,
6314
+ conversationId: threadId
5924
6315
  });
5925
- return held ? { status: "held" } : result;
6316
+ await mergePersistedState(threadStateKey(threadId), buildThreadStatePayload(patch));
6317
+ }
6318
+ /** Load legacy Redis-backed channel state during the SQL cutover. */
6319
+ async function getLegacyChannelState(channelId) {
6320
+ const stateAdapter = getStateAdapter();
6321
+ await stateAdapter.connect();
6322
+ return await stateAdapter.get(channelStateKey(channelId)) ?? {};
5926
6323
  }
5927
6324
  /**
5928
- * Stop each Conversation of a tree until a person sends it input or its
5929
- * parent gives it new work. Every stop path ends here: a person's stop,
5930
- * `stopAgent`, and the automated-turn limit. It writes the stop in one
5931
- * transaction with row locks, holds the automated input that already waits
5932
- * in each mailbox, ends a Turn that waits for sign-in, and asks each running
5933
- * Turn to stop. Each Turn it ends records one cancelled `turn_completed`.
5934
- * Watches stay, and each Conversation that this stop starts reports
5935
- * a `stopped` agent update to them. A Conversation that already stopped later
5936
- * keeps that stop, so a retried or cascaded stop does not move it back.
6325
+ * Resolve durable location configuration.
6326
+ *
6327
+ * Slack still reads the old channel-id Redis bag once during cutover.
5937
6328
  */
5938
- async function stopConversationTree(conversationIds, options) {
5939
- if (conversationIds.length === 0) return [];
5940
- const stoppedAt = new Date(options.stoppedAtMs);
5941
- const reported = await getSqlExecutor().transaction(async () => {
5942
- const tx = getDb();
5943
- const locked = await tx.select({
5944
- conversationId: juniorConversations.conversationId,
5945
- stoppedAt: juniorConversations.stoppedAt
5946
- }).from(juniorConversations).where(inArray(juniorConversations.conversationId, [...conversationIds])).orderBy(asc(juniorConversations.conversationId)).for("update");
5947
- await tx.update(juniorConversations).set({
5948
- stoppedAt,
5949
- detailVersion: nextDetailVersion
5950
- }).where(and(inArray(juniorConversations.conversationId, [...conversationIds]), or(isNull(juniorConversations.stoppedAt), lt(juniorConversations.stoppedAt, stoppedAt))));
5951
- return locked.flatMap((row) => !row.stoppedAt || row.stoppedAt.getTime() === stoppedAt.getTime() ? [row.conversationId] : []);
5952
- });
5953
- const queue = options.queue ?? getVercelConversationWorkQueue();
5954
- await mapBounded(reported, (conversationId) => publishAgentUpdate(conversationId, {
5955
- type: "stopped",
5956
- stoppedAtMs: stoppedAt.getTime()
5957
- }, {
5958
- nowMs: stoppedAt.getTime(),
5959
- queue,
5960
- starter: false,
5961
- state: options.state,
5962
- update: async () => ({
5963
- status: "stopped",
5964
- text: "This conversation was stopped."
5965
- })
5966
- }));
5967
- return await mapBounded(conversationIds, async (conversationId) => {
5968
- const pending = await takePendingEventMessages({
5969
- conversationId,
5970
- conversationStore: options.conversationStore,
5971
- nowMs: options.nowMs,
5972
- state: options.state
5973
- });
5974
- if (pending.length > 0) await saveHeldInput(conversationId, pending);
5975
- await cancelSignInWait(conversationId);
5976
- if (conversationId === options.finishedRunOf) return { status: "no_work" };
5977
- return await stopConversationWork({
5978
- conversationId,
5979
- conversationStore: options.conversationStore,
5980
- nowMs: options.nowMs,
5981
- onStopSaved: options.onStopSaved,
5982
- sentAtOrBeforeMs: options.sentAtOrBeforeMs,
5983
- state: options.state
5984
- });
6329
+ function getLocationConfigurationService(destination) {
6330
+ if (destination.platform !== "slack") throw new Error("Location configuration requires a Slack Location");
6331
+ return createDurableLocationConfigurationService({
6332
+ destination,
6333
+ db: getDb(),
6334
+ loadLegacy: async () => await getLegacyChannelState(destination.channelId)
5985
6335
  });
5986
6336
  }
5987
- /**
5988
- * End the stop of a Conversation and of the child agents below it, for new
5989
- * work sent at `sentAtMs`: a person's input, or new work from its parent.
5990
- * Nothing changes for work sent at or before the stop, so the input that a
5991
- * stop drops does not undo it. Only Conversations that stopped no later than
5992
- * this Conversation change, so a later stop of one child agent stays.
5993
- */
5994
- async function resumeConversationTree(conversationId, sentAtMs) {
5995
- const subtree = sql`(select ${conversationSubtreeColumns.conversationId} from ${conversationSubtree([conversationId])})`;
5996
- await getSqlExecutor().transaction(async () => {
5997
- const tx = getDb();
5998
- const stoppedAt = (await tx.select({
5999
- conversationId: juniorConversations.conversationId,
6000
- stoppedAt: juniorConversations.stoppedAt
6001
- }).from(juniorConversations).where(inArray(juniorConversations.conversationId, subtree)).orderBy(asc(juniorConversations.conversationId)).for("update")).find((row) => row.conversationId === conversationId)?.stoppedAt;
6002
- if (!stoppedAt || sentAtMs <= stoppedAt.getTime()) return;
6003
- await tx.update(juniorConversations).set({
6004
- stoppedAt: null,
6005
- detailVersion: nextDetailVersion
6006
- }).where(and(inArray(juniorConversations.conversationId, subtree), lte(juniorConversations.stoppedAt, stoppedAt)));
6007
- });
6337
+ // src/chat/runtime/turn-user-message.ts
6338
+ /** Return the user message for a persisted turn/session, if one exists. */
6339
+ function getTurnUserMessage(conversation, sessionId) {
6340
+ for (let index = conversation.messages.length - 1; index >= 0; index -= 1) {
6341
+ const message = conversation.messages[index];
6342
+ if (message?.role !== "user") continue;
6343
+ if (buildDeterministicTurnId(message.id) === sessionId) return message;
6344
+ }
6008
6345
  }
6009
- /**
6010
- * Resume a stopped Conversation when a person sent input after the stop.
6011
- * Known gap: input sent before the stop but received after it still runs,
6012
- * and the Conversation stays stopped.
6013
- */
6014
- async function resumeForPersonInput(conversationId, messages) {
6015
- const personInput = messages.filter((message) => isPersonInput(message.source));
6016
- if (personInput.length === 0) return;
6017
- await resumeConversationTree(conversationId, Math.max(...personInput.map((message) => message.createdAtMs)));
6346
+ /** Return the persisted user-message id for a turn/session, if one exists. */
6347
+ function getTurnUserMessageId(conversation, sessionId) {
6348
+ return getTurnUserMessage(conversation, sessionId)?.id;
6018
6349
  }
6019
- /**
6020
- * Save held input as one skipped Message, the Message that a Turn would save
6021
- * for it. The next Turn gets it as Turn input (`withHeldInput`). The append
6022
- * is idempotent by Message id, and the Message takes the id of the first
6023
- * input.
6024
- */
6025
- async function saveHeldInput(conversationId, messages) {
6026
- const first = messages[0];
6027
- const { text } = instructionForInputs(renderEventBatchInputs(messages, await eventInboxItemInputs(messages)));
6028
- const stored = toStoredConversationMessage({
6029
- id: first.inboundMessageId,
6030
- role: "user",
6031
- text: normalizeConversationText(text),
6032
- createdAtMs: first.createdAtMs,
6033
- ...first.input.authorIdentityId ? { authorIdentityId: first.input.authorIdentityId } : void 0,
6034
- meta: {
6035
- replied: false,
6036
- skippedReason: STOPPED_CONVERSATION_SKIP_REASON,
6037
- ...eventBatchMessageMeta(messages)
6038
- }
6039
- });
6040
- const { createdAtMs, ...data } = stored;
6041
- await getConversationEventStore().append(conversationId, [{
6042
- idempotencyKey: `message:${stored.messageId}`,
6043
- createdAtMs,
6044
- data: {
6045
- type: "message",
6046
- ...data
6047
- }
6048
- }]);
6350
+ /** Return the Slack timestamp for the user message that a resumed turn acts on. */
6351
+ function getTurnUserSlackMessageTs(message) {
6352
+ return parseSlackMessageTs(message?.meta?.slackTs);
6049
6353
  }
6050
- // src/chat/events/workspace.ts
6051
- const teamIdsByToken = /* @__PURE__ */ new Map();
6052
- /**
6053
- * Resolve the single-bot Slack team id for event-automation indexing, Event
6054
- * people mentions, and author trust.
6055
- *
6056
- * Watch matching does not use this. Event automations still key by
6057
- * destination team until that store is conversation-owned. System Events are
6058
- * not gated on Slack. Without a Slack bot, only a listed Event author is
6059
- * trusted.
6060
- */
6061
- async function resolveBotSlackTeamId() {
6062
- const token = getSlackBotToken();
6063
- if (!token) return void 0;
6064
- let pending = teamIdsByToken.get(token);
6065
- if (!pending) {
6066
- pending = getSlackClient().auth.test().then((result) => {
6067
- const teamId = result.team_id?.trim();
6068
- if (!teamId) throw new Error("Slack auth.test did not return a team id");
6069
- return teamId;
6070
- });
6071
- teamIdsByToken.set(token, pending);
6072
- pending.catch(() => teamIdsByToken.delete(token));
6073
- }
6074
- return await pending;
6354
+ /** Rebuild attachment context for a resumed turn from the persisted user message. */
6355
+ function getTurnUserReplyAttachmentContext(message) {
6356
+ const inboundAttachmentCount = message?.meta?.attachmentCount ?? 0;
6357
+ const imageAttachmentCount = message?.meta?.imageAttachmentCount ?? 0;
6358
+ const imagesHydrated = message?.meta?.imagesHydrated === true;
6359
+ return {
6360
+ ...inboundAttachmentCount > 0 ? { inboundAttachmentCount } : void 0,
6361
+ ...!imagesHydrated && imageAttachmentCount > 0 ? { omittedImageAttachmentCount: imageAttachmentCount } : void 0
6362
+ };
6075
6363
  }
6076
- // src/chat/identities/trust.ts
6077
- const emailSchema = z.string().trim().toLowerCase().pipe(z.email());
6364
+ // src/chat/conversations/web-mailbox.ts
6365
+ /** Parse web mailbox metadata written before Source and Actor were complete. */
6366
+ const legacyWebMailboxMetadataSchema = z.object({
6367
+ authorEmail: z.string().email(),
6368
+ authorFullName: z.string().min(1).optional(),
6369
+ authorUserId: z.string().min(1),
6370
+ authorUserName: z.string().min(1).optional(),
6371
+ kind: z.literal("api_turn"),
6372
+ messageId: z.string().min(1)
6373
+ }).strict();
6374
+ // src/chat/task-execution/mailbox-turn.ts
6078
6375
  /**
6079
- * Parse a value that must be an email, such as a sign-in or a verified email
6080
- * from a plugin. Return the normalized email and its domain, or undefined
6081
- * when the value is not a valid email.
6376
+ * Restore Turn input facts, with saved Message fallback for legacy cursors.
6377
+ *
6378
+ * TODO(dcramer): Remove Actor and Source reconstruction from the saved Message
6379
+ * after no deployed Turn cursor can omit either field.
6082
6380
  */
6083
- function parseEmail(value) {
6084
- const parsed = emailSchema.safeParse(value);
6085
- if (!parsed.success) return void 0;
6086
- const email = parsed.data;
6381
+ function turnInputFactsFromConversationMessage(message, args) {
6382
+ if (isParentMessageAuthor(message.author)) return args.savedActor && args.savedSource ? {
6383
+ actor: args.savedActor,
6384
+ author: message.author,
6385
+ source: args.savedSource
6386
+ } : void 0;
6387
+ if (isEventConversationMessage(message)) return {
6388
+ actor: args.savedActor ?? EVENT_SYSTEM_ACTOR,
6389
+ author: message.author ?? EVENT_MESSAGE_AUTHOR,
6390
+ source: args.savedSource ?? (args.location ? createWebSource(args.conversationId, args.visibility === "private" ? "private" : "public") : createLocalSource(args.conversationId))
6391
+ };
6392
+ const actor = args.savedActor ?? createActor(message.author, {
6393
+ platform: "web",
6394
+ userId: message.author?.userId
6395
+ });
6396
+ if (actor?.platform !== "web") return;
6087
6397
  return {
6088
- email,
6089
- domain: email.slice(email.lastIndexOf("@") + 1)
6398
+ actor,
6399
+ author: message.author ?? { userId: actor.userId },
6400
+ source: args.savedSource?.kind === "web" ? args.savedSource : createWebSource(args.conversationId, args.visibility === "private" ? "private" : "public")
6090
6401
  };
6091
6402
  }
6092
- /**
6093
- * Return whether a domain, such as the domain of a parsed email or Google's
6094
- * `hd` claim, is on the allowed domains. It only compares domains.
6095
- * `ifNoDomains` says what an empty list means: Slack authors allow every
6096
- * domain, and sign-ins allow none.
6097
- */
6098
- function isAllowedDomain(domain, options) {
6099
- if (options.allowedDomains.length === 0) return options.ifNoDomains === "allow";
6100
- const normalized = domain?.trim().toLowerCase();
6101
- return normalized ? options.allowedDomains.includes(normalized) : false;
6403
+ /** Normalize the selected mailbox Source with current Conversation visibility. */
6404
+ function sourceFromTurnInput(args) {
6405
+ if (args.source.kind === "web") return createWebSource(args.conversationId, args.visibility === "private" ? "private" : "public");
6406
+ return args.source;
6102
6407
  }
6103
- function isCoreIdentityProvider(provider) {
6104
- return provider === "junior" || isNativeIdentityProvider(provider);
6408
+ function hasEventActor(actors) {
6409
+ return Boolean(actors?.some((actor) => actor.platform === "system" && actor.name === EVENT_SYSTEM_ACTOR.name));
6105
6410
  }
6106
- function isSlackProfileDomainAllowed(profile) {
6107
- const email = profile.email?.trim();
6108
- const separator = email?.lastIndexOf("@") ?? -1;
6109
- const allowed = isAllowedDomain(separator > 0 ? email?.slice(separator + 1) : void 0, {
6110
- allowedDomains: getChatConfig().trust.allowedDomains,
6111
- ifNoDomains: "allow"
6112
- });
6113
- if (!allowed) logWarn("slack.allowed_domain.rejected", { "app.reason": email ? "domain_not_allowed" : "missing_email" });
6114
- return allowed;
6411
+ /** Return the active web Turn for one Conversation, if it has one. */
6412
+ async function getActiveConversationTurnId(conversationId) {
6413
+ const active = (await listTurnSummaries(conversationId)).filter((summary) => summary.surface === "api" && !summary.dispatchId && (summary.state === "paused" || summary.state === "running"));
6414
+ if (active.length > 1) throw new Error(`Conversation ${conversationId} has multiple active web turns`);
6415
+ const turnId = active[0]?.turnId;
6416
+ if (!turnId) return void 0;
6417
+ const record = await getTurnRecord(conversationId, turnId);
6418
+ return record && (record.source?.kind === "web" || !record.source && record.surface === "api") && !record.dispatchId && (record.state === "paused" || record.state === "running") ? turnId : void 0;
6115
6419
  }
6116
- const SLACK_TRUSTED_TTL_MS = 3e5;
6117
- const SLACK_UNTRUSTED_TTL_MS = 3e4;
6118
- async function readActiveMember(userId, teamId) {
6119
- return await createCache(getStateAdapter(), "core").getOrLoad(`slack:active-member:${teamId}:${userId}`, async () => {
6120
- const member = await lookupActiveSlackWorkspaceMember(userId, teamId);
6121
- const value = member ? {
6122
- email: member.email,
6123
- name: member.name,
6124
- real_name: member.real_name
6125
- } : null;
6126
- return {
6127
- value,
6128
- ttlMs: value ? SLACK_TRUSTED_TTL_MS : SLACK_UNTRUSTED_TTL_MS
6129
- };
6420
+ /** Return the web and event mailbox Turns that are paused or running. */
6421
+ async function listActiveMailboxTurns(conversationId) {
6422
+ const summaries = (await listTurnSummaries(conversationId)).filter(isOpenTurnSummary);
6423
+ const stored = await getStoredTurnFields(summaries);
6424
+ const candidates = summaries.filter((_summary, index) => {
6425
+ const fields = stored[index];
6426
+ return fields !== void 0 && (isActiveMailboxTurn(fields) || !fields.source && fields.surface !== "api");
6130
6427
  });
6428
+ return (await mapBounded(candidates, (summary) => getTurnRecord(conversationId, summary.turnId))).filter((record) => record !== void 0 && isActiveMailboxTurn(record));
6131
6429
  }
6132
6430
  /**
6133
- * Accept one stored Slack link only when it is a current human member of the
6134
- * workspace whose Slack email is on the allowed domains. With `email`, the
6135
- * Slack email must also still be that address, so a stale stored email does
6136
- * not match.
6431
+ * List the Source of each active mailbox Turn of several Conversations. It
6432
+ * reads the stored Turn cursors and not their Turn history, so unlike
6433
+ * `listActiveMailboxTurns` it keeps a Turn whose history was deleted.
6137
6434
  */
6138
- async function linkedMemberDecision(args) {
6139
- const userId = parseSlackUserId(args.linked?.slackUserId);
6140
- if (!args.linked || !userId) return {
6141
- trusted: false,
6142
- reason: "no_single_link"
6143
- };
6144
- const member = await readActiveMember(userId, args.teamId);
6145
- if (!member) return {
6146
- trusted: false,
6147
- reason: "inactive_member"
6148
- };
6149
- if (args.email && member.email?.trim().toLowerCase() !== args.email) return {
6150
- trusted: false,
6151
- reason: "email_changed"
6152
- };
6153
- if (!isSlackProfileDomainAllowed(member)) return {
6154
- trusted: false,
6155
- reason: "domain_not_allowed"
6156
- };
6157
- const fullName = member.real_name?.trim() || void 0;
6158
- const userName = member.name?.trim() || void 0;
6159
- return {
6160
- trusted: true,
6161
- actor: {
6162
- platform: "slack",
6163
- teamId: args.teamId,
6164
- userId,
6165
- ...fullName ? { fullName } : void 0,
6166
- ...userName ? { userName } : void 0
6167
- },
6168
- user: args.linked.user
6435
+ async function listActiveMailboxTurnSources(conversationIds) {
6436
+ const limit = pLimit(8);
6437
+ const summaries = (await Promise.all(conversationIds.map((conversationId) => limit(() => listTurnSummaries(conversationId))))).flatMap((list) => list.filter(isOpenTurnSummary));
6438
+ const stored = await getStoredTurnFields(summaries);
6439
+ const sources = new Map(conversationIds.map((conversationId) => [conversationId, []]));
6440
+ await Promise.all(summaries.map((summary, index) => limit(async () => {
6441
+ const fields = stored[index];
6442
+ const turn = fields && !fields.source && fields.surface !== "api" ? await getTurnRecord(summary.conversationId, summary.turnId) : fields;
6443
+ if (turn && isActiveMailboxTurn(turn)) sources.get(summary.conversationId)?.push(turn.source);
6444
+ })));
6445
+ return sources;
6446
+ }
6447
+ function isOpenTurnSummary(summary) {
6448
+ return !summary.dispatchId && (summary.state === "paused" || summary.state === "running");
6449
+ }
6450
+ function isActiveMailboxTurn(record) {
6451
+ return !record.dispatchId && (record.source?.kind === "web" || record.source?.kind === "event" || record.source?.kind === "parent_message" || !record.source && (record.surface === "api" || hasEventActor(record.actors))) && (record.state === "paused" || record.state === "running");
6452
+ }
6453
+ /** Return the active web or event mailbox Turn. */
6454
+ async function getActiveMailboxTurnId(conversationId) {
6455
+ const active = await listActiveMailboxTurns(conversationId);
6456
+ if (active.length > 1) throw new Error(`Conversation ${conversationId} has multiple active mailbox Turns`);
6457
+ return active[0]?.turnId;
6458
+ }
6459
+ /** Return the idle auth-paused web Turn for one Conversation. */
6460
+ async function getAuthPausedConversationTurnId(conversationId) {
6461
+ const turnId = await getActiveConversationTurnId(conversationId);
6462
+ if (!turnId) return void 0;
6463
+ const record = await getTurnRecord(conversationId, turnId);
6464
+ return record?.state === "paused" && record.resumeReason === "auth" ? turnId : void 0;
6465
+ }
6466
+ /** Return the transcript author of a web Actor's Message. */
6467
+ function webMessageAuthor(actor) {
6468
+ return {
6469
+ email: actor.email,
6470
+ ...actor.fullName ? { fullName: actor.fullName } : void 0,
6471
+ userId: actor.userId,
6472
+ ...actor.userName ? { userName: actor.userName } : void 0
6169
6473
  };
6170
6474
  }
6475
+ /** Read one web input batch as Turn input. A batch with no web input gives []. */
6476
+ function parseWebMessages(messages) {
6477
+ if (messages.length === 0) return [];
6478
+ const parsed = messages.map((message) => ({
6479
+ message,
6480
+ metadata: legacyWebMailboxMetadataSchema.safeParse(message.input.metadata)
6481
+ }));
6482
+ if (parsed.every((entry) => !entry.metadata.success)) return [];
6483
+ if (parsed.some((entry) => !entry.metadata.success)) throw new Error("A Turn cannot combine different kinds of input");
6484
+ return parsed.map((entry) => {
6485
+ if (!entry.metadata.success) throw new Error("User message has invalid metadata");
6486
+ const metadata = entry.metadata.data;
6487
+ const actor = {
6488
+ platform: "web",
6489
+ userId: metadata.authorUserId,
6490
+ email: metadata.authorEmail.trim().toLowerCase(),
6491
+ ...metadata.authorFullName ? { fullName: metadata.authorFullName } : void 0,
6492
+ ...metadata.authorUserName ? { userName: metadata.authorUserName } : void 0
6493
+ };
6494
+ return {
6495
+ actor,
6496
+ author: webMessageAuthor(actor),
6497
+ message: entry.message,
6498
+ source: createWebSource(entry.message.conversationId)
6499
+ };
6500
+ });
6501
+ }
6502
+ /** Extra debounce time added per additional event already batched. */
6503
+ const EVENT_WAIT_PER_EXTRA_MESSAGE_MS = 5e3;
6504
+ /** Upper bound on the debounce window regardless of batch size. */
6505
+ const EVENT_MAX_WAIT_MS = 6e4;
6171
6506
  /**
6172
- * A plugin account is trusted when the plugin lists it, or through its exact
6173
- * `subjectId`, linked by the OAuth account-linking flow to one Slack user who
6174
- * is a current human member on the allowed domains. Handles, emails, and
6175
- * display names never match.
6507
+ * Return how long an event batch must wait before its Turn starts.
6508
+ *
6509
+ * A resource-event burst (e.g. several check runs on one PR) should produce
6510
+ * one Turn instead of one per event. The window grows with batch size up to
6511
+ * EVENT_MAX_WAIT_MS, so later events in the same burst land in this batch.
6512
+ * Returns 0 when the batch can run now or does not start with an event.
6176
6513
  */
6177
- async function accountDecision(args) {
6178
- if (isCoreIdentityProvider(args.provider)) return {
6179
- trusted: false,
6180
- reason: "core_provider"
6181
- };
6182
- if (args.listed) return { trusted: true };
6183
- if (!args.subjectId) return {
6184
- trusted: false,
6185
- reason: "unknown_author"
6186
- };
6187
- const teamId = await resolveBotSlackTeamId();
6188
- if (!teamId) return {
6189
- trusted: false,
6190
- reason: "no_workspace"
6191
- };
6192
- return await linkedMemberDecision({
6193
- linked: await findLinkedSlackUser(getSqlExecutor(), {
6194
- provider: args.provider,
6195
- providerSubjectId: args.subjectId,
6196
- slackTeamId: teamId
6197
- }),
6198
- teamId
6514
+ function getEventBatchDelayMs(messages, nowMs = Date.now()) {
6515
+ const first = messages[0];
6516
+ if (!first || !isEventMailboxMetadata(first.input.metadata)) return 0;
6517
+ const waitMs = Math.min(EVENT_MAX_WAIT_MS, EVENT_WAIT_MS + EVENT_WAIT_PER_EXTRA_MESSAGE_MS * (messages.length - 1));
6518
+ return Math.max(0, first.receivedAtMs + waitMs - nowMs);
6519
+ }
6520
+ /** Read an event batch as Turn input, or return [] when it is not only events. */
6521
+ function parseEventMessages(messages) {
6522
+ if (messages.length === 0) return [];
6523
+ if (!messages.every((message) => message.source === "event" && isEventMailboxMetadata(message.input.metadata))) return [];
6524
+ return messages.map((message) => {
6525
+ if (!isEventMailboxMetadata(message.input.metadata)) throw new Error("Event has invalid metadata");
6526
+ return {
6527
+ actor: EVENT_SYSTEM_ACTOR,
6528
+ author: EVENT_MESSAGE_AUTHOR,
6529
+ message,
6530
+ source: createEventSource({
6531
+ eventKey: message.input.metadata.event.eventKey,
6532
+ eventType: message.input.metadata.event.eventType,
6533
+ identifier: message.input.metadata.event.identifier,
6534
+ namespace: message.input.metadata.event.namespace
6535
+ })
6536
+ };
6199
6537
  });
6200
6538
  }
6201
6539
  /**
6202
- * Return whether a Slack author may start a Turn. The caller must have
6203
- * checked that the author is a member of the workspace `teamId`. A member is
6204
- * trusted when their Slack email is on the allowed domains, or when the app
6205
- * lists them as a bot user. Without allowed domains, every member is.
6540
+ * Read a batch of parent messages as Turn input, or return [] when it is not
6541
+ * only parent messages. Each runs as the Actor of the parent's Turn, with its
6542
+ * grants, and is from the parent agent.
6206
6543
  */
6207
- async function isTrustedSlackAuthor(args) {
6208
- const userId = parseSlackUserId(args.user);
6209
- if (!userId || !args.teamId) return false;
6210
- const { allowedBotUserIds, allowedDomains } = getChatConfig().trust;
6211
- if (allowedBotUserIds.includes(userId) || allowedDomains.length === 0) return true;
6212
- return await createCache(args.state, "core").getOrLoad(`slack:allowed-domain:${args.teamId}:${userId}`, async () => {
6213
- const profile = await lookupSlackUserProfile(userId);
6214
- const trusted = profile.id === userId && isSlackProfileDomainAllowed(profile);
6544
+ function parseParentMessages(messages) {
6545
+ const parentMessages = messages.map(readParentMessage);
6546
+ if (parentMessages.length === 0 || parentMessages.some((parentMessage) => !parentMessage)) return [];
6547
+ return messages.map((message, index) => {
6548
+ const parentMessage = parentMessages[index];
6215
6549
  return {
6216
- value: trusted,
6217
- ttlMs: trusted ? SLACK_TRUSTED_TTL_MS : SLACK_UNTRUSTED_TTL_MS
6550
+ actor: parentMessage.actor,
6551
+ author: parentMessageAuthor(parentMessage.parentConversationId),
6552
+ ...parentMessage.credentialContext ? { credentialContext: parentMessage.credentialContext } : void 0,
6553
+ message,
6554
+ source: { kind: "parent_message" }
6218
6555
  };
6219
6556
  });
6220
6557
  }
6221
- async function verifiedEmailDecision(value) {
6222
- const email = parseEmail(value)?.email;
6223
- if (!email) return {
6224
- trusted: false,
6225
- reason: "invalid_email"
6558
+ /**
6559
+ * Select web, event, or parent work from new mailbox input or a saved Turn.
6560
+ * Saved Actor data identifies a resumed event Turn.
6561
+ */
6562
+ async function resolveMailboxTurnWork(context) {
6563
+ const batch = parseWebMessages(context.attempt.messages);
6564
+ if (batch.length > 0) return {
6565
+ kind: "mailbox",
6566
+ batch
6226
6567
  };
6227
- const teamId = await resolveBotSlackTeamId();
6228
- if (!teamId) return {
6229
- trusted: false,
6230
- reason: "no_workspace"
6568
+ const resourceBatch = parseEventMessages(context.attempt.messages);
6569
+ if (resourceBatch.length > 0) return {
6570
+ kind: "mailbox",
6571
+ batch: resourceBatch
6231
6572
  };
6232
- return await linkedMemberDecision({
6233
- email,
6234
- linked: await findSlackUserByPrimaryEmail(getSqlExecutor(), {
6235
- normalizedEmail: email,
6236
- slackTeamId: teamId
6237
- }),
6238
- teamId
6239
- });
6573
+ const parentBatch = parseParentMessages(context.attempt.messages);
6574
+ if (parentBatch.length > 0) return {
6575
+ kind: "mailbox",
6576
+ batch: parentBatch
6577
+ };
6578
+ if (context.attempt.messages.length > 0) return;
6579
+ const turnId = await getActiveMailboxTurnId(context.conversationId);
6580
+ return turnId ? {
6581
+ kind: "resume",
6582
+ turnId
6583
+ } : void 0;
6240
6584
  }
6585
+ // src/chat/task-execution/turn-cancel.ts
6241
6586
  /**
6242
- * Find the trusted person behind an account of a plugin's provider or behind
6243
- * a verified email, for work that runs as that person. A verified email is
6244
- * trusted when it is the primary email of the User of one Slack member on
6245
- * the allowed domains, and Slack still shows that email. Slack and storage
6246
- * errors propagate.
6587
+ * End a cancelled Turn: a stop that a worker saw, or a stop of a Turn that
6588
+ * waits for sign-in with no worker.
6247
6589
  */
6248
- async function findTrustedUser(author) {
6249
- let decision;
6250
- if ("subjectId" in author) decision = await accountDecision({
6251
- ...author,
6252
- listed: false
6590
+ /** Close a cancelled Turn, save it, and acknowledge its input. */
6591
+ async function completeCancelledConversationTurn(args) {
6592
+ const pendingAuthorization = args.conversation.processing.pendingAuth?.sessionId === args.turnId ? args.conversation.processing.pendingAuth : void 0;
6593
+ await abandonTurnRecord({
6594
+ conversationId: args.conversationId,
6595
+ turnId: args.turnId,
6596
+ errorMessage: "Turn cancelled"
6253
6597
  });
6254
- else decision = await verifiedEmailDecision(author.verifiedEmail);
6255
- if (!decision.trusted) return {
6256
- status: "untrusted",
6257
- reason: decision.reason
6258
- };
6259
- return decision.user ? {
6260
- status: "trusted",
6261
- user: decision.user
6262
- } : {
6263
- status: "untrusted",
6264
- reason: "no_single_link"
6265
- };
6598
+ clearPendingAuth(args.conversation, args.turnId);
6599
+ markConversationMessage(args.conversation, args.userMessageId, {
6600
+ replied: false,
6601
+ skippedReason: "turn cancelled"
6602
+ });
6603
+ markTurnClosed({
6604
+ conversation: args.conversation,
6605
+ nowMs: Date.now(),
6606
+ sessionId: args.turnId
6607
+ });
6608
+ if (pendingAuthorization) await deleteWebAuthorization({
6609
+ actorId: pendingAuthorization.actorId,
6610
+ conversationId: args.conversationId
6611
+ });
6612
+ await persistThreadStateById(args.conversationId, {
6613
+ conversation: args.conversation,
6614
+ sandboxRef: args.sandboxRef
6615
+ });
6616
+ await getTurnLifecycle().complete({
6617
+ conversationId: args.conversationId,
6618
+ createdAtMs: Date.now(),
6619
+ outcome: "cancelled",
6620
+ turnId: args.turnId
6621
+ });
6622
+ await args.acknowledge();
6266
6623
  }
6267
6624
  /**
6268
- * Resolve the author of an Event, the same way Slack ingress resolves a
6269
- * Slack author. It never throws: a failed check gives an untrusted author,
6270
- * so the Event still runs and the author's text stays context.
6625
+ * End the Turn of a stopped Conversation that waits for sign-in, so a later
6626
+ * sign-in cannot resume it. A web Turn waits as an auth-paused Turn record. A
6627
+ * Slack request waits as the thread's pending sign-in. Every stop path calls
6628
+ * this, because no worker holds a waiting Turn and the stop wake can go to
6629
+ * queued input first.
6271
6630
  */
6272
- async function resolveEventAuthor(event) {
6273
- const author = event.author;
6274
- if (!author) return { status: "system" };
6275
- const facts = {
6276
- ...author.bot ? { bot: true } : void 0,
6277
- handle: author.handle,
6278
- provider: event.namespace,
6279
- ...author.text?.trim() ? { text: author.text.trim() } : void 0
6280
- };
6281
- try {
6282
- const decision = await accountDecision({
6283
- listed: author.trusted === true,
6284
- provider: event.namespace,
6285
- ...author.subjectId ? { subjectId: author.subjectId } : void 0
6286
- });
6287
- if (!decision.trusted) return {
6288
- status: "untrusted",
6289
- reason: decision.reason,
6290
- ...facts
6291
- };
6292
- if (!decision.actor) return {
6293
- status: "trusted",
6294
- ...facts
6295
- };
6296
- return {
6297
- status: "trusted",
6298
- actor: decision.actor,
6299
- identityId: await resolveActorIdentityId(getSqlExecutor(), decision.actor),
6300
- ...facts
6301
- };
6302
- } catch (error) {
6303
- logException(error, "event.author.trust_check_failed", {
6304
- "app.event.event_type": event.eventType,
6305
- "app.event.namespace": event.namespace
6306
- });
6307
- return {
6308
- status: "untrusted",
6309
- reason: "check_failed",
6310
- ...facts
6311
- };
6312
- }
6313
- }
6314
- function safeId(value) {
6315
- return value.replace(/[^A-Za-z0-9._:@/#+[\]-]/g, "_");
6631
+ async function cancelSignInWait(conversationId) {
6632
+ const turnId = await getAuthPausedConversationTurnId(conversationId) ?? coerceThreadConversationState(await getPersistedThreadState(conversationId)).processing.pendingAuth?.sessionId;
6633
+ if (turnId) await cancelSignInPausedTurn({
6634
+ conversationId,
6635
+ turnId
6636
+ });
6316
6637
  }
6317
6638
  /**
6318
- * Return an Event author's own text and who wrote it. A linked person has
6319
- * the same author ID and name as on their Slack messages. Other authors
6320
- * show their handle on the provider.
6639
+ * Cancel a Turn that waits for sign-in outside its worker, with the same
6640
+ * cleanup as a stopped resume.
6321
6641
  */
6322
- function eventAuthorText(author) {
6323
- if (author.status === "system" || !author.text) return void 0;
6324
- const actor = author.status === "trusted" ? author.actor : void 0;
6325
- const name = actor?.fullName ?? actor?.userName ?? `${safeId(author.handle)} on ${safeId(author.provider)}${author.bot ? " (a bot)" : ""}`;
6326
- return {
6327
- text: author.text,
6328
- ...actor ? { authorId: actor.userId } : void 0,
6329
- authorName: name,
6330
- verified: author.status === "trusted"
6331
- };
6642
+ async function cancelSignInPausedTurn(args) {
6643
+ if (!await abandonTurnRecord({
6644
+ conversationId: args.conversationId,
6645
+ errorMessage: "Turn cancelled",
6646
+ onlyIfAuthPaused: true,
6647
+ turnId: args.turnId
6648
+ })) return;
6649
+ const conversation = coerceThreadConversationState(await getPersistedThreadState(args.conversationId));
6650
+ await hydrateConversationMessages({
6651
+ conversation,
6652
+ conversationId: args.conversationId
6653
+ });
6654
+ await completeCancelledConversationTurn({
6655
+ acknowledge: async () => {},
6656
+ conversation,
6657
+ conversationId: args.conversationId,
6658
+ turnId: args.turnId,
6659
+ userMessageId: getTurnUserMessage(conversation, args.turnId)?.id
6660
+ });
6332
6661
  }
6333
- // src/chat/events/notification.ts
6334
- const EVENT_WAIT_MS = 3e4;
6335
- const eventTaskFactsSchema = z.object({
6336
- about: z.string().optional(),
6337
- instructions: z.string().min(1),
6338
- guidance: z.string().optional(),
6339
- people: z.array(z.string()).optional(),
6340
- trustedSummary: z.string().optional(),
6341
- verifiedDetails: z.record(z.string(), z.unknown()).optional(),
6342
- externalText: z.string().optional(),
6343
- doneBy: z.object({
6344
- mention: z.string(),
6345
- handle: z.string().optional()
6346
- }).optional(),
6347
- /** The Event author's own text and who wrote it. It is context. */
6348
- authorText: z.object({
6349
- text: z.string().min(1),
6350
- authorId: z.string().optional(),
6351
- authorName: z.string().optional(),
6352
- verified: z.boolean()
6353
- }).optional()
6354
- });
6355
- /**
6356
- * Collect the task facts for one subscribed Event.
6357
- *
6358
- * Keep this short: facts the model cannot reconstruct, plus a one-line handling
6359
- * contract. Stable delivery rules live in runtime and docs, not this prompt.
6360
- */
6361
- function eventTaskFacts(subscription, event, people = [], doneBy, author = { status: "system" }) {
6362
- const guidance = [eventGuidance(getEventCatalog(), event.namespace, event.eventType), subscription.guidance?.[event.eventType]].filter((text) => Boolean(text?.trim())).join(" ");
6363
- const authorText = eventAuthorText(author);
6364
- return {
6365
- about: subscription.label,
6366
- instructions: subscription.intent,
6367
- ...guidance ? { guidance } : void 0,
6368
- ...people.length > 0 ? { people: [...people] } : void 0,
6369
- trustedSummary: event.trustedSummary,
6370
- ...event.data ? { verifiedDetails: event.data } : void 0,
6371
- ...authorText ? { authorText } : void 0,
6372
- ...event.untrustedText ? { externalText: event.untrustedText } : void 0,
6373
- ...doneBy ? { doneBy } : void 0
6374
- };
6662
+ // src/chat/conversations/session-stop.ts
6663
+ var session_stop_exports = /* @__PURE__ */ __exportAll({ resumeForPersonInput: () => resumeForPersonInput });
6664
+ /** Return when a Conversation stopped, or undefined when it is not stopped. */
6665
+ async function getConversationStoppedAtMs(conversationId) {
6666
+ const [row] = await getSqlExecutor().db().select({ stoppedAt: juniorConversations.stoppedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
6667
+ return row?.stoppedAt?.getTime();
6375
6668
  }
6376
6669
  /**
6377
- * Return the timer creator subject when every event in the batch carries a
6378
- * valid subject for its own Watch and the same user.
6670
+ * The hold rule: a Conversation holds automated input only while it is
6671
+ * stopped. Status and failure do not hold input.
6379
6672
  */
6380
- function timerWatchCredentialSubject(conversationId, messages) {
6381
- let shared;
6382
- for (const message of messages) {
6383
- const metadata = message.input.metadata;
6384
- if (!isEventMailboxMetadata(metadata)) return void 0;
6385
- const parsed = credentialSubjectSchema.safeParse(metadata.credentialSubject);
6386
- if (!parsed.success || !metadata.event.subscriptionId || !verifyTimerWatchCredentialSubject({
6387
- conversationId,
6388
- subject: parsed.data,
6389
- watchId: metadata.event.subscriptionId
6390
- }) || shared && shared.userId !== parsed.data.userId) return;
6391
- shared ??= parsed.data;
6392
- }
6393
- return shared;
6673
+ async function isHeld(conversationId) {
6674
+ return await getConversationStoppedAtMs(conversationId) !== void 0;
6394
6675
  }
6395
6676
  /**
6396
- * Read the saved Watch task facts from one Event mailbox entry. Entries
6397
- * without a Watch or saved facts, such as child agent results and input queued
6398
- * before facts were saved, return undefined and keep their own text.
6677
+ * Accept automated input, such as a Watch Event, a message from another
6678
+ * agent, or a child result. This is the only place that holds input. It
6679
+ * checks the hold under the mailbox lock, so it cannot race a stop: held
6680
+ * input is saved as a skipped Message and never reaches `pending`, and the
6681
+ * stop holds input that was appended before it.
6399
6682
  */
6400
- function readEventTaskFacts(message) {
6401
- const metadata = message.input.metadata;
6402
- if (!isEventMailboxMetadata(metadata)) return void 0;
6403
- const watchId = metadata.event.subscriptionId;
6404
- if (!watchId) return void 0;
6405
- const parsed = eventTaskFactsSchema.safeParse(metadata.task);
6406
- return parsed.success ? {
6407
- facts: parsed.data,
6408
- metadata,
6409
- watchId
6410
- } : void 0;
6683
+ async function enqueueAutomatedInput(args) {
6684
+ if (args.message.source !== "event") throw new Error("Automated input must be an Event");
6685
+ let held = false;
6686
+ const result = await appendAndEnqueueInboundMessage({
6687
+ ...args,
6688
+ renderText: async (inboundMessageIds, messageSenders) => {
6689
+ const text = args.renderText ? await args.renderText(inboundMessageIds, messageSenders) : args.message.input.text;
6690
+ if (text === void 0 || !await isHeld(args.message.conversationId)) return text;
6691
+ await saveHeldInput(args.message.conversationId, [{
6692
+ ...args.message,
6693
+ input: {
6694
+ ...args.message.input,
6695
+ text
6696
+ }
6697
+ }]);
6698
+ held = true;
6699
+ }
6700
+ });
6701
+ return held ? { status: "held" } : result;
6411
6702
  }
6412
6703
  /**
6413
- * Write the agent inputs for an Event batch, one prompt content part each.
6414
- *
6415
- * One Event keeps its own text. Several Watch Events become one `<task>`
6416
- * with one group per Watch, so shared instructions appear once. Entries
6417
- * without task facts, such as child agent results, keep their own text as
6418
- * their own inputs after the task. `rendered` replaces the input of an entry
6419
- * by inbound message id, such as a person change to an Inbox item.
6704
+ * Stop each Conversation of a tree until a person sends it input or its
6705
+ * parent gives it new work. Every stop path ends here: a person's stop,
6706
+ * `stopAgent`, and the automated-turn limit. It writes the stop in one
6707
+ * transaction with row locks, holds the automated input that already waits
6708
+ * in each mailbox, ends a Turn that waits for sign-in, and asks each running
6709
+ * Turn to stop. Each Turn it ends records one cancelled `turn_completed`.
6710
+ * Watches stay, and each Conversation that this stop starts reports
6711
+ * a `stopped` agent update to them. A Conversation that already stopped later
6712
+ * keeps that stop, so a retried or cascaded stop does not move it back.
6420
6713
  */
6421
- function renderEventBatchInputs(messages, rendered = /* @__PURE__ */ new Map()) {
6422
- const groups = /* @__PURE__ */ new Map();
6423
- const others = [];
6424
- for (const message of messages) {
6425
- const saved = readEventTaskFacts(message);
6426
- if (!saved) {
6427
- others.push(message);
6428
- continue;
6429
- }
6430
- const { facts, metadata, watchId } = saved;
6431
- let group = groups.get(watchId);
6432
- if (!group) {
6433
- group = {
6434
- about: facts.about,
6435
- instructions: facts.instructions,
6436
- people: [],
6437
- events: []
6438
- };
6439
- groups.set(watchId, group);
6440
- }
6441
- for (const person of facts.people ?? []) if (!group.people.includes(person)) group.people.push(person);
6442
- group.events.push({
6443
- eventType: metadata.event.eventType,
6444
- guidance: facts.guidance,
6445
- source: metadata.event.namespace,
6446
- trustedSummary: facts.trustedSummary,
6447
- verifiedDetails: facts.verifiedDetails,
6448
- authorText: facts.authorText,
6449
- externalText: facts.externalText,
6450
- doneBy: facts.doneBy
6714
+ async function stopConversationTree(conversationIds, options) {
6715
+ if (conversationIds.length === 0) return [];
6716
+ const stoppedAt = new Date(options.stoppedAtMs);
6717
+ const reported = await getSqlExecutor().transaction(async () => {
6718
+ const tx = getDb();
6719
+ const locked = await tx.select({
6720
+ conversationId: juniorConversations.conversationId,
6721
+ stoppedAt: juniorConversations.stoppedAt
6722
+ }).from(juniorConversations).where(inArray(juniorConversations.conversationId, [...conversationIds])).orderBy(asc(juniorConversations.conversationId)).for("update");
6723
+ await tx.update(juniorConversations).set({
6724
+ stoppedAt,
6725
+ detailVersion: nextDetailVersion
6726
+ }).where(and(inArray(juniorConversations.conversationId, [...conversationIds]), or(isNull(juniorConversations.stoppedAt), lt(juniorConversations.stoppedAt, stoppedAt))));
6727
+ return locked.flatMap((row) => !row.stoppedAt || row.stoppedAt.getTime() === stoppedAt.getTime() ? [row.conversationId] : []);
6728
+ });
6729
+ const queue = options.queue ?? getVercelConversationWorkQueue();
6730
+ await mapBounded(reported, (conversationId) => publishAgentUpdate(conversationId, {
6731
+ type: "stopped",
6732
+ stoppedAtMs: stoppedAt.getTime()
6733
+ }, {
6734
+ nowMs: stoppedAt.getTime(),
6735
+ queue,
6736
+ starter: false,
6737
+ state: options.state,
6738
+ update: async () => ({
6739
+ status: "stopped",
6740
+ text: "This conversation was stopped."
6741
+ })
6742
+ }));
6743
+ return await mapBounded(conversationIds, async (conversationId) => {
6744
+ const pending = await takePendingEventMessages({
6745
+ conversationId,
6746
+ conversationStore: options.conversationStore,
6747
+ nowMs: options.nowMs,
6748
+ state: options.state
6451
6749
  });
6452
- }
6453
- const ownInputs = (entries) => entries.map((message) => rendered.get(message.inboundMessageId) ?? {
6454
- kind: "runtime",
6455
- text: message.input.text.trim()
6456
- }).filter((input) => input.text);
6457
- if (messages.length - others.length < 2) return ownInputs(messages);
6458
- return [{
6459
- kind: "runtime",
6460
- text: renderTaskBatchInput({ groups: [...groups.values()] })
6461
- }, ...ownInputs(others)];
6462
- }
6463
- /** Return the conversation message entry for one Event input. */
6464
- function messageEvent(message) {
6465
- const metadata = message.input.metadata;
6466
- if (!isEventMailboxMetadata(metadata)) return [];
6467
- const label = readEventTaskFacts(message)?.facts.about;
6468
- return [{
6469
- eventType: metadata.event.eventType,
6470
- ...label ? { label } : void 0,
6471
- ...metadata.event.objectType ? { objectType: metadata.event.objectType } : void 0,
6472
- ...metadata.event.trustedSummary ? { trustedSummary: metadata.event.trustedSummary } : void 0
6473
- }];
6750
+ if (pending.length > 0) await saveHeldInput(conversationId, pending);
6751
+ await cancelSignInWait(conversationId);
6752
+ if (conversationId === options.finishedRunOf) return { status: "no_work" };
6753
+ return await stopConversationWork({
6754
+ conversationId,
6755
+ conversationStore: options.conversationStore,
6756
+ nowMs: options.nowMs,
6757
+ onStopSaved: options.onStopSaved,
6758
+ sentAtOrBeforeMs: options.sentAtOrBeforeMs,
6759
+ state: options.state
6760
+ });
6761
+ });
6474
6762
  }
6475
6763
  /**
6476
- * Return the saved Message fields for the Event inputs of one Turn.
6477
- *
6478
- * A person change to an Inbox item is not one of the Message's own Events:
6479
- * its record goes to `reviewItemChanges`, and the dashboard shows it as a
6480
- * change row. The Message's own Event is its first Watch Event, the
6481
- * kind the task message counts, or else its first other input, such as an
6482
- * agent result. `events` lists the Watch Events when several arrived. When
6483
- * changes share the Message with one own Event, `events` lists that Event, so
6484
- * a reader can tell it from a Message that only records changes.
6764
+ * End the stop of a Conversation and of the child agents below it, for new
6765
+ * work sent at `sentAtMs`: a person's input, or new work from its parent.
6766
+ * Nothing changes for work sent at or before the stop, so the input that a
6767
+ * stop drops does not undo it. Only Conversations that stopped no later than
6768
+ * this Conversation change, so a later stop of one child agent stays.
6485
6769
  */
6486
- function eventBatchMessageMeta(messages) {
6487
- const reviewItemChanges = messages.flatMap((message) => message.input.reviewItemChange ? [message.input.reviewItemChange] : []);
6488
- const own = messages.filter((message) => !message.input.reviewItemChange);
6489
- const watched = own.filter((message) => readEventTaskFacts(message));
6490
- const primary = watched[0] ?? own[0];
6491
- const metadata = (primary ?? messages[0])?.input.metadata;
6492
- if (!isEventMailboxMetadata(metadata)) return {};
6493
- const events = watched.length > 1 ? watched.flatMap(messageEvent) : reviewItemChanges.length && primary ? messageEvent(primary) : [];
6494
- return {
6495
- eventType: metadata.event.eventType,
6496
- eventNamespace: metadata.event.namespace,
6497
- eventIdentifier: metadata.event.identifier,
6498
- eventObjectType: metadata.event.objectType,
6499
- ...metadata.event.status ? { eventStatus: metadata.event.status } : void 0,
6500
- ...metadata.event.subscriptionId ? { eventWatchId: metadata.event.subscriptionId } : void 0,
6501
- ...metadata.event.trustedSummary ? { trustedSummary: metadata.event.trustedSummary } : void 0,
6502
- ...events.length ? { events } : void 0,
6503
- ...reviewItemChanges.length ? { reviewItemChanges } : void 0
6504
- };
6505
- }
6506
- function eventMessageAuthor(author) {
6507
- if (author?.status !== "trusted") return {
6508
- authorId: EVENT_AUTHOR_ID,
6509
- authorIdentityId: SYSTEM_IDENTITY_ID
6510
- };
6511
- if (author.identityId) return {
6512
- authorId: EVENT_AUTHOR_ID,
6513
- authorIdentityId: author.identityId
6514
- };
6515
- return { authorId: eventBotAuthorId(author.provider, author.handle) };
6516
- }
6517
- /** Build plain conversation mailbox input for one matched watch. */
6518
- function createEventInboundMessage(input) {
6519
- const metadata = {
6520
- kind: "event",
6521
- ...input.task ? { task: input.task } : void 0,
6522
- ...input.subscription.credentialSubject ? { credentialSubject: input.subscription.credentialSubject } : void 0,
6523
- event: {
6524
- eventKey: input.event.eventKey,
6525
- eventType: input.event.eventType,
6526
- namespace: input.event.namespace,
6527
- identifier: input.event.identifier,
6528
- subscriptionId: input.subscription.id,
6529
- trustedSummary: input.event.trustedSummary,
6530
- objectType: input.event.objectType,
6531
- ...input.status ? { status: input.status } : void 0
6532
- }
6533
- };
6534
- return {
6535
- conversationId: input.subscription.conversationId,
6536
- createdAtMs: input.event.occurredAtMs,
6537
- inboundMessageId: eventInboundMessageId(input.subscription.id, input.event.eventKey),
6538
- delivery: "defer",
6539
- source: "event",
6540
- receivedAtMs: input.receivedAtMs ?? Date.now(),
6541
- input: {
6542
- text: input.text,
6543
- ...eventMessageAuthor(input.author),
6544
- metadata
6545
- }
6546
- };
6770
+ async function resumeConversationTree(conversationId, sentAtMs) {
6771
+ const subtree = sql`(select ${conversationSubtreeColumns.conversationId} from ${conversationSubtree([conversationId])})`;
6772
+ await getSqlExecutor().transaction(async () => {
6773
+ const tx = getDb();
6774
+ const stoppedAt = (await tx.select({
6775
+ conversationId: juniorConversations.conversationId,
6776
+ stoppedAt: juniorConversations.stoppedAt
6777
+ }).from(juniorConversations).where(inArray(juniorConversations.conversationId, subtree)).orderBy(asc(juniorConversations.conversationId)).for("update")).find((row) => row.conversationId === conversationId)?.stoppedAt;
6778
+ if (!stoppedAt || sentAtMs <= stoppedAt.getTime()) return;
6779
+ await tx.update(juniorConversations).set({
6780
+ stoppedAt: null,
6781
+ detailVersion: nextDetailVersion
6782
+ }).where(and(inArray(juniorConversations.conversationId, subtree), lte(juniorConversations.stoppedAt, stoppedAt)));
6783
+ });
6547
6784
  }
6548
6785
  /**
6549
- * Deliver a Quiet Event as a Conversation note. It starts no Turn, so the
6550
- * automated-turn limit does not apply. The next Turn sees the note as
6551
- * runtime context. Core writes how to use it before the Event facts, so a
6552
- * long summary that the note limit cuts never loses that rule.
6786
+ * Resume a stopped Conversation when a person sent input after the stop.
6787
+ * Known gap: input sent before the stop but received after it still runs,
6788
+ * and the Conversation stays stopped.
6553
6789
  */
6554
- async function addQuietEventNote(args) {
6555
- const { event, subscription } = args;
6556
- await addConversationNote({
6557
- conversationId: subscription.conversationId,
6558
- createdAtMs: event.occurredAtMs,
6559
- key: `quiet_event:${subscription.id}:${event.eventKey}`,
6560
- text: `A Watch received this Event quietly: it started no Turn, and nobody was told. Use it as current state. Do not tell people about it unless they ask or your work needs it. ${subscription.label}, ${event.eventType}: ${event.trustedSummary}`
6561
- });
6790
+ async function resumeForPersonInput(conversationId, messages) {
6791
+ const personInput = messages.filter((message) => isPersonInput(message.source));
6792
+ if (personInput.length === 0) return;
6793
+ await resumeConversationTree(conversationId, Math.max(...personInput.map((message) => message.createdAtMs)));
6562
6794
  }
6563
6795
  /**
6564
- * Enqueue a event as normal conversation mailbox input.
6565
- *
6566
- * The watch only names the conversation. Destination stays on the conversation
6567
- * and is applied when the worker runs. A stopped Conversation holds the Event.
6796
+ * Save held input as one skipped Message, the Message that a Turn would save
6797
+ * for it. The next Turn gets it as Turn input (`withHeldInput`). The append
6798
+ * is idempotent by Message id, and the Message takes the id of the first
6799
+ * input.
6568
6800
  */
6569
- async function enqueueEventNotification(args) {
6570
- const task = eventTaskFacts(args.subscription, args.event, args.people, args.doneBy, args.author);
6571
- return await enqueueAutomatedInput({
6572
- message: createEventInboundMessage({
6573
- author: args.author,
6574
- event: args.event,
6575
- subscription: {
6576
- conversationId: args.subscription.conversationId,
6577
- credentialSubject: args.subscription.credentialSubject,
6578
- id: args.subscription.id
6579
- },
6580
- task,
6581
- text: renderTaskInput({
6582
- ...task,
6583
- event: args.event.eventType,
6584
- source: args.event.namespace
6585
- })
6586
- }),
6587
- queue: args.queue,
6588
- queueDelayMs: EVENT_WAIT_MS,
6589
- state: args.state
6801
+ async function saveHeldInput(conversationId, messages) {
6802
+ const first = messages[0];
6803
+ const { text } = instructionForInputs(renderEventBatchInputs(messages, await eventInboxItemInputs(messages)));
6804
+ const stored = toStoredConversationMessage({
6805
+ id: first.inboundMessageId,
6806
+ role: "user",
6807
+ text: normalizeConversationText(text),
6808
+ createdAtMs: first.createdAtMs,
6809
+ ...first.input.authorIdentityId ? { authorIdentityId: first.input.authorIdentityId } : void 0,
6810
+ meta: {
6811
+ replied: false,
6812
+ skippedReason: STOPPED_CONVERSATION_SKIP_REASON,
6813
+ ...eventBatchMessageMeta(messages)
6814
+ }
6590
6815
  });
6816
+ const { createdAtMs, ...data } = stored;
6817
+ await getConversationEventStore().append(conversationId, [{
6818
+ idempotencyKey: `message:${stored.messageId}`,
6819
+ createdAtMs,
6820
+ data: {
6821
+ type: "message",
6822
+ ...data
6823
+ }
6824
+ }]);
6591
6825
  }
6592
6826
  // src/chat/child-agents/fork-history.ts
6593
6827
  /** Instructions that a fork child reads with its first task. */
@@ -6917,225 +7151,411 @@ async function childAgentTurnOptions(args) {
6917
7151
  run: options?.reasoningLevel ? { reasoning: options.reasoningLevel } : {}
6918
7152
  };
6919
7153
  }
6920
- // src/chat/conversations/web-mailbox.ts
6921
- /** Parse web mailbox metadata written before Source and Actor were complete. */
6922
- const legacyWebMailboxMetadataSchema = z.object({
6923
- authorEmail: z.string().email(),
6924
- authorFullName: z.string().min(1).optional(),
6925
- authorUserId: z.string().min(1),
6926
- authorUserName: z.string().min(1).optional(),
6927
- kind: z.literal("api_turn"),
6928
- messageId: z.string().min(1)
6929
- }).strict();
6930
- // src/chat/task-execution/mailbox-turn.ts
6931
- /**
6932
- * Restore Turn input facts, with saved Message fallback for legacy cursors.
6933
- *
6934
- * TODO(dcramer): Remove Actor and Source reconstruction from the saved Message
6935
- * after no deployed Turn cursor can omit either field.
6936
- */
6937
- function turnInputFactsFromConversationMessage(message, args) {
6938
- if (isParentMessageAuthor(message.author)) return args.savedActor && args.savedSource ? {
6939
- actor: args.savedActor,
6940
- author: message.author,
6941
- source: args.savedSource
6942
- } : void 0;
6943
- if (isEventConversationMessage(message)) return {
6944
- actor: args.savedActor ?? EVENT_SYSTEM_ACTOR,
6945
- author: message.author ?? EVENT_MESSAGE_AUTHOR,
6946
- source: args.savedSource ?? (args.location ? createWebSource(args.conversationId, args.visibility === "private" ? "private" : "public") : createLocalSource(args.conversationId))
6947
- };
6948
- const actor = args.savedActor ?? createActor(message.author, {
6949
- platform: "web",
6950
- userId: message.author?.userId
6951
- });
6952
- if (actor?.platform !== "web") return;
6953
- return {
6954
- actor,
6955
- author: message.author ?? { userId: actor.userId },
6956
- source: args.savedSource?.kind === "web" ? args.savedSource : createWebSource(args.conversationId, args.visibility === "private" ? "private" : "public")
6957
- };
6958
- }
6959
- /** Normalize the selected mailbox Source with current Conversation visibility. */
6960
- function sourceFromTurnInput(args) {
6961
- if (args.source.kind === "web") return createWebSource(args.conversationId, args.visibility === "private" ? "private" : "public");
6962
- return args.source;
6963
- }
6964
- function hasEventActor(actors) {
6965
- return Boolean(actors?.some((actor) => actor.platform === "system" && actor.name === EVENT_SYSTEM_ACTOR.name));
6966
- }
6967
- /** Return the active web Turn for one Conversation, if it has one. */
6968
- async function getActiveConversationTurnId(conversationId) {
6969
- const active = (await listTurnSummaries(conversationId)).filter((summary) => summary.surface === "api" && !summary.dispatchId && (summary.state === "paused" || summary.state === "running"));
6970
- if (active.length > 1) throw new Error(`Conversation ${conversationId} has multiple active web turns`);
6971
- const turnId = active[0]?.turnId;
6972
- if (!turnId) return void 0;
6973
- const record = await getTurnRecord(conversationId, turnId);
6974
- return record && (record.source?.kind === "web" || !record.source && record.surface === "api") && !record.dispatchId && (record.state === "paused" || record.state === "running") ? turnId : void 0;
7154
+ // src/chat/child-agents/child-input.ts
7155
+ const parent = alias(juniorConversations, "parent");
7156
+ function childAgentInputKind(namespace, eventType, watchId) {
7157
+ if (namespace !== "junior" || !eventType) return;
7158
+ if (eventType === "agent.message") return "message";
7159
+ return isAgentUpdateEventType(eventType) && watchId === void 0 ? "reply" : void 0;
6975
7160
  }
6976
- /** Return the web and event mailbox Turns that are paused or running. */
6977
- async function listActiveMailboxTurns(conversationId) {
6978
- const summaries = (await listTurnSummaries(conversationId)).filter(isOpenTurnSummary);
6979
- const stored = await getStoredTurnFields(summaries);
6980
- const candidates = summaries.filter((_summary, index) => {
6981
- const fields = stored[index];
6982
- return fields !== void 0 && (isActiveMailboxTurn(fields) || !fields.source && fields.surface !== "api");
6983
- });
6984
- return (await mapBounded(candidates, (summary) => getTurnRecord(conversationId, summary.turnId))).filter((record) => record !== void 0 && isActiveMailboxTurn(record));
7161
+ /** Read the child that one reply or message Event names. */
7162
+ function childAgentInput(message) {
7163
+ const metadata = message.input.metadata;
7164
+ if (!isEventMailboxMetadata(metadata)) return;
7165
+ const kind = childAgentInputKind(metadata.event.namespace, metadata.event.eventType, metadata.event.subscriptionId);
7166
+ return kind ? {
7167
+ kind,
7168
+ senderId: metadata.event.identifier
7169
+ } : void 0;
6985
7170
  }
6986
7171
  /**
6987
- * List the Source of each active mailbox Turn of several Conversations. It
6988
- * reads the stored Turn cursors and not their Turn history, so unlike
6989
- * `listActiveMailboxTurns` it keeps a Turn whose history was deleted.
7172
+ * Whether one input is the `stopped` result that the stop of its sender
7173
+ * sends. Only a stop reports `stopped`, so the stored status tells this
7174
+ * result from the reply of a Turn.
6990
7175
  */
6991
- async function listActiveMailboxTurnSources(conversationIds) {
6992
- const limit = pLimit(8);
6993
- const summaries = (await Promise.all(conversationIds.map((conversationId) => limit(() => listTurnSummaries(conversationId))))).flatMap((list) => list.filter(isOpenTurnSummary));
6994
- const stored = await getStoredTurnFields(summaries);
6995
- const sources = new Map(conversationIds.map((conversationId) => [conversationId, []]));
6996
- await Promise.all(summaries.map((summary, index) => limit(async () => {
6997
- const fields = stored[index];
6998
- const turn = fields && !fields.source && fields.surface !== "api" ? await getTurnRecord(summary.conversationId, summary.turnId) : fields;
6999
- if (turn && isActiveMailboxTurn(turn)) sources.get(summary.conversationId)?.push(turn.source);
7000
- })));
7001
- return sources;
7176
+ function isStopResult(message) {
7177
+ const metadata = message.input.metadata;
7178
+ return isEventMailboxMetadata(metadata) && metadata.event.namespace === "junior" && isAgentUpdateEventType(metadata.event.eventType) && metadata.event.status === "stopped";
7002
7179
  }
7003
- function isOpenTurnSummary(summary) {
7004
- return !summary.dispatchId && (summary.state === "paused" || summary.state === "running");
7180
+ /**
7181
+ * Whether the saved Event fields of a Turn's input Message name a child
7182
+ * agent's reply or message. A new and a resumed Turn read the same fields.
7183
+ */
7184
+ function isChildAgentEvent(meta) {
7185
+ return Boolean(childAgentInputKind(meta?.eventNamespace, meta?.eventType, meta?.eventWatchId));
7005
7186
  }
7006
- function isActiveMailboxTurn(record) {
7007
- return !record.dispatchId && (record.source?.kind === "web" || record.source?.kind === "event" || record.source?.kind === "parent_message" || !record.source && (record.surface === "api" || hasEventActor(record.actors))) && (record.state === "paused" || record.state === "running");
7187
+ /**
7188
+ * Return the stored parent edge that a parent message claims, or undefined
7189
+ * when its author id is not that parent's, so it is dropped with no read.
7190
+ */
7191
+ function claimedParentEdge(message, parentMessage) {
7192
+ return hasParentMessageAuthor(message, parentMessage) ? parentEdgeKey(message.conversationId, parentMessage.parentConversationId) : void 0;
7008
7193
  }
7009
- /** Return the active web or event mailbox Turn. */
7010
- async function getActiveMailboxTurnId(conversationId) {
7011
- const active = await listActiveMailboxTurns(conversationId);
7012
- if (active.length > 1) throw new Error(`Conversation ${conversationId} has multiple active mailbox Turns`);
7013
- return active[0]?.turnId;
7194
+ function parentEdgeKey(childConversationId, parentConversationId) {
7195
+ return JSON.stringify([childConversationId, parentConversationId]);
7014
7196
  }
7015
- /** Return the idle auth-paused web Turn for one Conversation. */
7016
- async function getAuthPausedConversationTurnId(conversationId) {
7017
- const turnId = await getActiveConversationTurnId(conversationId);
7018
- if (!turnId) return void 0;
7019
- const record = await getTurnRecord(conversationId, turnId);
7020
- return record?.state === "paused" && record.resumeReason === "auth" ? turnId : void 0;
7197
+ /**
7198
+ * Return the child that sent a reply that a stop can skip. A message that a
7199
+ * child sent is still delivered, and so is the `stopped` result that a
7200
+ * person's stop sends.
7201
+ */
7202
+ function skippableReplySender(message) {
7203
+ if (childAgentInput(message)?.kind !== "reply" || isStopResult(message)) return;
7204
+ return readInboundMessageSender(message)?.conversationId;
7021
7205
  }
7022
- /** Return the transcript author of a web Actor's Message. */
7023
- function webMessageAuthor(actor) {
7206
+ /**
7207
+ * Read the stops that `isDroppedChildInput` needs for many inputs, with one
7208
+ * query for the receiving children and one for the reply senders.
7209
+ */
7210
+ async function readChildInputDropFacts(messages) {
7211
+ const childIds = /* @__PURE__ */ new Set();
7212
+ const parentIds = /* @__PURE__ */ new Set();
7213
+ const senderIds = /* @__PURE__ */ new Set();
7214
+ for (const message of messages) {
7215
+ const parentMessage = readParentMessage(message);
7216
+ if (parentMessage) {
7217
+ if (claimedParentEdge(message, parentMessage)) {
7218
+ childIds.add(message.conversationId);
7219
+ parentIds.add(parentMessage.parentConversationId);
7220
+ }
7221
+ continue;
7222
+ }
7223
+ const sender = skippableReplySender(message);
7224
+ if (sender) senderIds.add(sender);
7225
+ }
7226
+ const db = getSqlExecutor().db();
7227
+ const [children, senders] = await Promise.all([childIds.size > 0 ? db.select({
7228
+ conversationId: juniorConversations.conversationId,
7229
+ parentConversationId: parent.conversationId,
7230
+ stoppedAt: juniorConversations.stoppedAt
7231
+ }).from(juniorConversations).innerJoin(parent, eq(parent.conversationId, juniorConversations.parentConversationId)).where(and(inArray(juniorConversations.conversationId, [...childIds]), inArray(parent.conversationId, [...parentIds]))) : [], senderIds.size > 0 ? db.select({
7232
+ conversationId: juniorConversations.conversationId,
7233
+ stoppedAt: juniorConversations.stoppedAt
7234
+ }).from(juniorConversations).where(inArray(juniorConversations.conversationId, [...senderIds])) : []]);
7024
7235
  return {
7025
- email: actor.email,
7026
- ...actor.fullName ? { fullName: actor.fullName } : void 0,
7027
- userId: actor.userId,
7028
- ...actor.userName ? { userName: actor.userName } : void 0
7236
+ childStops: new Map(children.map((row) => [parentEdgeKey(row.conversationId, row.parentConversationId), row.stoppedAt])),
7237
+ senderStops: new Map(senders.flatMap((row) => row.stoppedAt ? [[row.conversationId, row.stoppedAt]] : []))
7029
7238
  };
7030
7239
  }
7031
- /** Read one web input batch as Turn input. A batch with no web input gives []. */
7032
- function parseWebMessages(messages) {
7033
- if (messages.length === 0) return [];
7034
- const parsed = messages.map((message) => ({
7035
- message,
7036
- metadata: legacyWebMailboxMetadataSchema.safeParse(message.input.metadata)
7037
- }));
7038
- if (parsed.every((entry) => !entry.metadata.success)) return [];
7039
- if (parsed.some((entry) => !entry.metadata.success)) throw new Error("A Turn cannot combine different kinds of input");
7040
- return parsed.map((entry) => {
7041
- if (!entry.metadata.success) throw new Error("User message has invalid metadata");
7042
- const metadata = entry.metadata.data;
7043
- const actor = {
7044
- platform: "web",
7045
- userId: metadata.authorUserId,
7046
- email: metadata.authorEmail.trim().toLowerCase(),
7047
- ...metadata.authorFullName ? { fullName: metadata.authorFullName } : void 0,
7048
- ...metadata.authorUserName ? { userName: metadata.authorUserName } : void 0
7240
+ /**
7241
+ * Return whether a Conversation drops one input, so it starts no work. Routing
7242
+ * and child status both read it, so they agree. `facts` are from
7243
+ * `readChildInputDropFacts`. A parent message is dropped when it is not from
7244
+ * the stored parent, or was sent before the child's stop. A stop drops unread
7245
+ * replies from the parent's mailbox. One sent before the stop can reach the
7246
+ * mailbox after that drop, so while the sending child is stopped, a reply that
7247
+ * it sent after the stop is dropped too. A stopped Conversation never reads
7248
+ * other automated input: `enqueueAutomatedInput` and the stop hold it first.
7249
+ */
7250
+ function isDroppedChildInput(message, facts) {
7251
+ if (isPersonInput(message.source)) return false;
7252
+ const parentMessage = readParentMessage(message);
7253
+ if (parentMessage) {
7254
+ const edge = claimedParentEdge(message, parentMessage);
7255
+ if (!edge || !facts.childStops.has(edge)) return true;
7256
+ const stoppedAtMs = facts.childStops.get(edge)?.getTime();
7257
+ return stoppedAtMs !== void 0 && message.receivedAtMs <= stoppedAtMs;
7258
+ }
7259
+ const sender = skippableReplySender(message);
7260
+ const senderStoppedAtMs = sender ? facts.senderStops.get(sender)?.getTime() : void 0;
7261
+ return senderStoppedAtMs !== void 0 && message.createdAtMs >= senderStoppedAtMs;
7262
+ }
7263
+ /**
7264
+ * Read the sender of one child Conversation from its parent edge and its
7265
+ * binding. A Conversation without a parent has none.
7266
+ */
7267
+ async function readChildConversationSender(childConversationId) {
7268
+ const [row] = await getSqlExecutor().db().select({
7269
+ agentName: juniorAgentBindings.name,
7270
+ parentConversationId: parent.conversationId,
7271
+ parentKind: parent.kind,
7272
+ title: juniorConversations.title
7273
+ }).from(juniorConversations).innerJoin(parent, eq(parent.conversationId, juniorConversations.parentConversationId)).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(eq(juniorConversations.conversationId, childConversationId));
7274
+ return row ? {
7275
+ ...row.agentName ? { agentName: row.agentName } : void 0,
7276
+ childConversationId,
7277
+ parentConversationId: row.parentConversationId,
7278
+ ...row.parentKind ? { parentKind: row.parentKind } : void 0,
7279
+ ...row.title ? { title: row.title } : void 0
7280
+ } : void 0;
7281
+ }
7282
+ /**
7283
+ * Read the sender of one reply or message, when it is a child of the
7284
+ * Conversation that received it. Input that names no child of this
7285
+ * Conversation has no sender, so `withSenderActors` runs it as the Event
7286
+ * system Actor and it gets no child's authority.
7287
+ */
7288
+ async function getChildAgentInputSender(message, input) {
7289
+ const sender = await readChildConversationSender(input.senderId);
7290
+ return sender?.parentConversationId === message.conversationId ? sender : void 0;
7291
+ }
7292
+ // src/chat/child-agents/sender-actors.ts
7293
+ const senderActorMetadataSchema = z.object({ actor: actorSchema });
7294
+ /**
7295
+ * Return the Inbound message author id for results sent by one Actor.
7296
+ * `selectContiguousTurnBatch` in `task-execution/worker.ts` puts messages in
7297
+ * one attempt only when their author ids and sources match. Mid-Turn drains
7298
+ * take only `interrupt` messages, and results are `defer`. So results never
7299
+ * share a Turn and its credentials with another Actor or with watch Events.
7300
+ * Keep this id unique per Actor if either rule changes. The id is opaque.
7301
+ * It keeps the value that earlier releases wrote, because a queued result
7302
+ * from before a deploy is checked against it.
7303
+ */
7304
+ function resultAuthorId(actor) {
7305
+ switch (actor.platform) {
7306
+ case "system": return `agent-invocation:system:${actor.name}`;
7307
+ case "slack": return `agent-invocation:slack:${actor.teamId}:${actor.userId}`;
7308
+ default: return `agent-invocation:${actor.platform}:${actor.userId}`;
7309
+ }
7310
+ }
7311
+ /** Read the Actor of the child Turn that a reply or message carries. */
7312
+ function senderActorFromMetadata(metadata) {
7313
+ const parsed = senderActorMetadataSchema.safeParse(metadata);
7314
+ return parsed.success ? parsed.data.actor : void 0;
7315
+ }
7316
+ /**
7317
+ * Run each child reply or message as the Actor of the child Turn that sent
7318
+ * it, which the input carries, so the parent never gets more authority than
7319
+ * that Turn. A parent message from the stored parent runs as the Actor of the
7320
+ * parent's Turn, with its grants and text. Input that a Turn with another
7321
+ * Actor sent, or that names no child of this Conversation, runs as the Event
7322
+ * system Actor. Input that `isDroppedChildInput` drops is left out. Returns
7323
+ * undefined when no input is left.
7324
+ */
7325
+ async function withSenderActors(work) {
7326
+ if (work.kind !== "mailbox") return work;
7327
+ const dropFacts = await readChildInputDropFacts(work.batch.map((entry) => entry.message));
7328
+ const kept = (await mapBounded(work.batch, async (entry) => {
7329
+ const parentMessage = readParentMessage(entry.message);
7330
+ if (parentMessage) {
7331
+ if (isDroppedChildInput(entry.message, dropFacts)) {
7332
+ logDroppedParentMessage(entry.message, parentMessage);
7333
+ return;
7334
+ }
7335
+ const text = await parentMessageText(entry.message, parentMessage);
7336
+ return {
7337
+ ...entry,
7338
+ actor: parentMessage.actor,
7339
+ requestText: entry.message.input.text.trim(),
7340
+ ...parentMessage.credentialContext ? { credentialContext: parentMessage.credentialContext } : void 0,
7341
+ message: {
7342
+ ...entry.message,
7343
+ input: {
7344
+ ...entry.message.input,
7345
+ text
7346
+ }
7347
+ }
7348
+ };
7349
+ }
7350
+ const input = childAgentInput(entry.message);
7351
+ if (!input) return entry;
7352
+ if (isDroppedChildInput(entry.message, dropFacts)) return;
7353
+ const sender = await getChildAgentInputSender(entry.message, input);
7354
+ const actor = senderActorFromMetadata(entry.message.input.metadata);
7355
+ if (!sender || !actor || entry.message.input.authorId !== resultAuthorId(actor)) return {
7356
+ ...entry,
7357
+ actor: EVENT_SYSTEM_ACTOR
7049
7358
  };
7050
7359
  return {
7051
- actor,
7052
- author: webMessageAuthor(actor),
7053
- message: entry.message,
7054
- source: createWebSource(entry.message.conversationId)
7360
+ ...entry,
7361
+ actor
7055
7362
  };
7056
- });
7363
+ })).filter((entry) => entry !== void 0);
7364
+ return kept.length > 0 ? {
7365
+ kind: "mailbox",
7366
+ batch: kept
7367
+ } : void 0;
7368
+ }
7369
+ // src/chat/child-agents/list.ts
7370
+ const childConversationKindSchema = z.enum(["thread", "task"]);
7371
+ /** Bound the child agents that one listing reads. */
7372
+ const CHILD_AGENT_LIST_LIMIT = 200;
7373
+ /**
7374
+ * List the direct child agents of one parent Conversation, with the newest
7375
+ * activity first. The state comes from each child's Turns and mailbox, not
7376
+ * from model output. Each child agent stores its agent config, so older
7377
+ * children of a parent, such as ones that a removed feature created, are not
7378
+ * listed. A child is `stopped` while stopped, `running` while a Turn or
7379
+ * mailbox input that answers its parent is open, `failed` when its stored
7380
+ * execution failed, such as when its worker gave up and no Turn ended, and
7381
+ * else `idle`.
7382
+ * `lastResult` is how its newest finished Turn that was not stopped ended:
7383
+ * the status that `readTurnUpdate` gives it, or `failed`.
7384
+ */
7385
+ async function listChildAgents(parentConversationId) {
7386
+ const rows = await getSqlExecutor().db().select({
7387
+ agentName: juniorAgentBindings.name,
7388
+ archivedAt: juniorConversations.archivedAt,
7389
+ conversationId: juniorConversations.conversationId,
7390
+ executionStatus: juniorConversations.executionStatus,
7391
+ executionUpdatedAt: juniorConversations.executionUpdatedAt,
7392
+ kind: juniorConversations.kind,
7393
+ lastTurnOutcome: conversationLastTurnOutcomeSql(juniorConversations),
7394
+ stoppedAt: juniorConversations.stoppedAt,
7395
+ title: juniorConversations.title,
7396
+ updatedAt: juniorConversations.updatedAt
7397
+ }).from(juniorConversations).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(and(eq(juniorConversations.parentConversationId, parentConversationId), isNotNull(juniorConversations.agentConfig))).orderBy(desc(sql`coalesce(${juniorConversations.executionUpdatedAt}, ${juniorConversations.updatedAt})`)).limit(CHILD_AGENT_LIST_LIMIT);
7398
+ const ids = rows.map((row) => row.conversationId);
7399
+ const [workStates, mailboxTurnSources] = await Promise.all([getConversationWorkStates(ids), listActiveMailboxTurnSources(ids)]);
7400
+ const pendingInput = (conversationId) => workStates.get(conversationId)?.execution.pendingMessages ?? [];
7401
+ const dropFacts = await readChildInputDropFacts(rows.flatMap((row) => row.stoppedAt ? [] : pendingInput(row.conversationId)));
7402
+ return rows.map((row) => {
7403
+ const kind = childConversationKindSchema.parse(row.kind);
7404
+ const stoppedAtMs = row.stoppedAt?.getTime();
7405
+ const running = stoppedAtMs === void 0 && runsOnConversationLoop(pendingInput(row.conversationId), mailboxTurnSources.get(row.conversationId) ?? [], dropFacts);
7406
+ const outcome = row.lastTurnOutcome;
7407
+ const lastResult = outcome === "failed" ? "failed" : outcome ? TURN_OUTCOME_STATUSES[outcome] : void 0;
7408
+ return {
7409
+ ...row.agentName ? { agentName: row.agentName } : void 0,
7410
+ ...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
7411
+ childConversationId: row.conversationId,
7412
+ kind,
7413
+ ...lastResult ? { lastResult } : void 0,
7414
+ status: stoppedAtMs !== void 0 ? "stopped" : running ? "running" : row.executionStatus === "failed" ? "failed" : "idle",
7415
+ ...row.title ? { title: row.title } : void 0,
7416
+ updatedAtMs: (row.executionUpdatedAt ?? row.updatedAt).getTime()
7417
+ };
7418
+ }).sort((left, right) => right.updatedAtMs - left.updatedAtMs);
7419
+ }
7420
+ /** List the ids of the child agents of one parent that have open work. */
7421
+ async function listOpenChildAgents(parentConversationId) {
7422
+ return (await listChildAgents(parentConversationId)).filter((child) => child.status === "running").map((child) => child.childConversationId);
7057
7423
  }
7058
- /** Extra debounce time added per additional event already batched. */
7059
- const EVENT_WAIT_PER_EXTRA_MESSAGE_MS = 5e3;
7060
- /** Upper bound on the debounce window regardless of batch size. */
7061
- const EVENT_MAX_WAIT_MS = 6e4;
7062
7424
  /**
7063
- * Return how long an event batch must wait before its Turn starts.
7064
- *
7065
- * A resource-event burst (e.g. several check runs on one PR) should produce
7066
- * one Turn instead of one per event. The window grows with batch size up to
7067
- * EVENT_MAX_WAIT_MS, so later events in the same burst land in this batch.
7068
- * Returns 0 when the batch can run now or does not start with an event.
7425
+ * Return whether a child has work that will answer its parent: `pending`
7426
+ * input that waits in the mailbox until its Turn commits it, such as a Watch
7427
+ * Event in its debounce window, or an open mailbox Turn. Every Turn of a
7428
+ * child answers its parent, whoever started it.
7069
7429
  */
7070
- function getEventBatchDelayMs(messages, nowMs = Date.now()) {
7071
- const first = messages[0];
7072
- if (!first || !isEventMailboxMetadata(first.input.metadata)) return 0;
7073
- const waitMs = Math.min(EVENT_MAX_WAIT_MS, EVENT_WAIT_MS + EVENT_WAIT_PER_EXTRA_MESSAGE_MS * (messages.length - 1));
7074
- return Math.max(0, first.receivedAtMs + waitMs - nowMs);
7430
+ function runsOnConversationLoop(pending, mailboxTurnSources, dropFacts) {
7431
+ return mailboxTurnSources.length > 0 || pending.some((message) => !isDroppedChildInput(message, dropFacts));
7075
7432
  }
7076
- /** Read an event batch as Turn input, or return [] when it is not only events. */
7077
- function parseEventMessages(messages) {
7078
- if (messages.length === 0) return [];
7079
- if (!messages.every((message) => message.source === "event" && isEventMailboxMetadata(message.input.metadata))) return [];
7080
- return messages.map((message) => {
7081
- if (!isEventMailboxMetadata(message.input.metadata)) throw new Error("Event has invalid metadata");
7082
- return {
7083
- actor: EVENT_SYSTEM_ACTOR,
7084
- author: EVENT_MESSAGE_AUTHOR,
7085
- message,
7086
- source: createEventSource({
7087
- eventKey: message.input.metadata.event.eventKey,
7088
- eventType: message.input.metadata.event.eventType,
7089
- identifier: message.input.metadata.event.identifier,
7090
- namespace: message.input.metadata.event.namespace
7091
- })
7092
- };
7093
- });
7433
+ /**
7434
+ * List the ids of a child's open Turns on the Conversation loop. A Turn keeps
7435
+ * its input in the mailbox until it commits it, so before its first
7436
+ * checkpoint its id comes from its first input. Attempt selection can take
7437
+ * any pending input first, so each one gives a candidate id.
7438
+ */
7439
+ async function listOpenLoopTurnIds(conversationId) {
7440
+ const [turns, work] = await Promise.all([listActiveMailboxTurns(conversationId), getConversationWorkState({ conversationId })]);
7441
+ return [...turns.map((turn) => turn.turnId), ...(work?.execution.pendingMessages ?? []).map((message) => buildDeterministicTurnId(message.inboundMessageId))];
7442
+ }
7443
+ async function listAnsweredLoopChildren(children, parentMessages) {
7444
+ if (children.length === 0 || parentMessages.length === 0) return [];
7445
+ return (await mapBounded(children, async ({ childConversationId }) => {
7446
+ const turnIds = await listOpenLoopTurnIds(childConversationId);
7447
+ return parentMessages.some(({ sender }) => sender.conversationId === childConversationId && turnIds.includes(sender.turnId)) ? childConversationId : void 0;
7448
+ })).filter((id) => id !== void 0);
7094
7449
  }
7095
7450
  /**
7096
- * Read a batch of parent messages as Turn input, or return [] when it is not
7097
- * only parent messages. Each runs as the Actor of the parent's Turn, with its
7098
- * grants, and is from the parent agent.
7451
+ * List the other child agents of one parent that still run and have not
7452
+ * answered. A running child whose open Turn's result is already among
7453
+ * `parentMessages`, the child replies and results that reached the parent's
7454
+ * mailbox, has answered, so it does not count.
7099
7455
  */
7100
- function parseParentMessages(messages) {
7101
- const parentMessages = messages.map(readParentMessage);
7102
- if (parentMessages.length === 0 || parentMessages.some((parentMessage) => !parentMessage)) return [];
7103
- return messages.map((message, index) => {
7104
- const parentMessage = parentMessages[index];
7105
- return {
7106
- actor: parentMessage.actor,
7107
- author: parentMessageAuthor(parentMessage.parentConversationId),
7108
- ...parentMessage.credentialContext ? { credentialContext: parentMessage.credentialContext } : void 0,
7109
- message,
7110
- source: { kind: "parent_message" }
7111
- };
7112
- });
7456
+ async function listUnreportedSiblingAgents(parentConversationId, childConversationId, parentMessages) {
7457
+ const running = (await listChildAgents(parentConversationId)).filter((child) => child.childConversationId !== childConversationId && child.status === "running");
7458
+ const answered = new Set(await listAnsweredLoopChildren(running, parentMessages));
7459
+ return running.filter((child) => !answered.has(child.childConversationId));
7113
7460
  }
7114
7461
  /**
7115
- * Select web, event, or parent work from new mailbox input or a saved Turn.
7116
- * Saved Actor data identifies a resumed event Turn.
7462
+ * List every child agent below one Conversation, at any depth. A parent owns
7463
+ * the work of its child agents and of their child agents. The list never has
7464
+ * the Conversation itself, its parent, or a sibling.
7117
7465
  */
7118
- async function resolveMailboxTurnWork(context) {
7119
- const batch = parseWebMessages(context.attempt.messages);
7120
- if (batch.length > 0) return {
7121
- kind: "mailbox",
7122
- batch
7123
- };
7124
- const resourceBatch = parseEventMessages(context.attempt.messages);
7125
- if (resourceBatch.length > 0) return {
7126
- kind: "mailbox",
7127
- batch: resourceBatch
7128
- };
7129
- const parentBatch = parseParentMessages(context.attempt.messages);
7130
- if (parentBatch.length > 0) return {
7131
- kind: "mailbox",
7132
- batch: parentBatch
7466
+ async function listDescendantAgents(conversationId) {
7467
+ return (await getSqlExecutor().db().select({
7468
+ conversationId: juniorConversations.conversationId,
7469
+ name: juniorAgentBindings.name
7470
+ }).from(juniorConversations).innerJoin(conversationSubtree([conversationId]), eq(conversationSubtreeColumns.conversationId, juniorConversations.conversationId)).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(ne(juniorConversations.conversationId, conversationId)).orderBy(juniorConversations.conversationId)).map((row) => ({
7471
+ conversationId: row.conversationId,
7472
+ ...row.name ? { name: row.name } : void 0
7473
+ }));
7474
+ }
7475
+ /**
7476
+ * List the agents that one Conversation can see. A root Conversation sees
7477
+ * only its child agents. A child agent also sees itself, its parent, and the
7478
+ * other child agents of its parent.
7479
+ */
7480
+ async function listAgentRelatives(input) {
7481
+ const { conversationId, parentConversationId } = input;
7482
+ const [children, family, parent] = await Promise.all([
7483
+ listChildAgents(conversationId),
7484
+ parentConversationId ? listChildAgents(parentConversationId) : [],
7485
+ parentConversationId ? getConversationStore().get({ conversationId: parentConversationId }) : void 0
7486
+ ]);
7487
+ const self = family.find((agent) => agent.childConversationId === conversationId);
7488
+ return {
7489
+ children,
7490
+ ...parent ? { parent: {
7491
+ conversationId: parent.conversationId,
7492
+ status: parent.execution.status,
7493
+ updatedAtMs: parent.execution.updatedAtMs ?? parent.updatedAtMs
7494
+ } } : void 0,
7495
+ ...self ? { self } : void 0,
7496
+ siblings: family.filter((agent) => agent.childConversationId !== conversationId)
7133
7497
  };
7134
- if (context.attempt.messages.length > 0) return;
7135
- const turnId = await getActiveMailboxTurnId(context.conversationId);
7136
- return turnId ? {
7137
- kind: "resume",
7138
- turnId
7139
- } : void 0;
7140
7498
  }
7141
- export { ConversationTurnBoundaryError as $, getAgentContextCompactionTriggerTokens as $n, CODE_MODE_CALL_STATUS_TEXT as $r, invalidateReadySnapshot as $t, createEventInboundMessage as A, recordSkillLoaded as An, TurnSliceLimitExceededError as Ar, instructionActorFor as At, resolveEventAuthor as B, estimateConversationMessagesTokens as Bn, buildTurnResult as Br, buildDeterministicAssistantMessageId as Bt, getChildAgentLockName as C, recordAgentsInstructionsUpdated as Cn, ConversationTurnLifecycleService as Cr, isHeldInputMessage as Ct, notInheritedByForkChild as D, recordAuthorizationRequested as Dn, GATED_TURN_LIMIT_WRAP_UP_MESSAGE as Dr, assemblePrompt as Dt, isInheritedForkHistory as E, recordAuthorizationCompleted as En, TURN_OUTCOME_STATUSES as Er, loadThreadContextTrimFloor as Et, eventAuthorText as F, persistConversationMessageWindow as Fn, buildTurnFailureResponse as Fr, readTaskInstructions as Ft, saveHeldInput as G, normalizeConversationText as Gn, createToolActionReview as Gr, getWorkspaceByName as Gt, enqueueAutomatedInput as H, isHumanConversationMessage as Hn, ToolActionRejectedError as Hr, createWorkspace as Ht, findTrustedUser as I, persistConversationMessages as In, captureTurnFailure as Ir, renderTaskInput as It, completeCancelledConversationTurn as J, trimConversationMessages as Jn, restoreToolActionRejections as Jr, listWorkspacesByRepository as Jt, session_stop_exports as K, recordDeliveredAssistantMessage as Kn, reviewToolActions as Kr, listWorkspaceNamesByRepository as Kt, isAllowedDomain as L, resolveConversationTitle as Ln, finalizeFailedTurnReplyWithEvent as Lr, readUserCustomization as Lt, eventBatchMessageMeta as M, recordToolExecutionStarted as Mn, buildTurnErrorResponse as Mr, loadPromptTurnContext as Mt, renderEventBatchInputs as N, appendConversationMessages as Nn, createTurnLimitGate as Nr, turnRequestText as Nt, EVENT_WAIT_MS as O, recordGuardianActionReviewed as On, TURN_LIMIT_WRAP_UP_MESSAGE as Or, buildPromptInput as Ot, timerWatchCredentialSubject as P, hydrateConversationMessages as Pn, isTurnExecutionLimitExceededError as Pr, withoutSavedSteeringMessages as Pt, getTurnUserSlackMessageTs as Q, getAgentBackgroundCompactionMarkTokens as Qn, CODEMODE_TOOL_NAME as Qr, workspaceRepoCheckoutPath as Qt, isTrustedSlackAuthor as R, settleConversationTitleWork as Rn, getAgentTurnDiagnosticsAttributes as Rr, saveUserCustomization as Rt, getAgentReplyMessageId as S, loadTurnProjection as Sn, recordTurnSummary as Sr, savedInputInstruction as St, getSpawnedChildConversationId as T, recordAuthenticationLinked as Tn, loadTurnStart as Tr, loadThreadContextCursor as Tt, getConversationStoppedAtMs as U, latestConversationMessageSeq as Un, ToolActionReviewLimitError as Ur, deleteWorkspace as Ut, resolveBotSlackTeamId as V, getConversationMessageSlackTs as Vn, isCutOffStopReason as Vr, buildDeterministicTurnId as Vt, resumeForPersonInput as W, markConversationMessage as Wn, ToolActionReviewUnavailableError as Wr, getWorkspace as Wt, getTurnUserMessageId as X, upsertConversationMessage as Xn, ROOT_LINE_BREAK as Xr, WorkspaceValidationError as Xt, getTurnUserMessage as Y, turnHasReply as Yn, RISK_LEVELS as Yr, updateWorkspace as Yt, getTurnUserReplyAttachmentContext as Z, calculateContextCompactionTargetTokens as Zn, USER_AUTHORIZATION_LEVELS as Zr, tryWorkspaceRepoCheckoutPath as Zt, parentMessageText as _, commitAcceptedReply as _n, abandonTurnRecord as _r, createWebAuthorization as _t, resolveMailboxTurnWork as a, projectConversationEvents as ai, AGENTS_REMOVAL_NOTICE as an, AuthPausePersistenceError as ar, isTurnInputCommitLostError as at, readAgentConfig as b, loadConversationProjection as bn, getTurnRecord as br, eventInboxItemInputs as bt, legacyWebMailboxMetadataSchema as c, configValueSchema as ci, findVisibleAgentsInstructions as cn, abandonReplacedPendingAuth as cr, markTurnCompleted as ct, childAgentTurnOptions as d, showsAgentsInstructions as dn, getConversationPendingAuth as dr, getLocationConfigurationService as dt, persistWithRetry as ei, loadSnapshotsForProfile as en, getAgentContextInputLimitTokens as er, CooperativeTurnYieldError as et, commitParentMessageFork as f, foldLeadingSystemMessages as fn, continuableMessages as fr, getPersistedSandboxState as ft, logDroppedParentMessage as g, writeAgentHistory as gn, saveTurnCheckpoint as gr, coerceThreadConversationState as gt, isParentMessageAuthor as h, withAgentRequest as hn, pauseLostWorkerTurn as hr, persistThreadStateById as ht, listActiveMailboxTurns as i, startOAuthFlow as ii, buildDeploymentSystemPrompt as in, authorizationId as ir, isCooperativeTurnYieldError as it, enqueueEventNotification as j, recordSubscribedReplyRoute as jn, TurnToolCallLimitExceededError as jr, instructionForInputs as jt, addQuietEventNote as k, recordMcpProviderConnected as kn, TurnBudgetExceededError as kr, buildSteeringPiMessage as kt, appendParentMessage as l, readRepositoryInstructions as ln, canReusePendingAuthLink as lr, markTurnFailed as lt, hasParentMessageAuthor as m, readAgentHistory as mn, lostWorkerBeforeFirstSave as mr, persistThreadRuntimeState as mt, getEventBatchDelayMs as n, formatProviderLabel as ni, setWorkspaceSnapshotBuild as nn, PluginCredentialFailureError as nr, TurnInputDeferredError as nt, sourceFromTurnInput as o, validateConfigKey as oi, AGENTS_REPLACEMENT_NOTICE as on, AuthorizationFlowDisabledError as or, isTurnInputDeferredError as ot, dropWaitingParentMessages as p, foldSystemMessages as pn, loadTurnCheckpoint as pr, getPersistedThreadState as pt, stopConversationTree as q, renderConversationMessageLine as qn, getToolActionRejectionMarker as qr, listWorkspaces as qt, listActiveMailboxTurnSources as r, parseOAuthStatePayload as ri, isExperimentalFeatureEnabled as rn, createPluginAuthOrchestration as rr, getConversationTurnBoundaryError as rt, turnInputFactsFromConversationMessage as s, validateConfigValue as si, buildAgentsInstructionsMessage as sn, AuthorizationPauseError as sr, markTurnClosed as st, getAuthPausedConversationTurnId as t, deliverOAuthAuthorization as ti, setWorkspaceSnapshot as tn, createPluginEgress as tr, TurnInputCommitLostError as tt, buildParentMessage as u, renderAgentsInstructions as un, clearPendingAuth as ur, startActiveTurn as ut, readLastParentMessageAtMs as v, commitMessages as vn, completeTurnRecord as vr, deleteWebAuthorization as vt, getPersonStopTurnId as w, recordAttachmentsDelivered as wn, getTurnLifecycle as wr, withHeldInput as wt, getAgentMessageId as x, loadConversationSkillNames as xn, listTurnSummaries as xr, loadInboxItemInput as xt, agentConfigSchema as y, loadConnectedMcpProviders as yn, failTurnRecord as yr, getWebAuthorization as yt, parseEmail as z, conversationAuthorDisplayName as zn, requireTurnFailureEventId as zr, addConversationNote as zt };
7499
+ // src/chat/child-agents/markers.ts
7500
+ const SUBAGENT_KIND = "agent";
7501
+ const SUBAGENT_STARTED_KEY_PREFIX = "subagent_started:";
7502
+ const SUBAGENT_ENDED_KEY_PREFIX = "subagent_ended:";
7503
+ /**
7504
+ * Record in the parent Conversation that a child agent got one task or
7505
+ * message. Write it before the input reaches the child's mailbox, so the
7506
+ * child cannot end first.
7507
+ */
7508
+ async function recordSubagentStartedMarker(start) {
7509
+ await getConversationEventStore().append(start.parentConversationId, [{
7510
+ idempotencyKey: `${SUBAGENT_STARTED_KEY_PREFIX}${start.markerId}`,
7511
+ data: {
7512
+ type: "subagent_started",
7513
+ subagentInvocationId: start.markerId,
7514
+ subagentKind: SUBAGENT_KIND,
7515
+ childConversationId: start.childConversationId,
7516
+ ...start.agentName ? { agentName: start.agentName } : void 0,
7517
+ parentToolCallId: start.parentToolCallId,
7518
+ task: start.input,
7519
+ ...start.title ? { title: start.title } : void 0,
7520
+ ...start.reasoningLevel ? { reasoningLevel: start.reasoningLevel } : void 0
7521
+ },
7522
+ createdAtMs: start.createdAtMs
7523
+ }]);
7524
+ }
7525
+ /**
7526
+ * Record in the parent Conversation how the work of a child agent ended.
7527
+ * Each parent message has its own `subagent_started` marker, named by the
7528
+ * message id, and each one that the child already took ends with `outcome`.
7529
+ * A parent message that still waits in the child's mailbox stays open,
7530
+ * because later work reads it, unless `includeWaiting` is set, as for a stop
7531
+ * that skips it. Write it before the child's result reaches the parent.
7532
+ */
7533
+ async function recordChildAgentEnded(childConversationId, outcome, options = {}) {
7534
+ if (!await readAgentConfig(childConversationId)) return;
7535
+ const work = await getConversationWorkState({
7536
+ conversationId: childConversationId,
7537
+ state: options.state
7538
+ });
7539
+ const running = new Set(work?.runningInboundMessageIds);
7540
+ const waiting = new Set(options.includeWaiting ? [] : (work?.messages ?? []).map((message) => message.inboundMessageId).filter((id) => !running.has(id)));
7541
+ const taken = (work?.execution.inboundMessageIds ?? []).filter((id) => !waiting.has(id));
7542
+ if (taken.length === 0) return;
7543
+ const sender = await readChildConversationSender(childConversationId);
7544
+ if (!sender) return;
7545
+ const keys = await getSqlExecutor().db().select({ idempotencyKey: juniorConversationEvents.idempotencyKey }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, sender.parentConversationId), inArray(juniorConversationEvents.idempotencyKey, taken.flatMap((id) => [`${SUBAGENT_STARTED_KEY_PREFIX}${id}`, `${SUBAGENT_ENDED_KEY_PREFIX}${id}`]))));
7546
+ const found = new Set(keys.map((row) => row.idempotencyKey));
7547
+ const open = taken.filter((id) => found.has(`${SUBAGENT_STARTED_KEY_PREFIX}${id}`) && !found.has(`${SUBAGENT_ENDED_KEY_PREFIX}${id}`));
7548
+ if (open.length > 0) await appendSubagentEnded(sender.parentConversationId, open, outcome, options.nowMs ?? Date.now());
7549
+ }
7550
+ async function appendSubagentEnded(parentConversationId, markerIds, outcome, createdAtMs) {
7551
+ await getConversationEventStore().append(parentConversationId, markerIds.map((id) => ({
7552
+ idempotencyKey: `${SUBAGENT_ENDED_KEY_PREFIX}${id}`,
7553
+ data: {
7554
+ type: "subagent_ended",
7555
+ subagentInvocationId: id,
7556
+ outcome
7557
+ },
7558
+ createdAtMs
7559
+ })));
7560
+ }
7561
+ export { createWebAuthorization as $, normalizeConversationText as $n, reviewToolActions as $r, getWorkspaceByName as $t, getConversationStoppedAtMs as A, loadTurnProjection as An, recordTurnSummary as Ar, withoutSavedSteeringMessages as At, sourceFromTurnInput as B, recordToolExecutionStarted as Bn, createTurnLimitGate as Br, getConversationTurnBoundaryError as Bt, getAgentReplyMessageId as C, withAgentRequest as Cn, pauseLostWorkerTurn as Cr, assemblePrompt as Ct, isInheritedForkHistory as D, loadConnectedMcpProviders as Dn, failTurnRecord as Dr, instructionForInputs as Dt, getSpawnedChildConversationId as E, commitMessages as En, completeTurnRecord as Er, instructionActorFor as Et, completeCancelledConversationTurn as F, recordAuthorizationRequested as Fn, TURN_LIMIT_WRAP_UP_MESSAGE as Fr, addConversationNote as Ft, getTurnUserReplyAttachmentContext as G, resolveConversationTitle as Gn, getAgentTurnDiagnosticsAttributes as Gr, markTurnCompleted as Gt, legacyWebMailboxMetadataSchema as H, hydrateConversationMessages as Hn, buildTurnFailureResponse as Hr, isTurnInputCommitLostError as Ht, getAuthPausedConversationTurnId as I, recordGuardianActionReviewed as In, TurnBudgetExceededError as Ir, ConversationTurnBoundaryError as It, getPersistedSandboxState as J, estimateConversationMessagesTokens as Jn, isCutOffStopReason as Jr, buildDeterministicAssistantMessageId as Jt, getTurnUserSlackMessageTs as K, settleConversationTitleWork as Kn, requireTurnFailureEventId as Kr, markTurnFailed as Kt, getEventBatchDelayMs as L, recordMcpProviderConnected as Ln, TurnSliceLimitExceededError as Lr, CooperativeTurnYieldError as Lt, saveHeldInput as M, recordAttachmentsDelivered as Mn, getTurnLifecycle as Mr, renderTaskInput as Mt, session_stop_exports as N, recordAuthenticationLinked as Nn, loadTurnStart as Nr, readUserCustomization as Nt, notInheritedByForkChild as O, loadConversationProjection as On, getTurnRecord as Or, loadPromptTurnContext as Ot, stopConversationTree as P, recordAuthorizationCompleted as Pn, GATED_TURN_LIMIT_WRAP_UP_MESSAGE as Pr, saveUserCustomization as Pt, coerceThreadConversationState as Q, markConversationMessage as Qn, createToolActionReview as Qr, getWorkspace as Qt, listActiveMailboxTurns as R, recordSkillLoaded as Rn, TurnToolCallLimitExceededError as Rr, TurnInputCommitLostError as Rt, getAgentMessageId as S, readAgentHistory as Sn, lostWorkerBeforeFirstSave as Sr, loadThreadContextTrimFloor as St, getPersonStopTurnId as T, commitAcceptedReply as Tn, abandonTurnRecord as Tr, buildSteeringPiMessage as Tt, getTurnUserMessage as U, persistConversationMessageWindow as Un, captureTurnFailure as Ur, isTurnInputDeferredError as Ut, turnInputFactsFromConversationMessage as V, appendConversationMessages as Vn, isTurnExecutionLimitExceededError as Vr, isCooperativeTurnYieldError as Vt, getTurnUserMessageId as W, persistConversationMessages as Wn, finalizeFailedTurnReplyWithEvent as Wr, markTurnClosed as Wt, persistThreadRuntimeState as X, isHumanConversationMessage as Xn, ToolActionReviewLimitError as Xr, createWorkspace as Xt, getPersistedThreadState as Y, getConversationMessageSlackTs as Yn, ToolActionRejectedError as Yr, buildDeterministicTurnId as Yt, persistThreadStateById as Z, latestConversationMessageSeq as Zn, ToolActionReviewUnavailableError as Zr, deleteWorkspace as Zt, dropWaitingParentMessages as _, readRepositoryInstructions as _n, canReusePendingAuthLink as _r, resolveEventAuthor as _t, listDescendantAgents as a, CODEMODE_TOOL_NAME as ai, tryWorkspaceRepoCheckoutPath as an, calculateContextCompactionTargetTokens as ar, EVENT_WAIT_MS as at, agentConfigSchema as b, foldLeadingSystemMessages as bn, continuableMessages as br, withHeldInput as bt, resultAuthorId as c, deliverOAuthAuthorization as ci, loadSnapshotsForProfile as cn, getAgentContextInputLimitTokens as cr, enqueueEventNotification as ct, isStopResult as d, startOAuthFlow as di, isExperimentalFeatureEnabled as dn, createPluginAuthOrchestration as dr, timerWatchCredentialSubject as dt, getToolActionRejectionMarker as ei, listWorkspaceNamesByRepository as en, recordDeliveredAssistantMessage as er, deleteWebAuthorization as et, readChildConversationSender as f, projectConversationEvents as fi, buildDeploymentSystemPrompt as fn, authorizationId as fr, eventAuthorText as ft, commitParentMessageFork as g, findVisibleAgentsInstructions as gn, abandonReplacedPendingAuth as gr, parseEmail as gt, childAgentTurnOptions as h, configValueSchema as hi, buildAgentsInstructionsMessage as hn, AuthorizationPauseError as hr, isTrustedSlackAuthor as ht, listChildAgents as i, USER_AUTHORIZATION_LEVELS as ii, WorkspaceValidationError as in, upsertConversationMessage as ir, savedInputInstruction as it, resumeForPersonInput as j, recordAgentsInstructionsUpdated as jn, ConversationTurnLifecycleService as jr, readTaskInstructions as jt, enqueueAutomatedInput as k, loadConversationSkillNames as kn, listTurnSummaries as kr, turnRequestText as kt, withSenderActors as l, formatProviderLabel as li, setWorkspaceSnapshot as ln, createPluginEgress as lr, eventBatchMessageMeta as lt, buildParentMessage as m, validateConfigValue as mi, AGENTS_REPLACEMENT_NOTICE as mn, AuthorizationFlowDisabledError as mr, isAllowedDomain as mt, recordSubagentStartedMarker as n, RISK_LEVELS as ni, listWorkspacesByRepository as nn, trimConversationMessages as nr, eventInboxItemInputs as nt, listOpenChildAgents as o, CODE_MODE_CALL_STATUS_TEXT as oi, workspaceRepoCheckoutPath as on, getAgentBackgroundCompactionMarkTokens as or, addQuietEventNote as ot, appendParentMessage as p, validateConfigKey as pi, AGENTS_REMOVAL_NOTICE as pn, AuthPausePersistenceError as pr, findTrustedUser as pt, getLocationConfigurationService as q, conversationAuthorDisplayName as qn, buildTurnResult as qr, startActiveTurn as qt, listAgentRelatives as r, ROOT_LINE_BREAK as ri, updateWorkspace as rn, turnHasReply as rr, loadInboxItemInput as rt, listUnreportedSiblingAgents as s, persistWithRetry as si, invalidateReadySnapshot as sn, getAgentContextCompactionTriggerTokens as sr, createEventInboundMessage as st, recordChildAgentEnded as t, restoreToolActionRejections as ti, listWorkspaces as tn, renderConversationMessageLine as tr, getWebAuthorization as tt, isChildAgentEvent as u, parseOAuthStatePayload as ui, setWorkspaceSnapshotBuild as un, PluginCredentialFailureError as ur, renderEventBatchInputs as ut, isParentMessageAuthor as v, renderAgentsInstructions as vn, clearPendingAuth as vr, resolveBotSlackTeamId as vt, getChildAgentLockName as w, writeAgentHistory as wn, saveTurnCheckpoint as wr, buildPromptInput as wt, readAgentConfig as x, foldSystemMessages as xn, loadTurnCheckpoint as xr, loadThreadContextCursor as xt, readLastParentMessageAtMs as y, showsAgentsInstructions as yn, getConversationPendingAuth as yr, isHeldInputMessage as yt, resolveMailboxTurnWork as z, recordSubscribedReplyRoute as zn, buildTurnErrorResponse as zr, TurnInputDeferredError as zt };