@sentry/junior 0.313.0 → 0.314.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 (108) hide show
  1. package/dist/{adapter-CYAvJzZS.js → adapter-JARQvoLw.js} +1 -2
  2. package/dist/{adapter-context-CVsHoVSf.js → adapter-context-B4BrJZuS.js} +2 -2
  3. package/dist/{admin-Cyhb4TwZ.js → admin-BXGAySz0.js} +1 -1
  4. package/dist/{agent-runner-B5y9MsT-.js → agent-runner-qZU5TR8i.js} +797 -118
  5. package/dist/agent-update-cS7Z9mnG.js +26 -0
  6. package/dist/agent-update-delivery-CZ5M8RDa.js +85 -0
  7. package/dist/api/schema.d.ts +2 -2
  8. package/dist/api/schema.js +6 -6
  9. package/dist/api.d.ts +1 -1
  10. package/dist/api.js +334 -100
  11. package/dist/{app-DA8-hCMj.d.ts → app-D7tKnw9a.d.ts} +4 -21
  12. package/dist/app.d.ts +2 -2
  13. package/dist/app.js +80 -169
  14. package/dist/{background-compaction-queue-iZXadLV3.js → background-compaction-queue-C_uIBUvS.js} +6 -67
  15. package/dist/callback-C8SdXCwr.js +68 -0
  16. package/dist/{catalog-runtime-kkE3hvCX.js → catalog-runtime-BLKtnUL3.js} +1 -1
  17. package/dist/{channel-access-mt7K6dPh.js → channel-access-BOL29BG3.js} +6 -6
  18. package/dist/child-message--2G3Ft26.js +19 -0
  19. package/dist/cli/chat.js +18 -21
  20. package/dist/cli/check.js +4 -4
  21. package/dist/cli/main.js +2 -2
  22. package/dist/cli/plugins.js +5 -5
  23. package/dist/cli/snapshot-create.js +5 -5
  24. package/dist/cli/upgrade.d.ts +1 -1
  25. package/dist/cli/upgrade.js +23 -4
  26. package/dist/{config-CWbwKj0j.js → config-BIfHKNXN.js} +40 -35
  27. package/dist/{continue-in-slack-CxyFzdlF.js → continue-in-slack-fnmD2Ifb.js} +5 -7
  28. package/dist/{conversation-feed-BEXLD3Me.js → conversation-feed-DdFQuQDR.js} +1 -1
  29. package/dist/{logging-DNt-qOIO.js → conversation-privacy-DtZhI91r.js} +188 -2
  30. package/dist/{conversation-turn-B35eu0uz.js → conversation-turn-DScuDYmN.js} +418 -33
  31. package/dist/create-CrNt4Ewu.js +212 -0
  32. package/dist/{credential-sync-DWTOEQrm.js → credential-sync-CtqsGjj1.js} +14 -17
  33. package/dist/{credentialed-Dyv8b-lu.js → credentialed-dWRA3-oJ.js} +910 -426
  34. package/dist/{db-PwSRzWWn.js → db-BTmLKZrp.js} +2235 -38
  35. package/dist/{db-DYGcXYl3.d.ts → db-DcmzbA55.d.ts} +2 -2
  36. package/dist/{history-CYstOMKX.js → history-CneKY7_V.js} +19 -1
  37. package/dist/{html-DidUcRhI.js → html-B8rBt7F4.js} +5 -7
  38. package/dist/{install-2urLLXNt.js → install-OtFboxOM.js} +2 -2
  39. package/dist/instrumentation.js +2 -2
  40. package/dist/{lineage-BXplQAVH.js → lineage-EULJkGO1.js} +1 -2
  41. package/dist/{list-DyIyReSV.js → list-C5400AlJ.js} +235 -77
  42. package/dist/{turn-membership-DTR3SaKD.js → mailbox-turn-DL3Lvsm0.js} +4698 -587
  43. package/dist/markers-DUP8aBOp.js +323 -0
  44. package/dist/{media-B0pZJ0bG.js → media-FYM-Bl3H.js} +33 -8
  45. package/dist/{message-Z5YKC-Af.js → message-DuDelZFr.js} +16 -29
  46. package/dist/{model-input-BhPJYdSV.js → model-input-0osF3pBS.js} +3 -3
  47. package/dist/nitro.d.ts +2 -4
  48. package/dist/nitro.js +340 -13
  49. package/dist/{oauth-callback-server-ByvDdcdY.js → oauth-callback-server-DX2fQ7Nq.js} +2 -2
  50. package/dist/{oauth-relay-D-kK0yoN.js → oauth-relay-PwPMdZJv.js} +1 -1
  51. package/dist/{plugins-Bkk0XRo2.js → plugins-BXMdNdyA.js} +1 -1
  52. package/dist/{registry-POH4bZC4.js → registry-D6kS6xYH.js} +1402 -64
  53. package/dist/{resolve-CWtBNSKP.js → resolve-D8CPJcNK.js} +3 -3
  54. package/dist/result-D090hxr5.js +402 -0
  55. package/dist/{runner-CsZ_VRxp.js → runner-BU7fgrm-.js} +7 -8
  56. package/dist/{sandbox-egress-signals-FbCk1FkN.js → sandbox-egress-signals-BUmVrsoG.js} +1 -1
  57. package/dist/{schema-DojR2uCL.js → schema-7gW9vBpJ.js} +90 -9
  58. package/dist/{schema-DBf18QPS.d.ts → schema-BB6E0wyV.d.ts} +138 -5
  59. package/dist/{service-account-CDYb9hfX.js → service-account-plA-uzIB.js} +6 -5
  60. package/dist/{skills-B0jP4whm.js → skills-CIosT6bS.js} +3 -3
  61. package/dist/{slack-conversation-unfurl-D26t9kBC.js → slack-conversation-unfurl-CBgZqth6.js} +8 -10
  62. package/dist/{spawn-BjljgExZ.js → spawn-DRjdzh3R.js} +9 -17
  63. package/dist/{start-conversation-DbVujrwO.js → start-conversation-a4NXH4X9.js} +12 -15
  64. package/dist/{store-CjXrp-Up.js → store-BuhF1QDm.js} +2 -4
  65. package/dist/{task-queue-Cwlatjz3.js → task-queue-CrRjFzOh.js} +5 -16
  66. package/dist/{task-runner--Ke8KSMf.js → task-runner-C-pXsgHM.js} +104 -50
  67. package/dist/{thread-context-B8exINEe.js → thread-context-CDX4dSZd.js} +8 -9
  68. package/dist/turn-session-routing-CZTRU8IY.js +116 -0
  69. package/dist/turn-wake-Bzq1Efrm.js +154 -0
  70. package/dist/user-customization-B27StpVQ.js +9 -0
  71. package/dist/{validation-Ce0qbMlT.js → validation-bTq88sya.js} +1 -1
  72. package/dist/{vercel-queue-q4z8w5QO.js → vercel-queue-nL0Hq3hr.js} +32 -147
  73. package/dist/{version-DFh4n9nr.js → version-DGUa1dZK.js} +1 -1
  74. package/dist/version.js +1 -1
  75. package/dist/{warmup-D5hzqTcp.js → warmup-CCOuIwAS.js} +639 -137
  76. package/dist/{worker-CDg9Lbpg.js → worker-AkZg7Dg1.js} +5 -6
  77. package/migrations/0160_money_micro_usd_repair.sql +99 -0
  78. package/migrations/0161_agent_config_backfill.sql +34 -0
  79. package/migrations/0162_inbox_item_deliveries.sql +15 -0
  80. package/migrations/0163_pg_trgm.sql +2 -0
  81. package/migrations/0164_search_indexes.sql +4 -0
  82. package/migrations/0165_drop_legacy_archive_columns.sql +4 -0
  83. package/migrations/0166_memory_prefix_index.sql +1 -0
  84. package/migrations/0167_todo_search_indexes.sql +2 -0
  85. package/migrations/0168_todo_inbox_items.sql +4 -0
  86. package/migrations/0169_drop_code_urls.sql +2 -0
  87. package/migrations/meta/0160_snapshot.json +6515 -0
  88. package/migrations/meta/0161_snapshot.json +6278 -0
  89. package/migrations/meta/0162_snapshot.json +6404 -0
  90. package/migrations/meta/0163_snapshot.json +6404 -0
  91. package/migrations/meta/0164_snapshot.json +6466 -0
  92. package/migrations/meta/0165_snapshot.json +6466 -0
  93. package/migrations/meta/0166_snapshot.json +6494 -0
  94. package/migrations/meta/0167_snapshot.json +6525 -0
  95. package/migrations/meta/0168_snapshot.json +6525 -0
  96. package/migrations/meta/0169_snapshot.json +6513 -0
  97. package/migrations/meta/_journal.json +70 -0
  98. package/package.json +9 -18
  99. package/skills/design-automation-skill/SKILL.md +2 -3
  100. package/dist/actor-BsBdxDXQ.js +0 -208
  101. package/dist/conversation-privacy-BrMiDN61.js +0 -189
  102. package/dist/executor-CgWyWfYz.js +0 -1858
  103. package/dist/fan-out-Cod-yEHG.js +0 -10
  104. package/dist/ingest-B0AggUEC.js +0 -7931
  105. package/dist/request-deadline-BUiRYQYj.js +0 -24
  106. package/dist/service-account-o15pZWcJ.js +0 -931
  107. package/dist/state-BTawTCme.js +0 -161
  108. package/dist/statuses-BKwqCPhj.js +0 -69
@@ -1,29 +1,26 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { $n as replyTextSchema, Dt as EVENT_AUTHOR_ID, Ft as getAgentContextCompactionTriggerTokens, It as getAgentContextInputLimitTokens, Nt as calculateContextCompactionTargetTokens, Pt as getAgentBackgroundCompactionMarkTokens, X as loadConversationProjection, Yn as REPLY_TOOL_NAME, _ as appendAndEnqueueInboundMessage, _n as withIdleConversation, ar as isLegacyNoReplyMarker, hr as projectConversationEvents, ir as findLegacyNoReplyMarker, lr as REPORT_BLOCKED_TOOL_NAME, mr as piMessageFromHistoryItem, pr as historyItemFromPiMessage, rr as NO_REPLY_TOOL_NAME } from "./turn-membership-DTR3SaKD.js";
3
- import { B as requestPrefixAttributes, G as gatewayRoutingAttributes, H as estimateRequestOverheadTokens, J as isCompactionSummaryText, K as COMPACTION_SUMMARY_PREFIX, O as resolveGatewayModel, R as fenceLock, U as estimateTextTokens, V as estimateMessagesTokens, W as textCharsForTokens, Z as unwrapCurrentInstruction, b as GEN_AI_SERVER_ADDRESS, ct as findProviderError, ft as isProviderRetryError, g as TURN_REASONING_LEVELS, lt as getProviderErrorAttributes, n as botConfig, ot as createAssistantProviderError, pt as getGatewayApiKey, q as hasCompactedConversationContext, r as getChatConfig, rt as renderThreadContext, st as createProviderError, y as GEN_AI_PROVIDER_NAME, z as withLock } from "./config-CWbwKj0j.js";
4
- import { E as withSpan, G as runWithLogAttributes, T as withLogContext, Y as toOptionalString, a as extractGenAiUsageSummary, b as setSpanAttributes, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, l as getLogContextAttributesForSpan, m as logInfo, p as logException, v as serializeGenAiAttribute, z as getDeploymentId } from "./logging-DNt-qOIO.js";
2
+ import { $i as NO_REPLY_TOOL_NAME, A as addQuietEventNote, Bt as getConversationWorkState, C as getPersonStopTurnId, Cn as todoOutputSchema, Dr as EVENT_AUTHOR_ID, E as isPersonStopTurnId, En as addConversationNote, Gi as REPLY_TOOL_NAME, Gn as readAgentHistory, H as resolveEventAuthor, K as getConversationStoppedAtMs, Kn as withAgentRequest, Lt as dropPendingMessages, M as enqueueEventNotification, Mn as isExperimentalFeatureEnabled, Mr as getAgentBackgroundCompactionMarkTokens, Nr as getAgentContextCompactionTriggerTokens, Or as EVENT_SYSTEM_ACTOR, Pn as buildDeploymentSystemPrompt, Pr as getAgentContextInputLimitTokens, S as getChildAgentLockName, Sn as parseTodoRef, Tn as todoRefSchema, Tt as appendAndEnqueueInboundMessage, Un as foldLeadingSystemMessages, Vn as renderAgentsInstructions, Wn as foldSystemMessages, X as stopConversationTree, Yi as replyTextSchema, Zn as loadConversationProjection, aa as REPORT_BLOCKED_TOOL_NAME, b as readAgentConfig, bi as readParentMessage, bn as renderTodosSnapshot, da as projectConversationEvents, dn as changeTodos, ea as findLegacyNoReplyMarker, gn as listTodos, hi as readInboundMessageSender, hn as listParentTodoIds, i as listActiveMailboxTurns, jr as calculateContextCompactionTargetTokens, k as EVENT_WAIT_MS, la as historyItemFromPiMessage, mi as withIdleConversation, p as dropWaitingParentMessages, pn as closeTodosForChild, si as hasConversationStop, ta as isLegacyNoReplyMarker, ua as piMessageFromHistoryItem, un as saveUserCustomization, v as readLastParentMessageAtMs, vn as TODO_DELTA_TAG, wn as todoRef, xn as outputTodo, yn as renderTodoAssignee, zn as findVisibleAgentsInstructions } from "./mailbox-turn-DL3Lvsm0.js";
3
+ import { B as requestPrefixAttributes, G as gatewayRoutingAttributes, H as estimateRequestOverheadTokens, J as isCompactionSummaryText, K as COMPACTION_SUMMARY_PREFIX, O as resolveGatewayModel, R as fenceLock, U as estimateTextTokens, V as estimateMessagesTokens, W as textCharsForTokens, Z as unwrapCurrentInstruction, b as GEN_AI_SERVER_ADDRESS, ct as findProviderError, ft as isProviderRetryError, g as TURN_REASONING_LEVELS, gt as mapBounded, it as renderThreadContext, lt as getProviderErrorAttributes, n as botConfig, ot as createAssistantProviderError, pt as getGatewayApiKey, q as hasCompactedConversationContext, r as getChatConfig, st as createProviderError, y as GEN_AI_PROVIDER_NAME, z as withLock } from "./config-BIfHKNXN.js";
4
+ import { C as logInfo, D as serializeGenAiAttribute, F as withSpan, J as getDeploymentId, P as withLogContext, S as logException, T as normalizeGenAiFinishReason, a as toCanonicalInputMessage, et as runWithLogAttributes, i as runWithConversationPrivacy, it as toOptionalString, k as setSpanAttributes, m as extractGenAiUsageSummary, o as toCanonicalOutputMessage, p as extractGenAiUsageAttributes, rt as normalizeIdentityEmail, s as toGenAiMessagesTraceAttributes, v as getLogContextAttributesForSpan, w as logWarn } from "./conversation-privacy-DtZhI91r.js";
5
5
  import { g as withActiveSpan, h as startSpan, m as startInactiveSpan, n as captureMessage, u as sentry_exports } from "./sentry-CPbZjomA.js";
