@sentry/junior 0.303.0 → 0.304.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/dist/{adapter-context-BdVnSuY5.js → adapter-context-B1IpoELr.js} +2 -2
  2. package/dist/{admin-AfeAdS3J.js → admin-BnVFGo_z.js} +5 -5
  3. package/dist/{agent-runner-BP8_DLUv.js → agent-runner-CoEeZSRh.js} +546 -372
  4. package/dist/api/schema.d.ts +1 -1
  5. package/dist/api/schema.js +5 -5
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +59 -61
  8. package/dist/{app-Dd9v1mNx.d.ts → app-Cs157Zc5.d.ts} +5 -3
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +77 -64
  11. package/dist/{automation-D9MvhOWY.js → automation-CuA3yEcD.js} +1 -1
  12. package/dist/{background-compaction-queue-xaE05jxH.js → background-compaction-queue-WLPNSF_b.js} +2 -2
  13. package/dist/{briefs-D8i-dKTp.js → briefs-CagVVefw.js} +11 -8
  14. package/dist/{catalog-runtime-d1EM6Z0V.js → catalog-runtime-B8ZXvXWm.js} +1 -1
  15. package/dist/cli/chat.js +15 -15
  16. package/dist/cli/check.js +5 -5
  17. package/dist/cli/init.js +1 -1
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +5 -5
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +4 -4
  23. package/dist/{config-oGM7KA9M.js → config-DdO1BNcw.js} +101 -7
  24. package/dist/{connections-BlikzEJv.js → connections-D20kp0j5.js} +6 -6
  25. package/dist/{continue-in-slack-BZnYifiG.js → continue-in-slack-BKEVMBj1.js} +8 -8
  26. package/dist/{conversation-CY1jnBiC.js → conversation-BOqdRtUx.js} +4 -12
  27. package/dist/{conversation-feed-BZJRk6UV.js → conversation-feed-CgpgP7yi.js} +35 -2
  28. package/dist/{conversation-privacy-Cx515ddM.js → conversation-privacy-L1SK_v0V.js} +10 -2
  29. package/dist/{conversation-turn-DAhRdX4m.js → conversation-turn-BptVJylj.js} +17 -17
  30. package/dist/{credential-sync-DfhmWFeo.js → credential-sync-D1J1CGzL.js} +14 -14
  31. package/dist/{db-C-2tFxk3.js → db-EKJnkrIb.js} +169 -6
  32. package/dist/{db-DPqcEM9_.d.ts → db-zbN5ZV_o.d.ts} +2 -2
  33. package/dist/{executor-NVfS8aQ2.js → executor-CoIZmFK8.js} +43 -9
  34. package/dist/{history-UZ3M2M9r.js → history-m2-ceTTX.js} +8 -2
  35. package/dist/{install-CHLrpRZc.js → install-BT2Pf6HP.js} +2 -2
  36. package/dist/instrumentation.js +7 -3
  37. package/dist/{lineage-HGLhd_-N.js → lineage-C5DGQCS_.js} +2 -2
  38. package/dist/{logging-DiyqRLBx.js → logging-QSZuMcvo.js} +1 -1
  39. package/dist/{message-CkCOcbFH.js → message-TtxftRHj.js} +8 -8
  40. package/dist/{model-input-DmoPPtPE.js → model-input-BHXfA29g.js} +2 -2
  41. package/dist/nitro.d.ts +1 -1
  42. package/dist/nitro.js +5 -5
  43. package/dist/{oauth-callback-server-CIf_6YmA.js → oauth-callback-server-B0enqHtZ.js} +2 -2
  44. package/dist/{projection-DBq8tsA5.js → projection-CNKK7doO.js} +547 -61
  45. package/dist/{prompt-D2KlJopL.js → prompt-DSjhoKu5.js} +185 -12
  46. package/dist/{queue-DFaOscp5.js → queue-CDxkit82.js} +4 -4
  47. package/dist/{registry-Bu0Z9BEO.js → registry-DBDNUUmz.js} +1 -1
  48. package/dist/{resolve-DXuA3G0g.js → resolve-CQLhMWSu.js} +3 -3
  49. package/dist/{result-DpiNseDA.js → result-B-pauj42.js} +8 -8
  50. package/dist/{runner-iu1heRFv.js → runner-B3KxKks5.js} +9 -9
  51. package/dist/{sandbox-egress-signals-2HFYDcQf.js → sandbox-egress-signals-DJJX9ClG.js} +1 -1
  52. package/dist/{schema-DvfX3Gq_.js → schema-Bx0Mlo32.js} +3 -3
  53. package/dist/{schema-DHMOaRzC.d.ts → schema-CKcu-IK6.d.ts} +43 -11
  54. package/dist/{service-account-BcT5LR7V.js → service-account-2HmlNPvy.js} +6 -5
  55. package/dist/{service-account-xYkaQTrw.js → service-account-DQLqkSVv.js} +5 -5
  56. package/dist/{session-stop-BLLp1IP_.js → session-stop-DEeZKqbX.js} +114 -49
  57. package/dist/{skills-CNAGH4ju.js → skills-2UrD7JkN.js} +2 -2
  58. package/dist/{slack-conversation-unfurl-DYnqe5ci.js → slack-conversation-unfurl-Dd129Uov.js} +12 -11
  59. package/dist/{spawn-cGasWW33.js → spawn-eMho9HDJ.js} +6 -6
  60. package/dist/{state-CDS6h_Wv.js → state-Bveuc4Zh.js} +4 -4
  61. package/dist/{stop-DMMA67yT.js → stop-D_ltJLDS.js} +170 -64
  62. package/dist/{store-Dgs7Oe44.js → store-COeYnPL_.js} +5 -5
  63. package/dist/{task-queue-DcF0nhhz.js → task-queue-CBIDXZpV.js} +3 -3
  64. package/dist/{task-runner-BGXF7Fo7.js → task-runner-CJF7zIJL.js} +7 -7
  65. package/dist/{thread-context-BPky1KBe.js → thread-context-Cg0jt0aE.js} +8 -8
  66. package/dist/{turn-session-routing-DGvn9MSl.js → turn-session-routing-CaY3Tp8m.js} +8 -8
  67. package/dist/{turn-user-message-19CkuUvM.js → turn-user-message-tcom1RYd.js} +3 -3
  68. package/dist/{validation-lu1DgjNQ.js → validation-EU91JwIT.js} +1 -1
  69. package/dist/{version-Uo3c94Dx.js → version-BYRPhY5G.js} +1 -1
  70. package/dist/version.js +1 -1
  71. package/dist/{viewer-BPQHMx3-.js → viewer-Cf8ISkAc.js} +3 -3
  72. package/dist/{warmup-H8uLvW9e.js → warmup-TgY4S1vx.js} +75 -469
  73. package/dist/{worker-B-pM_-3K.js → worker-C6Uq4OKD.js} +7 -7
  74. package/migrations/0111_attachment_kinds.sql +14 -0
  75. package/migrations/0112_attachment_url_fill.sql +51 -0
  76. package/migrations/0113_attachment_url_index.sql +1 -0
  77. package/migrations/meta/0099_snapshot.json +102 -326
  78. package/migrations/meta/0111_snapshot.json +5011 -0
  79. package/migrations/meta/0112_snapshot.json +5011 -0
  80. package/migrations/meta/0113_snapshot.json +5033 -0
  81. package/migrations/meta/_journal.json +21 -0
  82. package/package.json +7 -7
