@sentry/junior 0.256.0 → 0.258.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 (106) hide show
  1. package/dist/{actor-BTtLaeWy.js → actor-tlxzqaRe.js} +3 -6
  2. package/dist/{admin-BhucwVfy.js → admin-My1SLGVO.js} +2 -3
  3. package/dist/{agent-hooks-DlSK8PQQ.js → agent-hooks-BJ_5mlRH.js} +71 -111
  4. package/dist/{agent-invocations-BY60iNw-.js → agent-invocations-Qfz7dWgU.js} +8 -13
  5. package/dist/{agent-runner-C6_cd61V.js → agent-runner-DGsFQw72.js} +278 -467
  6. package/dist/api/schema.d.ts +454 -448
  7. package/dist/api/schema.js +5 -5
  8. package/dist/api.d.ts +2 -12
  9. package/dist/api.js +189 -165
  10. package/dist/{app-B0gT1Slp.d.ts → app-PX2H1PxU.d.ts} +20 -37
  11. package/dist/app.d.ts +3 -3
  12. package/dist/app.js +565 -305
  13. package/dist/{assistant-reply-yn5G-YEG.js → assistant-reply-H1M-91oF.js} +3 -5
  14. package/dist/{automation-CHdlHVZP.js → automation-DWBFBenG.js} +6 -11
  15. package/dist/{briefs-U6Bi3IYw.js → briefs-vYoK85rJ.js} +8 -11
  16. package/dist/{cadence-D00SCzT1.js → cadence-R7Em4RjE.js} +1 -2
  17. package/dist/{catalog-runtime-DF5OWqCc.js → catalog-runtime-BN4DVxco.js} +3 -4
  18. package/dist/cli/chat.d.ts +2 -4
  19. package/dist/cli/chat.js +22 -24
  20. package/dist/cli/check.d.ts +1 -3
  21. package/dist/cli/check.js +4 -5
  22. package/dist/cli/env.d.ts +1 -3
  23. package/dist/cli/env.js +1 -2
  24. package/dist/cli/init.d.ts +1 -3
  25. package/dist/cli/init.js +3 -3
  26. package/dist/cli/main.d.ts +1 -3
  27. package/dist/cli/main.js +4 -5
  28. package/dist/cli/plugins.d.ts +2 -4
  29. package/dist/cli/plugins.js +7 -8
  30. package/dist/cli/run.d.ts +1 -2
  31. package/dist/cli/run.js +1 -2
  32. package/dist/cli/snapshot-create.d.ts +1 -3
  33. package/dist/cli/snapshot-create.js +4 -5
  34. package/dist/cli/upgrade.d.ts +3 -6
  35. package/dist/cli/upgrade.js +11 -17
  36. package/dist/{client-BVrAp-pq.js → client-DbyHuMFU.js} +9 -16
  37. package/dist/{config-DdBiDanf.js → config-_WO_AjCB.js} +18 -15
  38. package/dist/{connections-CG04HdpC.js → connections-ag_1JOhB.js} +21 -21
  39. package/dist/{conversation-T18Xlkx9.js → conversation-DjN3mlog.js} +11 -17
  40. package/dist/{conversation-privacy-CpSYOWnP.js → conversation-privacy-DHP_xnVj.js} +2 -3
  41. package/dist/{conversation-work-C6y3T5Hx.js → conversation-work-BaT_T6EB.js} +1 -2
  42. package/dist/{credential-sync-DKWNdcgm.js → credential-sync-B-CPX_ag.js} +89 -52
  43. package/dist/{db-Ca9Nt5ci.d.ts → db-BnRqQ7G5.d.ts} +1 -1
  44. package/dist/{executor-BroK9oKy.js → executor-RvG6kVe1.js} +58 -70
  45. package/dist/{experimental-Qn9rKLgx.js → experimental-BNK1l1jv.js} +2 -3
  46. package/dist/{history-9pO1Zd4Y.js → history-AY8rs-FR.js} +5 -9
  47. package/dist/{history-DvqWZlYX.d.ts → history-BgI33Kie.d.ts} +12 -20
  48. package/dist/{images-D0VZ5nv0.js → images-C2J_bj2g.js} +5 -6
  49. package/dist/instrumentation.d.ts +1 -3
  50. package/dist/instrumentation.js +6 -8
  51. package/dist/{job-queue-BbGg3gvu.js → job-queue-DVe37it2.js} +6 -12
  52. package/dist/{logging-tPQeUe2i.js → logging-DsHONhVm.js} +54 -24
  53. package/dist/{message-DdPGRYQP.js → message-DyitL8no.js} +5 -6
  54. package/dist/{model-profile-BwU8mqwD.js → model-profile-Bg8EoCKD.js} +2 -4
  55. package/dist/nitro.d.ts +3 -5
  56. package/dist/nitro.js +12 -17
  57. package/dist/{oauth-authorization-BA4Dt6a7.js → oauth-authorization-djQn5Nhy.js} +2 -4
  58. package/dist/{oauth-callback-server-B-2errCX.js → oauth-callback-server-CDby-pCn.js} +3 -4
  59. package/dist/{oauth-relay-CdCnu80W.js → oauth-relay-CTygMkNx.js} +2 -3
  60. package/dist/{package-discovery-BVvSnQBB.js → package-discovery-DJBompdd.js} +17 -21
  61. package/dist/{pending-auth-DT3MRVW8.js → pending-auth-D8J1uJUS.js} +37 -28
  62. package/dist/{plugin-module-CVvEUSMH.js → plugin-module-Cf5gVPWP.js} +1 -2
  63. package/dist/{plugins-CjfUP5gJ.d.ts → plugins-B11Mfkmv.d.ts} +0 -4
  64. package/dist/{plugins-egKWjgue.js → plugins-DOm9Y6qI.js} +2 -3
  65. package/dist/{private-trace-result-BLvBjy_e.js → private-trace-result-CE7_lEdq.js} +1 -2
  66. package/dist/{profile-Bb1zCVGP.js → profile-DpYjfKke.js} +16 -28
  67. package/dist/{prompt-C04mP1hu.js → prompt-xgpyMtg7.js} +5 -9
  68. package/dist/{queue-B5SnqRln.d.ts → queue-C37RbDVc.d.ts} +0 -2
  69. package/dist/{registry-CsNavQ_Z.js → registry-Du566MtJ.js} +57 -30
  70. package/dist/{resolve-B6ZZ9duG.js → resolve-ClCIgh8E.js} +7 -12
  71. package/dist/{result-j9nS0se-.js → result-BBbKA61B.js} +13 -17
  72. package/dist/{rolldown-runtime-B4FMCO8f.js → rolldown-runtime-nwUcYXjP.js} +1 -2
  73. package/dist/{runner-Y331DoZ5.js → runner-CCuqFSqx.js} +12 -13
  74. package/dist/{sandbox-egress-signals-BUfjEdHY.js → sandbox-egress-signals-DY1mbKF4.js} +2 -3
  75. package/dist/{schema-BBgv0MNf.js → schema-DrMh3NtR.js} +17 -27
  76. package/dist/{sentry-CgWZM_kV.js → sentry-BBUlHih9.js} +2 -3
  77. package/dist/{session-stop-q-6GNHx6.js → session-stop-CIoFiwwe.js} +57 -41
  78. package/dist/{skills-CyvTsR9M.js → skills-DyQBLIrK.js} +9 -9
  79. package/dist/{spawn-Do5mX3d_.js → spawn-Dqfeo7XP.js} +4 -5
  80. package/dist/{store-DoewL5mG.d.ts → store-CG0VJyye.d.ts} +0 -14
  81. package/dist/{store-D2It0ozF.js → store-DJLwq4x8.js} +13 -15
  82. package/dist/{task-queue-ZMk9bLRT.js → task-queue-BzW4MaWU.js} +5 -7
  83. package/dist/{task-runner-cIGU5VwJ.js → task-runner-D3qJh4fK.js} +22 -26
  84. package/dist/{tasks-CODtRzvX.js → tasks-CEXKTASS.js} +78 -79
  85. package/dist/{thread-state-BPkwVmvK.js → thread-state-W3f6kAtz.js} +13 -19
  86. package/dist/{turn-failure-response-ChmMeKar.js → turn-failure-response-CWx7aNIh.js} +16 -22
  87. package/dist/{turn-lifecycle-BUP7ZOVa.js → turn-lifecycle-C9JFst7-.js} +2 -3
  88. package/dist/{turn-session-routing-BcWM3PLm.js → turn-session-routing-CUxtfpr7.js} +2 -3
  89. package/dist/{validation-DCd69-cP.js → validation-BHRxa5G4.js} +3 -4
  90. package/dist/vercel.d.ts +1 -3
  91. package/dist/vercel.js +1 -2
  92. package/dist/{version-DBc4Qt_P.js → version-C0U6rHg0.js} +3 -5
  93. package/dist/{version-CnXZ614E.d.ts → version-Cc2OFd9G.d.ts} +0 -2
  94. package/dist/version.d.ts +1 -1
  95. package/dist/version.js +1 -2
  96. package/dist/{viewer-C-9nFKYr.js → viewer-CGvvRqKp.js} +61 -44
  97. package/dist/{web-input-Cv42P3ni.js → web-input-Keb5GRWj.js} +139 -198
  98. package/dist/{web-message-id-xPI_EFSC.js → web-message-id-CJSUiksE.js} +3 -6
  99. package/dist/{work-6UmVQq1V.js → work-DRcsJ3hV.js} +14 -16
  100. package/dist/{worker-DAoBZuZn.js → worker-Cjo-QqPq.js} +7 -8
  101. package/migrations/0059_automation_run_version.sql +2 -0
  102. package/migrations/0060_identity_signed_in_at.sql +1 -0
  103. package/migrations/meta/0059_snapshot.json +3619 -0
  104. package/migrations/meta/0060_snapshot.json +3465 -0
  105. package/migrations/meta/_journal.json +15 -1
  106. package/package.json +8 -6
