@sentry/junior 0.317.0 → 0.318.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 (74) hide show
  1. package/dist/{admin-CAugg87B.js → admin-UOHix_5P.js} +1 -1
  2. package/dist/{agent-runner-AjrEV6Qe.js → agent-runner-DeYymwh2.js} +183 -113
  3. package/dist/{agent-update-delivery-B_YIZcgf.js → agent-update-delivery-DH8bx7jU.js} +5 -5
  4. package/dist/api/schema.d.ts +42 -28
  5. package/dist/api/schema.js +3 -3
  6. package/dist/api.js +38 -41
  7. package/dist/{app-MoNAsVV5.d.ts → app-DKAOuaoC.d.ts} +4 -9
  8. package/dist/app.d.ts +1 -1
  9. package/dist/app.js +62 -91
  10. package/dist/{thread-context-CqZDKErp.js → auth-pause-state-f9hJM_zO.js} +6 -59
  11. package/dist/{catalog-runtime-DfSpJZdY.js → catalog-runtime-BfdAnztW.js} +1 -1
  12. package/dist/{channel-access-j-YAVYK4.js → channel-access-A0de5lRv.js} +1 -1
  13. package/dist/{chat-core-engine-aH85nEHv.js → chat-core-engine-D3Wd7f5n.js} +6 -6
  14. package/dist/{child-message-DHjQLEd1.js → child-message-peFWLcCZ.js} +1 -5
  15. package/dist/cli/chat.js +32 -24
  16. package/dist/cli/check.js +4 -4
  17. package/dist/cli/main.js +2 -2
  18. package/dist/cli/plugins.js +4 -4
  19. package/dist/cli/snapshot-create.js +4 -5
  20. package/dist/cli/upgrade.js +3 -3
  21. package/dist/context-BKF_5zzI.js +1833 -0
  22. package/dist/{continue-in-slack-D-FZ8Fin.js → continue-in-slack-YxwMQVeR.js} +3 -2
  23. package/dist/{conversation-feed--9S0_PXL.js → conversation-feed-Cj7IuBtM.js} +1 -1
  24. package/dist/{conversation-privacy-B1uXn5sf.js → conversation-privacy-Cr_dNW1p.js} +1 -1
  25. package/dist/{conversation-turn-BUE_7xaN.js → conversation-turn-Bru4w_FD.js} +111 -18
  26. package/dist/{create-DoDIYgtZ.js → create-Btl1y1rq.js} +13 -15
  27. package/dist/{credential-sync-BJOqGnjV.js → credential-sync-DTarZ63K.js} +17 -17
  28. package/dist/{db-BFmyYZtJ.js → db-of6e3sGt.js} +1943 -1189
  29. package/dist/{deployment-DXq9ZLU4.js → deployment-C0qXa0FD.js} +1 -1
  30. package/dist/{engine-context-CgQ7mlHt.js → engine-context-C_QL_bMQ.js} +52 -21
  31. package/dist/{html-B3VKTGbJ.js → html-9_pS9SjY.js} +6 -6
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{job-runner-A1lCkybD.js → job-runner-B2XEvpif.js} +11 -12
  34. package/dist/{lineage-Bktb0UcV.js → lineage-nh4z9iQN.js} +1 -1
  35. package/dist/{list-Bxvg5wXf.js → list-HRP3TIRl.js} +45 -37
  36. package/dist/{logging--smS7XRK.js → logging-BnOG0qz2.js} +3 -49
  37. package/dist/{mailbox-turn-uSXhUFc9.js → mailbox-turn-Byrry9o1.js} +220 -223
  38. package/dist/{parent-result-Ck1rFYRQ.js → markers-CTTtJqYn.js} +84 -52
  39. package/dist/{message-BNenhsmB.js → message-BRUuLgrY.js} +9 -10
  40. package/dist/{model-input-BReSnwHp.js → model-input-CFC62mf-.js} +2 -2
  41. package/dist/nitro.d.ts +1 -1
  42. package/dist/nitro.js +4 -4
  43. package/dist/{oauth-callback-server-CE4soEIY.js → oauth-callback-server-CjnnUr4o.js} +2 -2
  44. package/dist/{oauth-relay-C36gX1gH.js → oauth-relay-BvHFH0fV.js} +1 -1
  45. package/dist/{profile-BQ-iBDsZ.js → profile-iHw1uu32.js} +7 -7
  46. package/dist/{prompt-Dv7gkpD6.js → prompt-DEkStuxG.js} +10 -10
  47. package/dist/{registry-iXMT5Jmh.js → registry-Cl7Labpe.js} +7 -7
  48. package/dist/{reports-WKHfGTsU.js → reports-C1d9azyV.js} +2 -2
  49. package/dist/{resolve-tony4ibz.js → resolve-DC6zBuDV.js} +5 -5
  50. package/dist/{result-Bta_dlWa.js → result-DxewDuXb.js} +12 -12
  51. package/dist/{run-conversation-DL6ru7iW.js → run-conversation-Cz2ubZK-.js} +6 -5
  52. package/dist/{runner-BstDRbD9.js → runner-99YxVN_r.js} +10 -18
  53. package/dist/{sandbox-egress-signals-oSJMJOnn.js → sandbox-egress-signals-CgoX5CTI.js} +1 -1
  54. package/dist/{schema-DfqrHACA.js → schema-BTojNBr5.js} +2 -2
  55. package/dist/{sender-actors-CPglLd5R.js → sender-actors-77zTQbSG.js} +7 -6
  56. package/dist/{service-account-CTV_jaNu.js → service-account-YDCPSByj.js} +3 -3
  57. package/dist/{skills-BCEU41zM.js → skills-CleC0Hze.js} +5 -4
  58. package/dist/{slack-conversation-unfurl-DxVmhbGP.js → slack-conversation-unfurl-BNQLC12R.js} +7 -7
  59. package/dist/{spawn-frczVPIr.js → spawn-DuZfodPa.js} +7 -10
  60. package/dist/{system-prompt-table-CiXy0eNR.js → system-prompt-table-Ci6Ck4gk.js} +2 -2
  61. package/dist/{task-runner-C9Yc2_ae.js → task-runner-BJ9Up3bG.js} +18 -15
  62. package/dist/{topics-SRN7IVX-.js → topics-BoCkoPJJ.js} +2 -5
  63. package/dist/{turn-membership-CENFf3kI.js → turn-membership-VT7XZh-L.js} +4 -4
  64. package/dist/{turn-wake-BhloiI2h.js → turn-wake-C7HeLHAM.js} +4 -4
  65. package/dist/{types-C4iC-IMC.js → types-DCzTAA63.js} +55 -49
  66. package/dist/{users-ByG5RCEJ.js → users-Cb9c1k9q.js} +1 -1
  67. package/dist/{validation-8gjfR91V.js → validation-BiUmWPhy.js} +1 -1
  68. package/dist/{version-BeZhWWBE.js → version-VEXiEcZu.js} +1 -1
  69. package/dist/version.js +1 -1
  70. package/dist/{worker-BqMQQNRk.js → worker-ChWYQdhm.js} +5 -5
  71. package/migrations/20261127002500_turn_discarded_usage/migration.sql +2 -0
  72. package/migrations/20261127002500_turn_discarded_usage/snapshot.json +73 -0
  73. package/package.json +5 -5
  74. package/dist/config-CHQ8X251.js +0 -2422
