@sentry/junior 0.312.0 → 0.314.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-iIq7ihf7.js → adapter-JARQvoLw.js} +1 -2
- package/dist/{adapter-context-BRjEWRy1.js → adapter-context-B4BrJZuS.js} +2 -2
- package/dist/{admin-DhInw5K9.js → admin-BXGAySz0.js} +1 -1
- package/dist/{agent-runner-C9iDurwX.js → agent-runner-qZU5TR8i.js} +865 -138
- package/dist/agent-update-cS7Z9mnG.js +26 -0
- package/dist/agent-update-delivery-CZ5M8RDa.js +85 -0
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +6 -6
- package/dist/api.d.ts +1 -1
- package/dist/api.js +340 -106
- package/dist/{app-DRFrC8Mw.d.ts → app-D7tKnw9a.d.ts} +4 -21
- package/dist/app.d.ts +2 -2
- package/dist/app.js +80 -171
- package/dist/{background-compaction-queue-DrKi7w3d.js → background-compaction-queue-C_uIBUvS.js} +6 -17
- package/dist/{callback-mFlTUWWx.js → callback-C8SdXCwr.js} +4 -11
- package/dist/{catalog-runtime-D7xapBAX.js → catalog-runtime-BLKtnUL3.js} +1 -1
- package/dist/{channel-access-CJGfNTdn.js → channel-access-BOL29BG3.js} +6 -6
- package/dist/child-message--2G3Ft26.js +19 -0
- package/dist/cli/chat.js +18 -21
- package/dist/cli/check.js +4 -4
- package/dist/cli/main.js +2 -2
- package/dist/cli/plugins.js +5 -5
- package/dist/cli/snapshot-create.js +5 -5
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +23 -4
- package/dist/{config-kXB2Y5tl.js → config-BIfHKNXN.js} +40 -35
- package/dist/{continue-in-slack-O6pV5004.js → continue-in-slack-fnmD2Ifb.js} +5 -7
- package/dist/{conversation-feed-uNOv_x68.js → conversation-feed-DdFQuQDR.js} +13 -2
- package/dist/{logging-dQ9ZRGQ8.js → conversation-privacy-DtZhI91r.js} +188 -2
- package/dist/{conversation-turn-CeLbHqdw.js → conversation-turn-DScuDYmN.js} +465 -62
- package/dist/create-CrNt4Ewu.js +212 -0
- package/dist/{credential-sync-I8VBGk05.js → credential-sync-CtqsGjj1.js} +14 -18
- package/dist/{credentialed-Cb6E2phL.js → credentialed-dWRA3-oJ.js} +911 -429
- package/dist/{db-LAyyX8tk.js → db-BTmLKZrp.js} +2245 -50
- package/dist/{db-BbC5stfa.d.ts → db-DcmzbA55.d.ts} +2 -2
- package/dist/{history-CYstOMKX.js → history-CneKY7_V.js} +19 -1
- package/dist/{html-BCZ3Xtb_.js → html-B8rBt7F4.js} +5 -7
- package/dist/{install-DCFJFkC0.js → install-OtFboxOM.js} +2 -2
- package/dist/instrumentation.js +2 -2
- package/dist/{lineage-B_m-4TJw.js → lineage-EULJkGO1.js} +1 -2
- package/dist/{list-CN2QA2R9.js → list-C5400AlJ.js} +284 -113
- package/dist/{thread-state-DhPndWi1.js → mailbox-turn-DL3Lvsm0.js} +4830 -485
- package/dist/markers-DUP8aBOp.js +323 -0
- package/dist/{media-CYm1QD8T.js → media-FYM-Bl3H.js} +42 -14
- package/dist/{message-DSXGj1hM.js → message-DuDelZFr.js} +16 -15
- package/dist/{model-input--TrP9hYV.js → model-input-0osF3pBS.js} +3 -3
- package/dist/nitro.d.ts +2 -4
- package/dist/nitro.js +340 -13
- package/dist/{oauth-callback-server-DHCZC6B4.js → oauth-callback-server-DX2fQ7Nq.js} +2 -2
- package/dist/{oauth-relay-pPMGnDZt.js → oauth-relay-PwPMdZJv.js} +1 -1
- package/dist/{plugins-Bkk0XRo2.js → plugins-BXMdNdyA.js} +1 -1
- package/dist/{registry-CZOzddwu.js → registry-D6kS6xYH.js} +1402 -64
- package/dist/{statuses-_cRJHXK7.js → reporting-window-C4dbzDiR.js} +1 -27
- package/dist/{resolve-cKOQ14Dh.js → resolve-D8CPJcNK.js} +3 -3
- package/dist/result-D090hxr5.js +402 -0
- package/dist/{runner-DBfUW44l.js → runner-BU7fgrm-.js} +7 -8
- package/dist/{sandbox-egress-signals-BVF_xAm1.js → sandbox-egress-signals-BUmVrsoG.js} +1 -1
- package/dist/{schema-Bk9Nm2E8.js → schema-7gW9vBpJ.js} +91 -10
- package/dist/{schema-BEHKxr4I.d.ts → schema-BB6E0wyV.d.ts} +2105 -2753
- package/dist/{service-account-CVYsFjty.js → service-account-plA-uzIB.js} +6 -5
- package/dist/{skills-VTnhAJWm.js → skills-CIosT6bS.js} +3 -3
- package/dist/{slack-conversation-unfurl-fuLnF1jE.js → slack-conversation-unfurl-CBgZqth6.js} +8 -10
- package/dist/spawn-DRjdzh3R.js +46 -0
- package/dist/{start-conversation-CEn2KH1A.js → start-conversation-a4NXH4X9.js} +13 -202
- package/dist/{store-DFZaN-Ix.js → store-BuhF1QDm.js} +2 -4
- package/dist/{task-queue-Cx4Lmjyk.js → task-queue-CrRjFzOh.js} +5 -16
- package/dist/{task-runner-CbTwFA6k.js → task-runner-C-pXsgHM.js} +105 -51
- package/dist/{thread-context-BkAZDTX2.js → thread-context-CDX4dSZd.js} +8 -10
- package/dist/turn-session-routing-CZTRU8IY.js +116 -0
- package/dist/turn-wake-Bzq1Efrm.js +154 -0
- package/dist/user-customization-B27StpVQ.js +9 -0
- package/dist/{validation-nIzMtAVJ.js → validation-bTq88sya.js} +1 -1
- package/dist/{vercel-queue-hW90XzbG.js → vercel-queue-nL0Hq3hr.js} +32 -147
- package/dist/{version-Brbtz4Qf.js → version-DGUa1dZK.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{warmup-BDA5myRK.js → warmup-CCOuIwAS.js} +831 -3254
- package/dist/{worker-D63RcaVD.js → worker-AkZg7Dg1.js} +5 -6
- package/migrations/0158_keep_legacy_archive_columns.sql +5 -0
- package/migrations/0159_conversation_embeddings_fk_validate.sql +5 -0
- package/migrations/0160_money_micro_usd_repair.sql +99 -0
- package/migrations/0161_agent_config_backfill.sql +34 -0
- package/migrations/0162_inbox_item_deliveries.sql +15 -0
- package/migrations/0163_pg_trgm.sql +2 -0
- package/migrations/0164_search_indexes.sql +4 -0
- package/migrations/0165_drop_legacy_archive_columns.sql +4 -0
- package/migrations/0166_memory_prefix_index.sql +1 -0
- package/migrations/0167_todo_search_indexes.sql +2 -0
- package/migrations/0168_todo_inbox_items.sql +4 -0
- package/migrations/0169_drop_code_urls.sql +2 -0
- package/migrations/meta/0158_snapshot.json +6515 -0
- package/migrations/meta/0159_snapshot.json +6515 -0
- package/migrations/meta/0160_snapshot.json +6515 -0
- package/migrations/meta/0161_snapshot.json +6278 -0
- package/migrations/meta/0162_snapshot.json +6404 -0
- package/migrations/meta/0163_snapshot.json +6404 -0
- package/migrations/meta/0164_snapshot.json +6466 -0
- package/migrations/meta/0165_snapshot.json +6466 -0
- package/migrations/meta/0166_snapshot.json +6494 -0
- package/migrations/meta/0167_snapshot.json +6525 -0
- package/migrations/meta/0168_snapshot.json +6525 -0
- package/migrations/meta/0169_snapshot.json +6513 -0
- package/migrations/meta/_journal.json +84 -0
- package/package.json +9 -18
- package/skills/design-automation-skill/SKILL.md +2 -3
- package/dist/actor-BsBdxDXQ.js +0 -208
- package/dist/child-message-DcsritGf.js +0 -179
- package/dist/conversation-privacy-L4ja1_W6.js +0 -189
- package/dist/executor-SCub-fAq.js +0 -1860
- package/dist/fan-out-Cod-yEHG.js +0 -10
- package/dist/ingest-BDf3D50j.js +0 -3836
- package/dist/result-DcvEOe1r.js +0 -574
- package/dist/result-event-type-BdIJuZxg.js +0 -48
- package/dist/service-account-Ts4ulcrV.js +0 -931
- package/dist/spawn-vxAarlX5.js +0 -73
- package/dist/state-C1P3_Ywk.js +0 -161
|
@@ -1,31 +1,25 @@
|
|
|
1
|
-
import { $
|
|
2
|
-
import { H as estimateRequestOverheadTokens, O as resolveGatewayModel, U as estimateTextTokens, W as textCharsForTokens, _ as toPiReasoningLevel, at as ProviderError, dt as isProviderRefusal, ft as isProviderRetryError,
|
|
3
|
-
import {
|
|
4
|
-
import { C as summarizeMessageText, E as withSpan, S as setTags, T as withLogContext, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, d as logAudit, f as logError, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, m as logInfo, p as logException, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging-dQ9ZRGQ8.js";
|
|
1
|
+
import { $a as recordRepeatInboxItemPush, A as readNotificationPause, An as consumeSandboxEgressPermissionDeniedSignal, Ar as SANDBOX_SKILLS_ROOT, As as transcribeFromUrl, Bi as getDashboardInboxItemSnoozeLink, Bn as tryWorkspaceRepoCheckoutPath, C as unpublishArtifact, Cn as wrapSandboxSetupError, Cs as credentialAuditSource, D as readWebPushConfig, Dn as workspaceSnapshotNotReadyUserMessage, Dr as SANDBOX_DATA_ROOT, Ds as completeText, Dt as isToolResultError, En as isWorkspaceSnapshotNotReadyError, Er as SANDBOX_COMMAND_PATH, Es as completeObject, Fn as buildSandboxEgressNetworkPolicy, Fr as buildCommandScript, Go as SlackActionError, Hi as getDashboardObjectIconLink, Hn as PluginToolDeniedError, In as resolveSandboxCommandEnvironment, Ir as buildNonInteractiveShellScript, Kt as renderToolResultNudge, L as isActiveInSlack, Lr as runNonInteractiveCommand, Ls as getConfigDefaults, Mr as sandboxSkillDir, Mt as trimTrailingAssistantMessages, Na as resolveTaskTitle, Ni as readScheduledAutomation, Nr as sandboxSkillFile, O as sendPushNotificationToUser, On as clearSandboxEgressSignals, Os as generateImages, Ot as isToolResultMessage, Pi as saveScheduledAutomation, Pr as sandboxSkillPathResolution, Qa as recordInboxItemSlackCard, Qi as createEventAutomation, Ra as getInboxItem, Ri as getDashboardConversationLink, Rt as resolveChannelCapabilities, Si as normalizeSlackReplyMarkdown, Sn as throwSandboxOperationError, Sr as userLookupIdentityProviders, Ss as credentialAuditAttributes, Tn as getWorkspaceSnapshotNotReadyError, Tr as ATTACHMENT_DIR, Tt as isContinuablePiBoundary, Ua as isInboxItemOpen, Xa as clearInboxItemDeliveries, Xo as isConversationScopedChannel, Ya as claimInboxItemPush, Yt as getWorkspace, Za as listInboxItemPushUserIds, _i as slackExternalRefIdSchema, _o as slackChannelMessageTrigger, _t as extractAssistantText, ai as deleteSlackMessage, bi as formatSlackLink, bt as getUserMessageInstructionText, c as createPluginHookRunner, cn as ensureDockerDaemon, d as getPluginSlackConversationLink, do as getEventCatalog, gn as resolveBaseUrl, hi as fitsSlackMetadataLimit, ia as saveEventAutomation, ii as addReactionToMessage, io as inboxItemSnoozedBy, is as sleep, jn as createSandboxEgressCredentialToken, jr as SANDBOX_WORKSPACE_ROOT, js as NoAudioError, k as notificationPreview, ki as createScheduledAutomation, kn as consumeSandboxEgressAuthRequiredSignal, kr as SANDBOX_SCRATCH_ROOT, kt as normalizeToolNameFromResult, ln as getSandboxProvider, ma as automationRevision, mi as uploadFilesToConversation, mn as formatProviderLabel, on as hash, p as getPluginTools, pi as updateSlackMessage, pn as deliverOAuthAuthorization, po as requireSlackChannelMessageScope, pr as resolveUserTimezone, r as createUserTokenStore, rt as isEventEmbeddingsEnabled, ss as updateTimerIndex, ta as getEventAutomation, tr as createConversationEmbedder, ui as postSlackMessage, un as isRetryableSandboxFailure, vn as SandboxCallTimeoutError, vt as getPiMessageRole, wt as isAssistantMessage, x as publishImage, xi as isTableRow, xn as isAlreadyExistsError, yi as escapeSlackMrkdwnText, yn as findInErrorChain, yt as getTerminalAssistantMessages, zi as getDashboardInboxItemLink, zn as SANDBOX_RUNTIME, zt as getSlackToolContext } from "./credentialed-dWRA3-oJ.js";
|
|
2
|
+
import { H as estimateRequestOverheadTokens, O as resolveGatewayModel, U as estimateTextTokens, W as textCharsForTokens, _ as toPiReasoningLevel, _t as bufferBody, at as ProviderError, dt as isProviderRefusal, ft as isProviderRetryError, gt as mapBounded, lt as getProviderErrorAttributes, n as botConfig, ot as createAssistantProviderError, pt as getGatewayApiKey, q as hasCompactedConversationContext, r as getChatConfig, st as createProviderError, tt as readParentAgentTask, v as normalizeSlackEmojiName, y as GEN_AI_PROVIDER_NAME, z as withLock } from "./config-BIfHKNXN.js";
|
|
3
|
+
import { A as setSpanStatus, C as logInfo, D as serializeGenAiAttribute, E as runBestEffort, F as withSpan, M as summarizeMessageText, P as withLogContext, S as logException, T as normalizeGenAiFinishReason, Z as buildSentryConversationUrl, b as logAudit, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, j as setTags, k as setSpanAttributes, l as toGenAiPayloadTraceAttributes, m as extractGenAiUsageSummary, o as toCanonicalOutputMessage, p as extractGenAiUsageAttributes, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes, w as logWarn, x as logError, y as getTracePropagationHeaders } from "./conversation-privacy-DtZhI91r.js";
|
|
5
4
|
import { g as withActiveSpan, i as getActiveSpan } from "./sentry-CPbZjomA.js";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import { H as juniorConversations, _ as juniorAutomationRuns, ct as juniorArtifacts, m as juniorInboxItemSlackCards } from "./executor-SCub-fAq.js";
|
|
10
|
-
import { d as contextProvenance, f as instructionActors, m as sameActorIdentity, p as instructionProvenanceFor } from "./history-CYstOMKX.js";
|
|
11
|
-
import { i as getStateAdapter } from "./adapter-iIq7ihf7.js";
|
|
5
|
+
import { Br as juniorConversations, C as createSlackActor, E as isUserActor, En as isToolInputError, F as dispatchInstructionsInvokeSkills, H as promptModeTurnTools, Hn as addAgentTurnUsage, Kn as hasAgentTurnUsage, L as isPersonInput, Tn as ToolInputError, Un as agentTurnCostUsd, W as turnBehavior, Xn as nextDetailVersion, Xt as readActorIdentity, Zt as readActorIdentityFromSql, a as getDb, bi as parseSlackMessageTs, di as sameDestination, fr as juniorInboxItemConversations, hi as parseSlackUserId, hr as juniorInboxItems, i as getConversationStore, mi as parseSlackTeamId, mr as juniorInboxItemSlackCards, n as getConversationEventStore, o as getSqlExecutor, si as juniorArtifacts, yr as juniorAutomationRuns, z as isTopLevelKind } from "./db-BTmLKZrp.js";
|
|
6
|
+
import { d as contextProvenance, f as instructionActors, m as sameActorIdentity, p as instructionProvenanceFor } from "./history-CneKY7_V.js";
|
|
7
|
+
import { i as getStateAdapter } from "./adapter-JARQvoLw.js";
|
|
12
8
|
import { a as listReferenceFiles } from "./package-discovery-DD9vencX.js";
|
|
13
|
-
import { n as findSkillByName, o as parseSkillInvocations, r as loadSkillsByName, t as discoverSkills } from "./skills-
|
|
14
|
-
import {
|
|
15
|
-
import { n as pluginCatalogRuntime } from "./catalog-runtime-
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import { t as
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
import { r as
|
|
24
|
-
import { t as
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
import { n as resolve$1 } from "./resolve-cKOQ14Dh.js";
|
|
28
|
-
import { t as runWithSlackInstallation } from "./adapter-context-BRjEWRy1.js";
|
|
9
|
+
import { n as findSkillByName, o as parseSkillInvocations, r as loadSkillsByName, t as discoverSkills } from "./skills-CIosT6bS.js";
|
|
10
|
+
import { B as getMcpProviderErrorAttributes, C as getMcpServerSessionId, D as putMcpServerSessionId, E as putMcpAuthSession, F as McpProviderError, G as actorLogContext, H as OAuthProviderError, I as McpServiceAccountRequiredError, L as McpToolError, N as resolvePluginHeaderEnvRefs, O as putMcpStoredOAuthCredentials, R as getMcpAwareErrorType, S as getMcpAuthSession, T as patchMcpAuthSession, U as fetchWithBoundedOAuthErrorBodies, V as toMcpProviderError, W as getOAuthProviderErrorAttributes, X as credentialUserSubjectId, _ as PluginMcpClient, b as deleteMcpServerSessionId, c as serviceAccountOnly, g as McpAuthorizationRequiredError, h as getMcpServiceAccountCredentials, m as createMcpServiceAccountClientProvider, s as serviceAccountAllows, v as deleteMcpAuthSession, w as getMcpStoredOAuthCredentials, z as getMcpAwareTelemetryMessage } from "./registry-D6kS6xYH.js";
|
|
11
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-BLKtnUL3.js";
|
|
12
|
+
import { $i as NO_REPLY_TOOL_NAME, $t as assemblePrompt, Ai as isTurnExecutionLimitExceededError, Bi as getToolActionRejectionMarker, Bn as readRepositoryInstructions, Br as AuthorizationFlowDisabledError, Ci as GATED_TURN_LIMIT_WRAP_UP_MESSAGE, Di as TurnToolCallLimitExceededError, Ei as TurnSliceLimitExceededError, Fi as ToolActionRejectedError, Fn as JUNIOR_PERSONALITY, Fr as createPluginEgress, Gi as REPLY_TOOL_NAME, Gn as readAgentHistory, Hi as RISK_LEVELS, Hn as showsAgentsInstructions, Hr as abandonReplacedPendingAuth, Ii as ToolActionReviewLimitError, In as AGENTS_REMOVAL_NOTICE, Ir as PluginCredentialFailureError, Ji as remindMissingAnswer, Ki as isAnswerToolName, Kn as withAgentRequest, Kr as continuableMessages, Li as ToolActionReviewUnavailableError, Ln as AGENTS_REPLACEMENT_NOTICE, Lr as createPluginAuthOrchestration, Nr as getAgentContextCompactionTriggerTokens, Qi as sanitizeAssistantText, Qn as loadConversationSkillNames, Ri as createToolActionReview, Rn as buildAgentsInstructionsMessage, Rr as authorizationId, Si as loadTurnStart, Ti as TurnBudgetExceededError, Ui as ROOT_LINE_BREAK, Ur as canReusePendingAuthLink, Vi as restoreToolActionRejections, Vr as AuthorizationPauseError, W as resolveBotSlackTeamId, Wi as USER_AUTHORIZATION_LEVELS, Xi as decideReply, Xn as loadConnectedMcpProviders, Xr as saveTurnCheckpoint, Zi as getAssistantReplyText, aa as REPORT_BLOCKED_TOOL_NAME, an as turnRequestText, ar as recordGuardianActionReviewed, ct as isTurnInputCommitLostError, en as buildPromptInput, er as recordAgentsInstructionsUpdated, ia as CODE_MODE_CALL_STATUS_TEXT, in as loadPromptTurnContext, ir as recordAuthorizationRequested, it as TurnInputCommitLostError, ji as captureTurnFailure, ki as createTurnLimitGate, lr as recordToolExecutionStarted, m as isParentMessageAuthor, na as readNoReply, oa as readBlockedReport, or as recordMcpProviderConnected, qi as readTurnAnswer, qn as writeAgentHistory, qr as loadTurnCheckpoint, ra as CODEMODE_TOOL_NAME, rt as CooperativeTurnYieldError, sn as readTaskInstructions, sr as recordSkillLoaded, ta as isLegacyNoReplyMarker, tn as buildSteeringPiMessage, tr as recordAttachmentsDelivered, wi as TURN_LIMIT_WRAP_UP_MESSAGE, zi as reviewToolActions, zn as findVisibleAgentsInstructions, zr as AuthPausePersistenceError } from "./mailbox-turn-DL3Lvsm0.js";
|
|
13
|
+
import { At as automationContextToolSchema, Lt as ScheduleIntentError, Mt as automationTitleSchema, Nt as taskOutcomeInputSchema, Pt as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, Qt as buttonUserInputField, Rt as compileScheduleIntent, Tt as MAX_ATTACHMENT_BYTES, Xt as USER_INPUT_NOTE, Yt as USER_INPUT_LIMITS, jt as automationInstructionToolSchema, r as detectImageMediaType, tn as normalizeUserInputAnswer, un as automationTaskDescription, zt as scheduleIntentFromTool } from "./media-FYM-Bl3H.js";
|
|
14
|
+
import { t as getVercelConversationWorkQueue } from "./vercel-queue-nL0Hq3hr.js";
|
|
15
|
+
import { $ as createUpdateTodosTool, $t as createSlackConversationMessageSearchTool, A as createListWorkspacesTool, An as automationToolResultSchema, B as createSubmitFeedbackTool, Bn as requireToolCaller, Br as connectedState, C as createSwitchWorkspaceTool, Cn as createSearchAutomationsTool, D as prepareWorkspaceSnapshot, Dn as automationIdForToolCall, Dr as recordWarmupCost, Dt as createUpdateInboxItemTool, E as requireReadyWorkspaceSnapshot, En as AUTOMATIONS_TOOL_SOURCE, Er as recordIdlePeriodSavings, Et as createAddInboxItemTool, F as createWebFetchTool, Fn as triggerKind, Fr as breakerOpen, Ft as effectiveToolExposure, G as bm25InverseDocumentFrequency, Gn as changeAutomationLifecycle, Gr as IDLE_HORIZON_MS, H as createStopWatchingResourcesTool, Hn as requireToolDestination, Hr as sendWarmup, I as createWatchTimerTool, In as getConversationAccess, It as listedToolExposure, J as createSearchConversationsTool, Jr as NO_REPLY_GAP_MS, Jt as createSlackPublicSearchTool, K as bm25NormalizedFrequency, Kr as MINUTE_MS, L as createWatchEventsTool, Ln as automationToolContext, Lr as cacheTtlMs, Lt as planToolExposure, M as createWorkspaceTool, Mn as automationTriggerSchema, Mt as createRunOperatorSqlTool, N as workspaceProviderNames, Nn as editedAutomationTask, Nt as createListWatchesTool, On as automationSkillToolSchema, P as createWebSearchTool, Pn as newAutomationTask, Pr as KEY_PREFIX, Q as createBashTool, Qt as createSlackListAddItemsTool, R as createUserLookupTool, Rn as automationToolsDisabledReason, Rr as cachedPrefixTokens, Rt as createSetConversationSubscriptionTool, S as createUpdateWorkspaceTool, Sn as createCanvas, Tn as createDeleteAutomationTool, Tr as idlePeriodSavings, U as createSearchEventTypesTool, Ur as warmupTiming, V as createSystemTimeTool, Vn as requireToolCreator, Vr as providerCacheTtlMs, W as createSearchConversationEventsTool, Wn as automationEditor, Wr as warmupTooLate, Wt as createSlackThreadReadTool, X as createReadFileTool, Xt as createSlackListGetItemsTool, Y as createWriteFileTool, Yr as decideWarmup, Yt as createSlackListUpdateItemTool, Z as createEditFileTool, Zr as createTracedStreamFn, Zt as createSlackListCreateTool, _ as CONTEXT_COMPACTION_PROMPT_NAME, _n as isMissingPathError, a as recordModelCall, an as createSlackChannelJoinTool, ar as editScheduledAutomation, b as coreToolSlots, bn as resolveWorkspacePath, bt as createArchiveAgentTool, cn as createSlackCanvasWriteTool, cr as requireEventAutomationTrigger, ct as createSpawnAgentTool, d as compactWithPreparedSummary, dn as SLACK_TOOL_SOURCE, dr as requireAutomationSkill, dt as createReportBlockedTool, en as createSlackConversationSearchChannelPort, f as lastRequestInputSize, fn as buildCompactDiff, ft as createReplyTool, gn as validateAndApplyTextEdits, gr as resolveTaskOutcomes, h as createNextInputTracker, hn as stripBom, hr as moveTaskOutcomes, j as createDeleteWorkspaceTool, jn as automationTriggerChangesSchema, jr as incrementStat, jt as createReadConversationEventTool, k as resolveHandleMentions, kn as automationToolResult, ln as createSlackCanvasReadTool, lt as createListAgentsTool, m as requestBackgroundCompaction, mn as restoreLineEndings, mt as createMessageAgentTool, nt as createStopAgentTool, on as resolveSlackChannelRef, or as editEventAutomation, pn as detectLineEnding, pr as missingAutomationSkillReason, pt as createNoReplyTool, q as bm25Saturation, s as stopIdleWarmups, sn as slackChannelRefParam, sr as changedEventMatch, t as ANSWER_TOOL_ENDINGS, tn as createSlackChannelListMessagesTool, un as createSlackCanvasEditTool, ut as createReportProgressTool, v as buildAgentModelRequest, vn as normalizeToLf$1, vr as createSearchInboxItemsTool, w as ensureWorkspaceSnapshotBuild, wn as createRunAutomationNowTool, wr as idlePeriodOutcome, x as enabledMode, xn as createOperationKey, y as requestContextSummary, yn as positiveInteger$1, z as createUpdateUserCustomizationTool, zn as requireToolAutomation } from "./warmup-CCOuIwAS.js";
|
|
16
|
+
import { A as makeStructuredToolOutput, D as zodToolDefinition, E as zodTool, O as injectContinuationToolName, S as readSlackAttachmentSource, T as parseToolInput, a as readLeadUser, k as juniorToolOutputSchema, t as createStartConversationTool } from "./start-conversation-a4NXH4X9.js";
|
|
17
|
+
import { t as checkSlackChannelReadAccess } from "./channel-access-BOL29BG3.js";
|
|
18
|
+
import { c as storeAttachments, i as readLiveAttachment, l as storeDeferredAttachment, u as AttachmentSourceUnavailableError } from "./store-BuhF1QDm.js";
|
|
19
|
+
import { o as getSandboxResources, r as setSnapshotSpanAttributes } from "./install-OtFboxOM.js";
|
|
20
|
+
import { i as savedTurnMessages, r as isTurnMessage, t as resolveConversationRouting } from "./turn-session-routing-CZTRU8IY.js";
|
|
21
|
+
import { n as resolve$1 } from "./resolve-D8CPJcNK.js";
|
|
22
|
+
import { t as runWithSlackInstallation } from "./adapter-context-B4BrJZuS.js";
|
|
29
23
|
import { n as privateTraceResultAttributes } from "./private-trace-result-CE7_lEdq.js";
|
|
30
24
|
import * as z from "zod";
|
|
31
25
|
import pLimit from "p-limit";
|
|
@@ -33,8 +27,8 @@ import { streamSimple } from "@earendil-works/pi-ai/compat";
|
|
|
33
27
|
import path from "node:path";
|
|
34
28
|
import { createHash, randomBytes, randomInt, randomUUID } from "node:crypto";
|
|
35
29
|
import { isRetryableAssistantError } from "@earendil-works/pi-ai";
|
|
36
|
-
import { declaredEventKeys, escapeTagText, missingToolAnnotationKeys, ownedObjectAnnotationSchema, renderEmptyTag, renderInlineTag, renderTag } from "@sentry/junior-plugin-api";
|
|
37
|
-
import { and, eq, inArray, isNotNull, isNull, sql } from "drizzle-orm";
|
|
30
|
+
import { declaredEventKeys, escapeTagText, missingToolAnnotationKeys, objectFactFields, objectPresentation, ownedObjectAnnotationSchema, renderEmptyTag, renderInlineTag, renderTag } from "@sentry/junior-plugin-api";
|
|
31
|
+
import { and, eq, inArray, isNotNull, isNull, or, sql } from "drizzle-orm";
|
|
38
32
|
import { alias } from "drizzle-orm/pg-core";
|
|
39
33
|
import { Agent } from "@earendil-works/pi-agent-core";
|
|
40
34
|
import fs from "node:fs/promises";
|
|
@@ -1249,7 +1243,7 @@ function assertRunConsistency(run, conversationKind) {
|
|
|
1249
1243
|
case "scheduled_automation":
|
|
1250
1244
|
case "event_automation":
|
|
1251
1245
|
case "plugin_dispatch":
|
|
1252
|
-
case "
|
|
1246
|
+
case "parent_message": return;
|
|
1253
1247
|
}
|
|
1254
1248
|
const actor = run.dispatch?.actor ?? run.actor;
|
|
1255
1249
|
if (!actor || actor.platform === "system") return;
|
|
@@ -1418,7 +1412,7 @@ var SandboxFileNotFoundError = class extends ToolInputError {
|
|
|
1418
1412
|
/** Resolve model-provided sandbox paths against the sandbox workspace root. */
|
|
1419
1413
|
function normalizeSandboxPath(inputPath) {
|
|
1420
1414
|
const trimmed = inputPath.trim();
|
|
1421
|
-
if (!trimmed) throw new ToolInputError("path is required");
|
|
1415
|
+
if (!trimmed) throw new ToolInputError("path is required. Set path to a file path in the sandbox.");
|
|
1422
1416
|
if (path.posix.isAbsolute(trimmed)) return trimmed;
|
|
1423
1417
|
return path.posix.join(SANDBOX_WORKSPACE_ROOT, trimmed);
|
|
1424
1418
|
}
|
|
@@ -1477,8 +1471,8 @@ async function readSandboxFileUpload(workspace, input) {
|
|
|
1477
1471
|
const targetPath = normalizeSandboxPath(input.path);
|
|
1478
1472
|
const fileBuffer = await workspace.readFileToBuffer({ path: targetPath });
|
|
1479
1473
|
if (!fileBuffer) throw new SandboxFileNotFoundError(targetPath);
|
|
1480
|
-
if (fileBuffer.byteLength === 0) throw new ToolInputError(`file is empty: ${targetPath}
|
|
1481
|
-
if (fileBuffer.byteLength > 10485760) throw new ToolInputError(`file exceeds ${MAX_SANDBOX_FILE_UPLOAD_BYTES} bytes: ${targetPath} (${fileBuffer.byteLength} bytes)
|
|
1474
|
+
if (fileBuffer.byteLength === 0) throw new ToolInputError(`file is empty: ${targetPath}. Write content to the file first.`);
|
|
1475
|
+
if (fileBuffer.byteLength > 10485760) throw new ToolInputError(`file exceeds ${MAX_SANDBOX_FILE_UPLOAD_BYTES} bytes: ${targetPath} (${fileBuffer.byteLength} bytes). Make the file smaller, or split it into smaller files.`);
|
|
1482
1476
|
const resolvedFilename = sanitizeFilename(input.filename, targetPath);
|
|
1483
1477
|
const detectedMimeType = await detectMimeType(workspace, targetPath);
|
|
1484
1478
|
const resolvedMimeType = inferMimeType(resolvedFilename, input.mime_type ?? detectedMimeType);
|
|
@@ -2225,7 +2219,7 @@ function sliceFileContent(params) {
|
|
|
2225
2219
|
}
|
|
2226
2220
|
/** Reject an expected missing read target through the tool-error channel. */
|
|
2227
2221
|
function missingFileResult(path) {
|
|
2228
|
-
throw new ToolInputError(`File not found: ${path}
|
|
2222
|
+
throw new ToolInputError(`File not found: ${path}. Check the path, for example with ls in bash.`);
|
|
2229
2223
|
}
|
|
2230
2224
|
// src/chat/sandbox/edit-file.ts
|
|
2231
2225
|
/** Apply exact, ordered file replacements through the sandbox filesystem API. */
|
|
@@ -2235,7 +2229,7 @@ async function editFile(params) {
|
|
|
2235
2229
|
try {
|
|
2236
2230
|
rawContent = await params.fs.readFile(filePath, { encoding: "utf8" });
|
|
2237
2231
|
} catch (error) {
|
|
2238
|
-
if (isMissingPathError(error)) throw new ToolInputError(`File not found: ${params.path}
|
|
2232
|
+
if (isMissingPathError(error)) throw new ToolInputError(`File not found: ${params.path}. Check the path with bash, or create the file with writeFile.`, { cause: error });
|
|
2239
2233
|
throw error;
|
|
2240
2234
|
}
|
|
2241
2235
|
const { bom, text } = stripBom(rawContent);
|
|
@@ -3284,7 +3278,7 @@ function createSandbox(options) {
|
|
|
3284
3278
|
};
|
|
3285
3279
|
const executeReadFileTool = async (rawInput, context) => {
|
|
3286
3280
|
const filePath = String(rawInput["path"] ?? "").trim();
|
|
3287
|
-
if (!filePath) throw new ToolInputError("path is required");
|
|
3281
|
+
if (!filePath) throw new ToolInputError("path is required. Set path to a file path in the sandbox.");
|
|
3288
3282
|
const offset = positiveInteger$1(rawInput["offset"]);
|
|
3289
3283
|
const limit = positiveInteger$1(rawInput["limit"]);
|
|
3290
3284
|
if (!runtime.sandboxRef()) {
|
|
@@ -3340,7 +3334,7 @@ function createSandbox(options) {
|
|
|
3340
3334
|
};
|
|
3341
3335
|
const executeWriteFileTool = async (rawInput, context) => {
|
|
3342
3336
|
const filePath = String(rawInput["path"] ?? "").trim();
|
|
3343
|
-
if (!filePath) throw new ToolInputError("path is required");
|
|
3337
|
+
if (!filePath) throw new ToolInputError("path is required. Set path to a file path in the sandbox.");
|
|
3344
3338
|
const workspacePath = resolveWorkspacePath(filePath);
|
|
3345
3339
|
const content = String(rawInput["content"] ?? "");
|
|
3346
3340
|
logSandboxBootRequest("tool.writeFile", { "file.path": filePath });
|
|
@@ -3365,8 +3359,8 @@ function createSandbox(options) {
|
|
|
3365
3359
|
};
|
|
3366
3360
|
const executeEditFileTool = async (rawInput, context) => {
|
|
3367
3361
|
const filePath = String(rawInput["path"] ?? "").trim();
|
|
3368
|
-
if (!filePath) throw new ToolInputError("path is required");
|
|
3369
|
-
if (!Array.isArray(rawInput["edits"])) throw new ToolInputError("edits is required");
|
|
3362
|
+
if (!filePath) throw new ToolInputError("path is required. Set path to a file path in the sandbox.");
|
|
3363
|
+
if (!Array.isArray(rawInput["edits"])) throw new ToolInputError("edits is required. Set edits to a list of { old_text, new_text } replacements.");
|
|
3370
3364
|
logSandboxBootRequest("tool.editFile", { "file.path": filePath });
|
|
3371
3365
|
const fileSystem = await context.fileSystem();
|
|
3372
3366
|
return await withSandboxToolSpan("sandbox.editFile", "sandbox.fs.edit", {
|
|
@@ -3387,7 +3381,7 @@ function createSandbox(options) {
|
|
|
3387
3381
|
const context = createToolCallContext(params.signal);
|
|
3388
3382
|
const bashCommand = params.toolName === "bash" ? String(rawInput["command"] ?? "").trim() : void 0;
|
|
3389
3383
|
if (params.toolName === "bash") {
|
|
3390
|
-
if (!bashCommand) throw new ToolInputError("command is required");
|
|
3384
|
+
if (!bashCommand) throw new ToolInputError("command is required. Set command to the shell command to run.");
|
|
3391
3385
|
}
|
|
3392
3386
|
const finish = (result) => context.sandboxReplaced ? withSandboxReplacedNotice(result) : result;
|
|
3393
3387
|
try {
|
|
@@ -3441,7 +3435,7 @@ function createSandbox(options) {
|
|
|
3441
3435
|
},
|
|
3442
3436
|
workspace: {
|
|
3443
3437
|
createPreview: async (port) => await runWorkspaceOperation("workspace.createPreview", async (sandbox) => {
|
|
3444
|
-
if (!sandbox.createPreview) throw new ToolInputError("This sandbox provider cannot create previews.");
|
|
3438
|
+
if (!sandbox.createPreview) throw new ToolInputError("This sandbox provider cannot create previews. No change to the call can fix this; continue without a preview.");
|
|
3445
3439
|
return await sandbox.createPreview(port);
|
|
3446
3440
|
}),
|
|
3447
3441
|
readFileToBuffer: async (input) => await runWorkspaceOperation("workspace.readFileToBuffer", async (sandbox) => await sandbox.readFileToBuffer(input)),
|
|
@@ -3853,10 +3847,10 @@ async function readSandboxImage(path, readFile, maxBytes) {
|
|
|
3853
3847
|
const targetPath = normalizeSandboxPath(path);
|
|
3854
3848
|
const data = await readFile(targetPath);
|
|
3855
3849
|
if (!data) throw new SandboxFileNotFoundError(targetPath);
|
|
3856
|
-
if (data.byteLength === 0) throw new ToolInputError(`image file is empty: ${targetPath}
|
|
3850
|
+
if (data.byteLength === 0) throw new ToolInputError(`image file is empty: ${targetPath}. Write the image first.`);
|
|
3857
3851
|
if (data.byteLength > maxBytes) throw new ToolInputError(`image exceeds ${maxBytes} bytes: ${targetPath} (${data.byteLength} bytes). Make the image smaller first.`);
|
|
3858
3852
|
const mimeType = detectImageMediaType(data);
|
|
3859
|
-
if (!mimeType) throw new ToolInputError(`not a readable image: ${targetPath} exists, but its content is not PNG, JPEG, GIF, or WebP data
|
|
3853
|
+
if (!mimeType) throw new ToolInputError(`not a readable image: ${targetPath} exists, but its content is not PNG, JPEG, GIF, or WebP data. Pass the path of a PNG, JPEG, GIF, or WebP file.`);
|
|
3860
3854
|
return {
|
|
3861
3855
|
data,
|
|
3862
3856
|
mimeType
|
|
@@ -4246,8 +4240,8 @@ function createTranscribeAudioTool(args) {
|
|
|
4246
4240
|
conversationId: args.conversationId,
|
|
4247
4241
|
db: args.db
|
|
4248
4242
|
});
|
|
4249
|
-
if (!attachment || attachment.storageProvider !== args.storage.provider) throw new ToolInputError("Attachment not found in this conversation.");
|
|
4250
|
-
if (!mayHaveAudio(attachment.contentType)) throw new ToolInputError(`This attachment is ${attachment.contentType}, not audio or video.`);
|
|
4243
|
+
if (!attachment || attachment.storageProvider !== args.storage.provider) throw new ToolInputError("Attachment not found in this conversation. Use an attachment_id from the attachment context or a Slack read result.");
|
|
4244
|
+
if (!mayHaveAudio(attachment.contentType)) throw new ToolInputError(`This attachment is ${attachment.contentType}, not audio or video. Use loadAttachment to read other files.`);
|
|
4251
4245
|
const { storageKey } = await storeAttachmentOnFirstUse({
|
|
4252
4246
|
attachment,
|
|
4253
4247
|
db: args.db,
|
|
@@ -4456,32 +4450,6 @@ function createLoadSkillTool(availableSkills, options) {
|
|
|
4456
4450
|
}
|
|
4457
4451
|
});
|
|
4458
4452
|
}
|
|
4459
|
-
// src/chat/tool-exposure.ts
|
|
4460
|
-
/** Return the runtime exposure for a tool, preserving direct compatibility. */
|
|
4461
|
-
function effectiveToolExposure(definition) {
|
|
4462
|
-
return definition.exposure ?? "direct";
|
|
4463
|
-
}
|
|
4464
|
-
const EXPOSURE_TABLES = {
|
|
4465
|
-
direct: [
|
|
4466
|
-
"directTools",
|
|
4467
|
-
"catalogTools",
|
|
4468
|
-
"scriptTools"
|
|
4469
|
-
],
|
|
4470
|
-
deferred: ["catalogTools", "scriptTools"],
|
|
4471
|
-
modelOnly: ["directTools"],
|
|
4472
|
-
codemode: ["scriptTools"],
|
|
4473
|
-
hidden: []
|
|
4474
|
-
};
|
|
4475
|
-
/** Plan which callers may call each tool. `ToolExposure` owns the rules. */
|
|
4476
|
-
function planToolExposure(tools) {
|
|
4477
|
-
const planned = {
|
|
4478
|
-
catalogTools: {},
|
|
4479
|
-
directTools: {},
|
|
4480
|
-
scriptTools: {}
|
|
4481
|
-
};
|
|
4482
|
-
for (const [name, definition] of Object.entries(tools)) for (const table of EXPOSURE_TABLES[effectiveToolExposure(definition)]) planned[table][name] = definition;
|
|
4483
|
-
return planned;
|
|
4484
|
-
}
|
|
4485
4453
|
// src/chat/tool-support/catalog-search.ts
|
|
4486
4454
|
const SEARCH_TOOLS_NAME = "searchTools";
|
|
4487
4455
|
const MODEL_VISIBLE_DESCRIPTION_CAP = 180;
|
|
@@ -5012,7 +4980,7 @@ function createViewImageTool(sandbox, supportsImageInput, deps = {}) {
|
|
|
5012
4980
|
exposure: "direct",
|
|
5013
4981
|
inputSchema: viewImageInputSchema,
|
|
5014
4982
|
async execute({ path }) {
|
|
5015
|
-
if (!supportsImageInput()) throw new ToolInputError("viewImage is unavailable because the current model does not support image inputs");
|
|
4983
|
+
if (!supportsImageInput()) throw new ToolInputError("viewImage is unavailable because the current model does not support image inputs. No change to the call can fix this in this Turn.");
|
|
5016
4984
|
const image = await readSandboxImage(path, deps.readFile ?? ((targetPath) => sandbox.readFileToBuffer({ path: targetPath })), MAX_VIEW_IMAGE_BYTES);
|
|
5017
4985
|
return { content: [{
|
|
5018
4986
|
type: "image",
|
|
@@ -5045,7 +5013,7 @@ function createSlackMessageAddReactionTool(context, state) {
|
|
|
5045
5013
|
execute: async ({ emoji }) => {
|
|
5046
5014
|
const targetChannelId = context.messageChannelId;
|
|
5047
5015
|
const targetMessageTs = context.messageTs;
|
|
5048
|
-
if (!targetChannelId || !targetMessageTs) throw new ToolInputError("No active Slack message is available for reactions.");
|
|
5016
|
+
if (!targetChannelId || !targetMessageTs) throw new ToolInputError("No active Slack message is available for reactions. No change to the call can fix this in this Turn.");
|
|
5049
5017
|
const normalizedEmoji = normalizeSlackEmojiName(emoji);
|
|
5050
5018
|
if (!normalizedEmoji) throw new ToolInputError("Emoji must be a valid Slack emoji alias name (for example `thumbsup` or `thumbsup::skin-tone-6`).");
|
|
5051
5019
|
const operationKey = createOperationKey("addReaction", {
|
|
@@ -5089,12 +5057,15 @@ async function pauseConversationDelivery(conversationId) {
|
|
|
5089
5057
|
detailVersion: nextDetailVersion
|
|
5090
5058
|
}).where(and(rootConversation(conversationId), isNull(juniorConversations.deliveryPausedAt))).returning({ conversationId: juniorConversations.conversationId })).length > 0;
|
|
5091
5059
|
}
|
|
5092
|
-
/**
|
|
5060
|
+
/**
|
|
5061
|
+
* Deliver a root's Event Turn replies to its Location again. Returns false
|
|
5062
|
+
* when Delivery was not paused or the root does not exist.
|
|
5063
|
+
*/
|
|
5093
5064
|
async function resumeConversationDelivery(conversationId) {
|
|
5094
|
-
await getSqlExecutor().db().update(juniorConversations).set({
|
|
5065
|
+
return (await getSqlExecutor().db().update(juniorConversations).set({
|
|
5095
5066
|
deliveryPausedAt: null,
|
|
5096
5067
|
detailVersion: nextDetailVersion
|
|
5097
|
-
}).where(and(rootConversation(conversationId), isNotNull(juniorConversations.deliveryPausedAt)));
|
|
5068
|
+
}).where(and(rootConversation(conversationId), isNotNull(juniorConversations.deliveryPausedAt))).returning({ conversationId: juniorConversations.conversationId })).length > 0;
|
|
5098
5069
|
}
|
|
5099
5070
|
/**
|
|
5100
5071
|
* True while the root of this Conversation is detached from its Location.
|
|
@@ -5105,6 +5076,466 @@ async function isConversationDeliveryPaused(conversationId) {
|
|
|
5105
5076
|
const [row] = await getSqlExecutor().db().select({ pausedAt: root.deliveryPausedAt }).from(juniorConversations).innerJoin(root, eq(root.conversationId, sql`coalesce(${juniorConversations.rootConversationId}, ${juniorConversations.conversationId})`)).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
|
|
5106
5077
|
return Boolean(row?.pausedAt);
|
|
5107
5078
|
}
|
|
5079
|
+
// src/chat/slack/annotation-ref.ts
|
|
5080
|
+
const KEY_DIGEST_LENGTH = 22;
|
|
5081
|
+
const legacyRefSchema = z.tuple([
|
|
5082
|
+
z.string().min(1),
|
|
5083
|
+
z.string().min(1),
|
|
5084
|
+
z.string().min(1)
|
|
5085
|
+
]);
|
|
5086
|
+
function decodeLegacyAnnotationRef(id) {
|
|
5087
|
+
try {
|
|
5088
|
+
return legacyRefSchema.safeParse(JSON.parse(Buffer.from(id, "base64url").toString("utf8"))).data;
|
|
5089
|
+
} catch {
|
|
5090
|
+
return;
|
|
5091
|
+
}
|
|
5092
|
+
}
|
|
5093
|
+
/** Return the fixed-size digest that identifies one annotation in a reference. */
|
|
5094
|
+
function annotationKeyDigest(plugin, key) {
|
|
5095
|
+
return createHash("sha256").update(JSON.stringify([plugin, key])).digest("base64url").slice(0, KEY_DIGEST_LENGTH);
|
|
5096
|
+
}
|
|
5097
|
+
/**
|
|
5098
|
+
* Build the Slack `external_ref.id` for an annotation, or null when the
|
|
5099
|
+
* Conversation ID is too long for Slack's limit.
|
|
5100
|
+
*/
|
|
5101
|
+
function encodeAnnotationRef(conversationId, plugin, key) {
|
|
5102
|
+
const id = annotationKeyDigest(plugin, key) + Buffer.from(conversationId, "utf8").toString("base64url");
|
|
5103
|
+
return slackExternalRefIdSchema.safeParse(id).success ? id : null;
|
|
5104
|
+
}
|
|
5105
|
+
/**
|
|
5106
|
+
* Split a current or legacy annotation `external_ref.id` into its
|
|
5107
|
+
* Conversation ID and key digest.
|
|
5108
|
+
*/
|
|
5109
|
+
function decodeAnnotationRef(id) {
|
|
5110
|
+
const legacy = decodeLegacyAnnotationRef(id);
|
|
5111
|
+
if (legacy) {
|
|
5112
|
+
const [conversationId, plugin, key] = legacy;
|
|
5113
|
+
return {
|
|
5114
|
+
conversationId,
|
|
5115
|
+
keyDigest: annotationKeyDigest(plugin, key)
|
|
5116
|
+
};
|
|
5117
|
+
}
|
|
5118
|
+
const keyDigest = id.slice(0, KEY_DIGEST_LENGTH);
|
|
5119
|
+
const encoded = id.slice(KEY_DIGEST_LENGTH);
|
|
5120
|
+
const conversationId = Buffer.from(encoded, "base64url").toString("utf8");
|
|
5121
|
+
if (!conversationId || Buffer.from(conversationId, "utf8").toString("base64url") !== encoded) return null;
|
|
5122
|
+
return {
|
|
5123
|
+
conversationId,
|
|
5124
|
+
keyDigest
|
|
5125
|
+
};
|
|
5126
|
+
}
|
|
5127
|
+
// src/chat/slack/automation-card.ts
|
|
5128
|
+
function preview(text, length) {
|
|
5129
|
+
const compact = text.replace(/\s+/g, " ").trim();
|
|
5130
|
+
return compact.length > length ? `${compact.slice(0, length - 1)}…` : compact;
|
|
5131
|
+
}
|
|
5132
|
+
/** Show an Automation as a native Work Object, not an operation receipt. */
|
|
5133
|
+
function renderSlackAutomationCard(card) {
|
|
5134
|
+
const title = preview(card.title, 160);
|
|
5135
|
+
const iconUrl = getDashboardObjectIconLink("workflow");
|
|
5136
|
+
const trigger = preview(card.trigger, 500);
|
|
5137
|
+
const warning = card.warning ? preview(card.warning, 500) : null;
|
|
5138
|
+
const text = [
|
|
5139
|
+
"Automation",
|
|
5140
|
+
card.url ? formatSlackLink(card.url, title) : escapeSlackMrkdwnText(title),
|
|
5141
|
+
escapeSlackMrkdwnText(trigger),
|
|
5142
|
+
warning ? escapeSlackMrkdwnText(warning) : null
|
|
5143
|
+
].filter(Boolean).join("\n");
|
|
5144
|
+
if (!card.url) return {
|
|
5145
|
+
entity: null,
|
|
5146
|
+
text
|
|
5147
|
+
};
|
|
5148
|
+
return {
|
|
5149
|
+
text,
|
|
5150
|
+
entity: {
|
|
5151
|
+
entity_type: "slack#/entities/item",
|
|
5152
|
+
external_ref: {
|
|
5153
|
+
id: card.id,
|
|
5154
|
+
type: "automation"
|
|
5155
|
+
},
|
|
5156
|
+
url: card.url,
|
|
5157
|
+
entity_payload: {
|
|
5158
|
+
attributes: {
|
|
5159
|
+
title: { text: title },
|
|
5160
|
+
display_type: "Automation",
|
|
5161
|
+
product_icon: iconUrl ? {
|
|
5162
|
+
url: iconUrl,
|
|
5163
|
+
alt_text: "Automation"
|
|
5164
|
+
} : void 0
|
|
5165
|
+
},
|
|
5166
|
+
custom_fields: [{
|
|
5167
|
+
key: "trigger",
|
|
5168
|
+
label: "When",
|
|
5169
|
+
type: "string",
|
|
5170
|
+
value: trigger,
|
|
5171
|
+
long: true
|
|
5172
|
+
}, ...warning ? [{
|
|
5173
|
+
key: "warning",
|
|
5174
|
+
label: "Needs attention",
|
|
5175
|
+
type: "string",
|
|
5176
|
+
value: warning,
|
|
5177
|
+
long: true
|
|
5178
|
+
}] : []]
|
|
5179
|
+
}
|
|
5180
|
+
}
|
|
5181
|
+
};
|
|
5182
|
+
}
|
|
5183
|
+
// src/chat/slack/object-card.ts
|
|
5184
|
+
function descriptionPreview(value) {
|
|
5185
|
+
const text = value?.replace(/\r\n/g, "\n").trim() ?? "";
|
|
5186
|
+
const preview = text.split("\n").slice(0, 6).join("\n").slice(0, 500);
|
|
5187
|
+
return preview.length < text.length ? `${preview.slice(0, 499).trimEnd()}…` : preview;
|
|
5188
|
+
}
|
|
5189
|
+
/** Render a compact Task or Item preview, or the saved facts for its detail panel. */
|
|
5190
|
+
function renderSlackObjectCard(card, conversationId, surface = "preview") {
|
|
5191
|
+
if (card.objectType === "automation" && card.plugin === "junior") return renderSlackAutomationCard({
|
|
5192
|
+
id: card.key,
|
|
5193
|
+
title: card.title,
|
|
5194
|
+
url: card.url,
|
|
5195
|
+
trigger: card.trigger ?? "",
|
|
5196
|
+
warning: card.warning ?? null
|
|
5197
|
+
});
|
|
5198
|
+
const presentation = objectPresentation(card);
|
|
5199
|
+
const type = card.displayType ?? presentation.label;
|
|
5200
|
+
const iconUrl = getDashboardObjectIconLink(presentation.icon);
|
|
5201
|
+
const title = card.title.slice(0, 160);
|
|
5202
|
+
const details = surface === "details";
|
|
5203
|
+
const deployment = card.objectType === "deployment" || card.objectType === "item" && card.facts?.type === "deployment";
|
|
5204
|
+
const calendarEvent = card.objectType === "calendar_event";
|
|
5205
|
+
const status = details || deployment || calendarEvent ? card.status : void 0;
|
|
5206
|
+
const warning = details || deployment ? card.warning : void 0;
|
|
5207
|
+
const facts = objectFactFields(card.facts).filter((field) => details || calendarEvent || deployment && field.key === "environment");
|
|
5208
|
+
const description = details ? card.description?.trim() ?? "" : calendarEvent ? "" : descriptionPreview(card.description);
|
|
5209
|
+
const text = [
|
|
5210
|
+
escapeSlackMrkdwnText(type),
|
|
5211
|
+
card.url ? formatSlackLink(card.url, title) : escapeSlackMrkdwnText(title),
|
|
5212
|
+
escapeSlackMrkdwnText(card.label),
|
|
5213
|
+
status ? escapeSlackMrkdwnText(status) : null,
|
|
5214
|
+
description ? escapeSlackMrkdwnText(description) : null,
|
|
5215
|
+
warning ? escapeSlackMrkdwnText(`Needs attention: ${warning}`) : null,
|
|
5216
|
+
...facts.map((field) => escapeSlackMrkdwnText(`${field.label}: ${field.value}`))
|
|
5217
|
+
].filter(Boolean).join("\n");
|
|
5218
|
+
const refId = encodeAnnotationRef(conversationId, card.plugin, card.key);
|
|
5219
|
+
if (!card.url || !refId) return {
|
|
5220
|
+
entity: null,
|
|
5221
|
+
text
|
|
5222
|
+
};
|
|
5223
|
+
const task = card.objectType === "task";
|
|
5224
|
+
const attributes = {
|
|
5225
|
+
title: { text: title },
|
|
5226
|
+
display_id: card.label,
|
|
5227
|
+
display_type: type,
|
|
5228
|
+
product_icon: iconUrl ? {
|
|
5229
|
+
url: iconUrl,
|
|
5230
|
+
alt_text: `${type}${status ? `: ${status}` : ""}`
|
|
5231
|
+
} : void 0,
|
|
5232
|
+
product_name: card.plugin
|
|
5233
|
+
};
|
|
5234
|
+
const customFields = [
|
|
5235
|
+
...description ? [{
|
|
5236
|
+
key: "description",
|
|
5237
|
+
label: "Description",
|
|
5238
|
+
type: "string",
|
|
5239
|
+
value: description,
|
|
5240
|
+
long: true,
|
|
5241
|
+
format: "markdown"
|
|
5242
|
+
}] : [],
|
|
5243
|
+
...facts.map((field) => ({
|
|
5244
|
+
...field,
|
|
5245
|
+
type: "string"
|
|
5246
|
+
})),
|
|
5247
|
+
...warning ? [{
|
|
5248
|
+
key: "warning",
|
|
5249
|
+
label: "Needs attention",
|
|
5250
|
+
type: "string",
|
|
5251
|
+
value: warning
|
|
5252
|
+
}] : []
|
|
5253
|
+
];
|
|
5254
|
+
return {
|
|
5255
|
+
text,
|
|
5256
|
+
entity: {
|
|
5257
|
+
...task ? {
|
|
5258
|
+
entity_type: "slack#/entities/task",
|
|
5259
|
+
entity_payload: {
|
|
5260
|
+
attributes,
|
|
5261
|
+
display_order: [...status ? ["status"] : [], ...customFields.map((field) => field.key)],
|
|
5262
|
+
fields: status ? { status: { value: status } } : void 0,
|
|
5263
|
+
custom_fields: customFields
|
|
5264
|
+
}
|
|
5265
|
+
} : {
|
|
5266
|
+
entity_type: "slack#/entities/item",
|
|
5267
|
+
entity_payload: {
|
|
5268
|
+
attributes,
|
|
5269
|
+
display_order: [...status ? ["status"] : [], ...customFields.map((field) => field.key)],
|
|
5270
|
+
custom_fields: [...status ? [{
|
|
5271
|
+
key: "status",
|
|
5272
|
+
label: "Status",
|
|
5273
|
+
type: "string",
|
|
5274
|
+
value: status
|
|
5275
|
+
}] : [], ...customFields]
|
|
5276
|
+
}
|
|
5277
|
+
},
|
|
5278
|
+
external_ref: {
|
|
5279
|
+
id: refId,
|
|
5280
|
+
type: "annotation"
|
|
5281
|
+
},
|
|
5282
|
+
url: card.url
|
|
5283
|
+
}
|
|
5284
|
+
};
|
|
5285
|
+
}
|
|
5286
|
+
// src/chat/slack/cards.ts
|
|
5287
|
+
/** Select the Slack object renderer for a built-in card. */
|
|
5288
|
+
function renderSlackCard(card, conversationId) {
|
|
5289
|
+
switch (card.kind) {
|
|
5290
|
+
case "object": return renderSlackObjectCard(card, conversationId);
|
|
5291
|
+
case "automation": return renderSlackAutomationCard(card);
|
|
5292
|
+
}
|
|
5293
|
+
}
|
|
5294
|
+
// src/chat/slack/footer.ts
|
|
5295
|
+
/** Render compact reply attribution for the Slack footer. */
|
|
5296
|
+
function formatReplyAttribution(attribution) {
|
|
5297
|
+
return attribution.detail ? `${attribution.label} · ${attribution.detail}` : attribution.label;
|
|
5298
|
+
}
|
|
5299
|
+
/**
|
|
5300
|
+
* Build the compact conversation footer for visible Slack reply surfaces.
|
|
5301
|
+
*
|
|
5302
|
+
* Detailed turn metrics stay in the dashboard instead of Slack-visible copy.
|
|
5303
|
+
*/
|
|
5304
|
+
function buildSlackReplyFooter(args) {
|
|
5305
|
+
const items = [];
|
|
5306
|
+
const conversationId = args.conversationId?.trim();
|
|
5307
|
+
if (conversationId) {
|
|
5308
|
+
const idItem = {
|
|
5309
|
+
label: "ID",
|
|
5310
|
+
value: conversationId
|
|
5311
|
+
};
|
|
5312
|
+
const conversationUrl = getPluginSlackConversationLink(conversationId)?.url ?? getDashboardConversationLink(conversationId) ?? buildSentryConversationUrl(conversationId);
|
|
5313
|
+
if (conversationUrl) idItem.url = conversationUrl;
|
|
5314
|
+
items.push(idItem);
|
|
5315
|
+
}
|
|
5316
|
+
return items.length > 0 || args.replyAttribution ? {
|
|
5317
|
+
...args.replyAttribution ? { attribution: args.replyAttribution } : void 0,
|
|
5318
|
+
items
|
|
5319
|
+
} : void 0;
|
|
5320
|
+
}
|
|
5321
|
+
/** Build Slack blocks for a reply chunk using the Slack-flavored markdown block for the body. */
|
|
5322
|
+
function buildSlackReplyBlocks(text, footer) {
|
|
5323
|
+
const blocks = text.trim() ? [{
|
|
5324
|
+
type: "markdown",
|
|
5325
|
+
text
|
|
5326
|
+
}] : [];
|
|
5327
|
+
if (footer && (footer.attribution || footer.items.length > 0)) {
|
|
5328
|
+
const attributionElements = footer.attribution ? [{
|
|
5329
|
+
type: "plain_text",
|
|
5330
|
+
text: formatReplyAttribution(footer.attribution)
|
|
5331
|
+
}] : [];
|
|
5332
|
+
blocks.push({
|
|
5333
|
+
type: "context",
|
|
5334
|
+
elements: [...attributionElements, ...footer.items.map((item) => ({
|
|
5335
|
+
type: "mrkdwn",
|
|
5336
|
+
text: item.url ? `*${escapeSlackMrkdwnText(item.label)}:* ${formatSlackLink(item.url, item.value)}` : `*${escapeSlackMrkdwnText(item.label)}:* ${escapeSlackMrkdwnText(item.value)}`
|
|
5337
|
+
}))]
|
|
5338
|
+
});
|
|
5339
|
+
}
|
|
5340
|
+
return blocks.length ? blocks : void 0;
|
|
5341
|
+
}
|
|
5342
|
+
// src/chat/slack/output.ts
|
|
5343
|
+
const MAX_INLINE_CHARS = 4e3;
|
|
5344
|
+
function getFenceContinuation(text) {
|
|
5345
|
+
let open;
|
|
5346
|
+
for (const line of text.split("\n")) {
|
|
5347
|
+
const trimmed = line.trimStart();
|
|
5348
|
+
const openerMatch = trimmed.match(/^(`{3,}|~{3,})(.*)$/);
|
|
5349
|
+
if (!openerMatch?.[1]) continue;
|
|
5350
|
+
if (!open) {
|
|
5351
|
+
open = {
|
|
5352
|
+
fence: openerMatch[1],
|
|
5353
|
+
openerLine: trimmed
|
|
5354
|
+
};
|
|
5355
|
+
continue;
|
|
5356
|
+
}
|
|
5357
|
+
if (new RegExp(`^${open.fence}\\s*$`).test(trimmed)) open = void 0;
|
|
5358
|
+
}
|
|
5359
|
+
if (!open) return null;
|
|
5360
|
+
return {
|
|
5361
|
+
closeSuffix: text.endsWith("\n") ? open.fence : `\n${open.fence}`,
|
|
5362
|
+
reopenPrefix: `${open.openerLine}\n`
|
|
5363
|
+
};
|
|
5364
|
+
}
|
|
5365
|
+
function findSplitIndex(text, maxChars) {
|
|
5366
|
+
const bounded = text.slice(0, maxChars);
|
|
5367
|
+
const newlineIndex = bounded.lastIndexOf("\n");
|
|
5368
|
+
if (newlineIndex > 0) return newlineIndex;
|
|
5369
|
+
const spaceIndex = bounded.lastIndexOf(" ");
|
|
5370
|
+
if (spaceIndex > 0) return spaceIndex;
|
|
5371
|
+
return maxChars;
|
|
5372
|
+
}
|
|
5373
|
+
function takePrefix(text, maxChars) {
|
|
5374
|
+
const prefix = text.slice(0, findSplitIndex(text, maxChars)).trimEnd() || text.slice(0, maxChars);
|
|
5375
|
+
return {
|
|
5376
|
+
prefix,
|
|
5377
|
+
rest: text.slice(prefix.length).trimStart()
|
|
5378
|
+
};
|
|
5379
|
+
}
|
|
5380
|
+
/**
|
|
5381
|
+
* Keep a pipe table readable when a split lands inside it. Each post renders
|
|
5382
|
+
* on its own, so rows without the header and delimiter rows show as text.
|
|
5383
|
+
* Move a table that starts mid-post to the next post. Repeat the header rows
|
|
5384
|
+
* when one table is longer than a post.
|
|
5385
|
+
*/
|
|
5386
|
+
function splitOutsideTable(text, prefix, rest) {
|
|
5387
|
+
const lines = prefix.split("\n");
|
|
5388
|
+
const gap = text.slice(prefix.length, text.length - rest.length);
|
|
5389
|
+
if (!isTableRow(lines.at(-1) ?? "") || !isTableRow(rest) || /\n\s*\n/.test(gap)) return {
|
|
5390
|
+
chunk: prefix,
|
|
5391
|
+
rest
|
|
5392
|
+
};
|
|
5393
|
+
let start = lines.length - 1;
|
|
5394
|
+
while (start > 0 && isTableRow(lines[start - 1] ?? "")) start--;
|
|
5395
|
+
const before = lines.slice(0, start).join("\n").trimEnd();
|
|
5396
|
+
const table = lines.slice(start);
|
|
5397
|
+
if (before) return {
|
|
5398
|
+
chunk: before,
|
|
5399
|
+
rest: `${table.join("\n")}\n${rest}`
|
|
5400
|
+
};
|
|
5401
|
+
if (table.length <= 2) return {
|
|
5402
|
+
chunk: prefix,
|
|
5403
|
+
rest
|
|
5404
|
+
};
|
|
5405
|
+
return {
|
|
5406
|
+
chunk: prefix,
|
|
5407
|
+
rest: `${table.slice(0, 2).join("\n")}\n${rest}`
|
|
5408
|
+
};
|
|
5409
|
+
}
|
|
5410
|
+
/** Take one post that fits the budget, closing a code fence it leaves open. */
|
|
5411
|
+
function takeChunk(text) {
|
|
5412
|
+
let { prefix, rest } = takePrefix(text, MAX_INLINE_CHARS);
|
|
5413
|
+
let carryover = getFenceContinuation(prefix);
|
|
5414
|
+
if (!carryover) return splitOutsideTable(text, prefix, rest);
|
|
5415
|
+
({prefix, rest} = takePrefix(text, MAX_INLINE_CHARS - carryover.closeSuffix.length));
|
|
5416
|
+
carryover = getFenceContinuation(prefix);
|
|
5417
|
+
if (!carryover || !rest) return {
|
|
5418
|
+
chunk: prefix,
|
|
5419
|
+
rest
|
|
5420
|
+
};
|
|
5421
|
+
return {
|
|
5422
|
+
chunk: `${prefix}${carryover.closeSuffix}`,
|
|
5423
|
+
rest: `${carryover.reopenPrefix}${rest}`
|
|
5424
|
+
};
|
|
5425
|
+
}
|
|
5426
|
+
/** Split a normalized Slack reply into thread posts that fit Slack limits. */
|
|
5427
|
+
function splitSlackReplyText(text, format) {
|
|
5428
|
+
const chunks = [];
|
|
5429
|
+
let remaining = normalizeSlackReplyMarkdown(text, format);
|
|
5430
|
+
while (remaining.length > MAX_INLINE_CHARS) {
|
|
5431
|
+
const { chunk, rest } = takeChunk(remaining);
|
|
5432
|
+
chunks.push(chunk);
|
|
5433
|
+
remaining = rest;
|
|
5434
|
+
}
|
|
5435
|
+
if (remaining) chunks.push(remaining);
|
|
5436
|
+
return chunks;
|
|
5437
|
+
}
|
|
5438
|
+
// src/chat/slack/reply.ts
|
|
5439
|
+
/**
|
|
5440
|
+
* Resolve where a Turn posts in Slack.
|
|
5441
|
+
*
|
|
5442
|
+
* The channel is always the Destination channel. The thread comes from the
|
|
5443
|
+
* Turn Source, then the Conversation Location, then the Destination, and each
|
|
5444
|
+
* one counts only when it names that channel. Do not derive the target from
|
|
5445
|
+
* the Conversation id: an Automation or Watch Conversation can own a Slack
|
|
5446
|
+
* thread, and its id is not a Slack thread id.
|
|
5447
|
+
*/
|
|
5448
|
+
function resolveSlackReplyTarget(args) {
|
|
5449
|
+
const { channelId } = args.destination;
|
|
5450
|
+
const sourceThreadTs = args.source?.kind === "slack" && args.source.channelId === channelId ? args.source.threadTs : void 0;
|
|
5451
|
+
const locationThreadTs = args.location?.provider === "slack" && args.location.channelId === channelId ? args.location.threadTs : void 0;
|
|
5452
|
+
const threadTs = sourceThreadTs ?? locationThreadTs ?? args.destination.threadTs;
|
|
5453
|
+
return {
|
|
5454
|
+
channelId,
|
|
5455
|
+
...threadTs ? { threadTs } : void 0
|
|
5456
|
+
};
|
|
5457
|
+
}
|
|
5458
|
+
/** Resolve known people for plugin formatting. Fails open, like the hooks. */
|
|
5459
|
+
async function resolveReplyMentions(text, teamId) {
|
|
5460
|
+
try {
|
|
5461
|
+
return await resolveHandleMentions(text, teamId);
|
|
5462
|
+
} catch (error) {
|
|
5463
|
+
logWarn("slack.reply.mentions.failed", { "exception.message": error instanceof Error ? error.message : String(error) });
|
|
5464
|
+
return;
|
|
5465
|
+
}
|
|
5466
|
+
}
|
|
5467
|
+
/**
|
|
5468
|
+
* Send one destination-visible Slack reply.
|
|
5469
|
+
*
|
|
5470
|
+
* Chunks oversized text, builds compact attribution and conversation footer
|
|
5471
|
+
* context, and posts through the shared Slack outbound boundary. Pass
|
|
5472
|
+
* `formatting` for agent replies so plugin formatting can use Location
|
|
5473
|
+
* defaults, such as a default repository, and mention known people.
|
|
5474
|
+
*/
|
|
5475
|
+
async function sendSlackReply(args) {
|
|
5476
|
+
const format = args.formatting && {
|
|
5477
|
+
configuration: args.formatting.configuration,
|
|
5478
|
+
mentions: await resolveReplyMentions(args.text, args.formatting.teamId)
|
|
5479
|
+
};
|
|
5480
|
+
const posts = splitSlackReplyText(args.text, format).map((text) => ({
|
|
5481
|
+
text,
|
|
5482
|
+
cards: []
|
|
5483
|
+
}));
|
|
5484
|
+
const groups = [];
|
|
5485
|
+
for (const card of args.cards ?? []) {
|
|
5486
|
+
const rendered = renderSlackCard(card, args.conversationId);
|
|
5487
|
+
const slackCard = rendered.entity && !fitsSlackMetadataLimit([rendered.entity]) ? {
|
|
5488
|
+
entity: null,
|
|
5489
|
+
text: rendered.text
|
|
5490
|
+
} : rendered;
|
|
5491
|
+
const group = groups.at(-1);
|
|
5492
|
+
const entities = [...group ?? [], slackCard].flatMap((item) => item.entity ? [item.entity] : []);
|
|
5493
|
+
if (group && group.length < 5 && fitsSlackMetadataLimit(entities)) group.push(slackCard);
|
|
5494
|
+
else groups.push([slackCard]);
|
|
5495
|
+
}
|
|
5496
|
+
for (const [index, group] of groups.entries()) {
|
|
5497
|
+
const lastPost = posts.at(-1);
|
|
5498
|
+
if (index === 0 && lastPost) lastPost.cards = group;
|
|
5499
|
+
else posts.push({
|
|
5500
|
+
text: "",
|
|
5501
|
+
cards: group
|
|
5502
|
+
});
|
|
5503
|
+
}
|
|
5504
|
+
const footer = buildSlackReplyFooter({
|
|
5505
|
+
conversationId: args.conversationId,
|
|
5506
|
+
replyAttribution: args.replyAttribution
|
|
5507
|
+
});
|
|
5508
|
+
const messageTs = [];
|
|
5509
|
+
let threadTs = args.threadTs;
|
|
5510
|
+
for (const [index, post] of posts.entries()) {
|
|
5511
|
+
const { text, cards } = post;
|
|
5512
|
+
const isFinalChunk = index === posts.length - 1;
|
|
5513
|
+
const blocks = buildSlackReplyBlocks(text, void 0) ?? [];
|
|
5514
|
+
for (const card of cards) if (!card.entity) blocks.push({
|
|
5515
|
+
type: "section",
|
|
5516
|
+
text: {
|
|
5517
|
+
type: "mrkdwn",
|
|
5518
|
+
text: card.text
|
|
5519
|
+
}
|
|
5520
|
+
});
|
|
5521
|
+
if (isFinalChunk || !text.trim()) blocks.push(...buildSlackReplyBlocks("", footer) ?? []);
|
|
5522
|
+
const entities = cards.flatMap((card) => card.entity ? [card.entity] : []);
|
|
5523
|
+
const accessibleText = [text, ...cards.map((card) => card.text)].filter(Boolean).join("\n\n");
|
|
5524
|
+
const fallbackText = isFinalChunk && args.replyAttribution ? `${accessibleText}\n\n${escapeSlackMrkdwnText(formatReplyAttribution(args.replyAttribution))}` : accessibleText;
|
|
5525
|
+
const response = await postSlackMessage({
|
|
5526
|
+
channelId: args.channelId,
|
|
5527
|
+
threadTs,
|
|
5528
|
+
text: fallbackText,
|
|
5529
|
+
...blocks.length ? { blocks } : void 0,
|
|
5530
|
+
...entities.length ? { entities } : void 0
|
|
5531
|
+
});
|
|
5532
|
+
if (response.ts) {
|
|
5533
|
+
messageTs.push(response.ts);
|
|
5534
|
+
threadTs ??= response.ts;
|
|
5535
|
+
}
|
|
5536
|
+
}
|
|
5537
|
+
return messageTs;
|
|
5538
|
+
}
|
|
5108
5539
|
// src/chat/slack/user-input.ts
|
|
5109
5540
|
const FIELD_BLOCK_ID_PREFIX = "field:";
|
|
5110
5541
|
const OTHER_BLOCK_ID = "other";
|
|
@@ -5531,16 +5962,6 @@ async function resolveSlackInboxItemCardConversationId(card) {
|
|
|
5531
5962
|
}
|
|
5532
5963
|
const SYNC_LOCK_WAIT_MS = 1e4;
|
|
5533
5964
|
/**
|
|
5534
|
-
* Return the Slack `ShowInboxItem` for app setup. Pass `getSlackAdapter`
|
|
5535
|
-
* outside Slack work so each card uses the token of its workspace.
|
|
5536
|
-
*/
|
|
5537
|
-
function createSlackInboxItemShow(getSlackAdapter) {
|
|
5538
|
-
return (itemId) => syncInboxItemSlackCards({
|
|
5539
|
-
getSlackAdapter,
|
|
5540
|
-
itemId
|
|
5541
|
-
});
|
|
5542
|
-
}
|
|
5543
|
-
/**
|
|
5544
5965
|
* Show the current state of an Inbox item in its linked Slack threads. An
|
|
5545
5966
|
* open item gets one card in each linked thread that has none and is not
|
|
5546
5967
|
* detached. Each existing
|
|
@@ -5579,6 +6000,277 @@ async function syncInboxItemSlackCards(args) {
|
|
|
5579
6000
|
}, { waitMs: SYNC_LOCK_WAIT_MS })).acquired) throw new Error("Another Inbox item card sync held the lock");
|
|
5580
6001
|
}, "inbox_item.slack_card.sync.failed", { "app.inbox_item.id": itemId });
|
|
5581
6002
|
}
|
|
6003
|
+
// src/chat/notifications/inbox-item-push.ts
|
|
6004
|
+
/**
|
|
6005
|
+
* How long a Slack card waits before its item pushes. A User who saw the
|
|
6006
|
+
* card in that time answers it, which closes the item.
|
|
6007
|
+
*/
|
|
6008
|
+
const SLACK_CARD_PUSH_DELAY_MS = 3e5;
|
|
6009
|
+
/** Pending pushes after a Slack card. Each id names one item and one User. */
|
|
6010
|
+
const INBOX_ITEM_PUSH_TIMER_INDEX = {
|
|
6011
|
+
batchSize: 100,
|
|
6012
|
+
key: "junior:inbox-items:push-due"
|
|
6013
|
+
};
|
|
6014
|
+
const pushTimerSchema = z.tuple([z.string(), z.string()]);
|
|
6015
|
+
function pushTimerId(itemId, userId) {
|
|
6016
|
+
return JSON.stringify([itemId, userId]);
|
|
6017
|
+
}
|
|
6018
|
+
async function scheduleInboxItemPushTimer(id, atMs) {
|
|
6019
|
+
const state = getStateAdapter();
|
|
6020
|
+
await state.connect();
|
|
6021
|
+
await updateTimerIndex(state, INBOX_ITEM_PUSH_TIMER_INDEX, {
|
|
6022
|
+
atMs,
|
|
6023
|
+
id,
|
|
6024
|
+
kind: "add"
|
|
6025
|
+
});
|
|
6026
|
+
}
|
|
6027
|
+
/**
|
|
6028
|
+
* Record the Slack card of an open item for each assignee, and keep a push
|
|
6029
|
+
* timer from their first card for each one with no push yet. A User
|
|
6030
|
+
* assigned again after their timer fired gets it again, and a timer that
|
|
6031
|
+
* is due already fires at the next heartbeat.
|
|
6032
|
+
*/
|
|
6033
|
+
async function scheduleSlackCardPushes(db, item) {
|
|
6034
|
+
const carded = await recordInboxItemSlackCard(db, {
|
|
6035
|
+
itemId: item.id,
|
|
6036
|
+
nowMs: Date.now(),
|
|
6037
|
+
userIds: item.assignees.map((assignee) => assignee.userId)
|
|
6038
|
+
});
|
|
6039
|
+
const pushed = await listInboxItemPushUserIds(db, item.id);
|
|
6040
|
+
for (const [userId, cardedAtMs] of carded) {
|
|
6041
|
+
if (pushed.has(userId)) continue;
|
|
6042
|
+
await scheduleInboxItemPushTimer(pushTimerId(item.id, userId), cardedAtMs + SLACK_CARD_PUSH_DELAY_MS);
|
|
6043
|
+
}
|
|
6044
|
+
}
|
|
6045
|
+
async function hasSlackCard(db, itemId) {
|
|
6046
|
+
return (await db.select({ itemId: juniorInboxItemSlackCards.itemId }).from(juniorInboxItemSlackCards).where(eq(juniorInboxItemSlackCards.itemId, itemId)).limit(1)).length > 0;
|
|
6047
|
+
}
|
|
6048
|
+
async function isSnoozedBy(db, itemId, userId) {
|
|
6049
|
+
return (await db.select({ id: juniorInboxItems.id }).from(juniorInboxItems).where(and(eq(juniorInboxItems.id, itemId), inboxItemSnoozedBy(userId))).limit(1)).length > 0;
|
|
6050
|
+
}
|
|
6051
|
+
async function skipReason(db, itemId, userId, nowMs) {
|
|
6052
|
+
if (await isSnoozedBy(db, itemId, userId)) return "snoozed";
|
|
6053
|
+
return await readNotificationPause(db, userId, nowMs);
|
|
6054
|
+
}
|
|
6055
|
+
/**
|
|
6056
|
+
* Record one push of an item to one User, then send it unless the User is
|
|
6057
|
+
* paused or snoozed the item. `record` returns false when another caller
|
|
6058
|
+
* already holds this push. `afterSlackCard`: the item's Slack card posted a
|
|
6059
|
+
* while ago, so a User active in Slack got Slack's own notification and
|
|
6060
|
+
* needs no push.
|
|
6061
|
+
*/
|
|
6062
|
+
async function deliverPush(args) {
|
|
6063
|
+
const { db, item, userId } = args;
|
|
6064
|
+
const nowMs = Date.now();
|
|
6065
|
+
const reason = await skipReason(db, item.id, userId, nowMs) ?? (args.afterSlackCard && await isActiveInSlack(db, userId) ? "slack_active" : void 0);
|
|
6066
|
+
if (!await args.record({
|
|
6067
|
+
itemId: item.id,
|
|
6068
|
+
nowMs,
|
|
6069
|
+
skipReason: reason,
|
|
6070
|
+
userId
|
|
6071
|
+
})) return;
|
|
6072
|
+
if (!await isInboxItemOpen(db, item.id)) {
|
|
6073
|
+
await clearInboxItemDeliveries(db, [item.id], Date.now());
|
|
6074
|
+
return;
|
|
6075
|
+
}
|
|
6076
|
+
if (reason) {
|
|
6077
|
+
logInfo("notification.inbox_item.skipped", { "app.notification.skip_reason": reason });
|
|
6078
|
+
return;
|
|
6079
|
+
}
|
|
6080
|
+
await sendPushNotificationToUser({
|
|
6081
|
+
config: args.config,
|
|
6082
|
+
db,
|
|
6083
|
+
kind: args.kind,
|
|
6084
|
+
payload: {
|
|
6085
|
+
body: notificationPreview(item.body),
|
|
6086
|
+
tag: item.id,
|
|
6087
|
+
title: item.title,
|
|
6088
|
+
url: args.url
|
|
6089
|
+
},
|
|
6090
|
+
userId
|
|
6091
|
+
});
|
|
6092
|
+
}
|
|
6093
|
+
/**
|
|
6094
|
+
* Only an action for named Users pushes. Everyone items and notices
|
|
6095
|
+
* show only in the Inbox.
|
|
6096
|
+
*/
|
|
6097
|
+
function pushesToAssignees(item) {
|
|
6098
|
+
return item.kind === "action" && !item.assignedToEveryone && item.assignees.length > 0;
|
|
6099
|
+
}
|
|
6100
|
+
/**
|
|
6101
|
+
* Push a new open action to each of its assigned Users, once per User. The
|
|
6102
|
+
* delivery record stops a second push when the item shows again, such as
|
|
6103
|
+
* after a content change. An item with a Slack card records that card for
|
|
6104
|
+
* each User and pushes to them later, from `runInboxItemPushTimers`, unless
|
|
6105
|
+
* `slackWaited` says that its wait already ended. A
|
|
6106
|
+
* User outside their notification hours, or who snoozed the item, gets no
|
|
6107
|
+
* push for it. Push is optional UI, the same as a Slack card: a failure is
|
|
6108
|
+
* logged and never fails the change that caused it, and nothing retries
|
|
6109
|
+
* it.
|
|
6110
|
+
*/
|
|
6111
|
+
async function syncInboxItemPush(itemId, options = {}) {
|
|
6112
|
+
const config = readWebPushConfig();
|
|
6113
|
+
if (!config) return;
|
|
6114
|
+
await runBestEffort(async () => {
|
|
6115
|
+
const db = getDb();
|
|
6116
|
+
const item = await getInboxItem(db, itemId);
|
|
6117
|
+
if (!item) return;
|
|
6118
|
+
if (item.status !== "open") {
|
|
6119
|
+
await clearInboxItemDeliveries(db, [item.id], Date.now());
|
|
6120
|
+
return;
|
|
6121
|
+
}
|
|
6122
|
+
if (!pushesToAssignees(item)) return;
|
|
6123
|
+
const url = getDashboardInboxItemLink(item.id);
|
|
6124
|
+
if (!url) return;
|
|
6125
|
+
const userIds = item.assignees.map((assignee) => assignee.userId);
|
|
6126
|
+
if (!options.slackWaited && await hasSlackCard(db, item.id)) {
|
|
6127
|
+
await scheduleSlackCardPushes(db, item);
|
|
6128
|
+
return;
|
|
6129
|
+
}
|
|
6130
|
+
await withSpan("notification.inbox_item.push", "notification.inbox_item.push", {}, async () => {
|
|
6131
|
+
const pushed = await listInboxItemPushUserIds(db, item.id);
|
|
6132
|
+
await mapBounded(userIds.filter((userId) => !pushed.has(userId)), (userId) => deliverPush({
|
|
6133
|
+
config,
|
|
6134
|
+
db,
|
|
6135
|
+
item,
|
|
6136
|
+
kind: "inbox_item",
|
|
6137
|
+
record: (input) => claimInboxItemPush(db, input),
|
|
6138
|
+
url,
|
|
6139
|
+
userId
|
|
6140
|
+
}));
|
|
6141
|
+
}, { "app.inbox_item.id": item.id });
|
|
6142
|
+
}, "notification.inbox_item.push_failed", { "app.inbox_item.id": itemId });
|
|
6143
|
+
}
|
|
6144
|
+
/**
|
|
6145
|
+
* Return where the wake push of an item opens, or undefined when the
|
|
6146
|
+
* item does not push to this User: they must be a named assignee of an
|
|
6147
|
+
* action, or the starter of a reply notice. A Slack card shows nothing new
|
|
6148
|
+
* when a snooze wakes, so it does not stop this push.
|
|
6149
|
+
*/
|
|
6150
|
+
function wakePushUrl(item, userId) {
|
|
6151
|
+
if (item.status !== "open" || item.assignedToEveryone) return void 0;
|
|
6152
|
+
if (!item.assignees.some((assignee) => assignee.userId === userId)) return;
|
|
6153
|
+
if (item.kind === "action") return getDashboardInboxItemLink(item.id);
|
|
6154
|
+
const [conversationId] = item.conversationIds;
|
|
6155
|
+
if (item.dedupeKey.startsWith("reply:") && conversationId) return getDashboardConversationLink(conversationId);
|
|
6156
|
+
}
|
|
6157
|
+
/**
|
|
6158
|
+
* Push each snooze that a time or an Event woke to the User who snoozed
|
|
6159
|
+
* it. The caller passes only the snoozes that its own update woke, so one
|
|
6160
|
+
* wake pushes once. A Wake that the User picks does not come here. Push is
|
|
6161
|
+
* optional UI: a failure is logged, and nothing retries it.
|
|
6162
|
+
*/
|
|
6163
|
+
async function pushInboxSnoozeWakes(wakes) {
|
|
6164
|
+
const config = readWebPushConfig();
|
|
6165
|
+
if (!config) return;
|
|
6166
|
+
await mapBounded(wakes, (wake) => runBestEffort(async () => {
|
|
6167
|
+
const db = getDb();
|
|
6168
|
+
const item = await getInboxItem(db, wake.inboxItemId);
|
|
6169
|
+
const url = item && wakePushUrl(item, wake.userId);
|
|
6170
|
+
if (!item || !url) return;
|
|
6171
|
+
await withSpan("notification.inbox_item.push", "notification.inbox_item.push", {}, () => deliverPush({
|
|
6172
|
+
config,
|
|
6173
|
+
db,
|
|
6174
|
+
item,
|
|
6175
|
+
kind: "wake",
|
|
6176
|
+
record: async (input) => {
|
|
6177
|
+
await recordRepeatInboxItemPush(db, {
|
|
6178
|
+
...input,
|
|
6179
|
+
event: "wake"
|
|
6180
|
+
});
|
|
6181
|
+
return true;
|
|
6182
|
+
},
|
|
6183
|
+
url,
|
|
6184
|
+
userId: wake.userId
|
|
6185
|
+
}), { "app.inbox_item.id": item.id });
|
|
6186
|
+
}, "notification.inbox_item.push_failed", { "app.inbox_item.id": wake.inboxItemId }));
|
|
6187
|
+
}
|
|
6188
|
+
/**
|
|
6189
|
+
* Push the open items of a root Conversation and its child agents now,
|
|
6190
|
+
* after the root attaches to or detaches from its Slack thread. Those items
|
|
6191
|
+
* count as having waited in Slack with no answer, so they skip the rest of
|
|
6192
|
+
* the Slack card wait. A User that an item pushed to already gets no
|
|
6193
|
+
* second push.
|
|
6194
|
+
*/
|
|
6195
|
+
async function pushConversationInboxItemsNow(rootConversationId) {
|
|
6196
|
+
if (!readWebPushConfig()) return;
|
|
6197
|
+
await runBestEffort(async () => {
|
|
6198
|
+
const rows = await getDb().selectDistinct({ itemId: juniorInboxItemConversations.itemId }).from(juniorInboxItemConversations).innerJoin(juniorConversations, eq(juniorConversations.conversationId, juniorInboxItemConversations.conversationId)).innerJoin(juniorInboxItems, eq(juniorInboxItems.id, juniorInboxItemConversations.itemId)).where(and(eq(juniorInboxItems.status, "open"), or(eq(juniorConversations.conversationId, rootConversationId), eq(juniorConversations.rootConversationId, rootConversationId))));
|
|
6199
|
+
await mapBounded(rows, (row) => syncInboxItemPush(row.itemId, { slackWaited: true }));
|
|
6200
|
+
}, "notification.inbox_item.push_failed", { "app.conversation.id": rootConversationId });
|
|
6201
|
+
}
|
|
6202
|
+
/**
|
|
6203
|
+
* Push the item of one due timer to its User, after the item's Slack card
|
|
6204
|
+
* waited for them. A closed item, or a User no longer assigned, gets
|
|
6205
|
+
* nothing. An item whose User is not assigned goes in `unassigned`.
|
|
6206
|
+
*/
|
|
6207
|
+
async function pushAfterSlackCard(db, config, timerId, unassigned) {
|
|
6208
|
+
const [itemId, userId] = pushTimerSchema.parse(JSON.parse(timerId));
|
|
6209
|
+
await runBestEffort(async () => {
|
|
6210
|
+
const item = await getInboxItem(db, itemId);
|
|
6211
|
+
if (!item || item.status !== "open" || !pushesToAssignees(item)) return;
|
|
6212
|
+
if (!item.assignees.some((assignee) => assignee.userId === userId)) {
|
|
6213
|
+
unassigned.add(item.id);
|
|
6214
|
+
return;
|
|
6215
|
+
}
|
|
6216
|
+
const url = getDashboardInboxItemLink(item.id);
|
|
6217
|
+
if (!url) return;
|
|
6218
|
+
await withSpan("notification.inbox_item.push", "notification.inbox_item.push", {}, () => deliverPush({
|
|
6219
|
+
afterSlackCard: true,
|
|
6220
|
+
config,
|
|
6221
|
+
db,
|
|
6222
|
+
item,
|
|
6223
|
+
kind: "inbox_item",
|
|
6224
|
+
record: (input) => claimInboxItemPush(db, input),
|
|
6225
|
+
url,
|
|
6226
|
+
userId
|
|
6227
|
+
}), { "app.inbox_item.id": item.id });
|
|
6228
|
+
}, "notification.inbox_item.push_failed", { "app.inbox_item.id": itemId });
|
|
6229
|
+
}
|
|
6230
|
+
/**
|
|
6231
|
+
* Push the items whose Slack card waited long enough. A failed pass leaves
|
|
6232
|
+
* its claims to expire, so the next heartbeat retries them. A push that
|
|
6233
|
+
* fails is logged and not retried, the same as one that sends at once.
|
|
6234
|
+
* A User assigned again while the pass holds the claim of their timer
|
|
6235
|
+
* gets it again from the show, and the removal then drops it. So the pass
|
|
6236
|
+
* adds back the timers of each item with a User who was not assigned.
|
|
6237
|
+
*/
|
|
6238
|
+
async function runInboxItemPushTimers(db, nowMs) {
|
|
6239
|
+
const state = getStateAdapter();
|
|
6240
|
+
await state.connect();
|
|
6241
|
+
const timerIds = await updateTimerIndex(state, INBOX_ITEM_PUSH_TIMER_INDEX, {
|
|
6242
|
+
kind: "claim",
|
|
6243
|
+
nowMs
|
|
6244
|
+
});
|
|
6245
|
+
if (timerIds.length === 0) return;
|
|
6246
|
+
const config = readWebPushConfig();
|
|
6247
|
+
const unassigned = /* @__PURE__ */ new Set();
|
|
6248
|
+
if (config) await mapBounded(timerIds, (id) => pushAfterSlackCard(db, config, id, unassigned));
|
|
6249
|
+
for (const id of timerIds) await updateTimerIndex(state, INBOX_ITEM_PUSH_TIMER_INDEX, {
|
|
6250
|
+
id,
|
|
6251
|
+
kind: "remove"
|
|
6252
|
+
});
|
|
6253
|
+
for (const itemId of unassigned) await runBestEffort(async () => {
|
|
6254
|
+
const item = await getInboxItem(db, itemId);
|
|
6255
|
+
if (item?.status === "open" && pushesToAssignees(item) && await hasSlackCard(db, item.id)) await scheduleSlackCardPushes(db, item);
|
|
6256
|
+
}, "notification.inbox_item.push_failed", { "app.inbox_item.id": itemId });
|
|
6257
|
+
}
|
|
6258
|
+
// src/chat/notifications/inbox-item-show.ts
|
|
6259
|
+
/**
|
|
6260
|
+
* Return the `ShowInboxItem` for app setup: the item's Slack cards, then
|
|
6261
|
+
* its push. The push reads the cards, so an item that Slack shows pushes
|
|
6262
|
+
* only after its card waited. Pass `getSlackAdapter` outside Slack work so each card uses the
|
|
6263
|
+
* token of its workspace.
|
|
6264
|
+
*/
|
|
6265
|
+
function createInboxItemShow(getSlackAdapter) {
|
|
6266
|
+
return async (itemId) => {
|
|
6267
|
+
await syncInboxItemSlackCards({
|
|
6268
|
+
getSlackAdapter,
|
|
6269
|
+
itemId
|
|
6270
|
+
});
|
|
6271
|
+
await syncInboxItemPush(itemId);
|
|
6272
|
+
};
|
|
6273
|
+
}
|
|
5582
6274
|
// src/chat/slack/inbox-item-tools.ts
|
|
5583
6275
|
const SLACK_MENTION = /^<@([A-Z0-9]+)(?:\|[^>]*)?>$/;
|
|
5584
6276
|
/**
|
|
@@ -5603,7 +6295,7 @@ function createSlackInboxItemToolServices(queue) {
|
|
|
5603
6295
|
return {
|
|
5604
6296
|
findMentionedUserId: findSlackMentionedUserId,
|
|
5605
6297
|
queue,
|
|
5606
|
-
show:
|
|
6298
|
+
show: createInboxItemShow()
|
|
5607
6299
|
};
|
|
5608
6300
|
}
|
|
5609
6301
|
// src/chat/tool-support/send-files.ts
|
|
@@ -5698,7 +6390,7 @@ function createSlackSendFilesTool(context, state, materializeFile, conversationI
|
|
|
5698
6390
|
key: `${channelId}:${threadTs ?? ""}`,
|
|
5699
6391
|
async send(files) {
|
|
5700
6392
|
if (await isConversationDeliveryPaused(conversationId)) {
|
|
5701
|
-
if (!attachments) throw new ToolInputError("This conversation is detached from Slack, so files cannot be sent to it.");
|
|
6393
|
+
if (!attachments) throw new ToolInputError("This conversation is detached from Slack, so files cannot be sent to it. No change to the call can fix this in this Turn.");
|
|
5702
6394
|
return;
|
|
5703
6395
|
}
|
|
5704
6396
|
await uploadFilesToConversation({
|
|
@@ -5800,7 +6492,7 @@ function createSlackCanvasCreateTool(context, state) {
|
|
|
5800
6492
|
});
|
|
5801
6493
|
const response = {
|
|
5802
6494
|
canvas_id: created.canvasId,
|
|
5803
|
-
|
|
6495
|
+
url: created.permalink,
|
|
5804
6496
|
summary: `Created canvas ${created.canvasId}`
|
|
5805
6497
|
};
|
|
5806
6498
|
state.setOperationResult(operationKey, response);
|
|
@@ -5820,7 +6512,7 @@ const automationDestinationParam = slackChannelRefParam.describe("Slack channel:
|
|
|
5820
6512
|
async function requireDestinationTeamId(context, caller) {
|
|
5821
6513
|
if (context.destination) {
|
|
5822
6514
|
const teamId = parseSlackTeamId(context.destination.teamId);
|
|
5823
|
-
if (!teamId) throw new ToolInputError("Slack workspace is
|
|
6515
|
+
if (!teamId) throw new ToolInputError("The Slack workspace of this Conversation is unknown. Set destination to \"current_conversation\", or ask from the Slack channel where the automation should deliver.");
|
|
5824
6516
|
return teamId;
|
|
5825
6517
|
}
|
|
5826
6518
|
const teamId = parseSlackTeamId(await resolveBotSlackTeamId());
|
|
@@ -6062,7 +6754,7 @@ function createAutomationTool(context, catalog, skills = []) {
|
|
|
6062
6754
|
toolCallId
|
|
6063
6755
|
});
|
|
6064
6756
|
const requireOwnAutomation = (candidate) => {
|
|
6065
|
-
if (!sameDestination(candidate.task.destination, destination) || candidate.task.createdBy.slackUserId !== createdBy.slackUserId) throw new ToolInputError("Automation operation identity is invalid.");
|
|
6757
|
+
if (!sameDestination(candidate.task.destination, destination) || candidate.task.createdBy.slackUserId !== createdBy.slackUserId) throw new ToolInputError("Automation operation identity is invalid. No change to the call can fix this in this Turn.");
|
|
6066
6758
|
return automationToolResult(context.conversationId, candidate, catalog);
|
|
6067
6759
|
};
|
|
6068
6760
|
const replayed = await readReplayedAutomation(kind, id);
|
|
@@ -6154,7 +6846,7 @@ async function updateEvent(current, input, editedTask, editor, catalog) {
|
|
|
6154
6846
|
credentialMode: input.credential_mode
|
|
6155
6847
|
}, current.ownedByViewer, catalog);
|
|
6156
6848
|
const saved = await saveEventAutomation(getDb(), next, automationRevision(task), editor);
|
|
6157
|
-
if (!saved) throw new ToolInputError("Automation was not found.");
|
|
6849
|
+
if (!saved) throw new ToolInputError("Automation was not found: it was deleted. No change to the call can fix this.");
|
|
6158
6850
|
return {
|
|
6159
6851
|
...current,
|
|
6160
6852
|
task: saved
|
|
@@ -6203,7 +6895,7 @@ function createUpdateAutomationTool(context, catalog, skills = []) {
|
|
|
6203
6895
|
const caller = await requireToolCaller(context);
|
|
6204
6896
|
const current = await requireToolAutomation(caller, automation_id);
|
|
6205
6897
|
if (input.trigger && triggerKind(input.trigger) !== current.kind) throw new ToolInputError(`This automation runs on ${current.kind === "scheduled" ? "a schedule" : "events"}. The trigger type cannot change. Create a new automation instead.`);
|
|
6206
|
-
if (Object.keys(input).length === 0 && status === void 0) throw new ToolInputError("Automation update requires a change.");
|
|
6898
|
+
if (Object.keys(input).length === 0 && status === void 0) throw new ToolInputError("Automation update requires a change. Set status or at least one field to change.");
|
|
6207
6899
|
if (current.kind === "scheduled" && current.task.status === "completed") throw new ToolInputError("Completed scheduled automations cannot be updated. Create a new automation instead.");
|
|
6208
6900
|
if (input.destination && current.kind === "event") throw new ToolInputError("Event automations cannot move. Create a new event automation in this conversation instead.");
|
|
6209
6901
|
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.");
|
|
@@ -6403,8 +7095,8 @@ function createLoadAttachmentTool(args) {
|
|
|
6403
7095
|
conversationId: args.conversationId,
|
|
6404
7096
|
db: args.db
|
|
6405
7097
|
});
|
|
6406
|
-
if (!attachment || attachment.storageProvider !== args.storage.provider) throw new ToolInputError("Attachment not found in this conversation.");
|
|
6407
|
-
if (attachment.bytes > 262144e3) throw new ToolInputError(ATTACHMENT_TOO_LARGE_MESSAGE);
|
|
7098
|
+
if (!attachment || attachment.storageProvider !== args.storage.provider) throw new ToolInputError("Attachment not found in this conversation. Use an attachment_id from the attachment context or a Slack read result.");
|
|
7099
|
+
if (attachment.bytes > 262144e3) throw new ToolInputError(`${ATTACHMENT_TOO_LARGE_MESSAGE} No change to the call can fix this.`);
|
|
6408
7100
|
let content;
|
|
6409
7101
|
try {
|
|
6410
7102
|
content = await readAttachmentContent({
|
|
@@ -6765,7 +7457,7 @@ function createTools(availableSkills, hooks = {}, context, options = {}) {
|
|
|
6765
7457
|
})) {
|
|
6766
7458
|
const tool = slot.kind === "static" ? STATIC_TOOL_BINDERS[slot.name](run) : RUN_BUILT_TOOL_BUILDERS[slot.slot](run);
|
|
6767
7459
|
if (!tool) continue;
|
|
6768
|
-
tools[slot.name] = slot.kind === "static" ? withDisabledReason(tool, TURN_TOOL_LIMITS[slot.name]?.(context.turnTools)) : tool;
|
|
7460
|
+
tools[slot.name] = listedToolExposure(listedTools, slot.name, slot.kind === "static" ? withDisabledReason(tool, TURN_TOOL_LIMITS[slot.name]?.(context.turnTools)) : tool);
|
|
6769
7461
|
}
|
|
6770
7462
|
const pluginTools = listedTools.only ? {} : getPluginTools(context, options.pluginSandbox);
|
|
6771
7463
|
for (const [name, pluginTool] of Object.entries(pluginTools)) {
|
|
@@ -6980,7 +7672,7 @@ function resolveCatalogToolCall(input, catalogTools) {
|
|
|
6980
7672
|
function prepareCatalogToolCall(call, dispatcherName = "executeTool") {
|
|
6981
7673
|
const prepared = call.definition.prepareArguments ? call.definition.prepareArguments(call.arguments) : call.arguments;
|
|
6982
7674
|
if (isTypeBoxInputSchema(call.definition.inputSchema) && !Value.Check(call.definition.inputSchema, prepared)) throw new ToolInputError(`${dispatcherName} arguments do not match schema for ${call.toolName}: ${schemaErrorText(call.definition.inputSchema, prepared)}`);
|
|
6983
|
-
if (!prepared || typeof prepared !== "object" || Array.isArray(prepared)) throw new ToolInputError(`${dispatcherName} arguments must prepare to an object for ${call.toolName}.`);
|
|
7675
|
+
if (!prepared || typeof prepared !== "object" || Array.isArray(prepared)) throw new ToolInputError(`${dispatcherName} arguments must prepare to an object for ${call.toolName}. Pass arguments as a JSON object.`);
|
|
6984
7676
|
return {
|
|
6985
7677
|
arguments: prepared,
|
|
6986
7678
|
definition: call.definition,
|
|
@@ -7091,7 +7783,7 @@ function createExecuteToolTool() {
|
|
|
7091
7783
|
return zodTool({
|
|
7092
7784
|
...executeToolDefinition,
|
|
7093
7785
|
execute: async () => {
|
|
7094
|
-
throw new ToolInputError("executeTool can only run through the agent tool dispatcher.");
|
|
7786
|
+
throw new ToolInputError("executeTool can only run through the agent tool dispatcher. In a codemode script, call the catalog tool as tools.<tool_name>(args) instead.");
|
|
7095
7787
|
}
|
|
7096
7788
|
});
|
|
7097
7789
|
}
|
|
@@ -8973,7 +9665,7 @@ function guardianPluginFacts(manifests) {
|
|
|
8973
9665
|
text: manifest.reviewContext
|
|
8974
9666
|
});
|
|
8975
9667
|
const credentials = manifest.credentials;
|
|
8976
|
-
if (credentials) {
|
|
9668
|
+
if (credentials?.authTokenEnv) {
|
|
8977
9669
|
const domains = credentials.domains.map((domain) => `\`${domain}\``).join(", ");
|
|
8978
9670
|
facts.push({
|
|
8979
9671
|
plugin: manifest.name,
|
|
@@ -9343,24 +10035,12 @@ async function actorIdentityIds(actor) {
|
|
|
9343
10035
|
const identities = resolved?.user?.identities ?? (resolved ? [resolved.identity] : []);
|
|
9344
10036
|
return new Set(identities.map((identity) => identity.id));
|
|
9345
10037
|
}
|
|
9346
|
-
/**
|
|
9347
|
-
* Ids of the agent invocations that a parent agent's spawnAgent or
|
|
9348
|
-
* messageAgent call started in this Conversation. Their input, and each
|
|
9349
|
-
* parent message that no Agent invocation names, is the instruction of a Run
|
|
9350
|
-
* that an agent started.
|
|
9351
|
-
*/
|
|
9352
|
-
async function parentTaskInvocationIds(conversationId) {
|
|
9353
|
-
const invocations = await listAgentInvocationsForConversation(conversationId, AGENT_INVOCATION_STATUSES);
|
|
9354
|
-
return new Set(invocations.flatMap((invocation) => invocation.parentToolCallId ? [invocation.invocationId] : []));
|
|
9355
|
-
}
|
|
9356
10038
|
/** Label one root message with its real author. */
|
|
9357
|
-
function messageLabel(root, data, actor, personIdentityIds
|
|
10039
|
+
function messageLabel(root, data, actor, personIdentityIds) {
|
|
9358
10040
|
if (data.role === "assistant") return "assistant";
|
|
9359
10041
|
if (data.role !== "user") return "system";
|
|
9360
|
-
if (
|
|
10042
|
+
if (!actor && isParentMessageAuthor(messageAuthorSchema.safeParse(data.meta?.["author"]).data)) return "user";
|
|
9361
10043
|
if (data.meta?.["eventType"] !== void 0) return "event";
|
|
9362
|
-
const invocationId = data.meta?.["agentInvocationId"];
|
|
9363
|
-
if (typeof invocationId === "string" && parentTaskIds?.has(invocationId)) return "user";
|
|
9364
10044
|
if (data.authorIdentityId && personIdentityIds.has(data.authorIdentityId)) return "user";
|
|
9365
10045
|
const author = messageAuthor(root, data);
|
|
9366
10046
|
if (author?.platform === "local" && actor && sameActorIdentity(author, actor)) return "user";
|
|
@@ -9442,20 +10122,19 @@ async function readRootConversation(args) {
|
|
|
9442
10122
|
text: openingEdit
|
|
9443
10123
|
} : pinnedRead?.data;
|
|
9444
10124
|
const personIdentityIds = args.actor ? await actorIdentityIds(args.actor) : /* @__PURE__ */ new Set();
|
|
9445
|
-
const parentTaskIds = args.actor ? void 0 : await parentTaskInvocationIds(root.conversationId);
|
|
9446
10125
|
const all = [];
|
|
9447
10126
|
for (const data of byId.values()) {
|
|
9448
10127
|
const text = normalizeLines(data.text).trim();
|
|
9449
10128
|
if (!text || data.messageId === opening?.messageId) continue;
|
|
9450
10129
|
all.push({
|
|
9451
|
-
author: messageLabel(root, data, args.actor, personIdentityIds
|
|
10130
|
+
author: messageLabel(root, data, args.actor, personIdentityIds),
|
|
9452
10131
|
messageId: data.messageId,
|
|
9453
10132
|
text: truncate(text, MAX_ROOT_MESSAGE_CHARS)
|
|
9454
10133
|
});
|
|
9455
10134
|
}
|
|
9456
10135
|
const openingText = opening ? normalizeLines(opening.text).trim() : "";
|
|
9457
10136
|
const pinned = opening && openingText ? [{
|
|
9458
|
-
author: messageLabel(root, opening, args.actor, personIdentityIds
|
|
10137
|
+
author: messageLabel(root, opening, args.actor, personIdentityIds),
|
|
9459
10138
|
text: truncate(openingText, MAX_ROOT_MESSAGE_CHARS)
|
|
9460
10139
|
}] : [];
|
|
9461
10140
|
const kept = /* @__PURE__ */ new Set();
|
|
@@ -9511,6 +10190,45 @@ async function readRootConversation(args) {
|
|
|
9511
10190
|
truncated: hasOlder || orphanEdits.size > 0 || kept.size < all.length
|
|
9512
10191
|
};
|
|
9513
10192
|
}
|
|
10193
|
+
// src/chat/tool-support/missing-tool-result.ts
|
|
10194
|
+
/**
|
|
10195
|
+
* Error text for a direct call to a name that is not in the model tool list.
|
|
10196
|
+
* It names the next call, because Pi's own text names none.
|
|
10197
|
+
*/
|
|
10198
|
+
function missingToolText(toolName, routes) {
|
|
10199
|
+
const name = `\`${toolName}\``;
|
|
10200
|
+
if (Object.hasOwn(routes.catalogTools, toolName)) return `${name} is a catalog tool, not in your tool list. Call ${EXECUTE_TOOL_NAME} with tool_name ${name} and the same arguments.`;
|
|
10201
|
+
if (Object.hasOwn(routes.scriptTools, toolName) && routes.modelToolNames.has("codemode")) return `${name} is not in your tool list. Call it in a ${CODEMODE_TOOL_NAME} script as \`tools.${toolName}(args)\` with the same arguments.`;
|
|
10202
|
+
const hintText = renderToolNameHint(findToolNameHint(toolName, routes.catalogTools));
|
|
10203
|
+
return `${name} is not a tool. ${hintText ? `${hintText} Call a tool in your tool list directly, and any other catalog tool through ${EXECUTE_TOOL_NAME}.` : `Call ${SEARCH_TOOLS_NAME} to find its exact name.`}`;
|
|
10204
|
+
}
|
|
10205
|
+
/** Pi's result text when a direct call names a tool that it does not have. */
|
|
10206
|
+
function isPiMissingToolResult(message) {
|
|
10207
|
+
const [part, ...rest] = message.content;
|
|
10208
|
+
return message.isError && rest.length === 0 && part?.type === "text" && part.text === `Tool ${message.toolName} not found`;
|
|
10209
|
+
}
|
|
10210
|
+
/**
|
|
10211
|
+
* Replace Pi's bare "not found" result of each call in `toolResults` that
|
|
10212
|
+
* names a tool outside the model tool list with {@link missingToolText}.
|
|
10213
|
+
* Return the new history, or undefined when nothing changed.
|
|
10214
|
+
*
|
|
10215
|
+
* Only results of the newest step change. Earlier results were already sent
|
|
10216
|
+
* to the model, so a change to them would break the cached prefix.
|
|
10217
|
+
*/
|
|
10218
|
+
function explainMissingToolResults(messages, toolResults, routes) {
|
|
10219
|
+
const missingCallIds = new Set(toolResults.filter((result) => !routes.modelToolNames.has(result.toolName) && isPiMissingToolResult(result)).map((result) => result.toolCallId));
|
|
10220
|
+
if (missingCallIds.size === 0) return;
|
|
10221
|
+
return messages.map((message) => {
|
|
10222
|
+
if (!isToolResultMessage(message) || !missingCallIds.has(message.toolCallId)) return message;
|
|
10223
|
+
return {
|
|
10224
|
+
...message,
|
|
10225
|
+
content: [{
|
|
10226
|
+
type: "text",
|
|
10227
|
+
text: missingToolText(message.toolName, routes)
|
|
10228
|
+
}]
|
|
10229
|
+
};
|
|
10230
|
+
});
|
|
10231
|
+
}
|
|
9514
10232
|
// src/chat/agent/tools.ts
|
|
9515
10233
|
/** Create the run's sandbox handle without acquiring a sandbox. */
|
|
9516
10234
|
async function createRunSandbox(args) {
|
|
@@ -9621,7 +10339,7 @@ function resolveToolRuntimeRoute(args) {
|
|
|
9621
10339
|
case "scheduled_automation":
|
|
9622
10340
|
case "event_automation":
|
|
9623
10341
|
case "plugin_dispatch":
|
|
9624
|
-
case "
|
|
10342
|
+
case "parent_message": return {
|
|
9625
10343
|
destination,
|
|
9626
10344
|
actor: args.actor,
|
|
9627
10345
|
source: args.run.source
|
|
@@ -9833,27 +10551,33 @@ async function wireAgentTools(args) {
|
|
|
9833
10551
|
report
|
|
9834
10552
|
});
|
|
9835
10553
|
} : void 0;
|
|
10554
|
+
const agentTools = createPiAgentTools(tools, args.skillSandbox, {
|
|
10555
|
+
spanContext: args.spanContext,
|
|
10556
|
+
searchToolsCost: {
|
|
10557
|
+
conversationId: args.run.conversationId,
|
|
10558
|
+
turnId: args.run.turnId
|
|
10559
|
+
},
|
|
10560
|
+
onStatus,
|
|
10561
|
+
sandboxTools: agentSandbox.tools,
|
|
10562
|
+
pluginAuthOrchestration: pluginAuth,
|
|
10563
|
+
onToolCall,
|
|
10564
|
+
agentHooks: pluginHooks,
|
|
10565
|
+
conversationPrivacy: args.conversationPrivacy,
|
|
10566
|
+
onToolResult,
|
|
10567
|
+
actionReview,
|
|
10568
|
+
codeMode: {
|
|
10569
|
+
countToolCall: args.resume.countToolCall,
|
|
10570
|
+
workspace: agentSandbox.workspace
|
|
10571
|
+
}
|
|
10572
|
+
});
|
|
10573
|
+
const missingToolRoutes = {
|
|
10574
|
+
catalogTools: plannedToolExposure.catalogTools,
|
|
10575
|
+
modelToolNames: new Set(agentTools.map((tool) => tool.name)),
|
|
10576
|
+
scriptTools: plannedToolExposure.scriptTools
|
|
10577
|
+
};
|
|
9836
10578
|
return {
|
|
9837
10579
|
activeMcpCatalogs,
|
|
9838
|
-
agentTools
|
|
9839
|
-
spanContext: args.spanContext,
|
|
9840
|
-
searchToolsCost: {
|
|
9841
|
-
conversationId: args.run.conversationId,
|
|
9842
|
-
turnId: args.run.turnId
|
|
9843
|
-
},
|
|
9844
|
-
onStatus,
|
|
9845
|
-
sandboxTools: agentSandbox.tools,
|
|
9846
|
-
pluginAuthOrchestration: pluginAuth,
|
|
9847
|
-
onToolCall,
|
|
9848
|
-
agentHooks: pluginHooks,
|
|
9849
|
-
conversationPrivacy: args.conversationPrivacy,
|
|
9850
|
-
onToolResult,
|
|
9851
|
-
actionReview,
|
|
9852
|
-
codeMode: {
|
|
9853
|
-
countToolCall: args.resume.countToolCall,
|
|
9854
|
-
workspace: agentSandbox.workspace
|
|
9855
|
-
}
|
|
9856
|
-
}),
|
|
10580
|
+
agentTools,
|
|
9857
10581
|
getPendingAuthPause,
|
|
9858
10582
|
mcpToolManager,
|
|
9859
10583
|
pluginHooks,
|
|
@@ -9874,6 +10598,7 @@ async function wireAgentTools(args) {
|
|
|
9874
10598
|
}
|
|
9875
10599
|
},
|
|
9876
10600
|
disabledTools,
|
|
10601
|
+
explainMissingToolResults: (messages, toolResults) => explainMissingToolResults(messages, toolResults, missingToolRoutes),
|
|
9877
10602
|
scriptTools: renderScriptTools(plannedToolExposure.scriptTools),
|
|
9878
10603
|
toolGuidance,
|
|
9879
10604
|
toolRuntimeContext
|
|
@@ -10742,6 +11467,8 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
10742
11467
|
* errors into error turns, so the caller keeps them for the step.
|
|
10743
11468
|
*/
|
|
10744
11469
|
const finishModelStep = async (event, runSignal) => {
|
|
11470
|
+
const explained = wiring.explainMissingToolResults(currentAgentMessages(), event.toolResults);
|
|
11471
|
+
if (explained) setAgentHistory(explained);
|
|
10745
11472
|
if (event.toolResults.length > 0) {
|
|
10746
11473
|
cacheWarming.toolsReturned();
|
|
10747
11474
|
await requireConversationLease("save");
|
|
@@ -10761,7 +11488,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
10761
11488
|
runEnded
|
|
10762
11489
|
};
|
|
10763
11490
|
});
|
|
10764
|
-
messagesChanged = boundary.contextUpdated;
|
|
11491
|
+
messagesChanged = Boolean(explained) || boundary.contextUpdated;
|
|
10765
11492
|
if (boundary.runEnded) return;
|
|
10766
11493
|
const yieldError = runResume.prepareYieldIfDue(currentAgentMessages());
|
|
10767
11494
|
if (yieldError) throw yieldError;
|
|
@@ -11220,7 +11947,7 @@ function createAgentRunner(execute, options) {
|
|
|
11220
11947
|
}
|
|
11221
11948
|
};
|
|
11222
11949
|
const loadStoredAttachments = async (attachments) => {
|
|
11223
|
-
const { loadInputAttachments } = await import("./model-input
|
|
11950
|
+
const { loadInputAttachments } = await import("./model-input-0osF3pBS.js").then((n) => n.i);
|
|
11224
11951
|
const storage = nextRun.environment?.attachmentStorage;
|
|
11225
11952
|
if (!storage) throw new Error("Attachment storage is unavailable.");
|
|
11226
11953
|
return await loadInputAttachments({
|
|
@@ -11244,4 +11971,4 @@ function createAgentRunner(execute, options) {
|
|
|
11244
11971
|
return await execute(nextRun, streamFn);
|
|
11245
11972
|
} };
|
|
11246
11973
|
}
|
|
11247
|
-
export {
|
|
11974
|
+
export { canPauseConversationDelivery as A, safeLinkUrl as C, renderSlackObjectCard as D, sendSlackReply as E, readAttachmentContent as F, previewOriginBelongsTo as I, RetryableDeliveryError as L, pauseConversationDelivery as M, resumeConversationDelivery as N, annotationKeyDigest as O, AttachmentDownloadError as P, actorFromRun as R, parseSlackInboxItemFormTarget as S, resolveSlackReplyTarget as T, syncInboxItemSlackCards as _, getMcpOAuthCallbackPath as a, buildSlackInboxItemModal as b, latestProgressStatus as c, scheduledAutomationRunAttributes as d, createInboxItemShow as f, resolveSlackInboxItemCardConversationId as g, runInboxItemPushTimers as h, finalizeMcpAuthorization as i, isConversationDeliveryPaused as j, decodeAnnotationRef as k, resolveDestinationVisibility as l, pushInboxSnoozeWakes as m, executeAgentRun as n, createClientMetadata as o, pushConversationInboxItemsNow as p, buildAuthPauseResponse as r, readMcpClientInformation as s, createAgentRunner as t, logScheduledAutomationRunSkipped as u, findSlackThreadOwnerId as v, parseSlackUserInputSubmission as w, parseSlackInboxItemClick as x, SLACK_INBOX_ITEM_VIEW_ID as y, shouldEmitDevAgentTrace as z };
|