@sentry/junior 0.318.0 → 0.320.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/dist/{context-BKF_5zzI.js → adapter-DlLLoJKj.js} +537 -537
  2. package/dist/{admin-UOHix_5P.js → admin-BzRXDVfh.js} +1 -1
  3. package/dist/{agent-runner-DeYymwh2.js → agent-DxZ7nHfD.js} +19866 -6720
  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-CO4FU5Gg.js} +4 -5
  6. package/dist/api/schema.d.ts +45 -23
  7. package/dist/api/schema.js +4 -4
  8. package/dist/api.js +79 -84
  9. package/dist/{app-DKAOuaoC.d.ts → app-CHCFIIDu.d.ts} +5 -4
  10. package/dist/app.d.ts +2 -2
  11. package/dist/app.js +119 -194
  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-BghWqlXx.js} +1 -1
  14. package/dist/{chat-core-engine-D3Wd7f5n.js → chat-core-engine-BgfSLrDu.js} +31 -14
  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-DBlQP4PC.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-qoh95v90.js} +1 -1
  27. package/dist/{create-Btl1y1rq.js → create-jZSaDrCR.js} +115 -5
  28. package/dist/{credential-sync-DTarZ63K.js → credential-sync-Bj9-UlNE.js} +15 -18
  29. package/dist/{db-of6e3sGt.js → db-BacvswT0.js} +4602 -727
  30. package/dist/{deployment-C0qXa0FD.js → deployment-BoJkRPDt.js} +3 -3
  31. package/dist/{engine-context-C_QL_bMQ.js → engine-context-Bi3Ync5t.js} +521 -150
  32. package/dist/{html-9_pS9SjY.js → html-DW0pw5Pr.js} +6 -8
  33. package/dist/instrumentation.js +7 -23
  34. package/dist/list-Dz3CdP3g.js +5016 -0
  35. package/dist/{logging-BnOG0qz2.js → logging-DsTnMqyi.js} +8 -33
  36. package/dist/{mailbox-turn-Byrry9o1.js → markers-C33gNYNE.js} +1705 -1284
  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-C-pEhAQK.js} +2 -2
  40. package/dist/{oauth-relay-BvHFH0fV.js → oauth-relay-DIXdH-io.js} +1 -1
  41. package/dist/{plugins-fBrz8PCV.d.ts → plugins-DhGXZjlu.d.ts} +1 -0
  42. package/dist/{profile-iHw1uu32.js → profile-v9vA3RvH.js} +16 -18
  43. package/dist/{prompt-DEkStuxG.js → prompt-C5CW2wKO.js} +1 -1
  44. package/dist/{reports-C1d9azyV.js → reports-eBgrhPXS.js} +2 -2
  45. package/dist/{resolve-DC6zBuDV.js → resolve-HVXmbeCr.js} +5 -5
  46. package/dist/{result-DxewDuXb.js → result-BPNzgeTl.js} +20 -9
  47. package/dist/{runner-99YxVN_r.js → runner-aNSDTST6.js} +7 -8
  48. package/dist/{sandbox-egress-signals-CgoX5CTI.js → sandbox-egress-signals-nzp9Ykf7.js} +1 -1
  49. package/dist/{schema-BTojNBr5.js → schema-BlTO5M1d.js} +16 -8
  50. package/dist/{service-account-YDCPSByj.js → service-account-DWIf1t6p.js} +4 -5
  51. package/dist/{skills-CleC0Hze.js → skills-50izzzdK.js} +9 -9
  52. package/dist/{slack-conversation-unfurl-BNQLC12R.js → slack-conversation-unfurl-C6jXhVYg.js} +7 -7
  53. package/dist/storage-BtCxXiNt.js +273 -0
  54. package/dist/{system-prompt-table-Ci6Ck4gk.js → system-prompt-table-CIR1B44Z.js} +27 -85
  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-DOVo9sdU.js} +1 -1
  59. package/dist/{validation-BiUmWPhy.js → validation-CK0vuEHB.js} +4 -4
  60. package/dist/{version-VEXiEcZu.js → version-BuLVNlxB.js} +1 -1
  61. package/dist/version.js +1 -1
  62. package/dist/{worker-ChWYQdhm.js → worker-C82kHU1R.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/migrations/20261127150242_drop_space_members/migration.sql +9 -0
  74. package/migrations/20261127150242_drop_space_members/snapshot.json +53 -0
  75. package/package.json +9 -7
  76. package/dist/auth-pause-state-f9hJM_zO.js +0 -113
  77. package/dist/catalog-runtime-BfdAnztW.js +0 -6
  78. package/dist/child-message-peFWLcCZ.js +0 -15
  79. package/dist/conversation-turn-Bru4w_FD.js +0 -1250
  80. package/dist/job-runner-B2XEvpif.js +0 -1505
  81. package/dist/lineage-nh4z9iQN.js +0 -36
  82. package/dist/list-HRP3TIRl.js +0 -12631
  83. package/dist/markers-CTTtJqYn.js +0 -342
  84. package/dist/message-BRUuLgrY.js +0 -153
  85. package/dist/model-input-CFC62mf-.js +0 -82
  86. package/dist/registry-Cl7Labpe.js +0 -3279
  87. package/dist/run-conversation-Cz2ubZK-.js +0 -337
  88. package/dist/sender-actors-77zTQbSG.js +0 -84
  89. package/dist/spawn-DuZfodPa.js +0 -45
  90. package/dist/task-runner-BJ9Up3bG.js +0 -1529
  91. package/dist/topic-CRYYBYp-.js +0 -7
  92. package/dist/topics-BoCkoPJJ.js +0 -21
  93. package/dist/turn-membership-VT7XZh-L.js +0 -856
  94. 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-DlLLoJKj.js";
3
+ import { $l as isPersonInput, $s as isDmChannel, Ad as conversationNoteEvent, Cc as findLinkedSlackUser, Cd as getProviderErrorUserMessage, Dd as JUNIOR_NATIVE_EVENT_NAMESPACE, Dn as releaseInboundMessage, Du as ToolInputError, Eo as publishAgentUpdate, Et as getRegistrations, Fn as readInboundMessageSender, Gp as juniorUsers, Ii as escapeSlackMrkdwnText, In as isEventMailboxMetadata, Is as findActorTimezone, Jo as verifyTimerWatchCredentialSubject, Kp as juniorDestinations, Li as formatSlackLink, N as claimProviderConversation, Nl as projectConversationMessages, Od as agentsInstructionsUpdatedEvent, Oi as postSlackEphemeralMessage, On as traceContextSchema, Op as juniorConversationEvents, Pd as getAppContext, Pf as addAgentTurnUsage, Pn as readParentMessage, Ql as instructionAuthor, Rr as getVercelConversationWorkQueue, Sd as getProviderErrorAttributes, Ts as conversationSubtreeColumns, Tt as getPlugins, Uf as nextDetailVersion, Ui as getPluginUserPromptContributions, Ut as appendAndEnqueueInboundMessage, W as conversationLastTurnOutcomeSql, Wt as appendInboundMessage, Xl as dispatchInstructionsInvokeSkills, Xo as JUNIOR_THREAD_STATE_TTL_MS, Xs as getSlackClient, Yu as completeText, Zr as formatSentryEventReference, _d as isCompactionSummaryText, _u as eventGuidance, a as getDb, aa as createPluginCache, ac as sleep, an as getConversationWorkState, ao as generateShortTitle, bd as createProviderError, bp as juniorLocationConfigurations, cu as EVENT_AUTHOR_ID, d as createSqlConversationEventStore, dd as estimateTextTokens, dr as readThroughHttpCache, du as eventBotAuthorId, ea as pluginConfigValues, fo as getEventCatalog, gn as takePendingEventMessages, hn as stopConversationWork, i as getConversationStore, ic as withSlackRetries, io as fallbackShortTitle, ip as juniorWorkspaces, j as startLocationThread, kd as authenticationLinkedEvent, ki as postSlackMessage, lu as EVENT_MESSAGE_AUTHOR, n as getConversationEventStore, nn as dropPendingMessages, np as juniorSnapshots, o as getSqlExecutor, oa as getConfigDefaults, od as createCache, on as getConversationWorkStates, pu as isEventConversationMessage, rp as juniorWorkspaceRepos, u as isPostgresErrorCode, uu as EVENT_SYSTEM_ACTOR, v as withConversationEventLock, vc as SYSTEM_IDENTITY_ID, wc as findSlackUserByPrimaryEmail, ws as conversationSubtree, xd as findProviderError, xp as juniorAgentBindings, yc as resolveActorIdentityId, yd as createAssistantProviderError, zc as getInboxItem, zp as juniorConversations } from "./db-BacvswT0.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-DsTnMqyi.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-C5CW2wKO.js";
7
+ import { a as toCanonicalInputMessage } from "./conversation-privacy-qoh95v90.js";
8
+ import { a as parseSkillFile, i as openAiPolicyDisablesImplicitInvocation } from "./skills-50izzzdK.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-v9vA3RvH.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-CIR1B44Z.js";
10
11
  import { t as isMissingVirtualModule } from "./virtual-module-BeKA_EII.js";
12
+ import { i as lookupSlackUserProfile, t as lookupActiveSlackWorkspaceMember } from "./users-DOVo9sdU.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, 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();
@@ -1525,6 +1519,7 @@ function isEventInboundMessageId(id) {
1525
1519
  return id.startsWith(EVENT_INBOUND_MESSAGE_PREFIX);
1526
1520
  }
1527
1521
  // src/chat/conversations/turn-lifecycle.ts
1522
+ /** The idempotency key of a Turn's `turn_started` event. */
1528
1523
  function turnStartedKey(turnId) {
1529
1524
  return `turn:${turnId}:started`;
1530
1525
  }
@@ -1569,7 +1564,7 @@ var ConversationTurnLifecycleService = class {
1569
1564
  /** Record a completion that is not a failure once. */
1570
1565
  async complete(input) {
1571
1566
  await this.events.append(input.conversationId, [{
1572
- idempotencyKey: `turn:${input.turnId}:terminal`,
1567
+ idempotencyKey: turnTerminalKey(input.turnId),
1573
1568
  createdAtMs: input.createdAtMs,
1574
1569
  data: {
1575
1570
  type: "turn_completed",
@@ -1582,7 +1577,7 @@ var ConversationTurnLifecycleService = class {
1582
1577
  /** Record a classified failure once. Do not store raw error text. */
1583
1578
  async fail(input) {
1584
1579
  await this.events.append(input.conversationId, [{
1585
- idempotencyKey: `turn:${input.turnId}:terminal`,
1580
+ idempotencyKey: turnTerminalKey(input.turnId),
1586
1581
  createdAtMs: input.createdAtMs,
1587
1582
  data: {
1588
1583
  type: "turn_failed",
@@ -1607,7 +1602,7 @@ var ConversationTurnLifecycleService = class {
1607
1602
  ...input.reportAs ? { starter: input.reportAs } : void 0,
1608
1603
  state: this.state
1609
1604
  };
1610
- const stored = await this.events.loadByIdempotencyKey(input.conversationId, `turn:${input.turnId}:terminal`);
1605
+ const stored = await this.events.loadByIdempotencyKey(input.conversationId, turnTerminalKey(input.turnId));
1611
1606
  if (stored?.data.type === "turn_failed") {
1612
1607
  const { failureCode } = stored.data;
1613
1608
  await publishAgentUpdate(input.conversationId, {
@@ -1648,6 +1643,13 @@ var ConversationTurnLifecycleService = class {
1648
1643
  });
1649
1644
  }
1650
1645
  };
1646
+ /**
1647
+ * The idempotency key of a Turn's `turn_completed` or `turn_failed` event.
1648
+ * The two share it, so a Turn ends once.
1649
+ */
1650
+ function turnTerminalKey(turnId) {
1651
+ return `turn:${turnId}:terminal`;
1652
+ }
1651
1653
  /** Return the Turn lifecycle that records Conversation events. */
1652
1654
  function getTurnLifecycle() {
1653
1655
  return new ConversationTurnLifecycleService(getConversationEventStore(), { watchQueue: getVercelConversationWorkQueue });
@@ -2619,7 +2621,7 @@ function createPluginAuthOrchestration(input) {
2619
2621
  let pendingPause;
2620
2622
  const startAuthorizationPause = async (provider, options) => {
2621
2623
  if (pendingPause) throw pendingPause;
2622
- if (!input.actorId || !pluginCatalogRuntime.getOAuthConfig(provider)) throw new Error(`Cannot start plugin authorization for ${provider}`);
2624
+ if (!input.actorId || !getAppContext().catalog.getOAuthConfig(provider)) throw new Error(`Cannot start plugin authorization for ${provider}`);
2623
2625
  if (input.interactiveAuthEnabled === false) throw new AuthorizationFlowDisabledError("plugin", provider);
2624
2626
  const recordPendingAuth = input.sessionId ? input.recordPendingAuth : void 0;
2625
2627
  if (input.sessionId && !recordPendingAuth) throw new Error(`Missing pending auth recorder for plugin authorization pause "${provider}"`);
@@ -2691,7 +2693,7 @@ function createPluginAuthOrchestration(input) {
2691
2693
  if (input.interactiveAuthEnabled === false) throw new AuthorizationFlowDisabledError("plugin", provider);
2692
2694
  throw new PluginCredentialFailureError(provider, signal.message ?? `${formatProviderLabel(provider)} credentials are required. Please connect your ${formatProviderLabel(provider)} account and try again.`);
2693
2695
  }
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.`);
2696
+ 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
2697
  await startAuthorizationPause(authorization.provider, authorization.scope ? { scope: authorization.scope } : void 0);
2696
2698
  },
2697
2699
  getPendingPause: () => pendingPause
@@ -2710,7 +2712,7 @@ function credentialContextForPluginEgress(credentialContext, source) {
2710
2712
  /** Create host-owned provider egress for plugin runtime tools. */
2711
2713
  function createPluginEgress(deps) {
2712
2714
  const credentialContext = deps.credentialContext ? credentialContextForPluginEgress(deps.credentialContext, deps.credentialAuditSource) : void 0;
2713
- return { async fetch(input) {
2715
+ const egress = { async fetch(input) {
2714
2716
  const operation = input.operation.trim();
2715
2717
  if (!operation) throw new Error("Plugin egress operation is required");
2716
2718
  if (!credentialContext) throw new PluginCredentialFailureError(input.provider, `Cannot issue ${input.provider} credentials without a credential context.`);
@@ -2733,6 +2735,25 @@ function createPluginEgress(deps) {
2733
2735
  if (result.authRequired) await deps.pluginAuth.handleAuthRequired(result.authRequired);
2734
2736
  return result.response;
2735
2737
  } };
2738
+ const { httpCache } = deps;
2739
+ if (!httpCache || !deps.credentialContext) return egress;
2740
+ const scope = `egress:${JSON.stringify([deps.credentialContext, deps.userOAuthOnly ? "user-oauth" : "any"])}`;
2741
+ return { async fetch(input) {
2742
+ if (input.request.method !== "GET") return await egress.fetch(input);
2743
+ return await readThroughHttpCache({
2744
+ ...httpCache,
2745
+ request: input.request,
2746
+ scope,
2747
+ send: async (headers) => {
2748
+ const request = new Request(input.request);
2749
+ for (const [name, value] of Object.entries(headers)) request.headers.set(name, value);
2750
+ return await egress.fetch({
2751
+ ...input,
2752
+ request
2753
+ });
2754
+ }
2755
+ });
2756
+ } };
2736
2757
  }
2737
2758
  // src/chat/plugins/conversation-title-context.ts
2738
2759
  const TITLE_CONTEXT_TIMEOUT_MS = 5e3;
@@ -2994,7 +3015,9 @@ function getConversationMessageSlackTs(message) {
2994
3015
  return parseSlackMessageTs(message.meta?.slackTs);
2995
3016
  }
2996
3017
  // src/chat/services/conversation-title.ts
2997
- const inFlightTitles = /* @__PURE__ */ new Map();
3018
+ function inFlightTitles() {
3019
+ return getAppContext().conversationTitles;
3020
+ }
2998
3021
  /**
2999
3022
  * Set-once conversation title from the earliest human message.
3000
3023
  *
@@ -3005,12 +3028,12 @@ const inFlightTitles = /* @__PURE__ */ new Map();
3005
3028
  * is already titled or generation does not apply.
3006
3029
  */
3007
3030
  async function ensureConversationTitle(args) {
3008
- const pending = inFlightTitles.get(args.conversationId);
3031
+ const pending = inFlightTitles().get(args.conversationId);
3009
3032
  if (pending) return pending;
3010
3033
  const work = ensureConversationTitleOnce(args).finally(() => {
3011
- inFlightTitles.delete(args.conversationId);
3034
+ inFlightTitles().delete(args.conversationId);
3012
3035
  });
3013
- inFlightTitles.set(args.conversationId, work);
3036
+ inFlightTitles().set(args.conversationId, work);
3014
3037
  return work;
3015
3038
  }
3016
3039
  /** Return the earliest user message, which is the input of a dispatched run. */
@@ -3108,14 +3131,14 @@ function scheduleConversationTitle(args) {
3108
3131
  * gives this to `waitUntil` so title work has an owner.
3109
3132
  */
3110
3133
  async function settleConversationTitleWork(conversationId) {
3111
- await inFlightTitles.get(conversationId);
3134
+ await inFlightTitles().get(conversationId);
3112
3135
  }
3113
3136
  /**
3114
3137
  * Join in-flight generation when present, otherwise read the stored title.
3115
3138
  * Does not start generation; providers use this only to project a title.
3116
3139
  */
3117
3140
  async function resolveConversationTitle(args) {
3118
- const pending = inFlightTitles.get(args.conversationId);
3141
+ const pending = inFlightTitles().get(args.conversationId);
3119
3142
  if (pending) {
3120
3143
  const generated = await pending;
3121
3144
  if (generated?.trim()) return generated.trim();
@@ -4620,6 +4643,97 @@ function buildDeterministicTurnId(messageId) {
4620
4643
  function buildDeterministicAssistantMessageId(turnId) {
4621
4644
  return `${turnId}:assistant:1`;
4622
4645
  }
4646
+ // src/chat/runtime/turn.ts
4647
+ /** Classified Slack turn failure carrying the owning Sentry capture outward. */
4648
+ var ConversationTurnBoundaryError = class extends Error {
4649
+ eventId;
4650
+ failureCode;
4651
+ constructor(args) {
4652
+ super(args.cause instanceof Error ? args.cause.message : String(args.cause), { cause: args.cause });
4653
+ this.name = "ConversationTurnBoundaryError";
4654
+ this.eventId = args.eventId;
4655
+ this.failureCode = args.failureCode;
4656
+ }
4657
+ };
4658
+ /** Return a classified Slack boundary failure without erasing its cause. */
4659
+ function getConversationTurnBoundaryError(error) {
4660
+ return error instanceof ConversationTurnBoundaryError ? error : void 0;
4661
+ }
4662
+ /**
4663
+ * Queue-worker yield routing: respond.ts returns a suspended AgentRunOutcome
4664
+ * and the Slack executor raises this at the worker boundary so the lease owner
4665
+ * requeues the conversation.
4666
+ */
4667
+ var CooperativeTurnYieldError = class extends Error {
4668
+ code = "cooperative_turn_yield";
4669
+ constructor(message = "Agent turn yielded at a safe boundary") {
4670
+ super(message);
4671
+ this.name = "CooperativeTurnYieldError";
4672
+ }
4673
+ };
4674
+ function isCooperativeTurnYieldError(error) {
4675
+ return error instanceof CooperativeTurnYieldError;
4676
+ }
4677
+ /** Error indicating durable turn input could not be committed by the worker owner. */
4678
+ var TurnInputCommitLostError = class extends Error {
4679
+ code = "turn_input_commit_lost";
4680
+ constructor(message = "Turn input commit lost its durable owner") {
4681
+ super(message);
4682
+ this.name = "TurnInputCommitLostError";
4683
+ }
4684
+ };
4685
+ /** Return whether an error means the durable worker lost input ownership. */
4686
+ function isTurnInputCommitLostError(error) {
4687
+ return error instanceof TurnInputCommitLostError;
4688
+ }
4689
+ /** Error indicating durable turn input should stay pending for a later worker. */
4690
+ var TurnInputDeferredError = class extends Error {
4691
+ code = "turn_input_deferred";
4692
+ constructor(message = "Turn input is deferred until the active resume ends") {
4693
+ super(message);
4694
+ this.name = "TurnInputDeferredError";
4695
+ }
4696
+ };
4697
+ /** Return whether an error means the durable worker should redeliver input later. */
4698
+ function isTurnInputDeferredError(error) {
4699
+ return error instanceof TurnInputDeferredError;
4700
+ }
4701
+ /** Mark a turn as the active turn in conversation state. */
4702
+ function startActiveTurn(args) {
4703
+ args.conversation.processing.activeTurnId = args.nextTurnId;
4704
+ }
4705
+ function clearActiveTurn(conversation, sessionId) {
4706
+ if (!sessionId || conversation.processing.activeTurnId === sessionId) conversation.processing.activeTurnId = void 0;
4707
+ }
4708
+ /**
4709
+ * Close the active turn without marking a Pi session reusable for future
4710
+ * history. Use this for auth handoffs and recovery replies that end the live
4711
+ * turn but do not produce a completed Pi session.
4712
+ */
4713
+ function markTurnClosed(args) {
4714
+ clearActiveTurn(args.conversation, args.sessionId);
4715
+ args.conversation.processing.lastCompletedAtMs = args.nowMs;
4716
+ }
4717
+ /**
4718
+ * Mark a turn as completed after its assistant output has been handled.
4719
+ */
4720
+ function markTurnCompleted(args) {
4721
+ clearActiveTurn(args.conversation, args.sessionId);
4722
+ args.conversation.processing.lastCompletedAtMs = args.nowMs;
4723
+ }
4724
+ /**
4725
+ * Mark a turn as failed when execution or final user-visible reply delivery
4726
+ * cannot be completed. If `sessionId` is provided, `activeTurnId` is only
4727
+ * cleared when it still matches the failing turn.
4728
+ */
4729
+ function markTurnFailed(args) {
4730
+ clearActiveTurn(args.conversation, args.sessionId);
4731
+ args.conversation.processing.lastCompletedAtMs = args.nowMs;
4732
+ args.markConversationMessage(args.conversation, args.userMessageId, {
4733
+ replied: false,
4734
+ skippedReason: "reply failed"
4735
+ });
4736
+ }
4623
4737
  // src/chat/plugins/prompt-history-messages.ts
4624
4738
  function textParts(message) {
4625
4739
  if (!("role" in message) || message.role !== "user") return [];
@@ -5424,1170 +5538,1300 @@ async function withHeldInput(args, instruction) {
5424
5538
  text: instruction.text
5425
5539
  }]]);
5426
5540
  }
5427
- // src/chat/inbox-items/prompt-input.ts
5541
+ // src/chat/events/workspace.ts
5428
5542
  /**
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.
5543
+ * Resolve the single-bot Slack team id for event-automation indexing, Event
5544
+ * people mentions, and author trust.
5545
+ *
5546
+ * Watch matching does not use this. Event automations still key by
5547
+ * destination team until that store is conversation-owned. System Events are
5548
+ * not gated on Slack. Without a Slack bot, only a listed Event author is
5549
+ * trusted.
5434
5550
  */
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");
5551
+ async function resolveBotSlackTeamId() {
5552
+ const token = getSlackBotToken();
5553
+ if (!token) return void 0;
5554
+ const teamIdsByToken = getAppContext().slackBotTeamIds;
5555
+ let pending = teamIdsByToken.get(token);
5556
+ if (!pending) {
5557
+ pending = getSlackClient().auth.test().then((result) => {
5558
+ const teamId = result.team_id?.trim();
5559
+ if (!teamId) throw new Error("Slack auth.test did not return a team id");
5560
+ return teamId;
5561
+ });
5562
+ teamIdsByToken.set(token, pending);
5563
+ pending.catch(() => teamIdsByToken.delete(token));
5564
+ }
5565
+ return await pending;
5439
5566
  }
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);
5567
+ // src/chat/identities/trust.ts
5568
+ const emailSchema = z.string().trim().toLowerCase().pipe(z.email());
5569
+ /**
5570
+ * Parse a value that must be an email, such as a sign-in or a verified email
5571
+ * from a plugin. Return the normalized email and its domain, or undefined
5572
+ * when the value is not a valid email.
5573
+ */
5574
+ function parseEmail(value) {
5575
+ const parsed = emailSchema.safeParse(value);
5576
+ if (!parsed.success) return void 0;
5577
+ const email = parsed.data;
5445
5578
  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
5579
+ email,
5580
+ domain: email.slice(email.lastIndexOf("@") + 1)
5449
5581
  };
5450
5582
  }
5451
5583
  /**
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.
5584
+ * Return whether a domain, such as the domain of a parsed email or Google's
5585
+ * `hd` claim, is on the allowed domains. It only compares domains.
5586
+ * `ifNoDomains` says what an empty list means: Slack authors allow every
5587
+ * domain, and sign-ins allow none.
5456
5588
  */
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;
5589
+ function isAllowedDomain(domain, options) {
5590
+ if (options.allowedDomains.length === 0) return options.ifNoDomains === "allow";
5591
+ const normalized = domain?.trim().toLowerCase();
5592
+ return normalized ? options.allowedDomains.includes(normalized) : false;
5461
5593
  }
5462
- /**
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>`.
5467
- */
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
- }]);
5594
+ function isCoreIdentityProvider(provider) {
5595
+ return provider === "junior" || isNativeIdentityProvider(provider);
5476
5596
  }
5477
- /**
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.
5482
- */
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]] : []));
5597
+ function isSlackProfileDomainAllowed(profile) {
5598
+ const email = profile.email?.trim();
5599
+ const separator = email?.lastIndexOf("@") ?? -1;
5600
+ const allowed = isAllowedDomain(separator > 0 ? email?.slice(separator + 1) : void 0, {
5601
+ allowedDomains: getChatConfig().trust.allowedDomains,
5602
+ ifNoDomains: "allow"
5603
+ });
5604
+ if (!allowed) logWarn("slack.allowed_domain.rejected", { "app.reason": email ? "domain_not_allowed" : "missing_email" });
5605
+ return allowed;
5486
5606
  }
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}`;
5607
+ const SLACK_TRUSTED_TTL_MS = 3e5;
5608
+ const SLACK_UNTRUSTED_TTL_MS = 3e4;
5609
+ async function readActiveMember(userId, teamId) {
5610
+ return await createCache(getStateAdapter(), "core").getOrLoad(`slack:active-member:${teamId}:${userId}`, async () => {
5611
+ const member = await lookupActiveSlackWorkspaceMember(userId, teamId);
5612
+ const value = member ? {
5613
+ email: member.email,
5614
+ name: member.name,
5615
+ real_name: member.real_name
5616
+ } : null;
5617
+ return {
5618
+ value,
5619
+ ttlMs: value ? SLACK_TRUSTED_TTL_MS : SLACK_UNTRUSTED_TTL_MS
5620
+ };
5621
+ });
5492
5622
  }
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
- }
5623
+ /**
5624
+ * Accept one stored Slack link only when it is a current human member of the
5625
+ * workspace whose Slack email is on the allowed domains. With `email`, the
5626
+ * Slack email must also still be that address, so a stale stored email does
5627
+ * not match.
5628
+ */
5629
+ async function linkedMemberDecision(args) {
5630
+ const userId = parseSlackUserId(args.linked?.slackUserId);
5631
+ if (!args.linked || !userId) return {
5632
+ trusted: false,
5633
+ reason: "no_single_link"
5503
5634
  };
5504
- }
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;
5509
- 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;
5515
- }
5516
- }
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));
5520
- }
5521
- // src/chat/state/conversation.ts
5522
- function defaultConversationState() {
5523
- return {
5524
- schemaVersion: 1,
5525
- messages: [],
5526
- processing: {},
5527
- vision: { byFileId: {} }
5635
+ const member = await readActiveMember(userId, args.teamId);
5636
+ if (!member) return {
5637
+ trusted: false,
5638
+ reason: "inactive_member"
5528
5639
  };
5529
- }
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)
5551
- });
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
- }
5640
+ if (args.email && member.email?.trim().toLowerCase() !== args.email) return {
5641
+ trusted: false,
5642
+ reason: "email_changed"
5643
+ };
5644
+ if (!isSlackProfileDomainAllowed(member)) return {
5645
+ trusted: false,
5646
+ reason: "domain_not_allowed"
5647
+ };
5648
+ const fullName = member.real_name?.trim() || void 0;
5649
+ const userName = member.name?.trim() || void 0;
5578
5650
  return {
5579
- schemaVersion: 1,
5580
- messages: [],
5581
- processing,
5582
- vision: {
5583
- backfillCompletedAtMs: vision.backfillCompletedAtMs,
5584
- byFileId
5585
- }
5651
+ trusted: true,
5652
+ actor: {
5653
+ platform: "slack",
5654
+ teamId: args.teamId,
5655
+ userId,
5656
+ ...fullName ? { fullName } : void 0,
5657
+ ...userName ? { userName } : void 0
5658
+ },
5659
+ user: args.linked.user
5586
5660
  };
5587
5661
  }
5588
5662
  /**
5589
- * Wrap active conversation control into the thread scratch envelope.
5590
- *
5591
- * Visible history lives in SQL. Image summaries use a separate disposable
5592
- * cache, so thread scratch does not retain them.
5663
+ * A plugin account is trusted when the plugin lists it, or through its exact
5664
+ * `subjectId`, linked by the OAuth account-linking flow to one Slack user who
5665
+ * is a current human member on the allowed domains. Handles, emails, and
5666
+ * display names never match.
5593
5667
  */
5594
- function buildConversationStatePatch(conversation) {
5595
- return { conversation: {
5596
- schemaVersion: 1,
5597
- processing: { ...conversation.processing }
5598
- } };
5599
- }
5600
- // src/chat/runtime/thread-state.ts
5601
- function threadStateKey(threadId) {
5602
- return `thread-state:${threadId}`;
5603
- }
5604
- function channelStateKey(channelId) {
5605
- return `channel-state:${channelId}`;
5606
- }
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 ?? "";
5617
- }
5618
- return payload;
5668
+ async function accountDecision(args) {
5669
+ if (isCoreIdentityProvider(args.provider)) return {
5670
+ trusted: false,
5671
+ reason: "core_provider"
5672
+ };
5673
+ if (args.listed) return { trusted: true };
5674
+ if (!args.subjectId) return {
5675
+ trusted: false,
5676
+ reason: "unknown_author"
5677
+ };
5678
+ const teamId = await resolveBotSlackTeamId();
5679
+ if (!teamId) return {
5680
+ trusted: false,
5681
+ reason: "no_workspace"
5682
+ };
5683
+ return await linkedMemberDecision({
5684
+ linked: await findLinkedSlackUser(getSqlExecutor(), {
5685
+ provider: args.provider,
5686
+ providerSubjectId: args.subjectId,
5687
+ slackTeamId: teamId
5688
+ }),
5689
+ teamId
5690
+ });
5619
5691
  }
5620
5692
  /**
5621
- * Merge a payload into thread scratch with Junior's TTL.
5622
- *
5623
- * Chat SDK state writes hardcode a 30-day TTL. This boundary owns Junior's
5624
- * shorter retention policy for the same scratch keys.
5693
+ * Return whether a Slack author may start a Turn. The caller must have
5694
+ * checked that the author is a member of the workspace `teamId`. A member is
5695
+ * trusted when their Slack email is on the allowed domains, or when the app
5696
+ * lists them as a bot user. Without allowed domains, every member is.
5625
5697
  */
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);
5698
+ async function isTrustedSlackAuthor(args) {
5699
+ const userId = parseSlackUserId(args.user);
5700
+ if (!userId || !args.teamId) return false;
5701
+ const { allowedBotUserIds, allowedDomains } = getChatConfig().trust;
5702
+ if (allowedBotUserIds.includes(userId) || allowedDomains.length === 0) return true;
5703
+ return await createCache(args.state, "core").getOrLoad(`slack:allowed-domain:${args.teamId}:${userId}`, async () => {
5704
+ const profile = await lookupSlackUserProfile(userId);
5705
+ const trusted = profile.id === userId && isSlackProfileDomainAllowed(profile);
5706
+ return {
5707
+ value: trusted,
5708
+ ttlMs: trusted ? SLACK_TRUSTED_TTL_MS : SLACK_UNTRUSTED_TTL_MS
5709
+ };
5710
+ });
5635
5711
  }
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"]);
5644
- 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
5712
+ async function verifiedEmailDecision(value) {
5713
+ const email = parseEmail(value)?.email;
5714
+ if (!email) return {
5715
+ trusted: false,
5716
+ reason: "invalid_email"
5652
5717
  };
5653
- }
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
5718
+ const teamId = await resolveBotSlackTeamId();
5719
+ if (!teamId) return {
5720
+ trusted: false,
5721
+ reason: "no_workspace"
5722
+ };
5723
+ return await linkedMemberDecision({
5724
+ email,
5725
+ linked: await findSlackUserByPrimaryEmail(getSqlExecutor(), {
5726
+ normalizedEmail: email,
5727
+ slackTeamId: teamId
5728
+ }),
5729
+ teamId
5669
5730
  });
5670
- await mergePersistedState(threadStateKey(threadId), buildThreadStatePayload(patch));
5671
- }
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)) ?? {};
5677
5731
  }
5678
5732
  /**
5679
- * Resolve durable location configuration.
5680
- *
5681
- * Slack still reads the old channel-id Redis bag once during cutover.
5733
+ * Find the trusted person behind an account of a plugin's provider or behind
5734
+ * a verified email, for work that runs as that person. A verified email is
5735
+ * trusted when it is the primary email of the User of one Slack member on
5736
+ * the allowed domains, and Slack still shows that email. Slack and storage
5737
+ * errors propagate.
5682
5738
  */
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)
5739
+ async function findTrustedUser(author) {
5740
+ let decision;
5741
+ if ("subjectId" in author) decision = await accountDecision({
5742
+ ...author,
5743
+ listed: false
5689
5744
  });
5690
- }
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;
5745
+ else decision = await verifiedEmailDecision(author.verifiedEmail);
5746
+ if (!decision.trusted) return {
5747
+ status: "untrusted",
5748
+ reason: decision.reason
5749
+ };
5750
+ return decision.user ? {
5751
+ status: "trusted",
5752
+ user: decision.user
5753
+ } : {
5754
+ status: "untrusted",
5755
+ reason: "no_single_link"
5756
+ };
5706
5757
  }
5707
5758
  /**
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.
5759
+ * Resolve the author of an Event, the same way Slack ingress resolves a
5760
+ * Slack author. It never throws: a failed check gives an untrusted author,
5761
+ * so the Event still runs and the author's text stays context.
5711
5762
  */
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";
5763
+ async function resolveEventAuthor(event) {
5764
+ const author = event.author;
5765
+ if (!author) return { status: "system" };
5766
+ const facts = {
5767
+ ...author.bot ? { bot: true } : void 0,
5768
+ handle: author.handle,
5769
+ provider: event.namespace,
5770
+ ...author.text?.trim() ? { text: author.text.trim() } : void 0
5771
+ };
5772
+ try {
5773
+ const decision = await accountDecision({
5774
+ listed: author.trusted === true,
5775
+ provider: event.namespace,
5776
+ ...author.subjectId ? { subjectId: author.subjectId } : void 0
5777
+ });
5778
+ if (!decision.trusted) return {
5779
+ status: "untrusted",
5780
+ reason: decision.reason,
5781
+ ...facts
5782
+ };
5783
+ if (!decision.actor) return {
5784
+ status: "trusted",
5785
+ ...facts
5786
+ };
5787
+ return {
5788
+ status: "trusted",
5789
+ actor: decision.actor,
5790
+ identityId: await resolveActorIdentityId(getSqlExecutor(), decision.actor),
5791
+ ...facts
5792
+ };
5793
+ } catch (error) {
5794
+ logException(error, "event.author.trust_check_failed", {
5795
+ "app.event.event_type": event.eventType,
5796
+ "app.event.namespace": event.namespace
5797
+ });
5798
+ return {
5799
+ status: "untrusted",
5800
+ reason: "check_failed",
5801
+ ...facts
5802
+ };
5740
5803
  }
5741
- };
5742
- /** Return whether an error means the durable worker should redeliver input later. */
5743
- function isTurnInputDeferredError(error) {
5744
- return error instanceof TurnInputDeferredError;
5745
- }
5746
- /** Mark a turn as the active turn in conversation state. */
5747
- function startActiveTurn(args) {
5748
- args.conversation.processing.activeTurnId = args.nextTurnId;
5749
5804
  }
5750
- function clearActiveTurn(conversation, sessionId) {
5751
- if (!sessionId || conversation.processing.activeTurnId === sessionId) conversation.processing.activeTurnId = void 0;
5805
+ function safeId(value) {
5806
+ return value.replace(/[^A-Za-z0-9._:@/#+[\]-]/g, "_");
5752
5807
  }
5753
5808
  /**
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.
5809
+ * Return an Event author's own text and who wrote it. A linked person has
5810
+ * the same author ID and name as on their Slack messages. Other authors
5811
+ * show their handle on the provider.
5757
5812
  */
5758
- function markTurnClosed(args) {
5759
- clearActiveTurn(args.conversation, args.sessionId);
5760
- args.conversation.processing.lastCompletedAtMs = args.nowMs;
5813
+ function eventAuthorText(author) {
5814
+ if (author.status === "system" || !author.text) return void 0;
5815
+ const actor = author.status === "trusted" ? author.actor : void 0;
5816
+ const name = actor?.fullName ?? actor?.userName ?? `${safeId(author.handle)} on ${safeId(author.provider)}${author.bot ? " (a bot)" : ""}`;
5817
+ return {
5818
+ text: author.text,
5819
+ ...actor ? { authorId: actor.userId } : void 0,
5820
+ authorName: name,
5821
+ verified: author.status === "trusted"
5822
+ };
5761
5823
  }
5824
+ // src/chat/events/notification.ts
5825
+ const EVENT_WAIT_MS = 3e4;
5826
+ const eventTaskFactsSchema = z.object({
5827
+ about: z.string().optional(),
5828
+ instructions: z.string().min(1),
5829
+ guidance: z.string().optional(),
5830
+ people: z.array(z.string()).optional(),
5831
+ trustedSummary: z.string().optional(),
5832
+ verifiedDetails: z.record(z.string(), z.unknown()).optional(),
5833
+ externalText: z.string().optional(),
5834
+ doneBy: z.object({
5835
+ mention: z.string(),
5836
+ handle: z.string().optional()
5837
+ }).optional(),
5838
+ /** The Event author's own text and who wrote it. It is context. */
5839
+ authorText: z.object({
5840
+ text: z.string().min(1),
5841
+ authorId: z.string().optional(),
5842
+ authorName: z.string().optional(),
5843
+ verified: z.boolean()
5844
+ }).optional()
5845
+ });
5762
5846
  /**
5763
- * Mark a turn as completed after its assistant output has been handled.
5847
+ * Collect the task facts for one subscribed Event.
5848
+ *
5849
+ * Keep this short: facts the model cannot reconstruct, plus a one-line handling
5850
+ * contract. Stable delivery rules live in runtime and docs, not this prompt.
5764
5851
  */
5765
- function markTurnCompleted(args) {
5766
- clearActiveTurn(args.conversation, args.sessionId);
5767
- args.conversation.processing.lastCompletedAtMs = args.nowMs;
5852
+ function eventTaskFacts(subscription, event, people = [], doneBy, author = { status: "system" }) {
5853
+ const guidance = [eventGuidance(getEventCatalog(), event.namespace, event.eventType), subscription.guidance?.[event.eventType]].filter((text) => Boolean(text?.trim())).join(" ");
5854
+ const authorText = eventAuthorText(author);
5855
+ return {
5856
+ about: subscription.label,
5857
+ instructions: subscription.intent,
5858
+ ...guidance ? { guidance } : void 0,
5859
+ ...people.length > 0 ? { people: [...people] } : void 0,
5860
+ trustedSummary: event.trustedSummary,
5861
+ ...event.data ? { verifiedDetails: event.data } : void 0,
5862
+ ...authorText ? { authorText } : void 0,
5863
+ ...event.untrustedText ? { externalText: event.untrustedText } : void 0,
5864
+ ...doneBy ? { doneBy } : void 0
5865
+ };
5768
5866
  }
5769
5867
  /**
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.
5868
+ * Return the timer creator subject when every event in the batch carries a
5869
+ * valid subject for its own Watch and the same user.
5773
5870
  */
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
- });
5781
- }
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;
5871
+ function timerWatchCredentialSubject(conversationId, messages) {
5872
+ let shared;
5873
+ for (const message of messages) {
5874
+ const metadata = message.input.metadata;
5875
+ if (!isEventMailboxMetadata(metadata)) return void 0;
5876
+ const parsed = credentialSubjectSchema.safeParse(metadata.credentialSubject);
5877
+ if (!parsed.success || !metadata.event.subscriptionId || !verifyTimerWatchCredentialSubject({
5878
+ conversationId,
5879
+ subject: parsed.data,
5880
+ watchId: metadata.event.subscriptionId
5881
+ }) || shared && shared.userId !== parsed.data.userId) return;
5882
+ shared ??= parsed.data;
5789
5883
  }
5884
+ return shared;
5790
5885
  }
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;
5794
- }
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);
5798
- }
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;
5804
- return {
5805
- ...inboundAttachmentCount > 0 ? { inboundAttachmentCount } : void 0,
5806
- ...!imagesHydrated && imageAttachmentCount > 0 ? { omittedImageAttachmentCount: imageAttachmentCount } : void 0
5807
- };
5886
+ /**
5887
+ * Read the saved Watch task facts from one Event mailbox entry. Entries
5888
+ * without a Watch or saved facts, such as child agent results and input queued
5889
+ * before facts were saved, return undefined and keep their own text.
5890
+ */
5891
+ function readEventTaskFacts(message) {
5892
+ const metadata = message.input.metadata;
5893
+ if (!isEventMailboxMetadata(metadata)) return void 0;
5894
+ const watchId = metadata.event.subscriptionId;
5895
+ if (!watchId) return void 0;
5896
+ const parsed = eventTaskFactsSchema.safeParse(metadata.task);
5897
+ return parsed.success ? {
5898
+ facts: parsed.data,
5899
+ metadata,
5900
+ watchId
5901
+ } : void 0;
5808
5902
  }
5809
- // src/chat/task-execution/turn-cancel.ts
5810
5903
  /**
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.
5904
+ * Write the agent inputs for an Event batch, one prompt content part each.
5905
+ *
5906
+ * One Event keeps its own text. Several Watch Events become one `<task>`
5907
+ * with one group per Watch, so shared instructions appear once. Entries
5908
+ * without task facts, such as child agent results, keep their own text as
5909
+ * their own inputs after the task. `rendered` replaces the input of an entry
5910
+ * by inbound message id, such as a person change to an Inbox item.
5813
5911
  */
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();
5912
+ function renderEventBatchInputs(messages, rendered = /* @__PURE__ */ new Map()) {
5913
+ const groups = /* @__PURE__ */ new Map();
5914
+ const others = [];
5915
+ for (const message of messages) {
5916
+ const saved = readEventTaskFacts(message);
5917
+ if (!saved) {
5918
+ others.push(message);
5919
+ continue;
5920
+ }
5921
+ const { facts, metadata, watchId } = saved;
5922
+ let group = groups.get(watchId);
5923
+ if (!group) {
5924
+ group = {
5925
+ about: facts.about,
5926
+ instructions: facts.instructions,
5927
+ people: [],
5928
+ events: []
5929
+ };
5930
+ groups.set(watchId, group);
5931
+ }
5932
+ for (const person of facts.people ?? []) if (!group.people.includes(person)) group.people.push(person);
5933
+ group.events.push({
5934
+ eventType: metadata.event.eventType,
5935
+ guidance: facts.guidance,
5936
+ source: metadata.event.namespace,
5937
+ trustedSummary: facts.trustedSummary,
5938
+ verifiedDetails: facts.verifiedDetails,
5939
+ authorText: facts.authorText,
5940
+ externalText: facts.externalText,
5941
+ doneBy: facts.doneBy
5942
+ });
5943
+ }
5944
+ const ownInputs = (entries) => entries.map((message) => rendered.get(message.inboundMessageId) ?? {
5945
+ kind: "runtime",
5946
+ text: message.input.text.trim()
5947
+ }).filter((input) => input.text);
5948
+ if (messages.length - others.length < 2) return ownInputs(messages);
5949
+ return [{
5950
+ kind: "runtime",
5951
+ text: renderTaskBatchInput({ groups: [...groups.values()] })
5952
+ }, ...ownInputs(others)];
5847
5953
  }
5848
- /**
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.
5854
- */
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
- });
5954
+ /** Return the conversation message entry for one Event input. */
5955
+ function messageEvent(message) {
5956
+ const metadata = message.input.metadata;
5957
+ if (!isEventMailboxMetadata(metadata)) return [];
5958
+ const label = readEventTaskFacts(message)?.facts.about;
5959
+ return [{
5960
+ eventType: metadata.event.eventType,
5961
+ ...label ? { label } : void 0,
5962
+ ...metadata.event.objectType ? { objectType: metadata.event.objectType } : void 0,
5963
+ ...metadata.event.trustedSummary ? { trustedSummary: metadata.event.trustedSummary } : void 0
5964
+ }];
5861
5965
  }
5862
5966
  /**
5863
- * Cancel a Turn that waits for sign-in outside its worker, with the same
5864
- * cleanup as a stopped resume.
5967
+ * Return the saved Message fields for the Event inputs of one Turn.
5968
+ *
5969
+ * A person change to an Inbox item is not one of the Message's own Events:
5970
+ * its record goes to `reviewItemChanges`, and the dashboard shows it as a
5971
+ * change row. The Message's own Event is its first Watch Event, the
5972
+ * kind the task message counts, or else its first other input, such as an
5973
+ * agent result. `events` lists the Watch Events when several arrived. When
5974
+ * changes share the Message with one own Event, `events` lists that Event, so
5975
+ * a reader can tell it from a Message that only records changes.
5865
5976
  */
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
- });
5977
+ function eventBatchMessageMeta(messages) {
5978
+ const reviewItemChanges = messages.flatMap((message) => message.input.reviewItemChange ? [message.input.reviewItemChange] : []);
5979
+ const own = messages.filter((message) => !message.input.reviewItemChange);
5980
+ const watched = own.filter((message) => readEventTaskFacts(message));
5981
+ const primary = watched[0] ?? own[0];
5982
+ const metadata = (primary ?? messages[0])?.input.metadata;
5983
+ if (!isEventMailboxMetadata(metadata)) return {};
5984
+ const events = watched.length > 1 ? watched.flatMap(messageEvent) : reviewItemChanges.length && primary ? messageEvent(primary) : [];
5985
+ return {
5986
+ eventType: metadata.event.eventType,
5987
+ eventNamespace: metadata.event.namespace,
5988
+ eventIdentifier: metadata.event.identifier,
5989
+ eventObjectType: metadata.event.objectType,
5990
+ ...metadata.event.status ? { eventStatus: metadata.event.status } : void 0,
5991
+ ...metadata.event.subscriptionId ? { eventWatchId: metadata.event.subscriptionId } : void 0,
5992
+ ...metadata.event.trustedSummary ? { trustedSummary: metadata.event.trustedSummary } : void 0,
5993
+ ...events.length ? { events } : void 0,
5994
+ ...reviewItemChanges.length ? { reviewItemChanges } : void 0
5995
+ };
5885
5996
  }
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();
5997
+ function eventMessageAuthor(author) {
5998
+ if (author?.status !== "trusted") return {
5999
+ authorId: EVENT_AUTHOR_ID,
6000
+ authorIdentityId: SYSTEM_IDENTITY_ID
6001
+ };
6002
+ if (author.identityId) return {
6003
+ authorId: EVENT_AUTHOR_ID,
6004
+ authorIdentityId: author.identityId
6005
+ };
6006
+ return { authorId: eventBotAuthorId(author.provider, author.handle) };
6007
+ }
6008
+ /** Build plain conversation mailbox input for one matched watch. */
6009
+ function createEventInboundMessage(input) {
6010
+ const metadata = {
6011
+ kind: "event",
6012
+ ...input.task ? { task: input.task } : void 0,
6013
+ ...input.subscription.credentialSubject ? { credentialSubject: input.subscription.credentialSubject } : void 0,
6014
+ event: {
6015
+ eventKey: input.event.eventKey,
6016
+ eventType: input.event.eventType,
6017
+ namespace: input.event.namespace,
6018
+ identifier: input.event.identifier,
6019
+ subscriptionId: input.subscription.id,
6020
+ trustedSummary: input.event.trustedSummary,
6021
+ objectType: input.event.objectType,
6022
+ ...input.status ? { status: input.status } : void 0
6023
+ }
6024
+ };
6025
+ return {
6026
+ conversationId: input.subscription.conversationId,
6027
+ createdAtMs: input.event.occurredAtMs,
6028
+ inboundMessageId: eventInboundMessageId(input.subscription.id, input.event.eventKey),
6029
+ delivery: "defer",
6030
+ source: "event",
6031
+ receivedAtMs: input.receivedAtMs ?? Date.now(),
6032
+ input: {
6033
+ text: input.text,
6034
+ ...eventMessageAuthor(input.author),
6035
+ metadata
6036
+ }
6037
+ };
5892
6038
  }
5893
6039
  /**
5894
- * The hold rule: a Conversation holds automated input only while it is
5895
- * stopped. Status and failure do not hold input.
6040
+ * Deliver a Quiet Event as a Conversation note. It starts no Turn, so the
6041
+ * automated-turn limit does not apply. The next Turn sees the note as
6042
+ * runtime context. Core writes how to use it before the Event facts, so a
6043
+ * long summary that the note limit cuts never loses that rule.
5896
6044
  */
5897
- async function isHeld(conversationId) {
5898
- return await getConversationStoppedAtMs(conversationId) !== void 0;
6045
+ async function addQuietEventNote(args) {
6046
+ const { event, subscription } = args;
6047
+ await addConversationNote({
6048
+ conversationId: subscription.conversationId,
6049
+ createdAtMs: event.occurredAtMs,
6050
+ key: `quiet_event:${subscription.id}:${event.eventKey}`,
6051
+ 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}`
6052
+ });
5899
6053
  }
5900
6054
  /**
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.
6055
+ * Enqueue a event as normal conversation mailbox input.
6056
+ *
6057
+ * The watch only names the conversation. Destination stays on the conversation
6058
+ * and is applied when the worker runs. A stopped Conversation holds the Event.
5906
6059
  */
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
- }
6060
+ async function enqueueEventNotification(args) {
6061
+ const task = eventTaskFacts(args.subscription, args.event, args.people, args.doneBy, args.author);
6062
+ return await enqueueAutomatedInput({
6063
+ message: createEventInboundMessage({
6064
+ author: args.author,
6065
+ event: args.event,
6066
+ subscription: {
6067
+ conversationId: args.subscription.conversationId,
6068
+ credentialSubject: args.subscription.credentialSubject,
6069
+ id: args.subscription.id
6070
+ },
6071
+ task,
6072
+ text: renderTaskInput({
6073
+ ...task,
6074
+ event: args.event.eventType,
6075
+ source: args.event.namespace
6076
+ })
6077
+ }),
6078
+ queue: args.queue,
6079
+ queueDelayMs: EVENT_WAIT_MS,
6080
+ state: args.state
5924
6081
  });
5925
- return held ? { status: "held" } : result;
5926
6082
  }
6083
+ // src/chat/inbox-items/prompt-input.ts
5927
6084
  /**
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.
6085
+ * Prompt inputs for person answers to Inbox items. An answer is its own
6086
+ * prompt content part, keyed by the item id that `addInboxItem` returned.
6087
+ * The runtime builds it from the stored change record and the item, so the
6088
+ * model never reads status prose. It repeats the question, then one line for
6089
+ * each answered field. `input-tags.ts` lists the input tags.
5937
6090
  */
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
- });
5985
- });
6091
+ const QUESTION_MAX_LENGTH = 512;
6092
+ function typedAnswerText(request, answer) {
6093
+ const normalized = normalizeUserInputAnswer(request, answer);
6094
+ return [...request.fields.flatMap((field) => field.kind === "text" ? normalized.values[field.id] ?? [] : []), ...normalized.other ? [normalized.other] : []].join("\n\n");
5986
6095
  }
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
- });
6096
+ function renderInboxItemAnswer(item) {
6097
+ const request = inboxItemQuestion(item.request);
6098
+ if (!request || !item.answer) return void 0;
6099
+ const question = request.question.trim();
6100
+ const requestText = typedAnswerText(request, item.answer);
6101
+ return {
6102
+ kind: "runtime",
6103
+ 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)),
6104
+ ...requestText ? { requestText } : void 0
6105
+ };
6008
6106
  }
