@sentry/junior 0.303.0 → 0.305.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-context-BdVnSuY5.js → adapter-context-BpvbUki8.js} +2 -2
- package/dist/{admin-AfeAdS3J.js → admin-CoDt35ny.js} +5 -5
- package/dist/{agent-runner-BP8_DLUv.js → agent-runner-C5d6rY5g.js} +600 -389
- package/dist/api/schema.d.ts +1 -1
- package/dist/api/schema.js +5 -5
- package/dist/api.d.ts +1 -1
- package/dist/api.js +59 -61
- package/dist/{app-Dd9v1mNx.d.ts → app-Cs157Zc5.d.ts} +5 -3
- package/dist/app.d.ts +1 -1
- package/dist/app.js +86 -82
- package/dist/{automation-D9MvhOWY.js → automation-CuA3yEcD.js} +1 -1
- package/dist/{background-compaction-queue-xaE05jxH.js → background-compaction-queue-BTqMIfTA.js} +7 -3
- package/dist/{briefs-D8i-dKTp.js → briefs-BRdznF7c.js} +11 -8
- package/dist/{catalog-runtime-d1EM6Z0V.js → catalog-runtime-J52Tej47.js} +1 -1
- package/dist/cli/chat.js +15 -15
- package/dist/cli/check.js +5 -5
- package/dist/cli/init.js +1 -1
- package/dist/cli/main.js +3 -3
- package/dist/cli/plugins.js +4 -4
- package/dist/cli/snapshot-create.js +5 -5
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +4 -4
- package/dist/{config-oGM7KA9M.js → config-CBZp0udd.js} +101 -7
- package/dist/{connections-BlikzEJv.js → connections-BYmuJ6Vm.js} +6 -6
- package/dist/{continue-in-slack-BZnYifiG.js → continue-in-slack-Cvot6S38.js} +8 -8
- package/dist/{conversation-CY1jnBiC.js → conversation-BOqdRtUx.js} +4 -12
- package/dist/{conversation-feed-BZJRk6UV.js → conversation-feed-CgpgP7yi.js} +35 -2
- package/dist/{conversation-privacy-Cx515ddM.js → conversation-privacy-D2pOzBNl.js} +10 -2
- package/dist/{conversation-turn-DAhRdX4m.js → conversation-turn-CI8WDpnK.js} +17 -17
- package/dist/{credential-sync-DfhmWFeo.js → credential-sync-COqnZ1Dx.js} +14 -14
- package/dist/{db-C-2tFxk3.js → db-DU84dCVu.js} +169 -6
- package/dist/{db-DPqcEM9_.d.ts → db-zbN5ZV_o.d.ts} +2 -2
- package/dist/{executor-NVfS8aQ2.js → executor-CFyrgOu1.js} +43 -9
- package/dist/{history-UZ3M2M9r.js → history-m2-ceTTX.js} +8 -2
- package/dist/{install-CHLrpRZc.js → install-CQ76CfRw.js} +2 -2
- package/dist/instrumentation.js +7 -3
- package/dist/{lineage-HGLhd_-N.js → lineage-DLd2UxVP.js} +2 -2
- package/dist/{logging-DiyqRLBx.js → logging-BPNTQVFu.js} +1 -1
- package/dist/{message-CkCOcbFH.js → message-BWJLeQ5e.js} +8 -8
- package/dist/{model-input-DmoPPtPE.js → model-input-DoM9Ht-d.js} +2 -2
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +5 -5
- package/dist/{oauth-callback-server-CIf_6YmA.js → oauth-callback-server-DeHbnAQl.js} +2 -2
- package/dist/{projection-DBq8tsA5.js → projection-CcFBVFUo.js} +552 -63
- package/dist/{prompt-D2KlJopL.js → prompt-C5LREK2p.js} +185 -12
- package/dist/{queue-DFaOscp5.js → queue-B2AAL3ym.js} +4 -4
- package/dist/{registry-Bu0Z9BEO.js → registry-BjZZqKqi.js} +1 -1
- package/dist/{resolve-DXuA3G0g.js → resolve-CeJgXuH1.js} +3 -3
- package/dist/{result-DpiNseDA.js → result-icDrueyB.js} +8 -8
- package/dist/{runner-iu1heRFv.js → runner-nVfMkMMB.js} +9 -9
- package/dist/{sandbox-egress-signals-2HFYDcQf.js → sandbox-egress-signals-H9vQ5qRf.js} +1 -1
- package/dist/{schema-DvfX3Gq_.js → schema-Bx0Mlo32.js} +3 -3
- package/dist/{schema-DHMOaRzC.d.ts → schema-CKcu-IK6.d.ts} +43 -11
- package/dist/{service-account-BcT5LR7V.js → service-account-DU5865XA.js} +6 -5
- package/dist/{service-account-xYkaQTrw.js → service-account-Dw06p3zm.js} +5 -5
- package/dist/{session-stop-BLLp1IP_.js → session-stop-uotLtp4g.js} +181 -59
- package/dist/{skills-CNAGH4ju.js → skills-Bex1EaO5.js} +2 -2
- package/dist/{slack-conversation-unfurl-DYnqe5ci.js → slack-conversation-unfurl-EPG3riWF.js} +12 -11
- package/dist/{spawn-cGasWW33.js → spawn-CoD3vDuS.js} +6 -6
- package/dist/{state-CDS6h_Wv.js → state-nCR4Muhn.js} +4 -4
- package/dist/{stop-DMMA67yT.js → stop-BFVd0P0m.js} +170 -65
- package/dist/{store-Dgs7Oe44.js → store-Ca6G962n.js} +5 -5
- package/dist/{task-queue-DcF0nhhz.js → task-queue-BLPZU6kC.js} +3 -3
- package/dist/{task-runner-BGXF7Fo7.js → task-runner-xsOPIxCZ.js} +7 -7
- package/dist/{thread-context-BPky1KBe.js → thread-context-BOvZhsKK.js} +8 -8
- package/dist/{turn-session-routing-DGvn9MSl.js → turn-session-routing-2bW2qfeb.js} +8 -8
- package/dist/{turn-user-message-19CkuUvM.js → turn-user-message-BrhuyYrH.js} +3 -3
- package/dist/{validation-lu1DgjNQ.js → validation-BnY9K5WB.js} +1 -1
- package/dist/{version-Uo3c94Dx.js → version-qROlRQGF.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-BPQHMx3-.js → viewer-CxUiOraX.js} +3 -3
- package/dist/{warmup-H8uLvW9e.js → warmup--Gkz7iB-.js} +79 -476
- package/dist/{worker-B-pM_-3K.js → worker-DJ8d9fmD.js} +7 -7
- package/migrations/0111_attachment_kinds.sql +14 -0
- package/migrations/0112_attachment_url_fill.sql +51 -0
- package/migrations/0113_attachment_url_index.sql +1 -0
- package/migrations/meta/0099_snapshot.json +102 -326
- package/migrations/meta/0111_snapshot.json +5011 -0
- package/migrations/meta/0112_snapshot.json +5011 -0
- package/migrations/meta/0113_snapshot.json +5033 -0
- package/migrations/meta/_journal.json +21 -0
- package/package.json +7 -7
|
@@ -1,39 +1,38 @@
|
|
|
1
|
-
import { $ as loadTurnCheckpoint, $
|
|
2
|
-
import {
|
|
3
|
-
import { C as summarizeMessageText, E as withSpan, H as runWithLogAttributes, S as setTags, T as withLogContext, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, d as logAudit, f as logError, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, l as getLogContextAttributesForSpan, m as logInfo, p as logException, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging-
|
|
1
|
+
import { $ as loadTurnCheckpoint, $o as storeDeferredAttachment, $t as TurnSliceLimitExceededError, Aa as updateSlackMessage, An as isStandaloneRuntimeContextMessage, B as getAgentContextInputLimitTokens, Ba as isWorkspaceSnapshotNotReadyError, Bn as TURN_CONTEXT_TAG, Cn as getTerminalAssistantMessages, Da as postSlackMessage, Ds as credentialAuditAttributes, En as hasTurnInput, Fa as isAlreadyExistsError, Fn as stripRuntimeTurnContext, Fs as getConfigDefaults, G as AuthPausePersistenceError, Ga as createSandboxEgressCredentialToken, H as PluginCredentialFailureError, Ha as clearSandboxEgressSignals, Ia as throwSandboxOperationError, In as trimTrailingAssistantMessages, J as abandonReplacedPendingAuth, Ja as buildSandboxEgressNetworkPolicy, Jo as readLiveAttachment, K as AuthorizationFlowDisabledError, L as calculateContextCompactionTargetTokens, La as wrapSandboxSetupError, Ln as CAPABILITY_SECTION_TAG, Mn as isToolResultMessage, Mr as getReviewItem, Ms as historyItemFromPiMessage, Ni as getDashboardReviewItemLink, Nn as normalizeToolNameFromResult, Ns as piMessageFromHistoryItem, On as isAssistantMessage, Os as credentialAuditSource, Pn as retainRuntimeTurnContext, Ps as projectConversationEvents, Q as continuableMessages, Qa as tryWorkspaceRepoCheckoutPath, Qo as storeAttachments, Qt as TurnBudgetExceededError, R as getAgentBackgroundCompactionMarkTokens, Rn as REQUEST_CONTEXT_SECTION_TAG, Sa as deleteSlackMessage, Sn as getPiMessageRole, T as resolveTaskTitle, U as createPluginAuthOrchestration, Ua as consumeSandboxEgressAuthRequiredSignal, Un as readParentAgentTask, Uo as readSlackAttachmentSource, V as createPluginEgress, Va as workspaceSnapshotNotReadyUserMessage, Vi as renderToolResultNudge, W as authorizationId, Wa as consumeSandboxEgressPermissionDeniedSignal, Wi as getWorkspace, Xt as GATED_TURN_LIMIT_WRAP_UP_MESSAGE, Y as canReusePendingAuthLink, Ya as resolveSandboxCommandEnvironment, Yn as createUserTokenStore, Za as SANDBOX_RUNTIME, Zt as TURN_LIMIT_WRAP_UP_MESSAGE, _n as CODE_MODE_CALL_STATUS_TEXT, ai as resolveChannelCapabilities, an as isAnswerToolName, ao as SANDBOX_COMMAND_PATH, as as isConversationScopedChannel, c as recordAgentsInstructionsUpdated, ca as formatProviderLabel, co as SANDBOX_SKILLS_ROOT, dn as sanitizeAssistantText, do as sandboxSkillFile, en as TurnToolCallLimitExceededError, eo as ToolInputError, es as SlackActionError, f as recordAuthorizationRequested, fn as NO_REPLY_TOOL_NAME, fo as sandboxSkillPathResolution, fs as sleep, g as recordToolExecutionStarted, gn as CODEMODE_TOOL_NAME, ha as normalizeSlackReplyMarkdown, hn as readNoReply, ho as runNonInteractiveCommand, hs as AttachmentSourceUnavailableError, i as loadConversationProjection, ia as getSandboxProvider, in as REPLY_TOOL_NAME, ja as uploadFilesToConversation, jn as isToolResultError, kn as isContinuablePiBoundary, l as recordAttachmentsDelivered, ln as decideReply, lo as SANDBOX_WORKSPACE_ROOT, m as recordMcpProviderConnected, mn as isLegacyNoReplyMarker, mo as buildNonInteractiveShellScript, nn as createTurnLimitGate, no as PluginToolDeniedError, nt as saveTurnCheckpoint, oi as getSlackToolContext, on as readTurnAnswer, oo as SANDBOX_DATA_ROOT, or as getPluginTools, p as recordGuardianActionReviewed, pa as escapeSlackMrkdwnText, po as buildCommandScript, q as AuthorizationPauseError, r as loadConnectedMcpProviders, ra as ensureDockerDaemon, rn as isTurnExecutionLimitExceededError, sa as deliverOAuthAuthorization, sn as remindMissingAnswer, ta as hash, to as isToolInputError, tr as createPluginHookRunner, ua as resolveBaseUrl, un as getAssistantReplyText, uo as sandboxSkillDir, vn as REPORT_BLOCKED_TOOL_NAME, vs as createConversationEmbedder, wn as getUserMessageInstructionText, ws as resolveUserTimezone, xa as addReactionToMessage, xn as extractAssistantText, yn as readBlockedReport, z as getAgentContextCompactionTriggerTokens, za as getWorkspaceSnapshotNotReadyError } from "./projection-CcFBVFUo.js";
|
|
2
|
+
import { $ as bufferBody, B as unwrapCurrentInstruction, F as textCharsForTokens, G as createProviderError, H as escapeXmlText, I as COMPACTION_SUMMARY_PREFIX, K as findProviderError, L as hasCompactedConversationContext, M as estimateMessagesTokens, N as estimateRequestOverheadTokens, P as estimateTextTokens, R as isCompactionSummaryText, U as ProviderError, V as escapeXml, W as createAssistantProviderError, X as isProviderRetryError, Y as isProviderRefusal, Z as getGatewayApiKey, b as GEN_AI_PROVIDER_NAME, j as requestPrefixAttributes, k as resolveGatewayModel, n as botConfig, q as getProviderErrorAttributes, v as toPiReasoningLevel, x as GEN_AI_SERVER_ADDRESS, y as normalizeSlackEmojiName } from "./config-CBZp0udd.js";
|
|
3
|
+
import { C as summarizeMessageText, E as withSpan, H as runWithLogAttributes, S as setTags, T as withLogContext, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, d as logAudit, f as logError, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, l as getLogContextAttributesForSpan, m as logInfo, p as logException, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging-BPNTQVFu.js";
|
|
4
4
|
import { g as withActiveSpan, i as getActiveSpan, m as startInactiveSpan } from "./sentry-CPbZjomA.js";
|
|
5
|
-
import { a as toCanonicalInputMessage, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-
|
|
5
|
+
import { a as toCanonicalInputMessage, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-D2pOzBNl.js";
|
|
6
6
|
import { f as parseSlackTeamId, n as createSlackActor, o as isUserActor, p as parseSlackUserId, v as parseSlackMessageTs } from "./actor-D2iXzvlN.js";
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import { d as contextProvenance, f as instructionActors, m as sameActorIdentity, p as instructionProvenanceFor } from "./history-
|
|
7
|
+
import { T as isPersonInput, X as getStateAdapter, a as getConversationStore, k as turnBehavior, nt as withLock, o as getDb, ot as addAgentTurnUsage, r as getConversationEventStore, s as getSqlExecutor, st as agentTurnCostUsd, ut as hasAgentTurnUsage, yt as sameDestination } from "./db-DU84dCVu.js";
|
|
8
|
+
import { L as juniorArtifacts, c as juniorReviewItemSlackCards, u as juniorAutomationRuns } from "./executor-CFyrgOu1.js";
|
|
9
|
+
import { d as contextProvenance, f as instructionActors, m as sameActorIdentity, p as instructionProvenanceFor } from "./history-m2-ceTTX.js";
|
|
10
10
|
import { a as listReferenceFiles } from "./package-discovery-x4AvVhMj.js";
|
|
11
|
-
import { c as fetchWithBoundedOAuthErrorBodies, d as actorLogContext, g as credentialUserSubjectId, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, s as OAuthProviderError } from "./registry-
|
|
12
|
-
import { n as pluginCatalogRuntime } from "./catalog-runtime-
|
|
13
|
-
import { a as parseSkillInvocation, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-
|
|
14
|
-
import { C as McpProviderError, D as getMcpAwareTelemetryMessage, E as getMcpAwareErrorType, O as getMcpProviderErrorAttributes, S as putMcpStoredOAuthCredentials, T as McpToolError, _ as getMcpServerSessionId, a as serviceAccountOnly, b as putMcpAuthSession, c as createMcpServiceAccountClientProvider, d as PluginMcpClient, f as deleteMcpAuthSession, g as getMcpAuthSession, i as serviceAccountAllows, k as toMcpProviderError, l as getMcpServiceAccountCredentials, m as deleteMcpServerSessionId, u as McpAuthorizationRequiredError, v as getMcpStoredOAuthCredentials, w as McpServiceAccountRequiredError, x as putMcpServerSessionId, y as patchMcpAuthSession } from "./service-account-
|
|
15
|
-
import { l as completeObject, u as completeText } from "./prompt-
|
|
16
|
-
import { a as readActorIdentityFromSql, i as readActorIdentity } from "./viewer-
|
|
17
|
-
import {
|
|
18
|
-
import { Q as
|
|
19
|
-
import { $ as
|
|
20
|
-
import { D as automationTitleSchema, E as automationInstructionToolSchema, F as compileScheduleIntent, I as scheduleIntentFromTool, O as taskOutcomeInputSchema, P as ScheduleIntentError, T as automationContextToolSchema, V as automationTaskDescription, j as SCHEDULED_AUTOMATION_SYSTEM_ACTOR } from "./automation-
|
|
21
|
-
import { G as readScheduledAutomation, K as saveScheduledAutomation, Q as createEventAutomation, V as createScheduledAutomation, it as saveEventAutomation, mt as automationRevision, t as resolveConversationRouting, tt as getEventAutomation } from "./turn-session-routing-
|
|
11
|
+
import { c as fetchWithBoundedOAuthErrorBodies, d as actorLogContext, g as credentialUserSubjectId, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, s as OAuthProviderError } from "./registry-BjZZqKqi.js";
|
|
12
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-J52Tej47.js";
|
|
13
|
+
import { a as parseSkillInvocation, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-Bex1EaO5.js";
|
|
14
|
+
import { C as McpProviderError, D as getMcpAwareTelemetryMessage, E as getMcpAwareErrorType, O as getMcpProviderErrorAttributes, S as putMcpStoredOAuthCredentials, T as McpToolError, _ as getMcpServerSessionId, a as serviceAccountOnly, b as putMcpAuthSession, c as createMcpServiceAccountClientProvider, d as PluginMcpClient, f as deleteMcpAuthSession, g as getMcpAuthSession, i as serviceAccountAllows, k as toMcpProviderError, l as getMcpServiceAccountCredentials, m as deleteMcpServerSessionId, u as McpAuthorizationRequiredError, v as getMcpStoredOAuthCredentials, w as McpServiceAccountRequiredError, x as putMcpServerSessionId, y as patchMcpAuthSession } from "./service-account-DU5865XA.js";
|
|
15
|
+
import { f as generateImages, h as NoAudioError, l as completeObject, m as transcribeFromUrl, u as completeText } from "./prompt-C5LREK2p.js";
|
|
16
|
+
import { a as readActorIdentityFromSql, i as readActorIdentity } from "./viewer-CxUiOraX.js";
|
|
17
|
+
import { W as MAX_ATTACHMENT_BYTES } from "./conversation-BOqdRtUx.js";
|
|
18
|
+
import { Q as getEventCatalog, R as resolveSlackReplyTarget, St as writeAgentHistory, _t as showsAgentsInstructions, bt as readAgentHistory, d as buildPromptInput, dt as AGENTS_REMOVAL_NOTICE, et as requireSlackChannelMessageScope, f as buildSteeringPiMessage, ft as AGENTS_REPLACEMENT_NOTICE, gt as renderAgentsInstructions, h as loadPromptTurnContext, ht as readRepositoryInstructions, it as slackChannelMessageTrigger, mt as findVisibleAgentsInstructions, pt as buildAgentsInstructionsMessage, u as assemblePrompt, ut as JUNIOR_PERSONALITY, vt as foldLeadingSystemMessages, xt as withAgentRequest, yt as foldSystemMessages } from "./session-stop-uotLtp4g.js";
|
|
19
|
+
import { $ as createBashTool, $n as createSlackPublicSearchTool, $r as requireToolCreator, A as createWebSearchTool, Ar as createSearchAutomationsTool, B as createSystemTimeTool, Br as automationTriggerChangesSchema, C as incrementStat, Ci as missingAutomationSkillReason, Cr as createSlackCanvasEditTool, D as requireReadyWorkspaceSnapshot, Dr as resolveWorkspacePath, Ei as resolveTaskOutcomes, Er as positiveInteger, F as userLookupIdentityProviders, Fr as zodToolDefinition, Ft as createRunOperatorSqlTool, G as createWriteFileTool, Gr as injectContinuationToolName, H as createSearchEventTypesTool, Hr as editedAutomationTask, Ir as automationIdForToolCall, It as createListWatchesTool, J as sliceFileContent, Jr as getConversationAccess, K as createReadFileTool, Kr as juniorToolOutputSchema, Lr as automationSkillToolSchema, M as createWatchTimerTool, Mr as createDeleteAutomationTool, N as createWatchEventsTool, Nr as AUTOMATIONS_TOOL_SOURCE, O as prepareWorkspaceSnapshot, Or as createOperationKey, P as createUserLookupTool, Pr as zodTool, Pt as createReadConversationEventTool, Q as editFile, Qr as requireToolCaller, R as createUpdateUserCustomizationTool, Rr as automationToolResult, S as createWorkspaceTools, Sr as createSlackCanvasReadTool, T as ensureWorkspaceSnapshotBuild, Ti as moveTaskOutcomes, Tr as isMissingPathError, U as createSearchConversationEventsTool, Ur as newAutomationTask, V as createStopWatchingResourcesTool, Vr as automationTriggerSchema, W as createSearchConversationsTool, Wn as createSetConversationSubscriptionTool, Wr as triggerKind, X as capToolResult, Xr as automationToolsDisabledReason, Y as TOOL_RESULT_MAX_CHARS, Yn as createSlackThreadReadTool, Yr as automationToolContext, Z as createEditFileTool, Zr as requireToolAutomation, _i as changedEventMatch, _t as createUpdateReviewItemTool, a as createCacheWarmingRecorder, ar as createSlackConversationSearchChannelPort, at as createReportBlockedTool, b as coreToolSlots, ct as createMessageAgentTool, dr as resolveSlackChannelRef, ei as requireToolDestination, er as createSlackListUpdateItemTool, et as createUpdatePlanTool, fr as slackChannelRefParam, gi as editEventAutomation, gt as createSearchReviewItemsTool, hi as editScheduledAutomation, ht as createAddReviewItemTool, in as isParentMessageMeta, ir as createSlackConversationMessageSearchTool, it as createReportProgressTool, j as createWebFetchTool, jr as createRunAutomationNowTool, kr as createCanvas, lt as createArchiveAgentTool, mr as joinPublicChannelForRead, ni as automationEditor, nr as createSlackListCreateTool, nt as createSpawnAgentTool, or as createSlackChannelListMessagesTool, ot as createReplyTool, pr as checkSlackChannelReadAccess, q as missingFileResult, qr as makeStructuredToolOutput, qt as listAgentInvocationsForConversation, ri as changeAutomationLifecycle, rr as createSlackListAddItemsTool, rt as createListAgentsTool, st as createNoReplyTool, tr as createSlackListGetItemsTool, tt as createStopAgentTool, ur as createSlackChannelJoinTool, vi as requireEventAutomationTrigger, wr as SLACK_TOOL_SOURCE, x as enabledMode, xi as requireAutomationSkill, xr as createSlackCanvasWriteTool, yi as requireAutomationTaskText, z as createSubmitFeedbackTool, zr as automationToolResultSchema } from "./warmup--Gkz7iB-.js";
|
|
20
|
+
import { D as automationTitleSchema, E as automationInstructionToolSchema, F as compileScheduleIntent, I as scheduleIntentFromTool, O as taskOutcomeInputSchema, P as ScheduleIntentError, T as automationContextToolSchema, V as automationTaskDescription, j as SCHEDULED_AUTOMATION_SYSTEM_ACTOR } from "./automation-CuA3yEcD.js";
|
|
21
|
+
import { G as readScheduledAutomation, K as saveScheduledAutomation, Q as createEventAutomation, V as createScheduledAutomation, it as saveEventAutomation, mt as automationRevision, t as resolveConversationRouting, tt as getEventAutomation } from "./turn-session-routing-2bW2qfeb.js";
|
|
22
22
|
import { a as USER_INPUT_LIMITS, i as AGENT_INVOCATION_STATUSES, m as detectImageMediaType, o as USER_INPUT_NOTE, s as buttonUserInputField, u as normalizeUserInputAnswer } from "./web-message-id-lNodcCOI.js";
|
|
23
|
-
import { d as isTurnInputCommitLostError, o as CooperativeTurnYieldError, s as TurnInputCommitLostError } from "./turn-user-message-
|
|
24
|
-
import { l as QUEUE_SIGNATURE_MAX_AGE_MS, n as backgroundCompactionId, o as getVercelConversationWorkQueue } from "./background-compaction-queue-
|
|
25
|
-
import { o as getSandboxResources, r as setSnapshotSpanAttributes } from "./install-
|
|
26
|
-
import { n as resolve$1 } from "./resolve-
|
|
27
|
-
import { t as runWithSlackInstallation } from "./adapter-context-
|
|
23
|
+
import { d as isTurnInputCommitLostError, o as CooperativeTurnYieldError, s as TurnInputCommitLostError } from "./turn-user-message-BrhuyYrH.js";
|
|
24
|
+
import { l as QUEUE_SIGNATURE_MAX_AGE_MS, n as backgroundCompactionId, o as getVercelConversationWorkQueue } from "./background-compaction-queue-BTqMIfTA.js";
|
|
25
|
+
import { o as getSandboxResources, r as setSnapshotSpanAttributes } from "./install-CQ76CfRw.js";
|
|
26
|
+
import { n as resolve$1 } from "./resolve-CeJgXuH1.js";
|
|
27
|
+
import { t as runWithSlackInstallation } from "./adapter-context-BpvbUki8.js";
|
|
28
28
|
import { n as privateTraceResultAttributes } from "./private-trace-result-CE7_lEdq.js";
|
|
29
29
|
import * as z from "zod";
|
|
30
30
|
import { streamSimple } from "@earendil-works/pi-ai/compat";
|
|
31
|
-
import { createGatewayProvider } from "@ai-sdk/gateway";
|
|
32
|
-
import { NoImageGeneratedError, generateImage } from "ai";
|
|
33
31
|
import path from "node:path";
|
|
34
32
|
import { isDeepStrictEqual } from "node:util";
|
|
35
33
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
36
34
|
import { createHash, randomBytes, randomInt, randomUUID } from "node:crypto";
|
|
35
|
+
import { createAssistantMessageEventStream, getInitialSystemMessage, getSystemMessageText as getSystemMessageText$1, isRetryableAssistantError, mergeClientIdentity } from "@earendil-works/pi-ai";
|
|
37
36
|
import { and, eq, inArray, isNull } from "drizzle-orm";
|
|
38
37
|
import { declaredEventKeys, missingToolAnnotationKeys, ownedObjectAnnotationSchema } from "@sentry/junior-plugin-api";
|
|
39
38
|
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
@@ -42,7 +41,6 @@ import fs from "node:fs/promises";
|
|
|
42
41
|
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
43
42
|
import { SignJWT, importPKCS8 } from "jose";
|
|
44
43
|
import { performance as performance$1 } from "node:perf_hooks";
|
|
45
|
-
import { createAssistantMessageEventStream, isRetryableAssistantError, mergeClientIdentity } from "@earendil-works/pi-ai";
|
|
46
44
|
import { Bash, defineCommand } from "just-bash";
|
|
47
45
|
import { Kind } from "@sinclair/typebox";
|
|
48
46
|
import { Value } from "@sinclair/typebox/value";
|
|
@@ -643,36 +641,6 @@ function serializeMcpPayload(payload, privacy, options = {}) {
|
|
|
643
641
|
if (privacy !== "private") return serializeGenAiAttribute(payload);
|
|
644
642
|
return options.privateMetadata ? serializeGenAiAttribute(toGenAiPayloadMetadata(payload)) : void 0;
|
|
645
643
|
}
|
|
646
|
-
// src/chat/pi/agent-history.ts
|
|
647
|
-
function isSystemMessage(message) {
|
|
648
|
-
return message.role === "system";
|
|
649
|
-
}
|
|
650
|
-
/** Return Junior history: the messages without Pi's system messages. */
|
|
651
|
-
function readAgentHistory(messages) {
|
|
652
|
-
return messages.filter((message) => !isSystemMessage(message));
|
|
653
|
-
}
|
|
654
|
-
/**
|
|
655
|
-
* Return the message list that replaces `current` with `history`. The leading
|
|
656
|
-
* system message of `current` stays first. System messages in `history` are
|
|
657
|
-
* dropped.
|
|
658
|
-
*/
|
|
659
|
-
function writeAgentHistory(current, history) {
|
|
660
|
-
const leading = current[0];
|
|
661
|
-
const messages = readAgentHistory(history);
|
|
662
|
-
return leading && isSystemMessage(leading) ? [leading, ...messages] : messages;
|
|
663
|
-
}
|
|
664
|
-
/**
|
|
665
|
-
* Give the stream path Junior's own system prompt and tools, with Junior
|
|
666
|
-
* history as the messages. The traced stream and cache warming then read the
|
|
667
|
-
* same request on every Pi version, without Pi's system messages.
|
|
668
|
-
*/
|
|
669
|
-
function withAgentRequest(base, request) {
|
|
670
|
-
return (model, context, options) => base(model, {
|
|
671
|
-
systemPrompt: request.systemPrompt,
|
|
672
|
-
messages: readAgentHistory(context.messages),
|
|
673
|
-
tools: request.tools
|
|
674
|
-
}, options);
|
|
675
|
-
}
|
|
676
644
|
// src/chat/agent/repository-context.ts
|
|
677
645
|
function findRestoredInstructions(messages, provenance) {
|
|
678
646
|
const restoredContext = messages?.map((message, index) => ({
|
|
@@ -3492,10 +3460,6 @@ function createImageGenerateTool(hooks, options, deps = {}) {
|
|
|
3492
3460
|
}),
|
|
3493
3461
|
outputSchema: imageGenerateOutputSchema,
|
|
3494
3462
|
execute: async ({ prompt, images = [] }) => {
|
|
3495
|
-
const gateway = createGatewayProvider({
|
|
3496
|
-
apiKey: await getGatewayApiKey(),
|
|
3497
|
-
...deps.fetch ? { fetch: deps.fetch } : void 0
|
|
3498
|
-
});
|
|
3499
3463
|
const model = options.modelId;
|
|
3500
3464
|
const { images: inputImages, resized } = await fitImagesToRequest(await Promise.all(images.map(async (path) => ({
|
|
3501
3465
|
path,
|
|
@@ -3505,22 +3469,20 @@ function createImageGenerateTool(hooks, options, deps = {}) {
|
|
|
3505
3469
|
resized_images: resized,
|
|
3506
3470
|
resize_notice: "Some input images were too large for the image model, so they were resized first. Tell the user which images were resized."
|
|
3507
3471
|
} : {};
|
|
3508
|
-
const enrichedPrompt = inputImages.length > 0 ? prompt : await enrichImagePrompt(prompt, options.
|
|
3509
|
-
|
|
3510
|
-
|
|
3511
|
-
|
|
3512
|
-
|
|
3513
|
-
|
|
3514
|
-
|
|
3515
|
-
|
|
3516
|
-
|
|
3517
|
-
|
|
3518
|
-
|
|
3519
|
-
|
|
3520
|
-
|
|
3521
|
-
|
|
3522
|
-
else throw error;
|
|
3523
|
-
}
|
|
3472
|
+
const enrichedPrompt = inputImages.length > 0 ? prompt : await enrichImagePrompt(prompt, options.modelCost);
|
|
3473
|
+
const { images: generatedImages } = await generateImages({
|
|
3474
|
+
operation: "image_generation",
|
|
3475
|
+
cost: options.modelCost,
|
|
3476
|
+
modelId: model,
|
|
3477
|
+
prompt: inputImages.length > 0 ? {
|
|
3478
|
+
text: enrichedPrompt,
|
|
3479
|
+
images: inputImages.map((image) => image.data)
|
|
3480
|
+
} : enrichedPrompt,
|
|
3481
|
+
fetch: deps.fetch
|
|
3482
|
+
}).catch((error) => {
|
|
3483
|
+
if (error instanceof Error && error.message.includes("not an image model")) throw new Error(`image generation failed: configured model "${model}" is not an image generation model. Set AI_IMAGE_MODEL to an AI Gateway image model.`, { cause: error });
|
|
3484
|
+
throw error;
|
|
3485
|
+
});
|
|
3524
3486
|
const uploads = generatedImages.map((image, index) => ({
|
|
3525
3487
|
data: Buffer.from(image.uint8Array),
|
|
3526
3488
|
filename: `generated-image-${Date.now()}-${index + 1}.${extensionForMediaType(image.mediaType)}`,
|
|
@@ -3550,6 +3512,430 @@ function createImageGenerateTool(hooks, options, deps = {}) {
|
|
|
3550
3512
|
}
|
|
3551
3513
|
});
|
|
3552
3514
|
}
|
|
3515
|
+
// src/chat/attachments/download.ts
|
|
3516
|
+
/** Refusal for a file over `MAX_ATTACHMENT_BYTES`. */
|
|
3517
|
+
const ATTACHMENT_TOO_LARGE_MESSAGE = `Attachment is larger than the ${MAX_ATTACHMENT_BYTES / 1024 / 1024} MB file limit.`;
|
|
3518
|
+
/** An attachment whose bytes cannot be read. The message is safe to show. */
|
|
3519
|
+
var AttachmentDownloadError = class extends Error {
|
|
3520
|
+
constructor(message, options) {
|
|
3521
|
+
super(message, options);
|
|
3522
|
+
this.name = "AttachmentDownloadError";
|
|
3523
|
+
}
|
|
3524
|
+
};
|
|
3525
|
+
/**
|
|
3526
|
+
* Look up the source file of an unstored row, with the size check done.
|
|
3527
|
+
* Errors that the person should see are `AttachmentDownloadError`.
|
|
3528
|
+
*/
|
|
3529
|
+
async function readSourceFile(attachment, readAttachmentSource) {
|
|
3530
|
+
const { source } = attachment;
|
|
3531
|
+
if (!source || !readAttachmentSource) throw new AttachmentDownloadError("Attachment cannot be downloaded from this conversation.");
|
|
3532
|
+
let file;
|
|
3533
|
+
try {
|
|
3534
|
+
file = await readAttachmentSource(source);
|
|
3535
|
+
} catch (error) {
|
|
3536
|
+
throw unavailableError(attachment, error);
|
|
3537
|
+
}
|
|
3538
|
+
if (file.bytes > 262144e3) throw new AttachmentDownloadError(ATTACHMENT_TOO_LARGE_MESSAGE);
|
|
3539
|
+
return {
|
|
3540
|
+
file,
|
|
3541
|
+
source
|
|
3542
|
+
};
|
|
3543
|
+
}
|
|
3544
|
+
function unavailableError(attachment, error) {
|
|
3545
|
+
return error instanceof AttachmentSourceUnavailableError ? new AttachmentDownloadError(`${attachment.filename} is no longer available: ${error.message}`, { cause: error }) : error;
|
|
3546
|
+
}
|
|
3547
|
+
/**
|
|
3548
|
+
* Find where the bytes of one attachment row are, without reading them.
|
|
3549
|
+
*
|
|
3550
|
+
* A stored file reads from storage. A large Slack file that no read has
|
|
3551
|
+
* stored yet downloads from its source on each `open`. The source reports
|
|
3552
|
+
* the current size, and the size check runs before any download. Errors that
|
|
3553
|
+
* the person should see are `AttachmentDownloadError`, from here or from
|
|
3554
|
+
* `open`. Callers that need the bytes more than once use
|
|
3555
|
+
* `storeAttachmentOnFirstUse` first.
|
|
3556
|
+
*
|
|
3557
|
+
* The row must come from a lookup scoped to the caller's conversation. The
|
|
3558
|
+
* source id comes from that row only, never from a request.
|
|
3559
|
+
*/
|
|
3560
|
+
async function readAttachmentContent(args) {
|
|
3561
|
+
const { attachment, storage } = args;
|
|
3562
|
+
const { storageKey } = attachment;
|
|
3563
|
+
if (storageKey !== null) return {
|
|
3564
|
+
bytes: attachment.bytes,
|
|
3565
|
+
open: async () => {
|
|
3566
|
+
const body = await storage.get(storageKey);
|
|
3567
|
+
if (!body) throw new AttachmentDownloadError("Stored attachment contents are unavailable.");
|
|
3568
|
+
return body;
|
|
3569
|
+
}
|
|
3570
|
+
};
|
|
3571
|
+
const { file } = await readSourceFile(attachment, args.readAttachmentSource);
|
|
3572
|
+
return {
|
|
3573
|
+
bytes: file.bytes,
|
|
3574
|
+
open: async () => {
|
|
3575
|
+
try {
|
|
3576
|
+
return await file.open();
|
|
3577
|
+
} catch (error) {
|
|
3578
|
+
throw unavailableError(attachment, error);
|
|
3579
|
+
}
|
|
3580
|
+
}
|
|
3581
|
+
};
|
|
3582
|
+
}
|
|
3583
|
+
/**
|
|
3584
|
+
* Return the row of one attachment with its bytes in storage.
|
|
3585
|
+
*
|
|
3586
|
+
* A large Slack file is recorded without its bytes. The first read that
|
|
3587
|
+
* needs them streams the file from its source into storage once, and later
|
|
3588
|
+
* reads use storage. The same rules as `readAttachmentContent` apply to the
|
|
3589
|
+
* row and to errors.
|
|
3590
|
+
*/
|
|
3591
|
+
async function storeAttachmentOnFirstUse(args) {
|
|
3592
|
+
const { attachment } = args;
|
|
3593
|
+
const { storageKey } = attachment;
|
|
3594
|
+
if (storageKey !== null) return {
|
|
3595
|
+
...attachment,
|
|
3596
|
+
storageKey
|
|
3597
|
+
};
|
|
3598
|
+
const { file, source } = await readSourceFile(attachment, args.readAttachmentSource);
|
|
3599
|
+
let stored;
|
|
3600
|
+
try {
|
|
3601
|
+
stored = await withSpan("attachment.store", "attachment.store", {}, async () => await storeDeferredAttachment({
|
|
3602
|
+
attachment: {
|
|
3603
|
+
...attachment,
|
|
3604
|
+
source
|
|
3605
|
+
},
|
|
3606
|
+
db: args.db,
|
|
3607
|
+
file,
|
|
3608
|
+
storage: args.storage
|
|
3609
|
+
}), {
|
|
3610
|
+
"app.attachment.source.provider": source.provider,
|
|
3611
|
+
"file.size": file.bytes
|
|
3612
|
+
});
|
|
3613
|
+
} catch (error) {
|
|
3614
|
+
throw unavailableError(attachment, error);
|
|
3615
|
+
}
|
|
3616
|
+
if (!stored) throw new AttachmentDownloadError(`${attachment.filename} is no longer available.`);
|
|
3617
|
+
return stored;
|
|
3618
|
+
}
|
|
3619
|
+
// src/chat/attachments/tool-params.ts
|
|
3620
|
+
/** Model-facing id of one attachment in the current Conversation. */
|
|
3621
|
+
const attachmentIdParam = z.string().min(1).describe("Stored attachment ID, as shown in attachment context or Slack read results.");
|
|
3622
|
+
// src/chat/tools/load-attachment.ts
|
|
3623
|
+
/** Sandbox directory for attachment files that tools write. */
|
|
3624
|
+
const ATTACHMENT_DIR = ".junior/attachments";
|
|
3625
|
+
/** Bytes held in memory and sent to the sandbox in one write. */
|
|
3626
|
+
const PART_BYTES = 8388608;
|
|
3627
|
+
const JOIN_PARTS_SCRIPT = "set -eu; out=$1; shift; cat -- \"$@\" > \"$out\"";
|
|
3628
|
+
/** Turn a read failure that the model can relay into a tool error. */
|
|
3629
|
+
function toolError(error) {
|
|
3630
|
+
return error instanceof AttachmentDownloadError ? new ToolInputError(error.message, { cause: error }) : error;
|
|
3631
|
+
}
|
|
3632
|
+
/** Run one sandbox command, and return its stdout. Throw when it fails. */
|
|
3633
|
+
async function runChecked(workspace, action, input) {
|
|
3634
|
+
const result = await workspace.runCommand(input);
|
|
3635
|
+
if (result.exitCode !== 0) throw new Error(`Failed to ${action}: ${result.stderr}`);
|
|
3636
|
+
return result.stdout;
|
|
3637
|
+
}
|
|
3638
|
+
/**
|
|
3639
|
+
* Write an attachment body to the sandbox in parts of at most `PART_BYTES`.
|
|
3640
|
+
*
|
|
3641
|
+
* The sandbox SDK writes only whole buffers, so this keeps one part in
|
|
3642
|
+
* memory, not the file. Returns the part paths in order.
|
|
3643
|
+
*/
|
|
3644
|
+
async function writeParts(args) {
|
|
3645
|
+
const parts = [];
|
|
3646
|
+
let pending = [];
|
|
3647
|
+
let pendingBytes = 0;
|
|
3648
|
+
let total = 0;
|
|
3649
|
+
const flush = async () => {
|
|
3650
|
+
const partPath = path.posix.join(args.partsDir, String(parts.length).padStart(4, "0"));
|
|
3651
|
+
await args.workspace.writeFiles([{
|
|
3652
|
+
content: Buffer.concat(pending),
|
|
3653
|
+
path: partPath
|
|
3654
|
+
}]);
|
|
3655
|
+
parts.push(partPath);
|
|
3656
|
+
pending = [];
|
|
3657
|
+
pendingBytes = 0;
|
|
3658
|
+
};
|
|
3659
|
+
const reader = args.body.getReader();
|
|
3660
|
+
try {
|
|
3661
|
+
for (;;) {
|
|
3662
|
+
const { done, value } = await reader.read();
|
|
3663
|
+
if (done) break;
|
|
3664
|
+
total += value.byteLength;
|
|
3665
|
+
if (total > args.expectedBytes) break;
|
|
3666
|
+
let chunk = value;
|
|
3667
|
+
while (pendingBytes + chunk.byteLength >= PART_BYTES) {
|
|
3668
|
+
const take = PART_BYTES - pendingBytes;
|
|
3669
|
+
pending.push(chunk.subarray(0, take));
|
|
3670
|
+
pendingBytes += take;
|
|
3671
|
+
await flush();
|
|
3672
|
+
chunk = chunk.subarray(take);
|
|
3673
|
+
}
|
|
3674
|
+
if (chunk.byteLength > 0) {
|
|
3675
|
+
pending.push(chunk);
|
|
3676
|
+
pendingBytes += chunk.byteLength;
|
|
3677
|
+
}
|
|
3678
|
+
}
|
|
3679
|
+
} finally {
|
|
3680
|
+
await reader.cancel().catch(() => void 0);
|
|
3681
|
+
}
|
|
3682
|
+
if (total !== args.expectedBytes) throw new Error(`Attachment ${args.attachmentId} read ${total} bytes, expected ${args.expectedBytes}.`);
|
|
3683
|
+
if (pendingBytes > 0 || parts.length === 0) await flush();
|
|
3684
|
+
return parts;
|
|
3685
|
+
}
|
|
3686
|
+
/**
|
|
3687
|
+
* Create a tool that restores one conversation attachment to the sandbox.
|
|
3688
|
+
*
|
|
3689
|
+
* The first load of a large Slack file streams it from Slack into storage
|
|
3690
|
+
* through the host. The sandbox never gets a Slack URL or token.
|
|
3691
|
+
*
|
|
3692
|
+
* @runBuilt loadAttachment
|
|
3693
|
+
*/
|
|
3694
|
+
function createLoadAttachmentTool(args) {
|
|
3695
|
+
return zodTool({
|
|
3696
|
+
description: "Load a stored attachment for this conversation into the sandbox.",
|
|
3697
|
+
annotations: {
|
|
3698
|
+
destructiveHint: false,
|
|
3699
|
+
idempotentHint: true,
|
|
3700
|
+
openWorldHint: true,
|
|
3701
|
+
readOnlyHint: false
|
|
3702
|
+
},
|
|
3703
|
+
inputSchema: z.object({ attachment_id: attachmentIdParam }),
|
|
3704
|
+
outputSchema: juniorToolOutputSchema,
|
|
3705
|
+
execute: async ({ attachment_id }) => {
|
|
3706
|
+
const attachment = await readLiveAttachment({
|
|
3707
|
+
attachmentId: attachment_id,
|
|
3708
|
+
conversationId: args.conversationId,
|
|
3709
|
+
db: args.db
|
|
3710
|
+
});
|
|
3711
|
+
if (!attachment || attachment.storageProvider !== args.storage.provider) throw new ToolInputError("Attachment not found in this conversation.");
|
|
3712
|
+
if (attachment.bytes > 262144e3) throw new ToolInputError(ATTACHMENT_TOO_LARGE_MESSAGE);
|
|
3713
|
+
let content;
|
|
3714
|
+
try {
|
|
3715
|
+
content = await readAttachmentContent({
|
|
3716
|
+
attachment: await storeAttachmentOnFirstUse({
|
|
3717
|
+
attachment,
|
|
3718
|
+
db: args.db,
|
|
3719
|
+
readAttachmentSource: args.readAttachmentSource,
|
|
3720
|
+
storage: args.storage
|
|
3721
|
+
}),
|
|
3722
|
+
storage: args.storage
|
|
3723
|
+
});
|
|
3724
|
+
} catch (error) {
|
|
3725
|
+
throw toolError(error);
|
|
3726
|
+
}
|
|
3727
|
+
const attachmentDir = path.posix.join(ATTACHMENT_DIR, attachment.id);
|
|
3728
|
+
const partsDir = `${attachmentDir}.parts`;
|
|
3729
|
+
const sandboxPath = path.posix.join(attachmentDir, path.posix.basename(attachment.filename));
|
|
3730
|
+
await runChecked(args.workspace, "create attachment directory", {
|
|
3731
|
+
cmd: "mkdir",
|
|
3732
|
+
args: [
|
|
3733
|
+
"-p",
|
|
3734
|
+
"--",
|
|
3735
|
+
attachmentDir,
|
|
3736
|
+
partsDir
|
|
3737
|
+
]
|
|
3738
|
+
});
|
|
3739
|
+
const joinedPath = path.posix.join(partsDir, "joined");
|
|
3740
|
+
try {
|
|
3741
|
+
const parts = await writeParts({
|
|
3742
|
+
attachmentId: attachment.id,
|
|
3743
|
+
body: await content.open(),
|
|
3744
|
+
expectedBytes: content.bytes,
|
|
3745
|
+
partsDir,
|
|
3746
|
+
workspace: args.workspace
|
|
3747
|
+
});
|
|
3748
|
+
await runChecked(args.workspace, "join attachment parts", {
|
|
3749
|
+
cmd: "sh",
|
|
3750
|
+
args: [
|
|
3751
|
+
"-c",
|
|
3752
|
+
JOIN_PARTS_SCRIPT,
|
|
3753
|
+
"sh",
|
|
3754
|
+
joinedPath,
|
|
3755
|
+
...parts
|
|
3756
|
+
]
|
|
3757
|
+
});
|
|
3758
|
+
const size = await runChecked(args.workspace, "read attachment size", {
|
|
3759
|
+
cmd: "stat",
|
|
3760
|
+
args: [
|
|
3761
|
+
"-c",
|
|
3762
|
+
"%s",
|
|
3763
|
+
"--",
|
|
3764
|
+
joinedPath
|
|
3765
|
+
]
|
|
3766
|
+
});
|
|
3767
|
+
const written = Number(size.trim());
|
|
3768
|
+
if (written !== content.bytes) throw new Error(`Attachment ${attachment.id} wrote ${written} bytes to the sandbox, expected ${content.bytes}.`);
|
|
3769
|
+
await runChecked(args.workspace, "move attachment into place", {
|
|
3770
|
+
cmd: "mv",
|
|
3771
|
+
args: [
|
|
3772
|
+
"-f",
|
|
3773
|
+
"--",
|
|
3774
|
+
joinedPath,
|
|
3775
|
+
sandboxPath
|
|
3776
|
+
]
|
|
3777
|
+
});
|
|
3778
|
+
} catch (error) {
|
|
3779
|
+
await args.workspace.runCommand({
|
|
3780
|
+
cmd: "rm",
|
|
3781
|
+
args: [
|
|
3782
|
+
"-rf",
|
|
3783
|
+
"--",
|
|
3784
|
+
partsDir
|
|
3785
|
+
]
|
|
3786
|
+
}).catch(() => void 0);
|
|
3787
|
+
throw toolError(error);
|
|
3788
|
+
}
|
|
3789
|
+
await runChecked(args.workspace, "remove attachment parts", {
|
|
3790
|
+
cmd: "rm",
|
|
3791
|
+
args: [
|
|
3792
|
+
"-rf",
|
|
3793
|
+
"--",
|
|
3794
|
+
partsDir
|
|
3795
|
+
]
|
|
3796
|
+
});
|
|
3797
|
+
return {
|
|
3798
|
+
path: sandboxPath,
|
|
3799
|
+
filename: attachment.filename,
|
|
3800
|
+
mime_type: attachment.contentType,
|
|
3801
|
+
bytes: content.bytes
|
|
3802
|
+
};
|
|
3803
|
+
}
|
|
3804
|
+
});
|
|
3805
|
+
}
|
|
3806
|
+
// src/chat/tools/transcribe-audio.ts
|
|
3807
|
+
/** Deferred tool catalog source for speech transcription. */
|
|
3808
|
+
const AUDIO_TOOL_SOURCE = {
|
|
3809
|
+
id: "audio",
|
|
3810
|
+
description: "Transcribe speech in audio and video attachments."
|
|
3811
|
+
};
|
|
3812
|
+
const DOWNLOAD_URL_TTL_MS = 3e5;
|
|
3813
|
+
const UNTYPED_CONTENT_TYPE = "application/octet-stream";
|
|
3814
|
+
const INLINE_RESERVE_CHARS = 1e3;
|
|
3815
|
+
const transcribeAudioOutputSchema = juniorToolOutputSchema.extend({
|
|
3816
|
+
transcript: z.string(),
|
|
3817
|
+
transcript_path: z.string().optional(),
|
|
3818
|
+
note: z.string().optional(),
|
|
3819
|
+
language: z.string().optional(),
|
|
3820
|
+
duration_seconds: z.number().nonnegative().optional()
|
|
3821
|
+
}).strict();
|
|
3822
|
+
function mayHaveAudio(contentType) {
|
|
3823
|
+
const mediaType = contentType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
|
|
3824
|
+
return mediaType.startsWith("audio/") || mediaType.startsWith("video/") || mediaType === UNTYPED_CONTENT_TYPE;
|
|
3825
|
+
}
|
|
3826
|
+
/** Format seconds as `MM:SS.s`, or `H:MM:SS.s` from one hour. */
|
|
3827
|
+
function timestamp(seconds) {
|
|
3828
|
+
const tenths = Math.floor(seconds * 10);
|
|
3829
|
+
const hours = Math.floor(tenths / 36e3);
|
|
3830
|
+
const time = `${String(Math.floor(tenths / 600) % 60).padStart(2, "0")}:${String(Math.floor(tenths / 10) % 60).padStart(2, "0")}.${tenths % 10}`;
|
|
3831
|
+
return hours > 0 ? `${hours}:${time}` : time;
|
|
3832
|
+
}
|
|
3833
|
+
/** One log-style line per entry: start time, then speaker and text. */
|
|
3834
|
+
function transcriptLine(entry) {
|
|
3835
|
+
const text = entry.text.replace(/\s+/g, " ");
|
|
3836
|
+
const body = entry.kind === "sound" ? `(${text})` : entry.speaker ? `${entry.speaker}: ${text}` : text;
|
|
3837
|
+
return `[${timestamp(entry.startSeconds)}] ${body}`;
|
|
3838
|
+
}
|
|
3839
|
+
/**
|
|
3840
|
+
* Keep the leading lines whose JSON-escaped size fits in `budget` chars.
|
|
3841
|
+
* The cut is always on a line boundary.
|
|
3842
|
+
*/
|
|
3843
|
+
function leadingLines(lines, budget) {
|
|
3844
|
+
let used = 0;
|
|
3845
|
+
let count = 0;
|
|
3846
|
+
for (const line of lines) {
|
|
3847
|
+
used += JSON.stringify(line).length - 2 + (count > 0 ? 2 : 0);
|
|
3848
|
+
if (used > budget) break;
|
|
3849
|
+
count += 1;
|
|
3850
|
+
}
|
|
3851
|
+
return {
|
|
3852
|
+
text: lines.slice(0, count).join("\n"),
|
|
3853
|
+
truncated: count < lines.length
|
|
3854
|
+
};
|
|
3855
|
+
}
|
|
3856
|
+
/**
|
|
3857
|
+
* Create a tool that transcribes speech in one Conversation attachment.
|
|
3858
|
+
*
|
|
3859
|
+
* The model provider downloads the file from a short-lived signed URL. The
|
|
3860
|
+
* URL never leaves this call. A large Slack file is stored first, so its
|
|
3861
|
+
* first transcription streams it through the host once.
|
|
3862
|
+
*
|
|
3863
|
+
* @runBuilt transcribeAudio
|
|
3864
|
+
*/
|
|
3865
|
+
function createTranscribeAudioTool(args) {
|
|
3866
|
+
return zodTool({
|
|
3867
|
+
exposure: "deferred",
|
|
3868
|
+
source: AUDIO_TOOL_SOURCE,
|
|
3869
|
+
description: "Transcribe speech in an audio or video attachment. Returns a transcript with one line per entry: `[MM:SS.s] speaker: text` for speech and `[MM:SS.s] (sound)` for sounds. The full transcript is saved at `transcript_path`. When `truncated` is true, the inline transcript has only the first lines: read the rest of the file with readFile, or search it with grep. When the save fails, `transcript_path` is absent and `note` says so.",
|
|
3870
|
+
annotations: {
|
|
3871
|
+
destructiveHint: false,
|
|
3872
|
+
idempotentHint: true,
|
|
3873
|
+
openWorldHint: true,
|
|
3874
|
+
readOnlyHint: true
|
|
3875
|
+
},
|
|
3876
|
+
inputSchema: z.object({ attachment_id: attachmentIdParam }),
|
|
3877
|
+
outputSchema: transcribeAudioOutputSchema,
|
|
3878
|
+
execute: async ({ attachment_id }, { signal }) => {
|
|
3879
|
+
const attachment = await readLiveAttachment({
|
|
3880
|
+
attachmentId: attachment_id,
|
|
3881
|
+
conversationId: args.conversationId,
|
|
3882
|
+
db: args.db
|
|
3883
|
+
});
|
|
3884
|
+
if (!attachment || attachment.storageProvider !== args.storage.provider) throw new ToolInputError("Attachment not found in this conversation.");
|
|
3885
|
+
if (!mayHaveAudio(attachment.contentType)) throw new ToolInputError(`This attachment is ${attachment.contentType}, not audio or video.`);
|
|
3886
|
+
const { storageKey } = await storeAttachmentOnFirstUse({
|
|
3887
|
+
attachment,
|
|
3888
|
+
db: args.db,
|
|
3889
|
+
readAttachmentSource: args.readAttachmentSource,
|
|
3890
|
+
storage: args.storage
|
|
3891
|
+
}).catch((error) => {
|
|
3892
|
+
if (error instanceof AttachmentDownloadError) throw new ToolInputError(error.message, { cause: error });
|
|
3893
|
+
throw error;
|
|
3894
|
+
});
|
|
3895
|
+
const sourceUrl = await args.storage.createDownloadUrl({
|
|
3896
|
+
expiresAtMs: Date.now() + DOWNLOAD_URL_TTL_MS,
|
|
3897
|
+
key: storageKey
|
|
3898
|
+
});
|
|
3899
|
+
const transcript = await transcribeFromUrl({
|
|
3900
|
+
cost: args.modelCost,
|
|
3901
|
+
modelId: args.modelId,
|
|
3902
|
+
operation: "transcription",
|
|
3903
|
+
signal,
|
|
3904
|
+
sourceUrl
|
|
3905
|
+
}).catch((error) => {
|
|
3906
|
+
if (error instanceof NoAudioError) throw new ToolInputError(error.message, { cause: error });
|
|
3907
|
+
throw error;
|
|
3908
|
+
});
|
|
3909
|
+
const lines = transcript.entries.map(transcriptLine);
|
|
3910
|
+
const transcriptPath = path.posix.join(ATTACHMENT_DIR, `${attachment.id}.transcript.txt`);
|
|
3911
|
+
let saved = true;
|
|
3912
|
+
try {
|
|
3913
|
+
await args.workspace.writeFiles([{
|
|
3914
|
+
content: `${lines.join("\n")}\n`,
|
|
3915
|
+
path: transcriptPath
|
|
3916
|
+
}]);
|
|
3917
|
+
} catch (error) {
|
|
3918
|
+
saved = false;
|
|
3919
|
+
logWarn("tool.transcript.write.failed", { "exception.message": String(error) });
|
|
3920
|
+
}
|
|
3921
|
+
const result = {
|
|
3922
|
+
...saved ? { transcript_path: transcriptPath } : { note: "The full transcript was not saved." },
|
|
3923
|
+
...transcript.language ? { language: transcript.language } : void 0,
|
|
3924
|
+
...transcript.durationSeconds !== void 0 ? { duration_seconds: transcript.durationSeconds } : void 0
|
|
3925
|
+
};
|
|
3926
|
+
const inline = leadingLines(lines, TOOL_RESULT_MAX_CHARS - INLINE_RESERVE_CHARS - JSON.stringify({
|
|
3927
|
+
...result,
|
|
3928
|
+
transcript: "",
|
|
3929
|
+
truncated: true
|
|
3930
|
+
}).length);
|
|
3931
|
+
return {
|
|
3932
|
+
...result,
|
|
3933
|
+
transcript: inline.text,
|
|
3934
|
+
...inline.truncated ? { truncated: true } : void 0
|
|
3935
|
+
};
|
|
3936
|
+
}
|
|
3937
|
+
});
|
|
3938
|
+
}
|
|
3553
3939
|
// src/chat/mcp/tool-name.ts
|
|
3554
3940
|
/** Extract the provider from canonical `mcp__<provider>__<tool>` names. */
|
|
3555
3941
|
function parseMcpProviderFromToolName(toolName) {
|
|
@@ -4083,6 +4469,17 @@ function slackUserInputAnswerNote(args) {
|
|
|
4083
4469
|
if (answer.other) lines.push(`*Other*: ${escapeSlackMrkdwnText(answer.other)}`);
|
|
4084
4470
|
return truncate$2([`${who} answered`, ...lines].join("\n"), MAX_NOTE_CHARS);
|
|
4085
4471
|
}
|
|
4472
|
+
// src/net/link-url.ts
|
|
4473
|
+
/**
|
|
4474
|
+
* Return the normalized href of an HTTP or HTTPS link, or undefined. Agents,
|
|
4475
|
+
* plugins and messages supply these links, and URL parsing also accepts
|
|
4476
|
+
* `javascript:` and `data:` URLs.
|
|
4477
|
+
*/
|
|
4478
|
+
function safeLinkUrl(url) {
|
|
4479
|
+
if (!url || !URL.canParse(url)) return void 0;
|
|
4480
|
+
const href = new URL(url);
|
|
4481
|
+
return href.protocol === "https:" || href.protocol === "http:" ? href.href : void 0;
|
|
4482
|
+
}
|
|
4086
4483
|
// src/chat/slack/review-item-card.ts
|
|
4087
4484
|
/** Callback id of the modal form that answers a Review item. */
|
|
4088
4485
|
const SLACK_REVIEW_ITEM_VIEW_ID = "junior_review_item";
|
|
@@ -4119,11 +4516,6 @@ function titleText(item) {
|
|
|
4119
4516
|
if (!href) return `**${item.title}**`;
|
|
4120
4517
|
return `**[${item.title.replace(/[[\]\\]/g, "\\$&")}](${href.replaceAll("(", "%28").replaceAll(")", "%29")})**`;
|
|
4121
4518
|
}
|
|
4122
|
-
function safeLinkUrl(url) {
|
|
4123
|
-
if (!url || !URL.canParse(url)) return void 0;
|
|
4124
|
-
const href = new URL(url);
|
|
4125
|
-
return href.protocol === "https:" || href.protocol === "http:" ? href.href : void 0;
|
|
4126
|
-
}
|
|
4127
4519
|
/** The title, body, and question of an item, in Slack markdown. */
|
|
4128
4520
|
function itemText(item) {
|
|
4129
4521
|
return normalizeSlackReplyMarkdown([
|
|
@@ -4420,7 +4812,7 @@ async function findSlackMentionedUserId(text, tenant) {
|
|
|
4420
4812
|
const slackUserId = parseSlackUserId(SLACK_MENTION.exec(text)?.[1] ?? text);
|
|
4421
4813
|
if (!slackUserId) return void 0;
|
|
4422
4814
|
const user = tenant?.provider === "slack" ? (await readActorIdentityFromSql(getDb(), createSlackActor(tenant.providerTenantId, slackUserId, void 0)))?.user : void 0;
|
|
4423
|
-
if (!user) throw new ToolInputError(`<@${slackUserId}> has no
|
|
4815
|
+
if (!user) throw new ToolInputError(`<@${slackUserId}> has no User yet. Assign them by email.`);
|
|
4424
4816
|
return user.id;
|
|
4425
4817
|
}
|
|
4426
4818
|
/**
|
|
@@ -5229,238 +5621,6 @@ function createUnpublishImageTool(args) {
|
|
|
5229
5621
|
}
|
|
5230
5622
|
});
|
|
5231
5623
|
}
|
|
5232
|
-
// src/chat/attachments/download.ts
|
|
5233
|
-
/** Refusal for a file over `MAX_ATTACHMENT_BYTES`. */
|
|
5234
|
-
const ATTACHMENT_TOO_LARGE_MESSAGE = `Attachment is larger than the ${MAX_ATTACHMENT_BYTES / 1024 / 1024} MB file limit.`;
|
|
5235
|
-
/** An attachment whose bytes cannot be read. The message is safe to show. */
|
|
5236
|
-
var AttachmentDownloadError = class extends Error {
|
|
5237
|
-
constructor(message, options) {
|
|
5238
|
-
super(message, options);
|
|
5239
|
-
this.name = "AttachmentDownloadError";
|
|
5240
|
-
}
|
|
5241
|
-
};
|
|
5242
|
-
/**
|
|
5243
|
-
* Find where the bytes of one attachment row are, without reading them.
|
|
5244
|
-
*
|
|
5245
|
-
* A stored file reads from storage. A large Slack file is never stored, so
|
|
5246
|
-
* each `open` downloads it from its source. The source reports the current
|
|
5247
|
-
* size, and the size check runs before any download. Errors that the person
|
|
5248
|
-
* should see are `AttachmentDownloadError`, from here or from `open`.
|
|
5249
|
-
*
|
|
5250
|
-
* The row must come from a lookup scoped to the caller's conversation. The
|
|
5251
|
-
* source id comes from that row only, never from a request.
|
|
5252
|
-
*/
|
|
5253
|
-
async function readAttachmentContent(args) {
|
|
5254
|
-
const { attachment, storage } = args;
|
|
5255
|
-
const { storageKey } = attachment;
|
|
5256
|
-
if (storageKey !== null) return {
|
|
5257
|
-
bytes: attachment.bytes,
|
|
5258
|
-
open: async () => {
|
|
5259
|
-
const body = await storage.get(storageKey);
|
|
5260
|
-
if (!body) throw new AttachmentDownloadError("Stored attachment contents are unavailable.");
|
|
5261
|
-
return body;
|
|
5262
|
-
}
|
|
5263
|
-
};
|
|
5264
|
-
const { source } = attachment;
|
|
5265
|
-
if (!source || !args.readAttachmentSource) throw new AttachmentDownloadError("Attachment cannot be downloaded from this conversation.");
|
|
5266
|
-
const unavailable = (error) => error instanceof AttachmentSourceUnavailableError ? new AttachmentDownloadError(`${attachment.filename} is no longer available: ${error.message}`, { cause: error }) : error;
|
|
5267
|
-
let file;
|
|
5268
|
-
try {
|
|
5269
|
-
file = await args.readAttachmentSource(source);
|
|
5270
|
-
} catch (error) {
|
|
5271
|
-
throw unavailable(error);
|
|
5272
|
-
}
|
|
5273
|
-
if (file.bytes > 262144e3) throw new AttachmentDownloadError(ATTACHMENT_TOO_LARGE_MESSAGE);
|
|
5274
|
-
return {
|
|
5275
|
-
bytes: file.bytes,
|
|
5276
|
-
open: async () => {
|
|
5277
|
-
try {
|
|
5278
|
-
return await file.open();
|
|
5279
|
-
} catch (error) {
|
|
5280
|
-
throw unavailable(error);
|
|
5281
|
-
}
|
|
5282
|
-
}
|
|
5283
|
-
};
|
|
5284
|
-
}
|
|
5285
|
-
// src/chat/tools/load-attachment.ts
|
|
5286
|
-
const ATTACHMENT_DIR = ".junior/attachments";
|
|
5287
|
-
/** Bytes held in memory and sent to the sandbox in one write. */
|
|
5288
|
-
const PART_BYTES = 8388608;
|
|
5289
|
-
const JOIN_PARTS_SCRIPT = "set -eu; out=$1; shift; cat -- \"$@\" > \"$out\"";
|
|
5290
|
-
/** Turn a read failure that the model can relay into a tool error. */
|
|
5291
|
-
function toolError(error) {
|
|
5292
|
-
return error instanceof AttachmentDownloadError ? new ToolInputError(error.message, { cause: error }) : error;
|
|
5293
|
-
}
|
|
5294
|
-
/** Run one sandbox command, and return its stdout. Throw when it fails. */
|
|
5295
|
-
async function runChecked(workspace, action, input) {
|
|
5296
|
-
const result = await workspace.runCommand(input);
|
|
5297
|
-
if (result.exitCode !== 0) throw new Error(`Failed to ${action}: ${result.stderr}`);
|
|
5298
|
-
return result.stdout;
|
|
5299
|
-
}
|
|
5300
|
-
/**
|
|
5301
|
-
* Write an attachment body to the sandbox in parts of at most `PART_BYTES`.
|
|
5302
|
-
*
|
|
5303
|
-
* The sandbox SDK writes only whole buffers, so this keeps one part in
|
|
5304
|
-
* memory, not the file. Returns the part paths in order.
|
|
5305
|
-
*/
|
|
5306
|
-
async function writeParts(args) {
|
|
5307
|
-
const parts = [];
|
|
5308
|
-
let pending = [];
|
|
5309
|
-
let pendingBytes = 0;
|
|
5310
|
-
let total = 0;
|
|
5311
|
-
const flush = async () => {
|
|
5312
|
-
const partPath = path.posix.join(args.partsDir, String(parts.length).padStart(4, "0"));
|
|
5313
|
-
await args.workspace.writeFiles([{
|
|
5314
|
-
content: Buffer.concat(pending),
|
|
5315
|
-
path: partPath
|
|
5316
|
-
}]);
|
|
5317
|
-
parts.push(partPath);
|
|
5318
|
-
pending = [];
|
|
5319
|
-
pendingBytes = 0;
|
|
5320
|
-
};
|
|
5321
|
-
const reader = args.body.getReader();
|
|
5322
|
-
try {
|
|
5323
|
-
for (;;) {
|
|
5324
|
-
const { done, value } = await reader.read();
|
|
5325
|
-
if (done) break;
|
|
5326
|
-
total += value.byteLength;
|
|
5327
|
-
if (total > args.expectedBytes) break;
|
|
5328
|
-
let chunk = value;
|
|
5329
|
-
while (pendingBytes + chunk.byteLength >= PART_BYTES) {
|
|
5330
|
-
const take = PART_BYTES - pendingBytes;
|
|
5331
|
-
pending.push(chunk.subarray(0, take));
|
|
5332
|
-
pendingBytes += take;
|
|
5333
|
-
await flush();
|
|
5334
|
-
chunk = chunk.subarray(take);
|
|
5335
|
-
}
|
|
5336
|
-
if (chunk.byteLength > 0) {
|
|
5337
|
-
pending.push(chunk);
|
|
5338
|
-
pendingBytes += chunk.byteLength;
|
|
5339
|
-
}
|
|
5340
|
-
}
|
|
5341
|
-
} finally {
|
|
5342
|
-
await reader.cancel().catch(() => void 0);
|
|
5343
|
-
}
|
|
5344
|
-
if (total !== args.expectedBytes) throw new Error(`Attachment ${args.attachmentId} read ${total} bytes, expected ${args.expectedBytes}.`);
|
|
5345
|
-
if (pendingBytes > 0 || parts.length === 0) await flush();
|
|
5346
|
-
return parts;
|
|
5347
|
-
}
|
|
5348
|
-
/**
|
|
5349
|
-
* Create a tool that restores one conversation attachment to the sandbox.
|
|
5350
|
-
*
|
|
5351
|
-
* A large Slack file is never stored: each load streams it from Slack
|
|
5352
|
-
* through the host. The sandbox never gets a Slack URL or token.
|
|
5353
|
-
*
|
|
5354
|
-
* @runBuilt loadAttachment
|
|
5355
|
-
*/
|
|
5356
|
-
function createLoadAttachmentTool(args) {
|
|
5357
|
-
return zodTool({
|
|
5358
|
-
description: "Load a stored attachment for this conversation into the sandbox.",
|
|
5359
|
-
annotations: {
|
|
5360
|
-
destructiveHint: false,
|
|
5361
|
-
idempotentHint: true,
|
|
5362
|
-
openWorldHint: true,
|
|
5363
|
-
readOnlyHint: false
|
|
5364
|
-
},
|
|
5365
|
-
inputSchema: z.object({ attachment_id: z.string().min(1).describe("Stored attachment ID, as shown in attachment context or Slack read results.") }),
|
|
5366
|
-
outputSchema: juniorToolOutputSchema,
|
|
5367
|
-
execute: async ({ attachment_id }) => {
|
|
5368
|
-
const attachment = await readLiveAttachment({
|
|
5369
|
-
attachmentId: attachment_id,
|
|
5370
|
-
conversationId: args.conversationId,
|
|
5371
|
-
db: args.db
|
|
5372
|
-
});
|
|
5373
|
-
if (!attachment || attachment.storageProvider !== args.storage.provider) throw new ToolInputError("Attachment not found in this conversation.");
|
|
5374
|
-
if (attachment.bytes > 262144e3) throw new ToolInputError(ATTACHMENT_TOO_LARGE_MESSAGE);
|
|
5375
|
-
let content;
|
|
5376
|
-
try {
|
|
5377
|
-
content = await readAttachmentContent({
|
|
5378
|
-
attachment,
|
|
5379
|
-
readAttachmentSource: args.readAttachmentSource,
|
|
5380
|
-
storage: args.storage
|
|
5381
|
-
});
|
|
5382
|
-
} catch (error) {
|
|
5383
|
-
throw toolError(error);
|
|
5384
|
-
}
|
|
5385
|
-
const attachmentDir = path.posix.join(ATTACHMENT_DIR, attachment.id);
|
|
5386
|
-
const partsDir = `${attachmentDir}.parts`;
|
|
5387
|
-
const sandboxPath = path.posix.join(attachmentDir, path.posix.basename(attachment.filename));
|
|
5388
|
-
await runChecked(args.workspace, "create attachment directory", {
|
|
5389
|
-
cmd: "mkdir",
|
|
5390
|
-
args: [
|
|
5391
|
-
"-p",
|
|
5392
|
-
"--",
|
|
5393
|
-
attachmentDir,
|
|
5394
|
-
partsDir
|
|
5395
|
-
]
|
|
5396
|
-
});
|
|
5397
|
-
const joinedPath = path.posix.join(partsDir, "joined");
|
|
5398
|
-
try {
|
|
5399
|
-
const parts = await writeParts({
|
|
5400
|
-
attachmentId: attachment.id,
|
|
5401
|
-
body: await content.open(),
|
|
5402
|
-
expectedBytes: content.bytes,
|
|
5403
|
-
partsDir,
|
|
5404
|
-
workspace: args.workspace
|
|
5405
|
-
});
|
|
5406
|
-
await runChecked(args.workspace, "join attachment parts", {
|
|
5407
|
-
cmd: "sh",
|
|
5408
|
-
args: [
|
|
5409
|
-
"-c",
|
|
5410
|
-
JOIN_PARTS_SCRIPT,
|
|
5411
|
-
"sh",
|
|
5412
|
-
joinedPath,
|
|
5413
|
-
...parts
|
|
5414
|
-
]
|
|
5415
|
-
});
|
|
5416
|
-
const size = await runChecked(args.workspace, "read attachment size", {
|
|
5417
|
-
cmd: "stat",
|
|
5418
|
-
args: [
|
|
5419
|
-
"-c",
|
|
5420
|
-
"%s",
|
|
5421
|
-
"--",
|
|
5422
|
-
joinedPath
|
|
5423
|
-
]
|
|
5424
|
-
});
|
|
5425
|
-
const written = Number(size.trim());
|
|
5426
|
-
if (written !== content.bytes) throw new Error(`Attachment ${attachment.id} wrote ${written} bytes to the sandbox, expected ${content.bytes}.`);
|
|
5427
|
-
await runChecked(args.workspace, "move attachment into place", {
|
|
5428
|
-
cmd: "mv",
|
|
5429
|
-
args: [
|
|
5430
|
-
"-f",
|
|
5431
|
-
"--",
|
|
5432
|
-
joinedPath,
|
|
5433
|
-
sandboxPath
|
|
5434
|
-
]
|
|
5435
|
-
});
|
|
5436
|
-
} catch (error) {
|
|
5437
|
-
await args.workspace.runCommand({
|
|
5438
|
-
cmd: "rm",
|
|
5439
|
-
args: [
|
|
5440
|
-
"-rf",
|
|
5441
|
-
"--",
|
|
5442
|
-
partsDir
|
|
5443
|
-
]
|
|
5444
|
-
}).catch(() => void 0);
|
|
5445
|
-
throw toolError(error);
|
|
5446
|
-
}
|
|
5447
|
-
await runChecked(args.workspace, "remove attachment parts", {
|
|
5448
|
-
cmd: "rm",
|
|
5449
|
-
args: [
|
|
5450
|
-
"-rf",
|
|
5451
|
-
"--",
|
|
5452
|
-
partsDir
|
|
5453
|
-
]
|
|
5454
|
-
});
|
|
5455
|
-
return {
|
|
5456
|
-
path: sandboxPath,
|
|
5457
|
-
filename: attachment.filename,
|
|
5458
|
-
mime_type: attachment.contentType,
|
|
5459
|
-
bytes: content.bytes
|
|
5460
|
-
};
|
|
5461
|
-
}
|
|
5462
|
-
});
|
|
5463
|
-
}
|
|
5464
5624
|
// src/chat/tools/index.ts
|
|
5465
5625
|
function createToolState() {
|
|
5466
5626
|
const operationResultCache = /* @__PURE__ */ new Map();
|
|
@@ -5488,11 +5648,12 @@ const STATIC_TOOL_BINDERS = {
|
|
|
5488
5648
|
updatePlan: () => createUpdatePlanTool(),
|
|
5489
5649
|
reportProgress: () => createReportProgressTool(),
|
|
5490
5650
|
systemTime: () => createSystemTimeTool(),
|
|
5651
|
+
submitFeedback: (run) => createSubmitFeedbackTool(run.context),
|
|
5491
5652
|
bash: () => createBashTool(),
|
|
5492
5653
|
readFile: () => createReadFileTool(),
|
|
5493
5654
|
editFile: () => createEditFileTool(),
|
|
5494
5655
|
writeFile: () => createWriteFileTool(),
|
|
5495
|
-
webSearch: (run) => createWebSearchTool(botConfig.webSearchModelId, run.hooks.toolOverrides?.webSearch),
|
|
5656
|
+
webSearch: (run) => createWebSearchTool(botConfig.webSearchModelId, run.modelCost, run.hooks.toolOverrides?.webSearch),
|
|
5496
5657
|
webFetch: (run) => createWebFetchTool(run.hooks, { canSendFilesToActiveConversation: run.canSendFilesToActiveConversation }),
|
|
5497
5658
|
watchTimer: (run) => createWatchTimerTool(run.context),
|
|
5498
5659
|
searchEventTypes: (run) => createSearchEventTypesTool(run.catalog),
|
|
@@ -5589,7 +5750,7 @@ const RUN_BUILT_TOOL_BUILDERS = {
|
|
|
5589
5750
|
imageGenerate: (run) => run.hooks.writeGeneratedArtifacts ? createImageGenerateTool({ writeGeneratedArtifacts: run.hooks.writeGeneratedArtifacts }, {
|
|
5590
5751
|
modelId: botConfig.imageGenerationModelId,
|
|
5591
5752
|
canSendFilesToActiveConversation: run.canSendFilesToActiveConversation,
|
|
5592
|
-
|
|
5753
|
+
modelCost: run.modelCost,
|
|
5593
5754
|
sandbox: run.context.workspace
|
|
5594
5755
|
}, run.hooks.toolOverrides?.imageGenerate) : void 0,
|
|
5595
5756
|
localSendFiles: (run) => {
|
|
@@ -5616,6 +5777,22 @@ const RUN_BUILT_TOOL_BUILDERS = {
|
|
|
5616
5777
|
conversationId: run.context.conversationId,
|
|
5617
5778
|
db: getSqlExecutor()
|
|
5618
5779
|
}) : void 0,
|
|
5780
|
+
transcribeAudio: (run) => {
|
|
5781
|
+
const storage = run.context.attachmentStorage;
|
|
5782
|
+
const createDownloadUrl = storage?.createDownloadUrl?.bind(storage);
|
|
5783
|
+
return storage && createDownloadUrl ? createTranscribeAudioTool({
|
|
5784
|
+
conversationId: run.context.conversationId,
|
|
5785
|
+
db: getSqlExecutor(),
|
|
5786
|
+
modelCost: run.modelCost,
|
|
5787
|
+
modelId: botConfig.transcriptionModelId,
|
|
5788
|
+
...run.slack ? { readAttachmentSource: readSlackAttachmentSource } : void 0,
|
|
5789
|
+
storage: {
|
|
5790
|
+
...storage,
|
|
5791
|
+
createDownloadUrl
|
|
5792
|
+
},
|
|
5793
|
+
workspace: run.context.workspace
|
|
5794
|
+
}) : void 0;
|
|
5795
|
+
},
|
|
5619
5796
|
searchMcpTools: (run) => run.context.mcpToolManager ? createSearchMcpToolsTool(run.context.mcpToolManager) : void 0,
|
|
5620
5797
|
callMcpTool: (run) => run.context.mcpToolManager ? createCallMcpToolTool(run.context.mcpToolManager) : void 0,
|
|
5621
5798
|
slackCanvasCreate: (run) => {
|
|
@@ -5871,7 +6048,7 @@ function schemaErrorText(schema, value) {
|
|
|
5871
6048
|
}
|
|
5872
6049
|
/** Resolve and validate a catalog executeTool request at runtime. */
|
|
5873
6050
|
function resolveCatalogToolCall(input, catalogTools) {
|
|
5874
|
-
const extraKeys = Object.keys(input).filter((key) => key !== "tool_name" && key !== "arguments");
|
|
6051
|
+
const extraKeys = Object.keys(input).filter((key) => key !== "tool_name" && key !== "arguments" && key !== "intent");
|
|
5875
6052
|
if (extraKeys.length > 0) throw new ToolInputError(`executeTool arguments must be nested under arguments, not top-level fields: ${extraKeys.join(", ")}`);
|
|
5876
6053
|
const toolName = input["tool_name"];
|
|
5877
6054
|
if (typeof toolName !== "string" || toolName.length === 0) throw new ToolInputError("executeTool requires a catalog tool_name.");
|
|
@@ -6381,7 +6558,8 @@ const executeToolDefinition = zodToolDefinition({
|
|
|
6381
6558
|
exposure: "modelOnly",
|
|
6382
6559
|
inputSchema: z.object({
|
|
6383
6560
|
tool_name: z.string().min(1).describe("Exact catalog tool_name, from searchTools or as named by a skill, tool result, or error."),
|
|
6384
|
-
arguments: z.record(z.string(), z.unknown()).describe("Arguments matching the selected catalog tool schema, for example { \"query\": \"...\" }.").optional()
|
|
6561
|
+
arguments: z.record(z.string(), z.unknown()).describe("Arguments matching the selected catalog tool schema, for example { \"query\": \"...\" }.").optional(),
|
|
6562
|
+
intent: z.string().min(1).describe("Optional short purpose of this call. It is not passed to the catalog tool.").optional()
|
|
6385
6563
|
}).strict(),
|
|
6386
6564
|
outputSchema: juniorToolOutputSchema
|
|
6387
6565
|
});
|
|
@@ -6497,6 +6675,40 @@ async function rerankSearchCandidates(args) {
|
|
|
6497
6675
|
telemetry(picked.length > 0 ? "picked" : "none");
|
|
6498
6676
|
return picked;
|
|
6499
6677
|
}
|
|
6678
|
+
// src/chat/tool-support/schema-summary.ts
|
|
6679
|
+
function asSchema(value) {
|
|
6680
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
6681
|
+
}
|
|
6682
|
+
function propertyList(schema) {
|
|
6683
|
+
const properties = asSchema(schema["properties"]);
|
|
6684
|
+
const required = new Set(Array.isArray(schema["required"]) ? schema["required"] : []);
|
|
6685
|
+
return Object.entries(properties).map(([name, property]) => `${name}${required.has(name) ? "" : "?"}: ${schemaType(asSchema(property))}`).join(", ");
|
|
6686
|
+
}
|
|
6687
|
+
function schemaType(schema) {
|
|
6688
|
+
if ("const" in schema) return JSON.stringify(schema["const"]);
|
|
6689
|
+
if (Array.isArray(schema["enum"])) return schema["enum"].map((value) => JSON.stringify(value)).join(" | ");
|
|
6690
|
+
const variants = schema["anyOf"] ?? schema["oneOf"];
|
|
6691
|
+
if (Array.isArray(variants)) return variants.map((variant) => schemaType(asSchema(variant))).join(" | ");
|
|
6692
|
+
return (Array.isArray(schema["type"]) ? schema["type"] : [schema["type"] ?? (schema["properties"] ? "object" : void 0)]).map((type) => {
|
|
6693
|
+
if (type === "array") {
|
|
6694
|
+
const item = schemaType(asSchema(schema["items"]));
|
|
6695
|
+
return item.includes(" | ") ? `(${item})[]` : `${item}[]`;
|
|
6696
|
+
}
|
|
6697
|
+
if (type === "object") {
|
|
6698
|
+
const properties = propertyList(schema);
|
|
6699
|
+
return properties ? `{ ${properties} }` : "object";
|
|
6700
|
+
}
|
|
6701
|
+
return typeof type === "string" ? type : "unknown";
|
|
6702
|
+
}).join(" | ");
|
|
6703
|
+
}
|
|
6704
|
+
/**
|
|
6705
|
+
* Summarize a tool input schema as `name: type` pairs, with `?` on optional
|
|
6706
|
+
* params, so a search result can show how to call a tool without its full
|
|
6707
|
+
* schema.
|
|
6708
|
+
*/
|
|
6709
|
+
function summarizeInputSchema(schema) {
|
|
6710
|
+
return propertyList(schema) || "No arguments.";
|
|
6711
|
+
}
|
|
6500
6712
|
// src/chat/tools/search-tools.ts
|
|
6501
6713
|
const SEARCH_TOOLS_NAME = "searchTools";
|
|
6502
6714
|
const DEFAULT_MAX_RESULTS = 5;
|
|
@@ -6640,9 +6852,9 @@ const searchToolsToolSchema = z.object({
|
|
|
6640
6852
|
tool_name: z.string(),
|
|
6641
6853
|
description: z.string(),
|
|
6642
6854
|
source: z.string().optional(),
|
|
6643
|
-
input_schema: z.unknown(),
|
|
6644
|
-
|
|
6645
|
-
|
|
6855
|
+
input_schema: z.unknown().optional(),
|
|
6856
|
+
params: z.string().optional(),
|
|
6857
|
+
call_notes: z.array(z.string()).optional()
|
|
6646
6858
|
}).strict();
|
|
6647
6859
|
const searchToolsOutputSchema = juniorToolOutputSchema.extend({
|
|
6648
6860
|
query: z.string().nullable(),
|
|
@@ -6864,7 +7076,7 @@ function selectedSourceSummaries(tools, matches, requestedSource, knownSources)
|
|
|
6864
7076
|
return knownSources.filter((source) => matchedSourceIds.has(source.id));
|
|
6865
7077
|
}
|
|
6866
7078
|
function renderSearchToolsDescription(knownSources) {
|
|
6867
|
-
const intro = "Search the executable tool catalog. Deferred tools are grouped by source; use searchTools with source to inspect one source, then executeTool with the exact returned tool_name.";
|
|
7079
|
+
const intro = "Search the executable tool catalog. Deferred tools are grouped by source; use searchTools with source to inspect one source, then executeTool with the exact returned tool_name. The best match has its full input_schema. Other results have params, a preview for choosing a tool: before you call one, search its exact name to get its input_schema.";
|
|
6868
7080
|
if (knownSources.length === 0) return intro;
|
|
6869
7081
|
return [
|
|
6870
7082
|
intro,
|
|
@@ -6873,14 +7085,14 @@ function renderSearchToolsDescription(knownSources) {
|
|
|
6873
7085
|
].join("\n");
|
|
6874
7086
|
}
|
|
6875
7087
|
/** Build the agent-visible catalog tool summary returned by searchTools. */
|
|
6876
|
-
function toolMetadata(name, definition, includeSource) {
|
|
7088
|
+
function toolMetadata(name, definition, includeSource, includeSchema) {
|
|
7089
|
+
const notes = callNotes(definition);
|
|
6877
7090
|
return {
|
|
6878
7091
|
tool_name: name,
|
|
6879
7092
|
description: summarizeModelVisibleDescription(definition.description),
|
|
6880
7093
|
...includeSource && definition.source ? { source: definition.source.id } : void 0,
|
|
6881
|
-
input_schema: definition.inputSchema,
|
|
6882
|
-
call_notes:
|
|
6883
|
-
annotations: definition.annotations ?? {}
|
|
7094
|
+
...includeSchema ? { input_schema: definition.inputSchema } : { params: summarizeInputSchema(definition.inputSchema) },
|
|
7095
|
+
...notes.length > 0 ? { call_notes: notes } : void 0
|
|
6884
7096
|
};
|
|
6885
7097
|
}
|
|
6886
7098
|
/**
|
|
@@ -6907,10 +7119,11 @@ function createSearchToolsTool(allCatalogTools, rerankCost) {
|
|
|
6907
7119
|
max_results: z.number().int().min(1).max(MAX_RESULTS).nullable().describe("Maximum matching catalog tool descriptors to return.").optional()
|
|
6908
7120
|
}).strict(),
|
|
6909
7121
|
outputSchema: searchToolsOutputSchema,
|
|
6910
|
-
privateTraceResult: (result) => ({ tools: result.tools.map(({ tool_name, description, input_schema }) => ({
|
|
7122
|
+
privateTraceResult: (result) => ({ tools: result.tools.map(({ tool_name, description, input_schema, params }) => ({
|
|
6911
7123
|
tool_name,
|
|
6912
7124
|
description,
|
|
6913
|
-
input_schema
|
|
7125
|
+
input_schema,
|
|
7126
|
+
params
|
|
6914
7127
|
})) }),
|
|
6915
7128
|
execute: async ({ query, source, max_results }, { signal }) => {
|
|
6916
7129
|
const maxResults = max_results ?? DEFAULT_MAX_RESULTS;
|
|
@@ -6940,7 +7153,7 @@ function createSearchToolsTool(allCatalogTools, rerankCost) {
|
|
|
6940
7153
|
const sources = !sourceExists ? knownSources : (query ?? "").trim() ? selectedSourceSummaries(catalogTools, matches, requestedSource, knownSources) : requestedSource ? knownSources.filter((candidate) => candidate.id === requestedSource) : knownSources;
|
|
6941
7154
|
const totalEligibleTools = sourceExists ? listCatalogTools(catalogTools, requestedSource).length : 0;
|
|
6942
7155
|
const includePerToolSource = requestedSource === null;
|
|
6943
|
-
const renderedTools = matches.map((name) => toolMetadata(name, catalogTools[name], includePerToolSource));
|
|
7156
|
+
const renderedTools = matches.map((name, index) => toolMetadata(name, catalogTools[name], includePerToolSource, hasQuery && index === 0));
|
|
6944
7157
|
const result = {
|
|
6945
7158
|
query: query ?? null,
|
|
6946
7159
|
source: requestedSource,
|
|
@@ -7417,8 +7630,8 @@ function renderDeclaration(name, tool) {
|
|
|
7417
7630
|
}).trim().replace(/\n/g, "\n ")}`;
|
|
7418
7631
|
}
|
|
7419
7632
|
/**
|
|
7420
|
-
* Tell the script which tools it may call, for the `<script-tools>`
|
|
7421
|
-
*
|
|
7633
|
+
* Tell the script which tools it may call, for the `<script-tools>` system
|
|
7634
|
+
* prompt section. Direct tools are only named: the model already has their
|
|
7422
7635
|
* input schemas. The other tools are declared within the token budget,
|
|
7423
7636
|
* cheapest first, so that the most tools fit. The others stay callable. The
|
|
7424
7637
|
* model finds their input with `searchTools`. Script-only tools come first,
|
|
@@ -7452,7 +7665,7 @@ function renderScriptTools(tools) {
|
|
|
7452
7665
|
...shown.map((entry) => entry.text),
|
|
7453
7666
|
"};"
|
|
7454
7667
|
] : [],
|
|
7455
|
-
...omitted > 0 ? [`${omitted} more tools are not declared here. To find one, call ${SEARCH_TOOLS_NAME} directly before the script. Then call each result as \`tools.<tool_name>(args)\`, with its input_schema. A script cannot call ${SEARCH_TOOLS_NAME} or ${EXECUTE_TOOL_NAME}.`] : [],
|
|
7668
|
+
...omitted > 0 ? [`${omitted} more tools are not declared here. To find one, call ${SEARCH_TOOLS_NAME} directly before the script. Then call each result as \`tools.<tool_name>(args)\`, with its input_schema. A result with only params is a preview: search its exact name to get its input_schema before you call it. A script cannot call ${SEARCH_TOOLS_NAME} or ${EXECUTE_TOOL_NAME}.`] : [],
|
|
7456
7669
|
...Object.hasOwn(tools, "callMcpTool") ? ["Call an MCP tool as `tools.callMcpTool({ tool_name, arguments })`. Its `result` field holds the structured content of the MCP tool, or its text. `tools.mcp__<provider>__<tool>` does not exist."] : []
|
|
7457
7670
|
].join("\n");
|
|
7458
7671
|
}
|
|
@@ -7466,7 +7679,7 @@ const DESCRIPTION = [
|
|
|
7466
7679
|
`- The script has ${CODE_MODE_SCRIPT_TIMEOUT_MS / 1e3} seconds, including its tool calls.`,
|
|
7467
7680
|
`- Start at most 10 calls before the script awaits. A larger batch fails, and none of its calls run.`,
|
|
7468
7681
|
"- The result lists each tool call and its status. When action review rejects a call, do what its instructions say, such as ask the user, before you try it again.",
|
|
7469
|
-
"- `<script-tools>` in the
|
|
7682
|
+
"- `<script-tools>` in the system prompt lists the tools that a script can call."
|
|
7470
7683
|
].join("\n");
|
|
7471
7684
|
function renderCall(call, index) {
|
|
7472
7685
|
return [`${index + 1}. ${call.toolName}: ${CODE_MODE_CALL_STATUS_TEXT[call.status]}`, ...[...call.error ? [call.error] : [], ...(call.nudges ?? []).map(renderToolResultNudge)].map((note) => ` ${note.replace(/\n/g, "\n ")}`)].join("\n");
|
|
@@ -8026,7 +8239,7 @@ function createJwtBearerMcpClientProvider(subject, mcpUrl, auth) {
|
|
|
8026
8239
|
/** The client metadata that Junior registers for one MCP OAuth callback. */
|
|
8027
8240
|
function createClientMetadata(callbackUrl) {
|
|
8028
8241
|
return {
|
|
8029
|
-
client_name:
|
|
8242
|
+
client_name: `${botConfig.userName} MCP Client`,
|
|
8030
8243
|
redirect_uris: [callbackUrl],
|
|
8031
8244
|
grant_types: ["authorization_code", "refresh_token"],
|
|
8032
8245
|
response_types: ["code"],
|
|
@@ -9398,7 +9611,7 @@ async function wireAgentTools(args) {
|
|
|
9398
9611
|
function bindAgentTools(run, agents) {
|
|
9399
9612
|
const { bindSpawnAgent, bindMessageAgent } = run.environment ?? {};
|
|
9400
9613
|
if (agents === "none" || !bindSpawnAgent) return {};
|
|
9401
|
-
const spawnAgent =
|
|
9614
|
+
const spawnAgent = agents === "children" || agents === "children_and_parent" && botConfig.maxAgentDepth > 0 ? bindSpawnAgent(run) : void 0;
|
|
9402
9615
|
const messageAgent = spawnAgent || agents === "children_and_parent" ? bindMessageAgent?.(run, agents) : void 0;
|
|
9403
9616
|
return {
|
|
9404
9617
|
...spawnAgent ? { spawnAgent } : void 0,
|
|
@@ -9685,13 +9898,13 @@ var ContextSummaryError = class extends Error {
|
|
|
9685
9898
|
* so it fails when Pi changes these steps.
|
|
9686
9899
|
*/
|
|
9687
9900
|
async function buildAgentModelRequest(agent, messages, signal) {
|
|
9688
|
-
const { model,
|
|
9901
|
+
const { model, thinkingLevel, tools } = agent.state;
|
|
9902
|
+
const leading = getInitialSystemMessage(agent.state.messages);
|
|
9689
9903
|
const transformed = agent.transformContext ? await agent.transformContext(messages, signal) : messages;
|
|
9690
9904
|
return {
|
|
9691
9905
|
model,
|
|
9692
9906
|
context: {
|
|
9693
|
-
|
|
9694
|
-
messages: await agent.convertToLlm(transformed),
|
|
9907
|
+
...foldLeadingSystemMessages(leading ? getSystemMessageText$1(leading) : "", await agent.convertToLlm(transformed)),
|
|
9695
9908
|
tools
|
|
9696
9909
|
},
|
|
9697
9910
|
options: {
|
|
@@ -9963,12 +10176,13 @@ async function requestAboveMark(args) {
|
|
|
9963
10176
|
historyVersion,
|
|
9964
10177
|
markSeq
|
|
9965
10178
|
};
|
|
9966
|
-
const {
|
|
10179
|
+
const { messages, thinkingLevel, tools } = args.agent.state;
|
|
10180
|
+
const leading = getInitialSystemMessage(messages);
|
|
9967
10181
|
const snapshot = {
|
|
9968
10182
|
conversationPrivacy: args.conversationPrivacy ?? "private",
|
|
9969
10183
|
inputSize: args.inputSize,
|
|
9970
10184
|
modelId: args.modelId,
|
|
9971
|
-
systemPrompt,
|
|
10185
|
+
systemPrompt: leading ? getSystemMessageText$1(leading) : "",
|
|
9972
10186
|
thinkingLevel,
|
|
9973
10187
|
tools: tools.map((tool) => ({
|
|
9974
10188
|
name: tool.name,
|
|
@@ -10250,39 +10464,18 @@ function withoutRequestContext(text) {
|
|
|
10250
10464
|
return withoutSections(text, Object.values(REQUEST_CONTEXT_SECTION_TAG));
|
|
10251
10465
|
}
|
|
10252
10466
|
/**
|
|
10253
|
-
*
|
|
10254
|
-
*
|
|
10467
|
+
* Remove the copies of capability sections that the Turn context of older
|
|
10468
|
+
* Turns held. Later system messages hold them now, and compaction folds
|
|
10469
|
+
* those.
|
|
10255
10470
|
*/
|
|
10256
|
-
|
|
10257
|
-
|
|
10258
|
-
return tags.flatMap((tag) => latestTurnContextSection(messages, tag) ?? []);
|
|
10259
|
-
}
|
|
10260
|
-
/**
|
|
10261
|
-
* Remove every copy of the latest-copy sections, then put the given copies in
|
|
10262
|
-
* the first Turn context part. Callers leave out a section that kept history
|
|
10263
|
-
* already has.
|
|
10264
|
-
*/
|
|
10265
|
-
function withLatestSections(content, sections) {
|
|
10266
|
-
const closingTag = `\n</${TURN_CONTEXT_TAG}>`;
|
|
10267
|
-
const added = sections.map((section) => `\n\n${section}`).join("");
|
|
10268
|
-
let pending = sections.length > 0;
|
|
10269
|
-
const result = content.map((part) => {
|
|
10471
|
+
function withoutCapabilitySections(content) {
|
|
10472
|
+
return content.map((part) => {
|
|
10270
10473
|
const text = textPart(part);
|
|
10271
|
-
|
|
10272
|
-
let stripped = withoutSections(text, LATEST_COPY_SECTION_TAGS);
|
|
10273
|
-
if (pending && stripped.endsWith(closingTag)) {
|
|
10274
|
-
stripped = `${stripped.slice(0, -closingTag.length)}${added}${closingTag}`;
|
|
10275
|
-
pending = false;
|
|
10276
|
-
}
|
|
10277
|
-
return {
|
|
10474
|
+
return text?.startsWith(`<runtime-turn-context>`) ? {
|
|
10278
10475
|
...part,
|
|
10279
|
-
text:
|
|
10280
|
-
};
|
|
10476
|
+
text: withoutSections(text, Object.values(CAPABILITY_SECTION_TAG))
|
|
10477
|
+
} : part;
|
|
10281
10478
|
});
|
|
10282
|
-
return pending ? [{
|
|
10283
|
-
type: "text",
|
|
10284
|
-
text: `<${TURN_CONTEXT_TAG}>${added}${closingTag}`
|
|
10285
|
-
}, ...result] : result;
|
|
10286
10479
|
}
|
|
10287
10480
|
/** Find the latest session context and keep only its session sections. */
|
|
10288
10481
|
function latestSessionContext(messages) {
|
|
@@ -10305,12 +10498,12 @@ function effectiveRuntimeContext(messages) {
|
|
|
10305
10498
|
break;
|
|
10306
10499
|
}
|
|
10307
10500
|
const effectiveMessages = latestBootstrapIndex < 0 ? messages : messages.slice(latestBootstrapIndex);
|
|
10308
|
-
return runtimeContextContent(effectiveMessages, effectiveMessages
|
|
10501
|
+
return runtimeContextContent(effectiveMessages, effectiveMessages);
|
|
10309
10502
|
}
|
|
10310
|
-
function runtimeContextContent(messages, agentsMessages
|
|
10503
|
+
function runtimeContextContent(messages, agentsMessages) {
|
|
10311
10504
|
const allContent = messages.flatMap(userMessageContent);
|
|
10312
10505
|
const firstAgentsIndex = allContent.findIndex((part) => textPart(part)?.startsWith("# AGENTS.md instructions") === true);
|
|
10313
|
-
const content =
|
|
10506
|
+
const content = withoutCapabilitySections(allContent.filter((part) => textPart(part)?.startsWith("# AGENTS.md instructions") !== true));
|
|
10314
10507
|
const visibleAgents = findVisibleAgentsInstructions(agentsMessages);
|
|
10315
10508
|
if (visibleAgents?.active === true) {
|
|
10316
10509
|
const insertionIndex = firstAgentsIndex < 0 ? content.length : Math.min(firstAgentsIndex, content.length);
|
|
@@ -10345,27 +10538,24 @@ function runtimeContextMessage(messages, timestamp) {
|
|
|
10345
10538
|
*
|
|
10346
10539
|
* Request context, such as plugin context and disabled tools, is true only for
|
|
10347
10540
|
* the Turn that received it. From earlier Turns, keep only the latest session
|
|
10348
|
-
* context
|
|
10349
|
-
* and AGENTS.md instructions.
|
|
10541
|
+
* context and AGENTS.md instructions.
|
|
10350
10542
|
*/
|
|
10351
10543
|
function turnRuntimeContextMessage(messages, turnStartMessageIndex, timestamp) {
|
|
10352
10544
|
if (turnStartMessageIndex === void 0) return runtimeContextMessage(retainRuntimeTurnContext(messages), timestamp);
|
|
10353
10545
|
const earlierContext = retainRuntimeTurnContext(messages.slice(0, turnStartMessageIndex));
|
|
10354
10546
|
const turnContext = retainRuntimeTurnContext(messages.slice(turnStartMessageIndex));
|
|
10355
10547
|
const sessionContext = turnContext.some((message) => userMessageContent(message).map(textPart).some(isSessionTurnContext)) ? void 0 : latestSessionContext(earlierContext);
|
|
10356
|
-
return toRuntimeContextMessage(runtimeContextContent(sessionContext ? [sessionContext, ...turnContext] : turnContext, [...earlierContext, ...turnContext]
|
|
10548
|
+
return toRuntimeContextMessage(runtimeContextContent(sessionContext ? [sessionContext, ...turnContext] : turnContext, [...earlierContext, ...turnContext]), timestamp);
|
|
10357
10549
|
}
|
|
10358
10550
|
/**
|
|
10359
10551
|
* Build the runtime context of summarized history that the kept history
|
|
10360
|
-
* does not carry: the latest session context
|
|
10361
|
-
* capability section and `<script-tools>`, and the AGENTS.md instructions.
|
|
10552
|
+
* does not carry: the latest session context and the AGENTS.md instructions.
|
|
10362
10553
|
* Request context of earlier Turns is left out.
|
|
10363
10554
|
*/
|
|
10364
10555
|
function summarizedRuntimeContextMessage(summarized, kept) {
|
|
10365
10556
|
const earlierContext = retainRuntimeTurnContext(summarized);
|
|
10366
|
-
const
|
|
10367
|
-
|
|
10368
|
-
return toRuntimeContextMessage(runtimeContextContent(sessionContext ? [sessionContext] : [], findVisibleAgentsInstructions(kept) ? [] : earlierContext, latestSections(earlierContext, LATEST_COPY_SECTION_TAGS.filter((tag) => !latestTurnContextSection(keptContext, tag)))));
|
|
10557
|
+
const sessionContext = retainRuntimeTurnContext(kept).some((message) => userMessageContent(message).map(textPart).some(isSessionTurnContext)) ? void 0 : latestSessionContext(earlierContext);
|
|
10558
|
+
return toRuntimeContextMessage(runtimeContextContent(sessionContext ? [sessionContext] : [], findVisibleAgentsInstructions(kept) ? [] : earlierContext));
|
|
10369
10559
|
}
|
|
10370
10560
|
/**
|
|
10371
10561
|
* Build retained user messages for a compacted Pi replacement history. Each
|
|
@@ -10423,13 +10613,19 @@ async function loadRetainedUserMessages(conversationId, pendingMessages) {
|
|
|
10423
10613
|
};
|
|
10424
10614
|
});
|
|
10425
10615
|
}
|
|
10426
|
-
|
|
10616
|
+
const COMPACTION_READ_BACK_NOTE = "The summary replaced earlier messages and tool results. When you need an exact detail that the summary lacks, read the full text with the searchConversationEvents and readConversationEvent tools.";
|
|
10617
|
+
/**
|
|
10618
|
+
* Keep generated text inside the existing evidence-only prompt boundary. The
|
|
10619
|
+
* last line says where replaced detail stays readable: without it, the model
|
|
10620
|
+
* often decides an exact value from a compacted tool result is gone.
|
|
10621
|
+
*/
|
|
10427
10622
|
function renderCompactionSummary(summary) {
|
|
10428
10623
|
return [
|
|
10429
10624
|
COMPACTION_SUMMARY_PREFIX,
|
|
10430
10625
|
"<thread-context authority=\"evidence-only\">",
|
|
10431
10626
|
escapeXml(summary),
|
|
10432
|
-
"</thread-context>"
|
|
10627
|
+
"</thread-context>",
|
|
10628
|
+
COMPACTION_READ_BACK_NOTE
|
|
10433
10629
|
].join("\n");
|
|
10434
10630
|
}
|
|
10435
10631
|
function timestampOf(message) {
|
|
@@ -10500,7 +10696,8 @@ function measuredReplacementTokens(messages) {
|
|
|
10500
10696
|
for (const message of messages.slice(summaryIndex + 1)) {
|
|
10501
10697
|
const timestamp = timestampOf(message);
|
|
10502
10698
|
if (timestamp === void 0 || timestamp <= summaryAt) {
|
|
10503
|
-
|
|
10699
|
+
const role = message.role;
|
|
10700
|
+
if (role !== "user" && role !== "system") return void 0;
|
|
10504
10701
|
continue;
|
|
10505
10702
|
}
|
|
10506
10703
|
const tokens = measuredInputTokens(message);
|
|
@@ -10589,10 +10786,16 @@ async function compactActiveAboveThreshold(args, summarize, source, triggerToken
|
|
|
10589
10786
|
...index === 0 && retainedInstruction ? { sourceEventSeq: retainedInstruction.sourceEventSeq } : void 0
|
|
10590
10787
|
}));
|
|
10591
10788
|
const retainedUserMessages = retainUserMessages ? await loadRetainedUserMessages(args.conversationId, instructionMessages) : [];
|
|
10789
|
+
const systemMessage = foldSystemMessages(args.piMessages);
|
|
10790
|
+
const systemEntries = systemMessage ? [{
|
|
10791
|
+
message: systemMessage,
|
|
10792
|
+
provenance: contextProvenance
|
|
10793
|
+
}] : [];
|
|
10592
10794
|
const keptTokens = estimateReplacementTokens([
|
|
10593
10795
|
...retainedUserMessages,
|
|
10594
10796
|
...contextEntries,
|
|
10595
|
-
...instructionEntries
|
|
10797
|
+
...instructionEntries,
|
|
10798
|
+
...systemEntries
|
|
10596
10799
|
].map((entry) => entry.message), args.modelId, args.requestOverheadTokens);
|
|
10597
10800
|
if (belowInputLimit && keptTokens > calculateContextCompactionTargetTokens(triggerTokens)) return skip("over_target");
|
|
10598
10801
|
if (keptTokens >= inputLimitTokens) return skip("over_input_limit");
|
|
@@ -10621,12 +10824,14 @@ async function compactActiveAboveThreshold(args, summarize, source, triggerToken
|
|
|
10621
10824
|
const replacement = retainUserMessages ? [
|
|
10622
10825
|
...retainedUserMessages,
|
|
10623
10826
|
summaryEntry,
|
|
10827
|
+
...systemEntries,
|
|
10624
10828
|
...contextEntries,
|
|
10625
10829
|
...instructionEntries
|
|
10626
10830
|
] : [
|
|
10627
10831
|
...contextEntries,
|
|
10628
10832
|
...instructionEntries,
|
|
10629
|
-
summaryEntry
|
|
10833
|
+
summaryEntry,
|
|
10834
|
+
...systemEntries
|
|
10630
10835
|
];
|
|
10631
10836
|
const retainedMessageCount = retainedUserMessages.length + instructionMessages.length;
|
|
10632
10837
|
const messages = replacement.map((entry) => entry.message);
|
|
@@ -10902,6 +11107,7 @@ async function applyPreparedSummary(args, prepared, budget) {
|
|
|
10902
11107
|
provenance: contextProvenance
|
|
10903
11108
|
};
|
|
10904
11109
|
}));
|
|
11110
|
+
const systemMessage = foldSystemMessages(summarized);
|
|
10905
11111
|
const replacement = [
|
|
10906
11112
|
...contextMessage ? [{
|
|
10907
11113
|
message: contextMessage,
|
|
@@ -10912,6 +11118,10 @@ async function applyPreparedSummary(args, prepared, budget) {
|
|
|
10912
11118
|
message: userMessage(appendOpenPlan(renderCompactionSummary(prepared.summary), summarized)),
|
|
10913
11119
|
provenance: contextProvenance
|
|
10914
11120
|
},
|
|
11121
|
+
...systemMessage ? [{
|
|
11122
|
+
message: systemMessage,
|
|
11123
|
+
provenance: contextProvenance
|
|
11124
|
+
}] : [],
|
|
10915
11125
|
...trimmedEntries,
|
|
10916
11126
|
...pendingMessages
|
|
10917
11127
|
];
|
|
@@ -11394,7 +11604,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
11394
11604
|
};
|
|
11395
11605
|
if (initialRepositoryInstructions) await recordAgentsTransition(initialRepositoryInstructions);
|
|
11396
11606
|
const getPendingAuthPause = wiring.getPendingAuthPause;
|
|
11397
|
-
const { baseInstructions: assembledBaseInstructions, contextContentParts: promptContextContentParts, inputMessages, inputMessagesAttribute, platform: promptPlatform, promptTimestamp: restoredPromptTimestamp, promptHistoryMessages, shouldPromptAgent, turnContexts, userContentParts: promptUserContentParts } = await assemblePrompt({
|
|
11607
|
+
const { baseInstructions: assembledBaseInstructions, contextContentParts: promptContextContentParts, inputMessages, inputMessagesAttribute, platform: promptPlatform, promptTimestamp: restoredPromptTimestamp, promptHistoryMessages, sectionsMessage, shouldPromptAgent, turnContexts, userContentParts: promptUserContentParts } = await assemblePrompt({
|
|
11398
11608
|
activeMcpCatalogs: wiring.activeMcpCatalogs,
|
|
11399
11609
|
promptMode: behavior.promptMode,
|
|
11400
11610
|
currentActor: actor,
|
|
@@ -11452,7 +11662,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
11452
11662
|
pendingMessages,
|
|
11453
11663
|
mode,
|
|
11454
11664
|
piMessages: messages,
|
|
11455
|
-
requestOverheadTokens: estimateRequestOverheadTokens(
|
|
11665
|
+
requestOverheadTokens: estimateRequestOverheadTokens(baseInstructions, agent.state.tools, activeModelId),
|
|
11456
11666
|
...pairPendingRuntimeContext && pendingMessages ? { runtimeContextMessages: [...messages, ...pendingMessages.map((entry) => entry.message)] } : void 0,
|
|
11457
11667
|
signal: hookSignal,
|
|
11458
11668
|
turnStartMessageIndex: runResume.turnStartMessageIndex
|
|
@@ -11684,6 +11894,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
11684
11894
|
runResume.setTurnStartMessageIndex(existingSessionRecord.turnStartMessageIndex);
|
|
11685
11895
|
runResume.adoptCommittedBoundary(currentAgentMessages());
|
|
11686
11896
|
} else if (promptHistoryMessages.length > 0) setAgentHistory(promptHistoryMessages);
|
|
11897
|
+
if (sectionsMessage) setAgentHistory([...currentAgentMessages(), sectionsMessage]);
|
|
11687
11898
|
runResume.setBeforeMessageCount(currentAgentMessages().length);
|
|
11688
11899
|
if (shouldPromptAgent) runResume.setTurnStartMessageIndex(currentAgentMessages().length);
|
|
11689
11900
|
const authPauseOutcome = await withSpan(`invoke_agent ${botConfig.userName}`, "gen_ai.invoke_agent", spanContext, async (setInvokeAgentSpanAttributes) => {
|
|
@@ -12022,7 +12233,7 @@ function createAgentRunner(execute, options) {
|
|
|
12022
12233
|
}
|
|
12023
12234
|
};
|
|
12024
12235
|
const loadStoredAttachments = async (attachments) => {
|
|
12025
|
-
const { loadInputAttachments } = await import("./model-input-
|
|
12236
|
+
const { loadInputAttachments } = await import("./model-input-DoM9Ht-d.js").then((n) => n.r);
|
|
12026
12237
|
const storage = nextRun.environment?.attachmentStorage;
|
|
12027
12238
|
if (!storage) throw new Error("Attachment storage is unavailable.");
|
|
12028
12239
|
return await loadInputAttachments({
|
|
@@ -12046,4 +12257,4 @@ function createAgentRunner(execute, options) {
|
|
|
12046
12257
|
return await execute(nextRun, streamFn);
|
|
12047
12258
|
} };
|
|
12048
12259
|
}
|
|
12049
|
-
export {
|
|
12260
|
+
export { RetryableDeliveryError as A, parseSlackReviewItemClick as C, AttachmentDownloadError as D, parseSlackUserInputSubmission as E, toolInvocationDestination as M, shouldEmitDevAgentTrace as N, readAttachmentContent as O, buildSlackReviewItemModal as S, safeLinkUrl as T, createSlackReviewItemShow as _, buildAuthPauseResponse as a, findSlackThreadOwnerId as b, createClientMetadata as c, publicArtifactHeaders as d, readPublicArtifact as f, scheduledAutomationRunAttributes as g, logScheduledAutomationRunSkipped as h, measureTurnCompactionWait as i, actorFromRun as j, previewOriginBelongsTo as k, readMcpClientInformation as l, resolveDestinationVisibility as m, executeAgentRun as n, finalizeMcpAuthorization as o, unpublishedArtifactHeaders as p, processBackgroundCompaction as r, getMcpOAuthCallbackPath as s, createAgentRunner as t, latestProgressStatus as u, resolveSlackReviewItemCardConversationId as v, parseSlackReviewItemFormTarget as w, SLACK_REVIEW_ITEM_VIEW_ID as x, syncReviewItemSlackCards as y };
|