@@ -1,33 +1,33 @@
1
- import { b as getGatewayApiKey, c as hasCompactedConversationContext, d as unwrapCurrentInstruction, f as escapeXml, g as getProviderErrorAttributes, h as findProviderError, i as completeText, l as isCompactionSummaryText, m as createProviderError, n as GEN_AI_SERVER_ADDRESS, o as resolveGatewayModel, p as ProviderError, r as completeObject, s as COMPACTION_SUMMARY_PREFIX, t as GEN_AI_PROVIDER_NAME, u as renderCurrentInstruction, v as isProviderRetryError, x as resolveGatewayCredential, y as MISSING_GATEWAY_CREDENTIALS_ERROR } from "./client-BVrAp-pq.js";
2
- import { C as withLogContext, F as normalizeIdentityEmail, I as isRecord$4, R as toOptionalString, a as extractGenAiUsageSummary, b as setTags, c as getLogContextAttributesForSpan, d as logException, f as logInfo, g as serializeGenAiAttribute, i as extractGenAiUsageAttributes, l as getTracePropagationHeaders, m as normalizeGenAiFinishReason, p as logWarn, u as logError, v as setSpanAttributes, w as withSpan, x as summarizeMessageText, y as setSpanStatus } from "./logging-tPQeUe2i.js";
3
- import { m as startInactiveSpan, v as withActiveSpan } from "./sentry-CgWZM_kV.js";
4
- import { a as toCanonicalInputMessage, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes, t as canExposeConversationPayload } from "./conversation-privacy-CpSYOWnP.js";
5
- import { n as botConfig, v as normalizeSlackEmojiName } from "./config-DdBiDanf.js";
6
- import { a as formatModelProfiles, c as profileConfig, i as formatModelProfile, l as TURN_REASONING_LEVELS, n as ModelProfileNotConfiguredError, o as modelIdForProfile, s as modelProfileSchema } from "./model-profile-BwU8mqwD.js";
7
- import { a as isUserActor, d as parseSlackTeamId, f as parseSlackUserId, g as parseSlackMessageTs, l as parseSlackChannelId, u as parseSlackChannelReferenceId } from "./actor-BTtLaeWy.js";
8
- import { N as parseDestination, S as agentTurnCostUsd, T as hasAgentTurnUsage, c as getConversationEventStore, d as getDb, f as getSqlExecutor, l as getConversationMessageSearchStore, r as readActorIdentity, u as getConversationStore, x as addAgentTurnUsage } from "./viewer-C-9nFKYr.js";
9
- import { a as juniorAgentInvocations, c as juniorIdentities, d as juniorDestinations, i as juniorAgentBindings, n as AGENT_INVOCATION_PARENT_MAILBOX_STATUSES, s as juniorConversations, t as AGENT_INVOCATION_MAILBOX_STATUSES } from "./agent-invocations-BY60iNw-.js";
10
- import { _ as juniorConversationAnnotations, b as juniorAttachments, c as juniorStats, f as juniorConversationBriefs, o as juniorAutomationRuns, x as juniorArtifacts } from "./executor-BroK9oKy.js";
11
- import { d as contextProvenance, f as instructionActors, m as sameActorIdentity, p as instructionProvenanceFor, t as KNOWN_CONVERSATION_EVENT_TYPES, u as agentInstructionProvenance } from "./history-9pO1Zd4Y.js";
12
- import { a as listReferenceFiles, c as soulPathCandidates, l as worldPathCandidates } from "./package-discovery-BVvSnQBB.js";
13
- import { a as resolveAuthTokenPlaceholder, c as fetchWithBoundedOAuthErrorBodies, d as credentialContextForActor, f as credentialContextSchema, h as CredentialUnavailableError, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, m as credentialUserSubjectId, o as resolvePluginCommandEnv, s as OAuthProviderError } from "./registry-CsNavQ_Z.js";
14
- import { n as pluginCatalogRuntime } from "./catalog-runtime-DF5OWqCc.js";
15
- import { a as parseSkillInvocation, i as parseSkillFile, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-CyvTsR9M.js";
16
- import { A as formatSlackLink, At as loadTurnRoute, Bt as recordToolExecutionStarted, D as automationRevision, Dt as loadLastModelProfile, Et as loadConversationProjection, F as addReactionToMessage, G as loadTurnCheckpoint, I as getSlackMessagePermalink, It as recordAuthorizationRequested, K as saveTurnCheckpoint, L as openSlackDirectMessage, Lt as recordGuardianActionReviewed, Mt as recordAgentsInstructionsUpdated, N as slackMention, Nt as recordAttachmentsDelivered, R as postSlackEphemeralMessage, Rt as recordMcpProviderConnected, St as ToolInputError, Tt as loadConnectedMcpProviders, V as uploadFilesToConversation, Vt as recordTurnRoute, W as continuableMessages, Xt as resolveTaskTitle, Yt as fallbackShortTitle, _t as normalizeToolNameFromResult, a as saveScheduledAutomation, at as createTurnLimitGate, bt as trimTrailingAssistantMessages, cn as estimateTextTokens, ct as getPiMessageRole, d as createEventAutomation, dn as historyItemFromPiMessage, dt as hasRuntimeTurnContext, et as TURN_LIMIT_DISABLED_REASON, f as deleteEventAutomation, fn as piMessageFromHistoryItem, g as listEventAutomationsForTeam, gt as isToolResultMessage, ht as isToolResultError, i as readScheduledAutomation, jt as openConversationProjection, k as escapeSlackMrkdwnText, ln as getAgentContextCompactionTriggerTokens, lt as getTerminalAssistantMessages, m as getEventAutomation, mt as isContinuablePiBoundary, n as listScheduledAutomationsForTeam, nt as TurnSliceLimitExceededError, ot as isTurnExecutionLimitExceededError, pt as isAssistantMessage, rt as TurnToolCallLimitExceededError, st as extractAssistantText, t as createScheduledAutomation, tt as TurnBudgetExceededError, un as getAgentContextInputLimitTokens, ut as getUserMessageInstructionText, v as saveEventAutomation, vt as retainRuntimeTurnContext, xt as TURN_CONTEXT_TAG, y as setEventAutomationStatus, yt as stripRuntimeTurnContext, z as postSlackMessage } from "./tasks-CODtRzvX.js";
17
- import { A as getWorkspaceSnapshotBuilder, B as STOP_WATCHING_TOOL_NAME, Bt as getFilePermalink, C as WorkspaceValidationError, D as setWorkspaceSnapshotBuild, Dt as matchSlackAttachments, E as setWorkspaceSnapshot, F as isSlackMessageTurn, Ft as defaultTimezone, G as createWatch, Gt as normalizeSlackConversationId, H as cancelWatch, Ht as getSlackClient, I as slackMessageTurnDisabledReason, It as resolveUserTimezone, J as getWatch, K as deliverWatch, L as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, M as workspaceRepoCheckoutPath, Mt as createPluginAnnotations, N as resolveChannelCapabilities, O as SANDBOX_RUNTIME, P as getSlackToolContext, R as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, Rt as SlackActionError, S as updateWorkspace, T as loadSnapshotsForProfile, Ut as isConversationScopedChannel, V as cancelSubscriptions, W as createTimerWatch, Wt as isDmChannel$1, Xt as JUNIOR_NATIVE_EVENT_NAMESPACE, Y as listWatches, _ as deleteWorkspace, at as getDashboardConversationLink, b as listWorkspaces, c as getPluginTools, en as conversationNoteEvent, ft as createPluginLogger, g as createWorkspace, j as tryWorkspaceRepoCheckoutPath, jt as saveObjectAnnotations, k as deleteWorkspaceSnapshotBuilders, l as getPluginUserPromptContributions, q as findMatchingWatches, qt as withSlackRetries, r as createPluginHookRunner, s as getPluginSystemPromptContributions, st as getDashboardTaskLink, u as getPlugins, v as getWorkspace, w as invalidateReadySnapshot, y as getWorkspaceByName, z as RESOURCE_WATCH_TOOL_SOURCE, zt as downloadPrivateSlackFile } from "./agent-hooks-DlSK8PQQ.js";
18
- import { B as briefLinkSchema, H as conversationBriefSchema, J as removedCardSchema, L as detectImageMediaType, R as isVisionImageMediaType, V as briefOutcomeStatusSchema } from "./conversation-T18Xlkx9.js";
19
- import { A as SANDBOX_DATA_ROOT, D as fenceLock, E as acquireActiveLock, F as sandboxSkillFile, I as sandboxSkillPathResolution, M as SANDBOX_SKILLS_ROOT, N as SANDBOX_WORKSPACE_ROOT, O as withLock, P as sandboxSkillDir, _ as workspaceSnapshotNotReadyUserMessage, a as isAbortError, b as buildNonInteractiveShellScript, c as isSandboxCommandStreamInterruptedError, d as isSnapshottingError, f as throwSandboxOperationError, g as isWorkspaceSnapshotNotReadyError, h as getWorkspaceSnapshotNotReadyError, i as ensureDockerDaemon, j as SANDBOX_REPOS_ROOT, k as sleep, l as isSandboxMissingError, m as WorkspaceSnapshotNotReadyError, n as hash, o as isAlreadyExistsError, p as wrapSandboxSetupError, r as isStale, s as isSandboxApiTransientError, t as create, u as isSandboxUnavailableError, v as getVercelSandboxCredentials, w as getStateAdapter, x as runNonInteractiveCommand, y as buildCommandScript } from "./profile-Bb1zCVGP.js";
20
- import { n as canReusePendingAuthLink, t as abandonReplacedPendingAuth } from "./pending-auth-DT3MRVW8.js";
21
- import { c as isTurnInputCommitLostError, i as TurnInputCommitLostError, r as CooperativeTurnYieldError, t as authorizationId } from "./oauth-authorization-BA4Dt6a7.js";
22
- import { a as isNoReplyMarker, i as NO_REPLY_MARKER, n as getAssistantReplyText, r as sanitizeAssistantText, t as decideReply } from "./assistant-reply-yn5G-YEG.js";
23
- import { C as registeredEventMatchSchema, D as requireSupportedEventMatch, E as requireEventIdentifier, I as readAutomationResult, L as remindMissingAutomationResult, M as FINISH_AUTOMATION_RUN_TOOL_NAME, N as automationResultSchema, S as pluginSupportsEvent, T as registeredResourceTypeSchema, _ as workspaceSnapshotWatch, b as eventNamespaceSchema, d as requireSlackChannelMessageScope, g as workspaceSnapshotFinishedEvent, h as WORKSPACE_SNAPSHOT_READY_EVENT, l as getEventCatalog, m as WORKSPACE_SNAPSHOT_FAILED_EVENT, n as markConversationsStopped, o as enqueueEventNotification, t as getConversationStoppedAtMs, v as automationEventCatalog, w as registeredEventTypeSchema, x as hasEventCatalogEntries } from "./session-stop-q-6GNHx6.js";
24
- import { i as isValidTimeZone, r as getZonedDateTimeParts } from "./cadence-D00SCzT1.js";
25
- import { a as createSandboxSession, c as postinstall, d as getSandboxResources, i as bindSandboxFileSystem, l as setSnapshotSpanAttributes, n as isMissingError, o as stopSession, r as resolve$1, s as dependencies } from "./resolve-B6ZZ9duG.js";
26
- import { a as getVercelConversationWorkQueue, f as getTurnRequestDeadline, n as sendNextWorkspaceSnapshotJob, r as sendWorkspaceSnapshotJob } from "./job-queue-BbGg3gvu.js";
27
- import { E as stopConversationWork } from "./store-D2It0ozF.js";
28
- import { F as taskOutcomeInputSchema, M as compileScheduleIntent, N as scheduleIntentSchema, O as automationInstructionToolSchema, T as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, j as ScheduleIntentError, k as automationTitleSchema } from "./automation-CHdlHVZP.js";
29
- import { r as isExperimentalFeatureEnabled } from "./experimental-Qn9rKLgx.js";
30
- import { n as privateTraceResultAttributes } from "./private-trace-result-BLvBjy_e.js";
1
+ import { b as getGatewayApiKey, c as hasCompactedConversationContext, d as unwrapCurrentInstruction, f as escapeXml, g as getProviderErrorAttributes, h as findProviderError, i as completeText, l as isCompactionSummaryText, m as createProviderError, n as GEN_AI_SERVER_ADDRESS, o as resolveGatewayModel, p as ProviderError, r as completeObject, s as COMPACTION_SUMMARY_PREFIX, t as GEN_AI_PROVIDER_NAME, u as renderCurrentInstruction, v as isProviderRetryError, x as resolveGatewayCredential, y as MISSING_GATEWAY_CREDENTIALS_ERROR } from "./client-DbyHuMFU.js";
2
+ import { R as normalizeIdentityEmail, S as summarizeMessageText, T as withSpan, V as toOptionalString, _ as serializeGenAiAttribute, a as extractGenAiUsageSummary, b as setSpanStatus, c as getLogContextAttributesForSpan, d as logError, f as logException, h as normalizeGenAiFinishReason, i as extractGenAiUsageAttributes, l as getTracePropagationHeaders, m as logWarn, p as logInfo, u as logAudit, w as withLogContext, x as setTags, y as setSpanAttributes, z as isRecord$4 } from "./logging-DsHONhVm.js";
3
+ import { m as startInactiveSpan, v as withActiveSpan } from "./sentry-BBUlHih9.js";
4
+ import { a as toCanonicalInputMessage, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes, t as canExposeConversationPayload } from "./conversation-privacy-DHP_xnVj.js";
5
+ import { n as botConfig, v as normalizeSlackEmojiName } from "./config-_WO_AjCB.js";
6
+ import { a as formatModelProfiles, c as profileConfig, i as formatModelProfile, l as TURN_REASONING_LEVELS, n as ModelProfileNotConfiguredError, o as modelIdForProfile, s as modelProfileSchema } from "./model-profile-Bg8EoCKD.js";
7
+ import { a as isUserActor, d as parseSlackTeamId, f as parseSlackUserId, g as parseSlackMessageTs, l as parseSlackChannelId, u as parseSlackChannelReferenceId } from "./actor-tlxzqaRe.js";
8
+ import { C as addAgentTurnUsage, D as hasAgentTurnUsage, R as parseDestination, c as getConversationEventStore, d as getDb, f as getSqlExecutor, l as getConversationMessageSearchStore, r as readActorIdentity, u as getConversationStore, w as agentTurnCostUsd } from "./viewer-CGvvRqKp.js";
9
+ import { a as juniorAgentInvocations, c as juniorIdentities, d as juniorDestinations, i as juniorAgentBindings, n as AGENT_INVOCATION_PARENT_MAILBOX_STATUSES, s as juniorConversations, t as AGENT_INVOCATION_MAILBOX_STATUSES } from "./agent-invocations-Qfz7dWgU.js";
10
+ import { _ as juniorConversationAnnotations, a as juniorAutomationRuns, b as juniorAttachments, c as juniorStats, f as juniorConversationBriefs, x as juniorArtifacts } from "./executor-RvG6kVe1.js";
11
+ import { d as contextProvenance, f as instructionActors, m as sameActorIdentity, p as instructionProvenanceFor, t as KNOWN_CONVERSATION_EVENT_TYPES, u as agentInstructionProvenance } from "./history-AY8rs-FR.js";
12
+ import { a as listReferenceFiles, c as soulPathCandidates, l as worldPathCandidates } from "./package-discovery-DJBompdd.js";
13
+ import { _ as CredentialUnavailableError, a as resolveAuthTokenPlaceholder, c as fetchWithBoundedOAuthErrorBodies, d as actorLogContext, f as credentialContextForActor, g as credentialUserSubjectId, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, o as resolvePluginCommandEnv, p as credentialContextSchema, s as OAuthProviderError } from "./registry-Du566MtJ.js";
14
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-BN4DVxco.js";
15
+ import { a as parseSkillInvocation, i as parseSkillFile, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-DyQBLIrK.js";
16
+ import { A as escapeSlackMrkdwnText, B as postSlackMessage, Ct as ToolInputError, Dt as loadConversationProjection, Et as loadConnectedMcpProviders, G as continuableMessages, H as uploadFilesToConversation, Ht as recordTurnRoute, I as addReactionToMessage, K as loadTurnCheckpoint, L as getSlackMessagePermalink, Lt as recordAuthorizationRequested, Mt as openConversationProjection, Nt as recordAgentsInstructionsUpdated, O as automationRevision, Ot as loadLastModelProfile, P as slackMention, Pt as recordAttachmentsDelivered, R as openSlackDirectMessage, Rt as recordGuardianActionReviewed, St as TURN_CONTEXT_TAG, Vt as recordToolExecutionStarted, Xt as fallbackShortTitle, Zt as resolveTaskTitle, _t as isToolResultMessage, a as saveScheduledAutomation, bt as stripRuntimeTurnContext, ct as extractAssistantText, d as createEventAutomation, dn as getAgentContextInputLimitTokens, dt as getUserMessageInstructionText, f as deleteEventAutomation, fn as historyItemFromPiMessage, ft as hasRuntimeTurnContext, g as listEventAutomationsForTeam, gt as isToolResultError, ht as isContinuablePiBoundary, i as readScheduledAutomation, it as TurnToolCallLimitExceededError, j as formatSlackLink, jt as loadTurnRoute, ln as estimateTextTokens, lt as getPiMessageRole, m as getEventAutomation, mt as isAssistantMessage, n as listScheduledAutomationsForTeam, nt as TurnBudgetExceededError, ot as createTurnLimitGate, pn as piMessageFromHistoryItem, q as saveTurnCheckpoint, rt as TurnSliceLimitExceededError, st as isTurnExecutionLimitExceededError, t as createScheduledAutomation, tt as TURN_LIMIT_DISABLED_REASON, un as getAgentContextCompactionTriggerTokens, ut as getTerminalAssistantMessages, v as saveEventAutomation, vt as normalizeToolNameFromResult, xt as trimTrailingAssistantMessages, y as setEventAutomationStatus, yt as retainRuntimeTurnContext, z as postSlackEphemeralMessage, zt as recordMcpProviderConnected } from "./tasks-CEXKTASS.js";
17
+ import { A as getWorkspaceSnapshotBuilder, B as STOP_WATCHING_TOOL_NAME, Bt as getFilePermalink, C as WorkspaceValidationError, D as setWorkspaceSnapshotBuild, Dt as matchSlackAttachments, E as setWorkspaceSnapshot, F as isSlackMessageTurn, Ft as defaultTimezone, G as createWatch, Gt as normalizeSlackConversationId, H as cancelWatch, Ht as getSlackClient, I as slackMessageTurnDisabledReason, It as resolveUserTimezone, J as getWatch, K as deliverWatch, L as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, M as workspaceRepoCheckoutPath, Mt as createPluginAnnotations, N as resolveChannelCapabilities, O as SANDBOX_RUNTIME, P as getSlackToolContext, R as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, Rt as SlackActionError, S as updateWorkspace, T as loadSnapshotsForProfile, Ut as isConversationScopedChannel, V as cancelSubscriptions, W as createTimerWatch, Wt as isDmChannel$1, Xt as JUNIOR_NATIVE_EVENT_NAMESPACE, Y as listWatches, _ as deleteWorkspace, at as getDashboardConversationLink, b as listWorkspaces, c as getPluginTools, en as conversationNoteEvent, ft as createPluginLogger, g as createWorkspace, j as tryWorkspaceRepoCheckoutPath, jt as saveObjectAnnotations, k as deleteWorkspaceSnapshotBuilders, l as getPluginUserPromptContributions, q as findMatchingWatches, qt as withSlackRetries, r as createPluginHookRunner, s as getPluginSystemPromptContributions, st as getDashboardTaskLink, u as getPlugins, v as getWorkspace, w as invalidateReadySnapshot, y as getWorkspaceByName, z as RESOURCE_WATCH_TOOL_SOURCE, zt as downloadPrivateSlackFile } from "./agent-hooks-BJ_5mlRH.js";
18
+ import { B as briefLinkSchema, H as conversationBriefSchema, J as removedCardSchema, L as detectImageMediaType, R as isVisionImageMediaType, V as briefOutcomeStatusSchema } from "./conversation-DjN3mlog.js";
19
+ import { A as SANDBOX_DATA_ROOT, D as fenceLock, E as acquireActiveLock, F as sandboxSkillFile, I as sandboxSkillPathResolution, M as SANDBOX_SKILLS_ROOT, N as SANDBOX_WORKSPACE_ROOT, O as withLock, P as sandboxSkillDir, _ as workspaceSnapshotNotReadyUserMessage, a as isAbortError, b as buildNonInteractiveShellScript, c as isSandboxCommandStreamInterruptedError, d as isSnapshottingError, f as throwSandboxOperationError, g as isWorkspaceSnapshotNotReadyError, h as getWorkspaceSnapshotNotReadyError, i as ensureDockerDaemon, j as SANDBOX_REPOS_ROOT, k as sleep, l as isSandboxMissingError, m as WorkspaceSnapshotNotReadyError, n as hash, o as isAlreadyExistsError, p as wrapSandboxSetupError, r as isStale, s as isSandboxApiTransientError, t as create, u as isSandboxUnavailableError, v as getVercelSandboxCredentials, w as getStateAdapter, x as runNonInteractiveCommand, y as buildCommandScript } from "./profile-DpYjfKke.js";
20
+ import { n as canReusePendingAuthLink, t as abandonReplacedPendingAuth } from "./pending-auth-D8J1uJUS.js";
21
+ import { c as isTurnInputCommitLostError, i as TurnInputCommitLostError, r as CooperativeTurnYieldError, t as authorizationId } from "./oauth-authorization-djQn5Nhy.js";
22
+ import { a as isNoReplyMarker, i as NO_REPLY_MARKER, n as getAssistantReplyText, r as sanitizeAssistantText, t as decideReply } from "./assistant-reply-H1M-91oF.js";
23
+ import { C as pluginSupportsEvent, D as requireEventIdentifier, E as registeredResourceTypeSchema, L as readAutomationResult, N as FINISH_AUTOMATION_RUN_TOOL_NAME, O as requireSupportedEventMatch, P as automationResultSchema, R as remindMissingAutomationResult, S as hasEventCatalogEntries, T as registeredEventTypeSchema, _ as workspaceSnapshotFinishedEvent, d as requireSlackChannelMessageScope, g as WORKSPACE_SNAPSHOT_READY_EVENT, h as WORKSPACE_SNAPSHOT_FAILED_EVENT, l as getEventCatalog, n as markConversationsStopped, o as enqueueEventNotification, t as getConversationStoppedAtMs, v as workspaceSnapshotWatch, w as registeredEventMatchSchema, x as eventNamespaceSchema, y as automationEventCatalog } from "./session-stop-CIoFiwwe.js";
24
+ import { i as isValidTimeZone, r as getZonedDateTimeParts } from "./cadence-R7Em4RjE.js";
25
+ import { a as createSandboxSession, c as postinstall, d as getSandboxResources, i as bindSandboxFileSystem, l as setSnapshotSpanAttributes, n as isMissingError, o as stopSession, r as resolve$1, s as dependencies } from "./resolve-ClCIgh8E.js";
26
+ import { a as getVercelConversationWorkQueue, f as getTurnRequestDeadline, n as sendNextWorkspaceSnapshotJob, r as sendWorkspaceSnapshotJob } from "./job-queue-DVe37it2.js";
27
+ import { E as stopConversationWork } from "./store-DJLwq4x8.js";
28
+ import { F as taskOutcomeInputSchema, M as compileScheduleIntent, N as scheduleIntentSchema, O as automationInstructionToolSchema, T as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, j as ScheduleIntentError, k as automationTitleSchema } from "./automation-DWBFBenG.js";
29
+ import { r as isExperimentalFeatureEnabled } from "./experimental-BNK1l1jv.js";
30
+ import { n as privateTraceResultAttributes } from "./private-trace-result-CE7_lEdq.js";
31
31
  import { streamSimple } from "@earendil-works/pi-ai/compat";
32
32
  import { createGatewayProvider } from "@ai-sdk/gateway";
33
33
  import { generateText } from "ai";
@@ -57,7 +57,7 @@ import net from "node:net";
57
57
  import { NodeHtmlMarkdown } from "node-html-markdown";
58
58
  import { Value } from "@sinclair/typebox/value";
59
59
  import { SignJWT, importPKCS8 } from "jose";
60
- //#region src/chat/configuration/defaults.ts
60
+ // src/chat/configuration/defaults.ts
61
61
  let installDefaults = {};
62
62
  function cloneDefaults(defaults) {
63
63
  return structuredClone(defaults);
@@ -78,8 +78,7 @@ function setConfigDefaults(defaults) {
78
78
  function getConfigDefaults() {
79
79
  return cloneDefaults(installDefaults);
80
80
  }
81
- //#endregion
82
- //#region src/chat/sandbox/skill-sandbox.ts
81
+ // src/chat/sandbox/skill-sandbox.ts
83
82
  const MAX_SKILL_FILE_BYTES = 262144;
84
83
  const DEFAULT_MAX_SKILL_FILE_CHARS = 2e4;
85
84
  const DEFAULT_MAX_SKILL_LIST_ENTRIES = 200;
@@ -219,12 +218,12 @@ var SkillSandbox = class {
219
218
  }
220
219
  const active = this.getActiveSkill();
221
220
  if (active) return active;
222
- if (this.loadedSkills.size === 1) return [...this.loadedSkills.values()][0];
221
+ const [onlySkill, ...otherSkills] = this.loadedSkills.values();
222
+ if (onlySkill && otherSkills.length === 0) return onlySkill;
223
223
  throw new Error("No active skill is loaded. Call loadSkill first or pass skill_name explicitly.");
224
224
  }
225
225
  };
226
- //#endregion
227
- //#region src/chat/tools/sandbox/file-utils.ts
226
+ // src/chat/tools/sandbox/file-utils.ts
228
227
  const MAX_TEXT_CHARS = 6e4;
229
228
  const RIPGREP_EXCLUDED_GLOBS = ["!**/.git/**", "!**/node_modules/**"];
230
229
  const DEFAULT_SEARCH_COMMAND_TIMEOUT_MS = 3e4;
@@ -269,7 +268,7 @@ function escapeRegExp(value) {
269
268
  function globToRegExp(pattern) {
270
269
  let source = "";
271
270
  for (let index = 0; index < pattern.length; index += 1) {
272
- const char = pattern[index];
271
+ const char = pattern.charAt(index);
273
272
  const next = pattern[index + 1];
274
273
  if (char === "*" && next === "*") {
275
274
  if (pattern[index + 2] === "/") {
@@ -390,8 +389,7 @@ async function collectFiles(params) {
390
389
  missingRoot: missingPath === params.root
391
390
  };
392
391
  }
393
- //#endregion
394
- //#region src/chat/repository-instructions.ts
392
+ // src/chat/repository-instructions.ts
395
393
  const AGENTS_FILENAME = "AGENTS.md";
396
394
  const MAX_REPOSITORY_INSTRUCTIONS_BYTES = 32768;
397
395
  /** Repository skill directories, in priority order, relative to the Git root. */
@@ -649,8 +647,7 @@ function findVisibleAgentsInstructions(messages) {
649
647
  }
650
648
  }
651
649
  }
652
- //#endregion
653
- //#region src/chat/agent/repository-context.ts
650
+ // src/chat/agent/repository-context.ts
654
651
  function findRestoredInstructions(messages, provenance) {
655
652
  const restoredContext = messages?.map((message, index) => ({
656
653
  message,
@@ -691,8 +688,7 @@ function createRepositoryInstructionsContext(options) {
691
688
  };
692
689
  } };
693
690
  }
694
- //#endregion
695
- //#region src/chat/pi/traced-stream.ts
691
+ // src/chat/pi/traced-stream.ts
696
692
  function attributeModeForPrivacy(conversationPrivacy) {
697
693
  return conversationPrivacy === "public" ? "content" : "metadata";
698
694
  }
@@ -800,13 +796,11 @@ function createTracedStreamFn(baseOrOptions = streamSimple) {
800
796
  }
801
797
  };
802
798
  }
803
- //#endregion
804
- //#region src/chat/runtime/dev-agent-trace.ts
799
+ // src/chat/runtime/dev-agent-trace.ts
805
800
  function shouldEmitDevAgentTrace() {
806
801
  return process.env.NODE_ENV === "development";
807
802
  }
808
- //#endregion
809
- //#region src/chat/agent-invocations/blocked-report.ts
803
+ // src/chat/agent-invocations/blocked-report.ts
810
804
  /** Blocked report of a child agent. See "Blocked Reports" in README.md. */
811
805
  /** Model-facing tool that ends a child agent run as blocked. */
812
806
  const REPORT_BLOCKED_TOOL_NAME = "reportBlocked";
@@ -825,8 +819,7 @@ function readBlockedReport(messages) {
825
819
  if (parsed.success) return parsed.data;
826
820
  }
827
821
  }
828
- //#endregion
829
- //#region src/chat/services/turn-result.ts
822
+ // src/chat/services/turn-result.ts
830
823
  /** Process raw agent messages into a structured AgentRunResult. */
831
824
  function buildTurnResult(input) {
832
825
  if (input.requireAutomationResult) return buildAutomationTurnResult(input);
@@ -939,8 +932,7 @@ function buildAutomationTurnResult(input) {
939
932
  })
940
933
  };
941
934
  }
942
- //#endregion
943
- //#region src/chat/services/provider-retry.ts
935
+ // src/chat/services/provider-retry.ts
944
936
  const PROVIDER_RETRY_DELAYS_MS = [
945
937
  2e3,
946
938
  4e3,
@@ -965,8 +957,7 @@ function nextProviderRetry(args) {
965
957
  providerError
966
958
  };
967
959
  }
