@sentry/junior 0.247.0 → 0.248.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 (61) hide show
  1. package/dist/{admin-BGwaqDMs.js → admin-BlHz8fGl.js} +1 -1
  2. package/dist/{agent-hooks-C72ByH0C.js → agent-hooks-DWCHBPYw.js} +24 -11
  3. package/dist/{agent-runner-DsAFAKKs.js → agent-runner-CnlFtbzb.js} +224 -89
  4. package/dist/api/schema.d.ts +171 -3
  5. package/dist/api/schema.js +3 -3
  6. package/dist/api.js +218 -155
  7. package/dist/{app-4t4mPTdS.d.ts → app-B0gT1Slp.d.ts} +3 -1
  8. package/dist/app.d.ts +1 -1
  9. package/dist/app.js +27 -27
  10. package/dist/{assistant-reply-ChOzcTBS.js → assistant-reply-BxCi7V4v.js} +1 -1
  11. package/dist/{briefs-Dc7qZrhc.js → briefs-CdkIl79U.js} +4 -4
  12. package/dist/{catalog-runtime-DS1k7fUG.js → catalog-runtime-CTBsdSam.js} +1 -1
  13. package/dist/cli/chat.js +15 -15
  14. package/dist/cli/check.js +3 -3
  15. package/dist/cli/main.js +2 -2
  16. package/dist/cli/plugins.js +4 -4
  17. package/dist/cli/snapshot-create.js +3 -3
  18. package/dist/cli/upgrade.js +3 -3
  19. package/dist/{client-BVnfNd3D.js → client-CWQtbizj.js} +2 -2
  20. package/dist/{config-CgWvImQL.js → config-aitDvTQm.js} +16 -9
  21. package/dist/{conversation-CYsbVFLx.js → conversation-Cjo9tHGm.js} +15 -1
  22. package/dist/{conversation-privacy-D3TdVM9H.js → conversation-privacy-BsqXHVBz.js} +1 -1
  23. package/dist/{credential-sync-DLw3jkv-.js → credential-sync-DqZF735a.js} +14 -14
  24. package/dist/{executor-DQazjeGA.js → executor-oIZAkQZb.js} +2 -2
  25. package/dist/{images-C3e5E-p_.js → images-Dzh3RBXY.js} +3 -3
  26. package/dist/instrumentation.js +2 -2
  27. package/dist/{job-queue-BEUqRhjC.js → job-queue-DyA2AEnY.js} +1 -1
  28. package/dist/{logging-CZEc8_v4.js → logging-OpC2jwiV.js} +1 -1
  29. package/dist/{message-BIJa7lKh.js → message-EyMrVXEf.js} +3 -3
  30. package/dist/nitro.d.ts +1 -1
  31. package/dist/nitro.js +3 -3
  32. package/dist/{oauth-callback-server-R9OSdLP1.js → oauth-callback-server-ClDv9Z5Y.js} +2 -2
  33. package/dist/{pending-auth-Oo5AQhaf.js → pending-auth-D_nf121N.js} +2 -2
  34. package/dist/{profile-aVLDAirh.js → profile-Dfg76pvk.js} +4 -4
  35. package/dist/{prompt-ZG1UCxjF.js → prompt-C7bRJ2vg.js} +1 -1
  36. package/dist/{registry-CtaDOOM5.js → registry-fpIZHoqE.js} +1 -1
  37. package/dist/{resolve-Bdw4hu7s.js → resolve-LMCZhQVg.js} +2 -2
  38. package/dist/{result-DNgmkASh.js → result-C1ZCRPLx.js} +7 -7
  39. package/dist/{runner-BUSScEu5.js → runner-DNZMviFH.js} +10 -10
  40. package/dist/{sandbox-egress-signals-E9r8bf9G.js → sandbox-egress-signals-Dcc-mwkl.js} +1 -1
  41. package/dist/{schema-tyd6hALh.js → schema-BRZsYL5-.js} +4 -3
  42. package/dist/{session-stop-CAhBfBUT.js → session-stop-dyvsZDB0.js} +11 -11
  43. package/dist/{skills-DQy-mmBC.js → skills-BgGiQt5Y.js} +2 -2
  44. package/dist/{spawn-DQ_MVWZ6.js → spawn-CpqxMPWE.js} +2 -2
  45. package/dist/{store-DjLA8GKs.js → store-OMQAFrJG.js} +6 -6
  46. package/dist/{task-queue-BT2h_t8I.js → task-queue-SWsXPSp-.js} +3 -3
  47. package/dist/{task-runner-CiPepjIB.js → task-runner-BOxv7shv.js} +10 -10
  48. package/dist/{tasks-DMmRrIVl.js → tasks-DREdnhVP.js} +49 -16
  49. package/dist/{thread-state-ehZYGpX9.js → thread-state-BoNCtSwk.js} +6 -6
  50. package/dist/{turn-failure-response-D7J10z7l.js → turn-failure-response-C6jrCPjc.js} +8 -8
  51. package/dist/{turn-lifecycle-Buswqs90.js → turn-lifecycle-cQFsZFOU.js} +1 -1
  52. package/dist/{turn-session-routing-Bw-yiSb4.js → turn-session-routing-Ba12fwXz.js} +1 -1
  53. package/dist/{validation-DTguegIe.js → validation-Dmfh2cTj.js} +1 -1
  54. package/dist/{version-BrZSE5du.js → version-ByV7nGOn.js} +1 -1
  55. package/dist/version.js +1 -1
  56. package/dist/{viewer-BlAozHer.js → viewer-CX41TWYr.js} +3 -3
  57. package/dist/{web-authorization-DwyTlkAg.js → web-authorization-rDLlKIS0.js} +6 -6
  58. package/dist/{web-input-DSYxI7Wi.js → web-input-Bn9HHZEo.js} +28 -28
  59. package/dist/{work-CRBXkJoU.js → work-CvFoEpRT.js} +10 -10
  60. package/dist/{worker-BVJKM9Ja.js → worker-CI5B63vk.js} +5 -5
  61. package/package.json +4 -4
@@ -1,30 +1,30 @@
1
- import { b as getGatewayApiKey, c as hasCompactedConversationContext, d as unwrapCurrentInstruction, f as escapeXml, g as getProviderErrorAttributes, h as findProviderError, i as completeText, l as isCompactionSummaryText, m as createProviderError, n as GEN_AI_SERVER_ADDRESS, o as resolveGatewayModel, p as ProviderError, r as completeObject, s as COMPACTION_SUMMARY_PREFIX, t as GEN_AI_PROVIDER_NAME, u as renderCurrentInstruction, v as isProviderRetryError, x as resolveGatewayCredential, y as MISSING_GATEWAY_CREDENTIALS_ERROR } from "./client-BVnfNd3D.js";
2
- import { C as withLogContext, F as normalizeIdentityEmail, I as isRecord$3, R as toOptionalString, a as extractGenAiUsageSummary, b as setTags, c as getLogContextAttributesForSpan, d as logException, f as logInfo, g as serializeGenAiAttribute, i as extractGenAiUsageAttributes, l as getTracePropagationHeaders, m as normalizeGenAiFinishReason, p as logWarn, u as logError, v as setSpanAttributes, w as withSpan, x as summarizeMessageText, y as setSpanStatus } from "./logging-CZEc8_v4.js";
1
+ import { b as getGatewayApiKey, c as hasCompactedConversationContext, d as unwrapCurrentInstruction, f as escapeXml, g as getProviderErrorAttributes, h as findProviderError, i as completeText, l as isCompactionSummaryText, m as createProviderError, n as GEN_AI_SERVER_ADDRESS, o as resolveGatewayModel, p as ProviderError, r as completeObject, s as COMPACTION_SUMMARY_PREFIX, t as GEN_AI_PROVIDER_NAME, u as renderCurrentInstruction, v as isProviderRetryError, x as resolveGatewayCredential, y as MISSING_GATEWAY_CREDENTIALS_ERROR } from "./client-CWQtbizj.js";
2
+ import { C as withLogContext, F as normalizeIdentityEmail, I as isRecord$3, R as toOptionalString, a as extractGenAiUsageSummary, b as setTags, c as getLogContextAttributesForSpan, d as logException, f as logInfo, g as serializeGenAiAttribute, i as extractGenAiUsageAttributes, l as getTracePropagationHeaders, m as normalizeGenAiFinishReason, p as logWarn, u as logError, v as setSpanAttributes, w as withSpan, x as summarizeMessageText, y as setSpanStatus } from "./logging-OpC2jwiV.js";
3
3
  import { m as startInactiveSpan, v as withActiveSpan } from "./sentry-CgWZM_kV.js";