6
- import { t as mapBounded } from "./fan-out-Cod-yEHG.js";
7
- import { At as automationCreatorUserId, Ct as isPluginInboxItem, Dt as requireInboxItemLinks, Et as requireInboxItemAssignees, Gt as identityAvatarUrl, I as watchRepeatsChildResults, In as touchConversationDetail, Jt as readUserAvatarUrls, K as usdToMicroUsd, Mn as resolveRootConversationId, Mt as resolveAssignees, N as promptModeTurnTools, Nn as rootConversationIsArchived, On as agentTurnCostUsd, Ot as EVERYONE_ASSIGNEE, S as userMessageQueries, Tt as readInboxItemAgentScope, Z as conversationStatusSql, Zt as SYSTEM_IDENTITY_ID, _ as readConversationTrees, a as getConversationStore, at as AUTOMATION_INBOX_ITEM_KEY_PREFIX, bn as readableSlackTeamId, ct as canAgentChangeInboxItem, d as eventFromRow, dn as ToolInputError, g as conversationDescendants, h as conversationAncestors, hn as canReadConversation, i as getConversationMessageSearchStore, jt as resolveAssignee, kt as activeParticipantUserIds, lt as canReadInboxItem, mn as canAddConversationMessages, o as getDb, ot as PLUGIN_INBOX_ITEM_KEY_PREFIX, r as getConversationEventStore, s as getSqlExecutor, v as setArchivedAt, vn as readConversationAccessFromSql } from "./db-PwSRzWWn.js";
8
- import { n as pluginCatalogRuntime } from "./catalog-runtime-kkE3hvCX.js";
9
- import { An as parseTodoRef, Bn as buildDeploymentSystemPrompt, Cn as listParentTodoIds, Dn as renderTodoAssignee, En as TODO_DELTA_TAG, G as AgentDepthLimitError, Gn as findVisibleAgentsInstructions, J as AgentMessageTargetError, K as AgentInvocationLimitError, Mn as todoRef, N as stopChildAgent, Nn as todoRefSchema, On as renderTodosSnapshot, Pn as addConversationNote, Qn as withAgentRequest, Rn as isExperimentalFeatureEnabled, X as AgentStoppedError, Xn as foldSystemMessages, Y as AgentNameInUseError, Yn as foldLeadingSystemMessages, Z as findChildAgentConversationId, Zn as readAgentHistory, a as listDescendantAgents, at as getLatestAgentInvocationForConversation, bn as changeTodos, dt as CHILD_AGENT_RESULTS, ft as PARENT_AGENT_TARGET, h as readLastParentMessageAtMs, i as listChildAgents, jn as todoOutputSchema, kn as outputTodo, pt as agentNameSchema, q as AgentMessageQueueFullError, qn as renderAgentsInstructions, r as listAgentRelatives, st as listOpenAgentInvocations, t as ingestEvent, tt as NON_TERMINAL_AGENT_INVOCATION_STATUSES, ut as CHILD_AGENT_KINDS, wn as listTodos, xn as closeTodosForChild, xt as EVENT_WAIT_MS, yn as saveUserCustomization } from "./ingest-B0AggUEC.js";
10
- import { $ as SEARCHABLE_EVENT_TYPES, $a as WORKSPACE_SNAPSHOT_FAILED_EVENT, $o as registeredResourceTypeSchema, Aa as ownerConversationId, An as workspaceRepoCheckoutPath, Ao as getSlackClient, At as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, Bt as listWorkspaces, Ca as dismissOpenInboxItems, Da as insertInboxItem, Do as downloadPrivateSlackFile, Eo as SlackActionError, Gi as setEventAutomationStatus, Gn as embedConversationQuery, Go as describeRegisteredEventTrigger, Gt as loadSnapshotsForProfile, H as fuseRankedLists, Hi as listDeletedEventAutomationsCreatedBy, Ht as updateWorkspace, It as createWorkspace, Ja as requireSlackChannelMessageScope, Ji as automationDefinition, Jn as createPluginAnnotations, Jo as eventWatchUnavailable, Jt as create, Ka as getEventCatalog, Kr as getSlackMessagePermalink, Kt as setWorkspaceSnapshot, Lt as deleteWorkspace, Mr as getDispatchInputMessageId, Mt as RESOURCE_WATCH_TOOL_SOURCE, Na as updateInboxItemContent, Nr as getDispatchRecord, Nt as STOP_WATCHING_TOOL_NAME, On as SANDBOX_RUNTIME, Oo as getFilePermalink, Ot as getSlackToolContext, Po as normalizeSlackConversationId, Qa as slackChannelMessageTrigger, Qi as sameDefinitionValue, Qo as registeredEventTypeSchema, Qt as getSandboxProvider, Rn as searchConversations, Ro as withSlackRetries, Rt as getWorkspace, Ta as getOpenInboxItemByDedupeKey, Ui as parseEventAutomationRow, Ut as WorkspaceValidationError, Wi as saveEventAutomation, Wo as automationEventCatalog, Wt as invalidateReadySnapshot, X as searchedEventTextSql, Xi as listAutomationVersions, Xo as registeredEventMatchSchema, Xt as isStale, Y as lexemesSql, Yo as hasEventCatalogEntries, Z as seqIn, Zi as readAutomationVersion, Zn as defaultTimezone, Zo as registeredEventTriggerProblems, _ as getStaticPluginToolDefinitions, _a as fallbackShortTitle, _r as SANDBOX_WORKSPACE_ROOT, _t as retainRuntimeTurnContext, aa as readAutomationExecutionStatusDays, ao as publishConversationStatus, as as createPluginCache, bi as saveScheduledAutomation, bn as createSandboxEgressCredentialToken, bt as CAPABILITY_SECTION_TAG, c as createPluginHookRunner, ca as readAutomationExecutions, cr as userLookupIdentityProviders, cs as completeText, ea as automationRevision, eo as WORKSPACE_SNAPSHOT_READY_EVENT, es as requireEventIdentifier, et as callsToolSql, gi as deleteScheduledAutomation, go as listWatches, h as getPlugins, hn as isWorkspaceSnapshotNotReadyError, ia as readAutomationExecutionByConversationId, ir as lookupUsers, ja as searchInboxItems, ji as getDashboardTaskLink, jo as isConversationScopedChannel, jr as getDispatchIdForConversation, jt as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, la as readAutomationRowStats, ln as isAbortError, lo as createTimerWatch, lt as hasTurnInput, mr as SANDBOX_REPOS_ROOT, na as emptyAutomationRunWindows, no as workspaceSnapshotWatch, nr as isSlackUserNotFound, nt as excerptTerms, oa as readAutomationExecutionStatusHours, pn as WorkspaceSnapshotNotReadyError, po as getWatch, pt as isStandaloneRuntimeContextMessage, qn as saveObjectAnnotations, qo as eventNamespaceSchema, qr as openSlackDirectMessage, qt as setWorkspaceSnapshotBuild, rr as looksLikeEmail, sa as readAutomationExecutionSummaries, so as cancelWatch, ta as requireAutomationRevision, to as workspaceSnapshotFinishedEvent, ts as requireValidEventTrigger, tt as eventExcerpt, ua as readAutomationRuns, ui as slackMention, uo as createWatch, us as searchWeb, vi as parseScheduledAutomationRow, vo as turnEvents, vt as stripRuntimeTurnContext, wa as getInboxItem, wi as getDashboardConversationLink, wn as buildSandboxEgressNetworkPolicy, wr as createPluginLogger, xa as closeInboxItem, xt as REQUEST_CONTEXT_SECTION_TAG, ya as resolveTaskTitle, yt as trimTrailingAssistantMessages, zi as deleteEventAutomation, zo as sleep, zt as getWorkspaceByName } from "./credentialed-Dyv8b-lu.js";
11
- import { D as zodToolDefinition, E as zodTool, b as matchSlackAttachments, f as webActorFromUser, k as juniorToolOutputSchema, n as startConversationToolDefinition, o as acceptsWebMessages, s as appendAndEnqueueWebMessage } from "./start-conversation-DbVujrwO.js";
12
- import { $t as formatUserInputAnswer, Bt as toolScheduleIntentSchema, Ct as removedCardSchema, Gt as isValidTimeZone, Ht as getFirstRunAtMs, Lt as ScheduleIntentError, Rt as compileScheduleIntent, Vt as weekdaySchema, Wt as getZonedDateTimeParts, an as automationTaskDescription, b as automationListQuerySchema, ct as AGENT_TYPES, dt as formatAgentTypes, l as apiErrorSchema, nn as userInputRequestSchema, on as automationTaskSchema, qt as eventAutomationTriggerSchema, rn as automationSkillNameSchema, sn as automationTaskText } from "./media-B0pZJ0bG.js";
13
- import { d as parseSlackChannelReferenceId, f as parseSlackTeamId, o as isUserActor, p as parseSlackUserId, u as parseSlackChannelId, v as parseSlackMessageTs } from "./actor-BsBdxDXQ.js";
14
- import { C as juniorConversationParticipants, D as juniorConversationEventEmbeddings, E as juniorConversationEventLexemes, H as juniorConversations, K as juniorUsers, M as juniorConversationEvents, S as juniorConversationReadPositions, U as juniorIdentities, _ as juniorAutomationRuns, at as guardedCosineDistance, g as juniorAutomations, l as juniorStats, q as juniorDestinations } from "./executor-CgWyWfYz.js";
15
- import { t as discoverSkills } from "./skills-B0jP4whm.js";
6
+ import { Ar as juniorConversationEvents, Br as juniorConversations, Bt as requireInboxItemAssignees, Cr as juniorConversationReadPositions, Dr as juniorConversationEventEmbeddings, E as isUserActor, Er as juniorConversationEventLexemes, G as watchRepeatsChildResults, Gr as juniorDestinations, Gt as resolveAssignee, H as promptModeTurnTools, Ht as EVERYONE_ASSIGNEE, Jn as rootConversationIsArchived, Kt as resolveAssignees, Lt as isPluginInboxItem, Mn as readConversationAccessFromSql, On as canAddConversationMessages, Pn as readableSlackTeamId, Sr as juniorAgentBindings, St as canReadInboxItem, Tn as ToolInputError, Un as agentTurnCostUsd, Ut as activeParticipantUserIds, Vr as juniorIdentities, Vt as requireInboxItemLinks, W as turnBehavior, Wr as juniorUsers, Wt as automationCreatorUserId, Zn as touchConversationDetail, _ as conversationDescendants, a as getDb, an as identityAvatarUrl, bi as parseSlackMessageTs, cn as readUserAvatarUrls, dn as SYSTEM_IDENTITY_ID, f as eventFromRow, fi as parseSlackChannelId, g as conversationAncestors, hi as parseSlackUserId, i as getConversationStore, ii as guardedCosineDistance, j as userMessageQueries, kn as canReadConversation, mi as parseSlackTeamId, n as getConversationEventStore, o as getSqlExecutor, or as juniorStats, pi as parseSlackChannelReferenceId, qn as resolveRootConversationId, r as getConversationMessageSearchStore, st as conversationStatusSql, tt as usdToMicroUsd, v as readConversationTrees, vr as juniorAutomations, vt as RESERVED_INBOX_ITEM_KEY_PREFIXES, wr as juniorConversationParticipants, xt as canAgentChangeInboxItem, y as setArchivedAt, yr as juniorAutomationRuns, zt as readInboxItemAgentScope } from "./db-BTmLKZrp.js";
7
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-BLKtnUL3.js";
8
+ import { $i as deleteEventAutomation, $o as normalizeSlackConversationId, $t as updateWorkspace, Ai as deleteScheduledAutomation, Ao as deliverWatch, At as retainRuntimeTurnContext, Ca as readAutomationRowStats, Ds as completeText, En as isWorkspaceSnapshotNotReadyError, Eo as cancelWatch, Et as isStandaloneRuntimeContextMessage, Fa as closeInboxItem, Fn as buildSandboxEgressNetworkPolicy, Fo as listWatches, Ga as ownerConversationId, Gi as getDashboardTaskLink, Go as SlackActionError, Gr as getDispatchIdForConversation, Ha as insertInboxItem, Ht as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, Ja as updateInboxItemContent, Jt as deleteWorkspace, Ka as searchInboxItems, Ko as downloadPrivateSlackFile, Kr as getDispatchInputMessageId, La as dismissOpenInboxItems, Lo as turnEvents, Mi as parseScheduledAutomationRow, Mo as getWatch, Mt as trimTrailingAssistantMessages, Na as resolveTaskTitle, No as isQuietEvent, Nt as CAPABILITY_SECTION_TAG, Oo as createTimerWatch, Or as SANDBOX_REPOS_ROOT, Pi as saveScheduledAutomation, Pt as REQUEST_CONTEXT_SECTION_TAG, Ra as getInboxItem, Ri as getDashboardConversationLink, Rr as createPluginLogger, Sa as readAutomationExecutions, Sr as userLookupIdentityProviders, St as hasTurnInput, Ut as RESOURCE_WATCH_TOOL_SOURCE, Vn as workspaceRepoCheckoutPath, Vt as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, Wt as STOP_WATCHING_TOOL_NAME, Xo as isConversationScopedChannel, Xt as getWorkspaceByName, Yn as searchConversations, Yo as getSlackClient, Yt as getWorkspace, Zt as listWorkspaces, _ as getStaticPluginToolDefinitions, _o as slackChannelMessageTrigger, _r as looksLikeEmail, _s as registeredEventTypeSchema, aa as setEventAutomationStatus, an as create, ba as readAutomationExecutionStatusHours, bn as isAbortError, bo as workspaceSnapshotFinishedEvent, bs as requireValidEventTrigger, c as createPluginHookRunner, ca as automationDefinition, cr as createPluginAnnotations, ct as lexemesSql, da as readAutomationVersion, do as getEventCatalog, dr as defaultTimezone, en as WorkspaceValidationError, fa as sameDefinitionValue, fs as eventNamespaceSchema, ft as SEARCHABLE_EVENT_TYPES, ga as emptyAutomationRunWindows, gr as isSlackUserNotFound, gs as registeredEventTriggerProblems, h as getPlugins, ha as requireAutomationRevision, hs as registeredEventMatchSchema, ht as excerptTerms, ia as saveEventAutomation, in as setWorkspaceSnapshotBuild, ir as saveObjectAnnotations, is as sleep, ja as fallbackShortTitle, jn as createSandboxEgressCredentialToken, jo as findMatchingWatches, jr as SANDBOX_WORKSPACE_ROOT, jt as stripRuntimeTurnContext, ko as createWatch, ks as searchWeb, ln as getSandboxProvider, ls as automationEventCatalog, lt as searchedEventTextSql, ma as automationRevision, ms as hasEventCatalogEntries, mt as eventExcerpt, na as listDeletedEventAutomationsCreatedBy, nn as loadSnapshotsForProfile, nr as embedConversationQuery, oi as getSlackMessagePermalink, po as requireSlackChannelMessageScope, ps as eventWatchUnavailable, pt as callsToolSql, qo as getFilePermalink, qr as getDispatchRecord, qt as createWorkspace, ra as parseEventAutomationRow, rn as setWorkspaceSnapshot, rs as withSlackRetries, si as openSlackDirectMessage, sn as isStale, tn as invalidateReadySnapshot, tt as fuseRankedLists, ua as listAutomationVersions, us as describeRegisteredEventTrigger, ut as seqIn, va as readAutomationExecutionByConversationId, vo as WORKSPACE_SNAPSHOT_FAILED_EVENT, vr as lookupUsers, vs as registeredResourceTypeSchema, wa as readAutomationRuns, wi as slackMention, wn as WorkspaceSnapshotNotReadyError, wo as publishAgentUpdate, ws as createPluginCache, xa as readAutomationExecutionSummaries, xo as workspaceSnapshotWatch, ya as readAutomationExecutionStatusDays, yo as WORKSPACE_SNAPSHOT_READY_EVENT, ys as requireEventIdentifier, z as closeReadReplyNotice, za as getOpenInboxItemByDedupeKey, zn as SANDBOX_RUNTIME, zt as getSlackToolContext } from "./credentialed-dWRA3-oJ.js";
9
+ import { D as zodToolDefinition, E as zodTool, b as matchSlackAttachments, f as webActorFromUser, k as juniorToolOutputSchema, n as startConversationToolDefinition, o as acceptsWebMessages, s as appendAndEnqueueWebMessage } from "./start-conversation-a4NXH4X9.js";
10
+ import { $t as formatUserInputAnswer, Bt as toolScheduleIntentSchema, Ct as removedCardSchema, Gt as isValidTimeZone, Ht as getFirstRunAtMs, Lt as ScheduleIntentError, Rt as compileScheduleIntent, Vt as weekdaySchema, Wt as getZonedDateTimeParts, b as automationListQuerySchema, cn as automationSkillNameSchema, ct as AGENT_TYPES, dn as automationTaskSchema, dt as formatAgentTypes, fn as automationTaskText, l as apiErrorSchema, nn as userInputRequestSchema, qt as eventAutomationTriggerSchema, un as automationTaskDescription } from "./media-FYM-Bl3H.js";
11
+ import { t as discoverSkills } from "./skills-CIosT6bS.js";
16
12
  import { s as sumUtcHoursIntoSixHours } from "./reporting-window-C4dbzDiR.js";