@@ -1,27 +1,27 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { A as retainRuntimeTurnContext, B as THREAD_CONTEXT_TAGS, D as isToolResultError, G as renderThreadContext, I as TURN_CONTEXT_TAG, L as mapBounded, M as trimTrailingAssistantMessages, O as isToolResultMessage, R as renderCurrentInstruction, T as isContinuablePiBoundary, V as authorAttrs, W as renderParentAgentTask, _ 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 } from "./prompt-Dv7gkpD6.js";
3
- import { Bo as credentialContextForActor, Bu as agentsInstructionsUpdatedEvent, Dc as getInboxItem, Dd as juniorWorkspaceRepos, Ed as juniorSnapshots, Ei as formatSlackLink, En as traceContextSchema, Es as isUserActor, Hs as isDmChannel, Ht as appendInboundMessage, Hu as conversationNoteEvent, Io as verifyTimerWatchCredentialSubject, Ji as createPluginCache, Js as sleep, Ka as fallbackShortTitle, Ku as getStateAdapter, Mi as getPluginUserPromptContributions, Mn as readParentMessage, N as claimProviderConversation, Od as juniorWorkspaces, Os as toStoredSlackActor, Pl as projectConversationMessages, Pn as isEventMailboxMetadata, Pu as completeText, Qd as juniorConversationEvents, Ro as JUNIOR_THREAD_STATE_TTL_MS, Ss as createActor, St as getRegistrations, Ti as escapeSlackMrkdwnText, Tn as releaseInboundMessage, Ui as pluginConfigValues, Uo as credentialSubjectSchema, Vt as appendAndEnqueueInboundMessage, Vu as authenticationLinkedEvent, Wd as juniorLocationConfigurations, Yu as addAgentTurnUsage, _i as postSlackEphemeralMessage, a as getDb, bf as getConfigDefaults, d as createSqlConversationEventStore, dc as findLinkedSlackUser, dd as parseSlackUserId, dl as eventGuidance, en as dropPendingMessages, eo as getEventCatalog, eu as dispatchInstructionsInvokeSkills, fc as findSlackUserByPrimaryEmail, fs as conversationSubtree, gd as parseSlackMessageTs, gf as juniorDestinations, hf as juniorUsers, i as getConversationStore, j as startLocationThread, jr as getVercelConversationWorkQueue, lf as juniorConversations, mn as takePendingEventMessages, mo as publishAgentUpdate, n as getConversationEventStore, nu as isPersonInput, o as getSqlExecutor, oc as SYSTEM_IDENTITY_ID, pn as stopConversationWork, ps as conversationSubtreeColumns, qa as generateShortTitle, qs as withSlackRetries, qu as getStateValues, rd as nextDetailVersion, rn as getConversationWorkState, sc as resolveActorIdentityId, u as isPostgresErrorCode, v as withConversationEventLock, vi as postSlackMessage, vs as findActorTimezone, xl as ToolInputError, xt as getPlugins, zs as getSlackClient, zu as JUNIOR_NATIVE_EVENT_NAMESPACE } from "./db-BFmyYZtJ.js";
4
- import { C as summarizeMessageText, E as withSpan, M as isNativeIdentityProvider, P as toOptionalString, b as setSpanAttributes, h as logWarn, k as formatSentryEventReference, m as logInfo, o as getActiveTraceContext, p as logException, t as buildTurnFailureResponse, v as serializeGenAiAttribute } from "./logging--smS7XRK.js";
5
- 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-CiXy0eNR.js";
6
- 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-BQ-iBDsZ.js";
7
- import { C as resolveGatewayModel, G as isCompactionSummaryText, J as createProviderError, N as fenceLock, P as withLock, X as getProviderErrorAttributes, Y as findProviderError, Z as getProviderErrorUserMessage, f as TURN_REASONING_LEVELS, i as getSlackBotToken, j as MUTATION_LOCK_TTL_MS, k as createCache, n as getChatConfig, q as createAssistantProviderError, t as botConfig, z as estimateTextTokens } from "./config-CHQ8X251.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-C4iC-IMC.js";
9
- import { n as pluginCatalogRuntime } from "./catalog-runtime-DfSpJZdY.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";
10
10
  import { t as isMissingVirtualModule } from "./virtual-module-BeKA_EII.js";
11
11
  import { r as userCustomizationTextSchema, s as isVisionImageMediaType } from "./user-customization-CvfuY9Eo.js";
12
- import { a as parseSkillFile, i as openAiPolicyDisablesImplicitInvocation } from "./skills-BCEU41zM.js";
13
- import { a as toCanonicalInputMessage } from "./conversation-privacy-B1uXn5sf.js";
14
- import { i as lookupSlackUserProfile, t as lookupActiveSlackWorkspaceMember } from "./users-ByG5RCEJ.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
15
  import * as z from "zod";
16
16
  import { getCurrentSystemMessage, getSystemMessageText } from "@earendil-works/pi-ai/compat";
17
17
  import path from "node:path";
18
- import { isDeepStrictEqual } from "node:util";
19
- import { createHash, randomBytes, randomUUID } from "node:crypto";
20
- import { isRetryableAssistantError, renderSystemMessageUpdate } from "@earendil-works/pi-ai";
21
- import { actorSchema, agentEventKeys, createEventSource, createLocalSource, createWebSource, destinationSchema, escapeClosingTag, escapeClosingTags, escapeTagText, escapeTagTextAndQuotes, findTag, indentTagLines, readTag, renderInlineTag, renderTag, sourceSchema, startsWithTag, tagJson, unescapeClosingTag, unescapeClosingTags } from "@sentry/junior-plugin-api";
22
18
  import { and, asc, desc, eq, inArray, isNull, like, lt, lte, ne, or, sql } from "drizzle-orm";
23
19
  import { alias } from "drizzle-orm/pg-core";
20
+ 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
+ import { isDeepStrictEqual } from "node:util";
22
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
24
23
  import pLimit from "p-limit";
24
+ import { isRetryableAssistantError, renderSystemMessageUpdate } from "@earendil-works/pi-ai";
25
25
  // src/chat/configuration/types.ts
26
26
  /** JSON value accepted by Location configuration. */
27
27
  const configValueSchema = z.json();
@@ -684,6 +684,56 @@ function restoreToolActionRejections(messages) {
684
684
  }
685
685
  return priorRejections;
686
686
  }
