@sentry/junior 0.215.0 → 0.217.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 (49) hide show
  1. package/dist/{agent-DL7L5IGV.js → agent-CV4MPfCD.js} +271 -119
  2. package/dist/{agent-hooks-CbS_0qVT.js → agent-hooks-BtGATjr2.js} +6 -6
  3. package/dist/{agent-runner-Dv_3inX5.js → agent-runner-DCj_cPjl.js} +5 -5
  4. package/dist/api.js +15 -15
  5. package/dist/app.js +30 -30
  6. package/dist/{auth-pause-state-CKyGi5MA.js → auth-pause-state-C7GMUpb9.js} +6 -6
  7. package/dist/{briefs-ObAqH9xe.js → briefs-eG5Jo1xa.js} +2 -2
  8. package/dist/{catalog-runtime-d65qfc1w.js → catalog-runtime-LUAIHslF.js} +1 -1
  9. package/dist/{checkpoint-DrgS0aKI.js → checkpoint-CmkbGGiR.js} +6 -6
  10. package/dist/cli/chat.js +13 -13
  11. package/dist/cli/check.js +3 -3
  12. package/dist/cli/main.js +1 -1
  13. package/dist/cli/plugins.js +3 -3
  14. package/dist/cli/snapshot-create.js +3 -3
  15. package/dist/cli/upgrade.js +3 -3
  16. package/dist/{client-CI4MF188.js → client-ciJRmcY5.js} +6 -6
  17. package/dist/{config-CC2WLw37.js → config-BMwzCmw-.js} +2 -2
  18. package/dist/{conversation-privacy-Dr3jEHg8.js → conversation-privacy-CLkpzAlt.js} +1 -1
  19. package/dist/{credential-sync-DFuzxOk0.js → credential-sync-BoWHpDBP.js} +22 -22
  20. package/dist/{execution-stats-D0CDD8i5.js → execution-stats-C-E5FIsT.js} +3 -3
  21. package/dist/{executor-DJBc9GHM.js → executor-D0xETqi8.js} +1 -1
  22. package/dist/instrumentation.js +2 -2
  23. package/dist/{job-queue-FDxeYtda.js → job-queue-C8FZ3LSY.js} +1 -1
  24. package/dist/{logging-X8-jOuNZ.js → logging-CHZ0aJXO.js} +1 -1
  25. package/dist/nitro.js +3 -3
  26. package/dist/{oauth-callback-server-C236l0dz.js → oauth-callback-server-D2JPUvY4.js} +2 -2
  27. package/dist/{pending-auth-WG65bhYl.js → pending-auth-HNSPyxoN.js} +2 -2
  28. package/dist/{profile-BygAXI52.js → profile-6veboDue.js} +4 -4
  29. package/dist/{registry-C8xgqDPT.js → registry-DR6TJe4J.js} +1 -1
  30. package/dist/{resolve-BcoTZROi.js → resolve-DprAzyQN.js} +2 -2
  31. package/dist/{runner-Gl6Iy-pT.js → runner-CV9Wahh9.js} +9 -9
  32. package/dist/{sandbox-egress-signals-BsXjnJrx.js → sandbox-egress-signals-BpRsWlQP.js} +1 -1
  33. package/dist/{short-title-CZv2wyYI.js → short-title-XUBD7AYC.js} +2 -2
  34. package/dist/{skills-XhDVA_7_.js → skills-DeUBvhdn.js} +2 -2
  35. package/dist/{spawn-Dgwv-HvF.js → spawn-BFzlrZae.js} +2 -2
  36. package/dist/{stats-feF70h9e.js → stats-BvNqVRdB.js} +5 -5
  37. package/dist/{task-queue-DDKd0vE_.js → task-queue-CbxNVEAg.js} +3 -3
  38. package/dist/{task-runner-KOTg-g4J.js → task-runner-BH5M3JHb.js} +7 -7
  39. package/dist/{thread-state-CVZMgZrC.js → thread-state-Db98GdYL.js} +5 -5
  40. package/dist/{turn-execution-Du5ai0bJ.js → turn-execution-mZIWtngI.js} +3 -3
  41. package/dist/{turn-lifecycle-CgmJKAad.js → turn-lifecycle-CNsgouon.js} +1 -1
  42. package/dist/{validation-eh1Obe24.js → validation-Dy7SUhLv.js} +1 -1
  43. package/dist/{version-nVlRbCxY.js → version-Es4nurl1.js} +1 -1
  44. package/dist/version.js +1 -1
  45. package/dist/{web-authorization-D5Lpo_X1.js → web-authorization-DG2K_bpi.js} +1 -1
  46. package/dist/{web-input-Ba4qiF7l.js → web-input-CZjYeCFh.js} +4 -4
  47. package/dist/{work-DgWqzN7_.js → work-DTqDMGeD.js} +9 -9
  48. package/dist/{worker-Bn2cv6mD.js → worker-BvuVxS4T.js} +5 -5
  49. package/package.json +5 -5
@@ -1,28 +1,28 @@
1
- import { C as resolveGatewayCredential, S as getGatewayApiKey, _ as findProviderError, b as isProviderRetryError, c as COMPACTION_SUMMARY_PREFIX, d as isCompactionSummaryText, f as renderCurrentInstruction, g as createProviderError, h as ProviderError, i as completeText, l as MODEL_HANDOFF_SUMMARY_PREFIX, m as escapeXml, n as GEN_AI_SERVER_ADDRESS, o as resolveGatewayModel, p as unwrapCurrentInstruction, r as completeObject, s as ACTIVE_TURN_COMPACTION_SUMMARY_PREFIX, t as GEN_AI_PROVIDER_NAME, u as hasCompactedConversationContext, v as getProviderErrorAttributes, x as MISSING_GATEWAY_CREDENTIALS_ERROR } from "./client-CI4MF188.js";
2
- import { C as withSpan, F as isRecord$2, P as normalizeIdentityEmail, S as withLogContext, _ as setSpanAttributes, a as extractGenAiUsageSummary, b as summarizeMessageText, c as getTracePropagationHeaders, d as logInfo, f as logWarn, h as serializeGenAiAttribute, i as extractGenAiUsageAttributes, l as logError, p as normalizeGenAiFinishReason, s as getLogContextAttributesForSpan, u as logException, v as setSpanStatus, y as setTags } from "./logging-X8-jOuNZ.js";
1
+ import { C as resolveGatewayCredential, S as getGatewayApiKey, _ as findProviderError, b as isProviderRetryError, c as COMPACTION_SUMMARY_PREFIX, d as isCompactionSummaryText, f as renderCurrentInstruction, g as createProviderError, h as ProviderError, i as completeText, l as MODEL_HANDOFF_SUMMARY_PREFIX, m as escapeXml, n as GEN_AI_SERVER_ADDRESS, o as resolveGatewayModel, p as unwrapCurrentInstruction, r as completeObject, s as ACTIVE_TURN_COMPACTION_SUMMARY_PREFIX, t as GEN_AI_PROVIDER_NAME, u as hasCompactedConversationContext, v as getProviderErrorAttributes, x as MISSING_GATEWAY_CREDENTIALS_ERROR } from "./client-ciJRmcY5.js";
2
+ import { C as withSpan, F as isRecord$2, P as normalizeIdentityEmail, S as withLogContext, _ as setSpanAttributes, a as extractGenAiUsageSummary, b as summarizeMessageText, c as getTracePropagationHeaders, d as logInfo, f as logWarn, h as serializeGenAiAttribute, i as extractGenAiUsageAttributes, l as logError, p as normalizeGenAiFinishReason, s as getLogContextAttributesForSpan, u as logException, v as setSpanStatus, y as setTags } from "./logging-CHZ0aJXO.js";
3
3
  import { m as startInactiveSpan, v as withActiveSpan } from "./sentry-CgWZM_kV.js";
