@sentry/junior 0.310.0 → 0.311.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-B1wujchl.js +259 -0
- package/dist/{adapter-context-BhKpjpGD.js → adapter-context-G2M0y6rP.js} +2 -2
- package/dist/{admin-tgZEZAk2.js → admin-DCiBhUT1.js} +1 -2
- package/dist/{agent-runner-D9cvNlQl.js → agent-runner-BVHPUIc8.js} +543 -1703
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +7 -6
- package/dist/api.d.ts +21 -3
- package/dist/api.js +1479 -372
- package/dist/{app-B_7Wn0en.d.ts → app-Cw5Vy6H6.d.ts} +14 -3
- package/dist/app.d.ts +2 -2
- package/dist/app.js +232 -506
- package/dist/{background-compaction-queue-BGHqkhkY.js → background-compaction-queue-CJDnWVOJ.js} +4 -4
- package/dist/{briefs-DKxkoruh.js → briefs-BDjnug6Y.js} +3 -3
- package/dist/{catalog-runtime-BxwzbLKY.js → catalog-runtime-DMY3VV-D.js} +1 -1
- package/dist/cli/chat.js +16 -16
- package/dist/cli/check.js +23 -29
- package/dist/cli/init.js +1 -6
- package/dist/cli/main.js +3 -3
- package/dist/cli/plugins.js +8 -7
- package/dist/cli/snapshot-create.js +5 -5
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +3 -3
- package/dist/{config-Dkt2Le2b.js → config-BrXDQefC.js} +239 -5
- package/dist/{continue-in-slack-BWVwePKD.js → continue-in-slack-DNXSC9So.js} +6 -5
- package/dist/{conversation-M9KZ5JxF.js → conversation-ca__NDQW.js} +47 -8
- package/dist/{conversation-feed-Ci6YD1N-.js → conversation-feed-DkinDu5o.js} +15 -6
- package/dist/{conversation-privacy-C39g8BY4.js → conversation-privacy-DxttrKb9.js} +1 -1
- package/dist/{conversation-turn-CBlZIH02.js → conversation-turn-DWw7Xhdr.js} +41 -38
- package/dist/{credential-sync-vGnrB0BY.js → credential-sync-Bk8wGb8Y.js} +15 -16
- package/dist/{db-B4Hjxr-u.d.ts → db-7ETESH44.d.ts} +3 -1
- package/dist/{db-CFZggNoy.js → db-DTxzH7u5.js} +1609 -1040
- package/dist/{executor-BPkZDx5-.js → executor-DqTiYj9S.js} +450 -99
- package/dist/{html-2r2KmLwi.js → html-B9Sl4Axb.js} +6 -6
- package/dist/{install-C-oE6C_u.js → install-Sg4ePfLl.js} +2 -2
- package/dist/instrumentation.js +3 -3
- package/dist/{lineage-CsvrEFQe.js → lineage-BHAMpNKr.js} +2 -2
- package/dist/{logging-D5gkyvnK.js → logging-FjclQsXu.js} +47 -9
- package/dist/{message-DwvJ-I3w.js → message-CJ7_RL50.js} +5 -8
- package/dist/{model-input-MAq2881y.js → model-input-CMLh4Cwq.js} +3 -3
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +3 -3
- package/dist/{oauth-callback-server-DIF6Li06.js → oauth-callback-server-RVcbiDjL.js} +2 -2
- package/dist/{oauth-relay-DPE-wrwO.js → oauth-relay-Bu9kkaQu.js} +1 -1
- package/dist/{projection-jZSlEAXG.js → projection-Cns7XwWa.js} +9445 -5574
- package/dist/{prompt-CaMyeCpA.js → prompt-CDqcsDYC.js} +4 -4
- package/dist/{registry-BBkWFCl8.js → registry-BPwuOP2O.js} +5 -8
- package/dist/{resolve-B38MkHXE.js → resolve-BK29bBry.js} +3 -3
- package/dist/rule-DAxQY-1h.js +20 -0
- package/dist/{runner-11h8PrHh.js → runner-BcAE-cJm.js} +10 -10
- package/dist/{sandbox-egress-signals-CTcACAtJ.js → sandbox-egress-signals-C-q0go5b.js} +1 -1
- package/dist/{schedule-DWxZ3kja.js → schedule-BLJ476XQ.js} +209 -43
- package/dist/{schema-obw5jvR4.js → schema-BLgSZXcL.js} +255 -49
- package/dist/{schema-DriSvB40.d.ts → schema-DYcJeV7d.d.ts} +701 -62
- package/dist/{service-account-Zc5bUcIJ.js → service-account-gN0zqf0S.js} +68 -68
- package/dist/{service-account-Bx93N1n1.js → service-account-iJoCtkHR.js} +3 -3
- package/dist/{skills-C8Npu5zO.js → skills-BoZ80epJ.js} +2 -2
- package/dist/{slack-conversation-unfurl-DlRVA02H.js → slack-conversation-unfurl-CogYrITA.js} +8 -10
- package/dist/{spawn-CXr58R0x.js → spawn-Dk92r7mX.js} +5 -6
- package/dist/{state-CGrGVeQC.js → state-DH3Cmgp3.js} +4 -4
- package/dist/{stop-DYzjRf2U.js → stop-CYsfc0Ed.js} +1063 -313
- package/dist/{store-D4FQ1Nml.js → store-DmmMIrQi.js} +5 -5
- package/dist/{task-queue-CaZffYaH.js → task-queue-C_zldF5J.js} +3 -3
- package/dist/{task-runner-Dm7BHbGp.js → task-runner-C7oCJQIx.js} +20 -13
- package/dist/{thread-context-Dyj1KWaY.js → thread-context-BW2BsQbH.js} +13 -11
- package/dist/{turn-session-routing-CD0BRCex.js → turn-session-routing-Xh_2nSQe.js} +52 -54
- package/dist/{validation-DxVNIxA0.js → validation-DrJd0nnq.js} +1 -1
- package/dist/{version-Cr7Z71yG.js → version-CNKZ8owc.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{warmup-C6LOZ2d2.js → warmup-BWdHew2H.js} +14287 -7195
- package/dist/{web-message-id-BT8Mg8LL.js → web-message-id-Ch5dPq-a.js} +32 -144
- package/dist/{worker-CUBtu1Li.js → worker-t9qpu_Zx.js} +7 -8
- package/migrations/0126_artifact_drop_public.sql +8 -0
- package/migrations/0127_artifact_path.sql +4 -0
- package/migrations/0128_artifact_path_index.sql +1 -0
- package/migrations/0129_review_item_answered_index.sql +1 -0
- package/migrations/0130_review_item_status_index.sql +1 -0
- package/migrations/0131_brief_outcome_status.sql +1 -0
- package/migrations/0132_brief_outcome_status_backfill.sql +7 -0
- package/migrations/0133_brief_created_at_index.sql +1 -0
- package/migrations/0134_slack_person_search_index.sql +1 -0
- package/migrations/0135_code_change_size.sql +3 -0
- package/migrations/0136_merge_conflict_notice_dismiss.sql +16 -0
- package/migrations/0137_inbox_snoozes.sql +27 -0
- package/migrations/0138_code_change_search_index.sql +2 -0
- package/migrations/0139_review_item_owner.sql +22 -0
- package/migrations/0140_review_item_owner_index.sql +1 -0
- package/migrations/0141_memory_core_adoption.sql +89 -0
- package/migrations/0142_memory_core_indexes.sql +17 -0
- package/migrations/meta/0126_snapshot.json +5488 -0
- package/migrations/meta/0127_snapshot.json +5519 -0
- package/migrations/meta/0128_snapshot.json +5519 -0
- package/migrations/meta/0129_snapshot.json +5547 -0
- package/migrations/meta/0130_snapshot.json +5563 -0
- package/migrations/meta/0131_snapshot.json +5569 -0
- package/migrations/meta/0132_snapshot.json +5569 -0
- package/migrations/meta/0133_snapshot.json +5590 -0
- package/migrations/meta/0134_snapshot.json +5606 -0
- package/migrations/meta/0135_snapshot.json +5624 -0
- package/migrations/meta/0136_snapshot.json +5624 -0
- package/migrations/meta/0137_snapshot.json +5864 -0
- package/migrations/meta/0138_snapshot.json +5894 -0
- package/migrations/meta/0139_snapshot.json +5898 -0
- package/migrations/meta/0140_snapshot.json +5919 -0
- package/migrations/meta/0141_snapshot.json +6429 -0
- package/migrations/meta/0142_snapshot.json +6457 -0
- package/migrations/meta/_journal.json +120 -1
- package/package.json +6 -7
- package/dist/result-BaqSZcJb.js +0 -548
- package/dist/session-stop-BfY4rhJs.js +0 -4255
- package/dist/turn-user-message-9IxeEv5v.js +0 -364
- package/dist/users-CaUAYMb3.js +0 -181
- package/dist/viewer-AHldghAD.js +0 -212
|
@@ -1,56 +1,46 @@
|
|
|
1
|
-
import { $ as loadTurnCheckpoint, $
|
|
2
|
-
import {
|
|
1
|
+
import { $ as loadTurnCheckpoint, $a as storeDeferredAttachment, $c as slackChannelMessageTrigger, $i as consumeSandboxEgressAuthRequiredSignal, $o as isConversationScopedChannel, $t as TurnBudgetExceededError, Ai as hash, Bi as resolveBaseUrl, Bo as postSlackMessage, Ca as buildCommandScript, Cn as createUserTokenStore, Cr as isToolResultError, El as getConfigDefaults, Fo as deleteSlackMessage, G as AuthPausePersistenceError, Gi as isAlreadyExistsError, Gs as getEventAutomation, H as PluginCredentialFailureError, Hi as SandboxCallTimeoutError, Hr as getSlackToolContext, Hs as createEventAutomation, J as abandonReplacedPendingAuth, Ja as readLiveAttachment, Jo as SlackActionError, Js as saveEventAutomation, K as AuthorizationFlowDisabledError, Ki as throwSandboxOperationError, Li as deliverOAuthAuthorization, Mi as ensureDockerDaemon, Ni as getSandboxProvider, Ns as getDashboardReviewItemLink, Oc as getReviewItem, Or as trimTrailingAssistantMessages, Pi as isRetryableSandboxFailure, Pn as getPluginTools, Po as addReactionToMessage, Pr as isEventEmbeddingsEnabled, Q as continuableMessages, Qa as storeAttachments, Qi as clearSandboxEgressSignals, Qt as TURN_LIMIT_WRAP_UP_MESSAGE, Ri as formatProviderLabel, Sa as sandboxSkillPathResolution, Sc as resolveTaskTitle, Ta as runNonInteractiveCommand, Tr as normalizeToolNameFromResult, Ts as saveScheduledAutomation, U as createPluginAuthOrchestration, Ua as readSlackAttachmentSource, Ui as findInErrorChain, Uo as updateSlackMessage, V as createPluginEgress, Vr as resolveChannelCapabilities, W as authorizationId, Wo as uploadFilesToConversation, Xi as isWorkspaceSnapshotNotReadyError, Y as canReusePendingAuthLink, Yc as requireSlackChannelMessageScope, Yi as getWorkspaceSnapshotNotReadyError, Zi as workspaceSnapshotNotReadyUserMessage, Zt as GATED_TURN_LIMIT_WRAP_UP_MESSAGE, _a as SANDBOX_SCRATCH_ROOT, _n as CODEMODE_TOOL_NAME, a as loadConversationSkillNames, aa as resolveSandboxCommandEnvironment, an as REPLY_TOOL_NAME, ba as sandboxSkillDir, bn as readBlockedReport, br as isAssistantMessage, bs as createScheduledAutomation, ca as tryWorkspaceRepoCheckoutPath, cn as remindMissingAnswer, dn as getAssistantReplyText, ea as consumeSandboxEgressPermissionDeniedSignal, en as TurnSliceLimitExceededError, eo as AttachmentSourceUnavailableError, fn as sanitizeAssistantText, fo as resolveUserTimezone, g as recordSkillLoaded, gi as renderToolResultNudge, gn as readNoReply, gr as getUserMessageInstructionText, h as recordMcpProviderConnected, ha as SANDBOX_DATA_ROOT, hn as isLegacyNoReplyMarker, hr as getTerminalAssistantMessages, ia as buildSandboxEgressNetworkPolicy, ic as automationRevision, in as isTurnExecutionLimitExceededError, io as createConversationEmbedder, kn as createPluginHookRunner, l as recordAgentsInstructionsUpdated, m as recordGuardianActionReviewed, ma as SANDBOX_COMMAND_PATH, mr as getPiMessageRole, nt as saveTurnCheckpoint, on as isAnswerToolName, os as sleep, p as recordAuthorizationRequested, pn as NO_REPLY_TOOL_NAME, pr as extractAssistantText, ps as normalizeSlackReplyMarkdown, q as AuthorizationPauseError, qc as getEventCatalog, qi as wrapSandboxSetupError, r as loadConnectedMcpProviders, rn as createTurnLimitGate, sa as SANDBOX_RUNTIME, sn as readTurnAnswer, ta as createSandboxEgressCredentialToken, tn as TurnToolCallLimitExceededError, u as recordAttachmentsDelivered, ua as PluginToolDeniedError, un as decideReply, us as escapeSlackMrkdwnText, v as recordToolExecutionStarted, va as SANDBOX_SKILLS_ROOT, vl as credentialAuditAttributes, vn as CODE_MODE_CALL_STATUS_TEXT, wa as buildNonInteractiveShellScript, wr as isToolResultMessage, ws as readScheduledAutomation, xa as sandboxSkillFile, xr as isContinuablePiBoundary, ya as SANDBOX_WORKSPACE_ROOT, yi as getWorkspace, yl as credentialAuditSource, yn as REPORT_BLOCKED_TOOL_NAME, z as getAgentContextCompactionTriggerTokens } from "./projection-Cns7XwWa.js";
|
|
2
|
+
import { B as withLock, G as textCharsForTokens, J as hasCompactedConversationContext, U as estimateRequestOverheadTokens, W as estimateTextTokens, b as GEN_AI_PROVIDER_NAME, ct as createProviderError, dt as getProviderErrorUserMessage, ft as isProviderRefusal, gt as bufferBody, k as resolveGatewayModel, lt as findProviderError, mt as getGatewayApiKey, n as botConfig, nt as readParentAgentTask, ot as ProviderError, pt as isProviderRetryError, st as createAssistantProviderError, ut as getProviderErrorAttributes, v as toPiReasoningLevel, y as normalizeSlackEmojiName } from "./config-BrXDQefC.js";
|
|
3
3
|
import { t as mapBounded } from "./fan-out-Cod-yEHG.js";
|
|
4
|
-
import { C as summarizeMessageText, E as withSpan,
|
|
5
|
-
import { g as withActiveSpan, i as getActiveSpan
|
|
6
|
-
import {
|
|
4
|
+
import { C as summarizeMessageText, E as withSpan, S as setTags, T as withLogContext, W as formatSentryEventReference, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, d as logAudit, f as logError, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, m as logInfo, p as logException, t as buildTurnFailureResponse, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging-FjclQsXu.js";
|
|
5
|
+
import { g as withActiveSpan, i as getActiveSpan } from "./sentry-CPbZjomA.js";
|
|
6
|
+
import { c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-DxttrKb9.js";
|
|
7
7
|
import { f as parseSlackTeamId, n as createSlackActor, o as isUserActor, p as parseSlackUserId, v as parseSlackMessageTs } from "./actor-BsBdxDXQ.js";
|
|
8
|
-
import {
|
|
9
|
-
import { H as
|
|
8
|
+
import { D as isPersonInput, E as dispatchInstructionsInvokeSkills, Ft as readActorIdentityFromSql, Ln as sameDestination, M as promptModeTurnTools, Mn as nextDetailVersion, On as hasAgentTurnUsage, P as turnBehavior, Pt as readActorIdentity, Tn as agentTurnCostUsd, a as getConversationStore, k as isTopLevelKind, ln as ToolInputError, o as getDb, r as getConversationEventStore, s as getSqlExecutor, un as isToolInputError, wn as addAgentTurnUsage } from "./db-DTxzH7u5.js";
|
|
9
|
+
import { H as juniorConversations, _ as juniorAutomationRuns, ct as juniorArtifacts, m as juniorReviewItemSlackCards } from "./executor-DqTiYj9S.js";
|
|
10
10
|
import { d as contextProvenance, f as instructionActors, m as sameActorIdentity, p as instructionProvenanceFor } from "./history-CYstOMKX.js";
|
|
11
|
+
import { i as getStateAdapter } from "./adapter-B1wujchl.js";
|
|
11
12
|
import { a as listReferenceFiles } from "./package-discovery-DD9vencX.js";
|
|
12
|
-
import { n as findSkillByName, o as parseSkillInvocations, r as loadSkillsByName, t as discoverSkills } from "./skills-
|
|
13
|
-
import { _ as credentialUserSubjectId, c as OAuthProviderError, f as actorLogContext, i as resolvePluginHeaderEnvRefs, l as fetchWithBoundedOAuthErrorBodies, u as getOAuthProviderErrorAttributes } from "./registry-
|
|
14
|
-
import { n as pluginCatalogRuntime } from "./catalog-runtime-
|
|
15
|
-
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-
|
|
16
|
-
import { d as completeText, g as NoAudioError, h as transcribeFromUrl, p as generateImages, u as completeObject } from "./prompt-
|
|
17
|
-
import { A as automationContextToolSchema,
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
26
|
-
import { t as resolveConversationRouting } from "./turn-session-routing-CD0BRCex.js";
|
|
27
|
-
import { o as getSandboxResources, r as setSnapshotSpanAttributes } from "./install-C-oE6C_u.js";
|
|
28
|
-
import { n as resolve$1 } from "./resolve-B38MkHXE.js";
|
|
29
|
-
import { t as runWithSlackInstallation } from "./adapter-context-BhKpjpGD.js";
|
|
13
|
+
import { n as findSkillByName, o as parseSkillInvocations, r as loadSkillsByName, t as discoverSkills } from "./skills-BoZ80epJ.js";
|
|
14
|
+
import { _ as credentialUserSubjectId, c as OAuthProviderError, f as actorLogContext, i as resolvePluginHeaderEnvRefs, l as fetchWithBoundedOAuthErrorBodies, u as getOAuthProviderErrorAttributes } from "./registry-BPwuOP2O.js";
|
|
15
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-DMY3VV-D.js";
|
|
16
|
+
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-gN0zqf0S.js";
|
|
17
|
+
import { d as completeText, g as NoAudioError, h as transcribeFromUrl, p as generateImages, u as completeObject } from "./prompt-CDqcsDYC.js";
|
|
18
|
+
import { A as automationContextToolSchema, L as ScheduleIntentError, M as automationTitleSchema, N as taskOutcomeInputSchema, P as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, Q as buttonUserInputField, R as compileScheduleIntent, X as USER_INPUT_NOTE, Y as USER_INPUT_LIMITS, at as automationTaskDescription, j as automationInstructionToolSchema, tt as normalizeUserInputAnswer, z as scheduleIntentFromTool } from "./schedule-BLJ476XQ.js";
|
|
19
|
+
import { $ as MAX_ATTACHMENT_BYTES } from "./conversation-ca__NDQW.js";
|
|
20
|
+
import { $ as bm25NormalizedFrequency, $i as SLACK_TOOL_SOURCE, A as coreToolSlots, Aa as requireToolAutomation, Ai as createSlackListGetItemsTool, B as createWebSearchTool, Bi as resolveSlackChannelRef, Ca as triggerKind, Co as writeAgentHistory, Cr as CooperativeTurnYieldError, Da as getConversationAccess, Dt as createSearchReviewItemsTool, Ea as makeStructuredToolOutput, Et as createAddReviewItemTool, F as ensureWorkspaceSnapshotBuild, Fa as automationEditor, Fi as createSlackChannelListMessagesTool, G as userLookupIdentityProviders, Gt as createReadConversationEventTool, H as createWatchTimerTool, Hi as checkSlackChannelReadAccess, Ia as changeAutomationLifecycle, J as createSystemTimeTool, K as createUpdateUserCustomizationTool, Kt as createRunOperatorSqlTool, L as requireReadyWorkspaceSnapshot, M as createWorkspaceTools, Ma as requireToolCreator, Mi as createSlackListAddItemsTool, N as incrementStat, Na as requireToolDestination, Ni as createSlackConversationMessageSearchTool, Nn as isParentMessageMeta, Oa as automationToolContext, Oi as createSlackPublicSearchTool, Or as isTurnInputCommitLostError, Ot as createUpdateReviewItemTool, Pi as createSlackConversationSearchChannelPort, Q as bm25InverseDocumentFrequency, Qa as requireEventAutomationTrigger, Qi as createSlackCanvasEditTool, Qn as listAgentInvocationsForConversation, Qr as buildSteeringPiMessage, R as prepareWorkspaceSnapshot, Sa as newAutomationTask, So as withAgentRequest, Ta as juniorToolOutputSchema, U as createWatchEventsTool, Ui as joinPublicChannelForRead, V as createWebFetchTool, Vi as slackChannelRefParam, W as createUserLookupTool, X as createSearchEventTypesTool, Xa as editEventAutomation, Xi as createSlackCanvasWriteTool, Xr as assemblePrompt, Y as createStopWatchingResourcesTool, Ya as editScheduledAutomation, Z as createSearchConversationEventsTool, Za as changedEventMatch, Zi as createSlackCanvasReadTool, Zr as buildPromptInput, _ as buildAgentModelRequest, _a as automationToolResult, _o as buildAgentsInstructionsMessage, _t as createReplyTool, a as createCacheWarmingRecorder, at as sliceFileContent, ba as automationTriggerSchema, bo as showsAgentsInstructions, bt as createArchiveAgentTool, ca as createSearchAutomationsTool, co as JUNIOR_PERSONALITY, ct as createEditFileTool, d as lastRequestInputSize, da as AUTOMATIONS_TOOL_SOURCE, dt as createUpdatePlanTool, ea as isMissingPathError, eo as requireAutomationTaskText, et as bm25Saturation, fa as parseToolInput, ft as createStopAgentTool, g as CONTEXT_COMPACTION_PROMPT_NAME, ga as automationSkillToolSchema, gn as resolveBotSlackTeamId, go as AGENTS_REPLACEMENT_NOTICE, gt as createReportBlockedTool, ha as automationIdForToolCall, ho as AGENTS_REMOVAL_NOTICE, ht as createReportProgressTool, ia as createCanvas, ii as readTaskInstructions, io as missingAutomationSkillReason, it as missingFileResult, j as enabledMode, ja as requireToolCaller, ji as createSlackListCreateTool, ka as automationToolsDisabledReason, ki as createSlackListUpdateItemTool, la as createRunAutomationNowTool, lt as editFile, m as createNextInputTracker, ma as zodToolDefinition, mo as createTracedStreamFn, mt as createListAgentsTool, na as resolveWorkspacePath, ni as turnRequestText, no as requireAutomationSkill, nt as createWriteFileTool, oo as moveTaskOutcomes, ot as TOOL_RESULT_MAX_CHARS, p as requestBackgroundCompaction, pa as zodTool, pt as createSpawnAgentTool, q as createSubmitFeedbackTool, qt as createListWatchesTool, ra as createOperationKey, rt as createReadFileTool, so as resolveTaskOutcomes, st as capToolResult, ta as positiveInteger, ti as loadPromptTurnContext, tt as createSearchConversationsTool, u as compactWithPreparedSummary, ua as createDeleteAutomationTool, ut as createBashTool, v as requestContextSummary, va as automationToolResultSchema, vi as createSetConversationSubscriptionTool, vo as findVisibleAgentsInstructions, vt as createNoReplyTool, wa as injectContinuationToolName, wi as createSlackThreadReadTool, wr as TurnInputCommitLostError, xa as editedAutomationTask, xo as readAgentHistory, ya as automationTriggerChangesSchema, yn as resolveSlackReplyTarget, yo as readRepositoryInstructions, yt as createMessageAgentTool, zi as createSlackChannelJoinTool } from "./warmup-BWdHew2H.js";
|
|
21
|
+
import { i as AGENT_INVOCATION_STATUSES, p as detectImageMediaType } from "./web-message-id-Ch5dPq-a.js";
|
|
22
|
+
import { m as getVercelConversationWorkQueue } from "./background-compaction-queue-CJDnWVOJ.js";
|
|
23
|
+
import { t as resolveConversationRouting } from "./turn-session-routing-Xh_2nSQe.js";
|
|
24
|
+
import { o as getSandboxResources, r as setSnapshotSpanAttributes } from "./install-Sg4ePfLl.js";
|
|
25
|
+
import { n as resolve$1 } from "./resolve-BK29bBry.js";
|
|
26
|
+
import { t as runWithSlackInstallation } from "./adapter-context-G2M0y6rP.js";
|
|
30
27
|
import { n as privateTraceResultAttributes } from "./private-trace-result-CE7_lEdq.js";
|
|
31
28
|
import * as z from "zod";
|
|
32
29
|
import pLimit from "p-limit";
|
|
33
|
-
import { streamSimple } from "@earendil-works/pi-ai/compat";
|
|
34
30
|
import path from "node:path";
|
|
35
|
-
import { isDeepStrictEqual } from "node:util";
|
|
36
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
37
31
|
import { createHash, randomBytes, randomInt, randomUUID } from "node:crypto";
|
|
38
|
-
import {
|
|
39
|
-
import { declaredEventKeys, escapeTagText,
|
|
32
|
+
import { isRetryableAssistantError } from "@earendil-works/pi-ai";
|
|
33
|
+
import { declaredEventKeys, escapeTagText, missingToolAnnotationKeys, ownedObjectAnnotationSchema, renderEmptyTag, renderInlineTag, renderTag } from "@sentry/junior-plugin-api";
|
|
40
34
|
import { and, eq, inArray, isNotNull, isNull, sql } from "drizzle-orm";
|
|
41
35
|
import { alias } from "drizzle-orm/pg-core";
|
|
42
|
-
import {
|
|
43
|
-
import { Agent, DEFAULT_AGENT_IDENTITY } from "@earendil-works/pi-agent-core";
|
|
36
|
+
import { Agent } from "@earendil-works/pi-agent-core";
|
|
44
37
|
import fs from "node:fs/promises";
|
|
45
38
|
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
46
39
|
import { SignJWT, importPKCS8 } from "jose";
|
|
47
|
-
import { performance as performance$1 } from "node:perf_hooks";
|
|
48
|
-
import { bm25InverseDocumentFrequency, bm25NormalizedFrequency, bm25Saturation } from "@sentry/junior-search";
|
|
49
|
-
import { Bash, defineCommand } from "just-bash";
|
|
50
40
|
import { Kind } from "@sinclair/typebox";
|
|
51
41
|
import { Value } from "@sinclair/typebox/value";
|
|
42
|
+
import { Bash, defineCommand } from "just-bash";
|
|
52
43
|
import { CodemodeSandbox, renderToolSignature } from "@earendil-works/pi-codemode";
|
|
53
|
-
import { calculateContextTokens } from "@earendil-works/pi-ai/utils/estimate";
|
|
54
44
|
// src/chat/sandbox/skill-sandbox.ts
|
|
55
45
|
const MAX_SKILL_FILE_BYTES = 262144;
|
|
56
46
|
const DEFAULT_MAX_SKILL_FILE_CHARS = 2e4;
|
|
@@ -694,204 +684,6 @@ async applyUpdate(messages) {
|
|
|
694
684
|
await options.onTransition?.(instructions);
|
|
695
685
|
}
|
|
696
686
|
}
|
|
697
|
-
// src/chat/pi/traced-stream.ts
|
|
698
|
-
function attributeModeForPrivacy(conversationPrivacy) {
|
|
699
|
-
return conversationPrivacy === "public" ? "content" : "metadata";
|
|
700
|
-
}
|
|
701
|
-
function buildChatStartAttributes(model, context, options, mode, conversationPrivacy, promptName) {
|
|
702
|
-
const attributes = {
|
|
703
|
-
"gen_ai.operation.name": "chat",
|
|
704
|
-
"gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
|
|
705
|
-
"gen_ai.request.model": model.id,
|
|
706
|
-
...promptName ? { "gen_ai.prompt.name": promptName } : void 0,
|
|
707
|
-
"gen_ai.request.stream": true,
|
|
708
|
-
"gen_ai.output.type": "text",
|
|
709
|
-
"server.address": GEN_AI_SERVER_ADDRESS,
|
|
710
|
-
"server.port": 443,
|
|
711
|
-
...options?.temperature !== void 0 ? { "gen_ai.request.temperature": options.temperature } : void 0,
|
|
712
|
-
...options?.maxTokens !== void 0 ? { "gen_ai.request.max_tokens": options.maxTokens } : void 0,
|
|
713
|
-
...options?.reasoning ? { "gen_ai.request.reasoning.level": options.reasoning } : void 0,
|
|
714
|
-
...hasCompactedConversationContext(context.messages) ? { "gen_ai.conversation.compacted": true } : void 0,
|
|
715
|
-
...conversationPrivacy ? { "app.conversation.privacy": conversationPrivacy } : void 0,
|
|
716
|
-
...toGenAiMessagesTraceAttributes("gen_ai.input", context.messages)
|
|
717
|
-
};
|
|
718
|
-
if (mode === "content") {
|
|
719
|
-
const inputMessages = serializeGenAiAttribute(context.messages.map(toCanonicalInputMessage));
|
|
720
|
-
if (inputMessages) attributes["gen_ai.input.messages"] = inputMessages;
|
|
721
|
-
}
|
|
722
|
-
if (context.systemPrompt) {
|
|
723
|
-
if (mode === "content") {
|
|
724
|
-
const systemInstructions = serializeGenAiAttribute([{
|
|
725
|
-
type: "text",
|
|
726
|
-
content: context.systemPrompt
|
|
727
|
-
}]);
|
|
728
|
-
if (systemInstructions) attributes["gen_ai.system_instructions"] = systemInstructions;
|
|
729
|
-
}
|
|
730
|
-
attributes["gen_ai.system_instructions.content_chars"] = context.systemPrompt.length;
|
|
731
|
-
}
|
|
732
|
-
return attributes;
|
|
733
|
-
}
|
|
734
|
-
function buildChatEndAttributes(message, mode) {
|
|
735
|
-
const attributes = { ...toGenAiMessagesTraceAttributes("gen_ai.output", [message]) };
|
|
736
|
-
if (mode === "content") {
|
|
737
|
-
const outputMessages = serializeGenAiAttribute([toCanonicalOutputMessage(message)]);
|
|
738
|
-
if (outputMessages) attributes["gen_ai.output.messages"] = outputMessages;
|
|
739
|
-
}
|
|
740
|
-
Object.assign(attributes, extractGenAiUsageAttributes(message));
|
|
741
|
-
if (message.usage.cacheWrite1h !== void 0) attributes["app.ai.usage.cache_write_1h"] = message.usage.cacheWrite1h;
|
|
742
|
-
if (message.stopReason) attributes["gen_ai.response.finish_reasons"] = [normalizeGenAiFinishReason(message.stopReason)];
|
|
743
|
-
if (message.model) attributes["gen_ai.response.model"] = message.model;
|
|
744
|
-
if (message.responseId) attributes["gen_ai.response.id"] = message.responseId;
|
|
745
|
-
if (message.stopReason === "error") {
|
|
746
|
-
const providerError = createAssistantProviderError(message);
|
|
747
|
-
Object.assign(attributes, getProviderErrorAttributes(providerError));
|
|
748
|
-
attributes["error.type"] = providerError.kind;
|
|
749
|
-
}
|
|
750
|
-
return attributes;
|
|
751
|
-
}
|
|
752
|
-
const NON_CONTENT_EVENT_TYPES = /* @__PURE__ */ new Set([
|
|
753
|
-
"start",
|
|
754
|
-
"done",
|
|
755
|
-
"error"
|
|
756
|
-
]);
|
|
757
|
-
function createResponseTiming(requestStartedAtMs) {
|
|
758
|
-
let firstByteAtMs;
|
|
759
|
-
let firstToken;
|
|
760
|
-
return {
|
|
761
|
-
observe: (event) => {
|
|
762
|
-
if (firstByteAtMs === void 0 && event.type !== "error") firstByteAtMs = Date.now();
|
|
763
|
-
if (!firstToken && !NON_CONTENT_EVENT_TYPES.has(event.type)) firstToken = {
|
|
764
|
-
type: event.type,
|
|
765
|
-
receivedAtMs: Date.now()
|
|
766
|
-
};
|
|
767
|
-
},
|
|
768
|
-
attributes: () => {
|
|
769
|
-
if (firstByteAtMs === void 0) return { "gen_ai.response.streaming": false };
|
|
770
|
-
return {
|
|
771
|
-
"gen_ai.response.streaming": true,
|
|
772
|
-
"app.ai.time_to_first_byte_ms": firstByteAtMs - requestStartedAtMs,
|
|
773
|
-
...firstToken ? {
|
|
774
|
-
"gen_ai.response.time_to_first_chunk": (firstToken.receivedAtMs - requestStartedAtMs) / 1e3,
|
|
775
|
-
"app.ai.first_token_type": firstToken.type
|
|
776
|
-
} : void 0
|
|
777
|
-
};
|
|
778
|
-
}
|
|
779
|
-
};
|
|
780
|
-
}
|
|
781
|
-
function traceResponseHeaders(span, options) {
|
|
782
|
-
const eventLoopStart = performance$1.eventLoopUtilization();
|
|
783
|
-
const onResponse = options?.onResponse;
|
|
784
|
-
return {
|
|
785
|
-
...options,
|
|
786
|
-
onResponse: async (response, model) => {
|
|
787
|
-
try {
|
|
788
|
-
const vercelId = response.headers["x-vercel-id"];
|
|
789
|
-
if (vercelId) span.setAttribute("app.ai.gateway.vercel_id", vercelId);
|
|
790
|
-
const { utilization } = performance$1.eventLoopUtilization(eventLoopStart);
|
|
791
|
-
span.setAttribute("app.ai.event_loop.utilization", Math.round(utilization * 1e3) / 1e3);
|
|
792
|
-
} catch {}
|
|
793
|
-
await onResponse?.(response, model);
|
|
794
|
-
}
|
|
795
|
-
};
|
|
796
|
-
}
|
|
797
|
-
function traceRequestPayload(span, options) {
|
|
798
|
-
const onPayload = options?.onPayload;
|
|
799
|
-
return {
|
|
800
|
-
...options,
|
|
801
|
-
onPayload: async (payload, model) => {
|
|
802
|
-
const nextPayload = await onPayload?.(payload, model);
|
|
803
|
-
span.setAttributes(requestPrefixAttributes(nextPayload ?? payload));
|
|
804
|
-
return nextPayload;
|
|
805
|
-
}
|
|
806
|
-
};
|
|
807
|
-
}
|
|
808
|
-
function relayStream(source, onEvent) {
|
|
809
|
-
const relayed = createAssistantMessageEventStream();
|
|
810
|
-
const finished = (async () => {
|
|
811
|
-
try {
|
|
812
|
-
for await (const event of source) {
|
|
813
|
-
onEvent(event);
|
|
814
|
-
relayed.push(event);
|
|
815
|
-
}
|
|
816
|
-
} finally {
|
|
817
|
-
relayed.end();
|
|
818
|
-
}
|
|
819
|
-
})();
|
|
820
|
-
finished.then(() => source.result()).then((message) => relayed.end(message), () => {});
|
|
821
|
-
return {
|
|
822
|
-
stream: relayed,
|
|
823
|
-
finished
|
|
824
|
-
};
|
|
825
|
-
}
|
|
826
|
-
/**
|
|
827
|
-
* Wraps pi-ai's `streamSimple` so each LLM call inside a pi-agent-core agent
|
|
828
|
-
* loop produces its own `gen_ai.chat` Sentry span. The returned function is
|
|
829
|
-
* passed to `new Agent({ streamFn: ... })` and runs once per loop iteration.
|
|
830
|
-
*
|
|
831
|
-
* The base argument exists so tests can inject a stub stream function.
|
|
832
|
-
* `promptName` names a request that is not an agent loop call, such as a
|
|
833
|
-
* context summary. `endAttributes` adds caller attributes from the final
|
|
834
|
-
* message.
|
|
835
|
-
*/
|
|
836
|
-
function createTracedStreamFn(baseOrOptions = streamSimple) {
|
|
837
|
-
const base = typeof baseOrOptions === "function" ? baseOrOptions : baseOrOptions.base ?? streamSimple;
|
|
838
|
-
const mode = attributeModeForPrivacy(typeof baseOrOptions === "function" ? void 0 : baseOrOptions.conversationPrivacy);
|
|
839
|
-
const effectivePrivacy = (typeof baseOrOptions === "function" ? void 0 : baseOrOptions.conversationPrivacy) ?? "private";
|
|
840
|
-
const promptName = typeof baseOrOptions === "function" ? void 0 : baseOrOptions.promptName;
|
|
841
|
-
const callerEndAttributes = typeof baseOrOptions === "function" ? void 0 : baseOrOptions.endAttributes;
|
|
842
|
-
return async (model, context, options) => {
|
|
843
|
-
const span = startInactiveSpan({
|
|
844
|
-
name: `chat ${model.id}`,
|
|
845
|
-
op: "gen_ai.chat",
|
|
846
|
-
attributes: {
|
|
847
|
-
...getLogContextAttributesForSpan("gen_ai.chat"),
|
|
848
|
-
...buildChatStartAttributes(model, context, options, mode, effectivePrivacy, promptName)
|
|
849
|
-
}
|
|
850
|
-
});
|
|
851
|
-
try {
|
|
852
|
-
const requestStartedAtMs = Date.now();
|
|
853
|
-
const stream = await withActiveSpan(span, () => Promise.resolve(base(model, context, traceRequestPayload(span, traceResponseHeaders(span, options)))));
|
|
854
|
-
const responseTiming = createResponseTiming(requestStartedAtMs);
|
|
855
|
-
const relay = relayStream(stream, responseTiming.observe);
|
|
856
|
-
relay.finished.then(() => stream.result()).then((finalMessage) => {
|
|
857
|
-
try {
|
|
858
|
-
const endAttributes = {
|
|
859
|
-
...buildChatEndAttributes(finalMessage, mode),
|
|
860
|
-
...responseTiming.attributes(),
|
|
861
|
-
...callerEndAttributes?.(finalMessage)
|
|
862
|
-
};
|
|
863
|
-
for (const [key, value] of Object.entries(endAttributes)) span.setAttribute(key, value);
|
|
864
|
-
if (finalMessage.stopReason === "error") {
|
|
865
|
-
const summary = endAttributes["app.ai.provider_error.summary"];
|
|
866
|
-
span.setStatus({
|
|
867
|
-
code: 2,
|
|
868
|
-
message: typeof summary === "string" ? summary : "LLM stream failed"
|
|
869
|
-
});
|
|
870
|
-
}
|
|
871
|
-
} finally {
|
|
872
|
-
span.end();
|
|
873
|
-
}
|
|
874
|
-
}, (error) => {
|
|
875
|
-
span.setAttributes(responseTiming.attributes());
|
|
876
|
-
span.setAttribute("error.type", error instanceof Error ? error.name : typeof error);
|
|
877
|
-
span.setStatus({
|
|
878
|
-
code: 2,
|
|
879
|
-
message: "LLM stream failed"
|
|
880
|
-
});
|
|
881
|
-
span.end();
|
|
882
|
-
}).catch(() => {});
|
|
883
|
-
return relay.stream;
|
|
884
|
-
} catch (error) {
|
|
885
|
-
span.setAttribute("error.type", error instanceof Error ? error.name : typeof error);
|
|
886
|
-
span.setStatus({
|
|
887
|
-
code: 2,
|
|
888
|
-
message: "LLM call failed"
|
|
889
|
-
});
|
|
890
|
-
span.end();
|
|
891
|
-
throw error;
|
|
892
|
-
}
|
|
893
|
-
};
|
|
894
|
-
}
|
|
895
687
|
// src/chat/runtime/dev-agent-trace.ts
|
|
896
688
|
function shouldEmitDevAgentTrace() {
|
|
897
689
|
return process.env["NODE_ENV"] === "development";
|
|
@@ -1114,7 +906,7 @@ function finalizeFailedTurnReplyWithEvent(args) {
|
|
|
1114
906
|
if (!eventId) throw new Error("Failed agent run has no Sentry event ID");
|
|
1115
907
|
const providerPartialText = args.reply.diagnostics.outcome === "provider_error" && args.reply.diagnostics.assistantMessageCount > 0 ? args.reply.text.trim() : "";
|
|
1116
908
|
const providerUserMessage = args.reply.diagnostics.providerError instanceof ProviderError ? getProviderErrorUserMessage(args.reply.diagnostics.providerError) : "";
|
|
1117
|
-
const failureText = providerUserMessage ? `${providerUserMessage} Reference:
|
|
909
|
+
const failureText = providerUserMessage ? `${providerUserMessage} Reference: ${formatSentryEventReference(eventId)}.` : buildTurnFailureResponse(eventId);
|
|
1118
910
|
return {
|
|
1119
911
|
eventId,
|
|
1120
912
|
...failureReason ? { failureReason } : void 0,
|
|
@@ -1344,22 +1136,23 @@ const rejectionMarkerSchema = z.object({
|
|
|
1344
1136
|
userAuthorization: z.enum(USER_AUTHORIZATION_LEVELS).optional(),
|
|
1345
1137
|
version: z.literal(1)
|
|
1346
1138
|
}).strict();
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1139
|
+
const markedMessageSchema = z.object({ details: z.object({ guardianActionRejection: rejectionMarkerSchema }) });
|
|
1140
|
+
const codeModeResultSchema = z.object({
|
|
1141
|
+
toolName: z.literal(CODEMODE_TOOL_NAME),
|
|
1142
|
+
details: z.object({ calls: z.array(z.unknown()) })
|
|
1143
|
+
});
|
|
1350
1144
|
/** Read a core-owned action rejection marker from one durable Pi message. */
|
|
1351
1145
|
function getToolActionRejectionMarker(message) {
|
|
1352
|
-
|
|
1353
|
-
const parsed = rejectionMarkerSchema.safeParse(message["details"]["guardianActionRejection"]);
|
|
1354
|
-
return parsed.success ? parsed.data : void 0;
|
|
1146
|
+
return markedMessageSchema.safeParse(message).data?.details.guardianActionRejection;
|
|
1355
1147
|
}
|
|
1356
1148
|
/**
|
|
1357
1149
|
* Read the markers of the nested calls in one `codemode` tool result, in
|
|
1358
1150
|
* call order. The bridge copies each marker from the gate.
|
|
1359
1151
|
*/
|
|
1360
1152
|
function getCodeModeRejectionMarkers(message) {
|
|
1361
|
-
|
|
1362
|
-
|
|
1153
|
+
const parsed = codeModeResultSchema.safeParse(message);
|
|
1154
|
+
if (!parsed.success) return [];
|
|
1155
|
+
return parsed.data.details.calls.flatMap((call) => {
|
|
1363
1156
|
const marker = getToolActionRejectionMarker({ details: call });
|
|
1364
1157
|
return marker ? [marker] : [];
|
|
1365
1158
|
});
|
|
@@ -1373,7 +1166,7 @@ function getCodeModeRejectionMarkers(message) {
|
|
|
1373
1166
|
function projectToolActionRejection(pending, toolCallId, result) {
|
|
1374
1167
|
const rejection = pending.get(toolCallId);
|
|
1375
1168
|
pending.delete(toolCallId);
|
|
1376
|
-
const details =
|
|
1169
|
+
const details = typeof result.details === "object" && result.details !== null && !Array.isArray(result.details) ? result.details : void 0;
|
|
1377
1170
|
const hasReservedMarker = details !== void 0 && "guardianActionRejection" in details;
|
|
1378
1171
|
if (!rejection && !hasReservedMarker) return result;
|
|
1379
1172
|
const safeDetails = details ? Object.fromEntries(Object.entries(details).filter(([key]) => key !== "guardianActionRejection")) : {};
|
|
@@ -1516,6 +1309,406 @@ async function restoreActiveSkill(args) {
|
|
|
1516
1309
|
const skillName = lastLoadedSkillName(args.currentTurnMessages);
|
|
1517
1310
|
if (skillName) await args.skillSandbox.loadSkill(skillName);
|
|
1518
1311
|
}
|
|
1312
|
+
// src/chat/tools/sandbox/file-uploads.ts
|
|
1313
|
+
/** Maximum single file size accepted by model-facing upload tools. */
|
|
1314
|
+
const MAX_SANDBOX_FILE_UPLOAD_BYTES = 10485760;
|
|
1315
|
+
/** Sandbox directory for generated files that later tools can consume. */
|
|
1316
|
+
const SANDBOX_GENERATED_DIR = `${SANDBOX_SCRATCH_ROOT}/gen`;
|
|
1317
|
+
const MAX_GENERATED_FILENAME_CODE_POINTS = 60;
|
|
1318
|
+
/** Canonical model-facing reference to a file that already exists in the sandbox. */
|
|
1319
|
+
const sandboxFileReferenceSchema = z.object({
|
|
1320
|
+
path: z.string().min(1).describe("Exact source path of an existing sandbox file. Preserve paths returned by other tools unchanged; do not move or rewrite them before sending."),
|
|
1321
|
+
filename: z.string().min(1).nullable().optional().describe("Optional filename override shown to the recipient. Null is treated as omitted."),
|
|
1322
|
+
mime_type: z.string().min(1).nullable().optional().describe("Optional MIME type override. Null is treated as omitted."),
|
|
1323
|
+
bytes: z.number().int().nonnegative().nullable().optional().describe("Optional known file size returned by a producing tool. Null is treated as omitted; sending tools validate the file contents directly.")
|
|
1324
|
+
});
|
|
1325
|
+
/** Generated file reference whose path and metadata can be passed directly to sendFiles. */
|
|
1326
|
+
const generatedFileRefSchema = sandboxFileReferenceSchema.extend({
|
|
1327
|
+
filename: z.string().min(1),
|
|
1328
|
+
mime_type: z.string().min(1).optional(),
|
|
1329
|
+
bytes: z.number().int().nonnegative()
|
|
1330
|
+
}).strict();
|
|
1331
|
+
const MIME_BY_EXTENSION = {
|
|
1332
|
+
".png": "image/png",
|
|
1333
|
+
".jpg": "image/jpeg",
|
|
1334
|
+
".jpeg": "image/jpeg",
|
|
1335
|
+
".gif": "image/gif",
|
|
1336
|
+
".webp": "image/webp",
|
|
1337
|
+
".svg": "image/svg+xml",
|
|
1338
|
+
".pdf": "application/pdf",
|
|
1339
|
+
".txt": "text/plain",
|
|
1340
|
+
".md": "text/markdown",
|
|
1341
|
+
".json": "application/json",
|
|
1342
|
+
".csv": "text/csv",
|
|
1343
|
+
".log": "text/plain"
|
|
1344
|
+
};
|
|
1345
|
+
/** Signal that a model-provided file path did not resolve in the active sandbox. */
|
|
1346
|
+
var SandboxFileNotFoundError = class extends ToolInputError {
|
|
1347
|
+
path;
|
|
1348
|
+
constructor(path) {
|
|
1349
|
+
super(`failed to read file: ${path}`);
|
|
1350
|
+
this.path = path;
|
|
1351
|
+
}
|
|
1352
|
+
};
|
|
1353
|
+
/** Resolve model-provided sandbox paths against the sandbox workspace root. */
|
|
1354
|
+
function normalizeSandboxPath(inputPath) {
|
|
1355
|
+
const trimmed = inputPath.trim();
|
|
1356
|
+
if (!trimmed) throw new ToolInputError("path is required");
|
|
1357
|
+
if (path.posix.isAbsolute(trimmed)) return trimmed;
|
|
1358
|
+
return path.posix.join(SANDBOX_WORKSPACE_ROOT, trimmed);
|
|
1359
|
+
}
|
|
1360
|
+
function sanitizeFilename(value, fallbackPath) {
|
|
1361
|
+
const candidate = (value ?? "").trim();
|
|
1362
|
+
if (candidate) {
|
|
1363
|
+
const base = path.posix.basename(candidate);
|
|
1364
|
+
if (base && base !== "." && base !== "..") return base;
|
|
1365
|
+
}
|
|
1366
|
+
const derived = path.posix.basename(fallbackPath);
|
|
1367
|
+
if (derived && derived !== "." && derived !== "..") return derived;
|
|
1368
|
+
return "attachment.bin";
|
|
1369
|
+
}
|
|
1370
|
+
function capFilename(filename) {
|
|
1371
|
+
const codePoints = Array.from(filename);
|
|
1372
|
+
if (codePoints.length <= MAX_GENERATED_FILENAME_CODE_POINTS) return filename;
|
|
1373
|
+
const ext = Array.from(path.posix.extname(filename));
|
|
1374
|
+
const keepExt = ext.length < MAX_GENERATED_FILENAME_CODE_POINTS / 2;
|
|
1375
|
+
const stemLength = MAX_GENERATED_FILENAME_CODE_POINTS - (keepExt ? ext.length : 0);
|
|
1376
|
+
return [...codePoints.slice(0, stemLength), ...keepExt ? ext : []].join("");
|
|
1377
|
+
}
|
|
1378
|
+
/**
|
|
1379
|
+
* Return the sandbox path for one generated file. The content hash keeps
|
|
1380
|
+
* different files with the same name apart. The last segment keeps the
|
|
1381
|
+
* original name, so a send with only the path still shows that name.
|
|
1382
|
+
*/
|
|
1383
|
+
function sandboxGeneratedFilePath(content, filename) {
|
|
1384
|
+
const hash = createHash("sha256").update(content).digest("hex").slice(0, 12);
|
|
1385
|
+
return path.posix.join(SANDBOX_GENERATED_DIR, hash, capFilename(sanitizeFilename(filename, "file.bin")));
|
|
1386
|
+
}
|
|
1387
|
+
/** Infer upload MIME type from an explicit value or filename extension. */
|
|
1388
|
+
function inferMimeType(filename, explicitMimeType) {
|
|
1389
|
+
const explicit = explicitMimeType?.trim();
|
|
1390
|
+
if (explicit) return explicit;
|
|
1391
|
+
const ext = path.extname(filename).toLowerCase();
|
|
1392
|
+
return MIME_BY_EXTENSION[ext] ?? "application/octet-stream";
|
|
1393
|
+
}
|
|
1394
|
+
async function detectMimeType(workspace, targetPath) {
|
|
1395
|
+
try {
|
|
1396
|
+
const result = await runNonInteractiveCommand(workspace, {
|
|
1397
|
+
cmd: "file",
|
|
1398
|
+
args: [
|
|
1399
|
+
"--mime-type",
|
|
1400
|
+
"-b",
|
|
1401
|
+
targetPath
|
|
1402
|
+
]
|
|
1403
|
+
});
|
|
1404
|
+
if (result.exitCode !== 0) return;
|
|
1405
|
+
return result.stdout.trim() || void 0;
|
|
1406
|
+
} catch {
|
|
1407
|
+
return;
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
/** Read and validate one sandbox file for Slack/file reply upload. */
|
|
1411
|
+
async function readSandboxFileUpload(workspace, input) {
|
|
1412
|
+
const targetPath = normalizeSandboxPath(input.path);
|
|
1413
|
+
const fileBuffer = await workspace.readFileToBuffer({ path: targetPath });
|
|
1414
|
+
if (!fileBuffer) throw new SandboxFileNotFoundError(targetPath);
|
|
1415
|
+
if (fileBuffer.byteLength === 0) throw new ToolInputError(`file is empty: ${targetPath}`);
|
|
1416
|
+
if (fileBuffer.byteLength > 10485760) throw new ToolInputError(`file exceeds ${MAX_SANDBOX_FILE_UPLOAD_BYTES} bytes: ${targetPath} (${fileBuffer.byteLength} bytes)`);
|
|
1417
|
+
const resolvedFilename = sanitizeFilename(input.filename, targetPath);
|
|
1418
|
+
const detectedMimeType = await detectMimeType(workspace, targetPath);
|
|
1419
|
+
const resolvedMimeType = inferMimeType(resolvedFilename, input.mime_type ?? detectedMimeType);
|
|
1420
|
+
return {
|
|
1421
|
+
bytes: fileBuffer.byteLength,
|
|
1422
|
+
data: fileBuffer,
|
|
1423
|
+
filename: resolvedFilename,
|
|
1424
|
+
mimeType: resolvedMimeType,
|
|
1425
|
+
path: targetPath
|
|
1426
|
+
};
|
|
1427
|
+
}
|
|
1428
|
+
// src/chat/artifacts/sync.ts
|
|
1429
|
+
/**
|
|
1430
|
+
* Durable conversation files.
|
|
1431
|
+
*
|
|
1432
|
+
* Every file under the Sandbox `artifacts/` directory belongs to its
|
|
1433
|
+
* Conversation and outlives the Sandbox. After a tool call that can change
|
|
1434
|
+
* files, the save step copies new and changed files to attachment storage
|
|
1435
|
+
* and records one row per path. When a Sandbox is prepared, the restore step
|
|
1436
|
+
* writes the live rows back. Nothing here reads outside `artifacts/`, so
|
|
1437
|
+
* `/tmp/jr` scratch files are never copied out.
|
|
1438
|
+
*/
|
|
1439
|
+
/** Sandbox directory, relative to the workspace root, whose files are artifacts. */
|
|
1440
|
+
const ARTIFACTS_DIR = "artifacts";
|
|
1441
|
+
const MAX_FILES = 200;
|
|
1442
|
+
const MAX_FILE_BYTES = 10485760;
|
|
1443
|
+
const MAX_TOTAL_BYTES = 52428800;
|
|
1444
|
+
const TOO_LARGE = "larger than 10 MB";
|
|
1445
|
+
const OVER_TOTAL = "over the 50 MB total limit";
|
|
1446
|
+
/** Tools that can change files. Read-only tools skip the save step. */
|
|
1447
|
+
const SAVE_TOOLS = /* @__PURE__ */ new Set([
|
|
1448
|
+
"bash",
|
|
1449
|
+
"editFile",
|
|
1450
|
+
"writeFile"
|
|
1451
|
+
]);
|
|
1452
|
+
const LIST_SCRIPT = `if [ -d ${ARTIFACTS_DIR} ] && [ ! -L ${ARTIFACTS_DIR} ]; then find -P ${ARTIFACTS_DIR} -type f -printf '%s\\t%C@\\t%P\\0'; fi`;
|
|
1453
|
+
/** Return the relative path when it stays inside the artifacts directory. */
|
|
1454
|
+
function safeArtifactPath(value) {
|
|
1455
|
+
if (!value || value.includes("\0") || path.posix.isAbsolute(value)) return;
|
|
1456
|
+
const normalized = path.posix.normalize(value);
|
|
1457
|
+
if (normalized !== value || normalized === "." || normalized === ".." || normalized.startsWith("../")) return;
|
|
1458
|
+
return normalized;
|
|
1459
|
+
}
|
|
1460
|
+
function sandboxPath(artifactPath) {
|
|
1461
|
+
return `${ARTIFACTS_DIR}/${artifactPath}`;
|
|
1462
|
+
}
|
|
1463
|
+
function storageKey(conversationId, sha256) {
|
|
1464
|
+
return `conversations/${conversationId}/artifacts/${sha256}`;
|
|
1465
|
+
}
|
|
1466
|
+
async function runChecked$1(workspace, action, cmd, args) {
|
|
1467
|
+
const result = await workspace.runCommand({
|
|
1468
|
+
cmd,
|
|
1469
|
+
args,
|
|
1470
|
+
cwd: SANDBOX_WORKSPACE_ROOT
|
|
1471
|
+
});
|
|
1472
|
+
if (result.exitCode !== 0) throw new Error(`Failed to ${action}: ${result.stderr.trim()}`);
|
|
1473
|
+
return result.stdout;
|
|
1474
|
+
}
|
|
1475
|
+
/** List every regular file under the artifacts directory in one command. */
|
|
1476
|
+
async function listArtifactFiles(workspace) {
|
|
1477
|
+
return (await runChecked$1(workspace, "list artifacts", "sh", ["-c", LIST_SCRIPT])).split("\0").filter(Boolean).flatMap((record) => {
|
|
1478
|
+
const [bytes, changedAt, ...rest] = record.split(" ");
|
|
1479
|
+
return bytes && changedAt && rest.length > 0 ? [{
|
|
1480
|
+
bytes: Number(bytes),
|
|
1481
|
+
changedAt,
|
|
1482
|
+
path: rest.join(" ")
|
|
1483
|
+
}] : [];
|
|
1484
|
+
});
|
|
1485
|
+
}
|
|
1486
|
+
/** Hash listed files inside the Sandbox, so restore reads no bytes back. */
|
|
1487
|
+
async function hashArtifactFiles(workspace, paths) {
|
|
1488
|
+
if (paths.length === 0) return /* @__PURE__ */ new Map();
|
|
1489
|
+
const stdout = await runChecked$1(workspace, "hash artifacts", "sha256sum", [
|
|
1490
|
+
"-z",
|
|
1491
|
+
"--",
|
|
1492
|
+
...paths.map(sandboxPath)
|
|
1493
|
+
]);
|
|
1494
|
+
const prefix = `${ARTIFACTS_DIR}/`;
|
|
1495
|
+
return new Map(stdout.split("\0").filter(Boolean).map((line) => [line.slice(66).slice(prefix.length), line.slice(0, 64)]));
|
|
1496
|
+
}
|
|
1497
|
+
const structuredResultSchema = z.object({
|
|
1498
|
+
content: z.unknown().optional(),
|
|
1499
|
+
details: z.looseObject({})
|
|
1500
|
+
});
|
|
1501
|
+
/**
|
|
1502
|
+
* Put the note in the structured result, so direct calls and script calls
|
|
1503
|
+
* both see it. Other content parts stay after it.
|
|
1504
|
+
*/
|
|
1505
|
+
function withArtifactNote(result, note) {
|
|
1506
|
+
const parsed = structuredResultSchema.safeParse(result);
|
|
1507
|
+
if (!parsed.success) return result;
|
|
1508
|
+
const { content, details } = parsed.data;
|
|
1509
|
+
const rest = Array.isArray(content) ? content.slice(1) : [];
|
|
1510
|
+
const output = makeStructuredToolOutput({
|
|
1511
|
+
...details,
|
|
1512
|
+
artifacts_note: note
|
|
1513
|
+
});
|
|
1514
|
+
return {
|
|
1515
|
+
...output,
|
|
1516
|
+
content: [...output.content, ...rest]
|
|
1517
|
+
};
|
|
1518
|
+
}
|
|
1519
|
+
/** Create save and restore steps that share one file list for the Run. */
|
|
1520
|
+
function createArtifactSync(args) {
|
|
1521
|
+
const { conversationId, db, storage } = args;
|
|
1522
|
+
let known;
|
|
1523
|
+
let pending = Promise.resolve();
|
|
1524
|
+
let restoreNote;
|
|
1525
|
+
const liveRows = async () => await db.db().select({
|
|
1526
|
+
bytes: juniorArtifacts.bytes,
|
|
1527
|
+
path: juniorArtifacts.path,
|
|
1528
|
+
sha256: juniorArtifacts.sha256,
|
|
1529
|
+
storageKey: juniorArtifacts.storageKey
|
|
1530
|
+
}).from(juniorArtifacts).where(and(eq(juniorArtifacts.conversationId, conversationId), isNotNull(juniorArtifacts.path), isNull(juniorArtifacts.deleteRequestedAt)));
|
|
1531
|
+
const saveFile = async (file, body, savedSha, storedShas) => {
|
|
1532
|
+
const sha256 = createHash("sha256").update(body).digest("hex");
|
|
1533
|
+
if (sha256 === savedSha) return;
|
|
1534
|
+
const key = storageKey(conversationId, sha256);
|
|
1535
|
+
const contentType = inferMimeType(file.path);
|
|
1536
|
+
if (!storedShas.has(sha256)) {
|
|
1537
|
+
await storage.put({
|
|
1538
|
+
body: bufferBody(body),
|
|
1539
|
+
bytes: body.byteLength,
|
|
1540
|
+
contentType,
|
|
1541
|
+
key
|
|
1542
|
+
});
|
|
1543
|
+
storedShas.add(sha256);
|
|
1544
|
+
}
|
|
1545
|
+
const values = {
|
|
1546
|
+
bytes: body.byteLength,
|
|
1547
|
+
contentType,
|
|
1548
|
+
deleteRequestedAt: null,
|
|
1549
|
+
ext: path.posix.extname(file.path).slice(1).toLowerCase(),
|
|
1550
|
+
sha256,
|
|
1551
|
+
storageKey: key
|
|
1552
|
+
};
|
|
1553
|
+
await db.db().insert(juniorArtifacts).values({
|
|
1554
|
+
...values,
|
|
1555
|
+
conversationId,
|
|
1556
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
1557
|
+
id: randomUUID(),
|
|
1558
|
+
path: file.path,
|
|
1559
|
+
visibility: "conversation"
|
|
1560
|
+
}).onConflictDoUpdate({
|
|
1561
|
+
target: [juniorArtifacts.conversationId, juniorArtifacts.path],
|
|
1562
|
+
set: values
|
|
1563
|
+
});
|
|
1564
|
+
};
|
|
1565
|
+
const save = async (workspace, previous) => {
|
|
1566
|
+
const listed = (await listArtifactFiles(workspace)).sort((a, b) => a.path.localeCompare(b.path));
|
|
1567
|
+
const isUnchanged = (file) => {
|
|
1568
|
+
const stat = previous.get(file.path);
|
|
1569
|
+
return stat?.bytes === file.bytes && stat.changedAt === file.changedAt;
|
|
1570
|
+
};
|
|
1571
|
+
const next = /* @__PURE__ */ new Map();
|
|
1572
|
+
let count = 0;
|
|
1573
|
+
let totalBytes = 0;
|
|
1574
|
+
for (const file of listed.filter(isUnchanged)) {
|
|
1575
|
+
next.set(file.path, {
|
|
1576
|
+
bytes: file.bytes,
|
|
1577
|
+
changedAt: file.changedAt
|
|
1578
|
+
});
|
|
1579
|
+
count += 1;
|
|
1580
|
+
totalBytes += file.bytes;
|
|
1581
|
+
}
|
|
1582
|
+
const unchangedBytes = totalBytes;
|
|
1583
|
+
const keepKnown = (filePath) => {
|
|
1584
|
+
if (previous.has(filePath)) next.set(filePath, {
|
|
1585
|
+
bytes: -1,
|
|
1586
|
+
changedAt: ""
|
|
1587
|
+
});
|
|
1588
|
+
};
|
|
1589
|
+
const skipped = [];
|
|
1590
|
+
const accepted = [];
|
|
1591
|
+
for (const file of listed.filter((item) => !isUnchanged(item))) {
|
|
1592
|
+
const reason = !safeArtifactPath(file.path) ? "unsupported path" : file.bytes > MAX_FILE_BYTES ? TOO_LARGE : count >= MAX_FILES ? "over the 200 file limit" : totalBytes + file.bytes > MAX_TOTAL_BYTES ? OVER_TOTAL : void 0;
|
|
1593
|
+
if (reason) {
|
|
1594
|
+
skipped.push(`${sandboxPath(file.path)} (${reason})`);
|
|
1595
|
+
keepKnown(file.path);
|
|
1596
|
+
continue;
|
|
1597
|
+
}
|
|
1598
|
+
accepted.push(file);
|
|
1599
|
+
count += 1;
|
|
1600
|
+
totalBytes += file.bytes;
|
|
1601
|
+
}
|
|
1602
|
+
const listedPaths = new Set(listed.map((file) => file.path));
|
|
1603
|
+
const removed = [...previous.keys()].filter((filePath) => !listedPaths.has(filePath));
|
|
1604
|
+
if (accepted.length === 0 && removed.length === 0) {
|
|
1605
|
+
known = next;
|
|
1606
|
+
return skippedNote(skipped);
|
|
1607
|
+
}
|
|
1608
|
+
let budget = MAX_TOTAL_BYTES - unchangedBytes;
|
|
1609
|
+
const rows = await liveRows();
|
|
1610
|
+
const savedShas = new Map(rows.map((row) => [row.path, row.sha256]));
|
|
1611
|
+
const storedShas = new Set(rows.map((row) => row.sha256));
|
|
1612
|
+
for (const file of accepted) {
|
|
1613
|
+
const body = await workspace.readFileToBuffer({ path: sandboxPath(file.path) });
|
|
1614
|
+
if (!body) {
|
|
1615
|
+
keepKnown(file.path);
|
|
1616
|
+
continue;
|
|
1617
|
+
}
|
|
1618
|
+
const reason = body.byteLength > MAX_FILE_BYTES ? TOO_LARGE : body.byteLength > budget ? OVER_TOTAL : void 0;
|
|
1619
|
+
if (reason) {
|
|
1620
|
+
skipped.push(`${sandboxPath(file.path)} (${reason})`);
|
|
1621
|
+
keepKnown(file.path);
|
|
1622
|
+
continue;
|
|
1623
|
+
}
|
|
1624
|
+
budget -= body.byteLength;
|
|
1625
|
+
await saveFile(file, body, savedShas.get(file.path), storedShas);
|
|
1626
|
+
next.set(file.path, {
|
|
1627
|
+
bytes: file.bytes,
|
|
1628
|
+
changedAt: file.changedAt
|
|
1629
|
+
});
|
|
1630
|
+
}
|
|
1631
|
+
if (removed.length > 0) await db.db().update(juniorArtifacts).set({ deleteRequestedAt: /* @__PURE__ */ new Date() }).where(and(eq(juniorArtifacts.conversationId, conversationId), inArray(juniorArtifacts.path, removed), isNull(juniorArtifacts.deleteRequestedAt)));
|
|
1632
|
+
known = next;
|
|
1633
|
+
return skippedNote(skipped);
|
|
1634
|
+
};
|
|
1635
|
+
/** Write live rows back, and return the files that now match them. */
|
|
1636
|
+
const restoreFiles = async (workspace) => {
|
|
1637
|
+
const rows = await liveRows();
|
|
1638
|
+
if (rows.length === 0) return /* @__PURE__ */ new Map();
|
|
1639
|
+
const listed = new Map((await listArtifactFiles(workspace)).map((file) => [file.path, file]));
|
|
1640
|
+
const hashes = await hashArtifactFiles(workspace, rows.flatMap((row) => row.path && listed.get(row.path)?.bytes === row.bytes ? [row.path] : []));
|
|
1641
|
+
const restored = /* @__PURE__ */ new Map();
|
|
1642
|
+
const written = [];
|
|
1643
|
+
for (const row of rows) {
|
|
1644
|
+
const artifactPath = row.path && safeArtifactPath(row.path);
|
|
1645
|
+
if (!artifactPath) continue;
|
|
1646
|
+
const present = listed.get(artifactPath);
|
|
1647
|
+
if (present && hashes.get(artifactPath) === row.sha256) {
|
|
1648
|
+
restored.set(artifactPath, present);
|
|
1649
|
+
continue;
|
|
1650
|
+
}
|
|
1651
|
+
const body = await storage.get(row.storageKey);
|
|
1652
|
+
if (!body) {
|
|
1653
|
+
logWarn("artifact.restore.skipped", {
|
|
1654
|
+
"app.conversation.id": conversationId,
|
|
1655
|
+
"error.type": "object_missing"
|
|
1656
|
+
});
|
|
1657
|
+
continue;
|
|
1658
|
+
}
|
|
1659
|
+
const content = Buffer.from(await new Response(body).arrayBuffer());
|
|
1660
|
+
await workspace.writeFiles([{
|
|
1661
|
+
content,
|
|
1662
|
+
path: sandboxPath(artifactPath)
|
|
1663
|
+
}]);
|
|
1664
|
+
written.push(artifactPath);
|
|
1665
|
+
}
|
|
1666
|
+
if (written.length > 0) {
|
|
1667
|
+
const relisted = new Map((await listArtifactFiles(workspace)).map((file) => [file.path, file]));
|
|
1668
|
+
for (const artifactPath of written) {
|
|
1669
|
+
const file = relisted.get(artifactPath);
|
|
1670
|
+
if (file) restored.set(artifactPath, file);
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
return new Map([...restored].map(([artifactPath, file]) => [artifactPath, {
|
|
1674
|
+
bytes: file.bytes,
|
|
1675
|
+
changedAt: file.changedAt
|
|
1676
|
+
}]));
|
|
1677
|
+
};
|
|
1678
|
+
return {
|
|
1679
|
+
async afterToolCall(toolName, workspace) {
|
|
1680
|
+
const notice = restoreNote;
|
|
1681
|
+
restoreNote = void 0;
|
|
1682
|
+
if (!SAVE_TOOLS.has(toolName) || !known) return notice;
|
|
1683
|
+
const run = pending.then(async () => {
|
|
1684
|
+
if (!known) return void 0;
|
|
1685
|
+
try {
|
|
1686
|
+
return await save(workspace, known);
|
|
1687
|
+
} catch (error) {
|
|
1688
|
+
logException(error, "artifact.save.failed", { "app.conversation.id": conversationId });
|
|
1689
|
+
return `Files in ${ARTIFACTS_DIR}/ were not saved because the save failed. The save runs again after the next bash, writeFile, or editFile call.`;
|
|
1690
|
+
}
|
|
1691
|
+
});
|
|
1692
|
+
pending = run;
|
|
1693
|
+
const saved = await run;
|
|
1694
|
+
return notice && saved ? `${notice}\n\n${saved}` : notice ?? saved;
|
|
1695
|
+
},
|
|
1696
|
+
async restore(workspace) {
|
|
1697
|
+
known = /* @__PURE__ */ new Map();
|
|
1698
|
+
restoreNote = void 0;
|
|
1699
|
+
try {
|
|
1700
|
+
known = await restoreFiles(workspace);
|
|
1701
|
+
} catch (error) {
|
|
1702
|
+
logException(error, "artifact.restore.failed", { "app.conversation.id": conversationId });
|
|
1703
|
+
restoreNote = `Saved files in ${ARTIFACTS_DIR}/ could not be restored to this Sandbox, so some may be missing. Their saved copies are kept.`;
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
};
|
|
1707
|
+
}
|
|
1708
|
+
function skippedNote(skipped) {
|
|
1709
|
+
if (skipped.length === 0) return void 0;
|
|
1710
|
+
return [`These files in ${ARTIFACTS_DIR}/ were not saved, so they will be lost when the Sandbox stops. A copy saved earlier stays as it was. Limits: ${MAX_FILES} files, 10 MB per file, 50 MB in total.`, ...skipped.map((entry) => `- ${entry}`)].join("\n");
|
|
1711
|
+
}
|
|
1519
1712
|
// src/chat/capabilities/jr-rpc-command.ts
|
|
1520
1713
|
function commandResult(input) {
|
|
1521
1714
|
let stdout = "";
|
|
@@ -2948,122 +3141,6 @@ function createSandbox(options) {
|
|
|
2948
3141
|
}
|
|
2949
3142
|
};
|
|
2950
3143
|
}
|
|
2951
|
-
// src/chat/tools/sandbox/file-uploads.ts
|
|
2952
|
-
/** Maximum single file size accepted by model-facing upload tools. */
|
|
2953
|
-
const MAX_SANDBOX_FILE_UPLOAD_BYTES = 10485760;
|
|
2954
|
-
/** Sandbox directory for generated files that later tools can consume. */
|
|
2955
|
-
const SANDBOX_GENERATED_DIR = `${SANDBOX_SCRATCH_ROOT}/gen`;
|
|
2956
|
-
const MAX_GENERATED_FILENAME_CODE_POINTS = 60;
|
|
2957
|
-
/** Canonical model-facing reference to a file that already exists in the sandbox. */
|
|
2958
|
-
const sandboxFileReferenceSchema = z.object({
|
|
2959
|
-
path: z.string().min(1).describe("Exact source path of an existing sandbox file. Preserve paths returned by other tools unchanged; do not move or rewrite them before sending."),
|
|
2960
|
-
filename: z.string().min(1).nullable().optional().describe("Optional filename override shown to the recipient. Null is treated as omitted."),
|
|
2961
|
-
mime_type: z.string().min(1).nullable().optional().describe("Optional MIME type override. Null is treated as omitted."),
|
|
2962
|
-
bytes: z.number().int().nonnegative().nullable().optional().describe("Optional known file size returned by a producing tool. Null is treated as omitted; sending tools validate the file contents directly.")
|
|
2963
|
-
});
|
|
2964
|
-
/** Generated file reference whose path and metadata can be passed directly to sendFiles. */
|
|
2965
|
-
const generatedFileRefSchema = sandboxFileReferenceSchema.extend({
|
|
2966
|
-
filename: z.string().min(1),
|
|
2967
|
-
mime_type: z.string().min(1).optional(),
|
|
2968
|
-
bytes: z.number().int().nonnegative()
|
|
2969
|
-
}).strict();
|
|
2970
|
-
const MIME_BY_EXTENSION = {
|
|
2971
|
-
".png": "image/png",
|
|
2972
|
-
".jpg": "image/jpeg",
|
|
2973
|
-
".jpeg": "image/jpeg",
|
|
2974
|
-
".gif": "image/gif",
|
|
2975
|
-
".webp": "image/webp",
|
|
2976
|
-
".svg": "image/svg+xml",
|
|
2977
|
-
".pdf": "application/pdf",
|
|
2978
|
-
".txt": "text/plain",
|
|
2979
|
-
".md": "text/markdown",
|
|
2980
|
-
".json": "application/json",
|
|
2981
|
-
".csv": "text/csv",
|
|
2982
|
-
".log": "text/plain"
|
|
2983
|
-
};
|
|
2984
|
-
/** Signal that a model-provided file path did not resolve in the active sandbox. */
|
|
2985
|
-
var SandboxFileNotFoundError = class extends ToolInputError {
|
|
2986
|
-
path;
|
|
2987
|
-
constructor(path) {
|
|
2988
|
-
super(`failed to read file: ${path}`);
|
|
2989
|
-
this.path = path;
|
|
2990
|
-
}
|
|
2991
|
-
};
|
|
2992
|
-
/** Resolve model-provided sandbox paths against the sandbox workspace root. */
|
|
2993
|
-
function normalizeSandboxPath(inputPath) {
|
|
2994
|
-
const trimmed = inputPath.trim();
|
|
2995
|
-
if (!trimmed) throw new ToolInputError("path is required");
|
|
2996
|
-
if (path.posix.isAbsolute(trimmed)) return trimmed;
|
|
2997
|
-
return path.posix.join(SANDBOX_WORKSPACE_ROOT, trimmed);
|
|
2998
|
-
}
|
|
2999
|
-
function sanitizeFilename(value, fallbackPath) {
|
|
3000
|
-
const candidate = (value ?? "").trim();
|
|
3001
|
-
if (candidate) {
|
|
3002
|
-
const base = path.posix.basename(candidate);
|
|
3003
|
-
if (base && base !== "." && base !== "..") return base;
|
|
3004
|
-
}
|
|
3005
|
-
const derived = path.posix.basename(fallbackPath);
|
|
3006
|
-
if (derived && derived !== "." && derived !== "..") return derived;
|
|
3007
|
-
return "attachment.bin";
|
|
3008
|
-
}
|
|
3009
|
-
function capFilename(filename) {
|
|
3010
|
-
const codePoints = Array.from(filename);
|
|
3011
|
-
if (codePoints.length <= MAX_GENERATED_FILENAME_CODE_POINTS) return filename;
|
|
3012
|
-
const ext = Array.from(path.posix.extname(filename));
|
|
3013
|
-
const keepExt = ext.length < MAX_GENERATED_FILENAME_CODE_POINTS / 2;
|
|
3014
|
-
const stemLength = MAX_GENERATED_FILENAME_CODE_POINTS - (keepExt ? ext.length : 0);
|
|
3015
|
-
return [...codePoints.slice(0, stemLength), ...keepExt ? ext : []].join("");
|
|
3016
|
-
}
|
|
3017
|
-
/**
|
|
3018
|
-
* Return the sandbox path for one generated file. The content hash keeps
|
|
3019
|
-
* different files with the same name apart. The last segment keeps the
|
|
3020
|
-
* original name, so a send with only the path still shows that name.
|
|
3021
|
-
*/
|
|
3022
|
-
function sandboxGeneratedFilePath(content, filename) {
|
|
3023
|
-
const hash = createHash("sha256").update(content).digest("hex").slice(0, 12);
|
|
3024
|
-
return path.posix.join(SANDBOX_GENERATED_DIR, hash, capFilename(sanitizeFilename(filename, "file.bin")));
|
|
3025
|
-
}
|
|
3026
|
-
/** Infer upload MIME type from an explicit value or filename extension. */
|
|
3027
|
-
function inferMimeType(filename, explicitMimeType) {
|
|
3028
|
-
const explicit = explicitMimeType?.trim();
|
|
3029
|
-
if (explicit) return explicit;
|
|
3030
|
-
const ext = path.extname(filename).toLowerCase();
|
|
3031
|
-
return MIME_BY_EXTENSION[ext] ?? "application/octet-stream";
|
|
3032
|
-
}
|
|
3033
|
-
async function detectMimeType(workspace, targetPath) {
|
|
3034
|
-
try {
|
|
3035
|
-
const result = await runNonInteractiveCommand(workspace, {
|
|
3036
|
-
cmd: "file",
|
|
3037
|
-
args: [
|
|
3038
|
-
"--mime-type",
|
|
3039
|
-
"-b",
|
|
3040
|
-
targetPath
|
|
3041
|
-
]
|
|
3042
|
-
});
|
|
3043
|
-
if (result.exitCode !== 0) return;
|
|
3044
|
-
return result.stdout.trim() || void 0;
|
|
3045
|
-
} catch {
|
|
3046
|
-
return;
|
|
3047
|
-
}
|
|
3048
|
-
}
|
|
3049
|
-
/** Read and validate one sandbox file for Slack/file reply upload. */
|
|
3050
|
-
async function readSandboxFileUpload(workspace, input) {
|
|
3051
|
-
const targetPath = normalizeSandboxPath(input.path);
|
|
3052
|
-
const fileBuffer = await workspace.readFileToBuffer({ path: targetPath });
|
|
3053
|
-
if (!fileBuffer) throw new SandboxFileNotFoundError(targetPath);
|
|
3054
|
-
if (fileBuffer.byteLength === 0) throw new ToolInputError(`file is empty: ${targetPath}`);
|
|
3055
|
-
if (fileBuffer.byteLength > 10485760) throw new ToolInputError(`file exceeds ${MAX_SANDBOX_FILE_UPLOAD_BYTES} bytes: ${targetPath} (${fileBuffer.byteLength} bytes)`);
|
|
3056
|
-
const resolvedFilename = sanitizeFilename(input.filename, targetPath);
|
|
3057
|
-
const detectedMimeType = await detectMimeType(workspace, targetPath);
|
|
3058
|
-
const resolvedMimeType = inferMimeType(resolvedFilename, input.mime_type ?? detectedMimeType);
|
|
3059
|
-
return {
|
|
3060
|
-
bytes: fileBuffer.byteLength,
|
|
3061
|
-
data: fileBuffer,
|
|
3062
|
-
filename: resolvedFilename,
|
|
3063
|
-
mimeType: resolvedMimeType,
|
|
3064
|
-
path: targetPath
|
|
3065
|
-
};
|
|
3066
|
-
}
|
|
3067
3144
|
// src/chat/tools/sandbox/generated-files.ts
|
|
3068
3145
|
async function fileUploadDataToBuffer(data) {
|
|
3069
3146
|
if (Buffer.isBuffer(data)) return data;
|
|
@@ -3127,11 +3204,12 @@ function replaceGeneratedTextContent(content, text) {
|
|
|
3127
3204
|
text
|
|
3128
3205
|
}, ...withoutFirstGeneratedTextContent(content)];
|
|
3129
3206
|
}
|
|
3130
|
-
|
|
3131
|
-
|
|
3132
|
-
}
|
|
3207
|
+
/** Any non-array object; tool details are read field by field. */
|
|
3208
|
+
const objectSchema = z.looseObject({});
|
|
3209
|
+
const continuationDetailsSchema = z.looseObject({ continuation: objectSchema });
|
|
3210
|
+
const permissionDeniedDetailsSchema = z.looseObject({ permission_denied: objectSchema });
|
|
3133
3211
|
function hasContinuation(value) {
|
|
3134
|
-
return
|
|
3212
|
+
return continuationDetailsSchema.safeParse(value).success;
|
|
3135
3213
|
}
|
|
3136
3214
|
function stringField(record, key) {
|
|
3137
3215
|
const value = record[key];
|
|
@@ -3145,8 +3223,10 @@ function stringListField(record, key) {
|
|
|
3145
3223
|
const value = record[key];
|
|
3146
3224
|
return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
|
|
3147
3225
|
}
|
|
3148
|
-
function accountText(
|
|
3149
|
-
|
|
3226
|
+
function accountText(account) {
|
|
3227
|
+
const parsed = objectSchema.safeParse(account);
|
|
3228
|
+
if (!parsed.success) return;
|
|
3229
|
+
const value = parsed.data;
|
|
3150
3230
|
const label = stringField(value, "label") || stringField(value, "id");
|
|
3151
3231
|
const id = stringField(value, "id");
|
|
3152
3232
|
if (!label) return;
|
|
@@ -3171,9 +3251,11 @@ function policyDeniedText(value, signal) {
|
|
|
3171
3251
|
...stderr ? ["", `stderr:\n${stderr}`] : []
|
|
3172
3252
|
].join("\n");
|
|
3173
3253
|
}
|
|
3174
|
-
function permissionDeniedText(
|
|
3175
|
-
|
|
3176
|
-
|
|
3254
|
+
function permissionDeniedText(details) {
|
|
3255
|
+
const parsed = permissionDeniedDetailsSchema.safeParse(details);
|
|
3256
|
+
if (!parsed.success) return;
|
|
3257
|
+
const value = parsed.data;
|
|
3258
|
+
const signal = value.permission_denied;
|
|
3177
3259
|
if (signal["source"] === "policy") return policyDeniedText(value, signal);
|
|
3178
3260
|
if (signal["source"] !== "upstream") return;
|
|
3179
3261
|
const provider = stringField(signal, "provider");
|
|
@@ -3182,7 +3264,7 @@ function permissionDeniedText(value) {
|
|
|
3182
3264
|
const upstreamPath = stringField(signal, "upstreamPath");
|
|
3183
3265
|
const status = numberField(signal, "status");
|
|
3184
3266
|
if (!provider || !message || !upstreamHost || !upstreamPath || !status) return;
|
|
3185
|
-
const grant =
|
|
3267
|
+
const grant = objectSchema.safeParse(signal["grant"]).data ?? {};
|
|
3186
3268
|
const grantName = stringField(grant, "name");
|
|
3187
3269
|
const grantAccess = stringField(grant, "access");
|
|
3188
3270
|
const grantReason = stringField(grant, "reason");
|
|
@@ -3318,7 +3400,10 @@ function createAgentSandbox(options) {
|
|
|
3318
3400
|
conversationId: options.conversationId,
|
|
3319
3401
|
credentialEgress: options.credentialEgress,
|
|
3320
3402
|
credentialAuditSource: options.credentialAuditSource,
|
|
3321
|
-
prepare:
|
|
3403
|
+
prepare: async (workspace) => {
|
|
3404
|
+
await options.prepareSandbox(workspace);
|
|
3405
|
+
await options.artifacts?.restore(workspace);
|
|
3406
|
+
},
|
|
3322
3407
|
prepareWorkspace: options.prepareWorkspace,
|
|
3323
3408
|
onSandboxRefChanged: async (sandboxRef) => {
|
|
3324
3409
|
options.onSandboxRefChanged(sandboxRef);
|
|
@@ -3350,7 +3435,10 @@ function createAgentSandbox(options) {
|
|
|
3350
3435
|
});
|
|
3351
3436
|
if (result.handled) return formatSandboxCommandResult(result.result);
|
|
3352
3437
|
}
|
|
3353
|
-
|
|
3438
|
+
const result = await sandbox.tools.execute(params);
|
|
3439
|
+
if (!options.artifacts) return result;
|
|
3440
|
+
const note = await options.artifacts.afterToolCall(params.toolName, sandbox.workspace);
|
|
3441
|
+
return note ? withArtifactNote(result, note) : result;
|
|
3354
3442
|
}
|
|
3355
3443
|
},
|
|
3356
3444
|
async writeGeneratedFiles(files) {
|
|
@@ -4372,9 +4460,12 @@ function createSearchMcpToolsTool(mcpToolManager) {
|
|
|
4372
4460
|
inputSchema: z.object({
|
|
4373
4461
|
query: z.string().min(1).describe("Optional search terms describing the MCP tool or arguments needed.").optional(),
|
|
4374
4462
|
provider: z.string().min(1).describe("Optional provider name to list or search within. If configured but not yet connected, the runtime activates it on demand.").optional(),
|
|
4375
|
-
intent: z.string().min(1).describe("
|
|
4463
|
+
intent: z.string().min(1).describe("Required with provider. A short purpose to show the user if this call needs them to connect their account, for example \"search Notion for the Q3 offsite doc\".").optional(),
|
|
4376
4464
|
max_results: z.number().int().min(1).max(MAX_RESULTS$1).describe("Maximum matching tool descriptors to return.").optional()
|
|
4377
|
-
}).strict(),
|
|
4465
|
+
}).strict().refine((input) => !input.provider || Boolean(input.intent), {
|
|
4466
|
+
message: "Pass intent with provider.",
|
|
4467
|
+
path: ["intent"]
|
|
4468
|
+
}),
|
|
4378
4469
|
outputSchema: searchMcpToolsOutputSchema,
|
|
4379
4470
|
privateTraceResult: (result) => ({
|
|
4380
4471
|
total_active_tools: result.total_active_tools,
|
|
@@ -4688,7 +4779,7 @@ function titleText(item) {
|
|
|
4688
4779
|
function itemText(item) {
|
|
4689
4780
|
return normalizeSlackReplyMarkdown([
|
|
4690
4781
|
titleText(item),
|
|
4691
|
-
truncate$1(item.body, MAX_BODY_CHARS),
|
|
4782
|
+
...item.request?.question === item.body ? [] : [truncate$1(item.body, MAX_BODY_CHARS)],
|
|
4692
4783
|
...item.request ? [slackUserInputText(item.request)] : []
|
|
4693
4784
|
].join("\n\n"));
|
|
4694
4785
|
}
|
|
@@ -4719,12 +4810,12 @@ function controls(item) {
|
|
|
4719
4810
|
label: option.label
|
|
4720
4811
|
})
|
|
4721
4812
|
})),
|
|
4722
|
-
{
|
|
4813
|
+
...buttonField.options.length > 1 ? [{
|
|
4723
4814
|
type: "button",
|
|
4724
4815
|
action_id: ANSWER_ACTION_ID,
|
|
4725
4816
|
text: plainText("Other…"),
|
|
4726
4817
|
value: item.id
|
|
4727
|
-
},
|
|
4818
|
+
}] : [],
|
|
4728
4819
|
dismiss
|
|
4729
4820
|
];
|
|
4730
4821
|
}
|
|
@@ -4750,7 +4841,7 @@ function closedNote(item) {
|
|
|
4750
4841
|
function buildSlackReviewItemCard(item) {
|
|
4751
4842
|
const text = itemText(item);
|
|
4752
4843
|
const link = getDashboardReviewItemLink(item.id);
|
|
4753
|
-
const details = [item.status === "open" ? assigneeText(item) : closedNote(item), ...link ? [`<${link}|Open in the
|
|
4844
|
+
const details = [item.status === "open" ? assigneeText(item) : closedNote(item), ...link ? [`<${link}|Open in the Inbox>`] : []].map((part) => ({
|
|
4754
4845
|
type: "mrkdwn",
|
|
4755
4846
|
text: truncate$1(part, MAX_CONTEXT_CHARS)
|
|
4756
4847
|
}));
|
|
@@ -4780,7 +4871,7 @@ function buildHiddenSlackReviewItemCard(item) {
|
|
|
4780
4871
|
type: "context",
|
|
4781
4872
|
elements: [{
|
|
4782
4873
|
type: "mrkdwn",
|
|
4783
|
-
text: link ? `This review item is not shown in this thread. <${link}|Open the
|
|
4874
|
+
text: link ? `This review item is not shown in this thread. <${link}|Open the Inbox>.` : "This review item is not shown in this thread."
|
|
4784
4875
|
}]
|
|
4785
4876
|
}],
|
|
4786
4877
|
text: "Review item"
|
|
@@ -5090,16 +5181,27 @@ function createSendFilesTool(state, materializeFile, output) {
|
|
|
5090
5181
|
});
|
|
5091
5182
|
}
|
|
5092
5183
|
// src/chat/slack/tools/send-files.ts
|
|
5093
|
-
/**
|
|
5094
|
-
|
|
5184
|
+
/**
|
|
5185
|
+
* Deliver files to the active Slack Location and retain Conversation
|
|
5186
|
+
* attachments. While the Conversation is detached from Slack, files are only
|
|
5187
|
+
* retained.
|
|
5188
|
+
*/
|
|
5189
|
+
function createSlackSendFilesTool(context, state, materializeFile, conversationId, attachments) {
|
|
5095
5190
|
const channelId = context.locationChannelId;
|
|
5096
5191
|
const threadTs = context.threadTs ?? context.messageTs;
|
|
5097
5192
|
return createSendFilesTool(state, materializeFile, {
|
|
5098
|
-
attachments
|
|
5193
|
+
...attachments ? { attachments: {
|
|
5194
|
+
...attachments,
|
|
5195
|
+
conversationId
|
|
5196
|
+
} } : void 0,
|
|
5099
5197
|
delivery: {
|
|
5100
5198
|
key: `${channelId}:${threadTs ?? ""}`,
|
|
5101
5199
|
description: "Send one or more sandbox files into the active Slack conversation.",
|
|
5102
5200
|
async send(files) {
|
|
5201
|
+
if (await isConversationDeliveryPaused(conversationId)) {
|
|
5202
|
+
if (!attachments) throw new ToolInputError("This conversation is detached from Slack, so files cannot be sent to it.");
|
|
5203
|
+
return;
|
|
5204
|
+
}
|
|
5103
5205
|
await uploadFilesToConversation({
|
|
5104
5206
|
channelId,
|
|
5105
5207
|
files: files.map((file) => ({
|
|
@@ -5921,7 +6023,7 @@ const STATIC_TOOL_BINDERS = {
|
|
|
5921
6023
|
updateReviewItem: (run) => createUpdateReviewItemTool(run.context, run.reviewItemServices())
|
|
5922
6024
|
};
|
|
5923
6025
|
const AGENT_TOOL_LIMIT = (turnTools) => turnTools.agents === "none" ? "A person's Turn in a Thread cannot use agent tools." : void 0;
|
|
5924
|
-
const
|
|
6026
|
+
const INBOX_LIMIT = (turnTools) => turnTools.inbox ? void 0 : `A child agent cannot use the Inbox. Use ${REPORT_BLOCKED_TOOL_NAME} to tell the parent agent what needs a person.`;
|
|
5925
6027
|
const TURN_TOOL_LIMITS = {
|
|
5926
6028
|
spawnAgent: AGENT_TOOL_LIMIT,
|
|
5927
6029
|
stopAgent: AGENT_TOOL_LIMIT,
|
|
@@ -5932,9 +6034,9 @@ const TURN_TOOL_LIMITS = {
|
|
|
5932
6034
|
[REPORT_BLOCKED_TOOL_NAME]: (turnTools) => turnTools.reportBlocked === "none" ? "This Turn cannot send a blocked report." : void 0,
|
|
5933
6035
|
updateUserCustomization: (turnTools) => turnTools.userCustomization ? void 0 : "Only a person's Turn can change user customization.",
|
|
5934
6036
|
setConversationSubscription: (turnTools) => turnTools.subscriptions ? void 0 : "Only a person's Turn can change subscriptions.",
|
|
5935
|
-
addReviewItem:
|
|
5936
|
-
searchReviewItems:
|
|
5937
|
-
updateReviewItem:
|
|
6037
|
+
addReviewItem: INBOX_LIMIT,
|
|
6038
|
+
searchReviewItems: INBOX_LIMIT,
|
|
6039
|
+
updateReviewItem: INBOX_LIMIT
|
|
5938
6040
|
};
|
|
5939
6041
|
function attachmentStore(run) {
|
|
5940
6042
|
const storage = run.context.attachmentStorage;
|
|
@@ -6020,7 +6122,7 @@ const RUN_BUILT_TOOL_BUILDERS = {
|
|
|
6020
6122
|
sendFiles: (run) => {
|
|
6021
6123
|
if (!run.slack) return void 0;
|
|
6022
6124
|
if (!resolveChannelCapabilities(run.slack.locationChannelId).canSendFiles) return void 0;
|
|
6023
|
-
return createSlackSendFilesTool(run.slack, run.state, (input) => readSandboxFileUpload(run.context.workspace, input), attachmentStore(run));
|
|
6125
|
+
return createSlackSendFilesTool(run.slack, run.state, (input) => readSandboxFileUpload(run.context.workspace, input), run.context.conversationId, attachmentStore(run));
|
|
6024
6126
|
},
|
|
6025
6127
|
addReaction: (run) => {
|
|
6026
6128
|
if (!run.slack) return void 0;
|
|
@@ -6763,31 +6865,26 @@ function handleToolExecutionError(error, toolName, toolCallId, shouldTrace, conv
|
|
|
6763
6865
|
function effectiveToolExposure(definition) {
|
|
6764
6866
|
return definition.exposure ?? "direct";
|
|
6765
6867
|
}
|
|
6868
|
+
const EXPOSURE_TABLES = {
|
|
6869
|
+
direct: [
|
|
6870
|
+
"directTools",
|
|
6871
|
+
"catalogTools",
|
|
6872
|
+
"scriptTools"
|
|
6873
|
+
],
|
|
6874
|
+
deferred: ["catalogTools", "scriptTools"],
|
|
6875
|
+
modelOnly: ["directTools"],
|
|
6876
|
+
codemode: ["scriptTools"],
|
|
6877
|
+
hidden: []
|
|
6878
|
+
};
|
|
6766
6879
|
/** Plan which callers may call each tool. `ToolExposure` owns the rules. */
|
|
6767
6880
|
function planToolExposure(tools) {
|
|
6768
|
-
const
|
|
6769
|
-
|
|
6770
|
-
|
|
6771
|
-
|
|
6772
|
-
case "direct":
|
|
6773
|
-
directTools[name] = definition;
|
|
6774
|
-
catalogTools[name] = definition;
|
|
6775
|
-
scriptTools[name] = definition;
|
|
6776
|
-
break;
|
|
6777
|
-
case "deferred":
|
|
6778
|
-
catalogTools[name] = definition;
|
|
6779
|
-
scriptTools[name] = definition;
|
|
6780
|
-
break;
|
|
6781
|
-
case "modelOnly":
|
|
6782
|
-
directTools[name] = definition;
|
|
6783
|
-
break;
|
|
6784
|
-
case "codemode": scriptTools[name] = definition;
|
|
6785
|
-
}
|
|
6786
|
-
return {
|
|
6787
|
-
catalogTools,
|
|
6788
|
-
directTools,
|
|
6789
|
-
scriptTools
|
|
6881
|
+
const planned = {
|
|
6882
|
+
catalogTools: {},
|
|
6883
|
+
directTools: {},
|
|
6884
|
+
scriptTools: {}
|
|
6790
6885
|
};
|
|
6886
|
+
for (const [name, definition] of Object.entries(tools)) for (const table of EXPOSURE_TABLES[effectiveToolExposure(definition)]) planned[table][name] = definition;
|
|
6887
|
+
return planned;
|
|
6791
6888
|
}
|
|
6792
6889
|
// src/chat/tools/search-tools-rerank.ts
|
|
6793
6890
|
const MAX_PICKED_TOOLS = 3;
|
|
@@ -9264,6 +9361,26 @@ function buildToolActionEvidence(messages) {
|
|
|
9264
9361
|
}
|
|
9265
9362
|
// src/chat/agent-invocations/root-conversation.ts
|
|
9266
9363
|
/**
|
|
9364
|
+
* Reads the authority of an action from the Conversation of its Run.
|
|
9365
|
+
*
|
|
9366
|
+
* When Guardian reviews an action, the runtime reads the messages of the
|
|
9367
|
+
* Conversation that the Run belongs to, and never of a Conversation above
|
|
9368
|
+
* it. The source is the `message` events: the durable visible transcript.
|
|
9369
|
+
* Compaction never rewrites these events, so an early request or a
|
|
9370
|
+
* later revocation is still there after the model history changes.
|
|
9371
|
+
*
|
|
9372
|
+
* A message counts as the user only when its stored author Identity is one
|
|
9373
|
+
* of the Identities of the person behind the Run's Actor: every Identity of
|
|
9374
|
+
* their User, or only the Actor's own Identity when it has no User. So a
|
|
9375
|
+
* Inbox answer from the person's web Identity counts in a Slack thread.
|
|
9376
|
+
* A message without a stored author Identity does not count. The local CLI is
|
|
9377
|
+
* the one exception, because it has no per-person Identity. A Run that an
|
|
9378
|
+
* agent started follows its parent agent, so the tasks and messages that the
|
|
9379
|
+
* parent sent with spawnAgent or messageAgent count as the user there, and no
|
|
9380
|
+
* person's message does. Each other message keeps its real author as a label
|
|
9381
|
+
* and is only context. Nothing is copied into the Run.
|
|
9382
|
+
*/
|
|
9383
|
+
/**
|
|
9267
9384
|
* Most root context messages that Guardian reads, newest first. Codex uses
|
|
9268
9385
|
* 16. Messages that can authorize do not count toward this number.
|
|
9269
9386
|
*/
|
|
@@ -9274,17 +9391,18 @@ const MAX_ROOT_MESSAGE_CHARS = 4e3;
|
|
|
9274
9391
|
const MAX_ROOT_CONVERSATION_CHARS = 24e3;
|
|
9275
9392
|
/** Message events read from the log. Edits and skipped messages use some. */
|
|
9276
9393
|
const MAX_ROOT_MESSAGE_EVENTS = 64;
|
|
9277
|
-
|
|
9278
|
-
|
|
9279
|
-
|
|
9394
|
+
const messageAuthorSchema = z.object({
|
|
9395
|
+
isBot: z.unknown().optional(),
|
|
9396
|
+
userId: z.string()
|
|
9397
|
+
});
|
|
9280
9398
|
/**
|
|
9281
9399
|
* Build the Actor that wrote one root message, from the runtime-recorded
|
|
9282
9400
|
* author and the root's provider. Returns nothing when it is not known.
|
|
9283
9401
|
*/
|
|
9284
9402
|
function messageAuthor(root, data) {
|
|
9285
|
-
const author =
|
|
9286
|
-
const userId =
|
|
9287
|
-
if (!userId || author?.
|
|
9403
|
+
const author = messageAuthorSchema.safeParse(data.meta?.["author"]).data;
|
|
9404
|
+
const userId = author?.userId.trim();
|
|
9405
|
+
if (!userId || author?.isBot === true) return;
|
|
9288
9406
|
const session = root.sessionSource;
|
|
9289
9407
|
const platform = session?.kind ?? root.destination?.platform;
|
|
9290
9408
|
if (platform === "slack") {
|
|
@@ -9494,6 +9612,7 @@ async function createRunSandbox(args) {
|
|
|
9494
9612
|
}
|
|
9495
9613
|
});
|
|
9496
9614
|
const workspace = args.state.sandboxRef?.workspaceId ? await getWorkspace(getDb(), args.state.sandboxRef.workspaceId) : void 0;
|
|
9615
|
+
const attachmentStorage = args.run.environment?.attachmentStorage;
|
|
9497
9616
|
const agentSandbox = createAgentSandbox({
|
|
9498
9617
|
sandboxRef: args.state.sandboxRef,
|
|
9499
9618
|
workspace,
|
|
@@ -9505,6 +9624,11 @@ async function createRunSandbox(args) {
|
|
|
9505
9624
|
credentialEgress: args.run.credentialContext,
|
|
9506
9625
|
credentialAuditSource: credentialAuditSource(args.run.source),
|
|
9507
9626
|
actor: args.currentActor,
|
|
9627
|
+
artifacts: attachmentStorage ? createArtifactSync({
|
|
9628
|
+
conversationId: args.run.conversationId,
|
|
9629
|
+
db: getSqlExecutor(),
|
|
9630
|
+
storage: attachmentStorage
|
|
9631
|
+
}) : void 0,
|
|
9508
9632
|
locationConfiguration: args.run.environment?.locationConfiguration,
|
|
9509
9633
|
configurationValues: args.configurationValues,
|
|
9510
9634
|
getActiveSkill: () => args.skillSandbox.getActiveSkill(),
|
|
@@ -9533,7 +9657,7 @@ function createPromptHookContext(args) {
|
|
|
9533
9657
|
run: args.run
|
|
9534
9658
|
}),
|
|
9535
9659
|
...actor ? { resolveActorIdentity: async () => await readActorIdentity(actor) } : void 0,
|
|
9536
|
-
userText: args.
|
|
9660
|
+
userText: turnRequestText(args.run)
|
|
9537
9661
|
};
|
|
9538
9662
|
}
|
|
9539
9663
|
/** Record optional reporting without changing the loadSkill outcome. */
|
|
@@ -10087,1289 +10211,6 @@ function createResumeState(args) {
|
|
|
10087
10211
|
}
|
|
10088
10212
|
};
|
|
10089
10213
|
}
|
|
10090
|
-
// src/chat/agent/context-summary.ts
|
|
10091
|
-
/**
|
|
10092
|
-
* Context summary for capacity compaction.
|
|
10093
|
-
*
|
|
10094
|
-
* The summary request is the agent model request for the same messages, with
|
|
10095
|
-
* one more user message that asks for the summary. The model, system prompt,
|
|
10096
|
-
* tools, and reasoning stay the same, so the provider can read the cached
|
|
10097
|
-
* prompt prefix of the last agent call. Anthropic drops cached messages when
|
|
10098
|
-
* `tool_choice`, thinking, or effort change, so the request keeps the tools
|
|
10099
|
-
* and the instruction forbids tool calls instead.
|
|
10100
|
-
*/
|
|
10101
|
-
/** Prompt name of the summary request on its `gen_ai.chat` span. */
|
|
10102
|
-
const CONTEXT_COMPACTION_PROMPT_NAME = "junior.context_compaction";
|
|
10103
|
-
const SUMMARY_MAX_TOKENS = 8e3;
|
|
10104
|
-
const SUMMARY_TAG = "summary";
|
|
10105
|
-
const SUMMARY_TAGS = renderInlineTag(SUMMARY_TAG, "");
|
|
10106
|
-
const SUMMARY_INSTRUCTION = `Stop work on the task now. Do not call tools. Write a summary of the conversation so far. The summary replaces the earlier history, and you will continue the work from the summary alone.
|
|
10107
|
-
|
|
10108
|
-
Return only the summary inside ${SUMMARY_TAGS} tags. Use these sections in this order. Write each item as one short line that starts with "- ". Write "- None" for an empty section.
|
|
10109
|
-
|
|
10110
|
-
## Goal
|
|
10111
|
-
## Constraints & preferences
|
|
10112
|
-
## Progress
|
|
10113
|
-
### Done
|
|
10114
|
-
### In progress
|
|
10115
|
-
### Blocked
|
|
10116
|
-
## Key decisions
|
|
10117
|
-
## Open asks
|
|
10118
|
-
User requests that are not complete yet, quoted in the user's exact words.
|
|
10119
|
-
## References
|
|
10120
|
-
Exact file paths, IDs, URLs, commands, and error text that the work needs. At most 20 items.
|
|
10121
|
-
## Next steps
|
|
10122
|
-
|
|
10123
|
-
Rules:
|
|
10124
|
-
- Keep the summary under 1,000 words.
|
|
10125
|
-
- Leave out the system prompt, AGENTS.md instructions, tool descriptions, and environment details. They are added again.
|
|
10126
|
-
- Do not mention this request or the summary itself.
|
|
10127
|
-
- If the history contains an earlier summary, update it. Keep the items that are still true, move finished work to Done, and remove stale items. When the earlier summary and newer history disagree, use the newer history.`;
|
|
10128
|
-
const SUMMARY_NUDGE = `Do not call tools. Keep the summary short. Return only the summary inside ${SUMMARY_TAGS} tags.`;
|
|
10129
|
-
/** Raised when the model returns no usable summary after one nudge. */
|
|
10130
|
-
var ContextSummaryError = class extends Error {
|
|
10131
|
-
failure;
|
|
10132
|
-
/** Estimated cost of the summary requests that did not succeed. */
|
|
10133
|
-
costUsd;
|
|
10134
|
-
constructor(failure, costUsd, options) {
|
|
10135
|
-
super(`Context summary failed: ${failure}`, options);
|
|
10136
|
-
this.failure = failure;
|
|
10137
|
-
this.name = "ContextSummaryError";
|
|
10138
|
-
if (costUsd !== void 0) this.costUsd = costUsd;
|
|
10139
|
-
}
|
|
10140
|
-
};
|
|
10141
|
-
/**
|
|
10142
|
-
* Build the model request that the agent loop sends for these messages.
|
|
10143
|
-
*
|
|
10144
|
-
* This repeats the steps of pi-agent-core before each model call
|
|
10145
|
-
* (`streamAssistantResponse` and `createLoopConfig`, which Pi does not
|
|
10146
|
-
* export): transform and convert the messages, then read the model,
|
|
10147
|
-
* reasoning, tools, and request options from the agent. A unit test compares
|
|
10148
|
-
* this request with the one that a real Pi `Agent` loop passes to `streamFn`,
|
|
10149
|
-
* so it fails when Pi changes these steps.
|
|
10150
|
-
*/
|
|
10151
|
-
async function buildAgentModelRequest(agent, messages, signal) {
|
|
10152
|
-
const { model, thinkingLevel, tools } = agent.state;
|
|
10153
|
-
const leading = getInitialSystemMessage(agent.state.messages);
|
|
10154
|
-
const transformed = agent.transformContext ? await agent.transformContext(messages, signal) : messages;
|
|
10155
|
-
return {
|
|
10156
|
-
model,
|
|
10157
|
-
context: {
|
|
10158
|
-
...foldLeadingSystemMessages(leading ? getSystemMessageText$1(leading) : "", await agent.convertToLlm(transformed)),
|
|
10159
|
-
tools
|
|
10160
|
-
},
|
|
10161
|
-
options: {
|
|
10162
|
-
reasoning: thinkingLevel === "off" ? void 0 : thinkingLevel,
|
|
10163
|
-
sessionId: agent.sessionId,
|
|
10164
|
-
onPayload: agent.onPayload,
|
|
10165
|
-
onResponse: agent.onResponse,
|
|
10166
|
-
transport: agent.transport,
|
|
10167
|
-
thinkingBudgets: agent.thinkingBudgets,
|
|
10168
|
-
maxRetryDelayMs: agent.maxRetryDelayMs,
|
|
10169
|
-
apiKey: await agent.getApiKey?.(model.provider) || void 0,
|
|
10170
|
-
identity: mergeClientIdentity(DEFAULT_AGENT_IDENTITY, agent.identity),
|
|
10171
|
-
signal
|
|
10172
|
-
}
|
|
10173
|
-
};
|
|
10174
|
-
}
|
|
10175
|
-
function userText(text) {
|
|
10176
|
-
return {
|
|
10177
|
-
role: "user",
|
|
10178
|
-
content: [{
|
|
10179
|
-
type: "text",
|
|
10180
|
-
text
|
|
10181
|
-
}],
|
|
10182
|
-
timestamp: Date.now()
|
|
10183
|
-
};
|
|
10184
|
-
}
|
|
10185
|
-
async function complete(request, streamFn, appended) {
|
|
10186
|
-
const message = await (await streamFn(request.model, {
|
|
10187
|
-
...request.context,
|
|
10188
|
-
messages: [...request.context.messages, ...appended]
|
|
10189
|
-
}, {
|
|
10190
|
-
...request.options,
|
|
10191
|
-
maxTokens: SUMMARY_MAX_TOKENS
|
|
10192
|
-
})).result();
|
|
10193
|
-
if (message.stopReason === "error" || message.stopReason === "aborted") throw createProviderError(message.errorMessage ?? message.stopReason, { modelId: request.model.id });
|
|
10194
|
-
return message;
|
|
10195
|
-
}
|
|
10196
|
-
/** Read the summary, or name why the output is not a usable summary. */
|
|
10197
|
-
function readSummary(message) {
|
|
10198
|
-
if (message.content.some((part) => part.type === "toolCall")) return { failure: "tool_call" };
|
|
10199
|
-
if (message.stopReason === "length") return { failure: "max_tokens" };
|
|
10200
|
-
const text = message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("").trim();
|
|
10201
|
-
if (!text) return { failure: "empty" };
|
|
10202
|
-
const summary = findTag(text, SUMMARY_TAG)?.body.trim();
|
|
10203
|
-
return summary ? { summary } : { failure: "missing_summary" };
|
|
10204
|
-
}
|
|
10205
|
-
/**
|
|
10206
|
-
* Ask the agent model for a summary of the request messages.
|
|
10207
|
-
*
|
|
10208
|
-
* A tool call, a stop at the output limit, empty output, or output without
|
|
10209
|
-
* `<summary>` tags gets one nudge. A second failure throws
|
|
10210
|
-
* `ContextSummaryError`, so the caller keeps the full history. The cost
|
|
10211
|
-
* covers each summary request, including a nudged one.
|
|
10212
|
-
*/
|
|
10213
|
-
async function requestContextSummary(request, streamFn) {
|
|
10214
|
-
const instruction = userText(SUMMARY_INSTRUCTION);
|
|
10215
|
-
const firstMessage = await complete(request, streamFn, [instruction]);
|
|
10216
|
-
const first = readSummary(firstMessage);
|
|
10217
|
-
if ("summary" in first) return withCost(first.summary, firstMessage);
|
|
10218
|
-
logWarn("context_compaction.summary.nudged", { "app.compaction.summary_failure": first.failure });
|
|
10219
|
-
let secondMessage;
|
|
10220
|
-
try {
|
|
10221
|
-
secondMessage = await complete(request, streamFn, [instruction, userText(SUMMARY_NUDGE)]);
|
|
10222
|
-
} catch (error) {
|
|
10223
|
-
throw new ContextSummaryError("request_failed", summaryCostUsd(firstMessage), { cause: error });
|
|
10224
|
-
}
|
|
10225
|
-
const second = readSummary(secondMessage);
|
|
10226
|
-
if ("summary" in second) return withCost(second.summary, firstMessage, secondMessage);
|
|
10227
|
-
throw new ContextSummaryError(second.failure, summaryCostUsd(firstMessage, secondMessage));
|
|
10228
|
-
}
|
|
10229
|
-
function summaryCostUsd(...messages) {
|
|
10230
|
-
return agentTurnCostUsd(extractGenAiUsageSummary(...messages));
|
|
10231
|
-
}
|
|
10232
|
-
function withCost(summary, ...messages) {
|
|
10233
|
-
const costUsd = summaryCostUsd(...messages);
|
|
10234
|
-
return costUsd === void 0 ? { summary } : {
|
|
10235
|
-
summary,
|
|
10236
|
-
costUsd
|
|
10237
|
-
};
|
|
10238
|
-
}
|
|
10239
|
-
// src/chat/services/context-compaction-telemetry.ts
|
|
10240
|
-
/**
|
|
10241
|
-
* Context compaction telemetry.
|
|
10242
|
-
*
|
|
10243
|
-
* Each compaction gets one `agent.context_compaction` span. The span and its
|
|
10244
|
-
* children, such as the summary `gen_ai.chat` span, carry
|
|
10245
|
-
* `app.compaction.mode`. The `chat.turn` span sums the time that the Turn
|
|
10246
|
-
* waited on compaction, with summary calls and prepared-summary swaps apart.
|
|
10247
|
-
*
|
|
10248
|
-
* Attribute keys do not contain "token": Sentry data scrubbing removes the
|
|
10249
|
-
* values of keys that match it.
|
|
10250
|
-
*/
|
|
10251
|
-
const turnCompactionWait = new AsyncLocalStorage();
|
|
10252
|
-
/** Run one compaction in its span and add its time to the Turn wait. */
|
|
10253
|
-
async function withCompactionSpan(mode, work, callback) {
|
|
10254
|
-
const startedAtMs = performance.now();
|
|
10255
|
-
try {
|
|
10256
|
-
return await runWithLogAttributes({ "app.compaction.mode": mode }, () => withSpan("agent.context_compaction", "agent.context_compaction", {}, callback));
|
|
10257
|
-
} finally {
|
|
10258
|
-
const wait = turnCompactionWait.getStore();
|
|
10259
|
-
if (wait) wait[work] += performance.now() - startedAtMs;
|
|
10260
|
-
}
|
|
10261
|
-
}
|
|
10262
|
-
/** Run one `chat.turn` callback and record its compaction wait, if any. */
|
|
10263
|
-
async function measureTurnCompactionWait(setTurnAttributes, callback) {
|
|
10264
|
-
const wait = {
|
|
10265
|
-
summary: 0,
|
|
10266
|
-
swap: 0
|
|
10267
|
-
};
|
|
10268
|
-
try {
|
|
10269
|
-
return await turnCompactionWait.run(wait, callback);
|
|
10270
|
-
} finally {
|
|
10271
|
-
setTurnAttributes({
|
|
10272
|
-
...wait.summary > 0 ? { "app.turn.compaction_wait_ms": Math.round(wait.summary) } : void 0,
|
|
10273
|
-
...wait.swap > 0 ? { "app.turn.compaction_swap_wait_ms": Math.round(wait.swap) } : void 0
|
|
10274
|
-
});
|
|
10275
|
-
}
|
|
10276
|
-
}
|
|
10277
|
-
/**
|
|
10278
|
-
* Track the replacement that waits for the provider-reported input of the
|
|
10279
|
-
* next model request. That request's `gen_ai.chat` span shows whether the
|
|
10280
|
-
* replacement got the history below the threshold. Production drops info
|
|
10281
|
-
* logs, so this is a span attribute.
|
|
10282
|
-
*/
|
|
10283
|
-
function createNextInputTracker() {
|
|
10284
|
-
let pending;
|
|
10285
|
-
return {
|
|
10286
|
-
replaced(mode, threshold) {
|
|
10287
|
-
pending = {
|
|
10288
|
-
mode,
|
|
10289
|
-
threshold
|
|
10290
|
-
};
|
|
10291
|
-
},
|
|
10292
|
-
attributes(inputSize) {
|
|
10293
|
-
if (!pending || !inputSize) return;
|
|
10294
|
-
const { mode, threshold } = pending;
|
|
10295
|
-
pending = void 0;
|
|
10296
|
-
return {
|
|
10297
|
-
"app.compaction.mode": mode,
|
|
10298
|
-
"app.compaction.next_input.size": inputSize,
|
|
10299
|
-
"app.compaction.next_input.over_threshold": inputSize > threshold,
|
|
10300
|
-
"app.compaction.threshold": threshold
|
|
10301
|
-
};
|
|
10302
|
-
}
|
|
10303
|
-
};
|
|
10304
|
-
}
|
|
10305
|
-
// src/chat/services/background-compaction.ts
|
|
10306
|
-
/**
|
|
10307
|
-
* Background compaction: prepare a summary before the history is full.
|
|
10308
|
-
*
|
|
10309
|
-
* After each model request at or above the mark, also in the middle of a
|
|
10310
|
-
* Turn, the Turn appends `compaction_requested` and sends a job. The job
|
|
10311
|
-
* asks the agent model for a summary of the history up to the marked event
|
|
10312
|
-
* and appends `compaction_prepared`. Turns keep the full history until a later
|
|
10313
|
-
* change swaps the summary in. Blocking compaction stays the fallback.
|
|
10314
|
-
*
|
|
10315
|
-
* The summary request repeats the system prompt and tools of the last agent
|
|
10316
|
-
* request, so the provider can read its cached prompt prefix. The job runs in
|
|
10317
|
-
* another request, so the Turn stores them in the State adapter.
|
|
10318
|
-
*/
|
|
10319
|
-
/**
|
|
10320
|
-
* Failed attempts for one History version before background tries stop.
|
|
10321
|
-
*/
|
|
10322
|
-
const MAX_FAILED_ATTEMPTS = 2;
|
|
10323
|
-
/**
|
|
10324
|
-
* A request without a prepared result after this long counts as a failed
|
|
10325
|
-
* attempt, so a later Turn can request again. This covers a lost job.
|
|
10326
|
-
*/
|
|
10327
|
-
const REQUEST_TIMEOUT_MS = 6e5;
|
|
10328
|
-
/** The queue drops a message after this long, so the snapshot can go too. */
|
|
10329
|
-
const SNAPSHOT_TTL_MS = QUEUE_SIGNATURE_MAX_AGE_MS;
|
|
10330
|
-
function snapshotKey(message) {
|
|
10331
|
-
return `${backgroundCompactionId(message)}:snapshot`;
|
|
10332
|
-
}
|
|
10333
|
-
/** Provider-reported input of the last model request, cache included. */
|
|
10334
|
-
function lastRequestInputSize(messages) {
|
|
10335
|
-
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
10336
|
-
const message = messages[index];
|
|
10337
|
-
if (message.role === "assistant") {
|
|
10338
|
-
const { input, cacheRead, cacheWrite } = message.usage;
|
|
10339
|
-
return input + cacheRead + cacheWrite;
|
|
10340
|
-
}
|
|
10341
|
-
}
|
|
10342
|
-
}
|
|
10343
|
-
/**
|
|
10344
|
-
* Return whether a Turn may request a background summary for this History
|
|
10345
|
-
* version. It may not while a request is pending, while a ready summary
|
|
10346
|
-
* waits for the compaction threshold, or after the attempt limit.
|
|
10347
|
-
*/
|
|
10348
|
-
function mayRequest(events, historyVersion, nowMs) {
|
|
10349
|
-
const outcomes = /* @__PURE__ */ new Map();
|
|
10350
|
-
for (const event of events) if (event.data.type === "compaction_prepared" && event.data.historyVersion === historyVersion) outcomes.set(event.data.markSeq, event.data.outcome);
|
|
10351
|
-
let failed = 0;
|
|
10352
|
-
for (const event of events) {
|
|
10353
|
-
if (event.data.type !== "compaction_requested" || event.data.historyVersion !== historyVersion) continue;
|
|
10354
|
-
const prepared = outcomes.get(event.data.markSeq);
|
|
10355
|
-
if (prepared === "ready") return false;
|
|
10356
|
-
if (prepared || nowMs - event.createdAtMs >= REQUEST_TIMEOUT_MS) failed += 1;
|
|
10357
|
-
else return false;
|
|
10358
|
-
}
|
|
10359
|
-
return failed < MAX_FAILED_ATTEMPTS;
|
|
10360
|
-
}
|
|
10361
|
-
/**
|
|
10362
|
-
* Find the newest background compaction fact of the current History version.
|
|
10363
|
-
* Facts of earlier versions belong to history that a replacement already
|
|
10364
|
-
* removed.
|
|
10365
|
-
*/
|
|
10366
|
-
async function loadLatestBackgroundCompaction(conversationId) {
|
|
10367
|
-
const store = getConversationEventStore();
|
|
10368
|
-
const [historyVersion, page] = await Promise.all([store.loadCurrentHistoryVersion(conversationId), store.query(conversationId, {
|
|
10369
|
-
limit: 1,
|
|
10370
|
-
types: ["compaction_requested", "compaction_prepared"]
|
|
10371
|
-
})]);
|
|
10372
|
-
const event = page.events.at(-1);
|
|
10373
|
-
return event && event.historyVersion === historyVersion ? {
|
|
10374
|
-
event,
|
|
10375
|
-
historyVersion
|
|
10376
|
-
} : void 0;
|
|
10377
|
-
}
|
|
10378
|
-
/**
|
|
10379
|
-
* Return whether the newest fact is a pending request or a ready summary.
|
|
10380
|
-
* Then `mayRequest` is false too, so a Turn can skip the other reads.
|
|
10381
|
-
* Only one request is pending at a time, so the newest fact decides it.
|
|
10382
|
-
*/
|
|
10383
|
-
function waitsForUse(event, nowMs) {
|
|
10384
|
-
if (event.data.type === "compaction_requested") return nowMs - event.createdAtMs < REQUEST_TIMEOUT_MS;
|
|
10385
|
-
return event.data.type === "compaction_prepared" && event.data.outcome === "ready";
|
|
10386
|
-
}
|
|
10387
|
-
/**
|
|
10388
|
-
* Request a background summary when the model request that just ended was at
|
|
10389
|
-
* or above the mark.
|
|
10390
|
-
*
|
|
10391
|
-
* The agent runs it after each model request, so a long Turn gets a summary
|
|
10392
|
-
* before the compaction threshold. Without a queue or below the mark, it does
|
|
10393
|
-
* nothing. A failure here leaves blocking compaction as the fallback, so it
|
|
10394
|
-
* is logged and does not fail the Turn. When the send fails after the request
|
|
10395
|
-
* is written, the request times out and counts as a failed attempt.
|
|
10396
|
-
*/
|
|
10397
|
-
async function requestBackgroundCompaction(args) {
|
|
10398
|
-
if (!args.queue) return;
|
|
10399
|
-
const inputSize = lastRequestInputSize(readAgentHistory(args.agent.state.messages));
|
|
10400
|
-
if (inputSize === void 0 || inputSize < getAgentBackgroundCompactionMarkTokens(args.modelId)) return;
|
|
10401
|
-
try {
|
|
10402
|
-
await requestAboveMark({
|
|
10403
|
-
...args,
|
|
10404
|
-
inputSize,
|
|
10405
|
-
queue: args.queue
|
|
10406
|
-
});
|
|
10407
|
-
} catch (error) {
|
|
10408
|
-
logWarn("context_compaction.background.request_failed", { "error.type": error instanceof Error ? error.name : typeof error });
|
|
10409
|
-
}
|
|
10410
|
-
}
|
|
10411
|
-
async function requestAboveMark(args) {
|
|
10412
|
-
const nowMs = Date.now();
|
|
10413
|
-
const eventStore = getConversationEventStore();
|
|
10414
|
-
const latest = await loadLatestBackgroundCompaction(args.conversationId);
|
|
10415
|
-
if (latest) {
|
|
10416
|
-
if (waitsForUse(latest.event, nowMs)) return;
|
|
10417
|
-
if (!mayRequest((await Promise.all([eventStore.loadEventsOfType(args.conversationId, "compaction_requested"), eventStore.loadEventsOfType(args.conversationId, "compaction_prepared")])).flat(), latest.historyVersion, nowMs)) return;
|
|
10418
|
-
}
|
|
10419
|
-
const events = await eventStore.loadCurrentHistory(args.conversationId);
|
|
10420
|
-
const historyVersion = events[0]?.historyVersion;
|
|
10421
|
-
if (historyVersion === void 0 || !mayRequest(events, historyVersion, nowMs)) return;
|
|
10422
|
-
const projection = projectConversationEvents(events);
|
|
10423
|
-
const markSeq = Math.max(projection.seqs.at(-1) ?? -1, projection.replacementSeq ?? -1);
|
|
10424
|
-
if (markSeq < 0) return;
|
|
10425
|
-
const message = {
|
|
10426
|
-
conversationId: args.conversationId,
|
|
10427
|
-
historyVersion,
|
|
10428
|
-
markSeq
|
|
10429
|
-
};
|
|
10430
|
-
const { messages, thinkingLevel, tools } = args.agent.state;
|
|
10431
|
-
const leading = getInitialSystemMessage(messages);
|
|
10432
|
-
const snapshot = {
|
|
10433
|
-
conversationPrivacy: args.conversationPrivacy ?? "private",
|
|
10434
|
-
inputSize: args.inputSize,
|
|
10435
|
-
modelId: args.modelId,
|
|
10436
|
-
systemPrompt: leading ? getSystemMessageText$1(leading) : "",
|
|
10437
|
-
thinkingLevel,
|
|
10438
|
-
tools: tools.map((tool) => ({
|
|
10439
|
-
name: tool.name,
|
|
10440
|
-
label: tool.label,
|
|
10441
|
-
description: tool.description,
|
|
10442
|
-
parameters: tool.parameters,
|
|
10443
|
-
...tool.constrainedSampling === void 0 ? void 0 : { constrainedSampling: tool.constrainedSampling }
|
|
10444
|
-
}))
|
|
10445
|
-
};
|
|
10446
|
-
await getStateAdapter().set(snapshotKey(message), JSON.parse(JSON.stringify(snapshot)), SNAPSHOT_TTL_MS);
|
|
10447
|
-
if ((await eventStore.append(args.conversationId, [{
|
|
10448
|
-
idempotencyKey: `${backgroundCompactionId(message)}:requested`,
|
|
10449
|
-
createdAtMs: nowMs,
|
|
10450
|
-
data: {
|
|
10451
|
-
type: "compaction_requested",
|
|
10452
|
-
markSeq,
|
|
10453
|
-
historyVersion,
|
|
10454
|
-
modelId: args.modelId
|
|
10455
|
-
}
|
|
10456
|
-
}], { activity: "preserve" })).length === 0) return;
|
|
10457
|
-
await args.queue.send(message);
|
|
10458
|
-
}
|
|
10459
|
-
/** A fixed label for a failed summary. Never raw exception text. */
|
|
10460
|
-
function failureLabel(error, signal) {
|
|
10461
|
-
if (signal.aborted) return "timeout";
|
|
10462
|
-
if (error instanceof ContextSummaryError && error.failure !== "request_failed") return error.failure;
|
|
10463
|
-
const providerError = findProviderError(error);
|
|
10464
|
-
return providerError ? `provider_${providerError.kind}` : "summary_error";
|
|
10465
|
-
}
|
|
10466
|
-
/**
|
|
10467
|
-
* Run one background compaction job.
|
|
10468
|
-
*
|
|
10469
|
-
* It writes `compaction_prepared` once for the request, with a summary or a
|
|
10470
|
-
* fixed failure label. It writes nothing when the request is no longer in
|
|
10471
|
-
* the current History version, because no Turn could use the summary.
|
|
10472
|
-
* `streamFn` replaces the model stream, for tests.
|
|
10473
|
-
*/
|
|
10474
|
-
async function processBackgroundCompaction(message, options = {}) {
|
|
10475
|
-
const startedAtMs = Date.now();
|
|
10476
|
-
await withLogContext({ conversationId: message.conversationId }, () => withCompactionSpan("background", "summary", async () => {
|
|
10477
|
-
setSpanAttributes({
|
|
10478
|
-
"app.compaction.mark_seq": message.markSeq,
|
|
10479
|
-
"app.compaction.history_version": message.historyVersion,
|
|
10480
|
-
...options.enqueuedAtMs === void 0 ? void 0 : { "app.compaction.queue_wait_ms": Math.max(0, startedAtMs - options.enqueuedAtMs) }
|
|
10481
|
-
});
|
|
10482
|
-
const outcome = await prepareSummary(message, options.streamFn);
|
|
10483
|
-
setSpanAttributes({ "app.compaction.outcome": outcome });
|
|
10484
|
-
}));
|
|
10485
|
-
}
|
|
10486
|
-
async function prepareSummary(message, streamFn) {
|
|
10487
|
-
const eventStore = getConversationEventStore();
|
|
10488
|
-
const state = getStateAdapter();
|
|
10489
|
-
const events = await eventStore.loadCurrentHistory(message.conversationId);
|
|
10490
|
-
const isThisRequest = (event) => (event.data.type === "compaction_requested" || event.data.type === "compaction_prepared") && event.data.historyVersion === message.historyVersion && event.data.markSeq === message.markSeq;
|
|
10491
|
-
const request = events.find((event) => isThisRequest(event) && event.data.type === "compaction_requested");
|
|
10492
|
-
if (request?.data.type !== "compaction_requested") {
|
|
10493
|
-
await state.delete(snapshotKey(message));
|
|
10494
|
-
return "stale";
|
|
10495
|
-
}
|
|
10496
|
-
const requested = request.data;
|
|
10497
|
-
if (events.some((event) => isThisRequest(event) && event.data.type === "compaction_prepared")) return "duplicate";
|
|
10498
|
-
const writePrepared = async (result) => {
|
|
10499
|
-
if (await eventStore.loadCurrentHistoryVersion(message.conversationId) !== message.historyVersion) {
|
|
10500
|
-
await state.delete(snapshotKey(message));
|
|
10501
|
-
return "stale";
|
|
10502
|
-
}
|
|
10503
|
-
await eventStore.append(message.conversationId, [{
|
|
10504
|
-
idempotencyKey: `${backgroundCompactionId(message)}:prepared`,
|
|
10505
|
-
createdAtMs: Date.now(),
|
|
10506
|
-
data: {
|
|
10507
|
-
type: "compaction_prepared",
|
|
10508
|
-
markSeq: message.markSeq,
|
|
10509
|
-
historyVersion: message.historyVersion,
|
|
10510
|
-
modelId: requested.modelId,
|
|
10511
|
-
...result
|
|
10512
|
-
}
|
|
10513
|
-
}], { activity: "preserve" });
|
|
10514
|
-
await state.delete(snapshotKey(message));
|
|
10515
|
-
if (result.outcome === "failed") setSpanAttributes({ "error.type": result.errorType });
|
|
10516
|
-
return result.outcome;
|
|
10517
|
-
};
|
|
10518
|
-
const remainingMs = request.createdAtMs + REQUEST_TIMEOUT_MS - Date.now();
|
|
10519
|
-
if (remainingMs <= 0) return await writePrepared({
|
|
10520
|
-
outcome: "failed",
|
|
10521
|
-
errorType: "timeout"
|
|
10522
|
-
});
|
|
10523
|
-
const snapshot = await state.get(snapshotKey(message));
|
|
10524
|
-
if (!snapshot) return await writePrepared({
|
|
10525
|
-
outcome: "failed",
|
|
10526
|
-
errorType: "snapshot_missing"
|
|
10527
|
-
});
|
|
10528
|
-
setSpanAttributes({ "app.compaction.input.size": snapshot.inputSize });
|
|
10529
|
-
const projection = projectConversationEvents(events, { maxSeq: message.markSeq });
|
|
10530
|
-
const signal = AbortSignal.timeout(remainingMs);
|
|
10531
|
-
let summary;
|
|
10532
|
-
try {
|
|
10533
|
-
summary = await runWithConversationPrivacy(snapshot.conversationPrivacy, async () => {
|
|
10534
|
-
const summaryStreamFn = createTracedStreamFn({
|
|
10535
|
-
conversationPrivacy: snapshot.conversationPrivacy,
|
|
10536
|
-
promptName: CONTEXT_COMPACTION_PROMPT_NAME,
|
|
10537
|
-
...streamFn ? { base: streamFn } : void 0
|
|
10538
|
-
});
|
|
10539
|
-
const tools = snapshot.tools.map((tool) => ({
|
|
10540
|
-
...tool,
|
|
10541
|
-
execute: async () => {
|
|
10542
|
-
throw new Error("Background compaction does not run tools");
|
|
10543
|
-
}
|
|
10544
|
-
}));
|
|
10545
|
-
return await requestContextSummary(await buildAgentModelRequest(new Agent({
|
|
10546
|
-
getApiKey: getGatewayApiKey,
|
|
10547
|
-
sessionId: message.conversationId,
|
|
10548
|
-
streamFn: withAgentRequest(summaryStreamFn, {
|
|
10549
|
-
systemPrompt: snapshot.systemPrompt,
|
|
10550
|
-
tools
|
|
10551
|
-
}),
|
|
10552
|
-
initialState: {
|
|
10553
|
-
systemPrompt: snapshot.systemPrompt,
|
|
10554
|
-
model: resolveGatewayModel(snapshot.modelId),
|
|
10555
|
-
thinkingLevel: snapshot.thinkingLevel,
|
|
10556
|
-
tools
|
|
10557
|
-
}
|
|
10558
|
-
}), projection.messages, signal), summaryStreamFn);
|
|
10559
|
-
});
|
|
10560
|
-
} catch (error) {
|
|
10561
|
-
return await writePrepared({
|
|
10562
|
-
outcome: "failed",
|
|
10563
|
-
errorType: failureLabel(error, signal),
|
|
10564
|
-
...error instanceof ContextSummaryError && error.costUsd !== void 0 ? { costUsd: error.costUsd } : void 0
|
|
10565
|
-
});
|
|
10566
|
-
}
|
|
10567
|
-
const outcome = await writePrepared({
|
|
10568
|
-
outcome: "ready",
|
|
10569
|
-
...summary
|
|
10570
|
-
});
|
|
10571
|
-
if (outcome === "ready") setSpanAttributes({
|
|
10572
|
-
"app.compaction.summary_chars": summary.summary.length,
|
|
10573
|
-
"app.compaction.ready_ms": Date.now() - request.createdAtMs
|
|
10574
|
-
});
|
|
10575
|
-
return outcome;
|
|
10576
|
-
}
|
|
10577
|
-
// src/chat/plan/snapshot.ts
|
|
10578
|
-
/**
|
|
10579
|
-
* Append one `<plan>` snapshot of the open items, read from the database, to
|
|
10580
|
-
* a compaction summary, so the plan and its version survive the history
|
|
10581
|
-
* replacement.
|
|
10582
|
-
*/
|
|
10583
|
-
async function appendPlanSnapshot(summaryText, conversationId) {
|
|
10584
|
-
const snapshot = renderPlanSnapshot(await listPlanItems(getSqlExecutor(), conversationId));
|
|
10585
|
-
return snapshot ? `${summaryText}\n\n${snapshot}` : summaryText;
|
|
10586
|
-
}
|
|
10587
|
-
// src/chat/services/context-compaction.ts
|
|
10588
|
-
/**
|
|
10589
|
-
* Context compaction.
|
|
10590
|
-
*
|
|
10591
|
-
* Bounds Pi history for long conversations and commits a history
|
|
10592
|
-
* replacement. Capacity compaction gets its summary from the caller, which
|
|
10593
|
-
* asks the agent model with the cached request prefix. Mid-turn replacements
|
|
10594
|
-
* keep the authored instruction before the summary. Turn-start replacements keep recent user
|
|
10595
|
-
* messages, the summary, then the new instruction. Checkpoints can append
|
|
10596
|
-
* fresh runtime context; the next replacement removes it again.
|
|
10597
|
-
*/
|
|
10598
|
-
const RETAINED_USER_MESSAGE_TOKENS = 2e4;
|
|
10599
|
-
/** Raised when Junior cannot compact history below the active model's hard ceiling. */
|
|
10600
|
-
var ContextInputLimitExceededError = class extends Error {
|
|
10601
|
-
estimatedTokens;
|
|
10602
|
-
inputLimitTokens;
|
|
10603
|
-
constructor(estimatedTokens, inputLimitTokens) {
|
|
10604
|
-
super(`Agent context is ${estimatedTokens} estimated input tokens, above the ${inputLimitTokens} token limit`);
|
|
10605
|
-
this.estimatedTokens = estimatedTokens;
|
|
10606
|
-
this.inputLimitTokens = inputLimitTokens;
|
|
10607
|
-
this.name = "ContextInputLimitExceededError";
|
|
10608
|
-
}
|
|
10609
|
-
};
|
|
10610
|
-
function textPart(value) {
|
|
10611
|
-
if (value && typeof value === "object" && value.type === "text" && typeof value.text === "string") return value.text;
|
|
10612
|
-
}
|
|
10613
|
-
/** Render Pi message text for retained user-message selection. */
|
|
10614
|
-
function messageText(message) {
|
|
10615
|
-
const content = message.content;
|
|
10616
|
-
const unwrapTask = message.role === "user";
|
|
10617
|
-
const displayText = (text) => unwrapTask ? unwrapCurrentInstruction(text) ?? text : text;
|
|
10618
|
-
if (!Array.isArray(content)) return typeof content === "string" ? displayText(content) : "";
|
|
10619
|
-
return content.map(textPart).filter((text) => Boolean(text)).map(displayText).join("\n").trim();
|
|
10620
|
-
}
|
|
10621
|
-
function sanitizeText(text) {
|
|
10622
|
-
return text.replace(/<data_base64>[\s\S]*?<\/data_base64>/g, "<data_base64>[omitted]</data_base64>").replace(/data:image\/[a-z0-9.+-]+;base64,[a-z0-9+/=]+/gi, "[image data omitted]").replaceAll("\0", " ").trim();
|
|
10623
|
-
}
|
|
10624
|
-
function truncateToTokenBudget(text, maxTokens) {
|
|
10625
|
-
const maxChars = Math.max(0, textCharsForTokens(maxTokens));
|
|
10626
|
-
if (text.length <= maxChars) return text;
|
|
10627
|
-
return `${text.slice(0, Math.max(0, maxChars - 3)).trimEnd()}...`;
|
|
10628
|
-
}
|
|
10629
|
-
function isCompactionSummary(text) {
|
|
10630
|
-
return isCompactionSummaryText(text);
|
|
10631
|
-
}
|
|
10632
|
-
function isPayloadHeavy(text) {
|
|
10633
|
-
return /<data_base64>[\s\S]*?<\/data_base64>|data:image\/[a-z0-9.+-]+;base64,/i.test(text);
|
|
10634
|
-
}
|
|
10635
|
-
/** Build a text-only user message for a replacement history. */
|
|
10636
|
-
function userMessage(text) {
|
|
10637
|
-
return {
|
|
10638
|
-
role: "user",
|
|
10639
|
-
content: [{
|
|
10640
|
-
type: "text",
|
|
10641
|
-
text
|
|
10642
|
-
}],
|
|
10643
|
-
timestamp: Date.now()
|
|
10644
|
-
};
|
|
10645
|
-
}
|
|
10646
|
-
function userMessageContent(message) {
|
|
10647
|
-
const content = message.content;
|
|
10648
|
-
return Array.isArray(content) ? content : [];
|
|
10649
|
-
}
|
|
10650
|
-
function hasTurnBootstrap(message) {
|
|
10651
|
-
return userMessageContent(message).some((part) => isTurnContextText(textPart(part)));
|
|
10652
|
-
}
|
|
10653
|
-
function isSessionTurnContext(text) {
|
|
10654
|
-
return isTurnContextText(text) && findTag(text, "runtime") !== void 0;
|
|
10655
|
-
}
|
|
10656
|
-
function isTurnContextText(text) {
|
|
10657
|
-
return text !== void 0 && startsWithTag(text, ["runtime-turn-context"]);
|
|
10658
|
-
}
|
|
10659
|
-
/**
|
|
10660
|
-
* Remove the sections that only the Turn that received them can use, and
|
|
10661
|
-
* plan deltas, which the `<plan>` snapshot of the summary replaces.
|
|
10662
|
-
*/
|
|
10663
|
-
function withoutRequestContext(text) {
|
|
10664
|
-
return stripTags(text, [...Object.values(REQUEST_CONTEXT_SECTION_TAG), PLAN_DELTA_TAG]);
|
|
10665
|
-
}
|
|
10666
|
-
/**
|
|
10667
|
-
* Remove the copies of capability sections that the Turn context of older
|
|
10668
|
-
* Turns held. Later system messages hold them now, and compaction folds
|
|
10669
|
-
* those.
|
|
10670
|
-
*/
|
|
10671
|
-
function withoutCapabilitySections(content) {
|
|
10672
|
-
return content.map((part) => {
|
|
10673
|
-
const text = textPart(part);
|
|
10674
|
-
return isTurnContextText(text) ? {
|
|
10675
|
-
...part,
|
|
10676
|
-
text: stripTags(text, Object.values(CAPABILITY_SECTION_TAG))
|
|
10677
|
-
} : part;
|
|
10678
|
-
});
|
|
10679
|
-
}
|
|
10680
|
-
/** Find the latest session context and keep only its session sections. */
|
|
10681
|
-
function latestSessionContext(messages) {
|
|
10682
|
-
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
10683
|
-
const message = messages[index];
|
|
10684
|
-
const text = userMessageContent(message).map(textPart).find(isSessionTurnContext);
|
|
10685
|
-
if (text) return {
|
|
10686
|
-
...message,
|
|
10687
|
-
content: [{
|
|
10688
|
-
type: "text",
|
|
10689
|
-
text: withoutRequestContext(text)
|
|
10690
|
-
}]
|
|
10691
|
-
};
|
|
10692
|
-
}
|
|
10693
|
-
}
|
|
10694
|
-
function effectiveRuntimeContext(messages) {
|
|
10695
|
-
let latestBootstrapIndex = -1;
|
|
10696
|
-
for (let index = messages.length - 1; index >= 0; index -= 1) if (hasTurnBootstrap(messages[index])) {
|
|
10697
|
-
latestBootstrapIndex = index;
|
|
10698
|
-
break;
|
|
10699
|
-
}
|
|
10700
|
-
const effectiveMessages = latestBootstrapIndex < 0 ? messages : messages.slice(latestBootstrapIndex);
|
|
10701
|
-
return runtimeContextContent(effectiveMessages, effectiveMessages);
|
|
10702
|
-
}
|
|
10703
|
-
function runtimeContextContent(messages, agentsMessages) {
|
|
10704
|
-
const allContent = messages.flatMap(userMessageContent);
|
|
10705
|
-
const firstAgentsIndex = allContent.findIndex((part) => textPart(part)?.startsWith("# AGENTS.md instructions") === true);
|
|
10706
|
-
const content = withoutCapabilitySections(allContent.filter((part) => textPart(part)?.startsWith("# AGENTS.md instructions") !== true));
|
|
10707
|
-
const visibleAgents = findVisibleAgentsInstructions(agentsMessages);
|
|
10708
|
-
if (visibleAgents?.active === true) {
|
|
10709
|
-
const insertionIndex = firstAgentsIndex < 0 ? content.length : Math.min(firstAgentsIndex, content.length);
|
|
10710
|
-
content.splice(insertionIndex, 0, {
|
|
10711
|
-
type: "text",
|
|
10712
|
-
text: renderAgentsInstructions({
|
|
10713
|
-
directory: visibleAgents.directory,
|
|
10714
|
-
text: visibleAgents.text
|
|
10715
|
-
})
|
|
10716
|
-
});
|
|
10717
|
-
}
|
|
10718
|
-
const latestTimestamp = messages.at(-1)?.timestamp;
|
|
10719
|
-
return {
|
|
10720
|
-
content,
|
|
10721
|
-
timestamp: typeof latestTimestamp === "number" ? latestTimestamp : Date.now()
|
|
10722
|
-
};
|
|
10723
|
-
}
|
|
10724
|
-
function toRuntimeContextMessage(runtimeContext, timestamp) {
|
|
10725
|
-
if (runtimeContext.content.length === 0) return;
|
|
10726
|
-
return {
|
|
10727
|
-
role: "user",
|
|
10728
|
-
content: runtimeContext.content,
|
|
10729
|
-
timestamp: timestamp ?? runtimeContext.timestamp
|
|
10730
|
-
};
|
|
10731
|
-
}
|
|
10732
|
-
function runtimeContextMessage(messages, timestamp) {
|
|
10733
|
-
return toRuntimeContextMessage(effectiveRuntimeContext(messages), timestamp);
|
|
10734
|
-
}
|
|
10735
|
-
/**
|
|
10736
|
-
* Build the runtime context that the current Turn can use after an in-turn
|
|
10737
|
-
* replacement.
|
|
10738
|
-
*
|
|
10739
|
-
* Request context, such as plugin context and disabled tools, is true only for
|
|
10740
|
-
* the Turn that received it. From earlier Turns, keep only the latest session
|
|
10741
|
-
* context and AGENTS.md instructions.
|
|
10742
|
-
*/
|
|
10743
|
-
function turnRuntimeContextMessage(messages, turnStartMessageIndex, timestamp) {
|
|
10744
|
-
if (turnStartMessageIndex === void 0) return runtimeContextMessage(retainRuntimeTurnContext(messages), timestamp);
|
|
10745
|
-
const earlierContext = retainRuntimeTurnContext(messages.slice(0, turnStartMessageIndex));
|
|
10746
|
-
const turnContext = retainRuntimeTurnContext(messages.slice(turnStartMessageIndex));
|
|
10747
|
-
const sessionContext = turnContext.some((message) => userMessageContent(message).map(textPart).some(isSessionTurnContext)) ? void 0 : latestSessionContext(earlierContext);
|
|
10748
|
-
return toRuntimeContextMessage(runtimeContextContent(sessionContext ? [sessionContext, ...turnContext] : turnContext, [...earlierContext, ...turnContext]), timestamp);
|
|
10749
|
-
}
|
|
10750
|
-
/**
|
|
10751
|
-
* Build the runtime context of summarized history that the kept history
|
|
10752
|
-
* does not carry: the latest session context and the AGENTS.md instructions.
|
|
10753
|
-
* Request context of earlier Turns is left out.
|
|
10754
|
-
*/
|
|
10755
|
-
function summarizedRuntimeContextMessage(summarized, kept) {
|
|
10756
|
-
const earlierContext = retainRuntimeTurnContext(summarized);
|
|
10757
|
-
const sessionContext = retainRuntimeTurnContext(kept).some((message) => userMessageContent(message).map(textPart).some(isSessionTurnContext)) ? void 0 : latestSessionContext(earlierContext);
|
|
10758
|
-
return toRuntimeContextMessage(runtimeContextContent(sessionContext ? [sessionContext] : [], findVisibleAgentsInstructions(kept) ? [] : earlierContext));
|
|
10759
|
-
}
|
|
10760
|
-
/**
|
|
10761
|
-
* Build retained user messages for a compacted Pi replacement history. Each
|
|
10762
|
-
* entry keeps the index of its source message.
|
|
10763
|
-
*/
|
|
10764
|
-
function selectRetainedUserMessageEntries(messages, maxTokens = RETAINED_USER_MESSAGE_TOKENS) {
|
|
10765
|
-
const selected = [];
|
|
10766
|
-
let remaining = maxTokens;
|
|
10767
|
-
for (let sourceIndex = messages.length - 1; sourceIndex >= 0; sourceIndex -= 1) {
|
|
10768
|
-
if (isStandaloneRuntimeContextMessage(messages, sourceIndex)) continue;
|
|
10769
|
-
const message = stripRuntimeTurnContext([messages[sourceIndex]])[0];
|
|
10770
|
-
if (!message || message.role !== "user" || remaining <= 0) continue;
|
|
10771
|
-
const text = sanitizeText(messageText(message));
|
|
10772
|
-
if (!text || isCompactionSummary(text) || isPayloadHeavy(text)) continue;
|
|
10773
|
-
const tokens = estimateTextTokens(text);
|
|
10774
|
-
if (tokens <= remaining) {
|
|
10775
|
-
selected.push({
|
|
10776
|
-
message: userMessage(text),
|
|
10777
|
-
sourceIndex
|
|
10778
|
-
});
|
|
10779
|
-
remaining -= tokens;
|
|
10780
|
-
continue;
|
|
10781
|
-
}
|
|
10782
|
-
const truncated = truncateToTokenBudget(text, remaining);
|
|
10783
|
-
if (truncated) selected.push({
|
|
10784
|
-
message: userMessage(truncated),
|
|
10785
|
-
sourceIndex
|
|
10786
|
-
});
|
|
10787
|
-
break;
|
|
10788
|
-
}
|
|
10789
|
-
return selected.reverse();
|
|
10790
|
-
}
|
|
10791
|
-
/** Match a message across a durable commit, which can reorder JSON keys. */
|
|
10792
|
-
function retainedMessageKey(message) {
|
|
10793
|
-
const { role, timestamp } = message;
|
|
10794
|
-
return `${String(role)}:${String(timestamp)}:${messageText(message)}`;
|
|
10795
|
-
}
|
|
10796
|
-
/**
|
|
10797
|
-
* Load recent user messages from committed history. Each one keeps its
|
|
10798
|
-
* original author and source event.
|
|
10799
|
-
*/
|
|
10800
|
-
async function loadRetainedUserMessages(conversationId, pendingMessages) {
|
|
10801
|
-
const projection = await loadConversationProjection({ conversationId });
|
|
10802
|
-
const pendingKeys = new Set(pendingMessages.map(retainedMessageKey));
|
|
10803
|
-
let pendingStart = projection.messages.findIndex((message) => pendingKeys.has(retainedMessageKey(message)));
|
|
10804
|
-
if (pendingStart > 0 && isStandaloneRuntimeContextMessage(projection.messages, pendingStart - 1)) pendingStart -= 1;
|
|
10805
|
-
const history = pendingStart === -1 ? projection.messages : projection.messages.slice(0, pendingStart);
|
|
10806
|
-
return selectRetainedUserMessageEntries(trimTrailingAssistantMessages(history)).map((entry) => {
|
|
10807
|
-
const provenance = projection.provenance[entry.sourceIndex];
|
|
10808
|
-
if (!provenance) throw new Error("retained message provenance is missing");
|
|
10809
|
-
return {
|
|
10810
|
-
message: entry.message,
|
|
10811
|
-
provenance,
|
|
10812
|
-
sourceEventSeq: projection.seqs[entry.sourceIndex]
|
|
10813
|
-
};
|
|
10814
|
-
});
|
|
10815
|
-
}
|
|
10816
|
-
const COMPACTION_READ_BACK_NOTE = "The summary replaced earlier messages and tool results and leaves out most of their details. Before you call a detail unknown or ask for it, search for it with a searchConversationEvents query, then read the full text with readConversationEvent.";
|
|
10817
|
-
/**
|
|
10818
|
-
* Keep generated text inside the existing evidence-only prompt boundary. The
|
|
10819
|
-
* last line says where replaced detail stays readable: without it, the model
|
|
10820
|
-
* often decides a detail from a compacted tool result is gone, and asks the
|
|
10821
|
-
* person for it.
|
|
10822
|
-
*/
|
|
10823
|
-
function renderCompactionSummary(summary) {
|
|
10824
|
-
return [
|
|
10825
|
-
COMPACTION_SUMMARY_PREFIX,
|
|
10826
|
-
renderThreadContext([escapeTagTextAndQuotes(summary)]),
|
|
10827
|
-
COMPACTION_READ_BACK_NOTE
|
|
10828
|
-
].join("\n");
|
|
10829
|
-
}
|
|
10830
|
-
function timestampOf(message) {
|
|
10831
|
-
const { timestamp } = message;
|
|
10832
|
-
return typeof timestamp === "number" ? timestamp : void 0;
|
|
10833
|
-
}
|
|
10834
|
-
/** Find the latest compaction summary in history. */
|
|
10835
|
-
function latestSummaryIndex(messages) {
|
|
10836
|
-
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
10837
|
-
const message = messages[index];
|
|
10838
|
-
if (message.role === "user" && hasCompactedConversationContext([message])) return index;
|
|
10839
|
-
}
|
|
10840
|
-
return -1;
|
|
10841
|
-
}
|
|
10842
|
-
/** Find when the latest compaction summary in history was written. */
|
|
10843
|
-
function latestSummaryTimestamp(messages) {
|
|
10844
|
-
const index = latestSummaryIndex(messages);
|
|
10845
|
-
return index < 0 ? void 0 : timestampOf(messages[index]);
|
|
10846
|
-
}
|
|
10847
|
-
/**
|
|
10848
|
-
* Read the input size that the provider reported for one model call. Output
|
|
10849
|
-
* is left out: it is not part of the request that the call measured.
|
|
10850
|
-
*/
|
|
10851
|
-
function measuredInputTokens(message) {
|
|
10852
|
-
const { role, stopReason, usage } = message;
|
|
10853
|
-
if (role !== "assistant" || !usage || stopReason === "aborted" || stopReason === "error") return;
|
|
10854
|
-
const tokens = (usage.input ?? 0) + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
|
|
10855
|
-
return tokens > 0 ? tokens : void 0;
|
|
10856
|
-
}
|
|
10857
|
-
function lastAssistantUsage(messages) {
|
|
10858
|
-
for (let index = messages.length - 1; index >= 0; index--) {
|
|
10859
|
-
const message = messages[index];
|
|
10860
|
-
if (message.role !== "assistant" || message.stopReason === "aborted" || message.stopReason === "error" || !message.usage) continue;
|
|
10861
|
-
const tokens = calculateContextTokens(message.usage);
|
|
10862
|
-
if (tokens > 0) return {
|
|
10863
|
-
tokens,
|
|
10864
|
-
index
|
|
10865
|
-
};
|
|
10866
|
-
}
|
|
10867
|
-
}
|
|
10868
|
-
/**
|
|
10869
|
-
* Measure provider-visible history without counting host-only message fields.
|
|
10870
|
-
*
|
|
10871
|
-
* Provider usage counts the request that produced it. A replacement keeps
|
|
10872
|
-
* assistant messages that are older than its summary, and their usage counts
|
|
10873
|
-
* the history before the replacement. So when the latest usage is older than
|
|
10874
|
-
* the latest summary, estimate each message by size.
|
|
10875
|
-
*/
|
|
10876
|
-
function estimateHistoryTokens(messages, modelId, requestOverheadTokens = 0) {
|
|
10877
|
-
const usage = lastAssistantUsage(messages);
|
|
10878
|
-
const summaryAt = latestSummaryTimestamp(messages);
|
|
10879
|
-
const usageAt = usage ? timestampOf(messages[usage.index]) : void 0;
|
|
10880
|
-
if (usage && usageAt !== void 0 && (summaryAt === void 0 || usageAt > summaryAt)) return usage.tokens + estimateMessagesTokens(messages.slice(usage.index + 1), modelId);
|
|
10881
|
-
return estimateReplacementTokens(messages, modelId, requestOverheadTokens);
|
|
10882
|
-
}
|
|
10883
|
-
/**
|
|
10884
|
-
* Read the provider-reported input of the first model call after the latest
|
|
10885
|
-
* full compaction. That request held only the summary and the kept context,
|
|
10886
|
-
* so another full compaction of the same context cannot get much below it.
|
|
10887
|
-
* A swap also keeps agent history from before its summary. A full compaction
|
|
10888
|
-
* can still drop that history, so a swap gives no such size.
|
|
10889
|
-
*/
|
|
10890
|
-
function measuredReplacementTokens(messages) {
|
|
10891
|
-
const summaryIndex = latestSummaryIndex(messages);
|
|
10892
|
-
if (summaryIndex < 0) return void 0;
|
|
10893
|
-
const summaryAt = timestampOf(messages[summaryIndex]);
|
|
10894
|
-
if (summaryAt === void 0) return void 0;
|
|
10895
|
-
for (const message of messages.slice(summaryIndex + 1)) {
|
|
10896
|
-
const timestamp = timestampOf(message);
|
|
10897
|
-
if (timestamp === void 0 || timestamp <= summaryAt) {
|
|
10898
|
-
const role = message.role;
|
|
10899
|
-
if (role !== "user" && role !== "system") return void 0;
|
|
10900
|
-
continue;
|
|
10901
|
-
}
|
|
10902
|
-
const tokens = measuredInputTokens(message);
|
|
10903
|
-
if (tokens !== void 0) return tokens;
|
|
10904
|
-
}
|
|
10905
|
-
}
|
|
10906
|
-
/**
|
|
10907
|
-
* Estimate a replacement request from each message's own size. A kept
|
|
10908
|
-
* assistant message holds provider usage for the whole request before the
|
|
10909
|
-
* replacement, so usage is ignored here.
|
|
10910
|
-
*/
|
|
10911
|
-
function estimateReplacementTokens(messages, modelId, requestOverheadTokens = 0) {
|
|
10912
|
-
return requestOverheadTokens + estimateMessagesTokens(messages, modelId);
|
|
10913
|
-
}
|
|
10914
|
-
async function loadLastInstruction(conversationId) {
|
|
10915
|
-
const event = await getConversationEventStore().loadLatestInstruction(conversationId);
|
|
10916
|
-
if (!event) return void 0;
|
|
10917
|
-
if (event.data.type === "user_message") {
|
|
10918
|
-
if (event.data.provenance.authority !== "instruction") return void 0;
|
|
10919
|
-
return {
|
|
10920
|
-
message: piMessageFromHistoryItem(event.data),
|
|
10921
|
-
provenance: event.data.provenance,
|
|
10922
|
-
sourceEventSeq: event.seq
|
|
10923
|
-
};
|
|
10924
|
-
}
|
|
10925
|
-
}
|
|
10926
|
-
function loadCompactionSource(messages, modelId, requestOverheadTokens) {
|
|
10927
|
-
if (messages.length > 0) return {
|
|
10928
|
-
estimatedTokens: estimateHistoryTokens(messages, modelId, requestOverheadTokens),
|
|
10929
|
-
messages
|
|
10930
|
-
};
|
|
10931
|
-
return { reason: "missing_context" };
|
|
10932
|
-
}
|
|
10933
|
-
/**
|
|
10934
|
-
* Replace oversized active history at Pi's next-turn boundary before another
|
|
10935
|
-
* provider request can observe it.
|
|
10936
|
-
*
|
|
10937
|
-
* `summarize` gets the history without pending messages. When it fails, the
|
|
10938
|
-
* history stays as it is, unless the history is at the input limit.
|
|
10939
|
-
*/
|
|
10940
|
-
async function compactActiveContextIfNeeded(args, summarize) {
|
|
10941
|
-
const pendingMessages = args.pendingMessages ?? [];
|
|
10942
|
-
const source = loadCompactionSource([...args.piMessages, ...pendingMessages.map((entry) => entry.message)], args.modelId, args.requestOverheadTokens);
|
|
10943
|
-
if ("reason" in source) return {
|
|
10944
|
-
compacted: false,
|
|
10945
|
-
reason: source.reason
|
|
10946
|
-
};
|
|
10947
|
-
const triggerTokens = getAgentContextCompactionTriggerTokens(args.modelId);
|
|
10948
|
-
if (source.estimatedTokens <= triggerTokens) return {
|
|
10949
|
-
compacted: false,
|
|
10950
|
-
reason: "below_threshold"
|
|
10951
|
-
};
|
|
10952
|
-
return await withCompactionSpan(args.mode, "summary", () => compactActiveAboveThreshold(args, summarize, source, triggerTokens));
|
|
10953
|
-
}
|
|
10954
|
-
async function compactActiveAboveThreshold(args, summarize, source, triggerTokens) {
|
|
10955
|
-
const pendingMessages = args.pendingMessages ?? [];
|
|
10956
|
-
const retainUserMessages = args.mode === "blocking" && pendingMessages.length > 0;
|
|
10957
|
-
const inputLimitTokens = getAgentContextInputLimitTokens(args.modelId);
|
|
10958
|
-
const skip = (reason) => {
|
|
10959
|
-
setSpanAttributes({
|
|
10960
|
-
"app.compaction.outcome": "skipped",
|
|
10961
|
-
"app.compaction.skip_reason": reason,
|
|
10962
|
-
"app.compaction.input.estimate": source.estimatedTokens,
|
|
10963
|
-
"app.compaction.threshold": triggerTokens
|
|
10964
|
-
});
|
|
10965
|
-
return {
|
|
10966
|
-
compacted: false,
|
|
10967
|
-
reason: reason === "over_input_limit" ? reason : "over_target"
|
|
10968
|
-
};
|
|
10969
|
-
};
|
|
10970
|
-
const belowInputLimit = source.estimatedTokens < inputLimitTokens;
|
|
10971
|
-
const measuredTokens = measuredReplacementTokens(source.messages);
|
|
10972
|
-
if (belowInputLimit && measuredTokens !== void 0 && measuredTokens > triggerTokens) return skip("last_over_threshold");
|
|
10973
|
-
const retainedInstruction = pendingMessages.length === 0 && !retainUserMessages ? await loadLastInstruction(args.conversationId) : void 0;
|
|
10974
|
-
const instructionMessages = retainedInstruction ? [retainedInstruction.message] : pendingMessages.map((entry) => entry.message);
|
|
10975
|
-
const instructionProvenance = retainedInstruction ? [retainedInstruction.provenance] : pendingMessages.map((entry) => entry.provenance);
|
|
10976
|
-
const instructionTimestamp = instructionMessages[0]?.timestamp;
|
|
10977
|
-
const contextMessage = turnRuntimeContextMessage(args.runtimeContextMessages ?? args.piMessages, args.turnStartMessageIndex, typeof instructionTimestamp === "number" ? instructionTimestamp : void 0);
|
|
10978
|
-
const contextEntries = contextMessage ? [{
|
|
10979
|
-
message: contextMessage,
|
|
10980
|
-
provenance: contextProvenance
|
|
10981
|
-
}] : [];
|
|
10982
|
-
const instructionEntries = instructionMessages.map((message, index) => ({
|
|
10983
|
-
message,
|
|
10984
|
-
provenance: instructionProvenance[index],
|
|
10985
|
-
...index === 0 && retainedInstruction ? { sourceEventSeq: retainedInstruction.sourceEventSeq } : void 0
|
|
10986
|
-
}));
|
|
10987
|
-
const retainedUserMessages = retainUserMessages ? await loadRetainedUserMessages(args.conversationId, instructionMessages) : [];
|
|
10988
|
-
const systemMessage = foldSystemMessages(args.piMessages);
|
|
10989
|
-
const systemEntries = systemMessage ? [{
|
|
10990
|
-
message: systemMessage,
|
|
10991
|
-
provenance: contextProvenance
|
|
10992
|
-
}] : [];
|
|
10993
|
-
const keptTokens = estimateReplacementTokens([
|
|
10994
|
-
...retainedUserMessages,
|
|
10995
|
-
...contextEntries,
|
|
10996
|
-
...instructionEntries,
|
|
10997
|
-
...systemEntries
|
|
10998
|
-
].map((entry) => entry.message), args.modelId, args.requestOverheadTokens);
|
|
10999
|
-
if (belowInputLimit && keptTokens > calculateContextCompactionTargetTokens(triggerTokens)) return skip("over_target");
|
|
11000
|
-
if (keptTokens >= inputLimitTokens) return skip("over_input_limit");
|
|
11001
|
-
await args.onCompactionStart?.();
|
|
11002
|
-
let summary;
|
|
11003
|
-
let costUsd;
|
|
11004
|
-
try {
|
|
11005
|
-
({summary, costUsd} = await summarize(args.piMessages, args.signal));
|
|
11006
|
-
} catch (error) {
|
|
11007
|
-
if (source.estimatedTokens >= inputLimitTokens) throw new ContextInputLimitExceededError(source.estimatedTokens, inputLimitTokens);
|
|
11008
|
-
logWarn("context_compaction.active.summary.failed", {
|
|
11009
|
-
"app.context_input_limit_tokens": inputLimitTokens,
|
|
11010
|
-
"app.context_tokens_estimated": source.estimatedTokens,
|
|
11011
|
-
"exception.message": error instanceof Error ? error.message : String(error)
|
|
11012
|
-
});
|
|
11013
|
-
setSpanAttributes({ "app.compaction.outcome": "summary_failed" });
|
|
11014
|
-
return {
|
|
11015
|
-
compacted: false,
|
|
11016
|
-
reason: "summary_failed"
|
|
11017
|
-
};
|
|
11018
|
-
}
|
|
11019
|
-
const summaryEntry = {
|
|
11020
|
-
message: userMessage(await appendPlanSnapshot(renderCompactionSummary(summary), args.conversationId)),
|
|
11021
|
-
provenance: contextProvenance
|
|
11022
|
-
};
|
|
11023
|
-
const replacement = retainUserMessages ? [
|
|
11024
|
-
...retainedUserMessages,
|
|
11025
|
-
summaryEntry,
|
|
11026
|
-
...systemEntries,
|
|
11027
|
-
...contextEntries,
|
|
11028
|
-
...instructionEntries
|
|
11029
|
-
] : [
|
|
11030
|
-
...contextEntries,
|
|
11031
|
-
...instructionEntries,
|
|
11032
|
-
summaryEntry,
|
|
11033
|
-
...systemEntries
|
|
11034
|
-
];
|
|
11035
|
-
const retainedMessageCount = retainedUserMessages.length + instructionMessages.length;
|
|
11036
|
-
const messages = replacement.map((entry) => entry.message);
|
|
11037
|
-
const replacementInputTokens = estimateReplacementTokens(messages, args.modelId, args.requestOverheadTokens);
|
|
11038
|
-
if (replacementInputTokens >= inputLimitTokens) throw new ContextInputLimitExceededError(replacementInputTokens, inputLimitTokens);
|
|
11039
|
-
args.signal?.throwIfAborted();
|
|
11040
|
-
await getConversationEventStore().replaceHistory(args.conversationId, {
|
|
11041
|
-
createdAtMs: Date.now(),
|
|
11042
|
-
data: {
|
|
11043
|
-
type: "compaction",
|
|
11044
|
-
modelId: args.modelId,
|
|
11045
|
-
details: {
|
|
11046
|
-
reason: "capacity",
|
|
11047
|
-
estimatedInputTokens: source.estimatedTokens,
|
|
11048
|
-
replacementInputTokens,
|
|
11049
|
-
triggerTokens,
|
|
11050
|
-
inputLimitTokens,
|
|
11051
|
-
inputMessageCount: source.messages.length,
|
|
11052
|
-
retainedMessageCount,
|
|
11053
|
-
summaryChars: summary.length
|
|
11054
|
-
},
|
|
11055
|
-
...costUsd === void 0 ? void 0 : { costUsd },
|
|
11056
|
-
summary,
|
|
11057
|
-
replacementHistory: replacement.map((entry) => ({
|
|
11058
|
-
item: historyItemFromPiMessage(entry.message, entry.provenance),
|
|
11059
|
-
...entry.sourceEventSeq === void 0 ? void 0 : { sourceEventSeq: entry.sourceEventSeq }
|
|
11060
|
-
}))
|
|
11061
|
-
}
|
|
11062
|
-
});
|
|
11063
|
-
setSpanAttributes({
|
|
11064
|
-
"app.compaction.outcome": "compacted",
|
|
11065
|
-
"app.compaction.input_messages": source.messages.length,
|
|
11066
|
-
"app.compaction.retained_messages": retainedMessageCount,
|
|
11067
|
-
"app.compaction.summary_chars": summary.length,
|
|
11068
|
-
"app.compaction.input.estimate": source.estimatedTokens,
|
|
11069
|
-
"app.compaction.replacement.estimate": replacementInputTokens,
|
|
11070
|
-
"app.compaction.input_limit": inputLimitTokens,
|
|
11071
|
-
"app.compaction.threshold": triggerTokens
|
|
11072
|
-
});
|
|
11073
|
-
return {
|
|
11074
|
-
compacted: true,
|
|
11075
|
-
piMessages: messages
|
|
11076
|
-
};
|
|
11077
|
-
}
|
|
11078
|
-
// src/chat/services/tool-result-trimming.ts
|
|
11079
|
-
/** Results up to this many text characters stay whole. */
|
|
11080
|
-
const MAX_KEPT_RESULT_CHARS = 2e3;
|
|
11081
|
-
/** Error results explain failures, so they stay whole up to this size. */
|
|
11082
|
-
const MAX_KEPT_ERROR_CHARS = 8e3;
|
|
11083
|
-
const EDGE_CHARS = 500;
|
|
11084
|
-
function role(message) {
|
|
11085
|
-
return message.role;
|
|
11086
|
-
}
|
|
11087
|
-
function resultParts(message) {
|
|
11088
|
-
const content = message.content;
|
|
11089
|
-
return Array.isArray(content) ? content : [];
|
|
11090
|
-
}
|
|
11091
|
-
function resultText(parts) {
|
|
11092
|
-
return parts.map((part) => part.type === "text" && typeof part.text === "string" ? part.text : "").join("\n");
|
|
11093
|
-
}
|
|
11094
|
-
function pointer(seq) {
|
|
11095
|
-
return `readConversationEvent({ seq: ${seq} })`;
|
|
11096
|
-
}
|
|
11097
|
-
/** Replace a long result text with a header, its edges, and a read-back pointer. */
|
|
11098
|
-
function clearedText(toolName, text, seq) {
|
|
11099
|
-
return [
|
|
11100
|
-
`[Tool result cleared to save context: ${toolName}, ${text.length.toLocaleString("en-US")} chars. Full result: ${pointer(seq)}`,
|
|
11101
|
-
"First 500 chars:",
|
|
11102
|
-
text.slice(0, EDGE_CHARS),
|
|
11103
|
-
"Last 500 chars:",
|
|
11104
|
-
`${text.slice(-500)}]`
|
|
11105
|
-
].join("\n");
|
|
11106
|
-
}
|
|
11107
|
-
function trimResult(message, seq) {
|
|
11108
|
-
const parts = resultParts(message);
|
|
11109
|
-
const text = resultText(parts);
|
|
11110
|
-
const hasImage = parts.some((part) => part.type === "image");
|
|
11111
|
-
const keptChars = message.isError === true ? MAX_KEPT_ERROR_CHARS : MAX_KEPT_RESULT_CHARS;
|
|
11112
|
-
const clearText = text.length > keptChars;
|
|
11113
|
-
if (!clearText && !hasImage) return;
|
|
11114
|
-
const toolName = String(message.toolName ?? "tool");
|
|
11115
|
-
const content = clearText ? [{
|
|
11116
|
-
type: "text",
|
|
11117
|
-
text: clearedText(toolName, text, seq)
|
|
11118
|
-
}] : parts.map((part) => part.type === "image" ? {
|
|
11119
|
-
type: "text",
|
|
11120
|
-
text: `[image cleared: ${toolName}, seq ${seq}]`
|
|
11121
|
-
} : part);
|
|
11122
|
-
if (clearText && hasImage) content.push({
|
|
11123
|
-
type: "text",
|
|
11124
|
-
text: `[image cleared: ${toolName}, seq ${seq}]`
|
|
11125
|
-
});
|
|
11126
|
-
return {
|
|
11127
|
-
message: {
|
|
11128
|
-
...message,
|
|
11129
|
-
content
|
|
11130
|
-
},
|
|
11131
|
-
removedChars: Math.max(0, text.length - resultText(content).length)
|
|
11132
|
-
};
|
|
11133
|
-
}
|
|
11134
|
-
/**
|
|
11135
|
-
* Trim old tool results in a replacement history.
|
|
11136
|
-
*
|
|
11137
|
-
* Results after the last Turn instruction belong to the latest Turn and stay
|
|
11138
|
-
* whole. Runtime context and summaries are user messages too, so they do not
|
|
11139
|
-
* mark a Turn. So do short results, error results up to a cap, and
|
|
11140
|
-
* results that have no source event to point to. Images outside the latest
|
|
11141
|
-
* Turn become a short note.
|
|
11142
|
-
*/
|
|
11143
|
-
function trimToolResults(entries) {
|
|
11144
|
-
let latestInstructionIndex = -1;
|
|
11145
|
-
for (const [index, entry] of entries.entries()) if (hasTurnInput(entry.message)) latestInstructionIndex = index;
|
|
11146
|
-
const trimming = {
|
|
11147
|
-
trimmedResults: 0,
|
|
11148
|
-
removedChars: 0
|
|
11149
|
-
};
|
|
11150
|
-
return {
|
|
11151
|
-
entries: entries.map((entry, index) => {
|
|
11152
|
-
if (index > latestInstructionIndex || role(entry.message) !== "toolResult" || entry.sourceEventSeq === void 0) return entry;
|
|
11153
|
-
const result = trimResult(entry.message, entry.sourceEventSeq);
|
|
11154
|
-
if (!result) return entry;
|
|
11155
|
-
trimming.trimmedResults += 1;
|
|
11156
|
-
trimming.removedChars += result.removedChars;
|
|
11157
|
-
return {
|
|
11158
|
-
...entry,
|
|
11159
|
-
message: result.message
|
|
11160
|
-
};
|
|
11161
|
-
}),
|
|
11162
|
-
trimming
|
|
11163
|
-
};
|
|
11164
|
-
}
|
|
11165
|
-
// src/chat/services/context-compaction-swap.ts
|
|
11166
|
-
/**
|
|
11167
|
-
* Prepared-summary swap.
|
|
11168
|
-
*
|
|
11169
|
-
* A background job writes `compaction_prepared` with a summary of the history
|
|
11170
|
-
* up to `markSeq`. The Turn swaps it in without a model call: retained user
|
|
11171
|
-
* messages, the summary, then every message after the mark. A swap runs only
|
|
11172
|
-
* above the compaction threshold, at Turn start or between model calls, in
|
|
11173
|
-
* place of a blocking summary call. Below it, a swap would only rewrite the
|
|
11174
|
-
* provider's prompt cache. A summary that no longer matches the history is
|
|
11175
|
-
* discarded, and the Turn carries on as if none existed.
|
|
11176
|
-
*
|
|
11177
|
-
* A summary that is still running replaces the blocking summary too, for a
|
|
11178
|
-
* limited time from its request. Below the input limit, the Turn defers: the
|
|
11179
|
-
* next model call gets the full history, and a later check swaps the summary
|
|
11180
|
-
* in. At the input limit, the Turn polls for it. The time counts from the
|
|
11181
|
-
* durable request, so a yield or a new request does not reset it.
|
|
11182
|
-
*/
|
|
11183
|
-
/** How long after its request a running summary replaces a blocking one. */
|
|
11184
|
-
const RUNNING_SUMMARY_WAIT_MS = 45e3;
|
|
11185
|
-
const RUNNING_SUMMARY_POLL_MS = 1e3;
|
|
11186
|
-
/** Compare a message across a durable commit, which drops undefined fields. */
|
|
11187
|
-
function durableIdentity(message) {
|
|
11188
|
-
const { role, timestamp, content, toolCallId } = message;
|
|
11189
|
-
return JSON.parse(JSON.stringify({
|
|
11190
|
-
role,
|
|
11191
|
-
timestamp,
|
|
11192
|
-
content,
|
|
11193
|
-
toolCallId
|
|
11194
|
-
}));
|
|
11195
|
-
}
|
|
11196
|
-
function committedPrefixLength(messages, committed) {
|
|
11197
|
-
const limit = Math.min(messages.length, committed.length);
|
|
11198
|
-
for (let index = 0; index < limit; index += 1) if (!isDeepStrictEqual(durableIdentity(messages[index]), durableIdentity(committed[index]))) return index;
|
|
11199
|
-
return limit;
|
|
11200
|
-
}
|
|
11201
|
-
function discard(reason) {
|
|
11202
|
-
setSpanAttributes({
|
|
11203
|
-
"app.compaction.outcome": "discarded",
|
|
11204
|
-
"app.compaction.discard_reason": reason
|
|
11205
|
-
});
|
|
11206
|
-
return { compacted: false };
|
|
11207
|
-
}
|
|
11208
|
-
/**
|
|
11209
|
-
* Swap a ready prepared summary into history, defer to one that is still
|
|
11210
|
-
* running, or run today's capacity compaction when none can be used.
|
|
11211
|
-
*/
|
|
11212
|
-
async function compactWithPreparedSummary(args, summarize) {
|
|
11213
|
-
const swapped = await swapPreparedCompaction(args);
|
|
11214
|
-
if (swapped.compacted || swapped.reason === "history_conflict" || swapped.reason === "deferred") return swapped;
|
|
11215
|
-
return await compactActiveContextIfNeeded(args, summarize);
|
|
11216
|
-
}
|
|
11217
|
-
/**
|
|
11218
|
-
* Poll until the running summary of `request` has a result, the History
|
|
11219
|
-
* changes, or the wait ends. Return the newest fact at that time.
|
|
11220
|
-
*/
|
|
11221
|
-
async function waitForRunningSummary(conversationId, request, waitUntilMs, signal) {
|
|
11222
|
-
let latest = request;
|
|
11223
|
-
while (latest?.event.seq === request.event.seq && Date.now() < waitUntilMs) {
|
|
11224
|
-
await setTimeout$1(Math.min(RUNNING_SUMMARY_POLL_MS, waitUntilMs - Date.now()), void 0, { signal });
|
|
11225
|
-
latest = await loadLatestBackgroundCompaction(conversationId);
|
|
11226
|
-
}
|
|
11227
|
-
return latest;
|
|
11228
|
-
}
|
|
11229
|
-
/**
|
|
11230
|
-
* Replace history above the compaction threshold with a ready prepared
|
|
11231
|
-
* summary, or defer to one that is still running.
|
|
11232
|
-
*/
|
|
11233
|
-
async function swapPreparedCompaction(args) {
|
|
11234
|
-
const pendingMessages = args.pendingMessages ?? [];
|
|
11235
|
-
const sourceMessages = [...args.piMessages, ...pendingMessages.map((entry) => entry.message)];
|
|
11236
|
-
const triggerTokens = getAgentContextCompactionTriggerTokens(args.modelId);
|
|
11237
|
-
const estimatedTokens = estimateHistoryTokens(sourceMessages, args.modelId, args.requestOverheadTokens);
|
|
11238
|
-
if (estimatedTokens <= triggerTokens) return {
|
|
11239
|
-
compacted: false,
|
|
11240
|
-
reason: "below_threshold"
|
|
11241
|
-
};
|
|
11242
|
-
const first = await loadLatestBackgroundCompaction(args.conversationId);
|
|
11243
|
-
if (!first) return { compacted: false };
|
|
11244
|
-
return await withCompactionSpan(args.mode, "swap", async () => {
|
|
11245
|
-
let latest = first;
|
|
11246
|
-
if (first.event.data.type === "compaction_requested") {
|
|
11247
|
-
const waitUntilMs = first.event.createdAtMs + RUNNING_SUMMARY_WAIT_MS;
|
|
11248
|
-
setSpanAttributes({ "app.compaction.request.age_ms": Math.max(0, Date.now() - first.event.createdAtMs) });
|
|
11249
|
-
if (Date.now() < waitUntilMs) {
|
|
11250
|
-
if (estimatedTokens < getAgentContextInputLimitTokens(args.modelId)) {
|
|
11251
|
-
setSpanAttributes({ "app.compaction.outcome": "deferred" });
|
|
11252
|
-
return {
|
|
11253
|
-
compacted: false,
|
|
11254
|
-
reason: "deferred"
|
|
11255
|
-
};
|
|
11256
|
-
}
|
|
11257
|
-
await args.onCompactionStart?.();
|
|
11258
|
-
latest = await waitForRunningSummary(args.conversationId, first, waitUntilMs, args.signal);
|
|
11259
|
-
setSpanAttributes({ "app.compaction.wait.timed_out": latest?.event.seq === first.event.seq });
|
|
11260
|
-
if (latest?.historyVersion !== first.historyVersion) return {
|
|
11261
|
-
...discard("history_version_changed"),
|
|
11262
|
-
reason: "history_conflict"
|
|
11263
|
-
};
|
|
11264
|
-
}
|
|
11265
|
-
}
|
|
11266
|
-
const prepared = latest?.event.data;
|
|
11267
|
-
if (!latest || prepared?.type !== "compaction_prepared" || prepared.outcome !== "ready") {
|
|
11268
|
-
setSpanAttributes({ "app.compaction.outcome": "not_ready" });
|
|
11269
|
-
return { compacted: false };
|
|
11270
|
-
}
|
|
11271
|
-
const { event, historyVersion } = latest;
|
|
11272
|
-
setSpanAttributes({ "app.compaction.prepared.age_ms": Math.max(0, Date.now() - event.createdAtMs) });
|
|
11273
|
-
if (prepared.historyVersion !== historyVersion) return discard("history_version_changed");
|
|
11274
|
-
return await applyPreparedSummary(args, prepared, {
|
|
11275
|
-
estimatedTokens,
|
|
11276
|
-
historyVersion,
|
|
11277
|
-
triggerTokens
|
|
11278
|
-
});
|
|
11279
|
-
});
|
|
11280
|
-
}
|
|
11281
|
-
async function applyPreparedSummary(args, prepared, budget) {
|
|
11282
|
-
const pendingMessages = args.pendingMessages ?? [];
|
|
11283
|
-
const projection = await loadConversationProjection({ conversationId: args.conversationId });
|
|
11284
|
-
const committedLength = committedPrefixLength(args.piMessages, projection.messages);
|
|
11285
|
-
const firstAfterMark = projection.seqs.slice(0, committedLength).findIndex((seq) => seq > prepared.markSeq);
|
|
11286
|
-
const markIndex = firstAfterMark === -1 ? committedLength : firstAfterMark;
|
|
11287
|
-
const summarized = args.piMessages.slice(0, markIndex);
|
|
11288
|
-
const kept = args.piMessages.slice(markIndex);
|
|
11289
|
-
if (kept[0]?.role === "toolResult") return discard("split_tool_call");
|
|
11290
|
-
const retained = selectRetainedUserMessageEntries(trimTrailingAssistantMessages(summarized)).map((entry) => ({
|
|
11291
|
-
message: entry.message,
|
|
11292
|
-
provenance: projection.provenance[entry.sourceIndex],
|
|
11293
|
-
sourceEventSeq: projection.seqs[entry.sourceIndex]
|
|
11294
|
-
}));
|
|
11295
|
-
const contextMessage = summarizedRuntimeContextMessage(summarized, [...kept, ...pendingMessages.map((entry) => entry.message)]);
|
|
11296
|
-
const { entries: trimmedEntries, trimming } = trimToolResults(kept.map((message, offset) => {
|
|
11297
|
-
const index = markIndex + offset;
|
|
11298
|
-
return index < committedLength ? {
|
|
11299
|
-
message,
|
|
11300
|
-
provenance: projection.provenance[index],
|
|
11301
|
-
sourceEventSeq: projection.seqs[index]
|
|
11302
|
-
} : {
|
|
11303
|
-
message,
|
|
11304
|
-
provenance: contextProvenance
|
|
11305
|
-
};
|
|
11306
|
-
}));
|
|
11307
|
-
const systemMessage = foldSystemMessages(summarized);
|
|
11308
|
-
const replacement = [
|
|
11309
|
-
...contextMessage ? [{
|
|
11310
|
-
message: contextMessage,
|
|
11311
|
-
provenance: contextProvenance
|
|
11312
|
-
}] : [],
|
|
11313
|
-
...retained,
|
|
11314
|
-
{
|
|
11315
|
-
message: userMessage(await appendPlanSnapshot(renderCompactionSummary(prepared.summary), args.conversationId)),
|
|
11316
|
-
provenance: contextProvenance
|
|
11317
|
-
},
|
|
11318
|
-
...systemMessage ? [{
|
|
11319
|
-
message: systemMessage,
|
|
11320
|
-
provenance: contextProvenance
|
|
11321
|
-
}] : [],
|
|
11322
|
-
...trimmedEntries,
|
|
11323
|
-
...pendingMessages
|
|
11324
|
-
];
|
|
11325
|
-
const messages = replacement.map((entry) => entry.message);
|
|
11326
|
-
const replacementTokens = estimateReplacementTokens(messages, args.modelId, args.requestOverheadTokens);
|
|
11327
|
-
const targetTokens = calculateContextCompactionTargetTokens(budget.triggerTokens);
|
|
11328
|
-
setSpanAttributes({
|
|
11329
|
-
"app.compaction.input.estimate": budget.estimatedTokens,
|
|
11330
|
-
"app.compaction.replacement.estimate": replacementTokens,
|
|
11331
|
-
"app.compaction.threshold": budget.triggerTokens,
|
|
11332
|
-
"app.compaction.carried_messages": kept.length,
|
|
11333
|
-
"app.compaction.carried.estimate": estimateReplacementTokens(trimmedEntries.map((entry) => entry.message), args.modelId),
|
|
11334
|
-
"app.compaction.trimmed_results": trimming.trimmedResults,
|
|
11335
|
-
"app.compaction.trimmed_chars": trimming.removedChars
|
|
11336
|
-
});
|
|
11337
|
-
if (replacementTokens > targetTokens) return discard("over_target");
|
|
11338
|
-
args.signal?.throwIfAborted();
|
|
11339
|
-
if ((await getConversationEventStore().replaceHistory(args.conversationId, {
|
|
11340
|
-
createdAtMs: Date.now(),
|
|
11341
|
-
data: {
|
|
11342
|
-
type: "compaction",
|
|
11343
|
-
modelId: args.modelId,
|
|
11344
|
-
details: {
|
|
11345
|
-
reason: "capacity",
|
|
11346
|
-
estimatedInputTokens: budget.estimatedTokens,
|
|
11347
|
-
replacementInputTokens: replacementTokens,
|
|
11348
|
-
triggerTokens: budget.triggerTokens,
|
|
11349
|
-
inputLimitTokens: getAgentContextInputLimitTokens(args.modelId),
|
|
11350
|
-
inputMessageCount: args.piMessages.length + pendingMessages.length,
|
|
11351
|
-
retainedMessageCount: retained.length + kept.length + pendingMessages.length,
|
|
11352
|
-
summaryChars: prepared.summary.length
|
|
11353
|
-
},
|
|
11354
|
-
summary: prepared.summary,
|
|
11355
|
-
replacementHistory: replacement.map((entry) => ({
|
|
11356
|
-
item: historyItemFromPiMessage(entry.message, entry.provenance),
|
|
11357
|
-
...entry.sourceEventSeq === void 0 ? void 0 : { sourceEventSeq: entry.sourceEventSeq }
|
|
11358
|
-
}))
|
|
11359
|
-
}
|
|
11360
|
-
}, { expectedHistoryVersion: budget.historyVersion })).status === "conflict") return {
|
|
11361
|
-
...discard("conflict"),
|
|
11362
|
-
reason: "history_conflict"
|
|
11363
|
-
};
|
|
11364
|
-
setSpanAttributes({
|
|
11365
|
-
"app.compaction.outcome": "applied",
|
|
11366
|
-
"app.compaction.summary_chars": prepared.summary.length
|
|
11367
|
-
});
|
|
11368
|
-
return {
|
|
11369
|
-
compacted: true,
|
|
11370
|
-
piMessages: messages
|
|
11371
|
-
};
|
|
11372
|
-
}
|
|
11373
10214
|
// src/chat/agent/exclusive-tools.ts
|
|
11374
10215
|
/**
|
|
11375
10216
|
* Tools that must be the only tool call in their assistant message. Each one
|
|
@@ -11725,8 +10566,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
11725
10566
|
const promptTurnContextPromise = loadPromptTurnContext({
|
|
11726
10567
|
context: createPromptHookContext({
|
|
11727
10568
|
actor,
|
|
11728
|
-
run
|
|
11729
|
-
userInput
|
|
10569
|
+
run
|
|
11730
10570
|
}),
|
|
11731
10571
|
currentActor: actor,
|
|
11732
10572
|
existingSessionPiMessages: existingSessionRecord?.piMessages,
|
|
@@ -12434,7 +11274,7 @@ function createAgentRunner(execute, options) {
|
|
|
12434
11274
|
}
|
|
12435
11275
|
};
|
|
12436
11276
|
const loadStoredAttachments = async (attachments) => {
|
|
12437
|
-
const { loadInputAttachments } = await import("./model-input-
|
|
11277
|
+
const { loadInputAttachments } = await import("./model-input-CMLh4Cwq.js").then((n) => n.i);
|
|
12438
11278
|
const storage = nextRun.environment?.attachmentStorage;
|
|
12439
11279
|
if (!storage) throw new Error("Attachment storage is unavailable.");
|
|
12440
11280
|
return await loadInputAttachments({
|
|
@@ -12458,4 +11298,4 @@ function createAgentRunner(execute, options) {
|
|
|
12458
11298
|
return await execute(nextRun, streamFn);
|
|
12459
11299
|
} };
|
|
12460
11300
|
}
|
|
12461
|
-
export {
|
|
11301
|
+
export { readAttachmentContent as A, safeLinkUrl as C, pauseConversationDelivery as D, isConversationDeliveryPaused as E, finalizeFailedTurnReplyWithEvent as F, getAgentTurnDiagnosticsAttributes as I, requireTurnFailureEventId as L, RetryableDeliveryError as M, actorFromRun as N, resumeConversationDelivery as O, toolInvocationDestination as P, shouldEmitDevAgentTrace as R, parseSlackReviewItemFormTarget as S, canPauseConversationDelivery as T, syncReviewItemSlackCards as _, getMcpOAuthCallbackPath as a, buildSlackReviewItemModal as b, latestProgressStatus as c, unpublishedArtifactHeaders as d, resolveDestinationVisibility as f, resolveSlackReviewItemCardConversationId as g, createSlackReviewItemShow as h, finalizeMcpAuthorization as i, previewOriginBelongsTo as j, AttachmentDownloadError as k, publicArtifactHeaders as l, scheduledAutomationRunAttributes as m, executeAgentRun as n, createClientMetadata as o, logScheduledAutomationRunSkipped as p, buildAuthPauseResponse as r, readMcpClientInformation as s, createAgentRunner as t, readPublicArtifact as u, findSlackThreadOwnerId as v, parseSlackUserInputSubmission as w, parseSlackReviewItemClick as x, SLACK_REVIEW_ITEM_VIEW_ID as y };
|