687
+ // src/chat/guardian/request.ts
688
+ /**
689
+ * Build the Guardian request from what core knows about one batch.
690
+ *
691
+ * Code only labels and orders facts here (`facts-from-junior`). It decides
692
+ * who wrote each message from the Run's Source and the author labels of the
693
+ * root Conversation, never from what the text says.
694
+ */
695
+ /**
696
+ * Whose words the current message of the Run is. An agent's brief passed
697
+ * Guardian when it was sent, so it is the instruction of this Run
698
+ * (`brief-is-instruction`). A person's Source with a system Actor, such as
699
+ * an Event Turn, is an Event.
700
+ */
701
+ function currentAuthor(context) {
702
+ const author = instructionAuthor(context.source);
703
+ return author === "person" && context.actor.platform === "system" ? "event" : author;
704
+ }
705
+ /**
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.
714
+ */
715
+ function guardianMessages(proposal) {
716
+ const { context, rootConversation } = proposal;
717
+ const author = currentAuthor(context);
718
+ const messages = [];
719
+ if (author === "automation") messages.push({
720
+ from: "instruction",
721
+ text: context.userIntent
722
+ });
723
+ if (rootConversation?.truncated) messages.push({
724
+ from: "context",
725
+ text: "[Older messages are not shown.]"
726
+ });
727
+ for (const message of rootConversation?.messages ?? []) messages.push({
728
+ from: message.author === "user" ? "instruction" : message.author === "other person" ? "other_person" : "context",
729
+ text: message.text
730
+ });
731
+ if (!rootConversation?.messages.some((message) => message.author === "user" && message.text === context.userIntent) && author !== "automation" && context.userIntent) messages.push({
732
+ from: author === "event" ? "context" : "instruction",
733
+ text: context.userIntent
734
+ });
735
+ return messages;
736
+ }
687
737
  // src/chat/guardian/gate.ts