6009
6107
  /**
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.
6108
+ * Render the prompt input of a message that records an answer, or undefined
6109
+ * when it has none. A take or a dismiss starts no Turn, so it has no input.
6110
+ * A message without an answer, or whose item is gone, goes to the model as
6111
+ * written.
6013
6112
  */
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)));
6113
+ async function loadInboxItemInput(record) {
6114
+ if (record?.kind !== "submitted") return void 0;
6115
+ const item = await getInboxItem(getDb(), record.reviewItemId);
6116
+ return item ? renderInboxItemAnswer(item) : void 0;
6018
6117
  }
6019
6118
  /**
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.
6119
+ * Return the instruction of one saved input. `runtime` text, such as an
6120
+ * Automation dispatch or an Event Turn, is already rendered as its tags.
6121
+ * An answer is its Inbox item tag. It is not typed text, so it does not go
6122
+ * in `<current-instruction>`.
6024
6123
  */
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
- }
6124
+ async function savedInputInstruction(args) {
6125
+ const inboxItemInput = args.runtime ? void 0 : await loadInboxItemInput(args.reviewItemChange);
6126
+ if (!args.runtime && !inboxItemInput) return { text: args.text };
6127
+ return instructionForInputs([inboxItemInput ?? {
6128
+ kind: "runtime",
6129
+ text: args.text,
6130
+ ...args.requestText ? { requestText: args.requestText } : void 0
6048
6131
  }]);
6049
6132
  }