@@ -1,39 +1,38 @@
1
- import { $ as loadTurnCheckpoint, $a as SANDBOX_RUNTIME, $o as isConversationScopedChannel, $t as TurnSliceLimitExceededError, An as isStandaloneRuntimeContextMessage, B as getAgentContextInputLimitTokens, Bn as SCRIPT_TOOLS_SECTION_TAG, Ca as addReactionToMessage, Cn as getTerminalAssistantMessages, Ds as piMessageFromHistoryItem, En as hasTurnInput, Es as historyItemFromPiMessage, Fi as getDashboardReviewItemLink, Fn as retainRuntimeTurnContext, G as AuthPausePersistenceError, Ga as consumeSandboxEgressAuthRequiredSignal, Gn as readParentAgentTask, Go as readSlackAttachmentSource, H as PluginCredentialFailureError, Ha as isWorkspaceSnapshotNotReadyError, Hn as TURN_CONTEXT_TAG, In as stripRuntimeTurnContext, J as abandonReplacedPendingAuth, Jo as SlackActionError, K as AuthorizationFlowDisabledError, Ka as consumeSandboxEgressPermissionDeniedSignal, Ki as getWorkspace, L as calculateContextCompactionTargetTokens, La as isAlreadyExistsError, Ln as trimTrailingAssistantMessages, Ma as updateSlackMessage, Mn as isToolResultMessage, Na as uploadFilesToConversation, Nn as latestTurnContextSection, On as isAssistantMessage, Os as projectConversationEvents, Pn as normalizeToolNameFromResult, Pr as getReviewItem, Q as continuableMessages, Qt as TurnBudgetExceededError, R as getAgentBackgroundCompactionMarkTokens, Ra as throwSandboxOperationError, Rn as CAPABILITY_SECTION_TAG, Sn as getPiMessageRole, Ss as credentialAuditSource, T as resolveTaskTitle, U as createPluginAuthOrchestration, Ua as workspaceSnapshotNotReadyUserMessage, Ui as renderToolResultNudge, V as createPluginEgress, Va as getWorkspaceSnapshotNotReadyError, W as authorizationId, Wa as clearSandboxEgressSignals, Xa as buildSandboxEgressNetworkPolicy, Xt as GATED_TURN_LIMIT_WRAP_UP_MESSAGE, Y as canReusePendingAuthLink, Za as resolveSandboxCommandEnvironment, Zn as createUserTokenStore, Zt as TURN_LIMIT_WRAP_UP_MESSAGE, _a as normalizeSlackReplyMarkdown, _n as CODE_MODE_CALL_STATUS_TEXT, _o as runNonInteractiveCommand, aa as ensureDockerDaemon, an as isAnswerToolName, c as recordAgentsInstructionsUpdated, ci as getSlackToolContext, co as SANDBOX_DATA_ROOT, cr as getPluginTools, dn as sanitizeAssistantText, do as SANDBOX_WORKSPACE_ROOT, en as TurnToolCallLimitExceededError, eo as tryWorkspaceRepoCheckoutPath, f as recordAuthorizationRequested, fa as resolveBaseUrl, fn as NO_REPLY_TOOL_NAME, fo as sandboxSkillDir, fs as createConversationEmbedder, g as recordToolExecutionStarted, gn as CODEMODE_TOOL_NAME, go as buildNonInteractiveShellScript, ha as escapeSlackMrkdwnText, hn as readNoReply, ho as buildCommandScript, i as loadConversationProjection, in as REPLY_TOOL_NAME, io as PluginToolDeniedError, jn as isToolResultError, ka as postSlackMessage, kn as isContinuablePiBoundary, ks as getConfigDefaults, l as recordAttachmentsDelivered, la as deliverOAuthAuthorization, ln as decideReply, ls as AttachmentSourceUnavailableError, m as recordMcpProviderConnected, mn as isLegacyNoReplyMarker, mo as sandboxSkillPathResolution, nn as createTurnLimitGate, no as ToolInputError, nt as saveTurnCheckpoint, oa as getSandboxProvider, on as readTurnAnswer, os as sleep, p as recordGuardianActionReviewed, po as sandboxSkillFile, q as AuthorizationPauseError, qa as createSandboxEgressCredentialToken, r as loadConnectedMcpProviders, ra as hash, rn as isTurnExecutionLimitExceededError, ro as isToolInputError, rr as createPluginHookRunner, si as resolveChannelCapabilities, sn as remindMissingAnswer, so as SANDBOX_COMMAND_PATH, ua as formatProviderLabel, un as getAssistantReplyText, uo as SANDBOX_SKILLS_ROOT, vn as REPORT_BLOCKED_TOOL_NAME, vs as resolveUserTimezone, wa as deleteSlackMessage, wn as getUserMessageInstructionText, xn as extractAssistantText, xs as credentialAuditAttributes, yn as readBlockedReport, z as getAgentContextCompactionTriggerTokens, za as wrapSandboxSetupError, zn as REQUEST_CONTEXT_SECTION_TAG } from "./projection-DBq8tsA5.js";
2
- import { A as estimateRequestOverheadTokens, B as ProviderError, D as resolveGatewayModel, F as isCompactionSummaryText, H as createProviderError, J as getGatewayApiKey, K as isProviderRefusal, L as unwrapCurrentInstruction, M as textCharsForTokens, N as COMPACTION_SUMMARY_PREFIX, O as requestPrefixAttributes, P as hasCompactedConversationContext, R as escapeXml, U as findProviderError, V as createAssistantProviderError, W as getProviderErrorAttributes, X as bufferBody, b as GEN_AI_PROVIDER_NAME, j as estimateTextTokens, k as estimateMessagesTokens, n as botConfig, q as isProviderRetryError, v as toPiReasoningLevel, x as GEN_AI_SERVER_ADDRESS, y as normalizeSlackEmojiName, z as escapeXmlText } from "./config-oGM7KA9M.js";
3
- import { C as summarizeMessageText, E as withSpan, H as runWithLogAttributes, 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, l as getLogContextAttributesForSpan, m as logInfo, p as logException, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging-DiyqRLBx.js";
1
+ import { $ as loadTurnCheckpoint, $o as storeDeferredAttachment, $t as TurnSliceLimitExceededError, Aa as updateSlackMessage, An as isStandaloneRuntimeContextMessage, B as getAgentContextInputLimitTokens, Ba as isWorkspaceSnapshotNotReadyError, Bn as TURN_CONTEXT_TAG, Cn as getTerminalAssistantMessages, Da as postSlackMessage, Ds as credentialAuditAttributes, En as hasTurnInput, Fa as isAlreadyExistsError, Fn as stripRuntimeTurnContext, Fs as getConfigDefaults, G as AuthPausePersistenceError, Ga as createSandboxEgressCredentialToken, H as PluginCredentialFailureError, Ha as clearSandboxEgressSignals, Ia as throwSandboxOperationError, In as trimTrailingAssistantMessages, J as abandonReplacedPendingAuth, Ja as buildSandboxEgressNetworkPolicy, Jo as readLiveAttachment, K as AuthorizationFlowDisabledError, L as calculateContextCompactionTargetTokens, La as wrapSandboxSetupError, Ln as CAPABILITY_SECTION_TAG, Mn as isToolResultMessage, Mr as getReviewItem, Ms as historyItemFromPiMessage, Ni as getDashboardReviewItemLink, Nn as normalizeToolNameFromResult, Ns as piMessageFromHistoryItem, On as isAssistantMessage, Os as credentialAuditSource, Pn as retainRuntimeTurnContext, Ps as projectConversationEvents, Q as continuableMessages, Qa as tryWorkspaceRepoCheckoutPath, Qo as storeAttachments, Qt as TurnBudgetExceededError, R as getAgentBackgroundCompactionMarkTokens, Rn as REQUEST_CONTEXT_SECTION_TAG, Sa as deleteSlackMessage, Sn as getPiMessageRole, T as resolveTaskTitle, U as createPluginAuthOrchestration, Ua as consumeSandboxEgressAuthRequiredSignal, Un as readParentAgentTask, Uo as readSlackAttachmentSource, V as createPluginEgress, Va as workspaceSnapshotNotReadyUserMessage, Vi as renderToolResultNudge, W as authorizationId, Wa as consumeSandboxEgressPermissionDeniedSignal, Wi as getWorkspace, Xt as GATED_TURN_LIMIT_WRAP_UP_MESSAGE, Y as canReusePendingAuthLink, Ya as resolveSandboxCommandEnvironment, Yn as createUserTokenStore, Za as SANDBOX_RUNTIME, Zt as TURN_LIMIT_WRAP_UP_MESSAGE, _n as CODE_MODE_CALL_STATUS_TEXT, ai as resolveChannelCapabilities, an as isAnswerToolName, ao as SANDBOX_COMMAND_PATH, as as isConversationScopedChannel, c as recordAgentsInstructionsUpdated, ca as formatProviderLabel, co as SANDBOX_SKILLS_ROOT, dn as sanitizeAssistantText, do as sandboxSkillFile, en as TurnToolCallLimitExceededError, eo as ToolInputError, es as SlackActionError, f as recordAuthorizationRequested, fn as NO_REPLY_TOOL_NAME, fo as sandboxSkillPathResolution, fs as sleep, g as recordToolExecutionStarted, gn as CODEMODE_TOOL_NAME, ha as normalizeSlackReplyMarkdown, hn as readNoReply, ho as runNonInteractiveCommand, hs as AttachmentSourceUnavailableError, i as loadConversationProjection, ia as getSandboxProvider, in as REPLY_TOOL_NAME, ja as uploadFilesToConversation, jn as isToolResultError, kn as isContinuablePiBoundary, l as recordAttachmentsDelivered, ln as decideReply, lo as SANDBOX_WORKSPACE_ROOT, m as recordMcpProviderConnected, mn as isLegacyNoReplyMarker, mo as buildNonInteractiveShellScript, nn as createTurnLimitGate, no as PluginToolDeniedError, nt as saveTurnCheckpoint, oi as getSlackToolContext, on as readTurnAnswer, oo as SANDBOX_DATA_ROOT, or as getPluginTools, p as recordGuardianActionReviewed, pa as escapeSlackMrkdwnText, po as buildCommandScript, q as AuthorizationPauseError, r as loadConnectedMcpProviders, ra as ensureDockerDaemon, rn as isTurnExecutionLimitExceededError, sa as deliverOAuthAuthorization, sn as remindMissingAnswer, ta as hash, to as isToolInputError, tr as createPluginHookRunner, ua as resolveBaseUrl, un as getAssistantReplyText, uo as sandboxSkillDir, vn as REPORT_BLOCKED_TOOL_NAME, vs as createConversationEmbedder, wn as getUserMessageInstructionText, ws as resolveUserTimezone, xa as addReactionToMessage, xn as extractAssistantText, yn as readBlockedReport, z as getAgentContextCompactionTriggerTokens, za as getWorkspaceSnapshotNotReadyError } from "./projection-CNKK7doO.js";
2
+ import { $ as bufferBody, B as unwrapCurrentInstruction, F as textCharsForTokens, G as createProviderError, H as escapeXmlText, I as COMPACTION_SUMMARY_PREFIX, K as findProviderError, L as hasCompactedConversationContext, M as estimateMessagesTokens, N as estimateRequestOverheadTokens, P as estimateTextTokens, R as isCompactionSummaryText, U as ProviderError, V as escapeXml, W as createAssistantProviderError, X as isProviderRetryError, Y as isProviderRefusal, Z as getGatewayApiKey, b as GEN_AI_PROVIDER_NAME, j as requestPrefixAttributes, k as resolveGatewayModel, n as botConfig, q as getProviderErrorAttributes, v as toPiReasoningLevel, x as GEN_AI_SERVER_ADDRESS, y as normalizeSlackEmojiName } from "./config-DdO1BNcw.js";
3
+ import { C as summarizeMessageText, E as withSpan, H as runWithLogAttributes, 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, l as getLogContextAttributesForSpan, m as logInfo, p as logException, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging-QSZuMcvo.js";
4
4
  import { g as withActiveSpan, i as getActiveSpan, m as startInactiveSpan } from "./sentry-CPbZjomA.js";
5
- import { a as toCanonicalInputMessage, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-Cx515ddM.js";
5
+ import { a as toCanonicalInputMessage, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-L1SK_v0V.js";
6
6
  import { f as parseSlackTeamId, n as createSlackActor, o as isUserActor, p as parseSlackUserId, v as parseSlackMessageTs } from "./actor-D2iXzvlN.js";
7
- import { C as isPersonInput, D as turnBehavior, J as getStateAdapter, _t as sameDestination, a as getConversationStore, at as agentTurnCostUsd, ct as hasAgentTurnUsage, et as withLock, it as addAgentTurnUsage, o as getDb, r as getConversationEventStore, s as getSqlExecutor } from "./db-C-2tFxk3.js";
8
- import { I as juniorArtifacts, c as juniorReviewItemSlackCards, u as juniorAutomationRuns } from "./executor-NVfS8aQ2.js";
9
- import { d as contextProvenance, f as instructionActors, m as sameActorIdentity, p as instructionProvenanceFor } from "./history-UZ3M2M9r.js";
7
+ import { T as isPersonInput, X as getStateAdapter, a as getConversationStore, k as turnBehavior, nt as withLock, o as getDb, ot as addAgentTurnUsage, r as getConversationEventStore, s as getSqlExecutor, st as agentTurnCostUsd, ut as hasAgentTurnUsage, yt as sameDestination } from "./db-EKJnkrIb.js";
8
+ import { L as juniorArtifacts, c as juniorReviewItemSlackCards, u as juniorAutomationRuns } from "./executor-CoIZmFK8.js";
9
+ import { d as contextProvenance, f as instructionActors, m as sameActorIdentity, p as instructionProvenanceFor } from "./history-m2-ceTTX.js";
10
10
  import { a as listReferenceFiles } from "./package-discovery-x4AvVhMj.js";
11
- import { c as fetchWithBoundedOAuthErrorBodies, d as actorLogContext, g as credentialUserSubjectId, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, s as OAuthProviderError } from "./registry-Bu0Z9BEO.js";
12
- import { n as pluginCatalogRuntime } from "./catalog-runtime-d1EM6Z0V.js";
13
- import { a as parseSkillInvocation, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-CNAGH4ju.js";
14
- import { C as McpProviderError, D as getMcpAwareTelemetryMessage, E as getMcpAwareErrorType, O as getMcpProviderErrorAttributes, S as putMcpStoredOAuthCredentials, T as McpToolError, _ as getMcpServerSessionId, a as serviceAccountOnly, b as putMcpAuthSession, c as createMcpServiceAccountClientProvider, d as PluginMcpClient, f as deleteMcpAuthSession, g as getMcpAuthSession, i as serviceAccountAllows, k as toMcpProviderError, l as getMcpServiceAccountCredentials, m as deleteMcpServerSessionId, u as McpAuthorizationRequiredError, v as getMcpStoredOAuthCredentials, w as McpServiceAccountRequiredError, x as putMcpServerSessionId, y as patchMcpAuthSession } from "./service-account-BcT5LR7V.js";
15
- import { l as completeObject, u as completeText } from "./prompt-D2KlJopL.js";
16
- import { a as readActorIdentityFromSql, i as readActorIdentity } from "./viewer-BPQHMx3-.js";
17
- import { G as MAX_ATTACHMENT_BYTES } from "./conversation-CY1jnBiC.js";
18
- import { Q as requireSlackChannelMessageScope, R as resolveSlackReplyTarget, X as getEventCatalog, ct as JUNIOR_PERSONALITY, d as buildPromptInput, dt as buildAgentsInstructionsMessage, f as buildSteeringPiMessage, ft as findVisibleAgentsInstructions, h as loadPromptTurnContext, ht as showsAgentsInstructions, lt as AGENTS_REMOVAL_NOTICE, mt as renderAgentsInstructions, nt as slackChannelMessageTrigger, pt as readRepositoryInstructions, u as assemblePrompt, ut as AGENTS_REPLACEMENT_NOTICE } from "./session-stop-BLLp1IP_.js";
19
- import { $ as createStopAgentTool, $r as automationToolContext, A as createWebSearchTool, Ai as resolveTaskOutcomes, Ar as positiveInteger, B as createStopWatchingResourcesTool, Br as automationIdForToolCall, C as incrementStat, Ci as requireAutomationTaskText, D as requireReadyWorkspaceSnapshot, Di as missingAutomationSkillReason, Dr as createSlackCanvasEditTool, Er as createSlackCanvasReadTool, F as userLookupIdentityProviders, Fr as createRunAutomationNowTool, G as createReadFileTool, Gr as automationTriggerSchema, H as createSearchConversationEventsTool, Hr as automationToolResult, Ir as createDeleteAutomationTool, It as storeAttachments, J as capToolResult, Jr as triggerKind, K as missingFileResult, Kr as editedAutomationTask, Lr as AUTOMATIONS_TOOL_SOURCE, Lt as createReadConversationEventTool, M as createWatchTimerTool, Mr as createOperationKey, N as createWatchEventsTool, Nr as createCanvas, Nt as readLiveAttachment, O as prepareWorkspaceSnapshot, Or as SLACK_TOOL_SOURCE, P as createUserLookupTool, Pr as createSearchAutomationsTool, Q as createUpdatePlanTool, Qn as createSlackThreadReadTool, Qr as getConversationAccess, R as createUpdateUserCustomizationTool, Rr as zodTool, Rt as createRunOperatorSqlTool, S as createWorkspaceTools, Si as requireEventAutomationTrigger, T as ensureWorkspaceSnapshotBuild, Ti as requireAutomationSkill, Tr as createSlackCanvasWriteTool, U as createSearchConversationsTool, Ur as automationToolResultSchema, V as createSearchEventTypesTool, Vr as automationSkillToolSchema, W as createWriteFileTool, Wr as automationTriggerChangesSchema, X as editFile, Xr as juniorToolOutputSchema, Xt as listAgentInvocationsForConversation, Y as createEditFileTool, Yr as injectContinuationToolName, Z as createBashTool, Zr as makeStructuredToolOutput, _r as checkSlackChannelReadAccess, a as createCacheWarmingRecorder, ar as createSlackListCreateTool, at as createNoReplyTool, b as coreToolSlots, bi as editEventAutomation, cr as createSlackConversationSearchChannelPort, ei as automationToolsDisabledReason, et as createSpawnAgentTool, gr as slackChannelRefParam, hr as resolveSlackChannelRef, ht as createUpdateReviewItemTool, ii as requireToolDestination, ir as createSlackListGetItemsTool, it as createReplyTool, j as createWebFetchTool, jr as resolveWorkspacePath, ki as moveTaskOutcomes, kr as isMissingPathError, lr as createSlackChannelListMessagesTool, mr as createSlackChannelJoinTool, mt as createSearchReviewItemsTool, ni as requireToolCaller, nr as createSlackPublicSearchTool, nt as createReportProgressTool, oi as automationEditor, or as createSlackListAddItemsTool, ot as createMessageAgentTool, pt as createAddReviewItemTool, q as sliceFileContent, qn as createSetConversationSubscriptionTool, qr as newAutomationTask, ri as requireToolCreator, rr as createSlackListUpdateItemTool, rt as createReportBlockedTool, si as changeAutomationLifecycle, sn as isParentMessageMeta, sr as createSlackConversationMessageSearchTool, st as createArchiveAgentTool, ti as requireToolAutomation, tt as createListAgentsTool, vr as joinPublicChannelForRead, x as enabledMode, xi as changedEventMatch, yi as editScheduledAutomation, z as createSystemTimeTool, zr as zodToolDefinition, zt as createListWatchesTool } from "./warmup-H8uLvW9e.js";
20
- import { D as automationTitleSchema, E as automationInstructionToolSchema, F as compileScheduleIntent, I as scheduleIntentFromTool, O as taskOutcomeInputSchema, P as ScheduleIntentError, T as automationContextToolSchema, V as automationTaskDescription, j as SCHEDULED_AUTOMATION_SYSTEM_ACTOR } from "./automation-D9MvhOWY.js";
21
- import { G as readScheduledAutomation, K as saveScheduledAutomation, Q as createEventAutomation, V as createScheduledAutomation, it as saveEventAutomation, mt as automationRevision, t as resolveConversationRouting, tt as getEventAutomation } from "./turn-session-routing-DGvn9MSl.js";
11
+ import { c as fetchWithBoundedOAuthErrorBodies, d as actorLogContext, g as credentialUserSubjectId, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, s as OAuthProviderError } from "./registry-DBDNUUmz.js";
12
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-B8ZXvXWm.js";
13
+ import { a as parseSkillInvocation, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-2UrD7JkN.js";
14
+ import { C as McpProviderError, D as getMcpAwareTelemetryMessage, E as getMcpAwareErrorType, O as getMcpProviderErrorAttributes, S as putMcpStoredOAuthCredentials, T as McpToolError, _ as getMcpServerSessionId, a as serviceAccountOnly, b as putMcpAuthSession, c as createMcpServiceAccountClientProvider, d as PluginMcpClient, f as deleteMcpAuthSession, g as getMcpAuthSession, i as serviceAccountAllows, k as toMcpProviderError, l as getMcpServiceAccountCredentials, m as deleteMcpServerSessionId, u as McpAuthorizationRequiredError, v as getMcpStoredOAuthCredentials, w as McpServiceAccountRequiredError, x as putMcpServerSessionId, y as patchMcpAuthSession } from "./service-account-2HmlNPvy.js";
15
+ import { f as generateImages, h as NoAudioError, l as completeObject, m as transcribeFromUrl, u as completeText } from "./prompt-DSjhoKu5.js";
16
+ import { a as readActorIdentityFromSql, i as readActorIdentity } from "./viewer-Cf8ISkAc.js";
17
+ import { W as MAX_ATTACHMENT_BYTES } from "./conversation-BOqdRtUx.js";
18
+ import { Q as requireSlackChannelMessageScope, R as resolveSlackReplyTarget, X as getEventCatalog, _t as foldSystemMessages, bt as writeAgentHistory, ct as JUNIOR_PERSONALITY, d as buildPromptInput, dt as buildAgentsInstructionsMessage, f as buildSteeringPiMessage, ft as findVisibleAgentsInstructions, gt as foldLeadingSystemMessages, h as loadPromptTurnContext, ht as showsAgentsInstructions, lt as AGENTS_REMOVAL_NOTICE, mt as renderAgentsInstructions, nt as slackChannelMessageTrigger, pt as readRepositoryInstructions, u as assemblePrompt, ut as AGENTS_REPLACEMENT_NOTICE, vt as readAgentHistory, yt as withAgentRequest } from "./session-stop-DEeZKqbX.js";
19
+ import { $ as createBashTool, $n as createSlackPublicSearchTool, $r as requireToolCreator, A as createWebSearchTool, Ar as createSearchAutomationsTool, B as createSystemTimeTool, Br as automationTriggerChangesSchema, C as incrementStat, Ci as missingAutomationSkillReason, Cr as createSlackCanvasEditTool, D as requireReadyWorkspaceSnapshot, Dr as resolveWorkspacePath, Ei as resolveTaskOutcomes, Er as positiveInteger, F as userLookupIdentityProviders, Fr as zodToolDefinition, Ft as createRunOperatorSqlTool, G as createWriteFileTool, Gr as injectContinuationToolName, H as createSearchEventTypesTool, Hr as editedAutomationTask, Ir as automationIdForToolCall, It as createListWatchesTool, J as sliceFileContent, Jr as getConversationAccess, K as createReadFileTool, Kr as juniorToolOutputSchema, Lr as automationSkillToolSchema, M as createWatchTimerTool, Mr as createDeleteAutomationTool, N as createWatchEventsTool, Nr as AUTOMATIONS_TOOL_SOURCE, O as prepareWorkspaceSnapshot, Or as createOperationKey, P as createUserLookupTool, Pr as zodTool, Pt as createReadConversationEventTool, Q as editFile, Qr as requireToolCaller, R as createUpdateUserCustomizationTool, Rr as automationToolResult, S as createWorkspaceTools, Sr as createSlackCanvasReadTool, T as ensureWorkspaceSnapshotBuild, Ti as moveTaskOutcomes, Tr as isMissingPathError, U as createSearchConversationEventsTool, Ur as newAutomationTask, V as createStopWatchingResourcesTool, Vr as automationTriggerSchema, W as createSearchConversationsTool, Wn as createSetConversationSubscriptionTool, Wr as triggerKind, X as capToolResult, Xr as automationToolsDisabledReason, Y as TOOL_RESULT_MAX_CHARS, Yn as createSlackThreadReadTool, Yr as automationToolContext, Z as createEditFileTool, Zr as requireToolAutomation, _i as changedEventMatch, _t as createUpdateReviewItemTool, a as createCacheWarmingRecorder, ar as createSlackConversationSearchChannelPort, at as createReportBlockedTool, b as coreToolSlots, ct as createMessageAgentTool, dr as resolveSlackChannelRef, ei as requireToolDestination, er as createSlackListUpdateItemTool, et as createUpdatePlanTool, fr as slackChannelRefParam, gi as editEventAutomation, gt as createSearchReviewItemsTool, hi as editScheduledAutomation, ht as createAddReviewItemTool, in as isParentMessageMeta, ir as createSlackConversationMessageSearchTool, it as createReportProgressTool, j as createWebFetchTool, jr as createRunAutomationNowTool, kr as createCanvas, lt as createArchiveAgentTool, mr as joinPublicChannelForRead, ni as automationEditor, nr as createSlackListCreateTool, nt as createSpawnAgentTool, or as createSlackChannelListMessagesTool, ot as createReplyTool, pr as checkSlackChannelReadAccess, q as missingFileResult, qr as makeStructuredToolOutput, qt as listAgentInvocationsForConversation, ri as changeAutomationLifecycle, rr as createSlackListAddItemsTool, rt as createListAgentsTool, st as createNoReplyTool, tr as createSlackListGetItemsTool, tt as createStopAgentTool, ur as createSlackChannelJoinTool, vi as requireEventAutomationTrigger, wr as SLACK_TOOL_SOURCE, x as enabledMode, xi as requireAutomationSkill, xr as createSlackCanvasWriteTool, yi as requireAutomationTaskText, z as createSubmitFeedbackTool, zr as automationToolResultSchema } from "./warmup-TgY4S1vx.js";
20
+ import { D as automationTitleSchema, E as automationInstructionToolSchema, F as compileScheduleIntent, I as scheduleIntentFromTool, O as taskOutcomeInputSchema, P as ScheduleIntentError, T as automationContextToolSchema, V as automationTaskDescription, j as SCHEDULED_AUTOMATION_SYSTEM_ACTOR } from "./automation-CuA3yEcD.js";
21
+ import { G as readScheduledAutomation, K as saveScheduledAutomation, Q as createEventAutomation, V as createScheduledAutomation, it as saveEventAutomation, mt as automationRevision, t as resolveConversationRouting, tt as getEventAutomation } from "./turn-session-routing-CaY3Tp8m.js";
22
22
  import { a as USER_INPUT_LIMITS, i as AGENT_INVOCATION_STATUSES, m as detectImageMediaType, o as USER_INPUT_NOTE, s as buttonUserInputField, u as normalizeUserInputAnswer } from "./web-message-id-lNodcCOI.js";
23
- import { d as isTurnInputCommitLostError, o as CooperativeTurnYieldError, s as TurnInputCommitLostError } from "./turn-user-message-19CkuUvM.js";
24
- import { l as QUEUE_SIGNATURE_MAX_AGE_MS, n as backgroundCompactionId, o as getVercelConversationWorkQueue } from "./background-compaction-queue-xaE05jxH.js";
25
- import { o as getSandboxResources, r as setSnapshotSpanAttributes } from "./install-CHLrpRZc.js";
26
- import { n as resolve$1 } from "./resolve-DXuA3G0g.js";
27
- import { t as runWithSlackInstallation } from "./adapter-context-BdVnSuY5.js";
23
+ import { d as isTurnInputCommitLostError, o as CooperativeTurnYieldError, s as TurnInputCommitLostError } from "./turn-user-message-tcom1RYd.js";
24
+ import { l as QUEUE_SIGNATURE_MAX_AGE_MS, n as backgroundCompactionId, o as getVercelConversationWorkQueue } from "./background-compaction-queue-WLPNSF_b.js";
25
+ import { o as getSandboxResources, r as setSnapshotSpanAttributes } from "./install-BT2Pf6HP.js";
26
+ import { n as resolve$1 } from "./resolve-CQLhMWSu.js";
27
+ import { t as runWithSlackInstallation } from "./adapter-context-B1IpoELr.js";
28
28
  import { n as privateTraceResultAttributes } from "./private-trace-result-CE7_lEdq.js";
29
29
  import * as z from "zod";
30
30
  import { streamSimple } from "@earendil-works/pi-ai/compat";
31
- import { createGatewayProvider } from "@ai-sdk/gateway";
32
- import { NoImageGeneratedError, generateImage } from "ai";
33
31
  import path from "node:path";
34
32
  import { isDeepStrictEqual } from "node:util";
35
33
  import { AsyncLocalStorage } from "node:async_hooks";
36
34
  import { createHash, randomBytes, randomInt, randomUUID } from "node:crypto";
35
+ import { createAssistantMessageEventStream, getInitialSystemMessage, getSystemMessageText as getSystemMessageText$1, isRetryableAssistantError, mergeClientIdentity } from "@earendil-works/pi-ai";
37
36
  import { and, eq, inArray, isNull } from "drizzle-orm";
38
37
  import { declaredEventKeys, missingToolAnnotationKeys, ownedObjectAnnotationSchema } from "@sentry/junior-plugin-api";
39
38
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
@@ -42,7 +41,6 @@ import fs from "node:fs/promises";
42
41
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
43
42
  import { SignJWT, importPKCS8 } from "jose";
44
43
  import { performance as performance$1 } from "node:perf_hooks";
45
- import { createAssistantMessageEventStream, isRetryableAssistantError, mergeClientIdentity } from "@earendil-works/pi-ai";
46
44
  import { Bash, defineCommand } from "just-bash";
47
45
  import { Kind } from "@sinclair/typebox";
48
46
  import { Value } from "@sinclair/typebox/value";
@@ -643,36 +641,6 @@ function serializeMcpPayload(payload, privacy, options = {}) {
643
641
  if (privacy !== "private") return serializeGenAiAttribute(payload);
644
642
  return options.privateMetadata ? serializeGenAiAttribute(toGenAiPayloadMetadata(payload)) : void 0;
645
643
  }
646
- // src/chat/pi/agent-history.ts
647
- function isSystemMessage(message) {
648
- return message.role === "system";
649
- }
650
- /** Return Junior history: the messages without Pi's system messages. */
651
- function readAgentHistory(messages) {
652
- return messages.filter((message) => !isSystemMessage(message));
653
- }
654
- /**
655
- * Return the message list that replaces `current` with `history`. The leading
656
- * system message of `current` stays first. System messages in `history` are
657
- * dropped.
658
- */
659
- function writeAgentHistory(current, history) {
660
- const leading = current[0];
661
- const messages = readAgentHistory(history);
662
- return leading && isSystemMessage(leading) ? [leading, ...messages] : messages;
663
- }
664
- /**
665
- * Give the stream path Junior's own system prompt and tools, with Junior
666
- * history as the messages. The traced stream and cache warming then read the
667
- * same request on every Pi version, without Pi's system messages.
668
- */
669
- function withAgentRequest(base, request) {
670
- return (model, context, options) => base(model, {
671
- systemPrompt: request.systemPrompt,
672
- messages: readAgentHistory(context.messages),
673
- tools: request.tools
674
- }, options);
675
- }
676
644
  // src/chat/agent/repository-context.ts
677
645
  function findRestoredInstructions(messages, provenance) {
678
646
  const restoredContext = messages?.map((message, index) => ({
@@ -3492,10 +3460,6 @@ function createImageGenerateTool(hooks, options, deps = {}) {
3492
3460
  }),
3493
3461
  outputSchema: imageGenerateOutputSchema,
3494
3462
  execute: async ({ prompt, images = [] }) => {
3495
- const gateway = createGatewayProvider({
3496
- apiKey: await getGatewayApiKey(),
3497
- ...deps.fetch ? { fetch: deps.fetch } : void 0
3498
- });
3499
3463
  const model = options.modelId;
3500
3464
  const { images: inputImages, resized } = await fitImagesToRequest(await Promise.all(images.map(async (path) => ({
3501
3465
  path,
@@ -3505,22 +3469,20 @@ function createImageGenerateTool(hooks, options, deps = {}) {
3505
3469
  resized_images: resized,
3506
3470
  resize_notice: "Some input images were too large for the image model, so they were resized first. Tell the user which images were resized."
3507
3471
  } : {};
3508
- const enrichedPrompt = inputImages.length > 0 ? prompt : await enrichImagePrompt(prompt, options.promptCost);
3509
- let generatedImages;
3510
- try {
3511
- ({images: generatedImages} = await generateImage({
3512
- model: gateway.imageModel(model),
3513
- prompt: inputImages.length > 0 ? {
3514
- text: enrichedPrompt,
3515
- images: inputImages.map((image) => image.data)
3516
- } : enrichedPrompt,
3517
- n: 1
3518
- }));
3519
- } catch (error) {
3520
- if (NoImageGeneratedError.isInstance(error)) generatedImages = [];
3521
- else if (error instanceof Error && error.message.includes("not an image model")) throw new Error(`image generation failed: configured model "${model}" is not an image generation model. Set AI_IMAGE_MODEL to an AI Gateway image model.`, { cause: error });
3522
- else throw error;
3523
- }
3472
+ const enrichedPrompt = inputImages.length > 0 ? prompt : await enrichImagePrompt(prompt, options.modelCost);
3473
+ const { images: generatedImages } = await generateImages({
3474
+ operation: "image_generation",
3475
+ cost: options.modelCost,
3476
+ modelId: model,
3477
+ prompt: inputImages.length > 0 ? {
3478
+ text: enrichedPrompt,
3479
+ images: inputImages.map((image) => image.data)
3480
+ } : enrichedPrompt,
3481
+ fetch: deps.fetch
3482
+ }).catch((error) => {
3483
+ if (error instanceof Error && error.message.includes("not an image model")) throw new Error(`image generation failed: configured model "${model}" is not an image generation model. Set AI_IMAGE_MODEL to an AI Gateway image model.`, { cause: error });
3484
+ throw error;
3485
+ });
3524
3486
  const uploads = generatedImages.map((image, index) => ({
3525
3487
  data: Buffer.from(image.uint8Array),
3526
3488
  filename: `generated-image-${Date.now()}-${index + 1}.${extensionForMediaType(image.mediaType)}`,
@@ -3550,6 +3512,430 @@ function createImageGenerateTool(hooks, options, deps = {}) {
3550
3512
  }
3551
3513
  });
3552
3514
  }
3515
+ // src/chat/attachments/download.ts
3516
+ /** Refusal for a file over `MAX_ATTACHMENT_BYTES`. */
3517
+ const ATTACHMENT_TOO_LARGE_MESSAGE = `Attachment is larger than the ${MAX_ATTACHMENT_BYTES / 1024 / 1024} MB file limit.`;
3518
+ /** An attachment whose bytes cannot be read. The message is safe to show. */
3519
+ var AttachmentDownloadError = class extends Error {
3520
+ constructor(message, options) {
3521
+ super(message, options);
3522
+ this.name = "AttachmentDownloadError";
3523
+ }
3524
+ };
3525
+ /**
3526
+ * Look up the source file of an unstored row, with the size check done.
3527
+ * Errors that the person should see are `AttachmentDownloadError`.
3528
+ */
3529
+ async function readSourceFile(attachment, readAttachmentSource) {
3530
+ const { source } = attachment;
3531
+ if (!source || !readAttachmentSource) throw new AttachmentDownloadError("Attachment cannot be downloaded from this conversation.");
3532
+ let file;
3533
+ try {
3534
+ file = await readAttachmentSource(source);
3535
+ } catch (error) {
3536
+ throw unavailableError(attachment, error);
3537
+ }
3538
+ if (file.bytes > 262144e3) throw new AttachmentDownloadError(ATTACHMENT_TOO_LARGE_MESSAGE);
3539
+ return {
3540
+ file,
3541
+ source
3542
+ };
3543
+ }
3544
+ function unavailableError(attachment, error) {
3545
+ return error instanceof AttachmentSourceUnavailableError ? new AttachmentDownloadError(`${attachment.filename} is no longer available: ${error.message}`, { cause: error }) : error;
3546
+ }
3547
+ /**
3548
+ * Find where the bytes of one attachment row are, without reading them.
3549
+ *
3550
+ * A stored file reads from storage. A large Slack file that no read has
3551
+ * stored yet downloads from its source on each `open`. The source reports
3552
+ * the current size, and the size check runs before any download. Errors that
3553
+ * the person should see are `AttachmentDownloadError`, from here or from
3554
+ * `open`. Callers that need the bytes more than once use
3555
+ * `storeAttachmentOnFirstUse` first.
3556
+ *
3557
+ * The row must come from a lookup scoped to the caller's conversation. The
3558
+ * source id comes from that row only, never from a request.
3559
+ */
3560
+ async function readAttachmentContent(args) {
3561
+ const { attachment, storage } = args;
3562
+ const { storageKey } = attachment;
3563
+ if (storageKey !== null) return {
3564
+ bytes: attachment.bytes,
3565
+ open: async () => {
3566
+ const body = await storage.get(storageKey);
3567
+ if (!body) throw new AttachmentDownloadError("Stored attachment contents are unavailable.");
3568
+ return body;
3569
+ }
3570
+ };
3571
+ const { file } = await readSourceFile(attachment, args.readAttachmentSource);
3572
+ return {
3573
+ bytes: file.bytes,
3574
+ open: async () => {
3575
+ try {
3576
+ return await file.open();
3577
+ } catch (error) {
3578
+ throw unavailableError(attachment, error);
3579
+ }
3580
+ }
3581
+ };
3582
+ }
3583
+ /**
3584
+ * Return the row of one attachment with its bytes in storage.
3585
+ *
3586
+ * A large Slack file is recorded without its bytes. The first read that
3587
+ * needs them streams the file from its source into storage once, and later
3588
+ * reads use storage. The same rules as `readAttachmentContent` apply to the
3589
+ * row and to errors.
3590
+ */
3591
+ async function storeAttachmentOnFirstUse(args) {
3592
+ const { attachment } = args;
3593
+ const { storageKey } = attachment;
3594
+ if (storageKey !== null) return {
3595
+ ...attachment,
3596
+ storageKey
3597
+ };
3598
+ const { file, source } = await readSourceFile(attachment, args.readAttachmentSource);
3599
+ let stored;
3600
+ try {
3601
+ stored = await withSpan("attachment.store", "attachment.store", {}, async () => await storeDeferredAttachment({
3602
+ attachment: {
3603
+ ...attachment,
3604
+ source
3605
+ },
3606
+ db: args.db,
3607
+ file,
3608
+ storage: args.storage
3609
+ }), {
3610
+ "app.attachment.source.provider": source.provider,
3611
+ "file.size": file.bytes
3612
+ });
3613
+ } catch (error) {
3614
+ throw unavailableError(attachment, error);
3615
+ }
3616
+ if (!stored) throw new AttachmentDownloadError(`${attachment.filename} is no longer available.`);
3617
+ return stored;
3618
+ }
3619
+ // src/chat/attachments/tool-params.ts
3620
+ /** Model-facing id of one attachment in the current Conversation. */
3621
+ const attachmentIdParam = z.string().min(1).describe("Stored attachment ID, as shown in attachment context or Slack read results.");
3622
+ // src/chat/tools/load-attachment.ts
3623
+ /** Sandbox directory for attachment files that tools write. */
3624
+ const ATTACHMENT_DIR = ".junior/attachments";
3625
+ /** Bytes held in memory and sent to the sandbox in one write. */
3626
+ const PART_BYTES = 8388608;
3627
+ const JOIN_PARTS_SCRIPT = "set -eu; out=$1; shift; cat -- \"$@\" > \"$out\"";
3628
+ /** Turn a read failure that the model can relay into a tool error. */
3629
+ function toolError(error) {
3630
+ return error instanceof AttachmentDownloadError ? new ToolInputError(error.message, { cause: error }) : error;
3631
+ }
3632
+ /** Run one sandbox command, and return its stdout. Throw when it fails. */
3633
+ async function runChecked(workspace, action, input) {
3634
+ const result = await workspace.runCommand(input);
3635
+ if (result.exitCode !== 0) throw new Error(`Failed to ${action}: ${result.stderr}`);
3636
+ return result.stdout;
3637
+ }
3638
+ /**
3639
+ * Write an attachment body to the sandbox in parts of at most `PART_BYTES`.
3640
+ *
3641
+ * The sandbox SDK writes only whole buffers, so this keeps one part in
3642
+ * memory, not the file. Returns the part paths in order.
3643
+ */
3644
+ async function writeParts(args) {
3645
+ const parts = [];
3646
+ let pending = [];
3647
+ let pendingBytes = 0;
3648
+ let total = 0;
3649
+ const flush = async () => {
3650
+ const partPath = path.posix.join(args.partsDir, String(parts.length).padStart(4, "0"));
3651
+ await args.workspace.writeFiles([{
3652
+ content: Buffer.concat(pending),
3653
+ path: partPath
3654
+ }]);
3655
+ parts.push(partPath);
3656
+ pending = [];
3657
+ pendingBytes = 0;
3658
+ };
3659
+ const reader = args.body.getReader();
3660
+ try {
3661
+ for (;;) {
3662
+ const { done, value } = await reader.read();
3663
+ if (done) break;
3664
+ total += value.byteLength;
3665
+ if (total > args.expectedBytes) break;
3666
+ let chunk = value;
3667
+ while (pendingBytes + chunk.byteLength >= PART_BYTES) {
3668
+ const take = PART_BYTES - pendingBytes;
3669
+ pending.push(chunk.subarray(0, take));
3670
+ pendingBytes += take;
3671
+ await flush();
3672
+ chunk = chunk.subarray(take);
3673
+ }
3674
+ if (chunk.byteLength > 0) {
3675
+ pending.push(chunk);
3676
+ pendingBytes += chunk.byteLength;
3677
+ }
3678
+ }
3679
+ } finally {
3680
+ await reader.cancel().catch(() => void 0);
3681
+ }
3682
+ if (total !== args.expectedBytes) throw new Error(`Attachment ${args.attachmentId} read ${total} bytes, expected ${args.expectedBytes}.`);
3683
+ if (pendingBytes > 0 || parts.length === 0) await flush();
3684
+ return parts;
3685
+ }
3686
+ /**
3687
+ * Create a tool that restores one conversation attachment to the sandbox.
3688
+ *
3689
+ * The first load of a large Slack file streams it from Slack into storage
3690
+ * through the host. The sandbox never gets a Slack URL or token.
3691
+ *
3692
+ * @runBuilt loadAttachment
3693
+ */
3694
+ function createLoadAttachmentTool(args) {
3695
+ return zodTool({
3696
+ description: "Load a stored attachment for this conversation into the sandbox.",
3697
+ annotations: {
3698
+ destructiveHint: false,
3699
+ idempotentHint: true,
3700
+ openWorldHint: true,
3701
+ readOnlyHint: false
3702
+ },
3703
+ inputSchema: z.object({ attachment_id: attachmentIdParam }),
3704
+ outputSchema: juniorToolOutputSchema,
3705
+ execute: async ({ attachment_id }) => {
3706
+ const attachment = await readLiveAttachment({
3707
+ attachmentId: attachment_id,
3708
+ conversationId: args.conversationId,
3709
+ db: args.db
3710
+ });
3711
+ if (!attachment || attachment.storageProvider !== args.storage.provider) throw new ToolInputError("Attachment not found in this conversation.");
3712
+ if (attachment.bytes > 262144e3) throw new ToolInputError(ATTACHMENT_TOO_LARGE_MESSAGE);
3713
+ let content;
3714
+ try {
3715
+ content = await readAttachmentContent({
3716
+ attachment: await storeAttachmentOnFirstUse({
3717
+ attachment,
3718
+ db: args.db,
3719
+ readAttachmentSource: args.readAttachmentSource,
3720
+ storage: args.storage
3721
+ }),
3722
+ storage: args.storage
3723
+ });
3724
+ } catch (error) {
3725
+ throw toolError(error);
3726
+ }
3727
+ const attachmentDir = path.posix.join(ATTACHMENT_DIR, attachment.id);
3728
+ const partsDir = `${attachmentDir}.parts`;
3729
+ const sandboxPath = path.posix.join(attachmentDir, path.posix.basename(attachment.filename));
3730
+ await runChecked(args.workspace, "create attachment directory", {
3731
+ cmd: "mkdir",
3732
+ args: [
3733
+ "-p",
3734
+ "--",
3735
+ attachmentDir,
3736
+ partsDir
3737
+ ]
3738
+ });
3739
+ const joinedPath = path.posix.join(partsDir, "joined");
3740
+ try {
3741
+ const parts = await writeParts({
3742
+ attachmentId: attachment.id,
3743
+ body: await content.open(),
3744
+ expectedBytes: content.bytes,
3745
+ partsDir,
3746
+ workspace: args.workspace
3747
+ });
3748
+ await runChecked(args.workspace, "join attachment parts", {
3749
+ cmd: "sh",
3750
+ args: [
3751
+ "-c",
3752
+ JOIN_PARTS_SCRIPT,
3753
+ "sh",
3754
+ joinedPath,
3755
+ ...parts
3756
+ ]
3757
+ });
3758
+ const size = await runChecked(args.workspace, "read attachment size", {
3759
+ cmd: "stat",
3760
+ args: [
3761
+ "-c",
3762
+ "%s",
3763
+ "--",
3764
+ joinedPath
3765
+ ]
3766
+ });
3767
+ const written = Number(size.trim());
3768
+ if (written !== content.bytes) throw new Error(`Attachment ${attachment.id} wrote ${written} bytes to the sandbox, expected ${content.bytes}.`);
3769
+ await runChecked(args.workspace, "move attachment into place", {
3770
+ cmd: "mv",
3771
+ args: [
3772
+ "-f",
3773
+ "--",
3774
+ joinedPath,
3775
+ sandboxPath
3776
+ ]
3777
+ });
3778
+ } catch (error) {
3779
+ await args.workspace.runCommand({
3780
+ cmd: "rm",
3781
+ args: [
3782
+ "-rf",
3783
+ "--",
3784
+ partsDir
3785
+ ]
3786
+ }).catch(() => void 0);
3787
+ throw toolError(error);
3788
+ }
3789
+ await runChecked(args.workspace, "remove attachment parts", {
3790
+ cmd: "rm",
3791
+ args: [
3792
+ "-rf",
3793
+ "--",
3794
+ partsDir
3795
+ ]
3796
+ });
3797
+ return {
3798
+ path: sandboxPath,
3799
+ filename: attachment.filename,
3800
+ mime_type: attachment.contentType,
3801
+ bytes: content.bytes
3802
+ };
3803
+ }
3804
+ });
3805
+ }
3806
+ // src/chat/tools/transcribe-audio.ts
3807
+ /** Deferred tool catalog source for speech transcription. */
3808
+ const AUDIO_TOOL_SOURCE = {
3809
+ id: "audio",
3810
+ description: "Transcribe speech in audio and video attachments."
3811
+ };
3812
+ const DOWNLOAD_URL_TTL_MS = 3e5;
3813
+ const UNTYPED_CONTENT_TYPE = "application/octet-stream";
3814
+ const INLINE_RESERVE_CHARS = 1e3;
3815
+ const transcribeAudioOutputSchema = juniorToolOutputSchema.extend({
3816
+ transcript: z.string(),
3817
+ transcript_path: z.string().optional(),
3818
+ note: z.string().optional(),
3819
+ language: z.string().optional(),
3820
+ duration_seconds: z.number().nonnegative().optional()
3821
+ }).strict();
3822
+ function mayHaveAudio(contentType) {
3823
+ const mediaType = contentType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
3824
+ return mediaType.startsWith("audio/") || mediaType.startsWith("video/") || mediaType === UNTYPED_CONTENT_TYPE;
3825
+ }
3826
+ /** Format seconds as `MM:SS.s`, or `H:MM:SS.s` from one hour. */
3827
+ function timestamp(seconds) {
3828
+ const tenths = Math.floor(seconds * 10);
3829
+ const hours = Math.floor(tenths / 36e3);
3830
+ const time = `${String(Math.floor(tenths / 600) % 60).padStart(2, "0")}:${String(Math.floor(tenths / 10) % 60).padStart(2, "0")}.${tenths % 10}`;
3831
+ return hours > 0 ? `${hours}:${time}` : time;
3832
+ }
3833
+ /** One log-style line per entry: start time, then speaker and text. */
3834
+ function transcriptLine(entry) {
3835
+ const text = entry.text.replace(/\s+/g, " ");
3836
+ const body = entry.kind === "sound" ? `(${text})` : entry.speaker ? `${entry.speaker}: ${text}` : text;
3837
+ return `[${timestamp(entry.startSeconds)}] ${body}`;
3838
+ }
3839
+ /**
3840
+ * Keep the leading lines whose JSON-escaped size fits in `budget` chars.
3841
+ * The cut is always on a line boundary.
3842
+ */
3843
+ function leadingLines(lines, budget) {
3844
+ let used = 0;
3845
+ let count = 0;
3846
+ for (const line of lines) {
3847
+ used += JSON.stringify(line).length - 2 + (count > 0 ? 2 : 0);
3848
+ if (used > budget) break;
3849
+ count += 1;
3850
+ }
3851
+ return {
3852
+ text: lines.slice(0, count).join("\n"),
3853
+ truncated: count < lines.length
3854
+ };
3855
+ }
3856
+ /**
3857
+ * Create a tool that transcribes speech in one Conversation attachment.
3858
+ *
3859
+ * The model provider downloads the file from a short-lived signed URL. The
3860
+ * URL never leaves this call. A large Slack file is stored first, so its
3861
+ * first transcription streams it through the host once.
3862
+ *
3863
+ * @runBuilt transcribeAudio
3864
+ */
3865
+ function createTranscribeAudioTool(args) {
3866
+ return zodTool({
3867
+ exposure: "deferred",
3868
+ source: AUDIO_TOOL_SOURCE,
3869
+ description: "Transcribe speech in an audio or video attachment. Returns a transcript with one line per entry: `[MM:SS.s] speaker: text` for speech and `[MM:SS.s] (sound)` for sounds. The full transcript is saved at `transcript_path`. When `truncated` is true, the inline transcript has only the first lines: read the rest of the file with readFile, or search it with grep. When the save fails, `transcript_path` is absent and `note` says so.",
3870
+ annotations: {
3871
+ destructiveHint: false,
3872
+ idempotentHint: true,
3873
+ openWorldHint: true,
3874
+ readOnlyHint: true
3875
+ },
3876
+ inputSchema: z.object({ attachment_id: attachmentIdParam }),
3877
+ outputSchema: transcribeAudioOutputSchema,
3878
+ execute: async ({ attachment_id }, { signal }) => {
3879
+ const attachment = await readLiveAttachment({
3880
+ attachmentId: attachment_id,
3881
+ conversationId: args.conversationId,
3882
+ db: args.db
3883
+ });
3884
+ if (!attachment || attachment.storageProvider !== args.storage.provider) throw new ToolInputError("Attachment not found in this conversation.");
3885
+ if (!mayHaveAudio(attachment.contentType)) throw new ToolInputError(`This attachment is ${attachment.contentType}, not audio or video.`);
3886
+ const { storageKey } = await storeAttachmentOnFirstUse({
3887
+ attachment,
3888
+ db: args.db,
3889
+ readAttachmentSource: args.readAttachmentSource,
3890
+ storage: args.storage
3891
+ }).catch((error) => {
3892
+ if (error instanceof AttachmentDownloadError) throw new ToolInputError(error.message, { cause: error });
3893
+ throw error;
3894
+ });
3895
+ const sourceUrl = await args.storage.createDownloadUrl({
3896
+ expiresAtMs: Date.now() + DOWNLOAD_URL_TTL_MS,
3897
+ key: storageKey
3898
+ });
3899
+ const transcript = await transcribeFromUrl({
3900
+ cost: args.modelCost,
3901
+ modelId: args.modelId,
3902
+ operation: "transcription",
3903
+ signal,
3904
+ sourceUrl
3905
+ }).catch((error) => {
3906
+ if (error instanceof NoAudioError) throw new ToolInputError(error.message, { cause: error });
3907
+ throw error;
3908
+ });
3909
+ const lines = transcript.entries.map(transcriptLine);
3910
+ const transcriptPath = path.posix.join(ATTACHMENT_DIR, `${attachment.id}.transcript.txt`);
3911
+ let saved = true;
3912
+ try {
3913
+ await args.workspace.writeFiles([{
3914
+ content: `${lines.join("\n")}\n`,
3915
+ path: transcriptPath
3916
+ }]);
3917
+ } catch (error) {
3918
+ saved = false;
3919
+ logWarn("tool.transcript.write.failed", { "exception.message": String(error) });
3920
+ }
3921
+ const result = {
3922
+ ...saved ? { transcript_path: transcriptPath } : { note: "The full transcript was not saved." },
3923
+ ...transcript.language ? { language: transcript.language } : void 0,
3924
+ ...transcript.durationSeconds !== void 0 ? { duration_seconds: transcript.durationSeconds } : void 0
3925
+ };
3926
+ const inline = leadingLines(lines, TOOL_RESULT_MAX_CHARS - INLINE_RESERVE_CHARS - JSON.stringify({
3927
+ ...result,
3928
+ transcript: "",
3929
+ truncated: true
3930
+ }).length);
3931
+ return {
3932
+ ...result,
3933
+ transcript: inline.text,
3934
+ ...inline.truncated ? { truncated: true } : void 0
3935
+ };
3936
+ }
3937
+ });
3938
+ }
3553
3939
  // src/chat/mcp/tool-name.ts
3554
3940
  /** Extract the provider from canonical `mcp__<provider>__<tool>` names. */
3555
3941
  function parseMcpProviderFromToolName(toolName) {
@@ -4083,6 +4469,17 @@ function slackUserInputAnswerNote(args) {
4083
4469
  if (answer.other) lines.push(`*Other*: ${escapeSlackMrkdwnText(answer.other)}`);
4084
4470
  return truncate$2([`${who} answered`, ...lines].join("\n"), MAX_NOTE_CHARS);
4085
4471
  }
4472
+ // src/net/link-url.ts
4473
+ /**
4474
+ * Return the normalized href of an HTTP or HTTPS link, or undefined. Agents,
4475
+ * plugins and messages supply these links, and URL parsing also accepts
4476
+ * `javascript:` and `data:` URLs.
4477
+ */
4478
+ function safeLinkUrl(url) {
4479
+ if (!url || !URL.canParse(url)) return void 0;
4480
+ const href = new URL(url);
4481
+ return href.protocol === "https:" || href.protocol === "http:" ? href.href : void 0;
4482
+ }
4086
4483
  // src/chat/slack/review-item-card.ts
4087
4484
  /** Callback id of the modal form that answers a Review item. */
4088
4485
  const SLACK_REVIEW_ITEM_VIEW_ID = "junior_review_item";
@@ -4119,11 +4516,6 @@ function titleText(item) {
4119
4516
  if (!href) return `**${item.title}**`;
4120
4517
  return `**[${item.title.replace(/[[\]\\]/g, "\\$&")}](${href.replaceAll("(", "%28").replaceAll(")", "%29")})**`;
4121
4518
  }
4122
- function safeLinkUrl(url) {
4123
- if (!url || !URL.canParse(url)) return void 0;
4124
- const href = new URL(url);
4125
- return href.protocol === "https:" || href.protocol === "http:" ? href.href : void 0;
4126
- }
4127
4519
  /** The title, body, and question of an item, in Slack markdown. */
4128
4520
  function itemText(item) {
4129
4521
  return normalizeSlackReplyMarkdown([
@@ -4420,7 +4812,7 @@ async function findSlackMentionedUserId(text, tenant) {
4420
4812
  const slackUserId = parseSlackUserId(SLACK_MENTION.exec(text)?.[1] ?? text);
4421
4813
  if (!slackUserId) return void 0;
4422
4814
  const user = tenant?.provider === "slack" ? (await readActorIdentityFromSql(getDb(), createSlackActor(tenant.providerTenantId, slackUserId, void 0)))?.user : void 0;
4423
- if (!user) throw new ToolInputError(`<@${slackUserId}> has no Junior user yet. Assign them by email.`);
4815
+ if (!user) throw new ToolInputError(`<@${slackUserId}> has no User yet. Assign them by email.`);
4424
4816
  return user.id;
4425
4817
  }
4426
4818
  /**
@@ -5229,238 +5621,6 @@ function createUnpublishImageTool(args) {
5229
5621
  }
5230
5622
  });
5231
5623
  }
5232
- // src/chat/attachments/download.ts
5233
- /** Refusal for a file over `MAX_ATTACHMENT_BYTES`. */
5234
- const ATTACHMENT_TOO_LARGE_MESSAGE = `Attachment is larger than the ${MAX_ATTACHMENT_BYTES / 1024 / 1024} MB file limit.`;
5235
- /** An attachment whose bytes cannot be read. The message is safe to show. */
5236
- var AttachmentDownloadError = class extends Error {
5237
- constructor(message, options) {
5238
- super(message, options);
5239
- this.name = "AttachmentDownloadError";
5240
- }
5241
- };
5242
- /**
5243
- * Find where the bytes of one attachment row are, without reading them.
5244
- *
5245
- * A stored file reads from storage. A large Slack file is never stored, so
5246
- * each `open` downloads it from its source. The source reports the current
5247
- * size, and the size check runs before any download. Errors that the person
5248
- * should see are `AttachmentDownloadError`, from here or from `open`.
5249
- *
5250
- * The row must come from a lookup scoped to the caller's conversation. The
5251
- * source id comes from that row only, never from a request.
5252
- */
5253
- async function readAttachmentContent(args) {
5254
- const { attachment, storage } = args;
5255
- const { storageKey } = attachment;
5256
- if (storageKey !== null) return {
5257
- bytes: attachment.bytes,
5258
- open: async () => {
5259
- const body = await storage.get(storageKey);
5260
- if (!body) throw new AttachmentDownloadError("Stored attachment contents are unavailable.");
5261
- return body;
5262
- }
5263
- };
5264
- const { source } = attachment;
5265
- if (!source || !args.readAttachmentSource) throw new AttachmentDownloadError("Attachment cannot be downloaded from this conversation.");
5266
- const unavailable = (error) => error instanceof AttachmentSourceUnavailableError ? new AttachmentDownloadError(`${attachment.filename} is no longer available: ${error.message}`, { cause: error }) : error;
5267
- let file;
5268
- try {
5269
- file = await args.readAttachmentSource(source);
5270
- } catch (error) {
5271
- throw unavailable(error);
5272
- }
5273
- if (file.bytes > 262144e3) throw new AttachmentDownloadError(ATTACHMENT_TOO_LARGE_MESSAGE);
5274
- return {
5275
- bytes: file.bytes,
5276
- open: async () => {
5277
- try {
5278
- return await file.open();
5279
- } catch (error) {
5280
- throw unavailable(error);
5281
- }
5282
- }
5283
- };
5284
- }
5285
- // src/chat/tools/load-attachment.ts
5286
- const ATTACHMENT_DIR = ".junior/attachments";
5287
- /** Bytes held in memory and sent to the sandbox in one write. */
5288
- const PART_BYTES = 8388608;
5289
- const JOIN_PARTS_SCRIPT = "set -eu; out=$1; shift; cat -- \"$@\" > \"$out\"";
5290
- /** Turn a read failure that the model can relay into a tool error. */
5291
- function toolError(error) {
5292
- return error instanceof AttachmentDownloadError ? new ToolInputError(error.message, { cause: error }) : error;
5293
- }
5294
- /** Run one sandbox command, and return its stdout. Throw when it fails. */
5295
- async function runChecked(workspace, action, input) {
5296
- const result = await workspace.runCommand(input);
5297
- if (result.exitCode !== 0) throw new Error(`Failed to ${action}: ${result.stderr}`);
5298
- return result.stdout;
5299
- }
5300
- /**
5301
- * Write an attachment body to the sandbox in parts of at most `PART_BYTES`.
5302
- *
5303
- * The sandbox SDK writes only whole buffers, so this keeps one part in
5304
- * memory, not the file. Returns the part paths in order.
5305
- */
5306
- async function writeParts(args) {
5307
- const parts = [];
5308
- let pending = [];
5309
- let pendingBytes = 0;
5310
- let total = 0;
5311
- const flush = async () => {
5312
- const partPath = path.posix.join(args.partsDir, String(parts.length).padStart(4, "0"));
5313
- await args.workspace.writeFiles([{
5314
- content: Buffer.concat(pending),
5315
- path: partPath
5316
- }]);
5317
- parts.push(partPath);
5318
- pending = [];
5319
- pendingBytes = 0;
5320
- };
5321
- const reader = args.body.getReader();
5322
- try {
5323
- for (;;) {
5324
- const { done, value } = await reader.read();
5325
- if (done) break;
5326
- total += value.byteLength;
5327
- if (total > args.expectedBytes) break;
5328
- let chunk = value;
5329
- while (pendingBytes + chunk.byteLength >= PART_BYTES) {
5330
- const take = PART_BYTES - pendingBytes;
5331
- pending.push(chunk.subarray(0, take));
5332
- pendingBytes += take;
5333
- await flush();
5334
- chunk = chunk.subarray(take);
5335
- }
5336
- if (chunk.byteLength > 0) {
5337
- pending.push(chunk);
5338
- pendingBytes += chunk.byteLength;
5339
- }
5340
- }
5341
- } finally {
5342
- await reader.cancel().catch(() => void 0);
5343
- }
5344
- if (total !== args.expectedBytes) throw new Error(`Attachment ${args.attachmentId} read ${total} bytes, expected ${args.expectedBytes}.`);
5345
- if (pendingBytes > 0 || parts.length === 0) await flush();
5346
- return parts;
5347
- }
5348
- /**
5349
- * Create a tool that restores one conversation attachment to the sandbox.
5350
- *
5351
- * A large Slack file is never stored: each load streams it from Slack
5352
- * through the host. The sandbox never gets a Slack URL or token.
5353
- *
5354
- * @runBuilt loadAttachment
5355
- */
5356
- function createLoadAttachmentTool(args) {
5357
- return zodTool({
5358
- description: "Load a stored attachment for this conversation into the sandbox.",
5359
- annotations: {
5360
- destructiveHint: false,
5361
- idempotentHint: true,
5362
- openWorldHint: true,
5363
- readOnlyHint: false
5364
- },
5365
- inputSchema: z.object({ attachment_id: z.string().min(1).describe("Stored attachment ID, as shown in attachment context or Slack read results.") }),
5366
- outputSchema: juniorToolOutputSchema,
5367
- execute: async ({ attachment_id }) => {
5368
- const attachment = await readLiveAttachment({
5369
- attachmentId: attachment_id,
5370
- conversationId: args.conversationId,
5371
- db: args.db
5372
- });
5373
- if (!attachment || attachment.storageProvider !== args.storage.provider) throw new ToolInputError("Attachment not found in this conversation.");
5374
- if (attachment.bytes > 262144e3) throw new ToolInputError(ATTACHMENT_TOO_LARGE_MESSAGE);
5375
- let content;
5376
- try {
5377
- content = await readAttachmentContent({
5378
- attachment,
5379
- readAttachmentSource: args.readAttachmentSource,
5380
- storage: args.storage
5381
- });
5382
- } catch (error) {
5383
- throw toolError(error);
5384
- }
5385
- const attachmentDir = path.posix.join(ATTACHMENT_DIR, attachment.id);
5386
- const partsDir = `${attachmentDir}.parts`;
5387
- const sandboxPath = path.posix.join(attachmentDir, path.posix.basename(attachment.filename));
5388
- await runChecked(args.workspace, "create attachment directory", {
5389
- cmd: "mkdir",
5390
- args: [
5391
- "-p",
5392
- "--",
5393
- attachmentDir,
5394
- partsDir
5395
- ]
5396
- });
5397
- const joinedPath = path.posix.join(partsDir, "joined");
5398
- try {
5399
- const parts = await writeParts({
5400
- attachmentId: attachment.id,
5401
- body: await content.open(),
5402
- expectedBytes: content.bytes,
5403
- partsDir,
5404
- workspace: args.workspace
5405
- });
5406
- await runChecked(args.workspace, "join attachment parts", {
5407
- cmd: "sh",
5408
- args: [
5409
- "-c",
5410
- JOIN_PARTS_SCRIPT,
5411
- "sh",
5412
- joinedPath,
5413
- ...parts
5414
- ]
5415
- });
5416
- const size = await runChecked(args.workspace, "read attachment size", {
5417
- cmd: "stat",
5418
- args: [
5419
- "-c",
5420
- "%s",
5421
- "--",
5422
- joinedPath
5423
- ]
5424
- });
5425
- const written = Number(size.trim());
5426
- if (written !== content.bytes) throw new Error(`Attachment ${attachment.id} wrote ${written} bytes to the sandbox, expected ${content.bytes}.`);
5427
- await runChecked(args.workspace, "move attachment into place", {
5428
- cmd: "mv",
5429
- args: [
5430
- "-f",
5431
- "--",
5432
- joinedPath,
5433
- sandboxPath
5434
- ]
5435
- });
5436
- } catch (error) {
5437
- await args.workspace.runCommand({
5438
- cmd: "rm",
5439
- args: [
5440
- "-rf",
5441
- "--",
5442
- partsDir
5443
- ]
5444
- }).catch(() => void 0);
5445
- throw toolError(error);
5446
- }
5447
- await runChecked(args.workspace, "remove attachment parts", {
5448
- cmd: "rm",
5449
- args: [
5450
- "-rf",
5451
- "--",
5452
- partsDir
5453
- ]
5454
- });
5455
- return {
5456
- path: sandboxPath,
5457
- filename: attachment.filename,
5458
- mime_type: attachment.contentType,
5459
- bytes: content.bytes
5460
- };
5461
- }
5462
- });
5463
- }
5464
5624
  // src/chat/tools/index.ts
5465
5625
  function createToolState() {
5466
5626
  const operationResultCache = /* @__PURE__ */ new Map();
@@ -5488,11 +5648,12 @@ const STATIC_TOOL_BINDERS = {
5488
5648
  updatePlan: () => createUpdatePlanTool(),
5489
5649
  reportProgress: () => createReportProgressTool(),
5490
5650
  systemTime: () => createSystemTimeTool(),
5651
+ submitFeedback: (run) => createSubmitFeedbackTool(run.context),
5491
5652
  bash: () => createBashTool(),
5492
5653
  readFile: () => createReadFileTool(),
5493
5654
  editFile: () => createEditFileTool(),
5494
5655
  writeFile: () => createWriteFileTool(),
5495
- webSearch: (run) => createWebSearchTool(botConfig.webSearchModelId, run.hooks.toolOverrides?.webSearch),
5656
+ webSearch: (run) => createWebSearchTool(botConfig.webSearchModelId, run.modelCost, run.hooks.toolOverrides?.webSearch),
5496
5657
  webFetch: (run) => createWebFetchTool(run.hooks, { canSendFilesToActiveConversation: run.canSendFilesToActiveConversation }),
5497
5658
  watchTimer: (run) => createWatchTimerTool(run.context),
5498
5659
  searchEventTypes: (run) => createSearchEventTypesTool(run.catalog),
@@ -5589,7 +5750,7 @@ const RUN_BUILT_TOOL_BUILDERS = {
5589
5750
  imageGenerate: (run) => run.hooks.writeGeneratedArtifacts ? createImageGenerateTool({ writeGeneratedArtifacts: run.hooks.writeGeneratedArtifacts }, {
5590
5751
  modelId: botConfig.imageGenerationModelId,
5591
5752
  canSendFilesToActiveConversation: run.canSendFilesToActiveConversation,
5592
- promptCost: run.modelCost,
5753
+ modelCost: run.modelCost,
5593
5754
  sandbox: run.context.workspace
5594
5755
  }, run.hooks.toolOverrides?.imageGenerate) : void 0,
5595
5756
  localSendFiles: (run) => {
@@ -5616,6 +5777,22 @@ const RUN_BUILT_TOOL_BUILDERS = {
5616
5777
  conversationId: run.context.conversationId,
5617
5778
  db: getSqlExecutor()
5618
5779
  }) : void 0,
5780
+ transcribeAudio: (run) => {
5781
+ const storage = run.context.attachmentStorage;
5782
+ const createDownloadUrl = storage?.createDownloadUrl?.bind(storage);
5783
+ return storage && createDownloadUrl ? createTranscribeAudioTool({
5784
+ conversationId: run.context.conversationId,
5785
+ db: getSqlExecutor(),
5786
+ modelCost: run.modelCost,
5787
+ modelId: botConfig.transcriptionModelId,
5788
+ ...run.slack ? { readAttachmentSource: readSlackAttachmentSource } : void 0,
5789
+ storage: {
5790
+ ...storage,
5791
+ createDownloadUrl
5792
+ },
5793
+ workspace: run.context.workspace
5794
+ }) : void 0;
5795
+ },
5619
5796
  searchMcpTools: (run) => run.context.mcpToolManager ? createSearchMcpToolsTool(run.context.mcpToolManager) : void 0,
5620
5797
  callMcpTool: (run) => run.context.mcpToolManager ? createCallMcpToolTool(run.context.mcpToolManager) : void 0,
5621
5798
  slackCanvasCreate: (run) => {
@@ -7417,8 +7594,8 @@ function renderDeclaration(name, tool) {
7417
7594
  }).trim().replace(/\n/g, "\n ")}`;
7418
7595
  }
7419
7596
  /**
7420
- * Tell the script which tools it may call, for the `<script-tools>` Turn
7421
- * context section. Direct tools are only named: the model already has their
7597
+ * Tell the script which tools it may call, for the `<script-tools>` system
7598
+ * prompt section. Direct tools are only named: the model already has their
7422
7599
  * input schemas. The other tools are declared within the token budget,
7423
7600
  * cheapest first, so that the most tools fit. The others stay callable. The
7424
7601
  * model finds their input with `searchTools`. Script-only tools come first,
@@ -7466,7 +7643,7 @@ const DESCRIPTION = [
7466
7643
  `- The script has ${CODE_MODE_SCRIPT_TIMEOUT_MS / 1e3} seconds, including its tool calls.`,
7467
7644
  `- Start at most 10 calls before the script awaits. A larger batch fails, and none of its calls run.`,
7468
7645
  "- The result lists each tool call and its status. When action review rejects a call, do what its instructions say, such as ask the user, before you try it again.",
7469
- "- `<script-tools>` in the runtime context lists the tools that a script can call. Only the latest `<script-tools>` is current."
7646
+ "- `<script-tools>` in the system prompt lists the tools that a script can call."
7470
7647
  ].join("\n");
7471
7648
  function renderCall(call, index) {
7472
7649
  return [`${index + 1}. ${call.toolName}: ${CODE_MODE_CALL_STATUS_TEXT[call.status]}`, ...[...call.error ? [call.error] : [], ...(call.nudges ?? []).map(renderToolResultNudge)].map((note) => ` ${note.replace(/\n/g, "\n ")}`)].join("\n");
@@ -8026,7 +8203,7 @@ function createJwtBearerMcpClientProvider(subject, mcpUrl, auth) {
8026
8203
  /** The client metadata that Junior registers for one MCP OAuth callback. */
8027
8204
  function createClientMetadata(callbackUrl) {
8028
8205
  return {
8029
- client_name: "Junior MCP Client",
8206
+ client_name: `${botConfig.userName} MCP Client`,
8030
8207
  redirect_uris: [callbackUrl],
8031
8208
  grant_types: ["authorization_code", "refresh_token"],
8032
8209
  response_types: ["code"],
@@ -9685,13 +9862,13 @@ var ContextSummaryError = class extends Error {
9685
9862
  * so it fails when Pi changes these steps.
9686
9863
  */
9687
9864
  async function buildAgentModelRequest(agent, messages, signal) {
9688
- const { model, systemPrompt, thinkingLevel, tools } = agent.state;
9865
+ const { model, thinkingLevel, tools } = agent.state;
9866
+ const leading = getInitialSystemMessage(agent.state.messages);
9689
9867
  const transformed = agent.transformContext ? await agent.transformContext(messages, signal) : messages;
9690
9868
  return {
9691
9869
  model,
9692
9870
  context: {
9693
- systemPrompt,
9694
- messages: await agent.convertToLlm(transformed),
9871
+ ...foldLeadingSystemMessages(leading ? getSystemMessageText$1(leading) : "", await agent.convertToLlm(transformed)),
9695
9872
  tools
9696
9873
  },
9697
9874
  options: {
@@ -10250,39 +10427,18 @@ function withoutRequestContext(text) {
10250
10427
  return withoutSections(text, Object.values(REQUEST_CONTEXT_SECTION_TAG));
10251
10428
  }
10252
10429
  /**
10253
- * Turn context sections that a Turn sends only when they differ from the
10254
- * latest copy in history. Compaction keeps exactly that copy, byte for byte.
10430
+ * Remove the copies of capability sections that the Turn context of older
10431
+ * Turns held. Later system messages hold them now, and compaction folds
10432
+ * those.
10255
10433
  */
10256
- const LATEST_COPY_SECTION_TAGS = [...Object.values(CAPABILITY_SECTION_TAG), SCRIPT_TOOLS_SECTION_TAG];
10257
- function latestSections(messages, tags = LATEST_COPY_SECTION_TAGS) {
10258
- return tags.flatMap((tag) => latestTurnContextSection(messages, tag) ?? []);
10259
- }
10260
- /**
10261
- * Remove every copy of the latest-copy sections, then put the given copies in
10262
- * the first Turn context part. Callers leave out a section that kept history
10263
- * already has.
10264
- */
10265
- function withLatestSections(content, sections) {
10266
- const closingTag = `\n</${TURN_CONTEXT_TAG}>`;
10267
- const added = sections.map((section) => `\n\n${section}`).join("");
10268
- let pending = sections.length > 0;
10269
- const result = content.map((part) => {
10434
+ function withoutCapabilitySections(content) {
10435
+ return content.map((part) => {
10270
10436
  const text = textPart(part);
10271
- if (!text?.startsWith(`<runtime-turn-context>`)) return part;
10272
- let stripped = withoutSections(text, LATEST_COPY_SECTION_TAGS);
10273
- if (pending && stripped.endsWith(closingTag)) {
10274
- stripped = `${stripped.slice(0, -closingTag.length)}${added}${closingTag}`;
10275
- pending = false;
10276
- }
10277
- return {
10437
+ return text?.startsWith(`<runtime-turn-context>`) ? {
10278
10438
  ...part,
10279
- text: stripped
10280
- };
10439
+ text: withoutSections(text, Object.values(CAPABILITY_SECTION_TAG))
10440
+ } : part;
10281
10441
  });
10282
- return pending ? [{
10283
- type: "text",
10284
- text: `<${TURN_CONTEXT_TAG}>${added}${closingTag}`
10285
- }, ...result] : result;
10286
10442
  }
10287
10443
  /** Find the latest session context and keep only its session sections. */
10288
10444
  function latestSessionContext(messages) {
@@ -10305,12 +10461,12 @@ function effectiveRuntimeContext(messages) {
10305
10461
  break;
10306
10462
  }
10307
10463
  const effectiveMessages = latestBootstrapIndex < 0 ? messages : messages.slice(latestBootstrapIndex);
10308
- return runtimeContextContent(effectiveMessages, effectiveMessages, latestSections(messages));
10464
+ return runtimeContextContent(effectiveMessages, effectiveMessages);
10309
10465
  }
10310
- function runtimeContextContent(messages, agentsMessages, latest) {
10466
+ function runtimeContextContent(messages, agentsMessages) {
10311
10467
  const allContent = messages.flatMap(userMessageContent);
10312
10468
  const firstAgentsIndex = allContent.findIndex((part) => textPart(part)?.startsWith("# AGENTS.md instructions") === true);
10313
- const content = withLatestSections(allContent.filter((part) => textPart(part)?.startsWith("# AGENTS.md instructions") !== true), latest);
10469
+ const content = withoutCapabilitySections(allContent.filter((part) => textPart(part)?.startsWith("# AGENTS.md instructions") !== true));
10314
10470
  const visibleAgents = findVisibleAgentsInstructions(agentsMessages);
10315
10471
  if (visibleAgents?.active === true) {
10316
10472
  const insertionIndex = firstAgentsIndex < 0 ? content.length : Math.min(firstAgentsIndex, content.length);
@@ -10345,27 +10501,24 @@ function runtimeContextMessage(messages, timestamp) {
10345
10501
  *
10346
10502
  * Request context, such as plugin context and disabled tools, is true only for
10347
10503
  * the Turn that received it. From earlier Turns, keep only the latest session
10348
- * context, the latest copy of each capability section and `<script-tools>`,
10349
- * and AGENTS.md instructions.
10504
+ * context and AGENTS.md instructions.
10350
10505
  */
10351
10506
  function turnRuntimeContextMessage(messages, turnStartMessageIndex, timestamp) {
10352
10507
  if (turnStartMessageIndex === void 0) return runtimeContextMessage(retainRuntimeTurnContext(messages), timestamp);
10353
10508
  const earlierContext = retainRuntimeTurnContext(messages.slice(0, turnStartMessageIndex));
10354
10509
  const turnContext = retainRuntimeTurnContext(messages.slice(turnStartMessageIndex));
10355
10510
  const sessionContext = turnContext.some((message) => userMessageContent(message).map(textPart).some(isSessionTurnContext)) ? void 0 : latestSessionContext(earlierContext);
10356
- return toRuntimeContextMessage(runtimeContextContent(sessionContext ? [sessionContext, ...turnContext] : turnContext, [...earlierContext, ...turnContext], latestSections([...earlierContext, ...turnContext])), timestamp);
10511
+ return toRuntimeContextMessage(runtimeContextContent(sessionContext ? [sessionContext, ...turnContext] : turnContext, [...earlierContext, ...turnContext]), timestamp);
10357
10512
  }
10358
10513
  /**
10359
10514
  * Build the runtime context of summarized history that the kept history
10360
- * does not carry: the latest session context, the latest copy of each
10361
- * capability section and `<script-tools>`, and the AGENTS.md instructions.
10515
+ * does not carry: the latest session context and the AGENTS.md instructions.
10362
10516
  * Request context of earlier Turns is left out.
10363
10517
  */
10364
10518
  function summarizedRuntimeContextMessage(summarized, kept) {
10365
10519
  const earlierContext = retainRuntimeTurnContext(summarized);
10366
- const keptContext = retainRuntimeTurnContext(kept);
10367
- const sessionContext = keptContext.some((message) => userMessageContent(message).map(textPart).some(isSessionTurnContext)) ? void 0 : latestSessionContext(earlierContext);
10368
- return toRuntimeContextMessage(runtimeContextContent(sessionContext ? [sessionContext] : [], findVisibleAgentsInstructions(kept) ? [] : earlierContext, latestSections(earlierContext, LATEST_COPY_SECTION_TAGS.filter((tag) => !latestTurnContextSection(keptContext, tag)))));
10520
+ const sessionContext = retainRuntimeTurnContext(kept).some((message) => userMessageContent(message).map(textPart).some(isSessionTurnContext)) ? void 0 : latestSessionContext(earlierContext);
10521
+ return toRuntimeContextMessage(runtimeContextContent(sessionContext ? [sessionContext] : [], findVisibleAgentsInstructions(kept) ? [] : earlierContext));
10369
10522
  }
10370
10523
  /**
10371
10524
  * Build retained user messages for a compacted Pi replacement history. Each
@@ -10423,13 +10576,19 @@ async function loadRetainedUserMessages(conversationId, pendingMessages) {
10423
10576
  };
10424
10577
  });
10425
10578
  }
10426
- /** Keep generated text inside the existing evidence-only prompt boundary. */
10579
+ const COMPACTION_READ_BACK_NOTE = "The summary replaced earlier messages and tool results. When you need an exact detail that the summary lacks, read the full text with the searchConversationEvents and readConversationEvent tools.";
10580
+ /**
10581
+ * Keep generated text inside the existing evidence-only prompt boundary. The
10582
+ * last line says where replaced detail stays readable: without it, the model
10583
+ * often decides an exact value from a compacted tool result is gone.
10584
+ */
10427
10585
  function renderCompactionSummary(summary) {
10428
10586
  return [
10429
10587
  COMPACTION_SUMMARY_PREFIX,
10430
10588
  "<thread-context authority=\"evidence-only\">",
10431
10589
  escapeXml(summary),
10432
- "</thread-context>"
10590
+ "</thread-context>",
10591
+ COMPACTION_READ_BACK_NOTE
10433
10592
  ].join("\n");
10434
10593
  }
10435
10594
  function timestampOf(message) {
@@ -10500,7 +10659,8 @@ function measuredReplacementTokens(messages) {
10500
10659
  for (const message of messages.slice(summaryIndex + 1)) {
10501
10660
  const timestamp = timestampOf(message);
10502
10661
  if (timestamp === void 0 || timestamp <= summaryAt) {
10503
- if (message.role !== "user") return void 0;
10662
+ const role = message.role;
10663
+ if (role !== "user" && role !== "system") return void 0;
10504
10664
  continue;
10505
10665
  }
10506
10666
  const tokens = measuredInputTokens(message);
@@ -10589,10 +10749,16 @@ async function compactActiveAboveThreshold(args, summarize, source, triggerToken
10589
10749
  ...index === 0 && retainedInstruction ? { sourceEventSeq: retainedInstruction.sourceEventSeq } : void 0
10590
10750
  }));
10591
10751
  const retainedUserMessages = retainUserMessages ? await loadRetainedUserMessages(args.conversationId, instructionMessages) : [];
10752
+ const systemMessage = foldSystemMessages(args.piMessages);
10753
+ const systemEntries = systemMessage ? [{
10754
+ message: systemMessage,
10755
+ provenance: contextProvenance
10756
+ }] : [];
10592
10757
  const keptTokens = estimateReplacementTokens([
10593
10758
  ...retainedUserMessages,
10594
10759
  ...contextEntries,
10595
- ...instructionEntries
10760
+ ...instructionEntries,
10761
+ ...systemEntries
10596
10762
  ].map((entry) => entry.message), args.modelId, args.requestOverheadTokens);
10597
10763
  if (belowInputLimit && keptTokens > calculateContextCompactionTargetTokens(triggerTokens)) return skip("over_target");
10598
10764
  if (keptTokens >= inputLimitTokens) return skip("over_input_limit");
@@ -10621,12 +10787,14 @@ async function compactActiveAboveThreshold(args, summarize, source, triggerToken
10621
10787
  const replacement = retainUserMessages ? [
10622
10788
  ...retainedUserMessages,
10623
10789
  summaryEntry,
10790
+ ...systemEntries,
10624
10791
  ...contextEntries,
10625
10792
  ...instructionEntries
10626
10793
  ] : [
10627
10794
  ...contextEntries,
10628
10795
  ...instructionEntries,
10629
- summaryEntry
10796
+ summaryEntry,
10797
+ ...systemEntries
10630
10798
  ];
10631
10799
  const retainedMessageCount = retainedUserMessages.length + instructionMessages.length;
10632
10800
  const messages = replacement.map((entry) => entry.message);
@@ -10902,6 +11070,7 @@ async function applyPreparedSummary(args, prepared, budget) {
10902
11070
  provenance: contextProvenance
10903
11071
  };
10904
11072
  }));
11073
+ const systemMessage = foldSystemMessages(summarized);
10905
11074
  const replacement = [
10906
11075
  ...contextMessage ? [{
10907
11076
  message: contextMessage,
@@ -10912,6 +11081,10 @@ async function applyPreparedSummary(args, prepared, budget) {
10912
11081
  message: userMessage(appendOpenPlan(renderCompactionSummary(prepared.summary), summarized)),
10913
11082
  provenance: contextProvenance
10914
11083
  },
11084
+ ...systemMessage ? [{
11085
+ message: systemMessage,
11086
+ provenance: contextProvenance
11087
+ }] : [],
10915
11088
  ...trimmedEntries,
10916
11089
  ...pendingMessages
10917
11090
  ];
@@ -11394,7 +11567,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
11394
11567
  };
11395
11568
  if (initialRepositoryInstructions) await recordAgentsTransition(initialRepositoryInstructions);
11396
11569
  const getPendingAuthPause = wiring.getPendingAuthPause;
11397
- const { baseInstructions: assembledBaseInstructions, contextContentParts: promptContextContentParts, inputMessages, inputMessagesAttribute, platform: promptPlatform, promptTimestamp: restoredPromptTimestamp, promptHistoryMessages, shouldPromptAgent, turnContexts, userContentParts: promptUserContentParts } = await assemblePrompt({
11570
+ const { baseInstructions: assembledBaseInstructions, contextContentParts: promptContextContentParts, inputMessages, inputMessagesAttribute, platform: promptPlatform, promptTimestamp: restoredPromptTimestamp, promptHistoryMessages, sectionsMessage, shouldPromptAgent, turnContexts, userContentParts: promptUserContentParts } = await assemblePrompt({
11398
11571
  activeMcpCatalogs: wiring.activeMcpCatalogs,
11399
11572
  promptMode: behavior.promptMode,
11400
11573
  currentActor: actor,
@@ -11452,7 +11625,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
11452
11625
  pendingMessages,
11453
11626
  mode,
11454
11627
  piMessages: messages,
11455
- requestOverheadTokens: estimateRequestOverheadTokens(agent.state.systemPrompt, agent.state.tools, activeModelId),
11628
+ requestOverheadTokens: estimateRequestOverheadTokens(baseInstructions, agent.state.tools, activeModelId),
11456
11629
  ...pairPendingRuntimeContext && pendingMessages ? { runtimeContextMessages: [...messages, ...pendingMessages.map((entry) => entry.message)] } : void 0,
11457
11630
  signal: hookSignal,
11458
11631
  turnStartMessageIndex: runResume.turnStartMessageIndex
@@ -11684,6 +11857,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
11684
11857
  runResume.setTurnStartMessageIndex(existingSessionRecord.turnStartMessageIndex);
11685
11858
  runResume.adoptCommittedBoundary(currentAgentMessages());
11686
11859
  } else if (promptHistoryMessages.length > 0) setAgentHistory(promptHistoryMessages);
11860
+ if (sectionsMessage) setAgentHistory([...currentAgentMessages(), sectionsMessage]);
11687
11861
  runResume.setBeforeMessageCount(currentAgentMessages().length);
11688
11862
  if (shouldPromptAgent) runResume.setTurnStartMessageIndex(currentAgentMessages().length);
11689
11863
  const authPauseOutcome = await withSpan(`invoke_agent ${botConfig.userName}`, "gen_ai.invoke_agent", spanContext, async (setInvokeAgentSpanAttributes) => {
@@ -12022,7 +12196,7 @@ function createAgentRunner(execute, options) {
12022
12196
  }
12023
12197
  };
12024
12198
  const loadStoredAttachments = async (attachments) => {
12025
- const { loadInputAttachments } = await import("./model-input-DmoPPtPE.js").then((n) => n.r);
12199
+ const { loadInputAttachments } = await import("./model-input-BHXfA29g.js").then((n) => n.r);
12026
12200
  const storage = nextRun.environment?.attachmentStorage;
12027
12201
  if (!storage) throw new Error("Attachment storage is unavailable.");
12028
12202
  return await loadInputAttachments({
@@ -12046,4 +12220,4 @@ function createAgentRunner(execute, options) {
12046
12220
  return await execute(nextRun, streamFn);
12047
12221
  } };
12048
12222
  }
12049
- export { actorFromRun as A, SLACK_REVIEW_ITEM_VIEW_ID as C, parseSlackUserInputSubmission as D, parseSlackReviewItemFormTarget as E, shouldEmitDevAgentTrace as M, previewOriginBelongsTo as O, findSlackThreadOwnerId as S, parseSlackReviewItemClick as T, logScheduledAutomationRunSkipped as _, buildAuthPauseResponse as a, resolveSlackReviewItemCardConversationId as b, createClientMetadata as c, AttachmentDownloadError as d, readAttachmentContent as f, resolveDestinationVisibility as g, unpublishedArtifactHeaders as h, measureTurnCompactionWait as i, toolInvocationDestination as j, RetryableDeliveryError as k, readMcpClientInformation as l, readPublicArtifact as m, executeAgentRun as n, finalizeMcpAuthorization as o, publicArtifactHeaders as p, processBackgroundCompaction as r, getMcpOAuthCallbackPath as s, createAgentRunner as t, latestProgressStatus as u, scheduledAutomationRunAttributes as v, buildSlackReviewItemModal as w, syncReviewItemSlackCards as x, createSlackReviewItemShow as y };
12223
+ export { RetryableDeliveryError as A, parseSlackReviewItemClick as C, AttachmentDownloadError as D, parseSlackUserInputSubmission as E, toolInvocationDestination as M, shouldEmitDevAgentTrace as N, readAttachmentContent as O, buildSlackReviewItemModal as S, safeLinkUrl as T, createSlackReviewItemShow as _, buildAuthPauseResponse as a, findSlackThreadOwnerId as b, createClientMetadata as c, publicArtifactHeaders as d, readPublicArtifact as f, scheduledAutomationRunAttributes as g, logScheduledAutomationRunSkipped as h, measureTurnCompactionWait as i, actorFromRun as j, previewOriginBelongsTo as k, readMcpClientInformation as l, resolveDestinationVisibility as m, executeAgentRun as n, finalizeMcpAuthorization as o, unpublishedArtifactHeaders as p, processBackgroundCompaction as r, getMcpOAuthCallbackPath as s, createAgentRunner as t, latestProgressStatus as u, resolveSlackReviewItemCardConversationId as v, parseSlackReviewItemFormTarget as w, SLACK_REVIEW_ITEM_VIEW_ID as x, syncReviewItemSlackCards as y };