688
738
  const ACTION_CONFIRMATION_INSTRUCTIONS = [
689
739
  "The action was not executed because explicit user confirmation is required.",
@@ -714,9 +764,7 @@ var ToolActionRejectedError = class extends Error {
714
764
  decision;
715
765
  reason;
716
766
  reviewedAction;
717
- riskLevel;
718
767
  rule;
719
- userAuthorization;
720
768
  constructor(decision, reason, assessment = {}) {
721
769
  const instructions = assessment.instructions ?? (decision === "ask" ? ACTION_CONFIRMATION_INSTRUCTIONS : ACTION_DENIAL_INSTRUCTIONS);
722
770
  super(`${instructions}\nReason: ${reason}`);
@@ -724,9 +772,7 @@ var ToolActionRejectedError = class extends Error {
724
772
  this.decision = decision;
725
773
  this.reason = reason;
726
774
  this.reviewedAction = assessment.reviewedAction;
727
- this.riskLevel = assessment.riskLevel;
728
775
  this.rule = assessment.rule;
729
- this.userAuthorization = assessment.userAuthorization;
730
776
  }
731
777
  };
732
778
  /** Required review could not run, so the action was not executed. */
@@ -880,9 +926,7 @@ function projectedRejection(proposal, decision) {
880
926
  decision: decision.decision,
881
927
  input,
882
928
  reason: decision.reason,
883
- riskLevel: decision.riskLevel,
884
- tool: proposal.tool,
885
- userAuthorization: decision.userAuthorization
929
+ tool: proposal.tool
886
930
  };
887
931
  }
888
932
  /** A core tool stays outside review unless it opts in. Plugin tools default to `auto`. */
@@ -896,10 +940,25 @@ async function prepareToolActionReview(action, context, priorRejections) {
896
940
  const resolved = await tool.resolveApprovalMetadata?.(input);
897
941
  if (tool.approvalMode === "auto" && !autoActionNeedsReview(tool, resolved)) return;
898
942
  assertAuthoritativeContext(context);
899
- return buildProposal(action.toolName, tool, input, resolved, context, priorRejections, await context.rootConversation?.(), action.script);
943
+ const proposal = buildProposal(action.toolName, tool, input, resolved, context, priorRejections, await context.rootConversation?.(), action.script);
944
+ return {
945
+ action: {
946
+ tool: proposal.tool.name,
947
+ input,
948
+ effect: "write",
949
+ summary: proposal.tool.proposalDescription ?? proposal.tool.name
950
+ },
951
+ proposal
952
+ };
953
+ }
954
+ /** Most actions of one batch that the gate prepares or records at the same time. */
955
+ const MAX_CONCURRENT_PREPARATIONS = 4;
956
+ function unavailableStep(error) {
957
+ return {
958
+ kind: "unavailable",
959
+ error: error instanceof ToolActionReviewUnavailableError ? error : new ToolActionReviewUnavailableError({ cause: error })
960
+ };
900
961
  }
901
- /** Most Guardian reviews of one batch that run at the same time. */
902
- const MAX_CONCURRENT_REVIEWS = 4;
903
962
  /** Create the core review path that prepares actions and enforces Guardian decisions. */
904
963
  function createToolActionReview(options) {
905
964
  const priorRejections = [...options.priorRejections ?? []];
@@ -912,38 +971,62 @@ function createToolActionReview(options) {
912
971
  */
913
972
  const attempts = /* @__PURE__ */ new Map();
914
973
  /**
915
- * Review one action and record its decision. Gate state does not change
916
- * here, so concurrent reviews in one batch cannot corrupt it.
974
+ * Prepare each action, send the proposals of the batch to Guardian at
975
+ * once, and record each decision. Gate state does not change here.
917
976
  */
918
- const reviewStep = async (action, rejections, signal) => {
919
- try {
920
- const proposal = await prepareToolActionReview(action, options.context, rejections);
921
- if (!proposal) return { kind: "skipped" };
922
- const decision = await options.reviewer.review(proposal, signal ? { signal } : {});
923
- await options.onDecision({
924
- toolCallId: action.toolCallId,
925
- toolName: proposal.tool.name,
926
- decision
927
- });
928
- return {
929
- kind: "reviewed",
930
- decision,
931
- proposal
932
- };
977
+ const reviewSteps = async (actions, signal) => {
978
+ const rejections = [...priorRejections];
979
+ const prepared = await mapBounded(actions, async (action) => {
980
+ try {
981
+ return await prepareToolActionReview(action, options.context, rejections) ?? { kind: "skipped" };
982
+ } catch (error) {
983
+ if (signal?.aborted) throw error;
984
+ return unavailableStep(error);
985
+ }
986
+ }, MAX_CONCURRENT_PREPARATIONS);
987
+ const reviews = prepared.filter((entry) => !("kind" in entry));
988
+ let decisions = [];
989
+ let failure;
990
+ if (reviews.length > 0) try {
991
+ decisions = await options.guardian({ proposals: reviews.map((review) => review.proposal) }).review({
992
+ actions: reviews.map((review) => review.action),
993
+ messages: guardianMessages(reviews[0].proposal)
994
+ }, signal ?? new AbortController().signal);
995
+ if (decisions.length !== reviews.length) throw new Error("Guardian must return one Review per action.");
933
996
  } catch (error) {
934
997
  if (signal?.aborted) throw error;
998
+ failure = error;
999
+ }
1000
+ let next = 0;
1001
+ const indexes = prepared.map((entry) => "kind" in entry ? void 0 : next++);
1002
+ const steps = await mapBounded(prepared, async (entry, index) => {
1003
+ if ("kind" in entry) return entry;
1004
+ if (failure !== void 0) return unavailableStep(failure);
1005
+ const decision = decisions[indexes[index]];
1006
+ try {
1007
+ await options.onDecision({
1008
+ toolCallId: actions[index].toolCallId,
1009
+ toolName: entry.proposal.tool.name,
1010
+ decision
1011
+ });
1012
+ } catch (error) {
1013
+ return unavailableStep(error);
1014
+ }
935
1015
  return {
936
- kind: "unavailable",
937
- error: error instanceof ToolActionReviewUnavailableError ? error : new ToolActionReviewUnavailableError({ cause: error })
1016
+ kind: "reviewed",
1017
+ decision,
1018
+ proposal: entry.proposal
938
1019
  };
939
- }
1020
+ }, MAX_CONCURRENT_PREPARATIONS);
1021
+ signal?.throwIfAborted();
1022
+ return steps;
940
1023
  };
941
1024
  /**
942
1025
  * Count each attempt in the batch once, in batch order. An attempt with a
943
1026
  * rejection adds one to the count from before the attempt, also when it
944
1027
  * has allowed actions or spans several batches. An attempt with only
945
- * allowed actions resets the count. Skipped and unavailable actions do not
946
- * change it. Return the attempt state of each action.
1028
+ * allowed actions resets the count. Skipped and unavailable actions do
1029
+ * not change it. Return the attempt state of each action.
947
1030
  */
948
1031
  const countAttempts = (actions, steps) => {
949
1032
  const states = actions.map((action) => {
@@ -972,9 +1055,7 @@ function createToolActionReview(options) {
972
1055
  state.exhausted = true;
973
1056
  logException(new ToolActionReviewLimitError(), "guardian.action_review.exhausted", {
974
1057
  "app.guardian.decision": step.decision.decision,
975
- "app.guardian.risk_level": step.decision.riskLevel,
976
- ...step.decision.rule ? { "app.guardian.rule": step.decision.rule } : void 0,
977
- "app.guardian.user_consent": step.decision.userAuthorization,
1058
+ "app.guardian.rule": step.decision.rule,
978
1059
  "gen_ai.tool.name": step.proposal.tool.name,
979
1060
  "gen_ai.tool.call.id": actions[index].toolCallId
980
1061
  });
@@ -1002,26 +1083,21 @@ function createToolActionReview(options) {
1002
1083
  decision: decision.decision,
1003
1084
  priorRejection: reviewedAction,
1004
1085
  reason: reviewedAction.reason,
1005
- riskLevel: decision.riskLevel,
1006
- userAuthorization: decision.userAuthorization,
1007
1086
  version: 1
1008
1087
  });
1009
1088
  return {
1010
1089
  allowed: false,
1011
1090
  error: new ToolActionRejectedError(decision.decision, decision.reason, {
1012
1091
  instructions: rejectionInstructions(decision.decision, { exhausted }),
1013
- riskLevel: decision.riskLevel,
1014
1092
  reviewedAction,
1015
- rule: decision.rule,
1016
- userAuthorization: decision.userAuthorization
1093
+ rule: decision.rule
1017
1094
  })
1018
1095
  };
1019
1096
  };
1020
1097
  return {
1021
1098
  async review(actions, signal) {
1022
1099
  return await withSpan("guardian.action_review", "guardian.action_review", {}, async () => {
1023
- const rejections = [...priorRejections];
1024
- const steps = await mapBounded(actions, (action) => reviewStep(action, rejections, signal), MAX_CONCURRENT_REVIEWS);
1100
+ const steps = await reviewSteps(actions, signal);
1025
1101
  const states = countAttempts(actions, steps);
1026
1102
  return new Map(actions.map((action, index) => [action.toolCallId, settle(action.toolCallId, steps[index], states[index].exhausted)]));
1027
1103
  }, { "app.guardian.batch.size": actions.length });
@@ -1194,6 +1270,10 @@ function buildGatedTurnResult(input, answer) {
1194
1270
  };
1195
1271
  }
1196
1272
  // src/chat/services/turn-failure-response.ts
1273
+ /** Build the static user-facing response for a failed turn. */
1274
+ function buildTurnFailureResponse(eventId) {
1275
+ return `I ran into an internal error while processing that. Reference: ${formatSentryEventReference(eventId)}.`;
1276
+ }
1197
1277
  /** Require captured turn failures to carry a real Sentry event reference. */
1198
1278
  function requireTurnFailureEventId(eventId, eventName) {
1199
1279
  if (!eventId) throw new Error(`Sentry did not return an event ID for ${eventName}`);
@@ -2748,51 +2828,8 @@ function getAgentContextInputLimitTokens(modelId) {
2748
2828
  function getConversationContextCompactionTriggerTokens() {
2749
2829
  return calculateContextCompactionTriggerTokens(getModelContextBudget(botConfig.fastModelId));
2750
2830
  }
2751
- // src/chat/events/actor.ts
2752
- /**
2753
- * System author ID stamped on event mailbox messages.
2754
- *
2755
- * Keep this stable so conversation history can recognize the same system input
2756
- * for event Turns.
2757
- *
2758
- * TODO(dcramer): Delete this ID after resumes read event Source.kind
2759
- * from the Turn checkpoint instead of Message author data.
2760
- */
2761
- const EVENT_AUTHOR_ID = "UJRNEVENT";
2762
- /** System Message author for event input. */
2763
- const EVENT_MESSAGE_AUTHOR = {
2764
- fullName: "System event",
2765
- isBot: true,
2766
- userId: EVENT_AUTHOR_ID,
2767
- userName: "junior-event"
2768
- };
2769
- /** System execution actor for every event turn. */
2770
- const EVENT_SYSTEM_ACTOR = {
2771
- platform: "system",
2772
- name: "event"
2773
- };
2774
- /**
2775
- * Whether a saved Message started a event Turn.
2776
- *
2777
- * TODO(dcramer): Delete this marker check after deployed Turn cursors all store
2778
- * Source and Actor. `eventType` only supports saved synthetic Slack input.
2779
- */
2780
- function isEventConversationMessage(message) {
2781
- return Boolean(message.meta?.eventType) || isEventAuthorId(message.author?.userId);
2782
- }
2783
- /** Author id of an Event Message by a listed bot, which has no Identity. */
2784
- function eventBotAuthorId(provider, handle) {
2785
- return `${EVENT_AUTHOR_ID}:${provider}:${handle.toLowerCase()}`;
2786
- }
2787
- /** Whether an author id belongs to an Event Message, system or listed bot. */
2788
- function isEventAuthorId(id) {
2789
- return id === "UJRNEVENT" || Boolean(id?.startsWith(`UJRNEVENT:`));
2790
- }
2791
2831
  // src/chat/services/conversation-memory.ts
2792
2832
  const CONTEXT_MIN_LIVE_MESSAGES = 12;
2793
- const CONTEXT_MAX_MESSAGE_CHARS = 3200;
2794
- const THREAD_CONTEXT_MAX_CHARS = 6e4;
2795
- const THREAD_CONTEXT_OMITTED_NOTE = "Older Messages of this thread are not shown. Find them with a searchConversationEvents query, then read them with readConversationEvent.";
2796
2833
  const SLACK_USER_ID_DISPLAY_PATTERN = /^[UW][A-Z0-9]{5,}$/;
2797
2834
  /** Normalize message boundaries without changing transcript formatting. */
2798
2835
  function normalizeConversationText(text) {
@@ -2806,16 +2843,21 @@ function buildImageContextSuffix(message, conversation) {
2806
2843
  if (summaries.length === 0) return "";
2807
2844
  return ` [image context: ${escapeTagTextAndQuotes(summaries.join(" | "))}]`;
2808
2845
  }
2809
- function renderConversationMessageLine(message, conversation) {
2846
+ /**
2847
+ * Render one Message as a single escaped transcript line. `text` replaces the
2848
+ * Message text, such as when a caller cuts it to a budget.
2849
+ */
2850
+ function renderConversationMessageLine(message, conversation, text = message.text) {
2810
2851
  const displayName = escapeTagTextAndQuotes(conversationAuthorDisplayName(message));
2811
- const text = escapeTagTextAndQuotes(message.text.replace(/\s+/g, " ").slice(0, CONTEXT_MAX_MESSAGE_CHARS));
2852
+ const lineText = escapeTagTextAndQuotes(text.replace(/\s+/g, " "));
2812
2853
  const markers = [];
2813
2854
  if (message.meta?.replied === false) markers.push(escapeTagTextAndQuotes(`assistant skipped: ${message.meta?.skippedReason ?? "no-reply route"}`));
2814
2855
  if (message.meta?.explicitMention) markers.push("explicit mention");
2815
2856
  const markerSuffix = markers.length > 0 ? ` (${markers.join("; ")})` : "";
2816
2857
  const imageContext = buildImageContextSuffix(message, conversation);
2817
- return `[${message.role}] ${displayName}: ${text}${imageContext}${markerSuffix}`;
2858
+ return `[${message.role}] ${displayName}: ${lineText}${imageContext}${markerSuffix}`;
2818
2859
  }
2860
+ /** Return the name to show for a Message author, never a raw Slack id. */
2819
2861
  function conversationAuthorDisplayName(message) {
2820
2862
  const author = message.author;
2821
2863
  const fullName = authorDisplayField(author?.fullName, author?.userId);
@@ -2891,64 +2933,12 @@ function markConversationMessage(conversation, messageId, patch) {
2891
2933
  }
2892
2934
  };
2893
2935
  }
2894
- function isTakeOrDismissOnly(message) {
2895
- const changes = message.meta?.reviewItemChanges;
2896
- return Boolean(changes?.length && changes.every((change) => change.kind === "taken" || change.kind === "dismissed"));
2897
- }
2898
- function renderThreadContextMessage(message, conversation, index) {
2899
- return indentTagLines(renderTag("message", {
2900
- index,
2901
- sent_at: new Date(message.createdAtMs).toISOString(),
2902
- role: message.role,
2903
- ...authorAttrs({
2904
- authorId: message.author?.userId,
2905
- authorName: conversationAuthorDisplayName(message)
2906
- }),
2907
- slack_ts: message.meta?.slackTs
2908
- }, [renderConversationMessageLine(message, conversation)]), " ");
2909
- }
2910
- function isUntaggedThreadMessage(message) {
2911
- return message.role === "user" && !message.meta?.explicitMention && !isEventConversationMessage(message);
2912
- }
2913
2936
  /** Return the highest saved Message seq, the thread context cursor of a Turn. */
2914
2937
  function latestConversationMessageSeq(conversation) {
2915
2938
  let latest;
2916
2939
  for (const message of conversation.messages) if (message.seq !== void 0 && (latest ?? -1) < message.seq) latest = message.seq;
2917
2940
  return latest;
2918
2941
  }
2919
- /**
2920
- * Render the thread Messages that this Turn needs as one evidence-only block.
2921
- *
2922
- * With agent history, earlier Turns already hold their thread context, Turn
2923
- * input, and replies. So only untagged Messages saved after the cursor of the
2924
- * previous Turn are new. Without history, show the latest Messages. Both keep
2925
- * the newest Messages under one hard size cap, so the block cannot grow with
2926
- * the thread.
2927
- */
2928
- function buildConversationContext(conversation, options = {}) {
2929
- const { history } = options;
2930
- const candidates = conversation.messages.filter((entry) => !options.excludeMessageIds?.includes(entry.id) && !isTakeOrDismissOnly(entry) && (!history || isUntaggedThreadMessage(entry) && (history.afterSeq === void 0 || entry.seq === void 0 || entry.seq > history.afterSeq)));
2931
- let first = candidates.length;
2932
- let chars = 0;
2933
- while (first > 0) {
2934
- const size = renderThreadContextMessage(candidates[first - 1], conversation, first).length;
2935
- if (chars + size > THREAD_CONTEXT_MAX_CHARS) break;
2936
- chars += size;
2937
- first -= 1;
2938
- }
2939
- const shown = candidates.slice(first).map((message, index) => renderThreadContextMessage(message, conversation, index + 1));
2940
- const counts = {
2941
- shownMessages: shown.length,
2942
- omittedMessages: candidates.length - shown.length
2943
- };
2944
- if (shown.length === 0) return counts;
2945
- const lines = [renderThreadContext(shown)];
2946
- if (shown.length < candidates.length || !history && conversation.historyFromSeq !== void 0) lines.push(THREAD_CONTEXT_OMITTED_NOTE);
2947
- return {
2948
- ...counts,
2949
- text: lines.join("\n")
2950
- };
2951
- }
2952
2942
  /** Return the earliest human-authored message known for a thread. */
2953
2943
  function getThreadTitleSourceMessage(conversation) {
2954
2944
  let firstMessage;
@@ -3714,8 +3704,8 @@ async function recordGuardianActionReviewed(args) {
3714
3704
  toolName: args.toolName,
3715
3705
  ...args.costUsd !== void 0 ? { costUsd: args.costUsd } : void 0,
3716
3706
  decision: args.decision,
3717
- riskLevel: args.riskLevel,
3718
- userAuthorization: args.userAuthorization
3707
+ ...args.rule ? { rule: args.rule } : void 0,
3708
+ ...args.reason ? { reason: args.reason } : void 0
3719
3709
  },
3720
3710
  createdAtMs: Date.now()
3721
3711
  }]);
@@ -4262,45 +4252,9 @@ async function buildDeploymentSystemPrompt(platform, mode) {
4262
4252
  })).map((section) => section.text).join("\n\n");
4263
4253
  }
4264
4254
  // src/chat/experimental.ts
4265
- /**
4266
- * Known unstable product features that must be opted into explicitly.
4267
- * Add new keys here as features graduate from private experiments; remove them
4268
- * once they become stable defaults.
4269
- */
4270
- const EXPERIMENTAL_FEATURES = [
4271
- "operator-tools",
4272
- "passive-routing",
4273
- "user-customization"
4274
- ];
4275
- const EXPERIMENTAL_FEATURE_SET = new Set(EXPERIMENTAL_FEATURES);
4276
- let configuredExperimental = {};
4277
- function isExperimentalFeature(value) {
4278
- return EXPERIMENTAL_FEATURE_SET.has(value);
4279
- }
4280
- /** Replace app-level experimental opt-ins and return the previous setting. */
4281
- function setExperimentalFeatures(config) {
4282
- const previous = { ...configuredExperimental };
4283
- if (config === void 0) {
4284
- configuredExperimental = {};
4285
- return previous;
4286
- }
4287
- const next = {};
4288
- for (const [rawName, enabled] of Object.entries(config)) {
4289
- if (enabled === void 0) continue;
4290
- if (typeof enabled !== "boolean") throw new Error(`experimental.${rawName} must be a boolean when provided`);
4291
- if (!isExperimentalFeature(rawName)) throw new Error(`experimental.${rawName} is not a known experimental feature. Known features: ${EXPERIMENTAL_FEATURES.join(", ")}`);
4292
- next[rawName] = enabled;
4293
- }
4294
- configuredExperimental = next;
4295
- return previous;
4296
- }
4297
- /** Return a copy of the app-level experimental opt-ins configured by createApp(). */
4298
- function getExperimentalFeatures() {
4299
- return { ...configuredExperimental };
4300
- }
4301
4255
  /** Return whether one experimental feature is enabled via createApp({ experimental }). */
4302
4256
  function isExperimentalFeatureEnabled(feature) {
4303
- return configuredExperimental[feature] === true;
4257
+ return getChatConfig().experimental[feature] === true;
4304
4258
  }
4305
4259
  // src/chat/sandbox/snapshot/store.ts
4306
4260
  function builderNames(rows) {
@@ -5411,6 +5365,65 @@ async function assemblePrompt(args) {
5411
5365
  userContentParts
5412
5366
  };
5413
5367
  }
5368
+ // src/chat/conversations/thread-context.ts
5369
+ const CURSOR_TURN_LOOKBACK = 10;
5370
+ /**
5371
+ * Return the Message seq that the latest other finished Turn covered. A failed
5372
+ * or cancelled Turn may not have its prompt in agent history, so its cursor
5373
+ * does not count. Showing a Message again is safe; skipping one that the model
5374
+ * never saw is not.
5375
+ */
5376
+ async function loadThreadContextCursor(args) {
5377
+ const store = getConversationEventStore();
5378
+ const [started, completed] = await Promise.all([store.query(args.conversationId, {
5379
+ limit: CURSOR_TURN_LOOKBACK,
5380
+ types: ["turn_started"]
5381
+ }), store.query(args.conversationId, {
5382
+ limit: CURSOR_TURN_LOOKBACK,
5383
+ types: ["turn_completed"]
5384
+ })]);
5385
+ const finished = new Set(completed.events.flatMap((event) => event.data.type === "turn_completed" && event.data.outcome !== "cancelled" ? [event.data.turnId] : []));
5386
+ const previous = [...started.events].reverse().find((event) => event.data.type === "turn_started" && event.data.turnId !== args.turnId && finished.has(event.data.turnId));
5387
+ return previous?.data.type === "turn_started" ? previous.data.threadContextThroughSeq : void 0;
5388
+ }
5389
+ /**
5390
+ * Return the oldest cursor of the Turns that the cursor lookup reads. Messages
5391
+ * after it may still be in the thread context delta of the next Turn, also
5392
+ * when the latest Turns failed or the next Turn retries.
5393
+ */
5394
+ async function loadThreadContextTrimFloor(conversationId) {
5395
+ const cursors = (await getConversationEventStore().query(conversationId, {
5396
+ limit: CURSOR_TURN_LOOKBACK,
5397
+ types: ["turn_started"]
5398
+ })).events.flatMap((event) => event.data.type === "turn_started" && event.data.threadContextThroughSeq !== void 0 ? [event.data.threadContextThroughSeq] : []);
5399
+ return cursors.length > 0 ? Math.min(...cursors) : void 0;
5400
+ }
5401
+ // src/chat/conversations/held-input.ts
5402
+ /** Skip reason on the Message that saves input a stopped Conversation holds. */
5403
+ const STOPPED_CONVERSATION_SKIP_REASON = "stopped conversation";
5404
+ /** Return whether a Message saves input that a stopped Conversation held. */
5405
+ function isHeldInputMessage(message) {
5406
+ return message.meta?.skippedReason === STOPPED_CONVERSATION_SKIP_REASON;
5407
+ }
5408
+ /**
5409
+ * Put the input that a stopped Conversation held since the previous Turn
5410
+ * before the inputs of this Turn, so the Turn gets it as Turn input. The
5411
+ * cursor is read only when the Conversation holds input.
5412
+ */
5413
+ async function withHeldInput(args, instruction) {
5414
+ const held = args.conversation.messages.filter(isHeldInputMessage);
5415
+ if (held.length === 0) return instruction;
5416
+ const afterSeq = await loadThreadContextCursor(args);
5417
+ const inputs = held.filter((message) => afterSeq === void 0 || message.seq === void 0 || message.seq > afterSeq).map((message) => ({
5418
+ kind: "runtime",
5419
+ text: message.text
5420
+ }));
5421
+ if (inputs.length === 0) return instruction;
5422
+ return instructionForInputs([...inputs, ...instruction.inputs ?? [{
5423
+ kind: "person",
5424
+ text: instruction.text
5425
+ }]]);
5426
+ }
5414
5427
  // src/chat/inbox-items/prompt-input.ts
5415
5428
  /**
5416
5429
  * Prompt inputs for person answers to Inbox items. An answer is its own
@@ -5872,8 +5885,6 @@ async function cancelSignInPausedTurn(args) {
5872
5885
  }
5873
5886
  // src/chat/conversations/session-stop.ts
5874
5887
  var session_stop_exports = /* @__PURE__ */ __exportAll({ resumeForPersonInput: () => resumeForPersonInput });
5875
- /** Skip reason on the Message that saves input a stopped Conversation holds. */
5876
- const STOPPED_CONVERSATION_SKIP_REASON = "stopped conversation";
5877
5888
  /** Return when a Conversation stopped, or undefined when it is not stopped. */
5878
5889
  async function getConversationStoppedAtMs(conversationId) {
5879
5890
  const [row] = await getSqlExecutor().db().select({ stoppedAt: juniorConversations.stoppedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
@@ -6007,8 +6018,9 @@ async function resumeForPersonInput(conversationId, messages) {
6007
6018
  }
6008
6019
  /**
6009
6020
  * Save held input as one skipped Message, the Message that a Turn would save
6010
- * for it, so the next Turn reads it. The append is idempotent by Message id,
6011
- * and the Message takes the id of the first input.
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.
6012
6024
  */
6013
6025
  async function saveHeldInput(conversationId, messages) {
6014
6026
  const first = messages[0];
@@ -6062,19 +6074,6 @@ async function resolveBotSlackTeamId() {
6062
6074
  return await pending;
6063
6075
  }
6064
6076
  // src/chat/identities/trust.ts
6065
- let trustConfig = {
6066
- allowedBotUserIds: [],
6067
- allowedDomains: []
6068
- };
6069
- /** Apply the trust settings of one app. Return the previous settings. */
6070
- function setTrustConfig(next) {
6071
- const previous = trustConfig;
6072
- trustConfig = {
6073
- allowedBotUserIds: [...next.allowedBotUserIds],
6074
- allowedDomains: [...next.allowedDomains]
6075
- };
6076
- return previous;
6077
- }
6078
6077
  const emailSchema = z.string().trim().toLowerCase().pipe(z.email());
6079
6078
  /**
6080
6079
  * Parse a value that must be an email, such as a sign-in or a verified email
@@ -6108,7 +6107,7 @@ function isSlackProfileDomainAllowed(profile) {
6108
6107
  const email = profile.email?.trim();
6109
6108
  const separator = email?.lastIndexOf("@") ?? -1;
6110
6109
  const allowed = isAllowedDomain(separator > 0 ? email?.slice(separator + 1) : void 0, {
6111
- allowedDomains: trustConfig.allowedDomains,
6110
+ allowedDomains: getChatConfig().trust.allowedDomains,
6112
6111
  ifNoDomains: "allow"
6113
6112
  });
6114
6113
  if (!allowed) logWarn("slack.allowed_domain.rejected", { "app.reason": email ? "domain_not_allowed" : "missing_email" });
@@ -6208,7 +6207,7 @@ async function accountDecision(args) {
6208
6207
  async function isTrustedSlackAuthor(args) {
6209
6208
  const userId = parseSlackUserId(args.user);
6210
6209
  if (!userId || !args.teamId) return false;
6211
- const { allowedBotUserIds, allowedDomains } = trustConfig;
6210
+ const { allowedBotUserIds, allowedDomains } = getChatConfig().trust;
6212
6211
  if (allowedBotUserIds.includes(userId) || allowedDomains.length === 0) return true;
6213
6212
  return await createCache(args.state, "core").getOrLoad(`slack:allowed-domain:${args.teamId}:${userId}`, async () => {
6214
6213
  const profile = await lookupSlackUserProfile(userId);
@@ -6830,14 +6829,12 @@ async function dropWaitingParentMessages(conversationId, state) {
6830
6829
  for (const { message, parentMessage } of waiting) logDroppedParentMessage(message, parentMessage);
6831
6830
  }
6832
6831
  /**
6833
- * Read the stop of the child that received a parent message, when the
6834
- * message names the child's stored parent with that parent's author id.
6835
- * Returns undefined for another message, which the caller drops.
6832
+ * Return whether a parent message has the author id of the parent that it
6833
+ * names. The child must also have that parent as its stored parent before
6834
+ * the message gets any authority.
6836
6835
  */
6837
- async function readChildOfStoredParent(message, parentMessage) {
6838
- if (message.input.authorId !== parentMessageAuthorId(parentMessage.parentConversationId)) return;
6839
- const [row] = await getSqlExecutor().db().select({ stoppedAt: juniorConversations.stoppedAt }).from(juniorConversations).where(and(eq(juniorConversations.conversationId, message.conversationId), eq(juniorConversations.parentConversationId, parentMessage.parentConversationId))).limit(1);
6840
- return row;
6836
+ function hasParentMessageAuthor(message, parentMessage) {
6837
+ return message.input.authorId === parentMessageAuthorId(parentMessage.parentConversationId);
6841
6838
  }
6842
6839
  /**
6843
6840
  * Log a parent message that a child dropped: its sender check failed, or a
@@ -7007,7 +7004,7 @@ function isOpenTurnSummary(summary) {
7007
7004
  return !summary.dispatchId && (summary.state === "paused" || summary.state === "running");
7008
7005
  }
7009
7006
  function isActiveMailboxTurn(record) {
7010
- return !record.dispatchId && record.surface !== "internal" && (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");
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");
7011
7008
  }
7012
7009
  /** Return the active web or event mailbox Turn. */
7013
7010
  async function getActiveMailboxTurnId(conversationId) {
@@ -7022,7 +7019,6 @@ async function getAuthPausedConversationTurnId(conversationId) {
7022
7019
  const record = await getTurnRecord(conversationId, turnId);
7023
7020
  return record?.state === "paused" && record.resumeReason === "auth" ? turnId : void 0;
7024
7021
  }
7025
- /** Read one web input batch as Turn input. A batch with no web input gives []. */
7026
7022
  /** Return the transcript author of a web Actor's Message. */
7027
7023
  function webMessageAuthor(actor) {
7028
7024
  return {
@@ -7032,6 +7028,7 @@ function webMessageAuthor(actor) {
7032
7028
  ...actor.userName ? { userName: actor.userName } : void 0
7033
7029
  };
7034
7030
  }
7031
+ /** Read one web input batch as Turn input. A batch with no web input gives []. */
7035
7032
  function parseWebMessages(messages) {
7036
7033
  if (messages.length === 0) return [];
7037
7034
  const parsed = messages.map((message) => ({
@@ -7141,4 +7138,4 @@ async function resolveMailboxTurnWork(context) {
7141
7138
  turnId
7142
7139
  } : void 0;
7143
7140
  }
7144
- export { getTurnUserSlackMessageTs as $, calculateContextCompactionTargetTokens as $n, CODEMODE_TOOL_NAME as $r, setWorkspaceSnapshotBuild as $t, createEventInboundMessage as A, recordSubscribedReplyRoute as An, TURN_LIMIT_WRAP_UP_MESSAGE as Ar, turnRequestText as At, resolveEventAuthor as B, getConversationMessageSlackTs as Bn, requireTurnFailureEventId as Br, deleteWorkspace as Bt, getChildAgentLockName as C, recordAttachmentsDelivered as Cn, listTurnSummaries as Cr, savedInputInstruction as Ct, notInheritedByForkChild as D, recordGuardianActionReviewed as Dn, loadTurnStart as Dr, instructionActorFor as Dt, isInheritedForkHistory as E, recordAuthorizationRequested as En, getTurnLifecycle as Er, buildSteeringPiMessage as Et, eventAuthorText as F, persistConversationMessages as Fn, createTurnLimitGate as Fr, saveUserCustomization as Ft, resumeForPersonInput as G, recordDeliveredAssistantMessage as Gn, ToolActionReviewUnavailableError as Gr, listWorkspacesByRepository as Gt, resolveBotSlackTeamId as H, latestConversationMessageSeq as Hn, isCutOffStopReason as Hr, getWorkspaceByName as Ht, findTrustedUser as I, resolveConversationTitle as In, isTurnExecutionLimitExceededError as Ir, addConversationNote as It, stopConversationTree as J, upsertConversationMessage as Jn, getToolActionRejectionMarker as Jr, tryWorkspaceRepoCheckoutPath as Jt, saveHeldInput as K, trimConversationMessages as Kn, createToolActionReview as Kr, updateWorkspace as Kt, isAllowedDomain as L, settleConversationTitleWork as Ln, captureTurnFailure as Lr, buildDeterministicAssistantMessageId as Lt, eventBatchMessageMeta as M, appendConversationMessages as Mn, TurnSliceLimitExceededError as Mr, readTaskInstructions as Mt, renderEventBatchInputs as N, hydrateConversationMessages as Nn, TurnToolCallLimitExceededError as Nr, renderTaskInput as Nt, EVENT_WAIT_MS as O, recordMcpProviderConnected as On, TURN_OUTCOME_STATUSES as Or, instructionForInputs as Ot, timerWatchCredentialSubject as P, persistConversationMessageWindow as Pn, buildTurnErrorResponse as Pr, readUserCustomization as Pt, getTurnUserReplyAttachmentContext as Q, isEventConversationMessage as Qn, USER_AUTHORIZATION_LEVELS as Qr, setWorkspaceSnapshot as Qt, isTrustedSlackAuthor as R, buildConversationContext as Rn, finalizeFailedTurnReplyWithEvent as Rr, buildDeterministicTurnId as Rt, getAgentReplyMessageId as S, recordAgentsInstructionsUpdated as Sn, getTurnRecord as Sr, loadInboxItemInput as St, getSpawnedChildConversationId as T, recordAuthorizationCompleted as Tn, ConversationTurnLifecycleService as Tr, buildPromptInput as Tt, enqueueAutomatedInput as U, markConversationMessage as Un, ToolActionRejectedError as Ur, listWorkspaceNamesByRepository as Ut, setTrustConfig as V, isHumanConversationMessage as Vn, buildTurnResult as Vr, getWorkspace as Vt, getConversationStoppedAtMs as W, normalizeConversationText as Wn, ToolActionReviewLimitError as Wr, listWorkspaces as Wt, getTurnUserMessage as X, EVENT_SYSTEM_ACTOR as Xn, RISK_LEVELS as Xr, invalidateReadySnapshot as Xt, completeCancelledConversationTurn as Y, EVENT_AUTHOR_ID as Yn, restoreToolActionRejections as Yr, workspaceRepoCheckoutPath as Yt, getTurnUserMessageId as Z, isEventAuthorId as Zn, ROOT_LINE_BREAK as Zr, loadSnapshotsForProfile as Zt, readChildOfStoredParent as _, commitMessages as _n, pauseLostWorkerTurn as _r, coerceThreadConversationState as _t, resolveMailboxTurnWork as a, startOAuthFlow as ai, AGENTS_REPLACEMENT_NOTICE as an, createPluginAuthOrchestration as ar, isCooperativeTurnYieldError as at, readAgentConfig as b, loadConversationSkillNames as bn, completeTurnRecord as br, getWebAuthorization as bt, legacyWebMailboxMetadataSchema as c, validateConfigValue as ci, readRepositoryInstructions as cn, AuthorizationFlowDisabledError as cr, markTurnClosed as ct, childAgentTurnOptions as d, foldLeadingSystemMessages as dn, canReusePendingAuthLink as dr, startActiveTurn as dt, CODE_MODE_CALL_STATUS_TEXT as ei, getExperimentalFeatures as en, getAgentBackgroundCompactionMarkTokens as er, ConversationTurnBoundaryError as et, commitParentMessageFork as f, foldSystemMessages as fn, clearPendingAuth as fr, getLocationConfigurationService as ft, parentMessageText as g, commitAcceptedReply as gn, lostWorkerBeforeFirstSave as gr, persistThreadStateById as gt, logDroppedParentMessage as h, writeAgentHistory as hn, loadTurnCheckpoint as hr, persistThreadRuntimeState as ht, listActiveMailboxTurns as i, parseOAuthStatePayload as ii, AGENTS_REMOVAL_NOTICE as in, PluginCredentialFailureError as ir, getConversationTurnBoundaryError as it, enqueueEventNotification as j, recordToolExecutionStarted as jn, TurnBudgetExceededError as jr, withoutSavedSteeringMessages as jt, addQuietEventNote as k, recordSkillLoaded as kn, GATED_TURN_LIMIT_WRAP_UP_MESSAGE as kr, loadPromptTurnContext as kt, appendParentMessage as l, configValueSchema as li, renderAgentsInstructions as ln, AuthorizationPauseError as lr, markTurnCompleted as lt, isParentMessageAuthor as m, withAgentRequest as mn, continuableMessages as mr, getPersistedThreadState as mt, getEventBatchDelayMs as n, deliverOAuthAuthorization as ni, setExperimentalFeatures as nn, getAgentContextInputLimitTokens as nr, TurnInputCommitLostError as nt, sourceFromTurnInput as o, projectConversationEvents as oi, buildAgentsInstructionsMessage as on, authorizationId as or, isTurnInputCommitLostError as ot, dropWaitingParentMessages as p, readAgentHistory as pn, getConversationPendingAuth as pr, getPersistedSandboxState as pt, session_stop_exports as q, turnHasReply as qn, reviewToolActions as qr, WorkspaceValidationError as qt, listActiveMailboxTurnSources as r, formatProviderLabel as ri, buildDeploymentSystemPrompt as rn, createPluginEgress as rr, TurnInputDeferredError as rt, turnInputFactsFromConversationMessage as s, validateConfigKey as si, findVisibleAgentsInstructions as sn, AuthPausePersistenceError as sr, isTurnInputDeferredError as st, getAuthPausedConversationTurnId as t, persistWithRetry as ti, isExperimentalFeatureEnabled as tn, getAgentContextCompactionTriggerTokens as tr, CooperativeTurnYieldError as tt, buildParentMessage as u, showsAgentsInstructions as un, abandonReplacedPendingAuth as ur, markTurnFailed as ut, readLastParentMessageAtMs as v, loadConnectedMcpProviders as vn, saveTurnCheckpoint as vr, createWebAuthorization as vt, getPersonStopTurnId as w, recordAuthenticationLinked as wn, recordTurnSummary as wr, assemblePrompt as wt, getAgentMessageId as x, loadTurnProjection as xn, failTurnRecord as xr, eventInboxItemInputs as xt, agentConfigSchema as y, loadConversationProjection as yn, abandonTurnRecord as yr, deleteWebAuthorization as yt, parseEmail as z, estimateConversationMessagesTokens as zn, getAgentTurnDiagnosticsAttributes as zr, createWorkspace as zt };
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 };