6050
- // src/chat/events/workspace.ts
6051
- const teamIdsByToken = /* @__PURE__ */ new Map();
6052
6133
  /**
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.
6134
+ * Render the Inbox item input of each Event in a batch that records an
6135
+ * answer, keyed by inbound message id. A Conversation with no web identity,
6136
+ * such as a local CLI Conversation, gets the answer as a system Event, but
6137
+ * the input is the same as on web.
6060
6138
  */
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;
6139
+ async function eventInboxItemInputs(messages) {
6140
+ const rendered = await mapBounded(messages, async (message) => [message.inboundMessageId, await loadInboxItemInput(message.input.reviewItemChange)]);
6141
+ return new Map(rendered.flatMap(([id, input]) => input ? [[id, input]] : []));
6075
6142
  }
6076
- // src/chat/identities/trust.ts
6077
- const emailSchema = z.string().trim().toLowerCase().pipe(z.email());
6078
- /**
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.
6082
- */
6083
- function parseEmail(value) {
6084
- const parsed = emailSchema.safeParse(value);
6085
- if (!parsed.success) return void 0;
6086
- const email = parsed.data;
6143
+ // src/chat/conversations/web-authorization.ts
6144
+ const WEB_AUTHORIZATION_PREFIX = "junior:web_authorization:v1";
6145
+ const WEB_AUTHORIZATION_TTL_MS = 864e5;
6146
+ function authorizationKey(conversationId, actorId) {
6147
+ return `${WEB_AUTHORIZATION_PREFIX}:${conversationId}:${actorId}`;
6148
+ }
6149
+ /** Build authorization delivery for one web turn. */
6150
+ function createWebAuthorization(args) {
6087
6151
  return {
6088
- email,
6089
- domain: email.slice(email.lastIndexOf("@") + 1)
6152
+ createState: async () => randomUUID(),
6153
+ deliver: async (request) => {
6154
+ await getStateAdapter().set(authorizationKey(args.conversationId, args.actorId), JSON.stringify({
6155
+ ...request,
6156
+ ...args
6157
+ }), WEB_AUTHORIZATION_TTL_MS);
6158
+ }
6090
6159
  };
6091
6160
  }
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;
6161
+ /** Read the pending authorization request for one web actor. */
6162
+ async function getWebAuthorization(args) {
6163
+ const value = await getStateAdapter().get(authorizationKey(args.conversationId, args.actorId));
6164
+ if (typeof value !== "string") return void 0;
6165
+ try {
6166
+ const parsed = JSON.parse(value);
6167
+ if (parsed.actorId !== args.actorId || parsed.conversationId !== args.conversationId || typeof parsed.authorizationUrl !== "string" || typeof parsed.label !== "string" || typeof parsed.completionText !== "string") return;
6168
+ return parsed;
6169
+ } catch {
6170
+ return;
6171
+ }
6102
6172
  }
6103
- function isCoreIdentityProvider(provider) {
6104
- return provider === "junior" || isNativeIdentityProvider(provider);
6173
+ /** Remove a web authorization request after the parked turn continues. */
6174
+ async function deleteWebAuthorization(args) {
6175
+ await getStateAdapter().delete(authorizationKey(args.conversationId, args.actorId));
6105
6176
  }
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;
6177
+ // src/chat/state/conversation.ts
6178
+ function defaultConversationState() {
6179
+ return {
6180
+ schemaVersion: 1,
6181
+ messages: [],
6182
+ processing: {},
6183
+ vision: { byFileId: {} }
6184
+ };
6115
6185
  }
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
- };
6130
- });
6131
- }
6132
- /**
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.
6137
- */
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;
6186
+ const nonEmptyString = z.string().refine((value) => value.trim().length > 0);
6187
+ const optionalString = nonEmptyString.optional().catch(void 0);
6188
+ const optionalNumber = z.number().optional().catch(void 0);
6189
+ const pendingAuthCommonFields = {
6190
+ provider: nonEmptyString,
6191
+ actorId: nonEmptyString,
6192
+ sessionId: nonEmptyString,
6193
+ linkSentAtMs: z.number(),
6194
+ scope: optionalString
6195
+ };
6196
+ const pendingAuthSchema = z.discriminatedUnion("kind", [z.object({
6197
+ ...pendingAuthCommonFields,
6198
+ kind: z.literal("mcp"),
6199
+ authSessionId: nonEmptyString
6200
+ }), z.object({
6201
+ ...pendingAuthCommonFields,
6202
+ kind: z.literal("plugin")
6203
+ })]);
6204
+ const visionSummarySchema = z.object({
6205
+ summary: nonEmptyString,
6206
+ analyzedAtMs: z.number().refine((value) => value !== 0)
6207
+ });
6208
+ const storedThreadStateSchema = z.object({ conversation: z.object({
6209
+ processing: z.object({
6210
+ activeTurnId: optionalString,
6211
+ lastCompletedAtMs: optionalNumber,
6212
+ pendingAuth: pendingAuthSchema.optional().catch(void 0)
6213
+ }).catch(() => ({})),
6214
+ vision: z.object({
6215
+ backfillCompletedAtMs: optionalNumber,
6216
+ byFileId: z.record(z.string(), z.unknown()).catch(() => ({}))
6217
+ }).catch(() => ({ byFileId: {} }))
6218
+ }).catch(() => ({
6219
+ processing: {},
6220
+ vision: { byFileId: {} }
6221
+ })) });
6222
+ /** Safely coerce an unknown persisted value into a ThreadConversationState. */
6223
+ function coerceThreadConversationState(value) {
6224
+ const parsed = storedThreadStateSchema.safeParse(value);
6225
+ if (!parsed.success) return defaultConversationState();
6226
+ const { processing, vision } = parsed.data.conversation;
6227
+ const byFileId = {};
6228
+ for (const [fileId, entry] of Object.entries(vision.byFileId)) {
6229
+ if (fileId.trim().length === 0) continue;
6230
+ const summary = visionSummarySchema.safeParse(entry);
6231
+ if (!summary.success) continue;
6232
+ byFileId[fileId] = summary.data;
6233
+ }
6159
6234
  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
6235
+ schemaVersion: 1,
6236
+ messages: [],
6237
+ processing,
6238
+ vision: {
6239
+ backfillCompletedAtMs: vision.backfillCompletedAtMs,
6240
+ byFileId
6241
+ }
6169
6242
  };
