@sentry/junior 0.309.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-1YUbMpD3.js → adapter-context-G2M0y6rP.js} +2 -2
- package/dist/{admin-u30A8TcD.js → admin-DCiBhUT1.js} +1 -2
- package/dist/{agent-runner-sJLhgPQV.js → agent-runner-BVHPUIc8.js} +695 -1817
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +8 -7
- 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 +233 -506
- package/dist/{background-compaction-queue-CUJXVKG3.js → background-compaction-queue-CJDnWVOJ.js} +4 -4
- package/dist/{briefs-BHi70IR5.js → briefs-BDjnug6Y.js} +3 -3
- package/dist/{catalog-runtime-Chc_IP2o.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-BIyIdTtA.js → config-BrXDQefC.js} +239 -5
- package/dist/{continue-in-slack-BQJBfiQh.js → continue-in-slack-DNXSC9So.js} +6 -5
- package/dist/{conversation-CzrLhdHG.js → conversation-ca__NDQW.js} +48 -9
- package/dist/{conversation-feed-B9e3_gxz.js → conversation-feed-DkinDu5o.js} +15 -6
- package/dist/{conversation-privacy-CkTW29hd.js → conversation-privacy-DxttrKb9.js} +1 -1
- package/dist/{conversation-turn-CZaYQUum.js → conversation-turn-DWw7Xhdr.js} +42 -39
- package/dist/{credential-sync-58m_CyIJ.js → credential-sync-Bk8wGb8Y.js} +15 -16
- package/dist/{db-B4Hjxr-u.d.ts → db-7ETESH44.d.ts} +3 -1
- package/dist/{db-CFUpEZi9.js → db-DTxzH7u5.js} +1618 -1041
- package/dist/{executor-DXL0O0MV.js → executor-DqTiYj9S.js} +454 -96
- package/dist/{history-N7IVbUom.js → history-CYstOMKX.js} +6 -0
- package/dist/{html-CaBu2VbT.js → html-B9Sl4Axb.js} +6 -6
- package/dist/{install-DhTBUUov.js → install-Sg4ePfLl.js} +2 -2
- package/dist/instrumentation.js +3 -3
- package/dist/{lineage-CxtOI2_p.js → lineage-BHAMpNKr.js} +2 -2
- package/dist/{logging-BNUovdcX.js → logging-FjclQsXu.js} +47 -9
- package/dist/{message-DcUsS2vg.js → message-CJ7_RL50.js} +5 -8
- package/dist/{model-input-o3rEqgwM.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-1Fizd1EM.js → oauth-callback-server-RVcbiDjL.js} +2 -2
- package/dist/{oauth-relay-DOwngqdM.js → oauth-relay-Bu9kkaQu.js} +1 -1
- package/dist/{projection-Ce4pmhKP.js → projection-Cns7XwWa.js} +9206 -5318
- package/dist/{prompt-DEqjDVMs.js → prompt-CDqcsDYC.js} +4 -4
- package/dist/{registry-CNE4ZBnG.js → registry-BPwuOP2O.js} +5 -8
- package/dist/{resolve-qbPg-aC-.js → resolve-BK29bBry.js} +3 -3
- package/dist/rule-DAxQY-1h.js +20 -0
- package/dist/{runner-eGIxpAMf.js → runner-BcAE-cJm.js} +10 -10
- package/dist/{sandbox-egress-signals-DMFB1kCp.js → sandbox-egress-signals-C-q0go5b.js} +1 -1
- package/dist/{schedule-Cire6NU7.js → schedule-BLJ476XQ.js} +209 -43
- package/dist/{schema-CfIey9Ao.js → schema-BLgSZXcL.js} +255 -49
- package/dist/{schema-DriSvB40.d.ts → schema-DYcJeV7d.d.ts} +701 -62
- package/dist/{service-account-Cw_LWZ4-.js → service-account-gN0zqf0S.js} +68 -68
- package/dist/{service-account-B1VXCTqg.js → service-account-iJoCtkHR.js} +3 -3
- package/dist/{skills-Zg8-vrje.js → skills-BoZ80epJ.js} +77 -31
- package/dist/{slack-conversation-unfurl-DA51qH0c.js → slack-conversation-unfurl-CogYrITA.js} +8 -10
- package/dist/{spawn-DBi4-zD8.js → spawn-Dk92r7mX.js} +5 -6
- package/dist/{state-C-Ftk23K.js → state-DH3Cmgp3.js} +4 -4
- package/dist/{stop-D9xideLM.js → stop-CYsfc0Ed.js} +1064 -314
- package/dist/{store-BjIXA0Al.js → store-DmmMIrQi.js} +5 -5
- package/dist/{task-queue-D0_qbnpo.js → task-queue-C_zldF5J.js} +3 -3
- package/dist/{task-runner-DQMq4XY0.js → task-runner-C7oCJQIx.js} +21 -14
- package/dist/{thread-context-D0i1e-5O.js → thread-context-BW2BsQbH.js} +13 -11
- package/dist/{turn-session-routing-C0l68I_O.js → turn-session-routing-Xh_2nSQe.js} +52 -54
- package/dist/{validation-CRbvRPvu.js → validation-DrJd0nnq.js} +1 -1
- package/dist/{version-BYdVs12p.js → version-CNKZ8owc.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{warmup-DN9OHN1-.js → warmup-BWdHew2H.js} +14289 -7197
- package/dist/{web-message-id-BT8Mg8LL.js → web-message-id-Ch5dPq-a.js} +32 -144
- package/dist/{worker-C9ZfJXmV.js → worker-t9qpu_Zx.js} +7 -8
- package/migrations/0124_artifact_visibility.sql +9 -0
- package/migrations/0125_artifact_public_sha_index.sql +1 -0
- 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/0124_snapshot.json +5516 -0
- package/migrations/meta/0125_snapshot.json +5516 -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 +134 -1
- package/package.json +6 -7
- package/dist/result-ZGnDzcsb.js +0 -548
- package/dist/session-stop-P2XdTiwr.js +0 -4252
- package/dist/turn-user-message-nBVvOXjs.js +0 -364
- package/dist/users-DdjMjbmM.js +0 -181
- package/dist/viewer-DudYrQGj.js +0 -212
|
@@ -1,56 +1,46 @@
|
|
|
1
|
-
import { $
|
|
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
|
|
10
|
-
import { d as contextProvenance, f as instructionActors, m as sameActorIdentity, p as instructionProvenanceFor } from "./history-
|
|
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
|
+
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 {
|
|
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-C0l68I_O.js";
|
|
27
|
-
import { o as getSandboxResources, r as setSnapshotSpanAttributes } from "./install-DhTBUUov.js";
|
|
28
|
-
import { n as resolve$1 } from "./resolve-qbPg-aC-.js";
|
|
29
|
-
import { t as runWithSlackInstallation } from "./adapter-context-1YUbMpD3.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")) : {};
|
|
@@ -1444,31 +1237,26 @@ function actionConfirmationRetryMessages(messages) {
|
|
|
1444
1237
|
return retryMessages;
|
|
1445
1238
|
}
|
|
1446
1239
|
// src/chat/agent/skills.ts
|
|
1447
|
-
/** Run-scoped skill discovery and explicit invocation. */
|
|
1448
1240
|
let startupDiscoveryLogged = false;
|
|
1449
|
-
/** Upsert a skill into the active skills list by name. */
|
|
1450
|
-
function upsertActiveSkill(activeSkills, next) {
|
|
1451
|
-
const existing = activeSkills.find((skill) => skill.name === next.name);
|
|
1452
|
-
if (existing) {
|
|
1453
|
-
existing.body = next.body;
|
|
1454
|
-
existing.description = next.description;
|
|
1455
|
-
existing.skillPath = next.skillPath;
|
|
1456
|
-
existing.allowedTools = next.allowedTools;
|
|
1457
|
-
existing.pluginProvider = next.pluginProvider;
|
|
1458
|
-
return;
|
|
1459
|
-
}
|
|
1460
|
-
activeSkills.push(next);
|
|
1461
|
-
}
|
|
1462
1241
|
/**
|
|
1463
1242
|
* Return the skills that the model can load with `loadSkill`. A manual-only
|
|
1464
|
-
* skill is loadable only
|
|
1465
|
-
*
|
|
1466
|
-
* SKILL.md instructions.
|
|
1467
|
-
*
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1243
|
+
* skill is loadable only when the Turn's message invokes it, when `loadSkill`
|
|
1244
|
+
* loaded it earlier in the Conversation, or when a loadable skill references
|
|
1245
|
+
* it as `$name` in its SKILL.md instructions. The model can load any loadable
|
|
1246
|
+
* skill at any time, so the list is fixed for the Turn. No other text, such
|
|
1247
|
+
* as memory, thread messages, or tool results, unlocks one.
|
|
1248
|
+
*/
|
|
1249
|
+
function loadableSkills(availableSkills, invokedSkillNames) {
|
|
1250
|
+
const byName = new Map(availableSkills.map((skill) => [skill.name, skill]));
|
|
1251
|
+
const unlocked = /* @__PURE__ */ new Set();
|
|
1252
|
+
const pending = [...invokedSkillNames, ...availableSkills.filter((skill) => skill.disableModelInvocation !== true).map((skill) => skill.name)];
|
|
1253
|
+
for (let name = pending.pop(); name !== void 0; name = pending.pop()) {
|
|
1254
|
+
const skill = byName.get(name);
|
|
1255
|
+
if (!skill || unlocked.has(name)) continue;
|
|
1256
|
+
unlocked.add(name);
|
|
1257
|
+
pending.push(...skill.references ?? []);
|
|
1258
|
+
}
|
|
1259
|
+
return availableSkills.filter((skill) => unlocked.has(skill.name));
|
|
1472
1260
|
}
|
|
1473
1261
|
/** Discover skills for one slice; emits the startup discovery summary once per process. */
|
|
1474
1262
|
async function discoverRunSkills(args) {
|
|
@@ -1487,6 +1275,21 @@ async function discoverRunSkills(args) {
|
|
|
1487
1275
|
}
|
|
1488
1276
|
return availableSkills;
|
|
1489
1277
|
}
|
|
1278
|
+
/**
|
|
1279
|
+
* Return the text whose skill references unlock skills in this Run: the
|
|
1280
|
+
* person's own input, or the instructions of an Automation run. Text that no
|
|
1281
|
+
* person wrote for this Run, such as Event text, an agent result, a parent
|
|
1282
|
+
* agent task, or a plugin dispatch, unlocks nothing.
|
|
1283
|
+
*/
|
|
1284
|
+
function skillInvocationText(run, actor) {
|
|
1285
|
+
if (run.dispatch) return dispatchInstructionsInvokeSkills(run.dispatch) ? readTaskInstructions(run.instruction.text) ?? "" : "";
|
|
1286
|
+
const provenance = run.instruction.provenance ?? instructionProvenanceFor(actor);
|
|
1287
|
+
if (provenance.authority !== "instruction" || !provenance.actor || provenance.actor.platform === "system") return "";
|
|
1288
|
+
return (run.instruction.inputs ?? [{
|
|
1289
|
+
kind: "person",
|
|
1290
|
+
text: run.instruction.text
|
|
1291
|
+
}]).filter((input) => input.kind === "person").map((input) => input.text).join("\n\n");
|
|
1292
|
+
}
|
|
1490
1293
|
function lastLoadedSkillName(messages) {
|
|
1491
1294
|
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
1492
1295
|
const message = messages[index];
|
|
@@ -1496,13 +1299,415 @@ function lastLoadedSkillName(messages) {
|
|
|
1496
1299
|
if (typeof skillName === "string" && skillName.trim()) return skillName;
|
|
1497
1300
|
}
|
|
1498
1301
|
}
|
|
1499
|
-
/**
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
return
|
|
1302
|
+
/**
|
|
1303
|
+
* Make the last skill that `loadSkill` loaded earlier in this Turn active
|
|
1304
|
+
* again in a resumed slice, so its tool limits and files still apply. Skills
|
|
1305
|
+
* from earlier Turns are never restored.
|
|
1306
|
+
*/
|
|
1307
|
+
async function restoreActiveSkill(args) {
|
|
1308
|
+
if (!args.resumed) return;
|
|
1309
|
+
const skillName = lastLoadedSkillName(args.currentTurnMessages);
|
|
1310
|
+
if (skillName) await args.skillSandbox.loadSkill(skillName);
|
|
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");
|
|
1506
1711
|
}
|
|
1507
1712
|
// src/chat/capabilities/jr-rpc-command.ts
|
|
1508
1713
|
function commandResult(input) {
|
|
@@ -2936,122 +3141,6 @@ function createSandbox(options) {
|
|
|
2936
3141
|
}
|
|
2937
3142
|
};
|
|
2938
3143
|
}
|
|
2939
|
-
// src/chat/tools/sandbox/file-uploads.ts
|
|
2940
|
-
/** Maximum single file size accepted by model-facing upload tools. */
|
|
2941
|
-
const MAX_SANDBOX_FILE_UPLOAD_BYTES = 10485760;
|
|
2942
|
-
/** Sandbox directory for generated files that later tools can consume. */
|
|
2943
|
-
const SANDBOX_GENERATED_DIR = `${SANDBOX_SCRATCH_ROOT}/gen`;
|
|
2944
|
-
const MAX_GENERATED_FILENAME_CODE_POINTS = 60;
|
|
2945
|
-
/** Canonical model-facing reference to a file that already exists in the sandbox. */
|
|
2946
|
-
const sandboxFileReferenceSchema = z.object({
|
|
2947
|
-
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."),
|
|
2948
|
-
filename: z.string().min(1).nullable().optional().describe("Optional filename override shown to the recipient. Null is treated as omitted."),
|
|
2949
|
-
mime_type: z.string().min(1).nullable().optional().describe("Optional MIME type override. Null is treated as omitted."),
|
|
2950
|
-
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.")
|
|
2951
|
-
});
|
|
2952
|
-
/** Generated file reference whose path and metadata can be passed directly to sendFiles. */
|
|
2953
|
-
const generatedFileRefSchema = sandboxFileReferenceSchema.extend({
|
|
2954
|
-
filename: z.string().min(1),
|
|
2955
|
-
mime_type: z.string().min(1).optional(),
|
|
2956
|
-
bytes: z.number().int().nonnegative()
|
|
2957
|
-
}).strict();
|
|
2958
|
-
const MIME_BY_EXTENSION = {
|
|
2959
|
-
".png": "image/png",
|
|
2960
|
-
".jpg": "image/jpeg",
|
|
2961
|
-
".jpeg": "image/jpeg",
|
|
2962
|
-
".gif": "image/gif",
|
|
2963
|
-
".webp": "image/webp",
|
|
2964
|
-
".svg": "image/svg+xml",
|
|
2965
|
-
".pdf": "application/pdf",
|
|
2966
|
-
".txt": "text/plain",
|
|
2967
|
-
".md": "text/markdown",
|
|
2968
|
-
".json": "application/json",
|
|
2969
|
-
".csv": "text/csv",
|
|
2970
|
-
".log": "text/plain"
|
|
2971
|
-
};
|
|
2972
|
-
/** Signal that a model-provided file path did not resolve in the active sandbox. */
|
|
2973
|
-
var SandboxFileNotFoundError = class extends ToolInputError {
|
|
2974
|
-
path;
|
|
2975
|
-
constructor(path) {
|
|
2976
|
-
super(`failed to read file: ${path}`);
|
|
2977
|
-
this.path = path;
|
|
2978
|
-
}
|
|
2979
|
-
};
|
|
2980
|
-
/** Resolve model-provided sandbox paths against the sandbox workspace root. */
|
|
2981
|
-
function normalizeSandboxPath(inputPath) {
|
|
2982
|
-
const trimmed = inputPath.trim();
|
|
2983
|
-
if (!trimmed) throw new ToolInputError("path is required");
|
|
2984
|
-
if (path.posix.isAbsolute(trimmed)) return trimmed;
|
|
2985
|
-
return path.posix.join(SANDBOX_WORKSPACE_ROOT, trimmed);
|
|
2986
|
-
}
|
|
2987
|
-
function sanitizeFilename(value, fallbackPath) {
|
|
2988
|
-
const candidate = (value ?? "").trim();
|
|
2989
|
-
if (candidate) {
|
|
2990
|
-
const base = path.posix.basename(candidate);
|
|
2991
|
-
if (base && base !== "." && base !== "..") return base;
|
|
2992
|
-
}
|
|
2993
|
-
const derived = path.posix.basename(fallbackPath);
|
|
2994
|
-
if (derived && derived !== "." && derived !== "..") return derived;
|
|
2995
|
-
return "attachment.bin";
|
|
2996
|
-
}
|
|
2997
|
-
function capFilename(filename) {
|
|
2998
|
-
const codePoints = Array.from(filename);
|
|
2999
|
-
if (codePoints.length <= MAX_GENERATED_FILENAME_CODE_POINTS) return filename;
|
|
3000
|
-
const ext = Array.from(path.posix.extname(filename));
|
|
3001
|
-
const keepExt = ext.length < MAX_GENERATED_FILENAME_CODE_POINTS / 2;
|
|
3002
|
-
const stemLength = MAX_GENERATED_FILENAME_CODE_POINTS - (keepExt ? ext.length : 0);
|
|
3003
|
-
return [...codePoints.slice(0, stemLength), ...keepExt ? ext : []].join("");
|
|
3004
|
-
}
|
|
3005
|
-
/**
|
|
3006
|
-
* Return the sandbox path for one generated file. The content hash keeps
|
|
3007
|
-
* different files with the same name apart. The last segment keeps the
|
|
3008
|
-
* original name, so a send with only the path still shows that name.
|
|
3009
|
-
*/
|
|
3010
|
-
function sandboxGeneratedFilePath(content, filename) {
|
|
3011
|
-
const hash = createHash("sha256").update(content).digest("hex").slice(0, 12);
|
|
3012
|
-
return path.posix.join(SANDBOX_GENERATED_DIR, hash, capFilename(sanitizeFilename(filename, "file.bin")));
|
|
3013
|
-
}
|
|
3014
|
-
/** Infer upload MIME type from an explicit value or filename extension. */
|
|
3015
|
-
function inferMimeType(filename, explicitMimeType) {
|
|
3016
|
-
const explicit = explicitMimeType?.trim();
|
|
3017
|
-
if (explicit) return explicit;
|
|
3018
|
-
const ext = path.extname(filename).toLowerCase();
|
|
3019
|
-
return MIME_BY_EXTENSION[ext] ?? "application/octet-stream";
|
|
3020
|
-
}
|
|
3021
|
-
async function detectMimeType(workspace, targetPath) {
|
|
3022
|
-
try {
|
|
3023
|
-
const result = await runNonInteractiveCommand(workspace, {
|
|
3024
|
-
cmd: "file",
|
|
3025
|
-
args: [
|
|
3026
|
-
"--mime-type",
|
|
3027
|
-
"-b",
|
|
3028
|
-
targetPath
|
|
3029
|
-
]
|
|
3030
|
-
});
|
|
3031
|
-
if (result.exitCode !== 0) return;
|
|
3032
|
-
return result.stdout.trim() || void 0;
|
|
3033
|
-
} catch {
|
|
3034
|
-
return;
|
|
3035
|
-
}
|
|
3036
|
-
}
|
|
3037
|
-
/** Read and validate one sandbox file for Slack/file reply upload. */
|
|
3038
|
-
async function readSandboxFileUpload(workspace, input) {
|
|
3039
|
-
const targetPath = normalizeSandboxPath(input.path);
|
|
3040
|
-
const fileBuffer = await workspace.readFileToBuffer({ path: targetPath });
|
|
3041
|
-
if (!fileBuffer) throw new SandboxFileNotFoundError(targetPath);
|
|
3042
|
-
if (fileBuffer.byteLength === 0) throw new ToolInputError(`file is empty: ${targetPath}`);
|
|
3043
|
-
if (fileBuffer.byteLength > 10485760) throw new ToolInputError(`file exceeds ${MAX_SANDBOX_FILE_UPLOAD_BYTES} bytes: ${targetPath} (${fileBuffer.byteLength} bytes)`);
|
|
3044
|
-
const resolvedFilename = sanitizeFilename(input.filename, targetPath);
|
|
3045
|
-
const detectedMimeType = await detectMimeType(workspace, targetPath);
|
|
3046
|
-
const resolvedMimeType = inferMimeType(resolvedFilename, input.mime_type ?? detectedMimeType);
|
|
3047
|
-
return {
|
|
3048
|
-
bytes: fileBuffer.byteLength,
|
|
3049
|
-
data: fileBuffer,
|
|
3050
|
-
filename: resolvedFilename,
|
|
3051
|
-
mimeType: resolvedMimeType,
|
|
3052
|
-
path: targetPath
|
|
3053
|
-
};
|
|
3054
|
-
}
|
|
3055
3144
|
// src/chat/tools/sandbox/generated-files.ts
|
|
3056
3145
|
async function fileUploadDataToBuffer(data) {
|
|
3057
3146
|
if (Buffer.isBuffer(data)) return data;
|
|
@@ -3115,11 +3204,12 @@ function replaceGeneratedTextContent(content, text) {
|
|
|
3115
3204
|
text
|
|
3116
3205
|
}, ...withoutFirstGeneratedTextContent(content)];
|
|
3117
3206
|
}
|
|
3118
|
-
|
|
3119
|
-
|
|
3120
|
-
}
|
|
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 });
|
|
3121
3211
|
function hasContinuation(value) {
|
|
3122
|
-
return
|
|
3212
|
+
return continuationDetailsSchema.safeParse(value).success;
|
|
3123
3213
|
}
|
|
3124
3214
|
function stringField(record, key) {
|
|
3125
3215
|
const value = record[key];
|
|
@@ -3133,8 +3223,10 @@ function stringListField(record, key) {
|
|
|
3133
3223
|
const value = record[key];
|
|
3134
3224
|
return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
|
|
3135
3225
|
}
|
|
3136
|
-
function accountText(
|
|
3137
|
-
|
|
3226
|
+
function accountText(account) {
|
|
3227
|
+
const parsed = objectSchema.safeParse(account);
|
|
3228
|
+
if (!parsed.success) return;
|
|
3229
|
+
const value = parsed.data;
|
|
3138
3230
|
const label = stringField(value, "label") || stringField(value, "id");
|
|
3139
3231
|
const id = stringField(value, "id");
|
|
3140
3232
|
if (!label) return;
|
|
@@ -3159,9 +3251,11 @@ function policyDeniedText(value, signal) {
|
|
|
3159
3251
|
...stderr ? ["", `stderr:\n${stderr}`] : []
|
|
3160
3252
|
].join("\n");
|
|
3161
3253
|
}
|
|
3162
|
-
function permissionDeniedText(
|
|
3163
|
-
|
|
3164
|
-
|
|
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;
|
|
3165
3259
|
if (signal["source"] === "policy") return policyDeniedText(value, signal);
|
|
3166
3260
|
if (signal["source"] !== "upstream") return;
|
|
3167
3261
|
const provider = stringField(signal, "provider");
|
|
@@ -3170,7 +3264,7 @@ function permissionDeniedText(value) {
|
|
|
3170
3264
|
const upstreamPath = stringField(signal, "upstreamPath");
|
|
3171
3265
|
const status = numberField(signal, "status");
|
|
3172
3266
|
if (!provider || !message || !upstreamHost || !upstreamPath || !status) return;
|
|
3173
|
-
const grant =
|
|
3267
|
+
const grant = objectSchema.safeParse(signal["grant"]).data ?? {};
|
|
3174
3268
|
const grantName = stringField(grant, "name");
|
|
3175
3269
|
const grantAccess = stringField(grant, "access");
|
|
3176
3270
|
const grantReason = stringField(grant, "reason");
|
|
@@ -3306,7 +3400,10 @@ function createAgentSandbox(options) {
|
|
|
3306
3400
|
conversationId: options.conversationId,
|
|
3307
3401
|
credentialEgress: options.credentialEgress,
|
|
3308
3402
|
credentialAuditSource: options.credentialAuditSource,
|
|
3309
|
-
prepare:
|
|
3403
|
+
prepare: async (workspace) => {
|
|
3404
|
+
await options.prepareSandbox(workspace);
|
|
3405
|
+
await options.artifacts?.restore(workspace);
|
|
3406
|
+
},
|
|
3310
3407
|
prepareWorkspace: options.prepareWorkspace,
|
|
3311
3408
|
onSandboxRefChanged: async (sandboxRef) => {
|
|
3312
3409
|
options.onSandboxRefChanged(sandboxRef);
|
|
@@ -3338,7 +3435,10 @@ function createAgentSandbox(options) {
|
|
|
3338
3435
|
});
|
|
3339
3436
|
if (result.handled) return formatSandboxCommandResult(result.result);
|
|
3340
3437
|
}
|
|
3341
|
-
|
|
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;
|
|
3342
3442
|
}
|
|
3343
3443
|
},
|
|
3344
3444
|
async writeGeneratedFiles(files) {
|
|
@@ -4205,7 +4305,11 @@ function createLoadSkillTool(availableSkills, options) {
|
|
|
4205
4305
|
const result = await loadSkillFromHost(availableSkills, skill_name);
|
|
4206
4306
|
const loadedSkill = toLoadedSkill(result, availableSkills);
|
|
4207
4307
|
if (loadedSkill) await options?.onSkillLoaded?.(loadedSkill);
|
|
4208
|
-
|
|
4308
|
+
const loadable = (availableSkills.find((skill) => skill.name === result.skill_name)?.references ?? []).filter((name) => name !== result.skill_name && availableSkills.some((skill) => skill.name === name && skill.disableModelInvocation));
|
|
4309
|
+
return loadable.length > 0 ? {
|
|
4310
|
+
...result,
|
|
4311
|
+
loadable_skills: loadable
|
|
4312
|
+
} : result;
|
|
4209
4313
|
}
|
|
4210
4314
|
});
|
|
4211
4315
|
}
|
|
@@ -4356,9 +4460,12 @@ function createSearchMcpToolsTool(mcpToolManager) {
|
|
|
4356
4460
|
inputSchema: z.object({
|
|
4357
4461
|
query: z.string().min(1).describe("Optional search terms describing the MCP tool or arguments needed.").optional(),
|
|
4358
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(),
|
|
4359
|
-
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(),
|
|
4360
4464
|
max_results: z.number().int().min(1).max(MAX_RESULTS$1).describe("Maximum matching tool descriptors to return.").optional()
|
|
4361
|
-
}).strict(),
|
|
4465
|
+
}).strict().refine((input) => !input.provider || Boolean(input.intent), {
|
|
4466
|
+
message: "Pass intent with provider.",
|
|
4467
|
+
path: ["intent"]
|
|
4468
|
+
}),
|
|
4362
4469
|
outputSchema: searchMcpToolsOutputSchema,
|
|
4363
4470
|
privateTraceResult: (result) => ({
|
|
4364
4471
|
total_active_tools: result.total_active_tools,
|
|
@@ -4672,7 +4779,7 @@ function titleText(item) {
|
|
|
4672
4779
|
function itemText(item) {
|
|
4673
4780
|
return normalizeSlackReplyMarkdown([
|
|
4674
4781
|
titleText(item),
|
|
4675
|
-
truncate$1(item.body, MAX_BODY_CHARS),
|
|
4782
|
+
...item.request?.question === item.body ? [] : [truncate$1(item.body, MAX_BODY_CHARS)],
|
|
4676
4783
|
...item.request ? [slackUserInputText(item.request)] : []
|
|
4677
4784
|
].join("\n\n"));
|
|
4678
4785
|
}
|
|
@@ -4703,12 +4810,12 @@ function controls(item) {
|
|
|
4703
4810
|
label: option.label
|
|
4704
4811
|
})
|
|
4705
4812
|
})),
|
|
4706
|
-
{
|
|
4813
|
+
...buttonField.options.length > 1 ? [{
|
|
4707
4814
|
type: "button",
|
|
4708
4815
|
action_id: ANSWER_ACTION_ID,
|
|
4709
4816
|
text: plainText("Other…"),
|
|
4710
4817
|
value: item.id
|
|
4711
|
-
},
|
|
4818
|
+
}] : [],
|
|
4712
4819
|
dismiss
|
|
4713
4820
|
];
|
|
4714
4821
|
}
|
|
@@ -4734,7 +4841,7 @@ function closedNote(item) {
|
|
|
4734
4841
|
function buildSlackReviewItemCard(item) {
|
|
4735
4842
|
const text = itemText(item);
|
|
4736
4843
|
const link = getDashboardReviewItemLink(item.id);
|
|
4737
|
-
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) => ({
|
|
4738
4845
|
type: "mrkdwn",
|
|
4739
4846
|
text: truncate$1(part, MAX_CONTEXT_CHARS)
|
|
4740
4847
|
}));
|
|
@@ -4764,7 +4871,7 @@ function buildHiddenSlackReviewItemCard(item) {
|
|
|
4764
4871
|
type: "context",
|
|
4765
4872
|
elements: [{
|
|
4766
4873
|
type: "mrkdwn",
|
|
4767
|
-
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."
|
|
4768
4875
|
}]
|
|
4769
4876
|
}],
|
|
4770
4877
|
text: "Review item"
|
|
@@ -5074,16 +5181,27 @@ function createSendFilesTool(state, materializeFile, output) {
|
|
|
5074
5181
|
});
|
|
5075
5182
|
}
|
|
5076
5183
|
// src/chat/slack/tools/send-files.ts
|
|
5077
|
-
/**
|
|
5078
|
-
|
|
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) {
|
|
5079
5190
|
const channelId = context.locationChannelId;
|
|
5080
5191
|
const threadTs = context.threadTs ?? context.messageTs;
|
|
5081
5192
|
return createSendFilesTool(state, materializeFile, {
|
|
5082
|
-
attachments
|
|
5193
|
+
...attachments ? { attachments: {
|
|
5194
|
+
...attachments,
|
|
5195
|
+
conversationId
|
|
5196
|
+
} } : void 0,
|
|
5083
5197
|
delivery: {
|
|
5084
5198
|
key: `${channelId}:${threadTs ?? ""}`,
|
|
5085
5199
|
description: "Send one or more sandbox files into the active Slack conversation.",
|
|
5086
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
|
+
}
|
|
5087
5205
|
await uploadFilesToConversation({
|
|
5088
5206
|
channelId,
|
|
5089
5207
|
files: files.map((file) => ({
|
|
@@ -5153,6 +5271,78 @@ function createSlackCanvasCreateTool(context, state) {
|
|
|
5153
5271
|
}
|
|
5154
5272
|
});
|
|
5155
5273
|
}
|
|
5274
|
+
// src/chat/automations/tool-destination.ts
|
|
5275
|
+
/** Model-facing Destination of a new or moved Automation. */
|
|
5276
|
+
const automationDestinationParam = slackChannelRefParam.describe("Slack channel: \"current_conversation\" (this conversation's channel or DM) or a public channel id, mention, or known name, only one the user named. Never a web conversation.");
|
|
5277
|
+
/**
|
|
5278
|
+
* Return the Slack workspace of a new Destination. A Conversation with no
|
|
5279
|
+
* Slack Location, such as a web Conversation, binds no workspace token, so
|
|
5280
|
+
* Slack calls use the single bot token. It can reach only that token's
|
|
5281
|
+
* workspace, and only for a caller with a linked Slack account there.
|
|
5282
|
+
*/
|
|
5283
|
+
async function requireDestinationTeamId(context, caller) {
|
|
5284
|
+
if (context.destination) {
|
|
5285
|
+
const teamId = parseSlackTeamId(context.destination.teamId);
|
|
5286
|
+
if (!teamId) throw new ToolInputError("Slack workspace is unavailable.");
|
|
5287
|
+
return teamId;
|
|
5288
|
+
}
|
|
5289
|
+
const teamId = parseSlackTeamId(await resolveBotSlackTeamId());
|
|
5290
|
+
if (!teamId) throw new ToolInputError("No Slack workspace can be chosen from this conversation. Ask from the Slack channel where the automation should deliver.");
|
|
5291
|
+
if (!caller.viewer.identities.some((identity) => identity.provider === "slack" && identity.providerTenantId === teamId)) throw new ToolInputError("An automation delivers to Slack, and your account has no linked Slack account in this workspace. Link Slack, or ask from the Slack channel where it should deliver.");
|
|
5292
|
+
return teamId;
|
|
5293
|
+
}
|
|
5294
|
+
/**
|
|
5295
|
+
* Resolve where a new or moved Automation delivers. "current_conversation"
|
|
5296
|
+
* is the channel or DM of this Conversation. A channel reference must name a
|
|
5297
|
+
* public Slack channel, and Junior joins it so the Automation can post there.
|
|
5298
|
+
* A private channel or DM can be a Destination only from there, so a web
|
|
5299
|
+
* Conversation can name only a public channel.
|
|
5300
|
+
*/
|
|
5301
|
+
async function resolveToolDestination(context, caller, value) {
|
|
5302
|
+
if (value === "current_conversation") return {
|
|
5303
|
+
destination: requireToolDestination(context),
|
|
5304
|
+
visibility: context.visibility
|
|
5305
|
+
};
|
|
5306
|
+
const teamId = await requireDestinationTeamId(context, caller);
|
|
5307
|
+
const { channelId, channelName } = await resolveSlackChannelRef({
|
|
5308
|
+
field: "destination",
|
|
5309
|
+
value,
|
|
5310
|
+
teamId
|
|
5311
|
+
});
|
|
5312
|
+
const here = context.destination;
|
|
5313
|
+
if (here && channelId === here.channelId) return {
|
|
5314
|
+
destination: here,
|
|
5315
|
+
visibility: context.visibility
|
|
5316
|
+
};
|
|
5317
|
+
const access = await checkSlackChannelReadAccess({
|
|
5318
|
+
currentChannelIds: [],
|
|
5319
|
+
targetChannelId: channelId,
|
|
5320
|
+
teamId
|
|
5321
|
+
});
|
|
5322
|
+
if (!access.allowed) throw new ToolInputError(access.reason === "private" ? "Only a public channel can be named as a destination. For a private channel or DM, ask from there." : access.error);
|
|
5323
|
+
if (access.isMember !== true) {
|
|
5324
|
+
const joined = await joinPublicChannelForRead({
|
|
5325
|
+
targetChannelId: channelId,
|
|
5326
|
+
...channelName ? { channelName } : void 0
|
|
5327
|
+
});
|
|
5328
|
+
if (!joined.ok) throw new ToolInputError(joined.error);
|
|
5329
|
+
}
|
|
5330
|
+
const destination = {
|
|
5331
|
+
platform: "slack",
|
|
5332
|
+
teamId,
|
|
5333
|
+
channelId
|
|
5334
|
+
};
|
|
5335
|
+
const name = access.channelName ?? channelName;
|
|
5336
|
+
await getConversationStore().recordDestinationVisibility({
|
|
5337
|
+
destination,
|
|
5338
|
+
...name ? { channelName: name } : void 0,
|
|
5339
|
+
visibility: "public"
|
|
5340
|
+
});
|
|
5341
|
+
return {
|
|
5342
|
+
destination,
|
|
5343
|
+
visibility: "public"
|
|
5344
|
+
};
|
|
5345
|
+
}
|
|
5156
5346
|
// src/chat/scheduled-automations/telemetry.ts
|
|
5157
5347
|
/** Safe structured telemetry attributes for scheduled-automation lifecycle events. */
|
|
5158
5348
|
/** Correlation attributes shared by scheduled-automation create and run events. */
|
|
@@ -5219,7 +5409,7 @@ async function createScheduled(context, next, compiled) {
|
|
|
5219
5409
|
updatedAtMs: nowMs,
|
|
5220
5410
|
createdBy: next.creator.createdBy,
|
|
5221
5411
|
creatorIdentityId: next.creator.identity.id,
|
|
5222
|
-
conversationAccess: getConversationAccess(destination,
|
|
5412
|
+
conversationAccess: getConversationAccess(destination, next.visibility),
|
|
5223
5413
|
credentialMode: next.credentialMode,
|
|
5224
5414
|
destination,
|
|
5225
5415
|
executionActor: SCHEDULED_AUTOMATION_SYSTEM_ACTOR,
|
|
@@ -5238,12 +5428,12 @@ async function createScheduled(context, next, compiled) {
|
|
|
5238
5428
|
ownedByViewer: true
|
|
5239
5429
|
};
|
|
5240
5430
|
}
|
|
5241
|
-
async function createEvent(
|
|
5431
|
+
async function createEvent(next, trigger) {
|
|
5242
5432
|
return {
|
|
5243
5433
|
kind: "event",
|
|
5244
5434
|
task: await createEventAutomation(getDb(), requireSlackChannelMessageScope({
|
|
5245
5435
|
id: next.id,
|
|
5246
|
-
destinationVisibility:
|
|
5436
|
+
destinationVisibility: next.visibility === "public" ? "public" : "private",
|
|
5247
5437
|
createdAtMs: next.nowMs,
|
|
5248
5438
|
createdBy: next.creator.createdBy,
|
|
5249
5439
|
creatorIdentityId: next.creator.identity.id,
|
|
@@ -5293,7 +5483,7 @@ function createAutomationTool(context, catalog, skills = []) {
|
|
|
5293
5483
|
readOnlyHint: false
|
|
5294
5484
|
},
|
|
5295
5485
|
executionMode: "sequential",
|
|
5296
|
-
description: "Create a durable automation. It
|
|
5486
|
+
description: "Create a durable automation. It delivers to a Slack channel or DM, never a thread or a web conversation. When an installed skill does the work, have the automation run that skill; do not write an instruction that names the skill. Ordinary watch, notify, or tell-me-when requests use watchEvents instead. Store the requested future work; do not perform it or check its service access now unless the user also asks for that. When the trigger is known, create it without redundant confirmation.",
|
|
5297
5487
|
inputSchema: z.object({
|
|
5298
5488
|
instruction: automationInstructionToolSchema.nullable().optional(),
|
|
5299
5489
|
skill: automationSkillToolSchema(skills).nullable().optional(),
|
|
@@ -5301,7 +5491,8 @@ function createAutomationTool(context, catalog, skills = []) {
|
|
|
5301
5491
|
title: z.string().trim().min(1).max(60).nullable().describe("Optional short display title. Omit or use null to generate one from the instruction or skill.").optional(),
|
|
5302
5492
|
trigger: trigger.describe("Use type \"schedule\" for one-time or recurring work. Use type \"event\" only when the user explicitly asks for an event automation or durable whenever-this-happens-do-X work; it runs for every matching event."),
|
|
5303
5493
|
outcomes: z.array(taskOutcomeInputSchema).max(5).describe("Successful work is silent by default: omit this or use an empty list when the Automation acts through tools without a status message. Add send_message only when the user asks for a reminder, notification, post, digest, summary, or other visible result.").optional(),
|
|
5304
|
-
credential_mode: z.enum(["creator", "system"]).nullable().describe("Omit or use null for the system default: runs use your own credentials. Use creator only when the creator asks for their connected credentials to be available to the runs.").optional()
|
|
5494
|
+
credential_mode: z.enum(["creator", "system"]).nullable().describe("Omit or use null for the system default: runs use your own credentials. Use creator only when the creator asks for their connected credentials to be available to the runs.").optional(),
|
|
5495
|
+
destination: automationDestinationParam.nullable().describe(`${automationDestinationParam.description} ${context.destination ? "Omit or use null for current_conversation." : "Required: current_conversation is unavailable here."}`).optional()
|
|
5305
5496
|
}).strict(),
|
|
5306
5497
|
prepareArguments(args) {
|
|
5307
5498
|
const prepared = { ...args };
|
|
@@ -5310,13 +5501,14 @@ function createAutomationTool(context, catalog, skills = []) {
|
|
|
5310
5501
|
if (prepared.skill == null) delete prepared.skill;
|
|
5311
5502
|
if (prepared.context == null) delete prepared.context;
|
|
5312
5503
|
if (prepared.credential_mode === null) delete prepared.credential_mode;
|
|
5504
|
+
if (prepared.destination == null) delete prepared.destination;
|
|
5313
5505
|
return prepared;
|
|
5314
5506
|
},
|
|
5315
5507
|
outputSchema: automationToolResultSchema,
|
|
5316
5508
|
async execute(input, options) {
|
|
5317
5509
|
const kind = triggerKind(input.trigger);
|
|
5318
|
-
const destination = requireToolDestination(context);
|
|
5319
5510
|
const caller = await requireToolCaller(context);
|
|
5511
|
+
const { destination, visibility } = await resolveToolDestination(context, caller, input.destination ?? "current_conversation");
|
|
5320
5512
|
const creator = requireToolCreator(caller, destination, kind);
|
|
5321
5513
|
const { createdBy } = creator;
|
|
5322
5514
|
const task = newAutomationTask({
|
|
@@ -5349,6 +5541,7 @@ function createAutomationTool(context, catalog, skills = []) {
|
|
|
5349
5541
|
const next = {
|
|
5350
5542
|
creator,
|
|
5351
5543
|
destination,
|
|
5544
|
+
visibility,
|
|
5352
5545
|
id,
|
|
5353
5546
|
nowMs,
|
|
5354
5547
|
task,
|
|
@@ -5362,7 +5555,7 @@ function createAutomationTool(context, catalog, skills = []) {
|
|
|
5362
5555
|
title: input.title
|
|
5363
5556
|
})
|
|
5364
5557
|
};
|
|
5365
|
-
return requireOwnAutomation(compiled ? await createScheduled(context, next, compiled) : await createEvent(
|
|
5558
|
+
return requireOwnAutomation(compiled ? await createScheduled(context, next, compiled) : await createEvent(next, eventTrigger));
|
|
5366
5559
|
}
|
|
5367
5560
|
});
|
|
5368
5561
|
}
|
|
@@ -5382,61 +5575,11 @@ async function resolveDestinationVisibility(args) {
|
|
|
5382
5575
|
async function requireNoIncompleteRun(automationId) {
|
|
5383
5576
|
if ((await getDb().select({ id: juniorAutomationRuns.id }).from(juniorAutomationRuns).where(and(eq(juniorAutomationRuns.automationId, automationId), inArray(juniorAutomationRuns.status, ["pending", "running"]))).limit(1)).length > 0) throw new ToolInputError("Scheduled automation cannot be moved while an occurrence is already running. Try again after the current run finishes.");
|
|
5384
5577
|
}
|
|
5385
|
-
/**
|
|
5386
|
-
* Resolve where a move goes. "current_conversation" is this Conversation. A
|
|
5387
|
-
* channel reference must name a public Slack channel in this workspace, and
|
|
5388
|
-
* Junior joins it so the Automation can post there.
|
|
5389
|
-
*/
|
|
5390
|
-
async function requireMoveDestination(context, value) {
|
|
5391
|
-
const here = requireToolDestination(context);
|
|
5392
|
-
if (value === "current_conversation") return {
|
|
5393
|
-
destination: here,
|
|
5394
|
-
visibility: context.visibility
|
|
5395
|
-
};
|
|
5396
|
-
const teamId = parseSlackTeamId(here.teamId);
|
|
5397
|
-
if (!teamId) throw new ToolInputError("Slack workspace is unavailable.");
|
|
5398
|
-
const { channelId, channelName } = await resolveSlackChannelRef({
|
|
5399
|
-
field: "destination",
|
|
5400
|
-
value,
|
|
5401
|
-
teamId
|
|
5402
|
-
});
|
|
5403
|
-
if (channelId === here.channelId) return {
|
|
5404
|
-
destination: here,
|
|
5405
|
-
visibility: context.visibility
|
|
5406
|
-
};
|
|
5407
|
-
const access = await checkSlackChannelReadAccess({
|
|
5408
|
-
currentChannelIds: [],
|
|
5409
|
-
targetChannelId: channelId,
|
|
5410
|
-
teamId
|
|
5411
|
-
});
|
|
5412
|
-
if (!access.allowed) throw new ToolInputError(access.reason === "private" ? "Only a public channel can be named as a destination. To move an automation into a private channel or DM, ask from there." : access.error);
|
|
5413
|
-
if (access.isMember !== true) {
|
|
5414
|
-
const joined = await joinPublicChannelForRead({
|
|
5415
|
-
targetChannelId: channelId,
|
|
5416
|
-
...channelName ? { channelName } : void 0
|
|
5417
|
-
});
|
|
5418
|
-
if (!joined.ok) throw new ToolInputError(joined.error);
|
|
5419
|
-
}
|
|
5420
|
-
const destination = {
|
|
5421
|
-
platform: "slack",
|
|
5422
|
-
teamId,
|
|
5423
|
-
channelId
|
|
5424
|
-
};
|
|
5425
|
-
const name = access.channelName ?? channelName;
|
|
5426
|
-
await getConversationStore().recordDestinationVisibility({
|
|
5427
|
-
destination,
|
|
5428
|
-
...name ? { channelName: name } : void 0,
|
|
5429
|
-
visibility: "public"
|
|
5430
|
-
});
|
|
5431
|
-
return {
|
|
5432
|
-
destination,
|
|
5433
|
-
visibility: "public"
|
|
5434
|
-
};
|
|
5435
|
-
}
|
|
5436
5578
|
/** Edit and save a scheduled Automation, including a move to a new Destination. */
|
|
5437
|
-
async function updateScheduled(context, current, input, editedTask, editor) {
|
|
5579
|
+
async function updateScheduled(context, caller, current, input, editedTask, editor) {
|
|
5438
5580
|
const { task, ownedByViewer: isCreator } = current;
|
|
5439
|
-
|
|
5581
|
+
if (input.destination && !context.destination) throw new ToolInputError("Move an automation from a Slack channel or DM, not from a web conversation.");
|
|
5582
|
+
const target = input.destination ? await resolveToolDestination(context, caller, input.destination) : void 0;
|
|
5440
5583
|
const destination = target?.destination;
|
|
5441
5584
|
const moving = destination !== void 0 && !sameDestination(task.destination, destination);
|
|
5442
5585
|
if (destination && !moving && Object.keys(input).every((key) => key === "destination" || key === "credential_mode" && input.credential_mode === task.credentialMode)) return current;
|
|
@@ -5504,7 +5647,7 @@ function createUpdateAutomationTool(context, catalog, skills = []) {
|
|
|
5504
5647
|
outcomes: z.array(taskOutcomeInputSchema).max(5).nullable().describe("Replacement messages to send after successful work. Use an empty list to send nothing. Omit or use null to leave unchanged.").optional(),
|
|
5505
5648
|
credential_mode: z.enum(["system", "creator"]).nullable().describe("Set creator to make the automation creator's credentials available, or system to disable them. Creator always means the automation's createdBy actor, never the current requester. Only that creator may enable creator mode. Omit or null leaves it unchanged.").optional(),
|
|
5506
5649
|
status: z.enum(["active", "paused"]).nullable().describe("Set active to resume a paused or blocked automation, or paused to stop it. When it uses its creator's credentials, only the creator can resume it. Omit or use null to leave unchanged.").optional(),
|
|
5507
|
-
destination:
|
|
5650
|
+
destination: automationDestinationParam.nullable().describe(`Where to move a scheduled automation. ${automationDestinationParam.description} Omit to keep its destination.`).optional()
|
|
5508
5651
|
}).strict();
|
|
5509
5652
|
return zodTool({
|
|
5510
5653
|
exposure: "deferred",
|
|
@@ -5541,7 +5684,7 @@ function createUpdateAutomationTool(context, catalog, skills = []) {
|
|
|
5541
5684
|
current: current.task.task
|
|
5542
5685
|
});
|
|
5543
5686
|
let saved = current;
|
|
5544
|
-
if (Object.keys(input).length > 0) saved = current.kind === "scheduled" ? await updateScheduled(context, current, input, editedTask, editor) : await updateEvent(current, input, editedTask, editor, catalog);
|
|
5687
|
+
if (Object.keys(input).length > 0) saved = current.kind === "scheduled" ? await updateScheduled(context, caller, current, input, editedTask, editor) : await updateEvent(current, input, editedTask, editor, catalog);
|
|
5545
5688
|
if (status !== void 0 && status !== saved.task.status) saved = await changeAutomationLifecycle(saved, {
|
|
5546
5689
|
action: status === "paused" ? "pause" : "resume",
|
|
5547
5690
|
revision: automationRevision(saved.task)
|
|
@@ -5608,7 +5751,7 @@ async function publishImage(args) {
|
|
|
5608
5751
|
const baseUrl = resolvePublicBaseUrl(args.publicBaseUrl);
|
|
5609
5752
|
const sha256 = createHash("sha256").update(args.body).digest("hex");
|
|
5610
5753
|
const now = args.now ?? /* @__PURE__ */ new Date();
|
|
5611
|
-
const [existing] = await args.db.db().select({ id: juniorArtifacts.id }).from(juniorArtifacts).where(and(eq(juniorArtifacts.conversationId, args.conversationId), eq(juniorArtifacts.sha256, sha256)));
|
|
5754
|
+
const [existing] = await args.db.db().select({ id: juniorArtifacts.id }).from(juniorArtifacts).where(and(eq(juniorArtifacts.conversationId, args.conversationId), eq(juniorArtifacts.sha256, sha256), eq(juniorArtifacts.visibility, "public")));
|
|
5612
5755
|
const id = existing?.id ?? randomUUID();
|
|
5613
5756
|
const storageKey = artifactKey(`${id}.${extension}`);
|
|
5614
5757
|
await args.storage.put({
|
|
@@ -5625,17 +5768,17 @@ async function publishImage(args) {
|
|
|
5625
5768
|
deleteRequestedAt: null,
|
|
5626
5769
|
ext: extension,
|
|
5627
5770
|
id,
|
|
5628
|
-
public: true,
|
|
5629
5771
|
sha256,
|
|
5630
|
-
storageKey
|
|
5772
|
+
storageKey,
|
|
5773
|
+
visibility: "public"
|
|
5631
5774
|
}).onConflictDoUpdate({
|
|
5632
5775
|
target: [juniorArtifacts.conversationId, juniorArtifacts.sha256],
|
|
5776
|
+
targetWhere: eq(juniorArtifacts.visibility, "public"),
|
|
5633
5777
|
set: {
|
|
5634
5778
|
bytes: args.body.byteLength,
|
|
5635
5779
|
contentType,
|
|
5636
5780
|
deleteRequestedAt: null,
|
|
5637
|
-
ext: extension
|
|
5638
|
-
public: true
|
|
5781
|
+
ext: extension
|
|
5639
5782
|
}
|
|
5640
5783
|
}).returning({
|
|
5641
5784
|
ext: juniorArtifacts.ext,
|
|
@@ -5668,7 +5811,7 @@ async function readPublicArtifact(args) {
|
|
|
5668
5811
|
const [row] = await args.db.db().select({
|
|
5669
5812
|
contentType: juniorArtifacts.contentType,
|
|
5670
5813
|
storageKey: juniorArtifacts.storageKey
|
|
5671
|
-
}).from(juniorArtifacts).where(and(eq(juniorArtifacts.id, parsed.id), eq(juniorArtifacts.
|
|
5814
|
+
}).from(juniorArtifacts).where(and(eq(juniorArtifacts.id, parsed.id), eq(juniorArtifacts.visibility, "public"), isNull(juniorArtifacts.deleteRequestedAt)));
|
|
5672
5815
|
if (!row) return null;
|
|
5673
5816
|
const body = await args.storage.get(row.storageKey);
|
|
5674
5817
|
if (!body) return null;
|
|
@@ -5880,7 +6023,7 @@ const STATIC_TOOL_BINDERS = {
|
|
|
5880
6023
|
updateReviewItem: (run) => createUpdateReviewItemTool(run.context, run.reviewItemServices())
|
|
5881
6024
|
};
|
|
5882
6025
|
const AGENT_TOOL_LIMIT = (turnTools) => turnTools.agents === "none" ? "A person's Turn in a Thread cannot use agent tools." : void 0;
|
|
5883
|
-
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.`;
|
|
5884
6027
|
const TURN_TOOL_LIMITS = {
|
|
5885
6028
|
spawnAgent: AGENT_TOOL_LIMIT,
|
|
5886
6029
|
stopAgent: AGENT_TOOL_LIMIT,
|
|
@@ -5891,9 +6034,9 @@ const TURN_TOOL_LIMITS = {
|
|
|
5891
6034
|
[REPORT_BLOCKED_TOOL_NAME]: (turnTools) => turnTools.reportBlocked === "none" ? "This Turn cannot send a blocked report." : void 0,
|
|
5892
6035
|
updateUserCustomization: (turnTools) => turnTools.userCustomization ? void 0 : "Only a person's Turn can change user customization.",
|
|
5893
6036
|
setConversationSubscription: (turnTools) => turnTools.subscriptions ? void 0 : "Only a person's Turn can change subscriptions.",
|
|
5894
|
-
addReviewItem:
|
|
5895
|
-
searchReviewItems:
|
|
5896
|
-
updateReviewItem:
|
|
6037
|
+
addReviewItem: INBOX_LIMIT,
|
|
6038
|
+
searchReviewItems: INBOX_LIMIT,
|
|
6039
|
+
updateReviewItem: INBOX_LIMIT
|
|
5897
6040
|
};
|
|
5898
6041
|
function attachmentStore(run) {
|
|
5899
6042
|
const storage = run.context.attachmentStorage;
|
|
@@ -5979,7 +6122,7 @@ const RUN_BUILT_TOOL_BUILDERS = {
|
|
|
5979
6122
|
sendFiles: (run) => {
|
|
5980
6123
|
if (!run.slack) return void 0;
|
|
5981
6124
|
if (!resolveChannelCapabilities(run.slack.locationChannelId).canSendFiles) return void 0;
|
|
5982
|
-
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));
|
|
5983
6126
|
},
|
|
5984
6127
|
addReaction: (run) => {
|
|
5985
6128
|
if (!run.slack) return void 0;
|
|
@@ -6722,31 +6865,26 @@ function handleToolExecutionError(error, toolName, toolCallId, shouldTrace, conv
|
|
|
6722
6865
|
function effectiveToolExposure(definition) {
|
|
6723
6866
|
return definition.exposure ?? "direct";
|
|
6724
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
|
+
};
|
|
6725
6879
|
/** Plan which callers may call each tool. `ToolExposure` owns the rules. */
|
|
6726
6880
|
function planToolExposure(tools) {
|
|
6727
|
-
const
|
|
6728
|
-
|
|
6729
|
-
|
|
6730
|
-
|
|
6731
|
-
case "direct":
|
|
6732
|
-
directTools[name] = definition;
|
|
6733
|
-
catalogTools[name] = definition;
|
|
6734
|
-
scriptTools[name] = definition;
|
|
6735
|
-
break;
|
|
6736
|
-
case "deferred":
|
|
6737
|
-
catalogTools[name] = definition;
|
|
6738
|
-
scriptTools[name] = definition;
|
|
6739
|
-
break;
|
|
6740
|
-
case "modelOnly":
|
|
6741
|
-
directTools[name] = definition;
|
|
6742
|
-
break;
|
|
6743
|
-
case "codemode": scriptTools[name] = definition;
|
|
6744
|
-
}
|
|
6745
|
-
return {
|
|
6746
|
-
catalogTools,
|
|
6747
|
-
directTools,
|
|
6748
|
-
scriptTools
|
|
6881
|
+
const planned = {
|
|
6882
|
+
catalogTools: {},
|
|
6883
|
+
directTools: {},
|
|
6884
|
+
scriptTools: {}
|
|
6749
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;
|
|
6750
6888
|
}
|
|
6751
6889
|
// src/chat/tools/search-tools-rerank.ts
|
|
6752
6890
|
const MAX_PICKED_TOOLS = 3;
|
|
@@ -9223,6 +9361,26 @@ function buildToolActionEvidence(messages) {
|
|
|
9223
9361
|
}
|
|
9224
9362
|
// src/chat/agent-invocations/root-conversation.ts
|
|
9225
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
|
+
/**
|
|
9226
9384
|
* Most root context messages that Guardian reads, newest first. Codex uses
|
|
9227
9385
|
* 16. Messages that can authorize do not count toward this number.
|
|
9228
9386
|
*/
|
|
@@ -9233,17 +9391,18 @@ const MAX_ROOT_MESSAGE_CHARS = 4e3;
|
|
|
9233
9391
|
const MAX_ROOT_CONVERSATION_CHARS = 24e3;
|
|
9234
9392
|
/** Message events read from the log. Edits and skipped messages use some. */
|
|
9235
9393
|
const MAX_ROOT_MESSAGE_EVENTS = 64;
|
|
9236
|
-
|
|
9237
|
-
|
|
9238
|
-
|
|
9394
|
+
const messageAuthorSchema = z.object({
|
|
9395
|
+
isBot: z.unknown().optional(),
|
|
9396
|
+
userId: z.string()
|
|
9397
|
+
});
|
|
9239
9398
|
/**
|
|
9240
9399
|
* Build the Actor that wrote one root message, from the runtime-recorded
|
|
9241
9400
|
* author and the root's provider. Returns nothing when it is not known.
|
|
9242
9401
|
*/
|
|
9243
9402
|
function messageAuthor(root, data) {
|
|
9244
|
-
const author =
|
|
9245
|
-
const userId =
|
|
9246
|
-
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;
|
|
9247
9406
|
const session = root.sessionSource;
|
|
9248
9407
|
const platform = session?.kind ?? root.destination?.platform;
|
|
9249
9408
|
if (platform === "slack") {
|
|
@@ -9453,6 +9612,7 @@ async function createRunSandbox(args) {
|
|
|
9453
9612
|
}
|
|
9454
9613
|
});
|
|
9455
9614
|
const workspace = args.state.sandboxRef?.workspaceId ? await getWorkspace(getDb(), args.state.sandboxRef.workspaceId) : void 0;
|
|
9615
|
+
const attachmentStorage = args.run.environment?.attachmentStorage;
|
|
9456
9616
|
const agentSandbox = createAgentSandbox({
|
|
9457
9617
|
sandboxRef: args.state.sandboxRef,
|
|
9458
9618
|
workspace,
|
|
@@ -9464,6 +9624,11 @@ async function createRunSandbox(args) {
|
|
|
9464
9624
|
credentialEgress: args.run.credentialContext,
|
|
9465
9625
|
credentialAuditSource: credentialAuditSource(args.run.source),
|
|
9466
9626
|
actor: args.currentActor,
|
|
9627
|
+
artifacts: attachmentStorage ? createArtifactSync({
|
|
9628
|
+
conversationId: args.run.conversationId,
|
|
9629
|
+
db: getSqlExecutor(),
|
|
9630
|
+
storage: attachmentStorage
|
|
9631
|
+
}) : void 0,
|
|
9467
9632
|
locationConfiguration: args.run.environment?.locationConfiguration,
|
|
9468
9633
|
configurationValues: args.configurationValues,
|
|
9469
9634
|
getActiveSkill: () => args.skillSandbox.getActiveSkill(),
|
|
@@ -9492,7 +9657,7 @@ function createPromptHookContext(args) {
|
|
|
9492
9657
|
run: args.run
|
|
9493
9658
|
}),
|
|
9494
9659
|
...actor ? { resolveActorIdentity: async () => await readActorIdentity(actor) } : void 0,
|
|
9495
|
-
userText: args.
|
|
9660
|
+
userText: turnRequestText(args.run)
|
|
9496
9661
|
};
|
|
9497
9662
|
}
|
|
9498
9663
|
/** Record optional reporting without changing the loadSkill outcome. */
|
|
@@ -9680,8 +9845,7 @@ async function wireAgentTools(args) {
|
|
|
9680
9845
|
modelId: botConfig.guardianModelId
|
|
9681
9846
|
})
|
|
9682
9847
|
});
|
|
9683
|
-
const
|
|
9684
|
-
const tools = createTools(skills, {
|
|
9848
|
+
const tools = createTools(loadableSkills(args.availableSkills, [...args.invokedSkillNames, ...args.conversationSkillNames]), {
|
|
9685
9849
|
writeGeneratedFiles: async (files) => {
|
|
9686
9850
|
const refs = await agentSandbox.writeGeneratedFiles(files);
|
|
9687
9851
|
args.generatedFiles.push(...files);
|
|
@@ -9690,8 +9854,10 @@ async function wireAgentTools(args) {
|
|
|
9690
9854
|
toolOverrides: args.run.environment?.toolOverrides,
|
|
9691
9855
|
onSkillLoaded: async (loadedSkill) => {
|
|
9692
9856
|
const effective = await args.skillSandbox.loadSkill(loadedSkill.name) ?? loadedSkill;
|
|
9693
|
-
|
|
9694
|
-
|
|
9857
|
+
if (effective.disableModelInvocation) await recordSkillLoaded({
|
|
9858
|
+
conversationId: args.run.conversationId,
|
|
9859
|
+
skillName: effective.name
|
|
9860
|
+
});
|
|
9695
9861
|
await tryRecordSkillLoadStat(effective);
|
|
9696
9862
|
}
|
|
9697
9863
|
}, toolRuntimeContext, {
|
|
@@ -10045,1289 +10211,6 @@ function createResumeState(args) {
|
|
|
10045
10211
|
}
|
|
10046
10212
|
};
|
|
10047
10213
|
}
|
|
10048
|
-
// src/chat/agent/context-summary.ts
|
|
10049
|
-
/**
|
|
10050
|
-
* Context summary for capacity compaction.
|
|
10051
|
-
*
|
|
10052
|
-
* The summary request is the agent model request for the same messages, with
|
|
10053
|
-
* one more user message that asks for the summary. The model, system prompt,
|
|
10054
|
-
* tools, and reasoning stay the same, so the provider can read the cached
|
|
10055
|
-
* prompt prefix of the last agent call. Anthropic drops cached messages when
|
|
10056
|
-
* `tool_choice`, thinking, or effort change, so the request keeps the tools
|
|
10057
|
-
* and the instruction forbids tool calls instead.
|
|
10058
|
-
*/
|
|
10059
|
-
/** Prompt name of the summary request on its `gen_ai.chat` span. */
|
|
10060
|
-
const CONTEXT_COMPACTION_PROMPT_NAME = "junior.context_compaction";
|
|
10061
|
-
const SUMMARY_MAX_TOKENS = 8e3;
|
|
10062
|
-
const SUMMARY_TAG = "summary";
|
|
10063
|
-
const SUMMARY_TAGS = renderInlineTag(SUMMARY_TAG, "");
|
|
10064
|
-
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.
|
|
10065
|
-
|
|
10066
|
-
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.
|
|
10067
|
-
|
|
10068
|
-
## Goal
|
|
10069
|
-
## Constraints & preferences
|
|
10070
|
-
## Progress
|
|
10071
|
-
### Done
|
|
10072
|
-
### In progress
|
|
10073
|
-
### Blocked
|
|
10074
|
-
## Key decisions
|
|
10075
|
-
## Open asks
|
|
10076
|
-
User requests that are not complete yet, quoted in the user's exact words.
|
|
10077
|
-
## References
|
|
10078
|
-
Exact file paths, IDs, URLs, commands, and error text that the work needs. At most 20 items.
|
|
10079
|
-
## Next steps
|
|
10080
|
-
|
|
10081
|
-
Rules:
|
|
10082
|
-
- Keep the summary under 1,000 words.
|
|
10083
|
-
- Leave out the system prompt, AGENTS.md instructions, tool descriptions, and environment details. They are added again.
|
|
10084
|
-
- Do not mention this request or the summary itself.
|
|
10085
|
-
- 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.`;
|
|
10086
|
-
const SUMMARY_NUDGE = `Do not call tools. Keep the summary short. Return only the summary inside ${SUMMARY_TAGS} tags.`;
|
|
10087
|
-
/** Raised when the model returns no usable summary after one nudge. */
|
|
10088
|
-
var ContextSummaryError = class extends Error {
|
|
10089
|
-
failure;
|
|
10090
|
-
/** Estimated cost of the summary requests that did not succeed. */
|
|
10091
|
-
costUsd;
|
|
10092
|
-
constructor(failure, costUsd, options) {
|
|
10093
|
-
super(`Context summary failed: ${failure}`, options);
|
|
10094
|
-
this.failure = failure;
|
|
10095
|
-
this.name = "ContextSummaryError";
|
|
10096
|
-
if (costUsd !== void 0) this.costUsd = costUsd;
|
|
10097
|
-
}
|
|
10098
|
-
};
|
|
10099
|
-
/**
|
|
10100
|
-
* Build the model request that the agent loop sends for these messages.
|
|
10101
|
-
*
|
|
10102
|
-
* This repeats the steps of pi-agent-core before each model call
|
|
10103
|
-
* (`streamAssistantResponse` and `createLoopConfig`, which Pi does not
|
|
10104
|
-
* export): transform and convert the messages, then read the model,
|
|
10105
|
-
* reasoning, tools, and request options from the agent. A unit test compares
|
|
10106
|
-
* this request with the one that a real Pi `Agent` loop passes to `streamFn`,
|
|
10107
|
-
* so it fails when Pi changes these steps.
|
|
10108
|
-
*/
|
|
10109
|
-
async function buildAgentModelRequest(agent, messages, signal) {
|
|
10110
|
-
const { model, thinkingLevel, tools } = agent.state;
|
|
10111
|
-
const leading = getInitialSystemMessage(agent.state.messages);
|
|
10112
|
-
const transformed = agent.transformContext ? await agent.transformContext(messages, signal) : messages;
|
|
10113
|
-
return {
|
|
10114
|
-
model,
|
|
10115
|
-
context: {
|
|
10116
|
-
...foldLeadingSystemMessages(leading ? getSystemMessageText$1(leading) : "", await agent.convertToLlm(transformed)),
|
|
10117
|
-
tools
|
|
10118
|
-
},
|
|
10119
|
-
options: {
|
|
10120
|
-
reasoning: thinkingLevel === "off" ? void 0 : thinkingLevel,
|
|
10121
|
-
sessionId: agent.sessionId,
|
|
10122
|
-
onPayload: agent.onPayload,
|
|
10123
|
-
onResponse: agent.onResponse,
|
|
10124
|
-
transport: agent.transport,
|
|
10125
|
-
thinkingBudgets: agent.thinkingBudgets,
|
|
10126
|
-
maxRetryDelayMs: agent.maxRetryDelayMs,
|
|
10127
|
-
apiKey: await agent.getApiKey?.(model.provider) || void 0,
|
|
10128
|
-
identity: mergeClientIdentity(DEFAULT_AGENT_IDENTITY, agent.identity),
|
|
10129
|
-
signal
|
|
10130
|
-
}
|
|
10131
|
-
};
|
|
10132
|
-
}
|
|
10133
|
-
function userText(text) {
|
|
10134
|
-
return {
|
|
10135
|
-
role: "user",
|
|
10136
|
-
content: [{
|
|
10137
|
-
type: "text",
|
|
10138
|
-
text
|
|
10139
|
-
}],
|
|
10140
|
-
timestamp: Date.now()
|
|
10141
|
-
};
|
|
10142
|
-
}
|
|
10143
|
-
async function complete(request, streamFn, appended) {
|
|
10144
|
-
const message = await (await streamFn(request.model, {
|
|
10145
|
-
...request.context,
|
|
10146
|
-
messages: [...request.context.messages, ...appended]
|
|
10147
|
-
}, {
|
|
10148
|
-
...request.options,
|
|
10149
|
-
maxTokens: SUMMARY_MAX_TOKENS
|
|
10150
|
-
})).result();
|
|
10151
|
-
if (message.stopReason === "error" || message.stopReason === "aborted") throw createProviderError(message.errorMessage ?? message.stopReason, { modelId: request.model.id });
|
|
10152
|
-
return message;
|
|
10153
|
-
}
|
|
10154
|
-
/** Read the summary, or name why the output is not a usable summary. */
|
|
10155
|
-
function readSummary(message) {
|
|
10156
|
-
if (message.content.some((part) => part.type === "toolCall")) return { failure: "tool_call" };
|
|
10157
|
-
if (message.stopReason === "length") return { failure: "max_tokens" };
|
|
10158
|
-
const text = message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("").trim();
|
|
10159
|
-
if (!text) return { failure: "empty" };
|
|
10160
|
-
const summary = findTag(text, SUMMARY_TAG)?.body.trim();
|
|
10161
|
-
return summary ? { summary } : { failure: "missing_summary" };
|
|
10162
|
-
}
|
|
10163
|
-
/**
|
|
10164
|
-
* Ask the agent model for a summary of the request messages.
|
|
10165
|
-
*
|
|
10166
|
-
* A tool call, a stop at the output limit, empty output, or output without
|
|
10167
|
-
* `<summary>` tags gets one nudge. A second failure throws
|
|
10168
|
-
* `ContextSummaryError`, so the caller keeps the full history. The cost
|
|
10169
|
-
* covers each summary request, including a nudged one.
|
|
10170
|
-
*/
|
|
10171
|
-
async function requestContextSummary(request, streamFn) {
|
|
10172
|
-
const instruction = userText(SUMMARY_INSTRUCTION);
|
|
10173
|
-
const firstMessage = await complete(request, streamFn, [instruction]);
|
|
10174
|
-
const first = readSummary(firstMessage);
|
|
10175
|
-
if ("summary" in first) return withCost(first.summary, firstMessage);
|
|
10176
|
-
logWarn("context_compaction.summary.nudged", { "app.compaction.summary_failure": first.failure });
|
|
10177
|
-
let secondMessage;
|
|
10178
|
-
try {
|
|
10179
|
-
secondMessage = await complete(request, streamFn, [instruction, userText(SUMMARY_NUDGE)]);
|
|
10180
|
-
} catch (error) {
|
|
10181
|
-
throw new ContextSummaryError("request_failed", summaryCostUsd(firstMessage), { cause: error });
|
|
10182
|
-
}
|
|
10183
|
-
const second = readSummary(secondMessage);
|
|
10184
|
-
if ("summary" in second) return withCost(second.summary, firstMessage, secondMessage);
|
|
10185
|
-
throw new ContextSummaryError(second.failure, summaryCostUsd(firstMessage, secondMessage));
|
|
10186
|
-
}
|
|
10187
|
-
function summaryCostUsd(...messages) {
|
|
10188
|
-
return agentTurnCostUsd(extractGenAiUsageSummary(...messages));
|
|
10189
|
-
}
|
|
10190
|
-
function withCost(summary, ...messages) {
|
|
10191
|
-
const costUsd = summaryCostUsd(...messages);
|
|
10192
|
-
return costUsd === void 0 ? { summary } : {
|
|
10193
|
-
summary,
|
|
10194
|
-
costUsd
|
|
10195
|
-
};
|
|
10196
|
-
}
|
|
10197
|
-
// src/chat/services/context-compaction-telemetry.ts
|
|
10198
|
-
/**
|
|
10199
|
-
* Context compaction telemetry.
|
|
10200
|
-
*
|
|
10201
|
-
* Each compaction gets one `agent.context_compaction` span. The span and its
|
|
10202
|
-
* children, such as the summary `gen_ai.chat` span, carry
|
|
10203
|
-
* `app.compaction.mode`. The `chat.turn` span sums the time that the Turn
|
|
10204
|
-
* waited on compaction, with summary calls and prepared-summary swaps apart.
|
|
10205
|
-
*
|
|
10206
|
-
* Attribute keys do not contain "token": Sentry data scrubbing removes the
|
|
10207
|
-
* values of keys that match it.
|
|
10208
|
-
*/
|
|
10209
|
-
const turnCompactionWait = new AsyncLocalStorage();
|
|
10210
|
-
/** Run one compaction in its span and add its time to the Turn wait. */
|
|
10211
|
-
async function withCompactionSpan(mode, work, callback) {
|
|
10212
|
-
const startedAtMs = performance.now();
|
|
10213
|
-
try {
|
|
10214
|
-
return await runWithLogAttributes({ "app.compaction.mode": mode }, () => withSpan("agent.context_compaction", "agent.context_compaction", {}, callback));
|
|
10215
|
-
} finally {
|
|
10216
|
-
const wait = turnCompactionWait.getStore();
|
|
10217
|
-
if (wait) wait[work] += performance.now() - startedAtMs;
|
|
10218
|
-
}
|
|
10219
|
-
}
|
|
10220
|
-
/** Run one `chat.turn` callback and record its compaction wait, if any. */
|
|
10221
|
-
async function measureTurnCompactionWait(setTurnAttributes, callback) {
|
|
10222
|
-
const wait = {
|
|
10223
|
-
summary: 0,
|
|
10224
|
-
swap: 0
|
|
10225
|
-
};
|
|
10226
|
-
try {
|
|
10227
|
-
return await turnCompactionWait.run(wait, callback);
|
|
10228
|
-
} finally {
|
|
10229
|
-
setTurnAttributes({
|
|
10230
|
-
...wait.summary > 0 ? { "app.turn.compaction_wait_ms": Math.round(wait.summary) } : void 0,
|
|
10231
|
-
...wait.swap > 0 ? { "app.turn.compaction_swap_wait_ms": Math.round(wait.swap) } : void 0
|
|
10232
|
-
});
|
|
10233
|
-
}
|
|
10234
|
-
}
|
|
10235
|
-
/**
|
|
10236
|
-
* Track the replacement that waits for the provider-reported input of the
|
|
10237
|
-
* next model request. That request's `gen_ai.chat` span shows whether the
|
|
10238
|
-
* replacement got the history below the threshold. Production drops info
|
|
10239
|
-
* logs, so this is a span attribute.
|
|
10240
|
-
*/
|
|
10241
|
-
function createNextInputTracker() {
|
|
10242
|
-
let pending;
|
|
10243
|
-
return {
|
|
10244
|
-
replaced(mode, threshold) {
|
|
10245
|
-
pending = {
|
|
10246
|
-
mode,
|
|
10247
|
-
threshold
|
|
10248
|
-
};
|
|
10249
|
-
},
|
|
10250
|
-
attributes(inputSize) {
|
|
10251
|
-
if (!pending || !inputSize) return;
|
|
10252
|
-
const { mode, threshold } = pending;
|
|
10253
|
-
pending = void 0;
|
|
10254
|
-
return {
|
|
10255
|
-
"app.compaction.mode": mode,
|
|
10256
|
-
"app.compaction.next_input.size": inputSize,
|
|
10257
|
-
"app.compaction.next_input.over_threshold": inputSize > threshold,
|
|
10258
|
-
"app.compaction.threshold": threshold
|
|
10259
|
-
};
|
|
10260
|
-
}
|
|
10261
|
-
};
|
|
10262
|
-
}
|
|
10263
|
-
// src/chat/services/background-compaction.ts
|
|
10264
|
-
/**
|
|
10265
|
-
* Background compaction: prepare a summary before the history is full.
|
|
10266
|
-
*
|
|
10267
|
-
* After each model request at or above the mark, also in the middle of a
|
|
10268
|
-
* Turn, the Turn appends `compaction_requested` and sends a job. The job
|
|
10269
|
-
* asks the agent model for a summary of the history up to the marked event
|
|
10270
|
-
* and appends `compaction_prepared`. Turns keep the full history until a later
|
|
10271
|
-
* change swaps the summary in. Blocking compaction stays the fallback.
|
|
10272
|
-
*
|
|
10273
|
-
* The summary request repeats the system prompt and tools of the last agent
|
|
10274
|
-
* request, so the provider can read its cached prompt prefix. The job runs in
|
|
10275
|
-
* another request, so the Turn stores them in the State adapter.
|
|
10276
|
-
*/
|
|
10277
|
-
/**
|
|
10278
|
-
* Failed attempts for one History version before background tries stop.
|
|
10279
|
-
*/
|
|
10280
|
-
const MAX_FAILED_ATTEMPTS = 2;
|
|
10281
|
-
/**
|
|
10282
|
-
* A request without a prepared result after this long counts as a failed
|
|
10283
|
-
* attempt, so a later Turn can request again. This covers a lost job.
|
|
10284
|
-
*/
|
|
10285
|
-
const REQUEST_TIMEOUT_MS = 6e5;
|
|
10286
|
-
/** The queue drops a message after this long, so the snapshot can go too. */
|
|
10287
|
-
const SNAPSHOT_TTL_MS = QUEUE_SIGNATURE_MAX_AGE_MS;
|
|
10288
|
-
function snapshotKey(message) {
|
|
10289
|
-
return `${backgroundCompactionId(message)}:snapshot`;
|
|
10290
|
-
}
|
|
10291
|
-
/** Provider-reported input of the last model request, cache included. */
|
|
10292
|
-
function lastRequestInputSize(messages) {
|
|
10293
|
-
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
10294
|
-
const message = messages[index];
|
|
10295
|
-
if (message.role === "assistant") {
|
|
10296
|
-
const { input, cacheRead, cacheWrite } = message.usage;
|
|
10297
|
-
return input + cacheRead + cacheWrite;
|
|
10298
|
-
}
|
|
10299
|
-
}
|
|
10300
|
-
}
|
|
10301
|
-
/**
|
|
10302
|
-
* Return whether a Turn may request a background summary for this History
|
|
10303
|
-
* version. It may not while a request is pending, while a ready summary
|
|
10304
|
-
* waits for the compaction threshold, or after the attempt limit.
|
|
10305
|
-
*/
|
|
10306
|
-
function mayRequest(events, historyVersion, nowMs) {
|
|
10307
|
-
const outcomes = /* @__PURE__ */ new Map();
|
|
10308
|
-
for (const event of events) if (event.data.type === "compaction_prepared" && event.data.historyVersion === historyVersion) outcomes.set(event.data.markSeq, event.data.outcome);
|
|
10309
|
-
let failed = 0;
|
|
10310
|
-
for (const event of events) {
|
|
10311
|
-
if (event.data.type !== "compaction_requested" || event.data.historyVersion !== historyVersion) continue;
|
|
10312
|
-
const prepared = outcomes.get(event.data.markSeq);
|
|
10313
|
-
if (prepared === "ready") return false;
|
|
10314
|
-
if (prepared || nowMs - event.createdAtMs >= REQUEST_TIMEOUT_MS) failed += 1;
|
|
10315
|
-
else return false;
|
|
10316
|
-
}
|
|
10317
|
-
return failed < MAX_FAILED_ATTEMPTS;
|
|
10318
|
-
}
|
|
10319
|
-
/**
|
|
10320
|
-
* Find the newest background compaction fact of the current History version.
|
|
10321
|
-
* Facts of earlier versions belong to history that a replacement already
|
|
10322
|
-
* removed.
|
|
10323
|
-
*/
|
|
10324
|
-
async function loadLatestBackgroundCompaction(conversationId) {
|
|
10325
|
-
const store = getConversationEventStore();
|
|
10326
|
-
const [historyVersion, page] = await Promise.all([store.loadCurrentHistoryVersion(conversationId), store.query(conversationId, {
|
|
10327
|
-
limit: 1,
|
|
10328
|
-
types: ["compaction_requested", "compaction_prepared"]
|
|
10329
|
-
})]);
|
|
10330
|
-
const event = page.events.at(-1);
|
|
10331
|
-
return event && event.historyVersion === historyVersion ? {
|
|
10332
|
-
event,
|
|
10333
|
-
historyVersion
|
|
10334
|
-
} : void 0;
|
|
10335
|
-
}
|
|
10336
|
-
/**
|
|
10337
|
-
* Return whether the newest fact is a pending request or a ready summary.
|
|
10338
|
-
* Then `mayRequest` is false too, so a Turn can skip the other reads.
|
|
10339
|
-
* Only one request is pending at a time, so the newest fact decides it.
|
|
10340
|
-
*/
|
|
10341
|
-
function waitsForUse(event, nowMs) {
|
|
10342
|
-
if (event.data.type === "compaction_requested") return nowMs - event.createdAtMs < REQUEST_TIMEOUT_MS;
|
|
10343
|
-
return event.data.type === "compaction_prepared" && event.data.outcome === "ready";
|
|
10344
|
-
}
|
|
10345
|
-
/**
|
|
10346
|
-
* Request a background summary when the model request that just ended was at
|
|
10347
|
-
* or above the mark.
|
|
10348
|
-
*
|
|
10349
|
-
* The agent runs it after each model request, so a long Turn gets a summary
|
|
10350
|
-
* before the compaction threshold. Without a queue or below the mark, it does
|
|
10351
|
-
* nothing. A failure here leaves blocking compaction as the fallback, so it
|
|
10352
|
-
* is logged and does not fail the Turn. When the send fails after the request
|
|
10353
|
-
* is written, the request times out and counts as a failed attempt.
|
|
10354
|
-
*/
|
|
10355
|
-
async function requestBackgroundCompaction(args) {
|
|
10356
|
-
if (!args.queue) return;
|
|
10357
|
-
const inputSize = lastRequestInputSize(readAgentHistory(args.agent.state.messages));
|
|
10358
|
-
if (inputSize === void 0 || inputSize < getAgentBackgroundCompactionMarkTokens(args.modelId)) return;
|
|
10359
|
-
try {
|
|
10360
|
-
await requestAboveMark({
|
|
10361
|
-
...args,
|
|
10362
|
-
inputSize,
|
|
10363
|
-
queue: args.queue
|
|
10364
|
-
});
|
|
10365
|
-
} catch (error) {
|
|
10366
|
-
logWarn("context_compaction.background.request_failed", { "error.type": error instanceof Error ? error.name : typeof error });
|
|
10367
|
-
}
|
|
10368
|
-
}
|
|
10369
|
-
async function requestAboveMark(args) {
|
|
10370
|
-
const nowMs = Date.now();
|
|
10371
|
-
const eventStore = getConversationEventStore();
|
|
10372
|
-
const latest = await loadLatestBackgroundCompaction(args.conversationId);
|
|
10373
|
-
if (latest) {
|
|
10374
|
-
if (waitsForUse(latest.event, nowMs)) return;
|
|
10375
|
-
if (!mayRequest((await Promise.all([eventStore.loadEventsOfType(args.conversationId, "compaction_requested"), eventStore.loadEventsOfType(args.conversationId, "compaction_prepared")])).flat(), latest.historyVersion, nowMs)) return;
|
|
10376
|
-
}
|
|
10377
|
-
const events = await eventStore.loadCurrentHistory(args.conversationId);
|
|
10378
|
-
const historyVersion = events[0]?.historyVersion;
|
|
10379
|
-
if (historyVersion === void 0 || !mayRequest(events, historyVersion, nowMs)) return;
|
|
10380
|
-
const projection = projectConversationEvents(events);
|
|
10381
|
-
const markSeq = Math.max(projection.seqs.at(-1) ?? -1, projection.replacementSeq ?? -1);
|
|
10382
|
-
if (markSeq < 0) return;
|
|
10383
|
-
const message = {
|
|
10384
|
-
conversationId: args.conversationId,
|
|
10385
|
-
historyVersion,
|
|
10386
|
-
markSeq
|
|
10387
|
-
};
|
|
10388
|
-
const { messages, thinkingLevel, tools } = args.agent.state;
|
|
10389
|
-
const leading = getInitialSystemMessage(messages);
|
|
10390
|
-
const snapshot = {
|
|
10391
|
-
conversationPrivacy: args.conversationPrivacy ?? "private",
|
|
10392
|
-
inputSize: args.inputSize,
|
|
10393
|
-
modelId: args.modelId,
|
|
10394
|
-
systemPrompt: leading ? getSystemMessageText$1(leading) : "",
|
|
10395
|
-
thinkingLevel,
|
|
10396
|
-
tools: tools.map((tool) => ({
|
|
10397
|
-
name: tool.name,
|
|
10398
|
-
label: tool.label,
|
|
10399
|
-
description: tool.description,
|
|
10400
|
-
parameters: tool.parameters,
|
|
10401
|
-
...tool.constrainedSampling === void 0 ? void 0 : { constrainedSampling: tool.constrainedSampling }
|
|
10402
|
-
}))
|
|
10403
|
-
};
|
|
10404
|
-
await getStateAdapter().set(snapshotKey(message), JSON.parse(JSON.stringify(snapshot)), SNAPSHOT_TTL_MS);
|
|
10405
|
-
if ((await eventStore.append(args.conversationId, [{
|
|
10406
|
-
idempotencyKey: `${backgroundCompactionId(message)}:requested`,
|
|
10407
|
-
createdAtMs: nowMs,
|
|
10408
|
-
data: {
|
|
10409
|
-
type: "compaction_requested",
|
|
10410
|
-
markSeq,
|
|
10411
|
-
historyVersion,
|
|
10412
|
-
modelId: args.modelId
|
|
10413
|
-
}
|
|
10414
|
-
}], { activity: "preserve" })).length === 0) return;
|
|
10415
|
-
await args.queue.send(message);
|
|
10416
|
-
}
|
|
10417
|
-
/** A fixed label for a failed summary. Never raw exception text. */
|
|
10418
|
-
function failureLabel(error, signal) {
|
|
10419
|
-
if (signal.aborted) return "timeout";
|
|
10420
|
-
if (error instanceof ContextSummaryError && error.failure !== "request_failed") return error.failure;
|
|
10421
|
-
const providerError = findProviderError(error);
|
|
10422
|
-
return providerError ? `provider_${providerError.kind}` : "summary_error";
|
|
10423
|
-
}
|
|
10424
|
-
/**
|
|
10425
|
-
* Run one background compaction job.
|
|
10426
|
-
*
|
|
10427
|
-
* It writes `compaction_prepared` once for the request, with a summary or a
|
|
10428
|
-
* fixed failure label. It writes nothing when the request is no longer in
|
|
10429
|
-
* the current History version, because no Turn could use the summary.
|
|
10430
|
-
* `streamFn` replaces the model stream, for tests.
|
|
10431
|
-
*/
|
|
10432
|
-
async function processBackgroundCompaction(message, options = {}) {
|
|
10433
|
-
const startedAtMs = Date.now();
|
|
10434
|
-
await withLogContext({ conversationId: message.conversationId }, () => withCompactionSpan("background", "summary", async () => {
|
|
10435
|
-
setSpanAttributes({
|
|
10436
|
-
"app.compaction.mark_seq": message.markSeq,
|
|
10437
|
-
"app.compaction.history_version": message.historyVersion,
|
|
10438
|
-
...options.enqueuedAtMs === void 0 ? void 0 : { "app.compaction.queue_wait_ms": Math.max(0, startedAtMs - options.enqueuedAtMs) }
|
|
10439
|
-
});
|
|
10440
|
-
const outcome = await prepareSummary(message, options.streamFn);
|
|
10441
|
-
setSpanAttributes({ "app.compaction.outcome": outcome });
|
|
10442
|
-
}));
|
|
10443
|
-
}
|
|
10444
|
-
async function prepareSummary(message, streamFn) {
|
|
10445
|
-
const eventStore = getConversationEventStore();
|
|
10446
|
-
const state = getStateAdapter();
|
|
10447
|
-
const events = await eventStore.loadCurrentHistory(message.conversationId);
|
|
10448
|
-
const isThisRequest = (event) => (event.data.type === "compaction_requested" || event.data.type === "compaction_prepared") && event.data.historyVersion === message.historyVersion && event.data.markSeq === message.markSeq;
|
|
10449
|
-
const request = events.find((event) => isThisRequest(event) && event.data.type === "compaction_requested");
|
|
10450
|
-
if (request?.data.type !== "compaction_requested") {
|
|
10451
|
-
await state.delete(snapshotKey(message));
|
|
10452
|
-
return "stale";
|
|
10453
|
-
}
|
|
10454
|
-
const requested = request.data;
|
|
10455
|
-
if (events.some((event) => isThisRequest(event) && event.data.type === "compaction_prepared")) return "duplicate";
|
|
10456
|
-
const writePrepared = async (result) => {
|
|
10457
|
-
if (await eventStore.loadCurrentHistoryVersion(message.conversationId) !== message.historyVersion) {
|
|
10458
|
-
await state.delete(snapshotKey(message));
|
|
10459
|
-
return "stale";
|
|
10460
|
-
}
|
|
10461
|
-
await eventStore.append(message.conversationId, [{
|
|
10462
|
-
idempotencyKey: `${backgroundCompactionId(message)}:prepared`,
|
|
10463
|
-
createdAtMs: Date.now(),
|
|
10464
|
-
data: {
|
|
10465
|
-
type: "compaction_prepared",
|
|
10466
|
-
markSeq: message.markSeq,
|
|
10467
|
-
historyVersion: message.historyVersion,
|
|
10468
|
-
modelId: requested.modelId,
|
|
10469
|
-
...result
|
|
10470
|
-
}
|
|
10471
|
-
}], { activity: "preserve" });
|
|
10472
|
-
await state.delete(snapshotKey(message));
|
|
10473
|
-
if (result.outcome === "failed") setSpanAttributes({ "error.type": result.errorType });
|
|
10474
|
-
return result.outcome;
|
|
10475
|
-
};
|
|
10476
|
-
const remainingMs = request.createdAtMs + REQUEST_TIMEOUT_MS - Date.now();
|
|
10477
|
-
if (remainingMs <= 0) return await writePrepared({
|
|
10478
|
-
outcome: "failed",
|
|
10479
|
-
errorType: "timeout"
|
|
10480
|
-
});
|
|
10481
|
-
const snapshot = await state.get(snapshotKey(message));
|
|
10482
|
-
if (!snapshot) return await writePrepared({
|
|
10483
|
-
outcome: "failed",
|
|
10484
|
-
errorType: "snapshot_missing"
|
|
10485
|
-
});
|
|
10486
|
-
setSpanAttributes({ "app.compaction.input.size": snapshot.inputSize });
|
|
10487
|
-
const projection = projectConversationEvents(events, { maxSeq: message.markSeq });
|
|
10488
|
-
const signal = AbortSignal.timeout(remainingMs);
|
|
10489
|
-
let summary;
|
|
10490
|
-
try {
|
|
10491
|
-
summary = await runWithConversationPrivacy(snapshot.conversationPrivacy, async () => {
|
|
10492
|
-
const summaryStreamFn = createTracedStreamFn({
|
|
10493
|
-
conversationPrivacy: snapshot.conversationPrivacy,
|
|
10494
|
-
promptName: CONTEXT_COMPACTION_PROMPT_NAME,
|
|
10495
|
-
...streamFn ? { base: streamFn } : void 0
|
|
10496
|
-
});
|
|
10497
|
-
const tools = snapshot.tools.map((tool) => ({
|
|
10498
|
-
...tool,
|
|
10499
|
-
execute: async () => {
|
|
10500
|
-
throw new Error("Background compaction does not run tools");
|
|
10501
|
-
}
|
|
10502
|
-
}));
|
|
10503
|
-
return await requestContextSummary(await buildAgentModelRequest(new Agent({
|
|
10504
|
-
getApiKey: getGatewayApiKey,
|
|
10505
|
-
sessionId: message.conversationId,
|
|
10506
|
-
streamFn: withAgentRequest(summaryStreamFn, {
|
|
10507
|
-
systemPrompt: snapshot.systemPrompt,
|
|
10508
|
-
tools
|
|
10509
|
-
}),
|
|
10510
|
-
initialState: {
|
|
10511
|
-
systemPrompt: snapshot.systemPrompt,
|
|
10512
|
-
model: resolveGatewayModel(snapshot.modelId),
|
|
10513
|
-
thinkingLevel: snapshot.thinkingLevel,
|
|
10514
|
-
tools
|
|
10515
|
-
}
|
|
10516
|
-
}), projection.messages, signal), summaryStreamFn);
|
|
10517
|
-
});
|
|
10518
|
-
} catch (error) {
|
|
10519
|
-
return await writePrepared({
|
|
10520
|
-
outcome: "failed",
|
|
10521
|
-
errorType: failureLabel(error, signal),
|
|
10522
|
-
...error instanceof ContextSummaryError && error.costUsd !== void 0 ? { costUsd: error.costUsd } : void 0
|
|
10523
|
-
});
|
|
10524
|
-
}
|
|
10525
|
-
const outcome = await writePrepared({
|
|
10526
|
-
outcome: "ready",
|
|
10527
|
-
...summary
|
|
10528
|
-
});
|
|
10529
|
-
if (outcome === "ready") setSpanAttributes({
|
|
10530
|
-
"app.compaction.summary_chars": summary.summary.length,
|
|
10531
|
-
"app.compaction.ready_ms": Date.now() - request.createdAtMs
|
|
10532
|
-
});
|
|
10533
|
-
return outcome;
|
|
10534
|
-
}
|
|
10535
|
-
// src/chat/plan/snapshot.ts
|
|
10536
|
-
/**
|
|
10537
|
-
* Append one `<plan>` snapshot of the open items, read from the database, to
|
|
10538
|
-
* a compaction summary, so the plan and its version survive the history
|
|
10539
|
-
* replacement.
|
|
10540
|
-
*/
|
|
10541
|
-
async function appendPlanSnapshot(summaryText, conversationId) {
|
|
10542
|
-
const snapshot = renderPlanSnapshot(await listPlanItems(getSqlExecutor(), conversationId));
|
|
10543
|
-
return snapshot ? `${summaryText}\n\n${snapshot}` : summaryText;
|
|
10544
|
-
}
|
|
10545
|
-
// src/chat/services/context-compaction.ts
|
|
10546
|
-
/**
|
|
10547
|
-
* Context compaction.
|
|
10548
|
-
*
|
|
10549
|
-
* Bounds Pi history for long conversations and commits a history
|
|
10550
|
-
* replacement. Capacity compaction gets its summary from the caller, which
|
|
10551
|
-
* asks the agent model with the cached request prefix. Mid-turn replacements
|
|
10552
|
-
* keep the authored instruction before the summary. Turn-start replacements keep recent user
|
|
10553
|
-
* messages, the summary, then the new instruction. Checkpoints can append
|
|
10554
|
-
* fresh runtime context; the next replacement removes it again.
|
|
10555
|
-
*/
|
|
10556
|
-
const RETAINED_USER_MESSAGE_TOKENS = 2e4;
|
|
10557
|
-
/** Raised when Junior cannot compact history below the active model's hard ceiling. */
|
|
10558
|
-
var ContextInputLimitExceededError = class extends Error {
|
|
10559
|
-
estimatedTokens;
|
|
10560
|
-
inputLimitTokens;
|
|
10561
|
-
constructor(estimatedTokens, inputLimitTokens) {
|
|
10562
|
-
super(`Agent context is ${estimatedTokens} estimated input tokens, above the ${inputLimitTokens} token limit`);
|
|
10563
|
-
this.estimatedTokens = estimatedTokens;
|
|
10564
|
-
this.inputLimitTokens = inputLimitTokens;
|
|
10565
|
-
this.name = "ContextInputLimitExceededError";
|
|
10566
|
-
}
|
|
10567
|
-
};
|
|
10568
|
-
function textPart(value) {
|
|
10569
|
-
if (value && typeof value === "object" && value.type === "text" && typeof value.text === "string") return value.text;
|
|
10570
|
-
}
|
|
10571
|
-
/** Render Pi message text for retained user-message selection. */
|
|
10572
|
-
function messageText(message) {
|
|
10573
|
-
const content = message.content;
|
|
10574
|
-
const unwrapTask = message.role === "user";
|
|
10575
|
-
const displayText = (text) => unwrapTask ? unwrapCurrentInstruction(text) ?? text : text;
|
|
10576
|
-
if (!Array.isArray(content)) return typeof content === "string" ? displayText(content) : "";
|
|
10577
|
-
return content.map(textPart).filter((text) => Boolean(text)).map(displayText).join("\n").trim();
|
|
10578
|
-
}
|
|
10579
|
-
function sanitizeText(text) {
|
|
10580
|
-
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();
|
|
10581
|
-
}
|
|
10582
|
-
function truncateToTokenBudget(text, maxTokens) {
|
|
10583
|
-
const maxChars = Math.max(0, textCharsForTokens(maxTokens));
|
|
10584
|
-
if (text.length <= maxChars) return text;
|
|
10585
|
-
return `${text.slice(0, Math.max(0, maxChars - 3)).trimEnd()}...`;
|
|
10586
|
-
}
|
|
10587
|
-
function isCompactionSummary(text) {
|
|
10588
|
-
return isCompactionSummaryText(text);
|
|
10589
|
-
}
|
|
10590
|
-
function isPayloadHeavy(text) {
|
|
10591
|
-
return /<data_base64>[\s\S]*?<\/data_base64>|data:image\/[a-z0-9.+-]+;base64,/i.test(text);
|
|
10592
|
-
}
|
|
10593
|
-
/** Build a text-only user message for a replacement history. */
|
|
10594
|
-
function userMessage(text) {
|
|
10595
|
-
return {
|
|
10596
|
-
role: "user",
|
|
10597
|
-
content: [{
|
|
10598
|
-
type: "text",
|
|
10599
|
-
text
|
|
10600
|
-
}],
|
|
10601
|
-
timestamp: Date.now()
|
|
10602
|
-
};
|
|
10603
|
-
}
|
|
10604
|
-
function userMessageContent(message) {
|
|
10605
|
-
const content = message.content;
|
|
10606
|
-
return Array.isArray(content) ? content : [];
|
|
10607
|
-
}
|
|
10608
|
-
function hasTurnBootstrap(message) {
|
|
10609
|
-
return userMessageContent(message).some((part) => isTurnContextText(textPart(part)));
|
|
10610
|
-
}
|
|
10611
|
-
function isSessionTurnContext(text) {
|
|
10612
|
-
return isTurnContextText(text) && findTag(text, "runtime") !== void 0;
|
|
10613
|
-
}
|
|
10614
|
-
function isTurnContextText(text) {
|
|
10615
|
-
return text !== void 0 && startsWithTag(text, ["runtime-turn-context"]);
|
|
10616
|
-
}
|
|
10617
|
-
/**
|
|
10618
|
-
* Remove the sections that only the Turn that received them can use, and
|
|
10619
|
-
* plan deltas, which the `<plan>` snapshot of the summary replaces.
|
|
10620
|
-
*/
|
|
10621
|
-
function withoutRequestContext(text) {
|
|
10622
|
-
return stripTags(text, [...Object.values(REQUEST_CONTEXT_SECTION_TAG), PLAN_DELTA_TAG]);
|
|
10623
|
-
}
|
|
10624
|
-
/**
|
|
10625
|
-
* Remove the copies of capability sections that the Turn context of older
|
|
10626
|
-
* Turns held. Later system messages hold them now, and compaction folds
|
|
10627
|
-
* those.
|
|
10628
|
-
*/
|
|
10629
|
-
function withoutCapabilitySections(content) {
|
|
10630
|
-
return content.map((part) => {
|
|
10631
|
-
const text = textPart(part);
|
|
10632
|
-
return isTurnContextText(text) ? {
|
|
10633
|
-
...part,
|
|
10634
|
-
text: stripTags(text, Object.values(CAPABILITY_SECTION_TAG))
|
|
10635
|
-
} : part;
|
|
10636
|
-
});
|
|
10637
|
-
}
|
|
10638
|
-
/** Find the latest session context and keep only its session sections. */
|
|
10639
|
-
function latestSessionContext(messages) {
|
|
10640
|
-
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
10641
|
-
const message = messages[index];
|
|
10642
|
-
const text = userMessageContent(message).map(textPart).find(isSessionTurnContext);
|
|
10643
|
-
if (text) return {
|
|
10644
|
-
...message,
|
|
10645
|
-
content: [{
|
|
10646
|
-
type: "text",
|
|
10647
|
-
text: withoutRequestContext(text)
|
|
10648
|
-
}]
|
|
10649
|
-
};
|
|
10650
|
-
}
|
|
10651
|
-
}
|
|
10652
|
-
function effectiveRuntimeContext(messages) {
|
|
10653
|
-
let latestBootstrapIndex = -1;
|
|
10654
|
-
for (let index = messages.length - 1; index >= 0; index -= 1) if (hasTurnBootstrap(messages[index])) {
|
|
10655
|
-
latestBootstrapIndex = index;
|
|
10656
|
-
break;
|
|
10657
|
-
}
|
|
10658
|
-
const effectiveMessages = latestBootstrapIndex < 0 ? messages : messages.slice(latestBootstrapIndex);
|
|
10659
|
-
return runtimeContextContent(effectiveMessages, effectiveMessages);
|
|
10660
|
-
}
|
|
10661
|
-
function runtimeContextContent(messages, agentsMessages) {
|
|
10662
|
-
const allContent = messages.flatMap(userMessageContent);
|
|
10663
|
-
const firstAgentsIndex = allContent.findIndex((part) => textPart(part)?.startsWith("# AGENTS.md instructions") === true);
|
|
10664
|
-
const content = withoutCapabilitySections(allContent.filter((part) => textPart(part)?.startsWith("# AGENTS.md instructions") !== true));
|
|
10665
|
-
const visibleAgents = findVisibleAgentsInstructions(agentsMessages);
|
|
10666
|
-
if (visibleAgents?.active === true) {
|
|
10667
|
-
const insertionIndex = firstAgentsIndex < 0 ? content.length : Math.min(firstAgentsIndex, content.length);
|
|
10668
|
-
content.splice(insertionIndex, 0, {
|
|
10669
|
-
type: "text",
|
|
10670
|
-
text: renderAgentsInstructions({
|
|
10671
|
-
directory: visibleAgents.directory,
|
|
10672
|
-
text: visibleAgents.text
|
|
10673
|
-
})
|
|
10674
|
-
});
|
|
10675
|
-
}
|
|
10676
|
-
const latestTimestamp = messages.at(-1)?.timestamp;
|
|
10677
|
-
return {
|
|
10678
|
-
content,
|
|
10679
|
-
timestamp: typeof latestTimestamp === "number" ? latestTimestamp : Date.now()
|
|
10680
|
-
};
|
|
10681
|
-
}
|
|
10682
|
-
function toRuntimeContextMessage(runtimeContext, timestamp) {
|
|
10683
|
-
if (runtimeContext.content.length === 0) return;
|
|
10684
|
-
return {
|
|
10685
|
-
role: "user",
|
|
10686
|
-
content: runtimeContext.content,
|
|
10687
|
-
timestamp: timestamp ?? runtimeContext.timestamp
|
|
10688
|
-
};
|
|
10689
|
-
}
|
|
10690
|
-
function runtimeContextMessage(messages, timestamp) {
|
|
10691
|
-
return toRuntimeContextMessage(effectiveRuntimeContext(messages), timestamp);
|
|
10692
|
-
}
|
|
10693
|
-
/**
|
|
10694
|
-
* Build the runtime context that the current Turn can use after an in-turn
|
|
10695
|
-
* replacement.
|
|
10696
|
-
*
|
|
10697
|
-
* Request context, such as plugin context and disabled tools, is true only for
|
|
10698
|
-
* the Turn that received it. From earlier Turns, keep only the latest session
|
|
10699
|
-
* context and AGENTS.md instructions.
|
|
10700
|
-
*/
|
|
10701
|
-
function turnRuntimeContextMessage(messages, turnStartMessageIndex, timestamp) {
|
|
10702
|
-
if (turnStartMessageIndex === void 0) return runtimeContextMessage(retainRuntimeTurnContext(messages), timestamp);
|
|
10703
|
-
const earlierContext = retainRuntimeTurnContext(messages.slice(0, turnStartMessageIndex));
|
|
10704
|
-
const turnContext = retainRuntimeTurnContext(messages.slice(turnStartMessageIndex));
|
|
10705
|
-
const sessionContext = turnContext.some((message) => userMessageContent(message).map(textPart).some(isSessionTurnContext)) ? void 0 : latestSessionContext(earlierContext);
|
|
10706
|
-
return toRuntimeContextMessage(runtimeContextContent(sessionContext ? [sessionContext, ...turnContext] : turnContext, [...earlierContext, ...turnContext]), timestamp);
|
|
10707
|
-
}
|
|
10708
|
-
/**
|
|
10709
|
-
* Build the runtime context of summarized history that the kept history
|
|
10710
|
-
* does not carry: the latest session context and the AGENTS.md instructions.
|
|
10711
|
-
* Request context of earlier Turns is left out.
|
|
10712
|
-
*/
|
|
10713
|
-
function summarizedRuntimeContextMessage(summarized, kept) {
|
|
10714
|
-
const earlierContext = retainRuntimeTurnContext(summarized);
|
|
10715
|
-
const sessionContext = retainRuntimeTurnContext(kept).some((message) => userMessageContent(message).map(textPart).some(isSessionTurnContext)) ? void 0 : latestSessionContext(earlierContext);
|
|
10716
|
-
return toRuntimeContextMessage(runtimeContextContent(sessionContext ? [sessionContext] : [], findVisibleAgentsInstructions(kept) ? [] : earlierContext));
|
|
10717
|
-
}
|
|
10718
|
-
/**
|
|
10719
|
-
* Build retained user messages for a compacted Pi replacement history. Each
|
|
10720
|
-
* entry keeps the index of its source message.
|
|
10721
|
-
*/
|
|
10722
|
-
function selectRetainedUserMessageEntries(messages, maxTokens = RETAINED_USER_MESSAGE_TOKENS) {
|
|
10723
|
-
const selected = [];
|
|
10724
|
-
let remaining = maxTokens;
|
|
10725
|
-
for (let sourceIndex = messages.length - 1; sourceIndex >= 0; sourceIndex -= 1) {
|
|
10726
|
-
if (isStandaloneRuntimeContextMessage(messages, sourceIndex)) continue;
|
|
10727
|
-
const message = stripRuntimeTurnContext([messages[sourceIndex]])[0];
|
|
10728
|
-
if (!message || message.role !== "user" || remaining <= 0) continue;
|
|
10729
|
-
const text = sanitizeText(messageText(message));
|
|
10730
|
-
if (!text || isCompactionSummary(text) || isPayloadHeavy(text)) continue;
|
|
10731
|
-
const tokens = estimateTextTokens(text);
|
|
10732
|
-
if (tokens <= remaining) {
|
|
10733
|
-
selected.push({
|
|
10734
|
-
message: userMessage(text),
|
|
10735
|
-
sourceIndex
|
|
10736
|
-
});
|
|
10737
|
-
remaining -= tokens;
|
|
10738
|
-
continue;
|
|
10739
|
-
}
|
|
10740
|
-
const truncated = truncateToTokenBudget(text, remaining);
|
|
10741
|
-
if (truncated) selected.push({
|
|
10742
|
-
message: userMessage(truncated),
|
|
10743
|
-
sourceIndex
|
|
10744
|
-
});
|
|
10745
|
-
break;
|
|
10746
|
-
}
|
|
10747
|
-
return selected.reverse();
|
|
10748
|
-
}
|
|
10749
|
-
/** Match a message across a durable commit, which can reorder JSON keys. */
|
|
10750
|
-
function retainedMessageKey(message) {
|
|
10751
|
-
const { role, timestamp } = message;
|
|
10752
|
-
return `${String(role)}:${String(timestamp)}:${messageText(message)}`;
|
|
10753
|
-
}
|
|
10754
|
-
/**
|
|
10755
|
-
* Load recent user messages from committed history. Each one keeps its
|
|
10756
|
-
* original author and source event.
|
|
10757
|
-
*/
|
|
10758
|
-
async function loadRetainedUserMessages(conversationId, pendingMessages) {
|
|
10759
|
-
const projection = await loadConversationProjection({ conversationId });
|
|
10760
|
-
const pendingKeys = new Set(pendingMessages.map(retainedMessageKey));
|
|
10761
|
-
let pendingStart = projection.messages.findIndex((message) => pendingKeys.has(retainedMessageKey(message)));
|
|
10762
|
-
if (pendingStart > 0 && isStandaloneRuntimeContextMessage(projection.messages, pendingStart - 1)) pendingStart -= 1;
|
|
10763
|
-
const history = pendingStart === -1 ? projection.messages : projection.messages.slice(0, pendingStart);
|
|
10764
|
-
return selectRetainedUserMessageEntries(trimTrailingAssistantMessages(history)).map((entry) => {
|
|
10765
|
-
const provenance = projection.provenance[entry.sourceIndex];
|
|
10766
|
-
if (!provenance) throw new Error("retained message provenance is missing");
|
|
10767
|
-
return {
|
|
10768
|
-
message: entry.message,
|
|
10769
|
-
provenance,
|
|
10770
|
-
sourceEventSeq: projection.seqs[entry.sourceIndex]
|
|
10771
|
-
};
|
|
10772
|
-
});
|
|
10773
|
-
}
|
|
10774
|
-
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.";
|
|
10775
|
-
/**
|
|
10776
|
-
* Keep generated text inside the existing evidence-only prompt boundary. The
|
|
10777
|
-
* last line says where replaced detail stays readable: without it, the model
|
|
10778
|
-
* often decides a detail from a compacted tool result is gone, and asks the
|
|
10779
|
-
* person for it.
|
|
10780
|
-
*/
|
|
10781
|
-
function renderCompactionSummary(summary) {
|
|
10782
|
-
return [
|
|
10783
|
-
COMPACTION_SUMMARY_PREFIX,
|
|
10784
|
-
renderThreadContext([escapeTagTextAndQuotes(summary)]),
|
|
10785
|
-
COMPACTION_READ_BACK_NOTE
|
|
10786
|
-
].join("\n");
|
|
10787
|
-
}
|
|
10788
|
-
function timestampOf(message) {
|
|
10789
|
-
const { timestamp } = message;
|
|
10790
|
-
return typeof timestamp === "number" ? timestamp : void 0;
|
|
10791
|
-
}
|
|
10792
|
-
/** Find the latest compaction summary in history. */
|
|
10793
|
-
function latestSummaryIndex(messages) {
|
|
10794
|
-
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
10795
|
-
const message = messages[index];
|
|
10796
|
-
if (message.role === "user" && hasCompactedConversationContext([message])) return index;
|
|
10797
|
-
}
|
|
10798
|
-
return -1;
|
|
10799
|
-
}
|
|
10800
|
-
/** Find when the latest compaction summary in history was written. */
|
|
10801
|
-
function latestSummaryTimestamp(messages) {
|
|
10802
|
-
const index = latestSummaryIndex(messages);
|
|
10803
|
-
return index < 0 ? void 0 : timestampOf(messages[index]);
|
|
10804
|
-
}
|
|
10805
|
-
/**
|
|
10806
|
-
* Read the input size that the provider reported for one model call. Output
|
|
10807
|
-
* is left out: it is not part of the request that the call measured.
|
|
10808
|
-
*/
|
|
10809
|
-
function measuredInputTokens(message) {
|
|
10810
|
-
const { role, stopReason, usage } = message;
|
|
10811
|
-
if (role !== "assistant" || !usage || stopReason === "aborted" || stopReason === "error") return;
|
|
10812
|
-
const tokens = (usage.input ?? 0) + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
|
|
10813
|
-
return tokens > 0 ? tokens : void 0;
|
|
10814
|
-
}
|
|
10815
|
-
function lastAssistantUsage(messages) {
|
|
10816
|
-
for (let index = messages.length - 1; index >= 0; index--) {
|
|
10817
|
-
const message = messages[index];
|
|
10818
|
-
if (message.role !== "assistant" || message.stopReason === "aborted" || message.stopReason === "error" || !message.usage) continue;
|
|
10819
|
-
const tokens = calculateContextTokens(message.usage);
|
|
10820
|
-
if (tokens > 0) return {
|
|
10821
|
-
tokens,
|
|
10822
|
-
index
|
|
10823
|
-
};
|
|
10824
|
-
}
|
|
10825
|
-
}
|
|
10826
|
-
/**
|
|
10827
|
-
* Measure provider-visible history without counting host-only message fields.
|
|
10828
|
-
*
|
|
10829
|
-
* Provider usage counts the request that produced it. A replacement keeps
|
|
10830
|
-
* assistant messages that are older than its summary, and their usage counts
|
|
10831
|
-
* the history before the replacement. So when the latest usage is older than
|
|
10832
|
-
* the latest summary, estimate each message by size.
|
|
10833
|
-
*/
|
|
10834
|
-
function estimateHistoryTokens(messages, modelId, requestOverheadTokens = 0) {
|
|
10835
|
-
const usage = lastAssistantUsage(messages);
|
|
10836
|
-
const summaryAt = latestSummaryTimestamp(messages);
|
|
10837
|
-
const usageAt = usage ? timestampOf(messages[usage.index]) : void 0;
|
|
10838
|
-
if (usage && usageAt !== void 0 && (summaryAt === void 0 || usageAt > summaryAt)) return usage.tokens + estimateMessagesTokens(messages.slice(usage.index + 1), modelId);
|
|
10839
|
-
return estimateReplacementTokens(messages, modelId, requestOverheadTokens);
|
|
10840
|
-
}
|
|
10841
|
-
/**
|
|
10842
|
-
* Read the provider-reported input of the first model call after the latest
|
|
10843
|
-
* full compaction. That request held only the summary and the kept context,
|
|
10844
|
-
* so another full compaction of the same context cannot get much below it.
|
|
10845
|
-
* A swap also keeps agent history from before its summary. A full compaction
|
|
10846
|
-
* can still drop that history, so a swap gives no such size.
|
|
10847
|
-
*/
|
|
10848
|
-
function measuredReplacementTokens(messages) {
|
|
10849
|
-
const summaryIndex = latestSummaryIndex(messages);
|
|
10850
|
-
if (summaryIndex < 0) return void 0;
|
|
10851
|
-
const summaryAt = timestampOf(messages[summaryIndex]);
|
|
10852
|
-
if (summaryAt === void 0) return void 0;
|
|
10853
|
-
for (const message of messages.slice(summaryIndex + 1)) {
|
|
10854
|
-
const timestamp = timestampOf(message);
|
|
10855
|
-
if (timestamp === void 0 || timestamp <= summaryAt) {
|
|
10856
|
-
const role = message.role;
|
|
10857
|
-
if (role !== "user" && role !== "system") return void 0;
|
|
10858
|
-
continue;
|
|
10859
|
-
}
|
|
10860
|
-
const tokens = measuredInputTokens(message);
|
|
10861
|
-
if (tokens !== void 0) return tokens;
|
|
10862
|
-
}
|
|
10863
|
-
}
|
|
10864
|
-
/**
|
|
10865
|
-
* Estimate a replacement request from each message's own size. A kept
|
|
10866
|
-
* assistant message holds provider usage for the whole request before the
|
|
10867
|
-
* replacement, so usage is ignored here.
|
|
10868
|
-
*/
|
|
10869
|
-
function estimateReplacementTokens(messages, modelId, requestOverheadTokens = 0) {
|
|
10870
|
-
return requestOverheadTokens + estimateMessagesTokens(messages, modelId);
|
|
10871
|
-
}
|
|
10872
|
-
async function loadLastInstruction(conversationId) {
|
|
10873
|
-
const event = await getConversationEventStore().loadLatestInstruction(conversationId);
|
|
10874
|
-
if (!event) return void 0;
|
|
10875
|
-
if (event.data.type === "user_message") {
|
|
10876
|
-
if (event.data.provenance.authority !== "instruction") return void 0;
|
|
10877
|
-
return {
|
|
10878
|
-
message: piMessageFromHistoryItem(event.data),
|
|
10879
|
-
provenance: event.data.provenance,
|
|
10880
|
-
sourceEventSeq: event.seq
|
|
10881
|
-
};
|
|
10882
|
-
}
|
|
10883
|
-
}
|
|
10884
|
-
function loadCompactionSource(messages, modelId, requestOverheadTokens) {
|
|
10885
|
-
if (messages.length > 0) return {
|
|
10886
|
-
estimatedTokens: estimateHistoryTokens(messages, modelId, requestOverheadTokens),
|
|
10887
|
-
messages
|
|
10888
|
-
};
|
|
10889
|
-
return { reason: "missing_context" };
|
|
10890
|
-
}
|
|
10891
|
-
/**
|
|
10892
|
-
* Replace oversized active history at Pi's next-turn boundary before another
|
|
10893
|
-
* provider request can observe it.
|
|
10894
|
-
*
|
|
10895
|
-
* `summarize` gets the history without pending messages. When it fails, the
|
|
10896
|
-
* history stays as it is, unless the history is at the input limit.
|
|
10897
|
-
*/
|
|
10898
|
-
async function compactActiveContextIfNeeded(args, summarize) {
|
|
10899
|
-
const pendingMessages = args.pendingMessages ?? [];
|
|
10900
|
-
const source = loadCompactionSource([...args.piMessages, ...pendingMessages.map((entry) => entry.message)], args.modelId, args.requestOverheadTokens);
|
|
10901
|
-
if ("reason" in source) return {
|
|
10902
|
-
compacted: false,
|
|
10903
|
-
reason: source.reason
|
|
10904
|
-
};
|
|
10905
|
-
const triggerTokens = getAgentContextCompactionTriggerTokens(args.modelId);
|
|
10906
|
-
if (source.estimatedTokens <= triggerTokens) return {
|
|
10907
|
-
compacted: false,
|
|
10908
|
-
reason: "below_threshold"
|
|
10909
|
-
};
|
|
10910
|
-
return await withCompactionSpan(args.mode, "summary", () => compactActiveAboveThreshold(args, summarize, source, triggerTokens));
|
|
10911
|
-
}
|
|
10912
|
-
async function compactActiveAboveThreshold(args, summarize, source, triggerTokens) {
|
|
10913
|
-
const pendingMessages = args.pendingMessages ?? [];
|
|
10914
|
-
const retainUserMessages = args.mode === "blocking" && pendingMessages.length > 0;
|
|
10915
|
-
const inputLimitTokens = getAgentContextInputLimitTokens(args.modelId);
|
|
10916
|
-
const skip = (reason) => {
|
|
10917
|
-
setSpanAttributes({
|
|
10918
|
-
"app.compaction.outcome": "skipped",
|
|
10919
|
-
"app.compaction.skip_reason": reason,
|
|
10920
|
-
"app.compaction.input.estimate": source.estimatedTokens,
|
|
10921
|
-
"app.compaction.threshold": triggerTokens
|
|
10922
|
-
});
|
|
10923
|
-
return {
|
|
10924
|
-
compacted: false,
|
|
10925
|
-
reason: reason === "over_input_limit" ? reason : "over_target"
|
|
10926
|
-
};
|
|
10927
|
-
};
|
|
10928
|
-
const belowInputLimit = source.estimatedTokens < inputLimitTokens;
|
|
10929
|
-
const measuredTokens = measuredReplacementTokens(source.messages);
|
|
10930
|
-
if (belowInputLimit && measuredTokens !== void 0 && measuredTokens > triggerTokens) return skip("last_over_threshold");
|
|
10931
|
-
const retainedInstruction = pendingMessages.length === 0 && !retainUserMessages ? await loadLastInstruction(args.conversationId) : void 0;
|
|
10932
|
-
const instructionMessages = retainedInstruction ? [retainedInstruction.message] : pendingMessages.map((entry) => entry.message);
|
|
10933
|
-
const instructionProvenance = retainedInstruction ? [retainedInstruction.provenance] : pendingMessages.map((entry) => entry.provenance);
|
|
10934
|
-
const instructionTimestamp = instructionMessages[0]?.timestamp;
|
|
10935
|
-
const contextMessage = turnRuntimeContextMessage(args.runtimeContextMessages ?? args.piMessages, args.turnStartMessageIndex, typeof instructionTimestamp === "number" ? instructionTimestamp : void 0);
|
|
10936
|
-
const contextEntries = contextMessage ? [{
|
|
10937
|
-
message: contextMessage,
|
|
10938
|
-
provenance: contextProvenance
|
|
10939
|
-
}] : [];
|
|
10940
|
-
const instructionEntries = instructionMessages.map((message, index) => ({
|
|
10941
|
-
message,
|
|
10942
|
-
provenance: instructionProvenance[index],
|
|
10943
|
-
...index === 0 && retainedInstruction ? { sourceEventSeq: retainedInstruction.sourceEventSeq } : void 0
|
|
10944
|
-
}));
|
|
10945
|
-
const retainedUserMessages = retainUserMessages ? await loadRetainedUserMessages(args.conversationId, instructionMessages) : [];
|
|
10946
|
-
const systemMessage = foldSystemMessages(args.piMessages);
|
|
10947
|
-
const systemEntries = systemMessage ? [{
|
|
10948
|
-
message: systemMessage,
|
|
10949
|
-
provenance: contextProvenance
|
|
10950
|
-
}] : [];
|
|
10951
|
-
const keptTokens = estimateReplacementTokens([
|
|
10952
|
-
...retainedUserMessages,
|
|
10953
|
-
...contextEntries,
|
|
10954
|
-
...instructionEntries,
|
|
10955
|
-
...systemEntries
|
|
10956
|
-
].map((entry) => entry.message), args.modelId, args.requestOverheadTokens);
|
|
10957
|
-
if (belowInputLimit && keptTokens > calculateContextCompactionTargetTokens(triggerTokens)) return skip("over_target");
|
|
10958
|
-
if (keptTokens >= inputLimitTokens) return skip("over_input_limit");
|
|
10959
|
-
await args.onCompactionStart?.();
|
|
10960
|
-
let summary;
|
|
10961
|
-
let costUsd;
|
|
10962
|
-
try {
|
|
10963
|
-
({summary, costUsd} = await summarize(args.piMessages, args.signal));
|
|
10964
|
-
} catch (error) {
|
|
10965
|
-
if (source.estimatedTokens >= inputLimitTokens) throw new ContextInputLimitExceededError(source.estimatedTokens, inputLimitTokens);
|
|
10966
|
-
logWarn("context_compaction.active.summary.failed", {
|
|
10967
|
-
"app.context_input_limit_tokens": inputLimitTokens,
|
|
10968
|
-
"app.context_tokens_estimated": source.estimatedTokens,
|
|
10969
|
-
"exception.message": error instanceof Error ? error.message : String(error)
|
|
10970
|
-
});
|
|
10971
|
-
setSpanAttributes({ "app.compaction.outcome": "summary_failed" });
|
|
10972
|
-
return {
|
|
10973
|
-
compacted: false,
|
|
10974
|
-
reason: "summary_failed"
|
|
10975
|
-
};
|
|
10976
|
-
}
|
|
10977
|
-
const summaryEntry = {
|
|
10978
|
-
message: userMessage(await appendPlanSnapshot(renderCompactionSummary(summary), args.conversationId)),
|
|
10979
|
-
provenance: contextProvenance
|
|
10980
|
-
};
|
|
10981
|
-
const replacement = retainUserMessages ? [
|
|
10982
|
-
...retainedUserMessages,
|
|
10983
|
-
summaryEntry,
|
|
10984
|
-
...systemEntries,
|
|
10985
|
-
...contextEntries,
|
|
10986
|
-
...instructionEntries
|
|
10987
|
-
] : [
|
|
10988
|
-
...contextEntries,
|
|
10989
|
-
...instructionEntries,
|
|
10990
|
-
summaryEntry,
|
|
10991
|
-
...systemEntries
|
|
10992
|
-
];
|
|
10993
|
-
const retainedMessageCount = retainedUserMessages.length + instructionMessages.length;
|
|
10994
|
-
const messages = replacement.map((entry) => entry.message);
|
|
10995
|
-
const replacementInputTokens = estimateReplacementTokens(messages, args.modelId, args.requestOverheadTokens);
|
|
10996
|
-
if (replacementInputTokens >= inputLimitTokens) throw new ContextInputLimitExceededError(replacementInputTokens, inputLimitTokens);
|
|
10997
|
-
args.signal?.throwIfAborted();
|
|
10998
|
-
await getConversationEventStore().replaceHistory(args.conversationId, {
|
|
10999
|
-
createdAtMs: Date.now(),
|
|
11000
|
-
data: {
|
|
11001
|
-
type: "compaction",
|
|
11002
|
-
modelId: args.modelId,
|
|
11003
|
-
details: {
|
|
11004
|
-
reason: "capacity",
|
|
11005
|
-
estimatedInputTokens: source.estimatedTokens,
|
|
11006
|
-
replacementInputTokens,
|
|
11007
|
-
triggerTokens,
|
|
11008
|
-
inputLimitTokens,
|
|
11009
|
-
inputMessageCount: source.messages.length,
|
|
11010
|
-
retainedMessageCount,
|
|
11011
|
-
summaryChars: summary.length
|
|
11012
|
-
},
|
|
11013
|
-
...costUsd === void 0 ? void 0 : { costUsd },
|
|
11014
|
-
summary,
|
|
11015
|
-
replacementHistory: replacement.map((entry) => ({
|
|
11016
|
-
item: historyItemFromPiMessage(entry.message, entry.provenance),
|
|
11017
|
-
...entry.sourceEventSeq === void 0 ? void 0 : { sourceEventSeq: entry.sourceEventSeq }
|
|
11018
|
-
}))
|
|
11019
|
-
}
|
|
11020
|
-
});
|
|
11021
|
-
setSpanAttributes({
|
|
11022
|
-
"app.compaction.outcome": "compacted",
|
|
11023
|
-
"app.compaction.input_messages": source.messages.length,
|
|
11024
|
-
"app.compaction.retained_messages": retainedMessageCount,
|
|
11025
|
-
"app.compaction.summary_chars": summary.length,
|
|
11026
|
-
"app.compaction.input.estimate": source.estimatedTokens,
|
|
11027
|
-
"app.compaction.replacement.estimate": replacementInputTokens,
|
|
11028
|
-
"app.compaction.input_limit": inputLimitTokens,
|
|
11029
|
-
"app.compaction.threshold": triggerTokens
|
|
11030
|
-
});
|
|
11031
|
-
return {
|
|
11032
|
-
compacted: true,
|
|
11033
|
-
piMessages: messages
|
|
11034
|
-
};
|
|
11035
|
-
}
|
|
11036
|
-
// src/chat/services/tool-result-trimming.ts
|
|
11037
|
-
/** Results up to this many text characters stay whole. */
|
|
11038
|
-
const MAX_KEPT_RESULT_CHARS = 2e3;
|
|
11039
|
-
/** Error results explain failures, so they stay whole up to this size. */
|
|
11040
|
-
const MAX_KEPT_ERROR_CHARS = 8e3;
|
|
11041
|
-
const EDGE_CHARS = 500;
|
|
11042
|
-
function role(message) {
|
|
11043
|
-
return message.role;
|
|
11044
|
-
}
|
|
11045
|
-
function resultParts(message) {
|
|
11046
|
-
const content = message.content;
|
|
11047
|
-
return Array.isArray(content) ? content : [];
|
|
11048
|
-
}
|
|
11049
|
-
function resultText(parts) {
|
|
11050
|
-
return parts.map((part) => part.type === "text" && typeof part.text === "string" ? part.text : "").join("\n");
|
|
11051
|
-
}
|
|
11052
|
-
function pointer(seq) {
|
|
11053
|
-
return `readConversationEvent({ seq: ${seq} })`;
|
|
11054
|
-
}
|
|
11055
|
-
/** Replace a long result text with a header, its edges, and a read-back pointer. */
|
|
11056
|
-
function clearedText(toolName, text, seq) {
|
|
11057
|
-
return [
|
|
11058
|
-
`[Tool result cleared to save context: ${toolName}, ${text.length.toLocaleString("en-US")} chars. Full result: ${pointer(seq)}`,
|
|
11059
|
-
"First 500 chars:",
|
|
11060
|
-
text.slice(0, EDGE_CHARS),
|
|
11061
|
-
"Last 500 chars:",
|
|
11062
|
-
`${text.slice(-500)}]`
|
|
11063
|
-
].join("\n");
|
|
11064
|
-
}
|
|
11065
|
-
function trimResult(message, seq) {
|
|
11066
|
-
const parts = resultParts(message);
|
|
11067
|
-
const text = resultText(parts);
|
|
11068
|
-
const hasImage = parts.some((part) => part.type === "image");
|
|
11069
|
-
const keptChars = message.isError === true ? MAX_KEPT_ERROR_CHARS : MAX_KEPT_RESULT_CHARS;
|
|
11070
|
-
const clearText = text.length > keptChars;
|
|
11071
|
-
if (!clearText && !hasImage) return;
|
|
11072
|
-
const toolName = String(message.toolName ?? "tool");
|
|
11073
|
-
const content = clearText ? [{
|
|
11074
|
-
type: "text",
|
|
11075
|
-
text: clearedText(toolName, text, seq)
|
|
11076
|
-
}] : parts.map((part) => part.type === "image" ? {
|
|
11077
|
-
type: "text",
|
|
11078
|
-
text: `[image cleared: ${toolName}, seq ${seq}]`
|
|
11079
|
-
} : part);
|
|
11080
|
-
if (clearText && hasImage) content.push({
|
|
11081
|
-
type: "text",
|
|
11082
|
-
text: `[image cleared: ${toolName}, seq ${seq}]`
|
|
11083
|
-
});
|
|
11084
|
-
return {
|
|
11085
|
-
message: {
|
|
11086
|
-
...message,
|
|
11087
|
-
content
|
|
11088
|
-
},
|
|
11089
|
-
removedChars: Math.max(0, text.length - resultText(content).length)
|
|
11090
|
-
};
|
|
11091
|
-
}
|
|
11092
|
-
/**
|
|
11093
|
-
* Trim old tool results in a replacement history.
|
|
11094
|
-
*
|
|
11095
|
-
* Results after the last Turn instruction belong to the latest Turn and stay
|
|
11096
|
-
* whole. Runtime context and summaries are user messages too, so they do not
|
|
11097
|
-
* mark a Turn. So do short results, error results up to a cap, and
|
|
11098
|
-
* results that have no source event to point to. Images outside the latest
|
|
11099
|
-
* Turn become a short note.
|
|
11100
|
-
*/
|
|
11101
|
-
function trimToolResults(entries) {
|
|
11102
|
-
let latestInstructionIndex = -1;
|
|
11103
|
-
for (const [index, entry] of entries.entries()) if (hasTurnInput(entry.message)) latestInstructionIndex = index;
|
|
11104
|
-
const trimming = {
|
|
11105
|
-
trimmedResults: 0,
|
|
11106
|
-
removedChars: 0
|
|
11107
|
-
};
|
|
11108
|
-
return {
|
|
11109
|
-
entries: entries.map((entry, index) => {
|
|
11110
|
-
if (index > latestInstructionIndex || role(entry.message) !== "toolResult" || entry.sourceEventSeq === void 0) return entry;
|
|
11111
|
-
const result = trimResult(entry.message, entry.sourceEventSeq);
|
|
11112
|
-
if (!result) return entry;
|
|
11113
|
-
trimming.trimmedResults += 1;
|
|
11114
|
-
trimming.removedChars += result.removedChars;
|
|
11115
|
-
return {
|
|
11116
|
-
...entry,
|
|
11117
|
-
message: result.message
|
|
11118
|
-
};
|
|
11119
|
-
}),
|
|
11120
|
-
trimming
|
|
11121
|
-
};
|
|
11122
|
-
}
|
|
11123
|
-
// src/chat/services/context-compaction-swap.ts
|
|
11124
|
-
/**
|
|
11125
|
-
* Prepared-summary swap.
|
|
11126
|
-
*
|
|
11127
|
-
* A background job writes `compaction_prepared` with a summary of the history
|
|
11128
|
-
* up to `markSeq`. The Turn swaps it in without a model call: retained user
|
|
11129
|
-
* messages, the summary, then every message after the mark. A swap runs only
|
|
11130
|
-
* above the compaction threshold, at Turn start or between model calls, in
|
|
11131
|
-
* place of a blocking summary call. Below it, a swap would only rewrite the
|
|
11132
|
-
* provider's prompt cache. A summary that no longer matches the history is
|
|
11133
|
-
* discarded, and the Turn carries on as if none existed.
|
|
11134
|
-
*
|
|
11135
|
-
* A summary that is still running replaces the blocking summary too, for a
|
|
11136
|
-
* limited time from its request. Below the input limit, the Turn defers: the
|
|
11137
|
-
* next model call gets the full history, and a later check swaps the summary
|
|
11138
|
-
* in. At the input limit, the Turn polls for it. The time counts from the
|
|
11139
|
-
* durable request, so a yield or a new request does not reset it.
|
|
11140
|
-
*/
|
|
11141
|
-
/** How long after its request a running summary replaces a blocking one. */
|
|
11142
|
-
const RUNNING_SUMMARY_WAIT_MS = 45e3;
|
|
11143
|
-
const RUNNING_SUMMARY_POLL_MS = 1e3;
|
|
11144
|
-
/** Compare a message across a durable commit, which drops undefined fields. */
|
|
11145
|
-
function durableIdentity(message) {
|
|
11146
|
-
const { role, timestamp, content, toolCallId } = message;
|
|
11147
|
-
return JSON.parse(JSON.stringify({
|
|
11148
|
-
role,
|
|
11149
|
-
timestamp,
|
|
11150
|
-
content,
|
|
11151
|
-
toolCallId
|
|
11152
|
-
}));
|
|
11153
|
-
}
|
|
11154
|
-
function committedPrefixLength(messages, committed) {
|
|
11155
|
-
const limit = Math.min(messages.length, committed.length);
|
|
11156
|
-
for (let index = 0; index < limit; index += 1) if (!isDeepStrictEqual(durableIdentity(messages[index]), durableIdentity(committed[index]))) return index;
|
|
11157
|
-
return limit;
|
|
11158
|
-
}
|
|
11159
|
-
function discard(reason) {
|
|
11160
|
-
setSpanAttributes({
|
|
11161
|
-
"app.compaction.outcome": "discarded",
|
|
11162
|
-
"app.compaction.discard_reason": reason
|
|
11163
|
-
});
|
|
11164
|
-
return { compacted: false };
|
|
11165
|
-
}
|
|
11166
|
-
/**
|
|
11167
|
-
* Swap a ready prepared summary into history, defer to one that is still
|
|
11168
|
-
* running, or run today's capacity compaction when none can be used.
|
|
11169
|
-
*/
|
|
11170
|
-
async function compactWithPreparedSummary(args, summarize) {
|
|
11171
|
-
const swapped = await swapPreparedCompaction(args);
|
|
11172
|
-
if (swapped.compacted || swapped.reason === "history_conflict" || swapped.reason === "deferred") return swapped;
|
|
11173
|
-
return await compactActiveContextIfNeeded(args, summarize);
|
|
11174
|
-
}
|
|
11175
|
-
/**
|
|
11176
|
-
* Poll until the running summary of `request` has a result, the History
|
|
11177
|
-
* changes, or the wait ends. Return the newest fact at that time.
|
|
11178
|
-
*/
|
|
11179
|
-
async function waitForRunningSummary(conversationId, request, waitUntilMs, signal) {
|
|
11180
|
-
let latest = request;
|
|
11181
|
-
while (latest?.event.seq === request.event.seq && Date.now() < waitUntilMs) {
|
|
11182
|
-
await setTimeout$1(Math.min(RUNNING_SUMMARY_POLL_MS, waitUntilMs - Date.now()), void 0, { signal });
|
|
11183
|
-
latest = await loadLatestBackgroundCompaction(conversationId);
|
|
11184
|
-
}
|
|
11185
|
-
return latest;
|
|
11186
|
-
}
|
|
11187
|
-
/**
|
|
11188
|
-
* Replace history above the compaction threshold with a ready prepared
|
|
11189
|
-
* summary, or defer to one that is still running.
|
|
11190
|
-
*/
|
|
11191
|
-
async function swapPreparedCompaction(args) {
|
|
11192
|
-
const pendingMessages = args.pendingMessages ?? [];
|
|
11193
|
-
const sourceMessages = [...args.piMessages, ...pendingMessages.map((entry) => entry.message)];
|
|
11194
|
-
const triggerTokens = getAgentContextCompactionTriggerTokens(args.modelId);
|
|
11195
|
-
const estimatedTokens = estimateHistoryTokens(sourceMessages, args.modelId, args.requestOverheadTokens);
|
|
11196
|
-
if (estimatedTokens <= triggerTokens) return {
|
|
11197
|
-
compacted: false,
|
|
11198
|
-
reason: "below_threshold"
|
|
11199
|
-
};
|
|
11200
|
-
const first = await loadLatestBackgroundCompaction(args.conversationId);
|
|
11201
|
-
if (!first) return { compacted: false };
|
|
11202
|
-
return await withCompactionSpan(args.mode, "swap", async () => {
|
|
11203
|
-
let latest = first;
|
|
11204
|
-
if (first.event.data.type === "compaction_requested") {
|
|
11205
|
-
const waitUntilMs = first.event.createdAtMs + RUNNING_SUMMARY_WAIT_MS;
|
|
11206
|
-
setSpanAttributes({ "app.compaction.request.age_ms": Math.max(0, Date.now() - first.event.createdAtMs) });
|
|
11207
|
-
if (Date.now() < waitUntilMs) {
|
|
11208
|
-
if (estimatedTokens < getAgentContextInputLimitTokens(args.modelId)) {
|
|
11209
|
-
setSpanAttributes({ "app.compaction.outcome": "deferred" });
|
|
11210
|
-
return {
|
|
11211
|
-
compacted: false,
|
|
11212
|
-
reason: "deferred"
|
|
11213
|
-
};
|
|
11214
|
-
}
|
|
11215
|
-
await args.onCompactionStart?.();
|
|
11216
|
-
latest = await waitForRunningSummary(args.conversationId, first, waitUntilMs, args.signal);
|
|
11217
|
-
setSpanAttributes({ "app.compaction.wait.timed_out": latest?.event.seq === first.event.seq });
|
|
11218
|
-
if (latest?.historyVersion !== first.historyVersion) return {
|
|
11219
|
-
...discard("history_version_changed"),
|
|
11220
|
-
reason: "history_conflict"
|
|
11221
|
-
};
|
|
11222
|
-
}
|
|
11223
|
-
}
|
|
11224
|
-
const prepared = latest?.event.data;
|
|
11225
|
-
if (!latest || prepared?.type !== "compaction_prepared" || prepared.outcome !== "ready") {
|
|
11226
|
-
setSpanAttributes({ "app.compaction.outcome": "not_ready" });
|
|
11227
|
-
return { compacted: false };
|
|
11228
|
-
}
|
|
11229
|
-
const { event, historyVersion } = latest;
|
|
11230
|
-
setSpanAttributes({ "app.compaction.prepared.age_ms": Math.max(0, Date.now() - event.createdAtMs) });
|
|
11231
|
-
if (prepared.historyVersion !== historyVersion) return discard("history_version_changed");
|
|
11232
|
-
return await applyPreparedSummary(args, prepared, {
|
|
11233
|
-
estimatedTokens,
|
|
11234
|
-
historyVersion,
|
|
11235
|
-
triggerTokens
|
|
11236
|
-
});
|
|
11237
|
-
});
|
|
11238
|
-
}
|
|
11239
|
-
async function applyPreparedSummary(args, prepared, budget) {
|
|
11240
|
-
const pendingMessages = args.pendingMessages ?? [];
|
|
11241
|
-
const projection = await loadConversationProjection({ conversationId: args.conversationId });
|
|
11242
|
-
const committedLength = committedPrefixLength(args.piMessages, projection.messages);
|
|
11243
|
-
const firstAfterMark = projection.seqs.slice(0, committedLength).findIndex((seq) => seq > prepared.markSeq);
|
|
11244
|
-
const markIndex = firstAfterMark === -1 ? committedLength : firstAfterMark;
|
|
11245
|
-
const summarized = args.piMessages.slice(0, markIndex);
|
|
11246
|
-
const kept = args.piMessages.slice(markIndex);
|
|
11247
|
-
if (kept[0]?.role === "toolResult") return discard("split_tool_call");
|
|
11248
|
-
const retained = selectRetainedUserMessageEntries(trimTrailingAssistantMessages(summarized)).map((entry) => ({
|
|
11249
|
-
message: entry.message,
|
|
11250
|
-
provenance: projection.provenance[entry.sourceIndex],
|
|
11251
|
-
sourceEventSeq: projection.seqs[entry.sourceIndex]
|
|
11252
|
-
}));
|
|
11253
|
-
const contextMessage = summarizedRuntimeContextMessage(summarized, [...kept, ...pendingMessages.map((entry) => entry.message)]);
|
|
11254
|
-
const { entries: trimmedEntries, trimming } = trimToolResults(kept.map((message, offset) => {
|
|
11255
|
-
const index = markIndex + offset;
|
|
11256
|
-
return index < committedLength ? {
|
|
11257
|
-
message,
|
|
11258
|
-
provenance: projection.provenance[index],
|
|
11259
|
-
sourceEventSeq: projection.seqs[index]
|
|
11260
|
-
} : {
|
|
11261
|
-
message,
|
|
11262
|
-
provenance: contextProvenance
|
|
11263
|
-
};
|
|
11264
|
-
}));
|
|
11265
|
-
const systemMessage = foldSystemMessages(summarized);
|
|
11266
|
-
const replacement = [
|
|
11267
|
-
...contextMessage ? [{
|
|
11268
|
-
message: contextMessage,
|
|
11269
|
-
provenance: contextProvenance
|
|
11270
|
-
}] : [],
|
|
11271
|
-
...retained,
|
|
11272
|
-
{
|
|
11273
|
-
message: userMessage(await appendPlanSnapshot(renderCompactionSummary(prepared.summary), args.conversationId)),
|
|
11274
|
-
provenance: contextProvenance
|
|
11275
|
-
},
|
|
11276
|
-
...systemMessage ? [{
|
|
11277
|
-
message: systemMessage,
|
|
11278
|
-
provenance: contextProvenance
|
|
11279
|
-
}] : [],
|
|
11280
|
-
...trimmedEntries,
|
|
11281
|
-
...pendingMessages
|
|
11282
|
-
];
|
|
11283
|
-
const messages = replacement.map((entry) => entry.message);
|
|
11284
|
-
const replacementTokens = estimateReplacementTokens(messages, args.modelId, args.requestOverheadTokens);
|
|
11285
|
-
const targetTokens = calculateContextCompactionTargetTokens(budget.triggerTokens);
|
|
11286
|
-
setSpanAttributes({
|
|
11287
|
-
"app.compaction.input.estimate": budget.estimatedTokens,
|
|
11288
|
-
"app.compaction.replacement.estimate": replacementTokens,
|
|
11289
|
-
"app.compaction.threshold": budget.triggerTokens,
|
|
11290
|
-
"app.compaction.carried_messages": kept.length,
|
|
11291
|
-
"app.compaction.carried.estimate": estimateReplacementTokens(trimmedEntries.map((entry) => entry.message), args.modelId),
|
|
11292
|
-
"app.compaction.trimmed_results": trimming.trimmedResults,
|
|
11293
|
-
"app.compaction.trimmed_chars": trimming.removedChars
|
|
11294
|
-
});
|
|
11295
|
-
if (replacementTokens > targetTokens) return discard("over_target");
|
|
11296
|
-
args.signal?.throwIfAborted();
|
|
11297
|
-
if ((await getConversationEventStore().replaceHistory(args.conversationId, {
|
|
11298
|
-
createdAtMs: Date.now(),
|
|
11299
|
-
data: {
|
|
11300
|
-
type: "compaction",
|
|
11301
|
-
modelId: args.modelId,
|
|
11302
|
-
details: {
|
|
11303
|
-
reason: "capacity",
|
|
11304
|
-
estimatedInputTokens: budget.estimatedTokens,
|
|
11305
|
-
replacementInputTokens: replacementTokens,
|
|
11306
|
-
triggerTokens: budget.triggerTokens,
|
|
11307
|
-
inputLimitTokens: getAgentContextInputLimitTokens(args.modelId),
|
|
11308
|
-
inputMessageCount: args.piMessages.length + pendingMessages.length,
|
|
11309
|
-
retainedMessageCount: retained.length + kept.length + pendingMessages.length,
|
|
11310
|
-
summaryChars: prepared.summary.length
|
|
11311
|
-
},
|
|
11312
|
-
summary: prepared.summary,
|
|
11313
|
-
replacementHistory: replacement.map((entry) => ({
|
|
11314
|
-
item: historyItemFromPiMessage(entry.message, entry.provenance),
|
|
11315
|
-
...entry.sourceEventSeq === void 0 ? void 0 : { sourceEventSeq: entry.sourceEventSeq }
|
|
11316
|
-
}))
|
|
11317
|
-
}
|
|
11318
|
-
}, { expectedHistoryVersion: budget.historyVersion })).status === "conflict") return {
|
|
11319
|
-
...discard("conflict"),
|
|
11320
|
-
reason: "history_conflict"
|
|
11321
|
-
};
|
|
11322
|
-
setSpanAttributes({
|
|
11323
|
-
"app.compaction.outcome": "applied",
|
|
11324
|
-
"app.compaction.summary_chars": prepared.summary.length
|
|
11325
|
-
});
|
|
11326
|
-
return {
|
|
11327
|
-
compacted: true,
|
|
11328
|
-
piMessages: messages
|
|
11329
|
-
};
|
|
11330
|
-
}
|
|
11331
10214
|
// src/chat/agent/exclusive-tools.ts
|
|
11332
10215
|
/**
|
|
11333
10216
|
* Tools that must be the only tool call in their assistant message. Each one
|
|
@@ -11585,11 +10468,9 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
11585
10468
|
});
|
|
11586
10469
|
}
|
|
11587
10470
|
const dispatchSkill = run.dispatch?.skill;
|
|
11588
|
-
const
|
|
11589
|
-
|
|
11590
|
-
|
|
11591
|
-
const activeSkills = [];
|
|
11592
|
-
const skillSandbox = new SkillSandbox(availableSkills, activeSkills);
|
|
10471
|
+
const invokedSkillNames = dispatchSkill ? [dispatchSkill] : parseSkillInvocations(skillInvocationText(run, actor), availableSkills);
|
|
10472
|
+
if (dispatchSkill && !findSkillByName(dispatchSkill, availableSkills)) throw new Error(missingAutomationSkillReason(dispatchSkill));
|
|
10473
|
+
const skillSandbox = new SkillSandbox(availableSkills);
|
|
11593
10474
|
const checkpoint = await loadTurnCheckpoint({
|
|
11594
10475
|
conversationId,
|
|
11595
10476
|
turnId
|
|
@@ -11657,10 +10538,9 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
11657
10538
|
conversationId,
|
|
11658
10539
|
credentialSubjectId: credentialUserId
|
|
11659
10540
|
}) : []);
|
|
11660
|
-
const
|
|
11661
|
-
|
|
10541
|
+
const conversationSkillNames = await loadConversationSkillNames(conversationId);
|
|
10542
|
+
await restoreActiveSkill({
|
|
11662
10543
|
currentTurnMessages,
|
|
11663
|
-
invokedSkill,
|
|
11664
10544
|
resumed: resumedFromSessionRecord,
|
|
11665
10545
|
skillSandbox
|
|
11666
10546
|
});
|
|
@@ -11686,8 +10566,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
11686
10566
|
const promptTurnContextPromise = loadPromptTurnContext({
|
|
11687
10567
|
context: createPromptHookContext({
|
|
11688
10568
|
actor,
|
|
11689
|
-
run
|
|
11690
|
-
userInput
|
|
10569
|
+
run
|
|
11691
10570
|
}),
|
|
11692
10571
|
currentActor: actor,
|
|
11693
10572
|
existingSessionPiMessages: existingSessionRecord?.piMessages,
|
|
@@ -11718,7 +10597,6 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
11718
10597
|
});
|
|
11719
10598
|
const wiring = await wireAgentTools({
|
|
11720
10599
|
abortAgent: () => agent?.abort(),
|
|
11721
|
-
activeSkills,
|
|
11722
10600
|
behavior,
|
|
11723
10601
|
currentActor: actor,
|
|
11724
10602
|
currentAgentMessages,
|
|
@@ -11731,7 +10609,8 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
11731
10609
|
durability,
|
|
11732
10610
|
authorization,
|
|
11733
10611
|
generatedFiles,
|
|
11734
|
-
|
|
10612
|
+
invokedSkillNames,
|
|
10613
|
+
conversationSkillNames,
|
|
11735
10614
|
onEvent: run.onEvent,
|
|
11736
10615
|
onFatalToolError(error) {
|
|
11737
10616
|
pendingPiHookError = error;
|
|
@@ -11777,7 +10656,6 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
11777
10656
|
conversationPrivacy,
|
|
11778
10657
|
existingSessionPiMessages: existingSessionRecord?.piMessages,
|
|
11779
10658
|
existingTurnStartMessageIndex: existingSessionRecord?.turnStartMessageIndex,
|
|
11780
|
-
explicitSkill,
|
|
11781
10659
|
priorPiMessages,
|
|
11782
10660
|
repositoryInstructions: initialRepositoryInstructions,
|
|
11783
10661
|
resumedFromSessionRecord,
|
|
@@ -12396,7 +11274,7 @@ function createAgentRunner(execute, options) {
|
|
|
12396
11274
|
}
|
|
12397
11275
|
};
|
|
12398
11276
|
const loadStoredAttachments = async (attachments) => {
|
|
12399
|
-
const { loadInputAttachments } = await import("./model-input-
|
|
11277
|
+
const { loadInputAttachments } = await import("./model-input-CMLh4Cwq.js").then((n) => n.i);
|
|
12400
11278
|
const storage = nextRun.environment?.attachmentStorage;
|
|
12401
11279
|
if (!storage) throw new Error("Attachment storage is unavailable.");
|
|
12402
11280
|
return await loadInputAttachments({
|
|
@@ -12420,4 +11298,4 @@ function createAgentRunner(execute, options) {
|
|
|
12420
11298
|
return await execute(nextRun, streamFn);
|
|
12421
11299
|
} };
|
|
12422
11300
|
}
|
|
12423
|
-
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 };
|