968
- //#endregion
969
- //#region src/chat/services/empty-output-continuation.ts
960
+ // src/chat/services/empty-output-continuation.ts
970
961
  /**
971
962
  * Decide whether empty assistant output gets one continuation after a
972
963
  * history replacement.
@@ -987,8 +978,7 @@ function nextEmptyOutputContinuation(args) {
987
978
  messages
988
979
  } : { kind: "exhausted" };
989
980
  }
990
- //#endregion
991
- //#region src/chat/agent/retry-usage.ts
981
+ // src/chat/agent/retry-usage.ts
992
982
  /**
993
983
  * Return usage discarded when a retry keeps an exact prefix of agent history.
994
984
  *
@@ -999,8 +989,7 @@ function getDiscardedRetryUsage(messages, retryMessages) {
999
989
  const usage = extractGenAiUsageSummary(...messages.slice(retryMessages.length).filter(isAssistantMessage));
1000
990
  return hasAgentTurnUsage(usage) ? usage : void 0;
1001
991
  }
1002
- //#endregion
1003
- //#region src/chat/tool-support/structured-result.ts
992
+ // src/chat/tool-support/structured-result.ts
1004
993
  const juniorToolContinuationSchema = z.object({
1005
994
  arguments: z.record(z.string(), z.unknown()),
1006
995
  reason: z.string().min(1).optional()
@@ -1042,8 +1031,7 @@ function makeStructuredToolOutput(details, options = {}) {
1042
1031
  details
1043
1032
  };
1044
1033
  }
1045
- //#endregion
1046
- //#region src/chat/tool-support/timed-out-tool-result.ts
1034
+ // src/chat/tool-support/timed-out-tool-result.ts
1047
1035
  /**
1048
1036
  * Project a host-preempted tool attempt onto the normal tool-result shape.
1049
1037
  *
@@ -1068,8 +1056,7 @@ function projectTimedOutToolResult(result) {
1068
1056
  isError: false
1069
1057
  };
1070
1058
  }
1071
- //#endregion
1072
- //#region src/chat/services/turn-router.ts
1059
+ // src/chat/services/turn-router.ts
1073
1060
  const CLASSIFIER_CONFIDENCE_THRESHOLD = .75;
1074
1061
  const MAX_ROUTER_CONTEXT_CHARS = 8e3;
1075
1062
  const ROUTER_CONTEXT_HEAD_CHARS = 3e3;
@@ -1304,8 +1291,7 @@ function toPiReasoningLevel(level) {
1304
1291
  case "xhigh": return "xhigh";
1305
1292
  }
1306
1293
  }
1307
- //#endregion
1308
- //#region src/chat/services/auth-pause.ts
1294
+ // src/chat/services/auth-pause.ts
1309
1295
  /**
1310
1296
  * Runtime-owned signal that the current turn must park until the user
1311
1297
  * completes an external authorization step.
@@ -1344,8 +1330,7 @@ var AuthorizationFlowDisabledError = class extends Error {
1344
1330
  this.provider = provider;
1345
1331
  }
1346
1332
  };
1347
- //#endregion
1348
- //#region src/chat/tools/definition.ts
1333
+ // src/chat/tools/definition.ts
1349
1334
  /** Distinguish legacy TypeBox schemas from JSON Schema projected from Zod. */
1350
1335
  function isTypeBoxInputSchema(schema) {
1351
1336
  return typeof schema === "object" && schema !== null && Kind in schema;
@@ -1367,8 +1352,7 @@ function disableTools(tools, reason) {
1367
1352
  disabledReason: reason
1368
1353
  }]));
1369
1354
  }
1370
- //#endregion
1371
- //#region src/chat/agent/types.ts
1355
+ // src/chat/agent/types.ts
1372
1356
  /** Resume the agent turn after a transient or ambiguous delivery failure. */
1373
1357
  var RetryableDeliveryError = class extends Error {
1374
1358
  constructor(cause) {
@@ -1434,8 +1418,7 @@ function surfaceFromRun(run) {
1434
1418
  if (run.source.kind === "web") return "api";
1435
1419
  return "internal";
1436
1420
  }
1437
- //#endregion
1438
- //#region src/chat/tool-support/action-review-history.ts
1421
+ // src/chat/tool-support/action-review-history.ts
1439
1422
  const MAX_VISIBLE_HISTORY_CHARS = 12e3;
1440
1423
  const priorRejectionSchema = z.object({
1441
1424
  decision: z.enum(["ask", "deny"]),
@@ -1537,8 +1520,7 @@ function restoreToolActionRejections(messages) {
1537
1520
  }
1538
1521
  return priorRejections;
1539
1522
  }
1540
- //#endregion
1541
- //#region src/chat/agent/action-confirmation-retry.ts
1523
+ // src/chat/agent/action-confirmation-retry.ts
1542
1524
  const RUN_ENDING_TOOL_NAMES = /* @__PURE__ */ new Set([FINISH_AUTOMATION_RUN_TOOL_NAME, REPORT_BLOCKED_TOOL_NAME]);
1543
1525
  function endsRun(message) {
1544
1526
  return isToolResultMessage(message) && !isToolResultError(message) && RUN_ENDING_TOOL_NAMES.has(normalizeToolNameFromResult(message) ?? "");
@@ -1567,8 +1549,7 @@ function actionConfirmationRetryMessages(messages) {
1567
1549
  if (getPiMessageRole(retryMessages.at(-1)) !== "toolResult") return;
1568
1550
  return retryMessages;
1569
1551
  }
1570
- //#endregion
1571
- //#region src/chat/tool-support/action-review.ts
1552
+ // src/chat/tool-support/action-review.ts
1572
1553
  /**
1573
1554
  * Owns the execution gate for reviewable tool actions.
1574
1555
  *
@@ -1843,8 +1824,7 @@ async function reviewToolAction(toolCallId, toolName, tool, input, review, signa
1843
1824
  if (!review) throw new ToolActionReviewUnavailableError();
1844
1825
  return review.review(toolCallId, toolName, tool, input, signal);
1845
1826
  }
1846
- //#endregion
1847
- //#region src/chat/agent/skills.ts
1827
+ // src/chat/agent/skills.ts
1848
1828
  /** Run-scoped skill discovery and explicit invocation. */
1849
1829
  let startupDiscoveryLogged = false;
1850
1830
  /** Upsert a skill into the active skills list by name. */
@@ -1894,8 +1874,7 @@ async function loadRunSkill(args) {
1894
1874
  if (loadedSkill) upsertActiveSkill(args.activeSkills, loadedSkill);
1895
1875
  return loadedSkill;
1896
1876
  }
1897
- //#endregion
1898
- //#region src/chat/prompt.ts
1877
+ // src/chat/prompt.ts
1899
1878
  /**
1900
1879
  * Prompt assembly.
1901
1880
  *
@@ -2378,8 +2357,7 @@ function buildTurnContextPrompt(params) {
2378
2357
  `</${TURN_CONTEXT_TAG}>`
2379
2358
  ].filter((section) => Boolean(section)).join("\n\n");
2380
2359
  }
2381
- //#endregion
2382
- //#region src/chat/conversations/notes.ts
2360
+ // src/chat/conversations/notes.ts
2383
2361
  /**
2384
2362
  * Conversation notes: short facts that core attaches to a Conversation without
2385
2363
  * starting a Turn. The next Turn shows them to the model in its runtime turn
@@ -2436,8 +2414,7 @@ async function loadTurnConversationNotes(input) {
2436
2414
  }
2437
2415
  return newestFirst.reverse();
2438
2416
  }
2439
- //#endregion
2440
- //#region src/chat/agent/prompt.ts
2417
+ // src/chat/agent/prompt.ts
2441
2418
  /**
2442
2419
  * Per-run prompt assembly.
2443
2420
  *
@@ -2812,8 +2789,7 @@ async function assemblePrompt(args) {
2812
2789
  userContentParts
2813
2790
  };
2814
2791
  }
2815
- //#endregion
2816
- //#region src/chat/capabilities/router.ts
2792
+ // src/chat/capabilities/router.ts
2817
2793
  var ProviderCredentialRouter = class {
2818
2794
  brokersByProvider;
2819
2795
  constructor(input) {
@@ -2828,11 +2804,9 @@ var ProviderCredentialRouter = class {
2828
2804
  });
2829
2805
  }
2830
2806
  };
2831
- //#endregion
2832
- //#region src/chat/credentials/user-token-store.ts
2807
+ // src/chat/credentials/user-token-store.ts
2833
2808
  const storedTokensSchema = pluginStoredTokensSchema;
2834
- //#endregion
2835
- //#region src/chat/credentials/state-adapter-token-store.ts
2809
+ // src/chat/credentials/state-adapter-token-store.ts
2836
2810
  const KEY_PREFIX = "oauth-token";
2837
2811
  const BUFFER_MS = 864e5;
2838
2812
  const LONG_LIVED_TTL_MS = 31536e6;
@@ -2878,8 +2852,7 @@ var StateAdapterTokenStore = class {
2878
2852
  }
2879
2853
  }
2880
2854
  };
2881
- //#endregion
2882
- //#region src/chat/capabilities/factory.ts
2855
+ // src/chat/capabilities/factory.ts
2883
2856
  const sandboxEgressRouters = /* @__PURE__ */ new WeakMap();
2884
2857
  /** Create the user token store used by OAuth-backed credential brokers. */
2885
2858
  function createUserTokenStore() {
@@ -2907,8 +2880,7 @@ function getSandboxEgressRouter() {
2907
2880
  async function issueProviderCredentialLease(input) {
2908
2881
  return await getSandboxEgressRouter().issue(input);
2909
2882
  }
2910
- //#endregion
2911
- //#region src/chat/capabilities/jr-rpc-command.ts
2883
+ // src/chat/capabilities/jr-rpc-command.ts
2912
2884
  function commandResult(input) {
2913
2885
  let stdout = "";
2914
2886
  if (typeof input.stdout === "string") stdout = input.stdout;
@@ -2941,7 +2913,7 @@ function parsePrefixFlag(extras) {
2941
2913
  ...prefix ? { prefix } : void 0
2942
2914
  };
2943
2915
  }
2944
- if (extras.length === 1 && extras[0].startsWith("--prefix=")) {
2916
+ if (extras.length === 1 && extras[0]?.startsWith("--prefix=")) {
2945
2917
  const prefix = extras[0].slice(9).trim();
2946
2918
  return {
2947
2919
  ok: true,
@@ -3163,8 +3135,7 @@ async function maybeExecuteJrRpcCustomCommand(command, deps) {
3163
3135
  }
3164
3136
  };
3165
3137
  }
3166
- //#endregion
3167
- //#region src/chat/sandbox/command-result.ts
3138
+ // src/chat/sandbox/command-result.ts
3168
3139
  /** Format one shell command outcome as Junior's structured tool result. */
3169
3140
  function formatSandboxCommandResult(params) {
3170
3141
  return makeStructuredToolOutput({
@@ -3184,8 +3155,7 @@ function formatSandboxCommandResult(params) {
3184
3155
  ...params.permission_denied ? { permission_denied: params.permission_denied } : void 0
3185
3156
  });
3186
3157
  }
3187
- //#endregion
3188
- //#region src/chat/slack/oauth-authorization-message.ts
3158
+ // src/chat/slack/oauth-authorization-message.ts
3189
3159
  const ACCOUNT_SCOPE_NOTE = "This connects only your account. Junior sees only what you can see.";
3190
3160
  /** Present private OAuth authorization with a clear action and text fallback. */
3191
3161
  function buildSlackOAuthAuthorizationMessage(args) {
@@ -3210,8 +3180,7 @@ function buildSlackOAuthAuthorizationMessage(args) {
3210
3180
  }]
3211
3181
  };
3212
3182
  }
3213
- //#endregion
3214
- //#region src/chat/oauth-flow.ts
3183
+ // src/chat/oauth-flow.ts
3215
3184
  const OAUTH_STATE_TTL_MS = 6e5;
3216
3185
  function optionalString(value) {
3217
3186
  return typeof value === "string" ? value : void 0;
@@ -3377,8 +3346,7 @@ async function startOAuthFlow(provider, input) {
3377
3346
  })
3378
3347
  };
3379
3348
  }
3380
- //#endregion
3381
- //#region src/chat/sandbox/egress/schemas.ts
3349
+ // src/chat/sandbox/egress/schemas.ts
3382
3350
  const finiteNumberSchema = z.number().refine(Number.isFinite);
3383
3351
  const httpStatusSchema = z.number().int().min(100).max(599);
3384
3352
  const providerNameSchema = z.string().regex(/^[a-z][a-z0-9-]*$/);
@@ -3386,6 +3354,8 @@ const credentialSignalKindSchema = z.enum(["auth_required", "unavailable"]);
3386
3354
  const sandboxEgressGrantSchema = pluginGrantSchema;
3387
3355
  const sandboxEgressCredentialContextSchema = z.object({
3388
3356
  credentials: credentialContextSchema,
3357
+ /** Conversation that the credentials act for. Telemetry only; it grants nothing. */
3358
+ conversationId: z.string().min(1).optional(),
3389
3359
  egressId: z.string().min(1),
3390
3360
  expiresAtMs: finiteNumberSchema,
3391
3361
  contextId: z.string().min(1)
@@ -3439,8 +3409,7 @@ function parseSandboxEgressPermissionDeniedSignal(value) {
3439
3409
  const result = sandboxEgressPermissionDeniedSignalSchema.safeParse(value);
3440
3410
  return result.success ? result.data : void 0;
3441
3411
  }
3442
- //#endregion
3443
- //#region src/chat/sandbox/egress/session.ts
3412
+ // src/chat/sandbox/egress/session.ts
3444
3413
  const SANDBOX_EGRESS_PROXY_PATH = "/api/internal/sandbox-egress";
3445
3414
  const SANDBOX_EGRESS_TOKEN_VERSION = "v1";
3446
3415
  const SANDBOX_EGRESS_HMAC_CONTEXT = "junior.sandbox_egress.v1";
@@ -3525,6 +3494,7 @@ function createSandboxEgressCredentialToken(input) {
3525
3494
  const ttlMs = Math.max(1, input.ttlMs ?? DEFAULT_SESSION_TTL_MS);
3526
3495
  const now = Date.now();
3527
3496
  const context = {
3497
+ ...input.conversationId ? { conversationId: input.conversationId } : void 0,
3528
3498
  credentials: input.credentials,
3529
3499
  egressId: input.egressId,
3530
3500
  expiresAtMs: now + ttlMs,
@@ -3647,8 +3617,7 @@ async function consumeSandboxEgressPermissionDeniedSignal(egressId) {
3647
3617
  await Promise.all([state.delete(permissionSignalKey(egressId, "read")), state.delete(permissionSignalKey(egressId, "write"))]);
3648
3618
  return signal;
3649
3619
  }
3650
- //#endregion
3651
- //#region src/chat/sandbox/egress/tracing.ts
3620
+ // src/chat/sandbox/egress/tracing.ts
3652
3621
  function isValidDomainPattern(domain) {
3653
3622
  if (domain.includes("*")) return domain.startsWith("*.") && domain.indexOf("*", 1) === -1;
3654
3623
  return true;
@@ -3676,8 +3645,7 @@ function shouldPropagateSandboxEgressTrace(host, config = {}) {
3676
3645
  return domain === normalizedHost;
3677
3646
  });
3678
3647
  }
3679
- //#endregion
3680
- //#region src/chat/sandbox/egress/policy.ts
3648
+ // src/chat/sandbox/egress/policy.ts
3681
3649
  /** Return whether an outbound host is covered by a provider domain rule. */
3682
3650
  function matchesSandboxEgressDomain(host, domain) {
3683
3651
  return host.toLowerCase() === domain.toLowerCase();
@@ -3746,8 +3714,7 @@ async function resolveSandboxCommandEnvironment() {
3746
3714
  }
3747
3715
  return env;
3748
3716
  }
3749
- //#endregion
3750
- //#region src/chat/sandbox/prepare-workspace.ts
3717
+ // src/chat/sandbox/prepare-workspace.ts
3751
3718
  const WORKSPACE_SETUP_FAILURE_OUTPUT_MAX_CHARS = 7e3;
3752
3719
  const WORKSPACE_SETUP_FAILURE_TRUNCATION_MARKER = "[earlier setup output truncated]\n";
3753
3720
  const WORKSPACE_SETUP_NODE_OPTIONS = "--max-old-space-size=4096";
@@ -3827,8 +3794,7 @@ async function prepareWorkspaceSnapshot(params) {
3827
3794
  });
3828
3795
  if (result.exitCode !== 0) throw new Error(`Workspace setup failed: ${workspaceSetupFailureDetail(result)}`);
3829
3796
  }
3830
- //#endregion
3831
- //#region src/chat/events/people.ts
3797
+ // src/chat/events/people.ts
3832
3798
  const linkedSlackIdentity$1 = alias(juniorIdentities, "event_people_slack");
3833
3799
  function personKey(person) {
3834
3800
  return "email" in person ? `email:${normalizeIdentityEmail(person.email)}` : `${person.provider}:${person.handle.toLowerCase()}`;
@@ -3873,8 +3839,7 @@ async function resolveEventPeopleMentions(people, slackTeamId) {
3873
3839
  }
3874
3840
  return mentions;
3875
3841
  }
3876
- //#endregion
3877
- //#region src/chat/events/ingest.ts
3842
+ // src/chat/events/ingest.ts
3878
3843
  /** Match a normalized event and enqueue notifications into conversations. */
3879
3844
  async function ingestEvent(input, options) {
3880
3845
  const event = eventSchema.parse(input);
@@ -3926,8 +3891,7 @@ async function ingestEvent(input, options) {
3926
3891
  if (errors.length > 0) throw new AggregateError(errors, "Failed to deliver one or more watches");
3927
3892
  return { enqueued };
3928
3893
  }
3929
- //#endregion
3930
- //#region src/chat/sandbox/snapshot/workspace.ts
3894
+ // src/chat/sandbox/snapshot/workspace.ts
3931
3895
  const BUILD_TIMEOUT_MS = 36e5;
3932
3896
  const BUILD_TIMEOUT_ERROR = "Workspace snapshot build timed out after 1 hour";
3933
3897
  const BUILD_LOCK_TTL_MS = 12e4;
@@ -4309,8 +4273,7 @@ async function resolveWorkspaceSnapshot(params) {
4309
4273
  await sleep(WAIT_POLL_MS, params.signal);
4310
4274
  }
4311
4275
  }
4312
- //#endregion
4313
- //#region src/chat/sandbox/snapshot/job-runner.ts
4276
+ // src/chat/sandbox/snapshot/job-runner.ts
4314
4277
  /** Build Workspace snapshots in a background job. */
4315
4278
  const SNAPSHOT_BUILD_SYSTEM_ACTOR = {
4316
4279
  platform: "system",
@@ -4434,8 +4397,7 @@ async function ensureWorkspaceSnapshotBuild(input) {
4434
4397
  else await sendWorkspaceSnapshotJob(message);
4435
4398
  return "building";
4436
4399
  }
4437
- //#endregion
4438
- //#region src/chat/sandbox/skill-sync.ts
4400
+ // src/chat/sandbox/skill-sync.ts
4439
4401
  const DIRECTORY_CREATE_CONCURRENCY = 8;
4440
4402
  function toPosixRelative(base, absolute) {
4441
4403
  return path.relative(base, absolute).split(path.sep).join("/");
@@ -4564,8 +4526,7 @@ async function syncSkillsToSandbox(params) {
4564
4526
  });
4565
4527
  });
4566
4528
  }
4567
- //#endregion
4568
- //#region src/chat/sandbox/session.ts
4529
+ // src/chat/sandbox/session.ts
4569
4530
  const DEFAULT_MAX_OUTPUT_LENGTH = 3e4;
4570
4531
  const DEFAULT_BASH_COMMAND_TIMEOUT_MS = 3e5;
4571
4532
  const SANDBOX_RUNTIME_BIN_DIR = `${SANDBOX_WORKSPACE_ROOT}/.junior/bin`;
@@ -5155,8 +5116,7 @@ function createSandboxRuntime(options) {
5155
5116
  }
5156
5117
  };
5157
5118
  }
5158
- //#endregion
5159
- //#region src/chat/tools/sandbox/text-edits.ts
5119
+ // src/chat/tools/sandbox/text-edits.ts
5160
5120
  const MAX_DIFF_LINE_CHARS = 4e3;
5161
5121
  /** Preserve a text artifact's dominant line-ending style across rewrites. */
5162
5122
  function detectLineEnding(value) {
@@ -5276,8 +5236,7 @@ function validateAndApplyTextEdits(content, edits, targetName) {
5276
5236
  };
5277
5237
  });
5278
5238
  const matchedEdits = [];
5279
- for (let index = 0; index < normalizedEdits.length; index += 1) {
5280
- const edit = normalizedEdits[index];
5239
+ for (const [index, edit] of normalizedEdits.entries()) {
5281
5240
  const matchIndex = content.indexOf(edit.oldText);
5282
5241
  if (matchIndex === -1) throw new ToolInputError(`Could not find edits[${index}] in ${targetName}. oldText must match exactly including whitespace and newlines.`);
5283
5242
  const occurrences = countOccurrences(content, edit.oldText);
@@ -5290,24 +5249,20 @@ function validateAndApplyTextEdits(content, edits, targetName) {
5290
5249
  });
5291
5250
  }
5292
5251
  matchedEdits.sort((a, b) => a.matchIndex - b.matchIndex);
