@sentry/junior 0.291.0 → 0.293.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 (67) hide show
  1. package/dist/{adapter-zphAlWE2.js → adapter-CMJfmHso.js} +1 -1
  2. package/dist/{admin-B3WR7Y6e.js → admin-uuecrKuD.js} +2 -2
  3. package/dist/{agent-runner-ke-hOiuv.js → agent-runner-DHq1pjUg.js} +283 -155
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +3 -3
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +43 -38
  8. package/dist/{app-C47PT68y.d.ts → app-fWzCHFIb.d.ts} +2 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +422 -394
  11. package/dist/{assistant-reply-BV8SZaVd.js → assistant-reply-CIApSfor.js} +1 -1
  12. package/dist/{automation-CrsYnvdV.js → automation-BE3z19VN.js} +71 -22
  13. package/dist/{background-compaction-queue-QDH_JS3D.js → background-compaction-queue-D7ncdEa6.js} +4 -4
  14. package/dist/{briefs-Bdv9BG5J.js → briefs-NpgMEFh1.js} +2 -2
  15. package/dist/{catalog-runtime-yGnL9ywD.js → catalog-runtime-DwbTyNRD.js} +1 -1
  16. package/dist/cli/chat.js +15 -15
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +4 -4
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +4 -3
  23. package/dist/{config-UsaBOQgC.js → config-B4b-NXH5.js} +2 -2
  24. package/dist/{connections-CePSRCoR.js → connections-Dz_AQg5p.js} +6 -6
  25. package/dist/{conversation-pending-messages-Cd7ShwBs.js → conversation-pending-messages-1Kad1Mif.js} +4 -1
  26. package/dist/{conversation-privacy-B3wmawmz.js → conversation-privacy-DRsSgLGO.js} +1 -1
  27. package/dist/{credential-sync-LNRLXZCn.js → credential-sync-ClCnnGVj.js} +13 -13
  28. package/dist/{db-7glZCI18.d.ts → db-BbpttyKH.d.ts} +1 -1
  29. package/dist/{db-c__lw9GH.js → db-CoA7_Xqu.js} +3 -3
  30. package/dist/{executor-N8-D5Gvv.js → executor-SWyHhit0.js} +51 -15
  31. package/dist/instrumentation.js +2 -2
  32. package/dist/{logging-DbXHuhac.js → logging-BN5drSEZ.js} +1 -1
  33. package/dist/{message-D1MEh8iR.js → message-D4qjpW1C.js} +9 -9
  34. package/dist/nitro.d.ts +1 -1
  35. package/dist/nitro.js +2 -2
  36. package/dist/{oauth-callback-server-DUtqhYwP.js → oauth-callback-server-Xi-mTLOV.js} +2 -2
  37. package/dist/{projection-D7XadqRY.js → projection-DXl4ftyL.js} +140 -50
  38. package/dist/{prompt-CzEV4BF4.js → prompt-Dmx6IfWZ.js} +3 -3
  39. package/dist/{registry-CTtGtXZP.js → registry-DosVt9f9.js} +1 -1
  40. package/dist/{resolve-nUuQ8yyH.js → resolve-BDjWJC9s.js} +3 -3
  41. package/dist/{result-Cr9tUdfS.js → result-CaAFpf4B.js} +8 -8
  42. package/dist/{runner-D7NMbBim.js → runner-h96Mkss6.js} +7 -7
  43. package/dist/{sandbox-egress-signals-BJAyfzOD.js → sandbox-egress-signals-rK91BW7i.js} +1 -1
  44. package/dist/{schema-CC2RxDAV.d.ts → schema-CHsBmXIj.d.ts} +246 -45
  45. package/dist/{schema-CVV5r-qP.js → schema-C_v8wb80.js} +2 -2
  46. package/dist/{service-account-_ml5D4Tk.js → service-account-BpGpScaT.js} +3 -3
  47. package/dist/{service-account-CP1oBWTc.js → service-account-WUMVuqVL.js} +3 -3
  48. package/dist/{session-stop-BbsyIbK2.js → session-stop-xYK15HUu.js} +20 -41
  49. package/dist/{skills-CayJ8-Bj.js → skills-DHApyCjj.js} +10 -9
  50. package/dist/{spawn-CktAopv_.js → spawn-BQQrwGNe.js} +5 -5
  51. package/dist/{stop-BUzUJuN_.js → stop-CBeD6_Gs.js} +34 -28
  52. package/dist/{store-lotbeXq3.js → store-xtibD98L.js} +3 -3
  53. package/dist/{task-runner-BinM1l5g.js → task-runner-BYPN4BEO.js} +65 -90
  54. package/dist/{turn-failure-response-DH5nE6HJ.js → turn-failure-response-jNVl00MD.js} +7 -7
  55. package/dist/{validation-I0CqX5NC.js → validation-DGeB_moV.js} +1 -1
  56. package/dist/{version-C3sVz3bv.js → version-C6nqU3Qc.js} +1 -1
  57. package/dist/version.js +1 -1
  58. package/dist/{viewer-so1MPU10.js → viewer-9KLQibjn.js} +3 -3
  59. package/dist/{warmup-BH9HRBCI.js → warmup-7S6z068f.js} +56 -24
  60. package/dist/{work-Cw6Fzvfz.js → work-xwX6unUE.js} +11 -11
  61. package/dist/{worker-qEykG39-.js → worker-CiCCfwd4.js} +6 -6
  62. package/migrations/0095_web_linked_slack_identity_repair.sql +252 -0
  63. package/migrations/0096_automation_task_kind.sql +75 -0
  64. package/migrations/meta/0095_snapshot.json +4452 -0
  65. package/migrations/meta/0096_snapshot.json +4490 -0
  66. package/migrations/meta/_journal.json +14 -0
  67. package/package.json +5 -5