6170
6243
  }
6171
6244
  /**
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.
6245
+ * Wrap active conversation control into the thread scratch envelope.
6246
+ *
6247
+ * Visible history lives in SQL. Image summaries use a separate disposable
6248
+ * cache, so thread scratch does not retain them.
6176
6249
  */
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
6199
- });
6250
+ function buildConversationStatePatch(conversation) {
6251
+ return { conversation: {
6252
+ schemaVersion: 1,
6253
+ processing: { ...conversation.processing }
6254
+ } };
6255
+ }
6256
+ // src/chat/runtime/thread-state.ts
6257
+ function threadStateKey(threadId) {
6258
+ return `thread-state:${threadId}`;
6259
+ }
6260
+ function channelStateKey(channelId) {
6261
+ return `channel-state:${channelId}`;
6262
+ }
6263
+ function buildThreadStatePayload(patch) {
6264
+ const payload = {};
6265
+ if (patch.conversation) Object.assign(payload, buildConversationStatePatch(patch.conversation));
6266
+ if (patch.sandboxRef !== void 0) {
6267
+ payload["app_sandbox_id"] = patch.sandboxRef?.id ?? "";
6268
+ payload["app_sandbox_dependency_profile_hash"] = patch.sandboxRef?.profileHash ?? "";
6269
+ payload["app_sandbox_workspace_id"] = patch.sandboxRef?.workspaceId ?? "";
6270
+ const toolSession = patch.sandboxRef?.toolSession;
6271
+ payload["app_sandbox_tool_sandbox_id"] = toolSession?.sandboxId ?? "";
6272
+ payload["app_sandbox_tool_session_id"] = toolSession?.sessionId ?? "";
6273
+ }
6274
+ return payload;
6200
6275
  }
6201
6276
  /**
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.
6277
+ * Merge a payload into thread scratch with Junior's TTL.
6278
+ *
6279
+ * Chat SDK state writes hardcode a 30-day TTL. This boundary owns Junior's
6280
+ * shorter retention policy for the same scratch keys.
6206
6281
  */
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);
6215
- return {
6216
- value: trusted,
6217
- ttlMs: trusted ? SLACK_TRUSTED_TTL_MS : SLACK_UNTRUSTED_TTL_MS
6218
- };
6219
- });
6282
+ async function mergePersistedState(key, payload) {
6283
+ if (Object.keys(payload).length === 0) return;
6284
+ const stateAdapter = getStateAdapter();
6285
+ await stateAdapter.connect();
6286
+ const existing = await stateAdapter.get(key) ?? {};
6287
+ await stateAdapter.set(key, {
6288
+ ...existing,
6289
+ ...payload
6290
+ }, JUNIOR_THREAD_STATE_TTL_MS);
6220
6291
  }