5293
- for (let index = 1; index < matchedEdits.length; index += 1) {
5252
+ for (const [index, current] of matchedEdits.entries()) {
5294
5253
  const previous = matchedEdits[index - 1];
5295
- const current = matchedEdits[index];
5254
+ if (!previous) continue;
5296
5255
  if (previous.matchIndex + previous.matchLength > current.matchIndex) throw new ToolInputError(`edits[${previous.editIndex}] and edits[${current.editIndex}] overlap in ${targetName}. Merge overlapping replacements into one edit.`);
5297
5256
  }
5298
5257
  let newContent = content;
5299
- for (let index = matchedEdits.length - 1; index >= 0; index -= 1) {
5300
- const edit = matchedEdits[index];
5301
- newContent = newContent.slice(0, edit.matchIndex) + edit.newText + newContent.slice(edit.matchIndex + edit.matchLength);
5302
- }
5258
+ for (const edit of [...matchedEdits].reverse()) newContent = newContent.slice(0, edit.matchIndex) + edit.newText + newContent.slice(edit.matchIndex + edit.matchLength);
5303
5259
  if (newContent === content) throw new ToolInputError(`No changes made to ${targetName}.`);
5304
5260
  return {
5305
5261
  baseContent: content,
5306
5262
  newContent
5307
5263
  };
5308
5264
  }
5309
- //#endregion
5310
- //#region src/chat/tool-support/zod-tool.ts
5265
+ // src/chat/tool-support/zod-tool.ts
5311
5266
  function isContentOnlyToolResult(value) {
5312
5267
  return value !== null && typeof value === "object" && Array.isArray(value.content) && !("details" in value);
5313
5268
  }
@@ -5364,8 +5319,7 @@ function zodTool(definition) {
5364
5319
  } } : void 0
5365
5320
  };
5366
5321
  }
5367
- //#endregion
5368
- //#region src/chat/tools/sandbox/edit-file.ts
5322
+ // src/chat/tools/sandbox/edit-file.ts
5369
5323
  /** Accept common edit argument variants before Pi validates the canonical schema. */
5370
5324
  function prepareEditFileArguments(input) {
5371
5325
  return prepareTextReplacementArguments(input);
@@ -5420,8 +5374,7 @@ function createEditFileTool() {
5420
5374
  }
5421
5375
  });
5422
5376
  }
5423
- //#endregion
5424
- //#region src/chat/tools/sandbox/find-files.ts
5377
+ // src/chat/tools/sandbox/find-files.ts
5425
5378
  const DEFAULT_FIND_LIMIT = 100;
5426
5379
  /** Find workspace files with structured limits instead of ad hoc shell output. */
5427
5380
  async function findFiles(params) {
@@ -5568,8 +5521,7 @@ function createFindFilesTool() {
5568
5521
  }
5569
5522
  });
5570
5523
  }
5571
- //#endregion
5572
- //#region src/chat/tools/sandbox/grep.ts
5524
+ // src/chat/tools/sandbox/grep.ts
5573
5525
  const DEFAULT_GREP_LIMIT = 100;
5574
5526
  const MAX_GREP_LINE_CHARS = 500;
5575
5527
  const booleanInput$2 = (description) => z.preprocess((value) => value === "true" ? true : value === "false" ? false : value, z.boolean()).describe(description);
@@ -5642,10 +5594,10 @@ async function grepFiles(params) {
5642
5594
  const lines = normalizeToLf$1(content).split("\n");
5643
5595
  const relativePath = files.length === 1 && filePath === root ? path.posix.basename(filePath) : path.posix.relative(root, filePath);
5644
5596
  const matchedLines = [];
5645
- for (let lineIndex = 0; lineIndex < lines.length; lineIndex += 1) {
5597
+ for (const [lineIndex, line] of lines.entries()) {
5646
5598
  if (!lineMatches({
5647
5599
  ignoreCase: params.ignoreCase,
5648
- line: lines[lineIndex],
5600
+ line,
5649
5601
  literal: params.literal,
5650
5602
  pattern: params.pattern,
5651
5603
  regex
@@ -5665,7 +5617,7 @@ async function grepFiles(params) {
5665
5617
  for (let current = start; current <= end; current += 1) {
5666
5618
  if (emittedLines.has(current)) continue;
5667
5619
  emittedLines.add(current);
5668
- const truncated = truncateGrepLine(lines[current]);
5620
+ const truncated = truncateGrepLine(lines[current] ?? "");
5669
5621
  lineTruncated ||= truncated.truncated;
5670
5622
  const separator = matchedLineSet.has(current) ? ":" : "-";
5671
5623
  output.push(`${relativePath}${separator}${current + 1}${separator} ${truncated.line}`);
@@ -5847,8 +5799,7 @@ function createGrepTool() {
5847
5799
  }
5848
5800
  });
5849
5801
  }
5850
- //#endregion
5851
- //#region src/chat/tools/sandbox/list-dir.ts
5802
+ // src/chat/tools/sandbox/list-dir.ts
5852
5803
  const DEFAULT_LIST_LIMIT = 500;
5853
5804
  /** List workspace directories without forcing the model through shell output. */
5854
5805
  async function listDir(params) {
@@ -5923,8 +5874,7 @@ function createListDirTool() {
5923
5874
  }
5924
5875
  });
5925
5876
  }
5926
- //#endregion
5927
- //#region src/chat/tool-support/text-range-result.ts
5877
+ // src/chat/tool-support/text-range-result.ts
5928
5878
  const DEFAULT_READ_LIMIT = 1e3;
5929
5879
  const MAX_READ_CHARS = 6e4;
5930
5880
  function positiveInteger(value) {
@@ -5998,8 +5948,7 @@ function sliceFileContent(params) {
5998
5948
  function missingFileResult(path) {
5999
5949
  throw new ToolInputError(`File not found: ${path}`);
6000
5950
  }
6001
- //#endregion
6002
- //#region src/chat/tools/sandbox/read-file.ts
5951
+ // src/chat/tools/sandbox/read-file.ts
6003
5952
  /** Create the sandbox read tool definition exposed to the agent. */
6004
5953
  function createReadFileTool() {
6005
5954
  return zodTool({
@@ -6021,8 +5970,7 @@ function createReadFileTool() {
6021
5970
  }
6022
5971
  });
6023
5972
  }
6024
- //#endregion
6025
- //#region src/chat/sandbox/sandbox.ts
5973
+ // src/chat/sandbox/sandbox.ts
6026
5974
  /** Create the safe expected tool error for an unavailable sandbox operation. */
6027
5975
  function createSandboxUnavailableToolError(operation, cause) {
6028
5976
  return new ToolInputError(`The temporary sandbox became unavailable during ${operation}, so the operation did not complete reliably. The next sandbox operation will use a fresh session. It may have produced side effects; retry only if it is safe.`, { cause });
@@ -6064,6 +6012,7 @@ function createSandbox(options) {
6064
6012
  if (!credentialEgress) throw new Error("Sandbox credential egress is not configured");
6065
6013
  const now = Date.now();
6066
6014
  const token = createSandboxEgressCredentialToken({
6015
+ conversationId: options.conversationId,
6067
6016
  credentials: credentialEgress,
6068
6017
  egressId,
6069
6018
  ttlMs: sandboxEgressTokenTtlMs
@@ -6432,8 +6381,7 @@ function createSandbox(options) {
6432
6381
  }
6433
6382
  };
6434
6383
  }
6435
- //#endregion
6436
- //#region src/chat/tools/sandbox/file-uploads.ts
6384
+ // src/chat/tools/sandbox/file-uploads.ts
6437
6385
  /** Maximum single file size accepted by model-facing upload tools. */
6438
6386
  const MAX_SANDBOX_FILE_UPLOAD_BYTES = 10485760;
6439
6387
  /** Sandbox directory for generated files that later tools can consume. */
@@ -6535,8 +6483,7 @@ async function readSandboxFileUpload(workspace, input) {
6535
6483
  path: targetPath
6536
6484
  };
6537
6485
  }
6538
- //#endregion
6539
- //#region src/chat/tools/sandbox/generated-artifacts.ts
6486
+ // src/chat/tools/sandbox/generated-artifacts.ts
6540
6487
  async function fileUploadDataToBuffer(data) {
6541
6488
  if (Buffer.isBuffer(data)) return data;
6542
6489
  if (data instanceof ArrayBuffer) return Buffer.from(data);
@@ -6568,8 +6515,7 @@ async function writeSandboxGeneratedArtifacts(workspace, files) {
6568
6515
  })));
6569
6516
  return artifacts.map((artifact) => artifact.ref);
6570
6517
  }
6571
- //#endregion
6572
- //#region src/chat/tool-support/normalize-result.ts
6518
+ // src/chat/tool-support/normalize-result.ts
6573
6519
  function isToolContent(value) {
6574
6520
  return Array.isArray(value) && value.every((part) => {
6575
6521
  if (!part || typeof part !== "object") return false;
@@ -6710,8 +6656,7 @@ function normalizeToolResult(result, options = {}) {
6710
6656
  details: normalized.details
6711
6657
  };
6712
6658
  }
6713
- //#endregion
6714
- //#region src/chat/agent/sandbox.ts
6659
+ // src/chat/agent/sandbox.ts
6715
6660
  function record(value) {
6716
6661
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
6717
6662
  }
@@ -6778,6 +6723,7 @@ function createAgentSandbox(options) {
6778
6723
  traceContext: options.traceContext,
6779
6724
  tracePropagation: options.tracePropagation,
6780
6725
  egressSignals: options.egressSignals,
6726
+ conversationId: options.conversationId,
6781
6727
  credentialEgress: options.credentialEgress,
6782
6728
  prepare: options.prepareSandbox,
6783
6729
  prepareWorkspace: options.prepareWorkspace,
@@ -6819,8 +6765,7 @@ function createAgentSandbox(options) {
6819
6765
  }
6820
6766
  };
6821
6767
  }
6822
- //#endregion
6823
- //#region src/chat/mcp/errors.ts
6768
+ // src/chat/mcp/errors.ts
6824
6769
  /** Safe failure at an MCP network or OAuth boundary. */
6825
6770
  var McpProviderError = class extends Error {
6826
6771
  phase;
@@ -6885,8 +6830,7 @@ function getMcpAwareTelemetryMessage(error, _privacy) {
6885
6830
  if (error instanceof McpProviderError) return error.message;
6886
6831
  return getMcpAwareErrorMessage(error);
6887
6832
  }
6888
- //#endregion
6889
- //#region src/chat/mcp/client.ts
6833
+ // src/chat/mcp/client.ts
6890
6834
  const MCP_CLIENT_INFO = {
6891
6835
  name: "junior-mcp-client",
6892
6836
  version: "1.0.0"
@@ -6919,8 +6863,6 @@ function isMissingSessionError(error) {
6919
6863
  return error instanceof StreamableHTTPError && (error.code === 404 || /Session not found/i.test(error.message));
6920
6864
  }
6921
6865
  var PluginMcpClient = class {
6922
- plugin;
6923
- options;
6924
6866
  client;
6925
6867
  clientPromise;
6926
6868
  lastAttemptedTransportSessionId;
@@ -6928,6 +6870,8 @@ var PluginMcpClient = class {
6928
6870
  transport;
6929
6871
  listedTools;
6930
6872
  resourceHost;
6873
+ plugin;
6874
+ options;
6931
6875
  constructor(plugin, options = {}) {
6932
6876
  this.plugin = plugin;
6933
6877
  this.options = options;
@@ -7095,8 +7039,7 @@ var PluginMcpClient = class {
7095
7039
  await provider.saveMcpServerSessionId(sessionId);
7096
7040
  }
7097
7041
  };
7098
- //#endregion
7099
- //#region src/chat/mcp/tool-manager.ts
7042
+ // src/chat/mcp/tool-manager.ts
7100
7043
  const MAX_TOOL_RESULT_TOKENS = 1e4;
7101
7044
  const MAX_TOOL_RESULT_BYTES = 32768;
7102
7045
  const CHARS_PER_ESTIMATED_TOKEN = 4;
@@ -7228,13 +7171,13 @@ function extractMcpErrorMessage(result) {
7228
7171
  return "MCP tool call failed";
7229
7172
  }
7230
7173
  var McpToolManager = class {
7231
- options;
7232
7174
  pluginsByProvider = /* @__PURE__ */ new Map();
7233
7175
  activeProviders = /* @__PURE__ */ new Set();
7234
7176
  authorizationPendingProviders = /* @__PURE__ */ new Set();
7235
7177
  clientsByProvider = /* @__PURE__ */ new Map();
7236
7178
  clientPromisesByProvider = /* @__PURE__ */ new Map();
7237
7179
  toolsByProvider = /* @__PURE__ */ new Map();
7180
+ options;
7238
7181
  constructor(plugins, options = {}) {
7239
7182
  this.options = options;
7240
7183
  for (const plugin of plugins) if (plugin.manifest.mcp) this.pluginsByProvider.set(plugin.manifest.name, plugin);
@@ -7474,8 +7417,7 @@ function serializeMcpPayload(payload, privacy, options = {}) {
7474
7417
  if (privacy !== "private") return serializeGenAiAttribute(payload);
7475
7418
  return options.privateMetadata ? serializeGenAiAttribute(toGenAiPayloadMetadata(payload)) : void 0;
7476
7419
  }
7477
- //#endregion
7478
- //#region src/chat/tools/sandbox/bash.ts
7420
+ // src/chat/tools/sandbox/bash.ts
7479
7421
  /** Create the sandbox shell tool definition exposed to the agent. */
7480
7422
  function createBashTool() {
7481
7423
  return zodTool({
@@ -7498,8 +7440,7 @@ function createBashTool() {
7498
7440
  }
7499
7441
  });
7500
7442
  }
7501
- //#endregion
7502
- //#region src/chat/tools/sandbox/image-files.ts
7443
+ // src/chat/tools/sandbox/image-files.ts
7503
7444
  /**
7504
7445
  * Read a sandbox image for a model request. The file signature, not the file
7505
7446
  * name, sets the MIME type.
@@ -7517,8 +7458,7 @@ async function readSandboxImage(path, readFile, maxBytes) {
7517
7458
  mimeType
7518
7459
  };
7519
7460
  }
7520
- //#endregion
7521
- //#region src/chat/tools/web/image-generate.ts
7461
+ // src/chat/tools/web/image-generate.ts
7522
7462
  const MAX_REQUEST_IMAGE_BYTES = 3145728;
7523
7463
  const MAX_SOURCE_IMAGE_BYTES = 26214400;
7524
7464
  const RESIZE_LONGEST_EDGES = [
@@ -7757,8 +7697,7 @@ function createImageGenerateTool(hooks, options, deps = {}) {
7757
7697
  }
7758
7698
  });
7759
7699
  }
7760
- //#endregion
7761
- //#region src/chat/mcp/tool-name.ts
7700
+ // src/chat/mcp/tool-name.ts
7762
7701
  /** Extract the provider from canonical `mcp__<provider>__<tool>` names. */
7763
7702
  function parseMcpProviderFromToolName(toolName) {
7764
7703
  if (!toolName.startsWith("mcp__")) return void 0;
@@ -7766,8 +7705,7 @@ function parseMcpProviderFromToolName(toolName) {
7766
7705
  const delimiterIndex = afterPrefix.indexOf("__");
7767
7706
  return delimiterIndex > 0 ? afterPrefix.slice(0, delimiterIndex) : void 0;
7768
7707
  }
7769
- //#endregion
7770
- //#region src/chat/tools/skill/call-mcp-tool.ts
7708
+ // src/chat/tools/skill/call-mcp-tool.ts
7771
7709
  function resolveMcpArguments(input) {
7772
7710
  const extraKeys = Object.keys(input).filter((key) => key !== "tool_name" && key !== "arguments" && key !== "intent");
7773
7711
  if (extraKeys.length > 0) throw new ToolInputError(`callMcpTool MCP arguments must be nested under arguments, not top-level fields: ${extraKeys.join(", ")}`);
@@ -7847,8 +7785,7 @@ function createCallMcpToolTool(mcpToolManager) {
7847
7785
  }
7848
7786
  });
7849
7787
  }
7850
- //#endregion
7851
- //#region src/chat/tools/skill/load-skill.ts
7788
+ // src/chat/tools/skill/load-skill.ts
7852
7789
  function toLoadedSkill(result, availableSkills) {
7853
7790
  if (typeof result.skill_name !== "string" || typeof result.description !== "string" || typeof result.skill_dir !== "string" || typeof result.instructions !== "string") return null;
7854
7791
  const metadata = availableSkills.find((skill) => skill.name === result.skill_name) ?? null;
@@ -7899,8 +7836,7 @@ function createLoadSkillTool(availableSkills, options) {
7899
7836
  }
7900
7837
  });
7901
7838
  }
7902
- //#endregion
7903
- //#region src/chat/tool-support/skill/mcp-tool-summary.ts
7839
+ // src/chat/tool-support/skill/mcp-tool-summary.ts
7904
7840
  /** Convert a managed MCP tool descriptor into agent-visible search output. */
7905
7841
  function toExposedToolSummary(toolDef) {
7906
7842
  return {
@@ -7923,8 +7859,7 @@ function toActiveMcpCatalogSummaries(toolDefs) {
7923
7859
  available_tool_count: availableToolCount
7924
7860
  })).sort((left, right) => left.provider.localeCompare(right.provider));
7925
7861
  }
7926
- //#endregion
7927
- //#region src/chat/tools/skill/search-mcp-tools.ts
7862
+ // src/chat/tools/skill/search-mcp-tools.ts
7928
7863
  const DEFAULT_MAX_RESULTS$1 = 5;
7929
7864
  const MAX_RESULTS$2 = 20;
7930
7865
  const providerSummarySchema = z.object({
@@ -8073,8 +8008,7 @@ function createSearchMcpToolsTool(mcpToolManager) {
8073
8008
  }
8074
8009
  });
8075
8010
  }
8076
- //#endregion
8077
- //#region src/chat/tools/sandbox/view-image.ts
8011
+ // src/chat/tools/sandbox/view-image.ts
8078
8012
  const MAX_VIEW_IMAGE_BYTES = 5242880;
8079
8013
  const viewImageInputSchema = z.object({ path: z.string().min(1).describe("Path to an image file in the sandbox workspace.") }).strict();
8080
8014
  /** Create a tool that loads a sandbox image into the active model context. */
@@ -8100,8 +8034,7 @@ function createViewImageTool(sandbox, supportsImageInput, deps = {}) {
8100
8034
  }
8101
8035
  });
8102
8036
  }
8103
- //#endregion
8104
- //#region src/chat/tools/runtime/report-progress.ts
8037
+ // src/chat/tools/runtime/report-progress.ts
8105
8038
  /** Create the internal tool the model uses for sparse progress updates. */
8106
8039
  function createReportProgressTool() {
8107
8040
  return zodTool({
@@ -8117,8 +8050,7 @@ function createReportProgressTool() {
8117
8050
  execute: async () => ({})
8118
8051
  });
8119
8052
  }
8120
- //#endregion
8121
- //#region src/chat/tools/runtime/update-plan.ts
8053
+ // src/chat/tools/runtime/update-plan.ts
8122
8054
  const planItemSchema = z.object({
8123
8055
  step: z.string().describe("Task step text."),
8124
8056
  status: z.enum([
@@ -8152,8 +8084,7 @@ function createUpdatePlanTool() {
8152
8084
  }] })
8153
8085
  });
8154
8086
  }
8155
- //#endregion
8156
- //#region src/chat/conversations/sql/subtree.ts
8087
+ // src/chat/conversations/sql/subtree.ts
8157
8088
  /** Columns of the `conversation_subtree` table that `conversationSubtree` returns. */
8158
8089
  const conversationSubtreeColumns = {
8159
8090
  conversationId: sql`conversation_subtree.conversation_id`,
@@ -8185,8 +8116,7 @@ function conversationSubtree(conversationIds) {
8185
8116
  select scope_conversation_id, conversation_id from tree
8186
8117
  ) conversation_subtree`;
8187
8118
  }
8188
- //#endregion
8189
- //#region src/chat/agent-invocations/types.ts
8119
+ // src/chat/agent-invocations/types.ts
8190
8120
  const exactStringSchema = z.string().min(1).refine((value) => value === value.trim());
8191
8121
  const agentNameSchema = exactStringSchema.max(64);
8192
8122
  /** `messageAgent` target for the parent of a child agent. */
@@ -8258,8 +8188,7 @@ const CHILD_AGENT_RESULTS = [
8258
8188
  "blocked",
8259
8189
  "failed"
8260
8190
  ];
8261
- //#endregion
8262
- //#region src/chat/agent-invocations/errors.ts
8191
+ // src/chat/agent-invocations/errors.ts
8263
8192
  /** A child agent already uses this name in the parent Conversation. */
8264
8193
  var AgentNameInUseError = class extends Error {
8265
8194
  constructor(name) {
@@ -8288,8 +8217,7 @@ var AgentMessageTargetError = class extends Error {
8288
8217
  this.name = "AgentMessageTargetError";
8289
8218
  }
8290
8219
  };
8291
- //#endregion
8292
- //#region src/chat/agent-invocations/store.ts
8220
+ // src/chat/agent-invocations/store.ts
8293
8221
  const CREATE_LOCK_PREFIX = "junior:agent_invocation:create";
8294
8222
  /**
8295
8223
  * Return the SQL lock that one parent Conversation takes to start, message,
@@ -8715,8 +8643,7 @@ async function markAgentInvocationSteered(invocationId, nowMs = Date.now()) {
8715
8643
  function isTerminalAgentInvocation(invocation) {
8716
8644
  return TERMINAL_AGENT_INVOCATION_STATUSES.includes(invocation.status);
8717
8645
  }
8718
- //#endregion
8719
- //#region src/chat/agent-invocations/list.ts
8646
+ // src/chat/agent-invocations/list.ts
8720
8647
  function isChildAgentResult(status) {
8721
8648
  return CHILD_AGENT_RESULTS.includes(status);
8722
8649
  }
@@ -8808,8 +8735,7 @@ async function listAgentRelatives(input) {
8808
8735
  siblings: family.filter((agent) => agent.childConversationId !== conversationId)
8809
8736
  };
8810
8737
  }
8811
- //#endregion
8812
- //#region src/chat/tools/runtime/list-agents.ts
8738
+ // src/chat/tools/runtime/list-agents.ts
8813
8739
  const TASK_MAX_LENGTH = 1e3;
8814
8740
  const ERROR_MAX_LENGTH = 500;
8815
8741
  /** How a listed agent relates to the conversation that lists it. */
@@ -8904,8 +8830,7 @@ function createListAgentsTool(context) {
8904
8830
  }
8905
8831
  });
8906
8832
  }
8907
- //#endregion
8908
- //#region src/chat/tools/runtime/message-agent.ts
8833
+ // src/chat/tools/runtime/message-agent.ts
8909
8834
  /** Bound the text of one message so a loop cannot fill a mailbox quickly. */
8910
8835
  const MESSAGE_AGENT_TEXT_MAX_LENGTH = 8e3;
8911
8836
  const messageAgentOutputSchema = juniorToolOutputSchema.extend({
@@ -8951,8 +8876,7 @@ function createMessageAgentTool(messageAgent) {
8951
8876
  }
8952
8877
  });
8953
8878
  }
8954
- //#endregion
8955
- //#region src/chat/tools/runtime/spawn-agent.ts
8879
+ // src/chat/tools/runtime/spawn-agent.ts
8956
8880
  const spawnAgentOutputSchema = juniorToolOutputSchema.extend({ conversation_id: z.string().min(1).describe("Child conversation ID. Pass it to searchConversationEvents to read the child's history.") });
8957
8881
  /** Create the asynchronous child-agent tool for one parent run. */
8958
8882
  function createSpawnAgentTool(spawnAgent, profileControl) {
@@ -9009,8 +8933,7 @@ function createSpawnAgentTool(spawnAgent, profileControl) {
9009
8933
  }
9010
8934
  });
9011
8935
  }
9012
- //#endregion
9013
- //#region src/chat/agent-invocations/markers.ts
8936
+ // src/chat/agent-invocations/markers.ts
9014
8937
  /**
9015
8938
  * Dashboard records for agent invocations. The parent Conversation gets one
9016
8939
  * `subagent_started` and one `subagent_ended` event for each agent invocation.
@@ -9093,8 +9016,7 @@ async function recordSubagentEnded(invocation) {
9093
9016
  createdAtMs: invocation.terminalAtMs
9094
9017
  }]);
9095
9018
  }
9096
- //#endregion
9097
- //#region src/chat/agent-invocations/stop.ts
9019
+ // src/chat/agent-invocations/stop.ts
9098
9020
  /**
9099
9021
  * Stop one child agent of a parent Conversation and every child agent below
9100
9022
  * it. The parent gets no result. SQL stops the work first. Then each
@@ -9203,8 +9125,7 @@ async function stopLockedAgentInvocationTree(conversationId, nowMs) {
9203
9125
  stopped: stopped.map(invocationFromRow).filter(isTerminalAgentInvocation)
9204
9126
  };
9205
9127
  }
9206
- //#endregion
9207
- //#region src/chat/tools/runtime/stop-agent.ts
9128
+ // src/chat/tools/runtime/stop-agent.ts
9208
9129
  const stopAgentOutputSchema = juniorToolOutputSchema.extend({
9209
9130
  conversation_id: z.string().min(1).describe("Stopped child conversation ID"),
9210
9131
  stopped: z.boolean().describe("True when work was stopped. False when the child agent had already stopped.")
@@ -9234,8 +9155,7 @@ function createStopAgentTool(conversationId) {
9234
9155
  }
9235
9156
  });
9236
9157
  }
9237
- //#endregion
9238
- //#region src/chat/tools/runtime/finish-automation-run.ts
9158
+ // src/chat/tools/runtime/finish-automation-run.ts
9239
9159
  const RESULT_GUIDANCE = ["Use `no_action` when the run worked and nothing should be posted, such as when a condition in the instruction is not met, or when a temporary failure stopped the work.", "Use `misconfigured` when the run cannot do its job until its creator changes the automation: a provider, tool, account, or access that the job needs is missing, a target no longer exists, or the instruction cannot be done. Do not use it for a temporary failure or a condition that is not met."].join(" ");
9240
9160
  /** Create the tool that ends one Automation run with a declared result. */
9241
9161
  function createFinishAutomationRunTool(options) {
@@ -9251,7 +9171,7 @@ function createFinishAutomationRunTool(options) {
9251
9171
  openWorldHint: false,
9252
9172
  readOnlyHint: false
9253
9173
  },
9254
- description: options.sendsMessage ? `End this automation run. Use \`send_message\` with the finished reminder, digest, alert, or answer; the runtime posts it to the stored destinations. ${RESULT_GUIDANCE}` : `End this automation run. This automation posts nothing. ${RESULT_GUIDANCE}`,
9174
+ description: options.sendsMessage ? `End this automation run. Use \`send_message\` with the finished reminder, digest, alert, or answer; the runtime posts it to the stored destinations. This is the only way that the run posts, so a missing Slack posting tool does not make the run \`misconfigured\`. ${RESULT_GUIDANCE}` : `End this automation run. This automation posts nothing. ${RESULT_GUIDANCE}`,
9255
9175
  inputSchema: z.object({
9256
9176
  result: z.enum(results),
9257
9177
  ...options.sendsMessage ? { message: z.string().optional().describe("Required for send_message. The text to post.") } : void 0,
@@ -9272,8 +9192,7 @@ function createFinishAutomationRunTool(options) {
9272
9192
  }
9273
9193
  });
9274
9194
  }
9275
- //#endregion
9276
- //#region src/chat/tools/runtime/report-blocked.ts
9195
+ // src/chat/tools/runtime/report-blocked.ts
9277
9196
  /** Create the tool that ends a child agent run as blocked. */
9278
9197
  function createReportBlockedTool() {
9279
9198
  return zodTool({
@@ -9289,8 +9208,7 @@ function createReportBlockedTool() {
9289
9208
  execute: async (input) => ({ missing: input.missing })
9290
9209
  });
9291
9210
  }
9292
- //#endregion
9293
- //#region src/chat/events/owned-watches.ts
9211
+ // src/chat/events/owned-watches.ts
9294
9212
  /**
9295
9213
  * Watch ownership for the watch tools. A Conversation owns its own watches and
9296
9214
  * the watches of every child agent below it, at any depth. A child agent still
@@ -9336,8 +9254,7 @@ async function stopOwnedWatch(input) {
9336
9254
  });
9337
9255
  return stopped;
9338
9256
  }
9339
- //#endregion
9340
- //#region src/chat/tools/list-watches.ts
9257
+ // src/chat/tools/list-watches.ts
9341
9258
  const listedResourceWatchSchema = z.object({
9342
9259
  id: z.string().min(1),
9343
9260
  label: z.string().min(1),
@@ -9390,8 +9307,7 @@ function createListWatchesTool(context) {
9390
9307
  }
9391
9308
  });
9392
9309
  }
9393
- //#endregion
9394
- //#region src/chat/tools/search-event-types.ts
9310
+ // src/chat/tools/search-event-types.ts
9395
9311
  const DEFAULT_SEARCH_RESULTS = 10;
9396
9312
  const MAX_SEARCH_RESULTS = 20;
9397
9313
  const searchedResourceTypeSchema = z.object({
@@ -9471,8 +9387,7 @@ function createSearchEventTypesTool(catalog) {
9471
9387
  }
9472
9388
  });
9473
9389
  }
9474
- //#endregion
9475
- //#region src/chat/tools/stop-watches.ts
9390
+ // src/chat/tools/stop-watches.ts
9476
9391
  const resultDataSchema$1 = z.object({
9477
9392
  watching_status: z.literal("stopped"),
9478
9393
  stoppedIds: z.array(z.string().min(1))
@@ -9528,8 +9443,7 @@ function createStopWatchingResourcesTool(context) {
9528
9443
  }
9529
9444
  });
9530
9445
  }
9531
- //#endregion
9532
- //#region src/chat/tools/watch-timer.ts
9446
+ // src/chat/tools/watch-timer.ts
9533
9447
  /** Create one heartbeat-backed Watch in the current Conversation. */
9534
9448
  function createWatchTimerTool(context) {
9535
9449
  return zodTool({
@@ -9564,8 +9478,7 @@ function createWatchTimerTool(context) {
9564
9478
  }
9565
9479
  });
9566
9480
  }
9567
- //#endregion
9568
- //#region src/chat/tools/watch-events.ts
9481
+ // src/chat/tools/watch-events.ts
9569
9482
  function inputSchema(catalog) {
9570
9483
  return z.object({
9571
9484
  identifier: z.string().trim().min(1).describe("Plugin-defined resource identifier."),
@@ -9670,8 +9583,7 @@ function createWatchEventsTool(context, catalog) {
9670
9583
  }
9671
9584
  });
9672
9585
  }
9673
- //#endregion
9674
- //#region src/chat/tools/events.ts
9586
+ // src/chat/tools/events.ts
9675
9587
  /** Build the complete resource-watch tool set for this runtime context. */
9676
9588
  function createEventTools(context, catalog) {
9677
9589
  const enabled = hasEventCatalogEntries(catalog);
@@ -9685,8 +9597,7 @@ function createEventTools(context, catalog) {
9685
9597
  stopWatchingResources: createStopWatchingResourcesTool(context)
9686
9598
  };
9687
9599
  }
9688
- //#endregion
9689
- //#region src/chat/automations/requester-mention.ts
9600
+ // src/chat/automations/requester-mention.ts
9690
9601
  function namesPerson(text, name) {
9691
9602
  const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9692
9603
  return new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, "iu").test(text);
@@ -9703,8 +9614,7 @@ function requireRequesterMention(instruction, actor) {
9703
9614
  if (instruction.includes(mention)) return;
9704
9615
  if (namesPerson(instruction, actor.fullName)) throw new ToolInputError(`The instruction names ${actor.fullName} without a Slack mention. Write ${mention} for this person.`);
9705
9616
  }
9706
- //#endregion
9707
- //#region src/chat/task-outcomes.ts
9617
+ // src/chat/task-outcomes.ts
9708
9618
  /** Resolve explicit message outcomes to the Slack Destinations stored on an Automation. */
9709
9619
  async function resolveTaskOutcomes(outcomes, currentDestination, creatorSlackUserId) {
9710
9620
  if (outcomes === void 0) return [];
@@ -9746,8 +9656,7 @@ function moveTaskOutcomes(outcomes, currentDestination, nextDestination) {
9746
9656
  destination: nextDestination
9747
9657
  } : outcome);
9748
9658
  }
9749
- //#endregion
9750
- //#region src/chat/event-automations/tool-support.ts
9659
+ // src/chat/event-automations/tool-support.ts
9751
9660
  const compactEventAutomationResultSchema = z.object({
9752
9661
  id: z.string().min(1),
9753
9662
  status: z.enum([
@@ -9910,8 +9819,7 @@ async function eventAutomationToolResult(conversationId, task, catalog, requeste
9910
9819
  }])
9911
9820
  };
9912
9821
  }
9913
- //#endregion
9914
- //#region src/chat/tools/create-event-automation.ts
9822
+ // src/chat/tools/create-event-automation.ts
9915
9823
  /** Build a retry-stable automation id scoped to actor, destination, and tool call. */
9916
9824
  function buildEventAutomationId(args) {
9917
9825
  const toolCallId = args.toolCallId?.trim();
@@ -10003,8 +9911,7 @@ function createEventAutomationTool(context, catalog) {
10003
9911
  }
10004
9912
  });