@@ -1,33 +1,33 @@
1
1
  import { g as withActiveSpan, h as startSpan, i as getActiveSpan, m as startInactiveSpan, r as continueTrace, v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { $ as loadTurnCheckpoint, $a as readConversationAccessFromSql, $t as extractAssistantText, A as latestConversationMessageSeq, Aa as SANDBOX_RUNTIME, Ar as resolveAssignee, B as getAgentContextInputLimitTokens, Ba as SANDBOX_SKILLS_ROOT, Bi as slackMention, Ca as consumeSandboxEgressPermissionDeniedSignal, Ci as setWorkspaceSnapshotBuild, Co as saveObjectAnnotations, Da as buildSandboxEgressNetworkPolicy, Di as ensureDockerDaemon, Dn as findLegacyWebActorUserId, Do as defaultTimezone, Dr as EVERYONE_ASSIGNEE, Ei as isStale, En as createUserTokenStore, Fo as piMessageFromHistoryItem, Fr as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, G as AuthPausePersistenceError, Ga as buildCommandScript, Gi as openSlackDirectMessage, Gr as getWatch, Gt as TurnBudgetExceededError, H as PluginCredentialFailureError, Ha as sandboxSkillDir, Hi as addReactionToMessage, Hr as createWatch, I as upsertConversationMessage, Ii as escapeSlackMrkdwnText, Io as projectConversationEvents, Ir as RESOURCE_WATCH_TOOL_SOURCE, J as abandonReplacedPendingAuth, Ji as postSlackMessage, K as AuthorizationFlowDisabledError, Ka as buildNonInteractiveShellScript, Kr as listWatches, Kt as TurnSliceLimitExceededError, L as calculateContextCompactionTargetTokens, La as SANDBOX_COMMAND_PATH, Ln as getPluginTools, Lo as getConfigDefaults, Lr as STOP_WATCHING_TOOL_NAME, M as normalizeConversationText, Ma as tryWorkspaceRepoCheckoutPath, Mi as formatProviderLabel, Mn as createPluginHookRunner, Mr as resolveChannelCapabilities, N as recordDeliveredAssistantMessage, Na as workspaceRepoCheckoutPath, Nr as getSlackToolContext, Oa as resolveSandboxCommandEnvironment, Oi as getSandboxProvider, Oo as resolveUserTimezone, Or as activeParticipantUserIds, Pa as PluginToolDeniedError, Pi as resolveBaseUrl, Po as historyItemFromPiMessage, Pr as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, Q as continuableMessages, Qi as uploadFilesToConversation, Qt as persistWithRetry, R as getAgentBackgroundCompactionMarkTokens, Ra as SANDBOX_DATA_ROOT, Ri as normalizeSlackReplyMarkdown, Sa as consumeSandboxEgressAuthRequiredSignal, Si as setWorkspaceSnapshot, Sr as requireReviewItemLinks, T as resolveTaskTitle, Ti as hash, U as createPluginAuthOrchestration, Ua as sandboxSkillFile, Ui as deleteSlackMessage, Ur as deliverWatch, V as createPluginEgress, Va as SANDBOX_WORKSPACE_ROOT, Vr as createTimerWatch, W as authorizationId, Wa as sandboxSkillPathResolution, Wi as getSlackMessagePermalink, Wr as findMatchingWatches, Wt as TURN_LIMIT_WRAP_UP_MESSAGE, X as clearPendingAuth, Xa as canAccessConversation, Xt as isTurnExecutionLimitExceededError, Y as canReusePendingAuthLink, Yt as createTurnLimitGate, Zi as updateSlackMessage, Zt as CODEMODE_TOOL_NAME, _a as WorkspaceSnapshotNotReadyError, _n as TURN_CONTEXT_TAG, _r as canReadReviewItem, a as loadProjection, aa as getSlackClient, ar as getOpenReviewItemByDedupeKey, at as failTurnRecord, b as persistConversationMessages, ba as workspaceSnapshotNotReadyUserMessage, bi as invalidateReadySnapshot, bn as readParentAgentTask, br as readReviewItemAgentScope, c as recordAgentsInstructionsUpdated, ca as normalizeSlackConversationId, cn as isStandaloneRuntimeContextMessage, di as renderToolResultNudge, dn as normalizeToolNameFromResult, dr as searchReviewItems, ei as verifyTimerWatchCredentialSubject, en as getPiMessageRole, f as recordAuthorizationRequested, fi as createWorkspace, fn as retainRuntimeTurnContext, g as recordToolExecutionStarted, ga as wrapSandboxSetupError, gi as listWorkspaces, gr as canAgentChangeReviewItem, ha as throwSandboxOperationError, hi as getWorkspaceByName, hn as REQUEST_CONTEXT_SECTION_TAG, i as loadConversationProjection, ii as getDashboardReviewItemLink, in as hasTurnInput, ir as dismissOpenReviewItems, j as markConversationMessage, ja as sleep, ji as deliverOAuthAuthorization, jr as resolveAssignees, kn as getOAuthAccountProviders, kr as automationCreatorUserId, l as recordAttachmentsDelivered, la as runWithSlackInstallationToken, li as ToolInputError, ln as isToolResultError, m as recordMcpProviderConnected, ma as isAlreadyExistsError, mi as getWorkspace, mn as trimTrailingAssistantMessages, mr as PLUGIN_REVIEW_ITEM_KEY_PREFIX, na as downloadPrivateSlackFile, ni as getDashboardConversationLink, nn as getUserMessageInstructionText, nr as closeReviewItem, nt as saveTurnCheckpoint, oa as isConversationScopedChannel, oi as getDashboardTaskLink, on as isAssistantMessage, or as getReviewItem, ot as getTurnRecord, p as recordGuardianActionReviewed, pa as isAbortError, pi as deleteWorkspace, pn as stripRuntimeTurnContext, pr as updateReviewItemContent, q as AuthorizationPauseError, qa as runNonInteractiveCommand, qt as TurnToolCallLimitExceededError, r as loadConnectedMcpProviders, ra as getFilePermalink, rt as abandonTurnRecord, sn as isContinuablePiBoundary, sr as insertReviewItem, t as commitAcceptedReply, ta as SlackActionError, tn as getTerminalAssistantMessages, ua as withSlackRetries, un as isToolResultMessage, v as hydrateConversationMessages, va as getWorkspaceSnapshotNotReadyError, vi as updateWorkspace, vo as matchSlackAttachments, w as fallbackShortTitle, wa as createSandboxEgressCredentialToken, wi as create, wo as createPluginAnnotations, xa as clearSandboxEgressSignals, xi as loadSnapshotsForProfile, xr as requireReviewItemAssignees, ya as isWorkspaceSnapshotNotReadyError, yi as WorkspaceValidationError, z as getAgentContextCompactionTriggerTokens, za as SANDBOX_REPOS_ROOT, zn as getPlugins, zr as cancelWatch } from "./projection-D7XadqRY.js";
3
- import { A as estimateTextTokens, B as createProviderError, D as requestPrefixAttributes, E as resolveGatewayModel, G as getGatewayApiKey, H as getProviderErrorAttributes, I as unwrapCurrentInstruction, K as resolveGatewayCredential, L as escapeXml, M as COMPACTION_SUMMARY_PREFIX, N as hasCompactedConversationContext, O as estimateMessagesTokens, P as isCompactionSummaryText, V as findProviderError, W as isProviderRetryError, _ as toPiReasoningLevel, b as GEN_AI_SERVER_ADDRESS, g as TURN_REASONING_LEVELS, j as textCharsForTokens, k as estimateRequestOverheadTokens, n as botConfig, v as normalizeSlackEmojiName, y as GEN_AI_PROVIDER_NAME, z as ProviderError } from "./config-UsaBOQgC.js";
4
- import { C as summarizeMessageText, E as withSpan, G as isRecord$4, S as setTags, T as withLogContext, V as runWithLogAttributes, W as normalizeIdentityEmail, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, d as logAudit, f as logError, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, l as getLogContextAttributesForSpan, m as logInfo, o as getActiveTraceContext, p as logException, q as toOptionalString, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging-DbXHuhac.js";
5
- import { a as toCanonicalInputMessage, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-B3wmawmz.js";
2
+ import { $ as loadTurnCheckpoint, $i as postSlackMessage, $t as createTurnLimitGate, A as latestConversationMessageSeq, Ai as hash, An as createUserTokenStore, B as getAgentContextInputLimitTokens, Bo as piMessageFromHistoryItem, Br as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, Ca as getWorkspaceSnapshotNotReadyError, Ci as updateWorkspace, Co as matchSlackAttachments, Da as consumeSandboxEgressAuthRequiredSignal, Di as setWorkspaceSnapshot, Dr as requireReviewItemLinks, Ea as clearSandboxEgressSignals, Ei as loadSnapshotsForProfile, Er as requireReviewItemAssignees, Fa as SANDBOX_RUNTIME, Fr as resolveAssignee, G as AuthPausePersistenceError, Ga as SANDBOX_SKILLS_ROOT, Gi as slackMention, Gt as isPersonInput, H as PluginCredentialFailureError, Ha as SANDBOX_COMMAND_PATH, Hn as getPluginTools, Ho as getConfigDefaults, Hr as STOP_WATCHING_TOOL_NAME, I as upsertConversationMessage, Ia as sleep, Ii as deliverOAuthAuthorization, Ir as resolveAssignees, J as abandonReplacedPendingAuth, Ja as sandboxSkillFile, Ji as deleteSlackMessage, Jr as deliverWatch, Jt as TURN_LIMIT_WRAP_UP_MESSAGE, K as AuthorizationFlowDisabledError, Ka as SANDBOX_WORKSPACE_ROOT, Kr as createTimerWatch, L as calculateContextCompactionTargetTokens, La as tryWorkspaceRepoCheckoutPath, Li as formatProviderLabel, Ln as createPluginHookRunner, Lr as resolveChannelCapabilities, M as normalizeConversationText, Ma as buildSandboxEgressNetworkPolicy, Mi as ensureDockerDaemon, Mo as defaultTimezone, Mr as EVERYONE_ASSIGNEE, N as recordDeliveredAssistantMessage, Na as resolveSandboxCommandEnvironment, Ni as getSandboxProvider, Nn as getOAuthAccountProviders, No as resolveUserTimezone, Nr as activeParticipantUserIds, Oa as consumeSandboxEgressPermissionDeniedSignal, Oi as setWorkspaceSnapshotBuild, Oo as saveObjectAnnotations, Pr as automationCreatorUserId, Q as continuableMessages, Qa as runNonInteractiveCommand, R as getAgentBackgroundCompactionMarkTokens, Ra as workspaceRepoCheckoutPath, Rr as getSlackToolContext, Sa as WorkspaceSnapshotNotReadyError, Sr as canReadReviewItem, T as resolveTaskTitle, Ta as workspaceSnapshotNotReadyUserMessage, Ti as invalidateReadySnapshot, Tr as readReviewItemAgentScope, U as createPluginAuthOrchestration, Ua as SANDBOX_DATA_ROOT, Ui as normalizeSlackReplyMarkdown, V as createPluginEgress, Vi as escapeSlackMrkdwnText, Vo as projectConversationEvents, Vr as RESOURCE_WATCH_TOOL_SOURCE, W as authorizationId, Wa as SANDBOX_REPOS_ROOT, Wn as getPlugins, Wr as cancelWatch, X as clearPendingAuth, Xa as buildCommandScript, Xi as openSlackDirectMessage, Xr as getWatch, Xt as TurnSliceLimitExceededError, Y as canReusePendingAuthLink, Ya as sandboxSkillPathResolution, Yi as getSlackMessagePermalink, Yr as findMatchingWatches, Yt as TurnBudgetExceededError, Za as buildNonInteractiveShellScript, Zr as listWatches, Zt as TurnToolCallLimitExceededError, _i as createWorkspace, _n as stripRuntimeTurnContext, a as loadProjection, ai as verifyTimerWatchCredentialSubject, an as getTerminalAssistantMessages, at as failTurnRecord, b as persistConversationMessages, ba as throwSandboxOperationError, bi as getWorkspaceByName, c as recordAgentsInstructionsUpdated, ca as getFilePermalink, cn as hasTurnInput, da as isConversationScopedChannel, di as getDashboardTaskLink, dn as isContinuablePiBoundary, dr as getReviewItem, en as isTurnExecutionLimitExceededError, f as recordAuthorizationRequested, fn as isStandaloneRuntimeContextMessage, fr as insertReviewItem, g as recordToolExecutionStarted, gi as renderToolResultNudge, gn as retainRuntimeTurnContext, gr as searchReviewItems, ha as withSlackRetries, hn as normalizeToolNameFromResult, i as loadConversationProjection, in as getPiMessageRole, io as readConversationAccessFromSql, j as markConversationMessage, ji as isStale, jn as findLegacyWebActorUserId, ka as createSandboxEgressCredentialToken, ki as create, ko as createPluginAnnotations, l as recordAttachmentsDelivered, li as getDashboardReviewItemLink, lr as dismissOpenReviewItems, m as recordMcpProviderConnected, ma as runWithSlackInstallationToken, mi as ToolInputError, mn as isToolResultMessage, na as updateSlackMessage, nn as persistWithRetry, nt as saveTurnCheckpoint, oa as SlackActionError, on as getUserMessageInstructionText, ot as getTurnRecord, p as recordGuardianActionReviewed, pa as normalizeSlackConversationId, pn as isToolResultError, q as AuthorizationPauseError, qa as sandboxSkillDir, qi as addReactionToMessage, qr as createWatch, qt as turnBehavior, r as loadConnectedMcpProviders, ra as uploadFilesToConversation, rn as extractAssistantText, rt as abandonTurnRecord, sa as downloadPrivateSlackFile, si as getDashboardConversationLink, sr as closeReviewItem, t as commitAcceptedReply, tn as CODEMODE_TOOL_NAME, to as canAccessConversation, ua as getSlackClient, un as isAssistantMessage, ur as getOpenReviewItemByDedupeKey, v as hydrateConversationMessages, va as isAbortError, vi as deleteWorkspace, vn as trimTrailingAssistantMessages, vr as updateReviewItemContent, w as fallbackShortTitle, wa as isWorkspaceSnapshotNotReadyError, wi as WorkspaceValidationError, wn as readParentAgentTask, xa as wrapSandboxSetupError, xi as listWorkspaces, xn as TURN_CONTEXT_TAG, xr as canAgentChangeReviewItem, ya as isAlreadyExistsError, yi as getWorkspace, yn as REQUEST_CONTEXT_SECTION_TAG, yr as PLUGIN_REVIEW_ITEM_KEY_PREFIX, z as getAgentContextCompactionTriggerTokens, za as PluginToolDeniedError, zi as resolveBaseUrl, zo as historyItemFromPiMessage, zr as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS } from "./projection-DXl4ftyL.js";
3
+ import { A as estimateTextTokens, B as createProviderError, D as requestPrefixAttributes, E as resolveGatewayModel, G as getGatewayApiKey, H as getProviderErrorAttributes, I as unwrapCurrentInstruction, K as resolveGatewayCredential, L as escapeXml, M as COMPACTION_SUMMARY_PREFIX, N as hasCompactedConversationContext, O as estimateMessagesTokens, P as isCompactionSummaryText, V as findProviderError, W as isProviderRetryError, _ as toPiReasoningLevel, b as GEN_AI_SERVER_ADDRESS, g as TURN_REASONING_LEVELS, j as textCharsForTokens, k as estimateRequestOverheadTokens, n as botConfig, v as normalizeSlackEmojiName, y as GEN_AI_PROVIDER_NAME, z as ProviderError } from "./config-B4b-NXH5.js";
4
+ import { C as summarizeMessageText, E as withSpan, G as isRecord$4, S as setTags, T as withLogContext, V as runWithLogAttributes, W as normalizeIdentityEmail, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, d as logAudit, f as logError, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, l as getLogContextAttributesForSpan, m as logInfo, o as getActiveTraceContext, p as logException, q as toOptionalString, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging-BN5drSEZ.js";
5
+ import { a as toCanonicalInputMessage, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-DRsSgLGO.js";
6
6
  import { d as parseSlackChannelReferenceId, f as parseSlackTeamId, h as parseSlackMessageTs, n as createSlackActor, o as isUserActor, p as parseSlackUserId, u as parseSlackChannelId } from "./actor-6jsm_v96.js";
7
- import { $ as sameDestination, B as addAgentTurnUsage, D as resolveActorIdentityId, G as resolveRootConversationId$1, J as nextDetailVersion, T as SYSTEM_IDENTITY_ID, V as agentTurnCostUsd, W as hasAgentTurnUsage, Y as touchConversationDetail, Z as parseDestination, _ as setArchivedAt, a as getConversationStore, c as conversationIdsWithAnnotation, g as readConversationTrees, h as conversationDescendants, i as getConversationMessageSearchStore, l as hasAnnotationKey, m as conversationAncestors, o as getDb, q as conversationDetailTouch, r as getConversationEventStore, s as getSqlExecutor, u as treeHasAnnotationKey, x as conversationKindFromRow } from "./db-c__lw9GH.js";
8
- import { A as juniorConversations, M as juniorUsers, N as juniorDestinations, P as juniorArtifacts, _ as juniorConversationReadPositions, b as juniorConversationBriefs, c as juniorReviewItemSlackCards, f as juniorAutomations, g as juniorAgentInvocations, h as juniorAgentBindings, j as juniorIdentities, k as juniorAttachments, p as juniorStats, u as juniorAutomationRuns, v as juniorConversationParticipants, w as juniorConversationEvents } from "./executor-N8-D5Gvv.js";
7
+ import { $ as sameDestination, B as addAgentTurnUsage, D as resolveActorIdentityId, G as resolveRootConversationId$1, J as nextDetailVersion, T as SYSTEM_IDENTITY_ID, V as agentTurnCostUsd, W as hasAgentTurnUsage, Y as touchConversationDetail, Z as parseDestination, _ as setArchivedAt, a as getConversationStore, c as conversationIdsWithAnnotation, g as readConversationTrees, h as conversationDescendants, i as getConversationMessageSearchStore, l as hasAnnotationKey, m as conversationAncestors, o as getDb, q as conversationDetailTouch, r as getConversationEventStore, s as getSqlExecutor, u as treeHasAnnotationKey, x as conversationKindFromRow } from "./db-CoA7_Xqu.js";
8
+ import { A as juniorConversations, M as juniorUsers, N as juniorDestinations, P as juniorArtifacts, _ as juniorConversationReadPositions, b as juniorConversationBriefs, c as juniorReviewItemSlackCards, f as juniorAutomations, g as juniorAgentInvocations, h as juniorAgentBindings, j as juniorIdentities, k as juniorAttachments, p as juniorStats, u as juniorAutomationRuns, v as juniorConversationParticipants, w as juniorConversationEvents } from "./executor-SWyHhit0.js";
9
9
  import { _ as instructionProvenanceFor, a as KNOWN_CONVERSATION_EVENT_TYPES, g as instructionActors, h as contextProvenance, r as detectImageMediaType, v as sameActorIdentity } from "./media-BepyEUNm.js";
10
10
  import { a as listReferenceFiles } from "./package-discovery-DJhGdS4c.js";
11
- import { c as fetchWithBoundedOAuthErrorBodies, d as actorLogContext, f as credentialContextForActor, g as credentialUserSubjectId, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, s as OAuthProviderError } from "./registry-CTtGtXZP.js";
12
- import { n as pluginCatalogRuntime } from "./catalog-runtime-yGnL9ywD.js";
13
- import { a as parseSkillInvocation, i as parseSkillFile, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-CayJ8-Bj.js";
14
- import { l as completeObject, o as isEventConversationMessage, r as EVENT_AUTHOR_ID, u as completeText } from "./prompt-CzEV4BF4.js";
11
+ import { c as fetchWithBoundedOAuthErrorBodies, d as actorLogContext, f as credentialContextForActor, g as credentialUserSubjectId, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, s as OAuthProviderError } from "./registry-DosVt9f9.js";
12
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-DwbTyNRD.js";
13
+ import { a as parseSkillInvocation, i as parseSkillFile, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-DHApyCjj.js";
14
+ import { l as completeObject, o as isEventConversationMessage, r as EVENT_AUTHOR_ID, u as completeText } from "./prompt-Dmx6IfWZ.js";
15
15
  import { a as withLock, i as fenceLock } from "./locks-D-0h111u.js";
16
- import { a as readActorIdentityFromSql, f as identityAvatarUrl, h as readUserAvatarUrls, i as readActorIdentity } from "./viewer-so1MPU10.js";
17
- import { r as getStateAdapter } from "./adapter-zphAlWE2.js";
16
+ import { a as readActorIdentityFromSql, f as identityAvatarUrl, h as readUserAvatarUrls, i as readActorIdentity } from "./viewer-9KLQibjn.js";
17
+ import { r as getStateAdapter } from "./adapter-CMJfmHso.js";
18
18
  import { i as getFirstRunAtMs, o as getZonedDateTimeParts, s as isValidTimeZone } from "./schedule-cP0AACm1.js";
19
19
  import { K as briefLinkSchema, W as readMessageAttachments, Z as parseStoredBrief, q as briefOutcomeStatusSchema, z as removedCardSchema } from "./conversation-CtjR1Zcx.js";
20
- import { i as createCacheWarmingRecorder, l as readLastUserMessageAtByConversation } from "./warmup-BH9HRBCI.js";
21
- import { D as QUEUE_SIGNATURE_MAX_AGE_MS, g as getVercelConversationWorkQueue, k as getTurnRequestDeadline, m as sendWorkspaceSnapshotJob, n as backgroundCompactionId, p as sendNextWorkspaceSnapshotJob } from "./background-compaction-queue-QDH_JS3D.js";
22
- import { B as AGENT_TYPES, C as isTerminalAgentInvocation, F as CHILD_AGENT_RESULTS, I as PARENT_AGENT_TARGET, J as getAgentInvocationMessageId, P as CHILD_AGENT_KINDS, R as agentNameSchema, S as invocationFromRow, T as listOpenAgentInvocations, U as formatAgentTypes, Z as getChildAgentLockName, at as getConversationTurnBoundaryError, dt as markTurnFailed, et as parseAgentInvocationResultMessageId, f as ConversationTurnLifecycleService, ft as startActiveTurn, g as NON_TERMINAL_AGENT_INVOCATION_STATUSES, i as completeAuthPauseTurn, l as buildDeliveredTurnStatePatch, lt as markTurnClosed, m as loadPendingMessageCards, mt as buildDeterministicTurnId, nt as CooperativeTurnYieldError, o as getTurnUserMessage, q as getAgentInvocationIdForResult, rt as TurnInputCommitLostError, st as isTurnInputCommitLostError, t as finalizeFailedTurnReplyWithEvent, u as buildTurnThreadContext, w as listAgentInvocationsForConversation, x as getLatestAgentInvocationForConversation } from "./turn-failure-response-DH5nE6HJ.js";
23
- import { a as isLegacyNoReplyMarker, i as NO_REPLY_TOOL_NAME, n as getAssistantReplyText, o as readNoReply, r as sanitizeAssistantText, t as decideReply } from "./assistant-reply-BV8SZaVd.js";
24
- import { $ as withoutSavedSteeringMessages, A as requireSlackChannelMessageScope, B as maybePostAutomatedTurnLimitNotice, C as enqueueEventNotification, D as timerWatchCredentialSubject, E as renderEventBatchInputs, F as WORKSPACE_SNAPSHOT_FAILED_EVENT, H as resolveSlackReplyTarget, I as WORKSPACE_SNAPSHOT_READY_EVENT, J as assemblePrompt, K as recordFinishedTurnForAutomatedLimit, L as workspaceSnapshotFinishedEvent, O as getEventCatalog, P as slackChannelMessageTrigger, Q as loadPromptTurnContext, R as workspaceSnapshotWatch, S as EVENT_WAIT_MS, T as isEventMailboxMetadata, X as buildSteeringPiMessage, Y as buildPromptInput, Z as instructionForInputs, _ as sourceFromTurnInput, at as addConversationNote, b as conversationSubtree, c as loadReviewItemInput, ct as readBlockedReport, d as getAuthPausedConversationTurnId, f as getEventBatchDelayMs, ht as remindMissingAutomationResult, lt as FINISH_AUTOMATION_RUN_TOOL_NAME, mt as readAutomationResult, ot as JUNIOR_PERSONALITY, p as listActiveMailboxTurns, r as markConversationsStopped, rt as isExperimentalFeatureEnabled, s as eventReviewItemInputs, st as REPORT_BLOCKED_TOOL_NAME, t as getConversationStoppedAtMs, tt as saveUserCustomization, ut as automationResultSchema$1, v as turnInputFactsFromConversationMessage, w as eventBatchMessageMeta, x as conversationSubtreeColumns, y as legacyWebMailboxMetadataSchema } from "./session-stop-BbsyIbK2.js";
20
+ import { i as createCacheWarmingRecorder, l as readLastUserMessageAtByConversation } from "./warmup-7S6z068f.js";
21
+ import { D as QUEUE_SIGNATURE_MAX_AGE_MS, g as getVercelConversationWorkQueue, k as getTurnRequestDeadline, m as sendWorkspaceSnapshotJob, n as backgroundCompactionId, p as sendNextWorkspaceSnapshotJob } from "./background-compaction-queue-D7ncdEa6.js";
22
+ import { B as AGENT_TYPES, C as isTerminalAgentInvocation, F as CHILD_AGENT_RESULTS, I as PARENT_AGENT_TARGET, J as getAgentInvocationMessageId, P as CHILD_AGENT_KINDS, R as agentNameSchema, S as invocationFromRow, T as listOpenAgentInvocations, U as formatAgentTypes, Z as getChildAgentLockName, at as getConversationTurnBoundaryError, dt as markTurnFailed, et as parseAgentInvocationResultMessageId, f as ConversationTurnLifecycleService, ft as startActiveTurn, g as NON_TERMINAL_AGENT_INVOCATION_STATUSES, i as completeAuthPauseTurn, l as buildDeliveredTurnStatePatch, lt as markTurnClosed, m as loadPendingMessageCards, mt as buildDeterministicTurnId, nt as CooperativeTurnYieldError, o as getTurnUserMessage, q as getAgentInvocationIdForResult, rt as TurnInputCommitLostError, st as isTurnInputCommitLostError, t as finalizeFailedTurnReplyWithEvent, u as buildTurnThreadContext, w as listAgentInvocationsForConversation, x as getLatestAgentInvocationForConversation } from "./turn-failure-response-jNVl00MD.js";
23
+ import { a as isLegacyNoReplyMarker, i as NO_REPLY_TOOL_NAME, n as getAssistantReplyText, o as readNoReply, r as sanitizeAssistantText, t as decideReply } from "./assistant-reply-CIApSfor.js";
24
+ import { $ as withoutSavedSteeringMessages, A as requireSlackChannelMessageScope, B as maybePostAutomatedTurnLimitNotice, C as enqueueEventNotification, D as timerWatchCredentialSubject, E as renderEventBatchInputs, F as WORKSPACE_SNAPSHOT_FAILED_EVENT, H as resolveSlackReplyTarget, I as WORKSPACE_SNAPSHOT_READY_EVENT, J as assemblePrompt, K as recordFinishedTurnForAutomatedLimit, L as workspaceSnapshotFinishedEvent, O as getEventCatalog, P as slackChannelMessageTrigger, Q as loadPromptTurnContext, R as workspaceSnapshotWatch, S as EVENT_WAIT_MS, T as isEventMailboxMetadata, X as buildSteeringPiMessage, Y as buildPromptInput, Z as instructionForInputs, _ as sourceFromTurnInput, at as addConversationNote, b as conversationSubtree, c as loadReviewItemInput, ct as readBlockedReport, d as getAuthPausedConversationTurnId, f as getEventBatchDelayMs, ft as readAutomationResult, lt as FINISH_AUTOMATION_RUN_TOOL_NAME, ot as JUNIOR_PERSONALITY, p as listActiveMailboxTurns, pt as remindMissingAutomationResult, r as markConversationsStopped, rt as isExperimentalFeatureEnabled, s as eventReviewItemInputs, st as REPORT_BLOCKED_TOOL_NAME, t as getConversationStoppedAtMs, tt as saveUserCustomization, ut as automationResultSchema$1, v as turnInputFactsFromConversationMessage, w as eventBatchMessageMeta, x as conversationSubtreeColumns, y as legacyWebMailboxMetadataSchema } from "./session-stop-xYK15HUu.js";
25
25
  import { D as userCustomizationTextSchema, T as USER_CUSTOMIZATION_MAX_CHARS, _ as buttonUserInputField, b as normalizeUserInputAnswer, g as USER_INPUT_NOTE, h as USER_INPUT_LIMITS, m as apiErrorSchema, p as webMessageId, s as sumUtcHoursIntoSixHours, v as formatUserInputAnswer, w as AGENT_INVOCATION_STATUSES, x as userInputRequestSchema } from "./reporting-window-B3Ze-Qnt.js";
26
- import { a as setSnapshotSpanAttributes, i as postinstall, n as resolve$1, r as dependencies, s as getSandboxResources } from "./resolve-nUuQ8yyH.js";
27
- import { S as requestConversationWork, T as stopConversationWork, g as getConversationWorkState, m as ensureConversationWake, n as appendAndEnqueueExclusiveInboundMessage, r as appendAndEnqueueInboundMessage } from "./store-lotbeXq3.js";
28
- import { $ as readAutomationExecutionByConversationId, At as registeredResourceTypeSchema, B as setEventAutomationStatus, C as deleteScheduledAutomation, D as saveScheduledAutomation, Dt as registeredEventMatchSchema, E as readScheduledAutomation, Et as hasEventCatalogEntries, G as listAutomationVersions, I as getEventAutomation, K as readAutomationVersion, L as listDeletedEventAutomationsCreatedBy, Mt as requireValidEventTrigger, N as createEventAutomation, Ot as registeredEventTriggerProblems, P as deleteEventAutomation, R as parseEventAutomationRow, S as createScheduledAutomation, T as parseScheduledAutomationRow, Tt as eventWatchUnavailable, U as automationDefinition, X as requireAutomationRevision, Y as automationRevision, Z as emptyAutomationRunWindows, _t as persistThreadStateById, at as readAutomationExecutions, bt as automationEventCatalog, d as getDispatchRecord, dt as resolveConversationRouting, et as readAutomationExecutionDays, ft as resolveTurnSessionRouting, ht as getPersistedThreadState, it as readAutomationExecutionSummaries, jt as requireEventIdentifier, kt as registeredEventTypeSchema, l as getDispatchIdForConversation, mt as getPersistedSandboxState, n as scheduleSessionCompletedPluginTasks, nt as readAutomationExecutionStatusDays, ot as readAutomationRuns, q as sameDefinitionValue, rt as readAutomationExecutionStatusHours, t as processPluginTask, tt as readAutomationExecutionHours, u as getDispatchInputMessageId, vt as coerceThreadConversationState, wt as eventNamespaceSchema, xt as describeRegisteredEventTrigger, z as saveEventAutomation } from "./task-runner-BinM1l5g.js";
29
- import { _ as getMcpProviderErrorAttributes, a as serviceAccountOnly, c as createMcpServiceAccountClientProvider, d as PluginMcpClient, f as McpProviderError, g as getMcpAwareTelemetryMessage, h as getMcpAwareErrorType, i as serviceAccountAllows, l as getMcpServiceAccountCredentials, m as McpToolError, p as McpServiceAccountRequiredError, u as McpAuthorizationRequiredError, v as toMcpProviderError } from "./service-account-_ml5D4Tk.js";
30
- import { A as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, D as taskOutcomeInputSchema, E as automationTitleSchema, F as scheduleIntentFromTool, I as toolScheduleIntentSchema, L as weekdaySchema, N as ScheduleIntentError, P as compileScheduleIntent, T as automationInstructionToolSchema, k as eventAutomationTriggerSchema, l as automationListQuerySchema } from "./automation-CrsYnvdV.js";
26
+ import { a as setSnapshotSpanAttributes, i as postinstall, n as resolve$1, r as dependencies, s as getSandboxResources } from "./resolve-BDjWJC9s.js";
27
+ import { S as requestConversationWork, T as stopConversationWork, g as getConversationWorkState, m as ensureConversationWake, n as appendAndEnqueueExclusiveInboundMessage, r as appendAndEnqueueInboundMessage } from "./store-xtibD98L.js";
28
+ import { $ as readAutomationExecutionByConversationId, At as requireValidEventTrigger, B as setEventAutomationStatus, C as deleteScheduledAutomation, Ct as eventWatchUnavailable, D as saveScheduledAutomation, Dt as registeredEventTypeSchema, E as readScheduledAutomation, Et as registeredEventTriggerProblems, G as listAutomationVersions, I as getEventAutomation, K as readAutomationVersion, L as listDeletedEventAutomationsCreatedBy, N as createEventAutomation, Ot as registeredResourceTypeSchema, P as deleteEventAutomation, R as parseEventAutomationRow, S as createScheduledAutomation, St as eventNamespaceSchema, T as parseScheduledAutomationRow, Tt as registeredEventMatchSchema, U as automationDefinition, X as requireAutomationRevision, Y as automationRevision, Z as emptyAutomationRunWindows, d as getDispatchRecord, et as readAutomationExecutionStatusDays, ft as getPersistedSandboxState, gt as coerceThreadConversationState, ht as persistThreadStateById, it as readAutomationRuns, kt as requireEventIdentifier, l as getDispatchIdForConversation, lt as resolveConversationRouting, n as scheduleSessionCompletedPluginTasks, nt as readAutomationExecutionSummaries, pt as getPersistedThreadState, q as sameDefinitionValue, rt as readAutomationExecutions, t as processPluginTask, tt as readAutomationExecutionStatusHours, u as getDispatchInputMessageId, ut as resolveTurnSessionRouting, vt as automationEventCatalog, wt as hasEventCatalogEntries, yt as describeRegisteredEventTrigger, z as saveEventAutomation } from "./task-runner-BYPN4BEO.js";
29
+ import { _ as getMcpProviderErrorAttributes, a as serviceAccountOnly, c as createMcpServiceAccountClientProvider, d as PluginMcpClient, f as McpProviderError, g as getMcpAwareTelemetryMessage, h as getMcpAwareErrorType, i as serviceAccountAllows, l as getMcpServiceAccountCredentials, m as McpToolError, p as McpServiceAccountRequiredError, u as McpAuthorizationRequiredError, v as toMcpProviderError } from "./service-account-BpGpScaT.js";
30
+ import { A as eventAutomationTriggerSchema, D as automationTitleSchema, E as automationInstructionToolSchema, F as compileScheduleIntent, H as automationTaskSchema, I as scheduleIntentFromTool, L as toolScheduleIntentSchema, O as taskOutcomeInputSchema, P as ScheduleIntentError, R as weekdaySchema, T as automationContextToolSchema, U as automationTaskText, V as automationTaskDescription, j as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, l as automationListQuerySchema, z as automationSkillNameSchema } from "./automation-BE3z19VN.js";
31
31
  import { n as privateTraceResultAttributes } from "./private-trace-result-CE7_lEdq.js";
32
32
  import { streamSimple } from "@earendil-works/pi-ai/compat";
33
33
  import { createGatewayProvider } from "@ai-sdk/gateway";
@@ -37,7 +37,7 @@ import { isDeepStrictEqual } from "node:util";
37
37
  import { AsyncLocalStorage } from "node:async_hooks";
38
38
  import { createHash, randomBytes, randomInt, randomUUID } from "node:crypto";
39
39
  import * as z from "zod";
40
- import { and, asc, count, desc, eq, exists, gt, gte, ilike, inArray, isNotNull, isNull, lt, lte, max, ne, notExists, notInArray, or, sql } from "drizzle-orm";
40
+ import { and, asc, count, desc, eq, gt, gte, ilike, inArray, isNotNull, isNull, lt, lte, max, ne, notExists, notInArray, or, sql } from "drizzle-orm";
41
41
  import { PluginToolInputError, agentEventKeys, agentEventMatchKey, agentEventMatchSchema, createWebSource, declaredEventKeys, eventMatchFieldSchema, eventSchema, eventTriggerText, localDestinationSchema, missingToolAnnotationKeys, ownedObjectAnnotationSchema, sourceSchema, stableEventMatchKey, watchResultSchema } from "@sentry/junior-plugin-api";
42
42
  import { alias } from "drizzle-orm/pg-core";
43
43
  import { Agent, estimateContextTokens } from "@earendil-works/pi-agent-core";
@@ -1370,6 +1370,19 @@ async function loadRunSkill(args) {
1370
1370
  if (loadedSkill) upsertActiveSkill(args.activeSkills, loadedSkill);
1371
1371
  return loadedSkill;
1372
1372
  }
1373
+ // src/chat/automations/skill.ts
1374
+ /**
1375
+ * Skills that an Automation can run. Any discovered skill can run, also a
1376
+ * skill with `disable-model-invocation`, because the Automation names it.
1377
+ */
1378
+ /** Find an installed skill by name. */
1379
+ async function findAutomationSkill(name) {
1380
+ return (await discoverSkills()).find((skill) => skill.name === name);
1381
+ }
1382
+ /** Say why an Automation whose skill is gone cannot run. */
1383
+ function missingAutomationSkillReason(name) {
1384
+ return `The skill ${name} is no longer installed. Choose another skill or switch to an instruction.`;
1385
+ }
1373
1386
  // src/chat/capabilities/jr-rpc-command.ts
1374
1387
  function commandResult(input) {
1375
1388
  let stdout = "";
@@ -5560,6 +5573,15 @@ async function listAgentRelatives(input) {
5560
5573
  siblings: family.filter((agent) => agent.childConversationId !== conversationId)
5561
5574
  };
5562
5575
  }
5576
+ // src/chat/conversations/sql/listed.ts
5577
+ /**
5578
+ * Match Conversations that lists and searches may show: roots that are not
5579
+ * an unkept Quick question. Each list adds its own access and scope filters.
5580
+ * Structural root checks, such as retention, do not use this.
5581
+ */
5582
+ function listedConversation() {
5583
+ return and(isNull(juniorConversations.parentConversationId), isNull(juniorConversations.quickQuestionAt));
5584
+ }
5563
5585
  // src/chat/agent-invocations/search-top-level.ts
5564
5586
  /**
5565
5587
  * Search the top-level agents that one root Conversation may find: public
@@ -5579,9 +5601,8 @@ async function searchTopLevelAgents(args) {
5579
5601
  const tsquery = sql`websearch_to_tsquery('english', ${query ?? ""})`;
5580
5602
  const searchVector = sql`to_tsvector('english', ${briefs.searchText})`;
5581
5603
  const conditions = [
5582
- isNull(juniorConversations.parentConversationId),
5604
+ listedConversation(),
5583
5605
  eq(juniorConversations.rootConversationId, juniorConversations.conversationId),
5584
- isNull(juniorConversations.quickQuestionAt),
5585
5606
  isNull(juniorConversations.transcriptPurgedAt),
5586
5607
  ne(juniorConversations.conversationId, requesterConversationId),
5587
5608
  eq(juniorDestinations.visibility, "public"),
@@ -6771,10 +6792,14 @@ function createConversationTurnWorker(agentRunner, deliverMessage) {
6771
6792
  visibility
6772
6793
  });
6773
6794
  const webActor = actor.platform === "web" ? actor : void 0;
6774
- const disabledFeatures = [...webActor ? [] : ["interactive-auth"], ...isThread ? ["subagents"] : []];
6795
+ const disabledFeatures = webActor ? [] : ["interactive-auth"];
6775
6796
  const conversationLocation = storedConversation?.location;
6776
6797
  const isEventTurn = source.kind === "event" || savedMessageIsEvent;
6777
- const deliverToProvider = Boolean(conversationLocation) && isEventTurn && storedConversation?.kind === "root";
6798
+ const deliverToProvider = Boolean(conversationLocation) && isEventTurn && turnBehavior({
6799
+ kind: storedConversation?.kind ?? "root",
6800
+ personInput: false,
6801
+ automationRun: false
6802
+ }).delivery === "location";
6778
6803
  const surface = deliverToProvider ? "slack" : "api";
6779
6804
  const inputTelemetry = resolved.kind === "mailbox" ? turnInputTelemetry(resolved.batch.map((entry) => entry.message)) : void 0;
6780
6805
  const turnTrace = inputTelemetry ?? (savedTurn?.traceContext ? { traceContexts: [savedTurn.traceContext] } : void 0);
@@ -9342,7 +9367,9 @@ function viewerAutomationCollection(viewer) {
9342
9367
  destination: sql`${automation.teamId} || ':' || ${automation.channelId}`.as("destination"),
9343
9368
  destinationLabel: sql`coalesce(nullif(${destination.displayName}, ''), ${automation.channelId})`.as("destination_label"),
9344
9369
  isPublic: publicDestination.as("is_public"),
9345
- instruction: automation.instruction
9370
+ instruction: automation.instruction,
9371
+ skill: automation.skill,
9372
+ task: sql`${automation.record}->'task'`.as("task")
9346
9373
  }).from(automation).leftJoin(destination, and(eq(destination.provider, "slack"), eq(destination.providerTenantId, automation.teamId), eq(destination.providerDestinationId, automation.channelId))).where(and(ne(automation.status, "deleted"), or(owned, sharedToViewer))).as("accessible_automations");
9347
9374
  }
9348
9375
  /**
@@ -9367,7 +9394,7 @@ async function readAutomationCollection(viewer, input) {
9367
9394
  const unavailableIds = await unavailableEventAutomationIds(collection);
9368
9395
  const unavailable = unavailableIds.length > 0 ? inArray(collection.id, unavailableIds) : sql`false`;
9369
9396
  const attention = and(notInArray(collection.state, ["paused", "completed"]), or(eq(collection.state, "blocked"), unavailable, eq(collection.lastRunNeedsAttention, true)));
9370
- const where = and(input.scope === "mine" ? eq(collection.owned, true) : input.scope === "public" ? eq(collection.isPublic, true) : input.scope === "attention" ? attention : void 0, input.type === "all" ? void 0 : eq(collection.kind, input.type), input.state === "all" ? void 0 : input.state === "unavailable" ? unavailable : eq(collection.state, input.state), input.creator ? eq(collection.creator, input.creator) : void 0, input.destination ? eq(collection.destination, input.destination) : void 0, input.q ? sql`(strpos(lower(concat_ws(' ', ${collection.title}, ${collection.instruction}, ${collection.resource})), ${input.q.toLowerCase()}) > 0 or strpos(${input.q.toLowerCase()}, lower(${collection.id})) > 0)` : void 0);
9397
+ const where = and(input.scope === "mine" ? eq(collection.owned, true) : input.scope === "public" ? eq(collection.isPublic, true) : input.scope === "attention" ? attention : void 0, input.type === "all" ? void 0 : eq(collection.kind, input.type), input.state === "all" ? void 0 : input.state === "unavailable" ? unavailable : eq(collection.state, input.state), input.creator ? eq(collection.creator, input.creator) : void 0, input.destination ? eq(collection.destination, input.destination) : void 0, input.skill ? eq(collection.skill, input.skill) : void 0, input.q ? sql`(strpos(lower(concat_ws(' ', ${collection.title}, ${collection.instruction}, ${collection.skill}, ${collection.resource})), ${input.q.toLowerCase()}) > 0 or strpos(${input.q.toLowerCase()}, lower(${collection.id})) > 0)` : void 0);
9371
9398
  const [totals, counts, creators, destinations] = await Promise.all([
9372
9399
  db.select({ total: count() }).from(collection).where(where),
9373
9400
  db.select({
@@ -9387,7 +9414,7 @@ async function readAutomationCollection(viewer, input) {
9387
9414
  ]);
9388
9415
  const total = totals[0].total;
9389
9416
  const page = Math.min(input.page, Math.max(1, Math.ceil(total / input.pageSize)));
9390
- const order = input.sort === "oldest" ? asc(collection.createdAtMs) : input.sort === "title" ? asc(sql`lower(coalesce(nullif(trim(${collection.title}), ''), ${collection.instruction}))`) : desc(collection.createdAtMs);
9417
+ const order = input.sort === "oldest" ? asc(collection.createdAtMs) : input.sort === "title" ? asc(sql`lower(coalesce(nullif(trim(${collection.title}), ''), ${collection.instruction}, ${collection.skill}))`) : desc(collection.createdAtMs);
9391
9418
  return {
9392
9419
  rows: await db.select({
9393
9420
  id: collection.id,
@@ -9462,8 +9489,23 @@ function requireCredentialStart(automation, isCreator) {
9462
9489
  if (isCreator || automation.credentialMode !== "creator") return;
9463
9490
  throw new AutomationEditError(`This ${"schedule" in automation ? "scheduled" : "event"} automation uses its creator's credentials. Only the creator can resume it or run it now. Switch it to system credentials first.`, "credentialMode");
9464
9491
  }
9492
+ /** Return true when an edit changes what a run does. */
9493
+ function changesAutomationTask(current, input) {
9494
+ return input.task !== void 0 && !isDeepStrictEqual(input.task, current);
9495
+ }
9465
9496
  /**
9466
- * Apply shared title, instruction, outcome, and creator credential rules.
9497
+ * Require a newly selected skill to be installed. A kept skill that is gone
9498
+ * stays, so other fields can still be saved; its runs block until someone
9499
+ * picks another skill.
9500
+ */
9501
+ async function requireAutomationSkill(task, current) {
9502
+ if (task.kind !== "skill") return;
9503
+ if (current?.kind === "skill" && current.skill === task.skill) return;
9504
+ if (await findAutomationSkill(task.skill)) return;
9505
+ throw new AutomationEditError(`The skill ${task.skill} is not installed. Choose an installed skill.`, "task.skill");
9506
+ }
9507
+ /**
9508
+ * Apply shared title, task, outcome, and creator credential rules.
9467
9509
  * Anyone who can manage the Automation can change any field except turning on
9468
9510
  * creator credentials. A non-creator change to execution or outcomes switches
9469
9511
  * it to system credentials, so creator credential output stays where the
@@ -9485,10 +9527,12 @@ async function editAutomationFields(current, input, isCreator, changesExecution)
9485
9527
  destination: outcome.destination
9486
9528
  });
9487
9529
  }
9530
+ const task = input.task ?? current.task;
9531
+ await requireAutomationSkill(task, current.task);
9488
9532
  const changesOutcomes = !isDeepStrictEqual(outcomes, current.outcomes);
9489
9533
  return {
9490
9534
  title: input.title ?? current.title,
9491
- task: { text: input.instruction ?? current.task.text },
9535
+ task,
9492
9536
  credentialMode: (changesExecution || changesOutcomes) && !isCreator ? "system" : input.credentialMode ?? current.credentialMode,
9493
9537
  outcomes
9494
9538
  };
@@ -9507,7 +9551,7 @@ const compactEventAutomationResultSchema = z.object({
9507
9551
  status_reason: z.string().nullable(),
9508
9552
  title: z.string().min(1).nullable(),
9509
9553
  dashboard_url: z.string().url().nullable(),
9510
- instruction: z.string().min(1),
9554
+ task: automationTaskSchema,
9511
9555
  trigger: z.object({
9512
9556
  namespace: z.string().min(1),
9513
9557
  identifier: z.string().min(1).nullable(),
@@ -9618,7 +9662,7 @@ function compactEventAutomation(task, catalog, isCreator) {
9618
9662
  status_reason: task.statusReason ?? null,
9619
9663
  title: task.title?.trim() || null,
9620
9664
  dashboard_url: getDashboardTaskLink(task.id) ?? null,
9621
- instruction: task.task.text,
9665
+ task: task.task,
9622
9666
  trigger: {
9623
9667
  namespace: task.trigger.namespace,
9624
9668
  identifier: task.trigger.identifier ?? null,
@@ -9653,7 +9697,8 @@ function compactEventAutomation(task, catalog, isCreator) {
9653
9697
  async function eventAutomationToolResult(conversationId, task, catalog, isCreator) {
9654
9698
  const automation = compactEventAutomation(task, catalog, isCreator);
9655
9699
  const description = describeEventAutomationTrigger(task.trigger, catalog);
9656
- const title = automation.title ?? fallbackShortTitle(task.task.text, "Event automation");
9700
+ const taskDescription = automationTaskDescription(task.task);
9701
+ const title = automation.title ?? fallbackShortTitle(taskDescription, "Event automation");
9657
9702
  return {
9658
9703
  automation,
9659
9704
  objectCards: await saveObjectAnnotations(conversationId, "junior", [{
@@ -9663,7 +9708,7 @@ async function eventAutomationToolResult(conversationId, task, catalog, isCreato
9663
9708
  key: task.id,
9664
9709
  title,
9665
9710
  url: automation.dashboard_url,
9666
- description: task.task.text,
9711
+ description: taskDescription,
9667
9712
  status: description.problems.length === 0 ? "ready" : "unavailable",
9668
9713
  trigger: eventTriggerText(task.trigger.label, description),
9669
9714
  warning: description.problems.length > 0 ? ["Trigger unavailable.", ...description.problems].join(" ") : void 0
@@ -9692,7 +9737,7 @@ async function editEventAutomation(current, input, isCreator, catalog, options)
9692
9737
  label: inputTrigger.label
9693
9738
  };
9694
9739
  }
9695
- const changesExecution = input.instruction !== void 0 && input.instruction !== current.task.text || changesEventAutomationTrigger(current.trigger, trigger);
9740
+ const changesExecution = changesAutomationTask(current.task, input) || changesEventAutomationTrigger(current.trigger, trigger);
9696
9741
  const next = {
9697
9742
  ...current,
9698
9743
  ...await editAutomationFields(current, input, isCreator, changesExecution),
@@ -9720,7 +9765,7 @@ async function editScheduledAutomation(current, input, isCreator, nowMs) {
9720
9765
  if (error instanceof ScheduleIntentError) throw new AutomationEditError(error.message, "schedule");
9721
9766
  throw error;
9722
9767
  }
9723
- const fields = await editAutomationFields(current, input, isCreator, input.instruction !== void 0 && input.instruction !== current.task.text || compiled !== void 0 && !isDeepStrictEqual(compiled.schedule, current.schedule));
9768
+ const fields = await editAutomationFields(current, input, isCreator, changesAutomationTask(current.task, input) || compiled !== void 0 && !isDeepStrictEqual(compiled.schedule, current.schedule));
9724
9769
  return {
9725
9770
  ...current,
9726
9771
  ...fields,
@@ -9800,14 +9845,16 @@ function executionSummaryFields(stats) {
9800
9845
  ...stats?.lastConversationId ? { lastConversationId: stats.lastConversationId } : void 0,
9801
9846
  ...stats?.lastExecutedAtMs ? { lastRunAt: new Date(stats.lastExecutedAtMs).toISOString() } : void 0,
9802
9847
  costUsd: stats?.costUsd ?? emptyAutomationRunWindows(),
9848
+ recentRuns: stats?.recentRuns ?? [],
9803
9849
  runs: stats?.runs ?? emptyAutomationRunWindows(),
9850
+ totalCostUsd: stats?.totalCostUsd ?? 0,
9804
9851
  totalRuns: stats?.totalRuns ?? 0
9805
9852
  };
9806
9853
  }
9807
9854
  function scheduledAutomationSummary(task, ownedByViewer, destination, stats, creator) {
9808
9855
  if (task.status === "deleted") throw new Error("Deleted scheduled automations cannot enter the Automations view");
9809
9856
  const nextRunAtMs = task.status === "active" ? task.runNowAtMs ?? task.nextRunAtMs : void 0;
9810
- const instruction = displayText(task.task.text, "Untitled scheduled automation");
9857
+ const description = displayText(automationTaskDescription(task.task), "Untitled scheduled automation");
9811
9858
  return {
9812
9859
  createdAt: new Date(task.createdAtMs).toISOString(),
9813
9860
  createdBy: creatorLabel(task.createdBy),
@@ -9820,7 +9867,7 @@ function scheduledAutomationSummary(task, ownedByViewer, destination, stats, cre
9820
9867
  visibility: destination.visibility
9821
9868
  },
9822
9869
  id: task.id,
9823
- instruction,
9870
+ task: task.task,
9824
9871
  kind: "scheduled",
9825
9872
  ...executionSummaryFields(stats),
9826
9873
  ...nextRunAtMs !== void 0 ? { nextRunAt: new Date(nextRunAtMs).toISOString() } : void 0,
@@ -9831,11 +9878,11 @@ function scheduledAutomationSummary(task, ownedByViewer, destination, stats, cre
9831
9878
  timezone: task.schedule.timezone,
9832
9879
  credentialMode: task.credentialMode,
9833
9880
  outcomes: effectiveTaskOutcomes(task.outcomes, task.destination),
9834
- title: taskDisplayTitle(task.title, instruction, "Untitled scheduled automation")
9881
+ title: taskDisplayTitle(task.title, description, "Untitled scheduled automation")
9835
9882
  };
9836
9883
  }
9837
9884
  function eventAutomationSummary(task, ownedByViewer, destination, stats, creator) {
9838
- const instruction = task.task.text;
9885
+ const description = automationTaskDescription(task.task);
9839
9886
  const catalog = getEventCatalog();
9840
9887
  return {
9841
9888
  createdAt: new Date(task.createdAtMs).toISOString(),
@@ -9849,7 +9896,7 @@ function eventAutomationSummary(task, ownedByViewer, destination, stats, creator
9849
9896
  visibility: destination.visibility
9850
9897
  },
9851
9898
  id: task.id,
9852
- instruction,
9899
+ task: task.task,
9853
9900
  kind: "event",
9854
9901
  ...executionSummaryFields(stats),
9855
9902
  ownedByViewer,
@@ -9857,7 +9904,7 @@ function eventAutomationSummary(task, ownedByViewer, destination, stats, creator
9857
9904
  source: task.trigger.namespace,
9858
9905
  credentialMode: task.credentialMode,
9859
9906
  outcomes: effectiveTaskOutcomes(task.outcomes, task.destination),
9860
- title: taskDisplayTitle(task.title, instruction, "Untitled event automation"),
9907
+ title: taskDisplayTitle(task.title, description, "Untitled event automation"),
9861
9908
  status: task.status === "deleted" ? "active" : task.status,
9862
9909
  statusReason: task.statusReason,
9863
9910
  trigger: describeEventAutomationTrigger(task.trigger, catalog)
@@ -9921,29 +9968,15 @@ async function automationSummaryForCandidate(candidate) {
9921
9968
  if (candidate.kind === "scheduled") return scheduledAutomationSummary(candidate.task, candidate.ownedByViewer, destination, stats.get(candidate.task.id), creator);
9922
9969
  return eventAutomationSummary(candidate.task, candidate.ownedByViewer, destination, stats.get(candidate.task.id), creator);
9923
9970
  }
9924
- function emptyAutomationExecutionDay(date) {
9925
- return {
9926
- costUsd: 0,
9927
- date,
9928
- event: 0,
9929
- scheduled: 0
9930
- };
9931
- }
9932
9971
  function emptyAutomationExecutionStatusDay(date) {
9933
9972
  return {
9934
9973
  blocked: 0,
9935
9974
  completed: 0,
9975
+ costUsd: 0,
9936
9976
  date,
9937
9977
  failed: 0
9938
9978
  };
9939
9979
  }
9940
- function automationExecutionSixHours(hours, nowMs = Date.now()) {
9941
- return sumUtcHoursIntoSixHours({
9942
- empty: emptyAutomationExecutionDay,
9943
- hours,
9944
- nowMs
9945
- });
9946
- }
9947
9980
  function automationExecutionStatusSixHours(hours, nowMs = Date.now()) {
9948
9981
  return sumUtcHoursIntoSixHours({
9949
9982
  empty: emptyAutomationExecutionStatusDay,
@@ -9987,27 +10020,17 @@ async function readViewerAutomations(user, input = automationListQuerySchema.par
9987
10020
  const selected = await readTaskCandidates(user, ids);
9988
10021
  const [destinations, creators] = await Promise.all([destinationDetails(selected.map(({ task }) => task.destination)), creatorProfiles(selected)]);
9989
10022
  const visible = selected.filter((candidate) => candidate.ownedByViewer || destinations.get(destinationKey(candidate.task.destination))?.visibility === "public");
9990
- const collection = viewerAutomationCollection(user);
9991
- const access = exists(getDb().select({ id: collection.id }).from(collection).where(eq(collection.id, juniorAutomationRuns.automationId)));
9992
- const [executionDays, executionHours, stats] = await Promise.all([
9993
- readAutomationExecutionDays(90, { access }),
9994
- readAutomationExecutionHours(168, { access }),
9995
- readAutomationExecutionSummaries(ids)
9996
- ]);
9997
- const automations = visible.map((candidate) => {
9998
- const destination = destinations.get(destinationKey(candidate.task.destination)) ?? {
9999
- label: `Channel ${candidate.task.destination.channelId}`,
10000
- visibility: "private"
10001
- };
10002
- const creator = creators.get(creatorKey(candidate.task.destination.teamId, candidate.task.createdBy.slackUserId));
10003
- if (candidate.kind === "scheduled") return scheduledAutomationSummary(candidate.task, candidate.ownedByViewer, destination, stats.get(candidate.task.id), creator);
10004
- return eventAutomationSummary(candidate.task, candidate.ownedByViewer, destination, stats.get(candidate.task.id), creator);
10005
- });
10023
+ const stats = await readAutomationExecutionSummaries(ids);
10006
10024
  return {
10007
- executionDays,
10008
- executionHours,
10009
- executionSixHours: automationExecutionSixHours(executionHours),
10010
- automations,
10025
+ automations: visible.map((candidate) => {
10026
+ const destination = destinations.get(destinationKey(candidate.task.destination)) ?? {
10027
+ label: `Channel ${candidate.task.destination.channelId}`,
10028
+ visibility: "private"
10029
+ };
10030
+ const creator = creators.get(creatorKey(candidate.task.destination.teamId, candidate.task.createdBy.slackUserId));
10031
+ if (candidate.kind === "scheduled") return scheduledAutomationSummary(candidate.task, candidate.ownedByViewer, destination, stats.get(candidate.task.id), creator);
10032
+ return eventAutomationSummary(candidate.task, candidate.ownedByViewer, destination, stats.get(candidate.task.id), creator);
10033
+ }),
10011
10034
  ...page
10012
10035
  };
10013
10036
  }
@@ -10047,14 +10070,14 @@ async function readViewerAutomationRuns(user) {
10047
10070
  const automationTitles = /* @__PURE__ */ new Map();
10048
10071
  const automations = [];
10049
10072
  for (const task of taskList) {
10050
- automationTitles.set(`${task.kind}:${task.id}`, taskDisplayTitle(task.title ?? void 0, task.instruction, `Untitled ${task.kind} automation`));
10073
+ automationTitles.set(`${task.kind}:${task.id}`, taskDisplayTitle(task.title ?? void 0, automationTaskDescription(automationTaskSchema.parse(task.task)), `Untitled ${task.kind} automation`));
10051
10074
  automations.push({
10052
10075
  kind: task.kind,
10053
10076
  automationId: task.id
10054
10077
  });
10055
10078
  }
10056
10079
  for (const task of deletedScheduled) {
10057
- const instruction = displayText(task.task.text, "Untitled scheduled automation");
10080
+ const instruction = displayText(automationTaskDescription(task.task), "Untitled scheduled automation");
10058
10081
  addDeletedAutomationRun({
10059
10082
  kind: "scheduled",
10060
10083
  automationId: task.id,
@@ -10062,7 +10085,7 @@ async function readViewerAutomationRuns(user) {
10062
10085
  }, automationTitles, automations);
10063
10086
  }
10064
10087
  for (const task of deletedEvent) {
10065
- const instruction = displayText(task.task.text, "Untitled event automation");
10088
+ const instruction = displayText(automationTaskDescription(task.task), "Untitled event automation");
10066
10089
  addDeletedAutomationRun({
10067
10090
  kind: "event",
10068
10091
  automationId: task.id,
@@ -10160,7 +10183,7 @@ async function readConversationSourceTask(args) {
10160
10183
  if (!candidate) return base;
10161
10184
  const credential = await readRunCredential(dispatchId, candidate.task.createdBy);
10162
10185
  if (candidate.kind === "scheduled") {
10163
- const instruction = displayText(candidate.task.task.text, "Untitled scheduled automation");
10186
+ const instruction = displayText(automationTaskDescription(candidate.task.task), "Untitled scheduled automation");
10164
10187
  const schedule = candidate.task.schedule.description.trim();
10165
10188
  return {
10166
10189
  ...base,
@@ -10172,7 +10195,7 @@ async function readConversationSourceTask(args) {
10172
10195
  ...schedule ? { triggerLabel: schedule } : void 0
10173
10196
  };
10174
10197
  }
10175
- const instruction = displayText(candidate.task.task.text, "Untitled event automation");
10198
+ const instruction = displayText(automationTaskDescription(candidate.task.task), "Untitled event automation");
10176
10199
  const { events, label } = candidate.task.trigger;
10177
10200
  return {
10178
10201
  ...base,
@@ -10216,7 +10239,7 @@ function editView(automation, ownedByViewer) {
10216
10239
  id: task.id,
10217
10240
  revision: automationRevision(task),
10218
10241
  title: task.title ?? null,
10219
- instruction: task.task.text,
10242
+ task: task.task,
10220
10243
  credentialMode: task.credentialMode,
10221
10244
  outcomes: task.outcomes,
10222
10245
  destination: task.destination,
@@ -10342,7 +10365,7 @@ async function activateViewerAutomationVersion(user, id, input) {
10342
10365
  if (sameDefinitionValue(definition, automationDefinition(current.task))) return editView(current, current.ownedByViewer);
10343
10366
  if (!sameDefinitionValue(definition.destination, current.task.destination)) throw new AutomationEditError("This version delivers to another Destination. Move the automation from Slack instead.", "destination");
10344
10367
  const fields = {};
10345
- if (definition.instruction !== current.task.task.text) fields.instruction = definition.instruction;
10368
+ if (!sameDefinitionValue(definition.task, current.task.task)) fields.task = definition.task;
10346
10369
  if (definition.credentialMode !== current.task.credentialMode) fields.credentialMode = definition.credentialMode;
10347
10370
  if (!sameDefinitionValue(definition.outcomes, current.task.outcomes)) fields.outcomes = await restorableOutcomes(current, definition.outcomes);
10348
10371
  const title = definition.title ?? void 0;
@@ -10458,6 +10481,7 @@ async function deleteAutomation(current) {
10458
10481
  });
10459
10482
  }
10460
10483
  // src/chat/automations/tool-access.ts
10484
+ /** Automation access for the Automation tools. */
10461
10485
  /**
10462
10486
  * Return the Actor when that person started this Turn from any surface.
10463
10487
  * Automation runs, Events, plugin dispatch, and Agent invocations act for no
@@ -10572,13 +10596,14 @@ const MAX_SEARCHED_AUTOMATIONS = 50;
10572
10596
  /** Model-facing input of the Automation search tool. */
10573
10597
  const automationSearchInputSchema = z.object({
10574
10598
  type: z.enum(["scheduled", "event"]).nullable().describe("scheduled: only automations with a schedule. event: only automations that run on events. Omit to find both.").optional(),
10575
- query: z.string().trim().min(1).max(200).nullable().describe("Text in the title or instruction, an automation ID, or a dashboard URL.").optional(),
10599
+ query: z.string().trim().min(1).max(200).nullable().describe("Text in the title, instruction, or skill name, an automation ID, or a dashboard URL.").optional(),
10576
10600
  scope: z.enum([
10577
10601
  "all",
10578
10602
  "current_conversation",
10579
10603
  "mine"
10580
10604
  ]).nullable().describe("Omit to search everything the requester can find. Set current_conversation (only automations that deliver to this conversation) or mine (only automations the requester created) only when the user limits the search that way.").optional(),
10581
- destination: z.string().trim().min(1).max(300).nullable().describe("Limit results to automations that deliver to this destination. Use destination.id from an earlier result.").optional()
10605
+ destination: z.string().trim().min(1).max(300).nullable().describe("Limit results to automations that deliver to this destination. Use destination.id from an earlier result.").optional(),
10606
+ skill: automationSkillNameSchema.nullable().describe("Only automations that run this skill, by exact name.").optional()
10582
10607
  }).strict();
10583
10608
  /**
10584
10609
  * Search Automations with the dashboard Automations search, as the tool
@@ -10596,6 +10621,7 @@ async function searchToolAutomations(context, caller, input) {
10596
10621
  scope: input.scope === "mine" ? "mine" : "all",
10597
10622
  type: input.type ?? "all",
10598
10623
  destination,
10624
+ skill: input.skill ?? void 0,
10599
10625
  pageSize: MAX_SEARCHED_AUTOMATIONS
10600
10626
  }));
10601
10627
  return {
@@ -10653,7 +10679,7 @@ const compactTaskResultSchema = z.object({
10653
10679
  created_at: z.string().datetime(),
10654
10680
  updated_at: z.string().datetime(),
10655
10681
  original_request: z.string().nullable(),
10656
- instruction: z.string(),
10682
+ task: automationTaskSchema,
10657
10683
  schedule: z.string(),
10658
10684
  timezone: z.string(),
10659
10685
  recurrence: z.unknown().nullable(),
@@ -10717,7 +10743,7 @@ function compactTask(task, isCreator) {
10717
10743
  created_at: new Date(task.createdAtMs).toISOString(),
10718
10744
  updated_at: new Date(task.updatedAtMs).toISOString(),
10719
10745
  original_request: task.originalRequest ?? null,
10720
- instruction: task.task.text,
10746
+ task: task.task,
10721
10747
  schedule: task.schedule.description,
10722
10748
  timezone: task.schedule.timezone,
10723
10749
  recurrence: task.schedule.recurrence ? {
@@ -10757,7 +10783,8 @@ function compactTask(task, isCreator) {
10757
10783
  /** Build the result of a tool that changed one scheduled automation, with its card. */
10758
10784
  async function scheduleAutomationToolResult(conversationId, task, isCreator) {
10759
10785
  const automation = compactTask(task, isCreator);
10760
- const title = automation.title ?? fallbackShortTitle(automation.instruction, "Scheduled automation");
10786
+ const description = automationTaskDescription(task.task);
10787
+ const title = automation.title ?? fallbackShortTitle(description, "Scheduled automation");
10761
10788
  const annotation = {
10762
10789
  kind: "object",
10763
10790
  objectType: "automation",
@@ -10765,7 +10792,7 @@ async function scheduleAutomationToolResult(conversationId, task, isCreator) {
10765
10792
  key: task.id,
10766
10793
  title,
10767
10794
  url: automation.dashboard_url,
10768
- description: automation.instruction,
10795
+ description,
10769
10796
  status: automation.status,
10770
10797
  trigger: task.schedule.kind === "one_off" && task.nextRunAtMs !== void 0 ? `${new Intl.DateTimeFormat("en-US", {
10771
10798
  dateStyle: "medium",
@@ -10810,6 +10837,50 @@ function automationTriggerSchema(catalog) {
10810
10837
  function automationTriggerChangesSchema(catalog) {
10811
10838
  return z.discriminatedUnion("type", [scheduleTriggerSchema, registeredEventAutomationTriggerChangesSchema(catalog).extend({ type: z.literal("event") })]);
10812
10839
  }
10840
+ /**
10841
+ * Build the skill input of the create and update tools. The description
10842
+ * lists every discovered skill, because `<available-skills>` leaves out the
10843
+ * ones with `disable-model-invocation`, and an Automation can run those too.
10844
+ */
10845
+ function automationSkillToolSchema(skills) {
10846
+ const names = skills.map((skill) => skill.disableModelInvocation ? `${skill.name} (manual only)` : skill.name);
10847
+ return automationSkillNameSchema.describe(`Skill that each run invokes instead of a written instruction. Any installed skill works, including manual-only ones. Installed skills: ${names.length > 0 ? names.join(", ") : "none"}.`);
10848
+ }
10849
+ /** Map the task fields of a new Automation to its task. */
10850
+ function newAutomationTask(input) {
10851
+ const task = editedAutomationTask(void 0, input);
10852
+ if (!task) throw new ToolInputError("Set instruction or skill.");
10853
+ return task;
10854
+ }
10855
+ /**
10856
+ * Map the task fields of an update to the saved task, or undefined when they
10857
+ * change nothing. `instruction` switches to an instruction. `skill` switches
10858
+ * to a skill and keeps the current context. `context` needs skill mode.
10859
+ */
10860
+ function editedAutomationTask(current, input) {
10861
+ const { instruction, skill, context } = input;
10862
+ if (instruction !== void 0 && skill !== void 0) throw new ToolInputError("Set instruction or skill, not both.");
10863
+ if (instruction !== void 0) {
10864
+ if (context !== void 0) throw new ToolInputError("Context goes only with a skill. Put everything in the instruction.");
10865
+ return {
10866
+ kind: "instruction",
10867
+ instruction
10868
+ };
10869
+ }
10870
+ const kept = current?.kind === "skill" ? current : void 0;
10871
+ const nextSkill = skill ?? kept?.skill;
10872
+ if (nextSkill === void 0) {
10873
+ if (context === void 0) return void 0;
10874
+ throw new ToolInputError("Context goes only with a skill. Set skill, or change the instruction instead.");
10875
+ }
10876
+ if (skill === void 0 && context === void 0) return void 0;
10877
+ const nextContext = context === void 0 ? kept?.context : context;
10878
+ return {
10879
+ kind: "skill",
10880
+ skill: nextSkill,
10881
+ ...nextContext ? { context: nextContext } : void 0
10882
+ };
10883
+ }
10813
10884
  /** Return the Automation kind of a trigger input. */
10814
10885
  function triggerKind(trigger) {
10815
10886
  return trigger.type === "schedule" ? "scheduled" : "event";
@@ -10924,7 +10995,7 @@ async function createScheduled(context, next, compiled) {
10924
10995
  schedule: compiled.schedule,
10925
10996
  status: "active",
10926
10997
  outcomes: next.outcomes,
10927
- task: { text: next.instruction },
10998
+ task: next.task,
10928
10999
  ...next.title ? { title: next.title } : void 0
10929
11000
  });
10930
11001
  logInfo("scheduled_automation.create.completed", scheduledAutomationAttributes(task));
@@ -10946,7 +11017,7 @@ async function createEvent(context, next, trigger) {
10946
11017
  credentialMode: next.credentialMode,
10947
11018
  destination: next.destination,
10948
11019
  outcomes: next.outcomes,
10949
- task: { text: next.instruction },
11020
+ task: next.task,
10950
11021
  ...next.title ? { title: next.title } : void 0,
10951
11022
  trigger
10952
11023
  })),
@@ -10972,7 +11043,7 @@ async function readReplayedAutomation(kind, id) {
10972
11043
  } : void 0;
10973
11044
  }
10974
11045
  /** Create the tool that stores a scheduled or event Automation. */
10975
- function createAutomationTool(context, catalog) {
11046
+ function createAutomationTool(context, catalog, skills = []) {
10976
11047
  const trigger = automationTriggerSchema(catalog);
10977
11048
  return zodTool({
10978
11049
  exposure: "deferred",
@@ -10985,10 +11056,12 @@ function createAutomationTool(context, catalog) {
10985
11056
  readOnlyHint: false
10986
11057
  },
10987
11058
  executionMode: "sequential",
10988
- description: "Create a durable automation. It belongs to the channel or DM of this conversation, never a thread. Its outcomes set where its messages go. Use trigger type \"schedule\" for one-time or recurring work. Use trigger type \"event\" only when the user explicitly asks for an event automation or durable whenever-this-happens-do-X work; it runs the instruction for every matching event. Ordinary watch, notify, or tell-me-when requests use watchEvents instead. Store the requested future work; do not perform it or check its service access now unless the user also asks for that. When the trigger is known, create it without redundant confirmation.",
11059
+ description: "Create a durable automation. It belongs to the channel or DM of this conversation, never a thread. Its outcomes set where its messages go. Use trigger type \"schedule\" for one-time or recurring work. Use trigger type \"event\" only when the user explicitly asks for an event automation or durable whenever-this-happens-do-X work; it runs for every matching event. Set instruction for written work, or skill to run an installed skill, with context only when the skill needs more. Ordinary watch, notify, or tell-me-when requests use watchEvents instead. Store the requested future work; do not perform it or check its service access now unless the user also asks for that. When the trigger is known, create it without redundant confirmation.",
10989
11060
  inputSchema: z.object({
10990
- instruction: automationInstructionToolSchema,
10991
- title: z.string().trim().min(1).max(60).nullable().describe("Optional short display title. Omit or use null to generate one from the instruction.").optional(),
11061
+ instruction: automationInstructionToolSchema.nullable().optional(),
11062
+ skill: automationSkillToolSchema(skills).nullable().optional(),
11063
+ context: automationContextToolSchema.nullable().optional(),
11064
+ title: z.string().trim().min(1).max(60).nullable().describe("Optional short display title. Omit or use null to generate one from the instruction or skill.").optional(),
10992
11065
  trigger,
10993
11066
  outcomes: z.array(taskOutcomeInputSchema).max(5).describe("Successful work is silent by default. Omit this field or use an empty list when the Automation should act through tools without a status message. Add send_message only when the user asks for a reminder, notification, post, digest, summary, or other visible result.").optional(),
10994
11067
  credential_mode: z.enum(["creator", "system"]).nullable().describe("Use creator to make the creator's connected credentials available, or system when the creator says not to use them. Omit or use null for the creator default.").optional()
@@ -10996,6 +11069,9 @@ function createAutomationTool(context, catalog) {
10996
11069
  prepareArguments(args) {
10997
11070
  const prepared = { ...args };
10998
11071
  if (prepared.title == null) delete prepared.title;
11072
+ if (prepared.instruction == null) delete prepared.instruction;
11073
+ if (prepared.skill == null) delete prepared.skill;
11074
+ if (prepared.context == null) delete prepared.context;
10999
11075
  if (prepared.credential_mode === "creator" || prepared.credential_mode === null) delete prepared.credential_mode;
11000
11076
  return prepared;
11001
11077
  },
@@ -11006,7 +11082,14 @@ function createAutomationTool(context, catalog) {
11006
11082
  const caller = await requireToolCaller(context);
11007
11083
  const creator = requireToolCreator(caller, destination, kind);
11008
11084
  const { createdBy } = creator;
11009
- requireInstructionReferences(input.instruction, {
11085
+ const task = newAutomationTask({
11086
+ instruction: input.instruction ?? void 0,
11087
+ skill: input.skill ?? void 0,
11088
+ context: input.context ?? void 0
11089
+ });
11090
+ await requireAutomationSkill(task, void 0);
11091
+ const text = automationTaskText(task);
11092
+ if (text) requireInstructionReferences(text, {
11010
11093
  creator: createdBy,
11011
11094
  destinationChannelId: destination.channelId
11012
11095
  });
@@ -11034,15 +11117,15 @@ function createAutomationTool(context, catalog) {
11034
11117
  creator,
11035
11118
  destination,
11036
11119
  id,
11037
- instruction: input.instruction,
11038
11120
  nowMs,
11121
+ task,
11039
11122
  credentialMode: input.credential_mode ?? "creator",
11040
11123
  outcomes: await resolveTaskOutcomes(input.outcomes, destination, createdBy.slackUserId),
11041
11124
  title: await resolveTaskTitle({
11042
11125
  signal: options.signal,
11043
11126
  completeText,
11044
11127
  cost: { conversationId: context.conversationId },
11045
- instruction: input.instruction,
11128
+ instruction: automationTaskDescription(task),
11046
11129
  title: input.title
11047
11130
  })
11048
11131
  };
@@ -11426,7 +11509,7 @@ async function requireMoveDestination(context, value) {
11426
11509
  };
11427
11510
  }
11428
11511
  /** Edit and save a scheduled Automation, including a move to a new Destination. */
11429
- async function updateScheduled(context, current, input, editor) {
11512
+ async function updateScheduled(context, current, input, editedTask, editor) {
11430
11513
  const { task, ownedByViewer: isCreator } = current;
11431
11514
  const target = input.destination ? await requireMoveDestination(context, input.destination) : void 0;
11432
11515
  const destination = target?.destination;
@@ -11435,7 +11518,7 @@ async function updateScheduled(context, current, input, editor) {
11435
11518
  if (moving) await requireNoIncompleteRun(task.id);
11436
11519
  const next = await editScheduledAutomation(task, {
11437
11520
  title: input.title,
11438
- instruction: input.instruction,
11521
+ task: editedTask,
11439
11522
  schedule: input.trigger?.type === "schedule" ? scheduleIntentFromTool(input.trigger.schedule) : void 0,
11440
11523
  credentialMode: input.credential_mode,
11441
11524
  outcomes: moving ? void 0 : input.outcomes
@@ -11454,12 +11537,12 @@ async function updateScheduled(context, current, input, editor) {
11454
11537
  };
11455
11538
  }
11456
11539
  /** Edit and save an event Automation. */
11457
- async function updateEvent(current, input, editor, catalog) {
11540
+ async function updateEvent(current, input, editedTask, editor, catalog) {
11458
11541
  const { task } = current;
11459
11542
  const trigger = input.trigger?.type === "event" ? input.trigger : void 0;
11460
11543
  const next = await editEventAutomation(task, {
11461
11544
  title: input.title,
11462
- instruction: input.instruction,
11545
+ task: editedTask,
11463
11546
  trigger: trigger ? {
11464
11547
  ...trigger,
11465
11548
  ...trigger.namespace === task.trigger.namespace ? {
@@ -11479,12 +11562,15 @@ async function updateEvent(current, input, editor, catalog) {
11479
11562
  };
11480
11563
  }
11481
11564
  /** Create the tool that edits, pauses, resumes, or moves one Automation. */
11482
- function createUpdateAutomationTool(context, catalog) {
11565
+ function createUpdateAutomationTool(context, catalog, skills = []) {
11483
11566
  const trigger = automationTriggerChangesSchema(catalog);
11567
+ const skill = automationSkillToolSchema(skills);
11484
11568
  const inputSchema = z.object({
11485
11569
  automation_id: z.string().min(1).describe("ID of the automation, from searchAutomations or its dashboard URL."),
11486
11570
  title: automationTitleSchema.optional(),
11487
- instruction: automationInstructionToolSchema.nullable().optional(),
11571
+ instruction: automationInstructionToolSchema.nullable().describe(`${automationInstructionToolSchema.description} Setting it switches a skill Automation to this instruction and drops its context. Omit or use null to keep the current task.`).optional(),
11572
+ skill: skill.nullable().describe(`${skill.description} Setting it switches an instruction Automation to this skill, or changes the skill and keeps its context. Omit or use null to keep the current task.`).optional(),
11573
+ context: automationContextToolSchema.nullable().describe(`${automationContextToolSchema.description} Only for a skill Automation, or with skill. Use null to remove the context. Omit to keep it.`).optional(),
11488
11574
  trigger: trigger.nullable().describe("Replacement trigger of the same type. For an event trigger, match changes only the filters that it names. Omit or use null to keep the trigger.").optional(),
11489
11575
  outcomes: z.array(taskOutcomeInputSchema).max(5).nullable().describe("Replacement messages to send after successful work. Use an empty list to send nothing. Omit or use null to leave unchanged.").optional(),
11490
11576
  credential_mode: z.enum(["system", "creator"]).nullable().describe("Set creator to make the automation creator's credentials available, or system to disable them. Creator always means the automation's createdBy actor, never the current requester. Only that creator may enable creator mode. Omit or use null to leave unchanged.").optional(),
@@ -11502,10 +11588,10 @@ function createUpdateAutomationTool(context, catalog) {
11502
11588
  readOnlyHint: false
11503
11589
  },
11504
11590
  executionMode: "sequential",
11505
- description: "Update the title, instruction, trigger, outcomes, credential use, or status of a scheduled or event automation. Anyone in the workspace can update anything on an automation in a public channel, including its outcomes and destination. Automations in private channels and DMs can be updated from there or by their creator, and only their creator can move them. Only the creator can enable creator credentials. A non-creator who changes the instruction, trigger, outcomes, or destination switches it to system credentials. The trigger type cannot change. Set destination to move a scheduled automation to this conversation or to a public channel.",
11591
+ description: "Update the title, instruction or skill and its context, trigger, outcomes, credential use, or status of a scheduled or event automation. Anyone in the workspace can update anything on an automation in a public channel, including its outcomes and destination. Automations in private channels and DMs can be updated from there or by their creator, and only their creator can move them. Only the creator can enable creator credentials. A non-creator who changes the instruction, skill, context, trigger, outcomes, or destination switches it to system credentials. The trigger type cannot change. Set destination to move a scheduled automation to this conversation or to a public channel.",
11506
11592
  inputSchema,
11507
11593
  prepareArguments(args) {
11508
- return Object.fromEntries(Object.entries(args).filter(([, value]) => value != null));
11594
+ return Object.fromEntries(Object.entries(args).filter(([key, value]) => value !== void 0 && (value !== null || key === "context")));
11509
11595
  },
11510
11596
  outputSchema: automationToolResultSchema,
11511
11597
  async execute({ automation_id, status: requestedStatus, ...fields }) {
@@ -11519,14 +11605,17 @@ function createUpdateAutomationTool(context, catalog) {
11519
11605
  if (input.destination && current.kind === "event") throw new ToolInputError("Event automations cannot move. Create a new event automation in this conversation instead.");
11520
11606
  if (input.destination && !current.ownedByViewer && await resolveDestinationVisibility({ destination: current.task.destination }) !== "public") throw new ToolInputError("Only the creator can move an automation out of a private channel or DM.");
11521
11607
  const editor = automationEditor(caller.viewer, current);
11522
- if (input.instruction !== void 0 && input.instruction !== current.task.task.text) requireInstructionReferences(input.instruction, {
11608
+ const editedTask = editedAutomationTask(current.task.task, input);
11609
+ const previousText = automationTaskText(current.task.task);
11610
+ const text = editedTask && automationTaskText(editedTask);
11611
+ if (text !== void 0 && text !== previousText) requireInstructionReferences(text, {
11523
11612
  creator: current.task.createdBy,
11524
11613
  destinationChannelId: current.task.destination.channelId,
11525
11614
  requester: editor,
11526
- previousInstruction: current.task.task.text
11615
+ previousInstruction: previousText ?? ""
11527
11616
  });
11528
11617
  let saved = current;
11529
- if (Object.keys(input).length > 0) saved = current.kind === "scheduled" ? await updateScheduled(context, current, input, editor) : await updateEvent(current, input, editor, catalog);
11618
+ if (Object.keys(input).length > 0) saved = current.kind === "scheduled" ? await updateScheduled(context, current, input, editedTask, editor) : await updateEvent(current, input, editedTask, editor, catalog);
11530
11619
  if (status !== void 0 && status !== saved.task.status) saved = await changeAutomationLifecycle(saved, {
11531
11620
  action: status === "paused" ? "pause" : "resume",
11532
11621
  revision: automationRevision(saved.task)
@@ -11559,12 +11648,12 @@ function disableTools(tools, reason) {
11559
11648
  }
11560
11649
  // src/chat/tools/automations.ts
11561
11650
  /** Build the Automation tools. A Turn that no person started cannot use them. */
11562
- function createAutomationTools(context, catalog) {
11651
+ function createAutomationTools(context, catalog, skills) {
11563
11652
  const automationContext = automationToolContext(context);
11564
11653
  return disableTools({
11565
- createAutomation: createAutomationTool(automationContext, catalog),
11654
+ createAutomation: createAutomationTool(automationContext, catalog, skills),
11566
11655
  searchAutomations: createSearchAutomationsTool(automationContext, catalog),
11567
- updateAutomation: createUpdateAutomationTool(automationContext, catalog),
11656
+ updateAutomation: createUpdateAutomationTool(automationContext, catalog, skills),
11568
11657
  deleteAutomation: createDeleteAutomationTool(automationContext, catalog),
11569
11658
  runAutomationNow: createRunAutomationNowTool(automationContext, catalog)
11570
11659
  }, automationToolsDisabledReason(context));
@@ -14748,7 +14837,7 @@ const USER_CUSTOMIZATION_TOOL_SOURCE = {
14748
14837
  */
14749
14838
  function createUserCustomizationTools(context) {
14750
14839
  if (!isExperimentalFeatureEnabled("user-customization")) return {};
14751
- if (context.agentInvocationId) return {};
14840
+ if (!context.turnTools.userCustomization) return {};
14752
14841
  return { updateUserCustomization: zodTool({
14753
14842
  exposure: "deferred",
14754
14843
  source: USER_CUSTOMIZATION_TOOL_SOURCE,
@@ -14874,7 +14963,7 @@ const CONVERSATION_SUBSCRIPTION_TOOL_SOURCE = {
14874
14963
  * its input. Contract: `api/conversations/subscription.ts`.
14875
14964
  */
14876
14965
  function createConversationSubscriptionTools(context) {
14877
- if (context.agentInvocationId) return {};
14966
+ if (!context.turnTools.subscriptions) return {};
14878
14967
  return { setConversationSubscription: zodTool({
14879
14968
  exposure: "deferred",
14880
14969
  source: CONVERSATION_SUBSCRIPTION_TOOL_SOURCE,
@@ -15471,8 +15560,7 @@ async function searchConversationBriefs(db, args) {
15471
15560
  const outcomeStatus = sql`${briefs.content}->'outcome'->>'status'`;
15472
15561
  const conditions = [
15473
15562
  notExists(db.select({ one: sql`1` }).from(newer).where(and(eq(newer.conversationId, briefs.conversationId), gt(newer.version, briefs.version)))),
15474
- isNull(juniorConversations.parentConversationId),
15475
- isNull(juniorConversations.quickQuestionAt),
15563
+ listedConversation(),
15476
15564
  ne(juniorConversations.conversationId, args.currentConversationId),
15477
15565
  eq(juniorDestinations.visibility, "public")
15478
15566
  ];
@@ -16439,6 +16527,7 @@ function createToolState() {
16439
16527
  */
16440
16528
  function createTools(availableSkills, hooks = {}, context, options = {}) {
16441
16529
  const state = createToolState();
16530
+ const turnTools = context.turnTools;
16442
16531
  const slackContext = getSlackToolContext(context);
16443
16532
  const slackLocationCapabilities = slackContext ? resolveChannelCapabilities(slackContext.locationChannelId) : void 0;
16444
16533
  const canSendFilesToActiveConversation = Boolean(slackContext ? slackLocationCapabilities?.canSendFiles : context.attachmentStorage);
@@ -16459,7 +16548,7 @@ function createTools(availableSkills, hooks = {}, context, options = {}) {
16459
16548
  webSearch: createWebSearchTool(botConfig.webSearchModelId, hooks.toolOverrides?.webSearch),
16460
16549
  webFetch: createWebFetchTool(hooks, { canSendFilesToActiveConversation }),
16461
16550
  ...createEventTools(context, eventCatalog),
16462
- ...createAutomationTools(context, eventCatalog),
16551
+ ...createAutomationTools(context, eventCatalog, options.automationSkills ?? []),
16463
16552
  ...createWorkspaceTools(context),
16464
16553
  ...createOperatorTools(context),
16465
16554
  ...createUserCustomizationTools(context),
@@ -16510,9 +16599,9 @@ function createTools(availableSkills, hooks = {}, context, options = {}) {
16510
16599
  parentConversationId: context.parentConversationId
16511
16600
  });
16512
16601
  if (context.messageAgent) tools.messageAgent = createMessageAgentTool(context.messageAgent);
16513
- if (context.agentInvocationId) tools[REPORT_BLOCKED_TOOL_NAME] = createReportBlockedTool();
16602
+ if (turnTools.reportBlocked) tools[REPORT_BLOCKED_TOOL_NAME] = createReportBlockedTool();
16514
16603
  if (context.automation) tools[FINISH_AUTOMATION_RUN_TOOL_NAME] = createFinishAutomationRunTool(context.automation);
16515
- else tools[NO_REPLY_TOOL_NAME] = createNoReplyTool();
16604
+ if (turnTools.noReply) tools[NO_REPLY_TOOL_NAME] = createNoReplyTool();
16516
16605
  if (context.mcpToolManager) {
16517
16606
  tools.searchMcpTools = createSearchMcpToolsTool(context.mcpToolManager);
16518
16607
  tools.callMcpTool = createCallMcpToolTool(context.mcpToolManager);
@@ -16551,7 +16640,7 @@ function createTools(availableSkills, hooks = {}, context, options = {}) {
16551
16640
  addReviewItem: createAddReviewItemTool(context, reviewItemServices),
16552
16641
  searchReviewItems: createSearchReviewItemsTool(context, reviewItemServices),
16553
16642
  updateReviewItem: createUpdateReviewItemTool(context, reviewItemServices)
16554
- }, context.agentInvocationId ? `A child agent cannot use the review desk. Use ${REPORT_BLOCKED_TOOL_NAME} to tell the parent agent what needs a person.` : void 0));
16643
+ }, !turnTools.reviewDesk ? `A child agent cannot use the review desk. Use ${REPORT_BLOCKED_TOOL_NAME} to tell the parent agent what needs a person.` : void 0));
16555
16644
  for (const [name, pluginTool] of Object.entries(getPluginTools(context, options.pluginSandbox))) {
16556
16645
  if (tools[name]) throw new Error(`Plugin tool "${name}" conflicts with a core tool`);
16557
16646
  tools[name] = pluginTool;
@@ -19921,7 +20010,7 @@ async function wireAgentTools(args) {
19921
20010
  const commonToolRuntimeContext = {
19922
20011
  conversationId: args.run.conversationId,
19923
20012
  turnId: args.run.turnId,
19924
- ...args.run.agentInvocationId ? { agentInvocationId: args.run.agentInvocationId } : void 0,
20013
+ turnTools: args.behavior.tools,
19925
20014
  ...args.run.parentConversationId ? { parentConversationId: args.run.parentConversationId } : void 0,
19926
20015
  ...args.run.location ? {
19927
20016
  location: args.run.location,
@@ -19948,9 +20037,8 @@ async function wireAgentTools(args) {
19948
20037
  supportsImageInput: args.supportsImageInput,
19949
20038
  surface: args.surface,
19950
20039
  ...args.currentActor ? { resolveActorIdentity: async () => await readActorIdentity(args.currentActor) } : void 0,
19951
- ...args.durability.spawnAgent ? { spawnAgent: args.durability.spawnAgent } : void 0,
19952
- ...args.durability.messageAgent ? { messageAgent: args.durability.messageAgent } : void 0,
19953
- ...args.run.dispatch?.declaresResult ? { automation: { sendsMessage: args.run.dispatch.outcomes?.length !== 0 } } : void 0
20040
+ ...bindAgentTools(args.run, args.behavior.tools.agents),
20041
+ ...args.behavior.tools.finishAutomationRun ? { automation: { sendsMessage: args.run.dispatch?.outcomes?.length !== 0 } } : void 0
19954
20042
  };
19955
20043
  const toolRoute = resolveToolRuntimeRoute({
19956
20044
  actor: args.currentActor,
@@ -20009,7 +20097,10 @@ async function wireAgentTools(args) {
20009
20097
  upsertActiveSkill(args.activeSkills, effective);
20010
20098
  await tryRecordSkillLoadStat(effective);
20011
20099
  }
20012
- }, toolRuntimeContext, { pluginSandbox: createPluginToolSandbox(agentSandbox, { handleAuthSignal: pluginAuth.maybeHandleAuthSignal }) });
20100
+ }, toolRuntimeContext, {
20101
+ automationSkills: args.availableSkills,
20102
+ pluginSandbox: createPluginToolSandbox(agentSandbox, { handleAuthSignal: pluginAuth.maybeHandleAuthSignal })
20103
+ });
20013
20104
  const plannedToolExposure = planToolExposure(tools);
20014
20105
  const disabledTools = Object.entries(tools).flatMap(([name, definition]) => definition.disabledReason ? [{
20015
20106
  name,
@@ -20093,6 +20184,17 @@ async function wireAgentTools(args) {
20093
20184
  toolRuntimeContext
20094
20185
  };
20095
20186
  }
20187
+ /** Bind the agent tools that the Turn's behavior gives it. */
20188
+ function bindAgentTools(run, agents) {
20189
+ const { bindSpawnAgent, bindMessageAgent } = run.environment ?? {};
20190
+ if (agents === "none" || !bindSpawnAgent) return {};
20191
+ const spawnAgent = isAgentRunFeatureDisabled(run.disabledFeatures, "subagents") ? void 0 : bindSpawnAgent(run);
20192
+ const messageAgent = spawnAgent || agents === "children_and_parent" ? bindMessageAgent?.(run, agents) : void 0;
20193
+ return {
20194
+ ...spawnAgent ? { spawnAgent } : void 0,
20195
+ ...messageAgent ? { messageAgent } : void 0
20196
+ };
20197
+ }
20096
20198
  // src/chat/agent/resume.ts
20097
20199
  function extractSliceUsage(messages, beforeMessageCount) {
20098
20200
  const usage = extractGenAiUsageSummary(...messages.slice(beforeMessageCount).filter(isAssistantMessage));
@@ -21539,20 +21641,35 @@ function exclusiveToolName(toolCalls) {
21539
21641
  for (const name of EXCLUSIVE_TOOL_NAMES) if (toolCalls.some((call) => call.name === name)) return name;
21540
21642
  }
21541
21643
  // src/chat/agent/tool-batch.ts
21644
+ /** Start the batch counts for one Run. */
21645
+ function createToolBatchStats() {
21646
+ return {
21647
+ count: 0,
21648
+ sequentialCount: 0,
21649
+ sequentialCallCount: 0,
21650
+ sequentialToolNames: /* @__PURE__ */ new Set()
21651
+ };
21652
+ }
21542
21653
  /**
21543
- * Record how Pi runs the tool calls of one assistant message. Pi runs them
21544
- * in parallel unless one of their tools is `sequential`; then it runs all of
21545
- * them one at a time.
21654
+ * Count one batch of tool calls. Pi runs them in parallel unless one of their
21655
+ * tools is `sequential`; then it runs all of them one at a time.
21546
21656
  */
21547
- function logToolBatch(toolCalls, tools) {
21548
- const names = toolCalls.map((call) => call.name);
21549
- const sequentialTools = [...new Set(names)].filter((name) => tools.find((tool) => tool.name === name)?.executionMode === "sequential").sort();
21550
- logInfo("agent.tool_batch.started", {
21551
- "app.tool_batch.size": toolCalls.length,
21552
- "app.tool_batch.execution": sequentialTools.length > 0 ? "sequential" : "parallel",
21553
- "app.tool_batch.tool_names": names,
21554
- "app.tool_batch.sequential_tool_names": sequentialTools
21555
- });
21657
+ function recordToolBatch(stats, toolCalls, tools) {
21658
+ const sequentialTools = toolCalls.map((call) => call.name).filter((name) => tools.find((tool) => tool.name === name)?.executionMode === "sequential");
21659
+ stats.count += 1;
21660
+ if (sequentialTools.length === 0) return;
21661
+ stats.sequentialCount += 1;
21662
+ stats.sequentialCallCount += toolCalls.length;
21663
+ for (const name of sequentialTools) stats.sequentialToolNames.add(name);
21664
+ }
21665
+ /** Span attributes for the batch counts of one Run. */
21666
+ function toolBatchSpanAttributes(stats) {
21667
+ return {
21668
+ "app.tool_batch.count": stats.count,
21669
+ "app.tool_batch.sequential_count": stats.sequentialCount,
21670
+ "app.tool_batch.sequential_call_count": stats.sequentialCallCount,
21671
+ "app.tool_batch.sequential_tool_names": [...stats.sequentialToolNames].sort().join(",")
21672
+ };
21556
21673
  }
21557
21674
  // src/chat/agent/index.ts
21558
21675
  /**
@@ -21611,6 +21728,7 @@ function waitForAbortSettlement(promise, timeoutMs) {
21611
21728
  async function executeAgentRun(run, streamFn) {
21612
21729
  if (!run.destination) throw new TypeError("Assistant reply generation requires a destination");
21613
21730
  const conversation = await getConversationStore().get({ conversationId: run.conversationId });
21731
+ if (!conversation && run.parentConversationId) throw new Error(`Child Conversation ${run.conversationId} has no Conversation row`);
21614
21732
  const visibility = conversation?.visibility;
21615
21733
  const conversationPrivacy = resolveConversationPrivacy({ visibility });
21616
21734
  const actor = actorFromRun(run);
@@ -21623,12 +21741,17 @@ async function executeAgentRun(run, streamFn) {
21623
21741
  runId: run.runId,
21624
21742
  assistantUserName: botConfig.userName
21625
21743
  };
21626
- return withLogContext(runLogContext, () => runWithConversationPrivacy(conversationPrivacy, () => executeAgentRunInPrivacyContext(run, conversation?.kind, conversationPrivacy, runLogContext, streamFn)));
21744
+ return withLogContext(runLogContext, () => runWithConversationPrivacy(conversationPrivacy, () => executeAgentRunInPrivacyContext(run, conversation?.kind ?? "root", conversationPrivacy, runLogContext, streamFn)));
21627
21745
  }
21628
21746
  async function executeAgentRunInPrivacyContext(run, conversationKind, conversationPrivacy, runLogContext, streamFn) {
21629
21747
  const conversationId = run.conversationId;
21630
21748
  const turnId = run.turnId;
21631
- const requireAutomationResult = run.dispatch?.declaresResult === true;
21749
+ const behavior = turnBehavior({
21750
+ kind: conversationKind,
21751
+ personInput: isPersonInput(run.source.kind),
21752
+ automationRun: run.dispatch?.declaresResult === true
21753
+ });
21754
+ const requireAutomationResult = behavior.gated;
21632
21755
  const input = {
21633
21756
  actor: run.instruction.actor,
21634
21757
  messageText: run.instruction.text,
@@ -21749,8 +21872,10 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
21749
21872
  "messaging.message.id": slackSource?.messageTs ?? ""
21750
21873
  });
21751
21874
  }
21752
- const skillInvocation = parseSkillInvocation(userInput, availableSkills);
21875
+ const dispatchSkill = run.dispatch?.skill;
21876
+ const skillInvocation = dispatchSkill ? { skillName: dispatchSkill } : parseSkillInvocation(userInput, availableSkills);
21753
21877
  const invokedSkill = skillInvocation ? findSkillByName(skillInvocation.skillName, availableSkills) : null;
21878
+ if (dispatchSkill && !invokedSkill) throw new Error(missingAutomationSkillReason(dispatchSkill));
21754
21879
  const activeSkills = [];
21755
21880
  const skillSandbox = new SkillSandbox(availableSkills, activeSkills);
21756
21881
  const checkpoint = await loadTurnCheckpoint({
@@ -21876,6 +22001,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
21876
22001
  const wiring = await wireAgentTools({
21877
22002
  abortAgent: () => agent?.abort(),
21878
22003
  activeSkills,
22004
+ behavior,
21879
22005
  currentActor: actor,
21880
22006
  currentAgentMessages,
21881
22007
  currentTurnMessages,
@@ -21924,6 +22050,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
21924
22050
  const getPendingAuthPause = wiring.getPendingAuthPause;
21925
22051
  const { baseInstructions: assembledBaseInstructions, contextContentParts: promptContextContentParts, inputMessages, inputMessagesAttribute, promptTimestamp: restoredPromptTimestamp, promptHistoryMessages, shouldPromptAgent, turnContexts, userContentParts: promptUserContentParts } = await assemblePrompt({
21926
22052
  activeMcpCatalogs: wiring.activeMcpCatalogs,
22053
+ promptMode: behavior.promptMode,
21927
22054
  currentActor: actor,
21928
22055
  availableSkills,
21929
22056
  configurationValues,
@@ -22073,6 +22200,8 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
22073
22200
  return acceptedMessages;
22074
22201
  };
22075
22202
  const cacheWarming = createCacheWarmingRecorder(conversationId, isUserActor(actor) && conversationKind !== "task");
22203
+ const toolBatchStats = createToolBatchStats();
22204
+ let setAgentSpanAttributes;
22076
22205
  agent = new Agent({
22077
22206
  getApiKey: getGatewayApiKey,
22078
22207
  sessionId: conversationId,
@@ -22083,7 +22212,10 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
22083
22212
  steeringMode: "all",
22084
22213
  beforeToolCall: async ({ assistantMessage, context, toolCall }) => {
22085
22214
  const toolCalls = assistantMessage.content.filter((part) => part.type === "toolCall");
22086
- if (toolCalls.length > 1 && toolCall.id === toolCalls[0].id) logToolBatch(toolCalls, context.tools ?? []);
22215
+ if (toolCalls.length > 1 && toolCall.id === toolCalls[0].id) {
22216
+ recordToolBatch(toolBatchStats, toolCalls, context.tools ?? []);
22217
+ setAgentSpanAttributes?.(toolBatchSpanAttributes(toolBatchStats));
22218
+ }
22087
22219
  const exclusiveTool = exclusiveToolName(toolCalls);
22088
22220
  if (exclusiveTool && toolCalls.length !== 1) return {
22089
22221
  block: true,
@@ -22184,7 +22316,8 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
22184
22316
  } else if (promptHistoryMessages.length > 0) agent.state.messages = [...promptHistoryMessages];
22185
22317
  runResume.setBeforeMessageCount(agent.state.messages.length);
22186
22318
  if (shouldPromptAgent) runResume.setTurnStartMessageIndex(agent.state.messages.length);
22187
- const authPauseOutcome = await withSpan(`invoke_agent ${botConfig.userName}`, "gen_ai.invoke_agent", spanContext, async () => {
22319
+ const authPauseOutcome = await withSpan(`invoke_agent ${botConfig.userName}`, "gen_ai.invoke_agent", spanContext, async (setInvokeAgentSpanAttributes) => {
22320
+ setAgentSpanAttributes = setInvokeAgentSpanAttributes;
22188
22321
  if (requireAutomationResult && readAutomationResult(agent.state.messages)) return;
22189
22322
  const promptTimestamp = restoredPromptTimestamp ?? Date.now();
22190
22323
  const contextMessage = shouldPromptAgent && promptContextContentParts.length > 0 ? {
@@ -22487,8 +22620,6 @@ function createAgentRunner(execute, options) {
22487
22620
  const bindSpawnAgent = options?.bindSpawnAgent;
22488
22621
  const bindMessageAgent = options?.bindMessageAgent;
22489
22622
  return { run: async (run) => {
22490
- const spawnAgent = bindSpawnAgent && !isAgentRunFeatureDisabled(run.disabledFeatures, "subagents") ? bindSpawnAgent(run) : void 0;
22491
- const messageAgent = bindMessageAgent && bindSpawnAgent && (spawnAgent || run.agentInvocationId) ? bindMessageAgent(run) : void 0;
22492
22623
  const nextRun = {
22493
22624
  ...run,
22494
22625
  environment: {
@@ -22496,13 +22627,10 @@ function createAgentRunner(execute, options) {
22496
22627
  attachmentStorage: run.environment?.attachmentStorage ?? attachmentStorage,
22497
22628
  backgroundCompactionQueue: run.environment?.backgroundCompactionQueue ?? backgroundCompactionQueue,
22498
22629
  conversationWorkQueue: run.environment?.conversationWorkQueue ?? conversationWorkQueue,
22499
- sandboxTracePropagation: run.environment?.sandboxTracePropagation ?? tracePropagation
22500
- },
22501
- ...spawnAgent || messageAgent ? { durability: {
22502
- ...run.durability,
22503
- ...spawnAgent ? { spawnAgent } : void 0,
22504
- ...messageAgent ? { messageAgent } : void 0
22505
- } } : void 0
22630
+ sandboxTracePropagation: run.environment?.sandboxTracePropagation ?? tracePropagation,
22631
+ ...bindSpawnAgent ? { bindSpawnAgent } : void 0,
22632
+ ...bindSpawnAgent && bindMessageAgent ? { bindMessageAgent } : void 0
22633
+ }
22506
22634
  };
22507
22635
  const loadStoredImages = async (attachments) => {
22508
22636
  const { loadInputImages } = await Promise.resolve().then(() => images_exports);
@@ -22529,4 +22657,4 @@ function createAgentRunner(execute, options) {
22529
22657
  return await execute(nextRun, streamFn);
22530
22658
  } };
22531
22659
  }
22532
- export { readViewerAutomationSummary as $, resumeConversationDelivery as $t, runWithSlackInstallation as A, cancelSignInWait as At, listThreadReplies as B, canShareTurn as Bt, readSlackReviewItemCardConversationId as C, emptyResponse as Ct, parseSlackReviewItemClick as D, stopChildAgentsOf as Dt, buildSlackReviewItemModal as E, stopChildAgentsBelow as Et, resolveSlackChannelIdFromThreadId as F, getPausedTurnRequest as Ft, changeViewerAutomationLifecycle as G, finishTurn as Gt, logScheduledAutomationRunSkipped as H, selectAttemptMessages as Ht, checkSlackChannelReadAccess as I, wakeAuthorizedTurn as It, updateViewerAutomation as J, withTurnSpan as Jt, deleteViewerTask as K, getTurnInputSpanAttributes as Kt, joinPublicChannelForRead as L, wakePausedTurn as Lt, parseSlackThreadId as M, supersedeOpenMailboxTurns as Mt, readSlackRawMessageContext as N, supersedeTurnForInput as Nt, parseSlackReviewItemFormTarget as O, recordSubagentEnded as Ot, resolveSlackChannelIdFromMessage as P, createPausedTurns as Pt, readViewerAutomationRuns as Q, pauseConversationDelivery as Qt, getConversationInfo as R, getTurnAuthorization as Rt, createSlackReviewItemShow as S, markConversationRead as St, SLACK_REVIEW_ITEM_VIEW_ID as T, throwApiError as Tt, scheduledAutomationRunAttributes as U, AgentRunError as Ut, resolveDestinationVisibility as V, isAttemptInterrupt as Vt, activateViewerAutomationVersion as W, executeTurn as Wt, readConversationSourceTask as X, getWebAuthorization as Xt, ViewerTaskNotFoundError as Y, deleteWebAuthorization as Yt, readViewerAutomationExecutions as Z, canPauseConversationDelivery as Zt, unpublishedArtifactHeaders as _, readLiveAttachment as _t, finalizeMcpAuthorization as a, AgentNameInUseError as an, deliverReviewItemChange as at, renderAttachmentText as b, archiveConversation as bt, deleteMcpServerSessionId as c, processWorkspaceSnapshotJob as cn, acceptsWebMessages as ct, getMcpStoredOAuthCredentials as d, actorFromRun as dn, createAndEnqueueConversation as dt, AgentDepthLimitError as en, readViewerAutomationVersions as et, putMcpStoredOAuthCredentials as f, toolInvocationDestination as fn, createConversationId as ft, readPublicArtifact as g, collectAttachmentGarbage as gt, publicArtifactHeaders as h, decodeInputImages as ht, buildAuthPauseResponse as i, AgentMessageTargetError as in, listOwnedWatches as it, verifySlackSignature as j, createConversationTurnWorker as jt, parseSlackUserInputSubmission as k, recordSubagentStarted as kt, deleteMcpStoredOAuthCredentials as l, ingestEvent as ln, appendAndEnqueueWebMessage as lt, readStats as m, webActorFromUser as mt, executeAgentRun as n, AgentMessagePausedError as nn, AutomationEditError as nt, deleteMcpAuthSession as o, listChildAgents as on, renderReviewItemMessage as ot, latestProgressStatus as p, shouldEmitDevAgentTrace as pn, recordWebConversationActivity as pt, readViewerAutomationEdit as q, turnInputTelemetry as qt, processBackgroundCompaction as r, AgentMessageQueueFullError as rn, effectiveTaskOutcomes as rt, deleteMcpAuthSessionsForUserProvider as s, listUnreportedSiblingAgents as sn, reviewItemChangeRecord as st, createAgentRunner as t, AgentInvocationLimitError as tn, readViewerAutomations as tt, getMcpAuthSession as u, RetryableDeliveryError as un, conversationTurnIdForMessage as ut, setConversationSubscription as v, requestAttachmentDeletion as vt, syncReviewItemSlackCards as w, jsonResponse as wt, renderBlockText as x, conversationReadPositionQuery as xt, lookupSlackUserProfile as y, storeAttachment as yt, joinPublicChannel as z, canJoinTurn as zt };
22660
+ export { readViewerAutomationSummary as $, resumeConversationDelivery as $t, runWithSlackInstallation as A, cancelSignInWait as At, listThreadReplies as B, canShareTurn as Bt, readSlackReviewItemCardConversationId as C, emptyResponse as Ct, parseSlackReviewItemClick as D, stopChildAgentsOf as Dt, buildSlackReviewItemModal as E, stopChildAgentsBelow as Et, resolveSlackChannelIdFromThreadId as F, getPausedTurnRequest as Ft, changeViewerAutomationLifecycle as G, finishTurn as Gt, logScheduledAutomationRunSkipped as H, selectAttemptMessages as Ht, checkSlackChannelReadAccess as I, wakeAuthorizedTurn as It, updateViewerAutomation as J, withTurnSpan as Jt, deleteViewerTask as K, getTurnInputSpanAttributes as Kt, joinPublicChannelForRead as L, wakePausedTurn as Lt, parseSlackThreadId as M, supersedeOpenMailboxTurns as Mt, readSlackRawMessageContext as N, supersedeTurnForInput as Nt, parseSlackReviewItemFormTarget as O, recordSubagentEnded as Ot, resolveSlackChannelIdFromMessage as P, createPausedTurns as Pt, readViewerAutomationRuns as Q, pauseConversationDelivery as Qt, getConversationInfo as R, getTurnAuthorization as Rt, createSlackReviewItemShow as S, markConversationRead as St, SLACK_REVIEW_ITEM_VIEW_ID as T, throwApiError as Tt, scheduledAutomationRunAttributes as U, AgentRunError as Ut, resolveDestinationVisibility as V, isAttemptInterrupt as Vt, activateViewerAutomationVersion as W, executeTurn as Wt, readConversationSourceTask as X, getWebAuthorization as Xt, ViewerTaskNotFoundError as Y, deleteWebAuthorization as Yt, readViewerAutomationExecutions as Z, canPauseConversationDelivery as Zt, unpublishedArtifactHeaders as _, readLiveAttachment as _t, finalizeMcpAuthorization as a, AgentNameInUseError as an, deliverReviewItemChange as at, renderAttachmentText as b, archiveConversation as bt, deleteMcpServerSessionId as c, listUnreportedSiblingAgents as cn, acceptsWebMessages as ct, getMcpStoredOAuthCredentials as d, findAutomationSkill as dn, createAndEnqueueConversation as dt, AgentDepthLimitError as en, readViewerAutomationVersions as et, putMcpStoredOAuthCredentials as f, missingAutomationSkillReason as fn, createConversationId as ft, readPublicArtifact as g, shouldEmitDevAgentTrace as gn, collectAttachmentGarbage as gt, publicArtifactHeaders as h, toolInvocationDestination as hn, decodeInputImages as ht, buildAuthPauseResponse as i, AgentMessageTargetError as in, listOwnedWatches as it, verifySlackSignature as j, createConversationTurnWorker as jt, parseSlackUserInputSubmission as k, recordSubagentStarted as kt, deleteMcpStoredOAuthCredentials as l, processWorkspaceSnapshotJob as ln, appendAndEnqueueWebMessage as lt, readStats as m, actorFromRun as mn, webActorFromUser as mt, executeAgentRun as n, AgentMessagePausedError as nn, AutomationEditError as nt, deleteMcpAuthSession as o, listedConversation as on, renderReviewItemMessage as ot, latestProgressStatus as p, RetryableDeliveryError as pn, recordWebConversationActivity as pt, readViewerAutomationEdit as q, turnInputTelemetry as qt, processBackgroundCompaction as r, AgentMessageQueueFullError as rn, effectiveTaskOutcomes as rt, deleteMcpAuthSessionsForUserProvider as s, listChildAgents as sn, reviewItemChangeRecord as st, createAgentRunner as t, AgentInvocationLimitError as tn, readViewerAutomations as tt, getMcpAuthSession as u, ingestEvent as un, conversationTurnIdForMessage as ut, setConversationSubscription as v, requestAttachmentDeletion as vt, syncReviewItemSlackCards as w, jsonResponse as wt, renderBlockText as x, conversationReadPositionQuery as xt, lookupSlackUserProfile as y, storeAttachment as yt, joinPublicChannel as z, canJoinTurn as zt };