4
- import { a as toCanonicalInputMessage, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes, t as canExposeConversationPayload } from "./conversation-privacy-D3TdVM9H.js";
5
- import { n as botConfig, v as normalizeSlackEmojiName } from "./config-CgWvImQL.js";
4
+ import { a as toCanonicalInputMessage, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes, t as canExposeConversationPayload } from "./conversation-privacy-BsqXHVBz.js";
5
+ import { n as botConfig, v as normalizeSlackEmojiName } from "./config-aitDvTQm.js";
6
6
  import { a as formatModelProfiles, c as profileConfig, i as formatModelProfile, l as TURN_REASONING_LEVELS, n as ModelProfileNotConfiguredError, o as modelIdForProfile, s as modelProfileSchema } from "./model-profile-BwU8mqwD.js";
7
7
  import { a as isUserActor, d as parseSlackTeamId, f as parseSlackUserId, g as parseSlackMessageTs, l as parseSlackChannelId, u as parseSlackChannelReferenceId } from "./actor-BTtLaeWy.js";
8
- import { N as parseDestination, T as hasAgentTurnUsage, c as getConversationEventStore, d as getDb, f as getSqlExecutor, l as getConversationMessageSearchStore, r as readActorIdentity, u as getConversationStore, x as addAgentTurnUsage } from "./viewer-BlAozHer.js";
8
+ import { N as parseDestination, S as agentTurnCostUsd, T as hasAgentTurnUsage, c as getConversationEventStore, d as getDb, f as getSqlExecutor, l as getConversationMessageSearchStore, r as readActorIdentity, u as getConversationStore, x as addAgentTurnUsage } from "./viewer-CX41TWYr.js";
9
9
  import { a as juniorAgentInvocations, c as juniorIdentities, d as juniorDestinations, i as juniorAgentBindings, n as AGENT_INVOCATION_PARENT_MAILBOX_STATUSES, s as juniorConversations, t as AGENT_INVOCATION_MAILBOX_STATUSES } from "./agent-invocations-D_YoNnAn.js";
10
- import { C as juniorArtifacts, S as juniorAttachments, a as juniorSchedulerRuns, l as juniorStats, m as juniorConversationBriefs, y as juniorConversationAnnotations } from "./executor-DQazjeGA.js";
10
+ import { C as juniorArtifacts, S as juniorAttachments, a as juniorSchedulerRuns, l as juniorStats, m as juniorConversationBriefs, y as juniorConversationAnnotations } from "./executor-oIZAkQZb.js";
11
11
  import { d as instructionActors, f as instructionProvenanceFor, p as sameActorIdentity, t as KNOWN_CONVERSATION_EVENT_TYPES, u as contextProvenance } from "./history-Nte1oVed.js";
12
12
  import { a as listReferenceFiles, c as soulPathCandidates, l as worldPathCandidates } from "./package-discovery-BVvSnQBB.js";