10005
9913
  }
10006
- //#endregion
10007
- //#region src/chat/tools/delete-event-automation.ts
9914
+ // src/chat/tools/delete-event-automation.ts
10008
9915
  /** Create the core tool that deletes an event automation. */
10009
9916
  function createDeleteEventAutomationTool(context, catalog) {
10010
9917
  return zodTool({
@@ -10039,8 +9946,7 @@ function createDeleteEventAutomationTool(context, catalog) {
10039
9946
  }
10040
9947
  });
10041
9948
  }
10042
- //#endregion
10043
- //#region src/chat/tools/list-event-automations.ts
9949
+ // src/chat/tools/list-event-automations.ts
10044
9950
  const MAX_LISTED_EVENT_AUTOMATIONS = 50;
10045
9951
  /** Create the core tool that lists event automations for this destination. */
10046
9952
  function createListEventAutomationsTool(context, catalog) {
@@ -10065,8 +9971,7 @@ function createListEventAutomationsTool(context, catalog) {
10065
9971
  }
10066
9972
  });
10067
9973
  }
10068
- //#endregion
10069
- //#region src/chat/automations/edit-rules.ts
9974
+ // src/chat/automations/edit-rules.ts
10070
9975
  /** Shared edit rules. Transport access checks run before these rules. */
10071
9976
  var AutomationEditError = class extends ToolInputError {
10072
9977
  field;
@@ -10101,8 +10006,7 @@ async function editAutomationFields(current, input, isCreator, changesExecution)
10101
10006
  outcomes
10102
10007
  };
10103
10008
  }
10104
- //#endregion
10105
- //#region src/chat/event-automations/edit.ts
10009
+ // src/chat/event-automations/edit.ts
10106
10010
  function changesEventAutomationTrigger(current, next) {
10107
10011
  const currentEvents = [...current.events].sort();
10108
10012
  const nextEvents = [...next.events].sort();
@@ -10142,8 +10046,7 @@ async function editEventAutomation(current, input, isCreator, catalog) {
10142
10046
  throw error;
10143
10047
  }
10144
10048
  }
10145
- //#endregion
10146
- //#region src/chat/tools/update-event-automation.ts
10049
+ // src/chat/tools/update-event-automation.ts
10147
10050
  /** Create the core tool that updates an event automation. */
10148
10051
  function createUpdateEventAutomationTool(context, catalog) {
10149
10052
  return zodTool({
@@ -10207,8 +10110,7 @@ function createUpdateEventAutomationTool(context, catalog) {
10207
10110
  }
10208
10111
  });
10209
10112
  }
10210
- //#endregion
10211
- //#region src/chat/tools/event-automations.ts
10113
+ // src/chat/tools/event-automations.ts
10212
10114
  /** Build event automation tools for a Conversation with a Slack Location. */
10213
10115
  function createEventAutomationTools(context, catalog) {
10214
10116
  if (!getSlackToolContext(context)) return {};
@@ -10219,8 +10121,7 @@ function createEventAutomationTools(context, catalog) {
10219
10121
  deleteEventAutomation: createDeleteEventAutomationTool(context, catalog)
10220
10122
  }, slackMessageTurnDisabledReason(context));
10221
10123
  }
10222
- //#endregion
10223
- //#region src/chat/scheduled-automations/telemetry.ts
10124
+ // src/chat/scheduled-automations/telemetry.ts
10224
10125
  /** Safe structured telemetry attributes for scheduled-automation lifecycle events. */
10225
10126
  /** Correlation attributes shared by scheduled-automation create and run events. */