6221
- async function verifiedEmailDecision(value) {
6222
- const email = parseEmail(value)?.email;
6223
- if (!email) return {
6224
- trusted: false,
6225
- reason: "invalid_email"
6226
- };
6227
- const teamId = await resolveBotSlackTeamId();
6228
- if (!teamId) return {
6229
- trusted: false,
6230
- reason: "no_workspace"
6292
+ /** Extract persisted sandbox metadata from thread state payload. */
6293
+ function getPersistedSandboxState(state) {
6294
+ const id = toOptionalString(state["app_sandbox_id"]);
6295
+ if (!id) return;
6296
+ const profileHash = toOptionalString(state["app_sandbox_dependency_profile_hash"]);
6297
+ const workspaceId = toOptionalString(state["app_sandbox_workspace_id"]);
6298
+ const toolSandboxId = toOptionalString(state["app_sandbox_tool_sandbox_id"]);
6299
+ const toolSessionId = toOptionalString(state["app_sandbox_tool_session_id"]);
6300
+ return {
6301
+ id,
6302
+ ...profileHash ? { profileHash } : void 0,
6303
+ ...workspaceId ? { workspaceId } : void 0,
6304
+ ...toolSandboxId && toolSessionId ? { toolSession: {
6305
+ sandboxId: toolSandboxId,
6306
+ sessionId: toolSessionId
6307
+ } } : void 0
6231
6308
  };
6232
- return await linkedMemberDecision({
6233
- email,
6234
- linked: await findSlackUserByPrimaryEmail(getSqlExecutor(), {
6235
- normalizedEmail: email,
6236
- slackTeamId: teamId
6237
- }),
6238
- teamId
6309
+ }
6310
+ /** Persist only the Redis-backed runtime scratch in a thread-state patch. */
6311
+ async function persistThreadRuntimeState(conversationId, patch) {
6312
+ await mergePersistedState(threadStateKey(conversationId), buildThreadStatePayload(patch));
6313
+ }
6314
+ /** Load the persisted state payload for a thread without requiring a Chat singleton. */
6315
+ async function getPersistedThreadState(threadId) {
6316
+ const stateAdapter = getStateAdapter();
6317
+ await stateAdapter.connect();
6318
+ return await stateAdapter.get(threadStateKey(threadId)) ?? {};
6319
+ }
6320
+ /** Persist a thread-state patch by thread id without constructing a Chat thread. */
6321
+ async function persistThreadStateById(threadId, patch) {
6322
+ if (patch.conversation) await persistConversationMessages({
6323
+ conversation: patch.conversation,
6324
+ conversationId: threadId
6239
6325
  });
6326
+ await mergePersistedState(threadStateKey(threadId), buildThreadStatePayload(patch));
6327
+ }
6328
+ /** Load legacy Redis-backed channel state during the SQL cutover. */
6329
+ async function getLegacyChannelState(channelId) {
6330
+ const stateAdapter = getStateAdapter();
6331
+ await stateAdapter.connect();
6332
+ return await stateAdapter.get(channelStateKey(channelId)) ?? {};
6240
6333
  }
6241
6334
  /**
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.
6335
+ * Resolve durable location configuration.
6336
+ *
6337
+ * Slack still reads the old channel-id Redis bag once during cutover.
6247
6338
  */
6248
- async function findTrustedUser(author) {
6249
- let decision;
6250
- if ("subjectId" in author) decision = await accountDecision({
6251
- ...author,
6252
- listed: false
6339
+ function getLocationConfigurationService(destination) {
6340
+ if (destination.platform !== "slack") throw new Error("Location configuration requires a Slack Location");
6341
+ return createDurableLocationConfigurationService({
6342
+ destination,
6343
+ db: getDb(),
6344
+ loadLegacy: async () => await getLegacyChannelState(destination.channelId)
6253
6345
  });
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
- };
6266
6346
  }
6267
- /**
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.
6271
- */
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
- };
6347
+ // src/chat/runtime/turn-user-message.ts
6348
+ /** Return the user message for a persisted turn/session, if one exists. */
6349
+ function getTurnUserMessage(conversation, sessionId) {
6350
+ for (let index = conversation.messages.length - 1; index >= 0; index -= 1) {
6351
+ const message = conversation.messages[index];
6352
+ if (message?.role !== "user") continue;
6353
+ if (buildDeterministicTurnId(message.id) === sessionId) return message;
6312
6354
  }
6313
6355
  }
6314
- function safeId(value) {
6315
- return value.replace(/[^A-Za-z0-9._:@/#+[\]-]/g, "_");
6356
+ /** Return the persisted user-message id for a turn/session, if one exists. */
6357
+ function getTurnUserMessageId(conversation, sessionId) {
6358
+ return getTurnUserMessage(conversation, sessionId)?.id;
6316
6359
  }
6317
- /**
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.
6321
- */
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)" : ""}`;
6360
+ /** Return the Slack timestamp for the user message that a resumed turn acts on. */
6361
+ function getTurnUserSlackMessageTs(message) {
6362
+ return parseSlackMessageTs(message?.meta?.slackTs);
6363
+ }
6364
+ /** Rebuild attachment context for a resumed turn from the persisted user message. */
6365
+ function getTurnUserReplyAttachmentContext(message) {
6366
+ const inboundAttachmentCount = message?.meta?.attachmentCount ?? 0;
6367
+ const imageAttachmentCount = message?.meta?.imageAttachmentCount ?? 0;
6368
+ const imagesHydrated = message?.meta?.imagesHydrated === true;
6326
6369
  return {
6327
- text: author.text,
6328
- ...actor ? { authorId: actor.userId } : void 0,
6329
- authorName: name,
6330
- verified: author.status === "trusted"
6370
+ ...inboundAttachmentCount > 0 ? { inboundAttachmentCount } : void 0,
6371
+ ...!imagesHydrated && imageAttachmentCount > 0 ? { omittedImageAttachmentCount: imageAttachmentCount } : void 0
6331
6372
  };
6332
6373
  }
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
- });
6374
+ // src/chat/conversations/web-mailbox.ts
6375
+ /** Parse web mailbox metadata written before Source and Actor were complete. */
6376
+ const legacyWebMailboxMetadataSchema = z.object({
6377
+ authorEmail: z.string().email(),
6378
+ authorFullName: z.string().min(1).optional(),
6379
+ authorUserId: z.string().min(1),
6380
+ authorUserName: z.string().min(1).optional(),
6381
+ kind: z.literal("api_turn"),
6382
+ messageId: z.string().min(1)
6383
+ }).strict();
6384
+ // src/chat/task-execution/mailbox-turn.ts
6355
6385
  /**
6356
- * Collect the task facts for one subscribed Event.
6386
+ * Restore Turn input facts, with saved Message fallback for legacy cursors.
6357
6387
  *
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.
6388
+ * TODO(dcramer): Remove Actor and Source reconstruction from the saved Message
6389
+ * after no deployed Turn cursor can omit either field.
6360
6390
  */
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);
6391
+ function turnInputFactsFromConversationMessage(message, args) {
6392
+ if (isParentMessageAuthor(message.author)) return args.savedActor && args.savedSource ? {
6393
+ actor: args.savedActor,
6394
+ author: message.author,
6395
+ source: args.savedSource
6396
+ } : void 0;
6397
+ if (isEventConversationMessage(message)) return {
6398
+ actor: args.savedActor ?? EVENT_SYSTEM_ACTOR,
6399
+ author: message.author ?? EVENT_MESSAGE_AUTHOR,
6400
+ source: args.savedSource ?? (args.location ? createWebSource(args.conversationId, args.visibility === "private" ? "private" : "public") : createLocalSource(args.conversationId))
6401
+ };
6402
+ const actor = args.savedActor ?? createActor(message.author, {
6403
+ platform: "web",
6404
+ userId: message.author?.userId
6405
+ });
6406
+ if (actor?.platform !== "web") return;
6364
6407
  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
6408
+ actor,
6409
+ author: message.author ?? { userId: actor.userId },
6410
+ source: args.savedSource?.kind === "web" ? args.savedSource : createWebSource(args.conversationId, args.visibility === "private" ? "private" : "public")
6374
6411
  };
6375
6412
  }
6376
- /**
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.
6379
- */
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;
6413
+ /** Normalize the selected mailbox Source with current Conversation visibility. */
6414
+ function sourceFromTurnInput(args) {
6415
+ if (args.source.kind === "web") return createWebSource(args.conversationId, args.visibility === "private" ? "private" : "public");
6416
+ return args.source;
6394
6417
  }
6395
- /**
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.
6399
- */
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;
6418
+ function hasEventActor(actors) {
6419
+ return Boolean(actors?.some((actor) => actor.platform === "system" && actor.name === EVENT_SYSTEM_ACTOR.name));
6420
+ }
6421
+ /** Return the active web Turn for one Conversation, if it has one. */
6422
+ async function getActiveConversationTurnId(conversationId) {
6423
+ const active = (await listTurnSummaries(conversationId)).filter((summary) => summary.surface === "api" && !summary.dispatchId && (summary.state === "paused" || summary.state === "running"));
6424
+ if (active.length > 1) throw new Error(`Conversation ${conversationId} has multiple active web turns`);
6425
+ const turnId = active[0]?.turnId;
6426
+ if (!turnId) return void 0;
6427
+ const record = await getTurnRecord(conversationId, turnId);
6428
+ return record && (record.source?.kind === "web" || !record.source && record.surface === "api") && !record.dispatchId && (record.state === "paused" || record.state === "running") ? turnId : void 0;
6429
+ }
6430
+ /** Return the web and event mailbox Turns that are paused or running. */
6431
+ async function listActiveMailboxTurns(conversationId) {
6432
+ const summaries = (await listTurnSummaries(conversationId)).filter(isOpenTurnSummary);
6433
+ const stored = await getStoredTurnFields(summaries);
6434
+ const candidates = summaries.filter((_summary, index) => {
6435
+ const fields = stored[index];
6436
+ return fields !== void 0 && (isActiveMailboxTurn(fields) || !fields.source && fields.surface !== "api");
6437
+ });
6438
+ return (await mapBounded(candidates, (summary) => getTurnRecord(conversationId, summary.turnId))).filter((record) => record !== void 0 && isActiveMailboxTurn(record));
6411
6439
  }
6412
6440
  /**
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.
6441
+ * List the Source of each active mailbox Turn of several Conversations. It
6442
+ * reads the stored Turn cursors and not their Turn history, so unlike
6443
+ * `listActiveMailboxTurns` it keeps a Turn whose history was deleted.
6420
6444
  */
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
6451
- });
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)];
6445
+ async function listActiveMailboxTurnSources(conversationIds) {
6446
+ const limit = pLimit(8);
6447
+ const summaries = (await Promise.all(conversationIds.map((conversationId) => limit(() => listTurnSummaries(conversationId))))).flatMap((list) => list.filter(isOpenTurnSummary));
6448
+ const stored = await getStoredTurnFields(summaries);
6449
+ const sources = new Map(conversationIds.map((conversationId) => [conversationId, []]));
6450
+ await Promise.all(summaries.map((summary, index) => limit(async () => {
6451
+ const fields = stored[index];
6452
+ const turn = fields && !fields.source && fields.surface !== "api" ? await getTurnRecord(summary.conversationId, summary.turnId) : fields;
6453
+ if (turn && isActiveMailboxTurn(turn)) sources.get(summary.conversationId)?.push(turn.source);
6454
+ })));
6455
+ return sources;
6462
6456
  }
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
- }];
6457
+ function isOpenTurnSummary(summary) {
6458
+ return !summary.dispatchId && (summary.state === "paused" || summary.state === "running");
6459
+ }
6460
+ function isActiveMailboxTurn(record) {
6461
+ 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");
6462
+ }
6463
+ /** Return the active web or event mailbox Turn. */
6464
+ async function getActiveMailboxTurnId(conversationId) {
6465
+ const active = await listActiveMailboxTurns(conversationId);
6466
+ if (active.length > 1) throw new Error(`Conversation ${conversationId} has multiple active mailbox Turns`);
6467
+ return active[0]?.turnId;
6468
+ }
6469
+ /** Return the idle auth-paused web Turn for one Conversation. */
6470
+ async function getAuthPausedConversationTurnId(conversationId) {
6471
+ const turnId = await getActiveConversationTurnId(conversationId);
6472
+ if (!turnId) return void 0;
6473
+ const record = await getTurnRecord(conversationId, turnId);
6474
+ return record?.state === "paused" && record.resumeReason === "auth" ? turnId : void 0;
6475
+ }
6476
+ /** Return the transcript author of a web Actor's Message. */
6477
+ function webMessageAuthor(actor) {
6478
+ return {
6479
+ email: actor.email,
6480
+ ...actor.fullName ? { fullName: actor.fullName } : void 0,
6481
+ userId: actor.userId,
6482
+ ...actor.userName ? { userName: actor.userName } : void 0
6483
+ };
6474
6484
  }
6485
+ /** Read one web input batch as Turn input. A batch with no web input gives []. */
6486
+ function parseWebMessages(messages) {
6487
+ if (messages.length === 0) return [];
6488
+ const parsed = messages.map((message) => ({
6489
+ message,
6490
+ metadata: legacyWebMailboxMetadataSchema.safeParse(message.input.metadata)
6491
+ }));
6492
+ if (parsed.every((entry) => !entry.metadata.success)) return [];
6493
+ if (parsed.some((entry) => !entry.metadata.success)) throw new Error("A Turn cannot combine different kinds of input");
6494
+ return parsed.map((entry) => {
6495
+ if (!entry.metadata.success) throw new Error("User message has invalid metadata");
6496
+ const metadata = entry.metadata.data;
6497
+ const actor = {
6498
+ platform: "web",
6499
+ userId: metadata.authorUserId,
6500
+ email: metadata.authorEmail.trim().toLowerCase(),
6501
+ ...metadata.authorFullName ? { fullName: metadata.authorFullName } : void 0,
6502
+ ...metadata.authorUserName ? { userName: metadata.authorUserName } : void 0
6503
+ };
6504
+ return {
6505
+ actor,
6506
+ author: webMessageAuthor(actor),
6507
+ message: entry.message,
6508
+ source: createWebSource(entry.message.conversationId)
6509
+ };
6510
+ });
6511
+ }
6512
+ /** Extra debounce time added per additional event already batched. */
6513
+ const EVENT_WAIT_PER_EXTRA_MESSAGE_MS = 5e3;
6514
+ /** Upper bound on the debounce window regardless of batch size. */
6515
+ const EVENT_MAX_WAIT_MS = 6e4;
6475
6516
  /**
6476
- * Return the saved Message fields for the Event inputs of one Turn.
6517
+ * Return how long an event batch must wait before its Turn starts.
6477
6518
  *
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.
6519
+ * A resource-event burst (e.g. several check runs on one PR) should produce
6520
+ * one Turn instead of one per event. The window grows with batch size up to
6521
+ * EVENT_MAX_WAIT_MS, so later events in the same burst land in this batch.
6522
+ * Returns 0 when the batch can run now or does not start with an event.
6485
6523
  */
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
- };
6524
+ function getEventBatchDelayMs(messages, nowMs = Date.now()) {
6525
+ const first = messages[0];
6526
+ if (!first || !isEventMailboxMetadata(first.input.metadata)) return 0;
6527
+ const waitMs = Math.min(EVENT_MAX_WAIT_MS, EVENT_WAIT_MS + EVENT_WAIT_PER_EXTRA_MESSAGE_MS * (messages.length - 1));
6528
+ return Math.max(0, first.receivedAtMs + waitMs - nowMs);
6505
6529
  }