4
- import { a as toCanonicalInputMessage, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes, t as canExposeConversationPayload } from "./conversation-privacy-Dr3jEHg8.js";
5
- import { h as normalizeSlackEmojiName, n as botConfig } from "./config-CC2WLw37.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-CLkpzAlt.js";
5
+ import { h as normalizeSlackEmojiName, n as botConfig } from "./config-BMwzCmw-.js";
6
6
  import { a as modelIdForProfile, c as TURN_REASONING_LEVELS, i as formatModelProfiles, o as modelProfileSchema, r as formatModelProfile, s as profileConfig, t as ModelProfileNotConfiguredError } from "./model-profile-CZmVoGdX.js";
7
7
  import { _ as parseSlackMessageTs, g as parseSlackUserId, h as parseSlackTeamId, i as credentialUserSubjectId, l as isUserActor, m as parseSlackChannelReferenceId, n as credentialContextSchema, p as parseSlackChannelId, t as credentialContextForActor } from "./context-Bplcgypl.js";
8
- import { A as tryWorkspaceRepoCheckoutPath, B as downloadPrivateSlackFile, C as invalidateReadySnapshot, D as SANDBOX_RUNTIME, E as setWorkspaceSnapshotBuild, Gt as getDb, Ht as getConversationEventStore, J as withSlackRetries, K as normalizeSlackConversationId, Kt as getSqlExecutor, M as resolveChannelCapabilities, O as deleteWorkspaceSnapshotBuilders, Q as readActorIdentity, S as WorkspaceValidationError, T as setWorkspaceSnapshot, U as getSlackClient, Ut as getConversationMessageSearchStore, V as getFilePermalink, W as isConversationScopedChannel, Wt as getConversationStore, _ as deleteWorkspace, at as STOP_WATCHING_TOOL_NAME, b as listWorkspaces, bt as createPluginLogger, c as getPluginTools, dt as findMatchingWatches, en as addAgentTurnUsage, ft as listWatches, g as createWorkspace, ht as getDashboardTaskLink, in as hasAgentTurnUsage, it as RESOURCE_WATCH_TOOL_SOURCE, j as workspaceRepoCheckoutPath, k as getWorkspaceSnapshotBuilder, l as getPluginUserPromptContributions, lt as createWatch, mt as getDashboardConversationLink, nt as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, ot as cancelSubscriptions, pt as JUNIOR_THREAD_STATE_TTL_MS, r as createPluginHookRunner, s as getPluginSystemPromptContributions, st as cancelWatch, tt as getSlackToolContext, u as getPlugins, un as parseDestination, ut as deliverWatch, v as getWorkspace, w as loadSnapshotsForProfile, x as updateWorkspace, y as getWorkspaceByName, z as SlackActionError } from "./agent-hooks-CbS_0qVT.js";
8
+ import { A as tryWorkspaceRepoCheckoutPath, B as downloadPrivateSlackFile, C as invalidateReadySnapshot, D as SANDBOX_RUNTIME, E as setWorkspaceSnapshotBuild, Gt as getDb, Ht as getConversationEventStore, J as withSlackRetries, K as normalizeSlackConversationId, Kt as getSqlExecutor, M as resolveChannelCapabilities, O as deleteWorkspaceSnapshotBuilders, Q as readActorIdentity, S as WorkspaceValidationError, T as setWorkspaceSnapshot, U as getSlackClient, Ut as getConversationMessageSearchStore, V as getFilePermalink, W as isConversationScopedChannel, Wt as getConversationStore, _ as deleteWorkspace, at as STOP_WATCHING_TOOL_NAME, b as listWorkspaces, bt as createPluginLogger, c as getPluginTools, dt as findMatchingWatches, en as addAgentTurnUsage, ft as listWatches, g as createWorkspace, ht as getDashboardTaskLink, in as hasAgentTurnUsage, it as RESOURCE_WATCH_TOOL_SOURCE, j as workspaceRepoCheckoutPath, k as getWorkspaceSnapshotBuilder, l as getPluginUserPromptContributions, lt as createWatch, mt as getDashboardConversationLink, nt as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, ot as cancelSubscriptions, pt as JUNIOR_THREAD_STATE_TTL_MS, r as createPluginHookRunner, s as getPluginSystemPromptContributions, st as cancelWatch, tt as getSlackToolContext, u as getPlugins, un as parseDestination, ut as deliverWatch, v as getWorkspace, w as loadSnapshotsForProfile, x as updateWorkspace, y as getWorkspaceByName, z as SlackActionError } from "./agent-hooks-BtGATjr2.js";
9
9
  import { n as juniorDestinations } from "./destinations-BeBiJeEM.js";
10
- import { D as juniorIdentities, E as juniorConversations, a as juniorSchedulerRuns, d as AGENT_INVOCATION_MAILBOX_STATUSES, g as juniorConversationBriefs, k as juniorArtifacts, w as juniorAttachments, x as juniorConversationAnnotations } from "./executor-DJBc9GHM.js";
10
+ import { D as juniorIdentities, E as juniorConversations, a as juniorSchedulerRuns, d as AGENT_INVOCATION_MAILBOX_STATUSES, g as juniorConversationBriefs, k as juniorArtifacts, w as juniorAttachments, x as juniorConversationAnnotations } from "./executor-D0xETqi8.js";
11
11
  import { A as briefLinkSchema, G as sameActorIdentity, H as contextProvenance, M as conversationBriefSchema, P as KNOWN_CONVERSATION_EVENT_TYPES, U as instructionActors, W as instructionProvenanceFor, j as briefOutcomeStatusSchema } from "./conversation-BpqLg4MM.js";
12
12
  import { a as listReferenceFiles, c as soulPathCandidates, l as worldPathCandidates } from "./package-discovery-7a9YqLhE.js";