10226
10127
  function scheduledAutomationAttributes(task, extras = {}) {
@@ -10255,8 +10156,7 @@ function scheduledAutomationRunAttributes(task, run, extras = {}) {
10255
10156
  function logScheduledAutomationRunSkipped(task, run, extras = {}) {
10256
10157
  logInfo("scheduled_automation.run.skipped", scheduledAutomationRunAttributes(task, run, extras));
10257
10158
  }
10258
- //#endregion
10259
- //#region src/chat/scheduled-automations/identity.ts
10159
+ // src/chat/scheduled-automations/identity.ts
10260
10160
  const SLACK_USER_ID_PATTERN = /^[UW][A-Z0-9]{5,}$/;
10261
10161
  function clean(value) {
10262
10162
  const normalized = value?.trim();
@@ -10283,8 +10183,7 @@ function sanitizeScheduledAutomationPrincipal(principal) {
10283
10183
  ...userName ? { userName } : void 0
10284
10184
  };
10285
10185
  }
10286
- //#endregion
10287
- //#region src/chat/scheduled-automations/tool-support.ts
10186
+ // src/chat/scheduled-automations/tool-support.ts
10288
10187
  const TASK_ID_PREFIX = "sched";
10289
10188
  const compactTaskResultSchema = z.object({
10290
10189
  id: z.string(),
@@ -10502,8 +10401,7 @@ function buildTaskId(args) {
10502
10401
  function normalizeStatus(value) {
10503
10402
  if (value === "active" || value === "blocked") return value;
10504
10403
  }
10505
- //#endregion
10506
- //#region src/chat/scheduled-automations/tools/create.ts
10404
+ // src/chat/scheduled-automations/tools/create.ts
10507
10405
  /** Create a tool that stores a scheduled automation for the active Slack context. */
10508
10406
  function createSlackScheduleCreateAutomationTool(context) {
10509
10407
  return zodTool({
@@ -10601,8 +10499,7 @@ function createSlackScheduleCreateAutomationTool(context) {
10601
10499
  }
10602
10500
  });
10603
10501
  }
10604
- //#endregion
10605
- //#region src/chat/scheduled-automations/tools/delete.ts
10502
+ // src/chat/scheduled-automations/tools/delete.ts
10606
10503
  /** Create a tool that removes a scheduled automation from the active Slack conversation. */
10607
10504
  function createSlackScheduleDeleteAutomationTool(context) {
10608
10505
  return zodTool({
@@ -10645,8 +10542,7 @@ function createSlackScheduleDeleteAutomationTool(context) {
10645
10542
  }
10646
10543
  });
10647
10544
  }
10648
- //#endregion
10649
- //#region src/chat/slack/id-param.ts
10545
+ // src/chat/slack/id-param.ts
10650
10546
  /** Define a model-facing Slack channel ID parameter. */
10651
10547
  function slackChannelIdParam(description) {
10652
10548
  return z.string().min(1).describe(description);
@@ -10679,8 +10575,7 @@ function parseRequiredSlackUserIdParam(field, value) {
10679
10575
  error: `Invalid \`${field}\` Slack user ID. Use a Slack user ID like \`U123\` or \`W123\`.`
10680
10576
  };
10681
10577
  }
10682
- //#endregion
10683
- //#region src/chat/scheduled-automations/tools/list.ts
10578
+ // src/chat/scheduled-automations/tools/list.ts
10684
10579
  function taskMatchesQuery(task, query) {
10685
10580
  const normalized = query.toLowerCase();
10686
10581
  return [
@@ -10735,8 +10630,7 @@ function createSlackScheduleListAutomationsTool(context) {
10735
10630
  }
10736
10631
  });
10737
10632
  }
10738
- //#endregion
10739
- //#region src/chat/scheduled-automations/tools/run-now.ts
10633
+ // src/chat/scheduled-automations/tools/run-now.ts
10740
10634
  /** Create a tool that marks an existing scheduled automation due immediately. */
10741
10635
  function createSlackScheduleRunAutomationNowTool(context) {
10742
10636
  return zodTool({
@@ -10768,8 +10662,7 @@ function createSlackScheduleRunAutomationNowTool(context) {
10768
10662
  }
10769
10663
  });
10770
10664
  }
10771
- //#endregion
10772
- //#region src/chat/scheduled-automations/edit.ts
10665
+ // src/chat/scheduled-automations/edit.ts
10773
10666
  /** Build an edit without restarting completed work or changing creator identity. */
10774
10667
  async function editScheduledAutomation(current, input, isCreator, nowMs) {
10775
10668
  if (current.status === "completed" || current.status === "deleted") throw new AutomationEditError("Completed scheduled automations cannot be updated. Create a new automation instead.");
@@ -10802,8 +10695,7 @@ async function editScheduledAutomation(current, input, isCreator, nowMs) {
10802
10695
  status
10803
10696
  };
10804
10697
  }
10805
- //#endregion
10806
- //#region src/chat/scheduled-automations/tools/update.ts
10698
+ // src/chat/scheduled-automations/tools/update.ts
10807
10699
  /** Create a tool that edits a scheduled automation, including moving it here. */
10808
10700
  function createSlackScheduleUpdateAutomationTool(context) {
10809
10701
  return zodTool({
@@ -10873,8 +10765,7 @@ function createSlackScheduleUpdateAutomationTool(context) {
10873
10765
  }
10874
10766
  });
10875
10767
  }
10876
- //#endregion
10877
- //#region src/chat/tools/scheduled-automations.ts
10768
+ // src/chat/tools/scheduled-automations.ts
10878
10769
  function scheduledAutomationToolContext(context) {
10879
10770
  const slackMessageTurn = isSlackMessageTurn(context) ? {
10880
10771
  actor: context.actor,
@@ -10899,8 +10790,7 @@ function createScheduledAutomationTools(context) {
10899
10790
  slackScheduleRunAutomationNow: createSlackScheduleRunAutomationNowTool(taskContext)
10900
10791
  }, slackMessageTurnDisabledReason(context));
10901
10792
  }
10902
- //#endregion
10903
- //#region src/chat/slack/channel.ts
10793
+ // src/chat/slack/channel.ts
10904
10794
  const replySubtypeSchema = z.object({ subtype: z.string().optional() });
10905
10795
  /** List channel history using Slack-native, pre-validated timestamp bounds. */
10906
10796
  async function listChannelMessages(input) {
@@ -10989,8 +10879,7 @@ async function joinPublicChannel(channelId) {
10989
10879
  idempotent: true
10990
10880
  });
10991
10881
  }
10992
- //#endregion
10993
- //#region src/chat/slack/tool-support/channel-access.ts
10882
+ // src/chat/slack/tool-support/channel-access.ts
10994
10883
  const DENIED_PRIVATE = "Cannot read this Slack conversation because it is private. Only the current conversation or public channels are readable.";
10995
10884
  const DENIED_NOT_FOUND = "Cannot read this Slack conversation because the channel was not found or the bot cannot see it.";
10996
10885
  const DENIED_NOT_IN_CHANNEL = "Cannot read this Slack conversation because the bot is not in the channel.";
@@ -11113,8 +11002,7 @@ async function resolveOptionalSlackChannelRef(input) {
11113
11002
  if (input.defaultChannelId) return { channelId: input.defaultChannelId };
11114
11003
  throw new ToolInputError("Provide `channel_id`, or use this tool in an active Slack channel context.");
11115
11004
  }
11116
- //#endregion
11117
- //#region src/chat/slack/tools/channel-join.ts
11005
+ // src/chat/slack/tools/channel-join.ts
11118
11006
  /** Create a tool that joins one public Slack channel. */
11119
11007
  function createSlackChannelJoinTool(context) {
11120
11008
  return zodTool({
@@ -11163,8 +11051,7 @@ function createSlackChannelJoinTool(context) {
11163
11051
  }
11164
11052
  });
11165
11053
  }
11166
- //#endregion
11167
- //#region src/chat/slack/context.ts
11054
+ // src/chat/slack/context.ts
11168
11055
  function toTrimmedSlackString(value) {
11169
11056
  return toOptionalString(value)?.trim() || void 0;
11170
11057
  }
@@ -11230,8 +11117,7 @@ function resolveSlackChannelIdFromMessage(message) {
11230
11117
  }
11231
11118
  return resolveSlackChannelIdFromThreadId(toTrimmedSlackString(message.threadId));
11232
11119
  }
11233
- //#endregion
11234
- //#region src/chat/slack/timestamp-param.ts
11120
+ // src/chat/slack/timestamp-param.ts
11235
11121
  /** Define a model-facing Slack timestamp, normalizing numeric model args to strings. */
11236
11122
  function slackTimestampParam(description) {
11237
11123
  return z.preprocess((value) => typeof value === "number" && Number.isFinite(value) ? String(value) : value, z.string().min(1)).describe(description);
@@ -11264,8 +11150,7 @@ function parseRequiredSlackTimestampParam(field, value) {
11264
11150
  error: `Invalid \`${field}\` Slack timestamp. Use a numeric Slack ts like \`1712345678.123456\`.`
11265
11151
  };
11266
11152
  }
11267
- //#endregion
11268
- //#region src/chat/slack/tools/channel-list-messages.ts
11153
+ // src/chat/slack/tools/channel-list-messages.ts
11269
11154
  const booleanInput$1 = (description) => z.preprocess((value) => value === "true" ? true : value === "false" ? false : value, z.boolean()).describe(description);
11270
11155
  /**
11271
11156
  * Accept numeric Slack ts bounds and recover matching
@@ -11379,8 +11264,7 @@ function createSlackChannelListMessagesTool(context) {
11379
11264
  }
11380
11265
  });
11381
11266
  }
11382
- //#endregion
11383
- //#region src/chat/slack/tools/conversation-brief-search.ts
11267
+ // src/chat/slack/tools/conversation-brief-search.ts
11384
11268
  /** Create Slack-owned filtering and match details for Brief search. */
11385
11269
  function createSlackConversationBriefSearchPort(teamId) {
11386
11270
  return {
@@ -11407,15 +11291,13 @@ function createSlackConversationBriefSearchPort(teamId) {
11407
11291
  }
11408
11292
  };
11409
11293
  }
11410
- //#endregion
11411
- //#region src/chat/conversations/tool-source.ts
11294
+ // src/chat/conversations/tool-source.ts
11412
11295
  /** Deferred tool catalog source for retained Junior conversations. */
11413
11296
  const CONVERSATIONS_TOOL_SOURCE = {
11414
11297
  id: "conversations",
11415
11298
  description: "Search messages and events in retained Junior conversations."
11416
11299
  };
11417
- //#endregion
11418
- //#region src/chat/slack/tools/conversation-message-search.ts
11300
+ // src/chat/slack/tools/conversation-message-search.ts
11419
11301
  const DEFAULT_LIMIT$3 = 20;
11420
11302
  const MAX_LIMIT$2 = 50;
11421
11303
  const conversationMessageSearchOutputSchema = juniorToolOutputSchema.extend({
@@ -11529,8 +11411,7 @@ function createSlackConversationMessageSearchTool(scope, currentConversationId)
11529
11411
  }
11530
11412
  });
11531
11413
  }
11532
- //#endregion
11533
- //#region src/chat/slack/tools/public-search.ts
11414
+ // src/chat/slack/tools/public-search.ts
11534
11415
  const DEFAULT_LIMIT$2 = 10;
11535
11416
  const DEFAULT_CONTENT_TYPES = ["messages"];
11536
11417
  const CONTENT_TYPES = [
@@ -11828,8 +11709,7 @@ function createSlackPublicSearchTool(actionToken) {
11828
11709
  }
11829
11710
  });
11830
11711
  }
11831
- //#endregion
11832
- //#region src/chat/tools/idempotency.ts
11712
+ // src/chat/tools/idempotency.ts
11833
11713
  function stableSerialize(value) {
11834
11714
  if (Array.isArray(value)) return `[${value.map((entry) => stableSerialize(entry)).join(",")}]`;
11835
11715
  if (value && typeof value === "object") return `{${Object.entries(value).sort((a, b) => a[0].localeCompare(b[0])).map(([key, entry]) => `${JSON.stringify(key)}:${stableSerialize(entry)}`).join(",")}}`;
@@ -11839,8 +11719,7 @@ function stableSerialize(value) {
11839
11719
  function createOperationKey(toolName, input) {
11840
11720
  return `${toolName}:${stableSerialize(input)}`;
11841
11721
  }
11842
- //#endregion
11843
- //#region src/chat/slack/tools/message-add-reaction.ts
11722
+ // src/chat/slack/tools/message-add-reaction.ts
11844
11723
  /** Create the tool that reacts to the current inbound Slack message. */
11845
11724
  function createSlackMessageAddReactionTool(context, state) {
11846
11725
  return zodTool({
@@ -11885,8 +11764,7 @@ function createSlackMessageAddReactionTool(context, state) {
11885
11764
  }
11886
11765
  });
11887
11766
  }
11888
- //#endregion
11889
- //#region src/chat/attachments/store.ts
11767
+ // src/chat/attachments/store.ts
11890
11768
  const DAY_MS = 864e5;
11891
11769
  const ATTACHMENT_GC_BATCH_LIMIT = 200;
11892
11770
  /** Time that Junior keeps attachment bytes after the file is stored. */
@@ -12177,8 +12055,7 @@ async function collectAttachmentGarbage(args) {
12177
12055
  if (stillEligible.length === 0) return { deleted: 0 };
12178
12056
  return { deleted: (await args.db.db().delete(juniorAttachments).where(inArray(juniorAttachments.id, stillEligible.map((row) => row.id))).returning({ id: juniorAttachments.id })).length };
12179
12057
  }
12180
- //#endregion
12181
- //#region src/chat/tools/send-files.ts
12058
+ // src/chat/tools/send-files.ts
12182
12059
  const sendFilesResultSchema = juniorToolOutputSchema.extend({
12183
12060
  deduplicated: z.boolean().optional(),
12184
12061
  attachment_refs: z.array(z.object({
@@ -12262,8 +12139,7 @@ function createSendFilesTool(state, materializeFile, output) {
12262
12139
  }
12263
12140
  });
12264
12141
  }
12265
- //#endregion
12266
- //#region src/chat/slack/tools/send-files.ts
12142
+ // src/chat/slack/tools/send-files.ts
12267
12143
  /** Deliver files to the active Slack Location and retain Conversation attachments. */
12268
12144
  function createSlackSendFilesTool(context, state, materializeFile, attachments) {
12269
12145
  const channelId = context.locationChannelId;
@@ -12286,8 +12162,7 @@ function createSlackSendFilesTool(context, state, materializeFile, attachments)
12286
12162
  }
12287
12163
  });
12288
12164
  }
12289
- //#endregion
12290
- //#region src/chat/slack/canvas-references.ts
12165
+ // src/chat/slack/canvas-references.ts
12291
12166
  const SLACK_FILE_ID_PATTERN = /^F[A-Z0-9]{4,}$/i;
12292
12167
  const SLACK_CANVAS_PATH_PATTERN = /^\/(?:docs|canvas|files)\/(?:T[A-Z0-9]+\/)?(?:U[A-Z0-9]+\/)?(F[A-Z0-9]{4,})(?:\/|$)/i;
12293
12168
  function isSlackHost(hostname) {
@@ -12311,8 +12186,7 @@ function extractCanvasId(input) {
12311
12186
  return;
12312
12187
  }
12313
12188
  }
12314
- //#endregion
12315
- //#region src/chat/slack/tool-support/canvas/markdown.ts
12189
+ // src/chat/slack/tool-support/canvas/markdown.ts
12316
12190
  function getListType(marker) {
12317
12191
  return /^\d/.test(marker) ? "numbered" : "bullet";
12318
12192
  }
@@ -12440,8 +12314,7 @@ function normalizeCanvasMarkdown(markdown) {
12440
12314
  unwrappedBlockquoteCount
12441
12315
  };
12442
12316
  }
12443
- //#endregion
12444
- //#region src/chat/slack/tool-support/canvas/api.ts
12317
+ // src/chat/slack/tool-support/canvas/api.ts
12445
12318
  /**
12446
12319
  * Create a standalone Slack canvas owned by the bot and best-effort grant write
12447
12320
  * access to the active channel. Standalone canvases (`canvases.create`) are not
@@ -12570,8 +12443,7 @@ async function readCanvas(canvasIdOrUrl) {
12570
12443
  byteLength: buffer.byteLength
12571
12444
  };
12572
12445
  }
12573
- //#endregion
12574
- //#region src/chat/slack/tools/canvas/create.ts
12446
+ // src/chat/slack/tools/canvas/create.ts
12575
12447
  /** Create a tool that provisions a new Slack canvas in the active channel. */
12576
12448
  function createSlackCanvasCreateTool(context, state) {
12577
12449
  return zodTool({
@@ -12622,8 +12494,7 @@ function createSlackCanvasCreateTool(context, state) {
12622
12494
  }
12623
12495
  });
12624
12496
  }
12625
- //#endregion
12626
- //#region src/chat/slack/tool-support/canvas/context.ts
12497
+ // src/chat/slack/tool-support/canvas/context.ts
12627
12498
  /** Model-facing Slack canvas ID or docs URL parameter. */
12628
12499
  const slackCanvasRefParam = z.string().min(1).describe("Slack canvas/file ID or canvas/docs URL.");
12629
12500
  /** Resolve model-provided canvas references before Slack API calls. */
@@ -12638,8 +12509,7 @@ function resolveCanvasTarget(canvas) {
12638
12509
  canvasId
12639
12510
  };
12640
12511
  }
12641
- //#endregion
12642
- //#region src/chat/slack/tools/canvas/edit.ts
12512
+ // src/chat/slack/tools/canvas/edit.ts
12643
12513
  function prepareCanvasEditArguments(input) {
12644
12514
  return prepareTextReplacementArguments(input);
12645
12515
  }
@@ -12709,8 +12579,7 @@ function createSlackCanvasEditTool(state) {
12709
12579
  }
12710
12580
  });
12711
12581
  }
12712
- //#endregion
12713
- //#region src/chat/slack/tools/canvas/read.ts
12582
+ // src/chat/slack/tools/canvas/read.ts
12714
12583
  const slackCanvasReadOutputSchema = juniorToolOutputSchema.extend({
12715
12584
  canvas_id: z.string().optional(),
12716
12585
  title: z.string().optional(),
@@ -12772,8 +12641,7 @@ function createSlackCanvasReadTool() {
12772
12641
  }
12773
12642
  });
12774
12643
  }
12775
- //#endregion
12776
- //#region src/chat/slack/tools/canvas/write.ts
12644
+ // src/chat/slack/tools/canvas/write.ts
12777
12645
  /** Create a tool that deliberately replaces a Slack canvas body. */
12778
12646
  function createSlackCanvasWriteTool(state) {
12779
12647
  return zodTool({
@@ -12816,8 +12684,7 @@ function createSlackCanvasWriteTool(state) {
12816
12684
  }
12817
12685
  });
12818
12686
  }
12819
- //#endregion
12820
- //#region src/chat/slack/tool-support/list/api.ts
12687
+ // src/chat/slack/tool-support/list/api.ts
12821
12688
  function normalizeKey(value) {
12822
12689
  return (value ?? "").toLowerCase().replace(/[^a-z0-9]+/g, "_");
12823
12690
  }
@@ -12976,14 +12843,12 @@ async function updateListItem(input) {
12976
12843
  cells
12977
12844
  }), 3, { action: "slackLists.items.update" });
12978
12845
  }
12979
- //#endregion
12980
- //#region src/chat/slack/tool-support/list/params.ts
12846
+ // src/chat/slack/tool-support/list/params.ts
12981
12847
  /** Model-facing Slack list ID parameter. */
12982
12848
  const slackListIdParam = z.string().min(1).describe("Slack list ID.");
12983
12849
  /** Model-facing Slack list item ID parameter. */
12984
12850
  const slackListItemIdParam = z.string().min(1).describe("Slack list item ID.");
12985
- //#endregion
12986
- //#region src/chat/slack/tools/list/add-items.ts
12851
+ // src/chat/slack/tools/list/add-items.ts
12987
12852
  /** Create a tool that appends items to an explicit Slack list. */
12988
12853
  function createSlackListAddItemsTool(state) {
12989
12854
  return zodTool({
@@ -13031,8 +12896,7 @@ function createSlackListAddItemsTool(state) {
13031
12896
  }
13032
12897
  });
13033
12898
  }
13034
- //#endregion
13035
- //#region src/chat/slack/tools/list/create.ts
12899
+ // src/chat/slack/tools/list/create.ts
13036
12900
  /** Create a tool that provisions a new Slack todo list. */
13037
12901
  function createSlackListCreateTool(state) {
13038
12902
  return zodTool({
@@ -13063,8 +12927,7 @@ function createSlackListCreateTool(state) {
13063
12927
  }
13064
12928
  });
13065
12929
  }
13066
- //#endregion
13067
- //#region src/chat/slack/tools/list/get-items.ts
12930
+ // src/chat/slack/tools/list/get-items.ts
13068
12931
  /** Create a tool that reads items from an explicit Slack list. */
13069
12932
  function createSlackListGetItemsTool() {
13070
12933
  return zodTool({
@@ -13091,8 +12954,7 @@ function createSlackListGetItemsTool() {
13091
12954
  }
13092
12955
  });
13093
12956
  }
13094
- //#endregion
13095
- //#region src/chat/slack/tools/list/update-item.ts
12957
+ // src/chat/slack/tools/list/update-item.ts
13096
12958
  const booleanInput = (description) => z.preprocess((value) => value === "true" ? true : value === "false" ? false : value, z.boolean()).describe(description);
13097
12959
  const updateListItemInputSchema = z.union([z.object({
13098
12960
  list_id: slackListIdParam,
@@ -13147,8 +13009,7 @@ function createSlackListUpdateItemTool(state) {
13147
13009
  }
13148
13010
  });
13149
13011
  }
13150
- //#endregion
13151
- //#region src/chat/slack/tool-support/slack-message-url.ts
13012
+ // src/chat/slack/tool-support/slack-message-url.ts
13152
13013
  /** Parse Slack archive URLs into structured message references. */
13153
13014
  const SLACK_HOST_PATTERN = /^[a-z0-9-]+\.slack(?:-gov)?\.com$/;
13154
13015
  const ARCHIVE_PATH_PATTERN = /^\/archives\/([CDG][A-Z0-9]+)\/p(\d{10})(\d{6})$/;
@@ -13223,8 +13084,7 @@ function parseSlackMessageReference(input) {
13223
13084
  }
13224
13085
  };
13225
13086
  }
13226
- //#endregion
13227
- //#region src/chat/slack/message/blocks.ts
13087
+ // src/chat/slack/message/blocks.ts
13228
13088
  const MAX_BLOCKS = 50;
13229
13089
  const MAX_CHILDREN = 50;
13230
13090
  const MAX_DEPTH = 16;
@@ -13305,8 +13165,7 @@ function renderBlockText(value) {
13305
13165
  const budget = { remainingNodes: MAX_NODES };
13306
13166
  return value.slice(0, MAX_BLOCKS).flatMap((block) => parseElement(block, budget, 0)).join("\n");
13307
13167
  }
13308
- //#endregion
13309
- //#region src/chat/slack/message/attachments.ts
13168
+ // src/chat/slack/message/attachments.ts
13310
13169
  const MAX_ATTACHMENTS = 10;
13311
13170
  const MAX_FIELDS_PER_ATTACHMENT = 20;
13312
13171
  const MAX_FIELD_CHARS = 1e3;