13
- import { a as resolveAuthTokenPlaceholder, c as fetchWithBoundedOAuthErrorBodies, d as credentialContextForActor, f as credentialContextSchema, h as CredentialUnavailableError, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, m as credentialUserSubjectId, o as resolvePluginCommandEnv, s as OAuthProviderError } from "./registry-CtaDOOM5.js";
14
- import { n as pluginCatalogRuntime } from "./catalog-runtime-DS1k7fUG.js";
15
- import { a as parseSkillInvocation, i as parseSkillFile, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-DQy-mmBC.js";
16
- import { At as openConversationProjection, B as postSlackEphemeralMessage, Bt as recordTurnRoute, Et as loadLastModelProfile, F as slackMention, Ft as recordAuthorizationRequested, It as recordGuardianActionReviewed, J as saveTurnCheckpoint, Jt as fallbackShortTitle, K as continuableMessages, L as addReactionToMessage, Lt as recordMcpProviderConnected, M as formatSlackLink, Mt as recordAttachmentsDelivered, R as getSlackMessagePermalink, Tt as loadConversationProjection, U as uploadFilesToConversation, V as postSlackMessage, Yt as resolveTaskTitle, _t as retainRuntimeTurnContext, a as readScheduledAutomation, at as isTurnExecutionLimitExceededError, b as saveEventAutomation, bt as TURN_CONTEXT_TAG, cn as getAgentContextCompactionTriggerTokens, ct as getTerminalAssistantMessages, dn as piMessageFromHistoryItem, f as createEventAutomation, ft as isAssistantMessage, g as getEventAutomation, gt as normalizeToolNameFromResult, ht as isToolResultMessage, j as escapeSlackMrkdwnText, jt as recordAgentsInstructionsUpdated, k as automationRevision, kt as loadTurnRoute, ln as getAgentContextInputLimitTokens, lt as getUserMessageInstructionText, mt as isToolResultError, nt as TurnSliceLimitExceededError, o as saveScheduledAutomation, ot as extractAssistantText, p as deleteEventAutomation, pt as isContinuablePiBoundary, q as loadTurnCheckpoint, r as listScheduledAutomationsForTeam, rt as assertTurnToolCallLimit, sn as estimateTextTokens, st as getPiMessageRole, t as createScheduledAutomation, un as historyItemFromPiMessage, ut as hasRuntimeTurnContext, v as listEventAutomationsForTeam, vt as stripRuntimeTurnContext, wt as loadConnectedMcpProviders, x as setEventAutomationStatus, xt as ToolInputError, yt as trimTrailingAssistantMessages, z as openSlackDirectMessage, zt as recordToolExecutionStarted } from "./tasks-DMmRrIVl.js";
17
- import { A as getWorkspaceSnapshotBuilder, B as cancelWatch, Bt as isConversationScopedChannel, C as WorkspaceValidationError, D as setWorkspaceSnapshotBuild, E as setWorkspaceSnapshot, F as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, Ft as SlackActionError, G as findMatchingWatches, H as createTimerWatch, Ht as normalizeSlackConversationId, I as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, It as downloadPrivateSlackFile, K as listWatches, L as RESOURCE_WATCH_TOOL_SOURCE, Lt as getFilePermalink, M as workspaceRepoCheckoutPath, Mt as defaultTimezone, N as resolveChannelCapabilities, Nt as resolveUserTimezone, O as SANDBOX_RUNTIME, Ot as saveObjectAnnotations, P as getSlackToolContext, R as STOP_WATCHING_TOOL_NAME, S as updateWorkspace, T as loadSnapshotsForProfile, U as createWatch, Vt as isDmChannel$1, W as deliverWatch, Wt as withSlackRetries, _ as deleteWorkspace, b as listWorkspaces, c as getPluginTools, g as createWorkspace, it as getDashboardTaskLink, j as tryWorkspaceRepoCheckoutPath, k as deleteWorkspaceSnapshotBuilders, kt as createPluginAnnotations, l as getPluginUserPromptContributions, lt as createPluginLogger, nt as getDashboardConversationLink, r as createPluginHookRunner, s as getPluginSystemPromptContributions, u as getPlugins, v as getWorkspace, w as invalidateReadySnapshot, wt as matchSlackAttachments, y as getWorkspaceByName, z as cancelSubscriptions, zt as getSlackClient } from "./agent-hooks-C72ByH0C.js";
18
- import { B as briefOutcomeStatusSchema, I as detectImageMediaType, L as isVisionImageMediaType, V as conversationBriefSchema, q as removedCardSchema, z as briefLinkSchema } from "./conversation-CYsbVFLx.js";
19
- import { A as SANDBOX_DATA_ROOT, D as fenceLock, E as acquireActiveLock, F as sandboxSkillFile, I as sandboxSkillPathResolution, M as SANDBOX_SKILLS_ROOT, N as SANDBOX_WORKSPACE_ROOT, O as withLock, P as sandboxSkillDir, _ as workspaceSnapshotNotReadyUserMessage, a as isAbortError, b as buildNonInteractiveShellScript, c as isSandboxCommandStreamInterruptedError, d as isSnapshottingError, f as throwSandboxOperationError, g as isWorkspaceSnapshotNotReadyError, h as getWorkspaceSnapshotNotReadyError, i as ensureDockerDaemon, j as SANDBOX_REPOS_ROOT, k as sleep, l as isSandboxMissingError, m as WorkspaceSnapshotNotReadyError, n as hash, o as isAlreadyExistsError, p as wrapSandboxSetupError, r as isStale, s as isSandboxApiTransientError, t as create, u as isSandboxUnavailableError, v as getVercelSandboxCredentials, w as getStateAdapter, x as runNonInteractiveCommand, y as buildCommandScript } from "./profile-aVLDAirh.js";
20
- import { n as canReusePendingAuthLink, t as abandonReplacedPendingAuth } from "./pending-auth-Oo5AQhaf.js";
13
+ import { a as resolveAuthTokenPlaceholder, c as fetchWithBoundedOAuthErrorBodies, d as credentialContextForActor, f as credentialContextSchema, h as CredentialUnavailableError, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, m as credentialUserSubjectId, o as resolvePluginCommandEnv, s as OAuthProviderError } from "./registry-fpIZHoqE.js";
14
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-CTBsdSam.js";
15
+ import { a as parseSkillInvocation, i as parseSkillFile, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-BgGiQt5Y.js";
16
+ import { B as postSlackEphemeralMessage, Bt as recordMcpProviderConnected, Ct as TURN_CONTEXT_TAG, Dt as loadConnectedMcpProviders, F as slackMention, Ft as recordAttachmentsDelivered, Ht as recordToolExecutionStarted, J as saveTurnCheckpoint, K as continuableMessages, L as addReactionToMessage, M as formatSlackLink, Mt as loadTurnRoute, Nt as openConversationProjection, Ot as loadConversationProjection, Pt as recordAgentsInstructionsUpdated, Qt as resolveTaskTitle, R as getSlackMessagePermalink, Rt as recordAuthorizationRequested, St as trimTrailingAssistantMessages, U as uploadFilesToConversation, Ut as recordTurnRoute, V as postSlackMessage, Zt as fallbackShortTitle, _t as isToolResultError, a as readScheduledAutomation, at as TurnToolCallLimitExceededError, b as saveEventAutomation, bt as retainRuntimeTurnContext, ct as isTurnExecutionLimitExceededError, dn as getAgentContextCompactionTriggerTokens, dt as getTerminalAssistantMessages, f as createEventAutomation, fn as getAgentContextInputLimitTokens, ft as getUserMessageInstructionText, g as getEventAutomation, gt as isContinuablePiBoundary, ht as isAssistantMessage, it as TurnSliceLimitExceededError, j as escapeSlackMrkdwnText, k as automationRevision, kt as loadLastModelProfile, lt as extractAssistantText, mn as piMessageFromHistoryItem, nt as TURN_LIMIT_DISABLED_REASON, o as saveScheduledAutomation, p as deleteEventAutomation, pn as historyItemFromPiMessage, pt as hasRuntimeTurnContext, q as loadTurnCheckpoint, r as listScheduledAutomationsForTeam, rt as TurnBudgetExceededError, st as createTurnLimitGate, t as createScheduledAutomation, un as estimateTextTokens, ut as getPiMessageRole, v as listEventAutomationsForTeam, vt as isToolResultMessage, wt as ToolInputError, x as setEventAutomationStatus, xt as stripRuntimeTurnContext, yt as normalizeToolNameFromResult, z as openSlackDirectMessage, zt as recordGuardianActionReviewed } from "./tasks-DREdnhVP.js";
17
+ import { A as getWorkspaceSnapshotBuilder, At as saveObjectAnnotations, B as STOP_WATCHING_TOOL_NAME, C as WorkspaceValidationError, D as setWorkspaceSnapshotBuild, E as setWorkspaceSnapshot, Et as matchSlackAttachments, F as isSlackMessageTurn, Ft as resolveUserTimezone, G as createWatch, H as cancelWatch, Ht as isConversationScopedChannel, I as slackMessageTurnDisabledReason, J as listWatches, K as deliverWatch, Kt as withSlackRetries, L as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, Lt as SlackActionError, M as workspaceRepoCheckoutPath, N as resolveChannelCapabilities, O as SANDBOX_RUNTIME, P as getSlackToolContext, Pt as defaultTimezone, R as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, Rt as downloadPrivateSlackFile, S as updateWorkspace, T as loadSnapshotsForProfile, Ut as isDmChannel$1, V as cancelSubscriptions, Vt as getSlackClient, W as createTimerWatch, Wt as normalizeSlackConversationId, _ as deleteWorkspace, b as listWorkspaces, c as getPluginTools, dt as createPluginLogger, g as createWorkspace, it as getDashboardConversationLink, j as tryWorkspaceRepoCheckoutPath, jt as createPluginAnnotations, k as deleteWorkspaceSnapshotBuilders, l as getPluginUserPromptContributions, ot as getDashboardTaskLink, q as findMatchingWatches, r as createPluginHookRunner, s as getPluginSystemPromptContributions, u as getPlugins, v as getWorkspace, w as invalidateReadySnapshot, y as getWorkspaceByName, z as RESOURCE_WATCH_TOOL_SOURCE, zt as getFilePermalink } from "./agent-hooks-DWCHBPYw.js";
18
+ import { B as briefLinkSchema, H as conversationBriefSchema, J as removedCardSchema, L as detectImageMediaType, R as isVisionImageMediaType, V as briefOutcomeStatusSchema } from "./conversation-Cjo9tHGm.js";
19
+ import { A as SANDBOX_DATA_ROOT, D as fenceLock, E as acquireActiveLock, F as sandboxSkillFile, I as sandboxSkillPathResolution, M as SANDBOX_SKILLS_ROOT, N as SANDBOX_WORKSPACE_ROOT, O as withLock, P as sandboxSkillDir, _ as workspaceSnapshotNotReadyUserMessage, a as isAbortError, b as buildNonInteractiveShellScript, c as isSandboxCommandStreamInterruptedError, d as isSnapshottingError, f as throwSandboxOperationError, g as isWorkspaceSnapshotNotReadyError, h as getWorkspaceSnapshotNotReadyError, i as ensureDockerDaemon, j as SANDBOX_REPOS_ROOT, k as sleep, l as isSandboxMissingError, m as WorkspaceSnapshotNotReadyError, n as hash, o as isAlreadyExistsError, p as wrapSandboxSetupError, r as isStale, s as isSandboxApiTransientError, t as create, u as isSandboxUnavailableError, v as getVercelSandboxCredentials, w as getStateAdapter, x as runNonInteractiveCommand, y as buildCommandScript } from "./profile-Dfg76pvk.js";
20
+ import { n as canReusePendingAuthLink, t as abandonReplacedPendingAuth } from "./pending-auth-D_nf121N.js";
21
21
  import { c as isTurnInputCommitLostError, i as TurnInputCommitLostError, r as CooperativeTurnYieldError, t as authorizationId } from "./oauth-authorization-BA4Dt6a7.js";
22
- import { a as isNoReplyMarker, i as NO_REPLY_MARKER, n as getAssistantReplyText, r as sanitizeAssistantText, t as decideReply } from "./assistant-reply-ChOzcTBS.js";
23
- import { C as registeredEventMatchSchema, D as requireSupportedEventMatch, E as requireEventIdentifier, I as readAutomationResult, L as remindMissingAutomationResult, M as FINISH_AUTOMATION_RUN_TOOL_NAME, N as automationResultSchema, S as pluginSupportsEvent, T as registeredResourceTypeSchema, _ as workspaceSnapshotWatch, b as eventNamespaceSchema, d as requireSlackChannelMessageScope, g as workspaceSnapshotFinishedEvent, h as WORKSPACE_SNAPSHOT_READY_EVENT, l as getEventCatalog, m as WORKSPACE_SNAPSHOT_FAILED_EVENT, n as markConversationsStopped, o as enqueueEventNotification, t as getConversationStoppedAtMs, v as automationEventCatalog, w as registeredEventTypeSchema, x as hasEventCatalogEntries } from "./session-stop-CAhBfBUT.js";
22
+ import { a as isNoReplyMarker, i as NO_REPLY_MARKER, n as getAssistantReplyText, r as sanitizeAssistantText, t as decideReply } from "./assistant-reply-BxCi7V4v.js";
23
+ import { C as registeredEventMatchSchema, D as requireSupportedEventMatch, E as requireEventIdentifier, I as readAutomationResult, L as remindMissingAutomationResult, M as FINISH_AUTOMATION_RUN_TOOL_NAME, N as automationResultSchema, S as pluginSupportsEvent, T as registeredResourceTypeSchema, _ as workspaceSnapshotWatch, b as eventNamespaceSchema, d as requireSlackChannelMessageScope, g as workspaceSnapshotFinishedEvent, h as WORKSPACE_SNAPSHOT_READY_EVENT, l as getEventCatalog, m as WORKSPACE_SNAPSHOT_FAILED_EVENT, n as markConversationsStopped, o as enqueueEventNotification, t as getConversationStoppedAtMs, v as automationEventCatalog, w as registeredEventTypeSchema, x as hasEventCatalogEntries } from "./session-stop-dyvsZDB0.js";
24
24
  import { i as isValidTimeZone, r as getZonedDateTimeParts } from "./cadence-D00SCzT1.js";
25
- import { a as createSandboxSession, c as postinstall, d as getSandboxResources, i as bindSandboxFileSystem, l as setSnapshotSpanAttributes, n as isMissingError, o as stopSession, r as resolve$1, s as dependencies } from "./resolve-Bdw4hu7s.js";
26
- import { a as getVercelConversationWorkQueue, f as getTurnRequestDeadline, n as sendNextWorkspaceSnapshotJob, r as sendWorkspaceSnapshotJob } from "./job-queue-BEUqRhjC.js";
27
- import { E as stopConversationWork } from "./store-DjLA8GKs.js";
25
+ import { a as createSandboxSession, c as postinstall, d as getSandboxResources, i as bindSandboxFileSystem, l as setSnapshotSpanAttributes, n as isMissingError, o as stopSession, r as resolve$1, s as dependencies } from "./resolve-LMCZhQVg.js";
26
+ import { a as getVercelConversationWorkQueue, f as getTurnRequestDeadline, n as sendNextWorkspaceSnapshotJob, r as sendWorkspaceSnapshotJob } from "./job-queue-DyA2AEnY.js";
27
+ import { E as stopConversationWork } from "./store-OMQAFrJG.js";
28
28
  import { F as taskOutcomeInputSchema, M as compileScheduleIntent, N as scheduleIntentSchema, O as automationInstructionToolSchema, T as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, j as ScheduleIntentError, k as automationTitleSchema } from "./automation-gznOMaQ2.js";
29
29
  import { r as isExperimentalFeatureEnabled } from "./experimental-Qn9rKLgx.js";
30
30
  import { n as privateTraceResultAttributes } from "./private-trace-result-BLvBjy_e.js";
@@ -43,6 +43,7 @@ import { Agent, estimateContextTokens } from "@earendil-works/pi-agent-core";
43
43
  import fs from "node:fs/promises";
44
44
  import fs$1 from "node:fs";
45
45
  import { isRetryableAssistantError } from "@earendil-works/pi-ai";
46
+ import { Kind } from "@sinclair/typebox";
46
47
  import { Sandbox } from "@vercel/sandbox";
47
48
  import { Bash, defineCommand } from "just-bash";
48
49
  import { structuredPatch } from "diff";
@@ -55,7 +56,6 @@ import https from "node:https";
55
56
  import net from "node:net";
56
57
  import { NodeHtmlMarkdown } from "node-html-markdown";
57
58
  import { Value } from "@sinclair/typebox/value";
58
- import { Kind } from "@sinclair/typebox";
59
59
  import { SignJWT, importPKCS8 } from "jose";
60
60
  //#region src/chat/configuration/defaults.ts
61
61
  let installDefaults = {};
@@ -1345,6 +1345,29 @@ var AuthorizationFlowDisabledError = class extends Error {
1345
1345
  }
1346
1346
  };
1347
1347
  //#endregion
1348
+ //#region src/chat/tools/definition.ts
1349
+ /** Distinguish legacy TypeBox schemas from JSON Schema projected from Zod. */
1350
+ function isTypeBoxInputSchema(schema) {
1351
+ return typeof schema === "object" && schema !== null && Kind in schema;
1352
+ }
1353
+ /** Tool error text for a call to a tool that is disabled in this Turn. */
1354
+ function disabledToolMessage(toolName, reason) {
1355
+ return `${toolName} is disabled in this Turn. ${reason} Do not call it again in this Turn.`;
1356
+ }
1357
+ /**
1358
+ * Disable tools for this Turn without removing them from the tool list.
1359
+ *
1360
+ * The tool adapter rejects their calls, and the Turn context lists them. An
1361
+ * unset reason keeps the tools enabled.
1362
+ */
1363
+ function disableTools(tools, reason) {
1364
+ if (!reason) return tools;
1365
+ return Object.fromEntries(Object.entries(tools).map(([name, tool]) => [name, {
1366
+ ...tool,
1367
+ disabledReason: reason
1368
+ }]));
1369
+ }
1370
+ //#endregion
1348
1371
  //#region src/chat/agent/types.ts
1349
1372
  /** Resume the agent turn after a transient or ambiguous delivery failure. */
1350
1373
  var RetryableDeliveryError = class extends Error {
@@ -1996,6 +2019,13 @@ function buildPluginPromptContributionsSection(contributions) {
1996
2019
  for (const contribution of contributions) lines.push(` <plugin-contribution plugin="${escapeXml(contribution.pluginName)}" id="${escapeXml(contribution.id)}">`, escapeXml(contribution.text.trim()), " </plugin-contribution>");
1997
2020
  return renderTagBlock("plugin-context", lines.join("\n"));
1998
2021
  }
2022
+ function buildDisabledToolsSection(tools) {
2023
+ if (!tools || tools.length === 0) return null;
2024
+ const namesByReason = /* @__PURE__ */ new Map();
2025
+ for (const tool of tools) namesByReason.set(tool.reason, [...namesByReason.get(tool.reason) ?? [], tool.name]);
2026
+ const lines = ["These tools are disabled in this Turn. Do not call them.", ...[...namesByReason].map(([reason, names]) => `- ${names.map((name) => `\`${name}\``).join(", ")}: ${reason}`)];
2027
+ return renderTagBlock("disabled-tools", escapeXml(lines.join("\n")));
2028
+ }
1999
2029
  /** Render plugin system prompt additions under a core-owned wrapper. */
2000
2030
  function buildPluginSystemPromptContributions(contributions) {
2001
2031
  if (contributions.length === 0) return null;
@@ -2035,7 +2065,8 @@ function buildSystemPrompt(platform, mode = "conversation") {
2035
2065
  function buildTurnContextPrompt(params) {
2036
2066
  const includeSessionContext = params.includeSessionContext ?? true;
2037
2067
  const pluginPromptContributions = buildPluginPromptContributionsSection(params.pluginPromptContributions);
2038
- if (!includeSessionContext && !pluginPromptContributions) return null;
2068
+ const disabledTools = buildDisabledToolsSection(params.disabledTools);
2069
+ if (!includeSessionContext && !pluginPromptContributions && !disabledTools) return null;
2039
2070
  const runtimeSections = [
2040
2071
  includeSessionContext ? buildCapabilitiesSection({
2041
2072
  availableSkills: params.availableSkills,
@@ -2043,6 +2074,7 @@ function buildTurnContextPrompt(params) {
2043
2074
  toolGuidance: params.toolGuidance ?? []
2044
2075
  }) : null,
2045
2076
  pluginPromptContributions,
2077
+ disabledTools,
2046
2078
  includeSessionContext ? buildContextSection({
2047
2079
  actor: params.actor,
2048
2080
  configuration: params.configuration,
@@ -2346,9 +2378,11 @@ async function assemblePrompt(args) {
2346
2378
  context: args.toolRuntimeContext,
2347
2379
  turnId: args.turnId
2348
2380
  });
2349
- const turnContextPrompt = needsBootstrapContextForPrompt || pluginUserPromptContributions.length > 0 ? buildTurnContextPrompt({
2381
+ const disabledTools = !shouldPromptAgent || replayedPrompt ? [] : args.disabledTools;
2382
+ const turnContextPrompt = needsBootstrapContextForPrompt || pluginUserPromptContributions.length > 0 || disabledTools.length > 0 ? buildTurnContextPrompt({
2350
2383
  availableSkills: args.availableSkills,
2351
2384
  activeMcpCatalogs: args.activeMcpCatalogs,
2385
+ disabledTools,
2352
2386
  includeSessionContext: needsBootstrapContextForPrompt,
2353
2387
  pluginPromptContributions: pluginUserPromptContributions,
2354
2388
  toolGuidance: args.toolGuidance,
@@ -4663,9 +4697,13 @@ function createSandboxRuntime(options) {
4663
4697
  if (activeWorkspace?.id === workspace.id && dependencyProfileHash === nextProfileHash) return;
4664
4698
  if (acquiringSandbox) await getOrAcquireSandbox(signal);
4665
4699
  const previous = activeSandbox;
4700
+ signal?.throwIfAborted();
4701
+ const switching = new AbortController();
4702
+ const stopSwitching = () => switching.abort(signal?.reason);
4703
+ signal?.addEventListener("abort", stopSwitching, { once: true });
4666
4704
  let candidate;
4667
4705
  try {
4668
- candidate = await createSandboxCandidate(workspace, nextProfileHash, signal);
4706
+ candidate = await createSandboxCandidate(workspace, nextProfileHash, switching.signal);
4669
4707
  await probeSession(candidate.session);
4670
4708
  signal?.throwIfAborted();
4671
4709
  await extendKeepAlive(candidate.session);
@@ -4674,6 +4712,8 @@ function createSandboxRuntime(options) {
4674
4712
  } catch (error) {
4675
4713
  await stopSession(candidate?.session);
4676
4714
  throw error;
4715
+ } finally {
4716
+ signal?.removeEventListener("abort", stopSwitching);
4677
4717
  }
4678
4718
  if (keepAliveTimer) {
4679
4719
  clearTimeout(keepAliveTimer);
@@ -8290,15 +8330,46 @@ async function listChildAgents(parentConversationId) {
8290
8330
  const stoppedAtMs = new Map(stops.map((row) => [row.conversationId, row.stoppedAt?.getTime()]));
8291
8331
  return [...byChild.entries()].map(([childConversationId, invocations]) => childAgentFromInvocations(invocations, resultInvocationIds, stoppedAtMs.get(childConversationId))).sort((left, right) => right.updatedAtMs - left.updatedAtMs);
8292
8332
  }
8333
+ /**
8334
+ * List the agents that one Conversation can see. A root Conversation sees
8335
+ * only its child agents. A child agent also sees itself, its parent, and the
8336
+ * other child agents of its parent.
8337
+ */
8338
+ async function listAgentRelatives(input) {
8339
+ const { conversationId, parentConversationId } = input;
8340
+ const [children, family, parent] = await Promise.all([
8341
+ listChildAgents(conversationId),
8342
+ parentConversationId ? listChildAgents(parentConversationId) : [],
8343
+ parentConversationId ? getConversationStore().get({ conversationId: parentConversationId }) : void 0
8344
+ ]);
8345
+ const self = family.find((agent) => agent.childConversationId === conversationId);
8346
+ return {
8347
+ children,
8348
+ ...parent ? { parent: {
8349
+ conversationId: parent.conversationId,
8350
+ status: parent.execution.status,
8351
+ updatedAtMs: parent.execution.updatedAtMs ?? parent.updatedAtMs
8352
+ } } : void 0,
8353
+ ...self ? { self } : void 0,
8354
+ siblings: family.filter((agent) => agent.childConversationId !== conversationId)
8355
+ };
8356
+ }
8293
8357
  //#endregion
8294
8358
  //#region src/chat/tools/runtime/list-agents.ts
8295
8359
  const TASK_MAX_LENGTH = 1e3;
8296
8360
  const ERROR_MAX_LENGTH = 500;
8361
+ /** How a listed agent relates to the conversation that lists it. */
8362
+ const AGENT_RELATIONS = [
8363
+ "self",
8364
+ "parent",
8365
+ "child",
8366
+ "sibling"
8367
+ ];
8297
8368
  /**
8298
- * What a child agent does now. The words match the Conversation execution
8369
+ * What an agent does now. The words match the Conversation execution
8299
8370
  * status, plus `stopped` after stopAgent.
8300
8371
  */
8301
- const CHILD_AGENT_STATUSES = [
8372
+ const LISTED_AGENT_STATUSES = [
8302
8373
  "pending",
8303
8374
  "running",
8304
8375
  "paused",
@@ -8316,23 +8387,45 @@ function childAgentStatus(agent) {
8316
8387
  case "failed": return "idle";
8317
8388
  }
8318
8389
  }
8390
+ function parentAgentStatus(agent) {
8391
+ return agent.status === "failed" ? "idle" : agent.status;
8392
+ }
8319
8393
  function truncate(text, maxLength) {
8320
8394
  return text.length > maxLength ? `${text.slice(0, maxLength)}…` : text;
8321
8395
  }
8322
- const listAgentsOutputSchema = juniorToolOutputSchema.extend({ agents: z.array(z.object({
8323
- conversation_id: z.string().min(1).describe("Child conversation ID. Pass it to searchConversationEvents to read the child's history."),
8324
- name: agentNameSchema.optional().describe("Child-agent name. Pass it to messageAgent."),
8325
- status: z.enum(CHILD_AGENT_STATUSES).describe("What the child agent does now. pending: waiting to run. running or paused: working. idle: finished its work and waits for a message. stopped: stopAgent stopped it."),
8326
- last_result: z.enum(CHILD_AGENT_RESULTS).optional().describe("How the latest finished task of the child agent ended"),
8327
- task: z.string().describe("Latest task given to the child agent"),
8396
+ const listedAgentSchema = z.object({
8397
+ relation: z.enum(AGENT_RELATIONS).describe("self: this conversation. parent: the agent that started it. child: an agent that it started. sibling: another child of its parent."),
8398
+ conversation_id: z.string().min(1).describe("Agent conversation ID. Pass it to searchConversationEvents to read the agent's history."),
8399
+ name: agentNameSchema.optional().describe("Agent name given by its parent. Pass the name of a child agent to messageAgent."),
8400
+ status: z.enum(LISTED_AGENT_STATUSES).describe("What the agent does now. pending: waiting to run. running or paused: working. idle: finished its work and waits for a message. stopped: stopAgent stopped it."),
8401
+ last_result: z.enum(CHILD_AGENT_RESULTS).optional().describe("How the latest finished task of the agent ended"),
8402
+ task: z.string().optional().describe("Latest task that its parent gave the agent. Not shown for the parent."),
8328
8403
  title: z.string().optional().describe("Short display title of the latest task"),
8329
- error: z.string().optional().describe("Why the child agent is blocked, failed, or stopped"),
8404
+ error: z.string().optional().describe("Why the agent is blocked, failed, or stopped"),
8330
8405
  updated_at: z.string().describe("Time of the latest change")
8331
- }).strict()).describe("Child agents of this conversation, newest activity first") });
8332
- /** Create the read-only tool that lists the child agents of one conversation. */
8333
- function createListAgentsTool(conversationId) {
8406
+ }).strict();
8407
+ function listedChildAgent(relation, agent) {
8408
+ return {
8409
+ relation,
8410
+ conversation_id: agent.childConversationId,
8411
+ ...agent.agentName ? { name: agent.agentName } : void 0,
8412
+ status: childAgentStatus(agent),
8413
+ ...agent.lastResult ? { last_result: agent.lastResult } : void 0,
8414
+ task: truncate(agent.task, TASK_MAX_LENGTH),
8415
+ ...agent.title ? { title: agent.title } : void 0,
8416
+ ...agent.errorMessage ? { error: truncate(agent.errorMessage, ERROR_MAX_LENGTH) } : void 0,
8417
+ updated_at: new Date(agent.updatedAtMs).toISOString()
8418
+ };
8419
+ }
8420
+ const listAgentsOutputSchema = juniorToolOutputSchema.extend({ agents: z.array(listedAgentSchema).describe("This conversation, its parent, its child agents, then its siblings. Child agents and siblings show the newest activity first.") });
8421
+ /**
8422
+ * Create the read-only tool that lists the agents one conversation can see:
8423
+ * its child agents and, for a child agent, itself, its parent, and its
8424
+ * siblings.
8425
+ */
8426
+ function createListAgentsTool(context) {
8334
8427
  return zodTool({
8335
- description: "List the child agents that this conversation started, with the state recorded by the runtime. Use it to check which child agents are still working, or to find a child agent before you give it more work with messageAgent. Results still arrive as new tasks; do not poll with this tool.",
8428
+ description: "List the agents that this conversation can see, with the state recorded by the runtime: the child agents it started and, for a child agent, itself, its parent, and its siblings. Use it to check which agents are still working, to see what your siblings work on, or to find a child agent before you give it more work with messageAgent. Results still arrive as new tasks; do not poll with this tool.",
8336
8429
  annotations: {
8337
8430
  destructiveHint: false,
8338
8431
  idempotentHint: true,
@@ -8341,16 +8434,20 @@ function createListAgentsTool(conversationId) {
8341
8434
  },
8342
8435
  inputSchema: z.object({}).strict(),
8343
8436
  outputSchema: listAgentsOutputSchema,
8344
- execute: async () => ({ agents: (await listChildAgents(conversationId)).map((agent) => ({
8345
- conversation_id: agent.childConversationId,
8346
- ...agent.agentName ? { name: agent.agentName } : void 0,
8347
- status: childAgentStatus(agent),
8348
- ...agent.lastResult ? { last_result: agent.lastResult } : void 0,
8349
- task: truncate(agent.task, TASK_MAX_LENGTH),
8350
- ...agent.title ? { title: agent.title } : void 0,
8351
- ...agent.errorMessage ? { error: truncate(agent.errorMessage, ERROR_MAX_LENGTH) } : void 0,
8352
- updated_at: new Date(agent.updatedAtMs).toISOString()
8353
- })) })
8437
+ execute: async () => {
8438
+ const { children, parent, self, siblings } = await listAgentRelatives(context);
8439
+ return { agents: [
8440
+ ...self ? [listedChildAgent("self", self)] : [],
8441
+ ...parent ? [{
8442
+ relation: "parent",
8443
+ conversation_id: parent.conversationId,
8444
+ status: parentAgentStatus(parent),
8445
+ updated_at: new Date(parent.updatedAtMs).toISOString()
8446
+ }] : [],
8447
+ ...children.map((agent) => listedChildAgent("child", agent)),
8448
+ ...siblings.map((agent) => listedChildAgent("sibling", agent))
8449
+ ] };
8450
+ }
8354
8451
  });
8355
8452
  }
8356
8453
  //#endregion
@@ -9585,15 +9682,15 @@ function createUpdateEventAutomationTool(context, catalog) {
9585
9682
  }
9586
9683
  //#endregion
9587
9684
  //#region src/chat/tools/event-automations.ts
9588
- /** Build event automation tools for an interactive Slack actor. */
9685
+ /** Build event automation tools for a Conversation with a Slack Location. */
9589
9686
  function createEventAutomationTools(context, catalog) {
9590
- if (context.source.kind !== "slack" || context.destination.platform !== "slack" || context.actor?.platform !== "slack") return {};
9591
- return {
9687
+ if (!getSlackToolContext(context)) return {};
9688
+ return disableTools({
9592
9689
  createEventAutomation: createEventAutomationTool(context, catalog),
9593
9690
  listEventAutomations: createListEventAutomationsTool(context, catalog),
9594
9691
  updateEventAutomation: createUpdateEventAutomationTool(context, catalog),
9595
9692
  deleteEventAutomation: createDeleteEventAutomationTool(context, catalog)
9596
- };
9693
+ }, slackMessageTurnDisabledReason(context));
9597
9694
  }
9598
9695
  //#endregion
9599
9696
  //#region src/chat/scheduled-automations/telemetry.ts
@@ -10252,26 +10349,28 @@ function createSlackScheduleUpdateAutomationTool(context) {
10252
10349
  //#endregion
10253
10350
  //#region src/chat/tools/scheduled-automations.ts
10254
10351
  function scheduledAutomationToolContext(context) {
10255
- if (context.source.kind !== "slack" || context.destination.platform !== "slack" || context.actor?.platform !== "slack" || !context.resolveActorIdentity) return;
10352
+ const slackMessageTurn = isSlackMessageTurn(context) ? {
10353
+ actor: context.actor,
10354
+ source: context.source
10355
+ } : void 0;
10256
10356
  return {
10257
10357
  conversationId: context.conversationId,
10258
- actor: context.actor,
10259
- source: context.source,
10260
- users: { resolveActor: context.resolveActorIdentity },
10358
+ ...slackMessageTurn,
10359
+ users: { resolveActor: context.resolveActorIdentity ?? (async () => void 0) },
10261
10360
  ...context.userText ? { userText: context.userText } : void 0
10262
10361
  };
10263
10362
  }
10264
- /** Build scheduled-automation tools for an interactive Slack actor. */
10363
+ /** Build scheduled-automation tools for a Conversation with a Slack Location. */
10265
10364
  function createScheduledAutomationTools(context) {
10365
+ if (!getSlackToolContext(context)) return {};
10266
10366
  const taskContext = scheduledAutomationToolContext(context);
10267
- if (!taskContext) return {};
10268
- return {
10367
+ return disableTools({
10269
10368
  slackScheduleCreateAutomation: createSlackScheduleCreateAutomationTool(taskContext),
10270
10369
  slackScheduleListAutomations: createSlackScheduleListAutomationsTool(taskContext),
10271
10370
  slackScheduleUpdateAutomation: createSlackScheduleUpdateAutomationTool(taskContext),
10272
10371
  slackScheduleDeleteAutomation: createSlackScheduleDeleteAutomationTool(taskContext),
10273
10372
  slackScheduleRunAutomationNow: createSlackScheduleRunAutomationNowTool(taskContext)
10274
- };
10373
+ }, slackMessageTurnDisabledReason(context));
10275
10374
  }
10276
10375
  //#endregion
10277
10376
  //#region src/chat/slack/channel.ts
@@ -15030,7 +15129,12 @@ function createToolState() {
15030
15129
  }
15031
15130
  };
15032
15131
  }
15033
- /** Build the model-facing tool registry from runtime-owned context and capabilities. */
15132
+ /**
15133
+ * Build the model-facing tool registry from runtime-owned context and capabilities.
15134
+ *
15135
+ * Choose tools from the Conversation, not from one Turn, so the cached tool
15136
+ * list stays the same. Use `disableTools` when a Turn cannot use a tool.
15137
+ */
15034
15138
  function createTools(availableSkills, hooks = {}, context, options = {}) {
15035
15139
  const state = createToolState();
15036
15140
  const slackContext = getSlackToolContext(context);
@@ -15038,7 +15142,7 @@ function createTools(availableSkills, hooks = {}, context, options = {}) {
15038
15142
  const canSendFilesToActiveConversation = Boolean(slackContext ? slackLocationCapabilities?.canSendFiles : context.attachmentStorage);
15039
15143
  const eventCatalog = getEventCatalog();
15040
15144
  const tools = {
15041
- ...options.includeLoadSkill === false ? void 0 : { loadSkill: createLoadSkillTool(availableSkills, { onSkillLoaded: hooks.onSkillLoaded }) },
15145
+ loadSkill: createLoadSkillTool(availableSkills, { onSkillLoaded: hooks.onSkillLoaded }),
15042
15146
  updatePlan: createUpdatePlanTool(),
15043
15147
  reportProgress: createReportProgressTool(),
15044
15148
  systemTime: createSystemTimeTool(),
@@ -15096,9 +15200,12 @@ function createTools(availableSkills, hooks = {}, context, options = {}) {
15096
15200
  if (context.spawnAgent) {
15097
15201
  if (!context.spawnAgentProfiles) throw new Error("spawnAgent is missing its configured model profiles");
15098
15202
  tools.spawnAgent = createSpawnAgentTool(context.spawnAgent, context.spawnAgentProfiles);
15099
- tools.listAgents = createListAgentsTool(context.conversationId);
15100
15203
  tools.stopAgent = createStopAgentTool(context.conversationId);
15101
15204
  }
15205
+ if (context.spawnAgent || context.messageAgent) tools.listAgents = createListAgentsTool({
15206
+ conversationId: context.conversationId,
15207
+ parentConversationId: context.parentConversationId
15208
+ });
15102
15209
  if (context.messageAgent) tools.messageAgent = createMessageAgentTool(context.messageAgent);
15103
15210
  if (context.parentConversationId) tools[REPORT_BLOCKED_TOOL_NAME] = createReportBlockedTool();
15104
15211
  if (context.automation) tools[FINISH_AUTOMATION_RUN_TOOL_NAME] = createFinishAutomationRunTool(context.automation);
@@ -15120,7 +15227,7 @@ function createTools(availableSkills, hooks = {}, context, options = {}) {
15120
15227
  provider: "slack",
15121
15228
  providerTenantId: slackContext.teamId
15122
15229
  }, context.conversationId);
15123
- if (context.source.kind === "slack") tools.slackPublicSearch = createSlackPublicSearchTool(context.slackActionToken);
15230
+ Object.assign(tools, disableTools({ slackPublicSearch: createSlackPublicSearchTool(context.slackActionToken) }, context.slackActionToken ? void 0 : "Slack gives a search token only for a new message or mention."));
15124
15231
  const identityProviders = ["slack", ...getOAuthAccountProviders().filter((provider) => provider !== "slack")];
15125
15232
  tools.userLookup = createUserLookupTool(slackContext.teamId, identityProviders);
15126
15233
  tools.slackListCreate = createSlackListCreateTool(state);
@@ -15137,7 +15244,7 @@ function createTools(availableSkills, hooks = {}, context, options = {}) {
15137
15244
  storage: context.attachmentStorage
15138
15245
  } : void 0);
15139
15246
  tools.slackChannelListMessages = createSlackChannelListMessagesTool(slackContext);
15140
- if (context.source.kind === "slack" && locationCapabilities.canAddReactions) tools.addReaction = createSlackMessageAddReactionTool(slackContext, state);
15247
+ if (locationCapabilities.canAddReactions) Object.assign(tools, disableTools({ addReaction: createSlackMessageAddReactionTool(slackContext, state) }, slackContext.messageTs ? void 0 : "It needs a Slack message in this Turn to react to."));
15141
15248
  }
15142
15249
  for (const [name, pluginTool] of Object.entries(getPluginTools(context, options.pluginSandbox))) {
15143
15250
  if (tools[name]) throw new Error(`Plugin tool "${name}" conflicts with a core tool`);
@@ -15188,12 +15295,6 @@ function latestProgressStatus(messages) {
15188
15295
  }
15189
15296
  }
15190
15297
  //#endregion
15191
- //#region src/chat/tools/definition.ts
15192
- /** Distinguish legacy TypeBox schemas from JSON Schema projected from Zod. */
15193
- function isTypeBoxInputSchema(schema) {
15194
- return typeof schema === "object" && schema !== null && Kind in schema;
15195
- }
15196
- //#endregion
15197
15298
  //#region src/chat/tool-support/catalog-tool-call.ts
15198
15299
  function schemaErrorText(schema, value) {
15199
15300
  const firstError = [...Value.Errors(schema, value)][0];
@@ -16064,6 +16165,7 @@ function createPiAgentTools(tools, sandbox, spanContext, onStatus, sandboxTools,
16064
16165
  const executeDefinition = async (args) => {
16065
16166
  const { toolCallId, params, signal, setSpanAttributes, toolDef, toolName } = args;
16066
16167
  if (typeof toolDef.execute !== "function") throw new Error(`Tool ${toolName} does not define an executor.`);
16168
+ if (toolDef.disabledReason) throw new ToolInputError(disabledToolMessage(toolName, toolDef.disabledReason));
16067
16169
  const beforeTool = agentHooks ? await agentHooks.beforeToolExecute({
16068
16170
  name: toolName,
16069
16171
  input: params
@@ -18028,7 +18130,6 @@ async function wireAgentTools(args) {
18028
18130
  });
18029
18131
  const getPendingAuthPause = () => pluginAuth.getPendingPause() ?? mcpAuth.getPendingPause();
18030
18132
  const loadableSkills = args.availableSkills.filter((skill) => skill.disableModelInvocation !== true || skill.name === args.invokedSkill?.name);
18031
- const explicitSkillLoaded = Boolean(args.invokedSkill && args.activeSkills.some((skill) => skill.name === args.invokedSkill?.name));
18032
18133
  const commonToolRuntimeContext = {
18033
18134
  conversationId: args.run.conversationId,
18034
18135
  ...args.run.parentConversationId ? { parentConversationId: args.run.parentConversationId } : void 0,
@@ -18117,11 +18218,12 @@ async function wireAgentTools(args) {
18117
18218
  upsertActiveSkill(args.activeSkills, effective);
18118
18219
  await tryRecordSkillLoadStat(effective);
18119
18220
  }
18120
- }, toolRuntimeContext, {
18121
- includeLoadSkill: !explicitSkillLoaded,
18122
- pluginSandbox: createPluginToolSandbox(agentSandbox, { handleAuthSignal: pluginAuth.maybeHandleAuthSignal })
18123
- });
18221
+ }, toolRuntimeContext, { pluginSandbox: createPluginToolSandbox(agentSandbox, { handleAuthSignal: pluginAuth.maybeHandleAuthSignal }) });
18124
18222
  const plannedToolExposure = planToolExposure(tools);
18223
+ const disabledTools = Object.entries(tools).flatMap(([name, definition]) => definition.disabledReason ? [{
18224
+ name,
18225
+ reason: definition.disabledReason
18226
+ }] : []);
18125
18227
  const toolGuidance = Object.entries(plannedToolExposure.directTools).map(([name, definition]) => ({
18126
18228
  name,
18127
18229
  promptGuidelines: definition.promptGuidelines,
@@ -18188,6 +18290,7 @@ async function wireAgentTools(args) {
18188
18290
  });
18189
18291
  }
18190
18292
  },
18293
+ disabledTools,
18191
18294
  toolGuidance,
18192
18295
  toolRuntimeContext
18193
18296
  };
@@ -18222,6 +18325,7 @@ function createResumeState(args) {
18222
18325
  let turnContexts = [];
18223
18326
  let turnStartMessageIndex;
18224
18327
  let cumulativeToolCallCount = args.checkpoint.record?.cumulativeToolCallCount ?? 0;
18328
+ let turnLimitWrappedUp = args.checkpoint.record?.turnLimitWrappedUp ?? false;
18225
18329
  let advancedPastResume = !args.checkpoint.resumed;
18226
18330
  let resumedBoundaryKey = "";
18227
18331
  if (args.checkpoint.resumed && args.checkpoint.record.piMessages.length) {
@@ -18238,6 +18342,7 @@ function createResumeState(args) {
18238
18342
  channelName: args.channelName,
18239
18343
  credentialSubject: args.credentialSubject,
18240
18344
  cumulativeToolCallCount,
18345
+ ...turnLimitWrappedUp ? { turnLimitWrappedUp } : void 0,
18241
18346
  destination: args.destination,
18242
18347
  dispatchId: args.dispatchId,
18243
18348
  source: args.runSource,
@@ -18260,11 +18365,22 @@ function createResumeState(args) {
18260
18365
  setBeforeMessageCount(count) {
18261
18366
  beforeMessageCount = count;
18262
18367
  },
18263
- /** Admit one tool call against the durable turn total, or throw the limit. */
18264
- admitToolCall() {
18265
- const next = cumulativeToolCallCount + 1;
18266
- assertTurnToolCallLimit(next, botConfig.maxToolCallsPerTurn);
18267
- cumulativeToolCallCount = next;
18368
+ /** Usage that earlier slices of this turn saved. */
18369
+ get priorSliceUsage() {
18370
+ return args.checkpoint.record?.cumulativeUsage;
18371
+ },
18372
+ /** True once a step of this turn hit a limit and wrapped up. */
18373
+ get turnLimitWrappedUp() {
18374
+ return turnLimitWrappedUp;
18375
+ },
18376
+ /** Save the wrap-up so later slices stop instead of wrapping up again. */
18377
+ markTurnLimitWrappedUp() {
18378
+ turnLimitWrappedUp = true;
18379
+ },
18380
+ /** Charge one tool call to the durable turn total and return the total. */
18381
+ countToolCall() {
18382
+ cumulativeToolCallCount += 1;
18383
+ return cumulativeToolCallCount;
18268
18384
  },
18269
18385
  setTurnContexts(contexts) {
18270
18386
  turnContexts = contexts;
@@ -19373,6 +19489,8 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
19373
19489
  activeModelProfile = routedModelProfile;
19374
19490
  activeModelId = routedModelId;
19375
19491
  let pendingPiHookError;
19492
+ let discardedRetryUsage;
19493
+ const turnLimitGate = createTurnLimitGate(runResume.turnLimitWrappedUp);
19376
19494
  const currentAgentMessages = () => agent ? [...agent.state.messages] : [];
19377
19495
  const usageSinceCurrentBoundary = (messages) => {
19378
19496
  const usage = extractGenAiUsageSummary(...messages.slice(runResume.beforeMessageCount).filter(isAssistantMessage));
@@ -19518,6 +19636,7 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
19518
19636
  run,
19519
19637
  spanContext,
19520
19638
  turnId,
19639
+ disabledTools: wiring.disabledTools,
19521
19640
  toolGuidance: wiring.toolGuidance,
19522
19641
  toolRuntimeContext: wiring.toolRuntimeContext,
19523
19642
  userContentParts
@@ -19618,24 +19737,39 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
19618
19737
  ...streamFn ? { base: streamFn } : void 0
19619
19738
  }),
19620
19739
  steeringMode: "all",
19621
- beforeToolCall: async ({ assistantMessage }) => {
19740
+ beforeToolCall: async ({ assistantMessage, toolCall }) => {
19622
19741
  const toolCalls = assistantMessage.content.filter((part) => part.type === "toolCall");
19623
19742
  const exclusiveTool = exclusiveToolName(toolCalls);
19624
19743
  if (exclusiveTool && toolCalls.length !== 1) return {
19625
19744
  block: true,
19626
19745
  reason: `${exclusiveTool} must be the only tool call in its assistant message; reissue it alone`
19627
19746
  };
19628
- try {
19629
- runResume.admitToolCall();
19630
- } catch (error) {
19631
- const limitError = error instanceof Error ? error : new Error(String(error));
19632
- pendingPiHookError ??= limitError;
19747
+ const toolCallCount = runResume.countToolCall();
19748
+ const turnCostUsd = agentTurnCostUsd(addAgentTurnUsage(runResume.priorSliceUsage, priorPhaseUsage, discardedRetryUsage, usageSinceCurrentBoundary(currentAgentMessages()))) ?? 0;
19749
+ const overBudget = turnCostUsd >= botConfig.maxTurnCostUsd;
19750
+ const decision = turnLimitGate({
19751
+ assistantMessage,
19752
+ overLimit: overBudget || toolCallCount > botConfig.maxToolCallsPerTurn
19753
+ });
19754
+ if (decision === "allow") return;
19755
+ if (decision === "wrap_up") {
19756
+ runResume.markTurnLimitWrappedUp();
19757
+ logWarn("agent.turn.limit.wrap_up", {
19758
+ "app.ai.cost.total_usd": turnCostUsd,
19759
+ "app.ai.tool_call_count": toolCallCount
19760
+ });
19633
19761
  return {
19634
19762
  block: true,
19635
- reason: limitError.message,
19636
- terminate: true
19763
+ reason: disabledToolMessage(toolCall.name, TURN_LIMIT_DISABLED_REASON)
19637
19764
  };
19638
19765
  }
19766
+ const limitError = toolCallCount > botConfig.maxToolCallsPerTurn && !overBudget ? new TurnToolCallLimitExceededError(botConfig.maxToolCallsPerTurn) : new TurnBudgetExceededError(botConfig.maxTurnCostUsd);
19767
+ pendingPiHookError ??= limitError;
19768
+ return {
19769
+ block: true,
19770
+ reason: limitError.message,
19771
+ terminate: true
19772
+ };
19639
19773
  },
19640
19774
  afterToolCall: async ({ isError, result, toolCall }, signal) => {
19641
19775
  const timedOutResult = runResume.timedOut && signal?.aborted ? projectTimedOutToolResult(result) : void 0;
@@ -19648,6 +19782,7 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
19648
19782
  prepareNextTurnWithContext: async (nextTurn, hookSignal) => {
19649
19783
  try {
19650
19784
  const handoffUpdate = applyPendingHandoff();
19785
+ if (hookSignal?.aborted) return handoffUpdate;
19651
19786
  const contextUpdate = await repositoryInstructionsContext.applyUpdate(handoffUpdate, nextTurn.context);
19652
19787
  const pendingMessages = await drainSteeringMessages();
19653
19788
  const capacityUpdate = await applyActiveContextCompaction(contextUpdate ? currentAgentMessages() : nextTurn.context.messages, hookSignal, pendingMessages, true);
@@ -19807,7 +19942,7 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
19807
19942
  }] : void 0, false, Boolean(contextMessage)), () => compactionAbortController.abort());
19808
19943
  if (shouldPromptAgent && handoffApplied && !capacityUpdate) await runResume.requireDurableInputCheckpoint([...agent.state.messages, freshPromptMessage]);
19809
19944
  run = shouldPromptAgent && !capacityUpdate ? agent.prompt(freshPromptMessage) : agent.continue();
19810
- let discardedRetryUsage;
19945
+ discardedRetryUsage = void 0;
19811
19946
  let actionConfirmationRetryUsed = false;
19812
19947
  let automationResultReminderUsed = !requireAutomationResult;
19813
19948
  let providerRetryAttempt = 0;
@@ -20021,7 +20156,7 @@ function createAgentRunner(execute, options) {
20021
20156
  } } : void 0
20022
20157
  };
20023
20158
  if (run.instruction.storedAttachments?.length) {
20024
- const { loadInputImages } = await import("./images-C3e5E-p_.js").then((n) => n.n);
20159
+ const { loadInputImages } = await import("./images-Dzh3RBXY.js").then((n) => n.n);
20025
20160
  const storage = nextRun.environment?.attachmentStorage;
20026
20161
  if (!storage) throw new Error("Attachment storage is unavailable.");
20027
20162
  nextRun.instruction = {