6506
- function eventMessageAuthor(author) {
6507
- if (author?.status !== "trusted") return {
6508
- authorId: EVENT_AUTHOR_ID,
6509
- authorIdentityId: SYSTEM_IDENTITY_ID
6530
+ /** Read an event batch as Turn input, or return [] when it is not only events. */
6531
+ function parseEventMessages(messages) {
6532
+ if (messages.length === 0) return [];
6533
+ if (!messages.every((message) => message.source === "event" && isEventMailboxMetadata(message.input.metadata))) return [];
6534
+ return messages.map((message) => {
6535
+ if (!isEventMailboxMetadata(message.input.metadata)) throw new Error("Event has invalid metadata");
6536
+ return {
6537
+ actor: EVENT_SYSTEM_ACTOR,
6538
+ author: EVENT_MESSAGE_AUTHOR,
6539
+ message,
6540
+ source: createEventSource({
6541
+ eventKey: message.input.metadata.event.eventKey,
6542
+ eventType: message.input.metadata.event.eventType,
6543
+ identifier: message.input.metadata.event.identifier,
6544
+ namespace: message.input.metadata.event.namespace
6545
+ })
6546
+ };
6547
+ });
6548
+ }
6549
+ /**
6550
+ * Read a batch of parent messages as Turn input, or return [] when it is not
6551
+ * only parent messages. Each runs as the Actor of the parent's Turn, with its
6552
+ * grants, and is from the parent agent.
6553
+ */
6554
+ function parseParentMessages(messages) {
6555
+ const parentMessages = messages.map(readParentMessage);
6556
+ if (parentMessages.length === 0 || parentMessages.some((parentMessage) => !parentMessage)) return [];
6557
+ return messages.map((message, index) => {
6558
+ const parentMessage = parentMessages[index];
6559
+ return {
6560
+ actor: parentMessage.actor,
6561
+ author: parentMessageAuthor(parentMessage.parentConversationId),
6562
+ ...parentMessage.credentialContext ? { credentialContext: parentMessage.credentialContext } : void 0,
6563
+ message,
6564
+ source: { kind: "parent_message" }
6565
+ };
6566
+ });
6567
+ }
6568
+ /**
6569
+ * Select web, event, or parent work from new mailbox input or a saved Turn.
6570
+ * Saved Actor data identifies a resumed event Turn.
6571
+ */
6572
+ async function resolveMailboxTurnWork(context) {
6573
+ const batch = parseWebMessages(context.attempt.messages);
6574
+ if (batch.length > 0) return {
6575
+ kind: "mailbox",
6576
+ batch
6510
6577
  };
6511
- if (author.identityId) return {
6512
- authorId: EVENT_AUTHOR_ID,
6513
- authorIdentityId: author.identityId
6578
+ const resourceBatch = parseEventMessages(context.attempt.messages);
6579
+ if (resourceBatch.length > 0) return {
6580
+ kind: "mailbox",
6581
+ batch: resourceBatch
6514
6582
  };
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
- }
6583
+ const parentBatch = parseParentMessages(context.attempt.messages);
6584
+ if (parentBatch.length > 0) return {
6585
+ kind: "mailbox",
6586
+ batch: parentBatch
6533
6587
  };
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
6588
+ if (context.attempt.messages.length > 0) return;
6589
+ const turnId = await getActiveMailboxTurnId(context.conversationId);
6590
+ return turnId ? {
6591
+ kind: "resume",
6592
+ turnId
6593
+ } : void 0;
6594
+ }
6595
+ // src/chat/task-execution/turn-cancel.ts
6596
+ /**
6597
+ * End a cancelled Turn: a stop that a worker saw, or a stop of a Turn that
6598
+ * waits for sign-in with no worker.
6599
+ */
6600
+ /** Close a cancelled Turn, save it, and acknowledge its input. */
6601
+ async function completeCancelledConversationTurn(args) {
6602
+ const pendingAuthorization = args.conversation.processing.pendingAuth?.sessionId === args.turnId ? args.conversation.processing.pendingAuth : void 0;
6603
+ await abandonTurnRecord({
6604
+ conversationId: args.conversationId,
6605
+ turnId: args.turnId,
6606
+ errorMessage: "Turn cancelled"
6607
+ });
6608
+ clearPendingAuth(args.conversation, args.turnId);
6609
+ markConversationMessage(args.conversation, args.userMessageId, {
6610
+ replied: false,
6611
+ skippedReason: "turn cancelled"
6612
+ });
6613
+ markTurnClosed({
6614
+ conversation: args.conversation,
6615
+ nowMs: Date.now(),
6616
+ sessionId: args.turnId
6617
+ });
6618
+ if (pendingAuthorization) await deleteWebAuthorization({
6619
+ actorId: pendingAuthorization.actorId,
6620
+ conversationId: args.conversationId
6621
+ });
6622
+ await persistThreadStateById(args.conversationId, {
6623
+ conversation: args.conversation,
6624
+ sandboxRef: args.sandboxRef
6625
+ });
6626
+ await getTurnLifecycle().complete({
6627
+ conversationId: args.conversationId,
6628
+ createdAtMs: Date.now(),
6629
+ outcome: "cancelled",
6630
+ turnId: args.turnId
6631
+ });
6632
+ await args.acknowledge();
6633
+ }
6634
+ /**
6635
+ * End the Turn of a stopped Conversation that waits for sign-in, so a later
6636
+ * sign-in cannot resume it. A web Turn waits as an auth-paused Turn record. A
6637
+ * Slack request waits as the thread's pending sign-in. Every stop path calls
6638
+ * this, because no worker holds a waiting Turn and the stop wake can go to
6639
+ * queued input first.
6640
+ */
6641
+ async function cancelSignInWait(conversationId) {
6642
+ const turnId = await getAuthPausedConversationTurnId(conversationId) ?? coerceThreadConversationState(await getPersistedThreadState(conversationId)).processing.pendingAuth?.sessionId;
6643
+ if (turnId) await cancelSignInPausedTurn({
6644
+ conversationId,
6645
+ turnId
6646
+ });
6647
+ }
6648
+ /**
6649
+ * Cancel a Turn that waits for sign-in outside its worker, with the same
6650
+ * cleanup as a stopped resume.
6651
+ */
6652
+ async function cancelSignInPausedTurn(args) {
6653
+ if (!await abandonTurnRecord({
6654
+ conversationId: args.conversationId,
6655
+ errorMessage: "Turn cancelled",
6656
+ onlyIfAuthPaused: true,
6657
+ turnId: args.turnId
6658
+ })) return;
6659
+ const conversation = coerceThreadConversationState(await getPersistedThreadState(args.conversationId));
6660
+ await hydrateConversationMessages({
6661
+ conversation,
6662
+ conversationId: args.conversationId
6663
+ });
6664
+ await completeCancelledConversationTurn({
6665
+ acknowledge: async () => {},
6666
+ conversation,
6667
+ conversationId: args.conversationId,
6668
+ turnId: args.turnId,
6669
+ userMessageId: getTurnUserMessage(conversation, args.turnId)?.id
6670
+ });
6671
+ }
6672
+ // src/chat/conversations/session-stop.ts
6673
+ var session_stop_exports = /* @__PURE__ */ __exportAll({ resumeForPersonInput: () => resumeForPersonInput });
6674
+ /** Return when a Conversation stopped, or undefined when it is not stopped. */
6675
+ async function getConversationStoppedAtMs(conversationId) {
6676
+ const [row] = await getSqlExecutor().db().select({ stoppedAt: juniorConversations.stoppedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
6677
+ return row?.stoppedAt?.getTime();
6678
+ }
6679
+ /**
6680
+ * The hold rule: a Conversation holds automated input only while it is
6681
+ * stopped. Status and failure do not hold input.
6682
+ */
6683
+ async function isHeld(conversationId) {
6684
+ return await getConversationStoppedAtMs(conversationId) !== void 0;
6685
+ }
6686
+ /**
6687
+ * Accept automated input, such as a Watch Event, a message from another
6688
+ * agent, or a child result. This is the only place that holds input. It
6689
+ * checks the hold under the mailbox lock, so it cannot race a stop: held
6690
+ * input is saved as a skipped Message and never reaches `pending`, and the
6691
+ * stop holds input that was appended before it.
6692
+ */
6693
+ async function enqueueAutomatedInput(args) {
6694
+ if (args.message.source !== "event") throw new Error("Automated input must be an Event");
6695
+ let held = false;
6696
+ const result = await appendAndEnqueueInboundMessage({
6697
+ ...args,
6698
+ renderText: async (inboundMessageIds, messageSenders) => {
6699
+ const text = args.renderText ? await args.renderText(inboundMessageIds, messageSenders) : args.message.input.text;
6700
+ if (text === void 0 || !await isHeld(args.message.conversationId)) return text;
6701
+ await saveHeldInput(args.message.conversationId, [{
6702
+ ...args.message,
6703
+ input: {
6704
+ ...args.message.input,
6705
+ text
6706
+ }
6707
+ }]);
6708
+ held = true;
6545
6709
  }
6546
- };
6710
+ });
6711
+ return held ? { status: "held" } : result;
6547
6712
  }
6548
6713
  /**
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.
6714
+ * Stop each Conversation of a tree until a person sends it input or its
6715
+ * parent gives it new work. Every stop path ends here: a person's stop,
6716
+ * `stopAgent`, and the automated-turn limit. It writes the stop in one
6717
+ * transaction with row locks, holds the automated input that already waits
6718
+ * in each mailbox, ends a Turn that waits for sign-in, and asks each running
6719
+ * Turn to stop. Each Turn it ends records one cancelled `turn_completed`.
6720
+ * Watches stay, and each Conversation that this stop starts reports
6721
+ * a `stopped` agent update to them. A Conversation that already stopped later
6722
+ * keeps that stop, so a retried or cascaded stop does not move it back.
6553
6723
  */
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}`
6724
+ async function stopConversationTree(conversationIds, options) {
6725
+ if (conversationIds.length === 0) return [];
6726
+ const stoppedAt = new Date(options.stoppedAtMs);
6727
+ const reported = await getSqlExecutor().transaction(async () => {
6728
+ const tx = getDb();
6729
+ const locked = await tx.select({
6730
+ conversationId: juniorConversations.conversationId,
6731
+ stoppedAt: juniorConversations.stoppedAt
6732
+ }).from(juniorConversations).where(inArray(juniorConversations.conversationId, [...conversationIds])).orderBy(asc(juniorConversations.conversationId)).for("update");
6733
+ await tx.update(juniorConversations).set({
6734
+ stoppedAt,
6735
+ detailVersion: nextDetailVersion
6736
+ }).where(and(inArray(juniorConversations.conversationId, [...conversationIds]), or(isNull(juniorConversations.stoppedAt), lt(juniorConversations.stoppedAt, stoppedAt))));
6737
+ return locked.flatMap((row) => !row.stoppedAt || row.stoppedAt.getTime() === stoppedAt.getTime() ? [row.conversationId] : []);
6738
+ });
6739
+ const queue = options.queue ?? getVercelConversationWorkQueue();
6740
+ await mapBounded(reported, (conversationId) => publishAgentUpdate(conversationId, {
6741
+ type: "stopped",
6742
+ stoppedAtMs: stoppedAt.getTime()
6743
+ }, {
6744
+ nowMs: stoppedAt.getTime(),
6745
+ queue,
6746
+ starter: false,
6747
+ state: options.state,
6748
+ update: async () => ({
6749
+ status: "stopped",
6750
+ text: "This conversation was stopped."
6751
+ })
6752
+ }));
6753
+ return await mapBounded(conversationIds, async (conversationId) => {
6754
+ const pending = await takePendingEventMessages({
6755
+ conversationId,
6756
+ conversationStore: options.conversationStore,
6757
+ nowMs: options.nowMs,
6758
+ state: options.state
6759
+ });
6760
+ if (pending.length > 0) await saveHeldInput(conversationId, pending);
6761
+ await cancelSignInWait(conversationId);
6762
+ if (conversationId === options.finishedRunOf) return { status: "no_work" };
6763
+ return await stopConversationWork({
6764
+ conversationId,
6765
+ conversationStore: options.conversationStore,
6766
+ nowMs: options.nowMs,
6767
+ onStopSaved: options.onStopSaved,
6768
+ sentAtOrBeforeMs: options.sentAtOrBeforeMs,
6769
+ state: options.state
6770
+ });
6561
6771
  });
6562
6772
  }
6563
6773
  /**
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.
6774
+ * End the stop of a Conversation and of the child agents below it, for new
6775
+ * work sent at `sentAtMs`: a person's input, or new work from its parent.
6776
+ * Nothing changes for work sent at or before the stop, so the input that a
6777
+ * stop drops does not undo it. Only Conversations that stopped no later than
6778
+ * this Conversation change, so a later stop of one child agent stays.
6568
6779
  */
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
6780
+ async function resumeConversationTree(conversationId, sentAtMs) {
6781
+ const subtree = sql`(select ${conversationSubtreeColumns.conversationId} from ${conversationSubtree([conversationId])})`;
6782
+ await getSqlExecutor().transaction(async () => {
6783
+ const tx = getDb();
6784
+ const stoppedAt = (await tx.select({
6785
+ conversationId: juniorConversations.conversationId,
6786
+ stoppedAt: juniorConversations.stoppedAt
6787
+ }).from(juniorConversations).where(inArray(juniorConversations.conversationId, subtree)).orderBy(asc(juniorConversations.conversationId)).for("update")).find((row) => row.conversationId === conversationId)?.stoppedAt;
6788
+ if (!stoppedAt || sentAtMs <= stoppedAt.getTime()) return;
6789
+ await tx.update(juniorConversations).set({
6790
+ stoppedAt: null,
6791
+ detailVersion: nextDetailVersion
6792
+ }).where(and(inArray(juniorConversations.conversationId, subtree), lte(juniorConversations.stoppedAt, stoppedAt)));
6793
+ });
6794
+ }
6795
+ /**
6796
+ * Resume a stopped Conversation when a person sent input after the stop.
6797
+ * Known gap: input sent before the stop but received after it still runs,
6798
+ * and the Conversation stays stopped.
6799
+ */
6800
+ async function resumeForPersonInput(conversationId, messages) {
6801
+ const personInput = messages.filter((message) => isPersonInput(message.source));
6802
+ if (personInput.length === 0) return;
6803
+ await resumeConversationTree(conversationId, Math.max(...personInput.map((message) => message.createdAtMs)));
6804
+ }
6805
+ /**
6806
+ * Save held input as one skipped Message, the Message that a Turn would save
6807
+ * for it. The next Turn gets it as Turn input (`withHeldInput`). The append
6808
+ * is idempotent by Message id, and the Message takes the id of the first
6809
+ * input.
6810
+ */
6811
+ async function saveHeldInput(conversationId, messages) {
6812
+ const first = messages[0];
6813
+ const { text } = instructionForInputs(renderEventBatchInputs(messages, await eventInboxItemInputs(messages)));
6814
+ const stored = toStoredConversationMessage({
6815
+ id: first.inboundMessageId,
6816
+ role: "user",
6817
+ text: normalizeConversationText(text),
6818
+ createdAtMs: first.createdAtMs,
6819
+ ...first.input.authorIdentityId ? { authorIdentityId: first.input.authorIdentityId } : void 0,
6820
+ meta: {
6821
+ replied: false,
6822
+ skippedReason: STOPPED_CONVERSATION_SKIP_REASON,
6823
+ ...eventBatchMessageMeta(messages)
6824
+ }
6590
6825
  });
6826
+ const { createdAtMs, ...data } = stored;
6827
+ await getConversationEventStore().append(conversationId, [{
6828
+ idempotencyKey: `message:${stored.messageId}`,
6829
+ createdAtMs,
6830
+ data: {
6831
+ type: "message",
6832
+ ...data
6833
+ }
6834
+ }]);
6591
6835
  }
6592
6836
  // src/chat/child-agents/fork-history.ts
6593
6837
  /** Instructions that a fork child reads with its first task. */
@@ -6879,15 +7123,6 @@ function isParentMessageAuthor(author) {
6879
7123
  return typeof author?.userId === "string" && author.userId.startsWith(PARENT_MESSAGE_AUTHOR_PREFIX);
6880
7124
  }
6881
7125
  /**
6882
- * Read when the root Turn code last saved a parent message to one child, or
6883
- * undefined when it saved none.
6884
- */
6885
- async function readLastParentMessageAtMs(conversationId) {
6886
- const payload = juniorConversationEvents.payload;
6887
- const [row] = await getSqlExecutor().db().select({ createdAt: juniorConversationEvents.createdAt }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "message"), like(sql`${payload}->'meta'->'author'->>'userId'`, `${PARENT_MESSAGE_AUTHOR_PREFIX}%`))).orderBy(desc(juniorConversationEvents.createdAt)).limit(1);
6888
- return row?.createdAt.getTime();
6889
- }
6890
- /**
6891
7126
  * Commit the parent's history for the first Turn of a fork child, before the
6892
7127
  * Turn starts. `inputs` passed the sender check.
6893
7128
  */
@@ -6917,225 +7152,411 @@ async function childAgentTurnOptions(args) {
6917
7152
  run: options?.reasoningLevel ? { reasoning: options.reasoningLevel } : {}
6918
7153
  };
6919
7154
  }
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;
7155
+ // src/chat/child-agents/child-input.ts
7156
+ const parent = alias(juniorConversations, "parent");
7157
+ function childAgentInputKind(namespace, eventType, watchId) {
7158
+ if (namespace !== "junior" || !eventType) return;
7159
+ if (eventType === "agent.message") return "message";
7160
+ return isAgentUpdateEventType(eventType) && watchId === void 0 ? "reply" : void 0;
6975
7161
  }
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));
7162
+ /** Read the child that one reply or message Event names. */
7163
+ function childAgentInput(message) {
7164
+ const metadata = message.input.metadata;
7165
+ if (!isEventMailboxMetadata(metadata)) return;
7166
+ const kind = childAgentInputKind(metadata.event.namespace, metadata.event.eventType, metadata.event.subscriptionId);
7167
+ return kind ? {
7168
+ kind,
7169
+ senderId: metadata.event.identifier
7170
+ } : void 0;
6985
7171
  }
6986
7172
  /**
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.
7173
+ * Whether one input is the `stopped` result that the stop of its sender
7174
+ * sends. Only a stop reports `stopped`, so the stored status tells this
7175
+ * result from the reply of a Turn.
6990
7176
  */
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;
7177
+ function isStopResult(message) {
7178
+ const metadata = message.input.metadata;
7179
+ return isEventMailboxMetadata(metadata) && metadata.event.namespace === "junior" && isAgentUpdateEventType(metadata.event.eventType) && metadata.event.status === "stopped";
7002
7180
  }
7003
- function isOpenTurnSummary(summary) {
7004
- return !summary.dispatchId && (summary.state === "paused" || summary.state === "running");
7181
+ /**
7182
+ * Whether the saved Event fields of a Turn's input Message name a child
7183
+ * agent's reply or message. A new and a resumed Turn read the same fields.
7184
+ */
7185
+ function isChildAgentEvent(meta) {
7186
+ return Boolean(childAgentInputKind(meta?.eventNamespace, meta?.eventType, meta?.eventWatchId));
7005
7187
  }
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");
7188
+ /**
7189
+ * Return the stored parent edge that a parent message claims, or undefined
7190
+ * when its author id is not that parent's, so it is dropped with no read.
7191
+ */
7192
+ function claimedParentEdge(message, parentMessage) {
7193
+ return hasParentMessageAuthor(message, parentMessage) ? parentEdgeKey(message.conversationId, parentMessage.parentConversationId) : void 0;
7008
7194
  }
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;
7195
+ function parentEdgeKey(childConversationId, parentConversationId) {
7196
+ return JSON.stringify([childConversationId, parentConversationId]);
7014
7197
  }
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;
7198
+ /**
7199
+ * Return the child that sent a reply that a stop can skip. A message that a
7200
+ * child sent is still delivered, and so is the `stopped` result that a
7201
+ * person's stop sends.
7202
+ */
7203
+ function skippableReplySender(message) {
7204
+ if (childAgentInput(message)?.kind !== "reply" || isStopResult(message)) return;
7205
+ return readInboundMessageSender(message)?.conversationId;
7021
7206
  }
7022
- /** Return the transcript author of a web Actor's Message. */
7023
- function webMessageAuthor(actor) {
7207
+ /**
7208
+ * Read the stops that `isDroppedChildInput` needs for many inputs, with one
7209
+ * query for the receiving children and one for the reply senders.
7210
+ */
7211
+ async function readChildInputDropFacts(messages) {
7212
+ const childIds = /* @__PURE__ */ new Set();
7213
+ const parentIds = /* @__PURE__ */ new Set();
7214
+ const senderIds = /* @__PURE__ */ new Set();
7215
+ for (const message of messages) {
7216
+ const parentMessage = readParentMessage(message);
7217
+ if (parentMessage) {
7218
+ if (claimedParentEdge(message, parentMessage)) {
7219
+ childIds.add(message.conversationId);
7220
+ parentIds.add(parentMessage.parentConversationId);
7221
+ }
7222
+ continue;
7223
+ }
7224
+ const sender = skippableReplySender(message);
7225
+ if (sender) senderIds.add(sender);
7226
+ }
7227
+ const db = getSqlExecutor().db();
7228
+ const [children, senders] = await Promise.all([childIds.size > 0 ? db.select({
7229
+ conversationId: juniorConversations.conversationId,
7230
+ parentConversationId: parent.conversationId,
7231
+ stoppedAt: juniorConversations.stoppedAt
7232
+ }).from(juniorConversations).innerJoin(parent, eq(parent.conversationId, juniorConversations.parentConversationId)).where(and(inArray(juniorConversations.conversationId, [...childIds]), inArray(parent.conversationId, [...parentIds]))) : [], senderIds.size > 0 ? db.select({
7233
+ conversationId: juniorConversations.conversationId,
7234
+ stoppedAt: juniorConversations.stoppedAt
7235
+ }).from(juniorConversations).where(inArray(juniorConversations.conversationId, [...senderIds])) : []]);
7024
7236
  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
7237
+ childStops: new Map(children.map((row) => [parentEdgeKey(row.conversationId, row.parentConversationId), row.stoppedAt])),
7238
+ senderStops: new Map(senders.flatMap((row) => row.stoppedAt ? [[row.conversationId, row.stoppedAt]] : []))
7029
7239
  };
7030
7240
  }
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
7241
+ /**
7242
+ * Return whether a Conversation drops one input, so it starts no work. Routing
7243
+ * and child status both read it, so they agree. `facts` are from
7244
+ * `readChildInputDropFacts`. A parent message is dropped when it is not from
7245
+ * the stored parent, or was sent before the child's stop. A stop drops unread
7246
+ * replies from the parent's mailbox. One sent before the stop can reach the
7247
+ * mailbox after that drop, so while the sending child is stopped, a reply that
7248
+ * it sent after the stop is dropped too. A stopped Conversation never reads
7249
+ * other automated input: `enqueueAutomatedInput` and the stop hold it first.
7250
+ */
7251
+ function isDroppedChildInput(message, facts) {
7252
+ if (isPersonInput(message.source)) return false;
7253
+ const parentMessage = readParentMessage(message);
7254
+ if (parentMessage) {
7255
+ const edge = claimedParentEdge(message, parentMessage);
7256
+ if (!edge || !facts.childStops.has(edge)) return true;
7257
+ const stoppedAtMs = facts.childStops.get(edge)?.getTime();
7258
+ return stoppedAtMs !== void 0 && message.receivedAtMs <= stoppedAtMs;
7259
+ }
7260
+ const sender = skippableReplySender(message);
7261
+ const senderStoppedAtMs = sender ? facts.senderStops.get(sender)?.getTime() : void 0;
7262
+ return senderStoppedAtMs !== void 0 && message.createdAtMs >= senderStoppedAtMs;
7263
+ }
7264
+ /**
7265
+ * Read the sender of one child Conversation from its parent edge and its
7266
+ * binding. A Conversation without a parent has none.
7267
+ */
7268
+ async function readChildConversationSender(childConversationId) {
7269
+ const [row] = await getSqlExecutor().db().select({
7270
+ agentName: juniorAgentBindings.name,
7271
+ parentConversationId: parent.conversationId,
7272
+ parentKind: parent.kind,
7273
+ title: juniorConversations.title
7274
+ }).from(juniorConversations).innerJoin(parent, eq(parent.conversationId, juniorConversations.parentConversationId)).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(eq(juniorConversations.conversationId, childConversationId));
7275
+ return row ? {
7276
+ ...row.agentName ? { agentName: row.agentName } : void 0,
7277
+ childConversationId,
7278
+ parentConversationId: row.parentConversationId,
7279
+ ...row.parentKind ? { parentKind: row.parentKind } : void 0,
7280
+ ...row.title ? { title: row.title } : void 0
7281
+ } : void 0;
7282
+ }
7283
+ /**
7284
+ * Read the sender of one reply or message, when it is a child of the
7285
+ * Conversation that received it. Input that names no child of this
7286
+ * Conversation has no sender, so `withSenderActors` runs it as the Event
7287
+ * system Actor and it gets no child's authority.
7288
+ */
7289
+ async function getChildAgentInputSender(message, input) {
7290
+ const sender = await readChildConversationSender(input.senderId);
7291
+ return sender?.parentConversationId === message.conversationId ? sender : void 0;
7292
+ }
7293
+ // src/chat/child-agents/sender-actors.ts
7294
+ const senderActorMetadataSchema = z.object({ actor: actorSchema });
7295
+ /**
7296
+ * Return the Inbound message author id for results sent by one Actor.
7297
+ * `selectContiguousTurnBatch` in `task-execution/worker.ts` puts messages in
7298
+ * one attempt only when their author ids and sources match. Mid-Turn drains
7299
+ * take only `interrupt` messages, and results are `defer`. So results never
7300
+ * share a Turn and its credentials with another Actor or with watch Events.
7301
+ * Keep this id unique per Actor if either rule changes. The id is opaque.
7302
+ * It keeps the value that earlier releases wrote, because a queued result
7303
+ * from before a deploy is checked against it.
7304
+ */
7305
+ function resultAuthorId(actor) {
7306
+ switch (actor.platform) {
7307
+ case "system": return `agent-invocation:system:${actor.name}`;
7308
+ case "slack": return `agent-invocation:slack:${actor.teamId}:${actor.userId}`;
7309
+ default: return `agent-invocation:${actor.platform}:${actor.userId}`;
7310
+ }
7311
+ }
7312
+ /** Read the Actor of the child Turn that a reply or message carries. */
7313
+ function senderActorFromMetadata(metadata) {
7314
+ const parsed = senderActorMetadataSchema.safeParse(metadata);
7315
+ return parsed.success ? parsed.data.actor : void 0;
7316
+ }
7317
+ /**
7318
+ * Run each child reply or message as the Actor of the child Turn that sent
7319
+ * it, which the input carries, so the parent never gets more authority than
7320
+ * that Turn. A parent message from the stored parent runs as the Actor of the
7321
+ * parent's Turn, with its grants and text. Input that a Turn with another
7322
+ * Actor sent, or that names no child of this Conversation, runs as the Event
7323
+ * system Actor. Input that `isDroppedChildInput` drops is left out. Returns
7324
+ * undefined when no input is left.
7325
+ */
7326
+ async function withSenderActors(work) {
7327
+ if (work.kind !== "mailbox") return work;
7328
+ const dropFacts = await readChildInputDropFacts(work.batch.map((entry) => entry.message));
7329
+ const kept = (await mapBounded(work.batch, async (entry) => {
7330
+ const parentMessage = readParentMessage(entry.message);
7331
+ if (parentMessage) {
7332
+ if (isDroppedChildInput(entry.message, dropFacts)) {
7333
+ logDroppedParentMessage(entry.message, parentMessage);
7334
+ return;
7335
+ }
7336
+ const text = await parentMessageText(entry.message, parentMessage);
7337
+ return {
7338
+ ...entry,
7339
+ actor: parentMessage.actor,
7340
+ requestText: entry.message.input.text.trim(),
7341
+ ...parentMessage.credentialContext ? { credentialContext: parentMessage.credentialContext } : void 0,
7342
+ message: {
7343
+ ...entry.message,
7344
+ input: {
7345
+ ...entry.message.input,
7346
+ text
7347
+ }
7348
+ }
7349
+ };
7350
+ }
7351
+ const input = childAgentInput(entry.message);
7352
+ if (!input) return entry;
7353
+ if (isDroppedChildInput(entry.message, dropFacts)) return;
7354
+ const sender = await getChildAgentInputSender(entry.message, input);
7355
+ const actor = senderActorFromMetadata(entry.message.input.metadata);
7356
+ if (!sender || !actor || entry.message.input.authorId !== resultAuthorId(actor)) return {
7357
+ ...entry,
7358
+ actor: EVENT_SYSTEM_ACTOR
7049
7359
  };
7050
7360
  return {
7051
- actor,
7052
- author: webMessageAuthor(actor),
7053
- message: entry.message,
7054
- source: createWebSource(entry.message.conversationId)
7361
+ ...entry,
7362
+ actor
7055
7363
  };
7056
- });
7364
+ })).filter((entry) => entry !== void 0);
7365
+ return kept.length > 0 ? {
7366
+ kind: "mailbox",
7367
+ batch: kept
7368
+ } : void 0;
7369
+ }
7370
+ // src/chat/child-agents/list.ts
7371
+ const childConversationKindSchema = z.enum(["thread", "task"]);
7372
+ /** Bound the child agents that one listing reads. */
7373
+ const CHILD_AGENT_LIST_LIMIT = 200;
7374
+ /**
7375
+ * List the direct child agents of one parent Conversation, with the newest
7376
+ * activity first. The state comes from each child's Turns and mailbox, not
7377
+ * from model output. Each child agent stores its agent config, so older
7378
+ * children of a parent, such as ones that a removed feature created, are not
7379
+ * listed. A child is `stopped` while stopped, `running` while a Turn or
7380
+ * mailbox input that answers its parent is open, `failed` when its stored
7381
+ * execution failed, such as when its worker gave up and no Turn ended, and
7382
+ * else `idle`.
7383
+ * `lastResult` is how its newest finished Turn that was not stopped ended:
7384
+ * the status that `readTurnUpdate` gives it, or `failed`.
7385
+ */
7386
+ async function listChildAgents(parentConversationId) {
7387
+ const rows = await getSqlExecutor().db().select({
7388
+ agentName: juniorAgentBindings.name,
7389
+ archivedAt: juniorConversations.archivedAt,
7390
+ conversationId: juniorConversations.conversationId,
7391
+ executionStatus: juniorConversations.executionStatus,
7392
+ executionUpdatedAt: juniorConversations.executionUpdatedAt,
7393
+ kind: juniorConversations.kind,
7394
+ lastTurnOutcome: conversationLastTurnOutcomeSql(juniorConversations),
7395
+ stoppedAt: juniorConversations.stoppedAt,
7396
+ title: juniorConversations.title,
7397
+ updatedAt: juniorConversations.updatedAt
7398
+ }).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);
7399
+ const ids = rows.map((row) => row.conversationId);
7400
+ const [workStates, mailboxTurnSources] = await Promise.all([getConversationWorkStates(ids), listActiveMailboxTurnSources(ids)]);
7401
+ const pendingInput = (conversationId) => workStates.get(conversationId)?.execution.pendingMessages ?? [];
7402
+ const dropFacts = await readChildInputDropFacts(rows.flatMap((row) => row.stoppedAt ? [] : pendingInput(row.conversationId)));
7403
+ return rows.map((row) => {
7404
+ const kind = childConversationKindSchema.parse(row.kind);
7405
+ const stoppedAtMs = row.stoppedAt?.getTime();
7406
+ const running = stoppedAtMs === void 0 && runsOnConversationLoop(pendingInput(row.conversationId), mailboxTurnSources.get(row.conversationId) ?? [], dropFacts);
7407
+ const outcome = row.lastTurnOutcome;
7408
+ const lastResult = outcome === "failed" ? "failed" : outcome ? TURN_OUTCOME_STATUSES[outcome] : void 0;
7409
+ return {
7410
+ ...row.agentName ? { agentName: row.agentName } : void 0,
7411
+ ...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
7412
+ childConversationId: row.conversationId,
7413
+ kind,
7414
+ ...lastResult ? { lastResult } : void 0,
7415
+ status: stoppedAtMs !== void 0 ? "stopped" : running ? "running" : row.executionStatus === "failed" ? "failed" : "idle",
7416
+ ...row.title ? { title: row.title } : void 0,
7417
+ updatedAtMs: (row.executionUpdatedAt ?? row.updatedAt).getTime()
7418
+ };
7419
+ }).sort((left, right) => right.updatedAtMs - left.updatedAtMs);
7420
+ }
7421
+ /** List the ids of the child agents of one parent that have open work. */
7422
+ async function listOpenChildAgents(parentConversationId) {
7423
+ return (await listChildAgents(parentConversationId)).filter((child) => child.status === "running").map((child) => child.childConversationId);
7057
7424
  }
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
7425
  /**
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.
7426
+ * Return whether a child has work that will answer its parent: `pending`
7427
+ * input that waits in the mailbox until its Turn commits it, such as a Watch
7428
+ * Event in its debounce window, or an open mailbox Turn. Every Turn of a
7429
+ * child answers its parent, whoever started it.
7069
7430
  */
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);
7431
+ function runsOnConversationLoop(pending, mailboxTurnSources, dropFacts) {
7432
+ return mailboxTurnSources.length > 0 || pending.some((message) => !isDroppedChildInput(message, dropFacts));
7075
7433
  }
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
- });
7434
+ /**
7435
+ * List the ids of a child's open Turns on the Conversation loop. A Turn keeps
7436
+ * its input in the mailbox until it commits it, so before its first
7437
+ * checkpoint its id comes from its first input. Attempt selection can take
7438
+ * any pending input first, so each one gives a candidate id.
7439
+ */
7440
+ async function listOpenLoopTurnIds(conversationId) {
7441
+ const [turns, work] = await Promise.all([listActiveMailboxTurns(conversationId), getConversationWorkState({ conversationId })]);
7442
+ return [...turns.map((turn) => turn.turnId), ...(work?.execution.pendingMessages ?? []).map((message) => buildDeterministicTurnId(message.inboundMessageId))];
7443
+ }
7444
+ async function listAnsweredLoopChildren(children, parentMessages) {
7445
+ if (children.length === 0 || parentMessages.length === 0) return [];
7446
+ return (await mapBounded(children, async ({ childConversationId }) => {
7447
+ const turnIds = await listOpenLoopTurnIds(childConversationId);
7448
+ return parentMessages.some(({ sender }) => sender.conversationId === childConversationId && turnIds.includes(sender.turnId)) ? childConversationId : void 0;
7449
+ })).filter((id) => id !== void 0);
7094
7450
  }
7095
7451
  /**
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.
7452
+ * List the other child agents of one parent that still run and have not
7453
+ * answered. A running child whose open Turn's result is already among
7454
+ * `parentMessages`, the child replies and results that reached the parent's
7455
+ * mailbox, has answered, so it does not count.
7099
7456
  */
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
- });
7457
+ async function listUnreportedSiblingAgents(parentConversationId, childConversationId, parentMessages) {
7458
+ const running = (await listChildAgents(parentConversationId)).filter((child) => child.childConversationId !== childConversationId && child.status === "running");
7459
+ const answered = new Set(await listAnsweredLoopChildren(running, parentMessages));
7460
+ return running.filter((child) => !answered.has(child.childConversationId));
7113
7461
  }
7114
7462
  /**
7115
- * Select web, event, or parent work from new mailbox input or a saved Turn.
7116
- * Saved Actor data identifies a resumed event Turn.
7463
+ * List every child agent below one Conversation, at any depth. A parent owns
7464
+ * the work of its child agents and of their child agents. The list never has
7465
+ * the Conversation itself, its parent, or a sibling.
7117
7466
  */
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
7467
+ async function listDescendantAgents(conversationId) {
7468
+ return (await getSqlExecutor().db().select({
7469
+ conversationId: juniorConversations.conversationId,
7470
+ name: juniorAgentBindings.name
7471
+ }).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) => ({
7472
+ conversationId: row.conversationId,
7473
+ ...row.name ? { name: row.name } : void 0
7474
+ }));
7475
+ }
7476
+ /**
7477
+ * List the agents that one Conversation can see. A root Conversation sees
7478
+ * only its child agents. A child agent also sees itself, its parent, and the
7479
+ * other child agents of its parent.
7480
+ */
7481
+ async function listAgentRelatives(input) {
7482
+ const { conversationId, parentConversationId } = input;
7483
+ const [children, family, parent] = await Promise.all([
7484
+ listChildAgents(conversationId),
7485
+ parentConversationId ? listChildAgents(parentConversationId) : [],
7486
+ parentConversationId ? getConversationStore().get({ conversationId: parentConversationId }) : void 0
7487
+ ]);
7488
+ const self = family.find((agent) => agent.childConversationId === conversationId);
7489
+ return {
7490
+ children,
7491
+ ...parent ? { parent: {
7492
+ conversationId: parent.conversationId,
7493
+ status: parent.execution.status,
7494
+ updatedAtMs: parent.execution.updatedAtMs ?? parent.updatedAtMs
7495
+ } } : void 0,
7496
+ ...self ? { self } : void 0,
7497
+ siblings: family.filter((agent) => agent.childConversationId !== conversationId)
7133
7498
  };
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
7499
  }
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 };
7500
+ // src/chat/child-agents/markers.ts
7501
+ const SUBAGENT_KIND = "agent";
7502
+ const SUBAGENT_STARTED_KEY_PREFIX = "subagent_started:";
7503
+ const SUBAGENT_ENDED_KEY_PREFIX = "subagent_ended:";
7504
+ /**
7505
+ * Record in the parent Conversation that a child agent got one task or
7506
+ * message. Write it before the input reaches the child's mailbox, so the
7507
+ * child cannot end first.
7508
+ */
7509
+ async function recordSubagentStartedMarker(start) {
7510
+ await getConversationEventStore().append(start.parentConversationId, [{
7511
+ idempotencyKey: `${SUBAGENT_STARTED_KEY_PREFIX}${start.markerId}`,
7512
+ data: {
7513
+ type: "subagent_started",
7514
+ subagentInvocationId: start.markerId,
7515
+ subagentKind: SUBAGENT_KIND,
7516
+ childConversationId: start.childConversationId,
7517
+ ...start.agentName ? { agentName: start.agentName } : void 0,
7518
+ parentToolCallId: start.parentToolCallId,
7519
+ task: start.input,
7520
+ ...start.title ? { title: start.title } : void 0,
7521
+ ...start.reasoningLevel ? { reasoningLevel: start.reasoningLevel } : void 0
7522
+ },
7523
+ createdAtMs: start.createdAtMs
7524
+ }]);
7525
+ }
7526
+ /**
7527
+ * Record in the parent Conversation how the work of a child agent ended.
7528
+ * Each parent message has its own `subagent_started` marker, named by the
7529
+ * message id, and each one that the child already took ends with `outcome`.
7530
+ * A parent message that still waits in the child's mailbox stays open,
7531
+ * because later work reads it, unless `includeWaiting` is set, as for a stop
7532
+ * that skips it. Write it before the child's result reaches the parent.
7533
+ */
7534
+ async function recordChildAgentEnded(childConversationId, outcome, options = {}) {
7535
+ if (!await readAgentConfig(childConversationId)) return;
7536
+ const work = await getConversationWorkState({
7537
+ conversationId: childConversationId,
7538
+ state: options.state
7539
+ });
7540
+ const running = new Set(work?.runningInboundMessageIds);
7541
+ const waiting = new Set(options.includeWaiting ? [] : (work?.messages ?? []).map((message) => message.inboundMessageId).filter((id) => !running.has(id)));
7542
+ const taken = (work?.execution.inboundMessageIds ?? []).filter((id) => !waiting.has(id));
7543
+ if (taken.length === 0) return;
7544
+ const sender = await readChildConversationSender(childConversationId);
7545
+ if (!sender) return;
7546
+ 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}`]))));
7547
+ const found = new Set(keys.map((row) => row.idempotencyKey));
7548
+ const open = taken.filter((id) => found.has(`${SUBAGENT_STARTED_KEY_PREFIX}${id}`) && !found.has(`${SUBAGENT_ENDED_KEY_PREFIX}${id}`));
7549
+ if (open.length > 0) await appendSubagentEnded(sender.parentConversationId, open, outcome, options.nowMs ?? Date.now());
7550
+ }
7551
+ async function appendSubagentEnded(parentConversationId, markerIds, outcome, createdAtMs) {
7552
+ await getConversationEventStore().append(parentConversationId, markerIds.map((id) => ({
7553
+ idempotencyKey: `${SUBAGENT_ENDED_KEY_PREFIX}${id}`,
7554
+ data: {
7555
+ type: "subagent_ended",
7556
+ subagentInvocationId: id,
7557
+ outcome
7558
+ },
7559
+ createdAtMs
7560
+ })));
7561
+ }
7562
+ export { deleteWebAuthorization as $, normalizeConversationText as $n, ToolActionReviewUnavailableError as $r, listWorkspaceNamesByRepository as $t, resumeForPersonInput as A, recordAgentsInstructionsUpdated as An, recordTurnSummary as Ar, readTaskInstructions as At, turnInputFactsFromConversationMessage as B, appendConversationMessages as Bn, TurnToolCallLimitExceededError as Br, isCooperativeTurnYieldError as Bt, getChildAgentLockName as C, writeAgentHistory as Cn, pauseLostWorkerTurn as Cr, buildPromptInput as Ct, notInheritedByForkChild as D, loadConversationProjection as Dn, failTurnRecord as Dr, loadPromptTurnContext as Dt, isInheritedForkHistory as E, loadConnectedMcpProviders as En, completeTurnRecord as Er, instructionForInputs as Et, getAuthPausedConversationTurnId as F, recordGuardianActionReviewed as Fn, turnTerminalKey as Fr, ConversationTurnBoundaryError as Ft, getTurnUserSlackMessageTs as G, resolveConversationTitle as Gn, captureTurnFailure as Gr, markTurnFailed as Gt, getTurnUserMessage as H, persistConversationMessageWindow as Hn, createTurnLimitGate as Hr, isTurnInputDeferredError as Ht, getEventBatchDelayMs as I, recordMcpProviderConnected as In, GATED_TURN_LIMIT_WRAP_UP_MESSAGE as Ir, CooperativeTurnYieldError as It, getPersistedThreadState as J, estimateConversationMessagesTokens as Jn, requireTurnFailureEventId as Jr, buildDeterministicTurnId as Jt, getLocationConfigurationService as K, settleConversationTitleWork as Kn, finalizeFailedTurnReplyWithEvent as Kr, startActiveTurn as Kt, listActiveMailboxTurns as L, recordSkillLoaded as Ln, TURN_LIMIT_WRAP_UP_MESSAGE as Lr, TurnInputCommitLostError as Lt, session_stop_exports as M, recordAuthenticationLinked as Mn, getTurnLifecycle as Mr, readUserCustomization as Mt, stopConversationTree as N, recordAuthorizationCompleted as Nn, loadTurnStart as Nr, saveUserCustomization as Nt, enqueueAutomatedInput as O, loadConversationSkillNames as On, getTurnRecord as Or, turnRequestText as Ot, completeCancelledConversationTurn as P, recordAuthorizationRequested as Pn, turnStartedKey as Pr, addConversationNote as Pt, createWebAuthorization as Q, markConversationMessage as Qn, ToolActionReviewLimitError as Qr, getWorkspaceByName as Qt, resolveMailboxTurnWork as R, recordSubscribedReplyRoute as Rn, TurnBudgetExceededError as Rr, TurnInputDeferredError as Rt, getAgentReplyMessageId as S, withAgentRequest as Sn, lostWorkerBeforeFirstSave as Sr, assemblePrompt as St, getSpawnedChildConversationId as T, commitMessages as Tn, abandonTurnRecord as Tr, instructionActorFor as Tt, getTurnUserMessageId as U, persistConversationMessages as Un, isTurnExecutionLimitExceededError as Ur, markTurnClosed as Ut, legacyWebMailboxMetadataSchema as V, hydrateConversationMessages as Vn, buildTurnErrorResponse as Vr, isTurnInputCommitLostError as Vt, getTurnUserReplyAttachmentContext as W, toStoredConversationMessage as Wn, buildTurnFailureResponse as Wr, markTurnCompleted as Wt, persistThreadStateById as X, isHumanConversationMessage as Xn, isCutOffStopReason as Xr, deleteWorkspace as Xt, persistThreadRuntimeState as Y, getConversationMessageSlackTs as Yn, buildTurnResult as Yr, createWorkspace as Yt, coerceThreadConversationState as Z, latestConversationMessageSeq as Zn, ToolActionRejectedError as Zr, getWorkspace as Zt, dropWaitingParentMessages as _, configValueSchema as _i, renderAgentsInstructions as _n, canReusePendingAuthLink as _r, resolveBotSlackTeamId as _t, listDescendantAgents as a, ROOT_LINE_BREAK as ai, workspaceRepoCheckoutPath as an, calculateContextCompactionTargetTokens as ar, addQuietEventNote as at, readAgentConfig as b, foldSystemMessages as bn, continuableMessages as br, loadThreadContextCursor as bt, resultAuthorId as c, CODE_MODE_CALL_STATUS_TEXT as ci, setWorkspaceSnapshot as cn, getAgentContextInputLimitTokens as cr, eventBatchMessageMeta as ct, isStopResult as d, formatProviderLabel as di, buildDeploymentSystemPrompt as dn, createPluginAuthOrchestration as dr, eventAuthorText as dt, createToolActionReview as ei, listWorkspaces as en, recordDeliveredAssistantMessage as er, getWebAuthorization as et, readChildConversationSender as f, parseOAuthStatePayload as fi, AGENTS_REMOVAL_NOTICE as fn, authorizationId as fr, findTrustedUser as ft, commitParentMessageFork as g, validateConfigValue as gi, readRepositoryInstructions as gn, abandonReplacedPendingAuth as gr, resolveEventAuthor as gt, childAgentTurnOptions as h, validateConfigKey as hi, findVisibleAgentsInstructions as hn, AuthorizationPauseError as hr, parseEmail as ht, listChildAgents as i, RISK_LEVELS as ii, tryWorkspaceRepoCheckoutPath as in, upsertConversationMessage as ir, EVENT_WAIT_MS as it, saveHeldInput as j, recordAttachmentsDelivered as jn, ConversationTurnLifecycleService as jr, renderTaskInput as jt, getConversationStoppedAtMs as k, loadTurnProjection as kn, listTurnSummaries as kr, withoutSavedSteeringMessages as kt, withSenderActors as l, persistWithRetry as li, setWorkspaceSnapshotBuild as ln, createPluginEgress as lr, renderEventBatchInputs as lt, buildParentMessage as m, projectConversationEvents as mi, buildAgentsInstructionsMessage as mn, AuthorizationFlowDisabledError as mr, isTrustedSlackAuthor as mt, recordSubagentStartedMarker as n, getToolActionRejectionMarker as ni, updateWorkspace as nn, trimConversationMessages as nr, loadInboxItemInput as nt, listOpenChildAgents as o, USER_AUTHORIZATION_LEVELS as oi, invalidateReadySnapshot as on, getAgentBackgroundCompactionMarkTokens as or, createEventInboundMessage as ot, appendParentMessage as p, startOAuthFlow as pi, AGENTS_REPLACEMENT_NOTICE as pn, AuthPausePersistenceError as pr, isAllowedDomain as pt, getPersistedSandboxState as q, conversationAuthorDisplayName as qn, getAgentTurnDiagnosticsAttributes as qr, buildDeterministicAssistantMessageId as qt, listAgentRelatives as r, restoreToolActionRejections as ri, WorkspaceValidationError as rn, turnHasReply as rr, savedInputInstruction as rt, listUnreportedSiblingAgents as s, CODEMODE_TOOL_NAME as si, loadSnapshotsForProfile as sn, getAgentContextCompactionTriggerTokens as sr, enqueueEventNotification as st, recordChildAgentEnded as t, reviewToolActions as ti, listWorkspacesByRepository as tn, renderConversationMessageLine as tr, eventInboxItemInputs as tt, isChildAgentEvent as u, deliverOAuthAuthorization as ui, isExperimentalFeatureEnabled as un, PluginCredentialFailureError as ur, timerWatchCredentialSubject as ut, isParentMessageAuthor as v, showsAgentsInstructions as vn, clearPendingAuth as vr, isHeldInputMessage as vt, getPersonStopTurnId as w, commitAcceptedReply as wn, saveTurnCheckpoint as wr, buildSteeringPiMessage as wt, getAgentMessageId as x, readAgentHistory as xn, loadTurnCheckpoint as xr, loadThreadContextTrimFloor as xt, agentConfigSchema as y, foldLeadingSystemMessages as yn, getConversationPendingAuth as yr, withHeldInput as yt, sourceFromTurnInput as z, recordToolExecutionStarted as zn, TurnSliceLimitExceededError as zr, getConversationTurnBoundaryError as zt };