@@ -13409,8 +13268,7 @@ function renderAttachment(raw) {
13409
13268
  function renderAttachmentText(input) {
13410
13269
  return getAttachmentPayload(input).slice(0, MAX_ATTACHMENTS).map(renderAttachment).filter((line) => line.length > 0).map((line) => `[attachment] ${line}`).join("\n").slice(0, MAX_ATTACHMENT_TEXT_CHARS);
13411
13270
  }
13412
- //#endregion
13413
- //#region src/chat/slack/tools/thread-read.ts
13271
+ // src/chat/slack/tools/thread-read.ts
13414
13272
  const MAX_THREAD_READ_CHARS = 4e4;
13415
13273
  /**
13416
13274
  * Combine top-level `files` with files nested inside `attachments`
@@ -13606,8 +13464,7 @@ function createSlackThreadReadTool(context, attachmentDeps) {
13606
13464
  }
13607
13465
  });
13608
13466
  }
13609
- //#endregion
13610
- //#region src/chat/slack/users.ts
13467
+ // src/chat/slack/users.ts
13611
13468
  const profileFieldsSchema = z.object({ fields: z.record(z.string(), z.object({
13612
13469
  value: z.string().optional(),
13613
13470
  alt: z.string().optional(),
@@ -13635,6 +13492,7 @@ function normalizeUser(raw) {
13635
13492
  email: raw.profile?.email || void 0,
13636
13493
  status_text: raw.profile?.status_text ?? void 0,
13637
13494
  status_emoji: raw.profile?.status_emoji ?? void 0,
13495
+ avatar_url: raw.profile?.image_512 || void 0,
13638
13496
  is_bot: raw.is_bot ?? false,
13639
13497
  is_deleted: raw.deleted ?? false,
13640
13498
  timezone: raw.tz || void 0,
@@ -13759,8 +13617,7 @@ async function searchSlackUsers(options) {
13759
13617
  truncated: listed.truncated
13760
13618
  };
13761
13619
  }
13762
- //#endregion
13763
- //#region src/chat/tools/user-lookup.ts
13620
+ // src/chat/tools/user-lookup.ts
13764
13621
  const linkedSlackIdentity = alias(juniorIdentities, "user_lookup_slack_identity");
13765
13622
  function explicitUserLookupError(error) {
13766
13623
  if (error.apiError === "user_not_found" || error.code === "not_found") return "No Slack user found for the supplied user ID.";
@@ -13893,8 +13750,7 @@ function createUserLookupTool(teamId, providers) {
13893
13750
  }
13894
13751
  });
13895
13752
  }
13896
- //#endregion
13897
- //#region src/chat/tools/system-time.ts
13753
+ // src/chat/tools/system-time.ts
13898
13754
  const systemTimeInputSchema = z.object({ timezone: z.string().trim().min(1).optional().describe("Optional IANA timezone, for example America/Los_Angeles. When set, iso_local and timezone_offset_minutes are for that zone.") });
13899
13755
  const systemTimeOutputSchema = juniorToolOutputSchema.extend({
13900
13756
  unix_ms: z.number(),
@@ -13965,8 +13821,7 @@ function getTimeZoneOffsetMinutes(timestampMs, timezone) {
13965
13821
  const asUtcMs = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);
13966
13822
  return Math.round((timestampMs - asUtcMs) / 6e4);
13967
13823
  }
13968
- //#endregion
13969
- //#region src/chat/tools/operator-sql.ts
13824
+ // src/chat/tools/operator-sql.ts
13970
13825
  /** Deferred tool catalog source for operator tools. */
13971
13826
  const OPERATOR_TOOL_SOURCE = {
13972
13827
  id: "operator",
@@ -14046,8 +13901,7 @@ function createOperatorTools(context) {
14046
13901
  }
14047
13902
  }) };
14048
13903
  }
14049
- //#endregion
14050
- //#region src/chat/artifacts/store.ts
13904
+ // src/chat/artifacts/store.ts
14051
13905
  const MAX_IMAGE_BYTES = 10485760;
14052
13906
  const IMAGE_EXTENSIONS = {
14053
13907
  "image/gif": "gif",
@@ -14188,8 +14042,7 @@ function unpublishedArtifactHeaders() {
14188
14042
  "x-content-type-options": "nosniff"
14189
14043
  });
14190
14044
  }
14191
- //#endregion
14192
- //#region src/chat/tools/publish-image.ts
14045
+ // src/chat/tools/publish-image.ts
14193
14046
  const outputSchema$1 = juniorToolOutputSchema.extend({
14194
14047
  bytes: z.number().int().positive(),
14195
14048
  content_type: z.string().min(1),
@@ -14233,8 +14086,7 @@ function createPublishImageTool(args) {
14233
14086
  }
14234
14087
  });
14235
14088
  }
14236
- //#endregion
14237
- //#region src/chat/tools/unpublish-image.ts
14089
+ // src/chat/tools/unpublish-image.ts
14238
14090
  const outputSchema = juniorToolOutputSchema.extend({
14239
14091
  filename: z.string().min(1),
14240
14092
  unpublished: z.literal(true)
@@ -14266,8 +14118,7 @@ function createUnpublishImageTool(args) {
14266
14118
  }
14267
14119
  });
14268
14120
  }
14269
- //#endregion
14270
- //#region src/chat/tools/load-attachment.ts
14121
+ // src/chat/tools/load-attachment.ts
14271
14122
  const ATTACHMENT_DIR = ".junior/attachments";
14272
14123
  async function readStream(stream) {
14273
14124
  const chunks = [];
@@ -14322,8 +14173,7 @@ function createLoadAttachmentTool(args) {
14322
14173
  }
14323
14174
  });
14324
14175
  }
14325
- //#endregion
14326
- //#region src/chat/tools/search-conversation-events.ts
14176
+ // src/chat/tools/search-conversation-events.ts
14327
14177
  const DEFAULT_LIMIT$1 = 25;
14328
14178
  const MAX_LIMIT$1 = 100;
14329
14179
  const MAX_EVENT_DATA_BYTES = 4e3;
@@ -14533,8 +14383,7 @@ function stripReplacementHistoryField(value) {
14533
14383
  replacement_history_count: Array.isArray(replacementHistory) ? replacementHistory.length : 0
14534
14384
  };
14535
14385
  }
14536
- //#endregion
14537
- //#region src/chat/briefs/search.ts
14386
+ // src/chat/briefs/search.ts
14538
14387
  /** Search the latest Brief of each public root Conversation in one scope. */
14539
14388
  async function searchConversationBriefs(db, args) {
14540
14389
  const query = args.filters.query?.trim() || void 0;
@@ -14598,8 +14447,7 @@ async function searchConversationBriefs(db, args) {
14598
14447
  };
14599
14448
  });
14600
14449
  }
14601
- //#endregion
14602
- //#region src/chat/tools/search-conversation-briefs.ts
14450
+ // src/chat/tools/search-conversation-briefs.ts
14603
14451
  const DEFAULT_LIMIT = 10;
14604
14452
  const MAX_LIMIT = 25;
14605
14453
  const conversationBriefSearchOutputSchema = juniorToolOutputSchema.extend({
@@ -14710,8 +14558,7 @@ function createSearchConversationBriefsTool(scope, currentConversationId, provid
14710
14558
  }
14711
14559
  });
14712
14560
  }
14713
- //#endregion
14714
- //#region src/chat/tools/handoff/tool.ts
14561
+ // src/chat/tools/handoff/tool.ts
14715
14562
  const HANDOFF_TOOL_NAME = "handoff";
14716
14563
  function formatHandoffProfiles(handoff) {
14717
14564
  return handoff.profiles.map((profile) => `- ${formatModelProfile(profile.name, profile.description)}`).join("\n");
@@ -14752,8 +14599,7 @@ function createHandoffTool(handoff) {
14752
14599
  }
14753
14600
  });
14754
14601
  }
14755
- //#endregion
14756
- //#region src/chat/plugins/credential-hooks.ts
14602
+ // src/chat/plugins/credential-hooks.ts
14757
14603
  function parseSchema(schema, value, message) {
14758
14604
  const result = schema.safeParse(value);
14759
14605
  if (!result.success) throw new Error(message);
@@ -14844,6 +14690,7 @@ async function resolvePluginOAuthAccount(input) {
14844
14690
  if (!plugin || !hook) return;
14845
14691
  const account = await hook({
14846
14692
  ...basePluginContext(plugin),
14693
+ tokenResponse: input.tokenResponse,
14847
14694
  tokens: input.tokens
14848
14695
  });
14849
14696
  return account === void 0 ? void 0 : parseSchema(pluginProviderAccountSchema, account, `Plugin "${plugin.manifest.name}" resolveOAuthAccount returned an invalid account`);
@@ -14880,31 +14727,30 @@ async function issuePluginCredential(input) {
14880
14727
  }
14881
14728
  }), plugin.manifest.name);
14882
14729
  }
14883
- //#endregion
14884
- //#region src/chat/tools/web/constants.ts
14730
+ // src/chat/tools/web/constants.ts
14885
14731
  const USER_AGENT = "junior-bot/0.1";
14886
14732
  const FETCH_TIMEOUT_MS = 8e3;
14887
14733
  const DEFAULT_MAX_CHARS = 6e3;
14888
14734
  const MAX_FETCH_CHARS = 12e3;
14889
14735
  const MAX_FETCH_BYTES = 1e6;
14890
- //#endregion
14891
- //#region src/chat/tools/web/network.ts
14736
+ // src/chat/tools/web/network.ts
14892
14737
  function isPrivateIpv4(ip) {
14893
14738
  const parts = ip.split(".").map((chunk) => Number.parseInt(chunk, 10));
14894
- if (parts.length !== 4 || parts.some((n) => Number.isNaN(n) || n < 0 || n > 255)) return true;
14895
- if (parts[0] === 10 || parts[0] === 127) return true;
14896
- if (parts[0] === 169 && parts[1] === 254) return true;
14897
- if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true;
14898
- if (parts[0] === 192 && parts[1] === 168) return true;
14899
- if (parts[0] === 0) return true;
14739
+ const [first, second] = parts;
14740
+ if (parts.length !== 4 || first === void 0 || second === void 0 || parts.some((n) => Number.isNaN(n) || n < 0 || n > 255)) return true;
14741
+ if (first === 10 || first === 127) return true;
14742
+ if (first === 169 && second === 254) return true;
14743
+ if (first === 172 && second >= 16 && second <= 31) return true;
14744
+ if (first === 192 && second === 168) return true;
14745
+ if (first === 0) return true;
14900
14746
  return false;
14901
14747
  }
14902
14748
  function parseMappedIpv4FromIpv6(mapped) {
14903
14749
  if (net.isIP(mapped) === 4) return mapped;
14904
- const hexMatch = mapped.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);
14905
- if (!hexMatch) return;
14906
- const high = Number.parseInt(hexMatch[1], 16);
14907
- const low = Number.parseInt(hexMatch[2], 16);
14750
+ const [, highHex, lowHex] = mapped.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i) ?? [];
14751
+ if (!highHex || !lowHex) return;
14752
+ const high = Number.parseInt(highHex, 16);
14753
+ const low = Number.parseInt(lowHex, 16);
14908
14754
  return `${high >> 8 & 255}.${high & 255}.${low >> 8 & 255}.${low & 255}`;
14909
14755
  }
14910
14756
  function isPrivateIpv6(ip) {
@@ -14930,7 +14776,6 @@ async function resolvePublicHostname(hostname) {
14930
14776
  all: true,
14931
14777
  verbatim: true
14932
14778
  });
14933
- if (records.length === 0) throw new ToolInputError("Could not resolve hostname");
14934
14779
  const deduped = /* @__PURE__ */ new Map();
14935
14780
  for (const record of records) {
14936
14781
  const family = record.family === 6 ? 6 : 4;
@@ -14941,7 +14786,9 @@ async function resolvePublicHostname(hostname) {
14941
14786
  family
14942
14787
  });
14943
14788
  }
14944
- return [...deduped.values()];
14789
+ const [first, ...rest] = deduped.values();
14790
+ if (!first) throw new ToolInputError("Could not resolve hostname");
14791
+ return [first, ...rest];
14945
14792
  }