13
- import { a as resolvePluginCommandEnv, c as getOAuthProviderErrorAttributes, i as resolveAuthTokenPlaceholder, o as OAuthProviderError, s as fetchWithBoundedOAuthErrorBodies, u as CredentialUnavailableError } from "./registry-C8xgqDPT.js";
14
- import { n as pluginCatalogRuntime } from "./catalog-runtime-d65qfc1w.js";
15
- import { a as parseSkillInvocation, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-XhDVA_7_.js";
16
- import { A as TURN_CONTEXT_TAG, C as isContinuablePiBoundary, D as retainRuntimeTurnContext, E as normalizeToolNameFromResult, H as recordAuthorizationRequested, I as loadTurnRoute, K as recordToolExecutionStarted, L as openConversationProjection, N as loadConnectedMcpProviders, O as stripRuntimeTurnContext, P as loadConversationProjection, R as recordAgentsInstructionsUpdated, S as isAssistantMessage, T as isToolResultMessage, U as recordGuardianActionReviewed, W as recordMcpProviderConnected, _ as getPiMessageRole, b as hasRuntimeTurnContext, dt as estimateTextTokens, f as TurnSliceLimitExceededError, ft as getAgentContextCompactionTriggerTokens, g as extractAssistantText, h as isTurnExecutionLimitExceededError, ht as piMessageFromHistoryItem, k as trimTrailingAssistantMessages, mt as historyItemFromPiMessage, n as loadTurnCheckpoint, p as assertTurnToolCallLimit, pt as getAgentContextInputLimitTokens, q as recordTurnRoute, r as saveTurnCheckpoint, t as continuableMessages, v as getTerminalAssistantMessages, w as isToolResultError, y as getUserMessageInstructionText, z as recordAttachmentsDelivered } from "./checkpoint-DrgS0aKI.js";
17
- import { n as generateShortTitle, r as resolveTaskTitle } from "./short-title-CZv2wyYI.js";
18
- import { A as sleep$1, D as fenceLock, E as acquireActiveLock, F as sandboxSkillDir, I as sandboxSkillFile, L as sandboxSkillPathResolution, M as SANDBOX_REPOS_ROOT, N as SANDBOX_SKILLS_ROOT, P as SANDBOX_WORKSPACE_ROOT, _ 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_DATA_ROOT, k as withLock, 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-BygAXI52.js";
19
- import { $ as workspaceSnapshotFinishedEvent, B as createEventAutomation, C as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, D as eventAutomationMatchesDestination, E as eventAutomationListToolResultSchema, F as effectiveTaskOutcomes, Gt as makeStructuredToolOutput, I as moveTaskOutcomes, Jt as ToolInputError, L as resolveTaskOutcomes, M as requireEventAutomationSlackContext, N as requireSupportedEventAutomationTrigger, O as eventAutomationToolResult, P as writableEventAutomation, Q as WORKSPACE_SNAPSHOT_READY_EVENT, R as taskOutcomeInputSchema, T as compactEventAutomation, Ut as injectContinuationToolName, V as deleteEventAutomation, W as getEventAutomation, Wt as juniorToolOutputSchema, X as getEventCatalog, Y as saveEventAutomation, Z as WORKSPACE_SNAPSHOT_FAILED_EVENT, at as normalizeCatalogEventIdentifier, c as parseSlackThreadId, ct as registeredEventTypeSchema, et as workspaceSnapshotWatch, f as createScheduledAutomation, g as listScheduledAutomationsForTeam, i as readLiveAttachment, it as hasPluginEventCatalogEntries, j as registeredEventAutomationTriggerSchema, k as eventAutomationToolResultSchema, lt as registeredResourceTypeSchema, nt as eventNamespaceSchema, ot as pluginSupportsEvent, pt as appendAndEnqueueInboundMessage, q as listEventAutomationsForTeam, rt as hasEventCatalogEntries, s as storeAttachments, st as registeredEventMatchSchema, t as incrementStat, tt as eventGuidance, ut as requireSupportedEventMatch, v as readScheduledAutomation, y as saveScheduledAutomation } from "./stats-feF70h9e.js";
20
- import { _ as isTurnInputCommitLostError, c as sanitizeAssistantText, f as CooperativeTurnYieldError, l as NO_REPLY_MARKER, n as canReusePendingAuthLink, o as decideReply, p as TurnInputCommitLostError, s as getAssistantReplyText, t as abandonReplacedPendingAuth, u as isNoReplyMarker } from "./pending-auth-WG65bhYl.js";
21
- import { C as toolInvocationDestination, S as surfaceFromRun, _ as uploadFilesToConversation, b as assertRunConsistency, h as postSlackMessage, i as formatProviderLabel, m as getSlackMessagePermalink, o as resolveBaseUrl, p as addReactionToMessage, r as deliverOAuthAuthorization, s as startOAuthFlow, v as RetryableDeliveryError, x as isAgentRunFeatureDisabled, y as actorFromRun } from "./agent-runner-Dv_3inX5.js";
13
+ import { a as resolvePluginCommandEnv, c as getOAuthProviderErrorAttributes, i as resolveAuthTokenPlaceholder, o as OAuthProviderError, s as fetchWithBoundedOAuthErrorBodies, u as CredentialUnavailableError } from "./registry-DR6TJe4J.js";
14
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-LUAIHslF.js";
15
+ import { a as parseSkillInvocation, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-DeUBvhdn.js";
16
+ import { A as TURN_CONTEXT_TAG, C as isContinuablePiBoundary, D as retainRuntimeTurnContext, E as normalizeToolNameFromResult, H as recordAuthorizationRequested, I as loadTurnRoute, K as recordToolExecutionStarted, L as openConversationProjection, N as loadConnectedMcpProviders, O as stripRuntimeTurnContext, P as loadConversationProjection, R as recordAgentsInstructionsUpdated, S as isAssistantMessage, T as isToolResultMessage, U as recordGuardianActionReviewed, W as recordMcpProviderConnected, _ as getPiMessageRole, b as hasRuntimeTurnContext, dt as estimateTextTokens, f as TurnSliceLimitExceededError, ft as getAgentContextCompactionTriggerTokens, g as extractAssistantText, h as isTurnExecutionLimitExceededError, ht as piMessageFromHistoryItem, k as trimTrailingAssistantMessages, mt as historyItemFromPiMessage, n as loadTurnCheckpoint, p as assertTurnToolCallLimit, pt as getAgentContextInputLimitTokens, q as recordTurnRoute, r as saveTurnCheckpoint, t as continuableMessages, v as getTerminalAssistantMessages, w as isToolResultError, y as getUserMessageInstructionText, z as recordAttachmentsDelivered } from "./checkpoint-CmkbGGiR.js";
17
+ import { n as generateShortTitle, r as resolveTaskTitle } from "./short-title-XUBD7AYC.js";
18
+ import { A as sleep$1, D as fenceLock, E as acquireActiveLock, F as sandboxSkillDir, I as sandboxSkillFile, L as sandboxSkillPathResolution, M as SANDBOX_REPOS_ROOT, N as SANDBOX_SKILLS_ROOT, P as SANDBOX_WORKSPACE_ROOT, _ 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_DATA_ROOT, k as withLock, 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-6veboDue.js";
19
+ import { $ as workspaceSnapshotFinishedEvent, B as createEventAutomation, C as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, D as eventAutomationMatchesDestination, E as eventAutomationListToolResultSchema, F as effectiveTaskOutcomes, Gt as makeStructuredToolOutput, I as moveTaskOutcomes, Jt as ToolInputError, L as resolveTaskOutcomes, M as requireEventAutomationSlackContext, N as requireSupportedEventAutomationTrigger, O as eventAutomationToolResult, P as writableEventAutomation, Q as WORKSPACE_SNAPSHOT_READY_EVENT, R as taskOutcomeInputSchema, T as compactEventAutomation, Ut as injectContinuationToolName, V as deleteEventAutomation, W as getEventAutomation, Wt as juniorToolOutputSchema, X as getEventCatalog, Y as saveEventAutomation, Z as WORKSPACE_SNAPSHOT_FAILED_EVENT, at as normalizeCatalogEventIdentifier, c as parseSlackThreadId, ct as registeredEventTypeSchema, et as workspaceSnapshotWatch, f as createScheduledAutomation, g as listScheduledAutomationsForTeam, i as readLiveAttachment, it as hasPluginEventCatalogEntries, j as registeredEventAutomationTriggerSchema, k as eventAutomationToolResultSchema, lt as registeredResourceTypeSchema, nt as eventNamespaceSchema, ot as pluginSupportsEvent, pt as appendAndEnqueueInboundMessage, q as listEventAutomationsForTeam, rt as hasEventCatalogEntries, s as storeAttachments, st as registeredEventMatchSchema, t as incrementStat, tt as eventGuidance, ut as requireSupportedEventMatch, v as readScheduledAutomation, y as saveScheduledAutomation } from "./stats-BvNqVRdB.js";
20
+ import { _ as isTurnInputCommitLostError, c as sanitizeAssistantText, f as CooperativeTurnYieldError, l as NO_REPLY_MARKER, n as canReusePendingAuthLink, o as decideReply, p as TurnInputCommitLostError, s as getAssistantReplyText, t as abandonReplacedPendingAuth, u as isNoReplyMarker } from "./pending-auth-HNSPyxoN.js";
21
+ import { C as toolInvocationDestination, S as surfaceFromRun, _ as uploadFilesToConversation, b as assertRunConsistency, h as postSlackMessage, i as formatProviderLabel, m as getSlackMessagePermalink, o as resolveBaseUrl, p as addReactionToMessage, r as deliverOAuthAuthorization, s as startOAuthFlow, v as RetryableDeliveryError, x as isAgentRunFeatureDisabled, y as actorFromRun } from "./agent-runner-DCj_cPjl.js";
22
22
  import { r as EVENT_AUTHOR_ID } from "./prompt-DAoaq0CT.js";
23
- 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-BcoTZROi.js";
23
+ 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-DprAzyQN.js";
24
24
  import { t as getVercelConversationWorkQueue } from "./vercel-queue-DIkVcfK4.js";
25
- import { a as getTurnRequestDeadline, n as sendNextWorkspaceSnapshotJob, r as sendWorkspaceSnapshotJob } from "./job-queue-FDxeYtda.js";
25
+ import { a as getTurnRequestDeadline, n as sendNextWorkspaceSnapshotJob, r as sendWorkspaceSnapshotJob } from "./job-queue-C8FZ3LSY.js";
26
26
  import { n as privateTraceResultAttributes } from "./private-trace-result-BLvBjy_e.js";
27
27
  import { streamSimple } from "@earendil-works/pi-ai/compat";
28
28
  import { createGatewayProvider } from "@ai-sdk/gateway";
@@ -1501,13 +1501,87 @@ const SKILL_POLICY_RULES = [
1501
1501
  "- Otherwise, scan `<available-skills>` before acting. Load the most specific skill whose description matches the request; do not answer from memory when one fits. Only call `loadSkill` with an exact listed `<name>`; if none fits, do not load a skill.",
1502
1502
  "- Load one skill at a time. After `loadSkill`, follow the instructions returned by that tool result."
1503
1503
  ];
1504
- const EXECUTION_CONTRACT_RULES = [
1504
+ const PLANNING_RULES = `You have access to an \`updatePlan\` tool which tracks steps and progress and renders them to the user. Using the tool helps demonstrate that you've understood the task and convey how you're approaching it. Plans can help to make complex, ambiguous, or multi-phase work clearer and more collaborative for the user. A good plan should break the task into meaningful, logically ordered steps that are easy to verify as you go.
1505
+
1506
+ Note that plans are not for padding out simple work with filler steps or stating the obvious. The content of your plan should not involve doing anything that you aren't capable of doing (i.e. don't try to test things that you can't test). Do not use plans for simple or single-step queries that you can just do or answer immediately.
1507
+
1508
+ Do not repeat the full contents of the plan after an \`updatePlan\` call — the harness already displays it. Instead, summarize the change made and highlight any important context or next step.
1509
+
1510
+ Before running a command, consider whether or not you have completed the previous step, and make sure to mark it as completed before moving on to the next step. It may be the case that you complete all steps in your plan after a single pass of implementation. If this is the case, you can simply mark all the planned steps as completed. Sometimes, you may need to change plans in the middle of a task: call \`updatePlan\` with the updated plan and make sure to provide an \`explanation\` of the rationale when doing so.
1511
+
1512
+ Use a plan when:
1513
+
1514
+ - The task is non-trivial and will require multiple actions over a long time horizon.
1515
+ - There are logical phases or dependencies where sequencing matters.
1516
+ - The work has ambiguity that benefits from outlining high-level goals.
1517
+ - You want intermediate checkpoints for feedback and validation.
1518
+ - When the user asked you to do more than one thing in a single prompt
1519
+ - The user has asked you to use the plan tool (aka "TODOs")
1520
+ - You generate additional steps while working, and plan to do them before yielding to the user
1521
+
1522
+ ### Examples
1523
+
1524
+ **High-quality plans**
1525
+
1526
+ Example 1:
1527
+
1528
+ 1. Add CLI entry with file args
1529
+ 2. Parse Markdown via CommonMark library
1530
+ 3. Apply semantic HTML template
1531
+ 4. Handle code blocks, images, links
1532
+ 5. Add error handling for invalid files
1533
+
1534
+ Example 2:
1535
+
1536
+ 1. Define CSS variables for colors
1537
+ 2. Add toggle with localStorage state
1538
+ 3. Refactor components to use variables
1539
+ 4. Verify all views for readability
1540
+ 5. Add smooth theme-change transition
1541
+
1542
+ Example 3:
1543
+
1544
+ 1. Set up Node.js + WebSocket server
1545
+ 2. Add join/leave broadcast events
1546
+ 3. Implement messaging with timestamps
1547
+ 4. Add usernames + mention highlighting
1548
+ 5. Persist messages in lightweight DB
1549
+ 6. Add typing indicators + unread count
1550
+
1551
+ **Low-quality plans**
1552
+
1553
+ Example 1:
1554
+
1555
+ 1. Create CLI tool
1556
+ 2. Add Markdown parser
1557
+ 3. Convert to HTML
1558
+
1559
+ Example 2:
1560
+
1561
+ 1. Add dark mode toggle
1562
+ 2. Save preference
1563
+ 3. Make styles look good
1564
+
1565
+ Example 3:
1566
+
1567
+ 1. Create single-file HTML game
1568
+ 2. Run quick sanity check
1569
+ 3. Summarize usage instructions
1570
+
1571
+ If you need to write a plan, only write high quality plans, not low quality ones.
1572
+ `.split("\n");
1573
+ const UPDATE_PLAN_RULES = `A tool named \`updatePlan\` is available to you. You can use it to keep an up‑to‑date, step‑by‑step plan for the task.
1574
+
1575
+ To create a new plan, call \`updatePlan\` with a short list of 1‑sentence steps (no more than 5-7 words each) with a \`status\` for each step (\`pending\`, \`in_progress\`, or \`completed\`).
1576
+
1577
+ When steps have been completed, use \`updatePlan\` to mark each finished step as \`completed\` and the next step you are working on as \`in_progress\`. There should always be exactly one \`in_progress\` step until everything is done. You can mark multiple items as complete in a single \`updatePlan\` call.
1578
+
1579
+ If all steps are complete, ensure you call \`updatePlan\` to mark all steps as \`completed\`.`.split("\n");
1580
+ const TASK_EXECUTION_RULES = [
1505
1581
  "- Actionable request: act in this turn.",
1506
1582
  "- Continue until done or genuinely blocked. Do not finish with a plan, promise, or offer to check next when an available tool or source can move the request forward.",
1507
- "- Complete the full task, but report only the result and evidence the user needs; do not narrate every step, check, or detail.",
1508
1583
  "- Ask the user only for missing access, approval, or a decision that blocks safe progress. Ask one focused question; otherwise infer conservatively and continue.",
1509
1584
  "- For conflicting evidence, compare sources and state which source is authoritative for the answer.",
1510
- "- Use `reportProgress` only for work with multiple substantive phases or a materially long wait. Skip short lookups and routine commands; after an initial update, call it again only when the major phase changes.",
1511
1585
  "- A tool result with `timed_out: true` means that attempt did not finish. Continue the active task. Before retrying work that may have side effects, inspect authoritative state and do not repeat a mutation that already applied."
1512
1586
  ];
1513
1587
  const CONVERSATION_RULES = [
@@ -1545,12 +1619,14 @@ function buildBehaviorSection(platform) {
1545
1619
  renderRuleSection("tool-policy", TOOL_POLICY_RULES),
1546
1620
  renderRuleSection("tool-call-style", TOOL_CALL_STYLE_RULES),
1547
1621
  renderRuleSection("skill-policy", SKILL_POLICY_RULES),
1548
- renderRuleSection("execution-contract", EXECUTION_CONTRACT_RULES),
1622
+ renderRuleSection("planning", PLANNING_RULES),
1623
+ renderRuleSection("task-execution", TASK_EXECUTION_RULES),
1549
1624
  renderRuleSection("conversation", CONVERSATION_RULES),
1550
1625
  renderRuleSection("safety", SAFETY_RULES),
1551
- renderRuleSection("failure-handling", FAILURE_RULES)
1626
+ renderRuleSection("failure-handling", FAILURE_RULES),
1627
+ renderRuleSection("update-plan", UPDATE_PLAN_RULES)
1552
1628
  ];
1553
- if (platform === "slack") sections.splice(5, 0, renderRuleSection("slack-actions", SLACK_ACTION_RULES));
1629
+ if (platform === "slack") sections.splice(6, 0, renderRuleSection("slack-actions", SLACK_ACTION_RULES));
1554
1630
  return sections.join("\n\n");
1555
1631
  }
1556
1632
  function buildOutputSection(platform) {
@@ -7377,6 +7453,41 @@ function createReportProgressTool() {
7377
7453
  });
7378
7454
  }
7379
7455
  //#endregion
7456
+ //#region src/chat/tools/runtime/update-plan.ts
7457
+ const planItemSchema = z.object({
7458
+ step: z.string().describe("Task step text."),
7459
+ status: z.enum([
7460
+ "pending",
7461
+ "in_progress",
7462
+ "completed"
7463
+ ]).describe("Step status.")
7464
+ }).strict();
7465
+ const updatePlanInputSchema = z.object({
7466
+ explanation: z.string().optional().describe("Optional explanation for this plan update."),
7467
+ plan: z.array(planItemSchema).describe("The list of steps")
7468
+ }).strict();
7469
+ /** Create the internal tool the model uses to replace its task plan. */
7470
+ function createUpdatePlanTool() {
7471
+ return zodTool({
7472
+ annotations: {
7473
+ destructiveHint: false,
7474
+ idempotentHint: true,
7475
+ openWorldHint: false,
7476
+ readOnlyHint: false
7477
+ },
7478
+ description: [
7479
+ "Updates the task plan.",
7480
+ "Provide an optional explanation and a list of plan items, each with a step and status.",
7481
+ "At most one step can be in_progress at a time."
7482
+ ].join("\n"),
7483
+ inputSchema: updatePlanInputSchema,
7484
+ execute: async () => ({ content: [{
7485
+ type: "text",
7486
+ text: "Plan updated"
7487
+ }] })
7488
+ });
7489
+ }
7490
+ //#endregion
7380
7491
  //#region src/chat/agent-invocations/errors.ts
7381
7492
  /** Named child cannot accept another invocation until its active work ends. */
7382
7493
  var AgentInvocationBusyError = class extends Error {
@@ -13408,6 +13519,7 @@ function createTools(availableSkills, hooks = {}, context, options = {}) {
13408
13519
  const eventCatalog = getEventCatalog();
13409
13520
  const tools = {
13410
13521
  ...options.includeLoadSkill === false ? void 0 : { loadSkill: createLoadSkillTool(availableSkills, { onSkillLoaded: hooks.onSkillLoaded }) },
13522
+ updatePlan: createUpdatePlanTool(),
13411
13523
  reportProgress: createReportProgressTool(),
13412
13524
  systemTime: createSystemTimeTool(),
13413
13525
  bash: createBashTool(),
@@ -13500,6 +13612,11 @@ function createTools(availableSkills, hooks = {}, context, options = {}) {
13500
13612
  }
13501
13613
  //#endregion
13502
13614
  //#region src/chat/runtime/report-progress.ts
13615
+ function isActivePlanItem(value) {
13616
+ if (!value || typeof value !== "object") return false;
13617
+ const item = value;
13618
+ return item.status === "in_progress" && typeof item.step === "string" && item.step.trim().length > 0;
13619
+ }
13503
13620
  /** Convert a `reportProgress` tool payload into assistant status text. */
13504
13621
  function buildReportedProgressStatus(input) {
13505
13622
  if (!input || typeof input !== "object") return;
@@ -13509,8 +13626,16 @@ function buildReportedProgressStatus(input) {
13509
13626
  if (!text) return;
13510
13627
  return { text };
13511
13628
  }
13512
- /** Recover the latest explicit progress update from a resumable Pi transcript. */
13513
- function latestReportedProgress(messages) {
13629
+ /** Convert an `updatePlan` payload into the active assistant status. */
13630
+ function buildPlanStatus(input) {
13631
+ if (!input || typeof input !== "object") return;
13632
+ const plan = input.plan;
13633
+ if (!Array.isArray(plan)) return;
13634
+ const active = plan.find(isActivePlanItem);
13635
+ return active ? { text: active.step.trim() } : void 0;
13636
+ }
13637
+ /** Recover the latest progress status from a resumable Pi transcript. */
13638
+ function latestProgressStatus(messages) {
13514
13639
  for (let messageIndex = messages.length - 1; messageIndex >= 0; messageIndex -= 1) {
13515
13640
  const message = messages[messageIndex];
13516
13641
  if (message.role !== "assistant" || !Array.isArray(message.content)) continue;
@@ -13518,9 +13643,12 @@ function latestReportedProgress(messages) {
13518
13643
  const part = message.content[partIndex];
13519
13644
  if (!part || typeof part !== "object") continue;
13520
13645
  const toolCall = part;
13521
- if (toolCall.type !== "toolCall" || toolCall.name !== "reportProgress") continue;
13522
- const status = buildReportedProgressStatus(toolCall.arguments);
13523
- if (status) return status;
13646
+ if (toolCall.type !== "toolCall") continue;
13647
+ if (toolCall.name === "updatePlan") return buildPlanStatus(toolCall.arguments);
13648
+ if (toolCall.name === "reportProgress") {
13649
+ const status = buildReportedProgressStatus(toolCall.arguments);
13650
+ if (status) return status;
13651
+ }
13524
13652
  }
13525
13653
  }
13526
13654
  }
@@ -14457,8 +14585,7 @@ function createPiAgentTools(tools, sandbox, spanContext, onStatus, sandboxTools,
14457
14585
  return normalized;
14458
14586
  };
14459
14587
  const reportStatus = async (executionToolName, params) => {
14460
- if (executionToolName !== "reportProgress") return;
14461
- const status = buildReportedProgressStatus(params);
14588
+ const status = executionToolName === "updatePlan" ? buildPlanStatus(params) : executionToolName === "reportProgress" ? buildReportedProgressStatus(params) : void 0;
14462
14589
  if (status) await onStatus?.(status);
14463
14590
  };
14464
14591
  return Object.entries(visibleTools).map(([toolName, toolDef]) => ({
@@ -16528,22 +16655,74 @@ function createResumeState(args) {
16528
16655
  };
16529
16656
  }
16530
16657
  //#endregion
16658
+ //#region src/chat/services/plan-continuation.ts
16659
+ const OPEN_PLAN_TAG = "open-plan";
16660
+ function openItems(input) {
16661
+ const plan = input && typeof input === "object" ? input.plan : void 0;
16662
+ if (!Array.isArray(plan)) return [];
16663
+ return plan.flatMap((value) => {
16664
+ const item = value;
16665
+ if (typeof item?.step !== "string" || item.status !== "pending" && item.status !== "in_progress") return [];
16666
+ return [{
16667
+ step: item.step,
16668
+ status: item.status
16669
+ }];
16670
+ });
16671
+ }
16672
+ function messageText$1(message) {
16673
+ const content = message.content;
16674
+ if (!Array.isArray(content)) return typeof content === "string" ? content : "";
16675
+ return content.flatMap((part) => {
16676
+ const text = part?.text;
16677
+ return typeof text === "string" ? [text] : [];
16678
+ }).join("\n");
16679
+ }
16680
+ function retainedOpenItems(message) {
16681
+ const text = messageText$1(message);
16682
+ if (!isCompactionSummaryText(text)) return;
16683
+ const continuation = unwrapCurrentInstruction(text) ?? text;
16684
+ const open = `<${OPEN_PLAN_TAG}>\n`;
16685
+ const close = `\n</${OPEN_PLAN_TAG}>`;
16686
+ const closeIndex = continuation.lastIndexOf(close);
16687
+ const openIndex = continuation.lastIndexOf(open, closeIndex);
16688
+ if (openIndex < 0 || closeIndex < 0) return;
16689
+ const payload = continuation.slice(openIndex + open.length, closeIndex);
16690
+ try {
16691
+ return openItems({ plan: JSON.parse(payload) });
16692
+ } catch {
16693
+ return;
16694
+ }
16695
+ }
16696
+ /** Read open items from the latest successful plan state. */
16697
+ function latestOpenPlanItems(messages) {
16698
+ const successfulCalls = /* @__PURE__ */ new Set();
16699
+ for (let messageIndex = messages.length - 1; messageIndex >= 0; messageIndex -= 1) {
16700
+ const message = messages[messageIndex];
16701
+ if (message.role === "toolResult" && message.toolName === "updatePlan" && typeof message.toolCallId === "string" && message.isError !== true) {
16702
+ successfulCalls.add(message.toolCallId);
16703
+ continue;
16704
+ }
16705
+ if (message.role === "user") {
16706
+ const retained = retainedOpenItems(messages[messageIndex]);
16707
+ if (retained) return retained;
16708
+ }
16709
+ if (message.role !== "assistant" || !Array.isArray(message.content)) continue;
16710
+ for (let partIndex = message.content.length - 1; partIndex >= 0; partIndex -= 1) {
16711
+ const call = message.content[partIndex];
16712
+ if (call?.type === "toolCall" && call.name === "updatePlan" && typeof call.id === "string" && successfulCalls.has(call.id)) return openItems(call.arguments);
16713
+ }
16714
+ }
16715
+ return [];
16716
+ }
16717
+ /** Append exact open plan state to continuation text. */
16718
+ function appendOpenPlan(continuation, messages) {
16719
+ const plan = latestOpenPlanItems(messages);
16720
+ return plan.length === 0 ? continuation : `${continuation}\n\n<${OPEN_PLAN_TAG}>\n${JSON.stringify(plan)}\n</${OPEN_PLAN_TAG}>`;
16721
+ }
16722
+ //#endregion
16531
16723
  //#region src/chat/services/context-compaction.ts
16532
- /**
16533
- * Context compaction.
16534
- *
16535
- * This module bounds visible Pi history for long conversations. It strips
16536
- * runtime-only turn context before summarizing and opens replacement epochs in
16537
- * the durable event store. Capacity compaction retains recent user intent;
16538
- * handoff starts a profile-bound epoch with only its summary. Normal checkpoints
16539
- * may later append the current bootstrap; future replacement strips it again.
16540
- */
16541
16724
  const RETAINED_USER_MESSAGE_TOKENS = 2e4;
16542
- const MAX_SUMMARY_INPUT_CHARS = 8e4;
16543
- const MAX_VISIBLE_CONTEXT_CHARS = 2e4;
16544
16725
  const MAX_SUMMARY_CHARS = 6e3;
16545
- const MAX_RENDERED_MESSAGE_CHARS = 4e3;
16546
- const OMITTED_OLDER_CONTEXT_NOTICE = "[older context omitted]";
16547
16726
  /** Raised when Junior cannot compact history below the active model's hard ceiling. */
16548
16727
  var ContextInputLimitExceededError = class extends Error {
16549
16728
  estimatedTokens;
@@ -16558,7 +16737,7 @@ var ContextInputLimitExceededError = class extends Error {
16558
16737
  function textPart(value) {
16559
16738
  if (value && typeof value === "object" && value.type === "text" && typeof value.text === "string") return value.text;
16560
16739
  }
16561
- /** Render Pi message text for compaction without retaining prompt-only wrappers. */
16740
+ /** Render Pi message text for retained user-message selection. */
16562
16741
  function messageText(message) {
16563
16742
  const content = message.content;
16564
16743
  const unwrapTask = message.role === "user";
@@ -16660,71 +16839,37 @@ function selectRetainedUserMessageEntries(messages, maxTokens = RETAINED_USER_ME
16660
16839
  }
16661
16840
  return selected.reverse();
16662
16841
  }
16663
- function renderMessageForSummary(message) {
16664
- const role = message.role;
16665
- if (typeof role !== "string") return;
16666
- const text = sanitizeText(messageText(message));
16667
- if (!text) return;
16668
- return `[${role}] ${text.length > MAX_RENDERED_MESSAGE_CHARS ? `${text.slice(0, MAX_RENDERED_MESSAGE_CHARS).trimEnd()}...` : text}`;
16669
- }
16670
- function keepTail(text, maxChars) {
16671
- if (text.length <= maxChars) return text;
16672
- const prefix = `${OMITTED_OLDER_CONTEXT_NOTICE}\n`;
16673
- return `${prefix}${text.slice(Math.max(0, text.length - maxChars + prefix.length))}`;
16674
- }
16675
- function renderSummaryInput(piMessages, conversationContext) {
16676
- const lines = [];
16677
- const visibleContext = conversationContext?.trim();
16678
- if (visibleContext) lines.push("<visible-thread-context>", keepTail(visibleContext, MAX_VISIBLE_CONTEXT_CHARS), "</visible-thread-context>", "");
16679
- const renderedPiMessages = stripRuntimeTurnContext(piMessages).map(renderMessageForSummary).filter((line) => Boolean(line));
16680
- if (renderedPiMessages.length > 0) {
16681
- const piHistory = keepTail(renderedPiMessages.join("\n"), Math.max(1, MAX_SUMMARY_INPUT_CHARS - lines.join("\n").length - 28));
16682
- lines.push("<pi-history>", piHistory, "</pi-history>");
16683
- }
16684
- return keepTail(lines.join("\n"), MAX_SUMMARY_INPUT_CHARS);
16685
- }
16686
16842
  /** Ask the fast model for a bounded continuation summary of durable context. */
16687
16843
  async function summarizeContext(args, deps) {
16688
- const source = renderSummaryInput(args.piMessages, args.conversationContext);
16689
- const instructions = args.purpose === "active_turn" ? [
16690
- "You are performing an ACTIVE-TURN CONTEXT CHECKPOINT COMPACTION for Junior.",
16691
- "Create concise internal continuation state for the same agent run, which must continue the unfinished task immediately after this checkpoint.",
16844
+ const instructions = [
16845
+ "You are performing a CONTEXT CHECKPOINT COMPACTION. Create a handoff summary for another LLM that will resume the task.",
16692
16846
  "",
16693
16847
  "Include:",
16694
- "- Work completed and concrete outcomes",
16695
- "- Exact work currently in progress",
16696
- "- The immediate next action",
16697
- "- Durable constraints, user preferences, IDs, URLs, artifacts, sandbox references, auth state, and unresolved blockers",
16698
- "",
16699
- "Do not write a user-facing reply or announce a plan.",
16700
- "Treat the task as complete only when the source history contains concrete evidence that every requested outcome occurred. Do not infer completion from intent, plans, progress, intermediate artifacts, or adjacent tool activity. If evidence is missing or ambiguous, preserve the task as unfinished and state the next required action."
16701
- ] : [
16702
- "You are performing a CONTEXT CHECKPOINT COMPACTION for Junior.",
16703
- "Create a concise continuation summary for the agent that will continue this Slack thread.",
16848
+ "- Current progress and key decisions made",
16849
+ "- Important context, constraints, or user preferences",
16850
+ "- What remains to be done (clear next steps)",
16851
+ "- Any critical data, examples, or references needed to continue",
16704
16852
  "",
16705
- "Include:",
16706
- "- Current outstanding asks",
16707
- "- Key decisions, completed work, and outcomes",
16708
- "- Durable constraints, user preferences, IDs, URLs, artifacts, canvas links, sandbox references, and auth state",
16709
- "- Clear next steps and unresolved blockers"
16710
- ];
16853
+ "Be concise, structured, and focused on helping the next LLM seamlessly continue the work."
16854
+ ].join("\n");
16855
+ const visibleContext = args.conversationContext?.trim();
16856
+ const labeledContext = visibleContext ? `<visible-thread-context>\n${visibleContext}\n</visible-thread-context>` : void 0;
16857
+ const history = stripRuntimeTurnContext(args.piMessages).filter((message) => [
16858
+ "user",
16859
+ "assistant",
16860
+ "toolResult"
16861
+ ].includes(message.role));
16711
16862
  const summary = (await deps.completeText({
16712
16863
  modelId: botConfig.fastModelId,
16713
16864
  messageAttributeMode: "metadata",
16714
16865
  temperature: 0,
16715
16866
  signal: args.signal,
16716
16867
  promptName: "junior.context_compaction",
16717
- messages: [{
16718
- role: "user",
16719
- content: [
16720
- ...instructions,
16721
- "",
16722
- "Do not invent details. Do not include raw secrets or credentials.",
16723
- "",
16724
- source
16725
- ].join("\n"),
16726
- timestamp: Date.now()
16727
- }],
16868
+ messages: [
16869
+ ...history,
16870
+ ...labeledContext ? [userMessage(labeledContext)] : [],
16871
+ userMessage(instructions)
16872
+ ],
16728
16873
  metadata: {
16729
16874
  modelId: botConfig.fastModelId,
16730
16875
  threadId: args.metadata?.threadId ?? "",
@@ -16812,7 +16957,8 @@ async function writeCompactedThreadContext(args, sourceMessages, summary, contex
16812
16957
  const eventStore = getConversationEventStore();
16813
16958
  const sourceProjection = await loadConversationProjection({ conversationId: args.conversationId });
16814
16959
  const retained = selectRetainedUserMessageEntries(trimTrailingAssistantMessages(sourceProjection.messages));
16815
- const replacement = [...retained.map((entry) => entry.message), userMessage(`${COMPACTION_SUMMARY_PREFIX}\n${summary}`)];
16960
+ const continuation = appendOpenPlan(summary, sourceMessages);
16961
+ const replacement = [...retained.map((entry) => entry.message), userMessage(`${COMPACTION_SUMMARY_PREFIX}\n${continuation}`)];
16816
16962
  const replacementInputTokens = estimateHistoryTokens(replacement);
16817
16963
  const replacementProvenance = buildReplacementProvenance({
16818
16964
  retained,
@@ -16865,7 +17011,8 @@ async function compactContextForHandoff(args, deps) {
16865
17011
  const contextMessage = runtimeContextMessage(args.runtimeContext);
16866
17012
  if (!contextMessage) throw new Error("Handoff requires the current runtime turn context");
16867
17013
  const generatedSummary = await summarizeContext(args, deps);
16868
- const summary = `${MODEL_HANDOFF_SUMMARY_PREFIX}\n${generatedSummary}`;
17014
+ const continuation = appendOpenPlan(generatedSummary, args.piMessages);
17015
+ const summary = `${MODEL_HANDOFF_SUMMARY_PREFIX}\n${continuation}`;
16869
17016
  const messages = [contextMessage, {
16870
17017
  role: "user",
16871
17018
  content: [{
@@ -16874,7 +17021,6 @@ async function compactContextForHandoff(args, deps) {
16874
17021
  }],
16875
17022
  timestamp: contextMessage.timestamp
16876
17023
  }];
16877
- const replacementMessages = stripRuntimeTurnContext(messages);
16878
17024
  args.signal?.throwIfAborted();
16879
17025
  await getConversationEventStore().replaceHistory(args.conversationId, {
16880
17026
  createdAtMs: Date.now(),
@@ -16885,7 +17031,7 @@ async function compactContextForHandoff(args, deps) {
16885
17031
  ...args.target.reasoningLevel ? { reasoningLevel: args.target.reasoningLevel } : void 0,
16886
17032
  ...args.triggeringToolCallId ? { triggeringToolCallId: args.triggeringToolCallId } : void 0,
16887
17033
  summary: generatedSummary,
16888
- replacementHistory: replacementMessages.map((replacementMessage) => ({ item: historyItemFromPiMessage(replacementMessage, contextProvenance) }))
17034
+ replacementHistory: messages.map((message) => ({ item: historyItemFromPiMessage(message, contextProvenance) }))
16889
17035
  }
16890
17036
  });
16891
17037
  return messages;
@@ -16912,8 +17058,7 @@ async function compactActiveContextIfNeeded(args, deps) {
16912
17058
  try {
16913
17059
  summary = await summarizeContext({
16914
17060
  ...args,
16915
- piMessages: args.piMessages,
16916
- purpose: "active_turn"
17061
+ piMessages: args.piMessages
16917
17062
  }, deps);
16918
17063
  } catch (error) {
16919
17064
  if (source.estimatedTokens >= inputLimitTokens) throw new ContextInputLimitExceededError(source.estimatedTokens, inputLimitTokens);
@@ -16927,21 +17072,31 @@ async function compactActiveContextIfNeeded(args, deps) {
16927
17072
  reason: "summary_failed"
16928
17073
  };
16929
17074
  }
16930
- const summaryMessage = userMessage(`${ACTIVE_TURN_COMPACTION_SUMMARY_PREFIX}\n${summary}`);
17075
+ const continuation = appendOpenPlan(summary, source.messages);
17076
+ const summaryMessage = userMessage(`${ACTIVE_TURN_COMPACTION_SUMMARY_PREFIX}\n${continuation}`);
16931
17077
  const retainedInstruction = pendingMessages.length === 0 ? await loadLastInstruction(args.conversationId) : void 0;
16932
17078
  const instructionMessages = retainedInstruction ? [retainedInstruction.message] : pendingMessages.map((entry) => entry.message);
16933
17079
  const instructionProvenance = retainedInstruction ? [retainedInstruction.provenance] : pendingMessages.map((entry) => entry.provenance);
16934
17080
  const instructionTimestamp = instructionMessages[0]?.timestamp;
16935
17081
  const contextMessage = runtimeContextMessage(retainRuntimeTurnContext(args.runtimeContextMessages ?? args.piMessages), typeof instructionTimestamp === "number" ? instructionTimestamp : void 0);
16936
- const messages = [
16937
- ...contextMessage ? [contextMessage] : [],
16938
- ...instructionMessages,
16939
- summaryMessage
17082
+ const replacement = [
17083
+ ...contextMessage ? [{
17084
+ message: contextMessage,
17085
+ provenance: contextProvenance
17086
+ }] : [],
17087
+ ...instructionMessages.map((message, index) => ({
17088
+ message,
17089
+ provenance: instructionProvenance[index],
17090
+ ...index === 0 && retainedInstruction ? { sourceEventSeq: retainedInstruction.sourceEventSeq } : void 0
17091
+ })),
17092
+ {
17093
+ message: summaryMessage,
17094
+ provenance: contextProvenance
17095
+ }
16940
17096
  ];
17097
+ const messages = replacement.map((entry) => entry.message);
16941
17098
  const replacementInputTokens = estimateHistoryTokens(messages);
16942
17099
  if (replacementInputTokens >= inputLimitTokens) throw new ContextInputLimitExceededError(replacementInputTokens, inputLimitTokens);
16943
- const replacementMessages = stripRuntimeTurnContext(messages);
16944
- if (replacementMessages.length !== 1 + instructionProvenance.length) throw new Error("persisted instruction provenance must align one-to-one with messages");
16945
17100
  args.signal?.throwIfAborted();
16946
17101
  await getConversationEventStore().replaceHistory(args.conversationId, {
16947
17102
  createdAtMs: Date.now(),
@@ -16960,13 +17115,10 @@ async function compactActiveContextIfNeeded(args, deps) {
16960
17115
  summaryChars: summary.length
16961
17116
  },
16962
17117
  summary,
16963
- replacementHistory: replacementMessages.map((message, index) => {
16964
- const provenance = index === replacementMessages.length - 1 ? contextProvenance : instructionProvenance[index];
16965
- return {
16966
- item: historyItemFromPiMessage(message, provenance),
16967
- ...index === 0 && retainedInstruction ? { sourceEventSeq: retainedInstruction.sourceEventSeq } : void 0
16968
- };
16969
- })
17118
+ replacementHistory: replacement.map((entry) => ({
17119
+ item: historyItemFromPiMessage(entry.message, entry.provenance),
17120
+ ...entry.sourceEventSeq === void 0 ? void 0 : { sourceEventSeq: entry.sourceEventSeq }
17121
+ }))
16970
17122
  }
16971
17123
  });
16972
17124
  setSpanAttributes({
@@ -18061,4 +18213,4 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
18061
18213
  }
18062
18214
  }
18063
18215
  //#endregion
18064
- export { AuthorizationFlowDisabledError as $, createAgentInvocationSchema as A, recordFinishedTurnForAutomatedLimit as B, renderBlockText as C, getNextRunAtMs as D, scheduledAutomationRunAttributes as E, ingestEvent as F, clearSandboxEgressSignals as G, normalizeSandboxEgressTracePropagationDomains as H, EVENT_WAIT_MS as I, parseSandboxEgressCredentialToken as J, consumeSandboxEgressAuthRequiredSignal as K, isEventMailboxMetadata as L, AgentInvocationLimitError as M, getMcpProviderErrorAttributes as N, agentBindingSchema as O, processWorkspaceSnapshotJob as P, isVisionImageMediaType as Q, renderTaskInput as R, renderAttachmentText as S, logScheduledAutomationRunSkipped as T, shouldPropagateSandboxEgressTrace as U, resolveSandboxEgressProviderForHost as V, SANDBOX_EGRESS_PROXY_PATH as W, createUserTokenStore as X, sandboxEgressSignalsResponseSchema as Y, buildSteeringPiMessage as Z, readPublicArtifact as _, deleteMcpAuthSession as a, readAttachmentVisionSummary as b, deleteMcpStoredOAuthCredentials as c, putMcpStoredOAuthCredentials as d, shouldEmitDevAgentTrace as et, PluginCredentialFailureError as f, publicArtifactHeaders as g, resolvePluginOAuthAccount as h, finalizeMcpAuthorization as i, AgentInvocationBusyError as j, agentInvocationSchema as k, getMcpAuthSession as l, latestReportedProgress as m, createContextCompactor as n, setConfigDefaults as nt, deleteMcpAuthSessionsForUserProvider as o, authorizationId as p, consumeSandboxEgressPermissionDeniedSignal as q, executeCredentialedEgressRequest as r, deleteMcpServerSessionId as s, executeAgentRun as t, getConfigDefaults as tt, getMcpStoredOAuthCredentials as u, unpublishedArtifactHeaders as v, listThreadReplies as w, recordSlackAttachment as x, lookupSlackUserProfile as y, maybePostAutomatedTurnLimitNotice as z };
18216
+ export { AuthorizationFlowDisabledError as $, createAgentInvocationSchema as A, recordFinishedTurnForAutomatedLimit as B, renderBlockText as C, getNextRunAtMs as D, scheduledAutomationRunAttributes as E, ingestEvent as F, clearSandboxEgressSignals as G, normalizeSandboxEgressTracePropagationDomains as H, EVENT_WAIT_MS as I, parseSandboxEgressCredentialToken as J, consumeSandboxEgressAuthRequiredSignal as K, isEventMailboxMetadata as L, AgentInvocationLimitError as M, getMcpProviderErrorAttributes as N, agentBindingSchema as O, processWorkspaceSnapshotJob as P, isVisionImageMediaType as Q, renderTaskInput as R, renderAttachmentText as S, logScheduledAutomationRunSkipped as T, shouldPropagateSandboxEgressTrace as U, resolveSandboxEgressProviderForHost as V, SANDBOX_EGRESS_PROXY_PATH as W, createUserTokenStore as X, sandboxEgressSignalsResponseSchema as Y, buildSteeringPiMessage as Z, readPublicArtifact as _, deleteMcpAuthSession as a, readAttachmentVisionSummary as b, deleteMcpStoredOAuthCredentials as c, putMcpStoredOAuthCredentials as d, shouldEmitDevAgentTrace as et, PluginCredentialFailureError as f, publicArtifactHeaders as g, resolvePluginOAuthAccount as h, finalizeMcpAuthorization as i, AgentInvocationBusyError as j, agentInvocationSchema as k, getMcpAuthSession as l, latestProgressStatus as m, createContextCompactor as n, setConfigDefaults as nt, deleteMcpAuthSessionsForUserProvider as o, authorizationId as p, consumeSandboxEgressPermissionDeniedSignal as q, executeCredentialedEgressRequest as r, deleteMcpServerSessionId as s, executeAgentRun as t, getConfigDefaults as tt, getMcpStoredOAuthCredentials as u, unpublishedArtifactHeaders as v, listThreadReplies as w, recordSlackAttachment as x, lookupSlackUserProfile as y, maybePostAutomatedTurnLimitNotice as z };
@@ -1,15 +1,15 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-B4FMCO8f.js";
2
- import { a as embedTexts, r as completeObject } from "./client-CI4MF188.js";
3
- import { C as withSpan, P as normalizeIdentityEmail, _ as setSpanAttributes, d as logInfo, f as logWarn, u as logException, v as setSpanStatus } from "./logging-X8-jOuNZ.js";
2
+ import { a as embedTexts, r as completeObject } from "./client-ciJRmcY5.js";
3
+ import { C as withSpan, P as normalizeIdentityEmail, _ as setSpanAttributes, d as logInfo, f as logWarn, u as logException, v as setSpanStatus } from "./logging-CHZ0aJXO.js";
4
4
  import { a as getClient$1 } from "./sentry-CgWZM_kV.js";
5
- import { t as canExposeConversationPayload } from "./conversation-privacy-Dr3jEHg8.js";
6
- import { a as getChatConfig, n as botConfig, s as getSlackBotToken } from "./config-CC2WLw37.js";
5
+ import { t as canExposeConversationPayload } from "./conversation-privacy-CLkpzAlt.js";
6
+ import { a as getChatConfig, n as botConfig, s as getSlackBotToken } from "./config-BMwzCmw-.js";
7
7
  import { n as defaultModelId } from "./model-profile-CZmVoGdX.js";
8
8
  import { _ as parseSlackMessageTs, c as isActorUserId, h as parseSlackTeamId, m as parseSlackChannelReferenceId, u as parseActorUserId } from "./context-Bplcgypl.js";
9
9
  import { n as juniorDestinations } from "./destinations-BeBiJeEM.js";
10
- import { C as juniorCodeRepositories, D as juniorIdentities, E as juniorConversations, O as juniorUsers, S as juniorCodeChanges, T as conversationReadColumns, _ as CONVERSATION_METRICS, g as juniorConversationBriefs, h as juniorConversationBindings, i as juniorWorkspaces, m as juniorConversationParticipants, n as juniorSnapshots, r as juniorWorkspaceRepos, t as createJuniorSqlExecutor, v as juniorConversationMetrics, x as juniorConversationAnnotations, y as juniorConversationEvents } from "./executor-DJBc9GHM.js";
10
+ import { C as juniorCodeRepositories, D as juniorIdentities, E as juniorConversations, O as juniorUsers, S as juniorCodeChanges, T as conversationReadColumns, _ as CONVERSATION_METRICS, g as juniorConversationBriefs, h as juniorConversationBindings, i as juniorWorkspaces, m as juniorConversationParticipants, n as juniorSnapshots, r as juniorWorkspaceRepos, t as createJuniorSqlExecutor, v as juniorConversationMetrics, x as juniorConversationAnnotations, y as juniorConversationEvents } from "./executor-D0xETqi8.js";
11
11
  import { B as historyReplacementSchema, C as conversationReportEventSchema, I as conversationEventDataSchema, K as usageSchema, M as conversationBriefSchema, N as parseBriefInput, V as newConversationEventSchema, z as decodeStoredConversationEvent } from "./conversation-BpqLg4MM.js";
12
- import { A as sleep$1, P as SANDBOX_WORKSPACE_ROOT, l as isSandboxMissingError, n as hash, v as getVercelSandboxCredentials, w as getStateAdapter, x as runNonInteractiveCommand } from "./profile-BygAXI52.js";
12
+ import { A as sleep$1, P as SANDBOX_WORKSPACE_ROOT, l as isSandboxMissingError, n as hash, v as getVercelSandboxCredentials, w as getStateAdapter, x as runNonInteractiveCommand } from "./profile-6veboDue.js";
13
13
  import { n as briefEntriesFromReportEvents, s as generateBrief, t as BRIEF_PROMPT } from "./prompt-DAoaq0CT.js";
14
14
  import { AsyncLocalStorage } from "node:async_hooks";
15
15
  import { z } from "zod";
@@ -1,9 +1,9 @@
1
- import { F as isRecord, d as logInfo, f as logWarn } from "./logging-X8-jOuNZ.js";
2
- import { h as normalizeSlackEmojiName } from "./config-CC2WLw37.js";
1
+ import { F as isRecord, d as logInfo, f as logWarn } from "./logging-CHZ0aJXO.js";
2
+ import { h as normalizeSlackEmojiName } from "./config-BMwzCmw-.js";
3
3
  import { _ as parseSlackMessageTs, g as parseSlackUserId } from "./context-Bplcgypl.js";
4
- import { G as isDmChannel, J as withSlackRetries, K as normalizeSlackConversationId, U as getSlackClient, n as applyPluginFormatMarkdown, un as parseDestination, z as SlackActionError } from "./agent-hooks-CbS_0qVT.js";
5
- import { n as pluginCatalogRuntime } from "./catalog-runtime-d65qfc1w.js";
6
- import { w as getStateAdapter } from "./profile-BygAXI52.js";
4
+ import { G as isDmChannel, J as withSlackRetries, K as normalizeSlackConversationId, U as getSlackClient, n as applyPluginFormatMarkdown, un as parseDestination, z as SlackActionError } from "./agent-hooks-BtGATjr2.js";
5
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-LUAIHslF.js";
6
+ import { w as getStateAdapter } from "./profile-6veboDue.js";
7
7
  import { r as isExperimentalFeatureEnabled } from "./experimental-CIXf7Uye.js";
8
8
  import { randomBytes } from "node:crypto";
9
9
  import { actorSchema, sourceSchema } from "@sentry/junior-plugin-api";