17
- import { c as listChannelMessages, l as listThreadReplies, n as joinPublicChannelForRead, s as joinPublicChannel, t as checkSlackChannelReadAccess } from "./channel-access-mt7K6dPh.js";
18
- import { d as userCustomizationTextSchema, g as isOpenTodoStatus, l as USER_CUSTOMIZATION_MAX_CHARS, m as TODO_STATUSES, p as SELF_TODO_ASSIGNEE } from "./statuses-BKwqCPhj.js";
19
- import { d as contextProvenance, t as KNOWN_CONVERSATION_EVENT_TYPES } from "./history-CYstOMKX.js";
20
- import { p as credentialContextForActor } from "./registry-POH4bZC4.js";
21
- import { t as getTurnRequestDeadline } from "./request-deadline-BUiRYQYj.js";
22
- import { n as postinstall, o as getSandboxResources, t as dependencies } from "./install-2urLLXNt.js";
23
- import { a as getStateValues, i as getStateAdapter, o as setStateValues } from "./adapter-CYAvJzZS.js";
24
- import { c as QUEUE_SIGNATURE_MAX_AGE_MS, t as getVercelConversationWorkQueue } from "./vercel-queue-q4z8w5QO.js";
25
- import { f as sendNextWorkspaceSnapshotJob, l as sendCacheWarmup, n as backgroundCompactionId, p as sendWorkspaceSnapshotJob } from "./background-compaction-queue-iZXadLV3.js";
26
- import { a as toCanonicalInputMessage, i as runWithConversationPrivacy, o as toCanonicalOutputMessage, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-BrMiDN61.js";
13
+ import { c as listChannelMessages, l as listThreadReplies, n as joinPublicChannelForRead, s as joinPublicChannel, t as checkSlackChannelReadAccess } from "./channel-access-BOL29BG3.js";
14
+ import { a as listChildAgents, d as PARENT_AGENT_TARGET, f as agentBindingSchema, i as listAgentRelatives, l as CHILD_AGENT_KINDS, o as listDescendantAgents, p as agentNameSchema, t as recordChildAgentEnded, u as CHILD_AGENT_RESULTS } from "./markers-DUP8aBOp.js";
15
+ import { _ as TODO_STATUSES, d as contextProvenance, g as SELF_TODO_ASSIGNEE, t as KNOWN_CONVERSATION_EVENT_TYPES, y as isOpenTodoStatus } from "./history-CneKY7_V.js";
16
+ import { c as parentResultActor, n as createDeliverToParent } from "./result-D090hxr5.js";
17
+ import { r as userCustomizationTextSchema, t as USER_CUSTOMIZATION_MAX_CHARS } from "./user-customization-B27StpVQ.js";
18
+ import { K as credentialContextForActor } from "./registry-D6kS6xYH.js";
19
+ import { n as getTurnRequestDeadline } from "./callback-C8SdXCwr.js";
20
+ import { n as postinstall, o as getSandboxResources, t as dependencies } from "./install-OtFboxOM.js";
21
+ import { a as getStateValues, i as getStateAdapter, o as setStateValues } from "./adapter-JARQvoLw.js";
22
+ import { c as QUEUE_SIGNATURE_MAX_AGE_MS, t as getVercelConversationWorkQueue } from "./vercel-queue-nL0Hq3hr.js";
23
+ import { l as sendNextWorkspaceSnapshotJob, n as backgroundCompactionId, s as sendCacheWarmup, u as sendWorkspaceSnapshotJob } from "./background-compaction-queue-C_uIBUvS.js";
27
24
  import * as z from "zod";
28
25
  import pLimit from "p-limit";
29
26
  import { streamSimple } from "@earendil-works/pi-ai/compat";
@@ -32,7 +29,7 @@ import { isDeepStrictEqual, promisify } from "node:util";
32
29
  import { AsyncLocalStorage } from "node:async_hooks";
33
30
  import { createHash, randomUUID } from "node:crypto";
34
31
  import { createAssistantMessageEventStream, getInitialSystemMessage, getSystemMessageText as getSystemMessageText$1, mergeClientIdentity } from "@earendil-works/pi-ai";
35
- import { agentEventKeys, agentEventMatchKey, agentEventMatchSchema, declaredEventKeys, escapeTagTextAndQuotes, eventMatchFieldSchema, eventTriggerText, findTag, ownedObjectAnnotationSchema, renderInlineTag, stableEventMatchKey, startsWithTag, stripTags, watchResultSchema } from "@sentry/junior-plugin-api";
32
+ import { agentEventKeys, agentEventMatchKey, agentEventMatchSchema, declaredEventKeys, escapeTagTextAndQuotes, eventMatchFieldSchema, eventSchema, eventTriggerText, findTag, ownedObjectAnnotationSchema, renderInlineTag, stableEventMatchKey, startsWithTag, stripTags, watchResultSchema } from "@sentry/junior-plugin-api";
36
33
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
37
34
  import { and, asc, count, desc, eq, gt, gte, inArray, isNotNull, isNull, lt, lte, max, min, ne, not, notInArray, or, sql } from "drizzle-orm";
38
35
  import { alias, unionAll } from "drizzle-orm/pg-core";
@@ -1091,7 +1088,7 @@ function ownerLinks(item) {
1091
1088
  /** Read an Inbox item that the agent may read, or fail with a tool input error. */
1092
1089
  async function readableItem(id, scope) {
1093
1090
  const item = await getInboxItem(getDb(), id);
1094
- if (!item || !canReadInboxItem(item, scope.reader)) throw new ToolInputError(`Inbox item ${id} is not found.`);
1091
+ if (!item || !canReadInboxItem(item, scope.reader)) throw new ToolInputError(`Inbox item ${id} is not found. Use searchInboxItems to find its id.`);
1095
1092
  return item;
1096
1093
  }
1097
1094
  /** Render one Inbox item for a tool result. */
@@ -1685,7 +1682,7 @@ async function saveAutomationCardResult(conversationId, automation, card) {
1685
1682
  label: title,
1686
1683
  key: automation.id,
1687
1684
  title,
1688
- url: automation.dashboard_url,
1685
+ url: automation.url,
1689
1686
  description,
1690
1687
  status,
1691
1688
  trigger: card.trigger,
@@ -1709,7 +1706,7 @@ const compactEventAutomationResultSchema = z.object({
1709
1706
  ]),
1710
1707
  status_reason: z.string().nullable(),
1711
1708
  title: z.string().min(1).nullable(),
1712
- dashboard_url: z.string().url().nullable(),
1709
+ url: z.string().url().nullable(),
1713
1710
  task: automationTaskSchema,
1714
1711
  trigger: z.object({
1715
1712
  namespace: z.string().min(1),
@@ -1762,7 +1759,7 @@ function changedEventMatch(saved, namespace, changes) {
1762
1759
  function requireEventAutomationTrigger(catalog, input, options) {
1763
1760
  const identifier = input.identifier ?? void 0;
1764
1761
  const resourceType = input.resourceType ?? void 0;
1765
- if (identifier === void 0 !== (resourceType === void 0)) throw new ToolInputError("Set both resourceType and identifier for one resource, or leave out both to run for every resource.");
1762
+ if (identifier === void 0 !== (resourceType === void 0)) throw new ToolInputError("Set both resource_type and identifier for one resource, or leave out both to run for every resource.");
1766
1763
  const events = [...new Set(input.events)];
1767
1764
  const match = requireValidEventTrigger(automationEventCatalog(catalog), {
1768
1765
  namespace: input.namespace,
@@ -1803,7 +1800,7 @@ function compactEventAutomation(task, catalog, isCreator) {
1803
1800
  status: task.status,
1804
1801
  status_reason: task.statusReason ?? null,
1805
1802
  title: task.title?.trim() || null,
1806
- dashboard_url: getDashboardTaskLink(task.id) ?? null,
1803
+ url: getDashboardTaskLink(task.id) ?? null,
1807
1804
  task: task.task,
1808
1805
  trigger: {
1809
1806
  namespace: task.trigger.namespace,
@@ -1933,6 +1930,13 @@ function taskDisplayTitle(title, instruction, fallback) {
1933
1930
  if (stored) return stored;
1934
1931
  return fallbackShortTitle(instruction, fallback);
1935
1932
  }
1933
+ /**
1934
+ * The title that the Automations list shows for a row of
1935
+ * `viewerAutomationCollection`: its own, or else one from its task.
1936
+ */
1937
+ function collectionRowTitle(row) {
1938
+ return taskDisplayTitle(row.title ?? void 0, automationTaskDescription(automationTaskSchema.parse(row.task)), `Untitled ${row.kind} automation`);
1939
+ }
1936
1940
  async function destinationDetails(destinations) {
1937
1941
  const selectors = new Map(destinations.map((destination) => [destinationKey(destination), destination]));
1938
1942
  if (selectors.size === 0) return /* @__PURE__ */ new Map();
@@ -2210,7 +2214,7 @@ async function readViewerAutomationRuns(user) {
2210
2214
  const automationTitles = /* @__PURE__ */ new Map();
2211
2215
  const automations = [];
2212
2216
  for (const task of taskList) {
2213
- automationTitles.set(`${task.kind}:${task.id}`, taskDisplayTitle(task.title ?? void 0, automationTaskDescription(automationTaskSchema.parse(task.task)), `Untitled ${task.kind} automation`));
2217
+ automationTitles.set(`${task.kind}:${task.id}`, collectionRowTitle(task));
2214
2218
  automations.push({
2215
2219
  kind: task.kind,
2216
2220
  automationId: task.id
@@ -2663,7 +2667,7 @@ async function deleteAutomation(current) {
2663
2667
  /** Automation access for the Automation tools. */
2664
2668
  /**
2665
2669
  * Return the Actor when that person started this Turn from any surface.
2666
- * Automation runs, Events, plugin dispatch, and Agent invocations act for no
2670
+ * Automation runs, Events, plugin dispatch, and parent messages act for no
2667
2671
  * person, so they cannot manage Automations.
2668
2672
  */
2669
2673
  function personActor(context) {
@@ -2716,7 +2720,7 @@ function storedIdentities(resolved) {
2716
2720
  */
2717
2721
  async function requireToolCaller(context) {
2718
2722
  const actor = context.actor;
2719
- if (!actor || actor.userId.trim().toLowerCase() === "unknown") throw new ToolInputError("Automation tools need a Turn that a person started.");
2723
+ if (!actor || actor.userId.trim().toLowerCase() === "unknown") throw new ToolInputError("Automation tools need a Turn that a person started. No change to the call can fix this in this Turn.");
2720
2724
  const resolved = await context.users.resolveActor();
2721
2725
  return {
2722
2726
  actor,
@@ -2740,7 +2744,7 @@ function requireToolDestination(context) {
2740
2744
  function requireToolCreator(caller, destination, kind) {
2741
2745
  const matches = (identity) => identity.provider === destination.platform && identity.providerTenantId === destination.teamId;
2742
2746
  const identity = [caller.resolved?.identity, ...storedIdentities(caller.resolved)].find((candidate) => candidate && matches(candidate));
2743
- if (!identity) throw new ToolInputError(`${kind === "scheduled" ? "Scheduled" : "Event"} automation creator identity is unavailable.`);
2747
+ if (!identity) throw new ToolInputError(`${kind === "scheduled" ? "Scheduled" : "Event"} automation creator identity is unavailable: the person has no account in the workspace of the destination. No change to the call can fix this in this Turn.`);
2744
2748
  const { actor } = caller;
2745
2749
  const fullName = actor.fullName ?? identity.displayName;
2746
2750
  const userName = actor.userName ?? identity.handle;
@@ -2753,7 +2757,7 @@ function requireToolCreator(caller, destination, kind) {
2753
2757
  })
2754
2758
  };
2755
2759
  }
2756
- const NOT_FOUND = "Automation was not found. Automations in private channels and DMs can be managed only from there or by their creator.";
2760
+ const NOT_FOUND = "Automation was not found. Use searchAutomations to find its id. Automations in private channels and DMs can be managed only from there or by their creator.";
2757
2761
  /** Load one Automation that the tool caller can manage. */
2758
2762
  async function requireToolAutomation(caller, id) {
2759
2763
  const candidate = await resolveViewerTaskCandidate(caller.viewer, id);
@@ -2839,7 +2843,7 @@ const compactTaskResultSchema = z.object({
2839
2843
  ]),
2840
2844
  visibility: z.enum(["private", "public"])
2841
2845
  }).strict(),
2842
- dashboard_url: z.string().url().nullable(),
2846
+ url: z.string().url().nullable(),
2843
2847
  last_run_at: z.string().nullable(),
2844
2848
  run_now_at: z.string().nullable()
2845
2849
  }).strict();
@@ -2887,7 +2891,7 @@ function compactTask(task, isCreator) {
2887
2891
  next_run_at: task.nextRunAtMs ? new Date(task.nextRunAtMs).toISOString() : null,
2888
2892
  ...automationResultFields(task, isCreator),
2889
2893
  conversation_access: task.conversationAccess,
2890
- dashboard_url: getDashboardTaskLink(task.id) ?? null,
2894
+ url: getDashboardTaskLink(task.id) ?? null,
2891
2895
  last_run_at: task.lastRunAtMs ? new Date(task.lastRunAtMs).toISOString() : null,
2892
2896
  run_now_at: task.runNowAtMs ? new Date(task.runNowAtMs).toISOString() : null
2893
2897
  });
@@ -3609,7 +3613,7 @@ function validateAndApplyTextEdits(content, edits, targetName) {
3609
3613
  const matchIndex = content.indexOf(edit.oldText);
3610
3614
  if (matchIndex === -1) throw new ToolInputError(`Could not find edits[${index}] in ${targetName}. old_text must match exactly including whitespace and newlines.`);
3611
3615
  const occurrences = countOccurrences(content, edit.oldText);
3612
- if (occurrences > 1) throw new ToolInputError(`Found ${occurrences} occurrences of edits[${index}] in ${targetName}. Each old_text must be unique.`);
3616
+ if (occurrences > 1) throw new ToolInputError(`Found ${occurrences} occurrences of edits[${index}] in ${targetName}. Each old_text must be unique. Add surrounding text to old_text so that it matches once.`);
3613
3617
  matchedEdits.push({
3614
3618
  editIndex: index,
3615
3619
  matchIndex,
@@ -3625,7 +3629,7 @@ function validateAndApplyTextEdits(content, edits, targetName) {
3625
3629
  }
3626
3630
  let newContent = content;
3627
3631
  for (const edit of [...matchedEdits].reverse()) newContent = newContent.slice(0, edit.matchIndex) + edit.newText + newContent.slice(edit.matchIndex + edit.matchLength);
3628
- if (newContent === content) throw new ToolInputError(`No changes made to ${targetName}.`);
3632
+ if (newContent === content) throw new ToolInputError(`No changes made to ${targetName}. Set new_text to text that differs from old_text, or remove that edit.`);
3629
3633
  return {
3630
3634
  baseContent: content,
3631
3635
  newContent
@@ -3648,7 +3652,7 @@ const editReplacementSchema$1 = z.object({
3648
3652
  const slackCanvasEditOutputSchema = juniorToolOutputSchema.extend({
3649
3653
  canvas_id: z.string().optional(),
3650
3654
  title: z.string().optional(),
3651
- permalink: z.string().optional(),
3655
+ url: z.string().optional(),
3652
3656
  diff: z.string().optional(),
3653
3657
  first_changed_line: z.number().int().positive().optional(),
3654
3658
  replacements: z.number().int().nonnegative().optional(),
@@ -3700,7 +3704,7 @@ function createSlackCanvasEditTool(state) {
3700
3704
  const response = {
3701
3705
  canvas_id: target.canvasId,
3702
3706
  title: current.title,
3703
- permalink: current.permalink,
3707
+ url: current.permalink,
3704
3708
  diff: diff.diff,
3705
3709
  first_changed_line: diff.firstChangedLine,
3706
3710
  replacements: edits.length,
@@ -3716,7 +3720,7 @@ function createSlackCanvasEditTool(state) {
3716
3720
  const slackCanvasReadOutputSchema = juniorToolOutputSchema.extend({
3717
3721
  canvas_id: z.string().optional(),
3718
3722
  title: z.string().optional(),
3719
- permalink: z.string().optional(),
3723
+ url: z.string().optional(),
3720
3724
  mimetype: z.string().optional(),
3721
3725
  filetype: z.string().optional(),
3722
3726
  original_byte_length: z.number().int().nonnegative().optional(),
@@ -3774,7 +3778,7 @@ function createSlackCanvasReadTool() {
3774
3778
  return {
3775
3779
  canvas_id: result.canvasId,
3776
3780
  title: result.title,
3777
- permalink: result.permalink,
3781
+ url: result.permalink,
3778
3782
  mimetype: result.mimetype,
3779
3783
  filetype: result.filetype,
3780
3784
  original_byte_length: result.byteLength,
@@ -3919,7 +3923,7 @@ function createSlackChannelJoinTool(context) {
3919
3923
  await joinPublicChannel(target.channelId);
3920
3924
  } catch (error) {
3921
3925
  if (error instanceof SlackActionError) {
3922
- if (error.code === "missing_scope") throw new ToolInputError("Cannot join this public Slack channel because this installation is missing the `channels:join` scope.", { cause: error });
3926
+ if (error.code === "missing_scope") throw new ToolInputError("Cannot join this public Slack channel because this installation is missing the `channels:join` scope. No change to the call can fix this; ask someone to add the bot to the channel.", { cause: error });
3923
3927
  throw new ToolInputError("Could not join this public Slack channel. Confirm it is public and retry, or ask an admin to add the bot.", { cause: error });
3924
3928
  }
3925
3929
  throw error;
@@ -4127,9 +4131,9 @@ function createSlackChannelListMessagesTool(context) {
4127
4131
  const error = readError;
4128
4132
  if (error instanceof SlackActionError && error.apiError === "invalid_cursor") throw new ToolInputError("The supplied Slack history cursor is no longer valid. Retry the lookup without `cursor` to start from the newest page again.", { cause: error });
4129
4133
  if (error instanceof SlackActionError) {
4130
- if (error.code === "not_in_channel") throw new ToolInputError("Could not read this Slack channel history because the bot is not in the channel.", { cause: error });
4131
- if (error.code === "missing_scope") throw new ToolInputError("Could not read this Slack channel history because this installation is missing history scopes.", { cause: error });
4132
- throw new ToolInputError("Could not read this Slack channel history.", { cause: error });
4134
+ if (error.code === "not_in_channel") throw new ToolInputError("Could not read this Slack channel history because the bot is not in the channel. Ask someone to add the bot to the channel.", { cause: error });
4135
+ if (error.code === "missing_scope") throw new ToolInputError("Could not read this Slack channel history because this installation is missing history scopes. No change to the call can fix this.", { cause: error });
4136
+ throw new ToolInputError("Could not read this Slack channel history. Check channel_id, or continue without it.", { cause: error });
4133
4137
  }
4134
4138
  throw error;
4135
4139
  }
@@ -4158,17 +4162,17 @@ function createSlackConversationSearchChannelPort(teamId) {
4158
4162
  teamId
4159
4163
  })).channelId;
4160
4164
  },
4161
- async describeMatch(match) {
4165
+ async describeMatch(match, options) {
4162
4166
  const reference = parseSlackThreadId(match.rootConversationId);
4163
4167
  if (!reference || reference.channelId !== match.providerDestinationId) return {};
4164
- const permalink = await getSlackMessagePermalink({
4168
+ const url = options.includeUrl ? await getSlackMessagePermalink({
4165
4169
  channelId: reference.channelId,
4166
4170
  messageTs: reference.threadTs
4167
- });
4171
+ }) : void 0;
4168
4172
  return {
4169
4173
  channel_id: reference.channelId,
4170
4174
  ...match.channelName ? { channel_name: match.channelName } : void 0,
4171
- ...permalink ? { permalink } : void 0
4175
+ ...url ? { url } : void 0
4172
4176
  };
4173
4177
  }
4174
4178
  };
@@ -4197,7 +4201,7 @@ const conversationMessageSearchOutputSchema = juniorToolOutputSchema.extend({
4197
4201
  message_id: z.string().min(1),
4198
4202
  message_role: z.enum(["assistant", "user"]),
4199
4203
  message_timestamp: z.string().datetime(),
4200
- permalink: z.string().url().optional(),
4204
+ url: z.string().url().optional().describe("Link to the conversation."),
4201
4205
  thread_ts: z.string().min(1)
4202
4206
  }).strict())
4203
4207
  });
@@ -4268,7 +4272,7 @@ function createSlackConversationMessageSearchTool(teamId, currentConversationId)
4268
4272
  const matchesOutput = await Promise.all(matches.map(async (match) => {
4269
4273
  const reference = parseSlackThreadId(match.conversationId);
4270
4274
  if (!reference || reference.channelId !== match.providerDestinationId) throw new Error("Stored Slack conversation search returned an invalid destination");
4271
- const permalink = await getSlackMessagePermalink({
4275
+ const url = getDashboardConversationLink(match.conversationId) ?? await getSlackMessagePermalink({
4272
4276
  channelId: reference.channelId,
4273
4277
  messageTs: reference.threadTs
4274
4278
  });
@@ -4281,7 +4285,7 @@ function createSlackConversationMessageSearchTool(teamId, currentConversationId)
4281
4285
  excerpt: match.excerpt,
4282
4286
  channel_id: match.providerDestinationId,
4283
4287
  ...match.channelName ? { channel_name: match.channelName } : void 0,
4284
- ...permalink ? { permalink } : void 0
4288
+ ...url ? { url } : void 0
4285
4289
  };
4286
4290
  }));
4287
4291
  return {
@@ -4541,7 +4545,7 @@ function createSlackListCreateTool(state) {
4541
4545
  const list = await createTodoList(name);
4542
4546
  const response = {
4543
4547
  list_id: list.listId,
4544
- permalink: list.permalink,
4548
+ url: list.permalink,
4545
4549
  column_map: list.listColumnMap
4546
4550
  };
4547
4551
  state.setOperationResult(operationKey, response);
@@ -4674,7 +4678,7 @@ const searchMessageSchema = z.object({
4674
4678
  message_ts: z.string().min(1).describe("Message timestamp."),
4675
4679
  content: z.string().describe("Message text."),
4676
4680
  is_author_bot: z.boolean().optional().describe("Whether the author is a bot."),
4677
- permalink: z.string().url().describe("Message permalink.")
4681
+ url: z.string().url().describe("Link to the message.")
4678
4682
  });
4679
4683
  /** Canonical public-search file result. */
4680
4684
  const searchFileSchema = z.object({
@@ -4686,7 +4690,7 @@ const searchFileSchema = z.object({
4686
4690
  user_name: z.string().min(1).optional().describe("Uploader user name."),
4687
4691
  channel_id: z.string().min(1).optional().describe("Channel ID."),
4688
4692
  channel_name: z.string().min(1).optional().describe("Channel name."),
4689
- permalink: z.string().url().optional().describe("File permalink."),
4693
+ url: z.string().url().optional().describe("Link to the file."),
4690
4694
  content: z.string().min(1).optional().describe("File preview or content snippet.")
4691
4695
  });
4692
4696
  /** Canonical public-search channel result. */
@@ -4697,7 +4701,7 @@ const searchChannelSchema = z.object({
4697
4701
  is_member: z.boolean().optional().describe("Whether the bot is a member."),
4698
4702
  topic: z.string().min(1).optional().describe("Channel topic."),
4699
4703
  purpose: z.string().min(1).optional().describe("Channel purpose."),
4700
- permalink: z.string().url().optional().describe("Channel permalink.")
4704
+ url: z.string().url().optional().describe("Link to the channel.")
4701
4705
  });
4702
4706
  /** Canonical public-search user result. */
4703
4707
  const searchUserSchema = z.object({
@@ -4706,7 +4710,7 @@ const searchUserSchema = z.object({
4706
4710
  real_name: z.string().min(1).optional().describe("Real name."),
4707
4711
  display_name: z.string().min(1).optional().describe("Display name."),
4708
4712
  title: z.string().min(1).optional().describe("Profile title."),
4709
- permalink: z.string().url().optional().describe("Profile permalink.")
4713
+ url: z.string().url().optional().describe("Link to the profile.")
4710
4714
  });
4711
4715
  const publicSearchOutputSchema = juniorToolOutputSchema.extend({
4712
4716
  query: z.string().describe("Search query."),
@@ -4753,7 +4757,7 @@ const slackSearchMessageWireSchema = z.object({
4753
4757
  channel_id: value.channel_id,
4754
4758
  message_ts: value.message_ts,
4755
4759
  content: value.content,
4756
- permalink: value.permalink,
4760
+ url: value.permalink,
4757
4761
  ...value.author_name ? { author_name: value.author_name } : void 0,
4758
4762
  ...value.author_user_id ? { author_user_id: value.author_user_id } : void 0,
4759
4763
  ...value.channel_name ? { channel_name: value.channel_name } : void 0,
@@ -4788,7 +4792,7 @@ const slackSearchFileWireSchema = z.object({
4788
4792
  ...value.user_name ?? value.username ? { user_name: value.user_name ?? value.username } : void 0,
4789
4793
  ...value.channel_id ? { channel_id: value.channel_id } : void 0,
4790
4794
  ...value.channel_name ? { channel_name: value.channel_name } : void 0,
4791
- ...value.permalink ? { permalink: value.permalink } : void 0,
4795
+ ...value.permalink ? { url: value.permalink } : void 0,
4792
4796
  ...value.content ?? value.preview ? { content: value.content ?? value.preview } : void 0
4793
4797
  };
4794
4798
  });
@@ -4817,7 +4821,7 @@ const slackSearchChannelWireSchema = z.object({
4817
4821
  ...value.is_member !== void 0 ? { is_member: value.is_member } : void 0,
4818
4822
  ...value.topic ? { topic: value.topic } : void 0,
4819
4823
  ...value.purpose ? { purpose: value.purpose } : void 0,
4820
- ...value.permalink ? { permalink: value.permalink } : void 0
4824
+ ...value.permalink ? { url: value.permalink } : void 0
4821
4825
  };
4822
4826
  });
4823
4827
  /** Slack wire shape for one search user. */
@@ -4840,7 +4844,7 @@ const slackSearchUserWireSchema = z.object({
4840
4844
  ...value.real_name ? { real_name: value.real_name } : void 0,
4841
4845
  ...value.display_name ? { display_name: value.display_name } : void 0,
4842
4846
  ...value.title ? { title: value.title } : void 0,
4843
- ...value.permalink ? { permalink: value.permalink } : void 0
4847
+ ...value.permalink ? { url: value.permalink } : void 0
4844
4848
  };
4845
4849
  });
4846
4850
  const slackSearchResponseSchema = z.object({ results: z.object({
@@ -4866,10 +4870,10 @@ function parseItems(values, schema) {
4866
4870
  function explicitSearchError(error) {
4867
4871
  if (error.code === "missing_scope") {
4868
4872
  const needed = error.needed?.trim();
4869
- if (needed) return `Public Slack search is unavailable because this installation is missing the \`${needed}\` scope.`;
4870
- return "Public Slack search is unavailable because this installation is missing a required search scope (`search:read.public`, and `search:read.files` / `search:read.users` when those content types are requested).";
4873
+ if (needed) return `Public Slack search is unavailable because this installation is missing the \`${needed}\` scope. Use slackChannelListMessages or slackThreadRead when you know the channel.`;
4874
+ return "Public Slack search is unavailable because this installation is missing a required search scope (`search:read.public`, and `search:read.files` / `search:read.users` when those content types are requested). Use slackChannelListMessages or slackThreadRead when you know the channel.";
4871
4875
  }
4872
- if (error.code === "feature_unavailable") return "Public Slack search is not available for this Slack workspace or app installation.";
4876
+ if (error.code === "feature_unavailable") return "Public Slack search is not available for this Slack workspace or app installation. Use slackChannelListMessages or slackThreadRead when you know the channel.";
4873
4877
  if (error.apiError === "invalid_action_token") return "Public Slack search could not use the current Slack interaction token. Ask again in a new message or mention.";
4874
4878
  }
4875
4879
  function normalizeContentTypes(contentTypes) {
@@ -5293,7 +5297,7 @@ function createSlackThreadReadTool(context, attachmentDeps) {
5293
5297
  let threadTs;
5294
5298
  if (url) {
5295
5299
  const parsed = parseSlackMessageReference(url);
5296
- if (!parsed.ok) throw new ToolInputError(parsed.error);
5300
+ if (!parsed.ok) throw new ToolInputError(`${parsed.error}. Set url to a Slack message link, such as https://example.slack.com/archives/C123/p1712345678123456, or set channel_id and slack_ts.`);
5297
5301
  channelId = parsed.reference.channelId;
5298
5302
  messageTs = parsed.reference.messageTs;
5299
5303
  threadTs = parsed.reference.threadTs;
@@ -5347,13 +5351,13 @@ function createSlackThreadReadTool(context, attachmentDeps) {
5347
5351
  if (!replies) {
5348
5352
  const error = readError;
5349
5353
  if (error instanceof SlackActionError) {
5350
- if (error.code === "not_in_channel") throw new ToolInputError("Could not read this Slack thread because the bot is not in the channel.", { cause: error });
5351
- if (error.code === "missing_scope") throw new ToolInputError("Could not read this Slack thread because this installation is missing history scopes.", { cause: error });
5352
- throw new ToolInputError("Could not read this Slack thread.", { cause: error });
5354
+ if (error.code === "not_in_channel") throw new ToolInputError("Could not read this Slack thread because the bot is not in the channel. Ask someone to add the bot to the channel.", { cause: error });
5355
+ if (error.code === "missing_scope") throw new ToolInputError("Could not read this Slack thread because this installation is missing history scopes. No change to the call can fix this.", { cause: error });
5356
+ throw new ToolInputError("Could not read this Slack thread. Check url, or channel_id and slack_ts, or continue without it.", { cause: error });
5353
5357
  }
5354
5358
  throw error;
5355
5359
  }
5356
- if (replies.length === 0) throw new ToolInputError("No messages found for this thread.");
5360
+ if (replies.length === 0) throw new ToolInputError("No messages found for this thread. Check url, or channel_id and slack_ts.");
5357
5361
  const root = replies[0];
5358
5362
  const resolvedThreadTs = threadTs ?? root?.thread_ts ?? root?.ts ?? lookupTs;
5359
5363
  const slackFileIds = replies.flatMap((reply) => collectMessageFiles(reply).map((file) => file.id).filter((fileId) => Boolean(fileId)));
@@ -5556,7 +5560,7 @@ const setConversationSubscriptionToolDefinition = zodToolDefinition({
5556
5560
  * Build the tool that changes the subscription of the person who started
5557
5561
  * the Turn, in the current Conversation. The actor comes from the runtime,
5558
5562
  * not from model arguments, so it cannot change another person's
5559
- * subscription. The registry never offers it to an Agent invocation,
5563
+ * subscription. The registry never offers it to a Turn on a parent message,
5560
5564
  * because an agent wrote its input. Contract:
5561
5565
  * `api/conversations/subscription.ts`.
5562
5566
  */
@@ -5565,9 +5569,9 @@ function createSetConversationSubscriptionTool(context) {
5565
5569
  ...setConversationSubscriptionToolDefinition,
5566
5570
  async execute(input) {
5567
5571
  const user = (await context.resolveActorIdentity?.())?.user;
5568
- if (!user) throw new ToolInputError("This person has no linked User, so their subscription cannot change.");
5572
+ if (!user) throw new ToolInputError("This person has no linked User, so their subscription cannot change. No change to the call can fix this.");
5569
5573
  const result = await updateConversationSubscription(user, context.conversationId, input.subscribed);
5570
- if (!result) throw new ToolInputError("This person is not a participant of this conversation.");
5574
+ if (!result) throw new ToolInputError("This person is not a participant of this conversation, so they have no subscription to change. No change to the call can fix this.");
5571
5575
  return {
5572
5576
  archived_at: result.archivedAt,
5573
5577
  subscribed: result.subscribed
@@ -5575,6 +5579,43 @@ function createSetConversationSubscriptionTool(context) {
5575
5579
  }
5576
5580
  });
5577
5581
  }
5582
+ // src/chat/tool-exposure.ts
5583
+ /** Return the runtime exposure for a tool, preserving direct compatibility. */
5584
+ function effectiveToolExposure(definition) {
5585
+ return definition.exposure ?? "direct";
5586
+ }
5587
+ /**
5588
+ * Return the tool as a Turn lists it. A deferred tool that the Turn's tool
5589
+ * config names in `direct` is in the model tool list. Other exposures do not
5590
+ * change, so `direct` cannot reveal a Code Mode-only or hidden tool.
5591
+ */
5592
+ function listedToolExposure(listedTools, name, tool) {
5593
+ return listedTools.direct?.includes(name) && effectiveToolExposure(tool) === "deferred" ? {
5594
+ ...tool,
5595
+ exposure: "direct"
5596
+ } : tool;
5597
+ }
5598
+ const EXPOSURE_TABLES = {
5599
+ direct: [
5600
+ "directTools",
5601
+ "catalogTools",
5602
+ "scriptTools"
5603
+ ],
5604
+ deferred: ["catalogTools", "scriptTools"],
5605
+ modelOnly: ["directTools"],
5606
+ codemode: ["scriptTools"],
5607
+ hidden: []
5608
+ };
5609
+ /** Plan which callers may call each tool. `ToolExposure` owns the rules. */
5610
+ function planToolExposure(tools) {
5611
+ const planned = {
5612
+ catalogTools: {},
5613
+ directTools: {},
5614
+ scriptTools: {}
5615
+ };
5616
+ for (const [name, definition] of Object.entries(tools)) for (const table of EXPOSURE_TABLES[effectiveToolExposure(definition)]) planned[table][name] = definition;
5617
+ return planned;
5618
+ }
5578
5619
  // src/chat/events/owned-watches.ts
5579
5620
  /**
5580
5621
  * Watch ownership for the watch tools. A Conversation owns its own watches and
@@ -5770,10 +5811,10 @@ function createRunOperatorSqlTool() {
5770
5811
  * the error does not show that a private Conversation exists.
5771
5812
  */
5772
5813
  async function assertCanReadConversationEvents(context, conversationId) {
5773
- const notAccessible = new ToolInputError(`Conversation events are not accessible: ${conversationId}`);
5814
+ const notAccessible = new ToolInputError(`Conversation events are not accessible: ${conversationId}. Check conversation_id, or use searchConversations to find a Conversation that you can read.`);
5774
5815
  const [readable, target] = await Promise.all([canReadConversation(getDb(), context.conversationId, conversationId), getConversationStore().get({ conversationId })]);
5775
5816
  if (!readable || !target) throw notAccessible;
5776
- if (target.transcriptPurgedAtMs !== void 0) throw new ToolInputError(`Conversation transcript was purged: ${conversationId}`);
5817
+ if (target.transcriptPurgedAtMs !== void 0) throw new ToolInputError(`Conversation transcript was purged: ${conversationId}. No change to the call can fix this.`);
5777
5818
  }
5778
5819
  /** Replace replacement history with its item count; the original events stay readable by seq. */
5779
5820
  function stripReplacementHistory(data) {
@@ -5844,9 +5885,9 @@ function createReadConversationEventTool(context) {
5844
5885
  beforeSeq: input.seq + 1,
5845
5886
  limit: 1
5846
5887
  })).events[0];
5847
- if (!event) throw new ToolInputError(`Conversation event not found: seq ${input.seq} in ${conversationId}`);
5888
+ if (!event) throw new ToolInputError(`Conversation event not found: seq ${input.seq} in ${conversationId}. Use searchConversationEvents to find a seq.`);
5848
5889
  const text = eventText(event.data);
5849
- if (offset > 0 && offset >= text.length) throw new ToolInputError(`offset ${offset} is past the end of the event text (${text.length} chars)`);
5890
+ if (offset > 0 && offset >= text.length) throw new ToolInputError(`offset ${offset} is past the end of the event text (${text.length} chars). Set offset below ${text.length}.`);
5850
5891
  const slice = text.slice(offset, limit === void 0 ? void 0 : offset + limit);
5851
5892
  return {
5852
5893
  conversation_id: conversationId,
@@ -6156,7 +6197,7 @@ function createUpdateInboxItemTool(context, services) {
6156
6197
  const changesContent = input.title || input.body || input.assignees || input.conversation_ids;
6157
6198
  const retriesClose = item.status !== "open" && !changesContent && !item.closedBy && input.status === item.status && input.reason === item.closeReason;
6158
6199
  const closesOnly = !changesContent && input.status && input.reason;
6159
- if (item.status !== "open" && !retriesClose && !closesOnly) throw new ToolInputError(`Inbox item ${item.id} is already closed.`);
6200
+ if (item.status !== "open" && !retriesClose && !closesOnly) throw new ToolInputError(`Inbox item ${item.id} is already closed. To follow up, add a new item with addInboxItem.`);
6160
6201
  if (item.dedupeKey.startsWith("plugin:")) throw new ToolInputError("A plugin added this item. Only the plugin or a person can change it.");
6161
6202
  if (!ownerConversationId(item)) throw new ToolInputError("No Conversation owns this item. It is an Automation alert, which closes when its Automation recovers. Only a person can dismiss it.");
6162
6203
  if (!canAgentChangeInboxItem(item, scope)) throw new ToolInputError("This Conversation cannot change this item. A public item changes only from a public Conversation. A private item changes only from the Conversation or Automation that added it.");
@@ -6199,7 +6240,7 @@ function createUpdateInboxItemTool(context, services) {
6199
6240
  visibility,
6200
6241
  ...item.request ? { request: item.request } : void 0,
6201
6242
  ...item.subject ? { subject: item.subject } : void 0
6202
- })) throw new ToolInputError(`Inbox item ${item.id} is already closed.`);
6243
+ })) throw new ToolInputError(`Inbox item ${item.id} is already closed. To follow up, add a new item with addInboxItem.`);
6203
6244
  }
6204
6245
  if (input.status && input.reason) {
6205
6246
  const nowMs = Date.now();
@@ -6209,7 +6250,7 @@ function createUpdateInboxItemTool(context, services) {
6209
6250
  reason: input.reason,
6210
6251
  status: input.status
6211
6252
  }))) {
6212
- if (changesContent) throw new ToolInputError(`Inbox item ${item.id} is already closed.`);
6253
+ if (changesContent) throw new ToolInputError(`Inbox item ${item.id} is already closed. To follow up, add a new item with addInboxItem.`);
6213
6254
  return alreadyClosedResult(await readableItem(item.id, scope));
6214
6255
  }
6215
6256
  const closedItem = await readableItem(item.id, scope);
@@ -6291,7 +6332,13 @@ const addInboxItemToolDefinition = zodToolDefinition({
6291
6332
  title: titleSchema$1,
6292
6333
  body: bodySchema,
6293
6334
  assignees: assigneesSchema.nullable().optional().describe("Who can act on the item. Omit for the person in this Turn, else the Automation creator in an Automation run, else the people still subscribed to the Conversation."),
6294
- dedupe_key: z.string().trim().min(1).max(200).nullable().optional().describe("Stable key for what the item is about, such as `fair-source:entry:acme`. If an open item has this key, the call updates that item instead of adding another. Use the same key on each run. Omit for a one-time question."),
6335
+ dedupe_key: z.string().trim().min(1).max(200).superRefine((key, context) => {
6336
+ const reserved = RESERVED_INBOX_ITEM_KEY_PREFIXES.find(({ prefix }) => key.startsWith(prefix));
6337
+ if (reserved) context.addIssue({
6338
+ code: "custom",
6339
+ message: `A \`dedupe_key\` that starts with \`${reserved.prefix}\` belongs to ${reserved.owner}. ${reserved.instead}`
6340
+ });
6341
+ }).nullable().optional().describe("Stable key for what the item is about, such as `fair-source:entry:acme`. If an open item has this key, the call updates that item instead of adding another. Use the same key on each run. Omit for a one-time question."),
6295
6342
  request: userInputRequestSchema.safeExtend({ evidence: evidenceSchema.nullable().optional().describe("Sources for the facts in the question. With a suggested answer, cite what supports it and what argues against it, such as a Conversation or chart that disagrees. Each entry has a `url` or a `conversation_id`.") }).nullable().optional().describe("Required for an action item. Not allowed for a notice. Ask for related input in one item. Write the question so it stands alone: a person who sees only the card must understand it."),
6296
6343
  subject: subjectSchema.nullable().optional(),
6297
6344
  conversation_ids: conversationIdsSchema.nullable().optional().describe("Other Conversations to link. The current Conversation is always linked.")
@@ -6327,8 +6374,6 @@ function createAddInboxItemTool(context, services) {
6327
6374
  execute: async (input, options) => {
6328
6375
  requireRequest(input.kind, Boolean(input.request));
6329
6376
  const evidence = evidenceInput(input.request?.evidence);
6330
- if (input.dedupe_key?.startsWith("plugin:")) throw new ToolInputError(`A \`dedupe_key\` that starts with \`${PLUGIN_INBOX_ITEM_KEY_PREFIX}\` belongs to a plugin. Use a different key.`);
6331
- if (input.dedupe_key?.startsWith("automation:")) throw new ToolInputError(`A \`dedupe_key\` that starts with \`${AUTOMATION_INBOX_ITEM_KEY_PREFIX}\` belongs to an Automation alert. Use a different key.`);
6332
6377
  const db = getDb();
6333
6378
  const scope = await readInboxItemAgentScope(context);
6334
6379
  const dedupeKey = input.dedupe_key ?? `ask:${options.toolCallId ?? randomUUID()}`;
@@ -6425,10 +6470,16 @@ function createAddInboxItemTool(context, services) {
6425
6470
  async function publishWaiting(services, item) {
6426
6471
  const conversationId = ownerConversationId(item);
6427
6472
  if (item.kind !== "action" || !conversationId) return;
6428
- await publishConversationStatus(conversationId, {
6473
+ await publishAgentUpdate(conversationId, {
6429
6474
  type: "waiting",
6430
6475
  inboxItemId: item.id
6431
- }, { queue: services.queue() });
6476
+ }, {
6477
+ queue: services.queue(),
6478
+ update: async () => ({
6479
+ status: "waiting",
6480
+ text: item.request?.question ?? item.body
6481
+ })
6482
+ });
6432
6483
  }
6433
6484
  // src/api/conversations/read-position.ts
6434
6485
  /**
@@ -6450,7 +6501,8 @@ function latestViewerMessageSeq(viewer, conversationId) {
6450
6501
  return getDb().select({ seq: max(juniorConversationEvents.seq) }).from(juniorConversationEvents).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversationEvents.actorIdentityId)).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "message"), eq(juniorIdentities.userId, viewer.id)));
6451
6502
  }
6452
6503
  /**
6453
- * Move the viewer's read position forward.
6504
+ * Move the viewer's read position forward. A read that reaches the latest
6505
+ * reply closes the viewer's reply notice of the Conversation.
6454
6506
  *
6455
6507
  * The stored value never goes back, so devices can report in any order. A
6456
6508
  * value past the last event is cut to the last event, so a bad client cannot
@@ -6474,6 +6526,11 @@ async function markConversationRead(viewer, conversationId, body) {
6474
6526
  updatedAt: sql`excluded.updated_at`
6475
6527
  }
6476
6528
  });
6529
+ await closeReadReplyNotice(tx, {
6530
+ conversationId,
6531
+ nowMs: Date.now(),
6532
+ userId: viewer.id
6533
+ });
6477
6534
  if (await readStatus(tx, conversationId) !== before) await touchConversationDetail(tx, [conversationId]);
6478
6535
  });
6479
6536
  return await readConversationReadPosition(viewer, conversationId);
@@ -6621,7 +6678,7 @@ async function readLastPersonMessageAtMs(conversationId) {
6621
6678
  const archiveAgentToolDefinition = zodToolDefinition({
6622
6679
  exposure: "deferred",
6623
6680
  source: AGENTS_TOOL_SOURCE,
6624
- description: "Archive a Thread that this conversation started, for everyone. A person's new message restores it. A result from a Thread does not mean that people are done with it: people message Threads directly, and you do not see those messages. The archive fails when a person messaged the Thread since you last gave it work: that person decides, and can archive it from its dashboard_url.",
6681
+ description: "Archive a Thread that this conversation started, for everyone. A person's new message restores it. A result from a Thread does not mean that people are done with it: people message Threads directly, and you do not see those messages. The archive fails when a person messaged the Thread since you last gave it work: that person decides, and can archive it from its url.",
6625
6682
  annotations: {
6626
6683
  destructiveHint: false,
6627
6684
  idempotentHint: true,
@@ -6647,11 +6704,10 @@ function createArchiveAgentTool(conversationId) {
6647
6704
  conversation_id: childConversationId,
6648
6705
  archived_at: new Date(child.archivedAtMs).toISOString()
6649
6706
  };
6650
- if (child.execution.status === "pending" || child.execution.status === "running" || child.execution.status === "paused" || (await listOpenAgentInvocations(childConversationId)).some((row) => row.childConversationId === childConversationId)) throw new ToolInputError(`${childConversationId} is working. Leave it, or wait until it is idle.`);
6707
+ if (child.execution.status === "pending" || child.execution.status === "running" || child.execution.status === "paused") throw new ToolInputError(`${childConversationId} is working. Leave it, or wait until it is idle.`);
6651
6708
  const personMessageAt = await readLastPersonMessageAtMs(childConversationId);
6652
- const latest = await getLatestAgentInvocationForConversation(childConversationId);
6653
- const lastWorkAt = latest ? latest.createdAtMs : await readLastParentMessageAtMs(childConversationId);
6654
- if (personMessageAt !== void 0 && personMessageAt > (lastWorkAt ?? 0)) throw new ToolInputError(`A person messaged ${childConversationId} since you last gave it work, so a person still uses it. Leave it. That person can archive it from its dashboard_url.`);
6709
+ const lastWorkAt = await readLastParentMessageAtMs(childConversationId);
6710
+ if (personMessageAt !== void 0 && personMessageAt > (lastWorkAt ?? 0)) throw new ToolInputError(`A person messaged ${childConversationId} since you last gave it work, so a person still uses it. Leave it. That person can archive it from its url.`);
6655
6711
  const result = await setConversationArchive({
6656
6712
  applyToChildren: input.apply_to_children ?? false,
6657
6713
  archived: true,
@@ -6672,6 +6728,48 @@ function createArchiveAgentTool(conversationId) {
6672
6728
  }
6673
6729
  });
6674
6730
  }
6731
+ // src/chat/agent-invocations/errors.ts
6732
+ /** A child agent already uses this name in the parent Conversation. */
6733
+ var AgentNameInUseError = class extends Error {
6734
+ constructor(name) {
6735
+ super(`A child agent named "${name}" already exists`);
6736
+ this.name = "AgentNameInUseError";
6737
+ }
6738
+ };
6739
+ /** Parent already has the maximum number of active child agents. */
6740
+ var AgentInvocationLimitError = class extends Error {
6741
+ constructor(limit) {
6742
+ super(`Parent already has ${limit} active child agents (limit ${limit})`);
6743
+ this.name = "AgentInvocationLimitError";
6744
+ }
6745
+ };
6746
+ /**
6747
+ * The Conversation that calls spawnAgent is too deep to start child agents,
6748
+ * or its parent chain does not end at a root.
6749
+ */
6750
+ var AgentDepthLimitError = class extends Error {
6751
+ constructor(maxAgentDepth) {
6752
+ super(`This agent cannot start child agents: only ${maxAgentDepth} level(s) of child agents can start their own`);
6753
+ this.name = "AgentDepthLimitError";
6754
+ }
6755
+ };
6756
+ /** A stopped Conversation cannot give work to child agents. */
6757
+ var AgentStoppedError = class extends Error {
6758
+ constructor() {
6759
+ super("This conversation is stopped, so it cannot give work to child agents");
6760
+ this.name = "AgentStoppedError";
6761
+ }
6762
+ };
6763
+ /**
6764
+ * A messageAgent target is not the parent, a child, or a top-level agent that
6765
+ * the sender can message.
6766
+ */
6767
+ var AgentMessageTargetError = class extends Error {
6768
+ constructor(message) {
6769
+ super(message);
6770
+ this.name = "AgentMessageTargetError";
6771
+ }
6772
+ };
6675
6773
  // src/chat/tools/runtime/message-agent.ts
6676
6774
  /** Bound the text of one message so a loop cannot fill a mailbox quickly. */
6677
6775
  const MESSAGE_AGENT_TEXT_MAX_LENGTH = 8e3;
@@ -6707,7 +6805,7 @@ function createMessageAgentTool(messageAgent) {
6707
6805
  return zodTool({
6708
6806
  ...messageAgentToolDefinition,
6709
6807
  execute: async (input, options) => {
6710
- if (!options.toolCallId) throw new ToolInputError("messageAgent requires an active tool call ID");
6808
+ if (!options.toolCallId) throw new ToolInputError("messageAgent requires an active tool call ID. No change to the call can fix this.");
6711
6809
  let result;
6712
6810
  try {
6713
6811
  result = await messageAgent({
@@ -6720,7 +6818,6 @@ function createMessageAgentTool(messageAgent) {
6720
6818
  } catch (error) {
6721
6819
  if (error instanceof AgentMessageTargetError) throw new ToolInputError(`${error.message}. Use listAgents to find an agent.`, { cause: error });
6722
6820
  if (error instanceof AgentStoppedError) throw new ToolInputError(`${error.message}. Do not start more work. End this turn.`, { cause: error });
6723
- if (error instanceof AgentMessageQueueFullError) throw new ToolInputError(`${error.message}. Wait for its result, then send one message with everything it needs.`, { cause: error });
6724
6821
  if (error instanceof AgentInvocationLimitError) throw new ToolInputError(`${error.message}. Wait for active children to finish before you give more work.`, { cause: error });
6725
6822
  throw error;
6726
6823
  }
@@ -6739,9 +6836,9 @@ const noReplyToolDefinition = zodToolDefinition({
6739
6836
  openWorldHint: false,
6740
6837
  readOnlyHint: true
6741
6838
  },
6742
- description: "End the Turn without a reply. Nothing is posted and nobody is notified.",
6839
+ description: "End the Turn quietly, without a reply.",
6743
6840
  exposure: "modelOnly",
6744
- inputSchema: z.object({ note: z.string().trim().min(1).nullable().optional().describe("Outcome to keep in the conversation without notifying anyone, such as a routine fix that worked. Omit it when a person asked for no reply. Null is the same as omitted.") }).strict(),
6841
+ inputSchema: z.object({ note: z.string().trim().min(1).nullable().optional().describe("Outcome to keep in the conversation, such as a routine fix that worked. A parent agent or a watcher of this conversation can get it. Omit it when a person asked for no reply. Null is the same as omitted.") }).strict(),
6745
6842
  outputSchema: juniorToolOutputSchema.extend({ note: z.string().optional() })
6746
6843
  });
6747
6844
  /** Create the tool that ends a Turn with no reply. */
@@ -6754,7 +6851,7 @@ function createNoReplyTool() {
6754
6851
  // src/chat/tools/runtime/reply.ts
6755
6852
  const DESCRIPTIONS$1 = {
6756
6853
  parent: {
6757
- tool: "Send the reply of this Turn to your parent agent when the Turn ends. The parent reads it as your result.",
6854
+ tool: "Send this text to your parent agent when the Turn ends.",
6758
6855
  text: "The finished result for your parent agent, with everything it needs to continue."
6759
6856
  },
6760
6857
  automation: {
@@ -6789,7 +6886,7 @@ function createReplyTool(target) {
6789
6886
  execute: async (input) => {
6790
6887
  if (isLegacyNoReplyMarker(input.text)) throw new ToolInputError(`To post nothing, call \`${NO_REPLY_TOOL_NAME}\` instead.`);
6791
6888
  const text = replyTextSchema.safeParse(input.text);
6792
- if (!text.success) throw new ToolInputError("The reply text must not be empty.");
6889
+ if (!text.success) throw new ToolInputError(`The reply text must not be empty. Set text to the reply, or call \`${NO_REPLY_TOOL_NAME}\` to post nothing.`);
6793
6890
  return { text: text.data };
6794
6891
  }
6795
6892
  });
@@ -6897,7 +6994,7 @@ const listedAgentSchema = z.object({
6897
6994
  last_result: z.enum(CHILD_AGENT_RESULTS).optional().describe("How the latest finished task of the agent ended"),
6898
6995
  task: z.string().optional().describe("Latest task that its parent gave the agent. Not shown for the parent."),
6899
6996
  title: z.string().optional().describe("Short display title of the latest task"),
6900
- dashboard_url: z.string().url().optional().describe("Dashboard link of the conversation"),
6997
+ url: z.string().url().optional().describe("Link to the conversation"),
6901
6998
  archived: z.literal(true).optional().describe("The conversation is archived."),
6902
6999
  error: z.string().optional().describe("Why the agent is blocked, failed, or stopped"),
6903
7000
  updated_at: z.string().describe("Time of the latest change"),
@@ -6918,7 +7015,7 @@ async function parentTodos(parentConversationId, conversationId) {
6918
7015
  return (await listTodos(getSqlExecutor(), parentConversationId)).filter((todo) => isOpenTodoStatus(todo.status)).map((todo) => parentTodo(todo, conversationId));
6919
7016
  }
6920
7017
  function listedChildAgent(relation, agent) {
6921
- const dashboardUrl = getDashboardConversationLink(agent.childConversationId);
7018
+ const url = getDashboardConversationLink(agent.childConversationId);
6922
7019
  return {
6923
7020
  relation,
6924
7021
  conversation_id: agent.childConversationId,
@@ -6928,7 +7025,7 @@ function listedChildAgent(relation, agent) {
6928
7025
  ...agent.lastResult ? { last_result: agent.lastResult } : void 0,
6929
7026
  task: truncate$1(agent.task, TASK_MAX_LENGTH),
6930
7027
  ...agent.title ? { title: agent.title } : void 0,
6931
- ...dashboardUrl ? { dashboard_url: dashboardUrl } : void 0,
7028
+ ...url ? { url } : void 0,
6932
7029
  ...agent.archivedAtMs !== void 0 ? { archived: true } : void 0,
6933
7030
  ...agent.errorMessage ? { error: truncate$1(agent.errorMessage, ERROR_MAX_LENGTH) } : void 0,
6934
7031
  updated_at: new Date(agent.updatedAtMs).toISOString()
@@ -6978,7 +7075,7 @@ function createListAgentsTool(context) {
6978
7075
  // src/chat/tools/runtime/spawn-agent.ts
6979
7076
  const spawnAgentOutputSchema = juniorToolOutputSchema.extend({
6980
7077
  conversation_id: z.string().min(1).describe("Child conversation ID. Pass it to searchConversationEvents to read the child's history."),
6981
- dashboard_url: z.string().url().optional().describe("Dashboard link of the child. People can message a Thread there.")
7078
+ url: z.string().url().optional().describe("Link to the child. People can message a Thread there.")
6982
7079
  });
6983
7080
  const spawnAgentToolDefinition = zodToolDefinition({
6984
7081
  description: [
@@ -6986,7 +7083,7 @@ const spawnAgentToolDefinition = zodToolDefinition({
6986
7083
  "Delegate a Task when: the request splits into independent tracks that each need real investigation, such as several repos, services, sources, or items (start every track in the same message); an answer needs reading across many files, logs, or sources and you need the conclusion, not the raw output; a side task does not block your main answer; or you want a second opinion that is not anchored on your analysis (give it the evidence, not your conclusion).",
6987
7084
  "Do it yourself instead of a Task when: the work fits in a handful of tool calls; you already know the file, symbol, or value to look up; or the job is one modest task that you would only split into pieces. Each child rebuilds its context and its result arrives in a later turn, so when in doubt, do not spawn a Task.",
6988
7085
  `Child agent types:\n${formatAgentTypes()}`,
6989
- "After you delegate, do not do the same work yourself. Make sure people know what is going on, but post only updates that matter to them. Share a Thread's dashboard_url so people can find it.",
7086
+ "After you delegate, do not do the same work yourself. Make sure people know what is going on, but post only updates that matter to them. Share a Thread's url so people can find it.",
6990
7087
  "You know nothing about a child's findings until its result arrives: do not predict them, do not wait or poll, and if the user asks before then, give status.",
6991
7088
  "Give a child a name when you may send it more work later. To give more work to a child agent that already exists, use messageAgent instead.",
6992
7089
  "A child keeps its type and kind when it receives more work through messageAgent.",
@@ -7016,7 +7113,7 @@ function createSpawnAgentTool(spawnAgent, titleCost) {
7016
7113
  return zodTool({
7017
7114
  ...spawnAgentToolDefinition,
7018
7115
  execute: async (input, options) => {
7019
- if (!options.toolCallId) throw new ToolInputError("spawnAgent requires an active tool call ID");
7116
+ if (!options.toolCallId) throw new ToolInputError("spawnAgent requires an active tool call ID. No change to the call can fix this.");
7020
7117
  const title = await resolveTaskTitle({
7021
7118
  completeText,
7022
7119
  cost: titleCost,
@@ -7045,14 +7142,239 @@ function createSpawnAgentTool(spawnAgent, titleCost) {
7045
7142
  if (error instanceof AgentDepthLimitError) throw new ToolInputError(`${error.message}. Do the work in this agent instead.`, { cause: error });
7046
7143
  throw error;
7047
7144
  }
7048
- const dashboardUrl = getDashboardConversationLink(result.childConversationId);
7145
+ const url = getDashboardConversationLink(result.childConversationId);
7049
7146
  return {
7050
7147
  conversation_id: result.childConversationId,
7051
- ...dashboardUrl ? { dashboard_url: dashboardUrl } : void 0
7148
+ ...url ? { url } : void 0
7052
7149
  };
7053
7150
  }
7054
7151
  });
7055
7152
  }
7153
+ // src/chat/agent-invocations/stop.ts
7154
+ /**
7155
+ * Stop one child agent of a parent Conversation and every child agent below
7156
+ * it. The parent gets no result. Each Conversation in the tree stops through
7157
+ * `stopConversationTree`, which keeps their Watches and holds their
7158
+ * automated input.
7159
+ *
7160
+ * Returns undefined when the child does not belong to the parent.
7161
+ */
7162
+ async function stopChildAgent(args) {
7163
+ const wasStopped = await getConversationStoppedAtMs(args.childConversationId) !== void 0;
7164
+ const conversationIds = await lockOwnedChildAgentTree(args);
7165
+ if (!conversationIds) return;
7166
+ await finishStoppedTree(conversationIds, {
7167
+ stoppedAtMs: Date.now(),
7168
+ state: args.state
7169
+ });
7170
+ await dropUnreadLoopReplies([args.parentConversationId, ...conversationIds], conversationIds, args.state);
7171
+ return { stopped: !wasStopped };
7172
+ }
7173
+ /**
7174
+ * Stop the child agents of a Conversation whose run saw its stop. The work
7175
+ * path in `app/conversation-work.ts` calls it after the run, for a root or a
7176
+ * child agent. So this sends no stop request to that Conversation.
7177
+ *
7178
+ * The run can see its stop late. The stop already reached every child agent
7179
+ * that existed then, so this stops only child agents that this Conversation
7180
+ * spawned after its stop, even when they already finished, and everything
7181
+ * below them. A child that a person resumed after the stop keeps running.
7182
+ * When the stop already ended, because a person or the parent gave the
7183
+ * Conversation new input, this does nothing.
7184
+ *
7185
+ * Only a person's stop of this Conversation itself leaves child agents to
7186
+ * stop here: an agent stop, or a stop of a Conversation above it, stops this
7187
+ * Conversation first under its lock, so it cannot spawn more.
7188
+ */
7189
+ async function stopChildAgentsOf(conversationId, state) {
7190
+ const stoppedAtMs = await getConversationStoppedAtMs(conversationId);
7191
+ if (stoppedAtMs === void 0) return;
7192
+ const nowMs = Date.now();
7193
+ const conversationIds = await lockChildAgentTree(conversationId, { createdAfterMs: stoppedAtMs });
7194
+ const stoppedIds = conversationIds.filter((id) => id !== conversationId);
7195
+ await finishStoppedTree(stoppedIds, {
7196
+ nowMs,
7197
+ stoppedAtMs,
7198
+ state
7199
+ });
7200
+ await dropUnreadLoopReplies(conversationIds, stoppedIds, state);
7201
+ await dropOwnUnreadLoopReplies(conversationId, state);
7202
+ }
7203
+ /**
7204
+ * Stop every child agent below a Conversation that a person stops. Call it
7205
+ * through `stopConversation`, which cancels the Conversation's own waiting
7206
+ * parent messages and stops its Turn next.
7207
+ *
7208
+ * The Conversation's run sees its stop only at its next stop signal check.
7209
+ * When it does, `stopChildAgentsOf` stops the child agents that it spawned
7210
+ * after this stop, at the time of this stop. So
7211
+ * input that ends this stop ends theirs too.
7212
+ */
7213
+ async function stopChildAgentsBelow(conversationId, options) {
7214
+ const { nowMs, queue, stoppedAtMs, state } = options;
7215
+ const conversationIds = await lockChildAgentTree(conversationId);
7216
+ const stoppedIds = conversationIds.filter((id) => id !== conversationId);
7217
+ await finishStoppedTree(stoppedIds, {
7218
+ nowMs,
7219
+ queue,
7220
+ stoppedAtMs,
7221
+ state
7222
+ });
7223
+ await dropUnreadLoopReplies(conversationIds, stoppedIds, state);
7224
+ }
7225
+ /**
7226
+ * Drop the unread replies that the stopped Conversations left in each
7227
+ * mailbox of `mailboxIds`, by their sender fields.
7228
+ * A reply sent after the stop is dropped when it is read, while the sender
7229
+ * is stopped. Call this after the stop is stored.
7230
+ *
7231
+ * A reply that a running Turn already took leaves the mailbox like one that
7232
+ * it read: the Turn's own ack removes nothing more.
7233
+ */
7234
+ async function dropUnreadLoopReplies(mailboxIds, stoppedIds, state) {
7235
+ const stopped = new Set(stoppedIds);
7236
+ await mapBounded(mailboxIds, async (conversationId) => {
7237
+ const inboundMessageIds = ((await getConversationWorkState({
7238
+ conversationId,
7239
+ state
7240
+ }))?.messages ?? []).flatMap((message) => {
7241
+ const sender = readInboundMessageSender(message);
7242
+ return sender && !isPersonStopTurnId(sender.turnId) && stopped.has(sender.conversationId) ? [message.inboundMessageId] : [];
7243
+ });
7244
+ if (inboundMessageIds.length > 0) await dropPendingMessages({
7245
+ conversationId,
7246
+ inboundMessageIds,
7247
+ state
7248
+ });
7249
+ });
7250
+ }
7251
+ /**
7252
+ * Drop the unread loop replies that a Conversation that a person stopped
7253
+ * left in its parent's mailbox, outside its tree. Call this after its stop
7254
+ * is stored: the parent mailbox lock then drops a later reply.
7255
+ */
7256
+ async function dropOwnUnreadLoopReplies(conversationId, state) {
7257
+ await dropUnreadLoopReplies((await getSqlExecutor().db().select({ id: juniorConversations.parentConversationId }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId))).flatMap((parent) => parent.id ? [parent.id] : []), [conversationId], state);
7258
+ }
7259
+ /**
7260
+ * Finish the stop of each Conversation in a stopped tree: cancel its waiting
7261
+ * parent messages, then stop it through `stopConversationTree`.
7262
+ */
7263
+ async function finishStoppedTree(conversationIdsToStop, options) {
7264
+ await mapBounded(conversationIdsToStop, (conversationId) => cancelWaitingParentMessages(conversationId, {
7265
+ nowMs: options.stoppedAtMs,
7266
+ state: options.state
7267
+ }));
7268
+ await stopConversationTree(conversationIdsToStop, options);
7269
+ }
7270
+ /**
7271
+ * Cancel the parent messages that wait for a Conversation that stops: end
7272
+ * their markers and drop them. Call it before the stop request is saved, so
7273
+ * none of them runs after the stop and no stop request outlives the stop.
7274
+ */
7275
+ async function cancelWaitingParentMessages(conversationId, options) {
7276
+ await recordChildAgentEnded(conversationId, "aborted", {
7277
+ includeWaiting: true,
7278
+ nowMs: options.nowMs,
7279
+ state: options.state
7280
+ });
7281
+ await dropWaitingParentMessages(conversationId, options.state);
7282
+ }
7283
+ /**
7284
+ * Tell the parent of a child agent that a person stops it, when the stop
7285
+ * cuts work: waiting input or a running Turn, whoever started it. Call it
7286
+ * before the stop request is saved, so a failure leaves the stop to be
7287
+ * retried. An idle child already sent its result, so it stays quiet, and so
7288
+ * does a run that an earlier stop already cut. The result is keyed by the
7289
+ * stop time, which a redelivery of the same stop keeps, so a retry adds
7290
+ * nothing even when a worker took the waiting work in between.
7291
+ */
7292
+ async function reportPersonStopToParent(conversationId, options) {
7293
+ if (!await readAgentConfig(conversationId)) return;
7294
+ const conversation = await getConversationStore().get({ conversationId });
7295
+ if (!conversation || turnBehavior({
7296
+ kind: conversation.kind,
7297
+ personInput: false
7298
+ }).failureNotice !== "parent") return;
7299
+ const work = await getConversationWorkState({
7300
+ conversationId,
7301
+ state: options.state
7302
+ });
7303
+ const runId = work?.execution.runId;
7304
+ if (runId && await hasConversationStop({
7305
+ conversationId,
7306
+ runId,
7307
+ state: options.state
7308
+ })) return;
7309
+ const [firstWaiting] = (work?.messages ?? []).flatMap((message) => {
7310
+ const parentMessage = readParentMessage(message);
7311
+ return parentMessage ? [parentMessage] : [];
7312
+ });
7313
+ const [turn] = runId ? await listActiveMailboxTurns(conversationId) : [];
7314
+ if (!runId && !work?.messages.length) return;
7315
+ await createDeliverToParent(options)({
7316
+ actor: turn?.actor ? parentResultActor(turn.actor, turn.source?.kind) : firstWaiting?.actor ?? EVENT_SYSTEM_ACTOR,
7317
+ conversationId,
7318
+ result: {
7319
+ kind: "stopped",
7320
+ text: `A person stopped this ${conversation.kind}.`
7321
+ },
7322
+ turnId: getPersonStopTurnId(options.stoppedAtMs)
7323
+ });
7324
+ }
7325
+ /**
7326
+ * List one Conversation and every child agent below it, the Conversation
7327
+ * first. It takes the create lock of each Conversation before it reads that
7328
+ * Conversation's children, so no child agent can start in the tree until the
7329
+ * caller's transaction ends. Each child agent stores its agent config.
7330
+ */
7331
+ async function lockAgentConversationTree(conversationId) {
7332
+ const executor = getSqlExecutor();
7333
+ const conversationIds = [conversationId];
7334
+ let parents = conversationIds;
7335
+ while (parents.length > 0) {
7336
+ for (const parent of parents) await executor.withLock(getChildAgentLockName(parent), async () => void 0);
7337
+ parents = (await executor.db().select({ childConversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(inArray(juniorConversations.parentConversationId, parents), isNotNull(juniorConversations.agentConfig)))).map((row) => row.childConversationId).filter((id) => !conversationIds.includes(id));
7338
+ conversationIds.push(...parents);
7339
+ }
7340
+ return conversationIds;
7341
+ }
7342
+ /**
7343
+ * Keep a Conversation, its child agents created after `createdAfterMs`, and
7344
+ * every Conversation below those child agents. A stopped parent gives a
7345
+ * child agent no work, so only a spawn that raced the stop created one after
7346
+ * it.
7347
+ */
7348
+ async function withChildAgentsCreatedAfter(conversationId, conversationIds, createdAfterMs) {
7349
+ const links = await getSqlExecutor().db().select({
7350
+ childConversationId: juniorConversations.conversationId,
7351
+ parentConversationId: juniorConversations.parentConversationId
7352
+ }).from(juniorConversations).where(and(inArray(juniorConversations.parentConversationId, [...conversationIds]), isNotNull(juniorConversations.agentConfig), or(ne(juniorConversations.parentConversationId, conversationId), gt(juniorConversations.createdAt, new Date(createdAfterMs)))));
7353
+ const kept = [conversationId];
7354
+ for (let index = 0; index < kept.length; index += 1) for (const link of links) if (link.parentConversationId === kept[index] && !kept.includes(link.childConversationId)) kept.push(link.childConversationId);
7355
+ return kept;
7356
+ }
7357
+ /**
7358
+ * Lock the tree of one direct child agent of a parent. Returns undefined
7359
+ * when the child does not belong to the parent.
7360
+ */
7361
+ async function lockOwnedChildAgentTree(args) {
7362
+ const [child] = await getSqlExecutor().db().select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(eq(juniorConversations.conversationId, args.childConversationId), eq(juniorConversations.parentConversationId, args.parentConversationId), isNotNull(juniorConversations.agentConfig)));
7363
+ return child ? await lockChildAgentTree(args.childConversationId) : void 0;
7364
+ }
7365
+ /**
7366
+ * List one agent Conversation and every child agent below it, under the
7367
+ * create locks of the tree, so the read sees every spawn that committed
7368
+ * before it. With
7369
+ * `createdAfterMs`, only the direct child agents created after that time,
7370
+ * and the Conversations below them, are listed.
7371
+ */
7372
+ async function lockChildAgentTree(conversationId, options = {}) {
7373
+ return await getSqlExecutor().withLock(getChildAgentLockName(conversationId), async () => {
7374
+ const lockedIds = await lockAgentConversationTree(conversationId);
7375
+ return options.createdAfterMs === void 0 ? lockedIds : await withChildAgentsCreatedAfter(conversationId, lockedIds, options.createdAfterMs);
7376
+ });
7377
+ }
7056
7378
  // src/chat/tools/runtime/stop-agent.ts
7057
7379
  const stopAgentOutputSchema = juniorToolOutputSchema.extend({
7058
7380
  conversation_id: z.string().min(1).describe("Stopped child conversation ID"),
@@ -7088,6 +7410,31 @@ function createStopAgentTool(conversationId) {
7088
7410
  }
7089
7411
  });
7090
7412
  }
7413
+ // src/chat/agent-invocations/bindings.ts
7414
+ function bindingFromRow(row) {
7415
+ return agentBindingSchema.parse({
7416
+ childConversationId: row.childConversationId,
7417
+ name: row.name,
7418
+ parentConversationId: row.parentConversationId
7419
+ });
7420
+ }
7421
+ /** Read one named child binding in its parent-agent scope. */
7422
+ async function getAgentBinding(args) {
7423
+ const rows = await getSqlExecutor().db().select().from(juniorAgentBindings).where(and(eq(juniorAgentBindings.parentConversationId, args.parentConversationId), eq(juniorAgentBindings.name, args.name)));
7424
+ return rows[0] ? bindingFromRow(rows[0]) : void 0;
7425
+ }
7426
+ /**
7427
+ * Find a direct child agent of one parent by name or child Conversation id.
7428
+ * Each child agent stores its agent config.
7429
+ */
7430
+ async function findChildAgentConversationId(args) {
7431
+ const binding = await getAgentBinding({
7432
+ name: args.target,
7433
+ parentConversationId: args.parentConversationId
7434
+ });
7435
+ if (binding) return binding.childConversationId;
7436
+ return (await getSqlExecutor().db().select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(eq(juniorConversations.parentConversationId, args.parentConversationId), eq(juniorConversations.conversationId, args.target), isNotNull(juniorConversations.agentConfig))).limit(1))[0]?.conversationId;
7437
+ }
7091
7438
  // src/chat/tools/runtime/update-todos.ts
7092
7439
  const MAX_TODOS_PER_CALL = 50;
7093
7440
  const statusSchema = z.enum(TODO_STATUSES).describe("in_progress marks work that has started. done and dropped close the To-do.");
@@ -7386,15 +7733,14 @@ const conversationMatchSchema = z.object({
7386
7733
  }).strict()).max(5).optional().describe("Top linked resources, such as pull requests"),
7387
7734
  channel_id: z.string().min(1).optional(),
7388
7735
  channel_name: z.string().min(1).optional(),
7389
- permalink: z.string().url().optional(),
7390
- dashboard_url: z.string().url().optional(),
7736
+ url: z.string().url().optional().describe("Link to the conversation."),
7391
7737
  archived: z.literal(true).optional().describe("The conversation is archived."),
7392
7738
  transcript_purged: z.literal(true).optional().describe("The transcript is purged. Only the title and the summary remain."),
7393
7739
  updated_at: z.string().describe("Time of the latest activity")
7394
7740
  }).strict();
7395
7741
  async function conversationMatch(match, channels) {
7396
7742
  const dashboardUrl = getDashboardConversationLink(match.conversationId);
7397
- const channelFields = channels ? await channels.describeMatch(match) : void 0;
7743
+ const channelFields = channels ? await channels.describeMatch(match, { includeUrl: !dashboardUrl }) : void 0;
7398
7744
  return {
7399
7745
  conversation_id: match.conversationId,
7400
7746
  ...match.kind ? { kind: match.kind } : void 0,
@@ -7405,7 +7751,7 @@ async function conversationMatch(match, channels) {
7405
7751
  ...match.excerpt ? { excerpt: match.excerpt } : void 0,
7406
7752
  ...match.links.length > 0 ? { links: match.links } : void 0,
7407
7753
  ...channelFields,
7408
- ...dashboardUrl ? { dashboard_url: dashboardUrl } : void 0,
7754
+ ...dashboardUrl ? { url: dashboardUrl } : void 0,
7409
7755
  ...match.archived ? { archived: true } : void 0,
7410
7756
  ...match.transcriptPurged ? { transcript_purged: true } : void 0,
7411
7757
  updated_at: new Date(match.updatedAtMs).toISOString()
@@ -7460,7 +7806,7 @@ function createSearchConversationsTool(context) {
7460
7806
  const channelInput = "channel_id" in input && typeof input.channel_id === "string" ? input.channel_id : void 0;
7461
7807
  const channelId = channels && channelInput ? await channels.resolveChannel(channelInput) : void 0;
7462
7808
  const participantUserId = input.participating ? await context.resolveUserId?.() : void 0;
7463
- if (input.participating && !participantUserId) throw new ToolInputError("`participating` needs a person: this Turn has none");
7809
+ if (input.participating && !participantUserId) throw new ToolInputError("`participating` needs a person: this Turn has none. Leave out `participating`.");
7464
7810
  const matches = await searchConversations(getDb(), {
7465
7811
  ...context.embedder ? { embedder: context.embedder } : void 0,
7466
7812
  requesterConversationId: context.conversationId,
@@ -8024,7 +8370,7 @@ function createStopWatchingResourcesTool(context) {
8024
8370
  conversationId: context.conversationId,
8025
8371
  watch: owned
8026
8372
  }) : void 0;
8027
- if (!stopped) throw new ToolInputError("Watch was not found in the current conversation or its child agents.");
8373
+ if (!stopped) throw new ToolInputError("Watch was not found in the current conversation or its child agents. Use listWatches to find its id.");
8028
8374
  if (stopped.status === "completed") throw new ToolInputError("Watch already completed; delivered input cannot be recalled.");
8029
8375
  stoppedIds = [stopped.id];
8030
8376
  } else {
@@ -8180,7 +8526,7 @@ function createUpdateUserCustomizationTool(context) {
8180
8526
  ...updateUserCustomizationToolDefinition,
8181
8527
  async execute(input) {
8182
8528
  const user = (await context.resolveActorIdentity?.())?.user;
8183
- if (!user) throw new ToolInputError("This person has no linked User, so customization cannot be saved.");
8529
+ if (!user) throw new ToolInputError("This person has no linked User, so customization cannot be saved. No change to the call can fix this.");
8184
8530
  if (!await saveUserCustomization(user.id, input.customization)) throw new Error("User customization target user was not found.");
8185
8531
  return { customization: input.customization };
8186
8532
  }
@@ -8223,7 +8569,7 @@ function createUserLookupTool(teamId, providers, egress) {
8223
8569
  query,
8224
8570
  teamId
8225
8571
  });
8226
- if (provider === "slack" && result.count === 0 && looksLikeEmail(query)) throw new ToolInputError(`No Slack user found with email address ${query}.`);
8572
+ if (provider === "slack" && result.count === 0 && looksLikeEmail(query)) throw new ToolInputError(`No Slack user found with email address ${query}. Check the email, or search by name.`);
8227
8573
  return result;
8228
8574
  } catch (error) {
8229
8575
  if (error instanceof SlackActionError) {
@@ -8274,8 +8620,8 @@ function cleanStrings(values) {
8274
8620
  }
8275
8621
  function ttlMs(input) {
8276
8622
  if (input.ttl_ms === void 0) return RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS;
8277
- if (!Number.isFinite(input.ttl_ms) || input.ttl_ms <= 0) throw new ToolInputError("ttl_ms must be a positive finite number");
8278
- if (input.ttl_ms > 2592e6) throw new ToolInputError("Watches cannot exceed 30 days");
8623
+ if (!Number.isFinite(input.ttl_ms) || input.ttl_ms <= 0) throw new ToolInputError("ttl_ms must be a positive number of milliseconds. Leave it out to use the default.");
8624
+ if (input.ttl_ms > 2592e6) throw new ToolInputError(`Watches cannot exceed 30 days. Set ttl_ms to at most ${RESOURCE_SUBSCRIPTION_MAX_TTL_MS}.`);
8279
8625
  return input.ttl_ms;
8280
8626
  }
8281
8627
  /**
@@ -8285,7 +8631,7 @@ function ttlMs(input) {
8285
8631
  * result twice.
8286
8632
  */
8287
8633
  async function requireWatchableConversation(watcherConversationId, conversationId) {
8288
- if (!await canReadConversation(getDb(), watcherConversationId, conversationId)) throw new ToolInputError(`Conversation is not accessible: ${conversationId}`);
8634
+ if (!await canReadConversation(getDb(), watcherConversationId, conversationId)) throw new ToolInputError(`Conversation is not accessible: ${conversationId}. Check identifier, or use searchConversations to find a Conversation that you can read.`);
8289
8635
  const target = await getConversationStore().get({ conversationId });
8290
8636
  if (target && watchRepeatsChildResults(target, watcherConversationId)) throw new ToolInputError(`${conversationId} is a child agent of this Conversation. Its results and messages already arrive here without a Watch.`);
8291
8637
  }
@@ -8312,7 +8658,7 @@ function createWatchEventsTool(context, catalog) {
8312
8658
  if (unavailable) throw new ToolInputError(unavailable);
8313
8659
  const events = cleanStrings(input.events);
8314
8660
  const intent = input.intent.trim();
8315
- if (!intent) throw new ToolInputError("intent is required");
8661
+ if (!intent) throw new ToolInputError("intent is required. Set intent to why this conversation wants these events.");
8316
8662
  const match = requireValidEventTrigger(catalog, {
8317
8663
  events,
8318
8664
  match: input.match ? declaredEventKeys(input.match) : void 0,
@@ -8444,15 +8790,15 @@ async function resolvePublicHostname(hostname) {
8444
8790
  const deduped = /* @__PURE__ */ new Map();
8445
8791
  for (const record of records) {
8446
8792
  const family = record.family === 6 ? 6 : 4;
8447
- if (family === 4 && isPrivateIpv4(record.address)) throw new ToolInputError("Resolved to a private IPv4 address");
8448
- if (family === 6 && isPrivateIpv6(record.address)) throw new ToolInputError("Resolved to a private IPv6 address");
8793
+ if (family === 4 && isPrivateIpv4(record.address)) throw new ToolInputError("Resolved to a private IPv4 address. Use a public URL.");
8794
+ if (family === 6 && isPrivateIpv6(record.address)) throw new ToolInputError("Resolved to a private IPv6 address. Use a public URL.");
8449
8795
  deduped.set(`${family}:${record.address}`, {
8450
8796
  address: record.address,
8451
8797
  family
8452
8798
  });
8453
8799
  }
8454
8800
  const [first, ...rest] = deduped.values();
8455
- if (!first) throw new ToolInputError("Could not resolve hostname");
8801
+ if (!first) throw new ToolInputError("Could not resolve hostname. Check the URL.");
8456
8802
  return [first, ...rest];
8457
8803
  }
8458
8804
  async function resolvePinnedAddresses(url) {
@@ -8542,10 +8888,10 @@ async function assertPublicUrl(rawUrl) {
8542
8888
  const parsed = new URL(rawUrl);
8543
8889
  if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new ToolInputError("Only http(s) URLs are allowed");
8544
8890
  const hostname = normalizeHostname(parsed.hostname);
8545
- if (hostname === "localhost" || hostname === "0.0.0.0" || hostname.endsWith(".local") || hostname.endsWith(".internal")) throw new ToolInputError("Local/private hostnames are blocked");
8891
+ if (hostname === "localhost" || hostname === "0.0.0.0" || hostname.endsWith(".local") || hostname.endsWith(".internal")) throw new ToolInputError("Local/private hostnames are blocked. Use a public URL.");
8546
8892
  const hostIpType = net.isIP(hostname);
8547
- if (hostIpType === 4 && isPrivateIpv4(hostname)) throw new ToolInputError("Private IPv4 addresses are blocked");
8548
- if (hostIpType === 6 && isPrivateIpv6(hostname)) throw new ToolInputError("Private IPv6 addresses are blocked");
8893
+ if (hostIpType === 4 && isPrivateIpv4(hostname)) throw new ToolInputError("Private IPv4 addresses are blocked. Use a public URL.");
8894
+ if (hostIpType === 6 && isPrivateIpv6(hostname)) throw new ToolInputError("Private IPv6 addresses are blocked. Use a public URL.");
8549
8895
  if (hostIpType === 0) await resolvePublicHostname(hostname);
8550
8896
  return parsed;
8551
8897
  }
@@ -8571,9 +8917,9 @@ async function fetchTextWithRedirects(url, redirectsLeft) {
8571
8917
  const response = await fetchWithPinnedLookup(url, await resolvePinnedAddresses(url), abortController.signal).finally(() => clearTimeout(timer));
8572
8918
  if (!(response.status >= 300 && response.status < 400)) return response;
8573
8919
  await response.body?.cancel();
8574
- if (redirectsLeft <= 0) throw new ToolInputError("Too many redirects");
8920
+ if (redirectsLeft <= 0) throw new ToolInputError("Too many redirects. Use another URL.");
8575
8921
  const location = response.headers.get("location");
8576
- if (!location) throw new ToolInputError("Redirect missing location");
8922
+ if (!location) throw new ToolInputError("Redirect missing location. Use another URL.");
8577
8923
  return fetchTextWithRedirects(await assertPublicUrl(new URL(location, url).toString()), redirectsLeft - 1);
8578
8924
  }
8579
8925
  /**
@@ -8700,13 +9046,13 @@ async function extractWebFetchResponse(url, response) {
8700
9046
  if (!response.ok) {
8701
9047
  await response.body?.cancel();
8702
9048
  const message = `fetch failed: ${response.status}`;
8703
- if (response.status >= 400 && response.status < 500) throw new ToolInputError(message);
9049
+ if (response.status >= 400 && response.status < 500) throw new ToolInputError(`${message}. Check the URL, or use another source.`);
8704
9050
  throw new Error(message);
8705
9051
  }
8706
9052
  const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
8707
9053
  if (!contentType.includes("text/") && !contentType.includes("json") && !contentType.includes("xml")) {
8708
9054
  await response.body?.cancel();
8709
- throw new ToolInputError(`unsupported content type: ${contentType || "unknown"}`);
9055
+ throw new ToolInputError(`unsupported content type: ${contentType || "unknown"}. Use a URL that returns text, JSON, XML, or an image.`);
8710
9056
  }
8711
9057
  const { bytes, truncated: sourceTruncated } = await readResponseBytes(response, MAX_FETCH_BYTES);
8712
9058
  const extracted = extractContentDetails(new TextDecoder().decode(bytes), contentType);
@@ -8755,7 +9101,7 @@ function createWebFetchTool(hooks, options = {}) {
8755
9101
  const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
8756
9102
  if (response.ok && contentType.startsWith("image/")) {
8757
9103
  const { bytes, truncated } = await readResponseBytes(response, MAX_FETCH_BYTES);
8758
- if (truncated) throw new ToolInputError("image response body too large");
9104
+ if (truncated) throw new ToolInputError("image response body too large. Use a smaller image or another URL.");
8759
9105
  const files = [{
8760
9106
  data: bytes,
8761
9107
  filename: filenameForUrl(safeUrl, contentType.split(";")[0] ?? "image/png"),
@@ -8986,7 +9332,7 @@ function createDeleteWorkspaceTool() {
8986
9332
  return zodTool({
8987
9333
  ...deleteWorkspaceToolDefinition,
8988
9334
  async execute({ id }) {
8989
- if (!await workspaceWrite(() => deleteWorkspace(id))) throw new ToolInputError(`Workspace not found: ${id}`);
9335
+ if (!await workspaceWrite(() => deleteWorkspace(id))) throw new ToolInputError(`Workspace not found: ${id}. Use listWorkspaces to find its ID.`);
8990
9336
  return { deleted: true };
8991
9337
  }
8992
9338
  });
@@ -9019,6 +9365,164 @@ function createListWorkspacesTool(workspaces) {
9019
9365
  }
9020
9366
  });
9021
9367
  }
9368
+ // src/chat/events/people.ts
9369
+ const linkedSlackIdentity = alias(juniorIdentities, "event_people_slack");
9370
+ function personKey(person) {
9371
+ return "email" in person ? `email:${normalizeIdentityEmail(person.email)}` : `${person.provider}:${person.handle.toLowerCase()}`;
9372
+ }
9373
+ function personCondition(person) {
9374
+ if ("email" in person) return and(eq(juniorIdentities.emailVerified, true), eq(juniorIdentities.emailNormalized, normalizeIdentityEmail(person.email)));
9375
+ return and(eq(juniorIdentities.provider, person.provider), sql`lower(${juniorIdentities.handle}) = lower(${person.handle})`);
9376
+ }
9377
+ /**
9378
+ * Read the Slack users in one workspace whose linked User has an identity that
9379
+ * matches `condition`, by person key. A key with more than one Slack user is
9380
+ * ambiguous, so callers must not mention it.
9381
+ */
9382
+ async function readLinkedSlackUsers(condition, slackTeamId) {
9383
+ const rows = await getSqlExecutor().db().select({
9384
+ emailNormalized: juniorIdentities.emailNormalized,
9385
+ emailVerified: juniorIdentities.emailVerified,
9386
+ handle: juniorIdentities.handle,
9387
+ provider: juniorIdentities.provider,
9388
+ slackUserId: linkedSlackIdentity.providerSubjectId
9389
+ }).from(juniorIdentities).innerJoin(linkedSlackIdentity, and(eq(linkedSlackIdentity.userId, juniorIdentities.userId), eq(linkedSlackIdentity.kind, "user"), eq(linkedSlackIdentity.provider, "slack"), eq(linkedSlackIdentity.providerTenantId, slackTeamId))).where(and(eq(juniorIdentities.kind, "user"), condition));
9390
+ const slackUsersByKey = /* @__PURE__ */ new Map();
9391
+ const add = (key, slackUserId) => {
9392
+ const users = slackUsersByKey.get(key) ?? /* @__PURE__ */ new Set();
9393
+ users.add(slackUserId);
9394
+ slackUsersByKey.set(key, users);
9395
+ };
9396
+ for (const row of rows) {
9397
+ if (row.handle) add(`${row.provider}:${row.handle.toLowerCase()}`, row.slackUserId);
9398
+ if (row.emailVerified && row.emailNormalized) add(`email:${row.emailNormalized}`, row.slackUserId);
9399
+ }
9400
+ return slackUsersByKey;
9401
+ }
9402
+ function soleMention(users) {
9403
+ return users?.size === 1 ? slackMention([...users][0]) : void 0;
9404
+ }
9405
+ const HANDLE_MENTION_PATTERN = /(?<![\w.@/-])@([A-Za-z0-9][A-Za-z0-9_.-]*[A-Za-z0-9]|[A-Za-z0-9])/g;
9406
+ const MAX_REPLY_HANDLES = 50;
9407
+ /**
9408
+ * Resolve the `@handle` words in reply text to Slack mentions of known people
9409
+ * in one Slack workspace, by `provider:handle` key in lowercase. A handle
9410
+ * resolves only when exactly one linked Slack user has it for that provider.
9411
+ * Plugins pick the provider when they format the reply.
9412
+ */
9413
+ async function resolveHandleMentions(text, slackTeamId) {
9414
+ const handles = [...new Set([...text.matchAll(HANDLE_MENTION_PATTERN)].map((match) => match[1].toLowerCase()))].slice(0, MAX_REPLY_HANDLES);
9415
+ if (handles.length === 0) return /* @__PURE__ */ new Map();
9416
+ const slackUsersByKey = await readLinkedSlackUsers(inArray(sql`lower(${juniorIdentities.handle})`, handles), slackTeamId);
9417
+ const mentions = /* @__PURE__ */ new Map();
9418
+ for (const [key, users] of slackUsersByKey) {
9419
+ const mention = soleMention(users);
9420
+ if (mention && !key.startsWith("email:")) mentions.set(key, mention);
9421
+ }
9422
+ return mentions;
9423
+ }
9424
+ /**
9425
+ * Resolve the Event people to Slack mentions through linked user identities
9426
+ * in one Slack workspace, with one query. Returns them in input order, with
9427
+ * no duplicates.
9428
+ *
9429
+ * A person resolves only when exactly one linked Slack user in that workspace
9430
+ * matches. Core drops unlinked and ambiguous people, so a provider value never
9431
+ * guesses a mention. The Event author is not resolved here: a handle can be
9432
+ * renamed or reused, so only the trust decision names the author.
9433
+ */
9434
+ async function resolveEventMentions(people, slackTeamId) {
9435
+ if (people.length === 0) return [];
9436
+ const slackUsersByKey = await readLinkedSlackUsers(or(...people.map(personCondition)), slackTeamId);
9437
+ const mentions = [];
9438
+ for (const person of people) {
9439
+ const mention = soleMention(slackUsersByKey.get(personKey(person)));
9440
+ if (mention && !mentions.includes(mention)) mentions.push(mention);
9441
+ }
9442
+ return mentions;
9443
+ }
9444
+ // src/chat/events/ingest.ts
9445
+ /** Match a normalized event and enqueue notifications into conversations. */
9446
+ async function ingestEvent(input, options) {
9447
+ const event = eventSchema.parse(input);
9448
+ const nowMs = options.nowMs ?? Date.now();
9449
+ const subscriptions = await findMatchingWatches({
9450
+ data: event.data,
9451
+ eventType: event.eventType,
9452
+ nowMs,
9453
+ namespace: event.namespace,
9454
+ identifier: event.identifier,
9455
+ state: options.state
9456
+ });
9457
+ if (subscriptions.length === 0) return { enqueued: 0 };
9458
+ const author = await resolveEventAuthor(event);
9459
+ if (author.status === "untrusted") logInfo("event.author.untrusted", {
9460
+ "app.event.event_type": event.eventType,
9461
+ "app.event.namespace": event.namespace,
9462
+ "app.event.author.reason": author.reason
9463
+ });
9464
+ let people = [];
9465
+ if (options.slackTeamId && event.people?.length) try {
9466
+ people = await resolveEventMentions(event.people, options.slackTeamId);
9467
+ } catch (error) {
9468
+ logException(error, "event.people.resolve.failed", {
9469
+ "app.event.event_type": event.eventType,
9470
+ "app.event.namespace": event.namespace
9471
+ });
9472
+ }
9473
+ const doneBy = author.status === "trusted" && author.actor ? {
9474
+ mention: slackMention(author.actor.userId),
9475
+ handle: author.handle
9476
+ } : void 0;
9477
+ const turnConversations = /* @__PURE__ */ new Set();
9478
+ const ordered = [...subscriptions].sort((left, right) => Number(isQuietEvent(left, event.eventType)) - Number(isQuietEvent(right, event.eventType)));
9479
+ let enqueued = 0;
9480
+ const errors = [];
9481
+ const waitDeadlineMs = Date.now() + 1e4;
9482
+ for (const subscription of ordered) {
9483
+ let quiet = false;
9484
+ try {
9485
+ if (await deliverWatch({
9486
+ data: event.data,
9487
+ eventType: event.eventType,
9488
+ namespace: event.namespace,
9489
+ identifier: event.identifier,
9490
+ terminal: event.terminal,
9491
+ nowMs,
9492
+ state: options.state,
9493
+ subscription,
9494
+ waitDeadlineMs,
9495
+ deliver: async (current) => {
9496
+ if (options.admit && !await options.admit(current)) return false;
9497
+ if (isQuietEvent(current, event.eventType)) {
9498
+ quiet = true;
9499
+ if (!turnConversations.has(current.conversationId)) await addQuietEventNote({
9500
+ event,
9501
+ subscription: current
9502
+ });
9503
+ return true;
9504
+ }
9505
+ const result = await enqueueEventNotification({
9506
+ author,
9507
+ doneBy,
9508
+ event,
9509
+ people,
9510
+ queue: options.queue,
9511
+ state: options.state,
9512
+ subscription: current
9513
+ });
9514
+ if (result.status === "held") return false;
9515
+ turnConversations.add(current.conversationId);
9516
+ return result.status === "appended";
9517
+ }
9518
+ }) && !quiet) enqueued += 1;
9519
+ } catch (error) {
9520
+ errors.push(error);
9521
+ }
9522
+ }
9523
+ if (errors.length > 0) throw new AggregateError(errors, "Failed to deliver one or more watches");
9524
+ return { enqueued };
9525
+ }
9022
9526
  // src/chat/sandbox/prepare-workspace.ts
9023
9527
  const WORKSPACE_SETUP_FAILURE_OUTPUT_MAX_CHARS = 7e3;
9024
9528
  const WORKSPACE_SETUP_FAILURE_TRUNCATION_MARKER = "[earlier setup output truncated]\n";
@@ -9486,9 +9990,7 @@ const SNAPSHOT_BUILD_SYSTEM_ACTOR = {
9486
9990
  /** Leave time to send the next job before this request ends. */
9487
9991
  const JOB_STOP_BUFFER_MS = 4e4;
9488
9992
  async function publishFinishedEvent(input) {
9489
- const event = workspaceSnapshotFinishedEvent(input);
9490
- const queue = getVercelConversationWorkQueue();
9491
- await ingestEvent(event, { queue });
9993
+ await ingestEvent(workspaceSnapshotFinishedEvent(input), { queue: getVercelConversationWorkQueue() });
9492
9994
  }
9493
9995
  function createSnapshotBuildHelpers() {
9494
9996
  const credentials = credentialContextForActor(SNAPSHOT_BUILD_SYSTEM_ACTOR);
@@ -9667,7 +10169,7 @@ function createSwitchWorkspaceTool(context) {
9667
10169
  ...switchWorkspaceToolDefinition,
9668
10170
  async execute({ name }, options) {
9669
10171
  const workspace = await getWorkspaceByName(getDb(), name);
9670
- if (!workspace) throw new ToolInputError(`Workspace not found: ${name}`);
10172
+ if (!workspace) throw new ToolInputError(`Workspace not found: ${name}. Use listWorkspaces to find its name.`);
9671
10173
  const watch = workspaceSnapshotWatch({
9672
10174
  workspaceId: workspace.id,
9673
10175
  workspaceName: workspace.name
@@ -9754,7 +10256,7 @@ function createUpdateWorkspaceTool(providers) {
9754
10256
  ...updateWorkspaceToolDefinition(providers),
9755
10257
  async execute({ id, ...input }) {
9756
10258
  const workspace = await workspaceWrite(() => updateWorkspace(id, workspaceWriteInput(input)));
9757
- if (!workspace) throw new ToolInputError(`Workspace not found: ${id}`);
10259
+ if (!workspace) throw new ToolInputError(`Workspace not found: ${id}. Use listWorkspaces to find its ID.`);
9758
10260
  return { workspace: workspaceView(workspace) };
9759
10261
  }
9760
10262
  });
@@ -9991,7 +10493,7 @@ function staticToolDefinitions(key) {
9991
10493
  const core = {};
9992
10494
  for (const [name, entry] of coreToolEntries(scope)) {
9993
10495
  if (isRunBuilt(entry) || entry.when && !entry.when(scope)) continue;
9994
- core[name] = modelFacing(entry.definition(scope));
10496
+ core[name] = listedToolExposure(scope.listedTools, name, modelFacing(entry.definition(scope)));
9995
10497
  }
9996
10498
  return scope.listedTools.only ? core : {
9997
10499
  ...core,
@@ -11651,7 +12153,7 @@ function askedInboxItem(messages, final) {
11651
12153
  */
11652
12154
  async function readPendingWork(conversationId, messages, final, idleNeedsPendingWork) {
11653
12155
  const [watches, children] = await Promise.all([listWatches({ conversationId }), listChildAgents(conversationId)]);
11654
- if (children.some((child) => NON_TERMINAL_AGENT_INVOCATION_STATUSES.includes(child.status))) return {
12156
+ if (children.some((child) => child.status === "running")) return {
11655
12157
  watches,
11656
12158
  waitingOn: "child"
11657
12159
  };
@@ -12254,4 +12756,4 @@ async function runCacheWarmup(message) {
12254
12756
  }, startedAtMs, warm);
12255
12757
  }, attributes);
12256
12758
  }
12257
- export { createSpawnAgentTool as $, createSearchInboxItemsTool as $n, validateAndApplyTextEdits as $t, createWorkspaceTool as A, deleteViewerTask as An, gapSegment as Ar, parseSlackMessageReference as At, createStopWatchingResourcesTool as B, readViewerAutomations as Bn, readSlackRawMessageContext as Bt, createSwitchWorkspaceTool as C, requireToolCaller as Cn, warmupTiming as Cr, setConversationSubscription as Ct, prepareWorkspaceSnapshot as D, automationEditor as Dn, MIN_WARMUP_PREFIX_TOKENS as Dr, createSlackThreadReadTool as Dt, requireReadyWorkspaceSnapshot as E, activateViewerAutomationVersion as En, MINUTE_MS as Er, throwApiError as Et, createWatchEventsTool as F, readConversationSourceTask as Fn, createSlackListAddItemsTool as Ft, bm25Saturation as G, automationCardStatus as Gn, createSlackCanvasWriteTool as Gt, createSearchConversationEventsTool as H, editEventAutomation as Hn, createSlackChannelJoinTool as Ht, createUserLookupTool as I, readViewerAutomationExecutions as In, createSlackConversationMessageSearchTool as It, createReadFileTool as J, findAutomationSkill as Jn, SLACK_TOOL_SOURCE as Jt, createSearchConversationsTool as K, AutomationEditError as Kn, createSlackCanvasReadTool as Kt, createUpdateUserCustomizationTool as L, readViewerAutomationRuns as Ln, createSlackConversationSearchChannelPort as Lt, createWebSearchTool as M, takeViewerAutomationAlertStep as Mn, createSlackListUpdateItemTool as Mt, createWebFetchTool as N, updateViewerAutomation as Nn, createSlackListGetItemsTool as Nt, createListWorkspacesTool as O, changeAutomationLifecycle as On, NO_REPLY_GAP_MS as Or, renderAttachmentText as Ot, createWatchTimerTool as P, ViewerTaskNotFoundError as Pn, createSlackListCreateTool as Pt, createStopAgentTool as Q, resolveTaskOutcomes as Qn, stripBom as Qt, createSubmitFeedbackTool as R, readViewerAutomationSummary as Rn, createSlackChannelListMessagesTool as Rt, createUpdateWorkspaceTool as S, requireToolAutomation as Sn, sendWarmup as Sr, inviteToConversation as St, processWorkspaceSnapshotJob as T, requireToolDestination as Tn, IDLE_HORIZON_MS as Tr, jsonResponse as Tt, bm25InverseDocumentFrequency as U, changedEventMatch as Un, resolveSlackChannelRef as Ut, createSearchEventTypesTool as V, editScheduledAutomation as Vn, resolveSlackChannelIdFromMessage as Vt, bm25NormalizedFrequency as W, requireEventAutomationTrigger as Wn, slackChannelRefParam as Wt, createBashTool as X, effectiveTaskOutcomes as Xn, detectLineEnding as Xt, createEditFileTool as Y, missingAutomationSkillReason as Yn, buildCompactDiff as Yt, createUpdateTodosTool as Z, moveTaskOutcomes as Zn, restoreLineEndings as Zt, CONTEXT_COMPACTION_PROMPT_NAME as _, newAutomationTask as _n, cacheTtlMs as _r, createReadConversationEventTool as _t, recordModelCall as a, createCanvas as an, idlePeriodOutcome as ar, createMessageAgentTool as at, coreToolSlots as b, automationToolContext as bn, connectedState as br, listOwnedWatches as bt, warmup_exports as c, createDeleteAutomationTool as cn, recordWarmupCost as cr, archiveConversation as ct, compactWithPreparedSummary as d, automationSkillToolSchema as dn, incrementStat as dr, reportConversationRead as dt, isMissingPathError as en, SAVINGS_NAMESPACE as er, createListAgentsTool as et, lastRequestInputSize as f, automationToolResult as fn, readStats as fr, createAddInboxItemTool as ft, measureTurnCompactionWait as g, editedAutomationTask as gn, breakerStates as gr, renderInboxItemMessage as gt, createNextInputTracker as h, automationTriggerSchema as hn, breakerOpen as hr, inboxItemChangeRecord as ht, GLOBAL_GAPS_TTL_MS as i, createOperationKey as in, historyPeriodSavings as ir, createNoReplyTool as it, workspaceProviderNames as j, readViewerAutomationEdit as jn, createTracedStreamFn as jr, createSlackPublicSearchTool as jt, createDeleteWorkspaceTool as k, changeViewerAutomationLifecycle as kn, decideWarmup as kr, renderBlockText as kt, isConversationWorkDone as l, AUTOMATIONS_TOOL_SOURCE as ln, replaceHistorySavings as lr, conversationReadPositionQuery as lt, requestBackgroundCompaction as m, automationTriggerChangesSchema as mn, KEY_PREFIX as mr, deliverInboxItemChange as mt, CONVERSATION_STATE_TTL_MS as n, positiveInteger as nn, addHistoryWarmupCost as nr, createReportBlockedTool as nt, segmentGapsKey as o, createSearchAutomationsTool as on, idlePeriodSavings as or, createArchiveAgentTool as ot, processBackgroundCompaction as p, automationToolResultSchema as pn, CACHE_RETENTION as pr, createUpdateInboxItemTool as pt, createWriteFileTool as q, requireAutomationSkill as qn, createSlackCanvasEditTool as qt, GLOBAL_GAPS_MAX as r, resolveWorkspacePath as rn, firstLiveSavingsDate as rr, createReplyTool as rt, stopIdleWarmups as s, createRunAutomationNowTool as sn, recordIdlePeriodSavings as sr, readLastUserMessageAtByConversation as st, ANSWER_TOOL_ENDINGS as t, normalizeToLf as tn, addHistoryPeriod as tr, createReportProgressTool as tt, listConversationWork as u, automationIdForToolCall as un, savingsTotals as ur, markConversationRead as ut, buildAgentModelRequest as v, triggerKind as vn, cachedPrefixTokens as vr, createRunOperatorSqlTool as vt, ensureWorkspaceSnapshotBuild as w, requireToolCreator as wn, warmupTooLate as wr, emptyResponse as wt, enabledMode as x, automationToolsDisabledReason as xn, providerCacheTtlMs as xr, createSetConversationSubscriptionTool as xt, requestContextSummary as y, getConversationAccess as yn, closeBreaker as yr, createListWatchesTool as yt, createSystemTimeTool as z, readViewerAutomationVersions as zn, parseSlackThreadId as zt };
12759
+ export { createUpdateTodosTool as $, readConversationSourceTask as $n, createSlackConversationMessageSearchTool as $t, createListWorkspacesTool as A, automationToolResultSchema as An, addStats as Ar, renderInboxItemMessage as At, createSubmitFeedbackTool as B, requireToolCaller as Bn, connectedState as Br, setConversationSubscription as Bt, createSwitchWorkspaceTool as C, createSearchAutomationsTool as Cn, historyPeriodSavings as Cr, conversationReadPositionQuery as Ct, prepareWorkspaceSnapshot as D, automationIdForToolCall as Dn, recordWarmupCost as Dr, createUpdateInboxItemTool as Dt, requireReadyWorkspaceSnapshot as E, AUTOMATIONS_TOOL_SOURCE as En, recordIdlePeriodSavings as Er, createAddInboxItemTool as Et, createWebFetchTool as F, triggerKind as Fn, breakerOpen as Fr, effectiveToolExposure as Ft, bm25InverseDocumentFrequency as G, changeAutomationLifecycle as Gn, IDLE_HORIZON_MS as Gr, renderAttachmentText as Gt, createStopWatchingResourcesTool as H, requireToolDestination as Hn, sendWarmup as Hr, jsonResponse as Ht, createWatchTimerTool as I, getConversationAccess as In, breakerStates as Ir, listedToolExposure as It, createSearchConversationsTool as J, readViewerAutomationEdit as Jn, NO_REPLY_GAP_MS as Jr, createSlackPublicSearchTool as Jt, bm25NormalizedFrequency as K, changeViewerAutomationLifecycle as Kn, MINUTE_MS as Kr, renderBlockText as Kt, createWatchEventsTool as L, automationToolContext as Ln, cacheTtlMs as Lr, planToolExposure as Lt, createWorkspaceTool as M, automationTriggerSchema as Mn, readStats as Mr, createRunOperatorSqlTool as Mt, workspaceProviderNames as N, editedAutomationTask as Nn, CACHE_RETENTION as Nr, createListWatchesTool as Nt, ingestEvent as O, automationSkillToolSchema as On, replaceHistorySavings as Or, deliverInboxItemChange as Ot, createWebSearchTool as P, newAutomationTask as Pn, KEY_PREFIX as Pr, listOwnedWatches as Pt, createBashTool as Q, collectionRowTitle as Qn, createSlackListAddItemsTool as Qt, createUserLookupTool as R, automationToolsDisabledReason as Rn, cachedPrefixTokens as Rr, createSetConversationSubscriptionTool as Rt, createUpdateWorkspaceTool as S, createCanvas as Sn, firstLiveSavingsDate as Sr, archiveConversation as St, processWorkspaceSnapshotJob as T, createDeleteAutomationTool as Tn, idlePeriodSavings as Tr, reportConversationRead as Tt, createSearchEventTypesTool as U, activateViewerAutomationVersion as Un, warmupTiming as Ur, throwApiError as Ut, createSystemTimeTool as V, requireToolCreator as Vn, providerCacheTtlMs as Vr, emptyResponse as Vt, createSearchConversationEventsTool as W, automationEditor as Wn, warmupTooLate as Wr, createSlackThreadReadTool as Wt, createReadFileTool as X, updateViewerAutomation as Xn, gapSegment as Xr, createSlackListGetItemsTool as Xt, createWriteFileTool as Y, takeViewerAutomationAlertStep as Yn, decideWarmup as Yr, createSlackListUpdateItemTool as Yt, createEditFileTool as Z, ViewerTaskNotFoundError as Zn, createTracedStreamFn as Zr, createSlackListCreateTool as Zt, CONTEXT_COMPACTION_PROMPT_NAME as _, isMissingPathError as _n, viewerAutomationCollection as _r, AgentMessageTargetError as _t, recordModelCall as a, createSlackChannelJoinTool as an, editScheduledAutomation as ar, reportPersonStopToParent as at, coreToolSlots as b, resolveWorkspacePath as bn, addHistoryPeriod as br, createArchiveAgentTool as bt, warmup_exports as c, createSlackCanvasWriteTool as cn, requireEventAutomationTrigger as cr, createSpawnAgentTool as ct, compactWithPreparedSummary as d, SLACK_TOOL_SOURCE as dn, requireAutomationSkill as dr, createReportBlockedTool as dt, createSlackConversationSearchChannelPort as en, readViewerAutomationExecutions as er, findChildAgentConversationId as et, lastRequestInputSize as f, buildCompactDiff as fn, findAutomationSkill as fr, createReplyTool as ft, measureTurnCompactionWait as g, validateAndApplyTextEdits as gn, resolveTaskOutcomes as gr, AgentInvocationLimitError as gt, createNextInputTracker as h, stripBom as hn, moveTaskOutcomes as hr, AgentDepthLimitError as ht, GLOBAL_GAPS_TTL_MS as i, resolveSlackChannelIdFromMessage as in, readViewerAutomations as ir, dropOwnUnreadLoopReplies as it, createDeleteWorkspaceTool as j, automationTriggerChangesSchema as jn, incrementStat as jr, createReadConversationEventTool as jt, resolveHandleMentions as k, automationToolResult as kn, savingsTotals as kr, inboxItemChangeRecord as kt, isConversationWorkDone as l, createSlackCanvasReadTool as ln, automationCardStatus as lr, createListAgentsTool as lt, requestBackgroundCompaction as m, restoreLineEndings as mn, effectiveTaskOutcomes as mr, createMessageAgentTool as mt, CONVERSATION_STATE_TTL_MS as n, parseSlackThreadId as nn, readViewerAutomationSummary as nr, createStopAgentTool as nt, segmentGapsKey as o, resolveSlackChannelRef as on, editEventAutomation as or, stopChildAgentsBelow as ot, processBackgroundCompaction as p, detectLineEnding as pn, missingAutomationSkillReason as pr, createNoReplyTool as pt, bm25Saturation as q, deleteViewerTask as qn, MIN_WARMUP_PREFIX_TOKENS as qr, parseSlackMessageReference as qt, GLOBAL_GAPS_MAX as r, readSlackRawMessageContext as rn, readViewerAutomationVersions as rr, cancelWaitingParentMessages as rt, stopIdleWarmups as s, slackChannelRefParam as sn, changedEventMatch as sr, stopChildAgentsOf as st, ANSWER_TOOL_ENDINGS as t, createSlackChannelListMessagesTool as tn, readViewerAutomationRuns as tr, getAgentBinding as tt, listConversationWork as u, createSlackCanvasEditTool as un, AutomationEditError as ur, createReportProgressTool as ut, buildAgentModelRequest as v, normalizeToLf as vn, createSearchInboxItemsTool as vr, AgentNameInUseError as vt, ensureWorkspaceSnapshotBuild as w, createRunAutomationNowTool as wn, idlePeriodOutcome as wr, markConversationRead as wt, enabledMode as x, createOperationKey as xn, addHistoryWarmupCost as xr, readLastUserMessageAtByConversation as xt, requestContextSummary as y, positiveInteger as yn, SAVINGS_NAMESPACE as yr, AgentStoppedError as yt, createUpdateUserCustomizationTool as z, requireToolAutomation as zn, closeBreaker as zr, inviteToConversation as zt };