14946
14793
  async function resolvePinnedAddresses(url) {
14947
14794
  const hostname = normalizeHostname(url.hostname);
@@ -14949,7 +14796,7 @@ async function resolvePinnedAddresses(url) {
14949
14796
  return resolvePublicHostname(hostname);
14950
14797
  }
14951
14798
  function createPinnedLookup(resolved) {
14952
- const fallback = resolved[0];
14799
+ const [fallback] = resolved;
14953
14800
  return (_hostname, options, callback) => {
14954
14801
  if (options?.all) {
14955
14802
  callback(null, resolved.map((entry) => ({
@@ -14996,7 +14843,7 @@ async function fetchWithPinnedLookup(url, resolved, signal) {
14996
14843
  signal.removeEventListener("abort", onAbort);
14997
14844
  const headers = new Headers();
14998
14845
  const rawHeaders = response.rawHeaders;
14999
- for (let i = 0; i < rawHeaders.length; i += 2) headers.append(rawHeaders[i], rawHeaders[i + 1]);
14846
+ for (let i = 0; i + 1 < rawHeaders.length; i += 2) headers.append(rawHeaders[i] ?? "", rawHeaders[i + 1] ?? "");
15000
14847
  const rawStatus = response.statusCode ?? 500;
15001
14848
  const status = rawStatus >= 200 && rawStatus <= 599 ? rawStatus : 502;
15002
14849
  resolve(new Response(Buffer.concat(chunks), {
@@ -15071,8 +14918,7 @@ async function readResponseBody(response, maxBytes) {
15071
14918
  }
15072
14919
  return new TextDecoder().decode(Buffer.concat(chunks));
15073
14920
  }
15074
- //#endregion
15075
- //#region src/chat/tools/web/fetch-content.ts
14921
+ // src/chat/tools/web/fetch-content.ts
15076
14922
  const htmlToMarkdownConverter = new NodeHtmlMarkdown({
15077
14923
  bulletMarker: "-",
15078
14924
  codeBlockStyle: "fenced",
@@ -15115,7 +14961,7 @@ function decodeHtmlEntities(value) {
15115
14961
  }
15116
14962
  function extractTitle(html) {
15117
14963
  const match = html.match(/<title\b[^>]*>([\s\S]*?)<\/title>/i);
15118
- const title = match ? normalizeWhitespace(decodeHtmlEntities(match[1])) : "";
14964
+ const title = match?.[1] !== void 0 ? normalizeWhitespace(decodeHtmlEntities(match[1])) : "";
15119
14965
  return title.length > 0 ? title : void 0;
15120
14966
  }
15121
14967
  function escapeRegex(value) {
@@ -15213,8 +15059,7 @@ async function extractWebFetchResponse(url, response, maxChars = DEFAULT_MAX_CHA
15213
15059
  truncated: extracted.truncated
15214
15060
  };
15215
15061
  }
15216
- //#endregion
15217
- //#region src/chat/tools/web/fetch-tool.ts
15062
+ // src/chat/tools/web/fetch-tool.ts
15218
15063
  function extensionForMediaType(mediaType) {
15219
15064
  if (mediaType === "image/png") return "png";
15220
15065
  if (mediaType === "image/jpeg") return "jpg";
@@ -15272,8 +15117,7 @@ function createWebFetchTool(hooks, options = {}) {
15272
15117
  }
15273
15118
  });
15274
15119
  }
15275
- //#endregion
15276
- //#region src/chat/tools/web/search.ts
15120
+ // src/chat/tools/web/search.ts
15277
15121
  const SEARCH_TIMEOUT_MS = 6e4;
15278
15122
  const MAX_RESULTS$1 = 5;
15279
15123
  const SEARCH_TOOL_NAME = "parallelSearch";
@@ -15345,8 +15189,7 @@ function createWebSearchTool(modelId, override) {
15345
15189
  }
15346
15190
  });
15347
15191
  }
15348
- //#endregion
15349
- //#region src/chat/tools/sandbox/write-file.ts
15192
+ // src/chat/tools/sandbox/write-file.ts
15350
15193
  /** Create the sandbox full-file write tool definition exposed to the agent. */
15351
15194
  function createWriteFileTool() {
15352
15195
  return zodTool({
@@ -15368,8 +15211,7 @@ function createWriteFileTool() {
15368
15211
  }
15369
15212
  });
15370
15213
  }
15371
- //#endregion
15372
- //#region src/stats.ts
15214
+ // src/stats.ts
15373
15215
  function utcDate(nowMs) {
15374
15216
  return new Date(nowMs).toISOString().slice(0, 10);
15375
15217
  }
@@ -15394,8 +15236,7 @@ async function incrementStat(key, options = {}) {
15394
15236
  async function readStats(start, end) {
15395
15237
  return await getDb().select().from(juniorStats).where(and(gte(juniorStats.date, start), lte(juniorStats.date, end))).orderBy(asc(juniorStats.date), asc(juniorStats.namespace), asc(juniorStats.metric), asc(juniorStats.name));
15396
15238
  }
15397
- //#endregion
15398
- //#region src/chat/workspaces/tools.ts
15239
+ // src/chat/workspaces/tools.ts
15399
15240
  /** Record optional reporting without changing the switchWorkspace outcome. */
15400
15241
  async function tryRecordWorkspaceSwitchStat(workspace) {
15401
15242
  if (!process.env.DATABASE_URL) return;
@@ -15670,8 +15511,7 @@ function createWorkspaceTools(context) {
15670
15511
  })
15671
15512
  };
15672
15513
  }
15673
- //#endregion
15674
- //#region src/chat/tools/index.ts
15514
+ // src/chat/tools/index.ts
15675
15515
  function createToolState() {
15676
15516
  const operationResultCache = /* @__PURE__ */ new Map();
15677
15517
  return {
@@ -15804,8 +15644,7 @@ function createTools(availableSkills, hooks = {}, context, options = {}) {
15804
15644
  }
15805
15645
  return tools;
15806
15646
  }
15807
- //#endregion
15808
- //#region src/chat/runtime/report-progress.ts
15647
+ // src/chat/runtime/report-progress.ts
15809
15648
  function isActivePlanItem(value) {
15810
15649
  if (!value || typeof value !== "object") return false;
15811
15650
  const item = value;
@@ -15846,8 +15685,7 @@ function latestProgressStatus(messages) {
15846
15685
  }
15847
15686
  }
15848
15687
  }
15849
- //#endregion
15850
- //#region src/chat/tool-support/catalog-tool-call.ts
15688
+ // src/chat/tool-support/catalog-tool-call.ts
15851
15689
  function schemaErrorText(schema, value) {
15852
15690
  const firstError = [...Value.Errors(schema, value)][0];
15853
15691
  if (!firstError) return "invalid arguments";
@@ -15885,8 +15723,7 @@ function prepareCatalogToolCall(call) {
15885
15723
  toolName: call.toolName
15886
15724
  };
15887
15725
  }
15888
- //#endregion
15889
- //#region src/chat/tools/execution/build-sandbox-input.ts
15726
+ // src/chat/tools/execution/build-sandbox-input.ts
15890
15727
  /** Normalize LLM tool params into the shape expected by the sandbox executor. */
15891
15728
  function buildSandboxInput(toolName, params) {
15892
15729
  const optionalNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
@@ -15929,8 +15766,7 @@ function buildSandboxInput(toolName, params) {
15929
15766
  };
15930
15767
  return params;
15931
15768
  }
15932
- //#endregion
15933
- //#region src/chat/services/plugin-auth-orchestration.ts
15769
+ // src/chat/services/plugin-auth-orchestration.ts
15934
15770
  var PluginAuthorizationPauseError = class extends AuthorizationPauseError {
15935
15771
  constructor(provider, providerDisplayName, disposition, requestText) {
15936
15772
  super("plugin", provider, providerDisplayName, disposition, requestText);
@@ -16043,8 +15879,7 @@ function createPluginAuthOrchestration(input) {
16043
15879
  getPendingPause: () => pendingPause
16044
15880
  };
16045
15881
  }
16046
- //#endregion
16047
- //#region src/chat/tools/execution/tool-error-handler.ts
15882
+ // src/chat/tools/execution/tool-error-handler.ts
16048
15883
  function isPluginToolInputError(error) {
16049
15884
  return error instanceof PluginToolInputError || error instanceof Error && error.name === "PluginToolInputError";
16050
15885
  }
@@ -16105,8 +15940,7 @@ function handleToolExecutionError(error, toolName, toolCallId, shouldTrace, conv
16105
15940
  });
16106
15941
  throw error;
16107
15942
  }
16108
- //#endregion
16109
- //#region src/chat/tools/execute-tool.ts
15943
+ // src/chat/tools/execute-tool.ts
16110
15944
  const EXECUTE_TOOL_NAME = "executeTool";
16111
15945
  /** Create the model-visible dispatcher schema for catalog tools. */
16112
15946
  function createExecuteToolTool() {
@@ -16129,8 +15963,7 @@ function createExecuteToolTool() {
16129
15963
  }
16130
15964
  });
16131
15965
  }
16132
- //#endregion
16133
- //#region src/chat/tool-exposure.ts
15966
+ // src/chat/tool-exposure.ts
16134
15967
  /** Return the runtime exposure for a tool, preserving direct compatibility. */
16135
15968
  function effectiveToolExposure(definition) {
16136
15969
  return definition.exposure ?? "direct";
@@ -16157,8 +15990,7 @@ function planToolExposure(tools) {
16157
15990
  excludedTools
16158
15991
  };
16159
15992
  }
16160
- //#endregion
16161
- //#region src/chat/tools/search-tools.ts
15993
+ // src/chat/tools/search-tools.ts
16162
15994
  const SEARCH_TOOLS_NAME = "searchTools";
16163
15995
  const DEFAULT_MAX_RESULTS = 5;
16164
15996
  const MAX_RESULTS = 20;
@@ -16415,8 +16247,7 @@ function createSearchToolsTool(catalogTools) {
16415
16247
  }
16416
16248
  });
16417
16249
  }
16418
- //#endregion
16419
- //#region src/chat/tool-support/pi-tool-adapter.ts
16250
+ // src/chat/tool-support/pi-tool-adapter.ts
16420
16251
  /**
16421
16252
  * How long a preempted tool may take to return its own aborted result. Keep it
16422
16253
  * below the agent's abort settle grace, so the parked turn sees the result.
@@ -16648,8 +16479,7 @@ function createPiAgentTools(tools, sandbox, spanContext, onStatus, sandboxTools,
16648
16479
  }
16649
16480
  }));
16650
16481
  }
16651
- //#endregion
16652
- //#region src/chat/mcp/jwt-bearer-provider.ts
16482
+ // src/chat/mcp/jwt-bearer-provider.ts
16653
16483
  /**
16654
16484
  * Non-interactive MCP auth for bot plugins.
16655
16485
  *
@@ -16717,8 +16547,7 @@ function createJwtBearerMcpClientProvider(subject, mcpUrl, auth) {
16717
16547
  }
16718
16548
  };
16719
16549
  }
16720
- //#endregion
16721
- //#region src/chat/mcp/auth-store.ts
16550
+ // src/chat/mcp/auth-store.ts
16722
16551
  const MCP_AUTH_SESSION_PREFIX = "junior:mcp_oauth_attempt:v2";
16723
16552
  const MCP_AUTH_CREDENTIALS_PREFIX = "junior:mcp_auth_credentials";
16724
16553
  const MCP_AUTH_SESSION_INDEX_PREFIX = "junior:mcp_oauth_attempt_index:v2";
@@ -16883,8 +16712,7 @@ async function putMcpServerSessionId(userId, provider, sessionId, ttlMs = MCP_SE
16883
16712
  async function deleteMcpServerSessionId(userId, provider) {
16884
16713
  await (await getConnectedStateAdapter()).delete(serverSessionKey(userId, provider));
16885
16714
  }
16886
- //#endregion
16887
- //#region src/chat/mcp/oauth-provider.ts
16715
+ // src/chat/mcp/oauth-provider.ts
16888
16716
  function createClientMetadata(callbackUrl) {
16889
16717
  return {
16890
16718
  client_name: "Junior MCP Client",
@@ -16905,12 +16733,12 @@ function requireEnv(name) {
16905
16733
  return value;
16906
16734
  }
16907
16735
  var StateBackedMcpOAuthClientProvider = class {
16736
+ clientMetadata;
16908
16737
  authSessionId;
16909
16738
  callbackUrl;
16910
16739
  sessionContext;
16911
16740
  runCredentialMutation;
16912
16741
  oauthClient;
16913
- clientMetadata;
16914
16742
  constructor(authSessionId, callbackUrl, sessionContext, runCredentialMutation, oauthClient) {
16915
16743
  this.authSessionId = authSessionId;
16916
16744
  this.callbackUrl = callbackUrl;
@@ -17043,8 +16871,7 @@ var StateBackedMcpOAuthClientProvider = class {
17043
16871
  return session;
17044
16872
  }
17045
16873
  };
17046
- //#endregion
17047
- //#region src/chat/mcp/oauth.ts
16874
+ // src/chat/mcp/oauth.ts
17048
16875
  function getMcpOAuthCallbackPath(provider) {
17049
16876
  return `/api/oauth/callback/mcp/${provider}`;
17050
16877
  }
@@ -17116,8 +16943,7 @@ async function finalizeMcpAuthorization(provider, authSessionId, authorizationCo
17116
16943
  if (!nextSession) throw new Error(`Unknown MCP auth session: ${authSessionId}`);
17117
16944
  return nextSession;
17118
16945
  }
17119
- //#endregion
17120
- //#region src/chat/services/auth-pause-response.ts
16946
+ // src/chat/services/auth-pause-response.ts
17121
16947
  const MAX_AUTH_REQUEST_LENGTH = 200;
17122
16948
  function formatAuthRequest(requestText) {
17123
16949
  const normalized = requestText.replace(/\s+/g, " ").trim();
@@ -17137,8 +16963,7 @@ function buildAuthPauseResponse(slackUserId, providerDisplayName, requestText) {
17137
16963
  const notice = `${mention}I need access to your ${providerDisplayName} account to continue. I sent you a private link.`;
17138
16964
  return request ? `${notice}\n\n*Why:* ${request}` : notice;
17139
16965
  }
17140
- //#endregion
17141
- //#region src/chat/services/mcp-auth-orchestration.ts
16966
+ // src/chat/services/mcp-auth-orchestration.ts
17142
16967
  var McpAuthorizationPauseError = class extends AuthorizationPauseError {
17143
16968
  constructor(provider, providerDisplayName, disposition, requestText) {
17144
16969
  super("mcp", provider, providerDisplayName, disposition, requestText);
@@ -17258,8 +17083,7 @@ function createMcpAuthOrchestration(input) {
17258
17083
  getPendingPause: () => pendingPause
17259
17084
  };
17260
17085
  }
17261
- //#endregion
17262
- //#region src/chat/sandbox/egress/credentials.ts
17086
+ // src/chat/sandbox/egress/credentials.ts
17263
17087
  const HTTP_READ_METHODS = /* @__PURE__ */ new Set([
17264
17088
  "GET",
17265
17089
  "HEAD",
@@ -17431,8 +17255,7 @@ async function sandboxEgressCredentialLease(provider, selection, context) {
17431
17255
  function hasSandboxEgressLeaseTransformForHost(lease, host) {
17432
17256
  return lease.headerTransforms.some((transform) => matchesSandboxEgressDomain(host, transform.domain));
17433
17257
  }
17434
- //#endregion
17435
- //#region src/chat/egress/credentialed.ts
17258
+ // src/chat/egress/credentialed.ts
17436
17259
  const HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
17437
17260
  "connection",
17438
17261
  "host",
@@ -17534,9 +17357,15 @@ function isEgressAuthRequired(error) {
17534
17357
  function isEgressPolicyDenied(error) {
17535
17358
  return error instanceof EgressPolicyDenied || error instanceof Error && error.name === "EgressPolicyDenied";
17536
17359
  }
17360
+ /**
17361
+ * Record one forwarded provider request. Write-grant requests are audit
17362
+ * events, so they reach Sentry in production. Other requests log only outside
17363
+ * production.
17364
+ */
17537
17365
  function logSandboxEgressUpstreamRequest(input) {
17538
- if (!shouldLogSandboxEgressInfo()) return;
17539
- logInfo("sandbox.egress.upstream.requested", {
17366
+ const isWrite = input.grantAccess === "write";
17367
+ if (!isWrite && !shouldLogSandboxEgressInfo()) return;
17368
+ (isWrite ? logAudit : logInfo)("sandbox.egress.upstream.requested", {
17540
17369
  ...egressAttributes({
17541
17370
  egressId: input.egressId,
17542
17371
  grantAccess: input.grantAccess,
@@ -17553,7 +17382,7 @@ function logSandboxEgressUpstreamRequest(input) {
17553
17382
  });
17554
17383
  }
17555
17384
  async function requestBodyBytes(request) {
17556
- if (request.method === "GET" || request.method === "HEAD" || request.body === null) return;
17385
+ if (request.method === "GET" || request.method === "HEAD" || request.method === "OPTIONS" || request.body === null) return;
17557
17386
  return await request.arrayBuffer();
17558
17387
  }
17559
17388
  /**
@@ -17973,8 +17802,7 @@ async function executeCredentialedEgressRequest(input) {
17973
17802
  });
17974
17803
  }
17975
17804
  }
17976
- //#endregion
17977
- //#region src/chat/egress/plugin.ts
17805
+ // src/chat/egress/plugin.ts
17978
17806
  function credentialContextForPluginEgress(credentialContext) {
17979
17807
  return {
17980
17808
  credentials: credentialContext,
@@ -18017,8 +17845,7 @@ function createPluginEgress(deps) {
18017
17845
  });
18018
17846
  } };
18019
17847
  }
18020
- //#endregion
18021
- //#region src/chat/services/guardian-action-policy.ts
17848
+ // src/chat/services/guardian-action-policy.ts
18022
17849
  /**
18023
17850
  * The only reasons that Guardian can block an action. Keep each rule broad
18024
17851
  * and free of tool or provider names. The model sees them in this order.
@@ -18144,8 +17971,7 @@ ${renderRules("deny")}
18144
17971
  - Rate risk and user authorization first.
18145
17972
  - Then set the rule to the id of the one rule that the action clearly matches. When a hard rule and a confirmation rule both match, name the hard rule. When no definition clearly fits, use \`none\`. Do not name a rule only to express general doubt.
18146
17973
  - Keep the reason to one concise, specific sentence. For a confirmation rule, name the exact action, target, and material side effects the user must confirm. For a hard rule, name the risk. For \`none\`, say why the action is ordinary.`;
18147
- //#endregion
18148
- //#region src/chat/services/guardian-action-review.ts
17974
+ // src/chat/services/guardian-action-review.ts
18149
17975
  const guardianAssessmentSchema = z.object({
18150
17976
  riskLevel: z.enum([
18151
17977
  "low",
@@ -18279,8 +18105,7 @@ function createGuardianActionReviewer(options) {
18279
18105
  };
18280
18106
  } };
18281
18107
  }
18282
- //#endregion
18283
- //#region src/chat/tool-support/action-review-evidence.ts
18108
+ // src/chat/tool-support/action-review-evidence.ts
18284
18109
  const MAX_MESSAGE_TRANSCRIPT_TOKENS = 1e4;
18285
18110
  const MAX_TOOL_TRANSCRIPT_TOKENS = 1e4;
18286
18111
  const MAX_MESSAGE_ENTRY_TOKENS = 2e3;
@@ -18424,8 +18249,7 @@ function buildToolActionEvidence(messages, options = {}) {
18424
18249
  omittedEntries: included.filter((value) => !value).length
18425
18250
  };
18426
18251
  }
18427
- //#endregion
18428
- //#region src/chat/agent-invocations/root-conversation.ts
18252
+ // src/chat/agent-invocations/root-conversation.ts
18429
18253
  /** Most root messages that Guardian reads, newest first. Codex uses 16. */
18430
18254
  const MAX_ROOT_MESSAGES = 16;
18431
18255
  /** Most characters of one root message. */
@@ -18577,8 +18401,7 @@ async function readRootConversation(args) {
18577
18401
  truncated: hasOlder || orphanEdits || messages.length < all.length
18578
18402
  };
18579
18403
  }
18580
- //#endregion
18581
- //#region src/chat/agent/tools.ts
18404
+ // src/chat/agent/tools.ts
18582
18405
  /** Record optional reporting without changing the loadSkill outcome. */
18583
18406
  async function tryRecordSkillLoadStat(skill) {
18584
18407
  if (!process.env.DATABASE_URL) return;
@@ -18648,6 +18471,7 @@ async function wireAgentTools(args) {
18648
18471
  traceContext: args.spanContext,
18649
18472
  tracePropagation: args.run.environment?.sandboxTracePropagation,
18650
18473
  egressSignals: args.run.environment?.sandboxEgressSignals,
18474
+ conversationId: args.run.conversationId,
18651
18475
  credentialEgress: args.run.credentialContext,
18652
18476
  actor: args.currentActor,
18653
18477
  locationConfiguration: args.run.environment?.locationConfiguration,
@@ -18876,8 +18700,7 @@ async function wireAgentTools(args) {
18876
18700
  toolRuntimeContext
18877
18701
  };
18878
18702
  }
18879
- //#endregion
18880
- //#region src/chat/agent/resume.ts
18703
+ // src/chat/agent/resume.ts
18881
18704
  function extractSliceUsage(messages, beforeMessageCount) {
18882
18705
  const usage = extractGenAiUsageSummary(...messages.slice(beforeMessageCount).filter(isAssistantMessage));
18883
18706
  return hasAgentTurnUsage(usage) ? usage : void 0;
@@ -19093,8 +18916,7 @@ function createResumeState(args) {
19093
18916
  }
19094
18917
  };
19095
18918
  }
19096
- //#endregion
19097
- //#region src/chat/services/plan-continuation.ts
18919
+ // src/chat/services/plan-continuation.ts
19098
18920
  const OPEN_PLAN_TAG = "open-plan";
19099
18921
  function openItems(input) {
19100
18922
  const plan = input && typeof input === "object" ? input.plan : void 0;
@@ -19158,8 +18980,7 @@ function appendOpenPlan(continuation, messages) {
19158
18980
  const plan = latestOpenPlanItems(messages);
19159
18981
  return plan.length === 0 ? continuation : `${continuation}\n\n<${OPEN_PLAN_TAG}>\n${JSON.stringify(plan)}\n</${OPEN_PLAN_TAG}>`;
19160
18982
  }
19161
- //#endregion
19162
- //#region src/chat/services/context-compaction.ts
18983
+ // src/chat/services/context-compaction.ts
19163
18984
  const RETAINED_USER_MESSAGE_TOKENS = 2e4;
19164
18985
  const MAX_SUMMARY_CHARS = 6e3;
19165
18986
  /** Raised when Junior cannot compact history below the active model's hard ceiling. */
@@ -19590,8 +19411,7 @@ async function compactActiveContextIfNeeded(args, deps) {
19590
19411
  piMessages: messages
19591
19412
  };
19592
19413
  }
19593
- //#endregion
19594
- //#region src/chat/agent/handoff.ts
19414
+ // src/chat/agent/handoff.ts
19595
19415
  /** Tools that must be the only tool call in their assistant message. */
19596
19416
  const EXCLUSIVE_TOOL_NAMES = [
19597
19417
  HANDOFF_TOOL_NAME,
@@ -19710,8 +19530,7 @@ function applyHandoff(args) {
19710
19530
  thinkingLevel: args.pending.thinkingLevel
19711
19531
  };
19712
19532
  }
19713
- //#endregion
19714
- //#region src/chat/agent/index.ts
19533
+ // src/chat/agent/index.ts
19715
19534
  /**
19716
19535
  * Agent executor.
19717
19536
  *
@@ -19776,20 +19595,14 @@ async function executeAgentRun(run, streamFn) {
19776
19595
  if (!run.destination) throw new TypeError("Assistant reply generation requires a destination");
19777
19596
  const visibility = await readRunConversationVisibility(run.conversationId);
19778
19597
  const conversationPrivacy = resolveConversationPrivacy({ visibility });
19779
- const credentialActor = run.credentialContext?.actor;
19780
19598
  const actor = actorFromRun(run);
19781
- const userActor = actor && "userId" in actor ? actor : void 0;
19782
19599
  const runLogContext = {
19783
19600
  conversationId: run.conversationId,
19784
19601
  platform: run.source.kind === "slack" || run.source.kind === "web" || run.source.kind === "local" ? run.source.kind : void 0,
19785
19602
  messageConversationId: run.source.kind === "slack" ? run.conversationId : run.source.kind === "web" || run.source.kind === "local" ? run.source.conversationId : run.conversationId,
19786
19603
  destinationName: run.location?.channelId ?? (run.source.kind === "slack" ? run.source.channelId : run.source.kind === "web" || run.source.kind === "local" ? run.source.conversationId : run.conversationId),
19787
- userId: userActor?.userId,
19788
- userName: userActor?.userName,
19789
- userEmail: userActor?.email,
19604
+ ...actorLogContext(actor, run.credentialContext),
19790
19605
  runId: run.runId,
19791
- actorType: credentialActor ? "type" in credentialActor ? credentialActor.type : "system" : void 0,
19792
- actorId: credentialActor ? "type" in credentialActor ? credentialActor.userId : credentialActor.name : void 0,
19793
19606
  assistantUserName: botConfig.userName
19794
19607
  };
19795
19608
  return withLogContext(runLogContext, () => runWithConversationPrivacy(conversationPrivacy, () => executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogContext, streamFn)));
@@ -20712,8 +20525,7 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
20712
20525
  await closeTools?.();
20713
20526
  }
20714
20527
  }
20715
- //#endregion
20716
- //#region src/chat/runtime/agent-runner.ts
20528
+ // src/chat/runtime/agent-runner.ts
20717
20529
  /** Compose the agent executor with stable host dependencies. */
20718
20530
  function createAgentRunner(execute, options) {
20719
20531
  const attachmentStorage = options?.attachmentStorage;
@@ -20739,7 +20551,7 @@ function createAgentRunner(execute, options) {
20739
20551
  } } : void 0
20740
20552
  };
20741
20553
  if (run.instruction.storedAttachments?.length) {
20742
- const { loadInputImages } = await import("./images-D0VZ5nv0.js").then((n) => n.n);
20554
+ const { loadInputImages } = await import("./images-C2J_bj2g.js").then((n) => n.n);
20743
20555
  const storage = nextRun.environment?.attachmentStorage;
20744
20556
  if (!storage) throw new Error("Attachment storage is unavailable.");
20745
20557
  nextRun.instruction = {
@@ -20754,5 +20566,4 @@ function createAgentRunner(execute, options) {
20754
20566
  return await execute(nextRun, streamFn);
20755
20567
  } };
20756
20568
  }
20757
- //#endregion
20758
20569
  export { getAgentInvocation as $, resolveSlackChannelIdFromMessage as A, consumeSandboxEgressPermissionDeniedSignal as At, effectiveTaskOutcomes as B, RetryableDeliveryError as Bt, renderBlockText as C, ingestEvent as Ct, storeAttachment as D, SANDBOX_EGRESS_PROXY_PATH as Dt, requestAttachmentDeletion as E, shouldPropagateSandboxEgressTrace as Et, logScheduledAutomationRunSkipped as F, resolveBaseUrl as Ft, recordSubagentStarted as G, shouldEmitDevAgentTrace as Gt, stopChildAgentsOf as H, toolInvocationDestination as Ht, scheduledAutomationRunAttributes as I, startOAuthFlow as It, createAgentInvocation as J, listChildAgents as K, getConfigDefaults as Kt, editEventAutomation as L, createUserTokenStore as Lt, getConversationInfo as M, sandboxEgressSignalsResponseSchema as Mt, listThreadReplies as N, formatProviderLabel as Nt, parseSlackThreadId as O, clearSandboxEgressSignals as Ot, editScheduledAutomation as P, parseOAuthStatePayload as Pt, getActiveAgentInvocationForConversation as Q, AutomationEditError as R, buildSteeringPiMessage as Rt, renderAttachmentText as S, processWorkspaceSnapshotJob as St, readLiveAttachment as T, normalizeSandboxEgressTracePropagationDomains as Tt, stopConversationSession as U, AuthorizationFlowDisabledError as Ut, resolveTaskOutcomes as V, actorFromRun as Vt, recordSubagentEnded as W, readBlockedReport as Wt, createAgentInvocationFromLatest as X, createAgentInvocationForMessage as Y, findChildAgentConversationId as Z, resolvePluginOAuthAccount as _, AgentMessageTargetError as _t, buildAuthPauseResponse as a, getAgentInvocationTurnId as at, unpublishedArtifactHeaders as b, conversationSubtreeColumns as bt, deleteMcpAuthSessionsForUserProvider as c, isTerminalAgentInvocation as ct, getMcpAuthSession as d, markAgentInvocationMailboxAppended as dt, getAgentInvocationIdForEvents as et, getMcpStoredOAuthCredentials as f, markAgentInvocationParentMailboxAppended as ft, readStats as g, reportReplacedAgentInvocation as gt, latestProgressStatus as h, markAgentInvocationSteered as ht, executeCredentialedEgressRequest as i, getAgentInvocationResultMessageId as it, resolveSlackChannelIdFromThreadId as j, parseSandboxEgressCredentialToken as jt, readSlackRawMessageContext as k, consumeSandboxEgressAuthRequiredSignal as kt, deleteMcpServerSessionId as l, listPendingAgentInvocationMailboxAppends as lt, PluginCredentialFailureError as m, markAgentInvocationRunning as mt, executeAgentRun as n, getAgentInvocationIdForResult as nt, finalizeMcpAuthorization as o, getChildAgentLabel as ot, putMcpStoredOAuthCredentials as p, markAgentInvocationPaused as pt, completeAgentInvocation as q, setConfigDefaults as qt, createContextCompactor as r, getAgentInvocationMessageId as rt, deleteMcpAuthSession as s, getLatestAgentInvocationForConversation as st, createAgentRunner as t, getAgentInvocationIdForMessage as tt, deleteMcpStoredOAuthCredentials as u, listPendingAgentInvocationResults as ut, publicArtifactHeaders as v, PARENT_AGENT_TARGET as vt, collectAttachmentGarbage as w, resolveSandboxEgressProviderForHost as wt, lookupSlackUserProfile as x, getMcpProviderErrorAttributes as xt, readPublicArtifact as y, conversationSubtree as yt, eventAutomationTriggerAvailable as z, withoutSavedSteeringMessages as zt };